{"text": "import tactic.tidy\n\nimport evaluation\n\nnamespace baseline\n\nsection tidy_proof_search\n\nmeta def tidy_default_tactics : list string := [\n     \"refl\"\n  ,  \"exact dec_trivial\"\n  ,  \"assumption\"\n  ,  \"tactic.intros1\"\n  ,  \"tactic.auto_cases\"\n  ,  \"apply_auto_param\"\n  ,  \"dsimp at *\"\n  ,  \"simp at *\"\n  ,  \"ext1\"\n  ,  \"fsplit\"\n  ,  \"injections_and_clear\"\n  ,  \"solve_by_elim\"\n  ,  \"norm_cast\"\n]\n\nmeta def tidy_api : ModelAPI := -- simulates logic of tidy, baseline (deterministic) model\nlet fn : json \u2192 io json := \u03bb msg, do {\n  pure $ json.array $ json.of_string <$> tidy_default_tactics\n} in \u27e8fn\u27e9\n\nmeta def tidy_greedy_proof_search_core\n   (fuel : \u2115 := 1000)\n   (verbose := ff)\n   : state_t GreedyProofSearchState tactic unit :=\ngreedy_proof_search_core\n  tidy_api\n    (\u03bb _, pure json.null)\n      (\u03bb msg n, run_best_beam_candidate (unwrap_lm_response $ some \"[tidy_greedy_proof_search]\") msg n)\n        fuel\n\n-- TODO(jesse): run against `tidy` test suite to confirm reproduction of `tidy` logic\nmeta def tidy_greedy_proof_search\n   (fuel : \u2115 := 1000)\n   (verbose := ff)\n   : tactic unit :=\ngreedy_proof_search\n  tidy_api\n    (\u03bb _, pure json.null)\n      (\u03bb msg n, run_best_beam_candidate (unwrap_lm_response $ some \"[tidy_greedy_proof_search]\") msg n)\n        fuel\n          verbose\n\nend tidy_proof_search\n\nsection playground\n\n-- example : true :=\n-- begin\n--   tidy_greedy_proof_search 5 tt,\n-- end\n\n-- open nat\n-- universe u\n-- example : \u2200 {\u03b1 : Type u} {s\u2081 s\u2082 t\u2081 t\u2082 : list \u03b1},\n--   s\u2081 ++ t\u2081 = s\u2082 ++ t\u2082 \u2192 s\u2081.length = s\u2082.length \u2192 s\u2081 = s\u2082 \u2227 t\u2081 = t\u2082 :=\n-- begin\n--   intros, -- tidy_greedy_proof_search\n-- end\n-- open nat\n\n-- example {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   tidy_greedy_proof_search 3 tt\n-- end\n-- run_cmd do {set_show_eval_trace tt *> do env \u2190 tactic.get_env, tactic.set_env_core env}\n\n-- example {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   tidy_greedy_proof_search 2 ff -- should only try one iteration before halting\n\nend playground\n\nend baseline\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/baseline.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740417, "lm_q2_score": 0.12592275991478885, "lm_q1q2_score": 0.04987399661161682}}
{"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 \u2192 b\n\n/-- Implication `\u2192` is transitive. If `P \u2192 Q` and `Q \u2192 R` then `P \u2192 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\u2081 : p \u2192 q) (h\u2082 : q \u2192 r) :\n    p \u2192 r := fun hp \u21a6 h\u2082 (h\u2081 hp)\n\n/- Not -/\n\n@[deprecated] def NonContradictory (a : Prop) : Prop := \u00ac\u00aca\n\n#align non_contradictory_intro not_not_intro\n\n/- Eq -/\n\nalias proofIrrel \u2190 proof_irrel\nalias congrFun \u2190 congr_fun\nalias congrArg \u2190 congr_arg\n\n@[deprecated] theorem trans_rel_left {\u03b1 : Sort u} {a b c : \u03b1}\n    (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (h\u2081 : r a b) (h\u2082 : b = c) : r a c := h\u2082 \u25b8 h\u2081\n\n@[deprecated] theorem trans_rel_right {\u03b1 : Sort u} {a b c : \u03b1}\n    (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (h\u2081 : a = b) (h\u2082 : r b c) : r a c := h\u2081 \u25b8 h\u2082\n\ntheorem not_of_eq_false {p : Prop} (h : p = False) : \u00acp := fun hp \u21a6 h \u25b8 hp\n\ntheorem cast_proof_irrel (h\u2081 h\u2082 : \u03b1 = \u03b2) (a : \u03b1) : cast h\u2081 a = cast h\u2082 a := rfl\n\nattribute [symm] Eq.symm\n\n/- Ne -/\n\ntheorem Ne.def {\u03b1 : Sort u} (a b : \u03b1) : (a \u2260 b) = \u00ac (a = b) := rfl\n\nattribute [symm] Ne.symm\n\n/- HEq -/\n\nalias eqRec_heq \u2190 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 {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} {p\u2081 : \u03c6 a} {p\u2082 : \u03c6 a'} :\n    (e : a = a') \u2192 (h\u2082 : Eq.rec (motive := fun a _ \u21a6 \u03c6 a) p\u2081 e = p\u2082) \u2192 HEq p\u2081 p\u2082\n  | rfl, rfl => HEq.rfl\n\ntheorem heq_of_eq_rec_right {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} {p\u2081 : \u03c6 a} {p\u2082 : \u03c6 a'} :\n    (e : a' = a) \u2192 (h\u2082 : p\u2081 = Eq.rec (motive := fun a _ \u21a6 \u03c6 a) p\u2082 e) \u2192 HEq p\u2081 p\u2082\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 {\u03b1 \u03b2 \u03c6 : Sort u} :\n    \u2200 (p\u2081 : \u03b2 = \u03c6) (p\u2082 : \u03b1 = \u03b2) (a : \u03b1),\n      (Eq.recOn p\u2081 (Eq.recOn p\u2082 a : \u03b2) : \u03c6) = Eq.recOn (Eq.trans p\u2082 p\u2081) 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 \u2227 \u00ac b) \u2228 (b \u2227 \u00ac 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 \u21a6 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 \u2194 not_of_not_not_not _\n\n-- FIXME\n-- attribute [congr] not_congr\n\n@[deprecated and_comm] theorem and_comm' (a b) : a \u2227 b \u2194 b \u2227 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 \u2227 b) \u2227 c \u2194 a \u2227 (b \u2227 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\u2093 -- reorder implicits\n\nvariable (p)\n\n-- FIXME: remove _iff and add _eq for the lean 4 core versions\ntheorem and_true_iff : p \u2227 True \u2194 p := iff_of_eq (and_true _)\n#align and_true and_true_iff\ntheorem true_and_iff : True \u2227 p \u2194 p := iff_of_eq (true_and _)\n#align true_and true_and_iff\ntheorem and_false_iff : p \u2227 False \u2194 False := iff_of_eq (and_false _)\n#align and_false and_false_iff\ntheorem false_and_iff : False \u2227 p \u2194 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 \u2227 p \u2194 p := iff_of_eq (and_self _)\n#align and_self and_self_iff\n\n#align or.imp Or.imp\u2093 -- reorder implicits\n\n#align and.elim And.elim\u2093\n#align iff.elim Iff.elim\u2093\n#align imp_congr imp_congr\u2093\n#align imp_congr_ctx imp_congr_ctx\u2093\n#align imp_congr_right imp_congr_right\u2093\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 \u2228 b \u2194 b \u2228 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 \u2228 b) \u2228 c \u2194 a \u2228 (b \u2228 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\u2093 -- reorder implicits\n\ntheorem true_or_iff : True \u2228 p \u2194 True := iff_of_eq (true_or _)\n#align true_or true_or_iff\ntheorem or_true_iff : p \u2228 True \u2194 True := iff_of_eq (or_true _)\n#align or_true or_true_iff\ntheorem false_or_iff : False \u2228 p \u2194 p := iff_of_eq (false_or _)\n#align false_or false_or_iff\ntheorem or_false_iff : p \u2228 False \u2194 p := iff_of_eq (or_false _)\n#align or_false or_false_iff\ntheorem or_self_iff : p \u2228 p \u2194 p := iff_of_eq (or_self _)\n#align or_self or_self_iff\n\ntheorem not_or_of_not : \u00aca \u2192 \u00acb \u2192 \u00ac(a \u2228 b) := fun h1 h2 \u21a6 not_or.2 \u27e8h1, h2\u27e9\n#align not_or not_or_of_not\n\ntheorem iff_true_iff : (a \u2194 True) \u2194 a := iff_of_eq (iff_true _)\n#align iff_true iff_true_iff\ntheorem true_iff_iff : (True \u2194 a) \u2194 a := iff_of_eq (true_iff _)\n#align true_iff true_iff_iff\n\ntheorem iff_false_iff : (a \u2194 False) \u2194 \u00aca := iff_of_eq (iff_false _)\n#align iff_false iff_false_iff\n\ntheorem false_iff_iff : (False \u2194 a) \u2194 \u00aca := iff_of_eq (false_iff _)\n#align false_iff false_iff_iff\n\ntheorem iff_self_iff (a : Prop) : (a \u2194 a) \u2194 True := iff_of_eq (iff_self _)\n#align iff_self iff_self_iff\n\n#align iff_congr iff_congr\u2093 -- 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 : \u03b1 \u2192 Prop) := \u2203 x, p x \u2227 \u2200 y, p y \u2192 y = x\n\nopen Lean TSyntax.Compat in\nmacro \"\u2203! \" 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 \u21a6 \u2203! $xs:binderIdent*, $b) => `(\u2203! $x:ident $xs:binderIdent*, $b)\n  | `($(_) fun $x:ident \u21a6 $b)                      => `(\u2203! $x:ident, $b)\n  | `($(_) fun ($x:ident : $t) \u21a6 $b)               => `(\u2203! ($x:ident : $t), $b)\n  | _                                               => throw ()\n\n-- @[intro] -- TODO\ntheorem ExistsUnique.intro {p : \u03b1 \u2192 Prop} (w : \u03b1)\n    (h\u2081 : p w) (h\u2082 : \u2200 y, p y \u2192 y = w) : \u2203! x, p x := \u27e8w, h\u2081, h\u2082\u27e9\n\ntheorem ExistsUnique.elim {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {b : Prop}\n    (h\u2082 : \u2203! x, p x) (h\u2081 : \u2200 x, p x \u2192 (\u2200 y, p y \u2192 y = x) \u2192 b) : b :=\n  Exists.elim h\u2082 (\u03bb w hw => h\u2081 w (And.left hw) (And.right hw))\n\ntheorem exists_unique_of_exists_of_unique {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop}\n    (hex : \u2203 x, p x) (hunique : \u2200 y\u2081 y\u2082, p y\u2081 \u2192 p y\u2082 \u2192 y\u2081 = y\u2082) : \u2203! x, p x :=\n  Exists.elim hex (\u03bb x px => ExistsUnique.intro x px (\u03bb y (h : p y) => hunique y x h px))\n\ntheorem ExistsUnique.exists {p : \u03b1 \u2192 Prop} : (\u2203! x, p x) \u2192 \u2203 x, p x | \u27e8x, h, _\u27e9 => \u27e8x, h\u27e9\n#align exists_of_exists_unique ExistsUnique.exists\n#align exists_unique.exists ExistsUnique.exists\n\ntheorem ExistsUnique.unique {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop}\n    (h : \u2203! x, p x) {y\u2081 y\u2082 : \u03b1} (py\u2081 : p y\u2081) (py\u2082 : p y\u2082) : y\u2081 = y\u2082 :=\n  let \u27e8_, _, hy\u27e9 := h; (hy _ py\u2081).trans (hy _ py\u2082).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 : \u03b1 \u2192 Prop} (h : \u2200 a, p a \u2194 q a) : (\u2203! a, p a) \u2194 \u2203! a, q a :=\n  exists_congr fun _ \u21a6 and_congr (h _) $ forall_congr' fun _ \u21a6 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\u2081 : p \u2192 Sort u} {h\u2082 : \u00acp \u2192 Sort u}\n    (h\u2083 : p) (h\u2084 : h\u2081 h\u2083) : Decidable.recOn h h\u2082 h\u2081 :=\n  cast (by match h with | .isTrue _ => rfl) h\u2084\n#align decidable.rec_on_true Decidable.recOn_true\n\ndef recOn_false [h : Decidable p] {h\u2081 : p \u2192 Sort u} {h\u2082 : \u00acp \u2192 Sort u} (h\u2083 : \u00acp) (h\u2084 : h\u2082 h\u2083) :\n    Decidable.recOn h h\u2082 h\u2081 :=\n  cast (by match h with | .isFalse _ => rfl) h\u2084\n#align decidable.rec_on_false Decidable.recOn_false\n\nalias byCases \u2190 by_cases\nalias byContradiction \u2190 by_contradiction\nalias not_not \u2190 not_not_iff\n\n@[deprecated not_or] theorem not_or_iff_and_not (p q) [Decidable p] [Decidable q] :\n    \u00ac(p \u2228 q) \u2194 \u00acp \u2227 \u00acq := 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 \u2190 Or.decidable\nalias instDecidableAnd \u2190 And.decidable\nalias instDecidableNot \u2190 Not.decidable\nalias instDecidableIff \u2190 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 {\u03b1 : Sort u} (p : \u03b1 \u2192 \u03b1 \u2192 Bool) : Prop := \u2200 \u2983x y : \u03b1\u2984, p x y = true \u2192 x = y\ndef IsDecRefl {\u03b1 : Sort u} (p : \u03b1 \u2192 \u03b1 \u2192 Bool) : Prop := \u2200 x, p x x = true\n\ndef decidableEq_of_bool_pred {\u03b1 : Sort u} {p : \u03b1 \u2192 \u03b1 \u2192 Bool} (h\u2081 : IsDecEq p)\n    (h\u2082 : IsDecRefl p) : DecidableEq \u03b1\n  | x, y =>\n    if hp : p x y = true then isTrue (h\u2081 hp)\n    else isFalse (\u03bb hxy : x = y => absurd (h\u2082 y) (by rwa [hxy] at hp))\n#align decidable_eq_of_bool_pred decidableEq_of_bool_pred\n\ntheorem decidableEq_inl_refl {\u03b1 : Sort u} [h : DecidableEq \u03b1] (a : \u03b1) :\n    h a a = isTrue (Eq.refl a) :=\n  match h a a with\n  | isTrue _ => rfl\n\ntheorem decidableEq_inr_neg {\u03b1 : Sort u} [h : DecidableEq \u03b1] {a b : \u03b1}\n    (n : a \u2260 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\u2081 : p \u2192 Sort u} {h\u2082 : \u00acp \u2192 Sort u}\n    [h\u2083 : \u2200 h : p, Subsingleton (h\u2081 h)] [h\u2084 : \u2200 h : \u00acp, Subsingleton (h\u2082 h)] :\n    Subsingleton (Decidable.recOn h h\u2082 h\u2081) :=\n  match h with\n  | isTrue h => h\u2083 h\n  | isFalse h => h\u2084 h\n\n@[deprecated ite_self]\ntheorem if_t_t (c : Prop) [Decidable c] {\u03b1 : Sort u} (t : \u03b1) : 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 \u25b8 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 : \u00acc) : e :=\n  by have := if_neg hnc \u25b8 h; exact this\n#align implies_of_if_neg imp_of_if_neg\n\ntheorem if_ctx_congr {\u03b1 : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c]\n    {x y u v : \u03b1} (h_c : b \u2194 c) (h_t : c \u2192 x = u) (h_e : \u00acc \u2192 y = v) : ite b x y = ite c u v :=\n  match dec_b, dec_c with\n  | isFalse _,  isFalse h\u2082 => h_e h\u2082\n  | isTrue _,   isTrue h\u2082  => h_t h\u2082\n  | isFalse h\u2081, isTrue h\u2082  => absurd h\u2082 (Iff.mp (not_congr h_c) h\u2081)\n  | isTrue h\u2081,  isFalse h\u2082 => absurd h\u2081 (Iff.mpr (not_congr h_c) h\u2082)\n\ntheorem if_congr {\u03b1 : Sort u} {b c : Prop} [Decidable b] [Decidable c]\n    {x y u v : \u03b1} (h_c : b \u2194 c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v :=\n  if_ctx_congr h_c (\u03bb _ => h_t) (\u03bb _ => 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 \u2194 c) (h_t : c \u2192 (x \u2194 u)) (h_e : \u00acc \u2192 (y \u2194 v)) : ite b x y \u2194 ite c u v :=\n  match dec_b, dec_c with\n  | isFalse _,  isFalse h\u2082 => h_e h\u2082\n  | isTrue _,   isTrue h\u2082  => h_t h\u2082\n  | isFalse h\u2081, isTrue h\u2082  => absurd h\u2082 (Iff.mp (not_congr h_c) h\u2081)\n  | isTrue h\u2081,  isFalse h\u2082 => absurd h\u2081 (Iff.mpr (not_congr h_c) h\u2082)\n\n-- @[congr]\ntheorem if_congr_prop {b c x y u v : Prop} [Decidable b] [Decidable c] (h_c : b \u2194 c) (h_t : x \u2194 u)\n    (h_e : y \u2194 v) : ite b x y \u2194 ite c u v :=\n  if_ctx_congr_prop h_c (\u03bb _ => h_t) (\u03bb _ => h_e)\n\ntheorem if_ctx_simp_congr_prop {b c x y u v : Prop} [Decidable b] (h_c : b \u2194 c) (h_t : c \u2192 (x \u2194 u))\n    -- FIXME: after https://github.com/leanprover/lean4/issues/1867 is fixed,\n    -- this should be changed back to:\n    -- (h_e : \u00acc \u2192 (y \u2194 v)) : ite b x y \u2194 ite c (h := decidable_of_decidable_of_iff h_c) u v :=\n    (h_e : \u00acc \u2192 (y \u2194 v)) : ite b x y \u2194 @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 \u2194 c) (h_t : x \u2194 u)\n    -- FIXME: after https://github.com/leanprover/lean4/issues/1867 is fixed,\n    -- this should be changed back to:\n    -- (h_e : y \u2194 v) : ite b x y \u2194 (ite c (h := decidable_of_decidable_of_iff h_c) u v) :=\n    (h_e : y \u2194 v) : ite b x y \u2194 (@ite _ c (decidable_of_decidable_of_iff h_c) u v) :=\n  if_ctx_simp_congr_prop h_c (\u03bb _ => h_t) (\u03bb _ => h_e)\n\n-- @[congr]\ntheorem dif_ctx_congr {\u03b1 : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c]\n    {x : b \u2192 \u03b1} {u : c \u2192 \u03b1} {y : \u00acb \u2192 \u03b1} {v : \u00acc \u2192 \u03b1}\n    (h_c : b \u2194 c) (h_t : \u2200 h : c, x (Iff.mpr h_c h) = u h)\n    (h_e : \u2200 h : \u00acc, y (Iff.mpr (not_congr h_c) h) = v h) :\n    @dite \u03b1 b dec_b x y = @dite \u03b1 c dec_c u v :=\n  match dec_b, dec_c with\n  | isFalse _, isFalse h\u2082 => h_e h\u2082\n  | isTrue _, isTrue h\u2082 => h_t h\u2082\n  | isFalse h\u2081, isTrue h\u2082 => absurd h\u2082 (Iff.mp (not_congr h_c) h\u2081)\n  | isTrue h\u2081, isFalse h\u2082 => absurd h\u2081 (Iff.mpr (not_congr h_c) h\u2082)\n\ntheorem dif_ctx_simp_congr {\u03b1 : Sort u} {b c : Prop} [Decidable b]\n    {x : b \u2192 \u03b1} {u : c \u2192 \u03b1} {y : \u00acb \u2192 \u03b1} {v : \u00acc \u2192 \u03b1}\n    (h_c : b \u2194 c) (h_t : \u2200 h : c, x (Iff.mpr h_c h) = u h)\n    (h_e : \u2200 h : \u00acc, 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\u2081 : Decidable c] (_ : AsTrue c) : c :=\n  match h\u2081 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 {\u03b1 : Sort u} {\u03b2 : Sort v} {a\u2081 a\u2082 : \u03b1} (b : \u03b1 \u2192 \u03b2)\n    (h : a\u2081 = a\u2082) : (let x : \u03b1 := a\u2081; b x) = (let x : \u03b1 := a\u2082; b x) := congrArg b h\n\ntheorem let_value_heq {\u03b1 : Sort v} {\u03b2 : \u03b1 \u2192 Sort u} {a\u2081 a\u2082 : \u03b1} (b : \u2200 x : \u03b1, \u03b2 x)\n    (h : a\u2081 = a\u2082) : HEq (let x : \u03b1 := a\u2081; b x) (let x : \u03b1 := a\u2082; 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 {\u03b1 : Sort v} {\u03b2 : \u03b1 \u2192 Sort u} (a : \u03b1) {b\u2081 b\u2082 : \u2200 x : \u03b1, \u03b2 x}\n    (h : \u2200 x, b\u2081 x = b\u2082 x) : (let x : \u03b1 := a; b\u2081 x) = (let x : \u03b1 := a; b\u2082 x) := by exact h _ \u25b8 rfl\n#align let_value_eq let_value_eq -- FIXME: mathport thinks this is a dubious translation\n\ntheorem let_eq {\u03b1 : Sort v} {\u03b2 : Sort u} {a\u2081 a\u2082 : \u03b1} {b\u2081 b\u2082 : \u03b1 \u2192 \u03b2}\n    (h\u2081 : a\u2081 = a\u2082) (h\u2082 : \u2200 x, b\u2081 x = b\u2082 x) :\n    (let x : \u03b1 := a\u2081; b\u2081 x) = (let x : \u03b1 := a\u2082; b\u2082 x) := by simp [h\u2081, h\u2082]\n#align let_eq let_eq -- FIXME: mathport thinks this is a dubious translation\n\nsection Relation\n\nvariable {\u03b1 : Sort u} {\u03b2 : Sort v} (r : \u03b2 \u2192 \u03b2 \u2192 Prop)\n\n/-- Local notation for an arbitrary binary relation `r`. -/\nlocal infix:50 \" \u227a \" => r\n\n/-- A reflexive relation relates every element to itself. -/\ndef Reflexive := \u2200 x, x \u227a x\n\n/-- A relation is symmetric if `x \u227a y` implies `y \u227a x`. -/\ndef Symmetric := \u2200 \u2983x y\u2984, x \u227a y \u2192 y \u227a x\n\n/-- A relation is transitive if `x \u227a y` and `y \u227a z` together imply `x \u227a z`. -/\ndef Transitive := \u2200 \u2983x y z\u2984, x \u227a y \u2192 y \u227a z \u2192 x \u227a z\n\nlemma Equivalence.reflexive {r : \u03b2 \u2192 \u03b2 \u2192 Prop} (h : Equivalence r) : Reflexive r := h.refl\n\nlemma Equivalence.symmetric {r : \u03b2 \u2192 \u03b2 \u2192 Prop} (h : Equivalence r) : Symmetric r := \u03bb _ _ => h.symm\n\nlemma Equivalence.transitive  {r : \u03b2 \u2192 \u03b2 \u2192 Prop}(h : Equivalence r) : Transitive r :=\n  \u03bb _ _ _ => h.trans\n\n/-- A relation is total if for all `x` and `y`, either `x \u227a y` or `y \u227a x`. -/\ndef Total := \u2200 x y, x \u227a y \u2228 y \u227a x\n\n#align mk_equivalence Equivalence.mk\n\n/-- Irreflexive means \"not reflexive\". -/\ndef Irreflexive := \u2200 x, \u00ac x \u227a x\n\n/-- A relation is antisymmetric if `x \u227a y` and `y \u227a x` together imply that `x = y`. -/\ndef AntiSymmetric := \u2200 \u2983x y\u2984, x \u227a y \u2192 y \u227a x \u2192 x = y\n\n/-- An empty relation does not relate any elements. -/\n@[nolint unusedArguments]\ndef EmptyRelation := \u03bb _ _ : \u03b1 => False\n\ntheorem InvImage.trans (f : \u03b1 \u2192 \u03b2) (h : Transitive r) : Transitive (InvImage r f) :=\n  fun (a\u2081 a\u2082 a\u2083 : \u03b1) (h\u2081 : InvImage r f a\u2081 a\u2082) (h\u2082 : InvImage r f a\u2082 a\u2083) \u21a6 h h\u2081 h\u2082\n\ntheorem InvImage.irreflexive (f : \u03b1 \u2192 \u03b2) (h : Irreflexive r) : Irreflexive (InvImage r f) :=\n  fun (a : \u03b1) (h\u2081 : InvImage r f a a) \u21a6 h (f a) h\u2081\n\nend Relation\n\nsection Binary\n\nvariable {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (inv : \u03b1 \u2192 \u03b1) (one : \u03b1)\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) \"\u207b\u00b9\" => inv\n\nvariable (g : \u03b1 \u2192 \u03b1 \u2192 \u03b1)\n\n/-- Local notation for `g`, high priority to avoid ambiguity with `HAdd.hAdd`. -/\nlocal infix:65 (priority := high) \" + \" => g\n\ndef Commutative       := \u2200 a b, a * b = b * a\ndef Associative       := \u2200 a b c, (a * b) * c = a * (b * c)\ndef LeftIdentity      := \u2200 a, one * a = a\ndef RightIdentity     := \u2200 a, a * one = a\ndef RightInverse      := \u2200 a, a * a\u207b\u00b9 = one\ndef LeftCancelative   := \u2200 a b c, a * b = a * c \u2192 b = c\ndef RightCancelative  := \u2200 a b c, a * b = c * b \u2192 a = c\ndef LeftDistributive  := \u2200 a b c, a * (b + c) = a * b + a * c\ndef RightDistributive := \u2200 a b c, (a + b) * c = a * c + b * c\ndef RightCommutative (h : \u03b2 \u2192 \u03b1 \u2192 \u03b2) := \u2200 b a\u2081 a\u2082, h (h b a\u2081) a\u2082 = h (h b a\u2082) a\u2081\ndef LeftCommutative  (h : \u03b1 \u2192 \u03b2 \u2192 \u03b2) := \u2200 a\u2081 a\u2082 b, h a\u2081 (h a\u2082 b) = h a\u2082 (h a\u2081 b)\n\ntheorem left_comm : Commutative f \u2192 Associative f \u2192 LeftCommutative f :=\n  fun hcomm hassoc a b c \u21a6\n    calc  a*(b*c)\n      _ = (a*b)*c := Eq.symm (hassoc a b c)\n      _ = (b*a)*c := hcomm a b \u25b8 rfl\n      _ = b*(a*c) := hassoc b a c\n\ntheorem right_comm : Commutative f \u2192 Associative f \u2192 RightCommutative f :=\n  fun hcomm hassoc a b c \u21a6\n    calc  (a*b)*c\n      _ = a*(b*c) := hassoc a b c\n      _ = a*(c*b) := hcomm b c \u25b8 rfl\n      _ = (a*c)*b := Eq.symm (hassoc a c b)\n\nend Binary\n\nnamespace WellFounded\n\nvariable {\u03b1 : Sort u} {C : \u03b1 \u2192 Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\n\nunsafe def fix'.impl (hwf : WellFounded r) (F : \u2200 x, (\u2200 y, r y x \u2192 C y) \u2192 C x) (x : \u03b1) : C x :=\n  F x fun y _ \u21a6 impl hwf F y\n\n@[implemented_by fix'.impl]\ndef fix' (hwf : WellFounded r) (F : \u2200 x, (\u2200 y, r y x \u2192 C y) \u2192 C x) (x : \u03b1) : 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\u2082_congr forall\u2082_congr\n#align exists\u2082_congr exists\u2082_congr\n#align forall\u2083_congr forall\u2083_congr\n#align exists\u2083_congr exists\u2083_congr\n#align forall\u2084_congr forall\u2084_congr\n#align exists\u2084_congr exists\u2084_congr\n#align forall\u2085_congr forall\u2085_congr\n#align exists\u2085_congr exists\u2085_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 {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := 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 {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := a\n\n/- `idRhs` is an auxiliary declaration used to implement \"smart unfolding\". It is used as a marker. -/\n@[macroInline, reducible] def idRhs (\u03b1 : Sort u) (a : \u03b1) : \u03b1 := a\n\nabbrev Function.comp {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b4 : Sort w} (f : \u03b2 \u2192 \u03b4) (g : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b4 :=\n  fun x => f (g x)\n\nabbrev Function.const {\u03b1 : Sort u} (\u03b2 : Sort v) (a : \u03b1) : \u03b2 \u2192 \u03b1 :=\n  fun x => a\n\n@[reducible] def inferInstance {\u03b1 : Type u} [i : \u03b1] : \u03b1 := i\n@[reducible] def inferInstanceAs (\u03b1 : Type u) [i : \u03b1] : \u03b1 := 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 {\u03b1 : Prop} : \u03b1\n\n/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/\nunsafe axiom lcUnreachable {\u03b1 : Sort u} : \u03b1\n\ninductive True : Prop\n  | intro : True\n\ninductive False : Prop\n\ninductive Empty : Type\n\ndef Not (a : Prop) : Prop := a \u2192 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\u2081 : a) (h\u2082 : Not a) : b :=\n  False.elim (h\u2082 h\u2081)\n\ninductive Eq {\u03b1 : Sort u} (a : \u03b1) : \u03b1 \u2192 Prop\n  | refl {} : Eq a a\n\nabbrev Eq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} (m : motive a) {b : \u03b1} (h : Eq a b) : motive b :=\n  Eq.rec (motive := fun \u03b1 _ => motive \u03b1) m h\n\n@[matchPattern] def rfl {\u03b1 : Sort u} {a : \u03b1} : Eq a a := Eq.refl a\n\ntheorem Eq.subst {\u03b1 : Sort u} {motive : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : Eq a b) (h\u2082 : motive a) : motive b :=\n  Eq.ndrec h\u2082 h\u2081\n\ntheorem Eq.symm {\u03b1 : Sort u} {a b : \u03b1} (h : Eq a b) : Eq b a :=\n  h \u25b8 rfl\n\n@[macroInline] def cast {\u03b1 \u03b2 : Sort u} (h : Eq \u03b1 \u03b2) (a : \u03b1) : \u03b2 :=\n  Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\n\ntheorem congrArg {\u03b1 : Sort u} {\u03b2 : Sort v} {a\u2081 a\u2082 : \u03b1} (f : \u03b1 \u2192 \u03b2) (h : Eq a\u2081 a\u2082) : Eq (f a\u2081) (f a\u2082) :=\n  h \u25b8 rfl\n\n/-\nInitialize the Quotient Module, which effectively adds the following definitions:\n\nconstant Quot {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Sort u\n\nconstant Quot.mk {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (a : \u03b1) : Quot r\n\nconstant Quot.lift {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) :\n  (\u2200 a b : \u03b1, r a b \u2192 Eq (f a) (f b)) \u2192 Quot r \u2192 \u03b2\n\nconstant Quot.ind {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Prop} :\n  (\u2200 a : \u03b1, \u03b2 (Quot.mk r a)) \u2192 \u2200 q : Quot r, \u03b2 q\n-/\ninit_quot\n\ninductive HEq {\u03b1 : Sort u} (a : \u03b1) : {\u03b2 : Sort u} \u2192 \u03b2 \u2192 Prop\n  | refl {} : HEq a a\n\n@[matchPattern] def HEq.rfl {\u03b1 : Sort u} {a : \u03b1} : HEq a a :=\n  HEq.refl a\n\ntheorem eqOfHEq {\u03b1 : Sort u} {a a' : \u03b1} (h : HEq a a') : Eq a a' :=\n  have : (\u03b1 \u03b2 : Sort u) \u2192 (a : \u03b1) \u2192 (b : \u03b2) \u2192 HEq a b \u2192 (h : Eq \u03b1 \u03b2) \u2192 Eq (cast h a) b :=\n    fun \u03b1 \u03b2 a b h\u2081 =>\n      HEq.rec (motive := fun {\u03b2} (b : \u03b2) (h : HEq a b) => (h\u2082 : Eq \u03b1 \u03b2) \u2192 Eq (cast h\u2082 a) b)\n        (fun (h\u2082 : Eq \u03b1 \u03b1) => rfl)\n        h\u2081\n  this \u03b1 \u03b1 a a' h rfl\n\nstructure Prod (\u03b1 : Type u) (\u03b2 : Type v) :=\n  (fst : \u03b1) (snd : \u03b2)\n\nattribute [unbox] Prod\n\n/-- Similar to `Prod`, but `\u03b1` and `\u03b2` can be propositions.\n   We use this Type internally to automatically generate the brecOn recursor. -/\nstructure PProd (\u03b1 : Sort u) (\u03b2 : Sort v) :=\n  (fst : \u03b1) (snd : \u03b2)\n\n/-- Similar to `Prod`, but `\u03b1` and `\u03b2` are in the same universe. -/\nstructure MProd (\u03b1 \u03b2 : Type u) :=\n  (fst : \u03b1) (snd : \u03b2)\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 {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) :=\n  (val : \u03b1) (property : p val)\n\n/-- Gadget for optional parameter support. -/\n@[reducible] def optParam (\u03b1 : Sort u) (default : \u03b1) : Sort u := \u03b1\n\n/-- Gadget for marking output parameters in type classes. -/\n@[reducible] def outParam (\u03b1 : Sort u) : Sort u := \u03b1\n\n/-- Auxiliary Declaration used to implement the notation (a : \u03b1) -/\n@[reducible] def typedExpr (\u03b1 : Sort u) (a : \u03b1) : \u03b1 := a\n\n/-- Auxiliary Declaration used to implement the named patterns `x@p` -/\n@[reducible] def namedPattern {\u03b1 : Sort u} (x a : \u03b1) : \u03b1 := a\n\n/- Auxiliary axiom used to implement `sorry`. -/\naxiom sorryAx (\u03b1 : Sort u) (synthetic := true) : \u03b1\n\ntheorem eqFalseOfNeTrue : {b : Bool} \u2192 Not (Eq b true) \u2192 Eq b false\n  | true, h => False.elim (h rfl)\n  | false, h => rfl\n\ntheorem eqTrueOfNeFalse : {b : Bool} \u2192 Not (Eq b false) \u2192 Eq b true\n  | true, h => rfl\n  | false, h => False.elim (h rfl)\n\ntheorem neFalseOfEqTrue : {b : Bool} \u2192 Eq b true \u2192 Not (Eq b false)\n  | true, _  => fun h => Bool.noConfusion h\n  | false, h => Bool.noConfusion h\n\ntheorem neTrueOfEqFalse : {b : Bool} \u2192 Eq b false \u2192 Not (Eq b true)\n  | true, h  => Bool.noConfusion h\n  | false, _ => fun h => Bool.noConfusion h\n\nclass Inhabited (\u03b1 : Sort u) :=\n  mk {} :: (default : \u03b1)\n\nconstant arbitrary (\u03b1 : Sort u) [s : Inhabited \u03b1] : \u03b1 :=\n  @Inhabited.default \u03b1 s\n\ninstance (\u03b1 : Sort u) {\u03b2 : Sort v} [Inhabited \u03b2] : Inhabited (\u03b1 \u2192 \u03b2) := {\n  default := fun _ => arbitrary \u03b2\n}\n\ninstance (\u03b1 : Sort u) {\u03b2 : \u03b1 \u2192 Sort v} [(a : \u03b1) \u2192 Inhabited (\u03b2 a)] : Inhabited ((a : \u03b1) \u2192 \u03b2 a) := {\n  default := fun a => arbitrary (\u03b2 a)\n}\n\n/-- Universe lifting operation from Sort to Type -/\nstructure PLift (\u03b1 : Sort u) : Type u :=\n  up :: (down : \u03b1)\n\n/- Bijection between \u03b1 and PLift \u03b1 -/\ntheorem PLift.upDown {\u03b1 : Sort u} : \u2200 (b : PLift \u03b1), Eq (up (down b)) b\n  | up a => rfl\n\ntheorem PLift.downUp {\u03b1 : Sort u} (a : \u03b1) : 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 := \u27e8\u27e9 }\n}\n\n/-- Universe lifting operation -/\nstructure ULift.{r, s} (\u03b1 : Type s) : Type (max s r) :=\n  up :: (down : \u03b1)\n\n/- Bijection between \u03b1 and ULift.{v} \u03b1 -/\ntheorem ULift.upDown {\u03b1 : Type u} : \u2200 (b : ULift.{v} \u03b1), Eq (up (down b)) b\n  | up a => rfl\n\ntheorem ULift.downUp {\u03b1 : Type u} (a : \u03b1) : 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 {\u03b1 : Sort u} (r : \u03b1 \u2192 Prop) :=\n  (a : \u03b1) \u2192 Decidable (r a)\n\nabbrev DecidableRel {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  (a b : \u03b1) \u2192 Decidable (r a b)\n\nabbrev DecidableEq (\u03b1 : Sort u) :=\n  (a b : \u03b1) \u2192 Decidable (Eq a b)\n\ndef decEq {\u03b1 : Sort u} [s : DecidableEq \u03b1] (a b : \u03b1) : Decidable (Eq a b) :=\n  s a b\n\ntheorem decideEqTrue : {p : Prop} \u2192 [s : Decidable p] \u2192 p \u2192 Eq (decide p) true\n  | _, isTrue  _, _   => rfl\n  | _, isFalse h\u2081, h\u2082 => absurd h\u2082 h\u2081\n\ntheorem decideEqTrue' : [s : Decidable p] \u2192 p \u2192 Eq (decide p) true\n  | isTrue  _, _   => rfl\n  | isFalse h\u2081, h\u2082 => absurd h\u2082 h\u2081\n\ntheorem decideEqFalse : {p : Prop} \u2192 [s : Decidable p] \u2192 Not p \u2192 Eq (decide p) false\n  | _, isTrue  h\u2081, h\u2082 => absurd h\u2081 h\u2082\n  | _, isFalse h, _   => rfl\n\ntheorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true \u2192 p := fun h =>\n  match s with\n  | isTrue  h\u2081 => h\u2081\n  | isFalse h\u2081 => absurd h (neTrueOfEqFalse (decideEqFalse h\u2081))\n\ntheorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false \u2192 Not p := fun h =>\n  match s with\n  | isTrue  h\u2081 => absurd h (neFalseOfEqTrue (decideEqTrue h\u2081))\n  | isFalse h\u2081 => h\u2081\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      (\u03b1 : Type u) := (beq : \u03b1 \u2192 \u03b1 \u2192 Bool)\n\nopen BEq (beq)\n\ninstance {\u03b1 : Type u} [DecidableEq \u03b1] : BEq \u03b1 :=\n  \u27e8fun a b => decide (Eq a b)\u27e9\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 {\u03b1 : Sort u} (c : Prop) [h : Decidable c] (t : c \u2192 \u03b1) (e : Not c \u2192 \u03b1) : \u03b1 :=\n  Decidable.casesOn (motive := fun _ => \u03b1) 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 {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := 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 {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := 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 (\u03b1 : Sort u) (a : \u03b1) : \u03b1 := a\n\nabbrev Function.comp {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b4 : Sort w} (f : \u03b2 \u2192 \u03b4) (g : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b4 :=\n  fun x => f (g x)\n\nabbrev Function.const {\u03b1 : Sort u} (\u03b2 : Sort v) (a : \u03b1) : \u03b2 \u2192 \u03b1 :=\n  fun x => a\n\n@[reducible] def inferInstance {\u03b1 : Type u} [i : \u03b1] : \u03b1 := i\n@[reducible] def inferInstanceAs (\u03b1 : Type u) [i : \u03b1] : \u03b1 := 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 {\u03b1 : Prop} : \u03b1\n\n/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/\nunsafe axiom lcUnreachable {\u03b1 : Sort u} : \u03b1\n\ninductive True : Prop\n  | intro : True\n\ninductive False : Prop\n\ninductive Empty : Type\n\ndef Not (a : Prop) : Prop := a \u2192 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\u2081 : a) (h\u2082 : Not a) : b :=\n  False.elim (h\u2082 h\u2081)\n\ninductive Eq : \u03b1 \u2192 \u03b1 \u2192 Prop\n  | refl (a : \u03b1) : Eq a a\n\nabbrev Eq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} (m : motive a) {b : \u03b1} (h : Eq a b) : motive b :=\n  Eq.rec (motive := fun \u03b1 _ => motive \u03b1) m h\n\n@[match_pattern] def rfl {\u03b1 : Sort u} {a : \u03b1} : Eq a a := Eq.refl a\n\ntheorem Eq.subst {\u03b1 : Sort u} {motive : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : Eq a b) (h\u2082 : motive a) : motive b :=\n  Eq.ndrec h\u2082 h\u2081\n\ntheorem Eq.symm {\u03b1 : Sort u} {a b : \u03b1} (h : Eq a b) : Eq b a :=\n  h \u25b8 rfl\n\n@[macro_inline] def cast {\u03b1 \u03b2 : Sort u} (h : Eq \u03b1 \u03b2) (a : \u03b1) : \u03b2 :=\n  Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\n\ntheorem congrArg {\u03b1 : Sort u} {\u03b2 : Sort v} {a\u2081 a\u2082 : \u03b1} (f : \u03b1 \u2192 \u03b2) (h : Eq a\u2081 a\u2082) : Eq (f a\u2081) (f a\u2082) :=\n  h \u25b8 rfl\n\n/-\nInitialize the Quotient Module, which effectively adds the following definitions:\n\nopaque Quot {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Sort u\n\nopaque Quot.mk {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (a : \u03b1) : Quot r\n\nopaque Quot.lift {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) :\n  (\u2200 a b : \u03b1, r a b \u2192 Eq (f a) (f b)) \u2192 Quot r \u2192 \u03b2\n\nopaque Quot.ind {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Prop} :\n  (\u2200 a : \u03b1, \u03b2 (Quot.mk r a)) \u2192 \u2200 q : Quot r, \u03b2 q\n-/\ninit_quot\n\ninductive HEq : {\u03b1 : Sort u} \u2192 \u03b1 \u2192 {\u03b2 : Sort u} \u2192 \u03b2 \u2192 Prop\n  | refl (a : \u03b1) : HEq a a\n\n@[match_pattern] def HEq.rfl {\u03b1 : Sort u} {a : \u03b1} : HEq a a :=\n  HEq.refl a\n\ntheorem eqOfHEq {\u03b1 : Sort u} {a a' : \u03b1} (h : HEq a a') : Eq a a' :=\n  have : (\u03b1 \u03b2 : Sort u) \u2192 (a : \u03b1) \u2192 (b : \u03b2) \u2192 HEq a b \u2192 (h : Eq \u03b1 \u03b2) \u2192 Eq (cast h a) b :=\n    fun \u03b1 \u03b2 a b h\u2081 =>\n      HEq.rec (motive := fun {\u03b2} (b : \u03b2) (h : HEq a b) => (h\u2082 : Eq \u03b1 \u03b2) \u2192 Eq (cast h\u2082 a) b)\n        (fun (h\u2082 : Eq \u03b1 \u03b1) => rfl)\n        h\u2081\n  this \u03b1 \u03b1 a a' h rfl\n\nstructure Prod (\u03b1 : Type u) (\u03b2 : Type v) :=\n  (fst : \u03b1) (snd : \u03b2)\n\nattribute [unbox] Prod\n\n/-- Similar to `Prod`, but `\u03b1` and `\u03b2` can be propositions.\n   We use this Type internally to automatically generate the brecOn recursor. -/\nstructure PProd (\u03b1 : Sort u) (\u03b2 : Sort v) :=\n  (fst : \u03b1) (snd : \u03b2)\n\n/-- Similar to `Prod`, but `\u03b1` and `\u03b2` are in the same universe. -/\nstructure MProd (\u03b1 \u03b2 : Type u) :=\n  (fst : \u03b1) (snd : \u03b2)\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 {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) :=\n  (val : \u03b1) (property : p val)\n\n/-- Gadget for optional parameter support. -/\n@[reducible] def optParam (\u03b1 : Sort u) (default : \u03b1) : Sort u := \u03b1\n\n/-- Gadget for marking output parameters in type classes. -/\n@[reducible] def outParam (\u03b1 : Sort u) : Sort u := \u03b1\n\n/-- Auxiliary Declaration used to implement the notation (a : \u03b1) -/\n@[reducible] def typedExpr (\u03b1 : Sort u) (a : \u03b1) : \u03b1 := a\n\n/-- Auxiliary Declaration used to implement the named patterns `x@p` -/\n@[reducible] def namedPattern {\u03b1 : Sort u} (x a : \u03b1) : \u03b1 := a\n\n/- Auxiliary axiom used to implement `sorry`. -/\naxiom sorryAx (\u03b1 : Sort u) (synthetic := true) : \u03b1\n\ntheorem eqFalseOfNeTrue : {b : Bool} \u2192 Not (Eq b true) \u2192 Eq b false\n  | true, h => False.elim (h rfl)\n  | false, h => rfl\n\ntheorem eqTrueOfNeFalse : {b : Bool} \u2192 Not (Eq b false) \u2192 Eq b true\n  | true, h => rfl\n  | false, h => False.elim (h rfl)\n\ntheorem neFalseOfEqTrue : {b : Bool} \u2192 Eq b true \u2192 Not (Eq b false)\n  | true, _  => fun h => Bool.noConfusion h\n  | false, h => Bool.noConfusion h\n\ntheorem neTrueOfEqFalse : {b : Bool} \u2192 Eq b false \u2192 Not (Eq b true)\n  | true, h  => Bool.noConfusion h\n  | false, _ => fun h => Bool.noConfusion h\n\nclass Inhabited (\u03b1 : Sort u) :=\n  (default : \u03b1)\n\nopaque arbitrary (\u03b1 : Sort u) [s : Inhabited \u03b1] : \u03b1 :=\n  @Inhabited.default \u03b1 s\n\ninstance (\u03b1 : Sort u) {\u03b2 : Sort v} [Inhabited \u03b2] : Inhabited (\u03b1 \u2192 \u03b2) := {default := fun _ => arbitrary \u03b2}\n\ninstance (\u03b1 : Sort u) {\u03b2 : \u03b1 \u2192 Sort v} [(a : \u03b1) \u2192 Inhabited (\u03b2 a)] : Inhabited ((a : \u03b1) \u2192 \u03b2 a) := {default := fun a => arbitrary (\u03b2 a)}\n\n/-- Universe lifting operation from Sort to Type -/\nstructure PLift (\u03b1 : Sort u) : Type u :=\n  up :: (down : \u03b1)\n\n/- Bijection between \u03b1 and PLift \u03b1 -/\ntheorem PLift.upDown {\u03b1 : Sort u} : \u2200 (b : PLift \u03b1), Eq (up (down b)) b\n  | up a => rfl\n\ntheorem PLift.downUp {\u03b1 : Sort u} (a : \u03b1) : 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 := \u27e8\u27e9 }}\n\n/-- Universe lifting operation -/\nstructure ULift.{r, s} (\u03b1 : Type s) : Type (max s r) :=\n  up :: (down : \u03b1)\n\n/- Bijection between \u03b1 and ULift.{v} \u03b1 -/\ntheorem ULift.upDown {\u03b1 : Type u} : \u2200 (b : ULift.{v} \u03b1), Eq (up (down b)) b\n  | up a => rfl\n\ntheorem ULift.downUp {\u03b1 : Type u} (a : \u03b1) : 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 {\u03b1 : Sort u} (r : \u03b1 \u2192 Prop) :=\n  (a : \u03b1) \u2192 Decidable (r a)\n\nabbrev DecidableRel {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  (a b : \u03b1) \u2192 Decidable (r a b)\n\nabbrev DecidableEq (\u03b1 : Sort u) :=\n  (a b : \u03b1) \u2192 Decidable (Eq a b)\n\ndef decEq {\u03b1 : Sort u} [s : DecidableEq \u03b1] (a b : \u03b1) : Decidable (Eq a b) :=\n  s a b\n\ntheorem decideEqTrue : {p : Prop} \u2192 [s : Decidable p] \u2192 p \u2192 Eq (decide p) true\n  | _, isTrue  _, _   => rfl\n  | _, isFalse h\u2081, h\u2082 => absurd h\u2082 h\u2081\n\ntheorem decideEqTrue' : [s : Decidable p] \u2192 p \u2192 Eq (decide p) true\n  | isTrue  _, _   => rfl\n  | isFalse h\u2081, h\u2082 => absurd h\u2082 h\u2081\n\ntheorem decideEqFalse : {p : Prop} \u2192 [s : Decidable p] \u2192 Not p \u2192 Eq (decide p) false\n  | _, isTrue  h\u2081, h\u2082 => absurd h\u2081 h\u2082\n  | _, isFalse h, _   => rfl\n\ntheorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true \u2192 p := fun h =>\n  match s with\n  | isTrue  h\u2081 => h\u2081\n  | isFalse h\u2081 => absurd h (neTrueOfEqFalse (decideEqFalse h\u2081))\n\ntheorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false \u2192 Not p := fun h =>\n  match s with\n  | isTrue  h\u2081 => absurd h (neFalseOfEqTrue (decideEqTrue h\u2081))\n  | isFalse h\u2081 => h\u2081\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      (\u03b1 : Type u) := (beq : \u03b1 \u2192 \u03b1 \u2192 Bool)\n\nopen BEq (beq)\n\ninstance {\u03b1 : Type u} [DecidableEq \u03b1] : BEq \u03b1 :=\n  \u27e8fun a b => decide (Eq a b)\u27e9\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 {\u03b1 : Sort u} (c : Prop) [h : Decidable c] (t : c \u2192 \u03b1) (e : Not c \u2192 \u03b1) : \u03b1 :=\n  Decidable.casesOn (motive := fun _ => \u03b1) 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) 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.buffer\n! leanprover-community/mathlib commit 9af482290ef68e8aaa5ead01aa7b09b7be7019fd\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\n\nuniverse u w\n\ndef Buffer (\u03b1 : Type u) :=\n  \u03a3n, Array' n \u03b1\n#align buffer Buffer\n\ndef mkBuffer {\u03b1 : Type u} : Buffer \u03b1 :=\n  \u27e80, { data := fun i => Fin.elim0 i }\u27e9\n#align mk_buffer mkBuffer\n\ndef Array'.toBuffer {\u03b1 : Type u} {n : Nat} (a : Array' n \u03b1) : Buffer \u03b1 :=\n  \u27e8n, a\u27e9\n#align array.to_buffer Array'.toBuffer\n\nnamespace Buffer\n\nvariable {\u03b1 : Type u} {\u03b2 : Type w}\n\ndef nil : Buffer \u03b1 :=\n  mkBuffer\n#align buffer.nil Buffer.nil\n\ndef size (b : Buffer \u03b1) : Nat :=\n  b.1\n#align buffer.size Buffer.size\n\ndef toArray (b : Buffer \u03b1) : Array' b.size \u03b1 :=\n  b.2\n#align buffer.to_array Buffer.toArray\n\ndef pushBack : Buffer \u03b1 \u2192 \u03b1 \u2192 Buffer \u03b1\n  | \u27e8n, a\u27e9, v => \u27e8n + 1, a.pushBack v\u27e9\n#align buffer.push_back Buffer.pushBack\n\ndef popBack : Buffer \u03b1 \u2192 Buffer \u03b1\n  | \u27e80, a\u27e9 => \u27e80, a\u27e9\n  | \u27e8n + 1, a\u27e9 => \u27e8n, a.popBack\u27e9\n#align buffer.pop_back Buffer.popBack\n\ndef read : \u2200 b : Buffer \u03b1, Fin b.size \u2192 \u03b1\n  | \u27e8n, a\u27e9, i => a.read i\n#align buffer.read Buffer.read\n\ndef write : \u2200 b : Buffer \u03b1, Fin b.size \u2192 \u03b1 \u2192 Buffer \u03b1\n  | \u27e8n, a\u27e9, i, v => \u27e8n, a.write i v\u27e9\n#align buffer.write Buffer.write\n\ndef read' [Inhabited \u03b1] : Buffer \u03b1 \u2192 Nat \u2192 \u03b1\n  | \u27e8n, a\u27e9, i => a.read' i\n#align buffer.read' Buffer.read'\n\ndef write' : Buffer \u03b1 \u2192 Nat \u2192 \u03b1 \u2192 Buffer \u03b1\n  | \u27e8n, a\u27e9, i, v => \u27e8n, a.write' i v\u27e9\n#align buffer.write' Buffer.write'\n\ntheorem read_eq_read' [Inhabited \u03b1] (b : Buffer \u03b1) (i : Nat) (h : i < b.size) :\n    read b \u27e8i, h\u27e9 = read' b i := by cases b <;> unfold read read' <;> simp [Array'.read_eq_read']\n#align buffer.read_eq_read' Buffer.read_eq_read'\n\ntheorem write_eq_write' (b : Buffer \u03b1) (i : Nat) (h : i < b.size) (v : \u03b1) :\n    write b \u27e8i, h\u27e9 v = write' b i v := by\n  cases b <;> unfold write write' <;> simp [Array'.write_eq_write']\n#align buffer.write_eq_write' Buffer.write_eq_write'\n\ndef toList (b : Buffer \u03b1) : List \u03b1 :=\n  b.toArray.toList\n#align buffer.to_list Buffer.toList\n\nprotected def toString (b : Buffer Char) : String :=\n  b.toArray.toList.asString\n#align buffer.to_string Buffer.toString\n\ndef appendList {\u03b1 : Type u} : Buffer \u03b1 \u2192 List \u03b1 \u2192 Buffer \u03b1\n  | b, [] => b\n  | b, v :: vs => append_list (b.pushBack v) vs\n#align buffer.append_list Buffer.appendList\n\ndef appendString (b : Buffer Char) (s : String) : Buffer Char :=\n  b.appendList s.toList\n#align buffer.append_string Buffer.appendString\n\ntheorem lt_aux_1 {a b c : Nat} (h : a + c < b) : a < b :=\n  lt_of_le_of_lt (Nat.le_add_right a c) h\n#align buffer.lt_aux_1 Buffer.lt_aux_1\n\ntheorem lt_aux_2 {n : Nat} (h : 0 < n) : n - 1 < n :=\n  Nat.sub_lt h (Nat.succ_pos 0)\n#align buffer.lt_aux_2 Buffer.lt_aux_2\n\ntheorem lt_aux_3 {n i} (h : i + 1 < n) : n - 2 - i < n :=\n  have : n > 0 := lt_trans (Nat.zero_lt_succ i) h\n  have : n - 2 < n := Nat.sub_lt this (by decide)\n  lt_of_le_of_lt (Nat.sub_le _ _) this\n#align buffer.lt_aux_3 Buffer.lt_aux_3\n\ndef appendArray {\u03b1 : Type u} {n : Nat} (nz : 0 < n) :\n    Buffer \u03b1 \u2192 Array' n \u03b1 \u2192 \u2200 i : Nat, i < n \u2192 Buffer \u03b1\n  | \u27e8m, b\u27e9, a, 0, _ =>\n    let i : Fin n := \u27e8n - 1, lt_aux_2 nz\u27e9\n    \u27e8m + 1, b.pushBack (a.read i)\u27e9\n  | \u27e8m, b\u27e9, a, j + 1, h =>\n    let i : Fin n := \u27e8n - 2 - j, lt_aux_3 h\u27e9\n    append_array \u27e8m + 1, b.pushBack (a.read i)\u27e9 a j (lt_aux_1 h)\n#align buffer.append_array Buffer.appendArray\n\nprotected def append {\u03b1 : Type u} : Buffer \u03b1 \u2192 Buffer \u03b1 \u2192 Buffer \u03b1\n  | b, \u27e80, a\u27e9 => b\n  | b, \u27e8n + 1, a\u27e9 => appendArray (Nat.zero_lt_succ _) b a n (Nat.lt_succ_self _)\n#align buffer.append Buffer.append\n\ndef iterate : \u2200 b : Buffer \u03b1, \u03b2 \u2192 (Fin b.size \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2\n  | \u27e8_, a\u27e9, b, f => a.iterate b f\n#align buffer.iterate Buffer.iterate\n\ndef foreach : \u2200 b : Buffer \u03b1, (Fin b.size \u2192 \u03b1 \u2192 \u03b1) \u2192 Buffer \u03b1\n  | \u27e8n, a\u27e9, f => \u27e8n, a.foreach f\u27e9\n#align buffer.foreach Buffer.foreach\n\n/-- Monadically map a function over the buffer. -/\n@[inline]\ndef mmap {m} [Monad m] (b : Buffer \u03b1) (f : \u03b1 \u2192 m \u03b2) : m (Buffer \u03b2) := do\n  let b' \u2190 b.2.mapM f\n  return b'\n#align buffer.mmap Buffer.mmap\n\n/-- Map a function over the buffer. -/\n@[inline]\ndef map : Buffer \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 Buffer \u03b2\n  | \u27e8n, a\u27e9, f => \u27e8n, a.map f\u27e9\n#align buffer.map Buffer.map\n\ndef foldl : Buffer \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2\n  | \u27e8_, a\u27e9, b, f => a.foldl b f\n#align buffer.foldl Buffer.foldl\n\ndef revIterate : \u2200 b : Buffer \u03b1, \u03b2 \u2192 (Fin b.size \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2\n  | \u27e8_, a\u27e9, b, f => a.revIterate b f\n#align buffer.rev_iterate Buffer.revIterate\n\ndef take (b : Buffer \u03b1) (n : Nat) : Buffer \u03b1 :=\n  if h : n \u2264 b.size then \u27e8n, b.toArray.take n h\u27e9 else b\n#align buffer.take Buffer.take\n\ndef takeRight (b : Buffer \u03b1) (n : Nat) : Buffer \u03b1 :=\n  if h : n \u2264 b.size then \u27e8n, b.toArray.takeRight n h\u27e9 else b\n#align buffer.take_right Buffer.takeRight\n\ndef drop (b : Buffer \u03b1) (n : Nat) : Buffer \u03b1 :=\n  if h : n \u2264 b.size then \u27e8_, b.toArray.drop n h\u27e9 else b\n#align buffer.drop Buffer.drop\n\ndef reverse (b : Buffer \u03b1) : Buffer \u03b1 :=\n  \u27e8b.size, b.toArray.reverse\u27e9\n#align buffer.reverse Buffer.reverse\n\nprotected def Mem (v : \u03b1) (a : Buffer \u03b1) : Prop :=\n  \u2203 i, read a i = v\n#align buffer.mem Buffer.Mem\n\ninstance : Membership \u03b1 (Buffer \u03b1) :=\n  \u27e8Buffer.Mem\u27e9\n\ninstance : Append (Buffer \u03b1) :=\n  \u27e8Buffer.append\u27e9\n\ninstance [Repr \u03b1] : Repr (Buffer \u03b1) :=\n  \u27e8repr \u2218 toList\u27e9\n\nunsafe instance [has_to_format \u03b1] : has_to_format (Buffer \u03b1) :=\n  \u27e8to_fmt \u2218 toList\u27e9\n\nunsafe instance [has_to_tactic_format \u03b1] : has_to_tactic_format (Buffer \u03b1) :=\n  \u27e8tactic.pp \u2218 toList\u27e9\n\nend Buffer\n\ndef List.toBuffer {\u03b1 : Type u} (l : List \u03b1) : Buffer \u03b1 :=\n  mkBuffer.appendList l\n#align list.to_buffer List.toBuffer\n\n@[reducible]\ndef CharBuffer :=\n  Buffer Char\n#align char_buffer CharBuffer\n\n/-- Convert a format object into a character buffer with the provided\n    formatting options. -/\nunsafe axiom format.to_buffer : format \u2192 options \u2192 Buffer Char\n#align format.to_buffer format.to_buffer\n\ndef String.toCharBuffer (s : String) : CharBuffer :=\n  Buffer.nil.appendString s\n#align string.to_char_buffer String.toCharBuffer\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.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.11436853221906972, "lm_q1q2_score": 0.0487577731257344}}
{"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 {\u03b1 : Sort u} {\u03b2 : Sort v}\n\n/-- Functorial action. -/\nprotected def map (f : \u03b1 \u2192 \u03b2) (a : plift \u03b1) : plift \u03b2 :=\nplift.up (f a.down)\n\n@[simp] \n\n/-- Embedding of pure values. -/\n@[simp] protected def pure : \u03b1 \u2192 plift \u03b1 := up\n\n/-- Applicative sequencing. -/\nprotected def seq (f : plift (\u03b1 \u2192 \u03b2)) (x : plift \u03b1) : plift \u03b2 :=\nplift.up (f.down x.down)\n\n@[simp] lemma seq_up (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (plift.up f).seq (plift.up x) = plift.up (f x) := rfl\n\n/-- Monadic bind. -/\nprotected def bind (a : plift \u03b1) (f : \u03b1 \u2192 plift \u03b2) : plift \u03b2 := f a.down\n\n@[simp] lemma bind_up (a : \u03b1) (f : \u03b1 \u2192 plift \u03b2) : (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 := \u03bb \u03b1 \u27e8x\u27e9, rfl,\n  comp_map := \u03bb \u03b1 \u03b2 \u03b3 g h \u27e8x\u27e9, rfl }\n\ninstance : is_lawful_applicative plift :=\n{ pure_seq_eq_map := \u03bb \u03b1 \u03b2 g \u27e8x\u27e9, rfl,\n  map_pure := \u03bb \u03b1 \u03b2 g x, rfl,\n  seq_pure := \u03bb \u03b1 \u03b2 \u27e8g\u27e9 x, rfl,\n  seq_assoc := \u03bb \u03b1 \u03b2 \u03b3 \u27e8x\u27e9 \u27e8g\u27e9 \u27e8h\u27e9, rfl }\n\ninstance : is_lawful_monad plift :=\n{ bind_pure_comp_eq_map := \u03bb \u03b1 \u03b2 f \u27e8x\u27e9, rfl,\n  bind_map_eq_seq := \u03bb \u03b1 \u03b2 \u27e8a\u27e9 \u27e8b\u27e9, rfl,\n  pure_bind := \u03bb \u03b1 \u03b2 x f, rfl,\n  bind_assoc := \u03bb \u03b1 \u03b2 \u03b3 \u27e8x\u27e9 f g, rfl }\n\n@[simp] lemma rec.constant {\u03b1 : Sort u} {\u03b2 : Type v} (b : \u03b2) :\n  @plift.rec \u03b1 (\u03bb _, \u03b2) (\u03bb _, b) = \u03bb _, b :=\nfunext (\u03bb x, plift.cases_on x (\u03bb a, eq.refl (plift.rec (\u03bb a', b) {down := a})))\n\nend plift\n\n\nnamespace ulift\n\nvariables {\u03b1 : Type u} {\u03b2 : Type v}\n\n/-- Functorial action. -/\nprotected def map (f : \u03b1 \u2192 \u03b2) (a : ulift \u03b1) : ulift \u03b2 :=\nulift.up (f a.down)\n\n@[simp] lemma map_up (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : (ulift.up a).map f = ulift.up (f a) := rfl\n\n/-- Embedding of pure values. -/\n@[simp] protected def pure : \u03b1 \u2192 ulift \u03b1 := up\n\n/-- Applicative sequencing. -/\nprotected def seq (f : ulift (\u03b1 \u2192 \u03b2)) (x : ulift \u03b1) : ulift \u03b2 :=\nulift.up (f.down x.down)\n\n@[simp] lemma seq_up (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (ulift.up f).seq (ulift.up x) = ulift.up (f x) := rfl\n\n/-- Monadic bind. -/\nprotected def bind (a : ulift \u03b1) (f : \u03b1 \u2192 ulift \u03b2) : ulift \u03b2 := f a.down\n\n@[simp] lemma bind_up (a : \u03b1) (f : \u03b1 \u2192 ulift \u03b2) : (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 := \u03bb \u03b1 \u27e8x\u27e9, rfl,\n  comp_map := \u03bb \u03b1 \u03b2 \u03b3 g h \u27e8x\u27e9, rfl }\n\ninstance : is_lawful_applicative ulift :=\n{ to_is_lawful_functor := ulift.is_lawful_functor,\n  pure_seq_eq_map := \u03bb \u03b1 \u03b2 g \u27e8x\u27e9, rfl,\n  map_pure := \u03bb \u03b1 \u03b2 g x, rfl,\n  seq_pure := \u03bb \u03b1 \u03b2 \u27e8g\u27e9 x, rfl,\n  seq_assoc := \u03bb \u03b1 \u03b2 \u03b3 \u27e8x\u27e9 \u27e8g\u27e9 \u27e8h\u27e9, rfl }\n\ninstance : is_lawful_monad ulift :=\n{ bind_pure_comp_eq_map := \u03bb \u03b1 \u03b2 f \u27e8x\u27e9, rfl,\n  bind_map_eq_seq := \u03bb \u03b1 \u03b2 \u27e8a\u27e9 \u27e8b\u27e9, rfl,\n  pure_bind := \u03bb \u03b1 \u03b2 x f,\n    by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl },\n  bind_assoc := \u03bb \u03b1 \u03b2 \u03b3 \u27e8x\u27e9 f g,\n    by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl } }\n\n@[simp] lemma rec.constant {\u03b1 : Type u} {\u03b2 : Sort v} (b : \u03b2) :\n  @ulift.rec \u03b1 (\u03bb _, \u03b2) (\u03bb _, b) = \u03bb _, b :=\nfunext (\u03bb x, ulift.cases_on x (\u03bb a, eq.refl (ulift.rec (\u03bb 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 \u2227 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 {\u03b1 : Type*} {\u03b2 : 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 {\u03b1 : Sort*} {a : \u03b1} := a\n\n/-- Ex falso, the nondependent eliminator for the `empty` type. -/\ndef empty.elim {C : Sort*} : empty \u2192 C.\n\ninstance : subsingleton empty := \u27e8\u03bba, a.elim\u27e9\n\ninstance subsingleton.prod {\u03b1 \u03b2 : Type*} [subsingleton \u03b1] [subsingleton \u03b2] : subsingleton (\u03b1 \u00d7 \u03b2) :=\n\u27e8by { intros a b, cases a, cases b, congr, }\u27e9\n\ninstance : decidable_eq empty := \u03bba, a.elim\n\ninstance sort.inhabited : inhabited (Sort*) := \u27e8punit\u27e9\ninstance sort.inhabited' : inhabited (default (Sort*)) := \u27e8punit.star\u27e9\n\ninstance psum.inhabited_left {\u03b1 \u03b2} [inhabited \u03b1] : inhabited (psum \u03b1 \u03b2) := \u27e8psum.inl (default _)\u27e9\ninstance psum.inhabited_right {\u03b1 \u03b2} [inhabited \u03b2] : inhabited (psum \u03b1 \u03b2) := \u27e8psum.inr (default _)\u27e9\n\n@[priority 10] instance decidable_eq_of_subsingleton\n  {\u03b1} [subsingleton \u03b1] : decidable_eq \u03b1\n| a b := is_true (subsingleton.elim a b)\n\n@[simp] lemma eq_iff_true_of_subsingleton {\u03b1 : Sort*} [subsingleton \u03b1] (x y : \u03b1) :\n  x = y \u2194 true :=\nby cc\n\n/-- If all points are equal to a given point `x`, then `\u03b1` is a subsingleton. -/\nlemma subsingleton_of_forall_eq {\u03b1 : Sort*} (x : \u03b1) (h : \u2200 y, y = x) : subsingleton \u03b1 :=\n\u27e8\u03bb a b, (h a).symm \u25b8 (h b).symm \u25b8 rfl\u27e9\n\nlemma subsingleton_iff_forall_eq {\u03b1 : Sort*} (x : \u03b1) : subsingleton \u03b1 \u2194 \u2200 y, y = x :=\n\u27e8\u03bb h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x\u27e9\n\n-- TODO[gh-6025]: make this an instance once safe to do so\nlemma subtype.subsingleton (\u03b1 : Sort*) [subsingleton \u03b1] (p : \u03b1 \u2192 Prop) : subsingleton (subtype p) :=\n\u27e8\u03bb \u27e8x,_\u27e9 \u27e8y,_\u27e9, have x = y, from subsingleton.elim _ _, by { cases this, refl }\u27e9\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 {\u03b1 \u03b2 \u03b3} [has_coe \u03b1 \u03b2] [has_coe_t \u03b2 \u03b3]\n  (a : \u03b1) : (a : \u03b3) = (a : \u03b2) := rfl\n\ntheorem coe_fn_coe_trans\n  {\u03b1 \u03b2 \u03b3 \u03b4} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_fun \u03b3 \u03b4]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\n/-- Non-dependent version of `coe_fn_coe_trans`, helps `rw` figure out the argument. -/\ntheorem coe_fn_coe_trans'\n  {\u03b1 \u03b2 \u03b3} {\u03b4 : out_param $ _} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_fun \u03b3 (\u03bb _, \u03b4)]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\n@[simp] theorem coe_fn_coe_base\n  {\u03b1 \u03b2 \u03b3} [has_coe \u03b1 \u03b2] [has_coe_to_fun \u03b2 \u03b3]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\n/-- Non-dependent version of `coe_fn_coe_base`, helps `rw` figure out the argument. -/\ntheorem coe_fn_coe_base'\n  {\u03b1 \u03b2} {\u03b3 : out_param $ _} [has_coe \u03b1 \u03b2] [has_coe_to_fun \u03b2 (\u03bb _, \u03b3)]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\ntheorem coe_sort_coe_trans\n  {\u03b1 \u03b2 \u03b3 \u03b4} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_sort \u03b3 \u03b4]\n  (x : \u03b1) : @coe_sort \u03b1 _ _ x = @coe_sort \u03b2 _ _ 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 : \u03b1 \u2243 \u03b2` and `a : \u03b1`\nthen you can write `e a` and this is elaborated as `\u21d1e 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 (\u03b1 \u03b2) extends \u03b1 \u2243 \u03b2\n\n-- if we add a `has_coe` instance,\ninstance {\u03b1 \u03b2} : has_coe (sparkling_equiv \u03b1 \u03b2) (\u03b1 \u2243 \u03b2) :=\n\u27e8sparkling_equiv.to_equiv\u27e9\n\n-- then a `has_coe_to_fun` instance **must** be added as well:\ninstance {\u03b1 \u03b2} : has_coe_to_fun (sparkling_equiv \u03b1 \u03b2) :=\n\u27e8\u03bb _, \u03b1 \u2192 \u03b2, \u03bb f, f.to_equiv.to_fun\u27e9\n```\n\n(Rationale: if we do not declare the direct coercion, then `\u21d1e a` is not in\nsimp-normal form. The lemma `coe_fn_coe_base` will unfold it to `\u21d1\u2191e a`. This\noften causes loops in the simplifier.)\n-/\nlibrary_note \"function coercion\"\n\n@[simp] theorem coe_sort_coe_base\n  {\u03b1 \u03b2 \u03b3} [has_coe \u03b1 \u03b2] [has_coe_to_sort \u03b2 \u03b3]\n  (x : \u03b1) : @coe_sort \u03b1 _ _ x = @coe_sort \u03b2 _ _ 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 \u2192 C.\n\ninstance subsingleton_pempty : subsingleton pempty := \u27e8\u03bba, a.elim\u27e9\n\n@[simp] lemma not_nonempty_pempty : \u00ac nonempty pempty :=\nassume \u27e8h\u27e9, h.elim\n\n@[simp] theorem forall_pempty {P : pempty \u2192 Prop} : (\u2200 x : pempty, P x) \u2194 true :=\n\u27e8\u03bb h, trivial, \u03bb h x, by cases x\u27e9\n\n@[simp] theorem exists_pempty {P : pempty \u2192 Prop} : (\u2203 x : pempty, P x) \u2194 false :=\n\u27e8\u03bb h, by { cases h with w, cases w }, false.elim\u27e9\n\nlemma congr_arg_heq {\u03b1} {\u03b2 : \u03b1 \u2192 Sort*} (f : \u2200 a, \u03b2 a) : \u2200 {a\u2081 a\u2082 : \u03b1}, a\u2081 = a\u2082 \u2192 f a\u2081 == f a\u2082\n| a _ rfl := heq.rfl\n\nlemma plift.down_inj {\u03b1 : Sort*} : \u2200 (a b : plift \u03b1), a.down = b.down \u2192 a = b\n| \u27e8a\u27e9 \u27e8b\u27e9 rfl := rfl\n\n-- missing [symm] attribute for ne in core.\nattribute [symm] ne.symm\n\nlemma ne_comm {\u03b1} {a b : \u03b1} : a \u2260 b \u2194 b \u2260 a := \u27e8ne.symm, ne.symm\u27e9\n\n@[simp] lemma eq_iff_eq_cancel_left {b c : \u03b1} :\n  (\u2200 {a}, a = b \u2194 a = c) \u2194 (b = c) :=\n\u27e8\u03bb h, by rw [\u2190 h], \u03bb h a, by rw h\u27e9\n\n@[simp] lemma eq_iff_eq_cancel_right {a b : \u03b1} :\n  (\u2200 {c}, a = c \u2194 b = c) \u2194 (a = b) :=\n\u27e8\u03bb h, by rw h, \u03bb h a, by rw h\u27e9\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 \u2194 p := \u27e8\u03bb h, h.1, \u03bb h, \u27e8h\u27e9\u27e9\n\nend miscellany\n\n/-!\n### Declarations about propositional connectives\n-/\n\ntheorem false_ne_true : false \u2260 true\n| h := h.symm \u25b8 trivial\n\nsection propositional\nvariables {a b c d : Prop}\n\n/-! ### Declarations about `implies` -/\n\ninstance : is_refl Prop iff := \u27e8iff.refl\u27e9\ninstance : is_trans Prop iff := \u27e8\u03bb _ _ _, iff.trans\u27e9\n\ntheorem iff_of_eq (e : a = b) : a \u2194 b := e \u25b8 iff.rfl\n\ntheorem iff_iff_eq : (a \u2194 b) \u2194 a = b := \u27e8propext, iff_of_eq\u27e9\n\n@[simp] lemma eq_iff_iff {p q : Prop} : (p = q) \u2194 (p \u2194 q) := iff_iff_eq.symm\n\n@[simp] theorem imp_self : (a \u2192 a) \u2194 true := iff_true_intro id\n\ntheorem imp_intro {\u03b1 \u03b2 : Prop} (h : \u03b1) : \u03b2 \u2192 \u03b1 := \u03bb _, h\n\ntheorem imp_false : (a \u2192 false) \u2194 \u00ac a := iff.rfl\n\ntheorem imp_and_distrib {\u03b1} : (\u03b1 \u2192 b \u2227 c) \u2194 (\u03b1 \u2192 b) \u2227 (\u03b1 \u2192 c) :=\n\u27e8\u03bb h, \u27e8\u03bb ha, (h ha).left, \u03bb ha, (h ha).right\u27e9,\n \u03bb h ha, \u27e8h.left ha, h.right ha\u27e9\u27e9\n\n@[simp] theorem and_imp : (a \u2227 b \u2192 c) \u2194 (a \u2192 b \u2192 c) :=\niff.intro (\u03bb h ha hb, h \u27e8ha, hb\u27e9) (\u03bb h \u27e8ha, hb\u27e9, h ha hb)\n\ntheorem iff_def : (a \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 a) :=\niff_iff_implies_and_implies _ _\n\ntheorem iff_def' : (a \u2194 b) \u2194 (b \u2192 a) \u2227 (a \u2192 b) :=\niff_def.trans and.comm\n\ntheorem imp_true_iff {\u03b1 : Sort*} : (\u03b1 \u2192 true) \u2194 true :=\niff_true_intro $ \u03bb_, trivial\n\ntheorem imp_iff_right (ha : a) : (a \u2192 b) \u2194 b :=\n\u27e8\u03bbf, f ha, imp_intro\u27e9\n\ntheorem decidable.imp_iff_right_iff [decidable a] : ((a \u2192 b) \u2194 b) \u2194 (a \u2228 b) :=\n\u27e8\u03bb H, (decidable.em a).imp_right $ \u03bb ha', H.1 $ \u03bb ha, (ha' ha).elim,\n  \u03bb H, H.elim imp_iff_right $ \u03bb hb, \u27e8\u03bb hab, hb, \u03bb _ _, hb\u27e9\u27e9\n\n@[simp] theorem imp_iff_right_iff : ((a \u2192 b) \u2194 b) \u2194 (a \u2228 b) :=\ndecidable.imp_iff_right_iff\n\n/-! ### Declarations about `not` -/\n\n/-- Ex falso for negation. From `\u00ac 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 {\u03b1 : Sort*} (H1 : \u00aca) (H2 : a) : \u03b1 := absurd H2 H1\n\n@[reducible] theorem not.imp {a b : Prop} (H2 : \u00acb) (H1 : a \u2192 b) : \u00aca := mt H1 H2\n\ntheorem not_not_of_not_imp : \u00ac(a \u2192 b) \u2192 \u00ac\u00aca :=\nmt not.elim\n\ntheorem not_of_not_imp {a : Prop} : \u00ac(a \u2192 b) \u2192 \u00acb :=\nmt imp_intro\n\ntheorem dec_em (p : Prop) [decidable p] : p \u2228 \u00acp := decidable.em p\n\ntheorem dec_em' (p : Prop) [decidable p] : \u00acp \u2228 p := (dec_em p).swap\n\ntheorem em (p : Prop) : p \u2228 \u00acp := classical.em _\n\ntheorem em' (p : Prop) : \u00acp \u2228 p := (em p).swap\n\ntheorem or_not {p : Prop} : p \u2228 \u00acp := em _\n\nsection eq_or_ne\n\nvariables {\u03b1 : Sort*} (x y : \u03b1)\n\ntheorem decidable.eq_or_ne [decidable (x = y)] : x = y \u2228 x \u2260 y := dec_em $ x = y\n\ntheorem decidable.ne_or_eq [decidable (x = y)] : x \u2260 y \u2228 x = y := dec_em' $ x = y\n\ntheorem eq_or_ne : x = y \u2228 x \u2260 y := em $ x = y\n\ntheorem ne_or_eq : x \u2260 y \u2228 x = y := em' $ x = y\n\nend eq_or_ne\n\ntheorem by_contradiction {p} : (\u00acp \u2192 false) \u2192 p := decidable.by_contradiction\n\n-- alias by_contradiction \u2190 by_contra\ntheorem by_contra {p} : (\u00acp \u2192 false) \u2192 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] : \u00ac\u00aca \u2194 a :=\niff.intro decidable.by_contradiction not_not_intro\n\n/-- The Double Negation Theorem: `\u00ac \u00ac 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 : \u00ac\u00aca \u2194 a := decidable.not_not\n\ntheorem of_not_not : \u00ac\u00aca \u2192 a := by_contra\n\n-- See Note [decidable namespace]\nprotected theorem decidable.of_not_imp [decidable a] (h : \u00ac (a \u2192 b)) : a :=\ndecidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp : \u00ac (a \u2192 b) \u2192 a := decidable.of_not_imp\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp_symm [decidable a] (h : \u00aca \u2192 b) (hb : \u00acb) : a :=\ndecidable.by_contradiction $ hb \u2218 h\n\ntheorem not.decidable_imp_symm [decidable a] : (\u00aca \u2192 b) \u2192 \u00acb \u2192 a := decidable.not_imp_symm\n\ntheorem not.imp_symm : (\u00aca \u2192 b) \u2192 \u00acb \u2192 a := not.decidable_imp_symm\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp_comm [decidable a] [decidable b] : (\u00aca \u2192 b) \u2194 (\u00acb \u2192 a) :=\n\u27e8not.decidable_imp_symm, not.decidable_imp_symm\u27e9\n\ntheorem not_imp_comm : (\u00aca \u2192 b) \u2194 (\u00acb \u2192 a) := decidable.not_imp_comm\n\n@[simp] theorem imp_not_self : (a \u2192 \u00aca) \u2194 \u00aca := \u27e8\u03bb h ha, h ha ha, \u03bb h _, h\u27e9\n\ntheorem decidable.not_imp_self [decidable a] : (\u00aca \u2192 a) \u2194 a :=\nby { have := @imp_not_self (\u00aca), rwa decidable.not_not at this }\n\n@[simp] theorem not_imp_self : (\u00aca \u2192 a) \u2194 a := decidable.not_imp_self\n\ntheorem imp.swap : (a \u2192 b \u2192 c) \u2194 (b \u2192 a \u2192 c) :=\n\u27e8swap, swap\u27e9\n\ntheorem imp_not_comm : (a \u2192 \u00acb) \u2194 (b \u2192 \u00aca) :=\nimp.swap\n\n/-! ### Declarations about `xor` -/\n\n@[simp] theorem xor_true : xor true = not := funext $ \u03bb a, by simp [xor]\n\n@[simp] theorem xor_false : xor false = id := funext $ \u03bb 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 := \u27e8xor_comm\u27e9\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 \u2192 (a \u2194 b)) : a \u2227 c \u2194 b \u2227 c :=\nand.comm.trans $ (and_congr_right h).trans and.comm\n\ntheorem and_congr_left' (h : a \u2194 b) : a \u2227 c \u2194 b \u2227 c := and_congr h iff.rfl\n\ntheorem and_congr_right' (h : b \u2194 c) : a \u2227 b \u2194 a \u2227 c := and_congr iff.rfl h\n\ntheorem not_and_of_not_left (b : Prop) : \u00aca \u2192 \u00ac(a \u2227 b) :=\nmt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : \u00acb \u2192 \u00ac(a \u2227 b) :=\nmt and.right\n\ntheorem and.imp_left (h : a \u2192 b) : a \u2227 c \u2192 b \u2227 c :=\nand.imp h id\n\ntheorem and.imp_right (h : a \u2192 b) : c \u2227 a \u2192 c \u2227 b :=\nand.imp id h\n\nlemma and.right_comm : (a \u2227 b) \u2227 c \u2194 (a \u2227 c) \u2227 b :=\nby simp only [and.left_comm, and.comm]\n\nlemma and_and_and_comm (a b c d : Prop) : (a \u2227 b) \u2227 c \u2227 d \u2194 (a \u2227 c) \u2227 b \u2227 d :=\nby rw [\u2190and_assoc, @and.right_comm a, and_assoc]\n\nlemma and.rotate : a \u2227 b \u2227 c \u2194 b \u2227 c \u2227 a :=\nby simp only [and.left_comm, and.comm]\n\ntheorem and_not_self_iff (a : Prop) : a \u2227 \u00ac a \u2194 false :=\niff.intro (assume h, (h.right) (h.left)) (assume h, h.elim)\n\ntheorem not_and_self_iff (a : Prop) : \u00ac a \u2227 a \u2194 false :=\niff.intro (assume \u27e8hna, ha\u27e9, hna ha) false.elim\n\ntheorem and_iff_left_of_imp {a b : Prop} (h : a \u2192 b) : (a \u2227 b) \u2194 a :=\niff.intro and.left (\u03bb ha, \u27e8ha, h ha\u27e9)\n\ntheorem and_iff_right_of_imp {a b : Prop} (h : b \u2192 a) : (a \u2227 b) \u2194 b :=\niff.intro and.right (\u03bb hb, \u27e8h hb, hb\u27e9)\n\n@[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a \u2227 b) \u2194 a) \u2194 (a \u2192 b) :=\n\u27e8\u03bb h ha, (h.2 ha).2, and_iff_left_of_imp\u27e9\n\n@[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a \u2227 b) \u2194 b) \u2194 (b \u2192 a) :=\n\u27e8\u03bb h ha, (h.2 ha).1, and_iff_right_of_imp\u27e9\n\n@[simp] lemma iff_self_and {p q : Prop} : (p \u2194 p \u2227 q) \u2194 (p \u2192 q) :=\nby rw [@iff.comm p, and_iff_left_iff_imp]\n\n@[simp] lemma iff_and_self {p q : Prop} : (p \u2194 q \u2227 p) \u2194 (p \u2192 q) :=\nby rw [and_comm, iff_self_and]\n\n@[simp] lemma and.congr_right_iff : (a \u2227 b \u2194 a \u2227 c) \u2194 (a \u2192 (b \u2194 c)) :=\n\u27e8\u03bb h ha, by simp [ha] at h; exact h, and_congr_right\u27e9\n\n@[simp] lemma and.congr_left_iff : (a \u2227 c \u2194 b \u2227 c) \u2194 c \u2192 (a \u2194 b) :=\nby simp only [and.comm, \u2190 and.congr_right_iff]\n\n@[simp] lemma and_self_left : a \u2227 a \u2227 b \u2194 a \u2227 b :=\n\u27e8\u03bb h, \u27e8h.1, h.2.2\u27e9, \u03bb h, \u27e8h.1, h.1, h.2\u27e9\u27e9\n\n@[simp] lemma and_self_right : (a \u2227 b) \u2227 b \u2194 a \u2227 b :=\n\u27e8\u03bb h, \u27e8h.1.1, h.2\u27e9, \u03bb h, \u27e8\u27e8h.1, h.2\u27e9, h.2\u27e9\u27e9\n\n/-! ### Declarations about `or` -/\n\ntheorem or_congr_left (h : a \u2194 b) : a \u2228 c \u2194 b \u2228 c := or_congr h iff.rfl\n\ntheorem or_congr_right (h : b \u2194 c) : a \u2228 b \u2194 a \u2228 c := or_congr iff.rfl h\n\ntheorem or.right_comm : (a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 b := by rw [or_assoc, or_assoc, or_comm b]\n\ntheorem or_of_or_of_imp_of_imp (h\u2081 : a \u2228 b) (h\u2082 : a \u2192 c) (h\u2083 : b \u2192 d) : c \u2228 d :=\nor.imp h\u2082 h\u2083 h\u2081\n\ntheorem or_of_or_of_imp_left (h\u2081 : a \u2228 c) (h : a \u2192 b) : b \u2228 c :=\nor.imp_left h h\u2081\n\ntheorem or_of_or_of_imp_right (h\u2081 : c \u2228 a) (h : a \u2192 b) : c \u2228 b :=\nor.imp_right h h\u2081\n\ntheorem or.elim3 (h : a \u2228 b \u2228 c) (ha : a \u2192 d) (hb : b \u2192 d) (hc : c \u2192 d) : d :=\nor.elim h ha (assume h\u2082, or.elim h\u2082 hb hc)\n\ntheorem or_imp_distrib : (a \u2228 b \u2192 c) \u2194 (a \u2192 c) \u2227 (b \u2192 c) :=\n\u27e8assume h, \u27e8assume ha, h (or.inl ha), assume hb, h (or.inr hb)\u27e9,\n  assume \u27e8ha, hb\u27e9, or.rec ha hb\u27e9\n\n-- See Note [decidable namespace]\nprotected theorem decidable.or_iff_not_imp_left [decidable a] : a \u2228 b \u2194 (\u00ac a \u2192 b) :=\n\u27e8or.resolve_left, \u03bb h, dite _ or.inl (or.inr \u2218 h)\u27e9\n\ntheorem or_iff_not_imp_left : a \u2228 b \u2194 (\u00ac a \u2192 b) := decidable.or_iff_not_imp_left\n\n-- See Note [decidable namespace]\nprotected theorem decidable.or_iff_not_imp_right [decidable b] : a \u2228 b \u2194 (\u00ac b \u2192 a) :=\nor.comm.trans decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right : a \u2228 b \u2194 (\u00ac b \u2192 a) := decidable.or_iff_not_imp_right\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp_not [decidable a] : (\u00ac a \u2192 \u00ac b) \u2194 (b \u2192 a) :=\n\u27e8assume h hb, decidable.by_contradiction $ assume na, h na hb, mt\u27e9\n\ntheorem not_imp_not : (\u00ac a \u2192 \u00ac b) \u2194 (b \u2192 a) := decidable.not_imp_not\n\n@[simp] theorem or_iff_left_iff_imp : (a \u2228 b \u2194 a) \u2194 (b \u2192 a) :=\n\u27e8\u03bb h hb, h.1 (or.inr hb), or_iff_left_of_imp\u27e9\n\n@[simp] theorem or_iff_right_iff_imp : (a \u2228 b \u2194 b) \u2194 (a \u2192 b) :=\nby rw [or_comm, or_iff_left_iff_imp]\n\n/-! ### Declarations about distributivity -/\n\n/-- `\u2227` distributes over `\u2228` (on the left). -/\ntheorem and_or_distrib_left : a \u2227 (b \u2228 c) \u2194 (a \u2227 b) \u2228 (a \u2227 c) :=\n\u27e8\u03bb \u27e8ha, hbc\u27e9, hbc.imp (and.intro ha) (and.intro ha),\n or.rec (and.imp_right or.inl) (and.imp_right or.inr)\u27e9\n\n/-- `\u2227` distributes over `\u2228` (on the right). -/\ntheorem or_and_distrib_right : (a \u2228 b) \u2227 c \u2194 (a \u2227 c) \u2228 (b \u2227 c) :=\n(and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm)\n\n/-- `\u2228` distributes over `\u2227` (on the left). -/\ntheorem or_and_distrib_left : a \u2228 (b \u2227 c) \u2194 (a \u2228 b) \u2227 (a \u2228 c) :=\n\u27e8or.rec (\u03bbha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr),\n and.rec $ or.rec (imp_intro \u2218 or.inl) (or.imp_right \u2218 and.intro)\u27e9\n\n/-- `\u2228` distributes over `\u2227` (on the right). -/\ntheorem and_or_distrib_right : (a \u2227 b) \u2228 c \u2194 (a \u2228 c) \u2227 (b \u2228 c) :=\n(or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm)\n\n@[simp] lemma or_self_left : a \u2228 a \u2228 b \u2194 a \u2228 b :=\n\u27e8\u03bb h, h.elim or.inl id, \u03bb h, h.elim or.inl (or.inr \u2218 or.inr)\u27e9\n\n@[simp] lemma or_self_right : (a \u2228 b) \u2228 b \u2194 a \u2228 b :=\n\u27e8\u03bb h, h.elim id or.inr, \u03bb h, h.elim (or.inl \u2218 or.inl) or.inr\u27e9\n\n/-! Declarations about `iff` -/\n\ntheorem iff_of_true (ha : a) (hb : b) : a \u2194 b :=\n\u27e8\u03bb_, hb, \u03bb _, ha\u27e9\n\ntheorem iff_of_false (ha : \u00aca) (hb : \u00acb) : a \u2194 b :=\n\u27e8ha.elim, hb.elim\u27e9\n\ntheorem iff_true_left (ha : a) : (a \u2194 b) \u2194 b :=\n\u27e8\u03bb h, h.1 ha, iff_of_true ha\u27e9\n\ntheorem iff_true_right (ha : a) : (b \u2194 a) \u2194 b :=\niff.comm.trans (iff_true_left ha)\n\ntheorem iff_false_left (ha : \u00aca) : (a \u2194 b) \u2194 \u00acb :=\n\u27e8\u03bb h, mt h.2 ha, iff_of_false ha\u27e9\n\ntheorem iff_false_right (ha : \u00aca) : (b \u2194 a) \u2194 \u00acb :=\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 \u2192 b) : \u00ac a \u2228 b :=\nif ha : a then or.inr (h ha) else or.inl ha\n\ntheorem not_or_of_imp : (a \u2192 b) \u2192 \u00ac a \u2228 b := decidable.not_or_of_imp\n\n-- See Note [decidable namespace]\nprotected theorem decidable.imp_iff_not_or [decidable a] : (a \u2192 b) \u2194 (\u00ac a \u2228 b) :=\n\u27e8decidable.not_or_of_imp, or.neg_resolve_left\u27e9\n\ntheorem imp_iff_not_or : (a \u2192 b) \u2194 (\u00ac a \u2228 b) := decidable.imp_iff_not_or\n\n-- See Note [decidable namespace]\nprotected theorem decidable.imp_or_distrib [decidable a] : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\nby simp [decidable.imp_iff_not_or, or.comm, or.left_comm]\n\ntheorem imp_or_distrib : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) := decidable.imp_or_distrib\n\n-- See Note [decidable namespace]\nprotected theorem decidable.imp_or_distrib' [decidable b] : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\nby by_cases b; simp [h, or_iff_right_of_imp ((\u2218) false.elim)]\n\ntheorem imp_or_distrib' : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) := decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not : a \u2227 \u00ac b \u2192 \u00ac (a \u2192 b)\n| \u27e8ha, hb\u27e9 h := hb $ h ha\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp [decidable a] : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb :=\n\u27e8\u03bb h, \u27e8decidable.of_not_imp h, not_of_not_imp h\u27e9, not_imp_of_and_not\u27e9\n\ntheorem not_imp : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb := decidable.not_imp\n\n-- for monotonicity\nlemma imp_imp_imp (h\u2080 : c \u2192 a) (h\u2081 : b \u2192 d) : (a \u2192 b) \u2192 (c \u2192 d) :=\nassume (h\u2082 : a \u2192 b), h\u2081 \u2218 h\u2082 \u2218 h\u2080\n\n-- See Note [decidable namespace]\nprotected theorem decidable.peirce (a b : Prop) [decidable a] : ((a \u2192 b) \u2192 a) \u2192 a :=\nif ha : a then \u03bb h, ha else \u03bb h, h ha.elim\n\ntheorem peirce (a b : Prop) : ((a \u2192 b) \u2192 a) \u2192 a := decidable.peirce _ _\n\ntheorem peirce' {a : Prop} (H : \u2200 b : Prop, (a \u2192 b) \u2192 a) : a := H _ id\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_iff_not [decidable a] [decidable b] : (\u00ac a \u2194 \u00ac b) \u2194 (a \u2194 b) :=\nby rw [@iff_def (\u00ac a), @iff_def' a]; exact and_congr decidable.not_imp_not decidable.not_imp_not\n\ntheorem not_iff_not : (\u00ac a \u2194 \u00ac b) \u2194 (a \u2194 b) := decidable.not_iff_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_iff_comm [decidable a] [decidable b] : (\u00ac a \u2194 b) \u2194 (\u00ac b \u2194 a) :=\nby rw [@iff_def (\u00ac a), @iff_def (\u00ac b)]; exact and_congr decidable.not_imp_comm imp_not_comm\n\ntheorem not_iff_comm : (\u00ac a \u2194 b) \u2194 (\u00ac b \u2194 a) := decidable.not_iff_comm\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_iff : \u2200 [decidable b], \u00ac (a \u2194 b) \u2194 (\u00ac a \u2194 b) :=\nby intro h; cases h; simp only [h, iff_true, iff_false]\n\ntheorem not_iff : \u00ac (a \u2194 b) \u2194 (\u00ac a \u2194 b) := decidable.not_iff\n\n-- See Note [decidable namespace]\nprotected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a \u2194 \u00ac b) \u2194 (b \u2194 \u00ac 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 \u2194 \u00ac b) \u2194 (b \u2194 \u00ac 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 \u2194 b) \u2194 (a \u2227 b) \u2228 (\u00ac a \u2227 \u00ac 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 \u2194 b) \u2194 (a \u2227 b) \u2228 (\u00ac a \u2227 \u00ac 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 \u2194 b) \u2194 ((\u00aca \u2228 b) \u2227 (a \u2228 \u00acb)) :=\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 \u2194 b) \u2194 ((\u00aca \u2228 b) \u2227 (a \u2228 \u00acb)) :=\ndecidable.iff_iff_not_or_and_or_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_and_not_right [decidable b] : \u00ac(a \u2227 \u00acb) \u2194 (a \u2192 b) :=\n\u27e8\u03bb h ha, h.decidable_imp_symm $ and.intro ha, \u03bb h \u27e8ha, hb\u27e9, hb $ h ha\u27e9\n\ntheorem not_and_not_right : \u00ac(a \u2227 \u00acb) \u2194 (a \u2192 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 \u2194 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 \u2194 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 \u2194 a`.\n(This is sometimes taken as an alternate definition of decidability.) -/\ndef decidable_of_bool : \u2200 (b : bool) (h : b \u2194 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 : \u00ac a \u2228 \u00ac b) : \u00ac (a \u2227 b)\n| \u27e8ha, hb\u27e9 := or.elim h (absurd ha) (absurd hb)\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_and_distrib [decidable a] : \u00ac (a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\n\u27e8\u03bb h, if ha : a then or.inr (\u03bb hb, h \u27e8ha, hb\u27e9) else or.inl ha, not_and_of_not_or_not\u27e9\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_and_distrib' [decidable b] : \u00ac (a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\n\u27e8\u03bb h, if hb : b then or.inl (\u03bb ha, h \u27e8ha, hb\u27e9) else or.inr hb, not_and_of_not_or_not\u27e9\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 : \u00ac (a \u2227 b) \u2194 \u00aca \u2228 \u00acb := decidable.not_and_distrib\n\n@[simp] theorem not_and : \u00ac (a \u2227 b) \u2194 (a \u2192 \u00ac b) := and_imp\n\ntheorem not_and' : \u00ac (a \u2227 b) \u2194 b \u2192 \u00aca :=\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 : \u00ac (a \u2228 b) \u2194 \u00ac a \u2227 \u00ac b :=\n\u27e8\u03bb h, \u27e8\u03bb ha, h (or.inl ha), \u03bb hb, h (or.inr hb)\u27e9,\n \u03bb \u27e8h\u2081, h\u2082\u27e9 h, or.elim h h\u2081 h\u2082\u27e9\n\n-- See Note [decidable namespace]\nprotected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a \u2228 b \u2194 \u00ac (\u00aca \u2227 \u00acb) :=\nby rw [\u2190 not_or_distrib, decidable.not_not]\n\ntheorem or_iff_not_and_not : a \u2228 b \u2194 \u00ac (\u00aca \u2227 \u00acb) := 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 \u2227 b \u2194 \u00ac (\u00ac a \u2228 \u00ac b) :=\nby rw [\u2190 decidable.not_and_distrib, decidable.not_not]\n\ntheorem and_iff_not_or_not : a \u2227 b \u2194 \u00ac (\u00ac a \u2228 \u00ac b) := decidable.and_iff_not_or_not\n\nend propositional\n\n/-! ### Declarations about equality -/\n\nsection equality\nvariables {\u03b1 : Sort*} {a b : \u03b1}\n\n@[simp] theorem heq_iff_eq : a == b \u2194 a = b :=\n\u27e8eq_of_heq, heq_of_eq\u27e9\n\ntheorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq :=\nhave p = q, from propext \u27e8\u03bb _, hq, \u03bb _, hp\u27e9,\nby subst q; refl\n\ntheorem ne_of_mem_of_not_mem {\u03b1 \u03b2} [has_mem \u03b1 \u03b2] {s : \u03b2} {a b : \u03b1}\n  (h : a \u2208 s) : b \u2209 s \u2192 a \u2260 b :=\nmt $ \u03bb e, e \u25b8 h\n\nlemma ne_of_apply_ne {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) {x y : \u03b1} (h : f x \u2260 f y) : x \u2260 y :=\n\u03bb (w : x = y), h (congr_arg f w)\n\ntheorem eq_equivalence : equivalence (@eq \u03b1) :=\n\u27e8eq.refl, @eq.symm _, @eq.trans _\u27e9\n\n/-- Transport through trivial families is the identity. -/\n@[simp]\nlemma eq_rec_constant {\u03b1 : Sort*} {a a' : \u03b1} {\u03b2 : Sort*} (y : \u03b2) (h : a = a') :\n  (@eq.rec \u03b1 a (\u03bb a, \u03b2) y a' h) = y :=\nby { cases h, refl, }\n\n@[simp]\nlemma eq_mp_eq_cast {\u03b1 \u03b2 : Sort*} (h : \u03b1 = \u03b2) : eq.mp h = cast h := rfl\n\n@[simp]\nlemma eq_mpr_eq_cast {\u03b1 \u03b2 : Sort*} (h : \u03b1 = \u03b2) : eq.mpr h = cast h.symm := rfl\n\n@[simp]\nlemma cast_cast : \u2200 {\u03b1 \u03b2 \u03b3 : Sort*} (ha : \u03b1 = \u03b2) (hb : \u03b2 = \u03b3) (a : \u03b1),\n  cast hb (cast ha a) = cast (ha.trans hb) a\n| _ _ _ rfl rfl a := rfl\n\n@[simp] lemma congr_refl_left {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) {a b : \u03b1} (h : a = b) :\n  congr (eq.refl f) h = congr_arg f h :=\nrfl\n\n@[simp] lemma congr_refl_right {\u03b1 \u03b2 : Sort*} {f g : \u03b1 \u2192 \u03b2} (h : f = g) (a : \u03b1) :\n  congr h (eq.refl a) = congr_fun h a :=\nrfl\n\n@[simp] lemma congr_arg_refl {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n  congr_arg f (eq.refl a) = eq.refl (f a) :=\nrfl\n\n@[simp] lemma congr_fun_rfl {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n  congr_fun (eq.refl f) a = eq.refl (f a) :=\nrfl\n\n@[simp] lemma congr_fun_congr_arg {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) {a a' : \u03b1} (p : a = a') (b : \u03b2) :\n  congr_fun (congr_arg f p) b = congr_arg (\u03bb a, f a b) p :=\nrfl\n\nlemma heq_of_cast_eq :\n  \u2200 {\u03b1 \u03b2 : Sort*} {a : \u03b1} {a' : \u03b2} (e : \u03b1 = \u03b2) (h\u2082 : cast e a = a'), a == a'\n| \u03b1 ._ a a' rfl h := eq.rec_on h (heq.refl _)\n\nlemma cast_eq_iff_heq {\u03b1 \u03b2 : Sort*} {a : \u03b1} {a' : \u03b2} {e : \u03b1 = \u03b2} : cast e a = a' \u2194 a == a' :=\n\u27e8heq_of_cast_eq _, \u03bb h, by cases h; refl\u27e9\n\nlemma rec_heq_of_heq {\u03b2} {C : \u03b1 \u2192 Sort*} {x : C a} {y : \u03b2} (eq : a = b) (h : x == y) :\n  @eq.rec \u03b1 a C x b eq == y :=\nby subst eq; exact h\n\nprotected lemma eq.congr {x\u2081 x\u2082 y\u2081 y\u2082 : \u03b1} (h\u2081 : x\u2081 = y\u2081) (h\u2082 : x\u2082 = y\u2082) :\n  (x\u2081 = x\u2082) \u2194 (y\u2081 = y\u2082) :=\nby { subst h\u2081, subst h\u2082 }\n\nlemma eq.congr_left {x y z : \u03b1} (h : x = y) : x = z \u2194 y = z := by rw [h]\nlemma eq.congr_right {x y z : \u03b1} (h : x = y) : z = x \u2194 z = y := by rw [h]\n\nlemma congr_arg2 {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) {x x' : \u03b1} {y y' : \u03b2}\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 {\u03b1 : Sort*} {\u03b2 : Sort*} {p q : \u03b1 \u2192 Prop} {b : Prop}\n\nlemma forall_imp (h : \u2200 a, p a \u2192 q a) : (\u2200 a, p a) \u2192 \u2200 a, q a :=\n\u03bb h' a, h a (h' a)\n\nlemma forall\u2082_congr {p q : \u03b1 \u2192 \u03b2 \u2192 Prop} (h : \u2200 a b, p a b \u2194 q a b) :\n  (\u2200 a b, p a b) \u2194 (\u2200 a b, q a b) :=\nforall_congr (\u03bb a, forall_congr (h a))\n\nlemma forall\u2083_congr {\u03b3 : Sort*} {p q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop}\n  (h : \u2200 a b c, p a b c \u2194 q a b c) :\n  (\u2200 a b c, p a b c) \u2194 (\u2200 a b c, q a b c) :=\nforall_congr (\u03bb a, forall\u2082_congr (h a))\n\nlemma forall\u2084_congr {\u03b3 \u03b4 : Sort*} {p q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop}\n  (h : \u2200 a b c d, p a b c d \u2194 q a b c d) :\n  (\u2200 a b c d, p a b c d) \u2194 (\u2200 a b c d, q a b c d) :=\nforall_congr (\u03bb a, forall\u2083_congr (h a))\n\nlemma Exists.imp (h : \u2200 a, (p a \u2192 q a)) (p : \u2203 a, p a) : \u2203 a, q a := exists_imp_exists h p\n\nlemma exists_imp_exists' {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2) (hpq : \u2200 a, p a \u2192 q (f a))\n  (hp : \u2203 a, p a) : \u2203 b, q b :=\nexists.elim hp (\u03bb a hp', \u27e8_, hpq _ hp'\u27e9)\n\nlemma exists\u2082_congr {p q : \u03b1 \u2192 \u03b2 \u2192 Prop} (h : \u2200 a b, p a b \u2194 q a b) :\n  (\u2203 a b, p a b) \u2194 (\u2203 a b, q a b) :=\nexists_congr (\u03bb a, exists_congr (h a))\n\nlemma exists\u2083_congr {\u03b3 : Sort*} {p q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop}\n  (h : \u2200 a b c, p a b c \u2194 q a b c) :\n  (\u2203 a b c, p a b c) \u2194 (\u2203 a b c, q a b c) :=\nexists_congr (\u03bb a, exists\u2082_congr (h a))\n\nlemma exists\u2084_congr {\u03b3 \u03b4 : Sort*} {p q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop}\n  (h : \u2200 a b c d, p a b c d \u2194 q a b c d) :\n  (\u2203 a b c d, p a b c d) \u2194 (\u2203 a b c d, q a b c d) :=\nexists_congr (\u03bb a, exists\u2083_congr (h a))\n\ntheorem forall_swap {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2200 x y, p x y) \u2194 \u2200 y x, p x y :=\n\u27e8swap, swap\u27e9\n\n/-- We intentionally restrict the type of `\u03b1` in this lemma so that this is a safer to use in simp\nthan `forall_swap`. -/\nlemma imp_forall_iff {\u03b1 : Type*} {p : Prop} {q : \u03b1 \u2192 Prop} : (p \u2192 \u2200 x, q x) \u2194 (\u2200 x, p \u2192 q x) :=\nforall_swap\n\ntheorem exists_swap {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 x y, p x y) \u2194 \u2203 y x, p x y :=\n\u27e8\u03bb \u27e8x, y, h\u27e9, \u27e8y, x, h\u27e9, \u03bb \u27e8y, x, h\u27e9, \u27e8x, y, h\u27e9\u27e9\n\n@[simp] theorem forall_exists_index {q : (\u2203 x, p x) \u2192 Prop} :\n  (\u2200 h, q h) \u2194 \u2200 x (h : p x), q \u27e8x, h\u27e9 :=\n\u27e8\u03bb h x hpx, h \u27e8x, hpx\u27e9, \u03bb h \u27e8x, hpx\u27e9, h x hpx\u27e9\n\ntheorem exists_imp_distrib : ((\u2203 x, p x) \u2192 b) \u2194 \u2200 x, p x \u2192 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 : \u03b1 \u2192 Prop} (P : \u2203 a, p a) : \u03b1 := classical.some P\n\n/--\nShow that an element extracted from `P : \u2203 a, p a` using `P.some` satisfies `p`.\n-/\nlemma Exists.some_spec {p : \u03b1 \u2192 Prop} (P : \u2203 a, p a) : p (P.some) := classical.some_spec P\n\n--theorem forall_not_of_not_exists (h : \u00ac \u2203 x, p x) : \u2200 x, \u00ac p x :=\n--forall_imp_of_exists_imp h\n\ntheorem not_exists_of_forall_not (h : \u2200 x, \u00ac p x) : \u00ac \u2203 x, p x :=\nexists_imp_distrib.2 h\n\n@[simp] theorem not_exists : (\u00ac \u2203 x, p x) \u2194 \u2200 x, \u00ac p x :=\nexists_imp_distrib\n\ntheorem not_forall_of_exists_not : (\u2203 x, \u00ac p x) \u2192 \u00ac \u2200 x, p x\n| \u27e8x, hn\u27e9 h := hn (h x)\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_forall {p : \u03b1 \u2192 Prop}\n  [decidable (\u2203 x, \u00ac p x)] [\u2200 x, decidable (p x)] : (\u00ac \u2200 x, p x) \u2194 \u2203 x, \u00ac p x :=\n\u27e8not.decidable_imp_symm $ \u03bb nx x, nx.decidable_imp_symm $ \u03bb h, \u27e8x, h\u27e9,\n not_forall_of_exists_not\u27e9\n\n@[simp] theorem not_forall {p : \u03b1 \u2192 Prop} : (\u00ac \u2200 x, p x) \u2194 \u2203 x, \u00ac p x := decidable.not_forall\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_forall_not [decidable (\u2203 x, p x)] :\n  (\u00ac \u2200 x, \u00ac p x) \u2194 \u2203 x, p x :=\n(@decidable.not_iff_comm _ _ _ (decidable_of_iff (\u00ac \u2203 x, p x) not_exists)).1 not_exists\n\ntheorem not_forall_not : (\u00ac \u2200 x, \u00ac p x) \u2194 \u2203 x, p x := decidable.not_forall_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_exists_not [\u2200 x, decidable (p x)] : (\u00ac \u2203 x, \u00ac p x) \u2194 \u2200 x, p x :=\nby simp [decidable.not_not]\n\n@[simp] theorem not_exists_not : (\u00ac \u2203 x, \u00ac p x) \u2194 \u2200 x, p x := decidable.not_exists_not\n\ntheorem forall_imp_iff_exists_imp [ha : nonempty \u03b1] : ((\u2200 x, p x) \u2192 b) \u2194 \u2203 x, p x \u2192 b :=\nlet \u27e8a\u27e9 := ha in\n\u27e8\u03bb h, not_forall_not.1 $ \u03bb h', classical.by_cases (\u03bb hb : b, h' a $ \u03bb _, hb)\n  (\u03bb hb, hb $ h $ \u03bb x, (not_imp.1 (h' x)).1), \u03bb \u27e8x, hx\u27e9 h, hx (h x)\u27e9\n\n-- TODO: duplicate of a lemma in core\ntheorem forall_true_iff : (\u03b1 \u2192 true) \u2194 true :=\nimplies_true_iff \u03b1\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 : \u2200 a, p a \u2194 true) : (\u2200 a, p a) \u2194 true :=\niff_true_intro (\u03bb _, of_iff_true (h _))\n\n@[simp] theorem forall_2_true_iff {\u03b2 : \u03b1 \u2192 Sort*} : (\u2200 a, \u03b2 a \u2192 true) \u2194 true :=\nforall_true_iff' $ \u03bb _, forall_true_iff\n\n@[simp] theorem forall_3_true_iff {\u03b2 : \u03b1 \u2192 Sort*} {\u03b3 : \u03a0 a, \u03b2 a \u2192 Sort*} :\n  (\u2200 a (b : \u03b2 a), \u03b3 a b \u2192 true) \u2194 true :=\nforall_true_iff' $ \u03bb _, forall_2_true_iff\n\nlemma exists_unique.exists {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} (h : \u2203! x, p x) : \u2203 x, p x :=\nexists.elim h (\u03bb x hx, \u27e8x, and.left hx\u27e9)\n\n@[simp] lemma exists_unique_iff_exists {\u03b1 : Sort*} [subsingleton \u03b1] {p : \u03b1 \u2192 Prop} :\n  (\u2203! x, p x) \u2194 \u2203 x, p x :=\n\u27e8\u03bb h, h.exists, Exists.imp $ \u03bb x hx, \u27e8hx, \u03bb y _, subsingleton.elim y x\u27e9\u27e9\n\n@[simp] theorem forall_const (\u03b1 : Sort*) [i : nonempty \u03b1] : (\u03b1 \u2192 b) \u2194 b :=\n\u27e8i.elim, \u03bb hb x, hb\u27e9\n\n@[simp] theorem exists_const (\u03b1 : Sort*) [i : nonempty \u03b1] : (\u2203 x : \u03b1, b) \u2194 b :=\n\u27e8\u03bb \u27e8x, h\u27e9, h, i.elim exists.intro\u27e9\n\ntheorem exists_unique_const (\u03b1 : Sort*) [i : nonempty \u03b1] [subsingleton \u03b1] :\n  (\u2203! x : \u03b1, b) \u2194 b :=\nby simp\n\ntheorem forall_and_distrib : (\u2200 x, p x \u2227 q x) \u2194 (\u2200 x, p x) \u2227 (\u2200 x, q x) :=\n\u27e8\u03bb h, \u27e8\u03bb x, (h x).left, \u03bb x, (h x).right\u27e9, \u03bb \u27e8h\u2081, h\u2082\u27e9 x, \u27e8h\u2081 x, h\u2082 x\u27e9\u27e9\n\ntheorem exists_or_distrib : (\u2203 x, p x \u2228 q x) \u2194 (\u2203 x, p x) \u2228 (\u2203 x, q x) :=\n\u27e8\u03bb \u27e8x, hpq\u27e9, hpq.elim (\u03bb hpx, or.inl \u27e8x, hpx\u27e9) (\u03bb hqx, or.inr \u27e8x, hqx\u27e9),\n \u03bb hepq, hepq.elim (\u03bb \u27e8x, hpx\u27e9, \u27e8x, or.inl hpx\u27e9) (\u03bb \u27e8x, hqx\u27e9, \u27e8x, or.inr hqx\u27e9)\u27e9\n\n@[simp] theorem exists_and_distrib_left {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2203x, q \u2227 p x) \u2194 q \u2227 (\u2203x, p x) :=\n\u27e8\u03bb \u27e8x, hq, hp\u27e9, \u27e8hq, x, hp\u27e9, \u03bb \u27e8hq, x, hp\u27e9, \u27e8x, hq, hp\u27e9\u27e9\n\n@[simp] theorem exists_and_distrib_right {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2203x, p x \u2227 q) \u2194 (\u2203x, p x) \u2227 q :=\nby simp [and_comm]\n\n@[simp] theorem forall_eq {a' : \u03b1} : (\u2200a, a = a' \u2192 p a) \u2194 p a' :=\n\u27e8\u03bb h, h a' rfl, \u03bb h a e, e.symm \u25b8 h\u27e9\n\n@[simp] theorem forall_eq' {a' : \u03b1} : (\u2200a, a' = a \u2192 p a) \u2194 p a' :=\nby simp [@eq_comm _ a']\n\ntheorem and_forall_ne (a : \u03b1) : (p a \u2227 \u2200 b \u2260 a, p b) \u2194 \u2200 b, p b :=\nby simp only [\u2190 @forall_eq _ p a, \u2190 forall_and_distrib, \u2190 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' : \u03b1} : (\u2200 a, a = a' \u2228 q a \u2192 p a) \u2194 p a' \u2227 \u2200 a, q a \u2192 p a :=\nby simp only [or_imp_distrib, forall_and_distrib, forall_eq]\n\ntheorem exists_eq {a' : \u03b1} : \u2203 a, a = a' := \u27e8_, rfl\u27e9\n\n@[simp] theorem exists_eq' {a' : \u03b1} : \u2203 a, a' = a := \u27e8_, rfl\u27e9\n\n@[simp] theorem exists_unique_eq {a' : \u03b1} : \u2203! a, a = a' :=\nby simp only [eq_comm, exists_unique, and_self, forall_eq', exists_eq']\n\n@[simp] theorem exists_unique_eq' {a' : \u03b1} : \u2203! a, a' = a :=\nby simp only [exists_unique, and_self, forall_eq', exists_eq']\n\n@[simp] theorem exists_eq_left {a' : \u03b1} : (\u2203 a, a = a' \u2227 p a) \u2194 p a' :=\n\u27e8\u03bb \u27e8a, e, h\u27e9, e \u25b8 h, \u03bb h, \u27e8_, rfl, h\u27e9\u27e9\n\n@[simp] theorem exists_eq_right {a' : \u03b1} : (\u2203 a, p a \u2227 a = a') \u2194 p a' :=\n(exists_congr $ by exact \u03bb a, and.comm).trans exists_eq_left\n\n@[simp] theorem exists_eq_right_right {a' : \u03b1} :\n  (\u2203 (a : \u03b1), p a \u2227 b \u2227 a = a') \u2194 p a' \u2227 b :=\n\u27e8\u03bb \u27e8_, hp, hq, rfl\u27e9, \u27e8hp, hq\u27e9, \u03bb \u27e8hp, hq\u27e9, \u27e8a', hp, hq, rfl\u27e9\u27e9\n\n@[simp] theorem exists_eq_right_right' {a' : \u03b1} :\n  (\u2203 (a : \u03b1), p a \u2227 b \u2227 a' = a) \u2194 p a' \u2227 b :=\n\u27e8\u03bb \u27e8_, hp, hq, rfl\u27e9, \u27e8hp, hq\u27e9, \u03bb \u27e8hp, hq\u27e9, \u27e8a', hp, hq, rfl\u27e9\u27e9\n\n@[simp] theorem exists_apply_eq_apply (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) : \u2203 a, f a = f a' := \u27e8a', rfl\u27e9\n\n@[simp] theorem exists_apply_eq_apply' (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) : \u2203 a, f a' = f a := \u27e8a', rfl\u27e9\n\n@[simp] theorem exists_exists_and_eq_and {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} :\n  (\u2203 b, (\u2203 a, p a \u2227 f a = b) \u2227 q b) \u2194 \u2203 a, p a \u2227 q (f a) :=\n\u27e8\u03bb \u27e8b, \u27e8a, ha, hab\u27e9, hb\u27e9, \u27e8a, ha, hab.symm \u25b8 hb\u27e9, \u03bb \u27e8a, hp, hq\u27e9, \u27e8f a, \u27e8a, hp, rfl\u27e9, hq\u27e9\u27e9\n\n@[simp] theorem exists_exists_eq_and {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2203 b, (\u2203 a, f a = b) \u2227 p b) \u2194 \u2203 a, p (f a) :=\n\u27e8\u03bb \u27e8b, \u27e8a, ha\u27e9, hb\u27e9, \u27e8a, ha.symm \u25b8 hb\u27e9, \u03bb \u27e8a, ha\u27e9, \u27e8f a, \u27e8a, rfl\u27e9, ha\u27e9\u27e9\n\n@[simp] lemma exists_or_eq_left (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), x = y \u2228 p x :=\n\u27e8y, or.inl rfl\u27e9\n\n@[simp] lemma exists_or_eq_right (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), p x \u2228 x = y :=\n\u27e8y, or.inr rfl\u27e9\n\n@[simp] lemma exists_or_eq_left' (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), y = x \u2228 p x :=\n\u27e8y, or.inl rfl\u27e9\n\n@[simp] lemma exists_or_eq_right' (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), p x \u2228 y = x :=\n\u27e8y, or.inr rfl\u27e9\n\n@[simp] theorem forall_apply_eq_imp_iff {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 a, \u2200 b, f a = b \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\n\u27e8\u03bb h a, h a (f a) rfl, \u03bb h a b hab, hab \u25b8 h a\u27e9\n\n@[simp] theorem forall_apply_eq_imp_iff' {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 b, \u2200 a, f a = b \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\nby { rw forall_swap, simp }\n\n@[simp] theorem forall_eq_apply_imp_iff {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 a, \u2200 b, b = f a \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\nby simp [@eq_comm _ _ (f _)]\n\n@[simp] theorem forall_eq_apply_imp_iff' {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 b, \u2200 a, b = f a \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\nby { rw forall_swap, simp }\n\n@[simp] theorem forall_apply_eq_imp_iff\u2082 {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} :\n  (\u2200 b, \u2200 a, p a \u2192 f a = b \u2192 q b) \u2194 \u2200 a, p a \u2192 q (f a) :=\n\u27e8\u03bb h a ha, h (f a) a ha rfl, \u03bb h b a ha hb, hb \u25b8 h a ha\u27e9\n\n@[simp] theorem exists_eq_left' {a' : \u03b1} : (\u2203 a, a' = a \u2227 p a) \u2194 p a' :=\nby simp [@eq_comm _ a']\n\n@[simp] theorem exists_eq_right' {a' : \u03b1} : (\u2203 a, p a \u2227 a' = a) \u2194 p a' :=\nby simp [@eq_comm _ a']\n\ntheorem exists_comm {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 a b, p a b) \u2194 \u2203 b a, p a b :=\n\u27e8\u03bb \u27e8a, b, h\u27e9, \u27e8b, a, h\u27e9, \u03bb \u27e8b, a, h\u27e9, \u27e8a, b, h\u27e9\u27e9\n\ntheorem and.exists {p q : Prop} {f : p \u2227 q \u2192 Prop} : (\u2203 h, f h) \u2194 \u2203 hp hq, f \u27e8hp, hq\u27e9 :=\n\u27e8\u03bb \u27e8h, H\u27e9, \u27e8h.1, h.2, H\u27e9, \u03bb \u27e8hp, hq, H\u27e9, \u27e8\u27e8hp, hq\u27e9, H\u27e9\u27e9\n\ntheorem forall_or_of_or_forall (h : b \u2228 \u2200x, p x) (x) : b \u2228 p x :=\nh.imp_right $ \u03bb h\u2082, h\u2082 x\n\n-- See Note [decidable namespace]\nprotected theorem decidable.forall_or_distrib_left {q : Prop} {p : \u03b1 \u2192 Prop} [decidable q] :\n  (\u2200x, q \u2228 p x) \u2194 q \u2228 (\u2200x, p x) :=\n\u27e8\u03bb h, if hq : q then or.inl hq else or.inr $ \u03bb x, (h x).resolve_left hq,\n  forall_or_of_or_forall\u27e9\n\ntheorem forall_or_distrib_left {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2200x, q \u2228 p x) \u2194 q \u2228 (\u2200x, p x) := decidable.forall_or_distrib_left\n\n-- See Note [decidable namespace]\nprotected theorem decidable.forall_or_distrib_right {q : Prop} {p : \u03b1 \u2192 Prop} [decidable q] :\n  (\u2200x, p x \u2228 q) \u2194 (\u2200x, p x) \u2228 q :=\nby simp [or_comm, decidable.forall_or_distrib_left]\n\ntheorem forall_or_distrib_right {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2200x, p x \u2228 q) \u2194 (\u2200x, p x) \u2228 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  {\u03b1 \u03b2 : Type*} {f : \u03b1 \u2192 \u03b2} (h : function.surjective f) {P : \u03b2 \u2192 Prop} :\n  (\u2200 a, P (f a)) \u2194 \u2200 b, P b :=\n\u27e8\u03bb ha b, by cases h b with a hab; rw \u2190hab; exact ha a, \u03bb hb a, hb $ f a\u27e9\n\n@[simp] theorem exists_prop {p q : Prop} : (\u2203 h : p, q) \u2194 p \u2227 q :=\n\u27e8\u03bb \u27e8h\u2081, h\u2082\u27e9, \u27e8h\u2081, h\u2082\u27e9, \u03bb \u27e8h\u2081, h\u2082\u27e9, \u27e8h\u2081, h\u2082\u27e9\u27e9\n\ntheorem exists_unique_prop {p q : Prop} : (\u2203! h : p, q) \u2194 p \u2227 q :=\nby simp\n\n@[simp] theorem exists_false : \u00ac (\u2203a:\u03b1, false) := assume \u27e8a, h\u27e9, h\n\n@[simp] lemma exists_unique_false : \u00ac (\u2203! (a : \u03b1), false) := assume \u27e8a, h, h'\u27e9, h\n\ntheorem Exists.fst {p : b \u2192 Prop} : Exists p \u2192 b\n| \u27e8h, _\u27e9 := h\n\ntheorem Exists.snd {p : b \u2192 Prop} : \u2200 h : Exists p, p h.fst\n| \u27e8_, h\u27e9 := h\n\ntheorem forall_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2200 h' : p, q h') \u2194 q h :=\n@forall_const (q h) p \u27e8h\u27e9\n\ntheorem exists_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2203 h' : p, q h') \u2194 q h :=\n@exists_const (q h) p \u27e8h\u27e9\n\ntheorem exists_unique_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2203! h' : p, q h') \u2194 q h :=\n@exists_unique_const (q h) p \u27e8h\u27e9 _\n\ntheorem forall_prop_of_false {p : Prop} {q : p \u2192 Prop} (hn : \u00ac p) :\n  (\u2200 h' : p, q h') \u2194 true :=\niff_true_intro $ \u03bb h, hn.elim h\n\ntheorem exists_prop_of_false {p : Prop} {q : p \u2192 Prop} : \u00ac p \u2192 \u00ac (\u2203 h' : p, q h') :=\nmt Exists.fst\n\n@[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : Exists q \u2194 \u2203 h : p', q' (hp.2 h) :=\n\u27e8\u03bb \u27e8_, _\u27e9, \u27e8hp.1 \u2039_\u203a, (hq _).1 \u2039_\u203a\u27e9, \u03bb \u27e8_, _\u27e9, \u27e8_, (hq _).2 \u2039_\u203a\u27e9\u27e9\n\n@[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : Exists q = \u2203 h : p', q' (hp.2 h) :=\npropext (exists_prop_congr hq _)\n\n@[simp] lemma exists_true_left (p : true \u2192 Prop) : (\u2203 x, p x) \u2194 p true.intro :=\nexists_prop_of_true _\n\n@[simp] lemma exists_false_left (p : false \u2192 Prop) : \u00ac \u2203 x, p x :=\nexists_prop_of_false not_false\n\nlemma exists_unique.unique {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} (h : \u2203! x, p x)\n  {y\u2081 y\u2082 : \u03b1} (py\u2081 : p y\u2081) (py\u2082 : p y\u2082) : y\u2081 = y\u2082 :=\nunique_of_exists_unique h py\u2081 py\u2082\n\n@[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : (\u2200 h, q h) \u2194 \u2200 h : p', q' (hp.2 h) :=\n\u27e8\u03bb h1 h2, (hq _).1 (h1 (hp.2 _)), \u03bb h1 h2, (hq _).2 (h1 (hp.1 h2))\u27e9\n\n@[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : (\u2200 h, q h) = \u2200 h : p', q' (hp.2 h) :=\npropext (forall_prop_congr hq _)\n\n@[simp] lemma forall_true_left (p : true \u2192 Prop) : (\u2200 x, p x) \u2194 p true.intro :=\nforall_prop_of_true _\n\n@[simp] lemma forall_false_left (p : false \u2192 Prop) : (\u2200 x, p x) \u2194 true :=\nforall_prop_of_false not_false\n\nlemma exists_unique.elim2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} [\u2200 x, subsingleton (p x)]\n  {q : \u03a0 x (h : p x), Prop} {b : Prop} (h\u2082 : \u2203! x (h : p x), q x h)\n  (h\u2081 : \u2200 x (h : p x), q x h \u2192 (\u2200 y (hy : p y), q y hy \u2192 y = x) \u2192 b) : b :=\nbegin\n  simp only [exists_unique_iff_exists] at h\u2082,\n  apply h\u2082.elim,\n  exact \u03bb x \u27e8hxp, hxq\u27e9 H, h\u2081 x hxp hxq (\u03bb y hyp hyq, H y \u27e8hyp, hyq\u27e9)\nend\n\nlemma exists_unique.intro2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} [\u2200 x, subsingleton (p x)]\n  {q : \u03a0 (x : \u03b1) (h : p x), Prop} (w : \u03b1) (hp : p w) (hq : q w hp)\n  (H : \u2200 y (hy : p y), q y hy \u2192 y = w) :\n  \u2203! x (hx : p x), q x hx :=\nbegin\n  simp only [exists_unique_iff_exists],\n  exact exists_unique.intro w \u27e8hp, hq\u27e9 (\u03bb y \u27e8hyp, hyq\u27e9, H y hyp hyq)\nend\n\nlemma exists_unique.exists2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} {q : \u03a0 (x : \u03b1) (h : p x), Prop}\n  (h : \u2203! x (hx : p x), q x hx) :\n  \u2203 x (hx : p x), q x hx :=\nh.exists.imp (\u03bb x hx, hx.exists)\n\nlemma exists_unique.unique2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} [\u2200 x, subsingleton (p x)]\n  {q : \u03a0 (x : \u03b1) (hx : p x), Prop} (h : \u2203! x (hx : p x), q x hx)\n  {y\u2081 y\u2082 : \u03b1} (hpy\u2081 : p y\u2081) (hqy\u2081 : q y\u2081 hpy\u2081)\n  (hpy\u2082 : p y\u2082) (hqy\u2082 : q y\u2082 hpy\u2082) : y\u2081 = y\u2082 :=\nbegin\n  simp only [exists_unique_iff_exists] at h,\n  exact h.unique \u27e8hpy\u2081, hqy\u2081\u27e9 \u27e8hpy\u2082, hqy\u2082\u27e9\nend\n\nend quantifiers\n\n/-! ### Classical lemmas -/\n\nnamespace classical\nvariables {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop}\n\ntheorem cases {p : Prop \u2192 Prop} (h1 : p true) (h2 : p false) : \u2200a, 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 : \u03b1 \u2192 Prop) : decidable_pred p :=\nby apply_instance\n/-- Any relation `p` is decidable classically. -/\nnoncomputable def dec_rel (p : \u03b1 \u2192 \u03b1 \u2192 Prop) : decidable_rel p :=\nby apply_instance\n/-- Any type `\u03b1` has decidable equality classically. -/\nnoncomputable def dec_eq (\u03b1 : Sort*) : decidable_eq \u03b1 :=\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 : \u2200 a, p a \u2192 C) : C :=\nif h : \u2203 a, p a then H (classical.some h) (classical.some_spec h) else H0\n\nlemma some_spec2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} {h : \u2203a, p a}\n  (q : \u03b1 \u2192 Prop) (hpq : \u2200a, p a \u2192 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 {\u03b1 : Type*} {P : \u03b1 \u2192 Prop} (h : \u2203 x, P x) : {x // P x} :=\n\u27e8classical.some h, classical.some_spec h\u27e9\n\n/-- A version of `by_contradiction` that uses types instead of propositions. -/\nprotected noncomputable def by_contradiction' {\u03b1 : Sort*} (H : \u00ac (\u03b1 \u2192 false)) : \u03b1 :=\nclassical.choice $ peirce _ false $ \u03bb h, (H $ \u03bb a, h \u27e8a\u27e9).elim\n\n/-- `classical.by_contradiction'` is equivalent to lean's axiom `classical.choice`. -/\ndef choice_of_by_contradiction' {\u03b1 : Sort*} (contra : \u00ac (\u03b1 \u2192 false) \u2192 \u03b1) : nonempty \u03b1 \u2192 \u03b1 :=\n\u03bb 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 {\u03b1} {p : \u03b1 \u2192 Prop} (h : \u2203 a, p a) {C : Sort u} (H : \u2200 a, p a \u2192 C) : C :=\nH (classical.some h) (classical.some_spec h)\n\n/-! ### Declarations about bounded quantifiers -/\n\nsection bounded_quantifiers\nvariables {\u03b1 : Sort*} {r p q : \u03b1 \u2192 Prop} {P Q : \u2200 x, p x \u2192 Prop} {b : Prop}\n\ntheorem bex_def : (\u2203 x (h : p x), q x) \u2194 \u2203 x, p x \u2227 q x :=\n\u27e8\u03bb \u27e8x, px, qx\u27e9, \u27e8x, px, qx\u27e9, \u03bb \u27e8x, px, qx\u27e9, \u27e8x, px, qx\u27e9\u27e9\n\ntheorem bex.elim {b : Prop} : (\u2203 x h, P x h) \u2192 (\u2200 a h, P a h \u2192 b) \u2192 b\n| \u27e8a, h\u2081, h\u2082\u27e9 h' := h' a h\u2081 h\u2082\n\ntheorem bex.intro (a : \u03b1) (h\u2081 : p a) (h\u2082 : P a h\u2081) : \u2203 x (h : p x), P x h :=\n\u27e8a, h\u2081, h\u2082\u27e9\n\ntheorem ball_congr (H : \u2200 x h, P x h \u2194 Q x h) :\n  (\u2200 x h, P x h) \u2194 (\u2200 x h, Q x h) :=\nforall_congr $ \u03bb x, forall_congr (H x)\n\ntheorem bex_congr (H : \u2200 x h, P x h \u2194 Q x h) :\n  (\u2203 x h, P x h) \u2194 (\u2203 x h, Q x h) :=\nexists_congr $ \u03bb x, exists_congr (H x)\n\ntheorem bex_eq_left {a : \u03b1} : (\u2203 x (_ : x = a), p x) \u2194 p a :=\nby simp only [exists_prop, exists_eq_left]\n\ntheorem ball.imp_right (H : \u2200 x h, (P x h \u2192 Q x h))\n  (h\u2081 : \u2200 x h, P x h) (x h) : Q x h :=\nH _ _ $ h\u2081 _ _\n\ntheorem bex.imp_right (H : \u2200 x h, (P x h \u2192 Q x h)) :\n  (\u2203 x h, P x h) \u2192 \u2203 x h, Q x h\n| \u27e8x, h, h'\u27e9 := \u27e8_, _, H _ _ h'\u27e9\n\ntheorem ball.imp_left (H : \u2200 x, p x \u2192 q x)\n  (h\u2081 : \u2200 x, q x \u2192 r x) (x) (h : p x) : r x :=\nh\u2081 _ $ H _ h\n\ntheorem bex.imp_left (H : \u2200 x, p x \u2192 q x) :\n  (\u2203 x (_ : p x), r x) \u2192 \u2203 x (_ : q x), r x\n| \u27e8x, hp, hr\u27e9 := \u27e8x, H _ hp, hr\u27e9\n\ntheorem ball_of_forall (h : \u2200 x, p x) (x) : p x :=\nh x\n\ntheorem forall_of_ball (H : \u2200 x, p x) (h : \u2200 x, p x \u2192 q x) (x) : q x :=\nh x $ H x\n\ntheorem bex_of_exists (H : \u2200 x, p x) : (\u2203 x, q x) \u2192 \u2203 x (_ : p x), q x\n| \u27e8x, hq\u27e9 := \u27e8x, H x, hq\u27e9\n\ntheorem exists_of_bex : (\u2203 x (_ : p x), q x) \u2192 \u2203 x, q x\n| \u27e8x, _, hq\u27e9 := \u27e8x, hq\u27e9\n\n@[simp] theorem bex_imp_distrib : ((\u2203 x h, P x h) \u2192 b) \u2194 (\u2200 x h, P x h \u2192 b) :=\nby simp\n\ntheorem not_bex : (\u00ac \u2203 x h, P x h) \u2194 \u2200 x h, \u00ac P x h :=\nbex_imp_distrib\n\ntheorem not_ball_of_bex_not : (\u2203 x h, \u00ac P x h) \u2192 \u00ac \u2200 x h, P x h\n| \u27e8x, h, hp\u27e9 al := hp $ al x h\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_ball [decidable (\u2203 x h, \u00ac P x h)] [\u2200 x h, decidable (P x h)] :\n  (\u00ac \u2200 x h, P x h) \u2194 (\u2203 x h, \u00ac P x h) :=\n\u27e8not.decidable_imp_symm $ \u03bb nx x h, nx.decidable_imp_symm $ \u03bb h', \u27e8x, h, h'\u27e9,\n not_ball_of_bex_not\u27e9\n\ntheorem not_ball : (\u00ac \u2200 x h, P x h) \u2194 (\u2203 x h, \u00ac P x h) := decidable.not_ball\n\ntheorem ball_true_iff (p : \u03b1 \u2192 Prop) : (\u2200 x, p x \u2192 true) \u2194 true :=\niff_true_intro (\u03bb h hrx, trivial)\n\ntheorem ball_and_distrib : (\u2200 x h, P x h \u2227 Q x h) \u2194 (\u2200 x h, P x h) \u2227 (\u2200 x h, Q x h) :=\niff.trans (forall_congr $ \u03bb x, forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib : (\u2203 x h, P x h \u2228 Q x h) \u2194 (\u2203 x h, P x h) \u2228 (\u2203 x h, Q x h) :=\niff.trans (exists_congr $ \u03bb x, exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib : (\u2200 x, p x \u2228 q x \u2192 r x) \u2194 (\u2200 x, p x \u2192 r x) \u2227 (\u2200 x, q x \u2192 r x) :=\niff.trans (forall_congr $ \u03bb x, or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib :\n  (\u2203 x (_ : p x \u2228 q x), r x) \u2194 (\u2203 x (_ : p x), r x) \u2228 (\u2203 x (_ : q x), r x) :=\nby simp only [exists_prop]; exact\niff.trans (exists_congr $ \u03bb x, or_and_distrib_right) exists_or_distrib\n\nend bounded_quantifiers\n\nnamespace classical\nlocal attribute [instance] prop_decidable\n\ntheorem not_ball {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} {P : \u03a0 (x : \u03b1), p x \u2192 Prop} :\n  (\u00ac \u2200 x h, P x h) \u2194 (\u2203 x h, \u00ac P x h) := _root_.not_ball\n\nend classical\n\nlemma ite_eq_iff {\u03b1} {p : Prop} [decidable p] {a b c : \u03b1} :\n  (if p then a else b) = c \u2194 p \u2227 a = c \u2228 \u00acp \u2227 b = c :=\nby by_cases p; simp *\n\n@[simp] lemma ite_eq_left_iff {\u03b1} {p : Prop} [decidable p] {a b : \u03b1} :\n  (if p then a else b) = a \u2194 (\u00acp \u2192 b = a) :=\nby by_cases p; simp *\n\n@[simp] lemma ite_eq_right_iff {\u03b1} {p : Prop} [decidable p] {a b : \u03b1} :\n  (if p then a else b) = b \u2194 (p \u2192 a = b) :=\nby by_cases p; simp *\n\nlemma ite_eq_or_eq {\u03b1} {p : Prop} [decidable p] (a b : \u03b1) :\n  ite p a b = a \u2228 ite p a b = b :=\ndecidable.by_cases (\u03bb h, or.inl (if_pos h)) (\u03bb h, or.inr (if_neg h))\n\n/-! ### Declarations about `nonempty` -/\n\nsection nonempty\nvariables {\u03b1 \u03b2 : Type*} {\u03b3 : \u03b1 \u2192 Type*}\n\nattribute [simp] nonempty_of_inhabited\n\n@[priority 20]\ninstance has_zero.nonempty [has_zero \u03b1] : nonempty \u03b1 := \u27e80\u27e9\n@[priority 20]\ninstance has_one.nonempty [has_one \u03b1] : nonempty \u03b1 := \u27e81\u27e9\n\nlemma exists_true_iff_nonempty {\u03b1 : Sort*} : (\u2203a:\u03b1, true) \u2194 nonempty \u03b1 :=\niff.intro (\u03bb\u27e8a, _\u27e9, \u27e8a\u27e9) (\u03bb\u27e8a\u27e9, \u27e8a, trivial\u27e9)\n\n@[simp] lemma nonempty_Prop {p : Prop} : nonempty p \u2194 p :=\niff.intro (assume \u27e8h\u27e9, h) (assume h, \u27e8h\u27e9)\n\nlemma not_nonempty_iff_imp_false {\u03b1 : Sort*} : \u00ac nonempty \u03b1 \u2194 \u03b1 \u2192 false :=\n\u27e8\u03bb h a, h \u27e8a\u27e9, \u03bb h \u27e8a\u27e9, h a\u27e9\n\n@[simp] lemma nonempty_sigma : nonempty (\u03a3a:\u03b1, \u03b3 a) \u2194 (\u2203a:\u03b1, nonempty (\u03b3 a)) :=\niff.intro (assume \u27e8\u27e8a, c\u27e9\u27e9, \u27e8a, \u27e8c\u27e9\u27e9) (assume \u27e8a, \u27e8c\u27e9\u27e9, \u27e8\u27e8a, c\u27e9\u27e9)\n\n@[simp] lemma nonempty_subtype {\u03b1} {p : \u03b1 \u2192 Prop} : nonempty (subtype p) \u2194 (\u2203a:\u03b1, p a) :=\niff.intro (assume \u27e8\u27e8a, h\u27e9\u27e9, \u27e8a, h\u27e9) (assume \u27e8a, h\u27e9, \u27e8\u27e8a, h\u27e9\u27e9)\n\n@[simp] lemma nonempty_prod : nonempty (\u03b1 \u00d7 \u03b2) \u2194 (nonempty \u03b1 \u2227 nonempty \u03b2) :=\niff.intro (assume \u27e8\u27e8a, b\u27e9\u27e9, \u27e8\u27e8a\u27e9, \u27e8b\u27e9\u27e9) (assume \u27e8\u27e8a\u27e9, \u27e8b\u27e9\u27e9, \u27e8\u27e8a, b\u27e9\u27e9)\n\n@[simp] lemma nonempty_pprod {\u03b1 \u03b2} : nonempty (pprod \u03b1 \u03b2) \u2194 (nonempty \u03b1 \u2227 nonempty \u03b2) :=\niff.intro (assume \u27e8\u27e8a, b\u27e9\u27e9, \u27e8\u27e8a\u27e9, \u27e8b\u27e9\u27e9) (assume \u27e8\u27e8a\u27e9, \u27e8b\u27e9\u27e9, \u27e8\u27e8a, b\u27e9\u27e9)\n\n@[simp] lemma nonempty_sum : nonempty (\u03b1 \u2295 \u03b2) \u2194 (nonempty \u03b1 \u2228 nonempty \u03b2) :=\niff.intro\n  (assume \u27e8h\u27e9, match h with sum.inl a := or.inl \u27e8a\u27e9 | sum.inr b := or.inr \u27e8b\u27e9 end)\n  (assume h, match h with or.inl \u27e8a\u27e9 := \u27e8sum.inl a\u27e9 | or.inr \u27e8b\u27e9 := \u27e8sum.inr b\u27e9 end)\n\n@[simp] lemma nonempty_psum {\u03b1 \u03b2} : nonempty (psum \u03b1 \u03b2) \u2194 (nonempty \u03b1 \u2228 nonempty \u03b2) :=\niff.intro\n  (assume \u27e8h\u27e9, match h with psum.inl a := or.inl \u27e8a\u27e9 | psum.inr b := or.inr \u27e8b\u27e9 end)\n  (assume h, match h with or.inl \u27e8a\u27e9 := \u27e8psum.inl a\u27e9 | or.inr \u27e8b\u27e9 := \u27e8psum.inr b\u27e9 end)\n\n@[simp] lemma nonempty_psigma {\u03b1} {\u03b2 : \u03b1 \u2192 Sort*} : nonempty (psigma \u03b2) \u2194 (\u2203a:\u03b1, nonempty (\u03b2 a)) :=\niff.intro (assume \u27e8\u27e8a, c\u27e9\u27e9, \u27e8a, \u27e8c\u27e9\u27e9) (assume \u27e8a, \u27e8c\u27e9\u27e9, \u27e8\u27e8a, c\u27e9\u27e9)\n\n@[simp] lemma nonempty_empty : \u00ac nonempty empty :=\nassume \u27e8h\u27e9, h.elim\n\n@[simp] lemma nonempty_ulift : nonempty (ulift \u03b1) \u2194 nonempty \u03b1 :=\niff.intro (assume \u27e8\u27e8a\u27e9\u27e9, \u27e8a\u27e9) (assume \u27e8a\u27e9, \u27e8\u27e8a\u27e9\u27e9)\n\n@[simp] lemma nonempty_plift {\u03b1} : nonempty (plift \u03b1) \u2194 nonempty \u03b1 :=\niff.intro (assume \u27e8\u27e8a\u27e9\u27e9, \u27e8a\u27e9) (assume \u27e8a\u27e9, \u27e8\u27e8a\u27e9\u27e9)\n\n@[simp] lemma nonempty.forall {\u03b1} {p : nonempty \u03b1 \u2192 Prop} : (\u2200h:nonempty \u03b1, p h) \u2194 (\u2200a, p \u27e8a\u27e9) :=\niff.intro (assume h a, h _) (assume h \u27e8a\u27e9, h _)\n\n@[simp] lemma nonempty.exists {\u03b1} {p : nonempty \u03b1 \u2192 Prop} : (\u2203h:nonempty \u03b1, p h) \u2194 (\u2203a, p \u27e8a\u27e9) :=\niff.intro (assume \u27e8\u27e8a\u27e9, h\u27e9, \u27e8a, h\u27e9) (assume \u27e8a, h\u27e9, \u27e8\u27e8a\u27e9, h\u27e9)\n\nlemma classical.nonempty_pi {\u03b1} {\u03b2 : \u03b1 \u2192 Sort*} : nonempty (\u03a0a:\u03b1, \u03b2 a) \u2194 (\u2200a:\u03b1, nonempty (\u03b2 a)) :=\niff.intro (assume \u27e8f\u27e9 a, \u27e8f a\u27e9) (assume f, \u27e8assume a, classical.choice $ f a\u27e9)\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' {\u03b1} [h : nonempty \u03b1] : inhabited \u03b1 :=\n\u27e8classical.choice h\u27e9\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\n@[reducible] protected noncomputable def nonempty.some {\u03b1} (h : nonempty \u03b1) : \u03b1 :=\nclassical.choice h\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\n@[reducible] protected noncomputable def classical.arbitrary (\u03b1) [h : nonempty \u03b1] : \u03b1 :=\nclassical.choice h\n\n/-- Given `f : \u03b1 \u2192 \u03b2`, if `\u03b1` is nonempty then `\u03b2` is also nonempty.\n  `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/\nlemma nonempty.map {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) : nonempty \u03b1 \u2192 nonempty \u03b2\n| \u27e8h\u27e9 := \u27e8f h\u27e9\n\nprotected lemma nonempty.map2 {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : nonempty \u03b1 \u2192 nonempty \u03b2 \u2192 nonempty \u03b3\n| \u27e8x\u27e9 \u27e8y\u27e9 := \u27e8f x y\u27e9\n\nprotected lemma nonempty.congr {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b1) :\n  nonempty \u03b1 \u2194 nonempty \u03b2 :=\n\u27e8nonempty.map f, nonempty.map g\u27e9\n\nlemma nonempty.elim_to_inhabited {\u03b1 : Sort*} [h : nonempty \u03b1] {p : Prop}\n  (f : inhabited \u03b1 \u2192 p) : p :=\nh.elim $ f \u2218 inhabited.mk\n\ninstance {\u03b1 \u03b2} [h : nonempty \u03b1] [h2 : nonempty \u03b2] : nonempty (\u03b1 \u00d7 \u03b2) :=\nh.elim $ \u03bb g, h2.elim $ \u03bb g2, \u27e8\u27e8g, g2\u27e9\u27e9\n\nend nonempty\n\nlemma subsingleton_of_not_nonempty {\u03b1 : Sort*} (h : \u00ac nonempty \u03b1) : subsingleton \u03b1 :=\n\u27e8\u03bb x, false.elim $ not_nonempty_iff_imp_false.mp h x\u27e9\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] {\u03b1 : Sort*} (x y : \u03b1) :\n  dite P (\u03bb h, x) (\u03bb 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 {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) (P : Prop) [decidable P] (x : P \u2192 \u03b1) (y : \u00acP \u2192 \u03b1) :\n  f (dite P x y) = dite P (\u03bb h, f (x h)) (\u03bb 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 {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) (P : Prop) [decidable P] (x y : \u03b1) :\n  f (ite P x y) = ite P (f x) (f y) :=\napply_dite f P (\u03bb _, x) (\u03bb _, 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 {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop) [decidable P] (a : P \u2192 \u03b1)\n  (b : \u00acP \u2192 \u03b1) (c : P \u2192 \u03b2) (d : \u00acP \u2192 \u03b2) :\n  f (dite P a b) (dite P c d) = dite P (\u03bb h, f (a h) (c h)) (\u03bb 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 {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop) [decidable P] (a b : \u03b1) (c d : \u03b2) :\n  f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=\napply_dite2 f P (\u03bb _, a) (\u03bb _, b) (\u03bb _, c) (\u03bb _, d)\n\n/-- A 'dite' producing a `Pi` type `\u03a0 a, \u03b2 a`, applied to a value `x : \u03b1`\nis a `dite` that applies either branch to `x`. -/\nlemma dite_apply {\u03b1 : Sort*} {\u03b2 : \u03b1 \u2192 Sort*} (P : Prop) [decidable P]\n  (f : P \u2192 \u03a0 a, \u03b2 a) (g : \u00ac P \u2192 \u03a0 a, \u03b2 a) (x : \u03b1) :\n  (dite P f g) x = dite P (\u03bb h, f h x) (\u03bb h, g h x) :=\nby { by_cases h : P; simp [h] }\n\n/-- A 'ite' producing a `Pi` type `\u03a0 a, \u03b2 a`, applied to a value `x : \u03b1`\nis a `ite` that applies either branch to `x` -/\nlemma ite_apply {\u03b1 : Sort*} {\u03b2 : \u03b1 \u2192 Sort*} (P : Prop) [decidable P]\n  (f g : \u03a0 a, \u03b2 a) (x : \u03b1) :\n  (ite P f g) x = ite P (f x) (g x) :=\ndite_apply P (\u03bb _, f) (\u03bb _, 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 {\u03b1 : Sort*} (P : Prop) [decidable P] (x : \u00ac P \u2192 \u03b1) (y : \u00ac\u00ac P \u2192 \u03b1) :\n  dite (\u00ac P) x y = dite P (\u03bb 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 {\u03b1 : Sort*} (P : Prop) [decidable P] (x y : \u03b1) :\n  ite (\u00ac P) x y = ite P y x :=\ndite_not P (\u03bb _, x) (\u03bb _, y)\n\nlemma ite_and {\u03b1} {p q : Prop} [decidable p] [decidable q] {x y : \u03b1} :\n  ite (p \u2227 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 \u2192 \u2115`).\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 \u2192 (state \u2192 \u2115) \u2192 stmt\n| seq    : stmt \u2192 stmt \u2192 stmt\n| ite    : (state \u2192 Prop) \u2192 stmt \u2192 stmt \u2192 stmt\n| while  : (state \u2192 Prop) \u2192 stmt \u2192 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 \u2192 \u2115`) and a Boolean expression is a\n  predicate (`state \u2192 Prop` or `state \u2192 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., \u03bb-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 (\u03bbs, s \"x\" > s \"y\")\n  (stmt.skip ;; stmt.assign \"x\" (\u03bbs, 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) \u27f9 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 \u21a6 3, y \u21a6 5]) \u27f9 [x \u21a6 8, y \u21a6 0]`\n\nDerivation rules:\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Skip\n    (skip, s) \u27f9 s\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Asn\n    (x := a, s) \u27f9 s[x \u21a6 s(a)]\n\n    (S, s) \u27f9 t   (T, t) \u27f9 u\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Seq\n    (S; T, s) \u27f9 u\n\n    (S, s) \u27f9 t\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 If-True   if s(b) is true\n    (if b then S else T, s) \u27f9 t\n\n    (T, s) \u27f9 t\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 If-False   if s(b) is false\n    (if b then S else T, s) \u27f9 t\n\n    (S, s) \u27f9 t   (while b do S, t) \u27f9 u\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 While-True   if s(b) is true\n    (while b do S, s) \u27f9 u\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 While-False   if s(b) is false\n    (while b do S, s) \u27f9 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 \u00d7 state \u2192 state \u2192 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 \u21a6 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 \u2192 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 \u2192 Prop} {S T s t} (hcond : \u00ac b s)\n    (hbody : big_step (T, s) t) :\n  big_step (stmt.ite b S T, s) t\n| while_true {b : state \u2192 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 \u2192 Prop} {S s} (hcond : \u00ac b s) :\n  big_step (stmt.while b S, s) s\n\ninfix ` \u27f9 ` : 110 := big_step\n\nlemma silly_loop_from_1_big_step :\n  (silly_loop, (\u03bb_, 0){\"x\" \u21a6 1}) \u27f9 (\u03bb_, 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) \u27f9 l)\n    (hr : (S, s) \u27f9 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  \u2203t, (S, s) \u27f9 t :=\nsorry   -- unprovable\n\nlemma big_step_doesnt_terminate {S s t} :\n  \u00ac (stmt.while (\u03bb_, true) S, s) \u27f9 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) \u27f9 t \u2194 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) \u27f9 t \u2194 t = s{x \u21a6 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) \u27f9 t \u2194 (\u2203u, (S, s) \u27f9 u \u2227 (T, u) \u27f9 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) \u27f9 t \u2194\n  (b s \u2227 (S, s) \u27f9 t) \u2228 (\u00ac b s \u2227 (T, s) \u27f9 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) \u27f9 u \u2194\n  (\u2203t, b s \u2227 (S, s) \u27f9 t \u2227 (stmt.while b S, t) \u27f9 u)\n  \u2228 (\u00ac b s \u2227 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 \u2192 Prop} {S s u}\n    (hcond : b s) :\n  (stmt.while b S, s) \u27f9 u \u2194\n  (\u2203t, (S, s) \u27f9 t \u2227 (stmt.while b S, t) \u27f9 u) :=\nby rw big_step_while_iff; simp [hcond]\n\n@[simp] lemma big_step_while_false_iff {b : state \u2192 Prop}\n    {S s t} (hcond : \u00ac b s) :\n  (stmt.while b S, s) \u27f9 t \u2194 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) \u21d2 (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\u2080, s\u2080) \u21d2 (S\u2081, s\u2081) \u21d2 \u2026`.\n\nA pair `(S, s)` is called a __configuration__. It is __final__ if no transition\nof the form `(S, s) \u21d2 _` is possible.\n\nExample:\n\n      `(x := x + y; y := 0, [x \u21a6 3, y \u21a6 5])`\n    `\u21d2 (skip; y := 0,       [x \u21a6 8, y \u21a6 5])`\n    `\u21d2 (y := 0,             [x \u21a6 8, y \u21a6 5])`\n    `\u21d2 (skip,               [x \u21a6 8, y \u21a6 0])`\n\nDerivation rules:\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Asn\n    (x := a, s) \u21d2 (skip, s[x \u21a6 s(a)])\n\n    (S, s) \u21d2 (S', s')\n    \u2014\u2014\u2014-\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Seq-Step\n    (S ; T, s) \u21d2 (S' ; T, s')\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Seq-Skip\n    (skip ; S, s) \u21d2 (S, s)\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 If-True   if s(b) is true\n    (if b then S else T, s) \u21d2 (S, s)\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 If-False   if s(b) is false\n    (if b then S else T, s) \u21d2 (T, s)\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 While\n    (while b do S, s) \u21d2 (if b then (S ; while b do S) else skip, s)\n\nThere is no rule for `skip` (why?). -/\n\ninductive small_step : stmt \u00d7 state \u2192 stmt \u00d7 state \u2192 Prop\n| assign {x a s} :\n  small_step (stmt.assign x a, s) (stmt.skip, s{x \u21a6 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 \u2192 Prop} {S T s} (hcond : b s) :\n  small_step (stmt.ite b S T, s) (S, s)\n| ite_false {b : state \u2192 Prop} {S T s} (hcond : \u00ac b s) :\n  small_step (stmt.ite b S T, s) (T, s)\n| while {b : state \u2192 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 ` \u21d2 ` := small_step\ninfixr ` \u21d2* ` : 100 := star small_step\n\nlemma silly_loop_from_1_small_step :\n  (silly_loop, (\u03bb_, 0){\"x\" \u21a6 1}) \u21d2*\n  (stmt.skip, ((\u03bb_, 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) \u27f9 t` if and only if `(S, s) \u21d2* (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`\u21d2` and `\u21d2*`, 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  (\u00ac \u2203T t, (S, s) \u21d2 (T, t)) \u2194 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 \u21a6 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) \u21d2 Ll) (hr : (S, s) \u21d2 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\u2081 T s s\u2081 hS\u2081 ih {\n    cases' hr,\n    case seq_step : S S\u2082 _ _ s\u2082 hS\u2082 {\n      have hSs\u2081\u2082 := ih hS\u2082,\n      cc },\n    case seq_skip {\n      cases' hS\u2081 } },\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  \u00ac ((stmt.skip, s) \u21d2 (S, t)) :=\nby intro h; cases' h\n\n@[simp] lemma small_step_seq_iff {S T s Ut} :\n  (S ;; T, s) \u21d2 Ut \u2194\n  (\u2203S' t, (S, s) \u21d2 (S', t) \u2227 Ut = (S' ;; T, t))\n  \u2228 (S = stmt.skip \u2227 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) \u21d2 Us \u2194\n  (b s \u2227 Us = (S, s)) \u2228 (\u00ac b s \u2227 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) \u27f9 t \u2194 (S, s) \u21d2* (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) \u21d2* (stmt.skip, u)) :\n  (S ;; T, s) \u21d2* (stmt.skip ;; T, u) :=\nbegin\n  apply star.lift (\u03bbSs, (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) \u27f9 t) :\n  (S, s) \u21d2* (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\u2080 S\u2081 s\u2080 s\u2081 s\u2082}\n  (h\u2081 : (S\u2080, s\u2080) \u21d2 (S\u2081, s\u2081)) :\n  (S\u2081, s\u2081) \u27f9 s\u2082 \u2192 (S\u2080, s\u2080) \u27f9 s\u2082 :=\nbegin\n  induction' h\u2081;\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) \u21d2* (stmt.skip, t) \u2192 (S, s) \u27f9 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) \u27f9 t \u2194 (S, s) \u21d2* (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 \u2192 list stmt \u00d7 state \u2192 list stmt \u00d7 state \u2192 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) \u21d2 (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 \u2260 j)\n    (hT : par_step i (Ss, s) (Ts, t))\n    (hT' : par_step j (Ss, s) (Ts', t')) :\n  \u2203u Us, par_step j (Ts, t) (Us, u) \u2227\n    par_step i (Ts', t') (Us, u) :=\nsorry   -- unprovable\n\ndef stmt.W : stmt \u2192 set string\n| stmt.skip         := \u2205\n| (stmt.assign x _) := {x}\n| (stmt.seq S T)    := stmt.W S \u222a stmt.W T\n| (stmt.ite _ S T)  := stmt.W S \u222a stmt.W T\n| (stmt.while _ S)  := stmt.W S\n\ndef exp.R {\u03b1 : Type} : (state \u2192 \u03b1) \u2192 set string\n| f := {x | \u2203s n, f (s{x \u21a6 n}) \u2260 f s}\n\ndef stmt.R : stmt \u2192 set string\n| stmt.skip         := \u2205\n| (stmt.assign _ a) := exp.R a\n| (stmt.seq S T)    := stmt.R S \u222a stmt.R T\n| (stmt.ite b S T)  := exp.R b \u222a stmt.R S \u222a stmt.R T\n| (stmt.while b S)  := exp.R b \u222a stmt.R S\n\ndef stmt.V : stmt \u2192 set string\n| S := stmt.W S \u222a 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 \u2260 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       \u2229 stmt.V (list.nth_le Ts j hjT) = \u2205)\n    (hVW : stmt.V (list.nth_le Ss i hiS)\n       \u2229 stmt.W (list.nth_le Ts j hjT) = \u2205) :\n  \u2203u Us, par_step j (Ts, t) (Us, u) \u2227\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\" `_\u2081, ..., _\u2084`.  If you want a different arity for your\nfunction, simply\nintroduce\n```lean\n@[nolint unused_arguments]\ndef congrm_fun_n {\u03b1\u2081 \u2026 \u03b1\u2099 \u03c1} {r : \u03c1} : \u03b1\u2081 \u2192 \u22ef \u2192 a\u2099 \u2192 \u03c1 := \u03bb _ \u2026 _, r\nnotation `_\u2099` := congrm_fun_n\n```\n_Warning:_ `convert_to_explicit` checks that the first 18 characters in the name of `_\u2099` 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 {\u03b1 \u03c1} {r : \u03c1} : \u03b1 \u2192 \u03c1 := \u03bb _, r\nnotation `_\u2081` := 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 {\u03b1 \u03b2 \u03c1} {r : \u03c1} : \u03b1 \u2192 \u03b2 \u2192 \u03c1 := \u03bb _ _, r\nnotation `_\u2082` := 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 {\u03b1 \u03b2 \u03b3 \u03c1} {r : \u03c1} : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03c1 := \u03bb _ _ _, r\nnotation `_\u2083` := 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 {\u03b1 \u03b2 \u03b3 \u03b4 \u03c1} {r : \u03c1} : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 \u03c1 := \u03bb _ _ _ _, r\nnotation `_\u2084` := 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 \u2192 list congr_arg_kind \u2192 list expr \u2192\n  tactic (list (expr \u00d7 expr))\n| (_ :: _ :: g :: prf_args) (congr_arg_kind.eq :: kinds)             (pat :: pat_args) :=\n  (\u03bb 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 \u2192 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 = %%_) \u2190 target,\n  pat \u2190 convert_to_explicit pat lhs,\n  cl \u2190 mk_specialized_congr_lemma pat,\n  H_congr_lemma \u2190 assertv `H_congr_lemma cl.type cl.proof,\n  [prf] \u2190 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 \u2190 instantiate_mvars prf,\n  subgoals \u2190 extract_subgoals prf.get_app_args cl.arg_kinds pat.get_app_args,\n  subgoals \u2190 subgoals.mmap (\u03bb \u27e8subgoal, subpat\u27e9, 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 \u2190 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 \u2190 intro pat.binding_name,\n  equate_with_pattern_core $ codomain.instantiate_var x\n| _ := do\n  pat \u2190 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 \u2190 solve1 (equate_with_pattern_core pat),\ngs \u2190 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 \u2194 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 : \u2115} :\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\u22a2 a = b\n\u22a2 d = b\n\u22a2 c + a.pred = c + d.pred\n-/\n  sorry,\n  sorry,\n  sorry,\nend\n\nexample {a b : \u2115} (h : a = b) : (\u03bb y : \u2115, \u2200 z, a + a = z) = (\u03bb x, \u2200 z, b + a = z) :=\nbegin\n  congrm \u03bb x, \u2200 w, _ + a = w,\n  -- produces one goal for the underscore: \u22a2 a = b\n  exact h,\nend\n```\n\nThe tactic also allows for \"function underscores\", denoted by `_\u2081, ..., _\u2084`.  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 _ _) \u2190 target | fail \"congrm: goal must be an equality or iff\",\nta \u2190 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 \u03b1` 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\u2080 u\u2081 v\u2080 v\u2081 v\u2082 w w\u2080 w\u2081\n\nvariable {s : Type u\u2080} {s' : Type u\u2081} {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\u2081 \u2192 Type\nu\u2082`, this class convert between instantiations, from\n`M.{u} : Type u\u2081 \u2192 Type u\u2082` to `M.{v} : Type v\u2081 \u2192 Type v\u2082` and back -/\nclass Uliftable (f : Type u\u2080 \u2192 Type u\u2081) (g : Type v\u2080 \u2192 Type v\u2081) where\n  congr {\u03b1 \u03b2} : \u03b1 \u2243 \u03b2 \u2192 f \u03b1 \u2243 g \u03b2\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} \u03b1` and lifts it to M.{max u v} (ulift.{v} \u03b1) -/\n@[reducible]\ndef up {f : Type u\u2080 \u2192 Type u\u2081} {g : Type max u\u2080 v\u2080 \u2192 Type v\u2081} [Uliftable f g] {\u03b1} :\n    f \u03b1 \u2192 g (ULift \u03b1) :=\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} \u03b1)` and lowers it to `M.{u} \u03b1` -/\n@[reducible]\ndef down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type max u\u2080 v\u2080 \u2192 Type v\u2081} [Uliftable f g] {\u03b1} :\n    g (ULift \u03b1) \u2192 f \u03b1 :=\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\u2080 \u2192 Type v\u2081) (G : Type max v\u2080 u\u2080 \u2192 Type u\u2081) [Uliftable F G] [Monad G] {\u03b1 \u03b2}\n    (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n  up x >>= f \u2218 ULift.down\n#align uliftable.adapt_up Uliftable.adaptUp\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adaptDown {F : Type max u\u2080 v\u2080 \u2192 Type u\u2081} {G : Type v\u2080 \u2192 Type v\u2081} [L : Uliftable G F] [Monad F]\n    {\u03b1 \u03b2} (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n  @down.{v\u2080, v\u2081, max u\u2080 v\u2080} G F L \u03b2 <| x >>= @up.{v\u2080, v\u2081, max u\u2080 v\u2080} G F L \u03b2 \u2218 f\n#align uliftable.adapt_down Uliftable.adaptDown\n\n/-- map function that moves up universes -/\ndef upMap {F : Type u\u2080 \u2192 Type u\u2081} {G : Type max u\u2080 v\u2080 \u2192 Type v\u2081} [inst : Uliftable F G] [Functor G]\n    {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\n  Functor.map (f \u2218 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\u2080 v\u2080 \u2192 Type u\u2081} {G : Type u\u2080 \u2192 Type v\u2081} [inst : Uliftable G F]\n    [Functor F] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\n  down (Functor.map (ULift.up \u2218 f) x : F (ULift \u03b2))\n#align uliftable.down_map Uliftable.downMap\n\n@[simp]\ntheorem up_down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type max u\u2080 v\u2080 \u2192 Type v\u2081} [Uliftable f g] {\u03b1}\n    (x : g (ULift \u03b1)) : up (down x : f \u03b1) = 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\u2080 \u2192 Type u\u2081} {g : Type max u\u2080 v\u2080 \u2192 Type v\u2081} [Uliftable f g] {\u03b1}\n    (x : f \u03b1) : 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 \u03b1 \u03b2 F := F\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef StateT.uliftable' {m : Type u\u2080 \u2192 Type v\u2080} {m' : Type u\u2081 \u2192 Type v\u2081} [Uliftable m m']\n    (F : s \u2243 s') : Uliftable (StateT s m) (StateT s' m')\n    where congr \u03b1 \u03b2 G :=\n    StateT.equiv <| Equiv.piCongr F fun _ => Uliftable.congr _ _ <| Equiv.prodCongr G F\n#align state_t.uliftable' StateT\u2093.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 \u2243 s') :\n    Uliftable (ReaderT s m) (ReaderT s' m')\n    where congr \u03b1 \u03b2 G := ReaderT.equiv <| Equiv.piCongr F fun _ => Uliftable.congr _ _ G\n#align reader_t.uliftable' ReaderT\u2093.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 \u2243 r') : Uliftable (ContT r m) (ContT r' m')\n    where congr \u03b1 \u03b2 := 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 \u2243 w') :\n    Uliftable (WriterT w m) (WriterT w' m')\n    where congr \u03b1 \u03b2 G := WriterT.equiv <| Uliftable.congr _ _ <| Equiv.prodCongr G F\n#align writer_t.uliftable' WriterT\u2093.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 \u2190 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 \u2190 kdepends_on tgt h\n      when dep <| fail <| f! \"Cannot clear hypothesis {h} since the target depends on it.\"\n  let n \u2190 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 \u2260 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 \u2190 mk_meta_var tgt\n  intron n\n  exact v\n  let gs \u2190 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 {\u03b1} {\u03b2 : \u03b1 \u2192 Type} (a : \u03b1) (b : \u03b2 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 \u2190 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 {\u03b1} {\u03b2 : \u03b1 \u2192 Type} (a : \u03b1) (b : \u03b2 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 \u2190 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 := \u27e8Int.ofNat\u27e9\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 `\u2191` operator to explicitly indicate a coercion. Using `\u2191x`\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 `\u2191x + \u2191y` where `+` is the addition on `Int`, or `\u2191(x + y)`\nwhere `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition\nwith the type `Nat \u2192 Nat \u2192 Int`. You can use the `\u2191` 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 `\u2191x : Int` and `\u2191y : Int`, resulting in the `\u2191x + \u2191y` version.\n\nNote that unlike most operators like `+`, `\u2191` 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 \u2192 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 ?\u03b1` 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 \u03b1 \u03b2` 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 `\u03b1` must be a subset of the variables in `\u03b2`\n  (or out-params of type class parameters),\n  because `Coe` is chained right-to-left.\n\n* `CoeOut \u03b1 \u03b2` is like `Coe \u03b1 \u03b2` but chained left-to-right.\n  Use this if the variables in the type `\u03b1` are a superset of the variables in `\u03b2`.\n\n* `CoeTail \u03b1 \u03b2` is like `Coe \u03b1 \u03b2`, but only applied once.\n  Use this for coercions that would cause loops, like `[Ring R] \u2192 CoeTail Nat R`.\n\n* `CoeHead \u03b1 \u03b2` is similar to `CoeOut \u03b1 \u03b2`, but only applied once.\n  Use this for coercions that would cause loops, like `[SetLike S \u03b1] \u2192 CoeHead S (Set \u03b1)`.\n\n* `CoeDep \u03b1 (x : \u03b1) \u03b2` allows `\u03b2` to depend not only on `\u03b1` but on the value\n  `x : \u03b1` itself. This is useful when the coercion function is dependent.\n  An example of a dependent coercion is the instance for `Prop \u2192 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 \u03b1 (\u03b3 : \u03b1 \u2192 Sort v)` is a coercion to a function. `\u03b3 a` should be a\n  (coercion-to-)function type, and this is triggered whenever an element\n  `f : \u03b1` 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 \u03b1 \u03b2` is a coercion to a sort. `\u03b2` must be a universe, and if\n  `a : \u03b1` appears in a place where a type is expected, like `(x : a)` or `a \u2192 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 \u03b1 \u03b2` is the typeclass for coercions from `\u03b1` to `\u03b2`. It can be transitively\nchained with other `Coe` instances, and coercion is automatically used when\n`x` has type `\u03b1` but it is used in a context where `\u03b2` is expected.\nYou can use the `\u2191x` operator to explicitly trigger coercion.\n-/\nclass Coe (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] Coe.coe\n\n/--\nAuxiliary class implementing `Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeTC (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeTC.coe\n\ninstance [Coe \u03b2 \u03b3] [CoeTC \u03b1 \u03b2] : CoeTC \u03b1 \u03b3 where coe a := Coe.coe (CoeTC.coe a : \u03b2)\ninstance [Coe \u03b1 \u03b2] : CoeTC \u03b1 \u03b2 where coe a := Coe.coe a\ninstance : CoeTC \u03b1 \u03b1 where coe a := a\n\n/--\n`CoeOut \u03b1 \u03b2` is for coercions that are applied from left-to-right.\n-/\nclass CoeOut (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeOut.coe\n\n/--\nAuxiliary class implementing `CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeOTC (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeOTC.coe\n\ninstance [CoeOut \u03b1 \u03b2] [CoeOTC \u03b2 \u03b3] : CoeOTC \u03b1 \u03b3 where coe a := CoeOTC.coe (CoeOut.coe a : \u03b2)\ninstance [CoeTC \u03b1 \u03b2] : CoeOTC \u03b1 \u03b2 where coe a := CoeTC.coe a\ninstance : CoeOTC \u03b1 \u03b1 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 \u2192+ B)` apply even when the two sides are defeq.)\n\n/--\n`CoeHead \u03b1 \u03b2` is for coercions that are applied from left-to-right at most once\nat beginning of the coercion chain.\n-/\nclass CoeHead (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeHead.coe\n\n/--\nAuxiliary class implementing `CoeHead CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTC (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeHTC.coe\n\ninstance [CoeHead \u03b1 \u03b2] [CoeOTC \u03b2 \u03b3] : CoeHTC \u03b1 \u03b3 where coe a := CoeOTC.coe (CoeHead.coe a : \u03b2)\ninstance [CoeOTC \u03b1 \u03b2] : CoeHTC \u03b1 \u03b2 where coe a := CoeOTC.coe a\ninstance : CoeHTC \u03b1 \u03b1 where coe a := a\n\n/--\n`CoeTail \u03b1 \u03b2` is for coercions that can only appear at the end of a\nsequence of coercions. That is, `\u03b1` can be further coerced via `Coe \u03c3 \u03b1` and\n`CoeHead \u03c4 \u03c3` instances but `\u03b2` will only be the expected type of the expression.\n-/\nclass CoeTail (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeTail.coe\n\n/--\nAuxiliary class implementing `CoeHead* Coe* CoeTail?`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTCT (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeHTCT.coe\n\ninstance [CoeTail \u03b2 \u03b3] [CoeHTC \u03b1 \u03b2] : CoeHTCT \u03b1 \u03b3 where coe a := CoeTail.coe (CoeHTC.coe a : \u03b2)\ninstance [CoeHTC \u03b1 \u03b2] : CoeHTCT \u03b1 \u03b2 where coe a := CoeHTC.coe a\ninstance : CoeHTCT \u03b1 \u03b1 where coe a := a\n\n/--\n`CoeDep \u03b1 (x : \u03b1) \u03b2` is a typeclass for dependent coercions, that is, the type `\u03b2`\ncan depend on `x` (or rather, the value of `x` is available to typeclass search\nso an instance that relates `\u03b2` 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 (\u03b1 : Sort u) (_ : \u03b1) (\u03b2 : Sort v) where\n  /-- The resulting value of type `\u03b2`. The input `x : \u03b1` is a parameter to\n  the type class, so the value of type `\u03b2` may possibly depend on additional\n  typeclasses on `x`. -/\n  coe : \u03b2\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 `\u2191x` or by double type\nascription `((x : \u03b1) : \u03b2)`.\n\nA `CoeT` chain has the grammar `CoeHead? CoeOut* Coe* CoeTail? | CoeDep`.\n-/\nclass CoeT (\u03b1 : Sort u) (_ : \u03b1) (\u03b2 : Sort v) where\n  /-- The resulting value of type `\u03b2`. The input `x : \u03b1` is a parameter to\n  the type class, so the value of type `\u03b2` may possibly depend on additional\n  typeclasses on `x`. -/\n  coe : \u03b2\nattribute [coe_decl] CoeT.coe\n\ninstance [CoeHTCT \u03b1 \u03b2] : CoeT \u03b1 a \u03b2 where coe := CoeHTCT.coe a\ninstance [CoeDep \u03b1 a \u03b2] : CoeT \u03b1 a \u03b2 where coe := CoeDep.coe a\ninstance : CoeT \u03b1 a \u03b1 where coe := a\n\n/--\n`CoeFun \u03b1 (\u03b3 : \u03b1 \u2192 Sort v)` is a coercion to a function. `\u03b3 a` should be a\n(coercion-to-)function type, and this is triggered whenever an element\n`f : \u03b1` 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 (\u03b1 : Sort u) (\u03b3 : outParam (\u03b1 \u2192 Sort v)) where\n  /-- Coerces a value `f : \u03b1` to type `\u03b3 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 : \u03b1) \u2192 \u03b3 f\nattribute [coe_decl] CoeFun.coe\n\ninstance [CoeFun \u03b1 fun _ => \u03b2] : CoeOut \u03b1 \u03b2 where coe a := CoeFun.coe a\n\n/--\n`CoeSort \u03b1 \u03b2` is a coercion to a sort. `\u03b2` must be a universe, and if\n`a : \u03b1` appears in a place where a type is expected, like `(x : a)` or `a \u2192 a`,\nthen it will be turned into `(x : CoeSort.coe a)`.\n-/\nclass CoeSort (\u03b1 : Sort u) (\u03b2 : outParam (Sort v)) where\n  /-- Coerces a value of type `\u03b1` to `\u03b2`, which must be a universe. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeSort.coe\n\ninstance [CoeSort \u03b1 \u03b2] : CoeOut \u03b1 \u03b2 where coe a := CoeSort.coe a\n\n/--\n`\u2191x` represents a coercion, which converts `x` of type `\u03b1` to type `\u03b2`, using\ntypeclasses to resolve a suitable conversion function. You can often leave the\n`\u2191` off entirely, since coercion is triggered implicitly whenever there is a\ntype error, but in ambiguous cases it can be useful to use `\u2191` to disambiguate\nbetween e.g. `\u2191x + \u2191y` and `\u2191(x + y)`.\n-/\nsyntax:1024 (name := coeNotation) \"\u2191\" 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 {\u03b1 : Type u} : Coe \u03b1 (Option \u03b1) where\n  coe := some\n\ninstance subtypeCoe {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : CoeOut (Subtype p) \u03b1 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 \u2192 Type v} {n : Type u \u2192 Type w} {\u03b1 \u03b2 : Type u}\n    [MonadLiftT m n] [\u2200 a, CoeT \u03b1 a \u03b2] [Monad n] (x : m \u03b1) : n \u03b2 := do\n  let a \u2190 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 \u2192 Type v} {\u03b1 \u03b2 : Type u}\n    [\u2200 a, CoeT \u03b1 a \u03b2] [Monad m] (x : m \u03b1) : m \u03b2 := do\n  let a \u2190 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\u00e9bastien Gou\u00ebzel. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: S\u00e9bastien Gou\u00ebzel\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 \u03bc`, 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 {\u03b9 \u03b1 \u03b2 \u03b3 \u03b4 R : Type*} {m0 : measurable_space \u03b1} [measurable_space \u03b2]\n   [measurable_space \u03b3] [measurable_space \u03b4] {f g : \u03b1 \u2192 \u03b2} {\u03bc \u03bd : measure \u03b1}\n\ninclude m0\n\nsection\n\n@[nontriviality, measurability]\nlemma subsingleton.ae_measurable [subsingleton \u03b1] : ae_measurable f \u03bc :=\nsubsingleton.measurable.ae_measurable\n\n@[nontriviality, measurability]\nlemma ae_measurable_of_subsingleton_codomain [subsingleton \u03b2] : ae_measurable f \u03bc :=\n(measurable_of_subsingleton_codomain f).ae_measurable\n\n@[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure \u03b1) :=\nbegin\n  nontriviality \u03b1, inhabit \u03b1,\n  exact \u27e8\u03bb x, f default, measurable_const, rfl\u27e9\nend\n\nnamespace ae_measurable\n\nlemma mono_measure (h : ae_measurable f \u03bc) (h' : \u03bd \u2264 \u03bc) : ae_measurable f \u03bd :=\n\u27e8h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk\u27e9\n\n\n\nprotected lemma mono' (h : ae_measurable f \u03bc) (h' : \u03bd \u226a \u03bc) : ae_measurable f \u03bd :=\n\u27e8h.mk f, h.measurable_mk, h' h.ae_eq_mk\u27e9\n\nlemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (\u03bc.restrict s)) :\n  \u2200\u1d50 x \u2202\u03bc, x \u2208 s \u2192 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 (\u03bc.restrict s)) :\n  f =\u1da0[\u03bc.ae \u2293 \ud835\udcdf s] h.mk f :=\nle_ae_restrict h.ae_eq_mk\n\n@[measurability]\nlemma sum_measure [countable \u03b9] {\u03bc : \u03b9 \u2192 measure \u03b1} (h : \u2200 i, ae_measurable f (\u03bc i)) :\n  ae_measurable f (sum \u03bc) :=\nbegin\n  nontriviality \u03b2, inhabit \u03b2,\n  set s : \u03b9 \u2192 set \u03b1 := \u03bb i, to_measurable (\u03bc i) {x | f x \u2260 (h i).mk f x},\n  have hs\u03bc : \u2200 i, \u03bc i (s i) = 0,\n  { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk },\n  have hsm : measurable_set (\u22c2 i, s i),\n    from measurable_set.Inter (\u03bb i, measurable_set_to_measurable _ _),\n  have hs : \u2200 i x, x \u2209 s i \u2192 f x = (h i).mk f x,\n  { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx },\n  set g : \u03b1 \u2192 \u03b2 := (\u22c2 i, s i).piecewise (const \u03b1 default) f,\n  refine \u27e8g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ \u03bb i, _\u27e9,\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 \u27e8\u22c3 i, ((h i).mk f \u207b\u00b9' t) \u2229 (s i)\u1d9c, measurable_set.Union $\n      \u03bb i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _\u27e9,\n    ext \u27e8x, hx\u27e9,\n    simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_iff,\n      mem_compl_iff] at hx \u22a2,\n    split,\n    { rintro \u27e8i, hxt, hxs\u27e9, rwa hs _ _ hxs },\n    { rcases hx with \u27e8i, hi\u27e9, rw hs _ _ hi, exact \u03bb h, \u27e8i, h, hi\u27e9 } },\n  { refine measure_mono_null (\u03bb x (hx : f x \u2260 g x), _) (hs\u03bc i),\n    contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm,\n    exact \u03bb h, hx (mem_Inter.1 h i) }\nend\n\n@[simp] lemma _root_.ae_measurable_sum_measure_iff [countable \u03b9] {\u03bc : \u03b9 \u2192 measure \u03b1} :\n  ae_measurable f (sum \u03bc) \u2194 \u2200 i, ae_measurable f (\u03bc i) :=\n\u27e8\u03bb h i, h.mono_measure (le_sum _ _), sum_measure\u27e9\n\n@[simp] lemma _root_.ae_measurable_add_measure_iff :\n  ae_measurable f (\u03bc + \u03bd) \u2194 ae_measurable f \u03bc \u2227 ae_measurable f \u03bd :=\nby { rw [\u2190 sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl }\n\n@[measurability]\nlemma add_measure {f : \u03b1 \u2192 \u03b2} (h\u03bc : ae_measurable f \u03bc) (h\u03bd : ae_measurable f \u03bd) :\n  ae_measurable f (\u03bc + \u03bd) :=\nae_measurable_add_measure_iff.2 \u27e8h\u03bc, h\u03bd\u27e9\n\n@[measurability]\nprotected lemma Union [countable \u03b9] {s : \u03b9 \u2192 set \u03b1} (h : \u2200 i, ae_measurable f (\u03bc.restrict (s i))) :\n  ae_measurable f (\u03bc.restrict (\u22c3 i, s i)) :=\n(sum_measure h).mono_measure $ restrict_Union_le\n\n@[simp] lemma _root_.ae_measurable_Union_iff [countable \u03b9] {s : \u03b9 \u2192 set \u03b1} :\n  ae_measurable f (\u03bc.restrict (\u22c3 i, s i)) \u2194 \u2200 i, ae_measurable f (\u03bc.restrict (s i)) :=\n\u27e8\u03bb h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union\u27e9\n\n@[simp] lemma _root_.ae_measurable_union_iff {s t : set \u03b1} :\n  ae_measurable f (\u03bc.restrict (s \u222a t)) \u2194\n    ae_measurable f (\u03bc.restrict s) \u2227 ae_measurable f (\u03bc.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 \u211d\u22650\u221e] [is_scalar_tower R \u211d\u22650\u221e \u211d\u22650\u221e]\n  (h : ae_measurable f \u03bc) (c : R) :\n  ae_measurable f (c \u2022 \u03bc) :=\n\u27e8h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c\u27e9\n\nlemma comp_ae_measurable {f : \u03b1 \u2192 \u03b4} {g : \u03b4 \u2192 \u03b2}\n  (hg : ae_measurable g (\u03bc.map f)) (hf : ae_measurable f \u03bc) : ae_measurable (g \u2218 f) \u03bc :=\n\u27e8hg.mk g \u2218 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))\u27e9\n\nlemma comp_measurable {f : \u03b1 \u2192 \u03b4} {g : \u03b4 \u2192 \u03b2}\n  (hg : ae_measurable g (\u03bc.map f)) (hf : measurable f) : ae_measurable (g \u2218 f) \u03bc :=\nhg.comp_ae_measurable hf.ae_measurable\n\nlemma comp_quasi_measure_preserving {\u03bd : measure \u03b4} {f : \u03b1 \u2192 \u03b4} {g : \u03b4 \u2192 \u03b2} (hg : ae_measurable g \u03bd)\n  (hf : quasi_measure_preserving f \u03bc \u03bd) : ae_measurable (g \u2218 f) \u03bc :=\n(hg.mono' hf.absolutely_continuous).comp_measurable hf.measurable\n\nlemma map_map_of_ae_measurable {g : \u03b2 \u2192 \u03b3} {f : \u03b1 \u2192 \u03b2}\n  (hg : ae_measurable g (measure.map f \u03bc)) (hf : ae_measurable f \u03bc) :\n  (\u03bc.map f).map g = \u03bc.map (g \u2218 f) :=\nbegin\n  ext1 s hs,\n  let g' := hg.mk g,\n  have A : map g (map f \u03bc) = map g' (map f \u03bc),\n  { apply measure_theory.measure.map_congr,\n    exact hg.ae_eq_mk },\n  have B : map (g \u2218 f) \u03bc = map (g' \u2218 f) \u03bc,\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 : \u03b1 \u2192 \u03b2} {g : \u03b1 \u2192 \u03b3} (hf : ae_measurable f \u03bc) (hg : ae_measurable g \u03bc) :\n  ae_measurable (\u03bb x, (f x, g x)) \u03bc :=\n\u27e8\u03bb 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\u27e9\n\nlemma exists_ae_eq_range_subset (H : ae_measurable f \u03bc) {t : set \u03b2} (ht : \u2200\u1d50 x \u2202\u03bc, f x \u2208 t)\n  (h\u2080 : t.nonempty) :\n  \u2203 g, measurable g \u2227 range g \u2286 t \u2227 f =\u1d50[\u03bc] g :=\nbegin\n  let s : set \u03b1 := to_measurable \u03bc {x | f x = H.mk f x \u2227 f x \u2208 t}\u1d9c,\n  let g : \u03b1 \u2192 \u03b2 := piecewise s (\u03bb x, h\u2080.some) (H.mk f),\n  refine \u27e8g, _, _, _\u27e9,\n  { exact measurable.piecewise (measurable_set_to_measurable _ _)\n      measurable_const H.measurable_mk },\n  { rintros _ \u27e8x, rfl\u27e9,\n    by_cases hx : x \u2208 s,\n    { simpa [g, hx] using h\u2080.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 : \u03bc (to_measurable \u03bc {x | f x = H.mk f x \u2227 f x \u2208 t}\u1d9c) = 0,\n    { rw [measure_to_measurable, \u2190 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 {\u03b2} [preorder \u03b2] [has_zero \u03b2] {m\u03b2 : measurable_space \u03b2} {f : \u03b1 \u2192 \u03b2}\n  (hf : ae_measurable f \u03bc) (f_nn : \u2200\u1d50 t \u2202\u03bc, 0 \u2264 f t) :\n  \u2203 g, measurable g \u2227 0 \u2264 g \u2227 f =\u1d50[\u03bc] g :=\nbegin\n  obtain \u27e8G, hG_meas, hG_mem, hG_ae_eq\u27e9 := hf.exists_ae_eq_range_subset f_nn \u27e80, le_rfl\u27e9,\n  exact \u27e8G, hG_meas, \u03bb x, hG_mem (mem_range_self x), hG_ae_eq\u27e9,\nend\n\nlemma subtype_mk (h : ae_measurable f \u03bc) {s : set \u03b2} {hfs : \u2200 x, f x \u2208 s} :\n  ae_measurable (cod_restrict f s hfs) \u03bc :=\nbegin\n  nontriviality \u03b1, inhabit \u03b1,\n  obtain \u27e8g, g_meas, hg, fg\u27e9 : \u2203 (g : \u03b1 \u2192 \u03b2), measurable g \u2227 range g \u2286 s \u2227 f =\u1d50[\u03bc] g :=\n    h.exists_ae_eq_range_subset (eventually_of_forall hfs) \u27e8_, hfs default\u27e9,\n  refine \u27e8cod_restrict g s (\u03bb x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _\u27e9,\n  filter_upwards [fg] with x hx,\n  simpa [subtype.ext_iff],\nend\n\nprotected lemma null_measurable (h : ae_measurable f \u03bc) : null_measurable f \u03bc :=\nlet \u27e8g, hgm, hg\u27e9 := h in hgm.null_measurable.congr hg.symm\n\nend ae_measurable\n\nlemma ae_measurable_const' (h : \u2200\u1d50 x y \u2202\u03bc, f x = f y) : ae_measurable f \u03bc :=\nbegin\n  rcases eq_or_ne \u03bc 0 with rfl | h\u03bc,\n  { exact ae_measurable_zero_measure },\n  { haveI := ae_ne_bot.2 h\u03bc,\n    rcases h.exists with \u27e8x, hx\u27e9,\n    exact \u27e8const \u03b1 (f x), measurable_const, eventually_eq.symm hx\u27e9 }\nend\n\nlemma ae_measurable_uIoc_iff [linear_order \u03b1] {f : \u03b1 \u2192 \u03b2} {a b : \u03b1} :\n  (ae_measurable f $ \u03bc.restrict $ \u0399 a b) \u2194\n    (ae_measurable f $ \u03bc.restrict $ Ioc a b) \u2227 (ae_measurable f $ \u03bc.restrict $ Ioc b a) :=\nby rw [uIoc_eq_union, ae_measurable_union_iff]\n\nlemma ae_measurable_iff_measurable [\u03bc.is_complete] :\n  ae_measurable f \u03bc \u2194 measurable f :=\n\u27e8\u03bb h, h.null_measurable.measurable_of_complete, \u03bb h, h.ae_measurable\u27e9\n\nlemma measurable_embedding.ae_measurable_map_iff {g : \u03b2 \u2192 \u03b3} (hf : measurable_embedding f) :\n  ae_measurable g (\u03bc.map f) \u2194 ae_measurable (g \u2218 f) \u03bc :=\nbegin\n  refine \u27e8\u03bb H, H.comp_measurable hf.measurable, _\u27e9,\n  rintro \u27e8g\u2081, hgm\u2081, heq\u27e9,\n  rcases hf.exists_measurable_extend hgm\u2081 (\u03bb x, \u27e8g x\u27e9) with \u27e8g\u2082, hgm\u2082, rfl\u27e9,\n  exact \u27e8g\u2082, hgm\u2082, hf.ae_map_iff.2 heq\u27e9\nend\n\nlemma measurable_embedding.ae_measurable_comp_iff {g : \u03b2 \u2192 \u03b3}\n  (hg : measurable_embedding g) {\u03bc : measure \u03b1} :\n  ae_measurable (g \u2218 f) \u03bc \u2194 ae_measurable f \u03bc :=\nbegin\n  refine \u27e8\u03bb H, _, hg.measurable.comp_ae_measurable\u27e9,\n  suffices : ae_measurable ((range_splitting g \u2218 range_factorization g) \u2218 f) \u03bc,\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 \u03b1} (hs : measurable_set s)\n  {\u03bc : measure \u03b1} {f : \u03b1 \u2192 \u03b2} :\n  ae_measurable f (\u03bc.restrict s) \u2194 ae_measurable (f \u2218 coe : s \u2192 \u03b2) (comap coe \u03bc) :=\nby rw [\u2190 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 \u03b2] : ae_measurable (\u03bb a : \u03b1, (1 : \u03b2)) \u03bc :=\nmeasurable_one.ae_measurable\n\n@[simp] lemma ae_measurable_smul_measure_iff {c : \u211d\u22650\u221e} (hc : c \u2260 0) :\n  ae_measurable f (c \u2022 \u03bc) \u2194 ae_measurable f \u03bc :=\n\u27e8\u03bb h, \u27e8h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk\u27e9,\n  \u03bb h, \u27e8h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk\u27e9\u27e9\n\nlemma ae_measurable_of_ae_measurable_trim {\u03b1} {m m0 : measurable_space \u03b1}\n  {\u03bc : measure \u03b1} (hm : m \u2264 m0) {f : \u03b1 \u2192 \u03b2} (hf : ae_measurable f (\u03bc.trim hm)) :\n  ae_measurable f \u03bc :=\n\u27e8hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk\u27e9\n\nlemma ae_measurable_restrict_of_measurable_subtype {s : set \u03b1}\n  (hs : measurable_set s) (hf : measurable (\u03bb x : s, f x)) : ae_measurable f (\u03bc.restrict s) :=\n(ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable\n\nlemma ae_measurable_map_equiv_iff (e : \u03b1 \u2243\u1d50 \u03b2) {f : \u03b2 \u2192 \u03b3} :\n  ae_measurable f (\u03bc.map e) \u2194 ae_measurable (f \u2218 e) \u03bc :=\ne.measurable_embedding.ae_measurable_map_iff\n\nend\n\nlemma ae_measurable.restrict (hfm : ae_measurable f \u03bc) {s} :\n  ae_measurable f (\u03bc.restrict s) :=\n\u27e8ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk\u27e9\n\nlemma ae_measurable_Ioi_of_forall_Ioc {\u03b2} {m\u03b2 : measurable_space \u03b2}\n  [linear_order \u03b1] [(at_top : filter \u03b1).is_countably_generated] {x : \u03b1} {g : \u03b1 \u2192 \u03b2}\n  (g_meas : \u2200 t > x, ae_measurable g (\u03bc.restrict (Ioc x t))) :\n  ae_measurable g (\u03bc.restrict (Ioi x)) :=\nbegin\n  haveI : nonempty \u03b1 := \u27e8x\u27e9,\n  obtain \u27e8u, hu_tendsto\u27e9 := exists_seq_tendsto (at_top : filter \u03b1),\n  have Ioi_eq_Union : Ioi x = \u22c3 n : \u2115, Ioc x (u n),\n  { rw Union_Ioc_eq_Ioi_self_iff.mpr _,\n    exact \u03bb 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 \u03b2]\n\nlemma ae_measurable_indicator_iff {s} (hs : measurable_set s) :\n  ae_measurable (indicator s f) \u03bc \u2194 ae_measurable f (\u03bc.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 \u27e8indicator s (h.mk f), h.measurable_mk.indicator hs, _\u27e9,\n    have A : s.indicator f =\u1d50[\u03bc.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 =\u1d50[\u03bc.restrict s\u1d9c] 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 \u03bc) {s} (hs : measurable_set s) :\n  ae_measurable (s.indicator f) \u03bc :=\n(ae_measurable_indicator_iff hs).mpr hfm.restrict\n\nlemma measure_theory.measure.restrict_map_of_ae_measurable\n  {f : \u03b1 \u2192 \u03b4} (hf : ae_measurable f \u03bc) {s : set \u03b4} (hs : measurable_set s) :\n  (\u03bc.map f).restrict s = (\u03bc.restrict $ f \u207b\u00b9' s).map f :=\ncalc\n(\u03bc.map f).restrict s = (\u03bc.map (hf.mk f)).restrict s :\n  by { congr' 1, apply measure.map_congr hf.ae_eq_mk }\n... = (\u03bc.restrict $ (hf.mk f) \u207b\u00b9' s).map (hf.mk f) :\n  measure.restrict_map hf.measurable_mk hs\n... = (\u03bc.restrict $ (hf.mk f) \u207b\u00b9' s).map f :\n  measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm))\n... = (\u03bc.restrict $ f \u207b\u00b9' 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 : \u03b1 \u2192 \u03b4} (h : \u03bc \u2264 \u03bd) (hf : ae_measurable f \u03bd) :\n  \u03bc.map f \u2264 \u03bd.map f :=\n\u03bb s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f \u207b\u00b9' 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) 2019 Jesse Han. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jesse Han\n\nSome goodies for working with `omitted`\n\n- `depends_omitted e` checks if `omitted` occurs in `e`. it will unfold one layer of\n  proof terms (e.g. a propositional field of a structure being checked) and check if\n  `omitted` occurs in those proof terms\n\n- `omitted` tries to close a propositional goal with `exact omitted`\n\n- `omit_proofs` tries to close any visible goals with the `omitted` tactic\n\n- `tidy_omitted` runs `tidy` and lets it use `omitted` (and still produces proof traces).\n  `tidy_omitted` will always attempt to split existential statements and sigma-types in the goal,   and will fill in as little data as possible (it is not allowed to use assumption,\n   solve_by_elim, simp, or dsimp)\n\n   if it has used `omitted`, `tidy` will emit a trace urging the user to replace\n   the call to `tidy_omitted` with the proof trace generated by\n   `tidy_omitted {trace_result := tt}\n-/\n\nimport tactic.tidy ..basic tactic.explode\n\nsection omitted_tactics\nopen tactic\n\n/-- Check if the goal is a proposition; if so, prove it using omitted.\n\n    When called with \"tidy using omitted\", tidy will run as usual and fulfill all\n    proof obligations using omitted, leaving it to the user to specify the data. -/\nmeta def tactic.interactive.omitted : tactic unit :=\n  propositional_goal >> `[exact omitted] <|> tactic.fail \"Goal is not a proposition and cannot be omitted\"\n\nmeta def tactic.interactive.omit_proofs : tactic unit := `[all_goals {try {omitted}}]\n\nmeta def tactic.verbose_omitted : tactic string :=\ntactic.interactive.omitted >> tactic.trace \"`tidy` used `omitted`, please replace this call to `tidy_omitted` with the output of {trace_result := tt}\"\n                           >> return \"omitted\"\n\nopen tactic.tidy\n\nmeta def omitted_default_tactics : list (tactic string) :=\n[ reflexivity                                 >> pure \"refl\",\n  `[exact dec_trivial]                        >> pure \"exact dec_trivial\",\n  -- propositional_goal >> assumption            >> pure \"assumption\",\n  ext1_wrapper,\n  intros1                                     >>= \u03bb ns, pure (\"intros \" ++ (\" \".intercalate (ns.map (\u03bb e, e.to_string)))),\n  auto_cases,\n  `[apply_auto_param]                         >> pure \"apply_auto_param\",\n  -- `[dsimp at *]                               >> pure \"dsimp at *\",\n  -- `[simp at *]                                >> pure \"simp at *\",\n  fsplit                                      >> pure \"fsplit\",\n  injections_and_clear                        >> pure \"injections_and_clear\",\n  -- propositional_goal >> (`[solve_by_elim])    >> pure \"solve_by_elim\",2\n\n  `[unfold_aux]                               >> pure \"unfold_aux\",--\n  -- tidy.run_tactics\n  tactic.verbose_omitted ]\n\nmeta structure omitted_cfg :=\n(trace_result : bool            := ff)\n(trace_result_prefix : string   := \"/- `tidy` says -/ \")\n(tactics : list (tactic string) := omitted_default_tactics)\n\nmeta def cfg_of_omitted_cfg : omitted_cfg \u2192 cfg :=\n\u03bb X, { trace_result := X.trace_result,\n  trace_result_prefix := X.trace_result_prefix,\n  tactics := X.tactics }\n\n/- Calls tidy, but with `omitted` thrown into the tactic list.\n\n  tidy {trace_result := tt}` produces a proof trace as usual.-/\nmeta def tactic.interactive.tidy_omitted (cfg : omitted_cfg := {}): tactic unit :=\ntidy (cfg_of_omitted_cfg cfg)\n\nend omitted_tactics\n\nsection depends_omitted_cmd\nopen tactic expr\n\nmeta def extract_proof_names_aux : \u2200(e : expr) (l : list name), tactic (list name)\n| (const a b) l := do b <- infer_type (const a b) >>= is_prop,\n                      if b then return (a::l) else return l\n| e l := return l\n\nmeta def extract_proof_names (e : expr) : tactic $ list name :=\n  e.mfold [] (\u03bb e n l\u2081, extract_proof_names_aux e l\u2081)\n\nmeta def depends_omitted_aux (n : name) : tactic expr :=\ndo const n _ \u2190 resolve_name n | fail \"cannot resolve name\",\n  d \u2190 get_decl n,\n  e \u2190 match d with\n  | (declaration.defn _ _ _ e _ _) := return e\n  | (declaration.thm _ _ _ e)      := return e.get\n  | _                  := fail \"not a definition\"\n  end, return e\n\nmeta def depends_omitted_aux' (n : name) : tactic expr :=\ndo const n _ \u2190 resolve_name n | fail \"cannot resolve name\",\n  d \u2190 get_decl n,\n  e \u2190 (match d with\n  | (declaration.defn _ _ _ e _ _) := return e\n  | (declaration.thm _ _ _ e)      := return e.get\n  | _                  := fail \"not a definition\"\n  end) <|> return expr.inhabited.default, return e\n\n\nmeta def depends_omitted (n : name) : tactic unit :=\ndo e <- depends_omitted_aux n,\n   o <- to_expr ``(omitted),\n   ls <- (extract_proof_names e) >>= \u03bb l, l.mmap depends_omitted_aux',\n   b_l <- ls.mfoldr (\u03bb e b, (kdepends_on e o) >>= return \u2218 (bor b)) ff,\n   b <- kdepends_on e o,\n   if (bor b b_l) then trace (n ++ \" directly depends on `omitted`\") else\n                       trace (n ++ \" does not directly depend on `omitted`\")\n\nopen interactive lean lean.parser interaction_monad.result\n\n@[user_command] meta def depends_omitted_cmd (_ : parse $ tk \"#depends_omitted\") : lean.parser unit :=\ndo n \u2190 ident,\n  depends_omitted n\n\nend depends_omitted_cmd\n\n/- Tests -/\n-- section test0\n-- lemma test : 1 + 1 = 2 := by omitted\n\n-- noncomputable def test' : \u2115 := classical.choice $ by omitted\n\n-- structure test_structure :=\n-- (x : \u2115)\n\n-- noncomputable def test'' : test_structure :=\n-- \u27e8test'\u27e9\n\n-- #depends_omitted test\n-- --test. directly depends on `omitted`\n\n-- #depends_omitted test'\n-- --test'. directly depends on `omitted`\n\n-- #depends_omitted test''\n-- --test''. does not directly depend on `omitted`\n\n-- end test0\n\n-- section test1\n\n-- variable {\u03b1 : Type*}\n-- variable (P : \u03b1 \u2192 Prop)\n-- variable (a : \u03b1)\n\n-- open vector\n\n-- example : vector \u03b1 1 \u2243 \u03b1 :=\n-- begin\n--  split, omit_proofs,\n--  from \u03bb x, \u27e8[x], dec_trivial\u27e9,\n--  from \u03bb x, x.head\n-- end\n\n-- /- In this example, (a : \u03b1) is in context, but `tidy_omitted` refuses to use it -/\n-- include a\n-- example : \u03a3' a : \u03b1, P a := -- by {tidy_omitted, exact a}\n-- by {/- `tidy` says -/ fsplit, work_on_goal 1 { omitted }, exact a}\n-- end test1\n\n-- section test2\n-- private def is_even (n : \u2115) := \u2203 k, 2 * k = n\n\n-- private lemma test : \u2203 m : \u2115, is_even m :=\n-- begin\n--  tidy_omitted, exact 2\n-- end\n\n-- private lemma test'' : \u2203 m, is_even m :=\n-- by {use 2, use 1, refl}\n\n-- -- #print test''\n\n-- -- #print test\n-- /-\n-- 92:1: theorem test : \u2203 (m : \u2115), is_even m :=\n-- id (Exists.intro (2 * 2) (Exists.intro 2 (eq.refl (2 * 2))))\n-- -/\n\n-- private lemma test' : \u2203 m, is_even m := by omitted\n\n-- -- #print test'\n-- /-\n-- 100:1: theorem hewwo' : \u2203 (m : \u2115), is_even m :=\n-- omitted\n-- -/\n\n-- end test2\n", "meta": {"author": "formalabstracts", "repo": "formalabstracts", "sha": "b0173da1af45421239d44492eeecd54bf65ee0f6", "save_path": "github-repos/lean/formalabstracts-formalabstracts", "path": "github-repos/lean/formalabstracts-formalabstracts/formalabstracts-b0173da1af45421239d44492eeecd54bf65ee0f6/src/tactic/omitted.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.10818896462614715, "lm_q1q2_score": 0.047784143595971336}}
{"text": "/-\nCopyright (c) 2021 S\u00e9bastien Gou\u00ebzel. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: S\u00e9bastien Gou\u00ebzel\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 \u03bc`, 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 {\u03b9 \u03b1 \u03b2 \u03b3 \u03b4 R : Type*} {m0 : measurable_space \u03b1} [measurable_space \u03b2]\n   [measurable_space \u03b3] [measurable_space \u03b4] {f g : \u03b1 \u2192 \u03b2} {\u03bc \u03bd : measure \u03b1}\n\ninclude m0\n\nsection\n\n@[nontriviality, measurability]\nlemma subsingleton.ae_measurable [subsingleton \u03b1] : ae_measurable f \u03bc :=\nsubsingleton.measurable.ae_measurable\n\n@[nontriviality, measurability]\nlemma ae_measurable_of_subsingleton_codomain [subsingleton \u03b2] : ae_measurable f \u03bc :=\n(measurable_of_subsingleton_codomain f).ae_measurable\n\n@[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure \u03b1) :=\nbegin\n  nontriviality \u03b1, inhabit \u03b1,\n  exact \u27e8\u03bb x, f default, measurable_const, rfl\u27e9\nend\n\nnamespace ae_measurable\n\nlemma mono_measure (h : ae_measurable f \u03bc) (h' : \u03bd \u2264 \u03bc) : ae_measurable f \u03bd :=\n\u27e8h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk\u27e9\n\n\n\nprotected lemma mono' (h : ae_measurable f \u03bc) (h' : \u03bd \u226a \u03bc) : ae_measurable f \u03bd :=\n\u27e8h.mk f, h.measurable_mk, h' h.ae_eq_mk\u27e9\n\nlemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (\u03bc.restrict s)) :\n  \u2200\u1d50 x \u2202\u03bc, x \u2208 s \u2192 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 (\u03bc.restrict s)) :\n  f =\u1da0[\u03bc.ae \u2293 \ud835\udcdf s] h.mk f :=\nle_ae_restrict h.ae_eq_mk\n\n@[measurability]\nlemma sum_measure [encodable \u03b9] {\u03bc : \u03b9 \u2192 measure \u03b1} (h : \u2200 i, ae_measurable f (\u03bc i)) :\n  ae_measurable f (sum \u03bc) :=\nbegin\n  nontriviality \u03b2, inhabit \u03b2,\n  set s : \u03b9 \u2192 set \u03b1 := \u03bb i, to_measurable (\u03bc i) {x | f x \u2260 (h i).mk f x},\n  have hs\u03bc : \u2200 i, \u03bc i (s i) = 0,\n  { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk },\n  have hsm : measurable_set (\u22c2 i, s i),\n    from measurable_set.Inter (\u03bb i, measurable_set_to_measurable _ _),\n  have hs : \u2200 i x, x \u2209 s i \u2192 f x = (h i).mk f x,\n  { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx },\n  set g : \u03b1 \u2192 \u03b2 := (\u22c2 i, s i).piecewise (const \u03b1 default) f,\n  refine \u27e8g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ \u03bb i, _\u27e9,\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 \u27e8\u22c3 i, ((h i).mk f \u207b\u00b9' t) \u2229 (s i)\u1d9c, measurable_set.Union $\n      \u03bb i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _\u27e9,\n    ext \u27e8x, hx\u27e9,\n    simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_eq,\n      mem_compl_iff] at hx \u22a2,\n    split,\n    { rintro \u27e8i, hxt, hxs\u27e9, rwa hs _ _ hxs },\n    { rcases hx with \u27e8i, hi\u27e9, rw hs _ _ hi, exact \u03bb h, \u27e8i, h, hi\u27e9 } },\n  { refine measure_mono_null (\u03bb x (hx : f x \u2260 g x), _) (hs\u03bc i),\n    contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm,\n    exact \u03bb h, hx (mem_Inter.1 h i) }\nend\n\n@[simp] lemma _root_.ae_measurable_sum_measure_iff [encodable \u03b9] {\u03bc : \u03b9 \u2192 measure \u03b1} :\n  ae_measurable f (sum \u03bc) \u2194 \u2200 i, ae_measurable f (\u03bc i) :=\n\u27e8\u03bb h i, h.mono_measure (le_sum _ _), sum_measure\u27e9\n\n@[simp] lemma _root_.ae_measurable_add_measure_iff :\n  ae_measurable f (\u03bc + \u03bd) \u2194 ae_measurable f \u03bc \u2227 ae_measurable f \u03bd :=\nby { rw [\u2190 sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl }\n\n@[measurability]\nlemma add_measure {f : \u03b1 \u2192 \u03b2} (h\u03bc : ae_measurable f \u03bc) (h\u03bd : ae_measurable f \u03bd) :\n  ae_measurable f (\u03bc + \u03bd) :=\nae_measurable_add_measure_iff.2 \u27e8h\u03bc, h\u03bd\u27e9\n\n@[measurability]\nprotected lemma Union [encodable \u03b9] {s : \u03b9 \u2192 set \u03b1} (h : \u2200 i, ae_measurable f (\u03bc.restrict (s i))) :\n  ae_measurable f (\u03bc.restrict (\u22c3 i, s i)) :=\n(sum_measure h).mono_measure $ restrict_Union_le\n\n@[simp] lemma _root_.ae_measurable_Union_iff [encodable \u03b9] {s : \u03b9 \u2192 set \u03b1} :\n  ae_measurable f (\u03bc.restrict (\u22c3 i, s i)) \u2194 \u2200 i, ae_measurable f (\u03bc.restrict (s i)) :=\n\u27e8\u03bb h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union\u27e9\n\n@[simp] lemma _root_.ae_measurable_union_iff {s t : set \u03b1} :\n  ae_measurable f (\u03bc.restrict (s \u222a t)) \u2194\n    ae_measurable f (\u03bc.restrict s) \u2227 ae_measurable f (\u03bc.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 \u211d\u22650\u221e] [is_scalar_tower R \u211d\u22650\u221e \u211d\u22650\u221e]\n  (h : ae_measurable f \u03bc) (c : R) :\n  ae_measurable f (c \u2022 \u03bc) :=\n\u27e8h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c\u27e9\n\nlemma comp_ae_measurable {f : \u03b1 \u2192 \u03b4} {g : \u03b4 \u2192 \u03b2}\n  (hg : ae_measurable g (\u03bc.map f)) (hf : ae_measurable f \u03bc) : ae_measurable (g \u2218 f) \u03bc :=\n\u27e8hg.mk g \u2218 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))\u27e9\n\nlemma comp_measurable {f : \u03b1 \u2192 \u03b4} {g : \u03b4 \u2192 \u03b2}\n  (hg : ae_measurable g (\u03bc.map f)) (hf : measurable f) : ae_measurable (g \u2218 f) \u03bc :=\nhg.comp_ae_measurable hf.ae_measurable\n\nlemma comp_measurable' {\u03bd : measure \u03b4} {f : \u03b1 \u2192 \u03b4} {g : \u03b4 \u2192 \u03b2} (hg : ae_measurable g \u03bd)\n  (hf : measurable f) (h : \u03bc.map f \u226a \u03bd) : ae_measurable (g \u2218 f) \u03bc :=\n(hg.mono' h).comp_measurable hf\n\nlemma map_map_of_ae_measurable {g : \u03b2 \u2192 \u03b3} {f : \u03b1 \u2192 \u03b2}\n  (hg : ae_measurable g (measure.map f \u03bc)) (hf : ae_measurable f \u03bc) :\n  (\u03bc.map f).map g = \u03bc.map (g \u2218 f) :=\nbegin\n  ext1 s hs,\n  let g' := hg.mk g,\n  have A : map g (map f \u03bc) = map g' (map f \u03bc),\n  { apply measure_theory.measure.map_congr,\n    exact hg.ae_eq_mk },\n  have B : map (g \u2218 f) \u03bc = map (g' \u2218 f) \u03bc,\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 : \u03b1 \u2192 \u03b2} {g : \u03b1 \u2192 \u03b3} (hf : ae_measurable f \u03bc) (hg : ae_measurable g \u03bc) :\n  ae_measurable (\u03bb x, (f x, g x)) \u03bc :=\n\u27e8\u03bb 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\u27e9\n\nlemma exists_ae_eq_range_subset (H : ae_measurable f \u03bc) {t : set \u03b2} (ht : \u2200\u1d50 x \u2202\u03bc, f x \u2208 t)\n  (h\u2080 : t.nonempty) :\n  \u2203 g, measurable g \u2227 range g \u2286 t \u2227 f =\u1d50[\u03bc] g :=\nbegin\n  let s : set \u03b1 := to_measurable \u03bc {x | f x = H.mk f x \u2227 f x \u2208 t}\u1d9c,\n  let g : \u03b1 \u2192 \u03b2 := piecewise s (\u03bb x, h\u2080.some) (H.mk f),\n  refine \u27e8g, _, _, _\u27e9,\n  { exact measurable.piecewise (measurable_set_to_measurable _ _)\n      measurable_const H.measurable_mk },\n  { rintros _ \u27e8x, rfl\u27e9,\n    by_cases hx : x \u2208 s,\n    { simpa [g, hx] using h\u2080.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 : \u03bc (to_measurable \u03bc {x | f x = H.mk f x \u2227 f x \u2208 t}\u1d9c) = 0,\n    { rw [measure_to_measurable, \u2190 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 \u03bc) {s : set \u03b2} {hfs : \u2200 x, f x \u2208 s} :\n  ae_measurable (cod_restrict f s hfs) \u03bc :=\nbegin\n  nontriviality \u03b1, inhabit \u03b1,\n  obtain \u27e8g, g_meas, hg, fg\u27e9 : \u2203 (g : \u03b1 \u2192 \u03b2), measurable g \u2227 range g \u2286 s \u2227 f =\u1d50[\u03bc] g :=\n    h.exists_ae_eq_range_subset (eventually_of_forall hfs) \u27e8_, hfs default\u27e9,\n  refine \u27e8cod_restrict g s (\u03bb x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _\u27e9,\n  filter_upwards [fg] with x hx,\n  simpa [subtype.ext_iff],\nend\n\nprotected lemma null_measurable (h : ae_measurable f \u03bc) : null_measurable f \u03bc :=\nlet \u27e8g, hgm, hg\u27e9 := h in hgm.null_measurable.congr hg.symm\n\nend ae_measurable\n\nlemma ae_measurable_interval_oc_iff [linear_order \u03b1] {f : \u03b1 \u2192 \u03b2} {a b : \u03b1} :\n  (ae_measurable f $ \u03bc.restrict $ \u0399 a b) \u2194\n    (ae_measurable f $ \u03bc.restrict $ Ioc a b) \u2227 (ae_measurable f $ \u03bc.restrict $ Ioc b a) :=\nby rw [interval_oc_eq_union, ae_measurable_union_iff]\n\nlemma ae_measurable_iff_measurable [\u03bc.is_complete] :\n  ae_measurable f \u03bc \u2194 measurable f :=\n\u27e8\u03bb h, h.null_measurable.measurable_of_complete, \u03bb h, h.ae_measurable\u27e9\n\nlemma measurable_embedding.ae_measurable_map_iff {g : \u03b2 \u2192 \u03b3} (hf : measurable_embedding f) :\n  ae_measurable g (\u03bc.map f) \u2194 ae_measurable (g \u2218 f) \u03bc :=\nbegin\n  refine \u27e8\u03bb H, H.comp_measurable hf.measurable, _\u27e9,\n  rintro \u27e8g\u2081, hgm\u2081, heq\u27e9,\n  rcases hf.exists_measurable_extend hgm\u2081 (\u03bb x, \u27e8g x\u27e9) with \u27e8g\u2082, hgm\u2082, rfl\u27e9,\n  exact \u27e8g\u2082, hgm\u2082, hf.ae_map_iff.2 heq\u27e9\nend\n\nlemma measurable_embedding.ae_measurable_comp_iff {g : \u03b2 \u2192 \u03b3}\n  (hg : measurable_embedding g) {\u03bc : measure \u03b1} :\n  ae_measurable (g \u2218 f) \u03bc \u2194 ae_measurable f \u03bc :=\nbegin\n  refine \u27e8\u03bb H, _, hg.measurable.comp_ae_measurable\u27e9,\n  suffices : ae_measurable ((range_splitting g \u2218 range_factorization g) \u2218 f) \u03bc,\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 \u03b1} (hs : measurable_set s)\n  {\u03bc : measure \u03b1} {f : \u03b1 \u2192 \u03b2} :\n  ae_measurable f (\u03bc.restrict s) \u2194 ae_measurable (f \u2218 coe : s \u2192 \u03b2) (comap coe \u03bc) :=\nby rw [\u2190 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 \u03b2] : ae_measurable (\u03bb a : \u03b1, (1 : \u03b2)) \u03bc :=\nmeasurable_one.ae_measurable\n\n@[simp] lemma ae_measurable_smul_measure_iff {c : \u211d\u22650\u221e} (hc : c \u2260 0) :\n  ae_measurable f (c \u2022 \u03bc) \u2194 ae_measurable f \u03bc :=\n\u27e8\u03bb h, \u27e8h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk\u27e9,\n  \u03bb h, \u27e8h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk\u27e9\u27e9\n\nlemma ae_measurable_of_ae_measurable_trim {\u03b1} {m m0 : measurable_space \u03b1}\n  {\u03bc : measure \u03b1} (hm : m \u2264 m0) {f : \u03b1 \u2192 \u03b2} (hf : ae_measurable f (\u03bc.trim hm)) :\n  ae_measurable f \u03bc :=\n\u27e8hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk\u27e9\n\nlemma ae_measurable_restrict_of_measurable_subtype {s : set \u03b1}\n  (hs : measurable_set s) (hf : measurable (\u03bb x : s, f x)) : ae_measurable f (\u03bc.restrict s) :=\n(ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable\n\nlemma ae_measurable_map_equiv_iff (e : \u03b1 \u2243\u1d50 \u03b2) {f : \u03b2 \u2192 \u03b3} :\n  ae_measurable f (\u03bc.map e) \u2194 ae_measurable (f \u2218 e) \u03bc :=\ne.measurable_embedding.ae_measurable_map_iff\n\nend\n\nlemma ae_measurable.restrict (hfm : ae_measurable f \u03bc) {s} :\n  ae_measurable f (\u03bc.restrict s) :=\n\u27e8ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk\u27e9\n\nvariables [has_zero \u03b2]\n\nlemma ae_measurable_indicator_iff {s} (hs : measurable_set s) :\n  ae_measurable (indicator s f) \u03bc \u2194 ae_measurable f (\u03bc.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 \u27e8indicator s (h.mk f), h.measurable_mk.indicator hs, _\u27e9,\n    have A : s.indicator f =\u1d50[\u03bc.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 =\u1d50[\u03bc.restrict s\u1d9c] 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 \u03bc) {s} (hs : measurable_set s) :\n  ae_measurable (s.indicator f) \u03bc :=\n(ae_measurable_indicator_iff hs).mpr hfm.restrict\n\nlemma measure_theory.measure.restrict_map_of_ae_measurable\n  {f : \u03b1 \u2192 \u03b4} (hf : ae_measurable f \u03bc) {s : set \u03b4} (hs : measurable_set s) :\n  (\u03bc.map f).restrict s = (\u03bc.restrict $ f \u207b\u00b9' s).map f :=\ncalc\n(\u03bc.map f).restrict s = (\u03bc.map (hf.mk f)).restrict s :\n  by { congr' 1, apply measure.map_congr hf.ae_eq_mk }\n... = (\u03bc.restrict $ (hf.mk f) \u207b\u00b9' s).map (hf.mk f) :\n  measure.restrict_map hf.measurable_mk hs\n... = (\u03bc.restrict $ (hf.mk f) \u207b\u00b9' s).map f :\n  measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm))\n... = (\u03bc.restrict $ f \u207b\u00b9' 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 : \u03b1 \u2192 \u03b4} (h : \u03bc \u2264 \u03bd) (hf : ae_measurable f \u03bd) :\n  \u03bc.map f \u2264 \u03bd.map f :=\n\u03bb s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f \u207b\u00b9' 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 \u226b bar = baz := ...\n```\n\nand produce\n\n```lean\nlemma some_lemma_assoc {Y : C} (f : X \u27f6 Y) : foo \u226b bar \u226b f = baz \u226b 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 : \u03a0 X : C, X \u27f6 X)\n(bar : \u2200 {X Y : C} (f : X \u27f6 Y), foo X \u226b f = f \u226b 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 \u226b g`, extract the expression representing the category instance. -/\nmeta def get_cat_inst : expr \u2192 tactic expr\n| `(@category_struct.comp _ %%struct_inst _ _ _ _ _) := pure struct_inst\n| _ := failed\n\n/-- (internals for `@[reassoc]`)\nGiven a lemma of the form `\u2200 ..., f \u226b g = h`, proves a new lemma of the form\n`h : \u2200 ... {W} (k), f \u226b (g \u226b k) = h \u226b k`, and returns the type and proof of this lemma.\n-/\nmeta def prove_reassoc (h : expr) : tactic (expr \u00d7 expr) :=\ndo\n   (vs,t) \u2190 infer_type h >>= open_pis,\n   (lhs,rhs) \u2190 match_eq t,\n   struct_inst \u2190 get_cat_inst lhs <|> get_cat_inst rhs <|> fail \"no composition found in statement\",\n   `(@quiver.hom _ %%hom_inst %%X %%Y) \u2190 infer_type lhs,\n   C \u2190 infer_type X,\n   X' \u2190 mk_local' `X' binder_info.implicit C,\n   ft \u2190 to_expr ``(@quiver.hom _ %%hom_inst %%Y %%X'),\n   f' \u2190 mk_local_def `f' ft,\n   t' \u2190 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) \u2190 solve_aux t' (rewrite_target c'; reflexivity),\n   pr \u2190 instantiate_mvars pr,\n   let s := simp_lemmas.mk,\n   s \u2190 s.add_simp ``category.assoc,\n   s \u2190 s.add_simp ``category.id_comp,\n   s \u2190 s.add_simp ``category.comp_id,\n   (t'', pr', _) \u2190 simplify s [] t',\n   pr' \u2190 mk_eq_mp pr' pr,\n   t'' \u2190 pis (vs ++ [X',f']) t'',\n   pr' \u2190 lambdas (vs ++ [X',f']) pr',\n   pure (t'',pr')\n\n/-- (implementation for `@[reassoc]`)\nGiven a declaration named `n` of the form `\u2200 ..., f \u226b g = h`, proves a new lemma named `n'`\nof the form `\u2200 ... {W} (k), f \u226b (g \u226b k) = h \u226b k`.\n-/\nmeta def reassoc_axiom (n : name) (n' : name := n.append_suffix \"_assoc\") : tactic unit :=\ndo d \u2190 get_decl n,\n   let ls := d.univ_params.map level.param,\n   let c := @expr.const tt n ls,\n   (t'',pr') \u2190 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 \u226b bar = baz := ...\n```\n\nto produce\n\n```lean\nlemma some_lemma_assoc {Y : C} (f : X \u27f6 Y) : foo \u226b bar \u226b f = baz \u226b 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 (\u03bb n _ _,\n    do some n' \u2190 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 : \u03a0 X : C, X \u27f6 X)\n(bar : \u2200 {X Y : C} (f : X \u27f6 Y), foo X \u226b f = f \u226b 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 \u27f6 Z) :\n  foo X \u226b f \u226b g = f \u226b foo Y \u226b 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 \u2190 ident,\n   of_tactic $\n   do n \u2190 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 \u226b y = z`, creates a new assumption\n`h : \u2200 {W} (f : Z \u27f6 W), x \u226b y \u226b f = z \u226b 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' (\u03bb n,\n   do h \u2190 get_local n,\n      (t,pr) \u2190 prove_reassoc h,\n      assertv n t pr,\n      when del.is_some (tactic.clear h) )\n\nend interactive\n\ndef calculated_Prop {\u03b1} (\u03b2 : Prop) (hh : \u03b1) := \u03b2\n\nmeta def derive_reassoc_proof : tactic unit :=\ndo `(calculated_Prop %%v %%h) \u2190 target,\n   (t,pr) \u2190 prove_reassoc h,\n   unify v t,\n   exact pr\n\nend tactic\n\n/-- With `h : x \u226b y \u226b z = x` (with universal quantifiers tolerated),\n`reassoc_of h : \u2200 {X'} (f : W \u27f6 X'), x \u226b y \u226b z \u226b f = x \u226b 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 \u27f6 Y) (y : Y \u27f6 Z) (z z' : Z \u27f6 W) (w : X \u27f6 Z)\n  (h : x \u226b y = w)\n  (h' : y \u226b z = y \u226b z') :\n  x \u226b y \u226b z = w \u226b z' :=\nbegin\n  rw [h',reassoc_of h],\nend\n```\n-/\ntheorem category_theory.reassoc_of {\u03b1} (hh : \u03b1) {\u03b2}\n  (x : tactic.calculated_Prop \u03b2 hh . tactic.derive_reassoc_proof) : \u03b2 := x\n\n/--\n`reassoc_of h` takes local assumption `h` and add a ` \u226b 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 \u27f6 Y) (y : Y \u27f6 Z) (z z' : Z \u27f6 W) (w : X \u27f6 Z)\n  (h : x \u226b y = w)\n  (h' : y \u226b z = y \u226b z') :\n  x \u226b y \u226b z = w \u226b z' :=\nbegin\n  -- reassoc_of h : \u2200 {X' : C} (f : W \u27f6 X'), x \u226b y \u226b f = w \u226b 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 {\u03b1 : Type _} [DecidableEq \u03b1]\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 : \u2200 (xs : List \u03b1) (x default : \u03b1), \u03b1\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 : \u03b1) : 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 : \u03b1) : 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 \u03b1) (x y d : \u03b1) : 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 \u03b1) (y x d : \u03b1) (h : x \u2260 y) :\n    nextOr (y :: xs) x d = nextOr xs x d :=\n  by\n  cases' xs with z zs\n  \u00b7 rfl\n  \u00b7 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 \u03b1) (x d d' : \u03b1) (x_mem : x \u2208 xs)\n    (x_ne : x \u2260 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  \u00b7 cases x_mem\n  cases' ys with z zs\n  \u00b7 simp at x_mem x_ne\n    contradiction\n  by_cases h : x = y\n  \u00b7 rw [h, next_or_self_cons_cons, next_or_self_cons_cons]\n  \u00b7 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 \u03b1} {x d : \u03b1} (h : nextOr xs x d \u2260 d) : x \u2208 xs :=\n  by\n  induction' xs with y ys IH\n  \u00b7 simpa using h\n  cases' ys with z zs\n  \u00b7 simpa using h\n  \u00b7 by_cases hx : x = y\n    \u00b7 simp [hx]\n    \u00b7 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 \u03b1} {x : \u03b1} (d : \u03b1) (h : x \u2209 xs) : nextOr (xs ++ [x]) x d = d :=\n  by\n  induction' xs with z zs IH\n  \u00b7 simp\n  \u00b7 obtain \u27e8hz, hzs\u27e9 := 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 \u03b1} {x d : \u03b1} (hd : d \u2208 xs) : nextOr xs x d \u2208 xs :=\n  by\n  revert hd\n  suffices \u2200 (xs' : List \u03b1) (h : \u2200 x \u2208 xs, x \u2208 xs') (hd : d \u2208 xs'), next_or xs x d \u2208 xs' by\n    exact this xs fun _ => id\n  intro xs' hxs' hd\n  induction' xs with y ys ih\n  \u00b7 exact hd\n  cases' ys with z zs\n  \u00b7 exact hd\n  rw [next_or]\n  split_ifs with h\n  \u00b7 exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _))\n  \u00b7 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 : \u03b1` of `l : list \u03b1` such that `x \u2208 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 \u03b1) (x : \u03b1) (h : x \u2208 l) : \u03b1 :=\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 : \u03b1` of `l : list \u03b1` such that `x \u2208 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 : \u2200 (l : List \u03b1) (x : \u03b1) (h : x \u2208 l), \u03b1\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 \u03b1) (x : \u03b1) (h : x \u2208 l)\n\n#print List.next_singleton /-\n@[simp]\ntheorem next_singleton (x y : \u03b1) (h : x \u2208 [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 : \u03b1) (h : x \u2208 [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 : \u03b1) (h : x \u2208 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 : \u03b1) (h : x \u2208 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 {\u03b1 : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} \u03b1] (l : List.{u1} \u03b1) (x : \u03b1) (y : \u03b1) (h : Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x (List.cons.{u1} \u03b1 y l)) (hy : Ne.{succ u1} \u03b1 x y), (Ne.{succ u1} \u03b1 x (List.getLast.{u1} \u03b1 (List.cons.{u1} \u03b1 y l) (List.cons_ne_nil.{u1} \u03b1 y l))) -> (Eq.{succ u1} \u03b1 (List.next.{u1} \u03b1 (fun (a : \u03b1) (b : \u03b1) => _inst_1 a b) (List.cons.{u1} \u03b1 y l) x h) (List.next.{u1} \u03b1 (fun (a : \u03b1) (b : \u03b1) => _inst_1 a b) l x (Eq.mpr.{0} (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (id_tag Tactic.IdTag.simp (Eq.{1} Prop (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)) (rfl.{1} Prop (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l))) (Eq.mp.{0} (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x (List.cons.{u1} \u03b1 y l)) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (Eq.trans.{1} Prop (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x (List.cons.{u1} \u03b1 y l)) (Or False (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (Eq.trans.{1} Prop (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x (List.cons.{u1} \u03b1 y l)) (Or (Eq.{succ u1} \u03b1 x y) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)) (Or False (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)) (propext (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x (List.cons.{u1} \u03b1 y l)) (Or (Eq.{succ u1} \u03b1 x y) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)) (List.mem_cons.{u1} \u03b1 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} \u03b1 x y) False (propext (Eq.{succ u1} \u03b1 x y) False (iff_false_intro (Eq.{succ u1} \u03b1 x y) hy)) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (rfl.{1} Prop (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)))) (propext (Or False (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)) (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l) (false_or_iff (Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x l)))) h))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} \u03b1] (l : List.{u1} \u03b1) (x : \u03b1), (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l) -> (forall (h : \u03b1) (hy : Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x (List.cons.{u1} \u03b1 h l)) (hx : Ne.{succ u1} \u03b1 x h), (Ne.{succ u1} \u03b1 x (List.getLast.{u1} \u03b1 (List.cons.{u1} \u03b1 h l) (List.cons_ne_nil.{u1} \u03b1 h l))) -> (Eq.{succ u1} \u03b1 (List.next.{u1} \u03b1 (fun (a : \u03b1) (b : \u03b1) => _inst_1 a b) (List.cons.{u1} \u03b1 h l) x hy) (List.next.{u1} \u03b1 (fun (a : \u03b1) (b : \u03b1) => _inst_1 a b) l x (Eq.mp.{0} (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x (List.cons.{u1} \u03b1 h l)) (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l) (Eq.trans.{1} Prop (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x (List.cons.{u1} \u03b1 h l)) (Or False (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l)) (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l) (Eq.trans.{1} Prop (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x (List.cons.{u1} \u03b1 h l)) (Or (Eq.{succ u1} \u03b1 x h) (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l)) (Or False (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l)) (Std.Data.List.Lemmas._auxLemma.2.{u1} \u03b1 x h l) (congrFun.{1, 1} Prop (fun (b : Prop) => Prop) (Or (Eq.{succ u1} \u03b1 x h)) (Or False) (congrArg.{1, 1} Prop (Prop -> Prop) (Eq.{succ u1} \u03b1 x h) False Or (eq_false (Eq.{succ u1} \u03b1 x h) hx)) (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l))) (false_or (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l))) hy))))\nCase conversion may be inaccurate. Consider using '#align list.next_ne_head_ne_last List.next_ne_head_ne_getLast\u2093'. -/\ntheorem next_ne_head_ne_getLast (y : \u03b1) (h : x \u2208 y :: l) (hy : x \u2260 y)\n    (hx : x \u2260 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  \u00b7 rwa [last_cons] at hx\n  \u00b7 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 : \u03b1) (hy : x \u2260 y) (hx : x \u2209 l)\n    (h : x \u2208 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  \u00b7 rfl\n  \u00b7 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 {\u03b1 : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} \u03b1] (l : List.{u1} \u03b1) (x : \u03b1) (y : \u03b1) (h : Membership.Mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.hasMem.{u1} \u03b1) x (List.cons.{u1} \u03b1 y l)), (Ne.{succ u1} \u03b1 x y) -> (Eq.{succ u1} \u03b1 x (List.getLast.{u1} \u03b1 (List.cons.{u1} \u03b1 y l) (List.cons_ne_nil.{u1} \u03b1 y l))) -> (List.Nodup.{u1} \u03b1 l) -> (Eq.{succ u1} \u03b1 (List.next.{u1} \u03b1 (fun (a : \u03b1) (b : \u03b1) => _inst_1 a b) (List.cons.{u1} \u03b1 y l) x h) y)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} \u03b1] (l : List.{u1} \u03b1) (x : \u03b1), (Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x l) -> (forall (h : \u03b1) (hy : Membership.mem.{u1, u1} \u03b1 (List.{u1} \u03b1) (List.instMembershipList.{u1} \u03b1) x (List.cons.{u1} \u03b1 h l)), (Ne.{succ u1} \u03b1 x h) -> (Eq.{succ u1} \u03b1 x (List.getLast.{u1} \u03b1 (List.cons.{u1} \u03b1 h l) (List.cons_ne_nil.{u1} \u03b1 h l))) -> (List.Nodup.{u1} \u03b1 l) -> (Eq.{succ u1} \u03b1 (List.next.{u1} \u03b1 (fun (a : \u03b1) (b : \u03b1) => _inst_1 a b) (List.cons.{u1} \u03b1 h l) x hy) h))\nCase conversion may be inaccurate. Consider using '#align list.next_last_cons List.next_getLast_cons\u2093'. -/\ntheorem next_getLast_cons (y : \u03b1) (h : x \u2208 y :: l) (hy : x \u2260 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, \u2190 init_append_last (cons_ne_nil y l), hx, next_or_concat]\n  subst hx\n  intro H\n  obtain \u27e8_ | k, hk, hk'\u27e9 := nth_le_of_mem H\n  \u00b7 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  \u00b7 simpa using hk\n  \u00b7 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 : \u03b1) (h : x \u2208 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 \u2208 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 : \u03b1) (h : x \u2208 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 : \u03b1) (h : x \u2208 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 : \u03b1) (h : x \u2208 y :: z :: l) (hy : x \u2260 y) (hz : x = z) :\n    prev (y :: z :: l) x h = y := by\n  cases l\n  \u00b7 simp [prev, hy, hz]\n  \u00b7 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 : \u03b1) (h : x \u2208 y :: x :: l) (hy : x \u2260 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 : \u03b1) (h : x \u2208 y :: z :: l) (hy : x \u2260 y) (hz : x \u2260 z) :\n    prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) :=\n  by\n  cases l\n  \u00b7 simpa [hy, hz] using h\n  \u00b7 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 \u2208 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 \u2208 l := by\n  cases' l with hd tl\n  \u00b7 simpa using h\n  induction' tl with hd' tl hl generalizing hd\n  \u00b7 simp\n  \u00b7 by_cases hx : x = hd\n    \u00b7 simp only [hx, prev_cons_cons_eq]\n      exact mem_cons_of_mem _ (last_mem _)\n    \u00b7 rw [prev, dif_neg hx]\n      split_ifs with hm\n      \u00b7 exact mem_cons_self _ _\n      \u00b7 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 \u03b1) (h : Nodup l) (n : \u2115) (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  \u00b7 simpa using hn\n  induction' l with y l hl generalizing x n\n  \u00b7 simp\n  \u00b7 cases n\n    \u00b7 simp\n    \u00b7 have hn' : n.succ \u2264 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 \u2260 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      \u00b7 rw [next_last_cons]\n        \u00b7 simp [hn'']\n        \u00b7 exact hx'\n        \u00b7 simp [last_eq_nth_le, hn'']\n        \u00b7 exact h.of_cons\n      \u00b7 have : n < l.length := by simpa [Nat.succ_lt_succ_iff] using hn''\n        rw [next_ne_head_ne_last _ _ _ _ hx']\n        \u00b7\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        \u00b7 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          \u00b7 simp\n          \u00b7 simpa using H\n#align list.next_nth_le List.next_nthLe\n-/\n\n#print List.prev_nthLe /-\ntheorem prev_nthLe (l : List \u03b1) (h : Nodup l) (n : \u2115) (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  \u00b7 simpa using hn\n  induction' l with y l hl generalizing n x\n  \u00b7 simp\n  \u00b7 rcases n with (_ | _ | n)\n    \u00b7 simpa [last_eq_nth_le, Nat.mod_eq_of_lt (Nat.succ_lt_succ l.length.lt_succ_self)]\n    \u00b7 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    \u00b7 rw [prev_ne_cons_cons]\n      \u00b7 convert hl _ _ h.of_cons _ using 1\n        have : \u2200 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, \u2190 Nat.add_succ, Nat.add_mod_right, Nat.succ_add, \u2190 Nat.add_succ _ k,\n          Nat.add_mod_right, Nat.mod_eq_of_lt, Nat.mod_eq_of_lt]\n        \u00b7 exact Nat.lt_succ_of_lt hn\n        \u00b7 exact Nat.succ_lt_succ (Nat.lt_succ_of_lt hn)\n      \u00b7 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      \u00b7 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  \u00b7 simp\n  \u00b7 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  \u00b7 simp\n  \u00b7 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 \u03b1) (h : Nodup l) (x : \u03b1) (hx : x \u2208 l) :\n    prev l (next l x hx) (next_mem _ _ _) = x :=\n  by\n  obtain \u27e8n, hn, rfl\u27e9 := 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  \u00b7 simp\n  \u00b7 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 \u03b1) (h : Nodup l) (x : \u03b1) (hx : x \u2208 l) :\n    next l (prev l x hx) (prev_mem _ _ _) = x :=\n  by\n  obtain \u27e8n, hn, rfl\u27e9 := 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  \u00b7 simp\n  \u00b7 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 \u03b1) (h : Nodup l) (x : \u03b1) (hx : x \u2208 l) :\n    prev l.reverse x (mem_reverse'.mpr hx) = next l x hx :=\n  by\n  obtain \u27e8k, hk, rfl\u27e9 := 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 [\u2190 nth_le_pmap l.next (fun _ h => h) (by simpa using hk)]\n  simp_rw [\u2190 nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h]\n  rw [\u2190 nth_le_pmap l.reverse.prev fun _ h => h]\n  \u00b7 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 [\u2190 nth_le_reverse]\n    \u00b7 simp [tsub_tsub_cancel_of_le (Nat.le_pred_of_lt hk)]\n    \u00b7 simpa using (Nat.sub_le _ _).trans_lt (tsub_lt_self lpos Nat.succ_pos')\n  \u00b7 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 \u03b1) (h : Nodup l) (x : \u03b1) (hx : x \u2208 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 \u03b1} (h : l ~r l') (hn : Nodup l) {x : \u03b1} (hx : x \u2208 l) :\n    l.next x hx = l'.next x (h.mem_iff.mp hx) :=\n  by\n  obtain \u27e8k, hk, rfl\u27e9 := nth_le_of_mem hx\n  obtain \u27e8n, rfl\u27e9 := id h\n  rw [next_nth_le _ hn]\n  simp_rw [\u2190 nth_le_rotate' _ n k]\n  rw [next_nth_le _ (h.nodup_iff.mp hn), \u2190 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 \u03b1} (h : l ~r l') (hn : Nodup l) {x : \u03b1} (hx : x \u2208 l) :\n    l.prev x hx = l'.prev x (h.mem_iff.mp hx) :=\n  by\n  rw [\u2190 next_reverse_eq_prev _ hn, \u2190 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 \u03b1` is the quotient of `list \u03b1` by cyclic permutation.\nDuplicates are allowed.\n-/\ndef Cycle (\u03b1 : Type _) : Type _ :=\n  Quotient (IsRotated.setoid \u03b1)\n#align cycle Cycle\n-/\n\nnamespace Cycle\n\nvariable {\u03b1 : Type _}\n\ninstance : Coe (List \u03b1) (Cycle \u03b1) :=\n  \u27e8Quot.mk _\u27e9\n\n#print Cycle.coe_eq_coe /-\n@[simp]\ntheorem coe_eq_coe {l\u2081 l\u2082 : List \u03b1} : (l\u2081 : Cycle \u03b1) = l\u2082 \u2194 l\u2081 ~r l\u2082 :=\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 \u03b1) : Quot.mk _ l = (l : Cycle \u03b1) :=\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 \u03b1) : Quotient.mk'' l = (l : Cycle \u03b1) :=\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 \u03b1) (a : \u03b1) : (\u2191(a :: l) : Cycle \u03b1) = \u2191(l ++ [a]) :=\n  Quot.sound \u27e81, by rw [rotate_cons_succ, rotate_zero]\u27e9\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 \u03b1 :=\n  ([] : List \u03b1)\n#align cycle.nil Cycle.nil\n-/\n\n#print Cycle.coe_nil /-\n@[simp]\ntheorem coe_nil : \u2191([] : List \u03b1) = @nil \u03b1 :=\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 \u03b1) : (l : Cycle \u03b1) = nil \u2194 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 \u03b1) :=\n  \u27e8nil\u27e9\n\n#print Cycle.empty_eq /-\n@[simp]\ntheorem empty_eq : \u2205 = @nil \u03b1 :=\n  rfl\n#align cycle.empty_eq Cycle.empty_eq\n-/\n\ninstance : Inhabited (Cycle \u03b1) :=\n  \u27e8nil\u27e9\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 \u03b1 \u2192 Prop} (s : Cycle \u03b1) (H0 : C nil)\n    (HI : \u2200 (a) (l : List \u03b1), C \u2191l \u2192 C \u2191(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 : \u03b1`, `s : cycle \u03b1`, `x \u2208 s` indicates that `x` occurs at least once in `s`. -/\ndef Mem (a : \u03b1) (s : Cycle \u03b1) : Prop :=\n  Quot.liftOn s (fun l => a \u2208 l) fun l\u2081 l\u2082 e => propext <| e.mem_iff\n#align cycle.mem Cycle.Mem\n-/\n\ninstance : Membership \u03b1 (Cycle \u03b1) :=\n  \u27e8Mem\u27e9\n\n#print Cycle.mem_coe_iff /-\n@[simp]\ntheorem mem_coe_iff {a : \u03b1} {l : List \u03b1} : a \u2208 (l : Cycle \u03b1) \u2194 a \u2208 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 : \u2200 a, a \u2209 @nil \u03b1 :=\n  not_mem_nil\n#align cycle.not_mem_nil Cycle.not_mem_nil\n-/\n\ninstance [DecidableEq \u03b1] : DecidableEq (Cycle \u03b1) := fun s\u2081 s\u2082 =>\n  Quotient.recOnSubsingleton\u2082' s\u2081 s\u2082 fun l\u2081 l\u2082 => decidable_of_iff' _ Quotient.eq''\n\ninstance [DecidableEq \u03b1] (x : \u03b1) (s : Cycle \u03b1) : Decidable (x \u2208 s) :=\n  Quotient.recOnSubsingleton' s fun l => List.decidableMem x l\n\n#print Cycle.reverse /-\n/-- Reverse a `s : cycle \u03b1` by reversing the underlying `list`. -/\ndef reverse (s : Cycle \u03b1) : Cycle \u03b1 :=\n  Quot.map reverse (fun l\u2081 l\u2082 => IsRotated.reverse) s\n#align cycle.reverse Cycle.reverse\n-/\n\n#print Cycle.reverse_coe /-\n@[simp]\ntheorem reverse_coe (l : List \u03b1) : (l : Cycle \u03b1).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 : \u03b1} {s : Cycle \u03b1} : a \u2208 s.reverse \u2194 a \u2208 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 \u03b1) : 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 \u03b1 :=\n  rfl\n#align cycle.reverse_nil Cycle.reverse_nil\n-/\n\n#print Cycle.length /-\n/-- The length of the `s : cycle \u03b1`, which is the number of elements, counting duplicates. -/\ndef length (s : Cycle \u03b1) : \u2115 :=\n  Quot.liftOn s length fun l\u2081 l\u2082 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 \u03b1) : length (l : Cycle \u03b1) = 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 \u03b1) = 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 \u03b1) : 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 \u03b1` that is at most one element. -/\ndef Subsingleton (s : Cycle \u03b1) : Prop :=\n  s.length \u2264 1\n#align cycle.subsingleton Cycle.Subsingleton\n-/\n\n#print Cycle.subsingleton_nil /-\ntheorem subsingleton_nil : Subsingleton (@nil \u03b1) :=\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 \u03b1} : Subsingleton s \u2194 length s \u2264 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 \u03b1} : s.reverse.Subsingleton \u2194 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 \u03b1} (h : Subsingleton s) :\n    \u2200 \u2983x\u2984 (hx : x \u2208 s) \u2983y\u2984 (hy : y \u2208 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 | \u27e8z, rfl\u27e9) <;> simp\n#align cycle.subsingleton.congr Cycle.Subsingleton.congr\n-/\n\n#print Cycle.Nontrivial /-\n/-- A `s : cycle \u03b1` that is made up of at least two unique elements. -/\ndef Nontrivial (s : Cycle \u03b1) : Prop :=\n  \u2203 (x y : \u03b1)(h : x \u2260 y), x \u2208 s \u2227 y \u2208 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 \u03b1} (hl : l.Nodup) :\n    Nontrivial (l : Cycle \u03b1) \u2194 2 \u2264 l.length :=\n  by\n  rw [Nontrivial]\n  rcases l with (_ | \u27e8hd, _ | \u27e8hd', tl\u27e9\u27e9)\n  \u00b7 simp\n  \u00b7 simp\n  \u00b7 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' \u27e8hd, hd', _, by simp\u27e9\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 \u03b1} : s.reverse.Nontrivial \u2194 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 \u03b1} (h : Nontrivial s) : 2 \u2264 length s :=\n  by\n  obtain \u27e8x, y, hxy, hx, hy\u27e9 := h\n  induction' s using Quot.inductionOn with l\n  rcases l with (_ | \u27e8hd, _ | \u27e8hd', tl\u27e9\u27e9)\n  \u00b7 simpa using hx\n  \u00b7 simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy\n    simpa [hx, hy] using hxy\n  \u00b7 simp [bit0]\n#align cycle.length_nontrivial Cycle.length_nontrivial\n-/\n\n#print Cycle.Nodup /-\n/-- The `s : cycle \u03b1` contains no duplicates. -/\ndef Nodup (s : Cycle \u03b1) : Prop :=\n  Quot.liftOn s Nodup fun l\u2081 l\u2082 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 \u03b1) :=\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 \u03b1} : Nodup (l : Cycle \u03b1) \u2194 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 \u03b1} : s.reverse.Nodup \u2194 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 \u03b1} (h : Subsingleton s) : Nodup s :=\n  by\n  induction' s using Quot.inductionOn with l\n  cases' l with hd tl\n  \u00b7 simp\n  \u00b7 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 \u03b1} (h : Nodup s) : Nontrivial s \u2194 \u00acSubsingleton 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 \u03b1` as a `multiset \u03b1`.\n-/\ndef toMultiset (s : Cycle \u03b1) : Multiset \u03b1 :=\n  Quotient.liftOn' s coe fun l\u2081 l\u2082 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 \u03b1) : (l : Cycle \u03b1).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 \u03b1) :=\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 {\u03b1 : Type.{u1}} (s : Cycle.{u1} \u03b1), Eq.{1} Nat (coeFn.{succ u1, succ u1} (AddMonoidHom.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.orderedCancelAddCommMonoid.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (fun (_x : AddMonoidHom.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.orderedCancelAddCommMonoid.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) => (Multiset.{u1} \u03b1) -> Nat) (AddMonoidHom.hasCoeToFun.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.orderedCancelAddCommMonoid.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.card.{u1} \u03b1) (Cycle.toMultiset.{u1} \u03b1 s)) (Cycle.length.{u1} \u03b1 s)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (s : Cycle.{u1} \u03b1), Eq.{1} ((fun (x._@.Mathlib.Algebra.Hom.Group._hyg.403 : Multiset.{u1} \u03b1) => Nat) (Cycle.toMultiset.{u1} \u03b1 s)) (FunLike.coe.{succ u1, succ u1, 1} (AddMonoidHom.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.{u1} \u03b1) (fun (_x : Multiset.{u1} \u03b1) => (fun (x._@.Mathlib.Algebra.Hom.Group._hyg.403 : Multiset.{u1} \u03b1) => Nat) _x) (AddHomClass.toFunLike.{u1, u1, 0} (AddMonoidHom.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.{u1} \u03b1) Nat (AddZeroClass.toAdd.{u1} (Multiset.{u1} \u03b1) (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} \u03b1))))))) (AddZeroClass.toAdd.{0} Nat (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (AddMonoidHomClass.toAddHomClass.{u1, u1, 0} (AddMonoidHom.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid) (AddMonoidHom.addMonoidHomClass.{u1, 0} (Multiset.{u1} \u03b1) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} \u03b1) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} \u03b1) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} \u03b1) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} \u03b1) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} \u03b1)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)))) (Multiset.card.{u1} \u03b1) (Cycle.toMultiset.{u1} \u03b1 s)) (Cycle.length.{u1} \u03b1 s)\nCase conversion may be inaccurate. Consider using '#align cycle.card_to_multiset Cycle.card_toMultiset\u2093'. -/\n@[simp]\ntheorem card_toMultiset (s : Cycle \u03b1) : 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 \u03b1} : s.toMultiset = 0 \u2194 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 {\u03b2 : Type _} (f : \u03b1 \u2192 \u03b2) : Cycle \u03b1 \u2192 Cycle \u03b2 :=\n  Quotient.map' (List.map f) fun l\u2081 l\u2082 h => h.map _\n#align cycle.map Cycle.map\n-/\n\n#print Cycle.map_nil /-\n@[simp]\ntheorem map_nil {\u03b2 : Type _} (f : \u03b1 \u2192 \u03b2) : 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 {\u03b2 : Type _} (f : \u03b1 \u2192 \u03b2) (l : List \u03b1) : map f \u2191l = 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 {\u03b2 : Type _} (f : \u03b1 \u2192 \u03b2) (s : Cycle \u03b1) : map f s = nil \u2194 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 {\u03b2 : Type _} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} {s : Cycle \u03b1} :\n    b \u2208 s.map f \u2194 \u2203 a, a \u2208 s \u2227 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 \u03b1) : Multiset (List \u03b1) :=\n  Quotient.liftOn' s (fun l => (l.cyclicPermutations : Multiset (List \u03b1))) fun l\u2081 l\u2082 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 \u03b1) : lists (l : Cycle \u03b1) = \u2191l.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 \u03b1} {l : List \u03b1} : l \u2208 s.lists \u2194 (l : Cycle \u03b1) = 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 \u03b1) = [([] : List \u03b1)] := by\n  rw [nil, lists_coe, cyclic_permutations_nil]\n#align cycle.lists_nil Cycle.lists_nil\n-/\n\nsection Decidable\n\nvariable [DecidableEq \u03b1]\n\n#print Cycle.decidableNontrivialCoe /-\n/-- Auxiliary decidability algorithm for lists that contain at least two unique elements.\n-/\ndef decidableNontrivialCoe : \u2200 l : List \u03b1, Decidable (Nontrivial (l : Cycle \u03b1))\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 \u03b1)) (by simp [h, Nontrivial])\n        (decidable_nontrivial_coe (x :: l))\n    else isTrue \u27e8x, y, h, by simp, by simp\u27e9\n#align cycle.decidable_nontrivial_coe Cycle.decidableNontrivialCoe\n-/\n\ninstance {s : Cycle \u03b1} : Decidable (Nontrivial s) :=\n  Quot.recOnSubsingleton' s decidableNontrivialCoe\n\ninstance {s : Cycle \u03b1} : Decidable (Nodup s) :=\n  Quot.recOnSubsingleton' s List.nodupDecidable\n\n#print Cycle.fintypeNodupCycle /-\ninstance fintypeNodupCycle [Fintype \u03b1] : Fintype { s : Cycle \u03b1 // s.Nodup } :=\n  Fintype.ofSurjective (fun l : { l : List \u03b1 // l.Nodup } => \u27e8l.val, by simpa using l.prop\u27e9)\n    fun \u27e8s, hs\u27e9 => by\n    induction s using Quotient.inductionOn'\n    exact \u27e8\u27e8s, hs\u27e9, by simp\u27e9\n#align cycle.fintype_nodup_cycle Cycle.fintypeNodupCycle\n-/\n\n#print Cycle.fintypeNodupNontrivialCycle /-\ninstance fintypeNodupNontrivialCycle [Fintype \u03b1] :\n    Fintype { s : Cycle \u03b1 // s.Nodup \u2227 s.Nontrivial } :=\n  Fintype.subtype\n    (((Finset.univ : Finset { s : Cycle \u03b1 // s.Nodup }).map (Function.Embedding.subtype _)).filter\u2093\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 \u03b1` as a `finset \u03b1`. -/\ndef toFinset (s : Cycle \u03b1) : Finset \u03b1 :=\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 \u03b1) : 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 \u03b1) : (l : Cycle \u03b1).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 \u03b1).toFinset = \u2205 :=\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 \u03b1} : s.toFinset = \u2205 \u2194 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 \u03b1` such that `nodup s`, retrieve the next element after `x \u2208 s`. -/\ndef next : \u2200 (s : Cycle \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 s), \u03b1 := fun s =>\n  Quot.hrecOn s (fun l hn x hx => next l x hx) fun l\u2081 l\u2082 h =>\n    Function.hfunext (propext h.nodup_iff) fun h\u2081 h\u2082 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\u2081 _)\n#align cycle.next Cycle.next\n-/\n\n#print Cycle.prev /-\n/-- Given a `s : cycle \u03b1` such that `nodup s`, retrieve the previous element before `x \u2208 s`. -/\ndef prev : \u2200 (s : Cycle \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 s), \u03b1 := fun s =>\n  Quot.hrecOn s (fun l hn x hx => prev l x hx) fun l\u2081 l\u2082 h =>\n    Function.hfunext (propext h.nodup_iff) fun h\u2081 h\u2082 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\u2081 _)\n#align cycle.prev Cycle.prev\n-/\n\n#print Cycle.prev_reverse_eq_next /-\n@[simp]\ntheorem prev_reverse_eq_next (s : Cycle \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 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 \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 s) :\n    s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by\n  simp [\u2190 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 \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 s) : s.next hs x hx \u2208 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 \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 s) : s.prev hs x hx \u2208 s :=\n  by\n  rw [\u2190 next_reverse_eq_prev, \u2190 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 \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 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 \u03b1) (hs : Nodup s) (x : \u03b1) (hx : x \u2208 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 \u03b1] : Repr (Cycle \u03b1) :=\n  \u27e8fun s => \"c[\" ++ String.intercalate \", \" (s.map repr).lists.unquot.headI ++ \"]\"\u27e9\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 \u03b1) \u2194 R a b \u2227 R b c \u2227 R c a` -/\ndef Chain (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (c : Cycle \u03b1) : 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      \u00b7 rfl\n      \u00b7 have := is_rotated_nil_iff'.1 hab\n        contradiction\n      \u00b7 have := is_rotated_nil_iff.1 hab\n        contradiction\n      \u00b7 unfold chain._match_1\n        cases' hab with n hn\n        induction' n with d hd generalizing a b l m\n        \u00b7 simp only [rotate_zero] at hn\n          rw [hn.1, hn.2]\n        \u00b7 cases' l with c s\n          \u00b7 simp only [rotate_singleton] at hn\n            rw [hn.1, hn.2]\n          \u00b7 rw [Nat.succ_eq_one_add, \u2190 rotate_rotate, rotate_cons_succ, rotate_zero, cons_append] at\n              hn\n            rw [\u2190 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 : \u03b1 \u2192 \u03b1 \u2192 Prop) : Cycle.Chain r (@nil \u03b1) := 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 : \u03b1 \u2192 \u03b1 \u2192 Prop) (a : \u03b1) (l : List \u03b1) :\n    Chain r (a :: l) \u2194 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 : \u03b1 \u2192 \u03b1 \u2192 Prop) (a : \u03b1) : Chain r [a] \u2194 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 : \u03b1 \u2192 \u03b1 \u2192 Prop) {l : List \u03b1} :\n    \u2200 hl : l \u2260 [], Chain r l \u2194 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 [\u2190 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 {\u03b2 : Type _} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (f : \u03b2 \u2192 \u03b1) {s : Cycle \u03b2} :\n    Chain r (s.map f) \u2194 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 : \u2115 \u2192 \u2115 \u2192 Prop) (n : \u2115) :\n    Chain r (List.range n.succ) \u2194 r n 0 \u2227 \u2200 m < n, r m m.succ := by\n  rw [range_succ, \u2190 coe_cons_eq_coe_append, chain_coe_cons, \u2190 range_succ, chain_range_succ]\n#align cycle.chain_range_succ Cycle.chain_range_succ\n-/\n\nvariable {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : Cycle \u03b1}\n\n#print Cycle.chain_of_pairwise /-\ntheorem chain_of_pairwise : (\u2200 a \u2208 s, \u2200 b \u2208 s, r a b) \u2192 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 \u2208 (a :: l : Cycle \u03b1) := by simp\n  have Hl : \u2200 {b} (hb : b \u2208 l), b \u2208 (a :: l : Cycle \u03b1) := fun b hb => by simp [hb]\n  rw [Cycle.chain_coe_cons]\n  apply pairwise.chain\n  rw [pairwise_cons]\n  refine'\n    \u27e8fun b hb => _,\n      pairwise_append.2\n        \u27e8pairwise_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 => _\u27e9\u27e9\n  \u00b7 rw [mem_append] at hb\n    cases hb\n    \u00b7 exact hs a Ha b (Hl hb)\n    \u00b7 rw [mem_singleton] at hb\n      rw [hb]\n      exact hs a Ha a Ha\n  \u00b7 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 \u03b1 r] : Chain r s \u2194 \u2200 a \u2208 s, \u2200 b \u2208 s, r a b :=\n  \u27e8by\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    \u00b7 exact hs.1 c (Or.inr rfl)\n    \u00b7 exact hs.1 c (Or.inl hc)\n    \u00b7 exact hs.2.2 b hb\n    \u00b7 exact trans (hs.2.2 b hb) (hs.1 c (Or.inl hc)), Cycle.chain_of_pairwise\u27e9\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 \u03b1 r] [IsAntisymm \u03b1 r] (hs : Chain r s) {a b : \u03b1} (ha : a \u2208 s)\n    (hb : b \u2208 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 \u2228 q) : q \u2228 p := by\n  cases h with\n  | inl hp => exact Or.inr hp\n  | inr hq => exact Or.inl hq\n\nexample (h : p \u2228 q) : q \u2228 p := by\n  cases' h with hp hq\n  \u00b7 exact Or.inr hp\n  \u00b7 exact Or.inl hq\n\nexample (h : p \u2228 q) : q \u2228 p := by\n  rcases h with hp | hq\n  \u00b7 exact Or.inr hp\n  \u00b7 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 \u00d7 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' \u00b7[0]) |>.toList\n  let mut subgoals := #[]\n  for (altName, g) in alts do\n    let numFields \u2190 getAltNumFields elimInfo altName\n    let (altVarNames, names') := names.splitAtD numFields `_\n    names := names'\n    let (_, g) \u2190 introN g numFields altVarNames\n    let some (g, _) \u2190 Cases.unifyEqs numEqs g {} | pure ()\n    let (_, g) \u2190 introNP g numGeneralized\n    let g \u2190 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 \u2190 elabCasesTargets tgts.getSepArgs\n  let (elimName, elimInfo) \u2190 getElimNameInfo usingArg targets (induction := true)\n  let g \u2190 getMainGoal\n  withMVarContext g do\n    let targets \u2190 addImplicitTargets elimInfo targets\n    evalInduction.checkTargets targets\n    let targetFVarIds := targets.map (\u00b7.fvarId!)\n    withMVarContext g do\n      let genArgs \u2190 if genArg.isNone then pure #[] else getFVarIds genArg[1].getArgs\n      let forbidden \u2190 mkGeneralizationForbiddenSet targets\n      let mut s \u2190 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) \u2190 Meta.revert g (\u2190 sortFVarIds s.toArray)\n      let result \u2190 withRef tgts <| ElimApp.mkElimApp elimName elimInfo targets (\u2190 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 \u2190 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 \u2190 elabCasesTargets tgts.getSepArgs\n  let (elimName, elimInfo) \u2190 getElimNameInfo usingArg targets (induction := false)\n  let g \u2190 getMainGoal\n  withMVarContext g do\n    let targets \u2190 addImplicitTargets elimInfo targets\n    let result \u2190 withRef tgts <| ElimApp.mkElimApp elimName elimInfo targets (\u2190 getMVarTag g)\n    let elimArgs := result.elimApp.getAppArgs\n    let targets \u2190 elimInfo.targetsPos.mapM (instantiateMVars elimArgs[\u00b7])\n    let motive := elimArgs[elimInfo.motivePos]\n    let g \u2190 generalizeTargetsEq g (\u2190 inferType motive) targets\n    let (targetsNew, g) \u2190 introN g targets.size\n    withMVarContext g do\n      ElimApp.setMotiveArg g motive.mvarId! targetsNew\n      assignExprMVar g result.elimApp\n      let subgoals \u2190 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": "-- import the definition of the maze surrounded by fore\nimport mazes.maze_with_fire.solutions.definition\nnamespace maze\n\n/-\n\n# Maze with fire.\n\nYou are in a maze of twisty passages, all distinct. \n\nYou can go north, south east or west.\n\nIf you fall into the fire, you will end up in the room of death,\nroom 5, from which there is no escape.\n\nSolver remark : there are 6 rooms.\n\nUse `n`, `s`,`e`, `w` to move around. The exit is room `4`.\nWhen you're at the exit, type `out`.\n-/\n\n/- Lemma : no-side-bar\nCan you solve this maze?\n-/\nexample : goal :=\nbegin\n  -- ready...\n  unfold goal,\n  -- go!\n  e,\n  n,\n  e,\n  e,\n  out,\nend\n\nend maze\n", "meta": {"author": "kbuzzard", "repo": "lean-game-skeleton", "sha": "098454dd6acc4c06beccf52b6547bf4cd99cc581", "save_path": "github-repos/lean/kbuzzard-lean-game-skeleton", "path": "github-repos/lean/kbuzzard-lean-game-skeleton/lean-game-skeleton-098454dd6acc4c06beccf52b6547bf4cd99cc581/src/mazes/maze_with_fire/level.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.09947020320382932, "lm_q1q2_score": 0.04740547473411392}}
{"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.\u03c0 f)`, and\n* `abelian.coimage f` is `cokernel (kernel.\u03b9 f)`.\n\n## Main results\n\n* In an abelian category, mono + epi = iso.\n* If `f : X \u27f6 Y`, then the map `factor_thru_image f : X \u27f6 image f` is an epimorphism, and the map\n  `factor_thru_coimage f : coimage f \u27f6 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 \u2245 limits.image f`.\n  * the canonical morphism `coimage_image_comparison : coimage f \u27f6 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 \u27f6 Y) : mono_factorisation f :=\n{ I := abelian.image f,\n  m := kernel.\u03b9 _,\n  m_mono := infer_instance,\n  e := kernel.lift _ f (cokernel.condition _),\n  fac' := kernel.lift_\u03b9 _ _ _ }\n\nlemma image_mono_factorisation_e' {X Y : C} (f : X \u27f6 Y) :\n  (image_mono_factorisation f).e = cokernel.\u03c0 _ \u226b abelian.coimage_image_comparison f :=\nbegin\n  ext,\n  simp only [abelian.coimage_image_comparison, image_mono_factorisation_e,\n    category.assoc, cokernel.\u03c0_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 \u27f6 Y) [is_iso (abelian.coimage_image_comparison f)] :\n  image_factorisation f :=\n{ F := image_mono_factorisation f,\n  is_image :=\n  { lift := \u03bb F, inv (abelian.coimage_image_comparison f) \u226b cokernel.desc _ F.e F.kernel_\u03b9_comp,\n    lift_fac' := \u03bb 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.\u03c0_desc_assoc, limits.coequalizer.\u03c0_desc_assoc, F.fac, kernel.lift_\u03b9]\n    end } }\n\ninstance [has_zero_object C] {X Y : C} (f : X \u27f6 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 \u27f6 Y) [epi f] :\n  is_iso (image_mono_factorisation f).m :=\nby { dsimp, apply_instance }\n\nvariables [\u2200 {X Y : C} (f : X \u27f6 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 := \u03bb X Y f,\n  { exists_image := \u27e8image_factorisation f\u27e9 } }\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 := \u03bb X Y f m,\n  { Z := _,\n    g := cokernel.\u03c0 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 _ (\u03bb A, limit.lift _ _ \u226b inv (image_mono_factorisation f).e) aux _,\n      { intros A g hg,\n        rw [kernel_fork.\u03b9_of_\u03b9] at hg,\n        rw [\u2190 cancel_mono f, hg, \u2190 aux, kernel_fork.\u03b9_of_\u03b9], },\n      { intro A,\n        simp only [kernel_fork.\u03b9_of_\u03b9, category.assoc],\n        convert limit.lift_\u03c0 _ _ 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 := \u03bb X Y f m,\n  { W := kernel f,\n    g := kernel.\u03b9 _,\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        (\u03bb A, inv (image_mono_factorisation f).m \u226b\n          inv (abelian.coimage_image_comparison f) \u226b colimit.desc _ _)\n        aux _,\n      { intros A g hg,\n        rw [cokernel_cofork.\u03c0_of_\u03c0] at hg,\n        rw [\u2190 cancel_epi f, hg, \u2190 aux, cokernel_cofork.\u03c0_of_\u03c0], },\n      { intro A,\n        simp only [cokernel_cofork.\u03c0_of_\u03c0, \u2190 category.assoc],\n        convert colimit.\u03b9_desc _ _ using 2,\n        rw [is_iso.comp_inv_eq, is_iso.comp_inv_eq, eq_comm, \u2190image_mono_factorisation_e'],\n        exact (image_mono_factorisation f).fac, }\n    end }, }\n\nend of_coimage_image_comparison_is_iso\n\nvariables [\u2200 {X Y : C} (f : X \u27f6 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 := { ..\u2039abelian C\u203a }\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 \u27f6 Q)\n\n/-- The map `p : P \u27f6 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 \u27f6 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 \u27f6 Q)\n\nsection\n\nlemma mono_of_kernel_\u03b9_eq_zero (h : kernel.\u03b9 f = 0) : mono f :=\nmono_of_kernel_zero h\n\nlemma epi_of_cokernel_\u03c0_eq_zero (h : cokernel.\u03c0 f = 0) : epi f :=\nbegin\n  apply normal_mono_category.epi_of_zero_cokernel _ (cokernel f),\n  simp_rw \u2190h,\n  exact is_colimit.of_iso_colimit (colimit.is_colimit (parallel_pair f 0)) (iso_of_\u03c0 _)\nend\n\nend\n\nsection\nvariables {f}\n\nlemma image_\u03b9_comp_eq_zero {R : C} {g : Q \u27f6 R} (h : f \u226b g = 0) : abelian.image.\u03b9 f \u226b g = 0 :=\nzero_of_epi_comp (abelian.factor_thru_image f) $ by simp [h]\n\nlemma comp_coimage_\u03c0_eq_zero {R : C} {g : Q \u27f6 R} (h : f \u226b g = 0) : f \u226b abelian.coimage.\u03c0 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.\u03b9 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.\u03c0 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 $ \u03bb 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 \u27f6 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 _ = _ \u226b (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 \u2245 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 \u2245 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 \u2245 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 \u27f6 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.\u03b9 s`. -/\ndef epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) :\n  is_colimit (cokernel_cofork.of_\u03c0 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.\u03c0 s`. -/\ndef mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) :\n  is_limit (kernel_fork.of_\u03b9 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 \u27f6 T) (hg : kernel.\u03b9 f \u226b g = 0) : Y \u27f6 T :=\n(epi_is_cokernel_of_kernel _ (limit.is_limit _)).desc (cokernel_cofork.of_\u03c0 _ hg)\n\n@[simp, reassoc]\nlemma comp_epi_desc [epi f] {T : C} (g : X \u27f6 T) (hg : kernel.\u03b9 f \u226b g = 0) :\n  f \u226b epi_desc f g hg = g :=\n(epi_is_cokernel_of_kernel _ (limit.is_limit _)).fac (cokernel_cofork.of_\u03c0 _ 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 \u27f6 Y) (hg : g \u226b cokernel.\u03c0 f = 0) : T \u27f6 X :=\n(mono_is_kernel_of_cokernel _ (colimit.is_colimit _)).lift (kernel_fork.of_\u03b9 _ hg)\n\n@[simp, reassoc]\nlemma mono_lift_comp [mono f] {T : C} (g : T \u27f6 Y) (hg : g \u226b cokernel.\u03c0 f = 0) :\n  mono_lift f g hg \u226b f = g :=\n(mono_is_kernel_of_cokernel _ (colimit.is_colimit _)).fac (kernel_fork.of_\u03b9 _ 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 \u27f6 Z) (g : Y \u27f6 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 \u27f6 X \u229e Y` -/\nabbreviation pullback_to_biproduct : pullback f g \u27f6 X \u229e Y :=\nbiprod.lift pullback.fst pullback.snd\n\n/-- The canonical map `pullback f g \u27f6 X \u229e Y` induces a kernel cone on the map\n    `biproduct X Y \u27f6 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_\u03b9 (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 \u27f6 X \u229e 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  (\u03bb s, pullback.lift (fork.\u03b9 s \u226b biprod.fst) (fork.\u03b9 s \u226b biprod.snd) $\n    sub_eq_zero.1 $ by rw [category.assoc, category.assoc, \u2190comp_sub, sub_eq_add_neg, \u2190comp_neg,\n      \u2190biprod.desc_eq, kernel_fork.condition s])\n  (\u03bb s,\n  begin\n    ext; rw [fork.\u03b9_of_\u03b9, category.assoc],\n    { rw [biprod.lift_fst, pullback.lift_fst] },\n    { rw [biprod.lift_snd, pullback.lift_snd] }\n  end)\n  (\u03bb s m h, by ext; simp [fork.\u03b9_eq_app_zero, \u2190h 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 \u27f6 Y) (g : X \u27f6 Z)\n\n/-- The canonical map `Y \u229e Z \u27f6 pushout f g` -/\nabbreviation biproduct_to_pushout : Y \u229e Z \u27f6 pushout f g :=\nbiprod.desc pushout.inl pushout.inr\n\n/-- The canonical map `Y \u229e Z \u27f6 pushout f g` induces a cokernel cofork on the map\n    `X \u27f6 Y \u229e Z` induced by `f` and `-g`. -/\nabbreviation biproduct_to_pushout_cofork : cokernel_cofork (biprod.lift f (-g)) :=\ncokernel_cofork.of_\u03c0 (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 \u229e Z \u27f6 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  (\u03bb s, pushout.desc (biprod.inl \u226b cofork.\u03c0 s) (biprod.inr \u226b cofork.\u03c0 s) $\n    sub_eq_zero.1 $ by rw [\u2190category.assoc, \u2190category.assoc, \u2190sub_comp, sub_eq_add_neg, \u2190neg_comp,\n      \u2190biprod.lift_eq, cofork.condition s, zero_comp])\n  (\u03bb s, by ext; simp)\n  (\u03bb s m h, by ext; simp [cofork.\u03c0_eq_app_one, \u2190h 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 \u27f6 Z) (g : Y \u27f6 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 \u27f6 Y) :=\n-- It will suffice to consider some morphism e : Y \u27f6 R such that\n-- pullback.snd \u226b e = 0 and show that e = 0.\nepi_of_cancel_zero _ $ \u03bb R e h,\nbegin\n  -- Consider the morphism u := (0, e) : X \u229e Y\u27f6 R.\n  let u := biprod.desc (0 : X \u27f6 R) e,\n  -- The composite pullback f g \u27f6 X \u229e Y \u27f6 R is zero by assumption.\n  have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g \u226b 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 \u27f6 R.\n  obtain \u27e8d, hd\u27e9 := cokernel_cofork.is_colimit.desc' this u hu,\n  change Z \u27f6 R at d,\n  change biprod.desc f (-g) \u226b d = u at hd,\n  -- But then f \u226b d = 0:\n  have : f \u226b d = 0, calc\n    f \u226b d = (biprod.inl \u226b biprod.desc f (-g)) \u226b d : by rw biprod.inl_desc\n    ... = biprod.inl \u226b 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 \u226b u : by rw biprod.inr_desc\n    ... = biprod.inr \u226b biprod.desc f (-g) \u226b d : by rw \u2190hd\n    ... = biprod.inr \u226b biprod.desc f (-g) \u226b 0 : by rw this\n    ... = (biprod.inr \u226b biprod.desc f (-g)) \u226b 0 : by rw \u2190category.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 \u27f6 X) :=\n-- It will suffice to consider some morphism e : X \u27f6 R such that\n-- pullback.fst \u226b e = 0 and show that e = 0.\nepi_of_cancel_zero _ $ \u03bb R e h,\nbegin\n  -- Consider the morphism u := (e, 0) : X \u229e Y \u27f6 R.\n  let u := biprod.desc e (0 : Y \u27f6 R),\n  -- The composite pullback f g \u27f6 X \u229e Y \u27f6 R is zero by assumption.\n  have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g \u226b 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 \u27f6 R.\n  obtain \u27e8d, hd\u27e9 := cokernel_cofork.is_colimit.desc' this u hu,\n  change Z \u27f6 R at d,\n  change biprod.desc f (-g) \u226b d = u at hd,\n  -- But then (-g) \u226b d = 0:\n  have : (-g) \u226b d = 0, calc\n    (-g) \u226b d = (biprod.inr \u226b biprod.desc f (-g)) \u226b d : by rw biprod.inr_desc\n    ... = biprod.inr \u226b 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 \u226b u : by rw biprod.inl_desc\n    ... = biprod.inl \u226b biprod.desc f (-g) \u226b d : by rw \u2190hd\n    ... = biprod.inl \u226b biprod.desc f (-g) \u226b 0 : by rw this\n    ... = (biprod.inl \u226b biprod.desc f (-g)) \u226b 0 : by rw \u2190category.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\u2081 : Y \u27f6 W) [epi g\u2081] (g\u2082 : W \u27f6 Z) [mono g\u2082] (hg : g\u2081 \u226b g\u2082 = g) (f' : X \u27f6 W) (hf : f' \u226b g\u2082 = 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\u2082 f' g\u2081 hf hg t ht)\n\nend epi_pullback\n\nsection mono_pushout\nvariables [limits.has_pushouts C] {W X Y Z : C} (f : X \u27f6 Y) (g : X \u27f6 Z)\n\ninstance mono_pushout_of_mono_f [mono f] : mono (pushout.inr : Z \u27f6 pushout f g) :=\nmono_of_cancel_zero _ $ \u03bb R e h,\nbegin\n  let u := biprod.lift (0 : R \u27f6 Y) e,\n  have hu : u \u226b 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 \u27e8d, hd\u27e9 := kernel_fork.is_limit.lift' this u hu,\n  change R \u27f6 X at d,\n  change d \u226b biprod.lift f (-g) = u at hd,\n  have : d \u226b f = 0, calc\n    d \u226b f = d \u226b biprod.lift f (-g) \u226b biprod.fst : by rw biprod.lift_fst\n    ... = u \u226b biprod.fst : by rw [\u2190category.assoc, hd]\n    ... = 0 : biprod.lift_fst _ _,\n  have : d = 0 := (cancel_mono f).1 (by simpa),\n  calc\n    e = u \u226b biprod.snd : by rw biprod.lift_snd\n    ... = (d \u226b biprod.lift f (-g)) \u226b biprod.snd : by rw \u2190hd\n    ... = (0 \u226b biprod.lift f (-g)) \u226b biprod.snd : by rw this\n    ... = 0 \u226b biprod.lift f (-g) \u226b biprod.snd : by rw category.assoc\n    ... = 0 : zero_comp\nend\n\ninstance mono_pushout_of_mono_g [mono g] : mono (pushout.inl : Y \u27f6 pushout f g) :=\nmono_of_cancel_zero _ $ \u03bb R e h,\nbegin\n  let u := biprod.lift e (0 : R \u27f6 Z),\n  have hu : u \u226b 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 \u27e8d, hd\u27e9 := kernel_fork.is_limit.lift' this u hu,\n  change R \u27f6 X at d,\n  change d \u226b biprod.lift f (-g) = u at hd,\n  have : d \u226b (-g) = 0, calc\n    d \u226b (-g) = d \u226b biprod.lift f (-g) \u226b biprod.snd : by rw biprod.lift_snd\n    ... = u \u226b biprod.snd : by rw [\u2190category.assoc, hd]\n    ... = 0 : biprod.lift_snd _ _,\n  have : d = 0 := (cancel_mono (-g)).1 (by simpa),\n  calc\n    e = u \u226b biprod.fst : by rw biprod.lift_fst\n    ... = (d \u226b biprod.lift f (-g)) \u226b biprod.fst : by rw \u2190hd\n    ... = (0 \u226b biprod.lift f (-g)) \u226b biprod.fst : by rw this\n    ... = 0 \u226b biprod.lift f (-g) \u226b 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 \u27f6 Y) (g : X \u27f6 Z)\n  (g\u2081 : X \u27f6 W) [epi g\u2081] (g\u2082 : W \u27f6 Z) [mono g\u2082] (hg : g\u2081 \u226b g\u2082 = g) (f' : W \u27f6 Y) (hf : g\u2081 \u226b 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": "-- 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\nimport tactic.basic\nimport tactic.ext\n\nopen tactic\n\nmeta def back_attribute : user_attribute := {\n  name := `back,\n  descr := \"A lemma that should be applied to a goal whenever possible; use `backwards_reasoning` to automatically `apply` all lemmas tagged `[back]`.\"\n}\n\nrun_cmd attribute.register ``back_attribute\n\n/-- Try to apply the given lemma, solving new terminal goals by solve_by_elim if possible. -/\nmeta def apply_using_solve_by_elim (c : name) : tactic unit :=\nfocus1 $ do\n  t \u2190 mk_const c,\n  r \u2190 apply t,\n  try (any_goals (terminal_goal >> solve_by_elim))\n\nmeta def elim_attribute : user_attribute := {\n  name := `elim,\n  descr := \"A lemma that should be applied to a goal whenever possible, as long as all arguments to the lemma by be fulfilled from existing hypotheses; use `backwards_reasoning` to automatically apply all lemmas tagged `[elim]`.\"\n}\n\nrun_cmd attribute.register ``elim_attribute\n\n/-- Try to apply the given lemma, fulfilling all new goals using existing hypotheses. -/\nmeta def apply_no_new_goals (c : name) : tactic unit :=\nfocus1 $ do\n  t \u2190 mk_const c,\n  r \u2190 apply t,\n  all_goals solve_by_elim,\n  a \u2190 r.mmap (\u03bb p, do e \u2190 instantiate_mvars p.2, return e.list_meta_vars.length),\n  guard (a.all (\u03bb n, n = 0))\n\n/-- Try to apply one of the given lemmas; it succeeds as soon as one of them succeeds. -/\nmeta def any_apply_with (f : name \u2192 tactic unit) : list name \u2192 tactic name\n| []      := failed\n| (c::cs) := (f c >> pure c) <|> any_apply_with cs\n\n/-- Try to apply any lemma marked with the attributes `@[back]` or `@[elim]`. -/\nmeta def backwards_reasoning : tactic string :=\n(attribute.get_instances `elim >>= any_apply_with apply_no_new_goals >>=\n  \u03bb n, return (\"apply \" ++ n.to_string ++ \" ; solve_by_elim\")) <|>\n(attribute.get_instances `back >>= any_apply_with apply_using_solve_by_elim >>=\n  \u03bb n, return (\"apply \" ++ n.to_string)) <|>\nfail \"no @[back] or @[back'] lemmas could be applied\"\n\nattribute [extensionality] subtype.eq\n\n-- TODO should `apply_instance` be in tidy? If so, these shouldn't be needed.\n@[back] definition decidable_true  : decidable true  := is_true  dec_trivial\n@[back] definition decidable_false : decidable false := is_false dec_trivial\n\nattribute [back] quotient.mk quotient.sound\n\nattribute [back] eqv_gen.rel\nattribute [elim] Exists.intro\n", "meta": {"author": "semorrison", "repo": "lean-tidy", "sha": "6c1d46de6cff05e1c2c4c9692af812bca3e13b6c", "save_path": "github-repos/lean/semorrison-lean-tidy", "path": "github-repos/lean/semorrison-lean-tidy/lean-tidy-6c1d46de6cff05e1c2c4c9692af812bca3e13b6c/src/tidy/backwards_reasoning.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326186278634367, "lm_q2_score": 0.1037486227096331, "lm_q1q2_score": 0.047025293990885855}}
{"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 \u27e8\u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9\u27e9,\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\u27e8\u27e8of punit, is_zero_of_subsingleton _\u27e9\u27e9\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 \u27e8\u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9\u27e9,\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\u27e8\u27e8of punit, is_zero_of_subsingleton _\u27e9\u27e9\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 {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := by solve_by_elim\nexample {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := by solve_by_elim\nexample {\u03b1 \u03b2 \u03b3 : Type} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (a : \u03b1) : \u03b3 := by solve_by_elim\nexample {\u03b1 \u03b2 \u03b3 : Type} (_f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (b : \u03b2) : \u03b3 := by solve_by_elim\nexample {\u03b1 : Nat \u2192 Type} (f : (n : Nat) \u2192 \u03b1 n \u2192 \u03b1 (n+1)) (a : \u03b1 0) : \u03b1 4 := by solve_by_elim\n\nexample (h : Nat) : Nat := by solve_by_elim []\nexample {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := by solve_by_elim []\nexample {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := by solve_by_elim []\nexample {\u03b1 \u03b2 \u03b3 : Type} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (a : \u03b1) : \u03b3 := by solve_by_elim []\nexample {\u03b1 \u03b2 \u03b3 : Type} (_f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (b : \u03b2) : \u03b3 := by solve_by_elim []\nexample {\u03b1 : Nat \u2192 Type} (f : (n : Nat) \u2192 \u03b1 n \u2192 \u03b1 (n+1)) (a : \u03b1 0) : \u03b1 4 := by solve_by_elim []\n\nexample {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := 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 {\u03b1 \u03b2 \u03b3 : Type} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (b : \u03b2) : \u03b3 := 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 {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := by solve_by_elim only [f, a]\nexample {\u03b1 \u03b2 : Type} (f : \u03b1 \u2192 \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := by solve_by_elim only [f, a]\nexample {\u03b1 \u03b2 \u03b3 : Type} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (a : \u03b1) : \u03b3 := by solve_by_elim only [f, g, a]\nexample {\u03b1 \u03b2 \u03b3 : Type} (_f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) (b : \u03b2) : \u03b3 := by solve_by_elim only [g, b]\nexample {\u03b1 : Nat \u2192 Type} (f : (n : Nat) \u2192 \u03b1 n \u2192 \u03b1 (n+1)) (a : \u03b1 0) : \u03b1 4 := by\n  solve_by_elim only [f, a]\n\nexample (h\u2081 h\u2082 : 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\u2081]\n  -- 'It does make sense to use `*` without `only`.'\n  fail_if_success solve_by_elim [*, -h\u2081]\n  solve_by_elim only [*, -h\u2081]\n\n-- Verify that already assigned metavariables are skipped.\nexample (P\u2081 P\u2082 : \u03b1 \u2192 Prop) (f : \u2200 (a : \u03b1), P\u2081 a \u2192 P\u2082 a \u2192 \u03b2)\n    (a : \u03b1) (ha\u2081 : P\u2081 a) (ha\u2082 : P\u2082 a) : \u03b2 := 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 \u2192 y = y \u2192 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\u2081 P\u2082 : \u03b1 \u2192 Prop) (f : \u2200 (a: \u03b1), P\u2081 a \u2192 P\u2082 a \u2192 \u03b2)\n    (a : \u03b1) (_ha\u2081 : P\u2081 a)\n    (a' : \u03b1) (ha'\u2081 : P\u2081 a') (ha'\u2082 : P\u2082 a') : \u03b2 := by\n  fail_if_success solve_by_elim (config := .noBackTracking)\n  solve_by_elim\n\nexample {\u03b1 : Type} {a b : \u03b1 \u2192 Prop} (h\u2080 : b = a) (y : \u03b1) : a y = b y :=\nby\n  fail_if_success solve_by_elim (config := {symm := false})\n  solve_by_elim\n\nexample (P : True \u2192 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 : \u2115) : \u2115 \u00d7 \u2115 := 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 : \u2115) : \u2115 \u00d7 \u2115 := by\n  constructor\n  solve_by_elim*\n\n-- Verifying that `solve_by_elim*` backtracks when given multiple goals.\nexample (n m : \u2115) (f : \u2115 \u2192 \u2115 \u2192 Prop) (h : f n m) : \u2203 p : \u2115 \u00d7 \u2115, 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 : \u2115 \u2192 Type) (f : {n : \u2115} \u2192 P n) : P 2 \u00d7 P 3 := by\n  fconstructor\n  solve_by_elim* only [f]\n\nexample : 6 = 6 \u2227 [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 : \u2115 \u2192 Prop) : (\u2203 k : \u2115, f k) \u2228 (\u2203 k : \u2115, g k) \u2194 \u2203 k : \u2115, f k \u2228 g k := by\n  dsimp at *\n  fconstructor\n  rintro (\u27e8n, fn\u27e9 | \u27e8n, gn\u27e9)\n  pick_goal 3\n  rintro \u27e8n, hf | hg\u27e9\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 \u2192 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 \u2227 Q \u2192 P \u2227 Q := by\n  solve_by_elim [And.imp, @id]\n\nsection apply_assumption\n\nexample {a b : Type} (h\u2080 : a \u2192 b) (h\u2081 : a) : b := by\n  apply_assumption\n  apply_assumption\n\nexample {\u03b1 : Type} {p : \u03b1 \u2192 Prop} (h\u2080 : \u2200 x, p x) (y : \u03b1) : p y := by\n  apply_assumption\n\n-- Check that `apply_assumption` uses `symm`.\nexample (a b : \u03b1) (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 \u2192 \u00ac Q) : \u2115 := by\n  fail_if_success apply_assumption (config := {exfalso := false})\n  apply_assumption <;> assumption\n\nend apply_assumption\n\nsection \u00abusing\u00bb\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 \u00abusing\u00bb\n\nsection issue1581\n\naxiom mySorry {\u03b1} : \u03b1\n\n@[dummy_label_attr] theorem le_rfl [LE \u03b1] {b c : \u03b1} (_h : b = c) : b \u2264 c := mySorry\n\nexample : 5 \u2264 7 := by\n  apply_rules using dummy_label_attr\n  guard_target = 5 = 7\n  exact mySorry\n\nexample : 5 \u2264 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": "import tactic --hide\n\n/-Lemma\nTrue implies true.\n-/\nlemma true_imp_true : true \u2192 true :=\nbegin\n  intro t,\n  triv,\nend", "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/true_false/tf2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.11920291732853862, "lm_q1q2_score": 0.04676769473135072}}
{"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\u00f6lzl, 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 \u2192 Type v} {\u03b1 : 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 \u2192 Type v) : Type (max (u+1) v) :=\n(\u03b1 : Type u)\n(str : c \u03b1 . 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 \u2192 Type v} (\u03b1 : Type u) [str : c \u03b1] : bundled c := \u27e8\u03b1, str\u27e9\n\ninstance : has_coe_to_sort (bundled c) :=\n{ S := Type u, coe := bundled.\u03b1 }\n\n@[simp]\nlemma coe_mk (\u03b1) (str) : (@bundled.mk c \u03b1 str : Type u) = \u03b1 := 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 \u27f6 S in Ring is really\na (semi)ring homomorphism from R.\u03b1 to S.\u03b1, and not merely from\n`(bundled.map @ring.to_semiring R).\u03b1` to `(bundled.map @ring.to_semiring S).\u03b1`.\n-/\n/-- Map over the bundled structure -/\n@[reducible] def map (f : \u03a0 {\u03b1}, c \u03b1 \u2192 d \u03b1) (b : bundled c) : bundled d :=\n\u27e8b, f b.str\u27e9\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 \u2192 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 {\u03b1} (m : expr \u2192 tactic expr) (t : tactic \u03b1) : tactic \u03b1 := do\n-- Replace the goals with copies.\ngs \u2190 get_goals,\ngs' \u2190 gs.mmap (\u03bb g, infer_type g >>= mk_meta_var),\nset_goals gs',\n-- Run the tactic on the copied goals.\na \u2190 t,\n-- Run `m` on the produced terms,\n(gs.zip gs').mmap (\u03bb \u27e8g, g'\u27e9, do\n  g' \u2190 instantiate_mvars g',\n  g'' \u2190 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 {\u03b1} (t : tactic \u03b1)\n  (cfg : dsimp_config := { fail_if_unchanged := ff }) (no_defaults := ff)\n  (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic \u03b1 :=\nintercept_result (\u03bb 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 {\u03b1} (t : tactic \u03b1)\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 \u03b1 :=\nintercept_result (\u03bb 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 (\u03b1 : Type) : \u03b1 \u2192 \u03b1 :=\nbegin\n  intro a,\n  exact a\nend\n\nexample (\u03b1 : Type) : \u2200 x : \u03b1, 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": "/-\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-/\nprelude\nimport Init.WFTactics\nimport Init.Data.Nat.Basic\nimport Init.Data.Fin.Basic\nimport Init.Data.UInt.Basic\nimport Init.Data.Repr\nimport Init.Data.ToString.Basic\nimport Init.Util\nuniverse u v w\n\nnamespace Array\nvariable {\u03b1 : Type u}\n\n@[extern \"lean_mk_array\"]\ndef mkArray {\u03b1 : Type u} (n : Nat) (v : \u03b1) : Array \u03b1 := {\n  data := List.replicate n v\n}\n\n@[simp] theorem size_mkArray (n : Nat) (v : \u03b1) : (mkArray n v).size = n :=\n  List.length_replicate ..\n\ninstance : EmptyCollection (Array \u03b1) := \u27e8Array.empty\u27e9\ninstance : Inhabited (Array \u03b1) where\n  default := Array.empty\n\ndef isEmpty (a : Array \u03b1) : Bool :=\n  a.size = 0\n\ndef singleton (v : \u03b1) : Array \u03b1 :=\n  mkArray 1 v\n\n/-- Low-level version of `fget` which is as fast as a C array read.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fget` may be slightly slower than `uget`. -/\n@[extern \"lean_array_uget\"]\ndef uget (a : @& Array \u03b1) (i : USize) (h : i.toNat < a.size) : \u03b1 :=\n  a[i.toNat]\n\ninstance : GetElem (Array \u03b1) USize \u03b1 fun xs i => i.toNat < xs.size where\n  getElem xs i h := xs.uget i h\n\ndef back [Inhabited \u03b1] (a : Array \u03b1) : \u03b1 :=\n  a.get! (a.size - 1)\n\ndef get? (a : Array \u03b1) (i : Nat) : Option \u03b1 :=\n  if h : i < a.size then some a[i] else none\n\ndef back? (a : Array \u03b1) : Option \u03b1 :=\n  a.get? (a.size - 1)\n\n-- auxiliary declaration used in the equation compiler when pattern matching array literals.\nabbrev getLit {\u03b1 : Type u} {n : Nat} (a : Array \u03b1) (i : Nat) (h\u2081 : a.size = n) (h\u2082 : i < n) : \u03b1 :=\n  have := h\u2081.symm \u25b8 h\u2082\n  a[i]\n\n@[simp] theorem size_set (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : (set a i v).size = a.size :=\n  List.length_set ..\n\n@[simp] theorem size_push (a : Array \u03b1) (v : \u03b1) : (push a v).size = a.size + 1 :=\n  List.length_concat ..\n\n/-- Low-level version of `fset` which is as fast as a C array fset.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fset` may be slightly slower than `uset`. -/\n@[extern \"lean_array_uset\"]\ndef uset (a : Array \u03b1) (i : USize) (v : \u03b1) (h : i.toNat < a.size) : Array \u03b1 :=\n  a.set \u27e8i.toNat, h\u27e9 v\n\n@[extern \"lean_array_fswap\"]\ndef swap (a : Array \u03b1) (i j : @& Fin a.size) : Array \u03b1 :=\n  let v\u2081 := a.get i\n  let v\u2082 := a.get j\n  let a'  := a.set i v\u2082\n  a'.set (size_set a i v\u2082 \u25b8 j) v\u2081\n\n@[extern \"lean_array_swap\"]\ndef swap! (a : Array \u03b1) (i j : @& Nat) : Array \u03b1 :=\n  if h\u2081 : i < a.size then\n  if h\u2082 : j < a.size then swap a \u27e8i, h\u2081\u27e9 \u27e8j, h\u2082\u27e9\n  else panic! \"index out of bounds\"\n  else panic! \"index out of bounds\"\n\n@[inline] def swapAt (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  let e := a.get i\n  let a := a.set i v\n  (e, a)\n\n@[inline]\ndef swapAt! (a : Array \u03b1) (i : Nat) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  if h : i < a.size then\n    swapAt a \u27e8i, h\u27e9 v\n  else\n    have : Inhabited \u03b1 := \u27e8v\u27e9\n    panic! (\"index \" ++ toString i ++ \" out of bounds\")\n\n@[extern \"lean_array_pop\"]\ndef pop (a : Array \u03b1) : Array \u03b1 := {\n  data := a.data.dropLast\n}\n\ndef shrink (a : Array \u03b1) (n : Nat) : Array \u03b1 :=\n  let rec loop\n    | 0,   a => a\n    | n+1, a => loop n a.pop\n  loop (a.size - n) a\n\n@[inline]\nunsafe def modifyMUnsafe [Monad m] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 m \u03b1) : m (Array \u03b1) := do\n  if h : i < a.size then\n    let idx : Fin a.size := \u27e8i, h\u27e9\n    let v                := a.get idx\n    -- Replace a[i] by `box(0)`.  This ensures that `v` remains unshared if possible.\n    -- Note: we assume that arrays have a uniform representation irrespective\n    -- of the element type, and that it is valid to store `box(0)` in any array.\n    let a'               := a.set idx (unsafeCast ())\n    let v \u2190 f v\n    pure <| a'.set (size_set a .. \u25b8 idx) v\n  else\n    pure a\n\n@[implemented_by modifyMUnsafe]\ndef modifyM [Monad m] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 m \u03b1) : m (Array \u03b1) := do\n  if h : i < a.size then\n    let idx := \u27e8i, h\u27e9\n    let v   := a.get idx\n    let v \u2190 f v\n    pure <| a.set idx v\n  else\n    pure a\n\n@[inline]\ndef modify (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  Id.run <| modifyM a i f\n\n@[inline]\ndef modifyOp (self : Array \u03b1) (idx : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  self.modify idx f\n\n/--\n  We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime.\n\n  This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/\n@[inline] unsafe def forInUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] loop (i : USize) (b : \u03b2) : m \u03b2 := do\n    if i < sz then\n      let a := as.uget i lcProof\n      match (\u2190 f a b) with\n      | ForInStep.done  b => pure b\n      | ForInStep.yield b => loop (i+1) b\n    else\n      pure b\n  loop 0 b\n\n/-- Reference implementation for `forIn` -/\n@[implemented_by Array.forInUnsafe]\nprotected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec loop (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    match i, h with\n    | 0,   _ => pure b\n    | i+1, h =>\n      have h' : i < as.size            := Nat.lt_of_lt_of_le (Nat.lt_succ_self i) h\n      have : as.size - 1 < as.size     := Nat.sub_lt (Nat.zero_lt_of_lt h') (by decide)\n      have : as.size - 1 - i < as.size := Nat.lt_of_le_of_lt (Nat.sub_le (as.size - 1) i) this\n      match (\u2190 f as[as.size - 1 - i] b) with\n      | ForInStep.done b  => pure b\n      | ForInStep.yield b => loop i (Nat.le_of_lt h') b\n  loop as.size (Nat.le_refl _) b\n\ninstance : ForIn m (Array \u03b1) \u03b1 where\n  forIn := Array.forIn\n\n/-- See comment at `forInUnsafe` -/\n@[inline]\nunsafe def foldlMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i+1) stop (\u2190 f b (as.uget i lcProof))\n  if start < stop then\n    if stop \u2264 as.size then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else\n    pure init\n\n/-- Reference implementation for `foldlM` -/\n@[implemented_by foldlMUnsafe]\ndef foldlM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let fold (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) (b : \u03b2) : m \u03b2 := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure b\n        | i'+1 =>\n          have : j < as.size := Nat.lt_of_lt_of_le hlt h\n          loop i' (j+1) (\u2190 f b as[j])\n      else\n        pure b\n    loop (stop - start) start init\n  if h : stop \u2264 as.size then\n    fold stop h\n  else\n    fold as.size (Nat.le_refl _)\n\n/-- See comment at `forInUnsafe` -/\n@[inline]\nunsafe def foldrMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i-1) stop (\u2190 f (as.uget (i-1) lcProof) b)\n  if start \u2264 as.size then\n    if stop < start then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else if stop < as.size then\n    fold (USize.ofNat as.size) (USize.ofNat stop) init\n  else\n    pure init\n\n/-- Reference implementation for `foldrM` -/\n@[implemented_by foldrMUnsafe]\ndef foldrM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec fold (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else match i, h with\n      | 0, _   => pure b\n      | i+1, h =>\n        have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h\n        fold i (Nat.le_of_lt this) (\u2190 f as[i] b)\n  if h : start \u2264 as.size then\n    if stop < start then\n      fold start h init\n    else\n      pure init\n  else if stop < as.size then\n    fold as.size (Nat.le_refl _) init\n  else\n    pure init\n\n/-- See comment at `forInUnsafe` -/\n@[inline]\nunsafe def mapMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do\n    if i < sz then\n     let v    := r.uget i lcProof\n     -- Replace r[i] by `box(0)`.  This ensures that `v` remains unshared if possible.\n     -- Note: we assume that arrays have a uniform representation irrespective\n     -- of the element type, and that it is valid to store `box(0)` in any array.\n     let r    := r.uset i default lcProof\n     let vNew \u2190 f (unsafeCast v)\n     map (i+1) (r.uset i (unsafeCast vNew) lcProof)\n    else\n     pure (unsafeCast r)\n  unsafeCast <| map 0 (unsafeCast as)\n\n/-- Reference implementation for `mapM` -/\n@[implemented_by mapMUnsafe]\ndef mapM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (fun bs a => do let b \u2190 f a; pure (bs.push b)) (mkEmpty as.size)\n\n@[inline]\ndef mapIdxM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 m \u03b2) : m (Array \u03b2) :=\n  let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array \u03b2) : m (Array \u03b2) := do\n    match i, inv with\n    | 0,    _  => pure bs\n    | i+1, inv =>\n      have : j < as.size := by\n        rw [\u2190 inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_comm]\n        apply Nat.le_add_right\n      let idx : Fin as.size := \u27e8j, this\u27e9\n      have : i + (j + 1) = as.size := by rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n      map i (j+1) this (bs.push (\u2190 f idx (as.get idx)))\n  map as.size 0 rfl (mkEmpty as.size)\n\n@[inline]\ndef findSomeM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) := do\n  for a in as do\n    match (\u2190 f a) with\n    | some b => return b\n    | _      => pure \u27e8\u27e9\n  return none\n\n@[inline]\ndef findM? {\u03b1 : Type} {m : Type \u2192 Type} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) := do\n  for a in as do\n    if (\u2190 p a) then\n      return a\n  return none\n\n@[inline]\ndef findIdxM? [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option Nat) := do\n  let mut i := 0\n  for a in as do\n    if (\u2190 p a) then\n      return some i\n    i := i + 1\n  return none\n\n@[inline]\nunsafe def anyMUnsafe {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do\n    if i == stop then\n      pure false\n    else\n      if (\u2190 p (as.uget i lcProof)) then\n        pure true\n      else\n        any (i+1) stop\n  if start < stop then\n    if stop \u2264 as.size then\n      any (USize.ofNat start) (USize.ofNat stop)\n    else\n      pure false\n  else\n    pure false\n\n@[implemented_by anyMUnsafe]\ndef anyM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let any (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (j : Nat) : m Bool := do\n      if hlt : j < stop then\n        have : j < as.size := Nat.lt_of_lt_of_le hlt h\n        if (\u2190 p as[j]) then\n          pure true\n        else\n          loop (j+1)\n      else\n        pure false\n    loop start\n  if h : stop \u2264 as.size then\n    any stop h\n  else\n    any as.size (Nat.le_refl _)\ntermination_by loop i j => stop - j\n\n@[inline]\ndef allM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  return !(\u2190 as.anyM (start := start) (stop := stop) fun v => return !(\u2190 p v))\n\n@[inline]\ndef findSomeRevM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) :=\n  let rec @[specialize] find : (i : Nat) \u2192 i \u2264 as.size \u2192 m (Option \u03b2)\n    | 0,   _ => pure none\n    | i+1, h => do\n      have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h\n      let r \u2190 f as[i]\n      match r with\n      | some _ => pure r\n      | none   =>\n        have : i \u2264 as.size := Nat.le_of_lt this\n        find i this\n  find as.size (Nat.le_refl _)\n\n@[inline]\ndef findRevM? {\u03b1 : Type} {m : Type \u2192 Type w} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) :=\n  as.findSomeRevM? fun a => return if (\u2190 p a) then some a else none\n\n@[inline]\ndef forM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := 0) (stop := as.size) : m PUnit :=\n  as.foldlM (fun _ => f) \u27e8\u27e9 start stop\n\n@[inline]\ndef forRevM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := as.size) (stop := 0) : m PUnit :=\n  as.foldrM (fun a _ => f a) \u27e8\u27e9 start stop\n\n@[inline]\ndef foldl {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : \u03b2 :=\n  Id.run <| as.foldlM f init start stop\n\n@[inline]\ndef foldr {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : \u03b2 :=\n  Id.run <| as.foldrM f init start stop\n\n@[inline]\ndef map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  Id.run <| as.mapM f\n\n@[inline]\ndef mapIdx {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 \u03b2) : Array \u03b2 :=\n  Id.run <| as.mapIdxM f\n\n@[inline]\ndef find? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findM? p\n\n@[inline]\ndef findSome? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeM? f\n\n@[inline]\ndef findSome! {\u03b1 : Type u} {\u03b2 : Type v} [Inhabited \u03b2] (a : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : \u03b2 :=\n  match findSome? a f with\n  | some b => b\n  | none   => panic! \"failed to find element\"\n\n@[inline]\ndef findSomeRev? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeRevM? f\n\n@[inline]\ndef findRev? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findRevM? p\n\n@[inline]\ndef findIdx? {\u03b1 : Type u} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option Nat :=\n  let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat :=\n    if hlt : j < as.size then\n      match i, inv with\n      | 0, inv => by\n        apply False.elim\n        rw [Nat.zero_add] at inv\n        rw [inv] at hlt\n        exact absurd hlt (Nat.lt_irrefl _)\n      | i+1, inv =>\n        if p as[j] then\n          some j\n        else\n          have : i + (j+1) = as.size := by\n            rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n          loop i (j+1) this\n    else\n      none\n  loop as.size 0 rfl\n\ndef getIdx? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option Nat :=\na.findIdx? fun a => a == v\n\n@[inline]\ndef any (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.anyM p start stop\n\n@[inline]\ndef all (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.allM p start stop\n\ndef contains [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Bool :=\n  as.any fun b => a == b\n\ndef elem [BEq \u03b1] (a : \u03b1) (as : Array \u03b1) : Bool :=\n  as.contains a\n\n@[inline] def getEvenElems (as : Array \u03b1) : Array \u03b1 :=\n  (\u00b7.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a =>\n    if even then\n      (false, r.push a)\n    else\n      (true, r)\n\n@[export lean_array_to_list]\ndef toList (as : Array \u03b1) : List \u03b1 :=\n  as.foldr List.cons []\n\ninstance {\u03b1 : Type u} [Repr \u03b1] : Repr (Array \u03b1) where\n  reprPrec a _ :=\n    let _ : Std.ToFormat \u03b1 := \u27e8repr\u27e9\n    if a.size == 0 then\n      \"#[]\"\n    else\n      Std.Format.bracketFill \"#[\" (Std.Format.joinSep (toList a) (\",\" ++ Std.Format.line)) \"]\"\n\ninstance [ToString \u03b1] : ToString (Array \u03b1) where\n  toString a := \"#\" ++ toString a.toList\n\nprotected def append (as : Array \u03b1) (bs : Array \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : Append (Array \u03b1) := \u27e8Array.append\u27e9\n\nprotected def appendList (as : Array \u03b1) (bs : List \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : HAppend (Array \u03b1) (List \u03b1) (Array \u03b1) := \u27e8Array.appendList\u27e9\n\n@[inline]\ndef concatMapM [Monad m] (f : \u03b1 \u2192 m (Array \u03b2)) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (init := empty) fun bs a => do return bs ++ (\u2190 f a)\n\n@[inline]\ndef concatMap (f : \u03b1 \u2192 Array \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  as.foldl (init := empty) fun bs a => bs ++ f a\n\nend Array\n\nexport Array (mkArray)\n\nsyntax \"#[\" withoutPosition(sepBy(term, \", \")) \"]\" : term\n\nmacro_rules\n  | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ])\n\nnamespace Array\n\n-- TODO(Leo): cleanup\n@[specialize]\ndef isEqvAux (a b : Array \u03b1) (hsz : a.size = b.size) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) (i : Nat) : Bool :=\n  if h : i < a.size then\n     have : i < b.size := hsz \u25b8 h\n     p a[i] b[i] && isEqvAux a b hsz p (i+1)\n  else\n    true\ntermination_by _ => a.size - i\n\n@[inline] def isEqv (a b : Array \u03b1) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) : Bool :=\n  if h : a.size = b.size then\n    isEqvAux a b h p 0\n  else\n    false\n\ninstance [BEq \u03b1] : BEq (Array \u03b1) :=\n  \u27e8fun a b => isEqv a b BEq.beq\u27e9\n\n@[inline]\ndef filter (p : \u03b1 \u2192 Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b1 :=\n  as.foldl (init := #[]) (start := start) (stop := stop) fun r a =>\n    if p a then r.push a else r\n\n@[inline]\ndef filterM [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b1) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do\n    if (\u2190 p a) then return r.push a else return r\n\n@[specialize]\ndef filterMapM [Monad m] (f : \u03b1 \u2192 m (Option \u03b2)) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b2) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do\n    match (\u2190 f a) with\n    | some b => pure (bs.push b)\n    | none   => pure bs\n\n@[inline]\ndef filterMap (f : \u03b1 \u2192 Option \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b2 :=\n  Id.run <| as.filterMapM f (start := start) (stop := stop)\n\n@[specialize]\ndef getMax? (as : Array \u03b1) (lt : \u03b1 \u2192 \u03b1 \u2192 Bool) : Option \u03b1 :=\n  if h : 0 < as.size then\n    let a0 := as[0]\n    some <| as.foldl (init := a0) (start := 1) fun best a =>\n      if lt best a then a else best\n  else\n    none\n\n@[inline]\ndef partition (p : \u03b1 \u2192 Bool) (as : Array \u03b1) : Array \u03b1 \u00d7 Array \u03b1 := Id.run do\n  let mut bs := #[]\n  let mut cs := #[]\n  for a in as do\n    if p a then\n      bs := bs.push a\n    else\n      cs := cs.push a\n  return (bs, cs)\n\ntheorem ext (a b : Array \u03b1)\n    (h\u2081 : a.size = b.size)\n    (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.size) \u2192 (hi\u2082 : i < b.size) \u2192 a[i] = b[i])\n    : a = b := by\n  let rec extAux (a b : List \u03b1)\n      (h\u2081 : a.length = b.length)\n      (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.length) \u2192 (hi\u2082 : i < b.length) \u2192 a.get \u27e8i, hi\u2081\u27e9 = b.get \u27e8i, hi\u2082\u27e9)\n      : a = b := by\n    induction a generalizing b with\n    | nil =>\n      cases b with\n      | nil       => rfl\n      | cons b bs => rw [List.length_cons] at h\u2081; injection h\u2081\n    | cons a as ih =>\n      cases b with\n      | nil => rw [List.length_cons] at h\u2081; injection h\u2081\n      | cons b bs =>\n        have hz\u2081 : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zero_lt_succ\n        have hz\u2082 : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zero_lt_succ\n        have headEq : a = b := h\u2082 0 hz\u2081 hz\u2082\n        have h\u2081' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h\u2081; injection h\u2081\n        have h\u2082' : (i : Nat) \u2192 (hi\u2081 : i < as.length) \u2192 (hi\u2082 : i < bs.length) \u2192 as.get \u27e8i, hi\u2081\u27e9 = bs.get \u27e8i, hi\u2082\u27e9 := by\n          intro i hi\u2081 hi\u2082\n          have hi\u2081' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have hi\u2082' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have : (a::as).get \u27e8i+1, hi\u2081'\u27e9 = (b::bs).get \u27e8i+1, hi\u2082'\u27e9 := h\u2082 (i+1) hi\u2081' hi\u2082'\n          apply this\n        have tailEq : as = bs := ih bs h\u2081' h\u2082'\n        rw [headEq, tailEq]\n  cases a; cases b\n  apply congrArg\n  apply extAux\n  assumption\n  assumption\n\ntheorem extLit {n : Nat}\n    (a b : Array \u03b1)\n    (hsz\u2081 : a.size = n) (hsz\u2082 : b.size = n)\n    (h : (i : Nat) \u2192 (hi : i < n) \u2192 a.getLit i hsz\u2081 hi = b.getLit i hsz\u2082 hi) : a = b :=\n  Array.ext a b (hsz\u2081.trans hsz\u2082.symm) fun i hi\u2081 _ => h i (hsz\u2081 \u25b8 hi\u2081)\n\nend Array\n\n-- CLEANUP the following code\nnamespace Array\n\ndef indexOfAux [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) (i : Nat) : Option (Fin a.size) :=\n  if h : i < a.size then\n    let idx : Fin a.size := \u27e8i, h\u27e9;\n    if a.get idx == v then some idx\n    else indexOfAux a v (i+1)\n  else none\ntermination_by _ => a.size - i\n\ndef indexOf? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option (Fin a.size) :=\n  indexOfAux a v 0\n\n@[simp] theorem size_swap (a : Array \u03b1) (i j : Fin a.size) : (a.swap i j).size = a.size := by\n  show ((a.set i (a.get j)).set (size_set a i _ \u25b8 j) (a.get i)).size = a.size\n  rw [size_set, size_set]\n\n@[simp] theorem size_pop (a : Array \u03b1) : a.pop.size = a.size - 1 := by\n  match a with\n  | \u27e8[]\u27e9 => rfl\n  | \u27e8a::as\u27e9 => simp [pop, Nat.succ_sub_succ_eq_sub, size]\n\ntheorem reverse.termination {i j : Nat} (h : i < j) : j - 1 - (i + 1) < j - i := by\n  rw [Nat.sub_sub, Nat.add_comm]\n  exact Nat.lt_of_le_of_lt (Nat.pred_le _) (Nat.sub_succ_lt_self _ _ h)\n\ndef reverse (as : Array \u03b1) : Array \u03b1 :=\n  if h : as.size \u2264 1 then\n    as\n  else\n    loop as 0 \u27e8as.size - 1, Nat.pred_lt (mt (fun h : as.size = 0 => h \u25b8 by decide) h)\u27e9\nwhere\n  loop (as : Array \u03b1) (i : Nat) (j : Fin as.size) :=\n    if h : i < j then\n      have := reverse.termination h\n      let as := as.swap \u27e8i, Nat.lt_trans h j.2\u27e9 j\n      have : j-1 < as.size := by rw [size_swap]; exact Nat.lt_of_le_of_lt (Nat.pred_le _) j.2\n      loop as (i+1) \u27e8j-1, this\u27e9\n    else\n      as\ntermination_by _ => j - i\n\ndef popWhile (p : \u03b1 \u2192 Bool) (as : Array \u03b1) : Array \u03b1 :=\n  if h : as.size > 0 then\n    if p (as.get \u27e8as.size - 1, Nat.sub_lt h (by decide)\u27e9) then\n      popWhile p as.pop\n    else\n      as\n  else\n    as\ntermination_by popWhile as => as.size\n\ndef takeWhile (p : \u03b1 \u2192 Bool) (as : Array \u03b1) : Array \u03b1 :=\n  let rec go (i : Nat) (r : Array \u03b1) : Array \u03b1 :=\n    if h : i < as.size then\n      let a := as.get \u27e8i, h\u27e9\n      if p a then\n        go (i+1) (r.push a)\n      else\n        r\n    else\n      r\n  go 0 #[]\ntermination_by go i r => as.size - i\n\ndef eraseIdxAux (i : Nat) (a : Array \u03b1) : Array \u03b1 :=\n  if h : i < a.size then\n    let idx  : Fin a.size := \u27e8i, h\u27e9;\n    let idx1 : Fin a.size := \u27e8i - 1, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h\u27e9;\n    let a' := a.swap idx idx1\n    eraseIdxAux (i+1) a'\n  else\n    a.pop\ntermination_by _ => a.size - i\n\ndef feraseIdx (a : Array \u03b1) (i : Fin a.size) : Array \u03b1 :=\n  eraseIdxAux (i.val + 1) a\n\ndef eraseIdx (a : Array \u03b1) (i : Nat) : Array \u03b1 :=\n  if i < a.size then eraseIdxAux (i+1) a else a\n\ndef eraseIdxSzAux (a : Array \u03b1) (i : Nat) (r : Array \u03b1) (heq : r.size = a.size) : { r : Array \u03b1 // r.size = a.size - 1 } :=\n  if h : i < r.size then\n    let idx  : Fin r.size := \u27e8i, h\u27e9;\n    let idx1 : Fin r.size := \u27e8i - 1, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h\u27e9;\n    eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq)\n  else\n    \u27e8r.pop, (size_pop r).trans (heq \u25b8 rfl)\u27e9\ntermination_by _ => r.size - i\n\ndef eraseIdx' (a : Array \u03b1) (i : Fin a.size) : { r : Array \u03b1 // r.size = a.size - 1 } :=\n  eraseIdxSzAux a (i.val + 1) a rfl\n\ndef erase [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Array \u03b1 :=\n  match as.indexOf? a with\n  | none   => as\n  | some i => as.feraseIdx i\n\n/-- Insert element `a` at position `i`. -/\n@[inline] def insertAt (as : Array \u03b1) (i : Fin (as.size + 1)) (a : \u03b1) : Array \u03b1 :=\n  let rec loop (as : Array \u03b1) (j : Fin as.size) :=\n    if i.1 < j then\n      let j' := \u27e8j-1, Nat.lt_of_le_of_lt (Nat.pred_le _) j.2\u27e9\n      let as := as.swap j' j\n      loop as \u27e8j', by rw [size_swap]; exact j'.2\u27e9\n    else\n      as\n  let j := as.size\n  let as := as.push a\n  loop as \u27e8j, size_push .. \u25b8 j.lt_succ_self\u27e9\ntermination_by loop j => j.1\n\n/-- Insert element `a` at position `i`. Panics if `i` is not `i \u2264 as.size`. -/\ndef insertAt! (as : Array \u03b1) (i : Nat) (a : \u03b1) : Array \u03b1 :=\n  if h : i \u2264 as.size then\n    insertAt as \u27e8i, Nat.lt_succ_of_le h\u27e9 a\n  else panic! \"invalid index\"\n\ndef toListLitAux (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : \u2200 (i : Nat), i \u2264 a.size \u2192 List \u03b1 \u2192 List \u03b1\n  | 0,     _,  acc => acc\n  | (i+1), hi, acc => toListLitAux a n hsz i (Nat.le_of_succ_le hi) (a.getLit i hsz (Nat.lt_of_lt_of_eq (Nat.lt_of_lt_of_le (Nat.lt_succ_self i) hi) hsz) :: acc)\n\ndef toArrayLit (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : Array \u03b1 :=\n  List.toArray <| toListLitAux a n hsz n (hsz \u25b8 Nat.le_refl _) []\n\ntheorem ext' {as bs : Array \u03b1} (h : as.data = bs.data) : as = bs := by\n  cases as; cases bs; simp at h; rw [h]\n\ntheorem toArrayAux_eq (as : List \u03b1) (acc : Array \u03b1) : (as.toArrayAux acc).data = acc.data ++ as := by\n  induction as generalizing acc <;> simp [*, List.toArrayAux, Array.push, List.append_assoc, List.concat_eq_append]\n\ntheorem data_toArray (as : List \u03b1) : as.toArray.data = as := by\n  simp [List.toArray, toArrayAux_eq, Array.mkEmpty]\n\ntheorem toArrayLit_eq (as : Array \u03b1) (n : Nat) (hsz : as.size = n) : as = toArrayLit as n hsz := by\n  apply ext'\n  simp [toArrayLit, data_toArray]\n  have hle : n \u2264 as.size := hsz \u25b8 Nat.le_refl _\n  have hge : as.size \u2264 n := hsz \u25b8 Nat.le_refl _\n  have := go n hle\n  rw [List.drop_eq_nil_of_le hge] at this\n  rw [this]\nwhere\n  getLit_eq (as : Array \u03b1) (i : Nat) (h\u2081 : as.size = n) (h\u2082 : i < n) : as.getLit i h\u2081 h\u2082 = getElem as.data i ((id (\u03b1 := as.data.length = n) h\u2081) \u25b8 h\u2082) :=\n    rfl\n\n  go (i : Nat) (hi : i \u2264 as.size) : toListLitAux as n hsz i hi (as.data.drop i) = as.data := by\n    cases i <;> simp [getLit_eq, List.get_drop_eq_drop, toListLitAux, List.drop, go]\n\ndef isPrefixOfAux [BEq \u03b1] (as bs : Array \u03b1) (hle : as.size \u2264 bs.size) (i : Nat) : Bool :=\n  if h : i < as.size then\n    let a := as[i]\n    have : i < bs.size := Nat.lt_of_lt_of_le h hle\n    let b := bs[i]\n    if a == b then\n      isPrefixOfAux as bs hle (i+1)\n    else\n      false\n  else\n    true\ntermination_by _ => as.size - i\n\n/-- Return true iff `as` is a prefix of `bs`.\nThat is, `bs = as ++ t` for some `t : List \u03b1`.-/\ndef isPrefixOf [BEq \u03b1] (as bs : Array \u03b1) : Bool :=\n  if h : as.size \u2264 bs.size then\n    isPrefixOfAux as bs h 0\n  else\n    false\n\nprivate def allDiffAuxAux [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : forall (i : Nat), i < as.size \u2192 Bool\n  | 0,   _ => true\n  | i+1, h =>\n    have : i < as.size := Nat.lt_trans (Nat.lt_succ_self _) h;\n    a != as[i] && allDiffAuxAux as a i this\n\nprivate def allDiffAux [BEq \u03b1] (as : Array \u03b1) (i : Nat) : Bool :=\n  if h : i < as.size then\n    allDiffAuxAux as as[i] i h && allDiffAux as (i+1)\n  else\n    true\ntermination_by _ => as.size - i\n\ndef allDiff [BEq \u03b1] (as : Array \u03b1) : Bool :=\n  allDiffAux as 0\n\n@[specialize] def zipWithAux (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (as : Array \u03b1) (bs : Array \u03b2) (i : Nat) (cs : Array \u03b3) : Array \u03b3 :=\n  if h : i < as.size then\n    let a := as[i]\n    if h : i < bs.size then\n      let b := bs[i]\n      zipWithAux f as bs (i+1) <| cs.push <| f a b\n    else\n      cs\n  else\n    cs\ntermination_by _ => as.size - i\n\n@[inline] def zipWith (as : Array \u03b1) (bs : Array \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : Array \u03b3 :=\n  zipWithAux f as bs 0 #[]\n\ndef zip (as : Array \u03b1) (bs : Array \u03b2) : Array (\u03b1 \u00d7 \u03b2) :=\n  zipWith as bs Prod.mk\n\ndef unzip (as : Array (\u03b1 \u00d7 \u03b2)) : Array \u03b1 \u00d7 Array \u03b2 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b)\n\ndef split (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Array \u03b1 \u00d7 Array \u03b1 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) a =>\n    if p a then (as.push a, bs) else (as, bs.push a)\n\nend Array\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/Array/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.09534945525903342, "lm_q1q2_score": 0.04618537717413516}}
{"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 : \u2115\n\n    def double := x + x\n    #check double y\n    #check double (2 * x)\n\n    theorem t\u2081 : 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 : \u2115 := 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 \u03b1` for some type `\u03b1`. 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 \u2192 b \u2192 a \u2227 b := \nbegin\nintros h\u2081 h\u2082, \nsplit, repeat {assumption},\nend\n\nexample : a \u2192 b \u2192 a \u2227 b := \nby do eh\u2081 \u2190 intro `h\u2081,\n      eh\u2082 \u2190 intro `h\u2082, \n      split, \n      repeat assumption,\n      trace_state \n\ndef my_fun : list \u2115 :=\ndo l \u2190 [1,2,3],\n   l \u2190 [4,5,6],\n  return (l+1)\n\nexample : a \u2192 b \u2192 a \u2227 b :=\nbegin\nintros ha hb,\nexact (and.intro ha hb),\nend\n\n-- example : a \u2192 b \u2192 a \u2227 b := \n-- by do eh\u2081 \u2190 intro `h\u2081, \n--       eh\u2082 \u2190 intro `h\u2082, \n--       e \u2190 pure `(and.intro %%eh\u2081 %%eh\u2082),\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 \u2192 tactic bool \n| `(%%a \u2227 %%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 \u2190 local_context,\n   g \u2190 @list.mmap tactic _ expr expr infer_type ctx,\n  --  trace ctx,\n  --  trace g,\n   l \u2190 g.mfilter identify_conj,\n   trace l, \n   triv \n\nexample (h\u2081 : a \u2227 b) (h\u2082 : c \u2192 a) (h\u2083 : b \u2227 c) : true  := by do foo \n\n\n/-\nWe can also add hypotheses to the local context. (III)\n-/\n\nexample (h\u2081 : a) (h\u2082 : b) : true :=\nby do hyp\u2081 \u2190 get_local `h\u2081, \n      hyp\u2082 \u2190 get_local `h\u2082, \n      typ\u2081 \u2190 infer_type hyp\u2081, \n      typ\u2082 \u2190 infer_type hyp\u2082,\n      typ \u2190 to_expr ``(%%typ\u2081 \u2227 %%typ\u2082),\n      trm \u2190 to_expr ``(and.intro %%hyp\u2081 %%hyp\u2082),\n      n \u2190 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\u2081` is a prefix of `l\u2082` if `l\u2082` starts with `l\u2081`.\n* `list.subfix`: `l\u2081` is a subfix of `l\u2082` if `l\u2082` ends with `l\u2081`.\n* `list.infix`: `l\u2081` is an infix of `l\u2082` if `l\u2081` is a prefix of some subfix of `l\u2082`.\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\u2081 <+: l\u2082`: `l\u2081` is a prefix of `l\u2082`.\n`l\u2081 <:+ l\u2082`: `l\u2081` is a subfix of `l\u2082`.\n`l\u2081 <:+: l\u2082`: `l\u2081` is an infix of `l\u2082`.\n-/\n\nopen nat\n\nvariables {\u03b1 \u03b2 : Type*}\n\nnamespace list\nvariables {l l\u2081 l\u2082 l\u2083 : list \u03b1} {a b : \u03b1} {m n : \u2115}\n\n/-! ### prefix, suffix, infix -/\n\nsection fix\n\n@[simp] lemma prefix_append (l\u2081 l\u2082 : list \u03b1) : l\u2081 <+: l\u2081 ++ l\u2082 := \u27e8l\u2082, rfl\u27e9\n@[simp] lemma suffix_append (l\u2081 l\u2082 : list \u03b1) : l\u2082 <:+ l\u2081 ++ l\u2082 := \u27e8l\u2081, rfl\u27e9\n\nlemma infix_append (l\u2081 l\u2082 l\u2083 : list \u03b1) : l\u2082 <:+: l\u2081 ++ l\u2082 ++ l\u2083 := \u27e8l\u2081, l\u2083, rfl\u27e9\n\n@[simp] lemma infix_append' (l\u2081 l\u2082 l\u2083 : list \u03b1) : l\u2082 <:+: l\u2081 ++ (l\u2082 ++ l\u2083) :=\nby rw \u2190 list.append_assoc; apply infix_append\n\nlemma is_prefix.is_infix : l\u2081 <+: l\u2082 \u2192 l\u2081 <:+: l\u2082 := \u03bb \u27e8t, h\u27e9, \u27e8[], t, h\u27e9\nlemma is_suffix.is_infix : l\u2081 <:+ l\u2082 \u2192 l\u2081 <:+: l\u2082 := \u03bb \u27e8t, h\u27e9, \u27e8t, [], by rw [h, append_nil]\u27e9\n\nlemma nil_prefix (l : list \u03b1) : [] <+: l := \u27e8l, rfl\u27e9\nlemma nil_suffix (l : list \u03b1) : [] <:+ l := \u27e8l, append_nil _\u27e9\nlemma nil_infix (l : list \u03b1) : [] <:+: l := (nil_prefix _).is_infix\n\n@[refl] lemma prefix_refl (l : list \u03b1) : l <+: l := \u27e8[], append_nil _\u27e9\n@[refl] lemma suffix_refl (l : list \u03b1) : l <:+ l := \u27e8[], rfl\u27e9\n@[refl] lemma infix_refl (l : list \u03b1) : 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 : \u03b1) : \u2200 l, l <:+ a :: l := suffix_append [a]\n\nlemma prefix_concat (a : \u03b1) (l) : l <+: concat l a := by simp\n\nlemma infix_cons : l\u2081 <:+: l\u2082 \u2192 l\u2081 <:+: a :: l\u2082 := \u03bb \u27e8L\u2081, L\u2082, h\u27e9, \u27e8a :: L\u2081, L\u2082, h \u25b8 rfl\u27e9\nlemma infix_concat : l\u2081 <:+: l\u2082 \u2192 l\u2081 <:+: concat l\u2082 a :=\n\u03bb \u27e8L\u2081, L\u2082, h\u27e9, \u27e8L\u2081, concat L\u2082 a, by simp_rw [\u2190h, concat_eq_append, append_assoc]\u27e9\n\n@[trans] lemma is_prefix.trans : \u2200 {l\u2081 l\u2082 l\u2083 : list \u03b1}, l\u2081 <+: l\u2082 \u2192 l\u2082 <+: l\u2083 \u2192 l\u2081 <+: l\u2083\n| l ._ ._ \u27e8r\u2081, rfl\u27e9 \u27e8r\u2082, rfl\u27e9 := \u27e8r\u2081 ++ r\u2082, (append_assoc _ _ _).symm\u27e9\n\n@[trans] lemma is_suffix.trans : \u2200 {l\u2081 l\u2082 l\u2083 : list \u03b1}, l\u2081 <:+ l\u2082 \u2192 l\u2082 <:+ l\u2083 \u2192 l\u2081 <:+ l\u2083\n| l ._ ._ \u27e8l\u2081, rfl\u27e9 \u27e8l\u2082, rfl\u27e9 := \u27e8l\u2082 ++ l\u2081, append_assoc _ _ _\u27e9\n\n@[trans] lemma is_infix.trans : \u2200 {l\u2081 l\u2082 l\u2083 : list \u03b1}, l\u2081 <:+: l\u2082 \u2192 l\u2082 <:+: l\u2083 \u2192 l\u2081 <:+: l\u2083\n| l ._ ._ \u27e8l\u2081, r\u2081, rfl\u27e9 \u27e8l\u2082, r\u2082, rfl\u27e9 := \u27e8l\u2082 ++ l\u2081, r\u2081 ++ r\u2082, by simp only [append_assoc]\u27e9\n\nprotected lemma is_infix.sublist : l\u2081 <:+: l\u2082 \u2192 l\u2081 <+ l\u2082 :=\n\u03bb \u27e8s, t, h\u27e9, by { rw [\u2190 h], exact (sublist_append_right _ _).trans (sublist_append_left _ _) }\n\nprotected lemma is_infix.subset (hl : l\u2081 <:+: l\u2082) : l\u2081 \u2286 l\u2082 :=\nhl.sublist.subset\n\nprotected lemma is_prefix.sublist (h : l\u2081 <+: l\u2082) : l\u2081 <+ l\u2082 :=\nh.is_infix.sublist\n\nprotected lemma is_prefix.subset (hl : l\u2081 <+: l\u2082) : l\u2081 \u2286 l\u2082 :=\nhl.sublist.subset\n\nprotected lemma is_suffix.sublist (h : l\u2081 <:+ l\u2082) : l\u2081 <+ l\u2082 :=\nh.is_infix.sublist\n\nprotected lemma is_suffix.subset (hl : l\u2081 <:+ l\u2082) : l\u2081 \u2286 l\u2082 :=\nhl.sublist.subset\n\n@[simp] lemma reverse_suffix : reverse l\u2081 <:+ reverse l\u2082 \u2194 l\u2081 <+: l\u2082 :=\n\u27e8\u03bb \u27e8r, e\u27e9, \u27e8reverse r,\n  by rw [\u2190 reverse_reverse l\u2081, \u2190 reverse_append, e, reverse_reverse]\u27e9,\n \u03bb \u27e8r, e\u27e9, \u27e8reverse r, by rw [\u2190 reverse_append, e]\u27e9\u27e9\n\n@[simp] lemma reverse_prefix : reverse l\u2081 <+: reverse l\u2082 \u2194 l\u2081 <:+ l\u2082 :=\nby rw \u2190 reverse_suffix; simp only [reverse_reverse]\n\n@[simp] lemma reverse_infix : reverse l\u2081 <:+: reverse l\u2082 \u2194 l\u2081 <:+: l\u2082 :=\n\u27e8\u03bb \u27e8s, t, e\u27e9, \u27e8reverse t, reverse s,\n  by rw [\u2190 reverse_reverse l\u2081, append_assoc,\n    \u2190 reverse_append, \u2190 reverse_append, e, reverse_reverse]\u27e9,\n \u03bb \u27e8s, t, e\u27e9, \u27e8reverse t, reverse s,\n  by rw [append_assoc, \u2190 reverse_append, \u2190 reverse_append, e]\u27e9\u27e9\n\nalias reverse_prefix \u2194 _ is_suffix.reverse\nalias reverse_suffix \u2194 _ is_prefix.reverse\nalias reverse_infix \u2194 _ is_infix.reverse\n\nlemma is_infix.length_le (h : l\u2081 <:+: l\u2082) : l\u2081.length \u2264 l\u2082.length := h.sublist.length_le\nlemma is_prefix.length_le (h : l\u2081 <+: l\u2082) : l\u2081.length \u2264 l\u2082.length := h.sublist.length_le\nlemma is_suffix.length_le (h : l\u2081 <:+ l\u2082) : l\u2081.length \u2264 l\u2082.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 <:+: [] \u2194 l = [] :=\n\u27e8\u03bb h, eq_nil_of_sublist_nil h.sublist, \u03bb h, h \u25b8 infix_rfl\u27e9\n\nalias infix_nil_iff \u2194 eq_nil_of_infix_nil _\n\n@[simp] lemma prefix_nil_iff : l <+: [] \u2194 l = [] :=\n\u27e8\u03bb h, eq_nil_of_infix_nil h.is_infix, \u03bb h, h \u25b8 prefix_rfl\u27e9\n\n@[simp] lemma suffix_nil_iff : l <:+ [] \u2194 l = [] :=\n\u27e8\u03bb h, eq_nil_of_infix_nil h.is_infix, \u03bb h, h \u25b8 suffix_rfl\u27e9\n\nalias prefix_nil_iff \u2194 eq_nil_of_prefix_nil _\nalias suffix_nil_iff \u2194 eq_nil_of_suffix_nil _\n\nlemma infix_iff_prefix_suffix (l\u2081 l\u2082 : list \u03b1) : l\u2081 <:+: l\u2082 \u2194 \u2203 t, l\u2081 <+: t \u2227 t <:+ l\u2082 :=\n\u27e8\u03bb \u27e8s, t, e\u27e9, \u27e8l\u2081 ++ t, \u27e8_, rfl\u27e9, by rw [\u2190 e, append_assoc]; exact \u27e8_, rfl\u27e9\u27e9,\n  \u03bb \u27e8._, \u27e8t, rfl\u27e9, s, e\u27e9, \u27e8s, t, by rw append_assoc; exact e\u27e9\u27e9\n\nlemma eq_of_infix_of_length_eq (h : l\u2081 <:+: l\u2082) : l\u2081.length = l\u2082.length \u2192 l\u2081 = l\u2082 :=\nh.sublist.eq_of_length\n\nlemma eq_of_prefix_of_length_eq (h : l\u2081 <+: l\u2082) : l\u2081.length = l\u2082.length \u2192 l\u2081 = l\u2082 :=\nh.sublist.eq_of_length\n\nlemma eq_of_suffix_of_length_eq (h : l\u2081 <:+ l\u2082) : l\u2081.length = l\u2082.length \u2192 l\u2081 = l\u2082 :=\nh.sublist.eq_of_length\n\nlemma prefix_of_prefix_length_le : \u2200 {l\u2081 l\u2082 l\u2083 : list \u03b1},\n  l\u2081 <+: l\u2083 \u2192 l\u2082 <+: l\u2083 \u2192 length l\u2081 \u2264 length l\u2082 \u2192 l\u2081 <+: l\u2082\n| []      l\u2082 l\u2083 h\u2081 h\u2082 _ := nil_prefix _\n| (a :: l\u2081) (b :: l\u2082) _ \u27e8r\u2081, rfl\u27e9 \u27e8r\u2082, e\u27e9 ll := begin\n  injection e with _ e', subst b,\n  rcases prefix_of_prefix_length_le \u27e8_, rfl\u27e9 \u27e8_, e'\u27e9\n    (le_of_succ_le_succ ll) with \u27e8r\u2083, rfl\u27e9,\n  exact \u27e8r\u2083, rfl\u27e9\nend\n\nlemma prefix_or_prefix_of_prefix (h\u2081 : l\u2081 <+: l\u2083) (h\u2082 : l\u2082 <+: l\u2083) : l\u2081 <+: l\u2082 \u2228 l\u2082 <+: l\u2081 :=\n(le_total (length l\u2081) (length l\u2082)).imp\n  (prefix_of_prefix_length_le h\u2081 h\u2082)\n  (prefix_of_prefix_length_le h\u2082 h\u2081)\n\nlemma suffix_of_suffix_length_le (h\u2081 : l\u2081 <:+ l\u2083) (h\u2082 : l\u2082 <:+ l\u2083) (ll : length l\u2081 \u2264 length l\u2082) :\n  l\u2081 <:+ l\u2082 :=\nreverse_prefix.1 $ prefix_of_prefix_length_le\n  (reverse_prefix.2 h\u2081) (reverse_prefix.2 h\u2082) (by simp [ll])\n\nlemma suffix_or_suffix_of_suffix (h\u2081 : l\u2081 <:+ l\u2083) (h\u2082 : l\u2082 <:+ l\u2083) : l\u2081 <:+ l\u2082 \u2228 l\u2082 <:+ l\u2081 :=\n(prefix_or_prefix_of_prefix (reverse_prefix.2 h\u2081) (reverse_prefix.2 h\u2082)).imp\n  reverse_prefix.1 reverse_prefix.1\n\nlemma suffix_cons_iff : l\u2081 <:+ a :: l\u2082 \u2194 l\u2081 = a :: l\u2082 \u2228 l\u2081 <:+ l\u2082 :=\nbegin\n  split,\n  { rintro \u27e8\u27e8hd, tl\u27e9, hl\u2083\u27e9,\n    { exact or.inl hl\u2083 },\n    { simp only [cons_append] at hl\u2083,\n      exact or.inr \u27e8_, hl\u2083.2\u27e9 } },\n  { rintro (rfl | hl\u2081),\n    { exact (a :: l\u2082).suffix_refl },\n    { exact hl\u2081.trans (l\u2082.suffix_cons _) } }\nend\n\nlemma infix_cons_iff : l\u2081 <:+: a :: l\u2082 \u2194 l\u2081 <+: a :: l\u2082 \u2228 l\u2081 <:+: l\u2082 :=\nbegin\n  split,\n  { rintro \u27e8\u27e8hd, tl\u27e9, t, hl\u2083\u27e9,\n    { exact or.inl \u27e8t, hl\u2083\u27e9 },\n    { simp only [cons_append] at hl\u2083,\n      exact or.inr \u27e8_, t, hl\u2083.2\u27e9 } },\n  { rintro (h | hl\u2081),\n    { exact h.is_infix },\n    { exact infix_cons hl\u2081 } }\nend\n\nlemma infix_of_mem_join : \u2200 {L : list (list \u03b1)}, l \u2208 L \u2192 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\u2081 <+: l ++ l\u2082 \u2194 l\u2081 <+: l\u2082 :=\nexists_congr $ \u03bb r, by rw [append_assoc, append_right_inj]\n\nlemma prefix_cons_inj (a) : a :: l\u2081 <+: a :: l\u2082 \u2194 l\u2081 <+: l\u2082 := prefix_append_right_inj [a]\n\nlemma take_prefix (n) (l : list \u03b1) : take n l <+: l := \u27e8_, take_append_drop _ _\u27e9\nlemma drop_suffix (n) (l : list \u03b1) : drop n l <:+ l := \u27e8_, take_append_drop _ _\u27e9\nlemma take_sublist (n) (l : list \u03b1) : take n l <+ l := (take_prefix n l).sublist\nlemma drop_sublist (n) (l : list \u03b1) : drop n l <+ l := (drop_suffix n l).sublist\nlemma take_subset (n) (l : list \u03b1) : take n l \u2286 l := (take_sublist n l).subset\nlemma drop_subset (n) (l : list \u03b1) : drop n l \u2286 l := (drop_sublist n l).subset\nlemma mem_of_mem_take (h : a \u2208 l.take n) : a \u2208 l := take_subset n l h\nlemma mem_of_mem_drop (h : a \u2208 l.drop n) : a \u2208 l := drop_subset n l h\n\nlemma slice_sublist (n m : \u2115) (l : list \u03b1) : l.slice n m <+ l :=\nbegin\n  rw list.slice_eq,\n  conv_rhs {rw \u2190list.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 : \u2115) (l : list \u03b1) : l.slice n m \u2286 l := (slice_sublist n m l).subset\nlemma mem_of_mem_slice {n m : \u2115} {l : list \u03b1} {a : \u03b1} (h : a \u2208 l.slice n m) : a \u2208 l :=\nslice_subset n m l h\n\nlemma take_while_prefix (p : \u03b1 \u2192 Prop) [decidable_pred p] : l.take_while p <+: l :=\n\u27e8l.drop_while p, take_while_append_drop p l\u27e9\n\nlemma drop_while_suffix (p : \u03b1 \u2192 Prop) [decidable_pred p] : l.drop_while p <:+ l :=\n\u27e8l.take_while p, take_while_append_drop p l\u27e9\n\nlemma init_prefix : \u2200 (l : list \u03b1), l.init <+: l\n| [] := \u27e8nil, by rw [init, list.append_nil]\u27e9\n| (a :: l) := \u27e8_, init_append_last (cons_ne_nil a l)\u27e9\n\nlemma tail_suffix (l : list \u03b1) : tail l <:+ l := by rw \u2190 drop_one; apply drop_suffix\n\nlemma init_sublist (l : list \u03b1) : l.init <+ l := (init_prefix l).sublist\n\n\nlemma prefix_iff_eq_append : l\u2081 <+: l\u2082 \u2194 l\u2081 ++ drop (length l\u2081) l\u2082 = l\u2082 :=\n\u27e8by rintros \u27e8r, rfl\u27e9; rw drop_left, \u03bb e, \u27e8_, e\u27e9\u27e9\n\nlemma suffix_iff_eq_append : l\u2081 <:+ l\u2082 \u2194 take (length l\u2082 - length l\u2081) l\u2082 ++ l\u2081 = l\u2082 :=\n\u27e8by rintros \u27e8r, rfl\u27e9; simp only [length_append, add_tsub_cancel_right, take_left], \u03bb e, \u27e8_, e\u27e9\u27e9\n\nlemma prefix_iff_eq_take : l\u2081 <+: l\u2082 \u2194 l\u2081 = take (length l\u2081) l\u2082 :=\n\u27e8\u03bb h, append_right_cancel $\n  (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n \u03bb e, e.symm \u25b8 take_prefix _ _\u27e9\n\nlemma suffix_iff_eq_drop : l\u2081 <:+ l\u2082 \u2194 l\u2081 = drop (length l\u2082 - length l\u2081) l\u2082 :=\n\u27e8\u03bb h, append_left_cancel $\n  (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n \u03bb e, e.symm \u25b8 drop_suffix _ _\u27e9\n\ninstance decidable_prefix [decidable_eq \u03b1] : \u2200 (l\u2081 l\u2082 : list \u03b1), decidable (l\u2081 <+: l\u2082)\n| []        l\u2082        := is_true \u27e8l\u2082, rfl\u27e9\n| (a :: l\u2081) []        := is_false $ \u03bb \u27e8t, te\u27e9, list.no_confusion te\n| (a :: l\u2081) (b :: l\u2082) :=\n  if h : a = b then\n    decidable_of_decidable_of_iff (decidable_prefix l\u2081 l\u2082) (by rw [\u2190 h, prefix_cons_inj])\n  else\n    is_false $ \u03bb \u27e8t, te\u27e9, h $ by injection te\n\n-- Alternatively, use mem_tails\ninstance decidable_suffix [decidable_eq \u03b1] : \u2200 (l\u2081 l\u2082 : list \u03b1), decidable (l\u2081 <:+ l\u2082)\n| []        l\u2082        := is_true \u27e8l\u2082, append_nil _\u27e9\n| (a :: l\u2081) []        := is_false $ mt (sublist.length_le \u2218 is_suffix.sublist) dec_trivial\n| l\u2081        (b :: l\u2082) := decidable_of_decidable_of_iff (@or.decidable _ _\n    _ (l\u2081.decidable_suffix l\u2082)) suffix_cons_iff.symm\n\ninstance decidable_infix [decidable_eq \u03b1] : \u2200 (l\u2081 l\u2082 : list \u03b1), decidable (l\u2081 <:+: l\u2082)\n| []        l\u2082        := is_true \u27e8[], l\u2082, rfl\u27e9\n| (a :: l\u2081) []        := is_false $ \u03bb \u27e8s, t, te\u27e9, by simp at te; exact te\n| l\u2081        (b :: l\u2082) := decidable_of_decidable_of_iff (@or.decidable _ _\n    (l\u2081.decidable_prefix (b :: l\u2082)) (l\u2081.decidable_infix l\u2082)) infix_cons_iff.symm\n\nlemma prefix_take_le_iff {L : list (list (option \u03b1))} (hm : m < L.length) :\n  L.take m <+: L.take n \u2194 m \u2264 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 \u27e8nat.succ_le_succ, nat.le_of_succ_le_succ\u27e9 }\nend\n\nlemma cons_prefix_iff : a :: l\u2081 <+: b :: l\u2082 \u2194 a = b \u2227 l\u2081 <+: l\u2082 :=\nbegin\n  split,\n  { rintro \u27e8L, hL\u27e9,\n    simp only [cons_append] at hL,\n    exact \u27e8hL.left, \u27e8L, hL.right\u27e9\u27e9 },\n  { rintro \u27e8rfl, h\u27e9,\n    rwa [prefix_cons_inj] }\nend\n\nlemma is_prefix.map (h : l\u2081 <+: l\u2082) (f : \u03b1 \u2192 \u03b2) : l\u2081.map f <+: l\u2082.map f :=\nbegin\n  induction l\u2081 with hd tl hl generalizing l\u2082,\n  { simp only [nil_prefix, map_nil] },\n  { cases l\u2082 with hd\u2082 tl\u2082,\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\u2081 <+: l\u2082) (f : \u03b1 \u2192 option \u03b2) :\n  l\u2081.filter_map f <+: l\u2082.filter_map f :=\nbegin\n  induction l\u2081 with hd\u2081 tl\u2081 hl generalizing l\u2082,\n  { simp only [nil_prefix, filter_map_nil] },\n  { cases l\u2082 with hd\u2082 tl\u2082,\n    { simpa only using eq_nil_of_prefix_nil h },\n    { rw cons_prefix_iff at h,\n      rw [\u2190@singleton_append _ hd\u2081 _, \u2190@singleton_append _ hd\u2082 _, 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\u2081 l\u2082 : list (option \u03b1)} (h : l\u2081 <+: l\u2082) :\n  l\u2081.reduce_option <+: l\u2082.reduce_option :=\nh.filter_map id\n\nlemma is_prefix.filter (p : \u03b1 \u2192 Prop) [decidable_pred p] \u2983l\u2081 l\u2082 : list \u03b1\u2984 (h : l\u2081 <+: l\u2082) :\n  l\u2081.filter p <+: l\u2082.filter p :=\nbegin\n  obtain \u27e8xs, rfl\u27e9 := h,\n  rw filter_append,\n  exact prefix_append _ _\nend\n\nlemma is_suffix.filter (p : \u03b1 \u2192 Prop) [decidable_pred p] \u2983l\u2081 l\u2082 : list \u03b1\u2984 (h : l\u2081 <:+ l\u2082) :\n  l\u2081.filter p <:+ l\u2082.filter p :=\nbegin\n  obtain \u27e8xs, rfl\u27e9 := h,\n  rw filter_append,\n  exact suffix_append _ _\nend\n\nlemma is_infix.filter (p : \u03b1 \u2192 Prop) [decidable_pred p] \u2983l\u2081 l\u2082 : list \u03b1\u2984 (h : l\u2081 <:+: l\u2082) :\n  l\u2081.filter p <:+: l\u2082.filter p :=\nbegin\n  obtain \u27e8xs, ys, rfl\u27e9 := h,\n  rw [filter_append, filter_append],\n  exact infix_append _ _ _\nend\n\ninstance : is_partial_order (list \u03b1) (<+:) :=\n{ refl := prefix_refl,\n  trans := \u03bb _ _ _, is_prefix.trans,\n  antisymm := \u03bb _ _ h\u2081 h\u2082, eq_of_prefix_of_length_eq h\u2081 $ h\u2081.length_le.antisymm h\u2082.length_le }\n\ninstance : is_partial_order (list \u03b1) (<:+) :=\n{ refl := suffix_refl,\n  trans := \u03bb _ _ _, is_suffix.trans,\n  antisymm := \u03bb _ _ h\u2081 h\u2082, eq_of_suffix_of_length_eq h\u2081 $ h\u2081.length_le.antisymm h\u2082.length_le }\n\ninstance : is_partial_order (list \u03b1) (<:+:) :=\n{ refl := infix_refl,\n  trans := \u03bb _ _ _, is_infix.trans,\n  antisymm := \u03bb _ _ h\u2081 h\u2082, eq_of_infix_of_length_eq h\u2081 $ h\u2081.length_le.antisymm h\u2082.length_le }\n\nend fix\n\nsection inits_tails\n\n@[simp] lemma mem_inits : \u2200 (s t : list \u03b1), s \u2208 inits t \u2194 s <+: t\n| s []     := suffices s = nil \u2194 s <+: nil, by simpa only [inits, mem_singleton],\n  \u27e8\u03bb h, h.symm \u25b8 prefix_refl [], eq_nil_of_prefix_nil\u27e9\n| s (a :: t) :=\n  suffices (s = nil \u2228 \u2203 l \u2208 inits t, a :: l = s) \u2194 s <+: a :: t, by simpa,\n  \u27e8\u03bb o, match s, o with\n  | ._, or.inl rfl := \u27e8_, rfl\u27e9\n  | s, or.inr \u27e8r, hr, hs\u27e9 := let \u27e8s, ht\u27e9 := (mem_inits _ _).1 hr in\n    by rw [\u2190 hs, \u2190 ht]; exact \u27e8s, rfl\u27e9\n  end, \u03bb mi, match s, mi with\n  | [], \u27e8._, rfl\u27e9 := or.inl rfl\n  | (b :: s), \u27e8r, hr\u27e9 := list.no_confusion hr $ \u03bb ba (st : s++r = t), or.inr $\n    by rw ba; exact \u27e8_, (mem_inits _ _).2 \u27e8_, st\u27e9, rfl\u27e9\n  end\u27e9\n\n@[simp] lemma mem_tails : \u2200 (s t : list \u03b1), s \u2208 tails t \u2194 s <:+ t\n| s []     := by simp only [tails, mem_singleton];\n  exact \u27e8\u03bb h, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil\u27e9\n| s (a :: t) := by simp only [tails, mem_cons_iff, mem_tails s t];\n  exact show s = a :: t \u2228 s <:+ t \u2194 s <:+ a :: t, from\n  \u27e8\u03bb o, match s, t, o with\n  | ._, t, or.inl rfl := suffix_rfl\n  | s, ._, or.inr \u27e8l, rfl\u27e9 := \u27e8a :: l, rfl\u27e9\n  end, \u03bb e, match s, t, e with\n  | ._, t, \u27e8[], rfl\u27e9 := or.inl rfl\n  | s, t, \u27e8b :: l, he\u27e9 := list.no_confusion he (\u03bb ab lt, or.inr \u27e8l, lt\u27e9)\n  end\u27e9\n\nlemma inits_cons (a : \u03b1) (l : list \u03b1) : inits (a :: l) = [] :: l.inits.map (\u03bb t, a :: t) := by simp\nlemma tails_cons (a : \u03b1) (l : list \u03b1) : tails (a :: l) = (a :: l) :: l.tails := by simp\n\n@[simp]\nlemma inits_append : \u2200 (s t : list \u03b1), inits (s ++ t) = s.inits ++ t.inits.tail.map (\u03bb 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 : \u2200 (s t : list \u03b1), tails (s ++ t) = s.tails.map (\u03bb 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 : \u2200 (l : list \u03b1), 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 : \u2200 (l : list \u03b1), 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : length (inits l) = length l + 1 :=\nby simp [inits_eq_tails]\n\n@[simp] lemma nth_le_tails (l : list \u03b1) (n : \u2115) (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 \u03b1) (n : \u2115) (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 \u03b1]\n\n@[simp] lemma insert_nil (a : \u03b1) : insert a nil = [a] := rfl\n\nlemma insert.def (a : \u03b1) (l : list \u03b1) : insert a l = if a \u2208 l then l else a :: l := rfl\n\n@[simp, priority 980]\nlemma insert_of_mem (h : a \u2208 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 \u2209 l) : insert a l = a :: l :=\nby simp only [insert.def, if_neg h]; split; refl\n\n@[simp] lemma mem_insert_iff : a \u2208 insert b l \u2194 a = b \u2228 a \u2208 l :=\nbegin\n  by_cases h' : b \u2208 l,\n  { simp only [insert_of_mem h'],\n    apply (or_iff_right_of_imp _).symm,\n    exact \u03bb e, e.symm \u25b8 h' },\n  { simp only [insert_of_not_mem h', mem_cons_iff] }\nend\n\n@[simp] lemma suffix_insert (a : \u03b1) (l : list \u03b1) : l <:+ insert a l :=\nby by_cases a \u2208 l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]\n\nlemma infix_insert (a : \u03b1) (l : list \u03b1) : l <:+: insert a l := (suffix_insert a l).is_infix\nlemma sublist_insert (a : \u03b1) (l : list \u03b1) : l <+  l.insert a := (suffix_insert a l).sublist\nlemma subset_insert (a : \u03b1) (l : list \u03b1) : l \u2286 l.insert a := (sublist_insert a l).subset\n\n@[simp] lemma mem_insert_self (a : \u03b1) (l : list \u03b1) : a \u2208  l.insert a :=\nmem_insert_iff.2 $ or.inl rfl\n\nlemma mem_insert_of_mem (h : a \u2208 l) : a \u2208 insert b l := mem_insert_iff.2 (or.inr h)\n\nlemma eq_or_mem_of_mem_insert (h : a \u2208 insert b l) : a = b \u2228 a \u2208 l := mem_insert_iff.1 h\n\n@[simp] lemma length_insert_of_mem (h : a \u2208 l) : (insert a l).length = l.length :=\ncongr_arg _ $ insert_of_mem h\n\n@[simp] lemma length_insert_of_not_mem (h : a \u2209 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 \u2208 l\u2081) (hl : l\u2081 <:+ l\u2082) : a \u2208 l\u2082 :=\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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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\u03bb 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 := \u27e8\u03bb ns,\n                ns.mfoldl\n                  (\u03bb 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 \u2190 aux_attr.get_param_untyped n',\n                    pure $ dict.insert n param.app_arg.const_name)\n                  mk_name_map, []\u27e9 }\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 `\u2115` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nmeta def ignore_args_attr : user_attribute (name_map $ list \u2115) (list \u2115) :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\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 `\u2115 \u00d7 \u03b1`\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 \u2115) \u2115 :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\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 \u2115) (list \u2115) :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\n  parser    := do\n    l \u2190 (lean.parser.small_nat)*,\n    guard (l.all (\u2260 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 \u2115 := do\n  d \u2190 get_decl nm,\n  let (es, _) := d.type.pi_binders,\n  l \u2190 es.mmap_with_index $ \u03bb n bi, do\n  { let tgt := bi.type.pi_codomain,\n    let n_bi := bi.type.pi_binders.fst.length,\n    tt \u2190 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 $ \u03bb 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 \u2192 string \u2192 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 \u2192 list string \u2192 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 \u2192 string :=\nstring.map_tokens ''' $\n\u03bb 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 \u2260 name.anonymous \u2228 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 \u2260 tgt_auto \u2228 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(\u03bb res,\n  if res = src \u2227 tgt \u2260 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 \u2190 option.is_some <$> (tk \"!\")?,\n  ques \u2190 option.is_some <$> (tk \"?\")?,\n  tgt \u2190 ident?,\n  e \u2190 texpr?,\n  doc \u2190 match e with\n      | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n      | none := pure none\n      end,\n  return \u27e8bang, ques, tgt.get_or_else name.anonymous, doc, ff\u27e9\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : \u2115) (f : name \u2192 tactic (list string)) :\n  command :=\ndo\n  src_fields \u2190 f src,\n  tgt_fields \u2190 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    \u03bb 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 : \u2115) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (\u03bb n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (\u03bb n, (list.map (\u03bb (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (\u03bb n, (env.constructors_of n).mmap $\n          \u03bb 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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 \u00d7 N) := \u27e8\u03bb p q, \u27e8p.1 * q.1, p.2 * q.2\u27e9\u27e9\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 \u2115 n m` (i.e. `(n * m : \u2115)`) will not change to `+`, since its\n  first argument is `\u2115`, an identifier not applied to any arguments.\n* `@has_mul.mul (\u03b1 \u00d7 \u03b2) x y` will change to `+`. It's first argument contains only the identifier\n  `prod`, but this is applied to arguments, `\u03b1` and `\u03b2`.\n* `@has_mul.mul (\u03b1 \u00d7 \u2124) x y` will not change to `+`, since its first argument contains `\u2124`.\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 `\u21a5Semigroup` is replaced by addition in `\u21a5AddSemigroup`.\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 \u2115)` can contain `\u2115`\n  (usually in the form `has_top.top \u2115 ...`) and still be additivized.\n  So `@has_mul.mul (C^\u221e\u27eeI, N; I', G\u27ef) _ 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 `\u2115` or `\u211d`. 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 `\u2115` or `\u211d`. Solutions:\n  * If the fixed type has an additive counterpart (like `\u21a5Semigroup`), 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 \u201cmain\u201d 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 \u201cmain\u201d 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 (\u201cmul\u201d, \u201cone\u201d, \u201cinv\u201d, \u201cprod\u201d) 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 $ \u03bb src prio persistent, do\n    guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n    env \u2190 get_env,\n    val \u2190 attr.get_param src,\n    dict \u2190 aux_attr.get_cache,\n    ignore \u2190 ignore_args_attr.get_cache,\n    relevant \u2190 relevant_arg_attr.get_cache,\n    reorder \u2190 reorder_attr.get_cache,\n    tgt \u2190 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 \u2190 first_multiplicative_arg src,\n    when (first_mult_arg \u2260 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) 2022 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Patrick Massot, Scott Morrison\n-/\nimport tactic.core\nimport tactic.lint.basic\n\n/-!\n# User commands for assert the (non-)existence of declaration or instances.\n\nThese commands are used to enforce the independence of different parts of mathlib.\n\n## Implementation notes\n\nThis file provides two linters that verify that things we assert do not _yet_ exist do _eventually_\nexist. This works by creating declarations of the form:\n\n* ``assert_not_exists._checked.<uniq> : name := `foo`` for `assert_not_exists foo`\n* `assert_no_instance._checked.<uniq> := t` for `assert_instance t`\n\nThese declarations are then picked up by the linter and analyzed accordingly.\nThe `_` in the `_checked` prefix should hide them from doc-gen.\n-/\n\nsection\nsetup_tactic_parser\nopen tactic\n\n/--\n`assert_exists n` is a user command that asserts that a declaration named `n` exists\nin the current import scope.\n\nBe careful to use names (e.g. `rat`) rather than notations (e.g. `\u211a`).\n-/\n@[user_command]\nmeta def assert_exists (_ : parse $ tk \"assert_exists\")  : lean.parser unit :=\ndo decl \u2190 ident,\n   d \u2190 get_decl decl,\n   return ()\n\n/--\n`assert_not_exists n` is a user command that asserts that a declaration named `n` *does not exist*\nin the current import scope.\n\nBe careful to use names (e.g. `rat`) rather than notations (e.g. `\u211a`).\n\nIt may be used (sparingly!) in mathlib to enforce plans that certain files\nare independent of each other.\n\nIf you encounter an error on an `assert_not_exists` command while developing mathlib,\nit is probably because you have introduced new import dependencies to a file.\n\nIn this case, you should refactor your work\n(for example by creating new files rather than adding imports to existing files).\nYou should *not* delete the `assert_not_exists` statement without careful discussion ahead of time.\n-/\n@[user_command]\nmeta def assert_not_exists (_ : parse $ tk \"assert_not_exists\")  : lean.parser unit :=\ndo\n  decl \u2190 ident,\n  ff \u2190 succeeds (get_decl decl) |\n  fail format!\"Declaration {decl} is not allowed to exist in this file.\",\n  n \u2190 tactic.mk_fresh_name,\n  let marker := (`assert_not_exists._checked).append (decl.append n),\n  add_decl\n    (declaration.defn marker [] `(name) `(decl) default tt),\n  pure ()\n\n/-- A linter for checking that the declarations marked `assert_not_exists` eventually exist. -/\nmeta def assert_not_exists.linter : linter :=\n{ test := \u03bb d, (do\n    let n := d.to_name,\n    tt \u2190 pure ((`assert_not_exists._checked).is_prefix_of n) | pure none,\n    declaration.defn _ _ `(name) val _ _ \u2190 pure d,\n    n \u2190 tactic.eval_expr name val,\n    tt \u2190 succeeds (get_decl n) | pure (some (format!\"`{n}` does not ever exist\").to_string),\n    pure none),\n  auto_decls := tt,\n  no_errors_found := \"All `assert_not_exists` declarations eventually exist.\",\n  errors_found :=\n    \"The following declarations used in `assert_not_exists` never exist; perhaps there is a typo.\",\n  is_fast := tt }\n\n/--\n`assert_instance e` is a user command that asserts that an instance `e` is available\nin the current import scope.\n\nExample usage:\n```\nassert_instance semiring \u2115\n```\n-/\n@[user_command]\nmeta def assert_instance (_ : parse $ tk \"assert_instance\")  : lean.parser unit :=\ndo q \u2190 texpr,\n   e \u2190 i_to_expr q,\n   mk_instance e,\n   return ()\n\n/--\n`assert_no_instance e` is a user command that asserts that an instance `e` *is not available*\nin the current import scope.\n\nIt may be used (sparingly!) in mathlib to enforce plans that certain files\nare independent of each other.\n\nIf you encounter an error on an `assert_no_instance` command while developing mathlib,\nit is probably because you have introduced new import dependencies to a file.\n\nIn this case, you should refactor your work\n(for example by creating new files rather than adding imports to existing files).\nYou should *not* delete the `assert_no_instance` statement without careful discussion ahead of time.\n\nExample usage:\n```\nassert_no_instance linear_ordered_field \u211a\n```\n-/\n@[user_command]\nmeta def assert_no_instance (_ : parse $ tk \"assert_no_instance\")  : lean.parser unit :=\ndo\n  q \u2190 texpr,\n  e \u2190 i_to_expr q,\n  i \u2190 try_core (mk_instance e),\n  match i with\n  | none := do\n      n \u2190 tactic.mk_fresh_name,\n      e_str \u2190 to_string <$> pp e,\n      let marker := ((`assert_no_instance._checked).mk_string e_str).append n,\n      et \u2190 infer_type e,\n      tt \u2190 succeeds (get_decl marker) |\n      add_decl\n          (declaration.defn marker [] et e default tt),\n      pure ()\n  | some i :=\n   (fail!\"Instance `{i} : {e}` is not allowed to be found in this file.\" : tactic unit)\n  end\n\n/-- A linter for checking that the declarations marked `assert_no_instance` eventually exist. -/\nmeta def assert_no_instance.linter : linter :=\n{ test := \u03bb d, (do\n    let n := d.to_name,\n    tt \u2190 pure ((`assert_no_instance._checked).is_prefix_of n) | pure none,\n    declaration.defn _ _ _ val _ _ \u2190 pure d,\n    tt \u2190 succeeds (tactic.mk_instance val)\n      | (some \u2218 format.to_string) <$> pformat!\"No instance of `{val}`\",\n    pure none),\n  auto_decls := tt,\n  no_errors_found := \"All `assert_no_instance` instances eventually exist.\",\n  errors_found :=\n    \"The following typeclass instances used in `assert_no_instance` never exist; perhaps they \" ++\n    \"are missing?\",\n  is_fast := ff }\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/assert_exists.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943704494217, "lm_q2_score": 0.1460872489071524, "lm_q1q2_score": 0.04538848582989569}}
{"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 {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (Thunk \u03b1) := by\n  intro a b\n  have : a = b \u2194 a.get = b.get := \u27e8by intro x; rw [x], by intro; ext; assumption\u27e9\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 (\u03b1 : Type _) : List \u03b1 \u2243 LazyList \u03b1\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 {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (LazyList \u03b1)\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 \u2192 Type u} [Applicative m] {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) :\n    LazyList \u03b1 \u2192 m (LazyList \u03b2)\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  \u00b7 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  \u00b7 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  \u00b7 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 {\u03b1} : LazyList \u03b1 \u2192 LazyList \u03b1\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 {\u03b1} (p : \u03b1 \u2192 Prop) [DecidablePred p] : LazyList \u03b1 \u2192 Option \u03b1\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 {\u03b1} : LazyList \u03b1 \u2192 LazyList \u03b1 \u2192 LazyList \u03b1\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 {\u03b1} : List (LazyList \u03b1) \u2192 LazyList \u03b1\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 {\u03b1 \u03b2} : LazyList \u03b1 \u2192 (\u03b1 \u2192 LazyList \u03b2) \u2192 LazyList \u03b2\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 {\u03b1} (xs : LazyList \u03b1) : LazyList \u03b1 :=\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 {\u03b1} (xs : LazyList \u03b1) : 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 {\u03b1} (xs ys zs : LazyList \u03b1) :\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 {\u03b1 \u03b2} (xs : LazyList \u03b1) (ys : Thunk (LazyList \u03b1)) (f : \u03b1 \u2192 LazyList \u03b2) :\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] {\u03b1 \u03b2} (f : \u03b1 \u2192 m \u03b2) : LazyList \u03b1 \u2192 m \u03b2\n  | nil => failure\n  | cons x xs => f x <|> xs.get.mfirst f\n#align lazy_list.mfirst LazyList.mfirst\u2093\n\n/-- Membership in lazy lists -/\nprotected def Mem {\u03b1} (x : \u03b1) : LazyList \u03b1 \u2192 Prop\n  | nil => False\n  | cons y ys => x = y \u2228 ys.get.Mem x\n#align lazy_list.mem LazyList.Mem\n\ninstance {\u03b1} : Membership \u03b1 (LazyList \u03b1) :=\n  \u27e8LazyList.Mem\u27e9\n\ninstance Mem.decidable {\u03b1} [DecidableEq \u03b1] (x : \u03b1) : \u2200 xs : LazyList \u03b1, Decidable (x \u2208 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 \u2208 ys.get) \u2194 (x \u2208 cons y ys) := by simp [(\u00b7 \u2208 \u00b7), 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 {\u03b1} (x : \u03b1) : x \u2208 @LazyList.nil \u03b1 \u2194 False :=\n  Iff.rfl\n#align lazy_list.mem_nil LazyList.mem_nil\n\n@[simp]\ntheorem mem_cons {\u03b1} (x y : \u03b1) (ys : Thunk (LazyList \u03b1)) :\n    x \u2208 @LazyList.cons \u03b1 y ys \u2194 x = y \u2228 x \u2208 ys.get := by\n  simp [Membership.mem, LazyList.Mem]\n#align lazy_list.mem_cons LazyList.mem_cons\n\ntheorem forall_mem_cons {\u03b1} {p : \u03b1 \u2192 Prop} {a : \u03b1} {l : Thunk (LazyList \u03b1)} :\n    (\u2200 x \u2208 @LazyList.cons _ a l, p x) \u2194 p a \u2227 \u2200 x \u2208 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 : \u2200 a, p a \u2192 \u03b2` is a partial function defined on\n  `a : \u03b1` 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 {\u03b1 \u03b2} {p : \u03b1 \u2192 Prop} (f : \u2200 a, p a \u2192 \u03b2) : \u2200 l : LazyList \u03b1, (\u2200 a \u2208 l, p a) \u2192 LazyList \u03b2\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 \u2208 l}`. -/\ndef attach {\u03b1} (l : LazyList \u03b1) : LazyList { x // x \u2208 l } :=\n  pmap Subtype.mk l fun _ \u21a6 id\n#align lazy_list.attach LazyList.attach\n\ninstance {\u03b1} [Repr \u03b1] : Repr (LazyList \u03b1) :=\n  \u27e8fun xs _ \u21a6 repr xs.toList\u27e9\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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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 \u2192 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 \u2192 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 $ \u03bb 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 \u2192 (\u2115 \u2192 expr) \u2192 tactic expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)\n| _ f := fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 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 \u2190 mk_iff_mp_app iffmp t (\u03bb_, expr.const d.to_name (level.param <$> ls)),\n  t' \u2190 infer_type v,\n  updateex_env $ \u03bb 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 \u2192 tactic (name \u00d7 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) \u2190 pure $ parts.span (\u2260 \"iff\"),\n  let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,\n  (suffix', right') \u2190 pure $ right.reverse.span (\u03bb s, pfx \"left\" s \u2228 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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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 \u2190 ident,\n  d \u2190 (do old \u2190 resolve_constant old, get_decl old) <|>\n    fail (\"declaration \" ++ to_string old ++ \" not found\"),\n  let doc := \u03bb (al : name) (inf : string), meta_info.doc_string.get_or_else $\n    sformat!\"**Alias** of {inf}`{old}`.\",\n  do\n  { tk \"\u2190\" <|> tk \"<-\",\n    aliases \u2190 many ident,\n    \u2191(aliases.mmap' $ \u03bb al, alias_direct d al) } <|>\n  do\n  { tk \"\u2194\" <|> tk \"<->\",\n    (left, right) \u2190\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 \u2192 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 \u2190 has_attribute' `alias n | pure none,\n   v \u2190 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": "import tactic.tidy\n\nimport evaluation\n\nnamespace baseline\n\nsection tidy_proof_search\n\nmeta def tidy_default_tactics : list string := [\n     \"refl\"\n  ,  \"exact dec_trivial\"\n  ,  \"assumption\"\n  ,  \"tactic.intros1\"\n  ,  \"tactic.auto_cases\"\n  ,  \"apply_auto_param\"\n  ,  \"dsimp at *\"\n  ,  \"simp at *\"\n  ,  \"ext1\"\n  ,  \"fsplit\"\n  ,  \"injections_and_clear\"\n  ,  \"solve_by_elim\"\n  ,  \"norm_cast\"\n]\n\n@[inline]\nmeta def tidy_default_tactics_json : json :=\njson.array $ json.of_string <$> tidy_default_tactics\n\n@[inline]\nmeta def tidy_default_tactics_scores : json :=\njson.array $ json.of_float <$> list.repeat (0.0 : native.float) tidy_default_tactics.length\n\nmeta def tidy_api : ModelAPI := -- simulates logic of tidy, baseline (deterministic) model\nlet fn : json \u2192 io json := \u03bb msg, do {\n  pure $ json.array $ [tidy_default_tactics_json, tidy_default_tactics_scores]\n} in \u27e8fn\u27e9\n\n-- TODO(jesse): pass and set max_width\nmeta def tidy_bfs_proof_search_core\n   (fuel : \u2115 := 1000)\n   (verbose := ff)\n   : state_t BFSState tactic unit :=\nbfs_core\n  tidy_api\n    (\u03bb _, pure json.null)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[tidy_bfs_proof_search]\") msg n)\n        fuel\n\nmeta def tidy_bfs_proof_search\n  (fuel : \u2115 := 1000)\n  (verbose := ff)\n  (max_width := 25)\n  (max_depth := 50)\n  : tactic unit :=\n  bfs tidy_api (\u03bb _, pure json.null)\n    (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ (some \"[tidy_bfs_proof_search]\")) msg n)\n      fuel verbose max_width max_depth\n\nend tidy_proof_search\n\nsection playground\n\n-- example : true :=\n-- begin\n--   tidy_bfs_proof_search 5 tt,\n-- end\n\n-- open nat\n-- universe u\n-- example : \u2200 {\u03b1 : Type u} {s\u2081 s\u2082 t\u2081 t\u2082 : list \u03b1},\n--   s\u2081 ++ t\u2081 = s\u2082 ++ t\u2082 \u2192 s\u2081.length = s\u2082.length \u2192 s\u2081 = s\u2082 \u2227 t\u2081 = t\u2082 :=\n-- begin\n--   intros, -- tidy_bfs_proof_search\n-- end\n-- open nat\n\n-- example {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   tidy_bfs_proof_search 3 tt\n-- end\n-- run_cmd do {set_show_eval_trace tt *> do env \u2190 tactic.get_env, tactic.set_env_core env}\n\n-- example {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   tidy_bfs_proof_search 2 ff -- should only try one iteration before halting\n\nend playground\n\nend baseline\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/bfs/baseline.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.10230469899740588, "lm_q1q2_score": 0.045185223899799065}}
{"text": "/-\nCopyright (c) 2022 Jo\u00ebl Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jo\u00ebl 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 \u224c chain_complex C \u2115`\nfor a pseudoabelian category `C` from the equivalence\n`karoubi (simplicial_object C) \u224c karoubi (chain_complex C \u2115)` and the two\nequivalences `simplicial_object C \u2245 karoubi (simplicial_object C)` and\n`chain_complex C \u2115 \u2245 karoubi (chain_complex C \u2115)`.\n\nIt is certainly possible to get an equivalence `simplicial_object C \u224c chain_complex C \u2115`\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`\u0393\u2080 : simplicial_object C \u2964 chain_complex C \u2115` which was constructed in `functor_gamma.lean`.\n\nIn this file, given four categories `A`, `A'`, `B`, `B'`, equivalences `eA : A \u2245 A'`,\n`eB : B \u2245 B'`, `e' : A' \u2245 B'`, functors `F : A \u2964 B'`, `G : B \u2964 A` equipped with certain\ncompatibilities, we construct successive equivalences:\n- `equivalence\u2080` from `A` to `B'`, which is the composition of `eA` and `e'`.\n- `equivalence\u2081` from `A` to `B'`, with the same inverse functor as `equivalence\u2080`,\nbut whose functor is `F`.\n- `equivalence\u2082` from `A` to `B`, which is the composition of `equivalence\u2081` and the\ninverse of `eB`:\n- `equivalence` from `A` to `B`, which has the same functor `F \u22d9 eB.inverse` as `equivalence\u2082`,\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 \u224c A')\n  (eB : B \u224c B') (e' : A' \u224c B') {F : A \u2964 B'} (hF : eA.Functor \u22d9 e'.Functor \u2245 F) {G : B \u2964 A}\n  (hG : eB.Functor \u22d9 e'.inverse \u2245 G \u22d9 eA.Functor)\n\n/-- A basic equivalence `A \u2245 B'` obtained by composing `eA : A \u2245 A'` and `e' : A' \u2245 B'`. -/\n@[simps Functor inverse unit_iso_hom_app]\ndef equivalence\u2080 : A \u224c B' :=\n  eA.trans e'\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2080 AlgebraicTopology.DoldKan.Compatibility.equivalence\u2080\n\ninclude hF\n\nvariable {eA} {e'}\n\n/-- An intermediate equivalence `A \u2245 B'` whose functor is `F` and whose inverse is\n`e'.inverse \u22d9 eA.inverse`. -/\n@[simps Functor]\ndef equivalence\u2081 : A \u224c B' :=\n  letI : is_equivalence F :=\n    is_equivalence.of_iso hF (is_equivalence.of_equivalence (equivalence\u2080 eA e'))\n  F.as_equivalence\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2081 AlgebraicTopology.DoldKan.Compatibility.equivalence\u2081\n\ntheorem equivalence\u2081_inverse : (equivalence\u2081 hF).inverse = e'.inverse \u22d9 eA.inverse :=\n  rfl\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2081_inverse AlgebraicTopology.DoldKan.Compatibility.equivalence\u2081_inverse\n\n/-- The counit isomorphism of the equivalence `equivalence\u2081` between `A` and `B'`. -/\n@[simps]\ndef equivalence\u2081CounitIso : (e'.inverse \u22d9 eA.inverse) \u22d9 F \u2245 \ud835\udfed B' :=\n  calc\n    (e'.inverse \u22d9 eA.inverse) \u22d9 F \u2245 (e'.inverse \u22d9 eA.inverse) \u22d9 eA.Functor \u22d9 e'.Functor :=\n      isoWhiskerLeft _ hF.symm\n    _ \u2245 e'.inverse \u22d9 (eA.inverse \u22d9 eA.Functor) \u22d9 e'.Functor := (Iso.refl _)\n    _ \u2245 e'.inverse \u22d9 \ud835\udfed _ \u22d9 e'.Functor := (isoWhiskerLeft _ (isoWhiskerRight eA.counitIso _))\n    _ \u2245 e'.inverse \u22d9 e'.Functor := (Iso.refl _)\n    _ \u2245 \ud835\udfed B' := e'.counitIso\n    \n#align algebraic_topology.dold_kan.compatibility.equivalence\u2081_counit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence\u2081CounitIso\n\ntheorem equivalence\u2081CounitIso_eq : (equivalence\u2081 hF).counitIso = equivalence\u2081CounitIso hF :=\n  by\n  ext Y\n  dsimp [equivalence\u2080, equivalence\u2081, is_equivalence.inverse, is_equivalence.of_equivalence]\n  simp only [equivalence\u2081_counit_iso_hom_app, CategoryTheory.Functor.map_id, comp_id]\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2081_counit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence\u2081CounitIso_eq\n\n/-- The unit isomorphism of the equivalence `equivalence\u2081` between `A` and `B'`. -/\n@[simps]\ndef equivalence\u2081UnitIso : \ud835\udfed A \u2245 F \u22d9 e'.inverse \u22d9 eA.inverse :=\n  calc\n    \ud835\udfed A \u2245 eA.Functor \u22d9 eA.inverse := eA.unitIso\n    _ \u2245 eA.Functor \u22d9 \ud835\udfed A' \u22d9 eA.inverse := (Iso.refl _)\n    _ \u2245 eA.Functor \u22d9 (e'.Functor \u22d9 e'.inverse) \u22d9 eA.inverse :=\n      (isoWhiskerLeft _ (isoWhiskerRight e'.unitIso _))\n    _ \u2245 (eA.Functor \u22d9 e'.Functor) \u22d9 e'.inverse \u22d9 eA.inverse := (Iso.refl _)\n    _ \u2245 F \u22d9 e'.inverse \u22d9 eA.inverse := isoWhiskerRight hF _\n    \n#align algebraic_topology.dold_kan.compatibility.equivalence\u2081_unit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence\u2081UnitIso\n\ntheorem equivalence\u2081UnitIso_eq : (equivalence\u2081 hF).unitIso = equivalence\u2081UnitIso hF :=\n  by\n  ext X\n  dsimp [equivalence\u2080, equivalence\u2081, nat_iso.hcomp, is_equivalence.of_equivalence]\n  simp only [id_comp, assoc, equivalence\u2081_unit_iso_hom_app]\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2081_unit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence\u2081UnitIso_eq\n\ninclude eB\n\n/-- An intermediate equivalence `A \u2245 B` obtained as the composition of `equivalence\u2081` and\nthe inverse of `eB : B \u224c B'`. -/\n@[simps Functor]\ndef equivalence\u2082 : A \u224c B :=\n  (equivalence\u2081 hF).trans eB.symm\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2082 AlgebraicTopology.DoldKan.Compatibility.equivalence\u2082\n\ntheorem equivalence\u2082_inverse :\n    (equivalence\u2082 eB hF).inverse = eB.Functor \u22d9 e'.inverse \u22d9 eA.inverse :=\n  rfl\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2082_inverse AlgebraicTopology.DoldKan.Compatibility.equivalence\u2082_inverse\n\n/-- The counit isomorphism of the equivalence `equivalence\u2082` between `A` and `B`. -/\n@[simps]\ndef equivalence\u2082CounitIso : (eB.Functor \u22d9 e'.inverse \u22d9 eA.inverse) \u22d9 F \u22d9 eB.inverse \u2245 \ud835\udfed B :=\n  calc\n    (eB.Functor \u22d9 e'.inverse \u22d9 eA.inverse) \u22d9 F \u22d9 eB.inverse \u2245\n        eB.Functor \u22d9 (e'.inverse \u22d9 eA.inverse \u22d9 F) \u22d9 eB.inverse :=\n      Iso.refl _\n    _ \u2245 eB.Functor \u22d9 \ud835\udfed _ \u22d9 eB.inverse :=\n      (isoWhiskerLeft _ (isoWhiskerRight (equivalence\u2081CounitIso hF) _))\n    _ \u2245 eB.Functor \u22d9 eB.inverse := (Iso.refl _)\n    _ \u2245 \ud835\udfed B := eB.unitIso.symm\n    \n#align algebraic_topology.dold_kan.compatibility.equivalence\u2082_counit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence\u2082CounitIso\n\ntheorem equivalence\u2082CounitIso_eq : (equivalence\u2082 eB hF).counitIso = equivalence\u2082CounitIso eB hF :=\n  by\n  ext Y'\n  dsimp [equivalence\u2082, iso.refl]\n  simp only [equivalence\u2081_counit_iso_eq, equivalence\u2082_counit_iso_hom_app,\n    equivalence\u2081_counit_iso_hom_app, functor.map_comp, assoc]\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2082_counit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence\u2082CounitIso_eq\n\n/-- The unit isomorphism of the equivalence `equivalence\u2082` between `A` and `B`. -/\n@[simps]\ndef equivalence\u2082UnitIso : \ud835\udfed A \u2245 (F \u22d9 eB.inverse) \u22d9 eB.Functor \u22d9 e'.inverse \u22d9 eA.inverse :=\n  calc\n    \ud835\udfed A \u2245 F \u22d9 e'.inverse \u22d9 eA.inverse := equivalence\u2081UnitIso hF\n    _ \u2245 F \u22d9 \ud835\udfed B' \u22d9 e'.inverse \u22d9 eA.inverse := (Iso.refl _)\n    _ \u2245 F \u22d9 (eB.inverse \u22d9 eB.Functor) \u22d9 e'.inverse \u22d9 eA.inverse :=\n      (isoWhiskerLeft _ (isoWhiskerRight eB.counitIso.symm _))\n    _ \u2245 (F \u22d9 eB.inverse) \u22d9 eB.Functor \u22d9 e'.inverse \u22d9 eA.inverse := Iso.refl _\n    \n#align algebraic_topology.dold_kan.compatibility.equivalence\u2082_unit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence\u2082UnitIso\n\ntheorem equivalence\u2082UnitIso_eq : (equivalence\u2082 eB hF).unitIso = equivalence\u2082UnitIso eB hF :=\n  by\n  ext X\n  dsimp [equivalence\u2082]\n  simpa only [equivalence\u2082_unit_iso_hom_app, equivalence\u2081_unit_iso_eq,\n    equivalence\u2081_unit_iso_hom_app, assoc, nat_iso.cancel_nat_iso_hom_left]\n#align algebraic_topology.dold_kan.compatibility.equivalence\u2082_unit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence\u2082UnitIso_eq\n\nvariable {eB}\n\ninclude hG\n\n/-- The equivalence `A \u2245 B` whose functor is `F \u22d9 eB.inverse` and\nwhose inverse is `G : B \u2245 A`. -/\n@[simps inverse]\ndef equivalence : A \u224c B :=\n  letI : is_equivalence G :=\n    by\n    refine' is_equivalence.of_iso _ (is_equivalence.of_equivalence (equivalence\u2082 eB hF).symm)\n    calc\n      eB.functor \u22d9 e'.inverse \u22d9 eA.inverse \u2245 (eB.functor \u22d9 e'.inverse) \u22d9 eA.inverse := iso.refl _\n      _ \u2245 (G \u22d9 eA.functor) \u22d9 eA.inverse := (iso_whisker_right hG _)\n      _ \u2245 G \u22d9 \ud835\udfed A := (iso_whisker_left _ eA.unit_iso.symm)\n      _ \u2245 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 \u22d9 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\n! This file was ported from Lean 3 source module data.buffer.parser.basic\n! leanprover-community/mathlib commit bb9d1c5085e0b7ea619806a68c5021927cecb2a6\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.String.Basic\nimport Mathbin.Data.Buffer.Basic\nimport Mathbin.Data.Nat.Digits\nimport Leanbin.Data.Buffer.Parser\n\n/-!\n# Parsers\n\n`parser \u03b1` is the type that describes a computation that can ingest a `char_buffer`\nand output, if successful, a term of type `\u03b1`.\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 \u03b1` 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\n\nopen Parser ParseResult\n\n/-- For some `parse_result \u03b1`, give the position at which the result was provided, in either the\n`done` or the `fail` case.\n-/\n@[simp]\ndef ParseResult.pos {\u03b1} : ParseResult \u03b1 \u2192 \u2115\n  | done n _ => n\n  | fail n _ => n\n#align parse_result.pos ParseResult.pos\n\nnamespace Parser\n\nsection DefnLemmas\n\nvariable {\u03b1 \u03b2 : Type} (msgs : Thunk (List String)) (msg : Thunk String)\n\nvariable (p q : Parser \u03b1) (cb : CharBuffer) (n n' : \u2115) {err : Dlist String}\n\nvariable {a : \u03b1} {b : \u03b2}\n\n/-- A `p : parser \u03b1` is defined to be `mono` if the result `p cb n` it gives,\nfor some `cb : char_buffer` and `n : \u2115`, (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 where\n  le' : \u2200 (cb : CharBuffer) (n : \u2115), n \u2264 (p cb n).Pos\n#align parser.mono Parser.Mono\n\ntheorem Mono.le [p.mono] : n \u2264 (p cb n).Pos :=\n  Mono.le' cb n\n#align parser.mono.le Parser.Mono.le\n\n/-- A `parser \u03b1` is defined to be `static` if it does not move on success.\n-/\nclass Static : Prop where\n  of_done : \u2200 {cb : CharBuffer} {n n' : \u2115} {a : \u03b1}, p cb n = done n' a \u2192 n = n'\n#align parser.static Parser.Static\n\n/-- A `parser \u03b1` is defined to be `err_static` if it does not move on error.\n-/\nclass ErrStatic : Prop where\n  of_fail : \u2200 {cb : CharBuffer} {n n' : \u2115} {err : Dlist String}, p cb n = fail n' err \u2192 n = n'\n#align parser.err_static Parser.ErrStatic\n\n/-- A `parser \u03b1` is defined to be `step` if it always moves exactly one char forward on success.\n-/\nclass Step : Prop where\n  of_done : \u2200 {cb : CharBuffer} {n n' : \u2115} {a : \u03b1}, p cb n = done n' a \u2192 n' = n + 1\n#align parser.step Parser.Step\n\n/-- A `parser \u03b1` is defined to be `prog` if it always moves forward on success.\n-/\nclass Prog : Prop where\n  of_done : \u2200 {cb : CharBuffer} {n n' : \u2115} {a : \u03b1}, p cb n = done n' a \u2192 n < n'\n#align parser.prog Parser.Prog\n\n/-- A `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 where\n  ex' :\n    \u2200 {cb : CharBuffer} {n : \u2115}, cb.size \u2264 n \u2192 \u2203 (n' : \u2115)(err : Dlist String), p cb n = fail n' err\n#align parser.bounded Parser.Bounded\n\ntheorem Bounded.exists (p : Parser \u03b1) [p.Bounded] {cb : CharBuffer} {n : \u2115} (h : cb.size \u2264 n) :\n    \u2203 (n' : \u2115)(err : Dlist String), p cb n = fail n' err :=\n  Bounded.ex' h\n#align parser.bounded.exists Parser.Bounded.exists\n\n/-- A `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`.\n-/\nclass Unfailing : Prop where\n  ex' : \u2200 (cb : CharBuffer) (n : \u2115), \u2203 (n' : \u2115)(a : \u03b1), p cb n = done n' a\n#align parser.unfailing Parser.Unfailing\n\n/-- A `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 ConditionallyUnfailing : Prop where\n  ex' : \u2200 {cb : CharBuffer} {n : \u2115}, n < cb.size \u2192 \u2203 (n' : \u2115)(a : \u03b1), p cb n = done n' a\n#align parser.conditionally_unfailing Parser.ConditionallyUnfailing\n\ntheorem fail_iff :\n    (\u2200 pos' result, p cb n \u2260 done pos' result) \u2194\n      \u2203 (pos' : \u2115)(err : Dlist String), p cb n = fail pos' err :=\n  by cases p cb n <;> simp\n#align parser.fail_iff Parser.fail_iff\n\ntheorem success_iff :\n    (\u2200 pos' err, p cb n \u2260 fail pos' err) \u2194 \u2203 (pos' : \u2115)(result : \u03b1), p cb n = done pos' result := by\n  cases p cb n <;> simp\n#align parser.success_iff Parser.success_iff\n\nvariable {p q cb n n' msgs msg}\n\ntheorem Mono.of_done [p.mono] (h : p cb n = done n' a) : n \u2264 n' := by simpa [h] using mono.le p cb n\n#align parser.mono.of_done Parser.Mono.of_done\n\ntheorem Mono.of_fail [p.mono] (h : p cb n = fail n' err) : n \u2264 n' := by\n  simpa [h] using mono.le p cb n\n#align parser.mono.of_fail Parser.Mono.of_fail\n\ntheorem Bounded.of_done [p.Bounded] (h : p cb n = done n' a) : n < cb.size :=\n  by\n  contrapose! h\n  obtain \u27e8np, err, hp\u27e9 := bounded.exists p h\n  simp [hp]\n#align parser.bounded.of_done Parser.Bounded.of_done\n\ntheorem Static.iff :\n    Static p \u2194 \u2200 (cb : CharBuffer) (n n' : \u2115) (a : \u03b1), p cb n = done n' a \u2192 n = n' :=\n  \u27e8fun h _ _ _ _ hp =>\n    haveI := h\n    static.of_done hp,\n    fun h => \u27e8h\u27e9\u27e9\n#align parser.static.iff Parser.Static.iff\n\ntheorem exists_done (p : Parser \u03b1) [p.Unfailing] (cb : CharBuffer) (n : \u2115) :\n    \u2203 (n' : \u2115)(a : \u03b1), p cb n = done n' a :=\n  Unfailing.ex' cb n\n#align parser.exists_done Parser.exists_done\n\ntheorem Unfailing.of_fail [p.Unfailing] (h : p cb n = fail n' err) : False :=\n  by\n  obtain \u27e8np, a, hp\u27e9 := p.exists_done cb n\n  simpa [hp] using h\n#align parser.unfailing.of_fail Parser.Unfailing.of_fail\n\n-- see Note [lower instance priority]\ninstance (priority := 100) conditionallyUnfailing_of_unfailing [p.Unfailing] :\n    ConditionallyUnfailing p :=\n  \u27e8fun _ _ _ => p.exists_done _ _\u27e9\n#align parser.conditionally_unfailing_of_unfailing Parser.conditionallyUnfailing_of_unfailing\n\ntheorem exists_done_in_bounds (p : Parser \u03b1) [p.ConditionallyUnfailing] {cb : CharBuffer} {n : \u2115}\n    (h : n < cb.size) : \u2203 (n' : \u2115)(a : \u03b1), p cb n = done n' a :=\n  ConditionallyUnfailing.ex' h\n#align parser.exists_done_in_bounds Parser.exists_done_in_bounds\n\ntheorem ConditionallyUnfailing.of_fail [p.ConditionallyUnfailing] (h : p cb n = fail n' err)\n    (hn : n < cb.size) : False :=\n  by\n  obtain \u27e8np, a, hp\u27e9 := p.exists_done_in_bounds hn\n  simpa [hp] using h\n#align parser.conditionally_unfailing.of_fail Parser.ConditionallyUnfailing.of_fail\n\ntheorem decorateErrors_fail (h : p cb n = fail n' err) :\n    @decorateErrors \u03b1 msgs p cb n = fail n (Std.DList.lazy_ofList (msgs ())) := by\n  simp [decorate_errors, h]\n#align parser.decorate_errors_fail Parser.decorateErrors_fail\n\ntheorem decorateErrors_success (h : p cb n = done n' a) :\n    @decorateErrors \u03b1 msgs p cb n = done n' a := by simp [decorate_errors, h]\n#align parser.decorate_errors_success Parser.decorateErrors_success\n\ntheorem decorateError_fail (h : p cb n = fail n' err) :\n    @decorateError \u03b1 msg p cb n = fail n (Std.DList.lazy_ofList [msg ()]) :=\n  decorateErrors_fail h\n#align parser.decorate_error_fail Parser.decorateError_fail\n\ntheorem decorateError_success (h : p cb n = done n' a) : @decorateError \u03b1 msg p cb n = done n' a :=\n  decorateErrors_success h\n#align parser.decorate_error_success Parser.decorateError_success\n\n@[simp]\ntheorem decorateErrors_eq_done : @decorateErrors \u03b1 msgs p cb n = done n' a \u2194 p cb n = done n' a :=\n  by cases h : p cb n <;> simp [decorate_errors, h]\n#align parser.decorate_errors_eq_done Parser.decorateErrors_eq_done\n\n@[simp]\ntheorem decorateError_eq_done : @decorateError \u03b1 msg p cb n = done n' a \u2194 p cb n = done n' a :=\n  decorateErrors_eq_done\n#align parser.decorate_error_eq_done Parser.decorateError_eq_done\n\n@[simp]\ntheorem decorateErrors_eq_fail :\n    @decorateErrors \u03b1 msgs p cb n = fail n' err \u2194\n      n = n' \u2227 err = Std.DList.lazy_ofList (msgs ()) \u2227 \u2203 np err', p cb n = fail np err' :=\n  by cases h : p cb n <;> simp [decorate_errors, h, eq_comm]\n#align parser.decorate_errors_eq_fail Parser.decorateErrors_eq_fail\n\n@[simp]\ntheorem decorateError_eq_fail :\n    @decorateError \u03b1 msg p cb n = fail n' err \u2194\n      n = n' \u2227 err = Std.DList.lazy_ofList [msg ()] \u2227 \u2203 np err', p cb n = fail np err' :=\n  decorateErrors_eq_fail\n#align parser.decorate_error_eq_fail Parser.decorateError_eq_fail\n\n@[simp]\ntheorem return_eq_pure : @return Parser _ _ a = pure a :=\n  rfl\n#align parser.return_eq_pure Parser.return_eq_pure\n\ntheorem pure_eq_done : @pure Parser _ _ a = fun _ n => done n a :=\n  rfl\n#align parser.pure_eq_done Parser.pure_eq_done\n\n@[simp]\ntheorem pure_ne_fail : (pure a : Parser \u03b1) cb n \u2260 fail n' err := by simp [pure_eq_done]\n#align parser.pure_ne_fail Parser.pure_ne_fail\n\nsection Bind\n\nvariable (f : \u03b1 \u2192 Parser \u03b2)\n\n@[simp]\ntheorem bind_eq_bind : p.bind f = p >>= f :=\n  rfl\n#align parser.bind_eq_bind Parser.bind_eq_bind\n\nvariable {f}\n\n@[simp]\ntheorem bind_eq_done :\n    (p >>= f) cb n = done n' b \u2194 \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 f a cb np = done n' b := by\n  cases hp : p cb n <;> simp [hp, \u2190 bind_eq_bind, Parser.bind, and_assoc']\n#align parser.bind_eq_done Parser.bind_eq_done\n\n@[simp]\ntheorem bind_eq_fail :\n    (p >>= f) cb n = fail n' err \u2194\n      p cb n = fail n' err \u2228 \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 f a cb np = fail n' err :=\n  by cases hp : p cb n <;> simp [hp, \u2190 bind_eq_bind, Parser.bind, and_assoc']\n#align parser.bind_eq_fail Parser.bind_eq_fail\n\n@[simp]\ntheorem andThen_eq_bind {\u03b1 \u03b2 : Type} {m : Type \u2192 Type} [Monad m] (a : m \u03b1) (b : m \u03b2) :\n    a >> b = a >>= fun _ => b :=\n  rfl\n#align parser.and_then_eq_bind Parser.andThen_eq_bind\n\ntheorem andThen_fail : (p >> return ()) cb n = ParseResult.fail n' err \u2194 p cb n = fail n' err := by\n  simp [pure_eq_done]\n#align parser.and_then_fail Parser.andThen_fail\n\ntheorem andThen_success :\n    (p >> return ()) cb n = ParseResult.done n' () \u2194 \u2203 a, p cb n = done n' a := by\n  simp [pure_eq_done]\n#align parser.and_then_success Parser.andThen_success\n\nend Bind\n\nsection Map\n\nvariable {f : \u03b1 \u2192 \u03b2}\n\n@[simp]\ntheorem map_eq_done : (f <$> p) cb n = done n' b \u2194 \u2203 a : \u03b1, p cb n = done n' a \u2227 f a = b := by\n  cases hp : p cb n <;> simp [\u2190 LawfulMonad.bind_pure_comp_eq_map, hp, and_assoc', pure_eq_done]\n#align parser.map_eq_done Parser.map_eq_done\n\n@[simp]\ntheorem map_eq_fail : (f <$> p) cb n = fail n' err \u2194 p cb n = fail n' err := by\n  simp [\u2190 bind_pure_comp_eq_map, pure_eq_done]\n#align parser.map_eq_fail Parser.map_eq_fail\n\n@[simp]\ntheorem mapConst_eq_done {b'} : (b <$ p) cb n = done n' b' \u2194 \u2203 a : \u03b1, p cb n = done n' a \u2227 b = b' :=\n  by simp [map_const_eq]\n#align parser.map_const_eq_done Parser.mapConst_eq_done\n\n@[simp]\ntheorem mapConst_eq_fail : (b <$ p) cb n = fail n' err \u2194 p cb n = fail n' err := by\n  simp only [map_const_eq, map_eq_fail]\n#align parser.map_const_eq_fail Parser.mapConst_eq_fail\n\ntheorem mapConstRev_eq_done {b'} :\n    (p $> b) cb n = done n' b' \u2194 \u2203 a : \u03b1, p cb n = done n' a \u2227 b = b' :=\n  mapConst_eq_done\n#align parser.map_const_rev_eq_done Parser.mapConstRev_eq_done\n\ntheorem map_rev_const_eq_fail : (p $> b) cb n = fail n' err \u2194 p cb n = fail n' err :=\n  mapConst_eq_fail\n#align parser.map_rev_const_eq_fail Parser.map_rev_const_eq_fail\n\nend Map\n\n@[simp]\ntheorem orelse_eq_orelse : p.orelse q = (p <|> q) :=\n  rfl\n#align parser.orelse_eq_orelse Parser.orelse_eq_orelse\n\n@[simp]\ntheorem orelse_eq_done :\n    (p <|> q) cb n = done n' a \u2194\n      p cb n = done n' a \u2228 q cb n = done n' a \u2227 \u2203 err, p cb n = fail n err :=\n  by\n  cases' hp : p cb n with np resp np errp\n  \u00b7 simp [hp, \u2190 orelse_eq_orelse, Parser.orelse]\n  \u00b7 by_cases hn : np = n\n    \u00b7 cases' hq : q cb n with nq resq nq errq\n      \u00b7 simp [hp, hn, hq, \u2190 orelse_eq_orelse, Parser.orelse]\n      \u00b7\n        rcases lt_trichotomy nq n with (H | rfl | H) <;>\n          first\n            |simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, \u2190 orelse_eq_orelse,\n              Parser.orelse]|simp [hp, hn, hq, lt_irrefl, \u2190 orelse_eq_orelse, Parser.orelse]\n    \u00b7 simp [hp, hn, \u2190 orelse_eq_orelse, Parser.orelse]\n#align parser.orelse_eq_done Parser.orelse_eq_done\n\n@[simp]\ntheorem orelse_eq_fail_eq :\n    (p <|> q) cb n = fail n err \u2194\n      (p cb n = fail n err \u2227 \u2203 nq errq, n < nq \u2227 q cb n = fail nq errq) \u2228\n        \u2203 errp errq, p cb n = fail n errp \u2227 q cb n = fail n errq \u2227 errp ++ errq = err :=\n  by\n  cases' hp : p cb n with np resp np errp\n  \u00b7 simp [hp, \u2190 orelse_eq_orelse, Parser.orelse]\n  \u00b7 by_cases hn : np = n\n    \u00b7 cases' hq : q cb n with nq resq nq errq\n      \u00b7 simp [hp, hn, hq, \u2190 orelse_eq_orelse, Parser.orelse]\n      \u00b7\n        rcases lt_trichotomy nq n with (H | rfl | H) <;>\n          first\n            |simp [hp, hq, hn, \u2190 orelse_eq_orelse, Parser.orelse, H, ne_of_gt H, ne_of_lt H,\n              not_lt_of_lt H]|simp [hp, hq, hn, \u2190 orelse_eq_orelse, Parser.orelse, lt_irrefl]\n    \u00b7 simp [hp, hn, \u2190 orelse_eq_orelse, Parser.orelse]\n#align parser.orelse_eq_fail_eq Parser.orelse_eq_fail_eq\n\ntheorem orelse_eq_fail_not_mono_lt (hn : n' < n) :\n    (p <|> q) cb n = fail n' err \u2194\n      p cb n = fail n' err \u2228 q cb n = fail n' err \u2227 \u2203 errp, p cb n = fail n errp :=\n  by\n  cases' hp : p cb n with np resp np errp\n  \u00b7 simp [hp, \u2190 orelse_eq_orelse, Parser.orelse]\n  \u00b7 by_cases h : np = n\n    \u00b7 cases' hq : q cb n with nq resq nq errq\n      \u00b7 simp [hp, h, hn, hq, ne_of_gt hn, \u2190 orelse_eq_orelse, Parser.orelse]\n      \u00b7 rcases lt_trichotomy nq n with (H | H | H)\n        \u00b7 simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, \u2190 orelse_eq_orelse, Parser.orelse]\n        \u00b7 simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, \u2190 orelse_eq_orelse, Parser.orelse]\n        \u00b7 simp [hp, hq, h, H, ne_of_gt (hn.trans H), \u2190 orelse_eq_orelse, Parser.orelse]\n    \u00b7 simp [hp, h, \u2190 orelse_eq_orelse, Parser.orelse]\n#align parser.orelse_eq_fail_not_mono_lt Parser.orelse_eq_fail_not_mono_lt\n\ntheorem orelse_eq_fail_of_mono_ne [q.mono] (hn : n \u2260 n') :\n    (p <|> q) cb n = fail n' err \u2194 p cb n = fail n' err :=\n  by\n  cases' hp : p cb n with np resp np errp\n  \u00b7 simp [hp, \u2190 orelse_eq_orelse, Parser.orelse]\n  \u00b7 by_cases h : np = n\n    \u00b7 cases' hq : q cb n with nq resq nq errq\n      \u00b7 simp [hp, h, hn, hq, hn, \u2190 orelse_eq_orelse, Parser.orelse]\n      \u00b7 have : n \u2264 nq := mono.of_fail hq\n        rcases eq_or_lt_of_le this with (rfl | H)\n        \u00b7 simp [hp, hq, h, hn, lt_irrefl, \u2190 orelse_eq_orelse, Parser.orelse]\n        \u00b7 simp [hp, hq, h, hn, H, \u2190 orelse_eq_orelse, Parser.orelse]\n    \u00b7 simp [hp, h, \u2190 orelse_eq_orelse, Parser.orelse]\n#align parser.orelse_eq_fail_of_mono_ne Parser.orelse_eq_fail_of_mono_ne\n\n@[simp]\ntheorem failure_eq_failure : @Parser.failure \u03b1 = failure :=\n  rfl\n#align parser.failure_eq_failure Parser.failure_eq_failure\n\n@[simp]\ntheorem failure_def : (failure : Parser \u03b1) cb n = fail n Dlist.empty :=\n  rfl\n#align parser.failure_def Parser.failure_def\n\ntheorem not_failure_eq_done : \u00ac(failure : Parser \u03b1) cb n = done n' a := by simp\n#align parser.not_failure_eq_done Parser.not_failure_eq_done\n\ntheorem failure_eq_fail : (failure : Parser \u03b1) cb n = fail n' err \u2194 n = n' \u2227 err = Dlist.empty := by\n  simp [eq_comm]\n#align parser.failure_eq_fail Parser.failure_eq_fail\n\ntheorem seq_eq_done {f : Parser (\u03b1 \u2192 \u03b2)} {p : Parser \u03b1} :\n    (f <*> p) cb n = done n' b \u2194\n      \u2203 (nf : \u2115)(f' : \u03b1 \u2192 \u03b2)(a : \u03b1), f cb n = done nf f' \u2227 p cb nf = done n' a \u2227 f' a = b :=\n  by simp [seq_eq_bind_map]\n#align parser.seq_eq_done Parser.seq_eq_done\n\ntheorem seq_eq_fail {f : Parser (\u03b1 \u2192 \u03b2)} {p : Parser \u03b1} :\n    (f <*> p) cb n = fail n' err \u2194\n      f cb n = fail n' err \u2228 \u2203 (nf : \u2115)(f' : \u03b1 \u2192 \u03b2), f cb n = done nf f' \u2227 p cb nf = fail n' err :=\n  by simp [seq_eq_bind_map]\n#align parser.seq_eq_fail Parser.seq_eq_fail\n\ntheorem seqLeft_eq_done {p : Parser \u03b1} {q : Parser \u03b2} :\n    (p <* q) cb n = done n' a \u2194 \u2203 (np : \u2115)(b : \u03b2), p cb n = done np a \u2227 q cb np = done n' b :=\n  by\n  have :\n    \u2200 p q : \u2115 \u2192 \u03b1 \u2192 Prop,\n      (\u2203 (np : \u2115)(x : \u03b1), p np x \u2227 q np x \u2227 x = a) \u2194 \u2203 np : \u2115, p np a \u2227 q np a :=\n    fun _ _ => \u27e8fun \u27e8np, x, hp, hq, rfl\u27e9 => \u27e8np, hp, hq\u27e9, fun \u27e8np, hp, hq\u27e9 => \u27e8np, a, hp, hq, rfl\u27e9\u27e9\n  simp [seq_left_eq, seq_eq_done, map_eq_done, this]\n#align parser.seq_left_eq_done Parser.seqLeft_eq_done\n\ntheorem seqLeft_eq_fail {p : Parser \u03b1} {q : Parser \u03b2} :\n    (p <* q) cb n = fail n' err \u2194\n      p cb n = fail n' err \u2228 \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 q cb np = fail n' err :=\n  by simp [seq_left_eq, seq_eq_fail]\n#align parser.seq_left_eq_fail Parser.seqLeft_eq_fail\n\ntheorem seqRight_eq_done {p : Parser \u03b1} {q : Parser \u03b2} :\n    (p *> q) cb n = done n' b \u2194 \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 q cb np = done n' b := by\n  simp [seq_right_eq, seq_eq_done, map_eq_done, and_comm, and_assoc]\n#align parser.seq_right_eq_done Parser.seqRight_eq_done\n\ntheorem seqRight_eq_fail {p : Parser \u03b1} {q : Parser \u03b2} :\n    (p *> q) cb n = fail n' err \u2194\n      p cb n = fail n' err \u2228 \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 q cb np = fail n' err :=\n  by simp [seq_right_eq, seq_eq_fail]\n#align parser.seq_right_eq_fail Parser.seqRight_eq_fail\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem mapM_eq_done {f : \u03b1 \u2192 Parser \u03b2} {a : \u03b1} {l : List \u03b1} {b : \u03b2} {l' : List \u03b2} :\n    (a::l).mapM f cb n = done n' (b::l') \u2194\n      \u2203 np : \u2115, f a cb n = done np b \u2227 l.mapM f cb np = done n' l' :=\n  by simp [mmap, and_comm, and_assoc, and_left_comm, pure_eq_done]\n#align parser.mmap_eq_done Parser.mapM_eq_done\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem mapM'_eq_done {f : \u03b1 \u2192 Parser \u03b2} {a : \u03b1} {l : List \u03b1} :\n    (a::l).mapM' f cb n = done n' () \u2194\n      \u2203 (np : \u2115)(b : \u03b2), f a cb n = done np b \u2227 l.mapM' f cb np = done n' () :=\n  by simp [mmap']\n#align parser.mmap'_eq_done Parser.mapM'_eq_done\n\ntheorem guard_eq_done {p : Prop} [Decidable p] {u : Unit} :\n    @guard Parser _ p _ cb n = done n' u \u2194 p \u2227 n = n' := by\n  by_cases hp : p <;> simp [guard, hp, pure_eq_done]\n#align parser.guard_eq_done Parser.guard_eq_done\n\ntheorem guard_eq_fail {p : Prop} [Decidable p] :\n    @guard Parser _ p _ cb n = fail n' err \u2194 \u00acp \u2227 n = n' \u2227 err = Dlist.empty := by\n  by_cases hp : p <;> simp [guard, hp, eq_comm, pure_eq_done]\n#align parser.guard_eq_fail Parser.guard_eq_fail\n\nnamespace Mono\n\nvariable {sep : Parser Unit}\n\ninstance pure : Mono (pure a) :=\n  \u27e8fun _ _ => by simp [pure_eq_done]\u27e9\n#align parser.mono.pure Parser.Mono.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.mono] [\u2200 a, (f a).mono] : (p >>= f).mono :=\n  by\n  constructor\n  intro cb n\n  cases hx : (p >>= f) cb n\n  \u00b7 obtain \u27e8n', a, h, h'\u27e9 := bind_eq_done.mp hx\n    refine' le_trans (of_done h) _\n    simpa [h'] using of_done h'\n  \u00b7 obtain h | \u27e8n', a, h, h'\u27e9 := bind_eq_fail.mp hx\n    \u00b7 simpa [h] using of_fail h\n    \u00b7 refine' le_trans (of_done h) _\n      simpa [h'] using of_fail h'\n#align parser.mono.bind Parser.Mono.bind\n\ninstance andThen {q : Parser \u03b2} [p.mono] [q.mono] : (p >> q).mono :=\n  Mono.bind\n#align parser.mono.and_then Parser.Mono.andThen\n\ninstance map [p.mono] {f : \u03b1 \u2192 \u03b2} : (f <$> p).mono :=\n  Mono.bind\n#align parser.mono.map Parser.Mono.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.mono] [p.mono] : (f <*> p).mono :=\n  Mono.bind\n#align parser.mono.seq Parser.Mono.seq\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM : \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a \u2208 l, (f a).mono], (l.mapM f).mono\n  | [], _, _ => Mono.pure\n  | a::l, f, h => by\n    convert mono.bind\n    \u00b7 exact h _ (List.mem_cons_self _ _)\n    \u00b7 intro\n      convert mono.map\n      convert mmap\n      exact fun _ ha => h _ (List.mem_cons_of_mem _ ha)\n#align parser.mono.mmap Parser.Mono.mapM\n\n/- warning: parser.mono.mmap' -> Parser.Mono.mapM' is a dubious translation:\nlean 3 declaration is\n  forall {\u03b1 : Type} {\u03b2 : Type} {l : List.{0} \u03b1} {f : \u03b1 -> (Parser \u03b2)} [_inst_1 : forall (a : \u03b1), (Membership.Mem.{0, 0} \u03b1 (List.{0} \u03b1) (List.hasMem.{0} \u03b1) a l) -> (Parser.Mono \u03b2 (f a))], Parser.Mono Unit (List.mapM'.{0, 0} Parser Parser.monad \u03b1 \u03b2 f l)\nbut is expected to have type\n  PUnit.{0}\nCase conversion may be inaccurate. Consider using '#align parser.mono.mmap' Parser.Mono.mapM'\u2093'. -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM' : \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a \u2208 l, (f a).mono], (l.mapM' f).mono\n  | [], _, _ => Mono.pure\n  | a::l, f, h => by\n    convert mono.and_then\n    \u00b7 exact h _ (List.mem_cons_self _ _)\n    \u00b7 convert mmap'\n      exact fun _ ha => h _ (List.mem_cons_of_mem _ ha)\n#align parser.mono.mmap' Parser.Mono.mapM'\n\ninstance failure : (failure : Parser \u03b1).mono :=\n  \u27e8by simp [le_refl]\u27e9\n#align parser.mono.failure Parser.Mono.failure\n\ninstance guard {p : Prop} [Decidable p] : Mono (guard p) :=\n  \u27e8by by_cases h : p <;> simp [h, pure_eq_done, le_refl]\u27e9\n#align parser.mono.guard Parser.Mono.guard\n\ninstance orelse [p.mono] [q.mono] : (p <|> q).mono :=\n  by\n  constructor\n  intro cb n\n  cases' hx : (p <|> q) cb n with posx resx posx errx\n  \u00b7 obtain h | \u27e8h, -, -\u27e9 := orelse_eq_done.mp hx <;> simpa [h] using of_done h\n  \u00b7 by_cases h : n = posx\n    \u00b7 simp [hx, h]\n    \u00b7 simp only [orelse_eq_fail_of_mono_ne h] at hx\n      exact of_fail hx\n#align parser.mono.orelse Parser.Mono.orelse\n\ninstance decorateErrors [p.mono] : (@decorateErrors \u03b1 msgs p).mono :=\n  by\n  constructor\n  intro cb n\n  cases h : p cb n\n  \u00b7 simpa [decorate_errors, h] using of_done h\n  \u00b7 simp [decorate_errors, h]\n#align parser.mono.decorate_errors Parser.Mono.decorateErrors\n\ninstance decorateError [p.mono] : (@decorateError \u03b1 msg p).mono :=\n  Mono.decorateErrors\n#align parser.mono.decorate_error Parser.Mono.decorateError\n\ninstance anyChar : Mono anyChar := by\n  constructor\n  intro cb n\n  by_cases h : n < cb.size <;> simp [any_char, h]\n#align parser.mono.any_char Parser.Mono.anyChar\n\ninstance sat {p : Char \u2192 Prop} [DecidablePred p] : Mono (sat p) :=\n  by\n  constructor\n  intro cb n\n  simp only [sat]\n  split_ifs <;> simp\n#align parser.mono.sat Parser.Mono.sat\n\ninstance eps : Mono eps :=\n  Mono.pure\n#align parser.mono.eps Parser.Mono.eps\n\ninstance ch {c : Char} : Mono (ch c) :=\n  Mono.decorateError\n#align parser.mono.ch Parser.Mono.ch\n\ninstance charBuf {s : CharBuffer} : Mono (charBuf s) :=\n  Mono.decorateError\n#align parser.mono.char_buf Parser.Mono.charBuf\n\ninstance oneOf {cs : List Char} : (oneOf cs).mono :=\n  Mono.decorateErrors\n#align parser.mono.one_of Parser.Mono.oneOf\n\ninstance oneOf' {cs : List Char} : (oneOf' cs).mono :=\n  Mono.andThen\n#align parser.mono.one_of' Parser.Mono.oneOf'\n\ninstance str {s : String} : (str s).mono :=\n  Mono.decorateError\n#align parser.mono.str Parser.Mono.str\n\ninstance remaining : remaining.mono :=\n  \u27e8fun _ _ => le_rfl\u27e9\n#align parser.mono.remaining Parser.Mono.remaining\n\ninstance eof : eof.mono :=\n  Mono.decorateError\n#align parser.mono.eof Parser.Mono.eof\n\ninstance foldrCore {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} [p.mono] : \u2200 {reps : \u2115}, (foldrCore f p b reps).mono\n  | 0 => Mono.failure\n  | reps + 1 => by\n    convert mono.orelse\n    \u00b7 convert mono.bind\n      \u00b7 infer_instance\n      \u00b7 exact fun _ => @mono.bind _ _ _ _ foldr_core _\n    \u00b7 exact mono.pure\n#align parser.mono.foldr_core Parser.Mono.foldrCore\n\ninstance foldr {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} [p.mono] : Mono (foldr f p b) :=\n  \u27e8fun _ _ => by\n    convert mono.le (foldr_core f p b _) _ _\n    exact mono.foldr_core\u27e9\n#align parser.mono.foldr Parser.Mono.foldr\n\ninstance foldlCore {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : Parser \u03b2} [p.mono] :\n    \u2200 {a : \u03b1} {reps : \u2115}, (foldlCore f a p reps).mono\n  | _, 0 => Mono.failure\n  | _, reps + 1 => by\n    convert mono.orelse\n    \u00b7 convert mono.bind\n      \u00b7 infer_instance\n      \u00b7 exact fun _ => foldl_core\n    \u00b7 exact mono.pure\n#align parser.mono.foldl_core Parser.Mono.foldlCore\n\ninstance foldl {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : Parser \u03b2} [p.mono] : Mono (foldl f a p) :=\n  \u27e8fun _ _ => by\n    convert mono.le (foldl_core f a p _) _ _\n    exact mono.foldl_core\u27e9\n#align parser.mono.foldl Parser.Mono.foldl\n\ninstance many [p.mono] : p.anyM.mono :=\n  Mono.foldr\n#align parser.mono.many Parser.Mono.many\n\ninstance manyChar {p : Parser Char} [p.mono] : p.manyChar.mono :=\n  Mono.map\n#align parser.mono.many_char Parser.Mono.manyChar\n\ninstance many' [p.mono] : p.many'.mono :=\n  Mono.andThen\n#align parser.mono.many' Parser.Mono.many'\n\ninstance many1 [p.mono] : p.many1.mono :=\n  Mono.seq\n#align parser.mono.many1 Parser.Mono.many1\n\ninstance manyChar1 {p : Parser Char} [p.mono] : p.manyChar1.mono :=\n  Mono.map\n#align parser.mono.many_char1 Parser.Mono.manyChar1\n\ninstance sepBy1 [p.mono] [sep.mono] : Mono (sepBy1 sep p) :=\n  Mono.seq\n#align parser.mono.sep_by1 Parser.Mono.sepBy1\n\ninstance sepBy [p.mono] [hs : sep.mono] : Mono (sepBy sep p) :=\n  Mono.orelse\n#align parser.mono.sep_by Parser.Mono.sepBy\n\ntheorem fixCore {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.mono \u2192 (F p).mono) :\n    \u2200 max_depth : \u2115, Mono (fixCore F max_depth)\n  | 0 => Mono.failure\n  | max_depth + 1 => hF _ (fix_core _)\n#align parser.mono.fix_core Parser.Mono.fixCore\n\ninstance digit : digit.mono :=\n  Mono.decorateError\n#align parser.mono.digit Parser.Mono.digit\n\ninstance nat : nat.mono :=\n  Mono.decorateError\n#align parser.mono.nat Parser.Mono.nat\n\ntheorem fix {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.mono \u2192 (F p).mono) : Mono (fix F) :=\n  \u27e8fun _ _ => by\n    convert mono.le (Parser.fixCore F _) _ _\n    exact fix_core hF _\u27e9\n#align parser.mono.fix Parser.Mono.fix\n\nend Mono\n\n@[simp]\ntheorem orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err \u2194 p cb n = fail n' err \u2227 n \u2260 n' :=\n  by\n  by_cases hn : n = n'\n  \u00b7 simp [hn, pure_eq_done]\n  \u00b7 simp [orelse_eq_fail_of_mono_ne, hn]\n#align parser.orelse_pure_eq_fail Parser.orelse_pure_eq_fail\n\nend DefnLemmas\n\nsection Done\n\nvariable {\u03b1 \u03b2 : Type} {cb : CharBuffer} {n n' : \u2115} {a a' : \u03b1} {b : \u03b2} {c : Char} {u : Unit}\n  {err : Dlist String}\n\ntheorem anyChar_eq_done :\n    anyChar cb n = done n' c \u2194 \u2203 hn : n < cb.size, n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = c :=\n  by\n  simp_rw [any_char]\n  split_ifs with h <;> simp [h, eq_comm]\n#align parser.any_char_eq_done Parser.anyChar_eq_done\n\ntheorem anyChar_eq_fail : anyChar cb n = fail n' err \u2194 n = n' \u2227 err = Dlist.empty \u2227 cb.size \u2264 n :=\n  by\n  simp_rw [any_char]\n  split_ifs with h <;> simp [\u2190 not_lt, h, eq_comm]\n#align parser.any_char_eq_fail Parser.anyChar_eq_fail\n\ntheorem sat_eq_done {p : Char \u2192 Prop} [DecidablePred p] :\n    sat p cb n = done n' c \u2194 \u2203 hn : n < cb.size, p c \u2227 n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = c :=\n  by\n  by_cases hn : n < cb.size\n  \u00b7 by_cases hp : p (cb.read \u27e8n, hn\u27e9)\n    \u00b7 simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true]\n      constructor\n      \u00b7 rintro \u27e8rfl, rfl\u27e9\n        simp [hp]\n      \u00b7 rintro \u27e8-, rfl, rfl\u27e9\n        simp\n    \u00b7 simp only [sat, hn, hp, dif_pos, false_iff_iff, not_and, exists_prop_of_true, if_false]\n      rintro H - rfl\n      exact hp H\n  \u00b7 simp [sat, hn]\n#align parser.sat_eq_done Parser.sat_eq_done\n\ntheorem sat_eq_fail {p : Char \u2192 Prop} [DecidablePred p] :\n    sat p cb n = fail n' err \u2194\n      n = n' \u2227 err = Dlist.empty \u2227 \u2200 h : n < cb.size, \u00acp (cb.read \u27e8n, h\u27e9) :=\n  by\n  dsimp only [sat]\n  split_ifs <;> simp [*, eq_comm]\n#align parser.sat_eq_fail Parser.sat_eq_fail\n\ntheorem eps_eq_done : eps cb n = done n' u \u2194 n = n' := by simp [eps, pure_eq_done]\n#align parser.eps_eq_done Parser.eps_eq_done\n\ntheorem ch_eq_done : ch c cb n = done n' u \u2194 \u2203 hn : n < cb.size, n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = c :=\n  by simp [ch, eps_eq_done, sat_eq_done, and_comm, @eq_comm _ n']\n#align parser.ch_eq_done Parser.ch_eq_done\n\ntheorem charBuf_eq_done {cb' : CharBuffer} :\n    charBuf cb' cb n = done n' u \u2194 n + cb'.size = n' \u2227 cb'.toList <+: cb.toList.drop n :=\n  by\n  simp only [char_buf, decorate_error_eq_done, Ne.def, \u2190 Buffer.length_toList]\n  induction' cb'.to_list with hd tl hl generalizing cb n n'\n  \u00b7 simp [pure_eq_done, mmap'_eq_done, -Buffer.length_toList, List.nil_prefix]\n  \u00b7 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_left, exists_const]\n    constructor\n    \u00b7 rintro \u27e8np, h, rfl, rfl, hn, rfl\u27e9\n      simp only [add_comm, add_left_comm, h, true_and_iff, eq_self_iff_true, and_true_iff]\n      have : n < cb.to_list.length := by simpa using hn\n      rwa [\u2190 Buffer.nthLe_toList _ this, \u2190 List.cons_nthLe_drop_succ this, List.prefix_cons_inj]\n    \u00b7 rintro \u27e8h, rfl\u27e9\n      by_cases hn : n < cb.size\n      \u00b7 have : n < cb.to_list.length := by simpa using hn\n        rw [\u2190 List.cons_nthLe_drop_succ this, List.cons_prefix_iff] at h\n        use n + 1, h.right\n        simpa [Buffer.nthLe_toList, add_comm, add_left_comm, add_assoc, hn] using h.left.symm\n      \u00b7 have : cb.to_list.length \u2264 n := by simpa using hn\n        rw [List.drop_eq_nil_of_le this] at h\n        simpa using h\n#align parser.char_buf_eq_done Parser.charBuf_eq_done\n\ntheorem oneOf_eq_done {cs : List Char} :\n    oneOf cs cb n = done n' c \u2194 \u2203 hn : n < cb.size, c \u2208 cs \u2227 n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = c := by\n  simp [one_of, sat_eq_done]\n#align parser.one_of_eq_done Parser.oneOf_eq_done\n\ntheorem oneOf'_eq_done {cs : List Char} :\n    oneOf' cs cb n = done n' u \u2194 \u2203 hn : n < cb.size, cb.read \u27e8n, hn\u27e9 \u2208 cs \u2227 n' = n + 1 :=\n  by\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_left]\n  constructor\n  \u00b7 rintro \u27e8c, hc, rfl, hn, rfl\u27e9\n    exact \u27e8rfl, hn, hc\u27e9\n  \u00b7 rintro \u27e8rfl, hn, hc\u27e9\n    exact \u27e8cb.read \u27e8n, hn\u27e9, hc, rfl, hn, rfl\u27e9\n#align parser.one_of'_eq_done Parser.oneOf'_eq_done\n\ntheorem str_eq_charBuf (s : String) : str s = charBuf s.toList.toBuffer :=\n  by\n  ext (cb n)\n  rw [str, char_buf]\n  congr\n  \u00b7 simp [Buffer.toString, String.asString_inv_toList]\n  \u00b7 simp\n#align parser.str_eq_char_buf Parser.str_eq_charBuf\n\ntheorem str_eq_done {s : String} :\n    str s cb n = done n' u \u2194 n + s.length = n' \u2227 s.toList <+: cb.toList.drop n := by\n  simp [str_eq_char_buf, char_buf_eq_done]\n#align parser.str_eq_done Parser.str_eq_done\n\ntheorem remaining_eq_done {r : \u2115} : remaining cb n = done n' r \u2194 n = n' \u2227 cb.size - n = r := by\n  simp [remaining]\n#align parser.remaining_eq_done Parser.remaining_eq_done\n\ntheorem remaining_ne_fail : remaining cb n \u2260 fail n' err := by simp [remaining]\n#align parser.remaining_ne_fail Parser.remaining_ne_fail\n\ntheorem eof_eq_done {u : Unit} : eof cb n = done n' u \u2194 n = n' \u2227 cb.size \u2264 n := by\n  simp [eof, guard_eq_done, remaining_eq_done, tsub_eq_zero_iff_le, and_comm', and_assoc']\n#align parser.eof_eq_done Parser.eof_eq_done\n\n@[simp]\ntheorem foldrCore_zero_eq_done {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {b' : \u03b2} :\n    foldrCore f p b 0 cb n \u2260 done n' b' := by simp [foldr_core]\n#align parser.foldr_core_zero_eq_done Parser.foldrCore_zero_eq_done\n\ntheorem foldrCore_eq_done {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {reps : \u2115} {b' : \u03b2} :\n    foldrCore f p b (reps + 1) cb n = done n' b' \u2194\n      (\u2203 (np : \u2115)(a : \u03b1)(xs : \u03b2),\n          p cb n = done np a \u2227 foldrCore f p b reps cb np = done n' xs \u2227 f a xs = b') \u2228\n        n = n' \u2227\n          b = b' \u2227\n            \u2203 err,\n              p cb n = fail n err \u2228\n                \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 foldrCore f p b reps cb np = fail n err :=\n  by simp [foldr_core, and_comm, and_assoc, pure_eq_done]\n#align parser.foldr_core_eq_done Parser.foldrCore_eq_done\n\n@[simp]\ntheorem foldrCore_zero_eq_fail {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {err : Dlist String} :\n    foldrCore f p b 0 cb n = fail n' err \u2194 n = n' \u2227 err = Dlist.empty := by\n  simp [foldr_core, eq_comm]\n#align parser.foldr_core_zero_eq_fail Parser.foldrCore_zero_eq_fail\n\ntheorem foldrCore_succ_eq_fail {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {reps : \u2115} {err : Dlist String} :\n    foldrCore f p b (reps + 1) cb n = fail n' err \u2194\n      n \u2260 n' \u2227\n        (p cb n = fail n' err \u2228\n          \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 foldrCore f p b reps cb np = fail n' err) :=\n  by simp [foldr_core, and_comm']\n#align parser.foldr_core_succ_eq_fail Parser.foldrCore_succ_eq_fail\n\ntheorem foldr_eq_done {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {b' : \u03b2} :\n    foldr f p b cb n = done n' b' \u2194\n      (\u2203 (np : \u2115)(a : \u03b1)(x : \u03b2),\n          p cb n = done np a \u2227 foldrCore f p b (cb.size - n) cb np = done n' x \u2227 f a x = b') \u2228\n        n = n' \u2227\n          b = b' \u2227\n            \u2203 err,\n              p cb n = ParseResult.fail n err \u2228\n                \u2203 (np : \u2115)(x : \u03b1),\n                  p cb n = done np x \u2227 foldrCore f p b (cb.size - n) cb np = fail n err :=\n  by simp [foldr, foldr_core_eq_done]\n#align parser.foldr_eq_done Parser.foldr_eq_done\n\ntheorem foldr_eq_fail_iff_mono_at_end {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {err : Dlist String} [p.mono]\n    (hc : cb.size \u2264 n) :\n    foldr f p b cb n = fail n' err \u2194\n      n < n' \u2227 (p cb n = fail n' err \u2228 \u2203 a : \u03b1, p cb n = done n' a \u2227 err = Dlist.empty) :=\n  by\n  have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr 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_right, exists_eq_left, and_congr_left_iff, exists_and_left]\n  rintro (h | \u27e8\u27e8a, h\u27e9, rfl\u27e9)\n  \u00b7 exact mono.of_fail h\n  \u00b7 exact mono.of_done h\n#align parser.foldr_eq_fail_iff_mono_at_end Parser.foldr_eq_fail_iff_mono_at_end\n\ntheorem foldr_eq_fail {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : Parser \u03b1} {err : Dlist String} :\n    foldr f p b cb n = fail n' err \u2194\n      n \u2260 n' \u2227\n        (p cb n = fail n' err \u2228\n          \u2203 (np : \u2115)(a : \u03b1),\n            p cb n = done np a \u2227 foldrCore f p b (cb.size - n) cb np = fail n' err) :=\n  by simp [foldr, foldr_core_succ_eq_fail]\n#align parser.foldr_eq_fail Parser.foldr_eq_fail\n\n@[simp]\ntheorem foldlCore_zero_eq_done {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {b' : \u03b2} :\n    foldlCore f b p 0 cb n = done n' b' \u2194 False := by simp [foldl_core]\n#align parser.foldl_core_zero_eq_done Parser.foldlCore_zero_eq_done\n\ntheorem foldlCore_eq_done {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {reps : \u2115} {b' : \u03b2} :\n    foldlCore f b p (reps + 1) cb n = done n' b' \u2194\n      (\u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 foldlCore f (f b a) p reps cb np = done n' b') \u2228\n        n = n' \u2227\n          b = b' \u2227\n            \u2203 err,\n              p cb n = fail n err \u2228\n                \u2203 (np : \u2115)(a : \u03b1),\n                  p cb n = done np a \u2227 foldlCore f (f b a) p reps cb np = fail n err :=\n  by simp [foldl_core, and_assoc, pure_eq_done]\n#align parser.foldl_core_eq_done Parser.foldlCore_eq_done\n\n@[simp]\ntheorem foldlCore_zero_eq_fail {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {err : Dlist String} :\n    foldlCore f b p 0 cb n = fail n' err \u2194 n = n' \u2227 err = Dlist.empty := by\n  simp [foldl_core, eq_comm]\n#align parser.foldl_core_zero_eq_fail Parser.foldlCore_zero_eq_fail\n\ntheorem foldlCore_succ_eq_fail {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {reps : \u2115} {err : Dlist String} :\n    foldlCore f b p (reps + 1) cb n = fail n' err \u2194\n      n \u2260 n' \u2227\n        (p cb n = fail n' err \u2228\n          \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 foldlCore f (f b a) p reps cb np = fail n' err) :=\n  by simp [foldl_core, and_comm']\n#align parser.foldl_core_succ_eq_fail Parser.foldlCore_succ_eq_fail\n\ntheorem foldl_eq_done {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {b' : \u03b2} :\n    foldl f b p cb n = done n' b' \u2194\n      (\u2203 (np : \u2115)(a : \u03b1),\n          p cb n = done np a \u2227 foldlCore f (f b a) p (cb.size - n) cb np = done n' b') \u2228\n        n = n' \u2227\n          b = b' \u2227\n            \u2203 err,\n              p cb n = fail n err \u2228\n                \u2203 (np : \u2115)(a : \u03b1),\n                  p cb n = done np a \u2227 foldlCore f (f b a) p (cb.size - n) cb np = fail n err :=\n  by simp [foldl, foldl_core_eq_done]\n#align parser.foldl_eq_done Parser.foldl_eq_done\n\ntheorem foldl_eq_fail {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {err : Dlist String} :\n    foldl f b p cb n = fail n' err \u2194\n      n \u2260 n' \u2227\n        (p cb n = fail n' err \u2228\n          \u2203 (np : \u2115)(a : \u03b1),\n            p cb n = done np a \u2227 foldlCore f (f b a) p (cb.size - n) cb np = fail n' err) :=\n  by simp [foldl, foldl_core_succ_eq_fail]\n#align parser.foldl_eq_fail Parser.foldl_eq_fail\n\ntheorem foldl_eq_fail_iff_mono_at_end {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : Parser \u03b1} {err : Dlist String} [p.mono]\n    (hc : cb.size \u2264 n) :\n    foldl f b p cb n = fail n' err \u2194\n      n < n' \u2227 (p cb n = fail n' err \u2228 \u2203 a : \u03b1, p cb n = done n' a \u2227 err = Dlist.empty) :=\n  by\n  have : cb.size - n = 0 := tsub_eq_zero_iff_le.mpr 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_right, and_congr_left_iff, exists_and_left, foldl_core_zero_eq_fail]\n  rintro (h | \u27e8\u27e8a, h\u27e9, rfl\u27e9)\n  \u00b7 exact mono.of_fail h\n  \u00b7 exact mono.of_done h\n#align parser.foldl_eq_fail_iff_mono_at_end Parser.foldl_eq_fail_iff_mono_at_end\n\ntheorem many_eq_done_nil {p : Parser \u03b1} :\n    many p cb n = done n' (@List.nil \u03b1) \u2194\n      n = n' \u2227\n        \u2203 err,\n          p cb n = fail n err \u2228\n            \u2203 (np : \u2115)(a : \u03b1),\n              p cb n = done np a \u2227 foldrCore List.cons p [] (cb.size - n) cb np = fail n err :=\n  by simp [many, foldr_eq_done]\n#align parser.many_eq_done_nil Parser.many_eq_done_nil\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem many_eq_done {p : Parser \u03b1} {x : \u03b1} {xs : List \u03b1} :\n    many p cb n = done n' (x::xs) \u2194\n      \u2203 np : \u2115, p cb n = done np x \u2227 foldrCore List.cons p [] (cb.size - n) cb np = done n' xs :=\n  by simp [many, foldr_eq_done, and_comm, and_assoc, and_left_comm]\n#align parser.many_eq_done Parser.many_eq_done\n\ntheorem many_eq_fail {p : Parser \u03b1} {err : Dlist String} :\n    many p cb n = fail n' err \u2194\n      n \u2260 n' \u2227\n        (p cb n = fail n' err \u2228\n          \u2203 (np : \u2115)(a : \u03b1),\n            p cb n = done np a \u2227 foldrCore List.cons p [] (cb.size - n) cb np = fail n' err) :=\n  by simp [many, foldr_eq_fail]\n#align parser.many_eq_fail Parser.many_eq_fail\n\ntheorem manyChar_eq_done_empty {p : Parser Char} :\n    manyChar p cb n = done n' String.empty \u2194\n      n = n' \u2227\n        \u2203 err,\n          p cb n = fail n err \u2228\n            \u2203 (np : \u2115)(c : Char),\n              p cb n = done np c \u2227 foldrCore List.cons p [] (cb.size - n) cb np = fail n err :=\n  by simp [many_char, many_eq_done_nil, map_eq_done, List.asString_eq]\n#align parser.many_char_eq_done_empty Parser.manyChar_eq_done_empty\n\ntheorem manyChar_eq_done_not_empty {p : Parser Char} {s : String} (h : s \u2260 \"\") :\n    manyChar p cb n = done n' s \u2194\n      \u2203 np : \u2115,\n        p cb n = done np s.headI \u2227\n          foldrCore List.cons p List.nil (Buffer.size cb - n) cb np = done n' (s.popn 1).toList :=\n  by simp [many_char, List.asString_eq, String.toList_nonempty h, many_eq_done]\n#align parser.many_char_eq_done_not_empty Parser.manyChar_eq_done_not_empty\n\ntheorem manyChar_eq_many_of_toList {p : Parser Char} {s : String} :\n    manyChar p cb n = done n' s \u2194 many p cb n = done n' s.toList := by\n  simp [many_char, List.asString_eq]\n#align parser.many_char_eq_many_of_to_list Parser.manyChar_eq_many_of_toList\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem many'_eq_done {p : Parser \u03b1} :\n    many' p cb n = done n' u \u2194\n      many p cb n = done n' [] \u2228\n        \u2203 (np : \u2115)(a : \u03b1)(l : List \u03b1),\n          many p cb n = done n' (a::l) \u2227\n            p cb n = done np a \u2227 foldrCore List.cons p [] (Buffer.size cb - n) cb np = done n' l :=\n  by\n  simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_right, bind_eq_done,\n    exists_eq_right]\n  constructor\n  \u00b7 rintro \u27e8_ | \u27e8hd, tl\u27e9, hl\u27e9\n    \u00b7 exact Or.inl hl\n    \u00b7 have hl2 := hl\n      simp only [foldr_core_eq_done, or_false_iff, exists_and_left, and_false_iff, false_and_iff,\n        exists_eq_right_right] at hl\n      obtain \u27e8np, hp, h\u27e9 := hl\n      refine' Or.inr \u27e8np, _, _, hl2, hp, h\u27e9\n  \u00b7 rintro (h | \u27e8np, a, l, hp, h\u27e9)\n    \u00b7 exact \u27e8[], h\u27e9\n    \u00b7 refine' \u27e8a::l, hp\u27e9\n#align parser.many'_eq_done Parser.many'_eq_done\n\n@[simp]\ntheorem many1_ne_done_nil {p : Parser \u03b1} : many1 p cb n \u2260 done n' [] := by simp [many1, seq_eq_done]\n#align parser.many1_ne_done_nil Parser.many1_ne_done_nil\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem many1_eq_done {p : Parser \u03b1} {l : List \u03b1} :\n    many1 p cb n = done n' (a::l) \u2194 \u2203 np : \u2115, p cb n = done np a \u2227 many p cb np = done n' l := by\n  simp [many1, seq_eq_done, map_eq_done]\n#align parser.many1_eq_done Parser.many1_eq_done\n\ntheorem many1_eq_fail {p : Parser \u03b1} {err : Dlist String} :\n    many1 p cb n = fail n' err \u2194\n      p cb n = fail n' err \u2228 \u2203 (np : \u2115)(a : \u03b1), p cb n = done np a \u2227 many p cb np = fail n' err :=\n  by simp [many1, seq_eq_fail]\n#align parser.many1_eq_fail Parser.many1_eq_fail\n\n@[simp]\ntheorem manyChar1_ne_empty {p : Parser Char} : manyChar1 p cb n \u2260 done n' \"\" := by\n  simp [many_char1, \u2190 String.nil_asString_eq_empty]\n#align parser.many_char1_ne_empty Parser.manyChar1_ne_empty\n\ntheorem manyChar1_eq_done {p : Parser Char} {s : String} (h : s \u2260 \"\") :\n    manyChar1 p cb n = done n' s \u2194\n      \u2203 np : \u2115, p cb n = done np s.headI \u2227 manyChar p cb np = done n' (s.popn 1) :=\n  by\n  simp [many_char1, List.asString_eq, String.toList_nonempty h, many1_eq_done,\n    many_char_eq_many_of_to_list]\n#align parser.many_char1_eq_done Parser.manyChar1_eq_done\n\n@[simp]\ntheorem sepBy1_ne_done_nil {sep : Parser Unit} {p : Parser \u03b1} : sepBy1 sep p cb n \u2260 done n' [] := by\n  simp [sep_by1, seq_eq_done]\n#align parser.sep_by1_ne_done_nil Parser.sepBy1_ne_done_nil\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem sepBy1_eq_done {sep : Parser Unit} {p : Parser \u03b1} {l : List \u03b1} :\n    sepBy1 sep p cb n = done n' (a::l) \u2194\n      \u2203 np : \u2115, p cb n = done np a \u2227 (sep >> p).anyM cb np = done n' l :=\n  by simp [sep_by1, seq_eq_done]\n#align parser.sep_by1_eq_done Parser.sepBy1_eq_done\n\ntheorem sepBy_eq_done_nil {sep : Parser Unit} {p : Parser \u03b1} :\n    sepBy sep p cb n = done n' [] \u2194 n = n' \u2227 \u2203 err, sepBy1 sep p cb n = fail n err := by\n  simp [sep_by, pure_eq_done]\n#align parser.sep_by_eq_done_nil Parser.sepBy_eq_done_nil\n\n@[simp]\ntheorem fixCore_ne_done_zero {F : Parser \u03b1 \u2192 Parser \u03b1} : fixCore F 0 cb n \u2260 done n' a := by\n  simp [fix_core]\n#align parser.fix_core_ne_done_zero Parser.fixCore_ne_done_zero\n\ntheorem fixCore_eq_done {F : Parser \u03b1 \u2192 Parser \u03b1} {max_depth : \u2115} :\n    fixCore F (max_depth + 1) cb n = done n' a \u2194 F (fixCore F max_depth) cb n = done n' a := by\n  simp [fix_core]\n#align parser.fix_core_eq_done Parser.fixCore_eq_done\n\ntheorem digit_eq_done {k : \u2115} :\n    digit cb n = done n' k \u2194\n      \u2203 hn : n < cb.size,\n        n' = n + 1 \u2227\n          k \u2264 9 \u2227\n            (cb.read \u27e8n, hn\u27e9).toNat - '0'.toNat = k \u2227\n              '0' \u2264 cb.read \u27e8n, hn\u27e9 \u2227 cb.read \u27e8n, hn\u27e9 \u2264 '9' :=\n  by\n  have c9 : '9'.toNat - '0'.toNat = 9 := rfl\n  have l09 : '0'.toNat \u2264 '9'.toNat := by decide\n  have le_iff_le : \u2200 {c c' : Char}, c \u2264 c' \u2194 c.toNat \u2264 c'.toNat := fun _ _ => Iff.rfl\n  constructor\n  \u00b7 simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, \u2190 c9]\n    rintro \u27e8np, c, \u27e8hn, \u27e8ge0, le9\u27e9, rfl, rfl\u27e9, rfl, rfl\u27e9\n    simpa [hn, ge0, le9, true_and_iff, and_true_iff, eq_self_iff_true, exists_prop_of_true,\n      tsub_le_tsub_iff_right, l09] using le_iff_le.mp le9\n  \u00b7 simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, \u2190 c9,\n      le_iff_le]\n    rintro \u27e8hn, rfl, -, rfl, ge0, le9\u27e9\n    use n + 1, cb.read \u27e8n, hn\u27e9\n    simp [hn, ge0, le9]\n#align parser.digit_eq_done Parser.digit_eq_done\n\ntheorem digit_eq_fail :\n    digit cb n = fail n' err \u2194\n      n = n' \u2227\n        err = Dlist.ofList [\"<digit>\"] \u2227\n          \u2200 h : n < cb.size, \u00ac(fun c => '0' \u2264 c \u2227 c \u2264 '9') (cb.read \u27e8n, h\u27e9) :=\n  by simp [digit, sat_eq_fail]\n#align parser.digit_eq_fail Parser.digit_eq_fail\n\nend Done\n\nnamespace Static\n\nvariable {\u03b1 \u03b2 : Type} {p q : Parser \u03b1} {msgs : Thunk (List String)} {msg : Thunk String}\n  {cb : CharBuffer} {n' n : \u2115} {err : Dlist String} {a : \u03b1} {b : \u03b2} {sep : Parser Unit}\n\ntheorem not_of_ne (h : p cb n = done n' a) (hne : n \u2260 n') : \u00acStatic p :=\n  by\n  intro\n  exact hne (of_done h)\n#align parser.static.not_of_ne Parser.Static.not_of_ne\n\ninstance pure : Static (pure a) :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [pure_eq_done]\n    rw [and_comm]\n    simp\u27e9\n#align parser.static.pure Parser.Static.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.Static] [\u2200 a, (f a).Static] : (p >>= f).Static :=\n  \u27e8fun _ _ _ _ => by\n    rw [bind_eq_done]\n    rintro \u27e8_, _, hp, hf\u27e9\n    exact trans (of_done hp) (of_done hf)\u27e9\n#align parser.static.bind Parser.Static.bind\n\ninstance andThen {q : Parser \u03b2} [p.Static] [q.Static] : (p >> q).Static :=\n  Static.bind\n#align parser.static.and_then Parser.Static.andThen\n\ninstance map [p.Static] {f : \u03b1 \u2192 \u03b2} : (f <$> p).Static :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [map_eq_done]\n    rintro \u27e8_, hp, _\u27e9\n    exact of_done hp\u27e9\n#align parser.static.map Parser.Static.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.Static] [p.Static] : (f <*> p).Static :=\n  Static.bind\n#align parser.static.seq Parser.Static.seq\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM : \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Static], (l.mapM f).Static\n  | [], _, _ => Static.pure\n  | a::l, _, h => by\n    convert static.bind\n    \u00b7 exact h _\n    \u00b7 intro\n      convert static.bind\n      \u00b7 convert mmap\n        exact h\n      \u00b7 exact fun _ => static.pure\n#align parser.static.mmap Parser.Static.mapM\n\n/- warning: parser.static.mmap' -> Parser.Static.mapM' is a dubious translation:\nlean 3 declaration is\n  forall {\u03b1 : Type} {\u03b2 : Type} {l : List.{0} \u03b1} {f : \u03b1 -> (Parser \u03b2)} [_inst_1 : forall (a : \u03b1), Parser.Static \u03b2 (f a)], Parser.Static Unit (List.mapM'.{0, 0} Parser Parser.monad \u03b1 \u03b2 f l)\nbut is expected to have type\n  PUnit.{0}\nCase conversion may be inaccurate. Consider using '#align parser.static.mmap' Parser.Static.mapM'\u2093'. -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM' : \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Static], (l.mapM' f).Static\n  | [], _, _ => Static.pure\n  | a::l, _, h => by\n    convert static.and_then\n    \u00b7 exact h _\n    \u00b7 convert mmap'\n      exact h\n#align parser.static.mmap' Parser.Static.mapM'\n\ninstance failure : @Parser.Static \u03b1 failure :=\n  \u27e8fun _ _ _ _ => by simp\u27e9\n#align parser.static.failure Parser.Static.failure\n\ninstance guard {p : Prop} [Decidable p] : Static (guard p) :=\n  \u27e8fun _ _ _ _ => by simp [guard_eq_done]\u27e9\n#align parser.static.guard Parser.Static.guard\n\ninstance orelse [p.Static] [q.Static] : (p <|> q).Static :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [orelse_eq_done]\n    rintro (h | \u27e8h, -\u27e9) <;> exact of_done h\u27e9\n#align parser.static.orelse Parser.Static.orelse\n\ninstance decorateErrors [p.Static] : (@decorateErrors \u03b1 msgs p).Static :=\n  \u27e8fun _ _ _ _ => by\n    rw [decorate_errors_eq_done]\n    exact of_done\u27e9\n#align parser.static.decorate_errors Parser.Static.decorateErrors\n\ninstance decorateError [p.Static] : (@decorateError \u03b1 msg p).Static :=\n  Static.decorateErrors\n#align parser.static.decorate_error Parser.Static.decorateError\n\ntheorem anyChar : \u00acStatic anyChar :=\n  haveI : any_char \"s\".toCharBuffer 0 = done 1 's' :=\n    by\n    have : 0 < \"s\".toCharBuffer.size := by decide\n    simpa [any_char_eq_done, this]\n  not_of_ne this zero_ne_one\n#align parser.static.any_char Parser.Static.anyChar\n\ntheorem sat_iff {p : Char \u2192 Prop} [DecidablePred p] : Static (sat p) \u2194 \u2200 c, \u00acp c :=\n  by\n  constructor\n  \u00b7 intro\n    intro c hc\n    have : sat p [c].toBuffer 0 = done 1 c := by simp [sat_eq_done, hc]\n    exact zero_ne_one (of_done this)\n  \u00b7 contrapose!\n    simp only [Iff, sat_eq_done, and_imp, exists_prop, exists_and_right, exists_and_left,\n      exists_imp, not_forall]\n    rintro _ _ _ a h hne rfl hp -\n    exact \u27e8a, hp\u27e9\n#align parser.static.sat_iff Parser.Static.sat_iff\n\ninstance sat : Static (sat fun _ => False) :=\n  by\n  apply sat_iff.mpr\n  simp\n#align parser.static.sat Parser.Static.sat\n\ninstance eps : Static eps :=\n  Static.pure\n#align parser.static.eps Parser.Static.eps\n\ntheorem ch (c : Char) : \u00acStatic (ch c) :=\n  haveI : ch c [c].toBuffer 0 = done 1 () :=\n    by\n    have : 0 < [c].toBuffer.size := by decide\n    simp [ch_eq_done, this]\n  not_of_ne this zero_ne_one\n#align parser.static.ch Parser.Static.ch\n\ntheorem charBuf_iff {cb' : CharBuffer} : Static (charBuf cb') \u2194 cb' = Buffer.nil :=\n  by\n  rw [\u2190 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  \u00b7 simp only [eq_self_iff_true, iff_true_iff]\n    exact \u27e8fun _ _ _ _ h => by simpa [hc] using (char_buf_eq_done.mp h).left\u27e9\n  \u00b7 rw [hc] at this\n    simpa [Nat.succ_ne_zero] using not_of_ne this (Nat.succ_ne_zero n).symm\n#align parser.static.char_buf_iff Parser.Static.charBuf_iff\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem oneOf_iff {cs : List Char} : Static (oneOf cs) \u2194 cs = [] :=\n  by\n  cases' cs with hd tl\n  \u00b7 simp [one_of, static.decorate_errors]\n  \u00b7 have : one_of (hd::tl) (hd::tl).toBuffer 0 = done 1 hd := by simp [one_of_eq_done]\n    simpa using not_of_ne this zero_ne_one\n#align parser.static.one_of_iff Parser.Static.oneOf_iff\n\ninstance oneOf : Static (oneOf []) := by\n  apply one_of_iff.mpr\n  rfl\n#align parser.static.one_of Parser.Static.oneOf\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem oneOf'_iff {cs : List Char} : Static (oneOf' cs) \u2194 cs = [] :=\n  by\n  cases' cs with hd tl\n  \u00b7 simp [one_of', static.bind]\n  \u00b7 have : one_of' (hd::tl) (hd::tl).toBuffer 0 = done 1 () := by simp [one_of'_eq_done]\n    simpa using not_of_ne this zero_ne_one\n#align parser.static.one_of'_iff Parser.Static.oneOf'_iff\n\ninstance one_of' : Static (oneOf []) :=\n  by\n  apply one_of_iff.mpr\n  rfl\n#align parser.static.one_of' Parser.Static.one_of'\n\ntheorem str_iff {s : String} : Static (str s) \u2194 s = \"\" := by\n  simp [str_eq_char_buf, char_buf_iff, \u2190 String.toList_inj, Buffer.ext_iff]\n#align parser.static.str_iff Parser.Static.str_iff\n\ninstance remaining : remaining.Static :=\n  \u27e8fun _ _ _ _ h => (remaining_eq_done.mp h).left\u27e9\n#align parser.static.remaining Parser.Static.remaining\n\ninstance eof : eof.Static :=\n  Static.decorateError\n#align parser.static.eof Parser.Static.eof\n\ninstance foldrCore {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} [p.Static] : \u2200 {b : \u03b2} {reps : \u2115}, (foldrCore f p b reps).Static\n  | _, 0 => Static.failure\n  | _, reps + 1 => by\n    simp_rw [Parser.foldrCore]\n    convert static.orelse\n    \u00b7 convert static.bind\n      \u00b7 infer_instance\n      \u00b7 intro\n        convert static.bind\n        \u00b7 exact foldr_core\n        \u00b7 infer_instance\n    \u00b7 exact static.pure\n#align parser.static.foldr_core Parser.Static.foldrCore\n\ninstance foldr {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} [p.Static] : Static (foldr f p b) :=\n  \u27e8fun _ _ _ _ => by\n    dsimp [foldr]\n    exact of_done\u27e9\n#align parser.static.foldr Parser.Static.foldr\n\ninstance foldlCore {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : Parser \u03b2} [p.Static] :\n    \u2200 {a : \u03b1} {reps : \u2115}, (foldlCore f a p reps).Static\n  | _, 0 => Static.failure\n  | _, reps + 1 => by\n    convert static.orelse\n    \u00b7 convert static.bind\n      \u00b7 infer_instance\n      \u00b7 exact fun _ => foldl_core\n    \u00b7 exact static.pure\n#align parser.static.foldl_core Parser.Static.foldlCore\n\ninstance foldl {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : Parser \u03b2} [p.Static] : Static (foldl f a p) :=\n  \u27e8fun _ _ _ _ => by\n    dsimp [foldl]\n    exact of_done\u27e9\n#align parser.static.foldl Parser.Static.foldl\n\ninstance many [p.Static] : p.anyM.Static :=\n  Static.foldr\n#align parser.static.many Parser.Static.many\n\ninstance manyChar {p : Parser Char} [p.Static] : p.manyChar.Static :=\n  Static.map\n#align parser.static.many_char Parser.Static.manyChar\n\ninstance many' [p.Static] : p.many'.Static :=\n  Static.andThen\n#align parser.static.many' Parser.Static.many'\n\ninstance many1 [p.Static] : p.many1.Static :=\n  Static.seq\n#align parser.static.many1 Parser.Static.many1\n\ninstance manyChar1 {p : Parser Char} [p.Static] : p.manyChar1.Static :=\n  Static.map\n#align parser.static.many_char1 Parser.Static.manyChar1\n\ninstance sepBy1 [p.Static] [sep.Static] : Static (sepBy1 sep p) :=\n  Static.seq\n#align parser.static.sep_by1 Parser.Static.sepBy1\n\ninstance sepBy [p.Static] [sep.Static] : Static (sepBy sep p) :=\n  Static.orelse\n#align parser.static.sep_by Parser.Static.sepBy\n\ntheorem fixCore {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.Static \u2192 (F p).Static) :\n    \u2200 max_depth : \u2115, Static (fixCore F max_depth)\n  | 0 => Static.failure\n  | max_depth + 1 => hF _ (fix_core _)\n#align parser.static.fix_core Parser.Static.fixCore\n\ntheorem digit : \u00acdigit.Static :=\n  haveI : digit \"1\".toCharBuffer 0 = done 1 1 :=\n    by\n    have : 0 < \"s\".toCharBuffer.size := by decide\n    simpa [this]\n  not_of_ne this zero_ne_one\n#align parser.static.digit Parser.Static.digit\n\ntheorem nat : \u00acnat.Static :=\n  haveI : Nat \"1\".toCharBuffer 0 = done 1 1 :=\n    by\n    have : 0 < \"s\".toCharBuffer.size := by decide\n    simpa [this]\n  not_of_ne this zero_ne_one\n#align parser.static.nat Parser.Static.nat\n\ntheorem fix {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.Static \u2192 (F p).Static) :\n    Static (fix F) :=\n  \u27e8fun cb n _ _ h => by\n    haveI := fix_core hF (cb.size - n + 1)\n    dsimp [fix] at h\n    exact static.of_done h\u27e9\n#align parser.static.fix Parser.Static.fix\n\nend Static\n\nnamespace Bounded\n\nvariable {\u03b1 \u03b2 : Type} {msgs : Thunk (List String)} {msg : Thunk String}\n\nvariable {p q : Parser \u03b1} {cb : CharBuffer} {n n' : \u2115} {err : Dlist String}\n\nvariable {a : \u03b1} {b : \u03b2}\n\ntheorem done_of_unbounded (h : \u00acp.Bounded) :\n    \u2203 (cb : CharBuffer)(n n' : \u2115)(a : \u03b1), p cb n = done n' a \u2227 cb.size \u2264 n :=\n  by\n  contrapose! h\n  constructor\n  intro cb n hn\n  cases hp : p cb n\n  \u00b7 exact absurd hn (h _ _ _ _ hp).not_le\n  \u00b7 simp [hp]\n#align parser.bounded.done_of_unbounded Parser.Bounded.done_of_unbounded\n\ntheorem pure : \u00acBounded (pure a) := by\n  intro\n  have : (pure a : Parser \u03b1) Buffer.nil 0 = done 0 a := by simp [pure_eq_done]\n  exact absurd (bounded.of_done this) (lt_irrefl _)\n#align parser.bounded.pure Parser.Bounded.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.Bounded] : (p >>= f).Bounded :=\n  by\n  constructor\n  intro cb n hn\n  obtain \u27e8_, _, hp\u27e9 := bounded.exists p hn\n  simp [hp]\n#align parser.bounded.bind Parser.Bounded.bind\n\ninstance andThen {q : Parser \u03b2} [p.Bounded] : (p >> q).Bounded :=\n  Bounded.bind\n#align parser.bounded.and_then Parser.Bounded.andThen\n\ninstance map [p.Bounded] {f : \u03b1 \u2192 \u03b2} : (f <$> p).Bounded :=\n  Bounded.bind\n#align parser.bounded.map Parser.Bounded.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.Bounded] : (f <*> p).Bounded :=\n  Bounded.bind\n#align parser.bounded.seq Parser.Bounded.seq\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM {a : \u03b1} {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Bounded] :\n    ((a::l).mapM f).Bounded :=\n  Bounded.bind\n#align parser.bounded.mmap Parser.Bounded.mapM\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM' {a : \u03b1} {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Bounded] :\n    ((a::l).mapM' f).Bounded :=\n  Bounded.andThen\n#align parser.bounded.mmap' Parser.Bounded.mapM'\n\ninstance failure : @Parser.Bounded \u03b1 failure :=\n  \u27e8by simp\u27e9\n#align parser.bounded.failure Parser.Bounded.failure\n\ntheorem guard_iff {p : Prop} [Decidable p] : Bounded (guard p) \u2194 \u00acp := by\n  simpa [guard, apply_ite bounded, pure, failure] using fun _ => bounded.failure\n#align parser.bounded.guard_iff Parser.Bounded.guard_iff\n\ninstance orelse [p.Bounded] [q.Bounded] : (p <|> q).Bounded :=\n  by\n  constructor\n  intro cb n hn\n  cases' hx : (p <|> q) cb n with posx resx posx errx\n  \u00b7 obtain h | \u27e8h, -, -\u27e9 := orelse_eq_done.mp hx <;> exact absurd hn (of_done h).not_le\n  \u00b7 simp\n#align parser.bounded.orelse Parser.Bounded.orelse\n\ninstance decorateErrors [p.Bounded] : (@decorateErrors \u03b1 msgs p).Bounded :=\n  by\n  constructor\n  intro _ _\n  simpa using bounded.exists p\n#align parser.bounded.decorate_errors Parser.Bounded.decorateErrors\n\ntheorem decorateErrors_iff : (@Parser.decorateErrors \u03b1 msgs p).Bounded \u2194 p.Bounded :=\n  by\n  constructor\n  \u00b7 intro\n    constructor\n    intro _ _ hn\n    obtain \u27e8_, _, h\u27e9 := bounded.exists (@Parser.decorateErrors \u03b1 msgs p) hn\n    simp [decorate_errors_eq_fail] at h\n    exact h.right.right\n  \u00b7 intro\n    constructor\n    intro _ _ hn\n    obtain \u27e8_, _, h\u27e9 := bounded.exists p hn\n    simp [h]\n#align parser.bounded.decorate_errors_iff Parser.Bounded.decorateErrors_iff\n\ninstance decorateError [p.Bounded] : (@decorateError \u03b1 msg p).Bounded :=\n  Bounded.decorateErrors\n#align parser.bounded.decorate_error Parser.Bounded.decorateError\n\ntheorem decorateError_iff : (@Parser.decorateError \u03b1 msg p).Bounded \u2194 p.Bounded :=\n  decorateErrors_iff\n#align parser.bounded.decorate_error_iff Parser.Bounded.decorateError_iff\n\ninstance anyChar : Bounded anyChar :=\n  \u27e8fun cb n hn => by simp [any_char, hn]\u27e9\n#align parser.bounded.any_char Parser.Bounded.anyChar\n\ninstance sat {p : Char \u2192 Prop} [DecidablePred p] : Bounded (sat p) :=\n  \u27e8fun cb n hn => by simp [sat, hn]\u27e9\n#align parser.bounded.sat Parser.Bounded.sat\n\ntheorem eps : \u00acBounded eps :=\n  pure\n#align parser.bounded.eps Parser.Bounded.eps\n\ninstance ch {c : Char} : Bounded (ch c) :=\n  Bounded.decorateError\n#align parser.bounded.ch Parser.Bounded.ch\n\ntheorem charBuf_iff {cb' : CharBuffer} : Bounded (charBuf cb') \u2194 cb' \u2260 Buffer.nil :=\n  by\n  have : cb' \u2260 Buffer.nil \u2194 cb'.to_list \u2260 [] :=\n    not_congr \u27e8fun h => by simp [h], fun h => by simpa using congr_arg List.toBuffer h\u27e9\n  rw [char_buf, decorate_error_iff, this]\n  cases cb'.to_list\n  \u00b7 simp [pure, ch]\n  \u00b7 simp only [iff_true_iff, Ne.def, not_false_iff]\n    infer_instance\n#align parser.bounded.char_buf_iff Parser.Bounded.charBuf_iff\n\ninstance oneOf {cs : List Char} : (oneOf cs).Bounded :=\n  Bounded.decorateErrors\n#align parser.bounded.one_of Parser.Bounded.oneOf\n\ninstance oneOf' {cs : List Char} : (oneOf' cs).Bounded :=\n  Bounded.andThen\n#align parser.bounded.one_of' Parser.Bounded.oneOf'\n\ntheorem str_iff {s : String} : (str s).Bounded \u2194 s \u2260 \"\" :=\n  by\n  rw [str, decorate_error_iff]\n  cases hs : s.to_list\n  \u00b7 have : s = \"\" := by\n      cases s\n      rw [String.toList] at hs\n      simpa [hs]\n    simp [pure, this]\n  \u00b7 have : s \u2260 \"\" := by\n      intro H\n      simpa [H] using hs\n    simp only [this, iff_true_iff, Ne.def, not_false_iff]\n    infer_instance\n#align parser.bounded.str_iff Parser.Bounded.str_iff\n\ntheorem remaining : \u00acremaining.Bounded := by\n  intro\n  have : remaining Buffer.nil 0 = done 0 0 := by simp [remaining_eq_done]\n  exact absurd (bounded.of_done this) (lt_irrefl _)\n#align parser.bounded.remaining Parser.Bounded.remaining\n\ntheorem eof : \u00aceof.Bounded := by\n  intro\n  have : eof Buffer.nil 0 = done 0 () := by simp [eof_eq_done]\n  exact absurd (bounded.of_done this) (lt_irrefl _)\n#align parser.bounded.eof Parser.Bounded.eof\n\nsection Fold\n\ninstance foldrCore_zero {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} : (foldrCore f p b 0).Bounded :=\n  Bounded.failure\n#align parser.bounded.foldr_core_zero Parser.Bounded.foldrCore_zero\n\ninstance foldlCore_zero {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {b : \u03b2} : (foldlCore f b p 0).Bounded :=\n  Bounded.failure\n#align parser.bounded.foldl_core_zero Parser.Bounded.foldlCore_zero\n\nvariable {reps : \u2115} [hpb : p.Bounded] (he : \u2200 cb n n' err, p cb n = fail n' err \u2192 n \u2260 n')\n\ninclude hpb he\n\ntheorem foldrCore {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} : (foldrCore f p b reps).Bounded :=\n  by\n  cases reps\n  \u00b7 exact bounded.foldr_core_zero\n  constructor\n  intro cb n hn\n  obtain \u27e8np, errp, hp\u27e9 := bounded.exists p hn\n  simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp\n#align parser.bounded.foldr_core Parser.Bounded.foldrCore\n\ntheorem foldr {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} : Bounded (foldr f p b) :=\n  by\n  constructor\n  intro cb n hn\n  haveI : (Parser.foldrCore f p b (cb.size - n + 1)).Bounded := foldr_core he\n  obtain \u27e8np, errp, hp\u27e9 := bounded.exists (Parser.foldrCore f p b (cb.size - n + 1)) hn\n  simp [foldr, hp]\n#align parser.bounded.foldr Parser.Bounded.foldr\n\ntheorem foldlCore {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} : (foldlCore f b p reps).Bounded :=\n  by\n  cases reps\n  \u00b7 exact bounded.foldl_core_zero\n  constructor\n  intro cb n hn\n  obtain \u27e8np, errp, hp\u27e9 := bounded.exists p hn\n  simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp\n#align parser.bounded.foldl_core Parser.Bounded.foldlCore\n\ntheorem foldl {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} : Bounded (foldl f b p) :=\n  by\n  constructor\n  intro cb n hn\n  haveI : (Parser.foldlCore f b p (cb.size - n + 1)).Bounded := foldl_core he\n  obtain \u27e8np, errp, hp\u27e9 := bounded.exists (Parser.foldlCore f b p (cb.size - n + 1)) hn\n  simp [foldl, hp]\n#align parser.bounded.foldl Parser.Bounded.foldl\n\ntheorem many : p.anyM.Bounded :=\n  foldr he\n#align parser.bounded.many Parser.Bounded.many\n\nomit hpb\n\ntheorem manyChar {pc : Parser Char} [pc.Bounded]\n    (he : \u2200 cb n n' err, pc cb n = fail n' err \u2192 n \u2260 n') : pc.manyChar.Bounded :=\n  by\n  convert bounded.map\n  exact many he\n#align parser.bounded.many_char Parser.Bounded.manyChar\n\ninclude hpb\n\ntheorem many' : p.many'.Bounded := by\n  convert bounded.and_then\n  exact many he\n#align parser.bounded.many' Parser.Bounded.many'\n\nend Fold\n\ninstance many1 [p.Bounded] : p.many1.Bounded :=\n  Bounded.seq\n#align parser.bounded.many1 Parser.Bounded.many1\n\ninstance manyChar1 {p : Parser Char} [p.Bounded] : p.manyChar1.Bounded :=\n  Bounded.map\n#align parser.bounded.many_char1 Parser.Bounded.manyChar1\n\ninstance sepBy1 {sep : Parser Unit} [p.Bounded] : Bounded (sepBy1 sep p) :=\n  Bounded.seq\n#align parser.bounded.sep_by1 Parser.Bounded.sepBy1\n\ntheorem fixCore {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.Bounded \u2192 (F p).Bounded) :\n    \u2200 max_depth : \u2115, Bounded (fixCore F max_depth)\n  | 0 => Bounded.failure\n  | max_depth + 1 => hF _ (fix_core _)\n#align parser.bounded.fix_core Parser.Bounded.fixCore\n\ninstance digit : digit.Bounded :=\n  Bounded.decorateError\n#align parser.bounded.digit Parser.Bounded.digit\n\ninstance nat : nat.Bounded :=\n  Bounded.decorateError\n#align parser.bounded.nat Parser.Bounded.nat\n\ntheorem fix {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.Bounded \u2192 (F p).Bounded) :\n    Bounded (fix F) := by\n  constructor\n  intro cb n hn\n  haveI : (Parser.fixCore F (cb.size - n + 1)).Bounded := fix_core hF _\n  obtain \u27e8np, errp, hp\u27e9 := bounded.exists (Parser.fixCore F (cb.size - n + 1)) hn\n  simp [fix, hp]\n#align parser.bounded.fix Parser.Bounded.fix\n\nend Bounded\n\nnamespace Unfailing\n\nvariable {\u03b1 \u03b2 : Type} {p q : Parser \u03b1} {msgs : Thunk (List String)} {msg : Thunk String}\n  {cb : CharBuffer} {n' n : \u2115} {err : Dlist String} {a : \u03b1} {b : \u03b2} {sep : Parser Unit}\n\ntheorem of_bounded [p.Bounded] : \u00acUnfailing p :=\n  by\n  intro\n  cases h : p Buffer.nil 0\n  \u00b7 simpa [lt_irrefl] using bounded.of_done h\n  \u00b7 exact of_fail h\n#align parser.unfailing.of_bounded Parser.Unfailing.of_bounded\n\ninstance pure : Unfailing (pure a) :=\n  \u27e8fun _ _ => by simp [pure_eq_done]\u27e9\n#align parser.unfailing.pure Parser.Unfailing.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.Unfailing] [\u2200 a, (f a).Unfailing] : (p >>= f).Unfailing :=\n  \u27e8fun cb n => by\n    obtain \u27e8np, a, hp\u27e9 := exists_done p cb n\n    simpa [hp, and_comm, and_left_comm, and_assoc] using exists_done (f a) cb np\u27e9\n#align parser.unfailing.bind Parser.Unfailing.bind\n\ninstance andThen {q : Parser \u03b2} [p.Unfailing] [q.Unfailing] : (p >> q).Unfailing :=\n  Unfailing.bind\n#align parser.unfailing.and_then Parser.Unfailing.andThen\n\ninstance map [p.Unfailing] {f : \u03b1 \u2192 \u03b2} : (f <$> p).Unfailing :=\n  Unfailing.bind\n#align parser.unfailing.map Parser.Unfailing.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.Unfailing] [p.Unfailing] : (f <*> p).Unfailing :=\n  Unfailing.bind\n#align parser.unfailing.seq Parser.Unfailing.seq\n\ninstance mapM {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Unfailing] : (l.mapM f).Unfailing :=\n  by\n  constructor\n  induction' l with hd tl hl\n  \u00b7 intros\n    simp [pure_eq_done]\n  \u00b7 intros\n    obtain \u27e8np, a, hp\u27e9 := exists_done (f hd) cb n\n    obtain \u27e8n', b, hf\u27e9 := hl cb np\n    simp [hp, hf, and_comm, and_left_comm, and_assoc, pure_eq_done]\n#align parser.unfailing.mmap Parser.Unfailing.mapM\n\ninstance mapM' {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Unfailing] : (l.mapM' f).Unfailing :=\n  by\n  constructor\n  induction' l with hd tl hl\n  \u00b7 intros\n    simp [pure_eq_done]\n  \u00b7 intros\n    obtain \u27e8np, a, hp\u27e9 := exists_done (f hd) cb n\n    obtain \u27e8n', b, hf\u27e9 := hl cb np\n    simp [hp, hf, and_comm, and_left_comm, and_assoc, pure_eq_done]\n#align parser.unfailing.mmap' Parser.Unfailing.mapM'\n\ntheorem failure : \u00ac@Parser.Unfailing \u03b1 failure :=\n  by\n  intro h\n  have : (failure : Parser \u03b1) Buffer.nil 0 = fail 0 Dlist.empty := by simp\n  exact of_fail this\n#align parser.unfailing.failure Parser.Unfailing.failure\n\ninstance guard_true : Unfailing (guard True) :=\n  Unfailing.pure\n#align parser.unfailing.guard_true Parser.Unfailing.guard_true\n\ntheorem guard : \u00acUnfailing (guard False) :=\n  Unfailing.failure\n#align parser.unfailing.guard Parser.Unfailing.guard\n\ninstance orelse [p.Unfailing] : (p <|> q).Unfailing :=\n  \u27e8fun cb n => by\n    obtain \u27e8_, _, h\u27e9 := p.exists_done cb n\n    simp [success_iff, h]\u27e9\n#align parser.unfailing.orelse Parser.Unfailing.orelse\n\ninstance decorateErrors [p.Unfailing] : (@decorateErrors \u03b1 msgs p).Unfailing :=\n  \u27e8fun cb n => by\n    obtain \u27e8_, _, h\u27e9 := p.exists_done cb n\n    simp [success_iff, h]\u27e9\n#align parser.unfailing.decorate_errors Parser.Unfailing.decorateErrors\n\ninstance decorateError [p.Unfailing] : (@decorateError \u03b1 msg p).Unfailing :=\n  Unfailing.decorateErrors\n#align parser.unfailing.decorate_error Parser.Unfailing.decorateError\n\ninstance anyChar : ConditionallyUnfailing anyChar :=\n  \u27e8fun _ _ hn => by simp [success_iff, any_char_eq_done, hn]\u27e9\n#align parser.unfailing.any_char Parser.Unfailing.anyChar\n\ntheorem sat : ConditionallyUnfailing (sat fun _ => True) :=\n  \u27e8fun _ _ hn => by simp [success_iff, sat_eq_done, hn]\u27e9\n#align parser.unfailing.sat Parser.Unfailing.sat\n\ninstance eps : Unfailing eps :=\n  Unfailing.pure\n#align parser.unfailing.eps Parser.Unfailing.eps\n\ninstance remaining : remaining.Unfailing :=\n  \u27e8fun _ _ => by simp [success_iff, remaining_eq_done]\u27e9\n#align parser.unfailing.remaining Parser.Unfailing.remaining\n\ntheorem foldrCore_zero {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} : \u00ac(foldrCore f p b 0).Unfailing :=\n  Unfailing.failure\n#align parser.unfailing.foldr_core_zero Parser.Unfailing.foldrCore_zero\n\ninstance foldrCore_of_static {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} {reps : \u2115} [p.Static] [p.Unfailing] :\n    (foldrCore f p b (reps + 1)).Unfailing :=\n  by\n  induction' reps with reps hr\n  \u00b7 constructor\n    intro cb n\n    obtain \u27e8np, a, h\u27e9 := p.exists_done cb n\n    simpa [foldr_core_eq_done, h] using (static.of_done h).symm\n  \u00b7 constructor\n    haveI := hr\n    intro cb n\n    obtain \u27e8np, a, h\u27e9 := p.exists_done cb n\n    obtain rfl : n = np := static.of_done h\n    obtain \u27e8np, b', hf\u27e9 := exists_done (foldr_core f p b (reps + 1)) cb n\n    obtain rfl : n = np := static.of_done hf\n    refine' \u27e8n, f a b', _\u27e9\n    rw [foldr_core_eq_done]\n    simp [h, hf, and_comm, and_left_comm, and_assoc]\n#align parser.unfailing.foldr_core_of_static Parser.Unfailing.foldrCore_of_static\n\ninstance foldrCore_one_of_errStatic {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} [p.Static] [p.ErrStatic] :\n    (foldrCore f p b 1).Unfailing := by\n  constructor\n  intro cb n\n  cases h : p cb n\n  \u00b7 simpa [foldr_core_eq_done, h] using (static.of_done h).symm\n  \u00b7 simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm\n#align parser.unfailing.foldr_core_one_of_err_static Parser.Unfailing.foldrCore_one_of_errStatic\n\n-- TODO: add foldr and foldl, many, etc, fix_core\ntheorem digit : \u00acdigit.Unfailing :=\n  of_bounded\n#align parser.unfailing.digit Parser.Unfailing.digit\n\ntheorem nat : \u00acnat.Unfailing :=\n  of_bounded\n#align parser.unfailing.nat Parser.Unfailing.nat\n\nend Unfailing\n\nnamespace ErrStatic\n\nvariable {\u03b1 \u03b2 : Type} {p q : Parser \u03b1} {msgs : Thunk (List String)} {msg : Thunk String}\n  {cb : CharBuffer} {n' n : \u2115} {err : Dlist String} {a : \u03b1} {b : \u03b2} {sep : Parser Unit}\n\ntheorem not_of_ne (h : p cb n = fail n' err) (hne : n \u2260 n') : \u00acErrStatic p :=\n  by\n  intro\n  exact hne (of_fail h)\n#align parser.err_static.not_of_ne Parser.ErrStatic.not_of_ne\n\ninstance pure : ErrStatic (pure a) :=\n  \u27e8fun _ _ _ _ => by simp [pure_eq_done]\u27e9\n#align parser.err_static.pure Parser.ErrStatic.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.Static] [p.ErrStatic] [\u2200 a, (f a).ErrStatic] :\n    (p >>= f).ErrStatic :=\n  \u27e8fun cb n n' err => by\n    rw [bind_eq_fail]\n    rintro (hp | \u27e8_, _, hp, hf\u27e9)\n    \u00b7 exact of_fail hp\n    \u00b7 exact trans (static.of_done hp) (of_fail hf)\u27e9\n#align parser.err_static.bind Parser.ErrStatic.bind\n\ninstance bind_of_unfailing {f : \u03b1 \u2192 Parser \u03b2} [p.ErrStatic] [\u2200 a, (f a).Unfailing] :\n    (p >>= f).ErrStatic :=\n  \u27e8fun cb n n' err => by\n    rw [bind_eq_fail]\n    rintro (hp | \u27e8_, _, hp, hf\u27e9)\n    \u00b7 exact of_fail hp\n    \u00b7 exact False.elim (unfailing.of_fail hf)\u27e9\n#align parser.err_static.bind_of_unfailing Parser.ErrStatic.bind_of_unfailing\n\ninstance andThen {q : Parser \u03b2} [p.Static] [p.ErrStatic] [q.ErrStatic] : (p >> q).ErrStatic :=\n  ErrStatic.bind\n#align parser.err_static.and_then Parser.ErrStatic.andThen\n\ninstance andThen_of_unfailing {q : Parser \u03b2} [p.ErrStatic] [q.Unfailing] : (p >> q).ErrStatic :=\n  ErrStatic.bind_of_unfailing\n#align parser.err_static.and_then_of_unfailing Parser.ErrStatic.andThen_of_unfailing\n\ninstance map [p.ErrStatic] {f : \u03b1 \u2192 \u03b2} : (f <$> p).ErrStatic :=\n  \u27e8fun _ _ _ _ => by\n    rw [map_eq_fail]\n    exact of_fail\u27e9\n#align parser.err_static.map Parser.ErrStatic.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.Static] [f.ErrStatic] [p.ErrStatic] : (f <*> p).ErrStatic :=\n  ErrStatic.bind\n#align parser.err_static.seq Parser.ErrStatic.seq\n\ninstance seq_of_unfailing {f : Parser (\u03b1 \u2192 \u03b2)} [f.ErrStatic] [p.Unfailing] : (f <*> p).ErrStatic :=\n  ErrStatic.bind_of_unfailing\n#align parser.err_static.seq_of_unfailing Parser.ErrStatic.seq_of_unfailing\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM :\n    \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Static] [\u2200 a, (f a).ErrStatic],\n      (l.mapM f).ErrStatic\n  | [], _, _, _ => ErrStatic.pure\n  | a::l, _, h, h' => by\n    convert err_static.bind\n    \u00b7 exact h _\n    \u00b7 exact h' _\n    \u00b7 intro\n      convert err_static.bind\n      \u00b7 convert static.mmap\n        exact h\n      \u00b7 apply mmap\n        \u00b7 exact h\n        \u00b7 exact h'\n      \u00b7 exact fun _ => err_static.pure\n#align parser.err_static.mmap Parser.ErrStatic.mapM\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM_of_unfailing :\n    \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Unfailing] [\u2200 a, (f a).ErrStatic],\n      (l.mapM f).ErrStatic\n  | [], _, _, _ => ErrStatic.pure\n  | a::l, _, h, h' => by\n    convert err_static.bind_of_unfailing\n    \u00b7 exact h' _\n    \u00b7 intro\n      convert unfailing.bind\n      \u00b7 convert unfailing.mmap\n        exact h\n      \u00b7 exact fun _ => unfailing.pure\n#align parser.err_static.mmap_of_unfailing Parser.ErrStatic.mapM_of_unfailing\n\n/- warning: parser.err_static.mmap' -> Parser.ErrStatic.mapM' is a dubious translation:\nlean 3 declaration is\n  forall {\u03b1 : Type} {\u03b2 : Type} {l : List.{0} \u03b1} {f : \u03b1 -> (Parser \u03b2)} [_inst_1 : forall (a : \u03b1), Parser.Static \u03b2 (f a)] [_inst_2 : forall (a : \u03b1), Parser.ErrStatic \u03b2 (f a)], Parser.ErrStatic Unit (List.mapM'.{0, 0} Parser Parser.monad \u03b1 \u03b2 f l)\nbut is expected to have type\n  PUnit.{0}\nCase conversion may be inaccurate. Consider using '#align parser.err_static.mmap' Parser.ErrStatic.mapM'\u2093'. -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM' :\n    \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Static] [\u2200 a, (f a).ErrStatic],\n      (l.mapM' f).ErrStatic\n  | [], _, _, _ => ErrStatic.pure\n  | a::l, _, h, h' => by\n    convert err_static.and_then\n    \u00b7 exact h _\n    \u00b7 exact h' _\n    \u00b7 convert mmap'\n      \u00b7 exact h\n      \u00b7 exact h'\n#align parser.err_static.mmap' Parser.ErrStatic.mapM'\n\n/- warning: parser.err_static.mmap'_of_unfailing -> Parser.ErrStatic.mapM'_of_unfailing is a dubious translation:\nlean 3 declaration is\n  forall {\u03b1 : Type} {\u03b2 : Type} {l : List.{0} \u03b1} {f : \u03b1 -> (Parser \u03b2)} [_inst_1 : forall (a : \u03b1), Parser.Unfailing \u03b2 (f a)] [_inst_2 : forall (a : \u03b1), Parser.ErrStatic \u03b2 (f a)], Parser.ErrStatic Unit (List.mapM'.{0, 0} Parser Parser.monad \u03b1 \u03b2 f l)\nbut is expected to have type\n  PUnit.{0}\nCase conversion may be inaccurate. Consider using '#align parser.err_static.mmap'_of_unfailing Parser.ErrStatic.mapM'_of_unfailing\u2093'. -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM'_of_unfailing :\n    \u2200 {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [\u2200 a, (f a).Unfailing] [\u2200 a, (f a).ErrStatic],\n      (l.mapM' f).ErrStatic\n  | [], _, _, _ => ErrStatic.pure\n  | a::l, _, h, h' => by\n    convert err_static.and_then_of_unfailing\n    \u00b7 exact h' _\n    \u00b7 convert unfailing.mmap'\n      exact h\n#align parser.err_static.mmap'_of_unfailing Parser.ErrStatic.mapM'_of_unfailing\n\ninstance failure : @Parser.ErrStatic \u03b1 failure :=\n  \u27e8fun _ _ _ _ h => (failure_eq_fail.mp h).left\u27e9\n#align parser.err_static.failure Parser.ErrStatic.failure\n\ninstance guard {p : Prop} [Decidable p] : ErrStatic (guard p) :=\n  \u27e8fun _ _ _ _ h => (guard_eq_fail.mp h).right.left\u27e9\n#align parser.err_static.guard Parser.ErrStatic.guard\n\ninstance orelse [p.ErrStatic] [q.mono] : (p <|> q).ErrStatic :=\n  \u27e8fun _ n n' _ => by\n    by_cases hn : n = n'\n    \u00b7 exact fun _ => hn\n    \u00b7 rw [orelse_eq_fail_of_mono_ne hn]\n      \u00b7 exact of_fail\n      \u00b7 infer_instance\u27e9\n#align parser.err_static.orelse Parser.ErrStatic.orelse\n\ninstance decorateErrors : (@decorateErrors \u03b1 msgs p).ErrStatic :=\n  \u27e8fun _ _ _ _ h => (decorateErrors_eq_fail.mp h).left\u27e9\n#align parser.err_static.decorate_errors Parser.ErrStatic.decorateErrors\n\ninstance decorateError : (@decorateError \u03b1 msg p).ErrStatic :=\n  ErrStatic.decorateErrors\n#align parser.err_static.decorate_error Parser.ErrStatic.decorateError\n\ninstance anyChar : ErrStatic anyChar :=\n  \u27e8fun _ _ _ _ => by\n    rw [any_char_eq_fail, and_comm]\n    simp\u27e9\n#align parser.err_static.any_char Parser.ErrStatic.anyChar\n\ninstance sat_iff {p : Char \u2192 Prop} [DecidablePred p] : ErrStatic (sat p) :=\n  \u27e8fun _ _ _ _ h => (sat_eq_fail.mp h).left\u27e9\n#align parser.err_static.sat_iff Parser.ErrStatic.sat_iff\n\ninstance eps : ErrStatic eps :=\n  ErrStatic.pure\n#align parser.err_static.eps Parser.ErrStatic.eps\n\ninstance ch (c : Char) : ErrStatic (ch c) :=\n  ErrStatic.decorateError\n#align parser.err_static.ch Parser.ErrStatic.ch\n\ninstance charBuf {cb' : CharBuffer} : ErrStatic (charBuf cb') :=\n  ErrStatic.decorateError\n#align parser.err_static.char_buf Parser.ErrStatic.charBuf\n\ninstance oneOf {cs : List Char} : ErrStatic (oneOf cs) :=\n  ErrStatic.decorateErrors\n#align parser.err_static.one_of Parser.ErrStatic.oneOf\n\ninstance oneOf' {cs : List Char} : ErrStatic (oneOf' cs) :=\n  ErrStatic.andThen_of_unfailing\n#align parser.err_static.one_of' Parser.ErrStatic.oneOf'\n\ninstance str {s : String} : ErrStatic (str s) :=\n  ErrStatic.decorateError\n#align parser.err_static.str Parser.ErrStatic.str\n\ninstance remaining : remaining.ErrStatic :=\n  \u27e8fun _ _ _ _ => by simp [remaining_ne_fail]\u27e9\n#align parser.err_static.remaining Parser.ErrStatic.remaining\n\ninstance eof : eof.ErrStatic :=\n  ErrStatic.decorateError\n#align parser.err_static.eof Parser.ErrStatic.eof\n\n-- TODO: add foldr and foldl, many, etc, fix_core\ntheorem fixCore {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.ErrStatic \u2192 (F p).ErrStatic) :\n    \u2200 max_depth : \u2115, ErrStatic (fixCore F max_depth)\n  | 0 => ErrStatic.failure\n  | max_depth + 1 => hF _ (fix_core _)\n#align parser.err_static.fix_core Parser.ErrStatic.fixCore\n\ninstance digit : digit.ErrStatic :=\n  ErrStatic.decorateError\n#align parser.err_static.digit Parser.ErrStatic.digit\n\ninstance nat : nat.ErrStatic :=\n  ErrStatic.decorateError\n#align parser.err_static.nat Parser.ErrStatic.nat\n\ntheorem fix {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.ErrStatic \u2192 (F p).ErrStatic) :\n    ErrStatic (fix F) :=\n  \u27e8fun cb n _ _ h => by\n    haveI := fix_core hF (cb.size - n + 1)\n    dsimp [fix] at h\n    exact err_static.of_fail h\u27e9\n#align parser.err_static.fix Parser.ErrStatic.fix\n\nend ErrStatic\n\nnamespace Step\n\nvariable {\u03b1 \u03b2 : Type} {p q : Parser \u03b1} {msgs : Thunk (List String)} {msg : Thunk String}\n  {cb : CharBuffer} {n' n : \u2115} {err : Dlist String} {a : \u03b1} {b : \u03b2} {sep : Parser Unit}\n\ntheorem not_step_of_static_done [Static p] (h : \u2203 cb n n' a, p cb n = done n' a) : \u00acStep p :=\n  by\n  intro\n  rcases h with \u27e8cb, n, n', a, h\u27e9\n  have hs := static.of_done h\n  simpa [\u2190 hs] using of_done h\n#align parser.step.not_step_of_static_done Parser.Step.not_step_of_static_done\n\ntheorem pure (a : \u03b1) : \u00acStep (pure a) :=\n  by\n  apply not_step_of_static_done\n  simp [pure_eq_done]\n#align parser.step.pure Parser.Step.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.step] [\u2200 a, (f a).Static] : (p >>= f).step :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [bind_eq_done]\n    rintro \u27e8_, _, hp, hf\u27e9\n    exact static.of_done hf \u25b8 of_done hp\u27e9\n#align parser.step.bind Parser.Step.bind\n\ninstance bind' {f : \u03b1 \u2192 Parser \u03b2} [p.Static] [\u2200 a, (f a).step] : (p >>= f).step :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [bind_eq_done]\n    rintro \u27e8_, _, hp, hf\u27e9\n    rw [static.of_done hp]\n    exact of_done hf\u27e9\n#align parser.step.bind' Parser.Step.bind'\n\ninstance andThen {q : Parser \u03b2} [p.step] [q.Static] : (p >> q).step :=\n  Step.bind\n#align parser.step.and_then Parser.Step.andThen\n\ninstance and_then' {q : Parser \u03b2} [p.Static] [q.step] : (p >> q).step :=\n  Step.bind'\n#align parser.step.and_then' Parser.Step.and_then'\n\ninstance map [p.step] {f : \u03b1 \u2192 \u03b2} : (f <$> p).step :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [map_eq_done]\n    rintro \u27e8_, hp, _\u27e9\n    exact of_done hp\u27e9\n#align parser.step.map Parser.Step.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.step] [p.Static] : (f <*> p).step :=\n  Step.bind\n#align parser.step.seq Parser.Step.seq\n\ninstance seq' {f : Parser (\u03b1 \u2192 \u03b2)} [f.Static] [p.step] : (f <*> p).step :=\n  Step.bind'\n#align parser.step.seq' Parser.Step.seq'\n\ninstance mapM {f : \u03b1 \u2192 Parser \u03b2} [(f a).step] : ([a].mapM f).step :=\n  by\n  convert step.bind\n  \u00b7 infer_instance\n  \u00b7 intro\n    convert static.bind\n    \u00b7 exact static.pure\n    \u00b7 exact fun _ => static.pure\n#align parser.step.mmap Parser.Step.mapM\n\ninstance mapM' {f : \u03b1 \u2192 Parser \u03b2} [(f a).step] : ([a].mapM' f).step :=\n  by\n  convert step.and_then\n  \u00b7 infer_instance\n  \u00b7 exact static.pure\n#align parser.step.mmap' Parser.Step.mapM'\n\ninstance failure : @Parser.Step \u03b1 failure :=\n  \u27e8fun _ _ _ _ => by simp\u27e9\n#align parser.step.failure Parser.Step.failure\n\ntheorem guard_true : \u00acStep (guard True) :=\n  pure _\n#align parser.step.guard_true Parser.Step.guard_true\n\ninstance guard : Step (guard False) :=\n  Step.failure\n#align parser.step.guard Parser.Step.guard\n\ninstance orelse [p.step] [q.step] : (p <|> q).step :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [orelse_eq_done]\n    rintro (h | \u27e8h, -\u27e9) <;> exact of_done h\u27e9\n#align parser.step.orelse Parser.Step.orelse\n\ntheorem decorateErrors_iff : (@Parser.decorateErrors \u03b1 msgs p).step \u2194 p.step :=\n  by\n  constructor\n  \u00b7 intro\n    constructor\n    intro cb n n' a h\n    have : (@Parser.decorateErrors \u03b1 msgs p) cb n = done n' a := by simpa using h\n    exact of_done this\n  \u00b7 intro\n    constructor\n    intro _ _ _ _ h\n    rw [decorate_errors_eq_done] at h\n    exact of_done h\n#align parser.step.decorate_errors_iff Parser.Step.decorateErrors_iff\n\ninstance decorateErrors [p.step] : (@decorateErrors \u03b1 msgs p).step :=\n  \u27e8fun _ _ _ _ => by\n    rw [decorate_errors_eq_done]\n    exact of_done\u27e9\n#align parser.step.decorate_errors Parser.Step.decorateErrors\n\ntheorem decorateError_iff : (@Parser.decorateError \u03b1 msg p).step \u2194 p.step :=\n  decorateErrors_iff\n#align parser.step.decorate_error_iff Parser.Step.decorateError_iff\n\ninstance decorateError [p.step] : (@decorateError \u03b1 msg p).step :=\n  Step.decorateErrors\n#align parser.step.decorate_error Parser.Step.decorateError\n\ninstance anyChar : Step anyChar := by\n  constructor\n  intro cb n\n  simp_rw [any_char_eq_done]\n  rintro _ _ \u27e8_, rfl, -\u27e9\n  simp\n#align parser.step.any_char Parser.Step.anyChar\n\ninstance sat {p : Char \u2192 Prop} [DecidablePred p] : Step (sat p) :=\n  by\n  constructor\n  intro cb n\n  simp_rw [sat_eq_done]\n  rintro _ _ \u27e8_, _, rfl, -\u27e9\n  simp\n#align parser.step.sat Parser.Step.sat\n\ntheorem eps : \u00acStep eps :=\n  Step.pure ()\n#align parser.step.eps Parser.Step.eps\n\ninstance ch {c : Char} : Step (ch c) :=\n  Step.decorateError\n#align parser.step.ch Parser.Step.ch\n\ntheorem charBuf_iff {cb' : CharBuffer} : (charBuf cb').step \u2194 cb'.size = 1 :=\n  by\n  have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done]\n  constructor\n  \u00b7 intro\n    simpa using of_done this\n  \u00b7 intro h\n    constructor\n    intro cb n n' _\n    rw [char_buf_eq_done, h]\n    rintro \u27e8rfl, -\u27e9\n    rfl\n#align parser.step.char_buf_iff Parser.Step.charBuf_iff\n\ninstance oneOf {cs : List Char} : (oneOf cs).step :=\n  Step.decorateErrors\n#align parser.step.one_of Parser.Step.oneOf\n\ninstance oneOf' {cs : List Char} : (oneOf' cs).step :=\n  Step.andThen\n#align parser.step.one_of' Parser.Step.oneOf'\n\ntheorem str_iff {s : String} : (str s).step \u2194 s.length = 1 := by\n  simp [str_eq_char_buf, char_buf_iff, \u2190 String.toList_inj, Buffer.ext_iff]\n#align parser.step.str_iff Parser.Step.str_iff\n\ntheorem remaining : \u00acremaining.step :=\n  by\n  apply not_step_of_static_done\n  simp [remaining_eq_done]\n#align parser.step.remaining Parser.Step.remaining\n\ntheorem eof : \u00aceof.step := by\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\n#align parser.step.eof Parser.Step.eof\n\n-- TODO: add foldr and foldl, many, etc, fix_core\ntheorem fixCore {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.step \u2192 (F p).step) :\n    \u2200 max_depth : \u2115, Step (fixCore F max_depth)\n  | 0 => Step.failure\n  | max_depth + 1 => hF _ (fix_core _)\n#align parser.step.fix_core Parser.Step.fixCore\n\ninstance digit : digit.step :=\n  Step.decorateError\n#align parser.step.digit Parser.Step.digit\n\ntheorem fix {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.step \u2192 (F p).step) : Step (fix F) :=\n  \u27e8fun cb n _ _ h => by\n    haveI := fix_core hF (cb.size - n + 1)\n    dsimp [fix] at h\n    exact of_done h\u27e9\n#align parser.step.fix Parser.Step.fix\n\nend Step\n\nsection Step\n\nvariable {\u03b1 \u03b2 : Type} {p q : Parser \u03b1} {msgs : Thunk (List String)} {msg : Thunk String}\n  {cb : CharBuffer} {n' n : \u2115} {err : Dlist String} {a : \u03b1} {b : \u03b2} {sep : Parser Unit}\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 many1_eq_done_iff_many_eq_done [p.step] [p.Bounded] {x : \u03b1} {xs : List \u03b1} :\n    many1 p cb n = done n' (x::xs) \u2194 many p cb n = done n' (x::xs) :=\n  by\n  induction' hx : x::xs with hd tl IH generalizing x xs n n'\n  \u00b7 simpa using hx\n  constructor\n  \u00b7 simp only [many1_eq_done, and_imp, exists_imp]\n    intro 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 \u27e8k, hk\u27e9 : \u2203 k, cb.size - n = k + 1 :=\n      Nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn))\n    cases k\n    \u00b7\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    \u00b7 simpa [many_eq_done_nil, Nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm\n    \u00b7 rw [\u2190 @IH hd' tl'] at hm\n      swap\n      rfl\n      simp only [many1_eq_done, many, foldr] at hm\n      obtain \u27e8np, hp', hf\u27e9 := hm\n      obtain rfl : np = n + 1 + 1 := step.of_done hp'\n      simpa [Nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf\n  \u00b7 simp only [many_eq_done, many1_eq_done, and_imp, exists_imp]\n    intro 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 \u27e8k, hk\u27e9 : \u2203 k, cb.size - n = k + 1 :=\n      Nat.exists_eq_succ_of_ne_zero (ne_of_gt (tsub_pos_of_lt hn))\n    cases k\n    \u00b7\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    \u00b7 simpa [many_eq_done_nil, Nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm\n    \u00b7 simp [hp]\n      rw [\u2190 @IH hd' tl' (n + 1) n']\n      swap\n      rfl\n      rw [hk, foldr_core_eq_done, or_comm] at hm\n      obtain hm | \u27e8np, hd', tl', hp', hf, hm\u27e9 := hm\n      \u00b7 simpa using hm\n      simp only at hm\n      obtain \u27e8rfl, rfl\u27e9 := hm\n      obtain rfl : np = n + 1 + 1 := step.of_done hp'\n      simp [Nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', \u2190 hf, foldr]\n#align parser.many1_eq_done_iff_many_eq_done Parser.many1_eq_done_iff_many_eq_done\n\nend Step\n\nnamespace Prog\n\nvariable {\u03b1 \u03b2 : Type} {p q : Parser \u03b1} {msgs : Thunk (List String)} {msg : Thunk String}\n  {cb : CharBuffer} {n' n : \u2115} {err : Dlist String} {a : \u03b1} {b : \u03b2} {sep : Parser Unit}\n\n-- see Note [lower instance priority]\ninstance (priority := 100) of_step [Step p] : Prog p :=\n  \u27e8fun _ _ _ _ h => by\n    rw [step.of_done h]\n    exact Nat.lt_succ_self _\u27e9\n#align parser.prog.of_step Parser.Prog.of_step\n\ntheorem pure (a : \u03b1) : \u00acProg (pure a) := by\n  intro h\n  have : (pure a : Parser \u03b1) 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\n#align parser.prog.pure Parser.Prog.pure\n\ninstance bind {f : \u03b1 \u2192 Parser \u03b2} [p.Prog] [\u2200 a, (f a).mono] : (p >>= f).Prog :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [bind_eq_done]\n    rintro \u27e8_, _, hp, hf\u27e9\n    exact lt_of_lt_of_le (of_done hp) (mono.of_done hf)\u27e9\n#align parser.prog.bind Parser.Prog.bind\n\ninstance andThen {q : Parser \u03b2} [p.Prog] [q.mono] : (p >> q).Prog :=\n  Prog.bind\n#align parser.prog.and_then Parser.Prog.andThen\n\ninstance map [p.Prog] {f : \u03b1 \u2192 \u03b2} : (f <$> p).Prog :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [map_eq_done]\n    rintro \u27e8_, hp, _\u27e9\n    exact of_done hp\u27e9\n#align parser.prog.map Parser.Prog.map\n\ninstance seq {f : Parser (\u03b1 \u2192 \u03b2)} [f.Prog] [p.mono] : (f <*> p).Prog :=\n  Prog.bind\n#align parser.prog.seq Parser.Prog.seq\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [(f a).Prog] [\u2200 a, (f a).mono] :\n    ((a::l).mapM f).Prog := by\n  constructor\n  simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp, pure_eq_done]\n  rintro _ _ _ _ _ _ h _ _ hp rfl rfl\n  exact lt_of_lt_of_le (of_done h) (mono.of_done hp)\n#align parser.prog.mmap Parser.Prog.mapM\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ninstance mapM' {l : List \u03b1} {f : \u03b1 \u2192 Parser \u03b2} [(f a).Prog] [\u2200 a, (f a).mono] :\n    ((a::l).mapM' f).Prog := by\n  constructor\n  simp only [and_imp, bind_eq_done, mmap', exists_imp, and_then_eq_bind]\n  intro _ _ _ _ _ _ h hm\n  exact lt_of_lt_of_le (of_done h) (mono.of_done hm)\n#align parser.prog.mmap' Parser.Prog.mapM'\n\ninstance failure : @Parser.Prog \u03b1 failure :=\n  Prog.of_step\n#align parser.prog.failure Parser.Prog.failure\n\ntheorem guard_true : \u00acProg (guard True) :=\n  pure _\n#align parser.prog.guard_true Parser.Prog.guard_true\n\ninstance guard : Prog (guard False) :=\n  Prog.failure\n#align parser.prog.guard Parser.Prog.guard\n\ninstance orelse [p.Prog] [q.Prog] : (p <|> q).Prog :=\n  \u27e8fun _ _ _ _ => by\n    simp_rw [orelse_eq_done]\n    rintro (h | \u27e8h, -\u27e9) <;> exact of_done h\u27e9\n#align parser.prog.orelse Parser.Prog.orelse\n\ntheorem decorateErrors_iff : (@Parser.decorateErrors \u03b1 msgs p).Prog \u2194 p.Prog :=\n  by\n  constructor\n  \u00b7 intro\n    constructor\n    intro cb n n' a h\n    have : (@Parser.decorateErrors \u03b1 msgs p) cb n = done n' a := by simpa using h\n    exact of_done this\n  \u00b7 intro\n    constructor\n    intro _ _ _ _ h\n    rw [decorate_errors_eq_done] at h\n    exact of_done h\n#align parser.prog.decorate_errors_iff Parser.Prog.decorateErrors_iff\n\ninstance decorateErrors [p.Prog] : (@decorateErrors \u03b1 msgs p).Prog :=\n  \u27e8fun _ _ _ _ => by\n    rw [decorate_errors_eq_done]\n    exact of_done\u27e9\n#align parser.prog.decorate_errors Parser.Prog.decorateErrors\n\ntheorem decorateError_iff : (@Parser.decorateError \u03b1 msg p).Prog \u2194 p.Prog :=\n  decorateErrors_iff\n#align parser.prog.decorate_error_iff Parser.Prog.decorateError_iff\n\ninstance decorateError [p.Prog] : (@decorateError \u03b1 msg p).Prog :=\n  Prog.decorateErrors\n#align parser.prog.decorate_error Parser.Prog.decorateError\n\ninstance anyChar : Prog anyChar :=\n  Prog.of_step\n#align parser.prog.any_char Parser.Prog.anyChar\n\ninstance sat {p : Char \u2192 Prop} [DecidablePred p] : Prog (sat p) :=\n  Prog.of_step\n#align parser.prog.sat Parser.Prog.sat\n\ntheorem eps : \u00acProg eps :=\n  Prog.pure ()\n#align parser.prog.eps Parser.Prog.eps\n\ninstance ch {c : Char} : Prog (ch c) :=\n  Prog.of_step\n#align parser.prog.ch Parser.Prog.ch\n\ntheorem charBuf_iff {cb' : CharBuffer} : (charBuf cb').Prog \u2194 cb' \u2260 Buffer.nil :=\n  by\n  have : cb' \u2260 Buffer.nil \u2194 cb'.to_list \u2260 [] :=\n    not_congr \u27e8fun h => by simp [h], fun h => by simpa using congr_arg List.toBuffer h\u27e9\n  rw [char_buf, this, decorate_error_iff]\n  cases cb'.to_list\n  \u00b7 simp [pure]\n  \u00b7 simp only [iff_true_iff, Ne.def, not_false_iff]\n    infer_instance\n#align parser.prog.char_buf_iff Parser.Prog.charBuf_iff\n\ninstance oneOf {cs : List Char} : (oneOf cs).Prog :=\n  Prog.decorateErrors\n#align parser.prog.one_of Parser.Prog.oneOf\n\ninstance oneOf' {cs : List Char} : (oneOf' cs).Prog :=\n  Prog.andThen\n#align parser.prog.one_of' Parser.Prog.oneOf'\n\ntheorem str_iff {s : String} : (str s).Prog \u2194 s \u2260 \"\" := by\n  simp [str_eq_char_buf, char_buf_iff, \u2190 String.toList_inj, Buffer.ext_iff]\n#align parser.prog.str_iff Parser.Prog.str_iff\n\ntheorem remaining : \u00acremaining.Prog := by\n  intro 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\n#align parser.prog.remaining Parser.Prog.remaining\n\ntheorem eof : \u00aceof.Prog := by\n  intro 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\n#align parser.prog.eof Parser.Prog.eof\n\n-- TODO: add foldr and foldl, many, etc, fix_core\ninstance many1 [p.mono] [p.Prog] : p.many1.Prog :=\n  by\n  constructor\n  rintro cb n n' (_ | \u27e8hd, tl\u27e9)\n  \u00b7 simp\n  \u00b7 rw [many1_eq_done]\n    rintro \u27e8np, hp, h\u27e9\n    exact (of_done hp).trans_le (mono.of_done h)\n#align parser.prog.many1 Parser.Prog.many1\n\ntheorem fixCore {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.Prog \u2192 (F p).Prog) :\n    \u2200 max_depth : \u2115, Prog (fixCore F max_depth)\n  | 0 => Prog.failure\n  | max_depth + 1 => hF _ (fix_core _)\n#align parser.prog.fix_core Parser.Prog.fixCore\n\ninstance digit : digit.Prog :=\n  Prog.of_step\n#align parser.prog.digit Parser.Prog.digit\n\ninstance nat : nat.Prog :=\n  Prog.decorateError\n#align parser.prog.nat Parser.Prog.nat\n\ntheorem fix {F : Parser \u03b1 \u2192 Parser \u03b1} (hF : \u2200 p : Parser \u03b1, p.Prog \u2192 (F p).Prog) : Prog (fix F) :=\n  \u27e8fun cb n _ _ h => by\n    haveI := fix_core hF (cb.size - n + 1)\n    dsimp [fix] at h\n    exact of_done h\u27e9\n#align parser.prog.fix Parser.Prog.fix\n\nend Prog\n\nvariable {\u03b1 \u03b2 : Type} {msgs : Thunk (List String)} {msg : Thunk String}\n\nvariable {p q : Parser \u03b1} {cb : CharBuffer} {n n' : \u2115} {err : Dlist String}\n\nvariable {a : \u03b1} {b : \u03b2}\n\nsection Many\n\n-- TODO: generalize to p.prog instead of p.step\ntheorem many_sublist_of_done [p.step] [p.Bounded] {l : List \u03b1} (h : p.anyM cb n = done n' l) :\n    \u2200 k < n' - n, p.anyM cb (n + k) = done n' (l.drop k) :=\n  by\n  induction' l with hd tl hl generalizing n\n  \u00b7 rw [many_eq_done_nil] at h\n    simp [h.left]\n  intro m hm\n  cases m\n  \u00b7 exact h\n  rw [List.drop, Nat.add_succ, \u2190 Nat.succ_add]\n  apply hl\n  \u00b7 rw [\u2190 many1_eq_done_iff_many_eq_done, many1_eq_done] at h\n    obtain \u27e8_, hp, h\u27e9 := h\n    convert h\n    exact (step.of_done hp).symm\n  \u00b7 exact nat.lt_pred_iff.mpr hm\n#align parser.many_sublist_of_done Parser.many_sublist_of_done\n\ntheorem many_eq_nil_of_done [p.step] [p.Bounded] {l : List \u03b1} (h : p.anyM cb n = done n' l) :\n    p.anyM cb n' = done n' [] :=\n  by\n  induction' l with hd tl hl generalizing n\n  \u00b7 convert h\n    rw [many_eq_done_nil] at h\n    exact h.left.symm\n  \u00b7 rw [\u2190 many1_eq_done_iff_many_eq_done, many1_eq_done] at h\n    obtain \u27e8_, -, h\u27e9 := h\n    exact hl h\n#align parser.many_eq_nil_of_done Parser.many_eq_nil_of_done\n\ntheorem many_eq_nil_of_out_of_bound [p.Bounded] {l : List \u03b1} (h : p.anyM cb n = done n' l)\n    (hn : cb.size < n) : n' = n \u2227 l = [] := by\n  cases l\n  \u00b7 rw [many_eq_done_nil] at h\n    exact \u27e8h.left.symm, rfl\u27e9\n  \u00b7 rw [many_eq_done] at h\n    obtain \u27e8np, hp, -\u27e9 := h\n    exact absurd (bounded.of_done hp) hn.not_lt\n#align parser.many_eq_nil_of_out_of_bound Parser.many_eq_nil_of_out_of_bound\n\ntheorem many1_length_of_done [p.mono] [p.step] [p.Bounded] {l : List \u03b1}\n    (h : many1 p cb n = done n' l) : l.length = n' - n :=\n  by\n  induction' l with hd tl hl generalizing n n'\n  \u00b7 simpa using h\n  \u00b7 obtain \u27e8k, hk\u27e9 : \u2203 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 \u27e8_, hp, h\u27e9 := h\n    obtain rfl := step.of_done hp\n    cases tl\n    \u00b7 simp only [many_eq_done_nil, add_left_inj, exists_and_right, self_eq_add_right] at h\n      rcases h with \u27e8rfl, -\u27e9\n      simp\n    rw [\u2190 many1_eq_done_iff_many_eq_done] at h\n    specialize hl h\n    simp [hl, add_comm, add_assoc, Nat.sub_succ]\n#align parser.many1_length_of_done Parser.many1_length_of_done\n\ntheorem many1_bounded_of_done [p.step] [p.Bounded] {l : List \u03b1} (h : many1 p cb n = done n' l) :\n    n' \u2264 cb.size := by\n  induction' l with hd tl hl generalizing n n'\n  \u00b7 simpa using h\n  \u00b7 simp only [many1_eq_done] at h\n    obtain \u27e8np, hp, h\u27e9 := h\n    obtain rfl := step.of_done hp\n    cases tl\n    \u00b7 simp only [many_eq_done_nil, exists_and_right] at h\n      simpa [\u2190 h.left] using bounded.of_done hp\n    \u00b7 rw [\u2190 many1_eq_done_iff_many_eq_done] at h\n      exact hl h\n#align parser.many1_bounded_of_done Parser.many1_bounded_of_done\n\nend Many\n\nsection Nat\n\n/-- The `val : \u2115` 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-/\ntheorem nat_of_done {val : \u2115} (h : nat cb n = done n' val) :\n    val =\n      Nat.ofDigits 10\n        (((cb.toList.drop n).take (n' - n)).reverse.map fun c => c.toNat - '0'.toNat) :=\n  by\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 \u2115` using a helper function that keeps track of both the running sum an\n    and the magnitude so far, using a `(sum, magnitude) : (\u2115 \u00d7 \u2115)` 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 `\u2115 ), 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 = fun (d : \u2115) p => \u27e8p.1 + d * p.2, p.2 * 10\u27e9 :=\n    by\n    ext1\n    ext1 \u27e8\u27e9\n    rfl\n  -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (\u2115 \u00d7 \u2115)` with\n  -- the function above. We use this lemma later when we finish our inductive case.\n  have hpow :\n    \u2200 l,\n      (List.foldr (fun (digit : \u2115) (x : \u2115 \u00d7 \u2115) => (x.fst + digit * x.snd, x.snd * 10)) (0, 1)\n            l).snd =\n        10 ^ l.length :=\n    by\n    intro l\n    induction' l with hd tl hl\n    \u00b7 simp\n    \u00b7 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 \u27e8n', l, hp, rfl, rfl\u27e9 := 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 \u2115`. 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  \u00b7-- 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 : \u2115` is precisely the digit that is\n  -- represented by the character at position `n` in `cb : char_buffer`.\n  -- We will also prove the correspondence between the subsequent digits `ltl : list \u2115` and the\n  -- remaining characters past position `n` up to position `n'`.\n  cases' hx : List.drop n (Buffer.toList cb) with chd ctl\n  \u00b7 -- 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 \u2264 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'.toNat = lhd :=\n    by\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 \u27e8_, hp, -\u27e9 := hp\n    obtain rfl := step.of_done hp\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 `\u2115` 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_nthLe_toList, hx, Buffer.length_toList, true_and_iff,\n      add_left_inj, List.length, List.nthLe, eq_self_iff_true, exists_and_left, Fin.val_mk] at hp\n    rcases hp with \u27e8_, hn, rfl, _, _\u27e9\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 [\u2190 List.cons_nthLe_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 \u21a6 n + 1` holds\n  -- due to the `step` property of `parser.digit`.\n  -- We also get here `k : \u2115` 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 \u27e8k, hk\u27e9 : \u2203 k, n' = n + k + 1 := Nat.exists_eq_add_of_lt (prog.of_done hp)\n  have hdm : ltl = [] \u2228 digit.many1 cb (n + 1) = done n' ltl :=\n    by\n    cases ltl\n    \u00b7 simp\n    \u00b7 rw [many1_eq_done] at hp\n      obtain \u27e8_, hp, hp'\u27e9 := 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 \u2115` is equal to the RHS, which is that\n  -- the `val : \u2115` that `nat.of_digits` produces when supplied a `list \u2115 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  \u00b7 -- Case that `ltl = []`.\n    simp only [many1_eq_done, many_eq_done_nil, exists_and_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 \u27e8_, hp, rfl, hp'\u27e9 := hp\n    obtain rfl := step.of_done hp\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.toList cb)) = ctl.take k := by\n    simp [\u2190 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    by\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 [\u2190 this, \u2190 rearr, many1_length_of_done hdm]\n    -- Likewise, we rid ourselves of the `k` we generated earlier.\n    have : k = n' - n - 1 := by simp [hk, add_assoc]\n    subst this\n    simp only [Nat.sub_succ, add_comm, \u2190 Nat.pred_sub, Buffer.length_toList, Nat.pred_one_add,\n      min_eq_left_iff, List.length_drop, add_tsub_cancel_left, List.length_take, tsub_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 [tsub_le_tsub_iff_right, Nat.pred_le_iff]\n    \u00b7 -- We know that `n' \u2264 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      \u00b7 -- 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      \u00b7 simp\n    \u00b7-- Here, we use the same result as above, that `n < cb.size`, and relate it to\n      -- `n \u2264 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, \u2190 chdh, \u2190 ltll, hpow, add_assoc, Nat.ofDigits_append, mul_comm]\n#align parser.nat_of_done Parser.nat_of_done\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 : \u2115`, `n \u2264 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-/\ntheorem nat_of_done_as_digit {val : \u2115} (h : nat cb n = done n' val) :\n    \u2200 (hn : n' \u2264 cb.size) (k) (hk : k < n'),\n      n \u2264 k \u2192 '0' \u2264 cb.read \u27e8k, hk.trans_le hn\u27e9 \u2227 cb.read \u27e8k, hk.trans_le hn\u27e9 \u2264 '9' :=\n  by\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 \u2115` generated by\n  -- `parser.digit.many1`.\n  simp only [Nat, pure_eq_done, and_left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left,\n    exists_and_left] at h\n  obtain \u27e8xs, h, -\u27e9 := h\n  -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we\n  -- induct on the `xs : list \u2115` that `parser.digit.many1` produced.\n  induction' xs with hd tl hl generalizing n n'\n  \u00b7-- 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 \u2115`,\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 \u27e8_, hp, h\u27e9 := 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_iff, exists_eq_left,\n    eq_self_iff_true, exists_and_left, exists_and_left] at hp\n  obtain \u27e8rfl, -, hn, ge0, le9, rfl\u27e9 := hp\n  -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`.\n  intro hn k hk hk'\n  -- What if we are at `n`? What if we are past `n`? We case on the `n \u2264 k`.\n  rcases hk'.eq_or_lt with (rfl | hk')\n  \u00b7-- The `n = k` case. But this is exactly what we know already, so we provide the\n    -- relevant hypotheses.\n    exact \u27e8ge0, le9\u27e9\n  -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we\n  -- case on `tl : list \u2115`\n  cases tl\n  \u00b7 -- 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_right] at h\n    -- Extract out just the `n + 1 = n'`.\n    obtain \u27e8rfl, -\u27e9 := 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  \u00b7 -- Case where `tl \u2260 []`. 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 [\u2190 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 \u2264 k`, since we are now on the `n < k` case.\n    exact Nat.succ_le_of_lt hk'\n#align parser.nat_of_done_as_digit Parser.nat_of_done_as_digit\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-/\ntheorem nat_of_done_bounded {val : \u2115} (h : nat cb n = done n' val) :\n    \u2200 hn : n' < cb.size, '0' \u2264 cb.read \u27e8n', hn\u27e9 \u2192 '9' < cb.read \u27e8n', hn\u27e9 :=\n  by\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 \u2115` generated by\n  -- `parser.digit.many1`.\n  -- We deal with the case of `n'` is \"out-of-bounds\" right away by requiring that\n  -- `\u2200 (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, exists_eq_left,\n    exists_and_left] at h\n  obtain \u27e8xs, h, -\u27e9 := h\n  -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we\n  -- induct on the `xs : list \u2115` that `parser.digit.many1` produced.\n  induction' xs with hd tl hl generalizing n n'\n  \u00b7-- 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 \u27e8k, hk\u27e9 : \u2203 k, cb.size = n + k + 1 := Nat.exists_eq_add_of_lt (bounded.of_done h)\n  cases tl\n  \u00b7 -- 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_right, exists_eq_left] at\n      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 \u27e8-, _, h\u27e9 := 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_iff, exists_eq_left,\n      eq_self_iff_true, exists_and_left] at h\n    obtain \u27e8rfl, h\u27e9 | \u27e8h, -\u27e9 := h\n    \u00b7 -- 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    \u00b7-- 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 \u2264 n'`.\n      simpa using mono.of_fail h\n  \u00b7 -- Case where `tl \u2260 []`. 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 \u27e8_, -, h\u27e9 := h\n    rw [\u2190 many1_eq_done_iff_many_eq_done] at h\n    exact hl h\n#align parser.nat_of_done_bounded Parser.nat_of_done_bounded\n\n/- ./././Mathport/Syntax/Translate/Tactic/Lean3.lean:564:6: unsupported: specialize @hyp -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- The `val : \u2115` 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 `\u2115` value encoded\nby its decimal characters.\n-/\ntheorem nat_eq_done {val : \u2115} :\n    nat cb n = done n' val \u2194\n      \u2203 hn : n < n',\n        val =\n            Nat.ofDigits 10\n              (((cb.toList.drop n).take (n' - n)).reverse.map fun c => c.toNat - '0'.toNat) \u2227\n          (\u2200 hn' : n' < cb.size, '0' \u2264 cb.read \u27e8n', hn'\u27e9 \u2192 '9' < cb.read \u27e8n', hn'\u27e9) \u2227\n            \u2203 hn'' : n' \u2264 cb.size,\n              \u2200 (k) (hk : k < n'),\n                n \u2264 k \u2192 '0' \u2264 cb.read \u27e8k, hk.trans_le hn''\u27e9 \u2227 cb.read \u27e8k, hk.trans_le hn''\u27e9 \u2264 '9' :=\n  by\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' \u27e8fun h => \u27e8prog.of_done h, nat_of_done h, nat_of_done_bounded h, _\u27e9, _\u27e9\n  \u00b7 -- 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_left] at h\n    obtain \u27e8_, h, -\u27e9 := h\n    -- Now we get our existential witness that `n' \u2264 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 \u27e8h, nat_of_done_as_digit H h\u27e9\n  -- We now prove that given the `cb : char_buffer` with characters within the `n \u2264 k < n'` interval\n  -- properly \"numeric\" and such that their `nat.of_digits` generates the `val : \u2115`, `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 \u27e8hn, hv, hb, hn', ho\u27e9\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_left]\n  -- We won't actually need the `val : \u2115` 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 = fun (d : \u2115) p => \u27e8p.1 + d * p.2, p.2 * 10\u27e9 :=\n    by\n    ext1\n    ext1 \u27e8\u27e9\n    rfl\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  \u00b7 -- Base case: there are no characters at position `n` or onwards, which means that\n    -- `cb.size \u2264 n`. But this is a contradiction, since we have `n < n' \u2264 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  \u00b7 -- 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 [\u2190\n      List.cons_nthLe_drop_succ (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 `\u2115` 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'.toNat) :=\n      by\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_rfl\n      -- We prove an additional result that the conversion of `hd : char` to a `\u2115` would give a\n      -- value `x \u2264 9`, since that is part of the iff statement in the `digit_eq_done` lemma.\n      have : (Buffer.read cb \u27e8n, hn.trans_le hn'\u27e9).toNat - '0'.toNat \u2264 9 :=\n        by\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' \u2264 '9'`, which\n        -- is true by computation, handled by `dec_trivial`.\n        rw [show 9 = '9'.toNat - '0'.toNat by decide, tsub_le_tsub_iff_right]\n        \u00b7 exact ho.right\n        \u00b7 decide\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, \u2190 H.left, Buffer.nthLe_toList, 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 \u2264 n + 1`. The more difficult goal comes first.\n    cases' lt_or_ge (n + 1) n' with hn'' hn''\n    \u00b7 -- 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 \u2264 k < n'` are \"numeric\". We already had this for `n \u2264 k < n`, so we just rearrange\n      -- the hypotheses we already have.\n      specialize IH hn'' _ H.right\n      \u00b7 intro 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 \u27e8l, hdl, hvl\u27e9 := 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'.toNat)::l\n      -- We case on `l : list \u2115` so that we can make statements about the fold on `l`\n      cases' l with lhd ltl\n      \u00b7-- 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,\n        true_and_iff, and_true_iff, 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 \u27e8m, rfl\u27e9 : \u2203 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        by\n        rw [add_assoc, tsub_eq_iff_eq_add_of_le, 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 (\u2115 \u00d7 \u2115)`\n      -- with the function above. We use this lemma to finish our inductive case.\n      have hpow :\n        \u2200 l,\n          (List.foldr (fun (digit : \u2115) (x : \u2115 \u00d7 \u2115) => (x.fst + digit * x.snd, x.snd * 10)) (0, 1)\n                l).snd =\n            10 ^ l.length :=\n        by\n        intro l\n        induction' l with hd tl hl\n        \u00b7 simp\n        \u00b7 simp [hl, pow_succ, mul_comm]\n      -- We prove that the parsed list of digits `(lhd :: ltl) : list \u2115` 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 \u2264 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        by-- On the way to proving this, we have to actually show that `m \u2264 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 \u2264 cb.size`, we have that `tl` must be at least `m` in length.\n        simpa [\u2190 H.right, le_tsub_iff_right (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 `\u2190pow_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.ofDigits_append, mul_comm, \u2190 pow_succ 10, hml, ltll]\n    \u00b7 -- Consider the case that `n' \u2264 n + 1`. But then since `n < n' \u2264 n + 1`, `n' = n + 1`.\n      obtain rfl : n' = n + 1 := le_antisymm hn'' (Nat.succ_le_of_lt hn)\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'.toNat]\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_iff, mul_one, Nat.ofDigits_singleton, List.take, exists_eq_left,\n        exists_and_right, add_tsub_cancel_left, eq_self_iff_true, List.reverse_singleton, zero_add,\n        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' \u27e8_, Or.inl \u27e8rfl, _\u27e9\u27e9\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\n#align parser.nat_eq_done Parser.nat_eq_done\n\nend Nat\n\nend Parser\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/Parser/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101676450173534, "lm_q2_score": 0.09670579980448575, "lm_q1q2_score": 0.04458299493441657}}
{"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 \u03b1` is the type that describes a computation that can ingest a `char_buffer`\nand output, if successful, a term of type `\u03b1`.\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 \u03b1` 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 \u03b1`, 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 {\u03b1} : parse_result \u03b1 \u2192 \u2115\n| (done n _) := n\n| (fail n _) := n\n\nnamespace parser\n\nsection defn_lemmas\n\nvariables {\u03b1 \u03b2 : Type} (msgs : thunk (list string)) (msg : thunk string)\nvariables (p q : parser \u03b1) (cb : char_buffer) (n n' : \u2115) {err : dlist string}\nvariables {a : \u03b1} {b : \u03b2}\n\n/--\nA `p : parser \u03b1` is defined to be `mono` if the result `p cb n` it gives,\nfor some `cb : char_buffer` and `n : \u2115`, (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' : \u2200 (cb : char_buffer) (n : \u2115), n \u2264 (p cb n).pos)\n\nlemma mono.le [p.mono] : n \u2264 (p cb n).pos := mono.le' cb n\n\n/--\nA `parser \u03b1` is defined to be `static` if it does not move on success.\n-/\nclass static : Prop :=\n(of_done : \u2200 {cb : char_buffer} {n n' : \u2115} {a : \u03b1}, p cb n = done n' a \u2192 n = n')\n\n/--\nA `parser \u03b1` is defined to be `err_static` if it does not move on error.\n-/\nclass err_static : Prop :=\n(of_fail : \u2200 {cb : char_buffer} {n n' : \u2115} {err : dlist string}, p cb n = fail n' err \u2192 n = n')\n\n/--\nA `parser \u03b1` is defined to be `step` if it always moves exactly one char forward on success.\n-/\nclass step : Prop :=\n(of_done : \u2200 {cb : char_buffer} {n n' : \u2115} {a : \u03b1}, p cb n = done n' a \u2192 n' = n + 1)\n\n/--\nA `parser \u03b1` is defined to be `prog` if it always moves forward on success.\n-/\nclass prog : Prop :=\n(of_done : \u2200 {cb : char_buffer} {n n' : \u2115} {a : \u03b1}, p cb n = done n' a \u2192 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' : \u2200 {cb : char_buffer} {n : \u2115}, cb.size \u2264 n \u2192 \u2203 (n' : \u2115) (err : dlist string),\n  p cb n = fail n' err)\n\nlemma bounded.exists (p : parser \u03b1) [p.bounded] {cb : char_buffer} {n : \u2115} (h : cb.size \u2264 n) :\n  \u2203 (n' : \u2115) (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' : \u2200 (cb : char_buffer) (n : \u2115), \u2203 (n' : \u2115) (a : \u03b1), 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' : \u2200 {cb : char_buffer} {n : \u2115}, n < cb.size \u2192 \u2203 (n' : \u2115) (a : \u03b1), p cb n = done n' a)\n\nlemma fail_iff :\n  (\u2200 pos' result, p cb n \u2260 done pos' result) \u2194\n    \u2203 (pos' : \u2115) (err : dlist string), p cb n = fail pos' err :=\nby cases p cb n; simp\n\nlemma success_iff :\n  (\u2200 pos' err, p cb n \u2260 fail pos' err) \u2194 \u2203 (pos' : \u2115) (result : \u03b1), 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 \u2264 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 \u2264 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 \u27e8np, err, hp\u27e9 := bounded.exists p h,\n  simp [hp]\nend\n\nlemma static.iff :\n  static p \u2194 (\u2200 (cb : char_buffer) (n n' : \u2115) (a : \u03b1), p cb n = done n' a \u2192 n = n') :=\n\u27e8\u03bb h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, \u03bb h, \u27e8h\u27e9\u27e9\n\nlemma exists_done (p : parser \u03b1) [p.unfailing] (cb : char_buffer) (n : \u2115) :\n  \u2203 (n' : \u2115) (a : \u03b1), 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 \u27e8np, a, hp\u27e9 := 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\u27e8\u03bb _ _ _, p.exists_done _ _\u27e9\n\nlemma exists_done_in_bounds (p : parser \u03b1) [p.conditionally_unfailing] {cb : char_buffer} {n : \u2115}\n  (h : n < cb.size) : \u2203 (n' : \u2115) (a : \u03b1), 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 \u27e8np, a, hp\u27e9 := 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 \u03b1 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 \u03b1 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 \u03b1 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 \u03b1 msg p cb n = done n' a :=\ndecorate_errors_success h\n\n@[simp] lemma decorate_errors_eq_done :\n  @decorate_errors \u03b1 msgs p cb n = done n' a \u2194 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 \u03b1 msg p cb n = done n' a \u2194 p cb n = done n' a :=\ndecorate_errors_eq_done\n\n@[simp] lemma decorate_errors_eq_fail :\n  @decorate_errors \u03b1 msgs p cb n = fail n' err \u2194\n    n = n' \u2227 err = dlist.lazy_of_list (msgs ()) \u2227 \u2203 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 \u03b1 msg p cb n = fail n' err \u2194\n    n = n' \u2227 err = dlist.lazy_of_list ([msg ()]) \u2227 \u2203 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) = \u03bb _ n, done n a := rfl\n\n@[simp] lemma pure_ne_fail : (pure a : parser \u03b1) cb n \u2260 fail n' err := by simp [pure_eq_done]\n\nsection bind\n\nvariable (f : \u03b1 \u2192 parser \u03b2)\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 \u2194\n  \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 f a cb np = done n' b :=\nby cases hp : p cb n; simp [hp, \u2190bind_eq_bind, parser.bind, and_assoc]\n\n@[simp] lemma bind_eq_fail :\n  (p >>= f) cb n = fail n' err \u2194\n  (p cb n = fail n' err) \u2228 (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 f a cb np = fail n' err) :=\nby cases hp : p cb n; simp [hp, \u2190bind_eq_bind, parser.bind, and_assoc]\n\n@[simp] lemma and_then_eq_bind {\u03b1 \u03b2 : Type} {m : Type \u2192 Type} [monad m] (a : m \u03b1) (b : m \u03b2) :\n  a >> b = a >>= (\u03bb _, b) := rfl\n\nlemma and_then_fail :\n  (p >> return ()) cb n = parse_result.fail n' err \u2194 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' () \u2194 \u2203 a, p cb n = done n' a:=\nby simp [pure_eq_done]\n\nend bind\n\nsection map\n\nvariable {f : \u03b1 \u2192 \u03b2}\n\n@[simp] lemma map_eq_done : (f <$> p) cb n = done n' b \u2194\n  \u2203 (a : \u03b1), p cb n = done n' a \u2227 f a = b :=\nby cases hp : p cb n; simp [\u2190is_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 \u2194 p cb n = fail n' err :=\nby simp [\u2190bind_pure_comp_eq_map, pure_eq_done]\n\n@[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' \u2194\n  \u2203 (a : \u03b1), p cb n = done n' a \u2227 b = b' :=\nby simp [map_const_eq]\n\n@[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err \u2194 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' \u2194\n  \u2203 (a : \u03b1), p cb n = done n' a \u2227 b = b' :=\nmap_const_eq_done\n\nlemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err \u2194 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 \u2194\n  (p cb n = done n' a \u2228 (q cb n = done n' a \u2227 \u2203 err, p cb n = fail n err)) :=\nbegin\n  cases hp : p cb n with np resp np errp,\n  { simp [hp, \u2190orelse_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, \u2190orelse_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, \u2190orelse_eq_orelse, parser.orelse] <|>\n          simp [hp, hn, hq, lt_irrefl, \u2190orelse_eq_orelse, parser.orelse] } },\n    { simp [hp, hn, \u2190orelse_eq_orelse, parser.orelse] } }\nend\n\n@[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err \u2194\n  (p cb n = fail n err \u2227 \u2203 (nq errq), n < nq \u2227 q cb n = fail nq errq) \u2228\n  (\u2203 (errp errq), p cb n = fail n errp \u2227 q cb n = fail n errq \u2227 errp ++ errq = err)\n :=\nbegin\n  cases hp : p cb n with np resp np errp,\n  { simp [hp, \u2190orelse_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, \u2190orelse_eq_orelse, parser.orelse] },\n      { rcases lt_trichotomy nq n with H|rfl|H;\n        simp [hp, hq, hn, \u2190orelse_eq_orelse, parser.orelse, H,\n              ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|>\n          simp [hp, hq, hn, \u2190orelse_eq_orelse, parser.orelse, lt_irrefl] } },\n    { simp [hp, hn, \u2190orelse_eq_orelse, parser.orelse] } }\nend\n\nlemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err \u2194\n  (p cb n = fail n' err) \u2228\n  (q cb n = fail n' err \u2227 (\u2203 (errp), p cb n = fail n errp)) :=\nbegin\n  cases hp : p cb n with np resp np errp,\n  { simp [hp, \u2190orelse_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, \u2190orelse_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, \u2190orelse_eq_orelse, parser.orelse] },\n        { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, \u2190orelse_eq_orelse, parser.orelse] },\n        { simp [hp, hq, h, H, ne_of_gt (hn.trans H), \u2190orelse_eq_orelse, parser.orelse] } } },\n    { simp [hp, h, \u2190orelse_eq_orelse, parser.orelse] } }\nend\n\nlemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n \u2260 n') :\n  (p <|> q) cb n = fail n' err \u2194 p cb n = fail n' err :=\nbegin\n  cases hp : p cb n with np resp np errp,\n  { simp [hp, \u2190orelse_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, \u2190orelse_eq_orelse, parser.orelse] },\n      { have : n \u2264 nq := mono.of_fail hq,\n        rcases eq_or_lt_of_le this with rfl|H,\n        { simp [hp, hq, h, hn, lt_irrefl, \u2190orelse_eq_orelse, parser.orelse] },\n        { simp [hp, hq, h, hn, H, \u2190orelse_eq_orelse, parser.orelse] } } },\n    { simp [hp, h, \u2190orelse_eq_orelse, parser.orelse] } },\nend\n\n@[simp] lemma failure_eq_failure : @parser.failure \u03b1 = failure := rfl\n\n@[simp] lemma failure_def : (failure : parser \u03b1) cb n = fail n dlist.empty := rfl\n\nlemma not_failure_eq_done : \u00ac (failure : parser \u03b1) cb n = done n' a :=\nby simp\n\nlemma failure_eq_fail : (failure : parser \u03b1) cb n = fail n' err \u2194 n = n' \u2227 err = dlist.empty :=\nby simp [eq_comm]\n\nlemma seq_eq_done {f : parser (\u03b1 \u2192 \u03b2)} {p : parser \u03b1} : (f <*> p) cb n = done n' b \u2194\n  \u2203 (nf : \u2115) (f' : \u03b1 \u2192 \u03b2) (a : \u03b1), f cb n = done nf f' \u2227 p cb nf = done n' a \u2227 f' a = b :=\nby simp [seq_eq_bind_map]\n\nlemma seq_eq_fail {f : parser (\u03b1 \u2192 \u03b2)} {p : parser \u03b1} : (f <*> p) cb n = fail n' err \u2194\n  (f cb n = fail n' err) \u2228 (\u2203 (nf : \u2115) (f' : \u03b1 \u2192 \u03b2), f cb n = done nf f' \u2227 p cb nf = fail n' err) :=\nby simp [seq_eq_bind_map]\n\nlemma seq_left_eq_done {p : parser \u03b1} {q : parser \u03b2} : (p <* q) cb n = done n' a \u2194\n  \u2203 (np : \u2115) (b : \u03b2), p cb n = done np a \u2227 q cb np = done n' b :=\nbegin\n  have : \u2200 (p q : \u2115 \u2192 \u03b1 \u2192 Prop),\n    (\u2203 (np : \u2115) (x : \u03b1), p np x \u2227 q np x \u2227 x = a) \u2194 \u2203 (np : \u2115), p np a \u2227 q np a :=\n    \u03bb _ _, \u27e8\u03bb \u27e8np, x, hp, hq, rfl\u27e9, \u27e8np, hp, hq\u27e9, \u03bb \u27e8np, hp, hq\u27e9, \u27e8np, a, hp, hq, rfl\u27e9\u27e9,\n  simp [seq_left_eq, seq_eq_done, map_eq_done, this]\nend\n\nlemma seq_left_eq_fail {p : parser \u03b1} {q : parser \u03b2} : (p <* q) cb n = fail n' err \u2194\n  (p cb n = fail n' err) \u2228 (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 q cb np = fail n' err) :=\nby simp [seq_left_eq, seq_eq_fail]\n\nlemma seq_right_eq_done {p : parser \u03b1} {q : parser \u03b2} : (p *> q) cb n = done n' b \u2194\n  \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 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 \u03b1} {q : parser \u03b2} : (p *> q) cb n = fail n' err \u2194\n  (p cb n = fail n' err) \u2228 (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 q cb np = fail n' err) :=\nby simp [seq_right_eq, seq_eq_fail]\n\nlemma mmap_eq_done {f : \u03b1 \u2192 parser \u03b2} {a : \u03b1} {l : list \u03b1} {b : \u03b2} {l' : list \u03b2} :\n  (a :: l).mmap f cb n = done n' (b :: l') \u2194\n  \u2203 (np : \u2115), f a cb n = done np b \u2227 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 : \u03b1 \u2192 parser \u03b2} {a : \u03b1} {l : list \u03b1} :\n  (a :: l).mmap' f cb n = done n' () \u2194\n  \u2203 (np : \u2115) (b : \u03b2), f a cb n = done np b \u2227 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 \u2194 p \u2227 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 \u2194 (\u00ac p) \u2227 n = n' \u2227 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\u27e8\u03bb _ _, by simp [pure_eq_done]\u27e9\n\ninstance bind {f : \u03b1 \u2192 parser \u03b2} [p.mono] [\u2200 a, (f a).mono] :\n  (p >>= f).mono :=\nbegin\n  constructor,\n  intros cb n,\n  cases hx : (p >>= f) cb n,\n  { obtain \u27e8n', a, h, h'\u27e9 := bind_eq_done.mp hx,\n    refine le_trans (of_done h) _,\n    simpa [h'] using of_done h' },\n  { obtain h | \u27e8n', a, h, h'\u27e9 := 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 \u03b2} [p.mono] [q.mono] : (p >> q).mono := mono.bind\n\ninstance map [p.mono] {f : \u03b1 \u2192 \u03b2} : (f <$> p).mono := mono.bind\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind\n\ninstance mmap : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 a \u2208 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 (\u03bb _ ha, h _ (list.mem_cons_of_mem _ ha)) }\nend\n\ninstance mmap' : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 a \u2208 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 (\u03bb _ ha, h _ (list.mem_cons_of_mem _ ha)) }\nend\n\ninstance failure : (failure : parser \u03b1).mono :=\n\u27e8by simp [le_refl]\u27e9\n\ninstance guard {p : Prop} [decidable p] : mono (guard p) :=\n\u27e8by { by_cases h : p; simp [h, pure_eq_done, le_refl] }\u27e9\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 | \u27e8h, -, -\u27e9 := 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 \u03b1 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 \u03b1 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 \u2192 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\u27e8\u03bb _ _, le_refl _\u27e9\n\ninstance eof : eof.mono :=\nmono.decorate_error\n\ninstance foldr_core {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} [p.mono] :\n  \u2200 {reps : \u2115}, (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 \u03bb _, @mono.bind _ _ _ _ foldr_core _ } },\n  { exact mono.pure }\nend\n\ninstance foldr {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} [p.mono] : mono (foldr f p b) :=\n\u27e8\u03bb _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }\u27e9\n\ninstance foldl_core {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} [p.mono] :\n  \u2200 {a : \u03b1} {reps : \u2115}, (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 \u03bb _, foldl_core } },\n  { exact mono.pure }\nend\n\ninstance foldl {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} [p.mono] : mono (foldl f a p) :=\n\u27e8\u03bb _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }\u27e9\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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.mono \u2192 (F p).mono) :\n  \u2200 (max_depth : \u2115), 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.mono \u2192 (F p).mono) :\n  mono (fix F) :=\n\u27e8\u03bb _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }\u27e9\n\nend mono\n\n@[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err \u2194\n  p cb n = fail n' err \u2227 n \u2260 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 {\u03b1 \u03b2 : Type} {cb : char_buffer} {n n' : \u2115} {a a' : \u03b1} {b : \u03b2} {c : char} {u : unit}\n  {err : dlist string}\n\nlemma any_char_eq_done : any_char cb n = done n' c \u2194\n  \u2203 (hn : n < cb.size), n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = 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 \u2194 n = n' \u2227 err = dlist.empty \u2227 cb.size \u2264 n :=\nbegin\n  simp_rw [any_char],\n  split_ifs with h;\n  simp [\u2190not_lt, h, eq_comm]\nend\n\nlemma sat_eq_done {p : char \u2192 Prop} [decidable_pred p] : sat p cb n = done n' c \u2194\n  \u2203 (hn : n < cb.size), p c \u2227 n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = c :=\nbegin\n  by_cases hn : n < cb.size,\n  { by_cases hp : p (cb.read \u27e8n, hn\u27e9),\n    { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true],\n      split,\n      { rintro \u27e8rfl, rfl\u27e9, simp [hp] },\n      { rintro \u27e8-, rfl, rfl\u27e9, 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 \u2192 Prop} [decidable_pred p] : sat p cb n = fail n' err \u2194\n  n = n' \u2227 err = dlist.empty \u2227 \u2200 (h : n < cb.size), \u00ac p (cb.read \u27e8n, h\u27e9) :=\nbegin\n  dsimp only [sat],\n  split_ifs;\n  simp [*, eq_comm]\nend\n\nlemma eps_eq_done : eps cb n = done n' u \u2194 n = n' := by simp [eps, pure_eq_done]\n\nlemma ch_eq_done : ch c cb n = done n' u \u2194 \u2203 (hn : n < cb.size), n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = 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 \u2194\n  n + cb'.size = n' \u2227 cb'.to_list <+: (cb.to_list.drop n) :=\nbegin\n  simp only [char_buf, decorate_error_eq_done, ne.def, \u2190buffer.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 \u27e8np, h, rfl, rfl, hn, rfl\u27e9,\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 [\u2190buffer.nth_le_to_list _ this, \u2190list.cons_nth_le_drop_succ this, list.prefix_cons_inj] },\n    { rintro \u27e8h, rfl\u27e9,\n      by_cases hn : n < cb.size,\n      { have : n < cb.to_list.length := by simpa using hn,\n        rw [\u2190list.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 \u2264 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 \u2194\n  \u2203 (hn : n < cb.size), c \u2208 cs \u2227 n' = n + 1 \u2227 cb.read \u27e8n, hn\u27e9 = 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 \u2194\n  \u2203 (hn : n < cb.size), cb.read \u27e8n, hn\u27e9 \u2208 cs \u2227 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 \u27e8c, hc, rfl, hn, rfl\u27e9,\n    exact \u27e8rfl, hn, hc\u27e9 },\n  { rintro \u27e8rfl, hn, hc\u27e9,\n    exact \u27e8cb.read \u27e8n, hn\u27e9, hc, rfl, hn, rfl\u27e9 }\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 \u2194\n  n + s.length = n' \u2227 s.to_list <+: (cb.to_list.drop n) :=\nby simp [str_eq_char_buf, char_buf_eq_done]\n\nlemma remaining_eq_done {r : \u2115} : remaining cb n = done n' r \u2194 n = n' \u2227 cb.size - n = r :=\nby simp [remaining]\n\nlemma remaining_ne_fail : remaining cb n \u2260 fail n' err :=\nby simp [remaining]\n\nlemma eof_eq_done {u : unit} : eof cb n = done n' u \u2194 n = n' \u2227 cb.size \u2264 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n  foldr_core f p b 0 cb n \u2260 done n' b' :=\nby simp [foldr_core]\n\nlemma foldr_core_eq_done {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {b' : \u03b2} :\n  foldr_core f p b (reps + 1) cb n = done n' b' \u2194\n  (\u2203 (np : \u2115) (a : \u03b1) (xs : \u03b2), p cb n = done np a \u2227 foldr_core f p b reps cb np = done n' xs\n    \u2227 f a xs = b') \u2228\n  (n = n' \u2227 b = b' \u2227 \u2203 (err), (p cb n = fail n err) \u2228\n    (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n  foldr_core f p b 0 cb n = fail n' err \u2194 n = n' \u2227 err = dlist.empty :=\nby simp [foldr_core, eq_comm]\n\nlemma foldr_core_succ_eq_fail {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {err : dlist string} :\n  foldr_core f p b (reps + 1) cb n = fail n' err \u2194 n \u2260 n' \u2227\n  (p cb n = fail n' err \u2228\n    \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 foldr_core f p b reps cb np = fail n' err) :=\nby simp [foldr_core, and_comm]\n\nlemma foldr_eq_done {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n  foldr f p b cb n = done n' b' \u2194\n  ((\u2203 (np : \u2115) (a : \u03b1) (x : \u03b2), p cb n = done np a \u2227\n    foldr_core f p b (cb.size - n) cb np = done n' x \u2227 f a x = b') \u2228\n  (n = n' \u2227 b = b' \u2227 (\u2203 (err), p cb n = parse_result.fail n err \u2228\n    \u2203 (np : \u2115) (x : \u03b1), p cb n = done np x \u2227 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string}\n  [p.mono] (hc : cb.size \u2264 n) : foldr f p b cb n = fail n' err \u2194\n    n < n' \u2227 (p cb n = fail n' err \u2228 \u2203 (a : \u03b1), p cb n = done n' a \u2227 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 | \u27e8\u27e8a, h\u27e9, rfl\u27e9),\n  { exact mono.of_fail h },\n  { exact mono.of_done h }\nend\n\nlemma foldr_eq_fail {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n  foldr f p b cb n = fail n' err \u2194 n \u2260 n' \u2227 (p cb n = fail n' err \u2228\n    \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 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 : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n  foldl_core f b p 0 cb n = done n' b' \u2194 false :=\nby simp [foldl_core]\n\nlemma foldl_core_eq_done {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {b' : \u03b2} :\n  foldl_core f b p (reps + 1) cb n = done n' b' \u2194\n  (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 foldl_core f (f b a) p reps cb np = done n' b') \u2228\n  (n = n' \u2227 b = b' \u2227 \u2203 (err), (p cb n = fail n err) \u2228\n    (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 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 : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n  foldl_core f b p 0 cb n = fail n' err \u2194 n = n' \u2227 err = dlist.empty :=\nby simp [foldl_core, eq_comm]\n\nlemma foldl_core_succ_eq_fail {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {err : dlist string} :\n  foldl_core f b p (reps + 1) cb n = fail n' err \u2194 n \u2260 n' \u2227\n  (p cb n = fail n' err \u2228\n    \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227 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 : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n  foldl f b p cb n = done n' b' \u2194\n  (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227\n    foldl_core f (f b a) p (cb.size - n) cb np = done n' b') \u2228\n  (n = n' \u2227 b = b' \u2227 \u2203 (err), (p cb n = fail n err) \u2228\n    (\u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227\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 : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n  foldl f b p cb n = fail n' err \u2194 n \u2260 n' \u2227 (p cb n = fail n' err \u2228\n    \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227\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 : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string}\n  [p.mono] (hc : cb.size \u2264 n) : foldl f b p cb n = fail n' err \u2194\n    n < n' \u2227 (p cb n = fail n' err \u2228 \u2203 (a : \u03b1), p cb n = done n' a \u2227 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 | \u27e8\u27e8a, h\u27e9, rfl\u27e9),\n  { exact mono.of_fail h },\n  { exact mono.of_done h }\nend\n\nlemma many_eq_done_nil {p : parser \u03b1} : many p cb n = done n' (@list.nil \u03b1) \u2194 n = n' \u2227\n  \u2203 (err), p cb n = fail n err \u2228 \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227\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 \u03b1} {x : \u03b1} {xs : list \u03b1} :\n  many p cb n = done n' (x :: xs) \u2194 \u2203 (np : \u2115), p cb n = done np x\n    \u2227 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 \u03b1} {err : dlist string} :\n  many p cb n = fail n' err \u2194 n \u2260 n' \u2227 (p cb n = fail n' err \u2228\n    \u2203 (np : \u2115) (a : \u03b1), p cb n = done np a \u2227\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 \u2194 n = n' \u2227\n  \u2203 (err), p cb n = fail n err \u2228 \u2203 (np : \u2115) (c : char), p cb n = done np c \u2227\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 \u2260 \"\") :\n  many_char p cb n = done n' s \u2194 \u2203 (np : \u2115), p cb n = done np s.head \u2227\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 \u2194 many p cb n = done n' s.to_list :=\nby simp [many_char, list.as_string_eq]\n\nlemma many'_eq_done {p : parser \u03b1} : many' p cb n = done n' u \u2194\n  many p cb n = done n' [] \u2228 \u2203 (np : \u2115) (a : \u03b1) (l : list \u03b1), many p cb n = done n' (a :: l)\n    \u2227 p cb n = done np a \u2227 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 \u27e8_ | \u27e8hd, tl\u27e9, hl\u27e9,\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 \u27e8np, hp, h\u27e9 := hl,\n      refine or.inr \u27e8np, _, _, hl2, hp, h\u27e9 } },\n  { rintro (h | \u27e8np, a, l, hp, h\u27e9),\n    { exact \u27e8[], h\u27e9 },\n    { refine \u27e8a :: l, hp\u27e9 } }\nend\n\n@[simp] lemma many1_ne_done_nil {p : parser \u03b1} : many1 p cb n \u2260 done n' [] :=\nby simp [many1, seq_eq_done]\n\nlemma many1_eq_done {p : parser \u03b1} {l : list \u03b1} : many1 p cb n = done n' (a :: l) \u2194\n  \u2203 (np : \u2115), p cb n = done np a \u2227 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 \u2260 done n' \"\" :=\nby simp [many_char1, \u2190string.nil_as_string_eq_empty]\n\nlemma many_char1_eq_done {p : parser char} {s : string} (h : s \u2260 \"\") :\n  many_char1 p cb n = done n' s \u2194\n  \u2203 (np : \u2115), p cb n = done np s.head \u2227 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 \u03b1} :\n  sep_by1 sep p cb n \u2260 done n' [] :=\nby simp [sep_by1, seq_eq_done]\n\nlemma sep_by1_eq_done {sep : parser unit} {p : parser \u03b1} {l : list \u03b1} :\n  sep_by1 sep p cb n = done n' (a :: l) \u2194 \u2203 (np : \u2115), p cb n = done np a \u2227\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 \u03b1} :\n  sep_by sep p cb n = done n' [] \u2194 n = n' \u2227 \u2203 (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 \u03b1 \u2192 parser \u03b1} :\n  fix_core F 0 cb n \u2260 done n' a :=\nby simp [fix_core]\n\nlemma fix_core_eq_done {F : parser \u03b1 \u2192 parser \u03b1} {max_depth : \u2115} :\n  fix_core F (max_depth + 1) cb n = done n' a \u2194 F (fix_core F max_depth) cb n = done n' a :=\nby simp [fix_core]\n\nlemma digit_eq_done {k : \u2115} : digit cb n = done n' k \u2194 \u2203 (hn : n < cb.size), n' = n + 1 \u2227 k \u2264 9 \u2227\n  (cb.read \u27e8n, hn\u27e9).to_nat - '0'.to_nat = k \u2227 '0' \u2264 cb.read \u27e8n, hn\u27e9 \u2227 cb.read \u27e8n, hn\u27e9 \u2264 '9' :=\nbegin\n  have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl,\n  have l09 : '0'.to_nat \u2264 '9'.to_nat := dec_trivial,\n  have le_iff_le : \u2200 {c c' : char}, c \u2264 c' \u2194 c.to_nat \u2264 c'.to_nat := \u03bb _ _, iff.rfl,\n  split,\n  { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, \u2190c9],\n    rintro \u27e8np, c, \u27e8hn, \u27e8ge0, le9\u27e9, rfl, rfl\u27e9, rfl, rfl\u27e9,\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, \u2190c9,\n               le_iff_le],\n    rintro \u27e8hn, rfl, -, rfl, ge0, le9\u27e9,\n    use [n + 1, cb.read \u27e8n, hn\u27e9],\n    simp [hn, ge0, le9] }\nend\n\nlemma digit_eq_fail : digit cb n = fail n' err \u2194 n = n' \u2227 err = dlist.of_list [\"<digit>\"] \u2227\n  \u2200 (h : n < cb.size), \u00ac ((\u03bb c, '0' \u2264 c \u2227 c \u2264 '9') (cb.read \u27e8n, h\u27e9)) :=\nby simp [digit, sat_eq_fail]\n\n\nend done\n\nnamespace static\n\nvariables {\u03b1 \u03b2 : Type} {p q : parser \u03b1} {msgs : thunk (list string)} {msg : thunk string}\n  {cb : char_buffer} {n' n : \u2115} {err : dlist string} {a : \u03b1} {b : \u03b2} {sep : parser unit}\n\nlemma not_of_ne (h : p cb n = done n' a) (hne : n \u2260 n') : \u00ac static p :=\nby { introI, exact hne (of_done h) }\n\ninstance pure : static (pure a) :=\n\u27e8\u03bb _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }\u27e9\n\ninstance bind {f : \u03b1 \u2192 parser \u03b2} [p.static] [\u2200 a, (f a).static] :\n  (p >>= f).static :=\n\u27e8\u03bb _ _ _ _, by { rw bind_eq_done, rintro \u27e8_, _, hp, hf\u27e9, exact trans (of_done hp) (of_done hf) }\u27e9\n\ninstance and_then {q : parser \u03b2} [p.static] [q.static] : (p >> q).static := static.bind\n\ninstance map [p.static] {f : \u03b1 \u2192 \u03b2} : (f <$> p).static :=\n\u27e8\u03bb _ _ _ _, by { simp_rw map_eq_done, rintro \u27e8_, hp, _\u27e9, exact of_done hp }\u27e9\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.static] [p.static] : (f <*> p).static := static.bind\n\ninstance mmap : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 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 \u03bb _, static.pure } }\nend\n\ninstance mmap' : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 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 \u03b1 failure :=\n\u27e8\u03bb _ _ _ _, by simp\u27e9\n\ninstance guard {p : Prop} [decidable p] : static (guard p) :=\n\u27e8\u03bb _ _ _ _, by simp [guard_eq_done]\u27e9\n\ninstance orelse [p.static] [q.static] : (p <|> q).static :=\n\u27e8\u03bb _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | \u27e8h, -\u27e9); exact of_done h }\u27e9\n\ninstance decorate_errors [p.static] :\n  (@decorate_errors \u03b1 msgs p).static :=\n\u27e8\u03bb _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }\u27e9\n\ninstance decorate_error [p.static] : (@decorate_error \u03b1 msg p).static :=\nstatic.decorate_errors\n\nlemma any_char : \u00ac 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 \u2192 Prop} [decidable_pred p] : static (sat p) \u2194 \u2200 c, \u00ac 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 \u27e8a, hp\u27e9 }\nend\n\ninstance sat : static (sat (\u03bb _, false)) :=\nby { apply sat_iff.mpr, simp }\n\ninstance eps : static eps := static.pure\n\nlemma ch (c : char) : \u00ac 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') \u2194 cb' = buffer.nil :=\nbegin\n  rw \u2190buffer.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 \u27e8\u03bb _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left\u27e9 },\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) \u2194 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) \u2194 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) \u2194 s = \"\" :=\nby simp [str_eq_char_buf, char_buf_iff, \u2190string.to_list_inj, buffer.ext_iff]\n\ninstance remaining : remaining.static :=\n\u27e8\u03bb _ _ _ _ h, (remaining_eq_done.mp h).left\u27e9\n\ninstance eof : eof.static :=\nstatic.decorate_error\n\ninstance foldr_core {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} [p.static] :\n  \u2200 {b : \u03b2} {reps : \u2115}, (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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2} [p.static] : static (foldr f p b) :=\n\u27e8\u03bb _ _ _ _, by { dsimp [foldr], exact of_done }\u27e9\n\ninstance foldl_core {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} [p.static] :\n  \u2200 {a : \u03b1} {reps : \u2115}, (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 \u03bb _, foldl_core } },\n  { exact static.pure }\nend\n\ninstance foldl {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} [p.static] : static (foldl f a p) :=\n\u27e8\u03bb _ _ _ _, by { dsimp [foldl], exact of_done }\u27e9\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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.static \u2192 (F p).static) :\n  \u2200 (max_depth : \u2115), static (fix_core F max_depth)\n| 0               := static.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\nlemma digit : \u00ac 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 : \u00ac 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.static \u2192 (F p).static) :\n  static (fix F) :=\n\u27e8\u03bb cb n _ _ h,\n  by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }\u27e9\n\nend static\n\nnamespace bounded\n\nvariables {\u03b1 \u03b2 : Type} {msgs : thunk (list string)} {msg : thunk string}\nvariables {p q : parser \u03b1} {cb : char_buffer} {n n' : \u2115} {err : dlist string}\nvariables {a : \u03b1} {b : \u03b2}\n\nlemma done_of_unbounded (h : \u00acp.bounded) : \u2203 (cb : char_buffer) (n n' : \u2115) (a : \u03b1),\n  p cb n = done n' a \u2227 cb.size \u2264 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 : \u00ac bounded (pure a) :=\nbegin\n  introI,\n  have : (pure a : parser \u03b1) 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 : \u03b1 \u2192 parser \u03b2} [p.bounded] :\n  (p >>= f).bounded :=\nbegin\n  constructor,\n  intros cb n hn,\n  obtain \u27e8_, _, hp\u27e9 := bounded.exists p hn,\n  simp [hp]\nend\n\ninstance and_then {q : parser \u03b2} [p.bounded] : (p >> q).bounded :=\nbounded.bind\n\ninstance map [p.bounded] {f : \u03b1 \u2192 \u03b2} : (f <$> p).bounded :=\nbounded.bind\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.bounded] : (f <*> p).bounded :=\nbounded.bind\n\ninstance mmap {a : \u03b1} {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 a, (f a).bounded] :\n  ((a :: l).mmap f).bounded :=\nbounded.bind\n\ninstance mmap' {a : \u03b1} {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 a, (f a).bounded] :\n  ((a :: l).mmap' f).bounded :=\nbounded.and_then\n\ninstance failure : @parser.bounded \u03b1 failure :=\n\u27e8by simp\u27e9\n\nlemma guard_iff {p : Prop} [decidable p] : bounded (guard p) \u2194 \u00ac p :=\nby simpa [guard, apply_ite bounded, pure, failure] using \u03bb _, 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 | \u27e8h, -, -\u27e9 := 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 \u03b1 msgs p).bounded :=\nbegin\n  constructor,\n  intros _ _,\n  simpa using bounded.exists p\nend\n\nlemma decorate_errors_iff : (@parser.decorate_errors \u03b1 msgs p).bounded \u2194 p.bounded :=\nbegin\n  split,\n  { introI,\n    constructor,\n    intros _ _ hn,\n    obtain \u27e8_, _, h\u27e9 := bounded.exists (@parser.decorate_errors \u03b1 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 \u27e8_, _, h\u27e9 := bounded.exists p hn,\n    simp [h] }\nend\n\ninstance decorate_error [p.bounded] : (@decorate_error \u03b1 msg p).bounded :=\nbounded.decorate_errors\n\nlemma decorate_error_iff : (@parser.decorate_error \u03b1 msg p).bounded \u2194 p.bounded :=\ndecorate_errors_iff\n\ninstance any_char : bounded any_char :=\n\u27e8\u03bb cb n hn, by simp [any_char, hn]\u27e9\n\ninstance sat {p : char \u2192 Prop} [decidable_pred p] : bounded (sat p) :=\n\u27e8\u03bb cb n hn, by simp [sat, hn]\u27e9\n\nlemma eps : \u00ac 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') \u2194 cb' \u2260 buffer.nil :=\nbegin\n  have : cb' \u2260 buffer.nil \u2194 cb'.to_list \u2260 [] :=\n      not_iff_not_of_iff \u27e8\u03bb h, by simp [h], \u03bb h, by simpa using congr_arg list.to_buffer h\u27e9,\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 \u2194 s \u2260 \"\" :=\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 \u2260 \"\",\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 : \u00ac 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 : \u00ac 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2} : (foldr_core f p b 0).bounded :=\nbounded.failure\n\ninstance foldl_core_zero {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {b : \u03b2} : (foldl_core f b p 0).bounded :=\nbounded.failure\n\nvariables {reps : \u2115} [hpb : p.bounded] (he : \u2200 cb n n' err, p cb n = fail n' err \u2192 n \u2260 n')\ninclude hpb he\n\nlemma foldr_core {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} : (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 \u27e8np, errp, hp\u27e9 := bounded.exists p hn,\n  simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp,\nend\n\nlemma foldr {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} : 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 \u27e8np, errp, hp\u27e9 := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn,\n  simp [foldr, hp]\nend\n\nlemma foldl_core {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} :\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 \u27e8np, errp, hp\u27e9 := bounded.exists p hn,\n  simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp,\nend\n\nlemma foldl {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} : 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 \u27e8np, errp, hp\u27e9 := 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 : \u2200 cb n n' err, pc cb n = fail n' err \u2192 n \u2260 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.bounded \u2192 (F p).bounded) :\n  \u2200 (max_depth : \u2115), 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.bounded \u2192 (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 \u27e8np, errp, hp\u27e9 := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn,\n  simp [fix, hp]\nend\n\nend bounded\n\nnamespace unfailing\n\nvariables {\u03b1 \u03b2 : Type} {p q : parser \u03b1} {msgs : thunk (list string)} {msg : thunk string}\n  {cb : char_buffer} {n' n : \u2115} {err : dlist string} {a : \u03b1} {b : \u03b2} {sep : parser unit}\n\nlemma of_bounded [p.bounded] : \u00ac 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\u27e8\u03bb _ _, by simp [pure_eq_done]\u27e9\n\ninstance bind {f : \u03b1 \u2192 parser \u03b2} [p.unfailing] [\u2200 a, (f a).unfailing] :\n  (p >>= f).unfailing :=\n\u27e8\u03bb cb n, begin\n  obtain \u27e8np, a, hp\u27e9 := exists_done p cb n,\n  simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np\nend\u27e9\n\ninstance and_then {q : parser \u03b2} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind\n\ninstance map [p.unfailing] {f : \u03b1 \u2192 \u03b2} : (f <$> p).unfailing := unfailing.bind\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing :=\nunfailing.bind\n\ninstance mmap {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 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 \u27e8np, a, hp\u27e9 := exists_done (f hd) cb n,\n    obtain \u27e8n', b, hf\u27e9 := hl cb np,\n    simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] }\nend\n\ninstance mmap' {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [\u2200 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 \u27e8np, a, hp\u27e9 := exists_done (f hd) cb n,\n    obtain \u27e8n', b, hf\u27e9 := hl cb np,\n    simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] }\nend\n\nlemma failure : \u00ac @parser.unfailing \u03b1 failure :=\nbegin\n  introI h,\n  have : (failure : parser \u03b1) 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 : \u00ac unfailing (guard false) :=\nunfailing.failure\n\ninstance orelse [p.unfailing] : (p <|> q).unfailing :=\n\u27e8\u03bb cb n, by { obtain \u27e8_, _, h\u27e9 := p.exists_done cb n, simp [success_iff, h] }\u27e9\n\ninstance decorate_errors [p.unfailing] :\n  (@decorate_errors \u03b1 msgs p).unfailing :=\n\u27e8\u03bb cb n, by { obtain \u27e8_, _, h\u27e9 := p.exists_done cb n, simp [success_iff, h] }\u27e9\n\ninstance decorate_error [p.unfailing] : (@decorate_error \u03b1 msg p).unfailing :=\nunfailing.decorate_errors\n\ninstance any_char : conditionally_unfailing any_char :=\n\u27e8\u03bb _ _ hn, by simp [success_iff, any_char_eq_done, hn]\u27e9\n\nlemma sat : conditionally_unfailing (sat (\u03bb _, true)) :=\n\u27e8\u03bb _ _ hn, by simp [success_iff, sat_eq_done, hn]\u27e9\n\ninstance eps : unfailing eps := unfailing.pure\n\ninstance remaining : remaining.unfailing :=\n\u27e8\u03bb _ _, by simp [success_iff, remaining_eq_done]\u27e9\n\nlemma foldr_core_zero {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} : \u00ac (foldr_core f p b 0).unfailing :=\nunfailing.failure\n\ninstance foldr_core_of_static {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} {reps : \u2115} [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 \u27e8np, a, h\u27e9 := 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 \u27e8np, a, h\u27e9 := p.exists_done cb n,\n    have : n = np := static.of_done h,\n    subst this,\n    obtain \u27e8np, b', hf\u27e9 := exists_done (foldr_core f p b (reps + 1)) cb n,\n    have : n = np := static.of_done hf,\n    subst this,\n    refine \u27e8n, f a b', _\u27e9,\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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} [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 : \u00ac digit.unfailing :=\nof_bounded\n\nlemma nat : \u00ac nat.unfailing :=\nof_bounded\n\nend unfailing\n\nnamespace err_static\n\nvariables {\u03b1 \u03b2 : Type} {p q : parser \u03b1} {msgs : thunk (list string)} {msg : thunk string}\n  {cb : char_buffer} {n' n : \u2115} {err : dlist string} {a : \u03b1} {b : \u03b2} {sep : parser unit}\n\nlemma not_of_ne (h : p cb n = fail n' err) (hne : n \u2260 n') : \u00ac err_static p :=\nby { introI, exact hne (of_fail h) }\n\ninstance pure : err_static (pure a) :=\n\u27e8\u03bb _ _ _ _, by { simp [pure_eq_done] }\u27e9\n\ninstance bind {f : \u03b1 \u2192 parser \u03b2} [p.static] [p.err_static] [\u2200 a, (f a).err_static] :\n  (p >>= f).err_static :=\n\u27e8\u03bb cb n n' err, begin\n  rw bind_eq_fail,\n  rintro (hp | \u27e8_, _, hp, hf\u27e9),\n  { exact of_fail hp },\n  { exact trans (static.of_done hp) (of_fail hf) }\nend\u27e9\n\ninstance bind_of_unfailing {f : \u03b1 \u2192 parser \u03b2} [p.err_static] [\u2200 a, (f a).unfailing] :\n  (p >>= f).err_static :=\n\u27e8\u03bb cb n n' err, begin\n  rw bind_eq_fail,\n  rintro (hp | \u27e8_, _, hp, hf\u27e9),\n  { exact of_fail hp },\n  { exact false.elim (unfailing.of_fail hf) }\nend\u27e9\n\ninstance and_then {q : parser \u03b2} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static :=\nerr_static.bind\n\ninstance and_then_of_unfailing {q : parser \u03b2} [p.err_static] [q.unfailing] : (p >> q).err_static :=\nerr_static.bind_of_unfailing\n\ninstance map [p.err_static] {f : \u03b1 \u2192 \u03b2} : (f <$> p).err_static :=\n\u27e8\u03bb _ _ _ _, by { rw map_eq_fail, exact of_fail }\u27e9\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static :=\nerr_static.bind\n\ninstance seq_of_unfailing {f : parser (\u03b1 \u2192 \u03b2)} [f.err_static] [p.unfailing] :\n  (f <*> p).err_static :=\nerr_static.bind_of_unfailing\n\ninstance mmap : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2}\n  [\u2200 a, (f a).static] [\u2200 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 \u03bb _, err_static.pure } }\nend\n\ninstance mmap_of_unfailing : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2}\n  [\u2200 a, (f a).unfailing] [\u2200 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 \u03bb _, unfailing.pure } }\nend\n\ninstance mmap' : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2}\n  [\u2200 a, (f a).static] [\u2200 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 : \u03a0 {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2}\n  [\u2200 a, (f a).unfailing] [\u2200 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 \u03b1 failure :=\n\u27e8\u03bb _ _ _ _ h, (failure_eq_fail.mp h).left\u27e9\n\ninstance guard {p : Prop} [decidable p] : err_static (guard p) :=\n\u27e8\u03bb _ _ _ _ h, (guard_eq_fail.mp h).right.left\u27e9\n\ninstance orelse [p.err_static] [q.mono] : (p <|> q).err_static :=\n\u27e8\u03bb _ n n' _, begin\n  by_cases hn : n = n',\n  { exact \u03bb _, hn },\n  { rw orelse_eq_fail_of_mono_ne hn,\n    { exact of_fail },\n    { apply_instance } }\nend\u27e9\n\ninstance decorate_errors :\n  (@decorate_errors \u03b1 msgs p).err_static :=\n\u27e8\u03bb _ _ _ _ h, (decorate_errors_eq_fail.mp h).left\u27e9\n\ninstance decorate_error : (@decorate_error \u03b1 msg p).err_static :=\nerr_static.decorate_errors\n\ninstance any_char : err_static any_char :=\n\u27e8\u03bb _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }\u27e9\n\ninstance sat_iff {p : char \u2192 Prop} [decidable_pred p] : err_static (sat p) :=\n\u27e8\u03bb _ _ _ _ h, (sat_eq_fail.mp h).left\u27e9\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\u27e8\u03bb _ _ _ _, by simp [remaining_ne_fail]\u27e9\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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.err_static \u2192 (F p).err_static) :\n  \u2200 (max_depth : \u2115), 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.err_static \u2192 (F p).err_static) :\n  err_static (fix F) :=\n\u27e8\u03bb cb n _ _ h,\n  by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }\u27e9\n\nend err_static\n\nnamespace step\n\nvariables {\u03b1 \u03b2 : Type} {p q : parser \u03b1} {msgs : thunk (list string)} {msg : thunk string}\n  {cb : char_buffer} {n' n : \u2115} {err : dlist string} {a : \u03b1} {b : \u03b2} {sep : parser unit}\n\nlemma not_step_of_static_done [static p] (h : \u2203 cb n n' a, p cb n = done n' a) : \u00ac step p :=\nbegin\n  introI,\n  rcases h with \u27e8cb, n, n', a, h\u27e9,\n  have hs := static.of_done h,\n  simpa [\u2190hs] using of_done h\nend\n\nlemma pure (a : \u03b1) : \u00ac step (pure a) :=\nbegin\n  apply not_step_of_static_done,\n  simp [pure_eq_done]\nend\n\ninstance bind {f : \u03b1 \u2192 parser \u03b2} [p.step] [\u2200 a, (f a).static] :\n  (p >>= f).step :=\n\u27e8\u03bb _ _ _ _, by { simp_rw bind_eq_done, rintro \u27e8_, _, hp, hf\u27e9,\n  exact (static.of_done hf) \u25b8 (of_done hp) }\u27e9\n\ninstance bind' {f : \u03b1 \u2192 parser \u03b2} [p.static] [\u2200 a, (f a).step] :\n  (p >>= f).step :=\n\u27e8\u03bb _ _ _ _, by { simp_rw bind_eq_done, rintro \u27e8_, _, hp, hf\u27e9,\n  rw static.of_done hp, exact of_done hf }\u27e9\n\ninstance and_then {q : parser \u03b2} [p.step] [q.static] : (p >> q).step := step.bind\n\ninstance and_then' {q : parser \u03b2} [p.static] [q.step] : (p >> q).step := step.bind'\n\ninstance map [p.step] {f : \u03b1 \u2192 \u03b2} : (f <$> p).step :=\n\u27e8\u03bb _ _ _ _, by { simp_rw map_eq_done, rintro \u27e8_, hp, _\u27e9, exact of_done hp }\u27e9\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.step] [p.static] : (f <*> p).step := step.bind\n\ninstance seq' {f : parser (\u03b1 \u2192 \u03b2)} [f.static] [p.step] : (f <*> p).step := step.bind'\n\ninstance mmap {f : \u03b1 \u2192 parser \u03b2} [(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 \u03bb _, static.pure } }\nend\n\ninstance mmap' {f : \u03b1 \u2192 parser \u03b2} [(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 \u03b1 failure :=\n\u27e8\u03bb _ _ _ _, by simp\u27e9\n\nlemma guard_true : \u00ac step (guard true) := pure _\n\ninstance guard : step (guard false) :=\nstep.failure\n\ninstance orelse [p.step] [q.step] : (p <|> q).step :=\n\u27e8\u03bb _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | \u27e8h, -\u27e9); exact of_done h }\u27e9\n\nlemma decorate_errors_iff : (@parser.decorate_errors \u03b1 msgs p).step \u2194 p.step :=\nbegin\n  split,\n  { introI,\n    constructor,\n    intros cb n n' a h,\n    have : (@parser.decorate_errors \u03b1 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 \u03b1 msgs p).step :=\n\u27e8\u03bb _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }\u27e9\n\nlemma decorate_error_iff : (@parser.decorate_error \u03b1 msg p).step \u2194 p.step :=\ndecorate_errors_iff\n\ninstance decorate_error [p.step] : (@decorate_error \u03b1 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 _ _ \u27e8_, rfl, -\u27e9,\n  simp\nend\n\ninstance sat {p : char \u2192 Prop} [decidable_pred p] : step (sat p) :=\nbegin\n  constructor,\n  intros cb n,\n  simp_rw [sat_eq_done],\n  rintro _ _ \u27e8_, _, rfl, -\u27e9,\n  simp\nend\n\nlemma eps : \u00ac 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 \u2194 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 \u27e8rfl, -\u27e9,\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 \u2194 s.length = 1 :=\nby simp [str_eq_char_buf, char_buf_iff, \u2190string.to_list_inj, buffer.ext_iff]\n\nlemma remaining : \u00ac remaining.step :=\nbegin\n  apply not_step_of_static_done,\n  simp [remaining_eq_done]\nend\n\nlemma eof : \u00ac 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.step \u2192 (F p).step) :\n  \u2200 (max_depth : \u2115), 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.step \u2192 (F p).step) :\n  step (fix F) :=\n\u27e8\u03bb cb n _ _ h,\n  by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }\u27e9\n\nend step\n\nsection step\n\nvariables {\u03b1 \u03b2 : Type} {p q : parser \u03b1} {msgs : thunk (list string)} {msg : thunk string}\n  {cb : char_buffer} {n' n : \u2115} {err : dlist string} {a : \u03b1} {b : \u03b2} {sep : parser unit}\n\nlemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : \u03b1} {xs : list \u03b1} :\n  many1 p cb n = done n' (x :: xs) \u2194 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 \u27e8k, hk\u27e9 : \u2203 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 \u2190@IH hd' tl' at hm, swap, refl,\n      simp only [many1_eq_done, many, foldr] at hm,\n      obtain \u27e8np, hp', hf\u27e9 := 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 \u27e8k, hk\u27e9 : \u2203 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 \u2190@IH hd' tl' (n + 1) n', swap, refl,\n      rw [hk, foldr_core_eq_done, or.comm] at hm,\n      obtain (hm | \u27e8np, hd', tl', hp', hf, hm\u27e9) := hm,\n      { simpa using hm },\n      simp only at hm,\n      obtain \u27e8rfl, rfl\u27e9 := 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', \u2190hf, foldr] } }\nend\n\nend step\n\nnamespace prog\n\nvariables {\u03b1 \u03b2 : Type} {p q : parser \u03b1} {msgs : thunk (list string)} {msg : thunk string}\n  {cb : char_buffer} {n' n : \u2115} {err : dlist string} {a : \u03b1} {b : \u03b2} {sep : parser unit}\n\n@[priority 100] -- see Note [lower instance priority]\ninstance of_step [step p] : prog p :=\n\u27e8\u03bb _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }\u27e9\n\nlemma pure (a : \u03b1) : \u00ac prog (pure a) :=\nbegin\n  introI h,\n  have : (pure a : parser \u03b1) 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 : \u03b1 \u2192 parser \u03b2} [p.prog] [\u2200 a, (f a).mono] :\n  (p >>= f).prog :=\n\u27e8\u03bb _ _ _ _, by { simp_rw bind_eq_done, rintro \u27e8_, _, hp, hf\u27e9,\n  exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }\u27e9\n\ninstance and_then {q : parser \u03b2} [p.prog] [q.mono] : (p >> q).prog := prog.bind\n\ninstance map [p.prog] {f : \u03b1 \u2192 \u03b2} : (f <$> p).prog :=\n\u27e8\u03bb _ _ _ _, by { simp_rw map_eq_done, rintro \u27e8_, hp, _\u27e9, exact of_done hp }\u27e9\n\ninstance seq {f : parser (\u03b1 \u2192 \u03b2)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind\n\ninstance mmap {l : list \u03b1} {f : \u03b1 \u2192 parser \u03b2} [(f a).prog] [\u2200 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 \u03b1} {f : \u03b1 \u2192 parser \u03b2} [(f a).prog] [\u2200 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 \u03b1 failure :=\nprog.of_step\n\nlemma guard_true : \u00ac prog (guard true) := pure _\n\ninstance guard : prog (guard false) :=\nprog.failure\n\ninstance orelse [p.prog] [q.prog] : (p <|> q).prog :=\n\u27e8\u03bb _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | \u27e8h, -\u27e9); exact of_done h }\u27e9\n\nlemma decorate_errors_iff : (@parser.decorate_errors \u03b1 msgs p).prog \u2194 p.prog :=\nbegin\n  split,\n  { introI,\n    constructor,\n    intros cb n n' a h,\n    have : (@parser.decorate_errors \u03b1 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 \u03b1 msgs p).prog :=\n\u27e8\u03bb _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }\u27e9\n\nlemma decorate_error_iff : (@parser.decorate_error \u03b1 msg p).prog \u2194 p.prog :=\ndecorate_errors_iff\n\ninstance decorate_error [p.prog] : (@decorate_error \u03b1 msg p).prog :=\nprog.decorate_errors\n\ninstance any_char : prog any_char :=\nprog.of_step\n\ninstance sat {p : char \u2192 Prop} [decidable_pred p] : prog (sat p) :=\nprog.of_step\n\nlemma eps : \u00ac 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 \u2194 cb' \u2260 buffer.nil :=\nbegin\n  have : cb' \u2260 buffer.nil \u2194 cb'.to_list \u2260 [] :=\n      not_iff_not_of_iff \u27e8\u03bb h, by simp [h], \u03bb h, by simpa using congr_arg list.to_buffer h\u27e9,\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 \u2194 s \u2260 \"\" :=\nby simp [str_eq_char_buf, char_buf_iff, \u2190string.to_list_inj, buffer.ext_iff]\n\nlemma remaining : \u00ac 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 : \u00ac 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' (_ | \u27e8hd, tl\u27e9),\n  { simp },\n  { rw many1_eq_done,\n    rintro \u27e8np, hp, h\u27e9,\n    exact (of_done hp).trans_le (mono.of_done h) }\nend\n\nlemma fix_core {F : parser \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.prog \u2192 (F p).prog) :\n  \u2200 (max_depth : \u2115), 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 \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), p.prog \u2192 (F p).prog) :\n  prog (fix F) :=\n\u27e8\u03bb cb n _ _ h,\n  by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }\u27e9\n\nend prog\n\nvariables {\u03b1 \u03b2 : Type} {msgs : thunk (list string)} {msg : thunk string}\nvariables {p q : parser \u03b1} {cb : char_buffer} {n n' : \u2115} {err : dlist string}\nvariables {a : \u03b1} {b : \u03b2}\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 \u03b1}\n  (h : p.many cb n = done n' l) :\n  \u2200 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, \u2190nat.succ_add],\n  apply hl,\n  { rw [\u2190many1_eq_done_iff_many_eq_done, many1_eq_done] at h,\n    obtain \u27e8_, hp, h\u27e9 := 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 \u03b1}\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 [\u2190many1_eq_done_iff_many_eq_done, many1_eq_done] at h,\n    obtain \u27e8_, -, h\u27e9 := h,\n    exact hl h }\nend\n\nlemma many_eq_nil_of_out_of_bound [p.bounded] {l : list \u03b1}\n  (h : p.many cb n = done n' l) (hn : cb.size < n) :\n  n' = n \u2227 l = [] :=\nbegin\n  cases l,\n  { rw many_eq_done_nil at h,\n    exact \u27e8h.left.symm, rfl\u27e9 },\n  { rw many_eq_done at h,\n    obtain \u27e8np, hp, -\u27e9 := 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 \u03b1}\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 \u27e8k, hk\u27e9 : \u2203 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 \u27e8_, hp, h\u27e9 := 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 \u27e8rfl, -\u27e9,\n      simp },\n    rw \u2190many1_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 \u03b1}\n  (h : many1 p cb n = done n' l) :\n  n' \u2264 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 \u27e8np, hp, h\u27e9 := 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 [\u2190h.left] using bounded.of_done hp },\n    { rw \u2190many1_eq_done_iff_many_eq_done at h,\n      exact hl h } }\nend\n\nend many\n\nsection nat\n/--\nThe `val : \u2115` 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 : \u2115} (h : nat cb n = done n' val) :\n  val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map\n          (\u03bb 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 \u2115` using a helper function that keeps track of both the running sum an\n  and the magnitude so far, using a `(sum, magnitude) : (\u2115 \u00d7 \u2115)` 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 `\u2115 ), 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 = (\u03bb (d : \u2115) p, \u27e8p.1 + d * p.2, p.2 * 10\u27e9),\n  { ext1, ext1 \u27e8\u27e9, refl },\n  -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (\u2115 \u00d7 \u2115)` with\n  -- the function above. We use this lemma later when we finish our inductive case.\n  have hpow : \u2200 l, (list.foldr (\u03bb (digit : \u2115) (x : \u2115 \u00d7 \u2115), (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 \u27e8n', l, hp, rfl, rfl\u27e9 := 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 \u2115`. 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 : \u2115` 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 \u2115` 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 \u2264 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 \u27e8_, hp, -\u27e9 := 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 `\u2115` 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 \u27e8_, hn, rfl, _, _\u27e9,\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 \u2190list.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 \u21a6 n + 1` holds\n  -- due to the `step` property of `parser.digit`.\n  -- We also get here `k : \u2115` 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 \u27e8k, hk\u27e9 : \u2203 k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp),\n  have hdm : ltl = [] \u2228 digit.many1 cb (n + 1) = done n' ltl,\n  { cases ltl,\n    { simp },\n    { rw many1_eq_done at hp,\n      obtain \u27e8_, hp, hp'\u27e9 := 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 \u2115` is equal to the RHS, which is that\n  -- the `val : \u2115` that `nat.of_digits` produces when supplied a `list \u2115 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 \u27e8_, hp, rfl, hp'\u27e9 := 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 [\u2190list.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 [\u2190this, \u2190rearr, 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, \u2190nat.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' \u2264 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 \u2264 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, \u2190chdh, \u2190ltll, 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 : \u2115`, `n \u2264 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 : \u2115} (h : nat cb n = done n' val) :\n  \u2200 (hn : n' \u2264 cb.size) k (hk : k < n'), n \u2264 k \u2192\n    '0' \u2264 cb.read \u27e8k, hk.trans_le hn\u27e9 \u2227 cb.read \u27e8k, hk.trans_le hn\u27e9 \u2264 '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 \u2115` 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 \u27e8xs, h, -\u27e9 := h,\n  -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we\n  -- induct on the `xs : list \u2115` 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 \u2115`,\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 \u27e8_, hp, h\u27e9 := 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 \u27e8rfl, -, hn, ge0, le9, rfl\u27e9 := 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 \u2264 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 \u27e8ge0, le9\u27e9 },\n  -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we\n  -- case on `tl : list \u2115`\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 \u27e8rfl, -\u27e9 := 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 \u2260 []`. 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 \u2190many1_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 \u2264 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 : \u2115} (h : nat cb n = done n' val) :\n  \u2200 (hn : n' < cb.size), '0' \u2264 cb.read \u27e8n', hn\u27e9 \u2192 '9' < cb.read \u27e8n', hn\u27e9 :=\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 \u2115` generated by\n  -- `parser.digit.many1`.\n  -- We deal with the case of `n'` is \"out-of-bounds\" right away by requiring that\n  -- `\u2200 (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 \u27e8xs, h, -\u27e9 := h,\n  -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we\n  -- induct on the `xs : list \u2115` 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 \u27e8k, hk\u27e9 : \u2203 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 \u27e8-, _, h\u27e9 := 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 (\u27e8rfl, h\u27e9 | \u27e8h, -\u27e9) := 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 \u2264 n'`.\n      simpa using mono.of_fail h } },\n  { -- Case where `tl \u2260 []`. 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 \u27e8_, -, h\u27e9 := h,\n    rw \u2190many1_eq_done_iff_many_eq_done at h,\n    exact hl h }\nend\n\n/--\nThe `val : \u2115` 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 `\u2115` value encoded\nby its decimal characters.\n-/\nlemma nat_eq_done {val : \u2115} : nat cb n = done n' val \u2194 \u2203 (hn : n < n'),\n  val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map\n          (\u03bb c, c.to_nat - '0'.to_nat)))) \u2227 (\u2200 (hn' : n' < cb.size),\n          ('0' \u2264 cb.read \u27e8n', hn'\u27e9 \u2192 '9' < cb.read \u27e8n', hn'\u27e9)) \u2227 \u2203 (hn'' : n' \u2264 cb.size),\n          (\u2200 k (hk : k < n'), n \u2264 k \u2192\n          '0' \u2264 cb.read \u27e8k, hk.trans_le hn''\u27e9 \u2227 cb.read \u27e8k, hk.trans_le hn''\u27e9 \u2264 '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 \u27e8\u03bb h, \u27e8prog.of_done h, nat_of_done h, nat_of_done_bounded h, _\u27e9, _\u27e9,\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 \u27e8_, h, -\u27e9 := h,\n    -- Now we get our existential witness that `n' \u2264 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 \u27e8h, nat_of_done_as_digit H h\u27e9 },\n  -- We now prove that given the `cb : char_buffer` with characters within the `n \u2264 k < n'` interval\n  -- properly \"numeric\" and such that their `nat.of_digits` generates the `val : \u2115`, `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 \u27e8hn, hv, hb, hn', ho\u27e9,\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 : \u2115` 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 = (\u03bb (d : \u2115) p, \u27e8p.1 + d * p.2, p.2 * 10\u27e9),\n  { ext1, ext1 \u27e8\u27e9, 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 \u2264 n`. But this is a contradiction, since we have `n < n' \u2264 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 [\u2190list.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 `\u2115` 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 `\u2115` would give a\n      -- value `x \u2264 9`, since that is part of the iff statement in the `digit_eq_done` lemma.\n      have : (buffer.read cb \u27e8n, hn.trans_le hn'\u27e9).to_nat - '0'.to_nat \u2264 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' \u2264 '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, \u2190H.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 \u2264 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 \u2264 k < n'` are \"numeric\". We already had this for `n \u2264 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 \u27e8l, hdl, hvl\u27e9 := 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 \u2115` 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 \u27e8m, rfl\u27e9 : \u2203 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 (\u2115 \u00d7 \u2115)`\n      -- with the function above. We use this lemma to finish our inductive case.\n      have hpow : \u2200 l, (list.foldr (\u03bb (digit : \u2115) (x : \u2115 \u00d7 \u2115),\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 \u2115` 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 \u2264 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 \u2264 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 \u2264 cb.size`, we have that `tl` must be at least `m` in length.\n        simpa [\u2190H.right, \u2190nat.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 `\u2190pow_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, \u2190pow_succ 10, hml, ltll] },\n    { -- Consider the case that `n' \u2264 n + 1`. But then since `n < n' \u2264 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 \u27e8_, or.inl \u27e8rfl, _\u27e9\u27e9,\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) 2020 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\nimport 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\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. -/\nmeta def tactic.clear' (clear_dependent : bool) (hyps : list expr) : tactic unit := do\ntgt \u2190 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.\nhyps.mmap' (\u03bb h, do\n  dep \u2190 kdepends_on tgt h,\n  when dep $ fail $\n    format!\"Cannot clear hypothesis {h} since the target depends on it.\"),\nn \u2190 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.\nwhen (! clear_dependent && (n \u2260 hyps.length)) $ fail $ format.join\n  [ \"Some of the following hypotheses cannot be cleared because other \"\n  , \"hypotheses depend on (some of) them:\\n\"\n  , format.intercalate \", \" (hyps.map to_fmt)\n  ],\nv \u2190 mk_meta_var tgt,\nintron n,\nexact v,\ngs \u2190 get_goals,\nset_goals $ v :: gs\n\nnamespace tactic.interactive\n\n/--\nAn 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 {\u03b1} {\u03b2 : \u03b1 \u2192 Type} (a : \u03b1) (b : \u03b2 a) : unit :=\nbegin\n  try { clear a b }, -- fails since `b` depends on `a`\n  clear' a b,        -- succeeds\n  exact ()\nend\n```\n-/\nmeta def clear' (p : parse (many ident)) : tactic unit := do\nhyps \u2190 p.mmap get_local,\ntactic.clear' false hyps\n\n/--\nA variant of `clear'` which clears not only the given hypotheses, but also any\nother hypotheses depending on them.\n\n```lean\nexample {\u03b1} {\u03b2 : \u03b1 \u2192 Type} (a : \u03b1) (b : \u03b2 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 -/\nmeta def clear_dependent (p : parse (many ident)) : tactic unit := do\nhyps \u2190 p.mmap get_local,\ntactic.clear' true hyps\n\nadd_tactic_doc\n{ name       := \"clear'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear', `tactic.interactive.clear_dependent],\n  tags       := [\"context management\"],\n  inherit_description_from := `tactic.interactive.clear' }\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/clear.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.11757212117767353, "lm_q1q2_score": 0.04438825890830495}}
{"text": "import tactic\nimport .tokens\n\nnamespace tactic\nsetup_tactic_parser\n\n\n@[interactive]\nmeta def Posons := interactive.set\nend tactic\n\nexample (a b : \u2115) : \u2115 :=\nbegin\n  Posons n := max a b,\n  exact n,\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/Posons.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.09009299762657569, "lm_q1q2_score": 0.043990914773483956}}
{"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 `\u03b1` is a type, then `option \u03b1` can be understood as the type with one more element than `\u03b1`.\n`option \u03b1` has terms `some a`, where `a : \u03b1`, 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 \u03b1` 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 : \u03b1` 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 {\u03b1 \u03b2 \u03b3 \u03b4 : Type*}\n\nlemma coe_def : (coe : \u03b1 \u2192 option \u03b1) = some := rfl\nlemma some_eq_coe (a : \u03b1) : some a = a := rfl\n\nlemma some_ne_none (x : \u03b1) : some x \u2260 none := \u03bb h, option.no_confusion h\n@[simp] lemma coe_ne_none (a : \u03b1) : (a : option \u03b1) \u2260 none .\n\nprotected lemma \u00abforall\u00bb {p : option \u03b1 \u2192 Prop} : (\u2200 x, p x) \u2194 p none \u2227 \u2200 x, p (some x) :=\n\u27e8\u03bb h, \u27e8h _, \u03bb x, h _\u27e9, \u03bb h x, option.cases_on x h.1 h.2\u27e9\n\nprotected lemma \u00abexists\u00bb {p : option \u03b1 \u2192 Prop} : (\u2203 x, p x) \u2194 p none \u2228 \u2203 x, p (some x) :=\n\u27e8\u03bb \u27e8x, hx\u27e9, (option.cases_on x or.inl $ \u03bb x hx, or.inr \u27e8x, hx\u27e9) hx,\n  \u03bb h, h.elim (\u03bb h, \u27e8_, h\u27e9) (\u03bb \u27e8x, hx\u27e9, \u27e8_, hx\u27e9)\u27e9\n\n@[simp] theorem get_mem : \u2200 {o : option \u03b1} (h : is_some o), option.get h \u2208 o\n| (some a) _ := rfl\n\ntheorem get_of_mem {a : \u03b1} : \u2200 {o : option \u03b1} (h : is_some o), a \u2208 o \u2192 option.get h = a\n| _ _ rfl := rfl\n\n@[simp] lemma not_mem_none (a : \u03b1) : a \u2209 (none : option \u03b1) :=\n\u03bb h, option.no_confusion h\n\n@[simp] lemma some_get : \u2200 {x : option \u03b1} (h : is_some x), some (option.get h) = x\n| (some x) hx := rfl\n\n@[simp] lemma get_some (x : \u03b1) (h : is_some (some x)) : option.get h = x := rfl\n\n@[simp] lemma get_or_else_some (x y : \u03b1) : option.get_or_else (some x) y = x := rfl\n\n@[simp] lemma get_or_else_none (x : \u03b1) : option.get_or_else none x = x := rfl\n\n@[simp] lemma get_or_else_coe (x y : \u03b1) : option.get_or_else \u2191x y = x := rfl\n\nlemma get_or_else_of_ne_none {x : option \u03b1} (hx : x \u2260 none) (y : \u03b1) : some (x.get_or_else y) = x :=\nby cases x; [contradiction, rw get_or_else_some]\n\n@[simp] lemma coe_get {o : option \u03b1} (h : o.is_some) : ((option.get h : \u03b1) : option \u03b1) = o :=\noption.some_get h\n\ntheorem mem_unique {o : option \u03b1} {a b : \u03b1} (ha : a \u2208 o) (hb : b \u2208 o) : a = b :=\noption.some.inj $ ha.symm.trans hb\n\ntheorem eq_of_mem_of_mem {a : \u03b1} {o1 o2 : option \u03b1} (h1 : a \u2208 o1) (h2 : a \u2208 o2) : o1 = o2 :=\nh1.trans h2.symm\n\ntheorem mem.left_unique : relator.left_unique ((\u2208) : \u03b1 \u2192 option \u03b1 \u2192 Prop) :=\n\u03bb a o b, mem_unique\n\ntheorem some_injective (\u03b1 : Type*) : function.injective (@some \u03b1) :=\n\u03bb _ _, some_inj.mp\n\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {f : \u03b1 \u2192 \u03b2} (Hf : function.injective f) : function.injective (option.map f)\n| none      none      H := rfl\n| (some a\u2081) (some a\u2082) H := by rw Hf (option.some.inj H)\n\n@[simp] theorem map_comp_some (f : \u03b1 \u2192 \u03b2) : option.map f \u2218 some = some \u2218 f := rfl\n\n@[ext] theorem ext : \u2200 {o\u2081 o\u2082 : option \u03b1}, (\u2200 a, a \u2208 o\u2081 \u2194 a \u2208 o\u2082) \u2192 o\u2081 = o\u2082\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 \u03b1} :\n  o = none \u2194 (\u2200 a, a \u2209 o) :=\n\u27e8\u03bb e a h, by rw e at h; cases h, \u03bb h, ext $ by simpa\u27e9\n\n@[simp] theorem none_bind {\u03b1 \u03b2} (f : \u03b1 \u2192 option \u03b2) : none >>= f = none := rfl\n\n@[simp] theorem some_bind {\u03b1 \u03b2} (a : \u03b1) (f : \u03b1 \u2192 option \u03b2) : some a >>= f = f a := rfl\n\n@[simp] theorem none_bind' (f : \u03b1 \u2192 option \u03b2) : none.bind f = none := rfl\n\n@[simp] theorem some_bind' (a : \u03b1) (f : \u03b1 \u2192 option \u03b2) : (some a).bind f = f a := rfl\n\n@[simp] theorem bind_some : \u2200 x : option \u03b1, x >>= some = x :=\n@bind_pure \u03b1 option _ _\n\n@[simp] theorem bind_some' : \u2200 x : option \u03b1, x.bind some = x :=\nbind_some\n\n@[simp] theorem bind_eq_some {\u03b1 \u03b2} {x : option \u03b1} {f : \u03b1 \u2192 option \u03b2} {b : \u03b2} :\n  x >>= f = some b \u2194 \u2203 a, x = some a \u2227 f a = some b :=\nby cases x; simp\n\n@[simp] theorem bind_eq_some' {x : option \u03b1} {f : \u03b1 \u2192 option \u03b2} {b : \u03b2} :\n  x.bind f = some b \u2194 \u2203 a, x = some a \u2227 f a = some b :=\nby cases x; simp\n\n@[simp] theorem bind_eq_none' {o : option \u03b1} {f : \u03b1 \u2192 option \u03b2} :\n  o.bind f = none \u2194 (\u2200 b a, a \u2208 o \u2192 b \u2209 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 {\u03b1 \u03b2} {o : option \u03b1} {f : \u03b1 \u2192 option \u03b2} :\n  o >>= f = none \u2194 (\u2200 b a, a \u2208 o \u2192 b \u2209 f a) :=\nbind_eq_none'\n\nlemma bind_comm {\u03b1 \u03b2 \u03b3} {f : \u03b1 \u2192 \u03b2 \u2192 option \u03b3} (a : option \u03b1) (b : option \u03b2) :\n  a.bind (\u03bbx, b.bind (f x)) = b.bind (\u03bby, a.bind (\u03bbx, f x y)) :=\nby cases a; cases b; refl\n\nlemma bind_assoc (x : option \u03b1) (f : \u03b1 \u2192 option \u03b2) (g : \u03b2 \u2192 option \u03b3) :\n  (x.bind f).bind g = x.bind (\u03bb y, (f y).bind g) := by cases x; refl\n\nlemma join_eq_some {x : option (option \u03b1)} {a : \u03b1} : x.join = some a \u2194 x = some (some a) := by simp\n\nlemma join_ne_none {x : option (option \u03b1)} : x.join \u2260 none \u2194 \u2203 z, x = some (some z) := by simp\n\nlemma join_ne_none' {x : option (option \u03b1)} : \u00ac(x.join = none) \u2194 \u2203 z, x = some (some z) := by simp\n\nlemma join_eq_none {o : option (option \u03b1)} : o.join = none \u2194 o = none \u2228 o = some none :=\nby rcases o with _|_|_; simp\n\nlemma bind_id_eq_join {x : option (option \u03b1)} : x >>= id = x.join := by simp\n\nlemma join_eq_join : mjoin = @join \u03b1 :=\nfunext (\u03bb x, by rw [mjoin, bind_id_eq_join])\n\nlemma bind_eq_bind {\u03b1 \u03b2 : Type*} {f : \u03b1 \u2192 option \u03b2} {x : option \u03b1} :\n  x >>= f = x.bind f := rfl\n\n@[simp] lemma map_eq_map {\u03b1 \u03b2} {f : \u03b1 \u2192 \u03b2} :\n  (<$>) f = option.map f := rfl\n\ntheorem map_none {\u03b1 \u03b2} {f : \u03b1 \u2192 \u03b2} : f <$> none = none := rfl\n\ntheorem map_some {\u03b1 \u03b2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> some a = some (f a) := rfl\n\ntheorem map_coe {\u03b1 \u03b2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> (a : option \u03b1) = \u2191(f a) := rfl\n\n@[simp] theorem map_none' {f : \u03b1 \u2192 \u03b2} : option.map f none = none := rfl\n\n@[simp] theorem map_some' {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : option.map f (some a) = some (f a) := rfl\n\n@[simp] theorem map_coe' {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : option.map f (a : option \u03b1) = \u2191(f a) := rfl\n\ntheorem map_eq_some {\u03b1 \u03b2} {x : option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} :\n  f <$> x = some b \u2194 \u2203 a, x = some a \u2227 f a = b :=\nby cases x; simp\n\n@[simp] theorem map_eq_some' {x : option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} :\n  x.map f = some b \u2194 \u2203 a, x = some a \u2227 f a = b :=\nby cases x; simp\n\nlemma map_eq_none {\u03b1 \u03b2} {x : option \u03b1} {f : \u03b1 \u2192 \u03b2} :\n  f <$> x = none \u2194 x = none :=\nby { cases x; simp only [map_none, map_some, eq_self_iff_true] }\n\n@[simp] lemma map_eq_none' {x : option \u03b1} {f : \u03b1 \u2192 \u03b2} :\n  x.map f = none \u2194 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 \u03b1 \u03b2) :=\n\u03bb f g h, funext $ \u03bb x, some_injective _ $ by simp only [\u2190 map_some', h]\n\n@[simp] theorem map_inj {f g : \u03b1 \u2192 \u03b2} : option.map f = option.map g \u2194 f = g :=\nmap_injective'.eq_iff\n\nlemma map_congr {f g : \u03b1 \u2192 \u03b2} {x : option \u03b1} (h : \u2200 a \u2208 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 : \u03b1 \u2192 \u03b1} : option.map f = id \u2194 f = id := map_injective'.eq_iff' map_id\n\n@[simp] lemma map_map (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  option.map h (option.map g x) = option.map (h \u2218 g) x :=\nby { cases x; simp only [map_none', map_some'] }\n\nlemma map_comm {f\u2081 : \u03b1 \u2192 \u03b2} {f\u2082 : \u03b1 \u2192 \u03b3} {g\u2081 : \u03b2 \u2192 \u03b4} {g\u2082 : \u03b3 \u2192 \u03b4} (h : g\u2081 \u2218 f\u2081 = g\u2082 \u2218 f\u2082) (a : \u03b1) :\n  (option.map f\u2081 a).map g\u2081 = (option.map f\u2082 a).map g\u2082 :=\nby rw [map_map, h, \u2190map_map]\n\nlemma comp_map (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  option.map (h \u2218 g) x = option.map h (option.map g x) := (map_map _ _ _).symm\n\n@[simp] lemma map_comp_map (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) :\n  option.map g \u2218 option.map f = option.map (g \u2218 f) :=\nby { ext x, rw comp_map }\n\nlemma mem_map_of_mem {a : \u03b1} {x : option \u03b1} (g : \u03b1 \u2192 \u03b2) (h : a \u2208 x) : g a \u2208 x.map g :=\nmem_def.mpr ((mem_def.mp h).symm \u25b8 map_some')\n\nlemma mem_map {f : \u03b1 \u2192 \u03b2} {y : \u03b2} {o : option \u03b1} : y \u2208 o.map f \u2194 \u2203 x \u2208 o, f x = y := by simp\n\nlemma forall_mem_map {f : \u03b1 \u2192 \u03b2} {o : option \u03b1} {p : \u03b2 \u2192 Prop} :\n  (\u2200 y \u2208 o.map f, p y) \u2194 \u2200 x \u2208 o, p (f x) :=\nby simp\n\nlemma exists_mem_map {f : \u03b1 \u2192 \u03b2} {o : option \u03b1} {p : \u03b2 \u2192 Prop} :\n  (\u2203 y \u2208 o.map f, p y) \u2194 \u2203 x \u2208 o, p (f x) :=\nby simp\n\nlemma bind_map_comm {\u03b1 \u03b2} {x : option (option \u03b1) } {f : \u03b1 \u2192 \u03b2} :\n  x >>= option.map f = x.map (option.map f) >>= id :=\nby { cases x; simp }\n\nlemma join_map_eq_map_join {f : \u03b1 \u2192 \u03b2} {x : option (option \u03b1)} :\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 \u03b1))} :\n  x.join.join = (x.map join).join :=\nby { rcases x with _ | _ | _ | x; simp }\n\nlemma mem_of_mem_join {a : \u03b1} {x : option (option \u03b1)} (h : a \u2208 x.join) : some a \u2208 x :=\nmem_def.mpr ((mem_def.mp h).symm \u25b8 join_eq_some.mp h)\n\nsection pmap\n\nvariables {p : \u03b1 \u2192 Prop} (f : \u03a0 (a : \u03b1), p a \u2192 \u03b2) (x : option \u03b1)\n\n@[simp] lemma pbind_eq_bind (f : \u03b1 \u2192 option \u03b2) (x : option \u03b1) :\n  x.pbind (\u03bb a _, f a) = x.bind f :=\nby { cases x; simp only [pbind, none_bind', some_bind'] }\n\nlemma map_bind {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 \u03b3) (x : option \u03b1) (g : \u03b1 \u2192 option \u03b2) :\n  option.map f (x >>= g) = (x >>= \u03bb a, option.map f (g a)) :=\nby simp_rw [\u2190map_eq_map, \u2190bind_pure_comp_eq_map,is_lawful_monad.bind_assoc]\n\nlemma map_bind' (f : \u03b2 \u2192 \u03b3) (x : option \u03b1) (g : \u03b1 \u2192 option \u03b2) :\n  option.map f (x.bind g) = x.bind (\u03bb a, option.map f (g a)) :=\nby { cases x; simp }\n\nlemma map_pbind (f : \u03b2 \u2192 \u03b3) (x : option \u03b1) (g : \u03a0 a, a \u2208 x \u2192 option \u03b2) :\n  option.map f (x.pbind g) = (x.pbind (\u03bb a H, option.map f (g a H))) :=\nby { cases x; simp only [pbind, map_none'] }\n\nlemma pbind_map (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) (g : \u03a0 (b : \u03b2), b \u2208 x.map f \u2192 option \u03b3) :\n  pbind (option.map f x) g = x.pbind (\u03bb a h, g (f a) (mem_map_of_mem _ h)) :=\nby { cases x; refl }\n\n@[simp] lemma pmap_none (f : \u03a0 (a : \u03b1), p a \u2192 \u03b2) {H} : pmap f (@none \u03b1) H = none := rfl\n\n@[simp] lemma pmap_some (f : \u03a0 (a : \u03b1), p a \u2192 \u03b2) {x : \u03b1} (h : p x) :\n  pmap f (some x) = \u03bb _, some (f x h) := rfl\n\nlemma mem_pmem {a : \u03b1} (h : \u2200 a \u2208 x, p a) (ha : a \u2208 x) :\n  f a (h a ha) \u2208 pmap f x h :=\nby { rw mem_def at ha \u22a2, subst ha, refl }\n\nlemma pmap_map (g : \u03b3 \u2192 \u03b1) (x : option \u03b3) (H) :\n  pmap f (x.map g) H = pmap (\u03bb a h, f (g a) h) x (\u03bb a h, H _ (mem_map_of_mem _ h)) :=\nby { cases x; simp only [map_none', map_some', pmap] }\n\nlemma map_pmap (g : \u03b2 \u2192 \u03b3) (f : \u03a0 a, p a \u2192 \u03b2) (x H) :\n  option.map g (pmap f x H) = pmap (\u03bb 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 : \u03b1 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) (x H) :\n  @pmap _ _ p (\u03bb 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 {\u03b1 \u03b2 \u03b3} {p : \u03b1 \u2192 Prop} (f : \u03a0 a, p a \u2192 \u03b2) (x : option \u03b1) (g : \u03b2 \u2192 option \u03b3) (H) :\n  (pmap f x H) >>= g = x.pbind (\u03bb 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 : \u03a0 (a : \u03b1), a \u2208 x \u2192 option \u03b2}\n  (h' : \u2200 a \u2208 x, f a H = none \u2192 x = none) :\n  x.pbind f = none \u2194 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 : \u03a0 (a : \u03b1), a \u2208 x \u2192 option \u03b2} {y : \u03b2} :\n  x.pbind f = some y \u2194 \u2203 (z \u2208 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 \u27e8z, H, hz\u27e9,\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 \u2194 x = none :=\nby { cases x; simp }\n\n@[simp] lemma pmap_eq_some_iff {hf} {y : \u03b2} :\n  pmap f x hf = some y \u2194 \u2203 (a : \u03b1) (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 \u27e8x, rfl, h\u27e9 },\n    { rintro \u27e8a, H, rfl\u27e9,\n      simp only [mem_def] at H,\n      simp only [H, pmap] } }\nend\n\n@[simp] lemma join_pmap_eq_pmap_join {f : \u03a0 a, p a \u2192 \u03b2} {x : option (option \u03b1)} (H) :\n  (pmap (pmap f) x H).join = pmap f x.join (\u03bb 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 {\u03b1 \u03b2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : some f <*> some a = some (f a) := rfl\n\n@[simp] theorem some_orelse' (a : \u03b1) (x : option \u03b1) : (some a).orelse x = some a := rfl\n\n@[simp] theorem some_orelse (a : \u03b1) (x : option \u03b1) : (some a <|> x) = some a := rfl\n\n@[simp] theorem none_orelse' (x : option \u03b1) : none.orelse x = x :=\nby cases x; refl\n\n@[simp] theorem none_orelse (x : option \u03b1) : (none <|> x) = x := none_orelse' x\n\n@[simp] theorem orelse_none' (x : option \u03b1) : x.orelse none = x :=\nby cases x; refl\n\n@[simp] theorem orelse_none (x : option \u03b1) : (x <|> none) = x := orelse_none' x\n\n@[simp] theorem is_some_none : @is_some \u03b1 none = ff := rfl\n\n@[simp] theorem is_some_some {a : \u03b1} : is_some (some a) = tt := rfl\n\ntheorem is_some_iff_exists {x : option \u03b1} : is_some x \u2194 \u2203 a, x = some a :=\nby cases x; simp [is_some]; exact \u27e8_, rfl\u27e9\n\n@[simp] theorem is_none_none : @is_none \u03b1 none = tt := rfl\n\n@[simp] theorem is_none_some {a : \u03b1} : is_none (some a) = ff := rfl\n\n@[simp] theorem not_is_some {a : option \u03b1} : is_some a = ff \u2194 a.is_none = tt :=\nby cases a; simp\n\nlemma eq_some_iff_get_eq {o : option \u03b1} {a : \u03b1} :\n  o = some a \u2194 \u2203 h : o.is_some, option.get h = a :=\nby cases o; simp\n\nlemma not_is_some_iff_eq_none {o : option \u03b1} :  \u00aco.is_some \u2194 o = none :=\nby cases o; simp\n\nlemma ne_none_iff_is_some {o : option \u03b1} : o \u2260 none \u2194 o.is_some :=\nby cases o; simp\n\nlemma ne_none_iff_exists {o : option \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), some x = o :=\nby {cases o; simp}\n\nlemma ne_none_iff_exists' {o : option \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), o = some x :=\nne_none_iff_exists.trans $ exists_congr $ \u03bb _, eq_comm\n\nlemma bex_ne_none {p : option \u03b1 \u2192 Prop} :\n  (\u2203 x \u2260 none, p x) \u2194 \u2203 x, p (some x) :=\n\u27e8\u03bb \u27e8x, hx, hp\u27e9, \u27e8get $ ne_none_iff_is_some.1 hx, by rwa [some_get]\u27e9,\n  \u03bb \u27e8x, hx\u27e9, \u27e8some x, some_ne_none x, hx\u27e9\u27e9\n\nlemma ball_ne_none {p : option \u03b1 \u2192 Prop} :\n  (\u2200 x \u2260 none, p x) \u2194 \u2200 x, p (some x) :=\n\u27e8\u03bb h x, h (some x) (some_ne_none x),\n  \u03bb h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)\u27e9\n\ntheorem iget_mem [inhabited \u03b1] : \u2200 {o : option \u03b1}, is_some o \u2192 o.iget \u2208 o\n| (some a) _ := rfl\n\ntheorem iget_of_mem [inhabited \u03b1] {a : \u03b1} : \u2200 {o : option \u03b1}, a \u2208 o \u2192 o.iget = a\n| _ rfl := rfl\n\nlemma get_or_else_default_eq_iget [inhabited \u03b1] (o : option \u03b1) : o.get_or_else default = o.iget :=\nby cases o; refl\n\n@[simp] theorem guard_eq_some {p : \u03b1 \u2192 Prop} [decidable_pred p] {a b : \u03b1} :\n  guard p a = some b \u2194 a = b \u2227 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 \u2194 p :=\nbegin\n  cases u,\n  by_cases p; simp [_root_.guard, h]; refl <|> contradiction,\nend\n\ntheorem lift_or_get_choice {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} (h : \u2200 a b, f a b = a \u2228 f a b = b) :\n  \u2200 o\u2081 o\u2082, lift_or_get f o\u2081 o\u2082 = o\u2081 \u2228 lift_or_get f o\u2081 o\u2082 = o\u2082\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 \u03b1} : lift_or_get f none b = b :=\nby cases b; refl\n\n@[simp] lemma lift_or_get_none_right {f} {a : option \u03b1} : lift_or_get f a none = a :=\nby cases a; refl\n\n@[simp] lemma lift_or_get_some_some {f} {a b : \u03b1} :\n  lift_or_get f (some a) (some b) = f a b := rfl\n\n/-- Given an element of `a : option \u03b1`, a default element `b : \u03b2` and a function `\u03b1 \u2192 \u03b2`, apply this\nfunction to `a` if it comes from `\u03b1`, and return `b` otherwise. -/\ndef cases_on' : option \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2\n| none     n s := n\n| (some a) n s := s a\n\n@[simp] lemma cases_on'_none (x : \u03b2) (f : \u03b1 \u2192 \u03b2) : cases_on' none x f = x := rfl\n\n@[simp] lemma cases_on'_some (x : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : cases_on' (some a) x f = f a := rfl\n\n@[simp] lemma cases_on'_coe (x : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : cases_on' (a : option \u03b1) x f = f a := rfl\n\n@[simp] lemma cases_on'_none_coe (f : option \u03b1 \u2192 \u03b2) (o : option \u03b1) :\n  cases_on' o (f none) (f \u2218 coe) = f o :=\nby cases o; refl\n\n@[simp] lemma get_or_else_map (f : \u03b1 \u2192 \u03b2) (x : \u03b1) (o : option \u03b1) :\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 \u03b1) (x : \u03b1) :\n  (o <|> o') = some x \u2194 o = some x \u2228 (o = none \u2227 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 \u03b1) (x : \u03b1) :\n  o.orelse o' = some x \u2194 o = some x \u2228 (o = none \u2227 o' = some x) :=\noption.orelse_eq_some o o' x\n\n@[simp] lemma orelse_eq_none (o o' : option \u03b1) :\n  (o <|> o') = none \u2194 (o = none \u2227 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 \u03b1) :\n  o.orelse o' = none \u2194 (o = none \u2227 o' = none) :=\noption.orelse_eq_none o o'\n\nsection\nopen_locale classical\n\n/-- An arbitrary `some a` with `a : \u03b1` if `\u03b1` is nonempty, and otherwise `none`. -/\nnoncomputable def choice (\u03b1 : Type*) : option \u03b1 :=\nif h : nonempty \u03b1 then\n  some h.some\nelse\n  none\n\nlemma choice_eq {\u03b1 : Type*} [subsingleton \u03b1] (a : \u03b1) : choice \u03b1 = some a :=\nbegin\n  dsimp [choice],\n  rw dif_pos (\u27e8a\u27e9 : nonempty \u03b1),\n  congr,\nend\n\nlemma choice_eq_none (\u03b1 : Type*) [is_empty \u03b1] : choice \u03b1 = none :=\ndif_neg (not_nonempty_iff_imp_false.mpr is_empty_elim)\n\nlemma choice_is_some_iff_nonempty {\u03b1 : Type*} : (choice \u03b1).is_some \u2194 nonempty \u03b1 :=\nbegin\n  fsplit,\n  { intro h, exact \u27e8option.get h\u27e9, },\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 : \u03b1) : (a : option \u03b1).to_list = [a] :=\nrfl\n\n@[simp] lemma to_list_none (\u03b1 : Type*) : (none : option \u03b1).to_list = [] :=\nrfl\n\n@[simp] lemma elim_none_some (f : option \u03b1 \u2192 \u03b2) : option.elim (f none) (f \u2218 some) = f :=\nfunext $ \u03bb 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.tidy\n\nimport evaluation_modified\n\nnamespace baseline\n\nsection tidy_proof_search\n\nmeta def tidy_default_tactics : list string := [\n     \"refl\"\n  ,  \"exact dec_trivial\"\n  ,  \"assumption\"\n  ,  \"tactic.intros1\"\n  ,  \"tactic.auto_cases\"\n  ,  \"apply_auto_param\"\n  ,  \"dsimp at *\"\n  ,  \"simp at *\"\n  ,  \"ext1\"\n  ,  \"fsplit\"\n  ,  \"injections_and_clear\"\n  ,  \"solve_by_elim\"\n  ,  \"norm_cast\"\n]\n\n@[inline]\nmeta def tidy_default_tactics_json : json :=\njson.array $ json.of_string <$> tidy_default_tactics\n\n@[inline]\nmeta def tidy_default_tactics_scores : json :=\njson.array $ json.of_float <$> list.repeat (0.0 : native.float) tidy_default_tactics.length\n\nmeta def tidy_api : ModelAPI := -- simulates logic of tidy, baseline (deterministic) model\nlet fn : json \u2192 io json := \u03bb msg, do {\n  pure $ json.array $ [tidy_default_tactics_json, tidy_default_tactics_scores]\n} in \u27e8fn\u27e9\n\n-- TODO(jesse): pass and set max_width\nmeta def tidy_bfs_proof_search_core\n   (fuel : \u2115 := 1000)\n   (verbose := ff)\n   : state_t BFSState tactic unit :=\nbfs_core\n  tidy_api\n    (\u03bb _, pure json.null)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[tidy_bfs_proof_search]\") msg n)\n        fuel\n\nmeta def tidy_bfs_proof_search\n  (fuel : \u2115 := 1000)\n  (verbose := ff)\n  (max_width := 25)\n  (max_depth := 50)\n  : tactic unit :=\n  bfs tidy_api (\u03bb _, pure json.null)\n    (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ (some \"[tidy_bfs_proof_search]\")) msg n)\n      fuel verbose max_width max_depth\n\nend tidy_proof_search\n\nsection playground\n\n-- example : true :=\n-- begin\n--   tidy_bfs_proof_search 5 tt,\n-- end\n\n-- open nat\n-- universe u\n-- example : \u2200 {\u03b1 : Type u} {s\u2081 s\u2082 t\u2081 t\u2082 : list \u03b1},\n--   s\u2081 ++ t\u2081 = s\u2082 ++ t\u2082 \u2192 s\u2081.length = s\u2082.length \u2192 s\u2081 = s\u2082 \u2227 t\u2081 = t\u2082 :=\n-- begin\n--   intros, -- tidy_bfs_proof_search\n-- end\n-- open nat\n\n-- example {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   tidy_bfs_proof_search 3 tt\n-- end\n-- run_cmd do {set_show_eval_trace tt *> do env \u2190 tactic.get_env, tactic.set_env_core env}\n\n-- example {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   tidy_bfs_proof_search 2 ff -- should only try one iteration before halting\n\nend playground\n\nend baseline\n", "meta": {"author": "toontran", "repo": "pact-lean-low-resource", "sha": "e24af1935b7f518f4d3ce5fe55e0a8fd1d541b82", "save_path": "github-repos/lean/toontran-pact-lean-low-resource", "path": "github-repos/lean/toontran-pact-lean-low-resource/pact-lean-low-resource-e24af1935b7f518f4d3ce5fe55e0a8fd1d541b82/src/backends/bfs/baseline_modified.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.09807932281138339, "lm_q1q2_score": 0.0436972350891518}}
{"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 \u2192 Supposons_args\n| absurde : name \u2192 option pexpr \u2192 Supposons_args\n\nmeta def Supposons_parser : lean.parser Supposons_args :=\nwith_desc \"... / Supposons par l'absurde ...\" $ \ndo { _ \u2190 tk \"par\", _ \u2190 tk \"l'absurde\", \n     n \u2190 ident,\n     do { _ \u2190 tk \":\", \n          hyp \u2190 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 \u2190 target,\n   when (not $ t.is_pi) whnf_target,\n   t \u2190 target,\n   when (not $ t.is_arrow) $\n     fail \"Il n'y a rien \u00e0 supposer ici, le but n'est pas une implication\",\n   ty \u2190 i_to_expr ty,\n   unify ty t.binding_domain,\n   intro_core n >> skip\n\nopen Supposons_args\n\n/-- Introduit une hypoth\u00e8se quand le but est une implication,\nou bien d\u00e9marre un raisonnement par l'absurde. -/\n@[interactive]\nmeta def Supposons : parse Supposons_parser \u2192 tactic unit\n| (regular le) := do le.mmap' (\u03bb 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 \u2190 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 \u2190 get_local n,\n                         change_core Hyp (some ehyp))\n\nend tactic\n\nexample : \u2200 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 : \u2200 n > 0, true :=\nbegin\n  intro n,\n  Supposons que H : n > 0,\n  trivial\nend\n\nexample : \u2200 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 : \u00ac Q \u2192 \u00ac P) : P \u2192 Q :=\nbegin\n  Supposons hP,\n  Supposons par l'absurde hnQ,\n  exact h hnQ hP,\nend\n\nexample (P Q : Prop) (h : \u00ac Q \u2192 \u00ac P) : P \u2192 Q :=\nbegin\n  Supposons hP,\n  Supposons par l'absurde hnQ : \u00ac Q,\n  exact h hnQ hP,\nend\n\nexample (P Q : Prop) (h : Q \u2192 \u00ac P) : P \u2192 \u00ac 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) 2019 Floris van Doorn. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Floris van Doorn\n-/\nimport tactic.protected\nimport algebra.group.to_additive\n\n/-!\n# simps attribute\n\nThis file defines the `@[simps]` attribute, to automatically generate `simp` lemmas\nreducing a definition when projections are applied to it.\n\n## Implementation Notes\n\nThere are three attributes being defined here\n* `@[simps]` is the attribute for objects of a structure or instances of a class. It will\n  automatically generate simplification lemmas for each projection of the object/instance that\n  contains data. See the doc strings for `simps_attr` and `simps_cfg` for more details and\n  configuration options.\n* `@[_simps_str]` is automatically added to structures that have been used in `@[simps]` at least\n  once. This attribute contains the data of the projections used for this structure by all following\n  invocations of `@[simps]`.\n* `@[notation_class]` should be added to all classes that define notation, like `has_mul` and\n  `has_zero`. This specifies that the projections that `@[simps]` used are the projections from\n  these notation classes instead of the projections of the superclasses.\n  Example: if `has_mul` is tagged with `@[notation_class]` then the projection used for `semigroup`\n  will be `\u03bb \u03b1 h\u03b1, @has_mul.mul \u03b1 (@semigroup.to_has_mul \u03b1 h\u03b1)` instead of `@semigroup.mul`.\n\n## Tags\n\nstructures, projections, simp, simplifier, generates declarations\n-/\n\nopen tactic expr option sum\n\nsetup_tactic_parser\ndeclare_trace simps.verbose\ndeclare_trace simps.debug\n\n/--\nProjection data for a single projection of a structure, consisting of the following fields:\n- the name used in the generated `simp` lemmas\n- an expression used by simps for the projection. It must be definitionally equal to an original\n  projection (or a composition of multiple projections).\n  These expressions can contain the universe parameters specified in the first argument of\n  `simps_str_attr`.\n- a list of natural numbers, which is the projection number(s) that have to be applied to the\n  expression. For example the list `[0, 1]` corresponds to applying the first projection of the\n  structure, and then the second projection of the resulting structure (this assumes that the\n  target of the first projection is a structure with at least two projections).\n  The composition of these projections is required to be definitionally equal to the provided\n  expression.\n- A boolean specifying whether `simp` lemmas are generated for this projection by default.\n- A boolean specifying whether this projection is written as prefix.\n-/\n@[protect_proj, derive [has_reflect, inhabited]]\nmeta structure projection_data :=\n(name : name)\n(expr : expr)\n(proj_nrs : list \u2115)\n(is_default : bool)\n(is_prefix : bool)\n\n/-- Temporary projection data parsed from `initialize_simps_projections` before the expression\n  matching this projection has been found. Only used internally in `simps_get_raw_projections`. -/\nmeta structure parsed_projection_data :=\n(orig_name : name) -- name for this projection used in the structure definition\n(new_name : name) -- name for this projection used in the generated `simp` lemmas\n(is_default : bool)\n(is_prefix : bool)\n\nsection\nopen format\nmeta instance : has_to_tactic_format projection_data :=\n\u27e8\u03bb \u27e8a, b, c, d, e\u27e9, (\u03bb x, group $ nest 1 $ to_fmt \"\u27e8\"  ++ to_fmt a ++ to_fmt \",\" ++ line ++ x ++\n  to_fmt \",\" ++ line ++ to_fmt c ++ to_fmt \",\" ++ line ++ to_fmt d ++ to_fmt \",\" ++ line ++\n  to_fmt e ++ to_fmt \"\u27e9\") <$> pp b\u27e9\n\nmeta instance : has_to_format parsed_projection_data :=\n\u27e8\u03bb \u27e8a, b, c, d\u27e9, group $ nest 1 $ to_fmt \"\u27e8\"  ++ to_fmt a ++ to_fmt \",\" ++ line ++ to_fmt b ++\n  to_fmt \",\" ++ line ++ to_fmt c ++ to_fmt \",\" ++ line ++ to_fmt d ++ to_fmt \"\u27e9\"\u27e9\nend\n\n/-- The type of rules that specify how metadata for projections in changes.\n  See `initialize_simps_projection`. -/\nabbreviation projection_rule := (name \u00d7 name \u2295 name) \u00d7 bool\n\n/--\nThe `@[_simps_str]` attribute specifies the preferred projections of the given structure,\nused by the `@[simps]` attribute.\n- This will usually be tagged by the `@[simps]` tactic.\n- You can also generate this with the command `initialize_simps_projections`.\n- To change the default value, see Note [custom simps projection].\n- You are strongly discouraged to add this attribute manually.\n- The first argument is the list of names of the universe variables used in the structure\n- The second argument is a list that consists of the projection data for each projection.\n-/\n@[user_attribute] meta def simps_str_attr :\n  user_attribute unit (list name \u00d7 list projection_data) :=\n{ name := `_simps_str,\n  descr := \"An attribute specifying the projection of the given structure.\",\n  parser := failed }\n\n/--\n  The `@[notation_class]` attribute specifies that this is a notation class,\n  and this notation should be used instead of projections by @[simps].\n  * The first argument `tt` for notation classes and `ff` for classes applied to the structure,\n    like `has_coe_to_sort` and `has_coe_to_fun`\n  * The second argument is the name of the projection (by default it is the first projection\n    of the structure)\n-/\n@[user_attribute] meta def notation_class_attr : user_attribute unit (bool \u00d7 option name) :=\n{ name := `notation_class,\n  descr := \"An attribute specifying that this is a notation class. Used by @[simps].\",\n  parser := prod.mk <$> (option.is_none <$> (tk \"*\")?) <*> ident? }\n\nattribute [notation_class] has_zero has_one has_add has_mul has_inv has_neg has_sub has_div has_dvd\n  has_mod has_le has_lt has_append has_andthen has_union has_inter has_sdiff has_equiv has_subset\n  has_ssubset has_emptyc has_insert has_singleton has_sep has_mem has_pow\n\nattribute [notation_class* coe_sort] has_coe_to_sort\nattribute [notation_class* coe_fn] has_coe_to_fun\n\n/-- Returns the projection information of a structure. -/\nmeta def projections_info (l : list projection_data) (pref : string) (str : name) : tactic format :=\ndo\n  \u27e8defaults, nondefaults\u27e9 \u2190 return $ l.partition_map $\n    \u03bb s, if s.is_default then inl s else inr s,\n  to_print \u2190 defaults.mmap $ \u03bb s, to_string <$>\n    let prefix_str := if s.is_prefix then \"(prefix) \" else \"\" in\n    pformat!\"Projection {prefix_str}{s.name}: {s.expr}\",\n  let print2 :=\n    string.join $ (nondefaults.map (\u03bb nm : projection_data, to_string nm.1)).intersperse \", \",\n  let to_print := to_print ++ if nondefaults.length = 0 then [] else\n    [\"No lemmas are generated for the projections: \" ++ print2 ++ \".\"],\n  let to_print := string.join $ to_print.intersperse \"\\n        > \",\n  return format!\"[simps] > {pref} {str}:\\n        > {to_print}\"\n\n/-- Auxiliary function of `get_composite_of_projections`. -/\nmeta def get_composite_of_projections_aux : \u03a0 (str : name) (proj : string) (x : expr)\n  (pos : list \u2115) (args : list expr), tactic (expr \u00d7 list \u2115) | str proj x pos args := do\n  e \u2190 get_env,\n  projs \u2190 e.structure_fields str,\n  let proj_info := projs.map_with_index $ \u03bb n p, (\u03bb x, (x, n, p)) <$> proj.get_rest (\"_\" ++ p.last),\n  when (proj_info.filter_map id = []) $\n    fail!\"Failed to find constructor {proj.popn 1} in structure {str}.\",\n  (proj_rest, index, proj_nm) \u2190 return (proj_info.filter_map id).ilast,\n  str_d \u2190 e.get str,\n  let proj_e : expr := const (str ++ proj_nm) str_d.univ_levels,\n  proj_d \u2190 e.get (str ++ proj_nm),\n  type \u2190 infer_type x,\n  let params := get_app_args type,\n  let univs := proj_d.univ_params.zip type.get_app_fn.univ_levels,\n  let new_x := (proj_e.instantiate_univ_params univs).mk_app $ params ++ [x],\n  let new_pos := pos ++ [index],\n  if proj_rest.is_empty then return (new_x.lambdas args, new_pos) else do\n    type \u2190 infer_type new_x,\n    (type_args, tgt) \u2190 open_pis_whnf type,\n    let new_str := tgt.get_app_fn.const_name,\n    get_composite_of_projections_aux new_str proj_rest (new_x.mk_app type_args) new_pos\n      (args ++ type_args)\n\n/-- Given a structure `str` and a projection `proj`, that could be multiple nested projections\n  (separated by `_`), returns an expression that is the composition of these projections and a\n  list of natural numbers, that are the projection numbers of the applied projections. -/\nmeta def get_composite_of_projections (str : name) (proj : string) : tactic (expr \u00d7 list \u2115) := do\n  e \u2190 get_env,\n  str_d \u2190 e.get str,\n  let str_e : expr := const str str_d.univ_levels,\n  type \u2190 infer_type str_e,\n  (type_args, tgt) \u2190 open_pis_whnf type,\n  let str_ap := str_e.mk_app type_args,\n  x \u2190 mk_local' `x binder_info.default str_ap,\n  get_composite_of_projections_aux str (\"_\" ++ proj) x [] $ type_args ++ [x]\n\n/--\n  Get the projections used by `simps` associated to a given structure `str`.\n\n  The returned information is also stored in a parameter of the attribute `@[_simps_str]`, which\n  is given to `str`. If `str` already has this attribute, the information is read from this\n  attribute instead. See the documentation for this attribute for the data this tactic returns.\n\n  The returned universe levels are the universe levels of the structure. For the projections there\n  are three cases\n  * If the declaration `{structure_name}.simps.{projection_name}` has been declared, then the value\n    of this declaration is used (after checking that it is definitionally equal to the actual\n    projection. If you rename the projection name, the declaration should have the *new* projection\n    name.\n  * You can also declare a custom projection that is a composite of multiple projections.\n  * Otherwise, for every class with the `notation_class` attribute, and the structure has an\n    instance of that notation class, then the projection of that notation class is used for the\n    projection that is definitionally equal to it (if there is such a projection).\n    This means in practice that coercions to function types and sorts will be used instead of\n    a projection, if this coercion is definitionally equal to a projection. Furthermore, for\n    notation classes like `has_mul` and `has_zero` those projections are used instead of the\n    corresponding projection.\n    Projections for coercions and notation classes are not automatically generated if they are\n    composites of multiple projections (for example when you use `extend` without the\n    `old_structure_cmd`).\n  * Otherwise, the projection of the structure is chosen.\n    For example: ``simps_get_raw_projections env `prod`` gives the default projections\n```\n  ([u, v], [prod.fst.{u v}, prod.snd.{u v}])\n```\n    while ``simps_get_raw_projections env `equiv`` gives\n```\n  ([u_1, u_2], [\u03bb \u03b1 \u03b2, coe_fn, \u03bb {\u03b1 \u03b2} (e : \u03b1 \u2243 \u03b2), \u21d1(e.symm), left_inv, right_inv])\n```\n    after declaring the coercion from `equiv` to function and adding the declaration\n```\n  def equiv.simps.inv_fun {\u03b1 \u03b2} (e : \u03b1 \u2243 \u03b2) : \u03b2 \u2192 \u03b1 := e.symm\n```\n\n  Optionally, this command accepts three optional arguments:\n  * If `trace_if_exists` the command will always generate a trace message when the structure already\n    has the attribute `@[_simps_str]`.\n  * The `rules` argument accepts a list of pairs `sum.inl (old_name, new_name)`. This is used to\n    change the projection name `old_name` to the custom projection name `new_name`. Example:\n    for the structure `equiv` the projection `to_fun` could be renamed `apply`. This name will be\n    used for parsing and generating projection names. This argument is ignored if the structure\n    already has an existing attribute. If an element of `rules` is of the form `sum.inr name`, this\n    means that the projection `name` will not be applied by default.\n  * if `trc` is true, this tactic will trace information.\n-/\n-- if performance becomes a problem, possible heuristic: use the names of the projections to\n-- skip all classes that don't have the corresponding field.\nmeta def simps_get_raw_projections (e : environment) (str : name) (trace_if_exists : bool := ff)\n  (rules : list projection_rule := []) (trc := ff) :\n  tactic (list name \u00d7 list projection_data) := do\n  let trc := trc || is_trace_enabled_for `simps.verbose,\n  has_attr \u2190 has_attribute' `_simps_str str,\n  if has_attr then do\n    data \u2190 simps_str_attr.get_param str,\n    -- We always print the projections when they already exists and are called by\n    -- `initialize_simps_projections`.\n    when (trace_if_exists || is_trace_enabled_for `simps.verbose) $ projections_info data.2\n      \"Already found projection information for structure\" str >>= trace,\n    return data\n  else do\n    when trc trace!\"[simps] > generating projection information for structure {str}.\",\n    when_tracing `simps.debug trace!\"[simps] > Applying the rules {rules}.\",\n    d_str \u2190 e.get str,\n    let raw_univs := d_str.univ_params,\n    let raw_levels := level.param <$> raw_univs,\n    /- Figure out projections, including renamings. The information for a projection is (before we\n    figure out the `expr` of the projection:\n    `(original name, given name, is default, is prefix)`.\n    The first projections are always the actual projections of the structure, but `rules` could\n    specify custom projections that are compositions of multiple projections. -/\n    projs \u2190 e.structure_fields str,\n    let projs : list parsed_projection_data := projs.map $ \u03bb nm, \u27e8nm, nm, tt, ff\u27e9,\n    let projs : list parsed_projection_data := rules.foldl (\u03bb projs rule,\n      match rule with\n      | (inl (old_nm, new_nm), is_prefix) := if old_nm \u2208 projs.map (\u03bb x, x.new_name) then\n        projs.map $ \u03bb proj,\n          if proj.new_name = old_nm then\n            { new_name := new_nm, is_prefix := is_prefix, ..proj } else\n            proj else\n        projs ++ [\u27e8old_nm, new_nm, tt, is_prefix\u27e9]\n      | (inr nm, is_prefix) := if nm \u2208 projs.map (\u03bb x, x.new_name) then\n        projs.map $ \u03bb proj, if proj.new_name = nm then\n          { is_default := ff, is_prefix := is_prefix, ..proj } else\n          proj else\n        projs ++ [\u27e8nm, nm, ff, is_prefix\u27e9]\n      end) projs,\n    when_tracing `simps.debug trace!\"[simps] > Projection info after applying the rules: {projs}.\",\n    when \u00ac (projs.map $ \u03bb x, x.new_name : list name).nodup $\n      fail $ \"Invalid projection names. Two projections have the same name.\nThis is likely because a custom composition of projections was given the same name as an \" ++\n\"existing projection. Solution: rename the existing projection (before renaming the custom \" ++\n\"projection).\",\n    /- Define the raw expressions for the projections, by default as the projections\n    (as an expression), but this can be overriden by the user. -/\n    raw_exprs_and_nrs \u2190 projs.mmap $ \u03bb \u27e8orig_nm, new_nm, _, _\u27e9, do\n    { (raw_expr, nrs) \u2190 get_composite_of_projections str orig_nm.last,\n      custom_proj \u2190 do\n      { decl \u2190 e.get (str ++ `simps ++ new_nm.last),\n        let custom_proj := decl.value.instantiate_univ_params $ decl.univ_params.zip raw_levels,\n        when trc trace!\n          \"[simps] > found custom projection for {new_nm}:\\n        > {custom_proj}\",\n        return custom_proj } <|> return raw_expr,\n      is_def_eq custom_proj raw_expr <|>\n        -- if the type of the expression is different, we show a different error message, because\n        -- that is more likely going to be helpful.\n        do\n        { custom_proj_type \u2190 infer_type custom_proj,\n          raw_expr_type \u2190 infer_type raw_expr,\n          b \u2190 succeeds (is_def_eq custom_proj_type raw_expr_type),\n          if b then fail!\"Invalid custom projection:\\n  {custom_proj}\nExpression is not definitionally equal to\\n  {raw_expr}\"\n          else fail!\"Invalid custom projection:\\n  {custom_proj}\nExpression has different type than {str ++ orig_nm}. Given type:\\n  {custom_proj_type}\nExpected type:\\n  {raw_expr_type}\" },\n      return (custom_proj, nrs) },\n    let raw_exprs := raw_exprs_and_nrs.map prod.fst,\n    /- Check for other coercions and type-class arguments to use as projections instead. -/\n    (args, _) \u2190 open_pis d_str.type,\n    let e_str := (expr.const str raw_levels).mk_app args,\n    automatic_projs \u2190 attribute.get_instances `notation_class,\n    raw_exprs \u2190 automatic_projs.mfoldl (\u03bb (raw_exprs : list expr) class_nm, do\n    { (is_class, proj_nm) \u2190 notation_class_attr.get_param class_nm,\n      proj_nm \u2190 proj_nm <|> (e.structure_fields_full class_nm).map list.head,\n      /- For this class, find the projection. `raw_expr` is the projection found applied to `args`,\n        and `lambda_raw_expr` has the arguments `args` abstracted. -/\n      (raw_expr, lambda_raw_expr) \u2190 if is_class then (do\n        guard $ args.length = 1,\n        let e_inst_type := (const class_nm raw_levels).mk_app args,\n        (hyp, e_inst) \u2190 try_for 1000 (mk_conditional_instance e_str e_inst_type),\n        raw_expr \u2190 mk_mapp proj_nm [args.head, e_inst],\n        clear hyp,\n        -- Note: `expr.bind_lambda` doesn't give the correct type\n        raw_expr_lambda \u2190 lambdas [hyp] raw_expr,\n        return (raw_expr, raw_expr_lambda.lambdas args))\n      else (do\n        e_inst_type \u2190 to_expr (((const class_nm []).app (pexpr.of_expr e_str)).app ``(_)),\n        e_inst \u2190 try_for 1000 (mk_instance e_inst_type),\n        raw_expr \u2190 mk_mapp proj_nm [e_str, none, e_inst],\n        return (raw_expr, raw_expr.lambdas args)),\n      raw_expr_whnf \u2190 whnf raw_expr,\n      let relevant_proj := raw_expr_whnf.binding_body.get_app_fn.const_name,\n      /- Use this as projection, if the function reduces to a projection, and this projection has\n        not been overrriden by the user. -/\n      guard $ projs.any $\n        \u03bb x, x.1 = relevant_proj.last \u2227 \u00ac e.contains (str ++ `simps ++ x.new_name.last),\n      let pos := projs.find_index (\u03bb x, x.1 = relevant_proj.last),\n      when trc trace!\n        \"        > using {proj_nm} instead of the default projection {relevant_proj.last}.\",\n      when_tracing `simps.debug trace!\"[simps] > The raw projection is:\\n  {lambda_raw_expr}\",\n      return $ raw_exprs.update_nth pos lambda_raw_expr } <|> return raw_exprs) raw_exprs,\n    let positions := raw_exprs_and_nrs.map prod.snd,\n    let proj_names := projs.map (\u03bb x, x.new_name),\n    let defaults := projs.map (\u03bb x, x.is_default),\n    let prefixes := projs.map (\u03bb x, x.is_prefix),\n    let projs := proj_names.zip_with5 projection_data.mk raw_exprs positions defaults prefixes,\n    /- make all proof non-default. -/\n    projs \u2190 projs.mmap $ \u03bb proj,\n      is_proof proj.expr >>= \u03bb b, return $ if b then { is_default := ff, .. proj } else proj,\n    when trc $ projections_info projs \"generated projections for\" str >>= trace,\n    simps_str_attr.set str (raw_univs, projs) tt,\n    when_tracing `simps.debug trace!\n       \"[simps] > Generated raw projection data: \\n{(raw_univs, projs)}\",\n    return (raw_univs, projs)\n\n/-- Parse a rule for `initialize_simps_projections`. It is either `<name>\u2192<name>` or `-<name>`,\n  possibly following by `as_prefix`.-/\nmeta def simps_parse_rule : parser projection_rule :=\nprod.mk <$>\n  ((\u03bb x y, inl (x, y)) <$> ident <*> (tk \"->\" >> ident) <|> inr <$> (tk \"-\" >> ident)) <*>\n  is_some <$> (tk \"as_prefix\")?\n\n/--\nYou can specify custom projections for the `@[simps]` attribute.\nTo do this for the projection `my_structure.original_projection` by adding a declaration\n`my_structure.simps.my_projection` that is definitionally equal to\n`my_structure.original_projection` but has the projection in the desired (simp-normal) form.\nThen you can call\n```\ninitialize_simps_projections (original_projection \u2192 my_projection, ...)\n```\nto register this projection. See `initialize_simps_projections_cmd` for more information.\n\nYou can also specify custom projections that are definitionally equal to a composite of multiple\nprojections. This is often desirable when extending structures (without `old_structure_cmd`).\n\n`has_coe_to_fun` and notation class (like `has_mul`) instances will be automatically used, if they\nare definitionally equal to a projection of the structure (but not when they are equal to the\ncomposite of multiple projections).\n-/\nlibrary_note \"custom simps projection\"\n\n/--\nThis command specifies custom names and custom projections for the simp attribute `simps_attr`.\n* You can specify custom names by writing e.g.\n  `initialize_simps_projections equiv (to_fun \u2192 apply, inv_fun \u2192 symm_apply)`.\n* See Note [custom simps projection] and the examples below for information how to declare custom\n  projections.\n* If no custom projection is specified, the projection will be `coe_fn`/`\u21d1` if a `has_coe_to_fun`\n  instance has been declared, or the notation of a notation class (like `has_mul`) if such an\n  instance is available. If none of these cases apply, the projection itself will be used.\n* You can disable a projection by default by running\n  `initialize_simps_projections equiv (-inv_fun)`\n  This will ensure that no simp lemmas are generated for this projection,\n  unless this projection is explicitly specified by the user.\n* If you want the projection name added as a prefix in the generated lemma name, you can add the\n  `as_prefix` modifier:\n  `initialize_simps_projections equiv (to_fun \u2192 coe as_prefix)`\n  Note that this does not influence the parsing of projection names: if you have a declaration\n  `foo` and you want to apply the projections `snd`, `coe` (which is a prefix) and `fst`, in that\n  order you can run `@[simps snd_coe_fst] def foo ...` and this will generate a lemma with the\n  name `coe_foo_snd_fst`.\n  * Run `initialize_simps_projections?` (or `set_option trace.simps.verbose true`)\n  to see the generated projections.\n* You can declare a new name for a projection that is the composite of multiple projections, e.g.\n  ```\n    structure A := (proj : \u2115)\n    structure B extends A\n    initialize_simps_projections? B (to_A_proj \u2192 proj, -to_A)\n  ```\n  You can also make your custom projection that is definitionally equal to a composite of\n  projections. In this case, coercions and notation classes are not automatically recognized, and\n  should be manually given by giving a custom projection.\n  This is especially useful when extending a structure (without `old_structure_cmd`).\n  In the above example, it is desirable to add `-to_A`, so that `@[simps]` doesn't automatically\n  apply the `B.to_A` projection and then recursively the `A.proj` projection in the lemmas it\n  generates. If you want to get both the `foo_proj` and `foo_to_A` simp lemmas, you can use\n  `@[simps, simps to_A]`.\n* Running `initialize_simps_projections my_struc` without arguments is not necessary, it has the\n  same effect if you just add `@[simps]` to a declaration.\n* If you do anything to change the default projections, make sure to call either `@[simps]` or\n  `initialize_simps_projections` in the same file as the structure declaration. Otherwise, you might\n  have a file that imports the structure, but not your custom projections.\n\nSome common uses:\n* If you define a new homomorphism-like structure (like `mul_hom`) you can just run\n  `initialize_simps_projections` after defining the `has_coe_to_fun` instance\n  ```\n    instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (mul_hom M N) := ...\n    initialize_simps_projections mul_hom (to_fun \u2192 apply)\n  ```\n  This will generate `foo_apply` lemmas for each declaration `foo`.\n* If you prefer `coe_foo` lemmas that state equalities between functions, use\n  `initialize_simps_projections mul_hom (to_fun \u2192 coe as_prefix)`\n  In this case you have to use `@[simps {fully_applied := ff}]` or equivalently `@[simps as_fn]`\n  whenever you call `@[simps]`.\n* You can also initialize to use both, in which case you have to choose which one to use by default,\n  by using either of the following\n  ```\n    initialize_simps_projections mul_hom (to_fun \u2192 apply, to_fun \u2192 coe, -coe as_prefix)\n    initialize_simps_projections mul_hom (to_fun \u2192 apply, to_fun \u2192 coe as_prefix, -apply)\n  ```\n  In the first case, you can get both lemmas using `@[simps, simps coe as_fn]` and in the second\n  case you can get both lemmas using `@[simps as_fn, simps apply]`.\n* If your new homomorphism-like structure extends another structure (without `old_structure_cmd`)\n  (like `rel_embedding`), then you have to specify explicitly that you want to use a coercion\n  as a custom projection. For example\n  ```\n    def rel_embedding.simps.apply (h : r \u21aar s) : \u03b1 \u2192 \u03b2 := h\n    initialize_simps_projections rel_embedding (to_embedding_to_fun \u2192 apply, -to_embedding)\n  ```\n* If you have an isomorphism-like structure (like `equiv`) you often want to define a custom\n  projection for the inverse:\n  ```\n    def equiv.simps.symm_apply (e : \u03b1 \u2243 \u03b2) : \u03b2 \u2192 \u03b1 := e.symm\n    initialize_simps_projections equiv (to_fun \u2192 apply, inv_fun \u2192 symm_apply)\n  ```\n-/\n@[user_command] meta def initialize_simps_projections_cmd\n  (_ : parse $ tk \"initialize_simps_projections\") : parser unit := do\n  env \u2190 get_env,\n  trc \u2190 is_some <$> (tk \"?\")?,\n  ns \u2190 (prod.mk <$> ident <*> (tk \"(\" >> sep_by (tk \",\") simps_parse_rule <* tk \")\")?)*,\n  ns.mmap' $ \u03bb data, do\n    nm \u2190 resolve_constant data.1,\n    simps_get_raw_projections env nm tt (data.2.get_or_else []) trc\n\nadd_tactic_doc\n{ name                     := \"initialize_simps_projections\",\n  category                 := doc_category.cmd,\n  decl_names               := [`initialize_simps_projections_cmd],\n  tags                     := [\"simplification\"] }\n\n/--\n  Configuration options for the `@[simps]` attribute.\n  * `attrs` specifies the list of attributes given to the generated lemmas. Default: ``[`simp]``.\n    The attributes can be either basic attributes, or user attributes without parameters.\n    There are two attributes which `simps` might add itself:\n    * If ``[`simp]`` is in the list, then ``[`_refl_lemma]`` is added automatically if appropriate.\n    * If the definition is marked with `@[to_additive ...]` then all generated lemmas are marked\n      with `@[to_additive]`. This is governed by the `add_additive` configuration option.\n  * if `simp_rhs` is `tt` then the right-hand-side of the generated lemmas will be put in\n    simp-normal form. More precisely: `dsimp, simp` will be called on all these expressions.\n    See note [dsimp, simp].\n  * `type_md` specifies how aggressively definitions are unfolded in the type of expressions\n    for the purposes of finding out whether the type is a function type.\n    Default: `instances`. This will unfold coercion instances (so that a coercion to a function type\n    is recognized as a function type), but not declarations like `set`.\n  * `rhs_md` specifies how aggressively definition in the declaration are unfolded for the purposes\n    of finding out whether it is a constructor.\n    Default: `none`\n    Exception: `@[simps]` will automatically add the options\n    `{rhs_md := semireducible, simp_rhs := tt}` if the given definition is not a constructor with\n    the given reducibility setting for `rhs_md`.\n  * If `fully_applied` is `ff` then the generated `simp` lemmas will be between non-fully applied\n    terms, i.e. equalities between functions. This does not restrict the recursive behavior of\n    `@[simps]`, so only the \"final\" projection will be non-fully applied.\n    However, it can be used in combination with explicit field names, to get a partially applied\n    intermediate projection.\n  * The option `not_recursive` contains the list of names of types for which `@[simps]` doesn't\n    recursively apply projections. For example, given an equivalence `\u03b1 \u00d7 \u03b2 \u2243 \u03b2 \u00d7 \u03b1` one usually\n    wants to only apply the projections for `equiv`, and not also those for `\u00d7`. This option is\n    only relevant if no explicit projection names are given as argument to `@[simps]`.\n  * The option `trace` is set to `tt` when you write `@[simps?]`. In this case, the attribute will\n    print all generated lemmas. It is almost the same as setting the option `trace.simps.verbose`,\n    except that it doesn't print information about the found projections.\n  * if `add_additive` is `some nm` then `@[to_additive]` is added to the generated lemma. This\n    option is automatically set to `tt` when the original declaration was tagged with\n    `@[to_additive, simps]` (in that order), where `nm` is the additive name of the original\n    declaration.\n-/\n@[derive [has_reflect, inhabited]] structure simps_cfg :=\n(attrs         := [`simp])\n(simp_rhs      := ff)\n(type_md       := transparency.instances)\n(rhs_md        := transparency.none)\n(fully_applied := tt)\n(not_recursive := [`prod, `pprod])\n(trace         := ff)\n(add_additive  := @none name)\n\n/-- A common configuration for `@[simps]`: generate equalities between functions instead equalities\n  between fully applied expressions. -/\ndef as_fn : simps_cfg := {fully_applied := ff}\n/-- A common configuration for `@[simps]`: don't tag the generated lemmas with `@[simp]`. -/\ndef lemmas_only : simps_cfg := {attrs := []}\n\n/--\n  Get the projections of a structure used by `@[simps]` applied to the appropriate arguments.\n  Returns a list of tuples\n  ```\n  (corresponding right-hand-side, given projection name, projection expression, projection numbers,\n    used by default, is prefix)\n  ```\n  (where all fields except the first are packed in a `projection_data` structure)\n  one for each projection. The given projection name is the name for the projection used by the user\n  used to generate (and parse) projection names. For example, in the structure\n\n  Example 1: ``simps_get_projection_exprs env `(\u03b1 \u00d7 \u03b2) `(\u27e8x, y\u27e9)`` will give the output\n  ```\n    [(`(x), `fst, `(@prod.fst.{u v} \u03b1 \u03b2), [0], tt, ff),\n     (`(y), `snd, `(@prod.snd.{u v} \u03b1 \u03b2), [1], tt, ff)]\n  ```\n\n  Example 2: ``simps_get_projection_exprs env `(\u03b1 \u2243 \u03b1) `(\u27e8id, id, \u03bb _, rfl, \u03bb _, rfl\u27e9)``\n  will give the output\n  ```\n    [(`(id), `apply, `(coe), [0], tt, ff),\n     (`(id), `symm_apply, `(\u03bb f, \u21d1f.symm), [1], tt, ff),\n     ...,\n     ...]\n  ```\n-/\nmeta def simps_get_projection_exprs (e : environment) (tgt : expr)\n  (rhs : expr) (cfg : simps_cfg) : tactic $ list $ expr \u00d7 projection_data := do\n  let params := get_app_args tgt, -- the parameters of the structure\n  (params.zip $ (get_app_args rhs).take params.length).mmap' (\u03bb \u27e8a, b\u27e9, is_def_eq a b)\n    <|> fail \"unreachable code (1)\",\n  let str := tgt.get_app_fn.const_name,\n  let rhs_args := (get_app_args rhs).drop params.length, -- the fields of the object\n  (raw_univs, proj_data) \u2190 simps_get_raw_projections e str ff [] cfg.trace,\n  let univs := raw_univs.zip tgt.get_app_fn.univ_levels,\n  let new_proj_data : list $ expr \u00d7 projection_data := proj_data.map $\n    \u03bb proj, (rhs_args.inth proj.proj_nrs.head,\n      { expr := (proj.expr.instantiate_univ_params univs).instantiate_lambdas_or_apps params,\n        proj_nrs := proj.proj_nrs.tail,\n        .. proj }),\n  return new_proj_data\n\n/-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`,\n  `args` is the list of local constants occurring, and `univs` is the list of universe variables. -/\nmeta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr)\n  (univs : list name) (cfg : simps_cfg) : tactic unit := do\n  when_tracing `simps.debug trace!\n    \"[simps] > Planning to add the equality\\n        > {lhs} = ({rhs} : {type})\",\n  lvl \u2190 get_univ_level type,\n  -- simplify `rhs` if `cfg.simp_rhs` is true\n  (rhs, prf) \u2190 do { guard cfg.simp_rhs,\n    rhs' \u2190 rhs.dsimp {fail_if_unchanged := ff},\n    when_tracing `simps.debug $ when (rhs \u2260 rhs') trace!\n      \"[simps] > `dsimp` simplified rhs to\\n        > {rhs'}\",\n    (rhsprf1, rhsprf2, ns) \u2190 rhs'.simp {fail_if_unchanged := ff},\n    when_tracing `simps.debug $ when (rhs' \u2260 rhsprf1) trace!\n      \"[simps] > `simp` simplified rhs to\\n        > {rhsprf1}\",\n    return (prod.mk rhsprf1 rhsprf2) }\n    <|> return (rhs, const `eq.refl [lvl] type lhs),\n  let eq_ap := const `eq [lvl] type lhs rhs,\n  decl_name \u2190 get_unused_decl_name nm,\n  let decl_type := eq_ap.pis args,\n  let decl_value := prf.lambdas args,\n  let decl := declaration.thm decl_name univs decl_type (pure decl_value),\n  when cfg.trace trace!\n    \"[simps] > adding projection {decl_name}:\\n        > {decl_type}\",\n  decorate_error (\"Failed to add projection lemma \" ++ decl_name.to_string ++ \". Nested error:\") $\n    add_decl decl,\n  b \u2190 succeeds $ is_def_eq lhs rhs,\n  when (b \u2227 `simp \u2208 cfg.attrs) (set_basic_attribute `_refl_lemma decl_name tt),\n  cfg.attrs.mmap' $ \u03bb nm, set_attribute nm decl_name tt,\n  when cfg.add_additive.is_some $\n    to_additive.attr.set decl_name \u27e8ff, cfg.trace, cfg.add_additive.iget, none, tt\u27e9 tt\n\n/-- Derive lemmas specifying the projections of the declaration.\n  If `todo` is non-empty, it will generate exactly the names in `todo`.\n  `to_apply` is non-empty after a custom projection that is a composition of multiple projections\n  was just used. In that case we need to apply these projections before we continue changing lhs. -/\nmeta def simps_add_projections : \u03a0 (e : environment) (nm : name)\n  (type lhs rhs : expr) (args : list expr) (univs : list name) (must_be_str : bool)\n  (cfg : simps_cfg) (todo : list string) (to_apply : list \u2115), tactic unit\n| e nm type lhs rhs args univs must_be_str cfg todo to_apply := do\n  -- we don't want to unfold non-reducible definitions (like `set`) to apply more arguments\n  when_tracing `simps.debug trace!\n    \"[simps] > Type of the expression before normalizing: {type}\",\n  (type_args, tgt) \u2190 open_pis_whnf type cfg.type_md,\n  when_tracing `simps.debug trace!\"[simps] > Type after removing pi's: {tgt}\",\n  tgt \u2190 whnf tgt,\n  when_tracing `simps.debug trace!\"[simps] > Type after reduction: {tgt}\",\n  let new_args := args ++ type_args,\n  let lhs_ap := lhs.instantiate_lambdas_or_apps type_args,\n  let rhs_ap := rhs.instantiate_lambdas_or_apps type_args,\n  let str := tgt.get_app_fn.const_name,\n  /- We want to generate the current projection if it is in `todo` -/\n  let todo_next := todo.filter (\u2260 \"\"),\n  /- Don't recursively continue if `str` is not a structure or if the structure is in\n    `not_recursive`. -/\n  if e.is_structure str \u2227 \u00ac(todo = [] \u2227 str \u2208 cfg.not_recursive \u2227 \u00acmust_be_str) then do\n    [intro] \u2190 return $ e.constructors_of str | fail \"unreachable code (3)\",\n    rhs_whnf \u2190 whnf rhs_ap cfg.rhs_md,\n    (rhs_ap, todo_now) \u2190 -- `todo_now` means that we still have to generate the current simp lemma\n      if \u00ac is_constant_of rhs_ap.get_app_fn intro \u2227\n        is_constant_of rhs_whnf.get_app_fn intro then\n      /- If this was a desired projection, we want to apply it before taking the whnf.\n        However, if the current field is an eta-expansion (see below), we first want\n        to eta-reduce it and only then construct the projection.\n        This makes the flow of this function messy. -/\n      when (\"\" \u2208 todo \u2227 to_apply = []) (if cfg.fully_applied then\n        simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else\n        simps_add_projection nm type lhs rhs args univs cfg) >>\n      return (rhs_whnf, ff) else\n      return (rhs_ap, \"\" \u2208 todo \u2227 to_apply = []),\n    if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application\n      proj_info \u2190 simps_get_projection_exprs e tgt rhs_ap cfg,\n      when_tracing `simps.debug trace!\"[simps] > Raw projection information:\\n  {proj_info}\",\n      eta \u2190 rhs_ap.is_eta_expansion, -- check whether `rhs_ap` is an eta-expansion\n      let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap`\n      /- As a special case, we want to automatically generate the current projection if `rhs_ap`\n        was an eta-expansion. Also, when this was a desired projection, we need to generate the\n        current projection if we haven't done it above. -/\n      when (todo_now \u2228 (todo = [] \u2227 eta.is_some \u2227 to_apply = [])) $\n        if cfg.fully_applied then\n          simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else\n          simps_add_projection nm type lhs rhs args univs cfg,\n      /- If we are in the middle of a composite projection. -/\n      when (to_apply \u2260 []) $ do\n      { \u27e8new_rhs, proj, proj_expr, proj_nrs, is_default, is_prefix\u27e9 \u2190\n          return $ proj_info.inth to_apply.head,\n        new_type \u2190 infer_type new_rhs,\n        when_tracing `simps.debug\n          trace!\"[simps] > Applying a custom composite projection. Current lhs:\n        >  {lhs_ap}\",\n        simps_add_projections e nm new_type lhs_ap new_rhs new_args univs ff cfg todo\n          to_apply.tail },\n      /- We stop if no further projection is specified or if we just reduced an eta-expansion and we\n      automatically choose projections -/\n      when \u00ac(to_apply \u2260 [] \u2228 todo = [\"\"] \u2228 (eta.is_some \u2227 todo = [])) $ do\n        let projs : list name := proj_info.map $ \u03bb x, x.snd.name,\n        let todo := if to_apply = [] then todo_next else todo,\n        -- check whether all elements in `todo` have a projection as prefix\n        guard (todo.all $ \u03bb x, projs.any $ \u03bb proj, (\"_\" ++ proj.last).is_prefix_of x) <|>\n          let x := (todo.find $ \u03bb x, projs.all $ \u03bb proj, \u00ac (\"_\" ++ proj.last).is_prefix_of x).iget,\n            simp_lemma := nm.append_suffix x,\n            needed_proj := (x.split_on '_').tail.head in\n          fail!\n\"Invalid simp lemma {simp_lemma}. Structure {str} does not have projection {needed_proj}.\nThe known projections are:\n  {projs}\nYou can also see this information by running\n  `initialize_simps_projections? {str}`.\nNote: these projection names might not correspond to the projection names of the structure.\",\n        proj_info.mmap_with_index' $\n          \u03bb proj_nr \u27e8new_rhs, proj, proj_expr, proj_nrs, is_default, is_prefix\u27e9, do\n          new_type \u2190 infer_type new_rhs,\n          let new_todo :=\n            todo.filter_map $ \u03bb x, x.get_rest (\"_\" ++ proj.last),\n          -- we only continue with this field if it is non-propositional or mentioned in todo\n          when ((is_default \u2227 todo = []) \u2228 new_todo \u2260 []) $ do\n            let new_lhs := proj_expr.instantiate_lambdas_or_apps [lhs_ap],\n            let new_nm := nm.append_to_last proj.last is_prefix,\n            let new_cfg := { add_additive := cfg.add_additive.map $\n              \u03bb nm, nm.append_to_last (to_additive.guess_name proj.last) is_prefix, ..cfg },\n            when_tracing `simps.debug trace!\"[simps] > Recursively add projections for:\n        >  {new_lhs}\",\n            simps_add_projections e new_nm new_type new_lhs new_rhs new_args univs\n              ff new_cfg new_todo proj_nrs\n    -- if I'm about to run into an error, try to set the transparency for `rhs_md` higher.\n    else if cfg.rhs_md = transparency.none \u2227 (must_be_str \u2228 todo_next \u2260 [] \u2228 to_apply \u2260 []) then do\n      when cfg.trace trace!\n        \"[simps] > The given definition is not a constructor application:\n        >   {rhs_ap}\n        > Retrying with the options {{ rhs_md := semireducible, simp_rhs := tt}.\",\n      simps_add_projections e nm type lhs rhs args univs must_be_str\n        { rhs_md := semireducible, simp_rhs := tt, ..cfg} todo to_apply\n    else do\n      when (to_apply \u2260 []) $\n        fail!\"Invalid simp lemma {nm}.\nThe given definition is not a constructor application:\\n  {rhs_ap}\",\n      when must_be_str $\n        fail!\"Invalid `simps` attribute. The body is not a constructor application:\\n  {rhs_ap}\",\n      when (todo_next \u2260 []) $\n        fail!\"Invalid simp lemma {nm.append_suffix todo_next.head}.\nThe given definition is not a constructor application:\\n  {rhs_ap}\",\n      if cfg.fully_applied then\n        simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else\n        simps_add_projection nm type lhs rhs args univs cfg\n  else do\n    when must_be_str $\n      fail!\"Invalid `simps` attribute. Target {str} is not a structure\",\n    when (todo_next \u2260 [] \u2227 str \u2209 cfg.not_recursive) $\n        let first_todo := todo_next.head in\n        fail!\"Invalid simp lemma {nm.append_suffix first_todo}.\nProjection {(first_todo.split_on '_').tail.head} doesn't exist, because target is not a structure.\",\n    if cfg.fully_applied then\n      simps_add_projection nm tgt lhs_ap rhs_ap new_args univs cfg else\n      simps_add_projection nm type lhs rhs args univs cfg\n\n/-- `simps_tac` derives `simp` lemmas for all (nested) non-Prop projections of the declaration.\n  If `todo` is non-empty, it will generate exactly the names in `todo`.\n  If `short_nm` is true, the generated names will only use the last projection name.\n  If `trc` is true, trace as if `trace.simps.verbose` is true. -/\nmeta def simps_tac (nm : name) (cfg : simps_cfg := {}) (todo : list string := []) (trc := ff) :\n  tactic unit := do\n  e \u2190 get_env,\n  d \u2190 e.get nm,\n  let lhs : expr := const d.to_name d.univ_levels,\n  let todo := todo.erase_dup.map $ \u03bb proj, \"_\" ++ proj,\n  let cfg := { trace := cfg.trace || is_trace_enabled_for `simps.verbose || trc, ..cfg },\n  b \u2190 has_attribute' `to_additive nm,\n  cfg \u2190 if b then do\n  { dict \u2190 to_additive.aux_attr.get_cache,\n    when cfg.trace\n      trace!\"[simps] > @[to_additive] will be added to all generated lemmas.\",\n    return { add_additive := dict.find nm, ..cfg } } else\n    return cfg,\n  simps_add_projections e nm d.type lhs d.value [] d.univ_params tt cfg todo []\n\n/-- The parser for the `@[simps]` attribute. -/\nmeta def simps_parser : parser (bool \u00d7 list string \u00d7 simps_cfg) := do\n/- note: we don't check whether the user has written a nonsense namespace in an argument. -/\nprod.mk <$> is_some <$> (tk \"?\")? <*>\n  (prod.mk <$> many (name.last <$> ident) <*>\n  (do some e \u2190 parser.pexpr? | return {}, eval_pexpr simps_cfg e))\n\n/--\nThe `@[simps]` attribute automatically derives lemmas specifying the projections of this\ndeclaration.\n\nExample:\n```lean\n@[simps] def foo : \u2115 \u00d7 \u2124 := (1, 2)\n```\nderives two `simp` lemmas:\n```lean\n@[simp] lemma foo_fst : foo.fst = 1\n@[simp] lemma foo_snd : foo.snd = 2\n```\n\n* It does not derive `simp` lemmas for the prop-valued projections.\n* It will automatically reduce newly created beta-redexes, but will not unfold any definitions.\n* If the structure has a coercion to either sorts or functions, and this is defined to be one\n  of the projections, then this coercion will be used instead of the projection.\n* If the structure is a class that has an instance to a notation class, like `has_mul`, then this\n  notation is used instead of the corresponding projection.\n* You can specify custom projections, by giving a declaration with name\n  `{structure_name}.simps.{projection_name}`. See Note [custom simps projection].\n\n  Example:\n  ```lean\n  def equiv.simps.inv_fun (e : \u03b1 \u2243 \u03b2) : \u03b2 \u2192 \u03b1 := e.symm\n  @[simps] def equiv.trans (e\u2081 : \u03b1 \u2243 \u03b2) (e\u2082 : \u03b2 \u2243 \u03b3) : \u03b1 \u2243 \u03b3 :=\n  \u27e8e\u2082 \u2218 e\u2081, e\u2081.symm \u2218 e\u2082.symm\u27e9\n  ```\n  generates\n  ```\n  @[simp] lemma equiv.trans_to_fun : \u2200 {\u03b1 \u03b2 \u03b3} (e\u2081 e\u2082) (a : \u03b1), \u21d1(e\u2081.trans e\u2082) a = (\u21d1e\u2082 \u2218 \u21d1e\u2081) a\n  @[simp] lemma equiv.trans_inv_fun : \u2200 {\u03b1 \u03b2 \u03b3} (e\u2081 e\u2082) (a : \u03b3),\n    \u21d1((e\u2081.trans e\u2082).symm) a = (\u21d1(e\u2081.symm) \u2218 \u21d1(e\u2082.symm)) a\n  ```\n\n* You can specify custom projection names, by specifying the new projection names using\n  `initialize_simps_projections`.\n  Example: `initialize_simps_projections equiv (to_fun \u2192 apply, inv_fun \u2192 symm_apply)`.\n  See `initialize_simps_projections_cmd` for more information.\n\n* If one of the fields itself is a structure, this command will recursively create\n  `simp` lemmas for all fields in that structure.\n  * Exception: by default it will not recursively create `simp` lemmas for fields in the structures\n    `prod` and `pprod`. You can give explicit projection names or change the value of\n    `simps_cfg.not_recursive` to override this behavior.\n\n  Example:\n  ```lean\n  structure my_prod (\u03b1 \u03b2 : Type*) := (fst : \u03b1) (snd : \u03b2)\n  @[simps] def foo : prod \u2115 \u2115 \u00d7 my_prod \u2115 \u2115 := \u27e8\u27e81, 2\u27e9, 3, 4\u27e9\n  ```\n  generates\n  ```lean\n  @[simp] lemma foo_fst : foo.fst = (1, 2)\n  @[simp] lemma foo_snd_fst : foo.snd.fst = 3\n  @[simp] lemma foo_snd_snd : foo.snd.snd = 4\n  ```\n\n* You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified\n  projections.\n* Recursive projection names can be specified using `proj1_proj2_proj3`.\n  This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`.\n\n  Example:\n  ```lean\n  structure my_prod (\u03b1 \u03b2 : Type*) := (fst : \u03b1) (snd : \u03b2)\n  @[simps fst fst_fst snd] def foo : prod \u2115 \u2115 \u00d7 my_prod \u2115 \u2115 := \u27e8\u27e81, 2\u27e9, 3, 4\u27e9\n  ```\n  generates\n  ```lean\n  @[simp] lemma foo_fst : foo.fst = (1, 2)\n  @[simp] lemma foo_fst_fst : foo.fst.fst = 1\n  @[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4}\n  ```\n* If one of the values is an eta-expanded structure, we will eta-reduce this structure.\n\n  Example:\n  ```lean\n  structure equiv_plus_data (\u03b1 \u03b2) extends \u03b1 \u2243 \u03b2 := (data : bool)\n  @[simps] def bar {\u03b1} : equiv_plus_data \u03b1 \u03b1 := { data := tt, ..equiv.refl \u03b1 }\n  ```\n  generates the following:\n  ```lean\n  @[simp] lemma bar_to_equiv : \u2200 {\u03b1 : Sort*}, bar.to_equiv = equiv.refl \u03b1\n  @[simp] lemma bar_data : \u2200 {\u03b1 : Sort*}, bar.data = tt\n  ```\n  This is true, even though Lean inserts an eta-expanded version of `equiv.refl \u03b1` in the\n  definition of `bar`.\n* For configuration options, see the doc string of `simps_cfg`.\n* The precise syntax is `('simps' ident* e)`, where `e` is an expression of type `simps_cfg`.\n* `@[simps]` reduces let-expressions where necessary.\n* When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the\n  lemmas it generates. The same can be achieved by using `@[simps?]`, except that in this case it\n  will not print projection information.\n* Use `@[to_additive, simps]` to apply both `to_additive` and `simps` to a definition, making sure\n  that `simps` comes after `to_additive`. This will also generate the additive versions of all\n  `simp` lemmas.\n-/\n/- If one of the fields is a partially applied constructor, we will eta-expand it\n  (this likely never happens, so is not included in the official doc). -/\n@[user_attribute] meta def simps_attr : user_attribute unit (bool \u00d7 list string \u00d7 simps_cfg) :=\n{ name := `simps,\n  descr := \"Automatically derive lemmas specifying the projections of this declaration.\",\n  parser := simps_parser,\n  after_set := some $\n    \u03bb n _ persistent, do\n      guard persistent <|> fail \"`simps` currently cannot be used as a local attribute\",\n      (trc, todo, cfg) \u2190 simps_attr.get_param n,\n      simps_tac n cfg todo trc }\n\nadd_tactic_doc\n{ name                     := \"simps\",\n  category                 := doc_category.attr,\n  decl_names               := [`simps_attr],\n  tags                     := [\"simplification\"] }\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/simps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.09670579720114002, "lm_q1q2_score": 0.043458872972235094}}
{"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 {\u03b1 : Type*} {xs : list \u03b1}\n\ninstance : inhabited (buffer \u03b1) := \u27e8nil\u27e9\n\n@[ext]\nlemma ext : \u2200 {b\u2081 b\u2082 : buffer \u03b1}, to_list b\u2081 = to_list b\u2082 \u2192 b\u2081 = b\u2082\n| \u27e8n\u2081, a\u2081\u27e9 \u27e8n\u2082, a\u2082\u27e9 h := begin\n  simp [to_list, to_array] at h,\n  have e : n\u2081 = n\u2082 :=\n    by rw [\u2190array.to_list_length a\u2081, \u2190array.to_list_length a\u2082, h],\n  subst e,\n  have h : a\u2081 == a\u2082.to_list.to_array := h \u25b8 a\u2081.to_list_to_array.symm,\n  rw eq_of_heq (h.trans a\u2082.to_list_to_array)\nend\n\nlemma ext_iff {b\u2081 b\u2082 : buffer \u03b1} : b\u2081 = b\u2082 \u2194 to_list b\u2081 = to_list b\u2082 :=\n\u27e8\u03bb h, h \u25b8 rfl, ext\u27e9\n\nlemma size_eq_zero_iff {b : buffer \u03b1} : b.size = 0 \u2194 b = nil :=\nbegin\n  rcases b with \u27e8_|n, \u27e8a\u27e9\u27e9,\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 \u03b1).size = 0 :=\nby rw size_eq_zero_iff\n\n@[simp] lemma to_list_nil : to_list (@nil \u03b1) = [] := rfl\n\ninstance (\u03b1) [decidable_eq \u03b1] : decidable_eq (buffer \u03b1) :=\nby tactic.mk_dec_eq_instance\n\n@[simp]\nlemma to_list_append_list {b : buffer \u03b1} :\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 \u03b1) : 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 \u03b1) : 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 \u03b1) : b.to_array.to_list = b.to_list :=\nby { cases b, simp [to_list] }\n\n@[simp] lemma append_list_nil (b : buffer \u03b1) : b.append_list [] = b := rfl\n\nlemma to_buffer_cons (c : \u03b1) (l : list \u03b1) :\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 \u03b1) (a : \u03b1) : (b.push_back a).size = b.size + 1 :=\nby { cases b, simp [size, push_back] }\n\n@[simp] lemma size_append_list (b : buffer \u03b1) (l : list \u03b1) :\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 \u03b1) : 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 \u03b1) : b.to_list.length = b.size :=\nby rw [\u2190to_buffer_to_list b, to_list_to_buffer, size_to_buffer]\n\nlemma size_singleton (a : \u03b1) : [a].to_buffer.size = 1 := rfl\n\nlemma read_push_back_left (b : buffer \u03b1) (a : \u03b1) {i : \u2115} (h : i < b.size) :\n  (b.push_back a).read \u27e8i, by { convert nat.lt_succ_of_lt h, simp }\u27e9 = b.read \u27e8i, h\u27e9 :=\nby { cases b, convert array.read_push_back_left _, simp }\n\n@[simp] lemma read_push_back_right (b : buffer \u03b1) (a : \u03b1) :\n  (b.push_back a).read \u27e8b.size, by simp\u27e9 = a :=\nby { cases b, convert array.read_push_back_right }\n\nlemma read_append_list_left' (b : buffer \u03b1) (l : list \u03b1) {i : \u2115}\n  (h : i < (b.append_list l).size) (h' : i < b.size) :\n  (b.append_list l).read \u27e8i, h\u27e9 = b.read \u27e8i, h'\u27e9 :=\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 \u27e8i, h\u27e9 =\n      read ((push_back b hd).append_list tl) \u27e8i, hb\u27e9 := rfl,\n    simp [this, hl _ hb hb', read_push_back_left _ _ h'] }\nend\n\nlemma read_append_list_left (b : buffer \u03b1) (l : list \u03b1) {i : \u2115} (h : i < b.size) :\n  (b.append_list l).read \u27e8i, by simpa using nat.lt_add_right _ _ _ h\u27e9 = b.read \u27e8i, h\u27e9 :=\nread_append_list_left' b l _ h\n\n@[simp] lemma read_append_list_right (b : buffer \u03b1) (l : list \u03b1) {i : \u2115} (h : i < l.length) :\n  (b.append_list l).read \u27e8b.size + i, by simp [h]\u27e9 = 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 \u03b1) {i : \u2115} (h : i < l.to_buffer.size) (h' : i < l.length) :\n  l.to_buffer.read \u27e8i, h\u27e9 = 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 \u27e8i, hi\u27e9 = _,\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 \u03b1) (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 \u03b1) {i : \u2115} (h h') :\n  b.to_list.nth_le i h = b.read \u27e8i, h'\u27e9 :=\nbegin\n  have : b.to_list.to_buffer.read \u27e8i, (by simpa using h')\u27e9 = b.read \u27e8i, h'\u27e9,\n  { congr' 1; simp [fin.heq_ext_iff] },\n  simp [\u2190this]\nend\n\nlemma nth_le_to_list (b : buffer \u03b1) {i : \u2115} (h) :\n  b.to_list.nth_le i h = b.read \u27e8i, by simpa using h\u27e9 :=\nnth_le_to_list' _ _ _\n\nlemma read_eq_nth_le_to_list (b : buffer \u03b1) (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 : \u03b1) : [c].to_buffer.read \u27e80, by simp\u27e9 = 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 (\u03b1 : Type*) : list \u03b1 \u2243 buffer \u03b1 :=\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 \u03b1) (i : \u2115) : tactic \u03b1 :=\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 \u03b1` 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\u2080 u\u2081 v\u2080 v\u2081 v\u2082 w w\u2080 w\u2081\nvariables {s : Type u\u2080} {s' : Type u\u2081} {r r' w w' : Type*}\n\n/-- Given a universe polymorphic type family `M.{u} : Type u\u2081 \u2192 Type\nu\u2082`, this class convert between instantiations, from\n`M.{u} : Type u\u2081 \u2192 Type u\u2082` to `M.{v} : Type v\u2081 \u2192 Type v\u2082` and back -/\nclass uliftable (f : Type u\u2080 \u2192 Type u\u2081) (g : Type v\u2080 \u2192 Type v\u2081) :=\n(congr [] {\u03b1 \u03b2} : \u03b1 \u2243 \u03b2 \u2192 f \u03b1 \u2243 g \u03b2)\n\nnamespace uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} \u03b1` and lifts it to M.{max u v} (ulift.{v} \u03b1) -/\n@[reducible]\ndef up {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} : f \u03b1 \u2192 g (ulift \u03b1) :=\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} \u03b1)` and lowers it to `M.{u} \u03b1` -/\n@[reducible]\ndef down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} : g (ulift \u03b1) \u2192 f \u03b1 :=\n(uliftable.congr f g equiv.ulift.symm).inv_fun\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v\u2080 \u2192 Type v\u2081) (G : Type (max v\u2080 u\u2080) \u2192 Type u\u2081)\n  [uliftable F G] [monad G] {\u03b1 \u03b2}\n  (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\nup x >>= f \u2218 ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type v\u2080 \u2192 Type v\u2081}\n  [L : uliftable G F] [monad F] {\u03b1 \u03b2}\n  (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n@down.{v\u2080 v\u2081 (max u\u2080 v\u2080)} G F L \u03b2 $ x >>= @up.{v\u2080 v\u2081 (max u\u2080 v\u2080)} G F L \u03b2 \u2218 f\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u\u2080 \u2192 Type u\u2081} {G : Type.{max u\u2080 v\u2080} \u2192 Type v\u2081} [inst : uliftable F G]\n  [functor G] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\nfunctor.map (f \u2218 ulift.down) (up x)\n\n/-- map function that moves down universes -/\ndef down_map {F : Type.{max u\u2080 v\u2080} \u2192 Type u\u2081} {G : Type u\u2080 \u2192 Type v\u2081} [inst : uliftable G F]\n  [functor F] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\ndown (functor.map (ulift.up \u2218 f) x : F (ulift \u03b2))\n\n@[simp]\nlemma up_down  {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} (x : g (ulift \u03b1)) : up (down x : f \u03b1) = x :=\n(uliftable.congr f g equiv.ulift.symm).right_inv _\n\n@[simp]\nlemma down_up  {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} (x : f \u03b1) : 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 := \u03bb \u03b1 \u03b2 F, F }\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {m : Type u\u2080 \u2192 Type v\u2080} {m' : Type u\u2081 \u2192 Type v\u2081}\n  [uliftable m m']\n  (F : s \u2243 s') :\n  uliftable (state_t s m) (state_t s' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 G, state_t.equiv $ equiv.Pi_congr F $\n      \u03bb _, 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 \u2243 s') :\n  uliftable (reader_t s m) (reader_t s' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 G, reader_t.equiv $ equiv.Pi_congr F $\n      \u03bb _, 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 \u2243 r') :\n  uliftable (cont_t r m) (cont_t r' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2, 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 \u2243 w') :\n  uliftable (writer_t w m) (writer_t w' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 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\u00ebl Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Ya\u00ebl 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 \u2194 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 \u2190 Eq.trans_ne\n#align eq.trans_ne Eq.trans_ne\n\nalias ne_of_ne_of_eq \u2190 Ne.trans_eq\n#align ne.trans_eq Ne.trans_eq\n\nvariable {\u03b1 : Sort _} {p q r : Prop} [Decidable p] [Decidable q] {a b c : \u03b1}\n\n#print dite_dite_distrib_left /-\ntheorem dite_dite_distrib_left {a : p \u2192 \u03b1} {b : \u00acp \u2192 q \u2192 \u03b1} {c : \u00acp \u2192 \u00acq \u2192 \u03b1} :\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 \u2192 q \u2192 \u03b1} {b : p \u2192 \u00acq \u2192 \u03b1} {c : \u00acp \u2192 \u03b1} :\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 : \u03b1} {b : q \u2192 \u03b1} {c : \u00acq \u2192 \u03b1} :\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 \u2192 \u03b1} {b : \u00acq \u2192 \u03b1} {c : \u03b1} :\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 \u2192 \u03b1} {b : \u00acp \u2192 \u03b1} {c : \u00acp \u2192 \u03b1} :\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 \u2192 \u03b1} {b : p \u2192 \u03b1} {c : \u00acp \u2192 \u03b1} :\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 \u2192 Prop} : (\u2200 p, f p) \u2194 f True \u2227 f False :=\n  \u27e8fun h => \u27e8h _, h _\u27e9, by\n    rintro \u27e8h\u2081, h\u2080\u27e9 p\n    by_cases hp : p <;> simp only [hp] <;> assumption\u27e9\n#align Prop.forall Prop.forall\n-/\n\n#print Prop.exists /-\ntheorem Prop.exists {f : Prop \u2192 Prop} : (\u2203 p, f p) \u2194 f True \u2228 f False :=\n  \u27e8fun \u27e8p, h\u27e9 => by refine' (em p).imp _ _ <;> intro H <;> convert h <;> simp [H], by\n    rintro (h | h) <;> exact \u27e8_, h\u27e9\u27e9\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) 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.Eqns\nimport Lean.Meta.Tactic.Split\nimport Lean.Meta.Tactic.Apply\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Structural.Basic\n\nnamespace Lean.Elab\nopen Meta\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 applyRefl mvarId; return true catch _ => return false\n\n/-- Delta reduce the equation left-hand-side -/\ndef deltaLHS (mvarId : MVarId) : MetaM MVarId := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) \u2190 target.eq? | throwTacticEx `deltaLHS mvarId \"equality expected\"\n  let some lhs \u2190 delta? lhs | throwTacticEx `deltaLHS mvarId \"failed to delta reduce lhs\"\n  replaceTargetDefEq mvarId (\u2190 mkEq lhs rhs)\n\ndef deltaRHS? (mvarId : MVarId) (declName : Name) : MetaM (Option MVarId) := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) \u2190 target.eq? | throwTacticEx `deltaRHS mvarId \"equality expected\"\n  let some rhs \u2190 delta? rhs (. == declName) | return none\n  replaceTargetDefEq mvarId (\u2190 mkEq lhs rhs)\n\nprivate partial def whnfAux (e : Expr) : MetaM Expr := do\n  let e \u2190 whnfR e\n  match e with\n  | Expr.proj _ _ s _ => e.updateProj! (\u2190 whnfAux s)\n  | _ => e\n\n/-- Apply `whnfR` to lhs, return `none` if `lhs` was not modified -/\ndef whnfReducibleLHS? (mvarId : MVarId) : MetaM (Option MVarId) := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) \u2190 target.eq? | throwTacticEx `whnfReducibleLHS mvarId \"equality expected\"\n  let lhs' \u2190 whnfAux lhs\n  if lhs' != lhs then\n    return some (\u2190 replaceTargetDefEq mvarId (\u2190 mkEq lhs' rhs))\n  else\n    return none\n\ndef tryContradiction (mvarId : MVarId) : MetaM Bool := do\n  try contradiction mvarId { genDiseq := true }; return true catch _ => return false\n\nnamespace Structural\n\nstructure EqnInfo where\n  declName    : Name\n  levelParams : List Name\n  type        : Expr\n  value       : Expr\n  recArgPos   : Nat\n  deriving Inhabited\n\nprivate partial def expand : Expr \u2192 Expr\n  | Expr.letE _ t v b _ => expand (b.instantiate1 v)\n  | Expr.mdata _ b _    => expand b\n  | e => e\n\nprivate def expandRHS? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) \u2190 target.eq? | return none\n  unless rhs.isLet || rhs.isMData do return none\n  return some (\u2190 replaceTargetDefEq mvarId (\u2190 mkEq lhs (expand rhs)))\n\nprivate def funext? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) \u2190 target.eq? | return none\n  unless rhs.isLambda do return none\n  commitWhenSome? do\n    let [mvarId] \u2190 apply mvarId (\u2190 mkConstWithFreshMVarLevels ``funext) | return none\n    let (_, mvarId) \u2190 intro1 mvarId\n    return some mvarId\n\nprivate def simpMatch? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let mvarId' \u2190 Split.simpMatchTarget mvarId\n  if mvarId != mvarId' then return some mvarId' else return none\n\nprivate def simpIf? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let mvarId' \u2190 simpIfTarget mvarId (useDecide := true)\n  if mvarId != mvarId' then return some mvarId' else return none\n\n/--\n  Auxiliary method for `mkEqnTypes`. We should \"keep going\"/\"processing\" the goal\n   `... |- f ... = rhs` at `mkEqnTypes` IF `rhs` contains a `f` application containing loose bound\n  variables. We do that to make sure we can create an elimination principle for `f` based\n  on the generateg equations.\n\n  Remark: we have considered using the same heuristic used in the `BRecOn` module.\n  That is we would do case-analysis on the `match` application because the recursive\n  argument (may) depend on it. We abandoned this approach because it was incompatible\n  with the generation of induction principles.\n\n  Remark: we could also always return `true` here, and split **all** match expressions on the `rhs`\n  even if they are not relevant for the `brecOn` construction.\n  TODO: reconsider this design decision in the future.\n  Another possible design option is to \"split\" other control structures such as `if-then-else`.\n-/\nprivate def keepGoing (mvarId : MVarId) : ReaderT EqnInfo (StateRefT (Array Expr) MetaM) Bool := do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) \u2190 target.eq? | return false\n  let ctx \u2190 read\n  return Option.isSome <| rhs.find? fun e => e.isAppOf ctx.declName && e.hasLooseBVars\n\nprivate def saveEqn (mvarId : MVarId) : StateRefT (Array Expr) MetaM Unit := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let fvarIds \u2190 sortFVarIds <| collectFVars {} target |>.fvarSet.toArray\n  -- We want to ensure the extra hypotheses occur after the main free variables\n  let (_, mvarId) \u2190 revert mvarId fvarIds (preserveOrder := true)\n  let type \u2190 instantiateMVars (\u2190 getMVarType mvarId)\n  modify (\u00b7.push type)\n\nprivate partial def mkEqnTypes (mvarId : MVarId) : ReaderT EqnInfo (StateRefT (Array Expr) MetaM) Unit := do\n  if !(\u2190 keepGoing mvarId) then\n    saveEqn mvarId\n  else if let some mvarId \u2190 expandRHS? mvarId then\n    mkEqnTypes mvarId\n  else if let some mvarId \u2190 funext? mvarId then\n    mkEqnTypes mvarId\n  else if let some mvarId \u2190 simpMatch? mvarId then\n    mkEqnTypes mvarId\n  else if let some mvarIds \u2190 splitTarget? mvarId then\n    mvarIds.forM mkEqnTypes\n  else\n    saveEqn mvarId\n\n/-- Create a \"unique\" base name for equations and splitter -/\nprivate def mkBaseNameFor (env : Environment) (declName : Name) : Name :=\n  Lean.mkBaseNameFor env declName `eq_1 `_eqns\n\nprivate partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do\n  trace[Elab.definition.structural.eqns] \"proving: {type}\"\n  withNewMCtxDepth do\n    let main \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let (_, mvarId) \u2190 intros main.mvarId!\n    unless (\u2190 tryURefl mvarId) do -- catch easy cases\n      go (\u2190 deltaLHS mvarId)\n    instantiateMVars main\nwhere\n  go (mvarId : MVarId) : MetaM Unit := do\n    trace[Elab.definition.structural.eqns] \"step\\n{MessageData.ofGoal mvarId}\"\n    if (\u2190 tryURefl mvarId) then\n      return ()\n    else if (\u2190 tryContradiction mvarId) then\n      return ()\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpIf? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 whnfReducibleLHS? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 deltaRHS? mvarId declName then\n      go mvarId\n    else if let some mvarIds \u2190 casesOnStuckLHS? mvarId then\n      mvarIds.forM go\n    else\n      throwError \"failed to generate equational theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n\ndef mkEqns (info : EqnInfo) : MetaM (Array Name) := do\n  withOptions (tactic.hygienic.set . false) do\n  let eqnTypes \u2190 withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do\n    let us := info.levelParams.map mkLevelParam\n    let target \u2190 mkEq (mkAppN (Lean.mkConst info.declName us) xs) body\n    let goal \u2190 mkFreshExprSyntheticOpaqueMVar target\n    let (_, eqnTypes) \u2190 mkEqnTypes goal.mvarId! |>.run info |>.run #[]\n    return eqnTypes\n  let baseName := mkBaseNameFor (\u2190 getEnv) info.declName\n  let mut thmNames := #[]\n  for i in [: eqnTypes.size] do\n    let type := eqnTypes[i]\n    trace[Elab.definition.structural.eqns] \"{eqnTypes[i]}\"\n    let name := baseName ++ (`eq).appendIndexAfter (i+1)\n    thmNames := thmNames.push name\n    let value \u2190 mkProof info.declName type\n    addDecl <| Declaration.thmDecl {\n      name, type, value\n      levelParams := info.levelParams\n    }\n  return thmNames\n\nbuiltin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo \u2190 mkMapDeclarationExtension `structEqInfo\n\ndef registerEqnsInfo (preDef : PreDefinition) (recArgPos : Nat) : CoreM Unit := do\n  modifyEnv fun env => eqnInfoExt.insert env preDef.declName { preDef with recArgPos }\n\nstructure EqnsExtState where\n  map : Std.PHashMap Name (Array Name) := {}\n  deriving Inhabited\n\n/- We generate the equations on demand, and do not save them on .olean files. -/\nbuiltin_initialize eqnsExt : EnvExtension EqnsExtState \u2190\n  registerEnvExtension (pure {})\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  let env \u2190 getEnv\n  if let some eqs := eqnsExt.getState env |>.map.find? declName then\n    return some eqs\n  else if let some info := eqnInfoExt.find? env declName then\n    let eqs \u2190 mkEqns info\n    modifyEnv fun env => eqnsExt.modifyState env fun s => { s with map := s.map.insert declName eqs }\n    return some eqs\n  else\n    return none\n\nbuiltin_initialize\n  registerGetEqnsFn getEqnsFor?\n  registerTraceClass `Elab.definition.structural.eqns\n\nend Structural\nend Lean.Elab\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/Elab/PreDefinition/Structural/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.13660839354130014, "lm_q1q2_score": 0.04290194219617966}}
{"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\u2081 v\u2082 v\u2083 u\u2081 u\u2082 u\u2083 -- 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\u2081} [\ud835\udc9e : category.{v\u2081} C] {D : Type u\u2082} [\ud835\udc9f : category.{v\u2082} D]\ninclude \ud835\udc9e \ud835\udc9f\n\n/--\n`adjunction F G` represents the data of an adjunction between two functors\n`F : C \u2964 D` and `G : D \u2964 C`. `F` is the left adjoint and `G` is the right adjoint.\n-/\nstructure adjunction (F : C \u2964 D) (G : D \u2964 C) :=\n(hom_equiv : \u03a0 (X Y), (F.obj X \u27f6 Y) \u2243 (X \u27f6 G.obj Y))\n(unit : functor.id C \u27f6 F.comp G)\n(counit : G.comp F \u27f6 functor.id D)\n(hom_equiv_unit' : \u03a0 {X Y f}, (hom_equiv X Y) f = (unit : _ \u27f9 _).app X \u226b G.map f . obviously)\n(hom_equiv_counit' : \u03a0 {X Y g}, (hom_equiv X Y).symm g = F.map g \u226b 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 \u2964 D} {G : D \u2964 C} (adj : adjunction F G) {X' X : C} {Y Y' : D}\n\n@[simp, priority 1] lemma hom_equiv_naturality_left_symm (f : X' \u27f6 X) (g : X \u27f6 G.obj Y) :\n  (adj.hom_equiv X' Y).symm (f \u226b g) = F.map f \u226b (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' \u27f6 X) (g : F.obj X \u27f6 Y) :\n  (adj.hom_equiv X' Y) (F.map f \u226b g) = f \u226b (adj.hom_equiv X Y) g :=\nby rw [\u2190 equiv.eq_symm_apply]; simp [-hom_equiv_unit]\n\n@[simp, priority 1] lemma hom_equiv_naturality_right (f : F.obj X \u27f6 Y) (g : Y \u27f6 Y') :\n  (adj.hom_equiv X Y') (f \u226b g) = (adj.hom_equiv X Y) f \u226b G.map g :=\nby rw [hom_equiv_unit, G.map_comp, \u2190 assoc, \u2190hom_equiv_unit]\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X \u27f6 G.obj Y) (g : Y \u27f6 Y') :\n  (adj.hom_equiv X Y').symm (f \u226b G.map g) = (adj.hom_equiv X Y).symm f \u226b 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 [\u2190 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 [\u2190 adj.hom_equiv_unit, \u2190 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) \u226b adj.counit.app (F.obj X) = \ud835\udfd9 _ :=\ncongr_arg (\u03bb (t : _ \u27f9 functor.id C \u22d9 F), t.app X) adj.left_triangle\n\n@[simp] lemma right_triangle_components {Y : D} :\n  adj.unit.app (G.obj Y) \u226b G.map (adj.counit.app Y) = \ud835\udfd9 _ :=\ncongr_arg (\u03bb (t : _ \u27f9 G \u22d9 functor.id C), t.app Y) adj.right_triangle\n\nend\n\nstructure core_hom_equiv (F : C \u2964 D) (G : D \u2964 C) :=\n(hom_equiv : \u03a0 (X Y), (F.obj X \u27f6 Y) \u2243 (X \u27f6 G.obj Y))\n(hom_equiv_naturality_left_symm' : \u03a0 {X' X Y} (f : X' \u27f6 X) (g : X \u27f6 G.obj Y),\n  (hom_equiv X' Y).symm (f \u226b g) = F.map f \u226b (hom_equiv X Y).symm g . obviously)\n(hom_equiv_naturality_right' : \u03a0 {X Y Y'} (f : F.obj X \u27f6 Y) (g : Y \u27f6 Y'),\n  (hom_equiv X Y') (f \u226b g) = (hom_equiv X Y) f \u226b 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 \u2964 D} {G : D \u2964 C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D}\n\n@[simp] lemma hom_equiv_naturality_left (f : X' \u27f6 X) (g : F.obj X \u27f6 Y) :\n  (adj.hom_equiv X' Y) (F.map f \u226b g) = f \u226b (adj.hom_equiv X Y) g :=\nby rw [\u2190 equiv.eq_symm_apply]; simp\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X \u27f6 G.obj Y) (g : Y \u27f6 Y') :\n  (adj.hom_equiv X Y').symm (f \u226b G.map g) = (adj.hom_equiv X Y).symm f \u226b g :=\nby rw [equiv.symm_apply_eq]; simp\n\nend core_hom_equiv\n\nstructure core_unit_counit (F : C \u2964 D) (G : D \u2964 C) :=\n(unit : functor.id C \u27f6 F.comp G)\n(counit : G.comp F \u27f6 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 \u2964 D) (G : D \u2964 C)\n\ndef mk_of_hom_equiv (adj : core_hom_equiv F G) : adjunction F G :=\n{ unit :=\n  { app := \u03bb X, (adj.hom_equiv X (F.obj X)) (\ud835\udfd9 (F.obj X)),\n    naturality' :=\n    begin\n      intros,\n      erw [\u2190 adj.hom_equiv_naturality_left, \u2190 adj.hom_equiv_naturality_right],\n      dsimp, simp\n    end },\n  counit :=\n  { app := \u03bb Y, (adj.hom_equiv _ _).inv_fun (\ud835\udfd9 (G.obj Y)),\n    naturality' :=\n    begin\n      intros,\n      erw [\u2190 adj.hom_equiv_naturality_left_symm, \u2190 adj.hom_equiv_naturality_right_symm],\n      dsimp, simp\n    end },\n  hom_equiv_unit' := \u03bb X Y f, by erw [\u2190 adj.hom_equiv_naturality_right]; simp,\n  hom_equiv_counit' := \u03bb X Y f, by erw [\u2190 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 := \u03bb X Y,\n  { to_fun := \u03bb f, adj.unit.app X \u226b G.map f,\n    inv_fun := \u03bb g, F.map g \u226b adj.counit.app Y,\n    left_inv := \u03bb f, begin\n      change F.map (_ \u226b _) \u226b _ = _,\n      rw [F.map_comp, assoc, \u2190functor.comp_map, adj.counit.naturality, \u2190assoc],\n      convert id_comp _ f,\n      exact congr_arg (\u03bb t : _ \u27f9 _, t.app _) adj.left_triangle\n    end,\n    right_inv := \u03bb g, begin\n      change _ \u226b G.map (_ \u226b _) = _,\n      rw [G.map_comp, \u2190assoc, \u2190functor.comp_map, \u2190adj.unit.naturality, assoc],\n      convert comp_id _ g,\n      exact congr_arg (\u03bb t : _ \u27f9 _, t.app _) adj.right_triangle\n  end },\n  .. adj }\n\nsection\nomit \ud835\udc9f\n\ndef id : adjunction (functor.id C) (functor.id C) :=\n{ hom_equiv := \u03bb X Y, equiv.refl _,\n  unit := \ud835\udfd9 _,\n  counit := \ud835\udfd9 _ }\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\u2083} [\u2130 : category.{v\u2083} E] (H : D \u2964 E) (I : E \u2964 D)\n\ndef comp (adj\u2081 : adjunction F G) (adj\u2082 : adjunction H I) : adjunction (F \u22d9 H) (I \u22d9 G) :=\n{ hom_equiv := \u03bb X Z, equiv.trans (adj\u2082.hom_equiv _ _) (adj\u2081.hom_equiv _ _),\n  unit := adj\u2081.unit \u226b\n  (whisker_left F $ whisker_right adj\u2082.unit G) \u226b (functor.associator _ _ _).inv,\n  counit := (functor.associator _ _ _).hom \u226b\n    (whisker_left I $ whisker_right adj\u2081.counit H) \u226b adj\u2082.counit }\n\nend\n\nstructure is_left_adjoint (left : C \u2964 D) :=\n(right : D \u2964 C)\n(adj : adjunction left right)\n\nstructure is_right_adjoint (right : D \u2964 C) :=\n(left : C \u2964 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 \u2192 C, it suffices to give the object part\n-- of a functor F : C \u2192 D together with isomorphisms Hom(FX, Y) \u2243\n-- Hom(X, GY) natural in Y. The action of F on morphisms can be\n-- constructed from this data.\nvariables {F_obj : C \u2192 D} {G}\nvariables (e : \u03a0 X Y, (F_obj X \u27f6 Y) \u2243 (X \u27f6 G.obj Y))\nvariables (he : \u03a0 X Y Y' g h, e X Y' (h \u226b g) = e X Y h \u226b G.map g)\ninclude he\n\nprivate lemma he' {X Y Y'} (f g) : (e X Y').symm (f \u226b G.map g) = (e X Y).symm f \u226b g :=\nby intros; rw [equiv.symm_apply_eq, he]; simp\n\ndef left_adjoint_of_equiv : C \u2964 D :=\n{ obj := F_obj,\n  map := \u03bb X X' f, (e X (F_obj X')).symm (f \u226b e X' (F_obj X') (\ud835\udfd9 _)),\n  map_comp' := \u03bb X X' X'' f f', begin\n    rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply],\n    conv { to_rhs, rw [assoc, \u2190he, 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 [\u2190 he' e he, \u2190 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 \u2192 C}\nvariables (e : \u03a0 X Y, (F.obj X \u27f6 Y) \u2243 (X \u27f6 G_obj Y))\nvariables (he : \u03a0 X' X Y f g, e X' Y (F.map f \u226b g) = f \u226b e X Y g)\ninclude he\n\nprivate lemma he' {X' X Y} (f g) : F.map f \u226b (e X Y).symm g = (e X' Y).symm (f \u226b g) :=\nby intros; rw [equiv.eq_symm_apply, he]; simp\n\ndef right_adjoint_of_equiv : D \u2964 C :=\n{ obj := G_obj,\n  map := \u03bb Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (\ud835\udfd9 _) \u226b g),\n  map_comp' := \u03bb Y Y' Y'' g g', begin\n    rw [\u2190 equiv.eq_symm_apply, \u2190 he' e he, equiv.symm_apply_apply],\n    conv { to_rhs, rw [\u2190 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 [\u2190he, equiv.apply_eq_iff_eq, \u2190assoc, 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\u2081 u\u2082 v\n\nvariables {C : Type u\u2081} [\ud835\udc9e : category.{v} C] {D : Type u\u2082} [\ud835\udc9f : category.{v} D]\ninclude \ud835\udc9e \ud835\udc9f\n\nvariables {F : C \u2964 D} {G : D \u2964 C} (adj : adjunction F G)\ninclude adj\n\nsection preservation_colimits\nvariables {J : Type v} [small_category J] (K : J \u2964 C)\n\ndef functoriality_is_left_adjoint :\n  is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) :=\n{ right := (cocones.functoriality G) \u22d9 (cocones.precompose\n    (K.right_unitor.inv \u226b (whisker_left K adj.unit) \u226b (associator _ _ _).inv)),\n  adj := mk_of_unit_counit _ _\n  { unit :=\n    { app := \u03bb c,\n      { hom := adj.unit.app c.X,\n        w' := \u03bb j, by have := adj.unit.naturality (c.\u03b9.app j); tidy },\n      naturality' := \u03bb _ _ f, by have := adj.unit.naturality (f.hom); tidy },\n    counit :=\n    { app := \u03bb 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.\u03b9.app j), \u2190 category.assoc,\n            adj.left_triangle_components, category.id_comp],\n          refl,\n        end },\n      naturality' := \u03bb _ _ 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\u03bb J \ud835\udca5 K, by resetI; exact\n{ preserves := \u03bb c hc, is_colimit_iso_unique_cocone_morphism.inv\n    (\u03bb 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 \u2964 D)\n\ndef functoriality_is_right_adjoint :\n  is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) :=\n{ left := (cones.functoriality F) \u22d9 (cones.postcompose\n    ((associator _ _ _).hom \u226b (whisker_left K adj.counit) \u226b K.right_unitor.hom)),\n  adj := mk_of_unit_counit _ _\n  { unit :=\n    { app := \u03bb 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, \u2190 category.assoc,\n            \u2190 adj.unit.naturality (c.\u03c0.app j), category.assoc,\n            adj.right_triangle_components, category.comp_id],\n          refl,\n        end },\n      naturality' := \u03bb _ _ f, by have := adj.unit.naturality (f.hom); tidy },\n    counit :=\n    { app := \u03bb c,\n      { hom := adj.counit.app c.X,\n        w' := \u03bb j, by have := adj.counit.naturality (c.\u03c0.app j); tidy },\n      naturality' := \u03bb _ _ 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\u03bb J \ud835\udca5 K, by resetI; exact\n{ preserves := \u03bb c hc, is_limit_iso_unique_cone_morphism.inv\n    (\u03bb 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 \u2964 C} :\n  (cocones J D).obj (op (K \u22d9 F)) \u2245 G \u22d9 ((cocones J C).obj (op K)) :=\nnat_iso.of_components (\u03bb Y,\n{ hom := \u03bb t,\n    { app := \u03bb j, (adj.hom_equiv (K.obj j) Y) (t.app j),\n      naturality' := \u03bb j j' f, by erw [\u2190 adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp },\n  inv := \u03bb t,\n    { app := \u03bb j, (adj.hom_equiv (K.obj j) Y).symm (t.app j),\n      naturality' := \u03bb j j' f, begin\n        erw [\u2190 adj.hom_equiv_naturality_left_symm, \u2190 adj.hom_equiv_naturality_right_symm, t.naturality],\n        dsimp, simp\n      end } } )\nbegin\n  intros Y\u2081 Y\u2082 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 \u2964 D} :\n  F.op \u22d9 ((cones J D).obj K) \u2245 (cones J C).obj (K \u22d9 G) :=\nnat_iso.of_components (\u03bb X,\n{ hom := \u03bb t,\n  { app := \u03bb j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j),\n    naturality' := \u03bb j j' f, begin\n      erw [\u2190 adj.hom_equiv_naturality_right, \u2190 t.naturality, category.id_comp, category.id_comp],\n      refl\n    end },\n  inv := \u03bb t,\n  { app := \u03bb j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j),\n    naturality' := \u03bb j j' f, begin\n      erw [\u2190 adj.hom_equiv_naturality_right_symm, \u2190 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 `\u03b1` is a type, then `option \u03b1` can be understood as the type with one more element than `\u03b1`.\n`option \u03b1` has terms `some a`, where `a : \u03b1`, 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 \u03b1` 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 : \u03b1` 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 {\u03b1 \u03b2 \u03b3 \u03b4 : Type _}\n\n#print Option.coe_def /-\ntheorem coe_def : (coe : \u03b1 \u2192 Option \u03b1) = some :=\n  rfl\n#align option.coe_def Option.coe_def\n-/\n\ntheorem some_eq_coe (a : \u03b1) : 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 : \u03b1) : some x \u2260 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 : \u03b1) : (a : Option \u03b1) \u2260 none :=\n  fun.\n#align option.coe_ne_none Option.coe_ne_none\n\n#print Option.forall /-\nprotected theorem forall {p : Option \u03b1 \u2192 Prop} : (\u2200 x, p x) \u2194 p none \u2227 \u2200 x, p (some x) :=\n  \u27e8fun h => \u27e8h _, fun x => h _\u27e9, fun h x => Option.casesOn x h.1 h.2\u27e9\n#align option.forall Option.forall\n-/\n\n#print Option.exists /-\nprotected theorem exists {p : Option \u03b1 \u2192 Prop} : (\u2203 x, p x) \u2194 p none \u2228 \u2203 x, p (some x) :=\n  \u27e8fun \u27e8x, hx\u27e9 => (Option.casesOn x Or.inl fun x hx => Or.inr \u27e8x, hx\u27e9) hx, fun h =>\n    h.elim (fun h => \u27e8_, h\u27e9) fun \u27e8x, hx\u27e9 => \u27e8_, hx\u27e9\u27e9\n#align option.exists Option.exists\n-/\n\n#print Option.get_mem /-\n@[simp]\ntheorem get_mem : \u2200 {o : Option \u03b1} (h : isSome o), Option.get h \u2208 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 : \u03b1} : \u2200 {o : Option \u03b1} (h : isSome o), a \u2208 o \u2192 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 : \u03b1) : a \u2209 (none : Option \u03b1) := 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 : \u2200 {x : Option \u03b1} (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 : \u03b1) (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 : \u03b1) : 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 : \u03b1) : 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 : \u03b1) : Option.getD (\u2191x) 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 \u03b1} (hx : x \u2260 none) (y : \u03b1) : 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 \u03b1} (h : o.isSome) : ((Option.get h : \u03b1) : Option \u03b1) = 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 \u03b1} {a b : \u03b1} (ha : a \u2208 o) (hb : b \u2208 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 : \u03b1} {o1 o2 : Option \u03b1} (h1 : a \u2208 o1) (h2 : a \u2208 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 ((\u00b7 \u2208 \u00b7) : \u03b1 \u2192 Option \u03b1 \u2192 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 (\u03b1 : Type _) : Function.Injective (@some \u03b1) := 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {f : \u03b1 -> \u03b2}, (Function.Injective.{succ u1, succ u2} \u03b1 \u03b2 f) -> (Function.Injective.{succ u1, succ u2} (Option.{u1} \u03b1) (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2}, (Function.Injective.{succ u2, succ u1} \u03b1 \u03b2 f) -> (Function.Injective.{succ u2, succ u1} (Option.{u2} \u03b1) (Option.{u1} \u03b2) (Option.map.{u2, u1} \u03b1 \u03b2 f))\nCase conversion may be inaccurate. Consider using '#align option.map_injective Option.map_injective\u2093'. -/\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {f : \u03b1 \u2192 \u03b2} (Hf : Function.Injective f) : Function.Injective (Option.map f)\n  | none, none, H => rfl\n  | some a\u2081, some a\u2082, 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} (f : \u03b1 -> \u03b2), Eq.{max (succ u1) (succ u2)} (\u03b1 -> (Option.{u2} \u03b2)) (Function.comp.{succ u1, succ u1, succ u2} \u03b1 (Option.{u1} \u03b1) (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f) (Option.some.{u1} \u03b1)) (Function.comp.{succ u1, succ u2, succ u2} \u03b1 \u03b2 (Option.{u2} \u03b2) (Option.some.{u2} \u03b2) f)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (f : \u03b1 -> \u03b2), Eq.{max (succ u2) (succ u1)} (\u03b1 -> (Option.{u1} \u03b2)) (Function.comp.{succ u2, succ u2, succ u1} \u03b1 (Option.{u2} \u03b1) (Option.{u1} \u03b2) (Option.map.{u2, u1} \u03b1 \u03b2 f) (Option.some.{u2} \u03b1)) (Function.comp.{succ u2, succ u1, succ u1} \u03b1 \u03b2 (Option.{u1} \u03b2) (Option.some.{u1} \u03b2) f)\nCase conversion may be inaccurate. Consider using '#align option.map_comp_some Option.map_comp_some\u2093'. -/\n@[simp]\ntheorem map_comp_some (f : \u03b1 \u2192 \u03b2) : Option.map f \u2218 some = some \u2218 f :=\n  rfl\n#align option.map_comp_some Option.map_comp_some\n\n#print Option.ext /-\n@[ext]\ntheorem ext : \u2200 {o\u2081 o\u2082 : Option \u03b1}, (\u2200 a, a \u2208 o\u2081 \u2194 a \u2208 o\u2082) \u2192 o\u2081 = o\u2082\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 \u03b1} : o = none \u2194 \u2200 a, a \u2209 o :=\n  \u27e8fun e a h => by rw [e] at h <;> cases h, fun h => ext <| by simpa\u27e9\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 {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_1}} (f : \u03b1 -> (Option.{u_1} \u03b2)), Eq.{succ u_1} (Option.{u_1} \u03b2) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) \u03b1 \u03b2 (Option.none.{u_1} \u03b1) f) (Option.none.{u_1} \u03b2)\nbut is expected to have type\n  forall {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_2}} (f : \u03b1 -> (Option.{u_2} \u03b2)), Eq.{succ u_2} (Option.{u_2} \u03b2) (Option.bind.{u_1, u_2} \u03b1 \u03b2 (Option.none.{u_1} \u03b1) f) (Option.none.{u_2} \u03b2)\nCase conversion may be inaccurate. Consider using '#align option.none_bind Option.none_bind\u2093'. -/\n@[simp]\ntheorem none_bind {\u03b1 \u03b2} (f : \u03b1 \u2192 Option \u03b2) : 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 {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_1}} (a : \u03b1) (f : \u03b1 -> (Option.{u_1} \u03b2)), Eq.{succ u_1} (Option.{u_1} \u03b2) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) \u03b1 \u03b2 (Option.some.{u_1} \u03b1 a) f) (f a)\nbut is expected to have type\n  forall {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_2}} (a : \u03b1) (f : \u03b1 -> (Option.{u_2} \u03b2)), Eq.{succ u_2} (Option.{u_2} \u03b2) (Option.bind.{u_1, u_2} \u03b1 \u03b2 (Option.some.{u_1} \u03b1 a) f) (f a)\nCase conversion may be inaccurate. Consider using '#align option.some_bind Option.some_bind\u2093'. -/\n@[simp]\ntheorem some_bind {\u03b1 \u03b2} (a : \u03b1) (f : \u03b1 \u2192 Option \u03b2) : 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 : \u03b1 \u2192 Option \u03b2) : 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 : \u03b1) (f : \u03b1 \u2192 Option \u03b2) : (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 {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b1 x (Option.some.{u1} \u03b1)) x\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (Option.bind.{u1, u1} \u03b1 \u03b1 x (Option.some.{u1} \u03b1)) x\nCase conversion may be inaccurate. Consider using '#align option.bind_some Option.bind_some\u2093'. -/\n@[simp]\ntheorem bind_some : \u2200 x : Option \u03b1, x >>= some = x :=\n  @bind_pure \u03b1 Option _ _\n#align option.bind_some Option.bind_some\n\n@[simp]\ntheorem bind_some' : \u2200 x : Option \u03b1, 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 {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_1}} {x : Option.{u_1} \u03b1} {f : \u03b1 -> (Option.{u_1} \u03b2)} {b : \u03b2}, Iff (Eq.{succ u_1} (Option.{u_1} \u03b2) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) \u03b1 \u03b2 x f) (Option.some.{u_1} \u03b2 b)) (Exists.{succ u_1} \u03b1 (fun (a : \u03b1) => And (Eq.{succ u_1} (Option.{u_1} \u03b1) x (Option.some.{u_1} \u03b1 a)) (Eq.{succ u_1} (Option.{u_1} \u03b2) (f a) (Option.some.{u_1} \u03b2 b))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u_1}} {\u03b2 : \u03b1} {x : Type.{u_2}} {f : Option.{u_2} x} {b : x -> (Option.{u_1} \u03b1)}, Iff (Eq.{succ u_1} (Option.{u_1} \u03b1) (Option.bind.{u_2, u_1} x \u03b1 f b) (Option.some.{u_1} \u03b1 \u03b2)) (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} \u03b1) (b a) (Option.some.{u_1} \u03b1 \u03b2))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_some Option.bind_eq_some\u2093'. -/\n@[simp]\ntheorem bind_eq_some {\u03b1 \u03b2} {x : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} {b : \u03b2} :\n    x >>= f = some b \u2194 \u2203 a, x = some a \u2227 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {x : Option.{u1} \u03b1} {f : \u03b1 -> (Option.{u2} \u03b2)} {b : \u03b2}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.bind.{u1, u2} \u03b1 \u03b2 x f) (Option.some.{u2} \u03b2 b)) (Exists.{succ u1} \u03b1 (fun (a : \u03b1) => And (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.some.{u1} \u03b1 a)) (Eq.{succ u2} (Option.{u2} \u03b2) (f a) (Option.some.{u2} \u03b2 b))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {x : Option.{u2} \u03b1} {f : \u03b1 -> (Option.{u1} \u03b2)} {b : \u03b2}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Option.bind.{u2, u1} \u03b1 \u03b2 x f) (Option.some.{u1} \u03b2 b)) (Exists.{succ u2} \u03b1 (fun (a : \u03b1) => And (Eq.{succ u2} (Option.{u2} \u03b1) x (Option.some.{u2} \u03b1 a)) (Eq.{succ u1} (Option.{u1} \u03b2) (f a) (Option.some.{u1} \u03b2 b))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_some' Option.bind_eq_some'\u2093'. -/\n@[simp]\ntheorem bind_eq_some' {x : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} {b : \u03b2} :\n    x.bind f = some b \u2194 \u2203 a, x = some a \u2227 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {o : Option.{u1} \u03b1} {f : \u03b1 -> (Option.{u2} \u03b2)}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.bind.{u1, u2} \u03b1 \u03b2 o f) (Option.none.{u2} \u03b2)) (forall (b : \u03b2) (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a o) -> (Not (Membership.Mem.{u2, u2} \u03b2 (Option.{u2} \u03b2) (Option.hasMem.{u2} \u03b2) b (f a))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {o : Option.{u2} \u03b1} {f : \u03b1 -> (Option.{u1} \u03b2)}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Option.bind.{u2, u1} \u03b1 \u03b2 o f) (Option.none.{u1} \u03b2)) (forall (b : \u03b2) (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a o) -> (Not (Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) b (f a))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_none' Option.bind_eq_none'\u2093'. -/\n@[simp]\ntheorem bind_eq_none' {o : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} :\n    o.bind f = none \u2194 \u2200 b a, a \u2208 o \u2192 b \u2209 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 {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_1}} {o : Option.{u_1} \u03b1} {f : \u03b1 -> (Option.{u_1} \u03b2)}, Iff (Eq.{succ u_1} (Option.{u_1} \u03b2) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) \u03b1 \u03b2 o f) (Option.none.{u_1} \u03b2)) (forall (b : \u03b2) (a : \u03b1), (Membership.Mem.{u_1, u_1} \u03b1 (Option.{u_1} \u03b1) (Option.hasMem.{u_1} \u03b1) a o) -> (Not (Membership.Mem.{u_1, u_1} \u03b2 (Option.{u_1} \u03b2) (Option.hasMem.{u_1} \u03b2) b (f a))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_2}} {o : Option.{u_1} \u03b1} {f : \u03b1 -> (Option.{u_2} \u03b2)}, Iff (Eq.{succ u_2} (Option.{u_2} \u03b2) (Option.bind.{u_1, u_2} \u03b1 \u03b2 o f) (Option.none.{u_2} \u03b2)) (forall (b : \u03b2) (a : \u03b1), (Membership.mem.{u_1, u_1} \u03b1 (Option.{u_1} \u03b1) (Option.instMembershipOption.{u_1} \u03b1) a o) -> (Not (Membership.mem.{u_2, u_2} \u03b2 (Option.{u_2} \u03b2) (Option.instMembershipOption.{u_2} \u03b2) b (f a))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_none Option.bind_eq_none\u2093'. -/\n@[simp]\ntheorem bind_eq_none {\u03b1 \u03b2} {o : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} :\n    o >>= f = none \u2194 \u2200 b a, a \u2208 o \u2192 b \u2209 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} {f : \u03b1 -> \u03b2 -> (Option.{u3} \u03b3)} (a : Option.{u1} \u03b1) (b : Option.{u2} \u03b2), Eq.{succ u3} (Option.{u3} \u03b3) (Option.bind.{u1, u3} \u03b1 \u03b3 a (fun (x : \u03b1) => Option.bind.{u2, u3} \u03b2 \u03b3 b (f x))) (Option.bind.{u2, u3} \u03b2 \u03b3 b (fun (y : \u03b2) => Option.bind.{u1, u3} \u03b1 \u03b3 a (fun (x : \u03b1) => f x y)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} {f : \u03b1 -> \u03b2 -> (Option.{u1} \u03b3)} (a : Option.{u3} \u03b1) (b : Option.{u2} \u03b2), Eq.{succ u1} (Option.{u1} \u03b3) (Option.bind.{u3, u1} \u03b1 \u03b3 a (fun (x : \u03b1) => Option.bind.{u2, u1} \u03b2 \u03b3 b (f x))) (Option.bind.{u2, u1} \u03b2 \u03b3 b (fun (y : \u03b2) => Option.bind.{u3, u1} \u03b1 \u03b3 a (fun (x : \u03b1) => f x y)))\nCase conversion may be inaccurate. Consider using '#align option.bind_comm Option.bind_comm\u2093'. -/\ntheorem bind_comm {\u03b1 \u03b2 \u03b3} {f : \u03b1 \u2192 \u03b2 \u2192 Option \u03b3} (a : Option \u03b1) (b : Option \u03b2) :\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (x : Option.{u1} \u03b1) (f : \u03b1 -> (Option.{u2} \u03b2)) (g : \u03b2 -> (Option.{u3} \u03b3)), Eq.{succ u3} (Option.{u3} \u03b3) (Option.bind.{u2, u3} \u03b2 \u03b3 (Option.bind.{u1, u2} \u03b1 \u03b2 x f) g) (Option.bind.{u1, u3} \u03b1 \u03b3 x (fun (y : \u03b1) => Option.bind.{u2, u3} \u03b2 \u03b3 (f y) g))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (x : Option.{u3} \u03b1) (f : \u03b1 -> (Option.{u2} \u03b2)) (g : \u03b2 -> (Option.{u1} \u03b3)), Eq.{succ u1} (Option.{u1} \u03b3) (Option.bind.{u2, u1} \u03b2 \u03b3 (Option.bind.{u3, u2} \u03b1 \u03b2 x f) g) (Option.bind.{u3, u1} \u03b1 \u03b3 x (fun (y : \u03b1) => Option.bind.{u2, u1} \u03b2 \u03b3 (f y) g))\nCase conversion may be inaccurate. Consider using '#align option.bind_assoc Option.bind_assoc\u2093'. -/\ntheorem bind_assoc (x : Option \u03b1) (f : \u03b1 \u2192 Option \u03b2) (g : \u03b2 \u2192 Option \u03b3) :\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 {\u03b1 : Type.{u1}} {x : Option.{u1} (Option.{u1} \u03b1)} {a : \u03b1}, Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.join.{u1} \u03b1 x) (Option.some.{u1} \u03b1 a)) (Eq.{succ u1} (Option.{u1} (Option.{u1} \u03b1)) x (Option.some.{u1} (Option.{u1} \u03b1) (Option.some.{u1} \u03b1 a)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {x : \u03b1} {a : Option.{u1} (Option.{u1} \u03b1)}, Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.join.{u1} \u03b1 a) (Option.some.{u1} \u03b1 x)) (Eq.{succ u1} (Option.{u1} (Option.{u1} \u03b1)) a (Option.some.{u1} (Option.{u1} \u03b1) (Option.some.{u1} \u03b1 x)))\nCase conversion may be inaccurate. Consider using '#align option.join_eq_some Option.join_eq_some\u2093'. -/\ntheorem join_eq_some {x : Option (Option \u03b1)} {a : \u03b1} : x.join = some a \u2194 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 \u03b1)} : x.join \u2260 none \u2194 \u2203 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 \u03b1)} : \u00acx.join = none \u2194 \u2203 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 \u03b1)} : o.join = none \u2194 o = none \u2228 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 {\u03b1 : Type.{u1}} {x : Option.{u1} (Option.{u1} \u03b1)}, Eq.{succ u1} (Option.{u1} \u03b1) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) (Option.{u1} \u03b1) \u03b1 x (id.{succ u1} (Option.{u1} \u03b1))) (Option.join.{u1} \u03b1 x)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {x : Option.{u1} (Option.{u1} \u03b1)}, Eq.{succ u1} (Option.{u1} \u03b1) (Option.bind.{u1, u1} (Option.{u1} \u03b1) \u03b1 x (id.{succ u1} (Option.{u1} \u03b1))) (Option.join.{u1} \u03b1 x)\nCase conversion may be inaccurate. Consider using '#align option.bind_id_eq_join Option.bind_id_eq_join\u2093'. -/\ntheorem bind_id_eq_join {x : Option (Option \u03b1)} : 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 {\u03b1 : Type.{u1}}, Eq.{succ u1} ((Option.{u1} (Option.{u1} \u03b1)) -> (Option.{u1} \u03b1)) (joinM.{u1} Option.{u1} Option.monad.{u1} \u03b1) (Option.join.{u1} \u03b1)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}}, Eq.{succ u1} ((Option.{u1} (Option.{u1} \u03b1)) -> (Option.{u1} \u03b1)) (joinM.{u1} Option.{u1} instMonadOption.{u1} \u03b1) (Option.join.{u1} \u03b1)\nCase conversion may be inaccurate. Consider using '#align option.join_eq_join Option.joinM_eq_join\u2093'. -/\ntheorem joinM_eq_join : joinM = @join \u03b1 :=\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {f : \u03b1 -> (Option.{u1} \u03b2)} {x : Option.{u1} \u03b1}, Eq.{succ u1} (Option.{u1} \u03b2) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b2 x f) (Option.bind.{u1, u1} \u03b1 \u03b2 x f)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {f : \u03b1 -> (Option.{u1} \u03b2)} {x : Option.{u1} \u03b1}, Eq.{succ u1} (Option.{u1} \u03b2) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b2 x f) (Option.bind.{u1, u1} \u03b1 \u03b2 x f)\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_bind Option.bind_eq_bind\u2093'. -/\ntheorem bind_eq_bind {\u03b1 \u03b2 : Type _} {f : \u03b1 \u2192 Option \u03b2} {x : Option \u03b1} : 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2}, Eq.{succ u1} ((Option.{u1} \u03b1) -> (Option.{u1} \u03b2)) (Functor.map.{u1, u1} Option.{u1} (Traversable.toFunctor.{u1} Option.{u1} Option.traversable.{u1}) \u03b1 \u03b2 f) (Option.map.{u1, u1} \u03b1 \u03b2 f)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2}, Eq.{succ u1} ((Option.{u1} \u03b1) -> (Option.{u1} \u03b2)) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} \u03b1 \u03b2 f) (Option.map.{u1, u1} \u03b1 \u03b2 f)\nCase conversion may be inaccurate. Consider using '#align option.map_eq_map Option.map_eq_map\u2093'. -/\n@[simp]\ntheorem map_eq_map {\u03b1 \u03b2} {f : \u03b1 \u2192 \u03b2} : (\u00b7 <$> \u00b7) 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} (Traversable.toFunctor.{u1} Option.{u1} Option.traversable.{u1}) \u03b1 \u03b2 f (Option.none.{u1} \u03b1)) (Option.none.{u1} \u03b2)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} \u03b1 \u03b2 f (Option.none.{u1} \u03b1)) (Option.none.{u1} \u03b2)\nCase conversion may be inaccurate. Consider using '#align option.map_none Option.map_none\u2093'. -/\ntheorem map_none {\u03b1 \u03b2} {f : \u03b1 \u2192 \u03b2} : 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {a : \u03b1} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} (Traversable.toFunctor.{u1} Option.{u1} Option.traversable.{u1}) \u03b1 \u03b2 f (Option.some.{u1} \u03b1 a)) (Option.some.{u1} \u03b2 (f a))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {a : \u03b1 -> \u03b2} {f : \u03b1}, Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} \u03b1 \u03b2 a (Option.some.{u1} \u03b1 f)) (Option.some.{u1} \u03b2 (a f))\nCase conversion may be inaccurate. Consider using '#align option.map_some Option.map_some\u2093'. -/\ntheorem map_some {\u03b1 \u03b2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {a : \u03b1} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} (fun {\u03b1 : Type.{u1}} => Option.{u1} \u03b1) (Traversable.toFunctor.{u1} (fun {\u03b1 : Type.{u1}} => Option.{u1} \u03b1) Option.traversable.{u1}) \u03b1 \u03b2 f ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) \u03b1 (Option.{u1} \u03b1) (HasLiftT.mk.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (CoeTC\u2093.coe.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (coeOption.{u1} \u03b1))) a)) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) \u03b2 (Option.{u1} \u03b2) (HasLiftT.mk.{succ u1, succ u1} \u03b2 (Option.{u1} \u03b2) (CoeTC\u2093.coe.{succ u1, succ u1} \u03b2 (Option.{u1} \u03b2) (coeOption.{u1} \u03b2))) (f a))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {a : \u03b1} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} \u03b1 \u03b2 f (Option.some.{u1} \u03b1 a)) (Option.some.{u1} \u03b2 (f a))\nCase conversion may be inaccurate. Consider using '#align option.map_coe Option.map_coe\u2093'. -/\ntheorem map_coe {\u03b1 \u03b2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> (a : Option \u03b1) = \u2191(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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {f : \u03b1 -> \u03b2}, Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f (Option.none.{u1} \u03b1)) (Option.none.{u2} \u03b2)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (f : \u03b1 -> \u03b2), Eq.{succ u1} (Option.{u1} \u03b2) (Option.map.{u2, u1} \u03b1 \u03b2 f (Option.none.{u2} \u03b1)) (Option.none.{u1} \u03b2)\nCase conversion may be inaccurate. Consider using '#align option.map_none' Option.map_none'\u2093'. -/\n@[simp]\ntheorem map_none' {f : \u03b1 \u2192 \u03b2} : 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {a : \u03b1} {f : \u03b1 -> \u03b2}, Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f (Option.some.{u1} \u03b1 a)) (Option.some.{u2} \u03b2 (f a))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (a : \u03b1) (f : \u03b1 -> \u03b2), Eq.{succ u1} (Option.{u1} \u03b2) (Option.map.{u2, u1} \u03b1 \u03b2 f (Option.some.{u2} \u03b1 a)) (Option.some.{u1} \u03b2 (f a))\nCase conversion may be inaccurate. Consider using '#align option.map_some' Option.map_some'\u2093'. -/\n@[simp]\ntheorem map_some' {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : 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 : \u03b1} {f : \u03b1 \u2192 \u03b2} : Option.map f (a : Option \u03b1) = \u2191(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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {x : Option.{u1} \u03b1} {f : \u03b1 -> \u03b2} {b : \u03b2}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} (fun {\u03b1 : Type.{u1}} => Option.{u1} \u03b1) (Traversable.toFunctor.{u1} (fun {\u03b1 : Type.{u1}} => Option.{u1} \u03b1) Option.traversable.{u1}) \u03b1 \u03b2 f x) (Option.some.{u1} \u03b2 b)) (Exists.{succ u1} \u03b1 (fun (a : \u03b1) => And (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.some.{u1} \u03b1 a)) (Eq.{succ u1} \u03b2 (f a) b)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {x : \u03b1 -> \u03b2} {f : Option.{u1} \u03b1} {b : \u03b2}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} \u03b1 \u03b2 x f) (Option.some.{u1} \u03b2 b)) (Exists.{succ u1} \u03b1 (fun (a : \u03b1) => And (Eq.{succ u1} (Option.{u1} \u03b1) f (Option.some.{u1} \u03b1 a)) (Eq.{succ u1} \u03b2 (x a) b)))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_some Option.map_eq_some\u2093'. -/\ntheorem map_eq_some {\u03b1 \u03b2} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} :\n    f <$> x = some b \u2194 \u2203 a, x = some a \u2227 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {x : Option.{u1} \u03b1} {f : \u03b1 -> \u03b2} {b : \u03b2}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f x) (Option.some.{u2} \u03b2 b)) (Exists.{succ u1} \u03b1 (fun (a : \u03b1) => And (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.some.{u1} \u03b1 a)) (Eq.{succ u2} \u03b2 (f a) b)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : \u03b1} {x : Type.{u1}} {f : Option.{u1} x} {b : x -> \u03b1}, Iff (Eq.{succ u2} (Option.{u2} \u03b1) (Option.map.{u1, u2} x \u03b1 b f) (Option.some.{u2} \u03b1 \u03b2)) (Exists.{succ u1} x (fun (a : x) => And (Eq.{succ u1} (Option.{u1} x) f (Option.some.{u1} x a)) (Eq.{succ u2} \u03b1 (b a) \u03b2)))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_some' Option.map_eq_some'\u2093'. -/\n@[simp]\ntheorem map_eq_some' {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} :\n    x.map f = some b \u2194 \u2203 a, x = some a \u2227 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {x : Option.{u1} \u03b1} {f : \u03b1 -> \u03b2}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} (fun {\u03b1 : Type.{u1}} => Option.{u1} \u03b1) (Traversable.toFunctor.{u1} (fun {\u03b1 : Type.{u1}} => Option.{u1} \u03b1) Option.traversable.{u1}) \u03b1 \u03b2 f x) (Option.none.{u1} \u03b2)) (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.none.{u1} \u03b1))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {x : \u03b1 -> \u03b2} {f : Option.{u1} \u03b1}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} \u03b1 \u03b2 x f) (Option.none.{u1} \u03b2)) (Eq.{succ u1} (Option.{u1} \u03b1) f (Option.none.{u1} \u03b1))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_none Option.map_eq_none\u2093'. -/\ntheorem map_eq_none {\u03b1 \u03b2} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> x = none \u2194 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {x : Option.{u1} \u03b1} {f : \u03b1 -> \u03b2}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f x) (Option.none.{u2} \u03b2)) (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.none.{u1} \u03b1))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Option.{u2} \u03b1} {x : Type.{u1}} {f : \u03b1 -> x}, Iff (Eq.{succ u1} (Option.{u1} x) (Option.map.{u2, u1} \u03b1 x f \u03b2) (Option.none.{u1} x)) (Eq.{succ u2} (Option.{u2} \u03b1) \u03b2 (Option.none.{u2} \u03b1))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_none' Option.map_eq_none'\u2093'. -/\n@[simp]\ntheorem map_eq_none' {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} : x.map f = none \u2194 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}}, Function.Injective.{max (succ u1) (succ u2), max (succ u1) (succ u2)} (\u03b1 -> \u03b2) ((Option.{u1} \u03b1) -> (Option.{u2} \u03b2)) (Option.map.{u1, u2} \u03b1 \u03b2)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}}, Function.Injective.{max (succ u2) (succ u1), max (succ u2) (succ u1)} (\u03b1 -> \u03b2) ((Option.{u2} \u03b1) -> (Option.{u1} \u03b2)) (Option.map.{u2, u1} \u03b1 \u03b2)\nCase conversion may be inaccurate. Consider using '#align option.map_injective' Option.map_injective'\u2093'. -/\n/-- `option.map` as a function between functions is injective. -/\ntheorem map_injective' : Function.Injective (@Option.map \u03b1 \u03b2) := fun f g h =>\n  funext fun x => some_injective _ <| by simp only [\u2190 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {f : \u03b1 -> \u03b2} {g : \u03b1 -> \u03b2}, Iff (Eq.{max (succ u1) (succ u2)} ((Option.{u1} \u03b1) -> (Option.{u2} \u03b2)) (Option.map.{u1, u2} \u03b1 \u03b2 f) (Option.map.{u1, u2} \u03b1 \u03b2 g)) (Eq.{max (succ u1) (succ u2)} (\u03b1 -> \u03b2) f g)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2} {g : \u03b1 -> \u03b2}, Iff (Eq.{max (succ u2) (succ u1)} ((Option.{u2} \u03b1) -> (Option.{u1} \u03b2)) (Option.map.{u2, u1} \u03b1 \u03b2 f) (Option.map.{u2, u1} \u03b1 \u03b2 g)) (Eq.{max (succ u2) (succ u1)} (\u03b1 -> \u03b2) f g)\nCase conversion may be inaccurate. Consider using '#align option.map_inj Option.map_inj\u2093'. -/\n@[simp]\ntheorem map_inj {f g : \u03b1 \u2192 \u03b2} : Option.map f = Option.map g \u2194 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {f : \u03b1 -> \u03b2} {g : \u03b1 -> \u03b2} {x : Option.{u1} \u03b1}, (forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (Eq.{succ u2} \u03b2 (f a) (g a))) -> (Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f x) (Option.map.{u1, u2} \u03b1 \u03b2 g x))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2} {g : \u03b1 -> \u03b2} {x : Option.{u2} \u03b1}, (forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (Eq.{succ u1} \u03b2 (f a) (g a))) -> (Eq.{succ u1} (Option.{u1} \u03b2) (Option.map.{u2, u1} \u03b1 \u03b2 f x) (Option.map.{u2, u1} \u03b1 \u03b2 g x))\nCase conversion may be inaccurate. Consider using '#align option.map_congr Option.map_congr\u2093'. -/\ntheorem map_congr {f g : \u03b1 \u2192 \u03b2} {x : Option \u03b1} (h : \u2200 a \u2208 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 : \u03b1 \u2192 \u03b1} : Option.map f = id \u2194 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (h : \u03b2 -> \u03b3) (g : \u03b1 -> \u03b2) (x : Option.{u1} \u03b1), Eq.{succ u3} (Option.{u3} \u03b3) (Option.map.{u2, u3} \u03b2 \u03b3 h (Option.map.{u1, u2} \u03b1 \u03b2 g x)) (Option.map.{u1, u3} \u03b1 \u03b3 (Function.comp.{succ u1, succ u2, succ u3} \u03b1 \u03b2 \u03b3 h g) x)\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (h : \u03b1 -> \u03b2) (g : \u03b3 -> \u03b1) (x : Option.{u1} \u03b3), Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u3, u2} \u03b1 \u03b2 h (Option.map.{u1, u3} \u03b3 \u03b1 g x)) (Option.map.{u1, u2} \u03b3 \u03b2 (Function.comp.{succ u1, succ u3, succ u2} \u03b3 \u03b1 \u03b2 h g) x)\nCase conversion may be inaccurate. Consider using '#align option.map_map Option.map_map\u2093'. -/\n@[simp]\ntheorem map_map (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2) (x : Option \u03b1) :\n    Option.map h (Option.map g x) = Option.map (h \u2218 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} {\u03b4 : Type.{u4}} {f\u2081 : \u03b1 -> \u03b2} {f\u2082 : \u03b1 -> \u03b3} {g\u2081 : \u03b2 -> \u03b4} {g\u2082 : \u03b3 -> \u03b4}, (Eq.{max (succ u1) (succ u4)} (\u03b1 -> \u03b4) (Function.comp.{succ u1, succ u2, succ u4} \u03b1 \u03b2 \u03b4 g\u2081 f\u2081) (Function.comp.{succ u1, succ u3, succ u4} \u03b1 \u03b3 \u03b4 g\u2082 f\u2082)) -> (forall (a : \u03b1), Eq.{succ u4} (Option.{u4} \u03b4) (Option.map.{u2, u4} \u03b2 \u03b4 g\u2081 (Option.map.{u1, u2} \u03b1 \u03b2 f\u2081 ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) \u03b1 (Option.{u1} \u03b1) (HasLiftT.mk.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (CoeTC\u2093.coe.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (coeOption.{u1} \u03b1))) a))) (Option.map.{u3, u4} \u03b3 \u03b4 g\u2082 (Option.map.{u1, u3} \u03b1 \u03b3 f\u2082 ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) \u03b1 (Option.{u1} \u03b1) (HasLiftT.mk.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (CoeTC\u2093.coe.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (coeOption.{u1} \u03b1))) a))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u4}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} {\u03b4 : Type.{u3}} {f\u2081 : \u03b1 -> \u03b2} {f\u2082 : \u03b1 -> \u03b3} {g\u2081 : \u03b2 -> \u03b4} {g\u2082 : \u03b3 -> \u03b4}, (Eq.{max (succ u4) (succ u3)} (\u03b1 -> \u03b4) (Function.comp.{succ u4, succ u2, succ u3} \u03b1 \u03b2 \u03b4 g\u2081 f\u2081) (Function.comp.{succ u4, succ u1, succ u3} \u03b1 \u03b3 \u03b4 g\u2082 f\u2082)) -> (forall (a : \u03b1), Eq.{succ u3} (Option.{u3} \u03b4) (Option.map.{u2, u3} \u03b2 \u03b4 g\u2081 (Option.map.{u4, u2} \u03b1 \u03b2 f\u2081 (Option.some.{u4} \u03b1 a))) (Option.map.{u1, u3} \u03b3 \u03b4 g\u2082 (Option.map.{u4, u1} \u03b1 \u03b3 f\u2082 (Option.some.{u4} \u03b1 a))))\nCase conversion may be inaccurate. Consider using '#align option.map_comm Option.map_comm\u2093'. -/\ntheorem map_comm {f\u2081 : \u03b1 \u2192 \u03b2} {f\u2082 : \u03b1 \u2192 \u03b3} {g\u2081 : \u03b2 \u2192 \u03b4} {g\u2082 : \u03b3 \u2192 \u03b4} (h : g\u2081 \u2218 f\u2081 = g\u2082 \u2218 f\u2082)\n    (a : \u03b1) : (Option.map f\u2081 a).map g\u2081 = (Option.map f\u2082 a).map g\u2082 := by rw [map_map, h, \u2190 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (h : \u03b2 -> \u03b3) (g : \u03b1 -> \u03b2) (x : Option.{u1} \u03b1), Eq.{succ u3} (Option.{u3} \u03b3) (Option.map.{u1, u3} \u03b1 \u03b3 (Function.comp.{succ u1, succ u2, succ u3} \u03b1 \u03b2 \u03b3 h g) x) (Option.map.{u2, u3} \u03b2 \u03b3 h (Option.map.{u1, u2} \u03b1 \u03b2 g x))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (h : \u03b1 -> \u03b2) (g : \u03b3 -> \u03b1) (x : Option.{u1} \u03b3), Eq.{succ u2} (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b3 \u03b2 (Function.comp.{succ u1, succ u3, succ u2} \u03b3 \u03b1 \u03b2 h g) x) (Option.map.{u3, u2} \u03b1 \u03b2 h (Option.map.{u1, u3} \u03b3 \u03b1 g x))\nCase conversion may be inaccurate. Consider using '#align option.comp_map Option.comp_map\u2093'. -/\ntheorem comp_map (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2) (x : Option \u03b1) :\n    Option.map (h \u2218 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (f : \u03b1 -> \u03b2) (g : \u03b2 -> \u03b3), Eq.{max (succ u1) (succ u3)} ((Option.{u1} \u03b1) -> (Option.{u3} \u03b3)) (Function.comp.{succ u1, succ u2, succ u3} (Option.{u1} \u03b1) (Option.{u2} \u03b2) (Option.{u3} \u03b3) (Option.map.{u2, u3} \u03b2 \u03b3 g) (Option.map.{u1, u2} \u03b1 \u03b2 f)) (Option.map.{u1, u3} \u03b1 \u03b3 (Function.comp.{succ u1, succ u2, succ u3} \u03b1 \u03b2 \u03b3 g f))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (f : \u03b1 -> \u03b2) (g : \u03b2 -> \u03b3), Eq.{max (succ u1) (succ u3)} ((Option.{u3} \u03b1) -> (Option.{u1} \u03b3)) (Function.comp.{succ u3, succ u2, succ u1} (Option.{u3} \u03b1) (Option.{u2} \u03b2) (Option.{u1} \u03b3) (Option.map.{u2, u1} \u03b2 \u03b3 g) (Option.map.{u3, u2} \u03b1 \u03b2 f)) (Option.map.{u3, u1} \u03b1 \u03b3 (Function.comp.{succ u3, succ u2, succ u1} \u03b1 \u03b2 \u03b3 g f))\nCase conversion may be inaccurate. Consider using '#align option.map_comp_map Option.map_comp_map\u2093'. -/\n@[simp]\ntheorem map_comp_map (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) : Option.map g \u2218 Option.map f = Option.map (g \u2218 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {a : \u03b1} {x : Option.{u1} \u03b1} (g : \u03b1 -> \u03b2), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (Membership.Mem.{u2, u2} \u03b2 (Option.{u2} \u03b2) (Option.hasMem.{u2} \u03b2) (g a) (Option.map.{u1, u2} \u03b1 \u03b2 g x))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {a : \u03b1} {x : Option.{u2} \u03b1} (g : \u03b1 -> \u03b2), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) (g a) (Option.map.{u2, u1} \u03b1 \u03b2 g x))\nCase conversion may be inaccurate. Consider using '#align option.mem_map_of_mem Option.mem_map_of_mem\u2093'. -/\ntheorem mem_map_of_mem {a : \u03b1} {x : Option \u03b1} (g : \u03b1 \u2192 \u03b2) (h : a \u2208 x) : g a \u2208 x.map g :=\n  mem_def.mpr ((mem_def.mp h).symm \u25b8 map_some')\n#align option.mem_map_of_mem Option.mem_map_of_mem\n\ntheorem mem_map {f : \u03b1 \u2192 \u03b2} {y : \u03b2} {o : Option \u03b1} : y \u2208 o.map f \u2194 \u2203 x \u2208 o, f x = y := by simp\n#align option.mem_map Option.mem_map\n\ntheorem forall_mem_map {f : \u03b1 \u2192 \u03b2} {o : Option \u03b1} {p : \u03b2 \u2192 Prop} :\n    (\u2200 y \u2208 o.map f, p y) \u2194 \u2200 x \u2208 o, p (f x) := by simp\n#align option.forall_mem_map Option.forall_mem_map\n\ntheorem exists_mem_map {f : \u03b1 \u2192 \u03b2} {o : Option \u03b1} {p : \u03b2 \u2192 Prop} :\n    (\u2203 y \u2208 o.map f, p y) \u2194 \u2203 x \u2208 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 {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_1}} {x : Option.{u_1} (Option.{u_1} \u03b1)} {f : \u03b1 -> \u03b2}, Eq.{succ u_1} (Option.{u_1} \u03b2) (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} \u03b1) \u03b2 x (Option.map.{u_1, u_1} \u03b1 \u03b2 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} \u03b2) \u03b2 (Option.map.{u_1, u_1} (Option.{u_1} \u03b1) (Option.{u_1} \u03b2) (Option.map.{u_1, u_1} \u03b1 \u03b2 f) x) (id.{succ u_1} (Option.{u_1} \u03b2)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u_1}} {\u03b2 : Type.{u_2}} {x : Option.{u_1} (Option.{u_1} \u03b1)} {f : \u03b1 -> \u03b2}, Eq.{succ u_2} (Option.{u_2} \u03b2) (Option.bind.{u_1, u_2} (Option.{u_1} \u03b1) \u03b2 x (Option.map.{u_1, u_2} \u03b1 \u03b2 f)) (Option.bind.{u_2, u_2} (Option.{u_2} \u03b2) \u03b2 (Option.map.{u_1, u_2} (Option.{u_1} \u03b1) (Option.{u_2} \u03b2) (Option.map.{u_1, u_2} \u03b1 \u03b2 f) x) (id.{succ u_2} (Option.{u_2} \u03b2)))\nCase conversion may be inaccurate. Consider using '#align option.bind_map_comm Option.bind_map_comm\u2093'. -/\ntheorem bind_map_comm {\u03b1 \u03b2} {x : Option (Option \u03b1)} {f : \u03b1 \u2192 \u03b2} :\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {f : \u03b1 -> \u03b2} {x : Option.{u1} (Option.{u1} \u03b1)}, Eq.{succ u2} (Option.{u2} \u03b2) (Option.join.{u2} \u03b2 (Option.map.{u1, u2} (Option.{u1} \u03b1) (Option.{u2} \u03b2) (Option.map.{u1, u2} \u03b1 \u03b2 f) x)) (Option.map.{u1, u2} \u03b1 \u03b2 f (Option.join.{u1} \u03b1 x))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {f : \u03b1 -> \u03b2} {x : Option.{u2} (Option.{u2} \u03b1)}, Eq.{succ u1} (Option.{u1} \u03b2) (Option.join.{u1} \u03b2 (Option.map.{u2, u1} (Option.{u2} \u03b1) (Option.{u1} \u03b2) (Option.map.{u2, u1} \u03b1 \u03b2 f) x)) (Option.map.{u2, u1} \u03b1 \u03b2 f (Option.join.{u2} \u03b1 x))\nCase conversion may be inaccurate. Consider using '#align option.join_map_eq_map_join Option.join_map_eq_map_join\u2093'. -/\ntheorem join_map_eq_map_join {f : \u03b1 \u2192 \u03b2} {x : Option (Option \u03b1)} :\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 \u03b1))} : 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 : \u03b1} {x : Option (Option \u03b1)} (h : a \u2208 x.join) : some a \u2208 x :=\n  mem_def.mpr ((mem_def.mp h).symm \u25b8 join_eq_some.mp h)\n#align option.mem_of_mem_join Option.mem_of_mem_join\n-/\n\nsection Pmap\n\nvariable {p : \u03b1 \u2192 Prop} (f : \u2200 a : \u03b1, p a \u2192 \u03b2) (x : Option \u03b1)\n\n#print Option.pbind_eq_bind /-\n@[simp]\ntheorem pbind_eq_bind (f : \u03b1 \u2192 Option \u03b2) (x : Option \u03b1) : (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u1}} (f : \u03b2 -> \u03b3) (x : Option.{u1} \u03b1) (g : \u03b1 -> (Option.{u1} \u03b2)), Eq.{succ u1} (Option.{u1} \u03b3) (Option.map.{u1, u1} \u03b2 \u03b3 f (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b2 x g)) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b3 x (fun (a : \u03b1) => Option.map.{u1, u1} \u03b2 \u03b3 f (g a)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u1}} (f : \u03b2 -> \u03b3) (x : Option.{u1} \u03b1) (g : \u03b1 -> (Option.{u1} \u03b2)), Eq.{succ u1} (Option.{u1} \u03b3) (Option.map.{u1, u1} \u03b2 \u03b3 f (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b2 x g)) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b3 x (fun (a : \u03b1) => Option.map.{u1, u1} \u03b2 \u03b3 f (g a)))\nCase conversion may be inaccurate. Consider using '#align option.map_bind Option.map_bind\u2093'. -/\ntheorem map_bind {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1) (g : \u03b1 \u2192 Option \u03b2) :\n    Option.map f (x >>= g) = x >>= fun a => Option.map f (g a) := by\n  simp_rw [\u2190 map_eq_map, \u2190 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (f : \u03b2 -> \u03b3) (x : Option.{u1} \u03b1) (g : \u03b1 -> (Option.{u2} \u03b2)), Eq.{succ u3} (Option.{u3} \u03b3) (Option.map.{u2, u3} \u03b2 \u03b3 f (Option.bind.{u1, u2} \u03b1 \u03b2 x g)) (Option.bind.{u1, u3} \u03b1 \u03b3 x (fun (a : \u03b1) => Option.map.{u2, u3} \u03b2 \u03b3 f (g a)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (f : \u03b2 -> \u03b3) (x : Option.{u3} \u03b1) (g : \u03b1 -> (Option.{u2} \u03b2)), Eq.{succ u1} (Option.{u1} \u03b3) (Option.map.{u2, u1} \u03b2 \u03b3 f (Option.bind.{u3, u2} \u03b1 \u03b2 x g)) (Option.bind.{u3, u1} \u03b1 \u03b3 x (fun (a : \u03b1) => Option.map.{u2, u1} \u03b2 \u03b3 f (g a)))\nCase conversion may be inaccurate. Consider using '#align option.map_bind' Option.map_bind'\u2093'. -/\ntheorem map_bind' (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1) (g : \u03b1 \u2192 Option \u03b2) :\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (f : \u03b2 -> \u03b3) (x : Option.{u1} \u03b1) (g : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (Option.{u2} \u03b2)), Eq.{succ u3} (Option.{u3} \u03b3) (Option.map.{u2, u3} \u03b2 \u03b3 f (Option.pbind.{u1, u2} \u03b1 \u03b2 x g)) (Option.pbind.{u1, u3} \u03b1 \u03b3 x (fun (a : \u03b1) (H : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) => Option.map.{u2, u3} \u03b2 \u03b3 f (g a H)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (f : \u03b2 -> \u03b3) (x : Option.{u3} \u03b1) (g : forall (a : \u03b1), (Membership.mem.{u3, u3} \u03b1 (Option.{u3} \u03b1) (Option.instMembershipOption.{u3} \u03b1) a x) -> (Option.{u2} \u03b2)), Eq.{succ u1} (Option.{u1} \u03b3) (Option.map.{u2, u1} \u03b2 \u03b3 f (Option.pbind.{u3, u2} \u03b1 \u03b2 x g)) (Option.pbind.{u3, u1} \u03b1 \u03b3 x (fun (a : \u03b1) (H : Membership.mem.{u3, u3} \u03b1 (Option.{u3} \u03b1) (Option.instMembershipOption.{u3} \u03b1) a x) => Option.map.{u2, u1} \u03b2 \u03b3 f (g a H)))\nCase conversion may be inaccurate. Consider using '#align option.map_pbind Option.map_pbind\u2093'. -/\ntheorem map_pbind (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1) (g : \u2200 a, a \u2208 x \u2192 Option \u03b2) :\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} (f : \u03b1 -> \u03b2) (x : Option.{u1} \u03b1) (g : forall (b : \u03b2), (Membership.Mem.{u2, u2} \u03b2 (Option.{u2} \u03b2) (Option.hasMem.{u2} \u03b2) b (Option.map.{u1, u2} \u03b1 \u03b2 f x)) -> (Option.{u3} \u03b3)), Eq.{succ u3} (Option.{u3} \u03b3) (Option.pbind.{u2, u3} \u03b2 \u03b3 (Option.map.{u1, u2} \u03b1 \u03b2 f x) g) (Option.pbind.{u1, u3} \u03b1 \u03b3 x (fun (a : \u03b1) (h : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) => g (f a) (Option.mem_map_of_mem.{u1, u2} \u03b1 \u03b2 a x f h)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} (f : \u03b1 -> \u03b2) (x : Option.{u3} \u03b1) (g : forall (b : \u03b2), (Membership.mem.{u2, u2} \u03b2 (Option.{u2} \u03b2) (Option.instMembershipOption.{u2} \u03b2) b (Option.map.{u3, u2} \u03b1 \u03b2 f x)) -> (Option.{u1} \u03b3)), Eq.{succ u1} (Option.{u1} \u03b3) (Option.pbind.{u2, u1} \u03b2 \u03b3 (Option.map.{u3, u2} \u03b1 \u03b2 f x) g) (Option.pbind.{u3, u1} \u03b1 \u03b3 x (fun (a : \u03b1) (h : Membership.mem.{u3, u3} \u03b1 (Option.{u3} \u03b1) (Option.instMembershipOption.{u3} \u03b1) a x) => g (f a) (Option.mem_map_of_mem.{u2, u3} \u03b1 \u03b2 a x f h)))\nCase conversion may be inaccurate. Consider using '#align option.pbind_map Option.pbind_map\u2093'. -/\ntheorem pbind_map (f : \u03b1 \u2192 \u03b2) (x : Option \u03b1) (g : \u2200 b : \u03b2, b \u2208 x.map f \u2192 Option \u03b3) :\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) {H : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a (Option.none.{u1} \u03b1)) -> (p a)}, Eq.{succ u2} (Option.{u2} \u03b2) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f (Option.none.{u1} \u03b1) H) (Option.none.{u2} \u03b2)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) {H : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a (Option.none.{u2} \u03b1)) -> (p a)}, Eq.{succ u1} (Option.{u1} \u03b2) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f (Option.none.{u2} \u03b1) H) (Option.none.{u1} \u03b2)\nCase conversion may be inaccurate. Consider using '#align option.pmap_none Option.pmap_none\u2093'. -/\n@[simp]\ntheorem pmap_none (f : \u2200 a : \u03b1, p a \u2192 \u03b2) {H} : pmap f (@none \u03b1) H = none :=\n  rfl\n#align option.pmap_none Option.pmap_none\n\n#print Option.pmap_some /-\n@[simp]\ntheorem pmap_some (f : \u2200 a : \u03b1, p a \u2192 \u03b2) {x : \u03b1} (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) (x : Option.{u1} \u03b1) {a : \u03b1} (h : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (p a)) (ha : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x), Membership.Mem.{u2, u2} \u03b2 (Option.{u2} \u03b2) (Option.hasMem.{u2} \u03b2) (f a (h a ha)) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x h)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) (x : Option.{u2} \u03b1) {a : \u03b1} (h : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (p a)) (ha : Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x), Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) (f a (h a ha)) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x h)\nCase conversion may be inaccurate. Consider using '#align option.mem_pmem Option.mem_pmem\u2093'. -/\ntheorem mem_pmem {a : \u03b1} (h : \u2200 a \u2208 x, p a) (ha : a \u2208 x) : f a (h a ha) \u2208 pmap f x h :=\n  by\n  rw [mem_def] at ha\u22a2\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) (g : \u03b3 -> \u03b1) (x : Option.{u3} \u03b3) (H : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a (Option.map.{u3, u1} \u03b3 \u03b1 g x)) -> (p a)), Eq.{succ u2} (Option.{u2} \u03b2) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f (Option.map.{u3, u1} \u03b3 \u03b1 g x) H) (Option.pmap.{u3, u2} \u03b3 \u03b2 (fun (a : \u03b3) => p (g a)) (fun (a : \u03b3) (h : p (g a)) => f (g a) h) x (fun (a : \u03b3) (h : Membership.Mem.{u3, u3} \u03b3 (Option.{u3} \u03b3) (Option.hasMem.{u3} \u03b3) a x) => H (g a) (Option.mem_map_of_mem.{u3, u1} \u03b3 \u03b1 a x g h)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u3}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) (g : \u03b3 -> \u03b1) (x : Option.{u3} \u03b3) (H : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a (Option.map.{u3, u2} \u03b3 \u03b1 g x)) -> (p a)), Eq.{succ u1} (Option.{u1} \u03b2) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f (Option.map.{u3, u2} \u03b3 \u03b1 g x) H) (Option.pmap.{u3, u1} \u03b3 \u03b2 (fun (a : \u03b3) => p (g a)) (fun (a : \u03b3) (h : p (g a)) => f (g a) h) x (fun (a : \u03b3) (h : Membership.mem.{u3, u3} \u03b3 (Option.{u3} \u03b3) (Option.instMembershipOption.{u3} \u03b3) a x) => H (g a) (Option.mem_map_of_mem.{u2, u3} \u03b3 \u03b1 a x g h)))\nCase conversion may be inaccurate. Consider using '#align option.pmap_map Option.pmap_map\u2093'. -/\ntheorem pmap_map (g : \u03b3 \u2192 \u03b1) (x : Option \u03b3) (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u3}} {p : \u03b1 -> Prop} (g : \u03b2 -> \u03b3) (f : forall (a : \u03b1), (p a) -> \u03b2) (x : Option.{u1} \u03b1) (H : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (p a)), Eq.{succ u3} (Option.{u3} \u03b3) (Option.map.{u2, u3} \u03b2 \u03b3 g (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x H)) (Option.pmap.{u1, u3} \u03b1 \u03b3 (fun (a : \u03b1) => p a) (fun (a : \u03b1) (h : p a) => g (f a h)) x H)\nbut is expected to have type\n  forall {\u03b1 : Type.{u3}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u2}} {p : \u03b1 -> Prop} (g : \u03b2 -> \u03b3) (f : forall (a : \u03b1), (p a) -> \u03b2) (x : Option.{u3} \u03b1) (H : forall (a : \u03b1), (Membership.mem.{u3, u3} \u03b1 (Option.{u3} \u03b1) (Option.instMembershipOption.{u3} \u03b1) a x) -> (p a)), Eq.{succ u2} (Option.{u2} \u03b3) (Option.map.{u1, u2} \u03b2 \u03b3 g (Option.pmap.{u3, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x H)) (Option.pmap.{u3, u2} \u03b1 \u03b3 (fun (a : \u03b1) => p a) (fun (a : \u03b1) (h : p a) => g (f a h)) x H)\nCase conversion may be inaccurate. Consider using '#align option.map_pmap Option.map_pmap\u2093'. -/\ntheorem map_pmap (g : \u03b2 \u2192 \u03b3) (f : \u2200 a, p a \u2192 \u03b2) (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} (p : \u03b1 -> Prop) (f : \u03b1 -> \u03b2) (x : Option.{u1} \u03b1) (H : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (p a)), Eq.{succ u2} (Option.{u2} \u03b2) (Option.pmap.{u1, u2} \u03b1 \u03b2 p (fun (a : \u03b1) (_x : p a) => f a) x H) (Option.map.{u1, u2} \u03b1 \u03b2 f x)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (p : \u03b1 -> Prop) (f : \u03b1 -> \u03b2) (x : Option.{u2} \u03b1) (H : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (p a)), Eq.{succ u1} (Option.{u1} \u03b2) (Option.pmap.{u2, u1} \u03b1 \u03b2 p (fun (a : \u03b1) (_x : p a) => f a) x H) (Option.map.{u2, u1} \u03b1 \u03b2 f x)\nCase conversion may be inaccurate. Consider using '#align option.pmap_eq_map Option.pmap_eq_map\u2093'. -/\n@[simp]\ntheorem pmap_eq_map (p : \u03b1 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u1}} {x : Option.{u1} \u03b1} {g : \u03b1 -> (Option.{u1} \u03b2)} {p : \u03b2 -> Prop} {f : forall (b : \u03b2), (p b) -> \u03b3} (H : forall (a : \u03b2), (Membership.Mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.hasMem.{u1} \u03b2) a (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b2 x g)) -> (p a)) (H' : forall (a : \u03b1) (b : \u03b2), (Membership.Mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.hasMem.{u1} \u03b2) b (g a)) -> (Membership.Mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.hasMem.{u1} \u03b2) b (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b2 x g))), Eq.{succ u1} (Option.{u1} \u03b3) (Option.pmap.{u1, u1} \u03b2 \u03b3 (fun (b : \u03b2) => p b) f (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b2 x g) H) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) \u03b1 \u03b3 x (fun (a : \u03b1) => Option.pmap.{u1, u1} \u03b2 \u03b3 (fun (b : \u03b2) => p b) f (g a) (fun (b : \u03b2) (h : Membership.Mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.hasMem.{u1} \u03b2) b (g a)) => H b (H' a b h))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u1}} {x : Option.{u1} \u03b1} {g : \u03b1 -> (Option.{u1} \u03b2)} {p : \u03b2 -> Prop} {f : forall (b : \u03b2), (p b) -> \u03b3} (H : forall (a : \u03b2), (Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) a (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b2 x g)) -> (p a)) (H' : forall (a : \u03b1) (b : \u03b2), (Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) b (g a)) -> (Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) b (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b2 x g))), Eq.{succ u1} (Option.{u1} \u03b3) (Option.pmap.{u1, u1} \u03b2 \u03b3 (fun (b : \u03b2) => p b) f (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b2 x g) H) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b1 \u03b3 x (fun (a : \u03b1) => Option.pmap.{u1, u1} \u03b2 \u03b3 (fun (b : \u03b2) => p b) f (g a) (fun (b : \u03b2) (h : Membership.mem.{u1, u1} \u03b2 (Option.{u1} \u03b2) (Option.instMembershipOption.{u1} \u03b2) b (g a)) => H b (H' a b h))))\nCase conversion may be inaccurate. Consider using '#align option.pmap_bind Option.pmap_bind\u2093'. -/\ntheorem pmap_bind {\u03b1 \u03b2 \u03b3} {x : Option \u03b1} {g : \u03b1 \u2192 Option \u03b2} {p : \u03b2 \u2192 Prop} {f : \u2200 b, p b \u2192 \u03b3} (H)\n    (H' : \u2200 (a : \u03b1), \u2200 b \u2208 g a, b \u2208 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u2}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) (x : Option.{u1} \u03b1) (g : \u03b2 -> (Option.{u2} \u03b3)) (H : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (p a)), Eq.{succ u2} (Option.{u2} \u03b3) (Bind.bind.{u2, u2} Option.{u2} (Monad.toHasBind.{u2, u2} Option.{u2} Option.monad.{u2}) \u03b2 \u03b3 (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x H) g) (Option.pbind.{u1, u2} \u03b1 \u03b3 x (fun (a : \u03b1) (h : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) => g (f a (H a h))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {\u03b3 : Type.{u1}} {p : \u03b1 -> Prop} (f : forall (a : \u03b1), (p a) -> \u03b2) (x : Option.{u2} \u03b1) (g : \u03b2 -> (Option.{u1} \u03b3)) (H : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (p a)), Eq.{succ u1} (Option.{u1} \u03b3) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) \u03b2 \u03b3 (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x H) g) (Option.pbind.{u2, u1} \u03b1 \u03b3 x (fun (a : \u03b1) (h : Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) => g (f a (H a h))))\nCase conversion may be inaccurate. Consider using '#align option.bind_pmap Option.bind_pmap\u2093'. -/\ntheorem bind_pmap {\u03b1 \u03b2 \u03b3} {p : \u03b1 \u2192 Prop} (f : \u2200 a, p a \u2192 \u03b2) (x : Option \u03b1) (g : \u03b2 \u2192 Option \u03b3) (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {x : Option.{u1} \u03b1} {f : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (Option.{u2} \u03b2)}, (forall (a : \u03b1) (H : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x), (Eq.{succ u2} (Option.{u2} \u03b2) (f a H) (Option.none.{u2} \u03b2)) -> (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.none.{u1} \u03b1))) -> (Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.pbind.{u1, u2} \u03b1 \u03b2 x f) (Option.none.{u2} \u03b2)) (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.none.{u1} \u03b1)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {x : Option.{u2} \u03b1} {f : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (Option.{u1} \u03b2)}, (forall (a : \u03b1) (H : Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x), (Eq.{succ u1} (Option.{u1} \u03b2) (f a H) (Option.none.{u1} \u03b2)) -> (Eq.{succ u2} (Option.{u2} \u03b1) x (Option.none.{u2} \u03b1))) -> (Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Option.pbind.{u2, u1} \u03b1 \u03b2 x f) (Option.none.{u1} \u03b2)) (Eq.{succ u2} (Option.{u2} \u03b1) x (Option.none.{u2} \u03b1)))\nCase conversion may be inaccurate. Consider using '#align option.pbind_eq_none Option.pbind_eq_none\u2093'. -/\ntheorem pbind_eq_none {f : \u2200 a : \u03b1, a \u2208 x \u2192 Option \u03b2} (h' : \u2200 a \u2208 x, f a H = none \u2192 x = none) :\n    x.pbind f = none \u2194 x = none := by\n  cases x\n  \u00b7 simp\n  \u00b7 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {x : Option.{u1} \u03b1} {f : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (Option.{u2} \u03b2)} {y : \u03b2}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.pbind.{u1, u2} \u03b1 \u03b2 x f) (Option.some.{u2} \u03b2 y)) (Exists.{succ u1} \u03b1 (fun (z : \u03b1) => Exists.{0} (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) z x) (fun (H : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) z x) => Eq.{succ u2} (Option.{u2} \u03b2) (f z H) (Option.some.{u2} \u03b2 y))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {x : Option.{u2} \u03b1} {f : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (Option.{u1} \u03b2)} {y : \u03b2}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Option.pbind.{u2, u1} \u03b1 \u03b2 x f) (Option.some.{u1} \u03b2 y)) (Exists.{succ u2} \u03b1 (fun (z : \u03b1) => Exists.{0} (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) z x) (fun (H : Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) z x) => Eq.{succ u1} (Option.{u1} \u03b2) (f z H) (Option.some.{u1} \u03b2 y))))\nCase conversion may be inaccurate. Consider using '#align option.pbind_eq_some Option.pbind_eq_some\u2093'. -/\ntheorem pbind_eq_some {f : \u2200 a : \u03b1, a \u2208 x \u2192 Option \u03b2} {y : \u03b2} :\n    x.pbind f = some y \u2194 \u2203 z \u2208 x, f z H = some y :=\n  by\n  cases x\n  \u00b7 simp\n  \u00b7 simp only [pbind]\n    constructor\n    \u00b7 intro h\n      use x\n      simpa only [mem_def, exists_prop_of_true] using h\n    \u00b7 rintro \u27e8z, H, hz\u27e9\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {p : \u03b1 -> Prop} {f : forall (a : \u03b1), (p a) -> \u03b2} {x : Option.{u1} \u03b1} {h : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (p a)}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x h) (Option.none.{u2} \u03b2)) (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.none.{u1} \u03b1))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {p : \u03b1 -> Prop} {f : forall (a : \u03b1), (p a) -> \u03b2} {x : Option.{u2} \u03b1} {h : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (p a)}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x h) (Option.none.{u1} \u03b2)) (Eq.{succ u2} (Option.{u2} \u03b1) x (Option.none.{u2} \u03b1))\nCase conversion may be inaccurate. Consider using '#align option.pmap_eq_none_iff Option.pmap_eq_none_iff\u2093'. -/\n@[simp]\ntheorem pmap_eq_none_iff {h} : pmap f x h = none \u2194 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {p : \u03b1 -> Prop} {f : forall (a : \u03b1), (p a) -> \u03b2} {x : Option.{u1} \u03b1} {hf : forall (a : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a x) -> (p a)} {y : \u03b2}, Iff (Eq.{succ u2} (Option.{u2} \u03b2) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x hf) (Option.some.{u2} \u03b2 y)) (Exists.{succ u1} \u03b1 (fun (a : \u03b1) => Exists.{0} (Eq.{succ u1} (Option.{u1} \u03b1) x (Option.some.{u1} \u03b1 a)) (fun (H : Eq.{succ u1} (Option.{u1} \u03b1) x (Option.some.{u1} \u03b1 a)) => Eq.{succ u2} \u03b2 (f a (hf a H)) y)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {p : \u03b1 -> Prop} {f : forall (a : \u03b1), (p a) -> \u03b2} {x : Option.{u2} \u03b1} {hf : forall (a : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a x) -> (p a)} {y : \u03b2}, Iff (Eq.{succ u1} (Option.{u1} \u03b2) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f x hf) (Option.some.{u1} \u03b2 y)) (Exists.{succ u2} \u03b1 (fun (a : \u03b1) => Exists.{0} (Eq.{succ u2} (Option.{u2} \u03b1) x (Option.some.{u2} \u03b1 a)) (fun (H : Eq.{succ u2} (Option.{u2} \u03b1) x (Option.some.{u2} \u03b1 a)) => Eq.{succ u1} \u03b2 (f a (hf a H)) y)))\nCase conversion may be inaccurate. Consider using '#align option.pmap_eq_some_iff Option.pmap_eq_some_iff\u2093'. -/\n@[simp]\ntheorem pmap_eq_some_iff {hf} {y : \u03b2} :\n    pmap f x hf = some y \u2194 \u2203 (a : \u03b1)(H : x = some a), f a (hf a H) = y :=\n  by\n  cases x\n  \u00b7 simp only [not_mem_none, exists_false, pmap, not_false_iff, exists_prop_of_false]\n  \u00b7 constructor\n    \u00b7 intro h\n      simp only [pmap] at h\n      exact \u27e8x, rfl, h\u27e9\n    \u00b7 rintro \u27e8a, H, rfl\u27e9\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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {p : \u03b1 -> Prop} {f : forall (a : \u03b1), (p a) -> \u03b2} {x : Option.{u1} (Option.{u1} \u03b1)} (H : forall (a : Option.{u1} \u03b1), (Membership.Mem.{u1, u1} (Option.{u1} \u03b1) (Option.{u1} (Option.{u1} \u03b1)) (Option.hasMem.{u1} (Option.{u1} \u03b1)) a x) -> (forall (a_1 : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a_1 a) -> (p a_1))), Eq.{succ u2} (Option.{u2} \u03b2) (Option.join.{u2} \u03b2 (Option.pmap.{u1, u2} (Option.{u1} \u03b1) (Option.{u2} \u03b2) (fun (a : Option.{u1} \u03b1) => forall (a_1 : \u03b1), (Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a_1 a) -> (p a_1)) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f) x H)) (Option.pmap.{u1, u2} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f (Option.join.{u1} \u03b1 x) (fun (a : \u03b1) (h : Membership.Mem.{u1, u1} \u03b1 (Option.{u1} \u03b1) (Option.hasMem.{u1} \u03b1) a (Option.join.{u1} \u03b1 x)) => H (Option.some.{u1} \u03b1 a) (Option.mem_of_mem_join.{u1} \u03b1 a x h) a (rfl.{succ u1} (Option.{u1} \u03b1) (Option.some.{u1} \u03b1 a))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} {p : \u03b1 -> Prop} {f : forall (a : \u03b1), (p a) -> \u03b2} {x : Option.{u2} (Option.{u2} \u03b1)} (H : forall (a : Option.{u2} \u03b1), (Membership.mem.{u2, u2} (Option.{u2} \u03b1) (Option.{u2} (Option.{u2} \u03b1)) (Option.instMembershipOption.{u2} (Option.{u2} \u03b1)) a x) -> (forall (a_1 : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a_1 a) -> (p a_1))), Eq.{succ u1} (Option.{u1} \u03b2) (Option.join.{u1} \u03b2 (Option.pmap.{u2, u1} (Option.{u2} \u03b1) (Option.{u1} \u03b2) (fun (a : Option.{u2} \u03b1) => forall (a_1 : \u03b1), (Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a_1 a) -> (p a_1)) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f) x H)) (Option.pmap.{u2, u1} \u03b1 \u03b2 (fun (a : \u03b1) => p a) f (Option.join.{u2} \u03b1 x) (fun (a : \u03b1) (h : Membership.mem.{u2, u2} \u03b1 (Option.{u2} \u03b1) (Option.instMembershipOption.{u2} \u03b1) a (Option.join.{u2} \u03b1 x)) => H (Option.some.{u2} \u03b1 a) (Option.mem_of_mem_join.{u2} \u03b1 a x h) a (rfl.{succ u2} (Option.{u2} \u03b1) (Option.some.{u2} \u03b1 a))))\nCase conversion may be inaccurate. Consider using '#align option.join_pmap_eq_pmap_join Option.join_pmap_eq_pmap_join\u2093'. -/\n@[simp]\ntheorem join_pmap_eq_pmap_join {f : \u2200 a, p a \u2192 \u03b2} {x : Option (Option \u03b1)} (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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {a : \u03b1} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Seq.seq.{u1, u1} Option.{u1} (Applicative.toHasSeq.{u1, u1} Option.{u1} (Monad.toApplicative.{u1, u1} Option.{u1} Option.monad.{u1})) \u03b1 \u03b2 (Option.some.{u1} (\u03b1 -> \u03b2) f) (Option.some.{u1} \u03b1 a)) (Option.some.{u1} \u03b2 (f a))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {a : \u03b1} {f : \u03b1 -> \u03b2}, Eq.{succ u1} (Option.{u1} \u03b2) (Seq.seq.{u1, u1} Option.{u1} (Applicative.toSeq.{u1, u1} Option.{u1} (Alternative.toApplicative.{u1, u1} Option.{u1} instAlternativeOption.{u1})) \u03b1 \u03b2 (Option.some.{u1} (\u03b1 -> \u03b2) f) (fun (x._@.Mathlib.Data.Option.Basic._hyg.2260 : Unit) => Option.some.{u1} \u03b1 a)) (Option.some.{u1} \u03b2 (f a))\nCase conversion may be inaccurate. Consider using '#align option.seq_some Option.seq_some\u2093'. -/\n@[simp]\ntheorem seq_some {\u03b1 \u03b2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : 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 : \u03b1) (x : Option \u03b1) : (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 {\u03b1 : Type.{u1}} (a : \u03b1) (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) \u03b1 (Option.some.{u1} \u03b1 a) x) (Option.some.{u1} \u03b1 a)\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (a : \u03b1) (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} \u03b1) (Option.{u1} \u03b1) (Option.{u1} \u03b1) (instHOrElse.{u1} (Option.{u1} \u03b1) (Option.instOrElseOption.{u1} \u03b1)) (Option.some.{u1} \u03b1 a) (fun (x._@.Std.Data.Option.Lemmas._hyg.3089 : Unit) => x)) (Option.some.{u1} \u03b1 a)\nCase conversion may be inaccurate. Consider using '#align option.some_orelse Option.some_orElse\u2093'. -/\n@[simp]\ntheorem some_orElse (a : \u03b1) (x : Option \u03b1) : (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 {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (Option.orelse.{u1} \u03b1 (Option.none.{u1} \u03b1) x) x\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (Option.orElse.{u1} \u03b1 (Option.none.{u1} \u03b1) (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'\u2093'. -/\n@[simp]\ntheorem none_orElse' (x : Option \u03b1) : 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 {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) \u03b1 (Option.none.{u1} \u03b1) x) x\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} \u03b1) (Option.{u1} \u03b1) (Option.{u1} \u03b1) (instHOrElse.{u1} (Option.{u1} \u03b1) (Option.instOrElseOption.{u1} \u03b1)) (Option.none.{u1} \u03b1) (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\u2093'. -/\n@[simp]\ntheorem none_orElse (x : Option \u03b1) : (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 \u03b1) : 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 {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) \u03b1 x (Option.none.{u1} \u03b1)) x\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (x : Option.{u1} \u03b1), Eq.{succ u1} (Option.{u1} \u03b1) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} \u03b1) (Option.{u1} \u03b1) (Option.{u1} \u03b1) (instHOrElse.{u1} (Option.{u1} \u03b1) (Option.instOrElseOption.{u1} \u03b1)) x (fun (x._@.Std.Data.Option.Lemmas._hyg.3117 : Unit) => Option.none.{u1} \u03b1)) x\nCase conversion may be inaccurate. Consider using '#align option.orelse_none Option.orElse_none\u2093'. -/\n@[simp]\ntheorem orElse_none (x : Option \u03b1) : (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 \u03b1 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 : \u03b1} : 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 \u03b1} : isSome x \u2194 \u2203 a, x = some a := by\n  cases x <;> simp [is_some] <;> exact \u27e8_, rfl\u27e9\n#align option.is_some_iff_exists Option.isSome_iff_exists\n-/\n\n#print Option.isNone_none /-\n@[simp]\ntheorem isNone_none : @isNone \u03b1 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 : \u03b1} : 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 \u03b1} : isSome a = false \u2194 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 \u03b1} {a : \u03b1} : o = some a \u2194 \u2203 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 \u03b1} : \u00aco.isSome \u2194 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 \u03b1} : o \u2260 none \u2194 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 \u03b1} : o \u2260 none \u2194 \u2203 x : \u03b1, 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 \u03b1} : o \u2260 none \u2194 \u2203 x : \u03b1, 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 \u00abexpr \u2260 \u00bb none[option.none]) -/\n#print Option.bex_ne_none /-\ntheorem bex_ne_none {p : Option \u03b1 \u2192 Prop} : (\u2203 (x : _)(_ : x \u2260 none), p x) \u2194 \u2203 x, p (some x) :=\n  \u27e8fun \u27e8x, hx, hp\u27e9 => \u27e8get <| ne_none_iff_isSome.1 hx, by rwa [some_get]\u27e9, fun \u27e8x, hx\u27e9 =>\n    \u27e8some x, some_ne_none x, hx\u27e9\u27e9\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 \u00abexpr \u2260 \u00bb none[option.none]) -/\n#print Option.ball_ne_none /-\ntheorem ball_ne_none {p : Option \u03b1 \u2192 Prop} : (\u2200 (x) (_ : x \u2260 none), p x) \u2194 \u2200 x, p (some x) :=\n  \u27e8fun 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)\u27e9\n#align option.ball_ne_none Option.ball_ne_none\n-/\n\n#print Option.iget_mem /-\ntheorem iget_mem [Inhabited \u03b1] : \u2200 {o : Option \u03b1}, isSome o \u2192 o.iget \u2208 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 \u03b1] {a : \u03b1} : \u2200 {o : Option \u03b1}, a \u2208 o \u2192 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 \u03b1] (o : Option \u03b1) : 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 {\u03b1 : Type.{u1}} {p : \u03b1 -> Prop} [_inst_1 : DecidablePred.{succ u1} \u03b1 p] {a : \u03b1} {b : \u03b1}, Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.guard.{u1} \u03b1 p (fun (a : \u03b1) => _inst_1 a) a) (Option.some.{u1} \u03b1 b)) (And (Eq.{succ u1} \u03b1 a b) (p a))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} {p : \u03b1 -> Prop} {_inst_1 : \u03b1} {a : \u03b1} [b : DecidablePred.{succ u1} \u03b1 p], Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.guard.{u1} \u03b1 p (fun (a : \u03b1) => b a) _inst_1) (Option.some.{u1} \u03b1 a)) (And (Eq.{succ u1} \u03b1 _inst_1 a) (p _inst_1))\nCase conversion may be inaccurate. Consider using '#align option.guard_eq_some Option.guard_eq_some\u2093'. -/\n@[simp]\ntheorem guard_eq_some {p : \u03b1 \u2192 Prop} [DecidablePred p] {a b : \u03b1} :\n    guard p a = some b \u2194 a = b \u2227 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'\u2093'. -/\n@[simp]\ntheorem guard_eq_some' {p : Prop} [Decidable p] (u) : guard p = some u \u2194 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 : \u03b1 \u2192 \u03b1 \u2192 \u03b1} (h : \u2200 a b, f a b = a \u2228 f a b = b) :\n    \u2200 o\u2081 o\u2082, liftOrGet f o\u2081 o\u2082 = o\u2081 \u2228 liftOrGet f o\u2081 o\u2082 = o\u2082\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 \u03b1} : 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 \u03b1} : 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 : \u03b1} : 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 \u03b1`, a default element `b : \u03b2` and a function `\u03b1 \u2192 \u03b2`, apply this\nfunction to `a` if it comes from `\u03b1`, and return `b` otherwise. -/\ndef casesOn' : Option \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2\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 : \u03b2) (f : \u03b1 \u2192 \u03b2) : 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 : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : 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 : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : casesOn' (a : Option \u03b1) 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} (f : (Option.{u1} \u03b1) -> \u03b2) (o : Option.{u1} \u03b1), Eq.{succ u2} \u03b2 (Option.casesOn'.{u1, u2} \u03b1 \u03b2 o (f (Option.none.{u1} \u03b1)) (Function.comp.{succ u1, succ u1, succ u2} \u03b1 (Option.{u1} \u03b1) \u03b2 f ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) \u03b1 (Option.{u1} \u03b1) (HasLiftT.mk.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (CoeTC\u2093.coe.{succ u1, succ u1} \u03b1 (Option.{u1} \u03b1) (coeOption.{u1} \u03b1)))))) (f o)\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (f : (Option.{u2} \u03b1) -> \u03b2) (o : Option.{u2} \u03b1), Eq.{succ u1} \u03b2 (Option.casesOn'.{u2, u1} \u03b1 \u03b2 o (f (Option.none.{u2} \u03b1)) (Function.comp.{succ u2, succ u2, succ u1} \u03b1 (Option.{u2} \u03b1) \u03b2 f (fun (a : \u03b1) => Option.some.{u2} \u03b1 a))) (f o)\nCase conversion may be inaccurate. Consider using '#align option.cases_on'_none_coe Option.casesOn'_none_coe\u2093'. -/\n@[simp]\ntheorem casesOn'_none_coe (f : Option \u03b1 \u2192 \u03b2) (o : Option \u03b1) : casesOn' o (f none) (f \u2218 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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} (f : \u03b1 -> \u03b2) (x : \u03b1) (o : Option.{u1} \u03b1), Eq.{succ u2} \u03b2 (Option.getD.{u2} \u03b2 (Option.map.{u1, u2} \u03b1 \u03b2 f o) (f x)) (f (Option.getD.{u1} \u03b1 o x))\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (f : \u03b1 -> \u03b2) (x : \u03b1) (o : Option.{u2} \u03b1), Eq.{succ u1} \u03b2 (Option.getD.{u1} \u03b2 (Option.map.{u2, u1} \u03b1 \u03b2 f o) (f x)) (f (Option.getD.{u2} \u03b1 o x))\nCase conversion may be inaccurate. Consider using '#align option.get_or_else_map Option.getD_map\u2093'. -/\n@[simp]\ntheorem getD_map (f : \u03b1 \u2192 \u03b2) (x : \u03b1) (o : Option \u03b1) : 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 {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1) (x : \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) \u03b1 o o') (Option.some.{u1} \u03b1 x)) (Or (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.some.{u1} \u03b1 x)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.some.{u1} \u03b1 x))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1) (x : \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} \u03b1) (Option.{u1} \u03b1) (Option.{u1} \u03b1) (instHOrElse.{u1} (Option.{u1} \u03b1) (Option.instOrElseOption.{u1} \u03b1)) o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3038 : Unit) => o')) (Option.some.{u1} \u03b1 x)) (Or (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.some.{u1} \u03b1 x)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.some.{u1} \u03b1 x))))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_some Option.orElse_eq_some\u2093'. -/\ntheorem orElse_eq_some (o o' : Option \u03b1) (x : \u03b1) :\n    (o <|> o') = some x \u2194 o = some x \u2228 o = none \u2227 o' = some x :=\n  by\n  cases o\n  \u00b7 simp only [true_and_iff, false_or_iff, eq_self_iff_true, none_orelse]\n  \u00b7 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 {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1) (x : \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.orelse.{u1} \u03b1 o o') (Option.some.{u1} \u03b1 x)) (Or (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.some.{u1} \u03b1 x)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.some.{u1} \u03b1 x))))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1) (x : \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.orElse.{u1} \u03b1 o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3099 : Unit) => o')) (Option.some.{u1} \u03b1 x)) (Or (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.some.{u1} \u03b1 x)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.some.{u1} \u03b1 x))))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_some' Option.orElse_eq_some'\u2093'. -/\ntheorem orElse_eq_some' (o o' : Option \u03b1) (x : \u03b1) :\n    o.orelse o' = some x \u2194 o = some x \u2228 o = none \u2227 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 {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) \u03b1 o o') (Option.none.{u1} \u03b1)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.none.{u1} \u03b1)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} \u03b1) (Option.{u1} \u03b1) (Option.{u1} \u03b1) (instHOrElse.{u1} (Option.{u1} \u03b1) (Option.instOrElseOption.{u1} \u03b1)) o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3151 : Unit) => o')) (Option.none.{u1} \u03b1)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.none.{u1} \u03b1)))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_none Option.orElse_eq_none\u2093'. -/\n@[simp]\ntheorem orElse_eq_none (o o' : Option \u03b1) : (o <|> o') = none \u2194 o = none \u2227 o' = none :=\n  by\n  cases o\n  \u00b7 simp only [true_and_iff, none_orelse, eq_self_iff_true]\n  \u00b7 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 {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.orelse.{u1} \u03b1 o o') (Option.none.{u1} \u03b1)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.none.{u1} \u03b1)))\nbut is expected to have type\n  forall {\u03b1 : Type.{u1}} (o : Option.{u1} \u03b1) (o' : Option.{u1} \u03b1), Iff (Eq.{succ u1} (Option.{u1} \u03b1) (Option.orElse.{u1} \u03b1 o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3201 : Unit) => o')) (Option.none.{u1} \u03b1)) (And (Eq.{succ u1} (Option.{u1} \u03b1) o (Option.none.{u1} \u03b1)) (Eq.{succ u1} (Option.{u1} \u03b1) o' (Option.none.{u1} \u03b1)))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_none' Option.orElse_eq_none'\u2093'. -/\n@[simp]\ntheorem orElse_eq_none' (o o' : Option \u03b1) : o.orelse o' = none \u2194 o = none \u2227 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 : \u03b1` if `\u03b1` is nonempty, and otherwise `none`. -/\nnoncomputable def choice (\u03b1 : Type _) : Option \u03b1 :=\n  if h : Nonempty \u03b1 then some h.some else none\n#align option.choice Option.choice\n-/\n\n#print Option.choice_eq /-\ntheorem choice_eq {\u03b1 : Type _} [Subsingleton \u03b1] (a : \u03b1) : choice \u03b1 = some a :=\n  by\n  dsimp [choice]\n  rw [dif_pos (\u27e8a\u27e9 : Nonempty \u03b1)]\n  congr\n#align option.choice_eq Option.choice_eq\n-/\n\n#print Option.choice_eq_none /-\ntheorem choice_eq_none (\u03b1 : Type _) [IsEmpty \u03b1] : choice \u03b1 = 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 {\u03b1 : Type _} : (choice \u03b1).isSome \u2194 Nonempty \u03b1 :=\n  by\n  fconstructor\n  \u00b7 intro h\n    exact \u27e8Option.get h\u27e9\n  \u00b7 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 : \u03b1) : (a : Option \u03b1).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 (\u03b1 : Type _) : (none : Option \u03b1).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 {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} (f : (Option.{u1} \u03b1) -> \u03b2), Eq.{max (succ u1) (succ u2)} ((Option.{u1} \u03b1) -> \u03b2) (Option.elim'.{u1, u2} \u03b1 \u03b2 (f (Option.none.{u1} \u03b1)) (Function.comp.{succ u1, succ u1, succ u2} \u03b1 (Option.{u1} \u03b1) \u03b2 f (Option.some.{u1} \u03b1))) f\nbut is expected to have type\n  forall {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} (f : (Option.{u2} \u03b1) -> \u03b2), Eq.{max (succ u2) (succ u1)} ((Option.{u2} \u03b1) -> \u03b2) (fun (x : Option.{u2} \u03b1) => Option.elim.{u2, succ u1} \u03b1 \u03b2 x (f (Option.none.{u2} \u03b1)) (Function.comp.{succ u2, succ u2, succ u1} \u03b1 (Option.{u2} \u03b1) \u03b2 f (Option.some.{u2} \u03b1))) f\nCase conversion may be inaccurate. Consider using '#align option.elim_none_some Option.elim_none_some\u2093'. -/\n@[simp]\ntheorem elim_none_some (f : Option \u03b1 \u2192 \u03b2) : Option.elim' (f none) (f \u2218 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 := \u00abvariables\u00bb) \"variables\" (bracketedBinder)* : command\n\n@[commandElab \u00abvariables\u00bb] def elabVariables : CommandElab\n  | `(variables%$pos $binders*) => do\n    logWarningAt pos \"'variables' has been replaced by 'variable' in lean 4\"\n    elabVariable (\u2190 `(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 : \u2200 a b : Nat, a = b \u2192 b = a := by\n  introv h,\n  exact h.symm\n```\nThe state after `introv h` is\n```\na b : \u2115,\nh : a = b\n\u22a2 b = a\n```\n\n```\nexample : \u2200 a b : Nat, a = b \u2192 \u2200 c, b = c \u2192 a = c := by\n  introv h\u2081 h\u2082,\n  exact h\u2081.trans h\u2082\n```\nThe state after `introv h\u2081 h\u2082` is\n```\na b : \u2115,\nh\u2081 : a = b,\nc : \u2115,\nh\u2082 : b = c\n\u22a2 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 (\u2190 `(tactic| introv; intro $h:ident; introv $hs:binderIdent*))\n  | `(tactic| introv _%$tk $hs:binderIdent*) =>\n    evalTactic (\u2190 `(tactic| introv; intro _%$tk; introv $hs:binderIdent*))\n  | _ => throwUnsupportedSyntax\nwhere\n  introsDep : TacticM Unit := do\n    let t \u2190 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) \u2190 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 (\u2190 `(tactic| exact $stx))\n  evalTactic (\u2190 `(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 \u2190 elabTerm r none\n  let p \u2190 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 \u2190 elabTerm r none\n  let t \u2190 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  ((\" : \" <|> \" :\u2090 \") term)? ((\" := \" <|> \" :=\u2090 \") 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 :\u2090 t` checks the type up to alpha equality.\n`guardHyp h := v` checks value up to syntactic equality,\nwhile `guardHyp h :=\u2090 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 \u2190 getFVarId h\n      let lDecl \u2190\n        match (\u2190 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 \u2190 elabTerm p none\n        let hty \u2190 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 \u2190 elabTerm val none\n          let hval \u2190 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) \u2190 elabTerm t (\u2190 inferType (\u2190 getMainTarget))\n    if not (\u2190 isDefEq val (\u2190 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\u2081; tac\u2082; \u22ef)` or\n```lean\niterate\n  tac\u2081\n  tac\u2082\n  \u22ef\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 \u2192 TacticM Unit\n| []    => pure ()\n| g::gs => do\n    try\n      let subgs \u2190 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 \u2190 getGoals\n  repeat'Aux seq gs\n\nelab \"any_goals \" seq:tacticSeq : tactic => do\n  let mvarIds \u2190 getGoals\n  let mut mvarIdsNew := #[]\n  let mut anySuccess := false\n  for mvarId in mvarIds do\n    unless (\u2190 isExprMVarAssigned mvarId) do\n      setGoals [mvarId]\n      try\n        evalTactic seq\n        mvarIdsNew := mvarIdsNew ++ (\u2190 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 \u2115 :=\nreturn 14\n\nmeta def trace_a_nat : tactic unit :=\ndo n \u2190 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 : \u2124) : 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 \u2190 target,\n   trace t,\n   a_expr \u2190 get_local `a <|> fail \"No hay ninguna a\",\n   trace (expr.to_raw_fmt a_expr),\n   a_type \u2190 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' \u2190 ctx.mmap (\u03bb e, infer_type e),\n   trace ctx'\n\nexample (a b c : \u2124) (p q : \u2115) : 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--    \u2124\n--    [a, b, c, p, q]\n--    40\n--    [\u2124, \u2124, \u2124, \u2115, \u2115]\n\nmeta def inspect2 : tactic unit :=\ndo t \u2190 target,\n   trace t,\n   a_expr \u2190 get_local `a <|> fail \"No hay ninguna a\",\n   trace (expr.to_raw_fmt a_expr),\n   a_type \u2190 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' \u2190 ctx.mmap (\u03bb e, infer_type e),\n   trace ctx',\n   ctx.mmap' (\u03bb e, do tp \u2190 infer_type e, trace tp)\n\nexample (a b c : \u2124) (p q : \u2115) : 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--    \u2124\n--    [a, b, c, p, q]\n--    40\n--    [\u2124, \u2124, \u2124, \u2115, \u2115]\n--    \u2124\n--    \u2124\n--    \u2124\n--    \u2115\n--    \u2115\n\n------------------------------------------------------------------------\n-- \u00a7 Referencia                                                       --\n------------------------------------------------------------------------\n\n-- Basado en el v\u00eddeo \"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": "import testbed.graph_theory \n\nimport tactic\nopen simple_graph tactic\n\n--------------------  TACTIC: GET ALL THEOREMS (or names, statements, proofs) -------------------- \n\nmeta def get_thm_decls_env: tactic (list declaration) := do {\n  env \u2190  get_env,\n  -- get their declarations to filter them based on if they are theorems\n  let all_decls := env.get_trusted_decls,\n  let thm_decls := all_decls.filter (\u03bb (d : declaration), d.is_theorem = tt), -- get the ones that are theorems (not axioms or defs)\n  return thm_decls\n}\n\n--------------------  TACTIC: GET ALL THEOREMS (or names, statements, proofs) TAGGED BY PROBLEM DOMAIN E.G. GRAPH THEORY -------------------- \n\nmeta def get_thm_decls (subject_area : name): tactic (list declaration) := do {\n  -- get all statements from the subject area\n  all_names  \u2190 attribute.get_instances subject_area,\n  -- get their declarations to filter them based on if they are theorems\n  all_decls  \u2190 all_names.mmap (\u03bb n, tactic.get_decl n), -- get all graph theory theorems\n  let thm_decls := all_decls.filter (\u03bb (d : declaration), d.is_theorem = tt), -- get the ones that are theorems (not axioms or defs)\n  return thm_decls\n}\n\n#eval get_thm_decls `graph_theory >>= \u03bb thm_decls, do{ let thm_names := thm_decls.map (\u03bbd, d.to_name), return thm_names} >>= trace\n\n--------------------  TACTIC: GET A PARTICULAR THEOREM BY NAME -------------------- \n\nmeta def get_thm_decl (n : name): tactic declaration := do {\n  thm_decls \u2190 get_thm_decls_env, \n\n  thm \u2190  thm_decls.mfirst (\u03bb d, if d.to_name=n then return d else tactic.failed),\n  return thm\n}\n\n#eval get_thm_decl `nat.add_one >>= trace\n#eval get_thm_decl `degree_sum >>= trace\n\nmeta def get_thm_statement (n : name): tactic expr := do {\n  thm_decl \u2190 get_thm_decl n, \n  \n  return thm_decl.type\n}\n\n#eval get_thm_statement `degree_sum >>= trace\n\nmeta def get_thm_proof (n : name): tactic expr := do {\n  thm_decl \u2190 get_thm_decl n, \n  \n  return thm_decl.value\n}\n\n#eval get_thm_proof `degree_sum >>= trace\n\n-- meta def get_thm_proofs (subject_area : name): tactic (list expr) := do {\n--   thm_decls \u2190 get_thm_decls subject_area, \n  \n--   let thm_proofs := thm_decls.map (\u03bbd, d.value),\n--   return thm_proofs\n-- }\n", "meta": {"author": "Human-Oriented-ATP", "repo": "lean-tactics", "sha": "8fa4c8b8efc0c6a1d408b48e999f3a36f228bd0f", "save_path": "github-repos/lean/Human-Oriented-ATP-lean-tactics", "path": "github-repos/lean/Human-Oriented-ATP-lean-tactics/lean-tactics-8fa4c8b8efc0c6a1d408b48e999f3a36f228bd0f/lean3/src/get_theorems.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.08389038927356948, "lm_q1q2_score": 0.04194519463678474}}
{"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 : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 Inhabited (\u03b1 i)] :\n    Inhabited (d_array n \u03b1) :=\n  { default := mk fun (_x : fin n) => Inhabited.default }\n\nend d_array\n\n\nnamespace array\n\n\nprotected instance inhabited {n : \u2115} {\u03b1 : Type u_1} [Inhabited \u03b1] : Inhabited (array n \u03b1) :=\n  d_array.inhabited\n\ntheorem to_list_of_heq {n\u2081 : \u2115} {n\u2082 : \u2115} {\u03b1 : Type u_1} {a\u2081 : array n\u2081 \u03b1} {a\u2082 : array n\u2082 \u03b1}\n    (hn : n\u2081 = n\u2082) (ha : a\u2081 == a\u2082) : to_list a\u2081 = to_list a\u2082 :=\n  sorry\n\n/- rev_list -/\n\ntheorem rev_list_reverse_aux {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} (i : \u2115) (h : i \u2264 n) (t : List \u03b1) :\n    list.reverse_core\n          (d_array.iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) i h []) t =\n        d_array.rev_iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) i h t :=\n  sorry\n\n@[simp] theorem rev_list_reverse {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} :\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 : \u2115} {\u03b1 : Type u} {a : array n \u03b1} :\n    list.reverse (to_list a) = rev_list a :=\n  sorry\n\n/- mem -/\n\ntheorem mem.def {n : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} :\n    v \u2208 a \u2194 \u2203 (i : fin n), read a i = v :=\n  iff.rfl\n\ntheorem mem_rev_list_aux {n : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} {i : \u2115} (h : i \u2264 n) :\n    (\u2203 (j : fin n), \u2191j < i \u2227 read a j = v) \u2194\n        v \u2208 d_array.iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) i h [] :=\n  sorry\n\n@[simp] theorem mem_rev_list {n : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} :\n    v \u2208 rev_list a \u2194 v \u2208 a :=\n  sorry\n\n@[simp] theorem mem_to_list {n : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} : v \u2208 to_list a \u2194 v \u2208 a :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (v \u2208 to_list a \u2194 v \u2208 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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type w} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {a : array n \u03b1}\n    {i : \u2115} (h : i \u2264 n) :\n    list.foldr f b\n          (d_array.iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type w} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {a : array n \u03b1} :\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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type w} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {a : array n \u03b1} :\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 : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : \u2115) (h : i \u2264 n) :\n    list.length\n          (d_array.iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) i h []) =\n        i :=\n  sorry\n\n@[simp] theorem rev_list_length {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) :\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 : \u2115} {\u03b1 : Type u} (a : array n \u03b1) : 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 : \u2115} {\u03b1 : Type u} {a : array n \u03b1} (i : \u2115) (ih : i < n) (j : \u2115)\n    {jh : j \u2264 n} {t : List \u03b1}\n    {h' :\n      i <\n        list.length\n          (d_array.rev_iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) j jh\n            t)} :\n    (\u2200 (k : \u2115) (tl : k < list.length t),\n          j + k = i \u2192 list.nth_le t k tl = read a { val := i, property := ih }) \u2192\n        list.nth_le\n            (d_array.rev_iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) j jh t)\n            i h' =\n          read a { val := i, property := ih } :=\n  sorry\n\ntheorem to_list_nth_le {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} (i : \u2115) (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 : \u2115) (tl : k < list.length []) => absurd tl (nat.not_lt_zero k)\n\n@[simp] theorem to_list_nth_le' {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n)\n    (h' : \u2191i < list.length (to_list a)) : list.nth_le (to_list a) (\u2191i) h' = read a i :=\n  sorry\n\ntheorem to_list_nth {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {i : \u2115} {v : \u03b1} :\n    list.nth (to_list a) i = some v \u2194 \u2203 (h : i < n), read a { val := i, property := h } = v :=\n  sorry\n\ntheorem write_to_list {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {i : fin n} {v : \u03b1} :\n    to_list (write a i v) = list.update_nth (to_list a) (\u2191i) v :=\n  sorry\n\n/- enum -/\n\ntheorem mem_to_list_enum {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {i : \u2115} {v : \u03b1} :\n    (i, v) \u2208 list.enum (to_list a) \u2194 \u2203 (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 : \u2115} {\u03b1 : Type u} (a : array n \u03b1) :\n    list.to_array (to_list a) == a :=\n  sorry\n\n@[simp] theorem to_array_to_list {\u03b1 : Type u} (l : List \u03b1) : to_list (list.to_array l) = l :=\n  list.ext_le (to_list_length (list.to_array l))\n    fun (n : \u2115) (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 : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} (i : \u2115) (h : i \u2264 n + 1)\n    (h' : i \u2264 n) :\n    d_array.iterate_aux (push_back a v) (fun (_x : fin (n + 1)) (_x : \u03b1) (_y : List \u03b1) => _x :: _y)\n          i h [] =\n        d_array.iterate_aux a (fun (_x : fin n) (_x : \u03b1) (_y : List \u03b1) => _x :: _y) i h' [] :=\n  sorry\n\n@[simp] theorem push_back_rev_list {n : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} :\n    rev_list (push_back a v) = v :: rev_list a :=\n  sorry\n\n@[simp] theorem push_back_to_list {n : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : array n \u03b1} :\n    to_list (push_back a v) = to_list a ++ [v] :=\n  sorry\n\n/- foreach -/\n\n@[simp] theorem read_foreach {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {i : fin n} {f : fin n \u2192 \u03b1 \u2192 \u03b2}\n    {a : array n \u03b1} : read (foreach a f) i = f i (read a i) :=\n  rfl\n\n/- map -/\n\ntheorem read_map {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {i : fin n} {f : \u03b1 \u2192 \u03b2} {a : array n \u03b1} :\n    read (map a f) i = f (read a i) :=\n  read_foreach\n\n/- map\u2082 -/\n\n@[simp] theorem read_map\u2082 {n : \u2115} {\u03b1 : Type u} {i : fin n} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {a\u2081 : array n \u03b1}\n    {a\u2082 : array n \u03b1} : read (map\u2082 f a\u2081 a\u2082) i = f (read a\u2081 i) (read a\u2082 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 : \u2115} (\u03b1 : fin n \u2192 Type u_1) : d_array n \u03b1 \u2243 ((i : fin n) \u2192 \u03b1 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 : \u2115) (\u03b1 : Type u_1) : array n \u03b1 \u2243 (fin n \u2192 \u03b1) :=\n  d_array_equiv_fin fun (_x : fin n) => \u03b1\n\n/-- The natural equivalence between length-`n` vectors and functions from `fin n`. -/\ndef vector_equiv_fin (\u03b1 : Type u_1) (n : \u2115) : vector \u03b1 n \u2243 (fin n \u2192 \u03b1) :=\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 (\u03b1 : Type u_1) (n : \u2115) : vector \u03b1 n \u2243 array n \u03b1 :=\n  equiv.trans (vector_equiv_fin \u03b1 n) (equiv.symm (array_equiv_fin n \u03b1))\n\nend equiv\n\n\nnamespace array\n\n\nprotected instance traversable {n : \u2115} : traversable (array n) :=\n  equiv.traversable fun (\u03b1 : Type u_1) => equiv.vector_equiv_array \u03b1 n\n\nprotected instance is_lawful_traversable {n : \u2115} : is_lawful_traversable (array n) :=\n  equiv.is_lawful_traversable fun (\u03b1 : Type u_1) => equiv.vector_equiv_array \u03b1 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 \u2227 q \u2227 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\u00f6lzl, 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 \u2192 Type v} {\u03b1 : 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 \u2192 Type v) : Type (max (u+1) v) :=\n(\u03b1 : Type u)\n(str : c \u03b1 . 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 \u2192 Type v} (\u03b1 : Type u) [str : c \u03b1] : bundled c := \u27e8\u03b1, str\u27e9\n\ninstance : has_coe_to_sort (bundled c) (Type u) := \u27e8bundled.\u03b1\u27e9\n\n@[simp] lemma coe_mk (\u03b1) (str) : (@bundled.mk c \u03b1 str : Type u) = \u03b1 := 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 \u27f6 S in Ring is really\na (semi)ring homomorphism from R.\u03b1 to S.\u03b1, and not merely from\n`(bundled.map @ring.to_semiring R).\u03b1` to `(bundled.map @ring.to_semiring S).\u03b1`.\n-/\n/-- Map over the bundled structure -/\n@[reducible] def map (f : \u03a0 {\u03b1}, c \u03b1 \u2192 d \u03b1) (b : bundled c) : bundled d :=\n\u27e8b, f b.str\u27e9\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 : \u03a0 X Y : C, has_zero (X \u27f6 Y)]\n(comp_zero' : \u2200 {X Y : C} (f : X \u27f6 Y) (Z : C), f \u226b (0 : Y \u27f6 Z) = (0 : X \u27f6 Z) . obviously)\n(zero_comp' : \u2200 (X : C) {Y Z : C} (f : Y \u27f6 Z), (0 : X \u27f6 Y) \u226b f = (0 : X \u27f6 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 \u27f6 Y} {Z : C} :\n  f \u226b (0 : Y \u27f6 Z) = (0 : X \u27f6 Z) := has_zero_morphisms.comp_zero f Z\n@[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y \u27f6 Z} :\n  (0 : X \u27f6 Y) \u226b f = (0 : X \u27f6 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 : \u2200 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 \u2190@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\u27e8ext\u27e9\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\u1d52\u1d56 :=\n{ has_zero := \u03bb X Y, \u27e8(0 : unop Y \u27f6 unop X).op\u27e9,\n  comp_zero' := \u03bb X Y f Z, congr_arg quiver.hom.op (has_zero_morphisms.zero_comp (unop Z) f.unop),\n  zero_comp' := \u03bb 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 \u27f6 Y} (g : Y \u27f6 Z) [mono g] (h : f \u226b g = 0) : f = 0 :=\nby { rw [\u2190zero_comp, cancel_mono] at h, exact h }\n\nlemma zero_of_epi_comp {X Y Z : C} (f : X \u27f6 Y) {g : Y \u27f6 Z} [epi f] (h : f \u226b g = 0) : g = 0 :=\nby { rw [\u2190comp_zero, cancel_epi] at h, exact h }\n\nlemma eq_zero_of_image_eq_zero {X Y : C} {f : X \u27f6 Y} [has_image f] (w : image.\u03b9 f = 0) : f = 0 :=\nby rw [\u2190image.fac f, w, has_zero_morphisms.comp_zero]\n\nlemma nonzero_image_of_nonzero {X Y : C} {f : X \u27f6 Y} [has_image f] (w : f \u2260 0) : image.\u03b9 f \u2260 0 :=\n\u03bb h, w (eq_zero_of_image_eq_zero h)\nend\n\nsection\n\nvariables [has_zero_morphisms D]\n\ninstance : has_zero_morphisms (C \u2964 D) :=\n{ has_zero := \u03bb F G, \u27e8{ app := \u03bb X, 0, }\u27e9 }\n\n@[simp] lemma zero_app (F G : C \u2964 D) (j : C) : (0 : F \u27f6 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 \u27f6 Y) : f = 0 :=\no.eq_of_src _ _\n\nlemma eq_zero_of_tgt {X Y : C} (o : is_zero Y) (f : X \u27f6 Y) : f = 0 :=\no.eq_of_tgt _ _\n\nlemma iff_id_eq_zero (X : C) : is_zero X \u2194 (\ud835\udfd9 X = 0) :=\n\u27e8\u03bb h, h.eq_of_src _ _,\n \u03bb h, \u27e8\n  \u03bb Y, \u27e8\u27e8\u27e80\u27e9, \u03bb f, by { rw [\u2190id_comp f, \u2190id_comp default, h, zero_comp, zero_comp], }\u27e9\u27e9,\n  \u03bb Y, \u27e8\u27e8\u27e80\u27e9, \u03bb f, by { rw [\u2190comp_id f, \u2190comp_id default, h, comp_zero, comp_zero], }\u27e9\u27e9\u27e9\u27e9\n\nlemma of_mono_zero (X Y : C) [mono (0 : X \u27f6 Y)] : is_zero X :=\n(iff_id_eq_zero X).mpr ((cancel_mono (0 : X \u27f6 Y)).1 (by simp))\n\nlemma of_epi_zero (X Y : C) [epi (0 : X \u27f6 Y)] : is_zero Y :=\n(iff_id_eq_zero Y).mpr ((cancel_epi (0 : X \u27f6 Y)).1 (by simp))\n\nlemma of_mono_eq_zero {X Y : C} (f : X \u27f6 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 \u27f6 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 \u27f6 Y) [split_mono f] : is_zero X \u2194 f = 0 :=\nbegin\n  rw iff_id_eq_zero,\n  split,\n  { intro h, rw [\u2190category.id_comp f, h, zero_comp], },\n  { intro h, rw [\u2190split_mono.id f], simp [h], },\nend\n\nlemma iff_split_epi_eq_zero {X Y : C} (f : X \u27f6 Y) [split_epi f] : is_zero Y \u2194 f = 0 :=\nbegin\n  rw iff_id_eq_zero,\n  split,\n  { intro h, rw [\u2190category.comp_id f, h, comp_zero], },\n  { intro h, rw [\u2190split_epi.id f], simp [h], },\nend\n\nlemma of_mono {X Y : C} (f : X \u27f6 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 \u27f6 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 := \u03bb X Y,\n  { zero := hO.from X \u226b hO.to Y },\n  zero_comp' := \u03bb X Y Z f, by { rw category.assoc, congr, apply hO.eq_of_src, },\n  comp_zero' := \u03bb X Y Z f, by { rw \u2190category.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 := \u03bb X Y,\n  { zero := (default : X \u27f6 0) \u226b default },\n  zero_comp' := \u03bb X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, },\n  comp_zero' := \u03bb X Y Z f, by { dunfold has_zero.zero, rw \u2190category.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 \u27f6 \u22a5_ C) :=\nby ext\n\n@[simp] lemma zero_iso_initial_inv [has_initial C] : zero_iso_initial.inv = (0 : \u22a5_ C \u27f6 0) :=\nby ext\n\n@[simp] \n\n@[simp] lemma zero_iso_terminal_inv [has_terminal C] : zero_iso_terminal.inv = (0 : \u22a4_ C \u27f6 0) :=\nby ext\n\nend has_zero_morphisms\n\nopen_locale zero_object\n\ninstance {B : Type*} [category B] : has_zero_object (B \u2964 C) :=\n(((category_theory.functor.const B).obj (0 : C)).is_zero $ \u03bb 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 \u2964 D} (hF : is_zero F)\n  {X Y : C} (f : X \u27f6 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 \u2964 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 \u27f6 Y) : (0 : C \u2964 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 : \ud835\udfd9 (0 : C) = (0 : 0 \u27f6 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 \u27f6 0) : f = 0 :=\nby ext\n\nlemma zero_of_target_iso_zero {X Y : C} (f : X \u27f6 Y) (i : Y \u2245 0) : f = 0 :=\nbegin\n  have h : f = f \u226b i.hom \u226b \ud835\udfd9 0 \u226b 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 \u27f6 X) : f = 0 :=\nby ext\n\nlemma zero_of_source_iso_zero {X Y : C} (f : X \u27f6 Y) (i : X \u2245 0) : f = 0 :=\nbegin\n  have h : f = i.hom \u226b \ud835\udfd9 0 \u226b i.inv \u226b 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 \u27f6 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 \u27f6 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 \u27f6 Y) (i : X \u2245 0) : mono f :=\n\u27e8\u03bb Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]\u27e9\n\nlemma epi_of_target_iso_zero {X Y : C} (f : X \u27f6 Y) (i : Y \u2245 0) : epi f :=\n\u27e8\u03bb Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]\u27e9\n\n/--\nAn object `X` has `\ud835\udfd9 X = 0` if and only if it is isomorphic to the zero object.\n\nBecause `X \u2245 0` contains data (even if a subsingleton), we express this `\u2194` as an `\u2243`.\n-/\ndef id_zero_equiv_iso_zero (X : C) : (\ud835\udfd9 X = 0) \u2243 (X \u2245 0) :=\n{ to_fun    := \u03bb h, { hom := 0, inv := 0, },\n  inv_fun   := \u03bb i, zero_of_target_iso_zero (\ud835\udfd9 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 : \ud835\udfd9 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 : \ud835\udfd9 X = 0) :\n  ((id_zero_equiv_iso_zero X) h).inv = 0 := rfl\n\n/-- If `0 : X \u27f6 Y` is an monomorphism, then `X \u2245 0`. -/\n@[simps]\ndef iso_zero_of_mono_zero {X Y : C} (h : mono (0 : X \u27f6 Y)) : X \u2245 0 :=\n{ hom := 0,\n  inv := 0,\n  hom_inv_id' := (cancel_mono (0 : X \u27f6 Y)).mp (by simp) }\n\n/-- If `0 : X \u27f6 Y` is an epimorphism, then `Y \u2245 0`. -/\n@[simps]\ndef iso_zero_of_epi_zero {X Y : C} (h : epi (0 : X \u27f6 Y)) : Y \u2245 0 :=\n{ hom := 0,\n  inv := 0,\n  hom_inv_id' := (cancel_epi (0 : X \u27f6 Y)).mp (by simp) }\n\n/-- If a monomorphism out of `X` is zero, then `X \u2245 0`. -/\ndef iso_zero_of_mono_eq_zero {X Y : C} {f : X \u27f6 Y} [mono f] (h : f = 0) : X \u2245 0 :=\nby { unfreezingI { subst h, }, apply iso_zero_of_mono_zero \u2039_\u203a, }\n\n/-- If an epimorphism in to `Y` is zero, then `Y \u2245 0`. -/\ndef iso_zero_of_epi_eq_zero {X Y : C} {f : X \u27f6 Y} [epi f] (h : f = 0) : Y \u2245 0 :=\nby { unfreezingI { subst h, }, apply iso_zero_of_epi_zero \u2039_\u203a, }\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 \u2245 0 :=\n{ hom := 0,\n  inv := 0,\n  hom_inv_id' :=\n  begin\n    casesI P,\n    rw \u2190P.hom_inv_id,\n    rw \u2190category.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 \u27f6 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 \u27f6 Y) \u2243 (\ud835\udfd9 X = 0 \u2227 \ud835\udfd9 Y = 0) :=\n{ to_fun := by { introsI i, rw \u2190is_iso.hom_inv_id (0 : X \u27f6 Y),\n    rw \u2190is_iso.inv_hom_id (0 : X \u27f6 Y), simp },\n  inv_fun := \u03bb h, \u27e8\u27e8(0 : Y \u27f6 X), by tidy\u27e9\u27e9,\n  left_inv := by tidy,\n  right_inv := by tidy, }\n\n/--\nA zero morphism `0 : X \u27f6 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 \u27f6 X) \u2243 (\ud835\udfd9 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 \u27f6 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 \u27f6 Y) \u2243 (X \u2245 0) \u00d7 (Y \u2245 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 \u27e8eX, eY\u27e9, fsplit,\n    exact (id_zero_equiv_iso_zero X).symm eX,\n    exact (id_zero_equiv_iso_zero Y).symm eY, },\n  { rintros \u27e8hX, hY\u27e9, 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 \u27f6 Y) (i : X \u2245 0) (j : Y \u2245 0) : is_iso f :=\nbegin\n  rw zero_of_source_iso_zero f i,\n  exact (is_iso_zero_equiv_iso_zero _ _).inv_fun \u27e8i, j\u27e9,\nend\n\n/--\nA zero morphism `0 : X \u27f6 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 \u27f6 X) \u2243 (X \u2245 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 \u27e8\u27e8\u22a5_ C, \u03bb X, \u27e8\u27e8\u27e80\u27e9, by tidy\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e80\u27e9, \u03bb f, _\u27e9\u27e9\u27e9\u27e9,\n  calc\n    f = f \u226b \ud835\udfd9 _ : (category.comp_id _).symm\n    ... = f \u226b 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 \u27e8\u27e8\u22a4_ C, \u03bb X, \u27e8\u27e8\u27e80\u27e9, \u03bb f, _\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e80\u27e9, by tidy\u27e9\u27e9\u27e9\u27e9,\n  calc\n    f = \ud835\udfd9 _ \u226b f : (category.id_comp _).symm\n    ... = 0 \u226b f : by congr\n    ... = 0     : zero_comp\nend\n\n\nsection image\nvariable [has_zero_morphisms C]\n\nlemma image_\u03b9_comp_eq_zero {X Y Z : C} {f : X \u27f6 Y} {g : Y \u27f6 Z} [has_image f]\n  [epi (factor_thru_image f)] (h : f \u226b g = 0) : image.\u03b9 f \u226b 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 \u27f6 Y} {g : Y \u27f6 Z} [has_image g]\n  (h : f \u226b g = 0) : f \u226b factor_thru_image g = 0 :=\nzero_of_comp_mono (image.\u03b9 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 \u27f6 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 \u27f6 Y) :=\n{ F := mono_factorisation_zero X Y,\n  is_image := { lift := \u03bb F', 0 } }\n\n\ninstance has_image_zero {X Y : C} : has_image (0 : X \u27f6 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 \u27f6 Y) \u2245 0 :=\nis_image.iso_ext (image.is_image (0 : X \u27f6 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 \u27f6 Y} (h : f = 0) [has_image f] : image f \u2245 0 :=\nimage.eq_to_iso h \u226a\u226b image_zero\n\n@[simp]\nlemma image.\u03b9_zero {X Y : C} [has_image (0 : X \u27f6 Y)] : image.\u03b9 (0 : X \u27f6 Y) = 0 :=\nbegin\n  rw \u2190image.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.\u03b9 f = 0`,\nbecause `f = g` only implies `image f \u2245 image g`.\n-/\n@[simp]\nlemma image.\u03b9_zero' [has_equalizers C] {X Y : C} {f : X \u27f6 Y} (h : f = 0) [has_image f] :\n  image.\u03b9 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_\u03b9\n  {\u03b2 : Type v} [has_zero_morphisms C]\n  (f : \u03b2 \u2192 C) [has_colimit (discrete.functor f)] (b : \u03b2) : split_mono (sigma.\u03b9 f b) :=\n{ retraction := sigma.desc (\u03bb 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_\u03c0\n  {\u03b2 : Type v} [has_zero_morphisms C]\n  (f : \u03b2 \u2192 C) [has_limit (discrete.functor f)] (b : \u03b2) : split_epi (pi.\u03c0 f b) :=\n{ section_ := pi.lift (\u03bb 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 \u27f6 X \u2a3f Y) :=\n{ retraction := coprod.desc (\ud835\udfd9 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 \u27f6 X \u2a3f Y) :=\n{ retraction := coprod.desc 0 (\ud835\udfd9 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 \u2a2f Y \u27f6 X) :=\n{ section_ := prod.lift (\ud835\udfd9 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 \u2a2f Y \u27f6 Y) :=\n{ section_ := prod.lift 0 (\ud835\udfd9 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 * `\u03c9CPO`\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 \u03c9CPO : Type (u+1) := bundled omega_complete_partial_order\n\nnamespace \u03c9CPO\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]] \u03c9CPO\n\ninstance : has_coe_to_sort \u03c9CPO Type* := bundled.has_coe_to_sort\n\n/-- Construct a bundled \u03c9CPO from the underlying type and typeclass. -/\ndef of (\u03b1 : Type*) [omega_complete_partial_order \u03b1] : \u03c9CPO := bundled.of \u03b1\n\n@[simp] lemma coe_of (\u03b1 : Type*) [omega_complete_partial_order \u03b1] : \u21a5(of \u03b1) = \u03b1 := rfl\n\ninstance : inhabited \u03c9CPO := \u27e8of punit\u27e9\n\ninstance (\u03b1 : \u03c9CPO) : omega_complete_partial_order \u03b1 := \u03b1.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 \u2192 \u03c9CPO.{v}) : fan f :=\nfan.mk (of (\u03a0 j, f j)) (\u03bb j, continuous_hom.of_mono (pi.eval_order_hom j) (\u03bb c, rfl))\n\n/-- The pi-type is a limit cone for the product. -/\ndef is_product (J : Type v) (f : J \u2192 \u03c9CPO) : is_limit (product f) :=\n{ lift := \u03bb s,\n    \u27e8\u27e8\u03bb t j, s.\u03c0.app \u27e8j\u27e9 t, \u03bb x y h j, (s.\u03c0.app \u27e8j\u27e9).monotone h\u27e9,\n     \u03bb x, funext (\u03bb j, (s.\u03c0.app \u27e8j\u27e9).continuous x)\u27e9,\n  uniq' := \u03bb s m w,\n  begin\n    ext t j,\n    change m t j = s.\u03c0.app \u27e8j\u27e9 t,\n    rw \u2190 w \u27e8j\u27e9,\n    refl,\n  end,\n  fac' := \u03bb s j, by { cases j, tidy, } }.\n\ninstance (J : Type v) (f : J \u2192 \u03c9CPO.{v}) : has_product f :=\nhas_limit.mk \u27e8_, is_product _ f\u27e9\n\nend has_products\n\ninstance omega_complete_partial_order_equalizer\n  {\u03b1 \u03b2 : Type*} [omega_complete_partial_order \u03b1] [omega_complete_partial_order \u03b2]\n  (f g : \u03b1 \u2192\ud835\udc84 \u03b2) : omega_complete_partial_order {a : \u03b1 // f a = g a} :=\nomega_complete_partial_order.subtype _ $ \u03bb c hc,\nbegin\n  rw [f.continuous, g.continuous],\n  congr' 1,\n  ext,\n  apply hc _ \u27e8_, rfl\u27e9,\nend\n\nnamespace has_equalizers\n\n/-- The equalizer inclusion function as a `continuous_hom`. -/\ndef equalizer_\u03b9 {\u03b1 \u03b2 : Type*} [omega_complete_partial_order \u03b1] [omega_complete_partial_order \u03b2]\n  (f g : \u03b1 \u2192\ud835\udc84 \u03b2) :\n  {a : \u03b1 // f a = g a} \u2192\ud835\udc84 \u03b1 :=\ncontinuous_hom.of_mono (order_hom.subtype.val _) (\u03bb c, rfl)\n\n/-- A construction of the equalizer fork. -/\ndef equalizer {X Y : \u03c9CPO.{v}} (f g : X \u27f6 Y) :\n  fork f g :=\n@fork.of_\u03b9 _ _ _ _ _ _ (\u03c9CPO.of {a // f a = g a}) (equalizer_\u03b9 f g)\n  (continuous_hom.ext _ _ (\u03bb x, x.2))\n\n/-- The equalizer fork is a limit. -/\ndef is_equalizer {X Y : \u03c9CPO.{v}} (f g : X \u27f6 Y) : is_limit (equalizer f g) :=\nfork.is_limit.mk' _ $ \u03bb s,\n\u27e8{ to_fun := \u03bb x, \u27e8s.\u03b9 x, by apply continuous_hom.congr_fun s.condition\u27e9,\n    monotone' := \u03bb x y h, s.\u03b9.monotone h,\n    cont := \u03bb x, subtype.ext (s.\u03b9.continuous x) },\n  by { ext, refl },\n  \u03bb m hm,\n  begin\n    ext,\n    apply continuous_hom.congr_fun hm,\n  end\u27e9\n\nend has_equalizers\n\ninstance : has_products.{v} \u03c9CPO.{v} :=\n\u03bb J, { has_limit := \u03bb F, has_limit_of_iso discrete.nat_iso_functor.symm }\n\ninstance {X Y : \u03c9CPO.{v}} (f g : X \u27f6 Y) : has_limit (parallel_pair f g) :=\nhas_limit.mk \u27e8_, has_equalizers.is_equalizer f g\u27e9\n\ninstance : has_equalizers \u03c9CPO.{v} := has_equalizers_of_has_limit_parallel_pair _\n\ninstance : has_limits \u03c9CPO.{v} := has_limits_of_has_equalizers_and_products\n\nend\n\n\nend \u03c9CPO\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) 2020 Floris van Doorn. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Floris van Doorn, Robert Y. Lewis\n-/\nimport data.bool\nimport meta.rb_map\nimport tactic.lint.basic\n\n/-!\n# Various linters\n\nThis file defines several small linters:\n  - `ge_or_gt` checks that `>` and `\u2265` do not occur in the statement of theorems.\n  - `dup_namespace` checks that no declaration has a duplicated namespace such as `list.list.monad`.\n  - `unused_arguments` checks that definitions and theorems do not have unused arguments.\n  - `doc_blame` checks that every definition has a documentation string.\n  - `doc_blame_thm` checks that every theorem has a documentation string (not enabled by default).\n  - `def_lemma` checks that a declaration is a lemma iff its type is a proposition.\n  - `check_type` checks that the statement of a declaration is well-typed.\n  - `check_univs` checks that there are no bad `max u v` universe levels.\n  - `syn_taut` checks that declarations are not syntactic tautologies.\n  - `unused_haves_suffices` checks that declarations produced via term mode do not have\n    ineffectual `have` or `suffices` statements\n-/\n\nopen tactic expr\n\n/-!\n## Linter against use of `>`/`\u2265`\n-/\n/-- The names of `\u2265` and `>`, mostly disallowed in lemma statements -/\nprivate meta def illegal_ge_gt : list name := [`gt, `ge]\n\nset_option eqn_compiler.max_steps 20000\n/--\n  Checks whether `\u2265` and `>` occurs in an illegal way in the expression.\n  The main ways we legally use these orderings are:\n  - `f (\u2265)`\n  - `\u2203 x \u2265 t, b`. This corresponds to the expression\n    `@Exists \u03b1 (fun (x : \u03b1), (@Exists (x > t) (\u03bb (H : x > t), b)))`\n  This function returns `tt` when it finds `ge`/`gt`, except in the following patterns\n  (which are the same for `gt`):\n  - `f (@ge _ _)`\n  - `f (&0 \u2265 y) (\u03bb x : t, b)`\n  - `\u03bb H : &0 \u2265 t, b`\n  Here `&0` is the 0-th de Bruijn variable.\n-/\nprivate meta def contains_illegal_ge_gt : expr \u2192 bool\n| (const nm us) := if nm \u2208 illegal_ge_gt then tt else ff\n| (app f e@(app (app (const nm us) tp) tc)) :=\n  contains_illegal_ge_gt f || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt e\n| (app (app custom_binder (app (app (app (app (const nm us) tp) tc) (var 0)) t))\n    e@(lam var_name bi var_type body)) :=\n  contains_illegal_ge_gt e || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt e\n| (app f x) := contains_illegal_ge_gt f || contains_illegal_ge_gt x\n| (lam `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) :=\n  contains_illegal_ge_gt body || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt type\n| (lam var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body\n| (pi `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) :=\n  contains_illegal_ge_gt body || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt type\n| (pi var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body\n| (elet var_name type assignment body) :=\n  contains_illegal_ge_gt type || contains_illegal_ge_gt assignment || contains_illegal_ge_gt body\n| _ := ff\n\n/-- Checks whether a `>`/`\u2265` is used in the statement of `d`.\n\nIt first does a quick check to see if there is any `\u2265` or `>` in the statement, and then does a\nslower check whether the occurrences of `\u2265` and `>` are allowed.\nCurrently it checks only the conclusion of the declaration, to eliminate false positive from\nbinders such as `\u2200 \u03b5 > 0, ...` -/\nprivate meta def ge_or_gt_in_statement (d : declaration) : tactic (option string) :=\nreturn $ if d.type.contains_constant (\u03bb n, n \u2208 illegal_ge_gt) &&\n  contains_illegal_ge_gt d.type\n  then some \"the type contains \u2265/>. Use \u2264/< instead.\"\n  else none\n\n-- TODO: the commented out code also checks for classicality in statements, but needs fixing\n-- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _\n-- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=\n-- return $ if d.type.contains_constant (\u03bb n, (n.get_prefix = `classical \u2227\n--   n.last \u2208 [\"prop_decidable\", \"dec\", \"dec_rel\", \"dec_eq\"]) \u2228 n \u2208 [`gt, `ge])\n-- then\n--   let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel,\n--     `classical.dec_eq],\n--       illegal2 := [`gt, `ge],\n--       occur1 := illegal1.filter (\u03bb n, d.type.contains_constant (eq n)),\n--       occur2 := illegal2.filter (\u03bb n, d.type.contains_constant (eq n)) in\n--   some $ sformat!\"the type contains the following declarations: {occur1 ++ occur2}.\" ++\n--     (if occur1 = [] then \"\" else \" Add decidability type-class arguments instead.\") ++\n--     (if occur2 = [] then \"\" else \" Use \u2264/< instead.\")\n-- else none\n\n/-- A linter for checking whether illegal constants (\u2265, >) appear in a declaration's type. -/\n@[linter] meta def linter.ge_or_gt : linter :=\n{ test := ge_or_gt_in_statement,\n  auto_decls := ff,\n  no_errors_found := \"Not using \u2265/> in declarations.\",\n  errors_found := \"The following declarations use \u2265/>, probably in a way where we would prefer\n  to use \u2264/< instead. See note [nolint_ge] for more information.\",\n  is_fast := ff }\n\n/--\nCurrently, the linter forbids the use of `>` and `\u2265` in definitions and\nstatements, as they cause problems in rewrites.\nThey are still allowed in statements such as `bounded (\u2265)` or `\u2200 \u03b5 > 0` or `\u2a06 n \u2265 m`,\nand the linter allows that.\nIf you write a pattern where you bind two or more variables, like `\u2203 n m > 0`, the linter will\nflag this as illegal, but it is also allowed. In this case, add the line\n```\n@[nolint ge_or_gt] -- see Note [nolint_ge]\n```\n-/\nlibrary_note \"nolint_ge\"\n\n/-!\n## Linter for duplicate namespaces\n-/\n\n/-- Checks whether a declaration has a namespace twice consecutively in its name -/\nprivate meta def dup_namespace (d : declaration) : tactic (option string) :=\nis_instance d.to_name >>= \u03bb is_inst,\nreturn $ let nm := d.to_name.components in if nm.chain' (\u2260) \u2228 is_inst then none\n  else let s := (nm.find $ \u03bb n, nm.count n \u2265 2).iget.to_string in\n  some $ \"The namespace `\" ++ s ++ \"` is duplicated in the name\"\n\n/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/\n@[linter] meta def linter.dup_namespace : linter :=\n{ test := dup_namespace,\n  auto_decls := ff,\n  no_errors_found := \"No declarations have a duplicate namespace.\",\n  errors_found := \"DUPLICATED NAMESPACES IN NAME:\" }\n\n\n\n/-!\n## Linter for unused arguments\n-/\n\n/-- Auxiliary definition for `check_unused_arguments` -/\nprivate meta def check_unused_arguments_aux : list \u2115 \u2192 \u2115 \u2192 \u2115 \u2192 expr \u2192 list \u2115 | l n n_max e :=\nif n > n_max then l else\nif \u00ac is_lambda e \u2227 \u00ac is_pi e then l else\n  let b := e.binding_body in\n  let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b\n\n/-- Check which arguments of a declaration are not used.\nPrints a list of natural numbers corresponding to which arguments are not used (e.g.\n  this outputs [1, 4] if the first and fourth arguments are unused).\nChecks both the type and the value of `d` for whether the argument is used\n(in rare cases an argument is used in the type but not in the value).\nWe return [] if the declaration was automatically generated.\nWe print arguments that are larger than the arity of the type of the declaration\n(without unfolding definitions). -/\nmeta def check_unused_arguments (d : declaration) : option (list \u2115) :=\nlet l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in\nif l = [] then none else\nlet l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in\n(l.filter $ \u03bb n, n \u2208 l2).reverse\n\n/-- Check for unused arguments, and print them with their position, variable name, type and whether\nthe argument is a duplicate.\nSee also `check_unused_arguments`.\nThis tactic additionally filters out all unused arguments of type `parse _`.\nWe skip all declarations that contain `sorry` in their value. -/\nprivate meta def unused_arguments (d : declaration) : tactic (option string) := do\n  ff \u2190 d.to_name.contains_sorry | return none,\n  let ns := check_unused_arguments d,\n  tt \u2190 return ns.is_some | return none,\n  let ns := ns.iget,\n  (ds, _) \u2190 get_pi_binders d.type,\n  let ns := ns.map (\u03bb n, (n, (ds.nth $ n - 1).iget)),\n  let ns := ns.filter (\u03bb x, x.2.type.get_app_fn \u2260 const `interactive.parse []),\n  ff \u2190 return ns.empty | return none,\n  ds' \u2190 ds.mmap pp,\n  ns \u2190 ns.mmap (\u03bb \u27e8n, b\u27e9, (\u03bb s, to_fmt \"argument \" ++ to_fmt n ++ \": \" ++ s ++\n    (if ds.countp (\u03bb b', b.type = b'.type) \u2265 2 then \" (duplicate)\" else \"\")) <$> pp b),\n  return $ some $ ns.to_string_aux tt\n\n/-- A linter object for checking for unused arguments. This is in the default linter set. -/\n@[linter] meta def linter.unused_arguments : linter :=\n{ test := unused_arguments,\n  auto_decls := ff,\n  no_errors_found := \"No unused arguments.\",\n  errors_found := \"UNUSED ARGUMENTS.\" }\n\nattribute [nolint unused_arguments] imp_intro\n\n\n\n/-!\n## Linter for documentation strings\n-/\n\n/-- Reports definitions and constants that are missing doc strings -/\nprivate meta def doc_blame_report_defn : declaration \u2192 tactic (option string)\n| (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return \"def missing doc string\"\n| (declaration.cnst n _ _ _) := doc_string n >> return none <|> return \"constant missing doc string\"\n| _ := return none\n\n/-- Reports definitions and constants that are missing doc strings -/\nprivate meta def doc_blame_report_thm : declaration \u2192 tactic (option string)\n| (declaration.thm n _ _ _) := doc_string n >> return none <|> return \"theorem missing doc string\"\n| _ := return none\n\n/-- A linter for checking definition doc strings -/\n@[linter] meta def linter.doc_blame : linter :=\n{ test := \u03bb d, mcond (bnot <$> has_attribute' `instance d.to_name)\n    (doc_blame_report_defn d) (return none),\n  auto_decls := ff,\n  no_errors_found := \"No definitions are missing documentation.\",\n  errors_found := \"DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:\" }\n\n/-- A linter for checking theorem doc strings. This is not in the default linter set. -/\nmeta def linter.doc_blame_thm : linter :=\n{ test := doc_blame_report_thm,\n  auto_decls := ff,\n  no_errors_found := \"No theorems are missing documentation.\",\n  errors_found := \"THEOREMS ARE MISSING DOCUMENTATION STRINGS:\",\n  is_fast := ff }\n\n/-!\n## Linter for correct usage of `lemma`/`def`\n-/\n\n/--\nChecks whether the correct declaration constructor (definition or theorem) by\ncomparing it to its sort. Instances will not be printed.\n\nThis test is not very quick: maybe we can speed-up testing that something is a proposition?\nThis takes almost all of the execution time.\n-/\nprivate meta def incorrect_def_lemma (d : declaration) : tactic (option string) :=\n  if d.is_constant \u2228 d.is_axiom\n  then return none else do\n    is_instance_d \u2190 is_instance d.to_name,\n    if is_instance_d then return none else do\n      -- the following seems to be a little quicker than `is_prop d.type`.\n      expr.sort n \u2190 infer_type d.type,\n      is_pattern \u2190 has_attribute' `pattern d.to_name,\n      return $\n        if d.is_theorem \u2194 n = level.zero then none\n        else if d.is_theorem then \"is a lemma/theorem, should be a def\"\n        else if is_pattern then none -- declarations with `@[pattern]` are allowed to be a `def`.\n        else \"is a def, should be a lemma/theorem\"\n\n/-- A linter for checking whether the correct declaration constructor (definition or theorem)\nhas been used. -/\n@[linter] meta def linter.def_lemma : linter :=\n{ test := incorrect_def_lemma,\n  auto_decls := ff,\n  no_errors_found := \"All declarations correctly marked as def/lemma.\",\n  errors_found := \"INCORRECT DEF/LEMMA:\" }\n\n/-!\n## Linter that checks whether declarations are well-typed\n-/\n\n/-- Checks whether the statement of a declaration is well-typed. -/\nmeta def check_type (d : declaration) : tactic (option string) :=\n(type_check d.type >> return none) <|> return \"The statement doesn't type-check\"\n\n/-- A linter for missing checking whether statements of declarations are well-typed. -/\n@[linter]\nmeta def linter.check_type : linter :=\n{ test := check_type,\n  auto_decls := ff,\n  no_errors_found :=\n    \"The statements of all declarations type-check with default reducibility settings.\",\n  errors_found := \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK.\nSome definitions in the statement are marked `@[irreducible]`, which means that the statement \" ++\n\"is now ill-formed. It is likely that these definitions were locally marked as `@[reducible]` \" ++\n\"or `@[semireducible]`. This can especially cause problems with type class inference or \" ++\n\"`@[simps]`.\",\n  is_fast := tt }\n\n/-!\n## Linter for universe parameters\n-/\n\nopen native\n/--\n  `univ_params_grouped e` computes for each `level` `u` of `e` the parameters that occur in `u`,\n  and returns the corresponding set of lists of parameters.\n  In pseudo-mathematical form, this returns `{ { p : parameter | p \u2208 u } | (u : level) \u2208 e }`\n  We use `list name` instead of `name_set`, since `name_set` does not have an order.\n  It will ignore `nm\u2080._proof_i` declarations.\n-/\nmeta def expr.univ_params_grouped (e : expr) (nm\u2080 : name) : rb_set (list name) :=\ne.fold mk_rb_set $ \u03bb e n l,\n  match e with\n  | e@(sort u) := l.insert u.params.to_list\n  | e@(const nm us) := if nm.get_prefix = nm\u2080 \u2227 nm.last.starts_with \"_proof_\" then l else\n      l.union $ rb_set.of_list $ us.map $ \u03bb u : level, u.params.to_list\n  | _ := l\n  end\n\n/--\n  The good parameters are the parameters that occur somewhere in the `rb_set` as a singleton or\n  (recursively) with only other good parameters.\n  All other parameters in the `rb_set` are bad.\n-/\nmeta def bad_params : rb_set (list name) \u2192 list name | l :=\nlet good_levels : name_set :=\n  l.fold mk_name_set $ \u03bb us prev, if us.length = 1 then prev.insert us.head else prev in\nif good_levels.empty then\nl.fold [] list.union\nelse bad_params $ rb_set.of_list $ l.to_list.map $ \u03bb us, us.filter $ \u03bb nm, !good_levels.contains nm\n\n/--\nChecks whether all universe levels `u` in the type of `d` are \"good\".\nThis means that `u` either occurs in a `level` of `d` by itself, or (recursively)\nwith only other good levels.\nWhen this fails, usually this means that there is a level `max u v`, where neither `u` nor `v`\noccur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example,\n`(\u03b1 : Type u) (\u03b2 : Type (max u v))` is a occasionally useful method of saying that `\u03b2` lives in\na higher universe level than `\u03b1`.\n-/\nmeta def check_univs (d : declaration) : tactic (option string) := do\n  let l := d.type.univ_params_grouped d.to_name,\n  let bad := bad_params l,\n  if bad.empty then return none else\n    return $ some $ \"universes \" ++ to_string bad ++ \" only occur together.\"\n\n/-- A linter for checking that there are no bad `max u v` universe levels. -/\n@[linter]\nmeta def linter.check_univs : linter :=\n{ test := check_univs,\n  auto_decls := ff,\n  no_errors_found :=\n    \"All declarations have good universe levels.\",\n  errors_found := \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. \" ++\n\"This usually means that there is a `max u v` in the type where neither `u` nor `v` \" ++\n\"occur by themselves. Solution: Find the type (or type bundled with data) that has this \" ++\n\"universe argument and provide the universe level explicitly. If this happens in an implicit \" ++\n\"argument of the declaration, a better solution is to move this argument to a `variables` \" ++\n\"command (then it's not necessary to provide the universe level).\nIt is possible that this linter gives a false positive on definitions where the value of the \" ++\n\"definition has the universes occur separately, and the definition will usually be used with \" ++\n\"explicit universe arguments. In this case, feel free to add `@[nolint check_univs]`.\",\n  is_fast := tt }\n\n/-!\n## Linter for syntactic tautologies\n-/\n\n/--\nChecks whether a lemma is a declaration of the form `\u2200 a b ... z, e\u2081 = e\u2082`\nwhere `e\u2081` and `e\u2082` are identical exprs.\nWe call declarations of this form syntactic tautologies.\nSuch lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts\nwith rfl when elaboration results in a different term than the user intended.\n-/\nmeta def syn_taut (d : declaration) : tactic (option string) :=\n  (do (el, er) \u2190 d.type.pi_codomain.is_eq,\n    guardb (el =\u2090 er),\n    return $ some \"LHS equals RHS syntactically\") <|>\n  return none\n\n/-- A linter for checking that declarations aren't syntactic tautologies. -/\n@[linter]\nmeta def linter.syn_taut : linter :=\n{ test := syn_taut,\n  auto_decls := ff, -- many false positives with this enabled\n  no_errors_found :=\n    \"No declarations are syntactic tautologies.\",\n  errors_found := \"THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. \" ++\n\"This usually means that they are of the form `\u2200 a b ... z, e\u2081 = e\u2082` where `e\u2081` and `e\u2082` are \" ++\n\"identical expressions. We call declarations of this form syntactic tautologies. \" ++\n\"Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving \" ++\n\"basic facts using `rfl`, when elaboration results in a different term than the user intended. \" ++\n\"You should check that the declaration really says what you think it does.\",\n  is_fast := tt }\n\nattribute [nolint syn_taut] rfl\n\n\n/-!\n## Linters for ineffectual have and suffices statements in term mode\n-/\n\n/--\nCheck if an expression contains `var 0` by folding over the expression and matching the binder depth\n-/\nmeta def expr.has_zero_var (e : expr) : bool :=\ne.fold ff $ \u03bb e' d res, res || match e' with | var k := k = d | _ := ff end\n\n/--\nReturn a list of unused have and suffices terms in an expression\n-/\nmeta def find_unused_have_suffices_macros : expr \u2192 tactic (list string)\n| (app a b) := (++) <$> find_unused_have_suffices_macros a <*> find_unused_have_suffices_macros b\n| (lam var_name bi var_type body) := find_unused_have_suffices_macros body\n| (pi var_name bi var_type body) := find_unused_have_suffices_macros body\n| (elet var_name type assignment body) := (++) <$> find_unused_have_suffices_macros assignment\n                                               <*> find_unused_have_suffices_macros body\n| m@(macro md [l@(lam ppnm bi vt bd)]) := do -- term mode have statements are tagged with a macro\n  -- if the macro annotation is `have then this lambda came from a term mode have statement\n  (++) (if m.is_annotation.iget.fst = `have \u2227 \u00acbd.has_zero_var then\n      [\"unnecessary have \" ++ ppnm.to_string ++ \" : \" ++ vt.to_string]\n    else []) <$>\n  find_unused_have_suffices_macros l\n| m@(macro md [app l@(lam ppnm bi vt bd) arg]) := do\n  -- term mode suffices statements are tagged with a macro\n  -- if the macro annotation is `suffices then this lambda came from a term mode suffices statement\n  (++) (if m.is_annotation.iget.fst = `suffices \u2227 \u00acbd.has_zero_var then\n      [\"unnecessary suffices \" ++ ppnm.to_string ++ \" : \" ++ vt.to_string]\n    else []) <$>\n  ((++) <$> find_unused_have_suffices_macros l <*> find_unused_have_suffices_macros arg)\n| (macro md l) := list.join <$> l.mmap find_unused_have_suffices_macros\n| _ := return []\n\n/--\nReturn a list of unused have and suffices terms in a declaration\n-/\nmeta def unused_have_of_decl : declaration \u2192 tactic (list string)\n| (declaration.defn _ _ _ bd _ _) := find_unused_have_suffices_macros bd\n| (declaration.thm _ _ _ bd) := find_unused_have_suffices_macros bd.get\n| _ := return []\n\n/--\nChecks whether a declaration contains term mode have statements that have no effect on the resulting\nterm.\n-/\nmeta def has_unused_haves_suffices (d : declaration) : tactic (option string) := do\n  ns \u2190 unused_have_of_decl d,\n  if ns.length = 0 then\n    return none\n  else\n    return (\", \".intercalate (ns.map to_string))\n\n/-- A linter for checking that declarations don't have unused term mode have statements. We do not\ntag this as `@[linter]` so that it is not in the default linter set as it is slow and an uncommon\nproblem. -/\nmeta def linter.unused_haves_suffices : linter :=\n{ test := has_unused_haves_suffices,\n  auto_decls := ff,\n  no_errors_found := \"No declarations have unused term mode have statements.\",\n  errors_found := \"THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. \" ++\n\"In the case of `have` this is a term of the form `have h := foo, bar` where `bar` does not \" ++\n\"refer to `foo`. Such statements have no effect on the generated proof, and can just be \" ++\n\"replaced by `bar`, in addition to being ineffectual, they may make unnecessary assumptions \" ++\n\"in proofs appear as if they are used. \" ++\n\"For `suffices` this is a term of the form `suffices h : foo, proof_of_goal, proof_of_foo` where\" ++\n\" `proof_of_goal` does not refer to `foo`. \" ++\n\"Such statements have no effect on the generated proof, and can just be replaced by \" ++\n\"`proof_of_goal`, in addition to being ineffectual, they may make unnecessary assumptions in \" ++\n\"proofs appear as if they are used. \",\n  is_fast := ff }\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/lint/misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.08882030144488993, "lm_q1q2_score": 0.04094764930967219}}
{"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek\n-/\nimport control.basic\nimport data.dlist.basic\nimport meta.expr\nimport system.io\nimport tactic.binder_matching\nimport tactic.interactive_expr\nimport tactic.lean_core_docs\nimport tactic.project_dir\n\nuniverse u\n\nattribute [derive [has_reflect, decidable_eq]] tactic.transparency\n\n-- Rather than import order.lexicographic here, we can get away with defining the order by hand.\ninstance : has_lt pos :=\n{ lt := \u03bb x y, x.line < y.line \u2228 x.line = y.line \u2227 x.column < y.column }\n\nnamespace tactic\n\n/-- Reflexivity conversion: given `e` returns `(e, \u22a2 e = e)` -/\nmeta def refl_conv (e : expr) : tactic (expr \u00d7 expr) :=\ndo p \u2190 mk_eq_refl e, return (e, p)\n\n/-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a\nproof by reflexivity. -/\nmeta def or_refl_conv (tac : expr \u2192 tactic (expr \u00d7 expr))\n  (e : expr) : tactic (expr \u00d7 expr) := tac e <|> refl_conv e\n\n/-- Transitivity conversion: given two conversions (which take an\nexpression `e` and returns `(e', \u22a2 e = e')`), produces another\nconversion that combines them with transitivity, treating failures\nas reflexivity conversions. -/\nmeta def trans_conv (t\u2081 t\u2082 : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) :\n  tactic (expr \u00d7 expr) :=\n(do (e\u2081, p\u2081) \u2190 t\u2081 e,\n  (do (e\u2082, p\u2082) \u2190 t\u2082 e\u2081,\n    p \u2190 mk_eq_trans p\u2081 p\u2082, return (e\u2082, p)) <|>\n  return (e\u2081, p\u2081)) <|> t\u2082 e\n\nend tactic\nopen tactic\n\nnamespace expr\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_nat \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`. -/\nprotected meta def of_nat (\u03b1 : expr) : \u2115 \u2192 tactic expr :=\nnat.binary_rec\n  (tactic.mk_mapp ``has_zero.zero [some \u03b1, none])\n  (\u03bb b n tac, if n = 0 then mk_mapp ``has_one.one [some \u03b1, none] else\n    do e \u2190 tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_int \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nprotected meta def of_int (\u03b1 : expr) : \u2124 \u2192 tactic expr\n| (n : \u2115) := expr.of_nat \u03b1 n\n| -[1+ n] := do\n  e \u2190 expr.of_nat \u03b1 (n+1),\n  tactic.mk_app ``has_neg.neg [e]\n\n/-- Generates an expression of the form `\u2203(args), inner`. `args` is assumed to be a list of local\nconstants. When possible, `p \u2227 q` is used instead of `\u2203(_ : p), q`. -/\nmeta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=\nargs.mfoldr (\u03bbarg i:expr, do\n    t \u2190 infer_type arg,\n    sort l \u2190 infer_type t,\n    return $ if arg.occurs i \u2228 l \u2260 level.zero\n      then (const `Exists [l] : expr) t (i.lambdas [arg])\n      else (const `and [] : expr) t i)\n  inner\n\n/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/\nmeta def traverse {m : Type \u2192 Type u} [applicative m]\n  {elab elab' : bool} (f : expr elab \u2192 m (expr elab')) :\n  expr elab \u2192 m (expr elab')\n | (var v)  := pure $ var v\n | (sort l) := pure $ sort l\n | (const n ls) := pure $ const n ls\n | (mvar n n' e) := mvar n n' <$> f e\n | (local_const n n' bi e) := local_const n n' bi <$> f e\n | (app e\u2080 e\u2081) := app <$> f e\u2080 <*> f e\u2081\n | (lam n bi e\u2080 e\u2081) := lam n bi <$> f e\u2080 <*> f e\u2081\n | (pi n bi e\u2080 e\u2081) := pi n bi <$> f e\u2080 <*> f e\u2081\n | (elet n e\u2080 e\u2081 e\u2082) := elet n <$> f e\u2080 <*> f e\u2081 <*> f e\u2082\n | (macro mac es) := macro mac <$> list.traverse f es\n\n/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,\nwith initial value `a`. -/\nmeta def mfoldl {\u03b1 : Type} {m} [monad m] (f : \u03b1 \u2192 expr \u2192 m \u03b1) : \u03b1 \u2192 expr \u2192 m \u03b1\n| x e := prod.snd <$> (state_t.run (e.traverse $ \u03bb e',\n    (get >>= monad_lift \u2218 flip f e' >>= put) $> e') x : m _)\n\n/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`\nwith `new`. The occurrences of `old` in `e` are determined using keyed matching\nwith transparency `md`; see `kabstract` for details. If `unify` is true,\nwe may assign metavariables in `e` as we match subterms of `e` against `old`. -/\nmeta def kreplace (e old new : expr) (md := semireducible) (unify := tt)\n  : tactic expr := do\n  e \u2190 kabstract e old md unify,\n  pure $ e.instantiate_var new\n\nend expr\n\nnamespace name\n\n/--\n`pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm`\nor (recusively) in any declarations occurring in the value of `nm` with namespace `pre`.\nAuxiliary function for `name.contains_sorry`. -/\nmeta def contains_sorry_aux (pre : name) : name \u2192 tactic bool | nm := do\n  env \u2190 get_env,\n  decl \u2190 get_decl nm,\n  ff \u2190 return decl.value.contains_sorry | return tt,\n  (decl.value.list_names_with_prefix pre).mfold ff $\n    \u03bb n b, if b then return tt else n.contains_sorry_aux\n\n/-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or\n  in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`).\n  See also `expr.contains_sorry`. -/\nmeta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm\n\nend name\n\nnamespace interaction_monad\nopen result\n\nvariables {\u03c3 : Type} {\u03b1 : Type u}\n\n/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/\n-- Note that this is a generalization of `tactic.read` in core.\nmeta def get_state : interaction_monad \u03c3 \u03c3 :=\n\u03bb state, success state state\n\n/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/\n-- Note that this is a generalization of `tactic.write` in core.\nmeta def set_state (state : \u03c3) : interaction_monad \u03c3 unit :=\n\u03bb _, success () state\n\n/--\n`run_with_state state tac` applies `tac` to the given state `state` and returns the result,\nsubsequently restoring the original state.\nIf `tac` fails, then `run_with_state` does too.\n-/\nmeta def run_with_state (state : \u03c3) (tac : interaction_monad \u03c3 \u03b1) : interaction_monad \u03c3 \u03b1 :=\n\u03bb s, match tac state with\n     | success val _      := success val s\n     | exception fn pos _ := exception fn pos s\n     end\n\nend interaction_monad\n\nnamespace format\n\n/-- `join' [a,b,c]` produces the format object `abc`.\nIt differs from `format.join` by using `format.nil` instead of `\"\"` for the empty list. -/\nmeta def join' (xs : list format) : format :=\nxs.foldl compose nil\n\n/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,\nwhere `.` represents `format.join`. -/\nmeta def intercalate (x : format) : list format \u2192 format :=\njoin' \u2218 list.intersperse x\n\n/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`\nthe result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`\neach line break is decided independently -/\nmeta def soft_break : format :=\ngroup line\n\n/-- Format a list as a comma separated list, without any brackets. -/\nmeta def comma_separated {\u03b1 : Type*} [has_to_format \u03b1] : list \u03b1 \u2192 format\n| [] := nil\n| xs := group (nest 1 $ intercalate (\",\" ++ soft_break) $ xs.map to_fmt)\n\nend format\n\nsection format\nopen format\n\n/-- format a `list` by separating elements with `soft_break` instead of `line` -/\nmeta def list.to_line_wrap_format {\u03b1 : Type u} [has_to_format \u03b1] (l : list \u03b1) : format :=\nbracket \"[\" \"]\" (comma_separated l)\n\nend format\n\nnamespace tactic\nopen function\n\nexport interaction_monad (get_state set_state run_with_state)\n\n/-- Private work function for `add_local_consts_as_local_hyps`: given\n    `mappings : list (expr \u00d7 expr)` corresponding to pairs `(var, hyp)` of variables and the local\n    hypothesis created as a result and `(var :: rest) : list expr` of more local variables we\n    examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the\n    back of the queue and recurse. If it does not, then we perform replacements inside the type of\n    `var` using the `mappings`, create a new associate local hypothesis, add this to the list of\n    mappings, and recurse. We are done once all local hypotheses have been processed.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\nprivate meta def add_local_consts_as_local_hyps_aux\n  : list (expr \u00d7 expr) \u2192 list expr \u2192 tactic (list (expr \u00d7 expr))\n| mappings [] := return mappings\n| mappings (var :: rest) := do\n  /- Determine if `var` contains any local variables in the lift `rest`. -/\n  let is_dependent := var.local_type.fold ff $ \u03bb e n b,\n    if b then b else e \u2208 rest,\n\n  /- If so, then skip it---add it to the end of the variable queue. -/\n  if is_dependent then\n    add_local_consts_as_local_hyps_aux mappings (rest ++ [var])\n  else do\n    /- Otherwise, replace all of the local constants referenced by the type of `var` with the\n       respective new corresponding local hypotheses as recorded in the list `mappings`. -/\n    let new_type := var.local_type.replace_subexprs mappings,\n\n    /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/\n    hyp \u2190 assertv var.local_pp_name new_type (var.local_const_set_type new_type),\n\n    /- Process the next variable in the queue, with the mapping list updated to include the local\n       hypothesis which we just created. -/\n    add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest\n\n/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the\n    tactic state. This is harder than it sounds, since the list of local constants which we have\n    been passed can have dependencies between their types.\n\n    For example, suppose we have two local constants `n : \u2115` and `h : n = 3`. Then we cannot blindly\n    add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as\n    a new local hypothesis, not the old local constant `n` with the same name. Of course, these\n    dependencies can be nested arbitrarily deep.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\nmeta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr \u00d7 expr)) :=\n/- The `list.reverse` below is a performance optimisation since the list of available variables\n   reported by the system is often mostly the reverse of the order in which they are dependent. -/\nadd_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup\n\nprivate meta def get_expl_pi_arity_aux : expr \u2192 tactic nat\n| (expr.pi n bi d b) :=\n  do m     \u2190 mk_fresh_name,\n     let l := expr.local_const m n bi d,\n     new_b \u2190 whnf (expr.instantiate_var b l),\n     r     \u2190 get_expl_pi_arity_aux new_b,\n     if bi = binder_info.default then\n       return (r + 1)\n     else\n       return r\n| e := return 0\n\n/-- Compute the arity of explicit arguments of `type`. -/\nmeta def get_expl_pi_arity (type : expr) : tactic nat :=\nwhnf type >>= get_expl_pi_arity_aux\n\n/-- Compute the arity of explicit arguments of `fn`'s type. -/\nmeta def get_expl_arity (fn : expr) : tactic nat :=\ninfer_type fn >>= get_expl_pi_arity\n\nprivate meta def get_app_fn_args_whnf_aux (md : transparency)\n  (unfold_ginductive : bool) : list expr \u2192 expr \u2192 tactic (expr \u00d7 list expr) :=\n\u03bb args e, do\n  e \u2190 whnf e md unfold_ginductive,\n  match e with\n  | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t\n  | _ := pure (e, args)\n  end\n\n/--\nFor `e = f x\u2081 ... x\u2099`, `get_app_fn_args_whnf e` returns `(f, [x\u2081, ..., x\u2099])`. `e`\nis normalised as necessary; for example:\n\n```\nget_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])\n```\n\nThe returned expression is in whnf, but the arguments are generally not.\n-/\nmeta def get_app_fn_args_whnf (e : expr) (md := semireducible)\n  (unfold_ginductive := tt) : tactic (expr \u00d7 list expr) :=\nget_app_fn_args_whnf_aux md unfold_ginductive [] e\n\n/--\n`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is\nnormalised as necessary (with transparency `md`). `unfold_ginductive` controls\nwhether constructors of generalised inductive types are unfolded. The returned\nexpression is in whnf.\n-/\nmeta def get_app_fn_whnf : expr \u2192 opt_param _ semireducible \u2192 opt_param _ tt \u2192 tactic expr\n| e md unfold_ginductive := do\n  e \u2190 whnf e md unfold_ginductive,\n  match e with\n  | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive\n  | _ := pure e\n  end\n\n/--\n`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x\u2081 ... x\u2099`,\nwhere `C` is a constant, after normalisation with transparency `md`. If so, the\nname of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded.\n-/\nmeta def get_app_fn_const_whnf (e : expr) (md := semireducible)\n  (unfold_ginductive := tt) : tactic name := do\n  f \u2190 get_app_fn_whnf e md unfold_ginductive,\n  match f with\n  | (expr.const n _) := pure n\n  | _ := fail format!\n    \"expected a constant (possibly applied to some arguments), but got:\\n{e}\"\n  end\n\n/--\n`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`\nis normalised as necessary (with transparency `md`). `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded. The\nreturned expressions are not necessarily in whnf.\n-/\nmeta def get_app_args_whnf (e : expr) (md := semireducible)\n  (unfold_ginductive := tt) : tactic (list expr) :=\nprod.snd <$> get_app_fn_args_whnf e md unfold_ginductive\n\n/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with pi binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``pis [a, b] `(f a b)`` will return the expression\n`\u03a0 (a : Ta) (b : Tb), f a b`. -/\nmeta def pis : list expr \u2192 expr \u2192 tactic expr\n| (e@(expr.local_const uniq pp info _) :: es) f := do\n  t \u2190 infer_type e,\n  f' \u2190 pis es f,\n  pure $ expr.pi pp info t (expr.abstract_local f' uniq)\n| _ f := pure f\n\n/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with lambda binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``lambdas [a, b] `(f a b)`` will return the expression\n`\u03bb (a : Ta) (b : Tb), f a b`. -/\nmeta def lambdas : list expr \u2192 expr \u2192 tactic expr\n| (e@(expr.local_const uniq pp info _) :: es) f := do\n  t \u2190 infer_type e,\n  f' \u2190 lambdas es f,\n  pure $ expr.lam pp info t (expr.abstract_local f' uniq)\n| _ f := pure f\n\n-- TODO: move to `declaration` namespace in `meta/expr.lean`\n/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named\n`ls`, type `t`, and body `e`. -/\nmeta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=\ndeclaration.thm n ls t (task.pure e)\n\n/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this\nto the environment as a theorem with name `n` and universe parameters `ls`. -/\nmeta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :\n  tactic expr :=\ndo ((), body) \u2190 solve_aux type tac,\n   body \u2190 instantiate_mvars body,\n   add_decl $ mk_theorem n ls type body,\n   return $ expr.const n $ ls.map level.param\n\n/-- `eval_expr' \u03b1 e` attempts to evaluate the expression `e` in the type `\u03b1`.\nThis is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare\nsituations the latter will fail but the former will succeed. -/\nmeta def eval_expr' (\u03b1 : Type*) [_inst_1 : reflected \u03b1] (e : expr) : tactic \u03b1 :=\nmk_app ``id [e] >>= eval_expr \u03b1\n\n/-- `mk_fresh_name` returns identifiers starting with underscores,\nwhich are not legal when emitted by tactic programs. `mk_user_fresh_name`\nturns the useful source of random names provided by `mk_fresh_name` into\nnames which are usable by tactic programs.\n\nThe returned name has four components which are all strings. -/\nmeta def mk_user_fresh_name : tactic name :=\ndo nm \u2190 mk_fresh_name,\n   return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__\n\n/-- `has_attribute' attr_name decl_name` checks\nwhether `decl_name` exists and has attribute `attr_name`. -/\nmeta def has_attribute' (attr_name decl_name : name) : tactic bool :=\nsucceeds (has_attribute attr_name decl_name)\n\n/-- Checks whether the name is a simp lemma -/\nmeta def is_simp_lemma : name \u2192 tactic bool :=\nhas_attribute' `simp\n\n/-- Checks whether the name is an instance. -/\nmeta def is_instance : name \u2192 tactic bool :=\nhas_attribute' `instance\n\n/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.\nCovers all declarations from the current file. -/\nmeta def local_decls : tactic (name_map declaration) :=\ndo e \u2190 tactic.get_env,\n   let xs := e.fold native.mk_rb_map\n     (\u03bb d s, if environment.in_current_file e d.to_name\n             then s.insert d.to_name d else s),\n   pure xs\n\n/-- `get_decls_from` returns a dictionary mapping names to their\ncorresponding declarations.  Covers all declarations the files listed\nin `fs`, with the current file listed as `none`.\n\nThe path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present); e.g. `\"src/tactic/core.lean\"`\n\nPossible issue: `get_decls_from` uses `get_cwd`, the current working\ndirectory, which may not always point at the root of the project.\nIt would work better if it searched for the root directory or,\nbetter yet, if Lean exposed its path information.\n-/\nmeta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=\ndo root \u2190 unsafe_run_io $ io.env.get_cwd,\n   let fs := fs.map (option.map $ \u03bb path, root ++ \"/\" ++ path),\n   err \u2190 unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot \u2218 io.fs.file_exists,\n   guard (err = []) <|> fail format!\"File not found: {err}\",\n   e \u2190 tactic.get_env,\n   let xs := e.fold native.mk_rb_map\n     (\u03bb d s,\n       let source := e.decl_olean d.to_name in\n       if source \u2208 fs \u2227 (source = none \u2192 e.in_current_file d.to_name)\n       then s.insert d.to_name d else s),\n   pure xs\n\n/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/\nmeta def get_unused_decl_name_aux (e : environment) (nm : name) : \u2115 \u2192 tactic name | n :=\nlet nm' := nm.append_suffix (\"_\" ++ to_string n) in\nif e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'\n\n/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it\nreturns that, otherwise it tries `nm_2`, `nm_3`, ... -/\nmeta def get_unused_decl_name (nm : name) : tactic name :=\nget_env >>= \u03bb e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm\n\n/--\nReturns a pair `(e, t)`, where `e \u2190 mk_const d.to_name`, and `t = d.type`\nbut with universe params updated to match the fresh universe metavariables in `e`.\n\nThis should have the same effect as just\n```lean\ndo e \u2190 mk_const d.to_name,\n   t \u2190 infer_type e,\n   return (e, t)\n```\nbut is hopefully faster.\n-/\nmeta def decl_mk_const (d : declaration) : tactic (expr \u00d7 expr) :=\ndo subst \u2190 d.univ_params.mmap $ \u03bb u, prod.mk u <$> mk_meta_univ,\n   let e : expr := expr.const d.to_name (prod.snd <$> subst),\n   return (e, d.type.instantiate_univ_params subst)\n\n/--\nReplace every universe metavariable in an expression with a universe parameter.\n\n(This is useful when making new declarations.)\n-/\nmeta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=\ndo\n  e.list_univ_meta_vars.enum.mmap (\u03bb n, do\n    let n' := (`u).append_suffix (\"_\" ++ to_string (n.1+1)),\n    unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),\n  instantiate_mvars e\n\n/-- `mk_local n` creates a dummy local variable with name `n`.\nThe type of this local constant is a constant with name `n`, so it is very unlikely to be\na meaningful expression. -/\nmeta def mk_local (n : name) : expr :=\nexpr.local_const n n binder_info.default (expr.const n [])\n\n/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,\n`y : ty x` and `z : tz x y`, creates an expression of sigma type:\n`\u27e8x,y,z\u27e9 : \u03a3' (x : tx) (y : ty x), tz x y`.\n-/\nmeta def mk_psigma : list expr \u2192 tactic expr\n| [] := mk_const ``punit\n| [x@(expr.local_const _ _ _ _)] := pure x\n| (x@(expr.local_const _ _ _ _) :: xs) :=\n  do y \u2190 mk_psigma xs,\n     \u03b1 \u2190 infer_type x,\n     \u03b2 \u2190 infer_type y,\n     t \u2190 lambdas [x] \u03b2 >>= instantiate_mvars,\n     r \u2190 mk_mapp ``psigma.mk [\u03b1,t],\n     pure $ r x y\n| _ := fail \"mk_psigma expects a list of local constants\"\n\n/--\nUpdate the type of a local constant or metavariable. For local constants and\nmetavariables obtained via, for example, `tactic.get_local`, the type stored in\nthe expression is not necessarily the same as the type returned by `infer_type`.\nThis tactic, given a local constant or metavariable, updates the stored type to\nmatch the output of `infer_type`. If the input is not a local constant or\nmetavariable, `update_type` does nothing.\n-/\nmeta def update_type : expr \u2192 tactic expr\n| e@(expr.local_const ppname uname binfo _) :=\n  expr.local_const ppname uname binfo <$> infer_type e\n| e@(expr.mvar ppname uname _) :=\n  expr.mvar ppname uname <$> infer_type e\n| e := pure e\n\n/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`\ntimes and uses `ns` to name the resulting variables. Returns a triple: list of new variables,\nremaining term and unused variable names.\n-/\nmeta def elim_gen_prod : nat \u2192 expr \u2192 list expr \u2192 list name \u2192 tactic (list expr \u00d7 expr \u00d7 list name)\n| 0       e hs ns := return (hs.reverse, e, ns)\n| (n + 1) e hs ns := do\n  t \u2190 infer_type e,\n  if t.is_app_of `eq then return (hs.reverse, e, ns)\n  else do\n    [(_, [h, h'], _)] \u2190 cases_core e (ns.take 1),\n    elim_gen_prod n h' (h :: hs) (ns.drop 1)\n\nprivate meta def elim_gen_sum_aux : nat \u2192 expr \u2192 list expr \u2192 tactic (list expr \u00d7 expr)\n| 0       e hs := return (hs, e)\n| (n + 1) e hs := do\n  [(_, [h], _), (_, [h'], _)] \u2190 induction e [],\n  swap,\n  elim_gen_sum_aux n h' (h::hs)\n\n/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose\ntype is a (nested) sum `\u2295`. Returns the list of local constants representing the components of `e`.\n-/\nmeta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do\n  (hs, h') \u2190 elim_gen_sum_aux n e [],\n  gs \u2190 get_goals,\n  set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),\n  return $ hs.reverse ++ [h']\n\n/-- Given `elab_def`, a tactic to solve the current goal,\n`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it\nto close the goal. If `trusted` is false, it will be a meta definition. -/\nmeta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=\ndo cxt \u2190 list.map expr.to_implicit_local_const <$> local_context,\n   t \u2190 target,\n   (eqns,d) \u2190 solve_aux t elab_def,\n   d \u2190 instantiate_mvars d,\n   t' \u2190 pis cxt t,\n   d' \u2190 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   applyc n\n\n/-- Attempts to close the goal with `dec_trivial`. -/\nmeta def exact_dec_trivial : tactic unit := `[exact dec_trivial]\n\n/-- Runs a tactic for a result, reverting the state after completion. -/\nmeta def retrieve {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s, result.cases_on (tac s)\n (\u03bb a s', result.success a s)\n result.exception\n\n/-- Runs a tactic for a result, reverting the state after completion or error. -/\nmeta def retrieve' {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s, result.cases_on (tac s)\n (\u03bb a s', result.success a s)\n (\u03bb msg pos s', result.exception msg pos s)\n\n/-- Repeat a tactic at least once, calling it recursively on all subgoals,\nuntil it fails. This tactic fails if the first invocation fails. -/\nmeta def repeat1 (t : tactic unit) : tactic unit := t; repeat t\n\n/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and\nat most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/\nmeta def iterate_range : \u2115 \u2192 \u2115 \u2192 tactic unit \u2192 tactic unit\n| 0 0     t := skip\n| 0 (n+1) t := try (t >> iterate_range 0 n t)\n| (m+1) n t := t >> iterate_range m (n-1) t\n\n/--\nGiven a tactic `tac` that takes an expression\nand returns a new expression and a proof of equality,\nuse that tactic to change the type of the hypotheses listed in `hs`,\nas well as the goal if `tgt = tt`.\n\nReturns `tt` if any types were successfully changed.\n-/\nmeta def replace_at (tac : expr \u2192 tactic (expr \u00d7 expr)) (hs : list expr) (tgt : bool) :\n  tactic bool :=\ndo to_remove \u2190 hs.mfilter $ \u03bb h, do\n  { h_type \u2190 infer_type h,\n    succeeds $ do\n      (new_h_type, pr) \u2190 tac h_type,\n      assert h.local_pp_name new_h_type,\n      mk_eq_mp pr h >>= tactic.exact },\n  goal_simplified \u2190 succeeds $ do\n  { guard tgt,\n    (new_t, pr) \u2190 target >>= tac,\n    replace_target new_t pr },\n  to_remove.mmap' (\u03bb h, try (clear h)),\n  return (\u00ac to_remove.empty \u2228 goal_simplified)\n\n/-- `revert_after e` reverts all local constants after local constant `e`. -/\nmeta def revert_after (e : expr) : tactic \u2115 := do\n  l \u2190 local_context,\n  [pos] \u2190 return $ l.indexes_of e | pp e >>= \u03bb s, fail format!\"No such local constant {s}\",\n  let l := l.drop pos.succ, -- all local hypotheses after `e`\n  revert_lst l\n\n/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).\n  Returns the number of local constants that have been reverted. -/\nmeta def revert_target_deps : tactic \u2115 :=\ndo tgt \u2190 target,\n   ctx \u2190 local_context,\n   l \u2190 ctx.mfilter (kdepends_on tgt),\n   n \u2190 revert_lst l,\n   if l = [] then return n\n     else do m \u2190 revert_target_deps, return (m + n)\n\n/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant\nwith name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.\n\n`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the\ngoal, in which case it just calls `assert`.\nIn contrast to `generalize` it already introduces the generalized variable. -/\nmeta def generalize' (e : expr) (n : name) : tactic expr :=\n(generalize e n >> intro n) <|> note n none e\n\n/--\n`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name\nprovided by the binder to name the new local constant.\nUnlike `intron`, it does not rename introduced constants if the names shadow existing constants.\n-/\nmeta def intron_no_renames : \u2115 \u2192 tactic unit\n| 0 := pure ()\n| (n+1) := do\n  expr.pi pp_n _ _ _ \u2190 target,\n  intro pp_n,\n  intron_no_renames n\n\n/-- `get_univ_level t` returns the universe level of a type `t` -/\nmeta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) :\n  tactic level :=\ndo expr.sort u \u2190 infer_type t >>= \u03bb s, whnf s md unfold_ginductive |\n    fail \"get_univ_level: argument is not a type\",\n   return u\n\n/-!\n### Various tactics related to local definitions (local constants of the form `x : \u03b1 := t`)\n\nWe call `t` the value of `x`.\n-/\n\n/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined\n  locally using a `let` expression. Otherwise it fails. -/\nmeta def local_def_value (e : expr) : tactic expr :=\npp e >>= \u03bb s, -- running `pp` here, because we cannot access it in the `type_context` monad.\ntactic.unsafe.type_context.run $ do\n  lctx <- tactic.unsafe.type_context.get_local_context,\n  some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |\n    tactic.unsafe.type_context.fail format!\"No such hypothesis {s}.\",\n  some let_val <- return ldecl.value |\n    tactic.unsafe.type_context.fail format!\"Variable {e} is not a local definition.\",\n  return let_val\n\n/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form\n`e : \u03b1 := t`) and otherwise fails. -/\nmeta def is_local_def (e : expr) : tactic unit := do\n  ctx \u2190 unsafe.type_context.get_local_context.run,\n  (some decl) \u2190 pure $ ctx.get_local_decl e.local_uniq_name |\n    fail format!\"is_local_def: {e} is not a local constant\",\n  when decl.value.is_none $ fail\n   format!\"is_local_def: {e} is not a local definition\"\n\n/-- Returns the local definitions from the context. A local definition is a\nlocal constant of the form `e : \u03b1 := t`. The local definitions are returned in\nthe order in which they appear in the context. -/\nmeta def local_defs : tactic (list expr) := do\n  ctx \u2190 unsafe.type_context.get_local_context.run,\n  ctx' \u2190 local_context,\n  ctx'.mfilter $ \u03bb h, do\n    (some decl) \u2190 pure $ ctx.get_local_decl h.local_uniq_name |\n      fail format!\"local_defs: local {h} not found in the local context\",\n    pure decl.value.is_some\n\n/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`\n(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.\nwhereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes\nthem in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition\nrunning up to the first match. -/\nprivate def partition_local_deps_aux {\u03b1} [decidable_eq \u03b1] (vs : list \u03b1) :\n  list \u03b1 \u2192 list \u03b1 \u2192 list (list \u03b1)\n| [] acc := [acc.reverse]\n| (l :: ls) acc :=\n  if l \u2208 vs then acc.reverse :: partition_local_deps_aux ls [l]\n  else partition_local_deps_aux ls (l :: acc)\n\n/-- `partition_local_deps vs`, with `vs` a list of local constants,\nreorders `vs` in the order they appear in the local context together\nwith the variables that follow them. If local context is `[a,b,c,d,e,f]`,\nand that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.\nThe head of each list is one of the variables given as a parameter. -/\nmeta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=\ndo ls \u2190 local_context,\n   pure (partition_local_deps_aux vs ls []).tail.reverse\n\n/-- `clear_value [e\u2080, e\u2081, e\u2082, ...]` clears the body of the local definitions `e\u2080`, `e\u2081`, `e\u2082`, ...\nchanging them into regular hypotheses. A hypothesis `e : \u03b1 := t` is changed to `e : \u03b1`. The order of\nlocals `e\u2080`, `e\u2081`, `e\u2082` does not matter as a permutation will be chosen so as to preserve type\ncorrectness. This tactic is called `clearbody` in Coq. -/\nmeta def clear_value (vs : list expr) : tactic unit := do\n  ls \u2190 partition_local_deps vs,\n  ls.mmap' $ \u03bb vs, do\n  { revert_lst vs,\n    (expr.elet v t d b) \u2190 target |\n      fail format!\"Cannot clear the body of {vs.head}. It is not a local definition.\",\n    let e := expr.pi v binder_info.default t b,\n    type_check e <|>\n      fail format!\"Cannot clear the body of {vs.head}. The resulting goal is not type correct.\",\n    g \u2190 mk_meta_var e,\n    h \u2190 note `h none g,\n    tactic.exact $ h d,\n    gs \u2190 get_goals,\n    set_goals $ g :: gs },\n  ls.reverse.mmap' $ \u03bb vs, intro_lst $ vs.map expr.local_pp_name\n\n/--\n`context_has_local_def` is true iff there is at least one local definition in\nthe context.\n-/\nmeta def context_has_local_def : tactic bool := do\n  ctx \u2190 local_context,\n  ctx.many (succeeds \u2218 local_def_value)\n\n/--\n`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the\ncontext up to and including `h` is a local definition.\n-/\nmeta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do\n  ff \u2190 succeeds (local_def_value h) | pure tt,\n  ctx \u2190 local_context,\n  let ctx := ctx.take_while (\u2260 h),\n  ctx.many (succeeds \u2218 local_def_value)\n\n/--\nIf the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\nIf `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and\nsubstitute `t` for `h`.\n\nThis is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a\nlocal definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nmeta def subst' (h : expr) : tactic unit := do\n  e \u2190 do { -- we first find the variable being substituted away\n    t \u2190 infer_type h,\n    let (f, args) := t.get_app_fn_args,\n    if (f.const_name = `eq \u2228 f.const_name = `heq) then do\n    { let lhs := args.inth 1,\n      let rhs := args.ilast,\n      if rhs.is_local_constant then return rhs else\n      if lhs.is_local_constant then return lhs else fail\n      \"subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x).\" }\n    else return h },\n  success_if_fail (is_local_def e) <|>\n    fail format!(\"Cannot substitute variable {e.local_pp_name}, \" ++\n      \"it is a local definition. If you really want to do this, use `clear_value` first.\"),\n  subst h\n\n/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,\n`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting\nexpression and a proof of equality. -/\nmeta def simp_bottom_up' (post : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) (cfg : simp_config := {}) :\n  tactic (expr \u00d7 expr) :=\nprod.snd <$> simplify_bottom_up () (\u03bb _, (<$>) (prod.mk ()) \u2218 post) e cfg\n\n/-- Caches unary type classes on a type `\u03b1 : Type.{univ}`. -/\nmeta structure instance_cache :=\n(\u03b1 : expr)\n(univ : level)\n(inst : name_map expr)\n\n/-- Creates an `instance_cache` for the type `\u03b1`. -/\nmeta def mk_instance_cache (\u03b1 : expr) : tactic instance_cache :=\ndo u \u2190 mk_meta_univ,\n   infer_type \u03b1 >>= unify (expr.sort (level.succ u)),\n   u \u2190 get_univ_assignment u,\n   return \u27e8\u03b1, u, mk_name_map\u27e9\n\nnamespace instance_cache\n\n/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of\n`n c.\u03b1` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance\nvia type class resolution, and updates the cache. -/\nmeta def get (c : instance_cache) (n : name) : tactic (instance_cache \u00d7 expr) :=\nmatch c.inst.find n with\n| some i := return (c, i)\n| none := do e \u2190 mk_app n [c.\u03b1] >>= mk_instance,\n  return (\u27e8c.\u03b1, c.univ, c.inst.insert n e\u27e9, e)\nend\n\nopen expr\n/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,\n`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/\nmeta def append_typeclasses : expr \u2192 instance_cache \u2192 list expr \u2192\n  tactic (instance_cache \u00d7 list expr)\n| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=\n  do (c, p) \u2190 c.get n, return (c, p :: l)\n| _ c l := return (c, l)\n\n/-- Creates the application `n c.\u03b1 p l`, where `p` is a type class instance found in the cache `c`.\n-/\nmeta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache \u00d7 expr) :=\ndo d \u2190 get_decl n,\n   (c, l) \u2190 append_typeclasses d.type.binding_body c l,\n   return (c, (expr.const n [c.univ]).mk_app (c.\u03b1 :: l))\n\n/-- `c.of_nat n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`. -/\nprotected meta def of_nat (c : instance_cache) (n : \u2115) : tactic (instance_cache \u00d7 expr) :=\nif n = 0 then c.mk_app ``has_zero.zero [] else do\n  (c, ai) \u2190 c.get ``has_add,\n  (c, oi) \u2190 c.get ``has_one,\n  (c, one) \u2190 c.mk_app ``has_one.one [],\n  return (c, n.binary_rec one $ \u03bb b n e,\n    if n = 0 then one else\n    cond b\n      ((expr.const ``bit1 [c.univ]).mk_app [c.\u03b1, oi, ai, e])\n      ((expr.const ``bit0 [c.univ]).mk_app [c.\u03b1, ai, e]))\n\n/-- `c.of_int n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nprotected meta def of_int (c : instance_cache) : \u2124 \u2192 tactic (instance_cache \u00d7 expr)\n| (n : \u2115) := c.of_nat n\n| -[1+ n] := do\n  (c, e) \u2190 c.of_nat (n+1),\n  c.mk_app ``has_neg.neg [e]\n\nend instance_cache\n\n/-- A variation on `assert` where a (possibly incomplete)\nproof of the assertion is provided as a parameter.\n\n``(h,gs) \u2190 local_proof `h p tac`` creates a local `h : p` and\nuse `tac` to (partially) construct a proof for it. `gs` is the\nlist of remaining goals in the proof of `h`.\n\nThe benefits over assert are:\n- unlike with ``h \u2190 assert `h p, tac`` , `h` cannot be used by `tac`;\n- when `tac` does not complete the proof of `h`, returning the list\n  of goals allows one to write a tactic using `h` and with the confidence\n  that a proof will not boil over to goals left over from the proof of `h`,\n  unlike what would be the case when using `tactic.swap`.\n-/\nmeta def local_proof (h : name) (p : expr) (tac\u2080 : tactic unit) :\n  tactic (expr \u00d7 list expr) :=\nfocus1 $\ndo h' \u2190 assert h p,\n   [g\u2080,g\u2081] \u2190 get_goals,\n   set_goals [g\u2080], tac\u2080,\n   gs \u2190 get_goals,\n   set_goals [g\u2081],\n   return (h', gs)\n\n/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/\nmeta def var_names : expr \u2192 list name\n| (expr.pi n _ _ b) := n :: var_names b\n| _ := []\n\n/-- When `struct_n` is the name of a structure type,\n`subobject_names struct_n` returns two lists of names `(instances, fields)`.\nThe names in `instances` are the projections from `struct_n` to the structures that it extends\n(assuming it was defined with `old_structure_cmd false`).\nThe names in `fields` are the standard fields of `struct_n`. -/\nmeta def subobject_names (struct_n : name) : tactic (list name \u00d7 list name) :=\ndo env \u2190 get_env,\n   c \u2190 match env.constructors_of struct_n with\n       | [c] := pure c\n       | [] :=\n         if env.is_inductive struct_n\n           then fail format!\"{struct_n} does not have constructors\"\n           else fail format!\"{struct_n} is not an inductive type\"\n       | _ := fail \"too many constructors\"\n       end,\n   vs  \u2190 var_names <$> (mk_const c >>= infer_type),\n   fields \u2190 env.structure_fields struct_n,\n   return $ fields.partition (\u03bb fn, \u2191(\"_\" ++ fn.to_string) \u2208 vs)\n\nprivate meta def expanded_field_list' : name \u2192 tactic (dlist $ name \u00d7 name) | struct_n :=\ndo (so,fs) \u2190 subobject_names struct_n,\n   ts \u2190 so.mmap (\u03bb n, do\n     (_, e) \u2190 mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,\n     expanded_field_list' $ e.get_app_fn.const_name),\n   return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)\nopen functor function\n\n/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure\nnamed `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name\nof the projection is `prefix.name`.\n\n`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/\nmeta def expanded_field_list (struct_n : name) : tactic (list $ name \u00d7 name) :=\ndlist.to_list <$> expanded_field_list' struct_n\n\n/--\nReturn a list of all type classes which can be instantiated\nfor the given expression.\n-/\nmeta def get_classes (e : expr) : tactic (list name) :=\nattribute.get_instances `class >>= list.mfilter (\u03bb n,\n  succeeds $ mk_app n [e] >>= mk_instance)\n\n/--\nFinds an instance of an implication `cond \u2192 tgt`.\nReturns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention\n`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,\nsince it has been \"proven\" by a metavariable.\n-/\nmeta def mk_conditional_instance (cond tgt : expr) : tactic (expr \u00d7 expr) := do\nf \u2190 mk_meta_var cond,\ne \u2190 assertv `c cond f, swap,\nreset_instance_cache,\ninst \u2190 mk_instance tgt,\nreturn (e, inst)\n\nopen nat\n\n/-- Create a list of `n` fresh metavariables. -/\nmeta def mk_mvar_list : \u2115 \u2192 tactic (list expr)\n| 0 := pure []\n| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n\n\n/-- Returns the only goal, or fails if there isn't just one goal. -/\nmeta def get_goal : tactic expr :=\ndo gs \u2190 get_goals,\n   match gs with\n   | [a] := return a\n   | []  := fail \"there are no goals\"\n   | _   := fail \"there are too many goals\"\n   end\n\n/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,\nor until it fails. Always succeeds. -/\nmeta def iterate_at_most_on_all_goals : nat \u2192 tactic unit \u2192 tactic unit\n| 0        tac := trace \"maximal iterations reached\"\n| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip\n\n/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first\ngoal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on\ncurrent goal. -/\nmeta def iterate_at_most_on_subgoals : nat \u2192 tactic unit \u2192 tactic unit\n| 0        tac := trace \"maximal iterations reached\"\n| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)\n\n/-- This makes sure that the execution of the tactic does not change the tactic state.\nThis can be helpful while using rewrite, apply, or expr munging.\nRemember to instantiate your metavariables before you're done! -/\nmeta def lock_tactic_state {\u03b1} (t : tactic \u03b1) : tactic \u03b1\n| s := match t s with\n       | result.success a s' := result.success a s\n       | result.exception msg pos s' := result.exception msg pos s\nend\n\n/--\n`apply_list l`, for `l : list (tactic expr)`,\ntries to apply the lemmas generated by the tactics in `l` on the first goal, and\nfail if none succeeds.\n-/\nmeta def apply_list_expr (opt : apply_cfg) : list (tactic expr) \u2192 tactic unit\n| []     := fail \"no matching rule\"\n| (h::t) := (do e \u2190 h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t\n\n/--\nConstructs a list of `tactic expr` given a list of p-expressions, as follows:\n- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it\n- if the p-expression is a user attribute, add all the theorems with this attribute\n  to the list.\n\nWe need to return a list of `tactic expr`, rather than just `expr`, because these expressions\nwill be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.\n-/\nmeta def build_list_expr_for_apply : list pexpr \u2192 tactic (list (tactic expr))\n| [] := return []\n| (h::t) := do\n  tail \u2190 build_list_expr_for_apply t,\n  a \u2190 i_to_expr_for_apply h,\n  (do l \u2190 attribute.get_instances (expr.const_name a),\n      m \u2190 l.mmap (\u03bb n, _root_.to_pexpr <$> mk_const n),\n      -- We reverse the list of lemmas marked with an attribute,\n      -- on the assumption that lemmas proved earlier are more often applicable\n      -- than lemmas proved later. This is a performance optimization.\n      build_list_expr_for_apply (m.reverse ++ t))\n  <|> return ((i_to_expr_for_apply h) :: tail)\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\nUnlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies\na lemma from the list until it can't.\n -/\nmeta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit :=\ndo l \u2190 lock_tactic_state $ build_list_expr_for_apply hs,\n   iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l)\n\n/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local\ncontext, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.\nFails if there is nothing named `h` in the local context. -/\nmeta def replace (h : name) (p : pexpr) : tactic unit :=\ndo h' \u2190 get_local h,\n   p \u2190 to_expr p,\n   note h none p,\n   clear h'\n\n/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``\nor `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an\n`iff`, returns an expression with the `iff` converted to either the forwards or backwards\nimplication, as requested. -/\nmeta def mk_iff_mp_app (iffmp : name) : expr \u2192 (nat \u2192 expr) \u2192 option expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := some $ @expr.const tt iffmp [] a b (f 0)\n| _ f := none\n\n/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., A \u2192 B`. -/\nmeta def iff_mp_core (e ty: expr) : option expr :=\nmk_iff_mp_app `iff.mp ty (\u03bb_, e)\n\n/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., B \u2192 A`. -/\nmeta def iff_mpr_core (e ty: expr) : option expr :=\nmk_iff_mp_app `iff.mpr ty (\u03bb_, e)\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the forward implication. -/\nmeta def iff_mp (e : expr) : tactic expr :=\ndo t \u2190 infer_type e,\n   iff_mp_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the reverse implication. -/\nmeta def iff_mpr (e : expr) : tactic expr :=\ndo t \u2190 infer_type e,\n   iff_mpr_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/--\nAttempts to apply `e`, and if that fails, if `e` is an `iff`,\ntry applying both directions separately.\n-/\nmeta def apply_iff (e : expr) : tactic (list (name \u00d7 expr)) :=\nlet ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in\nap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)\n\n/--\nConfiguration options for `apply_any`:\n* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.\n* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.\n* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.\n-/\nmeta structure apply_any_opt extends apply_cfg :=\n(use_symmetry : bool := tt)\n(use_exfalso : bool := tt)\n\n/--\nThis is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,\nand evaluates these as thunks before trying to apply them.\n\nWe need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.\n-/\nmeta def apply_any_thunk\n  (lemmas : list (tactic expr))\n  (opt : apply_any_opt := {})\n  (tac : tactic unit := skip)\n  (on_success : expr \u2192 tactic unit := (\u03bb _, skip))\n  (on_failure : tactic unit := skip) : tactic unit :=\ndo\n  let modes := [skip]\n    ++ (if opt.use_symmetry then [symmetry] else [])\n    ++ (if opt.use_exfalso then [exfalso] else []),\n  modes.any_of (\u03bb m, do m,\n    lemmas.any_of (\u03bb H, H >>= (\u03bb e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>\n  (on_failure >> fail \"apply_any tactic failed; no lemma could be applied\")\n\n/--\n`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.\n\n`apply_any lemmas opt` allows control over how lemmas are applied.\n`opt` has fields:\n* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)\n* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)\n* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).\n\n`apply_any lemmas tac` calls the tactic `tac` after a successful application.\nDefaults to `skip`. This is used, for example, by `solve_by_elim` to arrange\nrecursive invocations of `apply_any`.\n-/\nmeta def apply_any\n  (lemmas : list expr)\n  (opt : apply_any_opt := {})\n  (tac : tactic unit := skip) : tactic unit :=\napply_any_thunk (lemmas.map pure) opt tac\n\n/-- Try to apply a hypothesis from the local context to the goal. -/\nmeta def apply_assumption : tactic unit :=\nlocal_context >>= apply_any\n\n/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails\nif this is not a definitional equality.\n\n`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`\nby reverting `h`, changing the goal, and reintroducing hypotheses. -/\nmeta def change_core (e : expr) : option expr \u2192 tactic unit\n| none     := tactic.change e\n| (some h) :=\n  do num_reverted : \u2115 \u2190 revert h,\n     expr.pi n bi d b \u2190 target,\n     tactic.change $ expr.pi n bi e b,\n     intron num_reverted\n\n/--\n`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,\nassuming `olde` and `newe` are defeq when elaborated.\n-/\nmeta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=\ndo h \u2190 get_local hyp,\n   tp \u2190 infer_type h,\n   olde \u2190 to_expr olde, newe \u2190 to_expr newe,\n   let repl_tp := tp.replace (\u03bb a n, if a = olde then some newe else none),\n   when (repl_tp \u2260 tp) $ change_core repl_tp (some h)\n\n/-- Returns a list of all metavariables in the current partial proof. This can differ from\nthe list of goals, since the goals can be manually edited. -/\nmeta def metavariables : tactic (list expr) :=\nexpr.list_meta_vars <$> result\n\n/--\n`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,\nand fail otherwise.\n-/\nmeta def sorry_if_contains_sorry : tactic unit :=\ndo\n  g \u2190 target,\n  guard g.contains_sorry <|> fail \"goal does not contain `sorry`\",\n  tactic.admit\n\n/-- Fail if the target contains a metavariable. -/\nmeta def no_mvars_in_target : tactic unit :=\nexpr.has_meta_var <$> target >>= guardb \u2218 bnot\n\n/-- Succeeds only if the current goal is a proposition. -/\nmeta def propositional_goal : tactic unit :=\ndo g :: _ \u2190 get_goals,\n   is_proof g >>= guardb\n\n/-- Succeeds only if we can construct an instance showing the\n  current goal is a subsingleton type. -/\nmeta def subsingleton_goal : tactic unit :=\ndo g :: _ \u2190 get_goals,\n   ty \u2190 infer_type g >>= instantiate_mvars,\n   to_expr ``(subsingleton %%ty) >>= mk_instance >> skip\n\n/--\nSucceeds only if the current goal is \"terminal\",\nin the sense that no other goals depend on it\n(except possibly through shared metavariables; see `independent_goal`).\n-/\nmeta def terminal_goal : tactic unit :=\npropositional_goal <|> subsingleton_goal <|>\ndo g\u2080 :: _ \u2190 get_goals,\n   mvars \u2190 (\u03bb L, list.erase L g\u2080) <$> metavariables,\n   mvars.mmap' $ \u03bb g, do\n     t \u2190 infer_type g >>= instantiate_mvars,\n     d \u2190 kdepends_on t g\u2080,\n     monad.whenb d $\n       pp t >>= \u03bb s, fail (\"The current goal is not terminal: \" ++ s.to_string ++ \" depends on it.\")\n\n/--\nSucceeds only if the current goal is \"independent\", in the sense\nthat no other goals depend on it, even through shared meta-variables.\n-/\nmeta def independent_goal : tactic unit :=\nno_mvars_in_target >> terminal_goal\n\n/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,\nit only unfolds reducible definitions, so it sometimes fails faster. -/\nmeta def triv' : tactic unit := do c \u2190 mk_const `trivial, exact c reducible\n\nvariable {\u03b1 : Type}\n\n/-- Apply a tactic as many times as possible, collecting the results in a list.\nFail if the tactic does not succeed at least once. -/\nmeta def iterate1 (t : tactic \u03b1) : tactic (list \u03b1) :=\ndo r \u2190 decorate_ex \"iterate1 failed: tactic did not succeed\" t,\n   L \u2190 iterate t,\n   return (r :: L)\n\n/-- Introduces one or more variables and returns the new local constants.\nFails if `intro` cannot be applied. -/\nmeta def intros1 : tactic (list expr) :=\niterate1 intro1\n\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nmeta def under_binders {\u03b1 : Type} (t : tactic \u03b1) : tactic \u03b1 :=\ndo\n  v \u2190 intros,\n  r \u2190 t,\n  revert_lst v,\n  return r\n\nnamespace interactive\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nmeta def under_binders (i : itactic) : itactic := tactic.under_binders i\nend interactive\n\n/-- `successes` invokes each tactic in turn, returning the list of successful results. -/\nmeta def successes (tactics : list (tactic \u03b1)) : tactic (list \u03b1) :=\nlist.filter_map id <$> monad.sequence (tactics.map (\u03bb t, try_core t))\n\n/--\nTry all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results,\nand reverting to the original `tactic_state`.\n-/\n-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.\nmeta def try_all {\u03b1 : Type} (tactics : list (tactic \u03b1)) : tactic (list \u03b1) :=\n\u03bb s, result.success\n(tactics.map $\n\u03bb t : tactic \u03b1,\n  match t s with\n  | result.success a s' := [a]\n  | _ := []\n  end).join s\n\n/--\nTry all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results sorted by\nthe value produced by a subsequent execution of the `sort_by` tactic,\nand reverting to the original `tactic_state`.\n-/\nmeta def try_all_sorted {\u03b1 : Type} (tactics : list (tactic \u03b1)) (sort_by : tactic \u2115 := num_goals) :\n  tactic (list (\u03b1 \u00d7 \u2115)) :=\n\u03bb s, result.success\n((tactics.map $\n\u03bb t : tactic \u03b1,\n  match (do a \u2190 t, n \u2190 sort_by, return (a, n)) s with\n  | result.success a s' := [a]\n  | _ := []\n  end).join.qsort (\u03bb p q : \u03b1 \u00d7 \u2115, p.2 < q.2)) s\n\n/-- Return target after instantiating metavars and whnf. -/\nprivate meta def target' : tactic expr :=\ntarget >>= instantiate_mvars >>= whnf\n\n/--\nJust like `split`, `fsplit` applies the constructor when the type of the target is\nan inductive data type with one constructor.\nHowever it does not reorder goals or invoke `auto_param` tactics.\n-/\n-- FIXME check if we can remove `auto_param := ff`\nmeta def fsplit : tactic unit :=\ndo [c] \u2190 target' >>= get_constructors_for |\n     fail \"fsplit tactic failed, target is not an inductive datatype with only one constructor\",\n   mk_const c >>= \u03bb e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip\n\nrun_cmd add_interactive [`fsplit]\n\nadd_tactic_doc\n{ name                     := \"fsplit\",\n  category                 := doc_category.tactic,\n  decl_names               := [`tactic.interactive.fsplit],\n  tags                     := [\"logic\", \"goal management\"] }\n\n/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`\nsucceeds, clears the old hypothesis. -/\nmeta def injections_and_clear : tactic unit :=\ndo l \u2190 local_context,\n   results \u2190 successes $ l.map $ \u03bb e, injection e >> clear e,\n   when (results.empty) (fail \"could not use `injection` then `clear` on any hypothesis\")\n\nrun_cmd add_interactive [`injections_and_clear]\n\nadd_tactic_doc\n{ name                     := \"injections_and_clear\",\n  category                 := doc_category.tactic,\n  decl_names               := [`tactic.interactive.injections_and_clear],\n  tags                     := [\"context management\"] }\n\n/-- Calls `cases` on every local hypothesis, succeeding if\nit succeeds on at least one hypothesis. -/\nmeta def case_bash : tactic unit :=\ndo l \u2190 local_context,\n   r \u2190 successes (l.reverse.map (\u03bb h, cases h >> skip)),\n   when (r.empty) failed\n\n/--\n`note_anon t v`, given a proof `v : t`,\nadds `h : t` to the current context, where the name `h` is fresh.\n\n`note_anon none v` will infer the type `t` from `v`.\n-/\n-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.\nmeta def note_anon (t : option expr) (v : expr) : tactic expr :=\ndo h \u2190 get_unused_name `h none,\n   note h t v\n\n/-- `find_local t` returns a local constant with type t, or fails if none exists. -/\nmeta def find_local (t : pexpr) : tactic expr :=\ndo t' \u2190 to_expr t,\n   (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>\n     fail format!\"No hypothesis found of the form: {t'}\"\n\n/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values\nof the previous local constants. `l` is a list of local constants and their values. -/\nmeta def dependent_pose_core (l : list (expr \u00d7 expr)) : tactic unit := do\n  let lc := l.map prod.fst,\n  let lm := l.map (\u03bb\u27e8l, v\u27e9, (l.local_uniq_name, v)),\n  old::other_goals \u2190 get_goals,\n  t \u2190 infer_type old,\n  new_goal \u2190 mk_meta_var (t.pis lc),\n  set_goals (old :: new_goal :: other_goals),\n  exact ((new_goal.mk_app lc).instantiate_locals lm),\n  return ()\n\n/--\nInstantiates metavariables that appear in the current goal.\n-/\nmeta def instantiate_mvars_in_target : tactic unit :=\ntarget >>= instantiate_mvars >>= change\n\n/--\nInstantiates metavariables in all goals.\n-/\nmeta def instantiate_mvars_in_goals : tactic unit :=\nall_goals' $ instantiate_mvars_in_target\n\n/-- Protect the declaration `n` -/\nmeta def mk_protected (n : name) : tactic unit :=\ndo env \u2190 get_env, set_env (env.mk_protected n)\n\nend tactic\n\nnamespace lean.parser\nopen tactic interaction_monad\n\n/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the\ncurrent line. -/\nmeta def emit_command_here (str : string) : lean.parser string :=\ndo (_, left) \u2190 with_input command_like str,\n   return left\n\n/-- Inner recursion for `emit_code_here`. -/\nmeta def emit_code_here_aux : string \u2192 \u2115 \u2192 lean.parser unit\n| str slen := do\n  left \u2190 emit_command_here str,\n  let llen := left.length,\n  when (llen < slen \u2227 llen \u2260 0) (emit_code_here_aux left llen)\n\n/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in\nsource code. -/\nmeta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length\n\n/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the\ntop level, giving access to operations like `emit_code_here`. -/\n@[user_command]\nmeta def run_parser_cmd (_ : interactive.parse $ tk \"run_parser\") : lean.parser unit :=\ndo e \u2190 lean.parser.pexpr 0,\n  p \u2190 eval_pexpr (lean.parser unit) e,\n  p\n\nadd_tactic_doc\n{ name       := \"run_parser\",\n  category   := doc_category.cmd,\n  decl_names := [``run_parser_cmd],\n  tags       := [\"parsing\"] }\n\n/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).\n\nThis function deserves a C++ implementation in core lean, and will fail if it is not called from\nthe body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/\nmeta def get_current_namespace : lean.parser name :=\ndo n \u2190 tactic.mk_user_fresh_name,\n   emit_code_here $ sformat!\"def {n} := ()\",\n   nfull \u2190 tactic.resolve_constant n,\n   return $ nfull.get_nth_prefix n.components.length\n\n/-- `get_variables` returns a list of existing variable names, along with their types and binder\ninfo. -/\nmeta def get_variables : lean.parser (list (name \u00d7 binder_info \u00d7 expr)) :=\nlist.map expr.get_local_const_kind <$> list_available_include_vars\n\n/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been\n\"included\" by an `include v` statement and are not (yet) `omit`ed. -/\nmeta def get_included_variables : lean.parser (list (name \u00d7 binder_info \u00d7 expr)) :=\ndo ns \u2190 list_include_var_names,\n   list.filter (\u03bb v, v.1 \u2208 ns) <$> get_variables\n\n/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local\nvariables referenced in `es : list pexpr`, and those variables which have been `include`ed in the\nlocal context---precisely those variables which would be ambiently accessible if we were in a\ntactic-mode block where the goals had types `es.mmap to_expr`, for example.\n\nReturns a new `ts : tactic_state` with these local variables added, and\n`mappings : list (expr \u00d7 expr)`, for which pairs `(var, hyp)` correspond to an existing variable\n`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/\nmeta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)\n  : lean.parser (tactic_state \u00d7 list (expr \u00d7 expr)) :=\ndo /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the\n      declared variables to a fake `tactic_state`, and perform the resolution. At the end,\n      `to_expr e` has done the work of determining which variables were actually referenced, which\n      we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for\n      `pexpr`s). -/\n   vars \u2190 list_available_include_vars,\n   fake_es \u2190 lean.parser.of_tactic $ lock_tactic_state $ do\n   { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard\n        them on this first pass. (We return the mappings generated by our second invocation of this\n        function below.) -/\n     add_local_consts_as_local_hyps vars,\n     es.mmap to_expr },\n\n   /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were\n      referenced in `e` when it was resolved to `fake_e`.\n\n      It is important that we include variables of the kind a) because we want `simp` to have access\n      to declared local instances, and it is important that we only restrict to variables of kind a)\n      and b) together since we do not to recognise a hypothesis which is posited as a `variable`\n      in the environment but not referenced in the `pexpr` we were passed.\n\n      One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want\n      simp to use arbitrary hypotheses which were declared as `variables` in the local environment\n      but not referenced in the expression to simplify (as one would be expect generally in tactic\n      mode). -/\n   included_vars \u2190 list_include_var_names,\n   let referenced_vars := list.join $ fake_es.map $ \u03bb e, e.list_local_consts.map expr.local_pp_name,\n\n   /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the\n      `pexpr` list which we were passed.)  -/\n   let directly_included_vars := vars.filter $ \u03bb var,\n     (var.local_pp_name \u2208 included_vars) \u2228 (var.local_pp_name \u2208 referenced_vars),\n\n   /- Inflate the list `directly_included_vars` to include those variables which are \"implicitly\n      included\" by virtue of reference to one or multiple others. For example, given\n      `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass\n      instance `prime n` should be included, but `ih : even n` should not. -/\n   let all_implicitly_included_vars :=\n     expr.all_implicitly_included_variables vars directly_included_vars,\n\n   /- Capture a tactic state where both of these kinds of variables have been added as local\n      hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/\n   lean.parser.of_tactic $ do\n    { mappings \u2190 add_local_consts_as_local_hyps all_implicitly_included_vars,\n      ts \u2190 get_state,\n      return (ts, mappings) }\n\nend lean.parser\n\nnamespace tactic\n\nvariables {\u03b1 : Type}\n\n/--\nHole command used to fill in a structure's field when specifying an instance.\n\nIn the following:\n\n```lean\ninstance : monad id :=\n{! !}\n```\n\ninvoking the hole command \"Instance Stub\" (\"Generate a skeleton for the structure under\nconstruction.\") produces:\n\n```lean\ninstance : monad id :=\n{ map := _,\n  map_const := _,\n  pure := _,\n  seq := _,\n  seq_left := _,\n  seq_right := _,\n  bind := _ }\n```\n-/\n@[hole_command] meta def instance_stub : hole_command :=\n{ name := \"Instance Stub\",\n  descr := \"Generate a skeleton for the structure under construction.\",\n  action := \u03bb _,\n  do tgt \u2190 target >>= whnf,\n     let cl := tgt.get_app_fn.const_name,\n     env \u2190 get_env,\n     fs \u2190 expanded_field_list cl,\n     let fs := fs.map prod.snd,\n     let fs := format.intercalate (\",\\n  \" : format) $ fs.map (\u03bb fn, format!\"{fn} := _\"),\n     let out := format.to_string format!\"{{ {fs} }\",\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"instance_stub\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.instance_stub],\n  tags                     := [\"instances\"] }\n\n/-- Like `resolve_name` except when the list of goals is\nempty. In that situation `resolve_name` fails whereas\n`resolve_name'` simply proceeds on a dummy goal -/\nmeta def resolve_name' (n : name) : tactic pexpr :=\ndo [] \u2190 get_goals | resolve_name n,\n   g \u2190 mk_mvar,\n   set_goals [g],\n   resolve_name n <* set_goals []\n\nprivate meta def strip_prefix' (n : name) : list string \u2192 name \u2192 tactic name\n| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous\n| s (name.mk_string a p) :=\n  do let n' := s.foldl (flip name.mk_string) name.anonymous,\n     do { n'' \u2190 tactic.resolve_constant n',\n          if n'' = n\n            then pure n'\n            else strip_prefix' (a :: s) p }\n     <|> strip_prefix' (a :: s) p\n| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n\n\n/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/\nmeta def strip_prefix : name \u2192 tactic name\n| n@(name.mk_string a a_1) :=\n  if (`_private).is_prefix_of n\n    then let n' := n.update_prefix name.anonymous in\n            n' <$ resolve_name' n' <|> pure n\n    else strip_prefix' n [a] a_1\n| n := pure n\n\n/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/\nmeta def mk_patterns (t : expr) : tactic (list format) :=\ndo let cl := t.get_app_fn.const_name,\n   env \u2190 get_env,\n   let fs := env.constructors_of cl,\n   fs.mmap $ \u03bb f,\n     do { (vs,_) \u2190 mk_const f >>= infer_type >>= open_pis,\n          let vs := vs.filter (\u03bb v, v.is_default_local),\n          vs \u2190 vs.mmap (\u03bb v,\n            do v' \u2190 get_unused_name v.local_pp_name,\n               pose v' none `(()),\n               pure v' ),\n          vs.mmap' $ \u03bb v, get_local v >>= clear,\n          let args := list.intersperse (\" \" : format) $ vs.map to_fmt,\n          f \u2190 strip_prefix f,\n          if args.empty\n            then pure $ format!\"| {f} := _\\n\"\n            else pure format!\"| ({f} {format.join args}) := _\\n\" }\n\n/--\nHole command used to generate a `match` expression.\n\nIn the following:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\n{! e !}\n```\n\ninvoking hole command \"Match Stub\" (\"Generate a list of equations for a `match` expression\")\nproduces:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\nmatch e with\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\nend\n```\n-/\n@[hole_command] meta def match_stub : hole_command :=\n{ name := \"Match Stub\",\n  descr := \"Generate a list of equations for a `match` expression.\",\n  action := \u03bb es,\n  do [e] \u2190 pure es | fail \"expecting one expression\",\n     e \u2190 to_expr e,\n     t \u2190 infer_type e >>= whnf,\n     fs \u2190 mk_patterns t,\n     e \u2190 pp e,\n     let out := format.to_string format!\"match {e} with\\n{format.join fs}end\\n\",\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"Match Stub\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.match_stub],\n  tags                     := [\"pattern matching\"] }\n\n/--\nInvoking hole command \"Equations Stub\" (\"Generate a list of equations for a recursive definition\")\nin the following:\n\n```lean\nmeta def foo : {! expr \u2192 tactic unit !} -- `:=` is omitted\n```\n\nproduces:\n\n```lean\nmeta def foo : expr \u2192 tactic unit\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\nA similar result can be obtained by invoking \"Equations Stub\" on the following:\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- do not forget to write `:=`!!\n{! !}\n```\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- don't forget to erase `:=`!!\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\n-/\n@[hole_command] meta def eqn_stub : hole_command :=\n{ name := \"Equations Stub\",\n  descr := \"Generate a list of equations for a recursive definition.\",\n  action := \u03bb es,\n  do t \u2190 match es with\n         | [t] := to_expr t\n         | [] := target\n         | _ := fail \"expecting one type\"\n         end,\n     e \u2190 whnf t,\n     (v :: _,_) \u2190 open_pis e | fail \"expecting a Pi-type\",\n     t' \u2190 infer_type v,\n     fs \u2190 mk_patterns t',\n     t \u2190 pp t,\n     let out :=\n         if es.empty then\n           format.to_string format!\"-- do not forget to erase `:=`!!\\n{format.join fs}\"\n           else format.to_string format!\"{t}\\n{format.join fs}\",\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"Equations Stub\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.eqn_stub],\n  tags                     := [\"pattern matching\"] }\n\n/--\nThis command lists the constructors that can be used to satisfy the expected type.\n\nInvoking \"List Constructors\" (\"Show the list of constructors of the expected type\")\nin the following hole:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! !}\n```\n\nproduces:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! sum.inl, sum.inr !}\n```\n\nand will display:\n\n```lean\nsum.inl : \u2124 \u2192 \u2124 \u2295 \u2115\n\nsum.inr : \u2115 \u2192 \u2124 \u2295 \u2115\n```\n\n-/\n@[hole_command] meta def list_constructors_hole : hole_command :=\n{ name := \"List Constructors\",\n  descr := \"Show the list of constructors of the expected type.\",\n  action := \u03bb es,\n  do t \u2190 target >>= whnf,\n     (_,t) \u2190 open_pis t,\n     let cl := t.get_app_fn.const_name,\n     let args := t.get_app_args,\n     env \u2190 get_env,\n     let cs := env.constructors_of cl,\n     ts \u2190 cs.mmap $ \u03bb c,\n       do { e \u2190 mk_const c,\n            t \u2190 infer_type (e.mk_app args) >>= pp,\n            c \u2190 strip_prefix c,\n            pure format!\"\\n{c} : {t}\\n\" },\n     fs \u2190 format.intercalate \", \" <$> cs.mmap (strip_prefix >=> pure \u2218 to_fmt),\n     let out := format.to_string format!\"{{! {fs} !}\",\n     trace (format.join ts).to_string,\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"List Constructors\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.list_constructors_hole],\n  tags                     := [\"goal information\"] }\n\n/-- Makes the declaration `classical.prop_decidable` available to type class inference.\nThis asserts that all propositions are decidable, but does not have computational content. -/\nmeta def classical : tactic unit :=\ndo h \u2190 get_unused_name `_inst,\n   mk_const `classical.prop_decidable >>= note h none,\n   reset_instance_cache\n\nopen expr\n\n/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,\nreturns the expression `f \u2218 g \u2218 h`. -/\nmeta def mk_comp (v : expr) : expr \u2192 tactic expr\n| (app f e) :=\n  if e = v then pure f\n  else do\n    guard (\u00ac v.occurs f) <|> fail \"bad guard\",\n    e' \u2190 mk_comp e >>= instantiate_mvars,\n    f \u2190 instantiate_mvars f,\n    mk_mapp ``function.comp [none,none,none,f,e']\n| e :=\n  do guard (e = v),\n     t \u2190 infer_type e,\n     mk_mapp ``id [t]\n\n/-- Given two expressions `e\u2080` and `e\u2081`, return the expression `` `(%%e\u2080 \u2194 %%e\u2081)``. -/\nmeta def mk_iff (e\u2080 : expr) (e\u2081 : expr) : expr := `(%%e\u2080 \u2194 %%e\u2081)\n\n/--\nFrom a lemma of the shape `\u2200 x, f (g x) = h x`\nderive an auxiliary lemma of the form `f \u2218 g = h`\nfor reasoning about higher-order functions.\n-/\nmeta def mk_higher_order_type : expr \u2192 tactic expr\n| (pi n bi d b@(pi _ _ _ _)) :=\n  do v \u2190 mk_local_def n d,\n     let b' := (b.instantiate_var v),\n     (pi n bi d \u2218 flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'\n| (pi n bi d b) :=\n  do v \u2190 mk_local_def n d,\n     let b' := (b.instantiate_var v),\n     (l,r) \u2190 match_eq b' <|> fail format!\"not an equality {b'}\",\n     l' \u2190 mk_comp v l,\n     r' \u2190 mk_comp v r,\n     mk_app ``eq [l',r']\n | e := failed\n\nopen lean.parser interactive.types\n\n/-- A user attribute that applies to lemmas of the shape `\u2200 x, f (g x) = h x`.\nIt derives an auxiliary lemma of the form `f \u2218 g = h` for reasoning about higher-order functions.\n-/\n@[user_attribute]\nmeta def higher_order_attr : user_attribute unit (option name) :=\n{ name := `higher_order,\n  parser := optional ident,\n  descr :=\n\"From a lemma of the shape `\u2200 x, f (g x) = h x` derive an auxiliary lemma of the\nform `f \u2218 g = h` for reasoning about higher-order functions.\",\n  after_set := some $ \u03bb lmm _ _,\n    do env  \u2190 get_env,\n       decl \u2190 env.get lmm,\n       let num := decl.univ_params.length,\n       let lvls := (list.iota num).map (`l).append_after,\n       let l : expr := expr.const lmm $ lvls.map level.param,\n       t \u2190 infer_type l >>= instantiate_mvars,\n       t' \u2190 mk_higher_order_type t,\n       (_,pr) \u2190 solve_aux t' $ do\n       { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },\n       pr \u2190 instantiate_mvars pr,\n       lmm' \u2190 higher_order_attr.get_param lmm,\n       lmm' \u2190 (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,\n       add_decl $ declaration.thm lmm' lvls t' (pure pr),\n       copy_attribute `simp lmm lmm',\n       copy_attribute `functor_norm lmm lmm' }\n\nadd_tactic_doc\n{ name                     := \"higher_order\",\n  category                 := doc_category.attr,\n  decl_names               := [`tactic.higher_order_attr],\n  tags                     := [\"lemma derivation\"] }\n\nattribute [higher_order map_comp_pure] map_pure\n\n/--\nCopies a definition into the `tactic.interactive` namespace to make it usable\nin proof scripts. It allows one to write\n\n```lean\n@[interactive]\nmeta def my_tactic := ...\n```\n\ninstead of\n\n```lean\nmeta def my_tactic := ...\n\nrun_cmd add_interactive [``my_tactic]\n```\n-/\n@[user_attribute]\nmeta def interactive_attr : user_attribute :=\n{ name := `interactive,\n  descr :=\n\"Put a definition in the `tactic.interactive` namespace to make it usable\nin proof scripts.\",\n  after_set := some $ \u03bb tac _ _, add_interactive [tac] }\n\nadd_tactic_doc\n{ name                     := \"interactive\",\n  category                 := doc_category.attr,\n  decl_names               := [``tactic.interactive_attr],\n  tags                     := [\"environment\"] }\n\n/--\nUse `refine` to partially discharge the goal,\nor call `fconstructor` and try again.\n-/\nprivate meta def use_aux (h : pexpr) : tactic unit :=\n(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)\n\n/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations\nat the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to\nthe expected type.\n\n```lean\nexample : \u2203 x : \u2124, x = x :=\nby tactic.use ``(42)\n```\n\nSee the doc string for `tactic.interactive.use` for more information.\n -/\nprotected meta def use (l : list pexpr) : tactic unit :=\nfocus1 $ seq' (l.mmap' $ \u03bb h, use_aux h <|> fail format!\"failed to instantiate goal with {h}\")\n              instantiate_mvars_in_target\n\n/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the\nlocal context. -/\nmeta def clear_aux_decl_aux : list expr \u2192 tactic unit\n| []     := skip\n| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l\n\n/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/\nmeta def clear_aux_decl : tactic unit :=\nlocal_context >>= clear_aux_decl_aux\n\n/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)\nfinds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/\nmeta def apply_at_aux (arg t : expr) : list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr)\n| vs e (pi n bi d b) :=\n  do { v \u2190 mk_meta_var d,\n       apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>\n  (e arg, vs) <$ unify d t\n| vs e _ := failed\n\n/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/\nmeta def apply_at (e h : expr) : tactic unit :=\ndo ht \u2190 infer_type h,\n   et \u2190 infer_type e,\n   (h', gs') \u2190 apply_at_aux h ht [] e et,\n   note h.local_pp_name none h',\n   clear h,\n   gs' \u2190 gs'.mfilter is_assigned,\n   (g :: gs) \u2190 get_goals,\n   set_goals (g :: gs' ++ gs)\n\n/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/\nmeta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=\ndo tgt   \u2190 infer_type h,\n   env   \u2190 get_env,\n   let r := get_app_fn tgt,\n   match env.symm_for (const_name r) with\n   | (some symm) := do s \u2190 mk_const symm,\n                       apply_at s h\n   | none        := fail\n      \"symmetry tactic failed, target is not a relation application with the expected property.\"\n   end\n\n/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing\ninteractive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.\nIt does *not* use the `namespace` command, so it will typically be used after\n`namespace tactic.interactive`.\n-/\n@[user_command]\nmeta def setup_tactic_parser_cmd (_ : interactive.parse $ tk \"setup_tactic_parser\") :\n  lean.parser unit :=\nemit_code_here \"\nopen _root_.lean\nopen _root_.lean.parser\nopen _root_.interactive _root_.interactive.types\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many .\n\"\n\n/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if\n`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/\nmeta def finally {\u03b2} (tac : tactic \u03b1) (finalizer : tactic \u03b2) : tactic \u03b1 :=\n\u03bb s, match tac s with\n     | (result.success r s') := (finalizer >> pure r) s'\n     | (result.exception msg p s') := (finalizer >> result.exception msg p) s'\n     end\n\n/--\n`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.\n-/\nmeta def on_exception {\u03b2} (handler : tactic \u03b2) (tac : tactic \u03b1) : tactic \u03b1 | s :=\nmatch tac s with\n| result.exception msg p s' := (handler *> result.exception msg p) s'\n| ok := ok\nend\n\n/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/\nmeta def decorate_error (add_msg : string) (tac : tactic \u03b1) : tactic \u03b1 | s :=\nmatch tac s with\n| result.exception msg p s :=\n  let msg (_ : unit) : format := match msg with\n    | some msg := add_msg ++ format.line ++ msg ()\n    | none := add_msg\n    end in\n  result.exception msg p s\n| ok := ok\nend\n\n/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,\n  returns the error message. -/\nmeta def retrieve_or_report_error {\u03b1 : Type u} (t : tactic \u03b1) : tactic (\u03b1 \u2295 string) :=\n\u03bb s, match t s with\n| (interaction_monad.result.success a s') := result.success (sum.inl a) s\n| (interaction_monad.result.exception msg' _ s') :=\n  result.success (sum.inr (msg'.iget ()).to_string) s\nend\n\n/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/\nmeta def try_or_report_error {\u03b1 : Type u} (t : tactic \u03b1) : tactic (\u03b1 \u2295 string) :=\n\u03bb s, match t s with\n| (interaction_monad.result.success a s') := result.success (sum.inl a) s'\n| (interaction_monad.result.exception msg' _ s') :=\n  result.success (sum.inr (msg'.iget ()).to_string) s\nend\n\n/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.\n-/\nmeta def succeeds_or_fails_with_msg {\u03b1 : Type} (t : tactic \u03b1) (p : string \u2192 bool) : tactic unit :=\ndo x \u2190 retrieve_or_report_error t,\nmatch x with\n| (sum.inl _) := skip\n| (sum.inr msg) := if p msg then skip else fail msg\nend\n\nadd_tactic_doc\n{ name                     := \"setup_tactic_parser\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.setup_tactic_parser_cmd],\n  tags                     := [\"parsing\", \"notation\"] }\n\n/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message\nof `t`. -/\nmeta def trace_error (msg : string) (t : tactic \u03b1) : tactic \u03b1\n| s := match t s with\n       | (result.success r s') := result.success r s'\n       | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception\n            (some msg') p) s'\n       | (result.exception none p s') := result.exception none p s'\n       end\n\n/--\n``trace_if_enabled `n msg`` traces the message `msg`\nonly if tracing is enabled for the name `n`.\n\nCreate new names registered for tracing with `declare_trace n`.\nThen use `set_option trace.n true/false` to enable or disable tracing for `n`.\n-/\nmeta def trace_if_enabled\n  (n : name) {\u03b1 : Type u} [has_to_tactic_format \u03b1] (msg : \u03b1) : tactic unit :=\nwhen_tracing n (trace msg)\n\n/--\n``trace_state_if_enabled `n msg`` prints the tactic state,\npreceded by the optional string `msg`,\nonly if tracing is enabled for the name `n`.\n-/\nmeta def trace_state_if_enabled\n  (n : name) (msg : string := \"\") : tactic unit :=\nwhen_tracing n ((if msg = \"\" then skip else trace msg) >> trace_state)\n\n/--\nThis combinator is for testing purposes. It succeeds if `t` fails with message `msg`,\nand fails otherwise.\n-/\nmeta def success_if_fail_with_msg {\u03b1 : Type u} (t : tactic \u03b1) (msg : string) : tactic unit :=\n\u03bb s, match t s with\n| (interaction_monad.result.exception msg' _ s') :=\n  let expected_msg := (msg'.iget ()).to_string in\n  if msg = expected_msg then result.success () s\n  else mk_exception format!\"failure messages didn't match. Expected:\\n{expected_msg}\" none s\n| (interaction_monad.result.success a s) :=\n   mk_exception \"success_if_fail_with_msg combinator failed, given tactic succeeded\" none s\nend\n\n/--\nConstruct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.\n-/\nmeta def tactic_statement (g : expr) : tactic string :=\ndo g \u2190 instantiate_mvars g,\n   g \u2190 head_beta g,\n   r \u2190 pp (replace_mvars g),\n   if g.has_meta_var\n   then return (sformat!\"Try this: refine {r}\")\n   else return (sformat!\"Try this: exact {r}\")\n\n/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the\ninitial goals and returns the goals `tac` ended on. -/\nmeta def with_local_goals {\u03b1} (gs : list expr) (tac : tactic \u03b1) : tactic (\u03b1 \u00d7 list expr) :=\ndo gs' \u2190 get_goals,\n   set_goals gs,\n   finally (prod.mk <$> tac <*> get_goals) (set_goals gs')\n\n/-- like `with_local_goals` but discards the resulting goals -/\nmeta def with_local_goals' {\u03b1} (gs : list expr) (tac : tactic \u03b1) : tactic \u03b1 :=\nprod.fst <$> with_local_goals gs tac\n\n/-- Representation of a proof goal that lends itself to comparison. The\nfollowing goal:\n\n```lean\nl\u2080 : T,\nl\u2081 : T\n\u22a2 \u2200 v : T, foo\n```\n\nis represented as\n\n```\n(2, \u2200 l\u2080 l\u2081 v : T, foo)\n```\n\nThe number 2 indicates that first the two bound variables of the\n`\u2200` are actually local constant. Comparing two such goals with `=`\nrather than `=\u2090` or `is_def_eq` tells us that proof script should\nnot see the difference between the two.\n -/\nmeta def packaged_goal := \u2115 \u00d7 expr\n\n/-- proof state made of multiple `goal` meant for comparing\nthe result of running different tactics -/\nmeta def proof_state := list packaged_goal\n\nmeta instance goal.inhabited : inhabited packaged_goal := \u27e8(0,var 0)\u27e9\nmeta instance proof_state.inhabited : inhabited proof_state :=\n(infer_instance : inhabited (list packaged_goal))\n\n/-- create a `packaged_goal` corresponding to the current goal -/\nmeta def get_packaged_goal : tactic packaged_goal := do\nls \u2190 local_context,\ntgt \u2190 target >>= instantiate_mvars,\ntgt \u2190 pis ls tgt,\npure (ls.length, tgt)\n\n/-- `goal_of_mvar g`, with `g` a meta variable, creates a\n`packaged_goal` corresponding to `g` interpretted as a proof goal -/\nmeta def goal_of_mvar (g : expr) : tactic packaged_goal :=\nwith_local_goals' [g] get_packaged_goal\n\n/-- `get_proof_state` lists the user visible goal for each goal\nof the current state and for each goal, abstracts all of the\nmeta variables of the other gaols.\n\nThis produces a list of goals in the form of `\u2115 \u00d7 expr` where\nthe `expr` encodes the following proof state:\n\n```lean\n2 goals\nl\u2081 : t\u2081,\nl\u2082 : t\u2082,\nl\u2083 : t\u2083\n\u22a2 tgt\u2081\n\n\u22a2 tgt\u2082\n```\n\nas\n\n```lean\n[ (3, \u2200 (mv : tgt\u2081) (mv : tgt\u2082) (l\u2081 : t\u2081) (l\u2082 : t\u2082) (l\u2083 : t\u2083), tgt\u2081),\n  (0, \u2200 (mv : tgt\u2081) (mv : tgt\u2082), tgt\u2082) ]\n```\n\nwith 2 goals, the first 2 bound variables encode the meta variable\nof all the goals, the next 3 (in the first goal) and 0 (in the second goal)\nare the local constants.\n\nThis representation allows us to compare goals and proof states while\nignoring information like the unique name of local constants and\nthe equality or difference of meta variables that encode the same goal.\n-/\nmeta def get_proof_state : tactic proof_state :=\ndo gs \u2190 get_goals,\n   gs.mmap $ \u03bb g, do\n     \u27e8n,g\u27e9 \u2190 goal_of_mvar g,\n     g \u2190 gs.mfoldl (\u03bb g v, do\n       g \u2190 kabstract g v reducible ff,\n       pure $ pi `goal binder_info.default `(true) g ) g,\n     pure (n,g)\n\n/--\nRun `tac` in a disposable proof state and return the state.\nSee `proof_state`, `goal` and `get_proof_state`.\n-/\nmeta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=\ntry_core $ retrieve $ tac >> get_proof_state\n\nopen lean _root_.interactive\n\n/-- A type alias for `tactic format`, standing for \"pretty print format\". -/\nmeta def pformat := tactic format\n\n/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/\nmeta def pformat.mk (fmt : format) : pformat := pure fmt\n\n/-- an alias for `pp`. -/\nmeta def to_pfmt {\u03b1} [has_to_tactic_format \u03b1] (x : \u03b1) : pformat :=\npp x\n\nmeta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=\n\u27e8 id \u27e9\n\nmeta instance : has_append pformat :=\n\u27e8 \u03bb x y, (++) <$> x <*> y \u27e9\n\nmeta instance tactic.has_to_tactic_format [has_to_tactic_format \u03b1] :\n  has_to_tactic_format (tactic \u03b1) :=\n\u27e8 \u03bb x, x >>= to_pfmt \u27e9\n\nprivate meta def parse_pformat : string \u2192 list char \u2192 parser pexpr\n| acc []            := pure ``(to_pfmt %%(reflect acc))\n| acc ('\\n'::s)     :=\ndo f \u2190 parse_pformat \"\" s,\n   pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)\n| acc ('{'::'{'::s) := parse_pformat (acc ++ \"{\") s\n| acc ('{'::s) :=\ndo (e, s) \u2190 with_input (lean.parser.pexpr 0) s.as_string,\n   '}'::s \u2190 return s.to_list | fail \"'}' expected\",\n   f \u2190 parse_pformat \"\" s,\n   pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)\n| acc (c::s) := parse_pformat (acc.str c) s\n\n/-- See `format!` in `init/meta/interactive_base.lean`.\n\nThe main differences are that `pp` is called instead of `to_fmt` and that we can use\narguments of type `tactic \u03b1` in the quotations.\n\nNow, consider the following:\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace format!\"{e}\"  -- outputs `has_add.add.{0} nat nat.has_add\n                    -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`\ntrace pformat!\"{e}\" -- outputs `3 + 7`\n```\n\nThe difference is significant. And now, the following is expressible:\n\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace pformat!\"{e} : {infer_type e}\" -- outputs `3 + 7 : \u2115`\n```\n\nSee also: `trace!` and `fail!`\n-/\n@[user_notation]\nmeta def pformat_macro (_ : parse $ tk \"pformat!\") (s : string) : parser pexpr :=\ndo e \u2190 parse_pformat \"\" s.to_list,\n   return ``(%%e : pformat)\n\n/--\nThe combination of `pformat` and `fail`.\n-/\n@[user_notation]\nmeta def fail_macro (_ : parse $ tk \"fail!\") (s : string) : parser pexpr :=\ndo e \u2190 pformat_macro () s,\n   pure ``((%%e : pformat) >>= fail)\n\n/--\nThe combination of `pformat` and `trace`.\n-/\n@[user_notation]\nmeta def trace_macro (_ : parse $ tk \"trace!\") (s : string) : parser pexpr :=\ndo e \u2190 pformat_macro () s,\n   pure ``((%%e : pformat) >>= trace)\n\n/-- A hackish way to get the `src` directory of any project.\n  Requires as argument any declaration name `n` in that project, and `k`, the number of characters\n  in the path of the file where `n` is declared not part of the `src` directory.\n  Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`.\n  Note: does not work in the file where `n` is declared. -/\nmeta def get_project_dir (n : name) (k : \u2115) : tactic string :=\ndo e \u2190 get_env,\n  s \u2190 e.decl_olean n <|>\nfail!\"Did not find declaration {n}. This command does not work in the file where {n} is declared.\",\n  return $ s.popn_back k\n\n/-- A hackish way to get the `src` directory of mathlib. -/\nmeta def get_mathlib_dir : tactic string :=\nget_project_dir `mathlib_dir_locator 23\n\n/-- Checks whether a declaration with the given name is declared in mathlib.\nIf you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,\nsince it is expensive to execute `get_mathlib_dir` many times. -/\nmeta def is_in_mathlib (n : name) : tactic bool :=\ndo ml \u2190 get_mathlib_dir, e \u2190 get_env, return $ e.is_prefix_of_file ml n\n\n/--\nRuns a tactic by name.\nIf it is a `tactic string`, return whatever string it returns.\nIf it is a `tactic unit`, return the name.\n(This is mostly used in invoking \"self-reporting tactics\", e.g. by `tidy` and `hint`.)\n-/\nmeta def name_to_tactic (n : name) : tactic string :=\ndo d \u2190 get_decl n,\n   e \u2190 mk_const n,\n   let t := d.type,\n   if (t =\u2090 `(tactic unit)) then\n     (eval_expr (tactic unit) e) >>= (\u03bb t, t >> (name.to_string <$> strip_prefix n))\n   else if (t =\u2090 `(tactic string)) then\n     (eval_expr (tactic string) e) >>= (\u03bb t, t)\n   else fail!\n     \"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`\"\n\n/-- auxiliary function for `apply_under_n_pis` -/\nprivate meta def apply_under_n_pis_aux (func arg : pexpr) : \u2115 \u2192 \u2115 \u2192 expr \u2192 pexpr\n| n 0 _ :=\n  let vars := ((list.range n).reverse.map (@expr.var ff)),\n      bd := vars.foldl expr.app arg.mk_explicit in\n  func bd\n| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp)\n  (apply_under_n_pis_aux (n+1) k bd)\n| n (k+1) t := apply_under_n_pis_aux n 0 t\n\n/--\nAssumes `pi_expr` is of the form `\u03a0 x1 ... xn xn+1..., _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\nmeta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : \u2115) : pexpr :=\napply_under_n_pis_aux func arg 0 n pi_expr\n\n/--\nAssumes `pi_expr` is of the form `\u03a0 x1 ... xn, _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\nmeta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=\napply_under_n_pis func arg pi_expr pi_expr.pi_arity\n\n/--\nIf `func` is a `pexpr` representing a function that takes an argument `a`,\n`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.\nWhen `tgt` is a `pi` expr, `func` is elaborated in a context\nwith the domain of `tgt`.\n\nExamples:\n* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function\n  argument.\n* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument\n  of type `\u03b1 \u2192 \u03b1`.\n* ```get_pexpr_arg_arity_with_tgt ``(module R) `(\u03a0 (R : Type), comm_ring R \u2192 true)``` returns 0\n-/\nmeta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic \u2115 :=\nlock_tactic_state $ do\n  mv \u2190 mk_mvar,\n  solve_aux tgt $ intros >> to_expr ``(%%func %%mv),\n  expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)\n\n/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.\n\n`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a\ndeclaration named `m` can be found. -/\nmeta def find_private_decl (n : name) (fr : option name) : tactic name :=\ndo env \u2190 get_env,\n   fn \u2190 option_t.run (do\n         fr \u2190 option_t.mk (return fr),\n         d \u2190 monad_lift $ get_decl fr,\n         option_t.mk (return $ env.decl_olean d.to_name) ),\n   let p : string \u2192 bool :=\n     match fn with\n     | (some fn) := \u03bb x, fn = x\n     | none := \u03bb _, tt\n     end,\n   let xs := env.decl_filter_map (\u03bb d,\n     do fn \u2190 env.decl_olean d.to_name,\n        guard ((`_private).is_prefix_of d.to_name \u2227 p fn \u2227\n          d.to_name.update_prefix name.anonymous = n),\n        pure d.to_name),\n   match xs with\n   | [n] := pure n\n   | [] := fail \"no such private found\"\n   | _ := fail \"many matches found\"\n   end\n\nopen lean.parser interactive\n\n/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`\nand creates a local notation to refer to it.\n\n`import_private foo` looks for `foo` in all imported files.\n\nWhen possible, make `foo` non-private rather than using this feature.\n -/\n@[user_command]\nmeta def import_private_cmd (_ : parse $ tk \"import_private\") : lean.parser unit :=\ndo n  \u2190 ident,\n   fr \u2190 optional (tk \"from\" *> ident),\n   n \u2190 find_private_decl n fr,\n   c \u2190 resolve_constant n,\n   d \u2190 get_decl n,\n   let c := @expr.const tt c d.univ_levels,\n   new_n \u2190 new_aux_decl_name,\n   add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,\n   let new_not := sformat!\"local notation `{n.update_prefix name.anonymous}` := {new_n}\",\n   emit_command_here $ new_not,\n   skip .\n\nadd_tactic_doc\n{ name                     := \"import_private\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.import_private_cmd],\n  tags                     := [\"renaming\"] }\n\n/--\nThe command `mk_simp_attribute simp_name \"description\"` creates a simp set with name `simp_name`.\nLemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.\n`mk_simp_attribute simp_name none` will use a default description.\n\nAppending the command with `with attr1 attr2 ...` will include all declarations tagged with\n`attr1`, `attr2`, ... in the new simp set.\n\nThis command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string\nto the attribute that is defined. If you need to create a simp set in a file where this command is\nnot available, you should use\n```lean\nrun_cmd mk_simp_attr `simp_name\nrun_cmd add_doc_string `simp_attr.simp_name \"Description of the simp set here\"\n```\n-/\n@[user_command]\nmeta def mk_simp_attribute_cmd (_ : parse $ tk \"mk_simp_attribute\") : lean.parser unit :=\ndo n \u2190 ident,\n   d \u2190 parser.pexpr,\n   d \u2190 to_expr ``(%%d : option string),\n   descr \u2190 eval_expr (option string) d,\n   with_list \u2190 (tk \"with\" *> many ident) <|> return [],\n   mk_simp_attr n with_list,\n   add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ \"simp set for \" ++ to_string n\n\nadd_tactic_doc\n{ name                     := \"mk_simp_attribute\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.mk_simp_attribute_cmd],\n  tags                     := [\"simplification\"] }\n\n/--\nGiven a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns\nthe name of the declaration that defines this attribute.\nFails if there is no user attribute with this name.\nExample: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/\nmeta def get_user_attribute_name (attr_name : name) : tactic name := do\nns \u2190 attribute.get_instances `user_attribute,\nns.mfirst (\u03bb nm, do\n  d \u2190 get_decl nm,\n  e \u2190 mk_app `user_attribute.name [d.value],\n  attr_nm \u2190 eval_expr name e,\n  guard $ attr_nm = attr_name,\n  return nm) <|> fail!\"'{attr_name}' is not a user attribute.\"\n\n/-- A tactic to set either a basic attribute or a user attribute.\n  If the user attribute has a parameter, the default value will be used.\n  This tactic raises an error if there is no `inhabited` instance for the parameter type. -/\nmeta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)\n  (prio : option nat := none) : tactic unit := do\nget_decl c_name <|> fail!\"unknown declaration {c_name}\",\ns \u2190 try_or_report_error (set_basic_attribute attr_name c_name persistent prio),\nsum.inr msg \u2190 return s | skip,\nif msg =\n  (format!\"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute\").to_string\nthen do\n  user_attr_nm \u2190 get_user_attribute_name attr_name,\n  user_attr_const \u2190 mk_const user_attr_nm,\n  tac \u2190 eval_pexpr (tactic unit)\n    ``(user_attribute.set %%user_attr_const %%c_name (default _) %%persistent) <|>\n    fail! (\"Cannot set attribute @[{attr_name}].\\n\" ++\n      \"The corresponding user attribute {user_attr_nm} \" ++\n      \"has a parameter without a default value.\\n\" ++\n      \"Solution: provide an `inhabited` instance.\"),\n  tac\nelse fail msg\n\nend tactic\n\n/--\n`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),\nand returns the value associated with this key if it exists.\nOtherwise, it fails.\n-/\nmeta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr \u00d7 v)) (e : expr) :\n  tactic (expr \u00d7 v) :=\nm.mfind $ \u03bb \u27e8e', val\u27e9, tactic.is_def_eq e e' red\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/core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.08882029300310251, "lm_q1q2_score": 0.04094764673334665}}
{"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) = (\u00acp \u2228 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 \u2228 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 \u2227 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) = (\u00acp \u2227 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 := \u27e8Int.ofNat\u27e9\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 `\u2191` operator to explicitly indicate a coercion. Using `\u2191x`\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 `\u2191x + \u2191y` where `+` is the addition on `Int`, or `\u2191(x + y)`\nwhere `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition\nwith the type `Nat \u2192 Nat \u2192 Int`. You can use the `\u2191` 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 `\u2191x : Int` and `\u2191y : Int`, resulting in the `\u2191x + \u2191y` version.\n\nNote that unlike most operators like `+`, `\u2191` 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 \u2192 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 ?\u03b1` 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 \u03b1 \u03b2` 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 `\u03b1` must be a subset of the variables in `\u03b2`\n  (or out-params of type class parameters),\n  because `Coe` is chained right-to-left.\n\n* `CoeOut \u03b1 \u03b2` is like `Coe \u03b1 \u03b2` but chained left-to-right.\n  Use this if the variables in the type `\u03b1` are a superset of the variables in `\u03b2`.\n\n* `CoeTail \u03b1 \u03b2` is like `Coe \u03b1 \u03b2`, but only applied once.\n  Use this for coercions that would cause loops, like `[Ring R] \u2192 CoeTail Nat R`.\n\n* `CoeHead \u03b1 \u03b2` is similar to `CoeOut \u03b1 \u03b2`, but only applied once.\n  Use this for coercions that would cause loops, like `[SetLike S \u03b1] \u2192 CoeHead S (Set \u03b1)`.\n\n* `CoeDep \u03b1 (x : \u03b1) \u03b2` allows `\u03b2` to depend not only on `\u03b1` but on the value\n  `x : \u03b1` itself. This is useful when the coercion function is dependent.\n  An example of a dependent coercion is the instance for `Prop \u2192 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 \u03b1 (\u03b3 : \u03b1 \u2192 Sort v)` is a coercion to a function. `\u03b3 a` should be a\n  (coercion-to-)function type, and this is triggered whenever an element\n  `f : \u03b1` 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 \u03b1 \u03b2` is a coercion to a sort. `\u03b2` must be a universe, and if\n  `a : \u03b1` appears in a place where a type is expected, like `(x : a)` or `a \u2192 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 \u03b1 \u03b2` is the typeclass for coercions from `\u03b1` to `\u03b2`. It can be transitively\nchained with other `Coe` instances, and coercion is automatically used when\n`x` has type `\u03b1` but it is used in a context where `\u03b2` is expected.\nYou can use the `\u2191x` operator to explicitly trigger coercion.\n-/\nclass Coe (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] Coe.coe\n\n/--\nAuxiliary class implementing `Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeTC (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeTC.coe\n\ninstance [Coe \u03b2 \u03b3] [CoeTC \u03b1 \u03b2] : CoeTC \u03b1 \u03b3 where coe a := Coe.coe (CoeTC.coe a : \u03b2)\ninstance [Coe \u03b1 \u03b2] : CoeTC \u03b1 \u03b2 where coe a := Coe.coe a\ninstance : CoeTC \u03b1 \u03b1 where coe a := a\n\n/--\n`CoeOut \u03b1 \u03b2` is for coercions that are applied from left-to-right.\n-/\nclass CoeOut (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeOut.coe\n\n/--\nAuxiliary class implementing `CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeOTC (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeOTC.coe\n\ninstance [CoeOut \u03b1 \u03b2] [CoeOTC \u03b2 \u03b3] : CoeOTC \u03b1 \u03b3 where coe a := CoeOTC.coe (CoeOut.coe a : \u03b2)\ninstance [CoeTC \u03b1 \u03b2] : CoeOTC \u03b1 \u03b2 where coe a := CoeTC.coe a\ninstance : CoeOTC \u03b1 \u03b1 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 \u2192+ B)` apply even when the two sides are defeq.)\n\n/--\n`CoeHead \u03b1 \u03b2` is for coercions that are applied from left-to-right at most once\nat beginning of the coercion chain.\n-/\nclass CoeHead (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeHead.coe\n\n/--\nAuxiliary class implementing `CoeHead CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTC (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeHTC.coe\n\ninstance [CoeHead \u03b1 \u03b2] [CoeOTC \u03b2 \u03b3] : CoeHTC \u03b1 \u03b3 where coe a := CoeOTC.coe (CoeHead.coe a : \u03b2)\ninstance [CoeOTC \u03b1 \u03b2] : CoeHTC \u03b1 \u03b2 where coe a := CoeOTC.coe a\ninstance : CoeHTC \u03b1 \u03b1 where coe a := a\n\n/--\n`CoeTail \u03b1 \u03b2` is for coercions that can only appear at the end of a\nsequence of coercions. That is, `\u03b1` can be further coerced via `Coe \u03c3 \u03b1` and\n`CoeHead \u03c4 \u03c3` instances but `\u03b2` will only be the expected type of the expression.\n-/\nclass CoeTail (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeTail.coe\n\n/--\nAuxiliary class implementing `CoeHead* Coe* CoeTail?`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTCT (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Coerces a value of type `\u03b1` to type `\u03b2`. Accessible by the notation `\u2191x`,\n  or by double type ascription `((x : \u03b1) : \u03b2)`. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeHTCT.coe\n\ninstance [CoeTail \u03b2 \u03b3] [CoeHTC \u03b1 \u03b2] : CoeHTCT \u03b1 \u03b3 where coe a := CoeTail.coe (CoeHTC.coe a : \u03b2)\ninstance [CoeHTC \u03b1 \u03b2] : CoeHTCT \u03b1 \u03b2 where coe a := CoeHTC.coe a\ninstance : CoeHTCT \u03b1 \u03b1 where coe a := a\n\n/--\n`CoeDep \u03b1 (x : \u03b1) \u03b2` is a typeclass for dependent coercions, that is, the type `\u03b2`\ncan depend on `x` (or rather, the value of `x` is available to typeclass search\nso an instance that relates `\u03b2` 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 (\u03b1 : Sort u) (_ : \u03b1) (\u03b2 : Sort v) where\n  /-- The resulting value of type `\u03b2`. The input `x : \u03b1` is a parameter to\n  the type class, so the value of type `\u03b2` may possibly depend on additional\n  typeclasses on `x`. -/\n  coe : \u03b2\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 `\u2191x` or by double type\nascription `((x : \u03b1) : \u03b2)`.\n\nA `CoeT` chain has the grammar `CoeHead? CoeOut* Coe* CoeTail? | CoeDep`.\n-/\nclass CoeT (\u03b1 : Sort u) (_ : \u03b1) (\u03b2 : Sort v) where\n  /-- The resulting value of type `\u03b2`. The input `x : \u03b1` is a parameter to\n  the type class, so the value of type `\u03b2` may possibly depend on additional\n  typeclasses on `x`. -/\n  coe : \u03b2\nattribute [coe_decl] CoeT.coe\n\ninstance [CoeHTCT \u03b1 \u03b2] : CoeT \u03b1 a \u03b2 where coe := CoeHTCT.coe a\ninstance [CoeDep \u03b1 a \u03b2] : CoeT \u03b1 a \u03b2 where coe := CoeDep.coe a\ninstance : CoeT \u03b1 a \u03b1 where coe := a\n\n/--\n`CoeFun \u03b1 (\u03b3 : \u03b1 \u2192 Sort v)` is a coercion to a function. `\u03b3 a` should be a\n(coercion-to-)function type, and this is triggered whenever an element\n`f : \u03b1` 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 (\u03b1 : Sort u) (\u03b3 : outParam (\u03b1 \u2192 Sort v)) where\n  /-- Coerces a value `f : \u03b1` to type `\u03b3 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 : \u03b1) \u2192 \u03b3 f\nattribute [coe_decl] CoeFun.coe\n\ninstance [CoeFun \u03b1 fun _ => \u03b2] : CoeOut \u03b1 \u03b2 where coe a := CoeFun.coe a\n\n/--\n`CoeSort \u03b1 \u03b2` is a coercion to a sort. `\u03b2` must be a universe, and if\n`a : \u03b1` appears in a place where a type is expected, like `(x : a)` or `a \u2192 a`,\nthen it will be turned into `(x : CoeSort.coe a)`.\n-/\nclass CoeSort (\u03b1 : Sort u) (\u03b2 : outParam (Sort v)) where\n  /-- Coerces a value of type `\u03b1` to `\u03b2`, which must be a universe. -/\n  coe : \u03b1 \u2192 \u03b2\nattribute [coe_decl] CoeSort.coe\n\ninstance [CoeSort \u03b1 \u03b2] : CoeOut \u03b1 \u03b2 where coe a := CoeSort.coe a\n\n/--\n`\u2191x` represents a coercion, which converts `x` of type `\u03b1` to type `\u03b2`, using\ntypeclasses to resolve a suitable conversion function. You can often leave the\n`\u2191` off entirely, since coercion is triggered implicitly whenever there is a\ntype error, but in ambiguous cases it can be useful to use `\u2191` to disambiguate\nbetween e.g. `\u2191x + \u2191y` and `\u2191(x + y)`.\n-/\nsyntax:1024 (name := coeNotation) \"\u2191\" 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 {\u03b1 : Type u} : Coe \u03b1 (Option \u03b1) where\n  coe := some\n\ninstance subtypeCoe {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : CoeOut (Subtype p) \u03b1 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 \u2192 Type v} {n : Type u \u2192 Type w} {\u03b1 \u03b2 : Type u}\n    [MonadLiftT m n] [\u2200 a, CoeT \u03b1 a \u03b2] [Monad n] (x : m \u03b1) : n \u03b2 := do\n  let a \u2190 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 \u2192 Type v} {\u03b1 \u03b2 : Type u}\n    [\u2200 a, CoeT \u03b1 a \u03b2] [Monad m] (x : m \u03b1) : m \u03b2 := do\n  let a \u2190 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) 2017 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.tidy\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.AutoCases\nimport Mathbin.Tactic.Chain\nimport Mathbin.Tactic.NormCast\n\nnamespace Tactic\n\nnamespace Tidy\n\n/-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics\ncalled by `tidy`. -/\n@[user_attribute]\nunsafe def tidy_attribute : user_attribute\n    where\n  Name := `tidy\n  descr := \"A tactic that should be called by `tidy`.\"\n#align tactic.tidy.tidy_attribute tactic.tidy.tidy_attribute\n\nadd_tactic_doc\n  { Name := \"tidy\"\n    category := DocCategory.attr\n    declNames := [`tactic.tidy.tidy_attribute]\n    tags := [\"search\"] }\n\nunsafe def run_tactics : tactic String := do\n  let names \u2190 attribute.get_instances `tidy\n  first (names name_to_tactic) <|> fail \"no @[tidy] tactics succeeded\"\n#align tactic.tidy.run_tactics tactic.tidy.run_tactics\n\n@[hint_tactic]\nunsafe def ext1_wrapper : tactic String := do\n  let ng \u2190 num_goals\n  ext1 [] { NewGoals := new_goals.all }\n  let ng' \u2190 num_goals\n  return <| if ng' > ng then \"tactic.ext1 [] {new_goals := tactic.new_goals.all}\" else \"ext1\"\n#align tactic.tidy.ext1_wrapper tactic.tidy.ext1_wrapper\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/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\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/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\nunsafe def default_tactics : List (tactic String) :=\n  [reflexivity >> pure \"refl\", sorry >> pure \"exact dec_trivial\",\n    (propositional_goal >> assumption) >> pure \"assumption\",\n    intros1 >>= fun ns => pure (\"intros \" ++ (\" \".intercalate <| ns.map fun e => e.toString)),\n    auto_cases, sorry >> pure \"apply_auto_param\", sorry >> pure \"dsimp at *\",\n    sorry >> pure \"simp at *\", ext1_wrapper, fsplit >> pure \"fsplit\",\n    injections_and_clear >> pure \"injections_and_clear\",\n    (propositional_goal >> sorry) >> pure \"solve_by_elim\", sorry >> pure \"norm_cast\",\n    sorry >> pure \"unfold_coes\", sorry >> pure \"unfold_aux\", tidy.run_tactics]\n#align tactic.tidy.default_tactics tactic.tidy.default_tactics\n\nunsafe structure cfg where\n  trace_result : Bool := false\n  trace_result_prefix : String := \"Try this: \"\n  tactics : List (tactic String) := default_tactics\n#align tactic.tidy.cfg tactic.tidy.cfg\n\ninitialize\n  registerTraceClass.1 `tidy\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `cfg -/\nunsafe def core (cfg : cfg := { }) : tactic (List String) := do\n  let results \u2190 chain cfg.tactics\n  when (cfg cfg.trace_result) <| trace (cfg ++ \", \".intercalate results)\n  return results\n#align tactic.tidy.core tactic.tidy.core\n\nend Tidy\n\nunsafe def tidy (cfg : tidy.cfg := { }) :=\n  tactic.tidy.core cfg >> skip\n#align tactic.tidy tactic.tidy\n\nnamespace Interactive\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\n/-- Use a variety of conservative tactics to solve goals.\n\n`tidy?` reports back the tactic script it found. As an example\n```lean\nexample : \u2200 x : unit, x = unit.star :=\nbegin\n  tidy? -- Prints the trace message: \"Try this: intros x, exact dec_trivial\"\nend\n```\n\nThe default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.\nThis list can be overridden using `tidy { tactics := ... }`.\n(The list must be a `list` of `tactic string`, so that `tidy?`\ncan report a usable tactic script.)\n\nTactics can also be added to the list by tagging them (locally) with the\n`[tidy]` attribute. -/\nunsafe def tidy (trace : parse <| optional (tk \"?\")) (cfg : tidy.cfg := { }) :=\n  tactic.tidy { cfg with trace_result := trace.isSome }\n#align tactic.interactive.tidy tactic.interactive.tidy\n\nend Interactive\n\nadd_tactic_doc\n  { Name := \"tidy\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.tidy]\n    tags := [\"search\", \"Try this\", \"finishing\"] }\n\n/-- Invoking the hole command `tidy` (\"Use `tidy` to complete the goal\") runs the tactic of\nthe same name, replacing the hole with the tactic script `tidy` produces.\n-/\n@[hole_command]\nunsafe def tidy_hole_cmd : hole_command\n    where\n  Name := \"tidy\"\n  descr := \"Use `tidy` to complete the goal.\"\n  action _ := do\n    let script \u2190 tidy.core\n    return [(\"begin \" ++ \", \".intercalate script ++ \" end\", \"by tidy\")]\n#align tactic.tidy_hole_cmd tactic.tidy_hole_cmd\n\nadd_tactic_doc\n  { Name := \"tidy\"\n    category := DocCategory.hole_cmd\n    declNames := [`tactic.tidy_hole_cmd]\n    tags := [\"search\"] }\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/Tidy.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.0967057965503036, "lm_q1q2_score": 0.04085864866231331}}
{"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n\nTransport through constant families.\n-/\n\nuniverses u\u2081 u\u2082\n\n@[simp] lemma plift.rec.constant {\u03b1 : Sort u\u2081} {\u03b2 : Sort u\u2082} (b : \u03b2) : @plift.rec \u03b1 (\u03bb _, \u03b2) (\u03bb _, b) = \u03bb _, b :=\nfunext (\u03bb x, plift.cases_on x (\u03bb a, eq.refl (plift.rec (\u03bb a', b) {down := a})))\n\n@[simp] lemma ulift.rec.constant {\u03b1 : Type u\u2081} {\u03b2 : Sort u\u2082} (b : \u03b2) : @ulift.rec \u03b1 (\u03bb _, \u03b2) (\u03bb _, b) = \u03bb _, b :=\nfunext (\u03bb x, ulift.cases_on x (\u03bb a, eq.refl (ulift.rec (\u03bb a', b) {down := a})))\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/data/ulift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.08151974760686587, "lm_q1q2_score": 0.04075987380343293}}
{"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 : \u2200 {x : X}, x \u2208 carrier \u2192 sorry \u2208 carrier)\n\nnamespace my_subobject\n\nvariables (X : Type*)\n\ninstance : set_like (my_subobject X) X :=\n\u27e8sub_mul_action.carrier, \u03bb p q h, by cases p; cases q; congr'\u27e9\n\n@[simp] lemma mem_carrier {p : my_subobject X} : x \u2208 p.carrier \u2194 x \u2208 (p : set X) := iff.rfl\n\n@[ext] theorem ext {p q : my_subobject X} (h : \u2200 x, x \u2208 p \u2194 x \u2208 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 = \u2191p) : my_subobject X :=\n{ carrier := s,\n  op_mem' := hs.symm \u25b8 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 \u2192 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) := \u27e8set_like.coe\u27e9\n\n@[priority 100]\ninstance : has_mem B A := \u27e8\u03bb x p, x \u2208 (p : set B)\u27e9\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 := \u27e8_, \u03bb p, {x : B // x \u2208 p}\u27e9\n\nvariables (p q : A)\n\n@[simp, norm_cast] theorem coe_sort_coe : \u21a5(p : set B) = p := rfl\n\nvariables {p q}\n\nprotected theorem \u00abexists\u00bb {q : p \u2192 Prop} :\n  (\u2203 x, q x) \u2194 (\u2203 x \u2208 p, q \u27e8x, \u2039_\u203a\u27e9) := set_coe.exists\n\nprotected theorem \u00abforall\u00bb {q : p \u2192 Prop} :\n  (\u2200 x, q x) \u2194 (\u2200 x \u2208 p, q \u27e8x, \u2039_\u203a\u27e9) := set_coe.forall\n\ntheorem coe_injective : function.injective (coe : A \u2192 set B) :=\n\u03bb x y h, set_like.coe_injective' h\n\n@[simp, norm_cast] theorem coe_set_eq : (p : set B) = q \u2194 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 \u2194 (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 : \u2200 x, x \u2208 p \u2194 x \u2208 q) : p = q := coe_injective $ set.ext h\n\ntheorem ext_iff : p = q \u2194 (\u2200 x, x \u2208 p \u2194 x \u2208 q) := coe_injective.eq_iff.symm.trans set.ext_iff\n\n@[simp] theorem mem_coe {x : B} : x \u2208 (p : set B) \u2194 x \u2208 p := iff.rfl\n\n@[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : B) = y \u2194 x = y := subtype.ext_iff_val.symm\n\n@[simp, norm_cast] lemma coe_mk (x : B) (hx : x \u2208 p) : ((\u27e8x, hx\u27e9 : p) : B) = x := rfl\n@[simp] lemma coe_mem (x : p) : (x : B) \u2208 p := x.2\n\n@[simp] protected lemma eta (x : p) (hx : (x : B) \u2208 p) : (\u27e8x, hx\u27e9 : 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 := \u03bb H K, \u2200 \u2983x\u2984, x \u2208 H \u2192 x \u2208 K,\n  .. partial_order.lift (coe : A \u2192 set B) coe_injective }\n\nlemma le_def {S T : A} : S \u2264 T \u2194 \u2200 \u2983x : B\u2984, x \u2208 S \u2192 x \u2208 T := iff.rfl\n\n@[simp, norm_cast]\nlemma coe_subset_coe {S T : A} : (S : set B) \u2286 T \u2194 S \u2264 T := iff.rfl\n\n@[mono] lemma coe_mono : monotone (coe : A \u2192 set B) := \u03bb a b, coe_subset_coe.mpr\n\n@[simp, norm_cast]\nlemma coe_ssubset_coe {S T : A} : (S : set B) \u2282 T \u2194 S < T := iff.rfl\n\n@[mono] lemma coe_strict_mono : strict_mono (coe : A \u2192 set B) := \u03bb a b, coe_ssubset_coe.mpr\n\nlemma not_le_iff_exists : \u00ac(p \u2264 q) \u2194 \u2203 x \u2208 p, x \u2209 q := set.not_subset\n\nlemma exists_of_lt : p < q \u2192 \u2203 x \u2208 q, x \u2209 p := set.exists_of_ssubset\n\nlemma lt_iff_le_and_exists : p < q \u2194 p \u2264 q \u2227 \u2203 x \u2208 q, x \u2209 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 \u03b1` 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\u2080 u\u2081 v\u2080 v\u2081 v\u2082 w w\u2080 w\u2081\nvariables {s : Type u\u2080} {s' : Type u\u2081} {r r' w w' : Type*}\n\n/-- Given a universe polymorphic type family `M.{u} : Type u\u2081 \u2192 Type\nu\u2082`, this class convert between instantiations, from\n`M.{u} : Type u\u2081 \u2192 Type u\u2082` to `M.{v} : Type v\u2081 \u2192 Type v\u2082` and back -/\nclass uliftable (f : Type u\u2080 \u2192 Type u\u2081) (g : Type v\u2080 \u2192 Type v\u2081) :=\n(congr [] {\u03b1 \u03b2} : \u03b1 \u2243 \u03b2 \u2192 f \u03b1 \u2243 g \u03b2)\n\nnamespace uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} \u03b1` and lifts it to M.{max u v} (ulift.{v} \u03b1) -/\n@[reducible]\ndef up {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} : f \u03b1 \u2192 g (ulift \u03b1) :=\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} \u03b1)` and lowers it to `M.{u} \u03b1` -/\n@[reducible]\ndef down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} : g (ulift \u03b1) \u2192 f \u03b1 :=\n(uliftable.congr f g equiv.ulift.symm).inv_fun\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v\u2080 \u2192 Type v\u2081) (G : Type (max v\u2080 u\u2080) \u2192 Type u\u2081)\n  [uliftable F G] [monad G] {\u03b1 \u03b2}\n  (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\nup x >>= f \u2218 ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type v\u2080 \u2192 Type v\u2081}\n  [L : uliftable G F] [monad F] {\u03b1 \u03b2}\n  (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n@down.{v\u2080 v\u2081 (max u\u2080 v\u2080)} G F L \u03b2 $ x >>= @up.{v\u2080 v\u2081 (max u\u2080 v\u2080)} G F L \u03b2 \u2218 f\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u\u2080 \u2192 Type u\u2081} {G : Type.{max u\u2080 v\u2080} \u2192 Type v\u2081} [inst : uliftable F G]\n  [functor G] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\nfunctor.map (f \u2218 ulift.down) (up x)\n\n/-- map function that moves down universes -/\ndef down_map {F : Type.{max u\u2080 v\u2080} \u2192 Type u\u2081} {G : Type u\u2080 \u2192 Type v\u2081} [inst : uliftable G F]\n  [functor F] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\ndown (functor.map (ulift.up \u2218 f) x : F (ulift \u03b2))\n\n@[simp]\nlemma up_down  {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} (x : g (ulift \u03b1)) : up (down x : f \u03b1) = x :=\n(uliftable.congr f g equiv.ulift.symm).right_inv _\n\n@[simp]\nlemma down_up  {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} (x : f \u03b1) : 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 := \u03bb \u03b1 \u03b2 F, F }\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {m : Type u\u2080 \u2192 Type v\u2080} {m' : Type u\u2081 \u2192 Type v\u2081}\n  [uliftable m m']\n  (F : s \u2243 s') :\n  uliftable (state_t s m) (state_t s' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 G, state_t.equiv $ equiv.Pi_congr F $\n      \u03bb _, 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 \u2243 s') :\n  uliftable (reader_t s m) (reader_t s' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 G, reader_t.equiv $ equiv.Pi_congr F $\n      \u03bb _, 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 \u2243 r') :\n  uliftable (cont_t r m) (cont_t r' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2, 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 \u2243 w') :\n  uliftable (writer_t w m) (writer_t w' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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\u03bb 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 := \u27e8\u03bb ns,\n                ns.mfoldl\n                  (\u03bb 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 \u2190 aux_attr.get_param_untyped n',\n                    pure $ dict.insert n param.app_arg.const_name)\n                  mk_name_map, []\u27e9 }\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 `\u2115` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nmeta def ignore_args_attr : user_attribute (name_map $ list \u2115) (list \u2115) :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\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 `\u2115 \u00d7 \u03b1`\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 \u2115) \u2115 :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\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 \u2115) (list \u2115) :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\n  parser    := do\n    l \u2190 (lean.parser.small_nat)*,\n    guard (l.all (\u2260 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 \u2115 := do\n  d \u2190 get_decl nm,\n  let (es, _) := d.type.pi_binders,\n  l \u2190 es.mmap_with_index $ \u03bb n bi, do\n  { let tgt := bi.type.pi_codomain,\n    let n_bi := bi.type.pi_binders.fst.length,\n    tt \u2190 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 $ \u03bb 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 \u2192 string \u2192 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 \u2192 list string \u2192 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 \u2192 string :=\nstring.map_tokens ''' $\n\u03bb 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 \u2260 name.anonymous \u2228 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 \u2260 tgt_auto \u2228 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(\u03bb res,\n  if res = src \u2227 tgt \u2260 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 \u2190 option.is_some <$> (tk \"!\")?,\n  ques \u2190 option.is_some <$> (tk \"?\")?,\n  tgt \u2190 ident?,\n  e \u2190 texpr?,\n  doc \u2190 match e with\n      | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n      | none := pure none\n      end,\n  return \u27e8bang, ques, tgt.get_or_else name.anonymous, doc, ff\u27e9\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : \u2115) (f : name \u2192 tactic (list string)) :\n  command :=\ndo\n  src_fields \u2190 f src,\n  tgt_fields \u2190 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    \u03bb 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 : \u2115) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (\u03bb n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (\u03bb n, (list.map (\u03bb (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (\u03bb n, (env.constructors_of n).mmap $\n          \u03bb 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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 \u00d7 N) := \u27e8\u03bb p q, \u27e8p.1 * q.1, p.2 * q.2\u27e9\u27e9\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 \u2115 n m` (i.e. `(n * m : \u2115)`) will not change to `+`, since its\n  first argument is `\u2115`, an identifier not applied to any arguments.\n* `@has_mul.mul (\u03b1 \u00d7 \u03b2) x y` will change to `+`. It's first argument contains only the identifier\n  `prod`, but this is applied to arguments, `\u03b1` and `\u03b2`.\n* `@has_mul.mul (\u03b1 \u00d7 \u2124) x y` will not change to `+`, since its first argument contains `\u2124`.\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 `\u21a5Semigroup` is replaced by addition in `\u21a5AddSemigroup`.\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 : \u2115\u221e)` can contain `\u2115`\n  (usually in the form `has_top.top \u2115 ...`) and still be additivized.\n  So `@has_mul.mul (C^\u221e\u27eeI, N; I', G\u27ef) _ 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 `\u2115` or `\u211d`. 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 `\u2115` or `\u211d`. Solutions:\n  * If the fixed type has an additive counterpart (like `\u21a5Semigroup`), 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 \u201cmain\u201d 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 \u201cmain\u201d 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 (\u201cmul\u201d, \u201cone\u201d, \u201cinv\u201d, \u201cprod\u201d) 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 $ \u03bb src prio persistent, do\n    guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n    env \u2190 get_env,\n    val \u2190 attr.get_param src,\n    dict \u2190 aux_attr.get_cache,\n    ignore \u2190 ignore_args_attr.get_cache,\n    relevant \u2190 relevant_arg_attr.get_cache,\n    reorder \u2190 reorder_attr.get_cache,\n    tgt \u2190 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 \u2190 first_multiplicative_arg src,\n    when (first_mult_arg \u2260 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 \u2190 tactic.alias.get_alias_target src | skip,\n        let alias_name := alias_target.to_name,\n        some add_alias_name \u2190 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 := (\u03bb d, do\n    let mul_name := d.to_name,\n    dict \u2190 to_additive.aux_attr.get_cache,\n    match dict.find mul_name with\n    | some add_name := do\n      mul_doc \u2190 try_core $ doc_string mul_name,\n      add_doc \u2190 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 (\u03b1 n) : @mkEmpty \u03b1 n = #[] := rfl\n\n@[simp] theorem size_toArray (as : List \u03b1) : as.toArray.size = as.length := by simp [size]\n\n@[simp] theorem size_mk (as : List \u03b1) : (Array.mk as).size = as.length := by simp [size]\n\ntheorem getElem_eq_data_get (a : Array \u03b1) (h : i < a.size) : a[i] = a.data.get \u27e8i, h\u27e9 := by\n  by_cases i < a.size <;> simp [*] <;> rfl\n\ntheorem foldlM_eq_foldlM_data.aux [Monad m]\n    (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (arr : Array \u03b1) (i j) (H : arr.size \u2264 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  \u00b7 cases Nat.not_le_of_gt \u2039_\u203a (Nat.zero_add _ \u25b8 H)\n  \u00b7 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 [\u2190 List.get_drop_eq_drop _ _ \u2039_\u203a]\n  \u00b7 rw [List.drop_length_le (Nat.ge_of_not_lt \u2039_\u203a)]; rfl\n\ntheorem foldlM_eq_foldlM_data [Monad m]\n    (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (arr : Array \u03b1) :\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 : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (init : \u03b2) (arr : Array \u03b1) :\n    arr.foldl f init = arr.data.foldl f init :=\n  List.foldl_eq_foldlM .. \u25b8 foldlM_eq_foldlM_data ..\n\ntheorem foldrM_eq_reverse_foldlM_data.aux [Monad m]\n    (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (arr : Array \u03b1) (init : \u03b2) (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 [\u2190 List.take_concat_get _ _ h]; simp [\u2190 (aux f arr \u00b7 i)]; rfl\n\ntheorem foldrM_eq_reverse_foldlM_data [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (arr : Array \u03b1) :\n    arr.foldrM f init = arr.data.reverse.foldlM (fun x y => f y x) init := by\n  have : arr = #[] \u2228 0 < arr.size :=\n    match arr with | \u27e8[]\u27e9 => .inl rfl | \u27e8a::l\u27e9 => .inr (Nat.zero_lt_succ _)\n  match arr, this with | _, .inl rfl => rfl | arr, .inr h => ?_\n  simp [foldrM, h, \u2190 foldrM_eq_reverse_foldlM_data.aux, List.take_length]\n\ntheorem foldrM_eq_foldrM_data [Monad m]\n    (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (arr : Array \u03b1) :\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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (arr : Array \u03b1) :\n    arr.foldr f init = arr.data.foldr f init :=\n  List.foldr_eq_foldrM .. \u25b8 foldrM_eq_foldrM_data ..\n\n@[simp] theorem push_data (arr : Array \u03b1) (a : \u03b1) : (arr.push a).data = arr.data ++ [a] := by\n  simp [push, List.concat_eq_append]\n\ntheorem foldrM_push [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (arr : Array \u03b1) (a : \u03b1) :\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 : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (arr : Array \u03b1) (a : \u03b1) :\n    (arr.push a).foldrM f init (start := arr.size + 1) = f a init >>= arr.foldrM f := by\n  simp [\u2190 foldrM_push]\n\ntheorem foldr_push (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (arr : Array \u03b1) (a : \u03b1) :\n    (arr.push a).foldr f init = arr.foldr f (f a init) := foldrM_push ..\n\n@[simp] theorem foldr_push' (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (arr : Array \u03b1) (a : \u03b1) :\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 \u03b1) (l) : arr.toListAppend l = arr.data ++ l := by\n  simp [toListAppend, foldr_eq_foldr_data]\n\n@[simp] theorem toList_eq (arr : Array \u03b1) : 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 \u03b1) : List \u03b1 := arr.foldl (fun l t => t :: l) []\n\n@[simp] theorem toListRev_eq (arr : Array \u03b1) : arr.toListRev = arr.data.reverse := by\n  rw [toListRev, foldl_eq_foldl_data, \u2190 List.foldr_reverse, List.foldr_self]\n\ntheorem SatisfiesM_foldlM [Monad m] [LawfulMonad m]\n    {as : Array \u03b1} (motive : Nat \u2192 \u03b2 \u2192 Prop) {init : \u03b2} (h0 : motive 0 init) {f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2}\n    (hf : \u2200 i : Fin as.size, \u2200 b, motive i.1 b \u2192 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\u2081 : j \u2264 as.size) (h\u2082 : as.size \u2264 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    \u00b7 next hj =>\n      split\n      \u00b7 cases Nat.not_le_of_gt (by simp [hj]) h\u2082\n      \u00b7 exact (hf \u27e8j, hj\u27e9 b H).bind fun _ => go hj (by rwa [Nat.succ_add] at h\u2082)\n    \u00b7 next hj => exact Nat.le_antisymm h\u2081 (Nat.ge_of_not_lt hj) \u25b8 .pure H\n  simp [foldlM]; exact go (Nat.zero_le _) (Nat.le_refl _) h0\n\ntheorem foldl_induction\n    {as : Array \u03b1} (motive : Nat \u2192 \u03b2 \u2192 Prop) {init : \u03b2} (h0 : motive 0 init) {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2}\n    (hf : \u2200 i : Fin as.size, \u2200 b, motive i.1 b \u2192 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 \u03b1) (x : \u03b1) (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 \u03b1) (x : \u03b1) : (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 \u03b1) (x : \u03b1) (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 \u03b1) (f : \u03b1 \u2192 m \u03b2)\n    (motive : Nat \u2192 Prop) (h0 : motive 0)\n    (p : Fin as.size \u2192 \u03b2 \u2192 Prop)\n    (hs : \u2200 i, motive i.1 \u2192 SatisfiesM (p i \u00b7 \u2227 motive (i + 1)) (f as[i])) :\n    SatisfiesM\n      (fun arr => motive as.size \u2227 \u2203 eq : arr.size = as.size, \u2200 i h, p \u27e8i, h\u27e9 (arr[i]'(eq \u25b8 h)))\n      (Array.mapM f as) := by\n  unfold mapM\n  refine SatisfiesM_foldlM (m := m) (\u03b2 := Array \u03b2)\n    (motive := fun i arr => motive i \u2227 arr.size = i \u2227 \u2200 i h2, p i (arr[i.1]'h2)) ?z ?s\n    |>.imp fun \u27e8h\u2081, eq, h\u2082\u27e9 => \u27e8h\u2081, eq, fun _ _ => h\u2082 ..\u27e9\n  \u00b7 case z => exact \u27e8h0, rfl, fun.\u27e9\n  \u00b7 case s =>\n    intro \u27e8i, hi\u27e9 arr \u27e8ih\u2081, eq, ih\u2082\u27e9\n    refine (hs _ ih\u2081).bind fun b \u27e8h\u2081, h\u2082\u27e9 => .pure \u27e8h\u2082, by simp [eq], fun j hj => ?_\u27e9\n    simp [get_push] at hj \u22a2; split; {apply ih\u2082}\n    cases j; cases (Nat.le_or_eq_of_le_succ hj).resolve_left \u2039_\u203a; cases eq; exact h\u2081\n\ntheorem SatisfiesM_mapM' [Monad m] [LawfulMonad m] (as : Array \u03b1) (f : \u03b1 \u2192 m \u03b2)\n    (p : Fin as.size \u2192 \u03b2 \u2192 Prop)\n    (hs : \u2200 i, SatisfiesM (p i) (f as[i])) :\n    SatisfiesM\n      (fun arr => \u2203 eq : arr.size = as.size, \u2200 i h, p \u27e8i, h\u27e9 (arr[i]'(eq \u25b8 h)))\n      (Array.mapM f as) :=\n  (SatisfiesM_mapM _ _ (fun _ => True) trivial _ (fun _ h => (hs _).imp (\u27e8\u00b7, h\u27e9))).imp (\u00b7.2)\n\ntheorem size_mapM [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) :\n    SatisfiesM (fun arr => arr.size = as.size) (Array.mapM f as) :=\n  (SatisfiesM_mapM' _ _ (fun _ _ => True) (fun _ => .trivial)).imp (\u00b7.1)\n\n@[simp] theorem map_data (f : \u03b1 \u2192 \u03b2) (arr : Array \u03b1) : (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 = \u27e8arr.data ++ l.map f\u27e9 := by\n    induction l generalizing arr <;> simp [*]\n  simp [H]\n\n@[simp] theorem size_map (f : \u03b1 \u2192 \u03b2) (arr : Array \u03b1) : (arr.map f).size = arr.size := by\n  simp [size]\n\n@[simp] theorem getElem_map (f : \u03b1 \u2192 \u03b2) (arr : Array \u03b1) (i : Nat) (h) :\n    ((arr.map f)[i]'h) = f (arr[i]'(size_map .. \u25b8 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 .. \u25b8 h)\n\n@[simp] theorem pop_data (arr : Array \u03b1) : arr.pop.data = arr.data.dropLast := rfl\n\n@[simp] theorem append_eq_append (arr arr' : Array \u03b1) : arr.append arr' = arr ++ arr' := rfl\n\n@[simp] theorem append_data (arr arr' : Array \u03b1) :\n    (arr ++ arr').data = arr.data ++ arr'.data := by\n  rw [\u2190 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 \u03b1) (l : List \u03b1) : arr.appendList l = arr ++ l := rfl\n\n@[simp] theorem appendList_data (arr : Array \u03b1) (l : List \u03b1) :\n    (arr ++ l).data = arr.data ++ l := by\n  rw [\u2190 appendList_eq_append]; unfold Array.appendList\n  induction l generalizing arr <;> simp [*]\n\ntheorem foldl_data_eq_bind (l : List \u03b1) (acc : Array \u03b2)\n    (F : Array \u03b2 \u2192 \u03b1 \u2192 Array \u03b2) (G : \u03b1 \u2192 List \u03b2)\n    (H : \u2200 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 \u03b1) (acc : Array \u03b2) (G : \u03b1 \u2192 \u03b2) :\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 \u03b1) (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\u00ebl Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Ya\u00ebl 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 (\u03b1 : Type*) [heyting_algebra \u03b1] : HeytAlg := bundled.of \u03b1\n\n@[simp] lemma coe_of (\u03b1 : Type*) [heyting_algebra \u03b1] : \u21a5(of \u03b1) = \u03b1 := rfl\n\ninstance : inhabited HeytAlg := \u27e8of punit\u27e9\n\ninstance bundled_hom : bundled_hom heyting_hom :=\n{ to_fun := \u03bb \u03b1 \u03b2 [heyting_algebra \u03b1] [heyting_algebra \u03b2],\n    by exactI (coe_fn : heyting_hom \u03b1 \u03b2 \u2192 \u03b1 \u2192 \u03b2),\n  id := heyting_hom.id,\n  comp := @heyting_hom.comp,\n  hom_ext := \u03bb \u03b1 \u03b2 [heyting_algebra \u03b1] [heyting_algebra \u03b2], by exactI fun_like.coe_injective }\n\nattribute [derive [large_category, concrete_category]] HeytAlg\n\n@[simps]\ninstance has_forget_to_Lat : has_forget\u2082 HeytAlg BddDistLat :=\n{ forget\u2082 := { obj := \u03bb X, BddDistLat.of X,\n               map := \u03bb 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 {\u03b1 \u03b2 : HeytAlg.{u}} (e : \u03b1 \u2243o \u03b2) : \u03b1 \u2245 \u03b2 :=\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\u2081` is a prefix of `l\u2082` if `l\u2082` starts with `l\u2081`.\n* `List.subfix`: `l\u2081` is a subfix of `l\u2082` if `l\u2082` ends with `l\u2081`.\n* `List.infix`: `l\u2081` is an infix of `l\u2082` if `l\u2081` is a prefix of some subfix of `l\u2082`.\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\u2081 <+: l\u2082`: `l\u2081` is a prefix of `l\u2082`.\n`l\u2081 <:+ l\u2082`: `l\u2081` is a subfix of `l\u2082`.\n`l\u2081 <:+: l\u2082`: `l\u2081` is an infix of `l\u2082`.\n-/\n\nopen Nat\n\nvariable {\u03b1 \u03b2 : Type _}\n\nnamespace List\n\nvariable {l l\u2081 l\u2082 l\u2083 : List \u03b1} {a b : \u03b1} {m n : \u2115}\n\n/-! ### prefix, suffix, infix -/\n\n\nsection Fix\n\n@[simp]\ntheorem prefix_append (l\u2081 l\u2082 : List \u03b1) : l\u2081 <+: l\u2081 ++ l\u2082 :=\n  \u27e8l\u2082, rfl\u27e9\n#align list.prefix_append List.prefix_append\n\n@[simp]\ntheorem suffix_append (l\u2081 l\u2082 : List \u03b1) : l\u2082 <:+ l\u2081 ++ l\u2082 :=\n  \u27e8l\u2081, rfl\u27e9\n#align list.suffix_append List.suffix_append\n\ntheorem infix_append (l\u2081 l\u2082 l\u2083 : List \u03b1) : l\u2082 <:+: l\u2081 ++ l\u2082 ++ l\u2083 :=\n  \u27e8l\u2081, l\u2083, rfl\u27e9\n#align list.infix_append List.infix_append\n\n@[simp]\ntheorem infix_append' (l\u2081 l\u2082 l\u2083 : List \u03b1) : l\u2082 <:+: l\u2081 ++ (l\u2082 ++ l\u2083) := by\n  rw [\u2190 List.append_assoc]; apply infix_append\n#align list.infix_append' List.infix_append'\n\ntheorem isPrefix.isInfix : l\u2081 <+: l\u2082 \u2192 l\u2081 <:+: l\u2082 := fun \u27e8t, h\u27e9 => \u27e8[], t, h\u27e9\n#align list.is_prefix.is_infix List.isPrefix.isInfix\n\ntheorem isSuffix.isInfix : l\u2081 <:+ l\u2082 \u2192 l\u2081 <:+: l\u2082 := fun \u27e8t, h\u27e9 => \u27e8t, [], by rw [h, append_nil]\u27e9\n#align list.is_suffix.is_infix List.isSuffix.isInfix\n\ntheorem nil_prefix (l : List \u03b1) : [] <+: l :=\n  \u27e8l, rfl\u27e9\n#align list.nil_prefix List.nil_prefix\n\ntheorem nil_suffix (l : List \u03b1) : [] <:+ l :=\n  \u27e8l, append_nil _\u27e9\n#align list.nil_suffix List.nil_suffix\n\ntheorem nil_infix (l : List \u03b1) : [] <:+: l :=\n  (nil_prefix _).isInfix\n#align list.nil_infix List.nil_infix\n\n@[refl]\ntheorem prefix_refl (l : List \u03b1) : l <+: l :=\n  \u27e8[], append_nil _\u27e9\n#align list.prefix_refl List.prefix_refl\n\n@[refl]\ntheorem suffix_refl (l : List \u03b1) : l <:+ l :=\n  \u27e8[], rfl\u27e9\n#align list.suffix_refl List.suffix_refl\n\n@[refl]\ntheorem infix_refl (l : List \u03b1) : 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 : \u03b1) : \u2200 l, l <:+ a :: l :=\n  suffix_append [a]\n#align list.suffix_cons List.suffix_cons\n\ntheorem prefix_concat (a : \u03b1) (l) : l <+: concat l a := by simp\n#align list.prefix_concat List.prefix_concat\n\ntheorem infix_cons : l\u2081 <:+: l\u2082 \u2192 l\u2081 <:+: a :: l\u2082 := fun \u27e8L\u2081, L\u2082, h\u27e9 => \u27e8a :: L\u2081, L\u2082, h \u25b8 rfl\u27e9\n#align list.infix_cons List.infix_cons\n\ntheorem infix_concat : l\u2081 <:+: l\u2082 \u2192 l\u2081 <:+: concat l\u2082 a := fun \u27e8L\u2081, L\u2082, h\u27e9 =>\n  \u27e8L\u2081, concat L\u2082 a, by simp_rw [\u2190 h, concat_eq_append, append_assoc]\u27e9\n#align list.infix_concat List.infix_concat\n\n@[trans]\ntheorem isPrefix.trans : \u2200 {l\u2081 l\u2082 l\u2083 : List \u03b1}, l\u2081 <+: l\u2082 \u2192 l\u2082 <+: l\u2083 \u2192 l\u2081 <+: l\u2083\n  | _, _, _, \u27e8r\u2081, rfl\u27e9, \u27e8r\u2082, rfl\u27e9 => \u27e8r\u2081 ++ r\u2082, (append_assoc _ _ _).symm\u27e9\n#align list.is_prefix.trans List.isPrefix.trans\n\n@[trans]\ntheorem isSuffix.trans : \u2200 {l\u2081 l\u2082 l\u2083 : List \u03b1}, l\u2081 <:+ l\u2082 \u2192 l\u2082 <:+ l\u2083 \u2192 l\u2081 <:+ l\u2083\n  | _, _, _, \u27e8l\u2081, rfl\u27e9, \u27e8l\u2082, rfl\u27e9 => \u27e8l\u2082 ++ l\u2081, append_assoc _ _ _\u27e9\n#align list.is_suffix.trans List.isSuffix.trans\n\n@[trans]\ntheorem isInfix.trans : \u2200 {l\u2081 l\u2082 l\u2083 : List \u03b1}, l\u2081 <:+: l\u2082 \u2192 l\u2082 <:+: l\u2083 \u2192 l\u2081 <:+: l\u2083\n  | l, _, _, \u27e8l\u2081, r\u2081, rfl\u27e9, \u27e8l\u2082, r\u2082, rfl\u27e9 => \u27e8l\u2082 ++ l\u2081, r\u2081 ++ r\u2082, by simp only [append_assoc]\u27e9\n#align list.is_infix.trans List.isInfix.trans\n\nprotected theorem isInfix.sublist : l\u2081 <:+: l\u2082 \u2192 l\u2081 <+ l\u2082 := fun \u27e8s, t, h\u27e9 => by\n  rw [\u2190 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\u2081 <:+: l\u2082) : l\u2081 \u2286 l\u2082 :=\n  hl.sublist.subset\n#align list.is_infix.subset List.isInfix.subset\n\nprotected theorem isPrefix.sublist (h : l\u2081 <+: l\u2082) : l\u2081 <+ l\u2082 :=\n  h.isInfix.sublist\n#align list.is_prefix.sublist List.isPrefix.sublist\n\nprotected theorem isPrefix.subset (hl : l\u2081 <+: l\u2082) : l\u2081 \u2286 l\u2082 :=\n  hl.sublist.subset\n#align list.is_prefix.subset List.isPrefix.subset\n\nprotected theorem isSuffix.sublist (h : l\u2081 <:+ l\u2082) : l\u2081 <+ l\u2082 :=\n  h.isInfix.sublist\n#align list.is_suffix.sublist List.isSuffix.sublist\n\nprotected theorem isSuffix.subset (hl : l\u2081 <:+ l\u2082) : l\u2081 \u2286 l\u2082 :=\n  hl.sublist.subset\n#align list.is_suffix.subset List.isSuffix.subset\n\n@[simp]\ntheorem reverse_suffix : reverse l\u2081 <:+ reverse l\u2082 \u2194 l\u2081 <+: l\u2082 :=\n  \u27e8fun \u27e8r, e\u27e9 => \u27e8reverse r, by rw [\u2190 reverse_reverse l\u2081, \u2190 reverse_append, e, reverse_reverse]\u27e9,\n    fun \u27e8r, e\u27e9 => \u27e8reverse r, by rw [\u2190 reverse_append, e]\u27e9\u27e9\n#align list.reverse_suffix List.reverse_suffix\n\n@[simp]\ntheorem reverse_prefix : reverse l\u2081 <+: reverse l\u2082 \u2194 l\u2081 <:+ l\u2082 := by\n  rw [\u2190 reverse_suffix]; simp only [reverse_reverse]\n#align list.reverse_prefix List.reverse_prefix\n\n@[simp]\ntheorem reverse_infix : reverse l\u2081 <:+: reverse l\u2082 \u2194 l\u2081 <:+: l\u2082 :=\n  \u27e8fun \u27e8s, t, e\u27e9 =>\n    \u27e8reverse t, reverse s, by\n      rw [\u2190 reverse_reverse l\u2081, append_assoc, \u2190 reverse_append, \u2190 reverse_append, e,\n        reverse_reverse]\u27e9,\n    fun \u27e8s, t, e\u27e9 =>\n    \u27e8reverse t, reverse s, by rw [append_assoc, \u2190 reverse_append, \u2190 reverse_append, e]\u27e9\u27e9\n#align list.reverse_infix List.reverse_infix\n\nalias reverse_prefix \u2194 _ isSuffix.reverse\n#align list.is_suffix.reverse List.isSuffix.reverse\n\nalias reverse_suffix \u2194 _ isPrefix.reverse\n#align list.is_prefix.reverse List.isPrefix.reverse\n\nalias reverse_infix \u2194 _ isInfix.reverse\n#align list.is_infix.reverse List.isInfix.reverse\n\ntheorem isInfix.length_le (h : l\u2081 <:+: l\u2082) : l\u2081.length \u2264 l\u2082.length :=\n  h.sublist.length_le\n#align list.is_infix.length_le List.isInfix.length_le\n\ntheorem isPrefix.length_le (h : l\u2081 <+: l\u2082) : l\u2081.length \u2264 l\u2082.length :=\n  h.sublist.length_le\n#align list.is_prefix.length_le List.isPrefix.length_le\n\ntheorem isSuffix.length_le (h : l\u2081 <:+ l\u2082) : l\u2081.length \u2264 l\u2082.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 <:+: [] \u2194 l = [] :=\n  \u27e8fun h => eq_nil_of_sublist_nil h.sublist, fun h => h \u25b8 infix_rfl\u27e9\n#align list.infix_nil_iff List.infix_nil_iff\n\n@[simp]\ntheorem prefix_nil_iff : l <+: [] \u2194 l = [] :=\n  \u27e8fun h => eq_nil_of_infix_nil h.isInfix, fun h => h \u25b8 prefix_rfl\u27e9\n#align list.prefix_nil_iff List.prefix_nil_iff\n\n@[simp]\ntheorem suffix_nil_iff : l <:+ [] \u2194 l = [] :=\n  \u27e8fun h => eq_nil_of_infix_nil h.isInfix, fun h => h \u25b8 suffix_rfl\u27e9\n#align list.suffix_nil_iff List.suffix_nil_iff\n\nalias prefix_nil_iff \u2194 eq_nil_of_prefix_nil _\n#align list.eq_nil_of_prefix_nil List.eq_nil_of_prefix_nil\n\nalias suffix_nil_iff \u2194 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\u2081 l\u2082 : List \u03b1) : l\u2081 <:+: l\u2082 \u2194 \u2203 t, l\u2081 <+: t \u2227 t <:+ l\u2082 :=\n  \u27e8fun \u27e8s, t, e\u27e9 => \u27e8l\u2081 ++ t, \u27e8_, rfl\u27e9, by rw [\u2190 e, append_assoc]; exact \u27e8_, rfl\u27e9\u27e9,\n    fun \u27e8_, \u27e8t, rfl\u27e9, s, e\u27e9 => \u27e8s, t, by rw [append_assoc]; exact e\u27e9\u27e9\n#align list.infix_iff_prefix_suffix List.infix_iff_prefix_suffix\n\ntheorem eq_of_infix_of_length_eq (h : l\u2081 <:+: l\u2082) : l\u2081.length = l\u2082.length \u2192 l\u2081 = l\u2082 :=\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\u2081 <+: l\u2082) : l\u2081.length = l\u2082.length \u2192 l\u2081 = l\u2082 :=\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\u2081 <:+ l\u2082) : l\u2081.length = l\u2082.length \u2192 l\u2081 = l\u2082 :=\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 : \u2200 { l\u2081 l\u2082 l\u2083 : List \u03b1 } ,\n  l\u2081 <+: l\u2083 \u2192 l\u2082 <+: l\u2083 \u2192 length l\u2081 \u2264 length l\u2082 \u2192 l\u2081 <+: l\u2082\n| [] , l\u2082 , _, _, _, _ => nil_prefix _\n| a :: l\u2081 , b :: l\u2082 , _ , \u27e8 r\u2081 , rfl \u27e9 , \u27e8 r\u2082 , e \u27e9 , ll => by\n  injection e with _ e'\n  subst b\n  rcases prefix_of_prefix_length_le \u27e8 _ , rfl \u27e9 \u27e8 _ , e' \u27e9\n    (le_of_succ_le_succ ll) with \u27e8 r\u2083 , rfl \u27e9\n  exact \u27e8 r\u2083 , rfl \u27e9\n#align list.prefix_of_prefix_length_le List.prefix_of_prefix_length_le\n\ntheorem prefix_or_prefix_of_prefix (h\u2081 : l\u2081 <+: l\u2083) (h\u2082 : l\u2082 <+: l\u2083) : l\u2081 <+: l\u2082 \u2228 l\u2082 <+: l\u2081 :=\n  (le_total (length l\u2081) (length l\u2082)).imp (prefix_of_prefix_length_le h\u2081 h\u2082)\n    (prefix_of_prefix_length_le h\u2082 h\u2081)\n#align list.prefix_or_prefix_of_prefix List.prefix_or_prefix_of_prefix\n\ntheorem suffix_of_suffix_length_le (h\u2081 : l\u2081 <:+ l\u2083) (h\u2082 : l\u2082 <:+ l\u2083) (ll : length l\u2081 \u2264 length l\u2082) :\n    l\u2081 <:+ l\u2082 :=\n  reverse_prefix.1 <|\n    prefix_of_prefix_length_le (reverse_prefix.2 h\u2081) (reverse_prefix.2 h\u2082) (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\u2081 : l\u2081 <:+ l\u2083) (h\u2082 : l\u2082 <:+ l\u2083) : l\u2081 <:+ l\u2082 \u2228 l\u2082 <:+ l\u2081 :=\n  (prefix_or_prefix_of_prefix (reverse_prefix.2 h\u2081) (reverse_prefix.2 h\u2082)).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\u2081 <:+ a :: l\u2082 \u2194 l\u2081 = a :: l\u2082 \u2228 l\u2081 <:+ l\u2082 := by\n  constructor\n  \u00b7 rintro \u27e8\u27e8hd, tl\u27e9, hl\u2083\u27e9\n    \u00b7 exact Or.inl hl\u2083\n    \u00b7 simp only [cons_append] at hl\u2083\n      injection hl\u2083 with _ hl\u2084\n      exact Or.inr \u27e8_, hl\u2084\u27e9\n  \u00b7 rintro (rfl | hl\u2081)\n    \u00b7 exact (a :: l\u2082).suffix_refl\n    \u00b7 exact hl\u2081.trans (l\u2082.suffix_cons _)\n#align list.suffix_cons_iff List.suffix_cons_iff\n\ntheorem infix_cons_iff : l\u2081 <:+: a :: l\u2082 \u2194 l\u2081 <+: a :: l\u2082 \u2228 l\u2081 <:+: l\u2082 := by\n  constructor\n  \u00b7 rintro \u27e8\u27e8hd, tl\u27e9, t, hl\u2083\u27e9\n    \u00b7 exact Or.inl \u27e8t, hl\u2083\u27e9\n    \u00b7 simp only [cons_append] at hl\u2083\n      injection hl\u2083 with _ hl\u2084\n      exact Or.inr \u27e8_, t, hl\u2084\u27e9\n  \u00b7 rintro (h | hl\u2081)\n    \u00b7 exact h.isInfix\n    \u00b7 exact infix_cons hl\u2081\n#align list.infix_cons_iff List.infix_cons_iff\n\ntheorem infix_of_mem_join : \u2200 {L : List (List \u03b1)}, l \u2208 L \u2192 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\u2081 <+: l ++ l\u2082 \u2194 l\u2081 <+: l\u2082 :=\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\u2081 <+: a :: l\u2082 \u2194 l\u2081 <+: l\u2082 :=\n  prefix_append_right_inj [a]\n#align list.prefix_cons_inj List.prefix_cons_inj\n\ntheorem take_prefix (n) (l : List \u03b1) : take n l <+: l :=\n  \u27e8_, take_append_drop _ _\u27e9\n#align list.take_prefix List.take_prefix\n\ntheorem drop_suffix (n) (l : List \u03b1) : drop n l <:+ l :=\n  \u27e8_, take_append_drop _ _\u27e9\n#align list.drop_suffix List.drop_suffix\n\ntheorem take_sublist (n) (l : List \u03b1) : 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 \u03b1) : 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 \u03b1) : take n l \u2286 l :=\n  (take_sublist n l).subset\n#align list.take_subset List.take_subset\n\ntheorem drop_subset (n) (l : List \u03b1) : drop n l \u2286 l :=\n  (drop_sublist n l).subset\n#align list.drop_subset List.drop_subset\n\ntheorem mem_of_mem_take (h : a \u2208 l.take n) : a \u2208 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 : \u2115) (l : List \u03b1) : 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 : \u2115) (l : List \u03b1) : l.dropSlice n m \u2286 l :=\n  (dropSlice_sublist n m l).subset\n#align list.slice_subset List.dropSlice_subset\n\nlemma mem_of_mem_dropSlice {n m : \u2115} {l : List \u03b1} {a : \u03b1} (h : a \u2208 l.dropSlice n m) : a \u2208 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 : \u03b1 \u2192 Bool) : l.takeWhile p <+: l :=\n  \u27e8l.dropWhile p, takeWhile_append_drop p l\u27e9\n#align list.take_while_prefix List.takeWhile_prefix\n\ntheorem dropWhile_suffix (p : \u03b1 \u2192 Bool) : l.dropWhile p <:+ l :=\n  \u27e8l.takeWhile p, takeWhile_append_drop p l\u27e9\n#align list.drop_while_suffix List.dropWhile_suffix\n\ntheorem dropLast_prefix : \u2200 l : List \u03b1, l.dropLast <+: l\n  | [] => \u27e8nil, by rw [dropLast, List.append_nil]\u27e9\n  | a :: l => \u27e8_, dropLast_append_getLast (cons_ne_nil a l)\u27e9\n#align list.init_prefix List.dropLast_prefix\n\ntheorem tail_suffix (l : List \u03b1) : tail l <:+ l := by rw [\u2190 drop_one]; apply drop_suffix\n#align list.tail_suffix List.tail_suffix\n\ntheorem dropLast_sublist (l : List \u03b1) : l.dropLast <+ l :=\n  (dropLast_prefix l).sublist\n#align list.init_sublist List.dropLast_sublist\n\ntheorem tail_sublist (l : List \u03b1) : l.tail <+ l :=\n  (tail_suffix l).sublist\n#align list.tail_sublist List.tail_sublist\n\ntheorem dropLast_subset (l : List \u03b1) : l.dropLast \u2286 l :=\n  (dropLast_sublist l).subset\n#align list.init_subset List.dropLast_subset\n\ntheorem tail_subset (l : List \u03b1) : tail l \u2286 l :=\n  (tail_sublist l).subset\n#align list.tail_subset List.tail_subset\n\ntheorem mem_of_mem_dropLast (h : a \u2208 l.dropLast) : a \u2208 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 \u2208 l.tail) : a \u2208 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\u2081 <+: l\u2082 \u2194 l\u2081 ++ drop (length l\u2081) l\u2082 = l\u2082 :=\n  \u27e8by rintro \u27e8r, rfl\u27e9; rw [drop_left], fun e => \u27e8_, e\u27e9\u27e9\n#align list.prefix_iff_eq_append List.prefix_iff_eq_append\n\ntheorem suffix_iff_eq_append : l\u2081 <:+ l\u2082 \u2194 take (length l\u2082 - length l\u2081) l\u2082 ++ l\u2081 = l\u2082 :=\n  \u27e8by rintro \u27e8r, rfl\u27e9; simp only [length_append, add_tsub_cancel_right, take_left], fun e =>\n    \u27e8_, e\u27e9\u27e9\n#align list.suffix_iff_eq_append List.suffix_iff_eq_append\n\ntheorem prefix_iff_eq_take : l\u2081 <+: l\u2082 \u2194 l\u2081 = take (length l\u2081) l\u2082 :=\n  \u27e8fun h => append_right_cancel <| (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n    fun e => e.symm \u25b8 take_prefix _ _\u27e9\n#align list.prefix_iff_eq_take List.prefix_iff_eq_take\n\ntheorem suffix_iff_eq_drop : l\u2081 <:+ l\u2082 \u2194 l\u2081 = drop (length l\u2082 - length l\u2081) l\u2082 :=\n  \u27e8fun h => append_left_cancel <| (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n    fun e => e.symm \u25b8 drop_suffix _ _\u27e9\n#align list.suffix_iff_eq_drop List.suffix_iff_eq_drop\n\ninstance decidablePrefix [DecidableEq \u03b1] : \u2200 l\u2081 l\u2082 : List \u03b1, Decidable (l\u2081 <+: l\u2082)\n  | [], l\u2082 => isTrue \u27e8l\u2082, rfl\u27e9\n  | a :: l\u2081, [] => isFalse fun \u27e8t, te\u27e9 => List.noConfusion te\n  | a :: l\u2081, b :: l\u2082 =>\n    if h : a = b then\n      @decidable_of_decidable_of_iff _ _ (decidablePrefix l\u2081 l\u2082) (by rw [\u2190 h, prefix_cons_inj])\n    else\n      isFalse fun \u27e8t, te\u27e9 => h <| by injection te\n#align list.decidable_prefix List.decidablePrefix\n\n-- Alternatively, use mem_tails\ninstance decidableSuffix [DecidableEq \u03b1] : \u2200 l\u2081 l\u2082 : List \u03b1, Decidable (l\u2081 <:+ l\u2082)\n  | [], l\u2082 => isTrue \u27e8l\u2082, append_nil _\u27e9\n  | a :: l\u2081, [] => isFalse <| mt (Sublist.length_le \u2218 isSuffix.sublist) (by simp)\n  | l\u2081, b :: l\u2082 =>\n    @decidable_of_decidable_of_iff _ _\n      (@instDecidableOr _ _ _ (l\u2081.decidableSuffix l\u2082))\n      suffix_cons_iff.symm\ntermination_by decidableSuffix l\u2081 l\u2082 => (l\u2081, l\u2082)\n\n#align list.decidable_suffix List.decidableSuffix\n\ninstance decidableInfix [DecidableEq \u03b1] : \u2200 l\u2081 l\u2082 : List \u03b1, Decidable (l\u2081 <:+: l\u2082)\n  | [], l\u2082 => isTrue \u27e8[], l\u2082, rfl\u27e9\n  | a :: l\u2081, [] => isFalse fun \u27e8s, t, te\u27e9 => by simp at te\n  | l\u2081, b :: l\u2082 =>\n    @decidable_of_decidable_of_iff _ _\n      (@instDecidableOr _ _ (l\u2081.decidablePrefix (b :: l\u2082)) (l\u2081.decidableInfix l\u2082))\n      infix_cons_iff.symm\ntermination_by decidableInfix l\u2081 l\u2082 => (l\u2081, l\u2082)\n#align list.decidable_infix List.decidableInfix\n\ntheorem prefix_take_le_iff {L : List (List (Option \u03b1))} (hm : m < L.length) :\n    L.take m <+: L.take n \u2194 m \u2264 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 \u27e8Nat.succ_le_succ, Nat.le_of_succ_le_succ\u27e9\n#align list.prefix_take_le_iff List.prefix_take_le_iff\n\ntheorem cons_prefix_iff : a :: l\u2081 <+: b :: l\u2082 \u2194 a = b \u2227 l\u2081 <+: l\u2082 := by\n  constructor\n  \u00b7 rintro \u27e8L, hL\u27e9\n    simp only [cons_append] at hL\n    injection hL with hLLeft hLRight\n    exact \u27e8hLLeft, \u27e8L, hLRight\u27e9\u27e9\n  \u00b7 rintro \u27e8rfl, h\u27e9\n    rwa [prefix_cons_inj]\n#align list.cons_prefix_iff List.cons_prefix_iff\n\ntheorem isPrefix.map (h : l\u2081 <+: l\u2082) (f : \u03b1 \u2192 \u03b2) : l\u2081.map f <+: l\u2082.map f := by\n  induction' l\u2081 with hd tl hl generalizing l\u2082\n  \u00b7 simp only [nil_prefix, map_nil]\n  \u00b7 cases' l\u2082 with hd\u2082 tl\u2082\n    \u00b7 simpa only using eq_nil_of_prefix_nil h\n    \u00b7 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\u2081 <+: l\u2082) (f : \u03b1 \u2192 Option \u03b2) :\n    l\u2081.filterMap f <+: l\u2082.filterMap f := by\n  induction' l\u2081 with hd\u2081 tl\u2081 hl generalizing l\u2082\n  \u00b7 simp only [nil_prefix, filterMap_nil]\n  \u00b7 cases' l\u2082 with hd\u2082 tl\u2082\n    \u00b7 simpa only using eq_nil_of_prefix_nil h\n    \u00b7 rw [cons_prefix_iff] at h\n      rw [\u2190 @singleton_append _ hd\u2081 _, \u2190 @singleton_append _ hd\u2082 _, 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\u2081 l\u2082 : List (Option \u03b1)} (h : l\u2081 <+: l\u2082) :\n    l\u2081.reduceOption <+: l\u2082.reduceOption :=\n  h.filter_map id\n#align list.is_prefix.reduce_option List.isPrefix.reduceOption\n\ntheorem isPrefix.filter (p : \u03b1 \u2192 Bool) \u2983l\u2081 l\u2082 : List \u03b1\u2984 (h : l\u2081 <+: l\u2082) :\n    l\u2081.filter p <+: l\u2082.filter p := by\n  obtain \u27e8xs, rfl\u27e9 := h\n  rw [filter_append]\n  exact prefix_append _ _\n#align list.is_prefix.filter List.isPrefix.filter\n\ntheorem isSuffix.filter (p : \u03b1 \u2192 Bool) \u2983l\u2081 l\u2082 : List \u03b1\u2984 (h : l\u2081 <:+ l\u2082) :\n    l\u2081.filter p <:+ l\u2082.filter p := by\n  obtain \u27e8xs, rfl\u27e9 := h\n  rw [filter_append]\n  exact suffix_append _ _\n#align list.is_suffix.filter List.isSuffix.filter\n\ntheorem isInfix.filter (p : \u03b1 \u2192 Bool) \u2983l\u2081 l\u2082 : List \u03b1\u2984 (h : l\u2081 <:+: l\u2082) :\n    l\u2081.filter p <:+: l\u2082.filter p := by\n  obtain \u27e8xs, ys, rfl\u27e9 := h\n  rw [filter_append, filter_append]\n  exact infix_append _ _ _\n#align list.is_infix.filter List.isInfix.filter\n\ninstance : IsPartialOrder (List \u03b1) (\u00b7 <+: \u00b7) where\n  refl := prefix_refl\n  trans _ _ _ := isPrefix.trans\n  antisymm _ _ h\u2081 h\u2082 := eq_of_prefix_of_length_eq h\u2081 <| h\u2081.length_le.antisymm h\u2082.length_le\n\ninstance : IsPartialOrder (List \u03b1) (\u00b7 <:+ \u00b7) where\n  refl := suffix_refl\n  trans _ _ _ := isSuffix.trans\n  antisymm _ _ h\u2081 h\u2082 := eq_of_suffix_of_length_eq h\u2081 <| h\u2081.length_le.antisymm h\u2082.length_le\n\ninstance : IsPartialOrder (List \u03b1) (\u00b7 <:+: \u00b7) where\n  refl := infix_refl\n  trans _ _ _ := isInfix.trans\n  antisymm _ _ h\u2081 h\u2082 := eq_of_infix_of_length_eq h\u2081 <| h\u2081.length_le.antisymm h\u2082.length_le\n\nend Fix\n\nsection InitsTails\n\n@[simp]\ntheorem mem_inits : \u2200 s t : List \u03b1, s \u2208 inits t \u2194 s <+: t\n  | s, [] =>\n    suffices s = nil \u2194 s <+: nil by simpa only [inits, mem_singleton]\n    \u27e8fun h => h.symm \u25b8 prefix_refl [], eq_nil_of_prefix_nil\u27e9\n  | s, a :: t =>\n    suffices (s = nil \u2228 \u2203 l \u2208 inits t, a :: l = s) \u2194 s <+: a :: t by simpa\n    \u27e8fun o =>\n      match s, o with\n      | _, Or.inl rfl => \u27e8_, rfl\u27e9\n      | s, Or.inr \u27e8r, hr, hs\u27e9 => by\n        let \u27e8s, ht\u27e9 := (mem_inits _ _).1 hr\n        rw [\u2190 hs, \u2190 ht]; exact \u27e8s, rfl\u27e9,\n      fun mi =>\n      match s, mi with\n      | [], \u27e8_, rfl\u27e9 => Or.inl rfl\n      | b :: s, \u27e8r, hr\u27e9 =>\n        (List.noConfusion hr) fun ba (st : s ++ r = t) =>\n          Or.inr <| by rw [ba]; exact \u27e8_, (mem_inits _ _).2 \u27e8_, st\u27e9, rfl\u27e9\u27e9\n#align list.mem_inits List.mem_inits\n\n@[simp]\ntheorem mem_tails : \u2200 s t : List \u03b1, s \u2208 tails t \u2194 s <:+ t\n  | s, [] => by\n    simp only [tails, mem_singleton]\n    exact \u27e8fun h => by rw [h], eq_nil_of_suffix_nil\u27e9\n  | s, a :: t => by\n    simp only [tails, mem_cons, mem_tails s t];\n    exact\n      show s = a :: t \u2228 s <:+ t \u2194 s <:+ a :: t from\n        \u27e8fun o =>\n          match s, t, o with\n          | _, t, Or.inl rfl => suffix_rfl\n          | s, _, Or.inr \u27e8l, rfl\u27e9 => \u27e8a :: l, rfl\u27e9,\n          fun e =>\n          match s, t, e with\n          | _, t, \u27e8[], rfl\u27e9 => Or.inl rfl\n          | s, t, \u27e8b :: l, he\u27e9 => List.noConfusion he fun _ lt => Or.inr \u27e8l, lt\u27e9\u27e9\n#align list.mem_tails List.mem_tails\n\ntheorem inits_cons (a : \u03b1) (l : List \u03b1) : 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 : \u03b1) (l : List \u03b1) : tails (a :: l) = (a :: l) :: l.tails := by simp\n#align list.tails_cons List.tails_cons\n\n@[simp]\ntheorem inits_append : \u2200 s t : List \u03b1, inits (s ++ t) = s.inits ++ t.inits.tail.map fun l => s ++ l\n  | [], [] => by simp\n  | [], a :: t => by simp[\u00b7 \u2218 \u00b7]\n  | a :: s, t => by simp [inits_append s t, \u00b7 \u2218 \u00b7]\n#align list.inits_append List.inits_append\n\n@[simp]\ntheorem tails_append :\n    \u2200 s t : List \u03b1, 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 : \u2200 l : List \u03b1, 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 : \u2200 l : List \u03b1, 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : 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 \u03b1) : length (tails l) = length l + 1 := by\n  induction' l with x l IH\n  \u00b7 simp\n  \u00b7 simpa using IH\n#align list.length_tails List.length_tails\n\n@[simp]\ntheorem length_inits (l : List \u03b1) : 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 \u03b1) (n : \u2115) (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  \u00b7 simp\n  \u00b7 cases n\n    \u00b7 simp[nthLe_cons]\n    \u00b7 simpa[nthLe_cons] using IH _ _\n#align list.nth_le_tails List.nth_le_tails\n\n@[simp]\ntheorem nth_le_inits (l : List \u03b1) (n : \u2115) (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  \u00b7 simp\n  \u00b7 cases n\n    \u00b7 simp[nthLe_cons]\n    \u00b7 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 \u03b1]\n\n@[simp]\ntheorem insert_nil (a : \u03b1) : insert a nil = [a] :=\n  rfl\n#align list.insert_nil List.insert_nil\n\ntheorem insert.def (a : \u03b1) (l : List \u03b1) : insert a l = if a \u2208 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 : \u03b1) (l : List \u03b1) : l <:+ l.insert a := by\n  by_cases h : a \u2208 l\n  \u00b7 simp only [insert_of_mem h, insert, suffix_refl]\n  \u00b7 simp only [insert_of_not_mem h, suffix_cons, insert]\n\n#align list.suffix_insert List.suffix_insert\n\ntheorem infix_insert (a : \u03b1) (l : List \u03b1) : l <:+: l.insert a :=\n  (suffix_insert a l).isInfix\n#align list.infix_insert List.infix_insert\n\ntheorem sublist_insert (a : \u03b1) (l : List \u03b1) : l <+ l.insert a :=\n  (suffix_insert a l).sublist\n#align list.sublist_insert List.sublist_insert\n\ntheorem subset_insert (a : \u03b1) (l : List \u03b1) : l \u2286 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 \u2208 l\u2081) (hl : l\u2081 <:+ l\u2082) : a \u2208 l\u2082 :=\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 tactic.solve_by_elim\nimport tactic.interactive\n\nnamespace tactic\n\nnamespace hint\n\n/-- An attribute marking a `tactic unit` or `tactic string` which should be used by the `hint`\ntactic. -/\n@[user_attribute] meta def hint_tactic_attribute : user_attribute :=\n{ name := `hint_tactic,\n  descr := \"A tactic that should be tried by `hint`.\" }\n\nadd_tactic_doc\n{ name                     := \"hint_tactic\",\n  category                 := doc_category.attr,\n  decl_names               := [`tactic.hint.hint_tactic_attribute],\n  tags                     := [\"rewrite\", \"search\"] }\n\nsetup_tactic_parser\n\nprivate meta def add_tactic_hint (n : name) (t : expr) : tactic unit :=\ndo\n  add_decl $ declaration.defn n [] `(tactic string) t reducibility_hints.opaque ff,\n  hint_tactic_attribute.set n () tt\n\n/--\n`add_hint_tactic t` runs the tactic `t` whenever `hint` is invoked.\nThe typical use case is `add_hint_tactic \"foo\"` for some interactive tactic `foo`.\n-/\n@[user_command] meta def add_hint_tactic (_ : parse (tk \"add_hint_tactic\")) : parser unit :=\ndo n \u2190 parser.pexpr,\n   e \u2190 to_expr n,\n   s \u2190 eval_expr string e,\n   let t := \"`[\" ++ s ++ \"]\",\n   (t, _) \u2190 with_input parser.pexpr t,\n   of_tactic $ do\n   let h := s <.> \"_hint\",\n   t \u2190 to_expr ``(do %%t, pure %%n),\n   add_tactic_hint h t.\n\nadd_tactic_doc\n{ name                     := \"add_hint_tactic\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.hint.add_hint_tactic],\n  tags                     := [\"search\"] }\n\nadd_hint_tactic \"refl\"\nadd_hint_tactic \"exact dec_trivial\"\nadd_hint_tactic \"assumption\"\n-- tidy does something better here: it suggests the actual \"intros X Y f\" string.\n-- perhaps add a wrapper?\nadd_hint_tactic \"intro\"\nadd_hint_tactic \"apply_auto_param\"\nadd_hint_tactic \"dsimp at *\"\nadd_hint_tactic \"simp at *\" -- TODO hook up to squeeze_simp?\nadd_hint_tactic \"fconstructor\"\nadd_hint_tactic \"injections_and_clear\"\nadd_hint_tactic \"solve_by_elim\"\nadd_hint_tactic \"unfold_coes\"\nadd_hint_tactic \"unfold_aux\"\n\nend hint\n\n/--\nReport a list of tactics that can make progress against the current goal,\nand for each such tactic, the number of remaining goals afterwards.\n-/\nmeta def hint : tactic (list (string \u00d7 \u2115)) :=\ndo\n  names \u2190 attribute.get_instances `hint_tactic,\n  focus1 $ try_all_sorted (names.reverse.map name_to_tactic)\n\nnamespace interactive\n\n/--\nReport a list of tactics that can make progress against the current goal.\n-/\nmeta def hint : tactic unit :=\ndo\n  hints \u2190 tactic.hint,\n  if hints.length = 0 then\n    fail \"no hints available\"\n  else do\n    t \u2190 hints.nth 0,\n    if t.2 = 0 then do\n      trace \"the following tactics solve the goal:\\n----\",\n      (hints.filter (\u03bb p : string \u00d7 \u2115, p.2 = 0)).mmap' (\u03bb p, tactic.trace format!\"Try this: {p.1}\")\n    else do\n      trace \"the following tactics make progress:\\n----\",\n      hints.mmap' (\u03bb p, tactic.trace format!\"Try this: {p.1}\")\n\n/--\n`hint` lists possible tactics which will make progress (that is, not fail) against the current goal.\n\n```lean\nexample {P Q : Prop} (p : P) (h : P \u2192 Q) : Q :=\nbegin\n  hint,\n  /- the following tactics make progress:\n     ----\n     Try this: solve_by_elim\n     Try this: finish\n     Try this: tauto\n  -/\n  solve_by_elim,\nend\n```\n\nYou can add a tactic to the list that `hint` tries by either using\n1. `attribute [hint_tactic] my_tactic`, if `my_tactic` is already of type `tactic string`\n(`tactic unit` is allowed too, in which case the printed string will be the name of the\ntactic), or\n2. `add_hint_tactic \"my_tactic\"`, specifying a string which works as an interactive tactic.\n-/\nadd_tactic_doc\n{ name        := \"hint\",\n  category    := doc_category.tactic,\n  decl_names  := [`tactic.interactive.hint],\n  tags        := [\"search\", \"Try this\"] }\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/hint.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943704494217, "lm_q2_score": 0.12940272151925927, "lm_q1q2_score": 0.040204697096868094}}
{"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 \u27e8\u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9\u27e9,\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\u27e8\u27e8of punit, is_zero_of_subsingleton _\u27e9\u27e9\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 \u27e8\u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e81\u27e9, \u03bb f, _\u27e9\u27e9\u27e9,\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\u27e8\u27e8of punit, is_zero_of_subsingleton _\u27e9\u27e9\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 {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := 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, `(\u00b7<\u00b7)` is the less-than relation,\nand `flip (\u00b7<\u00b7)` is the greater-than relation.\n-/\n@[inline] def flip {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) : \u03b2 \u2192 \u03b1 \u2192 \u03c6 :=\n  fun b a => f a b\n\n@[simp] theorem Function.const_apply {y : \u03b2} {x : \u03b1} : const \u03b1 y x = y := rfl\n\n@[simp] theorem Function.comp_apply {f : \u03b2 \u2192 \u03b4} {g : \u03b1 \u2192 \u03b2} {x : \u03b1} : 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 (\u03b1 : Type u) : Type u where\n  /-- Constructs a new thunk from a function `Unit \u2192 \u03b1`\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 \u2192 \u03b1\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 : \u03b1) : Thunk \u03b1 :=\n  \u27e8fun _ => a\u27e9\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 \u03b1) : \u03b1 :=\n  x.fn ()\n\n/-- Map a function over a thunk. -/\n@[inline] protected def Thunk.map (f : \u03b1 \u2192 \u03b2) (x : Thunk \u03b1) : Thunk \u03b2 :=\n  \u27e8fun _ => f x.get\u27e9\n/-- Constructs a thunk that applies `f` to the result of `x` when forced. -/\n@[inline] protected def Thunk.bind (x : Thunk \u03b1) (f : \u03b1 \u2192 Thunk \u03b2) : Thunk \u03b2 :=\n  \u27e8fun _ => (f x.get).get\u27e9\n\n@[simp] theorem Thunk.sizeOf_eq [SizeOf \u03b1] (a : Thunk \u03b1) : sizeOf a = 1 + sizeOf a.get := by\n   cases a; rfl\n\ninstance thunkCoe : CoeTail \u03b1 (Thunk \u03b1) where\n  -- Since coercions are expanded eagerly, `a` is evaluated lazily.\n  coe a := \u27e8fun _ => a\u27e9\n\n/-- A variation on `Eq.ndrec` with the equality argument first. -/\nabbrev Eq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} {b : \u03b1} (h : a = b) (m : motive a) : motive b :=\n  Eq.ndrec m h\n\n/--\nIf and only if, or logical bi-implication. `a \u2194 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 \u2192 b` and `b \u2192 a` then `a` and `b` are equivalent. -/\n  intro ::\n  /-- Modus ponens for if and only if. If `a \u2194 b` and `a`, then `b`. -/\n  mp : a \u2192 b\n  /-- Modus ponens for if and only if, reversed. If `a \u2194 b` and `b`, then `a`. -/\n  mpr : b \u2192 a\n\n@[inherit_doc] infix:20 \" <-> \" => Iff\n@[inherit_doc] infix:20 \" \u2194 \"   => Iff\n\n/--\n`Sum \u03b1 \u03b2`, or `\u03b1 \u2295 \u03b2`, is the disjoint union of types `\u03b1` and `\u03b2`.\nAn element of `\u03b1 \u2295 \u03b2` is either of the form `.inl a` where `a : \u03b1`,\nor `.inr b` where `b : \u03b2`.\n-/\ninductive Sum (\u03b1 : Type u) (\u03b2 : Type v) where\n  /-- Left injection into the sum type `\u03b1 \u2295 \u03b2`. If `a : \u03b1` then `.inl a : \u03b1 \u2295 \u03b2`. -/\n  | inl (val : \u03b1) : Sum \u03b1 \u03b2\n  /-- Right injection into the sum type `\u03b1 \u2295 \u03b2`. If `b : \u03b2` then `.inr b : \u03b1 \u2295 \u03b2`. -/\n  | inr (val : \u03b2) : Sum \u03b1 \u03b2\n\n@[inherit_doc] infixr:30 \" \u2295 \" => Sum\n\n/--\n`PSum \u03b1 \u03b2`, or `\u03b1 \u2295' \u03b2`, is the disjoint union of types `\u03b1` and `\u03b2`.\nIt differs from `\u03b1 \u2295 \u03b2` in that it allows `\u03b1` and `\u03b2` 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 \u2295' 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 (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  /-- Left injection into the sum type `\u03b1 \u2295' \u03b2`. If `a : \u03b1` then `.inl a : \u03b1 \u2295' \u03b2`. -/\n  | inl (val : \u03b1) : PSum \u03b1 \u03b2\n  /-- Right injection into the sum type `\u03b1 \u2295' \u03b2`. If `b : \u03b2` then `.inr b : \u03b1 \u2295' \u03b2`. -/\n  | inr (val : \u03b2) : PSum \u03b1 \u03b2\n\n@[inherit_doc] infixr:30 \" \u2295' \" => PSum\n\n/--\n`Sigma \u03b2`, also denoted `\u03a3 a : \u03b1, \u03b2 a` or `(a : \u03b1) \u00d7 \u03b2 a`, is the type of dependent pairs\nwhose first component is `a : \u03b1` and whose second component is `b : \u03b2 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 {\u03b1 : Type u} (\u03b2 : \u03b1 \u2192 Type v) where\n  /-- Constructor for a dependent pair. If `a : \u03b1` and `b : \u03b2 a` then `\u27e8a, b\u27e9 : Sigma \u03b2`.\n  (This will usually require a type ascription to determine `\u03b2`\n  since it is not determined from `a` and `b` alone.) -/\n  mk ::\n  /-- The first component of a dependent pair. If `p : @Sigma \u03b1 \u03b2` then `p.1 : \u03b1`. -/\n  fst : \u03b1\n  /-- The second component of a dependent pair. If `p : Sigma \u03b2` then `p.2 : \u03b2 p.1`. -/\n  snd : \u03b2 fst\n\nattribute [unbox] Sigma\n\n/--\n`PSigma \u03b2`, also denoted `\u03a3' a : \u03b1, \u03b2 a` or `(a : \u03b1) \u00d7' \u03b2 a`, is the type of dependent pairs\nwhose first component is `a : \u03b1` and whose second component is `b : \u03b2 a`\n(so the type of the second component can depend on the value of the first component).\nIt differs from `\u03a3 a : \u03b1, \u03b2 a` in that it allows `\u03b1` and `\u03b2` 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) \u00d7' 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 {\u03b1 : Sort u} (\u03b2 : \u03b1 \u2192 Sort v) where\n  /-- Constructor for a dependent pair. If `a : \u03b1` and `b : \u03b2 a` then `\u27e8a, b\u27e9 : PSigma \u03b2`.\n  (This will usually require a type ascription to determine `\u03b2`\n  since it is not determined from `a` and `b` alone.) -/\n  mk ::\n  /-- The first component of a dependent pair. If `p : @Sigma \u03b1 \u03b2` then `p.1 : \u03b1`. -/\n  fst : \u03b1\n  /-- The second component of a dependent pair. If `p : Sigma \u03b2` then `p.2 : \u03b2 p.1`. -/\n  snd : \u03b2 fst\n\n/--\nExistential quantification. If `p : \u03b1 \u2192 Prop` is a predicate, then `\u2203 x : \u03b1, p x`\nasserts that there is some `x` of type `\u03b1` such that `p x` holds.\nTo create an existential proof, use the `exists` tactic,\nor the anonymous constructor notation `\u27e8x, h\u27e9`.\nTo unpack an existential, use `cases h` where `h` is a proof of `\u2203 x : \u03b1, p x`,\nor `let \u27e8x, hx\u27e9 := 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 : \u2203 x : Nat, x = x) : Nat :=\n  let \u27e8x, _\u27e9 := 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 : \u2203 x : Nat, x = x) : True :=\n  let \u27e8x, _\u27e9 := h  -- ok, because the goal is `True : Prop`\n  trivial\n```\n-/\ninductive Exists {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) : Prop where\n  /-- Existential introduction. If `a : \u03b1` and `h : p a`,\n  then `\u27e8a, h\u27e9` is a proof that `\u2203 x : \u03b1, p x`. -/\n  | intro (w : \u03b1) (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 : \u03b1)`, 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 : \u03b1)`, 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 (\u03b1 : 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  : \u03b1 \u2192 ForInStep \u03b1\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 : \u03b1 \u2192 ForInStep \u03b1\n  deriving Inhabited\n\n/--\n`ForIn m \u03c1 \u03b1` is the typeclass which supports `for x in xs` notation.\nHere `xs : \u03c1` is the type of the collection to iterate over, `x : \u03b1`\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\u2081 \u2192 Type u\u2082) (\u03c1 : Type u) (\u03b1 : outParam (Type v)) where\n  /-- `forIn x b f : m \u03b2` runs a for-loop in the monad `m` with additional state `\u03b2`.\n  This traverses over the \"contents\" of `x`, and passes the elements `a : \u03b1` to\n  `f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)`. `b : \u03b2` 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 \u2190 foo x b\n  ```\n  in a `do` block is syntactic sugar for:\n  ```\n  let b := ...\n  let b \u2190 forIn xs b (fun x b => do\n    let b \u2190 foo x b\n    return .yield b)\n  ```\n  (Here `b` corresponds to the variables mutated in the loop.) -/\n  forIn {\u03b2} [Monad m] (x : \u03c1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2\n\nexport ForIn (forIn)\n\n/--\n`ForIn' m \u03c1 \u03b1 d` is a variation on the `ForIn m \u03c1 \u03b1` typeclass which supports the\n`for h : x in xs` notation. It is the same as `for x in xs` except that `h : x \u2208 xs`\nis provided as an additional argument to the body of the for-loop.\n-/\nclass ForIn' (m : Type u\u2081 \u2192 Type u\u2082) (\u03c1 : Type u) (\u03b1 : outParam (Type v)) (d : outParam $ Membership \u03b1 \u03c1) where\n  /-- `forIn' x b f : m \u03b2` runs a for-loop in the monad `m` with additional state `\u03b2`.\n  This traverses over the \"contents\" of `x`, and passes the elements `a : \u03b1` along\n  with a proof that `a \u2208 x` to `f : (a : \u03b1) \u2192 a \u2208 x \u2192 \u03b2 \u2192 m (ForInStep \u03b2)`.\n  `b : \u03b2` 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' {\u03b2} [Monad m] (x : \u03c1) (b : \u03b2) (f : (a : \u03b1) \u2192 a \u2208 x \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2\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 : \u03b1) s` means that the block exited normally with return value `a`.\n* `return (b : \u03b2) 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 : \u03c3` which bundles all the mutable variables of the do-block.\n-/\ninductive DoResultPRBC (\u03b1 \u03b2 \u03c3 : Type u) where\n  /-- `pure (a : \u03b1) s` means that the block exited normally with return value `a` -/\n  | pure : \u03b1 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  /-- `return (b : \u03b2) s` means that the block exited via a `return b` early-exit command -/\n  | return : \u03b2 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  /-- `break s` means that `break` was called, meaning that we should exit\n  from the containing loop -/\n  | break : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  /-- `continue s` means that `continue` was called, meaning that we should continue\n  to the next iteration of the containing loop -/\n  | continue : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n\n/--\nAuxiliary type used to compile `do` notation. It is the same as\n`DoResultPRBC \u03b1 \u03b2 \u03c3` except that `break` and `continue` are not available\nbecause we are not in a loop context.\n-/\ninductive DoResultPR (\u03b1 \u03b2 \u03c3 : Type u) where\n  /-- `pure (a : \u03b1) s` means that the block exited normally with return value `a` -/\n  | pure   : \u03b1 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n  /-- `return (b : \u03b2) s` means that the block exited via a `return b` early-exit command -/\n  | return : \u03b2 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n\n/--\nAuxiliary type used to compile `do` notation. It is an optimization of\n`DoResultPRBC PEmpty PEmpty \u03c3` to remove the impossible cases,\nused when neither `pure` nor `return` are possible exit paths.\n-/\ninductive DoResultBC (\u03c3 : Type u) where\n  /-- `break s` means that `break` was called, meaning that we should exit\n  from the containing loop -/\n  | break    : \u03c3 \u2192 DoResultBC \u03c3\n  /-- `continue s` means that `continue` was called, meaning that we should continue\n  to the next iteration of the containing loop -/\n  | continue : \u03c3 \u2192 DoResultBC \u03c3\n\n/--\nAuxiliary type used to compile `do` notation. It is an optimization of\neither `DoResultPRBC \u03b1 PEmpty \u03c3` or `DoResultPRBC PEmpty \u03b1 \u03c3` to remove the\nimpossible case, used when either `pure` or `return` is never used.\n-/\ninductive DoResultSBC (\u03b1 \u03c3 : Type u) where\n  /-- This encodes either `pure (a : \u03b1)` or `return (a : \u03b1)`:\n  * `pure (a : \u03b1) s` means that the block exited normally with return value `a`\n  * `return (b : \u03b2) 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 : \u03b1 \u2192 \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  /-- `break s` means that `break` was called, meaning that we should exit\n  from the containing loop -/\n  | break    : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  /-- `continue s` means that `continue` was called, meaning that we should continue\n  to the next iteration of the containing loop -/\n  | continue   : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n\n/-- `HasEquiv \u03b1` is the typeclass which supports the notation `x \u2248 y` where `x y : \u03b1`.-/\nclass HasEquiv (\u03b1 : Sort u) where\n  /-- `x \u2248 y` says that `x` and `y` are equivalent. Because this is a typeclass,\n  the notion of equivalence is type-dependent. -/\n  Equiv : \u03b1 \u2192 \u03b1 \u2192 Sort v\n\n@[inherit_doc] infix:50 \" \u2248 \"  => HasEquiv.Equiv\n\n/-- `EmptyCollection \u03b1` is the typeclass which supports the notation `\u2205`, also written as `{}`. -/\nclass EmptyCollection (\u03b1 : Type u) where\n  /-- `\u2205` or `{}` is the empty set or empty collection.\n  It is supported by the `EmptyCollection` typeclass. -/\n  emptyCollection : \u03b1\n\n@[inherit_doc] notation \"{\" \"}\" => EmptyCollection.emptyCollection\n@[inherit_doc] notation \"\u2205\"     => EmptyCollection.emptyCollection\n\n/--\n`Task \u03b1` is a primitive for asynchronous computation.\nIt represents a computation that will resolve to a value of type `\u03b1`,\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 (\u03b1 : Type u) : Type u where\n  /-- `Task.pure (a : \u03b1)` constructs a task that is already resolved with value `a`. -/\n  pure ::\n  /-- If `task : Task \u03b1` then `task.get : \u03b1` blocks the current thread until the\n  value is available, and then returns the result of the task. -/\n  get : \u03b1\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 \u03b1` constructs and immediately launches a new task for\nevaluating the function `fn () : \u03b1` asynchronously.\n\n`prio`, if provided, is the priority of the task.\n-/\n@[noinline, extern \"lean_task_spawn\"]\nprotected def spawn {\u03b1 : Type u} (fn : Unit \u2192 \u03b1) (prio := Priority.default) : Task \u03b1 :=\n  \u27e8fn ()\u27e9\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 {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (x : Task \u03b1) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8f x.get\u27e9\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 {\u03b1 : Type u} {\u03b2 : Type v} (x : Task \u03b1) (f : \u03b1 \u2192 Task \u03b2) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8(f x.get).get\u27e9\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 (\u03b1 : Sort u) (default : \u03b1) : optParam \u03b1 default = \u03b1 := 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\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\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\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\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 \u2260 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 {\u03b1 : Type u} [BEq \u03b1] (a b : \u03b1) : Bool :=\n  !(a == b)\n\n@[inherit_doc] infix:50 \" != \" => bne\n\n/--\n`LawfulBEq \u03b1` is a typeclass which asserts that the `BEq \u03b1` 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 (\u03b1 : Type u) [BEq \u03b1] : Prop where\n  /-- If `a == b` evaluates to `true`, then `a` and `b` are equal in the logic. -/\n  eq_of_beq : {a b : \u03b1} \u2192 a == b \u2192 a = b\n  /-- `==` is reflexive, that is, `(a == a) = true`. -/\n  protected rfl : {a : \u03b1} \u2192 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 \u03b1] : LawfulBEq \u03b1 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 := \u27e8\u27e9\n\ntheorem mt {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : \u00acb) : \u00aca :=\n  fun ha => h\u2082 (h\u2081 ha)\n\ntheorem not_false : \u00acFalse := id\n\ntheorem not_not_intro {p : Prop} (h : p) : \u00ac \u00ac p :=\n  fun hn : \u00ac p => hn h\n\n-- proof irrelevance is built in\ntheorem proofIrrel {a : Prop} (h\u2081 h\u2082 : a) : h\u2081 = h\u2082 := rfl\n\ntheorem id.def {\u03b1 : Sort u} (a : \u03b1) : id a = a := rfl\n\n/--\nIf `h : \u03b1 = \u03b2` is a proof of type equality, then `h.mp : \u03b1 \u2192 \u03b2` is the induced\n\"cast\" operation, mapping elements of `\u03b1` to elements of `\u03b2`.\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 {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (a : \u03b1) : \u03b2 :=\n  h \u25b8 a\n\n/--\nIf `h : \u03b1 = \u03b2` is a proof of type equality, then `h.mpr : \u03b2 \u2192 \u03b1` is the induced\n\"cast\" operation in the reverse direction, mapping elements of `\u03b2` to elements of `\u03b1`.\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 {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (b : \u03b2) : \u03b1 :=\n  h \u25b8 b\n\n@[elab_as_elim]\ntheorem Eq.substr {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : b = a) (h\u2082 : p a) : p b :=\n  h\u2081 \u25b8 h\u2082\n\ntheorem cast_eq {\u03b1 : Sort u} (h : \u03b1 = \u03b1) (a : \u03b1) : cast h a = a :=\n  rfl\n\n/--\n`a \u2260 b`, or `Ne a b` is defined as `\u00ac (a = b)` or `a = b \u2192 False`,\nand asserts that `a` and `b` are not equal.\n-/\n@[reducible] def Ne {\u03b1 : Sort u} (a b : \u03b1) :=\n  \u00ac(a = b)\n\n@[inherit_doc] infix:50 \" \u2260 \"  => Ne\n\nsection Ne\nvariable {\u03b1 : Sort u}\nvariable {a b : \u03b1} {p : Prop}\n\ntheorem Ne.intro (h : a = b \u2192 False) : a \u2260 b := h\n\ntheorem Ne.elim (h : a \u2260 b) : a = b \u2192 False := h\n\ntheorem Ne.irrefl (h : a \u2260 a) : False := h rfl\n\ntheorem Ne.symm (h : a \u2260 b) : b \u2260 a :=\n  fun h\u2081 => h (h\u2081.symm)\n\ntheorem false_of_ne : a \u2260 a \u2192 False := Ne.irrefl\n\ntheorem ne_false_of_self : p \u2192 p \u2260 False :=\n  fun (hp : p) (h : p = False) => h \u25b8 hp\n\ntheorem ne_true_of_not : \u00acp \u2192 p \u2260 True :=\n  fun (hnp : \u00acp) (h : p = True) =>\n    have : \u00acTrue := h \u25b8 hnp\n    this trivial\n\ntheorem true_ne_false : \u00acTrue = False :=\n  ne_false_of_self trivial\n\nend Ne\n\ntheorem Bool.of_not_eq_true : {b : Bool} \u2192 \u00ac (b = true) \u2192 b = false\n  | true,  h => absurd rfl h\n  | false, _ => rfl\n\ntheorem Bool.of_not_eq_false : {b : Bool} \u2192 \u00ac (b = false) \u2192 b = true\n  | true,  _ => rfl\n  | false, h => absurd rfl h\n\ntheorem ne_of_beq_false [BEq \u03b1] [LawfulBEq \u03b1] {a b : \u03b1} (h : (a == b) = false) : a \u2260 b := by\n  intro h'; subst h'; have : true = false := Eq.trans LawfulBEq.rfl.symm h; contradiction\n\ntheorem beq_false_of_ne [BEq \u03b1] [LawfulBEq \u03b1] {a b : \u03b1} (h : a \u2260 b) : (a == b) = false :=\n  have : \u00ac (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 {\u03b1 \u03b2 \u03c6 : Sort u} {a a' : \u03b1} {b b' : \u03b2} {c : \u03c6}\n\ntheorem HEq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} (m : motive a) {\u03b2 : Sort u2} {b : \u03b2} (h : HEq a b) : motive b :=\n  h.rec m\n\ntheorem HEq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} {\u03b2 : Sort u2} {b : \u03b2} (h : HEq a b) (m : motive a) : motive b :=\n  h.rec m\n\ntheorem HEq.elim {\u03b1 : Sort u} {a : \u03b1} {p : \u03b1 \u2192 Sort v} {b : \u03b1} (h\u2081 : HEq a b) (h\u2082 : p a) : p b :=\n  eq_of_heq h\u2081 \u25b8 h\u2082\n\ntheorem HEq.subst {p : (T : Sort u) \u2192 T \u2192 Prop} (h\u2081 : HEq a b) (h\u2082 : p \u03b1 a) : p \u03b2 b :=\n  HEq.ndrecOn h\u2081 h\u2082\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\u2081 : HEq a b) (h\u2082 : HEq b c) : HEq a c :=\n  HEq.subst h\u2082 h\u2081\n\ntheorem heq_of_heq_of_eq (h\u2081 : HEq a b) (h\u2082 : b = b') : HEq a b' :=\n  HEq.trans h\u2081 (heq_of_eq h\u2082)\n\ntheorem heq_of_eq_of_heq (h\u2081 : a = a') (h\u2082 : HEq a' b) : HEq a b :=\n  HEq.trans (heq_of_eq h\u2081) h\u2082\n\ntheorem type_eq_of_heq (h : HEq a b) : \u03b1 = \u03b2 :=\n  h.rec (Eq.refl \u03b1)\n\nend\n\ntheorem eqRec_heq {\u03b1 : Sort u} {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} : (h : a = a') \u2192 (p : \u03c6 a) \u2192 HEq (Eq.recOn (motive := fun x _ => \u03c6 x) h p) p\n  | rfl, p => HEq.refl p\n\ntheorem heq_of_eqRec_eq {\u03b1 \u03b2 : Sort u} {a : \u03b1} {b : \u03b2} (h\u2081 : \u03b1 = \u03b2) (h\u2082 : Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\u2081 = b) : HEq a b := by\n  subst h\u2081\n  apply heq_of_eq\n  exact h\u2082\n\ntheorem cast_heq {\u03b1 \u03b2 : Sort u} : (h : \u03b1 = \u03b2) \u2192 (a : \u03b1) \u2192 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 \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 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 \u2194 a :=\n  Iff.intro (fun h => h) (fun h => h)\n\nprotected theorem Iff.rfl {a : Prop} : a \u2194 a :=\n  Iff.refl a\n\ntheorem Iff.trans (h\u2081 : a \u2194 b) (h\u2082 : b \u2194 c) : a \u2194 c :=\n  Iff.intro\n    (fun ha => Iff.mp h\u2082 (Iff.mp h\u2081 ha))\n    (fun hc => Iff.mpr h\u2081 (Iff.mpr h\u2082 hc))\n\ntheorem Iff.symm (h : a \u2194 b) : b \u2194 a :=\n  Iff.intro (Iff.mpr h) (Iff.mp h)\n\ntheorem Iff.comm : (a \u2194 b) \u2194 (b \u2194 a) :=\n  Iff.intro Iff.symm Iff.symm\n\ntheorem Iff.of_eq (h : a = b) : a \u2194 b :=\n  h \u25b8 Iff.refl _\n\ntheorem And.comm : a \u2227 b \u2194 b \u2227 a := by\n  constructor <;> intro \u27e8h\u2081, h\u2082\u27e9 <;> exact \u27e8h\u2082, h\u2081\u27e9\n\n/-! # Exists -/\n\ntheorem Exists.elim {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {b : Prop}\n   (h\u2081 : Exists (fun x => p x)) (h\u2082 : \u2200 (a : \u03b1), p a \u2192 b) : b :=\n  match h\u2081 with\n  | intro a h => h\u2082 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 \u27e8\u27e9\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) : \u00ac 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 \u2192 q) (h2 : \u00acp \u2192 q) : q :=\n  match dec with\n  | isTrue h  => h1 h\n  | isFalse h => h2 h\n\ntheorem em (p : Prop) [Decidable p] : p \u2228 \u00acp :=\n  byCases Or.inl Or.inr\n\nset_option linter.unusedVariables.funArgs false in\ntheorem byContradiction [dec : Decidable p] (h : \u00acp \u2192 False) : p :=\n  byCases id (fun np => False.elim (h np))\n\ntheorem of_not_not [Decidable p] : \u00ac \u00ac p \u2192 p :=\n  fun hnn => byContradiction (fun hn => absurd hn hnn)\n\ntheorem not_and_iff_or_not (p q : Prop) [d\u2081 : Decidable p] [d\u2082 : Decidable q] : \u00ac (p \u2227 q) \u2194 \u00ac p \u2228 \u00ac q :=\n  Iff.intro\n    (fun h => match d\u2081, d\u2082 with\n      | isTrue h\u2081,  isTrue h\u2082   => absurd (And.intro h\u2081 h\u2082) h\n      | _,           isFalse h\u2082 => Or.inr h\u2082\n      | isFalse h\u2081, _           => Or.inl h\u2081)\n    (fun (h) \u27e8hp, hq\u27e9 => 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 \u2194 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 \u25b8 Iff.rfl)\nend\n\n@[macro_inline] instance {p q} [Decidable p] [Decidable q] : Decidable (p \u2192 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 \u2194 q) :=\n  if hp : p then\n    if hq : q then\n      isTrue \u27e8fun _ => hq, fun _ => hp\u27e9\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 \u27e8fun h => absurd h hp, fun h => absurd h hq\u27e9\n\n/-! # if-then-else expression theorems -/\n\ntheorem if_pos {c : Prop} {h : Decidable c} (hc : c) {\u03b1 : Sort u} {t e : \u03b1} : (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 : \u00acc) {\u03b1 : Sort u} {t e : \u03b1} : (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) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (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 : \u00acc) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (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} {\u03b1 : Sort u} (t : \u03b1) (e : \u03b1) : 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 \u2192 Prop} {e : \u00acc \u2192 Prop} [dC : Decidable c] [dT : \u2200 h, Decidable (t h)] [dE : \u2200 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 {\u03b1 : Sort u} {\u03b2 : Sort v} [inst : DecidableEq \u03b2] (f : \u03b1 \u2192 \u03b2) (P : Sort w) (x y : \u03b1) : Sort w :=\n  (inst (f x) (f y)).casesOn\n    (fun _ => P)\n    (fun _ => P \u2192 P)\n\n/-- Auxiliary definition for generating compact `noConfusion` for enumeration types -/\nabbrev noConfusionEnum {\u03b1 : Sort u} {\u03b2 : Sort v} [inst : DecidableEq \u03b2] (f : \u03b1 \u2192 \u03b2) {P : Sort w} {x y : \u03b1} (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 \u2192 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 {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : Exists (fun x => p x) \u2192 Nonempty \u03b1\n  | \u27e8w, _\u27e9 => \u27e8w\u27e9\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 \u03b1` is a typeclass, so it is usually used as an implicit argument and\ninferred by typeclass inference.\n-/\nclass Subsingleton (\u03b1 : Sort u) : Prop where\n  /-- Construct a proof that `\u03b1` 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 : \u03b1) \u2192 a = b\n\nprotected theorem Subsingleton.elim {\u03b1 : Sort u} [h : Subsingleton \u03b1] : (a b : \u03b1) \u2192 a = b :=\n  h.allEq\n\nprotected theorem Subsingleton.helim {\u03b1 \u03b2 : Sort u} [h\u2081 : Subsingleton \u03b1] (h\u2082 : \u03b1 = \u03b2) (a : \u03b1) (b : \u03b2) : HEq a b := by\n  subst h\u2082\n  apply heq_of_eq\n  apply Subsingleton.elim\n\ninstance (p : Prop) : Subsingleton p :=\n  \u27e8fun a b => proofIrrel a b\u27e9\n\ninstance (p : Prop) : Subsingleton (Decidable p) :=\n  Subsingleton.intro fun\n    | isTrue t\u2081 => fun\n      | isTrue _   => rfl\n      | isFalse f\u2082 => absurd t\u2081 f\u2082\n    | isFalse f\u2081 => fun\n      | isTrue t\u2082  => absurd t\u2082 f\u2081\n      | isFalse _  => rfl\n\ntheorem recSubsingleton\n     {p : Prop} [h : Decidable p]\n     {h\u2081 : p \u2192 Sort u}\n     {h\u2082 : \u00acp \u2192 Sort u}\n     [h\u2083 : \u2200 (h : p), Subsingleton (h\u2081 h)]\n     [h\u2084 : \u2200 (h : \u00acp), Subsingleton (h\u2082 h)]\n     : Subsingleton (h.casesOn h\u2082 h\u2081) :=\n  match h with\n  | isTrue h  => h\u2083 h\n  | isFalse h => h\u2084 h\n\n/--\nAn equivalence relation `~ : \u03b1 \u2192 \u03b1 \u2192 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 \u03b1 r` is most well behaved\nwhen `r` is an equivalence relation, and in this case we use `Quotient` instead.\n-/\nstructure Equivalence {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Prop where\n  /-- An equivalence relation is reflexive: `x ~ x` -/\n  refl  : \u2200 x, r x x\n  /-- An equivalence relation is symmetric: `x ~ y` implies `y ~ x` -/\n  symm  : \u2200 {x y}, r x y \u2192 r y x\n  /-- An equivalence relation is transitive: `x ~ y` and `y ~ z` implies `x ~ z` -/\n  trans : \u2200 {x y z}, r x y \u2192 r y z \u2192 r x z\n\n/-- The empty relation is the relation on `\u03b1` which is always `False`. -/\ndef emptyRelation {\u03b1 : Sort u} (_ _ : \u03b1) : Prop :=\n  False\n\n/--\n`Subrelation q r` means that `q \u2286 r` or `\u2200 x y, q x y \u2192 r x y`.\nIt is the analogue of the subset relation on relations.\n-/\ndef Subrelation {\u03b1 : Sort u} (q r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  \u2200 {x y}, q x y \u2192 r x y\n\n/--\nThe inverse image of `r : \u03b2 \u2192 \u03b2 \u2192 Prop` by a function `\u03b1 \u2192 \u03b2` is the relation\n`s : \u03b1 \u2192 \u03b1 \u2192 Prop` defined by `s a b = r (f a) (f b)`.\n-/\ndef InvImage {\u03b1 : Sort u} {\u03b2 : Sort v} (r : \u03b2 \u2192 \u03b2 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b1 \u2192 Prop :=\n  fun a\u2081 a\u2082 => r (f a\u2081) (f a\u2082)\n\n/--\nThe transitive closure `r\u207a` of a relation `r` is the smallest relation which is\ntransitive and contains `r`. `r\u207a 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 {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : \u03b1 \u2192 \u03b1 \u2192 Prop where\n  /-- If `r a b` then `r\u207a a b`. This is the base case of the transitive closure. -/\n  | base  : \u2200 a b, r a b \u2192 TC r a b\n  /-- The transitive closure is transitive. -/\n  | trans : \u2200 a b c, TC r a b \u2192 TC r b c \u2192 TC r a c\n\n/-! # Subtype -/\n\nnamespace Subtype\ntheorem existsOfSubtype {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : { x // p x } \u2192 Exists (fun x => p x)\n  | \u27e8a, h\u27e9 => \u27e8a, h\u27e9\n\nvariable {\u03b1 : Type u} {p : \u03b1 \u2192 Prop}\n\nprotected theorem eq : \u2200 {a1 a2 : {x // p x}}, val a1 = val a2 \u2192 a1 = a2\n  | \u27e8_, _\u27e9, \u27e8_, _\u27e9, 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 {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} {a : \u03b1} (h : p a) : Inhabited {x // p x} where\n  default := \u27e8a, h\u27e9\n\ninstance {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [DecidableEq \u03b1] : DecidableEq {x : \u03b1 // p x} :=\n  fun \u27e8a, h\u2081\u27e9 \u27e8b, h\u2082\u27e9 =>\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 {\u03b1 : Type u} {\u03b2 : Type v}\n\ninstance Sum.inhabitedLeft [Inhabited \u03b1] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inl default\n\ninstance Sum.inhabitedRight [Inhabited \u03b2] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inr default\n\ninstance {\u03b1 : Type u} {\u03b2 : Type v} [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (Sum \u03b1 \u03b2) := fun a b =>\n  match a, b with\n  | Sum.inl a, Sum.inl b =>\n    if h : a = b then isTrue (h \u25b8 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 \u25b8 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 \u03b1] [Inhabited \u03b2] : Inhabited (\u03b1 \u00d7 \u03b2) where\n  default := (default, default)\n\ninstance [Inhabited \u03b1] [Inhabited \u03b2] : Inhabited (MProd \u03b1 \u03b2) where\n  default := \u27e8default, default\u27e9\n\ninstance [Inhabited \u03b1] [Inhabited \u03b2] : Inhabited (PProd \u03b1 \u03b2) where\n  default := \u27e8default, default\u27e9\n\ninstance [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (\u03b1 \u00d7 \u03b2) :=\n  fun (a, b) (a', b') =>\n    match decEq a a' with\n    | isTrue e\u2081 =>\n      match decEq b b' with\n      | isTrue e\u2082  => isTrue (e\u2081 \u25b8 e\u2082 \u25b8 rfl)\n      | isFalse n\u2082 => isFalse fun h => Prod.noConfusion h fun _   e\u2082' => absurd e\u2082' n\u2082\n    | isFalse n\u2081 => isFalse fun h => Prod.noConfusion h fun e\u2081' _   => absurd e\u2081' n\u2081\n\ninstance [BEq \u03b1] [BEq \u03b2] : BEq (\u03b1 \u00d7 \u03b2) where\n  beq := fun (a\u2081, b\u2081) (a\u2082, b\u2082) => a\u2081 == a\u2082 && b\u2081 == b\u2082\n\n/-- Lexicographical order for products -/\ndef Prod.lexLt [LT \u03b1] [LT \u03b2] (s : \u03b1 \u00d7 \u03b2) (t : \u03b1 \u00d7 \u03b2) : Prop :=\n  s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)\n\ninstance Prod.lexLtDec\n    [LT \u03b1] [LT \u03b2] [DecidableEq \u03b1] [DecidableEq \u03b2]\n    [(a b : \u03b1) \u2192 Decidable (a < b)] [(a b : \u03b2) \u2192 Decidable (a < b)]\n    : (s t : \u03b1 \u00d7 \u03b2) \u2192 Decidable (Prod.lexLt s t) :=\n  fun _ _ => inferInstanceAs (Decidable (_ \u2228 _))\n\ntheorem Prod.lexLt_def [LT \u03b1] [LT \u03b2] (s t : \u03b1 \u00d7 \u03b2) : (Prod.lexLt s t) = (s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)) :=\n  rfl\n\ntheorem Prod.eta (p : \u03b1 \u00d7 \u03b2) : (p.1, p.2) = p := rfl\n\n/--\n`Prod.map f g : \u03b1\u2081 \u00d7 \u03b2\u2081 \u2192 \u03b1\u2082 \u00d7 \u03b2\u2082` maps across a pair\nby applying `f` to the first component and `g` to the second.\n-/\ndef Prod.map {\u03b1\u2081 : Type u\u2081} {\u03b1\u2082 : Type u\u2082} {\u03b2\u2081 : Type v\u2081} {\u03b2\u2082 : Type v\u2082}\n    (f : \u03b1\u2081 \u2192 \u03b1\u2082) (g : \u03b2\u2081 \u2192 \u03b2\u2082) : \u03b1\u2081 \u00d7 \u03b2\u2081 \u2192 \u03b1\u2082 \u00d7 \u03b2\u2082\n  | (a, b) => (f a, g b)\n\n/-! # Dependent products -/\n\ntheorem ex_of_PSigma {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : (PSigma (fun x => p x)) \u2192 Exists (fun x => p x)\n  | \u27e8x, hx\u27e9 => \u27e8x, hx\u27e9\n\nprotected theorem PSigma.eta {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {a\u2081 a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081} {b\u2082 : \u03b2 a\u2082}\n    (h\u2081 : a\u2081 = a\u2082) (h\u2082 : Eq.ndrec b\u2081 h\u2081 = b\u2082) : PSigma.mk a\u2081 b\u2081 = PSigma.mk a\u2082 b\u2082 := by\n  subst h\u2081\n  subst h\u2082\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 = \u27e8\u27e9 :=\n  PUnit.subsingleton a \u27e8\u27e9\n\ninstance : Subsingleton PUnit :=\n  Subsingleton.intro PUnit.subsingleton\n\ninstance : Inhabited PUnit where\n  default := \u27e8\u27e9\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 `\u2248`.\nThis is mainly used as input to the `Quotient` type constructor.\n-/\nclass Setoid (\u03b1 : Sort u) where\n  /-- `x \u2248 y` is the distinguished equivalence relation of a setoid. -/\n  r : \u03b1 \u2192 \u03b1 \u2192 Prop\n  /-- The relation `x \u2248 y` is an equivalence relation. -/\n  iseqv : Equivalence r\n\ninstance {\u03b1 : Sort u} [Setoid \u03b1] : HasEquiv \u03b1 :=\n  \u27e8Setoid.r\u27e9\n\nnamespace Setoid\n\nvariable {\u03b1 : Sort u} [Setoid \u03b1]\n\ntheorem refl (a : \u03b1) : a \u2248 a :=\n  iseqv.refl a\n\ntheorem symm {a b : \u03b1} (hab : a \u2248 b) : b \u2248 a :=\n  iseqv.symm hab\n\ntheorem trans {a b c : \u03b1} (hab : a \u2248 b) (hbc : b \u2248 c) : a \u2248 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 \u2227 c \u2228 d \u2192 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 \u2192 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 \u2192 True) \u2194 True := \u27e8\u03bb _ => trivial, \u03bb _ _ => trivial\u27e9\n  have := propext this \u25b8 (2 : Nat)\n  exact this\n\n#reduce foo\n-- propext { mp := fun x x => True.intro, mpr := fun x => True.intro } \u25b8 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 \u2194 b) \u2192 a = b\n\ntheorem Eq.propIntro {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : b \u2192 a) : a = b :=\n  propext <| Iff.intro h\u2081 h\u2082\n\n-- Eq for Prop is now decidable if the equivalent Iff is decidable\ninstance {p q : Prop} [d : Decidable (p \u2194 q)] : Decidable (p = q) :=\n  match d with\n  | isTrue h => isTrue (propext h)\n  | isFalse h => isFalse fun heq => h (heq \u25b8 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 \u03b1] [LawfulBEq \u03b1] (a b : \u03b1) : a == b \u2194 a = b :=\n  \u27e8eq_of_beq, by intro h; subst h; exact LawfulBEq.rfl\u27e9\n\n/-! # Quotients -/\n\n/-- Iff can now be used to do substitutions in a calculation -/\ntheorem Iff.subst {a b : Prop} {p : Prop \u2192 Prop} (h\u2081 : a \u2194 b) (h\u2082 : p a) : p b :=\n  Eq.subst (propext h\u2081) h\u2082\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 {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Sort u\n\nopaque Quot.mk {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (a : \u03b1) : Quot r\n\nopaque Quot.lift {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) :\n  (\u2200 a b : \u03b1, r a b \u2192 f a = f b) \u2192 Quot r \u2192 \u03b2\n\nopaque Quot.ind {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Prop} :\n  (\u2200 a : \u03b1, \u03b2 (Quot.mk r a)) \u2192 \u2200 q : Quot r, \u03b2 q\n```\nAll of these axioms are true if we assume `Quot \u03b1 r = \u03b1` 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 \u03b1 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 : \u2200 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a b : \u03b1}, r a b \u2192 Quot.mk r a = Quot.mk r b\n\nprotected theorem liftBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v}\n    (f : \u03b1 \u2192 \u03b2)\n    (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b)\n    (a : \u03b1)\n    : lift f c (Quot.mk r a) = f a :=\n  rfl\n\nprotected theorem indBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (p : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (a : \u03b1)\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 {\u03b1 : Sort u} {\u03b2 : Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\n  (q : Quot r) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b) : \u03b2 :=\n  lift f c q\n\n@[elab_as_elim]\nprotected theorem inductionOn {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (q : Quot r)\n    (h : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q :=\n  ind h q\n\ntheorem exists_rep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=\n  q.inductionOn (fun a => \u27e8a, rfl\u27e9)\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\nvariable {motive : Quot r \u2192 Sort v}\n\n/-- Auxiliary definition for `Quot.rec`. -/\n@[reducible, macro_inline]\nprotected def indep (f : (a : \u03b1) \u2192 motive (Quot.mk r a)) (a : \u03b1) : PSigma motive :=\n  \u27e8Quot.mk r a, f a\u27e9\n\nprotected theorem indepCoherent\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : (a b : \u03b1) \u2192 r a b \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : \u2200 (a b : \u03b1) (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 \u25b8 f a = f b` assummption\n-/\nprotected abbrev rec\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 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 : \u03b1) \u2192 Subsingleton (motive (Quot.mk r a))]\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (c : (a b : \u03b1) \u2192 (p : r a b) \u2192 HEq (f a) (f b))\n    : motive q :=\n  Quot.recOn q f fun a b p => eq_of_heq <|\n    have p\u2081 : HEq (Eq.ndrec (f a) (sound p)) (f a) := eqRec_heq (sound p) (f a)\n    HEq.trans p\u2081 (c a b p)\n\nend\nend Quot\n\nset_option linter.unusedVariables.funArgs false in\n/--\n`Quotient \u03b1 s` is the same as `Quot \u03b1 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 {\u03b1 : Sort u} (s : Setoid \u03b1) :=\n  @Quot \u03b1 Setoid.r\n\nnamespace Quotient\n\n/-- The canonical quotient map into a `Quotient`. -/\n@[inline]\nprotected def mk {\u03b1 : Sort u} (s : Setoid \u03b1) (a : \u03b1) : 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' {\u03b1 : Sort u} [s : Setoid \u03b1] (a : \u03b1) : 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 {\u03b1 : Sort u} {s : Setoid \u03b1} {a b : \u03b1} : a \u2248 b \u2192 Quotient.mk s a = Quotient.mk s b :=\n  Quot.sound\n\n/--\nThe analogue of `Quot.lift`: if `f : \u03b1 \u2192 \u03b2` respects the equivalence relation `\u2248`,\nthen it lifts to a function on `Quotient s` such that `lift f h (mk a) = f a`.\n-/\nprotected abbrev lift {\u03b1 : Sort u} {\u03b2 : Sort v} {s : Setoid \u03b1} (f : \u03b1 \u2192 \u03b2) : ((a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) \u2192 Quotient s \u2192 \u03b2 :=\n  Quot.lift f\n\nprotected theorem ind {\u03b1 : Sort u} {s : Setoid \u03b1} {motive : Quotient s \u2192 Prop} : ((a : \u03b1) \u2192 motive (Quotient.mk s a)) \u2192 (q : Quot Setoid.r) \u2192 motive q :=\n  Quot.ind\n\n/--\nThe analogue of `Quot.liftOn`: if `f : \u03b1 \u2192 \u03b2` respects the equivalence relation `\u2248`,\nthen it lifts to a function on `Quotient s` such that `lift (mk a) f h = f a`.\n-/\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} {s : Setoid \u03b1} (q : Quotient s) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) : \u03b2 :=\n  Quot.liftOn q f c\n\n@[elab_as_elim]\nprotected theorem inductionOn {\u03b1 : Sort u} {s : Setoid \u03b1} {motive : Quotient s \u2192 Prop}\n    (q : Quotient s)\n    (h : (a : \u03b1) \u2192 motive (Quotient.mk s a))\n    : motive q :=\n  Quot.inductionOn q h\n\ntheorem exists_rep {\u03b1 : Sort u} {s : Setoid \u03b1} (q : Quotient s) : Exists (fun (a : \u03b1) => Quotient.mk s a = q) :=\n  Quot.exists_rep q\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {s : Setoid \u03b1}\nvariable {motive : Quotient s \u2192 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 : \u03b1) \u2192 motive (Quotient.mk s a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 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 : \u03b1) \u2192 motive (Quotient.mk s a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 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 : \u03b1) \u2192 Subsingleton (motive (Quotient.mk s a))]\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 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 : \u03b1) \u2192 motive (Quotient.mk s a))\n    (c : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 HEq (f a) (f b))\n    : motive q :=\n  Quot.hrecOn q f c\nend\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB} {\u03c6 : Sort uC}\nvariable {s\u2081 : Setoid \u03b1} {s\u2082 : Setoid \u03b2}\n\n/-- Lift a binary function to a quotient on both arguments. -/\nprotected abbrev lift\u2082\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    (q\u2081 : Quotient s\u2081) (q\u2082 : Quotient s\u2082)\n    : \u03c6 := by\n  apply Quotient.lift (fun (a\u2081 : \u03b1) => Quotient.lift (f a\u2081) (fun (a b : \u03b2) => c a\u2081 a a\u2081 b (Setoid.refl a\u2081)) q\u2082) _ q\u2081\n  intros\n  induction q\u2082 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\u2082\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    : \u03c6 :=\n  Quotient.lift\u2082 f c q\u2081 q\u2082\n\n@[elab_as_elim]\nprotected theorem ind\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\n@[elab_as_elim]\nprotected theorem inductionOn\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\n@[elab_as_elim]\nprotected theorem inductionOn\u2083\n    {s\u2083 : Setoid \u03c6}\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Quotient s\u2083 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (q\u2083 : Quotient s\u2083)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 (c : \u03c6) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b) (Quotient.mk s\u2083 c))\n    : motive q\u2081 q\u2082 q\u2083 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  induction q\u2083 using Quotient.ind\n  apply h\n\nend\n\nsection Exact\n\nvariable   {\u03b1 : Sort u}\n\nprivate def rel {s : Setoid \u03b1} (q\u2081 q\u2082 : Quotient s) : Prop :=\n  Quotient.liftOn\u2082 q\u2081 q\u2082\n    (fun a\u2081 a\u2082 => a\u2081 \u2248 a\u2082)\n    (fun _ _ _ _ a\u2081b\u2081 a\u2082b\u2082 =>\n      propext (Iff.intro\n        (fun a\u2081a\u2082 => Setoid.trans (Setoid.symm a\u2081b\u2081) (Setoid.trans a\u2081a\u2082 a\u2082b\u2082))\n        (fun b\u2081b\u2082 => Setoid.trans a\u2081b\u2081 (Setoid.trans b\u2081b\u2082 (Setoid.symm a\u2082b\u2082)))))\n\nprivate theorem rel.refl {s : Setoid \u03b1} (q : Quotient s) : rel q q :=\n  q.inductionOn Setoid.refl\n\nprivate theorem rel_of_eq {s : Setoid \u03b1} {q\u2081 q\u2082 : Quotient s} : q\u2081 = q\u2082 \u2192 rel q\u2081 q\u2082 :=\n  fun h => Eq.ndrecOn h (rel.refl q\u2081)\n\ntheorem exact {s : Setoid \u03b1} {a b : \u03b1} : Quotient.mk s a = Quotient.mk s b \u2192 a \u2248 b :=\n  fun h => rel_of_eq h\n\nend Exact\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB}\nvariable {s\u2081 : Setoid \u03b1} {s\u2082 : Setoid \u03b2}\n\n/-- Lift a binary function to a quotient on both arguments. -/\n@[elab_as_elim]\nprotected abbrev recOnSubsingleton\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Sort uC}\n    [s : (a : \u03b1) \u2192 (b : \u03b2) \u2192 Subsingleton (motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))]\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (g : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quot.recOnSubsingleton\n  induction q\u2082 using Quot.recOnSubsingleton\n  apply g\n  intro a; apply s\n  induction q\u2082 using Quot.recOnSubsingleton\n  intro a; apply s\n  infer_instance\n\nend\nend Quotient\n\nsection\nvariable {\u03b1 : Type u}\nvariable (r : \u03b1 \u2192 \u03b1 \u2192 Prop)\n\ninstance {\u03b1 : Sort u} {s : Setoid \u03b1} [d : \u2200 (a b : \u03b1), Decidable (a \u2248 b)] : DecidableEq (Quotient s) :=\n  fun (q\u2081 q\u2082 : Quotient s) =>\n    Quotient.recOnSubsingleton\u2082 q\u2081 q\u2082\n      fun a\u2081 a\u2082 =>\n        match d a\u2081 a\u2082 with\n        | isTrue h\u2081  => isTrue (Quotient.sound h\u2081)\n        | isFalse h\u2082 => isFalse fun h => absurd (Quotient.exact h) h\u2082\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: `(\u2200 x, f x = g x) \u2192 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 `(\u2200 x, x \u2208 s \u2194 x \u2208 t) \u2192 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 {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {f g : (x : \u03b1) \u2192 \u03b2 x}\n    (h : \u2200 x, f x = g x) : f = g := by\n  let eqv (f g : (x : \u03b1) \u2192 \u03b2 x) := \u2200 x, f x = g x\n  let extfunApp (f : Quot eqv) (x : \u03b1) : \u03b2 x :=\n    Quot.liftOn f\n      (fun (f : \u2200 (x : \u03b1), \u03b2 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 {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton (\u2200 a, \u03b2 a) where\n  allEq f g := funext fun a => Subsingleton.elim (f a) (g a)\n\n/-! # Squash -/\n\n/--\n`Squash \u03b1` is the quotient of `\u03b1` by the always true relation.\nIt is empty if `\u03b1` is empty, otherwise it is a singleton.\n(Thus it is unconditionally a `Subsingleton`.)\nIt is the \"universal `Subsingleton`\" mapped from `\u03b1`.\n\nIt is similar to `Nonempty \u03b1`, 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 \u03b1` the same as `\u03b1` itself\n(as compared to `Nonempty \u03b1`, whose elements are represented by a dummy value).\n\n`Squash.lift` will extract a value in any subsingleton `\u03b2` from a function on `\u03b1`,\nwhile `Nonempty.rec` can only do the same when `\u03b2` is a proposition.\n-/\ndef Squash (\u03b1 : Type u) := Quot (fun (_ _ : \u03b1) => True)\n\n/-- The canonical quotient map into `Squash \u03b1`. -/\ndef Squash.mk {\u03b1 : Type u} (x : \u03b1) : Squash \u03b1 := Quot.mk _ x\n\ntheorem Squash.ind {\u03b1 : Type u} {motive : Squash \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), motive (Squash.mk a)) : \u2200 (q : Squash \u03b1), motive q :=\n  Quot.ind h\n\n/-- If `\u03b2` is a subsingleton, then a function `\u03b1 \u2192 \u03b2` lifts to `Squash \u03b1 \u2192 \u03b2`. -/\n@[inline] def Squash.lift {\u03b1 \u03b2} [Subsingleton \u03b2] (s : Squash \u03b1) (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  Quot.lift f (fun _ _ _ => Subsingleton.elim _ _) s\n\ninstance : Subsingleton (Squash \u03b1) 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 (\u00b7\u2264\u00b7)` says that `(\u00b7\u2264\u00b7)` is antisymmetric, that is, `a \u2264 b \u2192 b \u2264 a \u2192 a = b`.\n-/\nclass Antisymm {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) where\n  /-- An antisymmetric relation `(\u00b7\u2264\u00b7)` satisfies `a \u2264 b \u2192 b \u2264 a \u2192 a = b`. -/\n  antisymm {a b : \u03b1} : r a b \u2192 r b a \u2192 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 {\u03b1} (a : \u03b1) : \u03b1 := 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 \u2218 b) \u2218 c = a \u2218 (b \u2218 c)`. It is used by the `ac_rfl` tactic.\n-/\nclass IsAssociative {\u03b1 : Sort u} (op : \u03b1 \u2192 \u03b1 \u2192 \u03b1) where\n  /-- An associative operation satisfies `(a \u2218 b) \u2218 c = a \u2218 (b \u2218 c)`. -/\n  assoc : (a b c : \u03b1) \u2192 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 \u2218 b = b \u2218 a`. It is used by the `ac_rfl` tactic.\n-/\nclass IsCommutative {\u03b1 : Sort u} (op : \u03b1 \u2192 \u03b1 \u2192 \u03b1) where\n  /-- A commutative operation satisfies `a \u2218 b = b \u2218 a`. -/\n  comm : (a b : \u03b1) \u2192 op a b = op b a\n\n/--\n`IsIdempotent op` says that `op` is an idempotent operation,\ni.e. `a \u2218 a = a`. It is used by the `ac_rfl` tactic\n(which also simplifies up to idempotence when available).\n-/\nclass IsIdempotent {\u03b1 : Sort u} (op : \u03b1 \u2192 \u03b1 \u2192 \u03b1) where\n  /-- An idempotent operation satisfies `a \u2218 a = a`. -/\n  idempotent : (x : \u03b1) \u2192 op x x = x\n\n/--\n`IsNeutral op e` says that `e` is a neutral operation for `op`,\ni.e. `a \u2218 e = a = e \u2218 a`. It is used by the `ac_rfl` tactic\n(which also simplifies neutral elements when available).\n-/\nclass IsNeutral {\u03b1 : Sort u} (op : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (neutral : \u03b1) where\n  /-- A neutral element can be cancelled on the left: `e \u2218 a = a`. -/\n  left_neutral : (a : \u03b1) \u2192 op neutral a = a\n  /-- A neutral element can be cancelled on the right: `a \u2218 e = a`. -/\n  right_neutral : (a : \u03b1) \u2192 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 {\u03b1 \u03b2 \u03b3 : 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.\u03b9) : (spec.domain i \u00d7 S) \u2192 oracle_comp spec' (spec.range i \u00d7 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 \u2115 :=\n{ default_state := 0,\n  o := \u03bb i \u27e8t, n\u27e9, 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  (\u03bb so, \u03a0 (i : spec.\u03b9), spec.domain i \u00d7 S \u2192 oracle_comp spec' (spec.range i \u00d7 S)) :=\n{ coe := \u03bb so, so.o }\n\nlemma has_coe_to_fun.def (so : sim_oracle spec spec' S) (i : spec.\u03b9)\n  (x : spec.domain i \u00d7 S) : so i x = so.o i x := rfl\n\ndef inhabited_state (so : sim_oracle spec spec' S) : inhabited S := \u27e8so.default_state\u27e9\n\ninstance inhabited [inhabited S] : inhabited (sim_oracle spec spec' S) :=\n\u27e8{default_state := default, o := \u03bb _ _, return default}\u27e9\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 : \u03b1) (i : spec.\u03b9) (t : spec.domain i) (oa oa' : oracle_comp spec \u03b1)\n  (ob ob' : \u03b1 \u2192 oracle_comp spec \u03b2) (oc : \u03b2 \u2192 oracle_comp spec \u03b3) (s : S) (f : \u03b1 \u2192 \u03b2)\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  \u03a0 {\u03b1 : Type} (oa : oracle_comp spec \u03b1), S \u2192 oracle_comp spec' (\u03b1 \u00d7 S)\n| _ (pure' \u03b1 a) state := return \u27e8a, state\u27e9\n| _ (bind' \u03b1 \u03b2 oa ob) state := simulate oa state >>= \u03bb 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 \u03b1) :\n  oracle_comp spec' (\u03b1 \u00d7 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' \u03b1 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 >>= \u03bb x, simulate so (ob x.1) x.2 := rfl\n\nlemma simulate_bind' : simulate so (bind' \u03b1 \u03b2 oa ob) s =\n  simulate so oa s >>= \u03bb 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 : \u2200 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 \u03b1 a \u03b1 \u03b2 oa ob hoa' hob' i t generalizing s},\n  { haveI : decidable_eq \u03b1 := 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 : \u2200 a, (ob a).decidable := \u03bb a, decidable_of_decidable_bind_snd a hoa,\n    haveI : (simulate so oa s).decidable := hoa' _,\n    haveI : \u2200 (x : \u03b1 \u00d7 S), (simulate so (ob x.1) x.2).decidable := \u03bb 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' \u03b1 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  \u22c3 x \u2208 (simulate so oa s).support, (simulate so (ob $ prod.fst x) x.2).support := rfl\n\nlemma mem_support_simulate_bind_iff (x : \u03b2 \u00d7 S) : x \u2208 (simulate so (oa >>= ob) s).support \u2194\n  \u2203 (a : \u03b1) (s' : S), (a, s') \u2208 (simulate so oa s).support \u2227 x \u2208 (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' \u03b1 \u03b2 oa ob) s).support\n  = \u22c3 x \u2208 (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 : \u2045simulate so (return a) s\u2046 = pmf.pure (a, s) := rfl\n\nlemma eval_dist_simulate_pure' : \u2045simulate so (pure' \u03b1 a) s\u2046 = pmf.pure (a, s) := rfl\n\nlemma eval_dist_simulate_pure : \u2045simulate so (pure a) s\u2046 = pmf.pure (a, s) := rfl\n\n@[simp] lemma eval_dist_simulate_bind : \u2045simulate so (oa >>= ob) s\u2046 =\n  (\u2045simulate so oa s\u2046).bind (\u03bb x, \u2045simulate so (ob x.1) x.2\u2046) :=\n(congr_arg _ $ simulate_bind so oa ob s).trans (eval_dist_bind _ _)\n\nlemma eval_dist_simulate_bind' : \u2045simulate so (bind' \u03b1 \u03b2 oa ob) s\u2046 =\n  (\u2045simulate so oa s\u2046).bind (\u03bb x, \u2045simulate so (ob x.1) x.2\u2046) :=\neval_dist_simulate_bind so oa ob s\n\nlemma eval_dist_simulate_query : \u2045simulate so (query i t) s\u2046 = \u2045so i (t, s)\u2046 := rfl\n\nlemma eval_dist_simulate_map : \u2045simulate so (f <$> oa) s\u2046 =\n  \u2045simulate so oa s\u2046.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 : \u03b2 \u00d7 S) : \u2045simulate so (oa >>= ob) s\u2046 x =\n  \u2211' a s', \u2045simulate so oa s\u2046 (a, s') * \u2045simulate so (ob a) s'\u2046 x :=\nby rw [simulate_bind, eval_dist_prod_bind]\n\nlemma eval_dist_simulate_bind_apply_eq_sum_sum [fintype \u03b1] [fintype S] (x : \u03b2 \u00d7 S) :\n  \u2045simulate so (oa >>= ob) s\u2046 x = \u2211 a s', \u2045simulate so oa s\u2046 (a, s') * \u2045simulate so (ob a) s'\u2046 x :=\nby simp only [simulate_bind, eval_dist_bind_apply_eq_sum, \u2190 @finset.sum_product \u211d\u22650\u221e S \u03b1 _\n  finset.univ finset.univ (\u03bb y, \u2045simulate so oa s\u2046 (y.1, y.2) * \u2045simulate so (ob y.1) y.2\u2046 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 (\u03b1 \u00d7 S)) :\n  \u2045e | simulate so (return a) s\u2046 = e.indicator (\u03bb _, 1) (a, s) :=\nprob_event_return_eq_indicator (a, s) e\n\nlemma prob_event_simulate_bind_eq_tsum_tsum (e : set (\u03b2 \u00d7 S)) : \u2045e | simulate so (oa >>= ob) s\u2046 =\n  \u2211' a s', \u2045simulate so oa s\u2046 (a, s') * \u2045e | simulate so (ob a) s'\u2046 :=\nby simp_rw [simulate_bind, prob_event_bind_eq_tsum, \u2190 ennreal.tsum_prod, prod.mk.eta]\n\nlemma prob_event_simulate_bind_eq_sum_sum [fintype \u03b1] [fintype S] (e : set (\u03b2 \u00d7 S)) :\n  \u2045e | simulate so (oa >>= ob) s\u2046 =\n    \u2211 a s', \u2045simulate so oa s\u2046 (a, s') * \u2045e | simulate so (ob a) s'\u2046 :=\nby simp only [simulate_bind, prob_event_bind_eq_sum, \u2190 @finset.sum_product \u211d\u22650\u221e S \u03b1 _ finset.univ\n  finset.univ (\u03bb x, \u2045simulate so oa s\u2046 (x.1, x.2) * \u2045e | simulate so (ob x.1) x.2\u2046),\n  finset.univ_product_univ, prod.mk.eta]\n\nlemma prob_event_simulate_query (e : set (spec.range i \u00d7 S)) :\n  \u2045e | simulate so (query i t) s\u2046 = \u2045e | so i (t, s)\u2046 := rfl\n\nlemma prob_event_simulate_map (e : set (\u03b2 \u00d7 S)) :\n  \u2045e | simulate so (f <$> oa) s\u2046 = \u2045prod.map f id \u207b\u00b9' e | simulate so oa s\u2046 :=\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 \u03b1) (s : S) :\n  oracle_comp spec' \u03b1 := 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 \u03b1) :\n  oracle_comp spec' \u03b1 := 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' \u03b1 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 >>= \u03bb x, simulate so (ob x.1) x.2) := rfl\n\nlemma simulate'_bind' : simulate' so (bind' \u03b1 \u03b2 oa ob) s =\n  prod.fst <$> (simulate so oa s >>= \u03bb 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 : \u2200 i t s, (so i (t, s)).decidable] : (oa.simulate' so s).decidable :=\nbegin\n  haveI : decidable_eq \u03b1 := 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 : \u03b1) :\n  a \u2208 (simulate' so oa s).support \u2194 \u2203 (s' : S), (a, s') \u2208 (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 : \u03b1) : (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 : \u03b1) : (simulate' so (pure' \u03b1 a) s).support = {a} :=\nsupport_simulate'_return so s a\n\nlemma support_simulate'_pure (a : \u03b1) : (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  \u22c3 x \u2208 (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' \u03b1 \u03b2 oa ob) s).support =\n  \u22c3 x \u2208 (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' : \u2045simulate' so oa s\u2046 = \u2045simulate so oa s\u2046.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 : \u2045simulate' so oa s\u2046 a = \u2211' s', \u2045simulate so oa s\u2046 (a, s') :=\nbegin\n  rw [eval_dist_simulate', pmf.map_apply],\n  refine (tsum_prod_eq_tsum_snd a $ \u03bb s a' ha', _).trans (tsum_congr (\u03bb 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 : \u2045simulate' so (return a) s\u2046 = pmf.pure a :=\nby simp only [simulate'_return, eval_dist_map, eval_dist_return, pmf.map_pure]\n\nlemma eval_dist_simulate'_pure' : \u2045simulate' so (pure' \u03b1 a) s\u2046 = pmf.pure a :=\neval_dist_simulate'_return so a s\n\nlemma eval_dist_simulate'_pure : \u2045simulate' so (pure a) s\u2046 = pmf.pure a :=\neval_dist_simulate'_return so a s\n\nlemma eval_dist_simulate'_bind : \u2045simulate' so (oa >>= ob) s\u2046 =\n  \u2045simulate so oa s\u2046.bind (\u03bb x, \u2045simulate' so (ob x.1) x.2\u2046) :=\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 : \u03b2) : \u2045simulate' so (oa >>= ob) s\u2046 b\n  = \u2211' (a : \u03b1) (s' : S), \u2045simulate so oa s\u2046 (a, s') * \u2045simulate' so (ob a) s'\u2046 b :=\nby rw [eval_dist_simulate'_bind, pmf.bind_apply, tsum_prod'\n  ennreal.summable (\u03bb _, ennreal.summable)]\n\nlemma eval_dist_simulate'_bind' : \u2045simulate' so (bind' \u03b1 \u03b2 oa ob) s\u2046 =\n  \u2045simulate so oa s\u2046.bind (\u03bb x, \u2045simulate' so (ob x.1) x.2\u2046) := eval_dist_simulate'_bind _ _ _ s\n\nlemma eval_dist_simulate'_query : \u2045simulate' so (query i t) s\u2046 = \u2045so i (t, s)\u2046.map prod.fst :=\nby simp only [simulate'_query, eval_dist_map]\n\n@[simp] lemma eval_dist_simulate'_map : \u2045simulate' so (f <$> oa) s\u2046 = \u2045simulate' so oa s\u2046.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 \u03b1) :\n  \u2045e | simulate' so oa s\u2046 = \u2045prod.fst \u207b\u00b9' e | simulate so oa s\u2046 :=\nby rw [simulate', prob_event_map]\n\nlemma prob_event_simulate'_return_eq_indicator (e : set \u03b1) :\n  \u2045e | simulate' so (return a) s\u2046 = e.indicator (\u03bb _, 1) a :=\nbegin\n  rw [prob_event_simulate', prob_event_simulate_return],\n  by_cases ha : a \u2208 e,\n  { have : (a, s) \u2208 (prod.fst \u207b\u00b9' e : set (\u03b1 \u00d7 S)) := ha,\n    rw [set.indicator_of_mem ha, set.indicator_of_mem this] },\n  { have : (a, s) \u2209 (prod.fst \u207b\u00b9' e : set (\u03b1 \u00d7 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 \u03b1) [decidable_pred (\u2208 e)] :\n  \u2045e | simulate' so (return a) s\u2046 = ite (a \u2208 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 \u03b2) : \u2045e | simulate' so (oa >>= ob) s\u2046 =\n  \u2211' a s', \u2045simulate so oa s\u2046 (a, s') * \u2045e | simulate' so (ob a) s'\u2046 :=\nby simp_rw [prob_event_simulate', prob_event_simulate_bind_eq_tsum_tsum]\n\nlemma prob_event_simulate'_bind_eq_sum_sum [fintype \u03b1] [fintype S] (e : set \u03b2) :\n  \u2045e | simulate' so (oa >>= ob) s\u2046 =\n    \u2211 a s', \u2045simulate so oa s\u2046 (a, s') * \u2045e | simulate' so (ob a) s'\u2046 :=\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  \u2045e | simulate' so (query i t) s\u2046 = \u2045prod.fst \u207b\u00b9' e | so i (t, s)\u2046 :=\nby rw [prob_event_simulate', prob_event_simulate_query]\n\nlemma prob_event_simulate'_map (e : set \u03b2) :\n  \u2045e | simulate' so (f <$> oa) s\u2046 = \u2045(f \u2218 prod.fst) \u207b\u00b9' e | simulate so oa s\u2046 :=\nby simpa only [prob_event_simulate', prob_event_simulate_map, \u2190 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": "/-\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.name\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.Data.Ordering.Basic\nimport Leanbin.Init.Coe\nimport Leanbin.Init.Data.ToString\n\n/-- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/\ninductive Name\n  | anonymous : Name\n  | mk_string : String \u2192 Name \u2192 Name\n  | mk_numeral : Unsigned \u2192 Name \u2192 Name\n#align 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]\ndef autoParam.{u} (\u03b1 : Sort u) (tac_name : Name) : Sort u :=\n  \u03b1\n#align auto_param autoParam\u2093\n\n@[simp]\ntheorem autoParam_eq.{u} (\u03b1 : Sort u) (n : Name) : autoParam \u03b1 n = \u03b1 :=\n  rfl\n#align auto_param_eq autoParam\u2093_eq\n\ninstance : Inhabited Name :=\n  \u27e8Name.anonymous\u27e9\n\ndef mkStrName (n : Name) (s : String) : Name :=\n  Name.mk_string s n\n#align mk_str_name mkStrName\n\ndef mkNumName (n : Name) (v : Nat) : Name :=\n  Name.mk_numeral (Unsigned.ofNat' v) n\n#align mk_num_name mkNumName\n\ndef mkSimpleName (s : String) : Name :=\n  mkStrName Name.anonymous s\n#align mk_simple_name mkSimpleName\n\ninstance stringToName : Coe String Name :=\n  \u27e8mkSimpleName\u27e9\n#align string_to_name stringToName\n\nopen Name\n\ndef Name.getPrefix : Name \u2192 Name\n  | anonymous => anonymous\n  | mk_string s p => p\n  | mk_numeral s p => p\n#align name.get_prefix Name.getPrefix\n\ndef Name.updatePrefix : Name \u2192 Name \u2192 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#align name.update_prefix Name.updatePrefix\n\n/- ./././Mathport/Syntax/Translate/Basic.lean:334:40: warning: unsupported option eqn_compiler.ite -/\n-- Without this option, we get errors when defining the following definitions.\nset_option eqn_compiler.ite false\n\ndef Name.toStringWithSep (sep : String) : Name \u2192 String\n  | anonymous => \"[anonymous]\"\n  | mk_string s anonymous => s\n  | mk_numeral v anonymous => repr v\n  | mk_string s n => Name.toStringWithSep n ++ sep ++ s\n  | mk_numeral v n => Name.toStringWithSep n ++ sep ++ repr v\n#align name.to_string_with_sep Name.toStringWithSep\n\nprivate def name.components' : Name \u2192 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#align name.components' name.components'\n\ndef Name.components (n : Name) : List Name :=\n  (Name.components' n).reverse\n#align name.components Name.components\n\nprotected def Name.toString : Name \u2192 String :=\n  Name.toStringWithSep \".\"\n#align name.to_string Name.toString\n\nprotected def Name.repr (n : Name) : String :=\n  \"`\" ++ n.toString\n#align name.repr Name.repr\n\ninstance : ToString Name :=\n  \u27e8Name.toString\u27e9\n\ninstance : Repr Name :=\n  \u27e8Name.repr\u27e9\n\n-- TODO(Leo): provide a definition in Lean.\nunsafe axiom name.has_decidable_eq : DecidableEq Name\n#align name.has_decidable_eq name.has_decidable_eq\n\n/-! Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/\n\n\nunsafe axiom name.cmp : Name \u2192 Name \u2192 Ordering\n#align name.cmp name.cmp\n\nunsafe axiom name.lex_cmp : Name \u2192 Name \u2192 Ordering\n#align name.lex_cmp name.lex_cmp\n\nunsafe axiom name.append : Name \u2192 Name \u2192 Name\n#align name.append name.append\n\nunsafe axiom name.is_internal : Name \u2192 Bool\n#align name.is_internal name.is_internal\n\nprotected unsafe def name.lt (a b : Name) : Prop :=\n  name.cmp a b = Ordering.lt\n#align name.lt name.lt\n\nunsafe instance : DecidableRel name.lt := fun a b => Ordering.decidableEq _ _\n\nunsafe instance : LT Name :=\n  \u27e8name.lt\u27e9\n\nattribute [instance] name.has_decidable_eq\n\nunsafe instance : Append Name :=\n  \u27e8name.append\u27e9\n\n/-- `name.append_after n i` return a name of the form n_i -/\nunsafe axiom name.append_after : Name \u2192 Nat \u2192 Name\n#align name.append_after name.append_after\n\nunsafe def name.is_prefix_of : Name \u2192 Name \u2192 Bool\n  | p, Name.anonymous => false\n  | p, n => if p = n then true else name.is_prefix_of p n.getPrefix\n#align name.is_prefix_of name.is_prefix_of\n\nunsafe def name.is_suffix_of : Name \u2192 Name \u2192 Bool\n  | anonymous, _ => true\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  | _, _ => false\n#align name.is_suffix_of name.is_suffix_of\n\nunsafe def name.replace_prefix : Name \u2192 Name \u2192 Name \u2192 Name\n  | anonymous, p, p' => anonymous\n  | mk_string s c, p, p' =>\n    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' =>\n    if c = p then mk_numeral v p' else mk_numeral v (name.replace_prefix c p p')\n#align name.replace_prefix name.replace_prefix\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/Name.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796361952087, "lm_q2_score": 0.08389039213655913, "lm_q1q2_score": 0.03998045256471475}}
{"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": "import Duper.Tactic\nimport Duper.TPTP\n\n-- Note: These tests only effectively test boolSimp when identBoolHoist is disabled\nset_option trace.Rule.boolSimp true\n\ntheorem boolSimpRule1Test (p : Prop) (h : (p \u2228 p \u2228 p \u2228 p) = q) : p = q :=\n  by duper\n\ntheorem boolSimpRule2Test (p q : Prop) (h : (\u00acp \u2228 p) = q) : q :=\n  by duper\n\ntheorem boolSimpRule2SymTest (p q : Prop) (h : (p \u2228 \u00acp) = q) : q :=\n  by duper\n\ntheorem boolSimpRule3Test (p q : Prop) (h : (p \u2228 True) = q) : q :=\n  by duper\n\ntheorem boolSimpRule3SymTest (p q : Prop) (h : (True \u2228 p) = q) : q :=\n  by duper\n\ntheorem boolSimpRule4Test (p q : Prop) (h : (p \u2228 False) = (q \u2228 False)) : p = q :=\n  by duper\n\ntheorem boolSimpRule4SymTest (p q : Prop) (h : (False \u2228 p) = (False \u2228 q)) : p = q :=\n  by duper\n\ntheorem boolSimpRule5Test (p q : Prop) (h : p = (q = q)) : p :=\n  by duper\n\ntheorem boolSimpRule6Test (p q : Prop) (h : (p = True) = (q = True)) : p = q :=\n  by duper\n\ntheorem boolSimpRule6SymTest (p q : Prop) (h : (True = p) = (True = q)) : p = q :=\n  by duper\n\ntheorem boolSimpRule7Test (p q : Prop) (h : p = Not False) : p :=\n  by duper\n\ntheorem boolSimpRule8Test (p : Prop) (h : (p \u2227 p \u2227 p \u2227 p) = q) : p = q :=\n  by duper\n\ntheorem boolSimpRule9Test (p q : Prop) (h : (\u00acp \u2227 p) = q) : \u00acq :=\n  by duper\n\ntheorem boolSimpRule9SymTest (p q : Prop) (h : (p \u2227 \u00acp) = q) : \u00acq :=\n  by duper\n\ntheorem boolSimpRule10Test (p q : Prop) (h : (p \u2227 True) = q) : p = q :=\n  by duper\n\ntheorem boolSimpRule10SymTest (p q : Prop) (h : (True \u2227 p) = q) : p = q :=\n  by duper\n\ntheorem boolSimpRule11Test (p q : Prop) (h : (p \u2227 False) = q) : \u00acq :=\n  by duper\n\ntheorem boolSimpRule11SymTest (p q : Prop) (h : (False \u2227 p) = q) : \u00acq :=\n  by duper\n\ntheorem boolSimpRule12Test (p q : Prop) (h : p = (q \u2260 q)) : \u00acp :=\n  by duper\n\ntheorem boolSimpRule13Test (p q : Prop) (h : (p = False) = (q = False)) : p = q :=\n  by duper\n\ntheorem boolSimpRule13SymTest (p q : Prop) (h : (False = p) = (False = q)) : p = q :=\n  by duper\n\ntheorem boolSimpRule14Test (p q : Prop) (h : p = Not True) : \u00acp :=\n  by duper\n\ntheorem boolSimpRule15Test (p q : Prop) (h : (\u00ac\u00acp) = q) : p = q :=\n  by duper\n\ntheorem boolSimpRule16Test (p q : Prop) (h : (True \u2192 p) = q) : p = q :=\n  by duper\n\ntheorem boolSimpRule17Test (p q : Prop) (h : (False \u2192 p) = q) : q :=\n  by duper\n\ntheorem boolSimpRule18Test (p q : Prop) (h : (p \u2192 False) = (q \u2192 False)) : p = q :=\n  by duper\n\ntheorem boolSimpRule19Test (p q : Prop) (h : (p \u2192 True) = q) : q :=\n  by duper\n\ntheorem boolSimpRule19Test2 (\u03b1) (q : Prop) (h : (\u2200 _ : \u03b1, True) = q) : q :=\n  by duper\n\ntheorem boolSimpRule20Test (p q : Prop) (h : (p \u2192 \u00acp) = (q \u2192 \u00acq)) : p = q :=\n  by duper\n\ntheorem boolSimpRule21Test (p q : Prop) (h : (\u00acp \u2192 p) = (\u00acq \u2192 q)) : p = q :=\n  by duper\n\ntheorem boolSimpRule22Test (p q : Prop) (h : (p \u2192 p) = q) : q :=\n  by duper\n\ntheorem boolSimpRule23Test (f : Prop \u2192 Prop) (q : Prop) (hq : q) (h : (\u2200 p : Prop, f p) = q) : f True :=\n  by duper\n\ntheorem boolSimpRule24Test (f : Prop \u2192 Prop) (q : Prop) (hq : q) (h : (\u2203 p : Prop, f p) = q) : (f True) \u2228 (f False) :=\n  by duper\n\ntheorem boolSimpRule25Test (p q r : Prop) (h : (p \u2192 \u00acq \u2192 q \u2192 p \u2192 False) = r) : r :=\n  by duper\n\ntheorem boolSimpRule26Test (a b c shared x y z r : Prop) (h : (a \u2192 b \u2192 shared \u2192 c \u2192 (x \u2228 shared \u2228 y \u2228 z)) = r) : r :=\n  by duper\n\ntheorem boolSimpRule27Test (a b c shared x y z r : Prop) (h : ((a \u2227 b \u2227 shared \u2227 c) \u2192 (x \u2228 shared \u2228 y \u2228 z)) = r) : r :=\n  by duper\n\ntheorem boolSimpRule28Test (p q r : Prop) (h : (p \u2194 r) = (q \u2194 r)) : p = q :=\n  by duper\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/Tests/test_boolSimp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07921033171684742, "lm_q1q2_score": 0.03960516585842371}}
{"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 \u2192 Type u}\nparameters (eqv : \u03a0 \u03b1, t \u03b1 \u2243 t' \u03b1)\nvariables [functor t]\n\nopen functor\n\nprotected def map {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 \u03b2) (x : t' \u03b1) : t' \u03b2 :=\neqv \u03b2 $ map f ((eqv \u03b1).symm x)\n\nprotected def functor : functor t' :=\n{ map := @equiv.map _ }\n\nvariables [is_lawful_functor t]\n\nprotected lemma id_map {\u03b1 : Type u} (x : t' \u03b1) : equiv.map id x = x :=\nby simp [equiv.map, id_map]\n\nprotected lemma comp_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) (x : t' \u03b1) :\n  equiv.map (h \u2218 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\u2080 : \u2200 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2), _root_.functor.map f = equiv.map f)\n  (h\u2081 : \u2200 {\u03b1 \u03b2} (f : \u03b2), _root_.functor.map_const f = (equiv.map \u2218 function.const \u03b1) f) :\n  _root_.is_lawful_functor t' :=\nbegin\n  have : F = equiv.functor,\n  { unfreezeI, cases F, dsimp [equiv.functor],\n    congr; ext; [rw \u2190 h\u2080, rw \u2190 h\u2081] },\n  constructor; intros;\n  haveI F' := equiv.is_lawful_functor,\n  { simp, intros, ext,\n    rw [h\u2081], rw \u2190 this at F',\n    have k := @map_const_eq t' _ _ \u03b1 \u03b2, rw this at \u22a2 k, rw \u2190 k, refl },\n  { rw [h\u2080], rw \u2190 this at F',\n    have k := id_map x, rw this at k, apply k },\n  { rw [h\u2080], rw \u2190 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 \u2192 Type u}\nparameters (eqv : \u03a0 \u03b1, t \u03b1 \u2243 t' \u03b1)\nvariables [traversable t]\nvariables {m : Type u \u2192 Type u} [applicative m]\nvariables {\u03b1 \u03b2 : Type u}\n\nprotected def traverse (f : \u03b1 \u2192 m \u03b2) (x : t' \u03b1) : m (t' \u03b2) :=\neqv \u03b2 <$> traverse f ((eqv \u03b1).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 \u2192 Type u}\nparameters (eqv : \u03a0 \u03b1, t \u03b1 \u2243 t' \u03b1)\nvariables [traversable t] [is_lawful_traversable t]\nvariables {F G : Type u \u2192 Type u} [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables (\u03b7 : applicative_transformation F G)\nvariables {\u03b1 \u03b2 \u03b3 : Type u}\n\nopen is_lawful_traversable functor\n\nprotected lemma id_traverse (x : t' \u03b1) :\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 : \u03b1 \u2192 \u03b2) (x : t' \u03b1) :\n  equiv.traverse eqv (id.mk \u2218 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 : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : t' \u03b1) :\n  equiv.traverse eqv (comp.mk \u2218 functor.map f \u2218 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 : \u03b1 \u2192 F \u03b2) (x : t' \u03b1) :\n  \u03b7 (equiv.traverse eqv f x) = equiv.traverse eqv (@\u03b7 _ \u2218 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\u2080 : \u2200 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2),\n         map f = equiv.map eqv f)\n  (h\u2081 : \u2200 {\u03b1 \u03b2} (f : \u03b2),\n         map_const f = (equiv.map eqv \u2218 function.const \u03b1) f)\n  (h\u2082 : \u2200 {F : Type u \u2192 Type u} [applicative F] [is_lawful_applicative F]\n          {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2),\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\u2082 needs a `is_lawful_applicative` assumption\n  refine {to_is_lawful_functor :=\n    equiv.is_lawful_functor' eqv @h\u2080 @h\u2081, ..}; intros; resetI,\n  { rw [h\u2082, equiv.id_traverse], apply_instance },\n  { rw [h\u2082, equiv.comp_traverse f g x, h\u2082], congr,\n    rw [h\u2082], all_goals { apply_instance } },\n  { rw [h\u2082, equiv.traverse_eq_map_id, h\u2080]; apply_instance },\n  { rw [h\u2082, equiv.naturality, h\u2082]; 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 \u03b1` 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\u2080 u\u2081 v\u2080 v\u2081 v\u2082 w w\u2080 w\u2081\n\n/-- Given a universe polymorphic type family `M.{u} : Type u\u2081 \u2192 Type\nu\u2082`, this class convert between instantiations, from\n`M.{u} : Type u\u2081 \u2192 Type u\u2082` to `M.{v} : Type v\u2081 \u2192 Type v\u2082` and back -/\nclass uliftable (f : Type u\u2080 \u2192 Type u\u2081) (g : Type v\u2080 \u2192 Type v\u2081) :=\n(congr [] {\u03b1 \u03b2} : \u03b1 \u2243 \u03b2 \u2192 f \u03b1 \u2243 g \u03b2)\n\nnamespace uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} \u03b1` and lifts it to M.{max u v} (ulift.{v} \u03b1) -/\n@[reducible]\ndef up {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} : f \u03b1 \u2192 g (ulift \u03b1) :=\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} \u03b1)` and lowers it to `M.{u} \u03b1` -/\n@[reducible]\ndef down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} : g (ulift \u03b1) \u2192 f \u03b1 :=\n(uliftable.congr f g equiv.ulift.symm).inv_fun\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v\u2080 \u2192 Type v\u2081) (G : Type (max v\u2080 u\u2080) \u2192 Type u\u2081)\n  [uliftable F G] [monad G] {\u03b1 \u03b2}\n  (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\nup x >>= f \u2218 ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type v\u2080 \u2192 Type v\u2081}\n  [L : uliftable G F] [monad F] {\u03b1 \u03b2}\n  (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n@down.{v\u2080 v\u2081 (max u\u2080 v\u2080)} G F L \u03b2 $ x >>= @up.{v\u2080 v\u2081 (max u\u2080 v\u2080)} G F L \u03b2 \u2218 f\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u\u2080 \u2192 Type u\u2081} {G : Type.{max u\u2080 v\u2080} \u2192 Type v\u2081} [inst : uliftable F G]\n  [functor G] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\nfunctor.map (f \u2218 ulift.down) (up x)\n\n/-- map function that moves down universes -/\ndef down_map {F : Type.{max u\u2080 v\u2080} \u2192 Type u\u2081} {G : Type \u2192 Type v\u2081} [inst : uliftable G F]\n  [functor F] {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\ndown (functor.map (ulift.up \u2218 f) x : F (ulift \u03b2))\n\n@[simp]\nlemma up_down  {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} (x : g (ulift \u03b1)) : up (down x : f \u03b1) = x :=\n(uliftable.congr f g equiv.ulift.symm).right_inv _\n\n@[simp]\nlemma down_up  {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n  {\u03b1} (x : f \u03b1) : 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 := \u03bb \u03b1 \u03b2 F, F }\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {s : Type u\u2080} {s' : Type u\u2081}\n  {m : Type u\u2080 \u2192 Type v\u2080} {m' : Type u\u2081 \u2192 Type v\u2081}\n  [uliftable m m']\n  (F : s \u2243 s') :\n  uliftable (state_t s m) (state_t s' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 G, state_t.equiv $ equiv.Pi_congr F $\n      \u03bb _, 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 \u2243 s') :\n  uliftable (reader_t s m) (reader_t s' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 G, reader_t.equiv $ equiv.Pi_congr F $\n      \u03bb _, 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 \u2243 r') :\n  uliftable (cont_t r m) (cont_t r' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2, 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 \u2243 w') :\n  uliftable (writer_t w m) (writer_t w' m') :=\n{ congr :=\n    \u03bb \u03b1 \u03b2 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 (\u03b1 : Type)\n  | nil  : Env \u03b1\n  | cons : \u03b1 \u2192 Env \u03b1 \u2192 Env \u03b1\n\n-- Env Operations\nnamespace Env\n\n/-- Append a hypothesis to the end of the environment. -/\n@[reducible]\ndef append : Env \u03b1 \u2192 \u03b1 \u2192 Env \u03b1\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 \u03b1 \u2192 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 \u03b1 \u2192 Nat\n  | .nil       => 0\n  | .cons _ as => as.length + 1\n\ntheorem length_cons_list_cons {a : \u03b1} {as : List \u03b1} {b : \u03b2} {bs : Env \u03b2} :\n  (a :: as).length = (Env.cons b bs).length \u2192\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 : (\u0393 : Env \u03b1) \u2192 Fin (\u0393.length) \u2192 Env \u03b1\n  | .cons _ as, \u27e80    , _\u27e9 => as\n  | .cons a as, \u27e8i + 1, h\u27e9 => .cons a <| as.delete \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9\n\n/-- Return the hypothesis at a given index without removing it. -/\n@[reducible]\ndef get : (\u0393 : Env \u03b1) \u2192 Fin (\u0393.length) \u2192 \u03b1\n  | .cons a _ , \u27e80    , _\u27e9 => a\n  | .cons _ as, \u27e8i + 1, h\u27e9 => as.get \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9\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 : (\u0393 : Env \u03b1) \u2192 (mask : List Bool) \u2192 (mask.length = \u0393.length) \u2192 Env \u03b1 \u00d7 Env \u03b1\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 \u03b1 \u2192 List \u03b1\n  | .nil       => []\n  | .cons a as => a :: toList as\n\n/-- Proposition of membership for an hypothesis in an environment. -/\ninductive Mem : \u03b1 \u2192 Env \u03b1 \u2192 Prop\n  | head (a : \u03b1) (as : Env \u03b1)         : Mem a (.cons a as)\n  | tail (a : \u03b1) {b : \u03b1} (as : Env \u03b1) : Mem b as \u2192 Mem b (.cons a as)\n\ninstance : Membership \u03b1 (Env \u03b1) where\n  mem := Mem\n\ninstance : Coe (Env \u03b1) (List \u03b1) where\n  coe := toList\n\ndelab_rule toList\n  | `($_ $env) => `($env)\n\ninstance [ToString \u03b1] : ToString <| Env \u03b1 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 \u2208 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 \u2208 Ps \u2192 P \u2208 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 \u27e8i + 1, h\u27e9 = (Env.cons P <| Ps.delete \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9)\n:= by\n  rw' [Env.delete]\n  \u00b7 exact P\n  \u00b7 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 \u27e8i + 1, h\u27e9 = Ps.get \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9\n:= by\n  rw' [Env.get]\n  \u00b7 exact Ps\n  \u00b7 exact Nat.zero_lt_succ _\n\ntheorem env_big_op_sep_append [BI PROP] {\u0393 : Env PROP} {P : PROP} : [\u2217] (\u0393.append P) \u22a3\u22a2 [\u2217] \u0393 \u2217 P := by\n  induction \u0393\n  <;> simp only [Env.append, Env.toList]\n  case nil =>\n    simp only [big_op]\n    rw' [(left_id : emp \u2217 _ \u22a3\u22a2 _)]\n  case cons P' _ h_ind =>\n    rw' [\n      !big_op_sep_cons,\n      h_ind,\n      \u2190 (assoc : _ \u22a3\u22a2 (P' \u2217 _) \u2217 P)]\n\ntheorem env_big_op_and_append [BI PROP] {\u0393 : Env PROP} {P : PROP} : \u25a1 [\u2227] (\u0393.append P) \u22a3\u22a2 \u25a1 [\u2227] \u0393 \u2217 \u25a1 P := by\n  induction \u0393\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 \u2217 _ \u22a3\u22a2 _)]\n  case cons P' _ h_ind =>\n    rw' [\n      !big_op_and_cons,\n      !intuitionistically_and,\n      !and_sep_intuitionistically,\n      h_ind,\n      \u2190 (assoc : _ \u22a3\u22a2 (\u25a1 P' \u2217 _) \u2217 \u25a1 P)]\n\ntheorem env_idx_rec [BI PROP] (P : (\u0393 : Env PROP) \u2192 Fin \u0393.length \u2192 Prop)\n  (zero : \u2200 {P'} {\u0393'} {is_lt}, P (.cons P' \u0393') \u27e80, is_lt\u27e9)\n  (succ : \u2200 {P'} {\u0393'} {val} {is_lt} {is_lt'}, P \u0393' \u27e8val, is_lt\u27e9 \u2192 P (.cons P' \u0393') \u27e8Nat.succ val, is_lt'\u27e9) :\n  \u2200 \u0393 i, P \u0393 i\n:= by\n  intro \u0393 i\n  let \u27e8val, is_lt\u27e9 := i\n  induction val generalizing \u0393\n  case zero =>\n    cases \u0393 with\n    | nil =>\n      contradiction\n    | cons P' \u0393' =>\n      exact zero\n  case succ val h_ind =>\n    cases \u0393 with\n    | nil =>\n      contradiction\n    | cons P' \u0393' =>\n      let is_lt := Nat.lt_of_succ_lt_succ is_lt\n      specialize h_ind \u0393' \u27e8val, is_lt\u27e9 is_lt\n      exact succ h_ind\n\ntheorem env_big_op_sep_delete_get [BI PROP] {\u0393 : Env PROP} (i : Fin \u0393.length) :\n  [\u2217] \u0393 \u22a3\u22a2 [\u2217] (\u0393.delete i) \u2217 (\u0393.get i)\n:= by\n  induction \u0393, 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' \u2217 _ \u22a3\u22a2 _)]\n  case succ P' _ _ _ _ h_ind =>\n    rw' [\n      env_delete_cons,\n      env_get_cons,\n      !big_op_sep_cons,\n      \u2190 (assoc : _ \u22a3\u22a2 (P' \u2217 _) \u2217 _),\n      \u2190 h_ind]\n\ntheorem env_big_op_and_delete_get [BI PROP] {\u0393 : Env PROP} (i : Fin \u0393.length) :\n  \u25a1 [\u2227] \u0393 \u22a3\u22a2 \u25a1 [\u2227] (\u0393.delete i) \u2217 \u25a1 (\u0393.get i)\n:= by\n  induction \u0393, 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 : \u25a1 P' \u2217 _ \u22a3\u22a2 _)]\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      \u2190 (assoc : _ \u22a3\u22a2 (\u25a1 P' \u2217 _) \u2217 _),\n      \u2190 h_ind]\n\ntheorem env_delete_length [BI PROP] {\u0393 : Env PROP} {i : Fin \u0393.length} : (\u0393.delete i).length = \u0393.length - 1 := by\n  induction \u0393, 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    \u00b7 apply Nat.succ_le_of_lt\n      exact Nat.zero_lt_of_lt is_lt\n\ntheorem env_delete_idx_length [BI PROP] {\u0393 : Env PROP} {i : Fin \u0393.length} : i \u2264 (\u0393.delete i).length := by\n  let \u27e8val, is_lt\u27e9 := 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  \u00b7 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] {\u0393 : Env PROP} {i : Fin \u0393.length} {j : Nat} : j < i \u2192 j < (\u0393.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] {\u0393 : Env PROP} (i : Fin \u0393.length) (h : 0 < i.val) : \u2200 {j}, (i - 1) < (\u0393.delete j).length := by\n  intro j\n  let \u27e8val, is_lt\u27e9 := 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  \u00b7 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} {\u0393\u2081 \u0393\u2082 : Env PROP} {h : (false :: bs).length = (Env.cons P Ps).length} :\n  (\u0393\u2081, \u0393\u2082) = (Env.cons P Ps).split (false :: bs) h \u2192\n  \u2203 (\u0393\u2082' : Env PROP), \u0393\u2082 = Env.cons P \u0393\u2082' \u2227\n  \u2203 (h' : bs.length = Ps.length), (\u0393\u2081, \u0393\u2082') = 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} {\u0393\u2081 \u0393\u2082 : Env PROP} {h : (true :: bs).length = (Env.cons P Ps).length} :\n  (\u0393\u2081, \u0393\u2082) = (Env.cons P Ps).split (true :: bs) h \u2192\n  \u2203 (\u0393\u2081' : Env PROP), \u0393\u2081 = Env.cons P \u0393\u2081' \u2227\n  \u2203 (h' : bs.length = Ps.length), (\u0393\u2081', \u0393\u2082) = 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] {\u0393 \u0393\u2081 \u0393\u2082 : Env PROP} {mask : List Bool} {h : mask.length = \u0393.length} :\n  (\u0393\u2081, \u0393\u2082) = \u0393.split mask h \u2192\n  ([\u2217] \u0393 : PROP) \u22a2 [\u2217] \u0393\u2081 \u2217 [\u2217] \u0393\u2082\n:= by\n  intro h_split\n  induction \u0393 generalizing mask \u0393\u2081 \u0393\u2082\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 \u2217 _ \u22a3\u22a2 _)]\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 \u27e8_, h_split_P, _, h_split_Ps\u27e9 := 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 : _ \u2217 (P \u2217 _) \u22a3\u22a2 _),\n          (comm : _ \u2217 P \u22a3\u22a2 _),\n          \u2190 (assoc : _ \u22a3\u22a2 (P \u2217 _) \u2217 _),\n          h_ind h_split_Ps]\n      case true =>\n        let \u27e8_, h_split_P, _, h_split_Ps\u27e9 := env_split_cons_true h_split\n        rw' [h_split_P]\n        simp only [Env.toList]\n        rw' [\n          !big_op_sep_cons,\n          \u2190 (assoc : _ \u22a3\u22a2 (P \u2217 _) \u2217 _),\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 \u2192 PROP\n  | \u27e8\u0393\u209a, \u0393\u209b\u27e9 => `[iprop| \u25a1 [\u2227] \u0393\u209a \u2217 [\u2217] \u0393\u209b]\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] (\u0394 : Envs PROP) (Q : PROP) : Prop :=\n  of_envs \u0394 \u22a2 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\u209a l\u209b : Nat)\n  | p : Fin l\u209a \u2192 EnvsIndex l\u209a l\u209b\n  | s : Fin l\u209b \u2192 EnvsIndex l\u209a l\u209b\n\n/-- Return the hypothesis type of the hypothesis referenced by the given index. -/\n@[reducible]\ndef EnvsIndex.type : EnvsIndex l\u209a l\u209b \u2192 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\u209a l\u209b \u2192 Nat\n  | .p \u27e8val, _\u27e9 => val\n  | .s \u27e8val, _\u27e9 => val\n\n/-- `EnvsIndex` type for the given `Envs` object. -/\nabbrev EnvsIndex.of [BI PROP] (\u0394 : Envs PROP) := EnvsIndex \u0394.intuitionistic.length \u0394.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 \u2192 MetaM (TSyntax `term)\n  | \u27e8.intuitionistic, index, length\u27e9 =>\n    ``(EnvsIndex.p \u27e8$(quote index), by show $(quote index) < $(quote length) ; decide\u27e9)\n  | \u27e8.spatial, index, length\u27e9 =>\n    ``(EnvsIndex.s \u27e8$(quote index), by show $(quote index) < $(quote length) ; decide\u27e9)\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 \u2192 PROP \u2192 Envs PROP \u2192 Envs PROP\n  | true,  P, \u27e8\u0393\u209a, \u0393\u209b\u27e9 => \u27e8\u0393\u209a.append P, \u0393\u209b\u27e9\n  | false, P, \u27e8\u0393\u209a, \u0393\u209b\u27e9 => \u27e8\u0393\u209a, \u0393\u209b.append P\u27e9\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 \u2192 (\u0394 : Envs PROP) \u2192 EnvsIndex.of \u0394 \u2192 Envs PROP\n  | true , \u27e8\u0393\u209a, \u0393\u209b\u27e9, .p i => \u27e8\u0393\u209a.delete i, \u0393\u209b\u27e9\n  | false, \u27e8\u0393\u209a, \u0393\u209b\u27e9, .p _ => \u27e8\u0393\u209a, \u0393\u209b\u27e9\n  | _    , \u27e8\u0393\u209a, \u0393\u209b\u27e9, .s i => \u27e8\u0393\u209a, \u0393\u209b.delete i\u27e9\n\n/-- Return the hypothesis at the given index. -/\n@[reducible]\ndef lookup [BI PROP] : (\u0394 : Envs PROP) \u2192 EnvsIndex.of \u0394 \u2192 Bool \u00d7 PROP\n  | \u27e8\u0393\u209a, _\u27e9, .p i => (true, \u0393\u209a.get i)\n  | \u27e8_, \u0393\u209b\u27e9, .s i => (false, \u0393\u209b.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] (\u0394 : Envs PROP) (rp : Bool) (i : EnvsIndex.of \u0394) (p : Bool) (P : PROP) : Envs PROP :=\n  \u0394.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] : (\u0394 : Envs PROP) \u2192 (mask : List Bool) \u2192 (mask.length = \u0394.spatial.length) \u2192 Envs PROP \u00d7 Envs PROP\n  | \u27e8\u0393\u209a, \u0393\u209b\u27e9, mask, h =>\n    let \u27e8\u0393\u209b\u2081, \u0393\u209b\u2082\u27e9 := \u0393\u209b.split mask h\n    (\u27e8\u0393\u209a, \u0393\u209b\u2081\u27e9, \u27e8\u0393\u209a, \u0393\u209b\u2082\u27e9)\n\n/-- Update an index `j` of `\u0394` to reference the same hypothesis in `\u0394.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] (\u0394 : Envs PROP) : (rp : Bool) \u2192 (i : EnvsIndex.of \u0394) \u2192 (j : EnvsIndex.of \u0394) \u2192 (i.type = j.type \u2192 i.val \u2260 j.val) \u2192 EnvsIndex.of (\u0394.delete rp i)\n  | rp, .p i, .s \u27e8val, is_lt\u27e9, _ =>\n    .s \u27e8val, by cases rp <;> simp [is_lt]\u27e9\n  | _, .s i, .p \u27e8val, is_lt\u27e9, _ =>\n    .p \u27e8val, by simp [delete, is_lt]\u27e9\n  | false, .p _, .p \u27e8val, is_lt\u27e9, _ =>\n    .p \u27e8val, by simp [delete, is_lt]\u27e9\n  | true, .p \u27e8val_d, is_lt_d\u27e9, .p \u27e8val, is_lt\u27e9, h_ne =>\n    if h_lt : val < val_d then\n      EnvsIndex.p \u27e8val, env_delete_idx_length_of_lt h_lt\u27e9\n    else if h_gt : val_d < val then\n      EnvsIndex.p \u27e8val - 1, env_delete_idx_pred_length \u27e8val, is_lt\u27e9 (Nat.zero_lt_of_lt h_gt)\u27e9\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 \u27e8val_d, is_lt_d\u27e9, .s \u27e8val, is_lt\u27e9, h_ne =>\n    if h_lt : val < val_d then\n      EnvsIndex.s \u27e8val, by simp only [delete] ; exact env_delete_idx_length_of_lt h_lt\u27e9\n    else if h_gt : val_d < val then\n      EnvsIndex.s \u27e8val - 1, by simp only [delete] ; exact env_delete_idx_pred_length \u27e8val, is_lt\u27e9 (Nat.zero_lt_of_lt h_gt)\u27e9\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] {\u0394 : Envs PROP} (p : Bool) (Q : PROP) :\n  of_envs \u0394 \u22a2 \u25a1?p Q -\u2217 of_envs (\u0394.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 : _ \u2217 (_ \u2217 Q) \u22a3\u22a2 _),\n      (comm : _ \u2217 Q \u22a3\u22a2 _)]\n  case true =>\n    rw' [\n      env_big_op_and_append,\n      (comm : _ \u2217 \u25a1 Q \u22a3\u22a2 _),\n      \u2190 (assoc : _ \u22a3\u22a2 (\u25a1 Q \u2217 _) \u2217 _)]\n\ntheorem envs_lookup_delete_sound [BI PROP] {\u0394 : Envs PROP} {i : EnvsIndex.of \u0394} {p : Bool} {P : PROP} (rp : Bool) :\n  \u0394.lookup i = (p, P) \u2192\n  of_envs \u0394 \u22a2 \u25a1?p P \u2217 of_envs (\u0394.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 : \u0394.spatial.get i \u2217 _ \u22a3\u22a2 _),\n      \u2190 (assoc : _ \u22a3\u22a2 _ \u2217 _),\n      \u2190 env_big_op_sep_delete_get]\n  case p i =>\n    cases rp\n    <;> simp only\n    case true =>\n      rw' [\n        (assoc : _ \u2217 _ \u22a3\u22a2 _),\n        (comm : \u25a1 \u0394.intuitionistic.get i \u2217 _ \u22a3\u22a2 _),\n        \u2190 env_big_op_and_delete_get i]\n    case false =>\n      rw' [\n        (assoc : _ \u2217 _ \u22a3\u22a2 _),\n        (comm : \u25a1 \u0394.intuitionistic.get i \u2217 _ \u22a3\u22a2 _),\n        env_big_op_and_delete_get i,\n        \u2190 (assoc : _ \u22a3\u22a2 (_ \u2217 _) \u2217 \u25a1 \u0394.intuitionistic.get i),\n        \u2190 intuitionistically_sep_dup]\n\ntheorem envs_lookup_replace_sound [BI PROP] {\u0394 : Envs PROP} {i : EnvsIndex.of \u0394} {p : Bool} {P : PROP} (rp : Bool) (q : Bool) (Q : PROP) :\n  \u0394.lookup i = (p, P) \u2192\n  of_envs \u0394 \u22a2 \u25a1?p P \u2217 (\u25a1?q Q -\u2217 of_envs (\u0394.replace rp i q Q))\n:= by\n  intro h_lookup\n  simp only [Envs.replace]\n  rw' [\n    \u2190 envs_append_sound q Q,\n    \u2190 envs_lookup_delete_sound rp h_lookup]\n\ntheorem envs_split_env_spatial_split [BI PROP] {\u0394 \u0394\u2081 \u0394\u2082 : Envs PROP} {mask : List Bool} {h : mask.length = \u0394.spatial.length} :\n  Envs.split \u0394 mask h = (\u0394\u2081, \u0394\u2082) \u2192\n  \u0394\u2081.intuitionistic = \u0394.intuitionistic \u2227\n  \u0394\u2082.intuitionistic = \u0394.intuitionistic \u2227\n  (\u0394\u2081.spatial, \u0394\u2082.spatial) = Env.split \u0394.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] {\u0394 \u0394\u2081 \u0394\u2082 : Envs PROP} {mask : List Bool} {h : mask.length = \u0394.spatial.length} :\n  \u0394.split mask h = (\u0394\u2081, \u0394\u2082) \u2192\n  of_envs \u0394 \u22a2 of_envs \u0394\u2081 \u2217 of_envs \u0394\u2082\n:= by\n  intro h_split_\u0394\n  let \u27e8h_split_\u0393\u209a\u2081, h_split_\u0393\u209a\u2082, h_split_\u0393\u209b\u27e9 := envs_split_env_spatial_split h_split_\u0394\n  simp only [of_envs]\n  rw' [\n    h_split_\u0393\u209a\u2081,\n    h_split_\u0393\u209a\u2082,\n    env_big_op_sep_split h_split_\u0393\u209b,\n    (assoc : _ \u2217 (\u25a1 _ \u2217 _) \u22a3\u22a2 _),\n    (comm : _ \u2217 \u25a1 _ \u22a3\u22a2 _),\n    (assoc : \u25a1 _ \u2217 (\u25a1 _ \u2217 _) \u22a3\u22a2 _),\n    \u2190 intuitionistically_sep_dup,\n    \u2190 (assoc : _ \u22a3\u22a2 (_ \u2217 _) \u2217 _)]\n\ntheorem envs_spatial_is_empty_intuitionistically [BI PROP] {\u0394 : Envs PROP} :\n  \u0394.spatial.isEmpty = true \u2192\n  of_envs \u0394 \u22a2 \u25a1 of_envs \u0394\n:= by\n  simp only [Env.isEmpty, of_envs]\n  cases \u0394.spatial\n  <;> simp [big_op]\n  rw' [\n    (right_id : _ \u2217 emp \u22a3\u22a2 _),\n    intuitionistically_idemp]\n\n-- AffineEnv\nclass AffineEnv [BI PROP] (\u0393 : Env PROP) where\n  affineEnv : \u2200 P, P \u2208 \u0393 \u2192 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) (\u0393 : Env PROP) :\n  [Affine P] \u2192\n  [AffineEnv \u0393] \u2192\n  AffineEnv (.cons P \u0393)\nwhere\n  affineEnv := by\n    intro P h\n    cases h\n    case head =>\n      exact \u27e8affine\u27e9\n    case tail h =>\n      exact affineEnv P h\n\ninstance (priority := default + 10) affineEnvBi (\u0393 : Env PROP) :\n  [BIAffine PROP] \u2192\n  AffineEnv \u0393\nwhere\n  affineEnv := by\n    intro P _\n    exact BIAffine.affine P\n\nscoped instance affineEnvSpatial [BI PROP] (\u0393 : Env PROP)\n  [inst : AffineEnv \u0393] :\n  Affine (`[iprop| [\u2217] \u0393] : PROP)\nwhere\n  affine := by\n    induction \u0393 generalizing inst\n    case nil =>\n      rw' [big_op_sep_nil]\n    case cons P Ps h_ind =>\n      have : AffineEnv Ps := \u27e8by\n        intro P h_Ps\n        exact inst.affineEnv P (env_mem_cons_2 h_Ps)\u27e9\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\u2014programming the prover\u2014is 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\u2026sub)goals until it cannot\nbe applied any further. -/\n\nlemma repeat_example :\n  even 4 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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  \u00ac 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\u2082 :\n  even 4 \u2227 even 7 \u2227 even 3 \u2227 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 \u2026\",\n  intro_and_even\n\nmeta def hello_then_intro_and_even : tactic unit :=\ndo\n  tactic.trace \"Proving evenness \u2026\",\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 \u2190 tactic.local_context,\n  tactic.trace ctx,\n  tactic.trace \"target:\",\n  P \u2190 tactic.target,\n  tactic.trace P,\n  tactic.trace \"all missing proofs:\",\n  Hs \u2190 tactic.get_goals,\n  tactic.trace Hs,\n  \u03c4s \u2190 list.mmap tactic.infer_type Hs,\n  tactic.trace \u03c4s\n\nlemma even_18_and_even_20 (\u03b1 : Type) (a : \u03b1) :\n  even 18 \u2227 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 \u2190 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  \u03c4 \u2190 tactic.infer_type h,\n  tactic.trace \u03c4,\n  tactic.trace \"type of type of h:\",\n  \u03c5 \u2190 tactic.infer_type \u03c4,\n  tactic.trace \u03c5,\n  tactic.apply h\n\nmeta def exact_list : list expr \u2192 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 \u2190 tactic.local_context,\n  exact_list hs\n\nlemma app_of_app {\u03b1 : Type} {p : \u03b1 \u2192 Prop} {a : \u03b1}\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 `\u2115 [] : 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  `(\u2115) : expr)\n#check (expr.mvar `uniq_name `pp_name `(\u2115) : expr)\n#check (expr.pi `pp_name binder_info.default `(\u2115)\n  (expr.sort level.zero) : expr)\n#check (expr.lam `pp_name binder_info.default `(\u2115)\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 (\u03bbn : \u2115, 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\u2081 : pexpr := ``(list.map (\u03bbn, n + 1) [1, 2, 3]),\n  let e\u2082 : pexpr := ``(list.map _ [1, 2, 3]),\n  tactic.trace e\u2081,\n  tactic.trace e\u2082\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 : \u2115),\n  let e : expr := `(%%x + 1),\n  tactic.trace e\n\nrun_cmd do\n  let x : expr  := `(@id \u2115),\n  let e : pexpr := ``(list.map %%x),\n  tactic.trace e\n\nrun_cmd do\n  let x : expr  := `(@id \u2115),\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) \u2190 tactic.target,\n  tactic.trace a,\n  tactic.trace b,\n  tactic.trace c,\n  `(@eq %%\u03b1 %%l %%r) \u2190 tactic.target,\n  tactic.trace \u03b1,\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 \u2190 tactic.get_env,\n  tactic.trace (environment.fold env 0 (\u03bbdecl n, n + 1))\n\n\n/-! ## First Example: A Conjuction-Destructing Tactic\n\nWe define a `destruct_and` tactic that automates the elimination of `\u2227` in\npremises, automating proofs such as these: -/\n\nlemma abcd_a (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  a :=\nand.elim_left h\n\nlemma abcd_b (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  b :=\nand.elim_left (and.elim_left (and.elim_right h))\n\nlemma abcd_bc (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  b \u2227 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 \u2192 tactic unit\n| h :=\n  do\n    t \u2190 tactic.infer_type h,\n    match t with\n    | `(%%a \u2227 %%b) :=\n      tactic.exact h\n      <|>\n      do {\n        ha \u2190 tactic.to_expr ``(and.elim_left %%h),\n        destruct_and_helper ha }\n      <|>\n      do {\n        hb \u2190 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 \u2190 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 \u2227 b \u2227 c) :\n  a :=\nby destruct_and `h\n\nlemma abc_b (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  b :=\nby destruct_and `h\n\nlemma abc_bc (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  b \u2227 c :=\nby destruct_and `h\n\nlemma abc_ac (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  a \u2227 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 \u2192 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 \u2190 tactic.get_env,\n  pure (environment.fold env [] (\u03bbdecl 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 \u2190 get_all_theorems,\n  list.mfirst (\u03bbnam,\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 : \u2115) (h : x = y) :\n  y = x :=\nby prove_direct\n\nlemma nat.eq_symm\u2082 (x y : \u2115) (h : x = y) :\n  y = x :=\nby library_search\n\nlemma list.reverse_twice (xs : list \u2115) :\n  list.reverse (list.reverse xs) = xs :=\nby prove_direct\n\nlemma list.reverse_twice_symm (xs : list \u2115) :\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\u2082 (xs : list \u2115) :\n  list.reverse (list.reverse xs) = xs :=\nby prove_direct_symm\n\nlemma list.reverse_twice_symm\u2082 (xs : list \u2115) :\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) 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.CongrTheorems\nimport Lean.Meta.Tactic.Assert\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Clear\nimport Lean.Meta.Tactic.Refl\nimport Lean.Meta.Tactic.Assumption\n\nnamespace Lean\nopen Meta\n\n/--\nPreprocessor before applying congruence theorem.\nTries to close new goals using `Eq.refl`, `HEq.refl`, and `assumption`.\nIt also tries to apply `heq_of_eq`.\n-/\ndef MVarId.congrPre (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let mvarId \u2190 mvarId.heqOfEq\n  try mvarId.refl; return none catch _ => pure ()\n  try mvarId.hrefl; return none catch _ => pure ()\n  if (\u2190 mvarId.assumptionCore) then return none\n  return some mvarId\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-/\nprivate def applyCongrThm? (mvarId : MVarId) (congrThm : CongrTheorem) : MetaM (List MVarId) := do\n  let mvarId \u2190 mvarId.assert (\u2190 mkFreshUserName `h_congr_thm) congrThm.type congrThm.proof\n  let (fvarId, mvarId) \u2190 mvarId.intro1P\n  let mvarIds \u2190 mvarId.apply (mkFVar fvarId) { synthAssignedInstances := false }\n  mvarIds.mapM fun mvarId => mvarId.tryClear fvarId\n\n/--\nTry to apply a `simp` congruence theorem.\n-/\ndef MVarId.congr? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n  mvarId.withContext do commitWhenSomeNoEx? do\n    mvarId.checkNotAssigned `congr\n    let target \u2190 mvarId.getType'\n    let some (_, lhs, _) := target.eq? | return none\n    let lhs := lhs.cleanupAnnotations\n    unless lhs.isApp do return none\n    let some congrThm \u2190 mkCongrSimp? lhs.getAppFn (subsingletonInstImplicitRhs := false) | return none\n    applyCongrThm? mvarId congrThm\n\n/--\nTry to apply a `hcongr` congruence theorem, and then tries to close resulting goals\nusing `Eq.refl`, `HEq.refl`, and assumption.\n-/\ndef MVarId.hcongr? (mvarId : MVarId) : MetaM (Option (List MVarId)) := do\n  commitWhenSomeNoEx? do\n    mvarId.checkNotAssigned `congr\n    let mvarId \u2190 mvarId.eqOfHEq\n    mvarId.withContext do\n      let target \u2190 mvarId.getType'\n      let some (_, lhs, _, _) := target.heq? | return none\n      let lhs := lhs.cleanupAnnotations\n      unless lhs.isApp do return none\n      let congrThm \u2190 mkHCongr lhs.getAppFn\n      applyCongrThm? mvarId congrThm\n\n/--\nTry to apply `implies_congr`.\n-/\ndef MVarId.congrImplies? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n  observing? do\n    let mvarId\u2081 :: mvarId\u2082 :: _ \u2190 mvarId.apply (\u2190 mkConstWithFreshMVarLevels ``implies_congr) | throwError \"unexpected number of goals\"\n    return [mvarId\u2081, mvarId\u2082]\n\n/--\nGiven a goal of the form `\u22a2 f as = f bs`, `\u22a2 (p \u2192 q) = (p' \u2192 q')`, or `\u22a2 HEq (f as) (f bs)`, try to apply congruence.\nIt takes proof irrelevance into account, and the fact that `Decidable p` is a subsingleton.\n-/\ndef MVarId.congrCore (mvarId : MVarId) : MetaM (List MVarId) := do\n  if let some mvarIds \u2190 mvarId.congr? then\n    pure mvarIds\n  else if let some mvarIds \u2190 mvarId.hcongr? then\n    pure mvarIds\n  else if let some mvarIds \u2190 mvarId.congrImplies? then\n    pure mvarIds\n  else\n    throwTacticEx `congr mvarId \"failed to apply congruence\"\n\n/--\nGiven a goal of the form `\u22a2 f as = f bs`, `\u22a2 (p \u2192 q) = (p' \u2192 q')`, or `\u22a2 HEq (f as) (f bs)`, try to apply congruence.\nIt takes proof irrelevance into account, and the fact that `Decidable p` is a subsingleton.\n\n* Applies `congr` recursively up to depth `depth`.\n* If `closePre := true`, it will attempt to close new goals\n  using `Eq.refl`, `HEq.refl`, and `assumption` with reducible transparency.\n* If `closePost := true`, it will try again on goals on which `congr` failed to make progress\n  with default transparency.\n-/\ndef MVarId.congrN (mvarId : MVarId) (depth : Nat := 1000000) (closePre := true) (closePost := true) : MetaM (List MVarId) := do\n  let (_, s) \u2190 go depth mvarId |>.run #[]\n  return s.toList\nwhere\n  post (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do\n    if closePost && (\u2190 getTransparency) != .reducible then\n      if let some mvarId \u2190 mvarId.congrPre then\n        modify (\u00b7.push mvarId)\n    else\n      modify (\u00b7.push mvarId)\n\n  go (n : Nat) (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do\n    if let some mvarId \u2190 if closePre then withReducible mvarId.congrPre else pure mvarId then\n      match n with\n      | 0 => post mvarId\n      | n+1 =>\n        let some mvarIds \u2190 observing? (m := MetaM) mvarId.congrCore\n          | post mvarId\n        mvarIds.forM (go n)\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/Congr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.08756383714196002, "lm_q1q2_score": 0.039350543457068586}}
{"text": "import basic\n\n/-- \n# How to play\nThe tactic `mk_random_game` will generate a random number between 1 and 100. You can then use the\ntactic `guess n` to guess a random number. If you get it right the goal will be solved otherwise it\nwill add a hypothesis saying whether you were too high or too low. You have 7 guesses.\n -/\nexample : true :=\nbegin\n  mk_random_game,\n  { \n    guess 10,\n    guess 20,\n    guess 30,\n    guess 40,\n    guess 50,\n    guess 60,\n  },\n  trivial,\nend", "meta": {"author": "foxthomson", "repo": "guessgame", "sha": "96d542b574949a883a9ed216a4f78e195d61878a", "save_path": "github-repos/lean/foxthomson-guessgame", "path": "github-repos/lean/foxthomson-guessgame/guessgame-96d542b574949a883a9ed216a4f78e195d61878a/src/game.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.07921033226026339, "lm_q1q2_score": 0.03929575706465798}}
{"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\u00e9sar dos Santos Oliveira\n    In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377\u2212402. 2009.\n    <http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf>\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 : \u03a0 {\u03b1}, \u03b1 \u2192 F \u03b1`. -/\ndef pure_transformation (F : Type u \u2192 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 \u2192 Type u) [Applicative F] [is_lawful_applicative F] {\u03b1 : Type u} (x : id \u03b1) : coe_fn (pure_transformation F) \u03b1 x = pure x :=\n  rfl\n\ntheorem map_eq_traverse_id {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {\u03b2 : Type u} {\u03b3 : Type u} (f : \u03b2 \u2192 \u03b3) : Functor.map f = traverse (id.mk \u2218 f) :=\n  funext fun (y : t \u03b2) => Eq.symm (is_lawful_traversable.traverse_eq_map_id f y)\n\ntheorem map_traverse {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b3 : Type u} (g : \u03b1 \u2192 F \u03b2) (f : \u03b2 \u2192 \u03b3) (x : t \u03b1) : Functor.map f <$> traverse g x = traverse (Functor.map f \u2218 g) x := sorry\n\ntheorem traverse_map {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b3 : Type u} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 \u03b2) (x : t \u03b1) : traverse f (g <$> x) = traverse (f \u2218 g) x := sorry\n\ntheorem pure_traverse {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] {\u03b1 : Type u} (x : t \u03b1) : 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 \u2192 Type u} [traversable t] [is_lawful_traversable t] {\u03b1 : Type u} (x : t \u03b1) : sequence (id.mk <$> x) = id.mk x := sorry\n\ntheorem comp_sequence {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {\u03b1 : Type u} (x : t (F (G \u03b1))) : sequence (functor.comp.mk <$> x) = functor.comp.mk (sequence <$> sequence x) := sorry\n\ntheorem naturality' {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {\u03b1 : Type u} (\u03b7 : applicative_transformation F G) (x : t (F \u03b1)) : coe_fn \u03b7 (t \u03b1) (sequence x) = sequence (coe_fn \u03b7 \u03b1 <$> x) := sorry\n\ntheorem traverse_id {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {\u03b1 : Type u} : traverse id.mk = id.mk := sorry\n\ntheorem traverse_comp {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b3 : Type u} (g : \u03b1 \u2192 F \u03b2) (h : \u03b2 \u2192 G \u03b3) : traverse (functor.comp.mk \u2218 Functor.map h \u2218 g) = functor.comp.mk \u2218 Functor.map (traverse h) \u2218 traverse g := sorry\n\ntheorem traverse_eq_map_id' {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {\u03b2 : Type u} {\u03b3 : Type u} (f : \u03b2 \u2192 \u03b3) : traverse (id.mk \u2218 f) = id.mk \u2218 Functor.map f := sorry\n\n-- @[functor_norm]\n\ntheorem traverse_map' {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {G : Type u \u2192 Type u} [Applicative G] [is_lawful_applicative G] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 G \u03b3) : traverse (h \u2218 g) = traverse h \u2218 Functor.map g := sorry\n\ntheorem map_traverse' {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {G : Type u \u2192 Type u} [Applicative G] [is_lawful_applicative G] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b3 : Type u} (g : \u03b1 \u2192 G \u03b2) (h : \u03b2 \u2192 \u03b3) : traverse (Functor.map h \u2218 g) = Functor.map (Functor.map h) \u2218 traverse g := sorry\n\ntheorem naturality_pf {t : Type u \u2192 Type u} [traversable t] [is_lawful_traversable t] {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {\u03b1 : Type u} {\u03b2 : Type u} (\u03b7 : applicative_transformation F G) (f : \u03b1 \u2192 F \u03b2) : traverse (coe_fn \u03b7 \u03b2 \u2218 f) = coe_fn \u03b7 (t \u03b2) \u2218 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  : \u2124) : a = b \u2192 (a+1 = b+1)  := begin \n    trace_goal, intro hyp, apply_fun  (\u03bb 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 `\u2223 X` in `conv` mode\nrepresents a goal of `\u22a2 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 : \u2124 \u2192 \u2124) (S : finset \u2124) (h : \u2200 m \u2208 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 \u2208 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 \u2208 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) 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.ProjFns\nimport Lean.Meta.WHNF\nimport Lean.Meta.InferType\nimport Lean.Meta.FunInfo\nimport Lean.Meta.LevelDefEq\nimport Lean.Meta.Check\nimport Lean.Meta.Offset\nimport Lean.Meta.ForEachExpr\nimport Lean.Meta.UnificationHint\n\nnamespace Lean.Meta\n\n/--\n  Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`.\n\n  Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean.\n  Example:\n    ```\n    (fun x : A => f ?m) =?= f\n    ```\n    The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/\nprivate def isDefEqEta (a b : Expr) : MetaM Bool := do\n  if a.isLambda && !b.isLambda then\n    let bType \u2190 inferType b\n    let bType \u2190 whnfD bType\n    match bType with\n    | Expr.forallE n d _ c =>\n      let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0))\n      checkpointDefEq <| Meta.isExprDefEqAux a b'\n    | _ => pure false\n  else\n    pure false\n\n/-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/\ndef isDefEqNative (s t : Expr) : MetaM LBool := do\n  let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t\n  let s? \u2190 reduceNative? s\n  let t? \u2190 reduceNative? t\n  match s?, t? with\n  | some s, some t => isDefEq s t\n  | some s, none   => isDefEq s t\n  | none,   some t => isDefEq s t\n  | none,   none   => pure LBool.undef\n\n/-- Support for reducing Nat basic operations. -/\ndef isDefEqNat (s t : Expr) : MetaM LBool := do\n  let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t\n  if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then\n    pure LBool.undef\n  else\n    let s? \u2190 reduceNat? s\n    let t? \u2190 reduceNat? t\n    match s?, t? with\n    | some s, some t => isDefEq s t\n    | some s, none   => isDefEq s t\n    | none,   some t => isDefEq s t\n    | none,   none   => pure LBool.undef\n\n/-- Support for constraints of the form `(\"...\" =?= String.mk cs)` -/\ndef isDefEqStringLit (s t : Expr) : MetaM LBool := do\n  let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t\n  if s.isStringLit && t.isAppOf `String.mk then\n    isDefEq (toCtorIfLit s) t\n  else if s.isAppOf `String.mk && t.isStringLit then\n    isDefEq s (toCtorIfLit t)\n  else\n    pure LBool.undef\n\n/--\n  Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned.\n  Remark: `n` may be 0. -/\ndef isEtaUnassignedMVar (e : Expr) : MetaM Bool := do\n  match e.etaExpanded? with\n  | some (Expr.mvar mvarId _) =>\n    if (\u2190 isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then\n      pure false\n    else if (\u2190 isExprMVarAssigned mvarId) then\n      pure false\n    else\n      pure true\n  | _   => pure false\n\n/-\n  First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases\n  Here, we say a case is easy if it is of the form\n\n       ?m =?= t\n       or\n       t  =?= ?m\n\n  where `?m` is unassigned.\n\n  These easy cases are not just an optimization. When\n  `?m` is a function, by assigning it to t, we make sure\n  a unification constraint (in the explicit part)\n  ```\n  ?m t =?= f s\n  ```\n  is not higher-order.\n\n  We also handle the eta-expanded cases:\n  ```\n  fun x\u2081 ... x\u2099 => ?m x\u2081 ... x\u2099 =?= t\n  t =?= fun x\u2081 ... x\u2099 => ?m x\u2081 ... x\u2099\n  ```\n  This is important because type inference often produces\n  eta-expanded terms, and without this extra case, we could\n  introduce counter intuitive behavior.\n\n  Pre: `paramInfo.size <= args\u2081.size = args\u2082.size`\n-/\nprivate partial def isDefEqArgsFirstPass\n    (paramInfo : Array ParamInfo) (args\u2081 args\u2082 : Array Expr) : MetaM (Option (Array Nat)) := do\n  let rec loop (i : Nat) (postponed : Array Nat) := do\n    if h : i < paramInfo.size then\n      let info := paramInfo.get \u27e8i, h\u27e9\n      let a\u2081 := args\u2081[i]\n      let a\u2082 := args\u2082[i]\n      if info.implicit || info.instImplicit then\n        if (\u2190 isEtaUnassignedMVar a\u2081 <||> isEtaUnassignedMVar a\u2082) then\n          if (\u2190 Meta.isExprDefEqAux a\u2081 a\u2082) then\n            loop (i+1) postponed\n          else\n            pure none\n        else\n          loop (i+1) (postponed.push i)\n      else if (\u2190 Meta.isExprDefEqAux a\u2081 a\u2082) then\n        loop (i+1) postponed\n      else\n        pure none\n    else\n      pure (some postponed)\n  loop 0 #[]\n\n@[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do\n  let mvarId? \u2190 getStuckMVar? e\n  match mvarId? with\n  | some mvarId => Meta.synthPending mvarId\n  | none        => pure false\n\nprivate partial def isDefEqArgs (f : Expr) (args\u2081 args\u2082 : Array Expr) : MetaM Bool :=\n  if h : args\u2081.size = args\u2082.size then do\n    let finfo \u2190 getFunInfoNArgs f args\u2081.size\n    let (some postponed) \u2190 isDefEqArgsFirstPass finfo.paramInfo args\u2081 args\u2082 | pure false\n    let rec processOtherArgs (i : Nat) : MetaM Bool := do\n      if h\u2081 : i < args\u2081.size then\n        let a\u2081 := args\u2081.get \u27e8i, h\u2081\u27e9\n        let a\u2082 := args\u2082.get \u27e8i, Eq.subst h h\u2081\u27e9\n        if (\u2190 Meta.isExprDefEqAux a\u2081 a\u2082) then\n          processOtherArgs (i+1)\n        else\n          pure false\n      else\n        pure true\n    if (\u2190 processOtherArgs finfo.paramInfo.size) then\n      postponed.allM fun i => do\n        /- Second pass: unify implicit arguments.\n           In the second pass, we make sure we are unfolding at\n           least non reducible definitions (default setting). -/\n        let a\u2081   := args\u2081[i]\n        let a\u2082   := args\u2082[i]\n        let info := finfo.paramInfo[i]\n        if info.instImplicit then\n          discard <| trySynthPending a\u2081\n          discard <| trySynthPending a\u2082\n        withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a\u2081 a\u2082\n    else\n      pure false\n  else\n    pure false\n\n/--\n  Check whether the types of the free variables at `fvars` are\n  definitionally equal to the types at `ds\u2082`.\n\n  Pre: `fvars.size == ds\u2082.size`\n\n  This method also updates the set of local instances, and invokes\n  the continuation `k` with the updated set.\n\n  We can't use `withNewLocalInstances` because the `isDeq fvarType d\u2082`\n  may use local instances. -/\n@[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds\u2082 : Array Expr) (k : MetaM Bool) : MetaM Bool :=\n  let rec loop (i : Nat) := do\n    if h : i < fvars.size then do\n      let fvar := fvars.get \u27e8i, h\u27e9\n      let fvarDecl \u2190 getFVarLocalDecl fvar\n      let fvarType := fvarDecl.type\n      let d\u2082       := ds\u2082[i]\n      if (\u2190 Meta.isExprDefEqAux fvarType d\u2082) then\n        match (\u2190 isClass? fvarType) with\n        | some className => withNewLocalInstance className fvar <| loop (i+1)\n        | none           => loop (i+1)\n      else\n        pure false\n    else\n      k\n  loop 0\n\n/- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`.\n   It accumulates the new free variables in `fvars`, and declare them at `lctx`.\n   We use the domain types of `e\u2081` to create the new free variables.\n   We store the domain types of `e\u2082` at `ds\u2082`. -/\nprivate partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e\u2081 e\u2082 : Expr) (ds\u2082 : Array Expr) : MetaM Bool :=\n  let process (n : Name) (d\u2081 d\u2082 b\u2081 b\u2082 : Expr) : MetaM Bool := do\n    let d\u2081     := d\u2081.instantiateRev fvars\n    let d\u2082     := d\u2082.instantiateRev fvars\n    let fvarId \u2190 mkFreshId\n    let lctx   := lctx.mkLocalDecl fvarId n d\u2081\n    let fvars  := fvars.push (mkFVar fvarId)\n    isDefEqBindingAux lctx fvars b\u2081 b\u2082 (ds\u2082.push d\u2082)\n  match e\u2081, e\u2082 with\n  | Expr.forallE n d\u2081 b\u2081 _, Expr.forallE _ d\u2082 b\u2082 _ => process n d\u2081 d\u2082 b\u2081 b\u2082\n  | Expr.lam     n d\u2081 b\u2081 _, Expr.lam     _ d\u2082 b\u2082 _ => process n d\u2081 d\u2082 b\u2081 b\u2082\n  | _,                      _                      =>\n    withReader (fun ctx => { ctx with lctx := lctx }) do\n      isDefEqBindingDomain fvars ds\u2082 do\n        Meta.isExprDefEqAux (e\u2081.instantiateRev fvars) (e\u2082.instantiateRev fvars)\n\n@[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do\n  let lctx \u2190 getLCtx\n  isDefEqBindingAux lctx #[] a b #[]\n\nprivate def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool :=\n  traceCtx `Meta.isDefEq.assign.checkTypes do\n    if !mvar.isMVar then\n      trace[Meta.isDefEq.assign.final] \"metavariable expected at {mvar} := {v}\"\n      return false\n    else\n      -- must check whether types are definitionally equal or not, before assigning and returning true\n      let mvarType \u2190 inferType mvar\n      let vType \u2190 inferType v\n      if (\u2190 withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then\n        trace[Meta.isDefEq.assign.final] \"{mvar} := {v}\"\n        assignExprMVar mvar.mvarId! v\n        pure true\n      else\n        trace[Meta.isDefEq.assign.typeMismatch] \"{mvar} : {mvarType} := {v} : {vType}\"\n        pure false\n\n/--\n  Auxiliary method for solving constraints of the form `?m xs := v`.\n  It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`.\n  `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`.\n  For example, suppose we have `xs` of the form `#[a, c]` where\n  ```\n  a : Nat\n  b : Nat := f a\n  c : b = a\n  ```\n  In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`,\n  and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal\n  to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`.\n  Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type\n  `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`,\n  and may not even be type correct.\n  The issue here is that we are not capturing the `let`-declarations.\n\n  This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t.\n  some `x` in `xs` depends on `y`.\n  `ys` is the `xs` with these extra let-declarations included.\n\n  In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces\n  `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`.\n\n  Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations.\n\n  This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`.\n  where the index is the position in the local context.\n-/\nprivate partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do\n  if not (\u2190 hasLetDeclsInBetween) then\n    mkLambdaFVars xs v\n  else\n    let ys \u2190 addLetDeps\n    trace[Meta.debug] \"ys: {ys}, v: {v}\"\n    mkLambdaFVars ys v\n\nwhere\n  /- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`.\n     We use it a quick-check to avoid the more expensive collection procedure. -/\n  hasLetDeclsInBetween : MetaM Bool := do\n    let check (lctx : LocalContext) : Bool := do\n      let start := lctx.getFVar! xs[0] |>.index\n      let stop  := lctx.getFVar! xs.back |>.index\n      for i in [start+1:stop] do\n        match lctx.getAt? i with\n        | some localDecl =>\n          if localDecl.isLet then\n            return true\n        | _ => pure ()\n      return false\n    if xs.size <= 1 then\n      pure false\n    else\n      check (\u2190 getLCtx)\n\n  /- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(\u2190 read)`.\n     The context `Nat` is the position of `xs[0]` in the local context. -/\n  collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do\n    let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit :=\n      checkCache e fun _ => do\n        match e with\n        | Expr.forallE _ d b _   => visit d; visit b\n        | Expr.lam _ d b _       => visit d; visit b\n        | Expr.letE _ t v b _    => visit t; visit v; visit b\n        | Expr.app f a _         => visit f; visit a\n        | Expr.mdata _ b _       => visit b\n        | Expr.proj _ _ b _      => visit b\n        | Expr.fvar fvarId _     =>\n          let localDecl \u2190 getLocalDecl fvarId\n          if localDecl.isLet && localDecl.index > (\u2190 read) then\n            modify fun s => s.insert localDecl.fvarId\n        | _ => pure ()\n    visit (\u2190 instantiateMVars e) |>.run\n\n  /-\n    Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards.\n    The `Nat` argument is the current position in the local context being visited, and it is less than\n    or equal to the position of `xs.back` in the local context.\n    The `Nat` context `(\u2190 read)` is the position of `xs[0]` in the local context.\n  -/\n  collectLetDepsAux : Nat \u2192 ReaderT Nat (StateRefT NameHashSet MetaM) Unit\n    | 0   => return ()\n    | i+1 => do\n      if i+1 == (\u2190 read) then\n        return ()\n      else\n        match (\u2190 getLCtx).getAt? (i+1) with\n        | none => collectLetDepsAux i\n        | some localDecl =>\n          if (\u2190 get).contains localDecl.fvarId then\n            collectLetDeclsFrom localDecl.type\n            match localDecl.value? with\n            | some val => collectLetDeclsFrom val\n            | _ =>  pure ()\n          collectLetDepsAux i\n\n  /- Computes the set `ys`. It is a set of `FVarId`s, -/\n  collectLetDeps : MetaM NameHashSet := do\n    let lctx \u2190 getLCtx\n    let start := lctx.getFVar! xs[0] |>.index\n    let stop  := lctx.getFVar! xs.back |>.index\n    let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId!\n    let (_, s) \u2190 collectLetDepsAux stop |>.run start |>.run s\n    return s\n\n  /- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that\n     some `x` in `xs` depends on. -/\n  addLetDeps : MetaM (Array Expr) := do\n    let lctx \u2190 getLCtx\n    let s \u2190 collectLetDeps\n    /- Convert `s` into the array `ys` -/\n    let start := lctx.getFVar! xs[0] |>.index\n    let stop  := lctx.getFVar! xs.back |>.index\n    let mut ys := #[]\n    for i in [start:stop+1] do\n      match lctx.getAt? i with\n      | none => pure ()\n      | some localDecl =>\n        if s.contains localDecl.fvarId then\n          ys := ys.push localDecl.toExpr\n    return ys\n\n/-\n  Each metavariable is declared in a particular local context.\n  We use the notation `C |- ?m : t` to denote a metavariable `?m` that\n  was declared at the local context `C` with type `t` (see `MetavarDecl`).\n  We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`.\n\n  The following method process the unification constraint\n\n       ?m@C a\u2081 ... a\u2099 =?= t\n\n  We say the unification constraint is a pattern IFF\n\n    1) `a\u2081 ... a\u2099` are pairwise distinct free variables that are \u200b*not*\u200b let-variables.\n    2) `a\u2081 ... a\u2099` are not in `C`\n    3) `t` only contains free variables in `C` and/or `{a\u2081, ..., a\u2099}`\n    4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C`\n    5) `?m` does not occur in `t`\n\n  Claim: we don't have to check free variable declarations. That is,\n  if `t` contains a reference to `x : A := v`, we don't need to check `v`.\n  Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3).\n  If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`.\n  So, condition 4 and 5 are satisfied.\n\n  If the conditions above have been satisfied, then the\n  solution for the unification constrain is\n\n    ?m := fun a\u2081 ... a\u2099 => t\n\n  Now, we consider some workarounds/approximations.\n\n A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3)\n     (precise) solution: unfold `x` in `t`.\n\n A2) Suppose some `a\u1d62` is in `C` (failed condition 2)\n     (approximated) solution (when `config.ctxApprox` is set to true) :\n     ignore condition and also use\n\n        ?m := fun a\u2081 ... a\u2099 => t\n\n   Here is an example where this approximation fails:\n   Given `C` containing `a : nat`, consider the following two constraints\n         ?m@C a =?= a\n         ?m@C b =?= a\n\n   If we use the approximation in the first constraint, we get\n         ?m := fun x => x\n   when we apply this solution to the second one we get a failure.\n\n   IMPORTANT: When applying this approximation we need to make sure the\n   abstracted term `fun a\u2081 ... a\u2099 => t` is type correct. The check\n   can only be skipped in the pattern case described above. Consider\n   the following example. Given the local context\n\n      (\u03b1 : Type) (a : \u03b1)\n\n   we try to solve\n\n     ?m \u03b1 =?= @id \u03b1 a\n\n   If we use the approximation above we obtain:\n\n     ?m := (fun \u03b1' => @id \u03b1' a)\n\n   which is a type incorrect term. `a` has type `\u03b1` but it is expected to have\n   type `\u03b1'`.\n\n   The problem occurs because the right hand side contains a free variable\n   `a` that depends on the free variable `\u03b1` being abstracted. Note that\n   this dependency cannot occur in patterns.\n\n   We can address this by type checking\n   the term after abstraction. This is not a significant performance\n   bottleneck because this case doesn't happen very often in practice\n   (262 times when compiling stdlib on Jan 2018). The second example\n   is trickier, but it also occurs less frequently (8 times when compiling\n   stdlib on Jan 2018, and all occurrences were at Init/Control when\n   we define monads and auxiliary combinators for them).\n   We considered three options for the addressing the issue on the second example:\n\n A3) `a\u2081 ... a\u2099` are not pairwise distinct (failed condition 1).\n   In Lean3, we would try to approximate this case using an approach similar to A2.\n   However, this approximation complicates the code, and is never used in the\n   Lean3 stdlib and mathlib.\n\n A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`.\n   If `?m'` is assigned, we substitute.\n   If not, we create an auxiliary metavariable with a smaller scope.\n   Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step.\n\n A5) If some `a\u1d62` is not a free variable,\n     then we use first-order unification (if `config.foApprox` is set to true)\n\n       ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k\n\n   reduces to\n\n       ?M a_1 ... a_i =?= f\n       a_{i+1}        =?= b_1\n       ...\n       a_{i+k}        =?= b_k\n\n\n A6) If (m =?= v) is of the form\n\n        ?m a_1 ... a_n =?= ?m b_1 ... b_k\n\n     then we use first-order unification (if `config.foApprox` is set to true)\n\n A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form\n     ```\n     ?m s\u2081 ... s\u2099 =?= t\n     ```\n     where `s\u2081 ... s\u2099` are arbitrary terms. We solve them by assigning the constant function to `?m`.\n     ```\n     ?m := fun _ ... _ => t\n     ```\n\n     In general, this approximation may produce bad solutions, and may prevent coercions from being tried.\n     For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`.\n     In this situation, the\n     elaborator generates the unification constraint\n     ```\n     ?m Prop =?= IO Bool\n     ```\n     It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation\n     produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from\n     the decidable proposition `x > 0` to `Bool`.\n\n     On the other hand, the constant approximation is desirable for elaborating the term\n     ```\n     let f (x : _) := pure \"hello\"; f ()\n     ```\n     with expected type `IO String`.\n     In this example, the following unification contraint is generated.\n     ```\n     ?m () String =?= IO String\n     ```\n     It is not a higher-order pattern, first-order approximation reduces it to\n     ```\n     ?m () =?= IO\n     ```\n     which fails to be solved. However, constant approximation solves it by assigning\n     ```\n     ?m := fun _ => IO\n     ```\n     Note that `f`s type is `(x : ?\u03b1) -> ?m x String`. The metavariable `?m` may depend on `x`.\n     If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide\n     whether we should apply it or not. The heuristic is based on observing where the constraints above come from.\n     In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to\n     be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model\n     a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f`\n     does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected\n     by any functional programmer used to non-dependently type languages (e.g., Haskell).\n     We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks\n     how many metavariable arguments are representing dependencies.\n-/\n\ndef mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do\n  mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs\n\nnamespace CheckAssignment\n\nbuiltin_initialize checkAssignmentExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `checkAssignment\nbuiltin_initialize outOfScopeExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `outOfScope\n\nstructure State where\n  cache : ExprStructMap Expr := {}\n\nstructure Context where\n  mvarId        : MVarId\n  mvarDecl      : MetavarDecl\n  fvars         : Array Expr\n  hasCtxLocals  : Bool\n  rhs           : Expr\n\nabbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM\n\ndef throwCheckAssignmentFailure : CheckAssignmentM \u03b1 :=\n  throw <| Exception.internal checkAssignmentExceptionId\n\ndef throwOutOfScopeFVar : CheckAssignmentM \u03b1 :=\n  throw <| Exception.internal outOfScopeExceptionId\n\nprivate def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do\n  return (\u2190 get).cache.find? e\n\nprivate def cache (e r : Expr) : CheckAssignmentM Unit := do\n  modify fun s => { s with cache := s.cache.insert e r }\n\ninstance : MonadCache Expr Expr CheckAssignmentM where\n  findCached? := findCached?\n  cache       := cache\n\n@[inline] private def visit (f : Expr \u2192 CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr :=\n  if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e)\n\nprivate def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do\n  let ctx \u2190 read\n  return m!\"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}\"\n\n@[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context }\n  let x : CheckAssignmentM (Option Expr) :=\n    catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId]\n      (do let e \u2190 x; return some e)\n      (fun _ => pure none)\n  x.run ctx |>.run' {}\n\nmutual\n\n  partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do\n    let ctxMeta \u2190 readThe Meta.Context\n    let ctx \u2190 read\n    if ctx.mvarDecl.lctx.containsFVar fvar then\n      pure fvar\n    else\n      let lctx := ctxMeta.lctx\n      match lctx.findFVar? fvar with\n      | some (LocalDecl.ldecl (value := v) ..) => visit check v\n      | _ =>\n        if ctx.fvars.contains fvar then pure fvar\n        else\n          traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar\n          throwOutOfScopeFVar\n\n  partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do\n    let mvarId := mvar.mvarId!\n    let ctx  \u2190 read\n    let mctx \u2190 getMCtx\n    if mvarId == ctx.mvarId then\n      traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo \"occurs check failed\"\n      throwCheckAssignmentFailure\n    else match mctx.getExprAssignment? mvarId with\n      | some v => check v\n      | none   =>\n        match mctx.findDecl? mvarId with\n        | none          => throwUnknownMVar mvarId\n        | some mvarDecl =>\n          if ctx.hasCtxLocals then\n            throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification\n          else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then\n            /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned.\n               We \"substract\" variables being abstracted because we use `elimMVarDeps` -/\n            pure mvar\n          else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then\n            traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId)\n            throwCheckAssignmentFailure\n          else\n            let ctxMeta \u2190 readThe Meta.Context\n            if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then\n              /- Create an auxiliary metavariable with a smaller context and \"checked\" type.\n                 Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains\n                 a metavariable that we also need to reduce the context.\n\n                 We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx`\n                 or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because\n                 `elimMVarDeps` will take care of them.\n\n                 First, we collect `toErase` the variables that need to be erased.\n                 Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`,\n                 we must also erase it.\n              -/\n              let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl =>\n                if ctx.mvarDecl.lctx.contains localDecl.fvarId then\n                  toErase\n                else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then\n                  if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then\n                    -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too\n                    toErase.push localDecl.fvarId\n                  else\n                    toErase\n                else\n                  toErase.push localDecl.fvarId\n              let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar =>\n                lctx.erase toEraseFVar\n              /- Compute new set of local instances. -/\n              let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId!\n              let mvarType \u2190 check mvarDecl.type\n              let newMVar \u2190 mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs\n              modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar }\n              pure newMVar\n            else\n              traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId)\n              throwCheckAssignmentFailure\n\n  /-\n    Auxiliary function used to \"fix\" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables,\n    and one of them is out-of-scope.\n    See `Expr.app` case at `check`.\n    If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope,\n    an assigning `?m := fun _ ... _ => ?n` -/\n  partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do\n    let mvarType \u2190 inferType mvar\n    forallBoundedTelescope mvarType numArgs fun xs _ => do\n      if xs.size != numArgs then pure false\n      else\n        let some v \u2190 mkLambdaFVarsWithLetDeps xs newMVar | return false\n        match (\u2190 checkAssignmentAux mvar.mvarId! #[] false v) with\n        | some v => checkTypesAndAssign mvar v\n        | none   => return false\n\n  -- See checkAssignment\n  partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do\n    run (check v) mvarId fvars hasCtxLocals v\n\n  partial def checkApp (e : Expr) : CheckAssignmentM Expr :=\n    e.withApp fun f args => do\n      let ctxMeta \u2190 readThe Meta.Context\n      if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then\n        let f \u2190 visit checkMVar f\n        catchInternalId outOfScopeExceptionId\n          (do\n            let args \u2190 args.mapM (visit check)\n            return mkAppN f args)\n          (fun ex => do\n            if !f.isMVar then\n              throw ex\n            else if (\u2190 isDelayedAssigned f.mvarId!) then\n              throw ex\n            else\n              let eType \u2190 inferType e\n              let mvarType \u2190 check eType\n              /- Create an auxiliary metavariable with a smaller context and \"checked\" type, assign `?f := fun _ => ?newMVar`\n                    Note that `mvarType` may be different from `eType`. -/\n              let ctx \u2190 read\n              let newMVar \u2190 mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType\n              if (\u2190 assignToConstFun f args.size newMVar) then\n                pure newMVar\n              else\n                throw ex)\n      else\n        let f \u2190 visit check f\n        let args \u2190 args.mapM (visit check)\n        return mkAppN f args\n\n  partial def check (e : Expr) : CheckAssignmentM Expr := do\n    match e with\n    | Expr.mdata _ b _     => return e.updateMData! (\u2190 visit check b)\n    | Expr.proj _ _ s _    => return e.updateProj! (\u2190 visit check s)\n    | Expr.lam _ d b _     => return e.updateLambdaE! (\u2190 visit check d) (\u2190 visit check b)\n    | Expr.forallE _ d b _ => return e.updateForallE! (\u2190 visit check d) (\u2190 visit check b)\n    | Expr.letE _ t v b _  => return e.updateLet! (\u2190 visit check t) (\u2190 visit check v) (\u2190 visit check b)\n    | Expr.bvar ..         => return e\n    | Expr.sort ..         => return e\n    | Expr.const ..        => return e\n    | Expr.lit ..          => return e\n    | Expr.fvar ..         => visit checkFVar e\n    | Expr.mvar ..         => visit checkMVar e\n    | Expr.app ..          =>\n      checkApp e\n      -- TODO: investigate whether the following feature is too expensive or not\n      /-\n      catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId]\n        (checkApp e)\n        fun ex => do\n          let e' \u2190 whnfR e\n          if e != e' then\n            check e'\n          else\n            throw ex\n      -/\nend\n\nend CheckAssignment\n\nnamespace CheckAssignmentQuick\n\npartial def check\n    (hasCtxLocals ctxApprox : Bool)\n    (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool :=\n  let rec visit (e : Expr) : Bool :=\n    if !e.hasExprMVar && !e.hasFVar then\n      true\n    else match e with\n    | Expr.mdata _ b _     => visit b\n    | Expr.proj _ _ s _    => visit s\n    | Expr.app f a _       => visit f && visit a\n    | Expr.lam _ d b _     => visit d && visit b\n    | Expr.forallE _ d b _ => visit d && visit b\n    | Expr.letE _ t v b _  => visit t && visit v && visit b\n    | Expr.bvar ..         => true\n    | Expr.sort ..         => true\n    | Expr.const ..        => true\n    | Expr.lit ..          => true\n    | Expr.fvar fvarId ..  =>\n      if mvarDecl.lctx.contains fvarId then true\n      else match lctx.find? fvarId with\n        | some (LocalDecl.ldecl (value := v) ..) => false -- need expensive CheckAssignment.check\n        | _ =>\n          if fvars.any fun x => x.fvarId! == fvarId then true\n          else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it\n    | Expr.mvar mvarId' _  =>\n      match mctx.getExprAssignment? mvarId' with\n      | some _ => false -- use CheckAssignment.check to instantiate\n      | none   =>\n        if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception\n        else match mctx.findDecl? mvarId' with\n          | none           => false\n          | some mvarDecl' =>\n            if hasCtxLocals then false -- use CheckAssignment.check\n            else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true\n            else false -- use CheckAssignment.check\n  visit e\n\nend CheckAssignmentQuick\n\n/--\n  Auxiliary function for handling constraints of the form `?m a\u2081 ... a\u2099 =?= v`.\n  It will check whether we can perform the assignment\n  ```\n  ?m := fun fvars => v\n  ```\n  The result is `none` if the assignment can't be performed.\n  The result is `some newV` where `newV` is a possibly updated `v`. This method may need\n  to unfold let-declarations. -/\ndef checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do\n  /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none`\n     to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/\n  for fvar in fvars do\n    unless (\u2190 occursCheck mvarId (\u2190 inferType fvar)) do\n      return none\n  if !v.hasExprMVar && !v.hasFVar then\n    pure (some v)\n  else\n    let mvarDecl \u2190 getMVarDecl mvarId\n    let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar\n    let ctx \u2190 read\n    let mctx \u2190 getMCtx\n    if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then\n      pure (some v)\n    else\n      let v \u2190 instantiateMVars v\n      CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v\n\nprivate def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=\n  match v with\n  | Expr.app f a _ =>\n    if args.isEmpty then\n      pure false\n    else\n      Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f\n  | _              => pure false\n\n/-\n  Auxiliary method for applying first-order unification. It is an approximation.\n  Remark: this method is trying to solve the unification constraint:\n\n      ?m a\u2081 ... a\u2099 =?= v\n\n   It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`.\n\n   We have added support for unfolding here because we want to be able to solve unification problems such as\n\n      ?m Unit =?= ITactic\n\n   where `ITactic` is defined as\n\n   def ITactic := Tactic Unit\n-/\nprivate partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=\n  let rec loop (v : Expr) := do\n    let cfg \u2190 getConfig\n    if !cfg.foApprox then\n      pure false\n    else\n      trace[Meta.isDefEq.foApprox] \"{mvar} {args} := {v}\"\n      let v := v.headBeta\n      if (\u2190 checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then\n        pure true\n      else\n        match (\u2190 unfoldDefinition? v) with\n        | none   => pure false\n        | some v => loop v\n  loop v\n\nprivate partial def simpAssignmentArgAux : Expr \u2192 MetaM Expr\n  | Expr.mdata _ e _       => simpAssignmentArgAux e\n  | e@(Expr.fvar fvarId _) => do\n    let decl \u2190 getLocalDecl fvarId\n    match decl.value? with\n    | some value => simpAssignmentArgAux value\n    | _          => pure e\n  | e => pure e\n\n/- Auxiliary procedure for processing `?m a\u2081 ... a\u2099 =?= v`.\n   We apply it to each `a\u1d62`. It instantiates assigned metavariables if `a\u1d62` is of the form `f[?n] b\u2081 ... b\u2098`,\n   and then removes metadata, and zeta-expand let-decls. -/\nprivate def simpAssignmentArg (arg : Expr) : MetaM Expr := do\n  let arg \u2190 if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg\n  simpAssignmentArgAux arg\n\n/- Assign `mvar := fun a_1 ... a_{numArgs} => v`.\n   We use it at `processConstApprox` and `isDefEqMVarSelf` -/\nprivate def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do\n  let mvarDecl \u2190 getMVarDecl mvar.mvarId!\n  forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do\n    if xs.size != numArgs then\n      pure false\n    else\n      let some v \u2190 mkLambdaFVarsWithLetDeps xs v | pure false\n      match (\u2190 checkAssignment mvar.mvarId! #[] v) with\n      | none   => pure false\n      | some v =>\n        trace[Meta.isDefEq.constApprox] \"{mvar} := {v}\"\n        checkTypesAndAssign mvar v\n\nprivate def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do\n  let cfg \u2190 getConfig\n  let mvarId := mvar.mvarId!\n  let mvarDecl \u2190 getMVarDecl mvarId\n  if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then\n    assignConst mvar numArgs v\n  else\n    pure false\n\n/-- Tries to solve `?m a\u2081 ... a\u2099 =?= v` by assigning `?m`.\n    It assumes `?m` is unassigned. -/\nprivate partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool :=\n  traceCtx `Meta.isDefEq.assign do\n    trace[Meta.isDefEq.assign] \"{mvarApp} := {v}\"\n    let mvar := mvarApp.getAppFn\n    let mvarDecl \u2190 getMVarDecl mvar.mvarId!\n    let rec process (i : Nat) (args : Array Expr) (v : Expr) := do\n      let cfg \u2190 getConfig\n      let useFOApprox (args : Array Expr) : MetaM Bool :=\n        processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v\n      if h : i < args.size then\n        let arg := args.get \u27e8i, h\u27e9\n        let arg \u2190 simpAssignmentArg arg\n        let args := args.set \u27e8i, h\u27e9 arg\n        match arg with\n        | Expr.fvar fvarId _ =>\n          if args[0:i].any fun prevArg => prevArg == arg then\n            useFOApprox args\n          else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then\n            useFOApprox args\n          else\n            process (i+1) args v\n        | _ =>\n          useFOApprox args\n      else\n        let v \u2190 instantiateMVars v -- enforce A4\n        if v.getAppFn == mvar then\n          -- using A6\n          useFOApprox args\n        else\n          let mvarId := mvar.mvarId!\n          match (\u2190 checkAssignment mvarId args v) with\n          | none   => useFOApprox args\n          | some v => do\n            trace[Meta.isDefEq.assign.beforeMkLambda] \"{mvar} {args} := {v}\"\n            let some v \u2190 mkLambdaFVarsWithLetDeps args v | return false\n            if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then\n              /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced\n                 a type incorrect term. See discussion at A2 -/\n              if (\u2190 isTypeCorrect v) then\n                checkTypesAndAssign mvar v\n              else\n                trace[Meta.isDefEq.assign.typeError] \"{mvar} := {v}\"\n                useFOApprox args\n            else\n              checkTypesAndAssign mvar v\n    process 0 mvarApp.getAppArgs v\n\n/--\n  Similar to processAssignment, but if it fails, compute v's whnf and try again.\n  This helps to solve constraints such as `?m =?= { \u03b1 := ?m, ... }.\u03b1`\n  Note this is not perfect solution since we still fail occurs check for constraints such as\n  ```lean\n    ?m =?= List { \u03b1 := ?m, \u03b2 := Nat }.\u03b2\n  ```\n-/\nprivate def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do\n  if (\u2190 processAssignment mvarApp v) then\n    return true\n  else\n    let vNew \u2190 whnf v\n    if vNew != v then\n      if mvarApp == vNew then\n        return true\n      else\n        processAssignment mvarApp vNew\n    else\n      return false\n\nprivate def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do\n  match t.getAppFn with\n  | Expr.const c _ _ =>\n    match (\u2190 getConst? c) with\n    | r@(some info) => if info.hasValue then return r else return none\n    | _             => return none\n  | _ => pure none\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isListLevelDefEq (us vs : List Level) : MetaM LBool :=\n  toLBoolM <| isListLevelDefEqAux us vs\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do\n  trace[Meta.isDefEq.delta.unfoldLeft] fn\n  toLBoolM <| Meta.isExprDefEqAux t s\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do\n  trace[Meta.isDefEq.delta.unfoldRight] fn\n  toLBoolM <| Meta.isExprDefEqAux t s\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do\n  trace[Meta.isDefEq.delta.unfoldLeftRight] fn\n  toLBoolM <| Meta.isExprDefEqAux t s\n\n/-- Try to solve `f a\u2081 ... a\u2099 =?= f b\u2081 ... b\u2099` by solving `a\u2081 =?= b\u2081, ..., a\u2099 =?= b\u2099`.\n\n    Auxiliary method for isDefEqDelta -/\nprivate def tryHeuristic (t s : Expr) : MetaM Bool :=\n  let tFn := t.getAppFn\n  let sFn := s.getAppFn\n  traceCtx `Meta.isDefEq.delta do\n    /-\n      We process arguments before universe levels to reduce a source of brittleness in the TC procedure.\n\n      In the TC procedure, we can solve problems containing metavariables.\n      If the TC procedure tries to assign one of these metavariables, it interrupts the search\n      using a \"stuck\" exception. The elaborator catches it, and \"interprets\" it as \"we should try again later\".\n      Now suppose we have a TC problem, and there are two \"local\" candidate instances we can try: \"bad\" and \"good\".\n      The \"bad\" candidate is stuck because of a universe metavariable in the TC problem.\n      If we try \"bad\" first, the TC procedure is interrupted. Moreover, if we have ignored the exception,\n      \"bad\" would fail anyway trying to assign two different free variables `\u03b1 =?= \u03b2`.\n      Example: `Preorder.{?u} \u03b1 =?= Preorder.{?v} \u03b2`, where `?u` and `?v` are universe metavariables that were\n      not created by the TC procedure.\n      The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the \"stuck\" exception,\n      but it would have failed anyway if we had continued processing it.\n      By solving the arguments first, we make the example above fail without throwing the \"stuck\" exception.\n\n      TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag.\n      Then the entry-point for `isDefEq` checks the flag before returning `true`.\n    -/\n    checkpointDefEq do\n      let b \u2190 isDefEqArgs tFn t.getAppArgs s.getAppArgs\n              <&&>\n              isListLevelDefEqAux tFn.constLevels! sFn.constLevels!\n      unless b do\n        trace[Meta.isDefEq.delta] \"heuristic failed {t} =?= {s}\"\n      pure b\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate abbrev unfold (e : Expr) (failK : MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  match (\u2190 unfoldDefinition? e) with\n  | some e => successK e\n  | none   => failK\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do\n  match t, s with\n  | Expr.const _ ls\u2081 _, Expr.const _ ls\u2082 _ => isListLevelDefEq ls\u2081 ls\u2082\n  | Expr.app _ _ _,     Expr.app _ _ _     =>\n    if (\u2190 tryHeuristic t s) then\n      pure LBool.true\n    else\n      unfold t\n       (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s))\n       (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))\n  | _, _ => pure LBool.false\n\nprivate def sameHeadSymbol (t s : Expr) : Bool :=\n  match t.getAppFn, s.getAppFn with\n  | Expr.const c\u2081 _ _, Expr.const c\u2082 _ _ => true\n  | _,                 _                 => false\n\n/--\n  - If headSymbol (unfold t) == headSymbol s, then unfold t\n  - If headSymbol (unfold s) == headSymbol t, then unfold s\n  - Otherwise unfold t and s if possible.\n\n  Auxiliary method for isDefEqDelta -/\nprivate def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=\n  unfold t\n    (unfold s\n      (pure LBool.undef) -- `t` and `s` failed to be unfolded\n      (fun s => isDefEqRight sInfo.name t s))\n    (fun tNew =>\n      if sameHeadSymbol tNew s then\n        isDefEqLeft tInfo.name tNew s\n      else\n        unfold s\n          (isDefEqLeft tInfo.name tNew s)\n          (fun sNew =>\n            if sameHeadSymbol t sNew then\n              isDefEqRight sInfo.name t sNew\n            else\n              isDefEqLeftRight tInfo.name tNew sNew))\n\n/-- If `t` and `s` do not contain metavariables, then use\n    kernel definitional equality heuristics.\n    Otherwise, use `unfoldComparingHeadsDefEq`.\n\n    Auxiliary method for isDefEqDelta -/\nprivate def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=\n  if !t.hasExprMVar && !s.hasExprMVar then\n    /- If `t` and `s` do not contain metavariables,\n       we simulate strategy used in the kernel. -/\n    if tInfo.hints.lt sInfo.hints then\n      unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s\n    else if sInfo.hints.lt tInfo.hints then\n      unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s\n    else\n      unfoldComparingHeadsDefEq tInfo sInfo t s\n  else\n    unfoldComparingHeadsDefEq tInfo sInfo t s\n\n/--\n  When `TransparencyMode` is set to `default` or `all`.\n  If `t` is reducible and `s` is not ==> `isDefEqLeft  (unfold t) s`\n  If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)`\n\n  Otherwise, use `unfoldDefEq`\n\n  Auxiliary method for isDefEqDelta -/\nprivate def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do\n  if (\u2190 shouldReduceReducibleOnly) then\n    unfoldDefEq tInfo sInfo t s\n  else\n    let tReducible \u2190 isReducible tInfo.name\n    let sReducible \u2190 isReducible sInfo.name\n    if tReducible && !sReducible then\n      unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s\n    else if !tReducible && sReducible then\n      unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s\n    else\n      unfoldDefEq tInfo sInfo t s\n\n/--\n  If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)`\n  If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s`\n\n  Otherwise, use `unfoldReducibeDefEq`\n\n  Auxiliary method for isDefEqDelta -/\nprivate def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do\n  let tProj? \u2190 isProjectionFn tInfo.name\n  let sProj? \u2190 isProjectionFn sInfo.name\n  if tProj? && !sProj? then\n    unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s\n  else if !tProj? && sProj? then\n    unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s\n  else\n    unfoldReducibeDefEq tInfo sInfo t s\n\n/--\n  isDefEq by lazy delta reduction.\n  This method implements many different heuristics:\n  1- If only `t` can be unfolded => then unfold `t` and continue\n  2- If only `s` can be unfolded => then unfold `s` and continue\n  3- If `t` and `s` can be unfolded and they have the same head symbol, then\n     a) First try to solve unification by unifying arguments.\n     b) If it fails, unfold both and continue.\n     Implemented by `unfoldBothDefEq`\n  4- If `t` is a projection function application and `s` is not => then unfold `s` and continue.\n  5- If `s` is a projection function application and `t` is not => then unfold `t` and continue.\n  Remark: 4&5 are implemented by `unfoldNonProjFnDefEq`\n  6- If `t` is reducible and `s` is not => then unfold `t` and continue.\n  7- If `s` is reducible and `t` is not => then unfold `s` and continue\n  Remark: 6&7 are implemented by `unfoldReducibeDefEq`\n  8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel.\n     Implemented by `unfoldDefEq`\n  9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue.\n  10- If `headSymbol (unfold s) == headSymbol t`, then unfold s\n  11- Otherwise, unfold `t` and `s` and continue.\n  Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/\nprivate def isDefEqDelta (t s : Expr) : MetaM LBool := do\n  let tInfo? \u2190 isDeltaCandidate? t.getAppFn\n  let sInfo? \u2190 isDeltaCandidate? s.getAppFn\n  match tInfo?, sInfo? with\n  | none,       none       => pure LBool.undef\n  | some tInfo, none       => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s\n  | none,       some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s\n  | some tInfo, some sInfo =>\n    if tInfo.name == sInfo.name then\n      unfoldBothDefEq tInfo.name t s\n    else\n      unfoldNonProjFnDefEq tInfo sInfo t s\n\nprivate def isAssigned : Expr \u2192 MetaM Bool\n  | Expr.mvar mvarId _ => isExprMVarAssigned mvarId\n  | _                  => pure false\n\nprivate def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do\n  match tFn with\n  | Expr.mvar mvarId _ =>\n    if (\u2190 isDelayedAssigned mvarId) then\n      let tNew \u2190 instantiateMVars t\n      return tNew != t\n    else\n      pure false\n  | _ => pure false\n\nprivate def isSynthetic : Expr \u2192 MetaM Bool\n  | Expr.mvar mvarId _ => do\n    let mvarDecl \u2190 getMVarDecl mvarId\n    match mvarDecl.kind with\n    | MetavarKind.synthetic       => pure true\n    | MetavarKind.syntheticOpaque => pure true\n    | MetavarKind.natural         => pure false\n  | _                  => pure false\n\nprivate def isAssignable : Expr \u2192 MetaM Bool\n  | Expr.mvar mvarId _ => do let b \u2190 isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b)\n  | _                  => pure false\n\nprivate def etaEq (t s : Expr) : Bool :=\n  match t.etaExpanded? with\n  | some t => t == s\n  | none   => false\n\nprivate def isLetFVar (fvarId : FVarId) : MetaM Bool := do\n  let decl \u2190 getLocalDecl fvarId\n  pure decl.isLet\n\nprivate def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do\n  let status \u2190 isProofQuick t\n  match status with\n  | LBool.false =>\n    pure LBool.undef\n  | LBool.true  =>\n    let tType \u2190 inferType t\n    let sType \u2190 inferType s\n    toLBoolM <| Meta.isExprDefEqAux tType sType\n  | LBool.undef =>\n    let tType \u2190 inferType t\n    if (\u2190 isProp tType) then\n      let sType \u2190 inferType s\n      toLBoolM <| Meta.isExprDefEqAux tType sType\n    else\n      pure LBool.undef\n\n/- Try to solve constraint of the form `?m args\u2081 =?= ?m args\u2082`.\n   - First try to unify `args\u2081` and `args\u2082`, and return true if successful\n   - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n`\n     where `?n` is a fresh metavariable. See `processConstApprox`. -/\nprivate def isDefEqMVarSelf (mvar : Expr) (args\u2081 args\u2082 : Array Expr) : MetaM Bool := do\n  if args\u2081.size != args\u2082.size then\n    pure false\n  else if (\u2190 isDefEqArgs mvar args\u2081 args\u2082) then\n    pure true\n  else if !(\u2190 isAssignable mvar) then\n    pure false\n  else\n    let cfg \u2190 getConfig\n    let mvarId := mvar.mvarId!\n    let mvarDecl \u2190 getMVarDecl mvarId\n    if mvarDecl.numScopeArgs == args\u2081.size || cfg.constApprox then\n      let type \u2190 inferType (mkAppN mvar args\u2081)\n      let auxMVar \u2190 mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type\n      assignConst mvar args\u2081.size auxMVar\n    else\n      pure false\n\n/- Remove unnecessary let-decls -/\nprivate def consumeLet : Expr \u2192 Expr\n  | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b\n  | e                       => e\n\nmutual\n\nprivate partial def isDefEqQuick (t s : Expr) : MetaM LBool :=\n  let t := consumeLet t\n  let s := consumeLet s\n  match t, s with\n  | Expr.lit  l\u2081 _,      Expr.lit l\u2082 _       => return (l\u2081 == l\u2082).toLBool\n  | Expr.sort u _,       Expr.sort v _       => toLBoolM <| isLevelDefEqAux u v\n  | Expr.lam ..,         Expr.lam ..         => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s\n  | Expr.forallE ..,     Expr.forallE ..     => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s\n  | Expr.mdata _ t _,    s                   => isDefEqQuick t s\n  | t,                   Expr.mdata _ s _    => isDefEqQuick t s\n  | Expr.fvar fvarId\u2081 _, Expr.fvar fvarId\u2082 _ => do\n    if (\u2190 isLetFVar fvarId\u2081 <||> isLetFVar fvarId\u2082) then\n      pure LBool.undef\n    else if fvarId\u2081 == fvarId\u2082 then\n      pure LBool.true\n    else\n      isDefEqProofIrrel t s\n  | t, s =>\n    isDefEqQuickOther t s\n\nprivate partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do\n  if t == s then\n    pure LBool.true\n  else if etaEq t s || etaEq s t then\n    pure LBool.true  -- t =?= (fun xs => t xs)\n  else\n    let tFn := t.getAppFn\n    let sFn := s.getAppFn\n    if !tFn.isMVar && !sFn.isMVar then\n      pure LBool.undef\n    else if (\u2190 isAssigned tFn) then\n      let t \u2190 instantiateMVars t\n      isDefEqQuick t s\n    else if (\u2190 isAssigned sFn) then\n      let s \u2190 instantiateMVars s\n      isDefEqQuick t s\n    else if (\u2190 isDelayedAssignedHead tFn t) then\n      let t \u2190 instantiateMVars t\n      isDefEqQuick t s\n    else if (\u2190 isDelayedAssignedHead sFn s) then\n      let s \u2190 instantiateMVars s\n      isDefEqQuick t s\n    else if (\u2190 isSynthetic tFn <&&> trySynthPending tFn) then\n      let t \u2190 instantiateMVars t\n      isDefEqQuick t s\n    else if (\u2190 isSynthetic sFn <&&> trySynthPending sFn) then\n      let s \u2190 instantiateMVars s\n      isDefEqQuick t s\n    else if tFn.isMVar && sFn.isMVar && tFn == sFn then\n      Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs\n    else\n      let tAssign? \u2190 isAssignable tFn\n      let sAssign? \u2190 isAssignable sFn\n      let assignableMsg (b : Bool) := if b then \"[assignable]\" else \"[nonassignable]\"\n      trace[Meta.isDefEq] \"{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}\"\n      if tAssign? && !sAssign? then\n        toLBoolM <| processAssignment' t s\n      else if !tAssign? && sAssign? then\n        toLBoolM <| processAssignment' s t\n      else if !tAssign? && !sAssign? then\n        if tFn.isMVar || sFn.isMVar then\n          let ctx \u2190 read\n          if ctx.config.isDefEqStuckEx then do\n            trace[Meta.isDefEq.stuck] \"{t} =?= {s}\"\n            Meta.throwIsDefEqStuck\n          else\n            pure LBool.false\n        else\n          pure LBool.undef\n      else\n        isDefEqQuickMVarMVar t s\n\n-- Both `t` and `s` are terms of the form `?m ...`\nprivate partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do\n  let tFn := t.getAppFn\n  let sFn := s.getAppFn\n  let tMVarDecl \u2190 getMVarDecl tFn.mvarId!\n  let sMVarDecl \u2190 getMVarDecl sFn.mvarId!\n  if s.isMVar && !t.isMVar then\n     /- Solve `?m t =?= ?n` by trying first `?n := ?m t`.\n        Reason: this assignment is precise. -/\n     if (\u2190 checkpointDefEq (processAssignment s t)) then\n       pure LBool.true\n     else\n       toLBoolM <| processAssignment t s\n  else\n     if (\u2190 checkpointDefEq (processAssignment t s)) then\n       pure LBool.true\n     else\n       toLBoolM <| processAssignment s t\n\nend\n\n@[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do\n  let status \u2190 x\n  match status with\n  | LBool.true  => pure true\n  | LBool.false => pure false\n  | LBool.undef => k\n\n@[specialize] private def unstuckMVar (e : Expr) (successK : Expr \u2192 MetaM Bool) (failK : MetaM Bool): MetaM Bool := do\n  match (\u2190 getStuckMVar? e) with\n  | some mvarId =>\n    trace[Meta.isDefEq.stuckMVar] \"found stuck MVar {mkMVar mvarId} : {\u2190 inferType (mkMVar mvarId)}\"\n    if (\u2190 Meta.synthPending mvarId) then\n      let e \u2190 instantiateMVars e\n      successK e\n    else\n      failK\n  | none   => failK\n\nprivate def isDefEqOnFailure (t s : Expr) : MetaM Bool :=\n  unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <|\n  unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <|\n  tryUnificationHints t s <||> tryUnificationHints s t\n\nprivate def isDefEqProj : Expr \u2192 Expr \u2192 MetaM Bool\n  | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s\n  | _, _ => pure false\n\n/-\n  Given applications `t` and `s` that are in WHNF (modulo the current transparency setting),\n  check whether they are definitionally equal or not.\n-/\nprivate def isDefEqApp (t s : Expr) : MetaM Bool := do\n  let tFn := t.getAppFn\n  let sFn := s.getAppFn\n  if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then\n    /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/\n    if (\u2190 checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then\n      return true\n    else\n      isDefEqOnFailure t s\n  else if (\u2190 checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then\n    return true\n  else\n    isDefEqOnFailure t s\n\npartial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do\n  trace[Meta.isDefEq.step] \"{t} =?= {s}\"\n  checkMaxHeartbeats \"isDefEq\"\n  withNestedTraces do\n  whenUndefDo (isDefEqQuick t s) do\n  whenUndefDo (isDefEqProofIrrel t s) do\n  let t' \u2190 whnfCore t\n  let s' \u2190 whnfCore s\n  if t != t' || s != s' then\n    isExprDefEqAuxImpl t' s'\n  else do\n    if (\u2190 (isDefEqEta t s <||> isDefEqEta s t)) then pure true else\n    if (\u2190 isDefEqProj t s) then pure true else\n    whenUndefDo (isDefEqNative t s) do\n    whenUndefDo (isDefEqNat t s) do\n    whenUndefDo (isDefEqOffset t s) do\n    whenUndefDo (isDefEqDelta t s) do\n    if t.isConst && s.isConst then\n      if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else pure false\n    else if t.isApp && s.isApp then\n      isDefEqApp t s\n    else\n      whenUndefDo (isDefEqStringLit t s) do\n      isDefEqOnFailure t s\n\nbuiltin_initialize\n  isExprDefEqAuxRef.set isExprDefEqAuxImpl\n\nbuiltin_initialize\n  registerTraceClass `Meta.isDefEq\n  registerTraceClass `Meta.isDefEq.foApprox\n  registerTraceClass `Meta.isDefEq.constApprox\n  registerTraceClass `Meta.isDefEq.delta\n  registerTraceClass `Meta.isDefEq.step\n  registerTraceClass `Meta.isDefEq.assign\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/ExprDefEq.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.090092998848117, "lm_q1q2_score": 0.03875326458066493}}
{"text": "/-\nCopyright (c) 2022 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Aesop\n\nstructure MyTrue\u2081\nstructure MyTrue\u2082\n\n@[aesop safe]\nstructure MyTrue\u2083 where\n  tt : MyTrue\u2081\n\nexample : MyTrue\u2083 := by\n  aesop\n  apply MyTrue\u2081.mk\n\n@[aesop safe]\nstructure MyFalse where\n  falso : False\n\nexample : MyFalse := by\n  aesop\n\nexample : MyFalse := by\n  fail_if_success aesop (options := { terminal := true })\n\nexample : MyFalse := by\n  aesop (options := { warnOnNonterminal := false })\n\n@[aesop safe]\nstructure MyFalse\u2082 where\n  falso : False\n  tt : MyTrue\u2083\n\nexample : MyFalse\u2082 := by\n  aesop\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/golden/Nonterminal.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091957, "lm_q2_score": 0.07807816407233607, "lm_q1q2_score": 0.03873409541270397}}
{"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 \u2192 Type v}\nvariables {\u03b1 \u03b2 \u03b3 : Type u}\nvariables [functor F] [is_lawful_functor F]\n\nlemma functor.map_id : (<$>) id = (id : F \u03b1 \u2192 F \u03b1) :=\nby apply funext; apply id_map\n\nlemma functor.map_comp_map (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) :\n  ((<$>) g \u2218 (<$>) f : F \u03b1 \u2192 F \u03b3) = (<$>) (g \u2218 f) :=\nby apply funext; intro; rw comp_map\n\ntheorem functor.ext {F} : \u2200 {F1 : functor F} {F2 : functor F}\n  [@is_lawful_functor F F1] [@is_lawful_functor F F2]\n  (H : \u2200 \u03b1 \u03b2 (f : \u03b1 \u2192 \u03b2) (x : F \u03b1),\n    @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x),\n  F1 = F2\n| \u27e8m, mc\u27e9 \u27e8m', mc'\u27e9 H1 H2 H :=\nbegin\n  cases show @m = @m', by funext \u03b1 \u03b2 f x; apply H,\n  congr, funext \u03b1 \u03b2,\n  have E1 := @map_const_eq _ \u27e8@m, @mc\u27e9 H1,\n  have E2 := @map_const_eq _ \u27e8@m, @mc'\u27e9 H2,\n  exact E1.trans E2.symm\nend\n\nend functor\n\ndef id.mk {\u03b1 : Sort u} : \u03b1 \u2192 id \u03b1 := id\n\nnamespace functor\n\ndef const (\u03b1 : Type*) (\u03b2 : Type*) := \u03b1\n\n@[pattern] def const.mk {\u03b1 \u03b2} (x : \u03b1) : const \u03b1 \u03b2 := x\n\ndef const.mk' {\u03b1} (x : \u03b1) : const \u03b1 punit := x\n\ndef const.run {\u03b1 \u03b2} (x : const \u03b1 \u03b2) : \u03b1 := x\n\nnamespace const\n\nprotected lemma ext {\u03b1 \u03b2} {x y : const \u03b1 \u03b2} (h : x.run = y.run) : x = y := h\n\nprotected def map {\u03b3 \u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : const \u03b3 \u03b2) : const \u03b3 \u03b1 := x\n\ninstance {\u03b3} : functor (const \u03b3) :=\n{ map := @const.map \u03b3 }\n\ninstance {\u03b3} : is_lawful_functor (const \u03b3) :=\nby constructor; intros; refl\n\nend const\n\ndef add_const (\u03b1 : Type*) := const \u03b1\n\n@[pattern]\ndef add_const.mk {\u03b1 \u03b2} (x : \u03b1) : add_const \u03b1 \u03b2 := x\n\ndef add_const.run {\u03b1 \u03b2} : add_const \u03b1 \u03b2 \u2192 \u03b1 := id\n\ninstance add_const.functor {\u03b3} : functor (add_const \u03b3) :=\n@const.functor \u03b3\n\ninstance add_const.is_lawful_functor {\u03b3} : is_lawful_functor (add_const \u03b3) :=\n@const.is_lawful_functor \u03b3\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 \u2192 Type w) (G : Type v \u2192 Type u) (\u03b1 : Type v) : Type w :=\nF $ G \u03b1\n\n@[pattern] def comp.mk {F : Type u \u2192 Type w} {G : Type v \u2192 Type u} {\u03b1 : Type v}\n  (x : F (G \u03b1)) : comp F G \u03b1 := x\n\ndef comp.run {F : Type u \u2192 Type w} {G : Type v \u2192 Type u} {\u03b1 : Type v}\n  (x : comp F G \u03b1) : F (G \u03b1) := x\n\nnamespace comp\n\nvariables {F : Type u \u2192 Type w} {G : Type v \u2192 Type u}\n\nprotected lemma ext\n  {\u03b1} {x y : comp F G \u03b1} : x.run = y.run \u2192 x = y := id\n\nvariables [functor F] [functor G]\n\nprotected def map {\u03b1 \u03b2 : Type v} (h : \u03b1 \u2192 \u03b2) : comp F G \u03b1 \u2192 comp F G \u03b2\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 {\u03b1 \u03b2} (h : \u03b1 \u2192 \u03b2) (x : F (G \u03b1)) :\n  h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl\n\nvariables [is_lawful_functor F] [is_lawful_functor G]\nvariables {\u03b1 \u03b2 \u03b3 : Type v}\n\nprotected lemma id_map : \u2200 (x : comp F G \u03b1), comp.map id x = x\n| (comp.mk x) := by simp [comp.map, functor.map_id]\n\nprotected lemma comp_map (g' : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) : \u2200 (x : comp F G \u03b1),\n           comp.map (h \u2218 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 : \u03b1 \u2192 \u03b2) (x : comp F G \u03b1) :\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 _ _ _ _) _ (\u03bb \u03b1 \u03b2 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 _ _ _ _) _ (\u03bb \u03b1 \u03b2 f x, rfl)\n\nend comp\n\nend functor\n\nnamespace ulift\n\ninstance : functor ulift :=\n{ map := \u03bb \u03b1 \u03b2 f, up \u2218 f \u2218 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 `\u2200 x, ...`,\n`\u2203 x, ...` and `\u03bb 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 `\u2200 x, ...`, `\u2203 x, ...` and `\u03bb 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 `\u2190` is applied in the reverse direction.\n  - `simp_rw [lemma_1, ..., lemma_n] at h\u2081 ... h\u2099` will rewrite the given hypotheses.\n  - `simp_rw [...] at \u22a2 h\u2081 ... h\u2099` 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 {\u03b1 \u03b2 : Type} {f : \u03b1 \u2192 \u03b2} {t : set \u03b2} :\n  (\u2200 s, f '' s \u2286 t) = \u2200 s : set \u03b1, \u2200 x \u2208 s, x \u2208 f \u207b\u00b9' 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": "import .tab\n\nopen tactic \nvariable {p : Prop}\n\nexample : p := \nby do proof_by_contradiction\n\n#exit\n\n#check @classical.by_contradiction\n\nexample : p := \nby do refine ``(classical.by_contradiction _),\n      -- trace \"After refine : \", trace_state,\n      intro `_,\n      -- trace \"After intro : \", trace_state,\n      skip", "meta": {"author": "skbaek", "repo": "tab", "sha": "70909a69464a8713412d640ac630e5e6ef4e43e8", "save_path": "github-repos/lean/skbaek-tab", "path": "github-repos/lean/skbaek-tab/tab-70909a69464a8713412d640ac630e5e6ef4e43e8/pbc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.07696083146183952, "lm_q1q2_score": 0.03848041573091976}}
{"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\u2081 : Q \u2192 P) (h\u2082 : R) (h\u2083 : R \u2192 Q) : P \u2227 R :=\nby show_term { tauto }\n```\nthe term mode proof `\u27e8h\u2081 (h\u2083 h\u2082), eq.mpr rfl h\u2082\u27e9` produced by `tauto` will be printed.\n\nAs another example, if the goal is `\u2115 \u00d7 \u2115`, `show_term { split, exact 0 }` will\nprint `refine (0, _)`, and afterwards there will be one remaining goal (of type `\u2115`).\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 :: _ \u2190 get_goals\n  t\n  let g \u2190 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 (\u03bb 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 (\u03bb 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 `\u03bb` which you can type in VS code using `\\la `.\n\nList has a specialized version of `map` defined as follows:\n-/\ndef map (f : \u03b1 \u2192 \u03b2) : List \u03b1 \u2192 List \u03b2\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 `(\u03b1 \u2192 \u03b2)` and use it\nto convert `List \u03b1 \u2192 List \u03b2`. 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 \u2192 List Nat\n#eval [\"elephant\", \"tiger\", \"giraffe\"].map (fun s => s.length)\n-- [8, 5, 7]\n\n-- List Nat \u2192 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 \u2192 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 `(\u00b7 + 1)`\nusing the middle dot unicode character which you can type in VS code using `\\. `.\n\n-/\n#eval (some 4).map (\u00b7 * 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 (\u03b1 : Type) where\n  totalSize : \u03b1\n  numBedrooms : Nat\n  masterBedroomSize : \u03b1\n  livingRoomSize : \u03b1\n  kitchenSize : \u03b1\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 : \u03b1 \u2192 \u03b2) (s : LivingSpace \u03b1) : LivingSpace \u03b2 :=\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 \u2192 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 \u03b1` you can map to `LivingSpace \u03b2` using the generic\n`LivingSpace.map` map function by simply providing a function that does the more primitive mapping\nfrom `(f : \u03b1 \u2192 \u03b2)`.  So `LivingSpace.map` is a sort of function applicator.\nThis is called a \"higher order function\" because it takes a function as input\n`(\u03b1 \u2192 \u03b2)` and returns another function as output `F \u03b1 \u2192 F \u03b2`.\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 (\u00b7 * 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 \u2192 Type v) : Type (max (u+1) v) where\n  map : {\u03b1 \u03b2 : Type u} \u2192 (\u03b1 \u2192 \u03b2) \u2192 f \u03b1 \u2192 f \u03b2\n  mapConst : {\u03b1 \u03b2 : Type u} \u2192 \u03b1 \u2192 f \u03b2 \u2192 f \u03b1\n```\n\nNote that `mapConst` has a default implementation, namely:\n`mapConst : {\u03b1 \u03b2 : Type u} \u2192 \u03b1 \u2192 f \u03b2 \u2192 f \u03b1 := 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 \u2192 Type v` equipped with an operator\ncalled `map` such that if you have a function `f` of type `\u03b1 \u2192 \u03b2` then `map f` will convert your\ncontainer type from `F \u03b1 \u2192 F \u03b2`. 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\u1d50\u1d52\u1d56` for the monoidal opposite of a monoidal category `C`.\n-/\n\n\nuniverses v\u2081 v\u2082 u\u2081 u\u2082\n\nvariables {C : Type u\u2081}\n\nnamespace category_theory\n\nopen category_theory.monoidal_category\n\n/-- A type synonym for the monoidal opposite. Use the notation `C\u1d39\u1d52\u1d56`. -/\n@[nolint has_inhabited_instance]\ndef monoidal_opposite (C : Type u\u2081) := C\n\nnamespace monoidal_opposite\n\nnotation C `\u1d39\u1d52\u1d56`:std.prec.max_plus := monoidal_opposite C\n\n/-- Think of an object of `C` as an object of `C\u1d39\u1d52\u1d56`. -/\n@[pp_nodot]\ndef mop (X : C) : C\u1d39\u1d52\u1d56 := X\n\n/-- Think of an object of `C\u1d39\u1d52\u1d56` as an object of `C`. -/\n@[pp_nodot]\ndef unmop (X : C\u1d39\u1d52\u1d56) : C := X\n\nlemma op_injective : function.injective (mop : C \u2192 C\u1d39\u1d52\u1d56) := \u03bb _ _, id\nlemma unop_injective : function.injective (unmop : C\u1d39\u1d52\u1d56 \u2192 C) := \u03bb _ _, id\n\n@[simp] lemma op_inj_iff (x y : C) : mop x = mop y \u2194 x = y := iff.rfl\n@[simp] lemma unop_inj_iff (x y : C\u1d39\u1d52\u1d56) : unmop x = unmop y \u2194 x = y := iff.rfl\n\nattribute [irreducible] monoidal_opposite\n\n@[simp] lemma mop_unmop (X : C\u1d39\u1d52\u1d56) : 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\u2081} C] : category C\u1d39\u1d52\u1d56 :=\n{ hom := \u03bb X Y, unmop X \u27f6 unmop Y,\n  id := \u03bb X, \ud835\udfd9 (unmop X),\n  comp := \u03bb X Y Z f g, f \u226b g, }\n\nend monoidal_opposite\n\nend category_theory\n\nopen category_theory\nopen category_theory.monoidal_opposite\n\nvariables [category.{v\u2081} C]\n\n/-- The monoidal opposite of a morphism `f : X \u27f6 Y` is just `f`, thought of as `mop X \u27f6 mop Y`. -/\ndef quiver.hom.mop {X Y : C} (f : X \u27f6 Y) : @quiver.hom C\u1d39\u1d52\u1d56 _ (mop X) (mop Y) := f\n/-- We can think of a morphism `f : mop X \u27f6 mop Y` as a morphism `X \u27f6 Y`. -/\ndef quiver.hom.unmop {X Y : C\u1d39\u1d52\u1d56} (f : X \u27f6 Y) : unmop X \u27f6 unmop Y := f\n\nnamespace category_theory\n\nlemma mop_inj {X Y : C} :\n  function.injective (quiver.hom.mop : (X \u27f6 Y) \u2192 (mop X \u27f6 mop Y)) :=\n\u03bb _ _ H, congr_arg quiver.hom.unmop H\n\nlemma unmop_inj {X Y : C\u1d39\u1d52\u1d56} :\n  function.injective (quiver.hom.unmop : (X \u27f6 Y) \u2192 (unmop X \u27f6 unmop Y)) :=\n\u03bb _ _ H, congr_arg quiver.hom.mop H\n\n@[simp] lemma unmop_mop {X Y : C} {f : X \u27f6 Y} : f.mop.unmop = f := rfl\n@[simp] lemma mop_unmop {X Y : C\u1d39\u1d52\u1d56} {f : X \u27f6 Y} : f.unmop.mop = f := rfl\n\n@[simp] lemma mop_comp {X Y Z : C} {f : X \u27f6 Y} {g : Y \u27f6 Z} :\n  (f \u226b g).mop = f.mop \u226b g.mop := rfl\n@[simp] lemma mop_id {X : C} : (\ud835\udfd9 X).mop = \ud835\udfd9 (mop X) := rfl\n\n@[simp] lemma unmop_comp {X Y Z : C\u1d39\u1d52\u1d56} {f : X \u27f6 Y} {g : Y \u27f6 Z} :\n  (f \u226b g).unmop = f.unmop \u226b g.unmop := rfl\n@[simp] lemma unmop_id {X : C\u1d39\u1d52\u1d56} : (\ud835\udfd9 X).unmop = \ud835\udfd9 (unmop X) := rfl\n\n@[simp] lemma unmop_id_mop {X : C} : (\ud835\udfd9 (mop X)).unmop = \ud835\udfd9 X := rfl\n@[simp] lemma mop_id_unmop {X : C\u1d39\u1d52\u1d56} : (\ud835\udfd9 (unmop X)).mop = \ud835\udfd9 X := rfl\n\nnamespace iso\n\nvariables {X Y : C}\n\n/-- An isomorphism in `C` gives an isomorphism in `C\u1d39\u1d52\u1d56`. -/\n@[simps]\ndef mop (f : X \u2245 Y) : mop X \u2245 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\u2081} C]\n\nopen opposite monoidal_category\n\ninstance monoidal_category_op : monoidal_category C\u1d52\u1d56 :=\n{ tensor_obj := \u03bb X Y, op (unop X \u2297 unop Y),\n  tensor_hom := \u03bb X\u2081 Y\u2081 X\u2082 Y\u2082 f g, (f.unop \u2297 g.unop).op,\n  tensor_unit := op (\ud835\udfd9_ C),\n  associator := \u03bb X Y Z, (\u03b1_ (unop X) (unop Y) (unop Z)).symm.op,\n  left_unitor := \u03bb X, (\u03bb_ (unop X)).symm.op,\n  right_unitor := \u03bb X, (\u03c1_ (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\u1d52\u1d56) : X \u2297 Y = op (unop X \u2297 unop Y) := rfl\nlemma op_tensor_unit : (\ud835\udfd9_ C\u1d52\u1d56) = op (\ud835\udfd9_ C) := rfl\n\ninstance monoidal_category_mop : monoidal_category C\u1d39\u1d52\u1d56 :=\n{ tensor_obj := \u03bb X Y, mop (unmop Y \u2297 unmop X),\n  tensor_hom := \u03bb X\u2081 Y\u2081 X\u2082 Y\u2082 f g, (g.unmop \u2297 f.unmop).mop,\n  tensor_unit := mop (\ud835\udfd9_ C),\n  associator := \u03bb X Y Z, (\u03b1_ (unmop Z) (unmop Y) (unmop X)).symm.mop,\n  left_unitor := \u03bb X, (\u03c1_ (unmop X)).mop,\n  right_unitor := \u03bb X, (\u03bb_ (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\u1d39\u1d52\u1d56) : X \u2297 Y = mop (unmop Y \u2297 unmop X) := rfl\nlemma mop_tensor_unit : (\ud835\udfd9_ C\u1d39\u1d52\u1d56) = mop (\ud835\udfd9_ 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": "import tidy.lib.pretty_print\nimport tidy.lib.name\nimport tidy.lib.expr\nimport tidy.lib.parser\n\nopen lean.parser\nopen interactive\n\nopen exceptional\nopen declaration\n\nnamespace tidy.command\n\nnamespace rfl_lemma\n\nstructure config :=\n(attrs : list string := [\"simp\"])\n(priv  : bool := ff)\n(trace : bool := ff)\n\nopen tactic\n\nmeta def handle_defn (lemma_name : string) (conf : config) (e : environment) (fn_name : name) (fn_us : list name) (fn_type : expr) (fn_val : expr) (field : name) : tactic string := do\n  (obj_name, obj_name_levels, fn_type_app_vars) \u2190 app.chop $ prod.snd fn_type.unroll_pi_binders,\n  (fn_val_params, fn_val_core) \u2190 pure fn_val.unroll_lam_binders,\n\n  let proj_name := obj_name ++ field,\n  let proj_prime_name := obj_name ++ field.append_suffix \"'\",\n\n  pi \u2190 e.is_projection proj_prime_name\n    <|> e.is_projection proj_name\n    <|> fail format!\"There are no projections: {proj_prime_name}', nor {proj_prime_name}\",\n  (field_params, field_val) \u2190 expr.unroll_lam_binders <$> structure_instance.extract_field fn_val_core pi,\n\n  field_proj \u2190 mk_const proj_name >>= infer_type\n    <|> fail format!\"There is no identifier: {proj_name}\",\n  let field_proj_params := (prod.fst field_proj.unroll_pi_binders).drop (pi.nparams + 1),\n  let field_params := field_params.zip_with binder.set_binder_info (field_proj_params.map binder.binder_info),\n\n  let lemma_params := fn_val_params ++ field_params,\n  args \u2190 binder.list_to_args lemma_params,\n  st_value \u2190 pretty_print (binder.instantiate field_val lemma_params) ff tt,\n\n  attrs \u2190 if \u00ac(conf.attrs.length = 0) then\n            pp format!\"@[{string.lconcat (conf.attrs.intersperse \\\", \\\")}] \"\n          else\n            return \"\",\n  let mods := if conf.priv then \"private \" else \"\",\n\n  code \u2190 pp format!\"{attrs}{mods}lemma {lemma_name} {args} : ({fn_name} {binder.list_to_invocation fn_val_params}).{field} {binder.list_to_invocation field_params} = {st_value} := rfl\",\n\n  if conf.trace then\n    tactic.trace code\n  else skip,\n  return code.to_string\n\nmeta def assert_not_declared (n : string) : tactic unit := do\n  ret \u2190 try_core $ resolve_constant $ mk_simple_name n,\n  match ret with\n  | some _ := tactic.fail format!\"There is already an identifier \\\"{n}\\\" in the environment!\"\n  | none   := return ()\n  end\n\nmeta def handle (conf : config) (obj_def : name) (field : name) : tactic string := do\n  e \u2190 tactic.get_env,\n  obj_def \u2190 tactic.resolve_constant obj_def\n  <|> interaction_monad.fail format!\"Could not resolve the identifier \\\"{obj_def}\\\"\",\n  match e.get obj_def with\n  | exception _ f := do\n    interaction_monad.fail format!\"Could not retrieve the declaration associated with \\\"{obj_def}\\\" from the environment!\"\n  | success decl :=\n    match decl with\n    | defn n us type val _ _ := do\n      n \u2190 n.get_suffix,\n      lemma_name \u2190 to_string <$> pp format!\"{n}_{field}\",\n      assert_not_declared lemma_name,\n      handle_defn lemma_name conf e n us type val field\n    | _ := interaction_monad.fail format!\"\\\"{obj_def}\\\" must be a definition, not a lemma, theorem, or axiom!\"\n    end\n  end\n\nend rfl_lemma\n\nmeta def rfl_lemma_core (conf : rfl_lemma.config) : lean.parser unit := do\n  obj_def \u2190 ident,\n  field \u2190 ident,\n  lean.parser.of_tactic_safe (rfl_lemma.handle conf obj_def field) >>= emit_code_here\n\n@[user_command]\nmeta def rfl_lemma_cmd (d : decl_meta_info) (_ : parse $ tk \"rfl_lemma\") : lean.parser unit :=\n  rfl_lemma_core {}\n\n@[user_command]\nmeta def rfl_lemma_private_cmd (d : decl_meta_info) (_ : parse $ tk \"private rfl_lemma\") : lean.parser unit :=\n  rfl_lemma_core {priv := tt}\n\n@[user_command]\nmeta def rfl_lemma_question_cmd (d : decl_meta_info) (_ : parse $ tk \"rfl_lemma?\") : lean.parser unit :=\n  rfl_lemma_core {trace := tt}\n\n@[user_command]\nmeta def rfl_lemma_question_private_cmd (d : decl_meta_info) (_ : parse $ tk \"private rfl_lemma?\") : lean.parser unit :=\n  rfl_lemma_core {trace := tt, priv := tt}\n\nend tidy.command", "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/tidy/command/rfl_lemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.0803574677210091, "lm_q1q2_score": 0.03798364721478079}}
{"text": "lemma subsingleton_injective {\u03b1 \u03b2 : Sort*} [subsingleton \u03b1] (f : \u03b1 \u2192 \u03b2) :\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": "theorem P_implies_P (P : Prop) : P \u2192 P :=\nbegin\n  sorry,\nend\n", "meta": {"author": "ImperialCollegeLondon", "repo": "xena-UROP-2018", "sha": "b111fb87f343cf79eca3b886f99ee15c1dd9884b", "save_path": "github-repos/lean/ImperialCollegeLondon-xena-UROP-2018", "path": "github-repos/lean/ImperialCollegeLondon-xena-UROP-2018/xena-UROP-2018-b111fb87f343cf79eca3b886f99ee15c1dd9884b/src/M1F/problem_bank/PB0004/Q0004.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.07585817688736327, "lm_q1q2_score": 0.03792908844368163}}
{"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) {\u03b1 : 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 \u2282\u2092 coe_spec'] :\n  has_coe (sim_oracle spec coe_spec S) (sim_oracle spec coe_spec' S) :=\n{ coe := \u03bb so, {default_state := so.default_state, o := \u03bb i x, \u2191(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 := \u2191so\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 \u00d7 S') :=\n\u2191so ++\u209b \u2191so'\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: \u2200 {sem} {P: regfile sem \u2192 Prop}\n    {HP0: P (@regfile.empty sem)}\n    {HPU: \u2200 rf, P rf \u2192 \u2200 n v, P (regfile.update sem rf n v)},\n  \u2200 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: \u2200 {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: \u2200 {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: \u2200 {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 \u2260 rname2\nlemma regfile.update_get_nomatch: \u2200 {sem} (rname rname2:string) vp rf\n    (Hnameeq: rname2 \u2260 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: \u2200 {sem} n,\n  n \u2209 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: \u2200 {sem} rf n n' v \n    (H: n \u2208 regfile.regnames sem rf),\n  n \u2208 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: \u2200 {sem} rf n v,\n  n \u2208 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: \u2200 {sem} rf n n' v \n    (H: n \u2208 regfile.regnames sem (regfile.update sem rf n' v))\n    (HNEQ: n \u2260 n'),\n  n \u2208 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: \u2200 {sem} (rname:string) (f:regfile sem),\n  regfile.get sem f rname = none \u2194 rname \u2209 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 \u2190 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: \u2200 {sem} (rname:string) (f:regfile sem),\n  (\u2203 v, regfile.get sem f rname = some v) \u2194 rname \u2208 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: \u2200 {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: \u2200 {sem} (rf:regfile sem) (f:valty sem \u2192 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: \u2200 {sem} (rf:regfile sem) (f:valty sem \u2192 valty sem) n,\n  regfile.get sem rf n = none \u2194 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: \u2200 (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: \u2200 (rname:string) (s:irstate irsem_smt)\n    (H:rname \u2209 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: \u2200 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 \u2260 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: \u2200 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 \u2260 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: \u2200 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 \u2260 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: \u2200 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: \u2200 {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: \u2200 (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: \u2200 (s:irstate irsem_smt) (f:valty_smt \u2192 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: \u2200 (s:irstate irsem_smt) (f:valty_smt \u2192 valty_smt) n,\n  irstate.getreg irsem_smt s n = none \u2194\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 \u2190 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: \u2200 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: \u2200 (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: \u2200 (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) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport tactic.auto_cases\nimport tactic.chain\nimport tactic.norm_cast\n\nnamespace tactic\n\nnamespace tidy\n/-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics\ncalled by `tidy`. -/\nmeta def tidy_attribute : user_attribute := {\n  name := `tidy,\n  descr := \"A tactic that should be called by `tidy`.\"\n}\n\nadd_tactic_doc\n{ name                     := \"tidy\",\n  category                 := doc_category.attr,\n  decl_names               := [`tactic.tidy.tidy_attribute],\n  tags                     := [\"search\"] }\n\nrun_cmd attribute.register ``tidy_attribute\n\nmeta def run_tactics : tactic string :=\ndo names \u2190 attribute.get_instances `tidy,\n   first (names.map name_to_tactic) <|> fail \"no @[tidy] tactics succeeded\"\n\n@[hint_tactic]\nmeta def ext1_wrapper : tactic string :=\ndo ng \u2190 num_goals,\n   ext1 [] {apply_cfg . new_goals := new_goals.all},\n   ng' \u2190 num_goals,\n   return $ if ng' > ng then\n     \"tactic.ext1 [] {new_goals := tactic.new_goals.all}\"\n   else \"ext1\"\n\nmeta def default_tactics : list (tactic string) :=\n[ reflexivity                                 >> pure \"refl\",\n  `[exact dec_trivial]                        >> pure \"exact dec_trivial\",\n  propositional_goal >> assumption            >> pure \"assumption\",\n  intros1                                     >>= \u03bb ns, pure (\"intros \" ++ (\" \".intercalate (ns.map (\u03bb e, e.to_string)))),\n  auto_cases,\n  `[apply_auto_param]                         >> pure \"apply_auto_param\",\n  `[dsimp at *]                               >> pure \"dsimp at *\",\n  `[simp at *]                                >> pure \"simp at *\",\n  ext1_wrapper,\n  fsplit                                      >> pure \"fsplit\",\n  injections_and_clear                        >> pure \"injections_and_clear\",\n  propositional_goal >> (`[solve_by_elim])    >> pure \"solve_by_elim\",\n  `[norm_cast]                                >> pure \"norm_cast\",\n  `[unfold_coes]                              >> pure \"unfold_coes\",\n  `[unfold_aux]                               >> pure \"unfold_aux\",\n  tidy.run_tactics ]\n\nmeta structure cfg :=\n(trace_result : bool            := ff)\n(trace_result_prefix : string   := \"Try this: \")\n(tactics : list (tactic string) := default_tactics)\n\ndeclare_trace tidy\n\nmeta def core (cfg : cfg := {}) : tactic (list string) :=\ndo\n  results \u2190 chain cfg.tactics,\n  when (cfg.trace_result) $\n    trace (cfg.trace_result_prefix ++ (\", \".intercalate results)),\n  return results\n\nend tidy\n\nmeta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip\n\nnamespace interactive\nopen lean.parser interactive\n\n/-- Use a variety of conservative tactics to solve goals.\n\n`tidy?` reports back the tactic script it found. As an example\n```lean\nexample : \u2200 x : unit, x = unit.star :=\nbegin\n  tidy? -- Prints the trace message: \"Try this: intros x, exact dec_trivial\"\nend\n```\n\nThe default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.\nThis list can be overridden using `tidy { tactics := ... }`.\n(The list must be a `list` of `tactic string`, so that `tidy?`\ncan report a usable tactic script.)\n\nTactics can also be added to the list by tagging them (locally) with the\n`[tidy]` attribute. -/\nmeta def tidy (trace : parse $ optional (tk \"?\")) (cfg : tidy.cfg := {}) :=\ntactic.tidy { trace_result := trace.is_some, ..cfg }\nend interactive\n\nadd_tactic_doc\n{ name                     := \"tidy\",\n  category                 := doc_category.tactic,\n  decl_names               := [`tactic.interactive.tidy],\n  tags                     := [\"search\", \"Try this\", \"finishing\"] }\n\n/-- Invoking the hole command `tidy` (\"Use `tidy` to complete the goal\") runs the tactic of\nthe same name, replacing the hole with the tactic script `tidy` produces.\n-/\n@[hole_command] meta def tidy_hole_cmd : hole_command :=\n{ name := \"tidy\",\n  descr := \"Use `tidy` to complete the goal.\",\n  action := \u03bb _, do script \u2190 tidy.core,\n    return [(\"begin \" ++ (\", \".intercalate script) ++ \" end\", \"by tidy\")] }\n\nadd_tactic_doc\n{ name                     := \"tidy\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.tidy_hole_cmd],\n  tags                     := [\"search\"] }\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/tidy.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037884, "lm_q2_score": 0.18713268669577832, "lm_q1q2_score": 0.03776585049231695}}
{"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 \u00d7 Y`\n* the product of a family `f : J \u2192 Type` is `\u03a0 j, f j`\n* the binary coproduct of `X` and `Y` is the sum type `X \u2295 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 \u27f6 Z` and `g : Y \u27f6 Z` is the subtype `{ p : X \u00d7 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_\u03c0_apply` that uses `pi.\u03c0` and `pi.lift`. -/\n@[simp]\nlemma pi_lift_\u03c0_apply\n  {\u03b2 : Type u} (f : \u03b2 \u2192 Type u) {P : Type u} (s : \u03a0 b, P \u27f6 f b) (b : \u03b2) (x : P) :\n  (pi.\u03c0 f b : (\u220f f) \u2192 f b) (@pi.lift \u03b2 _ _ f _ P s x) = s b x :=\ncongr_fun (limit.lift_\u03c0 (fan.mk P s) b) x\n\n/-- A restatement of `types.map_\u03c0_apply` that uses `pi.\u03c0` and `pi.map`. -/\n@[simp]\nlemma pi_map_\u03c0_apply {\u03b2 : Type u} {f g : \u03b2 \u2192 Type u} (\u03b1 : \u03a0 j, f j \u27f6 g j) (b : \u03b2) (x) :\n  (pi.\u03c0 g b : (\u220f g) \u2192 g b) (pi.map \u03b1 x) = \u03b1 b ((pi.\u03c0 f b : (\u220f f) \u2192 f b) x) :=\nlimit.map_\u03c0_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    \u03c0 := 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    \u03b9 := by tidy, },\n  is_colimit := by tidy, }\n\nopen category_theory.limits.walking_pair\n\n/-- The product type `X \u00d7 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 \u00d7 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 := \u03bb (s : binary_fan X Y) x, (s.fst x, s.snd x),\n  fac' := \u03bb s j, walking_pair.cases_on j rfl rfl,\n  uniq' := \u03bb s m w, funext $ \u03bb x, prod.ext (congr_fun (w left) x) (congr_fun (w right) x) }\n\n/--\nThe category of types has `X \u00d7 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\u27e8_, binary_product_limit X Y\u27e9\n\n/-- The functor which sends `X, Y` to the product type `X \u00d7 Y`. -/\n-- We add the option `type_md` to tell `@[simps]` to not treat homomorphisms `X \u27f6 Y` in `Type*` as\n-- a function type\n@[simps {type_md := reducible}]\ndef binary_product_functor : Type u \u2964 Type u \u2964 Type u :=\n{ obj := \u03bb X,\n  { obj := \u03bb Y, X \u00d7 Y,\n    map := \u03bb Y\u2081 Y\u2082 f, (binary_product_limit X Y\u2082).lift (binary_fan.mk prod.fst (prod.snd \u226b f)) },\n  map := \u03bb X\u2081 X\u2082 f,\n  { app := \u03bb Y, (binary_product_limit X\u2082 Y).lift (binary_fan.mk (prod.fst \u226b 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 \u2245 (prod.functor : Type u \u2964 _) :=\nbegin\n  apply nat_iso.of_components (\u03bb X, _) _,\n  { apply nat_iso.of_components (\u03bb Y, _) _,\n    { exact ((limit.is_limit _).cone_point_unique_up_to_iso (binary_product_limit X Y)).symm },\n    { intros Y\u2081 Y\u2082 f,\n      ext1;\n      simp } },\n  { intros X\u2081 X\u2082 g,\n    ext : 3;\n    simp }\nend\n\n/-- The sum type `X \u2295 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 \u2295 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 := \u03bb (s : binary_cofan X Y), sum.elim s.inl s.inr,\n  fac' := \u03bb s j, walking_pair.cases_on j rfl rfl,\n  uniq' := \u03bb s m w, funext $ \u03bb x, sum.cases_on x (congr_fun (w left)) (congr_fun (w right)) }\n\n/--\nThe category of types has `X \u2295 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\u27e8_, binary_coproduct_colimit X Y\u27e9\n\n/--\nThe category of types has `\u03a0 j, f j` as the product of a type family `f : J \u2192 Type`.\n-/\ndef product_limit_cone {J : Type u} (F : J \u2192 Type u) : limits.limit_cone (discrete.functor F) :=\n{ cone :=\n  { X := \u03a0 j, F j,\n    \u03c0 := { app := \u03bb j f, f j }, },\n  is_limit :=\n  { lift := \u03bb s x j, s.\u03c0.app j x,\n    uniq' := \u03bb s m w, funext $ \u03bb x, funext $ \u03bb j, (congr_fun (w j) x : _) } }\n\n/--\nThe category of types has `\u03a3 j, f j` as the coproduct of a type family `f : J \u2192 Type`.\n-/\ndef coproduct_colimit_cocone {J : Type u} (F : J \u2192 Type u) :\n  limits.colimit_cocone (discrete.functor F) :=\n{ cocone :=\n  { X := \u03a3 j, F j,\n    \u03b9 :=\n    { app := \u03bb j x, \u27e8j, x\u27e9 }, },\n  is_colimit :=\n  { desc := \u03bb s x, s.\u03b9.app x.1 x.2,\n    uniq' := \u03bb s m w,\n    begin\n      ext \u27e8j, x\u27e9,\n      have := congr_fun (w j) x,\n      exact this,\n    end }, }\n\nsection fork\nvariables {X Y Z : Type u} (f : X \u27f6 Y) {g h : Y \u27f6 Z} (w : f \u226b g = f \u226b 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 : \u2200 (y : Y), g y = h y \u2192 \u2203! (x : X), f x = y) :\n  is_limit (fork.of_\u03b9 _ w) :=\nfork.is_limit.mk' _ $ \u03bb s,\nbegin\n  refine \u27e8\u03bb i, _, _, _\u27e9,\n  { apply classical.some (t (s.\u03b9 i) _),\n    apply congr_fun s.condition i },\n  { ext i,\n    apply (classical.some_spec (t (s.\u03b9 i) _)).1 },\n  { intros m hm,\n    ext i,\n    apply (classical.some_spec (t (s.\u03b9 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_\u03b9 _ w)) (y : Y) (hy : g y = h y) :\n  \u2203! (x : X), f x = y :=\nbegin\n  let y' : punit \u27f6 Y := \u03bb _, y,\n  have hy' : y' \u226b g = y' \u226b h := funext (\u03bb _, hy),\n  refine \u27e8(fork.is_limit.lift' t _ hy').1 \u27e8\u27e9, congr_fun (fork.is_limit.lift' t y' _).2 \u27e8\u27e9, _\u27e9,\n  intros x' hx',\n  suffices : (\u03bb (_ : punit), x') = (fork.is_limit.lift' t y' hy').1,\n    rw \u2190 this,\n  apply fork.is_limit.hom_ext t,\n  ext \u27e8\u27e9,\n  apply hx'.trans (congr_fun (fork.is_limit.lift' t _ hy').2 \u27e8\u27e9).symm,\nend\n\nlemma type_equalizer_iff_unique :\n  nonempty (is_limit (fork.of_\u03b9 _ w)) \u2194 (\u2200 (y : Y), g y = h y \u2192 \u2203! (x : X), f x = y) :=\n\u27e8\u03bb i, unique_of_type_equalizer _ _ (classical.choice i), \u03bb k, \u27e8type_equalizer_of_unique f w k\u27e9\u27e9\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_\u03b9 (subtype.val : {x : Y // g x = h x} \u2192 Y) (funext subtype.prop),\n  is_limit := fork.is_limit.mk' _ $ \u03bb s,\n    \u27e8\u03bb i, \u27e8s.\u03b9 i, by apply congr_fun s.condition i\u27e9,\n     rfl,\n     \u03bb m hm, funext $ \u03bb x, subtype.ext (congr_fun hm x)\u27e9 }\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 \u27f6 Z) (g : Y \u27f6 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 \u00d7 Y // f p.1 = g p.2 }\n\n-- `pullback_obj f g` comes with a coercion to the product type `X \u00d7 Y`.\nexample (p : pullback_obj f g) : X \u00d7 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 (\u03bb p : pullback_obj f g, p.1.1) (\u03bb p, p.1.2) (funext (\u03bb 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 \u27f6 Z) (g : Y \u27f6 Z) : limits.limit_cone (cospan f g) :=\n{ cone := pullback_cone f g,\n  is_limit := pullback_cone.is_limit_aux _\n    (\u03bb s x, \u27e8\u27e8s.fst x, s.snd x\u27e9, congr_fun s.condition x\u27e9)\n    (by tidy)\n    (by tidy)\n    (\u03bb s m w, funext $ \u03bb 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) \u2245 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 \u2245 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 \u00d7 Y).fst = (pullback.fst : _ \u27f6 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 \u00d7 Y).snd = (pullback.snd : _ \u27f6 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 \u226b pullback.fst = (\u03bb p, (p : X \u00d7 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 \u226b pullback.snd = (\u03bb p, (p : X \u00d7 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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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 \u2192 target\n| forward : name \u2192 target\n| backwards : name \u2192 target\n\n/-- The name underlying an alias target -/\nmeta def target.to_name : target \u2192 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 \u2192 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 \u2190 al`. Creates an alias `al` for declaration `d`. -/\nmeta def alias_direct (doc : option string) (d : declaration) (al : name) : tactic unit :=\ndo updateex_env $ \u03bb 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 `\u03a0 x y z, a \u2194 b`, produces a proof of `\u03a0 x y z, a \u2192 b` or `\u03a0 x y z, b \u2192 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 \u2192 (\u2115 \u2192 expr) \u2192 tactic expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)\n| _ f := fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/-- The core tactic which handles `alias d \u2194 al _` or `alias d \u2194 _ 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 \u2190 mk_iff_mp_app iffmp t (\u03bb_, expr.const d.to_name (level.param <$> ls)),\n    t' \u2190 infer_type v,\n    updateex_env $ \u03bb 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 \u2194 ..`. -/\nmeta def make_left_right : name \u2192 tactic (name \u00d7 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) \u2190 pure $ parts.span (\u2260 \"iff\"),\n  let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,\n  (suffix', right') \u2190 pure $ right.reverse.span (\u03bb s, pfx \"left\" s \u2228 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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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 \u2190 ident,\n  d \u2190 (do old \u2190 resolve_constant old, get_decl old) <|>\n    fail (\"declaration \" ++ to_string old ++ \" not found\"),\n  ns \u2190 get_current_namespace,\n  let doc := meta_info.doc_string,\n  do\n  { tk \"\u2190\" <|> tk \"<-\",\n    aliases \u2190 many ident,\n    \u2191(aliases.mmap' $ \u03bb al, alias_direct doc d (ns.append_namespace al)) } <|>\n  do\n  { tk \"\u2194\" <|> tk \"<->\",\n    (left, right) \u2190\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 \u2190 has_attribute' `alias n | pure none,\n   v \u2190 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 \u2192 Type v} [Functor f] {\u03b1 \u03b2 : Type u} : f \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 f \u03b2 :=\n  fun a f => f <$> a\n\ninfixr:100 \" <&> \" => Functor.mapRev\n\n@[always_inline, inline]\ndef Functor.discard {f : Type u \u2192 Type v} {\u03b1 : Type u} [Functor f] (x : f \u03b1) : f PUnit :=\n  Functor.mapConst PUnit.unit x\n\nexport Functor (discard)\n\nclass Alternative (f : Type u \u2192 Type v) extends Applicative f : Type (max (u+1) v) where\n  failure : {\u03b1 : Type u} \u2192 f \u03b1\n  orElse  : {\u03b1 : Type u} \u2192 f \u03b1 \u2192 (Unit \u2192 f \u03b1) \u2192 f \u03b1\n\ninstance (f : Type u \u2192 Type v) (\u03b1 : Type u) [Alternative f] : OrElse (f \u03b1) := \u27e8Alternative.orElse\u27e9\n\nvariable {f : Type u \u2192 Type v} [Alternative f] {\u03b1 : Type u}\n\nexport Alternative (failure)\n\n@[always_inline, inline] def guard {f : Type \u2192 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 \u03b1) : f (Option \u03b1) :=\n  some <$> x <|> pure none\n\nclass ToBool (\u03b1 : Type u) where\n  toBool : \u03b1 \u2192 Bool\n\nexport ToBool (toBool)\n\ninstance : ToBool Bool where\n  toBool b := b\n\n@[macro_inline] def bool {\u03b2 : Type u} {\u03b1 : Type v} [ToBool \u03b2] (f t : \u03b1) (b : \u03b2) : \u03b1 :=\n  match toBool b with\n  | true  => t\n  | false => f\n\n@[macro_inline] def orM {m : Type u \u2192 Type v} {\u03b2 : Type u} [Monad m] [ToBool \u03b2] (x y : m \u03b2) : m \u03b2 := do\n  let b \u2190 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 \u2192 Type v} {\u03b2 : Type u} [Monad m] [ToBool \u03b2] (x y : m \u03b2) : m \u03b2 := do\n  let b \u2190 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 \u2192 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 : \u2200 \u03b1, IO \u03b1 \u2192 IO \u03b1` and `bar : StateT \u03c3 IO \u03b2` (ie, `bar : \u03c3 \u2192 IO (\u03c3 \u00d7 \u03b2)`).\nWe might want to 'map' `bar` by `foo`. Concretely we would write this as:\n\n```lean\nopaque foo : \u2200 {\u03b1}, IO \u03b1 \u2192 IO \u03b1\nopaque bar : StateT \u03c3 IO \u03b2\n\ndef mapped_foo : StateT \u03c3 IO \u03b2 := do\n  let s \u2190 get\n  let (b, s') \u2190 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 \u03b1 \u2192 StateT \u03c3 m \u03b1` for all `m`, but we also need to 'unlift' the state.\nBut `unlift : StateT \u03c3 IO \u03b1 \u2192 IO \u03b1` 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 (\u03c3 \u00d7 \u03b2)`. The key idea is that `\u03c3 \u00d7 \u03b2` 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 (\u03c3 \u00d7 \u03b2)` as `IO (stM \u03b2)`\n- Write `StateT.run . s` as `mapInBase : StateT \u03c3 IO \u03b1 \u2192 IO (stM \u03b2)`\n- Define `restoreM : IO (stM \u03b1) \u2192 StateT \u03c3 IO \u03b1` as below\n\n```lean\ndef stM (\u03b1 : Type) := \u03b1 \u00d7 \u03c3\n\ndef restoreM (x : IO (stM \u03b1)) : StateT \u03c3 IO \u03b1 := do\n  let (a,s) \u2190 liftM x\n  set s\n  return a\n```\n\nTo get:\n\n```lean\ndef mapped_foo' : StateT \u03c3 IO \u03b2 := do\n  let s \u2190 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 {\u03b1 : Type}\n  (f : ({\u03b2 : Type} \u2192 StateT \u03c3 IO \u03b2 \u2192 IO (stM \u03b2)) \u2192 IO (stM \u03b1))\n  : StateT \u03c3 IO \u03b1 := do\n  let s \u2190 get\n  let mapInBase := fun {\u03b2} (z : StateT \u03c3 IO \u03b2) => StateT.run z s\n  let r : IO (stM \u03b1) := f mapInBase\n  restoreM r\n```\n\nNow we can write `mapped_foo` as:\n\n```lean\ndef mapped_foo'' : StateT \u03c3 IO \u03b2 :=\n  control (fun mapInBase => foo (mapInBase bar))\n```\n\nThe core idea of `mapInBase` is that given any `\u03b2`, it runs an instance of\n`StateT \u03c3 IO \u03b2` and 'packages' the result and state as  `IO (stM \u03b2)` 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 \u03b2 = \u03c3 \u00d7 \u03b2` is the 'packaged result state', but we can generalise:\nif we have a tower `StateT \u03c3\u2081 <| StateT \u03c3\u2082 <| IO`, then the\ncomposite packaged state is going to be `stM\u2081\u2082 \u03b2 := \u03c3\u2081 \u00d7 \u03c3\u2082 \u00d7 \u03b2` or `stM\u2081\u2082 := stM\u2081 \u2218 stM\u2082`.\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 \u03b1 \u2192 MetaM \u03b1` that runs the input monad instance\nin a new nested metavariable context. We can lift this to `withNewMctxDepth : n \u03b1 \u2192 n \u03b1` 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 {\u03b1} : (\u2200 {\u03b2}, m \u03b2 \u2192 m \u03b2) \u2192 n \u03b1 \u2192 n \u03b1`. 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 {\u03b1}, (\u03b2 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 n \u03b1) : n \u03b1 :=\n   control fun runInBase => f fun b => runInBase <| k b\n\n @[inline] def map2MetaM [MonadControlT MetaM n] [Monad n] (f : forall {\u03b1}, (\u03b2 \u2192 \u03b3 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 \u03b3 \u2192 n \u03b1) : n \u03b1 :=\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 \u2192 Type v) (n : Type u \u2192 Type w) where\n  stM      : Type u \u2192 Type u\n  liftWith : {\u03b1 : Type u} \u2192 (({\u03b2 : Type u} \u2192 n \u03b2 \u2192 m (stM \u03b2)) \u2192 m \u03b1) \u2192 n \u03b1\n  restoreM : {\u03b1 : Type u} \u2192 m (stM \u03b1) \u2192 n \u03b1\n\n/-- Transitive closure of MonadControl. -/\nclass MonadControlT (m : Type u \u2192 Type v) (n : Type u \u2192 Type w) where\n  stM      : Type u \u2192 Type u\n  liftWith : {\u03b1 : Type u} \u2192 (({\u03b2 : Type u} \u2192 n \u03b2 \u2192 m (stM \u03b2)) \u2192 m \u03b1) \u2192 n \u03b1\n  restoreM {\u03b1 : Type u} : stM \u03b1 \u2192 n \u03b1\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 \u03b1 := stM m n (MonadControl.stM n o \u03b1)\n  liftWith f := MonadControl.liftWith fun x\u2082 => liftWith fun x\u2081 => f (x\u2081 \u2218 x\u2082)\n  restoreM := MonadControl.restoreM \u2218 restoreM\n\ninstance (m : Type u \u2192 Type v) [Pure m] : MonadControlT m m where\n  stM \u03b1 := \u03b1\n  liftWith f := f fun x => x\n  restoreM x := pure x\n\n@[always_inline, inline]\ndef controlAt (m : Type u \u2192 Type v) {n : Type u \u2192 Type w} [MonadControlT m n] [Bind n] {\u03b1 : Type u}\n    (f : ({\u03b2 : Type u} \u2192 n \u03b2 \u2192 m (stM m n \u03b2)) \u2192 m (stM m n \u03b1)) : n \u03b1 :=\n  liftWith f >>= restoreM\n\n@[always_inline, inline]\ndef control {m : Type u \u2192 Type v} {n : Type u \u2192 Type w} [MonadControlT m n] [Bind n] {\u03b1 : Type u}\n    (f : ({\u03b2 : Type u} \u2192 n \u03b2 \u2192 m (stM m n \u03b2)) \u2192 m (stM m n \u03b1)) : n \u03b1 :=\n  controlAt m f\n\n/--\n  Typeclass for the polymorphic `forM` operation described in the \"do unchained\" paper.\n  Remark:\n  - `\u03b3` is a \"container\" type of elements of type `\u03b1`.\n  - `\u03b1` is treated as an output parameter by the typeclass resolution procedure.\n    That is, it tries to find an instance using only `m` and `\u03b3`.\n-/\nclass ForM (m : Type u \u2192 Type v) (\u03b3 : Type w\u2081) (\u03b1 : outParam (Type w\u2082)) where\n  forM [Monad m] : \u03b3 \u2192 (\u03b1 \u2192 m PUnit) \u2192 m PUnit\n\nexport ForM (forM)\n\n/-- Left-to-right composition of Kleisli arrows. -/\n@[always_inline]\ndef Bind.kleisliRight [Bind m] (f\u2081 : \u03b1 \u2192 m \u03b2) (f\u2082 : \u03b2 \u2192 m \u03b3) (a : \u03b1) : m \u03b3 :=\n  f\u2081 a >>= f\u2082\n\n/-- Right-to-left composition of Kleisli arrows. -/\n@[always_inline]\ndef Bind.kleisliLeft [Bind m] (f\u2082 : \u03b2 \u2192 m \u03b3) (f\u2081 : \u03b1 \u2192 m \u03b2) (a : \u03b1) : m \u03b3 :=\n  f\u2081 a >>= f\u2082\n\n/-- Same as `Bind.bind` but with arguments swapped. -/\n@[always_inline]\ndef Bind.bindLeft [Bind m] (f : \u03b1 \u2192 m \u03b2) (ma : m \u03b1) : m \u03b2 :=\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": "import ProofWidgets.Presentation.Goal\n\nopen ProofWidgets Jsx\n\n@[expr_presenter]\ndef presenter : ExprPresenter where\n  userName := \"With octopodes\"\n  layoutKind := .inline\n  isApplicable _ := return true\n  present e :=\n    return Html.ofTHtml\n      <span>\n        {.text \"\ud83d\udc19 \"}<InteractiveCode fmt={\u2190 Lean.Widget.ppExprTagged e} />{.text \" \ud83d\udc19\"}\n      </span>\n\nexample (h : 2 + 2 = 5) : 2 + 2 = 4 := by\n  withSelectionDisplay\n  -- Place cursor here and select subexpressions in the goal with shift-click\n    rfl\n", "meta": {"author": "EdAyers", "repo": "ProofWidgets4", "sha": "c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e", "save_path": "github-repos/lean/EdAyers-ProofWidgets4", "path": "github-repos/lean/EdAyers-ProofWidgets4/ProofWidgets4-c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e/ProofWidgets/Demos/ExprPresentation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.39233681595684605, "lm_q2_score": 0.09534946104307897, "lm_q1q2_score": 0.037409103948842934}}
{"text": "/-\nCopyright (c) 2017 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl\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 {\u03b1 : Sort u_1} {s : setoid \u03b1} {t : setoid \u03b1} : (\u2200 (a b : \u03b1), r a b \u2194 r a b) \u2192 s = t := sorry\n\nend setoid\n\n\nnamespace quot\n\n\nprotected instance inhabited {\u03b1 : Sort u_1} {ra : \u03b1 \u2192 \u03b1 \u2192 Prop} [Inhabited \u03b1] : Inhabited (Quot ra) :=\n  { default := Quot.mk ra Inhabited.default }\n\n/-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `\u27e6a\u27e7` and `\u27e6b\u27e7`. -/\nprotected def hrec_on\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {ra : \u03b1 \u2192 \u03b1 \u2192 Prop} {rb : \u03b2 \u2192 \u03b2 \u2192 Prop} {\u03c6 : Quot ra \u2192 Quot rb \u2192 Sort u_3} (qa : Quot ra) (qb : Quot rb) (f : (a : \u03b1) \u2192 (b : \u03b2) \u2192 \u03c6 (Quot.mk ra a) (Quot.mk rb b)) (ca : \u2200 {b : \u03b2} {a\u2081 a\u2082 : \u03b1}, ra a\u2081 a\u2082 \u2192 f a\u2081 b == f a\u2082 b) (cb : \u2200 {a : \u03b1} {b\u2081 b\u2082 : \u03b2}, rb b\u2081 b\u2082 \u2192 f a b\u2081 == f a b\u2082) : \u03c6 qa qb :=\n  quot.hrec_on qa (fun (a : \u03b1) => quot.hrec_on qb (f a) sorry) sorry\n\n/-- Map a function `f : \u03b1 \u2192 \u03b2` such that `ra x y` implies `rb (f x) (f y)`\nto a map `quot ra \u2192 quot rb`. -/\nprotected def map {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {ra : \u03b1 \u2192 \u03b1 \u2192 Prop} {rb : \u03b2 \u2192 \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2) (h : relator.lift_fun ra rb f f) : Quot ra \u2192 Quot rb :=\n  Quot.lift (fun (x : \u03b1) => Quot.mk rb (f x)) sorry\n\n/-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra \u2192 quot ra'`. -/\nprotected def map_right {\u03b1 : Sort u_1} {ra : \u03b1 \u2192 \u03b1 \u2192 Prop} {ra' : \u03b1 \u2192 \u03b1 \u2192 Prop} (h : \u2200 (a\u2081 a\u2082 : \u03b1), ra a\u2081 a\u2082 \u2192 ra' a\u2081 a\u2082) : Quot ra \u2192 Quot ra' :=\n  quot.map id h\n\n/-- weaken the relation of a quotient -/\ndef factor {\u03b1 : Type u_1} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (s : \u03b1 \u2192 \u03b1 \u2192 Prop) (h : \u2200 (x y : \u03b1), r x y \u2192 s x y) : Quot r \u2192 Quot s :=\n  Quot.lift (Quot.mk s) sorry\n\ntheorem factor_mk_eq {\u03b1 : Type u_1} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (s : \u03b1 \u2192 \u03b1 \u2192 Prop) (h : \u2200 (x y : \u03b1), r x y \u2192 s x y) : factor r s h \u2218 Quot.mk r = Quot.mk s :=\n  rfl\n\n/-- Descends a function `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3` to quotients of `\u03b1` and `\u03b2`. -/\nprotected def lift\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hr : \u2200 (a : \u03b1) (b\u2081 b\u2082 : \u03b2), s b\u2081 b\u2082 \u2192 f a b\u2081 = f a b\u2082) (hs : \u2200 (a\u2081 a\u2082 : \u03b1) (b : \u03b2), r a\u2081 a\u2082 \u2192 f a\u2081 b = f a\u2082 b) (q\u2081 : Quot r) (q\u2082 : Quot s) : \u03b3 :=\n  Quot.lift (fun (a : \u03b1) => Quot.lift (f a) (hr a)) sorry q\u2081 q\u2082\n\n@[simp] theorem lift\u2082_mk {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} (a : \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hr : \u2200 (a : \u03b1) (b\u2081 b\u2082 : \u03b2), s b\u2081 b\u2082 \u2192 f a b\u2081 = f a b\u2082) (hs : \u2200 (a\u2081 a\u2082 : \u03b1) (b : \u03b2), r a\u2081 a\u2082 \u2192 f a\u2081 b = f a\u2082 b) : quot.lift\u2082 f hr hs (Quot.mk r a) (Quot.mk s b) = f a b :=\n  rfl\n\n/-- Descends a function `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3` to quotients of `\u03b1` and `\u03b2` and applies it. -/\nprotected def lift_on\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} (p : Quot r) (q : Quot s) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hr : \u2200 (a : \u03b1) (b\u2081 b\u2082 : \u03b2), s b\u2081 b\u2082 \u2192 f a b\u2081 = f a b\u2082) (hs : \u2200 (a\u2081 a\u2082 : \u03b1) (b : \u03b2), r a\u2081 a\u2082 \u2192 f a\u2081 b = f a\u2082 b) : \u03b3 :=\n  quot.lift\u2082 f hr hs p q\n\n@[simp] theorem lift_on\u2082_mk {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} (a : \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hr : \u2200 (a : \u03b1) (b\u2081 b\u2082 : \u03b2), s b\u2081 b\u2082 \u2192 f a b\u2081 = f a b\u2082) (hs : \u2200 (a\u2081 a\u2082 : \u03b1) (b : \u03b2), r a\u2081 a\u2082 \u2192 f a\u2081 b = f a\u2082 b) : quot.lift_on\u2082 (Quot.mk r a) (Quot.mk s b) f hr hs = f a b :=\n  rfl\n\n/-- Descends a function `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3` to quotients of `\u03b1` and `\u03b2` wih values in a quotient of\n`\u03b3`. -/\nprotected def map\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} {t : \u03b3 \u2192 \u03b3 \u2192 Prop} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hr : \u2200 (a : \u03b1) (b\u2081 b\u2082 : \u03b2), s b\u2081 b\u2082 \u2192 t (f a b\u2081) (f a b\u2082)) (hs : \u2200 (a\u2081 a\u2082 : \u03b1) (b : \u03b2), r a\u2081 a\u2082 \u2192 t (f a\u2081 b) (f a\u2082 b)) (q\u2081 : Quot r) (q\u2082 : Quot s) : Quot t :=\n  quot.lift\u2082 (fun (a : \u03b1) (b : \u03b2) => Quot.mk t (f a b)) sorry sorry q\u2081 q\u2082\n\n@[simp] theorem map\u2082_mk {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} {t : \u03b3 \u2192 \u03b3 \u2192 Prop} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hr : \u2200 (a : \u03b1) (b\u2081 b\u2082 : \u03b2), s b\u2081 b\u2082 \u2192 t (f a b\u2081) (f a b\u2082)) (hs : \u2200 (a\u2081 a\u2082 : \u03b1) (b : \u03b2), r a\u2081 a\u2082 \u2192 t (f a\u2081 b) (f a\u2082 b)) (a : \u03b1) (b : \u03b2) : quot.map\u2082 f hr hs (Quot.mk r a) (Quot.mk s b) = Quot.mk t (f a b) :=\n  rfl\n\nprotected theorem induction_on\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} {\u03b4 : Quot r \u2192 Quot s \u2192 Prop} (q\u2081 : Quot r) (q\u2082 : Quot s) (h : \u2200 (a : \u03b1) (b : \u03b2), \u03b4 (Quot.mk r a) (Quot.mk s b)) : \u03b4 q\u2081 q\u2082 :=\n  Quot.ind (fun (a\u2081 : \u03b1) => Quot.ind (fun (a\u2082 : \u03b2) => h a\u2081 a\u2082) q\u2082) q\u2081\n\nprotected theorem induction_on\u2083 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_4} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : \u03b2 \u2192 \u03b2 \u2192 Prop} {t : \u03b3 \u2192 \u03b3 \u2192 Prop} {\u03b4 : Quot r \u2192 Quot s \u2192 Quot t \u2192 Prop} (q\u2081 : Quot r) (q\u2082 : Quot s) (q\u2083 : Quot t) (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), \u03b4 (Quot.mk r a) (Quot.mk s b) (Quot.mk t c)) : \u03b4 q\u2081 q\u2082 q\u2083 :=\n  Quot.ind (fun (a\u2081 : \u03b1) => Quot.ind (fun (a\u2082 : \u03b2) => Quot.ind (fun (a\u2083 : \u03b3) => h a\u2081 a\u2082 a\u2083) q\u2083) q\u2082) q\u2081\n\nend quot\n\n\nnamespace quotient\n\n\nprotected instance inhabited {\u03b1 : Sort u_1} [sa : setoid \u03b1] [Inhabited \u03b1] : Inhabited (quotient sa) :=\n  { default := quotient.mk Inhabited.default }\n\n/-- Induction on two `quotient` arguments `a` and `b`, result type depends on `\u27e6a\u27e7` and `\u27e6b\u27e7`. -/\nprotected def hrec_on\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [sa : setoid \u03b1] [sb : setoid \u03b2] {\u03c6 : quotient sa \u2192 quotient sb \u2192 Sort u_3} (qa : quotient sa) (qb : quotient sb) (f : (a : \u03b1) \u2192 (b : \u03b2) \u2192 \u03c6 (quotient.mk a) (quotient.mk b)) (c : \u2200 (a\u2081 : \u03b1) (b\u2081 : \u03b2) (a\u2082 : \u03b1) (b\u2082 : \u03b2), a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 == f a\u2082 b\u2082) : \u03c6 qa qb :=\n  quot.hrec_on\u2082 qa qb f sorry sorry\n\n/-- Map a function `f : \u03b1 \u2192 \u03b2` that sends equivalent elements to equivalent elements\nto a function `quotient sa \u2192 quotient sb`. Useful to define unary operations on quotients. -/\nprotected def map {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [sa : setoid \u03b1] [sb : setoid \u03b2] (f : \u03b1 \u2192 \u03b2) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) : quotient sa \u2192 quotient sb :=\n  quot.map f h\n\n@[simp] theorem map_mk {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [sa : setoid \u03b1] [sb : setoid \u03b2] (f : \u03b1 \u2192 \u03b2) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) (x : \u03b1) : quotient.map f h (quotient.mk x) = quotient.mk (f x) :=\n  rfl\n\n/-- Map a function `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3` that sends equivalent elements to equivalent elements\nto a function `f : quotient sa \u2192 quotient sb \u2192 quotient sc`.\nUseful to define binary operations on quotients. -/\nprotected def map\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [sa : setoid \u03b1] [sb : setoid \u03b2] {\u03b3 : Sort u_4} [sc : setoid \u03b3] (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv \u21d2 has_equiv.equiv) f f) : quotient sa \u2192 quotient sb \u2192 quotient sc :=\n  quotient.lift\u2082 (fun (x : \u03b1) (y : \u03b2) => quotient.mk (f x y)) sorry\n\nend quotient\n\n\ntheorem quot.eq {\u03b1 : Type u_1} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {x : \u03b1} {y : \u03b1} : Quot.mk r x = Quot.mk r y \u2194 eqv_gen r x y :=\n  { mp := quot.exact r, mpr := quot.eqv_gen_sound }\n\n@[simp] theorem quotient.eq {\u03b1 : Sort u_1} [r : setoid \u03b1] {x : \u03b1} {y : \u03b1} : quotient.mk x = quotient.mk y \u2194 x \u2248 y :=\n  { mp := quotient.exact, mpr := quotient.sound }\n\ntheorem forall_quotient_iff {\u03b1 : Type u_1} [r : setoid \u03b1] {p : quotient r \u2192 Prop} : (\u2200 (a : quotient r), p a) \u2194 \u2200 (a : \u03b1), p (quotient.mk a) :=\n  { mp := fun (h : \u2200 (a : quotient r), p a) (x : \u03b1) => h (quotient.mk x),\n    mpr := fun (h : \u2200 (a : \u03b1), p (quotient.mk a)) (a : quotient r) => quotient.induction_on a h }\n\n@[simp] theorem quotient.lift_beta {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [s : setoid \u03b1] (f : \u03b1 \u2192 \u03b2) (h : \u2200 (a b : \u03b1), a \u2248 b \u2192 f a = f b) (x : \u03b1) : quotient.lift f h (quotient.mk x) = f x :=\n  rfl\n\n@[simp] theorem quotient.lift_on_beta {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [s : setoid \u03b1] (f : \u03b1 \u2192 \u03b2) (h : \u2200 (a b : \u03b1), a \u2248 b \u2192 f a = f b) (x : \u03b1) : quotient.lift_on (quotient.mk x) f h = f x :=\n  rfl\n\n@[simp] theorem quotient.lift_on_beta\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [setoid \u03b1] (f : \u03b1 \u2192 \u03b1 \u2192 \u03b2) (h : \u2200 (a\u2081 a\u2082 b\u2081 b\u2082 : \u03b1), a\u2081 \u2248 b\u2081 \u2192 a\u2082 \u2248 b\u2082 \u2192 f a\u2081 a\u2082 = f b\u2081 b\u2082) (x : \u03b1) (y : \u03b1) : quotient.lift_on\u2082 (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 {\u03b1 : Sort u_1} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : function.surjective (Quot.mk r) :=\n  quot.exists_rep\n\n/-- `quotient.mk` is a surjective function. -/\ntheorem surjective_quotient_mk (\u03b1 : Sort u_1) [s : setoid \u03b1] : 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 {\u03b1 : Sort u_1} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : \u03b1 :=\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 {\u03b1 : Sort u_1} {r : \u03b1 \u2192 \u03b1 \u2192 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 {\u03b1 : Sort u_1} [s : setoid \u03b1] : quotient s \u2192 \u03b1 :=\n  quot.out\n\n@[simp] theorem quotient.out_eq {\u03b1 : Sort u_1} [s : setoid \u03b1] (q : quotient s) : quotient.mk (quotient.out q) = q :=\n  quot.out_eq q\n\ntheorem quotient.mk_out {\u03b1 : Sort u_1} [s : setoid \u03b1] (a : \u03b1) : quotient.out (quotient.mk a) \u2248 a :=\n  quotient.exact (quotient.out_eq (quotient.mk a))\n\nprotected instance pi_setoid {\u03b9 : Sort u_1} {\u03b1 : \u03b9 \u2192 Sort u_2} [(i : \u03b9) \u2192 setoid (\u03b1 i)] : setoid ((i : \u03b9) \u2192 \u03b1 i) :=\n  setoid.mk (fun (a b : (i : \u03b9) \u2192 \u03b1 i) => \u2200 (i : \u03b9), a i \u2248 b i) sorry\n\n/-- Given a function `f : \u03a0 i, quotient (S i)`, returns the class of functions `\u03a0 i, \u03b1 i` sending\neach `i` to an element of the class `f i`. -/\ndef quotient.choice {\u03b9 : Type u_1} {\u03b1 : \u03b9 \u2192 Type u_2} [S : (i : \u03b9) \u2192 setoid (\u03b1 i)] (f : (i : \u03b9) \u2192 quotient (S i)) : quotient Mathlib.pi_setoid :=\n  quotient.mk fun (i : \u03b9) => quotient.out (f i)\n\ntheorem quotient.choice_eq {\u03b9 : Type u_1} {\u03b1 : \u03b9 \u2192 Type u_2} [(i : \u03b9) \u2192 setoid (\u03b1 i)] (f : (i : \u03b9) \u2192 \u03b1 i) : (quotient.choice fun (i : \u03b9) => quotient.mk (f i)) = quotient.mk f :=\n  quotient.sound fun (i : \u03b9) => quotient.mk_out (f i)\n\ntheorem nonempty_quotient_iff {\u03b1 : Sort u_1} (s : setoid \u03b1) : Nonempty (quotient s) \u2194 Nonempty \u03b1 := sorry\n\n/-- `trunc \u03b1` is the quotient of `\u03b1` by the always-true relation. This\n  is related to the propositional truncation in HoTT, and is similar\n  in effect to `nonempty \u03b1`, but unlike `nonempty \u03b1`, `trunc \u03b1` is data,\n  so the VM representation is the same as `\u03b1`, and so this can be used to\n  maintain computability. -/\ndef trunc (\u03b1 : Sort u) :=\n  Quot fun (_x _x : \u03b1) => True\n\ntheorem true_equivalence {\u03b1 : Sort u_1} : equivalence fun (_x _x : \u03b1) => True :=\n  { left := fun (_x : \u03b1) => trivial,\n    right := { left := fun (_x _x : \u03b1) (_x : True) => trivial, right := fun (_x _x _x : \u03b1) (_x _x : True) => trivial } }\n\nnamespace trunc\n\n\n/-- Constructor for `trunc \u03b1` -/\ndef mk {\u03b1 : Sort u_1} (a : \u03b1) : trunc \u03b1 :=\n  Quot.mk (fun (_x _x : \u03b1) => True) a\n\nprotected instance inhabited {\u03b1 : Sort u_1} [Inhabited \u03b1] : Inhabited (trunc \u03b1) :=\n  { default := mk Inhabited.default }\n\n/-- Any constant function lifts to a function out of the truncation -/\ndef lift {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (c : \u2200 (a b : \u03b1), f a = f b) : trunc \u03b1 \u2192 \u03b2 :=\n  Quot.lift f sorry\n\ntheorem ind {\u03b1 : Sort u_1} {\u03b2 : trunc \u03b1 \u2192 Prop} : (\u2200 (a : \u03b1), \u03b2 (mk a)) \u2192 \u2200 (q : trunc \u03b1), \u03b2 q :=\n  Quot.ind\n\nprotected theorem lift_beta {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (c : \u2200 (a b : \u03b1), f a = f b) (a : \u03b1) : lift f c (mk a) = f a :=\n  rfl\n\n/-- Lift a constant function on `q : trunc \u03b1`. -/\nprotected def lift_on {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (q : trunc \u03b1) (f : \u03b1 \u2192 \u03b2) (c : \u2200 (a b : \u03b1), f a = f b) : \u03b2 :=\n  lift f c q\n\nprotected theorem induction_on {\u03b1 : Sort u_1} {\u03b2 : trunc \u03b1 \u2192 Prop} (q : trunc \u03b1) (h : \u2200 (a : \u03b1), \u03b2 (mk a)) : \u03b2 q :=\n  ind h q\n\ntheorem exists_rep {\u03b1 : Sort u_1} (q : trunc \u03b1) : \u2203 (a : \u03b1), mk a = q :=\n  quot.exists_rep q\n\nprotected theorem induction_on\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {C : trunc \u03b1 \u2192 trunc \u03b2 \u2192 Prop} (q\u2081 : trunc \u03b1) (q\u2082 : trunc \u03b2) (h : \u2200 (a : \u03b1) (b : \u03b2), C (mk a) (mk b)) : C q\u2081 q\u2082 :=\n  trunc.induction_on q\u2081 fun (a\u2081 : \u03b1) => trunc.induction_on q\u2082 (h a\u2081)\n\nprotected theorem eq {\u03b1 : Sort u_1} (a : trunc \u03b1) (b : trunc \u03b1) : a = b :=\n  trunc.induction_on\u2082 a b fun (x y : \u03b1) => quot.sound trivial\n\nprotected instance subsingleton {\u03b1 : Sort u_1} : subsingleton (trunc \u03b1) :=\n  subsingleton.intro trunc.eq\n\n/-- The `bind` operator for the `trunc` monad. -/\ndef bind {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (q : trunc \u03b1) (f : \u03b1 \u2192 trunc \u03b2) : trunc \u03b2 :=\n  trunc.lift_on q f sorry\n\n/-- A function `f : \u03b1 \u2192 \u03b2` defines a function `map f : trunc \u03b1 \u2192 trunc \u03b2`. -/\ndef map {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (q : trunc \u03b1) : trunc \u03b2 :=\n  bind q (mk \u2218 f)\n\nprotected instance monad : Monad trunc := sorry\n\nprotected instance is_lawful_monad : is_lawful_monad trunc :=\n  is_lawful_monad.mk (fun (\u03b1 \u03b2 : Type u_1) (q : \u03b1) (f : \u03b1 \u2192 trunc \u03b2) => rfl)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (x : trunc \u03b1) (f : \u03b1 \u2192 trunc \u03b2) (g : \u03b2 \u2192 trunc \u03b3) =>\n      trunc.eq (x >>= f >>= g) (x >>= fun (x : \u03b1) => f x >>= g)\n\n/-- Recursion/induction principle for `trunc`. -/\nprotected def rec {\u03b1 : Sort u_1} {C : trunc \u03b1 \u2192 Sort u_3} (f : (a : \u03b1) \u2192 C (mk a)) (h : \u2200 (a b : \u03b1), Eq._oldrec (f a) (rec._proof_1 a b) = f b) (q : trunc \u03b1) : C q :=\n  quot.rec f sorry q\n\n/-- A version of `trunc.rec` taking `q : trunc \u03b1` as the first argument. -/\nprotected def rec_on {\u03b1 : Sort u_1} {C : trunc \u03b1 \u2192 Sort u_3} (q : trunc \u03b1) (f : (a : \u03b1) \u2192 C (mk a)) (h : \u2200 (a b : \u03b1), 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 {\u03b1 : Sort u_1} {C : trunc \u03b1 \u2192 Sort u_3} [\u2200 (a : \u03b1), subsingleton (C (mk a))] (q : trunc \u03b1) (f : (a : \u03b1) \u2192 C (mk a)) : C q :=\n  trunc.rec f sorry q\n\n/-- Noncomputably extract a representative of `trunc \u03b1` (using the axiom of choice). -/\ndef out {\u03b1 : Sort u_1} : trunc \u03b1 \u2192 \u03b1 :=\n  quot.out\n\n@[simp] theorem out_eq {\u03b1 : Sort u_1} (q : trunc \u03b1) : mk (out q) = q :=\n  trunc.eq (mk (out q)) q\n\nend trunc\n\n\ntheorem nonempty_of_trunc {\u03b1 : Sort u_1} (q : trunc \u03b1) : Nonempty \u03b1 :=\n  (fun (_a : \u2203 (a : \u03b1), trunc.mk a = q) =>\n      Exists.dcases_on _a fun (w : \u03b1) (h : trunc.mk w = q) => idRhs (Nonempty \u03b1) (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 \u03b1}` as an implicit argument instead of an\ninstance argument. -/\nprotected def mk' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} (a : \u03b1) : quotient s\u2081 :=\n  Quot.mk setoid.r a\n\n/-- `quotient.mk'` is a surjective function. -/\ntheorem surjective_quotient_mk' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} : function.surjective quotient.mk' :=\n  quot.exists_rep\n\n/-- A version of `quotient.lift_on` taking `{s : setoid \u03b1}` as an implicit argument instead of an\ninstance argument. -/\nprotected def lift_on' {\u03b1 : Sort u_1} {\u03c6 : Sort u_4} {s\u2081 : setoid \u03b1} (q : quotient s\u2081) (f : \u03b1 \u2192 \u03c6) (h : \u2200 (a b : \u03b1), setoid.r a b \u2192 f a = f b) : \u03c6 :=\n  quotient.lift_on q f h\n\n@[simp] protected theorem lift_on'_beta {\u03b1 : Sort u_1} {\u03c6 : Sort u_4} {s\u2081 : setoid \u03b1} (f : \u03b1 \u2192 \u03c6) (h : \u2200 (a b : \u03b1), setoid.r a b \u2192 f a = f b) (x : \u03b1) : quotient.lift_on' (quotient.mk' x) f h = f x :=\n  rfl\n\n/-- A version of `quotient.lift_on\u2082` taking `{s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2}` as implicit arguments\ninstead of instance arguments. -/\nprotected def lift_on\u2082' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (h : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2) (b\u2081 : \u03b1) (b\u2082 : \u03b2), setoid.r a\u2081 b\u2081 \u2192 setoid.r a\u2082 b\u2082 \u2192 f a\u2081 a\u2082 = f b\u2081 b\u2082) : \u03b3 :=\n  quotient.lift_on\u2082 q\u2081 q\u2082 f h\n\n@[simp] protected theorem lift_on\u2082'_beta {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (h : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2) (b\u2081 : \u03b1) (b\u2082 : \u03b2), setoid.r a\u2081 b\u2081 \u2192 setoid.r a\u2082 b\u2082 \u2192 f a\u2081 a\u2082 = f b\u2081 b\u2082) (a : \u03b1) (b : \u03b2) : quotient.lift_on\u2082' (quotient.mk' a) (quotient.mk' b) f h = f a b :=\n  rfl\n\n/-- A version of `quotient.ind` taking `{s : setoid \u03b1}` as an implicit argument instead of an\ninstance argument. -/\nprotected theorem ind' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {p : quotient s\u2081 \u2192 Prop} (h : \u2200 (a : \u03b1), p (quotient.mk' a)) (q : quotient s\u2081) : p q :=\n  quotient.ind h q\n\n/-- A version of `quotient.ind\u2082` taking `{s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2}` as implicit arguments\ninstead of instance arguments. -/\nprotected theorem ind\u2082' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {p : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Prop} (h : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2), p (quotient.mk' a\u2081) (quotient.mk' a\u2082)) (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) : p q\u2081 q\u2082 :=\n  quotient.ind\u2082 h q\u2081 q\u2082\n\n/-- A version of `quotient.induction_on` taking `{s : setoid \u03b1}` as an implicit argument instead\nof an instance argument. -/\nprotected theorem induction_on' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {p : quotient s\u2081 \u2192 Prop} (q : quotient s\u2081) (h : \u2200 (a : \u03b1), p (quotient.mk' a)) : p q :=\n  quotient.induction_on q h\n\n/-- A version of `quotient.induction_on\u2082` taking `{s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2}` as implicit\narguments instead of instance arguments. -/\nprotected theorem induction_on\u2082' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {p : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Prop} (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (h : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2), p (quotient.mk' a\u2081) (quotient.mk' a\u2082)) : p q\u2081 q\u2082 :=\n  quotient.induction_on\u2082 q\u2081 q\u2082 h\n\n/-- A version of `quotient.induction_on\u2083` taking `{s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {s\u2083 : setoid \u03b3}`\nas implicit arguments instead of instance arguments. -/\nprotected theorem induction_on\u2083' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {s\u2083 : setoid \u03b3} {p : quotient s\u2081 \u2192 quotient s\u2082 \u2192 quotient s\u2083 \u2192 Prop} (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (q\u2083 : quotient s\u2083) (h : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2) (a\u2083 : \u03b3), p (quotient.mk' a\u2081) (quotient.mk' a\u2082) (quotient.mk' a\u2083)) : p q\u2081 q\u2082 q\u2083 :=\n  quotient.induction_on\u2083 q\u2081 q\u2082 q\u2083 h\n\n/-- Recursion on a `quotient` argument `a`, result type depends on `\u27e6a\u27e7`. -/\nprotected def hrec_on' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {\u03c6 : quotient s\u2081 \u2192 Sort u_2} (qa : quotient s\u2081) (f : (a : \u03b1) \u2192 \u03c6 (quotient.mk' a)) (c : \u2200 (a\u2081 a\u2082 : \u03b1), a\u2081 \u2248 a\u2082 \u2192 f a\u2081 == f a\u2082) : \u03c6 qa :=\n  quot.hrec_on qa f c\n\n@[simp] theorem hrec_on'_mk' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {\u03c6 : quotient s\u2081 \u2192 Sort u_2} (f : (a : \u03b1) \u2192 \u03c6 (quotient.mk' a)) (c : \u2200 (a\u2081 a\u2082 : \u03b1), a\u2081 \u2248 a\u2082 \u2192 f a\u2081 == f a\u2082) (x : \u03b1) : 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 `\u27e6a\u27e7` and `\u27e6b\u27e7`. -/\nprotected def hrec_on\u2082' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {\u03c6 : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Sort u_3} (qa : quotient s\u2081) (qb : quotient s\u2082) (f : (a : \u03b1) \u2192 (b : \u03b2) \u2192 \u03c6 (quotient.mk' a) (quotient.mk' b)) (c : \u2200 (a\u2081 : \u03b1) (b\u2081 : \u03b2) (a\u2082 : \u03b1) (b\u2082 : \u03b2), a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 == f a\u2082 b\u2082) : \u03c6 qa qb :=\n  quotient.hrec_on\u2082 qa qb f c\n\n@[simp] theorem hrec_on\u2082'_mk' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {\u03c6 : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Sort u_3} (f : (a : \u03b1) \u2192 (b : \u03b2) \u2192 \u03c6 (quotient.mk' a) (quotient.mk' b)) (c : \u2200 (a\u2081 : \u03b1) (b\u2081 : \u03b2) (a\u2082 : \u03b1) (b\u2082 : \u03b2), a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 == f a\u2082 b\u2082) (x : \u03b1) (qb : quotient s\u2082) : quotient.hrec_on\u2082' (quotient.mk' x) qb f c = quotient.hrec_on' qb (f x) fun (b\u2081 b\u2082 : \u03b2) => c x b\u2081 x b\u2082 (setoid.refl x) :=\n  rfl\n\n/-- Map a function `f : \u03b1 \u2192 \u03b2` that sends equivalent elements to equivalent elements\nto a function `quotient sa \u2192 quotient sb`. Useful to define unary operations on quotients. -/\nprotected def map' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} (f : \u03b1 \u2192 \u03b2) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) : quotient s\u2081 \u2192 quotient s\u2082 :=\n  quot.map f h\n\n@[simp] theorem map'_mk' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} (f : \u03b1 \u2192 \u03b2) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) (x : \u03b1) : quotient.map' f h (quotient.mk' x) = quotient.mk' (f x) :=\n  rfl\n\n/-- A version of `quotient.map\u2082` using curly braces and unification. -/\nprotected def map\u2082' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {s\u2083 : setoid \u03b3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv \u21d2 has_equiv.equiv) f f) : quotient s\u2081 \u2192 quotient s\u2082 \u2192 quotient s\u2083 :=\n  quotient.map\u2082 f h\n\n@[simp] theorem map\u2082'_mk' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {s\u2081 : setoid \u03b1} {s\u2082 : setoid \u03b2} {s\u2083 : setoid \u03b3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv \u21d2 has_equiv.equiv) f f) (x : \u03b1) : quotient.map\u2082' f h (quotient.mk' x) = quotient.map' (f x) (h (setoid.refl x)) :=\n  rfl\n\ntheorem exact' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {a : \u03b1} {b : \u03b1} : quotient.mk' a = quotient.mk' b \u2192 setoid.r a b :=\n  exact\n\ntheorem sound' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {a : \u03b1} {b : \u03b1} : setoid.r a b \u2192 quotient.mk' a = quotient.mk' b :=\n  sound\n\n@[simp] protected theorem eq' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} {a : \u03b1} {b : \u03b1} : quotient.mk' a = quotient.mk' b \u2194 setoid.r a b :=\n  eq\n\n/-- A version of `quotient.out` taking `{s\u2081 : setoid \u03b1}` as an implicit argument instead of an\ninstance argument. -/\ndef out' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} (a : quotient s\u2081) : \u03b1 :=\n  out a\n\n@[simp] theorem out_eq' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} (q : quotient s\u2081) : quotient.mk' (out' q) = q :=\n  out_eq q\n\ntheorem mk_out' {\u03b1 : Sort u_1} {s\u2081 : setoid \u03b1} (a : \u03b1) : 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 \u21aa 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 \u2192 B)\n(injective' : function.injective to_fun)\n(map_op' : \u2200 {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' := \u03bb 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) (\u03bb _, A \u2192 B) := \u27e8my_embedding.to_fun\u27e9\n\n@[simp] lemma to_fun_eq_coe {f : my_embedding A B} : f.to_fun = (f : A \u2192 B) := rfl\n\n@[ext] theorem ext {f g : my_embedding A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : my_embedding A B :=\n{ to_fun := f',\n  injective' := h.symm \u25b8 f.injective',\n  map_op' := h.symm \u25b8 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 : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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\u2093'. -/\n/-- The class `embedding_like F \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to injective functions `\u03b1 \u21aa \u03b2`.\n-/\nclass EmbeddingLike (F : Sort _) (\u03b1 \u03b2 : outParam (Sort _)) extends FunLike F \u03b1 fun _ => \u03b2 where\n  injective' : \u2200 f : F, @Function.Injective \u03b1 \u03b2 (coe f)\n#align embedding_like EmbeddingLike\n\nnamespace EmbeddingLike\n\nvariable {F \u03b1 \u03b2 \u03b3 : Sort _} [i : EmbeddingLike F \u03b1 \u03b2]\n\ninclude i\n\n/- warning: embedding_like.injective -> EmbeddingLike.injective is a dubious translation:\nlean 3 declaration is\n  forall {F : Sort.{u1}} {\u03b1 : Sort.{u2}} {\u03b2 : Sort.{u3}} [i : EmbeddingLike.{u1, u2, u3} F \u03b1 \u03b2] (f : F), Function.Injective.{u2, u3} \u03b1 \u03b2 (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) (EmbeddingLike.toFunLike.{u1, u2, u3} F \u03b1 \u03b2 i)) f)\nbut is expected to have type\n  forall {F : Sort.{u1}} {\u03b1 : Sort.{u3}} {\u03b2 : Sort.{u2}} [i : EmbeddingLike.{u1, u3, u2} F \u03b1 \u03b2] (f : F), Function.Injective.{u3, u2} \u03b1 \u03b2 (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : \u03b1) => \u03b2) _x) (EmbeddingLike.toFunLike.{u1, u3, u2} F \u03b1 \u03b2 i) f)\nCase conversion may be inaccurate. Consider using '#align embedding_like.injective EmbeddingLike.injective\u2093'. -/\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}} {\u03b1 : Sort.{u2}} {\u03b2 : Sort.{u3}} [i : EmbeddingLike.{u1, u2, u3} F \u03b1 \u03b2] (f : F) {x : \u03b1} {y : \u03b1}, Iff (Eq.{u3} \u03b2 (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) (EmbeddingLike.toFunLike.{u1, u2, u3} F \u03b1 \u03b2 i)) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) (EmbeddingLike.toFunLike.{u1, u2, u3} F \u03b1 \u03b2 i)) f y)) (Eq.{u2} \u03b1 x y)\nbut is expected to have type\n  forall {F : Sort.{u2}} {\u03b1 : Sort.{u1}} {\u03b2 : Sort.{u3}} [i : EmbeddingLike.{u2, u1, u3} F \u03b1 \u03b2] (f : F) {x : \u03b1} {y : \u03b1}, Iff (Eq.{u3} ((fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : \u03b1) => \u03b2) x) (FunLike.coe.{u2, u1, u3} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : \u03b1) => \u03b2) _x) (EmbeddingLike.toFunLike.{u2, u1, u3} F \u03b1 \u03b2 i) f x) (FunLike.coe.{u2, u1, u3} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : \u03b1) => \u03b2) _x) (EmbeddingLike.toFunLike.{u2, u1, u3} F \u03b1 \u03b2 i) f y)) (Eq.{u1} \u03b1 x y)\nCase conversion may be inaccurate. Consider using '#align embedding_like.apply_eq_iff_eq EmbeddingLike.apply_eq_iff_eq\u2093'. -/\n@[simp]\ntheorem apply_eq_iff_eq (f : F) {x y : \u03b1} : f x = f y \u2194 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 {\u03b1 : Sort.{u1}} {\u03b2 : Sort.{u2}} {\u03b3 : Sort.{u3}} {F : Sort.{u4}} [_inst_1 : EmbeddingLike.{u4, u2, u3} F \u03b2 \u03b3] (f : \u03b1 -> \u03b2) (e : F), Iff (Function.Injective.{u1, u3} \u03b1 \u03b3 (Function.comp.{u1, u2, u3} \u03b1 \u03b2 \u03b3 (coeFn.{u4, imax u2 u3} F (fun (_x : F) => \u03b2 -> \u03b3) (FunLike.hasCoeToFun.{u4, u2, u3} F \u03b2 (fun (_x : \u03b2) => \u03b3) (EmbeddingLike.toFunLike.{u4, u2, u3} F \u03b2 \u03b3 _inst_1)) e) f)) (Function.Injective.{u1, u2} \u03b1 \u03b2 f)\nbut is expected to have type\n  forall {\u03b1 : Sort.{u1}} {\u03b2 : Sort.{u3}} {\u03b3 : Sort.{u2}} {F : Sort.{u4}} [_inst_1 : EmbeddingLike.{u4, u3, u2} F \u03b2 \u03b3] (f : \u03b1 -> \u03b2) (e : F), Iff (Function.Injective.{u1, u2} \u03b1 \u03b3 (Function.comp.{u1, u3, u2} \u03b1 \u03b2 \u03b3 (FunLike.coe.{u4, u3, u2} F \u03b2 (fun (_x : \u03b2) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : \u03b2) => \u03b3) _x) (EmbeddingLike.toFunLike.{u4, u3, u2} F \u03b2 \u03b3 _inst_1) e) f)) (Function.Injective.{u1, u3} \u03b1 \u03b2 f)\nCase conversion may be inaccurate. Consider using '#align embedding_like.comp_injective EmbeddingLike.comp_injective\u2093'. -/\n@[simp]\ntheorem comp_injective {F : Sort _} [EmbeddingLike F \u03b2 \u03b3] (f : \u03b1 \u2192 \u03b2) (e : F) :\n    Function.Injective (e \u2218 f) \u2194 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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {\u03b4 : Type z}\n\nopen nat\n\nnamespace list\n\n/- zip & unzip -/\n\n@[simp] theorem zip_with_cons_cons (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (a : \u03b1) (b : \u03b2) (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) :\n  zip_with f (a :: l\u2081) (b :: l\u2082) = f a b :: zip_with f l\u2081 l\u2082 := rfl\n\n@[simp] theorem zip_cons_cons (a : \u03b1) (b : \u03b2) (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) :\n  zip (a :: l\u2081) (b :: l\u2082) = (a, b) :: zip l\u2081 l\u2082 := rfl\n\n@[simp] theorem zip_with_nil_left (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l) : zip_with f [] l = [] := rfl\n\n@[simp] theorem zip_with_nil_right (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l)  : zip_with f l [] = [] :=\nby cases l; refl\n\n@[simp] lemma zip_with_eq_nil_iff {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {l l'} :\n  zip_with f l l' = [] \u2194 l = [] \u2228 l' = [] :=\nby { cases l; cases l'; simp }\n\n@[simp] theorem zip_nil_left (l : list \u03b1) : zip ([] : list \u03b2) l = [] := rfl\n\n@[simp] theorem zip_nil_right (l : list \u03b1) : zip l ([] : list \u03b2) = [] :=\nzip_with_nil_right _ l\n\n@[simp] theorem zip_swap : \u2200 (l\u2081 : list \u03b1) (l\u2082 : list \u03b2),\n  (zip l\u2081 l\u2082).map prod.swap = zip l\u2082 l\u2081\n| []      l\u2082      := (zip_nil_right _).symm\n| l\u2081      []      := by rw zip_nil_right; refl\n| (a::l\u2081) (b::l\u2082) := by simp only [zip_cons_cons, map_cons, zip_swap l\u2081 l\u2082, prod.swap_prod_mk];\n    split; refl\n\n@[simp] theorem length_zip_with (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : \u2200  (l\u2081 : list \u03b1) (l\u2082 : list \u03b2),\n   length (zip_with f l\u2081 l\u2082) = min (length l\u2081) (length l\u2082)\n| []      l\u2082      := rfl\n| l\u2081      []      := by simp only [length, min_zero, zip_with_nil_right]\n| (a::l\u2081) (b::l\u2082) := by by simp [length, zip_cons_cons, length_zip_with l\u2081 l\u2082, min_add_add_right]\n\n@[simp] theorem length_zip : \u2200 (l\u2081 : list \u03b1) (l\u2082 : list \u03b2),\n   length (zip l\u2081 l\u2082) = min (length l\u2081) (length l\u2082) :=\nlength_zip_with _\n\nlemma lt_length_left_of_zip_with {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {i : \u2115} {l : list \u03b1} {l' : list \u03b2}\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 : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {i : \u2115} {l : list \u03b1} {l' : list \u03b2}\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 : \u2115} {l : list \u03b1} {l' : list \u03b2} (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 : \u2115} {l : list \u03b1} {l' : list \u03b2} (h : i < (zip l l').length) :\n  i < l'.length :=\nlt_length_right_of_zip_with h\n\ntheorem zip_append : \u2200 {l\u2081 r\u2081 : list \u03b1} {l\u2082 r\u2082 : list \u03b2} (h : length l\u2081 = length l\u2082),\n   zip (l\u2081 ++ r\u2081) (l\u2082 ++ r\u2082) = zip l\u2081 l\u2082 ++ zip r\u2081 r\u2082\n| []      r\u2081 l\u2082      r\u2082 h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl\n| l\u2081      r\u2081 []      r\u2082 h := by simp only [eq_nil_of_length_eq_zero h]; refl\n| (a::l\u2081) r\u2081 (b::l\u2082) r\u2082 h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)];\n    split; refl\n\ntheorem zip_map (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) : \u2200 (l\u2081 : list \u03b1) (l\u2082 : list \u03b2),\n   zip (l\u2081.map f) (l\u2082.map g) = (zip l\u2081 l\u2082).map (prod.map f g)\n| []      l\u2082      := rfl\n| l\u2081      []      := by simp only [map, zip_nil_right]\n| (a::l\u2081) (b::l\u2082) := by simp only [map, zip_cons_cons, zip_map l\u2081 l\u2082, prod.map]; split; refl\n\ntheorem zip_map_left (f : \u03b1 \u2192 \u03b3) (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) :\n   zip (l\u2081.map f) l\u2082 = (zip l\u2081 l\u2082).map (prod.map f id) :=\nby rw [\u2190 zip_map, map_id]\n\ntheorem zip_map_right (f : \u03b2 \u2192 \u03b3) (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) :\n   zip l\u2081 (l\u2082.map f) = (zip l\u2081 l\u2082).map (prod.map id f) :=\nby rw [\u2190 zip_map, map_id]\n\n@[simp] lemma zip_with_map {\u03bc}\n  (f : \u03b3 \u2192 \u03b4 \u2192 \u03bc) (g : \u03b1 \u2192 \u03b3) (h : \u03b2 \u2192 \u03b4) (as : list \u03b1) (bs : list \u03b2) :\n  zip_with f (as.map g) (bs.map h) =\n  zip_with (\u03bb 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (g : \u03b4 \u2192 \u03b1) (l : list \u03b4) (l' : list \u03b2) :\n  zip_with f (l.map g) l' = zip_with (f \u2218 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l : list \u03b1) (g : \u03b4 \u2192 \u03b2) (l' : list \u03b4) :\n  zip_with f l (l'.map g) = zip_with (\u03bb x, f x \u2218 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 : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) : \u2200 (l : list \u03b1),\n   zip (l.map f) (l.map g) = l.map (\u03bb 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 {\u03b4 : Type*} (f : \u03b1 \u2192 \u03b2) (g : \u03b3 \u2192 \u03b4 \u2192 \u03b1) (l : list \u03b3) (l' : list \u03b4) :\n  map f (zip_with g l l') = zip_with (\u03bb 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} : \u2200 {l\u2081 : list \u03b1} {l\u2082 : list \u03b2},\n   (a, b) \u2208 zip l\u2081 l\u2082 \u2192 a \u2208 l\u2081 \u2227 b \u2208 l\u2082\n| (_::l\u2081) (_::l\u2082) (or.inl rfl) := \u27e8or.inl rfl, or.inl rfl\u27e9\n| (a'::l\u2081) (b'::l\u2082) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h]\n\ntheorem map_fst_zip : \u2200 (l\u2081 : list \u03b1) (l\u2082 : list \u03b2),\n  l\u2081.length \u2264 l\u2082.length \u2192\n  map prod.fst (zip l\u2081 l\u2082) = l\u2081\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 : \u2200 (l\u2081 : list \u03b1) (l\u2082 : list \u03b2),\n  l\u2082.length \u2264 l\u2081.length \u2192\n  map prod.snd (zip l\u2081 l\u2082) = l\u2082\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 (\u03b1 \u00d7 \u03b2)) = ([], []) := rfl\n\n@[simp] theorem unzip_cons (a : \u03b1) (b : \u03b2) (l : list (\u03b1 \u00d7 \u03b2)) :\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 : \u2200 (l : list (\u03b1 \u00d7 \u03b2)), 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 (\u03b1 \u00d7 \u03b2)) : (unzip l).1 = l.map prod.fst :=\nby simp only [unzip_eq_map]\n\ntheorem unzip_right (l : list (\u03b1 \u00d7 \u03b2)) : (unzip l).2 = l.map prod.snd :=\nby simp only [unzip_eq_map]\n\ntheorem unzip_swap (l : list (\u03b1 \u00d7 \u03b2)) : unzip (l.map prod.swap) = (unzip l).swap :=\nby simp only [unzip_eq_map, map_map]; split; refl\n\ntheorem zip_unzip : \u2200 (l : list (\u03b1 \u00d7 \u03b2)), 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 : \u2200 {l\u2081 : list \u03b1} {l\u2082 : list \u03b2}, length l\u2081 \u2264 length l\u2082 \u2192\n  (unzip (zip l\u2081 l\u2082)).1 = l\u2081\n| []      l\u2082      h := rfl\n| l\u2081      []      h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl\n| (a::l\u2081) (b::l\u2082) 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\u2081 : list \u03b1} {l\u2082 : list \u03b2} (h : length l\u2082 \u2264 length l\u2081) :\n  (unzip (zip l\u2081 l\u2082)).2 = l\u2082 :=\nby rw [\u2190 zip_swap, unzip_swap]; exact unzip_zip_left h\n\ntheorem unzip_zip {l\u2081 : list \u03b1} {l\u2082 : list \u03b2} (h : length l\u2081 = length l\u2082) :\n  unzip (zip l\u2081 l\u2082) = (l\u2081, l\u2082) :=\nby rw [\u2190 @prod.mk.eta _ _ (unzip (zip l\u2081 l\u2082)),\n  unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)]\n\nlemma zip_of_prod {l : list \u03b1} {l' : list \u03b2} {lp : list (\u03b1 \u00d7 \u03b2)}\n  (hl : lp.map prod.fst = l) (hr : lp.map prod.snd = l') :\n  lp = l.zip l' :=\nby rw [\u2190hl, \u2190hr, \u2190zip_unzip lp, \u2190unzip_left, \u2190unzip_right, zip_unzip, zip_unzip]\n\nlemma map_prod_left_eq_zip {l : list \u03b1} (f : \u03b1 \u2192 \u03b2) : l.map (\u03bb x, (x, f x)) = l.zip (l.map f) :=\nby { rw \u2190zip_map', congr, exact map_id _ }\n\n\n\nlemma zip_with_comm (f : \u03b1 \u2192 \u03b1 \u2192 \u03b2) (comm : \u2200 (x y : \u03b1), f x y = f y x)\n  (l l' : list \u03b1) :\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 : \u03b1 \u2192 \u03b1 \u2192 \u03b2) [is_symm_op \u03b1 \u03b2 f] : is_symm_op (list \u03b1) (list \u03b2) (zip_with f) :=\n\u27e8zip_with_comm f is_symm_op.symm_op\u27e9\n\n@[simp] theorem length_revzip (l : list \u03b1) : length (revzip l) = length l :=\nby simp only [revzip, length_zip, length_reverse, min_self]\n\n@[simp] theorem unzip_revzip (l : list \u03b1) : (revzip l).unzip = (l, l.reverse) :=\nunzip_zip (length_reverse l).symm\n\n@[simp] theorem revzip_map_fst (l : list \u03b1) : (revzip l).map prod.fst = l :=\nby rw [\u2190 unzip_left, unzip_revzip]\n\n@[simp] theorem revzip_map_snd (l : list \u03b1) : (revzip l).map prod.snd = l.reverse :=\nby rw [\u2190 unzip_right, unzip_revzip]\n\ntheorem reverse_revzip (l : list \u03b1) : reverse l.revzip = revzip l.reverse :=\nby rw [\u2190 zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip]\n\ntheorem revzip_swap (l : list \u03b1) : (revzip l).map prod.swap = revzip l.reverse :=\nby simp [revzip]\n\nlemma nth_zip_with (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) (i : \u2115) :\n  (zip_with f l\u2081 l\u2082).nth i = ((l\u2081.nth i).map f).bind (\u03bb g, (l\u2082.nth i).map g) :=\nbegin\n  induction l\u2081 generalizing l\u2082 i,\n  { simp [zip_with, (<*>)] },\n  { cases l\u2082; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'],\n    { cases ((l\u2081_hd :: l\u2081_tl).nth i); refl },\n    { cases i; simp only [option.map_some', nth, option.some_bind', *] } }\nend\n\nlemma nth_zip_with_eq_some {\u03b1 \u03b2 \u03b3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) (z : \u03b3) (i : \u2115) :\n  (zip_with f l\u2081 l\u2082).nth i = some z \u2194 \u2203 x y, l\u2081.nth i = some x \u2227 l\u2082.nth i = some y \u2227 f x y = z :=\nbegin\n  induction l\u2081 generalizing l\u2082 i,\n  { simp [zip_with] },\n  { cases l\u2082; simp only [zip_with, nth, exists_false, and_false, false_and],\n    cases i; simp *, },\nend\n\nlemma nth_zip_eq_some (l\u2081 : list \u03b1) (l\u2082 : list \u03b2) (z : \u03b1 \u00d7 \u03b2) (i : \u2115) :\n  (zip l\u2081 l\u2082).nth i = some z \u2194 l\u2081.nth i = some z.1 \u2227 l\u2082.nth i = some z.2 :=\nbegin\n  cases z,\n  rw [zip, nth_zip_with_eq_some], split,\n  { rintro \u27e8x, y, h\u2080, h\u2081, h\u2082\u27e9, cc },\n  { rintro \u27e8h\u2080, h\u2081\u27e9, exact \u27e8_,_,h\u2080,h\u2081,rfl\u27e9 }\nend\n\n@[simp] lemma nth_le_zip_with {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {l : list \u03b1} {l' : list \u03b2} {i : \u2115}\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 [\u2190option.some_inj, \u2190nth_le_nth, nth_zip_with_eq_some],\n  refine \u27e8l.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 _, _\u27e9,\n  simp only [\u2190nth_le_nth, eq_self_iff_true, and_self]\nend\n\n@[simp] lemma nth_le_zip {l : list \u03b1} {l' : list \u03b2} {i : \u2115} {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 \u03b1} {init tail : list \u03b1} :\n  (init, tail) \u2208 zip l.inits l.tails \u2194 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 (\u27e8rfl, rfl\u27e9 | \u27e8_, _, h, rfl, rfl\u27e9),\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 : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l : list \u03b1) (l' : list \u03b2) :\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 {\u03b3 : Type*} [semiring \u03b3]\n  (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (n : \u03b3) (l : list \u03b1) (l' : list \u03b2) :\n  (l.zip_with (\u03bb 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l : list \u03b1) (l' : list \u03b2) (n : \u2115)\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 [\u2190drop_one, zip_with_distrib_drop]\n\nlemma zip_with_append (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l la : list \u03b1) (l' lb : list \u03b2) (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) \u00d7 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 : \u2200 {\u03b1 : Sort u} {a : \u03b1}, 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) \u00d7 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) \u2190 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 (\u03bb h, i_to_expr_for_apply h),\n  l \u2190 attr.mmap $ \u03bb a, attribute.get_instances a,\n  let l := l.join,\n  let m := l.map (\u03bb h, mk_const h),\n  -- In order to remove the expressions we need to evaluate the thunks.\n  hs \u2190 (hs ++ m).mfilter $ \u03bb h, (do h \u2190 h, return $ expr.const_name h \u2209 gex),\n  let hs := if no_dflt then hs else\n    ([`rfl, `trivial, `congr_fun, `congr_arg].map (\u03bb n, (mk_const n))) ++ hs,\n  let locals : tactic (list expr) := if \u00ac no_dflt \u2228 all_hyps then do\n    ctx \u2190 local_context,\n    -- Remove local exceptions specified in `hex`:\n    return $ ctx.filter (\u03bb h : expr, h.local_uniq_name \u2209 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 \u2190 hs.mmap (\u03bb h : tactic expr, do\n    e \u2190 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 \u2192 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 := \u03bb _, 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 \u2192 tactic unit := \u03bb _, skip)\n(pre_apply : tactic unit := skip)\n(discharger : tactic unit := failed)\n(max_depth : \u2115 := 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 : \u2115) (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 : \u2115) (e : expr) : tactic unit :=\ndo\n  pp \u2190 pp e,\n  solve_by_elim_trace n (format!\"\u2705 `{pp}` solves `\u22a2 {g}`\")\n\n/-- A helper function to generate trace messages on unsuccessful applications. -/\nmeta def on_failure (g : format) (n : \u2115) : tactic unit :=\nsolve_by_elim_trace n (format!\"\u274c failed to solve `\u22a2 {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 : \u2115) : tactic ((expr \u2192 tactic unit) \u00d7 tactic unit) :=\nif is_trace_enabled_for `solve_by_elim then\n  do\n    g \u2190 target >>= pp,\n    return (on_success g n, on_failure g n)\nelse\n  return (\u03bb _, 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  \u2115 \u2192 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 \"\ud83d\uded1 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) \u2190 trace_hooks (opt.max_depth - n),\n    ctx_lemmas \u2190 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 (\u03bb 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) \u00d7 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) \u2190 opt.get_lemma_thunks,\n  (if opt.backtrack_all_goals then id else focus1) $ (do\n    gs \u2190 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 `... \u2192 \u2200 _, ... \u2192 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 \u2192 \u00ac 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 \u2190 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\u2081, h\u2082, ..., h\u1d63]` also applies the named lemmas.\n* `solve_by_elim with attr\u2081 ... attr\u1d63` also applies all lemmas tagged with the specified attributes.\n* `solve_by_elim only [h\u2081, h\u2082, ..., h\u1d63]` 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 \u2192 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) \u2190 mk_assumption_set no_dflt hs attr_names,\n   tactic.solve_by_elim\n   { backtrack_all_goals := all_goals.is_some \u2228 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 \u2228 q) : q \u2228 p := by\n  cases h with\n  | inl hp => exact Or.inr hp\n  | inr hq => exact Or.inl hq\n\nexample (h : p \u2228 q) : q \u2228 p := by\n  cases' h with hp hq\n  \u00b7 exact Or.inr hp\n  \u00b7 exact Or.inl hq\n\nexample (h : p \u2228 q) : q \u2228 p := by\n  rcases h with hp | hq\n  \u00b7 exact Or.inr hp\n  \u00b7 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 \u2190 getAltNumFields elimInfo altName\n    let (altVarNames, names') := names.splitAtD numFields (Unhygienic.run `(_))\n    names := names'\n    let (fvars, g) \u2190 g.introN numFields <| altVarNames.map (getNameOfIdent' \u00b7[0])\n    let some (g, subst) \u2190 Cases.unifyEqs? numEqs g {} | pure ()\n    let (_, g) \u2190 g.introNP numGeneralized\n    let g \u2190 liftM $ toClear.foldlM (\u00b7.tryClear) g\n    for fvar in fvars, stx in altVarNames do\n      g.withContext <| (subst.apply <| .fvar fvar).addLocalVarInfoForBinderIdent \u27e8stx\u27e9\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 \u2190 elabCasesTargets tgts.1.getSepArgs\n  let g :: gs \u2190 getUnsolvedGoals | throwNoGoalsToBeSolved\n  g.withContext do\n    let elimInfo \u2190 getElimNameInfo usingArg targets (induction := true)\n    let targets \u2190 addImplicitTargets elimInfo targets\n    evalInduction.checkTargets targets\n    let targetFVarIds := targets.map (\u00b7.fvarId!)\n    g.withContext do\n      let genArgs \u2190 if genArg.1.isNone then pure #[] else getFVarIds genArg.1[1].getArgs\n      let forbidden \u2190 mkGeneralizationForbiddenSet targets\n      let mut s \u2190 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) \u2190 g.revert (\u2190 sortFVarIds s.toArray)\n      let result \u2190 withRef tgts <| ElimApp.mkElimApp elimInfo targets (\u2190 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 \u2190 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 \u2190 elabCasesTargets tgts.1.getSepArgs\n  let g :: gs \u2190 getUnsolvedGoals | throwNoGoalsToBeSolved\n  g.withContext do\n    let elimInfo \u2190 getElimNameInfo usingArg targets (induction := false)\n    let targets \u2190 addImplicitTargets elimInfo targets\n    let result \u2190 withRef tgts <| ElimApp.mkElimApp elimInfo targets (\u2190 g.getTag)\n    let elimArgs := result.elimApp.getAppArgs\n    let targets \u2190 elimInfo.targetsPos.mapM (instantiateMVars elimArgs[\u00b7]!)\n    let motive := elimArgs[elimInfo.motivePos]!\n    let g \u2190 generalizeTargetsEq g (\u2190 inferType motive) targets\n    let (targetsNew, g) \u2190 g.introN targets.size\n    g.withContext do\n      ElimApp.setMotiveArg g motive.mvarId! targetsNew\n      g.assign result.elimApp\n      let subgoals \u2190 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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl, 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/-- `\u03b1 \u21aa \u03b2` is a bundled injective function. -/\nstructure embedding (\u03b1 : Sort u_1) (\u03b2 : Sort u_2) where\n  to_fun : \u03b1 \u2192 \u03b2\n  inj' : injective to_fun\n\ninfixr:25 \" \u21aa \" => Mathlib.function.embedding\n\nprotected instance embedding.has_coe_to_fun {\u03b1 : Sort u} {\u03b2 : Sort v} : has_coe_to_fun (\u03b1 \u21aa \u03b2) :=\n  has_coe_to_fun.mk (fun (x : \u03b1 \u21aa \u03b2) => \u03b1 \u2192 \u03b2) embedding.to_fun\n\nend function\n\n\n/-- Convert an `\u03b1 \u2243 \u03b2` to `\u03b1 \u21aa \u03b2`. -/\n@[simp] theorem equiv.to_embedding_apply {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2243 \u03b2) :\n    \u2200 (\u1fb0 : \u03b1), coe_fn (equiv.to_embedding f) \u1fb0 = coe_fn f \u1fb0 :=\n  fun (\u1fb0 : \u03b1) => Eq.refl (coe_fn (equiv.to_embedding f) \u1fb0)\n\nnamespace function\n\n\nnamespace embedding\n\n\ntheorem ext {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u21aa \u03b2} {g : \u03b1 \u21aa \u03b2}\n    (h : \u2200 (x : \u03b1), coe_fn f x = coe_fn g x) : f = g :=\n  sorry\n\ntheorem ext_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u21aa \u03b2} {g : \u03b1 \u21aa \u03b2} :\n    (\u2200 (x : \u03b1), coe_fn f x = coe_fn g x) \u2194 f = g :=\n  sorry\n\n@[simp] theorem to_fun_eq_coe {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) : to_fun f = \u21d1f := rfl\n\n@[simp] theorem coe_fn_mk {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (i : injective f) :\n    \u21d1(mk f i) = f :=\n  rfl\n\ntheorem injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) : injective \u21d1f := inj' f\n\n@[simp] theorem refl_apply (\u03b1 : Sort u_1) (a : \u03b1) : coe_fn (embedding.refl \u03b1) a = a := Eq.refl a\n\n@[simp] theorem trans_apply {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u21aa \u03b2) (g : \u03b2 \u21aa \u03b3) :\n    \u2200 (\u1fb0 : \u03b1), coe_fn (embedding.trans f g) \u1fb0 = coe_fn g (coe_fn f \u1fb0) :=\n  fun (\u1fb0 : \u03b1) => Eq.refl (coe_fn g (coe_fn f \u1fb0))\n\n@[simp] theorem equiv_to_embedding_trans_symm_to_embedding {\u03b1 : Sort u_1} {\u03b2 : Sort u_2}\n    (e : \u03b1 \u2243 \u03b2) :\n    embedding.trans (equiv.to_embedding e) (equiv.to_embedding (equiv.symm e)) = embedding.refl \u03b1 :=\n  sorry\n\n@[simp] theorem equiv_symm_to_embedding_trans_to_embedding {\u03b1 : Sort u_1} {\u03b2 : Sort u_2}\n    (e : \u03b1 \u2243 \u03b2) :\n    embedding.trans (equiv.to_embedding (equiv.symm e)) (equiv.to_embedding e) = embedding.refl \u03b2 :=\n  sorry\n\nprotected def congr {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b3 : Sort w} {\u03b4 : Sort x} (e\u2081 : \u03b1 \u2243 \u03b2) (e\u2082 : \u03b3 \u2243 \u03b4)\n    (f : \u03b1 \u21aa \u03b3) : \u03b2 \u21aa \u03b4 :=\n  embedding.trans (equiv.to_embedding (equiv.symm e\u2081)) (embedding.trans f (equiv.to_embedding e\u2082))\n\n/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/\nprotected def of_surjective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b2 \u2192 \u03b1) (hf : surjective f) : \u03b1 \u21aa \u03b2 :=\n  mk (surj_inv hf) (injective_surj_inv hf)\n\n/-- Convert a surjective `embedding` to an `equiv` -/\nprotected def equiv_of_surjective {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (f : \u03b1 \u21aa \u03b2) (hf : surjective \u21d1f) :\n    \u03b1 \u2243 \u03b2 :=\n  equiv.of_bijective \u21d1f sorry\n\nprotected def of_not_nonempty {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (h\u03b1 : \u00acNonempty \u03b1) : \u03b1 \u21aa \u03b2 :=\n  mk (fun (a : \u03b1) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) (a : \u03b1) (b : \u03b2)\n    [(a' : \u03b1) \u2192 Decidable (a' = a)] [(a' : \u03b1) \u2192 Decidable (coe_fn f a' = b)] : \u03b1 \u21aa \u03b2 :=\n  mk (fun (a' : \u03b1) => ite (a' = a) b (ite (coe_fn f a' = b) (coe_fn f a) (coe_fn f a'))) sorry\n\ntheorem set_value_eq {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) (a : \u03b1) (b : \u03b2)\n    [(a' : \u03b1) \u2192 Decidable (a' = a)] [(a' : \u03b1) \u2192 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 {\u03b1 : Type u_1} : \u03b1 \u21aa Option \u03b1 := mk some (option.some_injective \u03b1)\n\n/-- Embedding of a `subtype`. -/\ndef subtype {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : Subtype p \u21aa \u03b1 := mk coe sorry\n\n@[simp] theorem coe_subtype {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : \u21d1(subtype p) = coe := rfl\n\n/-- Choosing an element `b : \u03b2` gives an embedding of `punit` into `\u03b2`. -/\ndef punit {\u03b2 : Sort u_1} (b : \u03b2) : PUnit \u21aa \u03b2 := mk (fun (_x : PUnit) => b) sorry\n\n/-- Fixing an element `b : \u03b2` gives an embedding `\u03b1 \u21aa \u03b1 \u00d7 \u03b2`. -/\ndef sectl (\u03b1 : Type u_1) {\u03b2 : Type u_2} (b : \u03b2) : \u03b1 \u21aa \u03b1 \u00d7 \u03b2 := mk (fun (a : \u03b1) => (a, b)) sorry\n\n/-- Fixing an element `a : \u03b1` gives an embedding `\u03b2 \u21aa \u03b1 \u00d7 \u03b2`. -/\ndef sectr {\u03b1 : Type u_1} (a : \u03b1) (\u03b2 : Type u_2) : \u03b2 \u21aa \u03b1 \u00d7 \u03b2 := mk (fun (b : \u03b2) => (a, b)) sorry\n\n/-- Restrict the codomain of an embedding. -/\ndef cod_restrict {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (p : set \u03b2) (f : \u03b1 \u21aa \u03b2)\n    (H : \u2200 (a : \u03b1), coe_fn f a \u2208 p) : \u03b1 \u21aa \u21a5p :=\n  mk (fun (a : \u03b1) => { val := coe_fn f a, property := H a }) sorry\n\n@[simp] theorem cod_restrict_apply {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (p : set \u03b2) (f : \u03b1 \u21aa \u03b2)\n    (H : \u2200 (a : \u03b1), coe_fn f a \u2208 p) (a : \u03b1) :\n    coe_fn (cod_restrict p f H) a = { val := coe_fn f a, property := H a } :=\n  rfl\n\n/-- If `e\u2081` and `e\u2082` are embeddings, then so is `prod.map e\u2081 e\u2082 : (a, b) \u21a6 (e\u2081 a, e\u2082 b)`. -/\ndef prod_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) :\n    \u03b1 \u00d7 \u03b3 \u21aa \u03b2 \u00d7 \u03b4 :=\n  mk (prod.map \u21d1e\u2081 \u21d1e\u2082) sorry\n\n@[simp] theorem coe_prod_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4}\n    (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) : \u21d1(prod_map e\u2081 e\u2082) = prod.map \u21d1e\u2081 \u21d1e\u2082 :=\n  rfl\n\n/-- If `e\u2081` and `e\u2082` are embeddings, then so is `sum.map e\u2081 e\u2082`. -/\ndef sum_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) :\n    \u03b1 \u2295 \u03b3 \u21aa \u03b2 \u2295 \u03b4 :=\n  mk (sum.map \u21d1e\u2081 \u21d1e\u2082) sorry\n\n@[simp] theorem coe_sum_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2)\n    (e\u2082 : \u03b3 \u21aa \u03b4) : \u21d1(sum_map e\u2081 e\u2082) = sum.map \u21d1e\u2081 \u21d1e\u2082 :=\n  rfl\n\n/-- The embedding of `\u03b1` into the sum `\u03b1 \u2295 \u03b2`. -/\n@[simp] theorem inl_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} (val : \u03b1) : coe_fn inl val = sum.inl val :=\n  Eq.refl (coe_fn inl val)\n\n/-- The embedding of `\u03b2` into the sum `\u03b1 \u2295 \u03b2`. -/\n@[simp] theorem inr_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} (val : \u03b2) : 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 {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_3} (a : \u03b1) (snd : \u03b2 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 : \u03b1 \u21aa \u03b1'` is an embedding and `g : \u03a0 a, \u03b2 \u03b1 \u21aa \u03b2' (f \u03b1)` is a family\nof embeddings, then `sigma.map f g` is an embedding. -/\n@[simp] theorem sigma_map_apply {\u03b1 : Type u_1} {\u03b1' : Type u_2} {\u03b2 : \u03b1 \u2192 Type u_3}\n    {\u03b2' : \u03b1' \u2192 Type u_4} (f : \u03b1 \u21aa \u03b1') (g : (a : \u03b1) \u2192 \u03b2 a \u21aa \u03b2' (coe_fn f a))\n    (x : sigma fun (a : \u03b1) => \u03b2 a) :\n    coe_fn (sigma_map f g) x = sigma.map (\u21d1f) (fun (a : \u03b1) => \u21d1(g a)) x :=\n  Eq.refl (coe_fn (sigma_map f g) x)\n\ndef Pi_congr_right {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {\u03b3 : \u03b1 \u2192 Sort u_3} (e : (a : \u03b1) \u2192 \u03b2 a \u21aa \u03b3 a) :\n    ((a : \u03b1) \u2192 \u03b2 a) \u21aa (a : \u03b1) \u2192 \u03b3 a :=\n  mk (fun (f : (a : \u03b1) \u2192 \u03b2 a) (a : \u03b1) => coe_fn (e a) (f a)) sorry\n\ndef arrow_congr_left {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b3 : Sort w} (e : \u03b1 \u21aa \u03b2) : (\u03b3 \u2192 \u03b1) \u21aa \u03b3 \u2192 \u03b2 :=\n  Pi_congr_right fun (_x : \u03b3) => e\n\ndef arrow_congr_right {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b3 : Sort w} [Inhabited \u03b3] (e : \u03b1 \u21aa \u03b2) :\n    (\u03b1 \u2192 \u03b3) \u21aa \u03b2 \u2192 \u03b3 :=\n  let f' : (\u03b1 \u2192 \u03b3) \u2192 \u03b2 \u2192 \u03b3 :=\n    fun (f : \u03b1 \u2192 \u03b3) (b : \u03b2) =>\n      dite (\u2203 (c : \u03b1), coe_fn e c = b) (fun (h : \u2203 (c : \u03b1), coe_fn e c = b) => f (classical.some h))\n        fun (h : \u00ac\u2203 (c : \u03b1), coe_fn e c = b) => Inhabited.default;\n  mk f' sorry\n\nprotected def subtype_map {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u21aa \u03b2)\n    (h : \u2200 {x : \u03b1}, p x \u2192 q (coe_fn f x)) :\n    (Subtype fun (x : \u03b1) => p x) \u21aa Subtype fun (y : \u03b2) => q y :=\n  mk (subtype.map (\u21d1f) h) sorry\n\n/-- `set.image` as an embedding `set \u03b1 \u21aa set \u03b2`. -/\nprotected def image {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u21aa \u03b2) : set \u03b1 \u21aa set \u03b2 :=\n  mk (set.image \u21d1f) sorry\n\ntheorem swap_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} [DecidableEq \u03b1] [DecidableEq \u03b2] (f : \u03b1 \u21aa \u03b2) (x : \u03b1)\n    (y : \u03b1) (z : \u03b1) :\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [DecidableEq \u03b1] [DecidableEq \u03b2] (f : \u03b1 \u21aa \u03b2) (x : \u03b1)\n    (y : \u03b1) : \u21d1(equiv.swap (coe_fn f x) (coe_fn f y)) \u2218 \u21d1f = \u21d1f \u2218 \u21d1(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 {\u03b1 : Type u_1} :\n    equiv.to_embedding (equiv.refl \u03b1) = function.embedding.refl \u03b1 :=\n  rfl\n\n@[simp] theorem trans_to_embedding {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (e : \u03b1 \u2243 \u03b2)\n    (f : \u03b2 \u2243 \u03b3) :\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 {\u03b1 : Type u_1} (s : set \u03b1) (t : set \u03b1) (h : s \u2286 t) : \u21a5s \u21aa \u21a5t :=\n  function.embedding.mk (fun (x : \u21a5s) => { 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 \u21aa 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 `\u2295'` 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop)\n    (q : \u03b2 \u2192 Prop) :=\n  \u2203 (f : \u03b1 \u2192 \u03b2), computable f \u2227 \u2200 (a : \u03b1), p a \u2194 q (f a)\n\ninfixl:1000 \" \u2264\u2080 \" => Mathlib.many_one_reducible\n\ntheorem many_one_reducible.mk {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {f : \u03b1 \u2192 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable f) : (fun (a : \u03b1) => q (f a)) \u2264\u2080 q :=\n  Exists.intro f { left := h, right := fun (a : \u03b1) => iff.rfl }\n\ntheorem many_one_reducible_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 Prop) : p \u2264\u2080 p := sorry\n\ntheorem many_one_reducible.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} :\n    p \u2264\u2080 q \u2192 q \u2264\u2080 r \u2192 p \u2264\u2080 r :=\n  sorry\n\ntheorem reflexive_many_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] :\n    reflexive many_one_reducible :=\n  many_one_reducible_refl\n\ntheorem transitive_many_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] :\n    transitive many_one_reducible :=\n  fun (p q r : \u03b1 \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop)\n    (q : \u03b2 \u2192 Prop) :=\n  \u2203 (f : \u03b1 \u2192 \u03b2), computable f \u2227 function.injective f \u2227 \u2200 (a : \u03b1), p a \u2194 q (f a)\n\ninfixl:1000 \" \u2264\u2081 \" => Mathlib.one_one_reducible\n\ntheorem one_one_reducible.mk {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {f : \u03b1 \u2192 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable f) (i : function.injective f) :\n    (fun (a : \u03b1) => q (f a)) \u2264\u2081 q :=\n  Exists.intro f { left := h, right := { left := i, right := fun (a : \u03b1) => iff.rfl } }\n\ntheorem one_one_reducible_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 Prop) : p \u2264\u2081 p := sorry\n\ntheorem one_one_reducible.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} :\n    p \u2264\u2081 q \u2192 q \u2264\u2081 r \u2192 p \u2264\u2081 r :=\n  sorry\n\ntheorem one_one_reducible.to_many_one {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : p \u2264\u2081 q \u2192 p \u2264\u2080 q :=\n  sorry\n\ntheorem one_one_reducible.of_equiv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {e : \u03b1 \u2243 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable \u21d1e) : (q \u2218 \u21d1e) \u2264\u2081 q :=\n  one_one_reducible.mk q h (equiv.injective e)\n\ntheorem one_one_reducible.of_equiv_symm {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1]\n    [primcodable \u03b2] {e : \u03b1 \u2243 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable \u21d1(equiv.symm e)) : q \u2264\u2081 (q \u2218 \u21d1e) :=\n  sorry\n\ntheorem reflexive_one_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] : reflexive one_one_reducible :=\n  one_one_reducible_refl\n\ntheorem transitive_one_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] :\n    transitive one_one_reducible :=\n  fun (p q r : \u03b1 \u2192 Prop) => one_one_reducible.trans\n\nnamespace computable_pred\n\n\ntheorem computable_of_many_one_reducible {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1]\n    [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (h\u2081 : p \u2264\u2080 q) (h\u2082 : computable_pred q) :\n    computable_pred p :=\n  sorry\n\ntheorem computable_of_one_one_reducible {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1]\n    [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (h : p \u2264\u2081 q) :\n    computable_pred q \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop)\n    (q : \u03b2 \u2192 Prop) :=\n  p \u2264\u2080 q \u2227 q \u2264\u2080 p\n\n/-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/\ndef one_one_equiv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop)\n    (q : \u03b2 \u2192 Prop) :=\n  p \u2264\u2081 q \u2227 q \u2264\u2081 p\n\ntheorem many_one_equiv_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : many_one_equiv p q \u2192 many_one_equiv q p :=\n  and.swap\n\ntheorem many_one_equiv.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} :\n    many_one_equiv p q \u2192 many_one_equiv q r \u2192 many_one_equiv p r :=\n  sorry\n\ntheorem equivalence_of_many_one_equiv {\u03b1 : Type u_1} [primcodable \u03b1] : equivalence many_one_equiv :=\n  { left := many_one_equiv_refl,\n    right :=\n      { left := fun (x y : \u03b1 \u2192 Prop) => many_one_equiv.symm,\n        right := fun (x y z : \u03b1 \u2192 Prop) => many_one_equiv.trans } }\n\ntheorem one_one_equiv_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : one_one_equiv p q \u2192 one_one_equiv q p :=\n  and.swap\n\ntheorem one_one_equiv.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} :\n    one_one_equiv p q \u2192 one_one_equiv q r \u2192 one_one_equiv p r :=\n  sorry\n\ntheorem equivalence_of_one_one_equiv {\u03b1 : Type u_1} [primcodable \u03b1] : equivalence one_one_equiv :=\n  { left := one_one_equiv_refl,\n    right :=\n      { left := fun (x y : \u03b1 \u2192 Prop) => one_one_equiv.symm,\n        right := fun (x y z : \u03b1 \u2192 Prop) => one_one_equiv.trans } }\n\ntheorem one_one_equiv.to_many_one {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : one_one_equiv p q \u2192 many_one_equiv p q :=\n  sorry\n\n/-- a computable bijection -/\ndef equiv.computable {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (e : \u03b1 \u2243 \u03b2) :=\n  computable \u21d1e \u2227 computable \u21d1(equiv.symm e)\n\ntheorem equiv.computable.symm {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {e : \u03b1 \u2243 \u03b2} : equiv.computable e \u2192 equiv.computable (equiv.symm e) :=\n  and.swap\n\ntheorem equiv.computable.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {e\u2081 : \u03b1 \u2243 \u03b2} {e\u2082 : \u03b2 \u2243 \u03b3} :\n    equiv.computable e\u2081 \u2192 equiv.computable e\u2082 \u2192 equiv.computable (equiv.trans e\u2081 e\u2082) :=\n  sorry\n\ntheorem computable.eqv (\u03b1 : Type u_1) [denumerable \u03b1] : equiv.computable (denumerable.eqv \u03b1) :=\n  { left := computable.encode, right := computable.of_nat \u03b1 }\n\ntheorem computable.equiv\u2082 (\u03b1 : Type u_1) (\u03b2 : Type u_2) [denumerable \u03b1] [denumerable \u03b2] :\n    equiv.computable (denumerable.equiv\u2082 \u03b1 \u03b2) :=\n  equiv.computable.trans (computable.eqv \u03b1) (equiv.computable.symm (computable.eqv \u03b2))\n\ntheorem one_one_equiv.of_equiv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {e : \u03b1 \u2243 \u03b2} (h : equiv.computable e) {p : \u03b2 \u2192 Prop} : one_one_equiv (p \u2218 \u21d1e) 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {e : \u03b1 \u2243 \u03b2} (h : equiv.computable e) {p : \u03b2 \u2192 Prop} : many_one_equiv (p \u2218 \u21d1e) p :=\n  one_one_equiv.to_many_one (one_one_equiv.of_equiv h)\n\ntheorem many_one_equiv.le_congr_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : many_one_equiv p q) : p \u2264\u2080 r \u2194 q \u2264\u2080 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : many_one_equiv q r) : p \u2264\u2080 q \u2194 p \u2264\u2080 r :=\n  { mp := fun (h' : p \u2264\u2080 q) => many_one_reducible.trans h' (and.left h),\n    mpr := fun (h' : p \u2264\u2080 r) => many_one_reducible.trans h' (and.right h) }\n\ntheorem one_one_equiv.le_congr_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : one_one_equiv p q) : p \u2264\u2081 r \u2194 q \u2264\u2081 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : one_one_equiv q r) : p \u2264\u2081 q \u2194 p \u2264\u2081 r :=\n  { mp := fun (h' : p \u2264\u2081 q) => one_one_reducible.trans h' (and.left h),\n    mpr := fun (h' : p \u2264\u2081 r) => one_one_reducible.trans h' (and.right h) }\n\ntheorem many_one_equiv.congr_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : many_one_equiv p q) : many_one_equiv p r \u2194 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : many_one_equiv q r) : many_one_equiv p q \u2194 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : one_one_equiv p q) : one_one_equiv p r \u2194 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop}\n    (h : one_one_equiv q r) : one_one_equiv p q \u2194 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 {\u03b1 : Type u_1} [primcodable \u03b1] :\n    equiv.computable (ulower.equiv \u03b1) :=\n  { left := primrec.to_comp primrec.ulower_down, right := primrec.to_comp primrec.ulower_up }\n\ntheorem many_one_equiv_up {\u03b1 : Type u_1} [primcodable \u03b1] {p : \u03b1 \u2192 Prop} :\n    many_one_equiv (p \u2218 ulower.up) p :=\n  many_one_equiv.of_equiv (equiv.computable.symm ulower.down_computable)\n\ntheorem one_one_reducible.disjoin_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2]\n    {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : p \u2264\u2081 sum.elim p q :=\n  Exists.intro sum.inl\n    { left := computable.sum_inl,\n      right :=\n        { left := fun (x y : \u03b1) => iff.mp sum.inl.inj_iff, right := fun (a : \u03b1) => iff.rfl } }\n\ntheorem one_one_reducible.disjoin_right {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1]\n    [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : q \u2264\u2081 sum.elim p q :=\n  Exists.intro sum.inr\n    { left := computable.sum_inr,\n      right :=\n        { left := fun (x y : \u03b2) => iff.mp sum.inr.inj_iff, right := fun (a : \u03b2) => iff.rfl } }\n\ntheorem disjoin_many_one_reducible {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1]\n    [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} :\n    p \u2264\u2080 r \u2192 q \u2264\u2080 r \u2192 sum.elim p q \u2264\u2080 r :=\n  sorry\n\ntheorem disjoin_le {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2]\n    [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} :\n    sum.elim p q \u2264\u2080 r \u2194 p \u2264\u2080 r \u2227 q \u2264\u2080 r :=\n  sorry\n\n/--\nComputable and injective mapping of predicates to sets of natural numbers.\n-/\ndef to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] (p : set \u03b1) : set \u2115 :=\n  set_of fun (n : \u2115) => p (option.get_or_else (encodable.decode \u03b1 n) Inhabited.default)\n\n@[simp] theorem to_nat_many_one_reducible {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {p : set \u03b1} :\n    to_nat p \u2264\u2080 p :=\n  Exists.intro (fun (n : \u2115) => option.get_or_else (encodable.decode \u03b1 n) Inhabited.default)\n    { left := computable.option_get_or_else computable.decode (computable.const Inhabited.default),\n      right := fun (_x : \u2115) => iff.rfl }\n\n@[simp] theorem many_one_reducible_to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {p : set \u03b1} :\n    p \u2264\u2080 to_nat p :=\n  sorry\n\n@[simp] theorem many_one_reducible_to_nat_to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1]\n    {\u03b2 : Type v} [primcodable \u03b2] [Inhabited \u03b2] {p : set \u03b1} {q : set \u03b2} :\n    to_nat p \u2264\u2080 to_nat q \u2194 p \u2264\u2080 q :=\n  sorry\n\n@[simp] theorem to_nat_many_one_equiv {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {p : set \u03b1} :\n    many_one_equiv (to_nat p) p :=\n  sorry\n\n@[simp] theorem many_one_equiv_to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v}\n    [primcodable \u03b2] [Inhabited \u03b2] (p : set \u03b1) (q : set \u03b2) :\n    many_one_equiv (to_nat p) (to_nat q) \u2194 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 {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] (p : \u03b1 \u2192 Prop) : many_one_degree :=\n  quotient.mk' (to_nat p)\n\nprotected theorem ind_on {C : many_one_degree \u2192 Prop} (d : many_one_degree)\n    (h : \u2200 (p : set \u2115), 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 {\u03c6 : Sort u_1} (d : many_one_degree) (f : set \u2115 \u2192 \u03c6)\n    (h : \u2200 (p q : \u2115 \u2192 Prop), many_one_equiv p q \u2192 f p = f q) : \u03c6 :=\n  quotient.lift_on' d f h\n\n@[simp] protected theorem lift_on_eq {\u03c6 : Sort u_1} (p : set \u2115) (f : set \u2115 \u2192 \u03c6)\n    (h : \u2200 (p q : \u2115 \u2192 Prop), many_one_equiv p q \u2192 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\u2082 {\u03c6 : Sort u_1} (d\u2081 : many_one_degree) (d\u2082 : many_one_degree)\n    (f : set \u2115 \u2192 set \u2115 \u2192 \u03c6)\n    (h :\n      \u2200 (p\u2081 p\u2082 q\u2081 q\u2082 : \u2115 \u2192 Prop), many_one_equiv p\u2081 p\u2082 \u2192 many_one_equiv q\u2081 q\u2082 \u2192 f p\u2081 q\u2081 = f p\u2082 q\u2082) :\n    \u03c6 :=\n  many_one_degree.lift_on d\u2081 (fun (p : set \u2115) => many_one_degree.lift_on d\u2082 (f p) sorry) sorry\n\n@[simp] protected theorem lift_on\u2082_eq {\u03c6 : Sort u_1} (p : set \u2115) (q : set \u2115) (f : set \u2115 \u2192 set \u2115 \u2192 \u03c6)\n    (h :\n      \u2200 (p\u2081 p\u2082 q\u2081 q\u2082 : \u2115 \u2192 Prop), many_one_equiv p\u2081 p\u2082 \u2192 many_one_equiv q\u2081 q\u2082 \u2192 f p\u2081 q\u2081 = f p\u2082 q\u2082) :\n    many_one_degree.lift_on\u2082 (of p) (of q) f h = f p q :=\n  rfl\n\n@[simp] theorem of_eq_of {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2]\n    [Inhabited \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : of p = of q \u2194 many_one_equiv p q :=\n  sorry\n\nprotected instance inhabited : Inhabited many_one_degree := { default := of \u2205 }\n\n/--\nFor many-one degrees `d\u2081` and `d\u2082`, `d\u2081 \u2264 d\u2082` if the sets in `d\u2081` are many-one reducible to the\nsets in `d\u2082`.\n-/\nprotected instance has_le : HasLessEq many_one_degree :=\n  { LessEq :=\n      fun (d\u2081 d\u2082 : many_one_degree) => many_one_degree.lift_on\u2082 d\u2081 d\u2082 many_one_reducible sorry }\n\n@[simp] theorem of_le_of {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2]\n    [Inhabited \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : of p \u2264 of q \u2194 p \u2264\u2080 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\u2081 d\u2082 : many_one_degree) =>\n        many_one_degree.lift_on\u2082 d\u2081 d\u2082 (fun (a b : set \u2115) => of (sum.elim a b)) sorry }\n\n@[simp] theorem add_of {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2]\n    [Inhabited \u03b2] (p : set \u03b1) (q : set \u03b2) : of (sum.elim p q) = of p + of q :=\n  sorry\n\n@[simp] protected theorem add_le {d\u2081 : many_one_degree} {d\u2082 : many_one_degree}\n    {d\u2083 : many_one_degree} : d\u2081 + d\u2082 \u2264 d\u2083 \u2194 d\u2081 \u2264 d\u2083 \u2227 d\u2082 \u2264 d\u2083 :=\n  sorry\n\n@[simp] protected theorem le_add_left (d\u2081 : many_one_degree) (d\u2082 : many_one_degree) :\n    d\u2081 \u2264 d\u2081 + d\u2082 :=\n  and.left (iff.mp many_one_degree.add_le (le_refl (d\u2081 + d\u2082)))\n\n@[simp] protected theorem le_add_right (d\u2081 : many_one_degree) (d\u2082 : many_one_degree) :\n    d\u2082 \u2264 d\u2081 + d\u2082 :=\n  and.right (iff.mp many_one_degree.add_le (le_refl (d\u2081 + d\u2082)))\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 `\u00ac a` is definitionally equal to `p \u2192 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 `\u2115` `a.succ \u2264 b` is definitionally `a < b`,\n\n--   we add some special cases to allow looking for `<` lemmas even when the goal has a `\u2264`.\n\n--   Note we only do this in the `\u2115` 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 \u2192 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 `\u2194` 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\u2081 : a < c) (h\u2082 : 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\u2081 h\u2082)`\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 : \u2115) : 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\u2081 : a < c) (h\u2082 : 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\u2081 h\u2082)`\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) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.string.defs\nimport Mathlib.tactic.derive_inhabited\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\nnamespace binder_info\n\n\n/-! ### Declarations about `binder_info` -/\n\nprotected instance inhabited : Inhabited binder_info := { default := default }\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : binder_info \u2192 string \u00d7 string := sorry\n\nend binder_info\n\n\nnamespace name\n\n\n/-! ### Declarations about `name` -/\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef map_prefix (f : name \u2192 Option name) : name \u2192 name := sorry\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\n/-- Auxilliary definition for `pop_nth_prefix` -/\n/-- Pops the top `n` prefixes from the given name. -/\n/-- Pop the prefix of a name -/\n/-- Auxilliary definition for `from_components` -/\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef from_components : List string \u2192 name := from_components_aux anonymous\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\n/-- Append a string to the last component of a name -/\ndef append_suffix : name \u2192 string \u2192 name := sorry\n\n/-- The first component of a name, turning a number to a string -/\n/-- Tests whether the first component of a name is `\"_private\"` -/\n/-- Get the last component of a name, and convert it to a string. -/\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef has_prefix (P : name \u2192 Bool) : name \u2192 Bool := sorry\n\n/-- Appends `'` to the end of a name. -/\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef last_string : name \u2192 string := sorry\n\n/--\nConstructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\n/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\n/--\nCheck whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\n/--\nCheck whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nend name\n\n\nnamespace level\n\n\n/-! ### Declarations about `level` -/\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\n/--\n`l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nend level\n\n\n/-! ### Declarations about `binder` -/\n\n/-- The type of binders containing a name, the binding info and the binding type -/\nnamespace binder\n\n\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nend binder\n\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n/--\n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\n/--\n`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\n/--\n`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nnamespace expr\n\n\n/--\nTurns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\n/--\nTurns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\n/--\n`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\nignoring differences in type and type class arguments.\n-/\nend expr\n\n\n/-! ### Declarations about `expr` -/\n\nnamespace expr\n\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\n/-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/\n/-- Match a variable. -/\n/-- Match a sort. -/\n/-- Match a constant. -/\n/-- Match a metavariable. -/\n/-- Match a local constant. -/\n/-- Match an application. -/\n/-- Match an abstraction. -/\n/-- Match a \u03a0 type. -/\n/-- Match a let. -/\n/-- Match a macro. -/\n/-- Tests whether an expression is a meta-variable. -/\n/-- Tests whether an expression is a sort. -/\n/-- Get the universe levels of a `const` expression -/\n/--\nReplace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/\n/-- Returns a list of all local constants in an expression (without duplicates). -/\n/-- Returns the set of all local constants in an expression. -/\n/-- Returns the unique names of all local constants in an expression. -/\n/-- Returns a name_set of all constants in an expression. -/\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\n/-- Returns the set of all meta-variables in an expression. -/\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\n/--\nTest `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\n-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n\n/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\n/--\nReturns true if `e` contains a `sorry`.\n-/\n/--\n`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\n-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\n/-- head-reduce a single let expression -/\n/-- head-reduce all let expressions -/\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\n/-- Repeatedly apply `expr.subst`. -/\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\n/--\nSome declarations work with open expressions, i.e. an expr that has free variables.\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/meta/expr_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.09401017834740662, "lm_q1q2_score": 0.036883655376266034}}
{"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 \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1} (xs : list \u03b1) :\n  list.traverse id.mk xs = xs :=\nby induction xs; simp! * with functor_norm; refl\n\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 \u03b2') \u2208 traverse f (a :: as) \u2194 b \u2208 f a \u2227 bs \u2208 traverse f as,\n    by simpa [mem_traverse as bs],\n  iff.intro\n    (assume \u27e8_, \u27e8b, hb, rfl\u27e9, _, hl, rfl\u27e9, \u27e8hb, hl\u27e9)\n    (assume \u27e8hb, hl\u27e9, \u27e8_, \u27e8b, hb, rfl\u27e9, _, hl, rfl\u27e9)\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {\u03c3 : Type u}\nvariables {F G : Type u \u2192 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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3 }\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 \u2192 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 \u2192 B)\n(map_op' : \u2200 {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 (\u03bb _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := \u03bb 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) (\u03bb _, A \u2192 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 \u2192 B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : my_hom A B :=\n{ to_fun := f',\n  map_op' := h.symm \u25b8 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 (\u03bb _, B) :=\n(map_op : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u2192 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 (\u03b1 : outParam.{succ u2} Sort.{u2}), (outParam.{max u2 (succ u3)} (\u03b1 -> Sort.{u3})) -> Sort.{max 1 (imax u1 u2 u3)})\nbut is expected to have type\n  Sort.{u1} -> (forall (\u03b1 : outParam.{succ u2} Sort.{u2}), (outParam.{max u2 (succ u3)} (\u03b1 -> Sort.{u3})) -> Sort.{max (max (max 1 u1) u2) u3})\nCase conversion may be inaccurate. Consider using '#align fun_like FunLike\u2093'. -/\n/-- The class `fun_like F \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to functions from `\u03b1` to `\u03b2`.\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 _) (\u03b1 : outParam (Sort _)) (\u03b2 : outParam <| \u03b1 \u2192 Sort _) where\n  coe : F \u2192 \u2200 a : \u03b1, \u03b2 a\n  coe_injective' : Function.Injective coe\n#align fun_like FunLike\n\nsection Dependent\n\n/-! ### `fun_like F \u03b1 \u03b2` where `\u03b2` depends on `a : \u03b1` -/\n\n\nvariable (F \u03b1 : Sort _) (\u03b2 : \u03b1 \u2192 Sort _)\n\nnamespace FunLike\n\nvariable {F \u03b1 \u03b2} [i : FunLike F \u03b1 \u03b2]\n\ninclude i\n\n-- Give this a priority between `coe_fn_trans` and the default priority\n-- `\u03b1` and `\u03b2` are out_params, so this instance should not be dangerous\n@[nolint dangerous_instance]\ninstance (priority := 100) : CoeFun F fun _ => \u2200 a : \u03b1, \u03b2 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2], Eq.{imax u1 u2 u3} (F -> (forall (a : \u03b1), \u03b2 a)) (FunLike.coe.{u1, u2, u3} F \u03b1 (fun (a : \u03b1) => \u03b2 a) i) (coeFn.{u1, imax u2 u3} F (fun (\u1fb0 : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F \u03b1 \u03b2], Eq.{imax u3 u2 u1} (F -> (forall (a : \u03b1), \u03b2 a)) (FunLike.coe.{u3, u2, u1} F \u03b1 \u03b2 i) (fun (f : F) => FunLike.coe.{u3, u2, u1} F \u03b1 (fun (a : \u03b1) => \u03b2 a) i f)\nCase conversion may be inaccurate. Consider using '#align fun_like.coe_eq_coe_fn FunLike.coe_eq_coe_fn\u2093'. -/\n@[simp]\ntheorem coe_eq_coe_fn : (FunLike.coe : F \u2192 \u2200 a : \u03b1, \u03b2 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2], Function.Injective.{u1, imax u2 u3} F (forall (a : \u03b1), \u03b2 a) (coeFn.{u1, imax u2 u3} F (fun (\u1fb0 : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F \u03b1 \u03b2], Function.Injective.{u3, imax u2 u1} F (forall (a : \u03b1), \u03b2 a) (fun (f : F) => FunLike.coe.{u3, u2, u1} F \u03b1 (fun (a : \u03b1) => \u03b2 a) i f)\nCase conversion may be inaccurate. Consider using '#align fun_like.coe_injective FunLike.coe_injective\u2093'. -/\ntheorem coe_injective : Function.Injective (coeFn : F \u2192 \u2200 a : \u03b1, \u03b2 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Eq.{imax u2 u3} ((fun (_x : F) => forall (a : \u03b1), \u03b2 a) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g)) (Eq.{u1} F f g)\nbut is expected to have type\n  forall {F : Sort.{u1}} {\u03b1 : Sort.{u3}} {\u03b2 : \u03b1 -> Sort.{u2}} [i : FunLike.{u1, u3, u2} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Eq.{imax u3 u2} (forall (a : \u03b1), \u03b2 a) (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f) (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _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\u2093'. -/\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : \u2200 a : \u03b1, \u03b2 a) = (g : \u2200 a : \u03b1, \u03b2 a) \u2194 f = g :=\n  \u27e8fun h => @coe_injective _ _ _ i _ _ h, fun h => by cases h <;> rfl\u27e9\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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, (Eq.{imax u2 u3} ((fun (_x : F) => forall (a : \u03b1), \u03b2 a) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g)) -> (Eq.{u1} F f g)\nbut is expected to have type\n  forall {F : Sort.{u1}} {\u03b1 : Sort.{u3}} {\u03b2 : \u03b1 -> Sort.{u2}} [i : FunLike.{u1, u3, u2} F \u03b1 \u03b2] {f : F} {g : F}, (Eq.{imax u3 u2} (forall (a : \u03b1), \u03b2 a) (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f) (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g)) -> (Eq.{u1} F f g)\nCase conversion may be inaccurate. Consider using '#align fun_like.ext' FunLike.ext'\u2093'. -/\ntheorem ext' {f g : F} (h : (f : \u2200 a : \u03b1, \u03b2 a) = (g : \u2200 a : \u03b1, \u03b2 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Eq.{u1} F f g) (Eq.{imax u2 u3} ((fun (_x : F) => forall (a : \u03b1), \u03b2 a) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Eq.{u3} F f g) (Eq.{imax u2 u1} (forall (a : \u03b1), \u03b2 a) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g))\nCase conversion may be inaccurate. Consider using '#align fun_like.ext'_iff FunLike.ext'_iff\u2093'. -/\ntheorem ext'_iff {f g : F} : f = g \u2194 (f : \u2200 a : \u03b1, \u03b2 a) = (g : \u2200 a : \u03b1, \u03b2 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] (f : F) (g : F), (forall (x : \u03b1), Eq.{u3} (\u03b2 x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g x)) -> (Eq.{u1} F f g)\nbut is expected to have type\n  forall {F : Sort.{u2}} {\u03b1 : Sort.{u1}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u2, u1, u3} F \u03b1 \u03b2] (f : F) (g : F), (forall (x : \u03b1), Eq.{u3} (\u03b2 x) (FunLike.coe.{u2, u1, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f x) (FunLike.coe.{u2, u1, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g x)) -> (Eq.{u2} F f g)\nCase conversion may be inaccurate. Consider using '#align fun_like.ext FunLike.ext\u2093'. -/\ntheorem ext (f g : F) (h : \u2200 x : \u03b1, 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Eq.{u1} F f g) (forall (x : \u03b1), Eq.{u3} (\u03b2 x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g x))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u1}} {\u03b2 : \u03b1 -> Sort.{u2}} [i : FunLike.{u3, u1, u2} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Eq.{u3} F f g) (forall (x : \u03b1), Eq.{u2} (\u03b2 x) (FunLike.coe.{u3, u1, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f x) (FunLike.coe.{u3, u1, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g x))\nCase conversion may be inaccurate. Consider using '#align fun_like.ext_iff FunLike.ext_iff\u2093'. -/\ntheorem ext_iff {f g : F} : f = g \u2194 \u2200 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, (Eq.{u1} F f g) -> (forall (x : \u03b1), Eq.{u3} (\u03b2 x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g x))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u1}} {\u03b2 : \u03b1 -> Sort.{u2}} [i : FunLike.{u3, u1, u2} F \u03b1 \u03b2] {f : F} {g : F}, (Eq.{u3} F f g) -> (forall (x : \u03b1), Eq.{u2} (\u03b2 x) (FunLike.coe.{u3, u1, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f x) (FunLike.coe.{u3, u1, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g x))\nCase conversion may be inaccurate. Consider using '#align fun_like.congr_fun FunLike.congr_fun\u2093'. -/\nprotected theorem congr_fun {f g : F} (h\u2081 : f = g) (x : \u03b1) : f x = g x :=\n  congr_fun (congr_arg _ h\u2081) 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Ne.{u1} F f g) (Exists.{u2} \u03b1 (fun (a : \u03b1) => Ne.{u3} (\u03b2 a) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f a) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g a)))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F \u03b1 \u03b2] {f : F} {g : F}, Iff (Ne.{u3} F f g) (Exists.{u2} \u03b1 (fun (a : \u03b1) => Ne.{u1} (\u03b2 a) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f a) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g a)))\nCase conversion may be inaccurate. Consider using '#align fun_like.ne_iff FunLike.ne_iff\u2093'. -/\ntheorem ne_iff {f g : F} : f \u2260 g \u2194 \u2203 a, f a \u2260 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] {f : F} {g : F}, (Ne.{u1} F f g) -> (Exists.{u2} \u03b1 (fun (x : \u03b1) => Ne.{u3} (\u03b2 x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : \u03b1), \u03b2 a) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 \u03b2 i) g x)))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F \u03b1 \u03b2] {f : F} {g : F}, (Ne.{u3} F f g) -> (Exists.{u2} \u03b1 (fun (x : \u03b1) => Ne.{u1} (\u03b2 x) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i f x) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2 _x) i g x)))\nCase conversion may be inaccurate. Consider using '#align fun_like.exists_ne FunLike.exists_ne\u2093'. -/\ntheorem exists_ne {f g : F} (h : f \u2260 g) : \u2203 x, f x \u2260 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}} {\u03b1 : Sort.{u2}} {\u03b2 : \u03b1 -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 \u03b2] [_inst_1 : forall (a : \u03b1), Subsingleton.{u3} (\u03b2 a)], Subsingleton.{u1} F\nbut is expected to have type\n  forall {F : Sort.{u1}} {\u03b1 : Sort.{u3}} {\u03b2 : \u03b1 -> Sort.{u2}} [i : FunLike.{u1, u3, u2} F \u03b1 \u03b2] [_inst_1 : forall (a : \u03b1), Subsingleton.{u2} (\u03b2 a)], Subsingleton.{u1} F\nCase conversion may be inaccurate. Consider using '#align fun_like.subsingleton_cod FunLike.subsingleton_cod\u2093'. -/\n/-- This is not an instance to avoid slowing down every single `subsingleton` typeclass search.-/\ntheorem subsingleton_cod [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton F :=\n  \u27e8fun f g => coe_injective <| Subsingleton.elim _ _\u27e9\n#align fun_like.subsingleton_cod FunLike.subsingleton_cod\n\nend FunLike\n\nend Dependent\n\nsection NonDependent\n\n/-! ### `fun_like F \u03b1 (\u03bb _, \u03b2)` where `\u03b2` does not depend on `a : \u03b1` -/\n\n\nvariable {F \u03b1 \u03b2 : Sort _} [i : FunLike F \u03b1 fun _ => \u03b2]\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}} {\u03b1 : Sort.{u2}} {\u03b2 : Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2)] {f : F} {g : F} {x : \u03b1} {y : \u03b1}, (Eq.{u1} F f g) -> (Eq.{u2} \u03b1 x y) -> (Eq.{u3} \u03b2 (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) i) g y))\nbut is expected to have type\n  forall {F : Sort.{u3}} {\u03b1 : Sort.{u2}} {\u03b2 : Sort.{u1}} [i : FunLike.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => \u03b2)] {f : F} {g : F} {x : \u03b1} {y : \u03b1}, (Eq.{u3} F f g) -> (Eq.{u2} \u03b1 x y) -> (Eq.{u1} ((fun (x._@.Mathlib.Data.FunLike.Basic._hyg.614 : \u03b1) => \u03b2) x) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.614 : \u03b1) => \u03b2) _x) i f x) (FunLike.coe.{u3, u2, u1} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.614 : \u03b1) => \u03b2) _x) i g y))\nCase conversion may be inaccurate. Consider using '#align fun_like.congr FunLike.congr\u2093'. -/\nprotected theorem congr {f g : F} {x y : \u03b1} (h\u2081 : f = g) (h\u2082 : x = y) : f x = g y :=\n  congr (congr_arg _ h\u2081) h\u2082\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}} {\u03b1 : Sort.{u2}} {\u03b2 : Sort.{u3}} [i : FunLike.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2)] (f : F) {x : \u03b1} {y : \u03b1}, (Eq.{u2} \u03b1 x y) -> (Eq.{u3} \u03b2 (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => \u03b1 -> \u03b2) (FunLike.hasCoeToFun.{u1, u2, u3} F \u03b1 (fun (_x : \u03b1) => \u03b2) i) f y))\nbut is expected to have type\n  forall {F : Sort.{u1}} {\u03b1 : Sort.{u3}} {\u03b2 : Sort.{u2}} [i : FunLike.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => \u03b2)] (f : F) {x : \u03b1} {y : \u03b1}, (Eq.{u3} \u03b1 x y) -> (Eq.{u2} ((fun (x._@.Mathlib.Data.FunLike.Basic._hyg.657 : \u03b1) => \u03b2) x) (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.657 : \u03b1) => \u03b2) _x) i f x) (FunLike.coe.{u1, u3, u2} F \u03b1 (fun (_x : \u03b1) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.657 : \u03b1) => \u03b2) _x) i f y))\nCase conversion may be inaccurate. Consider using '#align fun_like.congr_arg FunLike.congr_arg\u2093'. -/\nprotected theorem congr_arg (f : F) {x y : \u03b1} (h\u2082 : x = y) : f x = f y :=\n  congr_arg _ h\u2082\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": "example : List (Unit -> Nat) :=\n  let g := [by exact fun _ => 0]; g\n\nexample : List (Unit -> Nat) :=\n  let g := [fun _ => 0]; g\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/1058.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.07369627682665666, "lm_q1q2_score": 0.03656026818868508}}
{"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\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/ -- doc string - /\nalias my_theorem \u2190 alias1 alias2 ...\n\nThis produces defs or theorems of the form:\n\n/ -- doc string - /\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/ -- doc string - /\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n\n\nIff alias syntax:\n\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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-/\nimport data.buffer.parser meta.coinductive_predicates\n\nopen lean.parser tactic interactive parser\n\nnamespace tactic.alias\n\n@[user_attribute] meta def alias_attr : user_attribute :=\n{ name := `alias, descr := \"This definition is an alias of another.\" }\n\nmeta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit :=\ndo updateex_env $ \u03bb 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  alias_attr.set al () tt,\n  add_doc_string al doc\n\nmeta def mk_iff_mp_app (iffmp : name) : expr \u2192 (nat \u2192 expr) \u2192 tactic expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)\n| _ f := fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\nmeta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : 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  v \u2190 mk_iff_mp_app iffmp t (\u03bb_, expr.const d.to_name (level.param <$> ls)),\n  t' \u2190 infer_type v,\n  updateex_env $ \u03bb env, env.add (declaration.thm al ls t' $ task.pure v),\n  alias_attr.set al () tt,\n  add_doc_string al doc\n\nmeta def make_left_right : name \u2192 tactic (name \u00d7 name)\n| (name.mk_string s p) := do\n  let buf : char_buffer := s.to_char_buffer,\n  sum.inr parts \u2190 pure $ run (sep_by1 (ch '_') (many_char (sat (\u2260 '_')))) s.to_char_buffer,\n  (left, _::right) \u2190 pure $ parts.span (\u2260 \"iff\"),\n  let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,\n  (suffix', right') \u2190 pure $ right.reverse.span (\u03bb s, pfx \"left\" s \u2228 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@[user_command] meta def alias_cmd (meta_info : decl_meta_info)\n  (_ : parse $ tk \"alias\") : lean.parser unit :=\ndo old \u2190 ident,\n  d \u2190 (do old \u2190 resolve_constant old, get_decl old) <|>\n    fail (\"declaration \" ++ to_string old ++ \" not found\"),\n  let doc := \u03bb al : name, meta_info.doc_string.get_or_else $\n    \"**Alias** of `\" ++ to_string old ++ \"`.\",\n  do {\n    tk \"\u2190\" <|> tk \"<-\",\n    aliases \u2190 many ident,\n    \u2191(aliases.mmap' $ \u03bb al, alias_direct d (doc al) al) } <|>\n  do {\n    tk \"\u2194\" <|> tk \"<->\",\n    (left, right) \u2190\n      mcond ((tk \".\" *> 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 (doc left) left `iff.mp,\n    alias_iff d (doc right) right `iff.mpr }\n\nmeta def get_lambda_body : expr \u2192 expr\n| (expr.lam _ _ _ b) := get_lambda_body b\n| a                  := a\n\nmeta def get_alias_target (n : name) : tactic (option name) :=\ndo attr \u2190 try_core (has_attribute `alias n),\n  option.cases_on attr (pure none) $ \u03bb_, do\n  d \u2190 get_decl n,\n  let (head, args) := (get_lambda_body d.value).get_app_fn_args,\n  let head := if head.is_constant_of `iff.mp \u2228 head.is_constant_of `iff.mpr then\n    expr.get_app_fn (head.ith_arg 2)\n  else head,\n  guardb $ head.is_constant,\n  pure $ head.const_name\n\nend tactic.alias\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/alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.09670579004193962, "lm_q1q2_score": 0.03651036864908692}}
{"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) \u00d7 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 : \u2200 {\u03b1 : Sort u} {a : \u03b1}, 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) \u00d7 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      \u2190 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 \u2190 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 \u2190\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 \u2190 h\n          return <| expr.const_name h \u2209 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 \u00acno_dflt \u2228 all_hyps then do\n        let ctx \u2190 local_context\n        -- Remove local exceptions specified in `hex`:\n            return <|\n            ctx fun h : expr => h \u2209 hex\n      else return []\n    let hs\n      \u2190-- 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 \u2190 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 \u2192 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 := \u03bb _, 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 \u2192 tactic Unit := fun _ => skip\n  pre_apply : tactic Unit := skip\n  discharger : tactic Unit := failed\n  max_depth : \u2115 := 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 : \u2115) (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 : \u2115) (e : expr) : tactic Unit := do\n  let pp \u2190 pp e\n  solve_by_elim_trace n f! \"\u2705 `{pp }` solves `\u22a2 {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 : \u2115) : tactic Unit :=\n  solve_by_elim_trace n f! \"\u274c failed to solve `\u22a2 {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 : \u2115) : tactic ((expr \u2192 tactic Unit) \u00d7 tactic Unit) :=\n  if is_trace_enabled_for `solve_by_elim then do\n    let g \u2190 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)) : \u2115 \u2192 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 \"\ud83d\uded1 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          \u2190 trace_hooks (opt - n)\n        let ctx_lemmas \u2190 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) \u00d7 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) \u2190 opt.get_lemma_thunks\n  (if opt then id else focus1) do\n      let gs \u2190 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 `... \u2192 \u2200 _, ... \u2192 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 \u2192 \u00ac 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 \u2190\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\u2081, h\u2082, ..., h\u1d63]` also applies the named lemmas.\n* `solve_by_elim with attr\u2081 ... attr\u1d63` also applies all lemmas tagged with the specified attributes.\n* `solve_by_elim only [h\u2081, h\u2082, ..., h\u1d63]` 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 \u2192 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) \u2190 mk_assumption_set no_dflt hs attr_names\n  tactic.solve_by_elim\n      { opt with\n        backtrack_all_goals := all_goals \u2228 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) 2014 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.Core\nimport Init.Control.Basic\nimport Init.Coe\n\nnamespace Option\n\ndef toMonad [Monad m] [Alternative m] : Option \u03b1 \u2192 m \u03b1\n  | none     => failure\n  | some a   => pure a\n\n@[inline] def toBool : Option \u03b1 \u2192 Bool\n  | some _ => true\n  | none   => false\n\n@[inline] def isSome : Option \u03b1 \u2192 Bool\n  | some _ => true\n  | none   => false\n\n@[inline] def isNone : Option \u03b1 \u2192 Bool\n  | some _ => false\n  | none   => true\n\n@[inline] def isEqSome [BEq \u03b1] : Option \u03b1 \u2192 \u03b1 \u2192 Bool\n  | some a, b => a == b\n  | none,   _ => false\n\n@[inline] protected def bind : Option \u03b1 \u2192 (\u03b1 \u2192 Option \u03b2) \u2192 Option \u03b2\n  | none,   _ => none\n  | some a, b => b a\n\n@[inline] protected def mapM [Monad m] (f : \u03b1 \u2192 m \u03b2) (o : Option \u03b1) : m (Option \u03b2) := do\n  if let some a := o then\n    return some (\u2190 f a)\n  else\n    return none\n\ntheorem map_id : (Option.map id : Option \u03b1 \u2192 Option \u03b1) = id :=\n  funext (fun o => match o with | none => rfl | some _ => rfl)\n\n@[always_inline, inline] protected def filter (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Option \u03b1\n  | some a => if p a then some a else none\n  | none   => none\n\n@[always_inline, inline] protected def all (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Bool\n  | some a => p a\n  | none   => true\n\n@[always_inline, inline] protected def any (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Bool\n  | some a => p a\n  | none   => false\n\n@[always_inline, macro_inline] protected def orElse : Option \u03b1 \u2192 (Unit \u2192 Option \u03b1) \u2192 Option \u03b1\n  | some a, _ => some a\n  | none,   b => b ()\n\ninstance : OrElse (Option \u03b1) where\n  orElse := Option.orElse\n\n@[inline] protected def lt (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Option \u03b1 \u2192 Option \u03b1 \u2192 Prop\n  | none, some _     => True\n  | some x,   some y => r x y\n  | _, _             => False\n\ninstance (r : \u03b1 \u2192 \u03b1 \u2192 Prop) [s : DecidableRel r] : DecidableRel (Option.lt r)\n  | none,   some _ => isTrue  trivial\n  | some x, some y => s x y\n  | some _, none   => isFalse not_false\n  | none,   none   => isFalse not_false\n\n/-- Take a pair of options and if they are both `some`, apply the given fn to produce an output.\nOtherwise act like `orElse`. -/\ndef merge (fn : \u03b1 \u2192 \u03b1 \u2192 \u03b1) : Option \u03b1 \u2192 Option \u03b1 \u2192 Option \u03b1\n  | none  , none   => none\n  | some x, none   => some x\n  | none  , some y => some y\n  | some x, some y => some <| fn x y\n\nend Option\n\nderiving instance DecidableEq for Option\nderiving instance BEq for Option\n\ninstance [LT \u03b1] : LT (Option \u03b1) where\n  lt := Option.lt (\u00b7 < \u00b7)\n\n@[always_inline]\ninstance : Functor Option where\n  map := Option.map\n\n@[always_inline]\ninstance : Monad Option where\n  pure := Option.some\n  bind := Option.bind\n\n@[always_inline]\ninstance : Alternative Option where\n  failure := Option.none\n  orElse  := Option.orElse\n\ndef liftOption [Alternative m] : Option \u03b1 \u2192 m \u03b1\n  | some a => pure a\n  | none   => failure\n\n@[always_inline, inline] protected def Option.tryCatch (x : Option \u03b1) (handle : Unit \u2192 Option \u03b1) : Option \u03b1 :=\n  match x with\n  | some _ => x\n  | none => handle ()\n\ninstance : MonadExceptOf Unit Option where\n  throw    := fun _ => Option.none\n  tryCatch := Option.tryCatch\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/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.08035747322699914, "lm_q1q2_score": 0.036422976816716544}}
{"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\u00f6lzl, 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 \u2192 Type v} {\u03b1 : 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 \u2192 Type v) : Type (max (u+1) v) :=\n(\u03b1 : Type u)\n(str : c \u03b1 . 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 \u2192 Type v} (\u03b1 : Type u) [str : c \u03b1] : bundled c := \u27e8\u03b1, str\u27e9\n\ninstance : has_coe_to_sort (bundled c) (Type u) := \u27e8bundled.\u03b1\u27e9\n\n@[simp] lemma coe_mk (\u03b1) (str) : (@bundled.mk c \u03b1 str : Type u) = \u03b1 := 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 \u27f6 S in Ring is really\na (semi)ring homomorphism from R.\u03b1 to S.\u03b1, and not merely from\n`(bundled.map @ring.to_semiring R).\u03b1` to `(bundled.map @ring.to_semiring S).\u03b1`.\n-/\n/-- Map over the bundled structure -/\n@[reducible] def map (f : \u03a0 {\u03b1}, c \u03b1 \u2192 d \u03b1) (b : bundled c) : bundled d :=\n\u27e8b, f b.str\u27e9\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 \u2243 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' : \u2200 {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 (\u03bb _, 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' := \u03bb 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 : \u2200 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 \u2192 B) (f_inv : B \u2192 A) (h : f' = \u21d1f) : MyIso A B :=\n{ toFun := f',\n  invFun := f_inv,\n  left_inv := h.symm \u25b8 f.left_inv,\n  right_inv := h.symm \u25b8 f.right_inv,\n  map_op' := h.symm \u25b8 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 (\u03bb _, 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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u03b1 \u03b2` expresses that terms of type `E` have an\ninjective coercion to bijections between `\u03b1` and `\u03b2`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `ZeroEquivClass`, `MulEquivClass`, `MonoidEquivClass`, ....\n-/\nclass EquivLike (E : Sort _) (\u03b1 \u03b2 : outParam (Sort _)) where\n  /-- The coercion to a function in the forward direction. -/\n  coe : E \u2192 \u03b1 \u2192 \u03b2\n  /-- The coercion to a function in the backwards direction. -/\n  inv : E \u2192 \u03b2 \u2192 \u03b1\n  /-- The coercions are left inverses. -/\n  left_inv : \u2200 e, Function.LeftInverse (inv e) (coe e)\n  /-- The coercions are right inverses. -/\n  right_inv : \u2200 e, Function.RightInverse (inv e) (coe e)\n  /-- If two coercions to functions are jointly injective. -/\n  coe_injective' : \u2200 e g, coe e = coe g \u2192 inv e = inv g \u2192 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 \u03b1 \u03b2 \u03b3 : Sort _} [iE : EquivLike E \u03b1 \u03b2] [iF : EquivLike F \u03b2 \u03b3]\n\ntheorem inv_injective : Function.Injective (EquivLike.inv : E \u2192 \u03b2 \u2192 \u03b1) := fun e g h \u21a6\n  coe_injective' e g ((right_inv e).eq_rightInverse (h.symm \u25b8 left_inv g)) h\n#align equiv_like.inv_injective EquivLike.inv_injective\n\ninstance (priority := 100) toEmbeddingLike : EmbeddingLike E \u03b1 \u03b2 where\n  coe := (coe : E \u2192 \u03b1 \u2192 \u03b2)\n  coe_injective' e g h :=\n    coe_injective' e g h ((left_inv e).eq_rightInverse (h.symm \u25b8 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 : \u03b1 \u2192 \u03b2) :=\n  \u27e8EquivLike.injective e, EquivLike.surjective e\u27e9\n#align equiv_like.bijective EquivLike.bijective\n\n\n\n@[simp]\ntheorem injective_comp (e : E) (f : \u03b2 \u2192 \u03b3) : Function.Injective (f \u2218 e) \u2194 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 : \u03b2 \u2192 \u03b3) : Function.Surjective (f \u2218 e) \u2194 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 : \u03b2 \u2192 \u03b3) : Function.Bijective (f \u2218 e) \u2194 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 : \u03b1) : 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 : \u03b2) : 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 : \u03b1 \u2192 \u03b2) (e : F) : Function.Injective (e \u2218 f) \u2194 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 : \u03b1 \u2192 \u03b2) (e : F) : Function.Surjective (e \u2218 f) \u2194 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 : \u03b1 \u2192 \u03b2) (e : F) : Function.Bijective (e \u2218 f) \u2194 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 \u03b2] : Subsingleton F :=\n\u27e8fun f g \u21a6 FunLike.ext f g $ fun _ \u21a6 (right_inv f).injective $ Subsingleton.elim _ _\u27e9\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<http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html>\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\u2080 u\u2081 v\u2080 v\u2081\n\nstructure MonadCont.Label (\u03b1 : Type w) (m : Type u \u2192 Type v) (\u03b2 : Type u) where\n  apply : \u03b1 \u2192 m \u03b2\n#align monad_cont.label MonadCont.Label\n\ndef MonadCont.goto {\u03b1 \u03b2} {m : Type u \u2192 Type v} (f : MonadCont.Label \u03b1 m \u03b2) (x : \u03b1) :=\n  f.apply x\n#align monad_cont.goto MonadCont.goto\n\nclass MonadCont (m : Type u \u2192 Type v) where\n  callCc : \u2200 {\u03b1 \u03b2}, (MonadCont.Label \u03b1 m \u03b2 \u2192 m \u03b1) \u2192 m \u03b1\n#align monad_cont MonadCont\n\nopen MonadCont\n\nclass IsLawfulMonadCont (m : Type u \u2192 Type v) [Monad m] [MonadCont m] extends LawfulMonad m where\n  callCc_bind_right {\u03b1 \u03c9 \u03b3} (cmd : m \u03b1) (next : Label \u03c9 m \u03b3 \u2192 \u03b1 \u2192 m \u03c9) :\n    (callCc fun f => cmd >>= next f) = cmd >>= fun x => callCc fun f => next f x\n  callCc_bind_left {\u03b1} (\u03b2) (x : \u03b1) (dead : Label \u03b1 m \u03b2 \u2192 \u03b2 \u2192 m \u03b1) :\n    (callCc fun f : Label \u03b1 m \u03b2 => goto f x >>= dead f) = pure x\n  callCc_dummy {\u03b1 \u03b2} (dummy : m \u03b1) : (callCc fun f : Label \u03b1 m \u03b2 => dummy) = dummy\n#align is_lawful_monad_cont IsLawfulMonadCont\n\nexport IsLawfulMonadCont ()\n\ndef ContT (r : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type w) :=\n  (\u03b1 \u2192 m r) \u2192 m r\n#align cont_t ContT\n\n@[reducible]\ndef Cont (r : Type u) (\u03b1 : Type w) :=\n  ContT r id \u03b1\n#align cont Cont\n\nnamespace ContT\n\nexport MonadCont (Label goto)\n\nvariable {r : Type u} {m : Type u \u2192 Type v} {\u03b1 \u03b2 \u03b3 \u03c9 : Type w}\n\ndef run : ContT r m \u03b1 \u2192 (\u03b1 \u2192 m r) \u2192 m r :=\n  id\n#align cont_t.run ContT.run\n\ndef map (f : m r \u2192 m r) (x : ContT r m \u03b1) : ContT r m \u03b1 :=\n  f \u2218 x\n#align cont_t.map ContT.map\n\ntheorem run_contT_map_contT (f : m r \u2192 m r) (x : ContT r m \u03b1) : run (map f x) = f \u2218 run x :=\n  rfl\n#align cont_t.run_cont_t_map_cont_t ContT.run_contT_map_contT\n\ndef withContT (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : ContT r m \u03b1) : ContT r m \u03b2 := fun g => x <| f g\n#align cont_t.with_cont_t ContT.withContT\n\ntheorem run_withContT (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : ContT r m \u03b1) :\n    run (withContT f x) = run x \u2218 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 \u03b1} (h : \u2200 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 \u03b1 x f := f x\n  bind \u03b1 \u03b2 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] {\u03b1} : m \u03b1 \u2192 ContT r m \u03b1 := fun x f => x >>= f\n#align cont_t.monad_lift ContT.monadLift\n\ninstance [Monad m] : HasMonadLift m (ContT r m) where monadLift \u03b1 := ContT.monadLift\n\ntheorem monadLift_bind [Monad m] [LawfulMonad m] {\u03b1 \u03b2} (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) :\n    (monadLift (x >>= f) : ContT r m \u03b2) = monadLift x >>= monadLift \u2218 f :=\n  by\n  ext\n  simp only [monad_lift, HasMonadLift.monadLift, (\u00b7 \u2218 \u00b7), (\u00b7 >>= \u00b7), 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 \u03b1 \u03b2 f g := f \u27e8fun x h => g x\u27e9 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 (\u03b5) [MonadExcept \u03b5 m] : MonadExcept \u03b5 (ContT r m)\n    where\n  throw x e f := throw e\n  catch \u03b1 act h f := catch (act f) fun e => h e f\n\ninstance : MonadRun (fun \u03b1 => (\u03b1 \u2192 m r) \u2192 ULift.{u, v} (m r)) (ContT.{u, v, u} r m)\n    where run \u03b1 f x := \u27e8f x\u27e9\n\nend ContT\n\nvariable {m : Type u \u2192 Type v} [Monad m]\n\ndef ExceptT.mkLabel {\u03b1 \u03b2 \u03b5} : Label (Except.{u, u} \u03b5 \u03b1) m \u03b2 \u2192 Label \u03b1 (ExceptT \u03b5 m) \u03b2\n  | \u27e8f\u27e9 => \u27e8fun a => monadLift <| f (Except.ok a)\u27e9\n#align except_t.mk_label ExceptT\u2093.mkLabel\n\ntheorem ExceptT.goto_mkLabel {\u03b1 \u03b2 \u03b5 : Type _} (x : Label (Except.{u, u} \u03b5 \u03b1) m \u03b2) (i : \u03b1) :\n    goto (ExceptT.mkLabel x) i = \u27e8Except.ok <$> goto x (Except.ok i)\u27e9 := by cases x <;> rfl\n#align except_t.goto_mk_label ExceptT\u2093.goto_mkLabel\n\ndef ExceptT.callCc {\u03b5} [MonadCont m] {\u03b1 \u03b2 : Type _} (f : Label \u03b1 (ExceptT \u03b5 m) \u03b2 \u2192 ExceptT \u03b5 m \u03b1) :\n    ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk (callCc fun x : Label _ m \u03b2 => ExceptT.run <| f (ExceptT.mkLabel x) : m (Except \u03b5 \u03b1))\n#align except_t.call_cc ExceptT\u2093.callCc\n\ninstance {\u03b5} [MonadCont m] : MonadCont (ExceptT \u03b5 m) where callCc \u03b1 \u03b2 := ExceptT.callCc\n\ninstance {\u03b5} [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (ExceptT \u03b5 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 \u27e8\u27e9 <;> 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 {\u03b1 \u03b2} : Label (Option.{u} \u03b1) m \u03b2 \u2192 Label \u03b1 (OptionT m) \u03b2\n  | \u27e8f\u27e9 => \u27e8fun a => monadLift <| f (some a)\u27e9\n#align option_t.mk_label OptionT\u2093.mkLabel\n\ntheorem OptionT.goto_mkLabel {\u03b1 \u03b2 : Type _} (x : Label (Option.{u} \u03b1) m \u03b2) (i : \u03b1) :\n    goto (OptionT.mkLabel x) i = \u27e8some <$> goto x (some i)\u27e9 := by cases x <;> rfl\n#align option_t.goto_mk_label OptionT\u2093.goto_mkLabel\n\ndef OptionT.callCc [MonadCont m] {\u03b1 \u03b2 : Type _} (f : Label \u03b1 (OptionT m) \u03b2 \u2192 OptionT m \u03b1) :\n    OptionT m \u03b1 :=\n  OptionT.mk (callCc fun x : Label _ m \u03b2 => OptionT.run <| f (OptionT.mkLabel x) : m (Option \u03b1))\n#align option_t.call_cc OptionT\u2093.callCc\n\ninstance [MonadCont m] : MonadCont (OptionT m) where callCc \u03b1 \u03b2 := 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 \u27e8\u27e9 <;> 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\u2093.mkLabel is a dubious translation:\nlean 3 declaration is\n  forall {m : Type.{u1} -> Type.{u2}} [_inst_1 : Monad.{u1, u2} m] {\u03b1 : Type.{u3}} {\u03b2 : Type.{u1}} {\u03c9 : Type.{u1}} [_inst_2 : One.{u1} \u03c9], (MonadCont.Label.{u1, u2, max u3 u1} (Prod.{u3, u1} \u03b1 \u03c9) m \u03b2) -> (MonadCont.Label.{u1, max u1 u2, u3} \u03b1 (WriterT\u2093.{u1, u2} \u03c9 m) \u03b2)\nbut is expected to have type\n  forall {m : Type.{u2} -> Type.{u3}} [_inst_1 : Monad.{u2, u3} m] {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} {\u03c9 : Type.{u2}} [_inst_2 : One.{u2} \u03c9], (MonadCont.Label.{u2, u3, max u1 u2} (Prod.{u1, u2} \u03b1 \u03c9) m \u03b2) -> (MonadCont.Label.{u2, max u2 u3, u1} \u03b1 (WriterT\u2093.{u2, u3} \u03c9 m) \u03b2)\nCase conversion may be inaccurate. Consider using '#align writer_t.mk_label WriterT\u2093.mkLabel\u2093'. -/\ndef WriterT.mkLabel {\u03b1 \u03b2 \u03c9} [One \u03c9] : Label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 Label \u03b1 (WriterT \u03c9 m) \u03b2\n  | \u27e8f\u27e9 => \u27e8fun a => monadLift <| f (a, 1)\u27e9\n#align writer_t.mk_label WriterT\u2093.mkLabel\n\ntheorem WriterT.goto_mkLabel {\u03b1 \u03b2 \u03c9 : Type _} [One \u03c9] (x : Label (\u03b1 \u00d7 \u03c9) m \u03b2) (i : \u03b1) :\n    goto (WriterT.mkLabel x) i = monadLift (goto x (i, 1)) := by cases x <;> rfl\n#align writer_t.goto_mk_label WriterT\u2093.goto_mkLabel\n\ndef WriterT.callCc [MonadCont m] {\u03b1 \u03b2 \u03c9 : Type _} [One \u03c9]\n    (f : Label \u03b1 (WriterT \u03c9 m) \u03b2 \u2192 WriterT \u03c9 m \u03b1) : WriterT \u03c9 m \u03b1 :=\n  \u27e8callCc (WriterT.run \u2218 f \u2218 WriterT.mkLabel : Label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 m (\u03b1 \u00d7 \u03c9))\u27e9\n#align writer_t.call_cc WriterT\u2093.callCc\n\ninstance (\u03c9) [Monad m] [One \u03c9] [MonadCont m] : MonadCont (WriterT \u03c9 m)\n    where callCc \u03b1 \u03b2 := WriterT.callCc\n\n/- warning: state_t.mk_label -> StateT\u2093.mkLabel is a dubious translation:\nlean 3 declaration is\n  forall {m : Type.{u1} -> Type.{u2}} [_inst_1 : Monad.{u1, u2} m] {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}} {\u03c3 : Type.{u1}}, (MonadCont.Label.{u1, u2, u1} (Prod.{u1, u1} \u03b1 \u03c3) m (Prod.{u1, u1} \u03b2 \u03c3)) -> (MonadCont.Label.{u1, max u1 u2, u1} \u03b1 (StateT\u2093.{u1, u2} \u03c3 m) \u03b2)\nbut is expected to have type\n  forall {m : Type.{u1} -> Type.{u2}} {_inst_1 : Type.{u1}} {\u03b1 : Type.{u1}} {\u03b2 : Type.{u1}}, (MonadCont.Label.{u1, u2, u1} (Prod.{u1, u1} _inst_1 \u03b2) m (Prod.{u1, u1} \u03b1 \u03b2)) -> (MonadCont.Label.{u1, max u1 u2, u1} _inst_1 (StateT\u2093.{u1, u2} \u03b2 m) \u03b1)\nCase conversion may be inaccurate. Consider using '#align state_t.mk_label StateT\u2093.mkLabel\u2093'. -/\ndef StateT.mkLabel {\u03b1 \u03b2 \u03c3 : Type u} : Label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3) \u2192 Label \u03b1 (StateT \u03c3 m) \u03b2\n  | \u27e8f\u27e9 => \u27e8fun a => \u27e8fun s => f (a, s)\u27e9\u27e9\n#align state_t.mk_label StateT\u2093.mkLabel\n\ntheorem StateT.goto_mkLabel {\u03b1 \u03b2 \u03c3 : Type u} (x : Label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) (i : \u03b1) :\n    goto (StateT.mkLabel x) i = \u27e8fun s => goto x (i, s)\u27e9 := by cases x <;> rfl\n#align state_t.goto_mk_label StateT\u2093.goto_mkLabel\n\ndef StateT.callCc {\u03c3} [MonadCont m] {\u03b1 \u03b2 : Type _} (f : Label \u03b1 (StateT \u03c3 m) \u03b2 \u2192 StateT \u03c3 m \u03b1) :\n    StateT \u03c3 m \u03b1 :=\n  \u27e8fun r => callCc fun f' => (f <| StateT.mkLabel f').run r\u27e9\n#align state_t.call_cc StateT\u2093.callCc\n\ninstance {\u03c3} [MonadCont m] : MonadCont (StateT \u03c3 m) where callCc \u03b1 \u03b2 := StateT.callCc\n\ninstance {\u03c3} [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (StateT \u03c3 m)\n    where\n  callCc_bind_right := by\n    intros\n    simp [call_cc, StateT.callCc, call_cc_bind_right, (\u00b7 >>= \u00b7), StateT.bind]\n    ext\n    dsimp\n    congr with \u27e8x\u2080, x\u2081\u27e9\n    rfl\n  callCc_bind_left := by\n    intros\n    simp [call_cc, StateT.callCc, call_cc_bind_left, (\u00b7 >>= \u00b7), 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, (\u00b7 >>= \u00b7), StateT.bind, @call_cc_dummy m _]\n    ext\n    rfl\n\n/- warning: reader_t.mk_label -> ReaderT\u2093.mkLabel is a dubious translation:\nlean 3 declaration is\n  forall {m : Type.{u1} -> Type.{u2}} [_inst_1 : Monad.{u1, u2} m] {\u03b1 : Type.{u3}} {\u03b2 : Type.{u1}} (\u03c1 : Type.{u1}), (MonadCont.Label.{u1, u2, u3} \u03b1 m \u03b2) -> (MonadCont.Label.{u1, max u1 u2, u3} \u03b1 (ReaderT\u2093.{u1, u2} \u03c1 m) \u03b2)\nbut is expected to have type\n  forall {m : Type.{u2} -> Type.{u3}} [_inst_1 : Monad.{u2, u3} m] {\u03b1 : Type.{u1}} {\u03b2 : Type.{u2}} (\u03c1 : Type.{u2}), (MonadCont.Label.{u2, u3, u1} \u03b1 m \u03b2) -> (MonadCont.Label.{u2, max u2 u3, u1} \u03b1 (ReaderT\u2093.{u2, u3} \u03c1 m) \u03b2)\nCase conversion may be inaccurate. Consider using '#align reader_t.mk_label ReaderT\u2093.mkLabel\u2093'. -/\ndef ReaderT.mkLabel {\u03b1 \u03b2} (\u03c1) : Label \u03b1 m \u03b2 \u2192 Label \u03b1 (ReaderT \u03c1 m) \u03b2\n  | \u27e8f\u27e9 => \u27e8monadLift \u2218 f\u27e9\n#align reader_t.mk_label ReaderT\u2093.mkLabel\n\ntheorem ReaderT.goto_mkLabel {\u03b1 \u03c1 \u03b2} (x : Label \u03b1 m \u03b2) (i : \u03b1) :\n    goto (ReaderT.mkLabel \u03c1 x) i = monadLift (goto x i) := by cases x <;> rfl\n#align reader_t.goto_mk_label ReaderT\u2093.goto_mkLabel\n\ndef ReaderT.callCc {\u03b5} [MonadCont m] {\u03b1 \u03b2 : Type _} (f : Label \u03b1 (ReaderT \u03b5 m) \u03b2 \u2192 ReaderT \u03b5 m \u03b1) :\n    ReaderT \u03b5 m \u03b1 :=\n  \u27e8fun r => callCc fun f' => (f <| ReaderT.mkLabel _ f').run r\u27e9\n#align reader_t.call_cc ReaderT\u2093.callCc\n\ninstance {\u03c1} [MonadCont m] : MonadCont (ReaderT \u03c1 m) where callCc \u03b1 \u03b2 := ReaderT.callCc\n\ninstance {\u03c1} [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (ReaderT \u03c1 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081} {\u03b1\u2081 r\u2081 : Type u\u2080}\n    {\u03b1\u2082 r\u2082 : Type u\u2081} (F : m\u2081 r\u2081 \u2243 m\u2082 r\u2082) (G : \u03b1\u2081 \u2243 \u03b1\u2082) : ContT r\u2081 m\u2081 \u03b1\u2081 \u2243 ContT r\u2082 m\u2082 \u03b1\u2082\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) 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.ProjFns\nimport Lean.Structure\nimport Lean.Meta.WHNF\nimport Lean.Meta.InferType\nimport Lean.Meta.FunInfo\nimport Lean.Meta.LevelDefEq\nimport Lean.Meta.Check\nimport Lean.Meta.Offset\nimport Lean.Meta.ForEachExpr\nimport Lean.Meta.UnificationHint\n\nnamespace Lean.Meta\n\n/--\n  Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`.\n\n  Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean.\n  Example:\n    ```\n    (fun x : A => f ?m) =?= f\n    ```\n    The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/\nprivate def isDefEqEta (a b : Expr) : MetaM Bool := do\n  if a.isLambda && !b.isLambda then\n    let bType \u2190 inferType b\n    let bType \u2190 whnfD bType\n    match bType with\n    | Expr.forallE n d _ c =>\n      let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0))\n      checkpointDefEq <| Meta.isExprDefEqAux a b'\n    | _ => pure false\n  else\n    pure false\n\n/-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/\ndef isDefEqNative (s t : Expr) : MetaM LBool := do\n  let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t\n  let s? \u2190 reduceNative? s\n  let t? \u2190 reduceNative? t\n  match s?, t? with\n  | some s, some t => isDefEq s t\n  | some s, none   => isDefEq s t\n  | none,   some t => isDefEq s t\n  | none,   none   => pure LBool.undef\n\n/-- Support for reducing Nat basic operations. -/\ndef isDefEqNat (s t : Expr) : MetaM LBool := do\n  let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t\n  if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then\n    pure LBool.undef\n  else\n    let s? \u2190 reduceNat? s\n    let t? \u2190 reduceNat? t\n    match s?, t? with\n    | some s, some t => isDefEq s t\n    | some s, none   => isDefEq s t\n    | none,   some t => isDefEq s t\n    | none,   none   => pure LBool.undef\n\n/-- Support for constraints of the form `(\"...\" =?= String.mk cs)` -/\ndef isDefEqStringLit (s t : Expr) : MetaM LBool := do\n  let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t\n  if s.isStringLit && t.isAppOf `String.mk then\n    isDefEq (toCtorIfLit s) t\n  else if s.isAppOf `String.mk && t.isStringLit then\n    isDefEq s (toCtorIfLit t)\n  else\n    pure LBool.undef\n\n/--\n  Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned.\n  Remark: `n` may be 0. -/\ndef isEtaUnassignedMVar (e : Expr) : MetaM Bool := do\n  match e.etaExpanded? with\n  | some (Expr.mvar mvarId _) =>\n    if (\u2190 isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then\n      pure false\n    else if (\u2190 isExprMVarAssigned mvarId) then\n      pure false\n    else\n      pure true\n  | _   => pure false\n\n/-\n  First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases\n  Here, we say a case is easy if it is of the form\n\n       ?m =?= t\n       or\n       t  =?= ?m\n\n  where `?m` is unassigned.\n\n  These easy cases are not just an optimization. When\n  `?m` is a function, by assigning it to t, we make sure\n  a unification constraint (in the explicit part)\n  ```\n  ?m t =?= f s\n  ```\n  is not higher-order.\n\n  We also handle the eta-expanded cases:\n  ```\n  fun x\u2081 ... x\u2099 => ?m x\u2081 ... x\u2099 =?= t\n  t =?= fun x\u2081 ... x\u2099 => ?m x\u2081 ... x\u2099\n  ```\n  This is important because type inference often produces\n  eta-expanded terms, and without this extra case, we could\n  introduce counter intuitive behavior.\n\n  Pre: `paramInfo.size <= args\u2081.size = args\u2082.size`\n-/\nprivate partial def isDefEqArgsFirstPass\n    (paramInfo : Array ParamInfo) (args\u2081 args\u2082 : Array Expr) : MetaM (Option (Array Nat)) := do\n  let rec loop (i : Nat) (postponed : Array Nat) := do\n    if h : i < paramInfo.size then\n      let info := paramInfo.get \u27e8i, h\u27e9\n      let a\u2081 := args\u2081[i]\n      let a\u2082 := args\u2082[i]\n      if info.implicit || info.instImplicit then\n        if (\u2190 isEtaUnassignedMVar a\u2081 <||> isEtaUnassignedMVar a\u2082) then\n          if (\u2190 Meta.isExprDefEqAux a\u2081 a\u2082) then\n            loop (i+1) postponed\n          else\n            pure none\n        else\n          loop (i+1) (postponed.push i)\n      else if (\u2190 Meta.isExprDefEqAux a\u2081 a\u2082) then\n        loop (i+1) postponed\n      else\n        pure none\n    else\n      pure (some postponed)\n  loop 0 #[]\n\n@[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do\n  let mvarId? \u2190 getStuckMVar? e\n  match mvarId? with\n  | some mvarId => Meta.synthPending mvarId\n  | none        => pure false\n\nprivate partial def isDefEqArgs (f : Expr) (args\u2081 args\u2082 : Array Expr) : MetaM Bool :=\n  if h : args\u2081.size = args\u2082.size then do\n    let finfo \u2190 getFunInfoNArgs f args\u2081.size\n    let (some postponed) \u2190 isDefEqArgsFirstPass finfo.paramInfo args\u2081 args\u2082 | pure false\n    let rec processOtherArgs (i : Nat) : MetaM Bool := do\n      if h\u2081 : i < args\u2081.size then\n        let a\u2081 := args\u2081.get \u27e8i, h\u2081\u27e9\n        let a\u2082 := args\u2082.get \u27e8i, Eq.subst h h\u2081\u27e9\n        if (\u2190 Meta.isExprDefEqAux a\u2081 a\u2082) then\n          processOtherArgs (i+1)\n        else\n          pure false\n      else\n        pure true\n    if (\u2190 processOtherArgs finfo.paramInfo.size) then\n      postponed.allM fun i => do\n        /- Second pass: unify implicit arguments.\n           In the second pass, we make sure we are unfolding at\n           least non reducible definitions (default setting). -/\n        let a\u2081   := args\u2081[i]\n        let a\u2082   := args\u2082[i]\n        let info := finfo.paramInfo[i]\n        if info.instImplicit then\n          discard <| trySynthPending a\u2081\n          discard <| trySynthPending a\u2082\n        withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a\u2081 a\u2082\n    else\n      pure false\n  else\n    pure false\n\n/--\n  Check whether the types of the free variables at `fvars` are\n  definitionally equal to the types at `ds\u2082`.\n\n  Pre: `fvars.size == ds\u2082.size`\n\n  This method also updates the set of local instances, and invokes\n  the continuation `k` with the updated set.\n\n  We can't use `withNewLocalInstances` because the `isDeq fvarType d\u2082`\n  may use local instances. -/\n@[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds\u2082 : Array Expr) (k : MetaM Bool) : MetaM Bool :=\n  let rec loop (i : Nat) := do\n    if h : i < fvars.size then do\n      let fvar := fvars.get \u27e8i, h\u27e9\n      let fvarDecl \u2190 getFVarLocalDecl fvar\n      let fvarType := fvarDecl.type\n      let d\u2082       := ds\u2082[i]\n      if (\u2190 Meta.isExprDefEqAux fvarType d\u2082) then\n        match (\u2190 isClass? fvarType) with\n        | some className => withNewLocalInstance className fvar <| loop (i+1)\n        | none           => loop (i+1)\n      else\n        pure false\n    else\n      k\n  loop 0\n\n/- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`.\n   It accumulates the new free variables in `fvars`, and declare them at `lctx`.\n   We use the domain types of `e\u2081` to create the new free variables.\n   We store the domain types of `e\u2082` at `ds\u2082`. -/\nprivate partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e\u2081 e\u2082 : Expr) (ds\u2082 : Array Expr) : MetaM Bool :=\n  let process (n : Name) (d\u2081 d\u2082 b\u2081 b\u2082 : Expr) : MetaM Bool := do\n    let d\u2081     := d\u2081.instantiateRev fvars\n    let d\u2082     := d\u2082.instantiateRev fvars\n    let fvarId \u2190 mkFreshId\n    let lctx   := lctx.mkLocalDecl fvarId n d\u2081\n    let fvars  := fvars.push (mkFVar fvarId)\n    isDefEqBindingAux lctx fvars b\u2081 b\u2082 (ds\u2082.push d\u2082)\n  match e\u2081, e\u2082 with\n  | Expr.forallE n d\u2081 b\u2081 _, Expr.forallE _ d\u2082 b\u2082 _ => process n d\u2081 d\u2082 b\u2081 b\u2082\n  | Expr.lam     n d\u2081 b\u2081 _, Expr.lam     _ d\u2082 b\u2082 _ => process n d\u2081 d\u2082 b\u2081 b\u2082\n  | _,                      _                      =>\n    withReader (fun ctx => { ctx with lctx := lctx }) do\n      isDefEqBindingDomain fvars ds\u2082 do\n        Meta.isExprDefEqAux (e\u2081.instantiateRev fvars) (e\u2082.instantiateRev fvars)\n\n@[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do\n  let lctx \u2190 getLCtx\n  isDefEqBindingAux lctx #[] a b #[]\n\nprivate def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool :=\n  traceCtx `Meta.isDefEq.assign.checkTypes do\n    if !mvar.isMVar then\n      trace[Meta.isDefEq.assign.final] \"metavariable expected at {mvar} := {v}\"\n      return false\n    else\n      -- must check whether types are definitionally equal or not, before assigning and returning true\n      let mvarType \u2190 inferType mvar\n      let vType \u2190 inferType v\n      if (\u2190 withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then\n        trace[Meta.isDefEq.assign.final] \"{mvar} := {v}\"\n        assignExprMVar mvar.mvarId! v\n        pure true\n      else\n        trace[Meta.isDefEq.assign.typeMismatch] \"{mvar} : {mvarType} := {v} : {vType}\"\n        pure false\n\n/--\n  Auxiliary method for solving constraints of the form `?m xs := v`.\n  It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`.\n  `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`.\n  For example, suppose we have `xs` of the form `#[a, c]` where\n  ```\n  a : Nat\n  b : Nat := f a\n  c : b = a\n  ```\n  In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`,\n  and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal\n  to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`.\n  Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type\n  `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`,\n  and may not even be type correct.\n  The issue here is that we are not capturing the `let`-declarations.\n\n  This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t.\n  some `x` in `xs` depends on `y`.\n  `ys` is the `xs` with these extra let-declarations included.\n\n  In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces\n  `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`.\n\n  Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations.\n\n  This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`.\n  where the index is the position in the local context.\n-/\nprivate partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do\n  if not (\u2190 hasLetDeclsInBetween) then\n    mkLambdaFVars xs v\n  else\n    let ys \u2190 addLetDeps\n    trace[Meta.debug] \"ys: {ys}, v: {v}\"\n    mkLambdaFVars ys v\n\nwhere\n  /- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`.\n     We use it a quick-check to avoid the more expensive collection procedure. -/\n  hasLetDeclsInBetween : MetaM Bool := do\n    let check (lctx : LocalContext) : Bool := do\n      let start := lctx.getFVar! xs[0] |>.index\n      let stop  := lctx.getFVar! xs.back |>.index\n      for i in [start+1:stop] do\n        match lctx.getAt? i with\n        | some localDecl =>\n          if localDecl.isLet then\n            return true\n        | _ => pure ()\n      return false\n    if xs.size <= 1 then\n      pure false\n    else\n      check (\u2190 getLCtx)\n\n  /- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(\u2190 read)`.\n     The context `Nat` is the position of `xs[0]` in the local context. -/\n  collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do\n    let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit :=\n      checkCache e fun _ => do\n        match e with\n        | Expr.forallE _ d b _   => visit d; visit b\n        | Expr.lam _ d b _       => visit d; visit b\n        | Expr.letE _ t v b _    => visit t; visit v; visit b\n        | Expr.app f a _         => visit f; visit a\n        | Expr.mdata _ b _       => visit b\n        | Expr.proj _ _ b _      => visit b\n        | Expr.fvar fvarId _     =>\n          let localDecl \u2190 getLocalDecl fvarId\n          if localDecl.isLet && localDecl.index > (\u2190 read) then\n            modify fun s => s.insert localDecl.fvarId\n        | _ => pure ()\n    visit (\u2190 instantiateMVars e) |>.run\n\n  /-\n    Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards.\n    The `Nat` argument is the current position in the local context being visited, and it is less than\n    or equal to the position of `xs.back` in the local context.\n    The `Nat` context `(\u2190 read)` is the position of `xs[0]` in the local context.\n  -/\n  collectLetDepsAux : Nat \u2192 ReaderT Nat (StateRefT NameHashSet MetaM) Unit\n    | 0   => return ()\n    | i+1 => do\n      if i+1 == (\u2190 read) then\n        return ()\n      else\n        match (\u2190 getLCtx).getAt? (i+1) with\n        | none => collectLetDepsAux i\n        | some localDecl =>\n          if (\u2190 get).contains localDecl.fvarId then\n            collectLetDeclsFrom localDecl.type\n            match localDecl.value? with\n            | some val => collectLetDeclsFrom val\n            | _ =>  pure ()\n          collectLetDepsAux i\n\n  /- Computes the set `ys`. It is a set of `FVarId`s, -/\n  collectLetDeps : MetaM NameHashSet := do\n    let lctx \u2190 getLCtx\n    let start := lctx.getFVar! xs[0] |>.index\n    let stop  := lctx.getFVar! xs.back |>.index\n    let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId!\n    let (_, s) \u2190 collectLetDepsAux stop |>.run start |>.run s\n    return s\n\n  /- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that\n     some `x` in `xs` depends on. -/\n  addLetDeps : MetaM (Array Expr) := do\n    let lctx \u2190 getLCtx\n    let s \u2190 collectLetDeps\n    /- Convert `s` into the array `ys` -/\n    let start := lctx.getFVar! xs[0] |>.index\n    let stop  := lctx.getFVar! xs.back |>.index\n    let mut ys := #[]\n    for i in [start:stop+1] do\n      match lctx.getAt? i with\n      | none => pure ()\n      | some localDecl =>\n        if s.contains localDecl.fvarId then\n          ys := ys.push localDecl.toExpr\n    return ys\n\n/-\n  Each metavariable is declared in a particular local context.\n  We use the notation `C |- ?m : t` to denote a metavariable `?m` that\n  was declared at the local context `C` with type `t` (see `MetavarDecl`).\n  We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`.\n\n  The following method process the unification constraint\n\n       ?m@C a\u2081 ... a\u2099 =?= t\n\n  We say the unification constraint is a pattern IFF\n\n    1) `a\u2081 ... a\u2099` are pairwise distinct free variables that are \u200b*not*\u200b let-variables.\n    2) `a\u2081 ... a\u2099` are not in `C`\n    3) `t` only contains free variables in `C` and/or `{a\u2081, ..., a\u2099}`\n    4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C`\n    5) `?m` does not occur in `t`\n\n  Claim: we don't have to check free variable declarations. That is,\n  if `t` contains a reference to `x : A := v`, we don't need to check `v`.\n  Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3).\n  If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`.\n  So, condition 4 and 5 are satisfied.\n\n  If the conditions above have been satisfied, then the\n  solution for the unification constrain is\n\n    ?m := fun a\u2081 ... a\u2099 => t\n\n  Now, we consider some workarounds/approximations.\n\n A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3)\n     (precise) solution: unfold `x` in `t`.\n\n A2) Suppose some `a\u1d62` is in `C` (failed condition 2)\n     (approximated) solution (when `config.ctxApprox` is set to true) :\n     ignore condition and also use\n\n        ?m := fun a\u2081 ... a\u2099 => t\n\n   Here is an example where this approximation fails:\n   Given `C` containing `a : nat`, consider the following two constraints\n         ?m@C a =?= a\n         ?m@C b =?= a\n\n   If we use the approximation in the first constraint, we get\n         ?m := fun x => x\n   when we apply this solution to the second one we get a failure.\n\n   IMPORTANT: When applying this approximation we need to make sure the\n   abstracted term `fun a\u2081 ... a\u2099 => t` is type correct. The check\n   can only be skipped in the pattern case described above. Consider\n   the following example. Given the local context\n\n      (\u03b1 : Type) (a : \u03b1)\n\n   we try to solve\n\n     ?m \u03b1 =?= @id \u03b1 a\n\n   If we use the approximation above we obtain:\n\n     ?m := (fun \u03b1' => @id \u03b1' a)\n\n   which is a type incorrect term. `a` has type `\u03b1` but it is expected to have\n   type `\u03b1'`.\n\n   The problem occurs because the right hand side contains a free variable\n   `a` that depends on the free variable `\u03b1` being abstracted. Note that\n   this dependency cannot occur in patterns.\n\n   We can address this by type checking\n   the term after abstraction. This is not a significant performance\n   bottleneck because this case doesn't happen very often in practice\n   (262 times when compiling stdlib on Jan 2018). The second example\n   is trickier, but it also occurs less frequently (8 times when compiling\n   stdlib on Jan 2018, and all occurrences were at Init/Control when\n   we define monads and auxiliary combinators for them).\n   We considered three options for the addressing the issue on the second example:\n\n A3) `a\u2081 ... a\u2099` are not pairwise distinct (failed condition 1).\n   In Lean3, we would try to approximate this case using an approach similar to A2.\n   However, this approximation complicates the code, and is never used in the\n   Lean3 stdlib and mathlib.\n\n A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`.\n   If `?m'` is assigned, we substitute.\n   If not, we create an auxiliary metavariable with a smaller scope.\n   Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step.\n\n A5) If some `a\u1d62` is not a free variable,\n     then we use first-order unification (if `config.foApprox` is set to true)\n\n       ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k\n\n   reduces to\n\n       ?M a_1 ... a_i =?= f\n       a_{i+1}        =?= b_1\n       ...\n       a_{i+k}        =?= b_k\n\n\n A6) If (m =?= v) is of the form\n\n        ?m a_1 ... a_n =?= ?m b_1 ... b_k\n\n     then we use first-order unification (if `config.foApprox` is set to true)\n\n A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form\n     ```\n     ?m s\u2081 ... s\u2099 =?= t\n     ```\n     where `s\u2081 ... s\u2099` are arbitrary terms. We solve them by assigning the constant function to `?m`.\n     ```\n     ?m := fun _ ... _ => t\n     ```\n\n     In general, this approximation may produce bad solutions, and may prevent coercions from being tried.\n     For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`.\n     In this situation, the\n     elaborator generates the unification constraint\n     ```\n     ?m Prop =?= IO Bool\n     ```\n     It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation\n     produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from\n     the decidable proposition `x > 0` to `Bool`.\n\n     On the other hand, the constant approximation is desirable for elaborating the term\n     ```\n     let f (x : _) := pure \"hello\"; f ()\n     ```\n     with expected type `IO String`.\n     In this example, the following unification contraint is generated.\n     ```\n     ?m () String =?= IO String\n     ```\n     It is not a higher-order pattern, first-order approximation reduces it to\n     ```\n     ?m () =?= IO\n     ```\n     which fails to be solved. However, constant approximation solves it by assigning\n     ```\n     ?m := fun _ => IO\n     ```\n     Note that `f`s type is `(x : ?\u03b1) -> ?m x String`. The metavariable `?m` may depend on `x`.\n     If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide\n     whether we should apply it or not. The heuristic is based on observing where the constraints above come from.\n     In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to\n     be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model\n     a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f`\n     does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected\n     by any functional programmer used to non-dependently type languages (e.g., Haskell).\n     We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks\n     how many metavariable arguments are representing dependencies.\n-/\n\ndef mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do\n  mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs\n\nnamespace CheckAssignment\n\nbuiltin_initialize checkAssignmentExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `checkAssignment\nbuiltin_initialize outOfScopeExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `outOfScope\n\nstructure State where\n  cache : ExprStructMap Expr := {}\n\nstructure Context where\n  mvarId        : MVarId\n  mvarDecl      : MetavarDecl\n  fvars         : Array Expr\n  hasCtxLocals  : Bool\n  rhs           : Expr\n\nabbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM\n\ndef throwCheckAssignmentFailure : CheckAssignmentM \u03b1 :=\n  throw <| Exception.internal checkAssignmentExceptionId\n\ndef throwOutOfScopeFVar : CheckAssignmentM \u03b1 :=\n  throw <| Exception.internal outOfScopeExceptionId\n\nprivate def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do\n  return (\u2190 get).cache.find? e\n\nprivate def cache (e r : Expr) : CheckAssignmentM Unit := do\n  modify fun s => { s with cache := s.cache.insert e r }\n\ninstance : MonadCache Expr Expr CheckAssignmentM where\n  findCached? := findCached?\n  cache       := cache\n\n@[inline] private def visit (f : Expr \u2192 CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr :=\n  if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e)\n\nprivate def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do\n  let ctx \u2190 read\n  return m!\"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}\"\n\n@[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context }\n  let x : CheckAssignmentM (Option Expr) :=\n    catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId]\n      (do let e \u2190 x; return some e)\n      (fun _ => pure none)\n  x.run ctx |>.run' {}\n\nmutual\n\n  partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do\n    let ctxMeta \u2190 readThe Meta.Context\n    let ctx \u2190 read\n    if ctx.mvarDecl.lctx.containsFVar fvar then\n      pure fvar\n    else\n      let lctx := ctxMeta.lctx\n      match lctx.findFVar? fvar with\n      | some (LocalDecl.ldecl (value := v) ..) => visit check v\n      | _ =>\n        if ctx.fvars.contains fvar then pure fvar\n        else\n          traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar\n          throwOutOfScopeFVar\n\n  partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do\n    let mvarId := mvar.mvarId!\n    let ctx  \u2190 read\n    let mctx \u2190 getMCtx\n    if mvarId == ctx.mvarId then\n      traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo \"occurs check failed\"\n      throwCheckAssignmentFailure\n    else match mctx.getExprAssignment? mvarId with\n      | some v => check v\n      | none   =>\n        match mctx.findDecl? mvarId with\n        | none          => throwUnknownMVar mvarId\n        | some mvarDecl =>\n          if ctx.hasCtxLocals then\n            throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification\n          else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then\n            /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned.\n               We \"substract\" variables being abstracted because we use `elimMVarDeps` -/\n            pure mvar\n          else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then\n            traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId)\n            throwCheckAssignmentFailure\n          else\n            let ctxMeta \u2190 readThe Meta.Context\n            if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then\n              /- Create an auxiliary metavariable with a smaller context and \"checked\" type.\n                 Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains\n                 a metavariable that we also need to reduce the context.\n\n                 We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx`\n                 or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because\n                 `elimMVarDeps` will take care of them.\n\n                 First, we collect `toErase` the variables that need to be erased.\n                 Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`,\n                 we must also erase it.\n              -/\n              let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl =>\n                if ctx.mvarDecl.lctx.contains localDecl.fvarId then\n                  toErase\n                else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then\n                  if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then\n                    -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too\n                    toErase.push localDecl.fvarId\n                  else\n                    toErase\n                else\n                  toErase.push localDecl.fvarId\n              let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar =>\n                lctx.erase toEraseFVar\n              /- Compute new set of local instances. -/\n              let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId!\n              let mvarType \u2190 check mvarDecl.type\n              let newMVar \u2190 mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs\n              modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar }\n              pure newMVar\n            else\n              traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId)\n              throwCheckAssignmentFailure\n\n  /-\n    Auxiliary function used to \"fix\" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables,\n    and one of them is out-of-scope.\n    See `Expr.app` case at `check`.\n    If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope,\n    an assigning `?m := fun _ ... _ => ?n` -/\n  partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do\n    let mvarType \u2190 inferType mvar\n    forallBoundedTelescope mvarType numArgs fun xs _ => do\n      if xs.size != numArgs then pure false\n      else\n        let some v \u2190 mkLambdaFVarsWithLetDeps xs newMVar | return false\n        match (\u2190 checkAssignmentAux mvar.mvarId! #[] false v) with\n        | some v => checkTypesAndAssign mvar v\n        | none   => return false\n\n  -- See checkAssignment\n  partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do\n    run (check v) mvarId fvars hasCtxLocals v\n\n  partial def checkApp (e : Expr) : CheckAssignmentM Expr :=\n    e.withApp fun f args => do\n      let ctxMeta \u2190 readThe Meta.Context\n      if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then\n        let f \u2190 visit checkMVar f\n        catchInternalId outOfScopeExceptionId\n          (do\n            let args \u2190 args.mapM (visit check)\n            return mkAppN f args)\n          (fun ex => do\n            if !f.isMVar then\n              throw ex\n            else if (\u2190 isDelayedAssigned f.mvarId!) then\n              throw ex\n            else\n              let eType \u2190 inferType e\n              let mvarType \u2190 check eType\n              /- Create an auxiliary metavariable with a smaller context and \"checked\" type, assign `?f := fun _ => ?newMVar`\n                    Note that `mvarType` may be different from `eType`. -/\n              let ctx \u2190 read\n              let newMVar \u2190 mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType\n              if (\u2190 assignToConstFun f args.size newMVar) then\n                pure newMVar\n              else\n                throw ex)\n      else\n        let f \u2190 visit check f\n        let args \u2190 args.mapM (visit check)\n        return mkAppN f args\n\n  partial def check (e : Expr) : CheckAssignmentM Expr := do\n    match e with\n    | Expr.mdata _ b _     => return e.updateMData! (\u2190 visit check b)\n    | Expr.proj _ _ s _    => return e.updateProj! (\u2190 visit check s)\n    | Expr.lam _ d b _     => return e.updateLambdaE! (\u2190 visit check d) (\u2190 visit check b)\n    | Expr.forallE _ d b _ => return e.updateForallE! (\u2190 visit check d) (\u2190 visit check b)\n    | Expr.letE _ t v b _  => return e.updateLet! (\u2190 visit check t) (\u2190 visit check v) (\u2190 visit check b)\n    | Expr.bvar ..         => return e\n    | Expr.sort ..         => return e\n    | Expr.const ..        => return e\n    | Expr.lit ..          => return e\n    | Expr.fvar ..         => visit checkFVar e\n    | Expr.mvar ..         => visit checkMVar e\n    | Expr.app ..          =>\n      checkApp e\n      -- TODO: investigate whether the following feature is too expensive or not\n      /-\n      catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId]\n        (checkApp e)\n        fun ex => do\n          let e' \u2190 whnfR e\n          if e != e' then\n            check e'\n          else\n            throw ex\n      -/\nend\n\nend CheckAssignment\n\nnamespace CheckAssignmentQuick\n\npartial def check\n    (hasCtxLocals ctxApprox : Bool)\n    (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool :=\n  let rec visit (e : Expr) : Bool :=\n    if !e.hasExprMVar && !e.hasFVar then\n      true\n    else match e with\n    | Expr.mdata _ b _     => visit b\n    | Expr.proj _ _ s _    => visit s\n    | Expr.app f a _       => visit f && visit a\n    | Expr.lam _ d b _     => visit d && visit b\n    | Expr.forallE _ d b _ => visit d && visit b\n    | Expr.letE _ t v b _  => visit t && visit v && visit b\n    | Expr.bvar ..         => true\n    | Expr.sort ..         => true\n    | Expr.const ..        => true\n    | Expr.lit ..          => true\n    | Expr.fvar fvarId ..  =>\n      if mvarDecl.lctx.contains fvarId then true\n      else match lctx.find? fvarId with\n        | some (LocalDecl.ldecl (value := v) ..) => false -- need expensive CheckAssignment.check\n        | _ =>\n          if fvars.any fun x => x.fvarId! == fvarId then true\n          else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it\n    | Expr.mvar mvarId' _  =>\n      match mctx.getExprAssignment? mvarId' with\n      | some _ => false -- use CheckAssignment.check to instantiate\n      | none   =>\n        if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception\n        else match mctx.findDecl? mvarId' with\n          | none           => false\n          | some mvarDecl' =>\n            if hasCtxLocals then false -- use CheckAssignment.check\n            else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true\n            else false -- use CheckAssignment.check\n  visit e\n\nend CheckAssignmentQuick\n\n/--\n  Auxiliary function for handling constraints of the form `?m a\u2081 ... a\u2099 =?= v`.\n  It will check whether we can perform the assignment\n  ```\n  ?m := fun fvars => v\n  ```\n  The result is `none` if the assignment can't be performed.\n  The result is `some newV` where `newV` is a possibly updated `v`. This method may need\n  to unfold let-declarations. -/\ndef checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do\n  /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none`\n     to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/\n  for fvar in fvars do\n    unless (\u2190 occursCheck mvarId (\u2190 inferType fvar)) do\n      return none\n  if !v.hasExprMVar && !v.hasFVar then\n    pure (some v)\n  else\n    let mvarDecl \u2190 getMVarDecl mvarId\n    let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar\n    let ctx \u2190 read\n    let mctx \u2190 getMCtx\n    if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then\n      pure (some v)\n    else\n      let v \u2190 instantiateMVars v\n      CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v\n\nprivate def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=\n  match v with\n  | Expr.app f a _ =>\n    if args.isEmpty then\n      pure false\n    else\n      Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f\n  | _              => pure false\n\n/-\n  Auxiliary method for applying first-order unification. It is an approximation.\n  Remark: this method is trying to solve the unification constraint:\n\n      ?m a\u2081 ... a\u2099 =?= v\n\n   It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`.\n\n   We have added support for unfolding here because we want to be able to solve unification problems such as\n\n      ?m Unit =?= ITactic\n\n   where `ITactic` is defined as\n\n   def ITactic := Tactic Unit\n-/\nprivate partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=\n  let rec loop (v : Expr) := do\n    let cfg \u2190 getConfig\n    if !cfg.foApprox then\n      pure false\n    else\n      trace[Meta.isDefEq.foApprox] \"{mvar} {args} := {v}\"\n      let v := v.headBeta\n      if (\u2190 checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then\n        pure true\n      else\n        match (\u2190 unfoldDefinition? v) with\n        | none   => pure false\n        | some v => loop v\n  loop v\n\nprivate partial def simpAssignmentArgAux : Expr \u2192 MetaM Expr\n  | Expr.mdata _ e _       => simpAssignmentArgAux e\n  | e@(Expr.fvar fvarId _) => do\n    let decl \u2190 getLocalDecl fvarId\n    match decl.value? with\n    | some value => simpAssignmentArgAux value\n    | _          => pure e\n  | e => pure e\n\n/- Auxiliary procedure for processing `?m a\u2081 ... a\u2099 =?= v`.\n   We apply it to each `a\u1d62`. It instantiates assigned metavariables if `a\u1d62` is of the form `f[?n] b\u2081 ... b\u2098`,\n   and then removes metadata, and zeta-expand let-decls. -/\nprivate def simpAssignmentArg (arg : Expr) : MetaM Expr := do\n  let arg \u2190 if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg\n  simpAssignmentArgAux arg\n\n/- Assign `mvar := fun a_1 ... a_{numArgs} => v`.\n   We use it at `processConstApprox` and `isDefEqMVarSelf` -/\nprivate def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do\n  let mvarDecl \u2190 getMVarDecl mvar.mvarId!\n  forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do\n    if xs.size != numArgs then\n      pure false\n    else\n      let some v \u2190 mkLambdaFVarsWithLetDeps xs v | pure false\n      match (\u2190 checkAssignment mvar.mvarId! #[] v) with\n      | none   => pure false\n      | some v =>\n        trace[Meta.isDefEq.constApprox] \"{mvar} := {v}\"\n        checkTypesAndAssign mvar v\n\nprivate def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do\n  let cfg \u2190 getConfig\n  let mvarId := mvar.mvarId!\n  let mvarDecl \u2190 getMVarDecl mvarId\n  if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then\n    assignConst mvar numArgs v\n  else\n    pure false\n\n/-- Tries to solve `?m a\u2081 ... a\u2099 =?= v` by assigning `?m`.\n    It assumes `?m` is unassigned. -/\nprivate partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool :=\n  traceCtx `Meta.isDefEq.assign do\n    trace[Meta.isDefEq.assign] \"{mvarApp} := {v}\"\n    let mvar := mvarApp.getAppFn\n    let mvarDecl \u2190 getMVarDecl mvar.mvarId!\n    let rec process (i : Nat) (args : Array Expr) (v : Expr) := do\n      let cfg \u2190 getConfig\n      let useFOApprox (args : Array Expr) : MetaM Bool :=\n        processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v\n      if h : i < args.size then\n        let arg := args.get \u27e8i, h\u27e9\n        let arg \u2190 simpAssignmentArg arg\n        let args := args.set \u27e8i, h\u27e9 arg\n        match arg with\n        | Expr.fvar fvarId _ =>\n          if args[0:i].any fun prevArg => prevArg == arg then\n            useFOApprox args\n          else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then\n            useFOApprox args\n          else\n            process (i+1) args v\n        | _ =>\n          useFOApprox args\n      else\n        let v \u2190 instantiateMVars v -- enforce A4\n        if v.getAppFn == mvar then\n          -- using A6\n          useFOApprox args\n        else\n          let mvarId := mvar.mvarId!\n          match (\u2190 checkAssignment mvarId args v) with\n          | none   => useFOApprox args\n          | some v => do\n            trace[Meta.isDefEq.assign.beforeMkLambda] \"{mvar} {args} := {v}\"\n            let some v \u2190 mkLambdaFVarsWithLetDeps args v | return false\n            if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then\n              /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced\n                 a type incorrect term. See discussion at A2 -/\n              if (\u2190 isTypeCorrect v) then\n                checkTypesAndAssign mvar v\n              else\n                trace[Meta.isDefEq.assign.typeError] \"{mvar} := {v}\"\n                useFOApprox args\n            else\n              checkTypesAndAssign mvar v\n    process 0 mvarApp.getAppArgs v\n\n/--\n  Similar to processAssignment, but if it fails, compute v's whnf and try again.\n  This helps to solve constraints such as `?m =?= { \u03b1 := ?m, ... }.\u03b1`\n  Note this is not perfect solution since we still fail occurs check for constraints such as\n  ```lean\n    ?m =?= List { \u03b1 := ?m, \u03b2 := Nat }.\u03b2\n  ```\n-/\nprivate def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do\n  if (\u2190 processAssignment mvarApp v) then\n    return true\n  else\n    let vNew \u2190 whnf v\n    if vNew != v then\n      if mvarApp == vNew then\n        return true\n      else\n        processAssignment mvarApp vNew\n    else\n      return false\n\nprivate def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do\n  match t.getAppFn with\n  | Expr.const c _ _ =>\n    match (\u2190 getConst? c) with\n    | r@(some info) => if info.hasValue then return r else return none\n    | _             => return none\n  | _ => pure none\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isListLevelDefEq (us vs : List Level) : MetaM LBool :=\n  toLBoolM <| isListLevelDefEqAux us vs\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do\n  trace[Meta.isDefEq.delta.unfoldLeft] fn\n  toLBoolM <| Meta.isExprDefEqAux t s\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do\n  trace[Meta.isDefEq.delta.unfoldRight] fn\n  toLBoolM <| Meta.isExprDefEqAux t s\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do\n  trace[Meta.isDefEq.delta.unfoldLeftRight] fn\n  toLBoolM <| Meta.isExprDefEqAux t s\n\n/-- Try to solve `f a\u2081 ... a\u2099 =?= f b\u2081 ... b\u2099` by solving `a\u2081 =?= b\u2081, ..., a\u2099 =?= b\u2099`.\n\n    Auxiliary method for isDefEqDelta -/\nprivate def tryHeuristic (t s : Expr) : MetaM Bool :=\n  let tFn := t.getAppFn\n  let sFn := s.getAppFn\n  traceCtx `Meta.isDefEq.delta do\n    /-\n      We process arguments before universe levels to reduce a source of brittleness in the TC procedure.\n\n      In the TC procedure, we can solve problems containing metavariables.\n      If the TC procedure tries to assign one of these metavariables, it interrupts the search\n      using a \"stuck\" exception. The elaborator catches it, and \"interprets\" it as \"we should try again later\".\n      Now suppose we have a TC problem, and there are two \"local\" candidate instances we can try: \"bad\" and \"good\".\n      The \"bad\" candidate is stuck because of a universe metavariable in the TC problem.\n      If we try \"bad\" first, the TC procedure is interrupted. Moreover, if we have ignored the exception,\n      \"bad\" would fail anyway trying to assign two different free variables `\u03b1 =?= \u03b2`.\n      Example: `Preorder.{?u} \u03b1 =?= Preorder.{?v} \u03b2`, where `?u` and `?v` are universe metavariables that were\n      not created by the TC procedure.\n      The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the \"stuck\" exception,\n      but it would have failed anyway if we had continued processing it.\n      By solving the arguments first, we make the example above fail without throwing the \"stuck\" exception.\n\n      TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag.\n      Then the entry-point for `isDefEq` checks the flag before returning `true`.\n    -/\n    checkpointDefEq do\n      let b \u2190 isDefEqArgs tFn t.getAppArgs s.getAppArgs\n              <&&>\n              isListLevelDefEqAux tFn.constLevels! sFn.constLevels!\n      unless b do\n        trace[Meta.isDefEq.delta] \"heuristic failed {t} =?= {s}\"\n      pure b\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate abbrev unfold (e : Expr) (failK : MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  match (\u2190 unfoldDefinition? e) with\n  | some e => successK e\n  | none   => failK\n\n/-- Auxiliary method for isDefEqDelta -/\nprivate def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do\n  match t, s with\n  | Expr.const _ ls\u2081 _, Expr.const _ ls\u2082 _ => isListLevelDefEq ls\u2081 ls\u2082\n  | Expr.app _ _ _,     Expr.app _ _ _     =>\n    if (\u2190 tryHeuristic t s) then\n      pure LBool.true\n    else\n      unfold t\n       (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s))\n       (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))\n  | _, _ => pure LBool.false\n\nprivate def sameHeadSymbol (t s : Expr) : Bool :=\n  match t.getAppFn, s.getAppFn with\n  | Expr.const c\u2081 _ _, Expr.const c\u2082 _ _ => true\n  | _,                 _                 => false\n\n/--\n  - If headSymbol (unfold t) == headSymbol s, then unfold t\n  - If headSymbol (unfold s) == headSymbol t, then unfold s\n  - Otherwise unfold t and s if possible.\n\n  Auxiliary method for isDefEqDelta -/\nprivate def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=\n  unfold t\n    (unfold s\n      (pure LBool.undef) -- `t` and `s` failed to be unfolded\n      (fun s => isDefEqRight sInfo.name t s))\n    (fun tNew =>\n      if sameHeadSymbol tNew s then\n        isDefEqLeft tInfo.name tNew s\n      else\n        unfold s\n          (isDefEqLeft tInfo.name tNew s)\n          (fun sNew =>\n            if sameHeadSymbol t sNew then\n              isDefEqRight sInfo.name t sNew\n            else\n              isDefEqLeftRight tInfo.name tNew sNew))\n\n/-- If `t` and `s` do not contain metavariables, then use\n    kernel definitional equality heuristics.\n    Otherwise, use `unfoldComparingHeadsDefEq`.\n\n    Auxiliary method for isDefEqDelta -/\nprivate def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=\n  if !t.hasExprMVar && !s.hasExprMVar then\n    /- If `t` and `s` do not contain metavariables,\n       we simulate strategy used in the kernel. -/\n    if tInfo.hints.lt sInfo.hints then\n      unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s\n    else if sInfo.hints.lt tInfo.hints then\n      unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s\n    else\n      unfoldComparingHeadsDefEq tInfo sInfo t s\n  else\n    unfoldComparingHeadsDefEq tInfo sInfo t s\n\n/--\n  When `TransparencyMode` is set to `default` or `all`.\n  If `t` is reducible and `s` is not ==> `isDefEqLeft  (unfold t) s`\n  If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)`\n\n  Otherwise, use `unfoldDefEq`\n\n  Auxiliary method for isDefEqDelta -/\nprivate def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do\n  if (\u2190 shouldReduceReducibleOnly) then\n    unfoldDefEq tInfo sInfo t s\n  else\n    let tReducible \u2190 isReducible tInfo.name\n    let sReducible \u2190 isReducible sInfo.name\n    if tReducible && !sReducible then\n      unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s\n    else if !tReducible && sReducible then\n      unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s\n    else\n      unfoldDefEq tInfo sInfo t s\n\n/--\n  If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)`\n  If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s`\n\n  Otherwise, use `unfoldReducibeDefEq`\n\n  Auxiliary method for isDefEqDelta -/\nprivate def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do\n  let tProj? \u2190 isProjectionFn tInfo.name\n  let sProj? \u2190 isProjectionFn sInfo.name\n  if tProj? && !sProj? then\n    unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s\n  else if !tProj? && sProj? then\n    unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s\n  else\n    unfoldReducibeDefEq tInfo sInfo t s\n\n/--\n  isDefEq by lazy delta reduction.\n  This method implements many different heuristics:\n  1- If only `t` can be unfolded => then unfold `t` and continue\n  2- If only `s` can be unfolded => then unfold `s` and continue\n  3- If `t` and `s` can be unfolded and they have the same head symbol, then\n     a) First try to solve unification by unifying arguments.\n     b) If it fails, unfold both and continue.\n     Implemented by `unfoldBothDefEq`\n  4- If `t` is a projection function application and `s` is not => then unfold `s` and continue.\n  5- If `s` is a projection function application and `t` is not => then unfold `t` and continue.\n  Remark: 4&5 are implemented by `unfoldNonProjFnDefEq`\n  6- If `t` is reducible and `s` is not => then unfold `t` and continue.\n  7- If `s` is reducible and `t` is not => then unfold `s` and continue\n  Remark: 6&7 are implemented by `unfoldReducibeDefEq`\n  8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel.\n     Implemented by `unfoldDefEq`\n  9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue.\n  10- If `headSymbol (unfold s) == headSymbol t`, then unfold s\n  11- Otherwise, unfold `t` and `s` and continue.\n  Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/\nprivate def isDefEqDelta (t s : Expr) : MetaM LBool := do\n  let tInfo? \u2190 isDeltaCandidate? t.getAppFn\n  let sInfo? \u2190 isDeltaCandidate? s.getAppFn\n  match tInfo?, sInfo? with\n  | none,       none       => pure LBool.undef\n  | some tInfo, none       => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s\n  | none,       some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s\n  | some tInfo, some sInfo =>\n    if tInfo.name == sInfo.name then\n      unfoldBothDefEq tInfo.name t s\n    else\n      unfoldNonProjFnDefEq tInfo sInfo t s\n\nprivate def isAssigned : Expr \u2192 MetaM Bool\n  | Expr.mvar mvarId _ => isExprMVarAssigned mvarId\n  | _                  => pure false\n\nprivate def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do\n  match tFn with\n  | Expr.mvar mvarId _ =>\n    if (\u2190 isDelayedAssigned mvarId) then\n      let tNew \u2190 instantiateMVars t\n      return tNew != t\n    else\n      pure false\n  | _ => pure false\n\nprivate def isSynthetic : Expr \u2192 MetaM Bool\n  | Expr.mvar mvarId _ => do\n    let mvarDecl \u2190 getMVarDecl mvarId\n    match mvarDecl.kind with\n    | MetavarKind.synthetic       => pure true\n    | MetavarKind.syntheticOpaque => pure true\n    | MetavarKind.natural         => pure false\n  | _                  => pure false\n\nprivate def isAssignable : Expr \u2192 MetaM Bool\n  | Expr.mvar mvarId _ => do let b \u2190 isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b)\n  | _                  => pure false\n\nprivate def etaEq (t s : Expr) : Bool :=\n  match t.etaExpanded? with\n  | some t => t == s\n  | none   => false\n\nprivate def isLetFVar (fvarId : FVarId) : MetaM Bool := do\n  let decl \u2190 getLocalDecl fvarId\n  pure decl.isLet\n\nprivate def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do\n  if (\u2190 getConfig).proofIrrelevance then\n    let status \u2190 isProofQuick t\n    match status with\n    | LBool.false =>\n      pure LBool.undef\n    | LBool.true  =>\n      let tType \u2190 inferType t\n      let sType \u2190 inferType s\n      toLBoolM <| Meta.isExprDefEqAux tType sType\n    | LBool.undef =>\n      let tType \u2190 inferType t\n      if (\u2190 isProp tType) then\n        let sType \u2190 inferType s\n        toLBoolM <| Meta.isExprDefEqAux tType sType\n      else\n        pure LBool.undef\n  else\n    pure LBool.undef\n\n/- Try to solve constraint of the form `?m args\u2081 =?= ?m args\u2082`.\n   - First try to unify `args\u2081` and `args\u2082`, and return true if successful\n   - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n`\n     where `?n` is a fresh metavariable. See `processConstApprox`. -/\nprivate def isDefEqMVarSelf (mvar : Expr) (args\u2081 args\u2082 : Array Expr) : MetaM Bool := do\n  if args\u2081.size != args\u2082.size then\n    pure false\n  else if (\u2190 isDefEqArgs mvar args\u2081 args\u2082) then\n    pure true\n  else if !(\u2190 isAssignable mvar) then\n    pure false\n  else\n    let cfg \u2190 getConfig\n    let mvarId := mvar.mvarId!\n    let mvarDecl \u2190 getMVarDecl mvarId\n    if mvarDecl.numScopeArgs == args\u2081.size || cfg.constApprox then\n      let type \u2190 inferType (mkAppN mvar args\u2081)\n      let auxMVar \u2190 mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type\n      assignConst mvar args\u2081.size auxMVar\n    else\n      pure false\n\n/- Remove unnecessary let-decls -/\nprivate def consumeLet : Expr \u2192 Expr\n  | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b\n  | e                       => e\n\nmutual\n\nprivate partial def isDefEqQuick (t s : Expr) : MetaM LBool :=\n  let t := consumeLet t\n  let s := consumeLet s\n  match t, s with\n  | Expr.lit  l\u2081 _,      Expr.lit l\u2082 _       => return (l\u2081 == l\u2082).toLBool\n  | Expr.sort u _,       Expr.sort v _       => toLBoolM <| isLevelDefEqAux u v\n  | Expr.lam ..,         Expr.lam ..         => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s\n  | Expr.forallE ..,     Expr.forallE ..     => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s\n  | Expr.mdata _ t _,    s                   => isDefEqQuick t s\n  | t,                   Expr.mdata _ s _    => isDefEqQuick t s\n  | Expr.fvar fvarId\u2081 _, Expr.fvar fvarId\u2082 _ => do\n    if (\u2190 isLetFVar fvarId\u2081 <||> isLetFVar fvarId\u2082) then\n      pure LBool.undef\n    else if fvarId\u2081 == fvarId\u2082 then\n      pure LBool.true\n    else\n      isDefEqProofIrrel t s\n  | t, s =>\n    isDefEqQuickOther t s\n\nprivate partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do\n  if t == s then\n    pure LBool.true\n  else if etaEq t s || etaEq s t then\n    pure LBool.true  -- t =?= (fun xs => t xs)\n  else\n    let tFn := t.getAppFn\n    let sFn := s.getAppFn\n    if !tFn.isMVar && !sFn.isMVar then\n      pure LBool.undef\n    else if (\u2190 isAssigned tFn) then\n      let t \u2190 instantiateMVars t\n      isDefEqQuick t s\n    else if (\u2190 isAssigned sFn) then\n      let s \u2190 instantiateMVars s\n      isDefEqQuick t s\n    else if (\u2190 isDelayedAssignedHead tFn t) then\n      let t \u2190 instantiateMVars t\n      isDefEqQuick t s\n    else if (\u2190 isDelayedAssignedHead sFn s) then\n      let s \u2190 instantiateMVars s\n      isDefEqQuick t s\n    else if (\u2190 isSynthetic tFn <&&> trySynthPending tFn) then\n      let t \u2190 instantiateMVars t\n      isDefEqQuick t s\n    else if (\u2190 isSynthetic sFn <&&> trySynthPending sFn) then\n      let s \u2190 instantiateMVars s\n      isDefEqQuick t s\n    else if tFn.isMVar && sFn.isMVar && tFn == sFn then\n      Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs\n    else\n      let tAssign? \u2190 isAssignable tFn\n      let sAssign? \u2190 isAssignable sFn\n      let assignableMsg (b : Bool) := if b then \"[assignable]\" else \"[nonassignable]\"\n      trace[Meta.isDefEq] \"{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}\"\n      if tAssign? && !sAssign? then\n        toLBoolM <| processAssignment' t s\n      else if !tAssign? && sAssign? then\n        toLBoolM <| processAssignment' s t\n      else if !tAssign? && !sAssign? then\n        if tFn.isMVar || sFn.isMVar then\n          let ctx \u2190 read\n          if ctx.config.isDefEqStuckEx then do\n            trace[Meta.isDefEq.stuck] \"{t} =?= {s}\"\n            Meta.throwIsDefEqStuck\n          else\n            pure LBool.false\n        else\n          pure LBool.undef\n      else\n        isDefEqQuickMVarMVar t s\n\n-- Both `t` and `s` are terms of the form `?m ...`\nprivate partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do\n  let tFn := t.getAppFn\n  let sFn := s.getAppFn\n  let tMVarDecl \u2190 getMVarDecl tFn.mvarId!\n  let sMVarDecl \u2190 getMVarDecl sFn.mvarId!\n  if s.isMVar && !t.isMVar then\n     /- Solve `?m t =?= ?n` by trying first `?n := ?m t`.\n        Reason: this assignment is precise. -/\n     if (\u2190 checkpointDefEq (processAssignment s t)) then\n       pure LBool.true\n     else\n       toLBoolM <| processAssignment t s\n  else\n     if (\u2190 checkpointDefEq (processAssignment t s)) then\n       pure LBool.true\n     else\n       toLBoolM <| processAssignment s t\n\nend\n\n@[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do\n  let status \u2190 x\n  match status with\n  | LBool.true  => pure true\n  | LBool.false => pure false\n  | LBool.undef => k\n\n@[specialize] private def unstuckMVar (e : Expr) (successK : Expr \u2192 MetaM Bool) (failK : MetaM Bool): MetaM Bool := do\n  match (\u2190 getStuckMVar? e) with\n  | some mvarId =>\n    trace[Meta.isDefEq.stuckMVar] \"found stuck MVar {mkMVar mvarId} : {\u2190 inferType (mkMVar mvarId)}\"\n    if (\u2190 Meta.synthPending mvarId) then\n      let e \u2190 instantiateMVars e\n      successK e\n    else\n      failK\n  | none   => failK\n\nprivate def isDefEqOnFailure (t s : Expr) : MetaM Bool :=\n  unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <|\n  unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <|\n  tryUnificationHints t s <||> tryUnificationHints s t\n\nprivate def isDefEqProj : Expr \u2192 Expr \u2192 MetaM Bool\n  | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s\n  | Expr.proj structName 0 s _, v => isDefEqSingleton structName s v\n  | v, Expr.proj structName 0 s _ => isDefEqSingleton structName s v\n  | _, _ => pure false\nwhere\n  /- If `structName` is a structure with a single field, then reduce `s.1 =?= v` to `s =?= \u27e8v\u27e9` -/\n  isDefEqSingleton (structName : Name) (s : Expr) (v : Expr) : MetaM Bool := do\n    let ctorVal := getStructureCtor (\u2190 getEnv) structName\n    if ctorVal.numFields != 1 then\n      return false -- It is not a structure with a single field.\n    let sType \u2190 whnf (\u2190 inferType s)\n    let sTypeFn := sType.getAppFn\n    if !sTypeFn.isConstOf structName then\n      return false\n    let ctorApp := mkApp (mkAppN (mkConst ctorVal.name sTypeFn.constLevels!) sType.getAppArgs) v\n    Meta.isExprDefEqAux s ctorApp\n\n/-\n  Given applications `t` and `s` that are in WHNF (modulo the current transparency setting),\n  check whether they are definitionally equal or not.\n-/\nprivate def isDefEqApp (t s : Expr) : MetaM Bool := do\n  let tFn := t.getAppFn\n  let sFn := s.getAppFn\n  if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then\n    /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/\n    if (\u2190 checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then\n      return true\n    else\n      isDefEqOnFailure t s\n  else if (\u2190 checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then\n    return true\n  else\n    isDefEqOnFailure t s\n\npartial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do\n  trace[Meta.isDefEq.step] \"{t} =?= {s}\"\n  checkMaxHeartbeats \"isDefEq\"\n  withNestedTraces do\n  whenUndefDo (isDefEqQuick t s) do\n  whenUndefDo (isDefEqProofIrrel t s) do\n  let t' \u2190 whnfCore t\n  let s' \u2190 whnfCore s\n  if t != t' || s != s' then\n    isExprDefEqAuxImpl t' s'\n  else do\n    if (\u2190 (isDefEqEta t s <||> isDefEqEta s t)) then pure true else\n    if (\u2190 isDefEqProj t s) then pure true else\n    whenUndefDo (isDefEqNative t s) do\n    whenUndefDo (isDefEqNat t s) do\n    whenUndefDo (isDefEqOffset t s) do\n    whenUndefDo (isDefEqDelta t s) do\n    if t.isConst && s.isConst then\n      if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else pure false\n    else if t.isApp && s.isApp then\n      isDefEqApp t s\n    else\n      whenUndefDo (isDefEqStringLit t s) do\n      isDefEqOnFailure t s\n\nbuiltin_initialize\n  isExprDefEqAuxRef.set isExprDefEqAuxImpl\n\nbuiltin_initialize\n  registerTraceClass `Meta.isDefEq\n  registerTraceClass `Meta.isDefEq.foApprox\n  registerTraceClass `Meta.isDefEq.constApprox\n  registerTraceClass `Meta.isDefEq.delta\n  registerTraceClass `Meta.isDefEq.step\n  registerTraceClass `Meta.isDefEq.assign\n\nend Lean.Meta\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Meta/ExprDefEq.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.0838903892735695, "lm_q1q2_score": 0.036085229743526154}}
{"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\u1d52\u1d56 \u2964 Type w) where\n  obj : \u2200 U, Set (F.obj U)\n  map : \u2200 {U V : C\u1d52\u1d56} (i : U \u27f6 V), obj U \u2286 F.map i \u207b\u00b9' obj V\n#align category_theory.grothendieck_topology.subpresheaf CategoryTheory.GrothendieckTopology.Subpresheaf\n\nvariable {F F' F'' : C\u1d52\u1d56 \u2964 Type w} (G G' : Subpresheaf F)\n\ninstance : PartialOrder (Subpresheaf F) :=\n  PartialOrder.lift Subpresheaf.obj Subpresheaf.ext\n\ninstance : Top (Subpresheaf F) :=\n  \u27e8\u27e8fun U => \u22a4, fun U V i x h => trivial\u27e9\u27e9\n\ninstance : Nonempty (Subpresheaf F) :=\n  inferInstance\n\n/-- The subpresheaf as a presheaf. -/\n@[simps]\ndef Subpresheaf.toPresheaf : C\u1d52\u1d56 \u2964 Type w\n    where\n  obj U := G.obj U\n  map U V i x := \u27e8F.map i x, G.map i x.Prop\u27e9\n  map_id' X := by\n    ext \u27e8x, _\u27e9\n    dsimp\n    rw [F.map_id]\n    rfl\n  map_comp' X Y Z i j := by\n    ext \u27e8x, _\u27e9\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.\u03b9 : G.toPresheaf \u27f6 F where app U x := x\n#align category_theory.grothendieck_topology.subpresheaf.\u03b9 CategoryTheory.GrothendieckTopology.Subpresheaf.\u03b9\n\ninstance : Mono G.\u03b9 :=\n  \u27e8fun H f\u2081 f\u2082 e =>\n    NatTrans.ext f\u2081 f\u2082 <|\n      funext fun U => funext fun x => Subtype.ext <| congr_fun (congr_app e U) x\u27e9\n\n/-- The inclusion of a subpresheaf to a larger subpresheaf -/\n@[simps]\ndef Subpresheaf.homOfLe {G G' : Subpresheaf F} (h : G \u2264 G') : G.toPresheaf \u27f6 G'.toPresheaf\n    where app U x := \u27e8x, h U x.Prop\u27e9\n#align category_theory.grothendieck_topology.subpresheaf.hom_of_le CategoryTheory.GrothendieckTopology.Subpresheaf.homOfLe\n\ninstance {G G' : Subpresheaf F} (h : G \u2264 G') : Mono (Subpresheaf.homOfLe h) :=\n  \u27e8fun H f\u2081 f\u2082 e =>\n    NatTrans.ext f\u2081 f\u2082 <|\n      funext fun U =>\n        funext fun x =>\n          Subtype.ext <| (congr_arg Subtype.val <| (congr_fun (congr_app e U) x : _) : _)\u27e9\n\n@[simp, reassoc.1]\ntheorem Subpresheaf.homOfLe_\u03b9 {G G' : Subpresheaf F} (h : G \u2264 G') :\n    Subpresheaf.homOfLe h \u226b G'.\u03b9 = G.\u03b9 := by\n  ext\n  rfl\n#align category_theory.grothendieck_topology.subpresheaf.hom_of_le_\u03b9 CategoryTheory.GrothendieckTopology.Subpresheaf.homOfLe_\u03b9\n\ninstance : IsIso (Subpresheaf.\u03b9 (\u22a4 : Subpresheaf F)) :=\n  by\n  apply (config := { instances := false }) nat_iso.is_iso_of_is_iso_app\n  \u00b7 intro X\n    rw [is_iso_iff_bijective]\n    exact \u27e8Subtype.coe_injective, fun x => \u27e8\u27e8x, _root_.trivial\u27e9, rfl\u27e9\u27e9\n\ntheorem Subpresheaf.eq_top_iff_isIso : G = \u22a4 \u2194 IsIso G.\u03b9 :=\n  by\n  constructor\n  \u00b7 rintro rfl\n    infer_instance\n  \u00b7 intro H\n    ext (U x)\n    apply (iff_true_iff _).mpr\n    rw [\u2190 is_iso.inv_hom_id_apply (G.\u03b9.app U) x]\n    exact ((inv (G.\u03b9.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' \u27f6 F) (hf : \u2200 U x, f.app U x \u2208 G.obj U) : F' \u27f6 G.toPresheaf\n    where\n  app U x := \u27e8f.app U x, hf U x\u27e9\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_\u03b9 (f : F' \u27f6 F) (hf : \u2200 U x, f.app U x \u2208 G.obj U) : G.lift f hf \u226b G.\u03b9 = f :=\n  by\n  ext\n  rfl\n#align category_theory.grothendieck_topology.subpresheaf.lift_\u03b9 CategoryTheory.GrothendieckTopology.Subpresheaf.lift_\u03b9\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 \u27f6 U` such that the restriction of `s` along `f` is in `G`. -/\n@[simps]\ndef Subpresheaf.sieveOfSection {U : C\u1d52\u1d56} (s : F.obj U) : Sieve (unop U)\n    where\n  arrows V f := F.map f.op s \u2208 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\u1d52\u1d56} (s : F.obj U) :\n    (G.sieveOfSection s).1.FamilyOfElements G.toPresheaf := fun V i hi => \u27e8F.map i.op s, hi\u27e9\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\u1d52\u1d56} (s : F.obj U) :\n    (G.familyOfElementsOfSection s).Compatible :=\n  by\n  intro Y\u2081 Y\u2082 Z g\u2081 g\u2082 f\u2081 f\u2082 h\u2081 h\u2082 e\n  ext1\n  change F.map g\u2081.op (F.map f\u2081.op s) = F.map g\u2082.op (F.map f\u2082.op s)\n  rw [\u2190 functor_to_types.map_comp_apply, \u2190 functor_to_types.map_comp_apply, \u2190 op_comp, \u2190 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' \u27f6 G.toPresheaf) {U V : C\u1d52\u1d56} (i : U \u27f6 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 \u2208 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\u22a2\n    rwa [\u2190 functor_to_types.map_comp_apply]\n#align category_theory.grothendieck_topology.subpresheaf.sheafify CategoryTheory.GrothendieckTopology.Subpresheaf.sheafify\n\ntheorem Subpresheaf.le_sheafify : G \u2264 G.sheafify J :=\n  by\n  intro U s hs\n  change _ \u2208 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 [\u2190 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 \u27f6 U} (hi : S' i) => hi\n  choose W i\u2081 i\u2082 hi\u2082 h\u2081 h\u2082\n  dsimp [-sieve.bind_apply] at *\n  let x'' : presieve.family_of_elements F S' := fun V i hi => F.map (i\u2081 hi).op (x _ (hi\u2082 hi))\n  have H : \u2200 s, x.is_amalgamation s \u2194 x''.is_amalgamation s.1 :=\n    by\n    intro s\n    constructor\n    \u00b7 intro H V i hi\n      dsimp only [x'']\n      conv_lhs => rw [\u2190 h\u2082 hi]\n      rw [\u2190 H _ (hi\u2082 hi)]\n      exact functor_to_types.map_comp_apply F (i\u2082 hi).op (i\u2081 hi).op _\n    \u00b7 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' \u226b i) := \u27e8_, _, _, hi, hi', rfl\u27e9\n      have := H _ hi''\n      rw [op_comp, F.map_comp] at this\n      refine' this.trans (congr_arg Subtype.val (hx _ _ (hi\u2082 hi'') hi (h\u2082 hi'')))\n  have : x''.compatible := by\n    intro V\u2081 V\u2082 V\u2083 g\u2081 g\u2082 g\u2083 g\u2084 S\u2081 S\u2082 e\n    rw [\u2190 functor_to_types.map_comp_apply, \u2190 functor_to_types.map_comp_apply]\n    exact\n      congr_arg Subtype.val\n        (hx (g\u2081 \u226b i\u2081 S\u2081) (g\u2082 \u226b i\u2081 S\u2082) (hi\u2082 S\u2081) (hi\u2082 S\u2082) (by simp only [category.assoc, h\u2082, e]))\n  obtain \u27e8t, ht, ht'\u27e9 := hF _ (J.bind_covering hS fun V i hi => (x i hi).2) _ this\n  refine' \u27e8\u27e8t, _\u27e9, (H \u27e8t, _\u27e9).mpr ht, fun y hy => Subtype.ext (ht' _ ((H _).mp hy))\u27e9\n  show G.sieve_of_section t \u2208 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\u2081 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 \u2194 Presieve.IsSheaf J G.toPresheaf :=\n  \u27e8fun e => e.symm \u25b8 G.sheafify_isSheaf h, G.eq_sheafify h\u27e9\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 \u2194\n      \u2200 (U) (s : F.obj U), G.sieveOfSection s \u2208 J (unop U) \u2192 s \u2208 G.obj U :=\n  by\n  rw [\u2190 G.eq_sheafify_iff h]\n  change _ \u2194 G.sheafify J \u2264 G\n  exact \u27e8Eq.ge, (G.le_sheafify J).antisymm\u27e9\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 \u27f6 F') (h : Presieve.IsSheaf J F') :\n    (G.sheafify J).toPresheaf \u27f6 F'\n    where\n  app U s := (h _ s.Prop).amalgamate _ ((G.family_of_elements_compatible \u2191s).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 [\u2190 functor_to_types.map_comp_apply]\n    change _ = F'.map (j \u226b i.unop).op _\n    refine' Eq.trans _ (presieve.is_sheaf_for.valid_glue _ _ _ _).symm\n    \u00b7 dsimp at hj\u22a2\n      rwa [functor_to_types.map_comp_apply]\n    \u00b7 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 \u27f6 F') (h : Presieve.IsSheaf J F') :\n    Subpresheaf.homOfLe (G.le_sheafify J) \u226b 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\u2081 l\u2082 : (G.sheafify J).toPresheaf \u27f6 F')\n    (e : Subpresheaf.homOfLe (G.le_sheafify J) \u226b l\u2081 = Subpresheaf.homOfLe (G.le_sheafify J) \u226b l\u2082) :\n    l\u2081 = l\u2082 := by\n  ext (U\u27e8s, hs\u27e9)\n  apply (h _ hs).IsSeparatedFor.ext\n  rintro V i hi\n  dsimp at hi\n  erw [\u2190 functor_to_types.naturality, \u2190 functor_to_types.naturality]\n  exact (congr_fun (congr_app e <| op V) \u27e8_, hi\u27e9 : _)\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 \u2264 G') (hF : Presieve.IsSheaf J F)\n    (hG' : Presieve.IsSheaf J G'.toPresheaf) : G.sheafify J \u2264 G' :=\n  by\n  intro U x hx\n  convert((G.sheafify_lift (subpresheaf.hom_of_le h) hG').app U \u27e8x, hx\u27e9).2\n  apply (hF _ hx).IsSeparatedFor.ext\n  intro V i hi\n  have :=\n    congr_arg (fun f : G.to_presheaf \u27f6 G'.to_presheaf => (nat_trans.app f (op V) \u27e8_, hi\u27e9).1)\n      (G.to_sheafify_lift (subpresheaf.hom_of_le h) hG')\n  convert this.symm\n  erw [\u2190 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' \u27f6 F) : Subpresheaf F\n    where\n  obj U := Set.range (f.app U)\n  map U V i := by\n    rintro _ \u27e8x, rfl\u27e9\n    have := elementwise_of f.naturality\n    exact \u27e8_, this i x\u27e9\n#align category_theory.grothendieck_topology.image_presheaf CategoryTheory.GrothendieckTopology.imagePresheaf\n\n@[simp]\ntheorem top_subpresheaf_obj (U) : (\u22a4 : Subpresheaf F).obj U = \u22a4 :=\n  rfl\n#align category_theory.grothendieck_topology.top_subpresheaf_obj CategoryTheory.GrothendieckTopology.top_subpresheaf_obj\n\n@[simp]\ntheorem imagePresheaf_id : imagePresheaf (\ud835\udfd9 F) = \u22a4 :=\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' \u27f6 F) : F' \u27f6 (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' \u27f6 F) : F' \u27f6 ((imagePresheaf f).sheafify J).toPresheaf :=\n  toImagePresheaf f \u226b 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_\u03b9 (f : F' \u27f6 F) : toImagePresheaf f \u226b (imagePresheaf f).\u03b9 = f :=\n  (imagePresheaf f).lift_\u03b9 _ _\n#align category_theory.grothendieck_topology.to_image_presheaf_\u03b9 CategoryTheory.GrothendieckTopology.toImagePresheaf_\u03b9\n\ntheorem imagePresheaf_comp_le (f\u2081 : F \u27f6 F') (f\u2082 : F' \u27f6 F'') :\n    imagePresheaf (f\u2081 \u226b f\u2082) \u2264 imagePresheaf f\u2082 := fun U x hx => \u27e8f\u2081.app U hx.some, hx.choose_spec\u27e9\n#align category_theory.grothendieck_topology.image_presheaf_comp_le CategoryTheory.GrothendieckTopology.imagePresheaf_comp_le\n\ninstance {F F' : C\u1d52\u1d56 \u2964 Type max v w} (f : F \u27f6 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  \u00b7 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  \u00b7 rintro \u27e8_, \u27e8x, rfl\u27e9\u27e9\n    exact \u27e8x, rfl\u27e9\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 \u27f6 F') : Sheaf J (Type w) :=\n  \u27e8((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 [\u2190 is_sheaf_iff_is_sheaf_of_type]\n    exact F'.2\u27e9\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 \u27f6 F') : F \u27f6 imageSheaf f :=\n  \u27e8toImagePresheafSheafify J f.1\u27e9\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\u03b9 {F F' : Sheaf J (Type w)} (f : F \u27f6 F') : imageSheaf f \u27f6 F' :=\n  \u27e8Subpresheaf.\u03b9 _\u27e9\n#align category_theory.grothendieck_topology.image_sheaf_\u03b9 CategoryTheory.GrothendieckTopology.imageSheaf\u03b9\n\n@[simp, reassoc.1]\ntheorem toImageSheaf_\u03b9 {F F' : Sheaf J (Type w)} (f : F \u27f6 F') :\n    toImageSheaf f \u226b imageSheaf\u03b9 f = f := by\n  ext1\n  simp [to_image_presheaf_sheafify]\n#align category_theory.grothendieck_topology.to_image_sheaf_\u03b9 CategoryTheory.GrothendieckTopology.toImageSheaf_\u03b9\n\ninstance {F F' : Sheaf J (Type w)} (f : F \u27f6 F') : Mono (imageSheaf\u03b9 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 \u27f6 F') : Epi (toImageSheaf f) :=\n  by\n  refine' \u27e8fun G' g\u2081 g\u2082 e => _\u27e9\n  ext (U\u27e8s, hx\u27e9)\n  apply ((is_sheaf_iff_is_sheaf_of_type J _).mp G'.2 _ hx).IsSeparatedFor.ext\n  rintro V i \u27e8y, e'\u27e9\n  change (g\u2081.val.app _ \u226b G'.val.map _) _ = (g\u2082.val.app _ \u226b G'.val.map _) _\n  rw [\u2190 nat_trans.naturality, \u2190 nat_trans.naturality]\n  have E : (to_image_sheaf f).val.app (op V) y = (image_sheaf f).val.map i.op \u27e8s, hx\u27e9 :=\n    Subtype.ext e'\n  have := congr_arg (fun f : F \u27f6 G' => (Sheaf.hom.val f).app _ y) e\n  dsimp at this\u22a2\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 \u27f6 F') : Limits.MonoFactorisation f\n    where\n  i := imageSheaf f\n  m := imageSheaf\u03b9 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 \u27f6 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' \u27e8subpresheaf.hom_of_le _ \u226b inv (to_image_presheaf I.m.1)\u27e9\n        apply subpresheaf.sheafify_le\n        \u00b7 conv_lhs => rw [\u2190 I.fac]\n          apply image_presheaf_comp_le\n        \u00b7 rw [\u2190 is_sheaf_iff_is_sheaf_of_type]\n          exact F'.2\n        \u00b7 apply presieve.is_sheaf_iso J (as_iso <| to_image_presheaf I.m.1)\n          rw [\u2190 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 [\u2190 subpresheaf.hom_of_le_\u03b9 h, category.assoc]\n        congr 1\n        rw [is_iso.inv_comp_eq, to_image_presheaf_\u03b9] }\n#align category_theory.grothendieck_topology.image_factorization CategoryTheory.GrothendieckTopology.imageFactorization\n\ninstance : Limits.HasImages (Sheaf J (Type max v u)) :=\n  \u27e8fun _ _ f => \u27e8\u27e8imageFactorization f\u27e9\u27e9\u27e9\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 \u21c0 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 `\ud835\udc9e` to labels for types `\u03b1` that are instances of `\ud835\udc9e`.\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 `\u03b1 : Type` and `[\ud835\udc9e \u03b1]` for some typeclass `\ud835\udc9e`, then the element pool contains labels for the elements of `\u03b1`.\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 \u03b1` 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 := \u27e8\u03bb n l, n \u2208 l.in_play\u27e9\nmeta instance {n} {l : labeller} : decidable (n \u2208 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            , (\"\u2192\", [\"f\", \"g\", \"h\"])\n            , (\"sequence\" , [\"\u03ba\", \"\u03c3\", \"\u03c4\"])\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\", [\"\u03b5\", \"\u03b4\", \"\u03b7\", \"\u03b6\", \"\u03b8\", \"\u03b1\", \"\u03b2\", \"\u03b3\", \"\u03c9\"])\n            , (\"Type\", [\"\u03b1\", \"\u03b2\", \"\u03b3\", \"\u03b4\", \"\u03b5\"])\n            , (\"Prop\", [\"P\", \"Q\", \"R\"])\n]\n\nmeta instance : inhabited labeller :=\n\u27e8{ in_play := \u2205\n, counts := dictd.empty (\u03bb _, 0)\n, cp := default_class_pool\n, tp := default_type_pool\n, ep := default_element_pool\n}\u27e9\n\nmeta def to_subscript_digit : nat \u2192 string\n| 0 := \"\u2080\" | 1 := \"\u2081\" | 2 := \"\u2082\" | 3 := \"\u2083\" | 4 := \"\u2084\" | 5 := \"\u2085\" | 6 := \"\u2086\" | 7 := \"\u2087\" | 8 := \"\u2088\" | 9 := \"\u2089\"\n| n := \"\u2658\"\n\nmeta def to_digits_rev : nat \u2192 list nat\n| 0 := []\n| n := (n % 10) :: to_digits_rev (n / 10)\n\nmeta def to_subscript : nat \u2192 string\n| 0 := \"\u2080\"\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 : \u03b1).\n- if `\u03b1 = f ..xs`, look up `f.last` in `type_pool`\n- if `\u03b1 = Type`, look up \"Type\" in `type_pool`\n- if `\u03b1 = Prop`, look up \"Prop\" in `type_pool`\n- if `\u03b1 = expr.pi _ _ _ _`, look up \"\u2192\" in `type_pool`,\n- if `[C \u03b1]` 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 \u2192 Type} [monad m] [monad_state labeller m] [has_monad_lift tactic m] {\u03b1 \u03b2 : Type}\n\nmeta def get_fn_name : expr \u2192 string\n| (expr.app f _) := get_fn_name f\n| (expr.pi _ _ _ _) := \"\u2192\"\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 \u2192 m bool | n:= do\n  labs \u2190 get,\n  pure $ n \u2208 in_play labs\n\nmeta def push_label : name \u2192 m unit | n := do\n  modify $ labeller.modify_in_play $ insert n\n\nmeta def trace_label_state : m unit := do\n  labs \u2190 get,\n  trace (to_string $ labs.in_play) (pure ()),\n  pure ()\n\nmeta def select_label : list string \u2192 m name\n| [] := \u2350 $ tactic.fail \"need to select from at least one label\"\n| ss := do\n  labs \u2190 get,\n\n  unused \u2190 pure $ ss.find ((\u2209 labs) \u2218 mk_simple_name),\n  match unused with\n  | (some h) := do\n    n \u2190 pure $ mk_simple_name h,\n    push_label n,\n    pure n\n  | none := do\n    ss \u2190 pure $ ss.map (\u03bb x, (x, labs.counts.get x)),\n    some (base, i) \u2190 pure $ ss.min_by (int.of_nat \u2218 prod.snd),\n    n \u2190 pure $ mk_simple_name $ base ++ to_subscript i,\n    modify $ labeller.modify_counts $ \u03bb cs, cs.modify (+ 1) base,\n    push_label n,\n    pure n\n  end\n\nmeta def label_intro (is_src : bool) : binder \u2192 cotelescope \u2192 m name\n| \u27e8n,bi,y\u27e9 rest := do\n  y \u2190 \u2350 $ tactic.instantiate_mvars $ y,\n  labs \u2190 get,\n  ip \u2190 \u2350 $ 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 \u2190 pure $ if is_src then \"H\" else \"T\",\n    select_label [base]\n  else if n \u2260 name.anonymous \u2227 n \u2209 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 \u2190 pure $ assignable.instantiate_var rest $ expr.local_const n n bi y,\n\n    cls \u2190 pure $ rest.collect $ \u03bb b,\n      match b with\n      | \u27e8_, binder_info.inst_implicit, expr.app (expr.const f _) (expr.local_const un _ _ _)\u27e9 :=\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 \u2190 \u2350 $ tactic.get_classes y,\n\n    els \u2190 pure $ cs.collect $ \u03bb c, labs.ep.get c.last,\n    -- \u2350 $ tactic.trace $ get_fn_name y,\n    tls \u2190 pure $ labs.tp.get $ get_fn_name y,\n    ns \u2190 pure $ cls ++ els ++ tls,\n    ns \u2190 pure $ if ns.empty then default_labels else ns,\n    -- \u2350 $ tactic.trace $ (\"selecting from names: \", ns),\n    select_label ns\n\nmeta def label (p: pool) : expr \u2192 tactic (list string)\n| T := do\n  cs \u2190 tactic.get_classes T,\n  ts : string \u2190 pure $ match expr.app_fn T with\n        | (expr.const f _) := f.head\n        | (expr.pi _ _ _ _) := \"\u2192\"\n        | _ := \"none\"\n        end,\n  ls \u2190 pure $ cs.collect $ \u03bb 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 \u00d7 name) := do\n--   -- [todo] also check the local_context.\n--   if \u00ac(name.is_private parent \u2228 parent = name.anonymous \u2228 table.contains parent ls.in_play) then pure (ls, parent) else do\n--   base \u2190 pure $ match parent with\n--   | name.anonymous := \"\"\n--   | name.mk_numeral i n := \"\"\n--   | name.mk_string  s n := s\n--   end,\n--   pool \u2190 pure $ ls.pools.get base,\n--   pool \u2190 pure $ if pool.empty then ls.pools.get \"\" else pool,\n\n--   ls \u2190 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 \u2192 m expr\n| m@(expr.mvar un pn _):= do\n  -- \u2350 tactic.trace_state,\n  y \u2190 \u2350 $ tactic.infer_type m >>= tactic.instantiate_mvars,\n  b \u2190 pure $ binder.mk name.anonymous binder_info.default y,\n  label \u2190 label_intro ff b [],\n  -- \u2350 $ tactic.trace (\"rename_meta\", un, y, label),\n  -- [todo] check if pn is sensible or something like `_mvar_.....`\n  \u2350 $ type_context.run $ do\n    -- pure (ls, mvar)\n    lctx \u2190 type_context.get_context m,\n    g \u2190 type_context.mk_mvar label y lctx,\n    type_context.assign m g,\n    pure g\n| _ := \u2350 $ tactic.fail \"not an mvar\"\n\nmeta def type_to_label_type_key : expr \u2192 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 \u00d7 expr) := do\n--   y \u2190 tactic.infer_type mvar,\n--   ip \u2190 tactic.is_prop y,\n--   if ip then rename_meta_core ls \"target\" parent mvar else do\n--   type \u2190 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 \u2192 tactic (labeller \u00d7 binder)\n-- | \u27e8n,bi,y\u27e9 := do\n--   ys \u2190 type_to_label_type_key y,\n--   (ls, n) \u2190 pure $ get_fresh_label ls ys n,\n--   pure (ls, \u27e8n,bi,y\u27e9)\n\nmeta def label_cotelescope : cotelescope \u2192 m cotelescope\n| [] := pure []\n| (b :: rest) := do\n  n \u2190 label_intro tt b rest,\n  -- \u2350 $ tactic.trace (\"relabel\", b, n),\n  b \u2190 pure $ {name := n, ..b},\n  l \u2190 \u2350 $ binder.mk_local b,\n  rest \u2190 pure $ @assignable.instantiate_var cotelescope (cotelescope.assignable) rest l,\n  -- \u2350 $ tactic.trace (rest.reverse),\n  rest \u2190 label_cotelescope (rest),\n  rest \u2190 pure $ assignable.abstract_local rest l.local_uniq_name,\n  -- \u2350 $ tactic.trace (rest.reverse),\n  pure $ b :: rest\n\nmeta def label_telescope : telescope \u2192 m telescope :=\n(pure \u2218 list.reverse) >=> label_cotelescope >=> (pure \u2218 list.reverse)\n\nmeta def free_label  (n : name) : m unit := do\n  ls \u2190 get,\n  -- put $ ls.modify_in_play (dict.erase n),\n  pure ()\n\nmeta def relabel_source : source \u2192 m source\n| src := do\n  l \u2190 label_intro tt \u27e8src.label, binder_info.default, src.type\u27e9 [],\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 {\u03b1 : Type*} {xs : list \u03b1}\n\ninstance : inhabited (buffer \u03b1) := \u27e8nil\u27e9\n\n@[ext]\nlemma ext : \u2200 {b\u2081 b\u2082 : buffer \u03b1}, to_list b\u2081 = to_list b\u2082 \u2192 b\u2081 = b\u2082\n| \u27e8n\u2081, a\u2081\u27e9 \u27e8n\u2082, a\u2082\u27e9 h := begin\n  simp [to_list, to_array] at h,\n  have e : n\u2081 = n\u2082 :=\n    by rw [\u2190array.to_list_length a\u2081, \u2190array.to_list_length a\u2082, h],\n  subst e,\n  have h : a\u2081 == a\u2082.to_list.to_array := h \u25b8 a\u2081.to_list_to_array.symm,\n  rw eq_of_heq (h.trans a\u2082.to_list_to_array)\nend\n\nlemma ext_iff {b\u2081 b\u2082 : buffer \u03b1} : b\u2081 = b\u2082 \u2194 to_list b\u2081 = to_list b\u2082 :=\n\u27e8\u03bb h, h \u25b8 rfl, ext\u27e9\n\nlemma size_eq_zero_iff {b : buffer \u03b1} : b.size = 0 \u2194 b = nil :=\nbegin\n  rcases b with \u27e8_|n, \u27e8a\u27e9\u27e9,\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 \u03b1).size = 0 :=\nby rw size_eq_zero_iff\n\n@[simp] lemma to_list_nil : to_list (@nil \u03b1) = [] := rfl\n\ninstance (\u03b1) [decidable_eq \u03b1] : decidable_eq (buffer \u03b1) :=\nby tactic.mk_dec_eq_instance\n\n@[simp]\nlemma to_list_append_list {b : buffer \u03b1} :\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 \u03b1) : 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 \u03b1) : 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 \u03b1) : b.to_array.to_list = b.to_list :=\nby { cases b, simp [to_list] }\n\n@[simp] lemma append_list_nil (b : buffer \u03b1) : b.append_list [] = b := rfl\n\nlemma to_buffer_cons (c : \u03b1) (l : list \u03b1) :\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 \u03b1) (a : \u03b1) : (b.push_back a).size = b.size + 1 :=\nby { cases b, simp [size, push_back] }\n\n@[simp] lemma size_append_list (b : buffer \u03b1) (l : list \u03b1) :\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 \u03b1) : 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 \u03b1) : b.to_list.length = b.size :=\nby rw [\u2190to_buffer_to_list b, to_list_to_buffer, size_to_buffer]\n\nlemma size_singleton (a : \u03b1) : [a].to_buffer.size = 1 := rfl\n\nlemma read_push_back_left (b : buffer \u03b1) (a : \u03b1) {i : \u2115} (h : i < b.size) :\n  (b.push_back a).read \u27e8i, by { convert nat.lt_succ_of_lt h, simp }\u27e9 = b.read \u27e8i, h\u27e9 :=\nby { cases b, convert array.read_push_back_left _, simp }\n\n@[simp] lemma read_push_back_right (b : buffer \u03b1) (a : \u03b1) :\n  (b.push_back a).read \u27e8b.size, by simp\u27e9 = a :=\nby { cases b, convert array.read_push_back_right }\n\nlemma read_append_list_left' (b : buffer \u03b1) (l : list \u03b1) {i : \u2115}\n  (h : i < (b.append_list l).size) (h' : i < b.size) :\n  (b.append_list l).read \u27e8i, h\u27e9 = b.read \u27e8i, h'\u27e9 :=\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 \u27e8i, h\u27e9 =\n      read ((push_back b hd).append_list tl) \u27e8i, hb\u27e9 := rfl,\n    simp [this, hl _ hb hb', read_push_back_left _ _ h'] }\nend\n\nlemma read_append_list_left (b : buffer \u03b1) (l : list \u03b1) {i : \u2115} (h : i < b.size) :\n  (b.append_list l).read \u27e8i, by simpa using nat.lt_add_right _ _ _ h\u27e9 = b.read \u27e8i, h\u27e9 :=\nread_append_list_left' b l _ h\n\n@[simp] lemma read_append_list_right (b : buffer \u03b1) (l : list \u03b1) {i : \u2115} (h : i < l.length) :\n  (b.append_list l).read \u27e8b.size + i, by simp [h]\u27e9 = 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 \u03b1) {i : \u2115} (h : i < l.to_buffer.size) (h' : i < l.length) :\n  l.to_buffer.read \u27e8i, h\u27e9 = 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 \u27e8i, hi\u27e9 = _,\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 \u03b1) (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 \u03b1) {i : \u2115} (h h') :\n  b.to_list.nth_le i h = b.read \u27e8i, h'\u27e9 :=\nbegin\n  have : b.to_list.to_buffer.read \u27e8i, (by simpa using h')\u27e9 = b.read \u27e8i, h'\u27e9,\n  { congr' 1; simp [fin.heq_ext_iff] },\n  simp [\u2190this]\nend\n\nlemma nth_le_to_list (b : buffer \u03b1) {i : \u2115} (h) :\n  b.to_list.nth_le i h = b.read \u27e8i, by simpa using h\u27e9 :=\nnth_le_to_list' _ _ _\n\nlemma read_eq_nth_le_to_list (b : buffer \u03b1) (i) :\n  b.read i = b.to_list.nth_le i (by simp) :=\nby simp [nth_le_to_list]\n\nlemma read_singleton (c : \u03b1) : [c].to_buffer.read \u27e80, by simp\u27e9 = 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 (\u03b1 : Type*) : list \u03b1 \u2243 buffer \u03b1 :=\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 \u03b1) (i : \u2115) : tactic \u03b1 :=\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-- \u0415\u0441\u043b\u0438 \u0432\u044b \u043d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u043b\u0438 \u0441 \u043c\u043e\u043d\u0430\u0434\u0430\u043c\u0438 \u0438 do-\u0431\u043b\u043e\u043a\u0430\u043c\u0438 \u0440\u0430\u043d\u044c\u0448\u0435, \u043f\u043e\u0447\u0438\u0442\u0430\u0439\u0442\u0435 \u0442\u0443\u0442\u043e\u0440\u0438\u0430\u043b \u0432 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u0435\n-- `tactic \u03b1` - \u0444\u0443\u043d\u043a\u0446\u0438\u044f, \u0440\u0430\u0431\u043e\u0442\u0430\u044e\u0449\u0438\u0435 \u0432 \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0435 \u0441\u043e\u0441\u0442\u043e\u044f\u043d\u0438\u044f \u0442\u0430\u043a\u0442\u0438\u043a\u0438 \u0438 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u03b1\n-- `tactic unit` - \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 (\u0438\u043b\u0438 \u0436\u0435 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 `()`)\n\nopen tactic\n\nmeta def make_nat : tactic \u2115 := \nreturn 42\n\n-- \u041a\u0430\u043a \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0440\u0430\u0431\u043e\u0442\u044b \u0434\u0440\u0443\u0433\u0438\u0445 \u0442\u0430\u043a\u0442\u0438\u043a \u0432\u043d\u0443\u0442\u0440\u0438 do-\u0431\u043b\u043e\u043a\u0430?\n-- n \u2190 make_nat\n\nmeta def trace_nat : tactic unit :=\ndo\n  n \u2190 make_nat,\n  tactic.trace n\n\n-- \u041a\u0430\u043a \u0434\u0435\u0431\u0430\u0433\u0430\u0442\u044c \u0442\u0430\u043a\u0442\u0438\u043a\u0438?\nexample : false :=\nbegin\n  trace_nat,\n  sorry,\nend\n\nrun_cmd trace_nat\n\n-- \u041a\u0430\u043a \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441 \u043e\u043a\u0440\u0443\u0436\u0435\u043d\u0438\u0435\u043c \u0432 \u0442\u0430\u043a\u0442\u0438\u043a\u0435?\n-- \u0414\u043b\u044f \u043f\u0435\u0440\u0432\u043e\u0439 \u0446\u0435\u043b\u0438 \u0435\u0441\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044f tactic.target\n#check tactic.target\n\nmeta def show_goal : tactic unit :=\ndo\n  t \u2190 target,\n  trace t\n  -- trace $ expr.to_raw_fmt t \u043f\u043e\u043a\u0430\u0436\u0435\u0442 \u043f\u043e\u043b\u043d\u0443\u044e \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u0443, \u043d\u0435 pretty printed\n\nexample (a b : \u2124) : a^2 + b^2 \u2265 0 :=\nbegin\n  show_goal,\n  sorry,\nend\n\n-- \u0414\u043b\u044f \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u044b\u0445 \u0433\u0438\u043f\u043e\u0442\u0435\u0437: \u0444\u0443\u043d\u043a\u0446\u0438\u0438 get_local \u0438 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 \u2190 get_local nm,\n  trace a,\n  trace (expr.to_raw_fmt a),\n  a_type \u2190 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-- \u0414\u043b\u044f \u043c\u043e\u043d\u0430\u0434\u0438\u0447\u0435\u0441\u043a\u043e\u0433\u043e \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0435\u0441\u0442\u044c \u043c\u043d\u043e\u0433\u043e (\u0445\u043e\u0442\u044c \u0438 \u043d\u0435 \u0442\u0430\u043a \u0431\u043e\u0433\u0430\u0442\u043e, \u043a\u0430\u043a \u0432 Haskell) \u0444\u0443\u043d\u043a\u0446\u0438\u0439\n#check list.mmap\n\nmeta def inspect_all : tactic unit :=\ndo\n  ctx \u2190 local_context,\n  trace ctx,\n  ctx_types \u2190 list.mmap (infer_type) ctx,\n  trace ctx_types,\n  ctx.mmap' (\u03bb e, \n              do \n                e_type \u2190 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-- \u041d\u0430\u043a\u043e\u043d\u0435\u0446, \u0440\u0435\u0430\u043b\u0438\u0437\u0443\u0435\u043c \u0432\u0435\u0440\u0441\u0438\u044e \u0442\u0430\u043a\u0442\u0438\u043a\u0438 `assumption`\n\nmeta def assump_one (e : expr) : tactic unit :=\ndo\n  tactic.exact e\n\n\nmeta def assump_list : list expr \u2192 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 \u2190 local_context,\n  assump_list ctx\n\n-- \u0422\u0435\u0441\u0442\nexample {A B C : Prop} (ha : A) (hb : B) (hc : C) : B :=\nbegin\n  assump,\n  -- sorry,\nend\n\n-- \u0411\u043e\u043b\u044c\u0448\u0435 \u0443\u043f\u0440\u0430\u0436\u043d\u0435\u043d\u0438\u0439: 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 \u2227 b \u2227 c \u2228 d` or\n`h2 : \u2203 x y, trans_rel R x y`. Usual usage might be `rcases h1 with \u27e8ha, hb, hc\u27e9 | hd` or\n`rcases h2 with \u27e8x, y, _ | \u27e8z, hxz, hzy\u27e9\u27e9` 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 `\u27e8p1, p2, p3\u27e9`, which matches a constructor with many arguments, or a series\n  of nested conjunctions or existentials. For example if the active hypothesis is `a \u2227 b \u2227 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 \u2228 b \u2228 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 \u27e8y, z\u27e9` 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 \u27e8hx, hy\u27e9 | hz := foo` is equivalent to `rcases foo with \u27e8hx, hy\u27e9 | hz`. Unlike `rcases`,\n  `obtain` also allows one to omit `:= foo`, although a type must be provided in this case,\n  as in `obtain \u27e8hx, hy\u27e9 | hz : a \u2227 b \u2228 c`, in which case it produces a subgoal for proving\n  `a \u2227 b \u2228 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) \"\u27e8\" rcasesPatLo,* \"\u27e9\" : 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\u03a3\" => List\n\n/- A list, with a conjunctive meaning (like a list of constructor arguments, or hypotheses) -/\nlocal notation \"List\u03a0\" => 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 `\u27e8p1, p2, p3\u27e9`\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 \u2228 a2 \u2228 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 \u2192 Name \u2192 RCasesPatt\n| clear : Syntax \u2192 RCasesPatt\n| typed : Syntax \u2192 RCasesPatt \u2192 Syntax \u2192 RCasesPatt\n| tuple : Syntax \u2192 List\u03a0 RCasesPatt \u2192 RCasesPatt\n| alts : Syntax \u2192 List\u03a3 RCasesPatt \u2192 RCasesPatt\nderiving Repr\n\nnamespace RCasesPatt\n\ninstance : Inhabited RCasesPatt := \u27e8RCasesPatt.one Syntax.missing `_\u27e9\n\n/-- Get the name from a pattern, if provided -/\npartial def name? : RCasesPatt \u2192 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 \u2192 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 `\u27e8p\u27e9`\nif `p` is not already a tuple. -/\ndef asTuple : RCasesPatt \u2192 List\u03a0 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 \u2192 List\u03a3 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 `\u27e8p\u27e9`. -/\ndef typed? (ref : Syntax) : RCasesPatt \u2192 Option Syntax \u2192 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 `\u27e8p\u27e9`. -/\ndef tuple' : List\u03a0 RCasesPatt \u2192 RCasesPatt\n| [p] => p\n| ps  => tuple (ps.head?.map (\u00b7.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\u03a3 RCasesPatt \u2192 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, \u27e8c, d\u27e9]`\nbecomes `\u27e8a, b, c, d\u27e9` instead of `\u27e8a, b, \u27e8c, d\u27e9\u27e9`.\n\nWe must be careful to turn `[a, \u27e8\u27e9]` into `\u27e8a, \u27e8\u27e9\u27e9` instead of `\u27e8a\u27e9` (which will not perform the\nnested match). -/\ndef tuple\u2081Core : List\u03a0 RCasesPatt \u2192 List\u03a0 RCasesPatt\n| []         => []\n| [tuple ref []] => [tuple ref []]\n| [tuple _ ps] => ps\n| p :: ps    => p :: tuple\u2081Core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`tuple\u2081Core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n`\ninstead of `\u27e8n\u27e9` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `\u27e8a, b, c\u27e9`. -/\ndef tuple\u2081 : List\u03a0 RCasesPatt \u2192 RCasesPatt\n| []      => default\n| [one ref n] => one ref n\n| ps      => tuple ps.head!.ref $ tuple\u2081Core 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\u2081` 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\u2081Core : List\u03a3 (List\u03a0 RCasesPatt) \u2192 List\u03a3 RCasesPatt\n| []          => []\n| [[alts _ ps]] => ps\n| p :: ps     => tuple\u2081 p :: alts\u2081Core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`alts\u2081Core`, but it produces a cases pattern directly instead of a list of alternatives. We\nspecially translate the empty alternation to `\u27e8\u27e9`, and translate `|(a | b)` to `\u27e8a | b\u27e9` (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\u2081 (ref : Syntax) : List\u03a3 (List\u03a0 RCasesPatt) \u2192 RCasesPatt\n| [[]]        => tuple Syntax.missing []\n| [[alts ref ps]] => tuple ref ps\n| ps          => alts' ref $ alts\u2081Core ps\n\nopen MessageData in\npartial instance : ToMessageData RCasesPatt := \u27e8fmt 0\u27e9 where\n  parenAbove (tgt p : Nat) (m : MessageData) : MessageData :=\n    if tgt < p then m.paren else m\n  fmt : Nat \u2192 RCasesPatt \u2192 MessageData\n  | _, one _ n => n\n  | _, clear _ => \"-\"\n  | p, typed _ pat ty => parenAbove 0 p m!\"{fmt 1 pat}: {ty}\"\n  | _, tuple _ pats => bracket \"\u27e8\" (joinSep (pats.map (fmt 0)) (\",\" ++ Format.line)) \"\u27e9\"\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 \u2192 List\u03a0 RCasesPatt \u2192 List\u03a0 Name \u00d7 List\u03a0 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\u03a3 Name \u2192 List\u03a3 RCasesPatt \u2192 MetaM (Array AltVarNames \u00d7 List\u03a3 (Name \u00d7 List\u03a0 RCasesPatt))\n| [], ps => pure (altVarNames, [])\n| c :: cs, ps => do\n  let n := FunInfo.getArity $ \u2190 getFunInfo (\u2190 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)  \u2190 processConstructors ref params (altVarNames.push \u27e8true, ns\u27e9) 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 \u00d7 MVarId) := do\n  let hLocalDecl \u2190 getLocalDecl hFVarId\n  let error {\u03b1} _ : MetaM \u03b1 := 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 (\u03b1, lhs, rhs) \u2190 matchEq? hLocalDecl.type | error ()\n  let substReduced (newType : Expr) (symm : Bool) : MetaM (FVarSubst \u00d7 MVarId) := do\n    let mvarId \u2190 assert mvarId hLocalDecl.userName newType (mkFVar hFVarId)\n    let (hFVarId', mvarId) \u2190 intro1P mvarId\n    let mvarId \u2190 clear mvarId hFVarId\n    substCore mvarId hFVarId' (symm := symm) (tryToSkip := true) (fvarSubst := fvarSubst)\n  let rhs' \u2190 whnf rhs\n  if rhs'.isFVar then\n    if rhs != rhs' then\n      substReduced (\u2190 mkEq lhs rhs') true\n    else\n      substCore mvarId hFVarId (symm := true) (tryToSkip := true) (fvarSubst := fvarSubst)\n  else\n    let lhs' \u2190 whnf lhs\n    if lhs'.isFVar then\n      if lhs != lhs' then\n        substReduced (\u2190 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 : \u03b1)\n  (pat : RCasesPatt) (cont : MVarId \u2192 FVarSubst \u2192 Array FVarId \u2192 \u03b1 \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\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) \u2190 subst' g (\u2190 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 \u2190 Term.elabType ty\n    let e \u2190 translate e\n    let etype \u2190 inferType e\n    unless \u2190 isDefEq etype expected do\n      Term.throwTypeMismatchError \"rcases: scrutinee\" expected etype e\n    let g \u2190 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 \u2190 translate e\n    let type \u2190 whnfD (\u2190 inferType e)\n    let failK {\u03b1} _ : TermElabM \u03b1 :=\n      throwError \"rcases tactic failed: {e} : {type} is not an inductive datatype\"\n    let (r, subgoals) \u2190 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) \u2190 Meta.revert g (\u2190 getFVarsToGeneralize #[e])\n        withMVarContext g do\n          let elimInfo \u2190 getElimInfo `Quot.ind\n          let res \u2190 ElimApp.mkElimApp `Quot.ind elimInfo #[e] (\u2190 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) \u2190 intro g x\n          let (varsOut, g) \u2190 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)], #[\u27e8\u27e8g, #[mkFVar v], fs'\u27e9, n\u27e9])\n      | ConstantInfo.inductInfo info, _ => do\n        let (altVarNames, r) \u2190 processConstructors pat.ref info.numParams #[] info.ctors pat.asAlts\n        (r, \u00b7) <$> cases g e.fvarId! altVarNames\n      | _, _ => failK ()\n    (\u00b7.2) <$> subgoals.foldlM (init := (r, a)) fun (r, a) \u27e8goal, ctorName\u27e9 => 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, \u00b7) <$> 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 `\u27e8a | b, \u27e8c, d\u27e9\u27e9` performs the `\u27e8c, d\u27e9` match twice, once on the\n`a` branch and once on `b`. -/\npartial def rcasesContinue (g : MVarId) (fs : FVarSubst) (clears : Array FVarId) (a : \u03b1)\n  (pats : List\u03a0 (RCasesPatt \u00d7 Expr)) (cont : MVarId \u2192 FVarSubst \u2192 Array FVarId \u2192 \u03b1 \u2192 TermElabM \u03b1) :\n  TermElabM \u03b1 :=\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 \u2190 getMCtx\n  let toErase := (\u2190 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`\u03b1` 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 (\u2190 ps.getElems.toList.mapM parse)\n  | `(Lean.Parser.Tactic.rcasesPatLo| $pat:rcasesPatMed : $t:term) => do\n    pure $ RCasesPatt.typed stx (\u2190 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| \u27e8$ps,*\u27e9) => do\n    pure $ RCasesPatt.tuple stx (\u2190 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 \u00d7 MVarId) := do\n  let argsToGeneralize := args.filter fun arg => !(arg.expr.isFVar && arg.hName?.isNone)\n  let (fvarIdsNew, mvarId) \u2190 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 \u00d7 Syntax))\n  (pat : RCasesPatt) (g : MVarId) : TermElabM (List MVarId) := do\n  let pats \u2190 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 <|\u2190 (tgts.zip pats.toArray).mapM fun ((hName?, tgt), pat) => do\n    let (pat, ty) \u2190 match pat with\n    | RCasesPatt.typed ref pat ty => pure (pat, some (\u2190 withRef ref <| Term.elabType ty))\n    | _ => pure (pat, none)\n    let expr \u2190 Term.ensureHasType ty (\u2190 Term.elabTerm tgt ty)\n    pure (pat, { expr, xName? := pat.name?, hName? : GeneralizeArg })\n  let (vs, g) \u2190 generalizeExceptFVar g args\n  let gs \u2190 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 \u2190 Term.elabType ty\n  let g\u2081 \u2190 mkFreshExprMVar (some ty)\n  let (v, g\u2082) \u2190 intro1 (\u2190 assert g (pat.name?.getD default) ty g\u2081)\n  let gs \u2190 rcasesCore g\u2082 {} #[] v #[] pat finish\n  pure (g\u2081.mvarId! :: gs.toList)\n\nmutual\n\npartial def rintroCore (g : MVarId) (fs : FVarSubst) (clears : Array FVarId) (a : \u03b1)\n  (ref pat : Syntax) (ty? : Option Syntax)\n  (cont : MVarId \u2192 FVarSubst \u2192 Array FVarId \u2192 \u03b1 \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  match pat with\n  | `(rintroPat| $pat:rcasesPat) =>\n    let pat := (\u2190 RCasesPatt.parse pat).typed? ref ty?\n    let (v, g) \u2190 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 : \u03b1)\n  (cont : MVarId \u2192 FVarSubst \u2192 Array FVarId \u2192 \u03b1 \u2192 TermElabM \u03b1) : TermElabM \u03b1 := 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 \u27e8i, h\u27e9) 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  (\u00b7.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 \u2190 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 (\u2190 RCases.rcases tgts pat (\u2190 getMainGoal))\n\nelab (name := obtain) tk:\"obtain\"\n    pat:(ppSpace rcasesPatMed)? ty:(\" : \" term)? val:(\" := \" term,+)? : tactic => do\n  let pat \u2190 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 \u27e8patt\u27e9? : type (:= val)?` or `obtain \u27e8patt\u27e9? (: type)? := val`\")\n    let pat := pat.getD (RCasesPatt.one tk `this)\n    withMainContext do\n      replaceMainGoal (\u2190 RCases.obtainNone pat ty[1] (\u2190 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 (\u2190 RCases.rcases tgts pat (\u2190 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 (\u2190 RCases.rintro ty pats.getArgs ty? (\u2190 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 \u2227 Q :=\nbegin\n  split,\n  work_on_goal 1 { swap_var [P Q] },\n  all_goals { exact \u2039P\u203a }\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 \u00d7 Name) :=\n  Prod.mk <$> ident <*> (optional (tk \"<->\" <|> tk \"\u2194\") *> ident)\n#align tactic.interactive.swap_arg_parser tactic.interactive.swap_arg_parser\n\nprivate unsafe def swap_args_parser : lean.parser (List (Name \u00d7 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 \u2194 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 \u2227 Q :=\nbegin\n  split,\n  work_on_goal 1 { swap_var [P Q] },\n  all_goals { exact \u2039P\u203a }\nend\n```\n-/\nunsafe def swap_var (renames : parse swap_args_parser) : tactic Unit := do\n  renames fun e => do\n      let n \u2190 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\u1d50\u1d52\u1d56` for the monoidal opposite of a monoidal category `C`.\n-/\n\n\nuniverses v\u2081 v\u2082 u\u2081 u\u2082\n\nvariables {C : Type u\u2081}\n\nnamespace category_theory\n\nopen category_theory.monoidal_category\n\n/-- A type synonym for the monoidal opposite. Use the notation `C\u1d39\u1d52\u1d56`. -/\n@[nolint has_nonempty_instance]\ndef monoidal_opposite (C : Type u\u2081) := C\n\nnamespace monoidal_opposite\n\nnotation C `\u1d39\u1d52\u1d56`:std.prec.max_plus := monoidal_opposite C\n\n/-- Think of an object of `C` as an object of `C\u1d39\u1d52\u1d56`. -/\n@[pp_nodot]\ndef mop (X : C) : C\u1d39\u1d52\u1d56 := X\n\n/-- Think of an object of `C\u1d39\u1d52\u1d56` as an object of `C`. -/\n@[pp_nodot]\ndef unmop (X : C\u1d39\u1d52\u1d56) : C := X\n\nlemma op_injective : function.injective (mop : C \u2192 C\u1d39\u1d52\u1d56) := \u03bb _ _, id\nlemma unop_injective : function.injective (unmop : C\u1d39\u1d52\u1d56 \u2192 C) := \u03bb _ _, id\n\n@[simp] lemma op_inj_iff (x y : C) : mop x = mop y \u2194 x = y := iff.rfl\n@[simp] \n\nattribute [irreducible] monoidal_opposite\n\n@[simp] lemma mop_unmop (X : C\u1d39\u1d52\u1d56) : 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\u2081} C] : category C\u1d39\u1d52\u1d56 :=\n{ hom := \u03bb X Y, unmop X \u27f6 unmop Y,\n  id := \u03bb X, \ud835\udfd9 (unmop X),\n  comp := \u03bb X Y Z f g, f \u226b g, }\n\nend monoidal_opposite\n\nend category_theory\n\nopen category_theory\nopen category_theory.monoidal_opposite\n\nvariables [category.{v\u2081} C]\n\n/-- The monoidal opposite of a morphism `f : X \u27f6 Y` is just `f`, thought of as `mop X \u27f6 mop Y`. -/\ndef quiver.hom.mop {X Y : C} (f : X \u27f6 Y) : @quiver.hom C\u1d39\u1d52\u1d56 _ (mop X) (mop Y) := f\n/-- We can think of a morphism `f : mop X \u27f6 mop Y` as a morphism `X \u27f6 Y`. -/\ndef quiver.hom.unmop {X Y : C\u1d39\u1d52\u1d56} (f : X \u27f6 Y) : unmop X \u27f6 unmop Y := f\n\nnamespace category_theory\n\nlemma mop_inj {X Y : C} :\n  function.injective (quiver.hom.mop : (X \u27f6 Y) \u2192 (mop X \u27f6 mop Y)) :=\n\u03bb _ _ H, congr_arg quiver.hom.unmop H\n\nlemma unmop_inj {X Y : C\u1d39\u1d52\u1d56} :\n  function.injective (quiver.hom.unmop : (X \u27f6 Y) \u2192 (unmop X \u27f6 unmop Y)) :=\n\u03bb _ _ H, congr_arg quiver.hom.mop H\n\n@[simp] lemma unmop_mop {X Y : C} {f : X \u27f6 Y} : f.mop.unmop = f := rfl\n@[simp] lemma mop_unmop {X Y : C\u1d39\u1d52\u1d56} {f : X \u27f6 Y} : f.unmop.mop = f := rfl\n\n@[simp] lemma mop_comp {X Y Z : C} {f : X \u27f6 Y} {g : Y \u27f6 Z} :\n  (f \u226b g).mop = f.mop \u226b g.mop := rfl\n@[simp] lemma mop_id {X : C} : (\ud835\udfd9 X).mop = \ud835\udfd9 (mop X) := rfl\n\n@[simp] lemma unmop_comp {X Y Z : C\u1d39\u1d52\u1d56} {f : X \u27f6 Y} {g : Y \u27f6 Z} :\n  (f \u226b g).unmop = f.unmop \u226b g.unmop := rfl\n@[simp] lemma unmop_id {X : C\u1d39\u1d52\u1d56} : (\ud835\udfd9 X).unmop = \ud835\udfd9 (unmop X) := rfl\n\n@[simp] lemma unmop_id_mop {X : C} : (\ud835\udfd9 (mop X)).unmop = \ud835\udfd9 X := rfl\n@[simp] lemma mop_id_unmop {X : C\u1d39\u1d52\u1d56} : (\ud835\udfd9 (unmop X)).mop = \ud835\udfd9 X := rfl\n\nnamespace iso\n\nvariables {X Y : C}\n\n/-- An isomorphism in `C` gives an isomorphism in `C\u1d39\u1d52\u1d56`. -/\n@[simps]\ndef mop (f : X \u2245 Y) : mop X \u2245 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\u2081} C]\n\nopen opposite monoidal_category\n\ninstance monoidal_category_op : monoidal_category C\u1d52\u1d56 :=\n{ tensor_obj := \u03bb X Y, op (unop X \u2297 unop Y),\n  tensor_hom := \u03bb X\u2081 Y\u2081 X\u2082 Y\u2082 f g, (f.unop \u2297 g.unop).op,\n  tensor_unit := op (\ud835\udfd9_ C),\n  associator := \u03bb X Y Z, (\u03b1_ (unop X) (unop Y) (unop Z)).symm.op,\n  left_unitor := \u03bb X, (\u03bb_ (unop X)).symm.op,\n  right_unitor := \u03bb X, (\u03c1_ (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\u1d52\u1d56) : X \u2297 Y = op (unop X \u2297 unop Y) := rfl\nlemma op_tensor_unit : (\ud835\udfd9_ C\u1d52\u1d56) = op (\ud835\udfd9_ C) := rfl\n\ninstance monoidal_category_mop : monoidal_category C\u1d39\u1d52\u1d56 :=\n{ tensor_obj := \u03bb X Y, mop (unmop Y \u2297 unmop X),\n  tensor_hom := \u03bb X\u2081 Y\u2081 X\u2082 Y\u2082 f g, (g.unmop \u2297 f.unmop).mop,\n  tensor_unit := mop (\ud835\udfd9_ C),\n  associator := \u03bb X Y Z, (\u03b1_ (unmop Z) (unmop Y) (unmop X)).symm.mop,\n  left_unitor := \u03bb X, (\u03c1_ (unmop X)).mop,\n  right_unitor := \u03bb X, (\u03bb_ (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\u1d39\u1d52\u1d56) : X \u2297 Y = mop (unmop Y \u2297 unmop X) := rfl\nlemma mop_tensor_unit : (\ud835\udfd9_ C\u1d39\u1d52\u1d56) = mop (\ud835\udfd9_ 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 `\u03b1 \u2192 \u03b1 \u2192 ... \u2192 \u03b1`. -/\ndef arity (\u03b1 : Type u) : \u2115 \u2192 Type u :=\n  sorry\n\nnamespace arity\n\n\n/-- Constant `n`-ary function with value `a`. -/\ndef const {\u03b1 : Type u} (a : \u03b1) (n : \u2115) : arity \u03b1 n :=\n  sorry\n\nprotected instance arity.inhabited {\u03b1 : Type u_1} {n : \u2115} [Inhabited \u03b1] : Inhabited (arity \u03b1 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 : (\u03b1 : Type u) \u2192 (\u03b1 \u2192 pSet) \u2192 pSet\n\nnamespace pSet\n\n\n/-- The underlying type of a pre-set -/\ndef type : pSet \u2192 Type u :=\n  sorry\n\n/-- The underlying pre-set family of a pre-set -/\ndef func (x : pSet) : type x \u2192 pSet :=\n  sorry\n\ntheorem mk_type_func (x : pSet) : mk (type x) (func x) = x :=\n  pSet.cases_on x\n    fun (x_\u03b1 : Type u_1) (x_A : x_\u03b1 \u2192 pSet) =>\n      idRhs (mk (type (mk x_\u03b1 x_A)) (func (mk x_\u03b1 x_A)) = mk (type (mk x_\u03b1 x_A)) (func (mk x_\u03b1 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 (\u03b1 : Type u_1) (z : \u03b1 \u2192 pSet) (m : \u03b1 \u2192 pSet \u2192 Prop) (_x : pSet) => sorry) x y\n\ntheorem equiv.refl (x : pSet) : equiv x x :=\n  pSet.rec_on x\n    fun (\u03b1 : Type u_1) (A : \u03b1 \u2192 pSet) (IH : \u2200 (\u1fb0 : \u03b1), equiv (A \u1fb0) (A \u1fb0)) =>\n      { left := fun (a : \u03b1) => Exists.intro a (IH a), right := fun (a : \u03b1) => Exists.intro a (IH a) }\n\ntheorem equiv.euc {x : pSet} {y : pSet} {z : pSet} : equiv x y \u2192 equiv z y \u2192 equiv x z := sorry\n\ntheorem equiv.symm {x : pSet} {y : pSet} : equiv x y \u2192 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 \u2192 pSet \u2192 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 \u2194 x \u2286 y \u2227 y \u2286 x := sorry\n\ntheorem subset.congr_left {x : pSet} {y : pSet} {z : pSet} : equiv x y \u2192 (x \u2286 z \u2194 y \u2286 z) := sorry\n\ntheorem subset.congr_right {x : pSet} {y : pSet} {z : pSet} : equiv x y \u2192 (z \u2286 x \u2194 z \u2286 y) := sorry\n\n/-- `x \u2208 y` as pre-sets if `x` is extensionally equivalent to a member\n  of the family `y`. -/\ndef mem : pSet \u2192 pSet \u2192 Prop :=\n  sorry\n\nprotected instance has_mem : has_mem pSet pSet :=\n  has_mem.mk mem\n\ntheorem mem.mk {\u03b1 : Type u} (A : \u03b1 \u2192 pSet) (a : \u03b1) : A a \u2208 mk \u03b1 A :=\n  (fun (this : mem (A a) (mk \u03b1 A)) => this) (Exists.intro a (equiv.refl (A a)))\n\ntheorem mem.ext {x : pSet} {y : pSet} : (\u2200 (w : pSet), w \u2208 x \u2194 w \u2208 y) \u2192 equiv x y := sorry\n\ntheorem mem.congr_right {x : pSet} {y : pSet} : equiv x y \u2192 \u2200 {w : pSet}, w \u2208 x \u2194 w \u2208 y := sorry\n\ntheorem equiv_iff_mem {x : pSet} {y : pSet} : equiv x y \u2194 \u2200 {w : pSet}, w \u2208 x \u2194 w \u2208 y := sorry\n\ntheorem mem.congr_left {x : pSet} {y : pSet} : equiv x y \u2192 \u2200 {w : pSet}, x \u2208 w \u2194 y \u2208 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 \u2208 u\n\n/-- Two pre-sets are equivalent iff they have the same members. -/\ntheorem equiv.eq {x : pSet} {y : pSet} : equiv x y \u2194 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 := \u2205 }\n\ntheorem mem_empty (x : pSet) : \u00acx \u2208 \u2205 := sorry\n\n/-- Insert an element into a pre-set -/\nprotected def insert : pSet \u2192 pSet \u2192 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 \u2205\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 : \u2115 \u2192 pSet :=\n  sorry\n\n/-- The von Neumann ordinal \u03c9 -/\ndef omega : pSet :=\n  mk (ulift \u2115) fun (n : ulift \u2115) => of_nat (ulift.down n)\n\n/-- The separation operation `{x \u2208 a | p x}` -/\nprotected def sep (p : set pSet) : pSet \u2192 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 \u2192 pSet :=\n  sorry\n\ntheorem mem_powerset {x : pSet} {y : pSet} : y \u2208 powerset x \u2194 y \u2286 x := sorry\n\n/-- The set union operator -/\ndef Union : pSet \u2192 pSet :=\n  sorry\n\ntheorem mem_Union {x : pSet} {y : pSet} : y \u2208 Union x \u2194 \u2203 (z : pSet), \u2203 (_x : z \u2208 x), y \u2208 z := sorry\n\n/-- The image of a function -/\ndef image (f : pSet \u2192 pSet) : pSet \u2192 pSet :=\n  sorry\n\ntheorem mem_image {f : pSet \u2192 pSet} (H : \u2200 {x y : pSet}, equiv x y \u2192 equiv (f x) (f y)) {x : pSet} {y : pSet} : y \u2208 image f x \u2194 \u2203 (z : pSet), \u2203 (H : z \u2208 x), equiv y (f z) := sorry\n\n/-- Universe lift operation -/\nprotected def lift : pSet \u2192 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 \u2208 embed :=\n  Exists.intro (ulift.up x) (equiv.refl (pSet.lift x))\n\n/-- Function equivalence is defined so that `f ~ g` iff\n  `\u2200 x y, x ~ y \u2192 f x ~ g y`. This extends to equivalence of n-ary\n  functions. -/\ndef arity.equiv {n : \u2115} : arity pSet n \u2192 arity pSet n \u2192 Prop :=\n  sorry\n\ntheorem arity.equiv_const {a : pSet} (n : \u2115) : 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 : \u2115) :=\n  Subtype fun (x : arity pSet n) => arity.equiv x x\n\nprotected instance resp.inhabited {n : \u2115} : Inhabited (resp n) :=\n  { default := { val := arity.const Inhabited.default n, property := sorry } }\n\ndef resp.f {n : \u2115} (f : resp (n + 1)) (x : pSet) : resp n :=\n  { val := subtype.val f x, property := sorry }\n\ndef resp.equiv {n : \u2115} (a : resp n) (b : resp n) :=\n  arity.equiv (subtype.val a) (subtype.val b)\n\ntheorem resp.refl {n : \u2115} (a : resp n) : resp.equiv a a :=\n  subtype.property a\n\ntheorem resp.euc {n : \u2115} {a : resp n} {b : resp n} {c : resp n} : resp.equiv a b \u2192 resp.equiv c b \u2192 resp.equiv a c := sorry\n\nprotected instance resp.setoid {n : \u2115} : 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 : \u2115} : Subtype fun (f : resp n \u2192 arity Set n) => \u2200 (a b : resp n), equiv a b \u2192 f a = f b :=\n  sorry\n\n/-- An equivalence-respecting function yields an n-ary Set function. -/\ndef eval (n : \u2115) : resp n \u2192 arity Set n :=\n  subtype.val eval_aux\n\ntheorem eval_val {n : \u2115} {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 : \u2115) : arity Set n \u2192 Type (u + 1)\nwhere\n| mk : (f : resp n) \u2192 definable n (resp.eval n f)\n\ndef definable.eq_mk {n : \u2115} (f : resp n) {s : arity Set n} (H : resp.eval n f = s) : definable n s :=\n  sorry\n\ndef definable.resp {n : \u2115} (s : arity Set n) [definable n s] : resp n :=\n  sorry\n\ntheorem definable.eq {n : \u2115} (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 : \u2115} (F : arity Set n) : pSet.definable n F :=\n  sorry\n\nend classical\n\n\nnamespace Set\n\n\ndef mk : pSet \u2192 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 : \u2115} {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 \u2192 Set \u2192 Prop :=\n  quotient.lift\u2082 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 \u2208 u\n\nprotected def subset (x : Set) (y : Set) :=\n  \u2200 {z : Set}, z \u2208 x \u2192 z \u2208 y\n\nprotected instance has_subset : has_subset Set :=\n  has_subset.mk Set.subset\n\ntheorem subset_def {x : Set} {y : Set} : x \u2286 y \u2194 \u2200 {z : Set}, z \u2208 x \u2192 z \u2208 y :=\n  iff.rfl\n\ntheorem subset_iff (x : pSet) (y : pSet) : mk x \u2286 mk y \u2194 x \u2286 y := sorry\n\ntheorem ext {x : Set} {y : Set} : (\u2200 (z : Set), z \u2208 x \u2194 z \u2208 y) \u2192 x = y :=\n  quotient.induction_on\u2082 x y\n    fun (u v : pSet) (h : \u2200 (z : Set), z \u2208 quotient.mk u \u2194 z \u2208 quotient.mk v) =>\n      quotient.sound (pSet.mem.ext fun (w : pSet) => h (quotient.mk w))\n\ntheorem ext_iff {x : Set} {y : Set} : (\u2200 (z : Set), z \u2208 x \u2194 z \u2208 y) \u2194 x = y := sorry\n\n/-- The empty set -/\ndef empty : Set :=\n  mk \u2205\n\nprotected instance has_emptyc : has_emptyc Set :=\n  has_emptyc.mk empty\n\nprotected instance inhabited : Inhabited Set :=\n  { default := \u2205 }\n\n@[simp] theorem mem_empty (x : Set) : \u00acx \u2208 \u2205 :=\n  quotient.induction_on x pSet.mem_empty\n\ntheorem eq_empty (x : Set) : x = \u2205 \u2194 \u2200 (y : Set), \u00acy \u2208 x := sorry\n\n/-- `insert x y` is the set `{x} \u222a y` -/\nprotected def insert : Set \u2192 Set \u2192 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 \u2205\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 \u2208 insert y z \u2194 x = y \u2228 x \u2208 z := sorry\n\n@[simp] theorem mem_singleton {x : Set} {y : Set} : x \u2208 singleton y \u2194 x = y :=\n  iff.trans mem_insert\n    { mp := fun (o : x = y \u2228 x \u2208 \u2205) => Or._oldrec (fun (h : x = y) => h) (fun (n : x \u2208 \u2205) => absurd n (mem_empty x)) o,\n      mpr := Or.inl }\n\n@[simp] theorem mem_pair {x : Set} {y : Set} {z : Set} : x \u2208 insert y (singleton z) \u2194 x = y \u2228 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 : \u2205 \u2208 omega :=\n  (fun (this : pSet.mem \u2205 pSet.omega) => this) (Exists.intro (ulift.up 0) (pSet.equiv.refl \u2205))\n\n@[simp] theorem omega_succ {n : Set} : n \u2208 omega \u2192 insert n n \u2208 omega := sorry\n\n/-- `{x \u2208 a | p x}` is the set of elements in `a` satisfying `p` -/\nprotected def sep (p : Set \u2192 Prop) : Set \u2192 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 \u2192 Prop} {x : Set} {y : Set} : y \u2208 has_sep.sep (fun (y : Set) => p y) x \u2194 y \u2208 x \u2227 p y := sorry\n\n/-- The powerset operation, the collection of subsets of a set -/\ndef powerset : Set \u2192 Set :=\n  pSet.resp.eval 1 { val := pSet.powerset, property := sorry }\n\n@[simp] theorem mem_powerset {x : Set} {y : Set} : y \u2208 powerset x \u2194 y \u2286 x := sorry\n\ntheorem Union_lem {\u03b1 : Type u} {\u03b2 : Type u} (A : \u03b1 \u2192 pSet) (B : \u03b2 \u2192 pSet) (\u03b1\u03b2 : \u2200 (a : \u03b1), \u2203 (b : \u03b2), pSet.equiv (A a) (B b)) (a : pSet.type (pSet.Union (pSet.mk \u03b1 A))) : \u2203 (b : pSet.type (pSet.Union (pSet.mk \u03b2 B))),\n  pSet.equiv (pSet.func (pSet.Union (pSet.mk \u03b1 A)) a) (pSet.func (pSet.Union (pSet.mk \u03b2 B)) b) := sorry\n\n/-- The union operator, the collection of elements of elements of a set -/\ndef Union : Set \u2192 Set :=\n  pSet.resp.eval 1 { val := pSet.Union, property := sorry }\n\nnotation:1024 \"\u22c3\" => Mathlib.Set.Union\n\n@[simp] theorem mem_Union {x : Set} {y : Set} : y \u2208 \u22c3 \u2194 \u2203 (z : Set), \u2203 (H : z \u2208 x), y \u2208 z := sorry\n\n@[simp] theorem Union_singleton {x : Set} : \u22c3 = x := sorry\n\ntheorem singleton_inj {x : Set} {y : Set} (H : singleton x = singleton y) : x = y :=\n  let this : \u22c3 = \u22c3 := congr_arg \u22c3 H;\n  eq.mp (Eq._oldrec (Eq.refl (x = \u22c3)) Union_singleton) (eq.mp (Eq._oldrec (Eq.refl (\u22c3 = \u22c3)) Union_singleton) this)\n\n/-- The binary union operation -/\nprotected def union (x : Set) (y : Set) : Set :=\n  \u22c3\n\n/-- The binary intersection operation -/\nprotected def inter (x : Set) (y : Set) : Set :=\n  has_sep.sep (fun (z : Set) => z \u2208 y) x\n\n/-- The set difference operation -/\nprotected def diff (x : Set) (y : Set) : Set :=\n  has_sep.sep (fun (z : Set) => \u00acz \u2208 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 \u2208 x \u222a y \u2194 z \u2208 x \u2228 z \u2208 y := sorry\n\n@[simp] theorem mem_inter {x : Set} {y : Set} {z : Set} : z \u2208 x \u2229 y \u2194 z \u2208 x \u2227 z \u2208 y :=\n  mem_sep\n\n@[simp] theorem mem_diff {x : Set} {y : Set} {z : Set} : z \u2208 x \\ y \u2194 z \u2208 x \u2227 \u00acz \u2208 y :=\n  mem_sep\n\ntheorem induction_on {p : Set \u2192 Prop} (x : Set) (h : \u2200 (x : Set), (\u2200 (y : Set), y \u2208 x \u2192 p y) \u2192 p x) : p x := sorry\n\ntheorem regularity (x : Set) (h : x \u2260 \u2205) : \u2203 (y : Set), \u2203 (H : y \u2208 x), x \u2229 y = \u2205 := sorry\n\n/-- The image of a (definable) set function -/\ndef image (f : Set \u2192 Set) [H : pSet.definable 1 f] : Set \u2192 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 \u2192 Set) [H : pSet.definable 1 f] (x : Set) {y : Set} (h : y \u2208 x) : f y \u2208 image f x := sorry\n\n@[simp] theorem mem_image {f : Set \u2192 Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : y \u2208 image f x \u2194 \u2203 (z : Set), \u2203 (H : z \u2208 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) \u2208 x \u00d7 y | p a b}` -/\ndef pair_sep (p : Set \u2192 Set \u2192 Prop) (x : Set) (y : Set) : Set :=\n  has_sep.sep (fun (z : Set) => \u2203 (a : Set), \u2203 (H : a \u2208 x), \u2203 (b : Set), \u2203 (H : b \u2208 y), z = pair a b \u2227 p a b)\n    (powerset (powerset (x \u222a y)))\n\n@[simp] theorem mem_pair_sep {p : Set \u2192 Set \u2192 Prop} {x : Set} {y : Set} {z : Set} : z \u2208 pair_sep p x y \u2194 \u2203 (a : Set), \u2203 (H : a \u2208 x), \u2203 (b : Set), \u2203 (H : b \u2208 y), z = pair a b \u2227 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' \u2227 y = y' := sorry\n\n/-- The cartesian product, `{(a, b) | a \u2208 x, b \u2208 y}` -/\ndef prod : Set \u2192 Set \u2192 Set :=\n  pair_sep fun (a b : Set) => True\n\n@[simp] theorem mem_prod {x : Set} {y : Set} {z : Set} : z \u2208 prod x y \u2194 \u2203 (a : Set), \u2203 (H : a \u2208 x), \u2203 (b : Set), \u2203 (H : b \u2208 y), z = pair a b := sorry\n\n@[simp] theorem pair_mem_prod {x : Set} {y : Set} {a : Set} {b : Set} : pair a b \u2208 prod x y \u2194 a \u2208 x \u2227 b \u2208 y := sorry\n\n/-- `is_func x y f` is the assertion `f : x \u2192 y` where `f` is a ZFC function\n  (a set of ordered pairs) -/\ndef is_func (x : Set) (y : Set) (f : Set) :=\n  f \u2286 prod x y \u2227 \u2200 (z : Set), z \u2208 x \u2192 exists_unique fun (w : Set) => pair z w \u2208 f\n\n/-- `funs x y` is `y ^ x`, the set of all set functions `x \u2192 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 \u2208 funs x y \u2194 is_func x y f := sorry\n\n-- TODO(Mario): Prove this computably\n\nprotected instance map_definable_aux (f : Set \u2192 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 \u2208 x` to `f a` -/\ndef map (f : Set \u2192 Set) [H : pSet.definable 1 f] : Set \u2192 Set :=\n  image fun (y : Set) => pair y (f y)\n\n@[simp] theorem mem_map {f : Set \u2192 Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : y \u2208 map f x \u2194 \u2203 (z : Set), \u2203 (H : z \u2208 x), pair z (f z) = y :=\n  mem_image\n\ntheorem map_unique {f : Set \u2192 Set} [H : pSet.definable 1 f] {x : Set} {z : Set} (zx : z \u2208 x) : exists_unique fun (w : Set) => pair z w \u2208 map f x := sorry\n\n@[simp] theorem map_is_func {f : Set \u2192 Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : is_func x y (map f x) \u2194 \u2200 (z : Set), z \u2208 x \u2192 f z \u2208 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 := \u2205 }\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 \u2208 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 \u2192 Prop) (A : Class) :=\n  \u2203 (x : Set), \u2191x = A \u2227 p x\n\n/-- `A \u2208 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 \u2208 univ \u2194 \u2203 (x : Set), \u2191x = A :=\n  exists_congr fun (x : Set) => and_true (\u2191x = 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) => \u2191y \u2208 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 \u2208 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 (\ud835\udcab 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  \u22c3\u2080Class_to_Cong x\n\nnotation:1024 \"\u22c3\" => Mathlib.Class.Union\n\ntheorem of_Set.inj {x : Set} {y : Set} (h : \u2191x = \u2191y) : x = y := sorry\n\n@[simp] theorem to_Set_of_Set (p : Set \u2192 Prop) (x : Set) : to_Set p \u2191x \u2194 p x := sorry\n\n@[simp] theorem mem_hom_left (x : Set) (A : Class) : \u2191x \u2208 A \u2194 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 \u2194 x \u2208 y :=\n  iff.rfl\n\n@[simp] theorem subset_hom (x : Set) (y : Set) : \u2191x \u2286 \u2191y \u2194 x \u2286 y :=\n  iff.rfl\n\n@[simp] theorem sep_hom (p : Set \u2192 Prop) (x : Set) : \u2191(has_sep.sep (fun (y : Set) => p y) x) = has_sep.sep (fun (y : Set) => p y) \u2191x :=\n  set.ext fun (y : Set) => Set.mem_sep\n\n@[simp] theorem empty_hom : \u2191\u2205 = \u2205 :=\n  set.ext\n    fun (y : Set) => (fun (this : y \u2208 \u2191\u2205 \u2194 False) => this) (eq.mpr (id (propext (iff_false (y \u2208 \u2191\u2205)))) (Set.mem_empty y))\n\n@[simp] theorem insert_hom (x : Set) (y : Set) : insert x \u2191y = \u2191(insert x y) :=\n  set.ext fun (z : Set) => iff.symm Set.mem_insert\n\n@[simp] theorem union_hom (x : Set) (y : Set) : \u2191x \u222a \u2191y = \u2191(x \u222a y) :=\n  set.ext fun (z : Set) => iff.symm Set.mem_union\n\n@[simp] theorem inter_hom (x : Set) (y : Set) : \u2191x \u2229 \u2191y = \u2191(x \u2229 y) :=\n  set.ext fun (z : Set) => iff.symm Set.mem_inter\n\n@[simp] theorem diff_hom (x : Set) (y : Set) : \u2191x \\ \u2191y = \u2191(x \\ y) :=\n  set.ext fun (z : Set) => iff.symm Set.mem_diff\n\n@[simp] theorem powerset_hom (x : Set) : powerset \u2191x = \u2191(Set.powerset x) :=\n  set.ext fun (z : Set) => iff.symm Set.mem_powerset\n\n@[simp] theorem Union_hom (x : Set) : \u22c3 = \u2191\u22c3 := sorry\n\n/-- The definite description operator, which is {x} if `{a | p a} = {x}`\n  and \u2205 otherwise -/\ndef iota (p : Set \u2192 Prop) : Class :=\n  \u22c3\n\ntheorem iota_val (p : Set \u2192 Prop) (x : Set) (H : \u2200 (y : Set), p y \u2194 y = x) : iota p = \u2191x := 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 \u2192 Prop) \u2192 Set` function. -/\ntheorem iota_ex (p : Set \u2192 Prop) : iota p \u2208 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 \"\u2032\" => Mathlib.Class.fval\n\ntheorem fval_ex (F : Class) (A : Class) : F\u2032A \u2208 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 \u2192 Set} [H : pSet.definable 1 f] {x : Set} {y : Set} (h : y \u2208 x) : \u2191(map f x)\u2032\u2191y = \u2191(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 \u2208 y) x\n\ntheorem choice_mem_aux (x : Set) (h : \u00ac\u2205 \u2208 x) (y : Set) (yx : y \u2208 x) : (classical.epsilon fun (z : Set) => z \u2208 y) \u2208 y := sorry\n\ntheorem choice_is_func (x : Set) (h : \u00ac\u2205 \u2208 x) : is_func x \u22c3 (choice x) := sorry\n\ntheorem choice_mem (x : Set) (h : \u00ac\u2205 \u2208 x) (y : Set) (yx : y \u2208 x) : \u2191(choice x)\u2032\u2191y \u2208 \u2191y := 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": "import ircbot.types ircbot.support\nopen types support\n\nnamespace modules.ping_pong\n\ndef ping_pong_func (input : irc_text) : list irc_text :=\nmatch input with\n| irc_text.parsed_normal\n  { object := some ~nick!ident, type := message.privmsg,\n    args := [subject], text := \"\\\\ping\" } :=\n  let new_subject :=\n    if subject.front = '#' then subject else nick in\n  [privmsg new_subject $ sformat! \"{nick}, pong\"]\n| _ := []\nend\n\n/-- For testing: send \u201cpong\u201d after \u201c\\ping\u201d. -/\ndef ping_pong : bot_function :=\n  { name := \"ping-pong\",\n    syntax := some \"\\\\ping\",\n    description := \"ping-pong game!\",\n    func := pure \u2218 ping_pong_func }\n\ntheorem ping_pong_is_correct_on_channel (nick ident subject: string)\n  (on_channel : subject.front = '#') :\n  (ping_pong_func $ irc_text.parsed_normal\n    { object := some ~nick!ident,\n      type := message.privmsg,\n      args := [subject],\n      text := \"\\\\ping\" }) =\n  [privmsg subject $ sformat! \"{nick}, pong\"] := begin\n  intros, simp [ping_pong_func], rw [on_channel], trivial\nend\n\ntheorem ping_pong_is_correct_on_priv (nick ident subject bot_nickname : string)\n  (bot_nickname_is_correct : bot_nickname.front \u2260 '#')\n  (not_on_channel : subject = bot_nickname):\n  (ping_pong_func $ irc_text.parsed_normal\n    { object := some ~nick!ident,\n      type := message.privmsg,\n      args := [bot_nickname],\n      text := \"\\\\ping\" }) =\n  [privmsg nick $ sformat! \"{nick}, pong\"] := begin\n  intros, simp [privmsg], simp [ping_pong_func],\n  simp [privmsg], simp [bot_nickname_is_correct]\nend\n\nend modules.ping_pong\n", "meta": {"author": "forked-from-1kasper", "repo": "leanbot", "sha": "c61c8c7fdad7b05877e0d232719ce23d2999557f", "save_path": "github-repos/lean/forked-from-1kasper-leanbot", "path": "github-repos/lean/forked-from-1kasper-leanbot/leanbot-c61c8c7fdad7b05877e0d232719ce23d2999557f/ircbot/modules/ping_pong.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.07263670937204118, "lm_q1q2_score": 0.03546729907529704}}
{"text": "import CodeAction.Interface\nimport StatementAutoformalisation.Translate\nimport StatementAutoformalisation.Config.FixedPrompts\n\nnamespace Default\n\ndef LLMParams : LLM.Params :=\n{\n  openAIModel := \"gpt-3.5-turbo\",\n  temperature := 8,\n  n := 7,\n  maxTokens := 300,\n  stopTokens := #[\":=\", \"\\n\\n/-\", \"\\n/-\", \"/-\"],\n  systemMessage := \n  \"You are a coding assistant who translates from natural language to Lean Theorem Prover code following examples.\n   Follow EXACTLY the examples given.\"\n}\n\ndef SentenceSimilarityParams : SentenceSimilarity.Params :=\n{\n  source := \"data/prompts.json\",\n  sentenceTransformersModel := \"all-mpnet-base-v2\",\n  kind := \"theorem\",\n  field := \"doc_string\",\n  nSim := 15\n}\n\ndef KeywordExtractionParams : KeywordExtraction.Params :=\n{\n  nKw := 0\n}\n\ndef PromptParams : Prompt.Params :=\n{\n  toLLMParams := LLMParams, \n  toSentenceSimilarityParams := #[SentenceSimilarityParams], \n  toKeywordExtractionParams := #[KeywordExtractionParams],\n  fixedPrompts := leanChatPrompts,\n  useNames := #[],\n  useModules := #[],\n  useMainCtx? := false,\n  printMessage := DeclarationWithDocstring.toMessage\n  mkSuffix := id,\n  processCompletion := fun comment completion => s!\"{printAsComment comment}\\n{completion}\"\n}\n\ndef InterfaceParams : Interface.Params DeclarationWithDocstring :=\n{\n  title := \"Translate comment to Lean theorem statement (with default settings).\",\n  nearestOccurrence? := nearestComment,\n  extractText? := extractCommentText?,\n  action := fun stmt =>\n    Prompt.typecorrectTranslations \u27e8PromptParams, stmt\u27e9 >>= (pure \u00b7[0]!),\n  postProcess := fun _ => DeclarationWithDocstring.toString\n}\n\n@[codeActionProvider] def Action := performCodeAction InterfaceParams\n\nend Default", "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/StatementAutoformalisation/Config/Default.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.08151975485900514, "lm_q1q2_score": 0.03537806262416578}}
{"text": "/-\nCopyright (c) 2021 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport tactic.aesop.rule\n\nnamespace tactic\nnamespace aesop\n\nmeta inductive rule_builder_output\n| rule (r : rule) (imode : indexing_mode)\n| simp_lemmas (s : simp_lemmas)\n\nmeta def rule_builder := declaration \u2192 tactic rule_builder_output\n\nnamespace rule_builder\n\nmeta def tac : rule_builder := \u03bb d,\nmatch d.type with\n| `(tactic unit) := do\n  t \u2190 eval_expr (tactic unit) d.value,\n  pure $ rule_builder_output.rule\n    { tac := t,\n      description := to_fmt d.to_name }\n    indexing_mode.unindexed\n| _ := fail! \"Expected {d.to_name} to have type `tactic unit`.\"\nend\n\nmeta def apply_indexing_mode (type : expr) : tactic indexing_mode := do\n  head_constant \u2190 type.conclusion_head_constant,\n  pure $\n    match head_constant with\n    | some c := index_target_head c\n    | none := unindexed\n    end\n\nmeta def apply : rule_builder := \u03bb d, do\n  imode \u2190 apply_indexing_mode d.type,\n  let n := d.to_name,\n  pure $ rule_builder_output.rule\n    { tac := mk_const n >>= tactic.apply >> skip,\n      description := format! \"apply {n}\"}\n    imode\n\nmeta def normalization_simp_lemma : rule_builder := \u03bb d, do\n  let n := d.to_name,\n  s \u2190 simp_lemmas.mk.add_simp n <|> fail!\n    \"Expected {n} to be a (conditional) equation that can be used as a simp lemma.\",\n  pure $ rule_builder_output.simp_lemmas s\n\nmeta def no_tactic (d : declaration) : tactic unit :=\nmatch d.type with\n| `(tactic _) := fail! \"To register a tactic as an Aesop rule, it must have type `tactic unit`, but {d.to_name} has type `{d.type}`.\"\n| _ := pure ()\nend\n\nmeta def normalization_default : rule_builder := \u03bb d,\ntac d <|> normalization_simp_lemma d <|>\n  fail! \"Expected {d.to_name} to have type `tactic unit` or to be suitable as a simp lemma.\"\n\nmeta def safe_default : rule_builder := \u03bb d,\ntac d <|> (no_tactic d >> apply d)\n\nmeta def unsafe_default : rule_builder :=\nsafe_default\n\nend rule_builder\nend aesop\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/aesop/rule_builder.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702254064929193, "lm_q2_score": 0.09534945654437686, "lm_q1q2_score": 0.03530079130802087}}
{"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 tactic.alias\n! leanprover-community/mathlib commit c8ab806ef73c20cab1d87b5157e43a82c205f28e\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 `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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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\n\nopen Lean.Parser Tactic Interactive\n\nnamespace Tactic.Alias\n\n/-- An alias can be in one of three forms -/\nunsafe inductive target\n  | plain : Name \u2192 target\n  | forward : Name \u2192 target\n  | backwards : Name \u2192 target\n  deriving has_reflect\n#align tactic.alias.target tactic.alias.target\n\n/-- The name underlying an alias target -/\nunsafe def target.to_name : target \u2192 Name\n  | target.plain n => n\n  | target.forward n => n\n  | target.backwards n => n\n#align tactic.alias.target.to_name tactic.alias.target.to_name\n\n/-- The docstring for an alias. Used by `alias` _and_ by `to_additive` -/\nunsafe def target.to_string : target \u2192 String\n  | target.plain n => s! \"**Alias** of `{n}`.\"\n  | target.forward n => s! \"**Alias** of the forward direction of `{n}`.\"\n  | target.backwards n => s! \"**Alias** of the reverse direction of `{n}`.\"\n#align tactic.alias.target.to_string tactic.alias.target.to_string\n\n/-- An auxiliary attribute which is placed on definitions created by the `alias` command. -/\n@[user_attribute]\nunsafe def alias_attr : user_attribute Unit target\n    where\n  Name := `alias\n  descr := \"This definition is an alias of another.\"\n  parser := failed\n#align tactic.alias.alias_attr tactic.alias.alias_attr\n\n/-- The core tactic which handles `alias d \u2190 al`. Creates an alias `al` for declaration `d`. -/\nunsafe def alias_direct (doc : Option String) (d : declaration) (al : Name) : tactic Unit := do\n  updateex_env fun env =>\n      env\n        (match d with\n        | declaration.defn n ls t _ _ _ =>\n          declaration.defn al ls t (expr.const n (level.param <$> ls)) ReducibilityHints.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  let target := target.plain d.to_name\n  alias_attr al target tt\n  add_doc_string al (doc target)\n#align tactic.alias.alias_direct tactic.alias.alias_direct\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n      Given a proof of `\u03a0 x y z, a \u2194 b`, produces a proof of `\u03a0 x y z, a \u2192 b` or `\u03a0 x y z, b \u2192 a`\n      (depending on whether `iffmp` is `iff.mp` or `iff.mpr`). The variable `f` supplies the proof,\n      under the specified number of binders. -/\n    unsafe\n  def\n    mk_iff_mp_app\n    ( iffmp : Name ) : expr \u2192 ( \u2115 \u2192 expr ) \u2192 tactic expr\n    |\n        expr.pi n bi e t , f\n        =>\n        expr.lam n bi e <$> mk_iff_mp_app t fun n => f ( n + 1 ) ( expr.var n )\n      | q( $ ( a ) \u2194 $ ( b ) ) , f => pure <| @ expr.const true iffmp [ ] a b ( f 0 )\n      | _ , f => fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n#align tactic.alias.mk_iff_mp_app tactic.alias.mk_iff_mp_app\n\n/-- The core tactic which handles `alias d \u2194 al _` or `alias d \u2194 _ al`. `ns` is the current\nnamespace, and `is_forward` is true if this is the forward implication (the first form). -/\nunsafe def alias_iff (doc : Option String) (d : declaration) (ns al : Name) (is_forward : Bool) :\n    tactic Unit :=\n  if al = `_ then skip\n  else\n    let al := ns.append_namespace al\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      let v \u2190 mk_iff_mp_app iffmp t fun _ => expr.const d.to_name (level.param <$> ls)\n      let t' \u2190 infer_type v\n      updateex_env fun env => env (declaration.thm al ls t' <| task.pure v)\n      alias_attr al target tt\n      add_doc_string al (doc target)\n#align tactic.alias.alias_iff tactic.alias.alias_iff\n\n/-- Get the default names for left/right to be used by `alias d \u2194 ..`. -/\nunsafe def make_left_right : Name \u2192 tactic (Name \u00d7 Name)\n  | Name.mk_string s p => do\n    let buf : CharBuffer := s.toCharBuffer\n    let parts := s.splitOn '_'\n    let (left, _ :: right) \u2190 pure <| parts.span\u2093 (\u00b7 \u2260 \"iff\")\n    let pfx (a b : String) := a.toList.isPrefixOf\u2093 b.toList\n    let (suffix', right') \u2190 pure <| right.reverse.span\u2093 fun s => pfx \"left\" s \u2228 pfx \"right\" s\n    let right := right'.reverse\n    let suffix := suffix'.reverse\n    pure\n        (.str p (\"_\".intercalate (right ++ \"of\" :: left ++ suffix)),\n          .str p (\"_\".intercalate (left ++ \"of\" :: right ++ suffix)))\n  | _ => failed\n#align tactic.alias.make_left_right tactic.alias.make_left_right\n\n/-- The `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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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]\nunsafe def alias_cmd (meta_info : decl_meta_info) (_ : parse <| tk \"alias\") : lean.parser Unit := do\n  let old \u2190 ident\n  let d \u2190\n    (do\n          let old \u2190 resolve_constant old\n          get_decl old) <|>\n        fail (\"declaration \" ++ toString old ++ \" not found\")\n  let ns \u2190 get_current_namespace\n  let doc := meta_info.doc_string\n  (do\n        tk \"\u2190\" <|> tk \"<-\"\n        let aliases \u2190 many ident\n        \u2191(aliases fun al => alias_direct doc d (ns al))) <|>\n      do\n      tk \"\u2194\" <|> tk \"<->\"\n      let (left, right) \u2190\n        condM (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#align tactic.alias.alias_cmd tactic.alias.alias_cmd\n\nadd_tactic_doc\n  { Name := \"alias\"\n    category := DocCategory.cmd\n    declNames := [`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. -/\nunsafe def get_alias_target (n : Name) : tactic (Option target) := do\n  let tt \u2190 has_attribute' `alias n |\n    pure none\n  let v \u2190 alias_attr.get_param n\n  pure <| some v\n#align tactic.alias.get_alias_target tactic.alias.get_alias_target\n\nend Tactic.Alias\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/Alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.07921032247877664, "lm_q1q2_score": 0.035290538144303975}}
{"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 \u03b1` 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 (\u03b1 : Type u) :=\n  tactic \u03b1\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 \u00d7 expr) := do\n  let lhs_type \u2190 infer_type lhs\n  let rhs \u2190 mk_meta_var lhs_type\n  let new_target \u2190 mk_app Rel [lhs, rhs]\n  let new_g \u2190 mk_meta_var new_target\n  let gs \u2190 get_goals\n  set_goals [new_g]\n  c\n  try <| any_goals reflexivity\n  let n \u2190 num_goals\n  when (n \u2260 0) (fail \"convert tactic failed, there are unsolved goals\")\n  set_goals gs\n  let rhs \u2190 instantiate_mvars rhs\n  let new_g \u2190 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) \u2190 target_lhs_rhs\n  return lhs\n#align conv.lhs conv.lhs\n\nunsafe def rhs : conv expr := do\n  let (_, lhs, rhs) \u2190 target_lhs_rhs\n  return rhs\n#align conv.rhs conv.rhs\n\n/-- `\u22a2 lhs = rhs` ~~> `\u22a2 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 \u2190 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) \u2190 target_lhs_rhs\n  let new_target \u2190 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 \u2190\n    match s with\n      | some s => return s\n      | none => simp_lemmas.mk_default\n  let l \u2190 lhs\n  s u l cfg >>= change\n#align conv.dsimp conv.dsimp\n\nprivate unsafe def congr_aux : List CongrArgKind \u2192 List expr \u2192 tactic (List expr \u00d7 List expr)\n  | [], [] => return ([], [])\n  | k :: ks, a :: as => do\n    let (gs, largs) \u2190 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 \u2190 infer_type a\n        let rhs \u2190 mk_meta_var a_type\n        let g_type \u2190 mk_app `eq [a, rhs]\n        let g \u2190 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' \u2192 y = y' \u2192 f x y = f x' y'`). -/\nunsafe def congr : conv Unit := do\n  let (r, lhs, rhs) \u2190 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 \u2190 mk_congr_lemma_simp fn (some args.length)\n  let g :: gs \u2190 get_goals\n  let (new_gs, lemma_args) \u2190 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) \u2190 target_lhs_rhs\n    guard (r = `eq)\n    let expr.lam n _ _ _ \u2190 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": "def f (x : Nat) : IO Nat := do\n  IO.println \"hello\"\n  if x > 5 then\n    IO.println (\"x: \" ++ toString x)\n    IO.println \"done\"\n  pure (x + 1)\n\n#eval f 2\n#eval f 10\n\ndef g (x : Nat) : StateT Nat Id Unit := do\n  if x > 10 then\n    let s \u2190 get\n    set (s + x)\n  pure ()\n\ntheorem ex1 : (g 10).run 1 = ((), 1) :=\nrfl\n\ntheorem ex2 : (g 20).run 1 = ((), 21) :=\nrfl\n\ndef h (x : Nat) : StateT Nat Id Unit := do\nif x > 10 then {\n  let s \u2190 get;\nset (s + x) -- we don't need to respect indentation when `{` `}` are used\n}\npure ()\n\ntheorem ex3 : (h 10).run 1 = ((), 1) :=\nrfl\n\ntheorem ex4 : (h 20).run 1 = ((), 21) :=\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/nicerNestedDos.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.07369627428358223, "lm_q1q2_score": 0.03512214468276258}}
{"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\u27e8(\u03bb s, match s with | ordering.lt := \"lt\" | ordering.eq := \"eq\" | ordering.gt := \"gt\" end)\u27e9\n\nnamespace ordering\ndef swap : ordering \u2192 ordering\n| lt := gt\n| eq := eq\n| gt := lt\n\n@[inline] def or_else : ordering \u2192 ordering \u2192 ordering\n| lt _ := lt\n| eq o := o\n| gt _ := gt\n\ntheorem swap_swap : \u2200 (o : ordering), o.swap.swap = o\n| lt := rfl\n| eq := rfl\n| gt := rfl\nend ordering\n\ndef cmp_using {\u03b1 : Type u} (lt : \u03b1 \u2192 \u03b1 \u2192 Prop) [decidable_rel lt] (a b : \u03b1) : ordering :=\nif lt a b      then ordering.lt\nelse if lt b a then ordering.gt\nelse                ordering.eq\n\ndef cmp {\u03b1 : Type u} [has_lt \u03b1] [decidable_rel ((<) : \u03b1 \u2192 \u03b1 \u2192 Prop)] (a b : \u03b1) : ordering :=\ncmp_using (<) a b\n\ninstance : decidable_eq ordering :=\n\u03bb a b,\n  match a with\n  | ordering.lt :=\n    match b with\n    | ordering.lt := is_true rfl\n    | ordering.eq := is_false (\u03bb h, ordering.no_confusion h)\n    | ordering.gt := is_false (\u03bb h, ordering.no_confusion h)\n    end\n  | ordering.eq :=\n    match b with\n    | ordering.lt := is_false (\u03bb h, ordering.no_confusion h)\n    | ordering.eq := is_true rfl\n    | ordering.gt := is_false (\u03bb h, ordering.no_confusion h)\n    end\n  | ordering.gt :=\n    match b with\n    | ordering.lt := is_false (\u03bb h, ordering.no_confusion h)\n    | ordering.eq := is_false (\u03bb 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 \u03b1 (ringAdd ?\u03b1 ?s) ?x ?x`\n  and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys\n  respctively\n  ```\n  \u27e8Add.add, 4\u27e9, *, *, *, *\n  \u27e8Add.add, 4\u27e9, *, *, \u27e8a,0\u27e9, \u27e8b,0\u27e9\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 \u2192 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 \u2192 Key s \u2192 Bool\n  | .lit v\u2081,        .lit v\u2082        => v\u2081 < v\u2082\n  | .fvar n\u2081 a\u2081,    .fvar n\u2082 a\u2082    => Name.quickLt n\u2081.name n\u2082.name || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | .const n\u2081 a\u2081,   .const n\u2082 a\u2082   => Name.quickLt n\u2081 n\u2082 || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | .proj s\u2081 i\u2081 a\u2081, .proj s\u2082 i\u2082 a\u2082 => Name.quickLt s\u2081 s\u2082 || (s\u2081 == s\u2082 && i\u2081 < i\u2082) || (s\u2081 == s\u2082 && i\u2081 == i\u2082 && a\u2081 < a\u2082)\n  | k\u2081,             k\u2082             => k\u2081.ctorIdx < k\u2082.ctorIdx\n\ninstance : LT (Key s) := \u27e8fun a b => Key.lt a b\u27e9\ninstance (a b : Key s) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key s \u2192 Format\n  | .star                   => \"*\"\n  | .other                  => \"\u25fe\"\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                  => \"\u2192\"\n\ninstance : ToFormat (Key s) := \u27e8Key.format\u27e9\n\ndef Key.arity : (Key s) \u2192 Nat\n  | .const _ a  => a\n  | .fvar _ a   => a\n  | .arrow      => 2\n  | .proj _ _ a => 1 + a\n  | _           => 0\n\ninstance : Inhabited (Trie \u03b1 s) := \u27e8.node #[] #[]\u27e9\n\ndef empty : DiscrTree \u03b1 s := { root := {} }\n\npartial def Trie.format [ToFormat \u03b1] : Trie \u03b1 s \u2192 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 \u27e8k, c\u27e9 => Format.line ++ Format.paren (Std.format k ++ \" => \" ++ format c))\n\ninstance [ToFormat \u03b1] : ToFormat (Trie \u03b1 s) := \u27e8Trie.format\u27e9\n\npartial def format [ToFormat \u03b1] (d : DiscrTree \u03b1 s) : Format :=\n  let (_, r) := d.root.foldl\n    (fun (p : Bool \u00d7 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 \u03b1] : ToFormat (DiscrTree \u03b1 s) := \u27e8format\u27e9\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 \u03b1 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 \u03b1]`) 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., `{\u03b1 : 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 \u27e8i, h\u27e9\n    if info.isInstImplicit then\n      return true\n    else if info.isImplicit || info.isStrictImplicit then\n      return not (\u2190 isType a)\n    else\n      isProof a\n  else\n    isProof a\n\nprivate partial def pushArgsAux (infos : Array ParamInfo) : Nat \u2192 Expr \u2192 Array Expr \u2192 MetaM (Array Expr)\n  | i, .app f a, todo => do\n    if (\u2190 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 (\u2190 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 (\u2190 isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false\n  else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then\n    if (\u2190 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 \u2190 whnfCore e (simpleReduceOnly := simpleReduce)\n  match (\u2190 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 \u2218 List.map g` would be mapped into the key `Key.other`\n  since the function composition `\u2218` 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 \u2190 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 \u2190 whnfCore e (simpleReduceOnly := simpleReduce)\n    match (\u2190 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 \u00d7 Array Expr) := do\n  if hasNoindexAnnotation e then\n    return (.star, todo)\n  else\n    let e \u2190 reduceDT e root (simpleReduce := s)\n    let fn := e.getAppFn\n    let push (k : Key s) (nargs : Nat) (todo : Array Expr): MetaM (Key s \u00d7 Array Expr) := do\n      let info \u2190 getFunInfoNArgs fn nargs\n      let todo \u2190 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 (\u2190 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 (\u2190 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 (\u2190 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) \u2190 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 : \u03b1) (i : Nat) : Trie \u03b1 s :=\n  if h : i < keys.size then\n    let k := keys.get \u27e8i, h\u27e9\n    let c := createNodes keys v (i+1)\n    .node #[] #[(k, c)]\n  else\n    .node #[v] #[]\n\nprivate def insertVal [BEq \u03b1] (vs : Array \u03b1) (v : \u03b1) : Array \u03b1 :=\n  if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq \u03b1] (keys : Array (Key s)) (v : \u03b1) : Nat \u2192 Trie \u03b1 s \u2192 Trie \u03b1 s\n  | i, .node vs cs =>\n    if h : i < keys.size then\n      let k := keys.get \u27e8i, h\u27e9\n      let c := Id.run $ cs.binInsertM\n          (fun a b => a.1 < b.1)\n          (fun \u27e8_, s\u27e9 => 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 \u03b1] (d : DiscrTree \u03b1 s) (keys : Array (Key s)) (v : \u03b1) : DiscrTree \u03b1 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 \u03b1] (d : DiscrTree \u03b1 s) (e : Expr) (v : \u03b1) : MetaM (DiscrTree \u03b1 s) := do\n  let keys \u2190 mkPath e\n  return d.insertCore keys v\n\nprivate def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key s \u00d7 Array Expr) := do\n  let e \u2190 reduceDT e root (simpleReduce := s)\n  match e.getAppFn with\n  | .lit v         => return (.lit v, #[])\n  | .const c _     =>\n    if (\u2190 getConfig).isDefEqStuckEx && e.hasExprMVar then\n      if (\u2190 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 \u2192 Type\n              | bool   => Bool\n              | fn a b => a.interp \u2192 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? (\u2190 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 (\u2190 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 \u2190 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 (\u2190 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 \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key s \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree \u03b1 s) : Array \u03b1 :=\n  let result : Array \u03b1 := .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 \u00d7 Trie \u03b1 s)) (k : Key s) : Option (Key s \u00d7 Trie \u03b1 s) :=\n  cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie \u03b1 s) (result : Array \u03b1) : MetaM (Array \u03b1) := 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) \u2190 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 \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) : MetaM (Array \u03b1) :=\n        match findKey cs k with\n        | none   => return result\n        | some c => getMatchLoop (todo ++ args) c.2 result\n      let result \u2190 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 #[] (\u2190 visitNonStar k args result)\n      | _      => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree \u03b1 s) (k : Key s) (args : Array Expr) (result : Array \u03b1) : MetaM (Array \u03b1) :=\n  match d.root.find? k with\n  | none   => return result\n  | some c => getMatchLoop args c result\n\nprivate def getMatchCore (d : DiscrTree \u03b1 s) (e : Expr) : MetaM (Key s \u00d7 Array \u03b1) :=\n  withReducible do\n    let result := getStarResult d\n    let (k, args) \u2190 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, (\u2190 getMatchRoot d k args (\u2190 getMatchRoot d .other #[] result)))\n    | _      => return (k, (\u2190 getMatchRoot d k args result))\n\n/--\n  Find values that match `e` in `d`.\n-/\ndef getMatch (d : DiscrTree \u03b1 s) (e : Expr) : MetaM (Array \u03b1) :=\n  return (\u2190 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 \u03b1 s) (e : Expr) : MetaM (Array (\u03b1 \u00d7 Nat)) := do\n  let (k, result) \u2190 getMatchCore d e\n  let result := result.map (\u00b7, 0)\n  if !e.isApp then\n    return result\n  else if !(\u2190 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 (\u03b1 \u00d7 Nat)) : MetaM (Array (\u03b1 \u00d7 Nat)) := do\n    let result := result ++ (\u2190 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 \u03b1 s) (e : Expr) : MetaM (Array \u03b1) :=\n  withReducible do\n    let (k, args) \u2190 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 \u03b1 s) (result : Array \u03b1) : MetaM (Array \u03b1) := 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 \u27e8k, c\u27e9 => 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) \u2190 getUnifyKeyArgs e (root := false)\n        let visitStar (result : Array \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) : MetaM (Array \u03b1) :=\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 \u27e8k, c\u27e9 => process k.arity todo c result\n        -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n        | .arrow => visitNonStar .other #[] (\u2190 visitNonStar k args (\u2190 visitStar result))\n        | _      => visitNonStar k args (\u2190 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 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Aesop\n\nset_option aesop.check.all true\n\n-- We used to add local rules to the `default` rule set, but this is doesn't\n-- work well when the default rule set is disabled. Now we add local rules to\n-- a separate `local` rule set.\nexample : Unit := by\n  fail_if_success\n    aesop (rule_sets [-default, -builtin]) (options := { terminal := true })\n  fail_if_success\n    aesop (add safe PUnit.unit) (rule_sets [-default, -builtin, -\u00ablocal\u00bb])\n      (options := { terminal := true })\n  aesop (add safe PUnit.unit) (rule_sets [-default, -builtin])\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/run/LocalRuleSet.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.07585818106587035, "lm_q1q2_score": 0.03497189431947805}}
{"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 \u27f6 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 \u27f6 Y) : Prop :=\n(is_compact_preimage : \u2200 U : set Y.carrier, is_open U \u2192 is_compact U \u2192 is_compact (f.1.base \u207b\u00b9' U))\n\nlemma quasi_compact_iff_spectral : quasi_compact f \u2194 is_spectral_map f.1.base :=\n\u27e8\u03bb \u27e8h\u27e9, \u27e8by continuity, h\u27e9, \u03bb h, \u27e8h.2\u27e9\u27e9\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\u03bb X Y f hf, compact_space X.carrier\n\n@[priority 900]\ninstance quasi_compact_of_is_iso {X Y : Scheme} (f : X \u27f6 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 \u27f6 Y) (g : Y \u27f6 Z)\n  [quasi_compact f] [quasi_compact g] : quasi_compact (f \u226b 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 \u2227 is_open U \u2194\n    \u2203 (s : set X.affine_opens), s.finite \u2227 U = \u22c3 (i : X.affine_opens) (h : i \u2208 s), i :=\nbegin\n  apply opens.is_basis.is_compact_open_iff_eq_finite_Union\n    (coe : X.affine_opens \u2192 opens X.carrier),\n  { rw subtype.range_coe, exact is_basis_affine_open X },\n  { exact \u03bb 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 \u2227 is_open U \u2194\n    \u2203 (s : set (X.presheaf.obj (op \u22a4))), s.finite \u2227\n      U = \u22c3 (i : X.presheaf.obj (op \u22a4)) (h : i \u2208 s), X.basic_open i :=\n(is_basis_basic_open X).is_compact_open_iff_eq_finite_Union _\n  (\u03bb i, ((top_is_affine_open _).basic_open_is_affine _).is_compact) _\n\nlemma quasi_compact_iff_forall_affine : quasi_compact f \u2194\n  \u2200 U : opens Y.carrier, is_affine_open U \u2192 is_compact (f.1.base \u207b\u00b9' (U : set Y.carrier)) :=\nbegin\n  rw quasi_compact_iff,\n  refine \u27e8\u03bb H U hU, H U U.is_open hU.is_compact, _\u27e9,\n  intros H U hU hU',\n  obtain \u27e8S, hS, rfl\u27e9 := (is_compact_open_iff_eq_finset_affine_union U).mp \u27e8hU', hU\u27e9,\n  simp only [set.preimage_Union, subtype.val_eq_coe],\n  exact hS.is_compact_bUnion (\u03bb i _, H i i.prop)\nend\n\n@[simp] lemma quasi_compact.affine_property_to_property {X Y : Scheme} (f : X \u27f6 Y) :\n  (quasi_compact.affine_property : _).to_property f \u2194\n    is_affine Y \u2227 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 \u2194 target_affine_locally quasi_compact.affine_property f :=\nbegin\n  rw quasi_compact_iff_forall_affine,\n  transitivity (\u2200 U : Y.affine_opens, is_compact (f.1.base \u207b\u00b9' (U : set Y.carrier))),\n  { exact \u27e8\u03bb h U, h U U.prop, \u03bb h U hU, h \u27e8U, hU\u27e9\u27e9 },\n  apply forall_congr,\n  exact \u03bb _, 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 \u27e8s, hs, e\u27e9 := (is_compact_open_iff_eq_finset_affine_union _).mp \u27e8hU, U.is_open\u27e9,\n  let g : s \u2192 X.affine_opens,\n  { intro V,\n    use V.1 \u2293 X.basic_open f,\n    have : V.1.1 \u27f6 U,\n    { apply hom_of_le, change _ \u2286 (U : set X.carrier), rw e,\n      convert @set.subset_Union\u2082 _ _ _ (\u03bb (U : X.affine_opens) (h : U \u2208 s), \u2191U) V V.prop using 1,\n      refl },\n    erw \u2190 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 \u27e8set.range g, set.finite_range g, _\u27e9,\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\u2082_inter],\n  apply le_antisymm; apply set.Union\u2082_subset,\n  { intros i hi,\n    refine set.subset.trans _ (set.subset_Union\u2082 _ (set.mem_range_self \u27e8i, hi\u27e9)),\n    exact set.subset.rfl },\n  { rintro \u27e8i, hi\u27e9 \u27e8\u27e8j, hj\u27e9, hj'\u27e9,\n    rw \u2190 hj',\n    refine set.subset.trans _ (set.subset_Union\u2082 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 \u22a2,\n    change compact_space ((opens.map f.val.base).obj (Y.basic_open r)),\n    rw Scheme.preimage_basic_open f r,\n    erw \u2190 is_compact_iff_compact_space,\n    rw \u2190 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 \u2190 is_affine_open.basic_open_union_eq_self_iff at hS,\n    delta quasi_compact.affine_property,\n    rw \u2190 is_compact_univ_iff,\n    change is_compact ((opens.map f.val.base).obj \u22a4).1,\n    rw \u2190 hS,\n    dsimp [opens.map],\n    simp only [opens.coe_supr, set.preimage_Union, subtype.val_eq_coe],\n    exacts [is_compact_Union (\u03bb 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 \u27f6 Y) :\n  tfae [quasi_compact f,\n    \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} Y) [\u2200 i, is_affine (\ud835\udcb0.obj i)],\n      \u2200 (i : \ud835\udcb0.J), compact_space (pullback f (\ud835\udcb0.map i)).carrier,\n    \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} Y) [\u2200 i, is_affine (\ud835\udcb0.obj i)] (i : \ud835\udcb0.J),\n      compact_space (pullback f (\ud835\udcb0.map i)).carrier,\n    \u2200 {U : Scheme} (g : U \u27f6 Y) [is_affine U] [is_open_immersion g],\n      compact_space (pullback f g).carrier,\n    \u2203 {\u03b9 : Type u} (U : \u03b9 \u2192 opens Y.carrier) (hU : supr U = \u22a4) (hU' : \u2200 i, is_affine_open (U i)),\n      \u2200 i, compact_space (f.1.base \u207b\u00b9' (U i).1)] :=\nquasi_compact_eq_affine_property.symm \u25b8\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 \u25b8\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 \u27f6 Y) :\n  tfae [quasi_compact f,\n    \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} Y), \u2200 (i : \ud835\udcb0.J),\n      quasi_compact (pullback.snd : (\ud835\udcb0.pullback_cover f).obj i \u27f6 \ud835\udcb0.obj i),\n    \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} Y) (i : \ud835\udcb0.J),\n      quasi_compact (pullback.snd : (\ud835\udcb0.pullback_cover f).obj i \u27f6 \ud835\udcb0.obj i),\n    \u2200 (U : opens Y.carrier), quasi_compact (f \u2223_ U),\n    \u2200 {U : Scheme} (g : U \u27f6 Y) [is_open_immersion g],\n      quasi_compact (pullback.snd : pullback f g \u27f6 _),\n    \u2203 {\u03b9 : Type u} (U : \u03b9 \u2192 opens Y.carrier) (hU : supr U = \u22a4), \u2200 i, quasi_compact (f \u2223_ (U i))] :=\nquasi_compact_eq_affine_property.symm \u25b8\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 \u27f6 Y) [is_affine Y] :\n  quasi_compact f \u2194 compact_space X.carrier :=\nquasi_compact_eq_affine_property.symm \u25b8\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 \u2194 quasi_compact (terminal.from X) :=\n(quasi_compact_over_affine_iff _).symm\n\nlemma quasi_compact.affine_open_cover_iff {X Y : Scheme.{u}} (\ud835\udcb0 : Scheme.open_cover.{u} Y)\n  [\u2200 i, is_affine (\ud835\udcb0.obj i)] (f : X \u27f6 Y) :\n  quasi_compact f \u2194 \u2200 i, compact_space (pullback f (\ud835\udcb0.map i)).carrier :=\nquasi_compact_eq_affine_property.symm \u25b8\n  quasi_compact.affine_property_is_local.affine_open_cover_iff f \ud835\udcb0\n\nlemma quasi_compact.open_cover_iff {X Y : Scheme.{u}} (\ud835\udcb0 : Scheme.open_cover.{u} Y) (f : X \u27f6 Y) :\n  quasi_compact f \u2194 \u2200 i, quasi_compact (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _) :=\nquasi_compact_eq_affine_property.symm \u25b8\n  quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_iff f \ud835\udcb0\n\n\n\nlemma quasi_compact_stable_under_composition :\n  morphism_property.stable_under_composition @quasi_compact :=\n\u03bb _ _ _ _ _ _ _, 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 \u22a2,\n  resetI,\n  let \ud835\udcb0 := Scheme.pullback.open_cover_of_right Y.affine_cover.finite_subcover f g,\n  haveI : finite \ud835\udcb0.J,\n  { dsimp [\ud835\udcb0], apply_instance },\n  haveI : \u2200 i, compact_space (\ud835\udcb0.obj i).carrier,\n  { intro i, dsimp, apply_instance },\n  exact \ud835\udcb0.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 \u25b8\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 \u27f6 Z) (g : Y \u27f6 Z) [quasi_compact g] :\n  quasi_compact (pullback.fst : pullback f g \u27f6 X) :=\nquasi_compact_stable_under_base_change.fst f g infer_instance\n\ninstance (f : X \u27f6 Z) (g : Y \u27f6 Z) [quasi_compact f] :\n  quasi_compact (pullback.snd : pullback f g \u27f6 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 \u2192 Prop} (S : opens X.carrier)\n  (hS : is_compact S.1)\n  (h\u2081 : P \u22a5)\n  (h\u2082 : \u2200 (S : opens X.carrier) (hS : is_compact S.1) (U : X.affine_opens), P S \u2192 P (S \u2294 U)) :\n    P S :=\nbegin\n  classical,\n  obtain \u27e8s, hs, hs'\u27e9 := (is_compact_open_iff_eq_finset_affine_union S.1).mp \u27e8hS, S.2\u27e9,\n  replace hs' : S = supr (\u03bb i : s, (i : opens X.carrier)) := by { ext1, simpa using hs' },\n  subst hs',\n  apply hs.induction_on,\n  { convert h\u2081, rw supr_eq_bot, rintro \u27e8_, h\u27e9, exact h.elim },\n  { intros x s h\u2083 hs h\u2084,\n    have : is_compact (\u2a06 i : s, (i : opens X.carrier)).1,\n    { refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1, exact \u27e8s, hs, by simp\u27e9 },\n    convert h\u2082 _ this x h\u2084,\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  \u2203 n : \u2115, f ^ n * x = 0 :=\nbegin\n  rw \u2190 map_zero (X.presheaf.map (hom_of_le $ X.basic_open_le f : X.basic_open f \u27f6 U).op) at H,\n  have := (is_localization_basic_open hU f).3,\n  obtain \u27e8\u27e8_, n, rfl\u27e9, e\u27e9 := this.mp H,\n  exact \u27e8n, by simpa [mul_comm x] using e\u27e9,\nend\n\n/-- If `x : \u0393(X, U)` is zero on `D(f)` for some `f : \u0393(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  \u2203 n : \u2115, f ^ n * x = 0 :=\nbegin\n  obtain \u27e8s, hs, e\u27e9 := (is_compact_open_iff_eq_finset_affine_union U.1).mp \u27e8hU, U.2\u27e9,\n  replace e : U = supr (\u03bb i : s, (i : opens X.carrier)),\n  { ext1, simpa using e },\n  have h\u2081 : \u2200 i : s, i.1.1 \u2264 U,\n  { intro i, change (i : opens X.carrier) \u2264 U, rw e, exact le_supr _ _ },\n  have H' := \u03bb (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\u2081 i)).op x) (X.presheaf.map (hom_of_le (h\u2081 i)).op f) _,\n  swap,\n  { delta Top.presheaf.restrict_open Top.presheaf.restrict at H \u22a2,\n    convert congr_arg (X.presheaf.map (hom_of_le _).op) H,\n    { simp only [\u2190 comp_apply, \u2190 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 : \u2200 (i : s), X.presheaf.map (hom_of_le (h\u2081 i)).op (f ^ (finset.univ.sup n) * x) = 0,\n  { subst e,\n    apply X.sheaf.eq_of_locally_eq (\u03bb (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    (\u03bb x, X.presheaf.map (hom_of_le (h\u2081 i)).op (f ^ (finset.univ.sup n - n i)) * x) (hn i),\n  dsimp at hn,\n  simp only [\u2190 map_mul, \u2190 map_pow] at hn,\n  rwa [mul_zero, \u2190 mul_assoc, \u2190 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": "import Smt\n\ntheorem comm (f : Bool \u2192 Bool \u2192 Bool) (p q : Bool) : f p q == f q p := by\n  smt\n  admit\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/Test/Bool/Comm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.06954174402373312, "lm_q1q2_score": 0.03477087201186656}}
{"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 \u03b1` is the type that describes a computation that can ingest a `char_buffer`\nand output, if successful, a term of type `\u03b1`.\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 \u03b1` 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 \u03b1`, 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 {\u03b1 : Type} : parse_result \u03b1 \u2192 \u2115 := sorry\n\nnamespace parser\n\n\n/--\nA `parser \u03b1` is defined to be `valid` if the result `p cb n` it gives,\nfor some `cb : char_buffer` and `n : \u2115`, (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 {\u03b1 : Type} (p : parser \u03b1) :=\n  \u2200 (cb : char_buffer) (n : \u2115),\n    n \u2264 parse_result.pos (p cb n) \u2227\n      (parse_result.pos (p cb n) \u2264 buffer.size cb \u2192 n \u2264 buffer.size cb)\n\ntheorem fail_iff {\u03b1 : Type} (p : parser \u03b1) (cb : char_buffer) (n : \u2115) :\n    (\u2200 (pos' : \u2115) (result : \u03b1), p cb n \u2260 parse_result.done pos' result) \u2194\n        \u2203 (pos' : \u2115), \u2203 (err : dlist string), p cb n = parse_result.fail pos' err :=\n  sorry\n\ntheorem success_iff {\u03b1 : Type} (p : parser \u03b1) (cb : char_buffer) (n : \u2115) :\n    (\u2200 (pos' : \u2115) (err : dlist string), p cb n \u2260 parse_result.fail pos' err) \u2194\n        \u2203 (pos' : \u2115), \u2203 (result : \u03b1), p cb n = parse_result.done pos' result :=\n  sorry\n\ntheorem decorate_errors_fail {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1}\n    {cb : char_buffer} {n : \u2115} {n' : \u2115} {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 {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1}\n    {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} (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 {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} {cb : char_buffer}\n    {n : \u2115} {n' : \u2115} {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 {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} {cb : char_buffer}\n    {n : \u2115} {n' : \u2115} {a : \u03b1} (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 {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1}\n    {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} :\n    decorate_errors msgs p cb n = parse_result.done n' a \u2194 p cb n = parse_result.done n' a :=\n  sorry\n\n@[simp] theorem decorate_error_eq_done {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1}\n    {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} :\n    decorate_error msg p cb n = parse_result.done n' a \u2194 p cb n = parse_result.done n' a :=\n  decorate_errors_eq_done\n\n@[simp] theorem decorate_errors_eq_fail {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1}\n    {cb : char_buffer} {n : \u2115} {err : dlist string} :\n    decorate_errors msgs p cb n = parse_result.fail n err \u2194\n        (err = dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) \u2227\n          \u2203 (np : \u2115), \u2203 (err' : dlist string), p cb n = parse_result.fail np err' :=\n  sorry\n\n@[simp] theorem decorate_error_eq_fail {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1}\n    {cb : char_buffer} {n : \u2115} {err : dlist string} :\n    decorate_error msg p cb n = parse_result.fail n err \u2194\n        (err = dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) \u2227\n          \u2203 (np : \u2115), \u2203 (err' : dlist string), p cb n = parse_result.fail np err' :=\n  decorate_errors_eq_fail\n\n@[simp] theorem return_eq_pure {\u03b1 : Type} {a : \u03b1} : return a = pure a := rfl\n\ntheorem pure_eq_done {\u03b1 : Type} {a : \u03b1} :\n    pure a = fun (_x : char_buffer) (n : \u2115) => parse_result.done n a :=\n  rfl\n\n@[simp] theorem pure_ne_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string}\n    {a : \u03b1} : pure a cb n \u2260 parse_result.fail n' err :=\n  sorry\n\n@[simp] theorem bind_eq_bind {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} (f : \u03b1 \u2192 parser \u03b2) :\n    parser.bind p f = p >>= f :=\n  rfl\n\n@[simp] theorem bind_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 parser \u03b2} :\n    bind p f cb n = parse_result.done n' b \u2194\n        \u2203 (np : \u2115),\n          \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 f a cb np = parse_result.done n' b :=\n  sorry\n\n@[simp] theorem bind_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {err : dlist string} {f : \u03b1 \u2192 parser \u03b2} :\n    bind p f cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err \u2228\n          \u2203 (np : \u2115),\n            \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 f a cb np = parse_result.fail n' err :=\n  sorry\n\n@[simp] theorem and_then_eq_bind {\u03b1 : Type} {\u03b2 : Type} {m : Type \u2192 Type} [Monad m] (a : m \u03b1)\n    (b : m \u03b2) :\n    a >> b =\n        do \n          a \n          b :=\n  rfl\n\ntheorem and_then_fail {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {err : dlist string} :\n    has_bind.and_then p (return Unit.unit) cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err :=\n  sorry\n\ntheorem and_then_success {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} :\n    has_bind.and_then p (return Unit.unit) cb n = parse_result.done n' Unit.unit \u2194\n        \u2203 (a : \u03b1), p cb n = parse_result.done n' a :=\n  sorry\n\n@[simp] theorem map_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {b : \u03b2} {f : \u03b1 \u2192 \u03b2} :\n    Functor.map f p cb n = parse_result.done n' b \u2194\n        \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 f a = b :=\n  sorry\n\n@[simp] theorem map_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {err : dlist string} {f : \u03b1 \u2192 \u03b2} :\n    Functor.map f p cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err :=\n  sorry\n\n@[simp] theorem map_const_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {b : \u03b2} {b' : \u03b2} :\n    Functor.mapConst b p cb n = parse_result.done n' b' \u2194\n        \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 b = b' :=\n  sorry\n\n@[simp] theorem map_const_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {err : dlist string} {b : \u03b2} :\n    Functor.mapConst b p cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err :=\n  sorry\n\ntheorem map_const_rev_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {b : \u03b2} {b' : \u03b2} :\n    functor.map_const_rev p b cb n = parse_result.done n' b' \u2194\n        \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 b = b' :=\n  map_const_eq_done\n\ntheorem map_rev_const_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {err : dlist string} {b : \u03b2} :\n    functor.map_const_rev p b cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err :=\n  map_const_eq_fail\n\n@[simp] theorem orelse_eq_orelse {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} :\n    parser.orelse p q = (p <|> q) :=\n  rfl\n\n@[simp] theorem orelse_eq_done {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer} {n : \u2115}\n    {n' : \u2115} {a : \u03b1} :\n    has_orelse.orelse p q cb n = parse_result.done n' a \u2194\n        p cb n = parse_result.done n' a \u2228\n          q cb n = parse_result.done n' a \u2227\n            \u2203 (err : dlist string), p cb n = parse_result.fail n err :=\n  sorry\n\n@[simp] theorem orelse_eq_fail_eq {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer}\n    {n : \u2115} {err : dlist string} :\n    has_orelse.orelse p q cb n = parse_result.fail n err \u2194\n        (p cb n = parse_result.fail n err \u2227\n            \u2203 (nq : \u2115), \u2203 (errq : dlist string), n < nq \u2227 q cb n = parse_result.fail nq errq) \u2228\n          \u2203 (errp : dlist string),\n            \u2203 (errq : dlist string),\n              p cb n = parse_result.fail n errp \u2227\n                q cb n = parse_result.fail n errq \u2227 errp ++ errq = err :=\n  sorry\n\ntheorem orelse_eq_fail_invalid_lt {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer}\n    {n : \u2115} {n' : \u2115} {err : dlist string} (hn : n' < n) :\n    has_orelse.orelse p q cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err \u2228\n          q cb n = parse_result.fail n' err \u2227\n            \u2203 (errp : dlist string), p cb n = parse_result.fail n errp :=\n  sorry\n\ntheorem orelse_eq_fail_of_valid_ne {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer}\n    {n : \u2115} {n' : \u2115} {err : dlist string} (hv : valid q) (hn : n \u2260 n') :\n    has_orelse.orelse p q cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err :=\n  sorry\n\n@[simp] theorem failure_eq_failure {\u03b1 : Type} : parser.failure = failure := rfl\n\n@[simp] theorem failure_def {\u03b1 : Type} {cb : char_buffer} {n : \u2115} :\n    failure cb n = parse_result.fail n dlist.empty :=\n  rfl\n\ntheorem not_failure_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} :\n    \u00acfailure cb n = parse_result.done n' a :=\n  sorry\n\ntheorem failure_eq_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} :\n    failure cb n = parse_result.fail n' err \u2194 n = n' \u2227 err = dlist.empty :=\n  sorry\n\ntheorem seq_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : parser (\u03b1 \u2192 \u03b2)} {p : parser \u03b1} :\n    Seq.seq f p cb n = parse_result.done n' b \u2194\n        \u2203 (nf : \u2115),\n          \u2203 (f' : \u03b1 \u2192 \u03b2),\n            \u2203 (a : \u03b1),\n              f cb n = parse_result.done nf f' \u2227 p cb nf = parse_result.done n' a \u2227 f' a = b :=\n  sorry\n\ntheorem seq_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string}\n    {f : parser (\u03b1 \u2192 \u03b2)} {p : parser \u03b1} :\n    Seq.seq f p cb n = parse_result.fail n' err \u2194\n        f cb n = parse_result.fail n' err \u2228\n          \u2203 (nf : \u2115),\n            \u2203 (f' : \u03b1 \u2192 \u03b2), f cb n = parse_result.done nf f' \u2227 p cb nf = parse_result.fail n' err :=\n  sorry\n\ntheorem seq_left_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1}\n    {p : parser \u03b1} {q : parser \u03b2} :\n    SeqLeft.seqLeft p q cb n = parse_result.done n' a \u2194\n        \u2203 (np : \u2115), \u2203 (b : \u03b2), p cb n = parse_result.done np a \u2227 q cb np = parse_result.done n' b :=\n  sorry\n\ntheorem seq_left_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {err : dlist string} {p : parser \u03b1} {q : parser \u03b2} :\n    SeqLeft.seqLeft p q cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err \u2228\n          \u2203 (np : \u2115),\n            \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 q cb np = parse_result.fail n' err :=\n  sorry\n\ntheorem seq_right_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {p : parser \u03b1} {q : parser \u03b2} :\n    SeqRight.seqRight p q cb n = parse_result.done n' b \u2194\n        \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 q cb np = parse_result.done n' b :=\n  sorry\n\ntheorem seq_right_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {err : dlist string} {p : parser \u03b1} {q : parser \u03b2} :\n    SeqRight.seqRight p q cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err \u2228\n          \u2203 (np : \u2115),\n            \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 q cb np = parse_result.fail n' err :=\n  sorry\n\ntheorem mmap_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {f : \u03b1 \u2192 parser \u03b2}\n    {a : \u03b1} {l : List \u03b1} {b : \u03b2} {l' : List \u03b2} :\n    mmap f (a :: l) cb n = parse_result.done n' (b :: l') \u2194\n        \u2203 (np : \u2115), f a cb n = parse_result.done np b \u2227 mmap f l cb np = parse_result.done n' l' :=\n  sorry\n\ntheorem mmap'_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {f : \u03b1 \u2192 parser \u03b2}\n    {a : \u03b1} {l : List \u03b1} :\n    mmap' f (a :: l) cb n = parse_result.done n' Unit.unit \u2194\n        \u2203 (np : \u2115),\n          \u2203 (b : \u03b2),\n            f a cb n = parse_result.done np b \u2227 mmap' f l cb np = parse_result.done n' Unit.unit :=\n  sorry\n\ntheorem guard_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : Prop} [Decidable p] :\n    guard p cb n = parse_result.done n' Unit.unit \u2194 p \u2227 n = n' :=\n  sorry\n\ntheorem guard_eq_fail {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {p : Prop}\n    [Decidable p] : guard p cb n = parse_result.fail n' err \u2194 \u00acp \u2227 n = n' \u2227 err = dlist.empty :=\n  sorry\n\nnamespace valid\n\n\ntheorem mono_done {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1}\n    (hp : valid p) (h : p cb n = parse_result.done n' a) : n \u2264 n' :=\n  sorry\n\ntheorem mono_fail {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string}\n    (hp : valid p) (h : p cb n = parse_result.fail n' err) : n \u2264 n' :=\n  sorry\n\ntheorem pure {\u03b1 : Type} {a : \u03b1} : valid (pure a) := sorry\n\n@[simp] theorem bind {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b1 \u2192 parser \u03b2} (hp : valid p)\n    (hf : \u2200 (a : \u03b1), valid (f a)) : valid (p >>= f) :=\n  sorry\n\ntheorem and_then {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {q : parser \u03b2} (hp : valid p) (hq : valid q) :\n    valid (p >> q) :=\n  bind hp fun (_x : \u03b1) => hq\n\n@[simp] theorem map {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} (hp : valid p) {f : \u03b1 \u2192 \u03b2} :\n    valid (f <$> p) :=\n  bind hp fun (_x : \u03b1) => pure\n\n@[simp] theorem seq {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : parser (\u03b1 \u2192 \u03b2)} (hf : valid f)\n    (hp : valid p) : valid (f <*> p) :=\n  bind hf fun (_x : \u03b1 \u2192 \u03b2) => map hp\n\n@[simp] theorem mmap {\u03b1 : Type} {\u03b2 : Type} {l : List \u03b1} {f : \u03b1 \u2192 parser \u03b2}\n    (h : \u2200 (a : \u03b1), a \u2208 l \u2192 valid (f a)) : valid (mmap f l) :=\n  sorry\n\n@[simp] theorem mmap' {\u03b1 : Type} {\u03b2 : Type} {l : List \u03b1} {f : \u03b1 \u2192 parser \u03b2}\n    (h : \u2200 (a : \u03b1), a \u2208 l \u2192 valid (f a)) : valid (mmap' f l) :=\n  sorry\n\n@[simp] theorem failure {\u03b1 : Type} : valid failure := sorry\n\n@[simp] theorem guard {p : Prop} [Decidable p] : valid (guard p) := sorry\n\n@[simp] theorem orelse {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} (hp : valid p) (hq : valid q) :\n    valid (p <|> q) :=\n  sorry\n\n@[simp] theorem decorate_errors {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1}\n    (hp : valid p) : valid (decorate_errors msgs p) :=\n  sorry\n\n@[simp] theorem decorate_error {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} (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 \u2192 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 \u2208 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 \u2208 string.to_list s) => ch)\n\ntheorem remaining : valid remaining :=\n  fun (_x : char_buffer) (_x_1 : \u2115) =>\n    { left := le_refl _x_1,\n      right := fun (h : parse_result.pos (remaining _x _x_1) \u2264 buffer.size _x) => h }\n\ntheorem eof : valid eof := decorate_error (bind remaining fun (_x : \u2115) => guard)\n\ntheorem foldr_core_zero {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} :\n    valid (foldr_core f p b 0) :=\n  failure\n\ntheorem foldr_core {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} (hp : valid p)\n    {reps : \u2115} : valid (foldr_core f p b reps) :=\n  sorry\n\ntheorem foldr {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} (hp : valid p) :\n    valid (foldr f p b) :=\n  fun (_x : char_buffer) (_x_1 : \u2115) => foldr_core hp _x _x_1\n\ntheorem foldl_core_zero {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {b : \u03b2} :\n    valid (foldl_core f b p 0) :=\n  failure\n\ntheorem foldl_core {\u03b1 : Type} {\u03b2 : Type} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} (hp : valid p) {a : \u03b1}\n    {reps : \u2115} : valid (foldl_core f a p reps) :=\n  sorry\n\ntheorem foldl {\u03b1 : Type} {\u03b2 : Type} {a : \u03b1} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} (hp : valid p) :\n    valid (foldl f a p) :=\n  fun (_x : char_buffer) (_x_1 : \u2115) => foldl_core hp _x _x_1\n\ntheorem many {\u03b1 : Type} {p : parser \u03b1} (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' {\u03b1 : Type} {p : parser \u03b1} (hp : valid p) : valid (many' p) := and_then (many hp) eps\n\ntheorem many1 {\u03b1 : Type} {p : parser \u03b1} (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 {\u03b1 : Type} {p : parser \u03b1} {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 {\u03b1 : Type} {p : parser \u03b1} {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 {\u03b1 : Type} {F : parser \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), valid p \u2192 valid (F p))\n    (max_depth : \u2115) : 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 \u2115) => pure)\n\ntheorem fix {\u03b1 : Type} {F : parser \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), valid p \u2192 valid (F p)) :\n    valid (fix F) :=\n  fun (_x : char_buffer) (_x_1 : \u2115) => fix_core hF (buffer.size _x - _x_1 + 1) _x _x_1\n\nend valid\n\n\n@[simp] theorem orelse_pure_eq_fail {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {err : dlist string} {a : \u03b1} :\n    has_orelse.orelse p (pure a) cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err \u2227 n \u2260 n' :=\n  sorry\n\ntheorem any_char_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char} :\n    any_char cb n = parse_result.done n' c \u2194\n        n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c :=\n  sorry\n\ntheorem sat_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char}\n    {p : char \u2192 Prop} [decidable_pred p] :\n    sat p cb n = parse_result.done n' c \u2194\n        p c \u2227 n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c :=\n  sorry\n\ntheorem eps_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} :\n    eps cb n = parse_result.done n' Unit.unit \u2194 n = n' :=\n  sorry\n\ntheorem ch_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char} :\n    ch c cb n = parse_result.done n' Unit.unit \u2194\n        n' = n + 1 \u2227 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 : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char}\n    {cs : List char} :\n    one_of cs cb n = parse_result.done n' c \u2194\n        c \u2208 cs \u2227 n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c :=\n  sorry\n\ntheorem one_of'_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb)\n    {cs : List char} :\n    one_of' cs cb n = parse_result.done n' Unit.unit \u2194\n        buffer.read cb { val := n, property := hn } \u2208 cs \u2227 n' = n + 1 :=\n  sorry\n\ntheorem remaining_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} {r : \u2115} :\n    remaining cb n = parse_result.done n' r \u2194 n = n' \u2227 buffer.size cb - n = r :=\n  sorry\n\ntheorem eof_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} :\n    eof cb n = parse_result.done n' Unit.unit \u2194 n = n' \u2227 buffer.size cb \u2264 n :=\n  sorry\n\n@[simp] theorem foldr_core_zero_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n    foldr_core f p b 0 cb n \u2260 parse_result.done n' b' :=\n  sorry\n\ntheorem foldr_core_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {b' : \u03b2} :\n    foldr_core f p b (reps + 1) cb n = parse_result.done n' b' \u2194\n        (\u2203 (np : \u2115),\n            \u2203 (a : \u03b1),\n              \u2203 (xs : \u03b2),\n                p cb n = parse_result.done np a \u2227\n                  foldr_core f p b reps cb np = parse_result.done n' xs \u2227 f a xs = b') \u2228\n          n = n' \u2227\n            b = b' \u2227\n              \u2203 (err : dlist string),\n                p cb n = parse_result.fail n err \u2228\n                  \u2203 (np : \u2115),\n                    \u2203 (a : \u03b1),\n                      p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n    foldr_core f p b 0 cb n = parse_result.fail n' err \u2194 n = n' \u2227 err = dlist.empty :=\n  sorry\n\ntheorem foldr_core_succ_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {err : dlist string} :\n    foldr_core f p b (reps + 1) cb n = parse_result.fail n' err \u2194\n        n \u2260 n' \u2227\n          (p cb n = parse_result.fail n' err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1),\n                p cb n = parse_result.done np a \u2227\n                  foldr_core f p b reps cb np = parse_result.fail n' err) :=\n  sorry\n\ntheorem foldr_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n    foldr f p b cb n = parse_result.done n' b' \u2194\n        (\u2203 (np : \u2115),\n            \u2203 (a : \u03b1),\n              \u2203 (x : \u03b2),\n                p cb n = parse_result.done np a \u2227\n                  foldr_core f p b (buffer.size cb - n) cb np = parse_result.done n' x \u2227\n                    f a x = b') \u2228\n          n = n' \u2227\n            b = b' \u2227\n              \u2203 (err : dlist string),\n                p cb n = parse_result.fail n err \u2228\n                  \u2203 (np : \u2115),\n                    \u2203 (x : \u03b1),\n                      p cb n = parse_result.done np x \u2227\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 {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} (hp : valid p)\n    (hc : buffer.size cb \u2264 n) :\n    foldr f p b cb n = parse_result.fail n' err \u2194\n        n < n' \u2227\n          (p cb n = parse_result.fail n' err \u2228\n            \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 err = dlist.empty) :=\n  sorry\n\ntheorem foldr_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n    foldr f p b cb n = parse_result.fail n' err \u2194\n        n \u2260 n' \u2227\n          (p cb n = parse_result.fail n' err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1),\n                p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n    foldl_core f b p 0 cb n = parse_result.done n' b' \u2194 False :=\n  sorry\n\ntheorem foldl_core_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {b' : \u03b2} :\n    foldl_core f b p (reps + 1) cb n = parse_result.done n' b' \u2194\n        (\u2203 (np : \u2115),\n            \u2203 (a : \u03b1),\n              p cb n = parse_result.done np a \u2227\n                foldl_core f (f b a) p reps cb np = parse_result.done n' b') \u2228\n          n = n' \u2227\n            b = b' \u2227\n              \u2203 (err : dlist string),\n                p cb n = parse_result.fail n err \u2228\n                  \u2203 (np : \u2115),\n                    \u2203 (a : \u03b1),\n                      p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n    foldl_core f b p 0 cb n = parse_result.fail n' err \u2194 n = n' \u2227 err = dlist.empty :=\n  sorry\n\ntheorem foldl_core_succ_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {err : dlist string} :\n    foldl_core f b p (reps + 1) cb n = parse_result.fail n' err \u2194\n        n \u2260 n' \u2227\n          (p cb n = parse_result.fail n' err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1),\n                p cb n = parse_result.done np a \u2227\n                  foldl_core f (f b a) p reps cb np = parse_result.fail n' err) :=\n  sorry\n\ntheorem foldl_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} :\n    foldl f b p cb n = parse_result.done n' b' \u2194\n        (\u2203 (np : \u2115),\n            \u2203 (a : \u03b1),\n              p cb n = parse_result.done np a \u2227\n                foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.done n' b') \u2228\n          n = n' \u2227\n            b = b' \u2227\n              \u2203 (err : dlist string),\n                p cb n = parse_result.fail n err \u2228\n                  \u2203 (np : \u2115),\n                    \u2203 (a : \u03b1),\n                      p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2}\n    {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} :\n    foldl f b p cb n = parse_result.fail n' err \u2194\n        n \u2260 n' \u2227\n          (p cb n = parse_result.fail n' err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1),\n                p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} :\n    many p cb n = parse_result.done n' [] \u2194\n        n = n' \u2227\n          \u2203 (err : dlist string),\n            p cb n = parse_result.fail n err \u2228\n              \u2203 (np : \u2115),\n                \u2203 (a : \u03b1),\n                  p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} {x : \u03b1}\n    {xs : List \u03b1} :\n    many p cb n = parse_result.done n' (x :: xs) \u2194\n        \u2203 (np : \u2115),\n          p cb n = parse_result.done np x \u2227\n            foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' xs :=\n  sorry\n\ntheorem many_eq_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1}\n    {err : dlist string} :\n    many p cb n = parse_result.fail n' err \u2194\n        n \u2260 n' \u2227\n          (p cb n = parse_result.fail n' err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1),\n                p cb n = parse_result.done np a \u2227\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 : \u2115} {n' : \u2115} {p : parser char} :\n    many_char p cb n = parse_result.done n' string.empty \u2194\n        n = n' \u2227\n          \u2203 (err : dlist string),\n            p cb n = parse_result.fail n err \u2228\n              \u2203 (np : \u2115),\n                \u2203 (c : char),\n                  p cb n = parse_result.done np c \u2227\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 : \u2115} {n' : \u2115} {p : parser char}\n    {s : string} (h : s \u2260 string.empty) :\n    many_char p cb n = parse_result.done n' s \u2194\n        \u2203 (np : \u2115),\n          p cb n = parse_result.done np (string.head s) \u2227\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 : \u2115} {n' : \u2115} {p : parser char}\n    {s : string} :\n    many_char p cb n = parse_result.done n' s \u2194\n        many p cb n = parse_result.done n' (string.to_list s) :=\n  sorry\n\ntheorem many'_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} :\n    many' p cb n = parse_result.done n' Unit.unit \u2194\n        many p cb n = parse_result.done n' [] \u2228\n          \u2203 (np : \u2115),\n            \u2203 (a : \u03b1),\n              \u2203 (l : List \u03b1),\n                many p cb n = parse_result.done n' (a :: l) \u2227\n                  p cb n = parse_result.done np a \u2227\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 {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} :\n    many1 p cb n \u2260 parse_result.done n' [] :=\n  sorry\n\ntheorem many1_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {p : parser \u03b1}\n    {l : List \u03b1} :\n    many1 p cb n = parse_result.done n' (a :: l) \u2194\n        \u2203 (np : \u2115), p cb n = parse_result.done np a \u2227 many p cb np = parse_result.done n' l :=\n  sorry\n\ntheorem many1_eq_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1}\n    {err : dlist string} :\n    many1 p cb n = parse_result.fail n' err \u2194\n        p cb n = parse_result.fail n' err \u2228\n          \u2203 (np : \u2115),\n            \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 many p cb np = parse_result.fail n' err :=\n  sorry\n\n@[simp] theorem many_char1_ne_empty {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} :\n    many_char1 p cb n \u2260 parse_result.done n' string.empty :=\n  sorry\n\ntheorem many_char1_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} {s : string}\n    (h : s \u2260 string.empty) :\n    many_char1 p cb n = parse_result.done n' s \u2194\n        \u2203 (np : \u2115),\n          p cb n = parse_result.done np (string.head s) \u2227\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 {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115}\n    {sep : parser Unit} {p : parser \u03b1} : sep_by1 sep p cb n \u2260 parse_result.done n' [] :=\n  sorry\n\ntheorem sep_by1_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {sep : parser Unit}\n    {p : parser \u03b1} {l : List \u03b1} :\n    sep_by1 sep p cb n = parse_result.done n' (a :: l) \u2194\n        \u2203 (np : \u2115),\n          p cb n = parse_result.done np a \u2227 many (sep >> p) cb np = parse_result.done n' l :=\n  sorry\n\ntheorem sep_by_eq_done_nil {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {sep : parser Unit}\n    {p : parser \u03b1} :\n    sep_by sep p cb n = parse_result.done n' [] \u2194\n        n = n' \u2227 \u2203 (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 {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1}\n    {F : parser \u03b1 \u2192 parser \u03b1} : fix_core F 0 cb n \u2260 parse_result.done n' a :=\n  sorry\n\ntheorem fix_core_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1}\n    {F : parser \u03b1 \u2192 parser \u03b1} {max_depth : \u2115} :\n    fix_core F (max_depth + 1) cb n = parse_result.done n' a \u2194\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 : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {k : \u2115} :\n    digit cb n = parse_result.done n' k \u2194\n        n' = n + 1 \u2227\n          k \u2264 bit1 (bit0 (bit0 1)) \u2227\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 \u2227\n              char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 1))))) \u2264\n                  buffer.read cb { val := n, property := hn } \u2227\n                buffer.read cb { val := n, property := hn } \u2264\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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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\u03bb 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 := \u27e8\u03bb ns,\n                ns.mfoldl\n                  (\u03bb 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 \u2190 aux_attr.get_param_untyped n',\n                    pure $ dict.insert n param.app_arg.const_name)\n                  mk_name_map, []\u27e9 }\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 `\u2115` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nmeta def ignore_args_attr : user_attribute (name_map $ list \u2115) (list \u2115) :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\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 `\u2115 \u00d7 \u03b1`\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 \u2115) \u2115 :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\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 \u2115) (list \u2115) :=\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    \u27e8\u03bb ns, ns.mfoldl\n      (\u03bb dict n, do\n        param \u2190 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, []\u27e9,\n  parser    := do\n    l \u2190 (lean.parser.small_nat)*,\n    guard (l.all (\u2260 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 \u2115 := do\n  d \u2190 get_decl nm,\n  let (es, _) := d.type.pi_binders,\n  l \u2190 es.mmap_with_index $ \u03bb n bi, do\n  { let tgt := bi.type.pi_codomain,\n    let n_bi := bi.type.pi_binders.fst.length,\n    tt \u2190 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 $ \u03bb 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 \u2192 string \u2192 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 \u2192 list string \u2192 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 \u2192 string :=\nstring.map_tokens ''' $\n\u03bb 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 \u2260 name.anonymous \u2228 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 \u2260 tgt_auto \u2228 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(\u03bb res,\n  if res = src \u2227 tgt \u2260 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 \u2190 option.is_some <$> (tk \"!\")?,\n  ques \u2190 option.is_some <$> (tk \"?\")?,\n  tgt \u2190 ident?,\n  e \u2190 texpr?,\n  doc \u2190 match e with\n      | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n      | none := pure none\n      end,\n  return \u27e8bang, ques, tgt.get_or_else name.anonymous, doc, ff\u27e9\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : \u2115) (f : name \u2192 tactic (list string)) :\n  command :=\ndo\n  src_fields \u2190 f src,\n  tgt_fields \u2190 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    \u03bb 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 : \u2115) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (\u03bb n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (\u03bb n, (list.map (\u03bb (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (\u03bb n, (env.constructors_of n).mmap $\n          \u03bb 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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 \u00d7 N) := \u27e8\u03bb p q, \u27e8p.1 * q.1, p.2 * q.2\u27e9\u27e9\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 \u2115 n m` (i.e. `(n * m : \u2115)`) will not change to `+`, since its\n  first argument is `\u2115`, an identifier not applied to any arguments.\n* `@has_mul.mul (\u03b1 \u00d7 \u03b2) x y` will change to `+`. It's first argument contains only the identifier\n  `prod`, but this is applied to arguments, `\u03b1` and `\u03b2`.\n* `@has_mul.mul (\u03b1 \u00d7 \u2124) x y` will not change to `+`, since its first argument contains `\u2124`.\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 `\u21a5Semigroup` is replaced by addition in `\u21a5AddSemigroup`.\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 \u2115)` can contain `\u2115`\n  (usually in the form `has_top.top \u2115 ...`) and still be additivized.\n  So `@has_mul.mul (C^\u221e\u27eeI, N; I', G\u27ef) _ 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 `\u2115` or `\u211d`. 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 `\u2115` or `\u211d`. Solutions:\n  * If the fixed type has an additive counterpart (like `\u21a5Semigroup`), 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 \u201cmain\u201d 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 \u201cmain\u201d 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 (\u201cmul\u201d, \u201cone\u201d, \u201cinv\u201d, \u201cprod\u201d) 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 $ \u03bb src prio persistent, do\n    guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n    env \u2190 get_env,\n    val \u2190 attr.get_param src,\n    dict \u2190 aux_attr.get_cache,\n    ignore \u2190 ignore_args_attr.get_cache,\n    relevant \u2190 relevant_arg_attr.get_cache,\n    reorder \u2190 reorder_attr.get_cache,\n    tgt \u2190 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 \u2190 first_multiplicative_arg src,\n    when (first_mult_arg \u2260 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 := (\u03bb d, do\n    let mul_name := d.to_name,\n    dict \u2190 to_additive.aux_attr.get_cache,\n    match dict.find mul_name with\n    | some add_name := do\n      mul_doc \u2190 try_core $ doc_string mul_name,\n      add_doc \u2190 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) 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 Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.lint.default\nimport Mathlib.tactic.dependencies\nimport Mathlib.PostPort\n\nuniverses u \n\nnamespace Mathlib\n\nnamespace tactic\n\n\nnamespace interactive\n\n\n/-- Similar to `constructor`, but does not reorder goals. -/\n/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.\nNever fails. Useful for debugging. -/\n/-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/\n/-- Unfold coercion-related definitions -/\n/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/\n/-- Unfold auxiliary definitions associated with the current declaration. -/\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\". -/\n/-- Like `try { tac }`, but in the case of failure it continues\nfrom the failure state instead of reverting to the original state. -/\n/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without\nrequiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a\nnon-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/\n/--\n`work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero),\nand does not require that the goal be solved at the end\n(any remaining subgoals are inserted back into the list of goals).\n\nTypically usage might look like:\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 2 {\n  dsimp,\n  simp\n},\nrefl\n````\n\nSee also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`.\n-/\n/--\n`swap n` will move the `n`th goal to the front.\n`swap` defaults to `swap 2`, and so interchanges the first and second goals.\n-/\n/-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. -/\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\n/--\nActs like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\n/-- Make every proposition in the context decidable. -/\ntheorem generalize_a_aux {\u03b1 : Sort u} (h : (x : Sort u) \u2192 (\u03b1 \u2192 x) \u2192 x) : \u03b1 := h \u03b1 id\n\n/--\nLike `generalize` but also considers assumptions\nspecified by the user. The user can also specify to\nomit the goal.\n-/\n/-- go from (x\u2080 : t\u2080) (x\u2081 : t\u2080) (x\u2082 : t\u2080) to (x\u2080 x\u2081 x\u2082 : t\u2080) -/\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.\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\n```lean\nrefine_struct ( { .. } : semigroup \u03b1 ),\n-- case semigroup, mul\n\n-- case semigroup, mul\n-- \u03b1 : Type u,\n\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\n\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\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-/\n/--\n`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).\nWe use this tactic for writing tests.\n-/\n/--\n`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast\nto `guard_expr`, this tests strict (syntactic) equality.\nWe use this tactic for writing tests.\n-/\n/--\n`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.\nWe use this tactic for writing tests.\n-/\n/--\n`guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal\nto `t`.\nWe use this tactic for writing tests.\n-/\n/-- Tests that there are `n` hypotheses in the current context. -/\n/-- Test that `t` is the tag of the main goal. -/\n/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term\n  unifies with `p`. -/\n/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with\nerror message `msg` (for test writing purposes). -/\n/-- Get the field of the current goal. -/\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\n/-- `apply_field` functions as `have_field, apply field, clear field` -/\n/--\n`apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is optional, equal to 50 by default.\nYou can pass an `apply_cfg` option argument as `apply_rules hs n opt`.\n(A typical usage would be with `apply_rules hs n { md := reducible })`,\nwhich asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)\nwhen checking if a lemma matches the goal.)\n\n`hs` can contain user attributes: in this case all theorems with this\nattribute are added to the list of rules.\n\nFor instance:\n\n```lean\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 b + d * e + b + d + e :=\n-- any of the following lines solve the goal:\n\n-- any of the following lines solve the goal:\nadd_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\nby apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\nby apply_rules [mono_rules]\nby apply_rules mono_rules\n```\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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`;\n- `h_generalize Hx : e == x with _` chooses automatically chooses the name of\n  assumption `\u03b1 = \u03b2`;\n- `h_generalize! Hx : e == x` reverts `Hx`;\n- when `Hx` is omitted, assumption `Hx : e == x` is not added.\n-/\n/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that\n  this uses definitional equality instead of alpha-equivalence. -/\n/--\n`guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.\nWe use this tactic for writing tests.\nThe difference with `guard_target` is that this uses definitional equality instead of\nalpha-equivalence.\n-/\n/--\na weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true,\nunfolding only `reducible` constants. -/\n/--\nSimilar to `existsi`. `use x` will instantiate the first term of an `\u2203` or `\u03a3` goal with `x`.\nIt will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`.\nUnlike `existsi`, `x` is elaborated with respect to the expected type.\n`use` will alternatively take a list of terms `[x0, ..., xn]`.\n\n`use` will work with constructors of arbitrary inductive types.\n\nExamples:\n```lean\nexample (\u03b1 : Type) : \u2203 S : set \u03b1, S = S :=\nby use \u2205\n\nexample : \u2203 x : \u2124, x = x :=\nby use 42\n\nexample : \u2203 n > 0, n = n :=\nbegin\n  use 1,\n  -- goal is now 1 > 0 \u2227 1 = 1, whereas it would be \u2203 (H : 1 > 0), 1 = 1 after existsi 1.\n  exact \u27e8zero_lt_one, rfl\u27e9,\nend\n\nexample : \u2203 a b c : \u2124, a + b + c = 6 :=\nby use [1, 2, 3]\n\nexample : \u2203 p : \u2124 \u00d7 \u2124, p.1 = 1 :=\nby use \u27e81, 42\u27e9\n\nexample : \u03a3 x y : \u2124, (\u2124 \u00d7 \u2124) \u00d7 \u2124 :=\nby use [1, 2, 3, 4, 5]\n\ninductive foo\n| mk : \u2115 \u2192 bool \u00d7 \u2115 \u2192 \u2115 \u2192 foo\n\nexample : foo :=\nby use [100, tt, 4, 3]\n```\n-/\n/--\n`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.\nThis includes the induction hypothesis when using the equation compiler and\n`_let_match` and `_fun_match`.\n\nIt is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these\nauxiliary declarations, and produce an error saying the recursion is not well founded.\n\n```lean\nexample (n m : \u2115) (h\u2081 : n = m) (h\u2082 : \u2203 a : \u2115, a = n \u2227 a = m) : 2 * m = 2 * n :=\nlet \u27e8a, ha\u27e9 := h\u2082 in\nbegin\n  clear_aux_decl, -- subst will fail without this line\n  subst h\u2081\nend\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl, -- finish produces an error without this line\n  finish\nend\n```\n-/\n/--\nThe logic of `change x with y at l` fails when there are dependencies.\n`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.\nIn this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses\nin `l`. As long as `x` and `y` are defeq, it should never fail.\n-/\n/--\n`set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to\nthe local context and replaces `t` with `a` everywhere it can.\n\n`set a := t with \u2190h` will add `h : t = a` instead.\n\n`set! a := t with h` does not do any replacing.\n\n```lean\nexample (x : \u2115) (h : x = 3)  : x + x + x = 9 :=\nbegin\n  set y := x with \u2190h_xy,\n/-\nx : \u2115,\ny : \u2115 := x,\nh_xy : x = y,\nh : y = 3\n\u22a2 y + y + y = 9\n-/\n/--\n`clear_except h\u2080 h\u2081` deletes all the assumptions it can except for `h\u2080` and `h\u2081`.\n-/\n/--\nFormat the current goal as a stand-alone example. Useful for testing tactics\nor creating [minimal working examples](https://leanprover-community.github.io/mwe.html).\n\n* `extract_goal`: formats the statement as an `example` declaration\n* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration\n  called `my_decl`\n* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration\n\nExamples:\n\n```lean\nexample (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\nbegin\n  extract_goal,\n     -- prints:\n     -- example (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\n  extract_goal my_lemma\n     -- prints:\n     -- lemma my_lemma (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\nend\n\nexample {i j k x y z w p q r m n : \u2115} (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) (h\u2081 : k \u2264 p) (h\u2081 : p \u2264 q) : i \u2264 k :=\nbegin\n  extract_goal my_lemma,\n    -- prints:\n    -- lemma my_lemma {i j k x y z w p q r m n : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p)\n    --   (h\u2081 : p \u2264 q) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\n\n  extract_goal my_lemma with i j k\n    -- prints:\n    -- lemma my_lemma {p i j k : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\nend\n\nexample : true :=\nbegin\n  let n := 0,\n  have m : \u2115, admit,\n  have k : fin n, admit,\n  have : n + m + k.1 = 0, extract_goal,\n    -- prints:\n    -- example (m : \u2115)  : let n : \u2115 := 0 in \u2200 (k : fin n), n + m + k.val = 0 :=\n    -- begin\n    --   intros n k,\n    --   admit,\n    -- end\nend\n```\n\n-/\n/--\n`inhabit \u03b1` tries to derive a `nonempty \u03b1` instance and then upgrades this\nto an `inhabited \u03b1` instance.\nIf the target is a `Prop`, this is done constructively;\notherwise, it uses `classical.choice`.\n\n```lean\nexample (\u03b1) [nonempty \u03b1] : \u2203 a : \u03b1, true :=\nbegin\n  inhabit \u03b1,\n  existsi default \u03b1,\n  trivial\nend\n```\n-/\n/-- `revert_deps n\u2081 n\u2082 ...` reverts all the hypotheses that depend on one of `n\u2081, n\u2082, ...`\nIt does not revert `n\u2081, n\u2082, ...` themselves (unless they depend on another `n\u1d62`). -/\n/-- `revert_after n` reverts all the hypotheses after `n`. -/\n/-- Reverts all local constants on which the target depends (recursively). -/\n/-- `clear_value n\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`. -/\n/--\n`generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of\nthe same type.\n\n`generalize' h : e = x` in addition registers the hypothesis `h : e = x`.\n\n`generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also\nsucceeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis\n`x` is not a local definition.\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/interactive_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.07585818211049714, "lm_q1q2_score": 0.034677560314494864}}
{"text": "import UserWidget.ContextualSuggestion\nimport UserWidget.SuggestionProviders\n\n/-!\n\n# Demo for contextual suggestions\n\n-/\n\nexample (x y : Nat) : x = x \u2192 y = y \u2192 x = y \u2192 y = x := by\n  -- put your cursor here!\n  -- and click on the arrow in the tactic state\n  sorry\n\n", "meta": {"author": "Vtec234", "repo": "npm-widget", "sha": "b7ba6a7cdc3e66e0614a16225e3bd1aee009e371", "save_path": "github-repos/lean/Vtec234-npm-widget", "path": "github-repos/lean/Vtec234-npm-widget/npm-widget-b7ba6a7cdc3e66e0614a16225e3bd1aee009e371/UserWidget/Demos/Magic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.08035746441741523, "lm_q1q2_score": 0.03456555025823237}}
{"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 `\u2194` 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 `\u2194`. -/\nunsafe def congr_core' : tactic Unit := do\n  let tgt \u2190 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 \u2190 target let h \u2190 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 \u2190 target\n  let @expr.const tt n [level.zero] \u2190 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 `\u22a2 f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `\u22a2 x = y`\n  and `\u22a2 y = x`, while `congr' 2` produces the intended `\u22a2 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 \u2115 \u2192 tactic Unit\n  | o =>\n    focus1 <|\n      assumption <|>\n        reflexivity Transparency.none <|>\n          by_proof_irrel <|>\n            (guard (o \u2260 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 `\u22a2 f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `\u22a2 x = y`\n  and `\u22a2 y = x`, while `congr' 2` produces the intended `\u22a2 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 `\u22a2 f '' s = g '' s` then `congr' with x` generates the goal\n  `x : \u03b1 \u22a2 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))) \u2192\n      tactic Unit\n  | none => tactic.congr' n\n  | some \u27e8p, m\u27e9 => 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\u22a2 (\u03bb x, f x + 3) '' s = (\u03bb x, g x + 3) '' s\n```\nthen `rcongr x` produces the goal\n```lean\nx : \u03b1 \u22a2 f x = g x\n```\nThis gives the same result as `congr', ext x, congr'`.\n\nIn contrast, `congr'` would produce\n```lean\n\u22a2 (\u03bb x, f x + 3) = (\u03bb x, g x + 3)\n```\nand `congr' with x` (or `congr', ext x`) would produce\n```lean\nx : \u03b1 \u22a2 f x + 3 = g x + 3\n```\n-/\nunsafe def rcongr : parse (List.join <$> parser.many rintro_patt_parse_hi) \u2192 tactic Unit\n  | ps => do\n    let t \u2190 target\n    let qs \u2190 try_core (tactic.ext ps none)\n    let some () \u2190\n      try_core\n          (tactic.congr' none >>\n            (done <|> do\n              let s \u2190 target\n              guard <| \u00acs == 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 : \u2115,\n      e : prime (2 * n + 1)\n      \u22a2 prime (n + n + 1)\n      ```\n      \n      the tactic `convert e` will change the goal to\n      \n      ```lean\n      \u22a2 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 : \u2115) := 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 \u2190 e` will reverse the direction of the new goals\n      (producing `\u22a2 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 `\u22a2 n + n + 1 = 2 * n + 1`.\n      -/\n    unsafe\n  def\n    convert\n    ( sym : parse ( with_desc \"\u2190\" ( 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 \u2190 target\n          let u \u2190 infer_type tgt\n          let r \u2190 i_to_expr ` `( ( $ ( r ) : ( _ : $ ( u ) ) ) )\n          let src \u2190 infer_type r\n          let src \u2190 simp_lemmas.mk . dsimplify [ ] src { failIfUnchanged := false }\n          let\n            v\n              \u2190\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 \u2190 get_goals\n          set_goals [ v ]\n          try ( tactic.congr' n )\n          let gs' \u2190 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 : \u2115) : (a + b) + (c + d) + (e + f) + g \u2264 N :=\nbegin\n  ac_change a + d + e + f + c + g + b \u2264 _,\n-- \u22a2 a + d + e + f + c + g + b \u2264 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) 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.control.traversable.basic\nimport Mathlib.tactic.simpa\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-- pretty print a `loc` -/\n/-- shift `pos` `n` columns to the left -/\nnamespace tactic\n\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\n/-- pretty print structure instance -/\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeeze_loc_attr_carrier : Unit := Unit.unit\n\n/-- Format a list of arguments for use with `simp` and friends. This omits the\nlist entirely if it is empty. -/\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. -/\n/-- translate a `pexpr` into a `simp` configuration -/\n/-- translate a `pexpr` into a `dsimp` configuration -/\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\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-/\n/-- make a `simp_arg_type` that references the name given as an argument -/\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 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\n-/\nnamespace interactive\n\n\n/-- Turn a `simp_arg_type` into a string. -/\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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (xs.tail.map f).length = xs.length :=\nbegin\n  have : xs = ys, admit,\n  squeeze_scope\n  { split; squeeze_simp, -- `squeeze_simp` is run twice, the first one requires\n                         -- `list.map_append` and the second one `[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]  -- `squeeze_simp` is run only once\n                         -- prints:\n                         -- > Try this: simp only [this]\n },\nend\n```\n\n-/\n/--\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\n-- prints:\n-- Try this: simp only [add_zero, eq_self_iff_true, zero_add]\n\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 `squeeze_simp?`\n\n-/\n/-- see `squeeze_simp` -/\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 -/\nend interactive\n\n\nend tactic\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/squeeze_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.0705595927669805, "lm_q1q2_score": 0.034453077526952654}}
{"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, Robert Y. Lewis\n-/\nimport data.bool.basic\nimport meta.rb_map\nimport tactic.lint.basic\n\n/-!\n# Various linters\n\nThis file defines several small linters:\n  - `ge_or_gt` checks that `>` and `\u2265` do not occur in the statement of theorems.\n  - `dup_namespace` checks that no declaration has a duplicated namespace such as `list.list.monad`.\n  - `unused_arguments` checks that definitions and theorems do not have unused arguments.\n  - `doc_blame` checks that every definition has a documentation string.\n  - `doc_blame_thm` checks that every theorem has a documentation string (not enabled by default).\n  - `def_lemma` checks that a declaration is a lemma iff its type is a proposition.\n  - `check_type` checks that the statement of a declaration is well-typed.\n  - `check_univs` checks that there are no bad `max u v` universe levels.\n  - `syn_taut` checks that declarations are not syntactic tautologies.\n  - `unused_haves_suffices` checks that declarations produced via term mode do not have\n    ineffectual `have` or `suffices` statements\n-/\n\nopen tactic expr\n\n/-!\n## Linter against use of `>`/`\u2265`\n-/\n/-- The names of `\u2265` and `>`, mostly disallowed in lemma statements -/\nprivate meta def illegal_ge_gt : list name := [`gt, `ge]\n\nset_option eqn_compiler.max_steps 20000\n/--\n  Checks whether `\u2265` and `>` occurs in an illegal way in the expression.\n  The main ways we legally use these orderings are:\n  - `f (\u2265)`\n  - `\u2203 x \u2265 t, b`. This corresponds to the expression\n    `@Exists \u03b1 (fun (x : \u03b1), (@Exists (x > t) (\u03bb (H : x > t), b)))`\n  This function returns `tt` when it finds `ge`/`gt`, except in the following patterns\n  (which are the same for `gt`):\n  - `f (@ge _ _)`\n  - `f (&0 \u2265 y) (\u03bb x : t, b)`\n  - `\u03bb H : &0 \u2265 t, b`\n  Here `&0` is the 0-th de Bruijn variable.\n-/\nprivate meta def contains_illegal_ge_gt : expr \u2192 bool\n| (const nm us) := if nm \u2208 illegal_ge_gt then tt else ff\n| (app f e@(app (app (const nm us) tp) tc)) :=\n  contains_illegal_ge_gt f || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt e\n| (app (app custom_binder (app (app (app (app (const nm us) tp) tc) (var 0)) t))\n    e@(lam var_name bi var_type body)) :=\n  contains_illegal_ge_gt e || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt e\n| (app f x) := contains_illegal_ge_gt f || contains_illegal_ge_gt x\n| (lam `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) :=\n  contains_illegal_ge_gt body || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt type\n| (lam var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body\n| (pi `H bi type@(app (app (app (app (const nm us) tp) tc) (var 0)) t) body) :=\n  contains_illegal_ge_gt body || if nm \u2208 illegal_ge_gt then ff else contains_illegal_ge_gt type\n| (pi var_name bi var_type body) := contains_illegal_ge_gt var_type || contains_illegal_ge_gt body\n| (elet var_name type assignment body) :=\n  contains_illegal_ge_gt type || contains_illegal_ge_gt assignment || contains_illegal_ge_gt body\n| _ := ff\n\n/-- Checks whether a `>`/`\u2265` is used in the statement of `d`.\n\nIt first does a quick check to see if there is any `\u2265` or `>` in the statement, and then does a\nslower check whether the occurrences of `\u2265` and `>` are allowed.\nCurrently it checks only the conclusion of the declaration, to eliminate false positive from\nbinders such as `\u2200 \u03b5 > 0, ...` -/\nprivate meta def ge_or_gt_in_statement (d : declaration) : tactic (option string) :=\nreturn $ if d.type.contains_constant (\u03bb n, n \u2208 illegal_ge_gt) &&\n  contains_illegal_ge_gt d.type\n  then some \"the type contains \u2265/>. Use \u2264/< instead.\"\n  else none\n\n-- TODO: the commented out code also checks for classicality in statements, but needs fixing\n-- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _\n-- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=\n-- return $ if d.type.contains_constant (\u03bb n, (n.get_prefix = `classical \u2227\n--   n.last \u2208 [\"prop_decidable\", \"dec\", \"dec_rel\", \"dec_eq\"]) \u2228 n \u2208 [`gt, `ge])\n-- then\n--   let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel,\n--     `classical.dec_eq],\n--       illegal2 := [`gt, `ge],\n--       occur1 := illegal1.filter (\u03bb n, d.type.contains_constant (eq n)),\n--       occur2 := illegal2.filter (\u03bb n, d.type.contains_constant (eq n)) in\n--   some $ sformat!\"the type contains the following declarations: {occur1 ++ occur2}.\" ++\n--     (if occur1 = [] then \"\" else \" Add decidability type-class arguments instead.\") ++\n--     (if occur2 = [] then \"\" else \" Use \u2264/< instead.\")\n-- else none\n\n/-- A linter for checking whether illegal constants (\u2265, >) appear in a declaration's type. -/\n@[linter] meta def linter.ge_or_gt : linter :=\n{ test := ge_or_gt_in_statement,\n  auto_decls := ff,\n  no_errors_found := \"Not using \u2265/> in declarations.\",\n  errors_found := \"The following declarations use \u2265/>, probably in a way where we would prefer\n  to use \u2264/< instead. See note [nolint_ge] for more information.\",\n  is_fast := ff }\n\n/--\nCurrently, the linter forbids the use of `>` and `\u2265` in definitions and\nstatements, as they cause problems in rewrites.\nThey are still allowed in statements such as `bounded (\u2265)` or `\u2200 \u03b5 > 0` or `\u2a06 n \u2265 m`,\nand the linter allows that.\nIf you write a pattern where you bind two or more variables, like `\u2203 n m > 0`, the linter will\nflag this as illegal, but it is also allowed. In this case, add the line\n```\n@[nolint ge_or_gt] -- see Note [nolint_ge]\n```\n-/\nlibrary_note \"nolint_ge\"\n\n/-!\n## Linter for duplicate namespaces\n-/\n\n/-- Checks whether a declaration has a namespace twice consecutively in its name -/\nprivate meta def dup_namespace (d : declaration) : tactic (option string) :=\nis_instance d.to_name >>= \u03bb is_inst,\nreturn $ let nm := d.to_name.components in if nm.chain' (\u2260) \u2228 is_inst then none\n  else let s := (nm.find $ \u03bb n, nm.count n \u2265 2).iget.to_string in\n  some $ \"The namespace `\" ++ s ++ \"` is duplicated in the name\"\n\n/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/\n@[linter] meta def linter.dup_namespace : linter :=\n{ test := dup_namespace,\n  auto_decls := ff,\n  no_errors_found := \"No declarations have a duplicate namespace.\",\n  errors_found := \"DUPLICATED NAMESPACES IN NAME:\" }\n\nattribute [nolint dup_namespace] iff.iff\n\n/-!\n## Linter for unused arguments\n-/\n\n/-- Auxiliary definition for `check_unused_arguments` -/\nprivate meta def check_unused_arguments_aux : list \u2115 \u2192 \u2115 \u2192 \u2115 \u2192 expr \u2192 list \u2115 | l n n_max e :=\nif n > n_max then l else\nif \u00ac is_lambda e \u2227 \u00ac is_pi e then l else\n  let b := e.binding_body in\n  let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b\n\n/-- Check which arguments of a declaration are not used.\nPrints a list of natural numbers corresponding to which arguments are not used (e.g.\n  this outputs [1, 4] if the first and fourth arguments are unused).\nChecks both the type and the value of `d` for whether the argument is used\n(in rare cases an argument is used in the type but not in the value).\nWe return [] if the declaration was automatically generated.\nWe print arguments that are larger than the arity of the type of the declaration\n(without unfolding definitions). -/\nmeta def check_unused_arguments (d : declaration) : option (list \u2115) :=\nlet l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in\nif l = [] then none else\nlet l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in\n(l.filter $ \u03bb n, n \u2208 l2).reverse\n\n/-- Check for unused arguments, and print them with their position, variable name, type and whether\nthe argument is a duplicate.\nSee also `check_unused_arguments`.\nThis tactic additionally filters out all unused arguments of type `parse _`.\nWe skip all declarations that contain `sorry` in their value. -/\nprivate meta def unused_arguments (d : declaration) : tactic (option string) := do\n  ff \u2190 d.to_name.contains_sorry | return none,\n  let ns := check_unused_arguments d,\n  tt \u2190 return ns.is_some | return none,\n  let ns := ns.iget,\n  (ds, _) \u2190 get_pi_binders d.type,\n  let ns := ns.map (\u03bb n, (n, (ds.nth $ n - 1).iget)),\n  let ns := ns.filter (\u03bb x, x.2.type.get_app_fn \u2260 const `interactive.parse []),\n  ff \u2190 return ns.empty | return none,\n  ds' \u2190 ds.mmap pp,\n  ns \u2190 ns.mmap (\u03bb \u27e8n, b\u27e9, (\u03bb s, to_fmt \"argument \" ++ to_fmt n ++ \": \" ++ s ++\n    (if ds.countp (\u03bb b', b.type = b'.type) \u2265 2 then \" (duplicate)\" else \"\")) <$> pp b),\n  return $ some $ ns.to_string_aux tt\n\n/-- A linter object for checking for unused arguments. This is in the default linter set. -/\n@[linter] meta def linter.unused_arguments : linter :=\n{ test := unused_arguments,\n  auto_decls := ff,\n  no_errors_found := \"No unused arguments.\",\n  errors_found := \"UNUSED ARGUMENTS.\" }\n\nattribute [nolint unused_arguments] imp_intro\n\n\n\n/-!\n## Linter for documentation strings\n-/\n\n/-- Reports definitions and constants that are missing doc strings -/\nprivate meta def doc_blame_report_defn : declaration \u2192 tactic (option string)\n| (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return \"def missing doc string\"\n| (declaration.cnst n _ _ _) := doc_string n >> return none <|> return \"constant missing doc string\"\n| _ := return none\n\n/-- Reports definitions and constants that are missing doc strings -/\nprivate meta def doc_blame_report_thm : declaration \u2192 tactic (option string)\n| (declaration.thm n _ _ _) := doc_string n >> return none <|> return \"theorem missing doc string\"\n| _ := return none\n\n/-- A linter for checking definition doc strings -/\n@[linter] meta def linter.doc_blame : linter :=\n{ test := \u03bb d, mcond (bnot <$> has_attribute' `instance d.to_name)\n    (doc_blame_report_defn d) (return none),\n  auto_decls := ff,\n  no_errors_found := \"No definitions are missing documentation.\",\n  errors_found := \"DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:\" }\n\n/-- A linter for checking theorem doc strings. This is not in the default linter set. -/\nmeta def linter.doc_blame_thm : linter :=\n{ test := doc_blame_report_thm,\n  auto_decls := ff,\n  no_errors_found := \"No theorems are missing documentation.\",\n  errors_found := \"THEOREMS ARE MISSING DOCUMENTATION STRINGS:\",\n  is_fast := ff }\n\n/-!\n## Linter for correct usage of `lemma`/`def`\n-/\n\n/--\nChecks whether the correct declaration constructor (definition or theorem) by\ncomparing it to its sort. Instances will not be printed.\n\nThis test is not very quick: maybe we can speed-up testing that something is a proposition?\nThis takes almost all of the execution time.\n-/\nprivate meta def incorrect_def_lemma (d : declaration) : tactic (option string) :=\n  if d.is_constant \u2228 d.is_axiom\n  then return none else do\n    is_instance_d \u2190 is_instance d.to_name,\n    if is_instance_d then return none else do\n      -- the following seems to be a little quicker than `is_prop d.type`.\n      expr.sort n \u2190 infer_type d.type,\n      is_pattern \u2190 has_attribute' `pattern d.to_name,\n      return $\n        if d.is_theorem \u2194 n = level.zero then none\n        else if d.is_theorem then \"is a lemma/theorem, should be a def\"\n        else if is_pattern then none -- declarations with `@[pattern]` are allowed to be a `def`.\n        else \"is a def, should be a lemma/theorem\"\n\n/-- A linter for checking whether the correct declaration constructor (definition or theorem)\nhas been used. -/\n@[linter] meta def linter.def_lemma : linter :=\n{ test := incorrect_def_lemma,\n  auto_decls := ff,\n  no_errors_found := \"All declarations correctly marked as def/lemma.\",\n  errors_found := \"INCORRECT DEF/LEMMA:\" }\n\n/-!\n## Linter that checks whether declarations are well-typed\n-/\n\n/-- Checks whether the statement of a declaration is well-typed. -/\nmeta def check_type (d : declaration) : tactic (option string) :=\n(type_check d.type >> return none) <|> return \"The statement doesn't type-check\"\n\n/-- A linter for missing checking whether statements of declarations are well-typed. -/\n@[linter]\nmeta def linter.check_type : linter :=\n{ test := check_type,\n  auto_decls := ff,\n  no_errors_found :=\n    \"The statements of all declarations type-check with default reducibility settings.\",\n  errors_found := \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK.\nSome definitions in the statement are marked `@[irreducible]`, which means that the statement \" ++\n\"is now ill-formed. It is likely that these definitions were locally marked as `@[reducible]` \" ++\n\"or `@[semireducible]`. This can especially cause problems with type class inference or \" ++\n\"`@[simps]`.\",\n  is_fast := tt }\n\n/-!\n## Linter for universe parameters\n-/\n\nopen native\n/--\n  `univ_params_grouped e` computes for each `level` `u` of `e` the parameters that occur in `u`,\n  and returns the corresponding set of lists of parameters.\n  In pseudo-mathematical form, this returns `{ { p : parameter | p \u2208 u } | (u : level) \u2208 e }`\n  We use `list name` instead of `name_set`, since `name_set` does not have an order.\n  It will ignore `nm\u2080._proof_i` declarations.\n-/\nmeta def expr.univ_params_grouped (e : expr) (nm\u2080 : name) : rb_set (list name) :=\ne.fold mk_rb_set $ \u03bb e n l,\n  match e with\n  | e@(sort u) := l.insert u.params.to_list\n  | e@(const nm us) := if nm.get_prefix = nm\u2080 \u2227 nm.last.starts_with \"_proof_\" then l else\n      l.union $ rb_set.of_list $ us.map $ \u03bb u : level, u.params.to_list\n  | _ := l\n  end\n\n/--\n  The good parameters are the parameters that occur somewhere in the `rb_set` as a singleton or\n  (recursively) with only other good parameters.\n  All other parameters in the `rb_set` are bad.\n-/\nmeta def bad_params : rb_set (list name) \u2192 list name | l :=\nlet good_levels : name_set :=\n  l.fold mk_name_set $ \u03bb us prev, if us.length = 1 then prev.insert us.head else prev in\nif good_levels.empty then\nl.fold [] list.union\nelse bad_params $ rb_set.of_list $ l.to_list.map $ \u03bb us, us.filter $ \u03bb nm, !good_levels.contains nm\n\n/--\nChecks whether all universe levels `u` in the type of `d` are \"good\".\nThis means that `u` either occurs in a `level` of `d` by itself, or (recursively)\nwith only other good levels.\nWhen this fails, usually this means that there is a level `max u v`, where neither `u` nor `v`\noccur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example,\n`(\u03b1 : Type u) (\u03b2 : Type (max u v))` is a occasionally useful method of saying that `\u03b2` lives in\na higher universe level than `\u03b1`.\n-/\nmeta def check_univs (d : declaration) : tactic (option string) := do\n  let l := d.type.univ_params_grouped d.to_name,\n  let bad := bad_params l,\n  if bad.empty then return none else\n    return $ some $ \"universes \" ++ to_string bad ++ \" only occur together.\"\n\n/-- A linter for checking that there are no bad `max u v` universe levels. -/\n@[linter]\nmeta def linter.check_univs : linter :=\n{ test := check_univs,\n  auto_decls := ff,\n  no_errors_found :=\n    \"All declarations have good universe levels.\",\n  errors_found := \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. \" ++\n\"This usually means that there is a `max u v` in the type where neither `u` nor `v` \" ++\n\"occur by themselves. Solution: Find the type (or type bundled with data) that has this \" ++\n\"universe argument and provide the universe level explicitly. If this happens in an implicit \" ++\n\"argument of the declaration, a better solution is to move this argument to a `variables` \" ++\n\"command (then it's not necessary to provide the universe level).\nIt is possible that this linter gives a false positive on definitions where the value of the \" ++\n\"definition has the universes occur separately, and the definition will usually be used with \" ++\n\"explicit universe arguments. In this case, feel free to add `@[nolint check_univs]`.\",\n  is_fast := tt }\n\n/-!\n## Linter for syntactic tautologies\n-/\n\n/--\nChecks whether a lemma is a declaration of the form `\u2200 a b ... z, e\u2081 = e\u2082`\nwhere `e\u2081` and `e\u2082` are identical exprs.\nWe call declarations of this form syntactic tautologies.\nSuch lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts\nwith rfl when elaboration results in a different term than the user intended.\n-/\nmeta def syn_taut (d : declaration) : tactic (option string) :=\n  (do (el, er) \u2190 d.type.pi_codomain.is_eq,\n    guardb (el =\u2090 er),\n    return $ some \"LHS equals RHS syntactically\") <|>\n  return none\n\n/-- A linter for checking that declarations aren't syntactic tautologies. -/\n@[linter]\nmeta def linter.syn_taut : linter :=\n{ test := syn_taut,\n  auto_decls := ff, -- many false positives with this enabled\n  no_errors_found :=\n    \"No declarations are syntactic tautologies.\",\n  errors_found := \"THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. \" ++\n\"This usually means that they are of the form `\u2200 a b ... z, e\u2081 = e\u2082` where `e\u2081` and `e\u2082` are \" ++\n\"identical expressions. We call declarations of this form syntactic tautologies. \" ++\n\"Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving \" ++\n\"basic facts using `rfl`, when elaboration results in a different term than the user intended. \" ++\n\"You should check that the declaration really says what you think it does.\",\n  is_fast := tt }\n\nattribute [nolint syn_taut] rfl\n\n\n/-!\n## Linters for ineffectual have and suffices statements in term mode\n-/\n\n/--\nCheck if an expression contains `var 0` by folding over the expression and matching the binder depth\n-/\nmeta def expr.has_zero_var (e : expr) : bool :=\ne.fold ff $ \u03bb e' d res, res || match e' with | var k := k = d | _ := ff end\n\n/--\nReturn a list of unused have and suffices terms in an expression\n-/\nmeta def find_unused_have_suffices_macros : expr \u2192 tactic (list string)\n| (app a b) := (++) <$> find_unused_have_suffices_macros a <*> find_unused_have_suffices_macros b\n| (lam var_name bi var_type body) := find_unused_have_suffices_macros body\n| (pi var_name bi var_type body) := find_unused_have_suffices_macros body\n| (elet var_name type assignment body) := (++) <$> find_unused_have_suffices_macros assignment\n                                               <*> find_unused_have_suffices_macros body\n| m@(macro md [l@(lam ppnm bi vt bd)]) := do -- term mode have statements are tagged with a macro\n  -- if the macro annotation is `have then this lambda came from a term mode have statement\n  (++) (if m.is_annotation.iget.fst = `have \u2227 \u00acbd.has_zero_var then\n      [\"unnecessary have \" ++ ppnm.to_string ++ \" : \" ++ vt.to_string]\n    else []) <$>\n  find_unused_have_suffices_macros l\n| m@(macro md [app l@(lam ppnm bi vt bd) arg]) := do\n  -- term mode suffices statements are tagged with a macro\n  -- if the macro annotation is `suffices then this lambda came from a term mode suffices statement\n  (++) (if m.is_annotation.iget.fst = `suffices \u2227 \u00acbd.has_zero_var then\n      [\"unnecessary suffices \" ++ ppnm.to_string ++ \" : \" ++ vt.to_string]\n    else []) <$>\n  ((++) <$> find_unused_have_suffices_macros l <*> find_unused_have_suffices_macros arg)\n| (macro md l) := list.join <$> l.mmap find_unused_have_suffices_macros\n| _ := return []\n\n/--\nReturn a list of unused have and suffices terms in a declaration\n-/\nmeta def unused_have_of_decl : declaration \u2192 tactic (list string)\n| (declaration.defn _ _ _ bd _ _) := find_unused_have_suffices_macros bd\n| (declaration.thm _ _ _ bd) := find_unused_have_suffices_macros bd.get\n| _ := return []\n\n/--\nChecks whether a declaration contains term mode have statements that have no effect on the resulting\nterm.\n-/\nmeta def has_unused_haves_suffices (d : declaration) : tactic (option string) := do\n  ns \u2190 unused_have_of_decl d,\n  if ns.length = 0 then\n    return none\n  else\n    return (\", \".intercalate (ns.map to_string))\n\n/-- A linter for checking that declarations don't have unused term mode have statements. We do not\ntag this as `@[linter]` so that it is not in the default linter set as it is slow and an uncommon\nproblem. -/\nmeta def linter.unused_haves_suffices : linter :=\n{ test := has_unused_haves_suffices,\n  auto_decls := ff,\n  no_errors_found := \"No declarations have unused term mode have statements.\",\n  errors_found := \"THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. \" ++\n\"In the case of `have` this is a term of the form `have h := foo, bar` where `bar` does not \" ++\n\"refer to `foo`. Such statements have no effect on the generated proof, and can just be \" ++\n\"replaced by `bar`, in addition to being ineffectual, they may make unnecessary assumptions \" ++\n\"in proofs appear as if they are used. \" ++\n\"For `suffices` this is a term of the form `suffices h : foo, proof_of_goal, proof_of_foo` where\" ++\n\" `proof_of_goal` does not refer to `foo`. \" ++\n\"Such statements have no effect on the generated proof, and can just be replaced by \" ++\n\"`proof_of_goal`, in addition to being ineffectual, they may make unnecessary assumptions in \" ++\n\"proofs appear as if they are used. \",\n  is_fast := ff }\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/lint/misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.08151975206972073, "lm_q1q2_score": 0.03444247307836052}}
{"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 | \"_\" | \"\u27e8\" (patt \",\")* patt \"\u27e9\"\n```\n\nA pattern like `\u27e8a, b, c\u27e9 | \u27e8d, e\u27e9` 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 `\u27e8\u27e8a\u27e9, b | c\u27e9 | d` then these will cause more case splits as necessary.\nIf there are too many arguments, such as `\u27e8a, b, c\u27e9` for splitting on\n`\u2203 x, \u2203 y, p x`, then it will be treated as `\u27e8a, \u27e8b, c\u27e9\u27e9`, 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 \u2192 tactic unit\n| (p, sum.inl ids) := tactic.rcases p ids\n| (p, sum.inr depth) := do\n  patt \u2190 tactic.rcases_hint p depth,\n  pe \u2190 pp p,\n  trace $ \u2191\"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 | \u27e8b, c\u27e9) \u27e8d, e\u27e9`\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 \u2192 tactic unit\n| (sum.inl []) := intros []\n| (sum.inl l)  := tactic.rintro l\n| (sum.inr depth) := do\n  ps \u2190 tactic.rintro_hint depth,\n  trace $ \u2191\"snippet: rintro\" ++ format.join (ps.map $ \u03bb 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 \u2190 i_to_expr e <|> do {\n    ty \u2190 target,\n    e \u2190 i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result\n    pty \u2190 pp ty, ptgt \u2190 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 \u2190 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 \u2190 i_to_expr_strict max >>= tactic.eval_expr nat,\n  \u03bb 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' (\u03bb 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 \u2190 target,\n   name \u2190 decl_name,\n   let to_unfold := (tgt.list_names_with_prefix name),\n   guard (\u00ac 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\u03bb s, result.cases_on (tac s)\n (\u03bb a, result.success ())\n (\u03bb e ref, result.success ())\n\n/-- Move goal `n` to the front. -/\nmeta def swap (n := 2) : tactic unit :=\ndo gs \u2190 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_* \u2192 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 \u2190 local_context,\n  l.reverse.mfirst $ \u03bb h, do\n    name.mk_string s p \u2190 return $ local_pp_name h,\n    guard (s.front = '_'),\n    cl \u2190 infer_type h >>= is_class, guard (\u00ac 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`\u22a2 f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `\u22a2 x = y`\nand `\u22a2 y = x`, while `congr' 2` produces the intended `\u22a2 x + y = y + x`. -/\nmeta def congr' : parse (with_desc \"n\" small_nat)? \u2192 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 \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nmeta def replace (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?) (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\ndo let h := h.get_or_else `this,\n  old \u2190 try_core (get_local h),\n  \u00abhave\u00bb h q\u2081 q\u2082,\n  match old, q\u2082 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 `... \u2192 \u2200 _, ... \u2192 head`\nwhere `head` matches the current goal.\n\nalternatively, when encountering an assumption of the form `sg\u2080 \u2192 \u00ac sg\u2081`,\nafter the main approach failed, the goal is dismissed and `sg\u2080` and `sg\u2081`\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 `_ \u2227 _`, `_ \u2228 _`, `_ \u2194 _` and `\u2203 _, _`\nand splits a goal of the form `_ \u2227 _`, `_ \u2194 _` or `\u2203 _, _` 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 \u2192 parser (pexpr \u00d7 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 \u00d7 name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\nlemma {u} generalize_a_aux {\u03b1 : Sort u}\n  (h : \u2200 x : Sort u, (\u03b1 \u2192 x) \u2192 x) : \u03b1 := h \u03b1 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' \u2190 get_unused_name `h,\n   x' \u2190 get_unused_name `x,\n   g \u2190 if \u00ac 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 \u2190 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 \"\u2190\" (tk \"<-\")?)) (r : parse texpr) (n : parse (tk \"using\" *> small_nat)?) : tactic unit :=\ndo v \u2190 mk_mvar,\n   if sym.is_some\n     then refine ``(eq.mp %%v %%r)\n     else refine ``(eq.mpr %%v %%r),\n   gs \u2190 get_goals,\n   set_goals [v],\n   congr' n,\n   gs' \u2190 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 \u2190 target,\n   e \u2190 i_to_expr_strict ``(%%q : %%tgt),\n   tactic.exact $ e.replace (\u03bb e n,\n     match e with\n     | (app (app (const n _) _) e') :=\n       if n \u2208 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 \u00d7 pexpr)) :=\ndo e \u2190 to_expr e,\n   t \u2190 infer_type e,\n   let struct_n : name := t.get_app_fn.const_name,\n   fields \u2190 expanded_field_list struct_n,\n   let exp_fields := fields.filter (\u03bb x, x.2 \u2208 missing),\n   exp_fields.mmap $ \u03bb \u27e8p,n\u27e9,\n     (prod.mk n \u2218 to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]\n\nmeta def collect_struct' : pexpr \u2192 state_t (list $ expr\u00d7structure_instance_info) tactic pexpr | e :=\ndo some str \u2190 pure (e.get_structure_instance_info)\n       | e.traverse collect_struct',\n   v \u2190 monad_lift mk_mvar,\n   modify (list.cons (v,str)),\n   pure $ to_pexpr v\n\nmeta def collect_struct (e : pexpr) : tactic $ pexpr \u00d7 list (expr\u00d7structure_instance_info) :=\nprod.map id list.reverse <$> (collect_struct' e).run []\n\nmeta def refine_one (str : structure_instance_info) :\n  tactic $ list (expr\u00d7structure_instance_info) :=\ndo    tgt \u2190 target,\n      let struct_n : name := tgt.get_app_fn.const_name,\n      exp_fields \u2190 expanded_field_list struct_n,\n      let missing_f := exp_fields.filter (\u03bb f, (f.2 : name) \u2209 str.field_names),\n      (src_field_names,src_field_vals) \u2190 (@list.unzip name _ \u2218 list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd),\n      let provided  := exp_fields.filter (\u03bb f, (f.2 : name) \u2208 str.field_names),\n      let missing_f' := missing_f.filter (\u03bb x, x.2 \u2209 src_field_names),\n      vs \u2190 mk_mvar_list missing_f'.length,\n      (field_values,new_goals) \u2190 list.unzip <$> (str.field_values.mmap collect_struct : tactic _),\n      e' \u2190 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 \u2190 with_enable_tags (\n        mzip_with (\u03bb (n : name \u00d7 name) v, do\n           set_goals [v],\n           try (interactive.unfold (provided.map $ \u03bb \u27e8s,f\u27e9, 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 \u00d7 structure_instance_info \u2192 tactic (list expr) | (e,str) :=\ndo set_goals [e],\n   rs \u2190 refine_one str,\n   gs \u2190 get_goals,\n   gs' \u2190 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 \u03b1 ),\n-- case semigroup, mul\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\n```\n-/\nmeta def refine_struct : parse texpr \u2192 tactic unit | e :=\ndo (x,xs) \u2190 collect_struct e,\n   refine x,\n   gs \u2190 get_goals,\n   xs' \u2190 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 \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p\n\nmeta def guard_hyp_nums (n : \u2115) : tactic unit :=\ndo k \u2190 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) \u2190 get_main_tag,\n   guard (t = tags)\n\nmeta def get_current_field : tactic name :=\ndo [_,field,str] \u2190 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 \u2190 get_goals,\n   ts \u2190 gs.mmap get_tag,\n   ([g],gs') \u2190 pure $ (list.zip gs ts).partition (\u03bb 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 \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```\nrefine_struct ({ .. } : semigroup \u03b1),\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 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 \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr))\n  (e x x' eq_h : expr) :\n  tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 expr)) :=\n(do guard (\u00ac e.has_var),\n    unify x x',\n    u \u2190 mk_meta_univ,\n    f \u2190 f <|> to_expr ``(@id %%(expr.sort u : expr)),\n    t' \u2190 infer_type e,\n    some (f',t) \u2190 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 \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr)) :\n  expr \u2192 tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 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 %%\u03b1 %%p %%a %%b  %%eq_h %%x') := return_cast p t es e x x' eq_h\n| e@`(@eq.substr %%\u03b1 %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'\n| e@`(@eq.rec %%\u03b1 %%a %%f %%x' _  %%eq_h) := return_cast f t es e x x' eq_h\n| e@`(@eq.rec_on %%\u03b1 %%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 \u00d7 expr \u00d7 expr)) :=\n(list.reverse \u2218 prod.snd) <$> tgt.mfold (none, []) (\u03bb e i es, list_cast_of_aux x es.1 es.2 e)\n\nprivate meta def h_generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`.\n\n`h_generalize Hx : e == x with _` chooses automatically chooses the name of\nassumption `\u03b1 = \u03b2`.\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' \u2190 (h' : tactic name) <|> get_unused_name (\"h\" ++ n.to_string : string),\n   e \u2190 to_expr e,\n   tgt \u2190 target,\n   ((e,x,eq_h)::es) \u2190 list_cast_of e tgt | fail \"no cast found\",\n   interactive.generalize h' () (to_pexpr e, n),\n   asm \u2190 get_local h',\n   v \u2190 get_local n,\n   hs \u2190 es.mmap (\u03bb \u27e8e,_\u27e9, mk_app `eq [e,v]),\n   (eqs_h.zip [e]).mmap' (\u03bb \u27e8h,e\u27e9, do\n        h \u2190 if h \u2260 `_ then pure h else get_unused_name `h,\n        () <$ note h none eq_h ),\n   hs.mmap' (\u03bb h,\n     do h' \u2190 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) 2018 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.WFTactics\nimport Init.Data.Nat.Basic\nimport Init.Data.Fin.Basic\nimport Init.Data.UInt\nimport Init.Data.Repr\nimport Init.Data.ToString.Basic\nimport Init.Util\nuniverse u v w\n\nnamespace Array\nvariable {\u03b1 : Type u}\n\n@[extern \"lean_mk_array\"]\ndef mkArray {\u03b1 : Type u} (n : Nat) (v : \u03b1) : Array \u03b1 := {\n  data := List.replicate n v\n}\n\n@[simp] theorem size_mkArray (n : Nat) (v : \u03b1) : (mkArray n v).size = n :=\n  List.length_replicate ..\n\ninstance : EmptyCollection (Array \u03b1) := \u27e8Array.empty\u27e9\ninstance : Inhabited (Array \u03b1) where\n  default := Array.empty\n\ndef isEmpty (a : Array \u03b1) : Bool :=\n  a.size = 0\n\ndef singleton (v : \u03b1) : Array \u03b1 :=\n  mkArray 1 v\n\n/- Low-level version of `fget` which is as fast as a C array read.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fget` may be slightly slower than `uget`. -/\n@[extern \"lean_array_uget\"]\ndef uget (a : @& Array \u03b1) (i : USize) (h : i.toNat < a.size) : \u03b1 :=\n  a.get \u27e8i.toNat, h\u27e9\n\ndef back [Inhabited \u03b1] (a : Array \u03b1) : \u03b1 :=\n  a.get! (a.size - 1)\n\ndef get? (a : Array \u03b1) (i : Nat) : Option \u03b1 :=\n  if h : i < a.size then some (a.get \u27e8i, h\u27e9) else none\n\ndef back? (a : Array \u03b1) : Option \u03b1 :=\n  a.get? (a.size - 1)\n\n-- auxiliary declaration used in the equation compiler when pattern matching array literals.\nabbrev getLit {\u03b1 : Type u} {n : Nat} (a : Array \u03b1) (i : Nat) (h\u2081 : a.size = n) (h\u2082 : i < n) : \u03b1 :=\n  a.get \u27e8i, h\u2081.symm \u25b8 h\u2082\u27e9\n\n@[simp] theorem size_set (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : (set a i v).size = a.size :=\n  List.length_set ..\n\n@[simp] theorem size_push (a : Array \u03b1) (v : \u03b1) : (push a v).size = a.size + 1 :=\n  List.length_concat ..\n\n/- Low-level version of `fset` which is as fast as a C array fset.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fset` may be slightly slower than `uset`. -/\n@[extern \"lean_array_uset\"]\ndef uset (a : Array \u03b1) (i : USize) (v : \u03b1) (h : i.toNat < a.size) : Array \u03b1 :=\n  a.set \u27e8i.toNat, h\u27e9 v\n\n@[extern \"lean_array_fswap\"]\ndef swap (a : Array \u03b1) (i j : @& Fin a.size) : Array \u03b1 :=\n  let v\u2081 := a.get i\n  let v\u2082 := a.get j\n  let a'  := a.set i v\u2082\n  a'.set (size_set a i v\u2082 \u25b8 j) v\u2081\n\n@[extern \"lean_array_swap\"]\ndef swap! (a : Array \u03b1) (i j : @& Nat) : Array \u03b1 :=\n  if h\u2081 : i < a.size then\n  if h\u2082 : j < a.size then swap a \u27e8i, h\u2081\u27e9 \u27e8j, h\u2082\u27e9\n  else panic! \"index out of bounds\"\n  else panic! \"index out of bounds\"\n\n@[inline] def swapAt (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  let e := a.get i\n  let a := a.set i v\n  (e, a)\n\n@[inline]\ndef swapAt! (a : Array \u03b1) (i : Nat) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  if h : i < a.size then\n    swapAt a \u27e8i, h\u27e9 v\n  else\n    have : Inhabited \u03b1 := \u27e8v\u27e9\n    panic! (\"index \" ++ toString i ++ \" out of bounds\")\n\n@[extern \"lean_array_pop\"]\ndef pop (a : Array \u03b1) : Array \u03b1 := {\n  data := a.data.dropLast\n}\n\ndef shrink (a : Array \u03b1) (n : Nat) : Array \u03b1 :=\n  let rec loop\n    | 0,   a => a\n    | n+1, a => loop n a.pop\n  loop (a.size - n) a\n\n@[inline]\nunsafe def modifyMUnsafe [Monad m] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 m \u03b1) : m (Array \u03b1) := do\n  if h : i < a.size then\n    let idx : Fin a.size := \u27e8i, h\u27e9\n    let v                := a.get idx\n    -- Replace a[i] by `box(0)`.  This ensures that `v` remains unshared if possible.\n    -- Note: we assume that arrays have a uniform representation irrespective\n    -- of the element type, and that it is valid to store `box(0)` in any array.\n    let a'               := a.set idx (unsafeCast ())\n    let v \u2190 f v\n    pure <| a'.set (size_set a .. \u25b8 idx) v\n  else\n    pure a\n\n@[implementedBy modifyMUnsafe]\ndef modifyM [Monad m] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 m \u03b1) : m (Array \u03b1) := do\n  if h : i < a.size then\n    let idx := \u27e8i, h\u27e9\n    let v   := a.get idx\n    let v \u2190 f v\n    pure <| a.set idx v\n  else\n    pure a\n\n@[inline]\ndef modify (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  Id.run <| modifyM a i f\n\n@[inline]\ndef modifyOp (self : Array \u03b1) (idx : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  self.modify idx f\n\n/-\n  We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime.\n\n  This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/\n@[inline] unsafe def forInUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] loop (i : USize) (b : \u03b2) : m \u03b2 := do\n    if i < sz then\n      let a := as.uget i lcProof\n      match (\u2190 f a b) with\n      | ForInStep.done  b => pure b\n      | ForInStep.yield b => loop (i+1) b\n    else\n      pure b\n  loop 0 b\n\n/- Reference implementation for `forIn` -/\n@[implementedBy Array.forInUnsafe]\nprotected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec loop (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    match i, h with\n    | 0,   _ => pure b\n    | i+1, h =>\n      have h' : i < as.size            := Nat.lt_of_lt_of_le (Nat.lt_succ_self i) h\n      have : as.size - 1 < as.size     := Nat.sub_lt (Nat.zero_lt_of_lt h') (by decide)\n      have : as.size - 1 - i < as.size := Nat.lt_of_le_of_lt (Nat.sub_le (as.size - 1) i) this\n      match (\u2190 f (as.get \u27e8as.size - 1 - i, this\u27e9) b) with\n      | ForInStep.done b  => pure b\n      | ForInStep.yield b => loop i (Nat.le_of_lt h') b\n  loop as.size (Nat.le_refl _) b\n\ninstance : ForIn m (Array \u03b1) \u03b1 where\n  forIn := Array.forIn\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def foldlMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i+1) stop (\u2190 f b (as.uget i lcProof))\n  if start < stop then\n    if stop \u2264 as.size then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else\n    pure init\n\n/- Reference implementation for `foldlM` -/\n@[implementedBy foldlMUnsafe]\ndef foldlM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let fold (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) (b : \u03b2) : m \u03b2 := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure b\n        | i'+1 =>\n          loop i' (j+1) (\u2190 f b (as.get \u27e8j, Nat.lt_of_lt_of_le hlt h\u27e9))\n      else\n        pure b\n    loop (stop - start) start init\n  if h : stop \u2264 as.size then\n    fold stop h\n  else\n    fold as.size (Nat.le_refl _)\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def foldrMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i-1) stop (\u2190 f (as.uget (i-1) lcProof) b)\n  if start \u2264 as.size then\n    if stop < start then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else if stop < as.size then\n    fold (USize.ofNat as.size) (USize.ofNat stop) init\n  else\n    pure init\n\n/- Reference implementation for `foldrM` -/\n@[implementedBy foldrMUnsafe]\ndef foldrM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec fold (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else match i, h with\n      | 0, _   => pure b\n      | i+1, h =>\n        have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h\n        fold i (Nat.le_of_lt this) (\u2190 f (as.get \u27e8i, this\u27e9) b)\n  if h : start \u2264 as.size then\n    if stop < start then\n      fold start h init\n    else\n      pure init\n  else if stop < as.size then\n    fold as.size (Nat.le_refl _) init\n  else\n    pure init\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def mapMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do\n    if i < sz then\n     let v    := r.uget i lcProof\n     -- Replace r[i] by `box(0)`.  This ensures that `v` remains unshared if possible.\n     -- Note: we assume that arrays have a uniform representation irrespective\n     -- of the element type, and that it is valid to store `box(0)` in any array.\n     let r    := r.uset i default lcProof\n     let vNew \u2190 f (unsafeCast v)\n     map (i+1) (r.uset i (unsafeCast vNew) lcProof)\n    else\n     pure (unsafeCast r)\n  unsafeCast <| map 0 (unsafeCast as)\n\n/- Reference implementation for `mapM` -/\n@[implementedBy mapMUnsafe]\ndef mapM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (fun bs a => do let b \u2190 f a; pure (bs.push b)) (mkEmpty as.size)\n\n@[inline]\ndef mapIdxM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 m \u03b2) : m (Array \u03b2) :=\n  let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array \u03b2) : m (Array \u03b2) := do\n    match i, inv with\n    | 0,    _  => pure bs\n    | i+1, inv =>\n      have : j < as.size := by\n        rw [\u2190 inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_comm]\n        apply Nat.le_add_right\n      let idx : Fin as.size := \u27e8j, this\u27e9\n      have : i + (j + 1) = as.size := by rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n      map i (j+1) this (bs.push (\u2190 f idx (as.get idx)))\n  map as.size 0 rfl (mkEmpty as.size)\n\n@[inline]\ndef findSomeM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) := do\n  for a in as do\n    match (\u2190 f a) with\n    | some b => return b\n    | _      => pure \u27e8\u27e9\n  return none\n\n@[inline]\ndef findM? {\u03b1 : Type} {m : Type \u2192 Type} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) := do\n  for a in as do\n    if (\u2190 p a) then\n      return a\n  return none\n\n@[inline]\ndef findIdxM? [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option Nat) := do\n  let mut i := 0\n  for a in as do\n    if (\u2190 p a) then\n      return some i\n    i := i + 1\n  return none\n\n@[inline]\nunsafe def anyMUnsafe {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do\n    if i == stop then\n      pure false\n    else\n      if (\u2190 p (as.uget i lcProof)) then\n        pure true\n      else\n        any (i+1) stop\n  if start < stop then\n    if stop \u2264 as.size then\n      any (USize.ofNat start) (USize.ofNat stop)\n    else\n      pure false\n  else\n    pure false\n\n@[implementedBy anyMUnsafe]\ndef anyM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let any (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) : m Bool := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure false\n        | i'+1 =>\n          if (\u2190 p (as.get \u27e8j, Nat.lt_of_lt_of_le hlt h\u27e9)) then\n            pure true\n          else\n            loop i' (j+1)\n      else\n        pure false\n    loop (stop - start) start\n  if h : stop \u2264 as.size then\n    any stop h\n  else\n    any as.size (Nat.le_refl _)\n\n@[inline]\ndef allM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  return !(\u2190 as.anyM fun v => return !(\u2190 p v))\n\n@[inline]\ndef findSomeRevM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) :=\n  let rec @[specialize] find : (i : Nat) \u2192 i \u2264 as.size \u2192 m (Option \u03b2)\n    | 0,   h => pure none\n    | i+1, h => do\n      have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h\n      let r \u2190 f (as.get \u27e8i, this\u27e9)\n      match r with\n      | some v => pure r\n      | none   =>\n        have : i \u2264 as.size := Nat.le_of_lt this\n        find i this\n  find as.size (Nat.le_refl _)\n\n@[inline]\ndef findRevM? {\u03b1 : Type} {m : Type \u2192 Type w} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) :=\n  as.findSomeRevM? fun a => return if (\u2190 p a) then some a else none\n\n@[inline]\ndef forM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := 0) (stop := as.size) : m PUnit :=\n  as.foldlM (fun _ => f) \u27e8\u27e9 start stop\n\n@[inline]\ndef forRevM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := as.size) (stop := 0) : m PUnit :=\n  as.foldrM (fun a _ => f a) \u27e8\u27e9 start stop\n\n@[inline]\ndef foldl {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : \u03b2 :=\n  Id.run <| as.foldlM f init start stop\n\n@[inline]\ndef foldr {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : \u03b2 :=\n  Id.run <| as.foldrM f init start stop\n\n@[inline]\ndef map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  Id.run <| as.mapM f\n\n@[inline]\ndef mapIdx {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 \u03b2) : Array \u03b2 :=\n  Id.run <| as.mapIdxM f\n\n@[inline]\ndef find? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findM? p\n\n@[inline]\ndef findSome? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeM? f\n\n@[inline]\ndef findSome! {\u03b1 : Type u} {\u03b2 : Type v} [Inhabited \u03b2] (a : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : \u03b2 :=\n  match findSome? a f with\n  | some b => b\n  | none   => panic! \"failed to find element\"\n\n@[inline]\ndef findSomeRev? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeRevM? f\n\n@[inline]\ndef findRev? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findRevM? p\n\n@[inline]\ndef findIdx? {\u03b1 : Type u} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option Nat :=\n  let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat :=\n    if hlt : j < as.size then\n      match i, inv with\n      | 0, inv => by\n        apply False.elim\n        rw [Nat.zero_add] at inv\n        rw [inv] at hlt\n        exact absurd hlt (Nat.lt_irrefl _)\n      | i+1, inv =>\n        if p (as.get \u27e8j, hlt\u27e9) then\n          some j\n        else\n          have : i + (j+1) = as.size := by\n            rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n          loop i (j+1) this\n    else\n      none\n  loop as.size 0 rfl\n\ndef getIdx? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option Nat :=\na.findIdx? fun a => a == v\n\n@[inline]\ndef any (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.anyM p start stop\n\n@[inline]\ndef all (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.allM p start stop\n\ndef contains [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Bool :=\n  as.any fun b => a == b\n\ndef elem [BEq \u03b1] (a : \u03b1) (as : Array \u03b1) : Bool :=\n  as.contains a\n\ndef reverse (as : Array \u03b1) : Array \u03b1 :=\n  let n   := as.size\n  let mid := n / 2\n  let rec rev (as : Array \u03b1) (i : Nat) :=\n    if h : i < mid then\n      rev (as.swap! i (n - i - 1)) (i+1)\n    else\n      as\n  rev as 0\ntermination_by _ => mid - i\n\n@[inline] def getEvenElems (as : Array \u03b1) : Array \u03b1 :=\n  (\u00b7.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a =>\n    if even then\n      (false, r.push a)\n    else\n      (true, r)\n\n@[export lean_array_to_list]\ndef toList (as : Array \u03b1) : List \u03b1 :=\n  as.foldr List.cons []\n\ninstance {\u03b1 : Type u} [Repr \u03b1] : Repr (Array \u03b1) where\n  reprPrec a n :=\n    let _ : Std.ToFormat \u03b1 := \u27e8repr\u27e9\n    if a.size == 0 then\n      \"#[]\"\n    else\n      Std.Format.bracketFill \"#[\" (Std.Format.joinSep (toList a) (\",\" ++ Std.Format.line)) \"]\"\n\ninstance [ToString \u03b1] : ToString (Array \u03b1) where\n  toString a := \"#\" ++ toString a.toList\n\nprotected def append (as : Array \u03b1) (bs : Array \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : Append (Array \u03b1) := \u27e8Array.append\u27e9\n\nprotected def appendList (as : Array \u03b1) (bs : List \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : HAppend (Array \u03b1) (List \u03b1) (Array \u03b1) := \u27e8Array.appendList\u27e9\n\n@[inline]\ndef concatMapM [Monad m] (f : \u03b1 \u2192 m (Array \u03b2)) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (init := empty) fun bs a => do return bs ++ (\u2190 f a)\n\n@[inline]\ndef concatMap (f : \u03b1 \u2192 Array \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  as.foldl (init := empty) fun bs a => bs ++ f a\n\nend Array\n\nexport Array (mkArray)\n\nsyntax \"#[\" sepBy(term, \", \") \"]\" : term\n\nmacro_rules\n  | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ])\n\nnamespace Array\n\n-- TODO(Leo): cleanup\n@[specialize]\ndef isEqvAux (a b : Array \u03b1) (hsz : a.size = b.size) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) (i : Nat) : Bool :=\n  if h : i < a.size then\n     let aidx : Fin a.size := \u27e8i, h\u27e9;\n     let bidx : Fin b.size := \u27e8i, hsz \u25b8 h\u27e9;\n     match p (a.get aidx) (b.get bidx) with\n     | true  => isEqvAux a b hsz p (i+1)\n     | false => false\n  else\n    true\ntermination_by _ => a.size - i\n\n@[inline] def isEqv (a b : Array \u03b1) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) : Bool :=\n  if h : a.size = b.size then\n    isEqvAux a b h p 0\n  else\n    false\n\ninstance [BEq \u03b1] : BEq (Array \u03b1) :=\n  \u27e8fun a b => isEqv a b BEq.beq\u27e9\n\n@[inline]\ndef filter (p : \u03b1 \u2192 Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b1 :=\n  as.foldl (init := #[]) (start := start) (stop := stop) fun r a =>\n    if p a then r.push a else r\n\n@[inline]\ndef filterM [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b1) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do\n    if (\u2190 p a) then return r.push a else return r\n\n@[specialize]\ndef filterMapM [Monad m] (f : \u03b1 \u2192 m (Option \u03b2)) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b2) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do\n    match (\u2190 f a) with\n    | some b => pure (bs.push b)\n    | none   => pure bs\n\n@[inline]\ndef filterMap (f : \u03b1 \u2192 Option \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b2 :=\n  Id.run <| as.filterMapM f (start := start) (stop := stop)\n\n@[specialize]\ndef getMax? (as : Array \u03b1) (lt : \u03b1 \u2192 \u03b1 \u2192 Bool) : Option \u03b1 :=\n  if h : 0 < as.size then\n    let a0 := as.get \u27e80, h\u27e9\n    some <| as.foldl (init := a0) (start := 1) fun best a =>\n      if lt best a then a else best\n  else\n    none\n\n@[inline]\ndef partition (p : \u03b1 \u2192 Bool) (as : Array \u03b1) : Array \u03b1 \u00d7 Array \u03b1 := Id.run <| do\n  let mut bs := #[]\n  let mut cs := #[]\n  for a in as do\n    if p a then\n      bs := bs.push a\n    else\n      cs := cs.push a\n  return (bs, cs)\n\ntheorem ext (a b : Array \u03b1)\n    (h\u2081 : a.size = b.size)\n    (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.size) \u2192 (hi\u2082 : i < b.size) \u2192 a.get \u27e8i, hi\u2081\u27e9 = b.get \u27e8i, hi\u2082\u27e9)\n    : a = b := by\n  let rec extAux (a b : List \u03b1)\n      (h\u2081 : a.length = b.length)\n      (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.length) \u2192 (hi\u2082 : i < b.length) \u2192 a.get i hi\u2081 = b.get i hi\u2082)\n      : a = b := by\n    induction a generalizing b with\n    | nil =>\n      cases b with\n      | nil       => rfl\n      | cons b bs => rw [List.length_cons] at h\u2081; injection h\u2081\n    | cons a as ih =>\n      cases b with\n      | nil => rw [List.length_cons] at h\u2081; injection h\u2081\n      | cons b bs =>\n        have hz\u2081 : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zero_lt_succ\n        have hz\u2082 : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zero_lt_succ\n        have headEq : a = b := h\u2082 0 hz\u2081 hz\u2082\n        have h\u2081' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h\u2081; injection h\u2081; assumption\n        have h\u2082' : (i : Nat) \u2192 (hi\u2081 : i < as.length) \u2192 (hi\u2082 : i < bs.length) \u2192 as.get i hi\u2081 = bs.get i hi\u2082 := by\n          intro i hi\u2081 hi\u2082\n          have hi\u2081' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have hi\u2082' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have : (a::as).get (i+1) hi\u2081' = (b::bs).get (i+1) hi\u2082' := h\u2082 (i+1) hi\u2081' hi\u2082'\n          apply this\n        have tailEq : as = bs := ih bs h\u2081' h\u2082'\n        rw [headEq, tailEq]\n  cases a; cases b\n  apply congrArg\n  apply extAux\n  assumption\n  assumption\n\ntheorem extLit {n : Nat}\n    (a b : Array \u03b1)\n    (hsz\u2081 : a.size = n) (hsz\u2082 : b.size = n)\n    (h : (i : Nat) \u2192 (hi : i < n) \u2192 a.getLit i hsz\u2081 hi = b.getLit i hsz\u2082 hi) : a = b :=\n  Array.ext a b (hsz\u2081.trans hsz\u2082.symm) fun i hi\u2081 hi\u2082 => h i (hsz\u2081 \u25b8 hi\u2081)\n\nend Array\n\n-- CLEANUP the following code\nnamespace Array\n\ndef indexOfAux [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) (i : Nat) : Option (Fin a.size) :=\n  if h : i < a.size then\n    let idx : Fin a.size := \u27e8i, h\u27e9;\n    if a.get idx == v then some idx\n    else indexOfAux a v (i+1)\n  else none\ntermination_by _ => a.size - i\n\ndef indexOf? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option (Fin a.size) :=\n  indexOfAux a v 0\n\n@[simp] theorem size_swap (a : Array \u03b1) (i j : Fin a.size) : (a.swap i j).size = a.size := by\n  show ((a.set i (a.get j)).set (size_set a i _ \u25b8 j) (a.get i)).size = a.size\n  rw [size_set, size_set]\n\n@[simp] theorem size_pop (a : Array \u03b1) : a.pop.size = a.size - 1 :=\n  List.length_dropLast ..\n\ndef eraseIdxAux (i : Nat) (a : Array \u03b1) : Array \u03b1 :=\n  if h : i < a.size then\n    let idx  : Fin a.size := \u27e8i, h\u27e9;\n    let idx1 : Fin a.size := \u27e8i - 1, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h\u27e9;\n    let a' := a.swap idx idx1\n    have : a'.size - (i+1) < a.size - i := by rw [size_swap]; apply Nat.sub_succ_lt_self; assumption\n    eraseIdxAux (i+1) a'\n  else\n    a.pop\ntermination_by _ => a.size - i\n\ndef feraseIdx (a : Array \u03b1) (i : Fin a.size) : Array \u03b1 :=\n  eraseIdxAux (i.val + 1) a\n\ndef eraseIdx (a : Array \u03b1) (i : Nat) : Array \u03b1 :=\n  if i < a.size then eraseIdxAux (i+1) a else a\n\ndef eraseIdxSzAux (a : Array \u03b1) (i : Nat) (r : Array \u03b1) (heq : r.size = a.size) : { r : Array \u03b1 // r.size = a.size - 1 } :=\n  if h : i < r.size then\n    let idx  : Fin r.size := \u27e8i, h\u27e9;\n    let idx1 : Fin r.size := \u27e8i - 1, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h\u27e9;\n    eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq)\n  else\n    \u27e8r.pop, (size_pop r).trans (heq \u25b8 rfl)\u27e9\ntermination_by _ => r.size - i\n\ndef eraseIdx' (a : Array \u03b1) (i : Fin a.size) : { r : Array \u03b1 // r.size = a.size - 1 } :=\n  eraseIdxSzAux a (i.val + 1) a rfl\n\ndef erase [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Array \u03b1 :=\n  match as.indexOf? a with\n  | none   => as\n  | some i => as.feraseIdx i\n\ndef insertAtAux (i : Nat) (as : Array \u03b1) (j : Nat) : Array \u03b1 :=\n  if h : i < j then\n    let as := as.swap! (j-1) j;\n    insertAtAux i as (j-1)\n  else\n    as\ntermination_by _ => j\n\n/--\n  Insert element `a` at position `i`.\n  Pre: `i < as.size` -/\ndef insertAt (as : Array \u03b1) (i : Nat) (a : \u03b1) : Array \u03b1 :=\n  if i > as.size then panic! \"invalid index\"\n  else\n    let as := as.push a;\n    as.insertAtAux i as.size\n\ndef toListLitAux (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : \u2200 (i : Nat), i \u2264 a.size \u2192 List \u03b1 \u2192 List \u03b1\n  | 0,     hi, acc => acc\n  | (i+1), hi, acc => toListLitAux a n hsz i (Nat.le_of_succ_le hi) (a.getLit i hsz (Nat.lt_of_lt_of_eq (Nat.lt_of_lt_of_le (Nat.lt_succ_self i) hi) hsz) :: acc)\n\ndef toArrayLit (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : Array \u03b1 :=\n  List.toArray <| toListLitAux a n hsz n (hsz \u25b8 Nat.le_refl _) []\n\ntheorem toArrayLit_eq (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz :=\n  -- TODO: this is painful to prove without proper automation\n  sorry\n  /-\n  First, we need to prove\n  \u2200 i j acc, i \u2264 a.size \u2192 (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i)\n  by induction\n\n  Base case is trivial\n  (j : Nat) (acc : List \u03b1) (hi : 0 \u2264 a.size)\n       |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0)\n  ...  |- acc.index j = acc.index j\n\n  Induction\n\n  (j : Nat) (acc : List \u03b1) (hi : i+1 \u2264 a.size)\n        |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))\n    ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))  * by def\n    ... |- if j < i     then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i)    * by induction hypothesis\n           =\n           if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))\n  If j < i, then both are a.getLit j hsz _\n  If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _)\n  If j >= i + 1, we use\n     - j - i >= 1 > 0\n     - (a::as).index k = as.index (k-1) If k > 0\n     - j - (i + 1) = (j - i) - 1\n     Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs\n\n  With this proof, we have\n\n  \u2200 j, j < n \u2192 (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _\n\n  We also need\n\n  - (toListLitAux a n hsz n _ []).length = n\n  - j < n -> (List.toArray as).getLit j _ _ = as.index j\n\n  Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ []\n  -/\n\ndef isPrefixOfAux [BEq \u03b1] (as bs : Array \u03b1) (hle : as.size \u2264 bs.size) (i : Nat) : Bool :=\n  if h : i < as.size then\n    let a := as.get \u27e8i, h\u27e9;\n    let b := bs.get \u27e8i, Nat.lt_of_lt_of_le h hle\u27e9;\n    if a == b then\n      isPrefixOfAux as bs hle (i+1)\n    else\n      false\n  else\n    true\ntermination_by _ => as.size - i\n\n/- Return true iff `as` is a prefix of `bs` -/\ndef isPrefixOf [BEq \u03b1] (as bs : Array \u03b1) : Bool :=\n  if h : as.size \u2264 bs.size then\n    isPrefixOfAux as bs h 0\n  else\n    false\n\nprivate def allDiffAuxAux [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : forall (i : Nat), i < as.size \u2192 Bool\n  | 0,   h => true\n  | i+1, h =>\n    have : i < as.size := Nat.lt_trans (Nat.lt_succ_self _) h;\n    a != as.get \u27e8i, this\u27e9 && allDiffAuxAux as a i this\n\nprivate def allDiffAux [BEq \u03b1] (as : Array \u03b1) (i : Nat) : Bool :=\n  if h : i < as.size then\n    allDiffAuxAux as (as.get \u27e8i, h\u27e9) i h && allDiffAux as (i+1)\n  else\n    true\ntermination_by _ => as.size - i\n\ndef allDiff [BEq \u03b1] (as : Array \u03b1) : Bool :=\n  allDiffAux as 0\n\n@[specialize] def zipWithAux (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (as : Array \u03b1) (bs : Array \u03b2) (i : Nat) (cs : Array \u03b3) : Array \u03b3 :=\n  if h : i < as.size then\n    let a := as.get \u27e8i, h\u27e9;\n    if h : i < bs.size then\n      let b := bs.get \u27e8i, h\u27e9;\n      zipWithAux f as bs (i+1) <| cs.push <| f a b\n    else\n      cs\n  else\n    cs\ntermination_by _ => as.size - i\n\n@[inline] def zipWith (as : Array \u03b1) (bs : Array \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : Array \u03b3 :=\n  zipWithAux f as bs 0 #[]\n\ndef zip (as : Array \u03b1) (bs : Array \u03b2) : Array (\u03b1 \u00d7 \u03b2) :=\n  zipWith as bs Prod.mk\n\ndef unzip (as : Array (\u03b1 \u00d7 \u03b2)) : Array \u03b1 \u00d7 Array \u03b2 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b)\n\ndef split (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Array \u03b1 \u00d7 Array \u03b1 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) a =>\n    if p a then (as.push a, bs) else (as, bs.push a)\n\nend Array\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/Array/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.08389038755577574, "lm_q1q2_score": 0.03417135679426493}}
{"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: Abdalrhman Mohamed, Tomaz Gomes Mascarenhas, Wojciech Nawrocki\n-/\n\nimport Lean\nimport Smt.Commands\nimport Smt.Graph\nimport Smt.Solver\nimport Smt.Translator\nimport Smt.Util\nimport Smt.Tactic.EqnDef\n\nnamespace Smt.Query\n\nopen Lean Expr Meta\nopen Solver Term\n\n-- TODO: move all `Nat` hacks in this file to `Nat.lean`; see also issue #27\n\nstructure QueryBuilderM.Config where\n  /-- Expressions to define rather than just declare.\n  Definition bodies are translated recursively. -/\n  toDefine : List Expr := []\n\nstructure QueryBuilderM.State where\n  graph : Graph Expr Unit := .empty\n  commands : HashMap Expr Command := .empty\n\nabbrev QueryBuilderM := ReaderT QueryBuilderM.Config <| StateT QueryBuilderM.State TranslationM\n\nnamespace QueryBuilderM\n\ndef addCommand (e : Expr) (cmd : Command) : QueryBuilderM Unit :=\n  modify fun st => { st with\n    graph := st.graph.addVertex e\n    commands := st.commands.insert e cmd\n  }\n\ndef addDependency (e e' : Expr) : QueryBuilderM Unit :=\n  modify fun st => { st with\n    graph := st.graph.addEdge e e' ()\n  }\n\n/-- Translate an expression and compute its (non-SMT-builtin) dependencies.\nWhen `fvarDeps = false`, we filter out dependencies on fvars. -/\ndef translateAndFindDeps (e : Expr) (fvarDeps := true) : QueryBuilderM (Term \u00d7 Array Expr) := do\n  let (tm, deps) \u2190 Translator.translateExpr e\n  let unknownConsts := deps.toArray.filterMap fun nm =>\n    if Util.smtConsts.contains nm.toString then none else some (mkConst nm)\n  if fvarDeps then\n    let st : CollectFVars.State := {}\n    let st := collectFVars st e\n    let fvs := st.fvarIds.map mkFVar\n    return (tm, fvs ++ unknownConsts)\n  else\n    return (tm, unknownConsts)\n\n/-- Return the body of a constant using its unfold equation theorem. Unlike raw delta-reduction,\nthis hides encoding tricks used to prove termination.\n\nGiven an equation theorem of the form `\u2200 x\u2081 \u2b1d\u2b1d\u2b1d x\u2099, c x\u2081 \u2b1d\u2b1d\u2b1d x\u2099 = body`,\nwe return `fun x\u2081 \u2b1d\u2b1d\u2b1d x\u2099 => body`. -/\ndef getConstBodyFromEqnTheorem (nm : Name) : MetaM Expr := do\n  let some eqnThm \u2190 getUnfoldEqnFor? (nonRec := true) nm\n    | throwError \"failed to retrieve equation theorem for '{nm}'\"\n  let eqnInfo \u2190 getConstInfo eqnThm\n  forallTelescopeReducing eqnInfo.type fun args eqn => do\n    let some (_, _, e) := eqn.eq? | throwError \"unexpected equation theorem{indentD eqn}\"\n    mkLambdaFVars args e\n\n/-- Given the body `e` of a definition, make its application to `params` reducing *only* top-level\nlambdas. For example, if `def foo (a : Int) : Int \u2192 Int := (+) a`, then `e = fun a => (+) a` and\nsupposing `params = #[a, b]`, we return `(+) a b`. -/\ndef makeFullyAppliedBody (e : Expr) (params : Array Expr) : MetaM Expr := do\n  let numXs := countLams e\n  let e \u2190 instantiateLambda e (params.shrink numXs)\n  mkAppOptM' e (params.toList.drop numXs |>.map some |>.toArray)\nwhere\n  countLams : Expr \u2192 Nat\n    | lam _ _ t _ => 1 + countLams t\n    | _ => 0\n  \n/-- Given a local (`let`) or global (`const`) definition, translate its body applied to `params`.\nWe expect `params` to contain enough free variables to make this a ground term. For example, given\n`def foo (x : Int) : Int \u2192 Int := t`, we need `params = #[x, y]` and translate `t[x/x] y`.\nReturn the translated body, its dependencies, and whether the definition is recursive. -/\ndef translateDefinitionBody (params : Array Expr) : Expr \u2192 QueryBuilderM (Term \u00d7 Array Expr \u00d7 Bool)\n  | e@(fvar id ..) => do\n    let decl \u2190 id.getDecl\n    -- Look for an equational definition before defaulting to the let-body.\n    let val \u2190 getEqnDefLamFor? decl.userName\n    let some val := val <|> decl.value?\n      | throwError \"trying to define {e} but it has no equational definition and is not a let-decl\"\n    let val \u2190 makeFullyAppliedBody val params\n    let (tmVal, deps) \u2190 translateAndFindDeps val\n    return (tmVal, deps, val.hasAnyFVar (\u00b7 == id))\n  | const nm .. => do\n    let mutRecFuns := ConstantInfo.all (\u2190 getConstInfo nm)\n    -- TODO: Replace by `DefinitionVal.isRec` check when (if?) it gets added to Lean core.\n    if mutRecFuns.length > 1 then\n      -- TODO: support mutually recursive functions.\n      throwError \"{nm} is a mutually recursive function, not yet supported\"\n    -- Look for an equational definition before defaulting to Lean's equational theorem.\n    let val \u2190 match (\u2190 getEqnDefLamFor? nm) with\n    | some val => pure val\n    | none => getConstBodyFromEqnTheorem nm\n    let val \u2190 makeFullyAppliedBody val params\n    -- Note that we temporarily store `params` free variables as (incorrect) dependencies,\n    -- but they are filtered out later in `addCommandFor`.\n    let (tm, deps) \u2190 translateAndFindDeps val\n    return (tm, deps, Util.countConst val nm > 0)\n  | e           => throwError \"internal error, expected fvar or const but got{indentD e}\\nof kind {e.ctorName}\"\n\n/-- Assuming `e : Sort u` and `u` is constant, return `u`. Otherwise fail. -/\ndef getSortLevel (e : Expr) : QueryBuilderM Nat := do\n  let sort l .. \u2190 inferType e | throwError \"sort expected, got{indentD e}\"\n  let some l := l.toNat | throwError \"type{indentD e}\\nhas varying universe level {l}\"\n  return l\n\ndef addDefineCommandFor (nm : String) (e : Expr) (params : Array Expr) (cod : Expr)\n    : QueryBuilderM (Array Expr) := do\n  -- Translate the body and the parameter types.\n  let (tmVal, deps, isRec) \u2190 translateDefinitionBody params e\n  let (tmParams, deps) \u2190 params.foldrM (init := ([], deps)) fun param (tmParams, deps) => do\n    let n := (\u2190 getFVarLocalDecl param).userName.toString\n    let (tm, deps') \u2190 translateAndFindDeps (\u2190 inferType param)\n    return ((n, tm) :: tmParams, deps ++ deps')\n\n  -- Is `e` a type?\n  if 1 < (\u2190 getSortLevel cod) then\n    addCommand e <| .defineSort nm (tmParams.map (\u00b7.snd)) tmVal\n    return deps\n  else -- Otherwise it is a function or constant.\n    let (tmCod, deps') \u2190 translateAndFindDeps cod\n    addCommand e <| .defineFun nm tmParams tmCod tmVal isRec\n    return deps ++ deps'\n\ndef addDeclareCommandFor (nm : String) (e tp : Expr) (params : Array Expr) (cod : Expr)\n    : QueryBuilderM (Array Expr) := do\n  if 1 < (\u2190 getSortLevel cod) then\n    addCommand e <| .declareSort nm params.size\n    return #[]\n  else\n    let (tmTp, deps) \u2190 translateAndFindDeps tp\n    addCommand e <| .declare nm tmTp\n    return deps\n\n/-- Build the command for `e : tp` and add it to the graph. Return the command's dependencies. -/\ndef addCommandFor (e tp : Expr) : QueryBuilderM (Array Expr) := do\n  -- Is `tp` a `Prop` to assert?\n  if let 0 \u2190 getSortLevel tp then\n    let (tmTp, deps) \u2190 translateAndFindDeps tp\n    addCommand e <| .assert tmTp\n    return deps\n\n  trace[smt.debug.translate.query] \"{tp} : Sort {\u2190 getSortLevel tp}\"\n\n  -- Otherwise it is a local/global declaration with name `nm`.\n  let nm \u2190 match e with\n    | fvar id .. => pure (\u2190 id.getDecl).userName.toString\n    | const n .. => pure n.toString\n    | _          => throwError \"internal error, expected fvar or const but got{indentD e}\\nof kind {e.ctorName}\"\n\n  -- Introduce the declaration's parameters and codomain.\n  let deps \u2190 Meta.forallTelescopeReducing tp fun params cod => do\n    -- Should we define the body of `e`?\n    if (\u2190 read).toDefine.elem e then addDefineCommandFor nm e params cod\n    -- Otherwise we just declare it.\n    else addDeclareCommandFor nm e tp params cod\n\n  -- Filter out fvars introduced by the forall telescope. We cannot just ignore all fvars because\n  -- the definition might depend on local bindings which we then have to translate.\n  deps.filterM (fun | fvar id .. => Option.isSome <$> id.findDecl? | _ => pure true)\n\n/-- Build a graph of SMT-LIB commands to emit with dependencies between them as edges. -/\npartial def buildDependencyGraph (g : Expr) : QueryBuilderM Unit := do\n  go g\n  for h in (\u2190 read).toDefine do\n    go h\nwhere\n  go (e : Expr) : QueryBuilderM Unit := do\n    if (\u2190 get).graph.contains e then\n      return\n    if !(e.isConst \u2228 e.isFVar \u2228 e.isMVar) then\n      throwError \"failed to build graph, unexpected expression{indentD e}\\nof kind {e.ctorName}\"\n\n    let et \u2190 inferType e\n    let et \u2190 instantiateMVars et\n    trace[smt.debug.translate.query] \"processing {e} : {et}\"\n\n    -- HACK: `Nat` special cases\n    if e matches const `Nat .. then\n      addCommand e Command.defNat\n      return\n    if e matches const `Nat.sub .. then\n      addCommand e Command.defNatSub\n      go (mkConst `Nat)\n      addDependency e (mkConst `Nat)\n      return\n\n    let deps \u2190 addCommandFor e et\n\n    trace[smt.debug.translate.query] \"deps: {deps}\"\n    for e' in deps do\n      go e'\n      addDependency e e'\n\nend QueryBuilderM\n\ndef sortEndsWithNat : Term \u2192 Bool\n  | .arrowT _ t    => sortEndsWithNat t\n  | .symbolT \"Nat\" => true\n  | _              => false\n\ndef natAssertBody (t : Term) : Term :=\n  .mkApp2 (.symbolT \">=\") t (.literalT \"0\")\n\n/-- TODO: remove this hack once we have a tactic that replaces Nat goals with Int goals. -/\ndef natConstAssert (n : String) (args : List Name) : Term \u2192 MetaM Term\n  | arrowT i@(symbolT \"Nat\") t => do\n    let id \u2190 mkFreshId\n    return (forallT id.toString i\n                   (imp id.toString (\u2190 natConstAssert n (id::args) t)))\n  | arrowT a t => do\n    let id \u2190 mkFreshId\n    return (forallT id.toString a (\u2190 natConstAssert n (id::args) t))\n  | _ => pure $ natAssertBody (applyList n args)\n  where\n    imp n t := appT (appT (symbolT \"=>\") (natAssertBody (symbolT n))) t\n    applyList n : List Name \u2192 Term\n      | [] => symbolT n\n      | t :: ts => appT (applyList n ts) (symbolT t.toString)\n\n/-- TODO: Remove this function and its `Nat` those hacks. -/\ndef addCommand (cmd : Command) (cmds : List Command) : MetaM (List Command) := do\n  let mut cmds := cmds\n  cmds := cmd :: cmds\n  match cmd with\n  | .declare nm st =>\n    if sortEndsWithNat st then\n      let x \u2190 natConstAssert nm [] st\n      cmds := .assert x :: cmds\n  | .defineFun nm ps cod _ _ =>\n    if sortEndsWithNat cod then\n      let tmArrow := ps.foldr (init := cod) fun (_, tp) acc => arrowT tp acc\n      cmds := .assert (\u2190 natConstAssert nm [] tmArrow) :: cmds\n  | _ => pure ()\n  return cmds\n\ndef emitVertex (cmds : HashMap Expr Command) (e : Expr) : StateT (List Command) MetaM Unit := do\n  trace[smt.debug.translate.query] \"emitting {e}\"\n  let some cmd := cmds.find? e | throwError \"no command was computed for {e}\"\n  set (\u2190 addCommand cmd (\u2190 get))\n\ndef generateQuery (goal : Expr) (hs : List Expr) : MetaM (List Command) :=\n  withTraceNode `smt.debug.translate.query (fun _ => pure .nil) do\n    trace[smt.debug.translate.query] \"Goal: {\u2190 inferType goal}\"\n    trace[smt.debug.translate.query] \"Provided Hints: {hs}\"\n    let ((_, st), _) \u2190 QueryBuilderM.buildDependencyGraph goal\n      |>.run { toDefine := hs : QueryBuilderM.Config }\n      |>.run { : QueryBuilderM.State }\n      |>.run { : TranslationM.State }\n    trace[smt.debug.translate.query] \"Dependency Graph: {st.graph}\"\n    -- The type of the proof generated by a solver depends on the order of asserions. We assert the\n    -- Lean goal at the end of the query to simplify unification during proof reconstruction.\n    let (_, cmds) \u2190 StateT.run (st.graph.orderedDfs (hs ++ [goal]) (emitVertex st.commands)) []\n    return cmds\n\nend Smt.Query\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/Query.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584297, "lm_q2_score": 0.07921031541437025, "lm_q1q2_score": 0.03407210715613969}}
{"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek\n-/\nimport control.basic\nimport data.dlist.basic\nimport meta.expr\nimport system.io\nimport tactic.binder_matching\nimport tactic.interactive_expr\nimport tactic.lean_core_docs\nimport tactic.project_dir\n\nuniverse u\n\nattribute [derive [has_reflect, decidable_eq]] tactic.transparency\n\n-- Rather than import data.prod.lex here, we can get away with defining the order by hand.\ninstance : has_lt pos :=\n{ lt := \u03bb x y, x.line < y.line \u2228 x.line = y.line \u2227 x.column < y.column }\n\nnamespace tactic\n\n/-- Reflexivity conversion: given `e` returns `(e, \u22a2 e = e)` -/\nmeta def refl_conv (e : expr) : tactic (expr \u00d7 expr) :=\ndo p \u2190 mk_eq_refl e, return (e, p)\n\n/-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a\nproof by reflexivity. -/\nmeta def or_refl_conv (tac : expr \u2192 tactic (expr \u00d7 expr))\n  (e : expr) : tactic (expr \u00d7 expr) := tac e <|> refl_conv e\n\n/-- Transitivity conversion: given two conversions (which take an\nexpression `e` and returns `(e', \u22a2 e = e')`), produces another\nconversion that combines them with transitivity, treating failures\nas reflexivity conversions. -/\nmeta def trans_conv (t\u2081 t\u2082 : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) :\n  tactic (expr \u00d7 expr) :=\n(do (e\u2081, p\u2081) \u2190 t\u2081 e,\n  (do (e\u2082, p\u2082) \u2190 t\u2082 e\u2081,\n    p \u2190 mk_eq_trans p\u2081 p\u2082, return (e\u2082, p)) <|>\n  return (e\u2081, p\u2081)) <|> t\u2082 e\n\nend tactic\nopen tactic\n\nnamespace expr\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_nat \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`. -/\nprotected meta def of_nat (\u03b1 : expr) : \u2115 \u2192 tactic expr :=\nnat.binary_rec\n  (tactic.mk_mapp ``has_zero.zero [some \u03b1, none])\n  (\u03bb b n tac, if n = 0 then mk_mapp ``has_one.one [some \u03b1, none] else\n    do e \u2190 tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_int \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nprotected meta def of_int (\u03b1 : expr) : \u2124 \u2192 tactic expr\n| (n : \u2115) := expr.of_nat \u03b1 n\n| -[1+ n] := do\n  e \u2190 expr.of_nat \u03b1 (n+1),\n  tactic.mk_app ``has_neg.neg [e]\n\n/-- Convert a list of expressions to an expression denoting the list of those expressions. -/\nmeta def of_list (\u03b1 : expr) : list expr \u2192 tactic expr\n| [] := tactic.mk_app ``list.nil [\u03b1]\n| (x :: xs) := do\n  exs \u2190 of_list xs,\n  tactic.mk_app ``list.cons [\u03b1, x, exs]\n\n/-- Generates an expression of the form `\u2203(args), inner`. `args` is assumed to be a list of local\nconstants. When possible, `p \u2227 q` is used instead of `\u2203(_ : p), q`. -/\nmeta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=\nargs.mfoldr (\u03bbarg i:expr, do\n    t \u2190 infer_type arg,\n    sort l \u2190 infer_type t,\n    return $ if arg.occurs i \u2228 l \u2260 level.zero\n      then (const `Exists [l] : expr) t (i.lambdas [arg])\n      else (const `and [] : expr) t i)\n  inner\n\n/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/\nmeta def traverse {m : Type \u2192 Type u} [applicative m]\n  {elab elab' : bool} (f : expr elab \u2192 m (expr elab')) :\n  expr elab \u2192 m (expr elab')\n | (var v)  := pure $ var v\n | (sort l) := pure $ sort l\n | (const n ls) := pure $ const n ls\n | (mvar n n' e) := mvar n n' <$> f e\n | (local_const n n' bi e) := local_const n n' bi <$> f e\n | (app e\u2080 e\u2081) := app <$> f e\u2080 <*> f e\u2081\n | (lam n bi e\u2080 e\u2081) := lam n bi <$> f e\u2080 <*> f e\u2081\n | (pi n bi e\u2080 e\u2081) := pi n bi <$> f e\u2080 <*> f e\u2081\n | (elet n e\u2080 e\u2081 e\u2082) := elet n <$> f e\u2080 <*> f e\u2081 <*> f e\u2082\n | (macro mac es) := macro mac <$> list.traverse f es\n\n/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,\nwith initial value `a`. -/\nmeta def mfoldl {\u03b1 : Type} {m} [monad m] (f : \u03b1 \u2192 expr \u2192 m \u03b1) : \u03b1 \u2192 expr \u2192 m \u03b1\n| x e := prod.snd <$> (state_t.run (e.traverse $ \u03bb e',\n    (get >>= monad_lift \u2218 flip f e' >>= put) $> e') x : m _)\n\n/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`\nwith `new`. The occurrences of `old` in `e` are determined using keyed matching\nwith transparency `md`; see `kabstract` for details. If `unify` is true,\nwe may assign metavariables in `e` as we match subterms of `e` against `old`. -/\nmeta def kreplace (e old new : expr) (md := semireducible) (unify := tt)\n  : tactic expr := do\n  e \u2190 kabstract e old md unify,\n  pure $ e.instantiate_var new\n\nend expr\n\nnamespace name\n\n/--\n`pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm`\nor (recusively) in any declarations occurring in the value of `nm` with namespace `pre`.\nAuxiliary function for `name.contains_sorry`. -/\nmeta def contains_sorry_aux (pre : name) : name \u2192 tactic bool | nm := do\n  env \u2190 get_env,\n  decl \u2190 get_decl nm,\n  ff \u2190 return decl.value.contains_sorry | return tt,\n  (decl.value.list_names_with_prefix pre).mfold ff $\n    \u03bb n b, if b then return tt else n.contains_sorry_aux\n\n/-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or\n  in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`).\n  See also `expr.contains_sorry`. -/\nmeta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm\n\nend name\n\nnamespace interaction_monad\nopen result\n\nvariables {\u03c3 : Type} {\u03b1 : Type u}\n\n/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/\n-- Note that this is a generalization of `tactic.read` in core.\nmeta def get_state : interaction_monad \u03c3 \u03c3 :=\n\u03bb state, success state state\n\n/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/\n-- Note that this is a generalization of `tactic.write` in core.\nmeta def set_state (state : \u03c3) : interaction_monad \u03c3 unit :=\n\u03bb _, success () state\n\n/--\n`run_with_state state tac` applies `tac` to the given state `state` and returns the result,\nsubsequently restoring the original state.\nIf `tac` fails, then `run_with_state` does too.\n-/\nmeta def run_with_state (state : \u03c3) (tac : interaction_monad \u03c3 \u03b1) : interaction_monad \u03c3 \u03b1 :=\n\u03bb s, match tac state with\n     | success val _      := success val s\n     | exception fn pos _ := exception fn pos s\n     end\n\nend interaction_monad\n\nnamespace format\n\n/-- `join' [a,b,c]` produces the format object `abc`.\nIt differs from `format.join` by using `format.nil` instead of `\"\"` for the empty list. -/\nmeta def join' (xs : list format) : format :=\nxs.foldl compose nil\n\n/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,\nwhere `.` represents `format.join`. -/\nmeta def intercalate (x : format) : list format \u2192 format :=\njoin' \u2218 list.intersperse x\n\n/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`\nthe result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`\neach line break is decided independently -/\nmeta def soft_break : format :=\ngroup line\n\n/-- Format a list as a comma separated list, without any brackets. -/\nmeta def comma_separated {\u03b1 : Type*} [has_to_format \u03b1] : list \u03b1 \u2192 format\n| [] := nil\n| xs := group (nest 1 $ intercalate (\",\" ++ soft_break) $ xs.map to_fmt)\n\nend format\n\nsection format\nopen format\n\n/-- format a `list` by separating elements with `soft_break` instead of `line` -/\nmeta def list.to_line_wrap_format {\u03b1 : Type u} [has_to_format \u03b1] (l : list \u03b1) : format :=\nbracket \"[\" \"]\" (comma_separated l)\n\nend format\n\nnamespace tactic\nopen function\n\nexport interaction_monad (get_state set_state run_with_state)\n\n/-- Private work function for `add_local_consts_as_local_hyps`: given\n    `mappings : list (expr \u00d7 expr)` corresponding to pairs `(var, hyp)` of variables and the local\n    hypothesis created as a result and `(var :: rest) : list expr` of more local variables we\n    examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the\n    back of the queue and recurse. If it does not, then we perform replacements inside the type of\n    `var` using the `mappings`, create a new associate local hypothesis, add this to the list of\n    mappings, and recurse. We are done once all local hypotheses have been processed.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\nprivate meta def add_local_consts_as_local_hyps_aux\n  : list (expr \u00d7 expr) \u2192 list expr \u2192 tactic (list (expr \u00d7 expr))\n| mappings [] := return mappings\n| mappings (var :: rest) := do\n  /- Determine if `var` contains any local variables in the lift `rest`. -/\n  let is_dependent := var.local_type.fold ff $ \u03bb e n b,\n    if b then b else e \u2208 rest,\n\n  /- If so, then skip it---add it to the end of the variable queue. -/\n  if is_dependent then\n    add_local_consts_as_local_hyps_aux mappings (rest ++ [var])\n  else do\n    /- Otherwise, replace all of the local constants referenced by the type of `var` with the\n       respective new corresponding local hypotheses as recorded in the list `mappings`. -/\n    let new_type := var.local_type.replace_subexprs mappings,\n\n    /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/\n    hyp \u2190 assertv var.local_pp_name new_type (var.local_const_set_type new_type),\n\n    /- Process the next variable in the queue, with the mapping list updated to include the local\n       hypothesis which we just created. -/\n    add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest\n\n/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the\n    tactic state. This is harder than it sounds, since the list of local constants which we have\n    been passed can have dependencies between their types.\n\n    For example, suppose we have two local constants `n : \u2115` and `h : n = 3`. Then we cannot blindly\n    add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as\n    a new local hypothesis, not the old local constant `n` with the same name. Of course, these\n    dependencies can be nested arbitrarily deep.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\nmeta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr \u00d7 expr)) :=\n/- The `list.reverse` below is a performance optimisation since the list of available variables\n   reported by the system is often mostly the reverse of the order in which they are dependent. -/\nadd_local_consts_as_local_hyps_aux [] vars.reverse.dedup\n\nprivate meta def get_expl_pi_arity_aux : expr \u2192 tactic nat\n| (expr.pi n bi d b) :=\n  do m     \u2190 mk_fresh_name,\n     let l := expr.local_const m n bi d,\n     new_b \u2190 whnf (expr.instantiate_var b l),\n     r     \u2190 get_expl_pi_arity_aux new_b,\n     if bi = binder_info.default then\n       return (r + 1)\n     else\n       return r\n| e := return 0\n\n/-- Compute the arity of explicit arguments of `type`. -/\nmeta def get_expl_pi_arity (type : expr) : tactic nat :=\nwhnf type >>= get_expl_pi_arity_aux\n\n/-- Compute the arity of explicit arguments of `fn`'s type. -/\nmeta def get_expl_arity (fn : expr) : tactic nat :=\ninfer_type fn >>= get_expl_pi_arity\n\nprivate meta def get_app_fn_args_whnf_aux (md : transparency)\n  (unfold_ginductive : bool) : list expr \u2192 expr \u2192 tactic (expr \u00d7 list expr) :=\n\u03bb args e, do\n  e \u2190 whnf e md unfold_ginductive,\n  match e with\n  | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t\n  | _ := pure (e, args)\n  end\n\n/--\nFor `e = f x\u2081 ... x\u2099`, `get_app_fn_args_whnf e` returns `(f, [x\u2081, ..., x\u2099])`. `e`\nis normalised as necessary; for example:\n\n```\nget_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])\n```\n\nThe returned expression is in whnf, but the arguments are generally not.\n-/\nmeta def get_app_fn_args_whnf (e : expr) (md := semireducible)\n  (unfold_ginductive := tt) : tactic (expr \u00d7 list expr) :=\nget_app_fn_args_whnf_aux md unfold_ginductive [] e\n\n/--\n`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is\nnormalised as necessary (with transparency `md`). `unfold_ginductive` controls\nwhether constructors of generalised inductive types are unfolded. The returned\nexpression is in whnf.\n-/\nmeta def get_app_fn_whnf : expr \u2192 opt_param _ semireducible \u2192 opt_param _ tt \u2192 tactic expr\n| e md unfold_ginductive := do\n  e \u2190 whnf e md unfold_ginductive,\n  match e with\n  | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive\n  | _ := pure e\n  end\n\n/--\n`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x\u2081 ... x\u2099`,\nwhere `C` is a constant, after normalisation with transparency `md`. If so, the\nname of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded.\n-/\nmeta def get_app_fn_const_whnf (e : expr) (md := semireducible)\n  (unfold_ginductive := tt) : tactic name := do\n  f \u2190 get_app_fn_whnf e md unfold_ginductive,\n  match f with\n  | (expr.const n _) := pure n\n  | _ := fail format!\n    \"expected a constant (possibly applied to some arguments), but got:\\n{e}\"\n  end\n\n/--\n`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`\nis normalised as necessary (with transparency `md`). `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded. The\nreturned expressions are not necessarily in whnf.\n-/\nmeta def get_app_args_whnf (e : expr) (md := semireducible)\n  (unfold_ginductive := tt) : tactic (list expr) :=\nprod.snd <$> get_app_fn_args_whnf e md unfold_ginductive\n\n/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with pi binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``pis [a, b] `(f a b)`` will return the expression\n`\u03a0 (a : Ta) (b : Tb), f a b`. -/\nmeta def pis : list expr \u2192 expr \u2192 tactic expr\n| (e@(expr.local_const uniq pp info _) :: es) f := do\n  t \u2190 infer_type e,\n  f' \u2190 pis es f,\n  pure $ expr.pi pp info t (expr.abstract_local f' uniq)\n| _ f := pure f\n\n/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with lambda binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``lambdas [a, b] `(f a b)`` will return the expression\n`\u03bb (a : Ta) (b : Tb), f a b`. -/\nmeta def lambdas : list expr \u2192 expr \u2192 tactic expr\n| (e@(expr.local_const uniq pp info _) :: es) f := do\n  t \u2190 infer_type e,\n  f' \u2190 lambdas es f,\n  pure $ expr.lam pp info t (expr.abstract_local f' uniq)\n| _ f := pure f\n\n/--  Given an expression `f` (likely a binary operation) and a further expression `x`, calling\n`list_binary_operands f x` breaks `x` apart into successions of applications of `f` until this can\nno longer be done and returns a list of the leaves of the process.\n\nThis matches `f` up to semireducible unification. In particular, it will match applications of the\nsame polymorphic function with different type-class arguments.\n\nE.g., if `i1` and `i2` are both instances of `has_add T` and\n`e := has_add.add T i1 x (has_add.add T i2 y z)`, then ``list_binary_operands `((+) : T \u2192 T \u2192 T) e``\nreturns `[x, y, z]`.\n\nFor example:\n```lean\n#eval list_binary_operands `(@has_add.add \u2115 _) `(3 + (4 * 5 + 6) + 7 / 3) >>= tactic.trace\n-- [3, 4 * 5, 6, 7 / 3]\n#eval list_binary_operands `(@list.append \u2115) `([1, 2] ++ [3, 4] ++ (1 :: [])) >>= tactic.trace\n-- [[1, 2], [3, 4], [1]]\n```\n-/\nmeta def list_binary_operands (f : expr) : expr \u2192 tactic (list expr)\n| x@(expr.app (expr.app g a) b) := do\n  some _ \u2190 try_core (unify f g) | pure [x],\n  as \u2190 list_binary_operands a,\n  bs \u2190 list_binary_operands b,\n  pure (as ++ bs)\n| a                      := pure [a]\n\n-- TODO: move to `declaration` namespace in `meta/expr.lean`\n/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named\n`ls`, type `t`, and body `e`. -/\nmeta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=\ndeclaration.thm n ls t (task.pure e)\n\n/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this\nto the environment as a theorem with name `n` and universe parameters `ls`. -/\nmeta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :\n  tactic expr :=\ndo ((), body) \u2190 solve_aux type tac,\n   body \u2190 instantiate_mvars body,\n   add_decl $ mk_theorem n ls type body,\n   return $ expr.const n $ ls.map level.param\n\n/-- `eval_expr' \u03b1 e` attempts to evaluate the expression `e` in the type `\u03b1`.\nThis is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare\nsituations the latter will fail but the former will succeed. -/\nmeta def eval_expr' (\u03b1 : Type*) [reflected _ \u03b1] (e : expr) : tactic \u03b1 :=\nmk_app ``id [e] >>= eval_expr \u03b1\n\n/-- `mk_fresh_name` returns identifiers starting with underscores,\nwhich are not legal when emitted by tactic programs. `mk_user_fresh_name`\nturns the useful source of random names provided by `mk_fresh_name` into\nnames which are usable by tactic programs.\n\nThe returned name has four components which are all strings. -/\nmeta def mk_user_fresh_name : tactic name :=\ndo nm \u2190 mk_fresh_name,\n   return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__\n\n/-- `has_attribute' attr_name decl_name` checks\nwhether `decl_name` exists and has attribute `attr_name`. -/\nmeta def has_attribute' (attr_name decl_name : name) : tactic bool :=\nsucceeds (has_attribute attr_name decl_name)\n\n/-- Checks whether the name is a simp lemma -/\nmeta def is_simp_lemma : name \u2192 tactic bool :=\nhas_attribute' `simp\n\n/-- Checks whether the name is an instance. -/\nmeta def is_instance : name \u2192 tactic bool :=\nhas_attribute' `instance\n\n/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.\nCovers all declarations from the current file. -/\nmeta def local_decls : tactic (name_map declaration) :=\ndo e \u2190 tactic.get_env,\n   let xs := e.fold native.mk_rb_map\n     (\u03bb d s, if environment.in_current_file e d.to_name\n             then s.insert d.to_name d else s),\n   pure xs\n\n/-- `get_decls_from` returns a dictionary mapping names to their\ncorresponding declarations.  Covers all declarations the files listed\nin `fs`, with the current file listed as `none`.\n\nThe path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present); e.g. `\"src/tactic/core.lean\"`\n\nPossible issue: `get_decls_from` uses `get_cwd`, the current working\ndirectory, which may not always point at the root of the project.\nIt would work better if it searched for the root directory or,\nbetter yet, if Lean exposed its path information.\n-/\nmeta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=\ndo root \u2190 unsafe_run_io $ io.env.get_cwd,\n   let fs := fs.map (option.map $ \u03bb path, root ++ \"/\" ++ path),\n   err \u2190 unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot \u2218 io.fs.file_exists,\n   guard (err = []) <|> fail format!\"File not found: {err}\",\n   e \u2190 tactic.get_env,\n   let xs := e.fold native.mk_rb_map\n     (\u03bb d s,\n       let source := e.decl_olean d.to_name in\n       if source \u2208 fs \u2227 (source = none \u2192 e.in_current_file d.to_name)\n       then s.insert d.to_name d else s),\n   pure xs\n\n/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/\nmeta def get_unused_decl_name_aux (e : environment) (nm : name) : \u2115 \u2192 tactic name | n :=\nlet nm' := nm.append_suffix (\"_\" ++ to_string n) in\nif e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'\n\n/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it\nreturns that, otherwise it tries `nm_2`, `nm_3`, ... -/\nmeta def get_unused_decl_name (nm : name) : tactic name :=\nget_env >>= \u03bb e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm\n\n/--\nReturns a pair `(e, t)`, where `e \u2190 mk_const d.to_name`, and `t = d.type`\nbut with universe params updated to match the fresh universe metavariables in `e`.\n\nThis should have the same effect as just\n```lean\ndo e \u2190 mk_const d.to_name,\n   t \u2190 infer_type e,\n   return (e, t)\n```\nbut is hopefully faster.\n-/\nmeta def decl_mk_const (d : declaration) : tactic (expr \u00d7 expr) :=\ndo subst \u2190 d.univ_params.mmap $ \u03bb u, prod.mk u <$> mk_meta_univ,\n   let e : expr := expr.const d.to_name (prod.snd <$> subst),\n   return (e, d.type.instantiate_univ_params subst)\n\n/--\nReplace every universe metavariable in an expression with a universe parameter.\n\n(This is useful when making new declarations.)\n-/\nmeta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=\ndo\n  e.list_univ_meta_vars.enum.mmap (\u03bb n, do\n    let n' := (`u).append_suffix (\"_\" ++ to_string (n.1+1)),\n    unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),\n  instantiate_mvars e\n\n/-- `mk_local n` creates a dummy local variable with name `n`.\nThe type of this local constant is a constant with name `n`, so it is very unlikely to be\na meaningful expression. -/\nmeta def mk_local (n : name) : expr :=\nexpr.local_const n n binder_info.default (expr.const n [])\n\n/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,\n`y : ty x` and `z : tz x y`, creates an expression of sigma type:\n`\u27e8x,y,z\u27e9 : \u03a3' (x : tx) (y : ty x), tz x y`.\n-/\nmeta def mk_psigma : list expr \u2192 tactic expr\n| [] := mk_const ``punit\n| [x@(expr.local_const _ _ _ _)] := pure x\n| (x@(expr.local_const _ _ _ _) :: xs) :=\n  do y \u2190 mk_psigma xs,\n     \u03b1 \u2190 infer_type x,\n     \u03b2 \u2190 infer_type y,\n     t \u2190 lambdas [x] \u03b2 >>= instantiate_mvars,\n     r \u2190 mk_mapp ``psigma.mk [\u03b1,t],\n     pure $ r x y\n| _ := fail \"mk_psigma expects a list of local constants\"\n\n/--\nUpdate the type of a local constant or metavariable. For local constants and\nmetavariables obtained via, for example, `tactic.get_local`, the type stored in\nthe expression is not necessarily the same as the type returned by `infer_type`.\nThis tactic, given a local constant or metavariable, updates the stored type to\nmatch the output of `infer_type`. If the input is not a local constant or\nmetavariable, `update_type` does nothing.\n-/\nmeta def update_type : expr \u2192 tactic expr\n| e@(expr.local_const ppname uname binfo _) :=\n  expr.local_const ppname uname binfo <$> infer_type e\n| e@(expr.mvar ppname uname _) :=\n  expr.mvar ppname uname <$> infer_type e\n| e := pure e\n\n/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`\ntimes and uses `ns` to name the resulting variables. Returns a triple: list of new variables,\nremaining term and unused variable names.\n-/\nmeta def elim_gen_prod : nat \u2192 expr \u2192 list expr \u2192 list name \u2192 tactic (list expr \u00d7 expr \u00d7 list name)\n| 0       e hs ns := return (hs.reverse, e, ns)\n| (n + 1) e hs ns := do\n  t \u2190 infer_type e,\n  if t.is_app_of `eq then return (hs.reverse, e, ns)\n  else do\n    [(_, [h, h'], _)] \u2190 cases_core e (ns.take 1),\n    elim_gen_prod n h' (h :: hs) (ns.drop 1)\n\nprivate meta def elim_gen_sum_aux : nat \u2192 expr \u2192 list expr \u2192 tactic (list expr \u00d7 expr)\n| 0       e hs := return (hs, e)\n| (n + 1) e hs := do\n  [(_, [h], _), (_, [h'], _)] \u2190 induction e [],\n  swap,\n  elim_gen_sum_aux n h' (h::hs)\n\n/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose\ntype is a (nested) sum `\u2295`. Returns the list of local constants representing the components of `e`.\n-/\nmeta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do\n  (hs, h') \u2190 elim_gen_sum_aux n e [],\n  gs \u2190 get_goals,\n  set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),\n  return $ hs.reverse ++ [h']\n\n/-- Given `elab_def`, a tactic to solve the current goal,\n`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it\nto close the goal. If `trusted` is false, it will be a meta definition. -/\nmeta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=\ndo cxt \u2190 list.map expr.to_implicit_local_const <$> local_context,\n   t \u2190 target,\n   (eqns,d) \u2190 solve_aux t elab_def,\n   d \u2190 instantiate_mvars d,\n   t' \u2190 pis cxt t,\n   d' \u2190 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   applyc n\n\n/-- Attempts to close the goal with `dec_trivial`. -/\nmeta def exact_dec_trivial : tactic unit := `[exact dec_trivial]\n\n/-- Runs a tactic for a result, reverting the state after completion. -/\nmeta def retrieve {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s, result.cases_on (tac s)\n (\u03bb a s', result.success a s)\n result.exception\n\n/-- Runs a tactic for a result, reverting the state after completion or error. -/\nmeta def retrieve' {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s, result.cases_on (tac s)\n (\u03bb a s', result.success a s)\n (\u03bb msg pos s', result.exception msg pos s)\n\n/-- Repeat a tactic at least once, calling it recursively on all subgoals,\nuntil it fails. This tactic fails if the first invocation fails. -/\nmeta def repeat1 (t : tactic unit) : tactic unit := t; repeat t\n\n/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and\nat most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/\nmeta def iterate_range : \u2115 \u2192 \u2115 \u2192 tactic unit \u2192 tactic unit\n| 0 0     t := skip\n| 0 (n+1) t := try (t >> iterate_range 0 n t)\n| (m+1) n t := t >> iterate_range m (n-1) t\n\n/--\nGiven a tactic `tac` that takes an expression\nand returns a new expression and a proof of equality,\nuse that tactic to change the type of the hypotheses listed in `hs`,\nas well as the goal if `tgt = tt`.\n\nReturns `tt` if any types were successfully changed.\n-/\nmeta def replace_at (tac : expr \u2192 tactic (expr \u00d7 expr)) (hs : list expr) (tgt : bool) :\n  tactic bool :=\ndo to_remove \u2190 hs.mfilter $ \u03bb h, do\n  { h_type \u2190 infer_type h,\n    succeeds $ do\n      (new_h_type, pr) \u2190 tac h_type,\n      assert h.local_pp_name new_h_type,\n      mk_eq_mp pr h >>= tactic.exact },\n  goal_simplified \u2190 succeeds $ do\n  { guard tgt,\n    (new_t, pr) \u2190 target >>= tac,\n    replace_target new_t pr },\n  to_remove.mmap' (\u03bb h, try (clear h)),\n  return (\u00ac to_remove.empty \u2228 goal_simplified)\n\n/-- `revert_after e` reverts all local constants after local constant `e`. -/\nmeta def revert_after (e : expr) : tactic \u2115 := do\n  l \u2190 local_context,\n  [pos] \u2190 return $ l.indexes_of e | pp e >>= \u03bb s, fail format!\"No such local constant {s}\",\n  let l := l.drop pos.succ, -- all local hypotheses after `e`\n  revert_lst l\n\n/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).\n  Returns the number of local constants that have been reverted. -/\nmeta def revert_target_deps : tactic \u2115 :=\ndo tgt \u2190 target,\n   ctx \u2190 local_context,\n   l \u2190 ctx.mfilter (kdepends_on tgt),\n   n \u2190 revert_lst l,\n   if l = [] then return n\n     else do m \u2190 revert_target_deps, return (m + n)\n\n/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant\nwith name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.\n\n`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the\ngoal, in which case it just calls `assert`.\nIn contrast to `generalize` it already introduces the generalized variable. -/\nmeta def generalize' (e : expr) (n : name) : tactic expr :=\n(generalize e n >> intro n) <|> note n none e\n\n/--\n`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name\nprovided by the binder to name the new local constant.\nUnlike `intron`, it does not rename introduced constants if the names shadow existing constants.\n-/\nmeta def intron_no_renames : \u2115 \u2192 tactic unit\n| 0 := pure ()\n| (n+1) := do\n  expr.pi pp_n _ _ _ \u2190 target,\n  intro pp_n,\n  intron_no_renames n\n\n/-- `get_univ_level t` returns the universe level of a type `t` -/\nmeta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) :\n  tactic level :=\ndo expr.sort u \u2190 infer_type t >>= \u03bb s, whnf s md unfold_ginductive |\n    fail \"get_univ_level: argument is not a type\",\n   return u\n\n/-!\n### Various tactics related to local definitions (local constants of the form `x : \u03b1 := t`)\n\nWe call `t` the value of `x`.\n-/\n\n/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined\n  locally using a `let` expression. Otherwise it fails. -/\nmeta def local_def_value (e : expr) : tactic expr :=\npp e >>= \u03bb s, -- running `pp` here, because we cannot access it in the `type_context` monad.\ntactic.unsafe.type_context.run $ do\n  lctx <- tactic.unsafe.type_context.get_local_context,\n  some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |\n    tactic.unsafe.type_context.fail format!\"No such hypothesis {s}.\",\n  some let_val <- return ldecl.value |\n    tactic.unsafe.type_context.fail format!\"Variable {e} is not a local definition.\",\n  return let_val\n\n/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form\n`e : \u03b1 := t`) and otherwise fails. -/\nmeta def is_local_def (e : expr) : tactic unit := do\n  ctx \u2190 unsafe.type_context.get_local_context.run,\n  (some decl) \u2190 pure $ ctx.get_local_decl e.local_uniq_name |\n    fail format!\"is_local_def: {e} is not a local constant\",\n  when decl.value.is_none $ fail\n   format!\"is_local_def: {e} is not a local definition\"\n\n/-- Returns the local definitions from the context. A local definition is a\nlocal constant of the form `e : \u03b1 := t`. The local definitions are returned in\nthe order in which they appear in the context. -/\nmeta def local_defs : tactic (list expr) := do\n  ctx \u2190 unsafe.type_context.get_local_context.run,\n  ctx' \u2190 local_context,\n  ctx'.mfilter $ \u03bb h, do\n    (some decl) \u2190 pure $ ctx.get_local_decl h.local_uniq_name |\n      fail format!\"local_defs: local {h} not found in the local context\",\n    pure decl.value.is_some\n\n/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`\n(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.\nwhereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes\nthem in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition\nrunning up to the first match. -/\nprivate def partition_local_deps_aux {\u03b1} [decidable_eq \u03b1] (vs : list \u03b1) :\n  list \u03b1 \u2192 list \u03b1 \u2192 list (list \u03b1)\n| [] acc := [acc.reverse]\n| (l :: ls) acc :=\n  if l \u2208 vs then acc.reverse :: partition_local_deps_aux ls [l]\n  else partition_local_deps_aux ls (l :: acc)\n\n/-- `partition_local_deps vs`, with `vs` a list of local constants,\nreorders `vs` in the order they appear in the local context together\nwith the variables that follow them. If local context is `[a,b,c,d,e,f]`,\nand that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.\nThe head of each list is one of the variables given as a parameter. -/\nmeta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=\ndo ls \u2190 local_context,\n   pure (partition_local_deps_aux vs ls []).tail.reverse\n\n/-- `clear_value [e\u2080, e\u2081, e\u2082, ...]` clears the body of the local definitions `e\u2080`, `e\u2081`, `e\u2082`, ...\nchanging them into regular hypotheses. A hypothesis `e : \u03b1 := t` is changed to `e : \u03b1`. The order of\nlocals `e\u2080`, `e\u2081`, `e\u2082` does not matter as a permutation will be chosen so as to preserve type\ncorrectness. This tactic is called `clearbody` in Coq. -/\nmeta def clear_value (vs : list expr) : tactic unit := do\n  ls \u2190 partition_local_deps vs,\n  ls.mmap' $ \u03bb vs, do\n  { revert_lst vs,\n    (expr.elet v t d b) \u2190 target |\n      fail format!\"Cannot clear the body of {vs.head}. It is not a local definition.\",\n    let e := expr.pi v binder_info.default t b,\n    type_check e <|>\n      fail format!\"Cannot clear the body of {vs.head}. The resulting goal is not type correct.\",\n    g \u2190 mk_meta_var e,\n    h \u2190 note `h none g,\n    tactic.exact $ h d,\n    gs \u2190 get_goals,\n    set_goals $ g :: gs },\n  ls.reverse.mmap' $ \u03bb vs, intro_lst $ vs.map expr.local_pp_name\n\n/--\n`context_has_local_def` is true iff there is at least one local definition in\nthe context.\n-/\nmeta def context_has_local_def : tactic bool := do\n  ctx \u2190 local_context,\n  ctx.many (succeeds \u2218 local_def_value)\n\n/--\n`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the\ncontext up to and including `h` is a local definition.\n-/\nmeta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do\n  ff \u2190 succeeds (local_def_value h) | pure tt,\n  ctx \u2190 local_context,\n  let ctx := ctx.take_while (\u2260 h),\n  ctx.many (succeeds \u2218 local_def_value)\n\n/--\nIf the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\nIf `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and\nsubstitute `t` for `h`.\n\nThis is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a\nlocal definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nmeta def subst' (h : expr) : tactic unit := do\n  e \u2190 do { -- we first find the variable being substituted away\n    t \u2190 infer_type h,\n    let (f, args) := t.get_app_fn_args,\n    if (f.const_name = `eq \u2228 f.const_name = `heq) then do\n    { let lhs := args.inth 1,\n      let rhs := args.ilast,\n      if rhs.is_local_constant then return rhs else\n      if lhs.is_local_constant then return lhs else fail\n      \"subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x).\" }\n    else return h },\n  success_if_fail (is_local_def e) <|>\n    fail format!(\"Cannot substitute variable {e.local_pp_name}, \" ++\n      \"it is a local definition. If you really want to do this, use `clear_value` first.\"),\n  subst h\n\n/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,\n`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting\nexpression and a proof of equality. -/\nmeta def simp_bottom_up' (post : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) (cfg : simp_config := {}) :\n  tactic (expr \u00d7 expr) :=\nprod.snd <$> simplify_bottom_up () (\u03bb _, (<$>) (prod.mk ()) \u2218 post) e cfg\n\n/-- Caches unary type classes on a type `\u03b1 : Type.{univ}`. -/\nmeta structure instance_cache :=\n(\u03b1 : expr)\n(univ : level)\n(inst : name_map expr)\n\n/-- Creates an `instance_cache` for the type `\u03b1`. -/\nmeta def mk_instance_cache (\u03b1 : expr) : tactic instance_cache :=\ndo u \u2190 mk_meta_univ,\n   infer_type \u03b1 >>= unify (expr.sort (level.succ u)),\n   u \u2190 get_univ_assignment u,\n   return \u27e8\u03b1, u, mk_name_map\u27e9\n\nnamespace instance_cache\n\n/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of\n`n c.\u03b1` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance\nvia type class resolution, and updates the cache. -/\nmeta def get (c : instance_cache) (n : name) : tactic (instance_cache \u00d7 expr) :=\nmatch c.inst.find n with\n| some i := return (c, i)\n| none := do e \u2190 mk_app n [c.\u03b1] >>= mk_instance,\n  return (\u27e8c.\u03b1, c.univ, c.inst.insert n e\u27e9, e)\nend\n\nopen expr\n/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,\n`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/\nmeta def append_typeclasses : expr \u2192 instance_cache \u2192 list expr \u2192\n  tactic (instance_cache \u00d7 list expr)\n| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=\n  do (c, p) \u2190 c.get n, return (c, p :: l)\n| _ c l := return (c, l)\n\n/-- Creates the application `n c.\u03b1 p l`, where `p` is a type class instance found in the cache `c`.\n-/\nmeta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache \u00d7 expr) :=\ndo d \u2190 get_decl n,\n   (c, l) \u2190 append_typeclasses d.type.binding_body c l,\n   return (c, (expr.const n [c.univ]).mk_app (c.\u03b1 :: l))\n\n/-- `c.of_nat n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`. -/\nprotected meta def of_nat (c : instance_cache) (n : \u2115) : tactic (instance_cache \u00d7 expr) :=\nif n = 0 then c.mk_app ``has_zero.zero [] else do\n  (c, ai) \u2190 c.get ``has_add,\n  (c, oi) \u2190 c.get ``has_one,\n  (c, one) \u2190 c.mk_app ``has_one.one [],\n  return (c, n.binary_rec one $ \u03bb b n e,\n    if n = 0 then one else\n    cond b\n      ((expr.const ``bit1 [c.univ]).mk_app [c.\u03b1, oi, ai, e])\n      ((expr.const ``bit0 [c.univ]).mk_app [c.\u03b1, ai, e]))\n\n/-- `c.of_int n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nprotected meta def of_int (c : instance_cache) : \u2124 \u2192 tactic (instance_cache \u00d7 expr)\n| (n : \u2115) := c.of_nat n\n| -[1+ n] := do\n  (c, e) \u2190 c.of_nat (n+1),\n  c.mk_app ``has_neg.neg [e]\n\nend instance_cache\n\n/-- A variation on `assert` where a (possibly incomplete)\nproof of the assertion is provided as a parameter.\n\n``(h,gs) \u2190 local_proof `h p tac`` creates a local `h : p` and\nuse `tac` to (partially) construct a proof for it. `gs` is the\nlist of remaining goals in the proof of `h`.\n\nThe benefits over assert are:\n- unlike with ``h \u2190 assert `h p, tac`` , `h` cannot be used by `tac`;\n- when `tac` does not complete the proof of `h`, returning the list\n  of goals allows one to write a tactic using `h` and with the confidence\n  that a proof will not boil over to goals left over from the proof of `h`,\n  unlike what would be the case when using `tactic.swap`.\n-/\nmeta def local_proof (h : name) (p : expr) (tac\u2080 : tactic unit) :\n  tactic (expr \u00d7 list expr) :=\nfocus1 $\ndo h' \u2190 assert h p,\n   [g\u2080,g\u2081] \u2190 get_goals,\n   set_goals [g\u2080], tac\u2080,\n   gs \u2190 get_goals,\n   set_goals [g\u2081],\n   return (h', gs)\n\n/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/\nmeta def var_names : expr \u2192 list name\n| (expr.pi n _ _ b) := n :: var_names b\n| _ := []\n\n/-- When `struct_n` is the name of a structure type,\n`subobject_names struct_n` returns two lists of names `(instances, fields)`.\nThe names in `instances` are the projections from `struct_n` to the structures that it extends\n(assuming it was defined with `old_structure_cmd false`).\nThe names in `fields` are the standard fields of `struct_n`. -/\nmeta def subobject_names (struct_n : name) : tactic (list name \u00d7 list name) :=\ndo env \u2190 get_env,\n   c \u2190 match env.constructors_of struct_n with\n       | [c] := pure c\n       | [] :=\n         if env.is_inductive struct_n\n           then fail format!\"{struct_n} does not have constructors\"\n           else fail format!\"{struct_n} is not an inductive type\"\n       | _ := fail \"too many constructors\"\n       end,\n   vs  \u2190 var_names <$> (mk_const c >>= infer_type),\n   fields \u2190 env.structure_fields struct_n,\n   return $ fields.partition (\u03bb fn, \u2191(\"_\" ++ fn.to_string) \u2208 vs)\n\nprivate meta def expanded_field_list' : name \u2192 tactic (dlist $ name \u00d7 name) | struct_n :=\ndo (so,fs) \u2190 subobject_names struct_n,\n   ts \u2190 so.mmap (\u03bb n, do\n     (_, e) \u2190 mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,\n     expanded_field_list' $ e.get_app_fn.const_name),\n   return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)\nopen functor function\n\n/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure\nnamed `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name\nof the projection is `prefix.name`.\n\n`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/\nmeta def expanded_field_list (struct_n : name) : tactic (list $ name \u00d7 name) :=\ndlist.to_list <$> expanded_field_list' struct_n\n\n/--\nReturn a list of all type classes which can be instantiated\nfor the given expression.\n-/\nmeta def get_classes (e : expr) : tactic (list name) :=\nattribute.get_instances `class >>= list.mfilter (\u03bb n,\n  succeeds $ mk_app n [e] >>= mk_instance)\n\n/--\nFinds an instance of an implication `cond \u2192 tgt`.\nReturns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention\n`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,\nsince it has been \"proven\" by a metavariable.\n-/\nmeta def mk_conditional_instance (cond tgt : expr) : tactic (expr \u00d7 expr) := do\nf \u2190 mk_meta_var cond,\ne \u2190 assertv `c cond f, swap,\nreset_instance_cache,\ninst \u2190 mk_instance tgt,\nreturn (e, inst)\n\nopen nat\n\n/-- Create a list of `n` fresh metavariables. -/\nmeta def mk_mvar_list : \u2115 \u2192 tactic (list expr)\n| 0 := pure []\n| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n\n\n/-- Returns the only goal, or fails if there isn't just one goal. -/\nmeta def get_goal : tactic expr :=\ndo gs \u2190 get_goals,\n   match gs with\n   | [a] := return a\n   | []  := fail \"there are no goals\"\n   | _   := fail \"there are too many goals\"\n   end\n\n/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,\nor until it fails. Always succeeds. -/\nmeta def iterate_at_most_on_all_goals : nat \u2192 tactic unit \u2192 tactic unit\n| 0        tac := trace \"maximal iterations reached\"\n| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip\n\n/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first\ngoal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on\ncurrent goal. -/\nmeta def iterate_at_most_on_subgoals : nat \u2192 tactic unit \u2192 tactic unit\n| 0        tac := trace \"maximal iterations reached\"\n| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)\n\n/-- This makes sure that the execution of the tactic does not change the tactic state.\nThis can be helpful while using rewrite, apply, or expr munging.\nRemember to instantiate your metavariables before you're done! -/\nmeta def lock_tactic_state {\u03b1} (t : tactic \u03b1) : tactic \u03b1\n| s := match t s with\n       | result.success a s' := result.success a s\n       | result.exception msg pos s' := result.exception msg pos s\nend\n\n/--\n`apply_list l`, for `l : list (tactic expr)`,\ntries to apply one of the lemmas generated by the tactics in `l` to the first goal, and\nfail if none succeeds.\n-/\nmeta def apply_list_expr (opt : apply_cfg) : list (tactic expr) \u2192 tactic unit\n| []     := fail \"no matching rule\"\n| (h::t) := (do e \u2190 h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t\n\n/--\nGiven the name of a user attribute, produces a list of `tactic expr`s, each of which is the\napplication of `i_to_expr_for_apply` to a declaration with that attribute.\n-/\nmeta def resolve_attribute_expr_list (attr_name : name) : tactic (list (tactic expr)) := do\n  l \u2190 attribute.get_instances attr_name,\n  list.map i_to_expr_for_apply <$> list.reverse\n    <$> l.mmap (\u03bb n, do c \u2190 (mk_const n), return (pexpr.of_expr c))\n\n\n/--`apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given\nas names of attributes) and the tactic `assumption` on the first goal and the resulting subgoals,\niteratively, at most `n` times.\n\nUnlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies\na lemma from the list until it can't.\n -/\nmeta def apply_rules (args : list pexpr) (attrs : list name) (n : nat) (opt : apply_cfg) :\n  tactic unit := do\n  attr_exprs \u2190 lock_tactic_state $ attrs.mfoldl\n    (\u03bb l n, list.append l <$> resolve_attribute_expr_list n) [],\n  let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs,\n-- `args_exprs` is a list of `tactic expr`, rather than just `expr`, because these expressions will\n-- be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.\n   iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt args_exprs)\n\n/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local\ncontext, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.\nFails if there is nothing named `h` in the local context. -/\nmeta def replace (h : name) (p : pexpr) : tactic unit :=\ndo h' \u2190 get_local h,\n   p \u2190 to_expr p,\n   note h none p,\n   clear h'\n\n/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``\nor `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an\n`iff`, returns an expression with the `iff` converted to either the forwards or backwards\nimplication, as requested. -/\nmeta def mk_iff_mp_app (iffmp : name) : expr \u2192 (nat \u2192 expr) \u2192 option expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := some $ @expr.const tt iffmp [] a b (f 0)\n| _ f := none\n\n/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., A \u2192 B`. -/\nmeta def iff_mp_core (e ty: expr) : option expr :=\nmk_iff_mp_app `iff.mp ty (\u03bb_, e)\n\n/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., B \u2192 A`. -/\nmeta def iff_mpr_core (e ty: expr) : option expr :=\nmk_iff_mp_app `iff.mpr ty (\u03bb_, e)\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the forward implication. -/\nmeta def iff_mp (e : expr) : tactic expr :=\ndo t \u2190 infer_type e,\n   iff_mp_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the reverse implication. -/\nmeta def iff_mpr (e : expr) : tactic expr :=\ndo t \u2190 infer_type e,\n   iff_mpr_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/--\nAttempts to apply `e`, and if that fails, if `e` is an `iff`,\ntry applying both directions separately.\n-/\nmeta def apply_iff (e : expr) : tactic (list (name \u00d7 expr)) :=\nlet ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in\nap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)\n\n/--\nConfiguration options for `apply_any`:\n* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.\n* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.\n* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.\n-/\nmeta structure apply_any_opt extends apply_cfg :=\n(use_symmetry : bool := tt)\n(use_exfalso : bool := tt)\n\n/--\nThis is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,\nand evaluates these as thunks before trying to apply them.\n\nWe need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.\n-/\nmeta def apply_any_thunk\n  (lemmas : list (tactic expr))\n  (opt : apply_any_opt := {})\n  (tac : tactic unit := skip)\n  (on_success : expr \u2192 tactic unit := (\u03bb _, skip))\n  (on_failure : tactic unit := skip) : tactic unit :=\ndo\n  let modes := [skip]\n    ++ (if opt.use_symmetry then [symmetry] else [])\n    ++ (if opt.use_exfalso then [exfalso] else []),\n  modes.any_of (\u03bb m, do m,\n    lemmas.any_of (\u03bb H, H >>= (\u03bb e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>\n  (on_failure >> fail \"apply_any tactic failed; no lemma could be applied\")\n\n/--\n`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.\n\n`apply_any lemmas opt` allows control over how lemmas are applied.\n`opt` has fields:\n* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)\n* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)\n* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).\n\n`apply_any lemmas tac` calls the tactic `tac` after a successful application.\nDefaults to `skip`. This is used, for example, by `solve_by_elim` to arrange\nrecursive invocations of `apply_any`.\n-/\nmeta def apply_any\n  (lemmas : list expr)\n  (opt : apply_any_opt := {})\n  (tac : tactic unit := skip) : tactic unit :=\napply_any_thunk (lemmas.map pure) opt tac\n\n/-- Try to apply a hypothesis from the local context to the goal. -/\nmeta def apply_assumption : tactic unit :=\nlocal_context >>= apply_any\n\n/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails\nif this is not a definitional equality.\n\n`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`\nby reverting `h`, changing the goal, and reintroducing hypotheses. -/\nmeta def change_core (e : expr) : option expr \u2192 tactic unit\n| none     := tactic.change e\n| (some h) :=\n  do num_reverted : \u2115 \u2190 revert h,\n     expr.pi n bi d b \u2190 target,\n     tactic.change $ expr.pi n bi e b,\n     intron num_reverted\n\n/--\n`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,\nassuming `olde` and `newe` are defeq when elaborated.\n-/\nmeta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=\ndo h \u2190 get_local hyp,\n   tp \u2190 infer_type h,\n   olde \u2190 to_expr olde, newe \u2190 to_expr newe,\n   let repl_tp := tp.replace (\u03bb a n, if a = olde then some newe else none),\n   when (repl_tp \u2260 tp) $ change_core repl_tp (some h)\n\n/-- Returns a list of all metavariables in the current partial proof. This can differ from\nthe list of goals, since the goals can be manually edited. -/\nmeta def metavariables : tactic (list expr) :=\nexpr.list_meta_vars <$> result\n\n/--\n`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,\nand fail otherwise.\n-/\nmeta def sorry_if_contains_sorry : tactic unit :=\ndo\n  g \u2190 target,\n  guard g.contains_sorry <|> fail \"goal does not contain `sorry`\",\n  tactic.admit\n\n/-- Fail if the target contains a metavariable. -/\nmeta def no_mvars_in_target : tactic unit :=\nexpr.has_meta_var <$> target >>= guardb \u2218 bnot\n\n/-- Succeeds only if the current goal is a proposition. -/\nmeta def propositional_goal : tactic unit :=\ndo g :: _ \u2190 get_goals,\n   is_proof g >>= guardb\n\n/-- Succeeds only if we can construct an instance showing the\n  current goal is a subsingleton type. -/\nmeta def subsingleton_goal : tactic unit :=\ndo g :: _ \u2190 get_goals,\n   ty \u2190 infer_type g >>= instantiate_mvars,\n   to_expr ``(subsingleton %%ty) >>= mk_instance >> skip\n\n/--\nSucceeds only if the current goal is \"terminal\",\nin the sense that no other goals depend on it\n(except possibly through shared metavariables; see `independent_goal`).\n-/\nmeta def terminal_goal : tactic unit :=\npropositional_goal <|> subsingleton_goal <|>\ndo g\u2080 :: _ \u2190 get_goals,\n   mvars \u2190 (\u03bb L, list.erase L g\u2080) <$> metavariables,\n   mvars.mmap' $ \u03bb g, do\n     t \u2190 infer_type g >>= instantiate_mvars,\n     d \u2190 kdepends_on t g\u2080,\n     monad.whenb d $\n       pp t >>= \u03bb s, fail (\"The current goal is not terminal: \" ++ s.to_string ++ \" depends on it.\")\n\n/--\nSucceeds only if the current goal is \"independent\", in the sense\nthat no other goals depend on it, even through shared meta-variables.\n-/\nmeta def independent_goal : tactic unit :=\nno_mvars_in_target >> terminal_goal\n\n/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,\nit only unfolds reducible definitions, so it sometimes fails faster. -/\nmeta def triv' : tactic unit := do c \u2190 mk_const `trivial, exact c reducible\n\nvariable {\u03b1 : Type}\n\n/-- Apply a tactic as many times as possible, collecting the results in a list.\nFail if the tactic does not succeed at least once. -/\nmeta def iterate1 (t : tactic \u03b1) : tactic (list \u03b1) :=\ndo r \u2190 decorate_ex \"iterate1 failed: tactic did not succeed\" t,\n   L \u2190 iterate t,\n   return (r :: L)\n\n/--  A simple check: `check_target_changes tac` applies tactic `tac` and fails if the main target\nbefore applying the tactic `tac` unifies with one of the goals produced by the tactic itself.\nUseful to make sure that the tactic `tac` is actually making progress. -/\nmeta def check_target_changes (tac : tactic \u03b1) : tactic \u03b1 :=\nfocus1 $ do\n  t \u2190 target,\n  x \u2190 tac,\n  gs \u2190 get_goals >>= list.mmap infer_type,\n  (success_if_fail $ gs.mfirst $ unify t) <|> fail \"Goal did not change\",\n  pure x\n\n/-- Introduces one or more variables and returns the new local constants.\nFails if `intro` cannot be applied. -/\nmeta def intros1 : tactic (list expr) :=\niterate1 intro1\n\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nmeta def under_binders {\u03b1 : Type} (t : tactic \u03b1) : tactic \u03b1 :=\ndo\n  v \u2190 intros,\n  r \u2190 t,\n  revert_lst v,\n  return r\n\nnamespace interactive\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nmeta def under_binders (i : itactic) : itactic := tactic.under_binders i\nend interactive\n\n/-- `successes` invokes each tactic in turn, returning the list of successful results. -/\nmeta def successes (tactics : list (tactic \u03b1)) : tactic (list \u03b1) :=\nlist.filter_map id <$> monad.sequence (tactics.map (\u03bb t, try_core t))\n\n/--\nTry all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results,\nand reverting to the original `tactic_state`.\n-/\n-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.\nmeta def try_all {\u03b1 : Type} (tactics : list (tactic \u03b1)) : tactic (list \u03b1) :=\n\u03bb s, result.success\n(tactics.map $\n\u03bb t : tactic \u03b1,\n  match t s with\n  | result.success a s' := [a]\n  | _ := []\n  end).join s\n\n/--\nTry all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results sorted by\nthe value produced by a subsequent execution of the `sort_by` tactic,\nand reverting to the original `tactic_state`.\n-/\nmeta def try_all_sorted {\u03b1 : Type} (tactics : list (tactic \u03b1)) (sort_by : tactic \u2115 := num_goals) :\n  tactic (list (\u03b1 \u00d7 \u2115)) :=\n\u03bb s, result.success\n((tactics.map $\n\u03bb t : tactic \u03b1,\n  match (do a \u2190 t, n \u2190 sort_by, return (a, n)) s with\n  | result.success a s' := [a]\n  | _ := []\n  end).join.qsort (\u03bb p q : \u03b1 \u00d7 \u2115, p.2 < q.2)) s\n\n/-- Return target after instantiating metavars and whnf. -/\nprivate meta def target' : tactic expr :=\ntarget >>= instantiate_mvars >>= whnf\n\n/--\nJust like `split`, `fsplit` applies the constructor when the type of the target is\nan inductive data type with one constructor.\nHowever it does not reorder goals or invoke `auto_param` tactics.\n-/\n-- FIXME check if we can remove `auto_param := ff`\nmeta def fsplit : tactic unit :=\ndo [c] \u2190 target' >>= get_constructors_for |\n     fail \"fsplit tactic failed, target is not an inductive datatype with only one constructor\",\n   mk_const c >>= \u03bb e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip\n\nrun_cmd add_interactive [`fsplit]\n\nadd_tactic_doc\n{ name                     := \"fsplit\",\n  category                 := doc_category.tactic,\n  decl_names               := [`tactic.interactive.fsplit],\n  tags                     := [\"logic\", \"goal management\"] }\n\n/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`\nsucceeds, clears the old hypothesis. -/\nmeta def injections_and_clear : tactic unit :=\ndo l \u2190 local_context,\n   results \u2190 successes $ l.map $ \u03bb e, injection e >> clear e,\n   when (results.empty) (fail \"could not use `injection` then `clear` on any hypothesis\")\n\nrun_cmd add_interactive [`injections_and_clear]\n\nadd_tactic_doc\n{ name                     := \"injections_and_clear\",\n  category                 := doc_category.tactic,\n  decl_names               := [`tactic.interactive.injections_and_clear],\n  tags                     := [\"context management\"] }\n\n/-- Calls `cases` on every local hypothesis, succeeding if\nit succeeds on at least one hypothesis. -/\nmeta def case_bash : tactic unit :=\ndo l \u2190 local_context,\n   r \u2190 successes (l.reverse.map (\u03bb h, cases h >> skip)),\n   when (r.empty) failed\n\n/--\n`note_anon t v`, given a proof `v : t`,\nadds `h : t` to the current context, where the name `h` is fresh.\n\n`note_anon none v` will infer the type `t` from `v`.\n-/\n-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.\nmeta def note_anon (t : option expr) (v : expr) : tactic expr :=\ndo h \u2190 get_unused_name `h none,\n   note h t v\n\n/-- `find_local t` returns a local constant with type t, or fails if none exists. -/\nmeta def find_local (t : pexpr) : tactic expr :=\ndo t' \u2190 to_expr t,\n   (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>\n     fail format!\"No hypothesis found of the form: {t'}\"\n\n/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values\nof the previous local constants. `l` is a list of local constants and their values. -/\nmeta def dependent_pose_core (l : list (expr \u00d7 expr)) : tactic unit := do\n  let lc := l.map prod.fst,\n  let lm := l.map (\u03bb\u27e8l, v\u27e9, (l.local_uniq_name, v)),\n  old::other_goals \u2190 get_goals,\n  t \u2190 infer_type old,\n  new_goal \u2190 mk_meta_var (t.pis lc),\n  set_goals (old :: new_goal :: other_goals),\n  exact ((new_goal.mk_app lc).instantiate_locals lm),\n  return ()\n\n/--\nInstantiates metavariables that appear in the current goal.\n-/\nmeta def instantiate_mvars_in_target : tactic unit :=\ntarget >>= instantiate_mvars >>= change\n\n/--\nInstantiates metavariables in all goals.\n-/\nmeta def instantiate_mvars_in_goals : tactic unit :=\nall_goals' $ instantiate_mvars_in_target\n\n/-- Protect the declaration `n` -/\nmeta def mk_protected (n : name) : tactic unit :=\ndo env \u2190 get_env, set_env (env.mk_protected n)\n\nend tactic\n\nnamespace lean.parser\nopen tactic interaction_monad\n\n/-- A version of `lean.parser.many` that requires at least `n` items -/\nmeta def repeat_at_least {\u03b1 : Type} (p : lean.parser \u03b1) : \u2115 \u2192 lean.parser (list \u03b1)\n| 0 := many p\n| (n + 1) := list.cons <$> p <*> repeat_at_least n\n\n/-- A version of `lean.parser.sep_by` that allows trailing delimiters, but requires at least one\nitem. Like `lean.parser.sep_by`, as a result of the `lean.parser` monad not being pure, this is only\nwell-behaved if `p` and `s` are backtrackable; which in practice means they must not consume the\ninput when they do not have a match. -/\nmeta def sep_by_trailing {\u03b1 : Type} (s : lean.parser unit) (p : lean.parser \u03b1) :\n  lean.parser (list \u03b1) :=\ndo\n  fst \u2190 p,\n  some () \u2190 optional s | pure [fst],\n  some rest \u2190 optional sep_by_trailing | pure [fst],\n  pure (fst :: rest)\n\n/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the\ncurrent line. -/\nmeta def emit_command_here (str : string) : lean.parser string :=\ndo (_, left) \u2190 with_input command_like str,\n   return left\n\n/-- Inner recursion for `emit_code_here`. -/\nmeta def emit_code_here_aux : string \u2192 \u2115 \u2192 lean.parser unit\n| str slen := do\n  left \u2190 emit_command_here str,\n  let llen := left.length,\n  when (llen < slen \u2227 llen \u2260 0) (emit_code_here_aux left llen)\n\n/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in\nsource code. -/\nmeta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length\n\n/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the\ntop level, giving access to operations like `emit_code_here`. -/\n@[user_command]\nmeta def run_parser_cmd (_ : interactive.parse $ tk \"run_parser\") : lean.parser unit :=\ndo e \u2190 lean.parser.pexpr 0,\n  p \u2190 eval_pexpr (lean.parser unit) e,\n  p\n\nadd_tactic_doc\n{ name       := \"run_parser\",\n  category   := doc_category.cmd,\n  decl_names := [``run_parser_cmd],\n  tags       := [\"parsing\"] }\n\n/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).\n\nThis function deserves a C++ implementation in core lean, and will fail if it is not called from\nthe body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/\nmeta def get_current_namespace : lean.parser name :=\ndo env \u2190 get_env,\n   n \u2190 tactic.mk_user_fresh_name,\n   emit_code_here $ sformat!\"def {n} := ()\",\n   nfull \u2190 tactic.resolve_constant n,\n   set_env env,\n   return $ nfull.get_nth_prefix n.components.length\n\n/-- `get_variables` returns a list of existing variable names, along with their types and binder\ninfo. -/\nmeta def get_variables : lean.parser (list (name \u00d7 binder_info \u00d7 expr)) :=\nlist.map expr.get_local_const_kind <$> list_available_include_vars\n\n/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been\n\"included\" by an `include v` statement and are not (yet) `omit`ed. -/\nmeta def get_included_variables : lean.parser (list (name \u00d7 binder_info \u00d7 expr)) :=\ndo ns \u2190 list_include_var_names,\n   list.filter (\u03bb v, v.1 \u2208 ns) <$> get_variables\n\n/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local\nvariables referenced in `es : list pexpr`, and those variables which have been `include`ed in the\nlocal context---precisely those variables which would be ambiently accessible if we were in a\ntactic-mode block where the goals had types `es.mmap to_expr`, for example.\n\nReturns a new `ts : tactic_state` with these local variables added, and\n`mappings : list (expr \u00d7 expr)`, for which pairs `(var, hyp)` correspond to an existing variable\n`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/\nmeta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)\n  : lean.parser (tactic_state \u00d7 list (expr \u00d7 expr)) :=\ndo /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the\n      declared variables to a fake `tactic_state`, and perform the resolution. At the end,\n      `to_expr e` has done the work of determining which variables were actually referenced, which\n      we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for\n      `pexpr`s). -/\n   vars \u2190 list_available_include_vars,\n   fake_es \u2190 lean.parser.of_tactic $ lock_tactic_state $ do\n   { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard\n        them on this first pass. (We return the mappings generated by our second invocation of this\n        function below.) -/\n     add_local_consts_as_local_hyps vars,\n     es.mmap to_expr },\n\n   /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were\n      referenced in `e` when it was resolved to `fake_e`.\n\n      It is important that we include variables of the kind a) because we want `simp` to have access\n      to declared local instances, and it is important that we only restrict to variables of kind a)\n      and b) together since we do not to recognise a hypothesis which is posited as a `variable`\n      in the environment but not referenced in the `pexpr` we were passed.\n\n      One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want\n      simp to use arbitrary hypotheses which were declared as `variables` in the local environment\n      but not referenced in the expression to simplify (as one would be expect generally in tactic\n      mode). -/\n   included_vars \u2190 list_include_var_names,\n   let referenced_vars := list.join $ fake_es.map $ \u03bb e, e.list_local_consts.map expr.local_pp_name,\n\n   /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the\n      `pexpr` list which we were passed.)  -/\n   let directly_included_vars := vars.filter $ \u03bb var,\n     (var.local_pp_name \u2208 included_vars) \u2228 (var.local_pp_name \u2208 referenced_vars),\n\n   /- Inflate the list `directly_included_vars` to include those variables which are \"implicitly\n      included\" by virtue of reference to one or multiple others. For example, given\n      `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass\n      instance `prime n` should be included, but `ih : even n` should not. -/\n   let all_implicitly_included_vars :=\n     expr.all_implicitly_included_variables vars directly_included_vars,\n\n   /- Capture a tactic state where both of these kinds of variables have been added as local\n      hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/\n   lean.parser.of_tactic $ do\n    { mappings \u2190 add_local_consts_as_local_hyps all_implicitly_included_vars,\n      ts \u2190 get_state,\n      return (ts, mappings) }\n\nend lean.parser\n\nnamespace tactic\n\nvariables {\u03b1 : Type}\n\n/--\nHole command used to fill in a structure's field when specifying an instance.\n\nIn the following:\n\n```lean\ninstance : monad id :=\n{! !}\n```\n\ninvoking the hole command \"Instance Stub\" (\"Generate a skeleton for the structure under\nconstruction.\") produces:\n\n```lean\ninstance : monad id :=\n{ map := _,\n  map_const := _,\n  pure := _,\n  seq := _,\n  seq_left := _,\n  seq_right := _,\n  bind := _ }\n```\n-/\n@[hole_command] meta def instance_stub : hole_command :=\n{ name := \"Instance Stub\",\n  descr := \"Generate a skeleton for the structure under construction.\",\n  action := \u03bb _,\n  do tgt \u2190 target >>= whnf,\n     let cl := tgt.get_app_fn.const_name,\n     env \u2190 get_env,\n     fs \u2190 expanded_field_list cl,\n     let fs := fs.map prod.snd,\n     let fs := format.intercalate (\",\\n  \" : format) $ fs.map (\u03bb fn, format!\"{fn} := _\"),\n     let out := format.to_string format!\"{{ {fs} }}\",\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"instance_stub\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.instance_stub],\n  tags                     := [\"instances\"] }\n\n/-- Like `resolve_name` except when the list of goals is\nempty. In that situation `resolve_name` fails whereas\n`resolve_name'` simply proceeds on a dummy goal -/\nmeta def resolve_name' (n : name) : tactic pexpr :=\ndo [] \u2190 get_goals | resolve_name n,\n   g \u2190 mk_mvar,\n   set_goals [g],\n   resolve_name n <* set_goals []\n\nprivate meta def strip_prefix' (n : name) : list string \u2192 name \u2192 tactic name\n| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous\n| s (name.mk_string a p) :=\n  do let n' := s.foldl (flip name.mk_string) name.anonymous,\n     do { n'' \u2190 tactic.resolve_constant n',\n          if n'' = n\n            then pure n'\n            else strip_prefix' (a :: s) p }\n     <|> strip_prefix' (a :: s) p\n| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n\n\n/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/\nmeta def strip_prefix : name \u2192 tactic name\n| n@(name.mk_string a a_1) :=\n  if (`_private).is_prefix_of n\n    then let n' := n.update_prefix name.anonymous in\n            n' <$ resolve_name' n' <|> pure n\n    else strip_prefix' n [a] a_1\n| n := pure n\n\n/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/\nmeta def mk_patterns (t : expr) : tactic (list format) :=\ndo let cl := t.get_app_fn.const_name,\n   env \u2190 get_env,\n   let fs := env.constructors_of cl,\n   fs.mmap $ \u03bb f,\n     do { (vs,_) \u2190 mk_const f >>= infer_type >>= open_pis,\n          let vs := vs.filter (\u03bb v, v.is_default_local),\n          vs \u2190 vs.mmap (\u03bb v,\n            do v' \u2190 get_unused_name v.local_pp_name,\n               pose v' none `(()),\n               pure v' ),\n          vs.mmap' $ \u03bb v, get_local v >>= clear,\n          let args := list.intersperse (\" \" : format) $ vs.map to_fmt,\n          f \u2190 strip_prefix f,\n          if args.empty\n            then pure $ format!\"| {f} := _\\n\"\n            else pure format!\"| ({f} {format.join args}) := _\\n\" }\n\n/--\nHole command used to generate a `match` expression.\n\nIn the following:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\n{! e !}\n```\n\ninvoking hole command \"Match Stub\" (\"Generate a list of equations for a `match` expression\")\nproduces:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\nmatch e with\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\nend\n```\n-/\n@[hole_command] meta def match_stub : hole_command :=\n{ name := \"Match Stub\",\n  descr := \"Generate a list of equations for a `match` expression.\",\n  action := \u03bb es,\n  do [e] \u2190 pure es | fail \"expecting one expression\",\n     e \u2190 to_expr e,\n     t \u2190 infer_type e >>= whnf,\n     fs \u2190 mk_patterns t,\n     e \u2190 pp e,\n     let out := format.to_string format!\"match {e} with\\n{format.join fs}end\\n\",\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"Match Stub\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.match_stub],\n  tags                     := [\"pattern matching\"] }\n\n/--\nInvoking hole command \"Equations Stub\" (\"Generate a list of equations for a recursive definition\")\nin the following:\n\n```lean\nmeta def foo : {! expr \u2192 tactic unit !} -- `:=` is omitted\n```\n\nproduces:\n\n```lean\nmeta def foo : expr \u2192 tactic unit\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\nA similar result can be obtained by invoking \"Equations Stub\" on the following:\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- do not forget to write `:=`!!\n{! !}\n```\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- don't forget to erase `:=`!!\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\n-/\n@[hole_command] meta def eqn_stub : hole_command :=\n{ name := \"Equations Stub\",\n  descr := \"Generate a list of equations for a recursive definition.\",\n  action := \u03bb es,\n  do t \u2190 match es with\n         | [t] := to_expr t\n         | [] := target\n         | _ := fail \"expecting one type\"\n         end,\n     e \u2190 whnf t,\n     (v :: _,_) \u2190 open_pis e | fail \"expecting a Pi-type\",\n     t' \u2190 infer_type v,\n     fs \u2190 mk_patterns t',\n     t \u2190 pp t,\n     let out :=\n         if es.empty then\n           format.to_string format!\"-- do not forget to erase `:=`!!\\n{format.join fs}\"\n           else format.to_string format!\"{t}\\n{format.join fs}\",\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"Equations Stub\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.eqn_stub],\n  tags                     := [\"pattern matching\"] }\n\n/--\nThis command lists the constructors that can be used to satisfy the expected type.\n\nInvoking \"List Constructors\" (\"Show the list of constructors of the expected type\")\nin the following hole:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! !}\n```\n\nproduces:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! sum.inl, sum.inr !}\n```\n\nand will display:\n\n```lean\nsum.inl : \u2124 \u2192 \u2124 \u2295 \u2115\n\nsum.inr : \u2115 \u2192 \u2124 \u2295 \u2115\n```\n\n-/\n@[hole_command] meta def list_constructors_hole : hole_command :=\n{ name := \"List Constructors\",\n  descr := \"Show the list of constructors of the expected type.\",\n  action := \u03bb es,\n  do t \u2190 target >>= whnf,\n     (_,t) \u2190 open_pis t,\n     let cl := t.get_app_fn.const_name,\n     let args := t.get_app_args,\n     env \u2190 get_env,\n     let cs := env.constructors_of cl,\n     ts \u2190 cs.mmap $ \u03bb c,\n       do { e \u2190 mk_const c,\n            t \u2190 infer_type (e.mk_app args) >>= pp,\n            c \u2190 strip_prefix c,\n            pure format!\"\\n{c} : {t}\\n\" },\n     fs \u2190 format.intercalate \", \" <$> cs.mmap (strip_prefix >=> pure \u2218 to_fmt),\n     let out := format.to_string format!\"{{! {fs} !}}\",\n     trace (format.join ts).to_string,\n     return [(out,\"\")] }\n\nadd_tactic_doc\n{ name                     := \"List Constructors\",\n  category                 := doc_category.hole_cmd,\n  decl_names               := [`tactic.list_constructors_hole],\n  tags                     := [\"goal information\"] }\n\n/-- Makes the declaration `classical.prop_decidable` available to type class inference.\nThis asserts that all propositions are decidable, but does not have computational content.\n\nThe `aggressive` argument controls whether the instance is added globally, where it has low\npriority, or in the local context, where it has very high priority. -/\nmeta def classical (aggressive : bool := ff) : tactic unit :=\nif aggressive then do\n  h \u2190 get_unused_name `_inst,\n  mk_const `classical.prop_decidable >>= note h none,\n  reset_instance_cache\nelse do\n  -- Turn on the `prop_decidable` instance. `9` is what we use in the `classical` locale\n  tactic.set_basic_attribute `instance `classical.prop_decidable ff (some 9)\n\nopen expr\n\n/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,\nreturns the expression `f \u2218 g \u2218 h`. -/\nmeta def mk_comp (v : expr) : expr \u2192 tactic expr\n| (app f e) :=\n  if e = v then pure f\n  else do\n    guard (\u00ac v.occurs f) <|> fail \"bad guard\",\n    e' \u2190 mk_comp e >>= instantiate_mvars,\n    f \u2190 instantiate_mvars f,\n    mk_mapp ``function.comp [none,none,none,f,e']\n| e :=\n  do guard (e = v),\n     t \u2190 infer_type e,\n     mk_mapp ``id [t]\n\n/-- Given two expressions `e\u2080` and `e\u2081`, return the expression `` `(%%e\u2080 \u2194 %%e\u2081)``. -/\nmeta def mk_iff (e\u2080 : expr) (e\u2081 : expr) : expr := `(%%e\u2080 \u2194 %%e\u2081)\n\n/--\nFrom a lemma of the shape `\u2200 x, f (g x) = h x`\nderive an auxiliary lemma of the form `f \u2218 g = h`\nfor reasoning about higher-order functions.\n-/\nmeta def mk_higher_order_type : expr \u2192 tactic expr\n| (pi n bi d b@(pi _ _ _ _)) :=\n  do v \u2190 mk_local_def n d,\n     let b' := (b.instantiate_var v),\n     (pi n bi d \u2218 flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'\n| (pi n bi d b) :=\n  do v \u2190 mk_local_def n d,\n     let b' := (b.instantiate_var v),\n     (l,r) \u2190 match_eq b' <|> fail format!\"not an equality {b'}\",\n     l' \u2190 mk_comp v l,\n     r' \u2190 mk_comp v r,\n     mk_app ``eq [l',r']\n | e := failed\n\nopen lean.parser interactive.types\n\n/-- A user attribute that applies to lemmas of the shape `\u2200 x, f (g x) = h x`.\nIt derives an auxiliary lemma of the form `f \u2218 g = h` for reasoning about higher-order functions.\n-/\n@[user_attribute]\nmeta def higher_order_attr : user_attribute unit (option name) :=\n{ name := `higher_order,\n  parser := optional ident,\n  descr :=\n\"From a lemma of the shape `\u2200 x, f (g x) = h x` derive an auxiliary lemma of the\nform `f \u2218 g = h` for reasoning about higher-order functions.\",\n  after_set := some $ \u03bb lmm _ _,\n    do env  \u2190 get_env,\n       decl \u2190 env.get lmm,\n       let num := decl.univ_params.length,\n       let lvls := (list.iota num).map (`l).append_after,\n       let l : expr := expr.const lmm $ lvls.map level.param,\n       t \u2190 infer_type l >>= instantiate_mvars,\n       t' \u2190 mk_higher_order_type t,\n       (_,pr) \u2190 solve_aux t' $ do\n       { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },\n       pr \u2190 instantiate_mvars pr,\n       lmm' \u2190 higher_order_attr.get_param lmm,\n       lmm' \u2190 (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,\n       add_decl $ declaration.thm lmm' lvls t' (pure pr),\n       copy_attribute `simp lmm lmm',\n       copy_attribute `functor_norm lmm lmm' }\n\nadd_tactic_doc\n{ name                     := \"higher_order\",\n  category                 := doc_category.attr,\n  decl_names               := [`tactic.higher_order_attr],\n  tags                     := [\"lemma derivation\"] }\n\nattribute [higher_order map_comp_pure] map_pure\n\n/--\nCopies a definition into the `tactic.interactive` namespace to make it usable\nin proof scripts. It allows one to write\n\n```lean\n@[interactive]\nmeta def my_tactic := ...\n```\n\ninstead of\n\n```lean\nmeta def my_tactic := ...\n\nrun_cmd add_interactive [``my_tactic]\n```\n-/\n@[user_attribute]\nmeta def interactive_attr : user_attribute :=\n{ name := `interactive,\n  descr :=\n\"Put a definition in the `tactic.interactive` namespace to make it usable\nin proof scripts.\",\n  after_set := some $ \u03bb tac _ _, add_interactive [tac] }\n\nadd_tactic_doc\n{ name                     := \"interactive\",\n  category                 := doc_category.attr,\n  decl_names               := [``tactic.interactive_attr],\n  tags                     := [\"environment\"] }\n\n/--\nUse `refine` to partially discharge the goal,\nor call `fconstructor` and try again.\n-/\nprivate meta def use_aux (h : pexpr) : tactic unit :=\n(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)\n\n/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations\nat the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to\nthe expected type.\n\n```lean\nexample : \u2203 x : \u2124, x = x :=\nby tactic.use ``(42)\n```\n\nSee the doc string for `tactic.interactive.use` for more information.\n -/\nprotected meta def use (l : list pexpr) : tactic unit :=\nfocus1 $ seq' (l.mmap' $ \u03bb h, use_aux h <|> fail format!\"failed to instantiate goal with {h}\")\n              instantiate_mvars_in_target\n\n/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the\nlocal context. -/\nmeta def clear_aux_decl_aux : list expr \u2192 tactic unit\n| []     := skip\n| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l\n\n/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/\nmeta def clear_aux_decl : tactic unit :=\nlocal_context >>= clear_aux_decl_aux\n\n/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)\nfinds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/\nmeta def apply_at_aux (arg t : expr) : list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr)\n| vs e (pi n bi d b) :=\n  do { v \u2190 mk_meta_var d,\n       apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>\n  (e arg, vs) <$ unify d t\n| vs e _ := failed\n\n/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/\nmeta def apply_at (e h : expr) : tactic unit :=\ndo ht \u2190 infer_type h,\n   et \u2190 infer_type e,\n   (h', gs') \u2190 apply_at_aux h ht [] e et,\n   note h.local_pp_name none h',\n   clear h,\n   gs' \u2190 gs'.mfilter is_assigned,\n   (g :: gs) \u2190 get_goals,\n   set_goals (g :: gs' ++ gs)\n\n/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/\nmeta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=\ndo tgt   \u2190 infer_type h,\n   env   \u2190 get_env,\n   let r := get_app_fn tgt,\n   match env.symm_for (const_name r) with\n   | (some symm) := do s \u2190 mk_const symm,\n                       apply_at s h\n   | none        := fail\n      \"symmetry tactic failed, target is not a relation application with the expected property.\"\n   end\n\n/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing\ninteractive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.\nIt does *not* use the `namespace` command, so it will typically be used after\n`namespace tactic.interactive`.\n-/\n@[user_command]\nmeta def setup_tactic_parser_cmd (_ : interactive.parse $ tk \"setup_tactic_parser\") :\n  lean.parser unit :=\nemit_code_here \"\nopen _root_.lean\nopen _root_.lean.parser\nopen _root_.interactive _root_.interactive.types\n\nlocal postfix (name := parser.optional) `?`:9001 := optional\nlocal postfix (name := parser.many) *:9001 := many .\n\"\n\n/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if\n`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/\nmeta def finally {\u03b2} (tac : tactic \u03b1) (finalizer : tactic \u03b2) : tactic \u03b1 :=\n\u03bb s, match tac s with\n     | (result.success r s') := (finalizer >> pure r) s'\n     | (result.exception msg p s') := (finalizer >> result.exception msg p) s'\n     end\n\n/--\n`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.\n-/\nmeta def on_exception {\u03b2} (handler : tactic \u03b2) (tac : tactic \u03b1) : tactic \u03b1 | s :=\nmatch tac s with\n| result.exception msg p s' := (handler *> result.exception msg p) s'\n| ok := ok\nend\n\n/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/\nmeta def decorate_error (add_msg : string) (tac : tactic \u03b1) : tactic \u03b1 | s :=\nmatch tac s with\n| result.exception msg p s :=\n  let msg (_ : unit) : format := match msg with\n    | some msg := add_msg ++ format.line ++ msg ()\n    | none := add_msg\n    end in\n  result.exception msg p s\n| ok := ok\nend\n\n/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,\n  returns the error message. -/\nmeta def retrieve_or_report_error {\u03b1 : Type u} (t : tactic \u03b1) : tactic (\u03b1 \u2295 string) :=\n\u03bb s, match t s with\n| (interaction_monad.result.success a s') := result.success (sum.inl a) s\n| (interaction_monad.result.exception msg' _ s') :=\n  result.success (sum.inr (msg'.iget ()).to_string) s\nend\n\n/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/\nmeta def try_or_report_error {\u03b1 : Type u} (t : tactic \u03b1) : tactic (\u03b1 \u2295 string) :=\n\u03bb s, match t s with\n| (interaction_monad.result.success a s') := result.success (sum.inl a) s'\n| (interaction_monad.result.exception msg' _ s') :=\n  result.success (sum.inr (msg'.iget ()).to_string) s\nend\n\n/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.\n-/\nmeta def succeeds_or_fails_with_msg {\u03b1 : Type} (t : tactic \u03b1) (p : string \u2192 bool) : tactic unit :=\ndo x \u2190 retrieve_or_report_error t,\nmatch x with\n| (sum.inl _) := skip\n| (sum.inr msg) := if p msg then skip else fail msg\nend\n\nadd_tactic_doc\n{ name                     := \"setup_tactic_parser\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.setup_tactic_parser_cmd],\n  tags                     := [\"parsing\", \"notation\"] }\n\n/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message\nof `t`. -/\nmeta def trace_error (msg : string) (t : tactic \u03b1) : tactic \u03b1\n| s := match t s with\n       | (result.success r s') := result.success r s'\n       | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception\n            (some msg') p) s'\n       | (result.exception none p s') := result.exception none p s'\n       end\n\n/--\n``trace_if_enabled `n msg`` traces the message `msg`\nonly if tracing is enabled for the name `n`.\n\nCreate new names registered for tracing with `declare_trace n`.\nThen use `set_option trace.n true/false` to enable or disable tracing for `n`.\n-/\nmeta def trace_if_enabled\n  (n : name) {\u03b1 : Type u} [has_to_tactic_format \u03b1] (msg : \u03b1) : tactic unit :=\nwhen_tracing n (trace msg)\n\n/--\n``trace_state_if_enabled `n msg`` prints the tactic state,\npreceded by the optional string `msg`,\nonly if tracing is enabled for the name `n`.\n-/\nmeta def trace_state_if_enabled\n  (n : name) (msg : string := \"\") : tactic unit :=\nwhen_tracing n ((if msg = \"\" then skip else trace msg) >> trace_state)\n\n/--\nThis combinator is for testing purposes. It succeeds if `t` fails with message `msg`,\nand fails otherwise.\n-/\nmeta def success_if_fail_with_msg {\u03b1 : Type u} (t : tactic \u03b1) (msg : string) : tactic unit :=\n\u03bb s, match t s with\n| (interaction_monad.result.exception msg' _ s') :=\n  let expected_msg := (msg'.iget ()).to_string in\n  if msg = expected_msg then result.success () s\n  else mk_exception format!\"failure messages didn't match. Expected:\\n{expected_msg}\" none s\n| (interaction_monad.result.success a s) :=\n   mk_exception \"success_if_fail_with_msg combinator failed, given tactic succeeded\" none s\nend\n\n/--\nConstruct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.\n-/\nmeta def tactic_statement (g : expr) : tactic string :=\ndo g \u2190 instantiate_mvars g,\n   g \u2190 head_beta g,\n   r \u2190 pp (replace_mvars g),\n   if g.has_meta_var\n   then return (sformat!\"Try this: refine {r}\")\n   else return (sformat!\"Try this: exact {r}\")\n\n/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the\ninitial goals and returns the goals `tac` ended on. -/\nmeta def with_local_goals {\u03b1} (gs : list expr) (tac : tactic \u03b1) : tactic (\u03b1 \u00d7 list expr) :=\ndo gs' \u2190 get_goals,\n   set_goals gs,\n   finally (prod.mk <$> tac <*> get_goals) (set_goals gs')\n\n/-- like `with_local_goals` but discards the resulting goals -/\nmeta def with_local_goals' {\u03b1} (gs : list expr) (tac : tactic \u03b1) : tactic \u03b1 :=\nprod.fst <$> with_local_goals gs tac\n\n/-- Representation of a proof goal that lends itself to comparison. The\nfollowing goal:\n\n```lean\nl\u2080 : T,\nl\u2081 : T\n\u22a2 \u2200 v : T, foo\n```\n\nis represented as\n\n```\n(2, \u2200 l\u2080 l\u2081 v : T, foo)\n```\n\nThe number 2 indicates that first the two bound variables of the\n`\u2200` are actually local constant. Comparing two such goals with `=`\nrather than `=\u2090` or `is_def_eq` tells us that proof script should\nnot see the difference between the two.\n -/\nmeta def packaged_goal := \u2115 \u00d7 expr\n\n/-- proof state made of multiple `goal` meant for comparing\nthe result of running different tactics -/\nmeta def proof_state := list packaged_goal\n\nmeta instance goal.inhabited : inhabited packaged_goal := \u27e8(0,var 0)\u27e9\nmeta instance proof_state.inhabited : inhabited proof_state :=\n(infer_instance : inhabited (list packaged_goal))\n\n/-- create a `packaged_goal` corresponding to the current goal -/\nmeta def get_packaged_goal : tactic packaged_goal := do\nls \u2190 local_context,\ntgt \u2190 target >>= instantiate_mvars,\ntgt \u2190 pis ls tgt,\npure (ls.length, tgt)\n\n/-- `goal_of_mvar g`, with `g` a meta variable, creates a\n`packaged_goal` corresponding to `g` interpretted as a proof goal -/\nmeta def goal_of_mvar (g : expr) : tactic packaged_goal :=\nwith_local_goals' [g] get_packaged_goal\n\n/-- `get_proof_state` lists the user visible goal for each goal\nof the current state and for each goal, abstracts all of the\nmeta variables of the other gaols.\n\nThis produces a list of goals in the form of `\u2115 \u00d7 expr` where\nthe `expr` encodes the following proof state:\n\n```lean\n2 goals\nl\u2081 : t\u2081,\nl\u2082 : t\u2082,\nl\u2083 : t\u2083\n\u22a2 tgt\u2081\n\n\u22a2 tgt\u2082\n```\n\nas\n\n```lean\n[ (3, \u2200 (mv : tgt\u2081) (mv : tgt\u2082) (l\u2081 : t\u2081) (l\u2082 : t\u2082) (l\u2083 : t\u2083), tgt\u2081),\n  (0, \u2200 (mv : tgt\u2081) (mv : tgt\u2082), tgt\u2082) ]\n```\n\nwith 2 goals, the first 2 bound variables encode the meta variable\nof all the goals, the next 3 (in the first goal) and 0 (in the second goal)\nare the local constants.\n\nThis representation allows us to compare goals and proof states while\nignoring information like the unique name of local constants and\nthe equality or difference of meta variables that encode the same goal.\n-/\nmeta def get_proof_state : tactic proof_state :=\ndo gs \u2190 get_goals,\n   gs.mmap $ \u03bb g, do\n     \u27e8n,g\u27e9 \u2190 goal_of_mvar g,\n     g \u2190 gs.mfoldl (\u03bb g v, do\n       g \u2190 kabstract g v reducible ff,\n       pure $ pi `goal binder_info.default `(true) g ) g,\n     pure (n,g)\n\n/--\nRun `tac` in a disposable proof state and return the state.\nSee `proof_state`, `goal` and `get_proof_state`.\n-/\nmeta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=\ntry_core $ retrieve $ tac >> get_proof_state\n\nopen lean _root_.interactive\n\n/-- A type alias for `tactic format`, standing for \"pretty print format\". -/\nmeta def pformat := tactic format\n\n/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/\nmeta def pformat.mk (fmt : format) : pformat := pure fmt\n\n/-- an alias for `pp`. -/\nmeta def to_pfmt {\u03b1} [has_to_tactic_format \u03b1] (x : \u03b1) : pformat :=\npp x\n\nmeta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=\n\u27e8 id \u27e9\n\nmeta instance : has_append pformat :=\n\u27e8 \u03bb x y, (++) <$> x <*> y \u27e9\n\nmeta instance tactic.has_to_tactic_format [has_to_tactic_format \u03b1] :\n  has_to_tactic_format (tactic \u03b1) :=\n\u27e8 \u03bb x, x >>= to_pfmt \u27e9\n\nprivate meta def parse_pformat : string \u2192 list char \u2192 parser pexpr\n| acc []            := pure ``(to_pfmt %%(reflect acc))\n| acc ('\\n'::s)     :=\ndo f \u2190 parse_pformat \"\" s,\n   pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)\n| acc ('{'::'{'::s) := parse_pformat (acc ++ \"{\") s\n| acc ('{'::s) :=\ndo (e, s) \u2190 with_input (lean.parser.pexpr 0) s.as_string,\n   '}'::s \u2190 return s.to_list | fail \"'}' expected\",\n   f \u2190 parse_pformat \"\" s,\n   pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)\n| acc (c::s) := parse_pformat (acc.str c) s\n\n/-- See `format!` in `init/meta/interactive_base.lean`.\n\nThe main differences are that `pp` is called instead of `to_fmt` and that we can use\narguments of type `tactic \u03b1` in the quotations.\n\nNow, consider the following:\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace format!\"{e}\"  -- outputs `has_add.add.{0} nat nat.has_add\n                    -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`\ntrace pformat!\"{e}\" -- outputs `3 + 7`\n```\n\nThe difference is significant. And now, the following is expressible:\n\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace pformat!\"{e} : {infer_type e}\" -- outputs `3 + 7 : \u2115`\n```\n\nSee also: `trace!` and `fail!`\n-/\n@[user_notation]\nmeta def pformat_macro (_ : parse $ tk \"pformat!\") (s : string) : parser pexpr :=\ndo e \u2190 parse_pformat \"\" s.to_list,\n   return ``(%%e : pformat)\n\n/--\nThe combination of `pformat` and `fail`.\n-/\n@[user_notation]\nmeta def fail_macro (_ : parse $ tk \"fail!\") (s : string) : parser pexpr :=\ndo e \u2190 pformat_macro () s,\n   pure ``((%%e : pformat) >>= fail)\n\n/--\nThe combination of `pformat` and `trace`.\n-/\n@[user_notation]\nmeta def trace_macro (_ : parse $ tk \"trace!\") (s : string) : parser pexpr :=\ndo e \u2190 pformat_macro () s,\n   pure ``((%%e : pformat) >>= trace)\n\n/-- A hackish way to get the `src` directory of any project.\n  Requires as argument any declaration name `n` in that project, and `k`, the number of characters\n  in the path of the file where `n` is declared not part of the `src` directory.\n  Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`.\n  Note: does not work in the file where `n` is declared. -/\nmeta def get_project_dir (n : name) (k : \u2115) : tactic string :=\ndo e \u2190 get_env,\n  s \u2190 e.decl_olean n <|>\nfail!\"Did not find declaration {n}. This command does not work in the file where {n} is declared.\",\n  return $ s.popn_back k\n\n/-- A hackish way to get the `src` directory of mathlib. -/\nmeta def get_mathlib_dir : tactic string :=\nget_project_dir `mathlib_dir_locator 23\n\n/-- Checks whether a declaration with the given name is declared in mathlib.\nIf you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,\nsince it is expensive to execute `get_mathlib_dir` many times. -/\nmeta def is_in_mathlib (n : name) : tactic bool :=\ndo ml \u2190 get_mathlib_dir, e \u2190 get_env, return $ e.is_prefix_of_file ml n\n\n/--\nRuns a tactic by name.\nIf it is a `tactic string`, return whatever string it returns.\nIf it is a `tactic unit`, return the name.\n(This is mostly used in invoking \"self-reporting tactics\", e.g. by `tidy` and `hint`.)\n-/\nmeta def name_to_tactic (n : name) : tactic string :=\ndo d \u2190 get_decl n,\n   e \u2190 mk_const n,\n   let t := d.type,\n   if (t =\u2090 `(tactic unit)) then\n     (eval_expr (tactic unit) e) >>= (\u03bb t, t >> (name.to_string <$> strip_prefix n))\n   else if (t =\u2090 `(tactic string)) then\n     (eval_expr (tactic string) e) >>= (\u03bb t, t)\n   else fail!\n     \"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`\"\n\n/-- auxiliary function for `apply_under_n_pis` -/\nprivate meta def apply_under_n_pis_aux (func arg : pexpr) : \u2115 \u2192 \u2115 \u2192 expr \u2192 pexpr\n| n 0 _ :=\n  let vars := ((list.range n).reverse.map (@expr.var ff)),\n      bd := vars.foldl expr.app arg.mk_explicit in\n  func bd\n| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp)\n  (apply_under_n_pis_aux (n+1) k bd)\n| n (k+1) t := apply_under_n_pis_aux n 0 t\n\n/--\nAssumes `pi_expr` is of the form `\u03a0 x1 ... xn xn+1..., _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\nmeta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : \u2115) : pexpr :=\napply_under_n_pis_aux func arg 0 n pi_expr\n\n/--\nAssumes `pi_expr` is of the form `\u03a0 x1 ... xn, _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\nmeta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=\napply_under_n_pis func arg pi_expr pi_expr.pi_arity\n\n/--\nIf `func` is a `pexpr` representing a function that takes an argument `a`,\n`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.\nWhen `tgt` is a `pi` expr, `func` is elaborated in a context\nwith the domain of `tgt`.\n\nExamples:\n* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function\n  argument.\n* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument\n  of type `\u03b1 \u2192 \u03b1`.\n* ```get_pexpr_arg_arity_with_tgt ``(module R) `(\u03a0 (R : Type), comm_ring R \u2192 true)``` returns 0\n-/\nmeta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic \u2115 :=\nlock_tactic_state $ do\n  mv \u2190 mk_mvar,\n  solve_aux tgt $ intros >> to_expr ``(%%func %%mv),\n  expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)\n\n/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.\n\n`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a\ndeclaration named `m` can be found. -/\nmeta def find_private_decl (n : name) (fr : option name) : tactic name :=\ndo env \u2190 get_env,\n   fn \u2190 option_t.run (do\n         fr \u2190 option_t.mk (return fr),\n         d \u2190 monad_lift $ get_decl fr,\n         option_t.mk (return $ env.decl_olean d.to_name) ),\n   let p : string \u2192 bool :=\n     match fn with\n     | (some fn) := \u03bb x, fn = x\n     | none := \u03bb _, tt\n     end,\n   let xs := env.decl_filter_map (\u03bb d,\n     do fn \u2190 env.decl_olean d.to_name,\n        guard ((`_private).is_prefix_of d.to_name \u2227 p fn \u2227\n          d.to_name.update_prefix name.anonymous = n),\n        pure d.to_name),\n   match xs with\n   | [n] := pure n\n   | [] := fail \"no such private found\"\n   | _ := fail \"many matches found\"\n   end\n\nopen lean.parser interactive\n\n/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`\nand creates a local notation to refer to it.\n\n`import_private foo` looks for `foo` in all imported files.\n\nWhen possible, make `foo` non-private rather than using this feature.\n -/\n@[user_command]\nmeta def import_private_cmd (_ : parse $ tk \"import_private\") : lean.parser unit :=\ndo n  \u2190 ident,\n   fr \u2190 optional (tk \"from\" *> ident),\n   n \u2190 find_private_decl n fr,\n   c \u2190 resolve_constant n,\n   d \u2190 get_decl n,\n   let c := @expr.const tt c d.univ_levels,\n   new_n \u2190 new_aux_decl_name,\n   add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,\n   let new_not := sformat!\"local notation `{n.update_prefix name.anonymous}` := {new_n}\",\n   emit_command_here $ new_not,\n   skip .\n\nadd_tactic_doc\n{ name                     := \"import_private\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.import_private_cmd],\n  tags                     := [\"renaming\"] }\n\n/--\nThe command `mk_simp_attribute simp_name \"description\"` creates a simp set with name `simp_name`.\nLemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.\n`mk_simp_attribute simp_name none` will use a default description.\n\nAppending the command with `with attr1 attr2 ...` will include all declarations tagged with\n`attr1`, `attr2`, ... in the new simp set.\n\nThis command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string\nto the attribute that is defined. If you need to create a simp set in a file where this command is\nnot available, you should use\n```lean\nrun_cmd mk_simp_attr `simp_name\nrun_cmd add_doc_string `simp_attr.simp_name \"Description of the simp set here\"\n```\n-/\n@[user_command]\nmeta def mk_simp_attribute_cmd (_ : parse $ tk \"mk_simp_attribute\") : lean.parser unit :=\ndo n \u2190 ident,\n   d \u2190 parser.pexpr,\n   d \u2190 to_expr ``(%%d : option string),\n   descr \u2190 eval_expr (option string) d,\n   with_list \u2190 (tk \"with\" *> many ident) <|> return [],\n   mk_simp_attr n with_list,\n   add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ \"simp set for \" ++ to_string n\n\nadd_tactic_doc\n{ name                     := \"mk_simp_attribute\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.mk_simp_attribute_cmd],\n  tags                     := [\"simplification\"] }\n\n/--\nGiven a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns\nthe name of the declaration that defines this attribute.\nFails if there is no user attribute with this name.\nExample: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/\nmeta def get_user_attribute_name (attr_name : name) : tactic name := do\nns \u2190 attribute.get_instances `user_attribute,\nns.mfirst (\u03bb nm, do\n  d \u2190 get_decl nm,\n  e \u2190 mk_app `user_attribute.name [d.value],\n  attr_nm \u2190 eval_expr name e,\n  guard $ attr_nm = attr_name,\n  return nm) <|> fail!\"'{attr_name}' is not a user attribute.\"\n\n/-- A tactic to set either a basic attribute or a user attribute.\n  If the user attribute has a parameter, the default value will be used.\n  This tactic raises an error if there is no `inhabited` instance for the parameter type. -/\nmeta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)\n  (prio : option nat := none) : tactic unit := do\nget_decl c_name <|> fail!\"unknown declaration {c_name}\",\ns \u2190 try_or_report_error (set_basic_attribute attr_name c_name persistent prio),\nsum.inr msg \u2190 return s | skip,\nif msg =\n  (format!\"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute\").to_string\nthen do\n  user_attr_nm \u2190 get_user_attribute_name attr_name,\n  user_attr_const \u2190 mk_const user_attr_nm,\n  tac \u2190 eval_pexpr (tactic unit)\n    ``(user_attribute.set %%user_attr_const %%`(c_name) default %%`(persistent)) <|>\n    fail! (\"Cannot set attribute @[{attr_name}].\\n\" ++\n      \"The corresponding user attribute {user_attr_nm} \" ++\n      \"has a parameter without a default value.\\n\" ++\n      \"Solution: provide an `inhabited` instance.\"),\n  tac\nelse fail msg\n\nend tactic\n\n/--\n`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),\nand returns the value associated with this key if it exists.\nOtherwise, it fails.\n-/\nmeta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr \u00d7 v)) (e : expr) :\n  tactic (expr \u00d7 v) :=\nm.mfind $ \u03bb \u27e8e', val\u27e9, tactic.is_def_eq e e' red\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/core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.08509904094645104, "lm_q1q2_score": 0.034023585969023315}}
{"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 \u2192 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 \u2192 B)\n(map_op' : \u2200 {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 (\u03bb _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := \u03bb 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) (\u03bb _, A \u2192 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 \u2192 B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : my_hom A B :=\n{ to_fun := f',\n  map_op' := h.symm \u25b8 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 (\u03bb _, B) :=\n(map_op : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u2192 has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to functions from `\u03b1` to `\u03b2`.\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*) (\u03b1 : out_param Sort*) (\u03b2 : out_param $ \u03b1 \u2192 Sort*) :=\n(coe : F \u2192 \u03a0 a : \u03b1, \u03b2 a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F \u03b1 \u03b2` where `\u03b2` depends on `a : \u03b1` -/\n\nvariables (F \u03b1 : Sort*) (\u03b2 : \u03b1 \u2192 Sort*)\n\nnamespace fun_like\n\nvariables {F \u03b1 \u03b2} [i : fun_like F \u03b1 \u03b2]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n  nolint dangerous_instance] -- `\u03b1` and `\u03b2` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (\u03bb _, \u03a0 a : \u03b1, \u03b2 a) := { coe := fun_like.coe }\n\n@[simp] \n\ntheorem coe_injective : function.injective (coe_fn : F \u2192 \u03a0 a : \u03b1, \u03b2 a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a) \u2194 f = g :=\n\u27e8\u03bb h, @coe_injective _ _ _ i _ _ h, \u03bb h, by cases h; refl\u27e9\n\ntheorem ext' {f g : F} (h : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g \u2194 ((f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : \u2200 (x : \u03b1), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g \u2194 (\u2200 x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h\u2081 : f = g) (x : \u03b1) : f x = g x :=\ncongr_fun (congr_arg _ h\u2081) x\n\nlemma ne_iff {f g : F} : f \u2260 g \u2194 \u2203 a, f a \u2260 g a :=\next_iff.not.trans not_forall\n\nlemma exists_ne {f g : F} (h : f \u2260 g) : \u2203 x, f x \u2260 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 [\u2200 a, subsingleton (\u03b2 a)] : subsingleton F :=\n\u27e8\u03bb f g, coe_injective $ subsingleton.elim _ _\u27e9\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F \u03b1 (\u03bb _, \u03b2)` where `\u03b2` does not depend on `a : \u03b1` -/\n\nvariables {F \u03b1 \u03b2 : Sort*} [i : fun_like F \u03b1 (\u03bb _, \u03b2)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : \u03b1} (h\u2081 : f = g) (h\u2082 : x = y) : f x = g y :=\ncongr (congr_arg _ h\u2081) h\u2082\n\nprotected lemma congr_arg (f : F) {x y : \u03b1} (h\u2082 : x = y) : f x = f y :=\ncongr_arg _ h\u2082\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 \u2192 NEList Expression \u2192\n      Option ((Option (NEList String)) \u00d7 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, \u2190 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 \u2192 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\u2097 e\u1d63 => match (reduce c e\u2097, reduce c e\u1d63) with\n      | (.val v\u2097, .val v\u1d63) => match v\u2097.binOp v\u1d63 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 \u2192 Context \u00d7 Result\n    | skip      => (c, .val .nil)\n    | eval e => (c, (reduce c e))\n    | seq p\u2081 p\u2082 =>\n      let res := p\u2081.run! c\n      match res.2 with\n      | .err .. => res\n      | _       => p\u2082.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 \u2192 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\u2081 p\u2082) => prog c (.seq p\u2082 k) p\u2081\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\u2081 e\u2082) => expr c (.binOp\u2081 o e\u2082 k) e\u2081\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\u2081 o e\u2082 k) v\u2081 => expr c (.binOp\u2082 o v\u2081 k) e\u2082\n  \n  /- Once the second evaluation is complete, we're good to go -/\n  | ret c (.binOp\u2082 o v\u2081 k) v\u2082 => match v\u2081.binOp v\u2082 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 \u00d7 Result :=\n  let rec run' (s : State) : Context \u00d7 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 \u2190 elabTerm t expectedType\n  synthesizeSyntheticMVars\n  let t \u2190 instantiateMVars t\n  let some t \u2190 delta? t | throwError \"cannot delta reduce {t}\"\n  pure t\n\n/- `eta_helper f = (\u00b7 + 3)` elabs to `\u2200 x, f x = x + 3` -/\nlocal elab \"eta_helper \" t:term : term => do\n  let t \u2190 elabTerm t none\n  let some (_, lhs, rhs) := t.eq? | throwError \"not an equation: {t}\"\n  synthesizeSyntheticMVars\n  let rhs \u2190 instantiateMVars rhs\n  lambdaLetTelescope rhs fun xs rhs \u21a6 do\n    let lhs := (mkAppN lhs xs).headBeta\n    mkForallFVars xs <|\u2190 mkEq lhs rhs\n\n/-- `value_proj x` elabs to `@x.value` -/\nlocal elab \"value_proj \" e:term : term => do\n  let e \u2190 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 (\u2190 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) \u2190 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 <| (\u00b7.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',*} := \u27e8_, rfl\u27e9\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\u2082 w\u2081 \n\nnamespace Mathlib\n\nnamespace list\n\n\n/- append -/\n\n@[simp] theorem nil_append {\u03b1 : Type u} (s : List \u03b1) : [] ++ s = s :=\n  rfl\n\n@[simp] theorem cons_append {\u03b1 : Type u} (x : \u03b1) (s : List \u03b1) (t : List \u03b1) : x :: s ++ t = x :: (s ++ t) :=\n  rfl\n\n@[simp] theorem append_nil {\u03b1 : Type u} (t : List \u03b1) : t ++ [] = t := sorry\n\n@[simp] theorem append_assoc {\u03b1 : Type u} (s : List \u03b1) (t : List \u03b1) (u : List \u03b1) : s ++ t ++ u = s ++ (t ++ u) := sorry\n\n/- length -/\n\ntheorem length_cons {\u03b1 : Type u} (a : \u03b1) (l : List \u03b1) : length (a :: l) = length l + 1 :=\n  rfl\n\n@[simp] theorem length_append {\u03b1 : Type u} (s : List \u03b1) (t : List \u03b1) : length (s ++ t) = length s + length t := sorry\n\n@[simp] theorem length_repeat {\u03b1 : Type u} (a : \u03b1) (n : \u2115) : length (repeat a n) = n := sorry\n\n@[simp] theorem length_tail {\u03b1 : Type u} (l : List \u03b1) : length (tail l) = length l - 1 :=\n  list.cases_on l (Eq.refl (length (tail []))) fun (l_hd : \u03b1) (l_tl : List \u03b1) => Eq.refl (length (tail (l_hd :: l_tl)))\n\n-- TODO(Leo): cleanup proof after arith dec proc\n\n@[simp] theorem length_drop {\u03b1 : Type u} (i : \u2115) (l : List \u03b1) : length (drop i l) = length l - i := sorry\n\n/- map -/\n\ntheorem map_cons {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) (l : List \u03b1) : map f (a :: l) = f a :: map f l :=\n  rfl\n\n@[simp] theorem map_append {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : map f (l\u2081 ++ l\u2082) = map f l\u2081 ++ map f l\u2082 := sorry\n\ntheorem map_singleton {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : map f [a] = [f a] :=\n  rfl\n\n@[simp] theorem map_id {\u03b1 : Type u} (l : List \u03b1) : map id l = l := sorry\n\n@[simp] theorem map_map {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (g : \u03b2 \u2192 \u03b3) (f : \u03b1 \u2192 \u03b2) (l : List \u03b1) : map g (map f l) = map (g \u2218 f) l := sorry\n\n@[simp] theorem length_map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (l : List \u03b1) : length (map f l) = length l := sorry\n\n/- bind -/\n\n@[simp] theorem nil_bind {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 List \u03b2) : list.bind [] f = [] := sorry\n\n@[simp] theorem cons_bind {\u03b1 : Type u} {\u03b2 : Type v} (x : \u03b1) (xs : List \u03b1) (f : \u03b1 \u2192 List \u03b2) : list.bind (x :: xs) f = f x ++ list.bind xs f := sorry\n\n@[simp] theorem append_bind {\u03b1 : Type u} {\u03b2 : Type v} (xs : List \u03b1) (ys : List \u03b1) (f : \u03b1 \u2192 List \u03b2) : list.bind (xs ++ ys) f = list.bind xs f ++ list.bind ys f := sorry\n\n/- mem -/\n\n@[simp] theorem mem_nil_iff {\u03b1 : Type u} (a : \u03b1) : a \u2208 [] \u2194 False :=\n  iff.rfl\n\n@[simp] theorem not_mem_nil {\u03b1 : Type u} (a : \u03b1) : \u00aca \u2208 [] :=\n  iff.mp (mem_nil_iff a)\n\n@[simp] theorem mem_cons_self {\u03b1 : Type u} (a : \u03b1) (l : List \u03b1) : a \u2208 a :: l :=\n  Or.inl rfl\n\n@[simp] theorem mem_cons_iff {\u03b1 : Type u} (a : \u03b1) (y : \u03b1) (l : List \u03b1) : a \u2208 y :: l \u2194 a = y \u2228 a \u2208 l :=\n  iff.rfl\n\ntheorem mem_cons_eq {\u03b1 : Type u} (a : \u03b1) (y : \u03b1) (l : List \u03b1) : a \u2208 y :: l = (a = y \u2228 a \u2208 l) :=\n  rfl\n\ntheorem mem_cons_of_mem {\u03b1 : Type u} (y : \u03b1) {a : \u03b1} {l : List \u03b1} : a \u2208 l \u2192 a \u2208 y :: l :=\n  fun (H : a \u2208 l) => Or.inr H\n\ntheorem eq_or_mem_of_mem_cons {\u03b1 : Type u} {a : \u03b1} {y : \u03b1} {l : List \u03b1} : a \u2208 y :: l \u2192 a = y \u2228 a \u2208 l :=\n  fun (h : a \u2208 y :: l) => h\n\n@[simp] theorem mem_append {\u03b1 : Type u} {a : \u03b1} {s : List \u03b1} {t : List \u03b1} : a \u2208 s ++ t \u2194 a \u2208 s \u2228 a \u2208 t := sorry\n\ntheorem mem_append_eq {\u03b1 : Type u} (a : \u03b1) (s : List \u03b1) (t : List \u03b1) : a \u2208 s ++ t = (a \u2208 s \u2228 a \u2208 t) :=\n  propext mem_append\n\ntheorem mem_append_left {\u03b1 : Type u} {a : \u03b1} {l\u2081 : List \u03b1} (l\u2082 : List \u03b1) (h : a \u2208 l\u2081) : a \u2208 l\u2081 ++ l\u2082 :=\n  iff.mpr mem_append (Or.inl h)\n\ntheorem mem_append_right {\u03b1 : Type u} {a : \u03b1} (l\u2081 : List \u03b1) {l\u2082 : List \u03b1} (h : a \u2208 l\u2082) : a \u2208 l\u2081 ++ l\u2082 :=\n  iff.mpr mem_append (Or.inr h)\n\n@[simp] theorem not_bex_nil {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) : \u00ac\u2203 (x : \u03b1), \u2203 (H : x \u2208 []), p x := sorry\n\n@[simp] theorem ball_nil {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) (x : \u03b1) (H : x \u2208 []) : p x :=\n  false.elim\n\n@[simp] theorem bex_cons {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) (a : \u03b1) (l : List \u03b1) : (\u2203 (x : \u03b1), \u2203 (H : x \u2208 a :: l), p x) \u2194 p a \u2228 \u2203 (x : \u03b1), \u2203 (H : x \u2208 l), p x := sorry\n\n@[simp] theorem ball_cons {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) (a : \u03b1) (l : List \u03b1) : (\u2200 (x : \u03b1), x \u2208 a :: l \u2192 p x) \u2194 p a \u2227 \u2200 (x : \u03b1), x \u2208 l \u2192 p x := sorry\n\n/- list subset -/\n\nprotected def subset {\u03b1 : Type u} (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) :=\n  \u2200 {a : \u03b1}, a \u2208 l\u2081 \u2192 a \u2208 l\u2082\n\nprotected instance has_subset {\u03b1 : Type u} : has_subset (List \u03b1) :=\n  has_subset.mk list.subset\n\n@[simp] theorem nil_subset {\u03b1 : Type u} (l : List \u03b1) : [] \u2286 l :=\n  fun (b : \u03b1) (i : b \u2208 []) => false.elim (iff.mp (mem_nil_iff b) i)\n\n@[simp] theorem subset.refl {\u03b1 : Type u} (l : List \u03b1) : l \u2286 l :=\n  fun (b : \u03b1) (i : b \u2208 l) => i\n\ntheorem subset.trans {\u03b1 : Type u} {l\u2081 : List \u03b1} {l\u2082 : List \u03b1} {l\u2083 : List \u03b1} (h\u2081 : l\u2081 \u2286 l\u2082) (h\u2082 : l\u2082 \u2286 l\u2083) : l\u2081 \u2286 l\u2083 :=\n  fun (b : \u03b1) (i : b \u2208 l\u2081) => h\u2082 (h\u2081 i)\n\n@[simp] theorem subset_cons {\u03b1 : Type u} (a : \u03b1) (l : List \u03b1) : l \u2286 a :: l :=\n  fun (b : \u03b1) (i : b \u2208 l) => Or.inr i\n\ntheorem subset_of_cons_subset {\u03b1 : Type u} {a : \u03b1} {l\u2081 : List \u03b1} {l\u2082 : List \u03b1} : a :: l\u2081 \u2286 l\u2082 \u2192 l\u2081 \u2286 l\u2082 :=\n  fun (s : a :: l\u2081 \u2286 l\u2082) (b : \u03b1) (i : b \u2208 l\u2081) => s (mem_cons_of_mem a i)\n\ntheorem cons_subset_cons {\u03b1 : Type u} {l\u2081 : List \u03b1} {l\u2082 : List \u03b1} (a : \u03b1) (s : l\u2081 \u2286 l\u2082) : a :: l\u2081 \u2286 a :: l\u2082 :=\n  fun (b : \u03b1) (hin : b \u2208 a :: l\u2081) =>\n    or.elim (eq_or_mem_of_mem_cons hin) (fun (e : b = a) => Or.inl e) fun (i : b \u2208 l\u2081) => Or.inr (s i)\n\n@[simp] theorem subset_append_left {\u03b1 : Type u} (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : l\u2081 \u2286 l\u2081 ++ l\u2082 :=\n  fun (b : \u03b1) => mem_append_left l\u2082\n\n@[simp] theorem subset_append_right {\u03b1 : Type u} (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : l\u2082 \u2286 l\u2081 ++ l\u2082 :=\n  fun (b : \u03b1) => mem_append_right l\u2081\n\ntheorem subset_cons_of_subset {\u03b1 : Type u} (a : \u03b1) {l\u2081 : List \u03b1} {l\u2082 : List \u03b1} : l\u2081 \u2286 l\u2082 \u2192 l\u2081 \u2286 a :: l\u2082 :=\n  fun (s : l\u2081 \u2286 l\u2082) (a_1 : \u03b1) (i : a_1 \u2208 l\u2081) => Or.inr (s i)\n\ntheorem eq_nil_of_length_eq_zero {\u03b1 : Type u} {l : List \u03b1} : length l = 0 \u2192 l = [] := sorry\n\ntheorem ne_nil_of_length_eq_succ {\u03b1 : Type u} {l : List \u03b1} {n : \u2115} : length l = Nat.succ n \u2192 l \u2260 [] := sorry\n\n@[simp] theorem length_map\u2082 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : length (map\u2082 f l\u2081 l\u2082) = min (length l\u2081) (length l\u2082) := sorry\n\n@[simp] theorem length_take {\u03b1 : Type u} (i : \u2115) (l : List \u03b1) : length (take i l) = min i (length l) := sorry\n\ntheorem length_take_le {\u03b1 : Type u} (n : \u2115) (l : List \u03b1) : length (take n l) \u2264 n := sorry\n\ntheorem length_remove_nth {\u03b1 : Type u} (l : List \u03b1) (i : \u2115) : i < length l \u2192 length (remove_nth l i) = length l - 1 := sorry\n\n@[simp] theorem partition_eq_filter_filter {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] (l : List \u03b1) : partition p l = (filter p l, filter (Not \u2218 p) l) := sorry\n\n/- sublists -/\n\ninductive sublist {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 \u2192 Prop\nwhere\n| slnil : sublist [] []\n| cons : \u2200 (l\u2081 l\u2082 : List \u03b1) (a : \u03b1), sublist l\u2081 l\u2082 \u2192 sublist l\u2081 (a :: l\u2082)\n| cons2 : \u2200 (l\u2081 l\u2082 : List \u03b1) (a : \u03b1), sublist l\u2081 l\u2082 \u2192 sublist (a :: l\u2081) (a :: l\u2082)\n\ninfixl:50 \" <+ \" => Mathlib.list.sublist\n\ntheorem length_le_of_sublist {\u03b1 : Type u} {l\u2081 : List \u03b1} {l\u2082 : List \u03b1} : l\u2081 <+ l\u2082 \u2192 length l\u2081 \u2264 length l\u2082 := sorry\n\n/- filter -/\n\n@[simp] theorem filter_nil {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [h : decidable_pred p] : filter p [] = [] :=\n  rfl\n\n@[simp] theorem filter_cons_of_pos {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [h : decidable_pred p] {a : \u03b1} (l : List \u03b1) : p a \u2192 filter p (a :: l) = a :: filter p l :=\n  fun (pa : p a) => if_pos pa\n\n@[simp] theorem filter_cons_of_neg {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [h : decidable_pred p] {a : \u03b1} (l : List \u03b1) : \u00acp a \u2192 filter p (a :: l) = filter p l :=\n  fun (pa : \u00acp a) => if_neg pa\n\n@[simp] theorem filter_append {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [h : decidable_pred p] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : filter p (l\u2081 ++ l\u2082) = filter p l\u2081 ++ filter p l\u2082 := sorry\n\n@[simp] theorem filter_sublist {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [h : decidable_pred p] (l : List \u03b1) : 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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03c3 : Type w\u2082} (f : \u03b1 \u2192 \u03c3 \u2192 \u03c3 \u00d7 \u03b2) : List \u03b1 \u2192 \u03c3 \u2192 \u03c3 \u00d7 List \u03b2 :=\n  sorry\n\n@[simp] theorem length_map_accumr {\u03b1 : Type u} {\u03b2 : Type v} {\u03c3 : Type w\u2082} (f : \u03b1 \u2192 \u03c3 \u2192 \u03c3 \u00d7 \u03b2) (x : List \u03b1) (s : \u03c3) : 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\u2082 {\u03b1 : Type u} {\u03b2 : Type v} {\u03c6 : Type w\u2081} {\u03c3 : Type w\u2082} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c3 \u2192 \u03c3 \u00d7 \u03c6) : List \u03b1 \u2192 List \u03b2 \u2192 \u03c3 \u2192 \u03c3 \u00d7 List \u03c6 :=\n  sorry\n\n@[simp] theorem length_map_accumr\u2082 {\u03b1 : Type u} {\u03b2 : Type v} {\u03c6 : Type w\u2081} {\u03c3 : Type w\u2082} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c3 \u2192 \u03c3 \u00d7 \u03c6) (x : List \u03b1) (y : List \u03b2) (c : \u03c3) : length (prod.snd (map_accumr\u2082 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\u00ebl Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Ya\u00ebl 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 {\u03b1 \u03b2 : Type*}\n\n/-- The category of bipointed types. -/\nstructure Bipointed : Type.{u + 1} :=\n(X : Type.{u})\n(to_prod : X \u00d7 X)\n\nnamespace Bipointed\n\ninstance : has_coe_to_sort Bipointed Type* := \u27e8X\u27e9\n\nattribute [protected] Bipointed.X\n\n/-- Turns a bipointing into a bipointed type. -/\ndef of {X : Type*} (to_prod : X \u00d7 X) : Bipointed := \u27e8X, to_prod\u27e9\n\n@[simp] lemma coe_of {X : Type*} (to_prod : X \u00d7 X) : \u21a5(of to_prod) = X := rfl\n\nalias of \u2190 _root_.prod.Bipointed\n\ninstance : inhabited Bipointed := \u27e8of ((), ())\u27e9\n\n/-- Morphisms in `Bipointed`. -/\n@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=\n(to_fun : X \u2192 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 := \u27e8id, rfl, rfl\u27e9\n\ninstance (X : Bipointed) : inhabited (hom X X) := \u27e8id X\u27e9\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\u27e8g.to_fun \u2218 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]\u27e9\n\nend hom\n\ninstance large_category : large_category Bipointed :=\n{ hom := hom,\n  id := hom.id,\n  comp := @hom.comp,\n  id_comp' := \u03bb _ _ _, hom.ext _ _ rfl,\n  comp_id' := \u03bb _ _ _, hom.ext _ _ rfl,\n  assoc' := \u03bb _ _ _ _ _ _ _, hom.ext _ _ rfl }\n\ninstance concrete_category : concrete_category Bipointed :=\n{ forget := { obj := Bipointed.X, map := @hom.to_fun },\n  forget_faithful := \u27e8@hom.ext\u27e9 }\n\n/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/\n@[simps] def swap : Bipointed \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.swap\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_snd, f.map_fst\u27e9 }\n\n/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/\n@[simps] def swap_equiv : Bipointed \u224c Bipointed :=\nequivalence.mk swap swap\n  (nat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl, rfl\u27e9, inv := \u27e8id, rfl, rfl\u27e9 }) $ \u03bb X Y f, rfl)\n  (nat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl, rfl\u27e9, inv := \u27e8id, rfl, rfl\u27e9 }) $ \u03bb 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 \u2964 Pointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.1\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_fst\u27e9 }\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/\ndef Bipointed_to_Pointed_snd : Bipointed \u2964 Pointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.2\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_snd\u27e9 }\n\n@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :\n  Bipointed_to_Pointed_fst \u22d9 forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :\n  Bipointed_to_Pointed_snd \u22d9 forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :\n  Bipointed.swap \u22d9 Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :\n  Bipointed.swap \u22d9 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} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8X, X.point, X.point\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_point, f.map_point\u27e9 }\n\n/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/\ndef Pointed_to_Bipointed_fst : Pointed.{u} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8option X, X.point, none\u27e9,\n  map := \u03bb X Y f, \u27e8option.map f.to_fun, congr_arg _ f.map_point, rfl\u27e9,\n  map_id' := \u03bb X, Bipointed.hom.ext _ _ option.map_id,\n  map_comp' := \u03bb 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} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8option X, none, X.point\u27e9,\n  map := \u03bb X Y f, \u27e8option.map f.to_fun, rfl, congr_arg _ f.map_point\u27e9,\n  map_id' := \u03bb X, Bipointed.hom.ext _ _ option.map_id,\n  map_comp' := \u03bb 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 \u22d9 Bipointed.swap = Pointed_to_Bipointed_snd := rfl\n\n@[simp] lemma Pointed_to_Bipointed_snd_comp_swap :\n  Pointed_to_Bipointed_snd \u22d9 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 \u22d9 Bipointed_to_Pointed_fst \u2245 \ud835\udfed _ :=\nnat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl\u27e9, inv := \u27e8id, rfl\u27e9 }) $ \u03bb 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 \u22d9 Bipointed_to_Pointed_snd \u2245 \ud835\udfed _ :=\nnat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl\u27e9, inv := \u27e8id, rfl\u27e9 }) $ \u03bb 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 \u22a3 Bipointed_to_Pointed_fst :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb X Y, { to_fun := \u03bb f, \u27e8f.to_fun \u2218 option.some, f.map_fst\u27e9,\n                        inv_fun := \u03bb f, \u27e8\u03bb o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl\u27e9,\n                        left_inv := \u03bb f, by { ext, cases x, exact f.map_snd.symm, refl },\n                        right_inv := \u03bb f, Pointed.hom.ext _ _ rfl },\n  hom_equiv_naturality_left_symm' := \u03bb 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 \u22a3 Bipointed_to_Pointed_snd :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb X Y, { to_fun := \u03bb f, \u27e8f.to_fun \u2218 option.some, f.map_snd\u27e9,\n                        inv_fun := \u03bb f, \u27e8\u03bb o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point\u27e9,\n                        left_inv := \u03bb f, by { ext, cases x, exact f.map_fst.symm, refl },\n                        right_inv := \u03bb f, Pointed.hom.ext _ _ rfl },\n  hom_equiv_naturality_left_symm' := \u03bb 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) 2020 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport meta.expr\n\n/-\nLean currently uses the name \u1fb0 for binders which aren't given a name explicitly\n(e.g. when using a function arrow to define a \u03a0 type). This test is here to make\nsure that should this change in the future,\n`name.is_likely_generated_binder_name` will be updated accordingly.\n-/\n\nexample : \u2115 \u2192 \u2115 \u2192 \u2115 :=\nbegin\n  intros,\n  guard_hyp \u1fb0 : \u2115,\n  guard_hyp \u1fb0_1 : \u2115,\n  (do guard $ name.is_likely_generated_binder_name `\u1fb0,\n      guard $ name.is_likely_generated_binder_name `\u1fb0_1\n  ),\n  exact \u1fb0\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/likely_generated_name.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.07585818367743737, "lm_q1q2_score": 0.033797062419714766}}
{"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 \u27f6 Y`,\n- `target_affine_locally (affine_and P)`: the preimage of an affine open `U = Spec A` is affine\n  (`= Spec B`) and `A \u27f6 B` satisfies `P`. (TODO)\n- `affine_locally P`: For each pair of affine open `U = Spec A \u2286 X` and `V = Spec B \u2286 f \u207b\u00b9' U`,\n  the ring hom `A \u27f6 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 : \u2200 {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R \u2192+* 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 \u27f6 Y) (r : Y.presheaf.obj (opposite.op \u22a4)) :\n  P (Scheme.\u0393.map (f \u2223_ Y.basic_open r).op) \u2194\n  P (@is_localization.away.map (Y.presheaf.obj (opposite.op \u22a4)) _\n      (Y.presheaf.obj (opposite.op $ Y.basic_open r)) _ _\n      (X.presheaf.obj (opposite.op \u22a4)) _ (X.presheaf.obj\n      (opposite.op $ X.basic_open (Scheme.\u0393.map f.op r))) _ _ (Scheme.\u0393.map f.op) r _ _) :=\nbegin\n  rw [\u0393_map_morphism_restrict, hP.cancel_left_is_iso, hP.cancel_right_is_iso,\n    \u2190 (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)), \u2190 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 _ \u226b _ = _ \u226b X.presheaf.map _,\n  rw f.val.c.naturality_assoc,\n  erw \u2190 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 \u27f6 Y) (r : Y.presheaf.obj (opposite.op \u22a4)) :\n  P (Scheme.\u0393.map (f \u2223_ Y.basic_open r).op) \u2194\n  P (localization.away_map (Scheme.\u0393.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 \u27f6 Y) (r : Y.presheaf.obj (opposite.op \u22a4))\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.\u0393.map ((X.restrict ((opens.map f.1.base).obj _).open_embedding).of_restrict\n    V.open_embedding \u226b f \u2223_ Y.basic_open r).op) \u2194\n    P (localization.away_map (Scheme.\u0393.map (X.of_restrict U.open_embedding \u226b 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) \u2286 coe '' set.univ,\n    rw [subtype.coe_image_univ, subtype.coe_image_univ],\n    exact set.image_preimage_subset _ _ },\n  { exact algebraic_geometry.\u0393_restrict_is_localization Y r },\n  { rw \u2190 U.open_embedding_obj_top at hU,\n    dsimp [Scheme.\u0393_obj_op, Scheme.\u0393_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.\u0393.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.\u0393_map_op, \u2190 Scheme.preimage_basic_open] },\n  { apply is_localization.ring_hom_ext (submonoid.powers r) _,\n    swap, { exact algebraic_geometry.\u0393_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.\u0393_map, quiver.hom.unop_op],\n    rw [morphism_restrict_c_app, category.assoc, category.assoc, category.assoc],\n    erw [f.1.c.naturality_assoc, \u2190 X.presheaf.map_comp, \u2190 X.presheaf.map_comp,\n      \u2190 X.presheaf.map_comp],\n    congr },\nend\n\nlemma stable_under_base_change.\u0393_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 \u27f6 S) (g : Y \u27f6 S) (H : P (Scheme.\u0393.map g.op)) :\n    P (Scheme.\u0393.map (pullback.fst : pullback f g \u27f6 _).op) :=\nbegin\n  rw [\u2190 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.\u0393.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.\u0393 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 [\u2190 this, hP'.cancel_right_is_iso,\n    \u2190 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 \u27f6 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\u03bb X Y f hY, \u2200 (U : X.affine_opens), P (Scheme.\u0393.map (X.of_restrict U.1.open_embedding \u226b f).op)\n\n/-- For `P` a property of ring homomorphisms, `affine_locally P` holds for `f : X \u27f6 Y` if for each\naffine open `U = Spec A \u2286 Y` and `V = Spec B \u2286 f \u207b\u00b9' U`, the ring hom `A \u27f6 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\u2081 : 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 [\u2190 h\u2081.cancel_right_is_iso _ (Scheme.\u0393.map (Scheme.restrict_map_iso e.inv U.1).hom.op),\n      \u2190 functor.map_comp, \u2190 op_comp],\n    convert H \u27e8_, U.prop.map_is_iso e.inv\u27e9 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 [\u2190 category.assoc, op_comp, functor.map_comp, h\u2081.cancel_left_is_iso],\n    exact H U }\nend\n\nlemma affine_locally_mono\n  (P\u2081 P\u2082 : \u2200 \u2983R S : Type u\u2984 [comm_ring R] [comm_ring S] (f : by exactI R \u2192+* S), Prop)\n  (H : \u2200 {R S : Type u} [comm_ring R] [comm_ring S], by exactI \u2200 (f : R \u2192+* S), P\u2081 f \u2192 P\u2082 f) :\n  affine_locally P\u2081 \u2264 affine_locally P\u2082 :=\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 \u27f6 Y) :\n  affine_locally @P f \u2194\n  (\u2200 (U : Y.affine_opens) (V : X.affine_opens) (e : V.1 \u2264 (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.\u0393.map_comp, \u0393_map_morphism_restrict, category.assoc, Scheme.\u0393_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 \u27e8(opens.map (X.of_restrict (U'.open_embedding)).1.base).obj V.1, _\u27e9,\n    erw \u2190 X.presheaf.map_comp at this,\n    rw [\u2190 hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc,\n      \u2190 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 \u27e8_, V.2.image_is_open_immersion (X.of_restrict _)\u27e9 (subtype.coe_image_subset _ _),\n    erw \u2190 X.presheaf.map_comp,\n    rw [\u2190 hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc,\n      \u2190 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\u2081 : ring_hom.respects_iso @P)\n  (h\u2082 : ring_hom.localization_preserves @P)\n  {X Y : Scheme} [is_affine Y] (f : X \u27f6 Y) (r : Y.presheaf.obj (op \u22a4))\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.\u0393.map\n    ((X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).of_restrict\n      U.1.open_embedding \u226b f \u2223_ Y.basic_open r).op) :=\nbegin\n  specialize H \u27e8_, U.2.image_is_open_immersion (X.of_restrict _)\u27e9,\n  convert (h\u2081.of_restrict_morphism_restrict_iff _ _ _ _ _).mpr _ using 1,\n  swap 5,\n  { exact h\u2082.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\u2081 : ring_hom.respects_iso @P)\n  (h\u2082 : ring_hom.localization_preserves @P)\n  (h\u2083 : ring_hom.of_localization_span @P) : (source_affine_locally @P).is_local :=\nbegin\n  constructor,\n  { exact source_affine_locally_respects_iso h\u2081 },\n  { introv H U,\n    apply Scheme_restrict_basic_open_of_localization_preserves h\u2081 h\u2082; assumption },\n  { introv hs hs' U,\n    resetI,\n    apply h\u2083 _ _ hs,\n    intro r,\n    have := hs' r \u27e8(opens.map (X.of_restrict _).1.base).obj U.1, _\u27e9,\n    rwa h\u2081.of_restrict_morphism_restrict_iff at this,\n    { exact U.2 },\n    { refl },\n    { apply_instance },\n    { suffices : \u2200 (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.\u0393.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\u2081 : ring_hom.respects_iso @P)\n  (h\u2083 : ring_hom.of_localization_span_target @P)\n  {X Y : Scheme} (f : X \u27f6 Y) (U : X.affine_opens)\n  (s : set (X.presheaf.obj (op U.1))) (hs : ideal.span s = \u22a4)\n  (hs' : \u2200 (r : s), P (Scheme.\u0393.map (X.of_restrict (X.basic_open r.1).open_embedding \u226b f).op)) :\n    P (Scheme.\u0393.map (X.of_restrict U.1.open_embedding \u226b 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\u2083 _ _ hs,\n  rintro \u27e8s, r, hr, hs\u27e9,\n  have := (@@localization.alg_equiv _ _ _ _ _ (@@algebraic_geometry.\u0393_restrict_is_localization\n    _ U.2 s)).to_ring_equiv.to_CommRing_iso,\n  refine (h\u2081.cancel_right_is_iso _ (@@localization.alg_equiv _ _ _ _ _\n    (@@algebraic_geometry.\u0393_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, \u2190 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, \u2190 CommRing.comp_eq_ring_hom_comp,\n    Scheme.\u0393_map_op, Scheme.\u0393_map_op, Scheme.\u0393_map_op, category.assoc],\n  erw \u2190 X.presheaf.map_comp,\n  rw [\u2190 h\u2081.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _))],\n  convert hs' \u27e8r, hr\u27e9 using 1,\n  { erw category.assoc, rw [\u2190 X.presheaf.map_comp, op_comp, Scheme.\u0393.map_comp,\n    Scheme.\u0393_map_op, Scheme.\u0393_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\u2081 : ring_hom.respects_iso @P)\n  {X Y Z : Scheme} [is_affine X] [is_affine Z] (f : X \u27f6 Y) [is_open_immersion f] (g : Y \u27f6 Z)\n  (h\u2082 : source_affine_locally @P g) :\n  P (Scheme.\u0393.map (f \u226b g).op) :=\nbegin\n  rw [\u2190 h\u2081.cancel_right_is_iso _ (Scheme.\u0393.map (is_open_immersion.iso_of_range_eq\n    (Y.of_restrict _) f _).hom.op), \u2190 functor.map_comp, \u2190 op_comp],\n  convert h\u2082 \u27e8_, range_is_affine_open_of_open_immersion f\u27e9 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 \u27f6 Y) [is_affine Y]\n  (\ud835\udcb0 : X.open_cover) [\u2200 i, is_affine (\ud835\udcb0.obj i)] (H : \u2200 i, P (Scheme.\u0393.map (\ud835\udcb0.map i \u226b f).op)) :\n  source_affine_locally @P f :=\nbegin\n  let S := \u03bb i, (\u27e8\u27e8set.range (\ud835\udcb0.map i).1.base, (\ud835\udcb0.is_open i).base_open.open_range\u27e9,\n    range_is_affine_open_of_open_immersion (\ud835\udcb0.map i)\u27e9 : 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.\u0393],\n      have := U.2,\n      rw \u2190 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 \u27e8\u27e8_, \ud835\udcb0.f x, rfl\u27e9, \ud835\udcb0.covers x\u27e9 },\n  { rintro \u27e8_, i, rfl\u27e9,\n    specialize H i,\n    rw \u2190 hP.respects_iso.cancel_right_is_iso _ (Scheme.\u0393.map (is_open_immersion.iso_of_range_eq\n      (\ud835\udcb0.map i) (X.of_restrict (S i).1.open_embedding) subtype.range_coe.symm).inv.op) at H,\n    rwa [\u2190 Scheme.\u0393.map_comp, \u2190 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 \u27f6 Y) :\n  tfae [source_affine_locally @P f,\n    \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} X) [\u2200 i, is_affine (\ud835\udcb0.obj i)],\n      \u2200 (i : \ud835\udcb0.J), P (Scheme.\u0393.map (\ud835\udcb0.map i \u226b f).op),\n    \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} X) [\u2200 i, is_affine (\ud835\udcb0.obj i)] (i : \ud835\udcb0.J),\n      P (Scheme.\u0393.map (\ud835\udcb0.map i \u226b f).op),\n    \u2200 {U : Scheme} (g : U \u27f6 X) [is_affine U] [is_open_immersion g],\n      P (Scheme.\u0393.map (g \u226b f).op)] :=\nbegin\n  tfae_have : 1 \u2192 4,\n  { intros H U g _ hg,\n    resetI,\n    specialize H \u27e8\u27e8_, hg.base_open.open_range\u27e9,\n      range_is_affine_open_of_open_immersion g\u27e9,\n    rw [\u2190 hP.respects_iso.cancel_right_is_iso _ (Scheme.\u0393.map (is_open_immersion.iso_of_range_eq\n      g (X.of_restrict (opens.open_embedding \u27e8_, hg.base_open.open_range\u27e9))\n      subtype.range_coe.symm).hom.op), \u2190 Scheme.\u0393.map_comp, \u2190 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 \u2192 3,\n  { intros H \ud835\udcb0 _ i, resetI, apply H },\n  tfae_have : 3 \u2192 2,\n  { intro H, refine \u27e8X.affine_cover, infer_instance, H _\u27e9 },\n  tfae_have : 2 \u2192 1,\n  { rintro \u27e8\ud835\udcb0, _, h\ud835\udcb0\u27e9,\n    exactI hP.source_affine_locally_of_source_open_cover f \ud835\udcb0 h\ud835\udcb0 },\n  tfae_finish\nend\n\nlemma open_cover_tfae {X Y : Scheme.{u}} [is_affine Y] (f : X \u27f6 Y) :\n  tfae [source_affine_locally @P f,\n    \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} X), \u2200 (i : \ud835\udcb0.J), source_affine_locally @P (\ud835\udcb0.map i \u226b f),\n    \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} X) (i : \ud835\udcb0.J), source_affine_locally @P (\ud835\udcb0.map i \u226b f),\n    \u2200 {U : Scheme} (g : U \u27f6 X) [is_open_immersion g], source_affine_locally @P (g \u226b f)] :=\nbegin\n  tfae_have : 1 \u2192 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 \u2190 category.assoc,\n    apply H },\n  tfae_have : 4 \u2192 3,\n  { intros H \ud835\udcb0 _ i, resetI, apply H },\n  tfae_have : 3 \u2192 2,\n  { intro H, refine \u27e8X.affine_cover, H _\u27e9 },\n  tfae_have : 2 \u2192 1,\n  { rintro \u27e8\ud835\udcb0, h\ud835\udcb0\u27e9,\n    rw (hP.affine_open_cover_tfae f).out 0 1,\n    refine \u27e8\ud835\udcb0.bind (\u03bb _, Scheme.affine_cover _), _, _\u27e9,\n    { intro i, dsimp, apply_instance },\n    { intro i,\n      specialize h\ud835\udcb0 i.1,\n      rw (hP.affine_open_cover_tfae (\ud835\udcb0.map i.fst \u226b f)).out 0 3 at h\ud835\udcb0,\n      erw category.assoc,\n      apply @@h\ud835\udcb0 _ (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 \u27f6 Y) (g : Y \u27f6 Z) [is_open_immersion f]\n  (H : source_affine_locally @P g) : source_affine_locally @P (f \u226b 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 \u27f6 Y)\n  [is_affine Y] (\ud835\udcb0 : Scheme.open_cover.{u} X) [\u2200 i, is_affine (\ud835\udcb0.obj i)] :\n  source_affine_locally @P f \u2194 (\u2200 i, P (Scheme.\u0393.map (\ud835\udcb0.map i \u226b f).op)) :=\n\u27e8\u03bb H, let h := ((hP.affine_open_cover_tfae f).out 0 2).mp H in h \ud835\udcb0,\n  \u03bb H, let h := ((hP.affine_open_cover_tfae f).out 1 0).mp in h \u27e8\ud835\udcb0, infer_instance, H\u27e9\u27e9\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 \u27f6 Y)\n  (\ud835\udcb0 : Scheme.open_cover.{u} Y) [\u2200 i, is_affine (\ud835\udcb0.obj i)]\n  (\ud835\udcb0' : \u2200 i, Scheme.open_cover.{u} ((\ud835\udcb0.pullback_cover f).obj i)) [\u2200 i j, is_affine ((\ud835\udcb0' i).obj j)] :\n  affine_locally @P f \u2194\n    (\u2200 i j, P (Scheme.\u0393.map ((\ud835\udcb0' i).map j \u226b pullback.snd).op)) :=\n(hP.is_local_source_affine_locally.affine_open_cover_iff f \ud835\udcb0).trans\n    (forall_congr (\u03bb i, hP.source_affine_open_cover_iff _ (\ud835\udcb0' i)))\n\nlemma source_open_cover_iff {X Y : Scheme.{u}} (f : X \u27f6 Y)\n  (\ud835\udcb0 : Scheme.open_cover.{u} X) :\n  affine_locally @P f \u2194 \u2200 i, affine_locally @P (\ud835\udcb0.map i \u226b 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 \u2223_ U.1)).out 1 0).mp,\n    use \ud835\udcb0.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, \u2190 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 \u27f6 Y) [hf : is_open_immersion f] : affine_locally @P f :=\nbegin\n  intro U,\n  haveI H : is_affine _ := U.2,\n  rw \u2190 category.comp_id (f \u2223_ 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 (\ud835\udfd9 _)),\n  { intro i, erw [category.id_comp, op_id, Scheme.\u0393.map_id],\n    convert hP.holds_for_localization_away _ (1 : Scheme.\u0393.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 : \u2200 {R S T : Type.{u}} [comm_ring R] [comm_ring S] [comm_ring T], by exactI\n    \u2200 (f : R \u2192+* S) (g : S \u2192+* T), P (g.comp f) \u2192 P g)\n  {X Y Z : Scheme} {f : X \u27f6 Y} {g : Y \u27f6 Z} (h : affine_locally @P (f \u226b g)) :\n  affine_locally @P f :=\nbegin\n  let \ud835\udcb0 : \u2200 i, ((Z.affine_cover.pullback_cover (f \u226b g)).obj i).open_cover,\n  { intro i,\n    refine Scheme.open_cover.bind _ (\u03bb 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\ud835\udcb0 : \u2200 i j, is_affine ((\ud835\udcb0 i).obj j), by { dsimp, apply_instance },\n  let \ud835\udcb0' := (Z.affine_cover.pullback_cover g).bind (\u03bb i, Scheme.affine_cover _),\n  haveI h\ud835\udcb0' : \u2200 i, is_affine (\ud835\udcb0'.obj i), by { dsimp, apply_instance },\n  rw hP.affine_open_cover_iff f \ud835\udcb0' (\u03bb i, Scheme.affine_cover _),\n  rw hP.affine_open_cover_iff (f \u226b g) Z.affine_cover \ud835\udcb0 at h,\n  rintros \u27e8i, j\u27e9 k,\n  dsimp at i j k,\n  specialize h i \u27e8j, k\u27e9,\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 \u22a2,\n  rw [category.assoc, category.assoc, pullback_right_pullback_fst_iso_hom_snd,\n    pullback.lift_snd_assoc, category.assoc, \u2190 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 \ud835\udcb0 : \u2200 i, ((S.affine_cover.pullback_cover (f \u226b g)).obj i).open_cover,\n  { intro i,\n    refine Scheme.open_cover.bind _ (\u03bb 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 \u226b g) S.affine_cover _,\n  rotate,\n  { exact \ud835\udcb0 },\n  { intros i j, dsimp at *, apply_instance },\n  { rintros i \u27e8j, k\u27e9,\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, \u2190 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 \u226b 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 \u226b pullback.fst) \u27f6 _)).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 \u27f6 _)).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.\u0393_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 \ud835\udcb0 }\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\u03bb X Y f hY, is_affine X \u2227 P (Scheme.\u0393.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 \u27f6 Y) :\n  target_affine_locally (affine_and @P) f \u2194\n    affine f \u2227 (\u2200 U : opens Y.carrier, is_affine_open U \u2192 P (f.1.c.app (op U))) :=\nbegin\n  delta target_affine_locally Scheme.affine_opens,\n  simp_rw [affine_iff, \u2190 forall_and_distrib, set_coe.forall],\n  apply forall\u2082_congr,\n  intros U hU,\n  apply and_congr iff.rfl,\n  rw [\u0393_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) \u2264 @affine :=\nbegin\n  rw affine_eq_affine_property,\n  apply target_affine_locally_mono,\n  exact \u03bb 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 \u2293 affine_locally @P :=\nbegin\n  rw [affine_eq_affine_property, \u2190 target_affine_locally_and],\n  congr' 1,\n  ext X Y f hY,\n  resetI,\n  split,\n  { intro H, refine \u27e8H.1, _\u27e9,\n    rw (hP.affine_open_cover_tfae f).out 0 1,\n    refine \u27e8Scheme.open_cover_of_is_iso (\ud835\udfd9 _), \u03bb i, H.1, \u03bb _, _\u27e9,\n    rw [Scheme.open_cover_of_is_iso_map, category.id_comp f],\n    exact H.2 },\n  { rintros \u27e8h\u2081 : is_affine X, h\u2082\u27e9,\n    rw (hP.affine_open_cover_tfae f).out 0 2 at h\u2082,\n    have := @h\u2082 (Scheme.open_cover_of_is_iso (\ud835\udfd9 _)) (\u03bb _, h\u2081) punit.star,\n    rw [Scheme.open_cover_of_is_iso_map, category.id_comp f] at this,\n    refine \u27e8h\u2081, this\u27e9 }\nend\n\nvariable (P)\n\nlemma is_local_affine_and\n  (hP : ring_hom.respects_iso @P)\n  (h\u2083 : ring_hom.localization_preserves @P)\n  (h\u2084 : 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 _ \u27e8H\u2081, H\u2082\u27e9,\n      resetI,\n      refine \u27e8is_affine_of_iso e.hom, _\u27e9,\n      rw [op_comp, functor.map_comp],\n      exact hP.1 (Scheme.\u0393.map f.op) (Scheme.\u0393.map_iso e.op).CommRing_iso_to_ring_equiv H\u2082 },\n    { rintros X Y Z e f _ \u27e8H\u2081, H\u2082\u27e9,\n      resetI,\n      refine \u27e8H\u2081, _\u27e9,\n      rw [op_comp, functor.map_comp],\n      exact hP.2 (Scheme.\u0393.map f.op) (Scheme.\u0393.map_iso e.op).CommRing_iso_to_ring_equiv H\u2082 } },\n  { rintros X Y hY f r \u27e8H\u2081, H\u2082\u27e9,\n    resetI,\n    refine \u27e8affine_affine_property_is_local.2 f r H\u2081, _\u27e9,\n    rw hP.basic_open_iff,\n    apply ring_hom.localization_preserves.away @h\u2083,\n    all_goals { assumption } },\n  { rintros X Y hY f s hs H,\n    obtain \u27e8H\u2081, H\u2082\u27e9 := forall_and_distrib.mp H,\n    resetI,\n    haveI := affine_affine_property_is_local.3 f s hs H\u2081,\n    refine \u27e8_, _\u27e9,\n    swap,\n    apply h\u2084 (Scheme.\u0393.map f.op) \u2191s hs,\n    intro r,\n    specialize H\u2082 r,\n    rw hP.basic_open_iff_localization at H\u2082,\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\u2081 h\u2082 U,\n  obtain \u27e8h\u2083, h\u2084\u27e9 := h\u2082 U,\n  obtain \u27e8h\u2085, h\u2086\u27e9 := h\u2081 \u27e8_, h\u2083\u27e9,\n  split,\n  { exact h\u2085 },\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\u2081 : ring_hom.localization_preserves @P)\n  (h\u2082 : ring_hom.of_localization_span @P)\n  (h\u2083 : _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\u2081 @h\u2082).stable_under_base_change,\n  rintros X Y S hS hX f g \u27e8hY, H\u27e9,\n  exactI \u27e8infer_instance, h\u2083.\u0393_pullback_fst hP _ _ H\u27e9\nend\n\nlemma affine_and_mono\n  (P\u2081 P\u2082 : \u2200 \u2983R S : Type u\u2984 [comm_ring R] [comm_ring S] (f : by exactI R \u2192+* S), Prop)\n  (H : \u2200 {R S : Type u} [comm_ring R] [comm_ring S], by exactI \u2200 (f : R \u2192+* S), P\u2081 f \u2192 P\u2082 f) :\n  target_affine_locally (affine_and P\u2081) \u2264 target_affine_locally (affine_and P\u2082) :=\nbegin\n  apply target_affine_locally_mono,\n  rintros X Y hY f \u27e8hX, hf\u27e9,\n  exact \u27e8hX, H _ hf\u27e9,\nend\n\nlemma affine_and_Spec_iff {P}\n  (h\u2081 : ring_hom.respects_iso @P) {R S : CommRing} (f : R \u27f6 S) :\n  affine_and @P (Scheme.Spec.map f.op) \u2194 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 (\u0393_Spec_arrow_iso f),\n  dsimp only [arrow.mk_hom] at this,\n  rw [this, h\u2081.cancel_left_is_iso, h\u2081.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": "/-\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 Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.Lean3Lib.data.dlist\nimport Mathlib.PostPort\n\nuniverses u_1 \n\nnamespace Mathlib\n\n/-- Concatenates a list of difference lists to form a single\ndifference list.  Similar to `list.join`. -/\ndef dlist.join {\u03b1 : Type u_1} : List (dlist \u03b1) \u2192 dlist \u03b1 := sorry\n\n@[simp] theorem dlist_singleton {\u03b1 : Type u_1} {a : \u03b1} :\n    dlist.singleton a = dlist.lazy_of_list fun (_ : Unit) => [a] :=\n  rfl\n\n@[simp] theorem dlist_lazy {\u03b1 : Type u_1} {l : List \u03b1} :\n    (dlist.lazy_of_list fun (_ : Unit) => l) = dlist.of_list l :=\n  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/dlist/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.06853748827553191, "lm_q1q2_score": 0.03373333858131993}}
{"text": "open classical\n\ntheorem dne {p : Prop} (h : \u00ac\u00acp) : p :=\n  or.elim (em p)\n    (assume hp : p, hp)\n    (assume hnp : \u00acp, 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 {\u03b1 : Type u_1} (x : \u03b1) : thunk \u03b1 := fun (_x : Unit) => x\n\nprotected instance decidable_eq {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (thunk \u03b1) := sorry\n\nend thunk\n\n\nnamespace lazy_list\n\n\n/-- Isomorphism between strict and lazy lists. -/\ndef list_equiv_lazy_list (\u03b1 : Type u_1) : List \u03b1 \u2243 lazy_list \u03b1 :=\n  equiv.mk of_list to_list sorry sorry\n\nprotected instance inhabited {\u03b1 : Type u} : Inhabited (lazy_list \u03b1) := { default := nil }\n\nprotected instance decidable_eq {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (lazy_list \u03b1) := sorry\n\n/-- Traversal of lazy lists using an applicative effect. -/\nprotected def traverse {m : Type u \u2192 Type u} [Applicative m] {\u03b1 : Type u} {\u03b2 : Type u}\n    (f : \u03b1 \u2192 m \u03b2) : lazy_list \u03b1 \u2192 m (lazy_list \u03b2) :=\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 {\u03b1 : Type u_1} : lazy_list \u03b1 \u2192 lazy_list \u03b1 := sorry\n\n/-- Return the first object contained in the list that satisfies\npredicate `p` -/\ndef find {\u03b1 : Type u_1} (p : \u03b1 \u2192 Prop) [decidable_pred p] : lazy_list \u03b1 \u2192 Option \u03b1 := sorry\n\n/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/\ndef interleave {\u03b1 : Type u_1} : lazy_list \u03b1 \u2192 lazy_list \u03b1 \u2192 lazy_list \u03b1 := 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 {\u03b1 : Type u_1} : List (lazy_list \u03b1) \u2192 lazy_list \u03b1 := sorry\n\n/-- Monadic bind operation for `lazy_list`. -/\nprotected def bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} : lazy_list \u03b1 \u2192 (\u03b1 \u2192 lazy_list \u03b2) \u2192 lazy_list \u03b2 :=\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 {\u03b1 : Type u_1} (xs : lazy_list \u03b1) : lazy_list \u03b1 := of_list (list.reverse (to_list xs))\n\nprotected instance monad : Monad lazy_list := sorry\n\ntheorem append_nil {\u03b1 : Type u_1} (xs : lazy_list \u03b1) : (append xs fun (_ : Unit) => nil) = xs :=\n  sorry\n\ntheorem append_assoc {\u03b1 : Type u_1} (xs : lazy_list \u03b1) (ys : lazy_list \u03b1) (zs : lazy_list \u03b1) :\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (xs : lazy_list \u03b1) (ys : thunk (lazy_list \u03b1))\n    (f : \u03b1 \u2192 lazy_list \u03b2) :\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 \u2192 Type u_2} [alternative m] {\u03b1 : Type u_3} {\u03b2 : Type u_1} (f : \u03b1 \u2192 m \u03b2) :\n    lazy_list \u03b1 \u2192 m \u03b2 :=\n  sorry\n\n/-- Membership in lazy lists -/\nprotected def mem {\u03b1 : Type u_1} (x : \u03b1) : lazy_list \u03b1 \u2192 Prop := sorry\n\nprotected instance has_mem {\u03b1 : outParam (Type u_1)} : has_mem \u03b1 (lazy_list \u03b1) :=\n  has_mem.mk lazy_list.mem\n\nprotected instance mem.decidable {\u03b1 : Type u_1} [DecidableEq \u03b1] (x : \u03b1) (xs : lazy_list \u03b1) :\n    Decidable (x \u2208 xs) :=\n  sorry\n\n@[simp] theorem mem_nil {\u03b1 : Type u_1} (x : \u03b1) : x \u2208 nil \u2194 False := iff.rfl\n\n@[simp] theorem mem_cons {\u03b1 : Type u_1} (x : \u03b1) (y : \u03b1) (ys : thunk (lazy_list \u03b1)) :\n    x \u2208 cons y ys \u2194 x = y \u2228 x \u2208 ys Unit.unit :=\n  iff.rfl\n\ntheorem forall_mem_cons {\u03b1 : Type u_1} {p : \u03b1 \u2192 Prop} {a : \u03b1} {l : thunk (lazy_list \u03b1)} :\n    (\u2200 (x : \u03b1), x \u2208 cons a l \u2192 p x) \u2194 p a \u2227 \u2200 (x : \u03b1), x \u2208 l Unit.unit \u2192 p x :=\n  sorry\n\n/-! ### map for partial functions -/\n\n/-- Partial map. If `f : \u03a0 a, p a \u2192 \u03b2` is a partial function defined on\n  `a : \u03b1` 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2)\n    (l : lazy_list \u03b1) : (\u2200 (a : \u03b1), a \u2208 l \u2192 p a) \u2192 lazy_list \u03b2 :=\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 \u2208 l}`. -/\ndef attach {\u03b1 : Type u_1} (l : lazy_list \u03b1) : lazy_list (Subtype fun (x : \u03b1) => x \u2208 l) :=\n  pmap Subtype.mk l sorry\n\nprotected instance has_repr {\u03b1 : Type u_1} [has_repr \u03b1] : has_repr (lazy_list \u03b1) :=\n  has_repr.mk fun (xs : lazy_list \u03b1) => 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 \u2227 b \u2227 c \u2228 d` or\n`h2 : \u2203 x y, trans_rel R x y`. Usual usage might be `rcases h1 with \u27e8ha, hb, hc\u27e9 | hd` or\n`rcases h2 with \u27e8x, y, _ | \u27e8z, hxz, hzy\u27e9\u27e9` 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 `\u27e8p1, p2, p3\u27e9`, which matches a constructor with many arguments, or a series\n  of nested conjunctions or existentials. For example if the active hypothesis is `a \u2227 b \u2227 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 \u2228 b \u2228 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 \u27e8y, z\u27e9` 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 \u27e8hx, hy\u27e9 | hz := foo` is equivalent to `rcases foo with \u27e8hx, hy\u27e9 | hz`. Unlike `rcases`,\n  `obtain` also allows one to omit `:= foo`, although a type must be provided in this case,\n  as in `obtain \u27e8hx, hy\u27e9 | hz : a \u2227 b \u2228 c`, in which case it produces a subgoal for proving\n  `a \u2227 b \u2228 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\u03a3` is used where a list represents a disjunction, such as the\n  list of possible constructors of an inductive type.\n\n- `list\u03a0` 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\u03a3` := list_Sigma\nlocal notation `list\u03a0` := 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 \u00d7 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 `\u27e8p1, p2, p3\u27e9`\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 \u2228 a2 \u2228 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 \u2192 rcases_patt\n| clear : rcases_patt\n| typed : rcases_patt \u2192 pexpr \u2192 rcases_patt\n| tuple : list\u03a0 rcases_patt \u2192 rcases_patt\n| alts : list\u03a3 rcases_patt \u2192 rcases_patt\n\nnamespace rcases_patt\nmeta instance inhabited : inhabited rcases_patt :=\n\u27e8one `_\u27e9\n\n/-- Get the name from a pattern, if provided -/\nmeta def name : rcases_patt \u2192 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 `\u27e8p\u27e9`\nif `p` is not already a tuple. -/\nmeta def as_tuple : rcases_patt \u2192 list\u03a0 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 \u2192 list\u03a3 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 `\u27e8p\u27e9`. -/\nmeta def tuple' : list\u03a0 rcases_patt \u2192 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\u03a3 rcases_patt \u2192 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, \u27e8c, d\u27e9]`\nbecomes `\u27e8a, b, c, d\u27e9` instead of `\u27e8a, b, \u27e8c, d\u27e9\u27e9`.\n\nWe must be careful to turn `[a, \u27e8\u27e9]` into `\u27e8a, \u27e8\u27e9\u27e9` instead of `\u27e8a\u27e9` (which will not perform the\nnested match). -/\nmeta def tuple\u2081_core : list\u03a0 rcases_patt \u2192 list\u03a0 rcases_patt\n| [] := []\n| [tuple []] := [tuple []]\n| [tuple ps] := ps\n| (p :: ps) := p :: tuple\u2081_core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`tuple\u2081_core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n`\ninstead of `\u27e8n\u27e9` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `\u27e8a, b, c\u27e9`. -/\nmeta def tuple\u2081 : list\u03a0 rcases_patt \u2192 rcases_patt\n| [] := default _\n| [one n] := one n\n| ps := tuple (tuple\u2081_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\u2081` 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\u2081_core : list\u03a3 (list\u03a0 rcases_patt) \u2192 list\u03a3 rcases_patt\n| [] := []\n| [[alts ps]] := ps\n| (p :: ps) := tuple\u2081 p :: alts\u2081_core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`alts\u2081_core`, but it produces a cases pattern directly instead of a list of alternatives. We\nspecially translate the empty alternation to `\u27e8\u27e9`, and translate `|(a | b)` to `\u27e8a | b\u27e9` (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\u2081 : list\u03a3 (list\u03a0 rcases_patt) \u2192 rcases_patt\n| [[]] := tuple []\n| [[alts ps]] := tuple [alts ps]\n| ps := alts' (alts\u2081_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) := `(\u03bb l, tuple l).subst $\n  by haveI := has_reflect; exact list.reflect l\n| (alts l) := `(\u03bb 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 : \u2200 bracket : bool, rcases_patt \u2192 tactic _root_.format\n| _ (one n) := pure $ to_fmt n\n| _ clear := pure \"-\"\n| _ (tuple []) := pure \"\u27e8\u27e9\"\n| _ (tuple ls) := do\n  fs \u2190 ls.mmap $ format ff,\n  pure $ \"\u27e8\" ++ _root_.format.group (_root_.format.nest 1 $\n    _root_.format.join $ list.intersperse (\",\" ++ _root_.format.line) fs) ++ \"\u27e9\"\n| br (alts ls) := do\n  fs \u2190 ls.mmap $ format tt,\n  let fmt := _root_.format.join $ list.intersperse (\u2191\" |\" ++ _root_.format.space) fs,\n  pure $ if br then _root_.format.bracket \"(\" \")\" fmt else fmt\n| br (typed p e) := do\n  fp \u2190 format ff p,\n  fe \u2190 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 := \u27e8rcases_patt.format ff\u27e9\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 \u2192 list\u03a0 rcases_patt \u2192 list\u03a0 name \u00d7 list\u03a0 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 `\u03b1 \u00d7 \u03b2 \u00d7 \u03b3` against `\u27e8a, b, c\u27e9`.\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\u03a3 name \u2192 list\u03a3 rcases_patt \u2192\n  tactic (dlist name \u00d7 list\u03a3 (name \u00d7 list\u03a0 rcases_patt))\n| []      ps := pure (dlist.empty, [])\n| (c::cs) ps := do\n  n \u2190 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  -- `\u03b1 \u2295 \u03b2 \u2295 \u03b3` 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) \u2190 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 {\u03b1 \u03b2} (p : \u03b1 \u2192 \u03b2 \u2192 Prop) [\u2200 a b, decidable (p a b)] :\n  list \u03b1 \u2192 list \u03b2 \u2192 list (\u03b1 \u00d7 \u03b2)\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 \u00d7 expr) :=\n(do t \u2190 infer_type e, pure (t, e)) <|> (do\n    e \u2190 get_local e.local_pp_name,\n    t \u2190 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  `\u27e8a | b, \u27e8c, d\u27e9\u27e9` performs the `\u27e8c, d\u27e9` match twice, once on the `a` branch and once on `b`.\n-/\nmeta mutual def rcases_core, rcases.continue\nwith rcases_core : rcases_patt \u2192 expr \u2192 tactic (list uncleared_goal)\n| (rcases_patt.one `rfl) e := do\n  (t, e) \u2190 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 \u2190 try_core (get_local_and_type e),\n  list.map (prod.mk $ m.elim [] (\u03bb \u27e8_, e\u27e9, [e])) <$> get_goals\n| (rcases_patt.typed p ty) e := do\n  (t, e) \u2190 get_local_and_type e,\n  ty \u2190 i_to_expr_no_subgoals ``(%%ty : Sort*),\n  unify t ty,\n  t \u2190 instantiate_mvars t,\n  ty \u2190 instantiate_mvars ty,\n  e \u2190 if t =\u2090 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) \u2190 get_local_and_type e,\n  t \u2190 whnf t,\n  env \u2190 get_env,\n  let I := t.get_app_fn.const_name,\n  let pat := pat.as_alts,\n  (ids, r, l) \u2190 (if I \u2260 `quot\n  then do\n    when (\u00acenv.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) \u2190 rcases.process_constructors params c pat,\n    l \u2190 cases_core e ids.to_list,\n    pure (ids, r, l)\n  else do\n    (ids, r) \u2190 rcases.process_constructors 2 [`quot.mk] pat,\n    [(_, d)] \u2190 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 \u2190 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 (\u03bb (a : name \u00d7 _) (b : _ \u00d7 name \u00d7 _), a.1 = b.2.1) r (gs.zip l),\n  list.join <$> ls.mmap (\u03bb\u27e8\u27e8_, ps\u27e9, g, _, hs, _\u27e9, set_goals [g] >> rcases.continue (ps.zip hs))\n\nwith rcases.continue : list\u03a0 (rcases_patt \u00d7 expr) \u2192 tactic (list uncleared_goal)\n| [] := list.map (prod.mk []) <$> get_goals\n| ((pat, e) :: pes) := do\n  gs \u2190 rcases_core pat e,\n  list.join <$> gs.mmap (\u03bb \u27e8cs, g\u27e9, do\n    set_goals [g],\n    ugs \u2190 rcases.continue pes,\n    pure $ ugs.map $ \u03bb \u27e8cs', gs\u27e9, (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 \u2190 ugs.mmap (\u03bb \u27e8cs, g\u27e9, do\n    set_goals [g],\n    cs \u2190 cs.mfoldr (\u03bb c cs,\n      (do (_, c) \u2190 get_local_and_type c, pure (c :: cs)) <|> pure cs) [],\n    clear' tt cs,\n    [g] \u2190 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 \u2190 match h with\n    | some h := do\n      x \u2190 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 \u2190 pat.name.elim mk_fresh_name pure,\n    n \u2190 revert_kdependencies e semireducible,\n    tactic.generalize e x <|> (do\n      t \u2190 infer_type e,\n      tactic.assertv x t e,\n      get_local x >>= tactic.revert,\n      pure ()),\n    h \u2190 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\u03a0 pexpr) (pat : rcases_patt) : tactic unit := do\n  let (_, pats) := rcases.process_constructor ps.length pat.as_tuple,\n  pes \u2190 (ps.zip pats).mmap (\u03bb \u27e8p, pat\u27e9, do\n    let p := match pat with\n    | rcases_patt.typed _ ty := ``(%%p : %%ty)\n    | _ := p\n    end,\n    e \u2190 i_to_expr p,\n    if e.is_local_constant then\n      pure (pat, e)\n    else do\n      x \u2190 pat.name.elim mk_fresh_name pure,\n      n \u2190 revert_kdependencies e semireducible,\n      tactic.generalize e x <|> (do\n        t \u2190 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\u2081 pat\u2082 ... pat\u2099` introduces `n` arguments, then pattern matches on the `pat\u1d62` using\nthe same syntax as `rcases`. -/\nmeta def rintro (ids : list\u03a0 rcases_patt) : tactic unit :=\ndo l \u2190 ids.mmap (\u03bb id, do\n    e \u2190 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 {\u03b1} (m : \u03b1 \u2192 \u03b1 \u2192 \u03b1) : list \u03b1 \u2192 list \u03b1 \u2192 list \u03b1\n| [] l\u2082 := l\u2082\n| l\u2081 [] := l\u2081\n| (a :: l\u2081) (b :: l\u2082) := m a b :: merge_list l\u2081 l\u2082\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 `\u27e8a, b\u27e9` 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 \u2192 rcases_patt \u2192 rcases_patt\n| (rcases_patt.alts p\u2081) p\u2082 := rcases_patt.alts (merge_list rcases_patt.merge p\u2081 p\u2082.as_alts)\n| p\u2081 (rcases_patt.alts p\u2082) := rcases_patt.alts (merge_list rcases_patt.merge p\u2081.as_alts p\u2082)\n| (rcases_patt.tuple p\u2081) p\u2082 := rcases_patt.tuple (merge_list rcases_patt.merge p\u2081 p\u2082.as_tuple)\n| p\u2081 (rcases_patt.tuple p\u2082) := rcases_patt.tuple (merge_list rcases_patt.merge p\u2081.as_tuple p\u2082)\n| (rcases_patt.typed p\u2081 e) p\u2082 := rcases_patt.typed (p\u2081.merge p\u2082) e\n| p\u2081 (rcases_patt.typed p\u2082 e) := rcases_patt.typed (p\u2081.merge p\u2082) 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 `\u03a3\u03a0`-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 : \u2115 \u2192 expr \u2192 tactic (rcases_patt \u00d7 list expr)\n| depth e := do\n  (t, e) \u2190 get_local_and_type e,\n  t \u2190 whnf t,\n  env \u2190 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 \u2190 try_core (guard (depth \u2260 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 \u2190 get_goals,\n    if gs.empty then\n      pure (rcases_patt.tuple [], [])\n    else do\n      (ps, gs') \u2190 rcases_hint.process_constructors (depth - 1) c (gs.zip l),\n      pure (rcases_patt.alts\u2081 ps, gs'))\n\nwith rcases_hint.process_constructors : \u2115 \u2192 list\u03a3 name \u2192\n  list (expr \u00d7 name \u00d7 list\u03a0 expr \u00d7 list (name \u00d7 expr)) \u2192\n  tactic (list\u03a3 (list\u03a0 rcases_patt) \u00d7 list expr)\n| depth [] _  := pure ([], [])\n| depth cs [] := pure (cs.map (\u03bb _, []), [])\n| depth (c::cs) ls@((g, c', hs, _) :: l) :=\n  if c \u2260 c' then do\n    (ps, gs) \u2190 rcases_hint.process_constructors depth cs ls,\n    pure ([] :: ps, gs)\n  else do\n    (p, gs) \u2190 set_goals [g] >> rcases_hint.continue depth hs,\n    (ps, gs') \u2190 rcases_hint.process_constructors depth cs l,\n    pure (p :: ps, gs ++ gs')\n\nwith rcases_hint.continue : \u2115 \u2192 list\u03a0 expr \u2192 tactic (list\u03a0 rcases_patt \u00d7 list expr)\n| depth [] := prod.mk [] <$> get_goals\n| depth (e :: es) := do\n  (p, gs) \u2190 rcases_hint_core depth e,\n  (ps, gs') \u2190 gs.mfoldl (\u03bb (r : list\u03a0 rcases_patt \u00d7 list expr) g,\n    do (ps, gs') \u2190 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 \u2190 i_to_expr p,\n  if e.is_local_constant then\n    focus1 $ do (p, gs) \u2190 rcases_hint_core depth e, set_goals gs, pure p\n  else do\n    x \u2190 mk_fresh_name,\n    n \u2190 revert_kdependencies e semireducible,\n    tactic.generalize e x <|> (do\n      t \u2190 infer_type e,\n      tactic.assertv x t e,\n      get_local x >>= tactic.revert,\n      pure ()),\n    h \u2190 tactic.intro1,\n    focus1 $ do (p, gs) \u2190 rcases_hint_core depth h, set_goals gs, pure p\n\n/--\n* `rcases? \u27e8e1, e2, e3\u27e9` is like `rcases \u27e8e1, e2, e3\u27e9 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? \u27e8e1, e2, e3\u27e9 : 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\u03a0 rcases_patt) :=\ndo es \u2190 ps.mmap (\u03bb p, do\n    e \u2190 i_to_expr p,\n    if e.is_local_constant then pure e\n    else do\n      x \u2190 mk_fresh_name,\n      n \u2190 revert_kdependencies e semireducible,\n      tactic.generalize e x <|> (do\n        t \u2190 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) \u2190 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\u03a0 rcases_patt) :=\ndo l \u2190 intros,\n  focus1 $ do\n    (p, gs) \u2190 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\" | \"_\" | \"\u27e8\" (patt \",\")* patt \"\u27e9\" | \"(\" patt \")\"\n```\n-/\nmeta mutual def rcases_patt_parse, rcases_patt_parse_list, rcases_patt_parse_list_rest\nwith rcases_patt_parse : bool \u2192 parser rcases_patt\n| tt := with_desc \"patt_hi\" $\n  (brackets \"(\" \")\" (rcases_patt_parse ff)) <|>\n  (rcases_patt.tuple <$> brackets \"\u27e8\" \"\u27e9\" (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 \u2190 rcases_patt.alts' <$> rcases_patt_parse_list,\n  (tk \":\" *> pat.typed <$> texpr) <|> pure pat\n\nwith rcases_patt_parse_list : parser (list\u03a3 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 \u2192 parser (list\u03a3 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 \u2190 (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? \u27e8expr, ...\u27e9 (: n)?` calls `rcases_hint`\n* `rcases? \u27e8expr, ...\u27e9 (: n)?` calls `rcases_hint_many`\n* `rcases (h :)? expr (with patt)?` calls `rcases`\n* `rcases \u27e8expr, ...\u27e9 (with patt)?` calls `rcases_many`\n-/\n@[derive has_reflect]\nmeta inductive rcases_args\n| hint (tgt : pexpr \u2295 list pexpr) (depth : nat)\n| rcases (name : option name) (tgt : pexpr) (pat : rcases_patt)\n| rcases_many (tgt : list\u03a0 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 \u2190 (tk \"?\")?,\n  p \u2190 (sum.inr <$> brackets \"\u27e8\" \"\u27e9\" (sep_by (tk \",\") (parser.pexpr 0))) <|>\n      (sum.inl <$> texpr),\n  match hint with\n  | none := do\n    p \u2190 (do\n      sum.inl (expr.local_const h _ _ _) \u2190 pure p,\n      tk \":\" *> (@sum.inl _ (pexpr \u2295 list pexpr) \u2218 prod.mk h) <$> texpr) <|>\n      pure (sum.inr p),\n    ids \u2190 (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 \u2190 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\u03a0 rcases_patt)\n| x := (with_desc \"rintro_patt_hi\" $\n  brackets \"(\" \")\" (rintro_patt_parse tt) <|>\n  (do p \u2190 rcases_patt_parse tt, pure [p])) x\nwith rintro_patt_parse : bool \u2192 parser (list\u03a0 rcases_patt)\n| med := with_desc \"rintro_patt\" $ do\n  ll \u2190 rintro_patt_parse_hi*,\n  pats \u2190 match med, ll.join with\n  | tt, [] := failure\n  | tt, [pat] := do l \u2190 rcases_patt_parse_list_rest pat, pure [rcases_patt.alts' l]\n  | _, pats := pure pats\n  end,\n  (do tk \":\", e \u2190 texpr, pure (pats.map (\u03bb 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\u03a0 rcases_patt \u2295 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 \u2227 b \u2227 c \u2228 d` or\n`h2 : \u2203 x y, trans_rel R x y`. Usual usage might be `rcases h1 with \u27e8ha, hb, hc\u27e9 | hd` or\n`rcases h2 with \u27e8x, y, _ | \u27e8z, hxz, hzy\u27e9\u27e9` 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 `\u27e8p1, p2, p3\u27e9`, which matches a constructor with many arguments, or a series\n  of nested conjunctions or existentials. For example if the active hypothesis is `a \u2227 b \u2227 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 \u2228 b \u2228 c`.\n\nA pattern like `\u27e8a, b, c\u27e9 | \u27e8d, e\u27e9` 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 `\u27e8\u27e8a\u27e9, b | c\u27e9 | d` then these will cause more case splits as necessary.\nIf there are too many arguments, such as `\u27e8a, b, c\u27e9` for splitting on\n`\u2203 x, \u2203 y, p x`, then it will be treated as `\u27e8a, \u27e8b, c\u27e9\u27e9`, 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 \u2192 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) \u2190 match p with\n  | sum.inl p := prod.mk <$> pp p <*> rcases_hint p depth\n  | sum.inr ps := do\n    patts \u2190 rcases_hint_many ps depth,\n    pes \u2190 ps.mmap pp,\n    pure (format.bracket \"\u27e8\" \"\u27e9\" (format.comma_separated pes), rcases_patt.tuple patts)\n  end,\n  ppat \u2190 pp patt,\n  trace $ \u2191\"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 | \u27e8b, c\u27e9) \u27e8d, e\u27e9`\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 \u2192 tactic unit\n| (sum.inl []) := intros []\n| (sum.inl l)  := tactic.rintro l\n| (sum.inr depth) := do\n  ps \u2190 tactic.rintro_hint depth,\n  fs \u2190 ps.mmap (\u03bb p, do\n    f \u2190 pp $ p.format tt,\n    pure $ format.space ++ format.group f),\n  trace $ \u2191\"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 \u00d7 option pexpr) \u00d7 option (pexpr \u2295 list pexpr)) :=\nwith_desc \"patt? (: expr)? (:= expr)?\" $ do\n  (pat, tp) \u2190\n    (do pat \u2190 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 \"\u27e8\" \"\u27e9\" (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 \u27e8patt\u27e9 : type,\n{ ... }\n```\nis equivalent to\n```lean\nhave h : type,\n{ ... },\nrcases h with \u27e8patt\u27e9\n```\n\nThe syntax `obtain \u27e8patt\u27e9 : type := proof` is also supported.\n\nIf `\u27e8patt\u27e9` is omitted, `rcases` will try to infer the pattern.\n\nIf `type` is omitted, `:= proof` is required.\n-/\nmeta def obtain : parse obtain_parse \u2192 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 \u2190 mk_fresh_name,\n  e \u2190 to_expr tp >>= assert nm,\n  (g :: gs) \u2190 get_goals,\n  set_goals gs,\n  tactic.rcases none ``(%%e) (pat.get_or_else (rcases_patt.one `this)),\n  gs \u2190 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 \u27e8patt\u27e9? : type (:= val)?` or `obtain \u27e8patt\u27e9? (: 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\u2081 + ... + a\u2099` where `+ : \u03b1 \u2192 \u03b1 \u2192 \u03b1` 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 {\u03b1 : Type _} : List (DList \u03b1) \u2192 DList \u03b1\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 \u03b1)) : DList \u03b1 :=\n\u27e8fun xs => l.get ++ xs, fun t => by simp\u27e9\n#align dlist.lazy_of_list Std.DList.lazy_ofList\n\n@[simp]\ntheorem DList_singleton {\u03b1 : Type _} {a : \u03b1} : DList.singleton a = DList.lazy_ofList [a] :=\n  rfl\n#align dlist_singleton Std.DList_singleton\n\n@[simp]\ntheorem DList_lazy {\u03b1 : Type _} {l : List \u03b1} : 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 \u03b1) : 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 \u2964 D` then pulls\nsheaves on `D` back to sheaves on `C` via `G.op \u22d9 -`.\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 \u2964 Sheaf J A` for a\ncover-preserving and compatible-preserving functor `G : (C, J) \u2964 (D, K)`.\n* `category_theory.sites.pushforward`: the induced functor `Sheaf J A \u2964 Sheaf K A` for a\ncover-preserving and compatible-preserving functor `G : (C, J) \u2964 (D, K)`.\n* `category_theory.sites.pushforward`: the induced functor `Sheaf J A \u2964 Sheaf K A` for a\ncover-preserving and compatible-preserving functor `G : (C, J) \u2964 (D, K)`.\n\n## Main results\n\n- `category_theory.sites.whiskering_left_is_sheaf_of_cover_preserving`: If `G : C \u2964 D` is\ncover-preserving and compatible-preserving, then `G \u22d9 -` (`u\u1d56`) as a functor\n`(D\u1d52\u1d56 \u2964 A) \u2964 (C\u1d52\u1d56 \u2964 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\u2081 v\u2082 v\u2083 u\u2081 u\u2082 u\u2083\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\u2081} [category.{v\u2081} C] {D : Type u\u2082} [category.{v\u2082} D]\nvariables {A : Type u\u2083} [category.{v\u2083} A]\nvariables (J : grothendieck_topology C) (K : grothendieck_topology D)\nvariables {L : grothendieck_topology A}\n\n/--\nA functor `G : (C, J) \u2964 (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 \u2964 D) : Prop :=\n(cover_preserve : \u2200 {U : C} {S : sieve U} (hS : S \u2208 J U), S.functor_pushforward G \u2208 K (G.obj U))\n\n/-- The identity functor on a site is cover-preserving. -/\nlemma id_cover_preserving : cover_preserving J J (\ud835\udfed _) := \u27e8\u03bb U S hS, by simpa using hS\u27e9\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 \u22d9 G) := \u27e8\u03bb U S hS,\nbegin\n  rw sieve.functor_pushforward_comp,\n  exact hG.cover_preserve (hF.cover_preserve hS)\nend\u27e9\n\n/--\nA functor `G : (C, J) \u2964 (D, K)` between sites is called compatible preserving if for each\ncompatible family of elements at `C` and valued in `G.op \u22d9 \u2131`, and each commuting diagram\n`f\u2081 \u226b G.map g\u2081 = f\u2082 \u226b G.map g\u2082`, `x g\u2081` and `x g\u2082` coincide when restricted via `f\u1d62`.\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 \u2964 D) : Prop :=\n(compatible :\n  \u2200 (\u2131 : SheafOfTypes.{w} K) {Z} {T : presieve Z}\n    {x : family_of_elements (G.op \u22d9 \u2131.val) T} (h : x.compatible)\n    {Y\u2081 Y\u2082} {X} (f\u2081 : X \u27f6 G.obj Y\u2081) (f\u2082 : X \u27f6 G.obj Y\u2082) {g\u2081 : Y\u2081 \u27f6 Z} {g\u2082 : Y\u2082 \u27f6 Z}\n    (hg\u2081 : T g\u2081) (hg\u2082 : T g\u2082) (eq : f\u2081 \u226b G.map g\u2081 = f\u2082 \u226b G.map g\u2082),\n      \u2131.val.map f\u2081.op (x g\u2081 hg\u2081) = \u2131.val.map f\u2082.op (x g\u2082 hg\u2082))\n\nvariables {J K} {G : C \u2964 D} (hG : compatible_preserving.{w} K G) (\u2131 : SheafOfTypes.{w} K) {Z : C}\nvariables {T : presieve Z} {x : family_of_elements (G.op \u22d9 \u2131.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\u2081 Z\u2082 W g\u2081 g\u2082 f\u2081' f\u2082' H\u2081 H\u2082 eq,\n  unfold family_of_elements.functor_pushforward,\n  rcases get_functor_pushforward_structure H\u2081 with \u27e8X\u2081, f\u2081, h\u2081, hf\u2081, rfl\u27e9,\n  rcases get_functor_pushforward_structure H\u2082 with \u27e8X\u2082, f\u2082, h\u2082, hf\u2082, rfl\u27e9,\n  suffices : \u2131.val.map (g\u2081 \u226b h\u2081).op (x f\u2081 hf\u2081) = \u2131.val.map (g\u2082 \u226b h\u2082).op (x f\u2082 hf\u2082),\n    simpa using this,\n  apply hG.compatible \u2131 h _ _ hf\u2081 hf\u2082,\n  simpa using eq\nend\n\n@[simp] lemma compatible_preserving.apply_map {Y : C} {f : Y \u27f6 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\u2081 : get_functor_pushforward_structure (image_mem_functor_pushforward G T hf) with\n    \u27e8X, g, f', hg, eq\u27e9,\n  simpa using hG.compatible \u2131 h f' (\ud835\udfd9 _) hg hf (by simp[eq])\nend\n\nomit h hG\n\nopen limits.walking_cospan\n\nlemma compatible_preserving_of_flat {C : Type u\u2081} [category.{v\u2081} C] {D : Type u\u2081} [category.{v\u2081} D]\n  (K : grothendieck_topology D) (G : C \u2964 D) [representably_flat G] : compatible_preserving K G :=\nbegin\n  constructor,\n  intros \u2131 Z T x hx Y\u2081 Y\u2082 X f\u2081 f\u2082 g\u2081 g\u2082 hg\u2081 hg\u2082 e,\n\n  /- First, `f\u2081` and `f\u2082` form a cone over `cospan g\u2081 g\u2082 \u22d9 u`. -/\n  let c : cone (cospan g\u2081 g\u2082 \u22d9 G) :=\n    (cones.postcompose (diagram_iso_cospan (cospan g\u2081 g\u2082 \u22d9 G)).inv).obj\n      (pullback_cone.mk f\u2081 f\u2082 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 \u22d9 structured_arrow.pre _ _ _),\n  have eq\u2081 : f\u2081 = (c'.X.hom \u226b G.map (c'.\u03c0.app left).right) \u226b eq_to_hom (by simp),\n  { erw \u2190 (c'.\u03c0.app left).w, dsimp, simp },\n  have eq\u2082 : f\u2082 = (c'.X.hom \u226b G.map (c'.\u03c0.app right).right) \u226b eq_to_hom (by simp),\n  { erw \u2190 (c'.\u03c0.app right).w, dsimp, simp },\n  conv_lhs { rw eq\u2081 },\n  conv_rhs { rw eq\u2082 },\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'.\u03c0.naturality walking_cospan.hom.inl with _ e\u2081,\n  injection c'.\u03c0.naturality walking_cospan.hom.inr with _ e\u2082,\n  exact hx (c'.\u03c0.app left).right (c'.\u03c0.app right).right hg\u2081 hg\u2082 (e\u2081.symm.trans e\u2082)\nend\n\n/--\nIf `G` is cover-preserving and compatible-preserving,\nthen `G.op \u22d9 _` 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 \u2964 D} (hG\u2081 : compatible_preserving.{v\u2083} K G)\n  (hG\u2082 : cover_preserving J K G) (\u2131 : Sheaf K A) :\n  presheaf.is_sheaf J (G.op \u22d9 \u2131.val) :=\nbegin\n  intros X U S hS x hx,\n  change family_of_elements (G.op \u22d9 \u2131.val \u22d9 coyoneda.obj (op X)) _ at x,\n  let H := \u2131.2 X _ (hG\u2082.cover_preserve hS),\n  let hx' := hx.functor_pushforward hG\u2081 (sheaf_over \u2131 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\u2081.apply_map (sheaf_over \u2131 X) hx },\n  { intros y hy,\n    refine H.is_separated_for _ y _ _\n      (H.is_amalgamation (hx.functor_pushforward hG\u2081 (sheaf_over \u2131 X))),\n    rintros V f \u27e8Z, f', g', h, rfl\u27e9,\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\u2081.apply_map (sheaf_over \u2131 X) hx h, \u2190hy f' h] }\nend\n\n/-- The pullback of a sheaf along a cover-preserving and compatible-preserving functor. -/\ndef pullback_sheaf {G : C \u2964 D} (hG\u2081 : compatible_preserving K G)\n  (hG\u2082 : cover_preserving J K G) (\u2131 : Sheaf K A) : Sheaf J A :=\n\u27e8G.op \u22d9 \u2131.val, pullback_is_sheaf_of_cover_preserving hG\u2081 hG\u2082 \u2131\u27e9\n\nvariable (A)\n\n/--\nThe induced functor from `Sheaf K A \u2964 Sheaf J A` given by `G.op \u22d9 _`\nif `G` is cover-preserving and compatible-preserving.\n-/\n@[simps] def sites.pullback {G : C \u2964 D} (hG\u2081 : compatible_preserving K G)\n  (hG\u2082 : cover_preserving J K G) : Sheaf K A \u2964 Sheaf J A :=\n{ obj := \u03bb \u2131, pullback_sheaf hG\u2081 hG\u2082 \u2131,\n  map := \u03bb _ _ f, \u27e8(((whiskering_left _ _ _).obj G.op)).map f.val\u27e9,\n  map_id' := \u03bb \u2131, by { ext1, apply (((whiskering_left _ _ _).obj G.op)).map_id },\n  map_comp' := \u03bb _ _ _ 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\u2081} [small_category C] {D : Type v\u2081} [small_category D]\nvariables (A : Type u\u2082) [category.{v\u2081} 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\u2082 v\u2081 v\u2081}\n\n-- The assumptions so that we have sheafification\nvariables [concrete_category.{v\u2081} 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 \u2964 Sheaf K A` associated to a functor `G : C \u2964 D` in the\nsame direction as `G`. -/\n@[simps] def sites.pushforward (G : C \u2964 D) : Sheaf J A \u2964 Sheaf K A :=\nSheaf_to_presheaf J A \u22d9 Lan G.op \u22d9 presheaf_to_Sheaf K A\n\ninstance (G : C \u2964 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\u2082 v\u2081 v\u2081},\n    apply_instance }\nend\n\n/-- The pushforward functor is left adjoint to the pullback functor. -/\ndef sites.pullback_pushforward_adjunction {G : C \u2964 D} (hG\u2081 : compatible_preserving K G)\n  (hG\u2082 : cover_preserving J K G) : sites.pushforward A J K G \u22a3 sites.pullback A hG\u2081 hG\u2082 :=\n((Lan.adjunction A G.op).comp _ _ (sheafification_adjunction K A)).restrict_fully_faithful\n  (Sheaf_to_presheaf J A) (\ud835\udfed _)\n  (nat_iso.of_components (\u03bb _, iso.refl _)\n    (\u03bb _ _ _,(category.comp_id _).trans (category.id_comp _).symm))\n  (nat_iso.of_components (\u03bb _, iso.refl _)\n    (\u03bb _ _ _,(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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u2124 \u2115`\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 {\u03b1} [has_to_tactic_format \u03b1] (msg : string) (a : \u03b1) : tactic unit :=\nwhen_tracing `norm_cast $ do\na \u2190 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 \u2192 string\n| elim   := \"elim\"\n| move   := \"move\"\n| squash := \"squash\"\n\ninstance : has_to_string label := \u27e8label.to_string\u27e9\ninstance : has_repr label := \u27e8label.to_string\u27e9\nmeta instance : has_to_format label := \u27e8\u03bb l, l.to_string\u27e9\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 \u2192 \u2115\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 \u2192 tactic \u2115\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 \u2190 mk_local' n bi t,\n  count_coes $ e.instantiate_var l\n| e := do\n  as \u2190 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 \u2115 := do\nncoes \u2190 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) \u2190 open_pis ty,\n(lhs, rhs) \u2190 match ty with\n  | `(%%lhs = %%rhs) := pure (lhs, rhs)\n  | `(%%lhs \u2194 %%rhs) := pure (lhs, rhs)\n  | _ := fail \"norm_cast: lemma must be = or \u2194\"\n  end,\nlhs_coes \u2190 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 \u2190 count_internal_coes lhs,\nlet rhs_head_coes := count_head_coes rhs,\nrhs_internal_coes \u2190 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 \u2260 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 := \u27e8empty_cache\u27e9\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 \u2190 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 \u2190 infer_type e,\n  new_up \u2190 cache.up.add e tt,\n  new_down \u2190 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 \u2190 simp_lemmas.add cache.squash e,\n  new_down \u2190 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 \u2190 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 \u2190 mk_const decl,\n  param \u2190 get_label_param attr decl,\n  l \u2190 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 \u2265, > and \u2260 operators\nprivate lemma ge_from_le {\u03b1} [has_le \u03b1] : \u2200 (x y : \u03b1), x \u2265 y \u2194 y \u2264 x := \u03bb _ _, iff.rfl\nprivate lemma gt_from_lt {\u03b1} [has_lt \u03b1] : \u2200 (x y : \u03b1), x > y \u2194 y < x := \u03bb _ _, iff.rfl\nprivate lemma ne_from_not_eq {\u03b1} : \u2200 (x y : \u03b1), x \u2260 y \u2194 \u00ac(x = y) := \u03bb _ _, 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 \u2190 names.mfoldr (\u03bb name cache, add_lemma (attr ()) cache name) empty_cache,\n\n--some special lemmas to handle binary relations\nlet up := cache.up,\nup \u2190 up.add_simp ``ge_from_le,\nup \u2190 up.add_simp ``gt_from_lt,\nup \u2190 up.add_simp ``ne_from_not_eq,\n\nlet down := cache.down,\ndown \u2190 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 \u2190 (label.of_string \u2218 to_string) <$> ident, return l)\n      <|> return none,\n  after_set := some (\u03bb decl prio persistent, do\n    param \u2190 get_label_param norm_cast_attr decl,\n    match param with\n    | some l :=\n      when (l \u2260 elim) $ simp_attr.push_cast.set decl () tt\n    | none := do\n      e \u2190 mk_const decl,\n      ty \u2190 infer_type e,\n      l \u2190 classify_type ty,\n      norm_cast_attr.set decl l persistent prio\n    end),\n  before_unset := some $ \u03bb _ _, 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 \u2190 mk_const decl,\n  ty \u2190 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 \u2190 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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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', _) \u2190 simplify s [] a {fail_if_unchanged := ff},\n(b', b_b', _) \u2190 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 \u2190 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 \u2190 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 (\u2191(x : \u03b1) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nis rewritten to:            op (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nwhen (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) = (\u2191(x : \u03b1) : \u03b3) can be proven with a squash lemma\n-/\nmeta def splitting_procedure : expr \u2192 tactic (expr \u00d7 expr)\n| (app (app op x) y) :=\n(do\n  `(@coe %%\u03b1 %%\u03b4 %%coe1 %%xx) \u2190 return x,\n  `(@coe %%\u03b2 %%\u03b3 %%coe2 %%yy) \u2190 return y,\n  success_if_fail $ is_def_eq \u03b1 \u03b2,\n  is_def_eq \u03b4 \u03b3,\n\n  (do\n    coe3 \u2190 mk_app `has_lift_t [\u03b1, \u03b2] >>= mk_instance_fast,\n    new_x \u2190 to_expr ``(@coe %%\u03b2 %%\u03b4 %%coe2 (@coe %%\u03b1 %%\u03b2 %%coe3 %%xx)),\n    let new_e := app (app op new_x) y,\n    eq_x \u2190 prove_eq_using_down x new_x,\n    pr \u2190 mk_congr_arg op eq_x,\n    pr \u2190 mk_congr_fun pr y,\n    return (new_e, pr)\n  ) <|> (do\n    coe3 \u2190 mk_app `has_lift_t [\u03b2, \u03b1] >>= mk_instance_fast,\n    new_y \u2190 to_expr ``(@coe %%\u03b1 %%\u03b4 %%coe1 (@coe %%\u03b2 %%\u03b1 %%coe3 %%yy)),\n    let new_e := app (app op x) new_y,\n    eq_y \u2190 prove_eq_using_down y new_y,\n    pr \u2190 mk_congr_arg (app op x) eq_y,\n    return (new_e, pr)\n  )\n) <|> (do\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return x,\n  `(@has_one.one %%\u03b2 %%h1) \u2190 return y,\n  h2 \u2190 to_expr ``(has_one %%\u03b1) >>= mk_instance_fast,\n  new_y \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_one.one %%\u03b1 %%h2)),\n  eq_y \u2190 prove_eq_using_down y new_y,\n  let new_e := app (app op x) new_y,\n  pr \u2190 mk_congr_arg (app op x) eq_y,\n  return (new_e, pr)\n ) <|> (do\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return x,\n  `(@has_zero.zero %%\u03b2 %%h1) \u2190 return y,\n  h2 \u2190 to_expr ``(has_zero %%\u03b1) >>= mk_instance_fast,\n  new_y \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_zero.zero %%\u03b1 %%h2)),\n  eq_y \u2190 prove_eq_using_down y new_y,\n  let new_e := app (app op x) new_y,\n  pr \u2190 mk_congr_arg (app op x) eq_y,\n  return (new_e, pr)\n) <|> (do\n  `(@has_one.one %%\u03b2 %%h1) \u2190 return x,\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return y,\n  h1 \u2190 to_expr ``(has_one %%\u03b1) >>= mk_instance_fast,\n  new_x \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_one.one %%\u03b1 %%h1)),\n  eq_x \u2190 prove_eq_using_down x new_x,\n  let new_e := app (app op new_x) y,\n  pr \u2190 mk_congr_arg (lam `x binder_info.default \u03b2 (app (app op (var 0)) y)) eq_x,\n  return (new_e, pr)\n) <|> (do\n  `(@has_zero.zero %%\u03b2 %%h1) \u2190 return x,\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return y,\n  h1 \u2190 to_expr ``(has_zero %%\u03b1) >>= mk_instance_fast,\n  new_x \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_zero.zero %%\u03b1 %%h1)),\n  eq_x \u2190 prove_eq_using_down x new_x,\n  let new_e := app (app op new_x) y,\n  pr \u2190 mk_congr_arg (lam `x binder_info.default \u03b2 (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 \u00d7 expr) :=\n(do\n  r \u2190 mcond (is_prop e) (return `iff) (return `eq),\n  (new_e, pr) \u2190 s.rewrite e prove r,\n  pr \u2190 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 : \u03b1)` to `((n : \u2115) : \u03b1)` where `n` is a numeral and `\u03b1 \u2260 \u2115`.\nReturns a pair of the new expression and proof that they are equal.\n-/\nmeta def numeral_to_coe (e : expr) : tactic (expr \u00d7 expr) :=\ndo\n  \u03b1 \u2190 infer_type e,\n  success_if_fail $ is_def_eq \u03b1 `(\u2115),\n  n \u2190 e.to_nat,\n  h1 \u2190 mk_app `has_lift_t [`(\u2115), \u03b1] >>= mk_instance_fast,\n  let new_e : expr := reflect n,\n  new_e \u2190 to_expr ``(@coe \u2115 %%\u03b1 %%h1 %%new_e),\n  pr \u2190 prove_eq_using_down e new_e,\n  return (new_e, pr)\n\n/--\nIf possible, rewrite `((n : \u2115) : \u03b1)` to `(n : \u03b1)` 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 \u00d7 expr) :=\ndo\n  `(@coe \u2115 %%\u03b1 %%h1 %%e') \u2190 return e,\n  n \u2190 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 \u2190 expr.of_nat \u03b1 n,\n  pr \u2190 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' {\u03b1} (a : \u03b1) (pre : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr))\n  (e : expr) (cfg : simp_config := {}) : tactic (\u03b1 \u00d7 expr \u00d7 expr) :=\next_simplify_core a cfg simp_lemmas.mk (\u03bb _, failed)\n  (\u03bb a _ _ _ e, do\n    (new_a, new_e, pr) \u2190 pre a e,\n    guard (\u00ac new_e =\u2090 e),\n    return (new_a, new_e, some pr, ff))\n  (\u03bb _ _ _ _ _, failed)\n  `eq e\n\n/--\nThe core simplification routine of `norm_cast`.\n-/\nmeta def derive (e : expr) : tactic (expr \u00d7 expr) :=\ndo\n  cache \u2190 norm_cast_attr.get_cache,\n  e \u2190 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) \u2190 simplify_top_down' () (\u03bb _ 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) \u2190 simplify_bottom_up () (\u03bb _ 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, _) \u2190 simplify cache.squash [] e2 cfg,\n  trace_norm_cast \"after squashing: \" e3,\n\n  -- step 4: post-processing of numerals\n  ((), e4, pr4) \u2190 simplify_top_down' () (\u03bb _ 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 (\u00ac new_e =\u2090 e),\n  pr \u2190 mk_eq_trans pr1 pr2,\n  pr \u2190 mk_eq_trans pr pr3,\n  pr \u2190 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 \u00d7 expr) :=\ndo (s, _) \u2190 mk_simp_set tt [`push_cast] extra_lems,\n   (e, prf, _) \u2190 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 \u2190 get_local lc,\n  replace_at derive [e] include_goal,\n  get_local lc\n| e := do\n  t \u2190 infer_type e,\n  e \u2190 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 \u2190 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 \u00d7 expr)) :=\ndecorate_error \"apply_mod_cast failed:\" $ do\n  new_e \u2190 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 \u2190 local_context,\n  try_lst $ ctx.map (\u03bb 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 \u2190 loc.get_locals,\n  tt \u2190 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 (\u00ac 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 \u2190 loc.get_locals,\n  monad.mapm' (\u03bb r : rw_rule, do\n    save_info r.pos,\n    replace_at derive ns loc.include_goal,\n    rw \u27e8[r], none\u27e9 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 \u2190 i_to_expr e <|> do {\n    ty \u2190 target,\n    e \u2190 i_to_expr_strict ``(%%e : %%ty),\n    pty \u2190 pp ty, ptgt \u2190 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 \u2190 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 {\u03b1 \u03b2} [has_lift_t \u03b1 \u03b2]\n  {c : Prop} [decidable c] {a b : \u03b1} :\n  \u2191(ite c a b) = ite c (\u2191a : \u03b2) (\u2191b : \u03b2) :=\nby by_cases h : c; simp [h]\n\n@[norm_cast] lemma dite_cast {\u03b1 \u03b2} [has_lift_t \u03b1 \u03b2]\n  {c : Prop} [decidable c] {a : c \u2192 \u03b1} {b : \u00ac c \u2192 \u03b1} :\n  \u2191(dite c a b) = dite c (\u03bb h, (\u2191(a h) : \u03b2)) (\u03bb h, (\u2191(b h) : \u03b2)) :=\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 : \u2124\nh : \u2191a + \u2191b < (10 : \u211a)\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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 `\u2191`, `\u21d1` and `\u21a5`, 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 : \u2115} : (\u2191m : \u2124) = \u2191n \u2194 m = n\n\n@[norm_cast] theorem coe_int_denom (n : \u2124) : (n : \u211a).denom = 1\n\n@[norm_cast] theorem cast_id : \u2200 n : \u211a, \u2191n = n\n\n@[norm_cast] theorem coe_nat_add (m n : \u2115) : (\u2191(m + n) : \u2124) = \u2191m + \u2191n\n\n@[norm_cast] theorem cast_sub [add_group \u03b1] [has_one \u03b1] {m n} (h : m \u2264 n) :\n  ((n - m : \u2115) : \u03b1) = n - m\n\n@[norm_cast] theorem coe_nat_bit0 (n : \u2115) : (\u2191(bit0 n) : \u2124) = bit0 \u2191n\n\n@[norm_cast] theorem cast_coe_nat (n : \u2115) : ((n : \u2124) : \u03b1) = n\n\n@[norm_cast] theorem cast_one : ((1 : \u211a) : \u03b1) = 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 : \u2115) : (n : \u2102).re = n :=\nby rw [\u2190 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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": "open Lean.Parser.Tactic in\nmacro \"rw0\" s:rwRuleSeq : tactic =>\n  `(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": "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/rwWithoutOffsetCnstrs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.08269733815352048, "lm_q1q2_score": 0.03337390457090661}}
{"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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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    \u27e8fun 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 \u2190 aux_attr.get_param_untyped n'\n          pure <| dict n param)\n        mk_name_map,\n      []\u27e9\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 `\u2115` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nunsafe def ignore_args_attr : user_attribute (name_map <| List \u2115) (List \u2115)\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    \u27e8fun ns =>\n      ns.foldlM\n        (fun dict n => do\n          let param \u2190 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      []\u27e9\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 `\u2115 \u00d7 \u03b1`\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 \u2115) \u2115\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    \u27e8fun ns =>\n      ns.foldlM\n        (fun dict n => do\n          let param \u2190 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      []\u27e9\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 \u2115) (List \u2115)\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    \u27e8fun ns =>\n      ns.foldlM\n        (fun dict n => do\n          let param \u2190 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      []\u27e9\n  parser := do\n    let l \u2190 parser.many lean.parser.small_nat\n    guard (l (\u00b7 \u2260 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 \u2115 := do\n  let d \u2190 get_decl nm\n  let (es, _) := d.type.pi_binders\n  let l \u2190\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 \u2190 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 \u2192 String \u2192 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 \u2192 List String \u2192 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 \u2192 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 \u2260 Name.anonymous \u2228 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 \u2260 tgt_auto \u2228 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 \u2227 tgt \u2260 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 \u2190 Option.isSome <$> parser.optional (tk \"!\")\n  let ques \u2190 Option.isSome <$> parser.optional (tk \"?\")\n  let tgt \u2190 parser.optional ident\n  let e \u2190 parser.optional texpr\n  let doc \u2190\n    match e with\n      | some pe => some <$> (to_expr pe >>= eval_expr String : tactic String)\n      | none => pure none\n  return \u27e8bang, ques, tgt Name.anonymous, doc, ff\u27e9\n#align to_additive.parser to_additive.parser\n\nprivate unsafe def proceed_fields_aux (src tgt : Name) (prio : \u2115)\n    (f : Name \u2192 tactic (List String)) : Tactic := do\n  let src_fields \u2190 f src\n  let tgt_fields \u2190 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 : \u2115) : 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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 \u00d7 N) := \u27e8\u03bb p q, \u27e8p.1 * q.1, p.2 * q.2\u27e9\u27e9\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 \u2115 n m` (i.e. `(n * m : \u2115)`) will not change to `+`, since its\n  first argument is `\u2115`, an identifier not applied to any arguments.\n* `@has_mul.mul (\u03b1 \u00d7 \u03b2) x y` will change to `+`. It's first argument contains only the identifier\n  `prod`, but this is applied to arguments, `\u03b1` and `\u03b2`.\n* `@has_mul.mul (\u03b1 \u00d7 \u2124) x y` will not change to `+`, since its first argument contains `\u2124`.\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 `\u21a5Semigroup` is replaced by addition in `\u21a5AddSemigroup`.\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 : \u2115\u221e)` can contain `\u2115`\n  (usually in the form `has_top.top \u2115 ...`) and still be additivized.\n  So `@has_mul.mul (C^\u221e\u27eeI, N; I', G\u27ef) _ 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 `\u2115` or `\u211d`. 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 `\u2115` or `\u211d`. Solutions:\n  * If the fixed type has an additive counterpart (like `\u21a5Semigroup`), 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 \u201cmain\u201d 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 \u201cmain\u201d 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 (\u201cmul\u201d, \u201cone\u201d, \u201cinv\u201d, \u201cprod\u201d) 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 \u2190 get_env\n      let val \u2190 attr.get_param src\n      let dict \u2190 aux_attr.get_cache\n      let ignore \u2190 ignore_args_attr.get_cache\n      let relevant \u2190 relevant_arg_attr.get_cache\n      let reorder \u2190 reorder_attr.get_cache\n      let tgt \u2190 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 \u2190 first_multiplicative_arg src\n      when (first_mult_arg \u2260 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 \u2190 tactic.alias.get_alias_target src |\n                skip\n              let alias_name := alias_target\n              let some add_alias_name \u2190 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 \u2190 to_additive.aux_attr.get_cache\n    match dict mul_name with\n      | some add_name => do\n        let mul_doc \u2190 try_core <| doc_string mul_name\n        let add_doc \u2190 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 (\u03b1 : Type u) where\n  apply : List \u03b1 \u2192 List \u03b1\n  invariant : \u2200 (l : List \u03b1), apply l = apply [] ++ l\n\nnamespace dlist\n\n\n/-- Convert a list to a dlist -/\ndef of_list {\u03b1 : Type u} (l : List \u03b1) : dlist \u03b1 := mk (append l) sorry\n\n/-- Convert a lazily-evaluated list to a dlist -/\ndef lazy_of_list {\u03b1 : Type u} (l : thunk (List \u03b1)) : dlist \u03b1 :=\n  mk (fun (xs : List \u03b1) => l Unit.unit ++ xs) sorry\n\n/-- Convert a dlist to a list -/\ndef to_list {\u03b1 : Type u} : dlist \u03b1 \u2192 List \u03b1 := sorry\n\n/--  Create a dlist containing no elements -/\ndef empty {\u03b1 : Type u} : dlist \u03b1 := mk id sorry\n\n/-- Create dlist with a single element -/\ndef singleton {\u03b1 : Type u} (x : \u03b1) : dlist \u03b1 := mk (List.cons x) sorry\n\n/-- `O(1)` Prepend a single element to a dlist -/\ndef cons {\u03b1 : Type u} (x : \u03b1) : dlist \u03b1 \u2192 dlist \u03b1 := sorry\n\n/-- `O(1)` Append a single element to a dlist -/\ndef concat {\u03b1 : Type u} (x : \u03b1) : dlist \u03b1 \u2192 dlist \u03b1 := sorry\n\n/-- `O(1)` Append dlists -/\nprotected def append {\u03b1 : Type u} : dlist \u03b1 \u2192 dlist \u03b1 \u2192 dlist \u03b1 := sorry\n\nprotected instance has_append {\u03b1 : Type u} : Append (dlist \u03b1) := { append := dlist.append }\n\ntheorem to_list_of_list {\u03b1 : Type u} (l : List \u03b1) : to_list (of_list l) = l := sorry\n\ntheorem of_list_to_list {\u03b1 : Type u} (l : dlist \u03b1) : of_list (to_list l) = l := sorry\n\ntheorem to_list_empty {\u03b1 : Type u} : to_list empty = [] := sorry\n\ntheorem to_list_singleton {\u03b1 : Type u} (x : \u03b1) : to_list (singleton x) = [x] := sorry\n\ntheorem to_list_append {\u03b1 : Type u} (l\u2081 : dlist \u03b1) (l\u2082 : dlist \u03b1) :\n    to_list (l\u2081 ++ l\u2082) = to_list l\u2081 ++ to_list l\u2082 :=\n  sorry\n\ntheorem to_list_cons {\u03b1 : Type u} (x : \u03b1) (l : dlist \u03b1) : to_list (cons x l) = x :: to_list l :=\n  sorry\n\ntheorem to_list_concat {\u03b1 : Type u} (x : \u03b1) (l : dlist \u03b1) :\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\u00f6lzl, 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 (\u03b1 \u03b2 : Type u_1) => map \u2218 function.const \u03b2 }\n\n@[simp] theorem fmap_def {\u03b1' : Type u_1} {\u03b2' : Type u_1} {s : multiset \u03b1'} (f : \u03b1' \u2192 \u03b2') : f <$> s = map f s :=\n  rfl\n\nprotected instance is_lawful_functor : is_lawful_functor multiset := sorry\n\ndef traverse {F : Type u \u2192 Type u} [Applicative F] [is_comm_applicative F] {\u03b1' : Type u} {\u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2') : multiset \u03b1' \u2192 F (multiset \u03b2') :=\n  quotient.lift (Functor.map coe \u2218 traverse f) sorry\n\nprotected instance monad : Monad multiset :=\n  { toApplicative :=\n      { toFunctor := { map := Functor.map, mapConst := Functor.mapConst },\n        toPure := { pure := fun (\u03b1 : Type u_1) (x : \u03b1) => x ::\u2098 0 },\n        toSeq :=\n          { seq := fun (\u03b1 \u03b2 : Type u_1) (f : multiset (\u03b1 \u2192 \u03b2)) (x : multiset \u03b1) => bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : multiset \u03b1) (b : multiset \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : multiset (\u03b1 \u2192 \u03b2)) (x : multiset \u03b1) => bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x) \u03b2 \u03b1\n                  (map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : multiset \u03b1) (b : multiset \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : multiset (\u03b1 \u2192 \u03b2)) (x : multiset \u03b1) => bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x) \u03b2 \u03b2\n                  (map (function.const \u03b1 id) a) b } },\n    toBind := { bind := bind } }\n\n@[simp] theorem pure_def {\u03b1 : Type u_1} : pure = fun (x : \u03b1) => x ::\u2098 0 :=\n  rfl\n\n@[simp] theorem bind_def {\u03b1 : Type u_1} {\u03b2 : Type u_1} : bind = bind :=\n  rfl\n\nprotected instance is_lawful_monad : is_lawful_monad multiset := sorry\n\n@[simp] theorem lift_beta {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : List \u03b1) (f : List \u03b1 \u2192 \u03b2) (h : \u2200 (a b : List \u03b1), a \u2248 b \u2192 f a = f b) : quotient.lift f h \u2191x = f x :=\n  quotient.lift_beta f h x\n\n@[simp] theorem map_comp_coe {\u03b1 : Type u_1} {\u03b2 : Type u_1} (h : \u03b1 \u2192 \u03b2) : Functor.map h \u2218 coe = coe \u2218 Functor.map h := sorry\n\ntheorem id_traverse {\u03b1 : Type u_1} (x : multiset \u03b1) : traverse id.mk x = x := sorry\n\ntheorem comp_traverse {G : Type u_1 \u2192 Type u_1} {H : Type u_1 \u2192 Type u_1} [Applicative G] [Applicative H] [is_comm_applicative G] [is_comm_applicative H] {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (g : \u03b1 \u2192 G \u03b2) (h : \u03b2 \u2192 H \u03b3) (x : multiset \u03b1) : traverse (functor.comp.mk \u2218 Functor.map h \u2218 g) x = functor.comp.mk (traverse h <$> traverse g x) := sorry\n\ntheorem map_traverse {G : Type u_1 \u2192 Type u_1} [Applicative G] [is_comm_applicative G] {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (g : \u03b1 \u2192 G \u03b2) (h : \u03b2 \u2192 \u03b3) (x : multiset \u03b1) : Functor.map h <$> traverse g x = traverse (Functor.map h \u2218 g) x := sorry\n\ntheorem traverse_map {G : Type u_1 \u2192 Type u_1} [Applicative G] [is_comm_applicative G] {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 G \u03b3) (x : multiset \u03b1) : traverse h (map g x) = traverse (h \u2218 g) x := sorry\n\ntheorem naturality {G : Type u_1 \u2192 Type u_1} {H : Type u_1 \u2192 Type u_1} [Applicative G] [Applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 G \u03b2) (x : multiset \u03b1) : coe_fn eta (multiset \u03b2) (traverse f x) = traverse (coe_fn eta \u03b2 \u2218 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\n-/\nimport tactic.doc_commands\n\n/-!\n# `generalize_proofs`\n\nA simple tactic to find and replace all occurrences of proof terms in the\ncontext and goal with new variables.\n-/\n\nopen interactive interactive.types lean.parser\n\nnamespace tactic\n\nprivate meta def collect_proofs_in :\n  expr \u2192 list expr \u2192 list name \u00d7 list expr \u2192 tactic (list name \u00d7 list expr)\n| e ctx (ns, hs) :=\nlet go (tac : list name \u00d7 list expr \u2192 tactic (list name \u00d7 list expr)) :\n  tactic (list name \u00d7 list expr) :=\ndo t \u2190 infer_type e,\n   mcond (is_prop t) (do\n     first (hs.map $ \u03bb h, do\n       t' \u2190 infer_type h,\n       is_def_eq t t',\n       g \u2190 target,\n       change $ g.replace (\u03bb a n, if a = e then some h else none),\n       return (ns, hs)) <|>\n     (let (n, ns) := (match ns with\n        | [] := (`_x, [])\n        | (n :: ns) := (n, ns)\n        end : name \u00d7 list name) in\n      do generalize e n,\n         h \u2190 intro n,\n         return (ns, h::hs)) <|> return (ns, hs)) (tac (ns, hs)) in\nmatch e with\n| expr.const _ _ := go return\n| expr.local_const _ _ _ _ := do t \u2190 infer_type e, collect_proofs_in t ctx (ns, hs)\n| expr.mvar _ _ _ := do\n  e \u2190 instantiate_mvars e,\n  match e with\n  | expr.mvar _ _ _ := do t \u2190 infer_type e, collect_proofs_in t ctx (ns, hs)\n  | _ := collect_proofs_in e ctx (ns, hs)\n  end\n| expr.app f x :=\n  go (\u03bb nh, collect_proofs_in f ctx nh >>= collect_proofs_in x ctx)\n| expr.lam n b d e :=\n  go (\u03bb nh, do\n    nh \u2190 collect_proofs_in d ctx nh,\n    var \u2190 mk_local' n b d,\n    collect_proofs_in (expr.instantiate_var e var) (var::ctx) nh)\n| expr.pi n b d e := do\n  nh \u2190 collect_proofs_in d ctx (ns, hs),\n  var \u2190 mk_local' n b d,\n  collect_proofs_in (expr.instantiate_var e var) (var::ctx) nh\n| expr.elet n t d e :=\n  go (\u03bb nh, do\n    nh \u2190 collect_proofs_in t ctx nh,\n    nh \u2190 collect_proofs_in d ctx nh,\n    collect_proofs_in (expr.instantiate_var e d) ctx nh)\n| expr.macro m l :=\n  go (\u03bb nh, mfoldl (\u03bb x e, collect_proofs_in e ctx x) nh l)\n| _ := return (ns, hs)\nend\n\n/-- Generalize proofs in the goal, naming them with the provided list. -/\nmeta def generalize_proofs (ns : list name) (loc : interactive.loc) : tactic unit :=\ndo intros_dep,\n  hs \u2190 local_context >>= mfilter is_proof,\n  n \u2190 loc.get_locals >>= revert_lst,\n  t \u2190 target,\n  collect_proofs_in t [] (ns, hs),\n  intron n <|> (intros $> ())\n\nlocal postfix (name := parser.many) *:9001 := many\n\nnamespace interactive\n/-- Generalize proofs in the goal, naming them with the provided list.\n\nFor example:\n```lean\nexample : list.nth_le [1, 2] 1 dec_trivial = 2 :=\nbegin\n  -- \u22a2 [1, 2].nth_le 1 _ = 2\n  generalize_proofs h,\n  -- h : 1 < [1, 2].length\n  -- \u22a2 [1, 2].nth_le 1 h = 2\nend\n```\n-/\nmeta def generalize_proofs : parse ident_* \u2192 parse location \u2192 tactic unit :=\ntactic.generalize_proofs\nend interactive\n\nadd_tactic_doc\n{ name       := \"generalize_proofs\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize_proofs],\n  tags       := [\"context management\"] }\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/generalize_proofs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.10230470857690285, "lm_q1q2_score": 0.03317080800306216}}
{"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-/\nprelude\nimport Init.Data.Nat.Basic\nimport Init.Data.Fin.Basic\nimport Init.Data.UInt\nimport Init.Data.Repr\nimport Init.Data.ToString.Basic\nimport Init.Util\nuniverse u v w\n\nnamespace Array\nvariable {\u03b1 : Type u}\n\n@[extern \"lean_mk_array\"]\ndef mkArray {\u03b1 : Type u} (n : Nat) (v : \u03b1) : Array \u03b1 := {\n  data := List.replicate n v\n}\n\n@[simp] theorem size_mkArray (n : Nat) (v : \u03b1) : (mkArray n v).size = n :=\n  List.length_replicate ..\n\ninstance : EmptyCollection (Array \u03b1) := \u27e8Array.empty\u27e9\ninstance : Inhabited (Array \u03b1) where\n  default := Array.empty\n\ndef isEmpty (a : Array \u03b1) : Bool :=\n  a.size = 0\n\ndef singleton (v : \u03b1) : Array \u03b1 :=\n  mkArray 1 v\n\n/- Low-level version of `fget` which is as fast as a C array read.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fget` may be slightly slower than `uget`. -/\n@[extern \"lean_array_uget\"]\ndef uget (a : @& Array \u03b1) (i : USize) (h : i.toNat < a.size) : \u03b1 :=\n  a.get \u27e8i.toNat, h\u27e9\n\ndef back [Inhabited \u03b1] (a : Array \u03b1) : \u03b1 :=\n  a.get! (a.size - 1)\n\ndef get? (a : Array \u03b1) (i : Nat) : Option \u03b1 :=\n  if h : i < a.size then some (a.get \u27e8i, h\u27e9) else none\n\ndef back? (a : Array \u03b1) : Option \u03b1 :=\n  a.get? (a.size - 1)\n\n-- auxiliary declaration used in the equation compiler when pattern matching array literals.\nabbrev getLit {\u03b1 : Type u} {n : Nat} (a : Array \u03b1) (i : Nat) (h\u2081 : a.size = n) (h\u2082 : i < n) : \u03b1 :=\n  a.get \u27e8i, h\u2081.symm \u25b8 h\u2082\u27e9\n\n@[simp] theorem size_set (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : (set a i v).size = a.size :=\n  List.length_set ..\n\n@[simp] theorem size_push (a : Array \u03b1) (v : \u03b1) : (push a v).size = a.size + 1 :=\n  List.length_concat ..\n\n/- Low-level version of `fset` which is as fast as a C array fset.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fset` may be slightly slower than `uset`. -/\n@[extern \"lean_array_uset\"]\ndef uset (a : Array \u03b1) (i : USize) (v : \u03b1) (h : i.toNat < a.size) : Array \u03b1 :=\n  a.set \u27e8i.toNat, h\u27e9 v\n\n@[extern \"lean_array_fswap\"]\ndef swap (a : Array \u03b1) (i j : @& Fin a.size) : Array \u03b1 :=\n  let v\u2081 := a.get i\n  let v\u2082 := a.get j\n  let a'  := a.set i v\u2082\n  a'.set (size_set a i v\u2082 \u25b8 j) v\u2081\n\n@[extern \"lean_array_swap\"]\ndef swap! (a : Array \u03b1) (i j : @& Nat) : Array \u03b1 :=\n  if h\u2081 : i < a.size then\n  if h\u2082 : j < a.size then swap a \u27e8i, h\u2081\u27e9 \u27e8j, h\u2082\u27e9\n  else panic! \"index out of bounds\"\n  else panic! \"index out of bounds\"\n\n@[inline] def swapAt (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  let e := a.get i\n  let a := a.set i v\n  (e, a)\n\n@[inline]\ndef swapAt! (a : Array \u03b1) (i : Nat) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  if h : i < a.size then\n    swapAt a \u27e8i, h\u27e9 v\n  else\n    have : Inhabited \u03b1 := \u27e8v\u27e9\n    panic! (\"index \" ++ toString i ++ \" out of bounds\")\n\n@[extern \"lean_array_pop\"]\ndef pop (a : Array \u03b1) : Array \u03b1 := {\n  data := a.data.dropLast\n}\n\ndef shrink (a : Array \u03b1) (n : Nat) : Array \u03b1 :=\n  let rec loop\n    | 0,   a => a\n    | n+1, a => loop n a.pop\n  loop (a.size - n) a\n\n@[inline]\ndef modifyM [Monad m] [Inhabited \u03b1] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 m \u03b1) : m (Array \u03b1) := do\n  if h : i < a.size then\n    let idx : Fin a.size := \u27e8i, h\u27e9\n    let v                := a.get idx\n    let a'               := a.set idx arbitrary\n    let v \u2190 f v\n    pure <| a'.set (size_set a .. \u25b8 idx) v\n  else\n    pure a\n\n@[inline]\ndef modify [Inhabited \u03b1] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  Id.run <| a.modifyM i f\n\n@[inline]\ndef modifyOp [Inhabited \u03b1] (self : Array \u03b1) (idx : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  self.modify idx f\n\n/-\n  We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime.\n\n  This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/\n@[inline] unsafe def forInUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] loop (i : USize) (b : \u03b2) : m \u03b2 := do\n    if i < sz then\n      let a := as.uget i lcProof\n      match (\u2190 f a b) with\n      | ForInStep.done  b => pure b\n      | ForInStep.yield b => loop (i+1) b\n    else\n      pure b\n  loop 0 b\n\n-- Move?\nprivate theorem zeroLtOfLt : {a b : Nat} \u2192 a < b \u2192 0 < b\n  | 0,   _, h => h\n  | a+1, b, h =>\n    have : a < b := Nat.ltTrans (Nat.ltSuccSelf _) h\n    zeroLtOfLt this\n\n/- Reference implementation for `forIn` -/\n@[implementedBy Array.forInUnsafe]\nprotected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec loop (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    match i, h with\n    | 0,   _ => pure b\n    | i+1, h =>\n      have h' : i < as.size            := Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h\n      have : as.size - 1 < as.size     := Nat.subLt (zeroLtOfLt h') (by decide)\n      have : as.size - 1 - i < as.size := Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this\n      match (\u2190 f (as.get \u27e8as.size - 1 - i, this\u27e9) b) with\n      | ForInStep.done b  => pure b\n      | ForInStep.yield b => loop i (Nat.leOfLt h') b\n  loop as.size (Nat.leRefl _) b\n\ninstance : ForIn m (Array \u03b1) \u03b1 where\n  forIn := Array.forIn\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def foldlMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i+1) stop (\u2190 f b (as.uget i lcProof))\n  if start < stop then\n    if stop \u2264 as.size then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else\n    pure init\n\n/- Reference implementation for `foldlM` -/\n@[implementedBy foldlMUnsafe]\ndef foldlM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let fold (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) (b : \u03b2) : m \u03b2 := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure b\n        | i'+1 =>\n          loop i' (j+1) (\u2190 f b (as.get \u27e8j, Nat.ltOfLtOfLe hlt h\u27e9))\n      else\n        pure b\n    loop (stop - start) start init\n  if h : stop \u2264 as.size then\n    fold stop h\n  else\n    fold as.size (Nat.leRefl _)\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def foldrMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i-1) stop (\u2190 f (as.uget (i-1) lcProof) b)\n  if start \u2264 as.size then\n    if stop < start then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else if stop < as.size then\n    fold (USize.ofNat as.size) (USize.ofNat stop) init\n  else\n    pure init\n\n/- Reference implementation for `foldrM` -/\n@[implementedBy foldrMUnsafe]\ndef foldrM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec fold (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else match i, h with\n      | 0, _   => pure b\n      | i+1, h =>\n        have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h\n        fold i (Nat.leOfLt this) (\u2190 f (as.get \u27e8i, this\u27e9) b)\n  if h : start \u2264 as.size then\n    if stop < start then\n      fold start h init\n    else\n      pure init\n  else if stop < as.size then\n    fold as.size (Nat.leRefl _) init\n  else\n    pure init\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def mapMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do\n    if i < sz then\n     let v    := r.uget i lcProof\n     let r    := r.uset i arbitrary lcProof\n     let vNew \u2190 f (unsafeCast v)\n     map (i+1) (r.uset i (unsafeCast vNew) lcProof)\n    else\n     pure (unsafeCast r)\n  unsafeCast <| map 0 (unsafeCast as)\n\n/- Reference implementation for `mapM` -/\n@[implementedBy mapMUnsafe]\ndef mapM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (fun bs a => do let b \u2190 f a; pure (bs.push b)) (mkEmpty as.size)\n\n@[inline]\ndef mapIdxM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 m \u03b2) : m (Array \u03b2) :=\n  let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array \u03b2) : m (Array \u03b2) := do\n    match i, inv with\n    | 0,    _  => pure bs\n    | i+1, inv =>\n      have : j < as.size := by rw [\u2190 inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_left_comm]; apply Nat.leAddRight\n      let idx : Fin as.size := \u27e8j, this\u27e9\n      have : i + (j + 1) = as.size := by rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n      map i (j+1) this (bs.push (\u2190 f idx (as.get idx)))\n  map as.size 0 rfl (mkEmpty as.size)\n\n@[inline]\ndef findSomeM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) := do\n  for a in as do\n    match (\u2190 f a) with\n    | some b => return b\n    | _      => pure \u27e8\u27e9\n  return none\n\n@[inline]\ndef findM? {\u03b1 : Type} {m : Type \u2192 Type} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) := do\n  for a in as do\n    if (\u2190 p a) then\n      return a\n  return none\n\n@[inline]\ndef findIdxM? [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option Nat) := do\n  let mut i := 0\n  for a in as do\n    if (\u2190 p a) then\n      return some i\n    i := i + 1\n  return none\n\n@[inline]\nunsafe def anyMUnsafe {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do\n    if i == stop then\n      pure false\n    else\n      if (\u2190 p (as.uget i lcProof)) then\n        pure true\n      else\n        any (i+1) stop\n  if start < stop then\n    if stop \u2264 as.size then\n      any (USize.ofNat start) (USize.ofNat stop)\n    else\n      pure false\n  else\n    pure false\n\n@[implementedBy anyMUnsafe]\ndef anyM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let any (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) : m Bool := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure false\n        | i'+1 =>\n          if (\u2190 p (as.get \u27e8j, Nat.ltOfLtOfLe hlt h\u27e9)) then\n            pure true\n          else\n            loop i' (j+1)\n      else\n        pure false\n    loop (stop - start) start\n  if h : stop \u2264 as.size then\n    any stop h\n  else\n    any as.size (Nat.leRefl _)\n\n@[inline]\ndef allM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  return !(\u2190 as.anyM fun v => return !(\u2190 p v))\n\n@[inline]\ndef findSomeRevM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) :=\n  let rec @[specialize] find : (i : Nat) \u2192 i \u2264 as.size \u2192 m (Option \u03b2)\n    | 0,   h => pure none\n    | i+1, h => do\n      have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h\n      let r \u2190 f (as.get \u27e8i, this\u27e9)\n      match r with\n      | some v => pure r\n      | none   =>\n        have : i \u2264 as.size := Nat.leOfLt this\n        find i this\n  find as.size (Nat.leRefl _)\n\n@[inline]\ndef findRevM? {\u03b1 : Type} {m : Type \u2192 Type w} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) :=\n  as.findSomeRevM? fun a => return if (\u2190 p a) then some a else none\n\n@[inline]\ndef forM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := 0) (stop := as.size) : m PUnit :=\n  as.foldlM (fun _ => f) \u27e8\u27e9 start stop\n\n@[inline]\ndef forRevM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := as.size) (stop := 0) : m PUnit :=\n  as.foldrM (fun a _ => f a) \u27e8\u27e9 start stop\n\n@[inline]\ndef foldl {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : \u03b2 :=\n  Id.run <| as.foldlM f init start stop\n\n@[inline]\ndef foldr {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : \u03b2 :=\n  Id.run <| as.foldrM f init start stop\n\n@[inline]\ndef map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  Id.run <| as.mapM f\n\n@[inline]\ndef mapIdx {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 \u03b2) : Array \u03b2 :=\n  Id.run <| as.mapIdxM f\n\n@[inline]\ndef find? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findM? p\n\n@[inline]\ndef findSome? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeM? f\n\n@[inline]\ndef findSome! {\u03b1 : Type u} {\u03b2 : Type v} [Inhabited \u03b2] (a : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : \u03b2 :=\n  match findSome? a f with\n  | some b => b\n  | none   => panic! \"failed to find element\"\n\n@[inline]\ndef findSomeRev? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeRevM? f\n\n@[inline]\ndef findRev? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findRevM? p\n\n@[inline]\ndef findIdx? {\u03b1 : Type u} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option Nat :=\n  let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat :=\n    if hlt : j < as.size then\n      match i, inv with\n      | 0, inv => by\n        apply False.elim\n        rw [Nat.zero_add] at inv\n        rw [inv] at hlt\n        exact absurd hlt (Nat.ltIrrefl _)\n      | i+1, inv =>\n        if p (as.get \u27e8j, hlt\u27e9) then\n          some j\n        else\n          have : i + (j+1) = as.size := by\n            rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n          loop i (j+1) this\n    else\n      none\n  loop as.size 0 rfl\n\ndef getIdx? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option Nat :=\na.findIdx? fun a => a == v\n\n@[inline]\ndef any (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.anyM p start stop\n\n@[inline]\ndef all (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.allM p start stop\n\ndef contains [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Bool :=\n  as.any fun b => a == b\n\ndef elem [BEq \u03b1] (a : \u03b1) (as : Array \u03b1) : Bool :=\n  as.contains a\n\n-- TODO(Leo): justify termination using wf-rec, and use `swap`\npartial def reverse (as : Array \u03b1) : Array \u03b1 :=\n  let n   := as.size\n  let mid := n / 2\n  let rec rev (as : Array \u03b1) (i : Nat) :=\n    if i < mid then\n      rev (as.swap! i (n - i - 1)) (i+1)\n    else\n      as\n  rev as 0\n\n@[inline] def getEvenElems (as : Array \u03b1) : Array \u03b1 :=\n  (\u00b7.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a =>\n    if even then\n      (false, r.push a)\n    else\n      (true, r)\n\n@[export lean_array_to_list]\ndef toList (as : Array \u03b1) : List \u03b1 :=\n  as.foldr List.cons []\n\ninstance {\u03b1 : Type u} [Repr \u03b1] : Repr (Array \u03b1) where\n  reprPrec a _ :=\n    if a.size == 0 then\n      \"#[]\"\n    else\n      Std.Format.bracketFill \"#[\" (@Std.Format.joinSep _ \u27e8repr\u27e9 (toList a) (\",\" ++ Std.Format.line)) \"]\"\n\ninstance [ToString \u03b1] : ToString (Array \u03b1) where\n  toString a := \"#\" ++ toString a.toList\n\nprotected def append (as : Array \u03b1) (bs : Array \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : Append (Array \u03b1) := \u27e8Array.append\u27e9\n\nprotected def appendList (as : Array \u03b1) (bs : List \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : HAppend (Array \u03b1) (List \u03b1) (Array \u03b1) := \u27e8Array.appendList\u27e9\n\n@[inline]\ndef concatMapM [Monad m] (f : \u03b1 \u2192 m (Array \u03b2)) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (init := empty) fun bs a => do return bs ++ (\u2190 f a)\n\n@[inline]\ndef concatMap (f : \u03b1 \u2192 Array \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  as.foldl (init := empty) fun bs a => bs ++ f a\n\nend Array\n\nexport Array (mkArray)\n\nsyntax \"#[\" sepBy(term, \", \") \"]\" : term\n\nmacro_rules\n  | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ])\n\nnamespace Array\n\n-- TODO(Leo): cleanup\n@[specialize]\npartial def isEqvAux (a b : Array \u03b1) (hsz : a.size = b.size) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) (i : Nat) : Bool :=\n  if h : i < a.size then\n     let aidx : Fin a.size := \u27e8i, h\u27e9;\n     let bidx : Fin b.size := \u27e8i, hsz \u25b8 h\u27e9;\n     match p (a.get aidx) (b.get bidx) with\n     | true  => isEqvAux a b hsz p (i+1)\n     | false => false\n  else\n    true\n\n@[inline] def isEqv (a b : Array \u03b1) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) : Bool :=\n  if h : a.size = b.size then\n    isEqvAux a b h p 0\n  else\n    false\n\ninstance [BEq \u03b1] : BEq (Array \u03b1) :=\n  \u27e8fun a b => isEqv a b BEq.beq\u27e9\n\n@[inline]\ndef filter (p : \u03b1 \u2192 Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b1 :=\n  as.foldl (init := #[]) (start := start) (stop := stop) fun r a =>\n    if p a then r.push a else r\n\n@[inline]\ndef filterM [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b1) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do\n    if (\u2190 p a) then r.push a else r\n\n@[specialize]\ndef filterMapM [Monad m] (f : \u03b1 \u2192 m (Option \u03b2)) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b2) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do\n    match (\u2190 f a) with\n    | some b => pure (bs.push b)\n    | none   => pure bs\n\n@[inline]\ndef filterMap (f : \u03b1 \u2192 Option \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b2 :=\n  Id.run <| as.filterMapM f (start := start) (stop := stop)\n\n@[specialize]\ndef getMax? (as : Array \u03b1) (lt : \u03b1 \u2192 \u03b1 \u2192 Bool) : Option \u03b1 :=\n  if h : 0 < as.size then\n    let a0 := as.get \u27e80, h\u27e9\n    some <| as.foldl (init := a0) (start := 1) fun best a =>\n      if lt best a then a else best\n  else\n    none\n\n@[inline]\ndef partition (p : \u03b1 \u2192 Bool) (as : Array \u03b1) : Array \u03b1 \u00d7 Array \u03b1 := do\n  let mut bs := #[]\n  let mut cs := #[]\n  for a in as do\n    if p a then\n      bs := bs.push a\n    else\n      cs := cs.push a\n  return (bs, cs)\n\ntheorem ext (a b : Array \u03b1)\n    (h\u2081 : a.size = b.size)\n    (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.size) \u2192 (hi\u2082 : i < b.size) \u2192 a.get \u27e8i, hi\u2081\u27e9 = b.get \u27e8i, hi\u2082\u27e9)\n    : a = b := by\n  let rec extAux (a b : List \u03b1)\n      (h\u2081 : a.length = b.length)\n      (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.length) \u2192 (hi\u2082 : i < b.length) \u2192 a.get i hi\u2081 = b.get i hi\u2082)\n      : a = b := by\n    induction a generalizing b with\n    | nil =>\n      cases b with\n      | nil       => rfl\n      | cons b bs => rw [List.length_cons] at h\u2081; injection h\u2081\n    | cons a as ih =>\n      cases b with\n      | nil => rw [List.length_cons] at h\u2081; injection h\u2081\n      | cons b bs =>\n        have hz\u2081 : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zeroLtSucc\n        have hz\u2082 : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zeroLtSucc\n        have headEq : a = b := h\u2082 0 hz\u2081 hz\u2082\n        have h\u2081' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h\u2081; injection h\u2081; assumption\n        have h\u2082' : (i : Nat) \u2192 (hi\u2081 : i < as.length) \u2192 (hi\u2082 : i < bs.length) \u2192 as.get i hi\u2081 = bs.get i hi\u2082 := by\n          intro i hi\u2081 hi\u2082\n          have hi\u2081' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have hi\u2082' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have : (a::as).get (i+1) hi\u2081' = (b::bs).get (i+1) hi\u2082' := h\u2082 (i+1) hi\u2081' hi\u2082'\n          apply this\n        have tailEq : as = bs := ih bs h\u2081' h\u2082'\n        rw [headEq, tailEq]\n  cases a; cases b\n  apply congrArg\n  apply extAux\n  assumption\n  assumption\n\ntheorem extLit {n : Nat}\n    (a b : Array \u03b1)\n    (hsz\u2081 : a.size = n) (hsz\u2082 : b.size = n)\n    (h : (i : Nat) \u2192 (hi : i < n) \u2192 a.getLit i hsz\u2081 hi = b.getLit i hsz\u2082 hi) : a = b :=\n  Array.ext a b (hsz\u2081.trans hsz\u2082.symm) fun i hi\u2081 hi\u2082 => h i (hsz\u2081 \u25b8 hi\u2081)\n\nend Array\n\n-- CLEANUP the following code\nnamespace Array\n\npartial def indexOfAux [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Nat \u2192 Option (Fin a.size)\n  | i =>\n    if h : i < a.size then\n      let idx : Fin a.size := \u27e8i, h\u27e9;\n      if a.get idx == v then some idx\n      else indexOfAux a v (i+1)\n    else none\n\ndef indexOf? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option (Fin a.size) :=\n  indexOfAux a v 0\n\npartial def eraseIdxAux : Nat \u2192 Array \u03b1 \u2192 Array \u03b1\n  | i, a =>\n    if h : i < a.size then\n      let idx  : Fin a.size := \u27e8i, h\u27e9;\n      let idx1 : Fin a.size := \u27e8i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h\u27e9;\n      eraseIdxAux (i+1) (a.swap idx idx1)\n    else\n      a.pop\n\ndef feraseIdx (a : Array \u03b1) (i : Fin a.size) : Array \u03b1 :=\n  eraseIdxAux (i.val + 1) a\n\ndef eraseIdx (a : Array \u03b1) (i : Nat) : Array \u03b1 :=\n  if i < a.size then eraseIdxAux (i+1) a else a\n\n@[simp] theorem size_swap (a : Array \u03b1) (i j : Fin a.size) : (a.swap i j).size = a.size := by\n  show ((a.set i (a.get j)).set (size_set a i _ \u25b8 j) (a.get i)).size = a.size\n  rw [size_set, size_set]\n\n@[simp] theorem size_pop (a : Array \u03b1) : a.pop.size = a.size - 1 :=\n  List.length_dropLast ..\n\nsection\n/- Instance for justifying `partial` declaration.\n   We should be able to delete it as soon as we restore support for well-founded recursion. -/\ninstance eraseIdxSzAuxInstance (a : Array \u03b1) : Inhabited { r : Array \u03b1 // r.size = a.size - 1 } where\n  default := \u27e8a.pop, size_pop a\u27e9\n\npartial def eraseIdxSzAux (a : Array \u03b1) : \u2200 (i : Nat) (r : Array \u03b1), r.size = a.size \u2192 { r : Array \u03b1 // r.size = a.size - 1 }\n  | i, r, heq =>\n    if h : i < r.size then\n      let idx  : Fin r.size := \u27e8i, h\u27e9;\n      let idx1 : Fin r.size := \u27e8i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h\u27e9;\n      eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq)\n    else\n      \u27e8r.pop, (size_pop r).trans (heq \u25b8 rfl)\u27e9\nend\n\ndef eraseIdx' (a : Array \u03b1) (i : Fin a.size) : { r : Array \u03b1 // r.size = a.size - 1 } :=\n  eraseIdxSzAux a (i.val + 1) a rfl\n\ndef erase [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Array \u03b1 :=\n  match as.indexOf? a with\n  | none   => as\n  | some i => as.feraseIdx i\n\npartial def insertAtAux (i : Nat) : Array \u03b1 \u2192 Nat \u2192 Array \u03b1\n  | as, j =>\n    if i == j then as\n    else\n      let as := as.swap! (j-1) j;\n      insertAtAux i as (j-1)\n\n/--\n  Insert element `a` at position `i`.\n  Pre: `i < as.size` -/\ndef insertAt (as : Array \u03b1) (i : Nat) (a : \u03b1) : Array \u03b1 :=\n  if i > as.size then panic! \"invalid index\"\n  else\n    let as := as.push a;\n    as.insertAtAux i as.size\n\ndef toListLitAux (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : \u2200 (i : Nat), i \u2264 a.size \u2192 List \u03b1 \u2192 List \u03b1\n  | 0,     hi, acc => acc\n  | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc)\n\ndef toArrayLit (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : Array \u03b1 :=\n  List.toArray <| toListLitAux a n hsz n (hsz \u25b8 Nat.leRefl _) []\n\ntheorem toArrayLitEq (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz :=\n  -- TODO: this is painful to prove without proper automation\n  sorry\n  /-\n  First, we need to prove\n  \u2200 i j acc, i \u2264 a.size \u2192 (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i)\n  by induction\n\n  Base case is trivial\n  (j : Nat) (acc : List \u03b1) (hi : 0 \u2264 a.size)\n       |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0)\n  ...  |- acc.index j = acc.index j\n\n  Induction\n\n  (j : Nat) (acc : List \u03b1) (hi : i+1 \u2264 a.size)\n        |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))\n    ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))  * by def\n    ... |- if j < i     then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i)    * by induction hypothesis\n           =\n           if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))\n  If j < i, then both are a.getLit j hsz _\n  If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _)\n  If j >= i + 1, we use\n     - j - i >= 1 > 0\n     - (a::as).index k = as.index (k-1) If k > 0\n     - j - (i + 1) = (j - i) - 1\n     Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs\n\n  With this proof, we have\n\n  \u2200 j, j < n \u2192 (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _\n\n  We also need\n\n  - (toListLitAux a n hsz n _ []).length = n\n  - j < n -> (List.toArray as).getLit j _ _ = as.index j\n\n  Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ []\n  -/\n\npartial def isPrefixOfAux [BEq \u03b1] (as bs : Array \u03b1) (hle : as.size \u2264 bs.size) : Nat \u2192 Bool\n  | i =>\n    if h : i < as.size then\n      let a := as.get \u27e8i, h\u27e9;\n      let b := bs.get \u27e8i, Nat.ltOfLtOfLe h hle\u27e9;\n      if a == b then\n        isPrefixOfAux as bs hle (i+1)\n      else\n        false\n    else\n      true\n\n/- Return true iff `as` is a prefix of `bs` -/\ndef isPrefixOf [BEq \u03b1] (as bs : Array \u03b1) : Bool :=\n  if h : as.size \u2264 bs.size then\n    isPrefixOfAux as bs h 0\n  else\n    false\n\nprivate def allDiffAuxAux [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : forall (i : Nat), i < as.size \u2192 Bool\n  | 0,   h => true\n  | i+1, h =>\n    have : i < as.size := Nat.ltTrans (Nat.ltSuccSelf _) h;\n    a != as.get \u27e8i, this\u27e9 && allDiffAuxAux as a i this\n\nprivate partial def allDiffAux [BEq \u03b1] (as : Array \u03b1) : Nat \u2192 Bool\n  | i =>\n    if h : i < as.size then\n      allDiffAuxAux as (as.get \u27e8i, h\u27e9) i h && allDiffAux as (i+1)\n    else\n      true\n\ndef allDiff [BEq \u03b1] (as : Array \u03b1) : Bool :=\n  allDiffAux as 0\n\n@[specialize] partial def zipWithAux (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (as : Array \u03b1) (bs : Array \u03b2) : Nat \u2192 Array \u03b3 \u2192 Array \u03b3\n  | i, cs =>\n    if h : i < as.size then\n      let a := as.get \u27e8i, h\u27e9;\n      if h : i < bs.size then\n        let b := bs.get \u27e8i, h\u27e9;\n        zipWithAux f as bs (i+1) <| cs.push <| f a b\n      else\n        cs\n    else\n      cs\n\n@[inline] def zipWith (as : Array \u03b1) (bs : Array \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : Array \u03b3 :=\n  zipWithAux f as bs 0 #[]\n\ndef zip (as : Array \u03b1) (bs : Array \u03b2) : Array (\u03b1 \u00d7 \u03b2) :=\n  zipWith as bs Prod.mk\n\ndef unzip (as : Array (\u03b1 \u00d7 \u03b2)) : Array \u03b1 \u00d7 Array \u03b2 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b)\n\ndef split (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Array \u03b1 \u00d7 Array \u03b1 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) a =>\n    if p a then (as.push a, bs) else (as, bs.push a)\n\nend Array\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Init/Data/Array/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.08509905370824052, "lm_q1q2_score": 0.03307102632663149}}
{"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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl\n\nBinder elimination\n-/\nimport order.complete_lattice\n\nnamespace old_conv\nopen tactic monad\n\nmeta instance : monad_fail old_conv :=\n{ fail := \u03bb \u03b1 s, (\u03bbr e, tactic.fail (to_fmt s) : old_conv \u03b1), ..old_conv.monad }\n\nmeta instance : has_monad_lift tactic old_conv :=\n\u27e8\u03bb\u03b1, lift_tactic\u27e9\n\nmeta instance (\u03b1 : Type) : has_coe (tactic \u03b1) (old_conv \u03b1) :=\n\u27e8monad_lift\u27e9\n\nmeta def current_relation : old_conv name := \u03bbr lhs, return \u27e8r, lhs, none\u27e9\n\nmeta def head_beta : old_conv unit :=\n\u03bb r e, do n \u2190 tactic.head_beta e, return \u27e8(), n, none\u27e9\n\n/- congr should forward data! -/\nmeta def congr_arg : old_conv unit \u2192 old_conv unit := congr_core (return ())\nmeta def congr_fun : old_conv unit \u2192 old_conv unit := \u03bbc, congr_core c (return ())\n\nmeta def congr_rule (congr : expr) (cs : list (list expr \u2192 old_conv unit)) :\n  old_conv unit :=\n\u03bbr lhs, do\n  meta_rhs \u2190 infer_type lhs >>= mk_meta_var, -- is maybe overly restricted for `heq`\n  t \u2190 mk_app r [lhs, meta_rhs],\n  ((), meta_pr) \u2190 solve_aux t (do\n    apply congr,\n    focus $ cs.map $ \u03bbc, (do\n      xs \u2190 intros,\n      conversion (head_beta >> c xs)),\n    done),\n  rhs \u2190 instantiate_mvars meta_rhs,\n  pr \u2190 instantiate_mvars meta_pr,\n  return \u27e8(), rhs, some pr\u27e9\n\nmeta def congr_binder (congr : name) (cs : expr \u2192 old_conv unit) : old_conv unit := do\n  e \u2190 mk_const congr,\n  congr_rule e [\u03bbbs, do [b] \u2190 return bs, cs b]\n\nmeta def funext' : (expr \u2192 old_conv unit) \u2192 old_conv unit := congr_binder ``_root_.funext\n\nmeta def propext' {\u03b1 : Type} (c : old_conv \u03b1) : old_conv \u03b1 := \u03bbr lhs, (do\n  guard (r = `iff),\n  c r lhs)\n<|> (do\n  guard (r = `eq),\n  \u27e8res, rhs, pr\u27e9 \u2190 c `iff lhs,\n  match pr with\n  | some pr := return \u27e8res, rhs, (expr.const `propext [] : expr) lhs rhs pr\u27e9\n  | none := return \u27e8res, rhs, none\u27e9\n  end)\n\nmeta def apply (pr : expr) : old_conv unit :=\n\u03bb r e, do\n  sl \u2190 simp_lemmas.mk.add pr,\n  apply_lemmas sl r e\n\nmeta def applyc (n : name) : old_conv unit :=\n\u03bb r e, do\n  sl \u2190 simp_lemmas.mk.add_simp n,\n  apply_lemmas sl r e\n\nmeta def apply' (n : name) : old_conv unit := do\n  e \u2190 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 \u2192 \u03a0 (\u03b1 : Sort u), (\u03b1 \u2192 t) \u2192 t`, where `t` is a type depending on `p`.\nExamples:\n  \u2203: there is no `p` and `t` is `Prop`.\n  \u2a05, \u2a06: here p is `\u03b2` and `[complete_lattice \u03b2]`, `p` is `\u03b2`\n\nProblem: \u2200x, _ should be a binder, but is not a constant!\n\nProvide a mechanism to rewrite:\n\n  B (x : \u03b1) ..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 \u2192 tactic (expr \u00d7 expr))    -- returns the bound type and body\n(adapt_rel     : old_conv unit \u2192 old_conv unit)          -- optionally adapt `eq` to `iff`\n(apply_comm    : old_conv unit)                      -- apply commutativity rule\n(apply_congr   : (expr \u2192 old_conv unit) \u2192 old_conv unit) -- apply congruence rule\n(apply_elim_eq : old_conv unit)                      -- (B (x : \u03b2) (h : x = t), s x) = s t\n\nmeta def binder_eq_elim.check_eq (b : binder_eq_elim) (x : expr) : expr \u2192 tactic unit\n| `(@eq %%\u03b2 %%l %%r) := guard ((l = x \u2227 \u00ac x.occurs r) \u2228 (r = x \u2227 \u00ac 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  (\u03b2, f) \u2190 lhs >>= (lift_tactic \u2218 b.match_binder),\n  guard (\u00ac x.occurs \u03b2)\n  <|> b.check_eq x \u03b2\n  <|> (do\n    b.apply_congr $ \u03bbx, 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 $ \u03bbx, 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 \u2192 tactic unit\n| e := do\n  (\u03b2, f) \u2190 b.match_binder e,\n  b.check_eq x \u03b2\n  <|> (do\n    (lam n bi d bd) \u2190 return f,\n    x \u2190 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  (\u03b2, f) \u2190 lhs >>= (lift_tactic \u2218 b.match_binder),\n  (lam n bi d bd) \u2190 return f,\n  x \u2190 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 {\u03b1 : Sort u} (a : \u03b1) (p : \u03a0(a':\u03b1), a' = a \u2192 Prop) :\n  (\u2203(a':\u03b1)(h : a' = a), p a' h) \u2194 p a rfl :=\n\u27e8\u03bb\u27e8a', \u27e8h, p_h\u27e9\u27e9, match a', h, p_h with ._, rfl, h := h end, \u03bbh, \u27e8a, rfl, h\u27e9\u27e9\n\ntheorem {u v} exists_elim_eq_right {\u03b1 : Sort u} (a : \u03b1) (p : \u03a0(a':\u03b1), a = a' \u2192 Prop) :\n  (\u2203(a':\u03b1)(h : a = a'), p a' h) \u2194 p a rfl :=\n\u27e8\u03bb\u27e8a', \u27e8h, p_h\u27e9\u27e9, match a', h, p_h with ._, rfl, h := h end, \u03bbh, \u27e8a, rfl, h\u27e9\u27e9\n\nmeta def exists_eq_elim : binder_eq_elim :=\n{ match_binder  := \u03bbe, (do `(@Exists %%\u03b2 %%f) \u2190 return e, return (\u03b2, 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 {\u03b1 : Sort u} {\u03b2 : Sort v} (p : \u03b1 \u2192 \u03b2 \u2192 Prop) :\n  (\u2200a b, p a b) \u2194 (\u2200b a, p a b) :=\n\u27e8assume h b a, h a b, assume h b a, h a b\u27e9\n\ntheorem {u v} forall_elim_eq_left {\u03b1 : Sort u} (a : \u03b1) (p : \u03a0(a':\u03b1), a' = a \u2192 Prop) :\n  (\u2200(a':\u03b1)(h : a' = a), p a' h) \u2194 p a rfl :=\n\u27e8\u03bbh, h a rfl, \u03bbh a' h_eq, match a', h_eq with ._, rfl := h end\u27e9\n\ntheorem {u v} forall_elim_eq_right {\u03b1 : Sort u} (a : \u03b1) (p : \u03a0(a':\u03b1), a = a' \u2192 Prop) :\n  (\u2200(a':\u03b1)(h : a = a'), p a' h) \u2194 p a rfl :=\n\u27e8\u03bbh, h a rfl, \u03bbh a' h_eq, match a', h_eq with ._, rfl := h end\u27e9\n\nmeta def forall_eq_elim : binder_eq_elim :=\n{ match_binder  := \u03bbe, (do (expr.pi n bi d bd) \u2190 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  := \u03bbe, (do `(@supr %%\u03b1 %%cl %%\u03b2 %%f) \u2190 return e, return (\u03b2, f)),\n  adapt_rel     := \u03bbc, (do r \u2190 current_relation, guard (r = `eq), c),\n  apply_comm    := applyc ``supr_comm,\n  apply_congr   := congr_arg \u2218 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  := \u03bbe, (do `(@infi %%\u03b1 %%cl %%\u03b2 %%f) \u2190 return e, return (\u03b2, f)),\n  adapt_rel     := \u03bbc, (do r \u2190 current_relation, guard (r = `eq), c),\n  apply_comm    := applyc ``infi_comm,\n  apply_congr   := congr_arg \u2218 funext',\n  apply_elim_eq := applyc ``infi_infi_eq_left <|> applyc ``infi_infi_eq_right }\n\n\nuniverses u v w w\u2082\nvariables {\u03b1 : Type u} {\u03b2 : Type v} {\u03b9 : Sort w} {\u03b9\u2082 : Sort w\u2082} {s t : set \u03b1} {a : \u03b1}\n\nsection\nvariables [complete_lattice \u03b1]\n\nexample {s : set \u03b2} {f : \u03b2 \u2192 \u03b1} : Inf (set.image f s) = (\u2a05 a \u2208 s, f a) :=\nbegin\n  simp [Inf_eq_infi, infi_and],\n  conversion infi_eq_elim.old_conv,\nend\n\nexample {s : set \u03b2} {f : \u03b2 \u2192 \u03b1} : Sup (set.image f s) = (\u2a06 a \u2208 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": "/-\nCopyright (c) 2023 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Floris van Doorn\n-/\nimport Lean\n\n/-!\n# `addRelatedDecl`\n\n-/\n\nopen Lean Meta Elab\n\nnamespace Mathlib.Tactic\n\n/-- A helper function for constructing a related declaration from an existing one.\n\nThis is currently used by the attributes `reassoc` and `elementwise`,\nand has been factored out to avoid code duplication.\nFeel free to add features as needed for other applications.\n\nThis helper:\n* calls `addDeclarationRanges`, so jump-to-definition works,\n* copies the `protected` status of the existing declaration, and\n* supports copying attributes.\n\nArguments:\n* `src : Name` is the existing declaration that we are modifying.\n* `suffix : String` will be appended to `src` to form the name of the new declaration.\n* `ref : Syntax` is the syntax where the user requested the related declaration.\n* `construct type value levels : MetaM (Expr \u00d7 List Name)`\n  given the type, value, and universe variables of the original declaration,\n  should construct the value of the new declaration,\n  along with the names of its universe variables.\n* `attrs` is the attributes that should be applied to both the new and the original declaration,\n  e.g. in the usage `@[reassoc (attr := simp)]`.\n  We apply it to both declarations, to have the same behavior as `to_additive`, and to shorten some\n  attribute commands. Note that `@[elementwise (attr := simp), reassoc (attr := simp)]` will try\n  to apply `simp` twice to the current declaration, but that causes no issues.\n-/\ndef addRelatedDecl (src : Name) (suffix : String) (ref : Syntax)\n    (attrs? : Option (Syntax.TSepArray `Lean.Parser.Term.attrInstance \",\"))\n    (construct : Expr \u2192 Expr \u2192 List Name \u2192 MetaM (Expr \u00d7 List Name)) :\n    MetaM Unit := do\n  let tgt := match src with\n    | Name.str n s => Name.mkStr n $ s ++ suffix\n    | x => x\n  addDeclarationRanges tgt {\n    range := \u2190 getDeclarationRange (\u2190 getRef)\n    selectionRange := \u2190 getDeclarationRange ref }\n  let info \u2190 getConstInfo src\n  let (newValue, newLevels) \u2190 construct info.type info.value! info.levelParams\n  let newValue \u2190 instantiateMVars newValue\n  let newType \u2190 instantiateMVars (\u2190 inferType newValue)\n  match info with\n  | ConstantInfo.thmInfo info =>\n    addAndCompile <| .thmDecl\n      { info with levelParams := newLevels, type := newType, name := tgt, value := newValue }\n  | ConstantInfo.defnInfo info =>\n    -- Structure fields are created using `def`, even when they are propositional,\n    -- so we don't rely on this to decided whether we should be constructing a `theorem` or a `def`.\n    addAndCompile <| if \u2190 isProp newType then .thmDecl\n      { info with levelParams := newLevels, type := newType, name := tgt, value := newValue }\n      else .defnDecl\n      { info with levelParams := newLevels, type := newType, name := tgt, value := newValue }\n  | _ => throwError \"Constant {src} is not a theorem or definition.\"\n  if isProtected (\u2190 getEnv) src then\n    setEnv $ addProtected (\u2190 getEnv) tgt\n  let attrs := match attrs? with | some attrs => attrs | none => #[]\n  _ \u2190 Term.TermElabM.run' <| do\n    let attrs \u2190 elabAttrs attrs\n    Term.applyAttributes src attrs\n    Term.applyAttributes tgt attrs\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/Util/AddRelatedDecl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.11596073047456816, "lm_q1q2_score": 0.03299964132448223}}
{"text": "variables {p q : Prop} (hp : p) (hq : q)\n\ninclude hp hq\n\nexample : p \u2227 q \u2227 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 {\u03b1 : Type u} : \u2200 {x y : Option \u03b1}, (\u2200z, x = some z \u2194 y = some z) \u2192 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 {\u03b1 : Type u} : \u2200 {o : Option \u03b1}, o.isNone \u2192 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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl, 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/-- `\u03b1 \u21aa \u03b2` is a bundled injective function. -/\nstructure embedding (\u03b1 : Sort u_1) (\u03b2 : Sort u_2) \nwhere\n  to_fun : \u03b1 \u2192 \u03b2\n  inj' : injective to_fun\n\ninfixr:25 \" \u21aa \" => Mathlib.function.embedding\n\nprotected instance embedding.has_coe_to_fun {\u03b1 : Sort u} {\u03b2 : Sort v} : has_coe_to_fun (\u03b1 \u21aa \u03b2) :=\n  has_coe_to_fun.mk (fun (x : \u03b1 \u21aa \u03b2) => \u03b1 \u2192 \u03b2) embedding.to_fun\n\nend function\n\n\n/-- Convert an `\u03b1 \u2243 \u03b2` to `\u03b1 \u21aa \u03b2`. -/\n@[simp] theorem equiv.to_embedding_apply {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2243 \u03b2) : \u2200 (\u1fb0 : \u03b1), coe_fn (equiv.to_embedding f) \u1fb0 = coe_fn f \u1fb0 :=\n  fun (\u1fb0 : \u03b1) => Eq.refl (coe_fn (equiv.to_embedding f) \u1fb0)\n\nnamespace function\n\n\nnamespace embedding\n\n\ntheorem ext {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u21aa \u03b2} {g : \u03b1 \u21aa \u03b2} (h : \u2200 (x : \u03b1), coe_fn f x = coe_fn g x) : f = g := sorry\n\ntheorem ext_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u21aa \u03b2} {g : \u03b1 \u21aa \u03b2} : (\u2200 (x : \u03b1), coe_fn f x = coe_fn g x) \u2194 f = g := sorry\n\n@[simp] theorem to_fun_eq_coe {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) : to_fun f = \u21d1f :=\n  rfl\n\n@[simp] theorem coe_fn_mk {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (i : injective f) : \u21d1(mk f i) = f :=\n  rfl\n\ntheorem injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) : injective \u21d1f :=\n  inj' f\n\n@[simp] theorem refl_apply (\u03b1 : Sort u_1) (a : \u03b1) : coe_fn (embedding.refl \u03b1) a = a :=\n  Eq.refl a\n\n@[simp] theorem trans_apply {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u21aa \u03b2) (g : \u03b2 \u21aa \u03b3) : \u2200 (\u1fb0 : \u03b1), coe_fn (embedding.trans f g) \u1fb0 = coe_fn g (coe_fn f \u1fb0) :=\n  fun (\u1fb0 : \u03b1) => Eq.refl (coe_fn g (coe_fn f \u1fb0))\n\n@[simp] theorem equiv_to_embedding_trans_symm_to_embedding {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (e : \u03b1 \u2243 \u03b2) : embedding.trans (equiv.to_embedding e) (equiv.to_embedding (equiv.symm e)) = embedding.refl \u03b1 := sorry\n\n@[simp] theorem equiv_symm_to_embedding_trans_to_embedding {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (e : \u03b1 \u2243 \u03b2) : embedding.trans (equiv.to_embedding (equiv.symm e)) (equiv.to_embedding e) = embedding.refl \u03b2 := sorry\n\nprotected def congr {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b3 : Sort w} {\u03b4 : Sort x} (e\u2081 : \u03b1 \u2243 \u03b2) (e\u2082 : \u03b3 \u2243 \u03b4) (f : \u03b1 \u21aa \u03b3) : \u03b2 \u21aa \u03b4 :=\n  embedding.trans (equiv.to_embedding (equiv.symm e\u2081)) (embedding.trans f (equiv.to_embedding e\u2082))\n\n/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/\nprotected def of_surjective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b2 \u2192 \u03b1) (hf : surjective f) : \u03b1 \u21aa \u03b2 :=\n  mk (surj_inv hf) (injective_surj_inv hf)\n\n/-- Convert a surjective `embedding` to an `equiv` -/\nprotected def equiv_of_surjective {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (f : \u03b1 \u21aa \u03b2) (hf : surjective \u21d1f) : \u03b1 \u2243 \u03b2 :=\n  equiv.of_bijective \u21d1f sorry\n\nprotected def of_not_nonempty {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (h\u03b1 : \u00acNonempty \u03b1) : \u03b1 \u21aa \u03b2 :=\n  mk (fun (a : \u03b1) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) (a : \u03b1) (b : \u03b2) [(a' : \u03b1) \u2192 Decidable (a' = a)] [(a' : \u03b1) \u2192 Decidable (coe_fn f a' = b)] : \u03b1 \u21aa \u03b2 :=\n  mk (fun (a' : \u03b1) => ite (a' = a) b (ite (coe_fn f a' = b) (coe_fn f a) (coe_fn f a'))) sorry\n\ntheorem set_value_eq {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u21aa \u03b2) (a : \u03b1) (b : \u03b2) [(a' : \u03b1) \u2192 Decidable (a' = a)] [(a' : \u03b1) \u2192 Decidable (coe_fn f a' = b)] : coe_fn (set_value f a b) a = b := sorry\n\n/-- Embedding into `option` -/\nprotected def some {\u03b1 : Type u_1} : \u03b1 \u21aa Option \u03b1 :=\n  mk some (option.some_injective \u03b1)\n\n/-- Embedding of a `subtype`. -/\ndef subtype {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : Subtype p \u21aa \u03b1 :=\n  mk coe sorry\n\n@[simp] theorem coe_subtype {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : \u21d1(subtype p) = coe :=\n  rfl\n\n/-- Choosing an element `b : \u03b2` gives an embedding of `punit` into `\u03b2`. -/\ndef punit {\u03b2 : Sort u_1} (b : \u03b2) : PUnit \u21aa \u03b2 :=\n  mk (fun (_x : PUnit) => b) sorry\n\n/-- Fixing an element `b : \u03b2` gives an embedding `\u03b1 \u21aa \u03b1 \u00d7 \u03b2`. -/\ndef sectl (\u03b1 : Type u_1) {\u03b2 : Type u_2} (b : \u03b2) : \u03b1 \u21aa \u03b1 \u00d7 \u03b2 :=\n  mk (fun (a : \u03b1) => (a, b)) sorry\n\n/-- Fixing an element `a : \u03b1` gives an embedding `\u03b2 \u21aa \u03b1 \u00d7 \u03b2`. -/\ndef sectr {\u03b1 : Type u_1} (a : \u03b1) (\u03b2 : Type u_2) : \u03b2 \u21aa \u03b1 \u00d7 \u03b2 :=\n  mk (fun (b : \u03b2) => (a, b)) sorry\n\n/-- Restrict the codomain of an embedding. -/\ndef cod_restrict {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (p : set \u03b2) (f : \u03b1 \u21aa \u03b2) (H : \u2200 (a : \u03b1), coe_fn f a \u2208 p) : \u03b1 \u21aa \u21a5p :=\n  mk (fun (a : \u03b1) => { val := coe_fn f a, property := H a }) sorry\n\n@[simp] theorem cod_restrict_apply {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (p : set \u03b2) (f : \u03b1 \u21aa \u03b2) (H : \u2200 (a : \u03b1), coe_fn f a \u2208 p) (a : \u03b1) : coe_fn (cod_restrict p f H) a = { val := coe_fn f a, property := H a } :=\n  rfl\n\n/-- If `e\u2081` and `e\u2082` are embeddings, then so is `prod.map e\u2081 e\u2082 : (a, b) \u21a6 (e\u2081 a, e\u2082 b)`. -/\ndef prod_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) : \u03b1 \u00d7 \u03b3 \u21aa \u03b2 \u00d7 \u03b4 :=\n  mk (prod.map \u21d1e\u2081 \u21d1e\u2082) sorry\n\n@[simp] theorem coe_prod_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) : \u21d1(prod_map e\u2081 e\u2082) = prod.map \u21d1e\u2081 \u21d1e\u2082 :=\n  rfl\n\n/-- If `e\u2081` and `e\u2082` are embeddings, then so is `sum.map e\u2081 e\u2082`. -/\ndef sum_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) : \u03b1 \u2295 \u03b3 \u21aa \u03b2 \u2295 \u03b4 :=\n  mk (sum.map \u21d1e\u2081 \u21d1e\u2082) sorry\n\n@[simp] theorem coe_sum_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (e\u2081 : \u03b1 \u21aa \u03b2) (e\u2082 : \u03b3 \u21aa \u03b4) : \u21d1(sum_map e\u2081 e\u2082) = sum.map \u21d1e\u2081 \u21d1e\u2082 :=\n  rfl\n\n/-- The embedding of `\u03b1` into the sum `\u03b1 \u2295 \u03b2`. -/\n@[simp] theorem inl_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} (val : \u03b1) : coe_fn inl val = sum.inl val :=\n  Eq.refl (coe_fn inl val)\n\n/-- The embedding of `\u03b2` into the sum `\u03b1 \u2295 \u03b2`. -/\n@[simp] theorem inr_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} (val : \u03b2) : 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 {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_3} (a : \u03b1) (snd : \u03b2 a) : coe_fn (sigma_mk a) snd = sigma.mk a snd :=\n  Eq.refl (coe_fn (sigma_mk a) snd)\n\n/-- If `f : \u03b1 \u21aa \u03b1'` is an embedding and `g : \u03a0 a, \u03b2 \u03b1 \u21aa \u03b2' (f \u03b1)` is a family\nof embeddings, then `sigma.map f g` is an embedding. -/\n@[simp] theorem sigma_map_apply {\u03b1 : Type u_1} {\u03b1' : Type u_2} {\u03b2 : \u03b1 \u2192 Type u_3} {\u03b2' : \u03b1' \u2192 Type u_4} (f : \u03b1 \u21aa \u03b1') (g : (a : \u03b1) \u2192 \u03b2 a \u21aa \u03b2' (coe_fn f a)) (x : sigma fun (a : \u03b1) => \u03b2 a) : coe_fn (sigma_map f g) x = sigma.map (\u21d1f) (fun (a : \u03b1) => \u21d1(g a)) x :=\n  Eq.refl (coe_fn (sigma_map f g) x)\n\ndef Pi_congr_right {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {\u03b3 : \u03b1 \u2192 Sort u_3} (e : (a : \u03b1) \u2192 \u03b2 a \u21aa \u03b3 a) : ((a : \u03b1) \u2192 \u03b2 a) \u21aa (a : \u03b1) \u2192 \u03b3 a :=\n  mk (fun (f : (a : \u03b1) \u2192 \u03b2 a) (a : \u03b1) => coe_fn (e a) (f a)) sorry\n\ndef arrow_congr_left {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b3 : Sort w} (e : \u03b1 \u21aa \u03b2) : (\u03b3 \u2192 \u03b1) \u21aa \u03b3 \u2192 \u03b2 :=\n  Pi_congr_right fun (_x : \u03b3) => e\n\ndef arrow_congr_right {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03b3 : Sort w} [Inhabited \u03b3] (e : \u03b1 \u21aa \u03b2) : (\u03b1 \u2192 \u03b3) \u21aa \u03b2 \u2192 \u03b3 :=\n  let f' : (\u03b1 \u2192 \u03b3) \u2192 \u03b2 \u2192 \u03b3 :=\n    fun (f : \u03b1 \u2192 \u03b3) (b : \u03b2) =>\n      dite (\u2203 (c : \u03b1), coe_fn e c = b) (fun (h : \u2203 (c : \u03b1), coe_fn e c = b) => f (classical.some h))\n        fun (h : \u00ac\u2203 (c : \u03b1), coe_fn e c = b) => Inhabited.default;\n  mk f' sorry\n\nprotected def subtype_map {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u21aa \u03b2) (h : \u2200 {x : \u03b1}, p x \u2192 q (coe_fn f x)) : (Subtype fun (x : \u03b1) => p x) \u21aa Subtype fun (y : \u03b2) => q y :=\n  mk (subtype.map (\u21d1f) h) sorry\n\n/-- `set.image` as an embedding `set \u03b1 \u21aa set \u03b2`. -/\nprotected def image {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u21aa \u03b2) : set \u03b1 \u21aa set \u03b2 :=\n  mk (set.image \u21d1f) sorry\n\ntheorem swap_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} [DecidableEq \u03b1] [DecidableEq \u03b2] (f : \u03b1 \u21aa \u03b2) (x : \u03b1) (y : \u03b1) (z : \u03b1) : 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [DecidableEq \u03b1] [DecidableEq \u03b2] (f : \u03b1 \u21aa \u03b2) (x : \u03b1) (y : \u03b1) : \u21d1(equiv.swap (coe_fn f x) (coe_fn f y)) \u2218 \u21d1f = \u21d1f \u2218 \u21d1(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 {\u03b1 : Type u_1} : equiv.to_embedding (equiv.refl \u03b1) = function.embedding.refl \u03b1 :=\n  rfl\n\n@[simp] theorem trans_to_embedding {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (e : \u03b1 \u2243 \u03b2) (f : \u03b2 \u2243 \u03b3) : 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 {\u03b1 : Type u_1} (s : set \u03b1) (t : set \u03b1) (h : s \u2286 t) : \u21a5s \u21aa \u21a5t :=\n  function.embedding.mk (fun (x : \u21a5s) => { 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 \u21aa 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) 2019 Rob Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Rob Lewis\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.simp_result\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\nnamespace tactic\n\n\n/--\n`delta_instance ids` tries to solve the goal by calling `apply_instance`,\nfirst unfolding the definitions in `ids`.\n-/\n-- We call `dsimp_result` here because otherwise\n\n-- `delta_target` will insert an `id` in the result.\n\n-- See the note [locally reducible category instances]\n\n-- https://github.com/leanprover-community/mathlib/blob/c9fca15420e2ad443707ace831679fd1762580fe/src/algebra/category/Mon/basic.lean#L27\n\n-- for an example where this used to cause a problem.\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/delta_instance_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.0758581847220642, "lm_q1q2_score": 0.03292104723371446}}
{"text": "/-\nCopyright (c) 2019 Patrick Massot. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Arthur Paulino, Patrick Massot\n-/\n\nimport Lean\nimport Mathlib.Util.Tactic\n\nnamespace Mathlib.Tactic\n\nopen Lean Meta Parser Elab Tactic\n\n/-- Renames a bound variable in a hypothesis. -/\ndef renameBVarHyp (mvarId : MVarId) (fvarId : FVarId) (old new : Name) :\n    MetaM Unit :=\n  modifyLocalDecl mvarId fvarId fun ldecl \u21a6\n    ldecl.setType $ ldecl.type.renameBVar old new\n\n/-- Renames a bound variable in the target. -/\ndef renameBVarTarget (mvarId : MVarId) (old new : Name) : MetaM Unit :=\n  modifyTarget mvarId fun e \u21a6 e.renameBVar old new\n\n/--\n* `rename_bvar old new` renames all bound variables named `old` to `new` in the target.\n* `rename_bvar old new at h` does the same in hypothesis `h`.\n\n```lean\nexample (P : \u2115 \u2192  \u2115 \u2192 Prop) (h : \u2200 n, \u2203 m, P n m) : \u2200 l, \u2203 m, P l m :=\nbegin\n  rename_bvar n q at h, -- h is now \u2200 (q : \u2115), \u2203 (m : \u2115), P q m,\n  rename_bvar m n, -- target is now \u2200 (l : \u2115), \u2203 (n : \u2115), P k n,\n  exact h -- Lean does not care about those bound variable names\nend\n```\nNote: name clashes are resolved automatically.\n-/\nelab \"rename_bvar \" old:ident \" \u2192 \" new:ident loc?:(ppSpace location)? : tactic => do\n  let mvarId \u2190 getMainGoal\n  match loc? with\n  | none => renameBVarTarget mvarId old.getId new.getId\n  | some loc =>\n    withLocation (expandLocation loc)\n      (fun fvarId \u21a6 renameBVarHyp mvarId fvarId old.getId new.getId)\n      (renameBVarTarget mvarId old.getId new.getId)\n      fun _ \u21a6 throwError \"unexpected location syntax\"\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/RenameBVar.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.11920291107043361, "lm_q1q2_score": 0.03279626400172691}}
{"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 {\u03b1 : Type u_1} (x : \u03b1) : thunk \u03b1 :=\n  fun (_x : Unit) => x\n\nprotected instance decidable_eq {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (thunk \u03b1) :=\n  sorry\n\nend thunk\n\n\nnamespace lazy_list\n\n\n/-- Isomorphism between strict and lazy lists. -/\ndef list_equiv_lazy_list (\u03b1 : Type u_1) : List \u03b1 \u2243 lazy_list \u03b1 :=\n  equiv.mk of_list to_list sorry sorry\n\nprotected instance inhabited {\u03b1 : Type u} : Inhabited (lazy_list \u03b1) :=\n  { default := nil }\n\nprotected instance decidable_eq {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (lazy_list \u03b1) :=\n  sorry\n\n/-- Traversal of lazy lists using an applicative effect. -/\nprotected def traverse {m : Type u \u2192 Type u} [Applicative m] {\u03b1 : Type u} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : lazy_list \u03b1 \u2192 m (lazy_list \u03b2) :=\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 {\u03b1 : Type u_1} : lazy_list \u03b1 \u2192 lazy_list \u03b1 :=\n  sorry\n\n/-- Return the first object contained in the list that satisfies\npredicate `p` -/\ndef find {\u03b1 : Type u_1} (p : \u03b1 \u2192 Prop) [decidable_pred p] : lazy_list \u03b1 \u2192 Option \u03b1 :=\n  sorry\n\n/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/\ndef interleave {\u03b1 : Type u_1} : lazy_list \u03b1 \u2192 lazy_list \u03b1 \u2192 lazy_list \u03b1 :=\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 {\u03b1 : Type u_1} : List (lazy_list \u03b1) \u2192 lazy_list \u03b1 :=\n  sorry\n\n/-- Monadic bind operation for `lazy_list`. -/\nprotected def bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} : lazy_list \u03b1 \u2192 (\u03b1 \u2192 lazy_list \u03b2) \u2192 lazy_list \u03b2 :=\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 {\u03b1 : Type u_1} (xs : lazy_list \u03b1) : lazy_list \u03b1 :=\n  of_list (list.reverse (to_list xs))\n\nprotected instance monad : Monad lazy_list := sorry\n\ntheorem append_nil {\u03b1 : Type u_1} (xs : lazy_list \u03b1) : (append xs fun (_ : Unit) => nil) = xs := sorry\n\ntheorem append_assoc {\u03b1 : Type u_1} (xs : lazy_list \u03b1) (ys : lazy_list \u03b1) (zs : lazy_list \u03b1) : (append (append xs fun (_ : Unit) => ys) fun (_ : Unit) => zs) =\n  append xs fun (_ : Unit) => append ys fun (_ : Unit) => zs := sorry\n\ntheorem append_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} (xs : lazy_list \u03b1) (ys : thunk (lazy_list \u03b1)) (f : \u03b1 \u2192 lazy_list \u03b2) : 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 \u2192 Type u_2} [alternative m] {\u03b1 : Type u_3} {\u03b2 : Type u_1} (f : \u03b1 \u2192 m \u03b2) : lazy_list \u03b1 \u2192 m \u03b2 :=\n  sorry\n\n/-- Membership in lazy lists -/\nprotected def mem {\u03b1 : Type u_1} (x : \u03b1) : lazy_list \u03b1 \u2192 Prop :=\n  sorry\n\nprotected instance has_mem {\u03b1 : outParam (Type u_1)} : has_mem \u03b1 (lazy_list \u03b1) :=\n  has_mem.mk lazy_list.mem\n\nprotected instance mem.decidable {\u03b1 : Type u_1} [DecidableEq \u03b1] (x : \u03b1) (xs : lazy_list \u03b1) : Decidable (x \u2208 xs) :=\n  sorry\n\n@[simp] theorem mem_nil {\u03b1 : Type u_1} (x : \u03b1) : x \u2208 nil \u2194 False :=\n  iff.rfl\n\n@[simp] theorem mem_cons {\u03b1 : Type u_1} (x : \u03b1) (y : \u03b1) (ys : thunk (lazy_list \u03b1)) : x \u2208 cons y ys \u2194 x = y \u2228 x \u2208 ys Unit.unit :=\n  iff.rfl\n\ntheorem forall_mem_cons {\u03b1 : Type u_1} {p : \u03b1 \u2192 Prop} {a : \u03b1} {l : thunk (lazy_list \u03b1)} : (\u2200 (x : \u03b1), x \u2208 cons a l \u2192 p x) \u2194 p a \u2227 \u2200 (x : \u03b1), x \u2208 l Unit.unit \u2192 p x := sorry\n\n/-! ### map for partial functions -/\n\n/-- Partial map. If `f : \u03a0 a, p a \u2192 \u03b2` is a partial function defined on\n  `a : \u03b1` 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (l : lazy_list \u03b1) : (\u2200 (a : \u03b1), a \u2208 l \u2192 p a) \u2192 lazy_list \u03b2 :=\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 \u2208 l}`. -/\ndef attach {\u03b1 : Type u_1} (l : lazy_list \u03b1) : lazy_list (Subtype fun (x : \u03b1) => x \u2208 l) :=\n  pmap Subtype.mk l sorry\n\nprotected instance has_repr {\u03b1 : Type u_1} [has_repr \u03b1] : has_repr (lazy_list \u03b1) :=\n  has_repr.mk fun (xs : lazy_list \u03b1) => 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) 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.Elab.App\n\n/-\nAuxiliary elaboration functions: AKA custom elaborators\n-/\n\nnamespace Lean.Elab.Term\nopen Meta\n\ndef elabBinRelCore (noProp : Bool) (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=  do\n  match (\u2190 resolveId? stx[1]) with\n  | some f =>\n    let s \u2190 saveState\n    let (lhs, rhs) \u2190 withSynthesize (mayPostpone := true) do\n      let mut lhs \u2190 elabTerm stx[2] none\n      let mut rhs \u2190 elabTerm stx[3] none\n      if lhs.isAppOfArity ``OfNat.ofNat 3 then\n        lhs \u2190 ensureHasType (\u2190 inferType rhs) lhs\n      else if rhs.isAppOfArity ``OfNat.ofNat 3 then\n        rhs \u2190 ensureHasType (\u2190 inferType lhs) rhs\n      return (lhs, rhs)\n    let lhs \u2190 toBoolIfNecessary lhs\n    let rhs \u2190 toBoolIfNecessary rhs\n    let lhsType \u2190 inferType lhs\n    let rhsType \u2190 inferType rhs\n\n    let (lhs, rhs) \u2190\n      try\n        pure (lhs, \u2190 withRef stx[3] do ensureHasType lhsType rhs)\n      catch _ =>\n        try\n          pure (\u2190 withRef stx[2] do ensureHasType rhsType lhs, rhs)\n        catch _ =>\n          s.restore\n          -- Use default approach\n          let lhs \u2190 elabTerm stx[2] none\n          let rhs \u2190 elabTerm stx[3] none\n          let lhsType \u2190 inferType lhs\n          let rhsType \u2190 inferType rhs\n          pure (lhs, \u2190 withRef stx[3] do ensureHasType lhsType rhs)\n    elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false)\n  | none   => throwUnknownConstant stx[1].getId\nwhere\n  /-- If `noProp == true` and `e` has type `Prop`, then coerce it to `Bool`. -/\n  toBoolIfNecessary (e : Expr) : TermElabM Expr := do\n    if noProp then\n      -- We use `withNewMCtxDepth` to make sure metavariables are not assigned\n      if (\u2190 withNewMCtxDepth <| isDefEq (\u2190 inferType e) (mkSort levelZero)) then\n        return (\u2190 ensureHasType (Lean.mkConst ``Bool) e)\n    return e\n\n@[builtinTermElab binrel] def elabBinRel : TermElab := elabBinRelCore false\n\n@[builtinTermElab binrel_no_prop] def elabBinRelNoProp : TermElab := elabBinRelCore true\n\n@[builtinTermElab forInMacro] def elabForIn : TermElab :=  fun stx expectedType? => do\n  match stx with\n  | `(for_in% $col $init $body) =>\n      match (\u2190 isLocalIdent? col) with\n      | none   => elabTerm (\u2190 `(let col := $col; for_in% col $init $body)) expectedType?\n      | some colFVar =>\n        tryPostponeIfNoneOrMVar expectedType?\n        let m \u2190 getMonad expectedType?\n        let colType \u2190 inferType colFVar\n        let elemType \u2190 mkFreshExprMVar (mkSort (mkLevelSucc (\u2190 mkFreshLevelMVar)))\n        let forInInstance \u2190\n          try\n            mkAppM ``ForIn #[m, colType, elemType]\n          catch\n            ex => tryPostpone; throwError \"failed to construct 'ForIn' instance for collection{indentExpr colType}\\nand monad{indentExpr m}\"\n        match (\u2190 trySynthInstance forInInstance) with\n        | LOption.some val =>\n          let ref \u2190 getRef\n          let forInFn \u2190 mkConst ``forIn\n          elabAppArgs forInFn #[] #[Arg.stx col, Arg.stx init, Arg.stx body] expectedType? (explicit := false) (ellipsis := false)\n        | LOption.undef    => tryPostpone; throwFailure forInInstance\n        | LOption.none     => throwFailure forInInstance\n  | _ => throwUnsupportedSyntax\nwhere\n  getMonad (expectedType? : Option Expr) : TermElabM Expr := do\n    match expectedType? with\n    | none => throwError \"invalid 'for_in%' notation, expected type is not available\"\n    | some expectedType =>\n      match (\u2190 isTypeApp? expectedType) with\n      | some (m, _) => return m\n      | none => throwError \"invalid 'for_in%' notation, expected type is not of of the form `M \u03b1`{indentExpr expectedType}\"\n  throwFailure (forInInstance : Expr) : TermElabM Expr :=\n    throwError \"failed to synthesize instance for 'for_in%' notation{indentExpr forInInstance}\"\n\nnamespace BinOp\n/-\n\nThe elaborator for `binop%` terms works as follows:\n\n1- Expand macros.\n2- Convert `Syntax` object corresponding to the `binop%` term into a `Tree`.\n   The `toTree` method visits nested `binop%` terms and parentheses.\n3- Synthesize pending metavariables without applying default instances and using the\n   `(mayPostpone := true)`.\n4- Tries to compute a maximal type for the tree computed at step 2.\n   We say a type \u03b1 is smaller than type \u03b2 if there is a (nondependent) coercion from \u03b1 to \u03b2.\n   We are currently ignoring the case we may have cycles in the coercion graph.\n   If there are \"uncomparable\" types \u03b1 and \u03b2 in the tree, we skip the next step.\n   We say two types are \"uncomparable\" if there isn't a coercion between them.\n   Note that two types may be \"uncomparable\" because some typing information may still be missing.\n5- We traverse the tree and inject coercions to the \"maximal\" type when needed.\n\nRecall that the coercions are expanded eagerly by the elaborator.\n\nProperties:\n\na) Given `n : Nat` and `i : Nat`, it can successfully elaborate `n + i` and `i + n`. Recall that Lean 3\n   fails on the former.\n\nb) The coercions are inserted in the \"leaves\" like in Lean 3.\n\nc) There are no coercions \"hidden\" inside instances, and we can elaborate\n```\naxiom Int.add_comm (i j : Int) : i + j = j + i\n\nexample (n : Nat) (i : Int) : n + i = i + n := by\n  rw [Int.add_comm]\n```\nRecall that the `rw` tactic used to fail because our old `binop%` elaborator would hide\ncoercions inside of a `HAdd` instance.\n\nRemarks:\n\nIn the new `binop%` elaborator the decision whether a coercion will be inserted or not\nis made at `binop%` elaboration time. This was not the case in the old elaborator.\nFor example, an instance, such as `HAdd Int ?m ?n`, could be created when executing\nthe `binop%` elaborator, and only resolved much later. We try to minimize this problem\nby synthesizing pending metavariables at step 3.\n\nFor types containing heterogeneous operators (e.g., matrix multiplication), step 4 will fail\nand we will skip coercion insertion. For example, `x : Matrix Real 5 4` and `y : Matrix Real 4 8`,\nthere is no coercion `Matrix Real 5 4` from `Matrix Real 4 8` and vice-versa, but\n`x * y` is elaborated successfully and has type `Matrix Real 5 8`.\n-/\n\nprivate inductive Tree where\n  | term  (ref : Syntax) (val : Expr)\n  | op    (ref : Syntax) (lazy : Bool) (f : Expr) (lhs rhs : Tree)\n\nprivate partial def toTree (s : Syntax) : TermElabM Tree := do\n  let result \u2190 go (\u2190 liftMacroM <| expandMacros s)\n  synthesizeSyntheticMVars (mayPostpone := true)\n  return result\nwhere\n  go (s : Syntax) := do\n    match s with\n    | `(binop% $f $lhs $rhs) => processOp (lazy := false) f lhs rhs\n    | `(binop_lazy% $f $lhs $rhs) => processOp (lazy := true) f lhs rhs\n    | `(($e)) => go e\n    | _ =>\n       return Tree.term s (\u2190 elabTerm s none)\n\n  processOp (f lhs rhs : Syntax) (lazy : Bool) := do\n    let some f \u2190 resolveId? f | throwUnknownConstant f.getId\n    return Tree.op s (lazy := lazy) f (\u2190 go lhs) (\u2190 go rhs)\n\n-- Auxiliary function used at `analyze`\nprivate def hasCoe (fromType toType : Expr) : TermElabM Bool := do\n  if (\u2190 getEnv).contains ``CoeHTCT then\n    let u \u2190 getLevel fromType\n    let v \u2190 getLevel toType\n    let coeInstType := mkAppN (Lean.mkConst ``CoeHTCT [u, v]) #[fromType, toType]\n    match \u2190 trySynthInstance coeInstType (some (maxCoeSize.get (\u2190 getOptions))) with\n    | LOption.some _ => return true\n    | LOption.none   => return false\n    | LOption.undef  => return false -- TODO: should we do something smarter here?\n  else\n    return false\n\nprivate structure AnalyzeResult where\n  max?            : Option Expr := none\n  hasUncomparable : Bool := false -- `true` if there are two types `\u03b1` and `\u03b2` where we don't have coercions in any direction.\n\nprivate def isUnknow : Expr \u2192 Bool\n  | Expr.mvar ..        => true\n  | Expr.app f ..       => isUnknow f\n  | Expr.letE _ _ _ b _ => isUnknow b\n  | Expr.mdata _ b _    => isUnknow b\n  | _                   => false\n\nprivate def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do\n  let max? \u2190\n    match expectedType? with\n    | none => pure none\n    | some expectedType =>\n      let expectedType \u2190 instantiateMVars expectedType\n      if isUnknow expectedType then pure none else pure (some expectedType)\n  (go t *> get).run' { max? }\nwhere\n   go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do\n     unless (\u2190 get).hasUncomparable do\n       match t with\n       | Tree.op _ _ _ lhs rhs => go lhs; go rhs\n       | Tree.term _ val =>\n         let type \u2190 instantiateMVars (\u2190 inferType val)\n         unless isUnknow type do\n           match (\u2190 get).max? with\n           | none     => modify fun s => { s with max? := type }\n           | some max =>\n             unless (\u2190 withNewMCtxDepth <| isDefEqGuarded max type) do\n               if (\u2190 hasCoe type max) then\n                 return ()\n               else if (\u2190 hasCoe max type) then\n                 modify fun s => { s with max? := type }\n               else\n                 trace[Elab.binop] \"uncomparable types: {max}, {type}\"\n                 modify fun s => { s with hasUncomparable := true }\n\nprivate def mkOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr :=\n  elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false)\n\nprivate def toExpr (t : Tree) : TermElabM Expr := do\n  match t with\n  | Tree.term _ e               => return e\n  | Tree.op ref true f lhs rhs  => withRef ref <| mkOp f (\u2190 toExpr lhs) (\u2190 mkFunUnit (\u2190 toExpr rhs))\n  | Tree.op ref false f lhs rhs => withRef ref <| mkOp f (\u2190 toExpr lhs) (\u2190 toExpr rhs)\n\nprivate def applyCoe (t : Tree) (maxType : Expr) : TermElabM Tree := do\n  go t\nwhere\n  go (t : Tree) : TermElabM Tree := do\n    match t with\n    | Tree.op ref lazy f lhs rhs => return Tree.op ref lazy f (\u2190 go lhs) (\u2190 go rhs)\n    | Tree.term ref e       =>\n      let type \u2190 inferType e\n      trace[Elab.binop] \"visiting {e} : {type} =?= {maxType}\"\n      if (\u2190 isDefEqGuarded maxType type) then\n        return t\n      else\n        trace[Elab.binop] \"added coercion: {e} : {type} => {maxType}\"\n        withRef ref <| return Tree.term ref (\u2190 mkCoe maxType type e)\n\n@[builtinTermElab binop]\ndef elabBinOp : TermElab :=  fun stx expectedType? => do\n  let tree \u2190 toTree stx\n  let r    \u2190 analyze tree expectedType?\n  trace[Elab.binop] \"hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}\"\n  if r.hasUncomparable || r.max?.isNone then\n    let result \u2190 toExpr tree\n    ensureHasType expectedType? result\n  else\n    let result \u2190 toExpr (\u2190 applyCoe tree r.max?.get!)\n    trace[Elab.binop] \"result: {result}\"\n    ensureHasType expectedType? result\n\n@[builtinTermElab binop_lazy]\ndef elabBinOpLazy : TermElab := elabBinOp\n\n/--\n  Decompose `e` into `(r, a, b)`.\n\n  Remark: it assumes the last two arguments are explicit. -/\nprivate def relation? (e : Expr) : MetaM (Option (Expr \u00d7 Expr \u00d7 Expr)) :=\n  if e.getAppNumArgs < 2 then\n    return none\n  else\n    return some (e.appFn!.appFn!, e.appFn!.appArg!, e.appArg!)\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@[builtinTermElab \u00abcalc\u00bb]\ndef elabBinCalc : TermElab :=  fun stx expectedType? => do\n  let stepStxs := stx[1].getArgs\n  let mut proofs := #[]\n  let mut types  := #[]\n  for stepStx in stepStxs do\n    let type  \u2190 elabType stepStx[0]\n    let some (_, lhs, _) \u2190 relation? type |\n      throwErrorAt stepStx[0] \"invalid 'calc' step, relation expected{indentExpr type}\"\n    if types.size > 0 then\n      let some (_, _, prevRhs) \u2190 relation? types.back | unreachable!\n      unless (\u2190 isDefEqGuarded lhs prevRhs) do\n        throwErrorAt stepStx[0] \"invalid 'calc' step, left-hand-side is {indentD m!\"{lhs} : {\u2190 inferType lhs}\"}\\nprevious right-hand-side is{indentD m!\"{prevRhs} : {\u2190 inferType prevRhs}\"}\"\n    types := types.push type\n    let proof \u2190 elabTermEnsuringType stepStx[2] type\n    synthesizeSyntheticMVars\n    proofs := proofs.push proof\n  let mut result := proofs[0]\n  let mut resultType := types[0]\n  for i in [1:proofs.size] do\n    let some (r, a, b) \u2190 relation? resultType | unreachable!\n    let some (s, _, c) \u2190 relation? (\u2190 instantiateMVars types[i]) | unreachable!\n    let (\u03b1, \u03b2, \u03b3)       := (\u2190 inferType a, \u2190 inferType b, \u2190 inferType c)\n    let (u_1, u_2, u_3) := (\u2190 getLevel \u03b1, \u2190 getLevel \u03b2, \u2190 getLevel \u03b3)\n    let t \u2190 mkFreshExprMVar (\u2190 mkArrow \u03b1 (\u2190 mkArrow \u03b3 (mkSort levelZero)))\n    let selfType := mkAppN (Lean.mkConst ``Trans [u_1, u_2, u_3]) #[\u03b1, \u03b2, \u03b3, r, s, t]\n    match (\u2190 trySynthInstance selfType) with\n    | LOption.some self =>\n      result := mkAppN (Lean.mkConst ``Trans.trans [u_1, u_2, u_3]) #[\u03b1, \u03b2, \u03b3, r, s, t, self, a, b, c, result, proofs[i]]\n      resultType := (\u2190 instantiateMVars (\u2190 inferType result)).headBeta\n      unless (\u2190 relation? resultType).isSome do\n        throwErrorAt stepStxs[i] \"invalid 'calc' step, step result is not a relation{indentExpr resultType}\"\n    | _ => throwErrorAt stepStxs[i] \"invalid 'calc' step, failed to synthesize `Trans` instance{indentExpr selfType}\"\n    pure ()\n  ensureHasType expectedType? result\n\n@[builtinTermElab defaultOrOfNonempty]\ndef elabDefaultOrNonempty : TermElab :=  fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  match expectedType? with\n  | none => throwError \"invalid 'default_or_ofNonempty%', expected type is not known\"\n  | some expectedType =>\n    try\n      mkDefault expectedType\n    catch ex => try\n      mkOfNonempty expectedType\n    catch _ =>\n      throw ex\n\nbuiltin_initialize\n  registerTraceClass `Elab.binop\n\nend BinOp\n\nend Lean.Elab.Term\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/Elab/Extra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234844434674, "lm_q2_score": 0.07477004445424333, "lm_q1q2_score": 0.032736081394949774}}
{"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 \u2282\u2092 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 {\u03b1 \u03b2 \u03b3 : 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) \u03b1)\n  (validity_check : \u03b1 \u2192 oracle_comp regular_spec bool) :\n  oracle_comp (regular_spec ++ adversary_spec) (option \u03b1) :=\n-- do { x \u2190 adversary, b \u2190 validity_check x, return (if b = tt then some x else none) }\ndo { x \u2190 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 \u2282\u2092 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.\u03b9) (t : sub_spec.domain i) : oracle_comp super_spec (sub_spec.range i))\n(eval_dist_to_fun' : \u2200 i t, \u2045to_fun i t\u2046 = \u2045query i t\u2046)\n\ninfixl ` \u2282\u2092 `:65 := is_sub_spec\n\nnamespace is_sub_spec\n\nvariables (sub_spec super_spec : oracle_spec) [h : sub_spec \u2282\u2092 super_spec]\n  (i : sub_spec.\u03b9) (t : sub_spec.domain i)\n\n@[simp] lemma support_to_fun : (h.to_fun i t).support = \u22a4 :=\nby rw [\u2190 support_eval_dist, h.eval_dist_to_fun', support_eval_dist, support_query]\n\n@[simp] lemma fin_support_to_fun [\u2200 i t, (h.to_fun i t).decidable] :\n  (h.to_fun i t).fin_support = \u22a4 :=\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 : \u2045h.to_fun i t\u2046 = 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  \u2045e | h.to_fun i t\u2046 = \u2045e | query i t\u2046 :=\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 \u2282\u2092 super_spec] (\u03b1 : Type) :\n  has_coe (oracle_comp sub_spec \u03b1) (oracle_comp super_spec \u03b1) :=\n{coe := \u03bb oa, default_simulate' \u27ea\u03bb i t, h.to_fun i t\u27eb oa}\n\nlemma coe_sub_spec_def {sub_spec super_spec : oracle_spec} [h : sub_spec \u2282\u2092 super_spec]\n  (oa : oracle_comp sub_spec \u03b1) : (\u2191oa : oracle_comp super_spec \u03b1) =\n    default_simulate' \u27ea\u03bb i t, h.to_fun i t\u27eb oa := rfl\n\nsection coe_sub_spec\n\nvariables (sub_spec super_spec : oracle_spec) [h : sub_spec \u2282\u2092 super_spec]\n  (a : \u03b1) (oa : oracle_comp sub_spec \u03b1) (ob : \u03b1 \u2192 oracle_comp sub_spec \u03b2)\n  (i : sub_spec.\u03b9) (t : sub_spec.domain i) (e : set \u03b1)\ninclude h\n\ninstance coe_sub_spec.decidable [\u2200 i t, (@is_sub_spec.to_fun sub_spec super_spec h i t).decidable]\n  (oa : oracle_comp sub_spec \u03b1) [oa.decidable] : (\u2191oa : oracle_comp super_spec \u03b1).decidable :=\nsimulate'.decidable _ oa ()\n\nlemma coe_sub_spec_return : (\u2191(return a : oracle_comp sub_spec \u03b1) : oracle_comp super_spec \u03b1) =\n  prod.fst <$> return (a, ()) := rfl\n\nlemma coe_sub_spec_bind : (\u2191(oa >>= ob) : oracle_comp super_spec \u03b2) =\n  prod.fst <$> (default_simulate \u27ea\u03bb i t, h.to_fun i t\u27eb oa >>=\n    \u03bb x, simulate \u27ea\u03bb i t, h.to_fun i t\u27eb (ob x.1) x.2) :=\nby rw [coe_sub_spec_def, default_simulate', simulate'_bind]\n\nlemma coe_sub_spec_query : (\u2191(query i t) : oracle_comp super_spec (sub_spec.range i)) =\n  prod.fst <$> (h.to_fun i t >>= \u03bb 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 : (\u2191oa : oracle_comp super_spec \u03b1).support = oa.support :=\nstateless_oracle.support_simulate'_eq_support _ _ ()\n  (\u03bb 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 [\u2200 i t, (@is_sub_spec.to_fun sub_spec super_spec _ i t).decidable]\n  [oa.decidable] : (\u2191oa : oracle_comp super_spec \u03b1).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 : \u2045(\u2191oa : oracle_comp super_spec \u03b1)\u2046 = \u2045oa\u2046 :=\nstateless_oracle.eval_dist_simulate'_eq_eval_dist _ _ ()\n  (\u03bb 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 : \u2045e | (\u2191oa : oracle_comp super_spec \u03b1)\u2046 = \u2045e | oa\u2046 :=\nstateless_oracle.prob_event_simulate'_eq_prob_event _ _ ()\n  (\u03bb 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 \u2282\u2092 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 : \u03b1) (oa : oracle_comp sub_spec \u03b1) (ob : \u03b1 \u2192 oracle_comp sub_spec \u03b2)\n  (i : sub_spec.\u03b9) (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 \u03b1) 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 \u03b1) 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' (\u2191(oa >>= ob) : oracle_comp super_spec \u03b2) s').support =\n    \u22c3 x \u2208 (simulate so' (\u2191oa : oracle_comp super_spec \u03b1) s').support,\n      (simulate so' \u2191(ob $ prod.fst x) x.2).support :=\ncalc (simulate so' (\u2191(oa >>= ob) : oracle_comp super_spec \u03b2) s').support =\n  (simulate so' \u2191oa s' >>= \u03bb (x : \u03b1 \u00d7 S'), simulate so' \u2191(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  ... = \u22c3 x \u2208 (simulate so' (\u2191oa : oracle_comp super_spec \u03b1) s').support,\n    (simulate so' \u2191(ob $ prod.fst x) x.2).support : by rw [support_bind]\n\n@[simp] lemma support_simulate'_coe_sub_spec_bind :\n  (simulate' so' (\u2191(oa >>= ob) : oracle_comp super_spec \u03b2) s').support =\n    \u22c3 x \u2208 (simulate so' (\u2191oa : oracle_comp super_spec \u03b1) s').support,\n      (simulate' so' \u2191(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' (\u2191(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 \u2282\u2092 spec'`,\nand a function `f : S \u2192 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 \u2192 S') (hf : \u2200 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' (\u2191oa : oracle_comp super_spec \u03b1) (f s)).support =\n    (prod.map id f) '' (simulate so oa s).support :=\nbegin\n  induction oa using oracle_comp.induction_on with \u03b1 a \u03b1 \u03b2 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, \u2190 hob, set.mem_Union],\n    refine \u27e8\u03bb h, let \u27e8x, \u27e8y', hy', hxy\u27e9, hx\u27e9 := h in \u27e8y', hy', by simpa only [\u2190 hxy] using hx\u27e9,\n      \u03bb h, let \u27e8x, hy, hx\u27e9 := h in \u27e8(x.1, f x.2), \u27e8x, hy, rfl\u27e9, hx\u27e9\u27e9 },\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 \u2192 S') (hf : \u2200 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' (\u2191oa : oracle_comp super_spec \u03b1) (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  \u2045simulate so' \u2191(return a : oracle_comp sub_spec \u03b1) s'\u2046 = 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  \u2045simulate so' (\u2191(oa >>= ob) : oracle_comp super_spec \u03b2) s'\u2046 =\n    \u2045simulate so' \u2191oa s'\u2046.bind (\u03bb x, \u2045simulate so' \u2191(ob $ prod.fst x) x.2\u2046) :=\ncalc \u2045simulate so' (\u2191(oa >>= ob) : oracle_comp super_spec \u03b2) s'\u2046\n  = \u2045simulate so' (default_simulate \u27eah.to_fun\u27eb oa) s'\u2046.bind (\u03bb (x : (\u03b1 \u00d7 unit) \u00d7 S'),\n      \u2045simulate so' (simulate \u27eah.to_fun\u27eb (ob x.1.1) x.1.2) x.2\u2046.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  ... = (\u2045simulate so' (default_simulate \u27eah.to_fun\u27eb oa) s'\u2046.map (prod.map prod.fst id)).bind\n      (\u03bb x, \u2045simulate so' (default_simulate \u27eah.to_fun\u27eb (ob x.1)) x.2\u2046.map (prod.map prod.fst id)) :\n    symm (trans (pmf.bind_map _ _ _) (congr_arg (\u03bb _, pmf.bind _ _) (funext $ \u03bb x, by simp only\n      [function.comp_app, prod_map, id.def, stateless_oracle.simulate_eq_default_simulate])))\n  ... = \u2045simulate so' (default_simulate' \u27eah.to_fun\u27eb oa) s'\u2046.bind (\u03bb (x : \u03b1 \u00d7 S'),\n      \u2045simulate so' (default_simulate \u27eah.to_fun\u27eb (ob x.1)) x.2\u2046.map (prod.map prod.fst id)) :\n    by rw [default_simulate', simulate', eval_dist_simulate_map]\n  ... = \u2045simulate so' \u2191oa s'\u2046.bind (\u03bb (x : \u03b1 \u00d7 S'), \u2045simulate so' \u2191(ob $ prod.fst x) x.2\u2046) :\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  \u2045simulate so' (\u2191(query i t) : oracle_comp super_spec _) s'\u2046 =\n    \u2045simulate so' (h.to_fun i t) s'\u2046 :=\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 \u2282\u2092 spec'`,\nand a function `f : S \u2192 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 \u2192 S') (hf : \u2200 i t s,\n  \u2045simulate so' (h.to_fun i t) (f s)\u2046 = pmf.map (prod.map id f) \u2045so i (t, s)\u2046) :\n  \u2045simulate so' (\u2191oa : oracle_comp super_spec \u03b1) (f s)\u2046 =\n    \u2045simulate so oa s\u2046.map (prod.map id f) :=\nbegin\n  induction oa using oracle_comp.induction_on with \u03b1 a \u03b1 \u03b2 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 (\u03bb _, pmf.bind _ _) (funext $ \u03bb 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 \u2192 S') (hf : \u2200 i t s,\n  \u2045simulate so' (h.to_fun i t) (f s)\u2046 = pmf.map (prod.map id f) \u2045so i (t, s)\u2046) :\n  \u2045simulate' so' (\u2191oa : oracle_comp super_spec \u03b1) (f s)\u2046 = \u2045simulate' so oa s\u2046 :=\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 (\u03b1 \u00d7 S')) (f : S \u2192 S') (hf : \u2200 i t s,\n  \u2045simulate so' (h.to_fun i t) (f s)\u2046 = pmf.map (prod.map id f) \u2045so i (t, s)\u2046) :\n  \u2045e | simulate so' (\u2191oa : oracle_comp super_spec \u03b1) (f s)\u2046 =\n    \u2045e | prod.map id f <$> simulate so oa s\u2046 :=\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 \u03b1) (f : S \u2192 S') (hf : \u2200 i t s,\n  \u2045simulate so' (h.to_fun i t) (f s)\u2046 = pmf.map (prod.map id f) \u2045so i (t, s)\u2046) :\n  \u2045e | simulate' so' (\u2191oa : oracle_comp super_spec \u03b1) (f s)\u2046 = \u2045e | simulate' so oa s\u2046 :=\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) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro, Minchao Wu\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.core\nimport Mathlib.PostPort\n\nuniverses l \n\nnamespace Mathlib\n\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\nnamespace tactic\n\n\nnamespace explode\n\n\ninductive status where\n| reg : status\n| intro : status\n| lam : status\n| sintro : status\n\n/--\nA type to distinguish introduction or elimination rules represented as \nstrings from theorems referred to by their names.\n-/\n/--\nTurn a thm into a string.\n-/\nend explode\n\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 : \u2200 {a : Prop}, a \u2192 (a \u2194 true)\n0\u2502   \u2502 a         \u251c Prop\n1\u2502   \u2502 h         \u251c a\n2\u2502   \u2502 hl        \u2502 \u250c a\n3\u2502   \u2502 trivial   \u2502 \u2502 true\n4\u25022,3\u2502 \u2200I        \u2502 a \u2192 true\n5\u2502   \u2502 hr        \u2502 \u250c true\n6\u25025,1\u2502 \u2200I        \u2502 true \u2192 a\n7\u25024,6\u2502 iff.intro \u2502 a \u2194 true\n8\u25021,7\u2502 \u2200I        \u2502 a \u2192 (a \u2194 true)\n9\u25020,8\u2502 \u2200I        \u2502 \u2200 {a : Prop}, a \u2192 (a \u2194 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 `\u2200E` 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 `\u2200E h ha` where `\u2200E` is\n    (n-ary) modus ponens.\n  * If the proof term is a lambda, we will also use `\u2200I` 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 `\u2200I` 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 `\u2200I` 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-/\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/explode_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.06754669301670264, "lm_q1q2_score": 0.03271827285606202}}
{"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 (\u03b1 : Sort u) where\n  /-- The \"size\" of an element, a natural number which decreases on fields of\n  each inductive type. -/\n  sizeOf : \u03b1 \u2192 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 `\u03b1` has a default `SizeOf` instance that just returns `0`\nfor every element of `\u03b1`.\n-/\nprotected def default.sizeOf (\u03b1 : Sort u) : \u03b1 \u2192 Nat\n  | _ => 0\n\ninstance (priority := low) (\u03b1 : Sort u) : SizeOf \u03b1 where\n  sizeOf := default.sizeOf \u03b1\n\n@[simp] theorem sizeOf_default (n : \u03b1) : 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 \u03b1] : SizeOf (Unit \u2192 \u03b1) where\n  sizeOf f := sizeOf (f ())\n\n@[simp] theorem sizeOf_thunk [SizeOf \u03b1] (f : Unit \u2192 \u03b1) : 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 \u2192 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 : \u2115} {\u03b1 : Fin n \u2192 Type u}\n\ninstance [\u2200 i, Inhabited (\u03b1 i)] : Inhabited (DArray n \u03b1) :=\n  \u27e8\u27e8default\u27e9\u27e9\n\nend DArray\n\nnamespace Array'\n\ninstance {n \u03b1} [Inhabited \u03b1] : Inhabited (Array' n \u03b1) :=\n  DArray.inhabited\n\ntheorem toList_of_hEq {n\u2081 n\u2082 \u03b1} {a\u2081 : Array' n\u2081 \u03b1} {a\u2082 : Array' n\u2082 \u03b1} (hn : n\u2081 = n\u2082)\n    (ha : HEq a\u2081 a\u2082) : a\u2081.toList = a\u2082.toList := by congr <;> assumption\n#align array.to_list_of_heq Array'.toList_of_hEq\n\n-- rev_list\nsection RevList\n\nvariable {n : \u2115} {\u03b1 : Type u} {a : Array' n \u03b1}\n\ntheorem rev_list_reverse_aux :\n    \u2200 (i) (h : i \u2264 n) (t : List \u03b1),\n      (a.iterateAux (fun _ => (\u00b7 :: \u00b7)) i h []).reverseAux t =\n        a.revIterateAux (fun _ => (\u00b7 :: \u00b7)) 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 [\u2190 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 : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : Array' n \u03b1}\n\ntheorem Mem.def : v \u2208 a \u2194 \u2203 i, a.read i = v :=\n  Iff.rfl\n#align array.mem.def Array'.Mem.def\n\ntheorem mem_rev_list_aux :\n    \u2200 {i} (h : i \u2264 n),\n      (\u2203 j : Fin n, (j : \u2115) < i \u2227 read a j = v) \u2194 v \u2208 a.iterateAux (fun _ => (\u00b7 :: \u00b7)) i h []\n  | 0, _ => \u27e8fun \u27e8i, n, _\u27e9 => absurd n i.val.not_lt_zero, False.elim\u27e9\n  | i + 1, h =>\n    let IH := mem_rev_list_aux (le_of_lt h)\n    \u27e8fun \u27e8j, ji1, e\u27e9 =>\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 \u27e8j, ji, e\u27e9) fun je => by\n        simp [DArray.iterateAux] <;> apply Or.inl <;> unfold read at e <;>\n            have H : j = \u27e8i, h\u27e9 := Fin.eq_of_veq je <;>\n          rwa [\u2190 H, e],\n      fun m => by\n      simp [DArray.iterateAux, List.Mem] at m\n      cases' m with e m'\n      exact \u27e8\u27e8i, h\u27e9, Nat.lt_succ_self _, Eq.symm e\u27e9\n      exact\n        let \u27e8j, ji, e\u27e9 := IH.2 m'\n        \u27e8j, Nat.le_succ_of_le ji, e\u27e9\u27e9\n#align array.mem_rev_list_aux Array'.mem_rev_list_aux\n\n@[simp]\ntheorem mem_revList : v \u2208 a.revList \u2194 v \u2208 a :=\n  Iff.symm <|\n    Iff.trans\n      (exists_congr fun j =>\n        Iff.symm <| show j.1 < n \u2227 read a j = v \u2194 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 \u2208 a.toList \u2194 v \u2208 a := by\n  rw [\u2190 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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type w} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {a : Array' n \u03b1}\n\ntheorem rev_list_foldr_aux :\n    \u2200 {i} (h : i \u2264 n),\n      (DArray.iterateAux a (fun _ => (\u00b7 :: \u00b7)) 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 \u27e8j, h\u27e9)) (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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type w} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {a : Array' n \u03b1}\n\ntheorem toList_foldl : a.toList.foldl f b = a.foldl b (Function.swap f) := by\n  rw [\u2190 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 : \u2115} {\u03b1 : Type u}\n\ntheorem rev_list_length_aux (a : Array' n \u03b1) (i h) :\n    (a.iterateAux (fun _ => (\u00b7 :: \u00b7)) 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 \u03b1) : 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 \u03b1) : a.toList.length = n := by\n  rw [\u2190 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 : \u2115} {\u03b1 : Type u} {a : Array' n \u03b1}\n\ntheorem to_list_nthLe_aux (i : \u2115) (ih : i < n) :\n    \u2200 (j) {jh t h'},\n      (\u2200 k tl, j + k = i \u2192 List.nthLe t k tl = a.read \u27e8i, ih\u27e9) \u2192\n        (a.revIterateAux (fun _ => (\u00b7 :: \u00b7)) j jh t).nthLe i h' = a.read \u27e8i, ih\u27e9\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 \u27e8j, jh\u27e9 :: t) k tl = a.read \u27e8i, ih\u27e9 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 : \u2115) (h h') : List.nthLe a.toList i h' = a.read \u27e8i, h\u27e9 :=\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 \u03b1) (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 \u2194 \u2203 h, a.read \u27e8i, h\u27e9 = 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  \u00b7 exact \u27e8ll \u25b8 h, (to_list_nth_le _ _ _).symm\u27e9\n  \u00b7 exact \u27e8ll.symm \u25b8 h, to_list_nth_le _ _ _\u27e9\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\u2081 h\u2082 =>\n    by\n    have h\u2083 : j < n := by simpa using h\u2081\n    rw [to_list_nth_le _ h\u2083]\n    refine'\n      let \u27e8_, e\u27e9 := List.get?_eq_some'.1 _\n      e.symm\n    by_cases ij : (i : \u2115) = j\n    \u00b7 subst j\n      rw [show (\u27e8(i : \u2115), h\u2083\u27e9 : Fin _) = i from Fin.eq_of_veq rfl, Array'.read_write,\n        List.get?_set_eq_of_lt]\n      simp [h\u2083]\n    \u00b7 rw [List.get?_set_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 \u27e8h\u2083, rfl\u27e9]\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 : \u2115} {\u03b1 : Type u} {a : Array' n \u03b1}\n\ntheorem mem_toList_enum {i v} : (i, v) \u2208 a.toList.enum \u2194 \u2203 h, a.read \u27e8i, h\u27e9 = 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 : \u2115} {\u03b1 : Type u}\n\n@[simp]\ntheorem toList_toArray (a : Array' n \u03b1) : 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 _ => \u03b1) fun v => a.toList.nthLe v.1 <| e.symm \u25b8 v.2))\n        a.toList_length HEq.rfl) <|\n    DArray.ext fun \u27e8i, h\u27e9 => toList_nthLe i h _\n#align array.to_list_to_array Array'.toList_toArray\n\n@[simp]\ntheorem toArray_toList (l : List \u03b1) : 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 : \u2115} {\u03b1 : Type u} {v : \u03b1} {a : Array' n \u03b1}\n\ntheorem pushBack_rev_list_aux :\n    \u2200 i h h',\n      DArray.iterateAux (a.pushBack v) (fun _ => (\u00b7 :: \u00b7)) i h [] =\n        DArray.iterateAux a (fun _ => (\u00b7 :: \u00b7)) i h' []\n  | 0, h, h' => rfl\n  | i + 1, h, h' => by\n    simp [DArray.iterateAux]\n    refine' \u27e8_, push_back_rev_list_aux _ _ _\u27e9\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 [\u2190 rev_list_reverse, \u2190 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 : \u00aci = 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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {i : Fin n} {f : Fin n \u2192 \u03b1 \u2192 \u03b2} {a : Array' n \u03b1}\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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {i : Fin n} {f : \u03b1 \u2192 \u03b2} {a : Array' n \u03b1}\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\u2082\nsection Map\u2082\n\nvariable {n : \u2115} {\u03b1 : Type u} {i : Fin n} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {a\u2081 a\u2082 : Array' n \u03b1}\n\n@[simp]\ntheorem read_map\u2082 : (map\u2082 f a\u2081 a\u2082).read i = f (a\u2081.read i) (a\u2082.read i) :=\n  read_foreach\n#align array.read_map\u2082 Array'.read_map\u2082\n\nend Map\u2082\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) 2023 Heather Macbeth. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Heather Macbeth\n-/\nimport Mathlib.Tactic.LabelAttr\n\n/-! # The @[mono] attribute -/\n\nnamespace Mathlib.Tactic.Monotonicity\n\nsyntax mono.side := &\"left\" <|> &\"right\" <|> &\"both\"\n\nnamespace Attr\n\n/-- A lemma stating the monotonicity of some function, with respect to appropriate relations on its\ndomain and range, and possibly with side conditions. -/\nsyntax (name := mono) \"mono\" (ppSpace mono.side)? : attr\n\n-- The following is inlined from `register_label_attr`.\n/- TODO: currently `left`/`right`/`both` is ignored, and e.g. `@[mono left]` means the same as\n`@[mono]`. No error is thrown by e.g. `@[mono left]`. -/\n-- TODO: possibly extend `register_label_attr` to handle trailing syntax\n\nopen LabelAttr in\n@[inherit_doc mono]\ninitialize ext : LabelExtension \u2190 (\n  let descr := \"A lemma stating the monotonicity of some function, with respect to appropriate\nrelations on its domain and range, and possibly with side conditions.\"\n  let mono := `mono\n  registerLabelAttr mono descr mono)\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/Monotonicity/Attr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.06560484430997267, "lm_q1q2_score": 0.0325461584455778}}
{"text": "/-\nCopyright 2022 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    https://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\nAuthors: Moritz Firsching\n-/\nimport tactic\n/-!\n# Pigeon-hole and double counting\n\n## TODO\n  - statement\n  - 1. Numbers\n    - Claim\n    - Claim\n  - 2. Sequences\n    - Claim\n      - proof\n  - 3. Sums\n    - Claim\n  - Double Counting\n  - 4. Numbers again\n  - 5. Graphs\n    - Theorem\n      - proof\n    - Claim\n  - 6. Sperner's Lemma\n    - proof\n    - Proof of Brouwer's fixed point theorem (for $n = 2$)\n-/\n", "meta": {"author": "mo271", "repo": "formal_book", "sha": "34cbc0b9e9d361b74adbe0fd06192a72e684b992", "save_path": "github-repos/lean/mo271-formal_book", "path": "github-repos/lean/mo271-formal_book/formal_book-34cbc0b9e9d361b74adbe0fd06192a72e684b992/src/chapters/28_Pigeon-hole_and_double_counting.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.06954174643420795, "lm_q1q2_score": 0.03233006616216647}}
{"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\n-/\nprelude\nimport Init.Control.Except\nimport Init.Data.ByteArray\nimport Init.SimpLemmas\nimport Init.Data.Nat.Linear\nimport Init.Util\nimport Init.WFTactics\n\nnamespace String\n\n/-- Interpret the string as the decimal representation of a natural number.\n\nPanics if the string is not a string of digits. -/\ndef toNat! (s : String) : Nat :=\n  if s.isNat then\n    s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0\n  else\n    panic! \"Nat expected\"\n\n/--\n  Convert a [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoded `ByteArray` string to `String`.\n  The result is unspecified if `a` is not properly UTF-8 encoded.\n-/\n@[extern \"lean_string_from_utf8_unchecked\"]\nopaque fromUTF8Unchecked (a : @& ByteArray) : String\n\n/-- Convert the given `String` to a [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoded byte array. -/\n@[extern \"lean_string_to_utf8\"]\nopaque toUTF8 (a : @& String) : ByteArray\n\ntheorem one_le_csize (c : Char) : 1 \u2264 csize c := by\n  simp [csize, Char.utf8Size]\n  repeat (first | split | decide)\n\n@[simp] theorem pos_lt_eq (p\u2081 p\u2082 : Pos) : (p\u2081 < p\u2082) = (p\u2081.1 < p\u2082.1) := rfl\n\n@[simp] theorem pos_add_char (p : Pos) (c : Char) : (p + c).byteIdx = p.byteIdx + csize c := rfl\n\ntheorem eq_empty_of_bsize_eq_zero (h : s.endPos = {}) : s = \"\" := by\n  match s with\n  | \u27e8[]\u27e9   => rfl\n  | \u27e8c::cs\u27e9 =>\n    injection h with h\n    simp [endPos, utf8ByteSize, utf8ByteSize.go] at h\n    have : utf8ByteSize.go cs + 1 \u2264 utf8ByteSize.go cs + csize c := Nat.add_le_add_left (one_le_csize c) _\n    simp_arith [h] at this\n\ntheorem lt_next (s : String) (i : String.Pos) : i.1 < (s.next i).1 := by\n  simp_arith [next]; apply one_le_csize\n\ntheorem Iterator.sizeOf_next_lt_of_hasNext (i : String.Iterator) (h : i.hasNext) : sizeOf i.next < sizeOf i := by\n  cases i; rename_i s pos; simp [Iterator.next, Iterator.sizeOf_eq]; simp [Iterator.hasNext] at h\n  have := String.lt_next s pos\n  apply Nat.sub.elim (motive := fun k => k < _) (utf8ByteSize s) (String.next s pos).1\n  . intro _ k he\n    simp [he]; rw [Nat.add_comm, Nat.add_sub_assoc (Nat.le_of_lt this)]\n    have := Nat.zero_lt_sub_of_lt this\n    simp_all_arith\n  . intro; apply Nat.zero_lt_sub_of_lt h\n\nmacro_rules | `(tactic| decreasing_trivial) => `(tactic| apply String.Iterator.sizeOf_next_lt_of_hasNext; assumption)\n\ntheorem Iterator.sizeOf_next_lt_of_atEnd (i : String.Iterator) (h : \u00ac i.atEnd = true) : sizeOf i.next < sizeOf i :=\n  have h : i.hasNext = true := by simp_arith [atEnd] at h; simp_arith [hasNext, h]\n  sizeOf_next_lt_of_hasNext i h\n\nmacro_rules | `(tactic| decreasing_trivial) => `(tactic| apply String.Iterator.sizeOf_next_lt_of_atEnd; assumption)\n\nnamespace Iterator\n\n/-- Advance the given iterator until the predicate returns true or the end of the string is reached. -/\n@[specialize] def find (it : Iterator) (p : Char \u2192 Bool) : Iterator :=\n  if it.atEnd then it\n  else if p it.curr then it\n  else find it.next p\n\n@[specialize] def foldUntil (it : Iterator) (init : \u03b1) (f : \u03b1 \u2192 Char \u2192 Option \u03b1) : \u03b1 \u00d7 Iterator :=\n  if it.atEnd then\n    (init, it)\n  else if let some a := f init it.curr then\n    foldUntil it.next a f\n  else\n    (init, it)\n\nend Iterator\n\nend String\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/String/Extra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.06656919221123701, "lm_q1q2_score": 0.03224479093352976}}
{"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 {\u03b1 : Type u_1} : Inhabited (buffer \u03b1) :=\n  { default := nil }\n\ntheorem ext {\u03b1 : Type u_1} {b\u2081 : buffer \u03b1} {b\u2082 : buffer \u03b1} : to_list b\u2081 = to_list b\u2082 \u2192 b\u2081 = b\u2082 := sorry\n\nprotected instance decidable_eq (\u03b1 : Type u_1) [DecidableEq \u03b1] : DecidableEq (buffer \u03b1) :=\n  id\n    fun (_v : buffer \u03b1) =>\n      sigma.cases_on _v\n        fun (fst : \u2115) (snd : array fst \u03b1) (w : buffer \u03b1) =>\n          sigma.cases_on w\n            fun (w_fst : \u2115) (w_snd : array w_fst \u03b1) =>\n              decidable.by_cases\n                (fun (\u1fb0 : fst = w_fst) =>\n                  Eq._oldrec\n                    (fun (w_snd : array fst \u03b1) =>\n                      decidable.by_cases (fun (\u1fb0 : snd = w_snd) => Eq._oldrec (is_true sorry) \u1fb0)\n                        fun (\u1fb0 : \u00acsnd = w_snd) => isFalse sorry)\n                    \u1fb0 w_snd)\n                fun (\u1fb0 : \u00acfst = w_fst) => isFalse sorry\n\n@[simp] theorem to_list_append_list {\u03b1 : Type u_1} {xs : List \u03b1} {b : buffer \u03b1} : to_list (append_list b xs) = to_list b ++ xs := sorry\n\n@[simp] theorem append_list_mk_buffer {\u03b1 : Type u_1} {xs : List \u03b1} : 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 (\u03b1 : Type u_1) : List \u03b1 \u2243 buffer \u03b1 :=\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": "example : 2 + 3 = 5 :=\nbegin\n  generalize : 3 = x,\n  sorry\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/ex0218.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4225046348141882, "lm_q2_score": 0.07585817636504989, "lm_q1q2_score": 0.03205043110278569}}
{"text": "/-\nCopyright (c) 2022 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Aesop\n\nset_option aesop.check.all true\n\n-- These test cases test the builtin subst tactic.\n\nexample (h\u2081 : x = 5) (h\u2082 : y = 5) : x = y := by\n  fail_if_success\n    aesop\n      (erase Aesop.BuiltinRules.subst)\n      (simp_options := { useHyps := false })\n      (options := { terminal := true })\n  aesop (simp_options := { useHyps := false })\n\nexample (h\u2081 : x = y) (h\u2082 : y = z) : x = z := by\n  fail_if_success\n    aesop\n      (erase Aesop.BuiltinRules.subst)\n      (simp_options := { useHyps := false })\n      (options := { terminal := true })\n  aesop (simp_options := { useHyps := false })\n\nexample (P : \u2200 x y, x = y \u2192 Prop) (h\u2081 : x = y) (h\u2082 : P x y h\u2081) : x = y := by\n  fail_if_success\n    aesop\n      (erase Aesop.BuiltinRules.subst,\n             Aesop.BuiltinRules.assumption,\n             Aesop.BuiltinRules.applyHyps)\n      (simp_options := { useHyps := false })\n      (options := { terminal := true })\n  aesop\n    (erase Aesop.BuiltinRules.assumption,\n           Aesop.BuiltinRules.applyHyps)\n    (simp_options := { useHyps := false })\n\n-- Subst also works for bi-implications.\nexample (h\u2081 : P \u2194 Q) (h\u2082 : Q \u2194 R) (h\u2083 : P) : R  := by\n  fail_if_success\n    aesop\n      (erase Aesop.BuiltinRules.subst)\n      (simp_options := { useHyps := false })\n      (options := { terminal := true })\n  aesop (simp_options := { useHyps := false })\n\n-- Subst also works for morally-homogeneous heterogeneous equalities (using a\n-- builtin simp rule which turns these into actual homogeneous equalities).\nexample {P : \u03b1 \u2192 Prop} {x y z : \u03b1} (h\u2081 : HEq x y) (h\u2082 : HEq y z) (h\u2083 : P x) :\n    P z  := by\n  fail_if_success\n    aesop\n      (erase Aesop.BuiltinRules.subst)\n      (simp_options := { useHyps := false })\n      (options := { terminal := true })\n  aesop (simp_options := { useHyps := false })\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/run/Subst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828338040285596, "lm_q2_score": 0.06560483426198128, "lm_q1q2_score": 0.032033750244209326}}
{"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-/\nprelude\nimport Init.Data.Nat.Basic\nimport Init.Data.Fin.Basic\nimport Init.Data.UInt\nimport Init.Data.Repr\nimport Init.Data.ToString.Basic\nimport Init.Util\nuniverses u v w\n\nnamespace Array\nvariable {\u03b1 : Type u}\n\n@[extern \"lean_mk_array\"]\ndef mkArray {\u03b1 : Type u} (n : Nat) (v : \u03b1) : Array \u03b1 := {\n  data := List.replicate n v\n}\n\n@[simp] theorem size_mkArray (n : Nat) (v : \u03b1) : (mkArray n v).size = n :=\n  List.length_replicate ..\n\ninstance : EmptyCollection (Array \u03b1) := \u27e8Array.empty\u27e9\ninstance : Inhabited (Array \u03b1) where\n  default := Array.empty\n\ndef isEmpty (a : Array \u03b1) : Bool :=\n  a.size = 0\n\ndef singleton (v : \u03b1) : Array \u03b1 :=\n  mkArray 1 v\n\n/- Low-level version of `fget` which is as fast as a C array read.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fget` may be slightly slower than `uget`. -/\n@[extern \"lean_array_uget\"]\ndef uget (a : @& Array \u03b1) (i : USize) (h : i.toNat < a.size) : \u03b1 :=\n  a.get \u27e8i.toNat, h\u27e9\n\ndef back [Inhabited \u03b1] (a : Array \u03b1) : \u03b1 :=\n  a.get! (a.size - 1)\n\ndef get? (a : Array \u03b1) (i : Nat) : Option \u03b1 :=\n  if h : i < a.size then some (a.get \u27e8i, h\u27e9) else none\n\ndef back? (a : Array \u03b1) : Option \u03b1 :=\n  a.get? (a.size - 1)\n\n-- auxiliary declaration used in the equation compiler when pattern matching array literals.\nabbrev getLit {\u03b1 : Type u} {n : Nat} (a : Array \u03b1) (i : Nat) (h\u2081 : a.size = n) (h\u2082 : i < n) : \u03b1 :=\n  a.get \u27e8i, h\u2081.symm \u25b8 h\u2082\u27e9\n\n@[simp] theorem size_set (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : (set a i v).size = a.size :=\n  List.length_set ..\n\n@[simp] theorem size_push (a : Array \u03b1) (v : \u03b1) : (push a v).size = a.size + 1 :=\n  List.length_concat ..\n\n/- Low-level version of `fset` which is as fast as a C array fset.\n   `Fin` values are represented as tag pointers in the Lean runtime. Thus,\n   `fset` may be slightly slower than `uset`. -/\n@[extern \"lean_array_uset\"]\ndef uset (a : Array \u03b1) (i : USize) (v : \u03b1) (h : i.toNat < a.size) : Array \u03b1 :=\n  a.set \u27e8i.toNat, h\u27e9 v\n\n@[extern \"lean_array_fswap\"]\ndef swap (a : Array \u03b1) (i j : @& Fin a.size) : Array \u03b1 :=\n  let v\u2081 := a.get i\n  let v\u2082 := a.get j\n  let a'  := a.set i v\u2082\n  a'.set (size_set a i v\u2082 \u25b8 j) v\u2081\n\n@[extern \"lean_array_swap\"]\ndef swap! (a : Array \u03b1) (i j : @& Nat) : Array \u03b1 :=\n  if h\u2081 : i < a.size then\n  if h\u2082 : j < a.size then swap a \u27e8i, h\u2081\u27e9 \u27e8j, h\u2082\u27e9\n  else panic! \"index out of bounds\"\n  else panic! \"index out of bounds\"\n\n@[inline] def swapAt (a : Array \u03b1) (i : Fin a.size) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  let e := a.get i\n  let a := a.set i v\n  (e, a)\n\n@[inline]\ndef swapAt! (a : Array \u03b1) (i : Nat) (v : \u03b1) : \u03b1 \u00d7 Array \u03b1 :=\n  if h : i < a.size then\n    swapAt a \u27e8i, h\u27e9 v\n  else\n    have : Inhabited \u03b1 := \u27e8v\u27e9\n    panic! (\"index \" ++ toString i ++ \" out of bounds\")\n\n@[extern \"lean_array_pop\"]\ndef pop (a : Array \u03b1) : Array \u03b1 := {\n  data := a.data.dropLast\n}\n\ndef shrink (a : Array \u03b1) (n : Nat) : Array \u03b1 :=\n  let rec loop\n    | 0,   a => a\n    | n+1, a => loop n a.pop\n  loop (a.size - n) a\n\n@[inline]\ndef modifyM [Monad m] [Inhabited \u03b1] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 m \u03b1) : m (Array \u03b1) := do\n  if h : i < a.size then\n    let idx : Fin a.size := \u27e8i, h\u27e9\n    let v                := a.get idx\n    let a'               := a.set idx arbitrary\n    let v \u2190 f v\n    pure <| a'.set (size_set a .. \u25b8 idx) v\n  else\n    pure a\n\n@[inline]\ndef modify [Inhabited \u03b1] (a : Array \u03b1) (i : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  Id.run <| a.modifyM i f\n\n@[inline]\ndef modifyOp [Inhabited \u03b1] (self : Array \u03b1) (idx : Nat) (f : \u03b1 \u2192 \u03b1) : Array \u03b1 :=\n  self.modify idx f\n\n/-\n  We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime.\n\n  This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/\n@[inline] unsafe def forInUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] loop (i : USize) (b : \u03b2) : m \u03b2 := do\n    if i < sz then\n      let a := as.uget i lcProof\n      match (\u2190 f a b) with\n      | ForInStep.done  b => pure b\n      | ForInStep.yield b => loop (i+1) b\n    else\n      pure b\n  loop 0 b\n\n-- Move?\nprivate theorem zeroLtOfLt : {a b : Nat} \u2192 a < b \u2192 0 < b\n  | 0,   _, h => h\n  | a+1, b, h =>\n    have : a < b := Nat.ltTrans (Nat.ltSuccSelf _) h\n    zeroLtOfLt this\n\n/- Reference implementation for `forIn` -/\n@[implementedBy Array.forInUnsafe]\nprotected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec loop (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    match i, h with\n    | 0,   _ => pure b\n    | i+1, h =>\n      have h' : i < as.size            := Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h\n      have : as.size - 1 < as.size     := Nat.subLt (zeroLtOfLt h') (by decide)\n      have : as.size - 1 - i < as.size := Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this\n      match (\u2190 f (as.get \u27e8as.size - 1 - i, this\u27e9) b) with\n      | ForInStep.done b  => pure b\n      | ForInStep.yield b => loop i (Nat.leOfLt h') b\n  loop as.size (Nat.leRefl _) b\n\ninstance : ForIn m (Array \u03b1) \u03b1 where\n  forIn := Array.forIn\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def foldlMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i+1) stop (\u2190 f b (as.uget i lcProof))\n  if start < stop then\n    if stop \u2264 as.size then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else\n    pure init\n\n/- Reference implementation for `foldlM` -/\n@[implementedBy foldlMUnsafe]\ndef foldlM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : m \u03b2 :=\n  let fold (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) (b : \u03b2) : m \u03b2 := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure b\n        | i'+1 =>\n          loop i' (j+1) (\u2190 f b (as.get \u27e8j, Nat.ltOfLtOfLe hlt h\u27e9))\n      else\n        pure b\n    loop (stop - start) start init\n  if h : stop \u2264 as.size then\n    fold stop h\n  else\n    fold as.size (Nat.leRefl _)\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def foldrMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec @[specialize] fold (i : USize) (stop : USize) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else\n      fold (i-1) stop (\u2190 f (as.uget (i-1) lcProof) b)\n  if start \u2264 as.size then\n    if stop < start then\n      fold (USize.ofNat start) (USize.ofNat stop) init\n    else\n      pure init\n  else if stop < as.size then\n    fold (USize.ofNat as.size) (USize.ofNat stop) init\n  else\n    pure init\n\n/- Reference implementation for `foldrM` -/\n@[implementedBy foldrMUnsafe]\ndef foldrM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : m \u03b2 :=\n  let rec fold (i : Nat) (h : i \u2264 as.size) (b : \u03b2) : m \u03b2 := do\n    if i == stop then\n      pure b\n    else match i, h with\n      | 0, _   => pure b\n      | i+1, h =>\n        have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h\n        fold i (Nat.leOfLt this) (\u2190 f (as.get \u27e8i, this\u27e9) b)\n  if h : start \u2264 as.size then\n    if stop < start then\n      fold start h init\n    else\n      pure init\n  else if stop < as.size then\n    fold as.size (Nat.leRefl _) init\n  else\n    pure init\n\n/- See comment at forInUnsafe -/\n@[inline]\nunsafe def mapMUnsafe {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  let sz := USize.ofNat as.size\n  let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do\n    if i < sz then\n     let v    := r.uget i lcProof\n     let r    := r.uset i arbitrary lcProof\n     let vNew \u2190 f (unsafeCast v)\n     map (i+1) (r.uset i (unsafeCast vNew) lcProof)\n    else\n     pure (unsafeCast r)\n  unsafeCast <| map 0 (unsafeCast as)\n\n/- Reference implementation for `mapM` -/\n@[implementedBy mapMUnsafe]\ndef mapM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m \u03b2) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (fun bs a => do let b \u2190 f a; pure (bs.push b)) (mkEmpty as.size)\n\n@[inline]\ndef mapIdxM {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 m \u03b2) : m (Array \u03b2) :=\n  let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array \u03b2) : m (Array \u03b2) := do\n    match i, inv with\n    | 0,    _  => pure bs\n    | i+1, inv =>\n      have : j < as.size := by rw [\u2190 inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_left_comm]; apply Nat.leAddRight\n      let idx : Fin as.size := \u27e8j, this\u27e9\n      have : i + (j + 1) = as.size := by rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n      map i (j+1) this (bs.push (\u2190 f idx (as.get idx)))\n  map as.size 0 rfl (mkEmpty as.size)\n\n@[inline]\ndef findSomeM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) := do\n  for a in as do\n    match (\u2190 f a) with\n    | some b => return b\n    | _      => pure \u27e8\u27e9\n  return none\n\n@[inline]\ndef findM? {\u03b1 : Type} {m : Type \u2192 Type} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) := do\n  for a in as do\n    if (\u2190 p a) then\n      return a\n  return none\n\n@[inline]\ndef findIdxM? [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option Nat) := do\n  let mut i := 0\n  for a in as do\n    if (\u2190 p a) then\n      return some i\n    i := i + 1\n  return none\n\n@[inline]\nunsafe def anyMUnsafe {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do\n    if i == stop then\n      pure false\n    else\n      if (\u2190 p (as.uget i lcProof)) then\n        pure true\n      else\n        any (i+1) stop\n  if start < stop then\n    if stop \u2264 as.size then\n      any (USize.ofNat start) (USize.ofNat stop)\n    else\n      pure false\n  else\n    pure false\n\n@[implementedBy anyMUnsafe]\ndef anyM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  let any (stop : Nat) (h : stop \u2264 as.size) :=\n    let rec loop (i : Nat) (j : Nat) : m Bool := do\n      if hlt : j < stop then\n        match i with\n        | 0    => pure false\n        | i'+1 =>\n          if (\u2190 p (as.get \u27e8j, Nat.ltOfLtOfLe hlt h\u27e9)) then\n            pure true\n          else\n            loop i' (j+1)\n      else\n        pure false\n    loop (stop - start) start\n  if h : stop \u2264 as.size then\n    any stop h\n  else\n    any as.size (Nat.leRefl _)\n\n@[inline]\ndef allM {\u03b1 : Type u} {m : Type \u2192 Type w} [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m Bool :=\n  return !(\u2190 as.anyM fun v => return !(\u2190 p v))\n\n@[inline]\ndef findSomeRevM? {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : Array \u03b1) (f : \u03b1 \u2192 m (Option \u03b2)) : m (Option \u03b2) :=\n  let rec @[specialize] find : (i : Nat) \u2192 i \u2264 as.size \u2192 m (Option \u03b2)\n    | 0,   h => pure none\n    | i+1, h => do\n      have : i < as.size := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h\n      let r \u2190 f (as.get \u27e8i, this\u27e9)\n      match r with\n      | some v => pure r\n      | none   =>\n        have : i \u2264 as.size := Nat.leOfLt this\n        find i this\n  find as.size (Nat.leRefl _)\n\n@[inline]\ndef findRevM? {\u03b1 : Type} {m : Type \u2192 Type w} [Monad m] (as : Array \u03b1) (p : \u03b1 \u2192 m Bool) : m (Option \u03b1) :=\n  as.findSomeRevM? fun a => return if (\u2190 p a) then some a else none\n\n@[inline]\ndef forM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := 0) (stop := as.size) : m PUnit :=\n  as.foldlM (fun _ => f) \u27e8\u27e9 start stop\n\n@[inline]\ndef forRevM {\u03b1 : Type u} {m : Type v \u2192 Type w} [Monad m] (f : \u03b1 \u2192 m PUnit) (as : Array \u03b1) (start := as.size) (stop := 0) : m PUnit :=\n  as.foldrM (fun a _ => f a) \u27e8\u27e9 start stop\n\n@[inline]\ndef foldl {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : \u03b2 :=\n  Id.run <| as.foldlM f init start stop\n\n@[inline]\ndef foldr {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (init : \u03b2) (as : Array \u03b1) (start := as.size) (stop := 0) : \u03b2 :=\n  Id.run <| as.foldrM f init start stop\n\n@[inline]\ndef map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  Id.run <| as.mapM f\n\n@[inline]\ndef mapIdx {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : Fin as.size \u2192 \u03b1 \u2192 \u03b2) : Array \u03b2 :=\n  Id.run <| as.mapIdxM f\n\n@[inline]\ndef find? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findM? p\n\n@[inline]\ndef findSome? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeM? f\n\n@[inline]\ndef findSome! {\u03b1 : Type u} {\u03b2 : Type v} [Inhabited \u03b2] (a : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : \u03b2 :=\n  match findSome? a f with\n  | some b => b\n  | none   => panic! \"failed to find element\"\n\n@[inline]\ndef findSomeRev? {\u03b1 : Type u} {\u03b2 : Type v} (as : Array \u03b1) (f : \u03b1 \u2192 Option \u03b2) : Option \u03b2 :=\n  Id.run <| as.findSomeRevM? f\n\n@[inline]\ndef findRev? {\u03b1 : Type} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option \u03b1 :=\n  Id.run <| as.findRevM? p\n\n@[inline]\ndef findIdx? {\u03b1 : Type u} (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option Nat :=\n  let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat :=\n    if hlt : j < as.size then\n      match i, inv with\n      | 0, inv => by\n        apply False.elim\n        rw [Nat.zero_add] at inv\n        rw [inv] at hlt\n        exact absurd hlt (Nat.ltIrrefl _)\n      | i+1, inv =>\n        if p (as.get \u27e8j, hlt\u27e9) then\n          some j\n        else\n          have : i + (j+1) = as.size := by\n            rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n          loop i (j+1) this\n    else\n      none\n  loop as.size 0 rfl\n\ndef getIdx? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option Nat :=\na.findIdx? fun a => a == v\n\n@[inline]\ndef any (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.anyM p start stop\n\n@[inline]\ndef all (as : Array \u03b1) (p : \u03b1 \u2192 Bool) (start := 0) (stop := as.size) : Bool :=\n  Id.run <| as.allM p start stop\n\ndef contains [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Bool :=\n  as.any fun b => a == b\n\ndef elem [BEq \u03b1] (a : \u03b1) (as : Array \u03b1) : Bool :=\n  as.contains a\n\n-- TODO(Leo): justify termination using wf-rec, and use `swap`\npartial def reverse (as : Array \u03b1) : Array \u03b1 :=\n  let n   := as.size\n  let mid := n / 2\n  let rec rev (as : Array \u03b1) (i : Nat) :=\n    if i < mid then\n      rev (as.swap! i (n - i - 1)) (i+1)\n    else\n      as\n  rev as 0\n\n@[inline] def getEvenElems (as : Array \u03b1) : Array \u03b1 :=\n  (\u00b7.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a =>\n    if even then\n      (false, r.push a)\n    else\n      (true, r)\n\n@[export lean_array_to_list]\ndef toList (as : Array \u03b1) : List \u03b1 :=\n  as.foldr List.cons []\n\ninstance {\u03b1 : Type u} [Repr \u03b1] : Repr (Array \u03b1) where\n  reprPrec a _ :=\n    if a.size == 0 then\n      \"#[]\"\n    else\n      Std.Format.bracketFill \"#[\" (@Std.Format.joinSep _ \u27e8repr\u27e9 (toList a) (\",\" ++ Std.Format.line)) \"]\"\n\ninstance [ToString \u03b1] : ToString (Array \u03b1) where\n  toString a := \"#\" ++ toString a.toList\n\nprotected def append (as : Array \u03b1) (bs : Array \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : Append (Array \u03b1) := \u27e8Array.append\u27e9\n\nprotected def appendList (as : Array \u03b1) (bs : List \u03b1) : Array \u03b1 :=\n  bs.foldl (init := as) fun r v => r.push v\n\ninstance : HAppend (Array \u03b1) (List \u03b1) (Array \u03b1) := \u27e8Array.appendList\u27e9\n\n@[inline]\ndef concatMapM [Monad m] (f : \u03b1 \u2192 m (Array \u03b2)) (as : Array \u03b1) : m (Array \u03b2) :=\n  as.foldlM (init := empty) fun bs a => do return bs ++ (\u2190 f a)\n\n@[inline]\ndef concatMap (f : \u03b1 \u2192 Array \u03b2) (as : Array \u03b1) : Array \u03b2 :=\n  as.foldl (init := empty) fun bs a => bs ++ f a\n\nend Array\n\nexport Array (mkArray)\n\nsyntax \"#[\" sepBy(term, \", \") \"]\" : term\n\nmacro_rules\n  | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ])\n\nnamespace Array\n\n-- TODO(Leo): cleanup\n@[specialize]\npartial def isEqvAux (a b : Array \u03b1) (hsz : a.size = b.size) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) (i : Nat) : Bool :=\n  if h : i < a.size then\n     let aidx : Fin a.size := \u27e8i, h\u27e9;\n     let bidx : Fin b.size := \u27e8i, hsz \u25b8 h\u27e9;\n     match p (a.get aidx) (b.get bidx) with\n     | true  => isEqvAux a b hsz p (i+1)\n     | false => false\n  else\n    true\n\n@[inline] def isEqv (a b : Array \u03b1) (p : \u03b1 \u2192 \u03b1 \u2192 Bool) : Bool :=\n  if h : a.size = b.size then\n    isEqvAux a b h p 0\n  else\n    false\n\ninstance [BEq \u03b1] : BEq (Array \u03b1) :=\n  \u27e8fun a b => isEqv a b BEq.beq\u27e9\n\n@[inline]\ndef filter (p : \u03b1 \u2192 Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b1 :=\n  as.foldl (init := #[]) (start := start) (stop := stop) fun r a =>\n    if p a then r.push a else r\n\n@[inline]\ndef filterM [Monad m] (p : \u03b1 \u2192 m Bool) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b1) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do\n    if (\u2190 p a) then r.push a else r\n\n@[specialize]\ndef filterMapM [Monad m] (f : \u03b1 \u2192 m (Option \u03b2)) (as : Array \u03b1) (start := 0) (stop := as.size) : m (Array \u03b2) :=\n  as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do\n    match (\u2190 f a) with\n    | some b => pure (bs.push b)\n    | none   => pure bs\n\n@[inline]\ndef filterMap (f : \u03b1 \u2192 Option \u03b2) (as : Array \u03b1) (start := 0) (stop := as.size) : Array \u03b2 :=\n  Id.run <| as.filterMapM f (start := start) (stop := stop)\n\n@[specialize]\ndef getMax? (as : Array \u03b1) (lt : \u03b1 \u2192 \u03b1 \u2192 Bool) : Option \u03b1 :=\n  if h : 0 < as.size then\n    let a0 := as.get \u27e80, h\u27e9\n    some <| as.foldl (init := a0) (start := 1) fun best a =>\n      if lt best a then a else best\n  else\n    none\n\n@[inline]\ndef partition (p : \u03b1 \u2192 Bool) (as : Array \u03b1) : Array \u03b1 \u00d7 Array \u03b1 := do\n  let mut bs := #[]\n  let mut cs := #[]\n  for a in as do\n    if p a then\n      bs := bs.push a\n    else\n      cs := cs.push a\n  return (bs, cs)\n\ntheorem ext (a b : Array \u03b1)\n    (h\u2081 : a.size = b.size)\n    (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.size) \u2192 (hi\u2082 : i < b.size) \u2192 a.get \u27e8i, hi\u2081\u27e9 = b.get \u27e8i, hi\u2082\u27e9)\n    : a = b := by\n  let rec extAux (a b : List \u03b1)\n      (h\u2081 : a.length = b.length)\n      (h\u2082 : (i : Nat) \u2192 (hi\u2081 : i < a.length) \u2192 (hi\u2082 : i < b.length) \u2192 a.get i hi\u2081 = b.get i hi\u2082)\n      : a = b := by\n    induction a generalizing b with\n    | nil =>\n      cases b with\n      | nil       => rfl\n      | cons b bs => rw [List.length_cons] at h\u2081; injection h\u2081\n    | cons a as ih =>\n      cases b with\n      | nil => rw [List.length_cons] at h\u2081; injection h\u2081\n      | cons b bs =>\n        have hz\u2081 : 0 < (a::as).length := by rw [List.length_cons]; apply Nat.zeroLtSucc\n        have hz\u2082 : 0 < (b::bs).length := by rw [List.length_cons]; apply Nat.zeroLtSucc\n        have headEq : a = b := h\u2082 0 hz\u2081 hz\u2082\n        have h\u2081' : as.length = bs.length := by rw [List.length_cons, List.length_cons] at h\u2081; injection h\u2081; assumption\n        have h\u2082' : (i : Nat) \u2192 (hi\u2081 : i < as.length) \u2192 (hi\u2082 : i < bs.length) \u2192 as.get i hi\u2081 = bs.get i hi\u2082 := by\n          intro i hi\u2081 hi\u2082\n          have hi\u2081' : i+1 < (a::as).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have hi\u2082' : i+1 < (b::bs).length := by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption\n          have : (a::as).get (i+1) hi\u2081' = (b::bs).get (i+1) hi\u2082' := h\u2082 (i+1) hi\u2081' hi\u2082'\n          apply this\n        have tailEq : as = bs := ih bs h\u2081' h\u2082'\n        rw [headEq, tailEq]\n  cases a; cases b\n  apply congrArg\n  apply extAux\n  assumption\n  assumption\n\ntheorem extLit {n : Nat}\n    (a b : Array \u03b1)\n    (hsz\u2081 : a.size = n) (hsz\u2082 : b.size = n)\n    (h : (i : Nat) \u2192 (hi : i < n) \u2192 a.getLit i hsz\u2081 hi = b.getLit i hsz\u2082 hi) : a = b :=\n  Array.ext a b (hsz\u2081.trans hsz\u2082.symm) fun i hi\u2081 hi\u2082 => h i (hsz\u2081 \u25b8 hi\u2081)\n\nend Array\n\n-- CLEANUP the following code\nnamespace Array\n\npartial def indexOfAux [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Nat \u2192 Option (Fin a.size)\n  | i =>\n    if h : i < a.size then\n      let idx : Fin a.size := \u27e8i, h\u27e9;\n      if a.get idx == v then some idx\n      else indexOfAux a v (i+1)\n    else none\n\ndef indexOf? [BEq \u03b1] (a : Array \u03b1) (v : \u03b1) : Option (Fin a.size) :=\n  indexOfAux a v 0\n\npartial def eraseIdxAux : Nat \u2192 Array \u03b1 \u2192 Array \u03b1\n  | i, a =>\n    if h : i < a.size then\n      let idx  : Fin a.size := \u27e8i, h\u27e9;\n      let idx1 : Fin a.size := \u27e8i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h\u27e9;\n      eraseIdxAux (i+1) (a.swap idx idx1)\n    else\n      a.pop\n\ndef feraseIdx (a : Array \u03b1) (i : Fin a.size) : Array \u03b1 :=\n  eraseIdxAux (i.val + 1) a\n\ndef eraseIdx (a : Array \u03b1) (i : Nat) : Array \u03b1 :=\n  if i < a.size then eraseIdxAux (i+1) a else a\n\n@[simp] theorem size_swap (a : Array \u03b1) (i j : Fin a.size) : (a.swap i j).size = a.size := by\n  show ((a.set i (a.get j)).set (size_set a i _ \u25b8 j) (a.get i)).size = a.size\n  rw [size_set, size_set]\n\n@[simp] theorem size_pop (a : Array \u03b1) : a.pop.size = a.size - 1 :=\n  List.length_dropLast ..\n\nsection\n/- Instance for justifying `partial` declaration.\n   We should be able to delete it as soon as we restore support for well-founded recursion. -/\ninstance eraseIdxSzAuxInstance (a : Array \u03b1) : Inhabited { r : Array \u03b1 // r.size = a.size - 1 } where\n  default := \u27e8a.pop, size_pop a\u27e9\n\npartial def eraseIdxSzAux (a : Array \u03b1) : \u2200 (i : Nat) (r : Array \u03b1), r.size = a.size \u2192 { r : Array \u03b1 // r.size = a.size - 1 }\n  | i, r, heq =>\n    if h : i < r.size then\n      let idx  : Fin r.size := \u27e8i, h\u27e9;\n      let idx1 : Fin r.size := \u27e8i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h\u27e9;\n      eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq)\n    else\n      \u27e8r.pop, (size_pop r).trans (heq \u25b8 rfl)\u27e9\nend\n\ndef eraseIdx' (a : Array \u03b1) (i : Fin a.size) : { r : Array \u03b1 // r.size = a.size - 1 } :=\n  eraseIdxSzAux a (i.val + 1) a rfl\n\ndef erase [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : Array \u03b1 :=\n  match as.indexOf? a with\n  | none   => as\n  | some i => as.feraseIdx i\n\npartial def insertAtAux (i : Nat) : Array \u03b1 \u2192 Nat \u2192 Array \u03b1\n  | as, j =>\n    if i == j then as\n    else\n      let as := as.swap! (j-1) j;\n      insertAtAux i as (j-1)\n\n/--\n  Insert element `a` at position `i`.\n  Pre: `i < as.size` -/\ndef insertAt (as : Array \u03b1) (i : Nat) (a : \u03b1) : Array \u03b1 :=\n  if i > as.size then panic! \"invalid index\"\n  else\n    let as := as.push a;\n    as.insertAtAux i as.size\n\ndef toListLitAux (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : \u2200 (i : Nat), i \u2264 a.size \u2192 List \u03b1 \u2192 List \u03b1\n  | 0,     hi, acc => acc\n  | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc)\n\ndef toArrayLit (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : Array \u03b1 :=\n  List.toArray <| toListLitAux a n hsz n (hsz \u25b8 Nat.leRefl _) []\n\ntheorem toArrayLitEq (a : Array \u03b1) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz :=\n  -- TODO: this is painful to prove without proper automation\n  sorry\n  /-\n  First, we need to prove\n  \u2200 i j acc, i \u2264 a.size \u2192 (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i)\n  by induction\n\n  Base case is trivial\n  (j : Nat) (acc : List \u03b1) (hi : 0 \u2264 a.size)\n       |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0)\n  ...  |- acc.index j = acc.index j\n\n  Induction\n\n  (j : Nat) (acc : List \u03b1) (hi : i+1 \u2264 a.size)\n        |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))\n    ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))  * by def\n    ... |- if j < i     then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i)    * by induction hypothesis\n           =\n           if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1))\n  If j < i, then both are a.getLit j hsz _\n  If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _)\n  If j >= i + 1, we use\n     - j - i >= 1 > 0\n     - (a::as).index k = as.index (k-1) If k > 0\n     - j - (i + 1) = (j - i) - 1\n     Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs\n\n  With this proof, we have\n\n  \u2200 j, j < n \u2192 (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _\n\n  We also need\n\n  - (toListLitAux a n hsz n _ []).length = n\n  - j < n -> (List.toArray as).getLit j _ _ = as.index j\n\n  Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ []\n  -/\n\npartial def isPrefixOfAux [BEq \u03b1] (as bs : Array \u03b1) (hle : as.size \u2264 bs.size) : Nat \u2192 Bool\n  | i =>\n    if h : i < as.size then\n      let a := as.get \u27e8i, h\u27e9;\n      let b := bs.get \u27e8i, Nat.ltOfLtOfLe h hle\u27e9;\n      if a == b then\n        isPrefixOfAux as bs hle (i+1)\n      else\n        false\n    else\n      true\n\n/- Return true iff `as` is a prefix of `bs` -/\ndef isPrefixOf [BEq \u03b1] (as bs : Array \u03b1) : Bool :=\n  if h : as.size \u2264 bs.size then\n    isPrefixOfAux as bs h 0\n  else\n    false\n\nprivate def allDiffAuxAux [BEq \u03b1] (as : Array \u03b1) (a : \u03b1) : forall (i : Nat), i < as.size \u2192 Bool\n  | 0,   h => true\n  | i+1, h =>\n    have : i < as.size := Nat.ltTrans (Nat.ltSuccSelf _) h;\n    a != as.get \u27e8i, this\u27e9 && allDiffAuxAux as a i this\n\nprivate partial def allDiffAux [BEq \u03b1] (as : Array \u03b1) : Nat \u2192 Bool\n  | i =>\n    if h : i < as.size then\n      allDiffAuxAux as (as.get \u27e8i, h\u27e9) i h && allDiffAux as (i+1)\n    else\n      true\n\ndef allDiff [BEq \u03b1] (as : Array \u03b1) : Bool :=\n  allDiffAux as 0\n\n@[specialize] partial def zipWithAux (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (as : Array \u03b1) (bs : Array \u03b2) : Nat \u2192 Array \u03b3 \u2192 Array \u03b3\n  | i, cs =>\n    if h : i < as.size then\n      let a := as.get \u27e8i, h\u27e9;\n      if h : i < bs.size then\n        let b := bs.get \u27e8i, h\u27e9;\n        zipWithAux f as bs (i+1) <| cs.push <| f a b\n      else\n        cs\n    else\n      cs\n\n@[inline] def zipWith (as : Array \u03b1) (bs : Array \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : Array \u03b3 :=\n  zipWithAux f as bs 0 #[]\n\ndef zip (as : Array \u03b1) (bs : Array \u03b2) : Array (\u03b1 \u00d7 \u03b2) :=\n  zipWith as bs Prod.mk\n\ndef unzip (as : Array (\u03b1 \u00d7 \u03b2)) : Array \u03b1 \u00d7 Array \u03b2 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) (a, b) => (as.push a, bs.push b)\n\ndef split (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Array \u03b1 \u00d7 Array \u03b1 :=\n  as.foldl (init := (#[], #[])) fun (as, bs) a =>\n    if p a then (as.push a, bs) else (as, bs.push a)\n\nend Array\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/Array/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.07921032682610396, "lm_q1q2_score": 0.03196666238056151}}
{"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 \u27f6 Y`\nasserts the existence of some `P.factor_thru f : X \u27f6 (P : C)` making the obvious diagram commute.\n\n-/\n\nuniverses v\u2081 v\u2082 u\u2081 u\u2082\n\nnoncomputable theory\n\nopen category_theory category_theory.category category_theory.limits\n\nvariables {C : Type u\u2081} [category.{v\u2081} C] {X Y Z : C}\nvariables {D : Type u\u2082} [category.{v\u2082} D]\n\nnamespace category_theory\n\nnamespace mono_over\n\n/-- When `f : X \u27f6 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 \u27f6 Y) : Prop := \u2203 g : X \u27f6 (P : C), g \u226b P.arrow = f\n\nlemma factors_congr {X : C} {f g : mono_over X} {Y : C} (h : Y \u27f6 X) (e : f \u2245 g) :\n  f.factors h \u2194 g.factors h :=\n\u27e8\u03bb \u27e8u, hu\u27e9, \u27e8u \u226b (((mono_over.forget _).map e.hom)).left, by simp [hu]\u27e9,\n \u03bb \u27e8u, hu\u27e9, \u27e8u \u226b (((mono_over.forget _).map e.inv)).left, by simp [hu]\u27e9\u27e9\n\n/-- `P.factor_thru f h` provides a factorisation of `f : X \u27f6 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 \u27f6 Y) (h : factors P f) : X \u27f6 (P : C) :=\nclassical.some h\n\nend mono_over\n\nnamespace subobject\n\n/-- When `f : X \u27f6 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 \u27f6 Y) : Prop :=\nquotient.lift_on' P (\u03bb P, P.factors f)\nbegin\n  rintros P Q \u27e8h\u27e9,\n  apply propext,\n  split,\n  { rintro \u27e8i, w\u27e9,\n    exact \u27e8i \u226b h.hom.left, by erw [category.assoc, over.w h.hom, w]\u27e9, },\n  { rintro \u27e8i, w\u27e9,\n    exact \u27e8i \u226b h.inv.left, by erw [category.assoc, over.w h.inv, w]\u27e9, },\nend\n\n@[simp] \n\nlemma mk_factors_self (f : X \u27f6 Y) [mono f] : (mk f).factors f := \u27e8\ud835\udfd9 _, by simp\u27e9\n\nlemma factors_iff {X Y : C} (P : subobject Y) (f : X \u27f6 Y) :\n  P.factors f \u2194 (representative.obj P).factors f :=\nquot.induction_on P $ \u03bb 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 \u27e8\ud835\udfd9 P, (by simp)\u27e9\n\nlemma factors_comp_arrow {X Y : C} {P : subobject Y} (f : X \u27f6 P) : P.factors (f \u226b P.arrow) :=\n(factors_iff _ _).mpr \u27e8f, rfl\u27e9\n\nlemma factors_of_factors_right {X Y Z : C} {P : subobject Z} (f : X \u27f6 Y) {g : Y \u27f6 Z}\n  (h : P.factors g) : P.factors (f \u226b g) :=\nbegin\n  revert P,\n  refine quotient.ind' _,\n  intro P,\n  rintro \u27e8g, rfl\u27e9,\n  exact \u27e8f \u226b g, by simp\u27e9,\nend\n\nlemma factors_zero [has_zero_morphisms C] {X Y : C} {P : subobject Y} :\n  P.factors (0 : X \u27f6 Y) :=\n(factors_iff _ _).mpr \u27e80, by simp\u27e9\n\nlemma factors_of_le {Y Z : C} {P Q : subobject Y} (f : Z \u27f6 Y) (h : P \u2264 Q) :\n  P.factors f \u2192 Q.factors f :=\nby { simp only [factors_iff], exact \u03bb \u27e8u, hu\u27e9, \u27e8u \u226b of_le _ _ h, by simp [\u2190hu]\u27e9 }\n\n/-- `P.factor_thru f h` provides a factorisation of `f : X \u27f6 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 \u27f6 Y) (h : factors P f) : X \u27f6 P :=\nclassical.some ((factors_iff _ _).mp h)\n\n@[simp, reassoc] lemma factor_thru_arrow {X Y : C} (P : subobject Y) (f : X \u27f6 Y) (h : factors P f) :\n  P.factor_thru f h \u226b 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 = \ud835\udfd9 P :=\nby { ext, simp, }\n\n@[simp] lemma factor_thru_mk_self (f : X \u27f6 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 \u27f6 P) (h) :\n  P.factor_thru (f \u226b 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 \u27f6 Y} {h : factors P f} :\n  P.factor_thru f h = 0 \u2194 f = 0 :=\nbegin\n  fsplit,\n  { intro w,\n    replace w := w =\u226b 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 \u27f6 Y) (g : Y \u27f6 Z) (h : P.factors g) :\n  f \u226b P.factor_thru g h = P.factor_thru (f \u226b 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 \u27f6 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 \u27f6 Y} (h : P \u2264 Q) (w : P.factors f) :\n  Q.factor_thru f (factors_of_le f h w) = P.factor_thru f w \u226b 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 \u27f6 Y) (wf : P.factors f) (wg : P.factors g) :\n  P.factors (f + g) :=\n(factors_iff _ _).mpr \u27e8P.factor_thru f wf + P.factor_thru g wg, by simp\u27e9\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 \u27f6 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 \u27f6 Y)\n  (w : P.factors (f + g)) (wg : P.factors g) : P.factors f :=\n(factors_iff _ _).mpr \u27e8P.factor_thru (f + g) w - P.factor_thru g wg, by simp\u27e9\n\n@[simp]\nlemma factor_thru_add_sub_factor_thru_right {X Y : C} {P : subobject Y} (f g : X \u27f6 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 \u27f6 Y)\n  (w : P.factors (f + g)) (wf : P.factors f) : P.factors g :=\n(factors_iff _ _).mpr \u27e8P.factor_thru (f + g) w - P.factor_thru f wf, by simp\u27e9\n\n@[simp]\nlemma factor_thru_add_sub_factor_thru_left {X Y : C} {P : subobject Y} (f g : X \u27f6 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 \u2190 elabTerm t expectedType\n  synthesizeSyntheticMVars\n  let t \u2190 instantiateMVars t\n  let some t \u2190 delta? t | throwError \"cannot delta reduce {t}\"\n  pure t\n\n/- `eta_helper f = (\u00b7 + 3)` elabs to `\u2200 x, f x = x + 3` -/\nlocal elab \"eta_helper \" t:term : term => do\n  let t \u2190 elabTerm t none\n  let some (_, lhs, rhs) := t.eq? | throwError \"not an equation: {t}\"\n  synthesizeSyntheticMVars\n  let rhs \u2190 instantiateMVars rhs\n  lambdaLetTelescope rhs fun xs rhs => do\n    let lhs := (mkAppN lhs xs).headBeta\n    mkForallFVars xs <|\u2190 mkEq lhs rhs\n\n/-- `value_proj x` elabs to `@x.value` -/\nlocal elab \"value_proj \" e:term : term => do\n  let e \u2190 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 (\u2190 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) \u2190 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 <| (\u00b7.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',*} := \u27e8_, rfl\u27e9\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, `\u03c3` is the type of \"signatures\" (parameters), while `\u03b5`\n    is the type of \"extended values\". For instance for `builtin.tensor`, `\u03c3` is\n    a datatype holding the dimensions and base type of the tensor, while `\u03b5` 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, `\u03b5` can be made to implement specific instances of the family\n    instead. -/\nclass DialectTypeIntf (\u03c3: Type) (\u03b5: \u03c3 \u2192 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: \u03c3), \u03b5 s\n\n  /-- The signature should have decidable equality, so we can compare types. -/\n  typeEq: DecidableEq \u03c3\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: \u03c3), DecidableEq (\u03b5 s)\n\n  /-- String representation of values in the type (eg. a multi-dimensional\n      array for tensors).  -/\n  str: (s: \u03c3) \u2192 \u03b5 s \u2192 String\n  /-- String representation of the type itself (eg. \"tensor<4x4xf64>\"). -/\n  typeStr: \u03c3 \u2192 String\n\n  -- TODO: DialectTypeIntf: Type signature, to match eg. \"any builtin.vector\"\n\ndef DialectTypeIntf.sigType {\u03c3 \u03b5} (_: DialectTypeIntf \u03c3 \u03b5): Type := \u03c3\ndef DialectTypeIntf.extType {\u03c3 \u03b5} (_: DialectTypeIntf \u03c3 \u03b5) (s: \u03c3): Type := \u03b5 s\n\n-- Expressing typeclass instances this way helps resolution\ninstance {\u03c3 \u03b5} [i: DialectTypeIntf \u03c3 \u03b5] (s: \u03c3): Inhabited (\u03b5 s) where\n  default := i.inhabited s\ninstance {\u03c3 \u03b5} [i: DialectTypeIntf \u03c3 \u03b5] (s: \u03c3): ToString (\u03b5 s) where\n  toString := i.str s\ninstance _DEq1 {\u03c3 \u03b5} [i: DialectTypeIntf \u03c3 \u03b5]: DecidableEq \u03c3 :=\n  i.typeEq\ninstance _DEq2 {\u03c3 \u03b5} [i: DialectTypeIntf \u03c3 \u03b5] (s: \u03c3): DecidableEq (\u03b5 s) :=\n  i.eq s\n\n\n/-- The `DialectAttrIntf` typeclass defines the requirements for dialect-\n   supplied custom attributes. -/\nclass DialectAttrIntf (\u03b1: Type) where\n\n  /-- The attribute should have decidable equality so that rewriting can match\n      against them (eg. in PDL). -/\n  eq: DecidableEq \u03b1\n\n  /-- String representation of attribute values. -/\n  str: \u03b1 \u2192 String\n\n  -- TODO: More data on attributes\n\ndef DialectAttrIntf.type {\u03b1} (_: DialectAttrIntf \u03b1): Type := \u03b1\n\ninstance _DEq3 {\u03b1} [i: DialectAttrIntf \u03b1]: DecidableEq \u03b1 := 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 {\u03b1 \u03b2 \u03b3} (f\u03b1: \u03b1 \u2192 \u03b3) (f\u03b2: \u03b2 \u2192 \u03b3): (\u03b1 \u2295 \u03b2) \u2192 \u03b3\n  | .inl a => f\u03b1 a\n  | .inr b => f\u03b2 b\n\ninstance {\u03c3\u2081 \u03b5\u2081 \u03c3\u2082 \u03b5\u2082} [i\u2081: DialectTypeIntf \u03c3\u2081 \u03b5\u2081] [i\u2082: DialectTypeIntf \u03c3\u2082 \u03b5\u2082]:\n    DialectTypeIntf (\u03c3\u2081 \u2295 \u03c3\u2082) (Sum.cases \u03b5\u2081 \u03b5\u2082) where\n  inhabited s :=\n    match s with\n    | .inl s\u2081 => i\u2081.inhabited s\u2081\n    | .inr s\u2082 => i\u2082.inhabited s\u2082\n  typeEq := inferInstance\n  eq s :=\n    match s with\n    | .inl s\u2081 => i\u2081.eq s\u2081\n    | .inr s\u2082 => i\u2082.eq s\u2082\n  str s :=\n    match s with\n    | .inl s\u2081 => i\u2081.str s\u2081\n    | .inr s\u2082 => i\u2082.str s\u2082\n  typeStr := Sum.cases i\u2081.typeStr i\u2082.typeStr\n\ninstance {\u03b1\u2081 \u03b1\u2082} [i\u2081: DialectAttrIntf \u03b1\u2081] [i\u2082: DialectAttrIntf \u03b1\u2082]:\n    DialectAttrIntf (\u03b1\u2081 \u2295 \u03b1\u2082) where\n  eq := inferInstance\n  str := Sum.cases i\u2081.str i\u2082.str\n\n\n/-\n### Dialects\n-/\n\n-- TODO: Document and finish the Dialect interface\nclass Dialect (\u03b1 \u03c3) (\u03b5: \u03c3 \u2192 Type): Type :=\n  name: String\n  i\u03b1: DialectAttrIntf \u03b1\n  i\u03b5: DialectTypeIntf \u03c3 \u03b5\n\ninstance {\u03b1 \u03b5} [\u03b4: Dialect \u03b1 \u03c3 \u03b5]: DialectAttrIntf \u03b1 := \u03b4.i\u03b1\ninstance {\u03b1 \u03b5} [\u03b4: Dialect \u03b1 \u03c3 \u03b5]: DialectTypeIntf \u03c3 \u03b5 := \u03b4.i\u03b5\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\u03b1 := inferInstance\n  i\u03b5 := inferInstance\n\n\n-- We write combinations of dialects with + as usual (no risk of confusion)\ninstance {\u03b1\u2081 \u03c3\u2081 \u03b5\u2081 \u03b1\u2082 \u03c3\u2082 \u03b5\u2082}:\n  HAdd (Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082)\n       (Dialect (\u03b1\u2081 \u2295 \u03b1\u2082) (\u03c3\u2081 \u2295 \u03c3\u2082) (Sum.cases \u03b5\u2081 \u03b5\u2082)) where\n  hAdd \u03b4\u2081 \u03b4\u2082 := {\n    name := s!\"({\u03b4\u2081.name}+{\u03b4\u2082.name})\"\n    i\u03b1 := inferInstance\n    i\u03b5 := inferInstance\n  }\n\ninstance {\u03b1\u2081 \u03c3\u2081 \u03b5\u2081 \u03b1\u2082 \u03c3\u2082 \u03b5\u2082} [\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081] [\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082]:\n    Dialect (\u03b1\u2081 \u2295 \u03b1\u2082) (\u03c3\u2081 \u2295 \u03c3\u2082) (Sum.cases \u03b5\u2081 \u03b5\u2082) :=\n  \u03b4\u2081 + \u03b4\u2082\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 (\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082) where\n  coe_\u03b1: \u03b1\u2081 \u2192 \u03b1\u2082\n  coe_\u03c3: \u03c3\u2081 \u2192 \u03c3\u2082\n  coe_\u03b5: forall s, \u03b5\u2081 s \u2192 \u03b5\u2082 (coe_\u03c3 s)\n\ninstance (\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082) [c: CoeDialect \u03b4\u2081 \u03b4\u2082]:\n  Coe \u03b1\u2081 \u03b1\u2082 where coe := c.coe_\u03b1\ninstance (\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082) [c: CoeDialect \u03b4\u2081 \u03b4\u2082]:\n  Coe \u03c3\u2081 \u03c3\u2082 where coe := c.coe_\u03c3\ninstance (\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082) [c: CoeDialect \u03b4\u2081 \u03b4\u2082] s:\n  Coe (\u03b5\u2081 s) (\u03b5\u2082 /-coe-/s) where coe := c.coe_\u03b5 s\n\ninstance (\u03b4: Dialect \u03b1 \u03c3 \u03b5): CoeDialect \u03b4 \u03b4 where\n  coe_\u03b1 := id\n  coe_\u03c3 := id\n  coe_\u03b5 s := id\n\ninstance (\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082):\n    CoeDialect \u03b4\u2081 (\u03b4\u2081 + \u03b4\u2082) where\n  coe_\u03b1 := .inl\n  coe_\u03c3 := .inl\n  coe_\u03b5 s := id\n\ninstance (\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081) (\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082):\n    CoeDialect \u03b4\u2082 (\u03b4\u2081 + \u03b4\u2082) where\n  coe_\u03b1 := .inr\n  coe_\u03c3 := .inr\n  coe_\u03b5 s := id\n\ninstance (\u03b4: Dialect \u03b1 \u03c3 \u03b5): CoeDialect Dialect.empty \u03b4 where\n  coe_\u03b1 a := nomatch a\n  coe_\u03c3 s := nomatch s\n  coe_\u03b5 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) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport data.dlist\n\n/-- Concatenates a list of difference lists to form a single\ndifference list.  Similar to `list.join`. -/\ndef dlist.join {\u03b1 : Type*} : list (dlist \u03b1) \u2192 dlist \u03b1\n | [] := dlist.empty\n | (x :: xs) := x ++ dlist.join xs\n\n@[simp] lemma dlist_singleton {\u03b1 : Type*} {a : \u03b1} :\n  dlist.singleton a = dlist.lazy_of_list ([a]) := rfl\n\n@[simp] lemma dlist_lazy {\u03b1 : Type*} {l : list \u03b1} :\n  dlist.lazy_of_list l = dlist.of_list l := 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/dlist/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.06560483197834706, "lm_q1q2_score": 0.031777674042649154}}
{"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 \u03b1 \u03b2` is \"the same as\" `List (\u03b1 \u00d7 \u03b2)`, 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 (\u03b1 : Type u) (\u03b2 : Type v) where\n  /-- An empty list -/\n  | nil\n  /-- Add a `key, value` pair to the list -/\n  | cons (key : \u03b1) (value : \u03b2) (tail : AssocList \u03b1 \u03b2)\n  deriving Inhabited\n\nnamespace AssocList\n\n/--\n`O(n)`. Convert an `AssocList \u03b1 \u03b2` into the equivalent `List (\u03b1 \u00d7 \u03b2)`.\nThis is used to give specifications for all the `AssocList` functions\nin terms of corresponding list functions.\n-/\n@[simp] def toList : AssocList \u03b1 \u03b2 \u2192 List (\u03b1 \u00d7 \u03b2)\n  | nil => []\n  | cons a b es => (a, b) :: es.toList\n\ninstance : EmptyCollection (AssocList \u03b1 \u03b2) := \u27e8nil\u27e9\n\n@[simp] theorem empty_eq : (\u2205 : AssocList \u03b1 \u03b2) = nil := rfl\n\n/-- `O(1)`. Is the list empty? -/\ndef isEmpty : AssocList \u03b1 \u03b2 \u2192 Bool\n  | nil => true\n  | _   => false\n\n@[simp] theorem isEmpty_eq (l : AssocList \u03b1 \u03b2) : 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 : \u03b4 \u2192 \u03b1 \u2192 \u03b2 \u2192 m \u03b4) : (init : \u03b4) \u2192 AssocList \u03b1 \u03b2 \u2192 m \u03b4\n  | d, nil         => pure d\n  | d, cons a b es => do foldlM f (\u2190 f d a b) es\n\n@[simp] theorem foldlM_eq [Monad m] (f : \u03b4 \u2192 \u03b1 \u2192 \u03b2 \u2192 m \u03b4) (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 : \u03b4 \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b4) (init : \u03b4) (as : AssocList \u03b1 \u03b2) : \u03b4 :=\n  Id.run (foldlM f init as)\n\n@[simp] theorem foldl_eq (f : \u03b4 \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b4) (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 \u03b1 \u03b2) : List (\u03b1 \u00d7 \u03b2) :=\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 \u03b1 \u03b2 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 : \u03b1 \u2192 \u03b2 \u2192 m PUnit) : AssocList \u03b1 \u03b2 \u2192 m PUnit\n  | nil         => pure \u27e8\u27e9\n  | cons a b es => do f a b; forM f es\n\n@[simp] theorem forM_eq [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 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 : \u03b1 \u2192 \u03b4) : AssocList \u03b1 \u03b2 \u2192 AssocList \u03b4 \u03b2\n  | nil        => nil\n  | cons k v t => cons (f k) v (mapKey f t)\n\n@[simp] theorem mapKey_toList (f : \u03b1 \u2192 \u03b4) (l : AssocList \u03b1 \u03b2) :\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 : \u03b1 \u2192 \u03b2 \u2192 \u03b4) : AssocList \u03b1 \u03b2 \u2192 AssocList \u03b1 \u03b4\n  | nil        => nil\n  | cons k v t => cons k (f k v) (mapVal f t)\n\n@[simp] theorem mapVal_toList (f : \u03b1 \u2192 \u03b2 \u2192 \u03b4) (l : AssocList \u03b1 \u03b2) :\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 : \u03b1 \u2192 \u03b2 \u2192 Bool) : AssocList \u03b1 \u03b2 \u2192 Option (\u03b1 \u00d7 \u03b2)\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 : \u03b1 \u2192 \u03b2 \u2192 Bool) (l : AssocList \u03b1 \u03b2) :\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 \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) : Option (\u03b1 \u00d7 \u03b2) :=\n  findEntryP? (fun k _ => k == a) l\n\n@[simp] theorem findEntry?_eq [BEq \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) :\n    findEntry? a l = l.toList.find? (\u00b7.1 == a) := findEntryP?_eq ..\n\n/-- `O(n)`. Returns the first value in the list whose key is equal to `a`. -/\ndef find? [BEq \u03b1] (a : \u03b1) : AssocList \u03b1 \u03b2 \u2192 Option \u03b2\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 \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) :\n    find? a l = (l.findEntry? a).map (\u00b7.2) := by\n  induction l <;> simp [find?]; split <;> simp [*]\n\n@[simp] theorem find?_eq [BEq \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) :\n    find? a l = (l.toList.find? (\u00b7.1 == a)).map (\u00b7.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 : \u03b1 \u2192 \u03b2 \u2192 Bool) : AssocList \u03b1 \u03b2 \u2192 Bool\n  | nil         => false\n  | cons k v es => p k v || any p es\n\n@[simp] theorem any_eq (p : \u03b1 \u2192 \u03b2 \u2192 Bool) (l : AssocList \u03b1 \u03b2) :\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 : \u03b1 \u2192 \u03b2 \u2192 Bool) : AssocList \u03b1 \u03b2 \u2192 Bool\n  | nil         => true\n  | cons k v es => p k v && all p es\n\n@[simp] theorem all_eq (p : \u03b1 \u2192 \u03b2 \u2192 Bool) (l : AssocList \u03b1 \u03b2) :\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 : \u03b1 \u2192 \u03b2 \u2192 Prop) (l : AssocList \u03b1 \u03b2) : Prop := \u2200 a \u2208 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 \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) : Bool := any (fun k _ => k == a) l\n\n@[simp] theorem contains_eq [BEq \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) :\n    contains a l = l.toList.any (\u00b7.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 \u03b1] (a : \u03b1) (b : \u03b2) : AssocList \u03b1 \u03b2 \u2192 AssocList \u03b1 \u03b2\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 \u03b1] (a : \u03b1) (b : \u03b2) (l : AssocList \u03b1 \u03b2) :\n    (replace a b l).toList =\n    l.toList.replaceF (bif \u00b7.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 : \u03b1 \u2192 \u03b2 \u2192 Bool) : AssocList \u03b1 \u03b2 \u2192 AssocList \u03b1 \u03b2\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 \u03b1 \u03b2) :\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 \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) : AssocList \u03b1 \u03b2 :=\n  eraseP (fun k _ => k == a) l\n\n@[simp] theorem erase_toList [BEq \u03b1] (a : \u03b1) (l : AssocList \u03b1 \u03b2) :\n    (erase a l).toList = l.toList.eraseP (\u00b7.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 \u03b1 \u03b2) (init : \u03b4) (f : (\u03b1 \u00d7 \u03b2) \u2192 \u03b4 \u2192 m (ForInStep \u03b4)) : m \u03b4 :=\n  match as with\n  | nil => pure init\n  | cons k v es => do\n    match (\u2190 f (k, v) init) with\n    | ForInStep.done d  => pure d\n    | ForInStep.yield d => es.forIn d f\n\ninstance : ForIn m (AssocList \u03b1 \u03b2) (\u03b1 \u00d7 \u03b2) where\n  forIn := AssocList.forIn\n\n@[simp] theorem forIn_eq [Monad m] (l : AssocList \u03b1 \u03b2) (init : \u03b4)\n    (f : (\u03b1 \u00d7 \u03b2) \u2192 \u03b4 \u2192 m (ForInStep \u03b4)) : 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 \u03b1 \u03b2 \u2192 Option ((\u03b1 \u00d7 \u03b2) \u00d7 AssocList \u03b1 \u03b2)\n  | nil => none\n  | cons a b l => some ((a, b), l)\n\ninstance : ToStream (AssocList \u03b1 \u03b2) (AssocList \u03b1 \u03b2) := \u27e8fun x => x\u27e9\ninstance : Stream (AssocList \u03b1 \u03b2) (\u03b1 \u00d7 \u03b2) := \u27e8pop?\u27e9\n\n/-- Converts a list into an `AssocList`. This is the inverse function to `AssocList.toList`. -/\n@[simp] def _root_.List.toAssocList : List (\u03b1 \u00d7 \u03b2) \u2192 AssocList \u03b1 \u03b2\n  | []          => nil\n  | (a,b) :: es => cons a b (toAssocList es)\n\n@[simp] theorem _root_.List.toAssocList_toList (l : List (\u03b1 \u00d7 \u03b2)) : l.toAssocList.toList = l := by\n  induction l <;> simp [*]\n\n@[simp] theorem toList_toAssocList (l : AssocList \u03b1 \u03b2) : 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) 2017 Daniel Selsam. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Daniel Selsam\n\nLabels.\n\nNote: this file is just because strings are slow and cumbersome in current Lean.\n-/\nimport .tactics\nnamespace certigrad\n\ninductive label : Type\n| default\n| batch_start\n| W_encode, W_encode\u2081, W_encode\u2082, h_encode, W_encode_\u03bc, W_encode_log\u03c3\u2082\n| W_decode, W_decode\u2081, W_decode\u2082, h_decode, W_decode_p\n| \u03bc, \u03c3, \u03c3\u2082, log_\u03c3\u2082, z, encoding_loss, decoding_loss, \u03b5, x, p, x_all\n\nnamespace label\n\ninstance : decidable_eq label := by tactic.mk_dec_eq_instance\n\ndef to_str : label \u2192 string\n| default := \"<default>\"\n| batch_start := \"batch_start\"\n| W_encode := \"W_encode\"\n| W_encode\u2081 := \"W_encode_1\"\n| W_encode\u2082 := \"W_encode_2\"\n| h_encode := \"h_encode\"\n| W_encode_\u03bc := \"W_encode_mu\"\n| W_encode_log\u03c3\u2082 := \"W_encode_logs\u2082\"\n| W_decode := \"W_decode\"\n| W_decode\u2081 := \"W_decode_1\"\n| W_decode\u2082 := \"W_decode_2\"\n| h_decode := \"h_decode\"\n| W_decode_p := \"W_decode_p\"\n| \u03bc := \"mu\"\n| \u03c3 := \"sigma\"\n| \u03c3\u2082 := \"sigma_sq\"\n| log_\u03c3\u2082 := \"log_s\u2082\"\n| z := \"z\"\n| encoding_loss := \"encoding_loss\"\n| decoding_loss := \"decoding_loss\"\n| \u03b5 := \"eps\"\n| x := \"x\"\n| p := \"p\"\n| x_all := \"x_all\"\n\ninstance : has_to_string label := \u27e8to_str\u27e9\n\ndef to_nat : label \u2192 \u2115\n| default := 0\n| batch_start := 1\n| W_encode := 2\n| W_encode\u2081 := 3\n| W_encode\u2082 := 4\n| h_encode := 5\n| W_encode_\u03bc := 6\n| W_encode_log\u03c3\u2082 := 7\n| W_decode := 8\n| W_decode\u2081 := 9\n| W_decode\u2082 := 10\n| h_decode := 11\n| W_decode_p := 12\n| \u03bc := 13\n| \u03c3 := 14\n| \u03c3\u2082 := 15\n| log_\u03c3\u2082 := 16\n| z := 17\n| encoding_loss := 18\n| decoding_loss := 19\n| \u03b5 := 20\n| x := 21\n| p := 22\n| x_all := 23\n\nsection proofs\nopen tactic\n\nmeta def prove_neq_case_core : tactic unit :=\ndo H \u2190 intro `H,\n   dunfold_at [`certigrad.label.to_nat] H,\n   H \u2190 get_local `H,\n   (lhs, rhs) \u2190 infer_type H >>= match_eq,\n   nty \u2190 mk_app `ne [lhs, rhs],\n   assert `H_not nty,\n   solve1 prove_nats_neq,\n   exfalso,\n   get_local `H_not >>= \u03bb H_not, exact (expr.app H_not H)\n\nlemma eq_of_to_nat_eq {x y : label} : x = y \u2192 to_nat x = to_nat y :=\nbegin\nintro H,\nsubst H,\nend\n\nlemma to_nat_eq_of_eq {x y : label} : to_nat x = to_nat y \u2192 x = y :=\nbegin\ncases x,\nall_goals { cases y },\nany_goals { intros, reflexivity },\nall_goals { prove_neq_case_core }\nend\n\nlemma neq_of_to_nat {x y : label} : (x \u2260 y) = (x^.to_nat \u2260 y^.to_nat) :=\nbegin\napply propext,\nsplit,\nintros H_ne H_eq,\nexact H_ne (to_nat_eq_of_eq H_eq),\nintros H_ne H_eq,\nexact H_ne (eq_of_to_nat_eq H_eq)\nend\n\nend proofs\n\ndef less_than (x y : label) : Prop := x^.to_nat < y^.to_nat\n\ninstance : has_lt label := \u27e8less_than\u27e9\n\ninstance decidable_less_than (x y : label) : decidable (x < y) := by apply nat.decidable_lt\n\nend label\nend certigrad\n", "meta": {"author": "dselsam", "repo": "certigrad", "sha": "c9a06e93f1ec58196d6d3b8563b29868d916727f", "save_path": "github-repos/lean/dselsam-certigrad", "path": "github-repos/lean/dselsam-certigrad/certigrad-c9a06e93f1ec58196d6d3b8563b29868d916727f/src/certigrad/label.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116550426623, "lm_q2_score": 0.07921032410902436, "lm_q1q2_score": 0.03166921077849472}}
{"text": "/-\nCopyright (c) 2022 Dhruv Bhatia. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Dhruv Bhatia, Robert Y. Lewis, Mario Carneiro\n-/\nimport Mathlib.Tactic.Polyrith\n\n/-!\n\nEach call to `polyrith` makes a call to the SageCell web API at\n<https://sagecell.sagemath.org/>. To avoid making many API calls from CI,\nwe only test this communication in a few tests.\n\nA full test suite is provided at the bottom of the file.\n\n-/\n\n/-!\n## Set up testing infrastructre\n-/\n\n-- section tactic\n-- open polyrith tactic\n-- /--\n-- For testing purposes, this behaves like `tactic.polyrith`, but takes an extra argument\n-- representing the expected output from a call to Sage.\n-- Allows for testing without actually making API calls.\n-- -/\n-- meta def tactic.test_polyrith (only_on : bool) (hyps : list pexpr)\n--   (sage_out : json) (expected_args : list string) (expected_out : string) :\n--   tactic unit := do\n--   (eq_names, m, R, args) \u2190 create_args only_on hyps,\n--   guard (args = expected_args) <|>\n--     fail!\"expected arguments to Sage: {expected_args}\\nbut produced: {args}\",\n--   out \u2190 to_string <$> process_output eq_names m R sage_out,\n--   guard (out = expected_out) <|>\n--     fail!\"expected final output: {expected_out}\\nbut produced: {out}\"\n\n-- meta def format_string_list (input : list string) : format :=\n-- \"[\" ++ (format.join $ (input.map (\u03bb s, (\"\\\"\" : format) ++ format.of_string s ++ \"\\\"\")).intersperse (\",\" ++ format.line)) ++ \"]\"\n\n-- setup_tactic_parser\n\n-- meta def tactic.interactive.test_polyrith (restr : parse (tk \"only\")?)\n--   (hyps : parse pexpr_list?)\n--   (sage_out : string) (expected_args : list string) (expected_out : string) : tactic unit := do\n--   some sage_out \u2190 return $ json.parse sage_out,\n--   tactic.test_polyrith restr.is_some (hyps.get_or_else []) sage_out expected_args expected_out\n\n-- meta def tactic.interactive.test_sage_output (restr : parse (tk \"only\")?)\n--   (hyps : parse pexpr_list?) (expected_out : string) : tactic unit := do\n--   expected_json \u2190 json.parse expected_out,\n--   sleep 10, -- otherwise can lead to weird errors when actively editing code with polyrith calls\n--   (eq_names, m, R, args) \u2190 create_args restr.is_some (hyps.get_or_else []),\n--   sage_out \u2190 sage_output args,\n--   guard (sage_out = expected_json) <|>\n--     fail!\"Expected output from Sage: {expected_out}\\nbut produced: {sage_out}\"\n\n-- /--\n-- A convenience function. Given a working test, prints the code for a call to `test_sage_output`.\n-- -/\n-- meta def tactic.interactive.create_sage_output_test (restr : parse (tk \"only\")?)\n--   (hyps : parse pexpr_list?) : tactic unit := do\n--   let hyps := (hyps.get_or_else []),\n--   sleep 10, -- otherwise can lead to weird errors when actively editing code with polyrith calls\n--   (eq_names, m, R, args) \u2190 create_args restr.is_some hyps,\n--   sage_out \u2190 to_string <$> sage_output args,\n--   let sage_out := sage_out.fold \"\" (\u03bb s c, s ++ (if c = '\"' then \"\\\\\\\"\" else to_string c)),\n--   let onl := if restr.is_some then \"only \" else \"\",\n--   let hyps := if hyps = [] then \"\" else to_string hyps,\n--   trace!\"test_sage_output {onl}{hyps} \\\"{sage_out}\\\"\"\n\n-- /--\n-- A convenience function. Given a working test, prints the code for a call to `test_polyrith`.\n-- -/\n-- meta def tactic.interactive.create_polyrith_test (restr : parse (tk \"only\")?)\n--   (hyps : parse pexpr_list?) : tactic unit := do\n--   let hyps := (hyps.get_or_else []),\n--   sleep 10, -- otherwise can lead to weird errors when actively editing code with polyrith calls\n--   (eq_names, m, R, args) \u2190 create_args restr.is_some hyps,\n--   sage_out \u2190 sage_output args,\n--   out \u2190 to_string <$> process_output eq_names m R sage_out,\n--   let out := out.fold \"\" (\u03bb s c, s ++ (if c = '\"' then \"\\\\\\\"\" else to_string c)),\n--   let sage_out := (to_string sage_out).fold \"\"\n--     (\u03bb s c, s ++ (if c = '\"' then \"\\\\\\\"\" else to_string c)),\n--   let argstring := format_string_list args,\n--   let onl := if restr.is_some then \"only \" else \"\",\n--   let hyps := if hyps = [] then \"\" else to_string hyps,\n--   let trf := format.nest 2 $ format!\"test_polyrith {onl}{hyps} \\n\\\"{sage_out}\\\"\\n{argstring}\\n\\\"{out}\\\"\",\n--   trace!\"Try this: {trf}\"\n\n\n-- end tactic\n\n-- /-!\n-- ## SageCell communcation tests\n-- -/\n\n-- example (x y : \u211a) (h1 : x*y + 2*x = 1) (h2 : x = y) :\n--   x*y = -2*y + 1 :=\n-- begin\n--   test_sage_output \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\",\\\"(poly.const -2/1)\\\"],\\\"success\\\":true}\",\n--   linear_combination h1 - 2 * h2\n-- end\n\n-- example (w x y z : \u211d) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5)\n--     (h3 : x + y + 5*z + 5*w = 3) :\n--   x + 2.2*y + 2*z - 5*w = -8.5 :=\n-- begin\n--   test_sage_output \"{\\\"data\\\":[\\\"(poly.const 2/1)\\\",\\\"(poly.const 1/1)\\\",\\\"(poly.const -2/1)\\\"],\\\"success\\\":true}\",\n--   linear_combination 2 * h1 + h2 - 2 * h3\n-- end\n\n\n\n-- /-! ### Standard Cases over \u2124, \u211a, and \u211d -/\n\n-- example (x y : \u2124) (h1 : 3*x + 2*y = 10):\n--   3*x + 2*y = 10 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"2\",\n--   \"[(((3 * var0) + (2 * var1)) - 10)]\",\n--   \"(((3 * var0) + (2 * var1)) - 10)\"]\n--   \"linear_combination h1\"\n\n-- example (x y : \u211a) (h1 : x*y + 2*x = 1) (h2 : x = y) :\n--   x*y = -2*y + 1 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\",\\\"(poly.const -2/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"2\",\n--   \"[(((var0 * var1) + (2 * var0)) - 1), (var0 - var1)]\",\n--   \"((var0 * var1) - ((-2 * var1) + 1))\"]\n--   \"linear_combination h1 - 2 * h2\"\n\n-- example (x y : \u211d) (h1 : x + 2 = -3) (h2 : y = 10) :\n--   -y + 2*x + 4 = -16 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 2/1)\\\",\\\"(poly.const -1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"real\",\n--   \"2\",\n--   \"[((var1 + 2) - -3), (var0 - 10)]\",\n--   \"(((-var0 + (2 * var1)) + 4) - -16)\"]\n--   \"linear_combination 2 * h1 - h2\"\n\n-- example (x y z : \u211d) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2)\n--     (hc : x + 2*y + z = 2) :\n--   -3*x - 3*y - 4*z = 2 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\",\\\"(poly.const -1/1)\\\",\\\"(poly.const -2/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"real\",\n--   \"3\",\n--   \"[(((var0 + (2 * var1)) - var2) - 4), ((((2 * var0) + var1) + var2) - -2), (((var0 + (2 * var1)) + var2) - 2)]\",\n--   \"((((-3 * var0) - (3 * var1)) - (4 * var2)) - 2)\"]\n--   \"linear_combination ha - hb - 2 * hc\"\n\n-- example (w x y z : \u211d) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5)\n--     (h3 : x + y + 5*z + 5*w = 3) :\n--   x + 2.2*y + 2*z - 5*w = -8.5 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 2/1)\\\",\\\"(poly.const 1/1)\\\",\\\"(poly.const -2/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"real\",\n--   \"4\",\n--   \"[(((var0 + (21/10 * var1)) + (2 * var2)) - 2), (((var0 + (8 * var2)) + (5 * var3)) - -13/2), ((((var0 + var1) + (5 * var2)) + (5 * var3)) - 3)]\",\n--   \"((((var0 + (11/5 * var1)) + (2 * var2)) - (5 * var3)) - -17/2)\"]\n--   \"linear_combination 2 * h1 + h2 - 2 * h3\"\n\n-- example (a b c d : \u211a) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) :\n--   2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 2/1)\\\",\\\"(poly.const -1/1)\\\",\\\"(poly.const 3/1)\\\",\\\"(poly.const -3/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"4\",\n--   \"[(var0 - 4), (3 - var3), ((var1 * 3) - var2), (-var2 - var0)]\",\n--   \"(((((2 * var0) - 3) + (9 * var1)) + (3 * var2)) - (((8 - var3) + (3 * var2)) - (3 * var0)))\"]\n--   \"linear_combination 2 * h1 - h2 + 3 * h3 - 3 * h4\"\n\n-- /-! ### Case with ambiguous identifiers-/\n\n-- example (\u00abdef evil\u00bb y : \u2124) (h1 : 3*\u00abdef evil\u00bb + 2*y = 10):\n--   3*\u00abdef evil\u00bb + 2*y = 10 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"2\",\n--   \"[(((3 * var0) + (2 * var1)) - 10)]\",\n--   \"(((3 * var0) + (2 * var1)) - 10)\"]\n--   \"linear_combination h1\"\n\n-- example (\u00ab\u00a5\u00bb y : \u2124) (h1 : 3*\u00ab\u00a5\u00bb + 2*y = 10):\n--   \u00ab\u00a5\u00bb * (3*\u00ab\u00a5\u00bb + 2*y) = 10 * \u00ab\u00a5\u00bb :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.var 0)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"2\",\n--   \"[(((3 * var0) + (2 * var1)) - 10)]\",\n--   \"((var0 * ((3 * var0) + (2 * var1))) - (10 * var0))\"]\n--   \"linear_combination \u00ab\u00a5\u00bb * h1\"\n\n-- /-! ### Cases with arbitrary coefficients -/\n\n-- example (a b : \u2124) (h : a = b) :\n--   a * a = a * b :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.var 0)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"2\",\n--   \"[(var0 - var1)]\",\n--   \"((var0 * var0) - (var0 * var1))\"]\n--   \"linear_combination a * h\"\n\n-- example (a b c : \u2124) (h : a = b) :\n--   a * c = b * c :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.var 1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"3\",\n--   \"[(var0 - var2)]\",\n--   \"((var0 * var1) - (var2 * var1))\"]\n--   \"linear_combination c * h\"\n\n-- example (a b c : \u2124) (h1 : a = b) (h2 : b = 1) :\n--   c * a + b = c * b + 1 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.var 0)\\\",\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"3\",\n--   \"[(var1 - var2), (var2 - 1)]\",\n--   \"(((var0 * var1) + var2) - ((var0 * var2) + 1))\"]\n--   \"linear_combination c * h1 + h2\"\n\n-- example (x y : \u211a) (h1 : x + y = 3) (h2 : 3*x = 7) :\n--   x*x*y + y*x*y + 6*x = 3*x*y + 14 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.mul (poly.var 0) (poly.var 1))\\\",\\\"(poly.const 2/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"2\",\n--   \"[((var0 + var1) - 3), ((3 * var0) - 7)]\",\n--   \"(((((var0 * var0) * var1) + ((var1 * var0) * var1)) + (6 * var0)) - (((3 * var0) * var1) + 14))\"]\n--   \"linear_combination x * y * h1 + 2 * h2\"\n\n-- example (x y z w : \u211a) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.add (poly.var 0) (poly.mul (poly.const 2/1) (poly.var 2)))\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"4\",\n--   \"[(var1 - var3)]\",\n--   \"(((var0 * var1) + ((2 * var2) * var1)) - ((var0 * var3) + ((2 * var2) * var3)))\"]\n--   \"linear_combination (x + 2 * y) * hzw\"\n\n-- /-! ### Cases with non-hypothesis inputs/input restrictions -/\n\n-- example (a b : \u211d) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) :\n--   b = 2 / 3 :=\n-- by test_polyrith only [ha, hab]\n--   \"{\\\"data\\\":[\\\"(poly.const 1/6)\\\",\\\"(poly.const 1/3)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"real\",\n--   \"2\",\n--   \"[((2 * var1) - 4), ((2 * var0) - (var1 - var0))]\",\n--   \"(var0 - 2/3)\"]\n--   \"linear_combination ha / 6 + hab / 3\"\n\n-- constant term : \u2200 a b : \u211a, a + b = 0\n\n-- example (a b c d : \u211a) (h : a + b = 0) (h2: b + c = 0): a + b + c + d = 0 :=\n-- by test_polyrith only [term c d, h]\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\",\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"4\",\n--   \"[((var2 + var3) - 0), ((var0 + var1) - 0)]\",\n--   \"((((var0 + var1) + var2) + var3) - 0)\"]\n--   \"linear_combination term c d + h\"\n\n-- constants (qc : \u211a) (hqc : qc = 2*qc)\n\n-- example (a b : \u211a) (h : \u2200 p q : \u211a, p = q) : 3*a + qc = 3*b + 2*qc :=\n-- by test_polyrith [h a b, hqc]\n--   \"{\\\"data\\\":[\\\"(poly.const 3/1)\\\",\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"3\",\n--   \"[(var0 - var2), (var1 - (2 * var1))]\",\n--   \"(((3 * var0) + var1) - ((3 * var2) + (2 * var1)))\"]\n--   \"linear_combination 3 * h a b + hqc\"\n\n-- constant bad (q : \u211a) : q = 0\n\n-- example (a b : \u211a) : a + b^3 = 0 :=\n-- by test_polyrith [bad a, bad (b^2)]\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\",\\\"(poly.var 1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"2\",\n--   \"[(var0 - 0), ((var1 ^ 2) - 0)]\",\n--   \"((var0 + (var1 ^ 3)) - 0)\"]\n--   \"linear_combination bad a + b * bad (b ^ 2)\"\n\n-- /-! ### Case over arbitrary field/ring -/\n\n-- example {\u03b1} [h : comm_ring \u03b1] {a b c d e f : \u03b1} (h1 : a*d = b*c) (h2 : c*f = e*d) :\n--   c * (a*f - b*e) = 0 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.var 4)\\\",\\\"(poly.var 1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"\u03b1\",\n--   \"6\",\n--   \"[((var1 * var5) - (var3 * var0)), ((var0 * var2) - (var4 * var5))]\",\n--   \"((var0 * ((var1 * var2) - (var3 * var4))) - 0)\"]\n--   \"linear_combination e * h1 + a * h2\"\n\n-- example {K : Type _} [field K] [invertible 2] [invertible 3]\n--   {\u03c9 p q r s t x: K} (hp_nonzero : p \u2260 0) (hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r)\n--   (ht : t * s = p) (x : K) (H : 1 + \u03c9 + \u03c9 ^ 2 = 0) :\n--   x ^ 3 + 3 * p * x - 2 * q =\n--     (x - (s - t)) * (x - (s * \u03c9 - t * \u03c9 ^ 2)) * (x - (s * \u03c9 ^ 2 - t * \u03c9)) :=\n-- begin\n--   have hs_nonzero : s \u2260 0,\n--   { contrapose! hp_nonzero with hs_nonzero,\n--     test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 0/1)\\\",\\\"(poly.const 0/1)\\\",\\\"(poly.const -1/1)\\\",\\\"(poly.const 0/1)\\\",\\\"(poly.var 4)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"K\",\n--   \"6\",\n--   \"[((var1 ^ 2) - ((var2 ^ 2) + (var0 ^ 3))), ((var3 ^ 3) - (var2 + var1)), ((var4 * var3) - var0), (((1 + var5) + (var5 ^ 2)) - 0), (var3 - 0)]\",\n--   \"(var0 - 0)\"]\n--   \"linear_combination -ht + t * hs_nonzero\"},\n--   have H' : 2 * q = s ^ 3 - t ^ 3,\n--   { rw \u2190 mul_left_inj' (pow_ne_zero 3 hs_nonzero),\n--     test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const -1/1)\\\",\\\"(poly.sub (poly.add (poly.neg (poly.pow (poly.var 1) 3)) (poly.var 0)) (poly.var 3))\\\",\\\"(poly.add (poly.add (poly.mul (poly.pow (poly.var 1) 2) (poly.pow (poly.var 2) 2)) (poly.mul (poly.mul (poly.var 1) (poly.var 2)) (poly.var 4))) (poly.pow (poly.var 4) 2))\\\",\\\"(poly.const 0/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"K\",\n--   \"6\",\n--   \"[((var3 ^ 2) - ((var0 ^ 2) + (var4 ^ 3))), ((var1 ^ 3) - (var0 + var3)), ((var2 * var1) - var4), (((1 + var5) + (var5 ^ 2)) - 0)]\",\n--   \"(((2 * var0) * (var1 ^ 3)) - (((var1 ^ 3) - (var2 ^ 3)) * (var1 ^ 3)))\"]\n--   \"linear_combination -hr + (-s ^ 3 + q - r) * hs3 + (s ^ 2 * t ^ 2 + s * t * p + p ^ 2) * ht\"},\n--   test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 0/1)\\\",\\\"(poly.const 0/1)\\\",\\\"(poly.add (poly.add (poly.sub (poly.add (poly.add (poly.sub (poly.add (poly.sub (poly.mul (poly.var 0) (poly.pow (poly.var 5) 4)) (poly.mul (poly.var 3) (poly.pow (poly.var 5) 4))) (poly.mul (poly.var 4) (poly.pow (poly.var 5) 4))) (poly.mul (poly.var 3) (poly.pow (poly.var 5) 3))) (poly.mul (poly.var 4) (poly.pow (poly.var 5) 3))) (poly.mul (poly.mul (poly.const 3/1) (poly.var 0)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.var 3) (poly.pow (poly.var 5) 2))) (poly.mul (poly.var 4) (poly.pow (poly.var 5) 2))) (poly.mul (poly.mul (poly.const 2/1) (poly.var 0)) (poly.var 5)))\\\",\\\"(poly.add (poly.sub (poly.add (poly.sub (poly.sub (poly.add (poly.add (poly.sub (poly.add (poly.sub (poly.sub (poly.add (poly.neg (poly.mul (poly.mul (poly.var 0) (poly.pow (poly.var 3) 2)) (poly.var 5))) (poly.mul (poly.pow (poly.var 3) 3) (poly.var 5))) (poly.mul (poly.mul (poly.var 0) (poly.pow (poly.var 4) 2)) (poly.var 5))) (poly.mul (poly.pow (poly.var 4) 3) (poly.var 5))) (poly.mul (poly.mul (poly.var 0) (poly.var 1)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.mul (poly.var 1) (poly.var 3)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.mul (poly.var 1) (poly.var 4)) (poly.pow (poly.var 5) 2))) (poly.mul (poly.pow (poly.var 0) 2) (poly.var 3))) (poly.pow (poly.var 3) 3)) (poly.mul (poly.pow (poly.var 0) 2) (poly.var 4))) (poly.pow (poly.var 4) 3)) (poly.mul (poly.mul (poly.var 0) (poly.var 1)) (poly.var 5))) (poly.mul (poly.mul (poly.const 3/1) (poly.var 0)) (poly.var 1)))\\\",\\\"(poly.const -1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"K\",\n--   \"7\",\n--   \"[((var6 ^ 2) - ((var2 ^ 2) + (var1 ^ 3))), ((var3 ^ 3) - (var2 + var6)), ((var4 * var3) - var1), (((1 + var5) + (var5 ^ 2)) - 0), ((2 * var2) - ((var3 ^ 3) - (var4 ^ 3)))]\",\n--   \"((((var0 ^ 3) + ((3 * var1) * var0)) - (2 * var2)) - (((var0 - (var3 - var4)) * (var0 - ((var3 * var5) - (var4 * (var5 ^ 2))))) * (var0 - ((var3 * (var5 ^ 2)) - (var4 * var5)))))\"]\n--   \"linear_combination (x * \u03c9 ^ 4 - s * \u03c9 ^ 4 + t * \u03c9 ^ 4 - s * \u03c9 ^ 3 + t * \u03c9 ^ 3 + 3 * x * \u03c9 ^ 2 - s * \u03c9 ^ 2 +\n--       t * \u03c9 ^ 2 +\n--     2 * x * \u03c9) * ht + (-(x * s ^ 2 * \u03c9) + s ^ 3 * \u03c9 - x * t ^ 2 * \u03c9 - t ^ 3 * \u03c9 + x * p * \u03c9 ^ 2 - p * s * \u03c9 ^ 2 +\n--                 p * t * \u03c9 ^ 2 +\n--               x ^ 2 * s -\n--             s ^ 3 -\n--           x ^ 2 * t +\n--         t ^ 3 -\n--       x * p * \u03c9 +\n--     3 * x * p) * H - H'\"\n-- end\n\n\n-- /-! ## Degenerate cases -/\n\n-- example {K : Type _} [field K] [char_zero K] {s : K} (hs : 3 * s + 1 = 4) : s = 1 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/3)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"K\",\n--   \"1\",\n--   \"[(((3 * var0) + 1) - 4)]\",\n--   \"(var0 - 1)\"]\n--   \"linear_combination hs / 3\"\n\n-- example {x : \u2124} (h1 : x + 4 = 2) : x = -2 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"1\",\n--   \"[((var0 + 4) - 2)]\",\n--   \"(var0 - -2)\"]\n--   \"linear_combination h1\"\n\n-- example {w : \u211a} (h1 : 3 * w + 1 = 4) : w = 1 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/3)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"1\",\n--   \"[(((3 * var0) + 1) - 4)]\",\n--   \"(var0 - 1)\"]\n--   \"linear_combination h1 / 3\"\n\n-- example {x : \u2124} (h1 : 2 * x + 3 = x) : x = -3 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"1\",\n--   \"[(((2 * var0) + 3) - var0)]\",\n--   \"(var0 - -3)\"]\n--   \"linear_combination h1\"\n\n-- example {c : \u211a} (h1 : 4 * c + 1 = 3 * c - 2) : c = -3 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"rat\",\n--   \"1\",\n--   \"[(((4 * var0) + 1) - ((3 * var0) - 2))]\",\n--   \"(var0 - -3)\"]\n--   \"linear_combination h1\"\n\n-- example (z : \u2124) (h1 : z + 1 = 2) (h2 : z + 2 = 2) : (1 : \u2124) = 2 :=\n-- by test_polyrith\n--   \"{\\\"data\\\":[\\\"(poly.const 1/1)\\\",\\\"(poly.const -1/1)\\\"],\\\"success\\\":true}\"\n--   [\"ff\",\n--   \"int\",\n--   \"1\",\n--   \"[((var0 + 1) - 2), ((var0 + 2) - 2)]\",\n--   \"(1 - 2)\"]\n--   \"linear_combination h1 - h2\"\n\n\n-- We comment the following tests so that we don't overwhelm the SageCell API.\n\n\n\n\n/-\n\n/-! ### Standard Cases over \u2124, \u211a, and \u211d -/\n\nexample (x y : \u2124) (h1 : 3*x + 2*y = 10):\n  3*x + 2*y = 10 :=\nby polyrith\n\nexample (x y : \u211a) (h1 : x*y + 2*x = 1) (h2 : x = y) :\n  x*y = -2*y + 1 :=\nby polyrith\n\n-- example (x y : \u211d) (h1 : x + 2 = -3) (h2 : y = 10) :\n--   -y + 2*x + 4 = -16 :=\n-- by polyrith\n\n-- example (x y z : \u211d) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2)\n--     (hc : x + 2*y + z = 2) :\n--   -3*x - 3*y - 4*z = 2 :=\n-- by polyrith\n\n-- example (w x y z : \u211d) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5)\n--     (h3 : x + y + 5*z + 5*w = 3) :\n--   x + 2.2*y + 2*z - 5*w = -8.5 :=\n-- by polyrith\n\nexample (a b c d : \u211a) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) :\n  2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a :=\nby polyrith\n\n/-! ### Case with ambiguous identifiers-/\n-- set_option trace.Meta.Tactic.polyrith true\nexample (\u00abdef evil\u00bb y : \u2124) (h1 : 3*\u00abdef evil\u00bb + 2*y = 10):\n  3*\u00abdef evil\u00bb + 2*y = 10 :=\nby polyrith\n\nexample (\u00ab\u00a5\u00bb y : \u2124) (h1 : 3*\u00ab\u00a5\u00bb + 2*y = 10):\n  \u00ab\u00a5\u00bb * (3*\u00ab\u00a5\u00bb + 2*y) = 10 * \u00ab\u00a5\u00bb :=\nby polyrith\n\n/-! ### Cases with arbitrary coefficients -/\n\nexample (a b : \u2124) (h : a = b) :\n  a * a = a * b :=\nby polyrith\n\nexample (a b c : \u2124) (h : a = b) :\n  a * c = b * c :=\nby polyrith\n\nexample (a b c : \u2124) (h1 : a = b) (h2 : b = 1) :\n  c * a + b = c * b + 1 :=\nby polyrith\n\nexample (x y : \u211a) (h1 : x + y = 3) (h2 : 3*x = 7) :\n  x*x*y + y*x*y + 6*x = 3*x*y + 14 :=\nby polyrith\n\nexample (x y z w : \u211a) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w :=\nby polyrith\n\n\n/-! ### Cases with non-hypothesis inputs/input restrictions -/\n\n-- example (a b : \u211d) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) :\n--   b = 2 / 3 :=\n-- by polyrith only [ha, hab]\n\naxiom term : \u2200 a b : \u211a, a + b = 0\n\nexample (a b c d : \u211a) (h : a + b = 0) (h2: b + c = 0): a + b + c + d = 0 :=\nby polyrith only [term c d, h]\n\naxiom qc : \u211a\naxiom hqc : qc = 2*qc\n\nexample (a b : \u211a) (h : \u2200 p q : \u211a, p = q) : 3*a + qc = 3*b + 2*qc :=\nby polyrith [h a b, hqc]\n\naxiom bad (q : \u211a) : q = 0\n\nexample (a b : \u211a) : a + b^3 = 0 :=\nby polyrith [bad a, bad (b^2)]\n\n/-! ### Case over arbitrary field/ring -/\n\nexample {\u03b1} [h : CommRing \u03b1] {a b c d e f : \u03b1} (h1 : a*d = b*c) (h2 : c*f = e*d) :\n  c * (a*f - b*e) = 0 :=\nby polyrith\n\n-- example {K : Type _} [Field K] [Invertible 2] [Invertible 3]\n--   {\u03c9 p q r s t x: K} (hp_nonzero : p \u2260 0) (hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r)\n--   (ht : t * s = p) (x : K) (H : 1 + \u03c9 + \u03c9 ^ 2 = 0) :\n--   x ^ 3 + 3 * p * x - 2 * q =\n--     (x - (s - t)) * (x - (s * \u03c9 - t * \u03c9 ^ 2)) * (x - (s * \u03c9 ^ 2 - t * \u03c9)) :=\n-- begin\n--   have hs_nonzero : s \u2260 0,\n--   { contrapose! hp_nonzero with hs_nonzero,\n--     polyrith,\n--      },\n--   have H' : 2 * q = s ^ 3 - t ^ 3,\n--   { rw \u2190 mul_left_inj' (pow_ne_zero 3 hs_nonzero),\n--     polyrith,},\n--   polyrith,\n-- end\n\n/-!\n### With trace enabled\nHere, the tactic will trace the command that gets sent to sage,\nand so the tactic will not prove the goal. `linear_combination`\nis called manually to prevent errors.\n-/\n\nset_option trace.Meta.Tactic.polyrith true\n\n-- example (x y : \u211d) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by\n--   polyrith\n--   linear_combination 2 * h1 - h2\n\nexample (a b c : \u2124) (h1 : a = b) (h2 : b = 1) : c * a + b = c * b + 1 := by\n  polyrith\n  linear_combination c * h1 + h2\n\nexample (a b c d : \u211a) (h : a + b = 0) (h2: b + c = 0): a + b + c + d = 0 := by\n  polyrith only [term c d, h]\n  linear_combination term c d + h\n\nexample (a b : \u211a) (h : \u2200 p q : \u211a, p = q) : 3*a + qc = 3*b + 2*qc := by\n  polyrith [h a b, hqc]\n  linear_combination 3 * h a b + hqc\n-/\n\n\n-- the following can be uncommented to regenerate the tests above.\n\n/-\n\n\n/-! ### Standard Cases over \u2124, \u211a, and \u211d -/\n\nexample (x y : \u2124) (h1 : 3*x + 2*y = 10):\n  3*x + 2*y = 10 :=\nby create_polyrith_test\n\nexample (x y : \u211a) (h1 : x*y + 2*x = 1) (h2 : x = y) :\n  x*y = -2*y + 1 :=\nby create_polyrith_test\n\nexample (x y : \u211d) (h1 : x + 2 = -3) (h2 : y = 10) :\n  -y + 2*x + 4 = -16 :=\nby create_polyrith_test\n\nexample (x y z : \u211d) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2)\n    (hc : x + 2*y + z = 2) :\n  -3*x - 3*y - 4*z = 2 :=\nby create_polyrith_test\n\nexample (w x y z : \u211d) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5)\n    (h3 : x + y + 5*z + 5*w = 3) :\n  x + 2.2*y + 2*z - 5*w = -8.5 :=\nby create_polyrith_test\n\nexample (a b c d : \u211a) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) :\n  2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a :=\nby create_polyrith_test\n\n/-! ### Case with ambiguous identifiers-/\n\nexample (\u00abdef evil\u00bb y : \u2124) (h1 : 3*\u00abdef evil\u00bb + 2*y = 10):\n  3*\u00abdef evil\u00bb + 2*y = 10 :=\nby create_polyrith_test\n\nexample (\u00ab\u00a5\u00bb y : \u2124) (h1 : 3*\u00ab\u00a5\u00bb + 2*y = 10):\n  \u00ab\u00a5\u00bb * (3*\u00ab\u00a5\u00bb + 2*y) = 10 * \u00ab\u00a5\u00bb :=\nby create_polyrith_test\n\n/-! ### Cases with arbitrary coefficients -/\n\nexample (a b : \u2124) (h : a = b) :\n  a * a = a * b :=\nby create_polyrith_test\n\nexample (a b c : \u2124) (h : a = b) :\n  a * c = b * c :=\nby create_polyrith_test\n\nexample (a b c : \u2124) (h1 : a = b) (h2 : b = 1) :\n  c * a + b = c * b + 1 :=\nby create_polyrith_test\n\nexample (x y : \u211a) (h1 : x + y = 3) (h2 : 3*x = 7) :\n  x*x*y + y*x*y + 6*x = 3*x*y + 14 :=\nby create_polyrith_test\n\nexample (x y z w : \u211a) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w :=\nby create_polyrith_test\n\n/-! ### Cases with non-hypothesis inputs/input restrictions -/\n\nexample (a b : \u211d) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) :\n  b = 2 / 3 :=\nby create_polyrith_test only [ha, hab]\n\nconstant term : \u2200 a b : \u211a, a + b = 0\n\nexample (a b c d : \u211a) (h : a + b = 0) (h2: b + c = 0): a + b + c + d = 0 :=\nby create_polyrith_test only [term c d, h]\n\nconstants (qc : \u211a) (hqc : qc = 2*qc)\n\nexample (a b : \u211a) (h : \u2200 p q : \u211a, p = q) : 3*a + qc = 3*b + 2*qc :=\nby create_polyrith_test [h a b, hqc]\n\nconstant bad (q : \u211a) : q = 0\n\nexample (a b : \u211a) : a + b^3 = 0 :=\nby create_polyrith_test [bad a, bad (b^2)]\n\n/-! ### Case over arbitrary field/ring -/\n\nexample {\u03b1} [h : comm_ring \u03b1] {a b c d e f : \u03b1} (h1 : a*d = b*c) (h2 : c*f = e*d) :\n  c * (a*f - b*e) = 0 :=\nby create_polyrith_test\n\nexample {K : Type _} [field K] [invertible 2] [invertible 3]\n  {\u03c9 p q r s t x: K} (hp_nonzero : p \u2260 0) (hr : r ^ 2 = q ^ 2 + p ^ 3) (hs3 : s ^ 3 = q + r)\n  (ht : t * s = p) (x : K) (H : 1 + \u03c9 + \u03c9 ^ 2 = 0) :\n  x ^ 3 + 3 * p * x - 2 * q =\n    (x - (s - t)) * (x - (s * \u03c9 - t * \u03c9 ^ 2)) * (x - (s * \u03c9 ^ 2 - t * \u03c9)) :=\nbegin\n  have hs_nonzero : s \u2260 0,\n  { contrapose! hp_nonzero with hs_nonzero,\n    create_polyrith_test },\n  have H' : 2 * q = s ^ 3 - t ^ 3,\n  { rw \u2190 mul_left_inj' (pow_ne_zero 3 hs_nonzero),\n    create_polyrith_test },\n  create_polyrith_test\nend\n\n\n/-! ## Degenerate cases -/\n\nexample {K : Type _} [field K] [char_zero K] {s : K} (hs : 3 * s + 1 = 4) : s = 1 :=\nby create_polyrith_test\n\nexample {x : \u2124} (h1 : x + 4 = 2) : x = -2 :=\nby create_polyrith_test\n\nexample {w : \u211a} (h1 : 3 * w + 1 = 4) : w = 1 :=\nby create_polyrith_test\n\nexample {x : \u2124} (h1 : 2 * x + 3 = x) : x = -3 :=\nby create_polyrith_test\n\nexample {c : \u211a} (h1 : 4 * c + 1 = 3 * c - 2) : c = -3 :=\nby create_polyrith_test\n\nexample (z : \u2124) (h1 : z + 1 = 2) (h2 : z + 2 = 2) : (1 : \u2124) = 2 :=\nby create_polyrith_test\n\n\n-/\n\n-- example (a b : \u2124) (h : a + b = 4) : a + b = 0 := by\n--   fail_if_success polyrith\n--   -- polyrith failed to retrieve a solution from Sage!\n--   -- ValueError: polynomial is not in the ideal\n--   sorry\n\n-- example (a : \u2115) : a = 0 := by\n--   have := True.intro\n--   polyrith -- polyrith did not find any relevant hypotheses and the goal is not provable by ring\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/polyrith.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.06754669817865513, "lm_q1q2_score": 0.031665258965705496}}
{"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 \u2227 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 {\u03b1 : Sort u_1} {a : \u03b1} : \u03b1 := a\n\n/-- Ex falso, the nondependent eliminator for the `empty` type. -/\ndef empty.elim {C : Sort u_1} : empty \u2192 C := sorry\n\nprotected instance empty.subsingleton : subsingleton empty :=\n  subsingleton.intro fun (a : empty) => empty.elim a\n\nprotected instance subsingleton.prod {\u03b1 : Type u_1} {\u03b2 : Type u_2} [subsingleton \u03b1]\n    [subsingleton \u03b2] : subsingleton (\u03b1 \u00d7 \u03b2) :=\n  subsingleton.intro\n    fun (a b : \u03b1 \u00d7 \u03b2) =>\n      prod.cases_on a\n        fun (a_fst : \u03b1) (a_snd : \u03b2) =>\n          prod.cases_on b\n            fun (b_fst : \u03b1) (b_snd : \u03b2) =>\n              (fun (fst fst_1 : \u03b1) (snd snd_1 : \u03b2) =>\n                  Eq.trans ((fun (fst : \u03b1) (snd : \u03b2) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [Inhabited \u03b1] :\n    Inhabited (psum \u03b1 \u03b2) :=\n  { default := psum.inl Inhabited.default }\n\nprotected instance psum.inhabited_right {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [Inhabited \u03b2] :\n    Inhabited (psum \u03b1 \u03b2) :=\n  { default := psum.inr Inhabited.default }\n\nprotected instance decidable_eq_of_subsingleton {\u03b1 : Sort u_1} [subsingleton \u03b1] : DecidableEq \u03b1 :=\n  sorry\n\n@[simp] theorem eq_iff_true_of_subsingleton {\u03b1 : Type u_1} [subsingleton \u03b1] (x : \u03b1) (y : \u03b1) :\n    x = y \u2194 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} [has_coe \u03b1 \u03b2] [has_coe_t \u03b2 \u03b3]\n    (a : \u03b1) : \u2191a = \u2191\u2191a :=\n  rfl\n\ntheorem coe_fn_coe_trans {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} [has_coe \u03b1 \u03b2]\n    [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_fun \u03b3] (x : \u03b1) : \u21d1x = \u21d1\u2191x :=\n  rfl\n\n@[simp] theorem coe_fn_coe_base {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [has_coe \u03b1 \u03b2] [has_coe_to_fun \u03b2]\n    (x : \u03b1) : \u21d1x = \u21d1\u2191x :=\n  rfl\n\ntheorem coe_sort_coe_trans {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} [has_coe \u03b1 \u03b2]\n    [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_sort \u03b3] (x : \u03b1) : \u21a5x = \u21a5\u2191x :=\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 : \u03b1 \u2243 \u03b2` and `a : \u03b1`\nthen you can write `e a` and this is elaborated as `\u21d1e 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 (\u03b1 \u03b2) extends \u03b1 \u2243 \u03b2\n\n-- if we add a `has_coe` instance,\n\n-- if we add a `has_coe` instance,\ninstance {\u03b1 \u03b2} : has_coe (sparkling_equiv \u03b1 \u03b2) (\u03b1 \u2243 \u03b2) :=\n\u27e8sparkling_equiv.to_equiv\u27e9\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 {\u03b1 \u03b2} : has_coe_to_fun (sparkling_equiv \u03b1 \u03b2) :=\n\u27e8\u03bb _, \u03b1 \u2192 \u03b2, \u03bb f, f.to_equiv.to_fun\u27e9\n```\n\n(Rationale: if we do not declare the direct coercion, then `\u21d1e a` is not in\nsimp-normal form. The lemma `coe_fn_coe_base` will unfold it to `\u21d1\u2191e a`. This\noften causes loops in the simplifier.)\n-/\n@[simp] theorem coe_sort_coe_base {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [has_coe \u03b1 \u03b2] [has_coe_to_sort \u03b2]\n    (x : \u03b1) : \u21a5x = \u21a5\u2191x :=\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 \u2192 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 : \u00acNonempty 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 \u2192 Prop} : (\u2200 (x : pempty), P x) \u2194 True :=\n  { mp := fun (h : \u2200 (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 \u2192 Prop} : (\u2203 (x : pempty), P x) \u2194 False := sorry\n\ntheorem congr_arg_heq {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (f : (a : \u03b1) \u2192 \u03b2 a) {a\u2081 : \u03b1} {a\u2082 : \u03b1} :\n    a\u2081 = a\u2082 \u2192 f a\u2081 == f a\u2082 :=\n  sorry\n\ntheorem plift.down_inj {\u03b1 : Sort u_1} (a : plift \u03b1) (b : plift \u03b1) :\n    plift.down a = plift.down b \u2192 a = b :=\n  sorry\n\n-- missing [symm] attribute for ne in core.\n\ntheorem ne_comm {\u03b1 : Sort u_1} {a : \u03b1} {b : \u03b1} : a \u2260 b \u2194 b \u2260 a := { mp := ne.symm, mpr := ne.symm }\n\n@[simp] theorem eq_iff_eq_cancel_left {\u03b1 : Type u_1} {b : \u03b1} {c : \u03b1} :\n    (\u2200 {a : \u03b1}, a = b \u2194 a = c) \u2194 b = c :=\n  { mp :=\n      fun (h : \u2200 {a : \u03b1}, a = b \u2194 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 : \u03b1) =>\n        eq.mpr (id (Eq._oldrec (Eq.refl (a = b \u2194 a = c)) h)) (iff.refl (a = c)) }\n\n@[simp] theorem eq_iff_eq_cancel_right {\u03b1 : Type u_1} {a : \u03b1} {b : \u03b1} :\n    (\u2200 {c : \u03b1}, a = c \u2194 b = c) \u2194 a = b :=\n  { mp :=\n      fun (h : \u2200 {c : \u03b1}, a = c \u2194 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 : \u03b1) =>\n        eq.mpr (id (Eq._oldrec (Eq.refl (a = a_1 \u2194 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 \u2260 True :=\n  fun (\u1fb0 : False = True) => idRhs ((fun (_x : Prop) => _x) False) (Eq.symm \u1fb0 \u25b8 trivial)\n\n/-! ### Declarations about `implies` -/\n\ntheorem iff_of_eq {a : Prop} {b : Prop} (e : a = b) : a \u2194 b := e \u25b8 iff.rfl\n\ntheorem iff_iff_eq {a : Prop} {b : Prop} : a \u2194 b \u2194 a = b := { mp := propext, mpr := iff_of_eq }\n\n@[simp] theorem eq_iff_iff {p : Prop} {q : Prop} : p = q \u2194 (p \u2194 q) := iff.symm iff_iff_eq\n\n@[simp] theorem imp_self {a : Prop} : a \u2192 a \u2194 True := iff_true_intro id\n\ntheorem imp_intro {\u03b1 : Prop} {\u03b2 : Prop} (h : \u03b1) : \u03b2 \u2192 \u03b1 := fun (_x : \u03b2) => h\n\ntheorem imp_false {a : Prop} : a \u2192 False \u2194 \u00aca := iff.rfl\n\ntheorem imp_and_distrib {b : Prop} {c : Prop} {\u03b1 : Sort u_1} : \u03b1 \u2192 b \u2227 c \u2194 (\u03b1 \u2192 b) \u2227 (\u03b1 \u2192 c) :=\n  { mp :=\n      fun (h : \u03b1 \u2192 b \u2227 c) =>\n        { left := fun (ha : \u03b1) => and.left (h ha), right := fun (ha : \u03b1) => and.right (h ha) },\n    mpr :=\n      fun (h : (\u03b1 \u2192 b) \u2227 (\u03b1 \u2192 c)) (ha : \u03b1) => { left := and.left h ha, right := and.right h ha } }\n\n@[simp] theorem and_imp {a : Prop} {b : Prop} {c : Prop} : a \u2227 b \u2192 c \u2194 a \u2192 b \u2192 c := sorry\n\ntheorem iff_def {a : Prop} {b : Prop} : a \u2194 b \u2194 (a \u2192 b) \u2227 (b \u2192 a) := iff_iff_implies_and_implies a b\n\ntheorem iff_def' {a : Prop} {b : Prop} : a \u2194 b \u2194 (b \u2192 a) \u2227 (a \u2192 b) := iff.trans iff_def and.comm\n\ntheorem imp_true_iff {\u03b1 : Sort u_1} : \u03b1 \u2192 True \u2194 True := iff_true_intro fun (_x : \u03b1) => trivial\n\n@[simp] theorem imp_iff_right {a : Prop} {b : Prop} (ha : a) : a \u2192 b \u2194 b :=\n  { mp := fun (f : a \u2192 b) => f ha, mpr := imp_intro }\n\n/-! ### Declarations about `not` -/\n\n/-- Ex falso for negation. From `\u00ac 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} {\u03b1 : Sort u_1} (H1 : \u00aca) (H2 : a) : \u03b1 := absurd H2 H1\n\ntheorem not.imp {a : Prop} {b : Prop} (H2 : \u00acb) (H1 : a \u2192 b) : \u00aca := mt H1 H2\n\ntheorem not_not_of_not_imp {a : Prop} {b : Prop} : \u00ac(a \u2192 b) \u2192 \u00ac\u00aca := mt not.elim\n\ntheorem not_of_not_imp {b : Prop} {a : Prop} : \u00ac(a \u2192 b) \u2192 \u00acb := mt imp_intro\n\ntheorem dec_em (p : Prop) [Decidable p] : p \u2228 \u00acp := decidable.em p\n\ntheorem em (p : Prop) : p \u2228 \u00acp := classical.em p\n\ntheorem or_not {p : Prop} : p \u2228 \u00acp := em p\n\ntheorem by_contradiction {p : Prop} : (\u00acp \u2192 False) \u2192 p := decidable.by_contradiction\n\n-- alias by_contradiction \u2190 by_contra\n\ntheorem by_contra {p : Prop} : (\u00acp \u2192 False) \u2192 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] : \u00ac\u00aca \u2194 a :=\n  { mp := decidable.by_contradiction, mpr := not_not_intro }\n\n/-- The Double Negation Theorem: `\u00ac \u00ac 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} : \u00ac\u00aca \u2194 a := decidable.not_not\n\ntheorem of_not_not {a : Prop} : \u00ac\u00aca \u2192 a := by_contra\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.of_not_imp {a : Prop} {b : Prop} [Decidable a] (h : \u00ac(a \u2192 b)) : a :=\n  decidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp {a : Prop} {b : Prop} : \u00ac(a \u2192 b) \u2192 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 : \u00aca \u2192 b)\n    (hb : \u00acb) : a :=\n  decidable.by_contradiction (hb \u2218 h)\n\ntheorem not.decidable_imp_symm {a : Prop} {b : Prop} [Decidable a] : (\u00aca \u2192 b) \u2192 \u00acb \u2192 a :=\n  decidable.not_imp_symm\n\ntheorem not.imp_symm {a : Prop} {b : Prop} : (\u00aca \u2192 b) \u2192 \u00acb \u2192 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    \u00aca \u2192 b \u2194 \u00acb \u2192 a :=\n  { mp := not.decidable_imp_symm, mpr := not.decidable_imp_symm }\n\ntheorem not_imp_comm {a : Prop} {b : Prop} : \u00aca \u2192 b \u2194 \u00acb \u2192 a := decidable.not_imp_comm\n\n@[simp] theorem imp_not_self {a : Prop} : a \u2192 \u00aca \u2194 \u00aca :=\n  { mp := fun (h : a \u2192 \u00aca) (ha : a) => h ha ha, mpr := fun (h : \u00aca) (_x : a) => h }\n\ntheorem decidable.not_imp_self {a : Prop} [Decidable a] : \u00aca \u2192 a \u2194 a :=\n  eq.mp (Eq._oldrec (Eq.refl (\u00aca \u2192 \u00ac\u00aca \u2194 \u00ac\u00aca)) (propext decidable.not_not)) imp_not_self\n\n@[simp] theorem not_imp_self {a : Prop} : \u00aca \u2192 a \u2194 a := decidable.not_imp_self\n\ntheorem imp.swap {a : Prop} {b : Prop} {c : Prop} : a \u2192 b \u2192 c \u2194 b \u2192 a \u2192 c :=\n  { mp := function.swap, mpr := function.swap }\n\ntheorem imp_not_comm {a : Prop} {b : Prop} : a \u2192 \u00acb \u2194 b \u2192 \u00aca := imp.swap\n\n/-! ### Declarations about `and` -/\n\ntheorem and_congr_left {a : Prop} {b : Prop} {c : Prop} (h : c \u2192 (a \u2194 b)) : a \u2227 c \u2194 b \u2227 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 \u2194 b) : a \u2227 c \u2194 b \u2227 c :=\n  and_congr h iff.rfl\n\ntheorem and_congr_right' {a : Prop} {b : Prop} {c : Prop} (h : b \u2194 c) : a \u2227 b \u2194 a \u2227 c :=\n  and_congr iff.rfl h\n\ntheorem not_and_of_not_left {a : Prop} (b : Prop) : \u00aca \u2192 \u00ac(a \u2227 b) := mt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : \u00acb \u2192 \u00ac(a \u2227 b) := mt and.right\n\ntheorem and.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a \u2192 b) : a \u2227 c \u2192 b \u2227 c := and.imp h id\n\ntheorem and.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a \u2192 b) : c \u2227 a \u2192 c \u2227 b := and.imp id h\n\ntheorem and.right_comm {a : Prop} {b : Prop} {c : Prop} : (a \u2227 b) \u2227 c \u2194 (a \u2227 c) \u2227 b := sorry\n\ntheorem and.rotate {a : Prop} {b : Prop} {c : Prop} : a \u2227 b \u2227 c \u2194 b \u2227 c \u2227 a := sorry\n\ntheorem and_not_self_iff (a : Prop) : a \u2227 \u00aca \u2194 False :=\n  { mp := fun (h : a \u2227 \u00aca) => and.right h (and.left h), mpr := fun (h : False) => false.elim h }\n\ntheorem not_and_self_iff (a : Prop) : \u00aca \u2227 a \u2194 False := sorry\n\ntheorem and_iff_left_of_imp {a : Prop} {b : Prop} (h : a \u2192 b) : a \u2227 b \u2194 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 \u2192 a) : a \u2227 b \u2194 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 \u2227 b \u2194 a \u2194 a \u2192 b :=\n  { mp := fun (h : a \u2227 b \u2194 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 \u2227 b \u2194 b \u2194 b \u2192 a :=\n  { mp := fun (h : a \u2227 b \u2194 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 \u2227 b \u2194 a \u2227 c \u2194 a \u2192 (b \u2194 c) :=\n  sorry\n\n@[simp] theorem and.congr_left_iff {a : Prop} {b : Prop} {c : Prop} : a \u2227 c \u2194 b \u2227 c \u2194 c \u2192 (a \u2194 b) :=\n  sorry\n\n@[simp] theorem and_self_left {a : Prop} {b : Prop} : a \u2227 a \u2227 b \u2194 a \u2227 b :=\n  { mp := fun (h : a \u2227 a \u2227 b) => { left := and.left h, right := and.right (and.right h) },\n    mpr :=\n      fun (h : a \u2227 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 \u2227 b) \u2227 b \u2194 a \u2227 b :=\n  { mp := fun (h : (a \u2227 b) \u2227 b) => { left := and.left (and.left h), right := and.right h },\n    mpr :=\n      fun (h : a \u2227 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 \u2194 b) : a \u2228 c \u2194 b \u2228 c :=\n  or_congr h iff.rfl\n\ntheorem or_congr_right {a : Prop} {b : Prop} {c : Prop} (h : b \u2194 c) : a \u2228 b \u2194 a \u2228 c :=\n  or_congr iff.rfl h\n\ntheorem or.right_comm {a : Prop} {b : Prop} {c : Prop} : (a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 b :=\n  eq.mpr (id (Eq._oldrec (Eq.refl ((a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 b)) (propext (or_assoc a b))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2228 c \u2194 (a \u2228 c) \u2228 b)) (propext (or_assoc a c))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2228 c \u2194 a \u2228 c \u2228 b)) (propext (or_comm b c))))\n        (iff.refl (a \u2228 c \u2228 b))))\n\ntheorem or_of_or_of_imp_of_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h\u2081 : a \u2228 b) (h\u2082 : a \u2192 c)\n    (h\u2083 : b \u2192 d) : c \u2228 d :=\n  or.imp h\u2082 h\u2083 h\u2081\n\ntheorem or_of_or_of_imp_left {a : Prop} {b : Prop} {c : Prop} (h\u2081 : a \u2228 c) (h : a \u2192 b) : b \u2228 c :=\n  or.imp_left h h\u2081\n\ntheorem or_of_or_of_imp_right {a : Prop} {b : Prop} {c : Prop} (h\u2081 : c \u2228 a) (h : a \u2192 b) : c \u2228 b :=\n  or.imp_right h h\u2081\n\ntheorem or.elim3 {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h : a \u2228 b \u2228 c) (ha : a \u2192 d)\n    (hb : b \u2192 d) (hc : c \u2192 d) : d :=\n  or.elim h ha fun (h\u2082 : b \u2228 c) => or.elim h\u2082 hb hc\n\ntheorem or_imp_distrib {a : Prop} {b : Prop} {c : Prop} : a \u2228 b \u2192 c \u2194 (a \u2192 c) \u2227 (b \u2192 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 \u2228 b \u2194 \u00aca \u2192 b :=\n  { mp := or.resolve_left, mpr := fun (h : \u00aca \u2192 b) => dite a Or.inl (Or.inr \u2218 h) }\n\ntheorem or_iff_not_imp_left {a : Prop} {b : Prop} : a \u2228 b \u2194 \u00aca \u2192 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 \u2228 b \u2194 \u00acb \u2192 a :=\n  iff.trans or.comm decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right {a : Prop} {b : Prop} : a \u2228 b \u2194 \u00acb \u2192 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] : \u00aca \u2192 \u00acb \u2194 b \u2192 a :=\n  { mp := fun (h : \u00aca \u2192 \u00acb) (hb : b) => decidable.by_contradiction fun (na : \u00aca) => h na hb,\n    mpr := mt }\n\ntheorem not_imp_not {a : Prop} {b : Prop} : \u00aca \u2192 \u00acb \u2194 b \u2192 a := decidable.not_imp_not\n\n@[simp] theorem or_iff_left_iff_imp {a : Prop} {b : Prop} : a \u2228 b \u2194 a \u2194 b \u2192 a :=\n  { mp := fun (h : a \u2228 b \u2194 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 \u2228 b \u2194 b \u2194 a \u2192 b :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2194 b \u2194 a \u2192 b)) (propext (or_comm a b))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (b \u2228 a \u2194 b \u2194 a \u2192 b)) (propext or_iff_left_iff_imp)))\n      (iff.refl (a \u2192 b)))\n\n/-! ### Declarations about distributivity -/\n\n/-- `\u2227` distributes over `\u2228` (on the left). -/\ntheorem and_or_distrib_left {a : Prop} {b : Prop} {c : Prop} : a \u2227 (b \u2228 c) \u2194 a \u2227 b \u2228 a \u2227 c := sorry\n\n/-- `\u2227` distributes over `\u2228` (on the right). -/\ntheorem or_and_distrib_right {a : Prop} {b : Prop} {c : Prop} : (a \u2228 b) \u2227 c \u2194 a \u2227 c \u2228 b \u2227 c :=\n  iff.trans (iff.trans and.comm and_or_distrib_left) (or_congr and.comm and.comm)\n\n/-- `\u2228` distributes over `\u2227` (on the left). -/\ntheorem or_and_distrib_left {a : Prop} {b : Prop} {c : Prop} : a \u2228 b \u2227 c \u2194 (a \u2228 b) \u2227 (a \u2228 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 \u2218 Or.inl) (or.imp_right \u2218 And.intro)) }\n\n/-- `\u2228` distributes over `\u2227` (on the right). -/\ntheorem and_or_distrib_right {a : Prop} {b : Prop} {c : Prop} : a \u2227 b \u2228 c \u2194 (a \u2228 c) \u2227 (b \u2228 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 \u2228 a \u2228 b \u2194 a \u2228 b :=\n  { mp := fun (h : a \u2228 a \u2228 b) => or.elim h Or.inl id,\n    mpr := fun (h : a \u2228 b) => or.elim h Or.inl (Or.inr \u2218 Or.inr) }\n\n@[simp] theorem or_self_right {a : Prop} {b : Prop} : (a \u2228 b) \u2228 b \u2194 a \u2228 b :=\n  { mp := fun (h : (a \u2228 b) \u2228 b) => or.elim h id Or.inr,\n    mpr := fun (h : a \u2228 b) => or.elim h (Or.inl \u2218 Or.inl) Or.inr }\n\n/-! Declarations about `iff` -/\n\ntheorem iff_of_true {a : Prop} {b : Prop} (ha : a) (hb : b) : a \u2194 b :=\n  { mp := fun (_x : a) => hb, mpr := fun (_x : b) => ha }\n\ntheorem iff_of_false {a : Prop} {b : Prop} (ha : \u00aca) (hb : \u00acb) : a \u2194 b :=\n  { mp := not.elim ha, mpr := not.elim hb }\n\ntheorem iff_true_left {a : Prop} {b : Prop} (ha : a) : a \u2194 b \u2194 b :=\n  { mp := fun (h : a \u2194 b) => iff.mp h ha, mpr := iff_of_true ha }\n\ntheorem iff_true_right {a : Prop} {b : Prop} (ha : a) : b \u2194 a \u2194 b :=\n  iff.trans iff.comm (iff_true_left ha)\n\ntheorem iff_false_left {a : Prop} {b : Prop} (ha : \u00aca) : a \u2194 b \u2194 \u00acb :=\n  { mp := fun (h : a \u2194 b) => mt (iff.mpr h) ha, mpr := iff_of_false ha }\n\ntheorem iff_false_right {a : Prop} {b : Prop} (ha : \u00aca) : b \u2194 a \u2194 \u00acb :=\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 \u2192 b) :\n    \u00aca \u2228 b :=\n  dite a (fun (ha : a) => Or.inr (h ha)) fun (ha : \u00aca) => Or.inl ha\n\ntheorem not_or_of_imp {a : Prop} {b : Prop} : (a \u2192 b) \u2192 \u00aca \u2228 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 \u2192 b \u2194 \u00aca \u2228 b :=\n  { mp := decidable.not_or_of_imp, mpr := or.neg_resolve_left }\n\ntheorem imp_iff_not_or {a : Prop} {b : Prop} : a \u2192 b \u2194 \u00aca \u2228 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 \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\n  sorry\n\ntheorem imp_or_distrib {a : Prop} {b : Prop} {c : Prop} : a \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 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 \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\n  sorry\n\ntheorem imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} : a \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\n  decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not {a : Prop} {b : Prop} : a \u2227 \u00acb \u2192 \u00ac(a \u2192 b) :=\n  fun (\u1fb0 : a \u2227 \u00acb) (\u1fb0_1 : a \u2192 b) =>\n    and.dcases_on \u1fb0 fun (\u1fb0_left : a) (\u1fb0_right : \u00acb) => idRhs False (\u1fb0_right (\u1fb0_1 \u1fb0_left))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp {a : Prop} {b : Prop} [Decidable a] : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb :=\n  { mp := fun (h : \u00ac(a \u2192 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} : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb := decidable.not_imp\n\n-- for monotonicity\n\ntheorem imp_imp_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h\u2080 : c \u2192 a) (h\u2081 : b \u2192 d) :\n    (a \u2192 b) \u2192 c \u2192 d :=\n  fun (h\u2082 : a \u2192 b) => h\u2081 \u2218 h\u2082 \u2218 h\u2080\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.peirce (a : Prop) (b : Prop) [Decidable a] : ((a \u2192 b) \u2192 a) \u2192 a :=\n  dite a (fun (ha : a) (h : (a \u2192 b) \u2192 a) => ha) fun (ha : \u00aca) (h : (a \u2192 b) \u2192 a) => h (not.elim ha)\n\ntheorem peirce (a : Prop) (b : Prop) : ((a \u2192 b) \u2192 a) \u2192 a := decidable.peirce a b\n\ntheorem peirce' {a : Prop} (H : \u2200 (b : Prop), (a \u2192 b) \u2192 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    \u00aca \u2194 \u00acb \u2194 (a \u2194 b) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (\u00aca \u2194 \u00acb \u2194 (a \u2194 b))) (propext iff_def)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl ((\u00aca \u2192 \u00acb) \u2227 (\u00acb \u2192 \u00aca) \u2194 (a \u2194 b))) (propext iff_def')))\n      (and_congr decidable.not_imp_not decidable.not_imp_not))\n\ntheorem not_iff_not {a : Prop} {b : Prop} : \u00aca \u2194 \u00acb \u2194 (a \u2194 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    \u00aca \u2194 b \u2194 (\u00acb \u2194 a) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (\u00aca \u2194 b \u2194 (\u00acb \u2194 a))) (propext iff_def)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl ((\u00aca \u2192 b) \u2227 (b \u2192 \u00aca) \u2194 (\u00acb \u2194 a))) (propext iff_def)))\n      (and_congr decidable.not_imp_comm imp_not_comm))\n\ntheorem not_iff_comm {a : Prop} {b : Prop} : \u00aca \u2194 b \u2194 (\u00acb \u2194 a) := decidable.not_iff_comm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff {a : Prop} {b : Prop} [Decidable b] : \u00ac(a \u2194 b) \u2194 (\u00aca \u2194 b) :=\n  sorry\n\ntheorem not_iff {a : Prop} {b : Prop} : \u00ac(a \u2194 b) \u2194 (\u00aca \u2194 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 \u2194 \u00acb \u2194 (b \u2194 \u00aca) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2194 \u00acb \u2194 (b \u2194 \u00aca))) (propext iff_def)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl ((a \u2192 \u00acb) \u2227 (\u00acb \u2192 a) \u2194 (b \u2194 \u00aca))) (propext iff_def)))\n      (and_congr imp_not_comm decidable.not_imp_comm))\n\ntheorem iff_not_comm {a : Prop} {b : Prop} : a \u2194 \u00acb \u2194 (b \u2194 \u00aca) := 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 \u2194 b \u2194 a \u2227 b \u2228 \u00aca \u2227 \u00acb :=\n  sorry\n\ntheorem iff_iff_and_or_not_and_not {a : Prop} {b : Prop} : a \u2194 b \u2194 a \u2227 b \u2228 \u00aca \u2227 \u00acb :=\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 \u2194 b \u2194 (\u00aca \u2228 b) \u2227 (a \u2228 \u00acb) :=\n  sorry\n\ntheorem iff_iff_not_or_and_or_not {a : Prop} {b : Prop} : a \u2194 b \u2194 (\u00aca \u2228 b) \u2227 (a \u2228 \u00acb) :=\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    \u00ac(a \u2227 \u00acb) \u2194 a \u2192 b :=\n  sorry\n\ntheorem not_and_not_right {a : Prop} {b : Prop} : \u00ac(a \u2227 \u00acb) \u2194 a \u2192 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 \u2194 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 \u2194 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 \u2194 a`.\n(This is sometimes taken as an alternate definition of decidability.) -/\ndef decidable_of_bool {a : Prop} (b : Bool) (h : \u21a5b \u2194 a) : Decidable a := sorry\n\n/-! ### De Morgan's laws -/\n\ntheorem not_and_of_not_or_not {a : Prop} {b : Prop} (h : \u00aca \u2228 \u00acb) : \u00ac(a \u2227 b) :=\n  fun (\u1fb0 : a \u2227 b) =>\n    and.dcases_on \u1fb0\n      fun (\u1fb0_left : a) (\u1fb0_right : b) => idRhs False (or.elim h (absurd \u1fb0_left) (absurd \u1fb0_right))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib {a : Prop} {b : Prop} [Decidable a] :\n    \u00ac(a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\n  sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib' {a : Prop} {b : Prop} [Decidable b] :\n    \u00ac(a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\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} : \u00ac(a \u2227 b) \u2194 \u00aca \u2228 \u00acb := decidable.not_and_distrib\n\n@[simp] theorem not_and {a : Prop} {b : Prop} : \u00ac(a \u2227 b) \u2194 a \u2192 \u00acb := and_imp\n\ntheorem not_and' {a : Prop} {b : Prop} : \u00ac(a \u2227 b) \u2194 b \u2192 \u00aca := 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} : \u00ac(a \u2228 b) \u2194 \u00aca \u2227 \u00acb := 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 \u2228 b \u2194 \u00ac(\u00aca \u2227 \u00acb) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2194 \u00ac(\u00aca \u2227 \u00acb))) (Eq.symm (propext not_or_distrib))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2194 \u00ac\u00ac(a \u2228 b))) (propext decidable.not_not)))\n      (iff.refl (a \u2228 b)))\n\ntheorem or_iff_not_and_not {a : Prop} {b : Prop} : a \u2228 b \u2194 \u00ac(\u00aca \u2227 \u00acb) :=\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 \u2227 b \u2194 \u00ac(\u00aca \u2228 \u00acb) :=\n  eq.mpr\n    (id (Eq._oldrec (Eq.refl (a \u2227 b \u2194 \u00ac(\u00aca \u2228 \u00acb))) (Eq.symm (propext decidable.not_and_distrib))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2227 b \u2194 \u00ac\u00ac(a \u2227 b))) (propext decidable.not_not)))\n      (iff.refl (a \u2227 b)))\n\ntheorem and_iff_not_or_not {a : Prop} {b : Prop} : a \u2227 b \u2194 \u00ac(\u00aca \u2228 \u00acb) :=\n  decidable.and_iff_not_or_not\n\n/-! ### Declarations about equality -/\n\n@[simp] theorem heq_iff_eq {\u03b1 : Sort u_1} {a : \u03b1} {b : \u03b1} : a == b \u2194 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 {\u03b1 : outParam (Type u_1)} {\u03b2 : Type u_2} [has_mem \u03b1 \u03b2] {s : \u03b2} {a : \u03b1}\n    {b : \u03b1} (h : a \u2208 s) : \u00acb \u2208 s \u2192 a \u2260 b :=\n  mt fun (e : a = b) => e \u25b8 h\n\ntheorem eq_equivalence {\u03b1 : 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 {\u03b1 : Sort u_1} {a : \u03b1} {a' : \u03b1} {\u03b2 : Sort u_2} (y : \u03b2)\n    (h : a = a') : Eq._oldrec y h = y :=\n  sorry\n\n@[simp] theorem eq_mp_rfl {\u03b1 : Sort u_1} {a : \u03b1} : eq.mp (Eq.refl \u03b1) a = a := rfl\n\n@[simp] theorem eq_mpr_rfl {\u03b1 : Sort u_1} {a : \u03b1} : eq.mpr (Eq.refl \u03b1) a = a := rfl\n\ntheorem heq_of_eq_mp {\u03b1 : Sort u_1} {\u03b2 : Sort u_1} {a : \u03b1} {a' : \u03b2} (e : \u03b1 = \u03b2)\n    (h\u2082 : eq.mp e a = a') : a == a' :=\n  sorry\n\ntheorem rec_heq_of_heq {\u03b1 : Sort u_1} {a : \u03b1} {b : \u03b1} {\u03b2 : Sort u_2} {C : \u03b1 \u2192 Sort u_2} {x : C a}\n    {y : \u03b2} (eq : a = b) (h : x == y) : Eq._oldrec x eq == y :=\n  eq.drec h eq\n\n@[simp] theorem eq_mpr_heq {\u03b1 : Sort u} {\u03b2 : Sort u} (h : \u03b2 = \u03b1) (x : \u03b1) : eq.mpr h x == x :=\n  eq.drec (fun (x : \u03b2) => HEq.refl (eq.mpr (Eq.refl \u03b2) x)) h x\n\nprotected theorem eq.congr {\u03b1 : Sort u_1} {x\u2081 : \u03b1} {x\u2082 : \u03b1} {y\u2081 : \u03b1} {y\u2082 : \u03b1} (h\u2081 : x\u2081 = y\u2081)\n    (h\u2082 : x\u2082 = y\u2082) : x\u2081 = x\u2082 \u2194 y\u2081 = y\u2082 :=\n  Eq._oldrec (Eq._oldrec (iff.refl (x\u2081 = x\u2082)) h\u2082) h\u2081\n\ntheorem eq.congr_left {\u03b1 : Sort u_1} {x : \u03b1} {y : \u03b1} {z : \u03b1} (h : x = y) : x = z \u2194 y = z :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (x = z \u2194 y = z)) h)) (iff.refl (y = z))\n\ntheorem eq.congr_right {\u03b1 : Sort u_1} {x : \u03b1} {y : \u03b1} {z : \u03b1} (h : x = y) : z = x \u2194 z = y :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (z = x \u2194 z = y)) h)) (iff.refl (z = y))\n\ntheorem congr_arg2 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) {x : \u03b1} {x' : \u03b1}\n    {y : \u03b2} {y' : \u03b2} (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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), p a \u2192 q a) :\n    (\u2200 (a : \u03b1), p a) \u2192 \u2200 (a : \u03b1), q a :=\n  fun (h' : \u2200 (a : \u03b1), p a) (a : \u03b1) => h a (h' a)\n\ntheorem forall\u2082_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 Prop}\n    (h : \u2200 (a : \u03b1) (b : \u03b2), p a b \u2194 q a b) :\n    (\u2200 (a : \u03b1) (b : \u03b2), p a b) \u2194 \u2200 (a : \u03b1) (b : \u03b2), q a b :=\n  forall_congr fun (a : \u03b1) => forall_congr (h a)\n\ntheorem forall\u2083_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop}\n    {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), p a b c \u2194 q a b c) :\n    (\u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), p a b c) \u2194 \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), q a b c :=\n  forall_congr fun (a : \u03b1) => forall\u2082_congr (h a)\n\ntheorem forall\u2084_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {\u03b4 : Sort u_4}\n    {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop}\n    (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), p a b c d \u2194 q a b c d) :\n    (\u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), p a b c d) \u2194 \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), q a b c d :=\n  forall_congr fun (a : \u03b1) => forall\u2083_congr (h a)\n\ntheorem Exists.imp {\u03b1 : Sort u_1} {q : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), p a \u2192 q a) :\n    (\u2203 (a : \u03b1), p a) \u2192 \u2203 (a : \u03b1), q a :=\n  fun (p_1 : \u2203 (a : \u03b1), p a) => exists_imp_exists h p_1\n\ntheorem exists_imp_exists' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2)\n    (hpq : \u2200 (a : \u03b1), p a \u2192 q (f a)) (hp : \u2203 (a : \u03b1), p a) : \u2203 (b : \u03b2), q b :=\n  exists.elim hp fun (a : \u03b1) (hp' : p a) => Exists.intro (f a) (hpq a hp')\n\ntheorem exists\u2082_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 Prop}\n    (h : \u2200 (a : \u03b1) (b : \u03b2), p a b \u2194 q a b) :\n    (\u2203 (a : \u03b1), \u2203 (b : \u03b2), p a b) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), q a b :=\n  exists_congr fun (a : \u03b1) => exists_congr (h a)\n\ntheorem exists\u2083_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop}\n    {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), p a b c \u2194 q a b c) :\n    (\u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), p a b c) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), q a b c :=\n  exists_congr fun (a : \u03b1) => exists\u2082_congr (h a)\n\ntheorem exists\u2084_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {\u03b4 : Sort u_4}\n    {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop}\n    (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), p a b c d \u2194 q a b c d) :\n    (\u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), \u2203 (d : \u03b4), p a b c d) \u2194\n        \u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), \u2203 (d : \u03b4), q a b c d :=\n  exists_congr fun (a : \u03b1) => exists\u2083_congr (h a)\n\ntheorem forall_swap {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} :\n    (\u2200 (x : \u03b1) (y : \u03b2), p x y) \u2194 \u2200 (y : \u03b2) (x : \u03b1), p x y :=\n  { mp := function.swap, mpr := function.swap }\n\ntheorem exists_swap {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u2203 (y : \u03b2), p x y) \u2194 \u2203 (y : \u03b2), \u2203 (x : \u03b1), p x y :=\n  sorry\n\n@[simp] theorem exists_imp_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} :\n    (\u2203 (x : \u03b1), p x) \u2192 b \u2194 \u2200 (x : \u03b1), p x \u2192 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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (P : \u2203 (a : \u03b1), p a) : \u03b1 := classical.some P\n\n/--\nShow that an element extracted from `P : \u2203 a, p a` using `P.some` satisfies `p`.\n-/\ntheorem Exists.some_spec {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (P : \u2203 (a : \u03b1), p a) : p (Exists.some P) :=\n  classical.some_spec P\n\n--theorem forall_not_of_not_exists (h : \u00ac \u2203 x, p x) : \u2200 x, \u00ac p x :=\n\n--forall_imp_of_exists_imp h\n\ntheorem not_exists_of_forall_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2200 (x : \u03b1), \u00acp x) :\n    \u00ac\u2203 (x : \u03b1), p x :=\n  iff.mpr exists_imp_distrib h\n\n@[simp] theorem not_exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2203 (x : \u03b1), p x) \u2194 \u2200 (x : \u03b1), \u00acp x :=\n  exists_imp_distrib\n\ntheorem not_forall_of_exists_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u00acp x) \u2192 \u00ac\u2200 (x : \u03b1), p x :=\n  fun (\u1fb0 : \u2203 (x : \u03b1), \u00acp x) (\u1fb0_1 : \u2200 (x : \u03b1), p x) =>\n    Exists.dcases_on \u1fb0 fun (\u1fb0_w : \u03b1) (\u1fb0_h : \u00acp \u1fb0_w) => idRhs False (\u1fb0_h (\u1fb0_1 \u1fb0_w))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [Decidable (\u2203 (x : \u03b1), \u00acp x)]\n    [(x : \u03b1) \u2192 Decidable (p x)] : (\u00ac\u2200 (x : \u03b1), p x) \u2194 \u2203 (x : \u03b1), \u00acp x :=\n  sorry\n\n@[simp] theorem not_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2200 (x : \u03b1), p x) \u2194 \u2203 (x : \u03b1), \u00acp x :=\n  decidable.not_forall\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop}\n    [Decidable (\u2203 (x : \u03b1), p x)] : (\u00ac\u2200 (x : \u03b1), \u00acp x) \u2194 \u2203 (x : \u03b1), p x :=\n  iff.mp decidable.not_iff_comm not_exists\n\ntheorem not_forall_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2200 (x : \u03b1), \u00acp x) \u2194 \u2203 (x : \u03b1), p x :=\n  decidable.not_forall_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_exists_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop}\n    [(x : \u03b1) \u2192 Decidable (p x)] : (\u00ac\u2203 (x : \u03b1), \u00acp x) \u2194 \u2200 (x : \u03b1), p x :=\n  sorry\n\n@[simp] theorem not_exists_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} :\n    (\u00ac\u2203 (x : \u03b1), \u00acp x) \u2194 \u2200 (x : \u03b1), p x :=\n  decidable.not_exists_not\n\n@[simp] theorem forall_true_iff {\u03b1 : Sort u_1} : \u03b1 \u2192 True \u2194 True :=\n  iff_true_intro fun (_x : \u03b1) => 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' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), p a \u2194 True) :\n    (\u2200 (a : \u03b1), p a) \u2194 True :=\n  iff_true_intro fun (_x : \u03b1) => of_iff_true (h _x)\n\n@[simp] theorem forall_2_true_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} :\n    (\u2200 (a : \u03b1), \u03b2 a \u2192 True) \u2194 True :=\n  forall_true_iff' fun (_x : \u03b1) => forall_true_iff\n\n@[simp] theorem forall_3_true_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {\u03b3 : (a : \u03b1) \u2192 \u03b2 a \u2192 Sort u_3} :\n    (\u2200 (a : \u03b1) (b : \u03b2 a), \u03b3 a b \u2192 True) \u2194 True :=\n  forall_true_iff' fun (_x : \u03b1) => forall_2_true_iff\n\n@[simp] theorem forall_const {b : Prop} (\u03b1 : Sort u_1) [i : Nonempty \u03b1] : \u03b1 \u2192 b \u2194 b :=\n  { mp := nonempty.elim i, mpr := fun (hb : b) (x : \u03b1) => hb }\n\n@[simp] theorem exists_const {b : Prop} (\u03b1 : Sort u_1) [i : Nonempty \u03b1] : (\u2203 (x : \u03b1), b) \u2194 b :=\n  { mp :=\n      fun (_x : \u2203 (x : \u03b1), b) =>\n        (fun (_a : \u2203 (x : \u03b1), b) => Exists.dcases_on _a fun (w : \u03b1) (h : b) => idRhs b h) _x,\n    mpr := nonempty.elim i exists.intro }\n\ntheorem forall_and_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} :\n    (\u2200 (x : \u03b1), p x \u2227 q x) \u2194 (\u2200 (x : \u03b1), p x) \u2227 \u2200 (x : \u03b1), q x :=\n  sorry\n\ntheorem exists_or_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), p x \u2228 q x) \u2194 (\u2203 (x : \u03b1), p x) \u2228 \u2203 (x : \u03b1), q x :=\n  sorry\n\n@[simp] theorem exists_and_distrib_left {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), q \u2227 p x) \u2194 q \u2227 \u2203 (x : \u03b1), p x :=\n  sorry\n\n@[simp] theorem exists_and_distrib_right {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), p x \u2227 q) \u2194 (\u2203 (x : \u03b1), p x) \u2227 q :=\n  sorry\n\n@[simp] theorem forall_eq {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2200 (a : \u03b1), a = a' \u2192 p a) \u2194 p a' :=\n  { mp := fun (h : \u2200 (a : \u03b1), a = a' \u2192 p a) => h a' rfl,\n    mpr := fun (h : p a') (a : \u03b1) (e : a = a') => Eq.symm e \u25b8 h }\n\n@[simp] theorem forall_eq' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2200 (a : \u03b1), a' = a \u2192 p a) \u2194 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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2200 (a : \u03b1), a = a' \u2228 q a \u2192 p a) \u2194 p a' \u2227 \u2200 (a : \u03b1), q a \u2192 p a :=\n  sorry\n\n@[simp] theorem exists_eq {\u03b1 : Sort u_1} {a' : \u03b1} : \u2203 (a : \u03b1), a = a' := Exists.intro a' rfl\n\n@[simp] theorem exists_eq' {\u03b1 : Sort u_1} {a' : \u03b1} : \u2203 (a : \u03b1), a' = a := Exists.intro a' rfl\n\n@[simp] theorem exists_eq_left {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2203 (a : \u03b1), a = a' \u2227 p a) \u2194 p a' :=\n  sorry\n\n@[simp] theorem exists_eq_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2203 (a : \u03b1), p a \u2227 a = a') \u2194 p a' :=\n  iff.trans (exists_congr fun (a : \u03b1) => and.comm) exists_eq_left\n\n@[simp] theorem exists_eq_right_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} {a' : \u03b1} :\n    (\u2203 (a : \u03b1), p a \u2227 b \u2227 a = a') \u2194 p a' \u2227 b :=\n  sorry\n\n@[simp] theorem exists_eq_right_right' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} {a' : \u03b1} :\n    (\u2203 (a : \u03b1), p a \u2227 b \u2227 a' = a) \u2194 p a' \u2227 b :=\n  sorry\n\n@[simp] theorem exists_apply_eq_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) :\n    \u2203 (a : \u03b1), f a = f a' :=\n  Exists.intro a' rfl\n\n@[simp] theorem exists_apply_eq_apply' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) :\n    \u2203 (a : \u03b1), f a' = f a :=\n  Exists.intro a' rfl\n\n@[simp] theorem exists_exists_and_eq_and {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop}\n    {q : \u03b2 \u2192 Prop} : (\u2203 (b : \u03b2), (\u2203 (a : \u03b1), p a \u2227 f a = b) \u2227 q b) \u2194 \u2203 (a : \u03b1), p a \u2227 q (f a) :=\n  sorry\n\n@[simp] theorem exists_exists_eq_and {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n    (\u2203 (b : \u03b2), (\u2203 (a : \u03b1), f a = b) \u2227 p b) \u2194 \u2203 (a : \u03b1), p (f a) :=\n  sorry\n\n@[simp] theorem forall_apply_eq_imp_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n    (\u2200 (a : \u03b1) (b : \u03b2), f a = b \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) :=\n  { mp := fun (h : \u2200 (a : \u03b1) (b : \u03b2), f a = b \u2192 p b) (a : \u03b1) => h a (f a) rfl,\n    mpr := fun (h : \u2200 (a : \u03b1), p (f a)) (a : \u03b1) (b : \u03b2) (hab : f a = b) => hab \u25b8 h a }\n\n@[simp] theorem forall_apply_eq_imp_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n    (\u2200 (b : \u03b2) (a : \u03b1), f a = b \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) :=\n  sorry\n\n@[simp] theorem forall_eq_apply_imp_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n    (\u2200 (a : \u03b1) (b : \u03b2), b = f a \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) :=\n  sorry\n\n@[simp] theorem forall_eq_apply_imp_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n    (\u2200 (b : \u03b2) (a : \u03b1), b = f a \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) :=\n  sorry\n\n@[simp] theorem forall_apply_eq_imp_iff\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop}\n    {q : \u03b2 \u2192 Prop} : (\u2200 (b : \u03b2) (a : \u03b1), p a \u2192 f a = b \u2192 q b) \u2194 \u2200 (a : \u03b1), p a \u2192 q (f a) :=\n  { mp := fun (h : \u2200 (b : \u03b2) (a : \u03b1), p a \u2192 f a = b \u2192 q b) (a : \u03b1) (ha : p a) => h (f a) a ha rfl,\n    mpr :=\n      fun (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) (b : \u03b2) (a : \u03b1) (ha : p a) (hb : f a = b) => hb \u25b8 h a ha }\n\n@[simp] theorem exists_eq_left' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2203 (a : \u03b1), a' = a \u2227 p a) \u2194 p a' :=\n  sorry\n\n@[simp] theorem exists_eq_right' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} :\n    (\u2203 (a : \u03b1), p a \u2227 a' = a) \u2194 p a' :=\n  sorry\n\ntheorem exists_comm {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} :\n    (\u2203 (a : \u03b1), \u2203 (b : \u03b2), p a b) \u2194 \u2203 (b : \u03b2), \u2203 (a : \u03b1), p a b :=\n  sorry\n\ntheorem forall_or_of_or_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} (h : b \u2228 \u2200 (x : \u03b1), p x)\n    (x : \u03b1) : b \u2228 p x :=\n  or.imp_right (fun (h\u2082 : \u2200 (x : \u03b1), p x) => h\u2082 x) h\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_left {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop}\n    [Decidable q] : (\u2200 (x : \u03b1), q \u2228 p x) \u2194 q \u2228 \u2200 (x : \u03b1), p x :=\n  sorry\n\ntheorem forall_or_distrib_left {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} :\n    (\u2200 (x : \u03b1), q \u2228 p x) \u2194 q \u2228 \u2200 (x : \u03b1), p x :=\n  decidable.forall_or_distrib_left\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_right {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop}\n    [Decidable q] : (\u2200 (x : \u03b1), p x \u2228 q) \u2194 (\u2200 (x : \u03b1), p x) \u2228 q :=\n  sorry\n\ntheorem forall_or_distrib_right {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} :\n    (\u2200 (x : \u03b1), p x \u2228 q) \u2194 (\u2200 (x : \u03b1), p x) \u2228 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} (h : function.surjective f)\n    {P : \u03b2 \u2192 Prop} : (\u2200 (a : \u03b1), P (f a)) \u2194 \u2200 (b : \u03b2), P b :=\n  sorry\n\n@[simp] theorem exists_prop {p : Prop} {q : Prop} : (\u2203 (h : p), q) \u2194 p \u2227 q := sorry\n\n@[simp] theorem exists_false {\u03b1 : Sort u_1} : \u00ac\u2203 (a : \u03b1), False :=\n  fun (_x : \u2203 (a : \u03b1), False) =>\n    (fun (_a : \u2203 (a : \u03b1), False) => Exists.dcases_on _a fun (w : \u03b1) (h : False) => idRhs False h) _x\n\n@[simp] theorem exists_unique_false {\u03b1 : Sort u_1} : \u00acexists_unique fun (a : \u03b1) => False := sorry\n\ntheorem Exists.fst {b : Prop} {p : b \u2192 Prop} : Exists p \u2192 b :=\n  fun (\u1fb0 : Exists p) => Exists.dcases_on \u1fb0 fun (\u1fb0_w : b) (\u1fb0_h : p \u1fb0_w) => idRhs b \u1fb0_w\n\ntheorem Exists.snd {b : Prop} {p : b \u2192 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 \u2192 Prop} (h : p) : (\u2200 (h' : p), q h') \u2194 q h :=\n  forall_const p\n\n@[simp] theorem exists_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2203 (h' : p), q h') \u2194 q h :=\n  exists_const p\n\n@[simp] theorem forall_prop_of_false {p : Prop} {q : p \u2192 Prop} (hn : \u00acp) :\n    (\u2200 (h' : p), q h') \u2194 True :=\n  iff_true_intro fun (h : p) => not.elim hn h\n\n@[simp] theorem exists_prop_of_false {p : Prop} {q : p \u2192 Prop} : \u00acp \u2192 \u00ac\u2203 (h' : p), q h' :=\n  mt Exists.fst\n\ntheorem exists_unique.exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : exists_unique fun (x : \u03b1) => p x) :\n    \u2203 (x : \u03b1), p x :=\n  exists.elim h\n    fun (x : \u03b1) (hx : (fun (x : \u03b1) => p x) x \u2227 \u2200 (y : \u03b1), p y \u2192 y = x) =>\n      Exists.intro x (and.left hx)\n\ntheorem exists_unique.unique {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : exists_unique fun (x : \u03b1) => p x)\n    {y\u2081 : \u03b1} {y\u2082 : \u03b1} (py\u2081 : p y\u2081) (py\u2082 : p y\u2082) : y\u2081 = y\u2082 :=\n  unique_of_exists_unique h py\u2081 py\u2082\n\n@[simp] theorem exists_unique_iff_exists {\u03b1 : Sort u_1} [subsingleton \u03b1] {p : \u03b1 \u2192 Prop} :\n    (exists_unique fun (x : \u03b1) => p x) \u2194 \u2203 (x : \u03b1), p x :=\n  { mp := fun (h : exists_unique fun (x : \u03b1) => p x) => exists_unique.exists h,\n    mpr :=\n      Exists.imp\n        fun (x : \u03b1) (hx : p x) =>\n          { left := hx, right := fun (y : \u03b1) (_x : p y) => subsingleton.elim y x } }\n\ntheorem exists_unique.elim2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} [\u2200 (x : \u03b1), subsingleton (p x)]\n    {q : (x : \u03b1) \u2192 p x \u2192 Prop} {b : Prop}\n    (h\u2082 : exists_unique fun (x : \u03b1) => exists_unique fun (h : p x) => q x h)\n    (h\u2081 : \u2200 (x : \u03b1) (h : p x), q x h \u2192 (\u2200 (y : \u03b1) (hy : p y), q y hy \u2192 y = x) \u2192 b) : b :=\n  sorry\n\ntheorem exists_unique.intro2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} [\u2200 (x : \u03b1), subsingleton (p x)]\n    {q : (x : \u03b1) \u2192 p x \u2192 Prop} (w : \u03b1) (hp : p w) (hq : q w hp)\n    (H : \u2200 (y : \u03b1) (hy : p y), q y hy \u2192 y = w) :\n    exists_unique fun (x : \u03b1) => exists_unique fun (hx : p x) => q x hx :=\n  sorry\n\ntheorem exists_unique.exists2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} {q : (x : \u03b1) \u2192 p x \u2192 Prop}\n    (h : exists_unique fun (x : \u03b1) => exists_unique fun (hx : p x) => q x hx) :\n    \u2203 (x : \u03b1), \u2203 (hx : p x), q x hx :=\n  Exists.imp (fun (x : \u03b1) (hx : exists_unique fun (hx : p x) => q x hx) => exists_unique.exists hx)\n    (exists_unique.exists h)\n\ntheorem exists_unique.unique2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} [\u2200 (x : \u03b1), subsingleton (p x)]\n    {q : (x : \u03b1) \u2192 p x \u2192 Prop}\n    (h : exists_unique fun (x : \u03b1) => exists_unique fun (hx : p x) => q x hx) {y\u2081 : \u03b1} {y\u2082 : \u03b1}\n    (hpy\u2081 : p y\u2081) (hqy\u2081 : q y\u2081 hpy\u2081) (hpy\u2082 : p y\u2082) (hqy\u2082 : q y\u2082 hpy\u2082) : y\u2081 = y\u2082 :=\n  sorry\n\n/-! ### Classical lemmas -/\n\nnamespace classical\n\n\ntheorem cases {p : Prop \u2192 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 {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : decidable_pred p :=\n  fun (a : \u03b1) => prop_decidable (p a)\n\ntheorem dec_rel {\u03b1 : Sort u_1} (p : \u03b1 \u2192 \u03b1 \u2192 Prop) : DecidableRel p :=\n  fun (a b : \u03b1) => prop_decidable (p a b)\n\ntheorem dec_eq (\u03b1 : Sort u_1) : DecidableEq \u03b1 := fun (a b : \u03b1) => 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. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html>\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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {C : Sort u} (H0 : C) (H : (a : \u03b1) \u2192 p a \u2192 C) : C :=\n  dite (\u2203 (a : \u03b1), p a) (fun (h : \u2203 (a : \u03b1), p a) => H (some h) sorry)\n    fun (h : \u00ac\u2203 (a : \u03b1), p a) => H0\n\ntheorem some_spec2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {h : \u2203 (a : \u03b1), p a} (q : \u03b1 \u2192 Prop)\n    (hpq : \u2200 (a : \u03b1), p a \u2192 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 {\u03b1 : Type u_1} {P : \u03b1 \u2192 Prop} (h : \u2203 (x : \u03b1), P x) :\n    Subtype fun (x : \u03b1) => 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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2203 (a : \u03b1), p a) {C : Sort u}\n    (H : (a : \u03b1) \u2192 p a \u2192 C) : C :=\n  H (classical.some h) sorry\n\n/-! ### Declarations about bounded quantifiers -/\n\ntheorem bex_def {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u2203 (h : p x), q x) \u2194 \u2203 (x : \u03b1), p x \u2227 q x :=\n  sorry\n\ntheorem bex.elim {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {b : Prop} :\n    (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2192 (\u2200 (a : \u03b1) (h : p a), P a h \u2192 b) \u2192 b :=\n  sorry\n\ntheorem bex.intro {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} (a : \u03b1) (h\u2081 : p a)\n    (h\u2082 : P a h\u2081) : \u2203 (x : \u03b1), \u2203 (h : p x), P x h :=\n  Exists.intro a (Exists.intro h\u2081 h\u2082)\n\ntheorem ball_congr {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2194 Q x h) :\n    (\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2200 (x : \u03b1) (h : p x), Q x h :=\n  forall_congr fun (x : \u03b1) => forall_congr (H x)\n\ntheorem bex_congr {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2194 Q x h) :\n    (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), Q x h :=\n  exists_congr fun (x : \u03b1) => exists_congr (H x)\n\ntheorem bex_eq_left {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a : \u03b1} :\n    (\u2203 (x : \u03b1), \u2203 (_x : x = a), p x) \u2194 p a :=\n  sorry\n\ntheorem ball.imp_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2192 Q x h)\n    (h\u2081 : \u2200 (x : \u03b1) (h : p x), P x h) (x : \u03b1) (h : p x) : Q x h :=\n  H x h (h\u2081 x h)\n\ntheorem bex.imp_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2192 Q x h) :\n    (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2192 \u2203 (x : \u03b1), \u2203 (h : p x), Q x h :=\n  sorry\n\ntheorem ball.imp_left {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop}\n    (H : \u2200 (x : \u03b1), p x \u2192 q x) (h\u2081 : \u2200 (x : \u03b1), q x \u2192 r x) (x : \u03b1) (h : p x) : r x :=\n  h\u2081 x (H x h)\n\ntheorem bex.imp_left {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop}\n    (H : \u2200 (x : \u03b1), p x \u2192 q x) : (\u2203 (x : \u03b1), \u2203 (_x : p x), r x) \u2192 \u2203 (x : \u03b1), \u2203 (_x : q x), r x :=\n  sorry\n\ntheorem ball_of_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2200 (x : \u03b1), p x) (x : \u03b1) : p x := h x\n\ntheorem forall_of_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (H : \u2200 (x : \u03b1), p x)\n    (h : \u2200 (x : \u03b1), p x \u2192 q x) (x : \u03b1) : q x :=\n  h x (H x)\n\ntheorem bex_of_exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (H : \u2200 (x : \u03b1), p x) :\n    (\u2203 (x : \u03b1), q x) \u2192 \u2203 (x : \u03b1), \u2203 (_x : p x), q x :=\n  fun (\u1fb0 : \u2203 (x : \u03b1), q x) =>\n    Exists.dcases_on \u1fb0\n      fun (\u1fb0_w : \u03b1) (\u1fb0_h : q \u1fb0_w) =>\n        idRhs (\u2203 (x : \u03b1), \u2203 (_x : p x), q x) (Exists.intro \u1fb0_w (Exists.intro (H \u1fb0_w) \u1fb0_h))\n\ntheorem exists_of_bex {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u2203 (_x : p x), q x) \u2192 \u2203 (x : \u03b1), q x :=\n  sorry\n\n@[simp] theorem bex_imp_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {b : Prop} : (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2192 b \u2194 \u2200 (x : \u03b1) (h : p x), P x h \u2192 b :=\n  sorry\n\ntheorem not_bex {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u00ac\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2194 \u2200 (x : \u03b1) (h : p x), \u00acP x h :=\n  bex_imp_distrib\n\ntheorem not_ball_of_bex_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h) \u2192 \u00ac\u2200 (x : \u03b1) (h : p x), P x h :=\n  sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    [Decidable (\u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h)] [(x : \u03b1) \u2192 (h : p x) \u2192 Decidable (P x h)] :\n    (\u00ac\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h :=\n  sorry\n\ntheorem not_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u00ac\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h :=\n  decidable.not_ball\n\ntheorem ball_true_iff {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : (\u2200 (x : \u03b1), p x \u2192 True) \u2194 True :=\n  iff_true_intro fun (h : \u03b1) (hrx : p h) => trivial\n\ntheorem ball_and_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {Q : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u2200 (x : \u03b1) (h : p x), P x h \u2227 Q x h) \u2194\n        (\u2200 (x : \u03b1) (h : p x), P x h) \u2227 \u2200 (x : \u03b1) (h : p x), Q x h :=\n  iff.trans (forall_congr fun (x : \u03b1) => forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop}\n    {Q : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u2203 (h : p x), P x h \u2228 Q x h) \u2194\n        (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2228 \u2203 (x : \u03b1), \u2203 (h : p x), Q x h :=\n  iff.trans (exists_congr fun (x : \u03b1) => exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} :\n    (\u2200 (x : \u03b1), p x \u2228 q x \u2192 r x) \u2194 (\u2200 (x : \u03b1), p x \u2192 r x) \u2227 \u2200 (x : \u03b1), q x \u2192 r x :=\n  iff.trans (forall_congr fun (x : \u03b1) => or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} :\n    (\u2203 (x : \u03b1), \u2203 (_x : p x \u2228 q x), r x) \u2194\n        (\u2203 (x : \u03b1), \u2203 (_x : p x), r x) \u2228 \u2203 (x : \u03b1), \u2203 (_x : q x), r x :=\n  sorry\n\nnamespace classical\n\n\ntheorem not_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u00ac\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h :=\n  not_ball\n\nend classical\n\n\ntheorem ite_eq_iff {\u03b1 : Sort u_1} {p : Prop} [Decidable p] {a : \u03b1} {b : \u03b1} {c : \u03b1} :\n    ite p a b = c \u2194 p \u2227 a = c \u2228 \u00acp \u2227 b = c :=\n  sorry\n\n@[simp] theorem ite_eq_left_iff {\u03b1 : Sort u_1} {p : Prop} [Decidable p] {a : \u03b1} {b : \u03b1} :\n    ite p a b = a \u2194 \u00acp \u2192 b = a :=\n  sorry\n\n@[simp] theorem ite_eq_right_iff {\u03b1 : Sort u_1} {p : Prop} [Decidable p] {a : \u03b1} {b : \u03b1} :\n    ite p a b = b \u2194 p \u2192 a = b :=\n  sorry\n\n/-! ### Declarations about `nonempty` -/\n\nprotected instance has_zero.nonempty {\u03b1 : Type u} [HasZero \u03b1] : Nonempty \u03b1 := Nonempty.intro 0\n\nprotected instance has_one.nonempty {\u03b1 : Type u} [HasOne \u03b1] : Nonempty \u03b1 := Nonempty.intro 1\n\ntheorem exists_true_iff_nonempty {\u03b1 : Sort u_1} : (\u2203 (a : \u03b1), True) \u2194 Nonempty \u03b1 := sorry\n\n@[simp] theorem nonempty_Prop {p : Prop} : Nonempty p \u2194 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 {\u03b1 : Type u} : \u00acNonempty \u03b1 \u2194 \u03b1 \u2192 False := sorry\n\n@[simp] theorem nonempty_sigma {\u03b1 : Type u} {\u03b3 : \u03b1 \u2192 Type w} :\n    Nonempty (sigma fun (a : \u03b1) => \u03b3 a) \u2194 \u2203 (a : \u03b1), Nonempty (\u03b3 a) :=\n  sorry\n\n@[simp] theorem nonempty_subtype {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} :\n    Nonempty (Subtype p) \u2194 \u2203 (a : \u03b1), p a :=\n  sorry\n\n@[simp] theorem nonempty_prod {\u03b1 : Type u} {\u03b2 : Type v} :\n    Nonempty (\u03b1 \u00d7 \u03b2) \u2194 Nonempty \u03b1 \u2227 Nonempty \u03b2 :=\n  sorry\n\n@[simp] theorem nonempty_pprod {\u03b1 : Sort u} {\u03b2 : Sort v} :\n    Nonempty (PProd \u03b1 \u03b2) \u2194 Nonempty \u03b1 \u2227 Nonempty \u03b2 :=\n  sorry\n\n@[simp] theorem nonempty_sum {\u03b1 : Type u} {\u03b2 : Type v} :\n    Nonempty (\u03b1 \u2295 \u03b2) \u2194 Nonempty \u03b1 \u2228 Nonempty \u03b2 :=\n  sorry\n\n@[simp] theorem nonempty_psum {\u03b1 : Sort u} {\u03b2 : Sort v} :\n    Nonempty (psum \u03b1 \u03b2) \u2194 Nonempty \u03b1 \u2228 Nonempty \u03b2 :=\n  sorry\n\n@[simp] theorem nonempty_psigma {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} :\n    Nonempty (psigma \u03b2) \u2194 \u2203 (a : \u03b1), Nonempty (\u03b2 a) :=\n  sorry\n\n@[simp] theorem nonempty_empty : \u00acNonempty 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 {\u03b1 : Type u} : Nonempty (ulift \u03b1) \u2194 Nonempty \u03b1 := sorry\n\n@[simp] theorem nonempty_plift {\u03b1 : Sort u} : Nonempty (plift \u03b1) \u2194 Nonempty \u03b1 := sorry\n\n@[simp] theorem nonempty.forall {\u03b1 : Sort u} {p : Nonempty \u03b1 \u2192 Prop} :\n    (\u2200 (h : Nonempty \u03b1), p h) \u2194 \u2200 (a : \u03b1), p (Nonempty.intro a) :=\n  sorry\n\n@[simp] theorem nonempty.exists {\u03b1 : Sort u} {p : Nonempty \u03b1 \u2192 Prop} :\n    (\u2203 (h : Nonempty \u03b1), p h) \u2194 \u2203 (a : \u03b1), p (Nonempty.intro a) :=\n  sorry\n\ntheorem classical.nonempty_pi {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} :\n    Nonempty ((a : \u03b1) \u2192 \u03b2 a) \u2194 \u2200 (a : \u03b1), Nonempty (\u03b2 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' {\u03b1 : Sort u} [h : Nonempty \u03b1] : Inhabited \u03b1 :=\n  { default := Classical.choice h }\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def nonempty.some {\u03b1 : Sort u} (h : Nonempty \u03b1) : \u03b1 := Classical.choice h\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def classical.arbitrary (\u03b1 : Sort u) [h : Nonempty \u03b1] : \u03b1 := Classical.choice h\n\n/-- Given `f : \u03b1 \u2192 \u03b2`, if `\u03b1` is nonempty then `\u03b2` is also nonempty.\n  `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/\ntheorem nonempty.map {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) : Nonempty \u03b1 \u2192 Nonempty \u03b2 :=\n  fun (\u1fb0 : Nonempty \u03b1) =>\n    nonempty.dcases_on \u1fb0 fun (\u1fb0 : \u03b1) => idRhs (Nonempty \u03b2) (Nonempty.intro (f \u1fb0))\n\nprotected theorem nonempty.map2 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) :\n    Nonempty \u03b1 \u2192 Nonempty \u03b2 \u2192 Nonempty \u03b3 :=\n  fun (\u1fb0 : Nonempty \u03b1) (\u1fb0_1 : Nonempty \u03b2) =>\n    nonempty.dcases_on \u1fb0\n      fun (\u1fb0_1_1 : \u03b1) =>\n        nonempty.dcases_on \u1fb0_1 fun (\u1fb0 : \u03b2) => idRhs (Nonempty \u03b3) (Nonempty.intro (f \u1fb0_1_1 \u1fb0))\n\nprotected theorem nonempty.congr {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b1) :\n    Nonempty \u03b1 \u2194 Nonempty \u03b2 :=\n  { mp := nonempty.map f, mpr := nonempty.map g }\n\ntheorem nonempty.elim_to_inhabited {\u03b1 : Sort u_1} [h : Nonempty \u03b1] {p : Prop}\n    (f : Inhabited \u03b1 \u2192 p) : p :=\n  nonempty.elim h (f \u2218 Inhabited.mk)\n\nprotected instance prod.nonempty {\u03b1 : Type u_1} {\u03b2 : Type u_2} [h : Nonempty \u03b1] [h2 : Nonempty \u03b2] :\n    Nonempty (\u03b1 \u00d7 \u03b2) :=\n  nonempty.elim h fun (g : \u03b1) => nonempty.elim h2 fun (g2 : \u03b2) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (P : Prop) [Decidable P] (x : P \u2192 \u03b1)\n    (y : \u00acP \u2192 \u03b1) : f (dite P x y) = dite P (fun (h : P) => f (x h)) fun (h : \u00acP) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (P : Prop) [Decidable P] (x : \u03b1)\n    (y : \u03b1) : f (ite P x y) = ite P (f x) (f y) :=\n  apply_dite f P (fun (_x : P) => x) fun (_x : \u00acP) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop)\n    [Decidable P] (a : P \u2192 \u03b1) (b : \u00acP \u2192 \u03b1) (c : P \u2192 \u03b2) (d : \u00acP \u2192 \u03b2) :\n    f (dite P a b) (dite P c d) =\n        dite P (fun (h : P) => f (a h) (c h)) fun (h : \u00acP) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop)\n    [Decidable P] (a : \u03b1) (b : \u03b1) (c : \u03b2) (d : \u03b2) :\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 : \u00acP) => b) (fun (_x : P) => c) fun (_x : \u00acP) => d\n\n/-- A 'dite' producing a `Pi` type `\u03a0 a, \u03b2 a`, applied to a value `x : \u03b1`\nis a `dite` that applies either branch to `x`. -/\ntheorem dite_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (P : Prop) [Decidable P]\n    (f : P \u2192 (a : \u03b1) \u2192 \u03b2 a) (g : \u00acP \u2192 (a : \u03b1) \u2192 \u03b2 a) (x : \u03b1) :\n    dite P f g x = dite P (fun (h : P) => f h x) fun (h : \u00acP) => g h x :=\n  sorry\n\n/-- A 'ite' producing a `Pi` type `\u03a0 a, \u03b2 a`, applied to a value `x : \u03b1`\nis a `ite` that applies either branch to `x` -/\ntheorem ite_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (P : Prop) [Decidable P] (f : (a : \u03b1) \u2192 \u03b2 a)\n    (g : (a : \u03b1) \u2192 \u03b2 a) (x : \u03b1) : ite P f g x = ite P (f x) (g x) :=\n  dite_apply P (fun (_x : P) => f) (fun (_x : \u00acP) => 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 {\u03b1 : Sort u_1} (P : Prop) [Decidable P] (x : \u00acP \u2192 \u03b1) (y : \u00ac\u00acP \u2192 \u03b1) :\n    dite (\u00acP) 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 {\u03b1 : Sort u_1} (P : Prop) [Decidable P] (x : \u03b1) (y : \u03b1) :\n    ite (\u00acP) x y = ite P y x :=\n  dite_not P (fun (_x : \u00acP) => x) fun (_x : \u00ac\u00acP) => y\n\ntheorem ite_and {\u03b1 : Sort u_1} {p : Prop} {q : Prop} [Decidable p] [Decidable q] {x : \u03b1} {y : \u03b1} :\n    ite (p \u2227 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 \u03b1`: free monoid over alphabet `\u03b1`; defined as a synonym for `list \u03b1`\n  with multiplication given by `(++)`.\n* `free_monoid.of`: embedding `\u03b1 \u2192 free_monoid \u03b1` sending each element `x` to `[x]`;\n* `free_monoid.lift`: natural equivalence between `\u03b1 \u2192 M` and `free_monoid \u03b1 \u2192* M`\n* `free_monoid.map`: embedding of `\u03b1 \u2192 \u03b2` into `free_monoid \u03b1 \u2192* free_monoid \u03b2` given by `list.map`.\n-/\n\n/-- Free monoid over a given alphabet. -/\ndef free_add_monoid (\u03b1 : Type u_1) := List \u03b1\n\nnamespace free_monoid\n\n\nprotected instance Mathlib.free_add_monoid.add_monoid {\u03b1 : Type u_1} :\n    add_monoid (free_add_monoid \u03b1) :=\n  add_monoid.mk (fun (x y : free_add_monoid \u03b1) => x ++ y) sorry [] sorry sorry\n\nprotected instance inhabited {\u03b1 : Type u_1} : Inhabited (free_monoid \u03b1) := { default := 1 }\n\ntheorem one_def {\u03b1 : Type u_1} : 1 = [] := rfl\n\ntheorem Mathlib.free_add_monoid.add_def {\u03b1 : Type u_1} (xs : List \u03b1) (ys : List \u03b1) :\n    xs + ys = xs ++ ys :=\n  rfl\n\n/-- Embeds an element of `\u03b1` into `free_monoid \u03b1` as a singleton list. -/\ndef of {\u03b1 : Type u_1} (x : \u03b1) : free_monoid \u03b1 := [x]\n\ntheorem of_def {\u03b1 : Type u_1} (x : \u03b1) : of x = [x] := rfl\n\ntheorem of_injective {\u03b1 : Type u_1} : function.injective of :=\n  fun (a b : \u03b1) => 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 {\u03b1 : Type u_1} {C : free_monoid \u03b1 \u2192 Sort u_2} (xs : free_monoid \u03b1) (h0 : C 1)\n    (ih : (x : \u03b1) \u2192 (xs : free_monoid \u03b1) \u2192 C xs \u2192 C (of x * xs)) : C xs :=\n  list.rec_on xs h0 ih\n\ntheorem hom_eq {\u03b1 : Type u_1} {M : Type u_4} [monoid M] {f : free_monoid \u03b1 \u2192* M}\n    {g : free_monoid \u03b1 \u2192* M} (h : \u2200 (x : \u03b1), coe_fn f (of x) = coe_fn g (of x)) : f = g :=\n  sorry\n\n/-- Equivalence between maps `\u03b1 \u2192 M` and monoid homomorphisms `free_monoid \u03b1 \u2192* M`. -/\ndef lift {\u03b1 : Type u_1} {M : Type u_4} [monoid M] : (\u03b1 \u2192 M) \u2243 (free_monoid \u03b1 \u2192* M) :=\n  equiv.mk\n    (fun (f : \u03b1 \u2192 M) =>\n      monoid_hom.mk (fun (l : free_monoid \u03b1) => list.prod (list.map f l)) sorry sorry)\n    (fun (f : free_monoid \u03b1 \u2192* M) (x : \u03b1) => coe_fn f (of x)) sorry sorry\n\n@[simp] theorem Mathlib.free_add_monoid.lift_symm_apply {\u03b1 : Type u_1} {M : Type u_4} [add_monoid M]\n    (f : free_add_monoid \u03b1 \u2192+ M) :\n    coe_fn (equiv.symm free_add_monoid.lift) f = \u21d1f \u2218 free_add_monoid.of :=\n  rfl\n\ntheorem lift_apply {\u03b1 : Type u_1} {M : Type u_4} [monoid M] (f : \u03b1 \u2192 M) (l : free_monoid \u03b1) :\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 {\u03b1 : Type u_1} {M : Type u_4} [add_monoid M]\n    (f : \u03b1 \u2192 M) : \u21d1(coe_fn free_add_monoid.lift f) \u2218 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 {\u03b1 : Type u_1} {M : Type u_4} [add_monoid M]\n    (f : \u03b1 \u2192 M) (x : \u03b1) : 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 {\u03b1 : Type u_1} {M : Type u_4} [monoid M] (f : free_monoid \u03b1 \u2192* M) :\n    coe_fn lift (\u21d1f \u2218 of) = f :=\n  equiv.apply_symm_apply lift f\n\ntheorem comp_lift {\u03b1 : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M \u2192* N)\n    (f : \u03b1 \u2192 M) : monoid_hom.comp g (coe_fn lift f) = coe_fn lift (\u21d1g \u2218 f) :=\n  sorry\n\ntheorem hom_map_lift {\u03b1 : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M \u2192* N)\n    (f : \u03b1 \u2192 M) (x : free_monoid \u03b1) :\n    coe_fn g (coe_fn (coe_fn lift f) x) = coe_fn (coe_fn lift (\u21d1g \u2218 f)) x :=\n  iff.mp monoid_hom.ext_iff (comp_lift g f) x\n\n/-- The unique monoid homomorphism `free_monoid \u03b1 \u2192* free_monoid \u03b2` that sends\neach `of x` to `of (f x)`. -/\ndef map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : free_monoid \u03b1 \u2192* free_monoid \u03b2 :=\n  monoid_hom.mk (list.map f) sorry sorry\n\n@[simp] theorem map_of {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (x : \u03b1) :\n    coe_fn (map f) (of x) = of (f x) :=\n  rfl\n\ntheorem Mathlib.free_add_monoid.lift_of_comp_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) :\n    (coe_fn free_add_monoid.lift fun (x : \u03b1) => free_add_monoid.of (f x)) = free_add_monoid.map f :=\n  free_add_monoid.hom_eq fun (x : \u03b1) => rfl\n\ntheorem map_comp {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (g : \u03b2 \u2192 \u03b3) (f : \u03b1 \u2192 \u03b2) :\n    map (g \u2218 f) = monoid_hom.comp (map g) (map f) :=\n  hom_eq fun (x : \u03b1) => rfl\n\nprotected instance star_monoid {\u03b1 : Type u_1} : star_monoid (free_monoid \u03b1) :=\n  star_monoid.mk list.reverse_append\n\n@[simp] theorem star_of {\u03b1 : Type u_1} (x : \u03b1) : 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 {\u03b1 : 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' (\u03b1 : Type u) : Bool \u2192 Type u\nwhere\n| atom : \u03b1 \u2192 lists' \u03b1 false\n| nil : lists' \u03b1 tt\n| cons' : {b : Bool} \u2192 lists' \u03b1 b \u2192 lists' \u03b1 tt \u2192 lists' \u03b1 tt\n\ndef lists (\u03b1 : Type u_1) :=\n  sigma fun (b : Bool) => lists' \u03b1 b\n\nnamespace lists'\n\n\nprotected instance inhabited {\u03b1 : Type u_1} [Inhabited \u03b1] (b : Bool) : Inhabited (lists' \u03b1 b) :=\n  sorry\n\ndef cons {\u03b1 : Type u_1} : lists \u03b1 \u2192 lists' \u03b1 tt \u2192 lists' \u03b1 tt :=\n  sorry\n\n@[simp] def to_list {\u03b1 : Type u_1} {b : Bool} : lists' \u03b1 b \u2192 List (lists \u03b1) :=\n  sorry\n\n@[simp] theorem to_list_cons {\u03b1 : Type u_1} (a : lists \u03b1) (l : lists' \u03b1 tt) : to_list (cons a l) = a :: to_list l := sorry\n\n@[simp] def of_list {\u03b1 : Type u_1} : List (lists \u03b1) \u2192 lists' \u03b1 tt :=\n  sorry\n\n@[simp] theorem to_of_list {\u03b1 : Type u_1} (l : List (lists \u03b1)) : to_list (of_list l) = l := sorry\n\n@[simp] theorem of_to_list {\u03b1 : Type u_1} (l : lists' \u03b1 tt) : of_list (to_list l) = l := sorry\n\nend lists'\n\n\ndef lists'.subset {\u03b1 : Type u_1} : lists' \u03b1 tt \u2192 lists' \u03b1 tt \u2192 Prop :=\n  fun (\u1fb0 \u1fb0_1 : lists' \u03b1 tt) =>\n    lists.equiv._mut_\n      ((fun (idx : psigma fun (\u1fb0 : lists' \u03b1 tt) => psigma fun (\u1fb0 : lists' \u03b1 tt) => Unit) => psum.inr idx)\n        ((fun (\u1fb0 \u1fb0_2 : lists' \u03b1 tt) => psigma.mk \u1fb0 (psigma.mk \u1fb0_2 Unit.unit)) \u1fb0 \u1fb0_1))\n\nnamespace lists'\n\n\nprotected instance has_subset {\u03b1 : Type u_1} : has_subset (lists' \u03b1 tt) :=\n  has_subset.mk subset\n\nprotected instance has_mem {\u03b1 : Type u_1} {b : Bool} : has_mem (lists \u03b1) (lists' \u03b1 b) :=\n  has_mem.mk fun (a : lists \u03b1) (l : lists' \u03b1 b) => \u2203 (a' : lists \u03b1), \u2203 (H : a' \u2208 to_list l), lists.equiv a a'\n\ntheorem mem_def {\u03b1 : Type u_1} {b : Bool} {a : lists \u03b1} {l : lists' \u03b1 b} : a \u2208 l \u2194 \u2203 (a' : lists \u03b1), \u2203 (H : a' \u2208 to_list l), lists.equiv a a' :=\n  iff.rfl\n\n@[simp] theorem mem_cons {\u03b1 : Type u_1} {a : lists \u03b1} {y : lists \u03b1} {l : lists' \u03b1 tt} : a \u2208 cons y l \u2194 lists.equiv a y \u2228 a \u2208 l := sorry\n\ntheorem cons_subset {\u03b1 : Type u_1} {a : lists \u03b1} {l\u2081 : lists' \u03b1 tt} {l\u2082 : lists' \u03b1 tt} : cons a l\u2081 \u2286 l\u2082 \u2194 a \u2208 l\u2082 \u2227 l\u2081 \u2286 l\u2082 := sorry\n\ntheorem of_list_subset {\u03b1 : Type u_1} {l\u2081 : List (lists \u03b1)} {l\u2082 : List (lists \u03b1)} (h : l\u2081 \u2286 l\u2082) : of_list l\u2081 \u2286 of_list l\u2082 := sorry\n\ntheorem subset.refl {\u03b1 : Type u_1} {l : lists' \u03b1 tt} : l \u2286 l :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (l \u2286 l)) (Eq.symm (of_to_list l)))) (of_list_subset (list.subset.refl (to_list l)))\n\ntheorem subset_nil {\u03b1 : Type u_1} {l : lists' \u03b1 tt} : l \u2286 nil \u2192 l = nil := sorry\n\ntheorem mem_of_subset' {\u03b1 : Type u_1} {a : lists \u03b1} {l\u2081 : lists' \u03b1 tt} {l\u2082 : lists' \u03b1 tt} (s : l\u2081 \u2286 l\u2082) (h : a \u2208 to_list l\u2081) : a \u2208 l\u2082 := sorry\n\ntheorem subset_def {\u03b1 : Type u_1} {l\u2081 : lists' \u03b1 tt} {l\u2082 : lists' \u03b1 tt} : l\u2081 \u2286 l\u2082 \u2194 \u2200 (a : lists \u03b1), a \u2208 to_list l\u2081 \u2192 a \u2208 l\u2082 := sorry\n\nend lists'\n\n\nnamespace lists\n\n\ndef atom {\u03b1 : Type u_1} (a : \u03b1) : lists \u03b1 :=\n  sigma.mk false (lists'.atom a)\n\ndef of' {\u03b1 : Type u_1} (l : lists' \u03b1 tt) : lists \u03b1 :=\n  sigma.mk tt l\n\n@[simp] def to_list {\u03b1 : Type u_1} : lists \u03b1 \u2192 List (lists \u03b1) :=\n  sorry\n\ndef is_list {\u03b1 : Type u_1} (l : lists \u03b1) :=\n  \u21a5(sigma.fst l)\n\ndef of_list {\u03b1 : Type u_1} (l : List (lists \u03b1)) : lists \u03b1 :=\n  of' (lists'.of_list l)\n\ntheorem is_list_to_list {\u03b1 : Type u_1} (l : List (lists \u03b1)) : is_list (of_list l) :=\n  Eq.refl (sigma.fst (of_list l))\n\ntheorem to_of_list {\u03b1 : Type u_1} (l : List (lists \u03b1)) : to_list (of_list l) = l := sorry\n\ntheorem of_to_list {\u03b1 : Type u_1} {l : lists \u03b1} : is_list l \u2192 of_list (to_list l) = l := sorry\n\nprotected instance inhabited {\u03b1 : Type u_1} : Inhabited (lists \u03b1) :=\n  { default := of' lists'.nil }\n\nprotected instance decidable_eq {\u03b1 : Type u_1} [DecidableEq \u03b1] : DecidableEq (lists \u03b1) :=\n  eq.mpr sorry fun (a b : sigma fun (b : Bool) => lists' \u03b1 b) => sigma.decidable_eq a b\n\nprotected instance has_sizeof {\u03b1 : Type u_1} [SizeOf \u03b1] : SizeOf (lists \u03b1) :=\n  eq.mpr sorry (sigma.has_sizeof Bool fun (b : Bool) => lists' \u03b1 b)\n\ndef induction_mut {\u03b1 : Type u_1} (C : lists \u03b1 \u2192 Sort u_2) (D : lists' \u03b1 tt \u2192 Sort u_3) (C0 : (a : \u03b1) \u2192 C (atom a)) (C1 : (l : lists' \u03b1 tt) \u2192 D l \u2192 C (of' l)) (D0 : D lists'.nil) (D1 : (a : lists \u03b1) \u2192 (l : lists' \u03b1 tt) \u2192 C a \u2192 D l \u2192 D (lists'.cons a l)) : PProd ((l : lists \u03b1) \u2192 C l) ((l : lists' \u03b1 tt) \u2192 D l) :=\n  { fst := fun (_x : lists \u03b1) => sorry,\n    snd :=\n      fun (l : lists' \u03b1 tt) =>\n        pprod.snd\n          ((fun (b : Bool) (l : lists' \u03b1 b) =>\n              lists'.rec (fun (a : \u03b1) => { fst := C0 a, snd := PUnit.unit }) { fst := C1 lists'.nil D0, snd := D0 }\n                (fun {b : Bool} (a : lists' \u03b1 b) (l : lists' \u03b1 tt) (IH\u2081 : PProd (C (sigma.mk b a)) sorry)\n                  (IH\u2082 : PProd (C (sigma.mk tt l)) sorry) =>\n                  { fst := C1 (lists'.cons' a l) (D1 (sigma.mk b a) l (pprod.fst IH\u2081) (pprod.snd IH\u2082)),\n                    snd := D1 (sigma.mk b a) l (pprod.fst IH\u2081) (pprod.snd IH\u2082) })\n                l)\n            tt l) }\n\ndef mem {\u03b1 : Type u_1} (a : lists \u03b1) : lists \u03b1 \u2192 Prop :=\n  sorry\n\nprotected instance has_mem {\u03b1 : Type u_1} : has_mem (lists \u03b1) (lists \u03b1) :=\n  has_mem.mk mem\n\ntheorem is_list_of_mem {\u03b1 : Type u_1} {a : lists \u03b1} {l : lists \u03b1} : a \u2208 l \u2192 is_list l := sorry\n\ntheorem equiv.antisymm_iff {\u03b1 : Type u_1} {l\u2081 : lists' \u03b1 tt} {l\u2082 : lists' \u03b1 tt} : equiv (of' l\u2081) (of' l\u2082) \u2194 l\u2081 \u2286 l\u2082 \u2227 l\u2082 \u2286 l\u2081 := sorry\n\ntheorem equiv_atom {\u03b1 : Type u_1} {a : \u03b1} {l : lists \u03b1} : equiv (atom a) l \u2194 atom a = l := sorry\n\ntheorem equiv.symm {\u03b1 : Type u_1} {l\u2081 : lists \u03b1} {l\u2082 : lists \u03b1} (h : equiv l\u2081 l\u2082) : equiv l\u2082 l\u2081 := sorry\n\ntheorem equiv.trans {\u03b1 : Type u_1} {l\u2081 : lists \u03b1} {l\u2082 : lists \u03b1} {l\u2083 : lists \u03b1} : equiv l\u2081 l\u2082 \u2192 equiv l\u2082 l\u2083 \u2192 equiv l\u2081 l\u2083 := sorry\n\nprotected instance setoid {\u03b1 : Type u_1} : setoid (lists \u03b1) :=\n  setoid.mk equiv sorry\n\n@[simp] def equiv.decidable_meas {\u03b1 : Type u_1} : psum (psigma fun (l\u2081 : lists \u03b1) => lists \u03b1)\n    (psum (psigma fun (l\u2081 : lists' \u03b1 tt) => lists' \u03b1 tt) (psigma fun (a : lists \u03b1) => lists' \u03b1 tt)) \u2192\n  \u2115 :=\n  sorry\n\ntheorem sizeof_pos {\u03b1 : Type u_1} {b : Bool} (l : lists' \u03b1 b) : 0 < sizeof l := sorry\n\ntheorem lt_sizeof_cons' {\u03b1 : Type u_1} {b : Bool} (a : lists' \u03b1 b) (l : lists' \u03b1 tt) : sizeof (sigma.mk b a) < sizeof (lists'.cons' a l) := sorry\n\ninstance mem.decidable {\u03b1 : Type u_1} [DecidableEq \u03b1] (a : lists \u03b1) (l : lists' \u03b1 tt) : Decidable (a \u2208 l) :=\n  sorry\n\nend lists\n\n\nnamespace lists'\n\n\ntheorem mem_equiv_left {\u03b1 : Type u_1} {l : lists' \u03b1 tt} {a : lists \u03b1} {a' : lists \u03b1} : lists.equiv a a' \u2192 (a \u2208 l \u2194 a' \u2208 l) := sorry\n\ntheorem mem_of_subset {\u03b1 : Type u_1} {a : lists \u03b1} {l\u2081 : lists' \u03b1 tt} {l\u2082 : lists' \u03b1 tt} (s : l\u2081 \u2286 l\u2082) : a \u2208 l\u2081 \u2192 a \u2208 l\u2082 := sorry\n\ntheorem subset.trans {\u03b1 : Type u_1} {l\u2081 : lists' \u03b1 tt} {l\u2082 : lists' \u03b1 tt} {l\u2083 : lists' \u03b1 tt} (h\u2081 : l\u2081 \u2286 l\u2082) (h\u2082 : l\u2082 \u2286 l\u2083) : l\u2081 \u2286 l\u2083 :=\n  iff.mpr subset_def fun (a\u2081 : lists \u03b1) (m\u2081 : a\u2081 \u2208 to_list l\u2081) => mem_of_subset h\u2082 (mem_of_subset' h\u2081 m\u2081)\n\nend lists'\n\n\ndef finsets (\u03b1 : Type u_1) :=\n  quotient lists.setoid\n\nnamespace finsets\n\n\nprotected instance has_emptyc {\u03b1 : Type u_1} : has_emptyc (finsets \u03b1) :=\n  has_emptyc.mk (quotient.mk (lists.of' lists'.nil))\n\nprotected instance inhabited {\u03b1 : Type u_1} : Inhabited (finsets \u03b1) :=\n  { default := \u2205 }\n\nprotected instance decidable_eq {\u03b1 : Type u_1} [DecidableEq \u03b1] : DecidableEq (finsets \u03b1) :=\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": "import tactic --hide\n\n/-Lemma\nThis is getting silly now!\n-/\nlemma lemma_9 (P Q R : Prop) : ((Q \u2192 P) \u2192 P) \u2192 (Q \u2192 R) \u2192 (R \u2192 P) \u2192 P :=\nbegin\n  intros h1 h2 h3,\n  apply h1,\n  intro hQ,\n  apply h3,\n  apply h2,\n  exact hQ,\n\n\n\nend", "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/logic_1/logic11.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.07477004187710674, "lm_q1q2_score": 0.0315906903257245}}
{"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\u1d50\u1d52\u1d56` for the monoidal opposite of a monoidal category `C`.\n-/\n\n\nuniverses v\u2081 v\u2082 u\u2081 u\u2082\n\nvariables {C : Type u\u2081}\n\nnamespace category_theory\n\nopen category_theory.monoidal_category\n\n/-- A type synonym for the monoidal opposite. Use the notation `C\u1d39\u1d52\u1d56`. -/\n@[nolint has_inhabited_instance]\ndef monoidal_opposite (C : Type u\u2081) := C\n\nnamespace monoidal_opposite\n\nnotation C `\u1d39\u1d52\u1d56`:std.prec.max_plus := monoidal_opposite C\n\n/-- Think of an object of `C` as an object of `C\u1d39\u1d52\u1d56`. -/\n@[pp_nodot]\ndef mop (X : C) : C\u1d39\u1d52\u1d56 := X\n\n/-- Think of an object of `C\u1d39\u1d52\u1d56` as an object of `C`. -/\n@[pp_nodot]\ndef unmop (X : C\u1d39\u1d52\u1d56) : C := X\n\nlemma op_injective : function.injective (mop : C \u2192 C\u1d39\u1d52\u1d56) := \u03bb _ _, id\nlemma unop_injective : function.injective (unmop : C\u1d39\u1d52\u1d56 \u2192 C) := \u03bb _ _, id\n\n@[simp] lemma op_inj_iff (x y : C) : mop x = mop y \u2194 x = y := iff.rfl\n@[simp] \n\nattribute [irreducible] monoidal_opposite\n\n@[simp] lemma mop_unmop (X : C\u1d39\u1d52\u1d56) : 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\u2081} C] : category C\u1d39\u1d52\u1d56 :=\n{ hom := \u03bb X Y, unmop X \u27f6 unmop Y,\n  id := \u03bb X, \ud835\udfd9 (unmop X),\n  comp := \u03bb X Y Z f g, f \u226b g, }\n\nend monoidal_opposite\n\nend category_theory\n\nopen category_theory\nopen category_theory.monoidal_opposite\n\nvariables [category.{v\u2081} C]\n\n/-- The monoidal opposite of a morphism `f : X \u27f6 Y` is just `f`, thought of as `mop X \u27f6 mop Y`. -/\ndef quiver.hom.mop {X Y : C} (f : X \u27f6 Y) : @quiver.hom C\u1d39\u1d52\u1d56 _ (mop X) (mop Y) := f\n/-- We can think of a morphism `f : mop X \u27f6 mop Y` as a morphism `X \u27f6 Y`. -/\ndef quiver.hom.unmop {X Y : C\u1d39\u1d52\u1d56} (f : X \u27f6 Y) : unmop X \u27f6 unmop Y := f\n\nnamespace category_theory\n\nlemma mop_inj {X Y : C} :\n  function.injective (quiver.hom.mop : (X \u27f6 Y) \u2192 (mop X \u27f6 mop Y)) :=\n\u03bb _ _ H, congr_arg quiver.hom.unmop H\n\nlemma unmop_inj {X Y : C\u1d39\u1d52\u1d56} :\n  function.injective (quiver.hom.unmop : (X \u27f6 Y) \u2192 (unmop X \u27f6 unmop Y)) :=\n\u03bb _ _ H, congr_arg quiver.hom.mop H\n\n@[simp] lemma unmop_mop {X Y : C} {f : X \u27f6 Y} : f.mop.unmop = f := rfl\n@[simp] lemma mop_unmop {X Y : C\u1d39\u1d52\u1d56} {f : X \u27f6 Y} : f.unmop.mop = f := rfl\n\n@[simp] lemma mop_comp {X Y Z : C} {f : X \u27f6 Y} {g : Y \u27f6 Z} :\n  (f \u226b g).mop = f.mop \u226b g.mop := rfl\n@[simp] lemma mop_id {X : C} : (\ud835\udfd9 X).mop = \ud835\udfd9 (mop X) := rfl\n\n@[simp] lemma unmop_comp {X Y Z : C\u1d39\u1d52\u1d56} {f : X \u27f6 Y} {g : Y \u27f6 Z} :\n  (f \u226b g).unmop = f.unmop \u226b g.unmop := rfl\n@[simp] lemma unmop_id {X : C\u1d39\u1d52\u1d56} : (\ud835\udfd9 X).unmop = \ud835\udfd9 (unmop X) := rfl\n\n@[simp] lemma unmop_id_mop {X : C} : (\ud835\udfd9 (mop X)).unmop = \ud835\udfd9 X := rfl\n@[simp] lemma mop_id_unmop {X : C\u1d39\u1d52\u1d56} : (\ud835\udfd9 (unmop X)).mop = \ud835\udfd9 X := rfl\n\nnamespace iso\n\nvariables {X Y : C}\n\n/-- An isomorphism in `C` gives an isomorphism in `C\u1d39\u1d52\u1d56`. -/\n@[simps]\ndef mop (f : X \u2245 Y) : mop X \u2245 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\u2081} C]\n\nopen opposite monoidal_category\n\ninstance monoidal_category_op : monoidal_category C\u1d52\u1d56 :=\n{ tensor_obj := \u03bb X Y, op (unop X \u2297 unop Y),\n  tensor_hom := \u03bb X\u2081 Y\u2081 X\u2082 Y\u2082 f g, (f.unop \u2297 g.unop).op,\n  tensor_unit := op (\ud835\udfd9_ C),\n  associator := \u03bb X Y Z, (\u03b1_ (unop X) (unop Y) (unop Z)).symm.op,\n  left_unitor := \u03bb X, (\u03bb_ (unop X)).symm.op,\n  right_unitor := \u03bb X, (\u03c1_ (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\u1d52\u1d56) : X \u2297 Y = op (unop X \u2297 unop Y) := rfl\nlemma op_tensor_unit : (\ud835\udfd9_ C\u1d52\u1d56) = op (\ud835\udfd9_ C) := rfl\n\ninstance monoidal_category_mop : monoidal_category C\u1d39\u1d52\u1d56 :=\n{ tensor_obj := \u03bb X Y, mop (unmop Y \u2297 unmop X),\n  tensor_hom := \u03bb X\u2081 Y\u2081 X\u2082 Y\u2082 f g, (g.unmop \u2297 f.unmop).mop,\n  tensor_unit := mop (\ud835\udfd9_ C),\n  associator := \u03bb X Y Z, (\u03b1_ (unmop Z) (unmop Y) (unmop X)).symm.mop,\n  left_unitor := \u03bb X, (\u03c1_ (unmop X)).mop,\n  right_unitor := \u03bb X, (\u03bb_ (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\u1d39\u1d52\u1d56) : X \u2297 Y = mop (unmop Y \u2297 unmop X) := rfl\nlemma mop_tensor_unit : (\ud835\udfd9_ C\u1d39\u1d52\u1d56) = mop (\ud835\udfd9_ 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\u2080 u\u2081 v\u2080 v\u2081 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 \u03b1` 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\u2081 \u2192 Type\nu\u2082`, this class convert between instantiations, from\n`M.{u} : Type u\u2081 \u2192 Type u\u2082` to `M.{v} : Type v\u2081 \u2192 Type v\u2082` and back -/\nclass uliftable (f : Type u\u2080 \u2192 Type u\u2081) (g : Type v\u2080 \u2192 Type v\u2081) where\n  congr : {\u03b1 : Type u\u2080} \u2192 {\u03b2 : Type v\u2080} \u2192 \u03b1 \u2243 \u03b2 \u2192 f \u03b1 \u2243 g \u03b2\n\nnamespace uliftable\n\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} \u03b1` and lifts it to M.{max u v} (ulift.{v} \u03b1) -/\ndef up {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g] {\u03b1 : Type u\u2080} :\n    f \u03b1 \u2192 g (ulift \u03b1) :=\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} \u03b1)` and lowers it to `M.{u} \u03b1` -/\ndef down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g] {\u03b1 : Type u\u2080} :\n    g (ulift \u03b1) \u2192 f \u03b1 :=\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\u2080 \u2192 Type v\u2081) (G : Type (max v\u2080 u\u2080) \u2192 Type u\u2081) [uliftable F G] [Monad G]\n    {\u03b1 : Type v\u2080} {\u03b2 : Type (max v\u2080 u\u2080)} (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n  up x >>= f \u2218 ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type v\u2080 \u2192 Type v\u2081} [L : uliftable G F]\n    [Monad F] {\u03b1 : Type (max u\u2080 v\u2080)} {\u03b2 : Type v\u2080} (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n  down (x >>= up \u2218 f)\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u\u2080 \u2192 Type u\u2081} {G : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [inst : uliftable F G]\n    [Functor G] {\u03b1 : Type u\u2080} {\u03b2 : Type (max u\u2080 v\u2080)} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\n  (f \u2218 ulift.down) <$> up x\n\n/-- map function that moves down universes -/\ndef down_map {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type \u2192 Type v\u2081} [inst : uliftable G F]\n    [Functor F] {\u03b1 : Type (max u\u2080 v\u2080)} {\u03b2 : Type} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\n  down ((ulift.up \u2218 f) <$> x)\n\n@[simp] theorem up_down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n    {\u03b1 : Type u\u2080} (x : g (ulift \u03b1)) : 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\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g]\n    {\u03b1 : Type u\u2080} (x : f \u03b1) : 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 (\u03b1 : Type u_1) (\u03b2 : Type u_2) (F : \u03b1 \u2243 \u03b2) => F\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {s : Type u\u2080} {s' : Type u\u2081} {m : Type u\u2080 \u2192 Type v\u2080} {m' : Type u\u2081 \u2192 Type v\u2081}\n    [uliftable m m'] (F : s \u2243 s') : uliftable (state_t s m) (state_t s' m') :=\n  uliftable.mk\n    fun (\u03b1 : Type u\u2080) (\u03b2 : Type u\u2081) (G : \u03b1 \u2243 \u03b2) =>\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 \u2192 Type u_2}\n    {m' : Type (max u_1 u_3) \u2192 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 \u2192 Type u_3}\n    {m' : Type u_2 \u2192 Type u_4} [uliftable m m'] (F : s \u2243 s') :\n    uliftable (reader_t s m) (reader_t s' m') :=\n  uliftable.mk\n    fun (\u03b1 : Type u_1) (\u03b2 : Type u_2) (G : \u03b1 \u2243 \u03b2) =>\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 \u2192 Type u_2}\n    {m' : Type (max u_1 u_3) \u2192 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 \u2192 Type u_3}\n    {m' : Type u_2 \u2192 Type u_4} [uliftable m m'] (F : r \u2243 r') :\n    uliftable (cont_t r m) (cont_t r' m') :=\n  uliftable.mk fun (\u03b1 : Type u_1) (\u03b2 : 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 \u2192 Type u_2}\n    {m' : Type (max u_1 u_3) \u2192 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) \u2192 Type u_5} {m' : Type (max u_3 u_4) \u2192 Type u_6} [uliftable m m']\n    (F : w \u2243 w') : uliftable (writer_t w m) (writer_t w' m') :=\n  uliftable.mk\n    fun (\u03b1 : Type (max u_1 u_2)) (\u03b2 : Type (max u_3 u_4)) (G : \u03b1 \u2243 \u03b2) =>\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) \u2192 Type u_3}\n    {m' : Type (max (max u_1 u_2) u_4) \u2192 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": "import Lean\nopen Lean Widget\n\n/-!\n# The user-widgets system\n\nProving and programming are inherently interactive tasks. Lots of mathematical objects and data\nstructures are visual in nature. *User widgets* let you associate custom interactive UIs with\nsections of a Lean document. User widgets are rendered in the Lean infoview.\n\n![Rubik's cube](../images/widgets_rubiks.png)\n\n## Trying it out\n\nTo try it out, simply type in the following code and place your cursor over the `#widget` command.\n-/\n\n@[widget]\ndef helloWidget : UserWidgetDefinition where\n  name := \"Hello\"\n  javascript := \"\n    import * as React from 'react';\n    export default function(props) {\n      const name = props.name || 'world'\n      return React.createElement('p', {}, name + '!')\n    }\"\n\n#widget helloWidget .null\n\n/-!\nIf you want to dive into a full sample right away, check out\n[`RubiksCube`](https://github.com/leanprover/lean4-samples/blob/main/RubiksCube/).\nBelow, we'll explain the system piece by piece.\n\n\u26a0\ufe0f WARNING: All of the user widget APIs are **unstable** and subject to breaking changes.\n\n## Widget sources and instances\n\nA *widget source* is a valid JavaScript [ESModule](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\nwhich exports a [React component](https://reactjs.org/docs/components-and-props.html). To access\nReact, the module must use `import * as React from 'react'`. Our first example of a widget source\nis of course the value of `helloWidget.javascript`.\n\nWe can register a widget source with the `@[widget]` attribute, giving it a friendlier name\nin the `name` field. This is bundled together in a `UserWidgetDefinition`.\n\nA *widget instance* is then the identifier of a `UserWidgetDefinition` (so `` `helloWidget ``,\nnot `\"Hello\"`) associated with a range of positions in the Lean source code. Widget instances\nare stored in the *infotree* in the same manner as other information about the source file\nsuch as the type of every expression. In our example, the `#widget` command stores a widget instance\nwith the entire line as its range. We can think of a widget instance as an instruction for the\ninfoview: \"when the user places their cursor here, please render the following widget\".\n\nEvery widget instance also contains a `props : Json` value. This value is passed as an argument\nto the React component. In our first invocation of `#widget`, we set it to `.null`. Try out what\nhappens when you type in:\n-/\n\n#widget helloWidget (Json.mkObj [(\"name\", \"<your name here>\")])\n\n/-!\n\ud83d\udca1 NOTE: The RPC system presented below does not depend on JavaScript. However the primary use case\nis the web-based infoview in VSCode.\n\n## Querying the Lean server\n\nBesides enabling us to create cool client-side visualizations, user widgets come with the ability\nto communicate with the Lean server. Thanks to this, they have the same metaprogramming capabilities\nas custom elaborators or the tactic framework. To see this in action, let's implement a `#check`\ncommand as a web input form. This example assumes some familiarity with React.\n\nThe first thing we'll need is to create an *RPC method*. Meaning \"Remote Procedure Call\", this\nis basically a Lean function callable from widget code (possibly remotely over the internet).\nOur method will take in the `name : Name` of a constant in the environment and return its type.\nBy convention, we represent the input data as a `structure`. Since it will be sent over from JavaScript,\nwe need `FromJson` and `ToJson`. We'll see below why the position field is needed.\n-/\n\nstructure GetTypeParams where\n  /-- Name of a constant to get the type of. -/\n  name : Name\n  /-- Position of our widget instance in the Lean file. -/\n  pos : Lsp.Position\n  deriving FromJson, ToJson\n\n/-!\nAfter its arguments, we define the `getType` method. Every RPC method executes in the `RequestM`\nmonad and must return a `RequestTask \u03b1` where `\u03b1` is its \"actual\" return type. The `Task` is so\nthat requests can be handled concurrently. A first guess for `\u03b1` might be `Expr`. However,\nexpressions in general can be large objects which depend on an `Environment` and `LocalContext`.\nThus we cannot directly serialize an `Expr` and send it to the widget. Instead, there are two\noptions:\n- One is to send a *reference* which points to an object residing on the server. From JavaScript's\n  point of view, references are entirely opaque, but they can be sent back to other RPC methods for\n  further processing.\n- Two is to pretty-print the expression and send its textual representation called `CodeWithInfos`.\n  This representation contains extra data which the infoview uses for interactivity. We take this\n  strategy here.\n\nRPC methods execute in the context of a file, but not any particular `Environment` so they don't\nknow about the available `def`initions and `theorem`s. Thus, we need to pass in a position at which\nwe want to use the local `Environment`. This is why we store it in `GetTypeParams`. The `withWaitFindSnapAtPos`\nmethod launches a concurrent computation whose job is to find such an `Environment` and a bit\nmore information for us, in the form of a `snap : Snapshot`. With this in hand, we can call\n`MetaM` procedures to find out the type of `name` and pretty-print it.\n-/\n\nopen Server RequestM in\n@[server_rpc_method]\ndef getType (params : GetTypeParams) : RequestM (RequestTask CodeWithInfos) :=\n  withWaitFindSnapAtPos params.pos fun snap => do\n    runTermElabM snap do\n      let name \u2190 resolveGlobalConstNoOverloadCore params.name\n      let some c \u2190 Meta.getConst? name\n        | throwThe RequestError \u27e8.invalidParams, s!\"no constant named '{name}'\"\u27e9\n      Widget.ppExprTagged c.type\n\n/-!\n## Using infoview components\n\nNow that we have all we need on the server side, let's write the widget source. By importing\n`@leanprover/infoview`, widgets can render UI components used to implement the infoview itself.\nFor example, the `<InteractiveCode>` component displays expressions with `term : type` tooltips\nas seen in the goal view. We will use it to implement our custom `#check` display.\n\n\u26a0\ufe0f WARNING: Like the other widget APIs, the infoview JS API is **unstable** and subject to breaking changes.\n\nThe code below demonstrates useful parts of the API. To make RPC method calls, we use the `RpcContext`.\nThe `useAsync` helper packs the results of a call into an `AsyncState` structure which indicates\nwhether the call has resolved successfully, has returned an error, or is still in-flight. Based\non this we either display an `InteractiveCode` with the type, `mapRpcError` the error in order\nto turn it into a readable message, or show a `Loading..` message, respectively.\n-/\n\n@[widget]\ndef checkWidget : UserWidgetDefinition where\n  name := \"#check as a service\"\n  javascript := \"\nimport * as React from 'react';\nconst e = React.createElement;\nimport { RpcContext, InteractiveCode, useAsync, mapRpcError } from '@leanprover/infoview';\n\nexport default function(props) {\n  const rs = React.useContext(RpcContext)\n  const [name, setName] = React.useState('getType')\n\n  const st = useAsync(() =>\n    rs.call('getType', { name, pos: props.pos }), [name, rs, props.pos])\n\n  const type = st.state === 'resolved' ? st.value && e(InteractiveCode, {fmt: st.value})\n    : st.state === 'rejected' ? e('p', null, mapRpcError(st.error).message)\n    : e('p', null, 'Loading..')\n  const onChange = (event) => { setName(event.target.value) }\n  return e('div', null,\n    e('input', { value: name, onChange }), ' : ', type)\n}\n\"\n\n/-!\nFinally we can try out the widget.\n-/\n\n#widget checkWidget .null\n\n/-!\n![`#check` as a service](../images/widgets_caas.png)\n\n## Building widget sources\n\nWhile typing JavaScript inline is fine for a simple example, for real developments we want to use\npackages from NPM, a proper build system, and JSX. Thus, most actual widget sources are built with\nLake and NPM. They consist of multiple files and may import libraries which don't work as ESModules\nby default. On the other hand a widget source must be a single, self-contained ESModule in the form\nof a string. Readers familiar with web development may already have guessed that to obtain such a\nstring, we need a *bundler*. Two popular choices are [`rollup.js`](https://rollupjs.org/guide/en/)\nand [`esbuild`](https://esbuild.github.io/). If we go with `rollup.js`, to make a widget work with\nthe infoview we need to:\n- Set [`output.format`](https://rollupjs.org/guide/en/#outputformat) to `'es'`.\n- [Externalize](https://rollupjs.org/guide/en/#external) `react`, `react-dom`, `@leanprover/infoview`.\n  These libraries are already loaded by the infoview so they should not be bundled.\n\nIn the RubiksCube sample, we provide a working `rollup.js` build configuration in\n[rollup.config.js](https://github.com/leanprover/lean4-samples/blob/main/RubiksCube/widget/rollup.config.js).\n\n## Inserting text\n\nWe can also instruct the editor to insert text, copy text to the clipboard, or\nreveal a certain location in the document.\nTo do this, use the `React.useContext(EditorContext)` React context.\nThis will return an `EditorConnection` whose `api` field contains a number of methods to\ninteract with the text editor.\n\nYou can see the full API for this [here](https://github.com/leanprover/vscode-lean4/blob/master/lean4-infoview-api/src/infoviewApi.ts#L52)\n-/\n\n@[widget]\ndef insertTextWidget : UserWidgetDefinition where\n  name := \"textInserter\"\n  javascript := \"\nimport * as React from 'react';\nconst e = React.createElement;\nimport { EditorContext } from '@leanprover/infoview';\n\nexport default function(props) {\n  const editorConnection = React.useContext(EditorContext)\n  function onClick() {\n    editorConnection.api.insertText('-- hello!!!', 'above')\n  }\n\n  return e('div', null, e('button', { value: name, onClick }, 'insert'))\n}\n\"\n\n/-! Finally, we can try this out: -/\n\n#widget insertTextWidget .null\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/widgets.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.07585817949893016, "lm_q1q2_score": 0.031473471118350235}}
{"text": "def x := 1\n\nsection\n  variable (\u03b1 : Type)\n  variable (x : \u03b1)\n  notation \"A\" => id x\n  #check A\n  theorem test : A = A := rfl\n\n  section\n    variable (x : Nat)\n    #check A  -- should use shadowed `x`\n  end\nend\n\n#check A  -- escaping section variable, should fail\n\nsection\n  variable (x : Nat)\n  #check A  -- should fail\nend\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/255.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.06754669677084987, "lm_q1q2_score": 0.03140256546984989}}
{"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.control.traversable.basic\nimport Mathlib.tactic.simpa\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-- pretty print a `loc` -/\n/-- shift `pos` `n` columns to the left -/\nnamespace tactic\n\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\n/-- pretty print structure instance -/\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeeze_loc_attr_carrier : Unit :=\n  Unit.unit\n\n/-- Format a list of arguments for use with `simp` and friends. This omits the\nlist entirely if it is empty. -/\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. -/\n/-- translate a `pexpr` into a `simp` configuration -/\n/-- translate a `pexpr` into a `dsimp` configuration -/\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\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-/\n/-- make a `simp_arg_type` that references the name given as an argument -/\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 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\n-/\nnamespace interactive\n\n\n/-- Turn a `simp_arg_type` into a string. -/\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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (xs.tail.map f).length = xs.length :=\nbegin\n  have : xs = ys, admit,\n  squeeze_scope\n  { split; squeeze_simp, -- `squeeze_simp` is run twice, the first one requires\n                         -- `list.map_append` and the second one `[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]  -- `squeeze_simp` is run only once\n                         -- prints:\n                         -- > Try this: simp only [this]\n },\nend\n```\n\n-/\n/--\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\n-- prints:\n-- Try this: simp only [add_zero, eq_self_iff_true, zero_add]\n\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 `squeeze_simp?`\n\n-/\n/-- see `squeeze_simp` -/\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 -/\nend interactive\n\n\nend tactic\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/squeeze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.06754668644694548, "lm_q1q2_score": 0.03140256067025052}}
{"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.doc_commands\n\n/-!\n# `generalize_proofs`\n\nA simple tactic to find and replace all occurrences of proof terms in the\ncontext and goal with new variables.\n-/\n\nopen interactive interactive.types lean.parser\n\nnamespace tactic\n\nprivate meta def collect_proofs_in :\n  expr \u2192 list expr \u2192 list name \u00d7 list expr \u2192 tactic (list name \u00d7 list expr)\n| e ctx (ns, hs) :=\nlet go (tac : list name \u00d7 list expr \u2192 tactic (list name \u00d7 list expr)) :\n  tactic (list name \u00d7 list expr) :=\ndo t \u2190 infer_type e,\n   mcond (is_prop t) (do\n     first (hs.map $ \u03bb h, do\n       t' \u2190 infer_type h,\n       is_def_eq t t',\n       g \u2190 target,\n       change $ g.replace (\u03bb a n, if a = e then some h else none),\n       return (ns, hs)) <|>\n     (let (n, ns) := (match ns with\n        | [] := (`_x, [])\n        | (n :: ns) := (n, ns)\n        end : name \u00d7 list name) in\n      do generalize e n,\n         h \u2190 intro n,\n         return (ns, h::hs)) <|> return (ns, hs)) (tac (ns, hs)) in\nmatch e with\n| (expr.const _ _)   := go return\n| (expr.local_const _ _ _ _) := do t \u2190 infer_type e, collect_proofs_in t ctx (ns, hs)\n| (expr.mvar _ _ _)  := do t \u2190 infer_type e, collect_proofs_in t ctx (ns, hs)\n| (expr.app f x)     :=\n  go (\u03bb nh, collect_proofs_in f ctx nh >>= collect_proofs_in x ctx)\n| (expr.lam n b d e) :=\n  go (\u03bb nh, do\n    nh \u2190 collect_proofs_in d ctx nh,\n    var \u2190 mk_local' n b d,\n    collect_proofs_in (expr.instantiate_var e var) (var::ctx) nh)\n| (expr.pi n b d e) := do\n  nh \u2190 collect_proofs_in d ctx (ns, hs),\n  var \u2190 mk_local' n b d,\n  collect_proofs_in (expr.instantiate_var e var) (var::ctx) nh\n| (expr.elet n t d e) :=\n  go (\u03bb nh, do\n    nh \u2190 collect_proofs_in t ctx nh,\n    nh \u2190 collect_proofs_in d ctx nh,\n    collect_proofs_in (expr.instantiate_var e d) ctx nh)\n| (expr.macro m l) :=\n  go (\u03bb nh, mfoldl (\u03bb x e, collect_proofs_in e ctx x) nh l)\n| _                  := return (ns, hs)\nend\n\n/-- Generalize proofs in the goal, naming them with the provided list. -/\nmeta def generalize_proofs (ns : list name) (loc : interactive.loc) : tactic unit :=\ndo intros_dep,\n  hs \u2190 local_context >>= mfilter is_proof,\n  n \u2190 loc.get_locals >>= revert_lst,\n  t \u2190 target,\n  collect_proofs_in t [] (ns, hs),\n  intron n <|> (intros $> ())\n\nlocal postfix *:9001 := many\n\nnamespace interactive\n/-- Generalize proofs in the goal, naming them with the provided list.\n\nFor example:\n```lean\nexample : list.nth_le [1, 2] 1 dec_trivial = 2 :=\nbegin\n  -- \u22a2 [1, 2].nth_le 1 _ = 2\n  generalize_proofs h,\n  -- h : 1 < [1, 2].length\n  -- \u22a2 [1, 2].nth_le 1 h = 2\nend\n```\n-/\nmeta def generalize_proofs : parse ident_* \u2192 parse location \u2192 tactic unit :=\ntactic.generalize_proofs\nend interactive\n\nadd_tactic_doc\n{ name       := \"generalize_proofs\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize_proofs],\n  tags       := [\"context management\"] }\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/generalize_proofs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.09670579394695797, "lm_q1q2_score": 0.03135544042120499}}
{"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 `\u03b2`, a `\u03b2`-graded object over some category `C` is just\na function `\u03b2 \u2192 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 `\u03b2 \u2192 \u03b3`.\n\nAs a consequence a fixed element (e.g. `1`) in an additive group `\u03b2` provides a shift\nfunctor on `\u03b2`-graded objects\n\nWhen `C` has coproducts we construct the `total` functor `graded_object \u03b2 C \u2964 C`,\nshow that it is faithful, and deduce that when `C` is concrete so is `graded_object \u03b2 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 `\u03b2 \u2192 C`, used for `\u03b2`-graded objects in a category `C`. -/\ndef graded_object (\u03b2 : Type w) (C : Type u) : Type (max w u) := \u03b2 \u2192 C\n\n-- Satisfying the inhabited linter...\ninstance inhabited_graded_object (\u03b2 : Type w) (C : Type u) [inhabited C] :\n  inhabited (graded_object \u03b2 C) :=\n\u27e8\u03bb b, inhabited.default\u27e9\n\n/--\nA type synonym for `\u03b2 \u2192 C`, used for `\u03b2`-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 {\u03b2 : Type w} [add_comm_group \u03b2] (s : \u03b2) (C : Type u) :\n  Type (max w u) := graded_object \u03b2 C\n\nnamespace graded_object\n\nvariables {C : Type u} [category.{v} C]\n\ninstance category_of_graded_objects (\u03b2 : Type w) : category.{max w v} (graded_object \u03b2 C) :=\ncategory_theory.pi (\u03bb _, C)\n\n/-- The projection of a graded object to its `i`-th component. -/\n@[simps] def eval {\u03b2 : Type w} (b : \u03b2) : graded_object \u03b2 C \u2964 C :=\n{ obj := \u03bb X, X b,\n  map := \u03bb 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 {\u03b2 \u03b3 : Type w} {f g : \u03b2 \u2192 \u03b3} (h : f = g) : comap (\u03bb _, C) f \u2245 comap (\u03bb _, C) g :=\n{ hom := { app := \u03bb X b, eq_to_hom begin dsimp [comap], subst h, end },\n  inv := { app := \u03bb X b, eq_to_hom begin dsimp [comap], subst h, end }, }\n\nlemma comap_eq_symm {\u03b2 \u03b3 : Type w} {f g : \u03b2 \u2192 \u03b3} (h : f = g) :\n  comap_eq C h.symm = (comap_eq C h).symm :=\nby tidy\n\nlemma comap_eq_trans {\u03b2 \u03b3 : Type w} {f g h : \u03b2 \u2192 \u03b3} (k : f = g) (l : g = h) :\n  comap_eq C (k.trans l) = comap_eq C k \u226a\u226b comap_eq C l :=\nbegin\n  ext X b,\n  simp,\nend\n\n@[simp] lemma eq_to_hom_apply {\u03b2 : Type w} {X Y : \u03a0 b : \u03b2, C} (h : X = Y) (b : \u03b2) :\n  (eq_to_hom h : X \u27f6 Y) b = eq_to_hom (by subst h) :=\nby { subst h, refl }\n\n/--\nThe equivalence between \u03b2-graded objects and \u03b3-graded objects,\ngiven an equivalence between \u03b2 and \u03b3.\n-/\n@[simps]\ndef comap_equiv {\u03b2 \u03b3 : Type w} (e : \u03b2 \u2243 \u03b3) :\n  (graded_object \u03b2 C) \u224c (graded_object \u03b3 C) :=\n{ functor := comap (\u03bb _, C) (e.symm : \u03b3 \u2192 \u03b2),\n  inverse := comap (\u03bb _, C) (e : \u03b2 \u2192 \u03b3),\n  counit_iso := (comap_comp (\u03bb _, 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' := \u03bb X, by { ext b, dsimp, simp, }, }  -- See note [dsimp, simp].\n\nend\n\ninstance has_shift {\u03b2 : Type*} [add_comm_group \u03b2] (s : \u03b2) :\n  has_shift (graded_object_with_shift s C) \u2124 :=\nhas_shift_mk _ _\n{ F := \u03bb n, comap (\u03bb _, C) $ \u03bb (b : \u03b2), b + n \u2022 s,\n  zero := comap_eq C (by { ext, simp }) \u226a\u226b comap_id \u03b2 (\u03bb _, C),\n  add := \u03bb m n,  comap_eq C (by { ext, simp [add_zsmul, add_comm], }) \u226a\u226b\n    (comap_comp _ _ _).symm,\n  assoc_hom_app := \u03bb m\u2081 m\u2082 m\u2083 X, by { ext, dsimp, simp, },\n  zero_add_hom_app := \u03bb n X, by { ext, dsimp, simpa, },\n  add_zero_hom_app := \u03bb n X, by { ext, dsimp, simpa, }, }\n\n@[simp] lemma shift_functor_obj_apply {\u03b2 : Type*} [add_comm_group \u03b2]\n  (s : \u03b2) (X : \u03b2 \u2192 C) (t : \u03b2) (n : \u2124) :\n  (shift_functor (graded_object_with_shift s C) n).obj X t = X (t + n \u2022 s) :=\nrfl\n\n@[simp] lemma shift_functor_map_apply {\u03b2 : Type*} [add_comm_group \u03b2] (s : \u03b2)\n  {X Y : graded_object_with_shift s C} (f : X \u27f6 Y) (t : \u03b2) (n : \u2124) :\n  (shift_functor (graded_object_with_shift s C) n).map f t = f (t + n \u2022 s) :=\nrfl\n\ninstance has_zero_morphisms [has_zero_morphisms C] (\u03b2 : Type w) :\n  has_zero_morphisms.{max w v} (graded_object \u03b2 C) :=\n{ has_zero := \u03bb X Y,\n  { zero := \u03bb b, 0 } }\n\n@[simp]\nlemma zero_apply [has_zero_morphisms C] (\u03b2 : Type w) (X Y : graded_object \u03b2 C) (b : \u03b2) :\n  (0 : X \u27f6 Y) b = 0 := rfl\n\nsection\nopen_locale zero_object\n\ninstance has_zero_object [has_zero_object C] [has_zero_morphisms C] (\u03b2 : Type w) :\n  has_zero_object.{max w v} (graded_object \u03b2 C) :=\nby { refine \u27e8\u27e8\u03bb b, 0, \u03bb X, \u27e8\u27e8\u27e8\u03bb b, 0\u27e9, \u03bb f, _\u27e9\u27e9, \u03bb X, \u27e8\u27e8\u27e8\u03bb b, 0\u27e9, \u03bb f, _\u27e9\u27e9\u27e9\u27e9; 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 \u2124 or a finite group, this should be okay.\n-- If you're grading by things in higher universes, have fun!\nvariables (\u03b2 : 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 \u03b2 C \u2964 C :=\n{ obj := \u03bb X, \u2210 (\u03bb i : \u03b2, X i),\n  map := \u03bb X Y f, limits.sigma.map (\u03bb 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 \u03b2 C) :=\n{ map_injective' := \u03bb X Y f g w,\n  begin\n    classical,\n    ext i,\n    replace w := sigma.\u03b9 (\u03bb i : \u03b2, X i) i \u226b= w,\n    erw [colimit.\u03b9_map, colimit.\u03b9_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 (\u03b2 : 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 \u03b2 C) :=\n{ forget := total \u03b2 C \u22d9 forget C }\n\ninstance : has_forget\u2082 (graded_object \u03b2 C) C :=\n{ forget\u2082 := total \u03b2 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": "/-\n---\ntitle: \"Metaprogramming in Lean 4\"\nauthor: [Arthur Paulino, Damiano Testa, Edward Ayers, Evgenia Karunus,\n        Henrik B\u00f6ving, Jannis Limperg, Siddhartha Gadgil, Siddharth Bhat]\n# abusing this field just because the template puts it at a decent right-sized spot\ndate: \"Formatted for PDF by Julian Berman using [Pascal Wagler's Template](https://github.com/Wandmalfarbe/pandoc-latex-template)\"\nmainfont: \"DejaVu Serif\"\nmonofont: \"DejaVu Sans Mono\"\nbook: true\nheader-right: \".\"\ntitlepage: true\ntitlepage-color: \"FFFFFF\"\ntitlepage-text-color: \"5F5F5F\"\ntitlepage-rule-color: \"435488\"\nkeywords: [Lean, theorem proving, mathematics, math, maths, tutorial]\n...\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/cover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.08035747047400407, "lm_q1q2_score": 0.031228361606680983}}
{"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 \u2192 foo\n| two : \u2200 x : fin 3, bar x \u2192 foo\n```\n\nThe list of elements that we generate is\n```\n{foo.zero}\n\u222a (finset.univ : bool).map (\u03bb b, finset.one b)\n\u222a (finset.univ : \u03a3' x : fin 3, bar x).map (\u03bb \u27e8x, y\u27e9, finset.two x y)\n```\nexcept that instead of `\u222a`, 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 \u2192 \u2115\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 \u2260 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 \u2208 s` have `n \u2264 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 `\u03bb 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 \u2208 {foo.zero}\n  \u222a (finset.univ : bool).map (\u03bb b, finset.one b)\n  \u222a (finset.univ : \u03a3' x : fin 3, bar x).map (\u03bb \u27e8x, y\u27e9, 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 `\u0393` 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 `\u2200 a, enum (f a) = k`\n* `mk_finset` constructs the finset `S = {foo.zero} \u222a ...` by recursion on the variants\n* `mk_finset_total` constructs the proof `|- foo.zero \u2208 S; |- foo.one a \u2208 S; |- foo.two a b \u2208 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 (\u03b1 : Type u_1) (enum : \u03b1 \u2192 \u2115) (n : \u2115) :=\n  Subtype fun (s : finset \u03b1) => \u2200 (x : \u03b1), x \u2208 s \u2192 n \u2264 enum x\n\n/-- Construct a fintype instance from a completed `finset_above`. -/\ndef mk_fintype {\u03b1 : Type u_1} (enum : \u03b1 \u2192 \u2115) (s : finset_above \u03b1 enum 0) (H : \u2200 (x : \u03b1), x \u2208 subtype.val s) : fintype \u03b1 :=\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 {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} (n : \u2115) (a : \u03b1) (h : enum a = n) (s : finset_above \u03b1 enum (n + 1)) : finset_above \u03b1 enum n :=\n  { val := finset.cons a (subtype.val s) sorry, property := sorry }\n\ntheorem finset_above.mem_cons_self {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} {n : \u2115} {a : \u03b1} {h : enum a = n} {s : finset_above \u03b1 enum (n + 1)} : a \u2208 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 {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} {n : \u2115} {a : \u03b1} {h : enum a = n} {s : finset_above \u03b1 enum (n + 1)} {b : \u03b1} : b \u2208 subtype.val s \u2192 b \u2208 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 {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} (n : \u2115) : finset_above \u03b1 enum n :=\n  { val := \u2205, property := sorry }\n\nprotected instance finset_above.inhabited (\u03b1 : Type u_1) (enum : \u03b1 \u2192 \u2115) (n : \u2115) : Inhabited (finset_above \u03b1 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 `\u03bb a, enum a = n` where `n` is the discriminant for the current\nvariant. -/\ndef finset_in {\u03b1 : Type u_1} (P : \u03b1 \u2192 Prop) :=\n  Subtype fun (s : finset \u03b1) => \u2200 (x : \u03b1), x \u2208 s \u2192 P x\n\n/-- To construct the finset, we use an injective map from the type `\u0393`, which will be the\nsigma over all constructor arguments. We use sigma instances and existing fintype instances\nto prove that `\u0393` is a fintype, and construct the function `f` that maps `\u27e8a, b, c, ...\u27e9`\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 {\u03b1 : Type u_1} {P : \u03b1 \u2192 Prop} (\u0393 : Type u_2) [fintype \u0393] (f : \u0393 \u2192 \u03b1) (inj : function.injective f) (mem : \u2200 (x : \u0393), 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 {\u03b1 : Type u_1} {P : \u03b1 \u2192 Prop} {\u0393 : Type u_2} {s : fintype \u0393} {f : \u0393 \u2192 \u03b1} {inj : function.injective f} {mem : \u2200 (x : \u0393), P (f x)} {a : \u03b1} (b : \u0393) (H : f b = a) : a \u2208 subtype.val (finset_in.mk \u0393 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 {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} (n : \u2115) (s : finset_in fun (a : \u03b1) => enum a = n) (t : finset_above \u03b1 enum (n + 1)) : finset_above \u03b1 enum n :=\n  { val := finset.disj_union (subtype.val s) (subtype.val t) sorry, property := sorry }\n\ntheorem finset_above.mem_union_left {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} {n : \u2115} {s : finset_in fun (a : \u03b1) => enum a = n} {t : finset_above \u03b1 enum (n + 1)} {a : \u03b1} (H : a \u2208 subtype.val s) : a \u2208 subtype.val (finset_above.union n s t) :=\n  iff.mpr multiset.mem_add (Or.inl H)\n\ntheorem finset_above.mem_union_right {\u03b1 : Type u_1} {enum : \u03b1 \u2192 \u2115} {n : \u2115} {s : finset_in fun (a : \u03b1) => enum a = n} {t : finset_above \u03b1 enum (n + 1)} {a : \u03b1} (H : a \u2208 subtype.val t) : a \u2208 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\u00ebl Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Ya\u00ebl 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 {\u03b1 \u03b2 : Type*}\n\n/-- The category of bipointed types. -/\nstructure Bipointed : Type.{u + 1} :=\n(X : Type.{u})\n(to_prod : X \u00d7 X)\n\nnamespace Bipointed\n\ninstance : has_coe_to_sort Bipointed Type* := \u27e8X\u27e9\n\nattribute [protected] Bipointed.X\n\n/-- Turns a bipointing into a bipointed type. -/\ndef of {X : Type*} (to_prod : X \u00d7 X) : Bipointed := \u27e8X, to_prod\u27e9\n\n@[simp] lemma coe_of {X : Type*} (to_prod : X \u00d7 X) : \u21a5(of to_prod) = X := rfl\n\nalias of \u2190 prod.Bipointed\n\ninstance : inhabited Bipointed := \u27e8of ((), ())\u27e9\n\n/-- Morphisms in `Bipointed`. -/\n@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=\n(to_fun : X \u2192 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 := \u27e8id, rfl, rfl\u27e9\n\ninstance (X : Bipointed) : inhabited (hom X X) := \u27e8id X\u27e9\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\u27e8g.to_fun \u2218 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]\u27e9\n\nend hom\n\ninstance large_category : large_category Bipointed :=\n{ hom := hom,\n  id := hom.id,\n  comp := @hom.comp,\n  id_comp' := \u03bb _ _ _, hom.ext _ _ rfl,\n  comp_id' := \u03bb _ _ _, hom.ext _ _ rfl,\n  assoc' := \u03bb _ _ _ _ _ _ _, hom.ext _ _ rfl }\n\ninstance concrete_category : concrete_category Bipointed :=\n{ forget := { obj := Bipointed.X, map := @hom.to_fun },\n  forget_faithful := \u27e8@hom.ext\u27e9 }\n\n/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/\n@[simps] def swap : Bipointed \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.swap\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_snd, f.map_fst\u27e9 }\n\n/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/\n@[simps] def swap_equiv : Bipointed \u224c Bipointed :=\nequivalence.mk swap swap\n  (nat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl, rfl\u27e9, inv := \u27e8id, rfl, rfl\u27e9 }) $ \u03bb X Y f, rfl)\n  (nat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl, rfl\u27e9, inv := \u27e8id, rfl, rfl\u27e9 }) $ \u03bb 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 \u2964 Pointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.1\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_fst\u27e9 }\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/\ndef Bipointed_to_Pointed_snd : Bipointed \u2964 Pointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.2\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_snd\u27e9 }\n\n@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :\n  Bipointed_to_Pointed_fst \u22d9 forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :\n  Bipointed_to_Pointed_snd \u22d9 forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :\n  Bipointed.swap \u22d9 Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :\n  Bipointed.swap \u22d9 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} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8X, X.point, X.point\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_point, f.map_point\u27e9 }\n\n/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/\ndef Pointed_to_Bipointed_fst : Pointed.{u} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8option X, X.point, none\u27e9,\n  map := \u03bb X Y f, \u27e8option.map f.to_fun, congr_arg _ f.map_point, rfl\u27e9,\n  map_id' := \u03bb X, Bipointed.hom.ext _ _ option.map_id,\n  map_comp' := \u03bb 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} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8option X, none, X.point\u27e9,\n  map := \u03bb X Y f, \u27e8option.map f.to_fun, rfl, congr_arg _ f.map_point\u27e9,\n  map_id' := \u03bb X, Bipointed.hom.ext _ _ option.map_id,\n  map_comp' := \u03bb 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 \u22d9 Bipointed.swap = Pointed_to_Bipointed_snd := rfl\n\n@[simp] lemma Pointed_to_Bipointed_snd_comp_swap :\n  Pointed_to_Bipointed_snd \u22d9 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 \u22d9 Bipointed_to_Pointed_fst \u2245 \ud835\udfed _ :=\nnat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl\u27e9, inv := \u27e8id, rfl\u27e9 }) $ \u03bb 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 \u22d9 Bipointed_to_Pointed_snd \u2245 \ud835\udfed _ :=\nnat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl\u27e9, inv := \u27e8id, rfl\u27e9 }) $ \u03bb 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 \u22a3 Bipointed_to_Pointed_fst :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb X Y, { to_fun := \u03bb f, \u27e8f.to_fun \u2218 option.some, f.map_fst\u27e9,\n                        inv_fun := \u03bb f, \u27e8\u03bb o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl\u27e9,\n                        left_inv := \u03bb f, by { ext, cases x, exact f.map_snd.symm, refl },\n                        right_inv := \u03bb f, Pointed.hom.ext _ _ rfl },\n  hom_equiv_naturality_left_symm' := \u03bb 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 \u22a3 Bipointed_to_Pointed_snd :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb X Y, { to_fun := \u03bb f, \u27e8f.to_fun \u2218 option.some, f.map_snd\u27e9,\n                        inv_fun := \u03bb f, \u27e8\u03bb o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point\u27e9,\n                        left_inv := \u03bb f, by { ext, cases x, exact f.map_fst.symm, refl },\n                        right_inv := \u03bb f, Pointed.hom.ext _ _ rfl },\n  hom_equiv_naturality_left_symm' := \u03bb 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 \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 {\u03c3 : Type u}\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3,\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 \u2227 ((p \u2227 q) \u2227 r) \u2227 (q \u2227 r \u2227 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": "import tactic --hide\n\n\n/-Lemma\nAn even more nested implications\n-/\nlemma lemma_8 (P Q R : Prop) : ((P \u2192 Q) \u2192 R) \u2192 ((Q \u2192 R) \u2192 P) \u2192 ((R \u2192 P) \u2192 Q) \u2192 P :=\nbegin\n  intros h1 h2 h3,\n  apply h2,\n  intro hQ,\n  apply h1,\n  intro hP,\n  exact hQ,\n\n\n\nend", "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/logic_1/logic10.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.06278920202041778, "lm_q1q2_score": 0.03090410028582584}}
{"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\nimport tidy.timing\n\nopen tactic\n\nprivate lemma f : 1 = 1 :=\nbegin\n    (time_tactic skip) >>= trace,\n    simp\nend\n", "meta": {"author": "semorrison", "repo": "lean-tidy", "sha": "6c1d46de6cff05e1c2c4c9692af812bca3e13b6c", "save_path": "github-repos/lean/semorrison-lean-tidy", "path": "github-repos/lean/semorrison-lean-tidy/lean-tidy-6c1d46de6cff05e1c2c4c9692af812bca3e13b6c/test/timing.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.07585818785594478, "lm_q1q2_score": 0.030899572489136374}}
{"text": "/-\nCopyright (c) 2017 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl\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 : \u03b1 \u00d7 \u03b2 \u2192 \u03b2 \u00d7 \u03b1` and proves various simple lemmas about `prod`.\n-/\n\n@[simp] theorem prod_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) (p : \u03b1 \u00d7 \u03b2) : prod.map f g p = (f (prod.fst p), g (prod.snd p)) :=\n  rfl\n\nnamespace prod\n\n\n@[simp] theorem forall {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2 \u2192 Prop} : (\u2200 (x : \u03b1 \u00d7 \u03b2), p x) \u2194 \u2200 (a : \u03b1) (b : \u03b2), p (a, b) := sorry\n\n@[simp] theorem exists {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2 \u2192 Prop} : (\u2203 (x : \u03b1 \u00d7 \u03b2), p x) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), p (a, b) := sorry\n\ntheorem forall' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2200 (x : \u03b1 \u00d7 \u03b2), p (fst x) (snd x)) \u2194 \u2200 (a : \u03b1) (b : \u03b2), p a b :=\n  forall\n\ntheorem exists' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 (x : \u03b1 \u00d7 \u03b2), p (fst x) (snd x)) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), p a b :=\n  exists\n\n@[simp] theorem map_mk {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) (a : \u03b1) (b : \u03b2) : map f g (a, b) = (f a, g b) :=\n  rfl\n\ntheorem map_fst {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) (p : \u03b1 \u00d7 \u03b2) : fst (map f g p) = f (fst p) :=\n  rfl\n\ntheorem map_snd {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) (p : \u03b1 \u00d7 \u03b2) : snd (map f g p) = g (snd p) :=\n  rfl\n\ntheorem map_fst' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) : fst \u2218 map f g = f \u2218 fst :=\n  funext (map_fst f g)\n\ntheorem map_snd' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) : snd \u2218 map f g = g \u2218 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {\u03b5 : Type u_5} {\u03b6 : Type u_6} (f : \u03b1 \u2192 \u03b2) (f' : \u03b3 \u2192 \u03b4) (g : \u03b2 \u2192 \u03b5) (g' : \u03b4 \u2192 \u03b6) : map g g' \u2218 map f f' = map (g \u2218 f) (g' \u2218 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {\u03b5 : Type u_5} {\u03b6 : Type u_6} (f : \u03b1 \u2192 \u03b2) (f' : \u03b3 \u2192 \u03b4) (g : \u03b2 \u2192 \u03b5) (g' : \u03b4 \u2192 \u03b6) (x : \u03b1 \u00d7 \u03b3) : map g g' (map f f' x) = map (g \u2218 f) (g' \u2218 f') x :=\n  rfl\n\n@[simp] theorem mk.inj_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} : (a\u2081, b\u2081) = (a\u2082, b\u2082) \u2194 a\u2081 = a\u2082 \u2227 b\u2081 = b\u2082 := sorry\n\ntheorem mk.inj_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} (a : \u03b1) : function.injective (Prod.mk a) := sorry\n\ntheorem mk.inj_right {\u03b1 : Type u_1} {\u03b2 : Type u_2} (b : \u03b2) : function.injective fun (a : \u03b1) => (a, b) := sorry\n\ntheorem ext_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} {q : \u03b1 \u00d7 \u03b2} : p = q \u2194 fst p = fst q \u2227 snd p = snd q := sorry\n\ntheorem ext {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} {q : \u03b1 \u00d7 \u03b2} (h\u2081 : fst p = fst q) (h\u2082 : snd p = snd q) : p = q :=\n  iff.mpr ext_iff { left := h\u2081, right := h\u2082 }\n\ntheorem map_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {f : \u03b1 \u2192 \u03b3} {g : \u03b2 \u2192 \u03b4} : map f g = fun (p : \u03b1 \u00d7 \u03b2) => (f (fst p), g (snd p)) :=\n  funext fun (p : \u03b1 \u00d7 \u03b2) => ext (map_fst f g p) (map_snd f g p)\n\ntheorem id_prod {\u03b1 : Type u_1} : (fun (p : \u03b1 \u00d7 \u03b1) => (fst p, snd p)) = id := sorry\n\ntheorem fst_surjective {\u03b1 : Type u_1} {\u03b2 : Type u_2} [h : Nonempty \u03b2] : function.surjective fst :=\n  fun (x : \u03b1) => nonempty.elim h fun (y : \u03b2) => Exists.intro (x, y) rfl\n\ntheorem snd_surjective {\u03b1 : Type u_1} {\u03b2 : Type u_2} [h : Nonempty \u03b1] : function.surjective snd :=\n  fun (y : \u03b2) => nonempty.elim h fun (x : \u03b1) => Exists.intro (x, y) rfl\n\ntheorem fst_injective {\u03b1 : Type u_1} {\u03b2 : Type u_2} [subsingleton \u03b2] : function.injective fst :=\n  fun (x y : \u03b1 \u00d7 \u03b2) (h : fst x = fst y) => ext h (subsingleton.elim (snd x) (snd y))\n\ntheorem snd_injective {\u03b1 : Type u_1} {\u03b2 : Type u_2} [subsingleton \u03b1] : function.injective snd :=\n  fun (x y : \u03b1 \u00d7 \u03b2) (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} : \u03b1 \u00d7 \u03b2 \u2192 \u03b2 \u00d7 \u03b1 :=\n  fun (p : \u03b1 \u00d7 \u03b2) => (snd p, fst p)\n\n@[simp] theorem swap_swap {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b1 \u00d7 \u03b2) : swap (swap x) = x :=\n  cases_on x fun (x_fst : \u03b1) (x_snd : \u03b2) => idRhs (swap (swap (x_fst, x_snd)) = swap (swap (x_fst, x_snd))) rfl\n\n@[simp] theorem fst_swap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} : fst (swap p) = snd p :=\n  rfl\n\n@[simp] theorem snd_swap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} : snd (swap p) = fst p :=\n  rfl\n\n@[simp] theorem swap_prod_mk {\u03b1 : Type u_1} {\u03b2 : Type u_2} {a : \u03b1} {b : \u03b2} : swap (a, b) = (b, a) :=\n  rfl\n\n@[simp] theorem swap_swap_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} : swap \u2218 swap = id :=\n  funext swap_swap\n\n@[simp] theorem swap_left_inverse {\u03b1 : Type u_1} {\u03b2 : Type u_2} : function.left_inverse swap swap :=\n  swap_swap\n\n@[simp] theorem swap_right_inverse {\u03b1 : Type u_1} {\u03b2 : Type u_2} : function.right_inverse swap swap :=\n  swap_swap\n\ntheorem swap_injective {\u03b1 : Type u_1} {\u03b2 : Type u_2} : function.injective swap :=\n  function.left_inverse.injective swap_left_inverse\n\ntheorem swap_surjective {\u03b1 : Type u_1} {\u03b2 : Type u_2} : function.surjective swap :=\n  function.left_inverse.surjective swap_left_inverse\n\ntheorem swap_bijective {\u03b1 : Type u_1} {\u03b2 : Type u_2} : function.bijective swap :=\n  { left := swap_injective, right := swap_surjective }\n\n@[simp] theorem swap_inj {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} {q : \u03b1 \u00d7 \u03b2} : swap p = swap q \u2194 p = q :=\n  function.injective.eq_iff swap_injective\n\ntheorem eq_iff_fst_eq_snd_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} {q : \u03b1 \u00d7 \u03b2} : p = q \u2194 fst p = fst q \u2227 snd p = snd q := sorry\n\ntheorem fst_eq_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} {x : \u03b1} : fst p = x \u2194 p = (x, snd p) := sorry\n\ntheorem snd_eq_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u00d7 \u03b2} {x : \u03b2} : snd p = x \u2194 p = (fst p, x) := sorry\n\ntheorem lex_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (s : \u03b2 \u2192 \u03b2 \u2192 Prop) {p : \u03b1 \u00d7 \u03b2} {q : \u03b1 \u00d7 \u03b2} : lex r s p q \u2194 r (fst p) (fst q) \u2228 fst p = fst q \u2227 s (snd p) (snd q) := sorry\n\nprotected instance lex.decidable {\u03b1 : Type u_1} {\u03b2 : Type u_2} [DecidableEq \u03b1] (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (s : \u03b2 \u2192 \u03b2 \u2192 Prop) [DecidableRel r] [DecidableRel s] : DecidableRel (lex r s) :=\n  fun (p q : \u03b1 \u00d7 \u03b2) => decidable_of_decidable_of_iff or.decidable sorry\n\nend prod\n\n\ntheorem function.injective.prod_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {f : \u03b1 \u2192 \u03b3} {g : \u03b2 \u2192 \u03b4} (hf : function.injective f) (hg : function.injective g) : function.injective (prod.map f g) :=\n  fun (x y : \u03b1 \u00d7 \u03b2) (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {f : \u03b1 \u2192 \u03b3} {g : \u03b2 \u2192 \u03b4} (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 \u27f6 Z} {g : Y \u27f6 Z}\n\n/-- A supremely useful structure for elementary topos theory. -/\nstructure has_pullback_top (left : W \u27f6 Y) (bottom : Y \u27f6 Z) (right : X \u27f6 Z) :=\n(top : W \u27f6 X)\n(comm : top \u226b right = left \u226b bottom)\n(is_pb : is_limit (pullback_cone.mk _ _ comm))\n\nattribute [reassoc] has_pullback_top.comm\n\ninstance subsingleton_hpb (left : W \u27f6 Y) (bottom : Y \u27f6 Z) (right : X \u27f6 Z) [mono right] :\n  subsingleton (has_pullback_top left bottom right) :=\n\u27e8begin\n  intros P Q,\n  cases P,\n  cases Q,\n  congr,\n  rw \u2190 cancel_mono right,\n  rw P_comm, rw Q_comm\nend\u27e9\n\ndef has_pullback_top_of_is_pb {U V W X : C}\n  {f : U \u27f6 V} {g : V \u27f6 W} {h : U \u27f6 X} {k : X \u27f6 W}\n  {comm : f \u226b g = h \u226b 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 : \u03a0 (s : pullback_cone f g), {l : s.X \u27f6 t.X // l \u226b t.fst = s.fst \u2227 l \u226b t.snd = s.snd \u2227 \u2200 {m : s.X \u27f6 t.X}, m \u226b t.fst = s.fst \u2192 m \u226b t.snd = s.snd \u2192 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 : \u03a0 (s : pullback_cone f g), {l : s.X \u27f6 t.X // l \u226b t.snd = s.snd \u2227 \u2200 {m : s.X \u27f6 t.X}, m \u226b t.fst = s.fst \u2192 m \u226b t.snd = s.snd \u2192 m = l}) :\nis_limit t :=\nis_limit.mk' t $\nbegin\n  intro s,\n  refine \u27e8(create s).1, _, (create s).2.1, \u03bb m m\u2081 m\u2082, (create s).2.2 m\u2081 m\u2082\u27e9,\n  rw [\u2190 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 : \u03a0 (s : pullback_cone f g), {l : s.X \u27f6 t.X // l \u226b t.snd = s.snd}) :\nis_limit t :=\nis_limit.mk' t $\nbegin\n  intro s,\n  refine \u27e8(create s).1, _, (create s).2, \u03bb m _ m\u2082, _\u27e9,\n  rw [\u2190 cancel_mono f, assoc, t.condition, s.condition, reassoc_of (create s).2],\n  rw [\u2190 cancel_mono t.snd, m\u2082, (create s).2],\nend\n\ndef construct_type_pb {W X Y Z : Type u} {f : X \u27f6 Z} {g : Y \u27f6 Z} {h : W \u27f6 _} {k} (comm : h \u226b f = k \u226b g) :\n  (\u2200 (x : X) (y : Y), f x = g y \u2192 {t // h t = x \u2227 k t = y \u2227 \u2200 t', h t' = x \u2192 k t' = y \u2192 t' = t}) \u2192 is_limit (pullback_cone.mk _ _ comm) :=\nbegin\n  intro z,\n  apply is_limit.mk' _ _,\n  intro s,\n  refine \u27e8\u03bb t, _, _, _, _\u27e9,\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\u2081 m\u2082,\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\u2081 t,\n  apply congr_fun m\u2082 t,\nend\n\ndef pullback_mono_is_mono (c : pullback_cone f g) [mono f] (t : is_limit c) : mono c.snd :=\n\u27e8\u03bb Z h k eq,\nbegin\n  apply t.hom_ext,\n  apply pullback_cone.equalizer_ext,\n  rw [\u2190 cancel_mono f, assoc, c.condition, reassoc_of eq, assoc, c.condition],\n  assumption\nend\u27e9\n\ndef cone_is_pullback {X Y Z : C} (f : X \u27f6 Z) (g : Y \u27f6 Z) [has_limit (cospan f g)] :\n  is_limit (pullback_cone.mk _ _ pullback.condition : pullback_cone f g) :=\nis_limit.mk' _ $ \u03bb s,\n\u27e8 pullback.lift _ _ s.condition,\n  pullback.lift_fst _ _ _,\n  pullback.lift_snd _ _ _,\n  \u03bb m m\u2081 m\u2082, pullback.hom_ext (by simpa using m\u2081) (by simpa using m\u2082) \u27e9\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 := \u03bb c, t.lift c,\n  fac' := \u03bb c j,\n  begin\n    cases j,\n    simp [\u2190 t.fac c none, \u2190 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' := \u03bb c m w,\n  begin\n    apply t.uniq,\n    intro j,\n    rw \u2190 w,\n    cases j,\n    simp [\u2190 t.fac c none, \u2190 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 \u27f6 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 \u27f6 V) (g : V \u27f6 W) (h : U \u27f6 X) (k : V \u27f6 Y) (l : W \u27f6 Z) (m : X \u27f6 Y) (n : Y \u27f6 Z)\n  (left_comm : f \u226b k = h \u226b m)\n  (right_comm : g \u226b l = k \u226b 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 \u226b g) h (begin rw [assoc, right_comm, reassoc_of left_comm]end)) :=\nis_limit.mk' _ $\nbegin\n  intro s,\n  let t : s.X \u27f6 V := right_pb.lift (pullback_cone.mk s.fst (s.snd \u226b m) (by rw [assoc, s.condition])),\n  have l_comm : t \u226b k = s.snd \u226b m := right_pb.fac _ walking_cospan.right,\n  let u : s.X \u27f6 U := left_pb.lift (pullback_cone.mk _ _ l_comm),\n  have uf : u \u226b f = t := left_pb.fac _ walking_cospan.left,\n  have tg : t \u226b g = s.fst := right_pb.fac _ walking_cospan.left,\n  refine \u27e8u, _, left_pb.fac _ walking_cospan.right, _\u27e9,\n  { rw [\u2190 tg, \u2190 uf, assoc u f g], refl },\n  { intros m' m\u2081 m\u2082,\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\u2081 },\n      { erw [uf, assoc, left_comm, reassoc_of m\u2082, l_comm] } },\n    { erw [left_pb.fac _ walking_cospan.right], exact m\u2082 } }\nend\n\ndef both_pb_to_left_pb {U V W X Y Z : C}\n  (f : U \u27f6 V) (g : V \u27f6 W) (h : U \u27f6 X) (k : V \u27f6 Y) (l : W \u27f6 Z) (m : X \u27f6 Y) (n : Y \u27f6 Z)\n  (left_comm : f \u226b k = h \u226b m)\n  (right_comm : g \u226b l = k \u226b n)\n  (right_pb : is_limit (pullback_cone.mk g k right_comm))\n  (entire_pb : is_limit (pullback_cone.mk (f \u226b 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 \u27f6 U := entire_pb.lift (pullback_cone.mk (s.fst \u226b g) s.snd (by rw [assoc, right_comm, s.condition_assoc])),\n  have uf : u \u226b 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, \u2190 assoc, entire_pb.fac _ walking_cospan.right, s.condition], refl } },\n  refine \u27e8u, uf, entire_pb.fac _ walking_cospan.right, _\u27e9,\n  { intros m' m\u2081 m\u2082,\n    apply entire_pb.hom_ext,\n    apply (pullback_cone.mk (f \u226b g) h _).equalizer_ext,\n    { erw [reassoc_of uf, reassoc_of m\u2081] },\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 \u27f6 W) (h : U \u27f6 X) (k : V \u27f6 Y) (l : W \u27f6 Z) (m : X \u27f6 Y) (n : Y \u27f6 Z)\n  (left : has_pullback_top h m k)\n  (right_comm : g \u226b l = k \u226b n)\n  (right_pb : is_limit (pullback_cone.mk g k right_comm)) :\n  has_pullback_top h (m \u226b n) l :=\n{ top := left.top \u226b 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 \u27f6 X} {k : V \u27f6 Y} (l : W \u27f6 Z) {m : X \u27f6 Y} (n : Y \u27f6 Z)\n  (both : has_pullback_top h (m \u226b n) l)\n  (right : has_pullback_top k n l) :\n  has_pullback_top h m k :=\nbegin\n  let t : U \u27f6 V := right.is_pb.lift (pullback_cone.mk both.top (h \u226b m) (by rw [assoc, both.comm])),\n  refine \u27e8t, right.is_pb.fac _ walking_cospan.right, _\u27e9,\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 \u27f6 X} (k : V \u27f6 Y) {l : W \u27f6 Z} {m : X \u27f6 Y} {n : Y \u27f6 Z}\n  (left : has_pullback_top h m k)\n  (right : has_pullback_top k n l) :\n  has_pullback_top h (m \u226b n) l :=\n{ top := left.top \u226b 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 \u27f6 V) (g : U \u27f6 W) (h : V \u27f6 X) (k : W \u27f6 X) (l : W \u27f6 Y) (m : X \u27f6 Z) (n : Y \u27f6 Z)\n  (up_comm : f \u226b h = g \u226b k) (down_comm : k \u226b m = l \u226b 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 \u226b l) (by rw [reassoc_of up_comm, down_comm, assoc]) : pullback_cone (h \u226b m) n):=\nis_limit.mk' _ $\nbegin\n  intro s,\n  let c' : pullback_cone m n := pullback_cone.mk (pullback_cone.fst s \u226b h) (pullback_cone.snd s) (by simp [pullback_cone.condition s]),\n  let t : s.X \u27f6 W := down_pb.lift c',\n  have tl : t \u226b l = pullback_cone.snd s := down_pb.fac c' walking_cospan.right,\n  have tk : t \u226b k = pullback_cone.fst s \u226b 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 \u27f6 U := up_pb.lift c'',\n  have uf : u \u226b f = pullback_cone.fst s := up_pb.fac c'' walking_cospan.left,\n  have ug : u \u226b g = t := up_pb.fac c'' walking_cospan.right,\n  refine \u27e8u, uf, by erw [reassoc_of ug, tl], _\u27e9,\n  intros m' m\u2081 m\u2082,\n  apply up_pb.hom_ext,\n  apply (pullback_cone.mk f g up_comm).equalizer_ext,\n  change m' \u226b f = u \u226b f,\n  erw [m\u2081, uf],\n  erw ug,\n  apply down_pb.hom_ext,\n  apply (pullback_cone.mk _ _ down_comm).equalizer_ext,\n  { change (m' \u226b g) \u226b k = t \u226b k,\n    slice_lhs 2 3 {rw \u2190 up_comm},\n    slice_lhs 1 2 {erw m\u2081},\n    rw tk },\n  { change (m' \u226b g) \u226b l = t \u226b l,\n    erw [assoc, m\u2082, tl] }\nend\n\ndef stretch_hpb_down {U V W X Y Z : C} (g : U \u27f6 W) (h : V \u27f6 X) (k : W \u27f6 X) (l : W \u27f6 Y) (m : X \u27f6 Z) (n : Y \u27f6 Z)\n  (up : has_pullback_top g k h)\n  (down_comm : k \u226b m = l \u226b n)\n  (down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :\nhas_pullback_top (g \u226b l) n (h \u226b 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 \u27f6 V) (g : U \u27f6 W) (h : V \u27f6 X) (k : W \u27f6 X) (l : W \u27f6 Y) (m : X \u27f6 Z) (n : Y \u27f6 Z)\n  (up_comm : f \u226b h = g \u226b k) (down_comm : k \u226b m = l \u226b n)\n  (down_pb : is_limit (pullback_cone.mk _ _ down_comm))\n  (entire_pb : is_limit (pullback_cone.mk f (g \u226b l) (by rw [reassoc_of up_comm, down_comm, assoc]) : pullback_cone (h \u226b m) n)) :\n  is_limit (pullback_cone.mk _ _ up_comm) :=\nis_limit.mk' _ $\nbegin\n  intro s,\n  let c' : pullback_cone (h \u226b m) n := pullback_cone.mk (pullback_cone.fst s) (pullback_cone.snd s \u226b l) (by simp [pullback_cone.condition_assoc s, down_comm]),\n  let t : s.X \u27f6 U := entire_pb.lift c',\n  have t\u2081 : t \u226b f = pullback_cone.fst s := entire_pb.fac c' walking_cospan.left,\n  have t\u2082 : t \u226b g \u226b l = pullback_cone.snd s \u226b l := entire_pb.fac c' walking_cospan.right,\n  have t\u2083 : t \u226b 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, \u2190 up_comm, reassoc_of t\u2081, pullback_cone.condition s], refl,\n    rwa [assoc],\n  refine \u27e8t, t\u2081, t\u2083, _\u27e9,\n  intros m' m\u2081 m\u2082,\n  apply entire_pb.hom_ext,\n  apply pullback_cone.equalizer_ext (pullback_cone.mk f (g \u226b l) _) _ _,\n  exact m\u2081.trans t\u2081.symm,\n  refine trans _ t\u2082.symm,\n  erw [reassoc_of m\u2082]\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 \u226b l as one of the arguments and calculate g\ndef cut_hpb_up {U V W X Y Z : C} (g : U \u27f6 W) (h : V \u27f6 X) (k : W \u27f6 X) (l : W \u27f6 Y) (m : X \u27f6 Z) (n : Y \u27f6 Z) [mono m]\n  (all : has_pullback_top (g \u226b l) n (h \u226b m))\n  (down_comm : k \u226b m = l \u226b 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 [\u2190 cancel_mono m, assoc, all.comm, assoc, \u2190 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 \u27f6 W) (h : V \u27f6 X) (k : W \u27f6 X) (l : W \u27f6 Y) (m : X \u27f6 Z) (n : Y \u27f6 Z)\n  (all : has_pullback_top (g \u226b l) n (h \u226b m))\n  (up_comm : all.top \u226b h = g \u226b k)\n  (down_comm : k \u226b m = l \u226b 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 \u00d7 A \u27f6 B \u00d7 A\n--   |       |\n--   v       v\n--   D   \u27f6   B\n-- is a pullback (needed in over/exponentiable_in_slice)\ndef pullback_prod (xy : X \u27f6 Y) (Z : C) [has_binary_products.{v} C] :\n  is_limit (pullback_cone.mk limits.prod.fst (limits.prod.map xy (\ud835\udfd9 Z)) (limits.prod.map_fst _ _).symm) :=\nis_limit.mk' _ $\nbegin\n  intro s,\n  refine \u27e8prod.lift (pullback_cone.fst s) (pullback_cone.snd s \u226b limits.prod.snd), limit.lift_\u03c0 _ _, _, _\u27e9,\n  { change limits.prod.lift (pullback_cone.fst s) (pullback_cone.snd s \u226b limits.prod.snd) \u226b\n      limits.prod.map xy (\ud835\udfd9 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\u2081 m\u2082,\n    apply prod.hom_ext,\n    simpa using m\u2081,\n    erw [prod.lift_snd, \u2190 m\u2082, assoc, limits.prod.map_snd, comp_id] },\nend\n\ndef pullback_prod' (xy : X \u27f6 Y) (Z : C) [has_binary_products.{v} C] :\n  is_limit (pullback_cone.mk limits.prod.snd (limits.prod.map (\ud835\udfd9 Z) xy) (limits.prod.map_snd _ _).symm) :=\nis_limit.mk' _ $\nbegin\n  intro s,\n  refine \u27e8prod.lift (pullback_cone.snd s \u226b limits.prod.fst) (pullback_cone.fst s), limit.lift_\u03c0 _ _, _, _\u27e9,\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\u2081 m\u2082,\n    apply prod.hom_ext,\n    erw [prod.lift_fst, \u2190 m\u2082, assoc, limits.prod.map_fst, comp_id],\n    simpa using m\u2081 }\nend\n\ndef pullback_flip {W X Y Z : C} {f : W \u27f6 X} {g : W \u27f6 Y} {h : X \u27f6 Z} {k : Y \u27f6 Z} {comm : f \u226b h = g \u226b k} (t : is_limit (pullback_cone.mk _ _ comm.symm)) :\n  is_limit (pullback_cone.mk _ _ comm) :=\nis_limit.mk' _ $ \u03bb s,\nbegin\n  refine \u27e8(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, \u03bb m m\u2081 m\u2082, t.hom_ext _\u27e9,\n  apply (pullback_cone.mk g f _).equalizer_ext,\n  { rw (pullback_cone.is_limit.lift' t _ _ _).2.1,\n    exact m\u2082 },\n  { rw (pullback_cone.is_limit.lift' t _ _ _).2.2,\n    exact m\u2081 },\nend\n\ndef pullback_square_iso {W X Y Z : C} (f : W \u27f6 X) (g : W \u27f6 Y) (h : X \u27f6 Z) (k : Y \u27f6 Z) [mono h] [is_iso g] (comm : f \u226b h = g \u226b k) :\n  is_limit (pullback_cone.mk _ _ comm) :=\nis_limit.mk''' _ (by dsimp [pullback_cone.mk]; apply_instance) $\n  \u03bb s, \u27e8s.snd \u226b inv g, by erw [assoc, is_iso.inv_hom_id g, comp_id] \u27e9\n\ndef left_iso_has_pullback_top {W X Y Z : C} (f : W \u27f6 X) (g : W \u27f6 Y) (h : X \u27f6 Z) (k : Y \u27f6 Z) [mono h] [is_iso g] (comm : f \u226b h = g \u226b 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 \u27f6 X) (g : W \u27f6 Y) (h : X \u27f6 Z) (k : Y \u27f6 Z) [is_iso f] [mono k] (comm : f \u226b h = g \u226b k) :\n  is_limit (pullback_cone.mk _ _ comm) :=\nis_limit.mk' _ $\nbegin\n  intro s,\n  refine \u27e8pullback_cone.fst s \u226b inv f, _, _, _\u27e9,\n  erw [assoc, is_iso.inv_hom_id, comp_id],\n  erw [\u2190 cancel_mono k, assoc, \u2190 comm, assoc, is_iso.inv_hom_id_assoc, pullback_cone.condition s],\n  intros m m\u2081 m\u2082,\n  erw [(as_iso f).eq_comp_inv, m\u2081]\nend\n\ndef top_iso_has_pullback_top {W X Y Z : C} (f : W \u27f6 X) (g : W \u27f6 Y) (h : X \u27f6 Z) (k : Y \u27f6 Z) [is_iso f] [mono k] (comm : f \u226b h = g \u226b 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 \u27f6 Y)\n  (hl : is_limit (pullback_cone.mk (\ud835\udfd9 X) (\ud835\udfd9 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 \u27f6 Y) [hf : mono f] :\n  is_limit (pullback_cone.mk (\ud835\udfd9 X) (\ud835\udfd9 X) rfl : pullback_cone f f) :=\npullback_square_iso' _ _ _ _ _\n\ndef mono_self_has_pullback_top {X Y : C} (f : X \u27f6 Y) [hf : mono f] :\n  has_pullback_top (\ud835\udfd9 _) f f :=\n{ top := \ud835\udfd9 _,\n  comm := by simp,\n  is_pb := pullback_of_mono f }\n\nuniverse u\u2082\nvariables {D : Type u\u2082} [category.{v} D] (F : C \u2964 D)\n\n\ndef cone_cospan_equiv :\n  cone (cospan (F.map f) (F.map g)) \u224c cone (cospan f g \u22d9 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 \u27f6 X} {g : X \u27f6 Z} {h : W \u27f6 Y} {k : Y \u27f6 Z} (comm : f \u226b g = h \u226b k) :\n(cones.postcompose (diagram_iso_cospan _).hom).obj (F.map_cone (pullback_cone.mk _ _ comm)) \u2245\n    (pullback_cone.mk (F.map f) (F.map h) (by rw [\u2190 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 \u27f6 X} {g : X \u27f6 Z} {h : W \u27f6 Y} {k : Y \u27f6 Z} (comm : f \u226b g = h \u226b k) :\nis_limit (F.map_cone (pullback_cone.mk _ _ comm)) \u2245 is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [\u2190 F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=\n{ hom := \u03bb 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 := \u03bb p,\n  begin\n    have := is_limit.of_right_adjoint (cones.postcompose_equivalence (diagram_iso_cospan (cospan g k \u22d9 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 \u27f6 X) (g : X \u27f6 Z) (h : W \u27f6 Y) (k : Y \u27f6 Z) (comm : f \u226b g = h \u226b k)\n  (t : is_limit (pullback_cone.mk _ _ comm)) :\nis_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [\u2190 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 \u27f6 X} {g : X \u27f6 Z} {h : W \u27f6 Y} {k : Y \u27f6 Z} (comm : f \u226b g = h \u226b k)\n  (t : is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [\u2190 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 \u27f6 Y) [mono f] :\n  mono (F.map f) :=\nbegin\n  apply mono_of_pullback,\n  have : \ud835\udfd9 (F.obj X) = F.map (\ud835\udfd9 X),\n    rw F.map_id,\n  convert preserves_pullback_cone F (\ud835\udfd9 _) f (\ud835\udfd9 _) f rfl (pullback_of_mono f),\nend\n\ndef preserves_walking_cospan_of_preserves_pb_cone {h : W \u27f6 _} {k} (comm : h \u226b f = k \u226b g) (is_lim : is_limit (pullback_cone.mk _ _ comm))\n  (t : is_limit (pullback_cone.mk (F.map h) (F.map k) (by rw [\u2190 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 \u27f6 Z} {h : W \u27f6 Y} {k : Y \u27f6 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 [\u2190 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 \u27f6 Z} {h : W \u27f6 Y} {k : Y \u27f6 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 \u27f6 Z) (h : Z \u27f6 W) (k : Y \u27f6 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 \u27f6 Z} {h : Z \u27f6 W} {k : Y \u27f6 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, \u2190 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 \u27e8\u03bb K, by apply_instance\u27e9,\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 \u2192 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 \u2192 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 := \u27e8UInt8.toUInt32 b, by\n    rcases b with \u27e8\u27e8x,h\u27e9\u27e9\n    apply Or.inl\n    simp\n    apply Nat.lt_trans h (by decide)\n  \u27e9\n\ndef Char.toUInt8 (c : Char) (h : c.val.val < UInt8.size := by decide) : UInt8 :=\n  \u27e8c.val.val, h\u27e9\n\ninstance (h : c.val.val < UInt8.size := by decide) : CoeDep Char c UInt8 := \u27e8c.toUInt8 h\u27e9\n\nstructure ThunkCache (a : Unit \u2192 \u03b1) where\n  val : Thunk \u03b1\n  h_val : val.get = a ()\n\ndef ThunkCache.new : ThunkCache a := \u27e8Thunk.mk a, by simp [Thunk.get]\u27e9\ninstance : Inhabited (ThunkCache a) := \u27e8.new\u27e9\n\ndef List.pmap (L : List \u03b1) (f : (a : \u03b1) \u2192 a \u2208 L \u2192 \u03b2) : List \u03b2 :=\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 \u2208 List.zipWith f L1 L2)\n  : \u2203 y z, x = f y z \u2227 y \u2208 L1 \u2227 z \u2208 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 \u27e8_, _, rfl, .inl rfl, .inl rfl\u27e9\n          . have := ih (by assumption)\n            rcases this with \u27e8y,z,rfl,hy,hz\u27e9\n            refine \u27e8y,z, rfl, .inr hy, .inr hz\u27e9\n\ntheorem List.mem_take (h : x \u2208 List.take n L)\n  : x \u2208 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 : \u03b1 \u2192 \u03b2) [DecidableEq \u03b1] (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 \u27e8U, R, \u27e8e\u27e9\u27e9 := X.local_affine x,\n  have hy := (h' _ U.1.2).mp U.2,\n  erw \u2190 subtype_inseparable_iff (\u27e8x, U.2\u27e9 : U.1.1) (\u27e8y, hy\u27e9 : U.1.1) at h',\n  let e' : U.1 \u2243\u209c prime_spectrum R :=\n    homeo_of_iso ((LocallyRingedSpace.forget_to_SheafedSpace \u22d9 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 \u27e8x, U.2\u27e9 \u27e8y, hy\u27e9 (by simpa using h) h'\nend\n\ninstance : quasi_sober X.carrier :=\nbegin\n  apply_with (quasi_sober_of_open_cover\n    (set.range (\u03bb x, set.range $ (X.affine_cover.map x).1.base)))\n    { instances := ff },\n  { rintro \u27e8_,i,rfl\u27e9, exact (X.affine_cover.is_open i).base_open.open_range },\n  { rintro \u27e8_,i,rfl\u27e9,\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 \u27e8_, \u27e8_, rfl\u27e9, X.affine_cover.covers x\u27e9 }\nend\n\n/-- A scheme `X` is reduced if all `\ud835\udcaa\u2093(U)` are reduced. -/\nclass is_reduced : Prop :=\n(component_reduced : \u2200 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 [\u2200 x : X.carrier, _root_.is_reduced (X.presheaf.stalk x)] :\n  is_reduced X :=\nbegin\n  refine \u27e8\u03bb U, \u27e8\u03bb s hs, _\u27e9\u27e9,\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 \u27e8n, e\u27e9,\n  obtain \u27e8U, hxU, s, rfl\u27e9 := X.presheaf.germ_exist x g,\n  rw [\u2190 map_pow, \u2190 map_zero (X.presheaf.germ \u27e8x, hxU\u27e9)] at e,\n  obtain \u27e8V, hxV, iU, iV, e'\u27e9 := 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 \u2190 concrete_category.congr_hom (X.presheaf.germ_res iU \u27e8x, hxV\u27e9) s,\n  rw [comp_apply, e', map_zero]\nend\n\nlemma is_reduced_of_open_immersion {X Y : Scheme} (f : X \u27f6 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 _ \u2245 _).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) \u2194 _root_.is_reduced R :=\nbegin\n  refine \u27e8_, \u03bb h, by exactI infer_instance\u27e9,\n  intro h,\n  resetI,\n  haveI : _root_.is_reduced (LocallyRingedSpace.\u0393.obj (op $ Spec.to_LocallyRingedSpace.obj $ op R)),\n  { change _root_.is_reduced ((Scheme.Spec.obj $ op R).presheaf.obj $ op \u22a4), apply_instance },\n  exact is_reduced_of_injective (to_Spec_\u0393 R)\n    ((as_iso $ to_Spec_\u0393 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 \u22a4))] : is_reduced X :=\nbegin\n  haveI : is_reduced (Scheme.Spec.obj (op (Scheme.\u0393.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 \u27f6 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 : \u2200 (X : Scheme) (U : opens X.carrier), Prop)\n  (h\u2081 : \u2200 (X : Scheme) (U : opens X.carrier),\n    (\u2200 (x : U), \u2203 {V} (h : x.1 \u2208 V) (i : V \u27f6 U), P X V) \u2192 P X U)\n  (h\u2082 : \u2200 {X Y} (f : X \u27f6 Y) [hf : is_open_immersion f], \u2203 {U : set X.carrier} {V : set Y.carrier}\n    (hU : U = \u22a4) (hV : V = set.range f.1.base), P X \u27e8U, hU.symm \u25b8 is_open_univ\u27e9 \u2192\n      P Y \u27e8V, hV.symm \u25b8 hf.base_open.open_range\u27e9)\n  (h\u2083 : \u2200 (R : CommRing), P (Scheme.Spec.obj $ op R) \u22a4) :\n  \u2200 (X : Scheme) (U : opens X.carrier), P X U :=\nbegin\n  intros X U,\n  apply h\u2081,\n  intro x,\n  obtain \u27e8_,\u27e8j,rfl\u27e9,hx,i\u27e9 := X.affine_basis_cover_is_basis.exists_subset_of_mem_open x.prop U.2,\n  let U' : opens _ := \u27e8_, (X.affine_basis_cover.is_open j).base_open.open_range\u27e9,\n  let i' : U' \u27f6 U :=\n    hom_of_le i,\n  refine \u27e8U', hx, i', _\u27e9,\n  obtain \u27e8_,_,rfl,rfl,h\u2082'\u27e9 := h\u2082 (X.affine_basis_cover.map j),\n  apply h\u2082',\n  apply h\u2083\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 = \u2205) :\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 \u27e8V, hx, i, H\u27e9 := hx x,\n    unfreezingI { specialize H (X.presheaf.map i.op s) },\n    erw Scheme.basic_open_res at H,\n    rw [hs, \u2190 subtype.coe_injective.eq_iff, opens.empty_eq, opens.inter_eq, inf_bot_eq] at H,\n    specialize H rfl \u27e8x, hx\u27e9,\n    erw Top.presheaf.germ_res_apply at H,\n    exact H },\n  { rintros X Y f hf,\n    have e : (f.val.base) \u207b\u00b9' set.range \u21d1(f.val.base) = \u22a4,\n    { rw [\u2190 set.image_univ, set.preimage_image_eq _ hf.base_open.inj, set.top_eq_univ] },\n    refine \u27e8_, _, e, rfl, _\u27e9,\n    rintros H hX s hs \u27e8_, x, rfl\u27e9,\n    unfreezingI { haveI := is_reduced_of_open_immersion f },\n    specialize H (f.1.c.app _ s) _ \u27e8x, by { change x \u2208 (f.val.base) \u207b\u00b9' _, rw e, trivial }\u27e9,\n    { rw [\u2190 Scheme.preimage_basic_open, hs], ext1, simp [opens.map] },\n    { erw \u2190 PresheafedSpace.stalk_map_germ_apply f.1 \u27e8_,_\u27e9 \u27e8x,_\u27e9 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_\u0393_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 \u22a4 }\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 = \u22a5 \u2194 s = 0 :=\nbegin\n  refine \u27e8eq_zero_of_basic_open_empty s, _\u27e9,\n  rintro rfl,\n  simp,\nend\n\n/-- A scheme `X` is integral if its carrier is nonempty,\nand `\ud835\udcaa\u2093(U)` is an integral domain for each `U \u2260 \u2205`. -/\nclass is_integral : Prop :=\n(nonempty : nonempty X.carrier . tactic.apply_instance)\n(component_integral : \u2200 (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 \u22a4)) :=\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 = \u2205 := 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 : \u00ac is_preirreducible (\u22a4 : set X.carrier) := \u03bb h,\n    H { to_preirreducible_space := \u27e8h\u27e9, to_nonempty := infer_instance },\n  simp_rw [is_preirreducible_iff_closed_union_closed, not_forall, not_or_distrib] at H,\n  rcases H with \u27e8S, T, hS, hT, h\u2081, h\u2082, h\u2083\u27e9,\n  erw not_forall at h\u2082 h\u2083,\n  simp_rw not_forall at h\u2082 h\u2083,\n  haveI : nonempty (\u27e8S\u1d9c, hS.1\u27e9 : opens X.carrier) := \u27e8\u27e8_, h\u2082.some_spec.some_spec\u27e9\u27e9,\n  haveI : nonempty (\u27e8T\u1d9c, hT.1\u27e9 : opens X.carrier) := \u27e8\u27e8_, h\u2083.some_spec.some_spec\u27e9\u27e9,\n  haveI : nonempty (\u27e8S\u1d9c, hS.1\u27e9 \u2294 \u27e8T\u1d9c, hT.1\u27e9 : opens X.carrier) :=\n    \u27e8\u27e8_, or.inl h\u2082.some_spec.some_spec\u27e9\u27e9,\n  let e : X.presheaf.obj _ \u2245 CommRing.of _ := (X.sheaf.is_product_of_disjoint \u27e8_, hS.1\u27e9 \u27e8_, hT.1\u27e9 _)\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 \u27e8hS,hT\u27e9,\n      cases h\u2081 (show x \u2208 \u22a4, 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 \u03bb U hU, \u27e8\u03bb a b e, _,\n    (@@LocallyRingedSpace.component_nontrivial X.to_LocallyRingedSpace U hU).1\u27e9,\n  simp_rw [\u2190 basic_open_eq_bot_iff, \u2190 opens.not_nonempty_iff_eq_bot],\n  by_contra' h,\n  obtain \u27e8_, \u27e8x, hx\u2081, rfl\u27e9, \u27e8x, hx\u2082, e'\u27e9\u27e9 := @@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\u2081.mul hx\u2082,\n  exact e.symm\nend\n\nlemma is_integral_iff_is_irreducible_and_is_reduced :\n  is_integral X \u2194 irreducible_space X.carrier \u2227 is_reduced X :=\n\u27e8\u03bb _, by exactI \u27e8infer_instance, infer_instance\u27e9,\n  \u03bb \u27e8_, _\u27e9, by exactI is_integral_of_is_irreducible_is_reduced X\u27e9\n\nlemma is_integral_of_open_immersion {X Y : Scheme} (f : X \u27f6 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 \u27e8\u27e8_, _, hU.some.prop, rfl\u27e9\u27e9 },\n  exact (as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) :\n    Y.presheaf.obj _ \u2245 _).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) \u2194 is_domain R :=\n\u27e8\u03bb h, by exactI ring_equiv.is_domain ((Scheme.Spec.obj $ op R).presheaf.obj _)\n  (as_iso $ to_Spec_\u0393 R).CommRing_iso_to_ring_equiv, \u03bb h, by exactI infer_instance\u27e9\n\nlemma is_integral_of_is_affine_is_domain [is_affine X] [nonempty X.carrier]\n  [h : is_domain (X.presheaf.obj (op \u22a4))] : is_integral X :=\nbegin\n  haveI : is_integral (Scheme.Spec.obj (op (Scheme.\u0393.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 \u27f6 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 \u2190 basic_open_eq_bot_iff at \u22a2 hx,\n  rw Scheme.basic_open_res at hx,\n  revert hx,\n  contrapose!,\n  simp_rw [\u2190 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\u00ebl Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Ya\u00ebl 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 {\u03b1 \u03b2 : Type*}\n\n/-- The category of bipointed types. -/\nstructure Bipointed : Type.{u + 1} :=\n(X : Type.{u})\n(to_prod : X \u00d7 X)\n\nnamespace Bipointed\n\ninstance : has_coe_to_sort Bipointed Type* := \u27e8X\u27e9\n\nattribute [protected] Bipointed.X\n\n/-- Turns a bipointing into a bipointed type. -/\ndef of {X : Type*} (to_prod : X \u00d7 X) : Bipointed := \u27e8X, to_prod\u27e9\n\nalias of \u2190 prod.Bipointed\n\ninstance : inhabited Bipointed := \u27e8of ((), ())\u27e9\n\n/-- Morphisms in `Bipointed`. -/\n@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=\n(to_fun : X \u2192 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 := \u27e8id, rfl, rfl\u27e9\n\ninstance (X : Bipointed) : inhabited (hom X X) := \u27e8id X\u27e9\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\u27e8g.to_fun \u2218 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]\u27e9\n\nend hom\n\ninstance large_category : large_category Bipointed :=\n{ hom := hom,\n  id := hom.id,\n  comp := @hom.comp,\n  id_comp' := \u03bb _ _ _, hom.ext _ _ rfl,\n  comp_id' := \u03bb _ _ _, hom.ext _ _ rfl,\n  assoc' := \u03bb _ _ _ _ _ _ _, hom.ext _ _ rfl }\n\ninstance concrete_category : concrete_category Bipointed :=\n{ forget := { obj := Bipointed.X, map := @hom.to_fun },\n  forget_faithful := \u27e8@hom.ext\u27e9 }\n\n/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/\n@[simps] def swap : Bipointed \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.swap\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_snd, f.map_fst\u27e9 }\n\n/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/\n@[simps] def swap_equiv : Bipointed \u224c Bipointed :=\nequivalence.mk swap swap\n  (nat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl, rfl\u27e9, inv := \u27e8id, rfl, rfl\u27e9 }) $ \u03bb X Y f, rfl)\n  (nat_iso.of_components (\u03bb X, { hom := \u27e8id, rfl, rfl\u27e9, inv := \u27e8id, rfl, rfl\u27e9 }) $ \u03bb 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 \u2964 Pointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.1\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_fst\u27e9 }\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/\ndef Bipointed_to_Pointed_snd : Bipointed \u2964 Pointed :=\n{ obj := \u03bb X, \u27e8X, X.to_prod.2\u27e9, map := \u03bb X Y f, \u27e8f.to_fun, f.map_snd\u27e9 }\n\n@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :\n  Bipointed_to_Pointed_fst \u22d9 forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :\n  Bipointed_to_Pointed_snd \u22d9 forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :\n  Bipointed.swap \u22d9 Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :\n  Bipointed.swap \u22d9 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} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8option X, X.point, none\u27e9,\n  map := \u03bb X Y f, \u27e8option.map f.to_fun, congr_arg _ f.map_point, rfl\u27e9,\n  map_id' := \u03bb X, Bipointed.hom.ext _ _ option.map_id,\n  map_comp' := \u03bb 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} \u2964 Bipointed :=\n{ obj := \u03bb X, \u27e8option X, none, X.point\u27e9,\n  map := \u03bb X Y f, \u27e8option.map f.to_fun, rfl, congr_arg _ f.map_point\u27e9,\n  map_id' := \u03bb X, Bipointed.hom.ext _ _ option.map_id,\n  map_comp' := \u03bb 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 \u22d9 Bipointed.swap = Pointed_to_Bipointed_snd := rfl\n\n@[simp] lemma Pointed_to_Bipointed_snd_comp :\n  Pointed_to_Bipointed_snd \u22d9 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 \u22a3 Bipointed_to_Pointed_fst :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb X Y, { to_fun := \u03bb f, \u27e8f.to_fun \u2218 option.some, f.map_fst\u27e9,\n                        inv_fun := \u03bb f, \u27e8\u03bb o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl\u27e9,\n                        left_inv := \u03bb f, by { ext, cases x, exact f.map_snd.symm, refl },\n                        right_inv := \u03bb f, Pointed.hom.ext _ _ rfl },\n  hom_equiv_naturality_left_symm' := \u03bb 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 \u22a3 Bipointed_to_Pointed_snd :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb X Y, { to_fun := \u03bb f, \u27e8f.to_fun \u2218 option.some, f.map_snd\u27e9,\n                        inv_fun := \u03bb f, \u27e8\u03bb o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point\u27e9,\n                        left_inv := \u03bb f, by { ext, cases x, exact f.map_fst.symm, refl },\n                        right_inv := \u03bb f, Pointed.hom.ext _ _ rfl },\n  hom_equiv_naturality_left_symm' := \u03bb 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 \u2192 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 \u2192 B)\n(map_op' : \u2200 {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 (\u03bb _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := \u03bb 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) (\u03bb _, A \u2192 B) := to_fun.to_coe_fn\n\n@[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A \u2192 B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : my_hom A B :=\n{ to_fun := f',\n  map_op' := h.symm \u25b8 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 (\u03bb _, B) :=\n(map_op : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u2192 has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to functions from `\u03b1` to `\u03b2`.\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*) (\u03b1 : out_param Sort*) (\u03b2 : out_param $ \u03b1 \u2192 Sort*) :=\n(coe : F \u2192 \u03a0 a : \u03b1, \u03b2 a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F \u03b1 \u03b2` where `\u03b2` depends on `a : \u03b1` -/\n\nvariables (F \u03b1 : Sort*) (\u03b2 : \u03b1 \u2192 Sort*)\n\nnamespace fun_like\n\nvariables {F \u03b1 \u03b2} [i : fun_like F \u03b1 \u03b2]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n  nolint dangerous_instance] -- `\u03b1` and `\u03b2` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (\u03bb _, \u03a0 a : \u03b1, \u03b2 a) := { coe := fun_like.coe }\n\n@[simp] \n\ntheorem coe_injective : function.injective (coe_fn : F \u2192 \u03a0 a : \u03b1, \u03b2 a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a) \u2194 f = g :=\n\u27e8\u03bb h, @coe_injective _ _ _ i _ _ h, \u03bb h, by cases h; refl\u27e9\n\ntheorem ext' {f g : F} (h : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g \u2194 ((f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : \u2200 (x : \u03b1), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g \u2194 (\u2200 x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h\u2081 : f = g) (x : \u03b1) : f x = g x :=\ncongr_fun (congr_arg _ h\u2081) x\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F \u03b1 (\u03bb _, \u03b2)` where `\u03b2` does not depend on `a : \u03b1` -/\n\nvariables {F \u03b1 \u03b2 : Sort*} [i : fun_like F \u03b1 (\u03bb _, \u03b2)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : \u03b1} (h\u2081 : f = g) (h\u2082 : x = y) : f x = g y :=\ncongr (congr_arg _ h\u2081) h\u2082\n\nprotected lemma congr_arg (f : F) {x y : \u03b1} (h\u2082 : x = y) : f x = f y :=\ncongr_arg _ h\u2082\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 \u2192 list pexpr \u2192 On_args -- On conclut par ... (appliqu\u00e9 \u00e0 ...)\n| aply : pexpr \u2192 On_args             -- On applique ...\n| aply_at : pexpr \u2192 list pexpr \u2192 On_args  -- On applique ... \u00e0 ...\n| rwrite : interactive.rw_rules_t \u2192 option name \u2192 option pexpr \u2192 On_args           -- On r\u00e9\u00e9crit via ... (dans ... (qui devient ...))\n| rwrite_all : interactive.rw_rules_t \u2192 On_args -- On r\u00e9\u00e9crit via ... partout\n| compute : On_args                  -- On calcule\n| compute_at : name \u2192 On_args        -- On calcule dans ...\n| linar : list pexpr \u2192 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\u00e9gation (dans ... (qui devient ...))\n| discussion : pexpr \u2192 On_args       -- On discute en utilisant ... [cases]\n| discussion_hyp : pexpr \u2192 On_args       -- On discute selon que ... [by_cases]\n| deplie : list name \u2192 On_args -- On d\u00e9plie ...\n| deplie_at : list name \u2192 loc \u2192 option pexpr \u2192 On_args -- On d\u00e9plie ... dans ... (qui devient ...)\n| rname : name \u2192 name \u2192 option loc \u2192 option pexpr \u2192 On_args -- On renomme ... en ... (dans ... (qui devient ...))\n| oubli : list name \u2192 On_args -- pour clear\n| reforml : name \u2192 pexpr \u2192 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\u00e9 \u00e0 ...) / On applique ... (\u00e0 ...) / On calcule (dans ...) / On r\u00e9\u00e9crit via ... (dans ... (qui devient ...)) / On combine ... / On contrapose / On discute selon ... / On discute selon que ... / On d\u00e9plie ... (dans ... (qui devient ...)) / On renomme ... en ... (dans ... (qui devient ...)) / On oublie ... / On reformule ... en ... / On pousse la n\u00e9gation (dans ... (qui devient ...))\" $\n(exct_aply <$> (tk \"conclut\" *> tk \"par\" *> texpr) <*> applique_a_parser) <|>\n(do { e \u2190 tk \"applique\" *> texpr,\n      aply_at e <$> (tk \"\u00e0\" *> 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 \u2190 tk \"r\u00e9\u00e9crit\" *> 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\u00e9gation\" *> (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 \u2190 tk \"d\u00e9plie\" *> ident*,\n     do { place \u2190 tk \"dans\" *> ident,\n          deplie_at ids (loc.ns [place]) <$> qui_devient_parser } <|> \n     pure (deplie ids) } <|>\ndo { old \u2190 tk \"renomme\" *> ident <* tk \"en\",\n     new \u2190 ident,\n     do { place \u2190 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\u00e9monstration -/\n@[interactive]\nmeta def On : parse On_parser \u2192 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 \u2190 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 \u2190 get_local hyp, \n                                                          enewhyp \u2190 to_expr newhyp,\n                                                          infer_type ne >>= unify enewhyp\n                          | (_, some n) := fail \"On ne peut pas utiliser \u00ab qui devient \u00bb lorsqu'on r\u00e9\u00e9crit 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' \u2190 le.mmap to_expr >>= split_ands,\n                   linarith ff tt le' <|> fail \"Combiner ces faits ce suffit pas.\"\n| (contrap push) := do \n      `(%%P \u2192 %%Q) \u2190 target | fail \"On ne peut pas contraposer, le but n'est pas une implication\",\n      cp \u2190 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 \u2190 to_expr pe,\n                                `(%%P \u2228 %%Q) \u2190 infer_type e <|> fail \"Cette expression n'est pas une disjonction.\",\n                                tgt \u2190 target, \n                                `[refine (or.elim %%e _ _)],\n                                all_goals (try (clear e)) >> skip)\n| (discussion_hyp pe) := do e \u2190 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 \u2190 get_local hyp, \n                                                                         enewhyp \u2190 to_expr newhyp,\n                                                                         infer_type ne >>= unify enewhyp\n                                | (_, some n) := fail \"On ne peut pas utiliser \u00ab qui devient \u00bb lorsqu'on d\u00e9plie 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 \u2190 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 \u2190 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 \u2190 get_local n, e \u2190 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 \u2190 get_local hyp,\n                                                             enewhyp \u2190 to_expr stuff,\n                                                             infer_type e >>= unify enewhyp\n                              | (none, some stuff) := fail \"On ne peut pas indiquer \u00ab qui devient \u00bb quand on pousse la n\u00e9gation dans le but.\"\n                              | _ := skip\n                              end\n\n\nend tactic\n\nexample (P Q R : Prop) (hRP : R \u2192 P) (hR : R) (hQ : Q) : P :=\nbegin\n  fail_if_success { On conclut par hRP appliqu\u00e9 \u00e0 hQ },\n  On conclut par hRP appliqu\u00e9 \u00e0 hR,\nend\n\nexample (P : \u2115 \u2192 Prop) (h : \u2200 n, P n) : P 0 :=\nbegin\n  On conclut par h appliqu\u00e9 \u00e0 _,\nend\n\nexample (P : \u2115 \u2192 Prop) (h : \u2200 n, P n) : P 0 :=\nbegin\n  On conclut par h,\nend\n    \n    \nexample {a b : \u2115}: a + b = b + a :=\nbegin\n  On calcule,\nend \n\nexample {a b : \u2115} (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 : \u2200 n : \u2115, true) : true :=\nbegin\n  On conclut par h appliqu\u00e9 \u00e0 0,\nend\n\nexample (h : true \u2192 true) : true :=\nbegin\n  On applique h,\n  trivial,\nend\n\nexample (h : \u2200 n k : \u2115, true) : true :=\nbegin\n  On conclut par h appliqu\u00e9 \u00e0 [0, 1],\nend\n\nexample (a b : \u2115) (h : a < b) : a \u2264 b :=\nbegin\n  On conclut par h,\nend\n\nexample (a b c : \u2115) (h : a < b \u2227 a < c) : a \u2264 b :=\nbegin\n  On conclut par h,\nend\n\nexample (a b c : \u2115) (h : a \u2264 b) (h' : b \u2264 c) : a \u2264 c :=\nbegin\n  On combine [h, h'],\nend\n\nexample (a b c : \u2124) (h : a = b + c) (h' : b - a = c) : c = 0 :=\nbegin\n  On combine [h, h'],\nend\n\nexample (a b c : \u2115) (h : a \u2264 b) (h' : b \u2264 c \u2227 a+b \u2264 a+c) : a \u2264 c :=\nbegin\n  On combine [h, h'],\nend\n\nexample (a b c : \u2115) (h : a = b) (h' : a = c) : b = c :=\nbegin\n  On r\u00e9\u00e9crit via \u2190 h,\n  On conclut par h',\nend\n\nexample (a b c : \u2115) (h : a = b) (h' : a = c) : b = c :=\nbegin\n  On r\u00e9\u00e9crit via h dans h',\n  On conclut par h',\nend\n\nexample (f : \u2115 \u2192 \u2115) (n : \u2115) (h : n > 0 \u2192 f n = 0) (hn : n > 0): f n = 0 :=\nbegin\n  On r\u00e9\u00e9crit via h,\n  exact hn\nend\n\nexample (f : \u2115 \u2192 \u2115) (n : \u2115) (h : \u2200 n > 0, f n = 0) : f 1 = 0 :=\nbegin\n  On r\u00e9\u00e9crit via h,\n  norm_num\nend\n\nexample (a b c : \u2115) (h : a = b) (h' : a = c) : b = c :=\nbegin\n  success_if_fail { On r\u00e9\u00e9crit via h dans h' qui devient a = c },\n  On r\u00e9\u00e9crit via h dans h' qui devient b = c,\n  On conclut par h',\nend\n\nexample (a b c : \u2115) (h : a = b) (h' : a = c) : a = c :=\nbegin\n  On r\u00e9\u00e9crit via h partout,\n  On conclut par h',\nend\n\nexample (P Q R : Prop) (h : P \u2192 Q) (h' : P) : Q :=\nbegin\n  On applique h \u00e0 h',\n  On conclut par h',\nend\n\nexample (P Q R : Prop) (h : P \u2192 Q \u2192 R) (hP : P) (hQ : Q) : R :=\nbegin\n  On conclut par h appliqu\u00e9 \u00e0 [hP, hQ],\nend\n\nexample (f : \u2115 \u2192 \u2115) (a b : \u2115) (h : a = b) : f a = f b :=\nbegin\n  On applique f \u00e0 h,\n  On conclut par h,\nend\n\nexample (P : \u2115 \u2192 Prop) (h : \u2200 n, P n) : P 0 :=\nbegin\n  On applique h \u00e0 0,\n  On conclut par h\nend\n\nexample (x : \u211d) : (\u2200 \u03b5 > 0, x \u2264 \u03b5) \u2192 x \u2264 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 (\u03b5 : \u211d) (h : \u03b5 > 0) : \u03b5 \u2265 0 := by On conclut par h\nexample (\u03b5 : \u211d) (h : \u03b5 > 0) : \u03b5/2 > 0 := by On conclut par h\nexample (\u03b5 : \u211d) (h : \u03b5 > 0) : \u03b5 \u2265 -1 := by On conclut par h\nexample (\u03b5 : \u211d) (h : \u03b5 > 0) : \u03b5/2 \u2265 -3 := by On conclut par h\n\nexample (x : \u211d) (h : x = 3) : 2*x = 6 := by On conclut par h\n\nexample (x : \u211d) : (\u2200 \u03b5 > 0, x \u2264 \u03b5) \u2192 x \u2264 0 :=\nbegin\n  On contrapose simplement,\n  intro h,\n  On pousse la n\u00e9gation,\n  On pousse la n\u00e9gation dans h,\n  use x/2,\n  split,\n    On conclut par h, -- linarith\n  On conclut par h, -- linarith\nend\n\nexample (x : \u211d) : (\u2200 \u03b5 > 0, x \u2264 \u03b5) \u2192 x \u2264 0 :=\nbegin\n  On contrapose simplement,\n  intro h,\n  success_if_fail { On pousse la n\u00e9gation qui devient 0 < x },\n  On pousse la n\u00e9gation,\n  success_if_fail { On pousse la n\u00e9gation dans h qui devient \u2203 (\u03b5 : \u211d), \u03b5 > 0 \u2227 \u03b5 < x },\n  On pousse la n\u00e9gation 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 : (\u2200 n : \u2115, false) \u2192 0 = 1 :=\nbegin\n  On contrapose,\n  On calcule,\nend\n\nexample (P Q : Prop) (h : P \u2228 Q) : true :=\nbegin\n  On discute en utilisant h,\n  all_goals { intro, trivial }\nend\n\nexample (P : Prop) (hP\u2081 : P \u2192 true) (hP\u2082 : \u00ac P \u2192 true): true :=\nbegin\n  On discute selon que P,\n  intro h,\n  exact hP\u2081 h,\n  intro h,\n  exact hP\u2082 h,\nend\n\ndef f (n : \u2115) := 2*n\n\nexample : f 2 = 4 :=\nbegin\n  On d\u00e9plie f,\n  refl,\nend\n\nexample (h : f 2 = 4) : true \u2192 true :=\nbegin\n  On d\u00e9plie f dans h,\n  guard_hyp_strict h : 2*2 = 4,\n  exact id\nend\n\nexample (h : f 2 = 4) : true \u2192 true :=\nbegin\n  success_if_fail { On d\u00e9plie f dans h qui devient 2*2 = 5 },\n  On d\u00e9plie f dans h qui devient 2*2 = 4,\n  exact id\nend\n\nexample (P : \u2115 \u2192 \u2115 \u2192 Prop) (h : \u2200 n : \u2115, \u2203 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 : \u2200 p, \u2203 l, P p l,\n  trivial\nend\n\nexample (P : \u2115 \u2192 \u2115 \u2192 Prop) (h : \u2200 n : \u2115, \u2203 k, P n k) : true :=\nbegin\n  On renomme n en p dans h qui devient \u2200 p, \u2203 k, P p k,\n  success_if_fail { On renomme k en l dans h qui devient \u2200 p, \u2203 j, P p j },\n  On renomme k en l dans h qui devient \u2200 p, \u2203 l, P p l,\n  trivial\nend\n\nexample (P : \u2115 \u2192 \u2115 \u2192 Prop) : (\u2200 n : \u2115, \u2203 k, P n k) \u2228 true :=\nbegin\n  On renomme n en p,\n  On renomme k en l,\n  guard_target_strict (\u2200 p, \u2203 l, P p l) \u2228 true,\n  right,\n  trivial\nend\n\nexample (a b c : \u2115) : 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) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.auto_cases\nimport Mathlib.tactic.chain\nimport Mathlib.tactic.norm_cast\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\nnamespace tactic\n\n\nnamespace tidy\n\n\n/-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics\ncalled by `tidy`. -/\nend tidy\n\n\nnamespace interactive\n\n\n/-- Use a variety of conservative tactics to solve goals.\n\n`tidy?` reports back the tactic script it found. As an example\n```lean\nexample : \u2200 x : unit, x = unit.star :=\nbegin\n  tidy? -- Prints the trace message: \"Try this: intros x, exact dec_trivial\"\nend\n```\n\nThe default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.\nThis list can be overridden using `tidy { tactics := ... }`.\n(The list must be a `list` of `tactic string`, so that `tidy?`\ncan report a usable tactic script.)\n\nTactics can also be added to the list by tagging them (locally) with the\n`[tidy]` attribute. -/\nend interactive\n\n\n/-- Invoking the hole command `tidy` (\"Use `tidy` to complete the goal\") runs the tactic of\nthe same name, replacing the hole with the tactic script `tidy` produces.\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/tidy_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658975016245987, "lm_q2_score": 0.08389038297499259, "lm_q1q2_score": 0.03075335453583561}}
{"text": "/-\nCopyright (c) 2022 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Aesop\n\ndef Foo := True\n\nexample : Foo := by\n  fail_if_success aesop (options := { terminal := true })\n  simp [Foo]\n\nopen Lean.Elab.Tactic in\n@[aesop safe]\ndef myTactic : TacticM Unit := do\n  evalTactic $ \u2190 `(tactic| rw [Foo])\n\nexample : Foo := by\n  aesop\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/run/CustomTactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.0715912034062289, "lm_q1q2_score": 0.030520876892162527}}
{"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 \u2964 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\u2081 v\u2082 v\u2083 v\u2084 u\u2081 u\u2082 u\u2083 u\u2084\n\nvariables {J : Type u\u2081} [category.{v\u2081} J] {K : Type u\u2082} [category.{v\u2082} K]\nvariables {C : Type u\u2083} [category.{v\u2083} C] {D : Type u\u2084} [category.{v\u2084} D]\n\n/-- Construct an object of the category `(\u0394 \u2193 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 \u2964 C) : cone F \u2964 costructured_arrow (const J) F :=\n{ obj := \u03bb c, costructured_arrow.mk c.\u03c0,\n  map := \u03bb 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 `(\u0394 \u2193 F)`. This is part of an\n    equivalence, see `cone.equiv_costructured_arrow`. -/\n@[simps]\ndef cone.from_costructured_arrow (F : J \u2964 C) : costructured_arrow (const J) F \u2964 cone F :=\n{ obj := \u03bb c, \u27e8c.left, c.hom\u27e9,\n  map := \u03bb c d f,\n  { hom := f.left,\n    w' := \u03bb 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 `(\u0394 \u2193 F)`, where `\u0394` is the constant\n    functor. -/\n@[simps]\ndef cone.equiv_costructured_arrow (F : J \u2964 C) : cone F \u224c 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 (\u03bb 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 \u2964 C} (c : cone F) : is_limit c \u2243 is_terminal c :=\nis_limit.iso_unique_cone_morphism.to_equiv.trans\n{ to_fun := \u03bb h, by exactI is_terminal.of_unique _,\n  inv_fun := \u03bb h s, \u27e8\u27e8is_terminal.from h s\u27e9, \u03bb a, is_terminal.hom_ext h a _\u27e9,\n  left_inv := by tidy,\n  right_inv := by tidy }\n\nlemma has_limit_iff_has_terminal_cone (F : J \u2964 C) : has_limit F \u2194 has_terminal (cone F) :=\n\u27e8\u03bb h, by exactI (cone.is_limit_equiv_is_terminal _ (limit.is_limit F)).has_terminal,\n \u03bb h, \u27e8\u27e8by exactI \u27e8\u22a4_ _, (cone.is_limit_equiv_is_terminal _).symm terminal_is_terminal\u27e9\u27e9\u27e9\u27e9\n\nlemma has_limits_of_shape_iff_is_left_adjoint_const :\n  has_limits_of_shape J C \u2194 nonempty (is_left_adjoint (const J : C \u2964 _)) :=\ncalc has_limits_of_shape J C\n      \u2194 \u2200 F : J \u2964 C, has_limit F : \u27e8\u03bb h, h.has_limit, \u03bb h, by exactI has_limits_of_shape.mk\u27e9\n  ... \u2194 \u2200 F : J \u2964 C, has_terminal (cone F) : forall_congr has_limit_iff_has_terminal_cone\n  ... \u2194 \u2200 F : J \u2964 C, has_terminal (costructured_arrow (const J) F) :\n    forall_congr $ \u03bb F, (cone.equiv_costructured_arrow F).has_terminal_iff\n  ... \u2194 nonempty (is_left_adjoint (const J : C \u2964 _)) :\n    nonempty_is_left_adjoint_iff_has_terminal_costructured_arrow.symm\n\nlemma is_limit.lift_cone_morphism_eq_is_terminal_from {F : J \u2964 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 \u2964 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 \u2964 cone F'` preserves terminal objects, it preserves limit cones. -/\ndef is_limit.of_preserves_cone_terminal {F : J \u2964 C} {F' : K \u2964 D} (G : cone F \u2964 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 \u2964 cone F'` reflects terminal objects, it reflects limit cones. -/\ndef is_limit.of_reflects_cone_terminal {F : J \u2964 C} {F' : K \u2964 D} (G : cone F \u2964 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 \u2193 \u0394)` 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 \u2964 C) : cocone F \u2964 structured_arrow F (const J) :=\n{ obj := \u03bb c, structured_arrow.mk c.\u03b9,\n  map := \u03bb 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 \u2193 \u0394)`. This is part of an\n    equivalence, see `cocone.equiv_structured_arrow`. -/\n@[simps]\ndef cocone.from_structured_arrow (F : J \u2964 C) : structured_arrow F (const J) \u2964 cocone F :=\n{ obj := \u03bb c, \u27e8c.right, c.hom\u27e9,\n  map := \u03bb c d f,\n  { hom := f.right,\n    w' := \u03bb 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 \u2193 \u0394)`, where `\u0394` is the constant\n    functor. -/\n@[simps]\ndef cocone.equiv_structured_arrow (F : J \u2964 C) : cocone F \u224c 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 (\u03bb 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 \u2964 C} (c : cocone F) : is_colimit c \u2243 is_initial c :=\nis_colimit.iso_unique_cocone_morphism.to_equiv.trans\n{ to_fun := \u03bb h, by exactI is_initial.of_unique _,\n  inv_fun := \u03bb h s, \u27e8\u27e8is_initial.to h s\u27e9, \u03bb a, is_initial.hom_ext h a _\u27e9,\n  left_inv := by tidy,\n  right_inv := by tidy }\n\nlemma has_colimit_iff_has_initial_cocone (F : J \u2964 C) : has_colimit F \u2194 has_initial (cocone F) :=\n\u27e8\u03bb h, by exactI (cocone.is_colimit_equiv_is_initial _ (colimit.is_colimit F)).has_initial,\n \u03bb h, \u27e8\u27e8by exactI \u27e8\u22a5_ _, (cocone.is_colimit_equiv_is_initial _).symm initial_is_initial\u27e9\u27e9\u27e9\u27e9\n\nlemma has_colimits_of_shape_iff_is_right_adjoint_const :\n  has_colimits_of_shape J C \u2194 nonempty (is_right_adjoint (const J : C \u2964 _)) :=\ncalc has_colimits_of_shape J C\n      \u2194 \u2200 F : J \u2964 C, has_colimit F : \u27e8\u03bb h, h.has_colimit, \u03bb h, by exactI has_colimits_of_shape.mk\u27e9\n  ... \u2194 \u2200 F : J \u2964 C, has_initial (cocone F) : forall_congr has_colimit_iff_has_initial_cocone\n  ... \u2194 \u2200 F : J \u2964 C, has_initial (structured_arrow F (const J)) :\n    forall_congr $ \u03bb F, (cocone.equiv_structured_arrow F).has_initial_iff\n  ... \u2194 nonempty (is_right_adjoint (const J : C \u2964 _)) :\n    nonempty_is_right_adjoint_iff_has_initial_structured_arrow.symm\n\nlemma is_colimit.desc_cocone_morphism_eq_is_initial_to {F : J \u2964 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 \u2964 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 \u2964 cocone F'` preserves initial objects, it preserves colimit cocones. -/\ndef is_colimit.of_preserves_cocone_initial {F : J \u2964 C} {F' : K \u2964 D} (G : cocone F \u2964 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 \u2964 cocone F'` reflects initial objects, it reflects colimit cocones. -/\ndef is_colimit.of_reflects_cocone_initial {F : J \u2964 C} {F' : K \u2964 D} (G : cocone F \u2964 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\u2081 P\u2082` (notation: `P\u2081 \u2243\u1d43[k] P\u2082`) to be the type of affine\nequivalences between `P\u2081` and `P\u2082, 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\u2081 : Type u_2) (P\u2082 : Type u_3) {V\u2081 : Type u_4}\n    {V\u2082 : Type u_5} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082]\n    extends P\u2081 \u2243 P\u2082 where\n  linear : linear_equiv k V\u2081 V\u2082\n  map_vadd' : \u2200 (p : P\u2081) (v : V\u2081), coe_fn _to_equiv (v +\u1d65 p) = coe_fn linear v +\u1d65 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 \u2192 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\u2081 : Type u_2} {V\u2082 : Type u_3} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_comm_group V\u2082] [semimodule k V\u2082] (e : linear_equiv k V\u2081 V\u2082) :\n    affine_equiv k V\u2081 V\u2082 :=\n  affine_equiv.mk (to_equiv e) e sorry\n\n@[simp] theorem coe_to_affine_equiv {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_comm_group V\u2082] [semimodule k V\u2082]\n    (e : linear_equiv k V\u2081 V\u2082) : \u21d1(to_affine_equiv e) = \u21d1e :=\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\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] : affine_equiv k P\u2081 P\u2081 :=\n  mk (equiv.refl P\u2081) (linear_equiv.refl k V\u2081) sorry\n\n@[simp] theorem coe_refl (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] : \u21d1(refl k P\u2081) = id :=\n  rfl\n\ntheorem refl_apply (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) : coe_fn (refl k P\u2081) x = x :=\n  rfl\n\n@[simp] theorem to_equiv_refl (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] :\n    to_equiv (refl k P\u2081) = equiv.refl P\u2081 :=\n  rfl\n\n@[simp] theorem linear_refl (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] :\n    linear (refl k P\u2081) = linear_equiv.refl k V\u2081 :=\n  rfl\n\n@[simp] theorem map_vadd {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) (p : P\u2081)\n    (v : V\u2081) : coe_fn e (v +\u1d65 p) = coe_fn (linear e) v +\u1d65 coe_fn e p :=\n  map_vadd' e p v\n\n@[simp] theorem coe_to_equiv {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    \u21d1(to_equiv e) = \u21d1e :=\n  rfl\n\n/-- Reinterpret an `affine_equiv` as an `affine_map`. -/\ndef to_affine_map {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6} {P\u2082 : Type u_7}\n    [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082]\n    [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) : affine_map k P\u2081 P\u2082 :=\n  affine_map.mk (\u21d1e) (\u2191(linear e)) (map_vadd' e)\n\n@[simp] theorem coe_to_affine_map {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    \u21d1(to_affine_map e) = \u21d1e :=\n  rfl\n\n@[simp] theorem to_affine_map_mk {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (f : P\u2081 \u2243 P\u2082)\n    (f' : linear_equiv k V\u2081 V\u2082)\n    (h : \u2200 (p : P\u2081) (v : V\u2081), coe_fn f (v +\u1d65 p) = coe_fn f' v +\u1d65 coe_fn f p) :\n    to_affine_map (mk f f' h) = affine_map.mk (\u21d1f) (\u2191f') h :=\n  rfl\n\n@[simp] theorem linear_to_affine_map {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    affine_map.linear (to_affine_map e) = \u2191(linear e) :=\n  rfl\n\ntheorem injective_to_affine_map {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] : function.injective to_affine_map :=\n  sorry\n\n@[simp] theorem to_affine_map_inj {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] {e : affine_equiv k P\u2081 P\u2082}\n    {e' : affine_equiv k P\u2081 P\u2082} : to_affine_map e = to_affine_map e' \u2194 e = e' :=\n  function.injective.eq_iff injective_to_affine_map\n\ntheorem ext {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6} {P\u2082 : Type u_7} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082]\n    [add_torsor V\u2082 P\u2082] {e : affine_equiv k P\u2081 P\u2082} {e' : affine_equiv k P\u2081 P\u2082}\n    (h : \u2200 (x : P\u2081), 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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] :\n    function.injective fun (e : affine_equiv k P\u2081 P\u2082) (x : P\u2081) => coe_fn e x :=\n  sorry\n\n@[simp] theorem coe_fn_inj {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] {e : affine_equiv k P\u2081 P\u2082}\n    {e' : affine_equiv k P\u2081 P\u2082} : \u21d1e = \u21d1e' \u2194 e = e' :=\n  function.injective.eq_iff injective_coe_fn\n\ntheorem injective_to_equiv {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] : function.injective to_equiv :=\n  fun (e e' : affine_equiv k P\u2081 P\u2082) (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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] {e : affine_equiv k P\u2081 P\u2082}\n    {e' : affine_equiv k P\u2081 P\u2082} : to_equiv e = to_equiv e' \u2194 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\u2081 \u2243 P\u2082`, a linear equivalece\n`e' : V\u2081 \u2243\u2097[k] V\u2082`, and a point `p` such that for any other point `p'` we have\n`e p' = e' (p' -\u1d65 p) +\u1d65 e p`. -/\ndef mk' {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6} {P\u2082 : Type u_7} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082]\n    [add_torsor V\u2082 P\u2082] (e : P\u2081 \u2243 P\u2082) (e' : linear_equiv k V\u2081 V\u2082) (p : P\u2081)\n    (h : \u2200 (p' : P\u2081), coe_fn e p' = coe_fn e' (p' -\u1d65 p) +\u1d65 coe_fn e p) : affine_equiv k P\u2081 P\u2082 :=\n  mk e e' sorry\n\n@[simp] theorem coe_mk' {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : P\u2081 \u2243 P\u2082)\n    (e' : linear_equiv k V\u2081 V\u2082) (p : P\u2081)\n    (h : \u2200 (p' : P\u2081), coe_fn e p' = coe_fn e' (p' -\u1d65 p) +\u1d65 coe_fn e p) : \u21d1(mk' e e' p h) = \u21d1e :=\n  rfl\n\n@[simp] theorem to_equiv_mk' {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : P\u2081 \u2243 P\u2082)\n    (e' : linear_equiv k V\u2081 V\u2082) (p : P\u2081)\n    (h : \u2200 (p' : P\u2081), coe_fn e p' = coe_fn e' (p' -\u1d65 p) +\u1d65 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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : P\u2081 \u2243 P\u2082)\n    (e' : linear_equiv k V\u2081 V\u2082) (p : P\u2081)\n    (h : \u2200 (p' : P\u2081), coe_fn e p' = coe_fn e' (p' -\u1d65 p) +\u1d65 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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6} {P\u2082 : Type u_7} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082]\n    [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) : affine_equiv k P\u2082 P\u2081 :=\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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    equiv.symm (to_equiv e) = to_equiv (symm e) :=\n  rfl\n\n@[simp] theorem symm_linear {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    linear_equiv.symm (linear e) = linear (symm e) :=\n  rfl\n\nprotected theorem bijective {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    function.bijective \u21d1e :=\n  equiv.bijective (to_equiv e)\n\nprotected theorem surjective {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    function.surjective \u21d1e :=\n  equiv.surjective (to_equiv e)\n\nprotected theorem injective {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    function.injective \u21d1e :=\n  equiv.injective (to_equiv e)\n\n@[simp] theorem range_eq {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    set.range \u21d1e = set.univ :=\n  function.surjective.range_eq (affine_equiv.surjective e)\n\n@[simp] theorem apply_symm_apply {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) (p : P\u2082) :\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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) (p : P\u2081) :\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\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) {p\u2081 : P\u2081}\n    {p\u2082 : P\u2082} : coe_fn e p\u2081 = p\u2082 \u2194 p\u2081 = coe_fn (symm e) p\u2082 :=\n  equiv.apply_eq_iff_eq_symm_apply (to_equiv e)\n\n@[simp] theorem apply_eq_iff_eq {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) {p\u2081 : P\u2081}\n    {p\u2082 : P\u2081} : coe_fn e p\u2081 = coe_fn e p\u2082 \u2194 p\u2081 = p\u2082 :=\n  equiv.apply_eq_iff_eq (to_equiv e)\n\n@[simp] theorem symm_refl {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] : symm (refl k P\u2081) = refl k P\u2081 :=\n  rfl\n\n/-- Composition of two `affine_equiv`alences, applied left to right. -/\ndef trans {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {V\u2083 : Type u_4} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} {P\u2083 : Type u_8} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081]\n    [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] [add_comm_group V\u2083]\n    [semimodule k V\u2083] [add_torsor V\u2083 P\u2083] (e : affine_equiv k P\u2081 P\u2082) (e' : affine_equiv k P\u2082 P\u2083) :\n    affine_equiv k P\u2081 P\u2083 :=\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\u2081 : Type u_2} {V\u2082 : Type u_3} {V\u2083 : Type u_4}\n    {P\u2081 : Type u_6} {P\u2082 : Type u_7} {P\u2083 : Type u_8} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081]\n    [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] [add_comm_group V\u2083]\n    [semimodule k V\u2083] [add_torsor V\u2083 P\u2083] (e : affine_equiv k P\u2081 P\u2082) (e' : affine_equiv k P\u2082 P\u2083) :\n    \u21d1(trans e e') = \u21d1e' \u2218 \u21d1e :=\n  rfl\n\ntheorem trans_apply {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {V\u2083 : Type u_4} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} {P\u2083 : Type u_8} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081]\n    [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] [add_comm_group V\u2083]\n    [semimodule k V\u2083] [add_torsor V\u2083 P\u2083] (e : affine_equiv k P\u2081 P\u2082) (e' : affine_equiv k P\u2082 P\u2083)\n    (p : P\u2081) : coe_fn (trans e e') p = coe_fn e' (coe_fn e p) :=\n  rfl\n\ntheorem trans_assoc {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {V\u2083 : Type u_4} {V\u2084 : Type u_5}\n    {P\u2081 : Type u_6} {P\u2082 : Type u_7} {P\u2083 : Type u_8} {P\u2084 : Type u_9} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082]\n    [add_comm_group V\u2083] [semimodule k V\u2083] [add_torsor V\u2083 P\u2083] [add_comm_group V\u2084] [semimodule k V\u2084]\n    [add_torsor V\u2084 P\u2084] (e\u2081 : affine_equiv k P\u2081 P\u2082) (e\u2082 : affine_equiv k P\u2082 P\u2083)\n    (e\u2083 : affine_equiv k P\u2083 P\u2084) : trans (trans e\u2081 e\u2082) e\u2083 = trans e\u2081 (trans e\u2082 e\u2083) :=\n  ext fun (_x : P\u2081) => rfl\n\n@[simp] theorem trans_refl {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    trans e (refl k P\u2082) = e :=\n  ext fun (_x : P\u2081) => rfl\n\n@[simp] theorem refl_trans {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    trans (refl k P\u2081) e = e :=\n  ext fun (_x : P\u2081) => rfl\n\n@[simp] theorem trans_symm {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    trans e (symm e) = refl k P\u2081 :=\n  ext (symm_apply_apply e)\n\n@[simp] theorem symm_trans {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) :\n    trans (symm e) e = refl k P\u2082 :=\n  ext (apply_symm_apply e)\n\n@[simp] theorem apply_line_map {k : Type u_1} {V\u2081 : Type u_2} {V\u2082 : Type u_3} {P\u2081 : Type u_6}\n    {P\u2082 : Type u_7} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    [add_comm_group V\u2082] [semimodule k V\u2082] [add_torsor V\u2082 P\u2082] (e : affine_equiv k P\u2081 P\u2082) (a : P\u2081)\n    (b : P\u2081) (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\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] : group (affine_equiv k P\u2081 P\u2081) :=\n  group.mk (fun (e e' : affine_equiv k P\u2081 P\u2081) => trans e' e) sorry (refl k P\u2081) trans_refl refl_trans\n    symm\n    (div_inv_monoid.div._default (fun (e e' : affine_equiv k P\u2081 P\u2081) => trans e' e) sorry (refl k P\u2081)\n      trans_refl refl_trans symm)\n    trans_symm\n\ntheorem one_def {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] : 1 = refl k P\u2081 :=\n  rfl\n\n@[simp] theorem coe_one {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] : \u21d11 = id :=\n  rfl\n\ntheorem mul_def {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (e : affine_equiv k P\u2081 P\u2081) (e' : affine_equiv k P\u2081 P\u2081) :\n    e * e' = trans e' e :=\n  rfl\n\n@[simp] theorem coe_mul {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (e : affine_equiv k P\u2081 P\u2081) (e' : affine_equiv k P\u2081 P\u2081) :\n    \u21d1(e * e') = \u21d1e \u2218 \u21d1e' :=\n  rfl\n\ntheorem inv_def {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (e : affine_equiv k P\u2081 P\u2081) : e\u207b\u00b9 = symm e :=\n  rfl\n\n/-- The map `v \u21a6 v +\u1d65 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\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (b : P\u2081) : affine_equiv k V\u2081 P\u2081 :=\n  mk (equiv.vadd_const b) (linear_equiv.refl k V\u2081) sorry\n\n@[simp] theorem linear_vadd_const (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (b : P\u2081) :\n    linear (vadd_const k b) = linear_equiv.refl k V\u2081 :=\n  rfl\n\n@[simp] theorem vadd_const_apply (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (b : P\u2081) (v : V\u2081) :\n    coe_fn (vadd_const k b) v = v +\u1d65 b :=\n  rfl\n\n@[simp] theorem vadd_const_symm_apply (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (b : P\u2081) (p : P\u2081) :\n    coe_fn (symm (vadd_const k b)) p = p -\u1d65 b :=\n  rfl\n\n/-- `p' \u21a6 p -\u1d65 p'` as an equivalence. -/\ndef const_vsub (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (p : P\u2081) : affine_equiv k P\u2081 V\u2081 :=\n  mk (equiv.const_vsub p) (linear_equiv.neg k) sorry\n\n@[simp] theorem coe_const_vsub (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (p : P\u2081) :\n    \u21d1(const_vsub k p) = has_vsub.vsub p :=\n  rfl\n\n@[simp] theorem coe_const_vsub_symm (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (p : P\u2081) :\n    \u21d1(symm (const_vsub k p)) = fun (v : V\u2081) => -v +\u1d65 p :=\n  rfl\n\n/-- The map `p \u21a6 v +\u1d65 p` as an affine automorphism of an affine space. -/\ndef const_vadd (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (v : V\u2081) : affine_equiv k P\u2081 P\u2081 :=\n  mk (equiv.const_vadd P\u2081 v) (linear_equiv.refl k V\u2081) sorry\n\n@[simp] theorem linear_const_vadd (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (v : V\u2081) :\n    linear (const_vadd k P\u2081 v) = linear_equiv.refl k V\u2081 :=\n  rfl\n\n@[simp] theorem const_vadd_apply (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (v : V\u2081) (p : P\u2081) :\n    coe_fn (const_vadd k P\u2081 v) p = v +\u1d65 p :=\n  rfl\n\n@[simp] theorem const_vadd_symm_apply (k : Type u_1) {V\u2081 : Type u_2} (P\u2081 : Type u_6) [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (v : V\u2081) (p : P\u2081) :\n    coe_fn (symm (const_vadd k P\u2081 v)) p = -v +\u1d65 p :=\n  rfl\n\n/-- Point reflection in `x` as a permutation. -/\ndef point_reflection (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) : affine_equiv k P\u2081 P\u2081 :=\n  trans (const_vsub k x) (vadd_const k x)\n\ntheorem point_reflection_apply (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) (y : P\u2081) :\n    coe_fn (point_reflection k x) y = x -\u1d65 y +\u1d65 x :=\n  rfl\n\n@[simp] theorem point_reflection_symm (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) :\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\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) :\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\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) :\n    coe_fn (point_reflection k x) x = x :=\n  vsub_vadd x x\n\ntheorem point_reflection_involutive (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (x : P\u2081) :\n    function.involutive \u21d1(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 \u2194 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\u2081 : Type u_2} {P\u2081 : Type u_6}\n    [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] {x : P\u2081} {y : P\u2081}\n    (h : function.injective bit0) : coe_fn (point_reflection k x) y = y \u2194 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\u2081 : Type u_2}\n    {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081]\n    (h : function.injective bit0) (y : P\u2081) :\n    function.injective fun (x : P\u2081) => 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\u2081 : Type u_2} {P\u2081 : Type u_6}\n    [ring k] [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [invertible (bit0 1)]\n    (y : P\u2081) : function.injective fun (x : P\u2081) => coe_fn (point_reflection k x) y :=\n  sorry\n\ntheorem point_reflection_fixed_iff_of_module (k : Type u_1) {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k]\n    [add_comm_group V\u2081] [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] [invertible (bit0 1)] {x : P\u2081}\n    {y : P\u2081} : coe_fn (point_reflection k x) y = y \u2194 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\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (v : V\u2081) (v' : V\u2081) (p : P\u2081) (c : k) :\n    coe_fn (line_map v v') c +\u1d65 p = coe_fn (line_map (v +\u1d65 p) (v' +\u1d65 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\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (p\u2081 : P\u2081) (p\u2082 : P\u2081) (p\u2083 : P\u2081) (c : k) :\n    coe_fn (line_map p\u2081 p\u2082) c -\u1d65 p\u2083 = coe_fn (line_map (p\u2081 -\u1d65 p\u2083) (p\u2082 -\u1d65 p\u2083)) c :=\n  affine_equiv.apply_line_map (affine_equiv.symm (affine_equiv.vadd_const k p\u2083)) p\u2081 p\u2082 c\n\ntheorem vsub_line_map {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (p\u2081 : P\u2081) (p\u2082 : P\u2081) (p\u2083 : P\u2081) (c : k) :\n    p\u2081 -\u1d65 coe_fn (line_map p\u2082 p\u2083) c = coe_fn (line_map (p\u2081 -\u1d65 p\u2082) (p\u2081 -\u1d65 p\u2083)) c :=\n  affine_equiv.apply_line_map (affine_equiv.const_vsub k p\u2081) p\u2082 p\u2083 c\n\ntheorem vadd_line_map {k : Type u_1} {V\u2081 : Type u_2} {P\u2081 : Type u_6} [ring k] [add_comm_group V\u2081]\n    [semimodule k V\u2081] [add_torsor V\u2081 P\u2081] (v : V\u2081) (p\u2081 : P\u2081) (p\u2082 : P\u2081) (c : k) :\n    v +\u1d65 coe_fn (line_map p\u2081 p\u2082) c = coe_fn (line_map (v +\u1d65 p\u2081) (v +\u1d65 p\u2082)) c :=\n  affine_equiv.apply_line_map (affine_equiv.const_vadd k P\u2081 v) p\u2081 p\u2082 c\n\ntheorem homothety_neg_one_apply {V\u2081 : Type u_2} {P\u2081 : Type u_6} [add_comm_group V\u2081]\n    [add_torsor V\u2081 P\u2081] {R' : Type u_10} [comm_ring R'] [semimodule R' V\u2081] (c : P\u2081) (p : P\u2081) :\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 \u2260 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 \u2964 D`, a `T`-structured arrow with source `S : D`\nis just a morphism `S \u27f6 T.obj Y`, for some `Y : D`.\n\nThese form a category with morphisms `g : Y \u27f6 Y'` making the obvious diagram commute.\n\nWe prove that `\ud835\udfd9 (T.obj Y)` is the initial object in `T`-structured objects with source `T.obj Y`.\n-/\n\nnamespace category_theory\n\nuniverses v\u2081 v\u2082 u\u2081 u\u2082 -- morphism levels before object levels. See note [category_theory universes].\nvariables {C : Type u\u2081} [category.{v\u2081} C] {D : Type u\u2082} [category.{v\u2082} D]\n\n/--\nThe category of `T`-structured arrows with domain `S : D` (here `T : C \u2964 D`),\nhas as its objects `D`-morphisms of the form `S \u27f6 T Y`, for some `Y : C`,\nand morphisms `C`-morphisms `Y \u27f6 Y'` making the obvious triangle commute.\n-/\n@[derive category, nolint has_inhabited_instance]\ndef structured_arrow (S : D) (T : C \u2964 D) := comma (functor.from_punit S) T\n\nnamespace structured_arrow\n\nvariables {S S' S'' : D} {Y Y' : C} {T : C \u2964 D}\n\n/-- The obvious projection functor from structured arrows. -/\ndef proj : structured_arrow S T \u2964 C := comma.snd _ _\n\n/-- Construct a structured arrow from a morphism. -/\ndef mk (f : S \u27f6 T.obj Y) : structured_arrow S T := \u27e8\u27e8\u27e9, Y, f\u27e9\n\n@[simp] lemma mk_left (f : S \u27f6 T.obj Y) : (mk f).left = punit.star := rfl\n@[simp] lemma mk_right (f : S \u27f6 T.obj Y) : (mk f).right = Y := rfl\n@[simp] lemma mk_hom_eq_self (f : S \u27f6 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 \u27f6 f'.right) (w : f.hom \u226b T.map g = f'.hom) :\n  f \u27f6 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 \u2245 f'.right)\n  (w : f.hom \u226b T.map g.hom = f'.hom) : f \u2245 f' :=\ncomma.iso_mk (eq_to_iso (by ext)) g (by simpa using w.symm)\n\n/--\nA morphism between source objects `S \u27f6 S'`\ncontravariantly induces a functor between structured arrows,\n`structured_arrow S' T \u2964 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 \u27f6 S') : structured_arrow S' T \u2964 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 (\ud835\udfd9 S)).obj f = f :=\nby { rw eq_mk f, simp, }\n\n@[simp] lemma map_comp {f : S \u27f6 S'} {f' : S' \u27f6 S''} {h : structured_arrow S'' T} :\n  (map (f \u226b 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 (\ud835\udfd9 (T.obj Y))) :=\n{ desc := \u03bb 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 \u2964 D`),\nhas as its objects `D`-morphisms of the form `S Y \u27f6 T`, for some `Y : C`,\nand morphisms `C`-morphisms `Y \u27f6 Y'` making the obvious triangle commute.\n-/\n@[derive category, nolint has_inhabited_instance]\ndef costructured_arrow (S : C \u2964 D) (T : D) := comma S (functor.from_punit T)\n\nnamespace costructured_arrow\n\nvariables {T T' T'' : D} {Y Y' : C} {S : C \u2964 D}\n\n/-- The obviuous projection functor from costructured arrows. -/\ndef proj : costructured_arrow S T \u2964 C := comma.fst _ _\n\n/-- Construct a costructured arrow from a morphism. -/\ndef mk (f : S.obj Y \u27f6 T) : costructured_arrow S T := \u27e8Y, \u27e8\u27e9, f\u27e9\n\n@[simp] lemma mk_left (f : S.obj Y \u27f6 T) : (mk f).left = Y := rfl\n@[simp] lemma mk_right (f : S.obj Y \u27f6 T) : (mk f).right = punit.star := rfl\n@[simp] lemma mk_hom_eq_self (f : S.obj Y \u27f6 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 \u27f6 f'.left) (w : S.map g \u226b f'.hom = f.hom) :\n  f \u27f6 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 \u2245 f'.left)\n  (w : S.map g.hom \u226b f'.hom = f.hom) : f \u2245 f' :=\ncomma.iso_mk g (eq_to_iso (by ext)) (by simpa using w)\n\n/--\nA morphism between target objects `T \u27f6 T'`\ncovariantly induces a functor between costructured arrows,\n`costructured_arrow S T \u2964 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 \u27f6 T') : costructured_arrow S T \u2964 costructured_arrow S T' :=\ncomma.map_right _ ((functor.const _).map f)\n\n@[simp] lemma map_mk {f : S.obj Y \u27f6 T} (g : T \u27f6 T') :\n  (map g).obj (mk f) = mk (f \u226b g) := rfl\n\n@[simp] lemma map_id {f : costructured_arrow S T} : (map (\ud835\udfd9 T)).obj f = f :=\nby { rw eq_mk f, simp, }\n\n@[simp] lemma map_comp {f : T \u27f6 T'} {f' : T' \u27f6 T''} {h : costructured_arrow S T} :\n  (map (f \u226b 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 (\ud835\udfd9 (S.obj Y))) :=\n{ lift := \u03bb 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 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\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/ -- doc string - /\nalias my_theorem \u2190 alias1 alias2 ...\n\nThis produces defs or theorems of the form:\n\n/ -- doc string - /\n@[alias] theorem alias1 : <type of my_theorem> := my_theorem\n\n/ -- doc string - /\n@[alias] theorem alias2 : <type of my_theorem> := my_theorem\n\n\nIff alias syntax:\n\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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-/\nimport data.buffer.parser\n\nopen lean.parser tactic interactive parser\n\nnamespace tactic.alias\n\n@[user_attribute] meta def alias_attr : user_attribute :=\n{ name := `alias, descr := \"This definition is an alias of another.\" }\n\nmeta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit :=\ndo updateex_env $ \u03bb 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  alias_attr.set al () tt,\n  add_doc_string al doc\n\nmeta def mk_iff_mp_app (iffmp : name) : expr \u2192 (nat \u2192 expr) \u2192 tactic expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)\n| _ f := fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\nmeta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : 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  v \u2190 mk_iff_mp_app iffmp t (\u03bb_, expr.const d.to_name (level.param <$> ls)),\n  t' \u2190 infer_type v,\n  updateex_env $ \u03bb env, env.add (declaration.thm al ls t' $ task.pure v),\n  alias_attr.set al () tt,\n  add_doc_string al doc\n\nmeta def make_left_right : name \u2192 tactic (name \u00d7 name)\n| (name.mk_string s p) := do\n  let buf : char_buffer := s.to_char_buffer,\n  sum.inr parts \u2190 pure $ run (sep_by1 (ch '_') (many_char (sat (\u2260 '_')))) s.to_char_buffer,\n  (left, _::right) \u2190 pure $ parts.span (\u2260 \"iff\"),\n  let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,\n  (suffix', right') \u2190 pure $ right.reverse.span (\u03bb s, pfx \"left\" s \u2228 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@[user_command] meta def alias_cmd (meta_info : decl_meta_info)\n  (_ : parse $ tk \"alias\") : lean.parser unit :=\ndo old \u2190 ident,\n  d \u2190 (do old \u2190 resolve_constant old, get_decl old) <|>\n    fail (\"declaration \" ++ to_string old ++ \" not found\"),\n  let doc := \u03bb al : name, meta_info.doc_string.get_or_else $\n    \"**Alias** of `\" ++ to_string old ++ \"`.\",\n  do {\n    tk \"\u2190\" <|> tk \"<-\",\n    aliases \u2190 many ident,\n    \u2191(aliases.mmap' $ \u03bb al, alias_direct d (doc al) al) } <|>\n  do {\n    tk \"\u2194\" <|> tk \"<->\",\n    (left, right) \u2190\n      mcond ((tk \".\" *> 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 (doc left) left `iff.mp,\n    alias_iff d (doc right) right `iff.mpr }\n\nmeta def get_lambda_body : expr \u2192 expr\n| (expr.lam _ _ _ b) := get_lambda_body b\n| a                  := a\n\nmeta def get_alias_target (n : name) : tactic (option name) :=\ndo attr \u2190 try_core (has_attribute `alias n),\n  option.cases_on attr (pure none) $ \u03bb_, do\n  d \u2190 get_decl n,\n  let (head, args) := (get_lambda_body d.value).get_app_fn_args,\n  let head := if head.is_constant_of `iff.mp \u2228 head.is_constant_of `iff.mpr then\n    expr.get_app_fn (head.ith_arg 2)\n  else head,\n  guardb $ head.is_constant,\n  pure $ head.const_name\n\nend tactic.alias\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/alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.08389039442695091, "lm_q1q2_score": 0.030147199880384997}}
{"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 \u2192 Type v}\nvariables [applicative F] [is_lawful_applicative F]\nvariables {\u03b1 \u03b2 \u03b3 \u03c3 : Type u}\n\nlemma applicative.map_seq_map (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (g : \u03c3 \u2192 \u03b2) (x : F \u03b1) (y : F \u03c3) :\n  (f <$> x) <*> (g <$> y) = (flip (\u2218) g \u2218 f) <$> x <*> y :=\nby simp [flip] with functor_norm\n\nlemma applicative.pure_seq_eq_map' (f : \u03b1 \u2192 \u03b2) : (<*>) (pure f : F (\u03b1 \u2192 \u03b2)) = (<$>) f :=\nby ext; simp with functor_norm\n\ntheorem applicative.ext {F} : \u2200 {A1 : applicative F} {A2 : applicative F}\n  [@is_lawful_applicative F A1] [@is_lawful_applicative F A2]\n  (H1 : \u2200 {\u03b1 : Type u} (x : \u03b1),\n    @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)\n  (H2 : \u2200 {\u03b1 \u03b2 : Type u} (f : F (\u03b1 \u2192 \u03b2)) (x : F \u03b1),\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 \u03b1 x, apply H1}, subst this,\n  have : @s1 = @s2, {funext \u03b1 \u03b2 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 \u03b1 \u03b2 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 \u2192 Type w} {G : Type v \u2192 Type u}\n\nvariables [applicative F] [applicative G]\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables {\u03b1 \u03b2 \u03b3 : Type v}\n\nlemma map_pure (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (f <$> pure x : comp F G \u03b2) = pure (f x) :=\ncomp.ext $ by simp\n\nlemma seq_pure (f : comp F G (\u03b1 \u2192 \u03b2)) (x : \u03b1) :\n  f <*> pure x = (\u03bb g : \u03b1 \u2192 \u03b2, g x) <$> f :=\ncomp.ext $ by simp [(\u2218)] with functor_norm\n\n\n\nlemma pure_seq_eq_map (f : \u03b1 \u2192 \u03b2) (x : comp F G \u03b1) :\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  (\u03bb \u03b1 x, rfl) (\u03bb \u03b1 \u03b2 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  (\u03bb \u03b1 x, rfl) (\u03bb \u03b1 \u03b2 f x, show id <$> f <*> x = f <*> x, by rw id_map)\n\nopen is_comm_applicative\n\ninstance {f : Type u \u2192 Type w} {g : Type v \u2192 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,(\u2218)] 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 {\u03b1 \u03b2 : Type w}\n  {f : Type u \u2192 Type v} {g : Type w \u2192 Type u}\n  [applicative f] [applicative g]\n  (h : f (g (\u03b1 \u2192 \u03b2))) (x : f (g \u03b1)) :\n  comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl\n\ninstance {\u03b1} [has_one \u03b1] [has_mul \u03b1] : applicative (const \u03b1) :=\n{ pure := \u03bb \u03b2 x, (1 : \u03b1),\n  seq := \u03bb \u03b2 \u03b3 f x, (f * x : \u03b1) }\n\ninstance {\u03b1} [monoid \u03b1] : is_lawful_applicative (const \u03b1) :=\nby refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]\n\ninstance {\u03b1} [has_zero \u03b1] [has_add \u03b1] : applicative (add_const \u03b1) :=\n{ pure := \u03bb \u03b2 x, (0 : \u03b1),\n  seq := \u03bb \u03b2 \u03b3 f x, (f + x : \u03b1) }\n\ninstance {\u03b1} [add_monoid \u03b1] : is_lawful_applicative (add_const \u03b1) :=\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": "/-\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.Data.KVMap\nimport Lean.Level\n\nnamespace Lean\n\n/-- Literal values for `Expr`. -/\ninductive Literal where\n  /-- Natural number literal -/\n  | natVal (val : Nat)\n  /-- String literal -/\n  | strVal (val : String)\n  deriving Inhabited, BEq, Repr\n\nprotected def Literal.hash : Literal \u2192 UInt64\n  | .natVal v => hash v\n  | .strVal v => hash v\n\ninstance : Hashable Literal := \u27e8Literal.hash\u27e9\n\n/--\nTotal order on `Expr` literal values.\nNatural number values are smaller than string literal values.\n-/\ndef Literal.lt : Literal \u2192 Literal \u2192 Bool\n  | .natVal _,  .strVal _  => true\n  | .natVal v\u2081, .natVal v\u2082 => v\u2081 < v\u2082\n  | .strVal v\u2081, .strVal v\u2082 => v\u2081 < v\u2082\n  | _,                 _   => false\n\ninstance : LT Literal := \u27e8fun a b => a.lt b\u27e9\n\ninstance (a b : Literal) : Decidable (a < b) :=\n  inferInstanceAs (Decidable (a.lt b))\n\n/--\nArguments in forallE binders can be labelled as implicit or explicit.\n\nEach `lam` or `forallE` binder comes with a `binderInfo` argument (stored in ExprData).\nThis can be set to\n- `default` -- `(x : \u03b1)`\n- `implicit` --  `{x : \u03b1}`\n- `strict_implicit` -- `\u2983x : \u03b1\u2984`\n- `inst_implicit` -- `[x : \u03b1]`.\n- `aux_decl` -- Auxillary definitions are helper methods that\n  Lean generates. `aux_decl` is used for `_match`, `_fun_match`,\n  `_let_match` and the self reference that appears in recursive pattern matching.\n\nThe difference between implicit `{}` and strict-implicit `\u2983\u2984` is how\nimplicit arguments are treated that are *not* followed by explicit arguments.\n`{}` arguments are applied eagerly, while `\u2983\u2984` arguments are left partially applied:\n```\ndef foo {x : Nat} : Nat := x\ndef bar \u2983x : Nat\u2984 : Nat := x\n#check foo -- foo : Nat\n#check bar -- bar : \u2983x : Nat\u2984 \u2192 Nat\n```\n\nSee also the Lean manual: https://leanprover.github.io/lean4/doc/expressions.html#implicit-arguments\n-/\ninductive BinderInfo where\n  /-- Default binder annotation, e.g. `(x : \u03b1)` -/\n  | default\n  /-- Implicit binder annotation, e.g., `{x : \u03b1}` -/\n  | implicit\n  /-- Strict implict binder annotation, e.g., `{{ x : \u03b1  }}` -/\n  | strictImplicit\n  /-- Local instance binder annotataion, e.g., `[Decidable \u03b1]` -/\n  | instImplicit\n  deriving Inhabited, BEq, Repr\n\ndef BinderInfo.hash : BinderInfo \u2192 UInt64\n  | .default        => 947\n  | .implicit       => 1019\n  | .strictImplicit => 1087\n  | .instImplicit   => 1153\n\n/--\nReturn `true` if the given `BinderInfo` does not correspond to an implicit binder annotation\n(i.e., `implicit`, `strictImplicit`, or `instImplicit`).\n-/\ndef BinderInfo.isExplicit : BinderInfo \u2192 Bool\n  | .implicit       => false\n  | .strictImplicit => false\n  | .instImplicit   => false\n  | _               => true\n\ninstance : Hashable BinderInfo := \u27e8BinderInfo.hash\u27e9\n\n/-- Return `true` if the given `BinderInfo` is an instance implicit annotation (e.g., `[Decidable \u03b1]`) -/\ndef BinderInfo.isInstImplicit : BinderInfo \u2192 Bool\n  | BinderInfo.instImplicit => true\n  | _                       => false\n\n/-- Return `true` if the given `BinderInfo` is a regular implicit annotation (e.g., `{\u03b1 : Type u}`) -/\ndef BinderInfo.isImplicit : BinderInfo \u2192 Bool\n  | BinderInfo.implicit => true\n  | _                   => false\n\n/-- Return `true` if the given `BinderInfo` is a strict implicit annotation (e.g., `{{\u03b1 : Type u}}`) -/\ndef BinderInfo.isStrictImplicit : BinderInfo \u2192 Bool\n  | BinderInfo.strictImplicit => true\n  | _                         => false\n\n/-- Expression metadata. Used with the `Expr.mdata` constructor. -/\nabbrev MData := KVMap\nabbrev MData.empty : MData := {}\n\n/--\nCached hash code, cached results, and other data for `Expr`.\n-  hash           : 32-bits\n-  approxDepth    : 8-bits -- the approximate depth is used to minimize the number of hash collisions\n-  hasFVar        : 1-bit -- does it contain free variables?\n-  hasExprMVar    : 1-bit -- does it contain metavariables?\n-  hasLevelMVar   : 1-bit -- does it contain level metavariables?\n-  hasLevelParam  : 1-bit -- does it contain level parameters?\n-  looseBVarRange : 20-bits\n\nRemark: this is mostly an internal datastructure used to implement `Expr`,\nmost will never have to use it.\n-/\ndef Expr.Data := UInt64\n\ninstance: Inhabited Expr.Data :=\n  inferInstanceAs (Inhabited UInt64)\n\ndef Expr.Data.hash (c : Expr.Data) : UInt64 :=\n  c.toUInt32.toUInt64\n\ninstance : BEq Expr.Data where\n  beq (a b : UInt64) := a == b\n\ndef Expr.Data.approxDepth (c : Expr.Data) : UInt8 :=\n  ((c.shiftRight 32).land 255).toUInt8\n\ndef Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 :=\n  (c.shiftRight 44).toUInt32\n\ndef Expr.Data.hasFVar (c : Expr.Data) : Bool :=\n  ((c.shiftRight 40).land 1) == 1\n\ndef Expr.Data.hasExprMVar (c : Expr.Data) : Bool :=\n  ((c.shiftRight 41).land 1) == 1\n\ndef Expr.Data.hasLevelMVar (c : Expr.Data) : Bool :=\n  ((c.shiftRight 42).land 1) == 1\n\ndef Expr.Data.hasLevelParam (c : Expr.Data) : Bool :=\n  ((c.shiftRight 43).land 1) == 1\n\n@[extern c inline \"(uint64_t)#1\"]\ndef BinderInfo.toUInt64 : BinderInfo \u2192 UInt64\n  | .default        => 0\n  | .implicit       => 1\n  | .strictImplicit => 2\n  | .instImplicit   => 3\n\ndef Expr.mkData\n    (h : UInt64) (looseBVarRange : Nat := 0) (approxDepth : UInt32 := 0)\n    (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false)\n    : Expr.Data :=\n  let approxDepth : UInt8 := if approxDepth > 255 then 255 else approxDepth.toUInt8\n  assert! (looseBVarRange \u2264 Nat.pow 2 20 - 1)\n  let r : UInt64 :=\n      h.toUInt32.toUInt64 +\n      approxDepth.toUInt64.shiftLeft 32 +\n      hasFVar.toUInt64.shiftLeft 40 +\n      hasExprMVar.toUInt64.shiftLeft 41 +\n      hasLevelMVar.toUInt64.shiftLeft 42 +\n      hasLevelParam.toUInt64.shiftLeft 43 +\n      looseBVarRange.toUInt64.shiftLeft 44\n  r\n\n/-- Optimized version of `Expr.mkData` for applications. -/\n@[inline] def Expr.mkAppData (fData : Data) (aData : Data) : Data :=\n  let depth          := (max fData.approxDepth.toUInt16 aData.approxDepth.toUInt16) + 1\n  let approxDepth    := if depth > 255 then 255 else depth.toUInt8\n  let looseBVarRange := max fData.looseBVarRange aData.looseBVarRange\n  let hash           := mixHash fData aData\n  let fData : UInt64 := fData\n  let aData : UInt64 := aData\n  assert! (looseBVarRange \u2264 (Nat.pow 2 20 - 1).toUInt32)\n  ((fData ||| aData) &&& ((15 : UInt64) <<< (40 : UInt64))) ||| hash.toUInt32.toUInt64 ||| (approxDepth.toUInt64 <<< (32 : UInt64)) ||| (looseBVarRange.toUInt64 <<< (44 : UInt64))\n\n@[inline] def Expr.mkDataForBinder (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt32) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) : Expr.Data :=\n  Expr.mkData h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam\n\n@[inline] def Expr.mkDataForLet (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt32) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) : Expr.Data :=\n  Expr.mkData h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam\n\ninstance : Repr Expr.Data where\n  reprPrec v prec := Id.run do\n    let mut r := \"Expr.mkData \" ++ toString v.hash\n    if v.looseBVarRange != 0 then\n      r := r ++ \" (looseBVarRange := \" ++ toString v.looseBVarRange ++ \")\"\n    if v.approxDepth != 0 then\n      r := r ++ \" (approxDepth := \" ++ toString v.approxDepth ++ \")\"\n    if v.hasFVar then\n      r := r ++ \" (hasFVar := \" ++ toString v.hasFVar ++ \")\"\n    if v.hasExprMVar then\n      r := r ++ \" (hasExprMVar := \" ++ toString v.hasExprMVar ++ \")\"\n    if v.hasLevelMVar then\n      r := r ++ \" (hasLevelMVar := \" ++ toString v.hasLevelMVar ++ \")\"\n    Repr.addAppParen r prec\n\nopen Expr\n\n/--\nThe unique free variable identifier. It is just a hierarchical name,\nbut we wrap it in `FVarId` to make sure they don't get mixed up with `MVarId`.\n\nThis is not the user-facing name for a free variable. This information is stored\nin the local context (`LocalContext`). The unique identifiers are generated using\na `NameGenerator`.\n-/\nstructure FVarId where\n  name : Name\n  deriving Inhabited, BEq, Hashable\n\ninstance : Repr FVarId where\n  reprPrec n p := reprPrec n.name p\n\n/--\nA set of unique free variable identifiers.\nThis is a persistent data structure implemented using red-black trees. -/\ndef FVarIdSet := RBTree FVarId (Name.quickCmp \u00b7.name \u00b7.name)\n  deriving Inhabited, EmptyCollection\n\ninstance : ForIn m FVarIdSet FVarId := inferInstanceAs (ForIn _ (RBTree ..) ..)\n\ndef FVarIdSet.insert (s : FVarIdSet) (fvarId : FVarId) : FVarIdSet :=\n  RBTree.insert s fvarId\n\n/--\nA set of unique free variable identifiers implemented using hashtables.\nHashtables are faster than red-black trees if they are used linearly.\nThey are not persistent data-structures. -/\ndef FVarIdHashSet := HashSet FVarId\n  deriving Inhabited, EmptyCollection\n\n/--\nA mapping from free variable identifiers to values of type `\u03b1`.\nThis is a persistent data structure implemented using red-black trees. -/\ndef FVarIdMap (\u03b1 : Type) := RBMap FVarId \u03b1 (Name.quickCmp \u00b7.name \u00b7.name)\n\ndef FVarIdMap.insert (s : FVarIdMap \u03b1) (fvarId : FVarId) (a : \u03b1) : FVarIdMap \u03b1 :=\n  RBMap.insert s fvarId a\n\ninstance : EmptyCollection (FVarIdMap \u03b1) := inferInstanceAs (EmptyCollection (RBMap ..))\n\ninstance : Inhabited (FVarIdMap \u03b1) where\n  default := {}\n\n/-- Universe metavariable Id   -/\nstructure MVarId where\n  name : Name\n  deriving Inhabited, BEq, Hashable, Repr\n\ninstance : Repr MVarId where\n  reprPrec n p := reprPrec n.name p\n\ndef MVarIdSet := RBTree MVarId (Name.quickCmp \u00b7.name \u00b7.name)\n  deriving Inhabited, EmptyCollection\n\ndef MVarIdSet.insert (s : MVarIdSet) (mvarId : MVarId) : MVarIdSet :=\n  RBTree.insert s mvarId\n\ninstance : ForIn m MVarIdSet MVarId := inferInstanceAs (ForIn _ (RBTree ..) ..)\n\ndef MVarIdMap (\u03b1 : Type) := RBMap MVarId \u03b1 (Name.quickCmp \u00b7.name \u00b7.name)\n\ndef MVarIdMap.insert (s : MVarIdMap \u03b1) (mvarId : MVarId) (a : \u03b1) : MVarIdMap \u03b1 :=\n  RBMap.insert s mvarId a\n\ninstance : EmptyCollection (MVarIdMap \u03b1) := inferInstanceAs (EmptyCollection (RBMap ..))\n\ninstance : ForIn m (MVarIdMap \u03b1) (MVarId \u00d7 \u03b1) := inferInstanceAs (ForIn _ (RBMap ..) ..)\n\ninstance : Inhabited (MVarIdMap \u03b1) where\n  default := {}\n\n/--\nLean expressions. This data structure is used in the kernel and\nelaborator. However, expressions sent to the kernel should not\ncontain metavariables.\n\nRemark: we use the `E` suffix (short for `Expr`) to avoid collision with keywords.\nWe considered using \u00ab...\u00bb, but it is too inconvenient to use.\n-/\ninductive Expr where\n  /--\n  The `bvar` constructor represents bound variables, i.e. occurrences\n  of a variable in the expression where there is a variable binder\n  above it (i.e. introduced by a `lam`, `forallE`, or `letE`).\n\n  The `deBruijnIndex` parameter is the *de-Bruijn* index for the bound\n  variable. See [here](https://en.wikipedia.org/wiki/De_Bruijn_index)\n  for additional information on de-Bruijn indexes.\n\n  For example, consider the expression `fun x : Nat => forall y : Nat, x = y`.\n  The `x` and `y` variables in the equality expression are constructed\n  using `bvar` and bound to the binders introduced by the earlier\n  `lam` and `forallE` constructors. Here is the corresponding `Expr` representation\n  for the same expression:\n  ```lean\n  .lam `x (.const `Nat [])\n    (.forallE `y (.const `Nat [])\n      (.app (.app (.app (.const `Eq [.succ .zero]) (.const `Nat [])) (.bvar 1)) (.bvar 0))\n      .default)\n    .default\n  ```\n  -/\n  | bvar (deBruijnIndex : Nat)\n\n  /--\n  The `fvar` constructor represent free variables. These /free/ variable\n  occurrences are not bound by an earlier `lam`, `forallE`, or `letE`\n  contructor and its binder exists in a local context only.\n\n  Note that Lean uses the /locally nameless approach/. See [here](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.365.2479&rep=rep1&type=pdf)\n  for additional details.\n\n  When \"visiting\" the body of a binding expression (i.e. `lam`, `forallE`, or `letE`),\n  bound variables are converted into free variables using a unique identifier,\n  and their user-facing name, type, value (for `LetE`), and binder annotation\n  are stored in the `LocalContext`.\n  -/\n  | fvar (fvarId : FVarId)\n\n  /--\n  Metavariables are used to represent \"holes\" in expressions, and goals in the\n  tactic framework. Metavariable declarations are stored in the `MetavarContext`.\n  Metavariables are used during elaboration, and are not allowed in the kernel,\n  or in the code generator.\n  -/\n  | mvar (mvarId : MVarId)\n\n  /--\n  Used for `Type u`, `Sort u`, and `Prop`:\n  - `Prop` is represented as `.sort .zero`,\n  - `Sort u` as ``.sort (.param `u)``, and\n  - `Type u` as ``.sort (.succ (.param `u))``\n  -/\n  | sort (u : Level)\n\n  /--\n  A (universe polymorphic) constant that has been defined earlier in the module or\n  by another imported module. For example, `@Eq.{1}` is represented\n  as ``Expr.const `Eq [.succ .zero]``, and `@Array.map.{0, 0}` is represented\n  as ``Expr.const `Array.map [.zero, .zero]``.\n  -/\n  | const (declName : Name) (us : List Level)\n\n  /--\n  A function application.\n\n  For example, the natural number one, i.e. `Nat.succ Nat.zero` is represented as\n  `Expr.app (.const `Nat.succ []) (.const .zero [])`\n  Note that multiple arguments are represented using partial application.\n\n  For example, the two argument application `f x y` is represented as\n  `Expr.app (.app f x) y`.\n  -/\n  | app (fn : Expr) (arg : Expr)\n\n  /--\n  A lambda abstraction (aka anonymous functions). It introduces a new binder for\n  variable `x` in scope for the lambda body.\n\n  For example, the expression `fun x : Nat => x` is represented as\n  ```\n  Expr.lam `x (.const `Nat []) (.bvar 0) .default\n  ```\n  -/\n  | lam (binderName : Name) (binderType : Expr) (body : Expr) (binderInfo : BinderInfo)\n\n  /--\n  A dependent arrow `(a : \u03b1) \u2192 \u03b2)` (aka forall-expression) where `\u03b2` may dependent\n  on `a`. Note that this constructor is also used to represent non-dependent arrows\n  where `\u03b2` does not depend on `a`.\n\n  For example:\n  - `forall x : Prop, x \u2227 x`:\n  ```lean\n  Expr.forallE `x (.sort .zero)\n    (.app (.app (.const `And []) (.bvar 0)) (.bvar 0)) .default\n  ```\n  - `Nat \u2192 Bool`:\n  ```lean\n  Expr.forallE `a (.const `Nat [])\n    (.const `Bool []) .default\n  ```\n  -/\n  | forallE (binderName : Name) (binderType : Expr) (body : Expr) (binderInfo : BinderInfo)\n\n  /--\n  Let-expressions.\n\n  **IMPORTANT**: The `nonDep` flag is for \"local\" use only. That is, a module should not \"trust\" its value for any purpose.\n  In the intended use-case, the compiler will set this flag, and be responsible for maintaining it.\n  Other modules may not preserve its value while applying transformations.\n\n  Given an environment, a metavariable context, and a local context,\n  we say a let-expression `let x : t := v; e` is non-dependent when it is equivalent\n  to `(fun x : t => e) v`. Here is an example of a dependent let-expression\n  `let n : Nat := 2; fun (a : Array Nat n) (b : Array Nat 2) => a = b` is type correct,\n  but `(fun (n : Nat) (a : Array Nat n) (b : Array Nat 2) => a = b) 2` is not.\n\n  The let-expression `let x : Nat := 2; Nat.succ x` is represented as\n  ```\n  Expr.letE `x (.const `Nat []) (.lit (.natVal 2)) (.app (.const `Nat.succ []) (.bvar 0)) true\n  ```\n  -/\n  | letE (declName : Name) (type : Expr) (value : Expr) (body : Expr) (nonDep : Bool)\n\n  /--\n  Natural number and string literal values.\n\n  They are not really needed, but provide a more compact representation in memory\n  for these two kinds of literals, and are used to implement efficient reduction\n  in the elaborator and kernel. The \"raw\" natural number `2` can be represented\n  as `Expr.lit (.natVal 2)`. Note that, it is definitionally equal to:\n  ```lean\n  Expr.app (.const `Nat.succ []) (.app (.const `Nat.succ []) (.const `Nat.zero []))\n  ```\n  -/\n  | lit : Literal \u2192 Expr\n\n  /--\n  Metadata (aka annotations).\n\n  We use annotations to provide hints to the pretty-printer,\n  store references to `Syntax` nodes, position information, and save information for\n  elaboration procedures (e.g., we use the `inaccessible` annotation during elaboration to\n  mark `Expr`s that correspond to inaccessible patterns).\n\n  Note that `Expr.mdata data e` is definitionally equal to `e`.\n  -/\n  | mdata (data : MData) (expr : Expr)\n\n  /--\n  Projection-expressions. They are redundant, but are used to create more compact\n  terms, speedup reduction, and implement eta for structures.\n  The type of `struct` must be an structure-like inductive type. That is, it has only one\n  constructor, is not recursive, and it is not an inductive predicate. The kernel and elaborators\n  check whether the `typeName` matches the type of `struct`, and whether the (zero-based) index\n  is valid (i.e., it is smaller than the numbef of constructor fields).\n  When exporting Lean developments to other systems, `proj` can be replaced with `typeName`.`rec`\n  applications.\n\n  Example, given `a : Nat x Bool`, `a.1` is represented as\n  ```\n  .proj `Prod 0 a\n  ```\n  -/\n  | proj (typeName : Name) (idx : Nat) (struct : Expr)\nwith\n  @[computed_field, extern c inline \"lean_ctor_get_uint64(#1, lean_ctor_num_objs(#1)*sizeof(void*))\"]\n  data : @& Expr \u2192 Data\n    | .const n lvls => mkData (mixHash 5 <| mixHash (hash n) (hash lvls)) 0 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam)\n    | .bvar idx => mkData (mixHash 7 <| hash idx) (idx+1)\n    | .sort lvl => mkData (mixHash 11 <| hash lvl) 0 0 false false lvl.hasMVar lvl.hasParam\n    | .fvar fvarId => mkData (mixHash 13 <| hash fvarId) 0 0 true\n    | .mvar fvarId => mkData (mixHash 17 <| hash fvarId) 0 0 false true\n    | .mdata _m e =>\n      let d := e.data.approxDepth.toUInt32+1\n      mkData (mixHash d.toUInt64 <| e.data.hash) e.data.looseBVarRange.toNat d e.data.hasFVar e.data.hasExprMVar e.data.hasLevelMVar e.data.hasLevelParam\n    | .proj s i e =>\n      let d := e.data.approxDepth.toUInt32+1\n      mkData (mixHash d.toUInt64 <| mixHash (hash s) <| mixHash (hash i) e.data.hash)\n          e.data.looseBVarRange.toNat d e.data.hasFVar e.data.hasExprMVar e.data.hasLevelMVar e.data.hasLevelParam\n    | .app f a => mkAppData f.data a.data\n    | .lam _ t b _ =>\n      let d := (max t.data.approxDepth.toUInt32 b.data.approxDepth.toUInt32) + 1\n      mkDataForBinder (mixHash d.toUInt64 <| mixHash t.data.hash b.data.hash)\n        (max t.data.looseBVarRange.toNat (b.data.looseBVarRange.toNat - 1))\n        d\n        (t.data.hasFVar || b.data.hasFVar)\n        (t.data.hasExprMVar || b.data.hasExprMVar)\n        (t.data.hasLevelMVar || b.data.hasLevelMVar)\n        (t.data.hasLevelParam || b.data.hasLevelParam)\n    | .forallE _ t b _ =>\n      let d := (max t.data.approxDepth.toUInt32 b.data.approxDepth.toUInt32) + 1\n      mkDataForBinder (mixHash d.toUInt64 <| mixHash t.data.hash b.data.hash)\n        (max t.data.looseBVarRange.toNat (b.data.looseBVarRange.toNat - 1))\n        d\n        (t.data.hasFVar || b.data.hasFVar)\n        (t.data.hasExprMVar || b.data.hasExprMVar)\n        (t.data.hasLevelMVar || b.data.hasLevelMVar)\n        (t.data.hasLevelParam || b.data.hasLevelParam)\n    | .letE _ t v b _ =>\n      let d := (max (max t.data.approxDepth.toUInt32 v.data.approxDepth.toUInt32) b.data.approxDepth.toUInt32) + 1\n      mkDataForLet (mixHash d.toUInt64 <| mixHash t.data.hash <| mixHash v.data.hash b.data.hash)\n        (max (max t.data.looseBVarRange.toNat v.data.looseBVarRange.toNat) (b.data.looseBVarRange.toNat - 1))\n        d\n        (t.data.hasFVar || v.data.hasFVar || b.data.hasFVar)\n        (t.data.hasExprMVar || v.data.hasExprMVar || b.data.hasExprMVar)\n        (t.data.hasLevelMVar || v.data.hasLevelMVar || b.data.hasLevelMVar)\n        (t.data.hasLevelParam || v.data.hasLevelParam || b.data.hasLevelParam)\n    | .lit l => mkData (mixHash 3 (hash l))\nderiving Inhabited, Repr\n\nnamespace Expr\n\n/-- The constructor name for the given expression. This is used for debugging purposes. -/\ndef ctorName : Expr \u2192 String\n  | bvar ..    => \"bvar\"\n  | fvar ..    => \"fvar\"\n  | mvar ..    => \"mvar\"\n  | sort ..    => \"sort\"\n  | const ..   => \"const\"\n  | app ..     => \"app\"\n  | lam ..     => \"lam\"\n  | forallE .. => \"forallE\"\n  | letE ..    => \"letE\"\n  | lit ..     => \"lit\"\n  | mdata ..   => \"mdata\"\n  | proj ..    => \"proj\"\n\nprotected def hash (e : Expr) : UInt64 :=\n  e.data.hash\n\ninstance : Hashable Expr := \u27e8Expr.hash\u27e9\n\n/--\nReturn `true` if `e` contains free variables.\nThis is a constant time operation.\n-/\ndef hasFVar (e : Expr) : Bool :=\n  e.data.hasFVar\n\n/--\nReturn `true` if `e` contains expression metavariables.\nThis is a constant time operation.\n-/\ndef hasExprMVar (e : Expr) : Bool :=\n  e.data.hasExprMVar\n\n/--\nReturn `true` if `e` contains universe (aka `Level`) metavariables.\nThis is a constant time operation.\n-/\ndef hasLevelMVar (e : Expr) : Bool :=\n  e.data.hasLevelMVar\n\n/--\nDoes the expression contain level (aka universe) or expression metavariables?\nThis is a constant time operation.\n-/\ndef hasMVar (e : Expr) : Bool :=\n  let d := e.data\n  d.hasExprMVar || d.hasLevelMVar\n\n/--\nReturn true if `e` contains universe level parameters.\nThis is a constant time operation.\n-/\ndef hasLevelParam (e : Expr) : Bool :=\n  e.data.hasLevelParam\n\n/--\nReturn the approximated depth of an expression. This information is used to compute\nthe expression hash code, and speedup comparisons.\nThis is a constant time operation. We say it is approximate because it maxes out at `255`.\n-/\ndef approxDepth (e : Expr) : UInt32 :=\n  e.data.approxDepth.toUInt32\n\n/--\nThe range of de-Bruijn variables that are loose.\nThat is, bvars that are not bound by a binder.\nFor example, `bvar i` has range `i + 1` and\nan expression with no loose bvars has range `0`.\n-/\ndef looseBVarRange (e : Expr) : Nat :=\n  e.data.looseBVarRange.toNat\n\n/--\nReturn the binder information if `e` is a lambda or forall expression, and `.default` otherwise.\n-/\ndef binderInfo (e : Expr) : BinderInfo :=\n  match e with\n  | .forallE _ _ _ bi => bi\n  | .lam _ _ _ bi => bi\n  | _ => .default\n\n/-!\nExport functions.\n-/\n@[export lean_expr_hash] def hashEx : Expr \u2192 UInt64 := hash\n@[export lean_expr_has_fvar] def hasFVarEx : Expr \u2192 Bool := hasFVar\n@[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr \u2192 Bool := hasExprMVar\n@[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr \u2192 Bool := hasLevelMVar\n@[export lean_expr_has_mvar] def hasMVarEx : Expr \u2192 Bool := hasMVar\n@[export lean_expr_has_level_param] def hasLevelParamEx : Expr \u2192 Bool := hasLevelParam\n@[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange\n@[export lean_expr_binder_info] def binderInfoEx : Expr \u2192 BinderInfo := binderInfo\n\nend Expr\n\n/-- `mkConst declName us` return `.const declName us`. -/\ndef mkConst (declName : Name) (us : List Level := []) : Expr :=\n  .const declName us\n\n/-- Return the type of a literal value. -/\ndef Literal.type : Literal \u2192 Expr\n  | .natVal _ => mkConst `Nat\n  | .strVal _ => mkConst `String\n\n@[export lean_lit_type]\ndef Literal.typeEx : Literal \u2192 Expr := Literal.type\n\n/-- `.bvar idx` is now the preferred form. -/\ndef mkBVar (idx : Nat) : Expr :=\n  .bvar idx\n\n/-- `.sort u` is now the preferred form. -/\ndef mkSort (u : Level) : Expr :=\n  .sort u\n\n/--\n`.fvar fvarId` is now the preferred form.\nThis function is seldom used, free variables are often automatically created using the\ntelescope functions (e.g., `forallTelescope` and `lambdaTelescope`) at `MetaM`.\n-/\ndef mkFVar (fvarId : FVarId) : Expr :=\n  .fvar fvarId\n\n/--\n`.mvar mvarId` is now the preferred form.\nThis function is seldom used, metavariables are often created using functions such\nas `mkFresheExprMVar` at `MetaM`.\n-/\ndef mkMVar (mvarId : MVarId) : Expr :=\n  .mvar mvarId\n\n/--\n`.mdata m e` is now the preferred form.\n-/\ndef mkMData (m : MData) (e : Expr) : Expr :=\n  .mdata m e\n\n/--\n`.proj structName idx struct` is now the preferred form.\n-/\ndef mkProj (structName : Name) (idx : Nat) (struct : Expr) : Expr :=\n  .proj structName idx struct\n\n/--\n`.app f a` is now the preferred form.\n-/\ndef mkApp (f a : Expr) : Expr :=\n  .app f a\n\n/--\n`.lam x t b bi` is now the preferred form.\n-/\ndef mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=\n  .lam x t b bi\n\n/--\n`.forallE x t b bi` is now the preferred form.\n-/\ndef mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=\n  .forallE x t b bi\n\n/-- Return `Unit -> type`. Do not confuse with `Thunk type` -/\ndef mkSimpleThunkType (type : Expr) : Expr :=\n  mkForall Name.anonymous .default (mkConst `Unit) type\n\n/-- Return `fun (_ : Unit), e` -/\ndef mkSimpleThunk (type : Expr) : Expr :=\n  mkLambda `_ BinderInfo.default (mkConst `Unit) type\n\n/--\n`.letE x t v b nonDep` is now the preferred form.\n-/\ndef mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr :=\n  .letE x t v b nonDep\n\ndef mkAppB (f a b : Expr) := mkApp (mkApp f a) b\ndef mkApp2 (f a b : Expr) := mkAppB f a b\ndef mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c\ndef mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d\ndef mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e\ndef mkApp6 (f a b c d e\u2081 e\u2082 : Expr) := mkAppB (mkApp4 f a b c d) e\u2081 e\u2082\ndef mkApp7 (f a b c d e\u2081 e\u2082 e\u2083 : Expr) := mkApp3 (mkApp4 f a b c d) e\u2081 e\u2082 e\u2083\ndef mkApp8 (f a b c d e\u2081 e\u2082 e\u2083 e\u2084 : Expr) := mkApp4 (mkApp4 f a b c d) e\u2081 e\u2082 e\u2083 e\u2084\ndef mkApp9 (f a b c d e\u2081 e\u2082 e\u2083 e\u2084 e\u2085 : Expr) := mkApp5 (mkApp4 f a b c d) e\u2081 e\u2082 e\u2083 e\u2084 e\u2085\ndef mkApp10 (f a b c d e\u2081 e\u2082 e\u2083 e\u2084 e\u2085 e\u2086 : Expr) := mkApp6 (mkApp4 f a b c d) e\u2081 e\u2082 e\u2083 e\u2084 e\u2085 e\u2086\n\n/--\n`.lit l` is now the preferred form.\n-/\ndef mkLit (l : Literal) : Expr :=\n  .lit l\n\n/--\nReturn the \"raw\" natural number `.lit (.natVal n)`.\nThis is not the default representation used by the Lean frontend.\nSee `mkNatLit`.\n-/\ndef mkRawNatLit (n : Nat) : Expr :=\n  mkLit (.natVal n)\n\n/--\nReturn a natural number literal used in the frontend. It is a `OfNat.ofNat` application.\nRecall that all theorems and definitions containing numeric literals are encoded using\n`OfNat.ofNat` applications in the frontend.\n-/\ndef mkNatLit (n : Nat) : Expr :=\n  let r := mkRawNatLit n\n  mkApp3 (mkConst ``OfNat.ofNat [levelZero]) (mkConst ``Nat) r (mkApp (mkConst ``instOfNatNat) r)\n\n/-- Return the string literal `.lit (.strVal s)` -/\ndef mkStrLit (s : String) : Expr :=\n  mkLit (.strVal s)\n\n@[export lean_expr_mk_bvar] def mkBVarEx : Nat \u2192 Expr := mkBVar\n@[export lean_expr_mk_fvar] def mkFVarEx : FVarId \u2192 Expr := mkFVar\n@[export lean_expr_mk_mvar] def mkMVarEx : MVarId \u2192 Expr := mkMVar\n@[export lean_expr_mk_sort] def mkSortEx : Level \u2192 Expr := mkSort\n@[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls\n@[export lean_expr_mk_app] def mkAppEx : Expr \u2192 Expr \u2192 Expr := mkApp\n@[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b\n@[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b\n@[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b\n@[export lean_expr_mk_lit] def mkLitEx : Literal \u2192 Expr := mkLit\n@[export lean_expr_mk_mdata] def mkMDataEx : MData \u2192 Expr \u2192 Expr := mkMData\n@[export lean_expr_mk_proj] def mkProjEx : Name \u2192 Nat \u2192 Expr \u2192 Expr := mkProj\n\n/-- `mkAppN f #[a\u2080, ..., a\u2099]` ==> `f a\u2080 a\u2081 .. a\u2099`-/\ndef mkAppN (f : Expr) (args : Array Expr) : Expr :=\n  args.foldl mkApp f\n\nprivate partial def mkAppRangeAux (n : Nat) (args : Array Expr) (i : Nat) (e : Expr) : Expr :=\n  if i < n then mkAppRangeAux n args (i+1) (mkApp e (args.get! i)) else e\n\n/-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/\ndef mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr :=\n  mkAppRangeAux j args i f\n\n/-- Same as `mkApp f args` but reversing `args`. -/\ndef mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr :=\n  revArgs.foldr (fun a r => mkApp r a) fn\n\nnamespace Expr\n-- TODO: implement it in Lean\n@[extern \"lean_expr_dbg_to_string\"]\nopaque dbgToString (e : @& Expr) : String\n\n/-- A total order for expressions. We say it is quick because it first compares the hashcodes. -/\n@[extern \"lean_expr_quick_lt\"]\nopaque quickLt (a : @& Expr) (b : @& Expr) : Bool\n\n/-- A total order for expressions that takes the structure into account (e.g., variable names). -/\n@[extern \"lean_expr_lt\"]\nopaque lt (a : @& Expr) (b : @& Expr) : Bool\n\n/--\nReturn true iff `a` and `b` are alpha equivalent.\nBinder annotations are ignored.\n-/\n@[extern \"lean_expr_eqv\"]\nopaque eqv (a : @& Expr) (b : @& Expr) : Bool\n\ninstance : BEq Expr where\n  beq := Expr.eqv\n\n/--\nReturn true iff `a` and `b` are equal.\nBinder names and annotations are taking into account.\n-/\n@[extern \"lean_expr_equal\"]\nopaque equal (a : @& Expr) (b : @& Expr) : Bool\n\n/-- Return `true` if the given expression is a `.sort ..` -/\ndef isSort : Expr \u2192 Bool\n  | sort .. => true\n  | _       => false\n\n/-- Return `true` if the given expression is of the form `.sort (.succ ..)`. -/\ndef isType : Expr \u2192 Bool\n  | sort (.succ ..) => true\n  | _ => false\n\n/-- Return `true` if the given expression is of the form `.sort (.succ .zero)`. -/\ndef isType0 : Expr \u2192 Bool\n  | sort (.succ .zero) => true\n  | _ => false\n\n/-- Return `true` if the given expression is a `.sort .zero` -/\ndef isProp : Expr \u2192 Bool\n  | sort (.zero ..) => true\n  | _ => false\n\n/-- Return `true` if the given expression is a bound variable. -/\ndef isBVar : Expr \u2192 Bool\n  | bvar .. => true\n  | _       => false\n\n/-- Return `true` if the given expression is a metavariable. -/\ndef isMVar : Expr \u2192 Bool\n  | mvar .. => true\n  | _       => false\n\n/-- Return `true` if the given expression is a free variable. -/\ndef isFVar : Expr \u2192 Bool\n  | fvar .. => true\n  | _       => false\n\n/-- Return `true` if the given expression is an application. -/\ndef isApp : Expr \u2192 Bool\n  | app .. => true\n  | _      => false\n\n/-- Return `true` if the given expression is a projection `.proj ..` -/\ndef isProj : Expr \u2192 Bool\n  | proj ..  => true\n  | _        => false\n\n/-- Return `true` if the given expression is a constant. -/\ndef isConst : Expr \u2192 Bool\n  | const .. => true\n  | _        => false\n\n/--\nReturn `true` if the given expression is a constant of the give name.\nExamples:\n- `` (.const `Nat []).isConstOf `Nat `` is `true`\n- `` (.const `Nat []).isConstOf `False `` is `false`\n-/\ndef isConstOf : Expr \u2192 Name \u2192 Bool\n  | const n .., m => n == m\n  | _,          _ => false\n\n/--\nReturn `true` if the given expression is a free variable with the given id.\nExamples:\n- `isFVarOf (.fvar id) id` is `true`\n- ``isFVarOf (.fvar id) id'`` is `false`\n- ``isFVarOf (.sort levelZero) id`` is `false`\n-/\ndef isFVarOf : Expr \u2192 FVarId \u2192 Bool\n  | .fvar fvarId, fvarId' => fvarId == fvarId'\n  | _, _ => false\n\n/-- Return `true` if the given expression is a forall-expression aka (dependent) arrow. -/\ndef isForall : Expr \u2192 Bool\n  | forallE .. => true\n  | _          => false\n\n/-- Return `true` if the given expression is a lambda abstraction aka anonymous function. -/\ndef isLambda : Expr \u2192 Bool\n  | lam .. => true\n  | _      => false\n\n/-- Return `true` if the given expression is a forall or lambda expression. -/\ndef isBinding : Expr \u2192 Bool\n  | lam ..     => true\n  | forallE .. => true\n  | _          => false\n\n/-- Return `true` if the given expression is a let-expression. -/\ndef isLet : Expr \u2192 Bool\n  | letE .. => true\n  | _       => false\n\n/-- Return `true` if the given expression is a metadata. -/\ndef isMData : Expr \u2192 Bool\n  | mdata .. => true\n  | _        => false\n\n/-- Return `true` if the given expression is a literal value. -/\ndef isLit : Expr \u2192 Bool\n  | lit .. => true\n  | _      => false\n\n/--\nReturn the \"body\" of a forall expression.\nExample: let `e` be the representation for `forall (p : Prop) (q : Prop), p \u2227 q`, then\n`getForallBody e` returns ``.app (.app (.const `And []) (.bvar 1)) (.bvar 0)``\n-/\ndef getForallBody : Expr \u2192 Expr\n  | forallE _ _ b .. => getForallBody b\n  | e                => e\n\ndef getForallBodyMaxDepth : (maxDepth : Nat) \u2192 Expr \u2192 Expr\n  | (n+1), forallE _ _ b _ => getForallBodyMaxDepth n b\n  | 0, e => e\n  | _, e => e\n\n/-- Given a sequence of nested foralls `(a\u2081 : \u03b1\u2081) \u2192 ... \u2192 (a\u2099 : \u03b1\u2099) \u2192 _`,\nreturns the names `[a\u2081, ... a\u2099]`. -/\ndef getForallBinderNames : Expr \u2192 List Name\n  | forallE n _ b _ => n :: getForallBinderNames b\n  | _ => []\n\n/--\nIf the given expression is a sequence of\nfunction applications `f a\u2081 .. a\u2099`, return `f`.\nOtherwise return the input expression.\n-/\ndef getAppFn : Expr \u2192 Expr\n  | app f _ => getAppFn f\n  | e         => e\n\nprivate def getAppNumArgsAux : Expr \u2192 Nat \u2192 Nat\n  | app f _, n => getAppNumArgsAux f (n+1)\n  | _,       n => n\n\n/-- Counts the number `n` of arguments for an expression `f a\u2081 .. a\u2099`. -/\ndef getAppNumArgs (e : Expr) : Nat :=\n  getAppNumArgsAux e 0\n\nprivate def getAppArgsAux : Expr \u2192 Array Expr \u2192 Nat \u2192 Array Expr\n  | app f a, as, i => getAppArgsAux f (as.set! i a) (i-1)\n  | _,       as, _ => as\n\n/-- Given `f a\u2081 a\u2082 ... a\u2099`, returns `#[a\u2081, ..., a\u2099]` -/\n@[inline] def getAppArgs (e : Expr) : Array Expr :=\n  let dummy := mkSort levelZero\n  let nargs := e.getAppNumArgs\n  getAppArgsAux e (mkArray nargs dummy) (nargs-1)\n\nprivate def getAppRevArgsAux : Expr \u2192 Array Expr \u2192 Array Expr\n  | app f a, as => getAppRevArgsAux f (as.push a)\n  | _,       as => as\n\n/-- Same as `getAppArgs` but reverse the output array. -/\n@[inline] def getAppRevArgs (e : Expr) : Array Expr :=\n  getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs)\n\n@[specialize] def withAppAux (k : Expr \u2192 Array Expr \u2192 \u03b1) : Expr \u2192 Array Expr \u2192 Nat \u2192 \u03b1\n  | app f a, as, i => withAppAux k f (as.set! i a) (i-1)\n  | f,       as, _ => k f as\n\n/-- Given `e = f a\u2081 a\u2082 ... a\u2099`, returns `k f #[a\u2081, ..., a\u2099]`. -/\n@[inline] def withApp (e : Expr) (k : Expr \u2192 Array Expr \u2192 \u03b1) : \u03b1 :=\n  let dummy := mkSort levelZero\n  let nargs := e.getAppNumArgs\n  withAppAux k e (mkArray nargs dummy) (nargs-1)\n\n/-- Given `e = fn a\u2081 ... a\u2099`, runs `f` on `fn` and each of the arguments `a\u1d62` and\nmakes a new function application with the results. -/\ndef traverseApp {M} [Monad M]\n  (f : Expr \u2192 M Expr) (e : Expr) : M Expr :=\n  e.withApp fun fn args => mkAppN <$> f fn <*> args.mapM f\n\n@[specialize] private def withAppRevAux (k : Expr \u2192 Array Expr \u2192 \u03b1) : Expr \u2192 Array Expr \u2192 \u03b1\n  | app f a, as => withAppRevAux k f (as.push a)\n  | f,       as => k f as\n\n/-- Same as `withApp` but with arguments reversed. -/\n@[inline] def withAppRev (e : Expr) (k : Expr \u2192 Array Expr \u2192 \u03b1) : \u03b1 :=\n  withAppRevAux k e (Array.mkEmpty e.getAppNumArgs)\n\ndef getRevArgD : Expr \u2192 Nat \u2192 Expr \u2192 Expr\n  | app _ a, 0,   _ => a\n  | app f _, i+1, v => getRevArgD f i v\n  | _,       _,   v => v\n\ndef getRevArg! : Expr \u2192 Nat \u2192 Expr\n  | app _ a, 0   => a\n  | app f _, i+1 => getRevArg! f i\n  | _,       _   => panic! \"invalid index\"\n\n/-- Given `f a\u2080 a\u2081 ... a\u2099`, returns the `i`th argument or panics if out of bounds. -/\n@[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr :=\n  getRevArg! e (n - i - 1)\n\n/-- Given `f a\u2080 a\u2081 ... a\u2099`, returns the `i`th argument or returns `v\u2080` if out of bounds. -/\n@[inline] def getArgD (e : Expr) (i : Nat) (v\u2080 : Expr) (n := e.getAppNumArgs) : Expr :=\n  getRevArgD e (n - i - 1) v\u2080\n\n/-- Given `f a\u2080 a\u2081 ... a\u2099`, returns true if `f` is a constant with name `n`. -/\ndef isAppOf (e : Expr) (n : Name) : Bool :=\n  match e.getAppFn with\n  | const c _ => c == n\n  | _           => false\n\n/--\nGiven `f a\u2081 ... a\u1d62`, returns true if `f` is a constant\nwith name `n` and has the correct number of arguments.\n-/\ndef isAppOfArity : Expr \u2192 Name \u2192 Nat \u2192 Bool\n  | const c _, n, 0   => c == n\n  | app f _,   n, a+1 => isAppOfArity f n a\n  | _,         _, _   => false\n\n/-- Similar to `isAppOfArity` but skips `Expr.mdata`. -/\ndef isAppOfArity' : Expr \u2192 Name \u2192 Nat \u2192 Bool\n  | mdata _ b , n, a   => isAppOfArity' b n a\n  | const c _,  n, 0   => c == n\n  | app f _,    n, a+1 => isAppOfArity' f n a\n  | _,          _,  _   => false\n\ndef appFn! : Expr \u2192 Expr\n  | app f _ => f\n  | _       => panic! \"application expected\"\n\ndef appArg! : Expr \u2192 Expr\n  | app _ a => a\n  | _       => panic! \"application expected\"\n\ndef appFn!' : Expr \u2192 Expr\n  | mdata _ b => appFn!' b\n  | app f _   => f\n  | _         => panic! \"application expected\"\n\ndef appArg!' : Expr \u2192 Expr\n  | mdata _ b => appArg!' b\n  | app _ a   => a\n  | _         => panic! \"application expected\"\n\ndef sortLevel! : Expr \u2192 Level\n  | sort u => u\n  | _      => panic! \"sort expected\"\n\ndef litValue! : Expr \u2192 Literal\n  | lit v => v\n  | _     => panic! \"literal expected\"\n\ndef isNatLit : Expr \u2192 Bool\n  | lit (Literal.natVal _) => true\n  | _                      => false\n\ndef natLit? : Expr \u2192 Option Nat\n  | lit (Literal.natVal v) => v\n  | _                      => none\n\ndef isStringLit : Expr \u2192 Bool\n  | lit (Literal.strVal _) => true\n  | _                      => false\n\ndef isCharLit (e : Expr) : Bool :=\n  e.isAppOfArity ``Char.ofNat 1 && e.appArg!.isNatLit\n\ndef constName! : Expr \u2192 Name\n  | const n _ => n\n  | _         => panic! \"constant expected\"\n\ndef constName? : Expr \u2192 Option Name\n  | const n _ => some n\n  | _         => none\n\ndef constLevels! : Expr \u2192 List Level\n  | const _ ls => ls\n  | _          => panic! \"constant expected\"\n\ndef bvarIdx! : Expr \u2192 Nat\n  | bvar idx => idx\n  | _        => panic! \"bvar expected\"\n\ndef fvarId! : Expr \u2192 FVarId\n  | fvar n => n\n  | _      => panic! \"fvar expected\"\n\ndef mvarId! : Expr \u2192 MVarId\n  | mvar n => n\n  | _      => panic! \"mvar expected\"\n\ndef bindingName! : Expr \u2192 Name\n  | forallE n _ _ _ => n\n  | lam n _ _ _     => n\n  | _               => panic! \"binding expected\"\n\ndef bindingDomain! : Expr \u2192 Expr\n  | forallE _ d _ _ => d\n  | lam _ d _ _     => d\n  | _               => panic! \"binding expected\"\n\ndef bindingBody! : Expr \u2192 Expr\n  | forallE _ _ b _ => b\n  | lam _ _ b _     => b\n  | _               => panic! \"binding expected\"\n\ndef bindingInfo! : Expr \u2192 BinderInfo\n  | forallE _ _ _ bi => bi\n  | lam _ _ _ bi     => bi\n  | _                => panic! \"binding expected\"\n\ndef letName! : Expr \u2192 Name\n  | letE n .. => n\n  | _         => panic! \"let expression expected\"\n\ndef letType! : Expr \u2192 Expr\n  | letE _ t .. => t\n  | _           => panic! \"let expression expected\"\n\ndef letValue! : Expr \u2192 Expr\n  | letE _ _ v .. => v\n  | _             => panic! \"let expression expected\"\n\ndef letBody! : Expr \u2192 Expr\n  | letE _ _ _ b .. => b\n  | _               => panic! \"let expression expected\"\n\ndef consumeMData : Expr \u2192 Expr\n  | mdata _ e => consumeMData e\n  | e         => e\n\ndef mdataExpr! : Expr \u2192 Expr\n  | mdata _ e => e\n  | _         => panic! \"mdata expression expected\"\n\ndef projExpr! : Expr \u2192 Expr\n  | proj _ _ e => e\n  | _          => panic! \"proj expression expected\"\n\ndef projIdx! : Expr \u2192 Nat\n  | proj _ i _ => i\n  | _          => panic! \"proj expression expected\"\n\ndef hasLooseBVars (e : Expr) : Bool :=\n  e.looseBVarRange > 0\n\n/--\nReturn `true` if `e` is a non-dependent arrow.\nRemark: the following function assumes `e` does not have loose bound variables.\n-/\ndef isArrow (e : Expr) : Bool :=\n  match e with\n  | forallE _ _ b _ => !b.hasLooseBVars\n  | _ => false\n\n@[extern \"lean_expr_has_loose_bvar\"]\nopaque hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool\n\n/-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/\ndef hasLooseBVarInExplicitDomain : Expr \u2192 Nat \u2192 Bool \u2192 Bool\n  | Expr.forallE _ d b bi, bvarIdx, tryRange =>\n    (bi.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange\n  | e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx\n\n/--\nLower the loose bound variables `>= s` in `e` by `d`.\nThat is, a loose bound variable `bvar i`.\n`i >= s` is mapped into `bvar (i-d)`.\n\nRemark: if `s < d`, then result is `e`\n-/\n@[extern \"lean_expr_lower_loose_bvars\"]\nopaque lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr\n\n/--\n  Lift loose bound variables `>= s` in `e` by `d`. -/\n@[extern \"lean_expr_lift_loose_bvars\"]\nopaque liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr\n\n/--\n`inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type.\nIt marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or\nthe resulting type if `considerRange == true`.\n\nRemark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections.\nWhen the `{}` annotation is used in these commands, we set `considerRange == false`.\n-/\ndef inferImplicit : Expr \u2192 Nat \u2192 Bool \u2192 Expr\n  | Expr.forallE n d b bi, i+1, considerRange =>\n    let b       := inferImplicit b i considerRange\n    let newInfo := if bi.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else bi\n    mkForall n newInfo d b\n  | e, 0, _ => e\n  | e, _, _ => e\n\n/--\nInstantiate the loose bound variables in `e` using `subst`.\nThat is, a loose `Expr.bvar i` is replaced with `subst[i]`.\n-/\n@[extern \"lean_expr_instantiate\"]\nopaque instantiate (e : @& Expr) (subst : @& Array Expr) : Expr\n\n@[extern \"lean_expr_instantiate1\"]\nopaque instantiate1 (e : @& Expr) (subst : @& Expr) : Expr\n\n/-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/\n@[extern \"lean_expr_instantiate_rev\"]\nopaque instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr\n\n/--\nSimilar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.\nFunction panics if `beginIdx <= endIdx <= xs.size` does not hold.\n-/\n@[extern \"lean_expr_instantiate_range\"]\nopaque instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr\n\n/--\nSimilar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.\nFunction panics if `beginIdx <= endIdx <= xs.size` does not hold.\n-/\n@[extern \"lean_expr_instantiate_rev_range\"]\nopaque instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr\n\n/-- Replace free (or meta) variables `xs` with loose bound variables. -/\n@[extern \"lean_expr_abstract\"]\nopaque abstract (e : @& Expr) (xs : @& Array Expr) : Expr\n\n/-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/\n@[extern \"lean_expr_abstract_range\"]\nopaque abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr\n\n/-- Replace occurrences of the free variable `fvar` in `e` with `v` -/\ndef replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr :=\n  (e.abstract #[fvar]).instantiate1 v\n\n/-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/\ndef replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr :=\n  replaceFVar e (mkFVar fvarId) v\n\n/-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/\ndef replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr :=\n  (e.abstract fvars).instantiateRev vs\n\ninstance : ToString Expr where\n  toString := Expr.dbgToString\n\n/-- Returns true when the expression does not have any sub-expressions. -/\ndef isAtomic : Expr \u2192 Bool\n  | Expr.const .. => true\n  | Expr.sort ..  => true\n  | Expr.bvar ..  => true\n  | Expr.lit ..   => true\n  | Expr.mvar ..  => true\n  | Expr.fvar ..  => true\n  | _             => false\n\nend Expr\n\ndef mkDecIsTrue (pred proof : Expr) :=\n  mkAppB (mkConst `Decidable.isTrue) pred proof\n\ndef mkDecIsFalse (pred proof : Expr) :=\n  mkAppB (mkConst `Decidable.isFalse) pred proof\n\nabbrev ExprMap (\u03b1 : Type)  := HashMap Expr \u03b1\nabbrev PersistentExprMap (\u03b1 : Type) := PHashMap Expr \u03b1\nabbrev ExprSet := HashSet Expr\nabbrev PersistentExprSet := PHashSet Expr\nabbrev PExprSet := PersistentExprSet\n\n/-- Auxiliary type for forcing `==` to be structural equality for `Expr` -/\nstructure ExprStructEq where\n  val : Expr\n  deriving Inhabited\n\ninstance : Coe Expr ExprStructEq := \u27e8ExprStructEq.mk\u27e9\n\nnamespace ExprStructEq\n\nprotected def beq : ExprStructEq \u2192 ExprStructEq \u2192 Bool\n  | \u27e8e\u2081\u27e9, \u27e8e\u2082\u27e9 => Expr.equal e\u2081 e\u2082\n\nprotected def hash : ExprStructEq \u2192 UInt64\n  | \u27e8e\u27e9 => e.hash\n\ninstance : BEq ExprStructEq := \u27e8ExprStructEq.beq\u27e9\ninstance : Hashable ExprStructEq := \u27e8ExprStructEq.hash\u27e9\ninstance : ToString ExprStructEq := \u27e8fun e => toString e.val\u27e9\n\nend ExprStructEq\n\nabbrev ExprStructMap (\u03b1 : Type) := HashMap ExprStructEq \u03b1\nabbrev PersistentExprStructMap (\u03b1 : Type) := PHashMap ExprStructEq \u03b1\n\nnamespace Expr\n\nprivate partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) (b : Expr) (i : Nat) : Expr :=\n  if i == start then b\n  else\n    let i := i - 1\n    mkAppRevRangeAux revArgs start (mkApp b (revArgs.get! i)) i\n\n/-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/\ndef mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr :=\n  mkAppRevRangeAux revArgs beginIdx f endIdx\n\n/--\nIf `f` is a lambda expression, than \"beta-reduce\" it using `revArgs`.\nThis function is often used with `getAppRev` or `withAppRev`.\nExamples:\n- `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y`\n- `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y`\n- `betaRev (fun x y => t x y) #[a, b]` ==> `t b a`\n- `betaRev (fun x y => t x y) #[a, b, c, d]` ==> `t d c b a`\nSuppose `t` is `(fun x y => t x y) a b c d`, then\n`args := t.getAppRev` is `#[d, c, b, a]`,\nand `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`.\n\nIf `useZeta` is true, the function also performs zeta-reduction (reduction of let binders) to create further\nopportunities for beta reduction.\n-/\npartial def betaRev (f : Expr) (revArgs : Array Expr) (useZeta := false) (preserveMData := false) : Expr :=\n  if revArgs.size == 0 then f\n  else\n    let sz := revArgs.size\n    let rec go (e : Expr) (i : Nat) : Expr :=\n      match e with\n      | Expr.lam _ _ b _ =>\n        if i + 1 < sz then\n          go b (i+1)\n        else\n          let n := sz - (i + 1)\n          mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs\n      | Expr.letE _ _ v b _ =>\n        if useZeta && i < sz then\n          go (b.instantiate1 v) i\n        else\n          let n := sz - i\n          mkAppRevRange (e.instantiateRange n sz revArgs) 0 n revArgs\n      | Expr.mdata k b =>\n        if preserveMData then\n          let n := sz - i\n          mkMData k (mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs)\n        else\n          go b i\n      | b =>\n        let n := sz - i\n        mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs\n    go f 0\n\n/--\nApply the given arguments to `f`, beta-reducing if `f` is a\nlambda expression. See docstring for `betaRev` for examples.\n-/\ndef beta (f : Expr) (args : Array Expr) : Expr :=\n  betaRev f args.reverse\n\n/--\nReturn true if the given expression is the function of an expression that is target for (head) beta reduction.\nIf `useZeta = true`, then `let`-expressions are visited. That is, it assumes\nthat zeta-reduction (aka let-expansion) is going to be used.\n\nSee `isHeadBetaTarget`.\n-/\ndef isHeadBetaTargetFn (useZeta : Bool) : Expr \u2192 Bool\n  | Expr.lam ..         => true\n  | Expr.letE _ _ _ b _ => useZeta && isHeadBetaTargetFn useZeta b\n  | Expr.mdata _ b      => isHeadBetaTargetFn useZeta b\n  | _                   => false\n\n/-- `(fun x => e) a` ==> `e[x/a]`. -/\ndef headBeta (e : Expr) : Expr :=\n  let f := e.getAppFn\n  if f.isHeadBetaTargetFn false then betaRev f e.getAppRevArgs else e\n\n/--\nReturn true if the given expression is a target for (head) beta reduction.\nIf `useZeta = true`, then `let`-expressions are visited. That is, it assumes\nthat zeta-reduction (aka let-expansion) is going to be used.\n-/\ndef isHeadBetaTarget (e : Expr) (useZeta := false) : Bool :=\n  e.isApp && e.getAppFn.isHeadBetaTargetFn useZeta\n\nprivate def etaExpandedBody : Expr \u2192 Nat \u2192 Nat \u2192 Option Expr\n  | app f (bvar j), n+1, i => if j == i then etaExpandedBody f n (i+1) else none\n  | _,              _+1, _ => none\n  | f,              0,   _ => if f.hasLooseBVars then none else some f\n\nprivate def etaExpandedAux : Expr \u2192 Nat \u2192 Option Expr\n  | lam _ _ b _, n => etaExpandedAux b (n+1)\n  | e,           n => etaExpandedBody e n 0\n\n/--\nIf `e` is of the form `(fun x\u2081 ... x\u2099 => f x\u2081 ... x\u2099)` and `f` does not contain `x\u2081`, ..., `x\u2099`,\nthen return `some f`. Otherwise, return `none`.\n\nIt assumes `e` does not have loose bound variables.\n\nRemark: `\u2099` may be 0\n-/\ndef etaExpanded? (e : Expr) : Option Expr :=\n  etaExpandedAux e 0\n\n/-- Similar to `etaExpanded?`, but only succeeds if `\u2099 \u2265 1`. -/\ndef etaExpandedStrict? : Expr \u2192 Option Expr\n  | lam _ _ b _ => etaExpandedAux b 1\n  | _           => none\n\n/-- Return `some e'` if `e` is of the form `optParam _ e'` -/\ndef getOptParamDefault? (e : Expr) : Option Expr :=\n  if e.isAppOfArity ``optParam 2 then\n    some e.appArg!\n  else\n    none\n\n/-- Return `some e'` if `e` is of the form `autoParam _ e'` -/\ndef getAutoParamTactic? (e : Expr) : Option Expr :=\n  if e.isAppOfArity ``autoParam 2 then\n    some e.appArg!\n  else\n    none\n\n/-- Return `true` if `e` is of the form `outParam _` -/\n@[export lean_is_out_param]\ndef isOutParam (e : Expr) : Bool :=\n  e.isAppOfArity ``outParam 1\n\n/-- Return `true` if `e` is of the form `optParam _ _` -/\ndef isOptParam (e : Expr) : Bool :=\n  e.isAppOfArity ``optParam 2\n\n/-- Return `true` if `e` is of the form `autoParam _ _` -/\ndef isAutoParam (e : Expr) : Bool :=\n  e.isAppOfArity ``autoParam 2\n\n/--\nRemove `outParam`, `optParam`, and `autoParam` applications/annotations from `e`.\nNote that it does not remove nested annotations.\nExamples:\n- Given `e` of the form `outParam (optParam Nat b)`, `consumeTypeAnnotations e = b`.\n- Given `e` of the form `Nat \u2192 outParam (optParam Nat b)`, `consumeTypeAnnotations e = e`.\n-/\n@[export lean_expr_consume_type_annotations]\npartial def consumeTypeAnnotations (e : Expr) : Expr :=\n  if e.isOptParam || e.isAutoParam then\n    consumeTypeAnnotations e.appFn!.appArg!\n  else if e.isOutParam then\n    consumeTypeAnnotations e.appArg!\n  else\n    e\n\n/--\nRemove metadata annotations and `outParam`, `optParam`, and `autoParam` applications/annotations from `e`.\nNote that it does not remove nested annotations.\nExamples:\n- Given `e` of the form `outParam (optParam Nat b)`, `cleanupAnnotations e = b`.\n- Given `e` of the form `Nat \u2192 outParam (optParam Nat b)`, `cleanupAnnotations e = e`.\n-/\npartial def cleanupAnnotations (e : Expr) : Expr :=\n  let e' := e.consumeMData.consumeTypeAnnotations\n  if e' == e then e else cleanupAnnotations e'\n\n/-- Return true iff `e` contains a free variable which statisfies `p`. -/\n@[inline] def hasAnyFVar (e : Expr) (p : FVarId \u2192 Bool) : Bool :=\n  let rec @[specialize] visit (e : Expr) := if !e.hasFVar then false else\n    match e with\n    | Expr.forallE _ d b _   => visit d || visit b\n    | Expr.lam _ d b _       => visit d || visit b\n    | Expr.mdata _ e         => visit e\n    | Expr.letE _ t v b _    => visit t || visit v || visit b\n    | Expr.app f a           => visit f || visit a\n    | Expr.proj _ _ e        => visit e\n    | Expr.fvar fvarId       => p fvarId\n    | _                      => false\n  visit e\n\n/-- Return `true` if `e` contains the given free variable. -/\ndef containsFVar (e : Expr) (fvarId : FVarId) : Bool :=\n  e.hasAnyFVar (\u00b7 == fvarId)\n\n/-!\nThe update functions try to avoid allocating new values using pointer equality.\nNote that if the `update*!` functions are used under a match-expression,\nthe compiler will eliminate the double-match.\n-/\n\n@[inline] private unsafe def updateApp!Impl (e : Expr) (newFn : Expr) (newArg : Expr) : Expr :=\n  match e with\n  | app fn arg => if ptrEq fn newFn && ptrEq arg newArg then e else mkApp newFn newArg\n  | _          => panic! \"application expected\"\n\n@[implemented_by updateApp!Impl]\ndef updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr :=\n  match e with\n  | app _ _ => mkApp newFn newArg\n  | _       => panic! \"application expected\"\n\n@[inline] def updateFVar! (e : Expr) (fvarIdNew : FVarId) : Expr :=\n  match e with\n  | .fvar fvarId => if fvarId == fvarIdNew then e else .fvar fvarIdNew\n  | _            => panic! \"fvar expected\"\n\n@[inline] private unsafe def updateConst!Impl (e : Expr) (newLevels : List Level) : Expr :=\n  match e with\n  | const n ls => if ptrEqList ls newLevels then e else mkConst n newLevels\n  | _          => panic! \"constant expected\"\n\n@[implemented_by updateConst!Impl]\ndef updateConst! (e : Expr) (newLevels : List Level) : Expr :=\n  match e with\n  | const n _ => mkConst n newLevels\n  | _         => panic! \"constant expected\"\n\n@[inline] private unsafe def updateSort!Impl (e : Expr) (u' : Level) : Expr :=\n  match e with\n  | sort u => if ptrEq u u' then e else mkSort u'\n  | _      => panic! \"level expected\"\n\n@[implemented_by updateSort!Impl]\ndef updateSort! (e : Expr) (newLevel : Level) : Expr :=\n  match e with\n  | sort _ => mkSort newLevel\n  | _      => panic! \"level expected\"\n\n@[inline] private unsafe def updateMData!Impl (e : Expr) (newExpr : Expr) : Expr :=\n  match e with\n  | mdata d a => if ptrEq a newExpr then e else mkMData d newExpr\n  | _         => panic! \"mdata expected\"\n\n@[implemented_by updateMData!Impl]\ndef updateMData! (e : Expr) (newExpr : Expr) : Expr :=\n  match e with\n  | mdata d _ => mkMData d newExpr\n  | _         => panic! \"mdata expected\"\n\n@[inline] private unsafe def updateProj!Impl (e : Expr) (newExpr : Expr) : Expr :=\n  match e with\n  | proj s i a => if ptrEq a newExpr then e else mkProj s i newExpr\n  | _          => panic! \"proj expected\"\n\n@[implemented_by updateProj!Impl]\ndef updateProj! (e : Expr) (newExpr : Expr) : Expr :=\n  match e with\n  | proj s i _ => mkProj s i newExpr\n  | _          => panic! \"proj expected\"\n\n@[inline] private unsafe def updateForall!Impl (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | forallE n d b bi =>\n    if ptrEq d newDomain && ptrEq b newBody && bi == newBinfo then\n      e\n    else\n      mkForall n newBinfo newDomain newBody\n  | _               => panic! \"forall expected\"\n\n@[implemented_by updateForall!Impl]\ndef updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | forallE n _ _ _ => mkForall n newBinfo newDomain newBody\n  | _               => panic! \"forall expected\"\n\n@[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | forallE n d b bi => updateForall! (forallE n d b bi) bi newDomain newBody\n  | _                => panic! \"forall expected\"\n\n@[inline] private unsafe def updateLambda!Impl (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | lam n d b bi =>\n    if ptrEq d newDomain && ptrEq b newBody && bi == newBinfo then\n      e\n    else\n      mkLambda n newBinfo newDomain newBody\n  | _           => panic! \"lambda expected\"\n\n@[implemented_by updateLambda!Impl]\ndef updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | lam n _ _ _ => mkLambda n newBinfo newDomain newBody\n  | _           => panic! \"lambda expected\"\n\n@[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | lam n d b bi => updateLambda! (lam n d b bi) bi newDomain newBody\n  | _            => panic! \"lambda expected\"\n\n@[inline] private unsafe def updateLet!Impl (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | letE n t v b nonDep =>\n    if ptrEq t newType && ptrEq v newVal && ptrEq b newBody then\n      e\n    else\n      letE n newType newVal newBody nonDep\n  | _              => panic! \"let expression expected\"\n\n@[implemented_by updateLet!Impl]\ndef updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr :=\n  match e with\n  | letE n _ _ _ c => letE n newType newVal newBody c\n  | _              => panic! \"let expression expected\"\n\ndef updateFn : Expr \u2192 Expr \u2192 Expr\n  | e@(app f a), g => e.updateApp! (updateFn f g) a\n  | _,           g => g\n\n/--\nEta reduction. If `e` is of the form `(fun x => f x)`, then return `f`.\n-/\npartial def eta (e : Expr) : Expr :=\n  match e with\n  | Expr.lam _ d b _ =>\n    let b' := b.eta\n    match b' with\n    | .app f (.bvar 0) =>\n      if !f.hasLooseBVar 0 then\n        f.lowerLooseBVars 1 1\n      else\n        e.updateLambdaE! d b'\n    | _ => e.updateLambdaE! d b'\n  | _ => e\n\n/--\nAnnotate `e` with the given option.\nThe information is stored using metadata around `e`.\n-/\ndef setOption (e : Expr) (optionName : Name) [KVMap.Value \u03b1] (val : \u03b1) : Expr :=\n  mkMData (MData.empty.set optionName val) e\n\n/--\nAnnotate `e` with `pp.explicit := flag`\nThe delaborator uses `pp` options.\n-/\ndef setPPExplicit (e : Expr) (flag : Bool) :=\n  e.setOption `pp.explicit flag\n\n/--\nAnnotate `e` with `pp.universes := flag`\nThe delaborator uses `pp` options.\n-/\ndef setPPUniverses (e : Expr) (flag : Bool) :=\n  e.setOption `pp.universes flag\n\n/--\nIf `e` is an application `f a_1 ... a_n` annotate `f`, `a_1` ... `a_n` with `pp.explicit := false`,\nand annotate `e` with `pp.explicit := true`.\n-/\ndef setAppPPExplicit (e : Expr) : Expr :=\n  match e with\n  | app .. =>\n    let f    := e.getAppFn.setPPExplicit false\n    let args := e.getAppArgs.map (\u00b7.setPPExplicit false)\n    mkAppN f args |>.setPPExplicit true\n  | _      => e\n\n/--\nSimilar for `setAppPPExplicit`, but only annotate children with `pp.explicit := false` if\n`e` does not contain metavariables.\n-/\ndef setAppPPExplicitForExposingMVars (e : Expr) : Expr :=\n  match e with\n  | app .. =>\n    let f    := e.getAppFn.setPPExplicit false\n    let args := e.getAppArgs.map fun arg => if arg.hasMVar then arg else arg.setPPExplicit false\n    mkAppN f args |>.setPPExplicit true\n  | _      => e\n\nend Expr\n\n/--\nAnnotate `e` with the given annotation name `kind`.\nIt uses metadata to store the annotation.\n-/\ndef mkAnnotation (kind : Name) (e : Expr) : Expr :=\n  mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e\n\n/--\nReturn `some e'` if `e = mkAnnotation kind e'`\n-/\ndef annotation? (kind : Name) (e : Expr) : Option Expr :=\n  match e with\n  | .mdata d b => if d.size == 1 && d.getBool kind false then some b else none\n  | _          => none\n\n/--\nAnnotate `e` with the `let_fun` annotation. This annotation is used as hint for the delaborator.\nIf `e` is of the form `(fun x : t => b) v`, then `mkLetFunAnnotation e` is delaborated at\n`let_fun x : t := v; b`\n-/\ndef mkLetFunAnnotation (e : Expr) : Expr :=\n  mkAnnotation `let_fun e\n\n/--\nReturn `some e'` if `e = mkLetFunAnnotation e'`\n-/\ndef letFunAnnotation? (e : Expr) : Option Expr :=\n  annotation? `let_fun e\n\n/--\nReturn true if `e = mkLetFunAnnotation e'`, and `e'` is of the form `(fun x : t => b) v`\n-/\ndef isLetFun (e : Expr) : Bool :=\n  match letFunAnnotation? e with\n  | none   => false\n  | some e => e.isApp && e.appFn!.isLambda\n\n/--\nAuxiliary annotation used to mark terms marked with the \"inaccessible\" annotation `.(t)` and\n`_` in patterns.\n-/\ndef mkInaccessible (e : Expr) : Expr :=\n  mkAnnotation `_inaccessible e\n\n/-- Return `some e'` if `e = mkInaccessible e'`. -/\ndef inaccessible? (e : Expr) : Option Expr :=\n  annotation? `_inaccessible e\n\nprivate def patternRefAnnotationKey := `_patWithRef\n\n/--\nDuring elaboration expressions corresponding to pattern matching terms\nare annotated with `Syntax` objects. This function returns `some (stx, p')` if\n`p` is the pattern `p'` annotated with `stx`\n-/\ndef patternWithRef? (p : Expr) : Option (Syntax \u00d7 Expr) :=\n  match p with\n  | .mdata d _ =>\n    match d.find patternRefAnnotationKey with\n    | some (DataValue.ofSyntax stx) => some (stx, p.mdataExpr!)\n    | _ => none\n  | _ => none\n\ndef isPatternWithRef (p : Expr) : Bool :=\n  patternWithRef? p |>.isSome\n\n/--\nAnnotate the pattern `p` with `stx`. This is an auxiliary annotation\nfor producing better hover information.\n-/\ndef mkPatternWithRef (p : Expr) (stx : Syntax) : Expr :=\n  if patternWithRef? p |>.isSome then\n    p\n  else\n    mkMData (KVMap.empty.insert patternRefAnnotationKey (DataValue.ofSyntax stx)) p\n\n/-- Return `some p` if `e` is an annotated pattern (`inaccessible?` or `patternWithRef?`) -/\ndef patternAnnotation? (e : Expr) : Option Expr :=\n  if let some e := inaccessible? e then\n    some e\n  else if let some (_, e) := patternWithRef? e then\n    some e\n  else\n    none\n\n/--\nAnnotate `e` with the LHS annotation. The delaborator displays\nexpressions of the form `lhs = rhs` as `lhs` when they have this annotation.\nThis is used to implement the infoview for the `conv` mode.\n\nThis version of `mkLHSGoal` does not check that the argument is an equality.\n-/\ndef mkLHSGoalRaw (e : Expr) : Expr :=\n  mkAnnotation `_lhsGoal e\n\n/-- Return `some lhs` if `e = mkLHSGoal e'`, where `e'` is of the form `lhs = rhs`. -/\ndef isLHSGoal? (e : Expr) : Option Expr :=\n  match annotation? `_lhsGoal e with\n  | none => none\n  | some e =>\n    if e.isAppOfArity `Eq 3 then\n      some e.appFn!.appArg!\n    else\n      none\n\n/--\nPolymorphic operation for generating unique/fresh free variable identifiers.\nIt is available in any monad `m` that implements the inferface `MonadNameGenerator`.\n-/\ndef mkFreshFVarId [Monad m] [MonadNameGenerator m] : m FVarId :=\n  return { name := (\u2190 mkFreshId) }\n\n/--\nPolymorphic operation for generating unique/fresh metavariable identifiers.\nIt is available in any monad `m` that implements the inferface `MonadNameGenerator`.\n-/\ndef mkFreshMVarId [Monad m] [MonadNameGenerator m] : m MVarId :=\n  return { name := (\u2190 mkFreshId) }\n\n/--\nPolymorphic operation for generating unique/fresh universe metavariable identifiers.\nIt is available in any monad `m` that implements the inferface `MonadNameGenerator`.\n-/\ndef mkFreshLMVarId [Monad m] [MonadNameGenerator m] : m LMVarId :=\n  return { name := (\u2190 mkFreshId) }\n\n/-- Return `Not p` -/\ndef mkNot (p : Expr) : Expr := mkApp (mkConst ``Not) p\n/-- Return `p \u2228 q` -/\ndef mkOr (p q : Expr) : Expr := mkApp2 (mkConst ``Or) p q\n/-- Return `p \u2227 q` -/\ndef mkAnd (p q : Expr) : Expr := mkApp2 (mkConst ``And) p q\n/-- Return `Classical.em p` -/\ndef mkEM (p : Expr) : Expr := mkApp (mkConst ``Classical.em) p\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/Expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44552954976388515, "lm_q2_score": 0.06754668973182397, "lm_q1q2_score": 0.030094046264260377}}
{"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) \u2190 do\n  -- IO.println \"Initialising TeX Command cache...\"\n  -- let js \u2190 Json.parseFile <| \u2190 reroutePath \"data/texcmds.json\"\n  -- let l := js.map $ fun j => (j[0]!.getStr!, j[1]!.getStr!)\n  let .obj js \u2190 IO.ofExcept $ Json.parse $ \u2190 IO.FS.readFile (\u2190 reroutePath \"data/full-tex.json\") | panic! \"Invalid JSON format\"\n  let l : List (String \u00d7 String) := js.fold (\u03bb 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 (\u00b7 != \"\")\n    let us \u2190 ls'.mapM $ fun l => do\n      let cmd := l.takeWhile (\u00b7 \u2209 teXDelimiters)\n      let s \u2190 findUnicodeReplacement cmd\n      pure $ s ++ l.dropWhile (\u00b7 \u2209 teXDelimiters)\n    \n    return .join (h :: us)\n\n  where\n    findUnicodeReplacement (cmd : String) : IO String := do\n      if let .some u :=\n          (\u2190 texCommandCache.get).find? cmd then\n        pure u else\n        pure <| \"\\\\\" ++ cmd\n\n    teXDelimiters := [' ', '_', '^', '{', '}', '[', ']', '(', ')']\n\n\nnamespace List\n\ndef alternate : List \u03b1 \u2192 List \u03b1 \u00d7 List \u03b1\n  | [] => ([], [])\n  | a :: as =>\n    match alternate as with\n      | (odds, evens) => (a :: evens, odds)\n\ndef interleave : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1\n  | [], bs => bs\n  | as, [] => as\n  | a :: as, b :: bs =>\n    a :: b :: interleave as bs\n\ntheorem alternate_interleave : (l : List \u03b1) \u2192 \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 := \u27e82, 1\u27e9)\n  (stopTokens : Array String :=  #[\":=\", \"-/\"]) : IO Json := do\n\n  let .some key \u2190 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 \u2190  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 \u2190 teXPrompts.mapM $ \u03bb (teXFormula, leanFormula) => do\n        return s!\"TeX: ${\u2190 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 \u2190 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 \u2190 makePrompt s\n    let codexOutput \u2190 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 \u2192 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 \u2192 IO String) \n      (modFormula : String \u2192 IO String) :\n          String \u2192 IO String := fun s => do\n        let (text, formulas) := s.splitOn teXDelimiter |>.alternate\n        let text' \u2190 text.mapM modText\n        let formulas' \u2190 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-- \u03b1 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 {\u03b1 : Type}\n\ninductive tactic_script (\u03b1 : Type) : Type\n| base : \u03b1 \u2192 tactic_script\n| work (index : \u2115) (first : \u03b1) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string \u2192 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 := \u03bb s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := \u03bb s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr \u2192 tactic \u03b1) (g : expr) : tactic \u03b1 :=\ndo\n  type \u2190 infer_type g,\n  is_lemma \u2190 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 \u2190 mk_meta_var type,\n    a \u2190 tac m,\n    do\n    { val \u2190 instantiate_mvars m,\n      guard (val.list_meta_vars = []),\n      c  \u2190 new_aux_decl_name,\n      gs \u2190 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 {\u03b1} (tac : tactic \u03b1)\nwith chain_single : expr \u2192 tactic (\u03b1 \u00d7 list (tactic_script \u03b1)) | g :=\ndo set_goals [g],\n  a \u2190 tac,\n  l \u2190 get_goals >>= chain_many,\n  return (a, l)\nwith chain_many : list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] := return []\n| [g] := do\n{ (a, l) \u2190 chain_single g,\n  return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr \u2192 list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do\n{ (a, l) \u2190 abstract_if_success chain_single g,\n  new_goals \u2190 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' \u2190 chain_many current_goals,\n  return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {\u03b1 : Type} [has_to_string (tactic_script \u03b1)] (tactics : list (tactic \u03b1)) :\n  tactic (list string) :=\ndo results \u2190 (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 \u03b1)] [has_to_format \u03b1]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic \u03b1) : tactic \u03b1 :=\ndo tgt \u2190 target,\n   r \u2190 t,\n   name \u2190 decl_name,\n   trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n   tgt \u2190 pp tgt,\n   trace format!\"previous target: {tgt}\",\n   trace format!\"tactic result: {r}\",\n   tgt \u2190 try_core target,\n   tgt \u2190 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 \u03b1)) : 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": "import Smt\n\ntheorem neg (x : Int) : - -x = x := by\n  smt <;> sorry\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/Test/Int/Neg.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.060086653540254206, "lm_q1q2_score": 0.030043326770127103}}
{"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 `\u2295'` 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop) (q : \u03b2 \u2192 Prop) :=\n  \u2203 (f : \u03b1 \u2192 \u03b2), computable f \u2227 \u2200 (a : \u03b1), p a \u2194 q (f a)\n\ninfixl:1000 \" \u2264\u2080 \" => Mathlib.many_one_reducible\n\ntheorem many_one_reducible.mk {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {f : \u03b1 \u2192 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable f) : (fun (a : \u03b1) => q (f a)) \u2264\u2080 q :=\n  Exists.intro f { left := h, right := fun (a : \u03b1) => iff.rfl }\n\ntheorem many_one_reducible_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 Prop) : p \u2264\u2080 p := sorry\n\ntheorem many_one_reducible.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} : p \u2264\u2080 q \u2192 q \u2264\u2080 r \u2192 p \u2264\u2080 r := sorry\n\ntheorem reflexive_many_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] : reflexive many_one_reducible :=\n  many_one_reducible_refl\n\ntheorem transitive_many_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] : transitive many_one_reducible :=\n  fun (p q r : \u03b1 \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop) (q : \u03b2 \u2192 Prop) :=\n  \u2203 (f : \u03b1 \u2192 \u03b2), computable f \u2227 function.injective f \u2227 \u2200 (a : \u03b1), p a \u2194 q (f a)\n\ninfixl:1000 \" \u2264\u2081 \" => Mathlib.one_one_reducible\n\ntheorem one_one_reducible.mk {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {f : \u03b1 \u2192 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable f) (i : function.injective f) : (fun (a : \u03b1) => q (f a)) \u2264\u2081 q :=\n  Exists.intro f { left := h, right := { left := i, right := fun (a : \u03b1) => iff.rfl } }\n\ntheorem one_one_reducible_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 Prop) : p \u2264\u2081 p := sorry\n\ntheorem one_one_reducible.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} : p \u2264\u2081 q \u2192 q \u2264\u2081 r \u2192 p \u2264\u2081 r := sorry\n\ntheorem one_one_reducible.to_many_one {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : p \u2264\u2081 q \u2192 p \u2264\u2080 q := sorry\n\ntheorem one_one_reducible.of_equiv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {e : \u03b1 \u2243 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable \u21d1e) : (q \u2218 \u21d1e) \u2264\u2081 q :=\n  one_one_reducible.mk q h (equiv.injective e)\n\ntheorem one_one_reducible.of_equiv_symm {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {e : \u03b1 \u2243 \u03b2} (q : \u03b2 \u2192 Prop) (h : computable \u21d1(equiv.symm e)) : q \u2264\u2081 (q \u2218 \u21d1e) := sorry\n\ntheorem reflexive_one_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] : reflexive one_one_reducible :=\n  one_one_reducible_refl\n\ntheorem transitive_one_one_reducible {\u03b1 : Type u_1} [primcodable \u03b1] : transitive one_one_reducible :=\n  fun (p q r : \u03b1 \u2192 Prop) => one_one_reducible.trans\n\nnamespace computable_pred\n\n\ntheorem computable_of_many_one_reducible {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (h\u2081 : p \u2264\u2080 q) (h\u2082 : computable_pred q) : computable_pred p := sorry\n\ntheorem computable_of_one_one_reducible {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (h : p \u2264\u2081 q) : computable_pred q \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop) (q : \u03b2 \u2192 Prop) :=\n  p \u2264\u2080 q \u2227 q \u2264\u2080 p\n\n/-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/\ndef one_one_equiv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (p : \u03b1 \u2192 Prop) (q : \u03b2 \u2192 Prop) :=\n  p \u2264\u2081 q \u2227 q \u2264\u2081 p\n\ntheorem many_one_equiv_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : many_one_equiv p q \u2192 many_one_equiv q p :=\n  and.swap\n\ntheorem many_one_equiv.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} : many_one_equiv p q \u2192 many_one_equiv q r \u2192 many_one_equiv p r := sorry\n\ntheorem equivalence_of_many_one_equiv {\u03b1 : Type u_1} [primcodable \u03b1] : equivalence many_one_equiv :=\n  { left := many_one_equiv_refl,\n    right :=\n      { left := fun (x y : \u03b1 \u2192 Prop) => many_one_equiv.symm, right := fun (x y z : \u03b1 \u2192 Prop) => many_one_equiv.trans } }\n\ntheorem one_one_equiv_refl {\u03b1 : Type u_1} [primcodable \u03b1] (p : \u03b1 \u2192 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : one_one_equiv p q \u2192 one_one_equiv q p :=\n  and.swap\n\ntheorem one_one_equiv.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} : one_one_equiv p q \u2192 one_one_equiv q r \u2192 one_one_equiv p r := sorry\n\ntheorem equivalence_of_one_one_equiv {\u03b1 : Type u_1} [primcodable \u03b1] : equivalence one_one_equiv :=\n  { left := one_one_equiv_refl,\n    right :=\n      { left := fun (x y : \u03b1 \u2192 Prop) => one_one_equiv.symm, right := fun (x y z : \u03b1 \u2192 Prop) => one_one_equiv.trans } }\n\ntheorem one_one_equiv.to_many_one {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : one_one_equiv p q \u2192 many_one_equiv p q := sorry\n\n/-- a computable bijection -/\ndef equiv.computable {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] (e : \u03b1 \u2243 \u03b2) :=\n  computable \u21d1e \u2227 computable \u21d1(equiv.symm e)\n\ntheorem equiv.computable.symm {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {e : \u03b1 \u2243 \u03b2} : equiv.computable e \u2192 equiv.computable (equiv.symm e) :=\n  and.swap\n\ntheorem equiv.computable.trans {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {e\u2081 : \u03b1 \u2243 \u03b2} {e\u2082 : \u03b2 \u2243 \u03b3} : equiv.computable e\u2081 \u2192 equiv.computable e\u2082 \u2192 equiv.computable (equiv.trans e\u2081 e\u2082) := sorry\n\ntheorem computable.eqv (\u03b1 : Type u_1) [denumerable \u03b1] : equiv.computable (denumerable.eqv \u03b1) :=\n  { left := computable.encode, right := computable.of_nat \u03b1 }\n\ntheorem computable.equiv\u2082 (\u03b1 : Type u_1) (\u03b2 : Type u_2) [denumerable \u03b1] [denumerable \u03b2] : equiv.computable (denumerable.equiv\u2082 \u03b1 \u03b2) :=\n  equiv.computable.trans (computable.eqv \u03b1) (equiv.computable.symm (computable.eqv \u03b2))\n\ntheorem one_one_equiv.of_equiv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {e : \u03b1 \u2243 \u03b2} (h : equiv.computable e) {p : \u03b2 \u2192 Prop} : one_one_equiv (p \u2218 \u21d1e) 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {e : \u03b1 \u2243 \u03b2} (h : equiv.computable e) {p : \u03b2 \u2192 Prop} : many_one_equiv (p \u2218 \u21d1e) p :=\n  one_one_equiv.to_many_one (one_one_equiv.of_equiv h)\n\ntheorem many_one_equiv.le_congr_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : many_one_equiv p q) : p \u2264\u2080 r \u2194 q \u2264\u2080 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : many_one_equiv q r) : p \u2264\u2080 q \u2194 p \u2264\u2080 r :=\n  { mp := fun (h' : p \u2264\u2080 q) => many_one_reducible.trans h' (and.left h),\n    mpr := fun (h' : p \u2264\u2080 r) => many_one_reducible.trans h' (and.right h) }\n\ntheorem one_one_equiv.le_congr_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : one_one_equiv p q) : p \u2264\u2081 r \u2194 q \u2264\u2081 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : one_one_equiv q r) : p \u2264\u2081 q \u2194 p \u2264\u2081 r :=\n  { mp := fun (h' : p \u2264\u2081 q) => one_one_reducible.trans h' (and.left h),\n    mpr := fun (h' : p \u2264\u2081 r) => one_one_reducible.trans h' (and.right h) }\n\ntheorem many_one_equiv.congr_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : many_one_equiv p q) : many_one_equiv p r \u2194 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : many_one_equiv q r) : many_one_equiv p q \u2194 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : one_one_equiv p q) : one_one_equiv p r \u2194 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} (h : one_one_equiv q r) : one_one_equiv p q \u2194 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 {\u03b1 : Type u_1} [primcodable \u03b1] : equiv.computable (ulower.equiv \u03b1) :=\n  { left := primrec.to_comp primrec.ulower_down, right := primrec.to_comp primrec.ulower_up }\n\ntheorem many_one_equiv_up {\u03b1 : Type u_1} [primcodable \u03b1] {p : \u03b1 \u2192 Prop} : many_one_equiv (p \u2218 ulower.up) p :=\n  many_one_equiv.of_equiv (equiv.computable.symm ulower.down_computable)\n\ntheorem one_one_reducible.disjoin_left {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : p \u2264\u2081 sum.elim p q :=\n  Exists.intro sum.inl\n    { left := computable.sum_inl,\n      right := { left := fun (x y : \u03b1) => iff.mp sum.inl.inj_iff, right := fun (a : \u03b1) => iff.rfl } }\n\ntheorem one_one_reducible.disjoin_right {\u03b1 : Type u_1} {\u03b2 : Type u_2} [primcodable \u03b1] [primcodable \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : q \u2264\u2081 sum.elim p q :=\n  Exists.intro sum.inr\n    { left := computable.sum_inr,\n      right := { left := fun (x y : \u03b2) => iff.mp sum.inr.inj_iff, right := fun (a : \u03b2) => iff.rfl } }\n\ntheorem disjoin_many_one_reducible {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} : p \u2264\u2080 r \u2192 q \u2264\u2080 r \u2192 sum.elim p q \u2264\u2080 r := sorry\n\ntheorem disjoin_le {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} : sum.elim p q \u2264\u2080 r \u2194 p \u2264\u2080 r \u2227 q \u2264\u2080 r := sorry\n\n/--\nComputable and injective mapping of predicates to sets of natural numbers.\n-/\ndef to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] (p : set \u03b1) : set \u2115 :=\n  set_of fun (n : \u2115) => p (option.get_or_else (encodable.decode \u03b1 n) Inhabited.default)\n\n@[simp] theorem to_nat_many_one_reducible {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {p : set \u03b1} : to_nat p \u2264\u2080 p :=\n  Exists.intro (fun (n : \u2115) => option.get_or_else (encodable.decode \u03b1 n) Inhabited.default)\n    { left := computable.option_get_or_else computable.decode (computable.const Inhabited.default),\n      right := fun (_x : \u2115) => iff.rfl }\n\n@[simp] theorem many_one_reducible_to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {p : set \u03b1} : p \u2264\u2080 to_nat p := sorry\n\n@[simp] theorem many_one_reducible_to_nat_to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2] [Inhabited \u03b2] {p : set \u03b1} {q : set \u03b2} : to_nat p \u2264\u2080 to_nat q \u2194 p \u2264\u2080 q := sorry\n\n@[simp] theorem to_nat_many_one_equiv {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {p : set \u03b1} : many_one_equiv (to_nat p) p := sorry\n\n@[simp] theorem many_one_equiv_to_nat {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2] [Inhabited \u03b2] (p : set \u03b1) (q : set \u03b2) : many_one_equiv (to_nat p) (to_nat q) \u2194 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 {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] (p : \u03b1 \u2192 Prop) : many_one_degree :=\n  quotient.mk' (to_nat p)\n\nprotected theorem ind_on {C : many_one_degree \u2192 Prop} (d : many_one_degree) (h : \u2200 (p : set \u2115), 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 {\u03c6 : Sort u_1} (d : many_one_degree) (f : set \u2115 \u2192 \u03c6) (h : \u2200 (p q : \u2115 \u2192 Prop), many_one_equiv p q \u2192 f p = f q) : \u03c6 :=\n  quotient.lift_on' d f h\n\n@[simp] protected theorem lift_on_eq {\u03c6 : Sort u_1} (p : set \u2115) (f : set \u2115 \u2192 \u03c6) (h : \u2200 (p q : \u2115 \u2192 Prop), many_one_equiv p q \u2192 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\u2082 {\u03c6 : Sort u_1} (d\u2081 : many_one_degree) (d\u2082 : many_one_degree) (f : set \u2115 \u2192 set \u2115 \u2192 \u03c6) (h : \u2200 (p\u2081 p\u2082 q\u2081 q\u2082 : \u2115 \u2192 Prop), many_one_equiv p\u2081 p\u2082 \u2192 many_one_equiv q\u2081 q\u2082 \u2192 f p\u2081 q\u2081 = f p\u2082 q\u2082) : \u03c6 :=\n  many_one_degree.lift_on d\u2081 (fun (p : set \u2115) => many_one_degree.lift_on d\u2082 (f p) sorry) sorry\n\n@[simp] protected theorem lift_on\u2082_eq {\u03c6 : Sort u_1} (p : set \u2115) (q : set \u2115) (f : set \u2115 \u2192 set \u2115 \u2192 \u03c6) (h : \u2200 (p\u2081 p\u2082 q\u2081 q\u2082 : \u2115 \u2192 Prop), many_one_equiv p\u2081 p\u2082 \u2192 many_one_equiv q\u2081 q\u2082 \u2192 f p\u2081 q\u2081 = f p\u2082 q\u2082) : many_one_degree.lift_on\u2082 (of p) (of q) f h = f p q :=\n  rfl\n\n@[simp] theorem of_eq_of {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2] [Inhabited \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : of p = of q \u2194 many_one_equiv p q := sorry\n\nprotected instance inhabited : Inhabited many_one_degree :=\n  { default := of \u2205 }\n\n/--\nFor many-one degrees `d\u2081` and `d\u2082`, `d\u2081 \u2264 d\u2082` if the sets in `d\u2081` are many-one reducible to the\nsets in `d\u2082`.\n-/\nprotected instance has_le : HasLessEq many_one_degree :=\n  { LessEq := fun (d\u2081 d\u2082 : many_one_degree) => many_one_degree.lift_on\u2082 d\u2081 d\u2082 many_one_reducible sorry }\n\n@[simp] theorem of_le_of {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2] [Inhabited \u03b2] {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : of p \u2264 of q \u2194 p \u2264\u2080 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\u2081 d\u2082 : many_one_degree) => many_one_degree.lift_on\u2082 d\u2081 d\u2082 (fun (a b : set \u2115) => of (sum.elim a b)) sorry }\n\n@[simp] theorem add_of {\u03b1 : Type u} [primcodable \u03b1] [Inhabited \u03b1] {\u03b2 : Type v} [primcodable \u03b2] [Inhabited \u03b2] (p : set \u03b1) (q : set \u03b2) : of (sum.elim p q) = of p + of q := sorry\n\n@[simp] protected theorem add_le {d\u2081 : many_one_degree} {d\u2082 : many_one_degree} {d\u2083 : many_one_degree} : d\u2081 + d\u2082 \u2264 d\u2083 \u2194 d\u2081 \u2264 d\u2083 \u2227 d\u2082 \u2264 d\u2083 := sorry\n\n@[simp] protected theorem le_add_left (d\u2081 : many_one_degree) (d\u2082 : many_one_degree) : d\u2081 \u2264 d\u2081 + d\u2082 :=\n  and.left (iff.mp many_one_degree.add_le (le_refl (d\u2081 + d\u2082)))\n\n@[simp] protected theorem le_add_right (d\u2081 : many_one_degree) (d\u2082 : many_one_degree) : d\u2082 \u2264 d\u2081 + d\u2082 :=\n  and.right (iff.mp many_one_degree.add_le (le_refl (d\u2081 + d\u2082)))\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 \u03b5 \u03b1 \u2192 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 \u2192 MetaM \u03b1)\n    (g : MVarId) : MetaM \u03b1 :=\n  lemmas.firstM fun e =>\n    withTraceNode trace (return m!\"{exceptEmoji \u00b7} trying to apply: {e}\") do\n      let goals \u2190 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 (\u2190 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 \u2192 List MVarId \u2192 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 \u2192 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 \u2192 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 \u2192 MetaM Bool) : Config :=\n{ cfg with\n  discharge := fun g => do\n    if (\u2190 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 \u2192 MetaM (List MVarId)) : Config :=\n{ cfg with\n  proc := fun orig goals => match goals with\n  | [] => pure none\n  | g :: gs => try\n      return (\u2190 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 [(\u2190 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 \u2192 MetaM Bool) : Config :=\n{ cfg with\n  proc := fun orig goals => do\n    let .true \u2190 test (\u2190 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 \u2192 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 ((\u2190 lemmas.mapM id) ++ (\u2190 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 \u2190 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!\"\u23ee\ufe0f starting over using `exfalso`\") do\n          let g \u2190 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 (\u2190 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 \u2190 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 \u2190 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 \u00b7} working on: {\u2190 addMessageContextFull g}\")\n    do\n      -- Check if we should suspend the search here:\n      if (\u2190 cfg.suspend g) then\n        withTraceNode `Meta.Tactic.solveByElim\n          (fun _ => return m!\"\u23f8\ufe0f suspending search and returning as subgoal\") do\n        run (n+1) gs (g :: acc)\n      else\n        let es \u2190 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 (\u2190 cfg.discharge g) with\n          | none => (withTraceNode `Meta.Tactic.solveByElim\n              (fun _ => return m!\"\u23ed\ufe0f deemed acceptable, returning as subgoal\") do\n            run (n+1) gs (g :: acc))\n          | some l => (withTraceNode `Meta.Tactic.solveByElim\n              (fun _ => return m!\"\u23ec 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 (\u2190 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) \u00d7 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 : \u2200 {\u03b1 : Sort u} {a : \u03b1}, 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) \u00d7 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    [\u2190 `(rfl), \u2190 `(trivial), \u2190 `(congrFun), \u2190 `(congrArg)].map elab'\n  let labelledLemmas := (\u2190 use.mapM (labelled \u00b7.raw.getId)).flatten.toList\n    |>.map (liftM <| mkConstWithFreshMVarLevels \u00b7)\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 <| (\u2190 getLocalHyps).toList.removeAll (\u2190 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 \u00d7 List Term \u00d7 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 \u2295 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\u2081, h\u2082, ..., h\u1d63]` also applies the given expressions.\n* `solve_by_elim only [h\u2081, h\u2082, ..., h\u1d63]` does not include the local context,\n  `rfl`, `trivial`, `congrFun`, or `congrArg` unless they are explicitly included.\n* `solve_by_elim [-h\u2081, ... -h\u2099]` removes the given local hypotheses.\n* `solve_by_elim using [a\u2081, ...]` uses all lemmas which have been labelled\n  with the attributes `a\u1d62` (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 \u27e8lemmas, ctx\u27e9 \u2190 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 \u2190 if s.isSome then\n    getGoals\n  else\n    pure [\u2190 getMainGoal]\n  let cfg \u2190 elabConfig (mkOptionalNode cfg)\n  let [] \u2190 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 `... \u2192 \u2200 _, ... \u2192 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\u2081, ...]` to use all lemmas which have been labelled\nwith the attributes `a\u1d62` (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 \u2192 \u00ac 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 \u2190 elabConfig (mkOptionalNode cfg)\n  let cfg := { cfg with\n    maxDepth := 1\n    failAtMaxDepth := false }\n  replaceMainGoal (\u2190 solveByElim.processSyntax cfg o.isSome star add remove use [\u2190 getMainGoal])\n\n/--\n`apply_rules [l\u2081, l\u2082, ...]` tries to solve the main goal by iteratively\napplying the list of lemmas `[l\u2081, l\u2082, ...]` 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\u2081, ...]` to use all lemmas which have been labelled\nwith the attributes `a\u1d62` (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 \u2190 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) 2022 Yakov Pechersky. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yakov Pechersky\n-/\nimport 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 \u2227 Q :=\nbegin\n  split,\n  work_on_goal 1 { swap_var [P Q] },\n  all_goals { exact \u2039P\u203a }\nend\n```\n\n# See also\n* `tactic.interactive.rename`\n* `tactic.interactive.rename_var`\n\n-/\n\nnamespace tactic.interactive\n\nsetup_tactic_parser\n\nprivate meta def swap_arg_parser : lean.parser (name \u00d7 name) :=\n  prod.mk <$> ident <*> (optional (tk \"<->\" <|> tk \"\u2194\") *> ident)\n\nprivate meta def swap_args_parser : lean.parser (list (name \u00d7 name)) :=\n  (functor.map (\u03bb x, [x]) swap_arg_parser)\n  <|>\n  (tk \"[\" *> sep_by (tk \",\") swap_arg_parser <* tk \"]\")\n\n/--\n`swap_var [x y, P \u2194 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 \u2227 Q :=\nbegin\n  split,\n  work_on_goal 1 { swap_var [P Q] },\n  all_goals { exact \u2039P\u203a }\nend\n```\n-/\nmeta def swap_var (renames : parse swap_args_parser) : tactic unit := do\n  renames.mmap' (\u03bb e, do\n    n \u2190 tactic.get_unused_name,\n    -- how to call `interactive.tactic.rename` here?\n    propagate_tags $ 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\nend tactic.interactive\n\nadd_tactic_doc\n{ name       := \"swap_var\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.swap_var],\n  tags       := [\"renaming\"] }\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/swap_var.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.1581743467959293, "lm_q1q2_score": 0.029977374825123408}}
{"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 \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 {\u03c3 : Type u}\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3,\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) 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.Basic\nimport Lean.Meta.AppBuilder\n\nnamespace Lean.Meta\n\ndef GetEqnsFn := Name \u2192 MetaM (Option (Array Name))\n\nprivate builtin_initialize getEqnsFnsRef : IO.Ref (List GetEqnsFn) \u2190 IO.mkRef []\n\n/--\n  Register a new function for retrieving equation theorems.\n  We generate equations theorems on demand, and they are generated by more than one module.\n  For example, the structural and well-founded recursion modules generate them.\n  Most recent getters are tried first.\n\n  A getter returns an `Option (Array Name)`. The result is `none` if the getter failed.\n  Otherwise, it is a sequence of theorem names where each one of them corresponds to\n  an alternative. Example: the definition\n\n  ```\n  def f (xs : List Nat) : List Nat :=\n    match xs with\n    | [] => []\n    | x::xs => (x+1)::f xs\n  ```\n  should have two equational theorems associated with it\n  ```\n  f [] = []\n  ```\n  and\n  ```\n  (x : Nat) \u2192 (xs : List Nat) \u2192 f (x :: xs) = (x+1) :: f xs\n  ```\n-/\ndef registerGetEqnsFn (f : GetEqnsFn) : IO Unit := do\n  unless (\u2190 initializing) do\n    throw (IO.userError \"failed to register equation getter, this kind of extension can only be registered during initialization\")\n  getEqnsFnsRef.modify (f :: \u00b7)\n\n/-- Return true iff `declName` is a definition and its type is not a proposition. -/\nprivate def shouldGenerateEqnThms (declName : Name) : MetaM Bool := do\n  if let some (.defnInfo info) := (\u2190 getEnv).find? declName then\n    return !(\u2190 isProp info.type)\n  else\n    return false\n\nstructure EqnsExtState where\n  map : PHashMap Name (Array Name) := {}\n  deriving Inhabited\n\n/- We generate the equations on demand, and do not save them on .olean files. -/\nbuiltin_initialize eqnsExt : EnvExtension EqnsExtState \u2190\n  registerEnvExtension (pure {})\n\n/--\n  Simple equation theorem for nonrecursive definitions.\n-/\nprivate def mkSimpleEqThm (declName : Name) : MetaM (Option Name) := do\n  if let some (.defnInfo info) := (\u2190 getEnv).find? declName then\n    lambdaTelescope info.value fun xs body => do\n      let lhs := mkAppN (mkConst info.name <| info.levelParams.map mkLevelParam) xs\n      let type  \u2190 mkForallFVars xs (\u2190 mkEq lhs body)\n      let value \u2190 mkLambdaFVars xs (\u2190 mkEqRefl lhs)\n      let name := mkPrivateName (\u2190 getEnv) declName ++ `_eq_1\n      addDecl <| Declaration.thmDecl {\n        name, type, value\n        levelParams := info.levelParams\n      }\n      return some name\n  else\n    return none\n\n/--\n  Return equation theorems for the given declaration.\n  By default, we not create equation theorems for nonrecursive definitions.\n  You can use `nonRec := true` to override this behavior, a dummy `rfl` proof is created on the fly.\n-/\ndef getEqnsFor? (declName : Name) (nonRec := false) : MetaM (Option (Array Name)) := withLCtx {} {} do\n  if let some eqs := eqnsExt.getState (\u2190 getEnv) |>.map.find? declName then\n    return some eqs\n  else if (\u2190 shouldGenerateEqnThms declName) then\n    for f in (\u2190 getEqnsFnsRef.get) do\n      if let some r \u2190 f declName then\n        modifyEnv fun env => eqnsExt.modifyState env fun s => { s with map := s.map.insert declName r }\n        return some r\n    if nonRec then\n      let some eqThm \u2190 mkSimpleEqThm declName | return none\n      let r := #[eqThm]\n      modifyEnv fun env => eqnsExt.modifyState env fun s => { s with map := s.map.insert declName r }\n      return some r\n  return none\n\ndef GetUnfoldEqnFn := Name \u2192 MetaM (Option Name)\n\nprivate builtin_initialize getUnfoldEqnFnsRef : IO.Ref (List GetUnfoldEqnFn) \u2190 IO.mkRef []\n\n/--\n  Register a new function for retrieving a \"unfold\" equation theorem.\n\n  We generate this kind of equation theorem on demand, and it is generated by more than one module.\n  For example, the structural and well-founded recursion modules generate it.\n  Most recent getters are tried first.\n\n  A getter returns an `Option Name`. The result is `none` if the getter failed.\n  Otherwise, it is a theorem name. Example: the definition\n\n  ```\n  def f (xs : List Nat) : List Nat :=\n    match xs with\n    | [] => []\n    | x::xs => (x+1)::f xs\n  ```\n  should have the theorem\n  ```\n  (xs : Nat) \u2192\n    f xs =\n      match xs with\n      | [] => []\n      | x::xs => (x+1)::f xs\n  ```\n-/\ndef registerGetUnfoldEqnFn (f : GetUnfoldEqnFn) : IO Unit := do\n  unless (\u2190 initializing) do\n    throw (IO.userError \"failed to register equation getter, this kind of extension can only be registered during initialization\")\n  getUnfoldEqnFnsRef.modify (f :: \u00b7)\n\n/--\n  Return a \"unfold\" theorem for the given declaration.\n  By default, we not create unfold theorems for nonrecursive definitions.\n  You can use `nonRec := true` to override this behavior.\n-/\ndef getUnfoldEqnFor? (declName : Name) (nonRec := false) : MetaM (Option Name) := withLCtx {} {} do\n  if (\u2190 shouldGenerateEqnThms declName) then\n    for f in (\u2190 getUnfoldEqnFnsRef.get) do\n      if let some r \u2190 f declName then\n        return some r\n    if nonRec then\n      let some #[eqThm] \u2190 getEqnsFor? declName (nonRec := true) | return none\n      return some eqThm\n   return none\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/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908328, "lm_q2_score": 0.07921032899976768, "lm_q1q2_score": 0.029905119476769583}}
{"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 \u2190 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 (\u2190 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 (\u2190 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 (\u00b7.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 (\u2190 getRef) combinatorDeclName\n  expandBrackedBindersAux combinator #[bracketedExplicitBinders] body\n\nsyntax unifConstraint := term patternIgnore(\" =?= \" <|> \" \u225f \") term\nsyntax unifConstraintElem := colGe unifConstraint \", \"?\n\nsyntax (docComment)? attrKind \"unif_hint \" (ident)? bracketedBinder* \" where \" withPosition(unifConstraintElem*) patternIgnore(\"|-\" <|> \"\u22a2 \") unifConstraint : command\n\nmacro_rules\n  | `($[$doc?:docComment]? $kind:attrKind unif_hint $(n)? $bs* where $[$cs\u2081 \u225f $cs\u2082]* |- $t\u2081 \u225f $t\u2082) => do\n    let mut body \u2190 `($t\u2081 = $t\u2082)\n    for (c\u2081, c\u2082) in cs\u2081.zip cs\u2082 |>.reverse do\n      body \u2190 `($c\u2081 = $c\u2082 \u2192 $body)\n    let hint : Ident \u2190 `(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 \"\u2203 \" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``Exists xs b\nmacro \"exists\" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``Exists xs b\nmacro \"\u03a3\" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``Sigma xs b\nmacro \"\u03a3'\" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``PSigma xs b\nmacro:35 xs:bracketedExplicitBinders \" \u00d7 \" b:term:35  : term => expandBrackedBinders ``Sigma xs b\nmacro:35 xs:bracketedExplicitBinders \" \u00d7' \" 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 `<lhs>\\n  _ = <rhs> :=\n<proof>`. 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 `<lhs>\\n  _ = <rhs> :=\n<proof>`. 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 \u25b8 $m)\n  | _             => throw ()\n\n@[app_unexpander Eq.rec] def unexpandEqRec : Lean.PrettyPrinter.Unexpander\n  | `($(_) $m $h) => `($h \u25b8 $m)\n  | _             => throw ()\n\n@[app_unexpander Exists] def unexpandExists : Lean.PrettyPrinter.Unexpander\n  | `($(_) fun $x:ident => \u2203 $xs:binderIdent*, $b) => `(\u2203 $x:ident $xs:binderIdent*, $b)\n  | `($(_) fun $x:ident => $b)                     => `(\u2203 $x:ident, $b)\n  | `($(_) fun ($x:ident : $t) => $b)              => `(\u2203 ($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) \u00d7 $b)\n  | _                                  => throw ()\n\n@[app_unexpander PSigma] def unexpandPSigma : Lean.PrettyPrinter.Unexpander\n  | `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) \u00d7' $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\u2081 ... h\u2099` 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 \u00d7 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 (\u03b2 := 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 <params> := D_1, ..., D_n\n  ```\n  into\n  ```\n  class C <params> 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(\"\u00b7 \" <|> \". \")\n/-- `\u00b7 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 {\u03b2 : Type u} {m : Type u \u2192 Type v} [Monad m] (_ : Loop) (init : \u03b2) (f : Unit \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec @[specialize] loop (b : \u03b2) : m \u03b2 := do\n    match \u2190 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\u2081 v\u2082 v\u2083 u\u2081 u\u2082 u\u2083\n\nlocal attribute [elab_simple] whisker_left whisker_right\n\nvariables {C : Type u\u2081} [category.{v\u2081} C] {D : Type u\u2082} [category.{v\u2082} D]\n\n/--\n`F \u22a3 G` represents the data of an adjunction between two functors\n`F : C \u2964 D` and `G : D \u2964 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 \u2964 D) (G : D \u2964 C) :=\n(hom_equiv : \u03a0 (X Y), (F.obj X \u27f6 Y) \u2243 (X \u27f6 G.obj Y))\n(unit : \ud835\udfed C \u27f6 F.comp G)\n(counit : G.comp F \u27f6 \ud835\udfed D)\n(hom_equiv_unit' : \u03a0 {X Y f}, (hom_equiv X Y) f = (unit : _ \u27f6 _).app X \u226b G.map f . obviously)\n(hom_equiv_counit' : \u03a0 {X Y g}, (hom_equiv X Y).symm g = F.map g \u226b counit.app Y . obviously)\n\ninfix ` \u22a3 `:15 := adjunction\n\n/-- A class giving a chosen right adjoint to the functor `left`. -/\nclass is_left_adjoint (left : C \u2964 D) :=\n(right : D \u2964 C)\n(adj : left \u22a3 right)\n\n/-- A class giving a chosen left adjoint to the functor `right`. -/\nclass is_right_adjoint (right : D \u2964 C) :=\n(left : C \u2964 D)\n(adj : left \u22a3 right)\n\n/-- Extract the left adjoint from the instance giving the chosen adjoint. -/\ndef left_adjoint (R : D \u2964 C) [is_right_adjoint R] : C \u2964 D :=\nis_right_adjoint.left R\n/-- Extract the right adjoint from the instance giving the chosen adjoint. -/\ndef right_adjoint (L : C \u2964 D) [is_left_adjoint L] : D \u2964 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 \u2964 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 \u2964 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 \u2964 D} {G : D \u2964 C} (adj : F \u22a3 G) {X' X : C} {Y Y' : D}\n\n@[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' \u27f6 X) (g : X \u27f6 G.obj Y) :\n  (adj.hom_equiv X' Y).symm (f \u226b g) = F.map f \u226b (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' \u27f6 X) (g : F.obj X \u27f6 Y) :\n  (adj.hom_equiv X' Y) (F.map f \u226b g) = f \u226b (adj.hom_equiv X Y) g :=\nby rw [\u2190 equiv.eq_symm_apply]; simp [-hom_equiv_unit]\n\n@[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X \u27f6 Y) (g : Y \u27f6 Y') :\n  (adj.hom_equiv X Y') (f \u226b g) = (adj.hom_equiv X Y) f \u226b G.map g :=\nby rw [hom_equiv_unit, G.map_comp, \u2190 assoc, \u2190hom_equiv_unit]\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X \u27f6 G.obj Y) (g : Y \u27f6 Y') :\n  (adj.hom_equiv X Y').symm (f \u226b G.map g) = (adj.hom_equiv X Y).symm f \u226b g :=\nby rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit]\n\n@[simp] lemma left_triangle :\n  (whisker_right adj.unit F) \u226b (whisker_left F adj.counit) = nat_trans.id _ :=\nbegin\n  ext, dsimp,\n  erw [\u2190 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) \u226b adj.counit.app (F.obj X) = \ud835\udfd9 (F.obj X) :=\ncongr_arg (\u03bb (t : nat_trans _ (\ud835\udfed C \u22d9 F)), t.app X) adj.left_triangle\n\n@[simp, reassoc] lemma right_triangle_components {Y : D} :\n  adj.unit.app (G.obj Y) \u226b G.map (adj.counit.app Y) = \ud835\udfd9 (G.obj Y) :=\ncongr_arg (\u03bb (t : nat_trans _ (G \u22d9 \ud835\udfed C)), t.app Y) adj.right_triangle\n\n@[simp, reassoc] lemma counit_naturality {X Y : D} (f : X \u27f6 Y) :\n  F.map (G.map f) \u226b (adj.counit).app Y = (adj.counit).app X \u226b f :=\nadj.counit.naturality f\n\n@[simp, reassoc] lemma unit_naturality {X Y : C} (f : X \u27f6 Y) :\n  (adj.unit).app X \u226b G.map (F.map f) = f \u226b (adj.unit).app Y :=\n(adj.unit.naturality f).symm\n\nlemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A \u27f6 B) (g : A \u27f6 G.obj B) :\n  adj.hom_equiv A B f = g \u2194 f = (adj.hom_equiv A B).symm g :=\n\u27e8\u03bb h, by {cases h, simp}, \u03bb h, by {cases h, simp}\u27e9\n\nlemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A \u27f6 B) (g : A \u27f6 G.obj B) :\n  g = adj.hom_equiv A B f \u2194 (adj.hom_equiv A B).symm g = f :=\n\u27e8\u03bb h, by {cases h, simp}, \u03bb h, by {cases h, simp}\u27e9\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 \u2964 D) (G : D \u2964 C) :=\n(hom_equiv : \u03a0 (X Y), (F.obj X \u27f6 Y) \u2243 (X \u27f6 G.obj Y))\n(hom_equiv_naturality_left_symm' : \u03a0 {X' X Y} (f : X' \u27f6 X) (g : X \u27f6 G.obj Y),\n  (hom_equiv X' Y).symm (f \u226b g) = F.map f \u226b (hom_equiv X Y).symm g . obviously)\n(hom_equiv_naturality_right' : \u03a0 {X Y Y'} (f : F.obj X \u27f6 Y) (g : Y \u27f6 Y'),\n  (hom_equiv X Y') (f \u226b g) = (hom_equiv X Y) f \u226b 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 \u2964 D} {G : D \u2964 C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D}\n\n@[simp] lemma hom_equiv_naturality_left (f : X' \u27f6 X) (g : F.obj X \u27f6 Y) :\n  (adj.hom_equiv X' Y) (F.map f \u226b g) = f \u226b (adj.hom_equiv X Y) g :=\nby rw [\u2190 equiv.eq_symm_apply]; simp\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X \u27f6 G.obj Y) (g : Y \u27f6 Y') :\n  (adj.hom_equiv X Y').symm (f \u226b G.map g) = (adj.hom_equiv X Y).symm f \u226b 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 \u2964 D) (G : D \u2964 C) :=\n(unit : \ud835\udfed C \u27f6 F.comp G)\n(counit : G.comp F \u27f6 \ud835\udfed D)\n(left_triangle' : whisker_right unit F \u226b (functor.associator F G F).hom \u226b whisker_left F counit =\n  nat_trans.id (\ud835\udfed C \u22d9 F) . obviously)\n(right_triangle' : whisker_left G unit \u226b (functor.associator G F G).inv \u226b whisker_right counit G =\n  nat_trans.id (G \u22d9 \ud835\udfed 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 \u2964 D} {G : D \u2964 C}\n\n/-- Construct an adjunction between `F` and `G` out of a natural bijection between each\n`F.obj X \u27f6 Y` and `X \u27f6 G.obj Y`. -/\n@[simps]\ndef mk_of_hom_equiv (adj : core_hom_equiv F G) : F \u22a3 G :=\n{ unit :=\n  { app := \u03bb X, (adj.hom_equiv X (F.obj X)) (\ud835\udfd9 (F.obj X)),\n    naturality' :=\n    begin\n      intros,\n      erw [\u2190 adj.hom_equiv_naturality_left, \u2190 adj.hom_equiv_naturality_right],\n      dsimp, simp  -- See note [dsimp, simp].\n    end },\n  counit :=\n  { app := \u03bb Y, (adj.hom_equiv _ _).inv_fun (\ud835\udfd9 (G.obj Y)),\n    naturality' :=\n    begin\n      intros,\n      erw [\u2190 adj.hom_equiv_naturality_left_symm, \u2190 adj.hom_equiv_naturality_right_symm],\n      dsimp, simp\n    end },\n  hom_equiv_unit' := \u03bb X Y f, by erw [\u2190 adj.hom_equiv_naturality_right]; simp,\n  hom_equiv_counit' := \u03bb X Y f, by erw [\u2190 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 \u22a3 G :=\n{ hom_equiv := \u03bb X Y,\n  { to_fun := \u03bb f, adj.unit.app X \u226b G.map f,\n    inv_fun := \u03bb g, F.map g \u226b adj.counit.app Y,\n    left_inv := \u03bb f, begin\n      change F.map (_ \u226b _) \u226b _ = _,\n      rw [F.map_comp, assoc, \u2190functor.comp_map, adj.counit.naturality, \u2190assoc],\n      convert id_comp f,\n      have t := congr_arg (\u03bb 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 := \u03bb g, begin\n      change _ \u226b G.map (_ \u226b _) = _,\n      rw [G.map_comp, \u2190assoc, \u2190functor.comp_map, \u2190adj.unit.naturality, assoc],\n      convert comp_id g,\n      have t := congr_arg (\u03bb 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 : \ud835\udfed C \u22a3 \ud835\udfed C :=\n{ hom_equiv := \u03bb X Y, equiv.refl _,\n  unit := \ud835\udfd9 _,\n  counit := \ud835\udfd9 _ }\n\n-- Satisfy the inhabited linter.\ninstance : inhabited (adjunction (\ud835\udfed C) (\ud835\udfed C)) := \u27e8id\u27e9\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 \u2964 D} (iso : F \u2245 F') {X : C} {Y : D} :\n  (F.obj X \u27f6 Y) \u2243 (F'.obj X \u27f6 Y) :=\n{ to_fun := \u03bb f, iso.inv.app _ \u226b f,\n  inv_fun := \u03bb g, iso.hom.app _ \u226b g,\n  left_inv := \u03bb f, by simp,\n  right_inv := \u03bb 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 \u2964 C} (iso : G \u2245 G') {X : C} {Y : D} :\n  (X \u27f6 G.obj Y) \u2243 (X \u27f6 G'.obj Y) :=\n{ to_fun := \u03bb f, f \u226b iso.hom.app _,\n  inv_fun := \u03bb g, g \u226b iso.inv.app _,\n  left_inv := \u03bb f, by simp,\n  right_inv := \u03bb g, by simp }\n\n/-- Transport an adjunction along an natural isomorphism on the left. -/\ndef of_nat_iso_left\n  {F G : C \u2964 D} {H : D \u2964 C} (adj : F \u22a3 H) (iso : F \u2245 G) :\n  G \u22a3 H :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb 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 \u2964 D} {G H : D \u2964 C} (adj : F \u22a3 G) (iso : G \u2245 H) :\n  F \u22a3 H :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb 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 \u2964 D} (h : F \u2245 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 \u2964 D} (h : F \u2245 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\u2083} [\u2130 : category.{v\u2083} E] (H : D \u2964 E) (I : E \u2964 D)\n\n/--\nComposition of adjunctions.\n\nSee https://stacks.math.columbia.edu/tag/0DV0.\n-/\ndef comp (adj\u2081 : F \u22a3 G) (adj\u2082 : H \u22a3 I) : F \u22d9 H \u22a3 I \u22d9 G :=\n{ hom_equiv := \u03bb X Z, equiv.trans (adj\u2082.hom_equiv _ _) (adj\u2081.hom_equiv _ _),\n  unit := adj\u2081.unit \u226b\n  (whisker_left F $ whisker_right adj\u2082.unit G) \u226b (functor.associator _ _ _).inv,\n  counit := (functor.associator _ _ _).hom \u226b\n    (whisker_left I $ whisker_right adj\u2081.counit H) \u226b adj\u2082.counit }\n\n/-- If `F` and `G` are left adjoints then `F \u22d9 G` is a left adjoint too. -/\ninstance left_adjoint_of_comp {E : Type u\u2083} [\u2130 : category.{v\u2083} E] (F : C \u2964 D) (G : D \u2964 E)\n  [Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F \u22d9 G) :=\n{ right := Gl.right \u22d9 Fl.right,\n  adj := comp _ _ Fl.adj Gl.adj }\n\n/-- If `F` and `G` are right adjoints then `F \u22d9 G` is a right adjoint too. -/\ninstance right_adjoint_of_comp {E : Type u\u2083} [\u2130 : category.{v\u2083} E] {F : C \u2964 D} {G : D \u2964 E}\n  [Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F \u22d9 G) :=\n{ left := Gr.left \u22d9 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 \u2192 C, it suffices to give the object part\n-- of a functor F : C \u2192 D together with isomorphisms Hom(FX, Y) \u2243\n-- Hom(X, GY) natural in Y. The action of F on morphisms can be\n-- constructed from this data.\nvariables {F_obj : C \u2192 D} {G}\nvariables (e : \u03a0 X Y, (F_obj X \u27f6 Y) \u2243 (X \u27f6 G.obj Y))\nvariables (he : \u2200 X Y Y' g h, e X Y' (h \u226b g) = e X Y h \u226b G.map g)\ninclude he\n\nprivate lemma he' {X Y Y'} (f g) : (e X Y').symm (f \u226b G.map g) = (e X Y).symm f \u226b 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 \u27f6 Y` and `X \u27f6 G.obj Y` satisfying a naturality law\n`he : \u2200 X Y Y' g h, e X Y' (h \u226b g) = e X Y h \u226b G.map g`.\nDual to `right_adjoint_of_equiv`. -/\n@[simps]\ndef left_adjoint_of_equiv : C \u2964 D :=\n{ obj := F_obj,\n  map := \u03bb X X' f, (e X (F_obj X')).symm (f \u226b e X' (F_obj X') (\ud835\udfd9 _)),\n  map_comp' := \u03bb X X' X'' f f', begin\n    rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply],\n    conv { to_rhs, rw [assoc, \u2190he, 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 \u22a3 G :=\nmk_of_hom_equiv\n{ hom_equiv := e,\n  hom_equiv_naturality_left_symm' :=\n  begin\n    intros,\n    erw [\u2190 he' e he, \u2190 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 \u2192 C}\nvariables (e : \u03a0 X Y, (F.obj X \u27f6 Y) \u2243 (X \u27f6 G_obj Y))\nvariables (he : \u2200 X' X Y f g, e X' Y (F.map f \u226b g) = f \u226b e X Y g)\ninclude he\n\nprivate lemma he' {X' X Y} (f g) : F.map f \u226b (e X Y).symm g = (e X' Y).symm (f \u226b 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 \u27f6 Y` and `X \u27f6 G_obj Y` satisfying a naturality law\n`he : \u2200 X Y Y' g h, e X' Y (F.map f \u226b g) = f \u226b e X Y g`.\nDual to `left_adjoint_of_equiv`. -/\n@[simps]\ndef right_adjoint_of_equiv : D \u2964 C :=\n{ obj := G_obj,\n  map := \u03bb Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (\ud835\udfd9 _) \u226b g),\n  map_comp' := \u03bb Y Y' Y'' g g', begin\n    rw [\u2190 equiv.eq_symm_apply, \u2190 he' e he, equiv.symm_apply_apply],\n    conv { to_rhs, rw [\u2190 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 \u22a3 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 [\u2190he, equiv.apply_eq_iff_eq, \u2190assoc, 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 \u22a3 G) [\u2200 X, is_iso (adj.unit.app X)] [\u2200 Y, is_iso (adj.counit.app Y)] :\n  C \u224c D :=\n{ functor := F,\n  inverse := G,\n  unit_iso := nat_iso.of_components (\u03bb X, as_iso (adj.unit.app X)) (by simp),\n  counit_iso := nat_iso.of_components (\u03bb 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  [\u2200 X, is_iso ((adjunction.of_right_adjoint G).unit.app X)]\n  [\u2200 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 \u224c D) : e.functor \u22a3 e.inverse :=\nmk_of_unit_counit \u27e8e.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 _, }\u27e9\n\nend equivalence\n\nnamespace functor\n\n/-- An equivalence `E` is left adjoint to its inverse. -/\ndef adjunction (E : C \u2964 D) [is_equivalence E] : E \u22a3 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 \u2964 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 \u2964 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 \u2964 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 \u2964 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) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.string.defs\nimport Mathlib.tactic.derive_inhabited\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\nnamespace binder_info\n\n\n/-! ### Declarations about `binder_info` -/\n\nprotected instance inhabited : Inhabited binder_info :=\n  { default := default }\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : binder_info \u2192 string \u00d7 string :=\n  sorry\n\nend binder_info\n\n\nnamespace name\n\n\n/-! ### Declarations about `name` -/\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef map_prefix (f : name \u2192 Option name) : name \u2192 name :=\n  sorry\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\n/-- Auxilliary definition for `pop_nth_prefix` -/\n/-- Pops the top `n` prefixes from the given name. -/\n/-- Pop the prefix of a name -/\n/-- Auxilliary definition for `from_components` -/\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef from_components : List string \u2192 name :=\n  from_components_aux anonymous\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\n/-- Append a string to the last component of a name -/\ndef append_suffix : name \u2192 string \u2192 name :=\n  sorry\n\n/-- The first component of a name, turning a number to a string -/\n/-- Tests whether the first component of a name is `\"_private\"` -/\n/-- Get the last component of a name, and convert it to a string. -/\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef has_prefix (P : name \u2192 Bool) : name \u2192 Bool :=\n  sorry\n\n/-- Appends `'` to the end of a name. -/\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef last_string : name \u2192 string :=\n  sorry\n\n/--\nConstructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\n/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\n/--\nCheck whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\n/--\nCheck whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nend name\n\n\nnamespace level\n\n\n/-! ### Declarations about `level` -/\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\n/--\n`l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nend level\n\n\n/-! ### Declarations about `binder` -/\n\n/-- The type of binders containing a name, the binding info and the binding type -/\nnamespace binder\n\n\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nend binder\n\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n/--\n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\n/--\n`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\n/--\n`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nnamespace expr\n\n\n/--\nTurns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\n/--\nTurns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\n/--\n`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\nignoring differences in type and type class arguments.\n-/\nend expr\n\n\n/-! ### Declarations about `expr` -/\n\nnamespace expr\n\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\n/-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/\n/-- Match a variable. -/\n/-- Match a sort. -/\n/-- Match a constant. -/\n/-- Match a metavariable. -/\n/-- Match a local constant. -/\n/-- Match an application. -/\n/-- Match an abstraction. -/\n/-- Match a \u03a0 type. -/\n/-- Match a let. -/\n/-- Match a macro. -/\n/-- Tests whether an expression is a meta-variable. -/\n/-- Tests whether an expression is a sort. -/\n/-- Get the universe levels of a `const` expression -/\n/--\nReplace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/\n/-- Returns a list of all local constants in an expression (without duplicates). -/\n/-- Returns the set of all local constants in an expression. -/\n/-- Returns the unique names of all local constants in an expression. -/\n/-- Returns a name_set of all constants in an expression. -/\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\n/-- Returns the set of all meta-variables in an expression. -/\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\n/--\nTest `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\n-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n\n/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\n/--\nReturns true if `e` contains a `sorry`.\n-/\n/--\n`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\n-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\n/-- head-reduce a single let expression -/\n/-- head-reduce all let expressions -/\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\n/-- Repeatedly apply `expr.subst`. -/\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\n/--\nSome declarations work with open expressions, i.e. an expr that has free variables.\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/meta/expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.09009299274041058, "lm_q1q2_score": 0.029831568298601365}}
{"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.data.option.basic\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.control.lawful\n\nuniverses u_1 u \n\nnamespace Mathlib\n\nprotected instance option.is_lawful_monad : is_lawful_monad Option :=\n  is_lawful_monad.mk (fun (\u03b1 \u03b2 : Type u_1) (x : \u03b1) (f : \u03b1 \u2192 Option \u03b2) => rfl)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (x : Option \u03b1) (f : \u03b1 \u2192 Option \u03b2) (g : \u03b2 \u2192 Option \u03b3) =>\n      Option.rec rfl (fun (x : \u03b1) => rfl) x\n\ntheorem option.eq_of_eq_some {\u03b1 : Type u} {x : Option \u03b1} {y : Option \u03b1} :\n    (\u2200 (z : \u03b1), x = some z \u2194 y = some z) \u2192 x = y :=\n  sorry\n\ntheorem option.eq_some_of_is_some {\u03b1 : Type u} {o : Option \u03b1} (h : \u21a5(option.is_some o)) :\n    o = some (option.get h) :=\n  sorry\n\ntheorem option.eq_none_of_is_none {\u03b1 : Type u} {o : Option \u03b1} : \u21a5(option.is_none o) \u2192 o = none :=\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/init/data/option/instances_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.06187598918353437, "lm_q1q2_score": 0.029730093485811192}}
{"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 {\u03b1 \u03b2 \u03b3 : 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 : \u03a0 (i : spec.\u03b9), spec.domain i \u2192 oracle_comp spec' (spec.range i))\n(state_f : \u03a0 (s : S) (i : spec.\u03b9), spec.domain i \u2192 spec.range i \u2192 S)\n(apply_equiv_state_f_map_query_f : \u2200 (i : spec.\u03b9) (t : spec.domain i) (s : S),\n  so i (t, s) \u2243\u209a (\u03bb u, (u, state_f s i t u)) <$> query_f i t)\n\nvariables (so : sim_oracle spec spec' S) (i : spec.\u03b9)\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.\u03b9) (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.\u03b9)\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  ((\u03bb u, (u, so.update_state s i t u)) <$> so.answer_query i t).support :=\nby simp_rw [\u2190 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  (\u03bb 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 [\u2200 i t, (so.o i t).decidable] [\u2200 i t, (so.answer_query i t).decidable]\n\nlemma fin_support_apply' [decidable_eq S] : (so i (t, s)).fin_support =\n  ((\u03bb 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 (\u03bb 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' : \u2045so i (t, s)\u2046 =\n  \u2045(\u03bb u, (u, so.update_state s i t u)) <$> so.answer_query i t\u2046 :=\napply_equiv_state_f_map_query_f i t s\n\n@[simp] lemma eval_dist_apply : \u2045so i (t, s)\u2046 =\n  \u2045so.answer_query i t\u2046.map (\u03bb 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 \u00d7 S)) : \u2045e | so i (t, s)\u2046 =\n  \u2045e | (\u03bb u, (u, so.update_state s i t u)) <$> so.answer_query i t\u2046 :=\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 \u00d7 S)) : \u2045e | so i (t, s)\u2046 =\n  \u2045(\u03bb u, (u, so.update_state s i t u)) \u207b\u00b9' e | so.answer_query i t\u2046 :=\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 James Gallicchio.\n\nAuthors: James Gallicchio\n-/\n\nimport LeanColls.Array.Basic\n\nnamespace LeanColls\n\nstructure COWArray (\u03b1 n) where\n  backing : Array \u03b1 n\nderiving Inhabited, Repr\n\nnamespace COWArray\nvariable (A : COWArray \u03b1 n)\n\ndef new (x : \u03b1) (n : Nat) := Array.new x n |> COWArray.mk\ndef empty : COWArray \u03b1 0 := \u27e8Array.empty\u27e9\ndef singleton (x : \u03b1) : COWArray \u03b1 1 := \u27e8Array.init (\u03bb _ => x)\u27e9\n\n@[inline] def get : Fin n \u2192 \u03b1 := A.backing.get\n@[inline] def set (i : Fin n) (x : \u03b1) : COWArray \u03b1 n :=\n  A.backing.copyIfShared |>.set i x |> COWArray.mk\n\n@[inline] def update (i : Fin n) (f : \u03b1 \u2192 \u03b1) : COWArray \u03b1 n :=\n  A.set i (f <| A.get i)\n\n@[inline] def cons (x : \u03b1) : COWArray \u03b1 n.succ :=\n  \u27e8Array.init (\u03bb i => match i with\n    | \u27e80,_\u27e9 => x\n    | \u27e8i+1,h\u27e9 => A.get \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9)\u27e9\n\n@[inline] def snoc (x : \u03b1) : COWArray \u03b1 n.succ :=\n  \u27e8Array.init (\u03bb i =>\n    if h:i.val < n then\n      A.get \u27e8i, h\u27e9\n    else x)\u27e9\n\n@[inline] def front (A : COWArray \u03b1 n.succ) : \u03b1 \u00d7 COWArray \u03b1 n :=\n  (A.get \u27e80, Nat.zero_lt_succ _\u27e9,\n  \u27e8Array.init (\u03bb i => A.get i.succ)\u27e9)\n\n@[inline] def back (A : COWArray \u03b1 n.succ) : COWArray \u03b1 n \u00d7 \u03b1 :=\n  (\u27e8Array.init (\u03bb i => A.get i.embed_succ)\u27e9,\n  A.get \u27e8n, Nat.lt_succ_self _\u27e9)\n\ninstance : FoldableOps (COWArray \u03b1 n) \u03b1 := FoldableOps.mapImpl (COWArray.backing)\n\ninstance : Indexed (COWArray \u03b1 n) \u03b1 where\n  size _ := n\n  nth := get\n\ninstance : IndexedOps (COWArray \u03b1 n) \u03b1 := default\n\n@[simp]\ntheorem fold_eq_backing_fold (A : COWArray \u03b1 n)\n  : \u2200 {\u03b2}, Foldable.fold A (\u03b2 := \u03b2) = Foldable.fold A.backing\n  := by\n  intro \u03b2\n  simp [Foldable.fold, Size.size, Indexed.nth, get]\n\n@[simp]\ntheorem backing_set (A : COWArray \u03b1 n) (i : Fin n) (x : \u03b1)\n  : (A.set i x).backing = A.backing.set i x\n  := by\n  simp [set, Array.copyIfShared_def]\n", "meta": {"author": "JamesGallicchio", "repo": "LeanColls", "sha": "9cb0a0c9a838bea24be80eace168bcc5f9481596", "save_path": "github-repos/lean/JamesGallicchio-LeanColls", "path": "github-repos/lean/JamesGallicchio-LeanColls/LeanColls-9cb0a0c9a838bea24be80eace168bcc5f9481596/LeanColls/Array/COWArray.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.06187597966883276, "lm_q1q2_score": 0.029730088914199936}}
{"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 \u2192 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 \u2190 mvarId.getType'\n  let some (_, lhs, rhs) := target.eq? | return none\n  unless rhs.isLet || rhs.isMData do return none\n  return some (\u2190 mvarId.replaceTargetDefEq (\u2190 mkEq lhs (expand rhs)))\n\ndef funext? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let target \u2190 mvarId.getType'\n  let some (_, _, rhs) := target.eq? | return none\n  unless rhs.isLambda do return none\n  commitWhenSome? do\n    let [mvarId] \u2190 mvarId.apply (\u2190 mkConstWithFreshMVarLevels ``funext) | return none\n    let (_, mvarId) \u2190 mvarId.intro1\n    return some mvarId\n\ndef simpMatch? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let mvarId' \u2190 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' \u2190 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 \u2190 mvarId.getType'\n  let rec go (badCases : ExprSet) : MetaM (Option (List MVarId)) := do\n    if let some e := findMatchToSplit? (\u2190 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, _) \u2190 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 \u00b7 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 (\u2190 instantiateMVars eqnType) fun ys type => do\n    let proofVars := collect type\n    trace[Elab.definition] \"simpEqnType type: {type}\"\n    let mut type \u2190 Match.unfoldNamedPattern type\n    let mut eliminated : FVarIdSet := {}\n    for y in ys.reverse do\n      trace[Elab.definition] \">> simpEqnType: {\u2190 inferType y}, {type}\"\n      if proofVars.contains y.fvarId! then\n        let some (_, Expr.fvar fvarId, rhs) \u2190 matchEq? (\u2190 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 (\u2190 dependsOn type y.fvarId!) then\n          type \u2190 mkForallFVars #[y] type\n      else\n        if let some (_, lhs, rhs) \u2190 matchEq? (\u2190 inferType y) then\n          if (\u2190 isDefEq lhs rhs) then\n            if !(\u2190 dependsOn type y.fvarId!) then\n              continue\n            else if !(\u2190 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 (\u2190 mkEqRefl lhs)\n              continue\n        type \u2190 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) (\u03c9) : ST \u03c9 FVarIdSet := do\n      let ref \u2190 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 (\u00b7.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 \u2190 mvarId.getType'\n  let fvarState := collectFVars {} target\n  let fvarState \u2190 (\u2190 getLCtx).foldrM (init := fvarState) fun decl fvarState => do\n    if fvarState.fvarSet.contains decl.fvarId then\n      return collectFVars fvarState (\u2190 instantiateMVars decl.type)\n    else\n      return fvarState\n  let mut fvarIdSet := fvarState.fvarSet\n  let mut fvarIds \u2190 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 (\u2190 getLCtx) do\n      unless fvarIdSet.contains decl.fvarId do\n        if (\u2190 isProp decl.type) then\n          let type \u2190 instantiateMVars decl.type\n          unless (\u2190 isIrrelevant fvarIdSet type) do\n            modified := true\n            (fvarIdSet, fvarIds) \u2190 pushDecl fvarIdSet fvarIds decl\n  until !modified\n  let type \u2190 mkForallFVars (fvarIds.map mkFVar) target\n  let type \u2190 simpEqnType type\n  modify (\u00b7.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 \u00d7 Array FVarId) := do\n    let (fvarIdSet, fvarIds) \u2190 collectDeps fvarIdSet fvarIds (\u2190 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 \u00d7 Array FVarId) := do\n    let s := collectFVars {} type\n    let usedFVarIds \u2190 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) \u2190 pushDecl fvarIdSet fvarIds (\u2190 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 \u2190 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) \u2190 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 (\u2190 tryURefl mvarId) then\n      saveEqn mvarId\n      return ()\n\n    if let some mvarId \u2190 expandRHS? mvarId then\n      return (\u2190 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 \u2190 funext? mvarId then\n        return (\u2190 go mvarId) -/\n\n    if (\u2190 shouldUseSimpMatch (\u2190 mvarId.getType')) then\n      if let some mvarId \u2190 simpMatch? mvarId then\n        return (\u2190 go mvarId)\n\n    if let some mvarIds \u2190 splitMatch? mvarId declNames then\n      return (\u2190 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 \u00d7 Expr) := do\n  go declType declValue #[] {}\nwhere\n  go (type value : Expr) (xs : Array Expr) (lctx : LocalContext) : CoreM (Expr \u00d7 Expr) := do\n    match value with\n    | .lam n d b bi =>\n      let d := d.instantiateRev xs\n      let fvarId \u2190 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 \u2190 mvarId.getType'\n  let some (_, lhs, rhs) := target.eq? | throwTacticEx `deltaLHS mvarId \"equality expected\"\n  let some lhs \u2190 delta? lhs | throwTacticEx `deltaLHS mvarId \"failed to delta reduce lhs\"\n  mvarId.replaceTargetDefEq (\u2190 mkEq lhs rhs)\n\ndef deltaRHS? (mvarId : MVarId) (declName : Name) : MetaM (Option MVarId) := mvarId.withContext do\n  let target \u2190 mvarId.getType'\n  let some (_, lhs, rhs) := target.eq? | return none\n  let some rhs \u2190 delta? rhs.consumeMData (\u00b7 == declName) | return none\n  mvarId.replaceTargetDefEq (\u2190 mkEq lhs rhs)\n\nprivate partial def whnfAux (e : Expr) : MetaM Expr := do\n  let e \u2190 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! (\u2190 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 \u2190 mvarId.getType'\n  let some (_, lhs, rhs) := target.eq? | return none\n  let lhs' \u2190 whnfAux lhs\n  if lhs' != lhs then\n    return some (\u2190 mvarId.replaceTargetDefEq (\u2190 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 \u2190\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 \u2190 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 \u2190 mvarId.apply (\u2190 mkConstWithFreshMVarLevels eq)\n        subgoals.allM fun subgoal => do\n          if (\u2190 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 (\u2190 tryEqns mvarId) then\n      return ()\n    -- Remark: we removed funext? from `mkEqnTypes`\n    -- else if let some mvarId \u2190 funext? mvarId then\n    --  go mvarId\n\n    if (\u2190 shouldUseSimpMatch (\u2190 mvarId.getType')) then\n      if let some mvarId \u2190 simpMatch? mvarId then\n        return (\u2190 go mvarId)\n\n    if let some mvarIds \u2190 splitTarget? mvarId (splitIte := false) then\n      return (\u2190 mvarIds.forM go)\n\n    if (\u2190 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 \u2190 getEnv\n  withOptions (tactic.hygienic.set \u00b7 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 \u2190 mkEq (mkAppN (Lean.mkConst declName us) xs) body\n      let goal \u2190 mkFreshExprSyntheticOpaqueMVar type\n      mkUnfoldProof declName goal.mvarId!\n      let type \u2190 mkForallFVars xs type\n      let value \u2190 mkLambdaFVars xs (\u2190 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 \u2192 Option EqnInfoCore) : MetaM (Option Name) := do\n  let env \u2190 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 \u2190 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": "/-\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, Robert Y. Lewis, Arthur Paulino, Gabriel Ebner\n-/\nimport Lean.Util.CollectLevelParams\nimport Lean.Meta.ForEachExpr\nimport Std.Tactic.Lint.Basic\nimport Std.Data.Array.Basic\n\nopen Lean Meta\n\nnamespace Std.Tactic.Lint\n\n/-!\n# Various linters\n\nThis file defines several small linters.\n-/\n\n/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/\n@[std_linter] def dupNamespace : Linter where\n  noErrorsFound := \"No declarations have a duplicate namespace.\"\n  errorsFound := \"DUPLICATED NAMESPACES IN NAME:\"\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    if isGlobalInstance (\u2190 getEnv) declName then return none\n    let nm := declName.components\n    let some (dup, _) := nm.zip nm.tail! |>.find? fun (x, y) => x == y\n      | return none\n    return m!\"The namespace {dup} is duplicated in the name\"\n\n/-- A linter for checking for unused arguments.\nWe skip all declarations that contain `sorry` in their value. -/\n@[std_linter] def unusedArguments : Linter where\n  noErrorsFound := \"No unused arguments.\"\n  errorsFound := \"UNUSED ARGUMENTS.\"\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    if \u2190 isProjectionFn declName then return none\n    let info \u2190 getConstInfo declName\n    let ty := info.type\n    let some val := info.value? | return none\n    forallTelescope ty fun args ty => do\n      let mut e := (mkAppN val args).headBeta\n      e := mkApp e ty\n      for arg in args do\n        let ldecl \u2190 getFVarLocalDecl arg\n        e := mkApp e ldecl.type\n        if let some val := ldecl.value? then\n          e := mkApp e val\n      let unused := args.zip (.range args.size) |>.filter fun (arg, _) =>\n        !e.containsFVar arg.fvarId!\n      if unused.isEmpty then return none\n      addMessageContextFull <| .joinSep (\u2190 unused.toList.mapM fun (arg, i) =>\n          return m!\"argument {i+1} {arg} : {\u2190 inferType arg}\") m!\", \"\n\n/-- A linter for checking definition doc strings. -/\n@[std_linter] def docBlame : Linter where\n  noErrorsFound := \"No definitions are missing documentation.\"\n  errorsFound := \"DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:\"\n  test declName := do\n    if (\u2190 isAutoDecl declName) || isGlobalInstance (\u2190 getEnv) declName then\n      return none\n    if let .str _ s := declName then\n      if s == \"parenthesizer\" || s == \"formatter\" || s == \"delaborator\" || s == \"quot\" then\n      return none\n    let kind \u2190 match \u2190 getConstInfo declName with\n      | .axiomInfo .. => pure \"axiom\"\n      | .opaqueInfo .. => pure \"constant\"\n      | .defnInfo .. => pure \"definition\"\n      | .inductInfo .. => pure \"inductive\"\n      | _ => return none\n    let (none) \u2190 findDocString? (\u2190 getEnv) declName | return none\n    return m!\"{kind} missing documentation string\"\n\n/-- A linter for checking theorem doc strings. -/\n@[std_linter disabled] def docBlameThm : Linter where\n  noErrorsFound := \"No theorems are missing documentation.\"\n  errorsFound := \"THEOREMS ARE MISSING DOCUMENTATION STRINGS:\"\n  test declName := do\n    if \u2190 isAutoDecl declName then\n      return none\n    let kind \u2190 match \u2190 getConstInfo declName with\n      | .thmInfo .. => pure \"theorem\"\n      | _ => return none\n    let (none) \u2190 findDocString? (\u2190 getEnv) declName | return none\n    return m!\"{kind} missing documentation string\"\n\n/-- A linter for checking whether the correct declaration constructor (definition or theorem)\nhas been used. -/\n@[std_linter] def defLemma : Linter where\n  noErrorsFound := \"All declarations correctly marked as def/lemma.\"\n  errorsFound := \"INCORRECT DEF/LEMMA:\"\n  test declName := do\n    if (\u2190 isAutoDecl declName) || isGlobalInstance (\u2190 getEnv) declName then\n      return none\n    if \u2190 isProjectionFn declName then return none\n    let info \u2190 getConstInfo declName\n    let isThm \u2190 match info with\n      | .defnInfo .. => pure false\n      | .thmInfo .. => pure true\n      | _ => return none\n    match isThm, \u2190 isProp info.type with\n    | true, false => pure \"is a lemma/theorem, should be a def\"\n    | false, true => pure \"is a def, should be lemma/theorem\"\n    | _, _ => return none\n\n/-- A linter for missing checking whether statements of declarations are well-typed. -/\n@[std_linter] def checkType : Linter where\n  noErrorsFound :=\n    \"The statements of all declarations type-check with default reducibility settings.\"\n  errorsFound := \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK.\"\n  isFast := true\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    if \u2190 isTypeCorrect (\u2190 getConstInfo declName).type then return none\n    return m!\"the statement doesn't type check.\"\n\n/--\n`univParamsGrouped e` computes for each `level` `u` of `e` the parameters that occur in `u`,\nand returns the corresponding set of lists of parameters.\nIn pseudo-mathematical form, this returns `{{p : parameter | p \u2208 u} | (u : level) \u2208 e}`\nFIXME: We use `Array Name` instead of `HashSet Name`, since `HashSet` does not have an equality\ninstance. It will ignore `nm\u2080.proof_i` declarations.\n-/\nprivate def univParamsGrouped (e : Expr) (nm\u2080 : Name) : Lean.HashSet (Array Name) :=\n  runST fun \u03c3 => do\n    let res \u2190 ST.mkRef (\u03c3 := \u03c3) {}\n    e.forEach fun\n      | .sort u =>\n        res.modify (\u00b7.insert (CollectLevelParams.visitLevel u {}).params)\n      | .const n us => do\n        if let .str n s .. := n then\n          if n == nm\u2080 && s.startsWith \"proof_\" then\n            return\n        res.modify <| us.foldl (\u00b7.insert <| CollectLevelParams.visitLevel \u00b7 {} |>.params)\n      | _ => pure ()\n    res.get\n\n/--\nThe good parameters are the parameters that occur somewhere in the set as a singleton or\n(recursively) with only other good parameters.\nAll other parameters in the set are bad.\n-/\nprivate partial def badParams (l : Array (Array Name)) : Array Name :=\n  let goodLevels := l.filterMap fun\n    | #[u] => some u\n    | _ => none\n  if goodLevels.isEmpty then\n    l.flatten.toList.eraseDups.toArray\n  else\n    badParams <| l.map (\u00b7.filter (!goodLevels.contains \u00b7))\n\n/-- A linter for checking that there are no bad `max u v` universe levels.\nChecks whether all universe levels `u` in the type of `d` are \"good\".\nThis means that `u` either occurs in a `level` of `d` by itself, or (recursively)\nwith only other good levels.\nWhen this fails, usually this means that there is a level `max u v`, where neither `u` nor `v`\noccur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example,\n`(\u03b1 : Type u) (\u03b2 : Type (max u v))` is a occasionally useful method of saying that `\u03b2` lives in\na higher universe level than `\u03b1`.\n-/\n@[std_linter] def checkUnivs : Linter where\n  noErrorsFound :=\n    \"All declarations have good universe levels.\"\n  errorsFound := \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. \" ++\n\"This usually means that there is a `max u v` in the type where neither `u` nor `v` \" ++\n\"occur by themselves. Solution: Find the type (or type bundled with data) that has this \" ++\n\"universe argument and provide the universe level explicitly. If this happens in an implicit \" ++\n\"argument of the declaration, a better solution is to move this argument to a `variables` \" ++\n\"command (then it's not necessary to provide the universe level).\nIt is possible that this linter gives a false positive on definitions where the value of the \" ++\n\"definition has the universes occur separately, and the definition will usually be used with \" ++\n\"explicit universe arguments. In this case, feel free to add `@[nolint checkUnivs]`.\"\n  isFast := true\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    let bad := badParams (univParamsGrouped (\u2190 getConstInfo declName).type declName).toArray\n    if bad.isEmpty then return none\n    return m!\"universes {bad} only occur together.\"\n\n/-- A linter for checking that declarations aren't syntactic tautologies.\nChecks whether a lemma is a declaration of the form `\u2200 a b ... z, e\u2081 = e\u2082`\nwhere `e\u2081` and `e\u2082` are identical exprs.\nWe call declarations of this form syntactic tautologies.\nSuch lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts\nwith rfl when elaboration results in a different term than the user intended. -/\n@[std_linter] def synTaut : Linter where\n  noErrorsFound :=\n    \"No declarations are syntactic tautologies.\"\n  errorsFound := \"THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. \" ++\n\"This usually means that they are of the form `\u2200 a b ... z, e\u2081 = e\u2082` where `e\u2081` and `e\u2082` are \" ++\n\"identical expressions. We call declarations of this form syntactic tautologies. \" ++\n\"Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving \" ++\n\"basic facts using `rfl`, when elaboration results in a different term than the user intended. \" ++\n\"You should check that the declaration really says what you think it does.\"\n  isFast := true\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    forallTelescope (\u2190 getConstInfo declName).type fun _ ty => do\n      let some (lhs, rhs) := ty.eq?.map (fun (_, l, r) => (l, r)) <|> ty.iff?\n        | return none\n      if lhs == rhs then\n        return m!\"LHS equals RHS syntactically\"\n      return none\n\n/--\nReturn a list of unused have/suffices/let_fun terms in an expression.\nThis actually finds all beta-redexes.\n-/\ndef findUnusedHaves (e : Expr) : MetaM (Array MessageData) := do\n  let res \u2190 IO.mkRef #[]\n  forEachExpr e fun e => do\n    let some e := letFunAnnotation? e | return\n    let Expr.app (Expr.lam n t b ..) _ .. := e | return\n    if n.isInternal then return\n    if b.hasLooseBVars then return\n    let msg \u2190 addMessageContextFull m!\"unnecessary have {n.eraseMacroScopes} : {t}\"\n    res.modify (\u00b7.push msg)\n  res.get\n\n/-- A linter for checking that declarations don't have unused term mode have statements. We do not\ntag this as `@[std_linter]` so that it is not in the default linter set as it is slow and an\nuncommon problem. -/\n@[std_linter] def unusedHavesSuffices : Linter where\n  noErrorsFound := \"No declarations have unused term mode have statements.\"\n  errorsFound := \"THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. \" ++\n    \"In the case of `have` this is a term of the form `have h := foo, bar` where `bar` does not \" ++\n    \"refer to `foo`. Such statements have no effect on the generated proof, and can just be \" ++\n    \"replaced by `bar`, in addition to being ineffectual, they may make unnecessary assumptions \" ++\n    \"in proofs appear as if they are used. \" ++\n    \"For `suffices` this is a term of the form `suffices h : foo, proof_of_goal, proof_of_foo` where\" ++\n    \" `proof_of_goal` does not refer to `foo`. \" ++\n    \"Such statements have no effect on the generated proof, and can just be replaced by \" ++\n    \"`proof_of_goal`, in addition to being ineffectual, they may make unnecessary assumptions in \" ++\n    \"proofs appear as if they are used. \"\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    let info \u2190 getConstInfo declName\n    let mut unused \u2190 findUnusedHaves info.type\n    if let some value := info.value? then\n      unused := unused ++ (\u2190 findUnusedHaves value)\n    unless unused.isEmpty do\n      return some <| .joinSep unused.toList \", \"\n    return none\n\n/--\nA linter for checking if variables appearing on both sides of an iff are explicit. Ideally, such\nvariables should be implicit instead.\n-/\n@[std_linter disabled] def explicitVarsOfIff : Linter where\n  noErrorsFound := \"No explicit variables on both sides of iff\"\n  errorsFound := \"EXPLICIT VARIABLES ON BOTH SIDES OF IFF\"\n  test declName := do\n    if \u2190 isAutoDecl declName then return none\n    forallTelescope (\u2190 getConstInfo declName).type fun args ty => do\n      let some (lhs, rhs) := ty.iff? | return none\n      let explicit \u2190 args.filterM fun arg =>\n        return (\u2190 getFVarLocalDecl arg).binderInfo.isExplicit &&\n          lhs.containsFVar arg.fvarId! && rhs.containsFVar arg.fvarId!\n      if explicit.isEmpty then return none\n      addMessageContextFull m!\"should be made implicit: {\n        MessageData.joinSep (explicit.toList.map (m!\"{\u00b7}\")) \", \"}\"\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/Lint/Misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.09670579785197646, "lm_q1q2_score": 0.02972330102003959}}
{"text": "/- Additional theroems for option. -/\nnamespace option\n\ntheorem failure_is_none (\u03b1 : Type _) : (failure : option \u03b1) = none := rfl\n\ntheorem coe_is_some {\u03b1 : Type _} (x:\u03b1) : (coe x : option \u03b1) = some x := rfl\n\ntheorem or_else_none {\u03b1 : Type _} (x : option \u03b1) : (x <|> none) = x :=\nbegin\n  cases x; trivial,\nend\n\ntheorem none_or_else {\u03b1 : Type _} (x : option \u03b1) : (none <|> x) = x :=\nbegin\n  cases x; trivial,\nend\n\ntheorem some_or_else {\u03b1 : Type _} (x : \u03b1) (y : option \u03b1) : (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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes H\u00f6lzl\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 {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} [Inhabited \u03b1]\n    [Inhabited (\u03b2 Inhabited.default)] : Inhabited (sigma \u03b2) :=\n  { default := mk Inhabited.default Inhabited.default }\n\nprotected instance decidable_eq {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} [h\u2081 : DecidableEq \u03b1]\n    [h\u2082 : (a : \u03b1) \u2192 DecidableEq (\u03b2 a)] : DecidableEq (sigma \u03b2) :=\n  sorry\n\n@[simp] theorem mk.inj_iff {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081}\n    {b\u2082 : \u03b2 a\u2082} : mk a\u2081 b\u2081 = mk a\u2082 b\u2082 \u2194 a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082 :=\n  sorry\n\n@[simp] theorem eta {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} (x : sigma fun (a : \u03b1) => \u03b2 a) :\n    mk (fst x) (snd x) = x :=\n  cases_on x\n    fun (x_fst : \u03b1) (x_snd : \u03b2 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 {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {x\u2080 : sigma \u03b2} {x\u2081 : sigma \u03b2} (h\u2080 : fst x\u2080 = fst x\u2081)\n    (h\u2081 : snd x\u2080 == snd x\u2081) : x\u2080 = x\u2081 :=\n  sorry\n\ntheorem ext_iff {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {x\u2080 : sigma \u03b2} {x\u2081 : sigma \u03b2} :\n    x\u2080 = x\u2081 \u2194 fst x\u2080 = fst x\u2081 \u2227 snd x\u2080 == snd x\u2081 :=\n  cases_on x\u2080\n    fun (x\u2080_fst : \u03b1) (x\u2080_snd : \u03b2 x\u2080_fst) =>\n      cases_on x\u2081 fun (x\u2081_fst : \u03b1) (x\u2081_snd : \u03b2 x\u2081_fst) => mk.inj_iff\n\n@[simp] theorem forall {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {p : (sigma fun (a : \u03b1) => \u03b2 a) \u2192 Prop} :\n    (\u2200 (x : sigma fun (a : \u03b1) => \u03b2 a), p x) \u2194 \u2200 (a : \u03b1) (b : \u03b2 a), p (mk a b) :=\n  sorry\n\n@[simp] theorem exists {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {p : (sigma fun (a : \u03b1) => \u03b2 a) \u2192 Prop} :\n    (\u2203 (x : sigma fun (a : \u03b1) => \u03b2 a), p x) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2 a), p (mk a b) :=\n  sorry\n\n/-- Map the left and right components of a sigma -/\ndef map {\u03b1\u2081 : Type u_2} {\u03b1\u2082 : Type u_3} {\u03b2\u2081 : \u03b1\u2081 \u2192 Type u_5} {\u03b2\u2082 : \u03b1\u2082 \u2192 Type u_6} (f\u2081 : \u03b1\u2081 \u2192 \u03b1\u2082)\n    (f\u2082 : (a : \u03b1\u2081) \u2192 \u03b2\u2081 a \u2192 \u03b2\u2082 (f\u2081 a)) (x : sigma \u03b2\u2081) : sigma \u03b2\u2082 :=\n  mk (f\u2081 (fst x)) (f\u2082 (fst x) (snd x))\n\nend sigma\n\n\ntheorem sigma_mk_injective {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {i : \u03b1} :\n    function.injective (sigma.mk i) :=\n  sorry\n\ntheorem function.injective.sigma_map {\u03b1\u2081 : Type u_2} {\u03b1\u2082 : Type u_3} {\u03b2\u2081 : \u03b1\u2081 \u2192 Type u_5}\n    {\u03b2\u2082 : \u03b1\u2082 \u2192 Type u_6} {f\u2081 : \u03b1\u2081 \u2192 \u03b1\u2082} {f\u2082 : (a : \u03b1\u2081) \u2192 \u03b2\u2081 a \u2192 \u03b2\u2082 (f\u2081 a)}\n    (h\u2081 : function.injective f\u2081) (h\u2082 : \u2200 (a : \u03b1\u2081), function.injective (f\u2082 a)) :\n    function.injective (sigma.map f\u2081 f\u2082) :=\n  sorry\n\ntheorem function.surjective.sigma_map {\u03b1\u2081 : Type u_2} {\u03b1\u2082 : Type u_3} {\u03b2\u2081 : \u03b1\u2081 \u2192 Type u_5}\n    {\u03b2\u2082 : \u03b1\u2082 \u2192 Type u_6} {f\u2081 : \u03b1\u2081 \u2192 \u03b1\u2082} {f\u2082 : (a : \u03b1\u2081) \u2192 \u03b2\u2081 a \u2192 \u03b2\u2082 (f\u2081 a)}\n    (h\u2081 : function.surjective f\u2081) (h\u2082 : \u2200 (a : \u03b1\u2081), function.surjective (f\u2082 a)) :\n    function.surjective (sigma.map f\u2081 f\u2082) :=\n  sorry\n\n/-- Interpret a function on `\u03a3 x : \u03b1, \u03b2 x` as a dependent function with two arguments. -/\ndef sigma.curry {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {\u03b3 : (a : \u03b1) \u2192 \u03b2 a \u2192 Type u_2}\n    (f : (x : sigma \u03b2) \u2192 \u03b3 (sigma.fst x) (sigma.snd x)) (x : \u03b1) (y : \u03b2 x) : \u03b3 x y :=\n  f (sigma.mk x y)\n\n/-- Interpret a dependent function with two arguments as a function on `\u03a3 x : \u03b1, \u03b2 x` -/\ndef sigma.uncurry {\u03b1 : Type u_1} {\u03b2 : \u03b1 \u2192 Type u_4} {\u03b3 : (a : \u03b1) \u2192 \u03b2 a \u2192 Type u_2}\n    (f : (x : \u03b1) \u2192 (y : \u03b2 x) \u2192 \u03b3 x y) (x : sigma \u03b2) : \u03b3 (sigma.fst x) (sigma.snd x) :=\n  f (sigma.fst x) (sigma.snd x)\n\n/-- Convert a product type to a \u03a3-type. -/\n@[simp] def prod.to_sigma {\u03b1 : Type u_1} {\u03b2 : Type u_2} : \u03b1 \u00d7 \u03b2 \u2192 sigma fun (_x : \u03b1) => \u03b2 := sorry\n\n@[simp] theorem prod.fst_to_sigma {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b1 \u00d7 \u03b2) :\n    sigma.fst (prod.to_sigma x) = prod.fst x :=\n  prod.cases_on x fun (x_fst : \u03b1) (x_snd : \u03b2) => Eq.refl (sigma.fst (prod.to_sigma (x_fst, x_snd)))\n\n@[simp] theorem prod.snd_to_sigma {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b1 \u00d7 \u03b2) :\n    sigma.snd (prod.to_sigma x) = prod.snd x :=\n  prod.cases_on x fun (x_fst : \u03b1) (x_snd : \u03b2) => Eq.refl (sigma.snd (prod.to_sigma (x_fst, x_snd)))\n\nnamespace psigma\n\n\n/-- Nondependent eliminator for `psigma`. -/\ndef elim {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {\u03b3 : Sort u_3} (f : (a : \u03b1) \u2192 \u03b2 a \u2192 \u03b3) (a : psigma \u03b2) :\n    \u03b3 :=\n  cases_on a f\n\n@[simp] theorem elim_val {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {\u03b3 : Sort u_3} (f : (a : \u03b1) \u2192 \u03b2 a \u2192 \u03b3)\n    (a : \u03b1) (b : \u03b2 a) : elim f (mk a b) = f a b :=\n  rfl\n\nprotected instance inhabited {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} [Inhabited \u03b1]\n    [Inhabited (\u03b2 Inhabited.default)] : Inhabited (psigma \u03b2) :=\n  { default := mk Inhabited.default Inhabited.default }\n\nprotected instance decidable_eq {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} [h\u2081 : DecidableEq \u03b1]\n    [h\u2082 : (a : \u03b1) \u2192 DecidableEq (\u03b2 a)] : DecidableEq (psigma \u03b2) :=\n  sorry\n\ntheorem mk.inj_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081} {b\u2082 : \u03b2 a\u2082} :\n    mk a\u2081 b\u2081 = mk a\u2082 b\u2082 \u2194 a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082 :=\n  sorry\n\ntheorem ext {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {x\u2080 : psigma \u03b2} {x\u2081 : psigma \u03b2} (h\u2080 : fst x\u2080 = fst x\u2081)\n    (h\u2081 : snd x\u2080 == snd x\u2081) : x\u2080 = x\u2081 :=\n  sorry\n\ntheorem ext_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {x\u2080 : psigma \u03b2} {x\u2081 : psigma \u03b2} :\n    x\u2080 = x\u2081 \u2194 fst x\u2080 = fst x\u2081 \u2227 snd x\u2080 == snd x\u2081 :=\n  cases_on x\u2080\n    fun (x\u2080_fst : \u03b1) (x\u2080_snd : \u03b2 x\u2080_fst) =>\n      cases_on x\u2081 fun (x\u2081_fst : \u03b1) (x\u2081_snd : \u03b2 x\u2081_fst) => mk.inj_iff\n\n/-- Map the left and right components of a sigma -/\ndef map {\u03b1\u2081 : Sort u_3} {\u03b1\u2082 : Sort u_4} {\u03b2\u2081 : \u03b1\u2081 \u2192 Sort u_5} {\u03b2\u2082 : \u03b1\u2082 \u2192 Sort u_6} (f\u2081 : \u03b1\u2081 \u2192 \u03b1\u2082)\n    (f\u2082 : (a : \u03b1\u2081) \u2192 \u03b2\u2081 a \u2192 \u03b2\u2082 (f\u2081 a)) : psigma \u03b2\u2081 \u2192 psigma \u03b2\u2082 :=\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<http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html>\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\u2080 u\u2081 v\u2080 v\u2081 \n\nnamespace Mathlib\n\nstructure monad_cont.label (\u03b1 : Type w) (m : Type u \u2192 Type v) (\u03b2 : Type u) where\n  apply : \u03b1 \u2192 m \u03b2\n\ndef monad_cont.goto {\u03b1 : Type u_1} {\u03b2 : Type u} {m : Type u \u2192 Type v} (f : monad_cont.label \u03b1 m \u03b2)\n    (x : \u03b1) : m \u03b2 :=\n  monad_cont.label.apply f x\n\nclass monad_cont (m : Type u \u2192 Type v) where\n  call_cc : {\u03b1 \u03b2 : Type u} \u2192 (monad_cont.label \u03b1 m \u03b2 \u2192 m \u03b1) \u2192 m \u03b1\n\nclass is_lawful_monad_cont (m : Type u \u2192 Type v) [Monad m] [monad_cont m] extends is_lawful_monad m\n    where\n  call_cc_bind_right :\n    \u2200 {\u03b1 \u03c9 \u03b3 : Type u} (cmd : m \u03b1) (next : monad_cont.label \u03c9 m \u03b3 \u2192 \u03b1 \u2192 m \u03c9),\n      (monad_cont.call_cc fun (f : monad_cont.label \u03c9 m \u03b3) => cmd >>= next f) =\n        do \n          let x \u2190 cmd \n          monad_cont.call_cc fun (f : monad_cont.label \u03c9 m \u03b3) => next f x\n  call_cc_bind_left :\n    \u2200 {\u03b1 : Type u} (\u03b2 : Type u) (x : \u03b1) (dead : monad_cont.label \u03b1 m \u03b2 \u2192 \u03b2 \u2192 m \u03b1),\n      (monad_cont.call_cc fun (f : monad_cont.label \u03b1 m \u03b2) => monad_cont.goto f x >>= dead f) =\n        pure x\n  call_cc_dummy :\n    \u2200 {\u03b1 \u03b2 : Type u} (dummy : m \u03b1),\n      (monad_cont.call_cc fun (f : monad_cont.label \u03b1 m \u03b2) => dummy) = dummy\n\ndef cont_t (r : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type w) := (\u03b1 \u2192 m r) \u2192 m r\n\ndef cont (r : Type u) (\u03b1 : Type w) := cont_t r id \u03b1\n\nnamespace cont_t\n\n\ndef run {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} : cont_t r m \u03b1 \u2192 (\u03b1 \u2192 m r) \u2192 m r := id\n\ndef map {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} (f : m r \u2192 m r) (x : cont_t r m \u03b1) :\n    cont_t r m \u03b1 :=\n  f \u2218 x\n\ntheorem run_cont_t_map_cont_t {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} (f : m r \u2192 m r)\n    (x : cont_t r m \u03b1) : run (map f x) = f \u2218 run x :=\n  rfl\n\ndef with_cont_t {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} {\u03b2 : Type w}\n    (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b2 :=\n  fun (g : \u03b2 \u2192 m r) => x (f g)\n\ntheorem run_with_cont_t {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} {\u03b2 : Type w}\n    (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) : run (with_cont_t f x) = run x \u2218 f :=\n  rfl\n\nprotected theorem ext {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} {x : cont_t r m \u03b1}\n    {y : cont_t r m \u03b1} (h : \u2200 (f : \u03b1 \u2192 m r), run x f = run y f) : x = y :=\n  funext fun (x_1 : \u03b1 \u2192 m r) => h x_1\n\nprotected instance monad {r : Type u} {m : Type u \u2192 Type v} : Monad (cont_t r m) := sorry\n\nprotected instance is_lawful_monad {r : Type u} {m : Type u \u2192 Type v} :\n    is_lawful_monad (cont_t r m) :=\n  is_lawful_monad.mk\n    (fun (\u03b1 \u03b2 : Type u_1) (x : \u03b1) (f : \u03b1 \u2192 cont_t r m \u03b2) =>\n      cont_t.ext fun (f_1 : \u03b2 \u2192 m r) => Eq.refl (run (pure x >>= f) f_1))\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (x : cont_t r m \u03b1) (f : \u03b1 \u2192 cont_t r m \u03b2) (g : \u03b2 \u2192 cont_t r m \u03b3) =>\n      cont_t.ext fun (f_1 : \u03b3 \u2192 m r) => Eq.refl (run (x >>= f >>= g) f_1)\n\ndef monad_lift {r : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} : m \u03b1 \u2192 cont_t r m \u03b1 :=\n  fun (x : m \u03b1) (f : \u03b1 \u2192 m r) => x >>= f\n\nprotected instance has_monad_lift {r : Type u} {m : Type u \u2192 Type v} [Monad m] :\n    has_monad_lift m (cont_t r m) :=\n  has_monad_lift.mk fun (\u03b1 : Type u) => monad_lift\n\ntheorem monad_lift_bind {r : Type u} {m : Type u \u2192 Type v} [Monad m] [is_lawful_monad m]\n    {\u03b1 : Type u} {\u03b2 : Type u} (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) :\n    monad_lift (x >>= f) = monad_lift x >>= monad_lift \u2218 f :=\n  sorry\n\nprotected instance monad_cont {r : Type u} {m : Type u \u2192 Type v} : monad_cont (cont_t r m) :=\n  monad_cont.mk\n    fun (\u03b1 \u03b2 : Type u_1) (f : label \u03b1 (cont_t r m) \u03b2 \u2192 cont_t r m \u03b1) (g : \u03b1 \u2192 m r) =>\n      f (monad_cont.label.mk fun (x : \u03b1) (h : \u03b2 \u2192 m r) => g x) g\n\nprotected instance is_lawful_monad_cont {r : Type u} {m : Type u \u2192 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 \u2192 Type v} (\u03b5 : outParam (Type u_1))\n    [monad_except \u03b5 m] : monad_except \u03b5 (cont_t r m) :=\n  monad_except.mk (fun (x : Type u_2) (e : \u03b5) (f : x \u2192 m r) => throw e)\n    fun (\u03b1 : Type u_2) (act : cont_t r m \u03b1) (h : \u03b5 \u2192 cont_t r m \u03b1) (f : \u03b1 \u2192 m r) =>\n      catch (act f) fun (e : \u03b5) => h e f\n\nprotected instance monad_run {r : Type u} {m : Type u \u2192 Type v} :\n    monad_run (fun (\u03b1 : Type u) => (\u03b1 \u2192 m r) \u2192 ulift (m r)) (cont_t r m) :=\n  monad_run.mk fun (\u03b1 : Type u) (f : cont_t r m \u03b1) (x : \u03b1 \u2192 m r) => ulift.up (f x)\n\nend cont_t\n\n\ndef except_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b5 : Type u} :\n    label (except \u03b5 \u03b1) m \u03b2 \u2192 label \u03b1 (except_t \u03b5 m) \u03b2 :=\n  sorry\n\ntheorem except_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u}\n    {\u03b5 : Type u} (x : label (except \u03b5 \u03b1) m \u03b2) (i : \u03b1) :\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 \u03b5 \u03b1 \u2192 m \u03b2) => Eq.refl (goto (except_t.mk_label (monad_cont.label.mk x)) i)\n\ndef except_t.call_cc {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] {\u03b1 : Type u}\n    {\u03b2 : Type u} (f : label \u03b1 (except_t \u03b5 m) \u03b2 \u2192 except_t \u03b5 m \u03b1) : except_t \u03b5 m \u03b1 :=\n  except_t.mk\n    (monad_cont.call_cc fun (x : label (except \u03b5 \u03b1) m \u03b2) => except_t.run (f (except_t.mk_label x)))\n\nprotected instance except_t.monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] :\n    monad_cont (except_t \u03b5 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => except_t.call_cc\n\nprotected instance except_t.is_lawful_monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u}\n    [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t \u03b5 m) :=\n  is_lawful_monad_cont.mk sorry sorry sorry\n\ndef option_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} :\n    label (Option \u03b1) m \u03b2 \u2192 label \u03b1 (option_t m) \u03b2 :=\n  sorry\n\ntheorem option_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u}\n    (x : label (Option \u03b1) m \u03b2) (i : \u03b1) :\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 \u03b1 \u2192 m \u03b2) => Eq.refl (goto (option_t.mk_label (monad_cont.label.mk x)) i)\n\ndef option_t.call_cc {m : Type u \u2192 Type v} [Monad m] [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u}\n    (f : label \u03b1 (option_t m) \u03b2 \u2192 option_t m \u03b1) : option_t m \u03b1 :=\n  option_t.mk\n    (monad_cont.call_cc fun (x : label (Option \u03b1) m \u03b2) => option_t.run (f (option_t.mk_label x)))\n\nprotected instance option_t.monad_cont {m : Type u \u2192 Type v} [Monad m] [monad_cont m] :\n    monad_cont (option_t m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => option_t.call_cc\n\nprotected instance option_t.is_lawful_monad_cont {m : Type u \u2192 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 \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03b2 : Type u} {\u03c9 : Type u}\n    [HasOne \u03c9] : label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 label \u03b1 (writer_t \u03c9 m) \u03b2 :=\n  sorry\n\ntheorem writer_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03b2 : Type u}\n    {\u03c9 : Type u} [HasOne \u03c9] (x : label (\u03b1 \u00d7 \u03c9) m \u03b2) (i : \u03b1) :\n    goto (writer_t.mk_label x) i = monad_lift (goto x (i, 1)) :=\n  monad_cont.label.cases_on x\n    fun (x : \u03b1 \u00d7 \u03c9 \u2192 m \u03b2) => Eq.refl (goto (writer_t.mk_label (monad_cont.label.mk x)) i)\n\ndef writer_t.call_cc {m : Type u \u2192 Type v} [Monad m] [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u}\n    {\u03c9 : Type u} [HasOne \u03c9] (f : label \u03b1 (writer_t \u03c9 m) \u03b2 \u2192 writer_t \u03c9 m \u03b1) : writer_t \u03c9 m \u03b1 :=\n  writer_t.mk (monad_cont.call_cc (writer_t.run \u2218 f \u2218 writer_t.mk_label))\n\nprotected instance writer_t.monad_cont {m : Type u \u2192 Type v} [Monad m] (\u03c9 : Type u) [Monad m]\n    [HasOne \u03c9] [monad_cont m] : monad_cont (writer_t \u03c9 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => writer_t.call_cc\n\ndef state_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03c3 : Type u} :\n    label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3) \u2192 label \u03b1 (state_t \u03c3 m) \u03b2 :=\n  sorry\n\ntheorem state_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03c3 : Type u}\n    (x : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) (i : \u03b1) :\n    goto (state_t.mk_label x) i = state_t.mk fun (s : \u03c3) => goto x (i, s) :=\n  monad_cont.label.cases_on x\n    fun (x : \u03b1 \u00d7 \u03c3 \u2192 m (\u03b2 \u00d7 \u03c3)) => Eq.refl (goto (state_t.mk_label (monad_cont.label.mk x)) i)\n\ndef state_t.call_cc {m : Type u \u2192 Type v} [Monad m] {\u03c3 : Type u} [monad_cont m] {\u03b1 : Type u}\n    {\u03b2 : Type u} (f : label \u03b1 (state_t \u03c3 m) \u03b2 \u2192 state_t \u03c3 m \u03b1) : state_t \u03c3 m \u03b1 :=\n  state_t.mk\n    fun (r : \u03c3) =>\n      monad_cont.call_cc\n        fun (f' : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) => state_t.run (f (state_t.mk_label f')) r\n\nprotected instance state_t.monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c3 : Type u} [monad_cont m] :\n    monad_cont (state_t \u03c3 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => state_t.call_cc\n\nprotected instance state_t.is_lawful_monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c3 : Type u}\n    [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t \u03c3 m) :=\n  is_lawful_monad_cont.mk sorry sorry sorry\n\ndef reader_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03b2 : Type u} (\u03c1 : Type u) :\n    label \u03b1 m \u03b2 \u2192 label \u03b1 (reader_t \u03c1 m) \u03b2 :=\n  sorry\n\ntheorem reader_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03c1 : Type u}\n    {\u03b2 : Type u} (x : label \u03b1 m \u03b2) (i : \u03b1) :\n    goto (reader_t.mk_label \u03c1 x) i = monad_lift (goto x i) :=\n  monad_cont.label.cases_on x\n    fun (x : \u03b1 \u2192 m \u03b2) => Eq.refl (goto (reader_t.mk_label \u03c1 (monad_cont.label.mk x)) i)\n\ndef reader_t.call_cc {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] {\u03b1 : Type u}\n    {\u03b2 : Type u} (f : label \u03b1 (reader_t \u03b5 m) \u03b2 \u2192 reader_t \u03b5 m \u03b1) : reader_t \u03b5 m \u03b1 :=\n  reader_t.mk\n    fun (r : \u03b5) =>\n      monad_cont.call_cc fun (f' : label \u03b1 m \u03b2) => reader_t.run (f (reader_t.mk_label \u03b5 f')) r\n\nprotected instance reader_t.monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c1 : Type u} [monad_cont m] :\n    monad_cont (reader_t \u03c1 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => reader_t.call_cc\n\nprotected instance reader_t.is_lawful_monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c1 : Type u}\n    [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t \u03c1 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081} {\u03b1\u2081 : Type u\u2080} {r\u2081 : Type u\u2080}\n    {\u03b1\u2082 : Type u\u2081} {r\u2082 : Type u\u2081} (F : m\u2081 r\u2081 \u2243 m\u2082 r\u2082) (G : \u03b1\u2081 \u2243 \u03b1\u2082) :\n    cont_t r\u2081 m\u2081 \u03b1\u2081 \u2243 cont_t r\u2082 m\u2082 \u03b1\u2082 :=\n  equiv.mk\n    (fun (f : cont_t r\u2081 m\u2081 \u03b1\u2081) (r : \u03b1\u2082 \u2192 m\u2082 r\u2082) =>\n      coe_fn F (f fun (x : \u03b1\u2081) => coe_fn (equiv.symm F) (r (coe_fn G x))))\n    (fun (f : cont_t r\u2082 m\u2082 \u03b1\u2082) (r : \u03b1\u2081 \u2192 m\u2081 r\u2081) =>\n      coe_fn (equiv.symm F) (f fun (x : \u03b1\u2082) => 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 \u2192 P (e \u226b f)` and `P f \u2192 P (f \u226b e)`, where\n  `e` is an isomorphism.\n* `stable_under_composition`: `P` is stable under composition if `P f \u2192 P g \u2192 P (f \u226b 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 := \u2200 \u2983X Y : C\u2984 (f : X \u27f6 Y), Prop\n\ninstance : inhabited (morphism_property C) := \u27e8\u22a4\u27e9\n\nvariable {C}\n\nnamespace morphism_property\n\ninstance : has_subset (morphism_property C) :=\n\u27e8\u03bb P\u2081 P\u2082, \u2200 \u2983X Y : C\u2984 (f : X \u27f6 Y) (hf : P\u2081 f), P\u2082 f\u27e9\ninstance : has_inter (morphism_property C) :=\n\u27e8\u03bb P\u2081 P\u2082 X Y f, P\u2081 f \u2227 P\u2082 f\u27e9\n\n/-- The morphism property in `C\u1d52\u1d56` associated to a morphism property in `C` -/\n@[simp] def op (P : morphism_property C) : morphism_property C\u1d52\u1d56 := \u03bb X Y f, P f.unop\n\n/-- The morphism property in `C` associated to a morphism property in `C\u1d52\u1d56` -/\n@[simp] def unop (P : morphism_property C\u1d52\u1d56) : morphism_property C := \u03bb 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\u1d52\u1d56) : P.unop.op = P := rfl\n\n/-- The inverse image of a `morphism_property D` by a functor `C \u2964 D` -/\ndef inverse_image (P : morphism_property D) (F : C \u2964 D) : morphism_property C :=\n\u03bb 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  (\u2200 {X Y Z} (e : X \u2245 Y) (f : Y \u27f6 Z), P f \u2192 P (e.hom \u226b f)) \u2227\n  (\u2200 {X Y Z} (e : Y \u2245 Z) (f : X \u27f6 Y), P f \u2192 P (f \u226b e.hom))\n\nlemma respects_iso.op {P : morphism_property C} (h : respects_iso P) : respects_iso P.op :=\n\u27e8\u03bb X Y Z e f hf, h.2 e.unop f.unop hf, \u03bb X Y Z e f hf, h.1 e.unop f.unop hf\u27e9\n\nlemma respects_iso.unop {P : morphism_property C\u1d52\u1d56} (h : respects_iso P) : respects_iso P.unop :=\n\u27e8\u03bb X Y Z e f hf, h.2 e.op f.op hf, \u03bb X Y Z e f hf, h.1 e.op f.op hf\u27e9\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  \u2200 \u2983X Y Z\u2984 (f : X \u27f6 Y) (g : Y \u27f6 Z), P f \u2192 P g \u2192 P (f \u226b g)\n\nlemma stable_under_composition.op {P : morphism_property C} (h : stable_under_composition P) :\n  stable_under_composition P.op := \u03bb X Y Z f g hf hg, h g.unop f.unop hg hf\n\nlemma stable_under_composition.unop {P : morphism_property C\u1d52\u1d56} (h : stable_under_composition P) :\n  stable_under_composition P.unop := \u03bb 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\u2200 \u2983X Y\u2984 (e : X \u2245 Y), P e.hom \u2192 P e.inv\n\nlemma stable_under_inverse.op {P : morphism_property C} (h : stable_under_inverse P) :\n  stable_under_inverse P.op := \u03bb X Y e he, h e.unop he\n\nlemma stable_under_inverse.unop {P : morphism_property C\u1d52\u1d56} (h : stable_under_inverse P) :\n  stable_under_inverse P.unop := \u03bb 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\u2200 \u2983X Y Y' S : C\u2984 \u2983f : X \u27f6 S\u2984 \u2983g : Y \u27f6 S\u2984 \u2983f' : Y' \u27f6 Y\u2984 \u2983g' : Y' \u27f6 X\u2984\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\u2200 \u2983A A' B B' : C\u2984 \u2983f : A \u27f6 A'\u2984 \u2983g : A \u27f6 B\u2984 \u2983f' : B \u27f6 B'\u2984 \u2983g' : A' \u27f6 B'\u2984\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' : \u2200 {X Y} (e : X \u2245 Y), P e.hom) : respects_iso P :=\n\u27e8\u03bb X Y Z e f hf, hP _ _ (hP' e) hf, \u03bb X Y Z e f hf, hP _ _ hf (hP' e)\u27e9\n\nlemma respects_iso.cancel_left_is_iso {P : morphism_property C}\n  (hP : respects_iso P) {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) [is_iso f] :\n    P (f \u226b g) \u2194 P g :=\n\u27e8\u03bb h, by simpa using hP.1 (as_iso f).symm (f \u226b g) h, hP.1 (as_iso f) g\u27e9\n\nlemma respects_iso.cancel_right_is_iso {P : morphism_property C}\n  (hP : respects_iso P) {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) [is_iso g] :\n    P (f \u226b g) \u2194 P f :=\n\u27e8\u03bb h, by simpa using hP.2 (as_iso g).symm (f \u226b g) h, hP.2 (as_iso g) f\u27e9\n\nlemma respects_iso.arrow_iso_iff {P : morphism_property C}\n  (hP : respects_iso P) {f g : arrow C} (e : f \u2245 g) : P f.hom \u2194 P g.hom :=\nby { rw [\u2190 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 \u27f6 X} {g : Y \u27f6 Z} (e : arrow.mk f \u2245 arrow.mk g) :\n    P f \u2194 P g :=\nhP.arrow_iso_iff e\n\nlemma respects_iso.of_respects_arrow_iso (P : morphism_property C)\n  (hP : \u2200 (f g : arrow C) (e : f \u2245 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 \u226b 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 \u226b 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\u2081 : respects_iso P)\n  (hP\u2082 : \u2200 (X Y S : C) (f : X \u27f6 S) (g : Y \u27f6 S) (hg : P g), P (pullback.fst : pullback f g \u27f6 X)) :\n  stable_under_base_change P := \u03bb X Y Y' S f g f' g' sq hg,\nbegin\n  let e := sq.flip.iso_pullback,\n  rw [\u2190 hP\u2081.cancel_left_is_iso e.inv, sq.flip.iso_pullback_inv_fst],\n  exact hP\u2082 _ _ _ 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 \u27f6 S) (g : Y \u27f6 S) [has_pullback f g]\n  (H : P g) : P (pullback.fst : pullback f g \u27f6 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 \u27f6 S) (g : Y \u27f6 S) [has_pullback f g]\n  (H : P f) : P (pullback.snd : pullback f g \u27f6 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' \u27f6 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' \u27f6 S)\n  {X Y : over S} (g : X \u27f6 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 \u226a\u226b\n    pullback.congr_hom (g.w.trans (category.comp_id _)) rfl,\n  have : e.inv \u226b pullback.snd = ((base_change f).map g).left,\n  { apply pullback.hom_ext; dsimp; simp },\n  rw [\u2190 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 \u27f6 S} {g : Y \u27f6 S} {f' : X' \u27f6 S} {g' : Y' \u27f6 S} {i\u2081 : X \u27f6 X'} {i\u2082 : Y \u27f6 Y'}\n  (h\u2081 : P i\u2081) (h\u2082 : P i\u2082) (e\u2081 : f = i\u2081 \u226b f') (e\u2082 : g = i\u2082 \u226b g') :\n    P (pullback.map f g f' g' i\u2081 i\u2082 (\ud835\udfd9 _)\n      ((category.comp_id _).trans e\u2081) ((category.comp_id _).trans e\u2082)) :=\nbegin\n  have : pullback.map f g f' g' i\u2081 i\u2082 (\ud835\udfd9 _)\n    ((category.comp_id _).trans e\u2081) ((category.comp_id _).trans e\u2082) =\n      ((pullback_symmetry _ _).hom \u226b\n      ((base_change _).map (over.hom_mk _ e\u2082.symm : over.mk g \u27f6 over.mk g')).left) \u226b\n      (pullback_symmetry _ _).hom \u226b\n      ((base_change g').map (over.hom_mk _ e\u2081.symm : over.mk f \u27f6 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\u2082.symm : over.mk g \u27f6 over.mk g') h\u2082,\n    hP.base_change_map _ (over.hom_mk _ e\u2081.symm : over.mk f \u27f6 over.mk f') h\u2081],\nend\n\nlemma stable_under_cobase_change.mk {P : morphism_property C} [has_pushouts C]\n  (hP\u2081 : respects_iso P)\n  (hP\u2082 : \u2200 (A B A' : C) (f : A \u27f6 A') (g : A \u27f6 B) (hf : P f), P (pushout.inr : B \u27f6 pushout f g)) :\n  stable_under_cobase_change P := \u03bb A A' B B' f g f' g' sq hf,\nbegin\n  let e := sq.flip.iso_pushout,\n  rw [\u2190 hP\u2081.cancel_right_is_iso _ e.hom, sq.flip.inr_iso_pushout_hom],\n  exact hP\u2082 _ _ _ 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 _ (\u03bb 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 \u27f6 A') (g : A \u27f6 B) [has_pushout f g]\n  (H : P g) : P (pushout.inl : A' \u27f6 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 \u27f6 A') (g : A \u27f6 B) [has_pushout f g]\n  (H : P f) : P (pushout.inr : B \u27f6 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\u03bb 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\u1d52\u1d56}\n  (hP : stable_under_cobase_change P) : stable_under_base_change P.unop :=\n\u03bb 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\u03bb 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\u1d52\u1d56}\n  (hP : stable_under_base_change P) : stable_under_cobase_change P.unop :=\n\u03bb A A' B B' f g f' g' sq hf, hP sq.op hf\n\n/-- If `P : morphism_property C` and `F : C \u2964 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 \u2964 D) : Prop :=\n\u2200 \u2983X Y : C\u2984 (f : X \u27f6 Y) (hf : P f), is_iso (F.map f)\n\nnamespace is_inverted_by\n\nlemma of_comp {C\u2081 C\u2082 C\u2083 : Type*} [category C\u2081] [category C\u2082] [category C\u2083]\n  (W : morphism_property C\u2081) (F : C\u2081 \u2964 C\u2082) (hF : W.is_inverted_by F) (G : C\u2082 \u2964 C\u2083) :\n  W.is_inverted_by (F \u22d9 G) :=\n\u03bb X Y f hf, by { haveI := hF f hf, dsimp, apply_instance, }\n\nlemma op {W : morphism_property C} {L : C \u2964 D} (h : W.is_inverted_by L) :\n  W.op.is_inverted_by L.op :=\n\u03bb X Y f hf, by { haveI := h f.unop hf, dsimp, apply_instance, }\n\nlemma right_op {W : morphism_property C} {L : C\u1d52\u1d56 \u2964 D} (h : W.op.is_inverted_by L) :\n  W.is_inverted_by L.right_op :=\n\u03bb X Y f hf, by { haveI := h f.op hf, dsimp, apply_instance, }\n\nlemma left_op {W : morphism_property C} {L : C \u2964 D\u1d52\u1d56} (h : W.is_inverted_by L) :\n  W.op.is_inverted_by L.left_op :=\n\u03bb X Y f hf, by { haveI := h f.unop hf, dsimp, apply_instance, }\n\nlemma unop {W : morphism_property C} {L : C\u1d52\u1d56 \u2964 D\u1d52\u1d56} (h : W.op.is_inverted_by L) :\n  W.is_inverted_by L.unop :=\n\u03bb X Y f hf, by { haveI := h f.op hf, dsimp, apply_instance, }\n\nend is_inverted_by\n\n/-- Given `app : \u03a0 X, F\u2081.obj X \u27f6 F\u2082.obj X` where `F\u2081` and `F\u2082` 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\u2081 F\u2082 : C \u2964 D} (app : \u03a0 X, F\u2081.obj X \u27f6 F\u2082.obj X) :\n  morphism_property C := \u03bb X Y f, F\u2081.map f \u226b app Y = app X \u226b F\u2082.map f\n\nnamespace naturality_property\n\nlemma is_stable_under_composition {F\u2081 F\u2082 : C \u2964 D} (app : \u03a0 X, F\u2081.obj X \u27f6 F\u2082.obj X) :\n  (naturality_property app).stable_under_composition := \u03bb X Y Z f g hf hg,\nbegin\n  simp only [naturality_property] at \u22a2 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\u2081 F\u2082 : C \u2964 D} (app : \u03a0 X, F\u2081.obj X \u27f6 F\u2082.obj X) :\n  (naturality_property app).stable_under_inverse := \u03bb X Y e he,\nbegin\n  simp only [naturality_property] at \u22a2 he,\n  rw \u2190 cancel_epi (F\u2081.map e.hom),\n  slice_rhs 1 2 { rw he },\n  simp only [category.assoc, \u2190 F\u2081.map_comp_assoc, \u2190 F\u2082.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 \u2964 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 \u2964 D) : stable_under_composition (P.inverse_image F) :=\n\u03bb X Y Z f g hf hg, by simpa only [\u2190 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 := \u03bb X Y f, is_iso f\n\n/-- The `morphism_property C` satisfied by monomorphisms in `C`. -/\ndef monomorphisms : morphism_property C := \u03bb X Y f, mono f\n\n/-- The `morphism_property C` satisfied by epimorphisms in `C`. -/\ndef epimorphisms : morphism_property C := \u03bb X Y f, epi f\n\nsection\n\nvariables {C} {X Y : C} (f : X \u27f6 Y)\n\n@[simp] lemma isomorphisms.iff : (isomorphisms C) f \u2194 is_iso f := by refl\n@[simp] lemma monomorphisms.iff : (monomorphisms C) f \u2194 mono f := by refl\n@[simp] lemma epimorphisms.iff : (epimorphisms C) f \u2194 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\u03bb X Y Z f g hf hg, begin\n  rw isomorphisms.iff at hf hg \u22a2,\n  haveI := hf,\n  haveI := hg,\n  apply_instance,\nend\n\nlemma stable_under_composition.monomorphisms : stable_under_composition (monomorphisms C) :=\n\u03bb X Y Z f g hf hg, begin\n  rw monomorphisms.iff at hf hg \u22a2,\n  haveI := hf,\n  haveI := hg,\n  apply mono_comp,\nend\n\nlemma stable_under_composition.epimorphisms : stable_under_composition (epimorphisms C) :=\n\u03bb X Y Z f g hf hg, begin\n  rw epimorphisms.iff at hf hg \u22a2,\n  haveI := hf,\n  haveI := hg,\n  apply epi_comp,\nend\n\nvariable {C}\n\n/-- The full subcategory of `C \u2964 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 (\u03bb (F : C \u2964 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 \u2964 D) (hF : W.is_inverted_by F) : W.functors_inverting D := \u27e8F, hF\u27e9\n\nlemma is_inverted_by.iff_of_iso (W : morphism_property C) {F\u2081 F\u2082 : C \u2964 D} (e : F\u2081 \u2245 F\u2082) :\n  W.is_inverted_by F\u2081 \u2194 W.is_inverted_by F\u2082 :=\nbegin\n  suffices : \u2200 (X Y : C) (f : X \u27f6 Y), is_iso (F\u2081.map f) \u2194 is_iso (F\u2082.map f),\n  { split,\n    exact \u03bb h X Y f hf, by { rw \u2190 this, exact h f hf, },\n    exact \u03bb 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 \u27f6 Y`\nwhenever `P` holds for `X \u27f6 Y x\u2093 Y`. -/\ndef diagonal (P : morphism_property C) : morphism_property C :=\n\u03bb X Y f, P (pullback.diagonal f)\n\nlemma diagonal_iff {X Y : C} {f : X \u27f6 Y} : P.diagonal f \u2194 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      \u2190 hP.cancel_right_is_iso _ _, \u2190 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\u2081 h\u2082,\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 \u27f6 Y` iff `P` holds for all `X \u00d7[Y] Y' \u27f6 Y'`. -/\ndef universally (P : morphism_property C) : morphism_property C :=\n\u03bb X Y f, \u2200 \u2983X' Y' : C\u2984 (i\u2081 : X' \u27f6 X) (i\u2082 : Y' \u27f6 Y) (f' : X' \u27f6 Y')\n  (h : is_pullback f' i\u2081 i\u2082 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\u2081 i\u2082 f' H,\n    have : is_pullback (\ud835\udfd9 _) (i\u2081 \u226b e.hom) i\u2081 e.inv := is_pullback.of_horiz_is_iso\n      \u27e8by rw [category.id_comp, category.assoc, e.hom_inv_id, category.comp_id]\u27e9,\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\u2081 i\u2082 f' H,\n    have : is_pullback (\ud835\udfd9 _) i\u2082 (i\u2082 \u226b e.inv) e.inv :=\n      is_pullback.of_horiz_is_iso \u27e8category.id_comp _\u27e9,\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\u03bb X Y Y' S f g f' g' H h\u2081 Y'' X'' i\u2081 i\u2082 f'' H', h\u2081 _ _ _ (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\u2081 i\u2082 f' H,\n  have := pullback.lift_fst _ _ (H.w.trans (category.assoc _ _ _).symm),\n  rw \u2190 this at H \u22a2,\n  apply hP _ _ _ (hg _ _ _ $ is_pullback.of_has_pullback _ _),\n  exact hf _ _ _ (H.of_right (pullback.lift_snd _ _ _) (is_pullback.of_has_pullback i\u2082 g))\nend\n\nlemma universally_le (P : morphism_property C) :\n  P.universally \u2264 P :=\nbegin\n  intros X Y f hf,\n  exact hf (\ud835\udfd9 _) (\ud835\udfd9 _) _ (is_pullback.of_vert_is_iso \u27e8by rw [category.comp_id, category.id_comp]\u27e9)\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 $ \u03bb X Y f hf X' Y' i\u2081 i\u2082 f' H, hP H.flip hf\n\nlemma universally_mono : monotone (universally : morphism_property C \u2192 morphism_property C) :=\n\u03bb P\u2081 P\u2082 h X Y f h\u2081 X' Y' i\u2081 i\u2082 f' H, h _ _ _ (h\u2081 _ _ _ 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 := \u03bb X Y f, injective f\n\n/-- Surjectiveness (in a concrete category) as a `morphism_property` -/\nprotected def surjective : morphism_property C := \u03bb X Y f, surjective f\n\n/-- Bijectiveness (in a concrete category) as a `morphism_property` -/\nprotected def bijective : morphism_property C := \u03bb X Y f, bijective f\n\nlemma bijective_eq_sup : morphism_property.bijective C =\n  morphism_property.injective C \u2293 morphism_property.surjective C :=\nrfl\n\nlemma injective_stable_under_composition :\n  (morphism_property.injective C).stable_under_composition :=\n\u03bb 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\u03bb 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\u03bb 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  (\u03bb 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  (\u03bb 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  (\u03bb 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) 2019 Rob Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Rob Lewis\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.simp_result\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\nnamespace tactic\n\n\n/--\n`delta_instance ids` tries to solve the goal by calling `apply_instance`,\nfirst unfolding the definitions in `ids`.\n-/\n-- We call `dsimp_result` here because otherwise\n\n-- `delta_target` will insert an `id` in the result.\n\n-- See the note [locally reducible category instances]\n\n-- https://github.com/leanprover-community/mathlib/blob/c9fca15420e2ad443707ace831679fd1762580fe/src/algebra/category/Mon/basic.lean#L27\n\n-- for an example where this used to cause a problem.\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/delta_instance.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.06853748589730285, "lm_q1q2_score": 0.02948121783746442}}
{"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 data.nat.basic\nimport data.set.image\nimport tactic.simp_rw\n\n/-!\n# Tests for `simp_rw` extensions\n-/\n\n-- `simp_rw` can perform rewrites under binders:\nexample : (\u03bb (x y : \u2115), x + y) = (\u03bb x y, y + x) := by simp_rw [add_comm]\n\n-- `simp_rw` can apply reverse rules:\nexample (f : \u2115 \u2192 \u2115) {a b c : \u2115} (ha : f b = a) (hc : f b = c) : a = c := by simp_rw [\u2190 ha, hc]\n\n-- `simp_rw` performs rewrites in the given order (`simp` fails on this example):\nexample {\u03b1 \u03b2 : Type} {f : \u03b1 \u2192 \u03b2} {t : set \u03b2} :\n  (\u2200 s, f '' s \u2286 t) = \u2200 s : set \u03b1, \u2200 x \u2208 s, x \u2208 f \u207b\u00b9' t :=\nby simp_rw [set.image_subset_iff, set.subset_def]\n\n-- `simp_rw` applies rewrite rules multiple times:\nexample (a b c d : \u2115) : a + (b + (c + d)) = ((d + c) + b) + a := by simp_rw [add_comm]\n\n-- `simp_rw` can also rewrite in assumptions:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h : p (a + b)) : p (b + a) :=\nby {simp_rw [add_comm a b] at h, exact h}\n-- or explicitly rewrite at the goal:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h : p (a + b)) : p (b + a) :=\nby {simp_rw [add_comm b a] at \u22a2, exact h}\n-- or at multiple assumptions:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h\u2081 : p (b + a) \u2192 p (a + b))  (h\u2082 : p (a + b)) : p (b + a) :=\nby {simp_rw [add_comm a b] at h\u2081 h\u2082, exact h\u2081 h\u2082}\n-- or everywhere:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h\u2081 : p (b + a) \u2192 p (a + b))  (h\u2082 : p (a + b)) : p (a + b) :=\nby {simp_rw [add_comm a b] at *, exact h\u2081 h\u2082}\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/simp_rw.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.0627892042126289, "lm_q1q2_score": 0.02943499038820149}}
{"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 \u2192 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 \u2192 B)\n(map_op' : \u2200 {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 (\u03bb _, B) :=\n{ coe := MyHom.toFun, coe_injective' := \u03bb 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) (\u03bb _, A \u2192 B) := \u27e8MyHom.toFun\u27e9\n\n@[ext] theorem ext {f g : MyHom A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : MyHom A B :=\n{ toFun := f',\n  map_op' := h.symm \u25b8 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 (\u03bb _, B) :=\n(map_op : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u2192 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 \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to functions from `\u03b1` to `\u03b2`.\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 _) (\u03b1 : outParam (Sort _)) (\u03b2 : outParam <| \u03b1 \u2192 Sort _) where\n  /-- The coercion from `F` to a function. -/\n  coe : F \u2192 \u2200 a : \u03b1, \u03b2 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 \u03b1 \u03b2` where `\u03b2` depends on `a : \u03b1` -/\n\nvariable (F \u03b1 : Sort _) (\u03b2 : \u03b1 \u2192 Sort _)\n\nnamespace FunLike\n\nvariable {F \u03b1 \u03b2} [i : FunLike F \u03b1 \u03b2]\n\ninstance (priority := 100) hasCoeToFun : CoeFun F fun _ \u21a6 \u2200 a : \u03b1, \u03b2 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 => \u2191f) := rfl\n#align fun_like.coe_eq_coe_fn FunLike.coe_eq_coe_fn\n\ntheorem coe_injective : Function.Injective (fun f : F \u21a6 (f : \u2200 a : \u03b1, \u03b2 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 : \u2200 a : \u03b1, \u03b2 a) = (g : \u2200 a : \u03b1, \u03b2 a) \u2194 f = g :=\n  \u27e8fun h \u21a6 FunLike.coe_injective' h, fun h \u21a6 by cases h; rfl\u27e9\n#align fun_like.coe_fn_eq FunLike.coe_fn_eq\n\ntheorem ext' {f g : F} (h : (f : \u2200 a : \u03b1, \u03b2 a) = (g : \u2200 a : \u03b1, \u03b2 a)) : f = g :=\n  FunLike.coe_injective' h\n#align fun_like.ext' FunLike.ext'\n\ntheorem ext'_iff {f g : F} : f = g \u2194 (f : \u2200 a : \u03b1, \u03b2 a) = (g : \u2200 a : \u03b1, \u03b2 a) :=\n  coe_fn_eq.symm\n#align fun_like.ext'_iff FunLike.ext'_iff\n\ntheorem ext (f g : F) (h : \u2200 x : \u03b1, 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 \u2194 \u2200 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\u2081 : f = g) (x : \u03b1) : f x = g x :=\n  congr_fun (congr_arg _ h\u2081) x\n#align fun_like.congr_fun FunLike.congr_fun\n\ntheorem ne_iff {f g : F} : f \u2260 g \u2194 \u2203 a, f a \u2260 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 [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton F :=\n\u27e8fun _ _ \u21a6 coe_injective $ Subsingleton.elim _ _\u27e9\n#align fun_like.subsingleton_cod FunLike.subsingleton_cod\n\nend FunLike\n\nend Dependent\n\nsection NonDependent\n\n/-! ### `FunLike F \u03b1 (\u03bb _, \u03b2)` where `\u03b2` does not depend on `a : \u03b1` -/\n\nvariable {F \u03b1 \u03b2 : Sort _} [i : FunLike F \u03b1 fun _ \u21a6 \u03b2]\n\nnamespace FunLike\n\nprotected theorem congr {f g : F} {x y : \u03b1} (h\u2081 : f = g) (h\u2082 : x = y) : f x = g y :=\n  congr (congr_arg _ h\u2081) h\u2082\n#align fun_like.congr FunLike.congr\n\nprotected theorem congr_arg (f : F) {x y : \u03b1} (h\u2082 : x = y) : f x = f y :=\n  congr_arg _ h\u2082\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 \u03a0-type -- whether it is visible or hidden behind a definition.\n\nFor instance, consider the following proof:\n\n```\nexample {\u03b1 \u03b2} (x y z : \u03b1 \u2192 \u03b2) (h\u2080 : x \u2264 y) (h\u2081 : y \u2264 z) : x \u2264 z :=\nbegin\n  apply le_trans,\nend\n```\n\nBecause `x \u2264 z` is definitionally equal to `\u2200 i, x i \u2264 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 {\u03b1} (gs : List (Bool \u00d7 \u03b1)) : NewGoals \u2192 List \u03b1\n  | new_goals.non_dep_first =>\n    let \u27e8dep, non_dep\u27e9 := gs.partition\u2093 (coe \u2218 Prod.fst)\n    non_dep.map Prod.snd ++ dep.map Prod.snd\n  | new_goals.non_dep_only => (gs.filter\u2093 (coe \u2218 not \u2218 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 \u00d7 expr)) : tactic Bool :=\n  ms.foldlM\n    (fun r m => do\n      let type \u2190 infer_type m.2\n      let b \u2190 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 \u00d7 expr)) : tactic Unit :=\n  whenM (has_opt_auto_param_inst_for_apply ms) do\n    let gs \u2190 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    \u2200 (e : expr) (cfg : ApplyCfg), List (Bool \u00d7 Name \u00d7 expr) \u2192 tactic (List (Name \u00d7 expr))\n  | e, cfg, gs =>\n    (focus1 do\n        let tgt : expr \u2190 target\n        let t \u2190 infer_type e\n        unify t tgt\n        exact e\n        let gs' \u2190 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 \u2190 infer_type e >>= whnf |\n        apply_core e cfg\n      let v \u2190 mk_meta_var d\n      let b := b.has_var\n      let e \u2190 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 \u00d7 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 \u00d7 expr)) := do\n  let r \u2190 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 \u00d7 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 \u00d7 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 \u2192 Name \u2192 Option Name)\n    (tac_name : String) : tactic Unit := do\n  let tgt \u2190 target >>= instantiate_mvars\n  let env \u2190 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 \u2190 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. `\u2264`) so that rules like transitivity on `le : (\u03b1 \u2192 \u03b2) \u2192 (\u03b1 \u2192 \u03b2) \u2192 (\u03b1 \u2192 \u03b2)` will be\nconsidered to have three parameters and two assumptions (i.e. `f g h : \u03b1 \u2192 \u03b2`, `H\u2080 : f \u2264 g`,\n`H\u2081 : g \u2264 h`) instead of three parameters, two assumptions and then one more parameter\n(i.e. `f g h : \u03b1 \u2192 \u03b2`, `H\u2080 : f \u2264 g`, `H\u2081 : g \u2264 h`, `x : \u03b1`). Whereas `apply` would expect the goal\n`f x \u2264 h x`, `apply'` will work with the goal `f \u2264 h`.\n-/\nunsafe def apply' (q : parse texpr) : tactic Unit :=\n  concat_tags do\n    let h \u2190 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 \u2190 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 \u2190 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 \u2192 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) \u2190 target_lhs_rhs\n      let t \u2190 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": "\n\nabbrev DelabM := Id\nabbrev Delab := DelabM Nat\n\nexample : DelabM Nat := pure 1  -- works\nexample : Delab := pure 1       -- works\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/121.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.08151975374329136, "lm_q1q2_score": 0.029295277736256335}}
{"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 \u2192 bool \u2192 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 `\u2200 x, myand ff x = ff` and `\u2200 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 : \u2200 x, myand ff x = ff :=\n  begin\n    intros, refl\n  end\n  ```\n\n  However, you can use `unfold_cases { refl }` to prove `\u2200 x, myand ff x = ff` and\n  `\u2200 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  \u03bb (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 `\u2200 x, myand ff x = ff`, it starts by `intros`,\n  followed by unfolding the definition:\n  ```lean\n  \u22a2 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  \u22a2 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  \u22a2 bool.rec (id_rhs bool ff) (id_rhs bool ff) ff = ff\n  \u22a2 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 \u2192 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 \u2190 target,\n  e \u2190 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 `\u22a2 f x\u2081 ... x\u2099 = y`, unfolds `f` using a delta reduction.\n-/\nmeta def unfold_tgt : expr \u2192 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 : \u2115 \u2192 \u2115 \u2192 \u2115\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 : \u2200 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 \u2190 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) 2020 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\nimport Lean.Meta.Tactic.Simp.Main\nimport Std.Tactic.Lint.Basic\nimport Std.Tactic.OpenPrivate\nimport Std.Util.LibraryNote\nopen Lean Meta\n\nnamespace Std.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\n/-- The data associated to a simp theorem. -/\nstructure SimpTheoremInfo where\n  /-- The hypotheses of the theorem -/\n  hyps : Array Expr\n  /-- True if this is a conditional rewrite rule -/\n  isConditional : Bool\n  /-- The thing to replace -/\n  lhs : Expr\n  /-- The result of replacement -/\n  rhs : Expr\n\n/-- Given the list of hypotheses, is this a conditional rewrite rule? -/\ndef isConditionalHyps (lhs : Expr) : List Expr \u2192 MetaM Bool\n  | [] => pure false\n  | h :: hs => do\n    let ldecl \u2190 getFVarLocalDecl h\n    if !ldecl.binderInfo.isInstImplicit\n        && !(\u2190 hs.anyM fun h' =>\n          return (\u2190 inferType h').consumeTypeAnnotations.containsFVar h.fvarId!)\n        && !lhs.containsFVar h.fvarId! then\n      return true\n    isConditionalHyps lhs hs\n\nopen private preprocess from Lean.Meta.Tactic.Simp.SimpTheorems in\n/-- Runs the continuation on all the simp theorems encoded in the given type. -/\ndef withSimpTheoremInfos (ty : Expr) (k : SimpTheoremInfo \u2192 MetaM \u03b1) : MetaM (Array \u03b1) :=\n  withReducible do\n    let e \u2190 preprocess (\u2190 mkSorry ty true) ty (inv := false) (isGlobal := true)\n    e.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        let isConditional \u2190 isConditionalHyps lhs hyps.toList\n        k { hyps, lhs, rhs, isConditional }\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 \u2190 if whnfFirst then whnf a else pure a\n  let b \u2190 if whnfFirst then whnf b else pure b\n  if a.getAppFn.constName? != b.getAppFn.constName? then return false\n  isDefEq a b\n\n/-- Constructs a message from all the simp theorems encoded in the given type. -/\ndef checkAllSimpTheoremInfos (ty : Expr) (k : SimpTheoremInfo \u2192 MetaM (Option MessageData)) :\n    MetaM (Option MessageData) := do\n  let errors :=\n    (\u2190 withSimpTheoremInfos ty fun i => do (\u2190 k i).mapM addMessageContextFull).filterMap id\n  if errors.isEmpty then\n    return none\n  return MessageData.joinSep errors.toList Format.line\n\n/-- Returns true if this is a `@[simp]` declaration. -/\ndef isSimpTheorem (declName : Name) : MetaM Bool := do\n  pure $ (\u2190 getSimpTheorems).lemmaNames.contains (.decl declName)\n\nopen Lean.Meta.DiscrTree in\n/-- Returns the list of elements in the discrimination tree. -/\npartial def _root_.Lean.Meta.DiscrTree.elements (d : DiscrTree \u03b1 s) : Array \u03b1 :=\n  d.root.foldl (init := #[]) fun arr _ => trieElements arr\nwhere\n  /-- Returns the list of elements in the trie. -/\n  trieElements (arr)\n  | Trie.node vs children =>\n    children.foldl (init := arr ++ vs) fun arr (_, child) => trieElements arr child\n\nopen Std\n\n/-- Add message `msg` to any errors thrown inside `k`. -/\ndef decorateError (msg : MessageData) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  try k catch e => throw (.error e.getRef m!\"{msg}\\n{e.toMessageData}\")\n\n/-- Render the list of simp lemmas. -/\ndef formatLemmas (usedSimps : Simp.UsedSimps) : MetaM MessageData := do\n  let mut args := #[]\n  let env \u2190 getEnv\n  for (thm, _) in usedSimps.toArray.qsort (\u00b7.2 < \u00b7.2) do\n    if let .decl declName := thm then\n      if env.contains declName && declName != ``eq_self then\n        args := args.push (\u2190 mkConstWithFreshMVarLevels declName)\n  return m!\"simp only {args.toList}\"\n\n/-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/\n@[std_linter] 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  test := fun declName => do\n    unless \u2190 isSimpTheorem declName do return none\n    let ctx := { \u2190 Simp.Context.mkDefault with config.decide := false }\n    checkAllSimpTheoremInfos (\u2190 getConstInfo declName).type fun {lhs, rhs, isConditional, ..} => do\n      let (\u27e8lhs', prf1, _\u27e9, prf1Lems) \u2190\n        decorateError \"simplify fails on left-hand side:\" <| simp lhs ctx\n      if prf1Lems.contains (.decl declName) then return none\n      let (\u27e8rhs', _, _\u27e9, used_lemmas) \u2190\n        decorateError \"simplify fails on right-hand side:\" <| simp rhs ctx (usedSimps := prf1Lems)\n      let lhs'EqRhs' \u2190 isSimpEq lhs' rhs' (whnfFirst := false)\n      let lhsInNF \u2190 isSimpEq lhs' lhs\n      if lhs'EqRhs' then\n        if prf1.isNone then return none -- TODO: FP rewriting foo.eq_2 using `simp only [foo]`\n        return m!\"simp can prove this:\n  by {\u2190 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 \u00ac lhsInNF then\n        return m!\"Left-hand side simplifies from\n  {lhs}\nto\n  {lhs'}\nusing\n  {\u2190 formatLemmas prf1Lems}\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, when using the simp lemma on itself.\nThis usually means that it will never apply.\n\"\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@[std_linter] 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 (after whnfR):\"\n  test := fun declName => do\n    unless \u2190 isSimpTheorem declName do return none\n    checkAllSimpTheoremInfos (\u2190 getConstInfo declName).type fun {lhs, ..} => do\n    let lhs \u2190 whnfR lhs\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\nprivate def Expr.eqOrIff? : Expr \u2192 Option (Expr \u00d7 Expr)\n  | .app (.app (.app (.const ``Eq _) _) lhs) rhs\n  | .app (.app (.const ``Iff _) lhs) rhs\n    => (lhs, rhs)\n  | _ => none\n\n/-- A linter for commutativity lemmas that are marked simp. -/\n@[std_linter] 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 \u2190 isSimpTheorem declName do return none\n    let ty := (\u2190 getConstInfo declName).type\n    forallTelescopeReducing ty fun _ ty' => do\n    let some (lhs, rhs) := ty'.eqOrIff? | return none\n    unless lhs.getAppFn.constName? == rhs.getAppFn.constName? do return none\n    let (_, _, ty') \u2190 forallMetaTelescopeReducing ty\n    let some (lhs', rhs') := ty'.eqOrIff? | return none\n    unless \u2190 isDefEq rhs lhs' do return none\n    unless \u2190 withNewMCtxDepth (isDefEq rhs lhs') do return none\n    -- make sure that the discrimination tree will actually find this match (see #69)\n    if (\u2190 (\u2190 DiscrTree.empty.insert (s := true) rhs ()).getMatch lhs').isEmpty then return none\n    -- ensure that the second application makes progress:\n    if \u2190 isDefEq lhs' rhs' then return none\n    pure m!\"should not be marked 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/Tactic/Lint/Simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.06187598788607498, "lm_q1q2_score": 0.02924775707331371}}
{"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 \u03b1` data structure is\nthe most generic version we define.\nIt is created using `Cache.mk f`\nwhere `f : MetaM \u03b1` performs\nthe initialization of the cache:\n```\ninitialize numberOfImports : Cache Nat \u2190 Cache.mk do\n  (\u2190 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 \u03b1` data structure computes\na fold over the environment's constants:\n`DeclCache.mk empty f` constructs such a cache\nwhere `empty : \u03b1` and `f : Name \u2192 ConstantInfo \u2192 \u03b1 \u2192 MetaM \u03b1`.\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 (\u03b1 : Type) :=\n  IO.Ref <| Sum (MetaM \u03b1) <|\n    Task <| Except Exception \u03b1\n\ninstance : Nonempty (Cache \u03b1) :=\n  inferInstanceAs <| Nonempty (IO.Ref _)\n\n/-- Creates a cache with an initialization function. -/\ndef Cache.mk (init : MetaM \u03b1) : IO (Cache \u03b1) :=\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 \u03b1) : m \u03b1 := do\n  let t \u2190 match \u2190 show BaseIO _ from ST.Ref.get cache with\n    | Sum.inr t => pure t\n    | Sum.inl init =>\n      let env \u2190 getEnv\n      let fileName \u2190 getFileName\n      let fileMap \u2190 getFileMap\n      let options \u2190 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 \u2190 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 (\u2190 ((init \u2039_\u203a).run \u2039_\u203a \u2039_\u203a).run \u2039_\u203a).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 `\u03b1` for every constant.\n-/\ndef DeclCache (\u03b1 : Type) :=\n  Cache \u03b1 \u00d7 (Name \u2192 ConstantInfo \u2192 \u03b1 \u2192 MetaM \u03b1)\n\ninstance : Nonempty (DeclCache \u03b1) :=\n  inferInstanceAs <| Nonempty (_ \u00d7 _)\n\n/--\nCreates a `DeclCache`.\nThe cached structure `\u03b1` 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 : \u03b1)\n    (addDecl : Name \u2192 ConstantInfo \u2192 \u03b1 \u2192 MetaM \u03b1) : IO (DeclCache \u03b1) := do\n  let cache \u2190 Cache.mk do\n    profileitM Exception profilingName (\u2190 getOptions) do\n    let mut a := empty\n    for (n, c) in (\u2190 getEnv).constants.map\u2081.toList do\n      a \u2190 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 \u03b1) : MetaM \u03b1 := do\n  let mut a \u2190 cache.1.get\n  for (n, c) in (\u2190 getEnv).constants.map\u2082.toList do\n    a \u2190 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\u207b\u00b9 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 \u2964 D} {\u03b1 : F \u27f6 G} {\u03b2 : G \u27f6 H} :\n  nat_trans.op (\u03b1 \u226b \u03b2) = nat_trans.op \u03b2 \u226b nat_trans.op \u03b1 := 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 : \u211d\u22650) (V : SemiNormedGroup) (r' : \u211d\u22650)\nvariables (c c\u2081 c\u2082 c\u2083 c\u2084 : \u211d\u22650) (l m n : \u2115)\n\n/-- `LC V n` is the functor that sends a profinite set `S` to `V(S)` -/\ndef LC (V : SemiNormedGroup) : Profinite\u1d52\u1d56 \u2964 SemiNormedGroup :=\nLocallyConstant.obj V\n\nnamespace LC\n\nlemma map_norm_noninc {M\u2081 M\u2082} (f : M\u2081 \u27f6 M\u2082) : ((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\u1d52\u1d56) :\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 \u2245 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  \u2225(LC.T r V).hom.app A\u2225 \u2264 r :=\nbegin\n  rw T_eq,\n  refine normed_add_group_hom.op_norm_le_bound _ (nnreal.zero_le_coe) (\u03bb 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 \u27f6 LC V :=\n(LocallyConstant.map (normed_with_aut.T.inv : V \u27f6 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  \u2225(T_inv r V).app A\u2225 \u2264 r\u207b\u00b9 :=\nbegin\n  rw T_inv_eq',\n  refine normed_add_group_hom.op_norm_le_bound _ (inv_nonneg.2 (nnreal.zero_le_coe)) (\u03bb 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' : \u211d\u22650) (c : \u211d\u22650) (n : \u2115) :\n  (ProFiltPseuNormGrpWithTinv r')\u1d52\u1d56 \u2964 SemiNormedGroup :=\n(FiltrationPow r' c n).op \u22d9 LC V\n\ntheorem LCFP_def (V : SemiNormedGroup) (r' : \u211d\u22650) (c : \u211d\u22650) (n : \u2115) :\n  LCFP V r' c n = (FiltrationPow r' c n).op \u22d9 LocallyConstant.obj V := rfl\n\nnamespace LCFP\n\nlemma map_norm_noninc {M\u2081 M\u2082} (f : M\u2081 \u27f6 M\u2082) : ((LCFP V r' c n).map f).norm_noninc :=\nLC.map_norm_noninc _ _\n\n@[simps {fully_applied := ff}]\ndef res (r' : \u211d\u22650) (c\u2081 c\u2082 : \u211d\u22650) [fact (c\u2082 \u2264 c\u2081)] (n : \u2115) : LCFP V r' c\u2081 n \u27f6 LCFP V r' c\u2082 n :=\n(whisker_right (nat_trans.op (FiltrationPow.cast_le r' c\u2082 c\u2081 n)) (LocallyConstant.obj V) : _)\n\n@[simp] lemma res_refl : res V r' c c n = \ud835\udfd9 _ :=\nby { simp [res, FiltrationPow.cast_le_refl], refl }\n\nlemma res_comp_res [h\u2081 : fact (c\u2083 \u2264 c\u2082)] [h\u2082 : fact (c\u2082 \u2264 c\u2081)] :\n  res V r' c\u2081 c\u2082 n \u226b res V r' c\u2082 c\u2083 n = @res V r' c\u2081 c\u2083 \u27e8le_trans h\u2081.1 h\u2082.1\u27e9 n :=\nby simp only [res, \u2190 whisker_right_comp, \u2190 nat_trans.op_comp, FiltrationPow.cast_le_comp]\n\nlemma res_norm_noninc [fact (c\u2082 \u2264 c\u2081)] (M) : ((res V r' c\u2081 c\u2082 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\u2082 \u2264 r' * c\u2081)] : LCFP V r' c\u2081 n \u27f6 LCFP V r' c\u2082 n :=\n(whisker_right (nat_trans.op $ FiltrationPow.Tinv r' c\u2082 c\u2081 n) (LocallyConstant.obj V) : _)\n\nlemma Tinv_def [fact (c\u2082 \u2264 r' * c\u2081)] : Tinv V r' c\u2081 c\u2082 n =\n  whisker_right (nat_trans.op $ FiltrationPow.Tinv r' c\u2082 c\u2081 n) (LC V) := rfl\n\nlemma res_comp_Tinv\n  [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2083 \u2264 c\u2082)] [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2083 \u2264 r' * c\u2082)] :\n  res V r' c\u2081 c\u2082 n \u226b Tinv V r' c\u2082 c\u2083 n = Tinv V r' c\u2081 c\u2082 n \u226b res V r' c\u2082 c\u2083 n :=\nbegin\n  simp only [Tinv, res, \u2190 whisker_right_comp, \u2190 nat_trans.op_comp],\n  refl\nend\n\nlemma Tinv_norm_noninc [fact (c\u2082 \u2264 r' * c\u2081)] (M) : ((Tinv V r' c\u2081 c\u2082 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 \u2245 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 \u27f6 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 \u27f6 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 (\u03d5 : basic_universal_map m n)\n\ndef eval_LCFP (c\u2081 c\u2082 : \u211d\u22650) [\u03d5.suitable c\u2082 c\u2081] : LCFP V r' c\u2081 n \u27f6 LCFP V r' c\u2082 m :=\n(whisker_right (nat_trans.op $ \u03d5.eval_FP r' c\u2082 c\u2081) (LocallyConstant.obj V) : _)\n\ndef eval_LCFP' (c\u2081 c\u2082 : \u211d\u22650) : LCFP V r' c\u2081 n \u27f6 LCFP V r' c\u2082 m :=\nif H : \u03d5.suitable c\u2082 c\u2081\nthen by exactI (whisker_right (nat_trans.op $ \u03d5.eval_FP r' c\u2082 c\u2081) (LocallyConstant.obj V) : _)\nelse 0\n\nlemma eval_LCFP_eq_eval_LCFP' (h : \u03d5.suitable c\u2082 c\u2081) :\n  \u03d5.eval_LCFP V r' c\u2081 c\u2082 = \u03d5.eval_LCFP' V r' c\u2081 c\u2082 :=\nby { delta eval_LCFP eval_LCFP', rw dif_pos h }\n\nlemma eval_LCFP'_def [h : \u03d5.suitable c\u2082 c\u2081] :\n  \u03d5.eval_LCFP' V r' c\u2081 c\u2082 =\n    (whisker_right (nat_trans.op $ \u03d5.eval_FP r' c\u2082 c\u2081) (LocallyConstant.obj V) : _) :=\ndif_pos h\n\nlemma eval_LCFP'_not_suitable (h : \u00ac \u03d5.suitable c\u2082 c\u2081) :\n  \u03d5.eval_LCFP' V r' c\u2081 c\u2082 = 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\u2082 c\u2081] [hg : g.suitable c\u2083 c\u2082] :\n  (basic_universal_map.comp f g).eval_LCFP' V r' c\u2081 c\u2083 = f.eval_LCFP' V r' c\u2081 c\u2082 \u226b g.eval_LCFP' V r' c\u2082 c\u2083 :=\nbegin\n  haveI : (basic_universal_map.comp f g).suitable c\u2083 c\u2081 := suitable_comp c\u2082,\n  simp only [eval_LCFP'_def, eval_FP_comp r' _ c\u2082, 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\u2082 c\u2081] [hg : g.suitable c\u2083 c\u2082] :\n  @eval_LCFP V r' _ _ (basic_universal_map.comp f g) c\u2081 c\u2083 (suitable_comp c\u2082) =\n    f.eval_LCFP V r' c\u2081 c\u2082 \u226b g.eval_LCFP V r' c\u2082 c\u2083 :=\nby { simp only [eval_LCFP_eq_eval_LCFP'], apply eval_LCFP'_comp }\n\nlemma res_comp_eval_LCFP\n  [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2084 \u2264 c\u2083)] [\u03d5.suitable c\u2084 c\u2082] [\u03d5.suitable c\u2083 c\u2081] :\n  res V r' c\u2081 c\u2082 n \u226b \u03d5.eval_LCFP V r' c\u2082 c\u2084 = \u03d5.eval_LCFP V r' c\u2081 c\u2083 \u226b res V r' c\u2083 c\u2084 m :=\nby simp only [res, eval_LCFP, \u2190 whisker_right_comp, \u2190 nat_trans.op_comp,\n  cast_le_comp_eval_FP _ c\u2084 c\u2083 c\u2082 c\u2081]\n\nlemma Tinv_comp_eval_LCFP [fact (0 < r')] [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [\u03d5.suitable c\u2084 c\u2082] [\u03d5.suitable c\u2083 c\u2081] :\n  Tinv V r' c\u2081 c\u2082 n \u226b \u03d5.eval_LCFP V r' c\u2082 c\u2084 = \u03d5.eval_LCFP V r' c\u2081 c\u2083 \u226b Tinv V r' c\u2083 c\u2084 m :=\nby simp only [Tinv, eval_LCFP, \u2190 whisker_right_comp, \u2190 nat_trans.op_comp,\n  Tinv_comp_eval_FP _ _ c\u2084 c\u2083 c\u2082 c\u2081]\n\nlemma T_inv_comp_eval_LCFP [normed_with_aut r V] [fact (0 < r)] [\u03d5.suitable c\u2082 c\u2081] :\n  T_inv r V r' c\u2081 n \u226b \u03d5.eval_LCFP V r' c\u2081 c\u2082 = \u03d5.eval_LCFP V r' c\u2081 c\u2082 \u226b T_inv r V r' c\u2082 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 (\u03d5 : universal_map m n)\n\ndef eval_LCFP [\u03d5.suitable c\u2082 c\u2081] : LCFP V r' c\u2081 n \u27f6 LCFP V r' c\u2082 m :=\n\u2211 g : {g : basic_universal_map m n // g \u2208 \u03d5.support},\n  begin\n    haveI := suitable_of_mem_support \u03d5 c\u2082 c\u2081 g g.2,\n    exact coeff (g : basic_universal_map m n) \u03d5 \u2022 (basic_universal_map.eval_LCFP V r' g c\u2081 c\u2082)\n  end\n\ndef eval_LCFP' : LCFP V r' c\u2081 n \u27f6 LCFP V r' c\u2082 m :=\n\u2211 g in \u03d5.support, coeff g \u03d5 \u2022 (g.eval_LCFP' V r' c\u2081 c\u2082)\n\nlemma eval_LCFP_eq_eval_LCFP' (h : \u03d5.suitable c\u2082 c\u2081) :\n  \u03d5.eval_LCFP V r' c\u2081 c\u2082 = \u03d5.eval_LCFP' V r' c\u2081 c\u2082 :=\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 \u03d5.support (\u03bb _, iff.rfl),\nend\n\n@[simp] lemma eval_LCFP'_of (f : basic_universal_map m n) :\n  eval_LCFP' V r' c\u2081 c\u2082 (of f) = f.eval_LCFP' V r' c\u2081 c\u2082 :=\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\u2082 c\u2081] :\n  eval_LCFP V r' c\u2081 c\u2082 (of f) = f.eval_LCFP V r' c\u2081 c\u2082 :=\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\u2081 c\u2082 = 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\u2081 c\u2082 = 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\u2081 c\u2082 (-f) = -f.eval_LCFP' V r' c\u2081 c\u2082 :=\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\u2082 c\u2081] :\n  eval_LCFP V r' c\u2081 c\u2082 (-f) = -f.eval_LCFP V r' c\u2081 c\u2082 :=\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\u2081 c\u2082 (f + g) = f.eval_LCFP' V r' c\u2081 c\u2082 + g.eval_LCFP' V r' c\u2081 c\u2082 :=\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\u2082 c\u2081] [g.suitable c\u2082 c\u2081] :\n  eval_LCFP V r' c\u2081 c\u2082 (f + g) = f.eval_LCFP V r' c\u2081 c\u2082 + g.eval_LCFP V r' c\u2081 c\u2082 :=\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\u2082 c\u2081] [g.suitable c\u2082 c\u2081] :\n  eval_LCFP V r' c\u2081 c\u2082 (f - g) = f.eval_LCFP V r' c\u2081 c\u2082 - g.eval_LCFP V r' c\u2081 c\u2082 :=\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\u2082 c\u2081] [hf : f.suitable c\u2083 c\u2082] :\n  eval_LCFP' V r' c\u2081 c\u2083 ((comp (of g)) (of f)) =\n    eval_LCFP' V r' c\u2081 c\u2082 (of g) \u226b eval_LCFP' V r' c\u2082 c\u2083 (of f) :=\nbegin\n  simp only [comp_of, eval_LCFP'_of],\n  haveI hfg : (basic_universal_map.comp g f).suitable c\u2083 c\u2081 := basic_universal_map.suitable_comp c\u2082,\n  rw \u2190 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\u2082 c\u2081] [hf : f.suitable c\u2083 c\u2082] :\n  (comp g f).eval_LCFP' V r' c\u2081 c\u2083 = g.eval_LCFP' V r' c\u2081 c\u2082 \u226b f.eval_LCFP' V r' c\u2082 c\u2083 :=\nbegin\n  unfreezingI { revert hf },\n  apply free_abelian_group.induction_on_free_predicate\n    (suitable c\u2082 c\u2081) (suitable_free_predicate c\u2082 c\u2081) g hg; unfreezingI { clear_dependent g },\n  { intros h\u2082,\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\u2083 c\u2082) (suitable_free_predicate c\u2083 c\u2082) 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\u2081 : universal_map l m) (f\u2082 : universal_map l m) hf\u2081 hf\u2082 IH\u2081 IH\u2082, resetI,\n      haveI Hg\u2081f : (comp (of g) f\u2081).suitable c\u2083 c\u2081 := suitable.comp c\u2082,\n      haveI Hg\u2082f : (comp (of g) f\u2082).suitable c\u2083 c\u2081 := suitable.comp c\u2082,\n      simp only [add_monoid_hom.map_add, eval_LCFP'_add, IH\u2081, IH\u2082, 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\u2081 : universal_map m n) (g\u2082 : universal_map m n) hg\u2081 hg\u2082 IH\u2081 IH\u2082 hf, resetI,\n    haveI Hg\u2081f : (comp g\u2081 f).suitable c\u2083 c\u2081 := suitable.comp c\u2082,\n    haveI Hg\u2082f : (comp g\u2082 f).suitable c\u2083 c\u2081 := suitable.comp c\u2082,\n    simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, eval_LCFP'_add, IH\u2081, IH\u2082, add_comp] }\nend\n\nlemma eval_LCFP_comp (g : universal_map m n) (f : universal_map l m)\n  [hg : g.suitable c\u2082 c\u2081] [hf : f.suitable c\u2083 c\u2082] :\n  @eval_LCFP V r' c\u2081 c\u2083 _ _ (comp g f) (suitable.comp c\u2082) =\n    g.eval_LCFP V r' c\u2081 c\u2082 \u226b f.eval_LCFP V r' c\u2082 c\u2083 :=\nby { simp only [eval_LCFP_eq_eval_LCFP'], apply eval_LCFP'_comp }\n\nlemma res_comp_eval_LCFP [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2084 \u2264 c\u2083)] [\u03d5.suitable c\u2083 c\u2081] [\u03d5.suitable c\u2084 c\u2082] :\n  res V r' c\u2081 c\u2082 n \u226b \u03d5.eval_LCFP V r' c\u2082 c\u2084 = \u03d5.eval_LCFP V r' c\u2081 c\u2083 \u226b res V r' c\u2083 c\u2084 m :=\nbegin\n  simp only [eval_LCFP, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n  apply finset.sum_congr rfl,\n  rintros \u27e8g, hg\u27e9 -,\n  haveI : g.suitable c\u2083 c\u2081 := suitable_of_mem_support \u03d5 _ _ g hg,\n  haveI : g.suitable c\u2084 c\u2082 := suitable_of_mem_support \u03d5 _ _ g hg,\n  simp only [subtype.coe_mk, g.res_comp_eval_LCFP V r' c\u2081 c\u2082 c\u2083 c\u2084],\nend\n\nlemma Tinv_comp_eval_LCFP [fact (0 < r')] [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [\u03d5.suitable c\u2083 c\u2081] [\u03d5.suitable c\u2084 c\u2082] :\n  Tinv V r' c\u2081 c\u2082 n \u226b \u03d5.eval_LCFP V r' c\u2082 c\u2084 = \u03d5.eval_LCFP V r' c\u2081 c\u2083 \u226b Tinv V r' c\u2083 c\u2084 m :=\nbegin\n  simp only [eval_LCFP, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n  apply finset.sum_congr rfl,\n  rintros \u27e8g, hg\u27e9 -,\n  haveI : g.suitable c\u2083 c\u2081 := suitable_of_mem_support \u03d5 _ _ g hg,\n  haveI : g.suitable c\u2084 c\u2082 := suitable_of_mem_support \u03d5 _ _ 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)] [\u03d5.suitable c\u2082 c\u2081] :\n  T_inv r V r' c\u2081 n \u226b \u03d5.eval_LCFP V r' c\u2081 c\u2082 =\n    \u03d5.eval_LCFP V r' c\u2081 c\u2082 \u226b T_inv r V r' c\u2082 m :=\nbegin\n  simp only [eval_LCFP, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n  apply finset.sum_congr rfl,\n  rintros \u27e8g, hg\u27e9 -,\n  haveI : g.suitable c\u2082 c\u2081 := suitable_of_mem_support \u03d5 _ _ 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)] [\u03d5.suitable c\u2082 c\u2081]\n  (N : \u2115) (h : \u03d5.bound_by N) (M) :\n  \u2225(\u03d5.eval_LCFP V r' c\u2081 c\u2082).app M\u2225 \u2264 N :=\nbegin\n  rw [eval_LCFP_eq_eval_LCFP', eval_LCFP'],\n  have : (\u2211 (g : basic_universal_map m n) in support \u03d5, (coeff g \u03d5).nat_abs : \u211d) \u2264 N,\n  { exact_mod_cast h },\n  simp only [\u2190 nat_trans.app_hom_apply, add_monoid_hom.map_sum, add_monoid_hom.map_zsmul],\n  refine le_trans (norm_sum_le_of_le \u03d5.support _) this,\n  intros g hg,\n  have aux := \u03d5.suitable_of_mem_support c\u2082 c\u2081 g hg,\n  refine le_trans (norm_zsmul_le _ _) _,\n  suffices : \u2225(nat_trans.app_hom M) (basic_universal_map.eval_LCFP' V r' g c\u2081 c\u2082)\u2225 \u2264 1,\n  { have aux\u2081 : \u2225(coeff g) \u03d5\u2225 = \u2191(((coeff g) \u03d5).nat_abs),\n    { rw [@coe_coe \u2115 \u2124 \u211d _ _ _, \u2190 int.abs_eq_nat_abs, int.cast_abs],\n    refl },\n    rw aux\u2081,\n    exact mul_le_of_le_one_right ((coeff g) \u03d5).nat_abs.cast_nonneg this },\n  rw [\u2190 g.eval_LCFP_eq_eval_LCFP' V r' c\u2081 c\u2082, 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": "import smt2\nimport .test_tactics\n\nexample (P Q : Prop) : P -> Q :=\nbegin\n    intros,\n    must_fail z3\nend\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/test/P_implies_Q_fail.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.06371499025175958, "lm_q1q2_score": 0.029126461456385214}}
{"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.Basic\nimport Lean.Meta.FunInfo\nimport Lean.Meta.InferType\nimport Lean.Meta.WHNF\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 \u03b1 (ringAdd ?\u03b1 ?s) ?x ?x`\n  and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys\n  respctively\n  ```\n  \u27e8Add.add, 4\u27e9, *, *, *, *\n  \u27e8Add.add, 4\u27e9, *, *, \u27e8a,0\u27e9, \u27e8b,0\u27e9\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 \u2192 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 \u2192 Key \u2192 Bool\n  | Key.lit v\u2081,      Key.lit v\u2082      => v\u2081 < v\u2082\n  | Key.fvar n\u2081 a\u2081,  Key.fvar n\u2082 a\u2082  => Name.quickLt n\u2081.name n\u2082.name || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | Key.const n\u2081 a\u2081, Key.const n\u2082 a\u2082 => Name.quickLt n\u2081 n\u2082 || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | Key.proj s\u2081 i\u2081,  Key.proj s\u2082 i\u2082  => Name.quickLt s\u2081 s\u2082 || (s\u2081 == s\u2082 && i\u2081 < i\u2082)\n  | k\u2081,              k\u2082              => k\u2081.ctorIdx < k\u2082.ctorIdx\n\ninstance : LT Key := \u27e8fun a b => Key.lt a b\u27e9\ninstance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key \u2192 Format\n  | Key.star                   => \"*\"\n  | Key.other                  => \"\u25fe\"\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                  => \"\u2192\"\n\ninstance : ToFormat Key := \u27e8Key.format\u27e9\n\ndef Key.arity : Key \u2192 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 \u03b1) := \u27e8Trie.node #[] #[]\u27e9\n\ndef empty : DiscrTree \u03b1 := { root := {} }\n\npartial def Trie.format [ToFormat \u03b1] : Trie \u03b1 \u2192 Format\n  | Trie.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 \u27e8k, c\u27e9 => Format.line ++ Format.paren (Std.format k ++ \" => \" ++ format c))\n\ninstance [ToFormat \u03b1] : ToFormat (Trie \u03b1) := \u27e8Trie.format\u27e9\n\npartial def format [ToFormat \u03b1] (d : DiscrTree \u03b1) : Format :=\n  let (_, r) := d.root.foldl\n    (fun (p : Bool \u00d7 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 \u03b1] : ToFormat (DiscrTree \u03b1) := \u27e8format\u27e9\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 \u03b1) 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 \u03b1]`) 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., `{\u03b1 : 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 \u27e8i, h\u27e9\n    if info.isInstImplicit then\n      return true\n    else if info.isImplicit || info.isStrictImplicit then\n      return not (\u2190 isType a)\n    else\n      isProof a\n  else\n    isProof a\n\nprivate partial def pushArgsAux (infos : Array ParamInfo) : Nat \u2192 Expr \u2192 Array Expr \u2192 MetaM (Array Expr)\n  | i, Expr.app f a _, todo => do\n    if (\u2190 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 (\u2190 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 (\u2190 isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false\n  else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then\n    if (\u2190 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\nprivate partial def whnfEta (e : Expr) : MetaM Expr := do\n  let e \u2190 whnf e\n  match e.etaExpandedStrict? with\n  | some e => whnfEta e\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 \u2218 List.map g` would be mapped into the key `Key.other`\n  since the function composition `\u2218` 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  | Expr.lit ..   => false\n  | Expr.const .. => false\n  | Expr.fvar ..  => false\n  | Expr.proj ..  => false\n  | Expr.forallE _ d 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 `whnfEta` for root terms at `pushArgs`. -/\nprivate partial def whnfUntilBadKey (e : Expr) : MetaM Expr := do\n  let e \u2190 step e\n  match e.etaExpandedStrict? with\n  | some e => whnfUntilBadKey e\n  | none   => return e\nwhere\n  step (e : Expr) := do\n    let e \u2190 whnfCore e\n    match (\u2190 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 whnfDT (e : Expr) (root : Bool) : MetaM Expr :=\n  if root then whnfUntilBadKey e else whnfEta e\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 \u00d7 Array Expr) := do\n  if hasNoindexAnnotation e then\n    return (Key.star, todo)\n  else\n    let e \u2190 whnfDT e root\n    let fn := e.getAppFn\n    let push (k : Key) (nargs : Nat) : MetaM (Key \u00d7 Array Expr) := do\n      let info \u2190 getFunInfoNArgs fn nargs\n      let todo \u2190 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      unless root do\n        if (\u2190 shouldAddAsStar c e) then\n          return (Key.star, todo)\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 implicit arguments and proofs\n        return (Key.star, todo)\n      else if (\u2190 isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then\n        return (Key.other, 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) \u2190 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  withReducible 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 : \u03b1) (i : Nat) : Trie \u03b1 :=\n  if h : i < keys.size then\n    let k := keys.get \u27e8i, h\u27e9\n    let c := createNodes keys v (i+1)\n    Trie.node #[] #[(k, c)]\n  else\n    Trie.node #[v] #[]\n\nprivate def insertVal [BEq \u03b1] (vs : Array \u03b1) (v : \u03b1) : Array \u03b1 :=\n  if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq \u03b1] (keys : Array Key) (v : \u03b1) : Nat \u2192 Trie \u03b1 \u2192 Trie \u03b1\n  | i, Trie.node vs cs =>\n    if h : i < keys.size then\n      let k := keys.get \u27e8i, h\u27e9\n      let c := Id.run $ cs.binInsertM\n          (fun a b => a.1 < b.1)\n          (fun \u27e8_, s\u27e9 => 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 \u03b1] (d : DiscrTree \u03b1) (keys : Array Key) (v : \u03b1) : DiscrTree \u03b1 :=\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 \u03b1] (d : DiscrTree \u03b1) (e : Expr) (v : \u03b1) : MetaM (DiscrTree \u03b1) := do\n  let keys \u2190 mkPath e\n  return d.insertCore keys v\n\nprivate def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key \u00d7 Array Expr) := do\n  let e \u2190 whnfDT e root\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      let ctx \u2190 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 (Key.star, #[])\n      else if (\u2190 isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then\n        return (Key.other, #[])\n      else\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 \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree \u03b1) : Array \u03b1 :=\n  let result : Array \u03b1 := 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 \u00d7 Trie \u03b1)) (k : Key) : Option (Key \u00d7 Trie \u03b1) :=\n  cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie \u03b1) (result : Array \u03b1) : MetaM (Array \u03b1) := 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) \u2190 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 \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) : MetaM (Array \u03b1) :=\n        match findKey cs k with\n        | none   => return result\n        | some c => getMatchLoop (todo ++ args) c.2 result\n      let result \u2190 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 #[] (\u2190 visitNonStar k args result)\n      | _         => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree \u03b1) (k : Key) (args : Array Expr) (result : Array \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) (e : Expr) : MetaM (Array \u03b1) :=\n  withReducible do\n    let result := getStarResult d\n    let (k, args) \u2190 getMatchKeyArgs e (root := true)\n    match k with\n    | Key.star => return result\n    | _        => getMatchRoot d k args result\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 \u03b1) (e : Expr) : MetaM (Array (\u03b1 \u00d7 Nat)) :=\n  withReducible do\n    let result := getStarResult d |>.map (., 0)\n    let (k, args) \u2190 getMatchKeyArgs e (root := true)\n    match k with\n    | Key.star => return result\n    | _        => process k args.toSubarray 0 result\nwhere\n  process (k : Key) (args : Subarray Expr) (numExtraArgs : Nat) (result : Array (\u03b1 \u00d7 Nat)) : MetaM (Array (\u03b1 \u00d7 Nat)) := do\n    -- Remark: the args are stored in reverse order\n    let result :=\n      if d.root.find? k |>.isSome then\n        result ++ ((\u2190 getMatchRoot d k args.toArray #[]).map (., numExtraArgs))\n      else\n        result\n    match k with\n    | Key.const f 0     => return result\n    | Key.const f (n+1) => process (Key.const f n) args.popFront (numExtraArgs + 1) result\n    | Key.fvar f 0      => return result\n    | Key.fvar f (n+1)  => process (Key.fvar f n) args.popFront (numExtraArgs + 1) result\n    | _                 => return result\n\npartial def getUnify (d : DiscrTree \u03b1) (e : Expr) : MetaM (Array \u03b1) :=\n  withReducible do\n    let (k, args) \u2190 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 \u03b1) (result : Array \u03b1) : MetaM (Array \u03b1) := 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 \u27e8k, c\u27e9 => 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) \u2190 getUnifyKeyArgs e (root := false)\n        let visitStar (result : Array \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) : MetaM (Array \u03b1) :=\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 \u27e8k, c\u27e9 => process k.arity todo c result\n        -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n        | Key.arrow => visitNonStar Key.other #[] (\u2190 visitNonStar k args (\u2190 visitStar result))\n        | _         => visitNonStar k args (\u2190 visitStar result)\n\nend Lean.Meta.DiscrTree\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/DiscrTree.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.06008665101556925, "lm_q1q2_score": 0.029104777082843186}}
{"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 \u2192 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 \u2192 B)\n(map_op' : \u2200 {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 (\u03bb _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := \u03bb 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 \u2192 B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : my_hom A B :=\n{ to_fun := f',\n  map_op' := h.symm \u25b8 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 (\u03bb _, B) :=\n(map_op : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u2192 has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to functions from `\u03b1` to `\u03b2`.\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*) (\u03b1 : out_param Sort*) (\u03b2 : out_param $ \u03b1 \u2192 Sort*) :=\n(coe : F \u2192 \u03a0 a : \u03b1, \u03b2 a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F \u03b1 \u03b2` where `\u03b2` depends on `a : \u03b1` -/\n\nvariables (F \u03b1 : Sort*) (\u03b2 : \u03b1 \u2192 Sort*)\n\nnamespace fun_like\n\nvariables {F \u03b1 \u03b2} [i : fun_like F \u03b1 \u03b2]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n  nolint dangerous_instance] -- `\u03b1` and `\u03b2` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (\u03bb _, \u03a0 a : \u03b1, \u03b2 a) := { coe := fun_like.coe }\n\ntheorem coe_injective : function.injective (coe_fn : F \u2192 \u03a0 a : \u03b1, \u03b2 a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a) \u2194 f = g :=\n\u27e8\u03bb h, @coe_injective _ _ _ i _ _ h, \u03bb h, by cases h; refl\u27e9\n\ntheorem ext' {f g : F} (h : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g \u2194 ((f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : \u2200 (x : \u03b1), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g \u2194 (\u2200 x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h\u2081 : f = g) (x : \u03b1) : f x = g x :=\ncongr_fun (congr_arg _ h\u2081) x\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F \u03b1 (\u03bb _, \u03b2)` where `\u03b2` does not depend on `a : \u03b1` -/\n\nvariables {F \u03b1 \u03b2 : Sort*} [i : fun_like F \u03b1 (\u03bb _, \u03b2)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : \u03b1} (h\u2081 : f = g) (h\u2082 : x = y) : f x = g y :=\ncongr (congr_arg _ h\u2081) h\u2082\n\nprotected lemma congr_arg (f : F) {x y : \u03b1} (h\u2082 : x = y) : f x = f y :=\ncongr_arg _ h\u2082\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) 2022 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\n-- This test can be used to check for memory leaks. It executes Aesop `N`\n-- times with a rule set containing a no-op rule (and the builtin rules) and\n-- with a limit of 10 goal applications. If everything works properly, the test\n-- should only require a small, constant amount of memory.\n\nimport Aesop\nimport Lean\n\nopen Lean\nopen Lean.Elab.Tactic\n\ndef N : Nat := 10000\n\n@[aesop safe]\ndef noopRule : TacticM Unit := return\n\nelab &\"memoryStressTest\" : tactic =>\n  for i in [0:N] do\n    evalTactic\n      (\u2190 `(tactic| try aesop (options := { maxRuleApplications := 10 })))\n\n-- Our very own True, to prevent the Aesop default rules from solving the goal.\nstructure TT where\n\nset_option maxHeartbeats 0\n\nexample : TT := by\n  memoryStressTest noopRule\n  exact TT.mk\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/expensive/Memory.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4493926197162523, "lm_q2_score": 0.06465348835622392, "lm_q1q2_score": 0.02905480050619768}}
{"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 \u03b1`: free monoid over alphabet `\u03b1`; defined as a synonym for `list \u03b1`\n  with multiplication given by `(++)`.\n* `free_monoid.of`: embedding `\u03b1 \u2192 free_monoid \u03b1` sending each element `x` to `[x]`;\n* `free_monoid.lift`: natural equivalence between `\u03b1 \u2192 M` and `free_monoid \u03b1 \u2192* M`\n* `free_monoid.map`: embedding of `\u03b1 \u2192 \u03b2` into `free_monoid \u03b1 \u2192* free_monoid \u03b2` given by `list.map`.\n-/\n\n/-- Free monoid over a given alphabet. -/\ndef free_add_monoid (\u03b1 : Type u_1) :=\n  List \u03b1\n\nnamespace free_monoid\n\n\nprotected instance Mathlib.free_add_monoid.add_monoid {\u03b1 : Type u_1} : add_monoid (free_add_monoid \u03b1) :=\n  add_monoid.mk (fun (x y : free_add_monoid \u03b1) => x ++ y) sorry [] sorry sorry\n\nprotected instance inhabited {\u03b1 : Type u_1} : Inhabited (free_monoid \u03b1) :=\n  { default := 1 }\n\ntheorem one_def {\u03b1 : Type u_1} : 1 = [] :=\n  rfl\n\ntheorem Mathlib.free_add_monoid.add_def {\u03b1 : Type u_1} (xs : List \u03b1) (ys : List \u03b1) : xs + ys = xs ++ ys :=\n  rfl\n\n/-- Embeds an element of `\u03b1` into `free_monoid \u03b1` as a singleton list. -/\ndef of {\u03b1 : Type u_1} (x : \u03b1) : free_monoid \u03b1 :=\n  [x]\n\ntheorem of_def {\u03b1 : Type u_1} (x : \u03b1) : of x = [x] :=\n  rfl\n\ntheorem of_injective {\u03b1 : Type u_1} : function.injective of :=\n  fun (a b : \u03b1) => 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 {\u03b1 : Type u_1} {C : free_monoid \u03b1 \u2192 Sort u_2} (xs : free_monoid \u03b1) (h0 : C 1) (ih : (x : \u03b1) \u2192 (xs : free_monoid \u03b1) \u2192 C xs \u2192 C (of x * xs)) : C xs :=\n  list.rec_on xs h0 ih\n\ntheorem hom_eq {\u03b1 : Type u_1} {M : Type u_4} [monoid M] {f : free_monoid \u03b1 \u2192* M} {g : free_monoid \u03b1 \u2192* M} (h : \u2200 (x : \u03b1), coe_fn f (of x) = coe_fn g (of x)) : f = g := sorry\n\n/-- Equivalence between maps `\u03b1 \u2192 M` and monoid homomorphisms `free_monoid \u03b1 \u2192* M`. -/\ndef lift {\u03b1 : Type u_1} {M : Type u_4} [monoid M] : (\u03b1 \u2192 M) \u2243 (free_monoid \u03b1 \u2192* M) :=\n  equiv.mk (fun (f : \u03b1 \u2192 M) => monoid_hom.mk (fun (l : free_monoid \u03b1) => list.prod (list.map f l)) sorry sorry)\n    (fun (f : free_monoid \u03b1 \u2192* M) (x : \u03b1) => coe_fn f (of x)) sorry sorry\n\n@[simp] theorem Mathlib.free_add_monoid.lift_symm_apply {\u03b1 : Type u_1} {M : Type u_4} [add_monoid M] (f : free_add_monoid \u03b1 \u2192+ M) : coe_fn (equiv.symm free_add_monoid.lift) f = \u21d1f \u2218 free_add_monoid.of :=\n  rfl\n\ntheorem lift_apply {\u03b1 : Type u_1} {M : Type u_4} [monoid M] (f : \u03b1 \u2192 M) (l : free_monoid \u03b1) : coe_fn (coe_fn lift f) l = list.prod (list.map f l) :=\n  rfl\n\ntheorem Mathlib.free_add_monoid.lift_comp_of {\u03b1 : Type u_1} {M : Type u_4} [add_monoid M] (f : \u03b1 \u2192 M) : \u21d1(coe_fn free_add_monoid.lift f) \u2218 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 {\u03b1 : Type u_1} {M : Type u_4} [add_monoid M] (f : \u03b1 \u2192 M) (x : \u03b1) : 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 {\u03b1 : Type u_1} {M : Type u_4} [monoid M] (f : free_monoid \u03b1 \u2192* M) : coe_fn lift (\u21d1f \u2218 of) = f :=\n  equiv.apply_symm_apply lift f\n\ntheorem comp_lift {\u03b1 : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M \u2192* N) (f : \u03b1 \u2192 M) : monoid_hom.comp g (coe_fn lift f) = coe_fn lift (\u21d1g \u2218 f) := sorry\n\ntheorem hom_map_lift {\u03b1 : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M \u2192* N) (f : \u03b1 \u2192 M) (x : free_monoid \u03b1) : coe_fn g (coe_fn (coe_fn lift f) x) = coe_fn (coe_fn lift (\u21d1g \u2218 f)) x :=\n  iff.mp monoid_hom.ext_iff (comp_lift g f) x\n\n/-- The unique monoid homomorphism `free_monoid \u03b1 \u2192* free_monoid \u03b2` that sends\neach `of x` to `of (f x)`. -/\ndef map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : free_monoid \u03b1 \u2192* free_monoid \u03b2 :=\n  monoid_hom.mk (list.map f) sorry sorry\n\n@[simp] theorem map_of {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : coe_fn (map f) (of x) = of (f x) :=\n  rfl\n\ntheorem Mathlib.free_add_monoid.lift_of_comp_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : (coe_fn free_add_monoid.lift fun (x : \u03b1) => free_add_monoid.of (f x)) = free_add_monoid.map f :=\n  free_add_monoid.hom_eq fun (x : \u03b1) => rfl\n\ntheorem map_comp {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (g : \u03b2 \u2192 \u03b3) (f : \u03b1 \u2192 \u03b2) : map (g \u2218 f) = monoid_hom.comp (map g) (map f) :=\n  hom_eq fun (x : \u03b1) => rfl\n\nprotected instance star_monoid {\u03b1 : Type u_1} : star_monoid (free_monoid \u03b1) :=\n  star_monoid.mk list.reverse_append\n\n@[simp] theorem star_of {\u03b1 : Type u_1} (x : \u03b1) : 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 {\u03b1 : 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": "import all\n\nsection eval_trace\n\nmeta def EVAL_TRACE := tt\n\nmeta def set_show_eval_trace : bool \u2192 tactic unit := tactic.set_bool_option `evaltrace\n\nmeta def eval_trace {\u03b1} [has_to_tactic_format \u03b1] : \u03b1 \u2192 tactic unit | a := do {\n  evaltrace_flag \u2190 tactic.get_bool_option `evaltrace ff,\n  -- let trace_flag := tactic.is_trace_enabled_for `EVAL_TRACE,\n  let trace_flag := EVAL_TRACE,\n  let cond := (trace_flag || evaltrace_flag),\n  when cond (tactic.trace a)\n}\n\nend eval_trace\n\nnamespace set_env\n\nmeta def get_env_at_decl (decl_nm : name) : tactic environment := do {\n  env \u2190 tactic.get_env,\n  lean_file \u2190 env.decl_olean decl_nm,\n  pure $ environment.for_decl_of_imported_module lean_file decl_nm\n}\n\nmeta def set_env_at_decl (decl_nm : name) : tactic unit := do {\n    env \u2190 get_env_at_decl decl_nm,\n    eval_trace format!\"[set_env_at_decl] GOT ENV AT DECL {decl_nm}\",\n    tactic.set_env_core env,\n    eval_trace format!\"[set_env_at_decl] SET ENV AT DECL {decl_nm}\"\n}\n\nend set_env\n\n\nmeta def add_open_namespace : name \u2192 tactic unit := \u03bb nm, do\nenv \u2190 tactic.get_env, tactic.set_env (env.execute_open nm)\n\nmeta def add_open_namespaces (nms : list name) : tactic unit :=\nnms.mmap' add_open_namespace\n\n\nrun_cmd do {\nset_env.set_env_at_decl `finset.union_comm,\nadd_open_namespaces [\n`finset,\n`finset,\n`nat,\n`function,\n`subtype,\n`multiset]}\n\nnamespace inspection_tools\n\ndef join (sep : string) : list string \u2192 string\n| [x]     := x\n| []      := \"\"\n| (x::xs) := x ++ sep ++ join xs\n\nmeta def expr_to_string (e : expr bool.tt) : tactic string :=\ndo\n  o \u2190 tactic.get_options,\n  tactic.set_options (options.mk.set_bool `pp.all tt),\n  f \u2190 tactic.pp e,\n  tactic.set_options o,  -- set back to before\n  return $ to_string f\n  \nmeta def local_cxt_to_string (v : expr bool.tt) : tactic string := \ndo \n  tp \u2190 tactic.infer_type v,\n  v_str \u2190 expr_to_string v,\n  tp_str \u2190 expr_to_string tp,\n  return $ v_str ++ \"\\n\\n\" ++ tp_str\n\nmeta def goal_to_string (g : expr) : tactic string :=\ndo \n  tactic.set_goals [g],\n  goal \u2190 tactic.target,\n  local_cxt \u2190 tactic.local_context,\n  let local_cxt_len := list.length local_cxt,\n  goal_str \u2190 expr_to_string goal,\n  local_cxt_strs \u2190 (list.mmap local_cxt_to_string local_cxt),\n  let s1 := goal_str ++ \"\\n\\n\",\n  let s2 := \"Local Context Vars: \" ++ (to_string local_cxt_len) ++ \"\\n\\n\",\n  let s3 := join \"\\n\\n\" local_cxt_strs,\n  return $ s1 ++ s2 ++ s3\n\nmeta def state_report : tactic string :=\ndo \n gs \u2190 tactic.get_goals,\n -- loop over all goals (has effect of resetting the goal each time)\n let gs_len := list.length gs,\n goal_strings \u2190 gs.mmap goal_to_string,\n tactic.set_goals gs,  -- set goals back\n let s := \"Goals: \" ++ (to_string gs_len) ++ \"\\n\\n\" ++ (join \"\\n\\n\" goal_strings),\n return s\n \nmeta def trace_goal_state : tactic unit :=\ndo \n s \u2190 state_report,\n tactic.trace s,\n return ()\n\nend inspection_tools\n\n\nnamespace custom\n \nmeta def trace_custom_state : tactic unit :=\ndo \n tactic.trace \"\",  -- make more interesting\n return ()\n\nend custom\n\nsection example_block\nuniverses u_1\nexample {\u03b1 : Type u_1} [_inst_1 : decidable_eq \u03b1] (s\u2081 s\u2082 : finset \u03b1) : s\u2081 \u222a s\u2082 = s\u2082 \u222a s\u2081 :=\nbegin\nsimp,\ninspection_tools.trace_goal_state,\ncustom.trace_custom_state,\nend\nend example_block\n\n#eval 1", "meta": {"author": "toontran", "repo": "pact-lean-low-resource", "sha": "e24af1935b7f518f4d3ce5fe55e0a8fd1d541b82", "save_path": "github-repos/lean/toontran-pact-lean-low-resource", "path": "github-repos/lean/toontran-pact-lean-low-resource/pact-lean-low-resource-e24af1935b7f518f4d3ce5fe55e0a8fd1d541b82/src/test_template.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.06278920772016683, "lm_q1q2_score": 0.028946878318723314}}
{"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 \u00d7 K} G = lim_J (lim_K G(j, -))$ for a functor `G : J \u00d7 K \u2964 C`,\nwhen all the appropriate limits exist.\n\nWe begin working with a functor `F : J \u2964 K \u2964 C`. We'll write `G : J \u00d7 K \u2964 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) \u2245 limit (F \u22d9 lim)`\nand give simp lemmas characterising it.\nFor convenience, we also provide\n`limit_iso_limit_curry_comp_lim G : limit G \u2245 limit ((curry.obj G) \u22d9 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 \u2964 K \u2964 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 : \u03a0 j : J, cone (F.obj j))\n(map : \u03a0 {j j' : J} (f : j \u27f6 j'), (cones.postcompose (F.map f)).obj (obj j) \u27f6 obj j')\n(id : \u2200 j : J, (map (\ud835\udfd9 j)).hom = \ud835\udfd9 _ . obviously)\n(comp : \u2200 {j\u2081 j\u2082 j\u2083 : J} (f : j\u2081 \u27f6 j\u2082) (g : j\u2082 \u27f6 j\u2083),\n  (map (f \u226b g)).hom = (map f).hom \u226b (map g).hom . obviously)\n\nvariables {F}\n\n/--\nExtract the functor `J \u2964 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 \u2964 C :=\n{ obj := \u03bb j, (D.obj j).X,\n  map := \u03bb j j' f, (D.map f).hom,\n  map_id' := \u03bb j, D.id j,\n  map_comp' := \u03bb j\u2081 j\u2082 j\u2083 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 : \u03a0 j, is_limit (D.obj j))\n  (c : cone (uncurry.obj F)) :\n  cone (D.cone_points) :=\n{ X := c.X,\n  \u03c0 :=\n  { app := \u03bb j, (Q j).lift\n    { X := c.X,\n      \u03c0 :=\n      { app := \u03bb k, c.\u03c0.app (j, k),\n        naturality' := \u03bb k k' f,\n        begin\n          dsimp, simp only [category.id_comp],\n          have := @nat_trans.naturality _ _ _ _ _ _ c.\u03c0 (j, k) (j, k') (\ud835\udfd9 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' := \u03bb 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_\u03c0, 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.\u03c0 (j, k) (j', k) (f, \ud835\udfd9 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 : \u03a0 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 := \u03bb s, P.lift\n  { X := s.X,\n    \u03c0 :=\n    { app := \u03bb p, s.\u03c0.app p.1 \u226b (D.obj p.1).\u03c0.app p.2,\n      naturality' := \u03bb p p' f,\n      begin\n        dsimp, simp only [category.id_comp, category.assoc],\n        rcases p with \u27e8j, k\u27e9,\n        rcases p' with \u27e8j', k'\u27e9,\n        rcases f with \u27e8fj, fk\u27e9,\n        dsimp,\n        slice_rhs 3 4 { rw \u2190nat_trans.naturality, },\n        slice_rhs 2 3 { rw \u2190(D.obj j).\u03c0.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 \u2190w,\n        have n := s.\u03c0.naturality fj,\n        dsimp at n,\n        simp only [category.id_comp] at n,\n        rw n,\n        simp,\n      end, } },\n  fac' := \u03bb s j,\n  begin\n    apply (Q j).hom_ext,\n    intro k,\n    simp,\n  end,\n  uniq' := \u03bb s m w,\n  begin\n    refine P.uniq { X := s.X, \u03c0 := _, } m _,\n    rintro \u27e8j, k\u27e9,\n    dsimp,\n    rw [\u2190w j],\n    simp,\n  end, }\n\nsection\nvariables (F)\nvariables [has_limits_of_shape K C]\n\n/--\nGiven a functor `F : J \u2964 K \u2964 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 := \u03bb j, limit.cone (F.obj j),\n  map := \u03bb 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\u27e8diagram_of_cones.mk_of_has_limits F\u27e9\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 \u22d9 lim) :=\nrfl\n\nvariables [has_limit (uncurry.obj F)]\nvariables [has_limit (F \u22d9 lim)]\n\n/--\nThe Fubini theorem for a functor `F : J \u2964 K \u2964 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) \u2245 limit (F \u22d9 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 : \u03a0 j, is_limit (G.obj j) := \u03bb j, limit.is_limit _,\n  have Q' := cone_of_cone_uncurry_is_limit Q P,\n  have Q'' := (limit.is_limit (F \u22d9 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_\u03c0_\u03c0 {j} {k} :\n  (limit_uncurry_iso_limit_comp_lim F).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k = limit.\u03c0 _ (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_\u03c0 {j} {k} :\n  (limit_uncurry_iso_limit_comp_lim F).inv \u226b limit.\u03c0 _ (j, k) = limit.\u03c0 _ j \u226b limit.\u03c0 _ k :=\nbegin\n  rw [\u2190cancel_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 \u00d7 K) C] [has_limits_of_shape (K \u00d7 J) C]\n\n/-- The limit of `F.flip \u22d9 lim` is isomorphic to the limit of `F \u22d9 lim`. -/\nnoncomputable\ndef limit_flip_comp_lim_iso_limit_comp_lim : limit (F.flip \u22d9 lim) \u2245 limit (F \u22d9 lim) :=\n(limit_uncurry_iso_limit_comp_lim _).symm \u226a\u226b\n  has_limit.iso_of_nat_iso (uncurry_obj_flip _) \u226a\u226b\n  (has_limit.iso_of_equivalence (prod.braiding _ _)\n    (nat_iso.of_components (\u03bb _, by refl) (by tidy))) \u226a\u226b\n  limit_uncurry_iso_limit_comp_lim _\n\n@[simp, reassoc]\nlemma limit_flip_comp_lim_iso_limit_comp_lim_hom_\u03c0_\u03c0 (j) (k) :\n  (limit_flip_comp_lim_iso_limit_comp_lim F).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k =\n  limit.\u03c0 _ k \u226b limit.\u03c0 _ 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_\u03c0_\u03c0 (k) (j) :\n  (limit_flip_comp_lim_iso_limit_comp_lim F).inv \u226b limit.\u03c0 _ k \u226b limit.\u03c0 _ j =\n  limit.\u03c0 _ j \u226b limit.\u03c0 _ k :=\nby { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, dsimp, simp, }\n\nend\n\nsection\nvariables (G : J \u00d7 K \u2964 C)\n\nsection\nvariables [has_limits_of_shape K C]\nvariables [has_limit G]\nvariables [has_limit ((curry.obj G) \u22d9 lim)]\n\n/--\nThe Fubini theorem for a functor `G : J \u00d7 K \u2964 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 \u2245 limit ((curry.obj G) \u22d9 lim) :=\nbegin\n  have i : G \u2245 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_\u03c0_\u03c0 {j} {k} :\n  (limit_iso_limit_curry_comp_lim G).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k = limit.\u03c0 _ (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_\u03c0 {j} {k} :\n  (limit_iso_limit_curry_comp_lim G).inv \u226b limit.\u03c0 _ (j, k) = limit.\u03c0 _ j \u226b limit.\u03c0 _ k :=\nbegin\n  rw [\u2190cancel_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 \u00d7 K \u2964 C`,\nshowing that $\\lim_k \\lim_j G(j,k) \u2245 \\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 \u22d9 G)) \u22d9 lim) \u2245 limit ((curry.obj G) \u22d9 lim) :=\ncalc\n  limit ((curry.obj (swap K J \u22d9 G)) \u22d9 lim)\n      \u2245 limit (swap K J \u22d9 G) : (limit_iso_limit_curry_comp_lim _).symm\n  ... \u2245 limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _)\n  ... \u2245 limit ((curry.obj G) \u22d9 lim) : limit_iso_limit_curry_comp_lim _\n\n@[simp]\nlemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_\u03c0_\u03c0 {j} {k} :\n  (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k =\n   limit.\u03c0 _ k \u226b limit.\u03c0 _ 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_\u03c0,\n    iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_\u03c0_\u03c0, 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_\u03c0_\u03c0 {j} {k} :\n  (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv \u226b limit.\u03c0 _ k \u226b limit.\u03c0 _ j =\n   limit.\u03c0 _ j \u226b limit.\u03c0 _ 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_\u03c0,\n    iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_\u03c0_\u03c0, 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 {\u03b1 : Sort u} {\u03b2 : Sort v}\n\n/-- Functorial action. -/\nprotected def map (f : \u03b1 \u2192 \u03b2) (a : PLift \u03b1) : PLift \u03b2 :=\n  PLift.up (f a.down)\n#align plift.map PLift.map\n\n@[simp]\ntheorem map_up (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : (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 : \u03b1 \u2192 PLift \u03b1 :=\n  up\n#align plift.pure PLift.pure\n\n/-- Applicative sequencing. -/\nprotected def seq (f : PLift (\u03b1 \u2192 \u03b2)) (x : Unit \u2192 PLift \u03b1) : PLift \u03b2 :=\n  PLift.up (f.down (x ()).down)\n#align plift.seq PLift.seq\n\n@[simp]\ntheorem seq_up (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (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 \u03b1) (f : \u03b1 \u2192 PLift \u03b2) : PLift \u03b2 :=\n  f a.down\n#align plift.bind PLift.bind\n\n@[simp]\ntheorem bind_up (a : \u03b1) (f : \u03b1 \u2192 PLift \u03b2) : (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 _ \u27e8_\u27e9 => rfl\n  comp_map := @fun _ _ _ _ _ \u27e8_\u27e9 => 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 _ _ _ \u27e8_\u27e9 => rfl\n  map_pure := @fun _ _ _ _ => rfl\n  seq_pure := @fun _ _ \u27e8_\u27e9 _ => rfl\n  seq_assoc := @fun _ _ _ \u27e8_\u27e9 \u27e8_\u27e9 \u27e8_\u27e9 => rfl\n\ninstance : LawfulMonad PLift where\n  bind_pure_comp := @fun _ _ _ \u27e8_\u27e9 => rfl\n  bind_map := @fun _ _ \u27e8_\u27e9 \u27e8_\u27e9 => rfl\n  pure_bind := @fun _ _ _ _ => rfl\n  bind_assoc := @fun _ _ _ \u27e8_\u27e9 _ _ => rfl\n\n@[simp]\ntheorem rec.constant {\u03b1 : Sort u} {\u03b2 : Type v} (b : \u03b2) :\n    (@PLift.rec \u03b1 (fun _ => \u03b2) fun _ => b) = fun _ => b := rfl\n\n#align plift.rec.constant PLift.rec.constant\n\nend PLift\n\nnamespace ULift\n\nvariable {\u03b1 : Type u} {\u03b2 : Type v}\n\n/-- Functorial action. -/\nprotected def map (f : \u03b1 \u2192 \u03b2) (a : ULift \u03b1) : ULift \u03b2 :=\n  ULift.up.{u} (f a.down)\n#align ulift.map ULift.map\n\n@[simp]\ntheorem map_up (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : (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 : \u03b1 \u2192 ULift \u03b1 :=\n  up\n#align ulift.pure ULift.pure\n\n/-- Applicative sequencing. -/\nprotected def seq {\u03b1 \u03b2} (f : ULift (\u03b1 \u2192 \u03b2)) (x : Unit \u2192 ULift \u03b1) : ULift \u03b2 :=\n  ULift.up.{u} (f.down (x ()).down)\n#align ulift.seq ULift.seq\n\n@[simp]\ntheorem seq_up (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (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 \u03b1) (f : \u03b1 \u2192 ULift \u03b2) : ULift \u03b2 :=\n  f a.down\n#align ulift.bind ULift.bind\n\n@[simp]\ntheorem bind_up (a : \u03b1) (f : \u03b1 \u2192 ULift \u03b2) : (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 _ \u27e8_\u27e9 => rfl\n  comp_map := @fun _ _ _ _ _ \u27e8_\u27e9 => 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 _ _ _ \u27e8_\u27e9 => rfl\n  map_pure := @fun _ _ _ _ => rfl\n  seq_pure := @fun _ _ \u27e8_\u27e9 _ => rfl\n  seq_assoc := @fun _ _ _ \u27e8_\u27e9 \u27e8_\u27e9 \u27e8_\u27e9 => rfl\n\ninstance : LawfulMonad ULift where\n  bind_pure_comp := @fun _ _ _ \u27e8_\u27e9 => rfl\n  bind_map := @fun _ _ \u27e8_\u27e9 \u27e8_\u27e9 => rfl\n  pure_bind := @fun _ _ _ _ => rfl\n  bind_assoc := @fun _ _ _ \u27e8_\u27e9 _ _ => rfl\n\n@[simp]\ntheorem rec.constant {\u03b1 : Type u} {\u03b2 : Sort v} (b : \u03b2) :\n     (@ULift.rec \u03b1 (fun _ => \u03b2) 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 \u2192 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 {\u03b1} (m : expr \u2192 tactic expr) (t : tactic \u03b1) : tactic \u03b1 := do\n  let gs\n    \u2190-- Replace the goals with copies.\n      get_goals\n  let gs' \u2190 gs.mapM fun g => infer_type g >>= mk_meta_var\n  set_goals gs'\n  let a\n    \u2190-- Run the tactic on the copied goals.\n      t\n  (-- Run `m` on the produced terms,\n          gs\n          gs').mapM\n      fun \u27e8g, g'\u27e9 => do\n      let g' \u2190 instantiate_mvars g'\n      let g'' \u2190 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 {\u03b1} (t : tactic \u03b1) (cfg : DsimpConfig := { failIfUnchanged := false })\n    (no_defaults := false) (attr_names : List Name := []) (hs : List simp_arg_type := []) :\n    tactic \u03b1 :=\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 {\u03b1} (t : tactic \u03b1) (cfg : SimpConfig := { failIfUnchanged := false })\n    (discharger : tactic Unit := failed) (no_defaults := false) (attr_names : List Name := [])\n    (hs : List simp_arg_type := []) : tactic \u03b1 :=\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) 2020 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n-/\nimport data.nat.basic\nimport data.set.basic\nimport tactic.simp_rw\n\n/-!\n# Tests for `simp_rw` extensions\n-/\n\n-- `simp_rw` can perform rewrites under binders:\nexample : (\u03bb (x y : \u2115), x + y) = (\u03bb x y, y + x) := by simp_rw [add_comm]\n\n-- `simp_rw` can apply reverse rules:\nexample (f : \u2115 \u2192 \u2115) {a b c : \u2115} (ha : f b = a) (hc : f b = c) : a = c := by simp_rw [\u2190 ha, hc]\n\n-- `simp_rw` performs rewrites in the given order (`simp` fails on this example):\nexample {\u03b1 \u03b2 : Type} {f : \u03b1 \u2192 \u03b2} {t : set \u03b2} :\n  (\u2200 s, f '' s \u2286 t) = \u2200 s : set \u03b1, \u2200 x \u2208 s, x \u2208 f \u207b\u00b9' t :=\nby simp_rw [set.image_subset_iff, set.subset_def]\n\n-- `simp_rw` applies rewrite rules multiple times:\nexample (a b c d : \u2115) : a + (b + (c + d)) = ((d + c) + b) + a := by simp_rw [add_comm]\n\n-- `simp_rw` can also rewrite in assumptions:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h : p (a + b)) : p (b + a) :=\nby {simp_rw [add_comm a b] at h, exact h}\n-- or explicitly rewrite at the goal:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h : p (a + b)) : p (b + a) :=\nby {simp_rw [add_comm b a] at \u22a2, exact h}\n-- or at multiple assumptions:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h\u2081 : p (b + a) \u2192 p (a + b))  (h\u2082 : p (a + b)) : p (b + a) :=\nby {simp_rw [add_comm a b] at h\u2081 h\u2082, exact h\u2081 h\u2082}\n-- or everywhere:\nexample (p : \u2115 \u2192 Prop) (a b : \u2115) (h\u2081 : p (b + a) \u2192 p (a + b))  (h\u2082 : p (a + b)) : p (a + b) :=\nby {simp_rw [add_comm a b] at *, exact h\u2081 h\u2082}\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/simp_rw.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) 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\u00e4rn\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 \u27f6 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 \u2245 Y) \u2243 (X \u27f6 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\u2082 u u\u2082 -- 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       : \u03a0 {X Y : obj}, (X \u27f6 Y) \u2192 (Y \u27f6 X))\n(inv_comp' : \u2200 {X Y : obj} (f : X \u27f6 Y), comp (inv f) f = id Y . obviously)\n(comp_inv' : \u2200 {X Y : obj} (f : X \u27f6 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 \u27f6 Y) : is_iso f :=\n\u27e8\u27e8groupoid.inv f, groupoid.comp_inv f, groupoid.inv_comp f\u27e9\u27e9\n\n@[simp] \n\n/-- `groupoid.inv` is involutive. -/\n@[simps] def groupoid.inv_equiv : (X \u27f6 Y) \u2243 (Y \u27f6 X) :=\n\u27e8groupoid.inv, groupoid.inv, \u03bb f, by simp, \u03bb f, by simp\u27e9\n\n@[priority 100]\ninstance groupoid_has_involutive_reverse : quiver.has_involutive_reverse C :=\n{ reverse' := \u03bb X Y f, groupoid.inv f,\n  inv' := \u03bb X Y f, by { dsimp [quiver.reverse], simp, } }\n\n@[simp] lemma groupoid.reverse_eq_inv (f : X \u27f6 Y) : quiver.reverse f = groupoid.inv f := rfl\n\ninstance functor_map_reverse {D : Type*} [groupoid D] (F : C \u2964 D) :\n  F.to_prefunctor.map_reverse :=\n{ map_reverse' := \u03bb 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 \u2245 Y) \u2243 (X \u27f6 Y) :=\n{ to_fun := iso.hom,\n  inv_fun := \u03bb f, \u27e8f, groupoid.inv f\u27e9,\n  left_inv := \u03bb i, iso.ext rfl,\n  right_inv := \u03bb 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 \u2964 C\u1d52\u1d56 :=\n{ obj := opposite.op,\n  map := \u03bb {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 : \u2200 {X Y : C} (f : X \u27f6 Y), is_iso f) : groupoid.{v} C :=\n{ inv := \u03bb 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 : \u2200 {X Y : C}, unique (X \u27f6 Y)) : groupoid.{v} C :=\n{ inv := \u03bb X Y f, all_unique.default }\n\nend\n\ninstance induced_category.groupoid {C : Type u} (D : Type u\u2082) [groupoid.{v} D] (F : C \u2192 D) :\n   groupoid.{v} (induced_category D F) :=\n{ inv       := \u03bb X Y f, groupoid.inv f,\n  inv_comp' := \u03bb X Y f, groupoid.inv_comp f,\n  comp_inv' := \u03bb X Y f, groupoid.comp_inv f,\n  .. induced_category.category F }\n\nsection\n\ninstance groupoid_pi {I : Type u} {J : I \u2192 Type u\u2082} [\u2200 i, groupoid.{v} (J i)] :\n  groupoid.{max u v} (\u03a0 i : I, J i) :=\n{ inv := \u03bb (x y : \u03a0 i, J i) (f : \u03a0 i, x i \u27f6 y i), (\u03bb i : I, groupoid.inv (f i)), }\n\ninstance groupoid_prod {\u03b1 : Type u} {\u03b2 : Type v} [groupoid.{u\u2082} \u03b1] [groupoid.{v\u2082} \u03b2] :\n  groupoid.{max u\u2082 v\u2082} (\u03b1 \u00d7 \u03b2) :=\n{ inv := \u03bb (x y : \u03b1 \u00d7 \u03b2) (f : x \u27f6 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) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek\n\n! This file was ported from Lean 3 source module tactic.core\n! leanprover-community/mathlib commit 938f1f1b89b04dc15659cca28163f250d201d6a1\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Control.Basic\nimport Mathbin.Data.Dlist.Basic\nimport Mathbin.Meta.Expr\nimport Leanbin.System.Io\nimport Mathbin.Tactic.BinderMatching\nimport Mathbin.Tactic.InteractiveExpr\nimport Mathbin.Tactic.LeanCoreDocs\nimport Mathbin.Tactic.ProjectDir\n\nuniverse u\n\nderiving instance has_reflect, DecidableEq for Tactic.Transparency\n\n-- Rather than import data.prod.lex here, we can get away with defining the order by hand.\ninstance : LT Pos where lt x y := x.line < y.line \u2228 x.line = y.line \u2227 x.column < y.column\n\nnamespace Tactic\n\n/-- Reflexivity conversion: given `e` returns `(e, \u22a2 e = e)` -/\nunsafe def refl_conv (e : expr) : tactic (expr \u00d7 expr) := do\n  let p \u2190 mk_eq_refl e\n  return (e, p)\n#align tactic.refl_conv tactic.refl_conv\n\n/-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a\nproof by reflexivity. -/\nunsafe def or_refl_conv (tac : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) : tactic (expr \u00d7 expr) :=\n  tac e <|> refl_conv e\n#align tactic.or_refl_conv tactic.or_refl_conv\n\n/-- Transitivity conversion: given two conversions (which take an\nexpression `e` and returns `(e', \u22a2 e = e')`), produces another\nconversion that combines them with transitivity, treating failures\nas reflexivity conversions. -/\nunsafe def trans_conv (t\u2081 t\u2082 : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) : tactic (expr \u00d7 expr) :=\n  (do\n      let (e\u2081, p\u2081) \u2190 t\u2081 e\n      (do\n            let (e\u2082, p\u2082) \u2190 t\u2082 e\u2081\n            let p \u2190 mk_eq_trans p\u2081 p\u2082\n            return (e\u2082, p)) <|>\n          return (e\u2081, p\u2081)) <|>\n    t\u2082 e\n#align tactic.trans_conv tactic.trans_conv\n\nend Tactic\n\nopen Tactic\n\nnamespace Expr\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_nat \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`. -/\nprotected unsafe def of_nat (\u03b1 : expr) : \u2115 \u2192 tactic expr :=\n  Nat.binaryRec (tactic.mk_mapp `` Zero.zero [some \u03b1, none]) fun b n tac =>\n    if n = 0 then mk_mapp `` One.one [some \u03b1, none]\n    else do\n      let e \u2190 tac\n      tactic.mk_app (cond b `` bit1 `` bit0) [e]\n#align expr.of_nat expr.of_nat\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_int \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nprotected unsafe def of_int (\u03b1 : expr) : \u2124 \u2192 tactic expr\n  | (n : \u2115) => expr.of_nat \u03b1 n\n  | -[n+1] => do\n    let e \u2190 expr.of_nat \u03b1 (n + 1)\n    tactic.mk_app `` Neg.neg [e]\n#align expr.of_int expr.of_int\n\n/-- Convert a list of expressions to an expression denoting the list of those expressions. -/\nunsafe def of_list (\u03b1 : expr) : List expr \u2192 tactic expr\n  | [] => tactic.mk_app `` List.nil [\u03b1]\n  | x :: xs => do\n    let exs \u2190 of_list xs\n    tactic.mk_app `` List.cons [\u03b1, x, exs]\n#align expr.of_list expr.of_list\n\n/-- Generates an expression of the form `\u2203(args), inner`. `args` is assumed to be a list of local\nconstants. When possible, `p \u2227 q` is used instead of `\u2203(_ : p), q`. -/\nunsafe def mk_exists_lst (args : List expr) (inner : expr) : tactic expr :=\n  args.foldrM\n    (fun arg i : expr => do\n      let t \u2190 infer_type arg\n      let sort l \u2190 infer_type t\n      return <|\n          if arg i \u2228 l \u2260 level.zero then (const `Exists [l] : expr) t (i [arg])\n          else (const `and [] : expr) t i)\n    inner\n#align expr.mk_exists_lst expr.mk_exists_lst\n\n/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/\nunsafe def traverse {m : Type \u2192 Type u} [Applicative m] {elab elab' : Bool}\n    (f : expr elab \u2192 m (expr elab')) : expr elab \u2192 m (expr elab')\n  | var v => pure <| var v\n  | sort l => pure <| sort l\n  | const n ls => pure <| const n ls\n  | mvar n n' e => mvar n n' <$> f e\n  | local_const n n' bi e => local_const n n' bi <$> f e\n  | app e\u2080 e\u2081 => app <$> f e\u2080 <*> f e\u2081\n  | lam n bi e\u2080 e\u2081 => lam n bi <$> f e\u2080 <*> f e\u2081\n  | pi n bi e\u2080 e\u2081 => pi n bi <$> f e\u2080 <*> f e\u2081\n  | elet n e\u2080 e\u2081 e\u2082 => elet n <$> f e\u2080 <*> f e\u2081 <*> f e\u2082\n  | macro mac es => macro mac <$> List.traverse f es\n#align expr.traverse expr.traverse\n\n/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,\nwith initial value `a`. -/\nunsafe def mfoldl {\u03b1 : Type} {m} [Monad m] (f : \u03b1 \u2192 expr \u2192 m \u03b1) : \u03b1 \u2192 expr \u2192 m \u03b1\n  | x, e =>\n    Prod.snd <$>\n      (StateT.run (e.traverse fun e' => (get >>= monadLift \u2218 flip f e' >>= put) $> e') x : m _)\n#align expr.mfoldl expr.mfoldl\n\n/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`\nwith `new`. The occurrences of `old` in `e` are determined using keyed matching\nwith transparency `md`; see `kabstract` for details. If `unify` is true,\nwe may assign metavariables in `e` as we match subterms of `e` against `old`. -/\nunsafe def kreplace (e old new : expr) (md := semireducible) (unify := true) : tactic expr := do\n  let e \u2190 kabstract e old md unify\n  pure <| e new\n#align expr.kreplace expr.kreplace\n\nend Expr\n\nnamespace Name\n\n/-- `pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm`\nor (recusively) in any declarations occurring in the value of `nm` with namespace `pre`.\nAuxiliary function for `name.contains_sorry`. -/\nunsafe def contains_sorry_aux (pre : Name) : Name \u2192 tactic Bool\n  | nm => do\n    let env \u2190 get_env\n    let decl \u2190 get_decl nm\n    let ff \u2190 return decl.value.contains_sorry |\n      return true\n    (decl pre).mfold ff fun n b => if b then return tt else n\n#align name.contains_sorry_aux name.contains_sorry_aux\n\n/-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or\n  in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`).\n  See also `expr.contains_sorry`. -/\nunsafe def contains_sorry (nm : Name) : tactic Bool :=\n  nm.contains_sorry_aux nm\n#align name.contains_sorry name.contains_sorry\n\nend Name\n\nnamespace InteractionMonad\n\nopen Result\n\nvariable {\u03c3 : Type} {\u03b1 : Type u}\n\n-- Note that this is a generalization of `tactic.read` in core.\n/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/\nunsafe def get_state : interaction_monad \u03c3 \u03c3 := fun state => success StateM StateM\n#align interaction_monad.get_state interaction_monad.get_state\n\n-- Note that this is a generalization of `tactic.write` in core.\n/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/\nunsafe def set_state (state : \u03c3) : interaction_monad \u03c3 Unit := fun _ => success () StateM\n#align interaction_monad.set_state interaction_monad.set_state\n\n/-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result,\nsubsequently restoring the original state.\nIf `tac` fails, then `run_with_state` does too.\n-/\nunsafe def run_with_state (state : \u03c3) (tac : interaction_monad \u03c3 \u03b1) : interaction_monad \u03c3 \u03b1 :=\n  fun s =>\n  match tac StateM with\n  | success val _ => success val s\n  | exception fn Pos _ => exception fn Pos s\n#align interaction_monad.run_with_state interaction_monad.run_with_state\n\nend InteractionMonad\n\nnamespace Format\n\n/-- `join' [a,b,c]` produces the format object `abc`.\nIt differs from `format.join` by using `format.nil` instead of `\"\"` for the empty list. -/\nunsafe def join' (xs : List format) : format :=\n  xs.foldl compose nil\n#align format.join' format.join'\n\n/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,\nwhere `.` represents `format.join`. -/\nunsafe def intercalate (x : format) : List format \u2192 format :=\n  join' \u2218 List.intersperse x\n#align format.intercalate format.intercalate\n\n/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`\nthe result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`\neach line break is decided independently -/\nunsafe def soft_break : format :=\n  group line\n#align format.soft_break format.soft_break\n\n/-- Format a list as a comma separated list, without any brackets. -/\nunsafe def comma_separated {\u03b1 : Type _} [has_to_format \u03b1] : List \u03b1 \u2192 format\n  | [] => nil\n  | xs => group (nest 1 <| intercalate (\",\" ++ soft_break) <| xs.map to_fmt)\n#align format.comma_separated format.comma_separated\n\nend Format\n\nsection Format\n\nopen Format\n\n/-- format a `list` by separating elements with `soft_break` instead of `line` -/\nunsafe def list.to_line_wrap_format {\u03b1 : Type u} [has_to_format \u03b1] (l : List \u03b1) : format :=\n  bracket \"[\" \"]\" (comma_separated l)\n#align list.to_line_wrap_format list.to_line_wrap_format\n\nend Format\n\nnamespace Tactic\n\nopen Function\n\nexport InteractionMonad (get_state set_state run_with_state)\n\n/-- Private work function for `add_local_consts_as_local_hyps`: given\n    `mappings : list (expr \u00d7 expr)` corresponding to pairs `(var, hyp)` of variables and the local\n    hypothesis created as a result and `(var :: rest) : list expr` of more local variables we\n    examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the\n    back of the queue and recurse. If it does not, then we perform replacements inside the type of\n    `var` using the `mappings`, create a new associate local hypothesis, add this to the list of\n    mappings, and recurse. We are done once all local hypotheses have been processed.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\nprivate unsafe def add_local_consts_as_local_hyps_aux :\n    List (expr \u00d7 expr) \u2192 List expr \u2192 tactic (List (expr \u00d7 expr))\n  | mappings, [] => return mappings\n  | mappings, var :: rest => do\n    let-- Determine if `var` contains any local variables in the lift `rest`.\n    is_dependent := var.local_type.fold false fun e n b => if b then b else e \u2208 rest\n    -- If so, then skip it---add it to the end of the variable queue.\n        if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var])\n      else do\n        let/- Otherwise, replace all of the local constants referenced by the type of `var` with the\n               respective new corresponding local hypotheses as recorded in the list `mappings`. -/\n        new_type := var mappings\n        let hyp\n          \u2190-- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type.\n              assertv\n              var new_type (var new_type)\n        /- Process the next variable in the queue, with the mapping list updated to include the local\n                   hypothesis which we just created. -/\n            add_local_consts_as_local_hyps_aux\n            ((var, hyp) :: mappings) rest\n#align tactic.add_local_consts_as_local_hyps_aux tactic.add_local_consts_as_local_hyps_aux\n\n/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the\n    tactic state. This is harder than it sounds, since the list of local constants which we have\n    been passed can have dependencies between their types.\n\n    For example, suppose we have two local constants `n : \u2115` and `h : n = 3`. Then we cannot blindly\n    add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as\n    a new local hypothesis, not the old local constant `n` with the same name. Of course, these\n    dependencies can be nested arbitrarily deep.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\nunsafe def add_local_consts_as_local_hyps (vars : List expr) : tactic (List (expr \u00d7 expr)) :=\n  /- The `list.reverse` below is a performance optimisation since the list of available variables\n       reported by the system is often mostly the reverse of the order in which they are dependent. -/\n    add_local_consts_as_local_hyps_aux\n    [] vars.reverse.dedup\n#align tactic.add_local_consts_as_local_hyps tactic.add_local_consts_as_local_hyps\n\nprivate unsafe def get_expl_pi_arity_aux : expr \u2192 tactic Nat\n  | expr.pi n bi d b => do\n    let m \u2190 mk_fresh_name\n    let l := expr.local_const m n bi d\n    let new_b \u2190 whnf (expr.instantiate_var b l)\n    let r \u2190 get_expl_pi_arity_aux new_b\n    if bi = BinderInfo.default then return (r + 1) else return r\n  | e => return 0\n#align tactic.get_expl_pi_arity_aux tactic.get_expl_pi_arity_aux\n\n/-- Compute the arity of explicit arguments of `type`. -/\nunsafe def get_expl_pi_arity (type : expr) : tactic Nat :=\n  whnf type >>= get_expl_pi_arity_aux\n#align tactic.get_expl_pi_arity tactic.get_expl_pi_arity\n\n/-- Compute the arity of explicit arguments of `fn`'s type. -/\nunsafe def get_expl_arity (fn : expr) : tactic Nat :=\n  infer_type fn >>= get_expl_pi_arity\n#align tactic.get_expl_arity tactic.get_expl_arity\n\nprivate unsafe def get_app_fn_args_whnf_aux (md : Transparency) (unfold_ginductive : Bool) :\n    List expr \u2192 expr \u2192 tactic (expr \u00d7 List expr) := fun args e => do\n  let e \u2190 whnf e md unfold_ginductive\n  match e with\n    | expr.app t u => get_app_fn_args_whnf_aux (u :: args) t\n    | _ => pure (e, args)\n#align tactic.get_app_fn_args_whnf_aux tactic.get_app_fn_args_whnf_aux\n\n/-- For `e = f x\u2081 ... x\u2099`, `get_app_fn_args_whnf e` returns `(f, [x\u2081, ..., x\u2099])`. `e`\nis normalised as necessary; for example:\n\n```\nget_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])\n```\n\nThe returned expression is in whnf, but the arguments are generally not.\n-/\nunsafe def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := true) :\n    tactic (expr \u00d7 List expr) :=\n  get_app_fn_args_whnf_aux md unfold_ginductive [] e\n#align tactic.get_app_fn_args_whnf tactic.get_app_fn_args_whnf\n\n/-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is\nnormalised as necessary (with transparency `md`). `unfold_ginductive` controls\nwhether constructors of generalised inductive types are unfolded. The returned\nexpression is in whnf.\n-/\nunsafe def get_app_fn_whnf : expr \u2192 optParam _ semireducible \u2192 optParam _ true \u2192 tactic expr\n  | e, md, unfold_ginductive => do\n    let e \u2190 whnf e md unfold_ginductive\n    match e with\n      | expr.app f _ => get_app_fn_whnf f md unfold_ginductive\n      | _ => pure e\n#align tactic.get_app_fn_whnf tactic.get_app_fn_whnf\n\n/-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x\u2081 ... x\u2099`,\nwhere `C` is a constant, after normalisation with transparency `md`. If so, the\nname of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded.\n-/\nunsafe def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := true) :\n    tactic Name := do\n  let f \u2190 get_app_fn_whnf e md unfold_ginductive\n  match f with\n    | expr.const n _ => pure n\n    | _ =>\n      fail\n        f! \"expected a constant (possibly applied to some arguments), but got:\n          {e}\"\n#align tactic.get_app_fn_const_whnf tactic.get_app_fn_const_whnf\n\n/-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`\nis normalised as necessary (with transparency `md`). `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded. The\nreturned expressions are not necessarily in whnf.\n-/\nunsafe def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := true) :\n    tactic (List expr) :=\n  Prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive\n#align tactic.get_app_args_whnf tactic.get_app_args_whnf\n\n/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with pi binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``pis [a, b] `(f a b)`` will return the expression\n`\u03a0 (a : Ta) (b : Tb), f a b`. -/\nunsafe def pis : List expr \u2192 expr \u2192 tactic expr\n  | e@(expr.local_const uniq pp info _) :: es, f => do\n    let t \u2190 infer_type e\n    let f' \u2190 pis es f\n    pure <| expr.pi pp info t (expr.abstract_local f' uniq)\n  | _, f => pure f\n#align tactic.pis tactic.pis\n\n/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with lambda binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``lambdas [a, b] `(f a b)`` will return the expression\n`\u03bb (a : Ta) (b : Tb), f a b`. -/\nunsafe def lambdas : List expr \u2192 expr \u2192 tactic expr\n  | e@(expr.local_const uniq pp info _) :: es, f => do\n    let t \u2190 infer_type e\n    let f' \u2190 lambdas es f\n    pure <| expr.lam pp info t (expr.abstract_local f' uniq)\n  | _, f => pure f\n#align tactic.lambdas tactic.lambdas\n\n/-- Given an expression `f` (likely a binary operation) and a further expression `x`, calling\n`list_binary_operands f x` breaks `x` apart into successions of applications of `f` until this can\nno longer be done and returns a list of the leaves of the process.\n\nThis matches `f` up to semireducible unification. In particular, it will match applications of the\nsame polymorphic function with different type-class arguments.\n\nE.g., if `i1` and `i2` are both instances of `has_add T` and\n`e := has_add.add T i1 x (has_add.add T i2 y z)`, then ``list_binary_operands `((+) : T \u2192 T \u2192 T) e``\nreturns `[x, y, z]`.\n\nFor example:\n```lean\n#eval list_binary_operands `(@has_add.add \u2115 _) `(3 + (4 * 5 + 6) + 7 / 3) >>= tactic.trace\n-- [3, 4 * 5, 6, 7 / 3]\n#eval list_binary_operands `(@list.append \u2115) `([1, 2] ++ [3, 4] ++ (1 :: [])) >>= tactic.trace\n-- [[1, 2], [3, 4], [1]]\n```\n-/\nunsafe def list_binary_operands (f : expr) : expr \u2192 tactic (List expr)\n  | x@(expr.app (expr.app g a) b) => do\n    let some _ \u2190 try_core (unify f g) |\n      pure [x]\n    let as \u2190 list_binary_operands a\n    let bs \u2190 list_binary_operands b\n    pure (as ++ bs)\n  | a => pure [a]\n#align tactic.list_binary_operands tactic.list_binary_operands\n\n-- TODO: move to `declaration` namespace in `meta/expr.lean`\n/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named\n`ls`, type `t`, and body `e`. -/\nunsafe def mk_theorem (n : Name) (ls : List Name) (t : expr) (e : expr) : declaration :=\n  declaration.thm n ls t (task.pure e)\n#align tactic.mk_theorem tactic.mk_theorem\n\n/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this\nto the environment as a theorem with name `n` and universe parameters `ls`. -/\nunsafe def add_theorem_by (n : Name) (ls : List Name) (type : expr) (tac : tactic Unit) :\n    tactic expr := do\n  let ((), body) \u2190 solve_aux type tac\n  let body \u2190 instantiate_mvars body\n  add_decl <| mk_theorem n ls type body\n  return <| expr.const n <| ls level.param\n#align tactic.add_theorem_by tactic.add_theorem_by\n\n/-- `eval_expr' \u03b1 e` attempts to evaluate the expression `e` in the type `\u03b1`.\nThis is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare\nsituations the latter will fail but the former will succeed. -/\nunsafe def eval_expr' (\u03b1 : Type _) [reflected _ \u03b1] (e : expr) : tactic \u03b1 :=\n  mk_app `` id [e] >>= eval_expr \u03b1\n#align tactic.eval_expr' tactic.eval_expr'\n\n/-- `mk_fresh_name` returns identifiers starting with underscores,\nwhich are not legal when emitted by tactic programs. `mk_user_fresh_name`\nturns the useful source of random names provided by `mk_fresh_name` into\nnames which are usable by tactic programs.\n\nThe returned name has four components which are all strings. -/\nunsafe def mk_user_fresh_name : tactic Name := do\n  let nm \u2190 mk_fresh_name\n  return <| `user__ ++ nm ++ `user__\n#align tactic.mk_user_fresh_name tactic.mk_user_fresh_name\n\n/-- `has_attribute' attr_name decl_name` checks\nwhether `decl_name` exists and has attribute `attr_name`. -/\nunsafe def has_attribute' (attr_name decl_name : Name) : tactic Bool :=\n  succeeds (has_attribute attr_name decl_name)\n#align tactic.has_attribute' tactic.has_attribute'\n\n/-- Checks whether the name is a simp lemma -/\nunsafe def is_simp_lemma : Name \u2192 tactic Bool :=\n  has_attribute' `simp\n#align tactic.is_simp_lemma tactic.is_simp_lemma\n\n/-- Checks whether the name is an instance. -/\nunsafe def is_instance : Name \u2192 tactic Bool :=\n  has_attribute' `instance\n#align tactic.is_instance tactic.is_instance\n\n/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.\nCovers all declarations from the current file. -/\nunsafe def local_decls : tactic (name_map declaration) := do\n  let e \u2190 tactic.get_env\n  let xs :=\n    e.fold native.mk_rb_map fun d s =>\n      if environment.in_current_file e d.to_name then s.insert d.to_name d else s\n  pure xs\n#align tactic.local_decls tactic.local_decls\n\n/-- `get_decls_from` returns a dictionary mapping names to their\ncorresponding declarations.  Covers all declarations the files listed\nin `fs`, with the current file listed as `none`.\n\nThe path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present); e.g. `\"src/tactic/core.lean\"`\n\nPossible issue: `get_decls_from` uses `get_cwd`, the current working\ndirectory, which may not always point at the root of the project.\nIt would work better if it searched for the root directory or,\nbetter yet, if Lean exposed its path information.\n-/\nunsafe def get_decls_from (fs : List (Option String)) : tactic (name_map declaration) := do\n  let root \u2190 unsafe_run_io <| Io.Env.getCwd\n  let fs := fs.map (Option.map fun path => root ++ \"/\" ++ Path)\n  let err \u2190 unsafe_run_io <| (fs.filterMap id).filterM <| (\u00b7 <$> \u00b7) not \u2218 Io.Fs.fileExists\n  guard (err = []) <|> fail f! \"File not found: {err}\"\n  let e \u2190 tactic.get_env\n  let xs :=\n    e.fold native.mk_rb_map fun d s =>\n      let source := e.decl_olean d.to_name\n      if source \u2208 fs \u2227 (source = none \u2192 e.in_current_file d.to_name) then s.insert d.to_name d\n      else s\n  pure xs\n#align tactic.get_decls_from tactic.get_decls_from\n\n/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/\nunsafe def get_unused_decl_name_aux (e : environment) (nm : Name) : \u2115 \u2192 tactic Name\n  | n =>\n    let nm' := nm.appendSuffix (\"_\" ++ toString n)\n    if e.contains nm' then get_unused_decl_name_aux (n + 1) else return nm'\n#align tactic.get_unused_decl_name_aux tactic.get_unused_decl_name_aux\n\n/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it\nreturns that, otherwise it tries `nm_2`, `nm_3`, ... -/\nunsafe def get_unused_decl_name (nm : Name) : tactic Name :=\n  get_env >>= fun e => if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm\n#align tactic.get_unused_decl_name tactic.get_unused_decl_name\n\n/-- Returns a pair `(e, t)`, where `e \u2190 mk_const d.to_name`, and `t = d.type`\nbut with universe params updated to match the fresh universe metavariables in `e`.\n\nThis should have the same effect as just\n```lean\ndo e \u2190 mk_const d.to_name,\n   t \u2190 infer_type e,\n   return (e, t)\n```\nbut is hopefully faster.\n-/\nunsafe def decl_mk_const (d : declaration) : tactic (expr \u00d7 expr) := do\n  let subst \u2190 d.univ_params.mapM fun u => Prod.mk u <$> mk_meta_univ\n  let e : expr := expr.const d.to_name (Prod.snd <$> subst)\n  return (e, d subst)\n#align tactic.decl_mk_const tactic.decl_mk_const\n\n/-- Replace every universe metavariable in an expression with a universe parameter.\n\n(This is useful when making new declarations.)\n-/\nunsafe def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do\n  e fun n => do\n      let n' := `u.appendSuffix (\"_\" ++ toString (n.1 + 1))\n      unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))\n  instantiate_mvars e\n#align tactic.replace_univ_metas_with_univ_params tactic.replace_univ_metas_with_univ_params\n\n/-- `mk_local n` creates a dummy local variable with name `n`.\nThe type of this local constant is a constant with name `n`, so it is very unlikely to be\na meaningful expression. -/\nunsafe def mk_local (n : Name) : expr :=\n  expr.local_const n n BinderInfo.default (expr.const n [])\n#align tactic.mk_local tactic.mk_local\n\n/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,\n`y : ty x` and `z : tz x y`, creates an expression of sigma type:\n`\u27e8x,y,z\u27e9 : \u03a3' (x : tx) (y : ty x), tz x y`.\n-/\nunsafe def mk_psigma : List expr \u2192 tactic expr\n  | [] => mk_const `` PUnit\n  | [x@(expr.local_const _ _ _ _)] => pure x\n  | x@(expr.local_const _ _ _ _) :: xs => do\n    let y \u2190 mk_psigma xs\n    let \u03b1 \u2190 infer_type x\n    let \u03b2 \u2190 infer_type y\n    let t \u2190 lambdas [x] \u03b2 >>= instantiate_mvars\n    let r \u2190 mk_mapp `` PSigma.mk [\u03b1, t]\n    pure <| r x y\n  | _ => fail \"mk_psigma expects a list of local constants\"\n#align tactic.mk_psigma tactic.mk_psigma\n\n/-- Update the type of a local constant or metavariable. For local constants and\nmetavariables obtained via, for example, `tactic.get_local`, the type stored in\nthe expression is not necessarily the same as the type returned by `infer_type`.\nThis tactic, given a local constant or metavariable, updates the stored type to\nmatch the output of `infer_type`. If the input is not a local constant or\nmetavariable, `update_type` does nothing.\n-/\nunsafe def update_type : expr \u2192 tactic expr\n  | e@(expr.local_const ppname uname binfo _) =>\n    expr.local_const ppname uname binfo <$> infer_type e\n  | e@(expr.mvar ppname uname _) => expr.mvar ppname uname <$> infer_type e\n  | e => pure e\n#align tactic.update_type tactic.update_type\n\n/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`\ntimes and uses `ns` to name the resulting variables. Returns a triple: list of new variables,\nremaining term and unused variable names.\n-/\nunsafe def elim_gen_prod :\n    Nat \u2192 expr \u2192 List expr \u2192 List Name \u2192 tactic (List expr \u00d7 expr \u00d7 List Name)\n  | 0, e, hs, ns => return (hs.reverse, e, ns)\n  | n + 1, e, hs, ns => do\n    let t \u2190 infer_type e\n    if t `eq then return (hs, e, ns)\n      else do\n        let [(_, [h, h'], _)] \u2190 cases_core e (ns 1)\n        elim_gen_prod n h' (h :: hs) (ns 1)\n#align tactic.elim_gen_prod tactic.elim_gen_prod\n\nprivate unsafe def elim_gen_sum_aux : Nat \u2192 expr \u2192 List expr \u2192 tactic (List expr \u00d7 expr)\n  | 0, e, hs => return (hs, e)\n  | n + 1, e, hs => do\n    let [(_, [h], _), (_, [h'], _)] \u2190 induction e []\n    swap\n    elim_gen_sum_aux n h' (h :: hs)\n#align tactic.elim_gen_sum_aux tactic.elim_gen_sum_aux\n\n/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose\ntype is a (nested) sum `\u2295`. Returns the list of local constants representing the components of `e`.\n-/\nunsafe def elim_gen_sum (n : Nat) (e : expr) : tactic (List expr) := do\n  let (hs, h') \u2190 elim_gen_sum_aux n e []\n  let gs \u2190 get_goals\n  set_goals <| (gs (n + 1)).reverse ++ gs (n + 1)\n  return <| hs ++ [h']\n#align tactic.elim_gen_sum tactic.elim_gen_sum\n\n/-- Given `elab_def`, a tactic to solve the current goal,\n`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it\nto close the goal. If `trusted` is false, it will be a meta definition. -/\nunsafe def extract_def (n : Name) (trusted : Bool) (elab_def : tactic Unit) : tactic Unit := do\n  let cxt \u2190 List.map expr.to_implicit_local_const <$> local_context\n  let t \u2190 target\n  let (eqns, d) \u2190 solve_aux t elab_def\n  let d \u2190 instantiate_mvars d\n  let t' \u2190 pis cxt t\n  let d' \u2190 lambdas cxt d\n  let univ := t'.collect_univ_params\n  add_decl <| declaration.defn n univ t' d' (ReducibilityHints.regular 1 tt) trusted\n  applyc n\n#align tactic.extract_def tactic.extract_def\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/-- Attempts to close the goal with `dec_trivial`. -/\nunsafe def exact_dec_trivial : tactic Unit :=\n  sorry\n#align tactic.exact_dec_trivial tactic.exact_dec_trivial\n\n/-- Runs a tactic for a result, reverting the state after completion. -/\nunsafe def retrieve {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 := fun s =>\n  result.cases_on (tac s) (fun a s' => result.success a s) result.exception\n#align tactic.retrieve tactic.retrieve\n\n/-- Runs a tactic for a result, reverting the state after completion or error. -/\nunsafe def retrieve' {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 := fun s =>\n  result.cases_on (tac s) (fun a s' => result.success a s) fun msg pos s' =>\n    result.exception msg Pos s\n#align tactic.retrieve' tactic.retrieve'\n\n/-- Repeat a tactic at least once, calling it recursively on all subgoals,\nuntil it fails. This tactic fails if the first invocation fails. -/\nunsafe def repeat1 (t : tactic Unit) : tactic Unit :=\n  andthen t (repeat t)\n#align tactic.repeat1 tactic.repeat1\n\n/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and\nat most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/\nunsafe def iterate_range : \u2115 \u2192 \u2115 \u2192 tactic Unit \u2192 tactic Unit\n  | 0, 0, t => skip\n  | 0, n + 1, t => try (t >> iterate_range 0 n t)\n  | m + 1, n, t => t >> iterate_range m (n - 1) t\n#align tactic.iterate_range tactic.iterate_range\n\n/-- Given a tactic `tac` that takes an expression\nand returns a new expression and a proof of equality,\nuse that tactic to change the type of the hypotheses listed in `hs`,\nas well as the goal if `tgt = tt`.\n\nReturns `tt` if any types were successfully changed.\n-/\nunsafe def replace_at (tac : expr \u2192 tactic (expr \u00d7 expr)) (hs : List expr) (tgt : Bool) :\n    tactic Bool := do\n  let to_remove \u2190\n    hs.filterM fun h => do\n        let h_type \u2190 infer_type h\n        succeeds do\n            let (new_h_type, pr) \u2190 tac h_type\n            assert h new_h_type\n            mk_eq_mp pr h >>= tactic.exact\n  let goal_simplified \u2190\n    succeeds do\n        guard tgt\n        let (new_t, pr) \u2190 target >>= tac\n        replace_target new_t pr\n  to_remove fun h => try (clear h)\n  return (\u00acto_remove \u2228 goal_simplified)\n#align tactic.replace_at tactic.replace_at\n\n/-- `revert_after e` reverts all local constants after local constant `e`. -/\nunsafe def revert_after (e : expr) : tactic \u2115 := do\n  let l \u2190 local_context\n  let [Pos] \u2190 return <| l.indexesOf e |\n    pp e >>= fun s => fail f! \"No such local constant {s}\"\n  let l := l.drop Pos.succ\n  -- all local hypotheses after `e`\n      revert_lst\n      l\n#align tactic.revert_after tactic.revert_after\n\n/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).\n  Returns the number of local constants that have been reverted. -/\nunsafe def revert_target_deps : tactic \u2115 := do\n  let tgt \u2190 target\n  let ctx \u2190 local_context\n  let l \u2190 ctx.filterM (kdepends_on tgt)\n  let n \u2190 revert_lst l\n  if l = [] then return n\n    else do\n      let m \u2190 revert_target_deps\n      return (m + n)\n#align tactic.revert_target_deps tactic.revert_target_deps\n\n/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant\nwith name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.\n\n`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the\ngoal, in which case it just calls `assert`.\nIn contrast to `generalize` it already introduces the generalized variable. -/\nunsafe def generalize' (e : expr) (n : Name) : tactic expr :=\n  generalize e n >> intro n <|> note n none e\n#align tactic.generalize' tactic.generalize'\n\n/-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name\nprovided by the binder to name the new local constant.\nUnlike `intron`, it does not rename introduced constants if the names shadow existing constants.\n-/\nunsafe def intron_no_renames : \u2115 \u2192 tactic Unit\n  | 0 => pure ()\n  | n + 1 => do\n    let expr.pi pp_n _ _ _ \u2190 target\n    intro pp_n\n    intron_no_renames n\n#align tactic.intron_no_renames tactic.intron_no_renames\n\n/-- `get_univ_level t` returns the universe level of a type `t` -/\nunsafe def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := true) :\n    tactic level := do\n  let expr.sort u \u2190 infer_type t >>= fun s => whnf s md unfold_ginductive |\n    fail \"get_univ_level: argument is not a type\"\n  return u\n#align tactic.get_univ_level tactic.get_univ_level\n\n/-!\n### Various tactics related to local definitions (local constants of the form `x : \u03b1 := t`)\n\nWe call `t` the value of `x`.\n-/\n\n\n/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined\n  locally using a `let` expression. Otherwise it fails. -/\nunsafe def local_def_value (e : expr) : tactic expr :=\n  pp e >>= fun s =>\n    -- running `pp` here, because we cannot access it in the `type_context` monad.\n      tactic.unsafe.type_context.run\n      do\n      let lctx \u2190 tactic.unsafe.type_context.get_local_context\n      let some ldecl \u2190 return <| lctx.get_local_decl e.local_uniq_name |\n        tactic.unsafe.type_context.fail f! \"No such hypothesis {s}.\"\n      let some let_val \u2190 return ldecl.value |\n        tactic.unsafe.type_context.fail f! \"Variable {e} is not a local definition.\"\n      return let_val\n#align tactic.local_def_value tactic.local_def_value\n\n/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form\n`e : \u03b1 := t`) and otherwise fails. -/\nunsafe def is_local_def (e : expr) : tactic Unit := do\n  let ctx \u2190 unsafe.type_context.get_local_context.run\n  let some decl \u2190 pure <| ctx.get_local_decl e.local_uniq_name |\n    fail f! \"is_local_def: {e} is not a local constant\"\n  when decl <| fail f! \"is_local_def: {e} is not a local definition\"\n#align tactic.is_local_def tactic.is_local_def\n\n/-- Returns the local definitions from the context. A local definition is a\nlocal constant of the form `e : \u03b1 := t`. The local definitions are returned in\nthe order in which they appear in the context. -/\nunsafe def local_defs : tactic (List expr) := do\n  let ctx \u2190 unsafe.type_context.get_local_context.run\n  let ctx' \u2190 local_context\n  ctx' fun h => do\n      let some decl \u2190 pure <| ctx h |\n        fail f! \"local_defs: local {h} not found in the local context\"\n      pure decl\n#align tactic.local_defs tactic.local_defs\n\n/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`\n(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.\nwhereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes\nthem in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition\nrunning up to the first match. -/\nprivate def partition_local_deps_aux {\u03b1} [DecidableEq \u03b1] (vs : List \u03b1) :\n    List \u03b1 \u2192 List \u03b1 \u2192 List (List \u03b1)\n  | [], Acc => [Acc.reverse]\n  | l :: ls, Acc =>\n    if l \u2208 vs then Acc.reverse :: partition_local_deps_aux ls [l]\n    else partition_local_deps_aux ls (l :: Acc)\n#align tactic.partition_local_deps_aux tactic.partition_local_deps_aux\n\n/-- `partition_local_deps vs`, with `vs` a list of local constants,\nreorders `vs` in the order they appear in the local context together\nwith the variables that follow them. If local context is `[a,b,c,d,e,f]`,\nand that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.\nThe head of each list is one of the variables given as a parameter. -/\nunsafe def partition_local_deps (vs : List expr) : tactic (List (List expr)) := do\n  let ls \u2190 local_context\n  pure (partition_local_deps_aux vs ls []).tail.reverse\n#align tactic.partition_local_deps tactic.partition_local_deps\n\n/-- `clear_value [e\u2080, e\u2081, e\u2082, ...]` clears the body of the local definitions `e\u2080`, `e\u2081`, `e\u2082`, ...\nchanging them into regular hypotheses. A hypothesis `e : \u03b1 := t` is changed to `e : \u03b1`. The order of\nlocals `e\u2080`, `e\u2081`, `e\u2082` does not matter as a permutation will be chosen so as to preserve type\ncorrectness. This tactic is called `clearbody` in Coq. -/\nunsafe def clear_value (vs : List expr) : tactic Unit := do\n  let ls \u2190 partition_local_deps vs\n  ls fun vs => do\n      revert_lst vs\n      let expr.elet v t d b \u2190 target |\n        fail f! \"Cannot clear the body of {vs}. It is not a local definition.\"\n      let e := expr.pi v BinderInfo.default t b\n      type_check e <|>\n          fail f! \"Cannot clear the body of {vs}. The resulting goal is not type correct.\"\n      let g \u2190 mk_meta_var e\n      let h \u2190 note `h none g\n      tactic.exact <| h d\n      let gs \u2190 get_goals\n      set_goals <| g :: gs\n  ls fun vs => intro_lst <| vs expr.local_pp_name\n#align tactic.clear_value tactic.clear_value\n\n/-- `context_has_local_def` is true iff there is at least one local definition in\nthe context.\n-/\nunsafe def context_has_local_def : tactic Bool := do\n  let ctx \u2190 local_context\n  ctx (succeeds \u2218 local_def_value)\n#align tactic.context_has_local_def tactic.context_has_local_def\n\n/-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the\ncontext up to and including `h` is a local definition.\n-/\nunsafe def context_upto_hyp_has_local_def (h : expr) : tactic Bool := do\n  let ff \u2190 succeeds (local_def_value h) |\n    pure true\n  let ctx \u2190 local_context\n  let ctx := ctx.takeWhile (\u00b7 \u2260 h)\n  ctx (succeeds \u2218 local_def_value)\n#align tactic.context_upto_hyp_has_local_def tactic.context_upto_hyp_has_local_def\n\n/-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\nIf `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and\nsubstitute `t` for `h`.\n\nThis is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a\nlocal definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nunsafe def subst' (h : expr) : tactic Unit := do\n  let e \u2190\n    do\n      let t\n        \u2190-- we first find the variable being substituted away\n            infer_type\n            h\n      let (f, args) := t.get_app_fn_args\n      if f = `eq \u2228 f = `heq then do\n          let lhs := args 1\n          let rhs := args\n          if rhs then return rhs\n            else\n              if lhs then return lhs\n              else\n                fail\n                  \"subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x).\"\n        else return h\n  success_if_fail (is_local_def e) <|>\n      fail\n        f! \"Cannot substitute variable {e}, it is a local definition. If you really want to do this, use `clear_value` first.\"\n  subst h\n#align tactic.subst' tactic.subst'\n\n/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,\n`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting\nexpression and a proof of equality. -/\nunsafe def simp_bottom_up' (post : expr \u2192 tactic (expr \u00d7 expr)) (e : expr)\n    (cfg : SimpConfig := { }) : tactic (expr \u00d7 expr) :=\n  Prod.snd <$> simplify_bottom_up () (fun _ => (\u00b7 <$> \u00b7) (Prod.mk ()) \u2218 post) e cfg\n#align tactic.simp_bottom_up' tactic.simp_bottom_up'\n\n/-- Caches unary type classes on a type `\u03b1 : Type.{univ}`. -/\nunsafe structure instance_cache where\n  \u03b1 : expr\n  univ : level\n  inst : name_map expr\n#align tactic.instance_cache tactic.instance_cache\n\n/-- Creates an `instance_cache` for the type `\u03b1`. -/\nunsafe def mk_instance_cache (\u03b1 : expr) : tactic instance_cache := do\n  let u \u2190 mk_meta_univ\n  infer_type \u03b1 >>= unify (expr.sort (level.succ u))\n  let u \u2190 get_univ_assignment u\n  return \u27e8\u03b1, u, mk_name_map\u27e9\n#align tactic.mk_instance_cache tactic.mk_instance_cache\n\nnamespace InstanceCache\n\n/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of\n`n c.\u03b1` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance\nvia type class resolution, and updates the cache. -/\nunsafe def get (c : instance_cache) (n : Name) : tactic (instance_cache \u00d7 expr) :=\n  match c.inst.find n with\n  | some i => return (c, i)\n  | none => do\n    let e \u2190 mk_app n [c.\u03b1] >>= mk_instance\n    return (\u27e8c, c, c n e\u27e9, e)\n#align tactic.instance_cache.get tactic.instance_cache.get\n\nopen Expr\n\n/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,\n`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/\nunsafe def append_typeclasses :\n    expr \u2192 instance_cache \u2192 List expr \u2192 tactic (instance_cache \u00d7 List expr)\n  | pi _ BinderInfo.inst_implicit (app (const n _) (var _)) body, c, l => do\n    let (c, p) \u2190 c.get n\n    return (c, p :: l)\n  | _, c, l => return (c, l)\n#align tactic.instance_cache.append_typeclasses tactic.instance_cache.append_typeclasses\n\n/-- Creates the application `n c.\u03b1 p l`, where `p` is a type class instance found in the cache `c`.\n-/\nunsafe def mk_app (c : instance_cache) (n : Name) (l : List expr) :\n    tactic (instance_cache \u00d7 expr) := do\n  let d \u2190 get_decl n\n  let (c, l) \u2190 append_typeclasses d.type.binding_body c l\n  return (c, (expr.const n [c]).mk_app (c :: l))\n#align tactic.instance_cache.mk_app tactic.instance_cache.mk_app\n\n/-- `c.of_nat n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`. -/\nprotected unsafe def of_nat (c : instance_cache) (n : \u2115) : tactic (instance_cache \u00d7 expr) :=\n  if n = 0 then c.mk_app `` Zero.zero []\n  else do\n    let (c, ai) \u2190 c.get `` Add\n    let (c, oi) \u2190 c.get `` One\n    let (c, one) \u2190 c.mk_app `` One.one []\n    return\n        (c,\n          n one fun b n e =>\n            if n = 0 then one\n            else\n              cond b ((expr.const `` bit1 [c]).mk_app [c, oi, ai, e])\n                ((expr.const `` bit0 [c]).mk_app [c, ai, e]))\n#align tactic.instance_cache.of_nat tactic.instance_cache.of_nat\n\n/-- `c.of_int n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nprotected unsafe def of_int (c : instance_cache) : \u2124 \u2192 tactic (instance_cache \u00d7 expr)\n  | (n : \u2115) => c.ofNat n\n  | -[n+1] => do\n    let (c, e) \u2190 c.ofNat (n + 1)\n    c `` Neg.neg [e]\n#align tactic.instance_cache.of_int tactic.instance_cache.of_int\n\nend InstanceCache\n\n/-- A variation on `assert` where a (possibly incomplete)\nproof of the assertion is provided as a parameter.\n\n``(h,gs) \u2190 local_proof `h p tac`` creates a local `h : p` and\nuse `tac` to (partially) construct a proof for it. `gs` is the\nlist of remaining goals in the proof of `h`.\n\nThe benefits over assert are:\n- unlike with ``h \u2190 assert `h p, tac`` , `h` cannot be used by `tac`;\n- when `tac` does not complete the proof of `h`, returning the list\n  of goals allows one to write a tactic using `h` and with the confidence\n  that a proof will not boil over to goals left over from the proof of `h`,\n  unlike what would be the case when using `tactic.swap`.\n-/\nunsafe def local_proof (h : Name) (p : expr) (tac\u2080 : tactic Unit) : tactic (expr \u00d7 List expr) :=\n  focus1 do\n    let h' \u2190 assert h p\n    let [g\u2080, g\u2081] \u2190 get_goals\n    set_goals [g\u2080]\n    tac\u2080\n    let gs \u2190 get_goals\n    set_goals [g\u2081]\n    return (h', gs)\n#align tactic.local_proof tactic.local_proof\n\n/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/\nunsafe def var_names : expr \u2192 List Name\n  | expr.pi n _ _ b => n :: var_names b\n  | _ => []\n#align tactic.var_names tactic.var_names\n\n/-- When `struct_n` is the name of a structure type,\n`subobject_names struct_n` returns two lists of names `(instances, fields)`.\nThe names in `instances` are the projections from `struct_n` to the structures that it extends\n(assuming it was defined with `old_structure_cmd false`).\nThe names in `fields` are the standard fields of `struct_n`. -/\nunsafe def subobject_names (struct_n : Name) : tactic (List Name \u00d7 List Name) := do\n  let env \u2190 get_env\n  let c \u2190\n    match env.constructors_of struct_n with\n      | [c] => pure c\n      | [] =>\n        if env.is_inductive struct_n then fail f! \"{struct_n} does not have constructors\"\n        else fail f! \"{struct_n} is not an inductive type\"\n      | _ => fail \"too many constructors\"\n  let vs \u2190 var_names <$> (mk_const c >>= infer_type)\n  let fields \u2190 env.structure_fields struct_n\n  return <| fields fun fn => \u2191(\"_\" ++ fn) \u2208 vs\n#align tactic.subobject_names tactic.subobject_names\n\nprivate unsafe def expanded_field_list' : Name \u2192 tactic (Dlist <| Name \u00d7 Name)\n  | struct_n => do\n    let (so, fs) \u2190 subobject_names struct_n\n    let ts \u2190\n      so.mapM fun n => do\n          let (_, e) \u2190 mk_const (n.updatePrefix struct_n) >>= infer_type >>= open_pis\n          expanded_field_list' <| e\n    return <| Std.DList.join ts ++ Dlist.ofList (fs <| Prod.mk struct_n)\n#align tactic.expanded_field_list' tactic.expanded_field_list'\n\nopen Functor Function\n\n/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure\nnamed `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name\nof the projection is `prefix.name`.\n\n`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/\nunsafe def expanded_field_list (struct_n : Name) : tactic (List <| Name \u00d7 Name) :=\n  Dlist.toList <$> expanded_field_list' struct_n\n#align tactic.expanded_field_list tactic.expanded_field_list\n\n/-- Return a list of all type classes which can be instantiated\nfor the given expression.\n-/\nunsafe def get_classes (e : expr) : tactic (List Name) :=\n  attribute.get_instances `class >>= List.filterM fun n => succeeds <| mk_app n [e] >>= mk_instance\n#align tactic.get_classes tactic.get_classes\n\n/-- Finds an instance of an implication `cond \u2192 tgt`.\nReturns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention\n`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,\nsince it has been \"proven\" by a metavariable.\n-/\nunsafe def mk_conditional_instance (cond tgt : expr) : tactic (expr \u00d7 expr) := do\n  let f \u2190 mk_meta_var cond\n  let e \u2190 assertv `c cond f\n  swap\n  reset_instance_cache\n  let inst \u2190 mk_instance tgt\n  return (e, inst)\n#align tactic.mk_conditional_instance tactic.mk_conditional_instance\n\nopen Nat\n\n/-- Create a list of `n` fresh metavariables. -/\nunsafe def mk_mvar_list : \u2115 \u2192 tactic (List expr)\n  | 0 => pure []\n  | succ n => (\u00b7 :: \u00b7) <$> mk_mvar <*> mk_mvar_list n\n#align tactic.mk_mvar_list tactic.mk_mvar_list\n\n/-- Returns the only goal, or fails if there isn't just one goal. -/\nunsafe def get_goal : tactic expr := do\n  let gs \u2190 get_goals\n  match gs with\n    | [a] => return a\n    | [] => fail \"there are no goals\"\n    | _ => fail \"there are too many goals\"\n#align tactic.get_goal tactic.get_goal\n\n/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,\nor until it fails. Always succeeds. -/\nunsafe def iterate_at_most_on_all_goals : Nat \u2192 tactic Unit \u2192 tactic Unit\n  | 0, tac => trace \"maximal iterations reached\"\n  | succ n, tac =>\n    tactic.all_goals' <|\n      (do\n          tac\n          iterate_at_most_on_all_goals n tac) <|>\n        skip\n#align tactic.iterate_at_most_on_all_goals tactic.iterate_at_most_on_all_goals\n\n/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first\ngoal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on\ncurrent goal. -/\nunsafe def iterate_at_most_on_subgoals : Nat \u2192 tactic Unit \u2192 tactic Unit\n  | 0, tac => trace \"maximal iterations reached\"\n  | succ n, tac =>\n    focus1 do\n      tac\n      iterate_at_most_on_all_goals n tac\n#align tactic.iterate_at_most_on_subgoals tactic.iterate_at_most_on_subgoals\n\n/-- This makes sure that the execution of the tactic does not change the tactic state.\nThis can be helpful while using rewrite, apply, or expr munging.\nRemember to instantiate your metavariables before you're done! -/\nunsafe def lock_tactic_state {\u03b1} (t : tactic \u03b1) : tactic \u03b1\n  | s =>\n    match t s with\n    | result.success a s' => result.success a s\n    | result.exception msg Pos s' => result.exception msg Pos s\n#align tactic.lock_tactic_state tactic.lock_tactic_state\n\n/-- `apply_list l`, for `l : list (tactic expr)`,\ntries to apply one of the lemmas generated by the tactics in `l` to the first goal, and\nfail if none succeeds.\n-/\nunsafe def apply_list_expr (opt : ApplyCfg) : List (tactic expr) \u2192 tactic Unit\n  | [] => fail \"no matching rule\"\n  | h :: t =>\n    (do\n        let e \u2190 h\n        interactive.concat_tags (apply e opt)) <|>\n      apply_list_expr t\n#align tactic.apply_list_expr tactic.apply_list_expr\n\n/-- Given the name of a user attribute, produces a list of `tactic expr`s, each of which is the\napplication of `i_to_expr_for_apply` to a declaration with that attribute.\n-/\nunsafe def resolve_attribute_expr_list (attr_name : Name) : tactic (List (tactic expr)) := do\n  let l \u2190 attribute.get_instances attr_name\n  List.map i_to_expr_for_apply <$>\n      List.reverse <$>\n        l fun n => do\n          let c \u2190 mk_const n\n          return (pexpr.of_expr c)\n#align tactic.resolve_attribute_expr_list tactic.resolve_attribute_expr_list\n\n/-- `apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given\nas names of attributes) and the tactic `assumption` on the first goal and the resulting subgoals,\niteratively, at most `n` times.\n\nUnlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies\na lemma from the list until it can't.\n -/\nunsafe def apply_rules (args : List pexpr) (attrs : List Name) (n : Nat) (opt : ApplyCfg) :\n    tactic Unit := do\n  let attr_exprs \u2190\n    lock_tactic_state <|\n        attrs.foldlM (fun l n => List.append l <$> resolve_attribute_expr_list n) []\n  let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs\n  -- `args_exprs` is a list of `tactic expr`, rather than just `expr`, because these expressions will\n      -- be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.\n      iterate_at_most_on_subgoals\n      n (assumption <|> apply_list_expr opt args_exprs)\n#align tactic.apply_rules tactic.apply_rules\n\n/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local\ncontext, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.\nFails if there is nothing named `h` in the local context. -/\nunsafe def replace (h : Name) (p : pexpr) : tactic Unit := do\n  let h' \u2190 get_local h\n  let p \u2190 to_expr p\n  note h none p\n  clear h'\n#align tactic.replace tactic.replace\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n      Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``\n      or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an\n      `iff`, returns an expression with the `iff` converted to either the forwards or backwards\n      implication, as requested. -/\n    unsafe\n  def\n    mk_iff_mp_app\n    ( iffmp : Name ) : expr \u2192 ( Nat \u2192 expr ) \u2192 Option expr\n    |\n        expr.pi n bi e t , f\n        =>\n        expr.lam n bi e <$> mk_iff_mp_app t fun n => f ( n + 1 ) ( expr.var n )\n      | q( $ ( a ) \u2194 $ ( b ) ) , f => some <| @ expr.const true iffmp [ ] a b ( f 0 )\n      | _ , f => none\n#align tactic.mk_iff_mp_app tactic.mk_iff_mp_app\n\n/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., A \u2192 B`. -/\nunsafe def iff_mp_core (e ty : expr) : Option expr :=\n  mk_iff_mp_app `iff.mp ty fun _ => e\n#align tactic.iff_mp_core tactic.iff_mp_core\n\n/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., B \u2192 A`. -/\nunsafe def iff_mpr_core (e ty : expr) : Option expr :=\n  mk_iff_mp_app `iff.mpr ty fun _ => e\n#align tactic.iff_mpr_core tactic.iff_mpr_core\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the forward implication. -/\nunsafe def iff_mp (e : expr) : tactic expr := do\n  let t \u2190 infer_type e\n  iff_mp_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n#align tactic.iff_mp tactic.iff_mp\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the reverse implication. -/\nunsafe def iff_mpr (e : expr) : tactic expr := do\n  let t \u2190 infer_type e\n  iff_mpr_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n#align tactic.iff_mpr tactic.iff_mpr\n\n/-- Attempts to apply `e`, and if that fails, if `e` is an `iff`,\ntry applying both directions separately.\n-/\nunsafe def apply_iff (e : expr) : tactic (List (Name \u00d7 expr)) :=\n  let ap (e) := tactic.apply e { NewGoals := NewGoals.non_dep_only }\n  ap e <|> iff_mp e >>= ap <|> iff_mpr e >>= ap\n#align tactic.apply_iff tactic.apply_iff\n\n/-- Configuration options for `apply_any`:\n* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.\n* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.\n* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.\n-/\nunsafe structure apply_any_opt extends ApplyCfg where\n  use_symmetry : Bool := true\n  use_exfalso : Bool := true\n#align tactic.apply_any_opt tactic.apply_any_opt\n\n/-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,\nand evaluates these as thunks before trying to apply them.\n\nWe need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.\n-/\nunsafe def apply_any_thunk (lemmas : List (tactic expr)) (opt : apply_any_opt := { })\n    (tac : tactic Unit := skip) (on_success : expr \u2192 tactic Unit := fun _ => skip)\n    (on_failure : tactic Unit := skip) : tactic Unit := do\n  let modes :=\n    ([skip] ++ if opt.use_symmetry then [symmetry] else []) ++\n      if opt.use_exfalso then [exfalso] else []\n  (modes fun m => do\n        m\n        lemmas fun H =>\n            H >>= fun e => do\n              apply e opt\n              on_success e\n              tac) <|>\n      on_failure >> fail \"apply_any tactic failed; no lemma could be applied\"\n#align tactic.apply_any_thunk tactic.apply_any_thunk\n\n/-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.\n\n`apply_any lemmas opt` allows control over how lemmas are applied.\n`opt` has fields:\n* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)\n* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)\n* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).\n\n`apply_any lemmas tac` calls the tactic `tac` after a successful application.\nDefaults to `skip`. This is used, for example, by `solve_by_elim` to arrange\nrecursive invocations of `apply_any`.\n-/\nunsafe def apply_any (lemmas : List expr) (opt : apply_any_opt := { }) (tac : tactic Unit := skip) :\n    tactic Unit :=\n  apply_any_thunk (lemmas.map pure) opt tac\n#align tactic.apply_any tactic.apply_any\n\n/-- Try to apply a hypothesis from the local context to the goal. -/\nunsafe def apply_assumption : tactic Unit :=\n  local_context >>= apply_any\n#align tactic.apply_assumption tactic.apply_assumption\n\n/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails\nif this is not a definitional equality.\n\n`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`\nby reverting `h`, changing the goal, and reintroducing hypotheses. -/\nunsafe def change_core (e : expr) : Option expr \u2192 tactic Unit\n  | none => tactic.change e\n  | some h => do\n    let num_reverted : \u2115 \u2190 revert h\n    let expr.pi n bi d b \u2190 target\n    tactic.change <| expr.pi n bi e b\n    intron num_reverted\n#align tactic.change_core tactic.change_core\n\n/-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,\nassuming `olde` and `newe` are defeq when elaborated.\n-/\nunsafe def change_with_at (olde newe : pexpr) (hyp : Name) : tactic Unit := do\n  let h \u2190 get_local hyp\n  let tp \u2190 infer_type h\n  let olde \u2190 to_expr olde\n  let newe \u2190 to_expr newe\n  let repl_tp := tp.replace fun a n => if a = olde then some newe else none\n  when (repl_tp \u2260 tp) <| change_core repl_tp (some h)\n#align tactic.change_with_at tactic.change_with_at\n\n/-- Returns a list of all metavariables in the current partial proof. This can differ from\nthe list of goals, since the goals can be manually edited. -/\nunsafe def metavariables : tactic (List expr) :=\n  expr.list_meta_vars <$> result\n#align tactic.metavariables tactic.metavariables\n\n/--\n`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,\nand fail otherwise.\n-/\nunsafe def sorry_if_contains_sorry : tactic Unit := do\n  let g \u2190 target\n  guard g <|> fail \"goal does not contain `sorry`\"\n  tactic.admit\n#align tactic.sorry_if_contains_sorry tactic.sorry_if_contains_sorry\n\n/-- Fail if the target contains a metavariable. -/\nunsafe def no_mvars_in_target : tactic Unit :=\n  expr.has_meta_var <$> target >>= guardb \u2218 not\n#align tactic.no_mvars_in_target tactic.no_mvars_in_target\n\n/-- Succeeds only if the current goal is a proposition. -/\nunsafe def propositional_goal : tactic Unit := do\n  let g :: _ \u2190 get_goals\n  is_proof g >>= guardb\n#align tactic.propositional_goal tactic.propositional_goal\n\n/-- Succeeds only if we can construct an instance showing the\n  current goal is a subsingleton type. -/\nunsafe def subsingleton_goal : tactic Unit := do\n  let g :: _ \u2190 get_goals\n  let ty \u2190 infer_type g >>= instantiate_mvars\n  (to_expr ``(Subsingleton $(ty)) >>= mk_instance) >> skip\n#align tactic.subsingleton_goal tactic.subsingleton_goal\n\n/-- Succeeds only if the current goal is \"terminal\",\nin the sense that no other goals depend on it\n(except possibly through shared metavariables; see `independent_goal`).\n-/\nunsafe def terminal_goal : tactic Unit :=\n  propositional_goal <|>\n    subsingleton_goal <|> do\n      let g\u2080 :: _ \u2190 get_goals\n      let mvars \u2190 (fun L => List.erase L g\u2080) <$> metavariables\n      mvars fun g => do\n          let t \u2190 infer_type g >>= instantiate_mvars\n          let d \u2190 kdepends_on t g\u2080\n          Monad.whenb d <|\n              pp t >>= fun s =>\n                fail (\"The current goal is not terminal: \" ++ s ++ \" depends on it.\")\n#align tactic.terminal_goal tactic.terminal_goal\n\n/-- Succeeds only if the current goal is \"independent\", in the sense\nthat no other goals depend on it, even through shared meta-variables.\n-/\nunsafe def independent_goal : tactic Unit :=\n  no_mvars_in_target >> terminal_goal\n#align tactic.independent_goal tactic.independent_goal\n\n/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,\nit only unfolds reducible definitions, so it sometimes fails faster. -/\nunsafe def triv' : tactic Unit := do\n  let c \u2190 mk_const `trivial\n  exact c reducible\n#align tactic.triv' tactic.triv'\n\nvariable {\u03b1 : Type}\n\n/-- Apply a tactic as many times as possible, collecting the results in a list.\nFail if the tactic does not succeed at least once. -/\nunsafe def iterate1 (t : tactic \u03b1) : tactic (List \u03b1) := do\n  let r \u2190 decorate_ex \"iterate1 failed: tactic did not succeed\" t\n  let L \u2190 iterate t\n  return (r :: L)\n#align tactic.iterate1 tactic.iterate1\n\n/-- A simple check: `check_target_changes tac` applies tactic `tac` and fails if the main target\nbefore applying the tactic `tac` unifies with one of the goals produced by the tactic itself.\nUseful to make sure that the tactic `tac` is actually making progress. -/\nunsafe def check_target_changes (tac : tactic \u03b1) : tactic \u03b1 :=\n  focus1 do\n    let t \u2190 target\n    let x \u2190 tac\n    let gs \u2190 get_goals >>= List.mapM infer_type\n    (success_if_fail <| gs <| unify t) <|> fail \"Goal did not change\"\n    pure x\n#align tactic.check_target_changes tactic.check_target_changes\n\n/-- Introduces one or more variables and returns the new local constants.\nFails if `intro` cannot be applied. -/\nunsafe def intros1 : tactic (List expr) :=\n  iterate1 intro1\n#align tactic.intros1 tactic.intros1\n\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nunsafe def under_binders {\u03b1 : Type} (t : tactic \u03b1) : tactic \u03b1 := do\n  let v \u2190 intros\n  let r \u2190 t\n  revert_lst v\n  return r\n#align tactic.under_binders tactic.under_binders\n\nnamespace Interactive\n\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nunsafe def under_binders (i : itactic) : itactic :=\n  tactic.under_binders i\n#align tactic.interactive.under_binders tactic.interactive.under_binders\n\nend Interactive\n\n/-- `successes` invokes each tactic in turn, returning the list of successful results. -/\nunsafe def successes (tactics : List (tactic \u03b1)) : tactic (List \u03b1) :=\n  List.filterMap id <$> Monad.sequence (tactics.map fun t => try_core t)\n#align tactic.successes tactic.successes\n\n-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.\n/-- Try all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results,\nand reverting to the original `tactic_state`.\n-/\nunsafe def try_all {\u03b1 : Type} (tactics : List (tactic \u03b1)) : tactic (List \u03b1) := fun s =>\n  result.success\n    (tactics.map fun t : tactic \u03b1 =>\n        match t s with\n        | result.success a s' => [a]\n        | _ => []).join\n    s\n#align tactic.try_all tactic.try_all\n\n/-- Try all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results sorted by\nthe value produced by a subsequent execution of the `sort_by` tactic,\nand reverting to the original `tactic_state`.\n-/\nunsafe def try_all_sorted {\u03b1 : Type} (tactics : List (tactic \u03b1)) (sort_by : tactic \u2115 := num_goals) :\n    tactic (List (\u03b1 \u00d7 \u2115)) := fun s =>\n  result.success\n    ((tactics.map fun t : tactic \u03b1 =>\n            match\n              (do\n                  let a \u2190 t\n                  let n \u2190 sort_by\n                  return (a, n))\n                s with\n            | result.success a s' => [a]\n            | _ => []).join.qsort\n      fun p q : \u03b1 \u00d7 \u2115 => p.2 < q.2)\n    s\n#align tactic.try_all_sorted tactic.try_all_sorted\n\n/-- Return target after instantiating metavars and whnf. -/\nprivate unsafe def target' : tactic expr :=\n  target >>= instantiate_mvars >>= whnf\n#align tactic.target' tactic.target'\n\n-- FIXME check if we can remove `auto_param := ff`\n/-- Just like `split`, `fsplit` applies the constructor when the type of the target is\nan inductive data type with one constructor.\nHowever it does not reorder goals or invoke `auto_param` tactics.\n-/\nunsafe def fsplit : tactic Unit := do\n  let [c] \u2190 target' >>= get_constructors_for |\n    fail \"fsplit tactic failed, target is not an inductive datatype with only one constructor\"\n  mk_const c >>= fun e =>\n      apply e\n          { NewGoals := new_goals.all\n            autoParam\u2093 := ff } >>\n        skip\n#align tactic.fsplit tactic.fsplit\n\nrun_cmd\n  add_interactive [`fsplit]\n\nadd_tactic_doc\n  { Name := \"fsplit\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.fsplit]\n    tags := [\"logic\", \"goal management\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `results -/\n/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`\nsucceeds, clears the old hypothesis. -/\nunsafe def injections_and_clear : tactic Unit := do\n  let l \u2190 local_context\n  let results \u2190 successes <| l.map fun e => injection e >> clear e\n  when (results results.empty) (fail \"could not use `injection` then `clear` on any hypothesis\")\n#align tactic.injections_and_clear tactic.injections_and_clear\n\nrun_cmd\n  add_interactive [`injections_and_clear]\n\nadd_tactic_doc\n  { Name := \"injections_and_clear\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.injections_and_clear]\n    tags := [\"context management\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `r -/\n/-- Calls `cases` on every local hypothesis, succeeding if\nit succeeds on at least one hypothesis. -/\nunsafe def case_bash : tactic Unit := do\n  let l \u2190 local_context\n  let r \u2190 successes (l.reverse.map fun h => cases h >> skip)\n  when (r r.empty) failed\n#align tactic.case_bash tactic.case_bash\n\n-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.\n/-- `note_anon t v`, given a proof `v : t`,\nadds `h : t` to the current context, where the name `h` is fresh.\n\n`note_anon none v` will infer the type `t` from `v`.\n-/\nunsafe def note_anon (t : Option expr) (v : expr) : tactic expr := do\n  let h \u2190 get_unused_name `h none\n  note h t v\n#align tactic.note_anon tactic.note_anon\n\n/-- `find_local t` returns a local constant with type t, or fails if none exists. -/\nunsafe def find_local (t : pexpr) : tactic expr := do\n  let t' \u2190 to_expr t\n  Prod.snd <$> solve_aux t' assumption >>= instantiate_mvars <|>\n      fail f! \"No hypothesis found of the form: {t'}\"\n#align tactic.find_local tactic.find_local\n\n/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values\nof the previous local constants. `l` is a list of local constants and their values. -/\nunsafe def dependent_pose_core (l : List (expr \u00d7 expr)) : tactic Unit := do\n  let lc := l.map Prod.fst\n  let lm := l.map fun \u27e8l, v\u27e9 => (l.local_uniq_name, v)\n  let old :: other_goals \u2190 get_goals\n  let t \u2190 infer_type old\n  let new_goal \u2190 mk_meta_var (t.pis lc)\n  set_goals (old :: new_goal :: other_goals)\n  exact ((new_goal lc).instantiate_locals lm)\n  return ()\n#align tactic.dependent_pose_core tactic.dependent_pose_core\n\n/-- Instantiates metavariables that appear in the current goal.\n-/\nunsafe def instantiate_mvars_in_target : tactic Unit :=\n  target >>= instantiate_mvars >>= change\n#align tactic.instantiate_mvars_in_target tactic.instantiate_mvars_in_target\n\n/-- Instantiates metavariables in all goals.\n-/\nunsafe def instantiate_mvars_in_goals : tactic Unit :=\n  all_goals' <| instantiate_mvars_in_target\n#align tactic.instantiate_mvars_in_goals tactic.instantiate_mvars_in_goals\n\n/-- Protect the declaration `n` -/\nunsafe def mk_protected (n : Name) : tactic Unit := do\n  let env \u2190 get_env\n  set_env (env n)\n#align tactic.mk_protected tactic.mk_protected\n\nend Tactic\n\nnamespace Lean.Parser\n\nopen Tactic InteractionMonad\n\n/-- A version of `lean.parser.many` that requires at least `n` items -/\nunsafe def repeat_at_least {\u03b1 : Type} (p : lean.parser \u03b1) : \u2115 \u2192 lean.parser (List \u03b1)\n  | 0 => many p\n  | n + 1 => List.cons <$> p <*> repeat_at_least n\n#align lean.parser.repeat_at_least lean.parser.repeat_at_least\n\n/-- A version of `lean.parser.sep_by` that allows trailing delimiters, but requires at least one\nitem. Like `lean.parser.sep_by`, as a result of the `lean.parser` monad not being pure, this is only\nwell-behaved if `p` and `s` are backtrackable; which in practice means they must not consume the\ninput when they do not have a match. -/\nunsafe def sep_by_trailing {\u03b1 : Type} (s : lean.parser Unit) (p : lean.parser \u03b1) :\n    lean.parser (List \u03b1) := do\n  let fst \u2190 p\n  let some () \u2190 optional s |\n    pure [fst]\n  let some rest \u2190 optional sep_by_trailing |\n    pure [fst]\n  pure (fst :: rest)\n#align lean.parser.sep_by_trailing lean.parser.sep_by_trailing\n\n/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the\ncurrent line. -/\nunsafe def emit_command_here (str : String) : lean.parser String := do\n  let (_, left) \u2190 with_input command_like str\n  return left\n#align lean.parser.emit_command_here lean.parser.emit_command_here\n\n/-- Inner recursion for `emit_code_here`. -/\nunsafe def emit_code_here_aux : String \u2192 \u2115 \u2192 lean.parser Unit\n  | str, slen => do\n    let left \u2190 emit_command_here str\n    let llen := left.length\n    when (llen < slen \u2227 llen \u2260 0) (emit_code_here_aux left llen)\n#align lean.parser.emit_code_here_aux lean.parser.emit_code_here_aux\n\n/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in\nsource code. -/\nunsafe def emit_code_here (s : String) : lean.parser Unit :=\n  emit_code_here_aux s s.length\n#align lean.parser.emit_code_here lean.parser.emit_code_here\n\n/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the\ntop level, giving access to operations like `emit_code_here`. -/\n@[user_command]\nunsafe def run_parser_cmd (_ : interactive.parse <| tk \"run_parser\") : lean.parser Unit := do\n  let e \u2190 lean.parser.pexpr 0\n  let p \u2190 eval_pexpr (lean.parser Unit) e\n  p\n#align lean.parser.run_parser_cmd lean.parser.run_parser_cmd\n\nadd_tactic_doc\n  { Name := \"run_parser\"\n    category := DocCategory.cmd\n    declNames := [`` run_parser_cmd]\n    tags := [\"parsing\"] }\n\n/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).\n\nThis function deserves a C++ implementation in core lean, and will fail if it is not called from\nthe body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/\nunsafe def get_current_namespace : lean.parser Name := do\n  let env \u2190 get_env\n  let n \u2190 tactic.mk_user_fresh_name\n  emit_code_here <| s! \"def {n} := ()\"\n  let nfull \u2190 tactic.resolve_constant n\n  set_env env\n  return <| nfull n\n#align lean.parser.get_current_namespace lean.parser.get_current_namespace\n\n/-- `get_variables` returns a list of existing variable names, along with their types and binder\ninfo. -/\nunsafe def get_variables : lean.parser (List (Name \u00d7 BinderInfo \u00d7 expr)) :=\n  List.map expr.get_local_const_kind <$> list_available_include_vars\n#align lean.parser.get_variables lean.parser.get_variables\n\n/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been\n\"included\" by an `include v` statement and are not (yet) `omit`ed. -/\nunsafe def get_included_variables : lean.parser (List (Name \u00d7 BinderInfo \u00d7 expr)) := do\n  let ns \u2190 list_include_var_names\n  (List.filter fun v => v.1 \u2208 ns) <$> get_variables\n#align lean.parser.get_included_variables lean.parser.get_included_variables\n\n/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local\nvariables referenced in `es : list pexpr`, and those variables which have been `include`ed in the\nlocal context---precisely those variables which would be ambiently accessible if we were in a\ntactic-mode block where the goals had types `es.mmap to_expr`, for example.\n\nReturns a new `ts : tactic_state` with these local variables added, and\n`mappings : list (expr \u00d7 expr)`, for which pairs `(var, hyp)` correspond to an existing variable\n`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/\nunsafe def synthesize_tactic_state_with_variables_as_hyps (es : List pexpr) :\n    lean.parser (tactic_state \u00d7 List (expr \u00d7 expr)) := do\n  let vars\n    \u2190/- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the\n            declared variables to a fake `tactic_state`, and perform the resolution. At the end,\n            `to_expr e` has done the work of determining which variables were actually referenced, which\n            we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for\n            `pexpr`s). -/\n      list_available_include_vars\n  let fake_es \u2190\n    lean.parser.of_tactic <|\n        lock_tactic_state do\n          /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard\n                      them on this first pass. (We return the mappings generated by our second invocation of this\n                      function below.) -/\n              add_local_consts_as_local_hyps\n              vars\n          es to_expr\n  let included_vars\n    \u2190/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were\n            referenced in `e` when it was resolved to `fake_e`.\n      \n            It is important that we include variables of the kind a) because we want `simp` to have access\n            to declared local instances, and it is important that we only restrict to variables of kind a)\n            and b) together since we do not to recognise a hypothesis which is posited as a `variable`\n            in the environment but not referenced in the `pexpr` we were passed.\n      \n            One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want\n            simp to use arbitrary hypotheses which were declared as `variables` in the local environment\n            but not referenced in the expression to simplify (as one would be expect generally in tactic\n            mode). -/\n      list_include_var_names\n  let referenced_vars :=\n    List.join <| fake_es.map fun e => e.list_local_consts.map expr.local_pp_name\n  let/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the\n        `pexpr` list which we were passed.)  -/\n  directly_included_vars :=\n    vars.filter\u2093 fun var => var.local_pp_name \u2208 included_vars \u2228 var.local_pp_name \u2208 referenced_vars\n  let/- Inflate the list `directly_included_vars` to include those variables which are \"implicitly\n        included\" by virtue of reference to one or multiple others. For example, given\n        `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass\n        instance `prime n` should be included, but `ih : even n` should not. -/\n  all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars\n  /- Capture a tactic state where both of these kinds of variables have been added as local\n            hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/\n      lean.parser.of_tactic\n      do\n      let mappings \u2190 add_local_consts_as_local_hyps all_implicitly_included_vars\n      let ts \u2190 get_state\n      return (ts, mappings)\n#align lean.parser.synthesize_tactic_state_with_variables_as_hyps lean.parser.synthesize_tactic_state_with_variables_as_hyps\n\nend Lean.Parser\n\nnamespace Tactic\n\nvariable {\u03b1 : Type}\n\n/-- Hole command used to fill in a structure's field when specifying an instance.\n\nIn the following:\n\n```lean\ninstance : monad id :=\n{! !}\n```\n\ninvoking the hole command \"Instance Stub\" (\"Generate a skeleton for the structure under\nconstruction.\") produces:\n\n```lean\ninstance : monad id :=\n{ map := _,\n  map_const := _,\n  pure := _,\n  seq := _,\n  seq_left := _,\n  seq_right := _,\n  bind := _ }\n```\n-/\n@[hole_command]\nunsafe def instance_stub : hole_command\n    where\n  Name := \"Instance Stub\"\n  descr := \"Generate a skeleton for the structure under construction.\"\n  action _ := do\n    let tgt \u2190 target >>= whnf\n    let cl := tgt.get_app_fn.const_name\n    let env \u2190 get_env\n    let fs \u2190 expanded_field_list cl\n    let fs := fs.map Prod.snd\n    let fs := format.intercalate (\",\\n  \" : format) <| fs.map fun fn => f! \"{fn} := _\"\n    let out := format.to_string f! \"\\{ {fs} }}\"\n    return [(out, \"\")]\n#align tactic.instance_stub tactic.instance_stub\n\nadd_tactic_doc\n  { Name := \"instance_stub\"\n    category := DocCategory.hole_cmd\n    declNames := [`tactic.instance_stub]\n    tags := [\"instances\"] }\n\n/-- Like `resolve_name` except when the list of goals is\nempty. In that situation `resolve_name` fails whereas\n`resolve_name'` simply proceeds on a dummy goal -/\nunsafe def resolve_name' (n : Name) : tactic pexpr := do\n  let [] \u2190 get_goals |\n    resolve_name n\n  let g \u2190 mk_mvar\n  set_goals [g]\n  resolve_name n <* set_goals []\n#align tactic.resolve_name' tactic.resolve_name'\n\nprivate unsafe def strip_prefix' (n : Name) : List String \u2192 Name \u2192 tactic Name\n  | s, Name.anonymous => pure <| s.foldl (flip Name.mk_string) Name.anonymous\n  | s, Name.mk_string a p => do\n    let n' := s.foldl (flip Name.mk_string) Name.anonymous\n    (do\n          let n'' \u2190 tactic.resolve_constant n'\n          if n'' = n then pure n' else strip_prefix' (a :: s) p) <|>\n        strip_prefix' (a :: s) p\n  | s, n@(Name.mk_numeral a p) => pure <| s.foldl (flip Name.mk_string) n\n#align tactic.strip_prefix' tactic.strip_prefix'\n\n/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/\nunsafe def strip_prefix : Name \u2192 tactic Name\n  | n@(Name.mk_string a a_1) =>\n    if `_private.isPrefixOf\u2093 n then\n      let n' := n.updatePrefix Name.anonymous\n      n' <$ resolve_name' n' <|> pure n\n    else strip_prefix' n [a] a_1\n  | n => pure n\n#align tactic.strip_prefix tactic.strip_prefix\n\n/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/\nunsafe def mk_patterns (t : expr) : tactic (List format) := do\n  let cl := t.get_app_fn.const_name\n  let env \u2190 get_env\n  let fs := env.constructors_of cl\n  fs fun f => do\n      let (vs, _) \u2190 mk_const f >>= infer_type >>= open_pis\n      let vs := vs fun v => v\n      let vs \u2190\n        vs fun v => do\n            let v' \u2190 get_unused_name v\n            pose v' none q(())\n            pure v'\n      vs fun v => get_local v >>= clear\n      let args := List.intersperse (\" \" : format) <| vs to_fmt\n      let f \u2190 strip_prefix f\n      if args then\n          pure <|\n            f! \"| {f} := _\n              \"\n        else\n          pure\n            f! \"| ({f } {format.join args}) := _\n              \"\n#align tactic.mk_patterns tactic.mk_patterns\n\n/-- Hole command used to generate a `match` expression.\n\nIn the following:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\n{! e !}\n```\n\ninvoking hole command \"Match Stub\" (\"Generate a list of equations for a `match` expression\")\nproduces:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\nmatch e with\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\nend\n```\n-/\n@[hole_command]\nunsafe def match_stub : hole_command\n    where\n  Name := \"Match Stub\"\n  descr := \"Generate a list of equations for a `match` expression.\"\n  action es := do\n    let [e] \u2190 pure es |\n      fail \"expecting one expression\"\n    let e \u2190 to_expr e\n    let t \u2190 infer_type e >>= whnf\n    let fs \u2190 mk_patterns t\n    let e \u2190 pp e\n    let out :=\n      format.to_string\n        f! \"match {e } with\n          {format.join fs}end\n          \"\n    return [(out, \"\")]\n#align tactic.match_stub tactic.match_stub\n\nadd_tactic_doc\n  { Name := \"Match Stub\"\n    category := DocCategory.hole_cmd\n    declNames := [`tactic.match_stub]\n    tags := [\"pattern matching\"] }\n\n/--\nInvoking hole command \"Equations Stub\" (\"Generate a list of equations for a recursive definition\")\nin the following:\n\n```lean\nmeta def foo : {! expr \u2192 tactic unit !} -- `:=` is omitted\n```\n\nproduces:\n\n```lean\nmeta def foo : expr \u2192 tactic unit\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\nA similar result can be obtained by invoking \"Equations Stub\" on the following:\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- do not forget to write `:=`!!\n{! !}\n```\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- don't forget to erase `:=`!!\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\n-/\n@[hole_command]\nunsafe def eqn_stub : hole_command\n    where\n  Name := \"Equations Stub\"\n  descr := \"Generate a list of equations for a recursive definition.\"\n  action es := do\n    let t \u2190\n      match es with\n        | [t] => to_expr t\n        | [] => target\n        | _ => fail \"expecting one type\"\n    let e \u2190 whnf t\n    let (v :: _, _) \u2190 open_pis e |\n      fail \"expecting a Pi-type\"\n    let t' \u2190 infer_type v\n    let fs \u2190 mk_patterns t'\n    let t \u2190 pp t\n    let out :=\n      if es.Empty then\n        format.to_string\n          f! \"-- do not forget to erase `:=`!!\n            {format.join fs}\"\n      else\n        format.to_string\n          f! \"{t }\n            {format.join fs}\"\n    return [(out, \"\")]\n#align tactic.eqn_stub tactic.eqn_stub\n\nadd_tactic_doc\n  { Name := \"Equations Stub\"\n    category := DocCategory.hole_cmd\n    declNames := [`tactic.eqn_stub]\n    tags := [\"pattern matching\"] }\n\n/-- This command lists the constructors that can be used to satisfy the expected type.\n\nInvoking \"List Constructors\" (\"Show the list of constructors of the expected type\")\nin the following hole:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! !}\n```\n\nproduces:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! sum.inl, sum.inr !}\n```\n\nand will display:\n\n```lean\nsum.inl : \u2124 \u2192 \u2124 \u2295 \u2115\n\nsum.inr : \u2115 \u2192 \u2124 \u2295 \u2115\n```\n\n-/\n@[hole_command]\nunsafe def list_constructors_hole : hole_command\n    where\n  Name := \"List Constructors\"\n  descr := \"Show the list of constructors of the expected type.\"\n  action es := do\n    let t \u2190 target >>= whnf\n    let (_, t) \u2190 open_pis t\n    let cl := t.get_app_fn.const_name\n    let args := t.get_app_args\n    let env \u2190 get_env\n    let cs := env.constructors_of cl\n    let ts \u2190\n      cs.mapM fun c => do\n          let e \u2190 mk_const c\n          let t \u2190 infer_type (e.mk_app args) >>= pp\n          let c \u2190 strip_prefix c\n          pure\n              f! \"\n                {c } : {t}\n                \"\n    let fs \u2190 format.intercalate \", \" <$> cs.mapM (strip_prefix >=> pure \u2218 to_fmt)\n    let out := format.to_string f! \"\\{! {fs} !}}\"\n    trace (format.join ts).toString\n    return [(out, \"\")]\n#align tactic.list_constructors_hole tactic.list_constructors_hole\n\nadd_tactic_doc\n  { Name := \"List Constructors\"\n    category := DocCategory.hole_cmd\n    declNames := [`tactic.list_constructors_hole]\n    tags := [\"goal information\"] }\n\n/-- Makes the declaration `classical.prop_decidable` available to type class inference.\nThis asserts that all propositions are decidable, but does not have computational content.\n\nThe `aggressive` argument controls whether the instance is added globally, where it has low\npriority, or in the local context, where it has very high priority. -/\nunsafe def classical (aggressive : Bool := false) : tactic Unit :=\n  if aggressive then do\n    let h \u2190 get_unused_name `_inst\n    mk_const `classical.prop_decidable >>= note h none\n    reset_instance_cache\n  else do\n    -- Turn on the `prop_decidable` instance. `9` is what we use in the `classical` locale\n        tactic.set_basic_attribute\n        `instance `classical.prop_decidable ff (some 9)\n#align tactic.classical tactic.classical\n\nopen Expr\n\n/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,\nreturns the expression `f \u2218 g \u2218 h`. -/\nunsafe def mk_comp (v : expr) : expr \u2192 tactic expr\n  | app f e =>\n    if e = v then pure f\n    else do\n      guard \u00acv f <|> fail \"bad guard\"\n      let e' \u2190 mk_comp e >>= instantiate_mvars\n      let f \u2190 instantiate_mvars f\n      mk_mapp `` Function.comp [none, none, none, f, e']\n  | e => do\n    guard (e = v)\n    let t \u2190 infer_type e\n    mk_mapp `` id [t]\n#align tactic.mk_comp tactic.mk_comp\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/-- Given two expressions `e\u2080` and `e\u2081`, return the expression `` `(%%e\u2080 \u2194 %%e\u2081)``. -/ unsafe\n  def mk_iff ( e\u2080 : expr ) ( e\u2081 : expr ) : expr := q( $ ( e\u2080 ) \u2194 $ ( e\u2081 ) )\n#align tactic.mk_iff tactic.mk_iff\n\n/-- From a lemma of the shape `\u2200 x, f (g x) = h x`\nderive an auxiliary lemma of the form `f \u2218 g = h`\nfor reasoning about higher-order functions.\n-/\nunsafe def mk_higher_order_type : expr \u2192 tactic expr\n  | pi n bi d b@(pi _ _ _ _) => do\n    let v \u2190 mk_local_def n d\n    let b' := b.instantiate_var v\n    (pi n bi d \u2218 flip abstract_local v) <$> mk_higher_order_type b'\n  | pi n bi d b => do\n    let v \u2190 mk_local_def n d\n    let b' := b.instantiate_var v\n    let (l, r) \u2190 match_eq b' <|> fail f! \"not an equality {b'}\"\n    let l' \u2190 mk_comp v l\n    let r' \u2190 mk_comp v r\n    mk_app `` Eq [l', r']\n  | e => failed\n#align tactic.mk_higher_order_type tactic.mk_higher_order_type\n\nopen Lean.Parser Interactive.Types\n\n/-- A user attribute that applies to lemmas of the shape `\u2200 x, f (g x) = h x`.\nIt derives an auxiliary lemma of the form `f \u2218 g = h` for reasoning about higher-order functions.\n-/\n@[user_attribute]\nunsafe def higher_order_attr : user_attribute Unit (Option Name)\n    where\n  Name := `higher_order\n  parser := optional ident\n  descr :=\n    \"From a lemma of the shape `\u2200 x, f (g x) = h x` derive an auxiliary lemma of the\\nform `f \u2218 g = h` for reasoning about higher-order functions.\"\n  after_set :=\n    some fun lmm _ _ => do\n      let env \u2190 get_env\n      let decl \u2190 env.get lmm\n      let num := decl.univ_params.length\n      let lvls := (List.iota Num).map `l.append_after\n      let l : expr := expr.const lmm <| lvls.map level.param\n      let t \u2190 infer_type l >>= instantiate_mvars\n      let t' \u2190 mk_higher_order_type t\n      let (_, pr) \u2190\n        solve_aux t' do\n            intros\n            applyc `` _root_.funext\n            intro1\n            andthen (applyc lmm) assumption\n      let pr \u2190 instantiate_mvars pr\n      let lmm' \u2190 higher_order_attr.get_param lmm\n      let lmm' \u2190 flip Name.updatePrefix lmm.getPrefix <$> lmm' <|> pure lmm.add_prime\n      add_decl <| declaration.thm lmm' lvls t' (pure pr)\n      copy_attribute `simp lmm lmm'\n      copy_attribute `functor_norm lmm lmm'\n#align tactic.higher_order_attr tactic.higher_order_attr\n\nadd_tactic_doc\n  { Name := \"higher_order\"\n    category := DocCategory.attr\n    declNames := [`tactic.higher_order_attr]\n    tags := [\"lemma derivation\"] }\n\nattribute [higher_order.1map_comp_pure] map_pure\n\n/-- Copies a definition into the `tactic.interactive` namespace to make it usable\nin proof scripts. It allows one to write\n\n```lean\n@[interactive]\nmeta def my_tactic := ...\n```\n\ninstead of\n\n```lean\nmeta def my_tactic := ...\n\nrun_cmd add_interactive [``my_tactic]\n```\n-/\n@[user_attribute]\nunsafe def interactive_attr : user_attribute\n    where\n  Name := `interactive\n  descr :=\n    \"Put a definition in the `tactic.interactive` namespace to make it usable\\nin proof scripts.\"\n  after_set := some fun tac _ _ => add_interactive [tac]\n#align tactic.interactive_attr tactic.interactive_attr\n\nadd_tactic_doc\n  { Name := \"interactive\"\n    category := DocCategory.attr\n    declNames := [`` tactic.interactive_attr]\n    tags := [\"environment\"] }\n\n/-- Use `refine` to partially discharge the goal,\nor call `fconstructor` and try again.\n-/\nprivate unsafe def use_aux (h : pexpr) : tactic Unit :=\n  focus1 (refine h >> done) <|> fconstructor >> use_aux\n#align tactic.use_aux tactic.use_aux\n\n/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations\nat the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to\nthe expected type.\n\n```lean\nexample : \u2203 x : \u2124, x = x :=\nby tactic.use ``(42)\n```\n\nSee the doc string for `tactic.interactive.use` for more information.\n -/\nprotected unsafe def use (l : List pexpr) : tactic Unit :=\n  focus1 <|\n    seq' (l.mapM' fun h => use_aux h <|> fail f! \"failed to instantiate goal with {h}\")\n      instantiate_mvars_in_target\n#align tactic.use tactic.use\n\n/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the\nlocal context. -/\nunsafe def clear_aux_decl_aux : List expr \u2192 tactic Unit\n  | [] => skip\n  | e :: l => do\n    cond e (tactic.clear e) skip\n    clear_aux_decl_aux l\n#align tactic.clear_aux_decl_aux tactic.clear_aux_decl_aux\n\n/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/\nunsafe def clear_aux_decl : tactic Unit :=\n  local_context >>= clear_aux_decl_aux\n#align tactic.clear_aux_decl tactic.clear_aux_decl\n\n/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)\nfinds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/\nunsafe def apply_at_aux (arg t : expr) : List expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 List expr)\n  | vs, e, pi n bi d b =>\n    (do\n        let v \u2190 mk_meta_var d\n        apply_at_aux (v :: vs) (e v) (b v)) <|>\n      (e arg, vs) <$ unify d t\n  | vs, e, _ => failed\n#align tactic.apply_at_aux tactic.apply_at_aux\n\n/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/\nunsafe def apply_at (e h : expr) : tactic Unit := do\n  let ht \u2190 infer_type h\n  let et \u2190 infer_type e\n  let (h', gs') \u2190 apply_at_aux h ht [] e et\n  note h none h'\n  clear h\n  let gs' \u2190 gs'.filterM is_assigned\n  let g :: gs \u2190 get_goals\n  set_goals (g :: gs' ++ gs)\n#align tactic.apply_at tactic.apply_at\n\n/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/\nunsafe def symmetry_hyp (h : expr) (md := semireducible) : tactic Unit := do\n  let tgt \u2190 infer_type h\n  let env \u2190 get_env\n  let r := get_app_fn tgt\n  match env (const_name r) with\n    | some symm => do\n      let s \u2190 mk_const symm\n      apply_at s h\n    | none =>\n      fail\n        \"symmetry tactic failed, target is not a relation application with the expected property.\"\n#align tactic.symmetry_hyp tactic.symmetry_hyp\n\n/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing\ninteractive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.\nIt does *not* use the `namespace` command, so it will typically be used after\n`namespace tactic.interactive`.\n-/\n@[user_command]\nunsafe def setup_tactic_parser_cmd (_ : interactive.parse <| tk \"setup_tactic_parser\") :\n    lean.parser Unit :=\n  emit_code_here\n    \"\\nopen _root_.lean\\nopen _root_.lean.parser\\nopen _root_.interactive _root_.interactive.types\\n\\nlocal postfix (name := parser.optional) `?`:9001 := optional\\nlocal postfix (name := parser.many) *:9001 := many .\\n\"\n#align tactic.setup_tactic_parser_cmd tactic.setup_tactic_parser_cmd\n\n/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if\n`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/\nunsafe def finally {\u03b2} (tac : tactic \u03b1) (finalizer : tactic \u03b2) : tactic \u03b1 := fun s =>\n  match tac s with\n  | result.success r s' => (finalizer >> pure r) s'\n  | result.exception msg p s' => (finalizer >> result.exception msg p) s'\n#align tactic.finally tactic.finally\n\n/-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.\n-/\nunsafe def on_exception {\u03b2} (handler : tactic \u03b2) (tac : tactic \u03b1) : tactic \u03b1\n  | s =>\n    match tac s with\n    | result.exception msg p s' => (handler *> result.exception msg p) s'\n    | ok => ok\n#align tactic.on_exception tactic.on_exception\n\n/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/\nunsafe def decorate_error (add_msg : String) (tac : tactic \u03b1) : tactic \u03b1\n  | s =>\n    match tac s with\n    | result.exception msg p s =>\n      let msg (_ : Unit) : format :=\n        match msg with\n        | some msg => add_msg ++ format.line ++ msg ()\n        | none => add_msg\n      result.exception msg p s\n    | ok => ok\n#align tactic.decorate_error tactic.decorate_error\n\n/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,\n  returns the error message. -/\nunsafe def retrieve_or_report_error {\u03b1 : Type u} (t : tactic \u03b1) : tactic (Sum \u03b1 String) := fun s =>\n  match t s with\n  | interaction_monad.result.success a s' => result.success (Sum.inl a) s\n  | interaction_monad.result.exception msg' _ s' =>\n    result.success (Sum.inr (msg'.iget ()).toString) s\n#align tactic.retrieve_or_report_error tactic.retrieve_or_report_error\n\n/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/\nunsafe def try_or_report_error {\u03b1 : Type u} (t : tactic \u03b1) : tactic (Sum \u03b1 String) := fun s =>\n  match t s with\n  | interaction_monad.result.success a s' => result.success (Sum.inl a) s'\n  | interaction_monad.result.exception msg' _ s' =>\n    result.success (Sum.inr (msg'.iget ()).toString) s\n#align tactic.try_or_report_error tactic.try_or_report_error\n\n/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.\n-/\nunsafe def succeeds_or_fails_with_msg {\u03b1 : Type} (t : tactic \u03b1) (p : String \u2192 Bool) : tactic Unit :=\n  do\n  let x \u2190 retrieve_or_report_error t\n  match x with\n    | Sum.inl _ => skip\n    | Sum.inr msg => if p msg then skip else fail msg\n#align tactic.succeeds_or_fails_with_msg tactic.succeeds_or_fails_with_msg\n\nadd_tactic_doc\n  { Name := \"setup_tactic_parser\"\n    category := DocCategory.cmd\n    declNames := [`tactic.setup_tactic_parser_cmd]\n    tags := [\"parsing\", \"notation\"] }\n\n/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message\nof `t`. -/\nunsafe def trace_error (msg : String) (t : tactic \u03b1) : tactic \u03b1\n  | s =>\n    match t s with\n    | result.success r s' => result.success r s'\n    | result.exception (some msg') p s' =>\n      ((trace msg >> trace (msg' ())) >> result.exception (some msg') p) s'\n    | result.exception none p s' => result.exception none p s'\n#align tactic.trace_error tactic.trace_error\n\n/-- ``trace_if_enabled `n msg`` traces the message `msg`\nonly if tracing is enabled for the name `n`.\n\nCreate new names registered for tracing with `declare_trace n`.\nThen use `set_option trace.n true/false` to enable or disable tracing for `n`.\n-/\nunsafe def trace_if_enabled (n : Name) {\u03b1 : Type u} [has_to_tactic_format \u03b1] (msg : \u03b1) :\n    tactic Unit :=\n  when_tracing n (trace msg)\n#align tactic.trace_if_enabled tactic.trace_if_enabled\n\n/-- ``trace_state_if_enabled `n msg`` prints the tactic state,\npreceded by the optional string `msg`,\nonly if tracing is enabled for the name `n`.\n-/\nunsafe def trace_state_if_enabled (n : Name) (msg : String := \"\") : tactic Unit :=\n  when_tracing n ((if msg = \"\" then skip else trace msg) >> trace_state)\n#align tactic.trace_state_if_enabled tactic.trace_state_if_enabled\n\n/-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,\nand fails otherwise.\n-/\nunsafe def success_if_fail_with_msg {\u03b1 : Type u} (t : tactic \u03b1) (msg : String) : tactic Unit :=\n  fun s =>\n  match t s with\n  | interaction_monad.result.exception msg' _ s' =>\n    let expected_msg := (msg'.iget ()).toString\n    if msg = expected_msg then result.success () s\n    else\n      mk_exception\n        (f! \"failure messages didn't match. Expected:\n          {expected_msg}\")\n        none s\n  | interaction_monad.result.success a s =>\n    mk_exception \"success_if_fail_with_msg combinator failed, given tactic succeeded\" none s\n#align tactic.success_if_fail_with_msg tactic.success_if_fail_with_msg\n\n/-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.\n-/\nunsafe def tactic_statement (g : expr) : tactic String := do\n  let g \u2190 instantiate_mvars g\n  let g \u2190 head_beta g\n  let r \u2190 pp (replace_mvars g)\n  if g then return s! \"Try this: refine {r}\" else return s! \"Try this: exact {r}\"\n#align tactic.tactic_statement tactic.tactic_statement\n\n/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the\ninitial goals and returns the goals `tac` ended on. -/\nunsafe def with_local_goals {\u03b1} (gs : List expr) (tac : tactic \u03b1) : tactic (\u03b1 \u00d7 List expr) := do\n  let gs' \u2190 get_goals\n  set_goals gs\n  finally (Prod.mk <$> tac <*> get_goals) (set_goals gs')\n#align tactic.with_local_goals tactic.with_local_goals\n\n/-- like `with_local_goals` but discards the resulting goals -/\nunsafe def with_local_goals' {\u03b1} (gs : List expr) (tac : tactic \u03b1) : tactic \u03b1 :=\n  Prod.fst <$> with_local_goals gs tac\n#align tactic.with_local_goals' tactic.with_local_goals'\n\n/-- Representation of a proof goal that lends itself to comparison. The\nfollowing goal:\n\n```lean\nl\u2080 : T,\nl\u2081 : T\n\u22a2 \u2200 v : T, foo\n```\n\nis represented as\n\n```\n(2, \u2200 l\u2080 l\u2081 v : T, foo)\n```\n\nThe number 2 indicates that first the two bound variables of the\n`\u2200` are actually local constant. Comparing two such goals with `=`\nrather than `=\u2090` or `is_def_eq` tells us that proof script should\nnot see the difference between the two.\n -/\nunsafe def packaged_goal :=\n  \u2115 \u00d7 expr\n#align tactic.packaged_goal tactic.packaged_goal\n\n/-- proof state made of multiple `goal` meant for comparing\nthe result of running different tactics -/\nunsafe def proof_state :=\n  List packaged_goal\n#align tactic.proof_state tactic.proof_state\n\nunsafe instance goal.inhabited : Inhabited packaged_goal :=\n  \u27e8(0, var 0)\u27e9\n#align tactic.goal.inhabited tactic.goal.inhabited\n\nunsafe instance proof_state.inhabited : Inhabited proof_state :=\n  (inferInstance : Inhabited (List packaged_goal))\n#align tactic.proof_state.inhabited tactic.proof_state.inhabited\n\n/-- create a `packaged_goal` corresponding to the current goal -/\nunsafe def get_packaged_goal : tactic packaged_goal := do\n  let ls \u2190 local_context\n  let tgt \u2190 target >>= instantiate_mvars\n  let tgt \u2190 pis ls tgt\n  pure (ls, tgt)\n#align tactic.get_packaged_goal tactic.get_packaged_goal\n\n/-- `goal_of_mvar g`, with `g` a meta variable, creates a\n`packaged_goal` corresponding to `g` interpretted as a proof goal -/\nunsafe def goal_of_mvar (g : expr) : tactic packaged_goal :=\n  with_local_goals' [g] get_packaged_goal\n#align tactic.goal_of_mvar tactic.goal_of_mvar\n\n/-- `get_proof_state` lists the user visible goal for each goal\nof the current state and for each goal, abstracts all of the\nmeta variables of the other gaols.\n\nThis produces a list of goals in the form of `\u2115 \u00d7 expr` where\nthe `expr` encodes the following proof state:\n\n```lean\n2 goals\nl\u2081 : t\u2081,\nl\u2082 : t\u2082,\nl\u2083 : t\u2083\n\u22a2 tgt\u2081\n\n\u22a2 tgt\u2082\n```\n\nas\n\n```lean\n[ (3, \u2200 (mv : tgt\u2081) (mv : tgt\u2082) (l\u2081 : t\u2081) (l\u2082 : t\u2082) (l\u2083 : t\u2083), tgt\u2081),\n  (0, \u2200 (mv : tgt\u2081) (mv : tgt\u2082), tgt\u2082) ]\n```\n\nwith 2 goals, the first 2 bound variables encode the meta variable\nof all the goals, the next 3 (in the first goal) and 0 (in the second goal)\nare the local constants.\n\nThis representation allows us to compare goals and proof states while\nignoring information like the unique name of local constants and\nthe equality or difference of meta variables that encode the same goal.\n-/\nunsafe def get_proof_state : tactic proof_state := do\n  let gs \u2190 get_goals\n  gs fun g => do\n      let \u27e8n, g\u27e9 \u2190 goal_of_mvar g\n      let g \u2190\n        gs\n            (fun g v => do\n              let g \u2190 kabstract g v reducible ff\n              pure <| pi `goal BinderInfo.default q(True) g)\n            g\n      pure (n, g)\n#align tactic.get_proof_state tactic.get_proof_state\n\n/-- Run `tac` in a disposable proof state and return the state.\nSee `proof_state`, `goal` and `get_proof_state`.\n-/\nunsafe def get_proof_state_after (tac : tactic Unit) : tactic (Option proof_state) :=\n  try_core <| retrieve <| tac >> get_proof_state\n#align tactic.get_proof_state_after tactic.get_proof_state_after\n\nopen Lean _Root_.Interactive\n\n/-- A type alias for `tactic format`, standing for \"pretty print format\". -/\nunsafe def pformat :=\n  tactic format\n#align tactic.pformat tactic.pformat\n\n/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/\nunsafe def pformat.mk (fmt : format) : pformat :=\n  pure fmt\n#align tactic.pformat.mk tactic.pformat.mk\n\n/-- an alias for `pp`. -/\nunsafe def to_pfmt {\u03b1} [has_to_tactic_format \u03b1] (x : \u03b1) : pformat :=\n  pp x\n#align tactic.to_pfmt tactic.to_pfmt\n\nunsafe instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=\n  \u27e8id\u27e9\n#align tactic.pformat.has_to_tactic_format tactic.pformat.has_to_tactic_format\n\nunsafe instance : Append pformat :=\n  \u27e8fun x y => (\u00b7 ++ \u00b7) <$> x <*> y\u27e9\n\nunsafe instance tactic.has_to_tactic_format [has_to_tactic_format \u03b1] :\n    has_to_tactic_format (tactic \u03b1) :=\n  \u27e8fun x => x >>= to_pfmt\u27e9\n#align tactic.tactic.has_to_tactic_format tactic.tactic.has_to_tactic_format\n\nprivate unsafe def parse_pformat : String \u2192 List Char \u2192 parser pexpr\n  | Acc, [] => pure ``(to_pfmt $(reflect Acc))\n  | Acc, '\\n' :: s => do\n    let f \u2190 parse_pformat \"\" s\n    pure ``(to_pfmt $(reflect Acc) ++ pformat.mk format.line ++ $(f))\n  | Acc, '{' :: '{' :: s => parse_pformat (Acc ++ \"{\") s\n  | Acc, '{' :: s => do\n    let (e, s) \u2190 with_input (lean.parser.pexpr 0) s.asString\n    let '}' :: s \u2190 return s.toList |\n      fail \"'}' expected\"\n    let f \u2190 parse_pformat \"\" s\n    pure ``(to_pfmt $(reflect Acc) ++ to_pfmt $(e) ++ $(f))\n  | Acc, c :: s => parse_pformat (Acc.str c) s\n#align tactic.parse_pformat tactic.parse_pformat\n\n/-- See `format!` in `init/meta/interactive_base.lean`.\n\nThe main differences are that `pp` is called instead of `to_fmt` and that we can use\narguments of type `tactic \u03b1` in the quotations.\n\nNow, consider the following:\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace format!\"{e}\"  -- outputs `has_add.add.{0} nat nat.has_add\n                    -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`\ntrace pformat!\"{e}\" -- outputs `3 + 7`\n```\n\nThe difference is significant. And now, the following is expressible:\n\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace pformat!\"{e} : {infer_type e}\" -- outputs `3 + 7 : \u2115`\n```\n\nSee also: `trace!` and `fail!`\n-/\n@[user_notation]\nunsafe def pformat_macro (_ : parse <| tk \"pformat!\") (s : String) : parser pexpr := do\n  let e \u2190 parse_pformat \"\" s.toList\n  return ``(($(e) : pformat))\n#align tactic.pformat_macro tactic.pformat_macro\n\n/-- The combination of `pformat` and `fail`.\n-/\n@[user_notation]\nunsafe def fail_macro (_ : parse <| tk \"fail!\") (s : String) : parser pexpr := do\n  let e \u2190 pformat_macro () s\n  pure ``(($(e) : pformat) >>= fail)\n#align tactic.fail_macro tactic.fail_macro\n\n/-- The combination of `pformat` and `trace`.\n-/\n@[user_notation]\nunsafe def trace_macro (_ : parse <| tk \"trace!\") (s : String) : parser pexpr := do\n  let e \u2190 pformat_macro () s\n  pure ``(($(e) : pformat) >>= trace)\n#align tactic.trace_macro tactic.trace_macro\n\n/-- A hackish way to get the `src` directory of any project.\n  Requires as argument any declaration name `n` in that project, and `k`, the number of characters\n  in the path of the file where `n` is declared not part of the `src` directory.\n  Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`.\n  Note: does not work in the file where `n` is declared. -/\nunsafe def get_project_dir (n : Name) (k : \u2115) : tactic String := do\n  let e \u2190 get_env\n  let s \u2190\n    e.decl_olean n <|>\n        throwError\n          \"Did not find declaration {(\u2190\n            n)}. This command does not work in the file where {\u2190 n} is declared.\"\n  return <| s k\n#align tactic.get_project_dir tactic.get_project_dir\n\n/-- A hackish way to get the `src` directory of mathlib. -/\nunsafe def get_mathlib_dir : tactic String :=\n  get_project_dir `mathlib_dir_locator 23\n#align tactic.get_mathlib_dir tactic.get_mathlib_dir\n\n/-- Checks whether a declaration with the given name is declared in mathlib.\nIf you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,\nsince it is expensive to execute `get_mathlib_dir` many times. -/\nunsafe def is_in_mathlib (n : Name) : tactic Bool := do\n  let ml \u2190 get_mathlib_dir\n  let e \u2190 get_env\n  return <| e ml n\n#align tactic.is_in_mathlib tactic.is_in_mathlib\n\n/-- Runs a tactic by name.\nIf it is a `tactic string`, return whatever string it returns.\nIf it is a `tactic unit`, return the name.\n(This is mostly used in invoking \"self-reporting tactics\", e.g. by `tidy` and `hint`.)\n-/\nunsafe def name_to_tactic (n : Name) : tactic String := do\n  let d \u2190 get_decl n\n  let e \u2190 mk_const n\n  let t := d.type\n  if t == q(tactic Unit) then\n      eval_expr (tactic Unit) e >>= fun t => t >> Name.toString <$> strip_prefix n\n    else\n      if t == q(tactic String) then eval_expr (tactic String) e >>= fun t => t\n      else\n        throwError\n          \"name_to_tactic cannot take `{\u2190\n            n} as input: its type must be `tactic string` or `tactic unit`\"\n#align tactic.name_to_tactic tactic.name_to_tactic\n\n/-- auxiliary function for `apply_under_n_pis` -/\nprivate unsafe def apply_under_n_pis_aux (func arg : pexpr) : \u2115 \u2192 \u2115 \u2192 expr \u2192 pexpr\n  | n, 0, _ =>\n    let vars := (List.range n).reverse.map (@expr.var false)\n    let bd := vars.foldl expr.app arg.mk_explicit\n    func bd\n  | n, k + 1, expr.pi nm bi tp bd =>\n    expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n + 1) k bd)\n  | n, k + 1, t => apply_under_n_pis_aux n 0 t\n#align tactic.apply_under_n_pis_aux tactic.apply_under_n_pis_aux\n\n/-- Assumes `pi_expr` is of the form `\u03a0 x1 ... xn xn+1..., _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\nunsafe def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : \u2115) : pexpr :=\n  apply_under_n_pis_aux func arg 0 n pi_expr\n#align tactic.apply_under_n_pis tactic.apply_under_n_pis\n\n/-- Assumes `pi_expr` is of the form `\u03a0 x1 ... xn, _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\nunsafe def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=\n  apply_under_n_pis func arg pi_expr pi_expr.pi_arity\n#align tactic.apply_under_pis tactic.apply_under_pis\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n      If `func` is a `pexpr` representing a function that takes an argument `a`,\n      `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.\n      When `tgt` is a `pi` expr, `func` is elaborated in a context\n      with the domain of `tgt`.\n      \n      Examples:\n      * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function\n        argument.\n      * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument\n        of type `\u03b1 \u2192 \u03b1`.\n      * ```get_pexpr_arg_arity_with_tgt ``(module R) `(\u03a0 (R : Type), comm_ring R \u2192 true)``` returns 0\n      -/\n    unsafe\n  def\n    get_pexpr_arg_arity_with_tgt\n    ( func : pexpr ) ( tgt : expr ) : tactic \u2115\n    :=\n      lock_tactic_state\n        do\n          let mv \u2190 mk_mvar\n            solve_aux tgt <| intros >> to_expr ` `( $ ( func ) $ ( mv ) )\n            expr.pi_arity <$> ( infer_type mv >>= instantiate_mvars )\n#align tactic.get_pexpr_arg_arity_with_tgt tactic.get_pexpr_arg_arity_with_tgt\n\n/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.\n\n`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a\ndeclaration named `m` can be found. -/\nunsafe def find_private_decl (n : Name) (fr : Option Name) : tactic Name := do\n  let env \u2190 get_env\n  let fn \u2190\n    OptionT.run do\n        let fr \u2190 OptionT.mk (return fr)\n        let d \u2190 monadLift <| get_decl fr\n        OptionT.mk (return <| env d)\n  let p : String \u2192 Bool :=\n    match fn with\n    | some fn => fun x => fn = x\n    | none => fun _ => true\n  let xs :=\n    env.decl_filter_map fun d => do\n      let fn \u2190 env.decl_olean d.to_name\n      guard (`_private.isPrefixOf\u2093 d \u2227 p fn \u2227 d Name.anonymous = n)\n      pure d\n  match xs with\n    | [n] => pure n\n    | [] => fail \"no such private found\"\n    | _ => fail \"many matches found\"\n#align tactic.find_private_decl tactic.find_private_decl\n\nopen Lean.Parser Interactive\n\n/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`\nand creates a local notation to refer to it.\n\n`import_private foo` looks for `foo` in all imported files.\n\nWhen possible, make `foo` non-private rather than using this feature.\n -/\n@[user_command]\nunsafe def import_private_cmd (_ : parse <| tk \"import_private\") : lean.parser Unit := do\n  let n \u2190 ident\n  let fr \u2190 optional (tk \"from\" *> ident)\n  let n \u2190 find_private_decl n fr\n  let c \u2190 resolve_constant n\n  let d \u2190 get_decl n\n  let c := @expr.const true c d.univ_levels\n  let new_n \u2190 new_aux_decl_name\n  add_decl <| declaration.defn new_n d d c ReducibilityHints.abbrev d\n  let new_not := s!\"local notation `{(n.updatePrefix Name.anonymous)}` := {new_n}\"\n  emit_command_here <| new_not\n  skip\n#align tactic.import_private_cmd tactic.import_private_cmd\n\nadd_tactic_doc\n  { Name := \"import_private\"\n    category := DocCategory.cmd\n    declNames := [`tactic.import_private_cmd]\n    tags := [\"renaming\"] }\n\n/--\nThe command `mk_simp_attribute simp_name \"description\"` creates a simp set with name `simp_name`.\nLemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.\n`mk_simp_attribute simp_name none` will use a default description.\n\nAppending the command with `with attr1 attr2 ...` will include all declarations tagged with\n`attr1`, `attr2`, ... in the new simp set.\n\nThis command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string\nto the attribute that is defined. If you need to create a simp set in a file where this command is\nnot available, you should use\n```lean\nrun_cmd mk_simp_attr `simp_name\nrun_cmd add_doc_string `simp_attr.simp_name \"Description of the simp set here\"\n```\n-/\n@[user_command]\nunsafe def mk_simp_attribute_cmd (_ : parse <| tk \"mk_simp_attribute\") : lean.parser Unit := do\n  let n \u2190 ident\n  let d \u2190 parser.pexpr\n  let d \u2190 to_expr ``(($(d) : Option String))\n  let descr \u2190 eval_expr (Option String) d\n  let with_list \u2190 tk \"with\" *> many ident <|> return []\n  mk_simp_attr n with_list\n  add_doc_string (name.append `simp_attr n) <| descr <| \"simp set for \" ++ toString n\n#align tactic.mk_simp_attribute_cmd tactic.mk_simp_attribute_cmd\n\nadd_tactic_doc\n  { Name := \"mk_simp_attribute\"\n    category := DocCategory.cmd\n    declNames := [`tactic.mk_simp_attribute_cmd]\n    tags := [\"simplification\"] }\n\n/-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns\nthe name of the declaration that defines this attribute.\nFails if there is no user attribute with this name.\nExample: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/\nunsafe def get_user_attribute_name (attr_name : Name) : tactic Name := do\n  let ns \u2190 attribute.get_instances `user_attribute\n  (ns fun nm => do\n        let d \u2190 get_decl nm\n        let e \u2190 mk_app `user_attribute.name [d]\n        let attr_nm \u2190 eval_expr Name e\n        guard <| attr_nm = attr_name\n        return nm) <|>\n      throwError \"'{\u2190 attr_name}' is not a user attribute.\"\n#align tactic.get_user_attribute_name tactic.get_user_attribute_name\n\n/-- A tactic to set either a basic attribute or a user attribute.\n  If the user attribute has a parameter, the default value will be used.\n  This tactic raises an error if there is no `inhabited` instance for the parameter type. -/\nunsafe def set_attribute (attr_name : Name) (c_name : Name) (persistent := true)\n    (prio : Option Nat := none) : tactic Unit := do\n  get_decl c_name <|> throwError \"unknown declaration {\u2190 c_name}\"\n  let s \u2190 try_or_report_error (set_basic_attribute attr_name c_name persistent prio)\n  let Sum.inr msg \u2190 return s |\n    skip\n  if\n        msg =\n          (f! \"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute\").toString then\n      do\n      let user_attr_nm \u2190 get_user_attribute_name attr_name\n      let user_attr_const \u2190 mk_const user_attr_nm\n      let tac \u2190\n        eval_pexpr (tactic Unit)\n              ``(user_attribute.set $(user_attr_const) $(q(c_name)) default $(q(persistent))) <|>\n            throwError \"Cannot set attribute @[{(\u2190 attr_name)}].\n              The corresponding user attribute {\u2190\n                user_attr_nm} has a parameter without a default value.\n              Solution: provide an `inhabited` instance.\"\n      tac\n    else fail msg\n#align tactic.set_attribute tactic.set_attribute\n\nend Tactic\n\n/-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),\nand returns the value associated with this key if it exists.\nOtherwise, it fails.\n-/\nunsafe def list.find_defeq (red : Tactic.Transparency) {v} (m : List (expr \u00d7 v)) (e : expr) :\n    tactic (expr \u00d7 v) :=\n  m.findM fun \u27e8e', val\u27e9 => tactic.is_def_eq e e' red\n#align list.find_defeq list.find_defeq\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/Core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.06465348204835548, "lm_q1q2_score": 0.028555697742981077}}
{"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 \u2192 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 \u2192 B)\n(map_op' : \u2200 {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 (\u03bb _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := \u03bb 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) (\u03bb _, A \u2192 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 \u2192 B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : \u2200 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 \u2192 B) (h : f' = \u21d1f) : my_hom A B :=\n{ to_fun := f',\n  map_op' := h.symm \u25b8 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 (\u03bb _, B) :=\n(map_op : \u2200 (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' := \u03bb 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 : \u2200 (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' := \u03bb 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 \u2192 has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F \u03b1 \u03b2` expresses that terms of type `F` have an\ninjective coercion to functions from `\u03b1` to `\u03b2`.\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*) (\u03b1 : out_param Sort*) (\u03b2 : out_param $ \u03b1 \u2192 Sort*) :=\n(coe : F \u2192 \u03a0 a : \u03b1, \u03b2 a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F \u03b1 \u03b2` where `\u03b2` depends on `a : \u03b1` -/\n\nvariables (F \u03b1 : Sort*) (\u03b2 : \u03b1 \u2192 Sort*)\n\nnamespace fun_like\n\nvariables {F \u03b1 \u03b2} [i : fun_like F \u03b1 \u03b2]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n  nolint dangerous_instance] -- `\u03b1` and `\u03b2` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (\u03bb _, \u03a0 a : \u03b1, \u03b2 a) := { coe := fun_like.coe }\n\n@[simp] \n\ntheorem coe_injective : function.injective (coe_fn : F \u2192 \u03a0 a : \u03b1, \u03b2 a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a) \u2194 f = g :=\n\u27e8\u03bb h, @coe_injective _ _ _ i _ _ h, \u03bb h, by cases h; refl\u27e9\n\ntheorem ext' {f g : F} (h : (f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g \u2194 ((f : \u03a0 a : \u03b1, \u03b2 a) = (g : \u03a0 a : \u03b1, \u03b2 a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : \u2200 (x : \u03b1), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g \u2194 (\u2200 x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h\u2081 : f = g) (x : \u03b1) : f x = g x :=\ncongr_fun (congr_arg _ h\u2081) x\n\nlemma ne_iff {f g : F} : f \u2260 g \u2194 \u2203 a, f a \u2260 g a :=\next_iff.not.trans not_forall\n\nlemma exists_ne {f g : F} (h : f \u2260 g) : \u2203 x, f x \u2260 g x :=\nne_iff.mp h\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F \u03b1 (\u03bb _, \u03b2)` where `\u03b2` does not depend on `a : \u03b1` -/\n\nvariables {F \u03b1 \u03b2 : Sort*} [i : fun_like F \u03b1 (\u03bb _, \u03b2)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : \u03b1} (h\u2081 : f = g) (h\u2082 : x = y) : f x = g y :=\ncongr (congr_arg _ h\u2081) h\u2082\n\nprotected lemma congr_arg (f : F) {x y : \u03b1} (h\u2082 : x = y) : f x = f y :=\ncongr_arg _ h\u2082\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\u2014programming the prover\u2014is 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\u2026sub)goals until it cannot\nbe applied any further. -/\n\nlemma repeat_example :\n  even 4 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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  \u00ac 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\u2082 :\n  even 4 \u2227 even 7 \u2227 even 3 \u2227 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 \u2026\",\n  intro_and_even\n\nmeta def hello_then_intro_and_even : tactic unit :=\ndo\n  tactic.trace \"Proving evenness \u2026\",\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 \u2190 tactic.local_context,\n  tactic.trace ctx,\n  tactic.trace \"target:\",\n  P \u2190 tactic.target,\n  tactic.trace P,\n  tactic.trace \"all missing proofs:\",\n  Hs \u2190 tactic.get_goals,\n  tactic.trace Hs,\n  \u03c4s \u2190 list.mmap tactic.infer_type Hs,\n  tactic.trace \u03c4s\n\nlemma even_18_and_even_20 (\u03b1 : Type) (a : \u03b1) :\n  even 18 \u2227 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 \u2190 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  \u03c4 \u2190 tactic.infer_type h,\n  tactic.trace \u03c4,\n  tactic.trace \"type of type of h:\",\n  \u03c5 \u2190 tactic.infer_type \u03c4,\n  tactic.trace \u03c5,\n  tactic.apply h\n\nmeta def exact_list : list expr \u2192 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 \u2190 tactic.local_context,\n  exact_list hs\n\nlemma app_of_app {\u03b1 : Type} {p : \u03b1 \u2192 Prop} {a : \u03b1}\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 `\u2115 [] : 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  `(\u2115) : expr)\n#check (expr.mvar `uniq_name `pp_name `(\u2115) : expr)\n#check (expr.pi `pp_name binder_info.default `(\u2115)\n  (expr.sort level.zero) : expr)\n#check (expr.lam `pp_name binder_info.default `(\u2115)\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 (\u03bbn : \u2115, 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\u2081 : pexpr := ``(list.map (\u03bbn, n + 1) [1, 2, 3]),\n  let e\u2082 : pexpr := ``(list.map _ [1, 2, 3]),\n  tactic.trace e\u2081,\n  tactic.trace e\u2082\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 : \u2115),\n  let e : expr := `(%%x + 1),\n  tactic.trace e\n\nrun_cmd do\n  let x : expr  := `(@id \u2115),\n  let e : pexpr := ``(list.map %%x),\n  tactic.trace e\n\nrun_cmd do\n  let x : expr  := `(@id \u2115),\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) \u2190 tactic.target,\n  tactic.trace a,\n  tactic.trace b,\n  tactic.trace c,\n  `(@eq %%\u03b1 %%l %%r) \u2190 tactic.target,\n  tactic.trace \u03b1,\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 \u2190 tactic.get_env,\n  tactic.trace (environment.fold env 0 (\u03bbdecl n, n + 1))\n\n\n/- ## First Example: A Conjuction-Destructing Tactic\n\nWe define a `destruct_and` tactic that automates the elimination of `\u2227` in\npremises, automating proofs such as these: -/\n\nlemma abcd_a (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  a :=\nand.elim_left h\n\nlemma abcd_b (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  b :=\nand.elim_left (and.elim_left (and.elim_right h))\n\nlemma abcd_bc (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  b \u2227 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 \u2192 tactic unit\n| h :=\n  do\n    t \u2190 tactic.infer_type h,\n    match t with\n    | `(%%a \u2227 %%b) :=\n      tactic.exact h\n      <|>\n      do {\n        ha \u2190 tactic.to_expr ``(and.elim_left %%h),\n        destruct_and_helper ha }\n      <|>\n      do {\n        hb \u2190 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 \u2190 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 \u2227 b \u2227 c) :\n  a :=\nby destruct_and `h\n\nlemma abc_b (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  b :=\nby destruct_and `h\n\nlemma abc_bc (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  b \u2227 c :=\nby destruct_and `h\n\nlemma abc_ac (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  a \u2227 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 \u2192 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 \u2190 tactic.get_env,\n  pure (environment.fold env [] (\u03bbdecl 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 \u2190 get_all_theorems,\n  list.mfirst (\u03bbnam,\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 : \u2115) (h : x = y) :\n  y = x :=\nby prove_direct\n\nlemma nat.eq_symm\u2082 (x y : \u2115) (h : x = y) :\n  y = x :=\nby library_search\n\nlemma list.reverse_twice (xs : list \u2115) :\n  list.reverse (list.reverse xs) = xs :=\nby prove_direct\n\nlemma list.reverse_twice_symm (xs : list \u2115) :\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\u2082 (xs : list \u2115) :\n  list.reverse (list.reverse xs) = xs :=\nby prove_direct_symm\n\nlemma list.reverse_twice_symm\u2082 (xs : list \u2115) :\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": "\n/-- Convert a character into a `UInt8`, by truncating (reducing modulo 256) if necessary. -/\ndef Char.toUInt8 (n : Char) : UInt8 := n.1.toUInt8\n\ntheorem Char.utf8Size_pos (c : Char) : 0 < c.utf8Size := by\n  simp only [utf8Size]\n  repeat (split; decide)\n  decide\n\ntheorem String.csize_pos : (c : Char) \u2192 0 < String.csize c := Char.utf8Size_pos\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/Data/Char.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.06278921210458951, "lm_q1q2_score": 0.028459954313956294}}
{"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\u27e8punit.star\u27e9\n\ninstance : decidable_eq punit :=\n\u03bb 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) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Meta.Tactic.Util\nimport Lean.Util.ForEachExpr\nimport Lean.Util.OccursCheck\nimport Lean.Elab.Tactic.Basic\n\nnamespace Lean.Elab.Term\nopen Tactic (TacticM evalTactic getUnsolvedGoals withTacticInfoContext)\nopen Meta\n\n/-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/\nprivate def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr :=\n  -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry`\n  withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do\n    elabTerm stx expectedType? false\n\n/--\n  Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`.\n  It returns `true` if it succeeded, and `false` otherwise.\n  It is used to implement `synthesizeSyntheticMVars`. -/\nprivate def resumePostponed (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool :=\n  withRef stx <| mvarId.withContext do\n    let s \u2190 saveState\n    try\n      withSavedContext savedContext do\n        let mvarDecl     \u2190 getMVarDecl mvarId\n        let expectedType \u2190 instantiateMVars mvarDecl.type\n        withInfoHole mvarId do\n          let result \u2190 resumeElabTerm stx expectedType (!postponeOnError)\n          /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx.\n            That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/\n          let result \u2190 withRef stx <| ensureHasType expectedType result\n          /- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/\n          if (\u2190 occursCheck mvarId result) then\n            mvarId.assign result\n            return true\n          else\n            return false\n    catch\n     | ex@(.internal id _) =>\n       if id == postponeExceptionId then\n         s.restore (restoreInfo := true)\n         return false\n       else\n         throw ex\n     | ex@(.error ..) =>\n       if postponeOnError then\n         s.restore (restoreInfo := true)\n         return false\n       else\n         logException ex\n         return true\n\n/--\n  Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances\n  are used. It also logs any error message produced. -/\nprivate def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool :=\n  instMVar.withContext do\n    try\n      synthesizeInstMVarCore instMVar\n    catch\n      | ex@(.error ..) => logException ex; return true\n      | _              => unreachable!\n\n/--\n  Try to synthesize `mvarId` by starting using a default instance with the give privority.\n  This method succeeds only if the metavariable of fully synthesized.\n\n  Remark: In the past, we would return a list of pending TC problems, but this was problematic since\n  a default instance may create subproblems that cannot be solved.\n\n  Remark: The new approach also has limitations because other pending metavariables are not taken into account\n  while backtraking. That is, we fail to synthesize `mvarId` because we reach subproblems that are stuck,\n  but we could \"unstuck\" them if we tried to solve other pending metavariables. Considering all pending metavariables\n  into a single backtracking search seems to be too expensive, and potentially generate incomprehensible error messages.\n  This is particularly true if we consider pending metavariables for \"postponed\" elaboration steps.\n  Here is an example that demonstrate this issue. The example considers we are using the old `binrel%` elaborator which was\n  disconnected from `binop%`.\n  ```\n  example (a : Int) (b c : Nat) : a = \u2191b - \u2191c := sorry\n  ```\n  We have two pending coercions for the `\u2191` and `HSub ?m.220 ?m.221 ?m.222`.\n  When we did not use a backtracking search here, then the homogenous default instance for `HSub`.\n  ```\n  instance [Sub \u03b1] : HSub \u03b1 \u03b1 \u03b1 where\n  ```\n  would be applied first, and would propagate the expected type `Int` to the pending coercions which would now be unblocked.\n\n  Instead of performing a backtracking search that considers all pending metavariables, we improved the `binrel%` elaborator.\n-/\nprivate partial def synthesizeUsingDefaultPrio (mvarId : MVarId) (prio : Nat) : TermElabM Bool :=\n  mvarId.withContext do\n    let mvarType \u2190 mvarId.getType\n    match (\u2190 isClass? mvarType) with\n    | none => return false\n    | some className =>\n      match (\u2190 getDefaultInstances className) with\n      | [] => return false\n      | defaultInstances =>\n        for (defaultInstance, instPrio) in defaultInstances do\n          if instPrio == prio then\n            if (\u2190 synthesizeUsingDefaultInstance mvarId defaultInstance) then\n              return true\n        return false\nwhere\n  synthesizeUsingDefault (mvarId : MVarId) : TermElabM Bool := do\n    for prio in (\u2190 getDefaultInstancesPriorities) do\n      if (\u2190 synthesizeUsingDefaultPrio mvarId prio) then\n        return true\n    return false\n\n  synthesizePendingInstMVar' (mvarId : MVarId) : TermElabM Bool :=\n    commitWhen <| mvarId.withContext do\n      try\n        synthesizeInstMVarCore mvarId\n      catch _ =>\n        return false\n\n  synthesizeUsingInstancesStep (mvarIds : List MVarId) : TermElabM (List MVarId) :=\n    mvarIds.filterM fun mvarId => do\n      if (\u2190 synthesizePendingInstMVar' mvarId) then\n        return false\n      else\n        return true\n\n  synthesizeUsingInstances (mvarIds : List MVarId) : TermElabM (List MVarId) := do\n    let mvarIds' \u2190 synthesizeUsingInstancesStep mvarIds\n    if mvarIds'.length < mvarIds.length then\n      synthesizeUsingInstances mvarIds'\n    else\n      return mvarIds'\n\n  synthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM Bool :=\n    commitWhen do\n      let candidate \u2190 mkConstWithFreshMVarLevels defaultInstance\n      let (mvars, bis, _) \u2190 forallMetaTelescopeReducing (\u2190 inferType candidate)\n      let candidate := mkAppN candidate mvars\n      trace[Elab.defaultInstance] \"{toString (mkMVar mvarId)}, {mkMVar mvarId} : {\u2190 inferType (mkMVar mvarId)} =?= {candidate} : {\u2190 inferType candidate}\"\n      /- The `coeAtOutParam` feature may mark output parameters of local instances as `syntheticOpaque`.\n         This kind of parameter is not assignable by default. We use `withAssignableSyntheticOpaque` to workaround this behavior\n         when processing default instances. TODO: try to avoid `withAssignableSyntheticOpaque`. -/\n      if (\u2190 withAssignableSyntheticOpaque <| isDefEqGuarded (mkMVar mvarId) candidate) then\n        -- Succeeded. Collect new TC problems\n        trace[Elab.defaultInstance] \"isDefEq worked {mkMVar mvarId} : {\u2190 inferType (mkMVar mvarId)} =?= {candidate} : {\u2190 inferType candidate}\"\n        let mut pending := []\n        for i in [:bis.size] do\n          if bis[i]! == BinderInfo.instImplicit then\n            pending := mvars[i]!.mvarId! :: pending\n        synthesizePending pending\n      else\n        return false\n\n  synthesizeSomeUsingDefault? (mvarIds : List MVarId) : TermElabM (Option (List MVarId)) := do\n    match mvarIds with\n    | [] => return none\n    | mvarId :: mvarIds =>\n      if (\u2190 synthesizeUsingDefault mvarId) then\n        return mvarIds\n      else if let some mvarIds' \u2190 synthesizeSomeUsingDefault? mvarIds then\n        return mvarId :: mvarIds'\n      else\n        return none\n\n  synthesizePending (mvarIds : List MVarId) : TermElabM Bool := do\n    let mvarIds \u2190 synthesizeUsingInstances mvarIds\n    if mvarIds.isEmpty then return true\n    let some mvarIds \u2190 synthesizeSomeUsingDefault? mvarIds | return false\n    synthesizePending mvarIds\n\n/-- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/\nprivate def synthesizeSomeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do\n  let rec visit (pendingMVars : List MVarId) (pendingMVarsNew : List MVarId) : TermElabM Bool := do\n    match pendingMVars with\n    | [] => return false\n    | mvarId :: pendingMVars =>\n      let some mvarDecl \u2190 getSyntheticMVarDecl? mvarId | visit pendingMVars (mvarId :: pendingMVarsNew)\n      match mvarDecl.kind with\n      | .typeClass =>\n        if (\u2190 withRef mvarDecl.stx <| synthesizeUsingDefaultPrio mvarId prio) then\n          modify fun s => { s with pendingMVars := pendingMVars.reverse ++ pendingMVarsNew }\n          return true\n        else\n          visit pendingMVars (mvarId :: pendingMVarsNew)\n      | _ => visit pendingMVars (mvarId :: pendingMVarsNew)\n  /- Recall that s.pendingMVars is essentially a stack. The first metavariable was the last one created.\n     We want to apply the default instance in reverse creation order. Otherwise,\n     `toString 0` will produce a `OfNat String _` cannot be synthesized error. -/\n  visit (\u2190 get).pendingMVars.reverse []\n\n/--\n  Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault`\n  Return true if something was synthesized. -/\nprivate def synthesizeUsingDefault : TermElabM Bool := do\n  let prioSet \u2190 getDefaultInstancesPriorities\n  /- Recall that `prioSet` is stored in descending order -/\n  for prio in prioSet do\n    if (\u2190 synthesizeSomeUsingDefaultPrio prio) then\n      return true\n  return false\n\n/--\nWe use this method to report typeclass (and coercion) resolution problems that are \"stuck\".\nThat is, there is nothing else to do, and we don't have enough information to synthesize them using TC resolution.\n-/\ndef reportStuckSyntheticMVar (mvarId : MVarId) (ignoreStuckTC := false) : TermElabM Unit := do\n  let some mvarSyntheticDecl \u2190 getSyntheticMVarDecl? mvarId | return ()\n  withRef mvarSyntheticDecl.stx do\n    match mvarSyntheticDecl.kind with\n    | .typeClass =>\n      unless ignoreStuckTC do\n         mvarId.withContext do\n          let mvarDecl \u2190 getMVarDecl mvarId\n          unless (\u2190 MonadLog.hasErrors) do\n            throwError \"typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}\"\n    | .coe header expectedType e f? =>\n      mvarId.withContext do\n        throwTypeMismatchError header expectedType (\u2190 inferType e) e f?\n          m!\"failed to create type class instance for{indentExpr (\u2190 getMVarDecl mvarId).type}\"\n    | _ => unreachable! -- TODO handle other cases.\n\n/--\n  Report an error for each synthetic metavariable that could not be resolved.\n  Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments.\n-/\nprivate def reportStuckSyntheticMVars (ignoreStuckTC := false) : TermElabM Unit := do\n  let pendingMVars \u2190 modifyGet fun s => (s.pendingMVars, { s with pendingMVars := [] })\n  for mvarId in pendingMVars do\n    reportStuckSyntheticMVar mvarId ignoreStuckTC\n\nprivate def getSomeSynthethicMVarsRef : TermElabM Syntax := do\n  for mvarId in (\u2190 get).pendingMVars do\n    if let some decl \u2190 getSyntheticMVarDecl? mvarId then\n      if decl.stx.getPos?.isSome then\n        return decl.stx\n  return .missing\n\n/--\n  Generate an nicer error message for stuck universe constraints.\n-/\nprivate def throwStuckAtUniverseCnstr : TermElabM Unit := do\n  -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property\n  let entries \u2190 getPostponed\n  let mut found : HashSet (Level \u00d7 Level) := {}\n  let mut uniqueEntries := #[]\n  for entry in entries do\n    let mut lhs := entry.lhs\n    let mut rhs := entry.rhs\n    if Level.normLt rhs lhs then\n      (lhs, rhs) := (rhs, lhs)\n    unless found.contains (lhs, rhs) do\n      found := found.insert (lhs, rhs)\n      uniqueEntries := uniqueEntries.push entry\n  for i in [1:uniqueEntries.size] do\n    logErrorAt uniqueEntries[i]!.ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[i]!)\n  throwErrorAt uniqueEntries[0]!.ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[0]!)\n\n/--\n  Try to solve postponed universe constraints, and throws an exception if there are stuck constraints.\n\n  Remark: in previous versions, each `isDefEq u v` invocation would fail if there\n  were pending universe level constraints. With this old approach, we were not able\n  to process\n  ```\n  Functor.map Prod.fst (x s)\n  ```\n  because after elaborating `Prod.fst` and trying to ensure its type\n  match the expected one, we would be stuck at the universe constraint:\n  ```\n  u =?= max u ?v\n  ```\n  Another benefit of using `withoutPostponingUniverseConstraints` is better error messages. Instead\n  of getting a mysterious type mismatch constraint, we get a list of\n  universe contraints the system is stuck at.\n-/\nprivate def processPostponedUniverseContraints : TermElabM Unit := do\n  unless (\u2190 processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do\n    throwStuckAtUniverseCnstr\n\n/--\n  Remove `mvarId` from the `syntheticMVars` table. We use this method after\n  the metavariable has been synthesized.\n-/\nprivate def markAsResolved (mvarId : MVarId) : TermElabM Unit :=\n  modify fun s => { s with syntheticMVars := s.syntheticMVars.erase mvarId }\n\nmutual\n\n  /--\n  Try to synthesize a term `val` using the tactic code `tacticCode`, and then assign `mvarId := val`.\n  -/\n  partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := withoutAutoBoundImplicit do\n    /- Recall, `tacticCode` is the whole `by ...` expression. -/\n    let code := tacticCode[1]\n    instantiateMVarDeclMVars mvarId\n    /-\n    TODO: consider using `runPendingTacticsAt` at `mvarId` local context and target type.\n    Issue #1380 demonstrates that the goal may still contain pending metavariables.\n    It happens in the following scenario we have a term `foo A (by tac)` where `A` has been postponed\n    and contains nested `by ...` terms. The pending metavar list contains two metavariables: ?m1 (for `A`) and\n    `?m2` (for `by tac`). When `A` is resumed, it creates a new metavariable `?m3` for the nested `by ...` term in `A`.\n    `?m3` is after `?m2` in the to-do list. Then, we execute `by tac` for synthesizing `?m2`, but its type depends on\n    `?m3`. We have considered putting `?m3` at `?m2` place in the to-do list, but this is not super robust.\n    The ideal solution is to make sure a tactic \"resolves\" all pending metavariables nested in their local contex and target type\n    before starting tactic execution. The procedure would be a generalization of `runPendingTacticsAt`. We can try to combine\n    it with `instantiateMVarDeclMVars` to make sure we do not perform two traversals.\n    Regarding issue #1380, we addressed the issue by avoiding the elaboration postponement step. However, the same issue can happen\n    in more complicated scenarios.\n    -/\n    try\n      let remainingGoals \u2190 withInfoHole mvarId <| Tactic.run mvarId do\n        withTacticInfoContext tacticCode do\n          -- also put an info node on the `by` keyword specifically -- the token may be `canonical` and thus shown in the info\n          -- view even though it is synthetic while a node like `tacticCode` never is (#1990)\n          withTacticInfoContext tacticCode[0] do\n            evalTactic code\n        synthesizeSyntheticMVars (mayPostpone := false)\n      unless remainingGoals.isEmpty do\n        reportUnsolvedGoals remainingGoals\n    catch ex =>\n      if (\u2190 read).errToSorry then\n        for mvarId in (\u2190 getMVars (mkMVar mvarId)) do\n          mvarId.admit\n        logException ex\n      else\n        throw ex\n\n  /-- Try to synthesize the given pending synthetic metavariable. -/\n  private partial def synthesizeSyntheticMVar (mvarId : MVarId) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do\n    let some mvarSyntheticDecl \u2190 getSyntheticMVarDecl? mvarId | return true -- The metavariable has already been synthesized\n    withRef mvarSyntheticDecl.stx do\n    match mvarSyntheticDecl.kind with\n    | .typeClass => synthesizePendingInstMVar mvarId\n    | .coe _header? expectedType e _f? => mvarId.withContext do\n      if (\u2190 withDefault do isDefEq (\u2190 inferType e) expectedType) then\n        -- Types may be defeq now due to mvar assignments, type class\n        -- defaulting, etc.\n        if (\u2190 occursCheck mvarId e) then\n          mvarId.assign e\n          return true\n      if let .some coerced \u2190 coerce? e expectedType then\n        if (\u2190 occursCheck mvarId coerced) then\n          mvarId.assign coerced\n          return true\n      return false\n    -- NOTE: actual processing at `synthesizeSyntheticMVarsAux`\n    | .postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarId postponeOnError\n    | .tactic tacticCode savedContext =>\n      withSavedContext savedContext do\n        if runTactics then\n          runTactic mvarId tacticCode\n          return true\n        else\n          return false\n  /--\n    Try to synthesize the current list of pending synthetic metavariables.\n    Return `true` if at least one of them was synthesized. -/\n  private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do\n    let ctx \u2190 read\n    traceAtCmdPos `Elab.resuming fun _ =>\n      m!\"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}\"\n    let pendingMVars    := (\u2190 get).pendingMVars\n    let numSyntheticMVars := pendingMVars.length\n    -- We reset `pendingMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`.\n    modify fun s => { s with pendingMVars := [] }\n    -- Recall that `pendingMVars` is a list where head is the most recent pending synthetic metavariable.\n    -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created.\n    -- It would not be incorrect to use `filterM`.\n    let remainingPendingMVars \u2190 pendingMVars.filterRevM fun mvarId => do\n       -- We use `traceM` because we want to make sure the metavar local context is used to trace the message\n       traceM `Elab.postpone (mvarId.withContext do addMessageContext m!\"resuming {mkMVar mvarId}\")\n       let succeeded \u2190 synthesizeSyntheticMVar mvarId postponeOnError runTactics\n       if succeeded then markAsResolved mvarId\n       trace[Elab.postpone] if succeeded then format \"succeeded\" else format \"not ready yet\"\n       pure !succeeded\n    -- Merge new synthetic metavariables with `remainingPendingMVars`, i.e., metavariables that still couldn't be synthesized\n    modify fun s => { s with pendingMVars := s.pendingMVars ++ remainingPendingMVars }\n    return numSyntheticMVars != remainingPendingMVars.length\n\n  /--\n    Try to process pending synthetic metavariables. If `mayPostpone == false`,\n    then `pendingMVars` is `[]` after executing this method.\n\n    It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made.\n    If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available)\n    metavariables that are still unresolved, and then tries to resolve metavariables\n    with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to\n    a \"best option\". If, after that, we still haven't made progress, we report \"stuck\" errors.\n\n    Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. Then,\n    pending TC problems become implicit parameters for the simp theorem.\n  -/\n  partial def synthesizeSyntheticMVars (mayPostpone := true) (ignoreStuckTC := false) : TermElabM Unit := do\n    let rec loop (_ : Unit) : TermElabM Unit := do\n      withRef (\u2190 getSomeSynthethicMVarsRef) <| withIncRecDepth do\n        unless (\u2190 get).pendingMVars.isEmpty do\n          if \u2190 synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then\n            loop ()\n          else if !mayPostpone then\n            /- Resume pending metavariables with \"elaboration postponement\" disabled.\n               We postpone elaboration errors in this step by setting `postponeOnError := true`.\n               Example:\n               ```\n               #check let x := \u27e81, 2\u27e9; Prod.fst x\n               ```\n               The term `\u27e81, 2\u27e9` can't be elaborated because the expected type is not know.\n               The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known.\n               When we execute the following step with \"elaboration postponement\" disabled,\n               the elaborator fails at `\u27e81, 2\u27e9` and postpones it, and succeeds at `x` and learns\n               that its type must be of the form `Prod ?\u03b1 ?\u03b2`.\n\n               Recall that we postponed `x` at `Prod.fst x` because its type it is not known.\n               We the type of `x` may learn later its type and it may contain implicit and/or auto arguments.\n               By disabling postponement, we are essentially giving up the opportunity of learning `x`s type\n               and assume it does not have implict and/or auto arguments. -/\n            if \u2190 withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := true) (runTactics := false) then\n              loop ()\n            else if \u2190 synthesizeUsingDefault then\n              loop ()\n            else if \u2190 withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then\n              loop ()\n            else if \u2190 synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then\n              loop ()\n            else\n              reportStuckSyntheticMVars ignoreStuckTC\n    loop ()\n    unless mayPostpone do\n     processPostponedUniverseContraints\nend\n\ndef synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := false) : TermElabM Unit :=\n  synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := ignoreStuckTC)\n\n/-- Keep invoking `synthesizeUsingDefault` until it returns false. -/\nprivate partial def synthesizeUsingDefaultLoop : TermElabM Unit := do\n  if (\u2190 synthesizeUsingDefault) then\n    synthesizeSyntheticMVars (mayPostpone := true)\n    synthesizeUsingDefaultLoop\n\ndef synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do\n  synthesizeSyntheticMVars (mayPostpone := true)\n  synthesizeUsingDefaultLoop\n\nprivate partial def withSynthesizeImp {\u03b1} (k : TermElabM \u03b1) (mayPostpone : Bool) (synthesizeDefault : Bool) : TermElabM \u03b1 := do\n  let pendingMVarsSaved := (\u2190 get).pendingMVars\n  modify fun s => { s with pendingMVars := [] }\n  try\n    let a \u2190 k\n    synthesizeSyntheticMVars mayPostpone\n    if mayPostpone && synthesizeDefault then\n      synthesizeUsingDefaultLoop\n    return a\n  finally\n    modify fun s => { s with pendingMVars := s.pendingMVars ++ pendingMVarsSaved }\n\n/--\n  Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved.\n  If `mayPostpone == false`, then all of them must be synthesized.\n  Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/\n@[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m \u03b1) (mayPostpone := false) : m \u03b1 :=\n  monadMap (m := TermElabM) (withSynthesizeImp \u00b7 mayPostpone (synthesizeDefault := true)) k\n\n/-- Similar to `withSynthesize`, but sets `mayPostpone` to `true`, and do not use `synthesizeUsingDefault` -/\n@[inline] def withSynthesizeLight [MonadFunctorT TermElabM m] [Monad m] (k : m \u03b1) : m \u03b1 :=\n  monadMap (m := TermElabM) (withSynthesizeImp \u00b7 (mayPostpone := true) (synthesizeDefault := false)) k\n\n/-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/\ndef elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=\n  withRef stx do\n    instantiateMVars (\u2190 withSynthesize <| elabTerm stx expectedType?)\n\n/--\nCollect unassigned metavariables at `e` that have associated tactic blocks, and then execute them using `runTactic`.\nWe use this method at the `match .. with` elaborator when it cannot be postponed anymore, but it is still waiting\nthe result of a tactic block.\n-/\ndef runPendingTacticsAt (e : Expr) : TermElabM Unit := do\n  for mvarId in (\u2190 getMVars e) do\n    let mvarId \u2190 getDelayedMVarRoot mvarId\n    if let some { kind := .tactic tacticCode savedContext, .. } \u2190 getSyntheticMVarDecl? mvarId then\n      withSavedContext savedContext do\n        runTactic mvarId tacticCode\n        markAsResolved mvarId\n\nbuiltin_initialize\n  registerTraceClass `Elab.resume\n\nend Lean.Elab.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/Lean/Elab/SyntheticMVars.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.08756383535613607, "lm_q1q2_score": 0.028391296236563935}}
{"text": "open classical\nvariables (\u03b1 : Type) (p q : \u03b1 \u2192 Prop)\nvariable a : \u03b1\nvariable r : Prop\ntheorem c4_1 : r\u2192(\u2203 x:\u03b1,r):=\n    begin\n        rw[exists_],\n    end", "meta": {"author": "ChrisHughes24", "repo": "leanstuff", "sha": "9efa85f72efaccd1d540385952a6acc18fce8687", "save_path": "github-repos/lean/ChrisHughes24-leanstuff", "path": "github-repos/lean/ChrisHughes24-leanstuff/leanstuff-9efa85f72efaccd1d540385952a6acc18fce8687/test2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.060975182571362606, "lm_q1q2_score": 0.028347458192205726}}
{"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 \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 {\u03c3 : Type u}\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3,\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 Lean.CoreM\n\n#eval Lean.addDecl <| .mutualDefnDecl [{\n  name := `False_intro\n  levelParams := []\n  type := .const ``False []\n  value := .const `False_intro []\n  hints := .opaque\n  safety := .partial\n}]\n\ntheorem False.intro : False := False_intro\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/partialIssue.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.06465348565285166, "lm_q1q2_score": 0.02830681531846136}}
{"text": "import Std.Tactic.SeqFocus\n\nexample : (True \u2227 (\u2203 x : Nat, x = x)) \u2227 True := by\n  constructor\n  constructor\n  -- error: too many tactics\n  fail_if_success map_tacs [trivial, exact \u27e80, rfl\u27e9, trivial, trivial]\n  -- error: not enough tactics\n  fail_if_success map_tacs [trivial, exact \u27e80, rfl\u27e9]\n  map_tacs [trivial, exact \u27e80, rfl\u27e9, trivial]\n\nexample : ((True \u2227 True) \u2227 (\u2203 x : Nat, x = x)) \u2227 (True \u2227 (\u2203 x : Nat, x = x)) := by\n  constructor\n  constructor\n  map_tacs [(constructor; trivial), exact \u27e80, rfl\u27e9, constructor]\n  trivial\n  trivial\n  exact \u27e80, rfl\u27e9\n\nexample : (True \u2227 (\u2203 x : Nat, x = x)) \u2227 True := by\n  constructor\n  -- error: not enough tactics\n  fail_if_success constructor <;> [trivial]\n  map_tacs [constructor <;> [trivial, exact \u27e80, rfl\u27e9], 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) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Daniel Selsam\n-/\nimport Search.Inspect.Basic\nimport Search.NTactic.Basic\nimport Lean\n\nnamespace Search\nnamespace NTactic\n\ndef chooseBoolsDoNothing : NTacticM Unit := do\n  Lean.Meta.setMCtx {}\n  let x \u2190 choice #[false, true]\n  if x \u2227 \u00ac x then deadend else pure ()\n\nexample : \u2200 (n : Nat), 2 * n + 1 < 3 * n + 2 :=\n  sorry\n  -- TODO: this will try to execute `inspect` in the interpreter\n  -- (right now it only works in compiled code)\n  -- by search chooseBoolsDoNothing\n\nend NTactic\nend Search\n", "meta": {"author": "dselsam", "repo": "search", "sha": "67003b859d2228d291a3873af6279c1f61430c64", "save_path": "github-repos/lean/dselsam-search", "path": "github-repos/lean/dselsam-search/search-67003b859d2228d291a3873af6279c1f61430c64/Search/NTactic/Examples.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.06754669583231306, "lm_q1q2_score": 0.028281592782178115}}
{"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 \u2192 Type v}\nvariables [applicative F] [is_lawful_applicative F]\nvariables {\u03b1 \u03b2 \u03b3 \u03c3 : Type u}\n\nlemma applicative.map_seq_map (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (g : \u03c3 \u2192 \u03b2) (x : F \u03b1) (y : F \u03c3) :\n  (f <$> x) <*> (g <$> y) = (flip (\u2218) g \u2218 f) <$> x <*> y :=\nby simp [flip] with functor_norm\n\nlemma applicative.pure_seq_eq_map' (f : \u03b1 \u2192 \u03b2) : (<*>) (pure f : F (\u03b1 \u2192 \u03b2)) = (<$>) f :=\nby ext; simp with functor_norm\n\ntheorem applicative.ext {F} : \u2200 {A1 : applicative F} {A2 : applicative F}\n  [@is_lawful_applicative F A1] [@is_lawful_applicative F A2]\n  (H1 : \u2200 {\u03b1 : Type u} (x : \u03b1),\n    @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)\n  (H2 : \u2200 {\u03b1 \u03b2 : Type u} (f : F (\u03b1 \u2192 \u03b2)) (x : F \u03b1),\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 \u03b1 x, apply H1},\n  obtain rfl : @s1 = @s2, {funext \u03b1 \u03b2 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 \u03b1 \u03b2 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 \u2192 Type w} {G : Type v \u2192 Type u}\n\nvariables [applicative F] [applicative G]\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables {\u03b1 \u03b2 \u03b3 : Type v}\n\nlemma map_pure (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (f <$> pure x : comp F G \u03b2) = pure (f x) :=\ncomp.ext $ by simp\n\nlemma seq_pure (f : comp F G (\u03b1 \u2192 \u03b2)) (x : \u03b1) :\n  f <*> pure x = (\u03bb g : \u03b1 \u2192 \u03b2, g x) <$> f :=\ncomp.ext $ by simp [(\u2218)] with functor_norm\n\n\n\nlemma pure_seq_eq_map (f : \u03b1 \u2192 \u03b2) (x : comp F G \u03b1) :\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  (\u03bb \u03b1 x, rfl) (\u03bb \u03b1 \u03b2 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  (\u03bb \u03b1 x, rfl) (\u03bb \u03b1 \u03b2 f x, show id <$> f <*> x = f <*> x, by rw id_map)\n\nopen is_comm_applicative\n\ninstance {f : Type u \u2192 Type w} {g : Type v \u2192 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,(\u2218)] 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 {\u03b1 \u03b2 : Type w}\n  {f : Type u \u2192 Type v} {g : Type w \u2192 Type u}\n  [applicative f] [applicative g]\n  (h : f (g (\u03b1 \u2192 \u03b2))) (x : f (g \u03b1)) :\n  comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl\n\ninstance {\u03b1} [has_one \u03b1] [has_mul \u03b1] : applicative (const \u03b1) :=\n{ pure := \u03bb \u03b2 x, (1 : \u03b1),\n  seq := \u03bb \u03b2 \u03b3 f x, (f * x : \u03b1) }\n\ninstance {\u03b1} [monoid \u03b1] : is_lawful_applicative (const \u03b1) :=\nby refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]\n\ninstance {\u03b1} [has_zero \u03b1] [has_add \u03b1] : applicative (add_const \u03b1) :=\n{ pure := \u03bb \u03b2 x, (0 : \u03b1),\n  seq := \u03bb \u03b2 \u03b3 f x, (f + x : \u03b1) }\n\ninstance {\u03b1} [add_monoid \u03b1] : is_lawful_applicative (add_const \u03b1) :=\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 CodeAction.Interface\nimport StatementAutoformalisation.Translate\nimport StatementAutoformalisation.Config.FixedPrompts\n\nnamespace Custom\n\ndef LLMParams : LLM.Params :=\n{\n  openAIModel := \"gpt-3.5-turbo\",\n  temperature := 2,\n  n := 1,\n  maxTokens := 200,\n  stopTokens := #[\":=\", \"\\n\\n/-\", \"\\n/-\", \"/-\"]\n  systemMessage := \n  \"You are a coding assistant who translates from natural language to Lean Theorem Prover code following examples.\n   Follow EXACTLY the examples given.\"\n}\n\ndef SentenceSimilarityParams : SentenceSimilarity.Params :=\n{\n  source := \"data/prompts.json\",\n  sentenceTransformersModel := \"all-mpnet-base-v2\",\n  kind := \"theorem\",\n  field := \"doc_string\",\n  nSim := 10\n}\n\ndef KeywordExtractionParams : KeywordExtraction.Params :=\n{\n  nKw := 0\n}\n\ndef PromptParams : Prompt.Params :=\n{\n  toLLMParams := LLMParams, \n  toSentenceSimilarityParams := #[SentenceSimilarityParams], \n  toKeywordExtractionParams := #[KeywordExtractionParams],\n  fixedPrompts := leanChatPrompts,\n  useNames := #[],\n  useModules := #[],\n  useMainCtx? := false,\n  printMessage := DeclarationWithDocstring.toMessage\n  mkSuffix := id,\n  processCompletion := fun comment completion => s!\"{printAsComment comment}\\n{completion}\"\n}\n\ndef InterfaceParams : Interface.Params DeclarationWithDocstring :=\n{\n  title := \"Translate comment to Lean theorem statement (with custom settings).\",\n  nearestOccurrence? := nearestComment,\n  extractText? := extractCommentText?,\n  action := fun stmt =>\n    Prompt.typecorrectTranslations \u27e8PromptParams, stmt\u27e9 >>= (pure \u00b7[0]!),\n  postProcess := fun _ => DeclarationWithDocstring.toString\n}\n\n@[codeActionProvider] def Action := performCodeAction InterfaceParams\n\nend Custom", "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/StatementAutoformalisation/Config/Custom.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.07263671037579261, "lm_q1q2_score": 0.028227935052644787}}
{"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 \u2190 resolveGlobalConstNoOverloadWithInfo stx[1]\n  liftTermElabM none do\n    IO.println (repr (\u2190 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": "import tactic.basic tactic\n\nopen tactic\n\n#print tactic.local_context\n#print expr.is_aux_decl\n#print tactic.clear\n#print tactic.interactive.clear\n\n\nnamespace tactic.interactive\n\nmeta def clear_aux_decl_aux : list expr \u2192 tactic unit\n| []     := skip\n| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l\n\nmeta def clear_aux_decl : tactic unit :=\nlocal_context >>= clear_aux_decl_aux\n\nend tactic.interactive\n\nmeta def h : tactic unit :=\ndo l \u2190 local_context, trace (l.filter (\u03bb e : expr, e.is_aux_decl)).length\n\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl,\n  finish\nend\n", "meta": {"author": "ChrisHughes24", "repo": "leanstuff", "sha": "9efa85f72efaccd1d540385952a6acc18fce8687", "save_path": "github-repos/lean/ChrisHughes24-leanstuff", "path": "github-repos/lean/ChrisHughes24-leanstuff/leanstuff-9efa85f72efaccd1d540385952a6acc18fce8687/clear_aux_decl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.08509904790742691, "lm_q1q2_score": 0.028177974585782268}}
{"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\u2081 v\u2082 u\u2081 u\u2082\n\nnamespace category_theory\n\nvariables {C : Type u\u2081} [category.{v\u2081} C]\n\nsection\nvariables {D : Type u\u2082} [category.{v\u2082} D]\n\nlemma left_adjoint_preserves_epi {F : C \u2964 D} {G : D \u2964 C} (adj : F \u22a3 G)\n  {X Y : C} {f : X \u27f6 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 \u2964 D} {G : D \u2964 C} (adj : F \u22a3 G)\n  {X Y : D} {f : X \u27f6 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 \u2964 D} [is_left_adjoint F] {X Y : C} {f : X \u27f6 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 \u2964 D} [is_right_adjoint F] {X Y : C} {f : X \u27f6 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 \u2964 D) [faithful F] {X Y : C} {f : X \u27f6 Y}\n  (hf : epi (F.map f)) : epi f :=\n\u27e8\u03bb Z g h H, F.map_injective $\n  by rw [\u2190cancel_epi (F.map f), \u2190F.map_comp, \u2190F.map_comp, H]\u27e9\n\nlemma faithful_reflects_mono (F : C \u2964 D) [faithful F] {X Y : C} {f : X \u27f6 Y}\n  (hf : mono (F.map f)) : mono f :=\n\u27e8\u03bb Z g h H, F.map_injective $\n  by rw [\u2190cancel_mono (F.map f), \u2190F.map_comp, \u2190F.map_comp, H]\u27e9\nend\n\n/--\nA split monomorphism is a morphism `f : X \u27f6 Y` admitting a retraction `retraction f : Y \u27f6 X`\nsuch that `f \u226b retraction f = \ud835\udfd9 X`.\n\nEvery split monomorphism is a monomorphism.\n-/\nclass split_mono {X Y : C} (f : X \u27f6 Y) :=\n(retraction : Y \u27f6 X)\n(id' : f \u226b retraction = \ud835\udfd9 X . obviously)\n\n/--\nA split epimorphism is a morphism `f : X \u27f6 Y` admitting a section `section_ f : Y \u27f6 X`\nsuch that `section_ f \u226b f = \ud835\udfd9 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 \u27f6 Y) :=\n(section_ : Y \u27f6 X)\n(id' : section_ \u226b f = \ud835\udfd9 Y . obviously)\n\n/-- The chosen retraction of a split monomorphism. -/\ndef retraction {X Y : C} (f : X \u27f6 Y) [split_mono f] : Y \u27f6 X := split_mono.retraction f\n@[simp, reassoc]\nlemma split_mono.id {X Y : C} (f : X \u27f6 Y) [split_mono f] : f \u226b retraction f = \ud835\udfd9 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 \u27f6 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 \u27f6 Y) [split_mono f] [epi f] : is_iso f :=\n\u27e8\u27e8retraction f, \u27e8by simp, by simp [\u2190 cancel_epi f]\u27e9\u27e9\u27e9\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 \u27f6 Y) [split_epi f] : Y \u27f6 X := split_epi.section_ f\n@[simp, reassoc]\nlemma split_epi.id {X Y : C} (f : X \u27f6 Y) [split_epi f] : section_ f \u226b f = \ud835\udfd9 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 \u27f6 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 \u27f6 Y) [mono f] [split_epi f] : is_iso f :=\n\u27e8\u27e8section_ f, \u27e8by simp [\u2190 cancel_mono f], by simp\u27e9\u27e9\u27e9\n\n/-- Every iso is a split mono. -/\n@[priority 100]\nnoncomputable\ninstance split_mono.of_iso {X Y : C} (f : X \u27f6 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 \u27f6 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 \u27f6 Y) [split_mono f] : mono f :=\n{ right_cancellation := \u03bb Z g h w, begin replace w := w =\u226b 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 \u27f6 Y) [split_epi f] : epi f :=\n{ left_cancellation := \u03bb Z g h w, begin replace w := section_ f \u226b= 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 \u27f6 Y} [split_mono f] [mono $ retraction f]\n  : is_iso f :=\n\u27e8\u27e8retraction f, \u27e8by simp, (cancel_mono_id $ retraction f).mp (by simp)\u27e9\u27e9\u27e9\n\n/-- Every split epi whose section is epi is an iso. -/\nlemma is_iso.of_epi_section {X Y : C} {f : X \u27f6 Y} [split_epi f] [epi $ section_ f]\n  : is_iso f :=\n\u27e8\u27e8section_ f, \u27e8(cancel_epi_id $ section_ f).mp (by simp), by simp\u27e9\u27e9\u27e9\n\ninstance unop_mono_of_epi {A B : C\u1d52\u1d56} (f : A \u27f6 B) [epi f] : mono f.unop :=\n\u27e8\u03bb Z g h eq, quiver.hom.op_inj ((cancel_epi f).1 (quiver.hom.unop_inj eq))\u27e9\n\ninstance unop_epi_of_mono {A B : C\u1d52\u1d56} (f : A \u27f6 B) [mono f] : epi f.unop :=\n\u27e8\u03bb Z g h eq, quiver.hom.op_inj ((cancel_mono f).1 (quiver.hom.unop_inj eq))\u27e9\n\ninstance op_mono_of_epi {A B : C} (f : A \u27f6 B) [epi f] : mono f.op :=\n\u27e8\u03bb Z g h eq, quiver.hom.unop_inj ((cancel_epi f).1 (quiver.hom.op_inj eq))\u27e9\n\ninstance op_epi_of_mono {A B : C} (f : A \u27f6 B) [mono f] : epi f.op :=\n\u27e8\u03bb Z g h eq, quiver.hom.unop_inj ((cancel_mono f).1 (quiver.hom.op_inj eq))\u27e9\n\nsection\nvariables {D : Type u\u2082} [category.{v\u2082} D]\n\n/-- Split monomorphisms are also absolute monomorphisms. -/\ninstance {X Y : C} (f : X \u27f6 Y) [split_mono f] (F : C \u2964 D) : split_mono (F.map f) :=\n{ retraction := F.map (retraction f),\n  id' := by { rw [\u2190functor.map_comp, split_mono.id, functor.map_id], } }\n\n/-- Split epimorphisms are also absolute epimorphisms. -/\ninstance {X Y : C} (f : X \u27f6 Y) [split_epi f] (F : C \u2964 D) : split_epi (F.map f) :=\n{ section_ := F.map (section_ f),\n  id' := by { rw [\u2190functor.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 \u2192 Prop} (h\u2081 : a \u2194 b) (h\u2082 : p a) : p b :=\n  propext h\u2081 \u25b8 h\u2082\n\nnamespace quot\n\n\naxiom sound {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a : \u03b1} {b : \u03b1} : r a b \u2192 Quot.mk r a = Quot.mk r bprotected theorem lift_beta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) (c : \u2200 (a b : \u03b1), r a b \u2192 f a = f b) (a : \u03b1) : Quot.lift f c (Quot.mk r a) = f a :=\n  rfl\n\nprotected theorem ind_beta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Prop} (p : \u2200 (a : \u03b1), \u03b2 (Quot.mk r a)) (a : \u03b1) : Quot.ind p (Quot.mk r a) = p a :=\n  rfl\n\nprotected def lift_on {\u03b1 : Sort u} {\u03b2 : Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) (f : \u03b1 \u2192 \u03b2) (c : \u2200 (a b : \u03b1), r a b \u2192 f a = f b) : \u03b2 :=\n  Quot.lift f c q\n\nprotected theorem induction_on {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Prop} (q : Quot r) (h : \u2200 (a : \u03b1), \u03b2 (Quot.mk r a)) : \u03b2 q :=\n  Quot.ind h q\n\ntheorem exists_rep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : \u2203 (a : \u03b1), Quot.mk r a = q :=\n  quot.induction_on q fun (a : \u03b1) => Exists.intro a rfl\n\nprotected def indep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) (a : \u03b1) : psigma \u03b2 :=\n  psigma.mk (Quot.mk r a) (f a)\n\nprotected theorem indep_coherent {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) (h : \u2200 (a b : \u03b1) (p : r a b), Eq._oldrec (f a) (sound p) = f b) (a : \u03b1) (b : \u03b1) : r a b \u2192 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 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) (h : \u2200 (a b : \u03b1) (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 : \u03b1) => Eq.refl (psigma.fst (quot.indep f a))) q\n\nprotected def rec {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) (h : \u2200 (a b : \u03b1) (p : r a b), Eq._oldrec (f a) (sound p) = f b) (q : Quot r) : \u03b2 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 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} (q : Quot r) (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) (h : \u2200 (a b : \u03b1) (p : r a b), Eq._oldrec (f a) (sound p) = f b) : \u03b2 q :=\n  quot.rec f h q\n\nprotected def rec_on_subsingleton {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} [h : \u2200 (a : \u03b1), subsingleton (\u03b2 (Quot.mk r a))] (q : Quot r) (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) : \u03b2 q :=\n  quot.rec f sorry q\n\nprotected def hrec_on {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Quot r \u2192 Sort v} (q : Quot r) (f : (a : \u03b1) \u2192 \u03b2 (Quot.mk r a)) (c : \u2200 (a b : \u03b1), r a b \u2192 f a == f b) : \u03b2 q :=\n  quot.rec_on q f sorry\n\nend quot\n\n\ndef quotient {\u03b1 : Sort u} (s : setoid \u03b1) :=\n  Quot setoid.r\n\nnamespace quotient\n\n\nprotected def mk {\u03b1 : Sort u} [s : setoid \u03b1] (a : \u03b1) : quotient s :=\n  Quot.mk setoid.r a\n\ndef sound {\u03b1 : Sort u} [s : setoid \u03b1] {a : \u03b1} {b : \u03b1} : a \u2248 b \u2192 quotient.mk a = quotient.mk b :=\n  quot.sound\n\nprotected def lift {\u03b1 : Sort u} {\u03b2 : Sort v} [s : setoid \u03b1] (f : \u03b1 \u2192 \u03b2) : (\u2200 (a b : \u03b1), a \u2248 b \u2192 f a = f b) \u2192 quotient s \u2192 \u03b2 :=\n  Quot.lift f\n\nprotected theorem ind {\u03b1 : Sort u} [s : setoid \u03b1] {\u03b2 : quotient s \u2192 Prop} : (\u2200 (a : \u03b1), \u03b2 (quotient.mk a)) \u2192 \u2200 (q : quotient s), \u03b2 q :=\n  Quot.ind\n\nprotected def lift_on {\u03b1 : Sort u} {\u03b2 : Sort v} [s : setoid \u03b1] (q : quotient s) (f : \u03b1 \u2192 \u03b2) (c : \u2200 (a b : \u03b1), a \u2248 b \u2192 f a = f b) : \u03b2 :=\n  quot.lift_on q f c\n\nprotected theorem induction_on {\u03b1 : Sort u} [s : setoid \u03b1] {\u03b2 : quotient s \u2192 Prop} (q : quotient s) (h : \u2200 (a : \u03b1), \u03b2 (quotient.mk a)) : \u03b2 q :=\n  quot.induction_on q h\n\ntheorem exists_rep {\u03b1 : Sort u} [s : setoid \u03b1] (q : quotient s) : \u2203 (a : \u03b1), quotient.mk a = q :=\n  quot.exists_rep q\n\nprotected def rec {\u03b1 : Sort u} [s : setoid \u03b1] {\u03b2 : quotient s \u2192 Sort v} (f : (a : \u03b1) \u2192 \u03b2 (quotient.mk a)) (h : \u2200 (a b : \u03b1) (p : a \u2248 b), Eq._oldrec (f a) (sound p) = f b) (q : quotient s) : \u03b2 q :=\n  quot.rec f h q\n\nprotected def rec_on {\u03b1 : Sort u} [s : setoid \u03b1] {\u03b2 : quotient s \u2192 Sort v} (q : quotient s) (f : (a : \u03b1) \u2192 \u03b2 (quotient.mk a)) (h : \u2200 (a b : \u03b1) (p : a \u2248 b), Eq._oldrec (f a) (sound p) = f b) : \u03b2 q :=\n  quot.rec_on q f h\n\nprotected def rec_on_subsingleton {\u03b1 : Sort u} [s : setoid \u03b1] {\u03b2 : quotient s \u2192 Sort v} [h : \u2200 (a : \u03b1), subsingleton (\u03b2 (quotient.mk a))] (q : quotient s) (f : (a : \u03b1) \u2192 \u03b2 (quotient.mk a)) : \u03b2 q :=\n  quot.rec_on_subsingleton q f\n\nprotected def hrec_on {\u03b1 : Sort u} [s : setoid \u03b1] {\u03b2 : quotient s \u2192 Sort v} (q : quotient s) (f : (a : \u03b1) \u2192 \u03b2 (quotient.mk a)) (c : \u2200 (a b : \u03b1), a \u2248 b \u2192 f a == f b) : \u03b2 q :=\n  quot.hrec_on q f c\n\nprotected def lift\u2082 {\u03b1 : Sort u_a} {\u03b2 : Sort u_b} {\u03c6 : Sort u_c} [s\u2081 : setoid \u03b1] [s\u2082 : setoid \u03b2] (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) (c : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2) (b\u2081 : \u03b1) (b\u2082 : \u03b2), a\u2081 \u2248 b\u2081 \u2192 a\u2082 \u2248 b\u2082 \u2192 f a\u2081 a\u2082 = f b\u2081 b\u2082) (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) : \u03c6 :=\n  quotient.lift (fun (a\u2081 : \u03b1) => quotient.lift (f a\u2081) sorry q\u2082) sorry q\u2081\n\nprotected def lift_on\u2082 {\u03b1 : Sort u_a} {\u03b2 : Sort u_b} {\u03c6 : Sort u_c} [s\u2081 : setoid \u03b1] [s\u2082 : setoid \u03b2] (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) (c : \u2200 (a\u2081 : \u03b1) (a\u2082 : \u03b2) (b\u2081 : \u03b1) (b\u2082 : \u03b2), a\u2081 \u2248 b\u2081 \u2192 a\u2082 \u2248 b\u2082 \u2192 f a\u2081 a\u2082 = f b\u2081 b\u2082) : \u03c6 :=\n  quotient.lift\u2082 f c q\u2081 q\u2082\n\nprotected theorem ind\u2082 {\u03b1 : Sort u_a} {\u03b2 : Sort u_b} [s\u2081 : setoid \u03b1] [s\u2082 : setoid \u03b2] {\u03c6 : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2), \u03c6 (quotient.mk a) (quotient.mk b)) (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) : \u03c6 q\u2081 q\u2082 :=\n  quotient.ind (fun (a\u2081 : \u03b1) => quotient.ind (fun (a\u2082 : \u03b2) => h a\u2081 a\u2082) q\u2082) q\u2081\n\nprotected theorem induction_on\u2082 {\u03b1 : Sort u_a} {\u03b2 : Sort u_b} [s\u2081 : setoid \u03b1] [s\u2082 : setoid \u03b2] {\u03c6 : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Prop} (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (h : \u2200 (a : \u03b1) (b : \u03b2), \u03c6 (quotient.mk a) (quotient.mk b)) : \u03c6 q\u2081 q\u2082 :=\n  quotient.ind (fun (a\u2081 : \u03b1) => quotient.ind (fun (a\u2082 : \u03b2) => h a\u2081 a\u2082) q\u2082) q\u2081\n\nprotected theorem induction_on\u2083 {\u03b1 : Sort u_a} {\u03b2 : Sort u_b} {\u03c6 : Sort u_c} [s\u2081 : setoid \u03b1] [s\u2082 : setoid \u03b2] [s\u2083 : setoid \u03c6] {\u03b4 : quotient s\u2081 \u2192 quotient s\u2082 \u2192 quotient s\u2083 \u2192 Prop} (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (q\u2083 : quotient s\u2083) (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03c6), \u03b4 (quotient.mk a) (quotient.mk b) (quotient.mk c)) : \u03b4 q\u2081 q\u2082 q\u2083 :=\n  quotient.ind (fun (a\u2081 : \u03b1) => quotient.ind (fun (a\u2082 : \u03b2) => quotient.ind (fun (a\u2083 : \u03c6) => h a\u2081 a\u2082 a\u2083) q\u2083) q\u2082) q\u2081\n\ntheorem exact {\u03b1 : Sort u} [s : setoid \u03b1] {a : \u03b1} {b : \u03b1} : quotient.mk a = quotient.mk b \u2192 a \u2248 b :=\n  fun (h : quotient.mk a = quotient.mk b) => eq_imp_rel h\n\nprotected def rec_on_subsingleton\u2082 {\u03b1 : Sort u_a} {\u03b2 : Sort u_b} [s\u2081 : setoid \u03b1] [s\u2082 : setoid \u03b2] {\u03c6 : quotient s\u2081 \u2192 quotient s\u2082 \u2192 Sort u_c} [h : \u2200 (a : \u03b1) (b : \u03b2), subsingleton (\u03c6 (quotient.mk a) (quotient.mk b))] (q\u2081 : quotient s\u2081) (q\u2082 : quotient s\u2082) (f : (a : \u03b1) \u2192 (b : \u03b2) \u2192 \u03c6 (quotient.mk a) (quotient.mk b)) : \u03c6 q\u2081 q\u2082 :=\n  quotient.rec_on_subsingleton q\u2081 fun (a : \u03b1) => quotient.rec_on_subsingleton q\u2082 fun (b : \u03b2) => f a b\n\nend quotient\n\n\ninductive eqv_gen {\u03b1 : Type u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : \u03b1 \u2192 \u03b1 \u2192 Prop\nwhere\n| rel : \u2200 (x y : \u03b1), r x y \u2192 eqv_gen r x y\n| refl : \u2200 (x : \u03b1), eqv_gen r x x\n| symm : \u2200 (x y : \u03b1), eqv_gen r x y \u2192 eqv_gen r y x\n| trans : \u2200 (x y z : \u03b1), eqv_gen r x y \u2192 eqv_gen r y z \u2192 eqv_gen r x z\n\ntheorem eqv_gen.is_equivalence {\u03b1 : Type u} (r : \u03b1 \u2192 \u03b1 \u2192 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 {\u03b1 : Type u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : setoid \u03b1 :=\n  setoid.mk (eqv_gen r) (eqv_gen.is_equivalence r)\n\ntheorem quot.exact {\u03b1 : Type u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) {a : \u03b1} {b : \u03b1} (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 : \u03b1) (h : r x y) => quot.sound (eqv_gen.rel x y h)) H)\n\ntheorem quot.eqv_gen_sound {\u03b1 : Type u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a : \u03b1} {b : \u03b1} (H : eqv_gen r a b) : Quot.mk r a = Quot.mk r b := sorry\n\nprotected instance quotient.decidable_eq {\u03b1 : Sort u} {s : setoid \u03b1} [d : (a b : \u03b1) \u2192 Decidable (a \u2248 b)] : DecidableEq (quotient s) :=\n  fun (q\u2081 q\u2082 : quotient s) => quotient.rec_on_subsingleton\u2082 q\u2081 q\u2082 fun (a\u2081 a\u2082 : \u03b1) => 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-- \u03b1 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 {\u03b1 : Type}\n\ninductive tactic_script (\u03b1 : Type) : Type\n| base : \u03b1 \u2192 tactic_script\n| work (index : \u2115) (first : \u03b1) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string \u2192 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 := \u03bb s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := \u03bb s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr \u2192 tactic \u03b1) (g : expr) : tactic \u03b1 :=\ndo\n  type \u2190 infer_type g,\n  is_lemma \u2190 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 \u2190 mk_meta_var type,\n    a \u2190 tac m,\n    do\n    { val \u2190 instantiate_mvars m,\n      guard (val.list_meta_vars = []),\n      c  \u2190 new_aux_decl_name,\n      gs \u2190 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 {\u03b1} (tac : tactic \u03b1)\nwith chain_single : expr \u2192 tactic (\u03b1 \u00d7 list (tactic_script \u03b1)) | g :=\ndo set_goals [g],\n  a \u2190 tac,\n  l \u2190 get_goals >>= chain_many,\n  return (a, l)\nwith chain_many : list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] := return []\n| [g] := do\n{ (a, l) \u2190 chain_single g,\n  return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr \u2192 list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do\n{ (a, l) \u2190 abstract_if_success chain_single g,\n  new_goals \u2190 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' \u2190 chain_many current_goals,\n  return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {\u03b1 : Type} [has_to_string (tactic_script \u03b1)] (tactics : list (tactic \u03b1)) :\n  tactic (list string) :=\ndo results \u2190 (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 \u03b1)] [has_to_format \u03b1]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic \u03b1) : tactic \u03b1 :=\ndo tgt \u2190 target,\n   r \u2190 t,\n   name \u2190 decl_name,\n   trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n   tgt \u2190 pp tgt,\n   trace format!\"previous target: {tgt}\",\n   trace format!\"tactic result: {r}\",\n   tgt \u2190 try_core target,\n   tgt \u2190 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 \u03b1)) : 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 (\u03b1 h_one h_add : expr) : pos_num \u2192 pexpr\n| pos_num.one      := ``(@has_one.one %%\u03b1 %%h_one)\n| (pos_num.bit0 n) := ``(@bit0 %%\u03b1 %%h_add (%%(pexpr_of_pos_num n)))\n| (pos_num.bit1 n) := ``(@bit1 %%\u03b1 %%h_one %%h_add (%%(pexpr_of_pos_num n)))\n\nmeta def expr_of_num (\u03b1 : expr) (n : num) : tactic expr :=\nmatch n with\n| num.zero := do\n  h_zero \u2190 mk_app `has_zero [\u03b1] >>= mk_instance,\n  to_expr ``(@has_zero.zero %%\u03b1 %%h_zero)\n| (num.pos (pos_num.one)) := do\n  h_one \u2190 mk_app `has_one [\u03b1] >>= mk_instance,\n  to_expr ``(@has_one.one %%\u03b1 %%h_one)\n| (num.pos m) := do\n  h_one \u2190 mk_app `has_one [\u03b1] >>= mk_instance,\n  h_add \u2190 mk_app `has_add [\u03b1] >>= mk_instance,\n  to_expr (pexpr_of_pos_num \u03b1 h_one h_add m)\nend\n\nmeta def expr_of_znum (\u03b1 : expr) (n : znum) : tactic expr :=\nmatch n with\n| znum.zero := do\n  h_zero \u2190 mk_app `has_zero [\u03b1] >>= mk_instance,\n  to_expr ``(@has_zero.zero %%\u03b1 %%h_zero)\n| (znum.pos n) :=\n  expr_of_num \u03b1 (num.pos n)\n| (znum.neg n) := do\n  h_neg \u2190 mk_app `has_neg [\u03b1] >>= mk_instance,\n  e \u2190 expr_of_num \u03b1 (num.pos n),\n  to_expr ``(@has_neg.neg %%\u03b1 %%h_neg %%e)\nend\n\nmeta def expr_of_rat (\u03b1 : expr) (q : \u211a) : tactic expr :=\nlet n : znum := q.num in\nlet d : znum := q.denom in\nif d = 1 then\n  expr_of_znum \u03b1 n\nelse do\n  a \u2190 expr_of_znum \u03b1 n,\n  b \u2190 expr_of_znum \u03b1 d,\n  to_expr ``(%%a / %%b)\n\nend tactic\n\nnamespace rat\n\nopen polya.field\n\ninstance : const_space \u211a :=\n{ df := by apply_instance,\n  lt := (<),\n  dec := by apply_instance,\n}\n\ninstance {\u03b1} [discrete_field \u03b1] [char_zero \u03b1] : morph \u211a \u03b1 :=\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 {\u03b1 : Type*} (l : list \u03b1) (f : \u03b1 \u2192 Prop) : Prop :=\nl.foldr (\u03bb a r, f a \u2227 r) true\n\ntheorem pall_iff_forall_prop :\n  \u2200 {\u03b1 : Type*} {p : \u03b1 \u2192 Prop} [_inst_1 : decidable_pred p] {l : list \u03b1},\n  list.pall l p \u2194 \u2200 (a : \u03b1), a \u2208 l \u2192 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 \u2192 tactic expr\n| [] := to_expr ``([] : list %%type)\n| (h::t) := do e \u2190 expr_reflect t, to_expr ``(list.cons (%%h : %%type) %%e)\n\ndef to_dict {\u03b1} [inhabited \u03b1] (l : list \u03b1) : dict \u03b1 :=\n\u27e8\u03bb i, list.func.get i l.reverse\u27e9\n\nend list\n\n--namespace finmap\n--open field\n--\n--def to_dict {\u03b1} [discrete_field \u03b1] (m : finmap (\u03bb _ : num, \u03b1)) : dict \u03b1 :=\n--\u27e8\u03bb i, match finmap.lookup i m with (some x) := x | _ := 0 end\u27e9\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\u27e8\u27e80, rb_map.mk _ _, rb_map.mk _ _\u27e9\u27e9\n\nmeta def state_dict : Type \u2192 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 {\u03b1} : has_coe (tactic \u03b1) (state_dict \u03b1) := \u27e8state_t.lift\u27e9\nend state_dict\n\nmeta def get_atom (e : expr) : state_dict num :=\nget >>= \u03bb s,\nmatch s.atoms.find e with\n| (some i) := return i\n| none     := do\n    let i := s.new_atom,\n    put \u27e8i + 1, s.atoms.insert e i, s.dict.insert i e\u27e9,\n    return i\nend\n\nmeta def cache_ty.dict_expr (\u03b1 : expr) (s : cache_ty) : tactic expr :=\ndo\n    e \u2190 s.dict.values.expr_reflect \u03b1,\n    mk_app `list.to_dict [e]\n\nmeta def term_of_expr : expr \u2192 state_dict term | e :=\nmatch e with\n| `(%%a + %%b) := do y \u2190 term_of_expr b, x \u2190 term_of_expr a, return (add x y)\n| `(%%a - %%b) := do y \u2190 term_of_expr b, x \u2190 term_of_expr a, return (sub x y)\n| `(%%a * %%b) := do y \u2190 term_of_expr b, x \u2190 term_of_expr a, return (mul x y)\n| `(%%a / %%b) := do y \u2190 term_of_expr b, x \u2190 term_of_expr a, return (div x y)\n| `(-%%a)      := do x \u2190 term_of_expr a, return (neg x)\n| `((%%a)\u207b\u00b9)   := do x \u2190 term_of_expr a, return (inv x)\n| `(%%a ^ %%b) := do x \u2190 term_of_expr a, ( (do n \u2190 b.to_nat, return (pow_nat x n)) <|> (do n \u2190 b.to_int, return (pow_int x n)) )\n| _            := do n \u2190 e.to_nat, return (numeral n)\nend <|> do i \u2190 get_atom e, return (atom i)\n\n--TODO: more generic\n@[reducible] def \u03b1 := \u211a\n@[reducible] def \u03b3 := \u211a\n\nmeta def nterm_to_expr (s : cache_ty) : nterm \u03b3 \u2192 tactic expr\n| (nterm.atom i)  := s.dict.find i\n| (nterm.const c) := expr_of_rat `(\u03b1) c\n| (nterm.add x y) := do a \u2190 nterm_to_expr x, b \u2190 nterm_to_expr y, to_expr ``(%%a + %%b)\n| (nterm.mul x y) := do a \u2190 nterm_to_expr x, b \u2190 nterm_to_expr y, to_expr ``(%%a * %%b)\n| (nterm.pow x n) := do a \u2190 nterm_to_expr x, b \u2190 expr_of_znum `(\u2124) n, to_expr ``(%%a ^ %%b)\n\nmeta def prove_norm_hyps (t : term) (s : cache_ty) : tactic (list expr \u00d7 expr) :=\ndo\n  let t_expr : expr := reflect t,\n  \u03c1 \u2190 s.dict_expr `(\u03b1),\n\n  let nhyps := norm_hyps \u03b3 t,\n  nhyps \u2190 monad.mapm (nterm_to_expr s) nhyps,\n  nhyps \u2190 monad.mapm (\u03bb e, to_expr ``(%%e \u2260 0)) nhyps,\n  mvars \u2190 monad.mapm mk_meta_var nhyps,\n\n  h \u2190 to_expr ``(\u2200 x \u2208 norm_hyps \u03b3 %%t_expr, nterm.eval %%\u03c1 x \u2260 0),\n  pe \u2190 to_expr ( mvars.foldr (\u03bb e pe, ``((and.intro %%e %%pe))) ``(trivial) ) tt ff,\n  ((), pr) \u2190 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 \u00d7 expr \u00d7 expr \u00d7 list expr \u00d7 cache_ty) :=\ndo\n  (t, s) \u2190 (term_of_expr e).run s,\n  let t_expr : expr := reflect t,\n  let norm_t := norm \u03b3 t,\n  norm_t_expr \u2190 to_expr ``(norm \u03b3 %%t_expr),\n  \u03c1_expr \u2190 s.dict_expr `(\u03b1),\n\n  (mvars, pr0) \u2190 prove_norm_hyps t s,\n\n  --reflexivity from expr to term\n  h1 \u2190 to_expr ``(%%e = term.eval %%\u03c1_expr %%t_expr),\n  ((), pr1) \u2190 solve_aux h1 `[refl, done],\n\n  --correctness theorem\n  --h2 \u2190 to_expr ``(term.eval %%\u03c1_expr %%t_expr = nterm.eval %%\u03c1_expr %%norm_t_expr),\n  pr2 \u2190 mk_app `polya.field.correctness [pr0],\n\n  --reflexivity from nterm to expr\n  new_e \u2190 nterm_to_expr s norm_t,\n  h3 \u2190 to_expr ``(nterm.eval %%\u03c1_expr %%norm_t_expr = %%new_e),\n  pr3 \u2190 mk_meta_var h3, --heavy computation in the kernel\n\n  pr \u2190 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 \u2190 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) \u2190 target,\n\n  (new_e1, pr1, mv1, mvs, s) \u2190 norm_expr e1 \u2205,\n  (new_e2, pr2, mv2, mvs', s) \u2190 norm_expr e2 s,\n\n  ( do\n    unify new_e1 new_e2,\n    prove_by_reflexivity [mv1, mv2],\n    gs \u2190 get_goals,\n    set_goals (gs ++ mvs ++ mvs'),\n    pr \u2190 mk_eq_symm pr2 >>= mk_eq_trans pr1,\n    tactic.exact pr\n  ) <|> ( do\n    prove_by_reflexivity [mv1, mv2],\n    pr0 \u2190 to_expr ``(%%new_e1 = %%new_e2) >>= mk_meta_var,\n    gs \u2190 get_goals,\n    set_goals (gs ++ [pr0] ++ mvs ++ mvs'),\n    pr \u2190 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\u2081 u\u2081 -- morphism levels before object levels. See note [category_theory universes].\n\nvariables (C : Type u\u2081) [category.{v\u2081} C]\n\n/--\nThe data of a monad on C consists of an endofunctor T together with natural transformations\n\u03b7 : \ud835\udfed C \u27f6 T and \u03bc : T \u22d9 T \u27f6 T satisfying three equations:\n- T \u03bc_X \u226b \u03bc_X = \u03bc_(TX) \u226b \u03bc_X (associativity)\n- \u03b7_(TX) \u226b \u03bc_X = 1_X (left unit)\n- T\u03b7_X \u226b \u03bc_X = 1_X (right unit)\n-/\nstructure monad extends C \u2964 C :=\n(\u03b7' [] : \ud835\udfed _ \u27f6 to_functor)\n(\u03bc' [] : to_functor \u22d9 to_functor \u27f6 to_functor)\n(assoc' : \u2200 X, to_functor.map (nat_trans.app \u03bc' X) \u226b \u03bc'.app _ = \u03bc'.app _ \u226b \u03bc'.app _ . obviously)\n(left_unit' : \u2200 X : C, \u03b7'.app (to_functor.obj X) \u226b \u03bc'.app _ = \ud835\udfd9 _ . obviously)\n(right_unit' : \u2200 X : C, to_functor.map (\u03b7'.app X) \u226b \u03bc'.app _ = \ud835\udfd9 _ . obviously)\n\n/--\nThe data of a comonad on C consists of an endofunctor G together with natural transformations\n\u03b5 : G \u27f6 \ud835\udfed C and \u03b4 : G \u27f6 G \u22d9 G satisfying three equations:\n- \u03b4_X \u226b G \u03b4_X = \u03b4_X \u226b \u03b4_(GX) (coassociativity)\n- \u03b4_X \u226b \u03b5_(GX) = 1_X (left counit)\n- \u03b4_X \u226b G \u03b5_X = 1_X (right counit)\n-/\nstructure comonad extends C \u2964 C :=\n(\u03b5' [] : to_functor \u27f6 \ud835\udfed _)\n(\u03b4' [] : to_functor \u27f6 to_functor \u22d9 to_functor)\n(coassoc' : \u2200 X, nat_trans.app \u03b4' _ \u226b to_functor.map (\u03b4'.app X) = \u03b4'.app _ \u226b \u03b4'.app _ . obviously)\n(left_counit' : \u2200 X : C, \u03b4'.app X \u226b \u03b5'.app (to_functor.obj X) = \ud835\udfd9 _ . obviously)\n(right_counit' : \u2200 X : C, \u03b4'.app X \u226b to_functor.map (\u03b5'.app X) = \ud835\udfd9 _ . obviously)\n\nvariables {C} (T : monad C) (G : comonad C)\n\ninstance coe_monad : has_coe (monad C) (C \u2964 C) := \u27e8\u03bb T, T.to_functor\u27e9\ninstance coe_comonad : has_coe (comonad C) (C \u2964 C) := \u27e8\u03bb G, G.to_functor\u27e9\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.\u03b7 : \ud835\udfed _ \u27f6 (T : C \u2964 C) := T.\u03b7'\n/-- The multiplication for the monad `T`. -/\ndef monad.\u03bc : (T : C \u2964 C) \u22d9 (T : C \u2964 C) \u27f6 T := T.\u03bc'\n\n/-- The counit for the comonad `G`. -/\ndef comonad.\u03b5 : (G : C \u2964 C) \u27f6 \ud835\udfed _  := G.\u03b5'\n/-- The comultiplication for the comonad `G`. -/\ndef comonad.\u03b4 : (G : C \u2964 C) \u27f6 (G : C \u2964 C) \u22d9 G := G.\u03b4'\n\n/-- A custom simps projection for the functor part of a monad, as a coercion. -/\ndef monad.simps.coe := (T : C \u2964 C)\n/-- A custom simps projection for the unit of a monad, in simp normal form. -/\ndef monad.simps.\u03b7 : \ud835\udfed _ \u27f6 (T : C \u2964 C) := T.\u03b7\n/-- A custom simps projection for the multiplication of a monad, in simp normal form. -/\ndef monad.simps.\u03bc : (T : C \u2964 C) \u22d9 (T : C \u2964 C) \u27f6 (T : C \u2964 C) := T.\u03bc\n\n/-- A custom simps projection for the functor part of a comonad, as a coercion. -/\ndef comonad.simps.coe := (G : C \u2964 C)\n/-- A custom simps projection for the counit of a comonad, in simp normal form. -/\ndef comonad.simps.\u03b5 : (G : C \u2964 C) \u27f6 \ud835\udfed _ := G.\u03b5\n/-- A custom simps projection for the comultiplication of a comonad, in simp normal form. -/\ndef comonad.simps.\u03b4 : (G : C \u2964 C) \u27f6 (G : C \u2964 C) \u22d9 (G : C \u2964 C) := G.\u03b4\n\ninitialize_simps_projections category_theory.monad (to_functor \u2192 coe, \u03b7' \u2192 \u03b7, \u03bc' \u2192 \u03bc)\ninitialize_simps_projections category_theory.comonad (to_functor \u2192 coe, \u03b5' \u2192 \u03b5, \u03b4' \u2192 \u03b4)\n\n@[reassoc]\nlemma monad.assoc (T : monad C) (X : C) :\n  (T : C \u2964 C).map (T.\u03bc.app X) \u226b T.\u03bc.app _ = T.\u03bc.app _ \u226b T.\u03bc.app _ :=\nT.assoc' X\n\n@[simp, reassoc] lemma monad.left_unit (T : monad C) (X : C) :\n  T.\u03b7.app ((T : C \u2964 C).obj X) \u226b T.\u03bc.app X = \ud835\udfd9 ((T : C \u2964 C).obj X) :=\nT.left_unit' X\n\n@[simp, reassoc] lemma monad.right_unit (T : monad C) (X : C) :\n  (T : C \u2964 C).map (T.\u03b7.app X) \u226b T.\u03bc.app X = \ud835\udfd9 ((T : C \u2964 C).obj X) :=\nT.right_unit' X\n\n@[reassoc]\nlemma comonad.coassoc (G : comonad C) (X : C) :\n  G.\u03b4.app _ \u226b (G : C \u2964 C).map (G.\u03b4.app X) = G.\u03b4.app _ \u226b G.\u03b4.app _ :=\nG.coassoc' X\n\n@[simp, reassoc] lemma comonad.left_counit (G : comonad C) (X : C) :\n  G.\u03b4.app X \u226b G.\u03b5.app ((G : C \u2964 C).obj X) = \ud835\udfd9 ((G : C \u2964 C).obj X) :=\nG.left_counit' X\n\n@[simp, reassoc] lemma comonad.right_counit (G : comonad C) (X : C) :\n  G.\u03b4.app X \u226b (G : C \u2964 C).map (G.\u03b5.app X) = \ud835\udfd9 ((G : C \u2964 C).obj X) :=\nG.right_counit' X\n\n/-- A morphism of monads is a natural transformation compatible with \u03b7 and \u03bc. -/\n@[ext]\nstructure monad_hom (T\u2081 T\u2082 : monad C) extends nat_trans (T\u2081 : C \u2964 C) T\u2082 :=\n(app_\u03b7' : \u2200 {X}, T\u2081.\u03b7.app X \u226b app X = T\u2082.\u03b7.app X . obviously)\n(app_\u03bc' : \u2200 {X}, T\u2081.\u03bc.app X \u226b app X = ((T\u2081 : C \u2964 C).map (app X) \u226b app _) \u226b T\u2082.\u03bc.app X . obviously)\n\n/-- A morphism of comonads is a natural transformation compatible with \u03b5 and \u03b4. -/\n@[ext]\nstructure comonad_hom (M N : comonad C) extends nat_trans (M : C \u2964 C) N :=\n(app_\u03b5' : \u2200 {X}, app X \u226b N.\u03b5.app X = M.\u03b5.app X . obviously)\n(app_\u03b4' : \u2200 {X}, app X \u226b N.\u03b4.app X = M.\u03b4.app X \u226b app (M.obj X) \u226b N.map (app X) . obviously)\n\nrestate_axiom monad_hom.app_\u03b7'\nrestate_axiom monad_hom.app_\u03bc'\nattribute [simp, reassoc] monad_hom.app_\u03b7 monad_hom.app_\u03bc\n\nrestate_axiom comonad_hom.app_\u03b5'\nrestate_axiom comonad_hom.app_\u03b4'\nattribute [simp, reassoc] comonad_hom.app_\u03b5 comonad_hom.app_\u03b4\n\ninstance : category (monad C) :=\n{ hom := monad_hom,\n  id := \u03bb M, { to_nat_trans := \ud835\udfd9 (M : C \u2964 C) },\n  comp := \u03bb _ _ _ f g,\n  { to_nat_trans := { app := \u03bb X, f.app X \u226b g.app X } } }\n\ninstance : category (comonad C) :=\n{ hom := comonad_hom,\n  id := \u03bb M, { to_nat_trans := \ud835\udfd9 (M : C \u2964 C) },\n  comp := \u03bb M N L f g,\n  { to_nat_trans := { app := \u03bb X, f.app X \u226b g.app X } } }\n\ninstance {T : monad C} : inhabited (monad_hom T T) := \u27e8\ud835\udfd9 T\u27e9\n\n@[simp] \n\ninstance {G : comonad C} : inhabited (comonad_hom G G) := \u27e8\ud835\udfd9 G\u27e9\n\n@[simp] lemma comonad_hom.id_to_nat_trans (T : comonad C) :\n  (\ud835\udfd9 T : T \u27f6 T).to_nat_trans = \ud835\udfd9 (T : C \u2964 C) :=\nrfl\n@[simp] lemma comp_to_nat_trans {T\u2081 T\u2082 T\u2083 : comonad C} (f : T\u2081 \u27f6 T\u2082) (g : T\u2082 \u27f6 T\u2083) :\n  (f \u226b g).to_nat_trans =\n    ((f.to_nat_trans : _ \u27f6 (T\u2082 : C \u2964 C)) \u226b g.to_nat_trans : (T\u2081 : C \u2964 C) \u27f6 T\u2083) :=\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 \u2964 (C \u2964 C) :=\n{ obj := \u03bb T, T,\n  map := \u03bb 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 \u2964 (C \u2964 C) :=\n{ obj := \u03bb G, G,\n  map := \u03bb 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 \u2245 N) : (M : C \u2964 C) \u2245 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 \u2245 N) : (M : C \u2964 C) \u2245 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 := \ud835\udfed C,\n  \u03b7' := \ud835\udfd9 (\ud835\udfed C),\n  \u03bc' := \ud835\udfd9 (\ud835\udfed C) }\n\ninstance : inhabited (monad C) := \u27e8monad.id C\u27e9\n\nend monad\n\nnamespace comonad\n\n/-- The identity comonad. -/\n@[simps]\ndef id : comonad C :=\n{ to_functor := \ud835\udfed _,\n  \u03b5' := \ud835\udfd9 (\ud835\udfed C),\n  \u03b4' := \ud835\udfd9 (\ud835\udfed C) }\n\ninstance : inhabited (comonad C) := \u27e8comonad.id C\u27e9\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 {\u03b1 : Type u_1} [encodable \u03b1] : List \u03b1 \u2192 \u2115 :=\n  sorry\n\ndef decode_list {\u03b1 : Type u_1} [encodable \u03b1] : \u2115 \u2192 Option (List \u03b1) :=\n  sorry\n\nprotected instance list {\u03b1 : Type u_1} [encodable \u03b1] : encodable (List \u03b1) :=\n  mk encode_list decode_list sorry\n\n@[simp] theorem encode_list_nil {\u03b1 : Type u_1} [encodable \u03b1] : encode [] = 0 :=\n  rfl\n\n@[simp] theorem encode_list_cons {\u03b1 : Type u_1} [encodable \u03b1] (a : \u03b1) (l : List \u03b1) : encode (a :: l) = Nat.succ (nat.mkpair (encode a) (encode l)) :=\n  rfl\n\n@[simp] theorem decode_list_zero {\u03b1 : Type u_1} [encodable \u03b1] : decode (List \u03b1) 0 = some [] :=\n  rfl\n\n@[simp] theorem decode_list_succ {\u03b1 : Type u_1} [encodable \u03b1] (v : \u2115) : decode (List \u03b1) (Nat.succ v) =\n  (fun (_x : \u03b1) (_y : List \u03b1) => _x :: _y) <$> decode \u03b1 (prod.fst (nat.unpair v)) <*>\n    decode (List \u03b1) (prod.snd (nat.unpair v)) := sorry\n\ntheorem length_le_encode {\u03b1 : Type u_1} [encodable \u03b1] (l : List \u03b1) : list.length l \u2264 encode l := sorry\n\ndef encode_multiset {\u03b1 : Type u_1} [encodable \u03b1] (s : multiset \u03b1) : \u2115 :=\n  encode (multiset.sort enle s)\n\ndef decode_multiset {\u03b1 : Type u_1} [encodable \u03b1] (n : \u2115) : Option (multiset \u03b1) :=\n  coe <$> decode (List \u03b1) n\n\nprotected instance multiset {\u03b1 : Type u_1} [encodable \u03b1] : encodable (multiset \u03b1) :=\n  mk encode_multiset decode_multiset sorry\n\ndef encodable_of_list {\u03b1 : Type u_1} [DecidableEq \u03b1] (l : List \u03b1) (H : \u2200 (x : \u03b1), x \u2208 l) : encodable \u03b1 :=\n  mk (fun (a : \u03b1) => list.index_of a l) (list.nth l) sorry\n\ndef trunc_encodable_of_fintype (\u03b1 : Type u_1) [DecidableEq \u03b1] [fintype \u03b1] : trunc (encodable \u03b1) :=\n  quot.rec_on_subsingleton (finset.val finset.univ)\n    (fun (l : List \u03b1) (H : \u2200 (x : \u03b1), x \u2208 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 (\u03b1 : Type u_1) [fintype \u03b1] : encodable \u03b1 :=\n  trunc.out (trunc_encodable_of_fintype \u03b1)\n\nprotected instance vector {\u03b1 : Type u_1} [encodable \u03b1] {n : \u2115} : encodable (vector \u03b1 n) :=\n  encodable.subtype\n\nprotected instance fin_arrow {\u03b1 : Type u_1} [encodable \u03b1] {n : \u2115} : encodable (fin n \u2192 \u03b1) :=\n  of_equiv (vector \u03b1 n) (equiv.symm (equiv.vector_equiv_fin \u03b1 n))\n\nprotected instance fin_pi (n : \u2115) (\u03c0 : fin n \u2192 Type u_1) [(i : fin n) \u2192 encodable (\u03c0 i)] : encodable ((i : fin n) \u2192 \u03c0 i) :=\n  of_equiv (\u21a5(set_of fun (f : fin n \u2192 sigma fun (i : fin n) => \u03c0 i) => \u2200 (i : fin n), sigma.fst (f i) = i))\n    (equiv.pi_equiv_subtype_sigma (fin n) \u03c0)\n\nprotected instance array {\u03b1 : Type u_1} [encodable \u03b1] {n : \u2115} : encodable (array n \u03b1) :=\n  of_equiv (fin n \u2192 \u03b1) (equiv.array_equiv_fin n \u03b1)\n\nprotected instance finset {\u03b1 : Type u_1} [encodable \u03b1] : encodable (finset \u03b1) :=\n  of_equiv (Subtype fun (s : multiset \u03b1) => multiset.nodup s)\n    (equiv.mk (fun (_x : finset \u03b1) => sorry) (fun (_x : Subtype fun (s : multiset \u03b1) => multiset.nodup s) => sorry) sorry\n      sorry)\n\ndef fintype_arrow (\u03b1 : Type u_1) (\u03b2 : Type u_2) [DecidableEq \u03b1] [fintype \u03b1] [encodable \u03b2] : trunc (encodable (\u03b1 \u2192 \u03b2)) :=\n  trunc.map\n    (fun (f : \u03b1 \u2243 fin (fintype.card \u03b1)) => of_equiv (fin (fintype.card \u03b1) \u2192 \u03b2) (equiv.arrow_congr f (equiv.refl \u03b2)))\n    (fintype.equiv_fin \u03b1)\n\ndef fintype_pi (\u03b1 : Type u_1) (\u03c0 : \u03b1 \u2192 Type u_2) [DecidableEq \u03b1] [fintype \u03b1] [(a : \u03b1) \u2192 encodable (\u03c0 a)] : trunc (encodable ((a : \u03b1) \u2192 \u03c0 a)) :=\n  trunc.bind (trunc_encodable_of_fintype \u03b1)\n    fun (a : encodable \u03b1) =>\n      trunc.bind (fintype_arrow \u03b1 (sigma fun (a : \u03b1) => \u03c0 a))\n        fun (f : encodable (\u03b1 \u2192 sigma fun (a : \u03b1) => \u03c0 a)) =>\n          trunc.mk\n            (of_equiv\n              (Subtype\n                fun (a : \u03b1 \u2192 sigma fun (a : \u03b1) => \u03c0 a) =>\n                  a \u2208 set_of fun (f : \u03b1 \u2192 sigma fun (a : \u03b1) => \u03c0 a) => \u2200 (i : \u03b1), sigma.fst (f i) = i)\n              (equiv.pi_equiv_subtype_sigma \u03b1 \u03c0))\n\n/-- The elements of a `fintype` as a sorted list. -/\ndef sorted_univ (\u03b1 : Type u_1) [fintype \u03b1] [encodable \u03b1] : List \u03b1 :=\n  finset.sort (\u21d1(encode' \u03b1) \u207b\u00b9'o LessEq) finset.univ\n\ntheorem mem_sorted_univ {\u03b1 : Type u_1} [fintype \u03b1] [encodable \u03b1] (x : \u03b1) : x \u2208 sorted_univ \u03b1 :=\n  iff.mpr (finset.mem_sort (\u21d1(encode' \u03b1) \u207b\u00b9'o LessEq)) (finset.mem_univ x)\n\ntheorem length_sorted_univ {\u03b1 : Type u_1} [fintype \u03b1] [encodable \u03b1] : list.length (sorted_univ \u03b1) = fintype.card \u03b1 :=\n  finset.length_sort (\u21d1(encode' \u03b1) \u207b\u00b9'o LessEq)\n\ntheorem sorted_univ_nodup {\u03b1 : Type u_1} [fintype \u03b1] [encodable \u03b1] : list.nodup (sorted_univ \u03b1) :=\n  finset.sort_nodup (\u21d1(encode' \u03b1) \u207b\u00b9'o LessEq) finset.univ\n\n/-- An encodable `fintype` is equivalent a `fin`.-/\ndef fintype_equiv_fin {\u03b1 : Type u_1} [fintype \u03b1] [encodable \u03b1] : \u03b1 \u2243 fin (fintype.card \u03b1) :=\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [encodable \u03b1] [fintype \u03b1] [encodable \u03b2] : encodable (\u03b1 \u2192 \u03b2) :=\n  of_equiv (fin (fintype.card \u03b1) \u2192 \u03b2) (equiv.arrow_congr fintype_equiv_fin (equiv.refl \u03b2))\n\nend encodable\n\n\nnamespace denumerable\n\n\ntheorem denumerable_list_aux {\u03b1 : Type u_1} [denumerable \u03b1] (n : \u2115) : \u2203 (a : List \u03b1), \u2203 (H : a \u2208 encodable.decode_list n), encodable.encode_list a = n := sorry\n\nprotected instance denumerable_list {\u03b1 : Type u_1} [denumerable \u03b1] : denumerable (List \u03b1) :=\n  mk denumerable_list_aux\n\n@[simp] theorem list_of_nat_zero {\u03b1 : Type u_1} [denumerable \u03b1] : of_nat (List \u03b1) 0 = [] :=\n  rfl\n\n@[simp] theorem list_of_nat_succ {\u03b1 : Type u_1} [denumerable \u03b1] (v : \u2115) : of_nat (List \u03b1) (Nat.succ v) = of_nat \u03b1 (prod.fst (nat.unpair v)) :: of_nat (List \u03b1) (prod.snd (nat.unpair v)) := sorry\n\ndef lower : List \u2115 \u2192 \u2115 \u2192 List \u2115 :=\n  sorry\n\ndef raise : List \u2115 \u2192 \u2115 \u2192 List \u2115 :=\n  sorry\n\ntheorem lower_raise (l : List \u2115) (n : \u2115) : lower (raise l n) n = l := sorry\n\ntheorem raise_lower {l : List \u2115} {n : \u2115} : list.sorted LessEq (n :: l) \u2192 raise (lower l n) n = l := sorry\n\ntheorem raise_chain (l : List \u2115) (n : \u2115) : list.chain LessEq n (raise l n) := sorry\n\ntheorem raise_sorted (l : List \u2115) (n : \u2115) : list.sorted LessEq (raise l n) := sorry\n\n/- Warning: this is not the same encoding as used in `encodable` -/\n\nprotected instance multiset {\u03b1 : Type u_1} [denumerable \u03b1] : denumerable (multiset \u03b1) :=\n  mk'\n    (equiv.mk\n      (fun (s : multiset \u03b1) => encodable.encode (lower (multiset.sort LessEq (multiset.map encodable.encode s)) 0))\n      (fun (n : \u2115) => multiset.map (of_nat \u03b1) \u2191(raise (of_nat (List \u2115) n) 0)) sorry sorry)\n\ndef lower' : List \u2115 \u2192 \u2115 \u2192 List \u2115 :=\n  sorry\n\ndef raise' : List \u2115 \u2192 \u2115 \u2192 List \u2115 :=\n  sorry\n\ntheorem lower_raise' (l : List \u2115) (n : \u2115) : lower' (raise' l n) n = l := sorry\n\ntheorem raise_lower' {l : List \u2115} {n : \u2115} : (\u2200 (m : \u2115), m \u2208 l \u2192 n \u2264 m) \u2192 list.sorted Less l \u2192 raise' (lower' l n) n = l := sorry\n\ntheorem raise'_chain (l : List \u2115) {m : \u2115} {n : \u2115} : m < n \u2192 list.chain Less m (raise' l n) := sorry\n\ntheorem raise'_sorted (l : List \u2115) (n : \u2115) : list.sorted Less (raise' l n) := sorry\n\ndef raise'_finset (l : List \u2115) (n : \u2115) : finset \u2115 :=\n  finset.mk \u2191(raise' l n) sorry\n\n/- Warning: this is not the same encoding as used in `encodable` -/\n\nprotected instance finset {\u03b1 : Type u_1} [denumerable \u03b1] : denumerable (finset \u03b1) :=\n  mk'\n    (equiv.mk\n      (fun (s : finset \u03b1) => encodable.encode (lower' (finset.sort LessEq (finset.map (equiv.to_embedding (eqv \u03b1)) s)) 0))\n      (fun (n : \u2115) => finset.map (equiv.to_embedding (equiv.symm (eqv \u03b1))) (raise'_finset (of_nat (List \u2115) 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 \u2243 \u2115 :=\n  mk list.length (list.repeat Unit.unit) sorry sorry\n\ndef list_nat_equiv_nat : List \u2115 \u2243 \u2115 :=\n  denumerable.eqv (List \u2115)\n\ndef list_equiv_self_of_equiv_nat {\u03b1 : Type} (e : \u03b1 \u2243 \u2115) : List \u03b1 \u2243 \u03b1 :=\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 \u2964 Cat.{u u}} {j} :\n  small_category ((F \u22d9 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 \u2964 Cat.{v v}} (X Y : limit (F \u22d9 Cat.objects.{v v})) : J \u2964 Type v :=\n{ obj := \u03bb j, limit.\u03c0 (F \u22d9 Cat.objects) j X \u27f6 limit.\u03c0 (F \u22d9 Cat.objects) j Y,\n  map := \u03bb j j' f g,\n  begin\n    refine eq_to_hom _ \u226b (F.map f).map g \u226b eq_to_hom _,\n    exact (congr_fun (limit.w (F \u22d9 Cat.objects) f) X).symm,\n    exact (congr_fun (limit.w (F \u22d9 Cat.objects) f) Y),\n  end,\n  map_id' := \u03bb X, begin\n    ext f, dsimp,\n    simp [functor.congr_hom (F.map_id X) f],\n  end,\n  map_comp' := \u03bb 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 \u2964 Cat.{v v}) : category (limit (F \u22d9 Cat.objects)) :=\n{ hom := \u03bb X Y, limit (hom_diagram X Y),\n  id := \u03bb X, types.limit.mk.{v v} (hom_diagram X X) (\u03bb j, \ud835\udfd9 _) (\u03bb j j' f, by simp),\n  comp := \u03bb X Y Z f g, types.limit.mk.{v v} (hom_diagram X Z)\n    (\u03bb j, limit.\u03c0 (hom_diagram X Y) j f \u226b limit.\u03c0 (hom_diagram Y Z) j g)\n    (\u03bb j j' h, begin\n      rw [\u2190congr_fun (limit.w (hom_diagram X Y) h) f, \u2190congr_fun (limit.w (hom_diagram Y Z) h) g],\n      dsimp,\n      simp,\n    end),\n  id_comp' := \u03bb _ _ _, by { ext, simp only [category.id_comp, types.limit.\u03c0_mk'] },\n  comp_id' := \u03bb _ _ _, by { ext, simp only [types.limit.\u03c0_mk', category.comp_id] } }\n\n/-- Auxiliary definition: the limit category. -/\n@[simps]\ndef limit_cone_X (F : J \u2964 Cat.{v v}) : Cat.{v v} :=\n{ \u03b1 := limit (F \u22d9 Cat.objects), }.\n\n/-- Auxiliary definition: the cone over the limit category. -/\n@[simps]\ndef limit_cone (F : J \u2964 Cat.{v v}) : cone F :=\n{ X := limit_cone_X F,\n  \u03c0 :=\n  { app := \u03bb j,\n    { obj := limit.\u03c0 (F \u22d9 Cat.objects) j,\n      map := \u03bb X Y, limit.\u03c0 (hom_diagram X Y) j, },\n    naturality' := \u03bb j j' f, category_theory.functor.ext\n      (\u03bb X, (congr_fun (limit.w (F \u22d9 Cat.objects) f) X).symm)\n      (\u03bb 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 \u2964 Cat.{v v}) (s : cone F) : s.X \u27f6 limit_cone_X F :=\n{ obj := limit.lift (F \u22d9 Cat.objects)\n  { X := s.X,\n    \u03c0 :=\n    { app := \u03bb j, (s.\u03c0.app j).obj,\n      naturality' := \u03bb j j' f, (congr_arg functor.obj (s.\u03c0.naturality f) : _), } },\n  map := \u03bb X Y f,\n  begin\n    fapply types.limit.mk.{v v},\n    { intro j,\n      refine eq_to_hom _ \u226b (s.\u03c0.app j).map f \u226b 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 [\u2190functor.comp_map],\n      have := (s.\u03c0.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' := \u03bb X, by simp,\n  map_comp' := \u03bb X Y Z f g, by simp }\n\n@[simp]\nlemma limit_\u03c0_hom_diagram_eq_to_hom {F : J \u2964 Cat.{v v}}\n  (X Y : limit (F \u22d9 Cat.objects.{v v})) (j : J) (h : X = Y) :\n  limit.\u03c0 (hom_diagram X Y) j (eq_to_hom h) =\n    eq_to_hom (congr_arg (limit.\u03c0 (F \u22d9 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 \u2964 Cat.{v v}) : is_limit (limit_cone F) :=\n{ lift := limit_cone_lift F,\n  fac' := \u03bb s j, category_theory.functor.ext (by tidy) (\u03bb X Y f, types.limit.\u03c0_mk _ _ _ _),\n  uniq' := \u03bb 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_\u03c0_apply', \u2190w j],\n      refl, },\n    { intros X Y f,\n      dsimp, simp [(\u03bb 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 := \u03bb J _, by exactI\n  { has_limit := \u03bb F, \u27e8\u27e8\u27e8has_limits.limit_cone F, has_limits.limit_cone_is_limit F\u27e9\u27e9\u27e9, } }\n\ninstance : preserves_limits Cat.objects.{v v} :=\n{ preserves_limits_of_shape := \u03bb J _, by exactI\n  { preserves_limit := \u03bb 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 \u22d9 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": "example : 3 = 3 :=\nbegin\n  generalize : 3 = x,\n  revert x,\n  intro y,\n  reflexivity\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/ex0217.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.36658972248186006, "lm_q2_score": 0.07585818211049714, "lm_q1q2_score": 0.027808829927865545}}
{"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.data.option.basic\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.control.lawful\n \n\nuniverses u_1 u \n\nnamespace Mathlib\n\nprotected instance option.is_lawful_monad : is_lawful_monad Option :=\n  is_lawful_monad.mk (fun (\u03b1 \u03b2 : Type u_1) (x : \u03b1) (f : \u03b1 \u2192 Option \u03b2) => rfl)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (x : Option \u03b1) (f : \u03b1 \u2192 Option \u03b2) (g : \u03b2 \u2192 Option \u03b3) => Option.rec rfl (fun (x : \u03b1) => rfl) x\n\ntheorem option.eq_of_eq_some {\u03b1 : Type u} {x : Option \u03b1} {y : Option \u03b1} : (\u2200 (z : \u03b1), x = some z \u2194 y = some z) \u2192 x = y := sorry\n\ntheorem option.eq_some_of_is_some {\u03b1 : Type u} {o : Option \u03b1} (h : \u21a5(option.is_some o)) : o = some (option.get h) := sorry\n\ntheorem option.eq_none_of_is_none {\u03b1 : Type u} {o : Option \u03b1} : \u21a5(option.is_none o) \u2192 o = none := 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/option/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.05582313995652302, "lm_q1q2_score": 0.027693515274122605}}
{"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 `?`: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 \u2190 i_to_expr e <|> do\n  { ty \u2190 target,\n    -- for positional error messages, we don't care about the result\n    e \u2190 i_to_expr_strict ``(%%e : %%ty),\n    pty \u2190 pp ty, ptgt \u2190 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 \u2190 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": "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/simpa.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.06371499958557338, "lm_q1q2_score": 0.027651127917251564}}
{"text": "import Lean.CoreM\n\n#eval Lean.addDecl <| .mutualDefnDecl [{\n  name := `FalseIntro\n  levelParams := []\n  type := .const ``False []\n  value := .const `FalseIntro []\n  hints := .opaque\n  safety := .partial\n}]\n\ntheorem False.intro : False := FalseIntro\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/RejectMetaFalse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4339814648038985, "lm_q2_score": 0.06371499514089998, "lm_q1q2_score": 0.02765112692122105}}
{"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* `\u0393` is the alphabet on the tape.\n* `\u039b` is the set of labels, or internal machine states.\n* `\u03c3` 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 `\u039b`.\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  `\u039b \u2192 stmt`, although different models have different ways of halting and other actions.\n* `step : cfg \u2192 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 \u2192 cfg` sets up the initial state. The type `input` depends on the model;\n  in most cases it is `list \u0393`.\n* `eval : machine \u2192 input \u2192 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 \u2192 output` to\n  the final state to obtain the result. The type `output` depends on the model.\n* `supports : machine \u2192 finset \u039b \u2192 Prop` asserts that a machine `M` starts in `S : finset \u039b`, 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 `\u039b` 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\u2081` and `l\u2082` if `l\u2082` is obtained by adding\nblanks (`default \u0393`) to the end of `l\u2081`. -/\ndef blank_extends {\u0393 : Type u_1} [Inhabited \u0393] (l\u2081 : List \u0393) (l\u2082 : List \u0393) :=\n  \u2203 (n : \u2115), l\u2082 = l\u2081 ++ list.repeat Inhabited.default n\n\ntheorem blank_extends.refl {\u0393 : Type u_1} [Inhabited \u0393] (l : List \u0393) : blank_extends l l := sorry\n\ntheorem blank_extends.trans {\u0393 : Type u_1} [Inhabited \u0393] {l\u2081 : List \u0393} {l\u2082 : List \u0393} {l\u2083 : List \u0393} : blank_extends l\u2081 l\u2082 \u2192 blank_extends l\u2082 l\u2083 \u2192 blank_extends l\u2081 l\u2083 := sorry\n\ntheorem blank_extends.below_of_le {\u0393 : Type u_1} [Inhabited \u0393] {l : List \u0393} {l\u2081 : List \u0393} {l\u2082 : List \u0393} : blank_extends l l\u2081 \u2192 blank_extends l l\u2082 \u2192 list.length l\u2081 \u2264 list.length l\u2082 \u2192 blank_extends l\u2081 l\u2082 := sorry\n\n/-- Any two extensions by blank `l\u2081,l\u2082` of `l` have a common join (which can be taken to be the\nlonger of `l\u2081` and `l\u2082`). -/\ndef blank_extends.above {\u0393 : Type u_1} [Inhabited \u0393] {l : List \u0393} {l\u2081 : List \u0393} {l\u2082 : List \u0393} (h\u2081 : blank_extends l l\u2081) (h\u2082 : blank_extends l l\u2082) : Subtype fun (l' : List \u0393) => blank_extends l\u2081 l' \u2227 blank_extends l\u2082 l' :=\n  dite (list.length l\u2081 \u2264 list.length l\u2082) (fun (h : list.length l\u2081 \u2264 list.length l\u2082) => { val := l\u2082, property := sorry })\n    fun (h : \u00aclist.length l\u2081 \u2264 list.length l\u2082) => { val := l\u2081, property := sorry }\n\ntheorem blank_extends.above_of_le {\u0393 : Type u_1} [Inhabited \u0393] {l : List \u0393} {l\u2081 : List \u0393} {l\u2082 : List \u0393} : blank_extends l\u2081 l \u2192 blank_extends l\u2082 l \u2192 list.length l\u2081 \u2264 list.length l\u2082 \u2192 blank_extends l\u2081 l\u2082 := 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 {\u0393 : Type u_1} [Inhabited \u0393] (l\u2081 : List \u0393) (l\u2082 : List \u0393) :=\n  blank_extends l\u2081 l\u2082 \u2228 blank_extends l\u2082 l\u2081\n\ntheorem blank_rel.refl {\u0393 : Type u_1} [Inhabited \u0393] (l : List \u0393) : blank_rel l l :=\n  Or.inl (blank_extends.refl l)\n\ntheorem blank_rel.symm {\u0393 : Type u_1} [Inhabited \u0393] {l\u2081 : List \u0393} {l\u2082 : List \u0393} : blank_rel l\u2081 l\u2082 \u2192 blank_rel l\u2082 l\u2081 :=\n  or.symm\n\ntheorem blank_rel.trans {\u0393 : Type u_1} [Inhabited \u0393] {l\u2081 : List \u0393} {l\u2082 : List \u0393} {l\u2083 : List \u0393} : blank_rel l\u2081 l\u2082 \u2192 blank_rel l\u2082 l\u2083 \u2192 blank_rel l\u2081 l\u2083 := sorry\n\n/-- Given two `blank_rel` lists, there exists (constructively) a common join. -/\ndef blank_rel.above {\u0393 : Type u_1} [Inhabited \u0393] {l\u2081 : List \u0393} {l\u2082 : List \u0393} (h : blank_rel l\u2081 l\u2082) : Subtype fun (l : List \u0393) => blank_extends l\u2081 l \u2227 blank_extends l\u2082 l :=\n  dite (list.length l\u2081 \u2264 list.length l\u2082) (fun (hl : list.length l\u2081 \u2264 list.length l\u2082) => { val := l\u2082, property := sorry })\n    fun (hl : \u00aclist.length l\u2081 \u2264 list.length l\u2082) => { val := l\u2081, property := sorry }\n\n/-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/\ndef blank_rel.old_below {\u0393 : Type u_1} [Inhabited \u0393] {l\u2081 : List \u0393} {l\u2082 : List \u0393} (h : blank_rel l\u2081 l\u2082) : Subtype fun (l : List \u0393) => blank_extends l l\u2081 \u2227 blank_extends l l\u2082 :=\n  dite (list.length l\u2081 \u2264 list.length l\u2082)\n    (fun (hl : list.length l\u2081 \u2264 list.length l\u2082) => { val := l\u2081, property := blank_rel.below._proof_1 h hl })\n    fun (hl : \u00aclist.length l\u2081 \u2264 list.length l\u2082) => { val := l\u2082, property := blank_rel.below._proof_2 h hl }\n\ntheorem blank_rel.equivalence (\u0393 : Type u_1) [Inhabited \u0393] : 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 (\u0393 : Type u_1) [Inhabited \u0393] : setoid (List \u0393) :=\n  setoid.mk blank_rel (blank_rel.equivalence \u0393)\n\n/-- A `list_blank \u0393` is a quotient of `list \u0393` 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 (\u0393 : Type u_1) [Inhabited \u0393] :=\n  quotient (blank_rel.setoid \u0393)\n\nprotected instance list_blank.inhabited {\u0393 : Type u_1} [Inhabited \u0393] : Inhabited (list_blank \u0393) :=\n  { default := quotient.mk' [] }\n\nprotected instance list_blank.has_emptyc {\u0393 : Type u_1} [Inhabited \u0393] : has_emptyc (list_blank \u0393) :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u03b1 : Sort u_2} (l : list_blank \u0393) (f : List \u0393 \u2192 \u03b1) (H : \u2200 (a b : List \u0393), blank_extends a b \u2192 f a = f b) : \u03b1 :=\n  quotient.lift_on' l f sorry\n\n/-- The quotient map turning a `list` into a `list_blank`. -/\ndef list_blank.mk {\u0393 : Type u_1} [Inhabited \u0393] : List \u0393 \u2192 list_blank \u0393 :=\n  quotient.mk'\n\nprotected theorem list_blank.induction_on {\u0393 : Type u_1} [Inhabited \u0393] {p : list_blank \u0393 \u2192 Prop} (q : list_blank \u0393) (h : \u2200 (a : List \u0393), 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 {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) : \u0393 :=\n  list_blank.lift_on l list.head sorry\n\n@[simp] theorem list_blank.head_mk {\u0393 : Type u_1} [Inhabited \u0393] (l : List \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) : list_blank \u0393 :=\n  list_blank.lift_on l (fun (l : List \u0393) => list_blank.mk (list.tail l)) sorry\n\n@[simp] theorem list_blank.tail_mk {\u0393 : Type u_1} [Inhabited \u0393] (l : List \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] (a : \u0393) (l : list_blank \u0393) : list_blank \u0393 :=\n  list_blank.lift_on l (fun (l : List \u0393) => list_blank.mk (a :: l)) sorry\n\n@[simp] theorem list_blank.cons_mk {\u0393 : Type u_1} [Inhabited \u0393] (a : \u0393) (l : List \u0393) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) :=\n  rfl\n\n@[simp] theorem list_blank.head_cons {\u0393 : Type u_1} [Inhabited \u0393] (a : \u0393) (l : list_blank \u0393) : list_blank.head (list_blank.cons a l) = a :=\n  quotient.ind' fun (l : List \u0393) => rfl\n\n@[simp] theorem list_blank.tail_cons {\u0393 : Type u_1} [Inhabited \u0393] (a : \u0393) (l : list_blank \u0393) : list_blank.tail (list_blank.cons a l) = l :=\n  quotient.ind' fun (l : List \u0393) => 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 {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) : \u2203 (a : \u0393), \u2203 (l' : list_blank \u0393), 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 : \u2115`, unlike in a `list`. -/\ndef list_blank.nth {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) (n : \u2115) : \u0393 :=\n  list_blank.lift_on l (fun (l : List \u0393) => list.inth l n) sorry\n\n@[simp] theorem list_blank.nth_mk {\u0393 : Type u_1} [Inhabited \u0393] (l : List \u0393) (n : \u2115) : list_blank.nth (list_blank.mk l) n = list.inth l n :=\n  rfl\n\n@[simp] theorem list_blank.nth_zero {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) : list_blank.nth l 0 = list_blank.head l := sorry\n\n@[simp] theorem list_blank.nth_succ {\u0393 : Type u_1} [Inhabited \u0393] (l : list_blank \u0393) (n : \u2115) : list_blank.nth l (n + 1) = list_blank.nth (list_blank.tail l) n := sorry\n\ntheorem list_blank.ext {\u0393 : Type u_1} [Inhabited \u0393] {L\u2081 : list_blank \u0393} {L\u2082 : list_blank \u0393} : (\u2200 (i : \u2115), list_blank.nth L\u2081 i = list_blank.nth L\u2082 i) \u2192 L\u2081 = L\u2082 := sorry\n\n/-- Apply a function to a value stored at the nth position of the list. -/\n@[simp] def list_blank.modify_nth {\u0393 : Type u_1} [Inhabited \u0393] (f : \u0393 \u2192 \u0393) : \u2115 \u2192 list_blank \u0393 \u2192 list_blank \u0393 :=\n  sorry\n\ntheorem list_blank.nth_modify_nth {\u0393 : Type u_1} [Inhabited \u0393] (f : \u0393 \u2192 \u0393) (n : \u2115) (i : \u2115) (L : list_blank \u0393) : 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 (\u0393 : Type u) (\u0393' : Type v) [Inhabited \u0393] [Inhabited \u0393'] \nwhere\n  f : \u0393 \u2192 \u0393'\n  map_pt' : f Inhabited.default = Inhabited.default\n\nprotected instance pointed_map.inhabited {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] : Inhabited (pointed_map \u0393 \u0393') :=\n  { default := pointed_map.mk (fun (_x : \u0393) => Inhabited.default) sorry }\n\nprotected instance pointed_map.has_coe_to_fun {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] : has_coe_to_fun (pointed_map \u0393 \u0393') :=\n  has_coe_to_fun.mk (fun (x : pointed_map \u0393 \u0393') => \u0393 \u2192 \u0393') pointed_map.f\n\n@[simp] theorem pointed_map.mk_val {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : \u0393 \u2192 \u0393') (pt : f Inhabited.default = Inhabited.default) : \u21d1(pointed_map.mk f pt) = f :=\n  rfl\n\n@[simp] theorem pointed_map.map_pt {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') : coe_fn f Inhabited.default = Inhabited.default :=\n  pointed_map.map_pt' f\n\n@[simp] theorem pointed_map.head_map {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : List \u0393) : list.head (list.map (\u21d1f) l) = coe_fn f (list.head l) :=\n  list.cases_on l (Eq.symm (pointed_map.map_pt f))\n    fun (l_hd : \u0393) (l_tl : List \u0393) => Eq.refl (list.head (list.map (\u21d1f) (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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : list_blank \u0393) : list_blank \u0393' :=\n  list_blank.lift_on l (fun (l : List \u0393) => list_blank.mk (list.map (\u21d1f) l)) sorry\n\n@[simp] theorem list_blank.map_mk {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : List \u0393) : list_blank.map f (list_blank.mk l) = list_blank.mk (list.map (\u21d1f) l) :=\n  rfl\n\n@[simp] theorem list_blank.head_map {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : list_blank \u0393) : list_blank.head (list_blank.map f l) = coe_fn f (list_blank.head l) := sorry\n\n@[simp] theorem list_blank.tail_map {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : list_blank \u0393) : 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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : list_blank \u0393) (a : \u0393) : 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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : list_blank \u0393) (n : \u2115) : 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 {\u03b9 : Type u_1} {\u0393 : \u03b9 \u2192 Type u_2} [(i : \u03b9) \u2192 Inhabited (\u0393 i)] (i : \u03b9) : pointed_map ((i : \u03b9) \u2192 \u0393 i) (\u0393 i) :=\n  pointed_map.mk (fun (a : (i : \u03b9) \u2192 \u0393 i) => a i) sorry\n\ntheorem proj_map_nth {\u03b9 : Type u_1} {\u0393 : \u03b9 \u2192 Type u_2} [(i : \u03b9) \u2192 Inhabited (\u0393 i)] (i : \u03b9) (L : list_blank ((i : \u03b9) \u2192 \u0393 i)) (n : \u2115) : list_blank.nth (list_blank.map (proj i) L) n = list_blank.nth L n i := sorry\n\ntheorem list_blank.map_modify_nth {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (F : pointed_map \u0393 \u0393') (f : \u0393 \u2192 \u0393) (f' : \u0393' \u2192 \u0393') (H : \u2200 (x : \u0393), coe_fn F (f x) = f' (coe_fn F x)) (n : \u2115) (L : list_blank \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] : List \u0393 \u2192 list_blank \u0393 \u2192 list_blank \u0393 :=\n  sorry\n\n@[simp] theorem list_blank.append_mk {\u0393 : Type u_1} [Inhabited \u0393] (l\u2081 : List \u0393) (l\u2082 : List \u0393) : list_blank.append l\u2081 (list_blank.mk l\u2082) = list_blank.mk (l\u2081 ++ l\u2082) := sorry\n\ntheorem list_blank.append_assoc {\u0393 : Type u_1} [Inhabited \u0393] (l\u2081 : List \u0393) (l\u2082 : List \u0393) (l\u2083 : list_blank \u0393) : list_blank.append (l\u2081 ++ l\u2082) l\u2083 = list_blank.append l\u2081 (list_blank.append l\u2082 l\u2083) := 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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (l : list_blank \u0393) (f : \u0393 \u2192 List \u0393') (hf : \u2203 (n : \u2115), f Inhabited.default = list.repeat Inhabited.default n) : list_blank \u0393' :=\n  list_blank.lift_on l (fun (l : List \u0393) => list_blank.mk (list.bind l f)) sorry\n\n@[simp] theorem list_blank.bind_mk {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (l : List \u0393) (f : \u0393 \u2192 List \u0393') (hf : \u2203 (n : \u2115), 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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (a : \u0393) (l : list_blank \u0393) (f : \u0393 \u2192 List \u0393') (hf : \u2203 (n : \u2115), 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 (\u0393 : Type u_1) [Inhabited \u0393] \nwhere\n  head : \u0393\n  left : list_blank \u0393\n  right : list_blank \u0393\n\nprotected instance tape.inhabited {\u0393 : Type u_1} [Inhabited \u0393] : Inhabited (tape \u0393) :=\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\u2080 {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : list_blank \u0393 :=\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\u2080 {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : list_blank \u0393 :=\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 {\u0393 : Type u_1} [Inhabited \u0393] : dir \u2192 tape \u0393 \u2192 tape \u0393 :=\n  sorry\n\n@[simp] theorem tape.move_left_right {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : tape.move dir.right (tape.move dir.left T) = T := sorry\n\n@[simp] theorem tape.move_right_left {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : 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' {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : tape \u0393 :=\n  tape.mk (list_blank.head R) L (list_blank.tail R)\n\n@[simp] theorem tape.mk'_left {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : tape.left (tape.mk' L R) = L :=\n  rfl\n\n@[simp] theorem tape.mk'_head {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : tape.head (tape.mk' L R) = list_blank.head R :=\n  rfl\n\n@[simp] theorem tape.mk'_right {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : tape.right (tape.mk' L R) = list_blank.tail R :=\n  rfl\n\n@[simp] theorem tape.mk'_right\u2080 {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : tape.right\u2080 (tape.mk' L R) = R :=\n  list_blank.cons_head_tail R\n\n@[simp] theorem tape.mk'_left_right\u2080 {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : tape.mk' (tape.left T) (tape.right\u2080 T) = T := sorry\n\ntheorem tape.exists_mk' {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : \u2203 (L : list_blank \u0393), \u2203 (R : list_blank \u0393), T = tape.mk' L R :=\n  Exists.intro (tape.left T) (Exists.intro (tape.right\u2080 T) (Eq.symm (tape.mk'_left_right\u2080 T)))\n\n@[simp] theorem tape.move_left_mk' {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : 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' {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) : 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\u2082 {\u0393 : Type u_1} [Inhabited \u0393] (L : List \u0393) (R : List \u0393) : tape \u0393 :=\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\u2081 {\u0393 : Type u_1} [Inhabited \u0393] (l : List \u0393) : tape \u0393 :=\n  tape.mk\u2082 [] 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 {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : \u2124 \u2192 \u0393 :=\n  sorry\n\n@[simp] theorem tape.nth_zero {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : tape.nth T 0 = tape.head T :=\n  rfl\n\ntheorem tape.right\u2080_nth {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) (n : \u2115) : list_blank.nth (tape.right\u2080 T) n = tape.nth T \u2191n := sorry\n\n@[simp] theorem tape.mk'_nth_nat {\u0393 : Type u_1} [Inhabited \u0393] (L : list_blank \u0393) (R : list_blank \u0393) (n : \u2115) : tape.nth (tape.mk' L R) \u2191n = list_blank.nth R n := sorry\n\n@[simp] theorem tape.move_left_nth {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) (i : \u2124) : tape.nth (tape.move dir.left T) i = tape.nth T (i - 1) := sorry\n\n@[simp] theorem tape.move_right_nth {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) (i : \u2124) : tape.nth (tape.move dir.right T) i = tape.nth T (i + 1) := sorry\n\n@[simp] theorem tape.move_right_n_head {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) (i : \u2115) : tape.head (nat.iterate (tape.move dir.right) i T) = tape.nth T \u2191i := sorry\n\n/-- Replace the current value of the head on the tape. -/\ndef tape.write {\u0393 : Type u_1} [Inhabited \u0393] (b : \u0393) (T : tape \u0393) : tape \u0393 :=\n  tape.mk b (tape.left T) (tape.right T)\n\n@[simp] theorem tape.write_self {\u0393 : Type u_1} [Inhabited \u0393] (T : tape \u0393) : tape.write (tape.head T) T = T :=\n  tape.cases_on T\n    fun (T_head : \u0393) (T_left T_right : list_blank \u0393) =>\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 {\u0393 : Type u_1} [Inhabited \u0393] (b : \u0393) (T : tape \u0393) {i : \u2124} : tape.nth (tape.write b T) i = ite (i = 0) b (tape.nth T i) := sorry\n\n@[simp] theorem tape.write_mk' {\u0393 : Type u_1} [Inhabited \u0393] (a : \u0393) (b : \u0393) (L : list_blank \u0393) (R : list_blank \u0393) : 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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (T : tape \u0393) : tape \u0393' :=\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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (T : tape \u0393) : tape.head (tape.map f T) = coe_fn f (tape.head T) :=\n  tape.cases_on T\n    fun (T_head : \u0393) (T_left T_right : list_blank \u0393) => Eq.refl (tape.head (tape.map f (tape.mk T_head T_left T_right)))\n\n@[simp] theorem tape.map_write {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (b : \u0393) (T : tape \u0393) : 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 : \u0393) (T_left T_right : list_blank \u0393) =>\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 {\u0393 : Type u_1} [Inhabited \u0393] (f : \u0393 \u2192 \u0393) (L : list_blank \u0393) (R : list_blank \u0393) (n : \u2115) : 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 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (T : tape \u0393) (d : dir) : tape.map f (tape.move d T) = tape.move d (tape.map f T) := sorry\n\ntheorem tape.map_mk' {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (L : list_blank \u0393) (R : list_blank \u0393) : 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\u2082 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (L : List \u0393) (R : List \u0393) : tape.map f (tape.mk\u2082 L R) = tape.mk\u2082 (list.map (\u21d1f) L) (list.map (\u21d1f) R) := sorry\n\ntheorem tape.map_mk\u2081 {\u0393 : Type u_1} {\u0393' : Type u_2} [Inhabited \u0393] [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') (l : List \u0393) : tape.map f (tape.mk\u2081 l) = tape.mk\u2081 (list.map (\u21d1f) l) :=\n  tape.map_mk\u2082 f [] l\n\n/-- Run a state transition function `\u03c3 \u2192 option \u03c3` \"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 {\u03c3 : Type u_1} (f : \u03c3 \u2192 Option \u03c3) : \u03c3 \u2192 roption \u03c3 :=\n  pfun.fix fun (s : \u03c3) => 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\u2081`, `f a\u2081 = some a\u2082`, ... such that `a\u2099 = b`.\nThis relation permits zero steps of the state transition function. -/\ndef reaches {\u03c3 : Type u_1} (f : \u03c3 \u2192 Option \u03c3) : \u03c3 \u2192 \u03c3 \u2192 Prop :=\n  relation.refl_trans_gen fun (a b : \u03c3) => b \u2208 f a\n\n/-- The transitive closure of a state transition function. `reaches\u2081 f a b` means there is a\nnonempty finite sequence of steps `f a = some a\u2081`, `f a\u2081 = some a\u2082`, ... such that `a\u2099 = b`.\nThis relation does not permit zero steps of the state transition function. -/\ndef reaches\u2081 {\u03c3 : Type u_1} (f : \u03c3 \u2192 Option \u03c3) : \u03c3 \u2192 \u03c3 \u2192 Prop :=\n  relation.trans_gen fun (a b : \u03c3) => b \u2208 f a\n\ntheorem reaches\u2081_eq {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} (h : f a = f b) : reaches\u2081 f a c \u2194 reaches\u2081 f b c := sorry\n\ntheorem reaches_total {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} : reaches f a b \u2192 reaches f a c \u2192 reaches f b c \u2228 reaches f c b :=\n  relation.refl_trans_gen.total_of_right_unique fun (_x _x_1 _x_2 : \u03c3) => option.mem_unique\n\ntheorem reaches\u2081_fwd {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} (h\u2081 : reaches\u2081 f a c) (h\u2082 : b \u2208 f a) : reaches f b c := sorry\n\n/-- A variation on `reaches`. `reaches\u2080 f a b` holds if whenever `reaches\u2081 f b c` then\n`reaches\u2081 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\u2080 {\u03c3 : Type u_1} (f : \u03c3 \u2192 Option \u03c3) (a : \u03c3) (b : \u03c3) :=\n  \u2200 (c : \u03c3), reaches\u2081 f b c \u2192 reaches\u2081 f a c\n\ntheorem reaches\u2080.trans {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} (h\u2081 : reaches\u2080 f a b) (h\u2082 : reaches\u2080 f b c) : reaches\u2080 f a c :=\n  fun (c_1 : \u03c3) (\u1fb0 : reaches\u2081 f c c_1) => idRhs (reaches\u2081 f a c_1) (h\u2081 c_1 (h\u2082 c_1 \u1fb0))\n\ntheorem reaches\u2080.refl {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} (a : \u03c3) : reaches\u2080 f a a :=\n  fun (c : \u03c3) (\u1fb0 : reaches\u2081 f a c) => idRhs (reaches\u2081 f a c) \u1fb0\n\ntheorem reaches\u2080.single {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (h : b \u2208 f a) : reaches\u2080 f a b :=\n  fun (c : \u03c3) (\u1fb0 : reaches\u2081 f b c) =>\n    idRhs (relation.trans_gen (fun (a b : \u03c3) => b \u2208 f a) a c) (relation.trans_gen.head h \u1fb0)\n\ntheorem reaches\u2080.head {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} (h : b \u2208 f a) (h\u2082 : reaches\u2080 f b c) : reaches\u2080 f a c :=\n  reaches\u2080.trans (reaches\u2080.single h) h\u2082\n\ntheorem reaches\u2080.tail {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} (h\u2081 : reaches\u2080 f a b) (h : c \u2208 f b) : reaches\u2080 f a c :=\n  reaches\u2080.trans h\u2081 (reaches\u2080.single h)\n\ntheorem reaches\u2080_eq {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (e : f a = f b) : reaches\u2080 f a b :=\n  fun (c : \u03c3) (\u1fb0 : reaches\u2081 f b c) => idRhs (reaches\u2081 f a c) (iff.mpr (reaches\u2081_eq e) \u1fb0)\n\ntheorem reaches\u2081.to\u2080 {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (h : reaches\u2081 f a b) : reaches\u2080 f a b :=\n  fun (c : \u03c3) (\u1fb0 : reaches\u2081 f b c) =>\n    idRhs (relation.trans_gen (fun (a b : \u03c3) => b \u2208 f a) a c) (relation.trans_gen.trans h \u1fb0)\n\ntheorem reaches.to\u2080 {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (h : reaches f a b) : reaches\u2080 f a b :=\n  fun (c : \u03c3) (\u1fb0 : reaches\u2081 f b c) =>\n    idRhs (relation.trans_gen (fun (a b : \u03c3) => b \u2208 f a) a c) (relation.trans_gen.trans_right h \u1fb0)\n\ntheorem reaches\u2080.tail' {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} {c : \u03c3} (h : reaches\u2080 f a b) (h\u2082 : c \u2208 f b) : reaches\u2081 f a c :=\n  h c (relation.trans_gen.single h\u2082)\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 {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {b : \u03c3} {C : \u03c3 \u2192 Sort u_2} {a : \u03c3} (h : b \u2208 eval f a) (H : (a : \u03c3) \u2192 b \u2208 eval f a \u2192 ((a' : \u03c3) \u2192 b \u2208 eval f a' \u2192 f a = some a' \u2192 C a') \u2192 C a) : C a :=\n  pfun.fix_induction h\n    fun (a' : \u03c3) (ha' : b \u2208 pfun.fix (fun (s : \u03c3) => roption.some (option.elim (f s) (sum.inl s) sum.inr)) a')\n      (h' :\n      (a'_1 : \u03c3) \u2192\n        b \u2208 pfun.fix (fun (s : \u03c3) => roption.some (option.elim (f s) (sum.inl s) sum.inr)) a'_1 \u2192\n          sum.inr a'_1 \u2208 roption.some (option.elim (f a') (sum.inl a') sum.inr) \u2192 C a'_1) =>\n      H a' ha' fun (b' : \u03c3) (hb' : b \u2208 eval f b') (e : f a' = some b') => h' b' hb' sorry\n\ntheorem mem_eval {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} : b \u2208 eval f a \u2194 reaches f a b \u2227 f b = none := sorry\n\ntheorem eval_maximal\u2081 {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (h : b \u2208 eval f a) (c : \u03c3) : \u00acreaches\u2081 f b c := sorry\n\ntheorem eval_maximal {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (h : b \u2208 eval f a) {c : \u03c3} : reaches f b c \u2194 c = b := sorry\n\ntheorem reaches_eval {\u03c3 : Type u_1} {f : \u03c3 \u2192 Option \u03c3} {a : \u03c3} {b : \u03c3} (ab : reaches f a b) : eval f a = eval f b := sorry\n\n/-- Given a relation `tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop` between state spaces, and state transition functions\n`f\u2081 : \u03c3\u2081 \u2192 option \u03c3\u2081` and `f\u2082 : \u03c3\u2082 \u2192 option \u03c3\u2082`, `respects f\u2081 f\u2082 tr` means that if `tr a\u2081 a\u2082` holds\ninitially and `f\u2081` takes a step to `a\u2082` then `f\u2082` will take one or more steps before reaching a\nstate `b\u2082` satisfying `tr a\u2082 b\u2082`, and if `f\u2081 a\u2081` terminates then `f\u2082 a\u2082` also terminates.\nSuch a relation `tr` is also known as a refinement. -/\ndef respects {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} (f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081) (f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082) (tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop) :=\n  {a\u2081 : \u03c3\u2081} \u2192 {a\u2082 : \u03c3\u2082} \u2192 tr a\u2081 a\u2082 \u2192 sorry\n\ntheorem tr_reaches\u2081 {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop} (H : respects f\u2081 f\u2082 tr) {a\u2081 : \u03c3\u2081} {a\u2082 : \u03c3\u2082} (aa : tr a\u2081 a\u2082) {b\u2081 : \u03c3\u2081} (ab : reaches\u2081 f\u2081 a\u2081 b\u2081) : \u2203 (b\u2082 : \u03c3\u2082), tr b\u2081 b\u2082 \u2227 reaches\u2081 f\u2082 a\u2082 b\u2082 := sorry\n\ntheorem tr_reaches {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop} (H : respects f\u2081 f\u2082 tr) {a\u2081 : \u03c3\u2081} {a\u2082 : \u03c3\u2082} (aa : tr a\u2081 a\u2082) {b\u2081 : \u03c3\u2081} (ab : reaches f\u2081 a\u2081 b\u2081) : \u2203 (b\u2082 : \u03c3\u2082), tr b\u2081 b\u2082 \u2227 reaches f\u2082 a\u2082 b\u2082 := sorry\n\ntheorem tr_reaches_rev {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop} (H : respects f\u2081 f\u2082 tr) {a\u2081 : \u03c3\u2081} {a\u2082 : \u03c3\u2082} (aa : tr a\u2081 a\u2082) {b\u2082 : \u03c3\u2082} (ab : reaches f\u2082 a\u2082 b\u2082) : \u2203 (c\u2081 : \u03c3\u2081), \u2203 (c\u2082 : \u03c3\u2082), reaches f\u2082 b\u2082 c\u2082 \u2227 tr c\u2081 c\u2082 \u2227 reaches f\u2081 a\u2081 c\u2081 := sorry\n\ntheorem tr_eval {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop} (H : respects f\u2081 f\u2082 tr) {a\u2081 : \u03c3\u2081} {b\u2081 : \u03c3\u2081} {a\u2082 : \u03c3\u2082} (aa : tr a\u2081 a\u2082) (ab : b\u2081 \u2208 eval f\u2081 a\u2081) : \u2203 (b\u2082 : \u03c3\u2082), tr b\u2081 b\u2082 \u2227 b\u2082 \u2208 eval f\u2082 a\u2082 := sorry\n\ntheorem tr_eval_rev {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop} (H : respects f\u2081 f\u2082 tr) {a\u2081 : \u03c3\u2081} {b\u2082 : \u03c3\u2082} {a\u2082 : \u03c3\u2082} (aa : tr a\u2081 a\u2082) (ab : b\u2082 \u2208 eval f\u2082 a\u2082) : \u2203 (b\u2081 : \u03c3\u2081), tr b\u2081 b\u2082 \u2227 b\u2081 \u2208 eval f\u2081 a\u2081 := sorry\n\ntheorem tr_eval_dom {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop} (H : respects f\u2081 f\u2082 tr) {a\u2081 : \u03c3\u2081} {a\u2082 : \u03c3\u2082} (aa : tr a\u2081 a\u2082) : roption.dom (eval f\u2082 a\u2082) \u2194 roption.dom (eval f\u2081 a\u2081) := sorry\n\n/-- A simpler version of `respects` when the state transition relation `tr` is a function. -/\ndef frespects {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} (f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082) (tr : \u03c3\u2081 \u2192 \u03c3\u2082) (a\u2082 : \u03c3\u2082) : Option \u03c3\u2081 \u2192 Prop :=\n  sorry\n\ntheorem frespects_eq {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082} {a\u2082 : \u03c3\u2082} {b\u2082 : \u03c3\u2082} (h : f\u2082 a\u2082 = f\u2082 b\u2082) {b\u2081 : Option \u03c3\u2081} : frespects f\u2082 tr a\u2082 b\u2081 \u2194 frespects f\u2082 tr b\u2082 b\u2081 := sorry\n\ntheorem fun_respects {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_2} {f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081} {f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082} : (respects f\u2081 f\u2082 fun (a : \u03c3\u2081) (b : \u03c3\u2082) => tr a = b) \u2194 \u2200 {a\u2081 : \u03c3\u2081}, frespects f\u2082 tr (tr a\u2081) (f\u2081 a\u2081) := sorry\n\ntheorem tr_eval' {\u03c3\u2081 : Type u_1} {\u03c3\u2082 : Type u_1} (f\u2081 : \u03c3\u2081 \u2192 Option \u03c3\u2081) (f\u2082 : \u03c3\u2082 \u2192 Option \u03c3\u2082) (tr : \u03c3\u2081 \u2192 \u03c3\u2082) (H : respects f\u2081 f\u2082 fun (a : \u03c3\u2081) (b : \u03c3\u2082) => tr a = b) (a\u2081 : \u03c3\u2081) : eval f\u2082 (tr a\u2081) = tr <$> eval f\u2081 a\u2081 := 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 `\u0393` and label type `\u039b` is a function\n`\u039b \u2192 \u0393 \u2192 option (\u039b \u00d7 stmt)`, where a `stmt` can be either `move left`, `move right` or `write a`\nfor `a : \u0393`. The machine works over a \"tape\", a doubly-infinite sequence of elements of `\u0393`, and\nan instantaneous configuration, `cfg`, is a label `q : \u039b` indicating the current internal state of\nthe machine, and a `tape \u0393` (which is essentially `\u2124 \u2192\u2080 \u0393`). 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 \u0393` and produces a `tape \u0393` 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 \u0393`, not a `list \u0393`, because we don't know, at this level\nof generality, where the output ends. If equality to `default \u0393` 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 (\u0393 : Type u_1) [Inhabited \u0393] \nwhere\n| move : dir \u2192 stmt \u0393\n| write : \u0393 \u2192 stmt \u0393\n\nprotected instance stmt.inhabited (\u0393 : Type u_1) [Inhabited \u0393] : Inhabited (stmt \u0393) :=\n  { default := stmt.write Inhabited.default }\n\n/-- A Post-Turing machine with symbol type `\u0393` and label type `\u039b`\n  is a function which, given the current state `q : \u039b` and\n  the tape head `a : \u0393`, either halts (returns `none`) or returns\n  a new state `q' : \u039b` and a `stmt` describing what to do,\n  either a move left or right, or a write command.\n\n  Both `\u039b` and `\u0393` are required to be inhabited; the default value\n  for `\u0393` is the \"blank\" tape value, and the default value of `\u039b` is\n  the initial state. -/\ndef machine (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) [Inhabited \u039b] :=\n  \u039b \u2192 \u0393 \u2192 Option (\u039b \u00d7 stmt \u0393)\n\nprotected instance machine.inhabited (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) [Inhabited \u039b] : Inhabited (machine \u0393 \u039b) :=\n  eq.mpr sorry (pi.inhabited \u039b)\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 (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) [Inhabited \u039b] \nwhere\n  q : \u039b\n  tape : tape \u0393\n\nprotected instance cfg.inhabited (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) [Inhabited \u039b] : Inhabited (cfg \u0393 \u039b) :=\n  { default := cfg.mk Inhabited.default Inhabited.default }\n\n/-- Execution semantics of the Turing machine. -/\ndef step {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : machine \u0393 \u039b) : cfg \u0393 \u039b \u2192 Option (cfg \u0393 \u039b) :=\n  sorry\n\n/-- The statement `reaches M s\u2081 s\u2082` means that `s\u2082` is obtained\n  starting from `s\u2081` after a finite number of steps from `s\u2082`. -/\ndef reaches {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : machine \u0393 \u039b) : cfg \u0393 \u039b \u2192 cfg \u0393 \u039b \u2192 Prop :=\n  relation.refl_trans_gen fun (a b : cfg \u0393 \u039b) => b \u2208 step M a\n\n/-- The initial configuration. -/\ndef init {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (l : List \u0393) : cfg \u0393 \u039b :=\n  cfg.mk Inhabited.default (tape.mk\u2081 l)\n\n/-- Evaluate a Turing machine on initial input to a final state,\n  if it terminates. -/\ndef eval {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : machine \u0393 \u039b) (l : List \u0393) : roption (list_blank \u0393) :=\n  roption.map (fun (c : cfg \u0393 \u039b) => tape.right\u2080 (cfg.tape c)) (eval (step M) (init l))\n\n/-- The raw definition of a Turing machine does not require that\n  `\u0393` and `\u039b` are finite, and in practice we will be interested\n  in the infinite `\u039b` 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 \u2286 \u039b`\n  supports a Turing machine `M` if `S` is closed under the\n  transition function and contains the initial state. -/\ndef supports {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : machine \u0393 \u039b) (S : set \u039b) :=\n  Inhabited.default \u2208 S \u2227 \u2200 {q : \u039b} {a : \u0393} {q' : \u039b} {s : stmt \u0393}, (q', s) \u2208 M q a \u2192 q \u2208 S \u2192 q' \u2208 S\n\ntheorem step_supports {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : machine \u0393 \u039b) {S : set \u039b} (ss : supports M S) {c : cfg \u0393 \u039b} {c' : cfg \u0393 \u039b} : c' \u2208 step M c \u2192 cfg.q c \u2208 S \u2192 cfg.q c' \u2208 S := sorry\n\ntheorem univ_supports {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : machine \u0393 \u039b) : supports M set.univ :=\n  { left := trivial,\n    right := fun (q : \u039b) (a : \u0393) (q' : \u039b) (s : stmt \u0393) (h\u2081 : (q', s) \u2208 M q a) (h\u2082 : q \u2208 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u0393' : Type u_2} [Inhabited \u0393'] (f : pointed_map \u0393 \u0393') : stmt \u0393 \u2192 stmt \u0393' :=\n  sorry\n\n/-- Map a configuration across a function, given `f : \u0393 \u2192 \u0393'` a map of the alphabets and\n`g : \u039b \u2192 \u039b'` a map of the machine states. -/\ndef cfg.map {\u0393 : Type u_1} [Inhabited \u0393] {\u0393' : Type u_2} [Inhabited \u0393'] {\u039b : Type u_3} [Inhabited \u039b] {\u039b' : Type u_4} [Inhabited \u039b'] (f : pointed_map \u0393 \u0393') (g : \u039b \u2192 \u039b') : cfg \u0393 \u039b \u2192 cfg \u0393' \u039b' :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u0393' : Type u_2} [Inhabited \u0393'] {\u039b : Type u_3} [Inhabited \u039b] {\u039b' : Type u_4} [Inhabited \u039b'] (M : machine \u0393 \u039b) (f\u2081 : pointed_map \u0393 \u0393') (f\u2082 : pointed_map \u0393' \u0393) (g\u2081 : \u039b \u2192 \u039b') (g\u2082 : \u039b' \u2192 \u039b) : machine \u0393' \u039b' :=\n  sorry\n\ntheorem machine.map_step {\u0393 : Type u_1} [Inhabited \u0393] {\u0393' : Type u_2} [Inhabited \u0393'] {\u039b : Type u_3} [Inhabited \u039b] {\u039b' : Type u_4} [Inhabited \u039b'] (M : machine \u0393 \u039b) (f\u2081 : pointed_map \u0393 \u0393') (f\u2082 : pointed_map \u0393' \u0393) (g\u2081 : \u039b \u2192 \u039b') (g\u2082 : \u039b' \u2192 \u039b) {S : set \u039b} (f\u2082\u2081 : function.right_inverse \u21d1f\u2081 \u21d1f\u2082) (g\u2082\u2081 : \u2200 (q : \u039b), q \u2208 S \u2192 g\u2082 (g\u2081 q) = q) (c : cfg \u0393 \u039b) : cfg.q c \u2208 S \u2192 option.map (cfg.map f\u2081 g\u2081) (step M c) = step (machine.map M f\u2081 f\u2082 g\u2081 g\u2082) (cfg.map f\u2081 g\u2081 c) := sorry\n\ntheorem map_init {\u0393 : Type u_1} [Inhabited \u0393] {\u0393' : Type u_2} [Inhabited \u0393'] {\u039b : Type u_3} [Inhabited \u039b] {\u039b' : Type u_4} [Inhabited \u039b'] (f\u2081 : pointed_map \u0393 \u0393') (g\u2081 : pointed_map \u039b \u039b') (l : List \u0393) : cfg.map f\u2081 (\u21d1g\u2081) (init l) = init (list.map (\u21d1f\u2081) l) :=\n  congr (congr_arg cfg.mk (pointed_map.map_pt g\u2081)) (tape.map_mk\u2081 f\u2081 l)\n\ntheorem machine.map_respects {\u0393 : Type u_1} [Inhabited \u0393] {\u0393' : Type u_2} [Inhabited \u0393'] {\u039b : Type u_3} [Inhabited \u039b] {\u039b' : Type u_4} [Inhabited \u039b'] (M : machine \u0393 \u039b) (f\u2081 : pointed_map \u0393 \u0393') (f\u2082 : pointed_map \u0393' \u0393) (g\u2081 : pointed_map \u039b \u039b') (g\u2082 : \u039b' \u2192 \u039b) {S : set \u039b} (ss : supports M S) (f\u2082\u2081 : function.right_inverse \u21d1f\u2081 \u21d1f\u2082) (g\u2082\u2081 : \u2200 (q : \u039b), q \u2208 S \u2192 g\u2082 (coe_fn g\u2081 q) = q) : respects (step M) (step (machine.map M f\u2081 f\u2082 (\u21d1g\u2081) g\u2082))\n  fun (a : cfg \u0393 \u039b) (b : cfg \u0393' \u039b') => cfg.q a \u2208 S \u2227 cfg.map f\u2081 (\u21d1g\u2081) 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 `\u03c3` of variables\nthat may be accessed and updated at any time.\n\nA machine is given by a `\u039b` 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 : \u0393 \u2192 \u03c3 \u2192 \u0393) q`: write `f a T.head` to the tape, then do `q`\n* `load (f : \u0393 \u2192 \u03c3 \u2192 \u03c3) q`: change the internal state to `f a T.head`\n* `branch (f : \u0393 \u2192 \u03c3 \u2192 bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`\n* `goto (f : \u0393 \u2192 \u03c3 \u2192 \u039b)`: 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 `\u03c3` of variables\n  that may be accessed and updated at any time.\n  A machine is given by a `\u039b` 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 (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) (\u03c3 : Type u_3) \nwhere\n| move : dir \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| write : (\u0393 \u2192 \u03c3 \u2192 \u0393) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| load : (\u0393 \u2192 \u03c3 \u2192 \u03c3) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| branch : (\u0393 \u2192 \u03c3 \u2192 Bool) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| goto : (\u0393 \u2192 \u03c3 \u2192 \u039b) \u2192 stmt \u0393 \u039b \u03c3\n| halt : stmt \u0393 \u039b \u03c3\n\nprotected instance stmt.inhabited (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) (\u03c3 : Type u_3) : Inhabited (stmt \u0393 \u039b \u03c3) :=\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 (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) (\u03c3 : Type u_3) \nwhere\n  l : Option \u039b\n  var : \u03c3\n  tape : tape \u0393\n\nprotected instance cfg.inhabited (\u0393 : Type u_1) [Inhabited \u0393] (\u039b : Type u_2) (\u03c3 : Type u_3) [Inhabited \u03c3] : Inhabited (cfg \u0393 \u039b \u03c3) :=\n  { default := cfg.mk Inhabited.default Inhabited.default Inhabited.default }\n\n/-- The semantics of TM1 evaluation. -/\ndef step_aux {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} : stmt \u0393 \u039b \u03c3 \u2192 \u03c3 \u2192 tape \u0393 \u2192 cfg \u0393 \u039b \u03c3 :=\n  sorry\n\n/-- The state transition function. -/\ndef step {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) : cfg \u0393 \u039b \u03c3 \u2192 Option (cfg \u0393 \u039b \u03c3) :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} (S : finset \u039b) : stmt \u0393 \u039b \u03c3 \u2192 Prop :=\n  sorry\n\n/-- The subterm closure of a statement. -/\ndef stmts\u2081 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} : stmt \u0393 \u039b \u03c3 \u2192 finset (stmt \u0393 \u039b \u03c3) :=\n  sorry\n\ntheorem stmts\u2081_self {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} {q : stmt \u0393 \u039b \u03c3} : q \u2208 stmts\u2081 q := sorry\n\ntheorem stmts\u2081_trans {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} {q\u2081 : stmt \u0393 \u039b \u03c3} {q\u2082 : stmt \u0393 \u039b \u03c3} : q\u2081 \u2208 stmts\u2081 q\u2082 \u2192 stmts\u2081 q\u2081 \u2286 stmts\u2081 q\u2082 := sorry\n\ntheorem stmts\u2081_supports_stmt_mono {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} {S : finset \u039b} {q\u2081 : stmt \u0393 \u039b \u03c3} {q\u2082 : stmt \u0393 \u039b \u03c3} (h : q\u2081 \u2208 stmts\u2081 q\u2082) (hs : supports_stmt S q\u2082) : supports_stmt S q\u2081 := 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) (S : finset \u039b) : finset (Option (stmt \u0393 \u039b \u03c3)) :=\n  finset.insert_none (finset.bUnion S fun (q : \u039b) => stmts\u2081 (M q))\n\ntheorem stmts_trans {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} {M : \u039b \u2192 stmt \u0393 \u039b \u03c3} {S : finset \u039b} {q\u2081 : stmt \u0393 \u039b \u03c3} {q\u2082 : stmt \u0393 \u039b \u03c3} (h\u2081 : q\u2081 \u2208 stmts\u2081 q\u2082) : some q\u2082 \u2208 stmts M S \u2192 some q\u2081 \u2208 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} [Inhabited \u039b] (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) (S : finset \u039b) :=\n  Inhabited.default \u2208 S \u2227 \u2200 (q : \u039b), q \u2208 S \u2192 supports_stmt S (M q)\n\ntheorem stmts_supports_stmt {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} [Inhabited \u039b] {M : \u039b \u2192 stmt \u0393 \u039b \u03c3} {S : finset \u039b} {q : stmt \u0393 \u039b \u03c3} (ss : supports M S) : some q \u2208 stmts M S \u2192 supports_stmt S q := sorry\n\ntheorem step_supports {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} [Inhabited \u039b] (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) {S : finset \u039b} (ss : supports M S) {c : cfg \u0393 \u039b \u03c3} {c' : cfg \u0393 \u039b \u03c3} : c' \u2208 step M c \u2192 cfg.l c \u2208 finset.insert_none S \u2192 cfg.l c' \u2208 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} [Inhabited \u039b] [Inhabited \u03c3] (l : List \u0393) : cfg \u0393 \u039b \u03c3 :=\n  cfg.mk (some Inhabited.default) Inhabited.default (tape.mk\u2081 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} {\u03c3 : Type u_3} [Inhabited \u039b] [Inhabited \u03c3] (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) (l : List \u0393) : roption (list_blank \u0393) :=\n  roption.map (fun (c : cfg \u0393 \u039b \u03c3) => tape.right\u2080 (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 `\u0393` is the same for both TM1 and TM0\n* The set of states `\u039b'` is defined to be `option stmt\u2081 \u00d7 \u03c3`, 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\u2081` 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\u2081` 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\u2081` representing the current program\nto be executed, or `none` for the halt state, and a `\u03c3` 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 `\u03c3`, only finitely many of these states are\nreachable. -/\n-- because of the inhabited instance, but we could avoid the inhabited instances on \u039b and \u03c3 here.\n\n-- But they are parameters so we cannot easily skip them for just this definition.\n\ndef \u039b' {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) :=\n  Option (TM1.stmt \u0393 \u039b \u03c3) \u00d7 \u03c3\n\nprotected instance \u039b'.inhabited {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) : Inhabited (\u039b' M) :=\n  { default := (some (M Inhabited.default), Inhabited.default) }\n\n/-- The core TM1 \u2192 TM0 translation function. Here `s` is the current value on the tape, and the\n`stmt\u2081` is the TM1 statement to translate, with local state `v : \u03c3`. 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) (s : \u0393) : TM1.stmt \u0393 \u039b \u03c3 \u2192 \u03c3 \u2192 \u039b' M \u00d7 TM0.stmt \u0393 :=\n  sorry\n\n/-- The translated TM0 machine (given the TM1 machine input). -/\ndef tr {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) : TM0.machine \u0393 (\u039b' M) :=\n  sorry\n\n/-- Translate configurations from TM1 to TM0. -/\ndef tr_cfg {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) : TM1.cfg \u0393 \u039b \u03c3 \u2192 TM0.cfg \u0393 (\u039b' M) :=\n  sorry\n\ntheorem tr_respects {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) : respects (TM1.step M) (TM0.step (tr M)) fun (c\u2081 : TM1.cfg \u0393 \u039b \u03c3) (c\u2082 : TM0.cfg \u0393 (\u039b' M)) => tr_cfg M c\u2081 = c\u2082 := sorry\n\ntheorem tr_eval {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) (l : List \u0393) : TM0.eval (tr M) l = TM1.eval M l := sorry\n\n/-- Given a finite set of accessible `\u039b` machine states, there is a finite set of accessible\nmachine states in the target (even though the type `\u039b'` is infinite). -/\ndef tr_stmts {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) [fintype \u03c3] (S : finset \u039b) : finset (\u039b' M) :=\n  finset.product (TM1.stmts M S) finset.univ\n\ntheorem tr_supports {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) [fintype \u03c3] {S : finset \u039b} (ss : TM1.supports M S) : TM0.supports (tr M) \u2191(tr_stmts M S) := sorry\n\nend TM1to0\n\n\n/-!\n## TM1(\u0393) emulator in TM1(bool)\n\nThe most parsimonious Turing machine model that is still Turing complete is `TM0` with `\u0393 = 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 `\u0393` 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 {\u0393 : Type u_1} [Inhabited \u0393] [fintype \u0393] : \u2203 (n : \u2115),\n  \u2203 (enc : \u0393 \u2192 vector Bool n),\n    \u2203 (dec : vector Bool n \u2192 \u0393), enc Inhabited.default = vector.repeat false n \u2227 \u2200 (a : \u0393), dec (enc a) = a := sorry\n\n/-- The configuration state of the TM. -/\ninductive \u039b' {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] \nwhere\n| normal : \u039b \u2192 \u039b'\n| write : \u0393 \u2192 TM1.stmt \u0393 \u039b \u03c3 \u2192 \u039b'\n\nprotected instance \u039b'.inhabited {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] : Inhabited \u039b' :=\n  { default := \u039b'.normal Inhabited.default }\n\n/-- Read a vector of length `n` from the tape. -/\ndef read_aux {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (n : \u2115) : (vector Bool n \u2192 TM1.stmt Bool \u039b' \u03c3) \u2192 TM1.stmt Bool \u039b' \u03c3 :=\n  sorry\n\n/-- A move left or right corresponds to `n` moves across the super-cell. -/\ndef move {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} (d : dir) (q : TM1.stmt Bool \u039b' \u03c3) : TM1.stmt Bool \u039b' \u03c3 :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} (dec : vector Bool n \u2192 \u0393) (f : \u0393 \u2192 TM1.stmt Bool \u039b' \u03c3) : TM1.stmt Bool \u039b' \u03c3 :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] : List Bool \u2192 TM1.stmt Bool \u039b' \u03c3 \u2192 TM1.stmt Bool \u039b' \u03c3 :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} (dec : vector Bool n \u2192 \u0393) : TM1.stmt \u0393 \u039b \u03c3 \u2192 TM1.stmt Bool \u039b' \u03c3 :=\n  sorry\n\ntheorem step_aux_move {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} (d : dir) (q : TM1.stmt Bool \u039b' \u03c3) (v : \u03c3) (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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} {S : finset \u039b'} {d : dir} {q : TM1.stmt Bool \u039b' \u03c3} : TM1.supports_stmt S (move d q) = TM1.supports_stmt S q := sorry\n\ntheorem supports_stmt_write {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {S : finset \u039b'} {l : List Bool} {q : TM1.stmt Bool \u039b' \u03c3} : TM1.supports_stmt S (write l q) = TM1.supports_stmt S q := sorry\n\ntheorem supports_stmt_read {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} (dec : vector Bool n \u2192 \u0393) {S : finset \u039b'} {f : \u0393 \u2192 TM1.stmt Bool \u039b' \u03c3} : (\u2200 (a : \u0393), TM1.supports_stmt S (f a)) \u2192 TM1.supports_stmt S (read dec f) := sorry\n\n/-- The low level tape corresponding to the given tape over alphabet `\u0393`. -/\ndef tr_tape' {\u0393 : Type u_1} [Inhabited \u0393] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank \u0393) (R : list_blank \u0393) : tape Bool :=\n  tape.mk' (list_blank.bind L (fun (x : \u0393) => list.reverse (vector.to_list (enc x))) sorry)\n    (list_blank.bind R (fun (x : \u0393) => vector.to_list (enc x)) sorry)\n\n/-- The low level tape corresponding to the given tape over alphabet `\u0393`. -/\ndef tr_tape {\u0393 : Type u_1} [Inhabited \u0393] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (T : tape \u0393) : tape Bool :=\n  tr_tape' enc0 (tape.left T) (tape.right\u2080 T)\n\ntheorem tr_tape_mk' {\u0393 : Type u_1} [Inhabited \u0393] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank \u0393) (R : list_blank \u0393) : tr_tape enc0 (tape.mk' L R) = tr_tape' enc0 L R := sorry\n\n/-- The top level program. -/\ndef tr {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} (enc : \u0393 \u2192 vector Bool n) (dec : vector Bool n \u2192 \u0393) (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) : \u039b' \u2192 TM1.stmt Bool \u039b' \u03c3 :=\n  sorry\n\n/-- The machine configuration translation. -/\ndef tr_cfg {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) : TM1.cfg \u0393 \u039b \u03c3 \u2192 TM1.cfg Bool \u039b' \u03c3 :=\n  sorry\n\ntheorem tr_tape'_move_left {\u0393 : Type u_1} [Inhabited \u0393] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank \u0393) (R : list_blank \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank \u0393) (R : list_blank \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (q : TM1.stmt Bool \u039b' \u03c3) (v : \u03c3) (a : \u0393) (b : \u0393) (L : list_blank \u0393) (R : list_blank \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (dec : vector Bool n \u2192 \u0393) (enc0 : enc Inhabited.default = vector.repeat false n) (encdec : \u2200 (a : \u0393), dec (enc a) = a) (f : \u0393 \u2192 TM1.stmt Bool \u039b' \u03c3) (v : \u03c3) (L : list_blank \u0393) (R : list_blank \u0393) : 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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (dec : vector Bool n \u2192 \u0393) (enc0 : enc Inhabited.default = vector.repeat false n) (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) (encdec : \u2200 (a : \u0393), dec (enc a) = a) : respects (TM1.step M) (TM1.step (tr enc dec M)) fun (c\u2081 : TM1.cfg \u0393 \u039b \u03c3) (c\u2082 : TM1.cfg Bool \u039b' \u03c3) => tr_cfg enc0 c\u2081 = c\u2082 := sorry\n\n/-- The set of accessible `\u039b'.write` machine states. -/\ndef writes {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] [fintype \u0393] : TM1.stmt \u0393 \u039b \u03c3 \u2192 finset \u039b' :=\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 {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) [fintype \u0393] (S : finset \u039b) : finset \u039b' :=\n  finset.bUnion S fun (l : \u039b) => insert (\u039b'.normal l) (writes (M l))\n\ntheorem tr_supports {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] {\u03c3 : Type u_3} [Inhabited \u03c3] {n : \u2115} {enc : \u0393 \u2192 vector Bool n} (dec : vector Bool n \u2192 \u0393) (M : \u039b \u2192 TM1.stmt \u0393 \u039b \u03c3) [fintype \u0393] {S : finset \u039b} (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 \u039b' {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] \nwhere\n| normal : \u039b \u2192 \u039b'\n| act : TM0.stmt \u0393 \u2192 \u039b \u2192 \u039b'\n\nprotected instance \u039b'.inhabited {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] : Inhabited \u039b' :=\n  { default := \u039b'.normal Inhabited.default }\n\n/-- The program.  -/\ndef tr {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : TM0.machine \u0393 \u039b) : \u039b' \u2192 TM1.stmt \u0393 \u039b' Unit :=\n  sorry\n\n/-- The configuration translation. -/\ndef tr_cfg {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : TM0.machine \u0393 \u039b) : TM0.cfg \u0393 \u039b \u2192 TM1.cfg \u0393 \u039b' Unit :=\n  sorry\n\ntheorem tr_respects {\u0393 : Type u_1} [Inhabited \u0393] {\u039b : Type u_2} [Inhabited \u039b] (M : TM0.machine \u0393 \u039b) : respects (TM0.step M) (TM1.step (tr M)) fun (a : TM0.cfg \u0393 \u039b) (b : TM1.cfg \u0393 \u039b' 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`\u0393 k`). The statements are:\n\n* `push k (f : \u03c3 \u2192 \u0393 k) q` puts `f a` on the `k`-th stack, then does `q`.\n* `pop k (f : \u03c3 \u2192 option (\u0393 k) \u2192 \u03c3) 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 : \u03c3 \u2192 option (\u0393 k) \u2192 \u03c3) 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 : \u03c3 \u2192 \u03c3) q` reads nothing but applies `f` to the internal state, then does `q`.\n* `branch (f : \u03c3 \u2192 bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.\n* `goto (f : \u03c3 \u2192 \u039b)` jumps to label `f a`.\n* `halt` halts on the next step.\n\nThe configuration is a tuple `(l, var, stk)` where `l : option \u039b` is the current label to run or\n`none` for the halting state, `var : \u03c3` is the (finite) internal state, and `stk : \u2200 k, list (\u0393 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 (\u0393 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] (\u0393 : K \u2192 Type u_2) (\u039b : Type u_3) (\u03c3 : Type u_4) \nwhere\n| push : (k : K) \u2192 (\u03c3 \u2192 \u0393 k) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| peek : (k : K) \u2192 (\u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| pop : (k : K) \u2192 (\u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| load : (\u03c3 \u2192 \u03c3) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| branch : (\u03c3 \u2192 Bool) \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3 \u2192 stmt \u0393 \u039b \u03c3\n| goto : (\u03c3 \u2192 \u039b) \u2192 stmt \u0393 \u039b \u03c3\n| halt : stmt \u0393 \u039b \u03c3\n\nprotected instance stmt.inhabited {K : Type u_1} [DecidableEq K] (\u0393 : K \u2192 Type u_2) (\u039b : Type u_3) (\u03c3 : Type u_4) : Inhabited (stmt \u0393 \u039b \u03c3) :=\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] (\u0393 : K \u2192 Type u_2) (\u039b : Type u_3) (\u03c3 : Type u_4) \nwhere\n  l : Option \u039b\n  var : \u03c3\n  stk : (k : K) \u2192 List (\u0393 k)\n\nprotected instance cfg.inhabited {K : Type u_1} [DecidableEq K] (\u0393 : K \u2192 Type u_2) (\u039b : Type u_3) (\u03c3 : Type u_4) [Inhabited \u03c3] : Inhabited (cfg \u0393 \u039b \u03c3) :=\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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} : stmt \u0393 \u039b \u03c3 \u2192 \u03c3 \u2192 ((k : K) \u2192 List (\u0393 k)) \u2192 cfg \u0393 \u039b \u03c3 :=\n  sorry\n\n/-- The step function for the TM2 model. -/\n@[simp] def step {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) : cfg \u0393 \u039b \u03c3 \u2192 Option (cfg \u0393 \u039b \u03c3) :=\n  sorry\n\n/-- The (reflexive) reachability relation for the TM2 model. -/\ndef reaches {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) : cfg \u0393 \u039b \u03c3 \u2192 cfg \u0393 \u039b \u03c3 \u2192 Prop :=\n  relation.refl_trans_gen fun (a b : cfg \u0393 \u039b \u03c3) => b \u2208 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} (S : finset \u039b) : stmt \u0393 \u039b \u03c3 \u2192 Prop :=\n  sorry\n\n/-- The set of subtree statements in a statement. -/\ndef stmts\u2081 {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} : stmt \u0393 \u039b \u03c3 \u2192 finset (stmt \u0393 \u039b \u03c3) :=\n  sorry\n\ntheorem stmts\u2081_self {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} {q : stmt \u0393 \u039b \u03c3} : q \u2208 stmts\u2081 q := sorry\n\ntheorem stmts\u2081_trans {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} {q\u2081 : stmt \u0393 \u039b \u03c3} {q\u2082 : stmt \u0393 \u039b \u03c3} : q\u2081 \u2208 stmts\u2081 q\u2082 \u2192 stmts\u2081 q\u2081 \u2286 stmts\u2081 q\u2082 := sorry\n\ntheorem stmts\u2081_supports_stmt_mono {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} {S : finset \u039b} {q\u2081 : stmt \u0393 \u039b \u03c3} {q\u2082 : stmt \u0393 \u039b \u03c3} (h : q\u2081 \u2208 stmts\u2081 q\u2082) (hs : supports_stmt S q\u2082) : supports_stmt S q\u2081 := sorry\n\n/-- The set of statements accessible from initial set `S` of labels. -/\ndef stmts {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) (S : finset \u039b) : finset (Option (stmt \u0393 \u039b \u03c3)) :=\n  finset.insert_none (finset.bUnion S fun (q : \u039b) => stmts\u2081 (M q))\n\ntheorem stmts_trans {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} {M : \u039b \u2192 stmt \u0393 \u039b \u03c3} {S : finset \u039b} {q\u2081 : stmt \u0393 \u039b \u03c3} {q\u2082 : stmt \u0393 \u039b \u03c3} (h\u2081 : q\u2081 \u2208 stmts\u2081 q\u2082) : some q\u2082 \u2208 stmts M S \u2192 some q\u2081 \u2208 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} [Inhabited \u039b] (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) (S : finset \u039b) :=\n  Inhabited.default \u2208 S \u2227 \u2200 (q : \u039b), q \u2208 S \u2192 supports_stmt S (M q)\n\ntheorem stmts_supports_stmt {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} [Inhabited \u039b] {M : \u039b \u2192 stmt \u0393 \u039b \u03c3} {S : finset \u039b} {q : stmt \u0393 \u039b \u03c3} (ss : supports M S) : some q \u2208 stmts M S \u2192 supports_stmt S q := sorry\n\ntheorem step_supports {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} [Inhabited \u039b] (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) {S : finset \u039b} (ss : supports M S) {c : cfg \u0393 \u039b \u03c3} {c' : cfg \u0393 \u039b \u03c3} : c' \u2208 step M c \u2192 cfg.l c \u2208 finset.insert_none S \u2192 cfg.l c' \u2208 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} [Inhabited \u039b] [Inhabited \u03c3] (k : K) (L : List (\u0393 k)) : cfg \u0393 \u039b \u03c3 :=\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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} {\u03c3 : Type u_4} [Inhabited \u039b] [Inhabited \u03c3] (M : \u039b \u2192 stmt \u0393 \u039b \u03c3) (k : K) (L : List (\u0393 k)) : roption (List (\u0393 k)) :=\n  roption.map (fun (c : cfg \u0393 \u039b \u03c3) => 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`\u0393' := bool \u00d7 \u2200 k, option (\u0393 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 (\u0393 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 : \u039b)`: waiting at `bottom` to execute function `l`\n* `go k (s : st_act k) (q : stmt\u2082)`: 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\u2082)`: 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} {\u0393 : K \u2192 Type u_2} {L : list_blank ((k : K) \u2192 Option (\u0393 k))} {k : K} {S : List (\u0393 k)} (n : \u2115) (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 \u0393' {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} :=\n  Bool \u00d7 ((k : K) \u2192 Option (\u0393 k))\n\nprotected instance \u0393'.inhabited {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} : Inhabited \u0393' :=\n  { default := (false, fun (_x : K) => none) }\n\nprotected instance \u0393'.fintype {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} [fintype K] [(k : K) \u2192 fintype (\u0393 k)] : fintype \u0393' :=\n  prod.fintype Bool ((k : K) \u2192 Option (\u0393 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] {\u0393 : K \u2192 Type u_2} (L : list_blank ((k : K) \u2192 Option (\u0393 k))) : list_blank \u0393' :=\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] {\u0393 : K \u2192 Type u_2} (L : list_blank ((k : K) \u2192 Option (\u0393 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] {\u0393 : K \u2192 Type u_2} (f : ((k : K) \u2192 Option (\u0393 k)) \u2192 (k : K) \u2192 Option (\u0393 k)) (L : list_blank ((k : K) \u2192 Option (\u0393 k))) (n : \u2115) : list_blank.modify_nth (fun (a : \u0393') => (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] {\u0393 : K \u2192 Type u_2} (L : list_blank ((k : K) \u2192 Option (\u0393 k))) (n : \u2115) : 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] {\u0393 : K \u2192 Type u_2} (L : list_blank ((k : K) \u2192 Option (\u0393 k))) (n : \u2115) : prod.fst (list_blank.nth (add_bottom L) (n + 1)) = false := sorry\n\ntheorem add_bottom_head_fst {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} (L : list_blank ((k : K) \u2192 Option (\u0393 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] {\u0393 : K \u2192 Type u_2} {\u03c3 : Type u_4} [Inhabited \u03c3] (k : K) \nwhere\n| push : (\u03c3 \u2192 \u0393 k) \u2192 st_act k\n| peek : (\u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) \u2192 st_act k\n| pop : (\u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) \u2192 st_act k\n\nprotected instance st_act.inhabited {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} : Inhabited (st_act k) :=\n  { default := st_act.peek fun (s : \u03c3) (_x : Option (\u0393 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} : st_act k \u2192 TM2.stmt \u0393 \u039b \u03c3 \u2192 TM2.stmt \u0393 \u039b \u03c3 :=\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] {\u0393 : K \u2192 Type u_2} {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} (v : \u03c3) (l : List (\u0393 k)) : st_act k \u2192 \u03c3 :=\n  sorry\n\n/-- The effect of a stack action on the stack. -/\ndef st_write {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} (v : \u03c3) (l : List (\u0393 k)) : st_act k \u2192 List (\u0393 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {C : TM2.stmt \u0393 \u039b \u03c3 \u2192 Sort l} (H\u2081 : (k : K) \u2192 (s : st_act k) \u2192 (q : TM2.stmt \u0393 \u039b \u03c3) \u2192 C q \u2192 C (st_run s q)) (H\u2082 : (a : \u03c3 \u2192 \u03c3) \u2192 (q : TM2.stmt \u0393 \u039b \u03c3) \u2192 C q \u2192 C (TM2.stmt.load a q)) (H\u2083 : (p : \u03c3 \u2192 Bool) \u2192 (q\u2081 q\u2082 : TM2.stmt \u0393 \u039b \u03c3) \u2192 C q\u2081 \u2192 C q\u2082 \u2192 C (TM2.stmt.branch p q\u2081 q\u2082)) (H\u2084 : (l : \u03c3 \u2192 \u039b) \u2192 C (TM2.stmt.goto l)) (H\u2085 : C TM2.stmt.halt) (n : TM2.stmt \u0393 \u039b \u03c3) : C n :=\n  sorry\n\ntheorem supports_run {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (S : finset \u039b) {k : K} (s : st_act k) (q : TM2.stmt \u0393 \u039b \u03c3) : TM2.supports_stmt S (st_run s q) \u2194 TM2.supports_stmt S q :=\n  st_act.cases_on s (fun (s : \u03c3 \u2192 \u0393 k) => iff.refl (TM2.supports_stmt S (st_run (st_act.push s) q)))\n    (fun (s : \u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) => iff.refl (TM2.supports_stmt S (st_run (st_act.peek s) q)))\n    fun (s : \u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) => 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 \u039b' {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] \nwhere\n| normal : \u039b \u2192 \u039b'\n| go : (k : K) \u2192 st_act k \u2192 TM2.stmt \u0393 \u039b \u03c3 \u2192 \u039b'\n| ret : TM2.stmt \u0393 \u039b \u03c3 \u2192 \u039b'\n\nprotected instance \u039b'.inhabited {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] : Inhabited \u039b' :=\n  { default := \u039b'.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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} (q : TM1.stmt \u0393' \u039b' \u03c3) : st_act k \u2192 TM1.stmt \u0393' \u039b' \u03c3 :=\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] {\u0393 : K \u2192 Type u_2} (k : K) (L : List (\u0393 k)) : List \u0393' :=\n  let L' : List \u0393' := list.map (fun (a : \u0393 k) => (false, function.update (fun (_x : K) => none) k \u2191a)) (list.reverse L);\n  (tt, prod.snd (list.head L')) :: list.tail L'\n\ntheorem step_run {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} (q : TM2.stmt \u0393 \u039b \u03c3) (v : \u03c3) (S : (k : K) \u2192 List (\u0393 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] : TM2.stmt \u0393 \u039b \u03c3 \u2192 TM1.stmt \u0393' \u039b' \u03c3 :=\n  sorry\n\ntheorem tr_normal_run {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} (s : st_act k) (q : TM2.stmt \u0393 \u039b \u03c3) : tr_normal (st_run s q) = TM1.stmt.goto fun (_x : \u0393') (_x : \u03c3) => \u039b'.go k s q :=\n  st_act.cases_on s (fun (s : \u03c3 \u2192 \u0393 k) => Eq.refl (tr_normal (st_run (st_act.push s) q)))\n    (fun (s : \u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) => Eq.refl (tr_normal (st_run (st_act.peek s) q)))\n    fun (s : \u03c3 \u2192 Option (\u0393 k) \u2192 \u03c3) => 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\u2081 {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] : TM2.stmt \u0393 \u039b \u03c3 \u2192 finset \u039b' :=\n  sorry\n\ntheorem tr_stmts\u2081_run {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} {s : st_act k} {q : TM2.stmt \u0393 \u039b \u03c3} : tr_stmts\u2081 (st_run s q) = insert (\u039b'.go k s q) (singleton (\u039b'.ret q)) \u222a tr_stmts\u2081 q := sorry\n\ntheorem tr_respects_aux\u2082 {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] {k : K} {q : TM1.stmt \u0393' \u039b' \u03c3} {v : \u03c3} {S : (k : K) \u2192 List (\u0393 k)} {L : list_blank ((k : K) \u2192 Option (\u0393 k))} (hL : \u2200 (k : K), list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some (S k)))) (o : st_act k) : let v' : \u03c3 := st_var v (S k) o;\nlet Sk' : List (\u0393 k) := st_write v (S k) o;\nlet S' : (k : K) \u2192 List (\u0393 k) := function.update S k Sk';\n\u2203 (L' : list_blank ((k : K) \u2192 Option (\u0393 k))),\n  (\u2200 (k : K), list_blank.map (proj k) L' = list_blank.mk (list.reverse (list.map some (S' k)))) \u2227\n    TM1.step_aux (tr_st_act q o) v (nat.iterate (tape.move dir.right) (list.length (S k)) (tape.mk' \u2205 (add_bottom L))) =\n      TM1.step_aux q v' (nat.iterate (tape.move dir.right) (list.length (S' k)) (tape.mk' \u2205 (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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) : \u039b' \u2192 TM1.stmt \u0393' \u039b' \u03c3 :=\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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) : TM2.cfg \u0393 \u039b \u03c3 \u2192 TM1.cfg \u0393' \u039b' \u03c3 \u2192 Prop\nwhere\n| mk : \u2200 {q : Option \u039b} {v : \u03c3} {S : (k : K) \u2192 List (\u0393 k)} (L : list_blank ((k : K) \u2192 Option (\u0393 k))),\n  (\u2200 (k : K), list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some (S k)))) \u2192\n    tr_cfg M (TM2.cfg.mk q v S) (TM1.cfg.mk (option.map \u039b'.normal q) v (tape.mk' \u2205 (add_bottom L)))\n\ntheorem tr_respects_aux\u2081 {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) {k : K} (o : st_act k) (q : TM2.stmt \u0393 \u039b \u03c3) (v : \u03c3) {S : List (\u0393 k)} {L : list_blank ((k : K) \u2192 Option (\u0393 k))} (hL : list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some S))) (n : \u2115) (H : n \u2264 list.length S) : reaches\u2080 (TM1.step (tr M)) (TM1.cfg.mk (some (\u039b'.go k o q)) v (tape.mk' \u2205 (add_bottom L)))\n  (TM1.cfg.mk (some (\u039b'.go k o q)) v (nat.iterate (tape.move dir.right) n (tape.mk' \u2205 (add_bottom L)))) := sorry\n\ntheorem tr_respects_aux\u2083 {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) {q : TM2.stmt \u0393 \u039b \u03c3} {v : \u03c3} {L : list_blank ((k : K) \u2192 Option (\u0393 k))} (n : \u2115) : reaches\u2080 (TM1.step (tr M))\n  (TM1.cfg.mk (some (\u039b'.ret q)) v (nat.iterate (tape.move dir.right) n (tape.mk' \u2205 (add_bottom L))))\n  (TM1.cfg.mk (some (\u039b'.ret q)) v (tape.mk' \u2205 (add_bottom L))) := sorry\n\ntheorem tr_respects_aux {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) {q : TM2.stmt \u0393 \u039b \u03c3} {v : \u03c3} {T : list_blank ((i : K) \u2192 Option (\u0393 i))} {k : K} {S : (k : K) \u2192 List (\u0393 k)} (hT : \u2200 (k : K), list_blank.map (proj k) T = list_blank.mk (list.reverse (list.map some (S k)))) (o : st_act k) (IH : \u2200 {v : \u03c3} {S : (k : K) \u2192 List (\u0393 k)} {T : list_blank ((i : K) \u2192 Option (\u0393 i))},\n  (\u2200 (k : K), list_blank.map (proj k) T = list_blank.mk (list.reverse (list.map some (S k)))) \u2192\n    \u2203 (b : TM1.cfg \u0393' \u039b' \u03c3),\n      tr_cfg M (TM2.step_aux q v S) b \u2227\n        reaches (TM1.step (tr M)) (TM1.step_aux (tr_normal q) v (tape.mk' \u2205 (add_bottom T))) b) : \u2203 (b : TM1.cfg \u0393' \u039b' \u03c3),\n  tr_cfg M (TM2.step_aux (st_run o q) v S) b \u2227\n    reaches (TM1.step (tr M)) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' \u2205 (add_bottom T))) b := sorry\n\ntheorem tr_respects {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) : respects (TM2.step M) (TM1.step (tr M)) (tr_cfg M) := sorry\n\ntheorem tr_cfg_init {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) (k : K) (L : List (\u0393 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) (k : K) (L : List (\u0393 k)) : roption.dom (TM1.eval (tr M) (tr_init k L)) \u2194 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] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) (k : K) (L : List (\u0393 k)) {L\u2081 : list_blank \u0393'} {L\u2082 : List (\u0393 k)} (H\u2081 : L\u2081 \u2208 TM1.eval (tr M) (tr_init k L)) (H\u2082 : L\u2082 \u2208 TM2.eval M k L) : \u2203 (S : (k : K) \u2192 List (\u0393 k)),\n  \u2203 (L' : list_blank ((k : K) \u2192 Option (\u0393 k))),\n    add_bottom L' = L\u2081 \u2227\n      (\u2200 (k : K), list_blank.map (proj k) L' = list_blank.mk (list.reverse (list.map some (S k)))) \u2227 S k = L\u2082 := sorry\n\n/-- The support of a set of TM2 states in the TM2 emulator. -/\ndef tr_supp {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) (S : finset \u039b) : finset \u039b' :=\n  finset.bUnion S fun (l : \u039b) => insert (\u039b'.normal l) (tr_stmts\u2081 (M l))\n\ntheorem tr_supports {K : Type u_1} [DecidableEq K] {\u0393 : K \u2192 Type u_2} {\u039b : Type u_3} [Inhabited \u039b] {\u03c3 : Type u_4} [Inhabited \u03c3] (M : \u039b \u2192 TM2.stmt \u0393 \u039b \u03c3) {S : finset \u039b} (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) \u2190 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 {\u03b1 : Type} (tac : smt_tactic \u03b1) : smt_tactic Unit :=\n  tac >> solve_goals\n#align smt_tactic.step smt_tactic.step\n\nunsafe def istep {\u03b1 : Type} (line0 col0 line col ast : Nat) (tac : smt_tactic \u03b1) :\n    smt_tactic Unit :=\n  \u27e8fun ss ts =>\n    (@scopeTrace _ line col fun _ => tactic.with_ast ast ((tac >> solve_goals).run ss) ts).clamp_pos\n      line0 line col\u27e9\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 := \u27e8{ }\u27e9\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: \u00abexpr ?\u00bb\nlocal postfix:1024 \"?\" => optional\n\n-- mathport name: \u00abexpr *\u00bb\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* \u2192 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\u2081 : parse (tk \":\" *> texpr)?)\n    (q\u2082 : parse <| (tk \":=\" *> texpr)?) : smt_tactic Unit :=\n  let h := h.getD `this\n  (match q\u2081, q\u2082 with\n    | some e, some p => do\n      let t \u2190 tactic.to_expr e\n      let v \u2190 tactic.to_expr ``(($(p) : $(t)))\n      smt_tactic.assertv h t v\n    | none, some p => do\n      let p \u2190 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 \u2190 tactic.mk_meta_univ\n      let e \u2190 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\u2081 : parse (tk \":\" *> texpr)?)\n    (q\u2082 : parse <| (tk \":=\" *> texpr)?) : smt_tactic Unit :=\n  let h := h.getD `this\n  (match q\u2081, q\u2082 with\n    | some e, some p => do\n      let t \u2190 tactic.to_expr e\n      let v \u2190 tactic.to_expr ``(($(p) : $(t)))\n      smt_tactic.definev h t v\n    | none, some p => do\n      let p \u2190 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 \u2190 tactic.mk_meta_univ\n      let e \u2190 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 \u2190 tactic.get_unused_name `h none\n  let p \u2190 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 {\u03b1 : Type} [has_to_tactic_format \u03b1] (a : \u03b1) : 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 \u2190 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 \u2190 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 {\u03b1 : Type} (n : Name) : smt_tactic \u03b1 :=\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 \u2190 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 \u2190 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 \u2190 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 \u2192 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 \u2192 smt_tactic Unit\n  | [] => return ()\n  | c :: cs => do\n    let p \u2190 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 \u2190 resolve_name n\n  match p with\n    | expr.const n _ =>\n      (do\n          let h \u2190 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\u2081 \u2190 mk_ematch_eqn_lemmas_for_core md n\n            tactic.save_const_type_info n ref\n            return <| hs hs\u2081) <|>\n          report_invalid_em_lemma n\n    | _ =>\n      (do\n          let e \u2190 to_expr p\n          let h \u2190 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 \u2190 to_expr p\n    let h \u2190 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 \u2192 hinst_lemmas \u2192 smt_tactic hinst_lemmas\n  | [], hs => return hs\n  | p :: ps, hs => do\n    let hs\u2081 \u2190 add_hinst_lemma_from_pexpr md lhs_lemma p hs\n    add_hinst_lemmas_from_pexprs ps hs\u2081\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 \u2190 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 \u2190 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 \u2190 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 \u2190 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 \u2190 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\u00f6lzl, 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 `\u03a0\u2080 i, M i`\n\nGiven an indexed collection of `R`-semimodules `M i`, the `R`-semimodule structure on `\u03a0\u2080 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 \u2192\u2097[R] \u03a0\u2080 i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lmk s : (\u03a0 i : (\u2191s : set \u03b9), M i) \u2192\u2097[R] \u03a0\u2080 i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lapply i : (\u03a0\u2080 i, M i) \u2192\u2097[R] M`: the map `\u03bb 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 {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9] [semiring R]\n    [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (s : finset \u03b9) :\n    linear_map R ((i : \u21a5\u2191s) \u2192 M \u2191i) (dfinsupp fun (i : \u03b9) => M i) :=\n  linear_map.mk (mk s) sorry sorry\n\n/-- `dfinsupp.single` as a `linear_map` -/\ndef lsingle {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9] [semiring R]\n    [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) :\n    linear_map R (M i) (dfinsupp fun (i : \u03b9) => M i) :=\n  linear_map.mk (single i) sorry sorry\n\n/-- Two `R`-linear maps from `\u03a0\u2080 i, M i` which agree on each `single i x` agree everywhere. -/\ntheorem lhom_ext {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} {N : Type u_4}\n    [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)]\n    [(i : \u03b9) \u2192 semimodule R (M i)] [add_comm_monoid N] [semimodule R N]\n    {\u03c6 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N}\n    {\u03c8 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N}\n    (h : \u2200 (i : \u03b9) (x : M i), coe_fn \u03c6 (single i x) = coe_fn \u03c8 (single i x)) : \u03c6 = \u03c8 :=\n  linear_map.to_add_monoid_hom_injective (add_hom_ext h)\n\n/-- Two `R`-linear maps from `\u03a0\u2080 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 `\u03c6 (single a 1) = \u03c8 (single a 1)`. -/\ntheorem lhom_ext' {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} {N : Type u_4}\n    [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)]\n    [(i : \u03b9) \u2192 semimodule R (M i)] [add_comm_monoid N] [semimodule R N]\n    {\u03c6 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N}\n    {\u03c8 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N}\n    (h : \u2200 (i : \u03b9), linear_map.comp \u03c6 (lsingle i) = linear_map.comp \u03c8 (lsingle i)) : \u03c6 = \u03c8 :=\n  lhom_ext fun (i : \u03b9) => linear_map.congr_fun (h i)\n\n/-- Interpret `\u03bb (f : \u03a0\u2080 i, M i), f i` as a linear map. -/\ndef lapply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [semiring R]\n    [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) :\n    linear_map R (dfinsupp fun (i : \u03b9) => M i) (M i) :=\n  linear_map.mk (fun (f : dfinsupp fun (i : \u03b9) => M i) => coe_fn f i) sorry sorry\n\n@[simp] theorem lmk_apply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9]\n    [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (s : finset \u03b9)\n    (x : (i : \u21a5\u2191s) \u2192 (fun (i : \u03b9) => M i) \u2191i) : coe_fn (lmk s) x = mk s x :=\n  rfl\n\n@[simp] theorem lsingle_apply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3}\n    [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)]\n    [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) (x : M i) : coe_fn (lsingle i) x = single i x :=\n  rfl\n\n@[simp] theorem lapply_apply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [semiring R]\n    [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9)\n    (f : dfinsupp fun (i : \u03b9) => M i) : coe_fn (lapply i) f = coe_fn f i :=\n  rfl\n\n/-- The `dfinsupp` version of `finsupp.lsum`. -/\ndef lsum {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} {N : Type u_4} [dec_\u03b9 : DecidableEq \u03b9]\n    [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)]\n    [add_comm_monoid N] [semimodule R N] :\n    ((i : \u03b9) \u2192 linear_map R (M i) N) \u2243+ linear_map R (dfinsupp fun (i : \u03b9) => M i) N :=\n  add_equiv.mk\n    (fun (F : (i : \u03b9) \u2192 linear_map R (M i) N) =>\n      linear_map.mk \u21d1(sum_add_hom fun (i : \u03b9) => linear_map.to_add_monoid_hom (F i)) sorry sorry)\n    (fun (F : linear_map R (dfinsupp fun (i : \u03b9) => M i) N) (i : \u03b9) =>\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 \u00d7 K} G = lim_J (lim_K G(j, -))$ for a functor `G : J \u00d7 K \u2964 C`,\nwhen all the appropriate limits exist.\n\nWe begin working with a functor `F : J \u2964 K \u2964 C`. We'll write `G : J \u00d7 K \u2964 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) \u2245 limit (F \u22d9 lim)`\nand give simp lemmas characterising it.\nFor convenience, we also provide\n`limit_iso_limit_curry_comp_lim G : limit G \u2245 limit ((curry.obj G) \u22d9 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 \u2964 K \u2964 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 : \u03a0 j : J, cone (F.obj j))\n(map : \u03a0 {j j' : J} (f : j \u27f6 j'), (cones.postcompose (F.map f)).obj (obj j) \u27f6 obj j')\n(id : \u2200 j : J, (map (\ud835\udfd9 j)).hom = \ud835\udfd9 _ . obviously)\n(comp : \u2200 {j\u2081 j\u2082 j\u2083 : J} (f : j\u2081 \u27f6 j\u2082) (g : j\u2082 \u27f6 j\u2083),\n  (map (f \u226b g)).hom = (map f).hom \u226b (map g).hom . obviously)\n\nvariables {F}\n\n/--\nExtract the functor `J \u2964 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 \u2964 C :=\n{ obj := \u03bb j, (D.obj j).X,\n  map := \u03bb j j' f, (D.map f).hom,\n  map_id' := \u03bb j, D.id j,\n  map_comp' := \u03bb j\u2081 j\u2082 j\u2083 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 : \u03a0 j, is_limit (D.obj j))\n  (c : cone (uncurry.obj F)) :\n  cone (D.cone_points) :=\n{ X := c.X,\n  \u03c0 :=\n  { app := \u03bb j, (Q j).lift\n    { X := c.X,\n      \u03c0 :=\n      { app := \u03bb k, c.\u03c0.app (j, k),\n        naturality' := \u03bb k k' f,\n        begin\n          dsimp, simp only [category.id_comp],\n          have := @nat_trans.naturality _ _ _ _ _ _ c.\u03c0 (j, k) (j, k') (\ud835\udfd9 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' := \u03bb 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_\u03c0, 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.\u03c0 (j, k) (j', k) (f, \ud835\udfd9 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 : \u03a0 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 := \u03bb s, P.lift\n  { X := s.X,\n    \u03c0 :=\n    { app := \u03bb p, s.\u03c0.app p.1 \u226b (D.obj p.1).\u03c0.app p.2,\n      naturality' := \u03bb p p' f,\n      begin\n        dsimp, simp only [category.id_comp, category.assoc],\n        rcases p with \u27e8j, k\u27e9,\n        rcases p' with \u27e8j', k'\u27e9,\n        rcases f with \u27e8fj, fk\u27e9,\n        dsimp,\n        slice_rhs 3 4 { rw \u2190nat_trans.naturality, },\n        slice_rhs 2 3 { rw \u2190(D.obj j).\u03c0.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 \u2190w,\n        have n := s.\u03c0.naturality fj,\n        dsimp at n,\n        simp only [category.id_comp] at n,\n        rw n,\n        simp,\n      end, } },\n  fac' := \u03bb s j,\n  begin\n    apply (Q j).hom_ext,\n    intro k,\n    simp,\n  end,\n  uniq' := \u03bb s m w,\n  begin\n    refine P.uniq { X := s.X, \u03c0 := _, } m _,\n    rintro \u27e8j, k\u27e9,\n    dsimp,\n    rw [\u2190w j],\n    simp,\n  end, }\n\nsection\nvariables (F)\nvariables [has_limits_of_shape K C]\n\n/--\nGiven a functor `F : J \u2964 K \u2964 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 := \u03bb j, limit.cone (F.obj j),\n  map := \u03bb 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\u27e8diagram_of_cones.mk_of_has_limits F\u27e9\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 \u22d9 lim) :=\nrfl\n\nvariables [has_limit (uncurry.obj F)]\nvariables [has_limit (F \u22d9 lim)]\n\n/--\nThe Fubini theorem for a functor `F : J \u2964 K \u2964 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) \u2245 limit (F \u22d9 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 : \u03a0 j, is_limit (G.obj j) := \u03bb j, limit.is_limit _,\n  have Q' := cone_of_cone_uncurry_is_limit Q P,\n  have Q'' := (limit.is_limit (F \u22d9 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_\u03c0_\u03c0 {j} {k} :\n  (limit_uncurry_iso_limit_comp_lim F).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k = limit.\u03c0 _ (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_\u03c0 {j} {k} :\n  (limit_uncurry_iso_limit_comp_lim F).inv \u226b limit.\u03c0 _ (j, k) = limit.\u03c0 _ j \u226b limit.\u03c0 _ k :=\nbegin\n  rw [\u2190cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom],\n  simp,\nend\nend\n\nsection\nvariables (G : J \u00d7 K \u2964 C)\n\nsection\nvariables [has_limits_of_shape K C]\nvariables [has_limit G]\nvariables [has_limit ((curry.obj G) \u22d9 lim)]\n\n/--\nThe Fubini theorem for a functor `G : J \u00d7 K \u2964 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 \u2245 limit ((curry.obj G) \u22d9 lim) :=\nbegin\n  have i : G \u2245 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_\u03c0_\u03c0 {j} {k} :\n  (limit_iso_limit_curry_comp_lim G).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k = limit.\u03c0 _ (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_\u03c0 {j} {k} :\n  (limit_iso_limit_curry_comp_lim G).inv \u226b limit.\u03c0 _ (j, k) = limit.\u03c0 _ j \u226b limit.\u03c0 _ k :=\nbegin\n  rw [\u2190cancel_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 \u00d7 K \u2964 C`,\nshowing that $\\lim_k \\lim_j G(j,k) \u2245 \\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 \u22d9 G)) \u22d9 lim) \u2245 limit ((curry.obj G) \u22d9 lim) :=\ncalc\n  limit ((curry.obj (swap K J \u22d9 G)) \u22d9 lim)\n      \u2245 limit (swap K J \u22d9 G) : (limit_iso_limit_curry_comp_lim _).symm\n  ... \u2245 limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _)\n  ... \u2245 limit ((curry.obj G) \u22d9 lim) : limit_iso_limit_curry_comp_lim _\n\n@[simp]\nlemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_\u03c0_\u03c0 {j} {k} :\n  (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom \u226b limit.\u03c0 _ j \u226b limit.\u03c0 _ k =\n   limit.\u03c0 _ k \u226b limit.\u03c0 _ 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_\u03c0,\n    iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_\u03c0_\u03c0, 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_\u03c0_\u03c0 {j} {k} :\n  (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv \u226b limit.\u03c0 _ k \u226b limit.\u03c0 _ j =\n   limit.\u03c0 _ j \u226b limit.\u03c0 _ 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_\u03c0,\n    iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_\u03c0_\u03c0, 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 {\u03b1 : Type u_1} (s : multiset \u03b1) := quot.lift_on s list.nodup sorry\n\n@[simp] theorem coe_nodup {\u03b1 : Type u_1} {l : List \u03b1} : nodup \u2191l \u2194 list.nodup l := iff.rfl\n\n@[simp] theorem nodup_zero {\u03b1 : Type u_1} : nodup 0 := list.pairwise.nil\n\n@[simp] theorem nodup_cons {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} :\n    nodup (a ::\u2098 s) \u2194 \u00aca \u2208 s \u2227 nodup s :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_cons\n\ntheorem nodup_cons_of_nodup {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} (m : \u00aca \u2208 s) (n : nodup s) :\n    nodup (a ::\u2098 s) :=\n  iff.mpr nodup_cons { left := m, right := n }\n\ntheorem nodup_singleton {\u03b1 : Type u_1} (a : \u03b1) : nodup (a ::\u2098 0) := list.nodup_singleton\n\ntheorem nodup_of_nodup_cons {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} (h : nodup (a ::\u2098 s)) :\n    nodup s :=\n  and.right (iff.mp nodup_cons h)\n\ntheorem not_mem_of_nodup_cons {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} (h : nodup (a ::\u2098 s)) :\n    \u00aca \u2208 s :=\n  and.left (iff.mp nodup_cons h)\n\ntheorem nodup_of_le {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} (h : s \u2264 t) :\n    nodup t \u2192 nodup s :=\n  le_induction_on h fun (l\u2081 l\u2082 : List \u03b1) => list.nodup_of_sublist\n\ntheorem not_nodup_pair {\u03b1 : Type u_1} (a : \u03b1) : \u00acnodup (a ::\u2098 a ::\u2098 0) := list.not_nodup_pair\n\ntheorem nodup_iff_le {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup s \u2194 \u2200 (a : \u03b1), \u00aca ::\u2098 a ::\u2098 0 \u2264 s :=\n  quot.induction_on s\n    fun (l : List \u03b1) =>\n      iff.trans list.nodup_iff_sublist\n        (forall_congr fun (a : \u03b1) => not_congr (iff.symm repeat_le_coe))\n\ntheorem nodup_iff_ne_cons_cons {\u03b1 : Type u_1} {s : multiset \u03b1} :\n    nodup s \u2194 \u2200 (a : \u03b1) (t : multiset \u03b1), s \u2260 a ::\u2098 a ::\u2098 t :=\n  sorry\n\ntheorem nodup_iff_count_le_one {\u03b1 : Type u_1} [DecidableEq \u03b1] {s : multiset \u03b1} :\n    nodup s \u2194 \u2200 (a : \u03b1), count a s \u2264 1 :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_iff_count_le_one\n\n@[simp] theorem count_eq_one_of_mem {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {s : multiset \u03b1}\n    (d : nodup s) (h : a \u2208 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 {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup s \u2194 pairwise ne s :=\n  quotient.induction_on s\n    fun (l : List \u03b1) => iff.symm (pairwise_coe_iff_pairwise fun (a b : \u03b1) => ne.symm)\n\ntheorem pairwise_of_nodup {\u03b1 : Type u_1} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : multiset \u03b1} :\n    (\u2200 (a : \u03b1), a \u2208 s \u2192 \u2200 (b : \u03b1), b \u2208 s \u2192 a \u2260 b \u2192 r a b) \u2192 nodup s \u2192 pairwise r s :=\n  sorry\n\ntheorem forall_of_pairwise {\u03b1 : Type u_1} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (H : symmetric r) {s : multiset \u03b1}\n    (hs : pairwise r s) (a : \u03b1) : a \u2208 s \u2192 \u2200 (b : \u03b1), b \u2208 s \u2192 a \u2260 b \u2192 r a b :=\n  sorry\n\ntheorem nodup_add {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} :\n    nodup (s + t) \u2194 nodup s \u2227 nodup t \u2227 disjoint s t :=\n  quotient.induction_on\u2082 s t fun (l\u2081 l\u2082 : List \u03b1) => list.nodup_append\n\ntheorem disjoint_of_nodup_add {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} (d : nodup (s + t)) :\n    disjoint s t :=\n  and.right (and.right (iff.mp nodup_add d))\n\ntheorem nodup_add_of_nodup {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} (d\u2081 : nodup s)\n    (d\u2082 : nodup t) : nodup (s + t) \u2194 disjoint s t :=\n  sorry\n\ntheorem nodup_of_nodup_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) {s : multiset \u03b1} :\n    nodup (map f s) \u2192 nodup s :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_of_nodup_map f\n\ntheorem nodup_map_on {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {s : multiset \u03b1} :\n    (\u2200 (x : \u03b1), x \u2208 s \u2192 \u2200 (y : \u03b1), y \u2208 s \u2192 f x = f y \u2192 x = y) \u2192 nodup s \u2192 nodup (map f s) :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_map_on\n\ntheorem nodup_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {s : multiset \u03b1}\n    (hf : function.injective f) : nodup s \u2192 nodup (map f s) :=\n  nodup_map_on fun (x : \u03b1) (_x : x \u2208 s) (y : \u03b1) (_x : y \u2208 s) (h : f x = f y) => hf h\n\ntheorem nodup_filter {\u03b1 : Type u_1} (p : \u03b1 \u2192 Prop) [decidable_pred p] {s : multiset \u03b1} :\n    nodup s \u2192 nodup (filter p s) :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_filter p\n\n@[simp] theorem nodup_attach {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup (attach s) \u2194 nodup s :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_attach\n\ntheorem nodup_pmap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} {f : (a : \u03b1) \u2192 p a \u2192 \u03b2}\n    {s : multiset \u03b1} {H : \u2200 (a : \u03b1), a \u2208 s \u2192 p a}\n    (hf : \u2200 (a : \u03b1) (ha : p a) (b : \u03b1) (hb : p b), f a ha = f b hb \u2192 a = b) :\n    nodup s \u2192 nodup (pmap f s H) :=\n  quot.induction_on s\n    (fun (l : List \u03b1) (H : \u2200 (a : \u03b1), a \u2208 Quot.mk setoid.r l \u2192 p a) => list.nodup_pmap hf) H\n\nprotected instance nodup_decidable {\u03b1 : Type u_1} [DecidableEq \u03b1] (s : multiset \u03b1) :\n    Decidable (nodup s) :=\n  quotient.rec_on_subsingleton s fun (l : List \u03b1) => list.nodup_decidable l\n\ntheorem nodup_erase_eq_filter {\u03b1 : Type u_1} [DecidableEq \u03b1] (a : \u03b1) {s : multiset \u03b1} :\n    nodup s \u2192 erase s a = filter (fun (_x : \u03b1) => _x \u2260 a) s :=\n  quot.induction_on s\n    fun (l : List \u03b1) (d : nodup (Quot.mk setoid.r l)) =>\n      congr_arg coe (list.nodup_erase_eq_filter a d)\n\ntheorem nodup_erase_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] (a : \u03b1) {l : multiset \u03b1} :\n    nodup l \u2192 nodup (erase l a) :=\n  nodup_of_le (erase_le a l)\n\ntheorem mem_erase_iff_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b1} {l : multiset \u03b1}\n    (d : nodup l) : a \u2208 erase l b \u2194 a \u2260 b \u2227 a \u2208 l :=\n  sorry\n\ntheorem mem_erase_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {l : multiset \u03b1} (h : nodup l) :\n    \u00aca \u2208 erase l a :=\n  sorry\n\ntheorem nodup_product {\u03b1 : Type u_1} {\u03b2 : Type u_2} {s : multiset \u03b1} {t : multiset \u03b2} :\n    nodup s \u2192 nodup t \u2192 nodup (product s t) :=\n  sorry\n\ntheorem nodup_sigma {\u03b1 : Type u_1} {\u03c3 : \u03b1 \u2192 Type u_2} {s : multiset \u03b1}\n    {t : (a : \u03b1) \u2192 multiset (\u03c3 a)} :\n    nodup s \u2192 (\u2200 (a : \u03b1), nodup (t a)) \u2192 nodup (multiset.sigma s t) :=\n  sorry\n\ntheorem nodup_filter_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 Option \u03b2) {s : multiset \u03b1}\n    (H : \u2200 (a a' : \u03b1) (b : \u03b2), b \u2208 f a \u2192 b \u2208 f a' \u2192 a = a') : nodup s \u2192 nodup (filter_map f s) :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_filter_map H\n\ntheorem nodup_range (n : \u2115) : nodup (range n) := list.nodup_range n\n\ntheorem nodup_inter_left {\u03b1 : Type u_1} [DecidableEq \u03b1] {s : multiset \u03b1} (t : multiset \u03b1) :\n    nodup s \u2192 nodup (s \u2229 t) :=\n  nodup_of_le (inter_le_left s t)\n\ntheorem nodup_inter_right {\u03b1 : Type u_1} [DecidableEq \u03b1] (s : multiset \u03b1) {t : multiset \u03b1} :\n    nodup t \u2192 nodup (s \u2229 t) :=\n  nodup_of_le (inter_le_right s t)\n\n@[simp] theorem nodup_union {\u03b1 : Type u_1} [DecidableEq \u03b1] {s : multiset \u03b1} {t : multiset \u03b1} :\n    nodup (s \u222a t) \u2194 nodup s \u2227 nodup t :=\n  sorry\n\n@[simp] theorem nodup_powerset {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup (powerset s) \u2194 nodup s :=\n  sorry\n\ntheorem nodup_powerset_len {\u03b1 : Type u_1} {n : \u2115} {s : multiset \u03b1} (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {s : multiset \u03b1} {t : \u03b1 \u2192 multiset \u03b2} :\n    nodup (bind s t) \u2194\n        (\u2200 (a : \u03b1), a \u2208 s \u2192 nodup (t a)) \u2227 pairwise (fun (a b : \u03b1) => disjoint (t a) (t b)) s :=\n  sorry\n\ntheorem nodup_ext {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} :\n    nodup s \u2192 nodup t \u2192 (s = t \u2194 \u2200 (a : \u03b1), a \u2208 s \u2194 a \u2208 t) :=\n  quotient.induction_on\u2082 s t\n    fun (l\u2081 l\u2082 : List \u03b1) (d\u2081 : nodup (quotient.mk l\u2081)) (d\u2082 : nodup (quotient.mk l\u2082)) =>\n      iff.trans quotient.eq (list.perm_ext d\u2081 d\u2082)\n\ntheorem le_iff_subset {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} :\n    nodup s \u2192 (s \u2264 t \u2194 s \u2286 t) :=\n  quotient.induction_on\u2082 s t\n    fun (l\u2081 l\u2082 : List \u03b1) (d : nodup (quotient.mk l\u2081)) =>\n      { mp := subset_of_le, mpr := list.subperm_of_subset_nodup d }\n\ntheorem range_le {m : \u2115} {n : \u2115} : range m \u2264 range n \u2194 m \u2264 n :=\n  iff.trans (le_iff_subset (nodup_range m)) range_subset\n\ntheorem mem_sub_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {s : multiset \u03b1} {t : multiset \u03b1}\n    (d : nodup s) : a \u2208 s - t \u2194 a \u2208 s \u2227 \u00aca \u2208 t :=\n  sorry\n\ntheorem map_eq_map_of_bij_of_nodup {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b3)\n    (g : \u03b2 \u2192 \u03b3) {s : multiset \u03b1} {t : multiset \u03b2} (hs : nodup s) (ht : nodup t)\n    (i : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b2) (hi : \u2200 (a : \u03b1) (ha : a \u2208 s), i a ha \u2208 t)\n    (h : \u2200 (a : \u03b1) (ha : a \u2208 s), f a = g (i a ha))\n    (i_inj : \u2200 (a\u2081 a\u2082 : \u03b1) (ha\u2081 : a\u2081 \u2208 s) (ha\u2082 : a\u2082 \u2208 s), i a\u2081 ha\u2081 = i a\u2082 ha\u2082 \u2192 a\u2081 = a\u2082)\n    (i_surj : \u2200 (b : \u03b2), b \u2208 t \u2192 \u2203 (a : \u03b1), \u2203 (ha : a \u2208 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\u2081 v\u2082 v\u2083 u\u2081 u\u2082 u\u2083\n\nnoncomputable theory\n\nnamespace category_theory\n\nopen category adjunction limits\n\nvariables {C : Type u\u2081} {D : Type u\u2082} {E : Type u\u2083}\nvariables [category.{v\u2081} C] [category.{v\u2082} D] [category.{v\u2083} E]\n\n/--\nA functor is *reflective*, or *a reflective inclusion*, if it is fully faithful and right adjoint.\n-/\nclass reflective (R : D \u2964 C) extends is_right_adjoint R, full R, faithful R.\n\nvariables {i : D \u2964 C}\n\n/--\nFor a reflective functor `i` (with left adjoint `L`), with unit `\u03b7`, we have `\u03b7_iL = iL \u03b7`.\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 [\u2190cancel_mono (i.map ((of_right_adjoint i).counit.app ((left_adjoint i).obj X))),\n     \u2190i.map_comp],\n simp,\nend\n\n/--\nWhen restricted to objects in `D` given by `i : D \u2964 C`, the unit is an isomorphism. In other words,\n`\u03b7_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 \u2190 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 `\u03b7_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 `\u03b7_A`.\n\n(For any `B` in the reflective subcategory, we automatically have that `\u03b5_B` is an iso.)\n-/\nlemma functor.ess_image.unit_is_iso [reflective i] {A : C} (h : A \u2208 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 \u226b (of_right_adjoint i).unit.app (i.obj h.witness) \u226b\n                  (left_adjoint i \u22d9 i).map h.get_iso.hom,\n  { rw this,\n    apply_instance },\n  rw \u2190 nat_trans.naturality,\n  simp,\nend\n\n/-- If `\u03b7_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 \u2208 i.ess_image :=\n\u27e8(left_adjoint i).obj A, \u27e8(as_iso ((of_right_adjoint i).unit.app A)).symm\u27e9\u27e9\n\n/-- If `\u03b7_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 \u2208 i.ess_image :=\nbegin\n  let \u03b7 : \ud835\udfed C \u27f6 left_adjoint i \u22d9 i := (of_right_adjoint i).unit,\n  haveI : is_iso (\u03b7.app (i.obj ((left_adjoint i).obj A))) := (i.obj_mem_ess_image _).unit_is_iso,\n  have : epi (\u03b7.app A),\n  { apply epi_of_epi (retraction (\u03b7.app A)) _,\n    rw (show retraction _ \u226b \u03b7.app A = _, from \u03b7.naturality (retraction (\u03b7.app A))),\n    apply epi_comp (\u03b7.app (i.obj ((left_adjoint i).obj A))) },\n  resetI,\n  haveI := is_iso_of_epi_of_split_mono (\u03b7.app A),\n  exact mem_ess_image_of_unit_is_iso A,\nend\n\n/-- Composition of reflective functors. -/\ninstance reflective.comp (F : C \u2964 D) (G : D \u2964 E) [Fr : reflective F] [Gr : reflective G] :\n  reflective (F \u22d9 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 \u27f6 i.obj B) \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 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) \u27f6 i.obj B) :\n  (unit_comp_partial_bijective_aux _ _).symm f = (of_right_adjoint i).unit.app A \u226b f :=\nby simp [unit_comp_partial_bijective_aux]\n\n/--\nIf `i` has a reflector `L`, then the function `(i.obj (L.obj A) \u27f6 B) \u2192 (A \u27f6 B)` given by\nprecomposing with `\u03b7.app A` is a bijection provided `B` is in the essential image of `i`.\nThat is, the function `\u03bb (f : i.obj (L.obj A) \u27f6 B), \u03b7.app A \u226b 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 \u27f6 B) \u2243 (i.obj (L.obj A) \u27f6 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 `\u03b7.app A` is an isomorphism.\n-/\ndef unit_comp_partial_bijective [reflective i] (A : C) {B : C} (hB : B \u2208 i.ess_image) :\n  (A \u27f6 B) \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 B) :=\ncalc (A \u27f6 B) \u2243 (A \u27f6 i.obj hB.witness) : iso.hom_congr (iso.refl _) hB.get_iso.symm\n     ...     \u2243 (i.obj _ \u27f6 i.obj hB.witness) : unit_comp_partial_bijective_aux _ _\n     ...     \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 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 \u2208 i.ess_image) (f) :\n  (unit_comp_partial_bijective A hB).symm f = (of_right_adjoint i).unit.app A \u226b 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 \u27f6 B')\n  (hB : B \u2208 i.ess_image) (hB' : B' \u2208 i.ess_image) (f : i.obj ((left_adjoint i).obj A) \u27f6 B) :\n  (unit_comp_partial_bijective A hB').symm (f \u226b h) =\n    (unit_comp_partial_bijective A hB).symm f \u226b h :=\nby simp\n\nlemma unit_comp_partial_bijective_natural [reflective i] (A : C) {B B' : C} (h : B \u27f6 B')\n  (hB : B \u2208 i.ess_image) (hB' : B' \u2208 i.ess_image) (f : A \u27f6 B) :\n  (unit_comp_partial_bijective A hB') (f \u226b h) = unit_comp_partial_bijective A hB f \u226b h :=\nby rw [\u2190equiv.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 (\u03b1 \u03b2 : Sort _) :=\n(toFun : \u03b1 \u2192 \u03b2)\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 (\u03b1) : BundledFunction \u03b1 \u03b1 := \u27e8\u03bb a => a\u27e9\n\n@[simp] theorem coe_id : (id \u03b1).toFun = _root_.id := rfl\n\nexample (x : \u03b1) : (id \u03b1).toFun x = x :=\nby simp only [coe_id, id_eq] -- should succeed\nexample (x : \u03b1) : (id \u03b1).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 \u03b1 \u03b2) : \u03b1 \u2192 \u03b2 := f.toFun\n\n-- Projections functions are expanded when populating the discrimination tree, and are indexed as `Expr.proj` objects.\n-- `@toFun \u03b1 \u03b2` 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 \u03b1 \u03b2 a = otherProjection a := rfl\n@[simp] theorem id_apply : (id \u03b1).otherProjection x = x := rfl\n\nexample : (id \u03b1).toFun x = x := by simp only [toFun_eq_otherProjection, id_apply]; done -- should work\nexample : (id \u03b1).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 : \u03b1) := x\n\n@[simp] theorem id2_eq_id : @id2 \u03b1 = 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) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Keeley Hoek, Scott Morrison\n-/\nimport tactic.core\n\n/-!\n## #simp\nA user command to run the simplifier.\n-/\n\nnamespace tactic\n\n/-- Strip all annotations of non local constants in the passed `expr`. (This is required in an\nincantation later on in order to make the C++ simplifier happy.) -/\nprivate meta def strip_annotations_from_all_non_local_consts {elab : bool} (e : expr elab)\n  : expr elab :=\nexpr.unsafe_cast $ e.unsafe_cast.replace $ \u03bb e n,\n  match e.is_annotation with\n  | some (_, expr.local_const _ _ _ _) := none\n  | some (_, _) := e.erase_annotations\n  | _ := none\n  end\n\n/-- `simp_arg_type.to_pexpr` retrieves the `pexpr` underlying the given `simp_arg_type`, if there is\none. -/\nmeta def simp_arg_type.to_pexpr : simp_arg_type \u2192 option pexpr\n| sat@(simp_arg_type.expr e) := e\n| sat@(simp_arg_type.symm_expr e) := e\n| sat := none\n\n/-- Incantation which prepares a `pexpr` in a `simp_arg_type` for use by the simplifier after\n`expr.replace_subexprs` as been called to replace some of its local variables. -/\nprivate meta def replace_subexprs_for_simp_arg (e : pexpr) (rules : list (expr \u00d7 expr)) : pexpr :=\nstrip_annotations_from_all_non_local_consts $ pexpr.of_expr $ e.unsafe_cast.replace_subexprs rules\n\n/-- `simp_arg_type.replace_subexprs` calls `expr.replace_subexprs` on the underlying `pexpr`, if\nthere is one, and then prepares the result for use by the simplifier. -/\nmeta def simp_arg_type.replace_subexprs : simp_arg_type \u2192 list (expr \u00d7 expr) \u2192 simp_arg_type\n| (simp_arg_type.expr      e) rules :=\n    simp_arg_type.expr      $ replace_subexprs_for_simp_arg e rules\n| (simp_arg_type.symm_expr e) rules :=\n    simp_arg_type.symm_expr $ replace_subexprs_for_simp_arg e rules\n| sat rules := sat\n\nsetup_tactic_parser\n\n/- Turn off the messages if the result is exactly `true` with this option. -/\ndeclare_trace silence_simp_if_true\n\n/--\nThe basic usage is `#simp e`, where `e` is an expression,\nwhich will print the simplified form of `e`.\n\nYou can specify additional simp lemmas as usual for example using\n`#simp [f, g] : e`, or `#simp with attr : e`.\n(The colon is optional, but helpful for the parser.)\n\n`#simp` understands local variables, so you can use them to\nintroduce parameters.\n-/\n@[user_command] meta def simp_cmd (_ : parse $ tk \"#simp\") : lean.parser unit :=\ndo\n  no_dflt \u2190 only_flag,\n  hs \u2190 simp_arg_list,\n  attr_names \u2190 with_ident_list,\n  o \u2190 optional (tk \":\"),\n  e \u2190 types.texpr,\n\n  /- Retrieve the `pexpr`s parsed as part of the simp args, and collate them into a big list. -/\n  let hs_es := list.join $ hs.map $ option.to_list \u2218 simp_arg_type.to_pexpr,\n\n  /- Synthesize a `tactic_state` including local variables as hypotheses under which `expr.simp`\n     may be safely called with expected behaviour given the `variables` in the environment. -/\n  (ts, mappings) \u2190 synthesize_tactic_state_with_variables_as_hyps (e :: hs_es),\n\n  /- Enter the `tactic` monad, *critically* using the synthesized tactic state `ts`. -/\n  simp_result \u2190 lean.parser.of_tactic $ \u03bb _, do\n  { /- Resolve the local variables added by the parser to `e` (when it was parsed) against the local\n       hypotheses added to the `ts : tactic_state` which we are using. -/\n    e \u2190 to_expr e,\n\n    /- Replace the variables referenced in the passed `simp_arg_list` with the `expr`s corresponding\n       to the local hypotheses we created.\n\n       We would prefer to just elaborate the `pexpr`s encoded in the `simp_arg_list` against the\n       tactic state we have created (as we could with `e` above), but the simplifier expects\n       `pexpr`s and not `expr`s. Thus, we just modify the `pexpr`s now and let `simp` do the\n       elaboration when the time comes.\n\n       You might think that we could just examine each of these `pexpr`s, call `to_expr` on them,\n       and then call `to_pexpr` afterward and save the results over the original `pexprs`. Due to\n       how functions like `simp_lemmas.add_pexpr` are implemented in the core library, the `simp`\n       framework is not robust enough to handle this method. When pieces of expressions like\n       annotation macros are injected, the direct patten matches in the `simp_lemmas.*` codebase\n       fail, and the lemmas we want don't get added.\n       -/\n    let hs := hs.map $ \u03bb sat, sat.replace_subexprs mappings,\n\n    /- Finally, call `expr.simp` with `e` and return the result. -/\n    prod.fst <$> e.simp {} failed no_dflt attr_names hs } ts,\n\n  /- Trace the result. -/\n  when (\u00ac is_trace_enabled_for `silence_simp_if_true \u2228 simp_result \u2260 expr.const `true [])\n    (trace simp_result)\n\nadd_tactic_doc\n{ name                     := \"#simp\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.simp_cmd],\n  tags                     := [\"simplification\"] }\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/simp_command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.06278921035082041, "lm_q1q2_score": 0.02724935348192915}}
{"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 \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 \u03b2') \u2208 traverse f (a :: as) \u2194 b \u2208 f a \u2227 bs \u2208 traverse f as,\n    by simp [mem_traverse as bs],\n  iff.intro\n    (assume \u27e8_, \u27e8b, hb, rfl\u27e9, _, hl, rfl\u27e9, \u27e8hb, hl\u27e9)\n    (assume \u27e8hb, hl\u27e9, \u27e8_, \u27e8b, hb, rfl\u27e9, _, hl, rfl\u27e9)\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {\u03c3 : Type u}\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3,\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": "import tactic\n\n-- \u0415\u0441\u043b\u0438 \u0432\u044b \u043d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u043b\u0438 \u0441 \u043c\u043e\u043d\u0430\u0434\u0430\u043c\u0438 \u0438 do-\u0431\u043b\u043e\u043a\u0430\u043c\u0438 \u0440\u0430\u043d\u044c\u0448\u0435, \u043f\u043e\u0447\u0438\u0442\u0430\u0439\u0442\u0435 \u0442\u0443\u0442\u043e\u0440\u0438\u0430\u043b \u0432 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442\u0435\n-- `tactic \u03b1` - \u0444\u0443\u043d\u043a\u0446\u0438\u044f, \u0440\u0430\u0431\u043e\u0442\u0430\u044e\u0449\u0438\u0435 \u0432 \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0435 \u0441\u043e\u0441\u0442\u043e\u044f\u043d\u0438\u044f \u0442\u0430\u043a\u0442\u0438\u043a\u0438 \u0438 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u03b1\n-- `tactic unit` - \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 (\u0438\u043b\u0438 \u0436\u0435 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 `()`)\n\nopen tactic\n\nmeta def make_nat : tactic \u2115 := \nreturn 42\n\n-- \u041a\u0430\u043a \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0440\u0430\u0431\u043e\u0442\u044b \u0434\u0440\u0443\u0433\u0438\u0445 \u0442\u0430\u043a\u0442\u0438\u043a \u0432\u043d\u0443\u0442\u0440\u0438 do-\u0431\u043b\u043e\u043a\u0430?\n-- n \u2190 make_nat\n\nmeta def trace_nat : tactic unit :=\ndo\n  n \u2190 make_nat,\n  tactic.trace n\n\n-- \u041a\u0430\u043a \u0434\u0435\u0431\u0430\u0433\u0430\u0442\u044c \u0442\u0430\u043a\u0442\u0438\u043a\u0438?\nexample : false :=\nbegin\n  trace_nat,\n  sorry,\nend\n\nrun_cmd trace_nat\n\n-- \u041a\u0430\u043a \u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441 \u043e\u043a\u0440\u0443\u0436\u0435\u043d\u0438\u0435\u043c \u0432 \u0442\u0430\u043a\u0442\u0438\u043a\u0435?\n-- \u0414\u043b\u044f \u043f\u0435\u0440\u0432\u043e\u0439 \u0446\u0435\u043b\u0438 \u0435\u0441\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044f tactic.target\n#check tactic.target\n\nmeta def show_goal : tactic unit :=\ndo\n  t \u2190 target,\n  trace t\n  -- trace $ expr.to_raw_fmt t \u043f\u043e\u043a\u0430\u0436\u0435\u0442 \u043f\u043e\u043b\u043d\u0443\u044e \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u0443, \u043d\u0435 pretty printed\n\nexample (a b : \u2124) : a^2 + b^2 \u2265 0 :=\nbegin\n  show_goal,\n  sorry,\nend\n\n-- \u0414\u043b\u044f \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u044b\u0445 \u0433\u0438\u043f\u043e\u0442\u0435\u0437: \u0444\u0443\u043d\u043a\u0446\u0438\u0438 get_local \u0438 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 \u2190 get_local nm,\n  trace a,\n  trace (expr.to_raw_fmt a),\n  a_type \u2190 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-- \u0414\u043b\u044f \u043c\u043e\u043d\u0430\u0434\u0438\u0447\u0435\u0441\u043a\u043e\u0433\u043e \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0435\u0441\u0442\u044c \u043c\u043d\u043e\u0433\u043e (\u0445\u043e\u0442\u044c \u0438 \u043d\u0435 \u0442\u0430\u043a \u0431\u043e\u0433\u0430\u0442\u043e, \u043a\u0430\u043a \u0432 Haskell) \u0444\u0443\u043d\u043a\u0446\u0438\u0439\n#check list.mmap\n\nmeta def inspect_all : tactic unit :=\ndo\n  fail \"TODO\"\n\nexample (A : Type) (b c : A) (h : b = c) : false :=\nbegin\n  inspect_all,\n  sorry,\nend\n\n\n-- \u041d\u0430\u043a\u043e\u043d\u0435\u0446, \u0440\u0435\u0430\u043b\u0438\u0437\u0443\u0435\u043c \u0432\u0435\u0440\u0441\u0438\u044e \u0442\u0430\u043a\u0442\u0438\u043a\u0438 `assumption`\n\nmeta def assump_one (e : expr) : tactic unit := sorry\n\nmeta def assump_list : list expr \u2192 tactic unit := sorry\n\nmeta def assump : tactic unit := sorry\n\n-- \u0422\u0435\u0441\u0442\nexample {A B C : Prop} (ha : A) (hb : B) (hc : C) : B :=\nbegin\n  assump,\n  -- sorry,\nend\n\n-- \u0411\u043e\u043b\u044c\u0448\u0435 \u0443\u043f\u0440\u0430\u0436\u043d\u0435\u043d\u0438\u0439: 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/e02_tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.07807816031818418, "lm_q1q2_score": 0.027221570770758836}}
{"text": "/-\nCopyright (c) 2018 Kenny Lau. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes H\u00f6lzl, 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 `\u03a0\u2080 i, M i`\n\nGiven an indexed collection of `R`-semimodules `M i`, the `R`-semimodule structure on `\u03a0\u2080 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 \u2192\u2097[R] \u03a0\u2080 i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lmk s : (\u03a0 i : (\u2191s : set \u03b9), M i) \u2192\u2097[R] \u03a0\u2080 i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lapply i : (\u03a0\u2080 i, M i) \u2192\u2097[R] M`: the map `\u03bb 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 {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (s : finset \u03b9) : linear_map R ((i : \u21a5\u2191s) \u2192 M \u2191i) (dfinsupp fun (i : \u03b9) => M i) :=\n  linear_map.mk (mk s) sorry sorry\n\n/-- `dfinsupp.single` as a `linear_map` -/\ndef lsingle {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) : linear_map R (M i) (dfinsupp fun (i : \u03b9) => M i) :=\n  linear_map.mk (single i) sorry sorry\n\n/-- Two `R`-linear maps from `\u03a0\u2080 i, M i` which agree on each `single i x` agree everywhere. -/\ntheorem lhom_ext {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} {N : Type u_4} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] [add_comm_monoid N] [semimodule R N] {\u03c6 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N} {\u03c8 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N} (h : \u2200 (i : \u03b9) (x : M i), coe_fn \u03c6 (single i x) = coe_fn \u03c8 (single i x)) : \u03c6 = \u03c8 :=\n  linear_map.to_add_monoid_hom_injective (add_hom_ext h)\n\n/-- Two `R`-linear maps from `\u03a0\u2080 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 `\u03c6 (single a 1) = \u03c8 (single a 1)`. -/\ntheorem lhom_ext' {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} {N : Type u_4} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] [add_comm_monoid N] [semimodule R N] {\u03c6 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N} {\u03c8 : linear_map R (dfinsupp fun (i : \u03b9) => M i) N} (h : \u2200 (i : \u03b9), linear_map.comp \u03c6 (lsingle i) = linear_map.comp \u03c8 (lsingle i)) : \u03c6 = \u03c8 :=\n  lhom_ext fun (i : \u03b9) => linear_map.congr_fun (h i)\n\n/-- Interpret `\u03bb (f : \u03a0\u2080 i, M i), f i` as a linear map. -/\ndef lapply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) : linear_map R (dfinsupp fun (i : \u03b9) => M i) (M i) :=\n  linear_map.mk (fun (f : dfinsupp fun (i : \u03b9) => M i) => coe_fn f i) sorry sorry\n\n@[simp] theorem lmk_apply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (s : finset \u03b9) (x : (i : \u21a5\u2191s) \u2192 (fun (i : \u03b9) => M i) \u2191i) : coe_fn (lmk s) x = mk s x :=\n  rfl\n\n@[simp] theorem lsingle_apply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) (x : M i) : coe_fn (lsingle i) x = single i x :=\n  rfl\n\n@[simp] theorem lapply_apply {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] (i : \u03b9) (f : dfinsupp fun (i : \u03b9) => M i) : coe_fn (lapply i) f = coe_fn f i :=\n  rfl\n\n/-- The `dfinsupp` version of `finsupp.lsum`. -/\ndef lsum {\u03b9 : Type u_1} {R : Type u_2} {M : \u03b9 \u2192 Type u_3} {N : Type u_4} [dec_\u03b9 : DecidableEq \u03b9] [semiring R] [(i : \u03b9) \u2192 add_comm_monoid (M i)] [(i : \u03b9) \u2192 semimodule R (M i)] [add_comm_monoid N] [semimodule R N] : ((i : \u03b9) \u2192 linear_map R (M i) N) \u2243+ linear_map R (dfinsupp fun (i : \u03b9) => M i) N :=\n  add_equiv.mk\n    (fun (F : (i : \u03b9) \u2192 linear_map R (M i) N) =>\n      linear_map.mk \u21d1(sum_add_hom fun (i : \u03b9) => linear_map.to_add_monoid_hom (F i)) sorry sorry)\n    (fun (F : linear_map R (dfinsupp fun (i : \u03b9) => M i) N) (i : \u03b9) => 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 \u2190 Lean.Meta.Match.mkMatcher input\n  let origMatcher \u2190 Lean.getConstInfo matcher\n  if not <| input.matcherName == matcher then\n    throwError \"matcher name not reconstructed correctly: {matcher} \u225f {input.matcherName}\"\n\n  let lCtx \u2190 Lean.getLCtx\n  let fvars \u2190 Lean.collectFVars {} res.matcher\n  let closure \u2190 Lean.Meta.Closure.mkLambda (fvars.fvarSet.toList.toArray.map lCtx.get!) res.matcher\n\n  let origTy := origMatcher.value!\n  let newTy \u2190 closure\n  if not <| \u2190Lean.Meta.isDefEq origTy newTy then\n    throwError \"matcher {matcher} does not round-trip correctly:\\n{origTy} \u225f {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 \u2228 q \u2192 r \u2192 (q \u2227 r) \u2228 (p \u2227 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 \u27e8hq, h\u27e9 }\n#eval checkWithMkMatcherInput ``ex3.match_1\n\ninductive C\n| mk\u2081 : Nat \u2192 C\n| mk\u2082 : Nat \u2192 Nat \u2192 C\n\ndef C.x : C \u2192 Nat\n| C.mk\u2081 x   => x\n| C.mk\u2082 x _ => x\n#eval checkWithMkMatcherInput ``C.x.match_1\n\ndef head : {\u03b1 : Type} \u2192 List \u03b1 \u2192 Option \u03b1\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 : {\u03b1 : Type} \u2192 List \u03b1 \u2192 Option \u03b1 :=\n@fun\n  | _, a::as => some a\n  | _, _     => none\n\ntheorem ex5 : head2 [1, 2] = some 1 :=\nrfl\n\ndef head3 {\u03b1 : Type} (xs : List \u03b1) : Option \u03b1 :=\nlet rec aux : {\u03b1 : Type} \u2192 List \u03b1 \u2192 Option \u03b1\n  | _, a::as => some a\n  | _, _     => none;\naux xs\n\ntheorem ex6 : head3 [1, 2] = some 1 :=\nrfl\n\ninductive Vec.{u} (\u03b1 : Type u) : Nat \u2192 Type u\n| nil : Vec \u03b1 0\n| cons {n} (head : \u03b1) (tail : Vec \u03b1 n) : Vec \u03b1 (n+1)\n\ndef Vec.mapHead1 {\u03b1 \u03b2 \u03b4} : {n : Nat} \u2192 Vec \u03b1 n \u2192 Vec \u03b2 n \u2192 (\u03b1 \u2192 \u03b2 \u2192 \u03b4) \u2192 Option \u03b4\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 {\u03b1 \u03b2 \u03b4} : {n : Nat} \u2192 Vec \u03b1 n \u2192 Vec \u03b2 n \u2192 (\u03b1 \u2192 \u03b2 \u2192 \u03b4) \u2192 Option \u03b4\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 {\u03b1 \u03b2 \u03b4} : {n : Nat} \u2192 Vec \u03b1 n \u2192 Vec \u03b2 n \u2192 (\u03b1 \u2192 \u03b2 \u2192 \u03b4) \u2192 Option \u03b4\n| _, nil,            nil,         f => none\n| _, cons (tail := as) (head := a), cons b bs,   f => some (f a b)\n\ninductive Foo\n| mk\u2081 (x y z w : Nat)\n| mk\u2082 (x y z w : Nat)\n\ndef Foo.z : Foo \u2192 Nat\n| mk\u2081 (z := z) .. => z\n| mk\u2082 (z := z) .. => z\n#eval checkWithMkMatcherInput ``Foo.z.match_1\n\n#eval (Foo.mk\u2081 10 20 30 40).z\n\ntheorem ex7 : (Foo.mk\u2081 10 20 30 40).z = 30 :=\nrfl\n\ndef Foo.addY? : Foo \u00d7 Foo \u2192 Option Nat\n| (mk\u2081 (y := y\u2081) .., mk\u2081 (y := y\u2082) ..) => some (y\u2081 + y\u2082)\n| _ => none\n#eval checkWithMkMatcherInput ``Foo.addY?.match_1\n\n#eval Foo.addY? (Foo.mk\u2081 1 2 3 4, Foo.mk\u2081 10 20 30 40)\n\ntheorem ex8 : Foo.addY? (Foo.mk\u2081 1 2 3 4, Foo.mk\u2081 10 20 30 40) = some 22 :=\nrfl\n\ninstance {\u03b1} : Inhabited (Sigma fun m => Vec \u03b1 m) :=\n\u27e8\u27e80, Vec.nil\u27e9\u27e9\n\npartial def filter {\u03b1} (p : \u03b1 \u2192 Bool) : {n : Nat} \u2192 Vec \u03b1 n \u2192 Sigma fun m => Vec \u03b1 m\n| _, Vec.nil        => \u27e80, Vec.nil\u27e9\n| _, Vec.cons x xs  => match p x, filter p xs with\n  | true,  \u27e8_, ys\u27e9 => \u27e8_, Vec.cons x ys\u27e9\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 \u2192 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 \u27e8y, rfl\u27e9\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 \u27e8y, Eq.trans (fooEq b).symm h\u27e9\n| none   => none\n#eval checkWithMkMatcherInput ``Bla.isNat2?.match_1\n\ndef foo2 (x : Nat) : Nat :=\nmatch x, rfl : (y : Nat) \u2192 x = y \u2192 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": "structure S where\n  fn1 : Nat\n  value : Bool\n  name : String\n\ndef f (s : S) : Nat := by\n  refine s.\n         --^ textDocument/completion\n\ndef g (s : S) : Nat := by\n  match s.\n        --^ textDocument/completion\n\ntheorem ex (x : Nat) : 0 + x = x := by\n  match x with\n--^ $/lean/plainGoal\n  | 0 => done\n       --^ $/lean/plainGoal\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/match.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.05749327516681067, "lm_q1q2_score": 0.027176121188143266}}
{"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 \u2192 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 (\u03bb r (s:string), max r s.length) 0 in\nl.map $ \u03bb s, nat.iterate (\u03bb 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) : \u2115 := es.s.size\n\nmeta def entries.add : entries \u2192 entry \u2192 entries\n| es@\u27e8s, l\u27e9 e := if s.contains e.expr then es else \u27e8s.insert e.expr e, e :: l\u27e9\n\nmeta def entries.head (es : entries) : option entry := es.l.head'\n\nmeta def format_aux : list string \u2192 list string \u2192 list string \u2192 list entry \u2192 tactic format\n| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do\n  fmt \u2190 do\n  { let margin := string.join (list.repeat \" \u2502\" en.depth),\n    let margin := match en.status with\n      | status.sintro := \" \u251c\" ++ margin\n      | status.intro := \" \u2502\" ++ margin ++ \" \u250c\"\n      | status.reg := \" \u2502\" ++ margin ++ \"\"\n      | status.lam := \" \u2502\" ++ margin ++ \"\"\n      end,\n    p \u2190 infer_type en.expr >>= pp,\n    let lhs :=  line ++ \"\u2502\" ++ dep ++ \"\u2502 \" ++ 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\u27e8\u03bb es : entries,\n  let lines := pad_right $ es.l.map (\u03bb en, to_string en.line),\n      deps  := pad_right $ es.l.map (\u03bb en, string.intercalate \",\" (en.deps.map to_string)),\n      thms  := pad_right $ es.l.map (\u03bb en, (entry.thm en).to_string) in\n  format_aux lines deps thms es.l\u27e9\n\nmeta def append_dep (filter : expr \u2192 tactic unit)\n (es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=\ndo { ei \u2190 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 \u2190 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 \u2192 tactic unit)\nwith explode.core : expr \u2192 bool \u2192 nat \u2192 entries \u2192 tactic entries\n| e@(lam n bi d b) si depth es := do\n  m \u2190 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 := \u27e8l, es.size, depth, status.sintro, thm.name n, []\u27e9 in do\n    es' \u2190 explode.core b' si depth (es.add en),\n    return $ es'.add \u27e8e, es'.size, depth, status.lam, thm.string \"\u2200I\", [es.size, es'.size - 1]\u27e9\n  else do\n    let en : entry := \u27e8l, es.size, depth, status.intro, thm.name n, []\u27e9,\n    es' \u2190 explode.core b' si (depth + 1) (es.add en),\n    -- in case of a \"have\" clause, the b' here has an annotation\n    deps' \u2190 explode.append_dep filter es' b'.erase_annotations [],\n    deps' \u2190 explode.append_dep filter es' l deps',\n    return $ es'.add \u27e8e, es'.size, depth, status.lam, thm.string \"\u2200I\", deps'\u27e9\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 := \u27e8fn, es.size, depth, status.reg, thm.expr fn, []\u27e9,\n    return (es.add en)\n  | (fn, args) := do\n    es' \u2190 explode.core fn ff depth es,\n    -- in case of a \"have\" clause, the fn here has an annotation\n    deps \u2190 explode.append_dep filter es' fn.erase_annotations [],\n    explode.args e args depth es' (thm.string \"\u2200E\") deps\n  end\nwith explode.args : expr \u2192 list expr \u2192 nat \u2192 entries \u2192 thm \u2192 list nat \u2192 tactic entries\n| e (arg :: args) depth es thm deps := do\n  es' \u2190 explode.core arg ff depth es <|> return es,\n  deps' \u2190 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 \u27e8e, es.size, depth, status.reg, thm, deps.reverse\u27e9)\n\nmeta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=\nlet filter := if hide_non_prop then \u03bb e, may_be_proof e >>= guardb else \u03bb _, skip in\ntactic.explode.core filter e tt 0 (default _)\n\nmeta def explode (n : name) : tactic unit :=\ndo const n _ \u2190 resolve_name n | fail \"cannot resolve name\",\n  d \u2190 get_decl n,\n  v \u2190 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 \u2190 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 : \u2200 {a : Prop}, a \u2192 (a \u2194 true)\n0\u2502   \u2502 a         \u251c Prop\n1\u2502   \u2502 h         \u251c a\n2\u2502   \u2502 hl        \u2502 \u250c a\n3\u2502   \u2502 trivial   \u2502 \u2502 true\n4\u25022,3\u2502 \u2200I        \u2502 a \u2192 true\n5\u2502   \u2502 hr        \u2502 \u250c true\n6\u25025,1\u2502 \u2200I        \u2502 true \u2192 a\n7\u25024,6\u2502 iff.intro \u2502 a \u2194 true\n8\u25021,7\u2502 \u2200I        \u2502 a \u2192 (a \u2194 true)\n9\u25020,8\u2502 \u2200I        \u2502 \u2200 {a : Prop}, a \u2192 (a \u2194 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 `\u2200E` 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 `\u2200E h ha` where `\u2200E` is\n    (n-ary) modus ponens.\n  * If the proof term is a lambda, we will also use `\u2200I` 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 `\u2200I` 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 `\u2200I` 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 \u2190 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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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) \u2190 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 {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x : \u03b1} {y : \u03b1} (x' : \u03b1) (y' : \u03b1) (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nby mono*\n```\n\n-/\n/--\ntransforms a goal of the form `f x \u227c f y` into `x \u2264 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 : \u2115 \u2192 rep_arity\n| many : rep_arity\n\n/--\n\n`ac_mono` reduces the `f x \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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 \u2192 Type u) (F: Type \u2192 Type v) :=\n  \u2200 T, E T \u2192 F T\nabbrev sum1 (E F: Type \u2192 Type) :=\n  fun T => E T \u2295 F T\ninductive Void1: Type \u2192 Type :=\n\ninfixr:40 \" ~> \" => to1\ninfixr:60 \" +' \" => sum1\n\nclass Member (E: Type \u2192 Type) (F: Type \u2192 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 \u2218 Member.inject T\n\ninstance MemberSumR {E F G} [Member E G]: Member E (F +' G) where\n  inject T := Sum.inr \u2218 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 \u2192 Type) (R: Type) where\n  | Ret (r: R): Fitree E R\n  | Vis {T: Type} (e: E T) (k: T \u2192 Fitree E R): Fitree E R\n\ndef Fitree.map {E R R'} (f: R \u2192 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 \u2192 Fitree E R :=\n  Fitree.Ret\n\n@[simp_itree]\ndef Fitree.trigger {E: Type \u2192 Type} {F: Type \u2192 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 \u2192 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 \u2192 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 \u2192 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\u2081: E ~> G) (h\u2082: F ~> G): E +' F ~> G :=\n  fun R ef => match ef with\n  | Sum.inl e => h\u2081 R e\n  | Sum.inr f => h\u2082 R f\n\n@[simp] theorem Fitree.case_left:\n  Fitree.case h\u2081 h\u2082 _ (Sum.inl e) = h\u2081 _ e := rfl\n@[simp] theorem Fitree.case_right:\n  Fitree.case h\u2081 h\u2082 _ (Sum.inr e) = h\u2082 _ 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 \u2192 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 \u2192 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 \u2192 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 \u2192 OptionT M R :=\n  interp h\n\n@[simp_itree]\ndef Fitree.interpExcept {M \u03b5} [Monad M] {E} (h: E ~> ExceptT \u03b5 M) {R}:\n    Fitree E R \u2192 ExceptT \u03b5 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 \u2192 S \u2192 Fitree E (R \u00d7 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 \u2192 Fitree E (R \u00d7 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 \u2192 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 \u2192 Fitree E (Except \u03b5 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 \u03b5 (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 \u03b5} [Monad M] (h: E ~> ExceptT \u03b5 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 \u2192 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 \u00d7 String) := by\n  simp [WriterT]\n\ntheorem Fitree.interpWriter_bind (h: E ~> WriterT (Fitree F))\n  (t: Fitree E T) (k: T \u2192 Fitree E R):\n    Fitree.interpWriter h (Fitree.bind t k) =\n    Fitree.bind (Fitree.interpWriter h t) fun (x,s\u2081) =>\n      Fitree.bind (Fitree.interpWriter h (k x)) fun (y,s\u2082) =>\n        Fitree.ret (y,s\u2081++s\u2082) := by\n  induction t with\n  | Ret _ =>\n      simp [bind, interpWriter]\n      have h\u2081: forall x, \"\" ++ x = x := by\n        simp [HAppend.hAppend, Append.append, String.append]\n        simp [List.nil_append]\n      simp [h\u2081]\n      have h\u2082: forall (\u03b1 \u03b2: Type) (x: \u03b1 \u00d7 \u03b2), (x.fst, x.snd) = x := by simp\n      simp [h\u2082]\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 \u2192 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) \u2192 match (bind) theorem to rewrite, so...\n      have fequal2 \u03b1 \u03b2 (f g: \u03b1 \u2192 \u03b2) x y: f = g \u2192 x = y \u2192 f x = g y :=\n        fun h\u2081 h\u2082 => by simp [h\u2081, h\u2082]\n      apply fequal2; rfl; funext x\n      cases x <;> simp [ih]\n\ntheorem Fitree.interpExcept_bind (h: E ~> ExceptT \u03b5 (Fitree F))\n  (t: Fitree E T) (k: T \u2192 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 \u03b5 => Fitree.ret (.error \u03b5)\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 \u03b1 \u03b2 (f g: \u03b1 \u2192 \u03b2) x y: f = g \u2192 x = y \u2192 f x = g y :=\n        fun h\u2081 h\u2082 => by simp [h\u2081, h\u2082]\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 \u2192 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 \u2192 Prop :=\n  | Ret r: noEventL (Ret r)\n  | Vis f k: (\u2200 t, noEventL (k t)) \u2192 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 := (\u2190 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 $ \u2190 `(tactic|dsimp [$(\u27e8fullSet\u27e9),*])\n  else\n    evalTactic $ \u2190 `(tactic|simp [$(\u27e8fullSet\u27e9),*])\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 : \u2115) (b : \u2115) (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 : \u2115) : 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 : \u2115) (b : \u2115) (c : \u2115) : a < b \u2192 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 : \u2115) (b : \u2115) (c : \u2115) : a < b \u2192 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 {\u03b1 : Type u} {\u03b2 : Type v} [SizeOf \u03b1] [SizeOf \u03b2] : psum \u03b1 \u03b2 \u2192 \u2115 :=\n  sorry\n\nprotected def psum.has_sizeof_alt (\u03b1 : Type u) (\u03b2 : Type v) [SizeOf \u03b1] [SizeOf \u03b2] :\n    SizeOf (psum \u03b1 \u03b2) :=\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 \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1} (xs : list \u03b1) :\n  list.traverse id.mk xs = xs :=\nby induction xs; simp! * with functor_norm; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 {\u03c3 : Type u}\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3,\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\u2080 u\u2081 v\u2080 v\u2081 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 \u03b1` 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\u2081 \u2192 Type\nu\u2082`, this class convert between instantiations, from\n`M.{u} : Type u\u2081 \u2192 Type u\u2082` to `M.{v} : Type v\u2081 \u2192 Type v\u2082` and back -/\nclass uliftable (f : Type u\u2080 \u2192 Type u\u2081) (g : Type v\u2080 \u2192 Type v\u2081) \nwhere\n  congr : {\u03b1 : Type u\u2080} \u2192 {\u03b2 : Type v\u2080} \u2192 \u03b1 \u2243 \u03b2 \u2192 f \u03b1 \u2243 g \u03b2\n\nnamespace uliftable\n\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} \u03b1` and lifts it to M.{max u v} (ulift.{v} \u03b1) -/\ndef up {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g] {\u03b1 : Type u\u2080} : f \u03b1 \u2192 g (ulift \u03b1) :=\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} \u03b1)` and lowers it to `M.{u} \u03b1` -/\ndef down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g] {\u03b1 : Type u\u2080} : g (ulift \u03b1) \u2192 f \u03b1 :=\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\u2080 \u2192 Type v\u2081) (G : Type (max v\u2080 u\u2080) \u2192 Type u\u2081) [uliftable F G] [Monad G] {\u03b1 : Type v\u2080} {\u03b2 : Type (max v\u2080 u\u2080)} (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n  up x >>= f \u2218 ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type v\u2080 \u2192 Type v\u2081} [L : uliftable G F] [Monad F] {\u03b1 : Type (max u\u2080 v\u2080)} {\u03b2 : Type v\u2080} (x : F \u03b1) (f : \u03b1 \u2192 G \u03b2) : G \u03b2 :=\n  down (x >>= up \u2218 f)\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u\u2080 \u2192 Type u\u2081} {G : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [inst : uliftable F G] [Functor G] {\u03b1 : Type u\u2080} {\u03b2 : Type (max u\u2080 v\u2080)} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\n  (f \u2218 ulift.down) <$> up x\n\n/-- map function that moves down universes -/\ndef down_map {F : Type (max u\u2080 v\u2080) \u2192 Type u\u2081} {G : Type \u2192 Type v\u2081} [inst : uliftable G F] [Functor F] {\u03b1 : Type (max u\u2080 v\u2080)} {\u03b2 : Type} (f : \u03b1 \u2192 \u03b2) (x : F \u03b1) : G \u03b2 :=\n  down ((ulift.up \u2218 f) <$> x)\n\n@[simp] theorem up_down {f : Type u\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g] {\u03b1 : Type u\u2080} (x : g (ulift \u03b1)) : 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\u2080 \u2192 Type u\u2081} {g : Type (max u\u2080 v\u2080) \u2192 Type v\u2081} [uliftable f g] {\u03b1 : Type u\u2080} (x : f \u03b1) : 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 (\u03b1 : Type u_1) (\u03b2 : Type u_2) (F : \u03b1 \u2243 \u03b2) => F\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {s : Type u\u2080} {s' : Type u\u2081} {m : Type u\u2080 \u2192 Type v\u2080} {m' : Type u\u2081 \u2192 Type v\u2081} [uliftable m m'] (F : s \u2243 s') : uliftable (state_t s m) (state_t s' m') :=\n  uliftable.mk\n    fun (\u03b1 : Type u\u2080) (\u03b2 : Type u\u2081) (G : \u03b1 \u2243 \u03b2) =>\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 \u2192 Type u_2} {m' : Type (max u_1 u_3) \u2192 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 \u2192 Type u_3} {m' : Type u_2 \u2192 Type u_4} [uliftable m m'] (F : s \u2243 s') : uliftable (reader_t s m) (reader_t s' m') :=\n  uliftable.mk\n    fun (\u03b1 : Type u_1) (\u03b2 : Type u_2) (G : \u03b1 \u2243 \u03b2) =>\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 \u2192 Type u_2} {m' : Type (max u_1 u_3) \u2192 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 \u2192 Type u_3} {m' : Type u_2 \u2192 Type u_4} [uliftable m m'] (F : r \u2243 r') : uliftable (cont_t r m) (cont_t r' m') :=\n  uliftable.mk fun (\u03b1 : Type u_1) (\u03b2 : 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 \u2192 Type u_2} {m' : Type (max u_1 u_3) \u2192 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) \u2192 Type u_5} {m' : Type (max u_3 u_4) \u2192 Type u_6} [uliftable m m'] (F : w \u2243 w') : uliftable (writer_t w m) (writer_t w' m') :=\n  uliftable.mk\n    fun (\u03b1 : Type (max u_1 u_2)) (\u03b2 : Type (max u_3 u_4)) (G : \u03b1 \u2243 \u03b2) =>\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) \u2192 Type u_3} {m' : Type (max (max u_1 u_2) u_4) \u2192 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 \u2192 Prop := id\n\nclass Foo (foo : Prop \u2192 Prop) where\n  l : x \u2192 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 \u2192 regular_mono` and\n* `regular_mono \u2192 mono`\nas well as the dual constructions for regular epimorphisms. Additionally, we give the\nconstruction\n* `regular_epi \u27f6 strong_epi`.\n\n-/\n\nnoncomputable theory\n\nnamespace category_theory\nopen category_theory.limits\n\nuniverses v\u2081 u\u2081 u\u2082\n\nvariables {C : Type u\u2081} [category.{v\u2081} 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 \u27f6 Y) :=\n(Z : C)\n(left right : Y \u27f6 Z)\n(w : f \u226b left = f \u226b right)\n(is_limit : is_limit (fork.of_\u03b9 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 \u27f6 Y) [regular_mono f] : mono f :=\nmono_of_is_limit_parallel_pair regular_mono.is_limit\n\ninstance equalizer_regular (g h : X \u27f6 Y) [has_limit (parallel_pair g h)] :\n  regular_mono (equalizer.\u03b9 g h) :=\n{ Z := Y,\n  left := g,\n  right := h,\n  w := equalizer.condition g h,\n  is_limit := fork.is_limit.mk _ (\u03bb s, limit.lift _ s) (by simp) (\u03bb s m w, by { ext1, simp [\u2190w] }) }\n\n/-- Every split monomorphism is a regular monomorphism. -/\n@[priority 100]\ninstance regular_mono.of_split_mono (f : X \u27f6 Y) [split_mono f] : regular_mono f :=\n{ Z     := Y,\n  left  := \ud835\udfd9 Y,\n  right := retraction f \u226b 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 \u27f6 Y` equalizing `regular_mono.left` and\n    `regular_mono.right` induces a morphism `l : W \u27f6 X` such that `l \u226b f = k`. -/\ndef regular_mono.lift' {W : C} (f : X \u27f6 Y) [regular_mono f] (k : W \u27f6 Y)\n  (h : k \u226b (regular_mono.left : Y \u27f6 @regular_mono.Z _ _ _ _ f _) = k \u226b regular_mono.right) :\n  {l : W \u27f6 X // l \u226b 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S}\n  {k : R \u27f6 S} [hr : regular_mono h] (comm : f \u226b h = g \u226b k)\n  (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono g :=\n{ Z := hr.Z,\n  left := k \u226b hr.left,\n  right := k \u226b hr.right,\n  w := by rw [\u2190 reassoc_of comm, \u2190 reassoc_of comm, hr.w],\n  is_limit :=\n  begin\n    apply fork.is_limit.mk' _ _,\n    intro s,\n    have l\u2081 : (fork.\u03b9 s \u226b k) \u226b regular_mono.left = (fork.\u03b9 s \u226b k) \u226b regular_mono.right,\n      rw [category.assoc, s.condition, category.assoc],\n    obtain \u27e8l, hl\u27e9 := fork.is_limit.lift' hr.is_limit _ l\u2081,\n    obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := pullback_cone.is_limit.lift' t _ _ hl,\n    refine \u27e8p, hp\u2082, _\u27e9,\n    intros m w,\n    have z : m \u226b g = p \u226b g := w.trans hp\u2082.symm,\n    apply t.hom_ext,\n    apply (pullback_cone.mk f g comm).equalizer_ext,\n    { erw [\u2190 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S}\n  {k : R \u27f6 S} [hr : regular_mono k] (comm : f \u226b h = g \u226b 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 \u27f6 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 \u27f6 Y) :=\n(W : C)\n(left right : W \u27f6 X)\n(w : left \u226b f = right \u226b f)\n(is_colimit : is_colimit (cofork.of_\u03c0 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 \u27f6 Y) [regular_epi f] : epi f :=\nepi_of_is_colimit_parallel_pair regular_epi.is_colimit\n\ninstance coequalizer_regular (g h : X \u27f6 Y) [has_colimit (parallel_pair g h)] :\n  regular_epi (coequalizer.\u03c0 g h) :=\n{ W := X,\n  left := g,\n  right := h,\n  w := coequalizer.condition g h,\n  is_colimit := cofork.is_colimit.mk _ (\u03bb s, colimit.desc _ s) (by simp)\n    (\u03bb s m w, by { ext1, simp [\u2190w] }) }\n\n/-- Every split epimorphism is a regular epimorphism. -/\n@[priority 100]\ninstance regular_epi.of_split_epi (f : X \u27f6 Y) [split_epi f] : regular_epi f :=\n{ W     := X,\n  left  := \ud835\udfd9 X,\n  right := f \u226b 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 \u27f6 W` coequalizing `regular_epi.left` and\n    `regular_epi.right` induces `l : Y \u27f6 W` such that `f \u226b l = k`. -/\ndef regular_epi.desc' {W : C} (f : X \u27f6 Y) [regular_epi f] (k : X \u27f6 W)\n  (h : (regular_epi.left : regular_epi.W f \u27f6 X) \u226b k = regular_epi.right \u226b k) :\n  {l : Y \u27f6 W // f \u226b 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S} {k : R \u27f6 S}\n  [gr : regular_epi g] (comm : f \u226b h = g \u226b k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi h :=\n{ W := gr.W,\n  left := gr.left \u226b f,\n  right := gr.right \u226b 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\u2081 : gr.left \u226b f \u226b s.\u03c0 = gr.right \u226b f \u226b s.\u03c0,\n      rw [\u2190 category.assoc, \u2190 category.assoc, s.condition],\n    obtain \u27e8l, hl\u27e9 := cofork.is_colimit.desc' gr.is_colimit (f \u226b cofork.\u03c0 s) l\u2081,\n    obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := pushout_cocone.is_colimit.desc' t _ _ hl.symm,\n    refine \u27e8p, hp\u2081, _\u27e9,\n    intros m w,\n    have z := w.trans hp\u2081.symm,\n    apply t.hom_ext,\n    apply (pushout_cocone.mk _ _ comm).coequalizer_ext,\n    { exact z },\n    { erw [\u2190 cancel_epi g, \u2190 reassoc_of comm, \u2190 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S} {k : R \u27f6 S}\n  [fr : regular_epi f] (comm : f \u226b h = g \u226b 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 \u27f6 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 \u27f6 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 \u27f6 X) \u226b u = regular_epi.right \u226b u,\n    { apply (cancel_mono z).1,\n      simp only [category.assoc, h, regular_epi.w_assoc] },\n    obtain \u27e8t, ht\u27e9 := regular_epi.desc' f u this,\n    exact arrow.has_lift.mk \u27e8t, ht, (cancel_epi f).1\n      (by simp only [\u2190category.assoc, ht, \u2190h, arrow.mk_hom, arrow.hom_mk'_right])\u27e9,\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": "import smt2\nimport .test_tactics\n\nlemma false_should_fail : false :=\nby must_fail z3\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/test/false.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.057493279607846996, "lm_q1q2_score": 0.026952310574160435}}
{"text": "inductive Foo: List \u03b1 \u2192 Type _\n  | mk (l): Foo l\n\ndef Foo.length: Foo l \u2192 Nat\n  | mk l => l.length\n\nvariable {\u03b1 : Type u} {\u0393 \u0393': List \u03b1} {p: Foo \u0393} {h: \u0393 = \u0393'}\n\ntheorem eq_rec_length : (h \u25b8 p).length = p.length := by\n  cases h; rfl\n\nexample : (h \u25b8 p).length = p.length :=\n  eq_rec_length\n\nexample : (h \u25b8 p).length = p.length := by\n  simp only [eq_rec_length]\n\nexample : (h \u25b8 p).length = p.length := by\n  rw [eq_rec_length]\n\nexample : (h \u25b8 p).length = p.length := by\n  subst h; rfl\n\nexample : (h \u25b8 p).length = p.length :=\n  match h with\n  | rfl => rfl\n\nexample : (h \u25b8 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": "import declaration_with_docstring\nimport fixed_prompts\nimport querying\n\n/-- A list of declarations from `mathlib` with docstrings similar to the given sentence. -/\nmeta def similar_prompts (s : string) (n : nat) : io (list declaration_with_docstring) := do\n  sim_stmts \u2190 get_similarity_prompts s n,\n  sim_prompts \u2190 sim_stmts.mmap $ \u03bb j, io.of_except (declaration_with_docstring.from_json j),\n  return sim_prompts.reverse\n\n/-- The declarations available in the context. -/\nmeta def context_prompts : io (list declaration_with_docstring) := \n  io.run_tactic declaration_with_docstring.module_decls\n\n/-- Build a prompt consisting of docstrings and theorem statements for querying Codex. -/\ndef build_prompt (decls : list declaration_with_docstring) : string :=\n  decls.foldr (\u03bb d prompt, d.to_full_string ++ \"\\n\\n\" ++ prompt) string.empty\n\n/-- Produce Lean translations of a statement by querying Codex with a custom prompt -/\nmeta def get_translations (stmt : string) \n    (use_fixed := tt)\n    (n_sim := 15) \n    (use_ctx := tt) \n    (temp := 6) \n    (n := 7) \n    (prompt_suffix := \"theorem\") : io (string \u00d7 list string) := do\n  let fix_prompts := if use_fixed then fixed_prompts else [],\n  sim_prompts \u2190 similar_prompts stmt n_sim,\n  ctx_prompts \u2190 if use_ctx then context_prompts else pure [],\n  let all_prompts := sim_prompts ++ ctx_prompts,\n  let main_prompt := (build_prompt all_prompts) ++ sformat!\"/-- {stmt} -/\\n\" ++ prompt_suffix,\n  \n  translations \u2190 completion_request.get_codex_completions {prompt := main_prompt, temperature := temp, n := n},\n  return $ (main_prompt, translations.map (\u03bb t, prompt_suffix ++ t))\n\n/-- Post-process the Codex completions by converting to `declaration_with_docstring` and typechecking. -/\nmeta def process_translations (stmt : string)\n    (use_fixed := tt) \n    (n_sim := 15) \n    (use_ctx := tt) \n    (temp := 6) \n    (n := 7) \n    (completion_prefix := \"theorem\") : tactic (list declaration_with_docstring \u00d7 list declaration_with_docstring) := do\n  (_, translations) \u2190 tactic.unsafe_run_io $ get_translations stmt use_fixed n_sim use_ctx temp n completion_prefix,\n  let translation_decls := translations.erase_dups.map $ \u03bb t, declaration_with_docstring.from_string t stmt,\n  (typecorrect_translations, failed_translations) \u2190 translation_decls.split_with $ \n      (functor.map option.is_some) \u2218 declaration_with_docstring.validate,\n  return (typecorrect_translations, failed_translations)", "meta": {"author": "0art0", "repo": "lean3-statement-translation-tool", "sha": "5bf00c4f3d7ddcae938e4d78349395061b866aab", "save_path": "github-repos/lean/0art0-lean3-statement-translation-tool", "path": "github-repos/lean/0art0-lean3-statement-translation-tool/lean3-statement-translation-tool-5bf00c4f3d7ddcae938e4d78349395061b866aab/src/prompting.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.055005285582501263, "lm_q1q2_score": 0.026858167603440737}}
{"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 \u2192 Type u) (F: Type \u2192 Type v) :=\n  \u2200 T, E T \u2192 F T\ndef psum (E: Type \u2192 Type u) (F: Type \u2192 Type v) :=\n  fun T => E T \u2295 F T\ninductive PVoid: Type -> Type u\n\ninfixr:40 \" ~> \" => pto\ninfixr:60 \" +' \" => psum\n\nclass Member (E: Type \u2192 Type u) (F: Type \u2192 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 \u2218 Member.inject T\n\ninstance {E F G} [Member E G]: Member E (F +' G) where\n  inject T := Sum.inr \u2218 Member.inject T\n\n-- Effects can now be put in context automatically by typeclass resolution\nexample (E: Type \u2192 Type u):\n  Member E E := inferInstance\nexample (E: Type \u2192 Type u) (F: Type \u2192 Type v):\n  Member E (E +' F) := inferInstance\nexample (E: Type \u2192 Type u) (F: Type \u2192 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 \u2192 Type where\n  | Read: Unit \u2192 StateE S\n  | Write: S \u2192 StateE Unit\n\ninductive WriteE {W: Type}: Type \u2192 Type where\n  | Tell: W \u2192 WriteE Unit\n\n\n/- The monadic domain; essentially finite Interaction Trees -/\n\nsection fitree\nuniverse u v\n\ninductive Fitree (E: Type \u2192 Type u) (R: Type) where\n  | Ret (r: R): Fitree E R\n  | Vis {T: Type} (e: E T) (k: T \u2192 Fitree E R): Fitree E R\n\n@[simp_itree]\ndef Fitree.ret {E R}: R \u2192 Fitree E R :=\n  Fitree.Ret\n\n@[simp_itree]\ndef Fitree.trigger {E: Type \u2192 Type u} {F: Type \u2192 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 \u2192 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 \u2983R\u2984, Fitree E R \u2192 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 \u2983R\u2984, Fitree E R \u2192 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 \u2192 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 \u2192 Prop :=\n  | Ret r: no_event_l (Ret r)\n  | Vis f k: (\u2200 t, no_event_l (k t)) \u2192 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 := (\u2190 SimpItreeExtension.getTheorems).toUnfold.fold\n    (init := #[]) (fun acc n => acc.push (toSimpLemma n))\n  evalTactic $ \u2190 `(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 {\u03b1 : Type u_1} : Inhabited (buffer \u03b1) := { default := nil }\n\ntheorem ext {\u03b1 : Type u_1} {b\u2081 : buffer \u03b1} {b\u2082 : buffer \u03b1} : to_list b\u2081 = to_list b\u2082 \u2192 b\u2081 = b\u2082 :=\n  sorry\n\nprotected instance decidable_eq (\u03b1 : Type u_1) [DecidableEq \u03b1] : DecidableEq (buffer \u03b1) :=\n  id\n    fun (_v : buffer \u03b1) =>\n      sigma.cases_on _v\n        fun (fst : \u2115) (snd : array fst \u03b1) (w : buffer \u03b1) =>\n          sigma.cases_on w\n            fun (w_fst : \u2115) (w_snd : array w_fst \u03b1) =>\n              decidable.by_cases\n                (fun (\u1fb0 : fst = w_fst) =>\n                  Eq._oldrec\n                    (fun (w_snd : array fst \u03b1) =>\n                      decidable.by_cases (fun (\u1fb0 : snd = w_snd) => Eq._oldrec (is_true sorry) \u1fb0)\n                        fun (\u1fb0 : \u00acsnd = w_snd) => isFalse sorry)\n                    \u1fb0 w_snd)\n                fun (\u1fb0 : \u00acfst = w_fst) => isFalse sorry\n\n@[simp] theorem to_list_append_list {\u03b1 : Type u_1} {xs : List \u03b1} {b : buffer \u03b1} :\n    to_list (append_list b xs) = to_list b ++ xs :=\n  sorry\n\n@[simp] theorem append_list_mk_buffer {\u03b1 : Type u_1} {xs : List \u03b1} :\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 (\u03b1 : Type u_1) : List \u03b1 \u2243 buffer \u03b1 :=\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) 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.Eqns\nimport Lean.Meta.Tactic.Split\nimport Lean.Meta.Tactic.Simp.Main\nimport Lean.Meta.Tactic.Apply\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Eqns\nimport Lean.Elab.PreDefinition.Structural.Basic\n\nnamespace Lean.Elab\nopen Meta\nopen Eqns\n\nnamespace Structural\n\nstructure EqnInfo extends EqnInfoCore where\n  recArgPos   : Nat\n  deriving Inhabited\n\nprivate partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do\n  trace[Elab.definition.structural.eqns] \"proving: {type}\"\n  withNewMCtxDepth do\n    let main \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let (_, mvarId) \u2190 intros main.mvarId!\n    unless (\u2190 tryURefl mvarId) do -- catch easy cases\n      go (\u2190 deltaLHS mvarId)\n    instantiateMVars main\nwhere\n  go (mvarId : MVarId) : MetaM Unit := do\n    trace[Elab.definition.structural.eqns] \"step\\n{MessageData.ofGoal mvarId}\"\n    if (\u2190 tryURefl mvarId) then\n      return ()\n    else if (\u2190 tryContradiction mvarId) then\n      return ()\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpIf? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 whnfReducibleLHS? mvarId then\n      go mvarId\n    else match (\u2190 simpTargetStar mvarId {}) with\n      | TacticResultCNM.closed => return ()\n      | TacticResultCNM.modified mvarId => go mvarId\n      | TacticResultCNM.noChange =>\n        if let some mvarId \u2190 deltaRHS? mvarId declName then\n          go mvarId\n        else if let some mvarIds \u2190 casesOnStuckLHS? mvarId then\n          mvarIds.forM go\n        else if let some mvarIds \u2190 splitTarget? mvarId then\n          mvarIds.forM go\n        else\n          throwError \"failed to generate equational theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n\ndef mkEqns (info : EqnInfo) : MetaM (Array Name) :=\n  withOptions (tactic.hygienic.set . false) do\n  let eqnTypes \u2190 withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do\n    let us := info.levelParams.map mkLevelParam\n    let target \u2190 mkEq (mkAppN (Lean.mkConst info.declName us) xs) body\n    let goal \u2190 mkFreshExprSyntheticOpaqueMVar target\n    mkEqnTypes #[info.declName] goal.mvarId!\n  let baseName := mkPrivateName (\u2190 getEnv) info.declName\n  let mut thmNames := #[]\n  for i in [: eqnTypes.size] do\n    let type := eqnTypes[i]\n    trace[Elab.definition.structural.eqns] \"{eqnTypes[i]}\"\n    let name := baseName ++ (`_eq).appendIndexAfter (i+1)\n    thmNames := thmNames.push name\n    let value \u2190 mkProof info.declName type\n    addDecl <| Declaration.thmDecl {\n      name, type, value\n      levelParams := info.levelParams\n    }\n  return thmNames\n\nbuiltin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo \u2190 mkMapDeclarationExtension `structEqInfo\n\ndef registerEqnsInfo (preDef : PreDefinition) (recArgPos : Nat) : CoreM Unit := do\n  modifyEnv fun env => eqnInfoExt.insert env preDef.declName { preDef with recArgPos }\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  let env \u2190 getEnv\n  if let some eqs := eqnsExt.getState env |>.map.find? declName then\n    return some eqs\n  else if let some info := eqnInfoExt.find? env declName then\n    let eqs \u2190 mkEqns info\n    modifyEnv fun env => eqnsExt.modifyState env fun s => { s with map := s.map.insert declName eqs }\n    return some eqs\n  else\n    return none\n\ndef getUnfoldFor? (declName : Name) : MetaM (Option Name) := do\n  let env \u2190 getEnv\n  Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (\u00b7.toEqnInfoCore)\n\nbuiltin_initialize\n  registerGetEqnsFn getEqnsFor?\n  registerGetUnfoldEqnFn getUnfoldFor?\n  registerTraceClass `Elab.definition.structural.eqns\n\nend Structural\nend Lean.Elab\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/src/Lean/Elab/PreDefinition/Structural/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.055823145454283137, "lm_q1q2_score": 0.02660417518187909}}
{"text": "import init.meta.tactic\nimport system.io\nimport assignment\n\nopen tactic\n\nmeta def in_import (env : environment) (n : name) (path : string) : bool :=\n(env.decl_olean n = path) && env.contains n && (n \u2209 [``quot, ``quot.mk, ``quot.lift, ``quot.ind])\n\nmeta def exact_list : list name \u2192 tactic unit \n| [] := failed \n| (H :: Hs) := do \n                  e \u2190 mk_const H,\n                  exact e <|> exact_list Hs\n\nmeta def check_solutions : tactic unit :=\ndo env <- get_env,\n   let decls := env.fold [] list.cons,\n   cwd \u2190 unsafe_run_io io.env.get_cwd,\n   let names := decls.map declaration.to_name,\n   let assignment_names := names.filter\n     (\u03bb x, in_import env x (cwd ++ \"/src/assignment.lean\") && not x.is_internal),\n   exact_list assignment_names\n\ntheorem check_problem1 : \u2200 (x : Type), x = x :=\nbegin\n  check_solutions,\nend\n\n#print \"Problem 1\"\n#print axioms check_problem1\n#print \"---\"\n\ntheorem check_problem2 : 0 = 1 :=\nbegin\n  check_solutions,\nend\n\n#print \"Problem 2\"\n#print axioms check_problem2\n#print \"---\"\n\ntheorem check_problem3 : \u2115 \u00d7 \u2115 \u00d7 \u2115 :=\nbegin\n  check_solutions,\nend\n\n#print \"Problem 3\"\n#print axioms check_problem3\n#print \"---\"\n\ntheorem check_problem4 : bool :=\nbegin\n  check_solutions,\nend\n\n#print \"Problem 4\"\n#print axioms check_problem4\n#print \"---\"\n\n", "meta": {"author": "mattrobball", "repo": "lean-autograding", "sha": "c004f4539968eaa5b3a42624308df9e9c9eeeca8", "save_path": "github-repos/lean/mattrobball-lean-autograding", "path": "github-repos/lean/mattrobball-lean-autograding/lean-autograding-c004f4539968eaa5b3a42624308df9e9c9eeeca8/.test/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.056652426502516375, "lm_q1q2_score": 0.02655812652001187}}
{"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 {\u03b1 : Type _} {xs : List \u03b1}\n\ninstance : Inhabited (Buffer \u03b1) :=\n  \u27e8nil\u27e9\n\n@[ext]\ntheorem ext : \u2200 {b\u2081 b\u2082 : Buffer \u03b1}, toList b\u2081 = toList b\u2082 \u2192 b\u2081 = b\u2082\n  | \u27e8n\u2081, a\u2081\u27e9, \u27e8n\u2082, a\u2082\u27e9, h => by\n    simp [to_list, to_array] at h\n    have e : n\u2081 = n\u2082 := by rw [\u2190 Array'.toList_length a\u2081, \u2190 Array'.toList_length a\u2082, h]\n    subst e\n    have h : HEq a\u2081 a\u2082.to_list.to_array := h \u25b8 a\u2081.to_list_to_array.symm\n    rw [eq_of_hEq (h.trans a\u2082.to_list_to_array)]\n#align buffer.ext Buffer.ext\n\ntheorem ext_iff {b\u2081 b\u2082 : Buffer \u03b1} : b\u2081 = b\u2082 \u2194 toList b\u2081 = toList b\u2082 :=\n  \u27e8fun h => h \u25b8 rfl, ext\u27e9\n#align buffer.ext_iff Buffer.ext_iff\n\ntheorem size_eq_zero_iff {b : Buffer \u03b1} : b.size = 0 \u2194 b = nil :=\n  by\n  rcases b with \u27e8_ | n, \u27e8a\u27e9\u27e9\n  \u00b7 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  \u00b7 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 \u03b1).size = 0 := by rw [size_eq_zero_iff]\n#align buffer.size_nil Buffer.size_nil\n\n@[simp]\ntheorem toList_nil : toList (@nil \u03b1) = [] :=\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 (\u03b1) [DecidableEq \u03b1] : DecidableEq (Buffer \u03b1) := by\n  run_tac\n    tactic.mk_dec_eq_instance\n\n@[simp]\ntheorem toList_appendList {b : Buffer \u03b1} : 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 \u03b1) : b.toList.toBuffer = b :=\n  by\n  cases b\n  rw [to_list, to_array, List.toBuffer, append_list_mk_buffer]\n  congr\n  \u00b7 simpa\n  \u00b7 apply Array'.toList_toArray\n#align buffer.to_buffer_to_list Buffer.toBuffer_toList\n\n@[simp]\ntheorem toList_toBuffer (l : List \u03b1) : l.toBuffer.toList = l :=\n  by\n  cases l\n  \u00b7 rfl\n  \u00b7 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 \u03b1) : 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 \u03b1) : b.appendList [] = b :=\n  rfl\n#align buffer.append_list_nil Buffer.appendList_nil\n\ntheorem toBuffer_cons (c : \u03b1) (l : List \u03b1) : (c :: l).toBuffer = [c].toBuffer.appendList l :=\n  by\n  induction' l with hd tl hl\n  \u00b7 simp\n  \u00b7 apply ext\n    simp [hl]\n#align buffer.to_buffer_cons Buffer.toBuffer_cons\n\n@[simp]\ntheorem size_pushBack (b : Buffer \u03b1) (a : \u03b1) : (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 \u03b1) (l : List \u03b1) : (b.appendList l).size = b.size + l.length :=\n  by\n  induction' l with hd tl hl generalizing b\n  \u00b7 simp\n  \u00b7 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 \u03b1) : l.toBuffer.size = l.length :=\n  by\n  induction' l with hd tl hl\n  \u00b7 simpa\n  \u00b7 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 \u03b1) : b.toList.length = b.size := by\n  rw [\u2190 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 : \u03b1) : [a].toBuffer.size = 1 :=\n  rfl\n#align buffer.size_singleton Buffer.size_singleton\n\ntheorem read_pushBack_left (b : Buffer \u03b1) (a : \u03b1) {i : \u2115} (h : i < b.size) :\n    (b.pushBack a).read\n        \u27e8i, by\n          convert Nat.lt_succ_of_lt h\n          simp\u27e9 =\n      b.read \u27e8i, h\u27e9 :=\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 \u03b1) (a : \u03b1) : (b.pushBack a).read \u27e8b.size, by simp\u27e9 = 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 \u03b1) (l : List \u03b1) {i : \u2115} (h : i < (b.appendList l).size)\n    (h' : i < b.size) : (b.appendList l).read \u27e8i, h\u27e9 = b.read \u27e8i, h'\u27e9 :=\n  by\n  induction' l with hd tl hl generalizing b\n  \u00b7 rfl\n  \u00b7 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 \u27e8i, h\u27e9 = read ((push_back b hd).appendList tl) \u27e8i, hb\u27e9 :=\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 \u03b1) (l : List \u03b1) {i : \u2115} (h : i < b.size) :\n    (b.appendList l).read \u27e8i, by simpa using Nat.lt_add_right _ _ _ h\u27e9 = b.read \u27e8i, h\u27e9 :=\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 \u03b1) (l : List \u03b1) {i : \u2115} (h : i < l.length) :\n    (b.appendList l).read \u27e8b.size + i, by simp [h]\u27e9 = l.nthLe i h :=\n  by\n  induction' l with hd tl hl generalizing b i\n  \u00b7 exact absurd i.zero_le (not_le_of_lt h)\n  \u00b7 convert_to((b.push_back hd).appendList tl).read _ = _\n    cases i\n    \u00b7 convert read_append_list_left _ _ _ <;> simp\n    \u00b7 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 \u03b1) {i : \u2115} (h : i < l.toBuffer.size) (h' : i < l.length) :\n    l.toBuffer.read \u27e8i, h\u27e9 = l.nthLe i h' :=\n  by\n  cases' l with hd tl\n  \u00b7 simpa using h'\n  \u00b7 have hi : i < ([hd].toBuffer.appendList tl).size := by simpa [add_comm] using h\n    convert_to([hd].toBuffer.appendList tl).read \u27e8i, hi\u27e9 = _\n    cases i\n    \u00b7 convert read_append_list_left _ _ _\n      simp\n    \u00b7 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 \u03b1) (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  \u00b7 simp\n  \u00b7 simpa using i.property\n#align buffer.read_to_buffer Buffer.read_toBuffer\n\ntheorem nthLe_to_list' (b : Buffer \u03b1) {i : \u2115} (h h') : b.toList.nthLe i h = b.read \u27e8i, h'\u27e9 :=\n  by\n  have : b.to_list.to_buffer.read \u27e8i, by simpa using h'\u27e9 = b.read \u27e8i, h'\u27e9 := by\n    congr 1 <;> simp [Fin.heq_ext_iff]\n  simp [\u2190 this]\n#align buffer.nth_le_to_list' Buffer.nthLe_to_list'\n\ntheorem nthLe_toList (b : Buffer \u03b1) {i : \u2115} (h) :\n    b.toList.nthLe i h = b.read \u27e8i, by simpa using h\u27e9 :=\n  nthLe_to_list' _ _ _\n#align buffer.nth_le_to_list Buffer.nthLe_toList\n\ntheorem read_eq_nthLe_toList (b : Buffer \u03b1) (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 : \u03b1) : [c].toBuffer.read \u27e80, by simp\u27e9 = 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 (\u03b1 : Type _) : List \u03b1 \u2243 Buffer \u03b1 := 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 \u03b1) (i : \u2115) : tactic \u03b1 :=\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": "import Lean\nopen Lean Elab Tactic\n\nmacro \"obviously1\" : tactic => `(tactic| exact sorryAx _)\n\ntheorem result1 : False := by obviously1\n\nelab \"obviously2\" : tactic =>\n  liftMetaTactic1 fun mvarId => mvarId.admit *> pure none\n\ntheorem result2 : False := by obviously2\n\ndef x : Bool := 0\n\ntheorem result3 : False := by obviously2\n\ntheorem result4 : False := by -- Does not generate a `sorry` warning because there is an error\n  let x : Bool := 0\n  obviously2\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/1163.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.05834583938364053, "lm_q1q2_score": 0.026445942983037807}}
{"text": "/-\nCopyright (c) 2022-2023 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport AesopTest.RuleSets0\n\nset_option aesop.check.all true\n\n@[aesop safe (rule_sets [test_A])]\ninductive A : Prop where\n| intro\n\n@[aesop safe (rule_sets [test_B])]\ninductive B : Prop where\n| intro\n\n@[aesop safe]\ninductive C : Prop where\n| intro\n\ninductive D : Prop where\n| intro\n\nexample : A := by\n  fail_if_success aesop (options := { terminal := true })\n  aesop (rule_sets [test_A])\n\nexample : B := by\n  aesop (rule_sets [test_A, test_B])\n\nexample : C := by\n  fail_if_success aesop (rule_sets [-default]) (options := { terminal := true })\n  aesop\n\nattribute [aesop safe (rule_sets [test_C])] C\n\n-- Removing the attribute removes all rules associated with C from all rule\n-- sets.\nattribute [-aesop] C\n\nexample : C := by\n  fail_if_success aesop (rule_sets [test_C]) (options := { terminal := true })\n  aesop (add safe C)\n\n@[aesop norm simp]\ntheorem ad : D \u2194 A :=\n  \u27e8\u03bb _ => A.intro, \u03bb _ => D.intro\u27e9\n\nexample : D := by\n  aesop (rule_sets [test_A])\n\nattribute [-aesop] ad\n\nexample : D := by\n  fail_if_success aesop (rule_sets [test_A]) (options := { terminal := true })\n  aesop (add norm ad) (rule_sets [test_A])\n\n-- Rules can also be local.\n\ninductive E : Prop where\n  | intro\n\nsection\n\nattribute [local aesop safe] E\n\nexample : E := by\n  aesop\n\nend\n\nexample : E := by\n  fail_if_success aesop (options := { terminal := true })\n  constructor\n\n-- Rules can also be scoped.\n\nnamespace EScope\n\nattribute [scoped aesop safe] E\n\nexample : E := by\n  aesop\n\nend EScope\n\nexample : E := by\n  fail_if_success aesop (options := { terminal := true })\n  open EScope in aesop\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/AesopTest/RuleSets1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790695, "lm_q2_score": 0.055005293328081274, "lm_q1q2_score": 0.026428870623913848}}
{"text": "/-\nCopyright (c) 2021 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Mario Carneiro\n-/\nimport Std.Tactic.RCases\nimport Std.Lean.Command\n\nnamespace Std.Tactic.Ext\nopen Lean Meta\n\n/-- `declare_ext_theorems_for A` declares the extensionality theorems for the structure `A`. -/\nsyntax \"declare_ext_theorems_for\" ident prio ? : command\n\n/-- Information about an extensionality theorem, stored in the environment extension. -/\nstructure ExtTheorem where\n  /-- Declaration name of the extensionality theorem. -/\n  declName : Name\n  /-- Priority of the extensionality theorem. -/\n  priority : Nat\n  /-- Key in the discrimination tree. -/\n  keys : Array (DiscrTree.Key true)\n  deriving Inhabited, Repr, BEq, Hashable\n\n/-- The environment extension to track `@[ext]` lemmas. -/\ninitialize extExtension :\n    SimpleScopedEnvExtension ExtTheorem (DiscrTree ExtTheorem true) \u2190\n  registerSimpleScopedEnvExtension {\n    addEntry := fun dt thm => dt.insertCore thm.keys thm\n    initial := {}\n  }\n\n/-- Get the list of `@[ext]` lemmas corresponding to the key `ty`. -/\n@[inline] def getExtLemmas (ty : Expr) : MetaM (Array ExtTheorem) :=\n  return (\u2190 (extExtension.getState (\u2190 getEnv)).getMatch ty)\n    |>.insertionSort fun a b => a.priority > b.priority\n\n/-- Registers an extensionality lemma.\n\nWhen `@[ext]` is applied to a structure,\nit generates `.ext` and `.ext_iff` theorems\nand registers them for the `ext` tactic.\n\nWhen `@[ext]` is applied to a theorem,\nthe theorem is registered for the `ext` tactic.\n\nYou can use `@[ext 9000]` to specify a priority for the attribute. -/\nsyntax (name := ext) \"ext\" prio ? : attr\n\ninitialize registerBuiltinAttribute {\n  name := `ext\n  descr := \"Marks a lemma as extensionality lemma\"\n  add := fun declName stx kind => do\n    let `(attr| ext $[$prio]?) := stx | throwError \"unexpected @[ext] attribute {stx}\"\n    if isStructure (\u2190 getEnv) declName then\n      liftCommandElabM <| Elab.Command.elabCommand <|\n        \u2190 `(declare_ext_theorems_for $(mkCIdentFrom stx declName) $[$prio]?)\n    else MetaM.run' do\n      let declTy := (\u2190 getConstInfo declName).type\n      let (_, _, declTy) \u2190 withDefault <| forallMetaTelescopeReducing declTy\n      let failNotEq := throwError\n        \"@[ext] attribute only applies to structures or lemmas proving x = y, got {declTy}\"\n      let some (ty, lhs, rhs) := declTy.eq? | failNotEq\n      unless lhs.isMVar && rhs.isMVar do failNotEq\n      let keys \u2190 withReducible <| DiscrTree.mkPath ty\n      let priority \u2190 liftCommandElabM do Elab.liftMacroM do\n        evalPrio (prio.getD (\u2190 `(prio| default)))\n      extExtension.add {declName, keys, priority} kind\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/Ext/Attr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.06853749065376102, "lm_q1q2_score": 0.026380912505086705}}
{"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 \u2190 i_to_expr e <|> do\n  { ty \u2190 target,\n    -- for positional error messages, we don't care about the result\n    e \u2190 i_to_expr_strict ``(%%e : %%ty),\n    pty \u2190 pp ty, ptgt \u2190 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 \u2190 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 {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) : plift \u03b1 \u2192 plift \u03b2 :=\n  sorry\n\n/-- Embedding of pure values. -/\n@[simp] protected def pure {\u03b1 : Sort u} : \u03b1 \u2192 plift \u03b1 :=\n  up\n\n/-- Applicative sequencing. -/\n@[simp] protected def seq {\u03b1 : Sort u} {\u03b2 : Sort v} : plift (\u03b1 \u2192 \u03b2) \u2192 plift \u03b1 \u2192 plift \u03b2 :=\n  sorry\n\n/-- Monadic bind. -/\n@[simp] protected def bind {\u03b1 : Sort u} {\u03b2 : Sort v} : plift \u03b1 \u2192 (\u03b1 \u2192 plift \u03b2) \u2192 plift \u03b2 :=\n  sorry\n\nprotected instance monad : Monad plift :=\n  { toApplicative :=\n      { toFunctor := { map := plift.map, mapConst := fun (\u03b1 \u03b2 : Type u_1) => plift.map \u2218 function.const \u03b2 },\n        toPure := { pure := plift.pure }, toSeq := { seq := plift.seq },\n        toSeqLeft :=\n          { seqLeft := fun (\u03b1 \u03b2 : Type u_1) (a : plift \u03b1) (b : plift \u03b2) => plift.seq (plift.map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : plift \u03b1) (b : plift \u03b2) => plift.seq (plift.map (function.const \u03b1 id) a) b } },\n    toBind := { bind := plift.bind } }\n\nprotected instance is_lawful_functor : is_lawful_functor plift :=\n  is_lawful_functor.mk (fun (\u03b1 : Type u_1) (_x : plift \u03b1) => sorry)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) (_x : plift \u03b1) => sorry\n\nprotected instance is_lawful_applicative : is_lawful_applicative plift :=\n  is_lawful_applicative.mk (fun (\u03b1 \u03b2 : Type u_1) (g : \u03b1 \u2192 \u03b2) (_x : plift \u03b1) => sorry)\n    (fun (\u03b1 \u03b2 : Type u_1) (g : \u03b1 \u2192 \u03b2) (x : \u03b1) => rfl) (fun (\u03b1 \u03b2 : Type u_1) (_x : plift (\u03b1 \u2192 \u03b2)) => sorry)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (_x : plift \u03b1) => sorry\n\nprotected instance is_lawful_monad : is_lawful_monad plift :=\n  is_lawful_monad.mk (fun (\u03b1 \u03b2 : Type u_1) (x : \u03b1) (f : \u03b1 \u2192 plift \u03b2) => rfl)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (_x : plift \u03b1) => sorry\n\n@[simp] theorem rec.constant {\u03b1 : Sort u} {\u03b2 : Type v} (b : \u03b2) : (plift.rec fun (_x : \u03b1) => b) = fun (_x : plift \u03b1) => b :=\n  funext fun (x : plift \u03b1) => cases_on x fun (a : \u03b1) => Eq.refl (plift.rec (fun (_x : \u03b1) => b) (up a))\n\nend plift\n\n\nnamespace ulift\n\n\n/-- Functorial action. -/\n@[simp] protected def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) : ulift \u03b1 \u2192 ulift \u03b2 :=\n  sorry\n\n/-- Embedding of pure values. -/\n@[simp] protected def pure {\u03b1 : Type u} : \u03b1 \u2192 ulift \u03b1 :=\n  up\n\n/-- Applicative sequencing. -/\n@[simp] protected def seq {\u03b1 : Type u} {\u03b2 : Type v} : ulift (\u03b1 \u2192 \u03b2) \u2192 ulift \u03b1 \u2192 ulift \u03b2 :=\n  sorry\n\n/-- Monadic bind. -/\n@[simp] protected def bind {\u03b1 : Type u} {\u03b2 : Type v} : ulift \u03b1 \u2192 (\u03b1 \u2192 ulift \u03b2) \u2192 ulift \u03b2 :=\n  sorry\n\n-- The `up \u2218 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 (\u03b1 \u03b2 : Type u_1) => ulift.map \u2218 function.const \u03b2 },\n        toPure := { pure := ulift.pure }, toSeq := { seq := ulift.seq },\n        toSeqLeft :=\n          { seqLeft := fun (\u03b1 \u03b2 : Type u_1) (a : ulift \u03b1) (b : ulift \u03b2) => ulift.seq (ulift.map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : ulift \u03b1) (b : ulift \u03b2) => ulift.seq (ulift.map (function.const \u03b1 id) a) b } },\n    toBind := { bind := ulift.bind } }\n\nprotected instance is_lawful_functor : is_lawful_functor ulift :=\n  is_lawful_functor.mk (fun (\u03b1 : Type u_1) (_x : ulift \u03b1) => sorry)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) (_x : ulift \u03b1) => sorry\n\nprotected instance is_lawful_applicative : is_lawful_applicative ulift :=\n  is_lawful_applicative.mk (fun (\u03b1 \u03b2 : Type u_1) (g : \u03b1 \u2192 \u03b2) (_x : ulift \u03b1) => sorry)\n    (fun (\u03b1 \u03b2 : Type u_1) (g : \u03b1 \u2192 \u03b2) (x : \u03b1) => rfl) (fun (\u03b1 \u03b2 : Type u_1) (_x : ulift (\u03b1 \u2192 \u03b2)) => sorry)\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (_x : ulift \u03b1) => sorry\n\nprotected instance is_lawful_monad : is_lawful_monad ulift :=\n  is_lawful_monad.mk\n    (fun (\u03b1 \u03b2 : Type u_1) (x : \u03b1) (f : \u03b1 \u2192 ulift \u03b2) =>\n      id (cases_on (f x) fun (down : \u03b2) => Eq.refl (up (down (up down)))))\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (_x : ulift \u03b1) => sorry\n\n@[simp] theorem rec.constant {\u03b1 : Type u} {\u03b2 : Sort v} (b : \u03b2) : (ulift.rec fun (_x : \u03b1) => b) = fun (_x : ulift \u03b1) => b :=\n  funext fun (x : ulift \u03b1) => cases_on x fun (a : \u03b1) => Eq.refl (ulift.rec (fun (_x : \u03b1) => 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 \u03b1` is the type of \"partial values\" of type `\u03b1`. It\n  is similar to `option \u03b1` except the domain condition can be an\n  arbitrary proposition, not necessarily decidable. -/\nstructure roption (\u03b1 : Type u) \nwhere\n  dom : Prop\n  get : dom \u2192 \u03b1\n\nnamespace roption\n\n\n/-- Convert an `roption \u03b1` with a decidable domain to an option -/\ndef to_option {\u03b1 : Type u_1} (o : roption \u03b1) [Decidable (dom o)] : Option \u03b1 :=\n  dite (dom o) (fun (h : dom o) => some (get o h)) fun (h : \u00acdom o) => none\n\n/-- `roption` extensionality -/\ntheorem ext' {\u03b1 : Type u_1} {o : roption \u03b1} {p : roption \u03b1} (H1 : dom o \u2194 dom p) (H2 : \u2200 (h\u2081 : dom o) (h\u2082 : dom p), get o h\u2081 = get p h\u2082) : o = p := sorry\n\n/-- `roption` eta expansion -/\n@[simp] theorem eta {\u03b1 : Type u_1} (o : roption \u03b1) : (mk (dom o) fun (h : dom o) => get o h) = o := sorry\n\n/-- `a \u2208 o` means that `o` is defined and equal to `a` -/\nprotected def mem {\u03b1 : Type u_1} (a : \u03b1) (o : roption \u03b1) :=\n  \u2203 (h : dom o), get o h = a\n\nprotected instance has_mem {\u03b1 : Type u_1} : has_mem \u03b1 (roption \u03b1) :=\n  has_mem.mk roption.mem\n\ntheorem mem_eq {\u03b1 : Type u_1} (a : \u03b1) (o : roption \u03b1) : a \u2208 o = \u2203 (h : dom o), get o h = a :=\n  rfl\n\ntheorem dom_iff_mem {\u03b1 : Type u_1} {o : roption \u03b1} : dom o \u2194 \u2203 (y : \u03b1), y \u2208 o := sorry\n\ntheorem get_mem {\u03b1 : Type u_1} {o : roption \u03b1} (h : dom o) : get o h \u2208 o :=\n  Exists.intro h rfl\n\n/-- `roption` extensionality -/\ntheorem ext {\u03b1 : Type u_1} {o : roption \u03b1} {p : roption \u03b1} (H : \u2200 (a : \u03b1), a \u2208 o \u2194 a \u2208 p) : o = p := sorry\n\n/-- The `none` value in `roption` has a `false` domain and an empty function. -/\ndef none {\u03b1 : Type u_1} : roption \u03b1 :=\n  mk False False._oldrec\n\nprotected instance inhabited {\u03b1 : Type u_1} : Inhabited (roption \u03b1) :=\n  { default := none }\n\n@[simp] theorem not_mem_none {\u03b1 : Type u_1} (a : \u03b1) : \u00aca \u2208 none :=\n  fun (h : a \u2208 none) => Exists.fst h\n\n/-- The `some a` value in `roption` has a `true` domain and the\n  function returns `a`. -/\ndef some {\u03b1 : Type u_1} (a : \u03b1) : roption \u03b1 :=\n  mk True fun (_x : True) => a\n\ntheorem mem_unique {\u03b1 : Type u_1} : relator.left_unique has_mem.mem := sorry\n\ntheorem get_eq_of_mem {\u03b1 : Type u_1} {o : roption \u03b1} {a : \u03b1} (h : a \u2208 o) (h' : dom o) : get o h' = a :=\n  mem_unique (Exists.intro h' rfl) h\n\n@[simp] theorem get_some {\u03b1 : Type u_1} {a : \u03b1} (ha : dom (some a)) : get (some a) ha = a :=\n  rfl\n\ntheorem mem_some {\u03b1 : Type u_1} (a : \u03b1) : a \u2208 some a :=\n  Exists.intro trivial rfl\n\n@[simp] theorem mem_some_iff {\u03b1 : Type u_1} {a : \u03b1} {b : \u03b1} : b \u2208 some a \u2194 b = a := sorry\n\ntheorem eq_some_iff {\u03b1 : Type u_1} {a : \u03b1} {o : roption \u03b1} : o = some a \u2194 a \u2208 o := sorry\n\ntheorem eq_none_iff {\u03b1 : Type u_1} {o : roption \u03b1} : o = none \u2194 \u2200 (a : \u03b1), \u00aca \u2208 o := sorry\n\ntheorem eq_none_iff' {\u03b1 : Type u_1} {o : roption \u03b1} : o = none \u2194 \u00acdom o :=\n  { mp := fun (e : o = none) => Eq.symm e \u25b8 id,\n    mpr := fun (h : \u00acdom o) => iff.mpr eq_none_iff fun (a : \u03b1) (h' : a \u2208 o) => h (Exists.fst h') }\n\ntheorem some_ne_none {\u03b1 : Type u_1} (x : \u03b1) : some x \u2260 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 {\u03b1 : Type u_1} {o : roption \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), o = some x := sorry\n\ntheorem eq_none_or_eq_some {\u03b1 : Type u_1} (o : roption \u03b1) : o = none \u2228 \u2203 (x : \u03b1), o = some x := sorry\n\n@[simp] theorem some_inj {\u03b1 : Type u_1} {a : \u03b1} {b : \u03b1} : some a = some b \u2194 a = b :=\n  function.injective.eq_iff fun (a b : \u03b1) (h : some a = some b) => congr_fun (eq_of_heq (and.right (mk.inj h))) trivial\n\n@[simp] theorem some_get {\u03b1 : Type u_1} {a : roption \u03b1} (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 {\u03b1 : Type u_1} {a : roption \u03b1} {ha : dom a} {b : \u03b1} : get a ha = b \u2194 a = some b := sorry\n\nprotected instance none_decidable {\u03b1 : Type u_1} : Decidable (dom none) :=\n  decidable.false\n\nprotected instance some_decidable {\u03b1 : Type u_1} (a : \u03b1) : Decidable (dom (some a)) :=\n  decidable.true\n\ndef get_or_else {\u03b1 : Type u_1} (a : roption \u03b1) [Decidable (dom a)] (d : \u03b1) : \u03b1 :=\n  dite (dom a) (fun (ha : dom a) => get a ha) fun (ha : \u00acdom a) => d\n\n@[simp] theorem get_or_else_none {\u03b1 : Type u_1} (d : \u03b1) : get_or_else none d = d :=\n  dif_neg id\n\n@[simp] theorem get_or_else_some {\u03b1 : Type u_1} (a : \u03b1) (d : \u03b1) : get_or_else (some a) d = a :=\n  dif_pos trivial\n\n@[simp] theorem mem_to_option {\u03b1 : Type u_1} {o : roption \u03b1} [Decidable (dom o)] {a : \u03b1} : a \u2208 to_option o \u2194 a \u2208 o := sorry\n\n/-- Convert an `option \u03b1` into an `roption \u03b1` -/\ndef of_option {\u03b1 : Type u_1} : Option \u03b1 \u2192 roption \u03b1 :=\n  sorry\n\n@[simp] theorem mem_of_option {\u03b1 : Type u_1} {a : \u03b1} {o : Option \u03b1} : a \u2208 of_option o \u2194 a \u2208 o := sorry\n\n@[simp] theorem of_option_dom {\u03b1 : Type u_1} (o : Option \u03b1) : dom (of_option o) \u2194 \u21a5(option.is_some o) := sorry\n\ntheorem of_option_eq_get {\u03b1 : Type u_1} (o : Option \u03b1) : of_option o = mk (\u21a5(option.is_some o)) option.get := sorry\n\nprotected instance has_coe {\u03b1 : Type u_1} : has_coe (Option \u03b1) (roption \u03b1) :=\n  has_coe.mk of_option\n\n@[simp] theorem mem_coe {\u03b1 : Type u_1} {a : \u03b1} {o : Option \u03b1} : a \u2208 \u2191o \u2194 a \u2208 o :=\n  mem_of_option\n\n@[simp] theorem coe_none {\u03b1 : Type u_1} : \u2191none = none :=\n  rfl\n\n@[simp] theorem coe_some {\u03b1 : Type u_1} (a : \u03b1) : \u2191(some a) = some a :=\n  rfl\n\nprotected theorem induction_on {\u03b1 : Type u_1} {P : roption \u03b1 \u2192 Prop} (a : roption \u03b1) (hnone : P none) (hsome : \u2200 (a : \u03b1), P (some a)) : P a :=\n  or.elim (classical.em (dom a)) (fun (h : dom a) => some_get h \u25b8 hsome (get a h))\n    fun (h : \u00acdom a) => Eq.symm (iff.mpr eq_none_iff' h) \u25b8 hnone\n\nprotected instance of_option_decidable {\u03b1 : Type u_1} (o : Option \u03b1) : Decidable (dom (of_option o)) :=\n  sorry\n\n@[simp] theorem to_of_option {\u03b1 : Type u_1} (o : Option \u03b1) : to_option (of_option o) = o :=\n  option.cases_on o (Eq.refl (to_option (of_option none))) fun (o : \u03b1) => Eq.refl (to_option (of_option (some o)))\n\n@[simp] theorem of_to_option {\u03b1 : Type u_1} (o : roption \u03b1) [Decidable (dom o)] : of_option (to_option o) = o :=\n  ext fun (a : \u03b1) => iff.trans mem_of_option mem_to_option\n\ndef equiv_option {\u03b1 : Type u_1} : roption \u03b1 \u2243 Option \u03b1 :=\n  equiv.mk (fun (o : roption \u03b1) => to_option o) of_option sorry sorry\n\nprotected instance order_bot {\u03b1 : Type u_1} : order_bot (roption \u03b1) :=\n  order_bot.mk none (fun (x y : roption \u03b1) => \u2200 (i : \u03b1), i \u2208 x \u2192 i \u2208 y)\n    (partial_order.lt._default fun (x y : roption \u03b1) => \u2200 (i : \u03b1), i \u2208 x \u2192 i \u2208 y) sorry sorry sorry sorry\n\nprotected instance preorder {\u03b1 : Type u_1} : preorder (roption \u03b1) :=\n  partial_order.to_preorder (roption \u03b1)\n\ntheorem le_total_of_le_of_le {\u03b1 : Type u_1} {x : roption \u03b1} {y : roption \u03b1} (z : roption \u03b1) (hx : x \u2264 z) (hy : y \u2264 z) : x \u2264 y \u2228 y \u2264 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 {\u03b1 : Type u_1} (p : Prop) (f : p \u2192 roption \u03b1) : roption \u03b1 :=\n  mk (\u2203 (h : p), dom (f h)) fun (ha : \u2203 (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : roption \u03b1) (g : \u03b1 \u2192 roption \u03b2) : roption \u03b2 :=\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (o : roption \u03b1) : roption \u03b2 :=\n  mk (dom o) (f \u2218 get o)\n\ntheorem mem_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) {o : roption \u03b1} {a : \u03b1} : a \u2208 o \u2192 f a \u2208 map f o := sorry\n\n@[simp] theorem mem_map_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) {o : roption \u03b1} {b : \u03b2} : b \u2208 map f o \u2194 \u2203 (a : \u03b1), \u2203 (H : a \u2208 o), f a = b := sorry\n\n@[simp] theorem map_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : map f none = none := sorry\n\n@[simp] theorem map_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : map f (some a) = some (f a) :=\n  iff.mpr eq_some_iff (mem_map f (mem_some a))\n\ntheorem mem_assert {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} {a : \u03b1} (h : p) : a \u2208 f h \u2192 a \u2208 assert p f := sorry\n\n@[simp] theorem mem_assert_iff {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} {a : \u03b1} : a \u2208 assert p f \u2194 \u2203 (h : p), a \u2208 f h := sorry\n\ntheorem assert_pos {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} (h : p) : assert p f = f h := sorry\n\ntheorem assert_neg {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} (h : \u00acp) : assert p f = none := sorry\n\ntheorem mem_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} {a : \u03b1} {b : \u03b2} : a \u2208 f \u2192 b \u2208 g a \u2192 b \u2208 roption.bind f g := sorry\n\n@[simp] theorem mem_bind_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} {b : \u03b2} : b \u2208 roption.bind f g \u2194 \u2203 (a : \u03b1), \u2203 (H : a \u2208 f), b \u2208 g a := sorry\n\n@[simp] theorem bind_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 roption \u03b2) : roption.bind none f = none := sorry\n\n@[simp] theorem bind_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} (a : \u03b1) (f : \u03b1 \u2192 roption \u03b2) : roption.bind (some a) f = f a := sorry\n\ntheorem bind_some_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (x : roption \u03b1) : roption.bind x (some \u2218 f) = map f x := sorry\n\ntheorem bind_assoc {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : roption \u03b1) (g : \u03b1 \u2192 roption \u03b2) (k : \u03b2 \u2192 roption \u03b3) : roption.bind (roption.bind f g) k = roption.bind f fun (x : \u03b1) => roption.bind (g x) k := sorry\n\n@[simp] theorem bind_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (x : roption \u03b1) (g : \u03b2 \u2192 roption \u03b3) : roption.bind (map f x) g = roption.bind x fun (y : \u03b1) => g (f y) := sorry\n\n@[simp] theorem map_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 roption \u03b2) (x : roption \u03b1) (g : \u03b2 \u2192 \u03b3) : map g (roption.bind x f) = roption.bind x fun (y : \u03b1) => map g (f y) := sorry\n\ntheorem map_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (g : \u03b2 \u2192 \u03b3) (f : \u03b1 \u2192 \u03b2) (o : roption \u03b1) : map g (map f o) = map (g \u2218 f) o := sorry\n\nprotected instance monad : Monad roption :=\n  { toApplicative :=\n      { toFunctor := { map := map, mapConst := fun (\u03b1 \u03b2 : Type u_1) => map \u2218 function.const \u03b2 },\n        toPure := { pure := some },\n        toSeq :=\n          { seq :=\n              fun (\u03b1 \u03b2 : Type u_1) (f : roption (\u03b1 \u2192 \u03b2)) (x : roption \u03b1) => roption.bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : roption \u03b1) (b : roption \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : roption (\u03b1 \u2192 \u03b2)) (x : roption \u03b1) =>\n                    roption.bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x)\n                  \u03b2 \u03b1 (map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : roption \u03b1) (b : roption \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : roption (\u03b1 \u2192 \u03b2)) (x : roption \u03b1) =>\n                    roption.bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x)\n                  \u03b2 \u03b2 (map (function.const \u03b1 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' {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1} (H : \u2200 (x : \u03b1), f x = x) (o : roption \u03b1) : 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 {\u03b1 : Type u_1} (x : roption \u03b1) : roption.bind x some = x := sorry\n\n@[simp] theorem pure_eq_some {\u03b1 : Type u_1} (a : \u03b1) : pure a = some a :=\n  rfl\n\n@[simp] theorem ret_eq_some {\u03b1 : Type u_1} (a : \u03b1) : return a = some a :=\n  rfl\n\n@[simp] theorem map_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 \u03b2) (o : roption \u03b1) : f <$> o = map f o :=\n  rfl\n\n@[simp] theorem bind_eq_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : roption \u03b1) (g : \u03b1 \u2192 roption \u03b2) : f >>= g = roption.bind f g :=\n  rfl\n\ntheorem bind_le {\u03b2 : Type u_2} {\u03b1 : Type u_2} (x : roption \u03b1) (f : \u03b1 \u2192 roption \u03b2) (y : roption \u03b2) : x >>= f \u2264 y \u2194 \u2200 (a : \u03b1), a \u2208 x \u2192 f a \u2264 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 {\u03b1 : Type u_1} (p : Prop) (o : roption \u03b1) : (p \u2192 dom o) \u2192 roption \u03b1 :=\n  sorry\n\n@[simp] theorem mem_restrict {\u03b1 : Type u_1} (p : Prop) (o : roption \u03b1) (h : p \u2192 dom o) (a : \u03b1) : a \u2208 restrict p o h \u2194 p \u2227 a \u2208 o := sorry\n\n/-- `unwrap o` gets the value at `o`, ignoring the condition.\n  (This function is unsound.) -/\ntheorem assert_defined {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} (h : p) : dom (f h) \u2192 dom (assert p f) :=\n  exists.intro\n\ntheorem bind_defined {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} (h : dom f) : dom (g (get f h)) \u2192 dom (roption.bind f g) :=\n  assert_defined\n\n@[simp] theorem bind_dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} : dom (roption.bind f g) \u2194 \u2203 (h : dom f), dom (g (get f h)) :=\n  iff.rfl\n\nend roption\n\n\n/-- `pfun \u03b1 \u03b2`, or `\u03b1 \u2192. \u03b2`, is the type of partial functions from\n  `\u03b1` to `\u03b2`. It is defined as `\u03b1 \u2192 roption \u03b2`. -/\ndef pfun (\u03b1 : Type u_1) (\u03b2 : Type u_2) :=\n  \u03b1 \u2192 roption \u03b2\n\ninfixr:25 \" \u2192. \" => Mathlib.pfun\n\nnamespace pfun\n\n\nprotected instance inhabited {\u03b1 : Type u_1} {\u03b2 : Type u_2} : Inhabited (\u03b1 \u2192. \u03b2) :=\n  { default := fun (a : \u03b1) => roption.none }\n\n/-- The domain of a partial function -/\ndef dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : set \u03b1 :=\n  set_of fun (a : \u03b1) => roption.dom (f a)\n\ntheorem mem_dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) : x \u2208 dom f \u2194 \u2203 (y : \u03b2), y \u2208 f x := sorry\n\ntheorem dom_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : dom f = set_of fun (x : \u03b1) => \u2203 (y : \u03b2), y \u2208 f x :=\n  set.ext (mem_dom f)\n\n/-- Evaluate a partial function -/\ndef fn {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) (h : dom f x) : \u03b2 :=\n  roption.get (f x) h\n\n/-- Evaluate a partial function to return an `option` -/\ndef eval_opt {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) [D : decidable_pred (dom f)] (x : \u03b1) : Option \u03b2 :=\n  roption.to_option (f x)\n\n/-- Partial function extensionality -/\ntheorem ext' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {g : \u03b1 \u2192. \u03b2} (H1 : \u2200 (a : \u03b1), a \u2208 dom f \u2194 a \u2208 dom g) (H2 : \u2200 (a : \u03b1) (p : dom f a) (q : dom g a), fn f a p = fn g a q) : f = g :=\n  funext fun (a : \u03b1) => roption.ext' (H1 a) (H2 a)\n\ntheorem ext {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {g : \u03b1 \u2192. \u03b2} (H : \u2200 (a : \u03b1) (b : \u03b2), b \u2208 f a \u2194 b \u2208 g a) : f = g :=\n  funext fun (a : \u03b1) => roption.ext (H a)\n\n/-- Turn a partial function into a function out of a subtype -/\ndef as_subtype {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : \u21a5(dom f)) : \u03b2 :=\n  fn f \u2191s sorry\n\n/-- The set of partial functions `\u03b1 \u2192. \u03b2` is equivalent to\nthe set of pairs `(p : \u03b1 \u2192 Prop, f : subtype p \u2192 \u03b2)`. -/\ndef equiv_subtype {\u03b1 : Type u_1} {\u03b2 : Type u_2} : (\u03b1 \u2192. \u03b2) \u2243 sigma fun (p : \u03b1 \u2192 Prop) => Subtype p \u2192 \u03b2 :=\n  equiv.mk (fun (f : \u03b1 \u2192. \u03b2) => sigma.mk (fun (a : \u03b1) => roption.dom (f a)) (as_subtype f))\n    (fun (f : sigma fun (p : \u03b1 \u2192 Prop) => Subtype p \u2192 \u03b2) (x : \u03b1) =>\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {x : \u03b1} {y : \u03b2} (fxy : y \u2208 f x) (domx : x \u2208 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192. \u03b2 :=\n  fun (a : \u03b1) => roption.some (f a)\n\nprotected instance has_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} : has_coe (\u03b1 \u2192 \u03b2) (\u03b1 \u2192. \u03b2) :=\n  has_coe.mk pfun.lift\n\n@[simp] theorem lift_eq_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : pfun.lift f = \u2191f :=\n  rfl\n\n@[simp] theorem coe_val {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : set (\u03b1 \u00d7 \u03b2) :=\n  set_of fun (p : \u03b1 \u00d7 \u03b2) => prod.snd p \u2208 f (prod.fst p)\n\ndef graph' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : rel \u03b1 \u03b2 :=\n  fun (x : \u03b1) (y : \u03b2) => y \u2208 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : set \u03b2 :=\n  set_of fun (b : \u03b2) => \u2203 (a : \u03b1), b \u2208 f a\n\n/-- Restrict a partial function to a smaller domain. -/\ndef restrict {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {p : set \u03b1} (H : p \u2286 dom f) : \u03b1 \u2192. \u03b2 :=\n  fun (x : \u03b1) => roption.restrict (x \u2208 p) (f x) H\n\n@[simp] theorem mem_restrict {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {s : set \u03b1} (h : s \u2286 dom f) (a : \u03b1) (b : \u03b2) : b \u2208 restrict f h a \u2194 a \u2208 s \u2227 b \u2208 f a := sorry\n\ndef res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) : \u03b1 \u2192. \u03b2 :=\n  restrict (pfun.lift f) (set.subset_univ s)\n\ntheorem mem_res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (a : \u03b1) (b : \u03b2) : b \u2208 res f s a \u2194 a \u2208 s \u2227 f a = b := sorry\n\ntheorem res_univ {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : res f set.univ = \u2191f :=\n  rfl\n\ntheorem dom_iff_graph {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) : x \u2208 dom f \u2194 \u2203 (y : \u03b2), (x, y) \u2208 graph f :=\n  roption.dom_iff_mem\n\ntheorem lift_graph {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {a : \u03b1} {b : \u03b2} : (a, b) \u2208 graph \u2191f \u2194 f a = b := sorry\n\n/-- The monad `pure` function, the total constant `x` function -/\nprotected def pure {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) : \u03b1 \u2192. \u03b2 :=\n  fun (_x : \u03b1) => roption.some x\n\n/-- The monad `bind` function, pointwise `roption.bind` -/\ndef bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192. \u03b2) (g : \u03b2 \u2192 \u03b1 \u2192. \u03b3) : \u03b1 \u2192. \u03b3 :=\n  fun (a : \u03b1) => roption.bind (f a) fun (b : \u03b2) => g b a\n\n/-- The monad `map` function, pointwise `roption.map` -/\ndef map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192. \u03b2) : \u03b1 \u2192. \u03b3 :=\n  fun (a : \u03b1) => roption.map f (g a)\n\nprotected instance monad {\u03b1 : Type u_1} : Monad (pfun \u03b1) :=\n  { toApplicative :=\n      { toFunctor := { map := map, mapConst := fun (\u03b1_1 \u03b2 : Type u_2) => map \u2218 function.const \u03b2 },\n        toPure := { pure := pfun.pure },\n        toSeq :=\n          { seq := fun (\u03b1_1 \u03b2 : Type u_2) (f : \u03b1 \u2192. \u03b1_1 \u2192 \u03b2) (x : \u03b1 \u2192. \u03b1_1) => bind f fun (_x : \u03b1_1 \u2192 \u03b2) => map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1_1 \u03b2 : Type u_2) (a : \u03b1 \u2192. \u03b1_1) (b : \u03b1 \u2192. \u03b2) =>\n                (fun (\u03b1_2 \u03b2 : Type u_2) (f : \u03b1 \u2192. \u03b1_2 \u2192 \u03b2) (x : \u03b1 \u2192. \u03b1_2) => bind f fun (_x : \u03b1_2 \u2192 \u03b2) => map _x x) \u03b2 \u03b1_1\n                  (map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1_1 \u03b2 : Type u_2) (a : \u03b1 \u2192. \u03b1_1) (b : \u03b1 \u2192. \u03b2) =>\n                (fun (\u03b1_2 \u03b2 : Type u_2) (f : \u03b1 \u2192. \u03b1_2 \u2192 \u03b2) (x : \u03b1 \u2192. \u03b1_2) => bind f fun (_x : \u03b1_2 \u2192 \u03b2) => map _x x) \u03b2 \u03b2\n                  (map (function.const \u03b1_1 id) a) b } },\n    toBind := { bind := bind } }\n\nprotected instance is_lawful_monad {\u03b1 : Type u_1} : is_lawful_monad (pfun \u03b1) :=\n  is_lawful_monad.mk (fun (\u03b2 \u03b3 : Type u_2) (x : \u03b2) (f : \u03b2 \u2192 \u03b1 \u2192. \u03b3) => funext fun (a : \u03b1) => roption.bind_some a (f x))\n    fun (\u03b2 \u03b3 \u03b4 : Type u_2) (f : \u03b1 \u2192. \u03b2) (g : \u03b2 \u2192 \u03b1 \u2192. \u03b3) (k : \u03b3 \u2192 \u03b1 \u2192. \u03b4) =>\n      funext fun (a : \u03b1) => roption.bind_assoc (f a) (fun (b : \u03b2) => g b a) fun (b : \u03b3) => k b a\n\ntheorem pure_defined {\u03b1 : Type u_1} {\u03b2 : Type u_2} (p : set \u03b1) (x : \u03b2) : p \u2286 dom (pfun.pure x) :=\n  set.subset_univ p\n\ntheorem bind_defined {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_2} (p : set \u03b1) {f : \u03b1 \u2192. \u03b2} {g : \u03b2 \u2192 \u03b1 \u2192. \u03b3} (H1 : p \u2286 dom f) (H2 : \u2200 (x : \u03b2), p \u2286 dom (g x)) : p \u2286 dom (f >>= g) :=\n  fun (a : \u03b1) (ha : a \u2208 p) => Exists.intro (H1 ha) (H2 (roption.get (f a) (H1 ha)) ha)\n\ndef fix {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2 \u2295 \u03b1) : \u03b1 \u2192. \u03b2 :=\n  fun (a : \u03b1) =>\n    roption.assert (acc (fun (x y : \u03b1) => sum.inr x \u2208 f y) a)\n      fun (h : acc (fun (x y : \u03b1) => sum.inr x \u2208 f y) a) =>\n        well_founded.fix_F\n          (fun (a : \u03b1) (IH : (y : \u03b1) \u2192 sum.inr y \u2208 f a \u2192 roption \u03b2) =>\n            roption.assert (roption.dom (f a))\n              fun (hf : roption.dom (f a)) =>\n                (fun (_x : \u03b2 \u2295 \u03b1) (e : roption.get (f a) hf = _x) =>\n                    sum.cases_on _x (fun (b : \u03b2) (e : roption.get (f a) hf = sum.inl b) => roption.some b)\n                      (fun (a' : \u03b1) (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {a : \u03b1} {b : \u03b2} (h : b \u2208 fix f a) : roption.dom (f a) := sorry\n\ntheorem mem_fix_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {a : \u03b1} {b : \u03b2} : b \u2208 fix f a \u2194 sum.inl b \u2208 f a \u2228 \u2203 (a' : \u03b1), sum.inr a' \u2208 f a \u2227 b \u2208 fix f a' := sorry\n\ndef fix_induction {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {b : \u03b2} {C : \u03b1 \u2192 Sort u_3} {a : \u03b1} (h : b \u2208 fix f a) (H : (a : \u03b1) \u2192 b \u2208 fix f a \u2192 ((a' : \u03b1) \u2192 b \u2208 fix f a' \u2192 sum.inr a' \u2208 f a \u2192 C a') \u2192 C a) : C a := sorry\n\nend pfun\n\n\nnamespace pfun\n\n\ndef image {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) : set \u03b2 :=\n  rel.image (graph' f) s\n\ntheorem image_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) : image f s = set_of fun (y : \u03b2) => \u2203 (x : \u03b1), \u2203 (H : x \u2208 s), y \u2208 f x :=\n  rfl\n\ntheorem mem_image {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (y : \u03b2) (s : set \u03b1) : y \u2208 image f s \u2194 \u2203 (x : \u03b1), \u2203 (H : x \u2208 s), y \u2208 f x :=\n  iff.rfl\n\ntheorem image_mono {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {s : set \u03b1} {t : set \u03b1} (h : s \u2286 t) : image f s \u2286 image f t :=\n  rel.image_mono (graph' f) h\n\ntheorem image_inter {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) (t : set \u03b1) : image f (s \u2229 t) \u2286 image f s \u2229 image f t :=\n  rel.image_inter (graph' f) s t\n\ntheorem image_union {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) (t : set \u03b1) : image f (s \u222a t) = image f s \u222a image f t :=\n  rel.image_union (graph' f) s t\n\ndef preimage {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : set \u03b1 :=\n  rel.preimage (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) s\n\ntheorem preimage_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : preimage f s = set_of fun (x : \u03b1) => \u2203 (y : \u03b2), \u2203 (H : y \u2208 s), y \u2208 f x :=\n  rfl\n\ntheorem mem_preimage {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (x : \u03b1) : x \u2208 preimage f s \u2194 \u2203 (y : \u03b2), \u2203 (H : y \u2208 s), y \u2208 f x :=\n  iff.rfl\n\ntheorem preimage_subset_dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : preimage f s \u2286 dom f := sorry\n\ntheorem preimage_mono {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {s : set \u03b2} {t : set \u03b2} (h : s \u2286 t) : preimage f s \u2286 preimage f t :=\n  rel.preimage_mono (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) h\n\ntheorem preimage_inter {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (t : set \u03b2) : preimage f (s \u2229 t) \u2286 preimage f s \u2229 preimage f t :=\n  rel.preimage_inter (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) s t\n\ntheorem preimage_union {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (t : set \u03b2) : preimage f (s \u222a t) = preimage f s \u222a preimage f t :=\n  rel.preimage_union (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) s t\n\ntheorem preimage_univ {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : preimage f set.univ = dom f := sorry\n\ndef core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : set \u03b1 :=\n  rel.core (graph' f) s\n\ntheorem core_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : core f s = set_of fun (x : \u03b1) => \u2200 (y : \u03b2), y \u2208 f x \u2192 y \u2208 s :=\n  rfl\n\ntheorem mem_core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) (s : set \u03b2) : x \u2208 core f s \u2194 \u2200 (y : \u03b2), y \u2208 f x \u2192 y \u2208 s :=\n  iff.rfl\n\ntheorem compl_dom_subset_core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : dom f\u1d9c \u2286 core f s :=\n  fun (x : \u03b1) (hx : x \u2208 (dom f\u1d9c)) (y : \u03b2) (fxy : graph' f x y) => absurd (iff.mpr (mem_dom f x) (Exists.intro y fxy)) hx\n\ntheorem core_mono {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {s : set \u03b2} {t : set \u03b2} (h : s \u2286 t) : core f s \u2286 core f t :=\n  rel.core_mono (graph' f) h\n\ntheorem core_inter {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (t : set \u03b2) : core f (s \u2229 t) = core f s \u2229 core f t :=\n  rel.core_inter (graph' f) s t\n\ntheorem mem_core_res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (t : set \u03b2) (x : \u03b1) : x \u2208 core (res f s) t \u2194 x \u2208 s \u2192 f x \u2208 t := sorry\n\ntheorem core_res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (t : set \u03b2) : core (res f s) t = s\u1d9c \u222a f \u207b\u00b9' t := sorry\n\ntheorem core_restrict {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b2) : core (\u2191f) s = f \u207b\u00b9' s := sorry\n\ntheorem preimage_subset_core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : preimage f s \u2286 core f s := sorry\n\ntheorem preimage_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : preimage f s = core f s \u2229 dom f := sorry\n\ntheorem core_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : core f s = preimage f s \u222a (dom f\u1d9c) := sorry\n\ntheorem preimage_as_subtype {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : as_subtype f \u207b\u00b9' s = subtype.val \u207b\u00b9' 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) 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\n\nuniverses u w u_1 \n\nnamespace Mathlib\n\ndef buffer (\u03b1 : Type u) := sigma fun (n : \u2115) => array n \u03b1\n\ndef mk_buffer {\u03b1 : Type u} : buffer \u03b1 := sigma.mk 0 (d_array.mk fun (i : fin 0) => fin.elim0 i)\n\ndef array.to_buffer {\u03b1 : Type u} {n : \u2115} (a : array n \u03b1) : buffer \u03b1 := sigma.mk n a\n\nnamespace buffer\n\n\ndef nil {\u03b1 : Type u} : buffer \u03b1 := mk_buffer\n\ndef size {\u03b1 : Type u} (b : buffer \u03b1) : \u2115 := sigma.fst b\n\ndef to_array {\u03b1 : Type u} (b : buffer \u03b1) : array (size b) \u03b1 := sigma.snd b\n\ndef push_back {\u03b1 : Type u} : buffer \u03b1 \u2192 \u03b1 \u2192 buffer \u03b1 := sorry\n\ndef pop_back {\u03b1 : Type u} : buffer \u03b1 \u2192 buffer \u03b1 := sorry\n\ndef read {\u03b1 : Type u} (b : buffer \u03b1) : fin (size b) \u2192 \u03b1 := sorry\n\ndef write {\u03b1 : Type u} (b : buffer \u03b1) : fin (size b) \u2192 \u03b1 \u2192 buffer \u03b1 := sorry\n\ndef read' {\u03b1 : Type u} [Inhabited \u03b1] : buffer \u03b1 \u2192 \u2115 \u2192 \u03b1 := sorry\n\ndef write' {\u03b1 : Type u} : buffer \u03b1 \u2192 \u2115 \u2192 \u03b1 \u2192 buffer \u03b1 := sorry\n\ntheorem read_eq_read' {\u03b1 : Type u} [Inhabited \u03b1] (b : buffer \u03b1) (i : \u2115) (h : i < size b) :\n    read b { val := i, property := h } = read' b i :=\n  sorry\n\ntheorem write_eq_write' {\u03b1 : Type u} (b : buffer \u03b1) (i : \u2115) (h : i < size b) (v : \u03b1) :\n    write b { val := i, property := h } v = write' b i v :=\n  sorry\n\ndef to_list {\u03b1 : Type u} (b : buffer \u03b1) : List \u03b1 := array.to_list (to_array b)\n\nprotected def to_string (b : buffer char) : string := list.as_string (array.to_list (to_array b))\n\ndef append_list {\u03b1 : Type u} : buffer \u03b1 \u2192 List \u03b1 \u2192 buffer \u03b1 := sorry\n\ndef append_string (b : buffer char) (s : string) : buffer char := append_list b (string.to_list s)\n\ntheorem lt_aux_1 {a : \u2115} {b : \u2115} {c : \u2115} (h : a + c < b) : a < b :=\n  lt_of_le_of_lt (nat.le_add_right a c) h\n\ntheorem lt_aux_2 {n : \u2115} (h : n > 0) : n - 1 < n :=\n  (fun (h\u2081 : 1 > 0) => nat.sub_lt h h\u2081) (of_as_true trivial)\n\ntheorem lt_aux_3 {n : \u2115} {i : \u2115} (h : i + 1 < n) : n - bit0 1 - i < n := sorry\n\ndef append_array {\u03b1 : Type u} {n : \u2115} (nz : n > 0) :\n    buffer \u03b1 \u2192 array n \u03b1 \u2192 (i : \u2115) \u2192 i < n \u2192 buffer \u03b1 :=\n  sorry\n\nprotected def append {\u03b1 : Type u} : buffer \u03b1 \u2192 buffer \u03b1 \u2192 buffer \u03b1 := sorry\n\ndef iterate {\u03b1 : Type u} {\u03b2 : Type w} (b : buffer \u03b1) : \u03b2 \u2192 (fin (size b) \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2 := sorry\n\ndef foreach {\u03b1 : Type u} (b : buffer \u03b1) : (fin (size b) \u2192 \u03b1 \u2192 \u03b1) \u2192 buffer \u03b1 := sorry\n\n/-- Monadically map a function over the buffer. -/\ndef mmap {\u03b1 : Type u} {\u03b2 : Type w} {m : Type w \u2192 Type u_1} [Monad m] (b : buffer \u03b1) (f : \u03b1 \u2192 m \u03b2) :\n    m (buffer \u03b2) :=\n  do \n    let b' \u2190 array.mmap (sigma.snd b) f \n    return (array.to_buffer b')\n\n/-- Map a function over the buffer. -/\ndef map {\u03b1 : Type u} {\u03b2 : Type w} : buffer \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 buffer \u03b2 := sorry\n\ndef foldl {\u03b1 : Type u} {\u03b2 : Type w} : buffer \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2 := sorry\n\ndef rev_iterate {\u03b1 : Type u} {\u03b2 : Type w} (b : buffer \u03b1) : \u03b2 \u2192 (fin (size b) \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2 :=\n  sorry\n\ndef take {\u03b1 : Type u} (b : buffer \u03b1) (n : \u2115) : buffer \u03b1 :=\n  dite (n \u2264 size b) (fun (h : n \u2264 size b) => sigma.mk n (array.take (to_array b) n h))\n    fun (h : \u00acn \u2264 size b) => b\n\ndef take_right {\u03b1 : Type u} (b : buffer \u03b1) (n : \u2115) : buffer \u03b1 :=\n  dite (n \u2264 size b) (fun (h : n \u2264 size b) => sigma.mk n (array.take_right (to_array b) n h))\n    fun (h : \u00acn \u2264 size b) => b\n\ndef drop {\u03b1 : Type u} (b : buffer \u03b1) (n : \u2115) : buffer \u03b1 :=\n  dite (n \u2264 size b) (fun (h : n \u2264 size b) => sigma.mk (size b - n) (array.drop (to_array b) n h))\n    fun (h : \u00acn \u2264 size b) => b\n\ndef reverse {\u03b1 : Type u} (b : buffer \u03b1) : buffer \u03b1 := sigma.mk (size b) (array.reverse (to_array b))\n\nprotected def mem {\u03b1 : Type u} (v : \u03b1) (a : buffer \u03b1) := \u2203 (i : fin (size a)), read a i = v\n\nprotected instance has_mem {\u03b1 : Type u} : has_mem \u03b1 (buffer \u03b1) := has_mem.mk buffer.mem\n\nprotected instance has_append {\u03b1 : Type u} : Append (buffer \u03b1) := { append := buffer.append }\n\nprotected instance has_repr {\u03b1 : Type u} [has_repr \u03b1] : has_repr (buffer \u03b1) :=\n  has_repr.mk (repr \u2218 to_list)\n\nend buffer\n\n\ndef list.to_buffer {\u03b1 : Type u} (l : List \u03b1) : buffer \u03b1 := buffer.append_list mk_buffer l\n\ndef char_buffer := buffer char\n\n/-- Convert a format object into a character buffer with the provided\n    formatting options. -/\ndef string.to_char_buffer (s : string) : char_buffer := buffer.append_string buffer.nil s\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/buffer_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.06278920377418667, "lm_q1q2_score": 0.026289645561156375}}
{"text": "example : (2:int)-(3:int)=(-1:int) :=\nbegin\ntrivial\nend", "meta": {"author": "sguzman", "repo": "lean-examples", "sha": "c7428b2982d0468d0adb4453766a27e1550a72e8", "save_path": "github-repos/lean/sguzman-lean-examples", "path": "github-repos/lean/sguzman-lean-examples/lean-examples-c7428b2982d0468d0adb4453766a27e1550a72e8/src/trivial2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.05340332452690108, "lm_q1q2_score": 0.026284482740188075}}
{"text": "import Preloaded Solution\n\ntheorem submission : SUBMISSION := immediate\n#print axioms submission", "meta": {"author": "DonaldKellett", "repo": "CW-Lean3-Examples", "sha": "9dd81b7c9327b029c859f37534232ab556f69699", "save_path": "github-repos/lean/DonaldKellett-CW-Lean3-Examples", "path": "github-repos/lean/DonaldKellett-CW-Lean3-Examples/CW-Lean3-Examples-9dd81b7c9327b029c859f37534232ab556f69699/kata4/SolutionTest.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.05749327234069682, "lm_q1q2_score": 0.02628228575749516}}
{"text": "/-\nCopyright (c) 2021 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg, Asta Halkj\u00e6r From\n-/\n\nimport Aesop.Index\nimport Aesop.Rule.Basic\nimport Aesop.Percent\nimport Aesop.Util\n\nnamespace Aesop\n\nopen Lean\nopen Lean.Meta\n\n/-! ### Normalisation Rules -/\n\nstructure NormRuleInfo where\n  penalty : Int\n  deriving Inhabited\n\ninstance : Ord NormRuleInfo where\n  compare i j := compare i.penalty j.penalty\n\ninstance : LT NormRuleInfo :=\n  ltOfOrd\n\ninstance : LE NormRuleInfo :=\n  leOfOrd\n\nabbrev NormRule := Rule NormRuleInfo\n\ninstance : ToString NormRule where\n  toString r := s!\"[{r.extra.penalty}] {r.name}\"\n\ndef defaultNormPenalty : Int := 1\n\n\n/-! ### Safe and Almost Safe Rules -/\n\ninductive Safety\n  | safe\n  | almostSafe\n  deriving Inhabited\n\nnamespace Safety\n\ninstance : ToString Safety where\n  toString\n    | safe => \"safe\"\n    | almostSafe => \"almostSafe\"\n\nend Safety\n\nstructure SafeRuleInfo where\n  penalty : Int\n  safety : Safety\n  deriving Inhabited\n\ninstance : Ord SafeRuleInfo where\n  compare i j := compare i.penalty j.penalty\n\ninstance : LT SafeRuleInfo :=\n  ltOfOrd\n\ninstance : LE SafeRuleInfo :=\n  leOfOrd\n\nabbrev SafeRule := Rule SafeRuleInfo\n\ninstance : ToString SafeRule where\n  toString r := s!\"[{r.extra.penalty}/{r.extra.safety}] {r.name}\"\n\ndef defaultSafePenalty : Int := 1\n\n\n/-! ### Unsafe Rules -/\n\nstructure UnsafeRuleInfo where\n  successProbability : Percent\n  deriving Inhabited\n\ninstance : Ord UnsafeRuleInfo where\n  compare i j := compare j.successProbability i.successProbability\n  -- NOTE: Rule with greater success probabilities are considered smaller.\n  -- This is because we take 'small' to mean 'high priority'.\n\ninstance : LT UnsafeRuleInfo :=\n  ltOfOrd\n\ninstance : LE UnsafeRuleInfo :=\n  leOfOrd\n\nabbrev UnsafeRule := Rule UnsafeRuleInfo\n\ninstance : ToString UnsafeRule where\n  toString r := s!\"[{r.extra.successProbability.toHumanString}] {r.name}\"\n\ndef defaultSuccessProbability : Percent := .fifty\n\n\n/-! ### Regular Rules -/\n\ninductive RegularRule\n  | safe (r : SafeRule)\n  | \u00abunsafe\u00bb (r : UnsafeRule)\n  deriving Inhabited, BEq\n\nnamespace RegularRule\n\ninstance : ToFormat RegularRule where\n  format\n    | safe r => format r\n    | \u00abunsafe\u00bb r => format r\n\ndef successProbability : RegularRule \u2192 Percent\n  | safe _ => Percent.hundred\n  | \u00abunsafe\u00bb r => r.extra.successProbability\n\ndef isSafe : RegularRule \u2192 Bool\n  | safe _ => true\n  | \u00abunsafe\u00bb _ => false\n\ndef isUnsafe : RegularRule \u2192 Bool\n  | safe _ => false\n  | \u00abunsafe\u00bb _ => true\n\n@[inline]\ndef withRule (f : \u2200 {\u03b1}, Rule \u03b1 \u2192 \u03b2) : RegularRule \u2192 \u03b2\n  | safe r => f r\n  | \u00abunsafe\u00bb r => f r\n\ndef name (r : RegularRule) : RuleName :=\n  r.withRule (\u00b7.name)\n\ndef indexingMode (r : RegularRule) : IndexingMode :=\n  r.withRule (\u00b7.indexingMode)\n\ndef tac (r : RegularRule) : RuleTacDescr :=\n  r.withRule (\u00b7.tac)\n\nend RegularRule\n\n\n/-! ### Normalisation Simp Rules -/\n\n-- A global rule for the norm simplifier. Each `SimpEntry` represents a member\n-- of the simp set, e.g. a declaration whose type is an equality or a smart\n-- unfolding theorem for a declaration.\nstructure NormSimpRule where\n  name : RuleName\n  entries : Array SimpEntry\n  deriving Inhabited\n\nnamespace NormSimpRule\n\ninstance : BEq NormSimpRule where\n  beq r s := r.name == s.name\n\ninstance : Hashable NormSimpRule where\n  hash r := hash r.name\n\nend NormSimpRule\n\n\n-- A local rule for the norm simplifier. This is a propositional hypothesis,\n-- represented by its user name. When we run the simplifier, we add this\n-- hypothesis to the simp set. This must be done for each goal individually\n-- since the `FVarId` of the hypothesis is not guaranteed to be stable.\nstructure LocalNormSimpRule where\n  fvarUserName : Name\n  deriving Inhabited\n\nnamespace LocalNormSimpRule\n\ninstance : BEq NormSimpRule where\n  beq r s := r.name == s.name\n\ninstance : Hashable NormSimpRule where\n  hash r := hash r.name\n\ndef name (r : LocalNormSimpRule) : RuleName :=\n  { name := r.fvarUserName, scope := .local, builder := .simp, phase := .norm }\n\nend LocalNormSimpRule\n\n\nstructure UnfoldRule where\n  decl : Name\n  unfoldThm? : Option Name\n  deriving Inhabited\n\nnamespace UnfoldRule\n\ninstance : BEq UnfoldRule where\n  beq r s := r.decl == s.decl\n\ninstance : Hashable UnfoldRule where\n  hash r := hash r.decl\n\ndef name (r : UnfoldRule) : RuleName :=\n  { name := r.decl, builder := .unfold, phase := .norm, scope := .global }\n\nend Aesop.UnfoldRule\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/Aesop/Rule.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05834584470514964, "lm_q1q2_score": 0.026220192862118945}}
{"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 \"\u2190\" 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 \ud83c\udf89\n\n/-\nWe can now try a harder problem, that cannot be immediately dispatched by `rfl`:\n-/\n\nexample : 43 = 43 \u2227 42 = 42:= by\n  custom_tactic\n-- tactic 'rfl' failed, equality expected\n--   43 = 43 \u2227 42 = 42\n-- \u22a2 43 = 43 \u2227 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 \u2227 42 = 42 := by\n  custom_tactic\n-- Goals accomplished \ud83c\udf89\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 \u2227 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 \u2227 2 = 2 := by\n  apply And.intro and_then rfl\n\n#print test_and_then\n-- theorem test_and_then : 1 = 1 \u2227 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: \u22a2 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 \u03b1`,\nwhich can synthesize an artificial term of type `\u03b1`. 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 \u2190 Lean.Elab.Tactic.getMainGoal\n    let goalDecl \u2190 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: \u22a2 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 \u2190 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: \u22a2 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 \u2192 2 = 2 \u2192 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-- \u22a2 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 \u2190 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-- \u22a2 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-- \u22a2 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 \u2190 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 \u2190 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 \u2190 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 \u2190 Lean.Elab.Tactic.getMainTarget\n    let ctx \u2190 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 \u2190 Lean.Meta.inferType declExpr -- Find the type.\n      let eq? \u2190 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 \u2190 Lean.Elab.Tactic.getMainTarget\n    let lctx \u2190 Lean.MonadLCtx.getLCtx\n    -- Iterate over the local declarations...\n    let option_matching_expr \u2190 lctx.findDeclM? fun ldecl: Lean.LocalDecl => do\n      let declExpr := ldecl.toExpr -- Find the expression of the declaration.\n      let declType \u2190 Lean.Meta.inferType declExpr -- Find the type.\n      if (\u2190 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 \u2190 Lean.Elab.Tactic.getMainGoal\n    let goalType \u2190 Lean.Elab.Tactic.getMainTarget\n    let ctx \u2190 Lean.MonadLCtx.getLCtx\n    let option_matching_expr \u2190 ctx.findDeclM? fun decl: Lean.LocalDecl => do\n      let declExpr := decl.toExpr\n      let declType \u2190 Lean.Meta.inferType declExpr\n      if \u2190 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-- \u22a2 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 \u2190 elabTerm t none\n    let v \u2190 elabTermEnsuringType v t\n    liftMetaTactic fun mvarId => do\n      let mvarIdNew \u2190 mvarId.define n.getId t v\n      let (_, mvarIdNew) \u2190 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 \u2190 elabTerm t none\n    let v \u2190 elabTermEnsuringType v t\n    liftMetaTactic fun mvarId => do\n      let mvarIdNew \u2190 mvarId.assert n.getId t v\n      let (_, mvarIdNew) \u2190 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-- \u22a2 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 \u2190 Lean.Elab.Tactic.getGoals\n    Lean.Elab.Tactic.setGoals goals.reverse\n\ntheorem test_reverse_goals : (1 = 2 \u2227 3 = 4) \u2227 5 = 6 := by\n  constructor\n  constructor\n-- case left.left\n-- \u22a2 1 = 2\n-- case left.right\n-- \u22a2 3 = 4\n-- case right\n-- \u22a2 5 = 6\n  reverse_goals\n-- case right\n-- \u22a2 5 = 6\n-- case left.right\n-- \u22a2 3 = 4\n-- case left.left\n-- \u22a2 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 \u2190 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 \u2190 Lean.Elab.Tactic.getGoals\n    goals.forM $ fun goal => do\n      let goalType \u2190 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 \u2190 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 \u2192 TacticM Unit` which evaluates a\ngiven tactic syntax. One can create tactic syntax using the macro\n`` `(tactic| \u22ef)``.\n\nFor example, one could call `try rfl` with the piece of code:\n\n```lean\nLean.Elab.Tactic.evalTactic (\u2190 `(tactic| try rfl))\n```\n\n**Q: How do I check if two expressions are equal?**\n\nA: Use `Lean.Meta.isExprDefEq <expr-1> <expr-2>`.\n-/\n\n#check Lean.Meta.isExprDefEq\n-- Lean.Meta.isExprDefEq : Lean.Expr \u2192 Lean.Expr \u2192 Lean.MetaM Bool\n\n/-\n**Q: How do I throw an error from a tactic?**\n\nA: Use `throwTacticEx <tactic-name> <goal-mvar> <error>`.\n-/\n\nelab \"faq_throw_error\" : tactic =>\n  Lean.Elab.Tactic.withMainContext do\n    let goal \u2190 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  -- \u22a2 true = true\n  -- tactic 'faq_throw_error' failed, throwing an error at the current goal\n  -- case false\n  -- \u22a2 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": "import Lean.Elab.Tactic.ElabTerm\nimport Mathlib.Tactic.RunCmd\n\nopen Lean Elab Tactic\n\nexample : True := by\n  run_tac\n    evalApplyLikeTactic MVarId.apply (\u2190 `(True.intro))\n\nexample : True := by_elab\n  Term.elabTerm (\u2190 `(True.intro)) none\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/runCmd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35577487985229844, "lm_q2_score": 0.07369626919743362, "lm_q1q2_score": 0.02621928131927959}}
{"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\u00b9` norm, by a sequence of simple functions.\n\n## Main definitions\n\n* `measure_theory.simple_func.nearest_pt (e : \u2115 \u2192 \u03b1) (N : \u2115) : \u03b1 \u2192\u209b \u2115`: the `simple_func` sending\n  each `x : \u03b1` to the point `e k` which is the nearest to `x` among `e 0`, ..., `e N`.\n* `measure_theory.simple_func.approx_on (f : \u03b2 \u2192 \u03b1) (hf : measurable f) (s : set \u03b1) (y\u2080 : \u03b1)\n  (h\u2080 : y\u2080 \u2208 s) [separable_space s] (n : \u2115) : \u03b2 \u2192\u209b \u03b1` : a simple function that takes values in `s`\n  and approximates `f`. If `f x \u2208 s`, then `measure_theory.simple_func.approx_on f hf s y\u2080 h\u2080 n x`\n  tends to `f x` as `n` tends to `\u221e`. If `\u03b1` is a `normed_group`, `f x - y\u2080`\n  is `measure_theory.integrable`, and `f x \u2208 s` for a.e. `x`, then\n  `simple_func.approx_on f hf s y\u2080 h\u2080 n` tends to `f` in `L\u2081`. The main use case is `s = univ`,\n  `y\u2080 = 0`.\n\n## Notations\n\n* `\u03b1 \u2192\u209b \u03b2` (local notation): the type of simple functions `\u03b1 \u2192 \u03b2`.\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 {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1] [opens_measurable_space \u03b1]\n    (e : \u2115 \u2192 \u03b1) : \u2115 \u2192 simple_func \u03b1 \u2115 :=\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 {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1] [opens_measurable_space \u03b1]\n    (e : \u2115 \u2192 \u03b1) (N : \u2115) : simple_func \u03b1 \u03b1 :=\n  map e (nearest_pt_ind e N)\n\n@[simp] theorem nearest_pt_ind_zero {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] (e : \u2115 \u2192 \u03b1) : nearest_pt_ind e 0 = const \u03b1 0 :=\n  rfl\n\n@[simp] theorem nearest_pt_zero {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] (e : \u2115 \u2192 \u03b1) : nearest_pt e 0 = const \u03b1 (e 0) :=\n  rfl\n\ntheorem nearest_pt_ind_succ {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] (e : \u2115 \u2192 \u03b1) (N : \u2115) (x : \u03b1) :\n    coe_fn (nearest_pt_ind e (N + 1)) x =\n        ite (\u2200 (k : \u2115), k \u2264 N \u2192 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 {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] (e : \u2115 \u2192 \u03b1) (N : \u2115) (x : \u03b1) : coe_fn (nearest_pt_ind e N) x \u2264 N :=\n  sorry\n\ntheorem edist_nearest_pt_le {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] (e : \u2115 \u2192 \u03b1) (x : \u03b1) {k : \u2115} {N : \u2115} (hk : k \u2264 N) :\n    edist (coe_fn (nearest_pt e N) x) x \u2264 edist (e k) x :=\n  sorry\n\ntheorem tendsto_nearest_pt {\u03b1 : Type u_1} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] {e : \u2115 \u2192 \u03b1} {x : \u03b1} (hx : x \u2208 closure (set.range e)) :\n    filter.tendsto (fun (N : \u2115) => 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 \u2208 s`. -/\ndef approx_on {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] (f : \u03b2 \u2192 \u03b1) (hf : measurable f) (s : set \u03b1)\n    (y\u2080 : \u03b1) (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] (n : \u2115) : simple_func \u03b2 \u03b1 :=\n  comp (nearest_pt (fun (k : \u2115) => nat.cases_on k y\u2080 (coe \u2218 topological_space.dense_seq \u21a5s)) n) f hf\n\n@[simp] theorem approx_on_zero {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] {f : \u03b2 \u2192 \u03b1} (hf : measurable f) {s : set \u03b1}\n    {y\u2080 : \u03b1} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] (x : \u03b2) :\n    coe_fn (approx_on f hf s y\u2080 h\u2080 0) x = y\u2080 :=\n  rfl\n\ntheorem approx_on_mem {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] {f : \u03b2 \u2192 \u03b1} (hf : measurable f) {s : set \u03b1}\n    {y\u2080 : \u03b1} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] (n : \u2115) (x : \u03b2) :\n    coe_fn (approx_on f hf s y\u2080 h\u2080 n) x \u2208 s :=\n  (fun (n_1 : \u2115) =>\n      nat.cases_on n_1 h\u2080 fun (n : \u2115) => subtype.mem (topological_space.dense_seq (\u21a5s) n))\n    (coe_fn\n      (nearest_pt_ind (fun (k : \u2115) => nat.cases_on k y\u2080 (coe \u2218 topological_space.dense_seq \u21a5s)) n)\n      (f x))\n\n@[simp] theorem approx_on_comp {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] {\u03b3 : Type u_3} [measurable_space \u03b3] {f : \u03b2 \u2192 \u03b1}\n    (hf : measurable f) {g : \u03b3 \u2192 \u03b2} (hg : measurable g) {s : set \u03b1} {y\u2080 : \u03b1} (h\u2080 : y\u2080 \u2208 s)\n    [topological_space.separable_space \u21a5s] (n : \u2115) :\n    approx_on (f \u2218 g) (measurable.comp hf hg) s y\u2080 h\u2080 n = comp (approx_on f hf s y\u2080 h\u2080 n) g hg :=\n  rfl\n\ntheorem tendsto_approx_on {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] {f : \u03b2 \u2192 \u03b1} (hf : measurable f) {s : set \u03b1}\n    {y\u2080 : \u03b1} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] {x : \u03b2} (hx : f x \u2208 closure s) :\n    filter.tendsto (fun (n : \u2115) => coe_fn (approx_on f hf s y\u2080 h\u2080 n) x) filter.at_top\n        (nhds (f x)) :=\n  sorry\n\ntheorem edist_approx_on_le {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] {f : \u03b2 \u2192 \u03b1} (hf : measurable f) {s : set \u03b1}\n    {y\u2080 : \u03b1} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] (x : \u03b2) (n : \u2115) :\n    edist (coe_fn (approx_on f hf s y\u2080 h\u2080 n) x) (f x) \u2264 edist y\u2080 (f x) :=\n  id\n    (edist_nearest_pt_le (Nat.rec y\u2080 fun (n : \u2115) (ih : \u03b1) => \u2191(topological_space.dense_seq (\u21a5s) n))\n      (f x) (zero_le n))\n\ntheorem edist_approx_on_y0_le {\u03b1 : Type u_1} {\u03b2 : Type u_2} [measurable_space \u03b1] [emetric_space \u03b1]\n    [opens_measurable_space \u03b1] [measurable_space \u03b2] {f : \u03b2 \u2192 \u03b1} (hf : measurable f) {s : set \u03b1}\n    {y\u2080 : \u03b1} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] (x : \u03b2) (n : \u2115) :\n    edist y\u2080 (coe_fn (approx_on f hf s y\u2080 h\u2080 n) x) \u2264 edist y\u2080 (f x) + edist y\u2080 (f x) :=\n  le_trans (edist_triangle_right y\u2080 (coe_fn (approx_on f hf s y\u2080 h\u2080 n) x) (f x))\n    (add_le_add_left (edist_approx_on_le hf h\u2080 x n) (edist y\u2080 (f x)))\n\ntheorem norm_approx_on_zero_le {\u03b2 : Type u_2} {E : Type u_4} [measurable_space \u03b2]\n    [measurable_space E] [normed_group E] [opens_measurable_space E] {f : \u03b2 \u2192 E} (hf : measurable f)\n    {s : set E} (h\u2080 : 0 \u2208 s) [topological_space.separable_space \u21a5s] (x : \u03b2) (n : \u2115) :\n    norm (coe_fn (approx_on f hf s 0 h\u2080 n) x) \u2264 norm (f x) + norm (f x) :=\n  sorry\n\ntheorem tendsto_approx_on_l1_edist {\u03b2 : Type u_2} {E : Type u_4} [measurable_space \u03b2]\n    [measurable_space E] [normed_group E] [opens_measurable_space E] {f : \u03b2 \u2192 E} (hf : measurable f)\n    {s : set E} {y\u2080 : E} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s] {\u03bc : measure \u03b2}\n    (h\u03bc : filter.eventually (fun (x : \u03b2) => f x \u2208 closure s) (measure.ae \u03bc))\n    (hi : has_finite_integral fun (x : \u03b2) => f x - y\u2080) :\n    filter.tendsto\n        (fun (n : \u2115) =>\n          lintegral \u03bc fun (x : \u03b2) => edist (coe_fn (approx_on f hf s y\u2080 h\u2080 n) x) (f x))\n        filter.at_top (nhds 0) :=\n  sorry\n\ntheorem integrable_approx_on {\u03b2 : Type u_2} {E : Type u_4} [measurable_space \u03b2] [measurable_space E]\n    [normed_group E] [borel_space E] {f : \u03b2 \u2192 E} {\u03bc : measure \u03b2} (fmeas : measurable f)\n    (hf : integrable f) {s : set E} {y\u2080 : E} (h\u2080 : y\u2080 \u2208 s) [topological_space.separable_space \u21a5s]\n    (hi\u2080 : integrable fun (x : \u03b2) => y\u2080) (n : \u2115) : integrable \u21d1(approx_on f fmeas s y\u2080 h\u2080 n) :=\n  sorry\n\ntheorem tendsto_approx_on_univ_l1_edist {\u03b2 : Type u_2} {E : Type u_4} [measurable_space \u03b2]\n    [measurable_space E] [normed_group E] [opens_measurable_space E]\n    [topological_space.second_countable_topology E] {f : \u03b2 \u2192 E} {\u03bc : measure \u03b2}\n    (fmeas : measurable f) (hf : integrable f) :\n    filter.tendsto\n        (fun (n : \u2115) =>\n          lintegral \u03bc\n            fun (x : \u03b2) => 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 {\u03b2 : Type u_2} {E : Type u_4} [measurable_space \u03b2]\n    [measurable_space E] [normed_group E] [borel_space E]\n    [topological_space.second_countable_topology E] {f : \u03b2 \u2192 E} {\u03bc : measure \u03b2}\n    (fmeas : measurable f) (hf : integrable f) (n : \u2115) :\n    integrable \u21d1(approx_on f fmeas set.univ 0 trivial n) :=\n  integrable_approx_on fmeas hf trivial (integrable_zero \u03b2 E \u03bc) n\n\ntheorem tendsto_approx_on_univ_l1 {\u03b2 : Type u_2} {E : Type u_4} [measurable_space \u03b2]\n    [measurable_space E] [normed_group E] [borel_space E]\n    [topological_space.second_countable_topology E] {f : \u03b2 \u2192 E} {\u03bc : measure \u03b2}\n    (fmeas : measurable f) (hf : integrable f) :\n    filter.tendsto\n        (fun (n : \u2115) =>\n          l1.of_fun (\u21d1(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 \u2192 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 \u2192 ReducibilityHints \u2192 Bool\n  | .abbrev,     .abbrev     => false\n  | .abbrev,     _           => true\n  | .regular d\u2081, .regular d\u2082 => d\u2081 < d\u2082\n  | .regular _,  .opaque     => true\n  | _,           _           => false\n\ndef isAbbrev : ReducibilityHints \u2192 Bool\n  | .abbrev => true\n  | _       => false\n\ndef isRegular : ReducibilityHints \u2192 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  | \u00abunsafe\u00bb | safe | \u00abpartial\u00bb\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 \u2192 Bool\n  | Declaration.inductDecl _ _ _ isUnsafe => isUnsafe\n  | _ => false\n\n@[specialize] def Declaration.foldExprM {\u03b1} {m : Type \u2192 Type} [Monad m] (d : Declaration) (f : \u03b1 \u2192 Expr \u2192 m \u03b1) (a : \u03b1) : m \u03b1 :=\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 \u2190 f a type; f a value\n  | Declaration.opaqueDecl { type := type, value := value, .. } => do let a \u2190 f a type; f a value\n  | Declaration.thmDecl { type := type, value := value, .. }    => do let a \u2190 f a type; f a value\n  | Declaration.mutualDefnDecl vals                             => vals.foldlM (fun a v => do let a \u2190 f a v.type; f a v.value) a\n  | Declaration.inductDecl _ _ inductTypes _                    =>\n    inductTypes.foldlM\n      (fun a inductType => do\n        let a \u2190 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 \u2192 Type} [Monad m] (d : Declaration) (f : Expr \u2192 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 `\u03b1 : Type` argument in the vector constructors\n  `nil : Vector \u03b1 0` and `cons : \u03b1 \u2192 Vector \u03b1 n \u2192 Vector \u03b1 (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 : \u03b1 \u2192 Vector \u03b1 n \u2192 Vector \u03b1 (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 \u2192 Type` is some suitably behaved (ie strictly positive) function (Eg `Array T`, `List T`, `T \u00d7 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 \u2192 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 \u2192 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 \u2192 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 \u2192 Option Expr\n  | defnInfo {value := r, ..} => some r\n  | thmInfo  {value := r, ..} => some r\n  | _                         => none\n\ndef hasValue : ConstantInfo \u2192 Bool\n  | defnInfo _ => true\n  | thmInfo  _ => true\n  | _                         => false\n\ndef value! : ConstantInfo \u2192 Expr\n  | defnInfo {value := r, ..} => r\n  | thmInfo  {value := r, ..} => r\n  | _                         => panic! \"declaration with value expected\"\n\ndef hints : ConstantInfo \u2192 ReducibilityHints\n  | defnInfo {hints := r, ..} => r\n  | _                         => ReducibilityHints.opaque\n\ndef isCtor : ConstantInfo \u2192 Bool\n  | ctorInfo _ => true\n  | _          => false\n\ndef isInductive : ConstantInfo \u2192 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 \u2192 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 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek\n-/\nimport data.dlist.basic category.basic meta.expr meta.rb_map\n\nnamespace expr\nopen tactic\n\nattribute [derive has_reflect] binder_info\n\nprotected meta def of_nat (\u03b1 : expr) : \u2115 \u2192 tactic expr :=\nnat.binary_rec\n  (tactic.mk_mapp ``has_zero.zero [some \u03b1, none])\n  (\u03bb b n tac, if n = 0 then mk_mapp ``has_one.one [some \u03b1, none] else\n    do e \u2190 tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])\n\nprotected meta def of_int (\u03b1 : expr) : \u2124 \u2192 tactic expr\n| (n : \u2115) := expr.of_nat \u03b1 n\n| -[1+ n] := do\n  e \u2190 expr.of_nat \u03b1 (n+1),\n  tactic.mk_app ``has_neg.neg [e]\n\n/- only traverses the direct descendents -/\nmeta def {u} traverse {m : Type \u2192 Type u} [applicative m]\n  {elab elab' : bool} (f : expr elab \u2192 m (expr elab')) :\n  expr elab \u2192 m (expr elab')\n | (var v)  := pure $ var v\n | (sort l) := pure $ sort l\n | (const n ls) := pure $ const n ls\n | (mvar n n' e) := mvar n n' <$> f e\n | (local_const n n' bi e) := local_const n n' bi <$> f e\n | (app e\u2080 e\u2081) := app <$> f e\u2080 <*> f e\u2081\n | (lam n bi e\u2080 e\u2081) := lam n bi <$> f e\u2080 <*> f e\u2081\n | (pi n bi e\u2080 e\u2081) := pi n bi <$> f e\u2080 <*> f e\u2081\n | (elet n e\u2080 e\u2081 e\u2082) := elet n <$> f e\u2080 <*> f e\u2081 <*> f e\u2082\n | (macro mac es) := macro mac <$> list.traverse f es\n\nmeta def mfoldl {\u03b1 : Type} {m} [monad m] (f : \u03b1 \u2192 expr \u2192 m \u03b1) : \u03b1 \u2192 expr \u2192 m \u03b1\n| x e := prod.snd <$> (state_t.run (e.traverse $ \u03bb e',\n    (get >>= monad_lift \u2218 flip f e' >>= put) $> e') x : m _)\n\nend expr\n\nnamespace interaction_monad\nopen result\n\nmeta def get_result {\u03c3 \u03b1} (tac : interaction_monad \u03c3 \u03b1) :\n  interaction_monad \u03c3 (interaction_monad.result \u03c3 \u03b1) | s :=\nmatch tac s with\n| r@(success _ s') := success r s'\n| r@(exception _ _ s') := success r s'\nend\n\nend interaction_monad\n\nnamespace lean.parser\nopen lean interaction_monad.result\n\nmeta def of_tactic' {\u03b1} (tac : tactic \u03b1) : parser \u03b1 :=\ndo r \u2190 of_tactic (interaction_monad.get_result tac),\nmatch r with\n| (success a _) := return a\n| (exception f pos _) := exception f pos\nend\n\n-- Override the builtin `lean.parser.of_tactic` coe, which is broken.\n-- (See test/tactics.lean for a failure case.)\n@[priority 2000]\nmeta instance has_coe' {\u03b1} : has_coe (tactic \u03b1) (parser \u03b1) :=\n\u27e8of_tactic'\u27e9\n\nmeta def emit_command_here (str : string) : lean.parser string :=\ndo (_, left) \u2190 with_input command_like str,\n   return left\n\n-- Emit a source code string at the location being parsed.\nmeta def emit_code_here : string \u2192 lean.parser unit\n| str := do left \u2190 emit_command_here str,\n            if left.length = 0 then return ()\n            else emit_code_here left\n\nend lean.parser\n\nnamespace name\n\nmeta def head : name \u2192 string\n| (mk_string s anonymous) := s\n| (mk_string s p)         := head p\n| (mk_numeral n p)        := head p\n| anonymous               := \"[anonymous]\"\n\nmeta def is_private (n : name) : bool :=\nn.head = \"_private\"\n\nmeta def last : name \u2192 string\n| (mk_string s _)  := s\n| (mk_numeral n _) := repr n\n| anonymous        := \"[anonymous]\"\n\nmeta def length : name \u2192 \u2115\n| (mk_string s anonymous) := s.length\n| (mk_string s p)         := s.length + 1 + p.length\n| (mk_numeral n p)        := p.length\n| anonymous               := \"[anonymous]\".length\n\nend name\n\nnamespace environment\nmeta def decl_filter_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 option \u03b1) : list \u03b1 :=\n  e.fold [] $ \u03bb d l, match f d with\n                     | some r := r :: l\n                     | none := l\n                     end\n\nmeta def decl_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 \u03b1) : list \u03b1 :=\n  e.decl_filter_map $ \u03bb d, some (f d)\n\nmeta def get_decls (e : environment) : list declaration :=\n  e.decl_map id\n\nmeta def get_trusted_decls (e : environment) : list declaration :=\n  e.decl_filter_map (\u03bb d, if d.is_trusted then some d else none)\n\nmeta def get_decl_names (e : environment) : list name :=\n  e.decl_map declaration.to_name\nend environment\n\nnamespace format\n\nmeta def intercalate (x : format) : list format \u2192 format :=\nformat.join \u2218 list.intersperse x\n\nend format\n\nnamespace tactic\n\nmeta def eval_expr' (\u03b1 : Type*) [_inst_1 : reflected \u03b1] (e : expr) : tactic \u03b1 :=\nmk_app ``id [e] >>= eval_expr \u03b1\n\n-- `mk_fresh_name` returns identifiers starting with underscores,\n-- which are not legal when emitted by tactic programs. Turn the\n-- useful source of random names provided by `mk_fresh_name` into\n-- names which are usable by tactic programs.\n--\n-- The returned name has four components.\nmeta def mk_user_fresh_name : tactic name :=\ndo nm \u2190 mk_fresh_name,\n   return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__\n\nmeta def is_simp_lemma : name \u2192 tactic bool :=\nsucceeds \u2218 tactic.has_attribute `simp\n\nmeta def local_decls : tactic (name_map declaration) :=\ndo e \u2190 tactic.get_env,\n   let xs := e.fold native.mk_rb_map\n     (\u03bb d s, if environment.in_current_file' e d.to_name\n             then s.insert d.to_name d else s),\n   pure xs\n\nmeta def simp_lemmas_from_file : tactic name_set :=\ndo s \u2190 local_decls,\n   let s := s.map (expr.list_constant \u2218 declaration.value),\n   xs \u2190 s.to_list.mmap ((<$>) name_set.of_list \u2218 mfilter tactic.is_simp_lemma \u2218 name_set.to_list \u2218 prod.snd),\n   return $ name_set.filter (\u03bb x, \u00ac s.contains x) (xs.foldl name_set.union mk_name_set)\n\nmeta def file_simp_attribute_decl (attr : name) : tactic unit :=\ndo s \u2190 simp_lemmas_from_file,\n   trace format!\"run_cmd mk_simp_attr `{attr}\",\n   let lmms := format.join $ list.intersperse \" \" $ s.to_list.map to_fmt,\n   trace format!\"local attribute [{attr}] {lmms}\"\n\nmeta def mk_local (n : name) : expr :=\nexpr.local_const n n binder_info.default (expr.const n [])\n\nmeta def local_def_value (e : expr) : tactic expr := do\ndo (v,_) \u2190 solve_aux `(true) (do\n         (expr.elet n t v _) \u2190 (revert e >> target)\n           | fail format!\"{e} is not a local definition\",\n         return v),\n   return v\n\nmeta def check_defn (n : name) (e : pexpr) : tactic unit :=\ndo (declaration.defn _ _ _ d _ _) \u2190 get_decl n,\n   e' \u2190 to_expr e,\n   guard (d =\u2090 e') <|> trace d >> failed\n\n-- meta def compile_eqn (n : name) (univ : list name) (args : list expr) (val : expr) (num : \u2115) : tactic unit :=\n-- do let lhs := (expr.const n $ univ.map level.param).mk_app args,\n--    stmt \u2190 mk_app `eq [lhs,val],\n--    let vs := stmt.list_local_const,\n--    let stmt := stmt.pis vs,\n--    (_,pr) \u2190 solve_aux stmt (tactic.intros >> reflexivity),\n--    add_decl $ declaration.thm (n <.> \"equations\" <.> to_string (format!\"_eqn_{num}\")) univ stmt (pure pr)\n\nmeta def to_implicit : expr \u2192 expr\n| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t\n| e := e\n\nmeta def pis : list expr \u2192 expr \u2192 tactic expr\n| (e@(expr.local_const uniq pp info _) :: es) f := do\n  t \u2190 infer_type e,\n  f' \u2190 pis es f,\n  pure $ expr.pi pp info t (expr.abstract_local f' uniq)\n| _ f := pure f\n\nmeta def lambdas : list expr \u2192 expr \u2192 tactic expr\n| (e@(expr.local_const uniq pp info _) :: es) f := do\n  t \u2190 infer_type e,\n  f' \u2190 lambdas es f,\n  pure $ expr.lam pp info t (expr.abstract_local f' uniq)\n| _ f := pure f\n\nmeta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=\ndo cxt \u2190 list.map to_implicit <$> local_context,\n   t \u2190 target,\n   (eqns,d) \u2190 solve_aux t elab_def,\n   d \u2190 instantiate_mvars d,\n   t' \u2190 pis cxt t,\n   d' \u2190 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   applyc n\n\nmeta def exact_dec_trivial : tactic unit := `[exact dec_trivial]\n\n/-- Runs a tactic for a result, reverting the state after completion -/\nmeta def retrieve {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s, result.cases_on (tac s)\n (\u03bb a s', result.success a s)\n result.exception\n\n/-- Repeat a tactic at least once, calling it recursively on all subgoals,\n  until it fails. This tactic fails if the first invocation fails. -/\nmeta def repeat1 (t : tactic unit) : tactic unit := t; repeat t\n\n/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and\n  at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/\nmeta def iterate_range : \u2115 \u2192 \u2115 \u2192 tactic unit \u2192 tactic unit\n| 0 0     t := skip\n| 0 (n+1) t := try (t >> iterate_range 0 n t)\n| (m+1) n t := t >> iterate_range m (n-1) t\n\nmeta def replace_at (tac : expr \u2192 tactic (expr \u00d7 expr)) (hs : list expr) (tgt : bool) : tactic bool :=\ndo to_remove \u2190 hs.mfilter $ \u03bb h, do {\n    h_type \u2190 infer_type h,\n    succeeds $ do\n      (new_h_type, pr) \u2190 tac h_type,\n      assert h.local_pp_name new_h_type,\n      mk_eq_mp pr h >>= tactic.exact },\n  goal_simplified \u2190 succeeds $ do {\n    guard tgt,\n    (new_t, pr) \u2190 target >>= tac,\n    replace_target new_t pr },\n  to_remove.mmap' (\u03bb h, try (clear h)),\n  return (\u00ac to_remove.empty \u2228 goal_simplified)\n\nmeta def simp_bottom_up' (post : expr \u2192 tactic (expr \u00d7 expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr \u00d7 expr) :=\nprod.snd <$> simplify_bottom_up () (\u03bb _, (<$>) (prod.mk ()) \u2218 post) e cfg\n\nmeta structure instance_cache :=\n(\u03b1 : expr)\n(univ : level)\n(inst : name_map expr)\n\nmeta def mk_instance_cache (\u03b1 : expr) : tactic instance_cache :=\ndo u \u2190 mk_meta_univ,\n   infer_type \u03b1 >>= unify (expr.sort (level.succ u)),\n   u \u2190 get_univ_assignment u,\n   return \u27e8\u03b1, u, mk_name_map\u27e9\n\nnamespace instance_cache\n\nmeta def get (c : instance_cache) (n : name) : tactic (instance_cache \u00d7 expr) :=\nmatch c.inst.find n with\n| some i := return (c, i)\n| none := do e \u2190 mk_app n [c.\u03b1] >>= mk_instance,\n  return (\u27e8c.\u03b1, c.univ, c.inst.insert n e\u27e9, e)\nend\n\nopen expr\nmeta def append_typeclasses : expr \u2192 instance_cache \u2192 list expr \u2192\n  tactic (instance_cache \u00d7 list expr)\n| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=\n  do (c, p) \u2190 c.get n, return (c, p :: l)\n| _ c l := return (c, l)\n\nmeta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache \u00d7 expr) :=\ndo d \u2190 get_decl n,\n   (c, l) \u2190 append_typeclasses d.type.binding_body c l,\n   return (c, (expr.const n [c.univ]).mk_app (c.\u03b1 :: l))\n\nend instance_cache\n\n/-- Reset the instance cache for the main goal. -/\nmeta def reset_instance_cache : tactic unit := unfreeze_local_instances\n\nmeta def match_head (e : expr) : expr \u2192 tactic unit\n| e' :=\n    unify e e'\n<|> do `(_ \u2192 %%e') \u2190 whnf e',\n       v \u2190 mk_mvar,\n       match_head (e'.instantiate_var v)\n\nmeta def find_matching_head : expr \u2192 list expr \u2192 tactic (list expr)\n| e []         := return []\n| e (H :: Hs) :=\n  do t \u2190 infer_type H,\n     ((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs\n\nmeta def subst_locals (s : list (expr \u00d7 expr)) (e : expr) : expr :=\n(e.abstract_locals (s.map (expr.local_uniq_name \u2218 prod.fst)).reverse).instantiate_vars (s.map prod.snd)\n\nmeta def set_binder : expr \u2192 list binder_info \u2192 expr\n| e [] := e\n| (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs)\n| e _ := e\n\nmeta def last_explicit_arg : expr \u2192 tactic expr\n| (expr.app f e) :=\ndo t \u2190 infer_type f >>= whnf,\n   if t.binding_info = binder_info.default\n     then pure e\n     else last_explicit_arg f\n| e := pure e\n\nprivate meta def get_expl_pi_arity_aux : expr \u2192 tactic nat\n| (expr.pi n bi d b) :=\n  do m     \u2190 mk_fresh_name,\n     let l := expr.local_const m n bi d,\n     new_b \u2190 whnf (expr.instantiate_var b l),\n     r     \u2190 get_expl_pi_arity_aux new_b,\n     if bi = binder_info.default then\n       return (r + 1)\n     else\n       return r\n| e := return 0\n\n/-- Compute the arity of explicit arguments of the given (Pi-)type -/\nmeta def get_expl_pi_arity (type : expr) : tactic nat :=\nwhnf type >>= get_expl_pi_arity_aux\n\n/-- Compute the arity of explicit arguments of the given function -/\nmeta def get_expl_arity (fn : expr) : tactic nat :=\ninfer_type fn >>= get_expl_pi_arity\n\n/-- variation on `assert` where a (possibly incomplete)\n    proof of the assertion is provided as a parameter.\n\n    ``(h,gs) \u2190 local_proof `h p tac`` creates a local `h : p` and\n    use `tac` to (partially) construct a proof for it. `gs` is the\n    list of remaining goals in the proof of `h`.\n\n    The benefits over assert are:\n    - unlike with ``h \u2190 assert `h p, tac`` , `h` cannot be used by `tac`;\n    - when `tac` does not complete the proof of `h`, returning the list\n      of goals allows one to write a tactic using `h` and with the confidence\n      that a proof will not boil over to goals left over from the proof of `h`,\n      unlike what would be the case when using `tactic.swap`.\n-/\nmeta def local_proof (h : name) (p : expr) (tac\u2080 : tactic unit) :\n  tactic (expr \u00d7 list expr) :=\nfocus1 $\ndo h' \u2190 assert h p,\n   [g\u2080,g\u2081] \u2190 get_goals,\n   set_goals [g\u2080], tac\u2080,\n   gs \u2190 get_goals,\n   set_goals [g\u2081],\n   return (h', gs)\n\nmeta def var_names : expr \u2192 list name\n| (expr.pi n _ _ b) := n :: var_names b\n| _ := []\n\nmeta def drop_binders : expr \u2192 tactic expr\n| (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders\n| e := pure e\n\nmeta def subobject_names (struct_n : name) : tactic (list name \u00d7 list name) :=\ndo env \u2190 get_env,\n   [c] \u2190 pure $ env.constructors_of struct_n | fail \"too many constructors\",\n   vs  \u2190 var_names <$> (mk_const c >>= infer_type),\n   fields \u2190 env.structure_fields struct_n,\n   return $ fields.partition (\u03bb fn, \u2191(\"_\" ++ fn.to_string) \u2208 vs)\n\nmeta def expanded_field_list' : name \u2192 tactic (dlist $ name \u00d7 name) | struct_n :=\ndo (so,fs) \u2190 subobject_names struct_n,\n   ts \u2190 so.mmap (\u03bb n, do\n     e \u2190 mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders,\n     expanded_field_list' $ e.get_app_fn.const_name),\n   return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)\nopen functor function\n\nmeta def expanded_field_list (struct_n : name) : tactic (list $ name \u00d7 name) :=\ndlist.to_list <$> expanded_field_list' struct_n\n\nmeta def get_classes (e : expr) : tactic (list name) :=\nattribute.get_instances `class >>= list.mfilter (\u03bb n,\n  succeeds $ mk_app n [e] >>= mk_instance)\n\nopen nat\n\nmeta def mk_mvar_list : \u2115 \u2192 tactic (list expr)\n| 0 := pure []\n| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n\n\n/--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,\nor until it fails. Always succeeds. -/\nmeta def iterate_at_most_on_all_goals : nat \u2192 tactic unit \u2192 tactic unit\n| 0        tac := trace \"maximal iterations reached\"\n| (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip\n\n/--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first\ngoal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on\ncurrent goal. -/\nmeta def iterate_at_most_on_subgoals : nat \u2192 tactic unit \u2192 tactic unit\n| 0        tac := trace \"maximal iterations reached\"\n| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)\n\n/--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and\nfail if none succeeds -/\nmeta def apply_list_expr : list expr \u2192 tactic unit\n| []     := fail \"no matching rule\"\n| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t\n\n/-- constructs a list of expressions given a list of p-expressions, as follows:\n- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it\n- if the p-expression is a user attribute, add all the theorems with this attribute\n  to the list.-/\nmeta def build_list_expr_for_apply : list pexpr \u2192 tactic (list expr)\n| [] := return []\n| (h::t) := do\n  tail \u2190 build_list_expr_for_apply t,\n  a \u2190 i_to_expr_for_apply h,\n  (do l \u2190 attribute.get_instances (expr.const_name a),\n      m \u2190 list.mmap mk_const l,\n      return (m.append tail))\n  <|> return (a::tail)\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 -/\nmeta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=\ndo l \u2190 build_list_expr_for_apply hs,\n   iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)\n\nmeta def replace (h : name) (p : pexpr) : tactic unit :=\ndo h' \u2190 get_local h,\n   p \u2190 to_expr p,\n   note h none p,\n   clear h'\n\n/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``\nor `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an\n`iff`, returns an expression with the `iff` converted to either the forwards or backwards\nimplication, as requested. -/\nmeta def mk_iff_mp_app (iffmp : name) : expr \u2192 (nat \u2192 expr) \u2192 option expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (\u03bb n, f (n+1) (expr.var n))\n| `(%%a \u2194 %%b) f := some $ @expr.const tt iffmp [] a b (f 0)\n| _ f := none\n\nmeta def iff_mp_core (e ty: expr) : option expr :=\nmk_iff_mp_app `iff.mp ty (\u03bb_, e)\n\nmeta def iff_mpr_core (e ty: expr) : option expr :=\nmk_iff_mp_app `iff.mpr ty (\u03bb_, e)\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the forward implication. -/\nmeta def iff_mp (e : expr) : tactic expr :=\ndo t \u2190 infer_type e,\n   iff_mp_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the reverse implication. -/\nmeta def iff_mpr (e : expr) : tactic expr :=\ndo t \u2190 infer_type e,\n   iff_mpr_core e t <|> fail \"Target theorem must have the form `\u03a0 x y z, a \u2194 b`\"\n\n/--\nAttempts to apply `e`, and if that fails, if `e` is an `iff`,\ntry applying both directions separately.\n-/\nmeta def apply_iff (e : expr) : tactic (list (name \u00d7 expr)) :=\nlet ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in\nap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)\n\nmeta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name \u00d7 expr)) :=\ntactic.apply e cfg <|> (symmetry >> tactic.apply e cfg)\n\nmeta def apply_assumption\n  (asms : tactic (list expr) := local_context)\n  (tac : tactic unit := skip) : tactic unit :=\ndo { ctx \u2190 asms,\n     ctx.any_of (\u03bb H, symm_apply H >> tac) } <|>\ndo { exfalso,\n     ctx \u2190 asms,\n     ctx.any_of (\u03bb H, symm_apply H >> tac) }\n<|> fail \"assumption tactic failed\"\n\nmeta def change_core (e : expr) : option expr \u2192 tactic unit\n| none     := tactic.change e\n| (some h) :=\n  do num_reverted : \u2115 \u2190 revert h,\n     expr.pi n bi d b \u2190 target,\n     tactic.change $ expr.pi n bi e b,\n     intron num_reverted\n\n/--\nassuming olde and newe are defeq when elaborated, replaces occurences of olde with newe at hypothesis h.\n-/\nmeta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=\ndo h \u2190 get_local hyp,\n   tp \u2190 infer_type h,\n   olde \u2190 to_expr olde, newe \u2190 to_expr newe,\n   let repl_tp := tp.replace (\u03bb a n, if a = olde then some newe else none),\n   change_core repl_tp (some h)\n\nopen nat\n\nmeta def solve_by_elim_aux (discharger : tactic unit) (asms : tactic (list expr))  : \u2115 \u2192 tactic unit\n| 0 := done\n| (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n)\n\nmeta structure by_elim_opt :=\n  (all_goals : bool := ff)\n  (discharger : tactic unit := done)\n  (assumptions : tactic (list expr) := local_context)\n  (max_rep : \u2115 := 3)\n\nmeta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit :=\ndo\n  tactic.fail_if_no_goals,\n  (if opt.all_goals then id else focus1) $\n    solve_by_elim_aux opt.discharger opt.assumptions opt.max_rep\n\nmeta def metavariables : tactic (list expr) :=\ndo r \u2190 result,\n   pure (r.list_meta_vars)\n\n/-- Succeeds only if the current goal is a proposition. -/\nmeta def propositional_goal : tactic unit :=\ndo goals \u2190 get_goals,\n   p \u2190 is_proof goals.head,\n   guard p\n\nmeta def triv' : tactic unit := do c \u2190 mk_const `trivial, exact c reducible\n\nvariable {\u03b1 : Type}\n\nprivate meta def iterate_aux (t : tactic \u03b1) : list \u03b1 \u2192 tactic (list \u03b1)\n| L := (do r \u2190 t, iterate_aux (r :: L)) <|> return L\n\n/-- Apply a tactic as many times as possible, collecting the results in a list. -/\nmeta def iterate' (t : tactic \u03b1) : tactic (list \u03b1) :=\nlist.reverse <$> iterate_aux t []\n\n/-- Like iterate', but fail if the tactic does not succeed at least once. -/\nmeta def iterate1 (t : tactic \u03b1) : tactic (\u03b1 \u00d7 list \u03b1) :=\ndo r \u2190 decorate_ex \"iterate1 failed: tactic did not succeed\" t,\n   L \u2190 iterate' t,\n   return (r, L)\n\nmeta def intros1 : tactic (list expr) :=\niterate1 intro1 >>= \u03bb p, return (p.1 :: p.2)\n\n/-- `successes` invokes each tactic in turn, returning the list of successful results. -/\nmeta def successes (tactics : list (tactic \u03b1)) : tactic (list \u03b1) :=\nlist.filter_map id <$> monad.sequence (tactics.map (\u03bb t, try_core t))\n\n/-- Return target after instantiating metavars and whnf -/\nprivate meta def target' : tactic expr :=\ntarget >>= instantiate_mvars >>= whnf\n\n/--\nJust like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor.\nHowever it does not reorder goals or invoke `auto_param` tactics.\n-/\n-- FIXME check if we can remove `auto_param := ff`\nmeta def fsplit : tactic unit :=\ndo [c] \u2190 target' >>= get_constructors_for | tactic.fail \"fsplit tactic failed, target is not an inductive datatype with only one constructor\",\n   mk_const c >>= \u03bb e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip\n\nrun_cmd add_interactive [`fsplit]\n\n/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`\n    succeeds, clears the old hypothesis. -/\nmeta def injections_and_clear : tactic unit :=\ndo l \u2190 local_context,\n   results \u2190 successes $ l.map $ \u03bb e, injection e >> clear e,\n   when (results.empty) (fail \"could not use `injection` then `clear` on any hypothesis\")\n\nrun_cmd add_interactive [`injections_and_clear]\n\nmeta def note_anon (e : expr) : tactic unit :=\ndo n \u2190 get_unused_name \"lh\",\n   note n none e, skip\n\n/-- `find_local t` returns a local constant with type t, or fails if none exists. -/\nmeta def find_local (t : pexpr) : tactic expr :=\ndo t' \u2190 to_expr t,\n   prod.snd <$> solve_aux t' assumption\n\n/-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values\nof the previous local constants. `l` is a list of local constants and their values. -/\nmeta def dependent_pose_core (l : list (expr \u00d7 expr)) : tactic unit := do\n  let lc := l.map prod.fst,\n  let lm := l.map (\u03bb\u27e8l, v\u27e9, (l.local_uniq_name, v)),\n  t \u2190 target,\n  new_goal \u2190 mk_meta_var (t.pis lc),\n  old::other_goals \u2190 get_goals,\n  set_goals (old :: new_goal :: other_goals),\n  exact ((new_goal.mk_app lc).instantiate_locals lm),\n  return ()\n\n/-- like `mk_local_pis` but translating into weak head normal form before checking if it is a \u03a0. -/\nmeta def mk_local_pis_whnf : expr \u2192 tactic (list expr \u00d7 expr) | e := do\n(expr.pi n bi d b) \u2190 whnf e | return ([], e),\np \u2190 mk_local' n bi d,\n(ps, r) \u2190 mk_local_pis (expr.instantiate_var b p),\nreturn ((p :: ps), r)\n\n/-- Changes `(h : \u2200xs, \u2203a:\u03b1, p a) \u22a2 g` to `(d : \u2200xs, a) (s : \u2200xs, p (d xs) \u22a2 g` -/\nmeta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do\n  t \u2190 infer_type h,\n  (ctxt, t) \u2190 mk_local_pis_whnf t,\n  `(@Exists %%\u03b1 %%p) \u2190 whnf t transparency.all | fail \"expected a term of the shape \u2200xs, \u2203a, p xs a\",\n  \u03b1_t \u2190 infer_type \u03b1,\n  expr.sort u \u2190 whnf \u03b1_t transparency.all,\n  value \u2190 mk_local_def data (\u03b1.pis ctxt),\n  t' \u2190 head_beta (p.app (value.mk_app ctxt)),\n  spec \u2190 mk_local_def spec (t'.pis ctxt),\n  dependent_pose_core [\n    (value, ((((expr.const `classical.some [u]).app \u03b1).app p).app (h.mk_app ctxt)).lambdas ctxt),\n    (spec, ((((expr.const `classical.some_spec [u]).app \u03b1).app p).app (h.mk_app ctxt)).lambdas ctxt)],\n  try (tactic.clear h),\n  intro1,\n  intro1\n\n/-- Changes `(h : \u2200xs, \u2203as, p as) \u22a2 g` to a list of functions `as`, an a final hypothesis on `p as` -/\nmeta def choose : expr \u2192 list name \u2192 tactic unit\n| h [] := fail \"expect list of variables\"\n| h [n] := do\n  cnt \u2190 revert h,\n  intro n,\n  intron (cnt - 1),\n  return ()\n| h (n::ns) := do\n  v \u2190 get_unused_name >>= choose1 h n,\n  choose v ns\n\n/-- This makes sure that the execution of the tactic does not change the tactic state.\n    This can be helpful while using rewrite, apply, or expr munging.\n    Remember to instantiate your metavariables before you're done! -/\nmeta def lock_tactic_state {\u03b1} (t : tactic \u03b1) : tactic \u03b1\n| s := match t s with\n       | result.success a s' := result.success a s\n       | result.exception msg pos s' := result.exception msg pos s\nend\n\n/--\nHole command used to fill in a structure's field when specifying an instance.\n\nIn the following:\n\n```\ninstance : monad id :=\n{! !}\n```\n\ninvoking hole command `Instance Stub` produces:\n\n```\ninstance : monad id :=\n{ map := _,\n  map_const := _,\n  pure := _,\n  seq := _,\n  seq_left := _,\n  seq_right := _,\n  bind := _ }\n```\n-/\n@[hole_command] meta def instance_stub : hole_command :=\n{ name := \"Instance Stub\",\n  descr := \"Generate a skeleton for the structure under construction.\",\n  action := \u03bb _,\n  do tgt \u2190 target >>= whnf,\n     let cl := tgt.get_app_fn.const_name,\n     env \u2190 get_env,\n     fs \u2190 expanded_field_list cl,\n     let fs := fs.map prod.snd,\n     let fs := format.intercalate (\",\\n  \" : format) $ fs.map (\u03bb fn, format!\"{fn} := _\"),\n     let out := format.to_string format!\"{{ {fs} }\",\n     return [(out,\"\")] }\n\nmeta def strip_prefix' (n : name) : list string \u2192 name \u2192 tactic name\n| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous\n| s (name.mk_string a p) :=\n  do let n' := s.foldl (flip name.mk_string) name.anonymous,\n     do { n'' \u2190 tactic.resolve_constant n',\n          if n'' = n\n            then pure n'\n            else strip_prefix' (a :: s) p }\n     <|> strip_prefix' (a :: s) p\n| s (name.mk_numeral a p) := interaction_monad.failed\n\nmeta def strip_prefix : name \u2192 tactic name\n| n@(name.mk_string a a_1) := strip_prefix' n [a] a_1\n| _ := interaction_monad.failed\n\nmeta def is_default_local : expr \u2192 bool\n| (expr.local_const _ _ binder_info.default _) := tt\n| _ := ff\n\nmeta def mk_patterns (t : expr) : tactic (list format) :=\ndo let cl := t.get_app_fn.const_name,\n   env \u2190 get_env,\n   let fs := env.constructors_of cl,\n   fs.mmap $ \u03bb f,\n     do { (vs,_) \u2190 mk_const f >>= infer_type >>= mk_local_pis,\n          let vs := vs.filter (\u03bb v, is_default_local v),\n          vs \u2190 vs.mmap (\u03bb v,\n            do v' \u2190 get_unused_name v.local_pp_name,\n               pose v' none `(()),\n               pure v' ),\n          vs.mmap' $ \u03bb v, get_local v >>= clear,\n          let args := list.intersperse (\" \" : format) $ vs.map to_fmt,\n          f \u2190 strip_prefix f,\n          if args.empty\n            then pure $ format!\"| {f} := _\\n\"\n            else pure format!\"| ({f} {format.join args}) := _\\n\" }\n\n/--\nHole command used to generate a `match` expression.\n\nIn the following:\n\n```\nmeta def foo (e : expr) : tactic unit :=\n{! e !}\n```\n\ninvoking hole command `Match Stub` produces:\n\n```\nmeta def foo (e : expr) : tactic unit :=\nmatch e with\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\nend\n```\n-/\n@[hole_command] meta def match_stub : hole_command :=\n{ name := \"Match Stub\",\n  descr := \"Generate a list of equations for a `match` expression.\",\n  action := \u03bb es,\n  do [e] \u2190 pure es | fail \"expecting one expression\",\n     e \u2190 to_expr e,\n     t \u2190 infer_type e >>= whnf,\n     fs \u2190 mk_patterns t,\n     e \u2190 pp e,\n     let out := format.to_string format!\"match {e} with\\n{format.join fs}end\\n\",\n     return [(out,\"\")] }\n\n/--\nHole command used to generate a `match` expression.\n\nIn the following:\n\n```\nmeta def foo : {! expr \u2192 tactic unit !} -- `:=` is omitted\n```\n\ninvoking hole command `Equations Stub` produces:\n\n```\nmeta def foo : expr \u2192 tactic unit\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\nA similar result can be obtained by invoking `Equations Stub` on the following:\n\n```\nmeta def foo : expr \u2192 tactic unit := -- do not forget to write `:=`!!\n{! !}\n```\n\n```\nmeta def foo : expr \u2192 tactic unit := -- don't forget to erase `:=`!!\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\n-/\n@[hole_command] meta def eqn_stub : hole_command :=\n{ name := \"Equations Stub\",\n  descr := \"Generate a list of equations for a recursive definition.\",\n  action := \u03bb es,\n  do t \u2190 match es with\n         | [t] := to_expr t\n         | [] := target\n         | _ := fail \"expecting one type\"\n         end,\n     e \u2190 whnf t,\n     (v :: _,_) \u2190 mk_local_pis e | fail \"expecting a Pi-type\",\n     t' \u2190 infer_type v,\n     fs \u2190 mk_patterns t',\n     t \u2190 pp t,\n     let out :=\n         if es.empty then\n           format.to_string format!\"-- do not forget to erase `:=`!!\\n{format.join fs}\"\n           else format.to_string format!\"{t}\\n{format.join fs}\",\n     return [(out,\"\")] }\n\n/--\nThis command lists the constructors that can be used to satisfy the expected type.\n\nWhen used in the following hole:\n\n```\ndef foo : \u2124 \u2295 \u2115 :=\n{! !}\n```\n\nthe command will produce:\n\n```\ndef foo : \u2124 \u2295 \u2115 :=\n{! sum.inl, sum.inr !}\n```\n\nand will display:\n\n```\nsum.inl : \u2124 \u2192 \u2124 \u2295 \u2115\n\nsum.inr : \u2115 \u2192 \u2124 \u2295 \u2115\n```\n\n-/\n@[hole_command] meta def list_constructors_hole : hole_command :=\n{ name := \"List Constructors\",\n  descr := \"Show the list of constructors of the expected type.\",\n  action := \u03bb es,\n  do t \u2190 target >>= whnf,\n     (_,t) \u2190 mk_local_pis t,\n     let cl := t.get_app_fn.const_name,\n     let args := t.get_app_args,\n     env \u2190 get_env,\n     let cs := env.constructors_of cl,\n     ts \u2190 cs.mmap $ \u03bb c,\n       do { e \u2190 mk_const c,\n            t \u2190 infer_type (e.mk_app args) >>= pp,\n            c \u2190 strip_prefix c,\n            pure format!\"\\n{c} : {t}\\n\" },\n     fs \u2190 format.intercalate \", \" <$> cs.mmap (strip_prefix >=> pure \u2218 to_fmt),\n     let out := format.to_string format!\"{{! {fs} !}\",\n     trace (format.join ts).to_string,\n     return [(out,\"\")] }\n\nmeta def classical : tactic unit :=\ndo h \u2190 get_unused_name `_inst,\n   mk_const `classical.prop_decidable >>= note h none,\n   reset_instance_cache\n\nopen expr\n\nmeta def add_prime : name \u2192 name\n| (name.mk_string s p) := name.mk_string (s ++ \"'\") p\n| n := (name.mk_string \"x'\" n)\n\nmeta def mk_comp (v : expr) : expr \u2192 tactic expr\n| (app f e) :=\n  if e = v then pure f\n  else do\n    guard (\u00ac v.occurs f) <|> fail \"bad guard\",\n    e' \u2190 mk_comp e >>= instantiate_mvars,\n    f \u2190 instantiate_mvars f,\n    mk_mapp ``function.comp [none,none,none,f,e']\n| e :=\n  do guard (e = v),\n     t \u2190 infer_type e,\n     mk_mapp ``id [t]\n\nmeta def mk_higher_order_type : expr \u2192 tactic expr\n| (pi n bi d b@(pi _ _ _ _)) :=\n  do v \u2190 mk_local_def n d,\n     let b' := (b.instantiate_var v),\n     (pi n bi d \u2218 flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'\n| (pi n bi d b) :=\n  do v \u2190 mk_local_def n d,\n     let b' := (b.instantiate_var v),\n     (l,r) \u2190 match_eq b' <|> fail format!\"not an equality {b'}\",\n     l' \u2190 mk_comp v l,\n     r' \u2190 mk_comp v r,\n     mk_app ``eq [l',r']\n | e := failed\n\nopen lean.parser interactive.types\n\n@[user_attribute]\nmeta def higher_order_attr : user_attribute unit (option name) :=\n{ name := `higher_order,\n  parser := optional ident,\n  descr :=\n\"From a lemma of the shape `f (g x) = h x` derive an auxiliary lemma of the\nform `f \u2218 g = h` for reasoning about higher-order functions.\",\n  after_set := some $ \u03bb lmm _ _,\n    do env  \u2190 get_env,\n       decl \u2190 env.get lmm,\n       let num := decl.univ_params.length,\n       let lvls := (list.iota num).map (`l).append_after,\n       let l : expr := expr.const lmm $ lvls.map level.param,\n       t \u2190 infer_type l >>= instantiate_mvars,\n       t' \u2190 mk_higher_order_type t,\n       (_,pr) \u2190 solve_aux t' $ do {\n         intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },\n       pr \u2190 instantiate_mvars pr,\n       lmm' \u2190 higher_order_attr.get_param lmm,\n       lmm' \u2190 (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure (add_prime lmm),\n       add_decl $ declaration.thm lmm' lvls t' (pure pr),\n       copy_attribute `simp lmm tt lmm',\n       copy_attribute `functor_norm lmm tt lmm' }\n\nattribute [higher_order map_comp_pure] map_pure\n\nprivate meta def tactic.use_aux (h : pexpr) : tactic unit :=\n(focus1 (refine h >> done)) <|> (fconstructor >> tactic.use_aux)\n\nmeta def tactic.use (l : list pexpr) : tactic unit :=\nfocus1 $ l.mmap' $ \u03bb h, tactic.use_aux h <|> fail format!\"failed to instantiate goal with {h}\"\n\nmeta def clear_aux_decl_aux : list expr \u2192 tactic unit\n| []     := skip\n| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l\n\nmeta def clear_aux_decl : tactic unit :=\nlocal_context >>= clear_aux_decl_aux\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/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368159568461, "lm_q2_score": 0.06656919128531262, "lm_q1q2_score": 0.02611754454970178}}
{"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\u00f6lzl, 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 \u2192 Type v} {\u03b1 : 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 $ \u2200 {\u03b1 \u03b2}, c \u03b1 \u2192 c \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 Prop) :=\n(hom_id : \u2200 {\u03b1} (ia : c \u03b1), hom ia ia id)\n(hom_comp : \u2200 {\u03b1 \u03b2 \u03b3} (ia : c \u03b1) (ib : c \u03b2) (ic : c \u03b3) {f g}, hom ia ib f \u2192 hom ib ic g \u2192 hom ia ic (g \u2218 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 \u2192 Type v) : Type (max (u+1) v) :=\n(\u03b1 : Type u)\n(str : c \u03b1)\n\ndef mk_ob {c : Type u \u2192 Type v} (\u03b1 : Type u) [str : c \u03b1] : bundled c := \u27e8\u03b1, str\u27e9\n\nnamespace bundled\n\ninstance : has_coe_to_sort (bundled c) :=\n{ S := Type u, coe := bundled.\u03b1 }\n\n/-- Map over the bundled structure -/\ndef map (f : \u2200 {\u03b1}, c \u03b1 \u2192 d \u03b1) (b : bundled c) : bundled d :=\n\u27e8b.\u03b1, f b.str\u27e9\n\nsection concrete_category\nvariables (hom : \u2200 {\u03b1 \u03b2 : Type u}, c \u03b1 \u2192 c \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 Prop)\nvariables [h : concrete_category @hom]\ninclude h\n\ninstance : category (bundled c) :=\n{ hom   := \u03bb a b, subtype (hom a.2 b.2),\n  id    := \u03bb a, \u27e8@id a.1, h.hom_id a.2\u27e9,\n  comp  := \u03bb a b c f g, \u27e8g.1 \u2218 f.1, h.hom_comp a.2 b.2 c.2 f.2 g.2\u27e9 }\n\nvariables {X Y Z : bundled c}\n\n@[simp] lemma concrete_category_id (X : bundled c) : subtype.val (\ud835\udfd9 X) = id :=\nrfl\n\n@[simp] lemma concrete_category_comp (f : X \u27f6 Y) (g : Y \u27f6 Z) :\n  subtype.val (f \u226b g) = g.val \u2218 f.val :=\nrfl\n\ninstance : has_coe_to_fun (X \u27f6 Y) :=\n{ F   := \u03bb f, X \u2192 Y,\n  coe := \u03bb f, f.1 }\n\n@[simp] lemma bundled_hom_coe {X Y : bundled c} (val : X \u2192 Y) (prop) (x : X) :\n  (\u27e8val, prop\u27e9 : X \u27f6 Y) x = val x := rfl\n\nend concrete_category\n\nend bundled\n\ndef concrete_functor\n  {C : Type u \u2192 Type v} {hC : \u2200{\u03b1 \u03b2}, C \u03b1 \u2192 C \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 Prop} [concrete_category @hC]\n  {D : Type u \u2192 Type v} {hD : \u2200{\u03b1 \u03b2}, D \u03b1 \u2192 D \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 Prop} [concrete_category @hD]\n  (m : \u2200{\u03b1}, C \u03b1 \u2192 D \u03b1) (h : \u2200{\u03b1 \u03b2} {ia : C \u03b1} {ib : C \u03b2} {f}, hC ia ib f \u2192 hD (m ia) (m ib) f) :\n  bundled C \u2964 bundled D :=\n{ obj := bundled.map @m,\n  map := \u03bb X Y f, \u27e8 f, h f.2 \u27e9}\n\nsection forget\nvariables {C : Type u \u2192 Type v} {hom : \u2200\u03b1 \u03b2, C \u03b1 \u2192 C \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 Prop} [i : concrete_category hom]\ninclude i\n\n/-- The forgetful functor from a bundled category to `Type`. -/\ndef forget : bundled C \u2964 Type u := { obj := bundled.\u03b1, map := \u03bba b h, h.1 }\n\ninstance forget.faithful : faithful (forget : bundled C \u2964 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 \u2964 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 \u2964 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 \u2964 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 \ud835\udfed\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 \u2964 C`. -/\ndef forget (C : Type u) [category C] : Monad C \u2964 C \u2964 C :=\n  functor.mk func fun (_x _x_1 : Monad C) (f : _x \u27f6 _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 \u27f6 N) (g : N \u27f6 L) : monad_hom.to_nat_trans (f \u226b 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 \u03bc_ X) \u226b nat_trans.app \u03bc_ X =\n  nat_trans.app \u03bc_ (functor.obj (func M) X) \u226b nat_trans.app \u03bc_ 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 \ud835\udfed\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 \u2964 C`. -/\ndef forget (C : Type u) [category C] : Comonad C \u2964 C \u2964 C :=\n  functor.mk func fun (_x _x_1 : Comonad C) (f : _x \u27f6 _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 \u27f6 N) (g : N \u27f6 L) : comonad_hom.to_nat_trans (f \u226b 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 \u03b4_ X \u226b functor.map (func M) (nat_trans.app \u03b4_ X) =\n  nat_trans.app \u03b4_ X \u226b nat_trans.app \u03b4_ (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": "/-\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 algebra.group.defs\nimport logic.equiv.basic\n\nuniverses u v w u\u2080 u\u2081 v\u2080 v\u2081\n\nstructure writer_t (\u03c9 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) : Type (max u v) :=\n(run : m (\u03b1 \u00d7 \u03c9))\n\n@[reducible] def writer (\u03c9 : Type u) := writer_t \u03c9 id\n\nattribute [pp_using_anonymous_constructor] writer_t\n\nnamespace writer_t\nsection\n  variable  {\u03c9 : Type u}\n  variable  {m : Type u \u2192 Type v}\n  variable  [monad m]\n  variables {\u03b1 \u03b2 : Type u}\n  open function\n\n  @[ext]\n  protected lemma ext (x x' : writer_t \u03c9 m \u03b1)\n    (h : x.run = x'.run) :\n    x = x' := by cases x; cases x'; congr; apply h\n\n  @[inline] protected def tell (w : \u03c9) : writer_t \u03c9 m punit :=\n  \u27e8pure (punit.star, w)\u27e9\n\n  @[inline] protected def listen : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m (\u03b1 \u00d7 \u03c9)\n  | \u27e8 cmd \u27e9 := \u27e8 (\u03bb x : \u03b1 \u00d7 \u03c9, ((x.1,x.2),x.2)) <$> cmd \u27e9\n\n  @[inline] protected def pass : writer_t \u03c9 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 writer_t \u03c9 m \u03b1\n  | \u27e8 cmd \u27e9 := \u27e8 uncurry (uncurry $ \u03bb x (f : \u03c9 \u2192 \u03c9) w, (x,f w)) <$> cmd \u27e9\n\n  @[inline] protected def pure [has_one \u03c9] (a : \u03b1) : writer_t \u03c9 m \u03b1 :=\n  \u27e8 pure (a,1) \u27e9\n\n  @[inline] protected def bind [has_mul \u03c9] (x : writer_t \u03c9 m \u03b1) (f : \u03b1 \u2192 writer_t \u03c9 m \u03b2) :\n    writer_t \u03c9 m \u03b2 :=\n  \u27e8 do x  \u2190 x.run,\n       x' \u2190 (f x.1).run,\n       pure (x'.1,x.2 * x'.2) \u27e9\n\n  instance [has_one \u03c9] [has_mul \u03c9] : monad (writer_t \u03c9 m) :=\n  { pure := \u03bb \u03b1, writer_t.pure, bind := \u03bb \u03b1 \u03b2, writer_t.bind }\n\n  instance [monoid \u03c9] [is_lawful_monad m] : is_lawful_monad (writer_t \u03c9 m) :=\n  { id_map := by { intros, cases x, simp [(<$>),writer_t.bind,writer_t.pure] },\n    pure_bind := by { intros, simp [has_pure.pure,writer_t.pure,(>>=),writer_t.bind], ext; refl },\n    bind_assoc := by { intros, simp [(>>=),writer_t.bind,mul_assoc] with functor_norm } }\n\n  @[inline] protected def lift [has_one \u03c9] (a : m \u03b1) : writer_t \u03c9 m \u03b1 :=\n  \u27e8 flip prod.mk 1 <$> a \u27e9\n\n  instance (m) [monad m] [has_one \u03c9] : has_monad_lift m (writer_t \u03c9 m) :=\n  \u27e8 \u03bb \u03b1, writer_t.lift  \u27e9\n\n  @[inline] protected def monad_map {m m'} [monad m] [monad m'] {\u03b1} (f : \u03a0 {\u03b1}, m \u03b1 \u2192 m' \u03b1) :\n    writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m' \u03b1 :=\n  \u03bb x, \u27e8 f x.run \u27e9\n\n  instance (m m') [monad m] [monad m'] : monad_functor m m' (writer_t \u03c9 m) (writer_t \u03c9 m') :=\n  \u27e8@writer_t.monad_map \u03c9 m m' _ _\u27e9\n\n  @[inline] protected def adapt {\u03c9' : Type u} {\u03b1 : Type u} (f : \u03c9 \u2192 \u03c9') :\n    writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9' m \u03b1 :=\n  \u03bb x, \u27e8prod.map id f <$> x.run\u27e9\n\n  instance (\u03b5) [has_one \u03c9] [monad m] [monad_except \u03b5 m] : monad_except \u03b5 (writer_t \u03c9 m) :=\n  { throw := \u03bb \u03b1, writer_t.lift \u2218 throw,\n    catch := \u03bb \u03b1 x c, \u27e8catch x.run (\u03bb e, (c e).run)\u27e9 }\nend\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 (\u03c1 : out_param (Type u)) (n : Type u \u2192 Type u) :=\n(lift {\u03b1 : Type u} : (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1) \u2192 n \u03b1)\n```\n-/\nclass monad_writer (\u03c9 : out_param (Type u)) (m : Type u \u2192 Type v) :=\n(tell (w : \u03c9) : m punit)\n(listen {\u03b1} : m \u03b1 \u2192 m (\u03b1 \u00d7 \u03c9))\n(pass {\u03b1 : Type u} : m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 m \u03b1)\n\nexport monad_writer\n\ninstance {\u03c9 : Type u} {m : Type u \u2192 Type v} [monad m] : monad_writer \u03c9 (writer_t \u03c9 m) :=\n{ tell := writer_t.tell,\n  listen := \u03bb \u03b1, writer_t.listen,\n  pass := \u03bb \u03b1, writer_t.pass }\n\ninstance {\u03c9 \u03c1 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (reader_t \u03c1 m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, listen (cmd r) \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, pass (cmd r) \u27e9 }\n\ndef swap_right {\u03b1 \u03b2 \u03b3} : (\u03b1 \u00d7 \u03b2) \u00d7 \u03b3 \u2192 (\u03b1 \u00d7 \u03b3) \u00d7 \u03b2\n| \u27e8\u27e8x,y\u27e9,z\u27e9 := ((x,z),y)\n\ninstance {\u03c9 \u03c3 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (state_t \u03c3 m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, swap_right <$> listen (cmd r) \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, pass (swap_right <$> cmd r) \u27e9 }\nopen function\n\ndef except_t.pass_aux {\u03b5 \u03b1 \u03c9} : except \u03b5 (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 except \u03b5 \u03b1 \u00d7 (\u03c9 \u2192 \u03c9)\n| (except.error a) := (except.error a,id)\n| (except.ok (x,y)) := (except.ok x,y)\n\ninstance {\u03c9 \u03b5 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (except_t \u03b5 m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 uncurry (\u03bb x y, flip prod.mk y <$> x) <$> listen cmd \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 pass (except_t.pass_aux <$> cmd) \u27e9 }\n\ndef option_t.pass_aux {\u03b1 \u03c9} : option (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 option \u03b1 \u00d7 (\u03c9 \u2192 \u03c9)\n| none := (none ,id)\n| (some (x,y)) := (some x,y)\n\ninstance {\u03c9 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (option_t m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 uncurry (\u03bb x y, flip prod.mk y <$> x) <$> listen cmd \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 pass (option_t.pass_aux <$> cmd) \u27e9 }\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 (\u03c1 \u03c1' : out_param (Type u)) (n n' : Type u \u2192 Type u) :=\n(map {\u03b1 : Type u} :\n  (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1 \u2192 reader_t \u03c1' m \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1)\n```\n-/\nclass monad_writer_adapter (\u03c9 \u03c9' : out_param (Type u)) (m m' : Type u \u2192 Type v) :=\n(adapt_writer {\u03b1 : Type u} : (\u03c9 \u2192 \u03c9') \u2192 m \u03b1 \u2192 m' \u03b1)\nexport monad_writer_adapter (adapt_writer)\n\nsection\nvariables {\u03c9 \u03c9' : Type u} {m m' : Type u \u2192 Type v}\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] -/\n@[nolint dangerous_instance, priority 100]\ninstance monad_writer_adapter_trans {n n' : Type u \u2192 Type v} [monad_writer_adapter \u03c9 \u03c9' m m']\n  [monad_functor m m' n n'] : monad_writer_adapter \u03c9 \u03c9' n n' :=\n\u27e8\u03bb \u03b1 f, monad_map (\u03bb \u03b1, (adapt_writer f : m \u03b1 \u2192 m' \u03b1))\u27e9\n\ninstance [monad m] : monad_writer_adapter \u03c9 \u03c9' (writer_t \u03c9 m) (writer_t \u03c9' m) :=\n\u27e8\u03bb \u03b1, writer_t.adapt\u27e9\nend\n\ninstance (\u03c9 : Type u) (m out) [monad_run out m] : monad_run (\u03bb \u03b1, out (\u03b1 \u00d7 \u03c9)) (writer_t \u03c9 m) :=\n\u27e8\u03bb \u03b1 x, run $ x.run \u27e9\n\n/-- reduce the equivalence between two writer monads to the equivalence between\ntheir underlying monad -/\ndef writer_t.equiv {m\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081}\n  {\u03b1\u2081 \u03c9\u2081 : Type u\u2080} {\u03b1\u2082 \u03c9\u2082 : Type u\u2081} (F : (m\u2081 (\u03b1\u2081 \u00d7 \u03c9\u2081)) \u2243 (m\u2082 (\u03b1\u2082 \u00d7 \u03c9\u2082))) :\n  writer_t \u03c9\u2081 m\u2081 \u03b1\u2081 \u2243 writer_t \u03c9\u2082 m\u2082 \u03b1\u2082 :=\n{ to_fun := \u03bb \u27e8f\u27e9, \u27e8F f\u27e9,\n  inv_fun := \u03bb \u27e8f\u27e9, \u27e8F.symm f\u27e9,\n  left_inv := \u03bb \u27e8f\u27e9, congr_arg writer_t.mk $ F.left_inv _,\n  right_inv := \u03bb \u27e8f\u27e9, congr_arg writer_t.mk $ F.right_inv _ }\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/monad/writer.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204329, "lm_q2_score": 0.055005285195222284, "lm_q1q2_score": 0.026000089438576096}}
{"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.Eqns\nimport Lean.Meta.Tactic.Split\nimport Lean.Meta.Tactic.Simp.Main\nimport Lean.Meta.Tactic.Apply\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Eqns\nimport Lean.Elab.PreDefinition.Structural.Basic\n\nnamespace Lean.Elab\nopen Meta\nopen Eqns\n\nnamespace Structural\n\nstructure EqnInfo extends EqnInfoCore where\n  recArgPos   : Nat\n  deriving Inhabited\n\nprivate partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do\n  trace[Elab.definition.structural.eqns] \"proving: {type}\"\n  withNewMCtxDepth do\n    let main \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let (_, mvarId) \u2190 main.mvarId!.intros\n    unless (\u2190 tryURefl mvarId) do -- catch easy cases\n      go (\u2190 deltaLHS mvarId)\n    instantiateMVars main\nwhere\n  go (mvarId : MVarId) : MetaM Unit := do\n    trace[Elab.definition.structural.eqns] \"step\\n{MessageData.ofGoal mvarId}\"\n    if (\u2190 tryURefl mvarId) then\n      return ()\n    else if (\u2190 tryContradiction mvarId) then\n      return ()\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpIf? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 whnfReducibleLHS? mvarId then\n      go mvarId\n    else match (\u2190 simpTargetStar mvarId {}).1 with\n      | TacticResultCNM.closed => return ()\n      | TacticResultCNM.modified mvarId => go mvarId\n      | TacticResultCNM.noChange =>\n        if let some mvarId \u2190 deltaRHS? mvarId declName then\n          go mvarId\n        else if let some mvarIds \u2190 casesOnStuckLHS? mvarId then\n          mvarIds.forM go\n        else if let some mvarIds \u2190 splitTarget? mvarId then\n          mvarIds.forM go\n        else\n          throwError \"failed to generate equational theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n\ndef mkEqns (info : EqnInfo) : MetaM (Array Name) :=\n  withOptions (tactic.hygienic.set \u00b7 false) do\n  let eqnTypes \u2190 withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do\n    let us := info.levelParams.map mkLevelParam\n    let target \u2190 mkEq (mkAppN (Lean.mkConst info.declName us) xs) body\n    let goal \u2190 mkFreshExprSyntheticOpaqueMVar target\n    mkEqnTypes #[info.declName] goal.mvarId!\n  let baseName := mkPrivateName (\u2190 getEnv) info.declName\n  let mut thmNames := #[]\n  for i in [: eqnTypes.size] do\n    let type := eqnTypes[i]!\n    trace[Elab.definition.structural.eqns] \"{eqnTypes[i]!}\"\n    let name := baseName ++ (`_eq).appendIndexAfter (i+1)\n    thmNames := thmNames.push name\n    let value \u2190 mkProof info.declName type\n    let (type, value) \u2190 removeUnusedEqnHypotheses type value\n    addDecl <| Declaration.thmDecl {\n      name, type, value\n      levelParams := info.levelParams\n    }\n  return thmNames\n\nbuiltin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo \u2190 mkMapDeclarationExtension\n\ndef registerEqnsInfo (preDef : PreDefinition) (recArgPos : Nat) : CoreM Unit := do\n  modifyEnv fun env => eqnInfoExt.insert env preDef.declName { preDef with recArgPos }\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  if let some info := eqnInfoExt.find? (\u2190 getEnv) declName then\n    mkEqns info\n  else\n    return none\n\ndef getUnfoldFor? (declName : Name) : MetaM (Option Name) := do\n  let env \u2190 getEnv\n  Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (\u00b7.toEqnInfoCore)\n\n@[export lean_get_structural_rec_arg_pos]\ndef getStructuralRecArgPosImp? (declName : Name) : CoreM (Option Nat) := do\n  let some info := eqnInfoExt.find? (\u2190 getEnv) declName | return none\n  return some info.recArgPos\n\nbuiltin_initialize\n  registerGetEqnsFn getEqnsFor?\n  registerGetUnfoldEqnFn getUnfoldFor?\n  registerTraceClass `Elab.definition.structural.eqns\n\nend Structural\nend Lean.Elab\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/Structural/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.05834584634253716, "lm_q1q2_score": 0.02599479779248094}}
{"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-- \u03b1 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 {\u03b1 : 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 \u2192 itactic \u2192 tactic unit\n| n t := do goals \u2190 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 \u2190 get_goals,\n            set_goals (earlier_goals ++ new_goals ++ later_goals)\nend interactive\n\ninductive tactic_script (\u03b1 : Type) : Type\n| base : \u03b1 \u2192 tactic_script\n| work (index : \u2115) (first : \u03b1) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string \u2192 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 := \u03bb s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := \u03bb s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr \u2192 tactic \u03b1) (g : expr) : tactic \u03b1 :=\ndo\n  type \u2190 infer_type g,\n  is_lemma \u2190 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 \u2190 mk_meta_var type,\n    a \u2190 tac m,\n    do {\n      val \u2190 instantiate_mvars m,\n      guard (val.list_meta_vars = []),\n      c  \u2190 new_aux_decl_name,\n      gs \u2190 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 {\u03b1} (tac : tactic \u03b1)\nwith chain_single : expr \u2192 tactic (\u03b1 \u00d7 list (tactic_script \u03b1)) | g :=\ndo set_goals [g],\n  a \u2190 tac,\n  l \u2190 get_goals >>= chain_many,\n  return (a, l)\nwith chain_many : list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] := return []\n| [g] := do {\n  (a, l) \u2190 chain_single g,\n  return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr \u2192 list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do {\n  (a, l) \u2190 abstract_if_success chain_single g,\n  new_goals \u2190 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' \u2190 chain_many current_goals,\n  return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {\u03b1 : Type} [has_to_string (tactic_script \u03b1)] (tactics : list (tactic \u03b1)) : tactic (list string) :=\ndo results \u2190 (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 \u03b1)] [has_to_format \u03b1]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic \u03b1) : tactic \u03b1 :=\ndo tgt \u2190 target,\n   r \u2190 t,\n   name \u2190 decl_name,\n   trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n   tgt \u2190 pp tgt,\n   trace format!\"previous target: {tgt}\",\n   trace format!\"tactic result: {r}\",\n   tgt \u2190 try_core target,\n   tgt \u2190 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 \u03b1)) : 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) 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.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Util.ReplaceExpr\n\nnamespace Lean.Compiler\nnamespace CSimp\n\nstructure Entry where\n  fromDeclName : Name\n  toDeclName   : Name\n  thmName      : Name\n  deriving Inhabited\n\nstructure State where\n  map : SMap Name Name := {}\n  thmNames : SSet Name := {}\n  deriving Inhabited\n\ndef State.switch : State \u2192 State\n  | { map, thmNames } => { map := map.switch, thmNames := thmNames.switch }\n\nbuiltin_initialize ext : SimpleScopedEnvExtension Entry State \u2190\n  registerSimpleScopedEnvExtension {\n    initial        := {}\n    addEntry       := fun { map, thmNames } { fromDeclName, toDeclName, thmName } => { map := map.insert fromDeclName toDeclName, thmNames := thmNames.insert thmName }\n    finalizeImport := fun s => s.switch\n  }\n\nprivate def isConstantReplacement? (declName : Name) : CoreM (Option Entry) := do\n  let info \u2190 getConstInfo declName\n  match info.type.eq? with\n  | some (_, Expr.const fromDeclName us .., Expr.const toDeclName vs ..) =>\n    if us == vs then\n      return some { fromDeclName, toDeclName, thmName := declName }\n    else\n      return none\n  | _ => return none\n\ndef add (declName : Name) (kind : AttributeKind) : CoreM Unit := do\n  if let some entry \u2190 isConstantReplacement? declName then\n    ext.add entry kind\n  else\n    throwError \"invalid 'csimp' theorem, only constant replacement theorems (e.g., `@f = @g`) are currently supported.\"\n\nbuiltin_initialize\n  registerBuiltinAttribute {\n    name  := `csimp\n    descr := \"simplification theorem for the compiler\"\n    add   := fun declName stx attrKind => do\n      Attribute.Builtin.ensureNoArgs stx\n      discard <| add declName attrKind\n  }\n\n@[export lean_csimp_replace_constants]\ndef replaceConstants (env : Environment) (e : Expr) : Expr :=\n  let s := ext.getState env\n  e.replace fun e =>\n    if e.isConst then\n      match s.map.find? e.constName! with\n      | some declNameNew => some (mkConst declNameNew e.constLevels!)\n      | none => none\n    else\n      none\n\nend CSimp\n\ndef hasCSimpAttribute (env : Environment) (declName : Name) : Bool :=\n  CSimp.ext.getState env |>.thmNames.contains declName\n\nend Lean.Compiler\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/CSimpAttr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.0685374916050527, "lm_q1q2_score": 0.02587569041831887}}
{"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 {\u03b1 : Type u_1} (x : Option \u03b1) : option.traverse id.mk x = x :=\n  option.cases_on x (Eq.refl (option.traverse id.mk none))\n    fun (x : \u03b1) => Eq.refl (option.traverse id.mk (some x))\n\ntheorem option.comp_traverse {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F]\n    [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {\u03b1 : Type u_1} {\u03b2 : Type u}\n    {\u03b3 : Type u} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : Option \u03b1) :\n    option.traverse (functor.comp.mk \u2218 Functor.map f \u2218 g) x =\n        functor.comp.mk (option.traverse f <$> option.traverse g x) :=\n  sorry\n\ntheorem option.traverse_eq_map_id {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 \u03b2) (x : Option \u03b1) :\n    traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\n  option.cases_on x (Eq.refl (traverse (id.mk \u2218 f) none))\n    fun (x : \u03b1) => Eq.refl (traverse (id.mk \u2218 f) (some x))\n\ntheorem option.naturality {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F]\n    [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n    (\u03b7 : applicative_transformation F G) {\u03b1 : Type u_1} {\u03b2 : Type u} (f : \u03b1 \u2192 F \u03b2) (x : Option \u03b1) :\n    coe_fn \u03b7 (Option \u03b2) (option.traverse f x) = option.traverse (coe_fn \u03b7 \u03b2 \u2218 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 {\u03b1 : Type u_1} (xs : List \u03b1) : list.traverse id.mk xs = xs := sorry\n\nprotected theorem comp_traverse {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F]\n    [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {\u03b1 : Type u_1} {\u03b2 : Type u}\n    {\u03b3 : Type u} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : List \u03b1) :\n    list.traverse (functor.comp.mk \u2218 Functor.map f \u2218 g) x =\n        functor.comp.mk (list.traverse f <$> list.traverse g x) :=\n  sorry\n\nprotected theorem traverse_eq_map_id {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 \u03b2) (x : List \u03b1) :\n    list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\n  sorry\n\nprotected theorem naturality {F : Type u \u2192 Type u} {G : Type u \u2192 Type u} [Applicative F]\n    [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n    (\u03b7 : applicative_transformation F G) {\u03b1 : Type u_1} {\u03b2 : Type u} (f : \u03b1 \u2192 F \u03b2) (x : List \u03b1) :\n    coe_fn \u03b7 (List \u03b2) (list.traverse f x) = list.traverse (coe_fn \u03b7 \u03b2 \u2218 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 \u2192 Type u} [Applicative F] {\u03b1' : Type u} {\u03b2' : Type u}\n    (f : \u03b1' \u2192 F \u03b2') : traverse f [] = pure [] :=\n  rfl\n\n@[simp] theorem traverse_cons {F : Type u \u2192 Type u} [Applicative F] {\u03b1' : Type u} {\u03b2' : Type u}\n    (f : \u03b1' \u2192 F \u03b2') (a : \u03b1') (l : List \u03b1') :\n    traverse f (a :: l) = (fun (_x : \u03b2') (_y : List \u03b2') => _x :: _y) <$> f a <*> traverse f l :=\n  rfl\n\n@[simp] theorem traverse_append {F : Type u \u2192 Type u} [Applicative F] {\u03b1' : Type u} {\u03b2' : Type u}\n    (f : \u03b1' \u2192 F \u03b2') [is_lawful_applicative F] (as : List \u03b1') (bs : List \u03b1') :\n    traverse f (as ++ bs) = append <$> traverse f as <*> traverse f bs :=\n  sorry\n\ntheorem mem_traverse {\u03b1' : Type u} {\u03b2' : Type u} {f : \u03b1' \u2192 set \u03b2'} (l : List \u03b1') (n : List \u03b2') :\n    n \u2208 traverse f l \u2194 forall\u2082 (fun (b : \u03b2') (a : \u03b1') => b \u2208 f a) n l :=\n  sorry\n\nend list\n\n\nnamespace sum\n\n\nprotected theorem traverse_map {\u03c3 : Type u} {G : Type u \u2192 Type u} [Applicative G] {\u03b1 : Type u}\n    {\u03b2 : Type u} {\u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n    sum.traverse f (g <$> x) = sum.traverse (f \u2218 g) x :=\n  sorry\n\nprotected theorem id_traverse {\u03c3 : Type u_1} {\u03b1 : Type u_1} (x : \u03c3 \u2295 \u03b1) :\n    sum.traverse id.mk x = x :=\n  sum.cases_on x (fun (x : \u03c3) => Eq.refl (sum.traverse id.mk (inl x)))\n    fun (x : \u03b1) => Eq.refl (sum.traverse id.mk (inr x))\n\nprotected theorem comp_traverse {\u03c3 : Type u} {F : Type u \u2192 Type u} {G : Type u \u2192 Type u}\n    [Applicative F] [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n    {\u03b1 : Type u_1} {\u03b2 : Type u} {\u03b3 : Type u} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n    sum.traverse (functor.comp.mk \u2218 Functor.map f \u2218 g) x =\n        functor.comp.mk (sum.traverse f <$> sum.traverse g x) :=\n  sorry\n\nprotected theorem traverse_eq_map_id {\u03c3 : Type u} {\u03b1 : Type u} {\u03b2 : Type u} (f : \u03b1 \u2192 \u03b2)\n    (x : \u03c3 \u2295 \u03b1) : sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\n  sorry\n\nprotected theorem map_traverse {\u03c3 : Type u} {G : Type u \u2192 Type u} [Applicative G]\n    [is_lawful_applicative G] {\u03b1 : Type u_1} {\u03b2 : Type u} {\u03b3 : Type u} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3)\n    (x : \u03c3 \u2295 \u03b1) : Functor.map f <$> sum.traverse g x = sum.traverse (Functor.map f \u2218 g) x :=\n  sorry\n\nprotected theorem naturality {\u03c3 : Type u} {F : Type u \u2192 Type u} {G : Type u \u2192 Type u}\n    [Applicative F] [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n    (\u03b7 : applicative_transformation F G) {\u03b1 : Type u_1} {\u03b2 : Type u} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n    coe_fn \u03b7 (\u03c3 \u2295 \u03b2) (sum.traverse f x) = sum.traverse (coe_fn \u03b7 \u03b2 \u2218 f) x :=\n  sorry\n\nprotected instance is_lawful_traversable {\u03c3 : Type u} : is_lawful_traversable (sum \u03c3) :=\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": "set_option trace.Elab true\ntheorem ex (h : a = b) : (fun x => x) a = b := by\n  simp (config := { beta := false })\n  trace_state\n  simp (config := { beta := true }) [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/declareConfigElabBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.06954174161325838, "lm_q1q2_score": 0.025746118590549427}}
{"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 \u2192 Type v}\nvariables [applicative F] [is_lawful_applicative F]\nvariables {\u03b1 \u03b2 \u03b3 \u03c3 : Type u}\n\nlemma applicative.map_seq_map (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (g : \u03c3 \u2192 \u03b2) (x : F \u03b1) (y : F \u03c3) :\n  (f <$> x) <*> (g <$> y) = (flip (\u2218) g \u2218 f) <$> x <*> y :=\nby simp [flip] with functor_norm\n\nlemma applicative.pure_seq_eq_map' (f : \u03b1 \u2192 \u03b2) : (<*>) (pure f : F (\u03b1 \u2192 \u03b2)) = (<$>) f :=\nby ext; simp with functor_norm\n\ntheorem applicative.ext {F} : \u2200 {A1 : applicative F} {A2 : applicative F}\n  [@is_lawful_applicative F A1] [@is_lawful_applicative F A2]\n  (H1 : \u2200 {\u03b1 : Type u} (x : \u03b1),\n    @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)\n  (H2 : \u2200 {\u03b1 \u03b2 : Type u} (f : F (\u03b1 \u2192 \u03b2)) (x : F \u03b1),\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 \u03b1 x, apply H1},\n  obtain rfl : @s1 = @s2, {funext \u03b1 \u03b2 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 \u03b1 \u03b2 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 \u2192 Type w} {G : Type v \u2192 Type u}\n\nvariables [applicative F] [applicative G]\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables {\u03b1 \u03b2 \u03b3 : Type v}\n\nlemma map_pure (f : \u03b1 \u2192 \u03b2) (x : \u03b1) : (f <$> pure x : comp F G \u03b2) = pure (f x) :=\ncomp.ext $ by simp\n\nlemma seq_pure (f : comp F G (\u03b1 \u2192 \u03b2)) (x : \u03b1) :\n  f <*> pure x = (\u03bb g : \u03b1 \u2192 \u03b2, g x) <$> f :=\ncomp.ext $ by simp [(\u2218)] with functor_norm\n\n\n\nlemma pure_seq_eq_map (f : \u03b1 \u2192 \u03b2) (x : comp F G \u03b1) :\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  (\u03bb \u03b1 x, rfl) (\u03bb \u03b1 \u03b2 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  (\u03bb \u03b1 x, rfl) (\u03bb \u03b1 \u03b2 f x, show id <$> f <*> x = f <*> x, by rw id_map)\n\nopen is_comm_applicative\n\ninstance {f : Type u \u2192 Type w} {g : Type v \u2192 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,(\u2218)] 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 {\u03b1 \u03b2 : Type w}\n  {f : Type u \u2192 Type v} {g : Type w \u2192 Type u}\n  [applicative f] [applicative g]\n  (h : f (g (\u03b1 \u2192 \u03b2))) (x : f (g \u03b1)) :\n  comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl\n\ninstance {\u03b1} [has_one \u03b1] [has_mul \u03b1] : applicative (const \u03b1) :=\n{ pure := \u03bb \u03b2 x, (1 : \u03b1),\n  seq := \u03bb \u03b2 \u03b3 f x, (f * x : \u03b1) }\n\ninstance {\u03b1} [monoid \u03b1] : is_lawful_applicative (const \u03b1) :=\nby refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]\n\ninstance {\u03b1} [has_zero \u03b1] [has_add \u03b1] : applicative (add_const \u03b1) :=\n{ pure := \u03bb \u03b2 x, (0 : \u03b1),\n  seq := \u03bb \u03b2 \u03b3 f x, (f + x : \u03b1) }\n\ninstance {\u03b1} [add_monoid \u03b1] : is_lawful_applicative (add_const \u03b1) :=\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-- \u03b1 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 {\u03b1 : Type}\n\ninductive tactic_script (\u03b1 : Type) : Type\n| base : \u03b1 \u2192 tactic_script\n| work (index : \u2115) (first : \u03b1) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string \u2192 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 := \u03bb s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := \u03bb s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr \u2192 tactic \u03b1) (g : expr) : tactic \u03b1 :=\ndo\n  type \u2190 infer_type g,\n  is_lemma \u2190 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 \u2190 mk_meta_var type,\n    a \u2190 tac m,\n    do {\n      val \u2190 instantiate_mvars m,\n      guard (val.list_meta_vars = []),\n      c  \u2190 new_aux_decl_name,\n      gs \u2190 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 {\u03b1} (tac : tactic \u03b1)\nwith chain_single : expr \u2192 tactic (\u03b1 \u00d7 list (tactic_script \u03b1)) | g :=\ndo set_goals [g],\n  a \u2190 tac,\n  l \u2190 get_goals >>= chain_many,\n  return (a, l)\nwith chain_many : list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] := return []\n| [g] := do {\n  (a, l) \u2190 chain_single g,\n  return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr \u2192 list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do {\n  (a, l) \u2190 abstract_if_success chain_single g,\n  new_goals \u2190 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' \u2190 chain_many current_goals,\n  return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {\u03b1 : Type} [has_to_string (tactic_script \u03b1)] (tactics : list (tactic \u03b1)) :\n  tactic (list string) :=\ndo results \u2190 (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 \u03b1)] [has_to_format \u03b1]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic \u03b1) : tactic \u03b1 :=\ndo tgt \u2190 target,\n   r \u2190 t,\n   name \u2190 decl_name,\n   trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n   tgt \u2190 pp tgt,\n   trace format!\"previous target: {tgt}\",\n   trace format!\"tactic result: {r}\",\n   tgt \u2190 try_core target,\n   tgt \u2190 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 \u03b1)) : 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 (\u03b1 : Type) [has_to_string \u03b1] : has_to_string (buffer \u03b1) :=\n\u27e8 fun b, to_string $ b.to_list \u27e9\n\nuniverses u v\n\ninductive parse_result (\u03b1 : Type u)\n| done (pos : \u2115) (result : \u03b1) : parse_result\n| fail (pos : \u2115) (expected : dlist string) : parse_result\n\ndef parser (elem : Type v) (\u03b1 : Type u) :=\n\u2200 (input : buffer elem) (start : \u2115), parse_result \u03b1\n\n-- todo: refactor into parser core\nnamespace parser\n\n-- Type polymorphism is restricted here because of monad.bind\nvariables {elem \u03b1 \u03b2 \u03b3 : Type}\n\nprotected def bind (p : parser elem \u03b1) (f : \u03b1 \u2192 parser elem \u03b2) : parser elem \u03b2 :=\n\u03bb 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 \u03b2 pos expected\nend\n\nprotected def pure (a : \u03b1) : parser elem \u03b1 :=\n\u03bb input pos, parse_result.done pos a\n\nprivate lemma id_map (p : parser elem \u03b1) : 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 \u03b1) (q : \u03b1 \u2192 parser elem \u03b2) (r : \u03b2 \u2192 parser elem \u03b3) :\n  parser.bind (parser.bind p q) r = parser.bind p (\u03bb 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 \u03b1 :=\n\u03bb _ pos, parse_result.fail \u03b1 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 := \u03bb _ _ _ _, rfl,\n  bind_assoc := @bind_assoc elem }\n\nprotected def failure : parser elem \u03b1 :=\n\u03bb _ pos, parse_result.fail \u03b1 pos dlist.empty\n\nprotected def orelse (p q : parser elem \u03b1) : parser elem \u03b1 :=\n\u03bb input pos, match p input pos with\n| parse_result.fail ._ pos\u2081 expected\u2081 :=\n  if pos\u2081 \u2260 pos then parse_result.fail _ pos\u2081 expected\u2081 else\n  match q input pos with\n  | parse_result.fail ._ pos\u2082 expected\u2082 :=\n    if pos\u2081 < pos\u2082 then\n      parse_result.fail _ pos\u2081 expected\u2081\n    else if pos\u2082 < pos\u2081 then\n      parse_result.fail _ pos\u2082 expected\u2082\n    else -- pos\u2081 = pos\u2082\n      parse_result.fail _ pos\u2081 (expected\u2081 ++ expected\u2082)\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 \u03b1) :=\n\u27e8parser.failure\u27e9\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorate_errors (msgs : thunk (list string)) (p : parser elem \u03b1) : parser elem \u03b1 :=\n\u03bb 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 \u03b1) : parser elem \u03b1 :=\ndecorate_errors [msg ()] p\n\n/-- Matches a single character satisfying the given predicate. -/\ndef sat (p : elem \u2192 Prop) [decidable_pred p] : parser elem elem :=\n\u03bb input pos,\nif h : pos < input.size then\n  let c := input.read \u27e8pos, h\u27e9 in\n  if p c then\n    parse_result.done (pos+1) $ input.read \u27e8pos, h\u27e9\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 \u2190 cs, return (to_string c)) $\nsat (\u2208 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 \u2115 :=\n\u03bb input pos, parse_result.done pos (input.size - pos)\n\n/-- Matches the end of the input. -/\ndef eof : parser elem unit :=\ndecorate_error \"<end-of-file>\" $\ndo rem \u2190 remaining, guard $ rem = 0\n\ndef foldr_core (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (p : parser elem \u03b1) (b : \u03b2) : \u2200 (reps : \u2115), parser elem \u03b2\n| 0 := failure\n| (reps+1) := (do x \u2190 p, xs \u2190 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (p : parser elem \u03b1) (b : \u03b2) : parser elem \u03b2 :=\n\u03bb input pos, foldr_core f p b (input.size - pos + 1) input pos\n\ndef foldl_core (f : \u03b1 \u2192 \u03b2 \u2192 \u03b1) : \u2200 (a : \u03b1) (p : parser elem \u03b2) (reps : \u2115), parser elem \u03b1\n| a p 0 := failure\n| a p (reps+1) := (do x \u2190 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b1) (a : \u03b1) (p : parser elem \u03b2) : parser elem \u03b1 :=\n\u03bb input pos, foldl_core f a p (input.size - pos + 1) input pos\n\ndef choice (ps : list (parser elem \u03b1)) : parser elem \u03b1 :=\n  ps.foldr (<|>) failure\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many (p : parser elem \u03b1) : parser elem (list \u03b1) :=\nfoldr list.cons p []\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many' (p : parser elem \u03b1) : parser elem unit :=\nmany p >> eps\n\n/-- Matches one or more occurrences of `p`. -/\ndef many1 (p : parser elem \u03b1) : parser elem (list \u03b1) :=\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 \u03b1) : parser elem (list \u03b1) :=\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 \u03b1) : parser elem (list \u03b1) :=\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 \u03b1 : Type u} (p : parser elem \u03b1) : parser elem \u03b1 :=\n\u03bb 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 \u03b1 \u2192 parser elem \u03b1) : \u2200 (max_depth : \u2115), parser elem \u03b1\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 \u03b1 \u2192 parser elem \u03b1) : parser elem \u03b1 :=\n\u03bb input pos, fix_core F (input.size - pos + 1) input pos\n\ndef fix_core_fn {\u03b2 : Type} (F : (\u03b2 \u2192 parser elem \u03b1) \u2192 (\u03b2 \u2192 parser elem \u03b1)) : \u2200 (max_depth : \u2115), \u03b2 \u2192 parser elem \u03b1\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 {\u03b2 : Type} (F : (\u03b2 \u2192 parser elem \u03b1) \u2192 (\u03b2 \u2192 parser elem \u03b1)) : \u03b2 \u2192 parser elem \u03b1 :=\n\u03bb a input pos, fix_core_fn F (input.size - pos + 1) a input pos\n\nprivate def make_monospaced : char \u2192 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 : \u2115) (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 (\u03bb _, ' ') ++ -/ \"^\\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 \u03b1) (input : buffer elem) : sum string \u03b1 :=\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": "/-\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, Robert Y. Lewis, Arthur Paulino\n\n! This file was ported from Lean 3 source module tactic.lint.misc\n! leanprover-community/mathlib commit 58d83ed5268d96bd37757ac03062a4d69e5aa435\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.Meta.RbMap\nimport Mathbin.Tactic.Lint.Basic\n\n/-!\n# Various linters\n\nThis file defines several small linters:\n  - `ge_or_gt` checks that `>` and `\u2265` do not occur in the statement of theorems.\n  - `dup_namespace` checks that no declaration has a duplicated namespace such as `list.list.monad`.\n  - `unused_arguments` checks that definitions and theorems do not have unused arguments.\n  - `doc_blame` checks that every definition has a documentation string.\n  - `doc_blame_thm` checks that every theorem has a documentation string (not enabled by default).\n  - `def_lemma` checks that a declaration is a lemma iff its type is a proposition.\n  - `check_type` checks that the statement of a declaration is well-typed.\n  - `check_univs` checks that there are no bad `max u v` universe levels.\n  - `syn_taut` checks that declarations are not syntactic tautologies.\n  - `unused_haves_suffices` checks that declarations produced via term mode do not have\n    ineffectual `have` or `suffices` statements\n-/\n\n\nopen Tactic Expr\n\n/-!\n## Linter against use of `>`/`\u2265`\n-/\n\n\n/-- The names of `\u2265` and `>`, mostly disallowed in lemma statements -/\nprivate unsafe def illegal_ge_gt : List Name :=\n  [`gt, `ge]\n#align illegal_ge_gt illegal_ge_gt\n\n/- ./././Mathport/Syntax/Translate/Basic.lean:334:40: warning: unsupported option eqn_compiler.max_steps -/\nset_option eqn_compiler.max_steps 20000\n\n/-- Checks whether `\u2265` and `>` occurs in an illegal way in the expression.\n  The main ways we legally use these orderings are:\n  - `f (\u2265)`\n  - `\u2203 x \u2265 t, b`. This corresponds to the expression\n    `@Exists \u03b1 (fun (x : \u03b1), (@Exists (x > t) (\u03bb (H : x > t), b)))`\n  This function returns `tt` when it finds `ge`/`gt`, except in the following patterns\n  (which are the same for `gt`):\n  - `f (@ge _ _)`\n  - `f (&0 \u2265 y) (\u03bb x : t, b)`\n  - `\u03bb H : &0 \u2265 t, b`\n  Here `&0` is the 0-th de Bruijn variable.\n-/\nprivate unsafe def contains_illegal_ge_gt : expr \u2192 Bool\n  | const nm us => if nm \u2208 illegal_ge_gt then true else false\n  | app f e@(app (app (const nm us) tp) tc) =>\n    contains_illegal_ge_gt f || if nm \u2208 illegal_ge_gt then false else contains_illegal_ge_gt e\n  |\n  app (app custom_binder (app (app (app (app (const nm us) tp) tc) (var 0)) t))\n      e@(lam var_name bi var_type body) =>\n    contains_illegal_ge_gt e || if nm \u2208 illegal_ge_gt then false else contains_illegal_ge_gt e\n  | app f x => contains_illegal_ge_gt f || contains_illegal_ge_gt x\n  | lam `H bi (type@(app (app (app (app (const nm us) tp) tc) (var 0)) t)) body =>\n    contains_illegal_ge_gt body || if nm \u2208 illegal_ge_gt then false else contains_illegal_ge_gt type\n  | lam var_name bi var_type body => contains_illegal_ge_gt var_type || contains_illegal_ge_gt body\n  | pi `H bi (type@(app (app (app (app (const nm us) tp) tc) (var 0)) t)) body =>\n    contains_illegal_ge_gt body || if nm \u2208 illegal_ge_gt then false else contains_illegal_ge_gt type\n  | pi var_name bi var_type body => contains_illegal_ge_gt var_type || contains_illegal_ge_gt body\n  | elet var_name type assignment body =>\n    contains_illegal_ge_gt type || contains_illegal_ge_gt assignment || contains_illegal_ge_gt body\n  | _ => false\n#align contains_illegal_ge_gt contains_illegal_ge_gt\n\n/-- Checks whether a `>`/`\u2265` is used in the statement of `d`.\n\nIt first does a quick check to see if there is any `\u2265` or `>` in the statement, and then does a\nslower check whether the occurrences of `\u2265` and `>` are allowed.\nCurrently it checks only the conclusion of the declaration, to eliminate false positive from\nbinders such as `\u2200 \u03b5 > 0, ...` -/\nprivate unsafe def ge_or_gt_in_statement (d : declaration) : tactic (Option String) :=\n  return <|\n    if (d.type.contains_constant fun n => n \u2208 illegal_ge_gt) && contains_illegal_ge_gt d.type then\n      some \"the type contains \u2265/>. Use \u2264/< instead.\"\n    else none\n#align ge_or_gt_in_statement ge_or_gt_in_statement\n\n-- TODO: the commented out code also checks for classicality in statements, but needs fixing\n-- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _\n-- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) :=\n-- return $ if d.type.contains_constant (\u03bb n, (n.get_prefix = `classical \u2227\n--   n.last \u2208 [\"prop_decidable\", \"dec\", \"dec_rel\", \"dec_eq\"]) \u2228 n \u2208 [`gt, `ge])\n-- then\n--   let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel,\n--     `classical.dec_eq],\n--       illegal2 := [`gt, `ge],\n--       occur1 := illegal1.filter (\u03bb n, d.type.contains_constant (eq n)),\n--       occur2 := illegal2.filter (\u03bb n, d.type.contains_constant (eq n)) in\n--   some $ sformat!\"the type contains the following declarations: {occur1 ++ occur2}.\" ++\n--     (if occur1 = [] then \"\" else \" Add decidability type-class arguments instead.\") ++\n--     (if occur2 = [] then \"\" else \" Use \u2264/< instead.\")\n-- else none\n/-- A linter for checking whether illegal constants (\u2265, >) appear in a declaration's type. -/\n@[linter]\nunsafe def linter.ge_or_gt : linter\n    where\n  test := ge_or_gt_in_statement\n  auto_decls := false\n  no_errors_found := \"Not using \u2265/> in declarations.\"\n  errors_found :=\n    \"The following declarations use \u2265/>, probably in a way where we would prefer\\n  to use \u2264/< instead. See note [nolint_ge] for more information.\"\n  is_fast := false\n#align linter.ge_or_gt linter.ge_or_gt\n\nlibrary_note \"nolint_ge\"/-- Currently, the linter forbids the use of `>` and `\u2265` in definitions and\nstatements, as they cause problems in rewrites.\nThey are still allowed in statements such as `bounded (\u2265)` or `\u2200 \u03b5 > 0` or `\u2a06 n \u2265 m`,\nand the linter allows that.\nIf you write a pattern where you bind two or more variables, like `\u2203 n m > 0`, the linter will\nflag this as illegal, but it is also allowed. In this case, add the line\n```\n@[nolint ge_or_gt] -- see Note [nolint_ge]\n```\n-/\n\n\n/-!\n## Linter for duplicate namespaces\n-/\n\n\n/-- Checks whether a declaration has a namespace twice consecutively in its name -/\nprivate unsafe def dup_namespace (d : declaration) : tactic (Option String) :=\n  is_instance d.to_name >>= fun is_inst =>\n    return <|\n      let nm := d.to_name.components\n      if nm.Chain' (\u00b7 \u2260 \u00b7) \u2228 is_inst then none\n      else\n        let s := (nm.find fun n => nm.count n \u2265 2).iget.toString\n        some <| \"The namespace `\" ++ s ++ \"` is duplicated in the name\"\n#align dup_namespace dup_namespace\n\n/-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/\n@[linter]\nunsafe def linter.dup_namespace : linter\n    where\n  test := dup_namespace\n  auto_decls := false\n  no_errors_found := \"No declarations have a duplicate namespace.\"\n  errors_found := \"DUPLICATED NAMESPACES IN NAME:\"\n#align linter.dup_namespace linter.dup_namespace\n\nattribute [nolint dup_namespace] Iff.iff\n\n/-!\n## Linter for unused arguments\n-/\n\n\n/-- Auxiliary definition for `check_unused_arguments` -/\nprivate unsafe def check_unused_arguments_aux : List \u2115 \u2192 \u2115 \u2192 \u2115 \u2192 expr \u2192 List \u2115\n  | l, n, n_max, e =>\n    if n > n_max then l\n    else\n      if \u00acis_lambda e \u2227 \u00acis_pi e then l\n      else\n        let b := e.binding_body\n        let l' := if b.has_var_idx 0 then l else n :: l\n        check_unused_arguments_aux l' (n + 1) n_max b\n#align check_unused_arguments_aux check_unused_arguments_aux\n\n/-- Check which arguments of a declaration are not used.\nPrints a list of natural numbers corresponding to which arguments are not used (e.g.\n  this outputs [1, 4] if the first and fourth arguments are unused).\nChecks both the type and the value of `d` for whether the argument is used\n(in rare cases an argument is used in the type but not in the value).\nWe return [] if the declaration was automatically generated.\nWe print arguments that are larger than the arity of the type of the declaration\n(without unfolding definitions). -/\nunsafe def check_unused_arguments (d : declaration) : Option (List \u2115) :=\n  let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value\n  if l = [] then none\n  else\n    let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type\n    (l.filter\u2093 fun n => n \u2208 l2).reverse\n#align check_unused_arguments check_unused_arguments\n\n/-- Check for unused arguments, and print them with their position, variable name, type and whether\nthe argument is a duplicate.\nSee also `check_unused_arguments`.\nThis tactic additionally filters out all unused arguments of type `parse _`.\nWe skip all declarations that contain `sorry` in their value. -/\nprivate unsafe def unused_arguments (d : declaration) : tactic (Option String) := do\n  let ff \u2190 d.to_name.contains_sorry |\n    return none\n  let ns := check_unused_arguments d\n  let tt \u2190 return ns.isSome |\n    return none\n  let ns := ns.iget\n  let (ds, _) \u2190 get_pi_binders d.type\n  let ns := ns.map fun n => (n, (ds.get? <| n - 1).iget)\n  let ns := ns.filter\u2093 fun x => x.2.type.get_app_fn \u2260 const `interactive.parse []\n  let ff \u2190 return ns.Empty |\n    return none\n  let ds' \u2190 ds.mapM pp\n  let ns \u2190\n    ns.mapM fun \u27e8n, b\u27e9 =>\n        (fun s =>\n            to_fmt \"argument \" ++ to_fmt n ++ \": \" ++ s ++\n              if (ds.countp fun b' => b.type = b'.type) \u2265 2 then \" (duplicate)\" else \"\") <$>\n          pp b\n  return <| some <| ns tt\n#align unused_arguments unused_arguments\n\n/-- A linter object for checking for unused arguments. This is in the default linter set. -/\n@[linter]\nunsafe def linter.unused_arguments : linter\n    where\n  test := unused_arguments\n  auto_decls := false\n  no_errors_found := \"No unused arguments.\"\n  errors_found := \"UNUSED ARGUMENTS.\"\n#align linter.unused_arguments linter.unused_arguments\n\nattribute [nolint unused_arguments] imp_intro\n\n/-!\n## Linter for documentation strings\n-/\n\n\n/-- Reports definitions and constants that are missing doc strings -/\nprivate unsafe def doc_blame_report_defn : declaration \u2192 tactic (Option String)\n  | declaration.defn n _ _ _ _ _ => doc_string n >> return none <|> return \"def missing doc string\"\n  | declaration.cnst n _ _ _ => doc_string n >> return none <|> return \"constant missing doc string\"\n  | _ => return none\n#align doc_blame_report_defn doc_blame_report_defn\n\n/-- Reports definitions and constants that are missing doc strings -/\nprivate unsafe def doc_blame_report_thm : declaration \u2192 tactic (Option String)\n  | declaration.thm n _ _ _ => doc_string n >> return none <|> return \"theorem missing doc string\"\n  | _ => return none\n#align doc_blame_report_thm doc_blame_report_thm\n\n/-- A linter for checking definition doc strings -/\n@[linter]\nunsafe def linter.doc_blame : linter\n    where\n  test d :=\n    condM (not <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none)\n  auto_decls := false\n  no_errors_found := \"No definitions are missing documentation.\"\n  errors_found := \"DEFINITIONS ARE MISSING DOCUMENTATION STRINGS:\"\n#align linter.doc_blame linter.doc_blame\n\n/-- A linter for checking theorem doc strings. This is not in the default linter set. -/\nunsafe def linter.doc_blame_thm : linter\n    where\n  test := doc_blame_report_thm\n  auto_decls := false\n  no_errors_found := \"No theorems are missing documentation.\"\n  errors_found := \"THEOREMS ARE MISSING DOCUMENTATION STRINGS:\"\n  is_fast := false\n#align linter.doc_blame_thm linter.doc_blame_thm\n\n/-!\n## Linter for correct usage of `lemma`/`def`\n-/\n\n\n/-- Checks whether the correct declaration constructor (definition or theorem) by\ncomparing it to its sort. Instances will not be printed.\n\nThis test is not very quick: maybe we can speed-up testing that something is a proposition?\nThis takes almost all of the execution time.\n-/\nprivate unsafe def incorrect_def_lemma (d : declaration) : tactic (Option String) :=\n  if d.is_constant \u2228 d.is_axiom then return none\n  else do\n    let is_instance_d \u2190 is_instance d.to_name\n    if is_instance_d then return none\n      else do\n        let-- the following seems to be a little quicker than `is_prop d.type`.\n            expr.sort\n            n\n          \u2190 infer_type d\n        let is_pattern \u2190 has_attribute' `pattern d\n        return <|\n            if d \u2194 n = level.zero then none\n            else\n              if d then \"is a lemma/theorem, should be a def\"\n              else\n                if is_pattern then none\n                else-- declarations with `@[pattern]` are allowed to be a `def`.\n                  \"is a def, should be a lemma/theorem\"\n#align incorrect_def_lemma incorrect_def_lemma\n\n/-- A linter for checking whether the correct declaration constructor (definition or theorem)\nhas been used. -/\n@[linter]\nunsafe def linter.def_lemma : linter\n    where\n  test := incorrect_def_lemma\n  auto_decls := false\n  no_errors_found := \"All declarations correctly marked as def/lemma.\"\n  errors_found := \"INCORRECT DEF/LEMMA:\"\n#align linter.def_lemma linter.def_lemma\n\n/-!\n## Linter that checks whether declarations are well-typed\n-/\n\n\n/-- Checks whether the statement of a declaration is well-typed. -/\nunsafe def check_type (d : declaration) : tactic (Option String) :=\n  type_check d.type >> return none <|> return \"The statement doesn't type-check\"\n#align check_type check_type\n\n/-- A linter for missing checking whether statements of declarations are well-typed. -/\n@[linter]\nunsafe def linter.check_type : linter\n    where\n  test := check_type\n  auto_decls := false\n  no_errors_found :=\n    \"The statements of all declarations type-check with default reducibility settings.\"\n  errors_found :=\n    \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS DO NOT TYPE-CHECK.\\nSome definitions in the statement are marked `@[irreducible]`, which means that the statement \" ++\n          \"is now ill-formed. It is likely that these definitions were locally marked as `@[reducible]` \" ++\n        \"or `@[semireducible]`. This can especially cause problems with type class inference or \" ++\n      \"`@[simps]`.\"\n  is_fast := true\n#align linter.check_type linter.check_type\n\n/-!\n## Linter for universe parameters\n-/\n\n\nopen Native\n\n/-- `univ_params_grouped e` computes for each `level` `u` of `e` the parameters that occur in `u`,\n  and returns the corresponding set of lists of parameters.\n  In pseudo-mathematical form, this returns `{ { p : parameter | p \u2208 u } | (u : level) \u2208 e }`\n  We use `list name` instead of `name_set`, since `name_set` does not have an order.\n  It will ignore `nm\u2080._proof_i` declarations.\n-/\nunsafe def expr.univ_params_grouped (e : expr) (nm\u2080 : Name) : rb_set (List Name) :=\n  e.fold mk_rb_set fun e n l =>\n    match e with\n    | e@(sort u) => l.insert u.params.toList\n    | e@(const nm us) =>\n      if nm.getPrefix = nm\u2080 \u2227 nm.getLast.startsWith \"_proof_\" then l\n      else l.union <| rb_set.of_list <| us.map fun u : level => u.params.toList\n    | _ => l\n#align expr.univ_params_grouped expr.univ_params_grouped\n\n/-- The good parameters are the parameters that occur somewhere in the `rb_set` as a singleton or\n  (recursively) with only other good parameters.\n  All other parameters in the `rb_set` are bad.\n-/\nunsafe def bad_params : rb_set (List Name) \u2192 List Name\n  | l =>\n    let good_levels : name_set :=\n      l.fold mk_name_set fun us prev => if us.length = 1 then prev.insert us.headI else prev\n    if good_levels.Empty then l.fold [] List.union\n    else\n      bad_params <|\n        rb_set.of_list <| l.toList.map fun us => us.filter\u2093 fun nm => !good_levels.contains nm\n#align bad_params bad_params\n\n/-- Checks whether all universe levels `u` in the type of `d` are \"good\".\nThis means that `u` either occurs in a `level` of `d` by itself, or (recursively)\nwith only other good levels.\nWhen this fails, usually this means that there is a level `max u v`, where neither `u` nor `v`\noccur by themselves in a level. It is ok if *one* of `u` or `v` never occurs alone. For example,\n`(\u03b1 : Type u) (\u03b2 : Type (max u v))` is a occasionally useful method of saying that `\u03b2` lives in\na higher universe level than `\u03b1`.\n-/\nunsafe def check_univs (d : declaration) : tactic (Option String) := do\n  let l := d.type.univ_params_grouped d.to_name\n  let bad := bad_params l\n  if bad then return none\n    else return <| some <| \"universes \" ++ toString bad ++ \" only occur together.\"\n#align check_univs check_univs\n\n/-- A linter for checking that there are no bad `max u v` universe levels. -/\n@[linter]\nunsafe def linter.check_univs : linter\n    where\n  test := check_univs\n  auto_decls := false\n  no_errors_found := \"All declarations have good universe levels.\"\n  errors_found :=\n    \"THE STATEMENTS OF THE FOLLOWING DECLARATIONS HAVE BAD UNIVERSE LEVELS. \" ++\n                  \"This usually means that there is a `max u v` in the type where neither `u` nor `v` \" ++\n                \"occur by themselves. Solution: Find the type (or type bundled with data) that has this \" ++\n              \"universe argument and provide the universe level explicitly. If this happens in an implicit \" ++\n            \"argument of the declaration, a better solution is to move this argument to a `variables` \" ++\n          \"command (then it's not necessary to provide the universe level).\\nIt is possible that this linter gives a false positive on definitions where the value of the \" ++\n        \"definition has the universes occur separately, and the definition will usually be used with \" ++\n      \"explicit universe arguments. In this case, feel free to add `@[nolint check_univs]`.\"\n  is_fast := true\n#align linter.check_univs linter.check_univs\n\n/-!\n## Linter for syntactic tautologies\n-/\n\n\n/-- Checks whether a lemma is a declaration of the form `\u2200 a b ... z, e\u2081 = e\u2082`\nwhere `e\u2081` and `e\u2082` are identical exprs.\nWe call declarations of this form syntactic tautologies.\nSuch lemmas are (mostly) useless and sometimes introduced unintentionally when proving basic facts\nwith rfl when elaboration results in a different term than the user intended.\n-/\nunsafe def syn_taut (d : declaration) : tactic (Option String) :=\n  (do\n      let (el, er) \u2190 d.type.pi_codomain.is_eq\n      guardb (el == er)\n      return <| some \"LHS equals RHS syntactically\") <|>\n    return none\n#align syn_taut syn_taut\n\n/-- A linter for checking that declarations aren't syntactic tautologies. -/\n@[linter]\nunsafe def linter.syn_taut : linter where\n  test := syn_taut\n  auto_decls := false\n  -- many false positives with this enabled\n  no_errors_found := \"No declarations are syntactic tautologies.\"\n  errors_found :=\n    \"THE FOLLOWING DECLARATIONS ARE SYNTACTIC TAUTOLOGIES. \" ++\n              \"This usually means that they are of the form `\u2200 a b ... z, e\u2081 = e\u2082` where `e\u2081` and `e\u2082` are \" ++\n            \"identical expressions. We call declarations of this form syntactic tautologies. \" ++\n          \"Such lemmas are (mostly) useless and sometimes introduced unintentionally when proving \" ++\n        \"basic facts using `rfl`, when elaboration results in a different term than the user intended. \" ++\n      \"You should check that the declaration really says what you think it does.\"\n  is_fast := true\n#align linter.syn_taut linter.syn_taut\n\nattribute [nolint syn_taut] rfl\n\n/-!\n## Linters for ineffectual have and suffices statements in term mode\n-/\n\n\n/--\nCheck if an expression contains `var 0` by folding over the expression and matching the binder depth\n-/\nunsafe def expr.has_zero_var (e : expr) : Bool :=\n  e.fold false fun e' d res =>\n    res ||\n      match e' with\n      | var k => k = d\n      | _ => false\n#align expr.has_zero_var expr.has_zero_var\n\n/-- Return a list of unused have and suffices terms in an expression\n-/\nunsafe def find_unused_have_suffices_macros : expr \u2192 tactic (List String)\n  | app a b =>\n    (\u00b7 ++ \u00b7) <$> find_unused_have_suffices_macros a <*> find_unused_have_suffices_macros b\n  | lam var_name bi var_type body => find_unused_have_suffices_macros body\n  | pi var_name bi var_type body => find_unused_have_suffices_macros body\n  | elet var_name type assignment body =>\n    (\u00b7 ++ \u00b7) <$> find_unused_have_suffices_macros assignment <*>\n      find_unused_have_suffices_macros body\n  | m@(macro md [l@(lam ppnm bi vt bd)]) => do\n    -- term mode have statements are tagged with a macro\n          -- if the macro annotation is `have then this lambda came from a term mode have statement\n          (\u00b7 ++ \u00b7)\n          (if m = `have \u2227 \u00acbd then [\"unnecessary have \" ++ ppnm ++ \" : \" ++ vt] else []) <$>\n        find_unused_have_suffices_macros l\n  | m@(macro md [app (l@(lam ppnm bi vt bd)) arg]) => do\n    -- term mode suffices statements are tagged with a macro\n          -- if the macro annotation is `suffices then this lambda came from a term mode suffices statement\n          (\u00b7 ++ \u00b7)\n          (if m = `suffices \u2227 \u00acbd then [\"unnecessary suffices \" ++ ppnm ++ \" : \" ++ vt] else []) <$>\n        ((\u00b7 ++ \u00b7) <$> find_unused_have_suffices_macros l <*> find_unused_have_suffices_macros arg)\n  | macro md l => List.join <$> l.mapM find_unused_have_suffices_macros\n  | _ => return []\n#align find_unused_have_suffices_macros find_unused_have_suffices_macros\n\n/-- Return a list of unused have and suffices terms in a declaration\n-/\nunsafe def unused_have_of_decl : declaration \u2192 tactic (List String)\n  | declaration.defn _ _ _ bd _ _ => find_unused_have_suffices_macros bd\n  | declaration.thm _ _ _ bd => find_unused_have_suffices_macros bd.get\n  | _ => return []\n#align unused_have_of_decl unused_have_of_decl\n\n/--\nChecks whether a declaration contains term mode have statements that have no effect on the resulting\nterm.\n-/\nunsafe def has_unused_haves_suffices (d : declaration) : tactic (Option String) := do\n  let ns \u2190 unused_have_of_decl d\n  if ns = 0 then return none else return (\", \".intercalate (ns toString))\n#align has_unused_haves_suffices has_unused_haves_suffices\n\n/-- A linter for checking that declarations don't have unused term mode have statements. We do not\ntag this as `@[linter]` so that it is not in the default linter set as it is slow and an uncommon\nproblem. -/\nunsafe def linter.unused_haves_suffices : linter\n    where\n  test := has_unused_haves_suffices\n  auto_decls := false\n  no_errors_found := \"No declarations have unused term mode have statements.\"\n  errors_found :=\n    \"THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. \" ++\n                      \"In the case of `have` this is a term of the form `have h := foo, bar` where `bar` does not \" ++\n                    \"refer to `foo`. Such statements have no effect on the generated proof, and can just be \" ++\n                  \"replaced by `bar`, in addition to being ineffectual, they may make unnecessary assumptions \" ++\n                \"in proofs appear as if they are used. \" ++\n              \"For `suffices` this is a term of the form `suffices h : foo, proof_of_goal, proof_of_foo` where\" ++\n            \" `proof_of_goal` does not refer to `foo`. \" ++\n          \"Such statements have no effect on the generated proof, and can just be replaced by \" ++\n        \"`proof_of_goal`, in addition to being ineffectual, they may make unnecessary assumptions in \" ++\n      \"proofs appear as if they are used. \"\n  is_fast := false\n#align linter.unused_haves_suffices linter.unused_haves_suffices\n\n/-!\n## Linter for unprintable interactive tactics\n-/\n\n\n/-- Ensures that every interactive tactic has arguments for which `interactive.param_desc` succeeds.\nThis is used to generate the parser documentation that appears in hovers on interactive tactics.\n-/\nunsafe def unprintable_interactive (d : declaration) : tactic (Option String) :=\n  match d.to_name with\n  | Name.mk_string _ (Name.mk_string \"interactive\" (Name.mk_string _ Name.anonymous)) => do\n    let (ds, _) \u2190 mk_local_pis d.type\n    let ds \u2190 ds.filterM fun d => not <$> succeeds (interactive.param_desc d.local_type)\n    let ff \u2190 return ds.Empty |\n      return none\n    let ds \u2190 ds.mapM (pp \u2218 to_binder)\n    return <| some <| ds tt\n  | _ => return none\n#align unprintable_interactive unprintable_interactive\n\n/-- A linter for checking that interactive tactics have parser documentation. -/\n@[linter]\nunsafe def linter.unprintable_interactive : linter\n    where\n  test := unprintable_interactive\n  auto_decls := true\n  no_errors_found := \"No tactics are unprintable.\"\n  errors_found :=\n    \"THE FOLLOWING TACTICS ARE UNPRINTABLE. \" ++\n              \"This means that an interactive tactic is using `parse p` where `p` does not have \" ++\n            \"an associated description. You can fix this by wrapping `p` as `with_desc \\\"p\\\" p`, \" ++\n          \"and provide the description there, or you can stick to \\\"approved\\\" tactic combinators \" ++\n        \"like `?` `*>` `<*` `<*>` `<|>` and `<$>` (but not `>>=` or `do` blocks) \" ++\n      \"that automatically generate a description.\"\n  is_fast := true\n#align linter.unprintable_interactive linter.unprintable_interactive\n\n/-!\n## Linter for iff's\n-/\n\n\nopen BinderInfo\n\n/-- Recursively consumes a Pi expression while accumulating names and the complement of de-Bruijn\nindexes of explicit variables, ultimately obtaining the remaining non-Pi expression as well.\n-/\nunsafe def unravel_explicits_of_pi : expr \u2192 \u2115 \u2192 List Name \u2192 List \u2115 \u2192 List Name \u00d7 List \u2115 \u00d7 expr\n  | pi n default _ e, i, ln, li => unravel_explicits_of_pi e (i + 1) (n :: ln) (i :: li)\n  | pi n _ _ e, i, ln, li => unravel_explicits_of_pi e (i + 1) ln li\n  | e, _, ln, li => (ln, li, e)\n#align unravel_explicits_of_pi unravel_explicits_of_pi\n\n/-- This function works as follows:\n1. Call `unravel_explicits_of_pi` to obtain the names, complements of de-Bruijn indexes and the\nremaining non-Pi expression;\n2. Check if the remaining non-Pi expression is an iff, already obtaining the respective left and\nright expressions if this is the case. Returns `none` otherwise;\n3. Filter the explicit variables that appear on the left *and* right side of the iff;\n4. If no variable satisfies the condition above, return `none`;\n5. Return a message mentioning the variables that do, otherwise.\n-/\nunsafe def explicit_vars_of_iff (d : declaration) : tactic (Option String) := do\n  let (ln, li, e) := unravel_explicits_of_pi d.type 0 [] []\n  match e with\n    | none => return none\n    | some (el, er) => do\n      let li := li fun i => d - i - 1\n      let-- fixing for the actual de-Bruijn indexes\n      l := (ln li).filter\u2093 fun t => el t.2 && er t.2\n      if l = [] then return none\n        else\n          return <|\n            \"The following variables are used on both sides of an iff and \".append <|\n              \"should be made implicit: \".append <| \", \".intercalate (l fun t => toString t.1)\n#align explicit_vars_of_iff explicit_vars_of_iff\n\n/-- A linter for checking if variables appearing on both sides of an iff are explicit. Ideally, such\nvariables should be implicit instead.\n-/\nunsafe def linter.explicit_vars_of_iff : linter\n    where\n  test := explicit_vars_of_iff\n  auto_decls := false\n  no_errors_found := \"No explicit variables on both sides of iff\"\n  errors_found := \"EXPLICIT VARIABLES ON BOTH SIDES OF IFF\"\n#align linter.explicit_vars_of_iff linter.explicit_vars_of_iff\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/Lint/Misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.0758581868113179, "lm_q1q2_score": 0.02564591764040425}}
{"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\nnamespace tactic\nnamespace interactive\nopen interactive interactive.types expr lean.parser\n\nlocal postfix `?`: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 \u2190 i_to_expr e <|> do {\n    ty \u2190 target,\n    -- for positional error messages, we don't care about the result\n    e \u2190 i_to_expr_strict ``(%%e : %%ty),\n    pty \u2190 pp ty, ptgt \u2190 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 \u2190 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": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/simpa.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.06656918387791787, "lm_q1q2_score": 0.02562328732299466}}
{"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 \" \ud83d\udc80 \" rhs:72 => lhs - rhs\nend a\n\nnamespace b\n  set_option quotPrecheck false\n  scoped infixl:71 \" \ud83d\udc80 \" => fun lhs rhs => lhs - rhs\nend b\n\nnamespace c\n  scoped syntax:71 term:50 \" \ud83d\udc80 \" term:72 : term\n  scoped macro_rules | `($l:term \ud83d\udc80 $r:term) => `($l - $r)\nend c\n\nopen a\n#eval 5 * 8 \ud83d\udc80 4 -- 20\n#eval 8 \ud83d\udc80 6 \ud83d\udc80 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) \"\u2211 \" 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 \u2211 x in { 1, 2, 3 }, x^2\n\ndef hi := (\u2211 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 \u2192 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 (\u03bb r (s:string), max r s.length) 0 in\nl.map $ \u03bb s, nat.iterate (\u03bb 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) : \u2115 := es.s.size\n\nmeta def entries.add : entries \u2192 entry \u2192 entries\n| es@\u27e8s, l\u27e9 e := if s.contains e.expr then es else \u27e8s.insert e.expr e, e :: l\u27e9\n\nmeta def entries.head (es : entries) : option entry := es.l.head'\n\nmeta def format_aux : list string \u2192 list string \u2192 list string \u2192 list entry \u2192 tactic format\n| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do\n  fmt \u2190 do\n  { let margin := string.join (list.replicate en.depth \" \u2502\"),\n    let margin := match en.status with\n      | status.sintro := \" \u251c\" ++ margin\n      | status.intro := \" \u2502\" ++ margin ++ \" \u250c\"\n      | status.reg := \" \u2502\" ++ margin ++ \"\"\n      | status.lam := \" \u2502\" ++ margin ++ \"\"\n      end,\n    p \u2190 infer_type en.expr >>= pp,\n    let lhs :=  line ++ \"\u2502\" ++ dep ++ \"\u2502 \" ++ 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\u27e8\u03bb es : entries,\n  let lines := pad_right $ es.l.map (\u03bb en, to_string en.line),\n      deps  := pad_right $ es.l.map (\u03bb en, string.intercalate \",\" (en.deps.map to_string)),\n      thms  := pad_right $ es.l.map (\u03bb en, (entry.thm en).to_string) in\n  format_aux lines deps thms es.l\u27e9\n\nmeta def append_dep (filter : expr \u2192 tactic unit)\n (es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=\ndo { ei \u2190 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 \u2190 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 \u2192 tactic unit)\nwith explode.core : expr \u2192 bool \u2192 nat \u2192 entries \u2192 tactic entries\n| e@(lam n bi d b) si depth es := do\n  m \u2190 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 := \u27e8l, es.size, depth, status.sintro, thm.name n, []\u27e9 in do\n    es' \u2190 explode.core b' si depth (es.add en),\n    return $ es'.add \u27e8e, es'.size, depth, status.lam, thm.string \"\u2200I\", [es.size, es'.size - 1]\u27e9\n  else do\n    let en : entry := \u27e8l, es.size, depth, status.intro, thm.name n, []\u27e9,\n    es' \u2190 explode.core b' si (depth + 1) (es.add en),\n    -- in case of a \"have\" clause, the b' here has an annotation\n    deps' \u2190 explode.append_dep filter es' b'.erase_annotations [],\n    deps' \u2190 explode.append_dep filter es' l deps',\n    return $ es'.add \u27e8e, es'.size, depth, status.lam, thm.string \"\u2200I\", deps'\u27e9\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 := \u27e8fn, es.size, depth, status.reg, thm.expr fn, []\u27e9,\n    return (es.add en)\n  | (fn, args) := do\n    es' \u2190 explode.core fn ff depth es,\n    -- in case of a \"have\" clause, the fn here has an annotation\n    deps \u2190 explode.append_dep filter es' fn.erase_annotations [],\n    explode.args e args depth es' (thm.string \"\u2200E\") deps\n  end\nwith explode.args : expr \u2192 list expr \u2192 nat \u2192 entries \u2192 thm \u2192 list nat \u2192 tactic entries\n| e (arg :: args) depth es thm deps := do\n  es' \u2190 explode.core arg ff depth es <|> return es,\n  deps' \u2190 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 \u27e8e, es.size, depth, status.reg, thm, deps.reverse\u27e9)\n\nmeta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=\nlet filter := if hide_non_prop then \u03bb e, may_be_proof e >>= guardb else \u03bb _, skip in\ntactic.explode.core filter e tt 0 default\n\nmeta def explode (n : name) : tactic unit :=\ndo const n _ \u2190 resolve_name n | fail \"cannot resolve name\",\n  d \u2190 get_decl n,\n  v \u2190 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 \u2190 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 : \u2200 {a : Prop}, a \u2192 (a \u2194 true)\n0\u2502   \u2502 a         \u251c Prop\n1\u2502   \u2502 h         \u251c a\n2\u2502   \u2502 hl        \u2502 \u250c a\n3\u2502   \u2502 trivial   \u2502 \u2502 true\n4\u25022,3\u2502 \u2200I        \u2502 a \u2192 true\n5\u2502   \u2502 hr        \u2502 \u250c true\n6\u25025,1\u2502 \u2200I        \u2502 true \u2192 a\n7\u25024,6\u2502 iff.intro \u2502 a \u2194 true\n8\u25021,7\u2502 \u2200I        \u2502 a \u2192 (a \u2194 true)\n9\u25020,8\u2502 \u2200I        \u2502 \u2200 {a : Prop}, a \u2192 (a \u2194 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 `\u2200E` 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 `\u2200E h ha` where `\u2200E` is\n    (n-ary) modus ponens.\n  * If the proof term is a lambda, we will also use `\u2200I` 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 `\u2200I` 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 `\u2200I` 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 \u2190 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 \u03a0-type -- whether it is visible or hidden behind a definition.\n\nFor instance, consider the following proof:\n\n```\nexample {\u03b1 \u03b2} (x y z : \u03b1 \u2192 \u03b2) (h\u2080 : x \u2264 y) (h\u2081 : y \u2264 z) : x \u2264 z :=\nbegin\n  apply le_trans,\nend\n```\n\nBecause `x \u2264 z` is definitionally equal to `\u2200 i, x i \u2264 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 {\u03b1} (gs : list (bool \u00d7 \u03b1)) : new_goals \u2192 list \u03b1\n| new_goals.non_dep_first :=\n  let \u27e8dep,non_dep\u27e9 := gs.partition (coe \u2218 prod.fst) in\n  non_dep.map prod.snd ++ dep.map prod.snd\n| new_goals.non_dep_only := (gs.filter (coe \u2218 bnot \u2218 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 \u00d7 expr)) : tactic bool :=\nms.mfoldl\n (\u03bb r m, do type \u2190 infer_type m.2,\n            b \u2190 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 \u00d7 expr)) : tactic unit :=\nmwhen (has_opt_auto_param_inst_for_apply ms) $ do\n  gs \u2190 get_goals,\n  ms.mmap' (\u03bb 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  \u03a0 (e : expr) (cfg : apply_cfg), list (bool \u00d7 name \u00d7  expr) \u2192 tactic (list (name \u00d7 expr))\n| e cfg gs :=\nfocus1 (do\n   { tgt : expr \u2190 target, t \u2190 infer_type e,\n     unify t tgt,\n     exact e,\n     gs' \u2190 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) \u2190 infer_type e >>= whnf | apply_core e cfg,\n   v \u2190 mk_meta_var d,\n   let b := b.has_var,\n   e \u2190 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 \u00d7 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 \u00d7 expr)) :=\ndo r \u2190 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 \u00d7 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 \u00d7 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 \u2192 name \u2192 option name)\n  (tac_name : string) : tactic unit :=\ndo tgt   \u2190 target >>= instantiate_mvars,\n   env   \u2190 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 \u2190 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. `\u2264`) so that rules like transitivity on `le : (\u03b1 \u2192 \u03b2) \u2192 (\u03b1 \u2192 \u03b2) \u2192 (\u03b1 \u2192 \u03b2)` will be\nconsidered to have three parameters and two assumptions (i.e. `f g h : \u03b1 \u2192 \u03b2`, `H\u2080 : f \u2264 g`,\n`H\u2081 : g \u2264 h`) instead of three parameters, two assumptions and then one more parameter\n(i.e. `f g h : \u03b1 \u2192 \u03b2`, `H\u2080 : f \u2264 g`, `H\u2081 : g \u2264 h`, `x : \u03b1`). Whereas `apply` would expect the goal\n`f x \u2264 h x`, `apply'` will work with the goal `f \u2264 h`.\n-/\nmeta def apply' (q : parse texpr) : tactic unit :=\nconcat_tags (do h \u2190 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 \u2190 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 \u2190 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 \u2192 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) \u2190 target_lhs_rhs,\n     t \u2190 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": "/-\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.Elab.App\n\n/-\nAuxiliary elaboration functions: AKA custom elaborators\n-/\n\nnamespace Lean.Elab.Term\nopen Meta\n\n@[builtinTermElab binrel] def elabBinRel : TermElab :=  fun stx expectedType? => do\n  match (\u2190 resolveId? stx[1]) with\n  | some f =>\n    let s \u2190 saveState\n    let (lhs, rhs) \u2190 withSynthesize (mayPostpone := true) do\n      let mut lhs \u2190 elabTerm stx[2] none\n      let mut rhs \u2190 elabTerm stx[3] none\n      if lhs.isAppOfArity ``OfNat.ofNat 3 then\n        lhs \u2190 ensureHasType (\u2190 inferType rhs) lhs\n      else if rhs.isAppOfArity ``OfNat.ofNat 3 then\n        rhs \u2190 ensureHasType (\u2190 inferType lhs) rhs\n      return (lhs, rhs)\n    let lhsType \u2190 inferType lhs\n    let rhsType \u2190 inferType rhs\n    let (lhs, rhs) \u2190\n      try\n        pure (lhs, \u2190 withRef stx[3] do ensureHasType lhsType rhs)\n      catch _ =>\n        try\n          pure (\u2190 withRef stx[2] do ensureHasType rhsType lhs, rhs)\n        catch _ =>\n          s.restore\n          -- Use default approach\n          let lhs \u2190 elabTerm stx[2] none\n          let rhs \u2190 elabTerm stx[3] none\n          let lhsType \u2190 inferType lhs\n          let rhsType \u2190 inferType rhs\n          pure (lhs, \u2190 withRef stx[3] do ensureHasType lhsType rhs)\n    elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false)\n  | none   => throwUnknownConstant stx[1].getId\n\n@[builtinTermElab forInMacro] def elabForIn : TermElab :=  fun stx expectedType? => do\n  match stx with\n  | `(forIn% $col $init $body) =>\n      match (\u2190 isLocalIdent? col) with\n      | none   => elabTerm (\u2190 `(let col := $col; forIn% col $init $body)) expectedType?\n      | some colFVar =>\n        tryPostponeIfNoneOrMVar expectedType?\n        let m \u2190 getMonad expectedType?\n        let colType \u2190 inferType colFVar\n        let elemType \u2190 mkFreshExprMVar (mkSort (mkLevelSucc (\u2190 mkFreshLevelMVar)))\n        let forInInstance \u2190\n          try\n            mkAppM ``ForIn #[m, colType, elemType]\n          catch\n            ex => tryPostpone; throwError \"failed to construct 'ForIn' instance for collection{indentExpr colType}\\nand monad{indentExpr m}\"\n        match (\u2190 trySynthInstance forInInstance) with\n        | LOption.some val =>\n          let ref \u2190 getRef\n          let forInFn \u2190 mkConst ``forIn\n          elabAppArgs forInFn #[] #[Arg.stx col, Arg.stx init, Arg.stx body] expectedType? (explicit := false) (ellipsis := false)\n        | LOption.undef    => tryPostpone; throwFailure forInInstance\n        | LOption.none     => throwFailure forInInstance\n  | _ => throwUnsupportedSyntax\nwhere\n  getMonad (expectedType? : Option Expr) : TermElabM Expr := do\n    match expectedType? with\n    | none => throwError \"invalid 'forIn%' notation, expected type is not available\"\n    | some expectedType =>\n      match (\u2190 isTypeApp? expectedType) with\n      | some (m, _) => return m\n      | none => throwError \"invalid 'forIn%' notation, expected type is not of of the form `M \u03b1`{indentExpr expectedType}\"\n  throwFailure (forInInstance : Expr) : TermElabM Expr :=\n    throwError \"failed to synthesize instance for 'forIn%' notation{indentExpr forInInstance}\"\n\nnamespace BinOp\n/-\n\nThe elaborator for `binop%` terms works as follows:\n\n1- Expand macros.\n2- Convert `Syntax` object corresponding to the `binop%` term into a `Tree`.\n   The `toTree` method visits nested `binop%` terms and parentheses.\n3- Synthesize pending metavariables without applying default instances and using the\n   `(mayPostpone := true)`.\n4- Tries to compute a maximal type for the tree computed at step 2.\n   We say a type \u03b1 is smaller than type \u03b2 if there is a (nondependent) coercion from \u03b1 to \u03b2.\n   We are currently ignoring the case we may have cycles in the coercion graph.\n   If there are \"uncomparable\" types \u03b1 and \u03b2 in the tree, we skip the next step.\n   We say two types are \"uncomparable\" if there isn't a coercion between them.\n   Note that two types may be \"uncomparable\" because some typing information may still be missing.\n5- We traverse the tree and inject coercions to the \"maximal\" type when needed.\n\nRecall that the coercions are expanded eagerly by the elaborator.\n\nProperties:\n\na) Given `n : Nat` and `i : Nat`, it can successfully elaborate `n + i` and `i + n`. Recall that Lean 3\n   fails on the former.\n\nb) The coercions are inserted in the \"leaves\" like in Lean 3.\n\nc) There are no coercions \"hidden\" inside instances, and we can elaborate\n```\naxiom Int.add_comm (i j : Int) : i + j = j + i\n\nexample (n : Nat) (i : Int) : n + i = i + n := by\n  rw [Int.add_comm]\n```\nRecall that the `rw` tactic used to fail because our old `binop%` elaborator would hide\ncoercions inside of a `HAdd` instance.\n\nRemarks:\n\nIn the new `binop%` elaborator the decision whether a coercion will be inserted or not\nis made at `binop%` elaboration time. This was not the case in the old elaborator.\nFor example, an instance, such as `HAdd Int ?m ?n`, could be created when executing\nthe `binop%` elaborator, and only resolved much later. We try to minimize this problem\nby synthesizing pending metavariables at step 3.\n\nFor types containing heterogeneous operators (e.g., matrix multiplication), step 4 will fail\nand we will skip coercion insertion. For example, `x : Matrix Real 5 4` and `y : Matrix Real 4 8`,\nthere is no coercion `Matrix Real 5 4` from `Matrix Real 4 8` and vice-versa, but\n`x * y` is elaborated successfully and has type `Matrix Real 5 8`.\n-/\n\nprivate inductive Tree where\n  | term  (ref : Syntax) (val : Expr)\n  | op    (ref : Syntax) (lazy : Bool) (f : Expr) (lhs rhs : Tree)\n\nprivate partial def toTree (s : Syntax) : TermElabM Tree := do\n  let result \u2190 go (\u2190 liftMacroM <| expandMacros s)\n  synthesizeSyntheticMVars (mayPostpone := true)\n  return result\nwhere\n  go (s : Syntax) := do\n    match s with\n    | `(binop% $f $lhs $rhs) => processOp (lazy := false) f lhs rhs\n    | `(binop_lazy% $f $lhs $rhs) => processOp (lazy := true) f lhs rhs\n    | `(($e)) => (\u2190 go e)\n    | _ =>\n       return Tree.term s (\u2190 elabTerm s none)\n\n  processOp (f lhs rhs : Syntax) (lazy : Bool) := do\n    let some f \u2190 resolveId? f | throwUnknownConstant f.getId\n    return Tree.op s (lazy := lazy) f (\u2190 go lhs) (\u2190 go rhs)\n\n-- Auxiliary function used at `analyze`\nprivate def hasCoe (fromType toType : Expr) : TermElabM Bool := do\n  if (\u2190 getEnv).contains ``CoeHTCT then\n    let u \u2190 getLevel fromType\n    let v \u2190 getLevel toType\n    let coeInstType := mkAppN (Lean.mkConst ``CoeHTCT [u, v]) #[fromType, toType]\n    match \u2190 trySynthInstance coeInstType (some (maxCoeSize.get (\u2190 getOptions))) with\n    | LOption.some _ => return true\n    | LOption.none   => return false\n    | LOption.undef  => return false -- TODO: should we do something smarter here?\n  else\n    return false\n\nprivate structure AnalyzeResult where\n  max?            : Option Expr := none\n  hasUncomparable : Bool := false -- `true` if there are two types `\u03b1` and `\u03b2` where we don't have coercions in any direction.\n\nprivate def isUnknow : Expr \u2192 Bool\n  | Expr.mvar ..        => true\n  | Expr.app f ..       => isUnknow f\n  | Expr.letE _ _ _ b _ => isUnknow b\n  | Expr.mdata _ b _    => isUnknow b\n  | _                   => false\n\nprivate def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do\n  let max? \u2190\n    match expectedType? with\n    | none => pure none\n    | some expectedType =>\n      let expectedType \u2190 instantiateMVars expectedType\n      if isUnknow expectedType then pure none else pure (some expectedType)\n  (go t *> get).run' { max? }\nwhere\n   go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do\n     unless (\u2190 get).hasUncomparable do\n       match t with\n       | Tree.op _ _ _ lhs rhs => go lhs; go rhs\n       | Tree.term _ val =>\n         let type \u2190 instantiateMVars (\u2190 inferType val)\n         unless isUnknow type do\n           match (\u2190 get).max? with\n           | none     => modify fun s => { s with max? := type }\n           | some max =>\n             unless (\u2190 withNewMCtxDepth <| isDefEqGuarded max type) do\n               if (\u2190 hasCoe type max) then\n                 return ()\n               else if (\u2190 hasCoe max type) then\n                 modify fun s => { s with max? := type }\n               else\n                 trace[Elab.binop] \"uncomparable types: {max}, {type}\"\n                 modify fun s => { s with hasUncomparable := true }\n\nprivate def mkOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr :=\n  elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false)\n\nprivate def toExpr (t : Tree) : TermElabM Expr := do\n  match t with\n  | Tree.term _ e               => return e\n  | Tree.op ref true f lhs rhs  => withRef ref <| mkOp f (\u2190 toExpr lhs) (\u2190 mkFunUnit (\u2190 toExpr rhs))\n  | Tree.op ref false f lhs rhs => withRef ref <| mkOp f (\u2190 toExpr lhs) (\u2190 toExpr rhs)\n\nprivate def applyCoe (t : Tree) (maxType : Expr) : TermElabM Tree := do\n  go t\nwhere\n  go (t : Tree) : TermElabM Tree := do\n    match t with\n    | Tree.op ref lazy f lhs rhs => return Tree.op ref lazy f (\u2190 go lhs) (\u2190 go rhs)\n    | Tree.term ref e       =>\n      let type \u2190 inferType e\n      trace[Elab.binop] \"visiting {e} : {type} =?= {maxType}\"\n      if (\u2190 isDefEqGuarded maxType type) then\n        return t\n      else\n        trace[Elab.binop] \"added coercion: {e} : {type} => {maxType}\"\n        withRef ref <| return Tree.term ref (\u2190 mkCoe maxType type e)\n\n@[builtinTermElab binop]\ndef elabBinOp : TermElab :=  fun stx expectedType? => do\n  let tree \u2190 toTree stx\n  let r    \u2190 analyze tree expectedType?\n  trace[Elab.binop] \"hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}\"\n  if r.hasUncomparable || r.max?.isNone then\n    let result \u2190 toExpr tree\n    ensureHasType expectedType? result\n  else\n    let result \u2190 toExpr (\u2190 applyCoe tree r.max?.get!)\n    trace[Elab.binop] \"result: {result}\"\n    ensureHasType expectedType? result\n\n@[builtinTermElab binop_lazy]\ndef elabBinOpLazy : TermElab := elabBinOp\n\n/--\n  Decompose `e` into `(r, a, b)`.\n\n  Remark: it assumes the last two arguments are explicit. -/\nprivate def relation? (e : Expr) : MetaM (Option (Expr \u00d7 Expr \u00d7 Expr)) :=\n  if e.getAppNumArgs < 2 then\n    return none\n  else\n    return some (e.appFn!.appFn!, e.appFn!.appArg!, e.appArg!)\n\n@[builtinTermElab \u00abcalc\u00bb]\ndef elabBinCalc : TermElab :=  fun stx expectedType? => do\n  let stepStxs := stx[1].getArgs\n  let mut proofs := #[]\n  let mut types  := #[]\n  for stepStx in stepStxs do\n    let type  \u2190 elabType stepStx[0]\n    let some (_, lhs, _) \u2190 relation? type |\n      throwErrorAt stepStx[0] \"invalid 'calc' step, relation expected{indentExpr type}\"\n    if types.size > 0 then\n      let some (_, _, prevRhs) \u2190 relation? types.back | unreachable!\n      unless (\u2190 isDefEqGuarded lhs prevRhs) do\n        throwErrorAt stepStx[0] \"invalid 'calc' step, left-hand-side is {indentD m!\"{lhs} : {\u2190 inferType lhs}\"}\\nprevious right-hand-side is{indentD m!\"{prevRhs} : {\u2190 inferType prevRhs}\"}\"\n    types := types.push type\n    let proof \u2190 elabTermEnsuringType stepStx[2] type\n    synthesizeSyntheticMVars\n    proofs := proofs.push proof\n  let mut result := proofs[0]\n  let mut resultType := types[0]\n  for i in [1:proofs.size] do\n    let some (r, a, b) \u2190 relation? resultType | unreachable!\n    let some (s, _, c) \u2190 relation? (\u2190 instantiateMVars types[i]) | unreachable!\n    let (\u03b1, \u03b2, \u03b3)       := (\u2190 inferType a, \u2190 inferType b, \u2190 inferType c)\n    let (u_1, u_2, u_3) := (\u2190 getLevel \u03b1, \u2190 getLevel \u03b2, \u2190 getLevel \u03b3)\n    let t \u2190 mkFreshExprMVar (\u2190 mkArrow \u03b1 (\u2190 mkArrow \u03b3 (mkSort levelZero)))\n    let selfType := mkAppN (Lean.mkConst ``Trans [u_1, u_2, u_3]) #[\u03b1, \u03b2, \u03b3, r, s, t]\n    match (\u2190 trySynthInstance selfType) with\n    | LOption.some self =>\n      result := mkAppN (Lean.mkConst ``Trans.trans [u_1, u_2, u_3]) #[\u03b1, \u03b2, \u03b3, r, s, t, self, a, b, c, result, proofs[i]]\n      resultType := (\u2190 instantiateMVars (\u2190 inferType result)).headBeta\n      unless (\u2190 relation? resultType).isSome do\n        throwErrorAt stepStxs[i] \"invalid 'calc' step, step result is not a relation{indentExpr resultType}\"\n    | _ => throwErrorAt stepStxs[i] \"invalid 'calc' step, failed to synthesize `Trans` instance{indentExpr selfType}\"\n    pure ()\n  ensureHasType expectedType? result\n\nbuiltin_initialize\n  registerTraceClass `Elab.binop\n\nend BinOp\n\nend Lean.Elab.Term\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/Elab/Extra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.0627892081586091, "lm_q1q2_score": 0.025576141645437908}}
{"text": "/-!\n# Monad Stacks\nBefore you read this: This chapter does not attempt to introduce the concept\nof a monad in general, it assume this as a given and explains the monads\nand constructs on top of them that are essential to Lean meta programming.\nIf you don't know what a monad is already you can read (TODO: Link to monad tutorial).\n\n## Monad Transformers\nQuite often in functional programming with monads one wants to have the power\nof more than one monad available. Specifically in Lean meta programming it\nis a very common pattern that we have some sort of read only input, an\nexecution context, available to us, as well as the ability to operate on\na mutable state. Both of these issues have monads that can solve them\nseparately already, namely the `Reader` monad for read only input and the\n`StateM` monad for the mutable state. Now we can try to just \"stack\" them\nontop like this:`\n-/\nnamespace Playground1\nabbrev Context := Nat\nabbrev State := String\n\nabbrev MyM (\u03b1 : Type) := Reader Context (StateM State \u03b1)\n\nend Playground1\n/-!\nAnd this will indeed type check, however we have a very annoying issue,\nif we attempt to synthesize a `Monad` instance for this via the `#synth` command:\n-/\nnamespace Playground1\n\n-- failed to synthesize\n--  Monad MyM\n#synth Monad MyM\n\ndef test1 : MyM Unit := pure () -- failure, pure requires a monad instance\ndef test2 : MyM Unit := do\n  let res \u2190 test1 -- failure, <- syntax requires a monad instance\n  pure res -- same issue as with the pure above\n\nend Playground1\n/-!\nWe can fix this by manually declaring the instance though:\n-/\nnamespace Playground1\n\ninstance : Monad MyM where\n  pure x := fun ctx state => (x, state)\n  bind x f := fun ctx state =>\n    let (res, newState) := x ctx state\n    f res ctx newState\n\nend Playground1\n\n/-!\nNow while we can use bind, aka the `<-` Syntax and `pure` now we are still\nmissing convenience functions:\n- `Reader` should give us `read` to get the context\n- `StateM` should give us `get` and `set` to get and set the state\n-/\nnamespace Playground1\n\ndef foo : MyM Unit := do\n  let ctx \u2190 read -- failure because read is not found, the bind syntax works\n  let state \u2190 get -- failure because get is not found, the bind syntax works\n  set state -- failure because set is not found\n  pure () -- pure also works thanks to the monad instance!\n\nend Playground1\n/-!\nNow we could of course write all of these functions ourselves and keep repeating\nourselves whenever we do this sort of \"combining monads\" again but it would obviously\nbe much nicer if we could just have all of this done for us automatically.\nThis is where monad transformers come in. A monad transformer gives us a way\nto combine the effects that certain monads give us (not all monad can be turned into\na transformer) in a nice way. For these monads specifically there is the `Reader`\ntransformer `ReaderT` and the `StateM` transformer `StateT`, let's see how they\nperform:\n-/\nnamespace Playground2\nabbrev Context := Nat\nabbrev State := String\n\n-- `StateM` is defined as `StateM \u03c3 \u03b1 = StateT \u03c3 Id \u03b1` so the following two are equivalent.\nabbrev MyM  := ReaderT Context (StateT State Id)\nabbrev MyM2  := ReaderT Context (StateM State)\n-- This definition of `StateM` makes perfect sense since the `Id` monad has no effect,\n-- so combining it with `StateT` will create a monad that has only the state effect.\n-- Can you guess the definition of `Reader` based on `ReaderT`?\n\n#synth Monad MyM -- monad instance!\n#synth Monad MyM2 -- monad instance!\n\nend Playground2\n/-!\nSo that's the monad instance for free. The other thing that failed above,\nwas that we didn't have access to `read`, `get` and `set`, anymore, let's\nsee whether our monad transformers allow this:\n-/\nnamespace Playground2\n\ndef testReader : MyM String := do\n  let get \u2190 read -- obtain our context\n  pure s!\"This is my context: {get}\"\n\ndef testState (add : State) : MyM Unit := do\n  let old \u2190 get\n  set s!\"{old} + {add}\"\n\ndef testStateChange : MyM String := do\n  let _ \u2190 testState \"new stuff!\"\n  testState \"more new stuff!\"\n  get\n\ndef MyM.run (context : Context) (state : State) (x : MyM \u03b1) : \u03b1 :=\n  Prod.fst <$> StateT.run (ReaderT.run x context) state\n\n#eval MyM.run 12 \"hello\" testReader -- \"This is my context: 12\"\n#eval MyM.run 12 \"hello\" testStateChange -- \"hello + new stuff! + more new stuff!\"\n\nend Playground2\n/-!\nNice! Everything just seems to work here, if you are interested in how\nLean does this internally you can check out the infrastructure around:\n- `MonadReader`, `MonadReaderOf` for the `ReaderT` part\n- `MonadState`, `MonadStateOf` for the `StateT` part\n\nfor most applications the idea that our `ReaderT` `StateT` monad transformers\njust combine nicely out of the box is perfectly fine though.\n\n### Lifting\nThe next interesting question one might come up with is, can we just combine\nmonad stacks nicely like this as well? What we are aiming for is that\nassuming we have a monad stack `S` and another one of our monad stacks `MyM`,\nthat is built on top of `S`, we want to be able to execute computations inside of `S`\njust as easily inside of `MyM` as well. Let's see if the built-in stacks\ncan do this already, as an example for `S` we will use the `IO` monad which is\na monad stack under the hood as well:\n-/\nnamespace Playground3\n\nabbrev Context := Nat\nabbrev State := String\n\nabbrev MyM  := ReaderT Context (StateT State IO)\n\ndef test : MyM Unit := do\n  let old \u2190 get\n  let new := s!\"Number {\u2190read}, String: {old}\"\n  IO.println s!\"Old was: {old}, New will be: {new}\"\n  set new\n\ndef MyM.run (context : Context) (state : State) (x : MyM \u03b1) : IO \u03b1 :=\n  Prod.fst <$> StateT.run (ReaderT.run x context) state\n\n#eval MyM.run 12 \"hello\" test -- Old was: hello, New will be: Number 12, String: hello\n\nend Playground3\n/-!\nThis also just worked without any additional effort on our side! The infrastructure\nresponsible for this is `MonadLift` and `MonadLiftT` as well as some effort\nin the implementation of `do` to figure out when to lift. However you can again\nignore this if you want, it just works out of the box most of the time.\n-/\n\n/-!\n## Error monads\nNext up we'll take a look at 2 monads you have most likely not heard of yet,\nboth of which will show up in meta programming.\n\nFirst is `EStateM`, as it's name suggests it is very similar to `StateM` but\nwith the fundamental difference that it can throw some sort of `E`rror,\nas such it is parameterized by 3 types: `EStateM Error State Value`.\nIt is one of the monads that implement the `MonadExcept`/`MonadExceptOf`\nmachinery which allows us to introduce a concept of exceptions into our\nmonad stacks:\n-/\nnamespace Playground4\n\nabbrev Context := Nat\nabbrev Error := String\nabbrev State := Nat\n\nabbrev MyM := ReaderT Nat (EStateM Error State)\n\ndef alarm (x : String) : MyM Unit := do\n  throw s!\"Alarm!: {x}\"\n\ndef main : MyM String := do\n  alarm \"hi\"\n  pure \"test\"\n\ndef MyM.run (context : Context) (state : State) (x : MyM \u03b1) : Sum \u03b1 Error :=\n  let res := EStateM.run (ReaderT.run x context) state\n  match res with\n  | .ok v _ => Sum.inl v\n  | .error e _ => Sum.inr e\n\n#eval MyM.run 12 13 main -- Sum.inr \"Alarm!: hi\"\n\nend Playground4\n/-!\nWhat happened here is that `alarm` threw an exception and because we didn't\nhave any mechanism in place to catch it, the rest of our program didn't get\nexecuted and the error got propagated up to us. Luckily Lean has some\nnice built-in syntax to catch exceptions (if we want to do so):\n-/\nnamespace Playground4\n\ndef main2 : MyM String := do\n  try\n    alarm \"hi\"\n    pure \"Success\"\n  catch err =>\n    pure s!\"Got an error: {err}\"\n\n#eval MyM.run 12 13 main2 -- Sum.inl \"Got an error: Alarm!: hi\"\n\nend Playground4\n/-!\nThere exists another monad that implements `MonadExcept`, its the one underlying `IO`, `EIO`.\n`EIO` is basically `IO` but parameterized with an exception type.\n`IO` sets this to the `IO.Error`, a type based on UNIX errno. Unsurprisingly\n`EIO` (and thus `IO`) have the capability to throw exceptions.\n\nNote: `EIO` is in fact based on `EStateM`, this is however not a tutorial on the inner\nworkings of `IO` so we will leave it at that.\n\n### `StateRefT`\n`StateT` is implemented as a function that forwards the state\nfrom one monadic computation to the next like this: `State -> (Value, State)`.\nEspecially when updating the state lots of times this does of course become\nrather inefficient so there is an alternative to it, `StateRefT`. Thanks to\n`MonadState` the `StateRefT` transformer behaves basically identical to the\nuser. Internally it works with an `ST.Ref` which is in essence a truly\nmutable memory location and thus much more efficient than ordinary `StateT`,\nhence most of the meta programming monad stacks are implemented with it instead\nof `StateT`. There is only a single issue with this, Lean is a pure programming\nlanguage so we can't just have mutable memory locations like that, this is why\n`StateRefT` expects another monad stack that can provide this capability.\nRight now these are:\n- The `IO` family and stacks built on top of them, that is `IO`, `EIO` and `BaseIO`\n- `EST` and stacks built on top of it, `EST` is a (not reducible) alias to `EStateM`\n  (TODO: Figure out why this distinction is made)\n\nFor our example we will simply use `IO`.\n-/\nnamespace Playground5\n\nabbrev Context := Nat\nabbrev State := String\n\nabbrev MyM  := ReaderT Context (StateRefT State IO)\n\ndef test : MyM Unit := do\n  let old \u2190 get\n  let new := s!\"Number {\u2190read}, String: {old}\"\n  IO.println s!\"Old was: {old}, New will be: {new}\"\n  set new\n\ndef MyM.run (context : Context) (state : State) (x : MyM \u03b1) : IO \u03b1 :=\n  -- We use StateRefT' because StateRefT is actually a macro, figuring out the\n  -- details on how to provide the mutable memory location based on the stack we are building on.\n  Prod.fst <$> StateRefT'.run (ReaderT.run x context) state\n\n#eval MyM.run 12 \"hello\" test -- Old was: hello, New will be: Number 12, String: hello\n\nend Playground5\n\n/-!\n## More `Monad` type class extensions\nLast but not least lets take a look at a few more, general, `Monad` extensions\nthat might be useful along the way.\n### `MonadWithReader`\nProvides a function `withReader : (\u03c1 \u2192 \u03c1) \u2192 m \u03b1 \u2192 m \u03b1` where `\u03c1` is the context\nstored inside of a `Reader`. The idea is, that you pass it a function\nthat will be applied to your context and the resulting context will be passed on to\nthe second argument as its context, returning the result of that computation.\nThis allows you to temporarily change the context in some sub section of your\nprogram before continuing with the original one. In order to make this accessible\nin monad stacks as well there exists an equivalent machinery to `MonadReader`/`MonadReaderOf`,\nnamed `MonadWithReaderOf`.\n### `MonadFinally`\n`MonadFinally` provides a function `tryFinally' : m \u03b1 \u2192 (Option \u03b1 \u2192 m \u03b2) \u2192 m (\u03b1 \u00d7 \u03b2)`\nthat works as follows: `tryFinally' x f` runs `x` and then the \"finally\" computation `f`.\nWhen `x` succeeds with `a : \u03b1`, `f (some a)` is returned. If `x` fails for `m`'s definition\nof failure, `f none` is returned. Hence `tryFinally'` can be thought of as performing the same\nrole as a finally block in an imperative programming language. (TODO: This is a docstring,\nlink to rendered documentation instead). Like above `MonadFinally` is implemented\nso that it is accessible throughout monad stacks that are based on a monad which implements\nthis behaviour.\n### `MonadBackTrack`\nTODO: The doc string does explain what it does: Similar to MonadState,\nbut it retrieves/restores only the \"backtrackable\" part of the state.\n\nHowever this is a little abstract and probably requires an example, the issue\nwith this is that all instances of `MonadBackTrack` are inside the meta stack\nso I'm not quite sure how to do one.\n### `MonadControl`\nIs explained in an excellent doc string [here](https://github.com/leanprover/lean4/blob/575b1187c500af22bfc4c49c8aa58371d91843fa/src/Init/Control/Basic.lean#L69-L178)\n### `MonadFunctor`\nTODO: Again the doc string explains it: A functor in the category of monads.\nCan be used to lift monad-transforming functions. Based on pipes' MFunctor,\nbut not restricted to monad transformers. Alternatively, an implementation\nof MonadTransFunctor.\n\nThis might however be rather confusing to most people (including me) so\nwe should probably try to come up with some nice examples as well.\n-/\n\n\n/-!\n# Monads used in Lean 4\n\nHere is a list of monads that are used in Lean 4 that you might run into. Some have already been discussed above.\nMonad stacks can be quite tall in Lean 4. For example if we were to write out the full defininition of `TacticM`:\n\n```lean\nTacticM :=\n  EStateM Exception IO.RealWorld\n  |> StateRefT Core.State\n  |> ReaderT Core.Context\n  |> StateRefT Meta.State\n  |> ReaderT Meta.Context\n  |> StateRefT Elab.Term.State\n  |> ReaderT Elab.Term.Context\n  |> StateRefT Elab.Tactic.State\n  |> ReaderT Elab.Tactic.Context\n```\n\n## The IO monads\n\nAn IO monad is used to create computations that interact with the rest of the computer.\nThings like: connecting to the internet, writing files etc.\nUse an IO monad to say, \"hey! this code can cause arbitrary OS-level side effects\".\nTODO: potentially there will be a whole chapter on the IO API, so we will just focus on the monad here.\n\nIn Lean 4 there are a family of IO monads: `IO`, `EIO \u03b5`, `BaseIO`.\n`EIO \u03b5` is the main one, it is defined as `EStateM \u03b5 IO.RealWorld`: you can throw errors of type `\u03b5` and it has a strange state object called `IO.Realworld`.\n\nThis state is a little strange.\nThere is a magic definition `IO.RealWorld : Type := Unit`, that represents the 'io state' of your application.\nYou should never actually use `IO.RealWorld`.\nA description of how it works in Haskell is given [here](https://www.well-typed.com/blog/2014/06/understanding-the-realworld/).\nTo summarise: it's essentially a placeholder for the current state of everything outside your app.\nIt seems to just be some bookkeeping for the compiler (TODO: check with authorities), since if you are passing this `() : IO.Realworld` object around,\nthe optimiser will never try to reorder operations and so on.\nYou should always use `EIO` and items defined in terms of `EIO`, because of course you can't reset the state of reality.\n\nThe difference between `IO`, `BaseIO` and `EIO \u03b5` are the exceptions that are thrown. `BaseIO` has no exceptions and `IO := EIO IO.Error`.\n`IO.Error` is specialised for errors that can happen when interfacing with the OS (rather than lean-specific errors which use `Exception`).\nThere is an error type for all of the errors that you might get from the OS while doing syscalls.\nThere is also a `userError (msg : String)` for when you want to pass a user error.\n\n## `CoreM`\n\nThe best way to think about `CoreM` is that it tracks everything Lean-related that doesn't yet involve managing expressions.\nIt's a set of common context and state for the other metaprogramming monads.\nYou can use this to running attribute handlers (`AttrM := CoreM`), manipulating the environment and setting options.\n\nIt is defined as `ReaderT Core.Context $ StateRefT Core.State $ EIO Exception`.\n\nThe main things in the context are:\n- The options that are set. I.e. storing the settings from `set_option trace.simplify.rewrite true` commands.\n- The current namespace.\n- Which namespaces are currently open. That is, things that have been opened with the `open` command.\n\nThe main things in the state are:\n- The current `Environment`\n- The name generator (responsible for making sure that unique names are created.)\n- The trace state (where messages to the user are stored)\n\n## `MetaM`\n\n`CoreM` is `MetaM` with a local context and a metavariable state.\nIt is used for building expressions where you need to handle metavariables and local contexts.\nYou can learn more about it in [[main/metam]].\n\n## `TermElabM`\n\nThe `TermElabM` tracks a lot of extra information that is needed to turn Lean syntax in to expressions: pending elaboration problems, pending tactics to be executed, etc.\nThis is used for writing term elaborators. You will encounter it when writing `elab` methods for custom syntax.\n\n## `TacticM`\n\nThe tactic monad.\nThis is `TermElabM` with a list of goals. It is used to implement your own tactics.\n\n## `CommandElabM`\n\nThis one sits outside the main monad stack.\nIt works similarly to a combined `TermElabM` and `CoreM`. It is used for elaborating commands.\n\n## `MacroM`\n\nA macro is a function `Syntax \u2192 MacroM Syntax`. The macro state and context contains information\nneeded to expand macros hygienically. You can learn more about macros in [[main/macros]] and [The Lean manual](https://leanprover.github.io/lean4/doc/macro_overview.html).\n\n## `RequestM`\n\nThis is used to handle the requests in the Lean language server from vscode or emacs.\n\n## `ImportM`\n\nTODO\n\n## Conversion table\n\nOften when writing monads you will want to run monad `A` in monad `B`.\nThis is done with 'running' and 'lifting' monads.\nHere is a table giving methods that can be used to lift or run monads from other monads.\n\n| run \u2193 in \u2192 | IO | `CoreM`  | `MetaM`  | `TermElabM` | `TacticM` | `CommandElabM` |\n| ----------- | ---- | -------  | -------  | ----------- |  -------- |  -------------- |\n| IO        |   .   | `liftM`  | `liftM`  | `liftM`     |   `liftM`        | `liftM`\n| `CoreM`     |   `CoreM.toIO`, `CoreM.run`   |    .      | `liftM`  | `liftM`     |   `liftM`        | `liftCoreM`\n| `MetaM`     | `MetaM.toIO`     | `MetaM.run`      |    .      | `liftM`     |   `liftM`        |\n| `TermElabM` |      |          |    `TermElabM.run`      |      .       |     `liftM`      | `runTermElabM`, `liftTermElabM`\n| `TacticM`   |      |          |    |    `Lean.Elab.Tactic.run`         |       .    |\n| `CommandElabM` | `CommandElabM.run`  |          |          |             |          |        .        |\n\n\nIf you are writing your own definitions involving monads, rather than specifically\nusing a concrete monad like `MetaM`, consider using a variable monad `M` with monad typeclasses for the\nbits that you need: eg `[MonadEnv M]` if you are using the environment or `[MonadControlT MetaM M]` if you want to use the metavariable context.\nDoing this means that you have to worry less about lifting and running concrete monads.\n\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/temp/monad-stacks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.05500528577614074, "lm_q1q2_score": 0.02557204379117013}}
{"text": "namespace List\n\n@[simp] theorem filter_nil {p : \u03b1 \u2192 Bool} : filter p [] = [] := by\n  simp [filter, filterAux, reverse, reverseAux]\n\ntheorem cons_eq_append (a : \u03b1) (as : List \u03b1) : a :: as = [a] ++ as := rfl\n\ntheorem filter_cons (a : \u03b1) (as : List \u03b1) :\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 \u03b1} {p : \u03b1 \u2192 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 \u2192 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\ninductive Label\n  /-- elim lemma: LHS has 0 head coes and \u2265 1 internal coe -/\n  | elim\n  /-- move lemma: LHS has 1 head coe and 0 internal coes,\n  RHS has 0 head coes and \u2265 1 internal coes -/\n  | move\n  /-- squash lemma: LHS has \u2265 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 \u2190 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 \u2190 getCoeFnInfo? fn then\n      if e.getAppNumArgs >= info.numArgs then\n        return (\u2190 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 \u2190 getCoeFnInfo? fn then\n        if e.getAppNumArgs >= info.numArgs then\n          let mut coes := (\u2190 countHeadCoes (e.getArg! info.coercee)) + 1\n          for i in [info.numArgs:e.getAppNumArgs] do\n            coes := coes + (\u2190 countCoes (e.getArg! i))\n          return coes\n    return (\u2190 (\u2190 getSimpArgs e).mapM countCoes).foldl (\u00b7+\u00b7) 0\n\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\ndef countInternalCoes (e : Expr) : MetaM Nat :=\n  return (\u2190 countCoes e) - (\u2190 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 \u2190 whnf ty\n    let (lhs, rhs) \u2190\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 \u2194, but is{indentExpr ty}\"\n    let lhsCoes \u2190 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 \u2190 countHeadCoes lhs\n    let rhsHeadCoes \u2190 countHeadCoes rhs\n    let rhsInternalCoes \u2190 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 \u2190\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 \u2190 pure {\n  up := \u2190 mkSimpExt (decl_name% ++ `up)\n  down := \u2190 mkSimpExt (decl_name% ++ `down)\n  squash := \u2190 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 := (\u2190 getConstInfo decl).type\n  match \u2190 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 `\u2191`, `\u21d1` and `\u21a5`, 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 : \u2115} : (\u2191m : \u2124) = \u2191n \u2194 m = n\n\n@[norm_cast] theorem coe_int_denom (n : \u2124) : (n : \u211a).denom = 1\n\n@[norm_cast] theorem cast_id : \u2200 n : \u211a, \u2191n = n\n\n@[norm_cast] theorem coe_nat_add (m n : \u2115) : (\u2191(m + n) : \u2124) = \u2191m + \u2191n\n\n@[norm_cast] theorem cast_coe_nat (n : \u2115) : ((n : \u2124) : \u03b1) = n\n\n@[norm_cast] theorem cast_one : ((1 : \u211a) : \u03b1) = 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 : \u2115) : (n : \u2102).re = n := by\n  rw [\u2190 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 (\u00b7.1.isNatLit?)).getD (eval_prio default)\n    match label.bind (\u00b7.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": "open tactic\n\nmeta def force { \u03b1 : Type } (t : tactic \u03b1) : tactic \u03b1 :=\n  do gs \u2190 get_goals,\n     a \u2190 t,\n     gs' \u2190 get_goals,\n     guard (gs \u2260 gs') <|> fail \"force tactic failed\",\n     return a\n\nnamespace tactic.interactive\n  meta def force (t : itactic) : tactic unit := _root_.force t\nend tactic.interactive\n\nset_option pp.all true\n\nlemma a ( p q : nat ) : 1 = 1 :=\nbegin\n  -- p q : nat\n  -- \u22a2 @eq.{1} nat (@one.{0} nat nat.has_one) (@one.{0} nat nat.has_one)\n  force {\n    revert q,\n    intron 1\n    -- p q : nat\n    -- \u22a2 @eq.{1} nat (@one.{0} nat nat.has_one) (@one.{0} nat nat.has_one)\n  } -- ... but force succeeds here.\nend", "meta": {"author": "semorrison", "repo": "proof", "sha": "5ee398aa239a379a431190edbb6022b1a0aa2c70", "save_path": "github-repos/lean/semorrison-proof", "path": "github-repos/lean/semorrison-proof/proof-5ee398aa239a379a431190edbb6022b1a0aa2c70/lean/20170512-force-tactic-error.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.06560483517543499, "lm_q1q2_score": 0.025495221588240007}}
{"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 \u03b1` is the type of \"partial values\" of type `\u03b1`. It\n  is similar to `option \u03b1` except the domain condition can be an\n  arbitrary proposition, not necessarily decidable. -/\nstructure roption (\u03b1 : Type u) where\n  dom : Prop\n  get : dom \u2192 \u03b1\n\nnamespace roption\n\n\n/-- Convert an `roption \u03b1` with a decidable domain to an option -/\ndef to_option {\u03b1 : Type u_1} (o : roption \u03b1) [Decidable (dom o)] : Option \u03b1 :=\n  dite (dom o) (fun (h : dom o) => some (get o h)) fun (h : \u00acdom o) => none\n\n/-- `roption` extensionality -/\ntheorem ext' {\u03b1 : Type u_1} {o : roption \u03b1} {p : roption \u03b1} (H1 : dom o \u2194 dom p)\n    (H2 : \u2200 (h\u2081 : dom o) (h\u2082 : dom p), get o h\u2081 = get p h\u2082) : o = p :=\n  sorry\n\n/-- `roption` eta expansion -/\n@[simp] theorem eta {\u03b1 : Type u_1} (o : roption \u03b1) : (mk (dom o) fun (h : dom o) => get o h) = o :=\n  sorry\n\n/-- `a \u2208 o` means that `o` is defined and equal to `a` -/\nprotected def mem {\u03b1 : Type u_1} (a : \u03b1) (o : roption \u03b1) := \u2203 (h : dom o), get o h = a\n\nprotected instance has_mem {\u03b1 : Type u_1} : has_mem \u03b1 (roption \u03b1) := has_mem.mk roption.mem\n\ntheorem mem_eq {\u03b1 : Type u_1} (a : \u03b1) (o : roption \u03b1) : a \u2208 o = \u2203 (h : dom o), get o h = a := rfl\n\ntheorem dom_iff_mem {\u03b1 : Type u_1} {o : roption \u03b1} : dom o \u2194 \u2203 (y : \u03b1), y \u2208 o := sorry\n\ntheorem get_mem {\u03b1 : Type u_1} {o : roption \u03b1} (h : dom o) : get o h \u2208 o := Exists.intro h rfl\n\n/-- `roption` extensionality -/\ntheorem ext {\u03b1 : Type u_1} {o : roption \u03b1} {p : roption \u03b1} (H : \u2200 (a : \u03b1), a \u2208 o \u2194 a \u2208 p) : o = p :=\n  sorry\n\n/-- The `none` value in `roption` has a `false` domain and an empty function. -/\ndef none {\u03b1 : Type u_1} : roption \u03b1 := mk False False._oldrec\n\nprotected instance inhabited {\u03b1 : Type u_1} : Inhabited (roption \u03b1) := { default := none }\n\n@[simp] theorem not_mem_none {\u03b1 : Type u_1} (a : \u03b1) : \u00aca \u2208 none :=\n  fun (h : a \u2208 none) => Exists.fst h\n\n/-- The `some a` value in `roption` has a `true` domain and the\n  function returns `a`. -/\ndef some {\u03b1 : Type u_1} (a : \u03b1) : roption \u03b1 := mk True fun (_x : True) => a\n\ntheorem mem_unique {\u03b1 : Type u_1} : relator.left_unique has_mem.mem := sorry\n\ntheorem get_eq_of_mem {\u03b1 : Type u_1} {o : roption \u03b1} {a : \u03b1} (h : a \u2208 o) (h' : dom o) :\n    get o h' = a :=\n  mem_unique (Exists.intro h' rfl) h\n\n@[simp] theorem get_some {\u03b1 : Type u_1} {a : \u03b1} (ha : dom (some a)) : get (some a) ha = a := rfl\n\ntheorem mem_some {\u03b1 : Type u_1} (a : \u03b1) : a \u2208 some a := Exists.intro trivial rfl\n\n@[simp] theorem mem_some_iff {\u03b1 : Type u_1} {a : \u03b1} {b : \u03b1} : b \u2208 some a \u2194 b = a := sorry\n\ntheorem eq_some_iff {\u03b1 : Type u_1} {a : \u03b1} {o : roption \u03b1} : o = some a \u2194 a \u2208 o := sorry\n\ntheorem eq_none_iff {\u03b1 : Type u_1} {o : roption \u03b1} : o = none \u2194 \u2200 (a : \u03b1), \u00aca \u2208 o := sorry\n\ntheorem eq_none_iff' {\u03b1 : Type u_1} {o : roption \u03b1} : o = none \u2194 \u00acdom o :=\n  { mp := fun (e : o = none) => Eq.symm e \u25b8 id,\n    mpr := fun (h : \u00acdom o) => iff.mpr eq_none_iff fun (a : \u03b1) (h' : a \u2208 o) => h (Exists.fst h') }\n\ntheorem some_ne_none {\u03b1 : Type u_1} (x : \u03b1) : some x \u2260 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 {\u03b1 : Type u_1} {o : roption \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), o = some x := sorry\n\ntheorem eq_none_or_eq_some {\u03b1 : Type u_1} (o : roption \u03b1) : o = none \u2228 \u2203 (x : \u03b1), o = some x :=\n  sorry\n\n@[simp] theorem some_inj {\u03b1 : Type u_1} {a : \u03b1} {b : \u03b1} : some a = some b \u2194 a = b :=\n  function.injective.eq_iff\n    fun (a b : \u03b1) (h : some a = some b) => congr_fun (eq_of_heq (and.right (mk.inj h))) trivial\n\n@[simp] theorem some_get {\u03b1 : Type u_1} {a : roption \u03b1} (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 {\u03b1 : Type u_1} {a : roption \u03b1} {ha : dom a} {b : \u03b1} :\n    get a ha = b \u2194 a = some b :=\n  sorry\n\nprotected instance none_decidable {\u03b1 : Type u_1} : Decidable (dom none) := decidable.false\n\nprotected instance some_decidable {\u03b1 : Type u_1} (a : \u03b1) : Decidable (dom (some a)) :=\n  decidable.true\n\ndef get_or_else {\u03b1 : Type u_1} (a : roption \u03b1) [Decidable (dom a)] (d : \u03b1) : \u03b1 :=\n  dite (dom a) (fun (ha : dom a) => get a ha) fun (ha : \u00acdom a) => d\n\n@[simp] theorem get_or_else_none {\u03b1 : Type u_1} (d : \u03b1) : get_or_else none d = d := dif_neg id\n\n@[simp] theorem get_or_else_some {\u03b1 : Type u_1} (a : \u03b1) (d : \u03b1) : get_or_else (some a) d = a :=\n  dif_pos trivial\n\n@[simp] theorem mem_to_option {\u03b1 : Type u_1} {o : roption \u03b1} [Decidable (dom o)] {a : \u03b1} :\n    a \u2208 to_option o \u2194 a \u2208 o :=\n  sorry\n\n/-- Convert an `option \u03b1` into an `roption \u03b1` -/\ndef of_option {\u03b1 : Type u_1} : Option \u03b1 \u2192 roption \u03b1 := sorry\n\n@[simp] theorem mem_of_option {\u03b1 : Type u_1} {a : \u03b1} {o : Option \u03b1} : a \u2208 of_option o \u2194 a \u2208 o :=\n  sorry\n\n@[simp] theorem of_option_dom {\u03b1 : Type u_1} (o : Option \u03b1) :\n    dom (of_option o) \u2194 \u21a5(option.is_some o) :=\n  sorry\n\ntheorem of_option_eq_get {\u03b1 : Type u_1} (o : Option \u03b1) :\n    of_option o = mk (\u21a5(option.is_some o)) option.get :=\n  sorry\n\nprotected instance has_coe {\u03b1 : Type u_1} : has_coe (Option \u03b1) (roption \u03b1) := has_coe.mk of_option\n\n@[simp] theorem mem_coe {\u03b1 : Type u_1} {a : \u03b1} {o : Option \u03b1} : a \u2208 \u2191o \u2194 a \u2208 o := mem_of_option\n\n@[simp] theorem coe_none {\u03b1 : Type u_1} : \u2191none = none := rfl\n\n@[simp] theorem coe_some {\u03b1 : Type u_1} (a : \u03b1) : \u2191(some a) = some a := rfl\n\nprotected theorem induction_on {\u03b1 : Type u_1} {P : roption \u03b1 \u2192 Prop} (a : roption \u03b1)\n    (hnone : P none) (hsome : \u2200 (a : \u03b1), P (some a)) : P a :=\n  or.elim (classical.em (dom a)) (fun (h : dom a) => some_get h \u25b8 hsome (get a h))\n    fun (h : \u00acdom a) => Eq.symm (iff.mpr eq_none_iff' h) \u25b8 hnone\n\nprotected instance of_option_decidable {\u03b1 : Type u_1} (o : Option \u03b1) :\n    Decidable (dom (of_option o)) :=\n  sorry\n\n@[simp] theorem to_of_option {\u03b1 : Type u_1} (o : Option \u03b1) : to_option (of_option o) = o :=\n  option.cases_on o (Eq.refl (to_option (of_option none)))\n    fun (o : \u03b1) => Eq.refl (to_option (of_option (some o)))\n\n@[simp] theorem of_to_option {\u03b1 : Type u_1} (o : roption \u03b1) [Decidable (dom o)] :\n    of_option (to_option o) = o :=\n  ext fun (a : \u03b1) => iff.trans mem_of_option mem_to_option\n\ndef equiv_option {\u03b1 : Type u_1} : roption \u03b1 \u2243 Option \u03b1 :=\n  equiv.mk (fun (o : roption \u03b1) => to_option o) of_option sorry sorry\n\nprotected instance order_bot {\u03b1 : Type u_1} : order_bot (roption \u03b1) :=\n  order_bot.mk none (fun (x y : roption \u03b1) => \u2200 (i : \u03b1), i \u2208 x \u2192 i \u2208 y)\n    (partial_order.lt._default fun (x y : roption \u03b1) => \u2200 (i : \u03b1), i \u2208 x \u2192 i \u2208 y) sorry sorry sorry\n    sorry\n\nprotected instance preorder {\u03b1 : Type u_1} : preorder (roption \u03b1) :=\n  partial_order.to_preorder (roption \u03b1)\n\ntheorem le_total_of_le_of_le {\u03b1 : Type u_1} {x : roption \u03b1} {y : roption \u03b1} (z : roption \u03b1)\n    (hx : x \u2264 z) (hy : y \u2264 z) : x \u2264 y \u2228 y \u2264 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 {\u03b1 : Type u_1} (p : Prop) (f : p \u2192 roption \u03b1) : roption \u03b1 :=\n  mk (\u2203 (h : p), dom (f h)) fun (ha : \u2203 (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : roption \u03b1) (g : \u03b1 \u2192 roption \u03b2) : roption \u03b2 :=\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (o : roption \u03b1) : roption \u03b2 :=\n  mk (dom o) (f \u2218 get o)\n\ntheorem mem_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) {o : roption \u03b1} {a : \u03b1} :\n    a \u2208 o \u2192 f a \u2208 map f o :=\n  sorry\n\n@[simp] theorem mem_map_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) {o : roption \u03b1} {b : \u03b2} :\n    b \u2208 map f o \u2194 \u2203 (a : \u03b1), \u2203 (H : a \u2208 o), f a = b :=\n  sorry\n\n@[simp] theorem map_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : map f none = none := sorry\n\n@[simp] theorem map_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n    map f (some a) = some (f a) :=\n  iff.mpr eq_some_iff (mem_map f (mem_some a))\n\ntheorem mem_assert {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} {a : \u03b1} (h : p) :\n    a \u2208 f h \u2192 a \u2208 assert p f :=\n  sorry\n\n@[simp] theorem mem_assert_iff {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} {a : \u03b1} :\n    a \u2208 assert p f \u2194 \u2203 (h : p), a \u2208 f h :=\n  sorry\n\ntheorem assert_pos {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} (h : p) : assert p f = f h := sorry\n\ntheorem assert_neg {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} (h : \u00acp) : assert p f = none :=\n  sorry\n\ntheorem mem_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} {a : \u03b1} {b : \u03b2} :\n    a \u2208 f \u2192 b \u2208 g a \u2192 b \u2208 roption.bind f g :=\n  sorry\n\n@[simp] theorem mem_bind_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2}\n    {b : \u03b2} : b \u2208 roption.bind f g \u2194 \u2203 (a : \u03b1), \u2203 (H : a \u2208 f), b \u2208 g a :=\n  sorry\n\n@[simp] theorem bind_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 roption \u03b2) :\n    roption.bind none f = none :=\n  sorry\n\n@[simp] theorem bind_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} (a : \u03b1) (f : \u03b1 \u2192 roption \u03b2) :\n    roption.bind (some a) f = f a :=\n  sorry\n\ntheorem bind_some_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (x : roption \u03b1) :\n    roption.bind x (some \u2218 f) = map f x :=\n  sorry\n\ntheorem bind_assoc {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : roption \u03b1) (g : \u03b1 \u2192 roption \u03b2)\n    (k : \u03b2 \u2192 roption \u03b3) :\n    roption.bind (roption.bind f g) k = roption.bind f fun (x : \u03b1) => roption.bind (g x) k :=\n  sorry\n\n@[simp] theorem bind_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (x : roption \u03b1)\n    (g : \u03b2 \u2192 roption \u03b3) : roption.bind (map f x) g = roption.bind x fun (y : \u03b1) => g (f y) :=\n  sorry\n\n@[simp] theorem map_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 roption \u03b2)\n    (x : roption \u03b1) (g : \u03b2 \u2192 \u03b3) :\n    map g (roption.bind x f) = roption.bind x fun (y : \u03b1) => map g (f y) :=\n  sorry\n\ntheorem map_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (g : \u03b2 \u2192 \u03b3) (f : \u03b1 \u2192 \u03b2)\n    (o : roption \u03b1) : map g (map f o) = map (g \u2218 f) o :=\n  sorry\n\nprotected instance monad : Monad roption :=\n  { toApplicative :=\n      { toFunctor := { map := map, mapConst := fun (\u03b1 \u03b2 : Type u_1) => map \u2218 function.const \u03b2 },\n        toPure := { pure := some },\n        toSeq :=\n          { seq :=\n              fun (\u03b1 \u03b2 : Type u_1) (f : roption (\u03b1 \u2192 \u03b2)) (x : roption \u03b1) =>\n                roption.bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : roption \u03b1) (b : roption \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : roption (\u03b1 \u2192 \u03b2)) (x : roption \u03b1) =>\n                    roption.bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x)\n                  \u03b2 \u03b1 (map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : roption \u03b1) (b : roption \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : roption (\u03b1 \u2192 \u03b2)) (x : roption \u03b1) =>\n                    roption.bind f fun (_x : \u03b1 \u2192 \u03b2) => map _x x)\n                  \u03b2 \u03b2 (map (function.const \u03b1 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' {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1} (H : \u2200 (x : \u03b1), f x = x) (o : roption \u03b1) : 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 {\u03b1 : Type u_1} (x : roption \u03b1) : roption.bind x some = x := sorry\n\n@[simp] theorem pure_eq_some {\u03b1 : Type u_1} (a : \u03b1) : pure a = some a := rfl\n\n@[simp] theorem ret_eq_some {\u03b1 : Type u_1} (a : \u03b1) : return a = some a := rfl\n\n@[simp] theorem map_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 \u03b2) (o : roption \u03b1) :\n    f <$> o = map f o :=\n  rfl\n\n@[simp] theorem bind_eq_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : roption \u03b1) (g : \u03b1 \u2192 roption \u03b2) :\n    f >>= g = roption.bind f g :=\n  rfl\n\ntheorem bind_le {\u03b2 : Type u_2} {\u03b1 : Type u_2} (x : roption \u03b1) (f : \u03b1 \u2192 roption \u03b2) (y : roption \u03b2) :\n    x >>= f \u2264 y \u2194 \u2200 (a : \u03b1), a \u2208 x \u2192 f a \u2264 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 {\u03b1 : Type u_1} (p : Prop) (o : roption \u03b1) : (p \u2192 dom o) \u2192 roption \u03b1 := sorry\n\n@[simp] theorem mem_restrict {\u03b1 : Type u_1} (p : Prop) (o : roption \u03b1) (h : p \u2192 dom o) (a : \u03b1) :\n    a \u2208 restrict p o h \u2194 p \u2227 a \u2208 o :=\n  sorry\n\n/-- `unwrap o` gets the value at `o`, ignoring the condition.\n  (This function is unsound.) -/\ntheorem assert_defined {\u03b1 : Type u_1} {p : Prop} {f : p \u2192 roption \u03b1} (h : p) :\n    dom (f h) \u2192 dom (assert p f) :=\n  exists.intro\n\ntheorem bind_defined {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} (h : dom f) :\n    dom (g (get f h)) \u2192 dom (roption.bind f g) :=\n  assert_defined\n\n@[simp] theorem bind_dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : roption \u03b1} {g : \u03b1 \u2192 roption \u03b2} :\n    dom (roption.bind f g) \u2194 \u2203 (h : dom f), dom (g (get f h)) :=\n  iff.rfl\n\nend roption\n\n\n/-- `pfun \u03b1 \u03b2`, or `\u03b1 \u2192. \u03b2`, is the type of partial functions from\n  `\u03b1` to `\u03b2`. It is defined as `\u03b1 \u2192 roption \u03b2`. -/\ndef pfun (\u03b1 : Type u_1) (\u03b2 : Type u_2) := \u03b1 \u2192 roption \u03b2\n\ninfixr:25 \" \u2192. \" => Mathlib.pfun\n\nnamespace pfun\n\n\nprotected instance inhabited {\u03b1 : Type u_1} {\u03b2 : Type u_2} : Inhabited (\u03b1 \u2192. \u03b2) :=\n  { default := fun (a : \u03b1) => roption.none }\n\n/-- The domain of a partial function -/\ndef dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : set \u03b1 :=\n  set_of fun (a : \u03b1) => roption.dom (f a)\n\ntheorem mem_dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) :\n    x \u2208 dom f \u2194 \u2203 (y : \u03b2), y \u2208 f x :=\n  sorry\n\ntheorem dom_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) :\n    dom f = set_of fun (x : \u03b1) => \u2203 (y : \u03b2), y \u2208 f x :=\n  set.ext (mem_dom f)\n\n/-- Evaluate a partial function -/\ndef fn {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) (h : dom f x) : \u03b2 := roption.get (f x) h\n\n/-- Evaluate a partial function to return an `option` -/\ndef eval_opt {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) [D : decidable_pred (dom f)] (x : \u03b1) :\n    Option \u03b2 :=\n  roption.to_option (f x)\n\n/-- Partial function extensionality -/\ntheorem ext' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {g : \u03b1 \u2192. \u03b2}\n    (H1 : \u2200 (a : \u03b1), a \u2208 dom f \u2194 a \u2208 dom g)\n    (H2 : \u2200 (a : \u03b1) (p : dom f a) (q : dom g a), fn f a p = fn g a q) : f = g :=\n  funext fun (a : \u03b1) => roption.ext' (H1 a) (H2 a)\n\ntheorem ext {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {g : \u03b1 \u2192. \u03b2}\n    (H : \u2200 (a : \u03b1) (b : \u03b2), b \u2208 f a \u2194 b \u2208 g a) : f = g :=\n  funext fun (a : \u03b1) => roption.ext (H a)\n\n/-- Turn a partial function into a function out of a subtype -/\ndef as_subtype {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : \u21a5(dom f)) : \u03b2 := fn f \u2191s sorry\n\n/-- The set of partial functions `\u03b1 \u2192. \u03b2` is equivalent to\nthe set of pairs `(p : \u03b1 \u2192 Prop, f : subtype p \u2192 \u03b2)`. -/\ndef equiv_subtype {\u03b1 : Type u_1} {\u03b2 : Type u_2} :\n    (\u03b1 \u2192. \u03b2) \u2243 sigma fun (p : \u03b1 \u2192 Prop) => Subtype p \u2192 \u03b2 :=\n  equiv.mk (fun (f : \u03b1 \u2192. \u03b2) => sigma.mk (fun (a : \u03b1) => roption.dom (f a)) (as_subtype f))\n    (fun (f : sigma fun (p : \u03b1 \u2192 Prop) => Subtype p \u2192 \u03b2) (x : \u03b1) =>\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {x : \u03b1} {y : \u03b2}\n    (fxy : y \u2208 f x) (domx : x \u2208 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192. \u03b2 :=\n  fun (a : \u03b1) => roption.some (f a)\n\nprotected instance has_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} : has_coe (\u03b1 \u2192 \u03b2) (\u03b1 \u2192. \u03b2) :=\n  has_coe.mk pfun.lift\n\n@[simp] theorem lift_eq_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : pfun.lift f = \u2191f := rfl\n\n@[simp] theorem coe_val {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : set (\u03b1 \u00d7 \u03b2) :=\n  set_of fun (p : \u03b1 \u00d7 \u03b2) => prod.snd p \u2208 f (prod.fst p)\n\ndef graph' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : rel \u03b1 \u03b2 := fun (x : \u03b1) (y : \u03b2) => y \u2208 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : set \u03b2 :=\n  set_of fun (b : \u03b2) => \u2203 (a : \u03b1), b \u2208 f a\n\n/-- Restrict a partial function to a smaller domain. -/\ndef restrict {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {p : set \u03b1} (H : p \u2286 dom f) : \u03b1 \u2192. \u03b2 :=\n  fun (x : \u03b1) => roption.restrict (x \u2208 p) (f x) H\n\n@[simp] theorem mem_restrict {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2} {s : set \u03b1} (h : s \u2286 dom f)\n    (a : \u03b1) (b : \u03b2) : b \u2208 restrict f h a \u2194 a \u2208 s \u2227 b \u2208 f a :=\n  sorry\n\ndef res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) : \u03b1 \u2192. \u03b2 :=\n  restrict (pfun.lift f) (set.subset_univ s)\n\ntheorem mem_res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (a : \u03b1) (b : \u03b2) :\n    b \u2208 res f s a \u2194 a \u2208 s \u2227 f a = b :=\n  sorry\n\ntheorem res_univ {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) : res f set.univ = \u2191f := rfl\n\ntheorem dom_iff_graph {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) :\n    x \u2208 dom f \u2194 \u2203 (y : \u03b2), (x, y) \u2208 graph f :=\n  roption.dom_iff_mem\n\ntheorem lift_graph {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {a : \u03b1} {b : \u03b2} :\n    (a, b) \u2208 graph \u2191f \u2194 f a = b :=\n  sorry\n\n/-- The monad `pure` function, the total constant `x` function -/\nprotected def pure {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) : \u03b1 \u2192. \u03b2 := fun (_x : \u03b1) => roption.some x\n\n/-- The monad `bind` function, pointwise `roption.bind` -/\ndef bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192. \u03b2) (g : \u03b2 \u2192 \u03b1 \u2192. \u03b3) : \u03b1 \u2192. \u03b3 :=\n  fun (a : \u03b1) => roption.bind (f a) fun (b : \u03b2) => g b a\n\n/-- The monad `map` function, pointwise `roption.map` -/\ndef map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192. \u03b2) : \u03b1 \u2192. \u03b3 :=\n  fun (a : \u03b1) => roption.map f (g a)\n\nprotected instance monad {\u03b1 : Type u_1} : Monad (pfun \u03b1) :=\n  { toApplicative :=\n      { toFunctor := { map := map, mapConst := fun (\u03b1_1 \u03b2 : Type u_2) => map \u2218 function.const \u03b2 },\n        toPure := { pure := pfun.pure },\n        toSeq :=\n          { seq :=\n              fun (\u03b1_1 \u03b2 : Type u_2) (f : \u03b1 \u2192. \u03b1_1 \u2192 \u03b2) (x : \u03b1 \u2192. \u03b1_1) =>\n                bind f fun (_x : \u03b1_1 \u2192 \u03b2) => map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1_1 \u03b2 : Type u_2) (a : \u03b1 \u2192. \u03b1_1) (b : \u03b1 \u2192. \u03b2) =>\n                (fun (\u03b1_2 \u03b2 : Type u_2) (f : \u03b1 \u2192. \u03b1_2 \u2192 \u03b2) (x : \u03b1 \u2192. \u03b1_2) =>\n                    bind f fun (_x : \u03b1_2 \u2192 \u03b2) => map _x x)\n                  \u03b2 \u03b1_1 (map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1_1 \u03b2 : Type u_2) (a : \u03b1 \u2192. \u03b1_1) (b : \u03b1 \u2192. \u03b2) =>\n                (fun (\u03b1_2 \u03b2 : Type u_2) (f : \u03b1 \u2192. \u03b1_2 \u2192 \u03b2) (x : \u03b1 \u2192. \u03b1_2) =>\n                    bind f fun (_x : \u03b1_2 \u2192 \u03b2) => map _x x)\n                  \u03b2 \u03b2 (map (function.const \u03b1_1 id) a) b } },\n    toBind := { bind := bind } }\n\nprotected instance is_lawful_monad {\u03b1 : Type u_1} : is_lawful_monad (pfun \u03b1) :=\n  is_lawful_monad.mk\n    (fun (\u03b2 \u03b3 : Type u_2) (x : \u03b2) (f : \u03b2 \u2192 \u03b1 \u2192. \u03b3) =>\n      funext fun (a : \u03b1) => roption.bind_some a (f x))\n    fun (\u03b2 \u03b3 \u03b4 : Type u_2) (f : \u03b1 \u2192. \u03b2) (g : \u03b2 \u2192 \u03b1 \u2192. \u03b3) (k : \u03b3 \u2192 \u03b1 \u2192. \u03b4) =>\n      funext fun (a : \u03b1) => roption.bind_assoc (f a) (fun (b : \u03b2) => g b a) fun (b : \u03b3) => k b a\n\ntheorem pure_defined {\u03b1 : Type u_1} {\u03b2 : Type u_2} (p : set \u03b1) (x : \u03b2) : p \u2286 dom (pfun.pure x) :=\n  set.subset_univ p\n\ntheorem bind_defined {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_2} (p : set \u03b1) {f : \u03b1 \u2192. \u03b2}\n    {g : \u03b2 \u2192 \u03b1 \u2192. \u03b3} (H1 : p \u2286 dom f) (H2 : \u2200 (x : \u03b2), p \u2286 dom (g x)) : p \u2286 dom (f >>= g) :=\n  fun (a : \u03b1) (ha : a \u2208 p) => Exists.intro (H1 ha) (H2 (roption.get (f a) (H1 ha)) ha)\n\ndef fix {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2 \u2295 \u03b1) : \u03b1 \u2192. \u03b2 :=\n  fun (a : \u03b1) =>\n    roption.assert (acc (fun (x y : \u03b1) => sum.inr x \u2208 f y) a)\n      fun (h : acc (fun (x y : \u03b1) => sum.inr x \u2208 f y) a) =>\n        well_founded.fix_F\n          (fun (a : \u03b1) (IH : (y : \u03b1) \u2192 sum.inr y \u2208 f a \u2192 roption \u03b2) =>\n            roption.assert (roption.dom (f a))\n              fun (hf : roption.dom (f a)) =>\n                (fun (_x : \u03b2 \u2295 \u03b1) (e : roption.get (f a) hf = _x) =>\n                    sum.cases_on _x\n                      (fun (b : \u03b2) (e : roption.get (f a) hf = sum.inl b) => roption.some b)\n                      (fun (a' : \u03b1) (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {a : \u03b1} {b : \u03b2}\n    (h : b \u2208 fix f a) : roption.dom (f a) :=\n  sorry\n\ntheorem mem_fix_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {a : \u03b1} {b : \u03b2} :\n    b \u2208 fix f a \u2194 sum.inl b \u2208 f a \u2228 \u2203 (a' : \u03b1), sum.inr a' \u2208 f a \u2227 b \u2208 fix f a' :=\n  sorry\n\ndef fix_induction {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {b : \u03b2} {C : \u03b1 \u2192 Sort u_3} {a : \u03b1}\n    (h : b \u2208 fix f a)\n    (H : (a : \u03b1) \u2192 b \u2208 fix f a \u2192 ((a' : \u03b1) \u2192 b \u2208 fix f a' \u2192 sum.inr a' \u2208 f a \u2192 C a') \u2192 C a) : C a :=\n  sorry\n\nend pfun\n\n\nnamespace pfun\n\n\ndef image {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) : set \u03b2 := rel.image (graph' f) s\n\ntheorem image_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) :\n    image f s = set_of fun (y : \u03b2) => \u2203 (x : \u03b1), \u2203 (H : x \u2208 s), y \u2208 f x :=\n  rfl\n\ntheorem mem_image {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (y : \u03b2) (s : set \u03b1) :\n    y \u2208 image f s \u2194 \u2203 (x : \u03b1), \u2203 (H : x \u2208 s), y \u2208 f x :=\n  iff.rfl\n\ntheorem image_mono {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {s : set \u03b1} {t : set \u03b1} (h : s \u2286 t) :\n    image f s \u2286 image f t :=\n  rel.image_mono (graph' f) h\n\ntheorem image_inter {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) (t : set \u03b1) :\n    image f (s \u2229 t) \u2286 image f s \u2229 image f t :=\n  rel.image_inter (graph' f) s t\n\ntheorem image_union {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b1) (t : set \u03b1) :\n    image f (s \u222a t) = image f s \u222a image f t :=\n  rel.image_union (graph' f) s t\n\ndef preimage {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : set \u03b1 :=\n  rel.preimage (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) s\n\ntheorem preimage_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    preimage f s = set_of fun (x : \u03b1) => \u2203 (y : \u03b2), \u2203 (H : y \u2208 s), y \u2208 f x :=\n  rfl\n\ntheorem mem_preimage {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (x : \u03b1) :\n    x \u2208 preimage f s \u2194 \u2203 (y : \u03b2), \u2203 (H : y \u2208 s), y \u2208 f x :=\n  iff.rfl\n\ntheorem preimage_subset_dom {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    preimage f s \u2286 dom f :=\n  sorry\n\ntheorem preimage_mono {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {s : set \u03b2} {t : set \u03b2}\n    (h : s \u2286 t) : preimage f s \u2286 preimage f t :=\n  rel.preimage_mono (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) h\n\ntheorem preimage_inter {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (t : set \u03b2) :\n    preimage f (s \u2229 t) \u2286 preimage f s \u2229 preimage f t :=\n  rel.preimage_inter (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) s t\n\ntheorem preimage_union {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (t : set \u03b2) :\n    preimage f (s \u222a t) = preimage f s \u222a preimage f t :=\n  rel.preimage_union (fun (x : \u03b1) (y : \u03b2) => y \u2208 f x) s t\n\ntheorem preimage_univ {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) : preimage f set.univ = dom f :=\n  sorry\n\ndef core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) : set \u03b1 := rel.core (graph' f) s\n\ntheorem core_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    core f s = set_of fun (x : \u03b1) => \u2200 (y : \u03b2), y \u2208 f x \u2192 y \u2208 s :=\n  rfl\n\ntheorem mem_core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (x : \u03b1) (s : set \u03b2) :\n    x \u2208 core f s \u2194 \u2200 (y : \u03b2), y \u2208 f x \u2192 y \u2208 s :=\n  iff.rfl\n\ntheorem compl_dom_subset_core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    dom f\u1d9c \u2286 core f s :=\n  fun (x : \u03b1) (hx : x \u2208 (dom f\u1d9c)) (y : \u03b2) (fxy : graph' f x y) =>\n    absurd (iff.mpr (mem_dom f x) (Exists.intro y fxy)) hx\n\ntheorem core_mono {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) {s : set \u03b2} {t : set \u03b2} (h : s \u2286 t) :\n    core f s \u2286 core f t :=\n  rel.core_mono (graph' f) h\n\ntheorem core_inter {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) (t : set \u03b2) :\n    core f (s \u2229 t) = core f s \u2229 core f t :=\n  rel.core_inter (graph' f) s t\n\ntheorem mem_core_res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (t : set \u03b2) (x : \u03b1) :\n    x \u2208 core (res f s) t \u2194 x \u2208 s \u2192 f x \u2208 t :=\n  sorry\n\ntheorem core_res {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (t : set \u03b2) :\n    core (res f s) t = s\u1d9c \u222a f \u207b\u00b9' t :=\n  sorry\n\ntheorem core_restrict {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (s : set \u03b2) :\n    core (\u2191f) s = f \u207b\u00b9' s :=\n  sorry\n\ntheorem preimage_subset_core {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    preimage f s \u2286 core f s :=\n  sorry\n\ntheorem preimage_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    preimage f s = core f s \u2229 dom f :=\n  sorry\n\ntheorem core_eq {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    core f s = preimage f s \u222a (dom f\u1d9c) :=\n  sorry\n\ntheorem preimage_as_subtype {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192. \u03b2) (s : set \u03b2) :\n    as_subtype f \u207b\u00b9' s = subtype.val \u207b\u00b9' 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 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Parser.Term\n\nnamespace Lean\nnamespace Parser\nnamespace Tactic\n\nbuiltin_initialize\n  register_parser_alias tacticSeq\n  register_parser_alias tacticSeqIndentGt\n\n/- This is a fallback tactic parser for any identifier which exists only\nto improve syntax error messages.\n```\nexample : True := by foo -- unknown tactic\n```\n-/\n@[builtin_tactic_parser] def \u00abunknown\u00bb    := leading_parser\n  withPosition (ident >> errorAtSavedPos \"unknown tactic\" true)\n\n@[builtin_tactic_parser] def nestedTactic := tacticSeqBracketed\n\ndef matchRhs  := Term.hole <|> Term.syntheticHole <|> tacticSeq\ndef matchAlts := Term.matchAlts (rhsParser := matchRhs)\n\n/-- `match` performs case analysis on one or more expressions.\nSee [Induction and Recursion][tpil4].\nThe syntax for the `match` tactic is the same as term-mode `match`, except that\nthe match arms are tactics instead of expressions.\n```\nexample (n : Nat) : n = n := by\n  match n with\n  | 0 => rfl\n  | i+1 => simp\n```\n\n[tpil4]: https://leanprover.github.io/theorem_proving_in_lean4/induction_and_recursion.html\n-/\n@[builtin_tactic_parser] def \u00abmatch\u00bb := leading_parser:leadPrec\n  \"match \" >> optional Term.generalizingParam >>\n  optional Term.motive >> sepBy1 Term.matchDiscr \", \" >>\n  \" with \" >> ppDedent matchAlts\n\n/--\nThe tactic\n```\nintro\n| pat1 => tac1\n| pat2 => tac2\n```\nis the same as:\n```\nintro x\nmatch x with\n| pat1 => tac1\n| pat2 => tac2\n```\nThat is, `intro` can be followed by match arms and it introduces the values while\ndoing a pattern match. This is equivalent to `fun` with match arms in term mode.\n-/\n@[builtin_tactic_parser] def introMatch := leading_parser\n  nonReservedSymbol \"intro \" >> matchAlts\n\n/-- `decide` will attempt to prove a goal of type `p` by synthesizing an instance\nof `Decidable p` and then evaluating it to `isTrue ..`. Because this uses kernel\ncomputation to evaluate the term, it may not work in the presence of definitions\nby well founded recursion, since this requires reducing proofs.\n```\nexample : 2 + 2 \u2260 5 := by decide\n```\n-/\n@[builtin_tactic_parser] def decide := leading_parser\n  nonReservedSymbol \"decide\"\n\n/-- `native_decide` will attempt to prove a goal of type `p` by synthesizing an instance\nof `Decidable p` and then evaluating it to `isTrue ..`. Unlike `decide`, this\nuses `#eval` to evaluate the decidability instance.\n\nThis should be used with care because it adds the entire lean compiler to the trusted\npart, and the axiom `ofReduceBool` will show up in `#print axioms` for theorems using\nthis method or anything that transitively depends on them. Nevertheless, because it is\ncompiled, this can be significantly more efficient than using `decide`, and for very\nlarge computations this is one way to run external programs and trust the result.\n```\nexample : (List.range 1000).length = 1000 := by native_decide\n```\n-/\n@[builtin_tactic_parser] def nativeDecide := leading_parser\n  nonReservedSymbol \"native_decide\"\n\nend Tactic\nend Parser\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/Parser/Tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.08269733532757162, "lm_q1q2_score": 0.02541768898632414}}
{"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 {\u03b1 : Sort*} {\u03b2 : Sort*}\n\n@[simp] lemma pprod.mk.eta {p : pprod \u03b1 \u03b2} : pprod.mk p.1 p.2 = p :=\npprod.cases_on p (\u03bb 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": "import Lean\n\ndef f1 (x : Nat) : Except String Nat :=\n  if x > 0 then\n    .ok x\n  else\n    .error \"argument is zero\"\n\nnamespace Lean.Elab\nopen Lsp\n\ndef identOf : Info \u2192 Option (RefIdent \u00d7 Bool)\n  | .ofTermInfo ti => match ti.expr with\n    | .const n .. => some (.const n, ti.isBinder)\n    | .fvar id .. => some (.fvar id, ti.isBinder)\n    | _ => none\n  | .ofFieldInfo fi => some (.const fi.projName, false)\n  | _ => none\n\ndef isConst (e : Expr) : Bool :=\n  e matches .const ..\n\ndef isImplicit (bi : BinderInfo) : Bool :=\n  bi matches .implicit\n\nend Lean.Elab\n\ndef f2 (xs : List Nat) : List Nat :=\n  .map (\u00b7 + 1) xs\n\ndef f2' (xs : List Nat) : List Nat :=\n  .map .succ xs\n\ndef f3 : Nat :=\n  .zero\n\ndef f4 (x : Nat) : Nat :=\n  .succ x\n\nexample (xs : List \u03b1) : Lean.RBTree \u03b1 ord :=\n  xs.foldl .insert \u2205\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/944.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.06560484476669959, "lm_q1q2_score": 0.0252521014876859}}
{"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.Check\nimport Lean.Meta.Closure\nimport Lean.Meta.Tactic.Cases\nimport Lean.Meta.Tactic.Contradiction\nimport Lean.Meta.GeneralizeTelescope\nimport Lean.Meta.Match.Basic\n\nnamespace Lean.Meta.Match\n\n/-- The number of patterns in each AltLHS must be equal to the number of discriminants. -/\nprivate def checkNumPatterns (numDiscrs : Nat) (lhss : List AltLHS) : MetaM Unit := do\n  if lhss.any fun lhs => lhs.patterns.length != numDiscrs then\n    throwError \"incorrect number of patterns\"\n\n/--\n  Execute `k hs` where `hs` contains new equalities `h : lhs[i] = rhs[i]` for each `discrInfos[i] = some h`.\n  Assume `lhs.size == rhs.size == discrInfos.size`\n-/\nprivate partial def withEqs (lhs rhs : Array Expr) (discrInfos : Array DiscrInfo) (k : Array Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  go 0 #[]\nwhere\n  go (i : Nat) (hs : Array Expr) : MetaM \u03b1 := do\n    if i < lhs.size then\n      if let some hName := discrInfos[i]!.hName? then\n        withLocalDeclD hName (\u2190 mkEqHEq lhs[i]! rhs[i]!) fun h =>\n          go (i+1) (hs.push h)\n      else\n        go (i+1) hs\n    else\n      k hs\n\n/-- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/\nprivate def withAlts {\u03b1} (motive : Expr) (discrs : Array Expr) (discrInfos : Array DiscrInfo) (lhss : List AltLHS) (k : List Alt \u2192 Array (Expr \u00d7 Nat) \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  loop lhss [] #[]\nwhere\n  mkMinorType (xs : Array Expr) (lhs : AltLHS) : MetaM Expr :=\n    withExistingLocalDecls lhs.fvarDecls do\n      let args \u2190 lhs.patterns.toArray.mapM (Pattern.toExpr \u00b7 (annotate := true))\n      let minorType := mkAppN motive args\n      withEqs discrs args discrInfos fun eqs => do\n        mkForallFVars (xs ++ eqs) minorType\n\n  loop (lhss : List AltLHS) (alts : List Alt) (minors : Array (Expr \u00d7 Nat)) : MetaM \u03b1 := do\n    match lhss with\n    | [] => k alts.reverse minors\n    | lhs::lhss =>\n      let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr\n      let minorType \u2190 mkMinorType xs lhs\n      let hasParams := !xs.isEmpty || discrInfos.any fun info => info.hName?.isSome\n      let (minorType, minorNumParams) := if hasParams then (minorType, xs.size) else (mkSimpleThunkType minorType, 1)\n      let idx       := alts.length\n      let minorName := (`h).appendIndexAfter (idx+1)\n      trace[Meta.Match.debug] \"minor premise {minorName} : {minorType}\"\n      withLocalDeclD minorName minorType fun minor => do\n        let rhs    := if hasParams then mkAppN minor xs else mkApp minor (mkConst `Unit.unit)\n        let minors := minors.push (minor, minorNumParams)\n        let fvarDecls \u2190 lhs.fvarDecls.mapM instantiateLocalDeclMVars\n        let alts   := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns, cnstrs := [] } :: alts\n        loop lhss alts minors\n\nstructure State where\n  used            : HashSet Nat := {} -- used alternatives\n  counterExamples : List (List Example) := []\n\n/-- Return true if the given (sub-)problem has been solved. -/\nprivate def isDone (p : Problem) : Bool :=\n  p.vars.isEmpty\n\n/-- Return true if the next element on the `p.vars` list is a variable. -/\nprivate def isNextVar (p : Problem) : Bool :=\n  match p.vars with\n  | .fvar _ :: _ => true\n  | _            => false\n\nprivate def hasAsPattern (p : Problem) : Bool :=\n  p.alts.any fun alt => match alt.patterns with\n    | .as .. :: _ => true\n    | _           => false\n\nprivate def hasCtorPattern (p : Problem) : Bool :=\n  p.alts.any fun alt => match alt.patterns with\n    | .ctor .. :: _ => true\n    | _             => false\n\nprivate def hasValPattern (p : Problem) : Bool :=\n  p.alts.any fun alt => match alt.patterns with\n    | .val _ :: _ => true\n    | _           => false\n\nprivate def hasNatValPattern (p : Problem) : Bool :=\n  p.alts.any fun alt => match alt.patterns with\n    | .val v :: _ => v.isNatLit\n    | _           => false\n\nprivate def hasVarPattern (p : Problem) : Bool :=\n  p.alts.any fun alt => match alt.patterns with\n    | .var _ :: _ => true\n    | _           => false\n\nprivate def hasArrayLitPattern (p : Problem) : Bool :=\n  p.alts.any fun alt => match alt.patterns with\n    | .arrayLit .. :: _ => true\n    | _                 => false\n\nprivate def isVariableTransition (p : Problem) : Bool :=\n  p.alts.all fun alt => match alt.patterns with\n    | .inaccessible _ :: _ => true\n    | .var _ :: _          => true\n    | _                    => false\n\nprivate def isConstructorTransition (p : Problem) : Bool :=\n  (hasCtorPattern p || p.alts.isEmpty)\n  && p.alts.all fun alt => match alt.patterns with\n     | .ctor .. :: _        => true\n     | .var _ :: _          => true\n     | .inaccessible _ :: _ => true\n     | _                    => false\n\nprivate def isValueTransition (p : Problem) : Bool :=\n  hasVarPattern p && hasValPattern p\n  && p.alts.all fun alt => match alt.patterns with\n     | .val _ :: _ => true\n     | .var _ :: _ => true\n     | _           => false\n\nprivate def isArrayLitTransition (p : Problem) : Bool :=\n  hasArrayLitPattern p && hasVarPattern p\n  && p.alts.all fun alt => match alt.patterns with\n     | .arrayLit .. :: _ => true\n     | .var _ :: _       => true\n     | _                 => false\n\nprivate def isNatValueTransition (p : Problem) : Bool :=\n  hasNatValPattern p\n  && (!isNextVar p ||\n      p.alts.any fun alt => match alt.patterns with\n      | .ctor .. :: _        => true\n      | .inaccessible _ :: _ => true\n      | _                    => false)\n\nprivate def processSkipInaccessible (p : Problem) : Problem := Id.run do\n  let x :: xs := p.vars | unreachable!\n  let alts := p.alts.map fun alt => Id.run do\n    let .inaccessible e :: ps := alt.patterns | unreachable!\n    { alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs }\n  { p with alts := alts, vars := xs }\n\n/--\nIf contraint is of the form `e \u224b x` where `x` is a free variable, reorient it\nas `x \u224b e` If\n- `x` is an `alt`-local declaration\n- `e` is not a free variable.\n-/\nprivate def reorientCnstrs (alt : Alt) : Alt :=\n  let cnstrs := alt.cnstrs.map fun (lhs, rhs) =>\n    if rhs.isFVar && alt.isLocalDecl rhs.fvarId! then\n      (rhs, lhs)\n    else if !lhs.isFVar && rhs.isFVar then\n      (rhs, lhs)\n    else\n      (lhs, rhs)\n  { alt with cnstrs }\n\n/--\nRemove constraints of the form `lhs \u224b rhs` where `lhs` and `rhs` are definitionally equal,\nor `lhs` is a free variable.\n-/\nprivate def filterTrivialCnstrs (alt : Alt) : MetaM Alt := do\n   let cnstrs \u2190 withExistingLocalDecls alt.fvarDecls do\n     alt.cnstrs.filterM fun (lhs, rhs) => do\n       if (\u2190 isDefEqGuarded lhs rhs) then\n         return false\n       else if lhs.isFVar then\n         return false\n       else\n         return true\n   return { alt with cnstrs }\n\n/--\nFind an alternative constraint of the form `x \u224b e` where `x` is an alternative\nlocal declarations, and `x` and `e` have definitionally equal types.\nThen, replace `x` with `e` in the alternative, and return it.\nReturn `none` if the alternative does not contain a constraint of this form.\n-/\nprivate def solveSomeLocalFVarIdCnstr? (alt : Alt) : MetaM (Option Alt) :=\n  withExistingLocalDecls alt.fvarDecls do\n    let (some (fvarId, val), cnstrs) \u2190 go alt.cnstrs | return none\n    trace[Meta.Match.match] \"found cnstr to solve {mkFVar fvarId} \u21a6 {val}\"\n    return some <| { alt with cnstrs }.replaceFVarId fvarId val\nwhere\n  go (cnstrs : List (Expr \u00d7 Expr)) := do\n    match cnstrs with\n    | [] => return (none, [])\n    | (lhs, rhs) :: cnstrs =>\n      if lhs.isFVar && alt.isLocalDecl lhs.fvarId! then\n        if !(\u2190 dependsOn rhs lhs.fvarId!) && (\u2190 isDefEqGuarded (\u2190 inferType lhs) (\u2190 inferType rhs)) then\n          return (some (lhs.fvarId!, rhs), cnstrs)\n      let (p, cnstrs) \u2190 go cnstrs\n      return (p, (lhs, rhs) :: cnstrs)\n\n/--\nSolve pending alternative constraints. If all constraints can be solved perform assignment\n`mvarId := alt.rhs`, and return true.\n-/\nprivate partial def solveCnstrs (mvarId : MVarId) (alt : Alt) : StateRefT State MetaM Bool := do\n  go (reorientCnstrs alt)\nwhere\n  go (alt : Alt) : StateRefT State MetaM Bool := do\n    match (\u2190 solveSomeLocalFVarIdCnstr? alt) with\n    | some alt => go alt\n    | none =>\n      let alt \u2190 filterTrivialCnstrs alt\n      if alt.cnstrs.isEmpty then\n        let eType \u2190 inferType alt.rhs\n        let targetType \u2190 mvarId.getType\n        unless (\u2190 isDefEqGuarded targetType eType) do\n          trace[Meta.Match.match] \"assignGoalOf failed {eType} =?= {targetType}\"\n          throwError \"dependent elimination failed, type mismatch when solving alternative with type{indentExpr eType}\\nbut expected{indentExpr targetType}\"\n        mvarId.assign alt.rhs\n        modify fun s => { s with used := s.used.insert alt.idx }\n        return true\n      else\n        trace[Meta.Match.match] \"alt has unsolved cnstrs:\\n{\u2190 alt.toMessageData}\"\n        return false\n\n/--\nTry to solve the problem by using the first alternative whose pending constraints can be resolved.\n-/\nprivate def processLeaf (p : Problem) : StateRefT State MetaM Unit :=\n  p.mvarId.withContext do\n    trace[Meta.Match.match] \"local context at processLeaf:\\n{(\u2190 mkFreshTypeMVar).mvarId!}\"\n    go p.alts\nwhere\n  go (alts : List Alt) : StateRefT State MetaM Unit := do\n    match alts with\n    | [] =>\n      /- TODO: allow users to configure which tactic is used to close leaves. -/\n      unless (\u2190 p.mvarId.contradictionCore {}) do\n        trace[Meta.Match.match] \"missing alternative\"\n        p.mvarId.admit\n        modify fun s => { s with counterExamples := p.examples :: s.counterExamples }\n    | alt :: alts =>\n      unless (\u2190 solveCnstrs p.mvarId alt) do\n        go alts\n\nprivate def processAsPattern (p : Problem) : MetaM Problem := withGoalOf p do\n  let x :: _ := p.vars | unreachable!\n  let alts \u2190 p.alts.mapM fun alt => do\n    match alt.patterns with\n    | .as fvarId p h :: ps =>\n      /- We used to use `checkAndReplaceFVarId` here, but `x` and `fvarId` may have different types\n        when dependent types are beind used. Let's consider the repro for issue #471\n        ```\n        inductive vec : Nat \u2192 Type\n        | nil : vec 0\n        | cons : Int \u2192 vec n \u2192 vec n.succ\n\n        def vec_len : vec n \u2192 Nat\n        | vec.nil => 0\n        | x@(vec.cons h t) => vec_len t + 1\n\n        ```\n        we reach the state\n        ```\n          [Meta.Match.match] remaining variables: [x\u271d:(vec n\u271d)]\n          alternatives:\n            [n:(Nat), x:(vec (Nat.succ n)), h:(Int), t:(vec n)] |- [x@(vec.cons n h t)] => h_1 n x h t\n            [x\u271d:(vec n\u271d)] |- [x\u271d] => h_2 n\u271d x\u271d\n        ```\n        The variables `x\u271d:(vec n\u271d)` and `x:(vec (Nat.succ n))` have different types, but we perform the substitution anyway,\n        because we claim the \"discrepancy\" will be corrected after we process the pattern `(vec.cons n h t)`.\n        The right-hand-side is temporarily type incorrect, but we claim this is fine because it will be type correct again after\n        we the pattern `(vec.cons n h t)`. TODO: try to find a cleaner solution.\n       -/\n      let r \u2190 mkEqRefl x\n      return { alt with patterns := p :: ps }.replaceFVarId fvarId x |>.replaceFVarId h r\n    | _ => return alt\n  return { p with alts := alts }\n\nprivate def processVariable (p : Problem) : MetaM Problem := withGoalOf p do\n  let x :: xs := p.vars | unreachable!\n  let alts \u2190 p.alts.mapM fun alt => do\n    match alt.patterns with\n    | .inaccessible e :: ps => return { alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs }\n    | .var fvarId :: ps     =>\n      withExistingLocalDecls alt.fvarDecls do\n        if (\u2190 isDefEqGuarded (\u2190 fvarId.getType) (\u2190 inferType x)) then\n          return { alt with patterns := ps }.replaceFVarId fvarId x\n        else\n          return { alt with patterns := ps, cnstrs := (mkFVar fvarId, x) :: alt.cnstrs }\n    | _  => unreachable!\n  return { p with alts := alts, vars := xs }\n\n/-!\nNote that we decided to store pending constraints to address issues exposed by #1279 and #1361.\nHere is a simplified version of the example on this issue (see test: `1279_simplified.lean`)\n```lean\ninductive Arrow : Type \u2192 Type \u2192 Type 1\n  | id   : Arrow a a\n  | unit : Arrow Unit Unit\n  | comp : Arrow \u03b2 \u03b3 \u2192 Arrow \u03b1 \u03b2 \u2192 Arrow \u03b1 \u03b3\nderiving Repr\n\ndef Arrow.compose (f : Arrow \u03b2 \u03b3) (g : Arrow \u03b1 \u03b2) : Arrow \u03b1 \u03b3 :=\n  match f, g with\n  | id, g => g\n  | f, id => f\n  | f, g => comp f g\n```\nThe initial state for the `match`-expression above is\n```lean\n[Meta.Match.match] remaining variables: [\u03b2\u271d:(Type), \u03b3\u271d:(Type), f\u271d:(Arrow \u03b2\u271d \u03b3\u271d), g\u271d:(Arrow \u03b1 \u03b2\u271d)]\nalternatives:\n  [\u03b2:(Type), g:(Arrow \u03b1 \u03b2)] |- [\u03b2, .(\u03b2), (Arrow.id .(\u03b2)), g] => h_1 \u03b2 g\n  [\u03b3:(Type), f:(Arrow \u03b1 \u03b3)] |- [.(\u03b1), \u03b3, f, (Arrow.id .(\u03b1))] => h_2 \u03b3 f\n  [\u03b2:(Type), \u03b3:(Type), f:(Arrow \u03b2 \u03b3), g:(Arrow \u03b1 \u03b2)] |- [\u03b2, \u03b3, f, g] => h_3 \u03b2 \u03b3 f g\n```\nThe first step is a variable-transition which replaces `\u03b2` with `\u03b2\u271d` in the first and third alternatives.\nThe constraint `\u03b2\u271d \u224b \u03b1` in the second alternative used to be discarded. We now store it at the\nalternative `cnstrs` field.\n-/\n\nprivate def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool :=\n  localDecls.any fun d => d.fvarId == fvarId\n\nprivate def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) :=\n  withExistingLocalDecls alt.fvarDecls do\n    trace[Meta.Match.unify] \"expandVarIntoCtor? fvarId: {mkFVar fvarId}, ctorName: {ctorName}, alt:\\n{\u2190 alt.toMessageData}\"\n    let expectedType \u2190 inferType (mkFVar fvarId)\n    let expectedType \u2190 whnfD expectedType\n    let (ctorLevels, ctorParams) \u2190 getInductiveUniverseAndParams expectedType\n    let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams\n    let ctorType \u2190 inferType ctor\n    forallTelescopeReducing ctorType fun ctorFields resultType => do\n      let ctor := mkAppN ctor ctorFields\n      let alt  := alt.replaceFVarId fvarId ctor\n      let ctorFieldDecls \u2190 ctorFields.mapM fun ctorField => ctorField.fvarId!.getDecl\n      let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls\n      let mut cnstrs := alt.cnstrs\n      unless (\u2190 isDefEqGuarded resultType expectedType) do\n         cnstrs := (resultType, expectedType) :: cnstrs\n      trace[Meta.Match.unify] \"expandVarIntoCtor? {mkFVar fvarId} : {expectedType}, ctor: {ctor}\"\n      let ctorFieldPatterns := ctorFieldDecls.toList.map fun decl => Pattern.var decl.fvarId\n      return some { alt with fvarDecls := newAltDecls, patterns := ctorFieldPatterns ++ alt.patterns, cnstrs }\n\nprivate def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do\n  let xType \u2190 inferType x\n  let xType \u2190 whnfD xType\n  match xType.getAppFn with\n  | Expr.const constName _ =>\n    let cinfo \u2190 getConstInfo constName\n    match cinfo with\n    | ConstantInfo.inductInfo val => return some val\n    | _ => return none\n  | _ => return none\n\nprivate def hasRecursiveType (x : Expr) : MetaM Bool := do\n  match (\u2190 getInductiveVal? x) with\n  | some val => return val.isRec\n  | _        => return false\n\n/-- Given `alt` s.t. the next pattern is an inaccessible pattern `e`,\n   try to normalize `e` into a constructor application.\n   If it is not a constructor, throw an error.\n   Otherwise, if it is a constructor application of `ctorName`,\n   update the next patterns with the fields of the constructor.\n   Otherwise, return none. -/\ndef processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do\n  let env \u2190 getEnv\n  match alt.patterns with\n  | p@(.inaccessible e) :: ps =>\n    trace[Meta.Match.match] \"inaccessible in ctor step {e}\"\n    withExistingLocalDecls alt.fvarDecls do\n      -- Try to push inaccessible annotations.\n      let e \u2190 whnfD e\n      match e.constructorApp? env with\n      | some (ctorVal, ctorArgs) =>\n        if ctorVal.name == ctorName then\n          let fields := ctorArgs.extract ctorVal.numParams ctorArgs.size\n          let fields := fields.toList.map .inaccessible\n          return some { alt with patterns := fields ++ ps }\n        else\n          return none\n      | _ => throwErrorAt alt.ref \"dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\\nconstructor expected\"\n  | _ => unreachable!\n\nprivate def hasNonTrivialExample (p : Problem) : Bool :=\n  p.examples.any fun | Example.underscore => false | _ => true\n\nprivate def throwCasesException (p : Problem) (ex : Exception) : MetaM \u03b1 := do\n  match ex with\n  | .error ref msg =>\n    let exampleMsg :=\n      if hasNonTrivialExample p then m!\" after processing{indentD <| examplesToMessageData p.examples}\" else \"\"\n    throw <| Exception.error ref <| m!\"{msg}{exampleMsg}\\n\" ++\n              \"the dependent pattern matcher can solve the following kinds of equations\\n\" ++\n              \"- <var> = <term> and <term> = <var>\\n\" ++\n              \"- <term> = <term> where the terms are definitionally equal\\n\" ++\n              \"- <constructor> = <constructor>, examples: List.cons x xs = List.cons y ys, and List.cons x xs = List.nil\"\n  | _ => throw ex\n\nprivate def processConstructor (p : Problem) : MetaM (Array Problem) := do\n  trace[Meta.Match.match] \"constructor step\"\n  let x :: xs := p.vars | unreachable!\n  let subgoals? \u2190 commitWhenSome? do\n     let subgoals \u2190\n       try\n         p.mvarId.cases x.fvarId!\n       catch ex =>\n         if p.alts.isEmpty then\n           /- If we have no alternatives and dependent pattern matching fails, then a \"missing cases\" error is bettern than a \"stuck\" error message. -/\n           return none\n         else\n           throwCasesException p ex\n     if subgoals.isEmpty then\n       /- Easy case: we have solved problem `p` since there are no subgoals -/\n       return some #[]\n     else if !p.alts.isEmpty then\n       return some subgoals\n     else do\n       let isRec \u2190 withGoalOf p <| hasRecursiveType x\n        /- If there are no alternatives and the type of the current variable is recursive, we do NOT consider\n          a constructor-transition to avoid nontermination.\n          TODO: implement a more general approach if this is not sufficient in practice -/\n       if isRec then\n         return none\n       else\n         return some subgoals\n  let some subgoals := subgoals? | return #[{ p with vars := xs }]\n  subgoals.mapM fun subgoal => subgoal.mvarId.withContext do\n    let subst    := subgoal.subst\n    let fields   := subgoal.fields.toList\n    let newVars  := fields ++ xs\n    let newVars  := newVars.map fun x => x.applyFVarSubst subst\n    let subex    := Example.ctor subgoal.ctorName <| fields.map fun field => match field with\n      | .fvar fvarId => Example.var fvarId\n      | _            => Example.underscore -- This case can happen due to dependent elimination\n    let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex\n    let examples := examples.map <| Example.applyFVarSubst subst\n    let newAlts  := p.alts.filter fun alt => match alt.patterns with\n      | .ctor n .. :: _       => n == subgoal.ctorName\n      | .var _ :: _           => true\n      | .inaccessible _ :: _  => true\n      | _                     => false\n    let newAlts  := newAlts.map fun alt => alt.applyFVarSubst subst\n    let newAlts \u2190 newAlts.filterMapM fun alt => do\n      match alt.patterns with\n      | .ctor _ _ _ fields :: ps  => return some { alt with patterns := fields ++ ps }\n      | .var fvarId :: ps         => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName\n      | .inaccessible _ :: _      => processInaccessibleAsCtor alt subgoal.ctorName\n      | _                         => unreachable!\n    return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }\n\nprivate def altsAreCtorLike (p : Problem) : MetaM Bool := withGoalOf p do\n  p.alts.allM fun alt => do match alt.patterns with\n    | .ctor .. :: _ => return true\n    | .inaccessible e :: _ => return (\u2190 whnfD e).isConstructorApp (\u2190 getEnv)\n    | _ => return false\n\nprivate def processNonVariable (p : Problem) : MetaM Problem := withGoalOf p do\n  let x :: xs := p.vars | unreachable!\n  if let some (ctorVal, xArgs) := (\u2190 whnfD x).constructorApp? (\u2190 getEnv) then\n    if (\u2190 altsAreCtorLike p) then\n      let alts \u2190 p.alts.filterMapM fun alt => do\n        match alt.patterns with\n        | .ctor ctorName _ _ fields :: ps   =>\n          if ctorName != ctorVal.name then\n            return none\n          else\n            return some { alt with patterns := fields ++ ps }\n        | .inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name\n        | _ => unreachable!\n      let xFields := xArgs.extract ctorVal.numParams xArgs.size\n      return { p with alts := alts, vars := xFields.toList ++ xs }\n  let alts \u2190 p.alts.mapM fun alt => do\n    match alt.patterns with\n    | p :: ps => return { alt with patterns := ps, cnstrs := (x, \u2190 p.toExpr) :: alt.cnstrs }\n    | _      => unreachable!\n  return { p with alts := alts, vars := xs }\n\nprivate def collectValues (p : Problem) : Array Expr :=\n  p.alts.foldl (init := #[]) fun values alt =>\n    match alt.patterns with\n    | .val v :: _ => if values.contains v then values else values.push v\n    | _           => values\n\nprivate def isFirstPatternVar (alt : Alt) : Bool :=\n  match alt.patterns with\n  | .var _ :: _ => true\n  | _           => false\n\nprivate def processValue (p : Problem) : MetaM (Array Problem) := do\n  trace[Meta.Match.match] \"value step\"\n  let x :: xs := p.vars | unreachable!\n  let values := collectValues p\n  let subgoals \u2190 caseValues p.mvarId x.fvarId! values (substNewEqs := true)\n  subgoals.mapIdxM fun i subgoal => do\n    trace[Meta.Match.match] \"processValue subgoal\\n{MessageData.ofGoal subgoal.mvarId}\"\n    if h : i.val < values.size then\n      let value := values.get \u27e8i, h\u27e9\n      -- (x = value) branch\n      let subst := subgoal.subst\n      trace[Meta.Match.match] \"processValue subst: {subst.map.toList.map fun p => mkFVar p.1}, {subst.map.toList.map fun p => p.2}\"\n        let examples := p.examples.map <| Example.replaceFVarId x.fvarId! (Example.val value)\n      let examples := examples.map <| Example.applyFVarSubst subst\n      let newAlts  := p.alts.filter fun alt => match alt.patterns with\n        | .val v :: _ => v == value\n        | .var _ :: _ => true\n        | _           => false\n      let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst\n      let newAlts := newAlts.map fun alt => match alt.patterns with\n        | .val _ :: ps      => { alt with patterns := ps }\n        | .var fvarId :: ps =>\n          let alt := { alt with patterns := ps }\n          alt.replaceFVarId fvarId value\n        | _  => unreachable!\n      let newVars := xs.map fun x => x.applyFVarSubst subst\n      return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }\n    else\n      -- else branch for value\n      let newAlts := p.alts.filter isFirstPatternVar\n      return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }\n\nprivate def collectArraySizes (p : Problem) : Array Nat :=\n  p.alts.foldl (init := #[]) fun sizes alt =>\n    match alt.patterns with\n    | .arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz\n    | _                   => sizes\n\nprivate def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt :=\n  withExistingLocalDecls alt.fvarDecls do\n    let fvarDecl \u2190 fvarId.getDecl\n    let varNamePrefix := fvarDecl.userName\n    let rec loop (n : Nat) (newVars : Array Expr) := do\n      match n with\n      | n+1 =>\n        withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x =>\n          loop n (newVars.push x)\n      | 0 =>\n        let arrayLit \u2190 mkArrayLit arrayElemType newVars.toList\n        let alt := alt.replaceFVarId fvarId arrayLit\n        let newDecls \u2190 newVars.toList.mapM fun newVar => newVar.fvarId!.getDecl\n        let newPatterns := newVars.toList.map fun newVar => .var newVar.fvarId!\n        return { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns }\n    loop arraySize #[]\n\nprivate def processArrayLit (p : Problem) : MetaM (Array Problem) := do\n  trace[Meta.Match.match] \"array literal step\"\n  let x :: xs := p.vars | unreachable!\n  let sizes := collectArraySizes p\n  let subgoals \u2190 caseArraySizes p.mvarId x.fvarId! sizes\n  subgoals.mapIdxM fun i subgoal => do\n    if i.val < sizes.size then\n      let size     := sizes.get! i\n      let subst    := subgoal.subst\n      let elems    := subgoal.elems.toList\n      let newVars  := elems.map mkFVar ++ xs\n      let newVars  := newVars.map fun x => x.applyFVarSubst subst\n      let subex    := Example.arrayLit <| elems.map Example.var\n      let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex\n      let examples := examples.map <| Example.applyFVarSubst subst\n      let newAlts  := p.alts.filter fun alt => match alt.patterns with\n        | .arrayLit _ ps :: _ => ps.length == size\n        | .var _ :: _         => true\n        | _                          => false\n      let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst\n      let newAlts \u2190 newAlts.mapM fun alt => do\n        match alt.patterns with\n        | .arrayLit _ pats :: ps => return { alt with patterns := pats ++ ps }\n        | .var fvarId :: ps      =>\n          let \u03b1 \u2190 getArrayArgType <| subst.apply x\n          expandVarIntoArrayLit { alt with patterns := ps } fvarId \u03b1 size\n        | _  => unreachable!\n      return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples }\n    else\n      -- else branch\n      let newAlts := p.alts.filter isFirstPatternVar\n      return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs }\n\nprivate def expandNatValuePattern (p : Problem) : Problem :=\n  let alts := p.alts.map fun alt => match alt.patterns with\n    | .val (.lit (.natVal 0)) :: ps     => { alt with patterns := .ctor ``Nat.zero [] [] [] :: ps }\n    | .val (.lit (.natVal (n+1))) :: ps => { alt with patterns := .ctor ``Nat.succ [] [] [.val (mkRawNatLit n)] :: ps }\n    | _                                 => alt\n  { p with alts := alts }\n\nprivate def traceStep (msg : String) : StateRefT State MetaM Unit := do\n  trace[Meta.Match.match] \"{msg} step\"\n\nprivate def traceState (p : Problem) : MetaM Unit :=\n  withGoalOf p (traceM `Meta.Match.match p.toMessageData)\n\nprivate def throwNonSupported (p : Problem) : MetaM Unit :=\n  withGoalOf p do\n    let msg \u2190 p.toMessageData\n    throwError \"failed to compile pattern matching, stuck at{indentD msg}\"\n\ndef isCurrVarInductive (p : Problem) : MetaM Bool := do\n  match p.vars with\n  | []   => return false\n  | x::_ => withGoalOf p do\n    let val? \u2190 getInductiveVal? x\n    return val?.isSome\n\nprivate def checkNextPatternTypes (p : Problem) : MetaM Unit := do\n  match p.vars with\n  | []   => return ()\n  | x::_ => withGoalOf p do\n    for alt in p.alts do\n      withRef alt.ref do\n        match alt.patterns with\n        | []   => return ()\n        | p::_ =>\n          let e \u2190 p.toExpr\n          let xType \u2190 inferType x\n          let eType \u2190 inferType e\n          unless (\u2190 isDefEq xType eType) do\n            throwError \"pattern{indentExpr e}\\n{\u2190 mkHasTypeButIsExpectedMsg eType xType}\"\n\nprivate partial def process (p : Problem) : StateRefT State MetaM Unit := do\n  traceState p\n  let isInductive \u2190 isCurrVarInductive p\n  if isDone p then\n    traceStep (\"leaf\")\n    processLeaf p\n  else if hasAsPattern p then\n    traceStep (\"as-pattern\")\n    let p \u2190 processAsPattern p\n    process p\n  else if isNatValueTransition p then\n    traceStep (\"nat value to constructor\")\n    process (expandNatValuePattern p)\n  else if !isNextVar p then\n    traceStep (\"non variable\")\n    let p \u2190 processNonVariable p\n    process p\n  else if isInductive && isConstructorTransition p then\n    let ps \u2190 processConstructor p\n    ps.forM process\n  else if isVariableTransition p then\n    traceStep (\"variable\")\n    let p \u2190 processVariable p\n    process p\n  else if isValueTransition p then\n    let ps \u2190 processValue p\n    ps.forM process\n  else if isArrayLitTransition p then\n    let ps \u2190 processArrayLit p\n    ps.forM process\n  else if hasNatValPattern p then\n    -- This branch is reachable when `p`, for example, is just values without an else-alternative.\n    -- We added it just to get better error messages.\n    traceStep (\"nat value to constructor\")\n    process (expandNatValuePattern p)\n  else\n    checkNextPatternTypes p\n    throwNonSupported p\n\nprivate def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) :=\n  if uElim == levelZero then\n    return none\n  else match matcherLevels.toArray.indexOf? uElim with\n    | none => throwError \"dependent match elimination failed, universe level not found\"\n    | some pos => return some pos.val\n\n/- See comment at `mkMatcher` before `mkAuxDefinition` -/\nregister_builtin_option bootstrap.genMatcherCode : Bool := {\n  defValue := true\n  group := \"bootstrap\"\n  descr := \"disable code generation for auxiliary matcher function\"\n}\n\nbuiltin_initialize matcherExt : EnvExtension (PHashMap (Expr \u00d7 Bool) Name) \u2190 registerEnvExtension (pure {})\n\n/-- Similar to `mkAuxDefinition`, but uses the cache `matcherExt`.\n   It also returns an Boolean that indicates whether a new matcher function was added to the environment or not. -/\ndef mkMatcherAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM (Expr \u00d7 Option (MatcherInfo \u2192 MetaM Unit)) := do\n  trace[Meta.Match.debug] \"{name} : {type} := {value}\"\n  let compile := bootstrap.genMatcherCode.get (\u2190 getOptions)\n  let result \u2190 Closure.mkValueTypeClosure type value (zeta := false)\n  let env \u2190 getEnv\n  let mkMatcherConst name :=\n    mkAppN (mkConst name result.levelArgs.toList) result.exprArgs\n  match (matcherExt.getState env).find? (result.value, compile) with\n  | some nameNew => return (mkMatcherConst nameNew, none)\n  | none =>\n    let decl := Declaration.defnDecl {\n      name\n      levelParams := result.levelParams.toList\n      type        := result.type\n      value       := result.value\n      hints       := ReducibilityHints.abbrev\n      safety      := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe\n    }\n    trace[Meta.Match.debug] \"{name} : {result.type} := {result.value}\"\n    let addMatcher : MatcherInfo \u2192 MetaM Unit := fun mi => do\n      addDecl decl\n      modifyEnv fun env => matcherExt.modifyState env fun s => s.insert (result.value, compile) name\n      addMatcherInfo name mi\n      setInlineAttribute name\n      if compile then\n        compileDecl decl\n    return (mkMatcherConst name, some addMatcher)\n\nstructure MkMatcherInput where\n  matcherName : Name\n  matchType   : Expr\n  discrInfos  : Array DiscrInfo\n  lhss        : List AltLHS\n\ndef MkMatcherInput.numDiscrs (m : MkMatcherInput) :=\n  m.discrInfos.size\n\ndef MkMatcherInput.collectFVars (m : MkMatcherInput) : StateRefT CollectFVars.State MetaM Unit := do\n  m.matchType.collectFVars\n  m.lhss.forM fun alt => alt.collectFVars\n\ndef MkMatcherInput.collectDependencies (m : MkMatcherInput) : MetaM FVarIdSet := do\n  let (_, s) \u2190 m.collectFVars |>.run {}\n  let s \u2190 s.addDependencies\n  return s.fvarSet\n\n/--\nAuxiliary method used at `mkMatcher`. It executes `k` in a local context that contains only\nthe local declarations `m` depends on. This is important because otherwise dependent elimination\nmay \"refine\" the types of unnecessary declarations and accidentally introduce unnecessary dependencies\nin the auto-generated auxiliary declaration. Note that this is not just an optimization because the\nunnecessary dependencies may prevent the termination checker from succeeding. For an example,\nsee issue #1237.\n-/\ndef withCleanLCtxFor (m : MkMatcherInput) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let s \u2190 m.collectDependencies\n  let lctx \u2190 getLCtx\n  let lctx := lctx.foldr (init := lctx) fun localDecl lctx =>\n    if s.contains localDecl.fvarId then lctx else lctx.erase localDecl.fvarId\n  let localInstances := (\u2190 getLocalInstances).filter fun localInst => s.contains localInst.fvar.fvarId!\n  withLCtx lctx localInstances k\n\n/--\nCreate a dependent matcher for `matchType` where `matchType` is of the form\n`(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]`\nwhere `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives.\nEach `AltLHS` has a list of local declarations and a list of patterns.\nThe number of patterns must be the same in each `AltLHS`.\nThe generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form\n`(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)`\nwhere `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/\ndef mkMatcher (input : MkMatcherInput) : MetaM MatcherResult := withCleanLCtxFor input do\n  let \u27e8matcherName, matchType, discrInfos, lhss\u27e9 := input\n  let numDiscrs := discrInfos.size\n  let numEqs := getNumEqsFromDiscrInfos discrInfos\n  checkNumPatterns numDiscrs lhss\n  forallBoundedTelescope matchType numDiscrs fun discrs matchTypeBody => do\n  /- We generate an matcher that can eliminate using different motives with different universe levels.\n     `uElim` is the universe level the caller wants to eliminate to.\n     If it is not levelZero, we create a matcher that can eliminate in any universe level.\n     This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/\n  let uElim \u2190 getLevel matchTypeBody\n  let uElimGen \u2190 if uElim == levelZero then pure levelZero else mkFreshLevelMVar\n  let mkMatcher (type val : Expr) (minors : Array (Expr \u00d7 Nat)) (s : State) : MetaM MatcherResult := do\n    trace[Meta.Match.debug] \"matcher value: {val}\\ntype: {type}\"\n    trace[Meta.Match.debug] \"minors num params: {minors.map (\u00b7.2)}\"\n    /- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example,\n       for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt`\n       for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to\n       give the reference implementation for\n       ```\n       @[extern \"lean_int_neg\"] def neg (n : @& Int) : Int :=\n       match n with\n       | ofNat n   => negOfNat n\n       | negSucc n => succ n\n       ```\n       which is defined **before** `Int.decLt` -/\n\n    let (matcher, addMatcher) \u2190 mkMatcherAuxDefinition matcherName type val\n    trace[Meta.Match.debug] \"matcher levels: {matcher.getAppFn.constLevels!}, uElim: {uElimGen}\"\n    let uElimPos? \u2190 getUElimPos? matcher.getAppFn.constLevels! uElimGen\n    discard <| isLevelDefEq uElimGen uElim\n    let addMatcher :=\n      match addMatcher with\n      | some addMatcher => addMatcher <|\n        { numParams := matcher.getAppNumArgs\n          altNumParams := minors.map fun minor => minor.2 + numEqs\n          discrInfos\n          numDiscrs\n          uElimPos?\n          }\n      | none => pure ()\n\n    trace[Meta.Match.debug] \"matcher: {matcher}\"\n    let unusedAltIdxs := lhss.length.fold (init := []) fun i r =>\n      if s.used.contains i then r else i::r\n    return {\n      matcher,\n      counterExamples := s.counterExamples,\n      unusedAltIdxs := unusedAltIdxs.reverse,\n      addMatcher\n    }\n\n  let motiveType \u2190 mkForallFVars discrs (mkSort uElimGen)\n  trace[Meta.Match.debug] \"motiveType: {motiveType}\"\n  withLocalDeclD `motive motiveType fun motive => do\n  if discrInfos.any fun info => info.hName?.isSome then\n    forallBoundedTelescope matchType numDiscrs fun discrs' _ => do\n    let (mvarType, isEqMask) \u2190 withEqs discrs discrs' discrInfos fun eqs => do\n      let mvarType \u2190 mkForallFVars eqs (mkAppN motive discrs')\n      let isEqMask \u2190 eqs.mapM fun eq => return (\u2190 inferType eq).isEq\n      return (mvarType, isEqMask)\n    trace[Meta.Match.debug] \"target: {mvarType}\"\n    withAlts motive discrs discrInfos lhss fun alts minors => do\n      let mvar \u2190 mkFreshExprMVar mvarType\n      trace[Meta.Match.debug] \"goal\\n{mvar.mvarId!}\"\n      let examples := discrs'.toList.map fun discr => Example.var discr.fvarId!\n      let (_, s) \u2190 (process { mvarId := mvar.mvarId!, vars := discrs'.toList, alts := alts, examples := examples }).run {}\n      let val \u2190 mkLambdaFVars discrs' mvar\n      trace[Meta.Match.debug] \"matcher\\nvalue: {val}\\ntype: {\u2190 inferType val}\"\n      let mut rfls := #[]\n      let mut isEqMaskIdx := 0\n      for discr in discrs, info in discrInfos do\n        if info.hName?.isSome then\n          if isEqMask[isEqMaskIdx]! then\n            rfls := rfls.push (\u2190 mkEqRefl discr)\n          else\n            rfls := rfls.push (\u2190 mkHEqRefl discr)\n          isEqMaskIdx := isEqMaskIdx + 1\n      let val := mkAppN (mkAppN val discrs) rfls\n      let args := #[motive] ++ discrs ++ minors.map Prod.fst\n      let val \u2190 mkLambdaFVars args val\n      let type \u2190 mkForallFVars args (mkAppN motive discrs)\n      mkMatcher type val minors s\n  else\n    let mvarType  := mkAppN motive discrs\n    trace[Meta.Match.debug] \"target: {mvarType}\"\n    withAlts motive discrs discrInfos lhss fun alts minors => do\n      let mvar \u2190 mkFreshExprMVar mvarType\n      let examples := discrs.toList.map fun discr => Example.var discr.fvarId!\n      let (_, s) \u2190 (process { mvarId := mvar.mvarId!, vars := discrs.toList, alts := alts, examples := examples }).run {}\n      let args := #[motive] ++ discrs ++ minors.map Prod.fst\n      let type \u2190 mkForallFVars args mvarType\n      let val  \u2190 mkLambdaFVars args mvar\n      mkMatcher type val minors s\n\ndef getMkMatcherInputInContext (matcherApp : MatcherApp) : MetaM MkMatcherInput := do\n  let matcherName := matcherApp.matcherName\n  let some matcherInfo \u2190 getMatcherInfo? matcherName | throwError \"not a matcher: {matcherName}\"\n  let matcherConst \u2190 getConstInfo matcherName\n  let matcherType \u2190 instantiateForall matcherConst.type <| matcherApp.params ++ #[matcherApp.motive]\n  let matchType \u2190 do\n    let u :=\n      if let some idx := matcherInfo.uElimPos?\n      then mkLevelParam matcherConst.levelParams.toArray[idx]!\n      else levelZero\n    forallBoundedTelescope matcherType (some matcherInfo.numDiscrs) fun discrs _ => do\n    mkForallFVars discrs (mkConst ``PUnit [u])\n\n  let matcherType \u2190 instantiateForall matcherType matcherApp.discrs\n  let lhss \u2190 forallBoundedTelescope matcherType (some matcherApp.alts.size) fun alts _ =>\n    alts.mapM fun alt => do\n    let ty \u2190 inferType alt\n    forallTelescope ty fun xs body => do\n    let xs \u2190 xs.filterM fun x => dependsOn body x.fvarId!\n    body.withApp fun _ args => do\n    let ctx \u2190 getLCtx\n    let localDecls := xs.map ctx.getFVar!\n    let patterns \u2190 args.mapM Match.toPattern\n    return {\n      ref := Syntax.missing\n      fvarDecls := localDecls.toList\n      patterns := patterns.toList : Match.AltLHS }\n\n  return { matcherName, matchType, discrInfos := matcherInfo.discrInfos, lhss := lhss.toList }\n\n/-- This function is only used for testing purposes -/\ndef withMkMatcherInput (matcherName : Name) (k : MkMatcherInput \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let some matcherInfo \u2190 getMatcherInfo? matcherName | throwError \"not a matcher: {matcherName}\"\n  let matcherConst \u2190 getConstInfo matcherName\n  forallBoundedTelescope matcherConst.type (some matcherInfo.arity) fun xs _ => do\n  let matcherApp \u2190 mkConstWithLevelParams matcherConst.name\n  let matcherApp := mkAppN matcherApp xs\n  let some matcherApp \u2190 matchMatcherApp? matcherApp | throwError \"not a matcher app: {matcherApp}\"\n  let mkMatcherInput \u2190 getMkMatcherInputInContext matcherApp\n  k mkMatcherInput\n\nend Match\n\n/-- Auxiliary function for MatcherApp.addArg -/\nprivate partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat \u00d7 Array Expr) := do\n  if h : i < alts.size then\n    let alt       := alts.get \u27e8i, h\u27e9\n    let numParams := altNumParams[i]!\n    let typeNew \u2190 whnfD typeNew\n    match typeNew with\n    | Expr.forallE _ d b _ =>\n      let alt \u2190 forallBoundedTelescope d (some numParams) fun xs d => do\n        let alt \u2190 try instantiateLambda alt xs catch _ => throwError \"unexpected matcher application, insufficient number of parameters in alternative\"\n        forallBoundedTelescope d (some 1) fun x _ => do\n          let alt \u2190 mkLambdaFVars x alt -- x is the new argument we are adding to the alternative\n          mkLambdaFVars xs alt\n      updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set \u27e8i, h\u27e9 alt) (i+1)\n    | _ => throwError \"unexpected type at MatcherApp.addArg\"\n  else\n    return (altNumParams, alts)\n\n/-- Given\n  - matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and\n  - expression `e : B[discrs]`,\n  Construct the term\n  `match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and\n  We use `kabstract` to abstract the discriminants from `B[discrs]`.\n  This method assumes\n  - the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size`\n  - each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]`\n-/\ndef MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp :=\n  lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do\n    unless motiveArgs.size == matcherApp.discrs.size do\n      -- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`.\n      throwError \"unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments\"\n    let eType \u2190 inferType e\n    let eTypeAbst \u2190 matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do\n      let motiveArg := motiveArgs[i]!\n      let discr     := matcherApp.discrs[i]!\n      let eTypeAbst \u2190 kabstract eTypeAbst discr\n      return eTypeAbst.instantiate1 motiveArg\n    let motiveBody \u2190 mkArrow eTypeAbst motiveBody\n    let matcherLevels \u2190 match matcherApp.uElimPos? with\n      | none     => pure matcherApp.matcherLevels\n      | some pos =>\n        let uElim \u2190 getLevel motiveBody\n        pure <| matcherApp.matcherLevels.set! pos uElim\n    let motive \u2190 mkLambdaFVars motiveArgs motiveBody\n    -- Construct `aux` `match_i As (fun xs => B[xs] \u2192 motive[xs]) discrs`, and infer its type `auxType`.\n    -- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative.\n    let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params\n    let aux := mkApp aux motive\n    let aux := mkAppN aux matcherApp.discrs\n    unless (\u2190 isTypeCorrect aux) do\n      throwError \"failed to add argument to matcher application, type error when constructing the new motive\"\n    let auxType \u2190 inferType aux\n    let (altNumParams, alts) \u2190 updateAlts auxType matcherApp.altNumParams matcherApp.alts 0\n    return { matcherApp with\n      matcherLevels := matcherLevels,\n      motive        := motive,\n      alts          := alts,\n      altNumParams  := altNumParams,\n      remaining     := #[e] ++ matcherApp.remaining\n    }\n\n/-- Similar `MatcherApp.addArg?`, but returns `none` on failure. -/\ndef MatcherApp.addArg? (matcherApp : MatcherApp) (e : Expr) : MetaM (Option MatcherApp) :=\n  try\n    return some (\u2190 matcherApp.addArg e)\n  catch _ =>\n    return none\n\nbuiltin_initialize\n  registerTraceClass `Meta.Match.match\n  registerTraceClass `Meta.Match.debug\n  registerTraceClass `Meta.Match.unify\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/Match/Match.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.05340333356619822, "lm_q1q2_score": 0.02524287337319123}}
{"text": "theorem ex\n     (h\u2081 : \u03b1 = \u03b2)\n     (as : List \u03b1)\n     (bs : List \u03b2)\n     (h\u2082 : (h \u25b8 as) = bs)\n     : True :=\n  True.intro\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/autoBoundPostponeLoop.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.06187598226375124, "lm_q1q2_score": 0.025204154236675467}}
{"text": "import Std.Data.PersistentHashMap\n\nopen Std\ndef m : PersistentHashMap Nat Nat :=\nlet m : PersistentHashMap Nat Nat := {};\nm.insert 1 1\n\ndef natDiffHash : Hashable Nat :=\n\u27e8fun n => USize.ofNat $ n+10\u27e9\n\n-- The following example should fail since the `Hashable` instance used to create `m` is not `natDiffHash`\n#eval @PersistentHashMap.find? Nat Nat _ natDiffHash m 1\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/phashmap_inst_coherence.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.05419872753163018, "lm_q1q2_score": 0.025197073595893005}}
{"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 \u2192 MetaM Bool\n  | [] => pure false\n  | h :: hs => do\n    let ldecl \u2190 getFVarLocalDecl h\n    if !ldecl.binderInfo.isInstImplicit\n        && !(\u2190 hs.anyM fun h' => do pure $ (\u2190 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 \u2192 MetaM \u03b1) : MetaM (Array \u03b1) := withReducible do\n  (\u2190 preprocess (\u2190 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 := \u2190 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 \u2190 if whnfFirst then whnf a else pure a\n  let b \u2190 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 \u2192 MetaM (Option MessageData)) : MetaM (Option MessageData) := do\n  let errors := (\u2190 withSimpTheoremInfos ty fun i => do (\u2190 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 $ (\u2190 getSimpTheorems).lemmaNames.contains declName\n\nopen Lean.Meta.DiscrTree\npartial def trieElements : Trie \u03b1 \u2192 StateT (Array \u03b1) Id Unit\n  | Trie.node vs children => do\n    modify (\u00b7 ++ vs)\n    for (_, child) in children do\n      trieElements child\n\ndef elements (d : DiscrTree \u03b1) : StateT (Array \u03b1) 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 \u2194 b` it generates `decl._auxLemma.1 : a = b`.\n-- This function computes the map ``{`decl._auxLemma.1 \u21a6 `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 \u03b1) : MetaM \u03b1 := 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 \u2190 isSimpTheorem declName do return none\n    -- TODO: equation lemmas\n    let ctx \u2190 Simp.Context.mkDefault\n    checkAllSimpTheoremInfos (\u2190 getConstInfo declName).type fun {lhs, rhs, isConditional, ..} => do\n    let \u27e8lhs', prf1\u27e9 \u2190 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 \u27e8rhs', prf2\u27e9 \u2190 decorateError \"simplify fails on right-hand side:\" <| simp rhs ctx\n    let lhs'_eq_rhs' \u2190 isSimpEq lhs' rhs' (whnfFirst := false)\n    let lhs_in_nf \u2190 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 {\u2190 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 \u00ac lhs_in_nf then do\n      return m!\"Left-hand side simplifies from\n  {lhs}\nto\n  {lhs'}\nusing\n  {\u2190 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 \u2190 isSimpTheorem declName do return none\n    checkAllSimpTheoremInfos (\u2190 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 \u2190 isSimpTheorem declName do return none\n    let ty := (\u2190 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') \u2190 forallMetaTelescopeReducing ty\n    let some (_, lhs', rhs') := ty'.eq? | return none\n    unless \u2190 isDefEq rhs lhs' do return none\n    unless \u2190 withNewMCtxDepth (isDefEq rhs lhs') do return none\n    -- ensure that the second application makes progress:\n    if \u2190 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 =\u1d63 X_2] \u2260 Pr[Y_1 =\u1d63 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 {\u03b4:Type*} {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n  (S:set (\u03a0 (a:\u03b4), \u03c0 a)):Prop := \u2203 (f:\u03a0 (a:\u03b4), set (\u03c0 a)), (\u2200 i, measurable_set (f i)) \u2227\n  set.pi set.univ f = S\n\n\nlemma pi_base.closed_inter\n  {\u03b4:Type*} {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n  (S T:set (\u03a0 (a:\u03b4), \u03c0 a)):pi_base S \u2192 pi_base T \u2192 pi_base (S \u2229 T) :=\nbegin\n  intros hS hT,\n  cases hS with fS hS,\n  cases hT with fT hT,\n  apply exists.intro (\u03bb i, (fS i) \u2229 (fT i)),\n  split,\n  { intros i, apply measurable_set.inter, apply hS.left, apply hT.left },\n  rw \u2190 hS.right,\n  rw \u2190 hT.right,\n  ext \u03c9, split; intros h1; simp at h1; simp [h1],\nend\n\nlemma pi_base.empty\n  {\u03b4:Type*} [nonempty \u03b4] {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]:\n  pi_base (\u2205:set (\u03a0 (a : \u03b4), \u03c0 a)) := begin\n  apply exists.intro (\u03bb (d:\u03b4), (\u2205:set (\u03c0 d))),\n  simp [set.pi], \nend\n\nlemma pi_base.univ\n  {\u03b4:Type*} [nonempty \u03b4] {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]:\n  pi_base (set.univ:set (\u03a0 (a : \u03b4), \u03c0 a)) := begin\n  apply exists.intro (\u03bb (d:\u03b4), (set.univ:set (\u03c0 d))),\n  simp [set.pi], \nend\n\nlemma pi_base.closed_compl \n  {\u03b4:Type*} [fintype \u03b4] [nonempty \u03b4] {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n    (s : set (\u03a0 (a : \u03b4), \u03c0 a)):\n    pi_base s \u2192\n    (set.disjoint_union_closure pi_base) s\u1d9c  := begin\n  classical,\n  intros h1,\n  simp [pi_base] at h1,\n  cases h1 with f h1,\n  let f':(\u03b4 \u2192 bool) \u2192 set (\u03a0 (a : \u03b4), \u03c0 a) := \n    (\u03bb x, if (\u2200 (d:\u03b4), x d) then \u2205  else \n   (set.pi (@set.univ \u03b4) (\u03bb (d:\u03b4), if (x d) then (f d) else (f d)\u1d9c))),  \n  begin\n    have h2:s\u1d9c = set.Union f',\n    { rw \u2190 h1.right, simp [f'], ext; split; intros h2_1;\n      simp at h2_1; simp [h2_1],\n      { let i:\u03b4 \u2192 bool := (\u03bb (d:\u03b4), x d \u2208 (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 \u2208 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 (\u2200 (d : \u03b4), (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 (\u2200 (d : \u03b4), (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 (\u03bb (d : \u03b4), ite \u21a5(b d) (f d) (f d)\u1d9c),\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 \u2190 set.subset_empty_iff,\n    rw set.subset_def,\n    intros \u03c9 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 (\u2200 (d : \u03b4), (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 (\u2200 (d : \u03b4), (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 {\u03b4:Type*} {\u03c0:\u03b4 \u2192 Type*} {f:\u03a0 (a:\u03b4), set (\u03c0 a)}:\n  (set.pi set.univ f) = (\u22c2 (i:\u03b4), (\u03bb (d:\u03a0 (a:\u03b4), \u03c0 a), d i) \u207b\u00b9' (f i)) := begin\n  ext,split;intros A1; simp at A1; simp [A1],\nend\n\nlemma pi_base.measurable_set {\u03b4:Type*} [encodable \u03b4] {\u03c0:\u03b4 \u2192 Type*} \n  [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n  (S:set (\u03a0 (a:\u03b4), \u03c0 a)):pi_base S \u2192 measurable_set S :=\nbegin\n  intros hS,\n  cases hS with fS hS,\n  cases hS with h_meas h_def,\n  rw \u2190 h_def,\n  rw set.pi_as_preimage,\n  apply measurable_set.Inter,\n  intros b,\n  have h_proj_meas:measurable (\u03bb (d : \u03a0 (a : \u03b4), \u03c0 a), d b),\n  { apply measurable_pi_apply },\n  apply h_proj_meas,\n  apply h_meas,\nend\n\nlemma pi_base.covers_generate {\u03b4:Type*} [encodable \u03b4] {\u03c0:\u03b4 \u2192 Type*} \n  [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n  (S:set (\u03a0 (a:\u03b4), \u03c0 a)):\n  S \u2208  \n     (\u22c3 (i : \u03b4),\n       (measurable_space.comap (\u03bb (b : \u03a0 (a : \u03b4), (\u03bb (a : \u03b4), \u03c0 a) a), b i)\n          ((\u03bb (a : \u03b4), M a) i)).measurable_set') \u2192 \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:\u2200 (d':\u03b4), \u2203 (T:set (\u03c0 d')), measurable_set T \u2227\n     (\u2200 (s':(\u03a0 (a:\u03b4), \u03c0 a)), s' \u2208 S \u2192 s' d' \u2208 T) \u2227 (d' = d \u2192 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 \u2190 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 \u03c9,\n     simp [set.pi],split; intros h8,\n     { rw \u2190 h3,\n       have h9:d = d := rfl,\n       have h10 := (h7 d).right.right h9,\n       simp at h10, rw \u2190 h10, \n       simp, apply h8 },\n     { intros d',\n       have h11 := (h7 d').right.left \u03c9 h8, apply h11 } },\nend\n\nlemma pi_base_eq_measurable_space_pi {\u03b4:Type*} [encodable \u03b4] {\u03c0:\u03b4 \u2192 Type*} \n  [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]:\n @measurable_space.pi \u03b4 \u03c0 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 {\u03b4:Type*} [fintype \u03b4] {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n  (S:measurable_setB (@measurable_space.pi \u03b4 \u03c0 M)):pi_base S.val \u2192\n  \u2203 (f:\u03a0 (b:\u03b4), 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 := (\u03bb (b:\u03b4), @measurable_setB.mk _ _ (g b) (h1 b)),\n  begin\n     apply exists.intro f,\n     apply subtype.eq,\n     rw \u2190 h2,\n     simp [set.pi, set.pi_measurable, f],\n     ext \u03c9,split;intros h1; simp at h1; simp [h1]; intros i; apply h1,\n  end\nend\n\nlemma pi_base_is_semialgebra {\u03b4:Type*} [fintype \u03b4] [nonempty \u03b4] {\u03c0:\u03b4 \u2192 Type*} \n  [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]:set.is_semialgebra (@pi_base \u03b4 \u03c0 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 {\u03a9 \u03b4:Type*} [fintype \u03b4] \n  {P:probability_space \u03a9}\n  {\u03c0:\u03b4 \u2192 Type*} [M:\u03a0 (a:\u03b4), measurable_space (\u03c0 a)]\n  (f:\u03a0 (b:\u03b4), measurable_setB (M b))\n  {X:\u03a0 (b:\u03b4), P \u2192\u1d63 (M b)}:\n  (pi.random_variable_combine X \u2208\u1d63 (set.pi_measurable set.univ f)) =\n  (\u2200\u1d63 (b:\u03b4), (X b) \u2208\u1d63 (f b)) := begin\n  apply event.eq,\n  simp [pi.random_variable_combine, set.pi_measurable, pi.measurable_fun],\n  ext \u03c9, split; intros h1; simp at h1; simp [h1],\nend\n\n  \nlemma random_variable_independent_all {\u03a9 \u03b2:Type*} {P:probability_space \u03a9} [fintype \u03b2]\n  {\u03b3:\u03b2 \u2192 Type*} {M:\u03a0 (b:\u03b2), measurable_space (\u03b3 b)}\n   (S:\u03a0 (b:\u03b2), measurable_setB (M b))\n   {X:\u03a0 (b:\u03b2), P \u2192\u1d63 (M b)}:\n   random_variable_independent X \u2192\n   Pr[\u2200\u1d63 (b : \u03b2), X b \u2208\u1d63 S b] =  finset.univ.prod (\u03bb (b:\u03b2), Pr[X b \u2208\u1d63 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' {\u03a9\u2081 \u03a9\u2082 \u03b2 \u03b3:Type*} [fintype \u03b2] \n  {P\u2081:probability_space \u03a9\u2081}\n  {P\u2082:probability_space \u03a9\u2082}\n  {M:measurable_space \u03b3} \n  {X\u2081:\u03b2 \u2192 P\u2081 \u2192\u1d63 M}  {X\u2082:\u03b2  \u2192 P\u2082 \u2192\u1d63 M}\n  (S:measurable_setB (@measurable_space.pi \u03b2 (\u03bb _, \u03b3) (\u03bb _, M))):\n  pi_base S.val \u2192\n  (\u2200 (b:\u03b2), random_variable_identical (X\u2081 b) (X\u2082 b)) \u2192\n  (random_variables_IID X\u2081) \u2192\n  (random_variables_IID X\u2082) \u2192\n  (Pr[pi.random_variable_combine X\u2081 \u2208\u1d63 S] =\n   Pr[pi.random_variable_combine X\u2082 \u2208\u1d63 S]) :=\nbegin\n  intros h1 h2 h3 h4,\n  have h5:=pi_base_eq S h1,\n  cases h5 with f h5,\n  rw \u2190 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:(\u03bb (b : \u03b2), Pr[X\u2081 b \u2208\u1d63 f b]) = (\u03bb (b : \u03b2), Pr[X\u2082 b \u2208\u1d63 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' {\u03a9\u2081 \u03a9\u2082 \u03b2 \u03b3:Type*} [fintype \u03b2] [nonempty \u03b2] \n  {P\u2081:probability_space \u03a9\u2081}\n  {P\u2082:probability_space \u03a9\u2082}\n  {M:measurable_space \u03b3} \n  {X\u2081:\u03b2 \u2192 P\u2081 \u2192\u1d63 M}  {X\u2082:\u03b2  \u2192 P\u2082 \u2192\u1d63 M}:\n  (\u2200 (b:\u03b2), random_variable_identical (X\u2081 b) (X\u2082 b)) \u2192\n  (random_variables_IID X\u2081) \u2192\n  (random_variables_IID X\u2082) \u2192\n  random_variable_identical (pi.random_variable_combine X\u2081)\n                            (pi.random_variable_combine X\u2082)\n  :=\nbegin\n  intros h1 h2 h3,\n  haveI:encodable \u03b2 := fintype.encodable \u03b2,\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 {\u03a9\u2081 \u03a9\u2082 \u03b2 \u03b3:Type*} [fintype \u03b2] [nonempty \u03b2]\n  {P\u2081:probability_space \u03a9\u2081}\n  {P\u2082:probability_space \u03a9\u2082}\n  {M:measurable_space \u03b3} \n  {X\u2081:\u03b2 \u2192 P\u2081 \u2192\u1d63 M}  {X\u2082:\u03b2  \u2192 P\u2082 \u2192\u1d63 M}: \n  (\u2203 (b\u2081 b\u2082:\u03b2), random_variable_identical (X\u2081 b\u2081) (X\u2082 b\u2082)) \u2192\n  (random_variables_IID X\u2081) \u2192\n  (random_variables_IID X\u2082) \u2192\n  random_variable_identical (pi.random_variable_combine X\u2081)\n                            (pi.random_variable_combine X\u2082) :=\nbegin\n  intros h1 h2 h3,\n  apply IID_identical_joint',\n  intros b,\n  cases h1 with b\u2081 h1,\n  cases h1 with b\u2082 h1,\n  have h4:random_variable_identical (X\u2081 b) (X\u2081 b\u2081),\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": "/-\nCopyright \u00a9 2022 Fran\u00e7ois G. Dorais, Kyrill Serdyuk, Emma Shroyer. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n-/\n\nimport Std\nimport UnicodeBasic\n\nstructure ByteSubarray extends ByteArray where\n  start : Nat\n  size  : Nat\n  valid : start + size \u2264 toByteArray.size := by simp_arith [*]\n\nabbrev ByteSubarray.stop (bs : ByteSubarray) : Nat := bs.start + bs.size\n\ndef ByteArray.toByteSubarray (bs : ByteArray) : ByteSubarray where\n  toByteArray := bs\n  start := 0\n  size := bs.size\n\nnamespace ByteSubarray\nvariable (bs : ByteSubarray)\n\n@[inline] def extract : ByteArray := bs.toByteArray.extract bs.start bs.stop\n\n@[inline] def get (i : Fin bs.size) : UInt8 :=\n  have : bs.start + i.val < bs.toByteArray.size := calc\n    _ < bs.start + bs.size := Nat.add_lt_add_left i.isLt bs.start\n    _ \u2264 bs.toByteArray.size := bs.valid\n  bs.toByteArray[bs.start + i.val]'this\n\ninstance : GetElem ByteSubarray Nat UInt8 fun bs i => i < bs.size where\n  getElem xs i h := xs.get \u27e8i, h\u27e9\n\n@[inline] def get? (i : Nat) : Option UInt8 :=\n  if h : i < bs.size then some (bs.get \u27e8i, h\u27e9) else none\n\n@[inline] def getD (i : Nat) (default : UInt8) : UInt8 :=\n  if h : i < bs.size then bs.get \u27e8i, h\u27e9 else default\n\nabbrev get! (i : Nat) : UInt8 := getD bs i default\n\ndef popFront : ByteSubarray :=\n  if h : bs.size \u2265 1 then\n    have : (bs.start+1) + (bs.size-1) = bs.start + bs.size := by\n      rw [Nat.add_assoc, Nat.add_sub_cancel' h]\n    {bs with start := bs.start+1, size := bs.size-1, valid := by rw [this]; exact bs.valid}\n  else bs\n\ndef slice (start stop : Nat) (h : start \u2264 stop \u2227 stop \u2264 bs.size := by simp_arith [*]) : ByteSubarray where\n  toByteArray := bs.toByteArray\n  start := bs.start + start\n  size := stop - start\n  valid := by\n    rw [Nat.add_assoc]\n    rw [Nat.add_sub_cancel' h.1]\n    apply Nat.le_trans _ bs.valid\n    apply Nat.add_le_add_left h.2\n\n@[simp] theorem size_slice (start stop : Nat) (h : start \u2264 stop \u2227 stop \u2264 bs.size := by simp_arith [*]) : (bs.slice start stop h).size = stop - start := rfl\n\n@[inline] unsafe def forInUnsafe {\u03b1 m} [Monad m] (bs : ByteSubarray) (a : \u03b1) (f : UInt8 \u2192 \u03b1 \u2192 m (ForInStep \u03b1)) : m \u03b1 :=\n  let sz := USize.ofNat bs.stop\n  let rec @[specialize] loop (i : USize) (a : \u03b1) : m \u03b1 := do\n    if i < sz then\n      let b := bs.uget i lcProof\n      match (\u2190 f b a) with\n      | ForInStep.done  a => pure a\n      | ForInStep.yield a => loop (i+1) a\n    else\n      pure a\n  loop (USize.ofNat bs.start) a\n\n@[implemented_by ByteSubarray.forInUnsafe]\nprotected def forIn {\u03b1 m} [Monad m] (bs : ByteSubarray) (a : \u03b1) (f : UInt8 \u2192 \u03b1 \u2192 m (ForInStep \u03b1)) : m \u03b1 :=\n  let rec @[specialize] loop (i : Nat) (a : \u03b1) : m \u03b1 := do\n    if h : i < bs.size then\n      let b := bs.get \u27e8i, h\u27e9\n      match (\u2190 f b a) with\n      | ForInStep.done  a => pure a\n      | ForInStep.yield a => loop (i+1) a\n    else\n      pure a\n  loop bs.start a\ntermination_by loop => bs.size - i\n\ninstance : ForIn m ByteSubarray UInt8 where\n  forIn := ByteSubarray.forIn\n\ninstance : Stream ByteSubarray UInt8 where\n  next? s :=\n    if h : s.size > 0 then\n      some (s.get \u27e80, h\u27e9, s.popFront)\n    else\n      none\n\nend ByteSubarray\n", "meta": {"author": "fgdorais", "repo": "lean4-parser", "sha": "26e5e67c7da25e066540107637b1a952863d7387", "save_path": "github-repos/lean/fgdorais-lean4-parser", "path": "github-repos/lean/fgdorais-lean4-parser/lean4-parser-26e5e67c7da25e066540107637b1a952863d7387/Parser/Prelude.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.060086644283076515, "lm_q1q2_score": 0.025158092254878674}}
{"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.environment\n! leanprover-community/mathlib commit 1340477dccb7fbe0cf2146aa1f1995022c13cd30\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.Declaration\nimport Leanbin.Init.Meta.Exceptional\nimport Leanbin.Init.Data.Option.Basic\nimport Leanbin.Init.Meta.RbMap\n\n/--\nAn __environment__ contains all of the declarations and notation that have been defined so far.   -/\nunsafe axiom environment : Type\n#align environment environment\n\nnamespace Environment\n\n/--\nConsider a type `\u03c8` which is an inductive datatype using a single constructor `mk (a : \u03b1) (b : \u03b2) : \u03c8`.\nLean will automatically make two projection functions `a : \u03c8 \u2192 \u03b1`, `b : \u03c8 \u2192 \u03b2`.\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 ProjectionInfo where\n  cname : Name\n  nparams : Nat\n  idx : Nat\n  isClass : Bool\n#align environment.projection_info Environment.ProjectionInfo\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 ImplicitInferKind\n  | implicit\n  | relaxed_implicit\n  | none\n#align environment.implicit_infer_kind Environment.ImplicitInferKind\n\ninstance ImplicitInferKind.inhabited : Inhabited ImplicitInferKind :=\n  \u27e8ImplicitInferKind.implicit\u27e9\n#align environment.implicit_infer_kind.inhabited Environment.ImplicitInferKind.inhabited\n\n/-- One introduction rule in an inductive declaration -/\nunsafe structure intro_rule where\n  constr : Name\n  type : expr\n  infer : ImplicitInferKind := ImplicitInferKind.implicit\n#align environment.intro_rule environment.intro_rule\n\n/-- Create a standard environment using the given trust level -/\nunsafe axiom mk_std : Nat \u2192 environment\n#align environment.mk_std environment.mk_std\n\n/-- Return the trust level of the given environment -/\nunsafe axiom trust_lvl : environment \u2192 Nat\n#align environment.trust_lvl environment.trust_lvl\n\n/-- Add a new declaration to the environment -/\nunsafe axiom add : environment \u2192 declaration \u2192 exceptional environment\n#align environment.add environment.add\n\n/-- make declaration `n` protected -/\nunsafe axiom mk_protected : environment \u2192 Name \u2192 environment\n#align environment.mk_protected environment.mk_protected\n\n/-- add declaration `d` and make it protected -/\nunsafe def add_protected (env : environment) (d : declaration) : exceptional environment := do\n  let env \u2190 env.add d\n  pure <| env d\n#align environment.add_protected environment.add_protected\n\n/-- check if `n` is the name of a protected declaration -/\nunsafe axiom is_protected : environment \u2192 Name \u2192 Bool\n#align environment.is_protected environment.is_protected\n\n/-- Retrieve a declaration from the environment -/\nunsafe axiom get : environment \u2192 Name \u2192 exceptional declaration\n#align environment.get environment.get\n\nunsafe def contains (env : environment) (d : Name) : Bool :=\n  match env.get d with\n  | exceptional.success _ => true\n  | exceptional.exception _ => false\n#align environment.contains environment.contains\n\nunsafe axiom add_defn_eqns (env : environment) (opt : options) (lp_params : List Name)\n    (params : List expr) (sig : expr) (eqns : List (List (expr false) \u00d7 expr)) (is_meta : Bool) :\n    exceptional environment\n#align environment.add_defn_eqns environment.add_defn_eqns\n\n/-- Register the given name as a namespace, making it available to the `open` command -/\nunsafe axiom add_namespace : environment \u2192 Name \u2192 environment\n#align environment.add_namespace environment.add_namespace\n\n/-- Mark a namespace as open -/\nunsafe axiom mark_namespace_as_open : environment \u2192 Name \u2192 environment\n#align environment.mark_namespace_as_open environment.mark_namespace_as_open\n\n/-- Modify the environment as if `open %%name` had been parsed -/\nunsafe axiom execute_open : environment \u2192 Name \u2192 environment\n#align environment.execute_open environment.execute_open\n\n/-- Retrieve all registered namespaces -/\nunsafe axiom get_namespaces : environment \u2192 List Name\n#align environment.get_namespaces environment.get_namespaces\n\n/-- Return tt iff the given name is a namespace -/\nunsafe axiom is_namespace : environment \u2192 Name \u2192 Bool\n#align environment.is_namespace environment.is_namespace\n\n/-- Add a new inductive datatype to the environment\n   name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/\nunsafe axiom add_inductive (env : environment) (n : Name) (levels : List Name) (num_params : Nat)\n    (type : expr) (intros : List (Name \u00d7 expr)) (is_meta : Bool) : exceptional environment\n#align environment.add_inductive environment.add_inductive\n\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-/\nunsafe axiom add_ginductive (env : environment) (opt : options) (levels : List Name)\n    (params : List expr) (inds : List ((Name \u00d7 expr) \u00d7 List intro_rule)) (is_meta : Bool) :\n    exceptional environment\n#align environment.add_ginductive environment.add_ginductive\n\n/-- Return tt iff the given name is an inductive datatype -/\nunsafe axiom is_inductive : environment \u2192 Name \u2192 Bool\n#align environment.is_inductive environment.is_inductive\n\n/-- Return tt iff the given name is a constructor -/\nunsafe axiom is_constructor : environment \u2192 Name \u2192 Bool\n#align environment.is_constructor environment.is_constructor\n\n/-- Return tt iff the given name is a recursor -/\nunsafe axiom is_recursor : environment \u2192 Name \u2192 Bool\n#align environment.is_recursor environment.is_recursor\n\n/-- Return tt iff the given name is a recursive inductive datatype -/\nunsafe axiom is_recursive : environment \u2192 Name \u2192 Bool\n#align environment.is_recursive environment.is_recursive\n\n/-- Return the name of the inductive datatype of the given constructor. -/\nunsafe axiom inductive_type_of : environment \u2192 Name \u2192 Option Name\n#align environment.inductive_type_of environment.inductive_type_of\n\n/-- Return the constructors of the inductive datatype with the given name -/\nunsafe axiom constructors_of : environment \u2192 Name \u2192 List Name\n#align environment.constructors_of environment.constructors_of\n\n/-- Return the recursor of the given inductive datatype -/\nunsafe axiom recursor_of : environment \u2192 Name \u2192 Option Name\n#align environment.recursor_of environment.recursor_of\n\n/-- Return the number of parameters of the inductive datatype -/\nunsafe axiom inductive_num_params : environment \u2192 Name \u2192 Nat\n#align environment.inductive_num_params environment.inductive_num_params\n\n/-- Return the number of indices of the inductive datatype -/\nunsafe axiom inductive_num_indices : environment \u2192 Name \u2192 Nat\n#align environment.inductive_num_indices environment.inductive_num_indices\n\n/-- Return tt iff the inductive datatype recursor supports dependent elimination -/\nunsafe axiom inductive_dep_elim : environment \u2192 Name \u2192 Bool\n#align environment.inductive_dep_elim environment.inductive_dep_elim\n\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 -/\nunsafe axiom is_ginductive : environment \u2192 Name \u2192 Bool\n#align environment.is_ginductive environment.is_ginductive\n\n/-- See the docstring for `projection_info`. -/\nunsafe axiom is_projection : environment \u2192 Name \u2192 Option ProjectionInfo\n#align environment.is_projection environment.is_projection\n\n/-- Fold over declarations in the environment. -/\nunsafe axiom fold {\u03b1 : Type} : environment \u2192 \u03b1 \u2192 (declaration \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1\n#align environment.fold environment.fold\n\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. -/\nunsafe axiom relation_info : environment \u2192 Name \u2192 Option (Nat \u00d7 Nat \u00d7 Nat)\n#align environment.relation_info environment.relation_info\n\n/-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/\nunsafe axiom refl_for : environment \u2192 Name \u2192 Option Name\n#align environment.refl_for environment.refl_for\n\n/-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/\nunsafe axiom symm_for : environment \u2192 Name \u2192 Option Name\n#align environment.symm_for environment.symm_for\n\n/-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/\nunsafe axiom trans_for : environment \u2192 Name \u2192 Option Name\n#align environment.trans_for environment.trans_for\n\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. -/\nunsafe axiom decl_olean : environment \u2192 Name \u2192 Option String\n#align environment.decl_olean environment.decl_olean\n\n/-- `decl_pos env d` returns the source location of d if available. -/\nunsafe axiom decl_pos : environment \u2192 Name \u2192 Option Pos\n#align environment.decl_pos environment.decl_pos\n\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`. -/\nunsafe axiom decl_noncomputable_reason : environment \u2192 Name \u2192 Option Name\n#align environment.decl_noncomputable_reason environment.decl_noncomputable_reason\n\n/-- Return the fields of the structure with the given name, or `none` if it is not a structure -/\nunsafe axiom structure_fields : environment \u2192 Name \u2192 Option (List Name)\n#align environment.structure_fields environment.structure_fields\n\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] -/\nunsafe axiom get_class_attribute_symbols : environment \u2192 Name \u2192 name_set\n#align environment.get_class_attribute_symbols environment.get_class_attribute_symbols\n\n/--\nThe fingerprint of the environment is a hash formed from all of the declarations in the environment. -/\nunsafe axiom fingerprint : environment \u2192 Nat\n#align environment.fingerprint environment.fingerprint\n\n/-- Gets the equation lemmas for the declaration `n`. -/\nunsafe axiom get_eqn_lemmas_for (env : environment) (n : Name) : List Name\n#align environment.get_eqn_lemmas_for environment.get_eqn_lemmas_for\n\n/-- Gets the equation lemmas for the declaration `n`, including lemmas for match statements, etc. -/\nunsafe axiom get_ext_eqn_lemmas_for (env : environment) (n : Name) : List Name\n#align environment.get_ext_eqn_lemmas_for environment.get_ext_eqn_lemmas_for\n\n/-- Adds 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-/\nunsafe axiom add_eqn_lemma (env : environment) (n : Name) : environment\n#align environment.add_eqn_lemma environment.add_eqn_lemma\n\nopen Expr\n\nunsafe axiom unfold_untrusted_macros : environment \u2192 expr \u2192 expr\n#align environment.unfold_untrusted_macros environment.unfold_untrusted_macros\n\nunsafe axiom unfold_all_macros : environment \u2192 expr \u2192 expr\n#align environment.unfold_all_macros environment.unfold_all_macros\n\nunsafe def is_constructor_app (env : environment) (e : expr) : Bool :=\n  is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e))\n#align environment.is_constructor_app environment.is_constructor_app\n\nunsafe def is_refl_app (env : environment) (e : expr) : Option (Name \u00d7 expr \u00d7 expr) :=\n  match refl_for env (const_name (get_app_fn e)) with\n  | some n => if get_app_num_args e \u2265 2 then some (n, app_arg (app_fn e), app_arg e) else none\n  | none => none\n#align environment.is_refl_app environment.is_refl_app\n\n/-- Return true if 'n' has been declared in the current file -/\nunsafe def in_current_file (env : environment) (n : Name) : Bool :=\n  (env.decl_olean n).isNone && env.contains n &&\n    n \u2209 [`` Quot, `` Quot.mk, `` Quot.lift, `` Quot.ind]\n#align environment.in_current_file environment.in_current_file\n\nunsafe def is_definition (env : environment) (n : Name) : Bool :=\n  match env.get n with\n  | exceptional.success (declaration.defn _ _ _ _ _ _) => true\n  | _ => false\n#align environment.is_definition environment.is_definition\n\nend Environment\n\nunsafe instance : Repr environment :=\n  \u27e8fun e => \"[environment]\"\u27e9\n\nunsafe instance : Inhabited environment :=\n  \u27e8environment.mk_std 0\u27e9\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/Environment.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755162, "lm_q2_score": 0.05834583938364054, "lm_q1q2_score": 0.025097307259436652}}
{"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-/\nprelude\nimport Init.Core\nimport Init.Control.Basic\nimport Init.Coe\n\nnamespace Option\n\ndef toMonad [Monad m] [Alternative m] : Option \u03b1 \u2192 m \u03b1\n  | none     => failure\n  | some a   => pure a\n\n@[inline] def toBool : Option \u03b1 \u2192 Bool\n  | some _ => true\n  | none   => false\n\n@[inline] def isSome : Option \u03b1 \u2192 Bool\n  | some _ => true\n  | none   => false\n\n@[inline] def isNone : Option \u03b1 \u2192 Bool\n  | some _ => false\n  | none   => true\n\n@[inline] def isEqSome [BEq \u03b1] : Option \u03b1 \u2192 \u03b1 \u2192 Bool\n  | some a, b => a == b\n  | none,   _ => false\n\n@[inline] protected def bind : Option \u03b1 \u2192 (\u03b1 \u2192 Option \u03b2) \u2192 Option \u03b2\n  | none,   b => none\n  | some a, b => b a\n\n@[inline] protected def map (f : \u03b1 \u2192 \u03b2) (o : Option \u03b1) : Option \u03b2 :=\n  Option.bind o (some \u2218 f)\n\ntheorem map_id : (Option.map id : Option \u03b1 \u2192 Option \u03b1) = id :=\n  funext (fun o => match o with | none => rfl | some x => rfl)\n\ninstance : Functor Option where\n  map := Option.map\n\n@[inline] protected def filter (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Option \u03b1\n  | some a => if p a then some a else none\n  | none   => none\n\n@[inline] protected def all (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Bool\n  | some a => p a\n  | none   => true\n\n@[inline] protected def any (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Bool\n  | some a => p a\n  | none   => false\n\n@[macroInline] protected def orElse : Option \u03b1 \u2192 (Unit \u2192 Option \u03b1) \u2192 Option \u03b1\n  | some a, _ => some a\n  | none,   b => b ()\n\ninstance : OrElse (Option \u03b1) where\n  orElse := Option.orElse\n\n@[inline] protected def lt (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Option \u03b1 \u2192 Option \u03b1 \u2192 Prop\n  | none, some x     => True\n  | some x,   some y => r x y\n  | _, _             => False\n\ninstance (r : \u03b1 \u2192 \u03b1 \u2192 Prop) [s : DecidableRel r] : DecidableRel (Option.lt r)\n  | none,   some y => isTrue  trivial\n  | some x, some y => s x y\n  | some x, none   => isFalse not_false\n  | none,   none   => isFalse not_false\n\nend Option\n\nderiving instance DecidableEq for Option\nderiving instance BEq for Option\n\ninstance [LT \u03b1] : LT (Option \u03b1) where\n  lt := Option.lt (\u00b7 < \u00b7)\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/Data/Option/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.05582313681494604, "lm_q1q2_score": 0.02508650651735531}}
{"text": "example (P Q R : Type) : (P \u2192 (Q \u2192 R)) \u2192 ((P \u2192 Q) \u2192 (P \u2192 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 \u2192 (Q \u2192 R)) \u2192 ((P \u2192 Q) \u2192 (P \u2192 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u2124 \u2115`\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 {\u03b1} [has_to_tactic_format \u03b1] (msg : string) (a : \u03b1) : tactic unit :=\nwhen_tracing `norm_cast $ do\na \u2190 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 \u2192 string\n| elim   := \"elim\"\n| move   := \"move\"\n| squash := \"squash\"\n\ninstance : has_to_string label := \u27e8label.to_string\u27e9\ninstance : has_repr label := \u27e8label.to_string\u27e9\nmeta instance : has_to_format label := \u27e8\u03bb l, l.to_string\u27e9\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 \u2192 \u2115\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 \u2192 tactic \u2115\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 \u2190 mk_local' n bi t,\n  count_coes $ e.instantiate_var l\n| e := do\n  as \u2190 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 \u2115 := do\nncoes \u2190 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) \u2190 open_pis ty,\n(lhs, rhs) \u2190 match ty with\n  | `(%%lhs = %%rhs) := pure (lhs, rhs)\n  | `(%%lhs \u2194 %%rhs) := pure (lhs, rhs)\n  | _ := fail \"norm_cast: lemma must be = or \u2194\"\n  end,\nlhs_coes \u2190 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 \u2190 count_internal_coes lhs,\nlet rhs_head_coes := count_head_coes rhs,\nrhs_internal_coes \u2190 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 \u2260 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 := \u27e8empty_cache\u27e9\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 \u2190 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 \u2190 cache.up.add e tt,\n  new_down \u2190 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 \u2190 cache.squash.add e,\n  new_down \u2190 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 \u2190 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 \u2190 mk_const decl,\n  param \u2190 get_label_param attr decl,\n  l \u2190 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 \u2265, > and \u2260 operators\nprivate lemma ge_from_le {\u03b1} [has_le \u03b1] : \u2200 (x y : \u03b1), x \u2265 y \u2194 y \u2264 x := \u03bb _ _, iff.rfl\nprivate lemma gt_from_lt {\u03b1} [has_lt \u03b1] : \u2200 (x y : \u03b1), x > y \u2194 y < x := \u03bb _ _, iff.rfl\nprivate lemma ne_from_not_eq {\u03b1} : \u2200 (x y : \u03b1), x \u2260 y \u2194 \u00ac(x = y) := \u03bb _ _, 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 \u2190 names.mfoldr (\u03bb name cache, add_lemma (attr ()) cache name) empty_cache,\n\n--some special lemmas to handle binary relations\nlet up := cache.up,\nup \u2190 up.add_simp ``ge_from_le,\nup \u2190 up.add_simp ``gt_from_lt,\nup \u2190 up.add_simp ``ne_from_not_eq,\n\nlet down := cache.down,\ndown \u2190 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 \u2190 (label.of_string \u2218 to_string) <$> ident, return l)\n      <|> return none,\n  after_set := some (\u03bb decl prio persistent, do\n    param \u2190 get_label_param norm_cast_attr decl,\n    match param with\n    | some l :=\n      when (l \u2260 elim) $ simp_attr.push_cast.set decl () tt prio\n    | none := do\n      e \u2190 mk_const decl,\n      ty \u2190 infer_type e,\n      l \u2190 classify_type ty,\n      norm_cast_attr.set decl l persistent prio\n    end),\n  before_unset := some $ \u03bb _ _, 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 \u2190 mk_const decl,\n  ty \u2190 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 \u2190 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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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', _) \u2190 simplify s [] a {fail_if_unchanged := ff},\n(b', b_b', _) \u2190 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 \u2190 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 \u2190 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 (\u2191(x : \u03b1) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nis rewritten to:            op (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nwhen (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) = (\u2191(x : \u03b1) : \u03b3) can be proven with a squash lemma\n-/\nmeta def splitting_procedure : expr \u2192 tactic (expr \u00d7 expr)\n| (app (app op x) y) :=\n(do\n  `(@coe %%\u03b1 %%\u03b4 %%coe1 %%xx) \u2190 return x,\n  `(@coe %%\u03b2 %%\u03b3 %%coe2 %%yy) \u2190 return y,\n  success_if_fail $ is_def_eq \u03b1 \u03b2,\n  is_def_eq \u03b4 \u03b3,\n\n  (do\n    coe3 \u2190 mk_app `has_lift_t [\u03b1, \u03b2] >>= mk_instance_fast,\n    new_x \u2190 to_expr ``(@coe %%\u03b2 %%\u03b4 %%coe2 (@coe %%\u03b1 %%\u03b2 %%coe3 %%xx)),\n    let new_e := app (app op new_x) y,\n    eq_x \u2190 prove_eq_using_down x new_x,\n    pr \u2190 mk_congr_arg op eq_x,\n    pr \u2190 mk_congr_fun pr y,\n    return (new_e, pr)\n  ) <|> (do\n    coe3 \u2190 mk_app `has_lift_t [\u03b2, \u03b1] >>= mk_instance_fast,\n    new_y \u2190 to_expr ``(@coe %%\u03b1 %%\u03b4 %%coe1 (@coe %%\u03b2 %%\u03b1 %%coe3 %%yy)),\n    let new_e := app (app op x) new_y,\n    eq_y \u2190 prove_eq_using_down y new_y,\n    pr \u2190 mk_congr_arg (app op x) eq_y,\n    return (new_e, pr)\n  )\n) <|> (do\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return x,\n  `(@has_one.one %%\u03b2 %%h1) \u2190 return y,\n  h2 \u2190 to_expr ``(has_one %%\u03b1) >>= mk_instance_fast,\n  new_y \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_one.one %%\u03b1 %%h2)),\n  eq_y \u2190 prove_eq_using_down y new_y,\n  let new_e := app (app op x) new_y,\n  pr \u2190 mk_congr_arg (app op x) eq_y,\n  return (new_e, pr)\n ) <|> (do\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return x,\n  `(@has_zero.zero %%\u03b2 %%h1) \u2190 return y,\n  h2 \u2190 to_expr ``(has_zero %%\u03b1) >>= mk_instance_fast,\n  new_y \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_zero.zero %%\u03b1 %%h2)),\n  eq_y \u2190 prove_eq_using_down y new_y,\n  let new_e := app (app op x) new_y,\n  pr \u2190 mk_congr_arg (app op x) eq_y,\n  return (new_e, pr)\n) <|> (do\n  `(@has_one.one %%\u03b2 %%h1) \u2190 return x,\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return y,\n  h1 \u2190 to_expr ``(has_one %%\u03b1) >>= mk_instance_fast,\n  new_x \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_one.one %%\u03b1 %%h1)),\n  eq_x \u2190 prove_eq_using_down x new_x,\n  let new_e := app (app op new_x) y,\n  pr \u2190 mk_congr_arg (lam `x binder_info.default \u03b2 (app (app op (var 0)) y)) eq_x,\n  return (new_e, pr)\n) <|> (do\n  `(@has_zero.zero %%\u03b2 %%h1) \u2190 return x,\n  `(@coe %%\u03b1 %%\u03b2 %%coe1 %%xx) \u2190 return y,\n  h1 \u2190 to_expr ``(has_zero %%\u03b1) >>= mk_instance_fast,\n  new_x \u2190 to_expr ``(@coe %%\u03b1 %%\u03b2 %%coe1 (@has_zero.zero %%\u03b1 %%h1)),\n  eq_x \u2190 prove_eq_using_down x new_x,\n  let new_e := app (app op new_x) y,\n  pr \u2190 mk_congr_arg (lam `x binder_info.default \u03b2 (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 \u00d7 expr) :=\n(do\n  r \u2190 mcond (is_prop e) (return `iff) (return `eq),\n  (new_e, pr) \u2190 s.rewrite e prove r,\n  pr \u2190 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 : \u03b1)` to `((n : \u2115) : \u03b1)` where `n` is a numeral and `\u03b1 \u2260 \u2115`.\nReturns a pair of the new expression and proof that they are equal.\n-/\nmeta def numeral_to_coe (e : expr) : tactic (expr \u00d7 expr) :=\ndo\n  \u03b1 \u2190 infer_type e,\n  success_if_fail $ is_def_eq \u03b1 `(\u2115),\n  n \u2190 e.to_nat,\n  h1 \u2190 mk_app `has_lift_t [`(\u2115), \u03b1] >>= mk_instance_fast,\n  let new_e : expr := reflect n,\n  new_e \u2190 to_expr ``(@coe \u2115 %%\u03b1 %%h1 %%new_e),\n  pr \u2190 prove_eq_using_down e new_e,\n  return (new_e, pr)\n\n/--\nIf possible, rewrite `((n : \u2115) : \u03b1)` to `(n : \u03b1)` 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 \u00d7 expr) :=\ndo\n  `(@coe \u2115 %%\u03b1 %%h1 %%e') \u2190 return e,\n  n \u2190 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 \u2190 expr.of_nat \u03b1 n,\n  pr \u2190 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' {\u03b1} (a : \u03b1) (pre : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr))\n  (e : expr) (cfg : simp_config := {}) : tactic (\u03b1 \u00d7 expr \u00d7 expr) :=\next_simplify_core a cfg simp_lemmas.mk (\u03bb _, failed)\n  (\u03bb a _ _ _ e, do\n    (new_a, new_e, pr) \u2190 pre a e,\n    guard (\u00ac new_e =\u2090 e),\n    return (new_a, new_e, some pr, ff))\n  (\u03bb _ _ _ _ _, failed)\n  `eq e\n\n/--\nThe core simplification routine of `norm_cast`.\n-/\nmeta def derive (e : expr) : tactic (expr \u00d7 expr) :=\ndo\n  cache \u2190 norm_cast_attr.get_cache,\n  e \u2190 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) \u2190 simplify_top_down' () (\u03bb _ 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) \u2190 simplify_bottom_up () (\u03bb _ 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, _) \u2190 simplify cache.squash [] e2 cfg,\n  trace_norm_cast \"after squashing: \" e3,\n\n  -- step 4: post-processing of numerals\n  ((), e4, pr4) \u2190 simplify_top_down' () (\u03bb _ 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 (\u00ac new_e =\u2090 e),\n  pr \u2190 mk_eq_trans pr1 pr2,\n  pr \u2190 mk_eq_trans pr pr3,\n  pr \u2190 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 \u00d7 expr) :=\ndo (s, _) \u2190 mk_simp_set tt [`push_cast] extra_lems,\n   (e, prf, _) \u2190 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 \u2190 get_local lc,\n  replace_at derive [e] include_goal,\n  get_local lc\n| e := do\n  t \u2190 infer_type e,\n  e \u2190 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 \u2190 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 \u00d7 expr)) :=\ndecorate_error \"apply_mod_cast failed:\" $ do\n  new_e \u2190 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 \u2190 local_context,\n  ctx.mfirst (\u03bb 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 \u2190 loc.get_locals,\n  tt \u2190 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 (\u00ac 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 \u2190 loc.get_locals,\n  monad.mapm' (\u03bb r : rw_rule, do\n    save_info r.pos,\n    replace_at derive ns loc.include_goal,\n    rw \u27e8[r], none\u27e9 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 \u2190 i_to_expr e <|> do\n  { ty \u2190 target,\n    e \u2190 i_to_expr_strict ``(%%e : %%ty),\n    pty \u2190 pp ty, ptgt \u2190 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 \u2190 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 {\u03b1 \u03b2} [has_lift_t \u03b1 \u03b2]\n  {c : Prop} [decidable c] {a b : \u03b1} :\n  \u2191(ite c a b) = ite c (\u2191a : \u03b2) (\u2191b : \u03b2) :=\nby by_cases h : c; simp [h]\n\n@[norm_cast] lemma dite_cast {\u03b1 \u03b2} [has_lift_t \u03b1 \u03b2]\n  {c : Prop} [decidable c] {a : c \u2192 \u03b1} {b : \u00ac c \u2192 \u03b1} :\n  \u2191(dite c a b) = dite c (\u03bb h, (\u2191(a h) : \u03b2)) (\u03bb h, (\u2191(b h) : \u03b2)) :=\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 : \u2124\nh : \u2191a + \u2191b < (10 : \u211a)\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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 `\u2191`, `\u21d1` and `\u21a5`, 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 : \u2115} : (\u2191m : \u2124) = \u2191n \u2194 m = n\n\n@[norm_cast] theorem coe_int_denom (n : \u2124) : (n : \u211a).denom = 1\n\n@[norm_cast] theorem cast_id : \u2200 n : \u211a, \u2191n = n\n\n@[norm_cast] theorem coe_nat_add (m n : \u2115) : (\u2191(m + n) : \u2124) = \u2191m + \u2191n\n\n@[norm_cast] theorem cast_sub [add_group \u03b1] [has_one \u03b1] {m n} (h : m \u2264 n) :\n  ((n - m : \u2115) : \u03b1) = n - m\n\n@[norm_cast] theorem coe_nat_bit0 (n : \u2115) : (\u2191(bit0 n) : \u2124) = bit0 \u2191n\n\n@[norm_cast] theorem cast_coe_nat (n : \u2115) : ((n : \u2124) : \u03b1) = n\n\n@[norm_cast] theorem cast_one : ((1 : \u211a) : \u03b1) = 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 : \u2115) : (n : \u2102).re = n :=\nby rw [\u2190 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u27f6 U \u2286 Y`, and the sheaf map `Y(V) \u27f6 f _* X(V)` is an iso for each `V \u2286 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 \u27f6 Y) (g : Y \u27f6 Z)\n\nlemma is_open_immersion_iff_stalk {f : X \u27f6 Y} :\n  is_open_immersion f \u2194\n    open_embedding f.1.base \u2227 \u2200 x, is_iso (PresheafedSpace.stalk_map f.1 x) :=\nbegin\n  split,\n  { intro h, exactI \u27e8h.1, infer_instance\u27e9 },\n  { rintro \u27e8h\u2081, h\u2082\u27e9, exactI is_open_immersion.of_stalk_iso f h\u2081 }\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\u2081 h\u2082, 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 \ud835\udcb0 H,\n    rw is_open_immersion_iff_stalk,\n    split,\n    { apply (open_embedding_iff_open_embedding_of_supr_eq_top\n        \ud835\udcb0.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 (\ud835\udcb0.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 ((\ud835\udcb0.map $ \ud835\udcb0.f $ f.1 x).opens_range)\n        \u27e8x, \ud835\udcb0.covers _\u27e9),\n      dsimp only [arrow.mk_hom] at this,\n      rw this,\n      haveI : is_open_immersion (f \u2223_ (\ud835\udcb0.map $ \ud835\udcb0.f $ f.1 x).opens_range) :=\n        (is_open_immersion_respects_iso.arrow_iso_iff\n          (morphism_restrict_opens_range f (\ud835\udcb0.map _))).mpr (H _),\n      apply_instance } }\nend\n\nlemma is_open_immersion.open_cover_tfae {X Y : Scheme.{u}} (f : X \u27f6 Y) :\n  tfae [is_open_immersion f,\n    \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} Y), \u2200 (i : \ud835\udcb0.J),\n      is_open_immersion (pullback.snd : (\ud835\udcb0.pullback_cover f).obj i \u27f6 \ud835\udcb0.obj i),\n    \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} Y) (i : \ud835\udcb0.J),\n      is_open_immersion (pullback.snd : (\ud835\udcb0.pullback_cover f).obj i \u27f6 \ud835\udcb0.obj i),\n    \u2200 (U : opens Y.carrier), is_open_immersion (f \u2223_ U),\n    \u2200 {U : Scheme} (g : U \u27f6 Y) [is_open_immersion g],\n      is_open_immersion (pullback.snd : pullback f g \u27f6 _),\n    \u2203 {\u03b9 : Type u} (U : \u03b9 \u2192 opens Y.carrier) (hU : supr U = \u22a4),\n      \u2200 i, is_open_immersion (f \u2223_ (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  (\ud835\udcb0 : Scheme.open_cover.{u} Y) (f : X \u27f6 Y) :\n  is_open_immersion f \u2194 \u2200 i, is_open_immersion (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _) :=\nis_open_immersion_is_local_at_target.open_cover_iff f \ud835\udcb0\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 \u03b1 n)\n(y : Vector \u03b1 20)\n```\nthe term `x = y` is correct. However, its closure using lambda abstractions\nis not.\n```lean\nfun (n : Nat) (x : Vector \u03b1 n) (y : Vector \u03b1 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 \u03b1 n) (y : Vector \u03b1 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 \u2192 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 } := \u27e820, rfl\u27e9; y.1 + n + f x, z + 10)\n```\nwe obtain\n```lean\ndef aux (x : Nat) (f : Nat \u2192 Nat) (z : Nat) : Nat\u00d7Nat :=\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 \u2192 ClosureM Level) (u : Level) : ClosureM Level := do\n  if !u.hasMVar && !u.hasParam then\n    pure u\n  else\n    let s \u2190 get\n    match s.visitedLevel.find? u with\n    | some v => pure v\n    | none   => do\n      let v \u2190 f u\n      modify fun s => { s with visitedLevel := s.visitedLevel.insert u v }\n      pure v\n\n@[inline] def visitExpr (f : Expr \u2192 ClosureM Expr) (e : Expr) : ClosureM Expr := do\n  if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then\n    pure e\n  else\n    let s \u2190 get\n    match s.visitedExpr.find? e with\n    | some r => pure r\n    | none   =>\n      let r \u2190 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 \u2190 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 \u2192 ClosureM Level\n  | u@(Level.succ v _)      => return u.updateSucc! (\u2190 visitLevel collectLevelAux v)\n  | u@(Level.max v w _)     => return u.updateMax! (\u2190 visitLevel collectLevelAux v) (\u2190 visitLevel collectLevelAux w)\n  | u@(Level.imax v w _)    => return u.updateIMax! (\u2190 visitLevel collectLevelAux v) (\u2190 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 \u2190 instantiateLevelMVars u\n  visitLevel collectLevelAux u\n\ndef preprocess (e : Expr) : ClosureM Expr := do\n  let e \u2190 instantiateMVars e\n  let ctx \u2190 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 \u2190 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! (\u2190 collect s)\n  | Expr.forallE _ d b _ => return e.updateForallE! (\u2190 collect d) (\u2190 collect b)\n  | Expr.lam _ d b _     => return e.updateLambdaE! (\u2190 collect d) (\u2190 collect b)\n  | Expr.letE _ t v b _  => return e.updateLet! (\u2190 collect t) (\u2190 collect v) (\u2190 collect b)\n  | Expr.app f a _       => return e.updateApp! (\u2190 collect f) (\u2190 collect a)\n  | Expr.mdata _ b _     => return e.updateMData! (\u2190 collect b)\n  | Expr.sort u _        => return e.updateSort! (\u2190 collectLevel u)\n  | Expr.const c us _    => return e.updateConst! (\u2190 us.mapM collectLevel)\n  | Expr.mvar mvarId _   =>\n    let mvarDecl \u2190 getMVarDecl mvarId\n    let type \u2190 preprocess mvarDecl.type\n    let type \u2190 collect type\n    let newFVarId \u2190 mkFreshFVarId\n    let userName \u2190 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 (\u2190 read).zeta, (\u2190 getLocalDecl fvarId).value? with\n    | true, some value => collect (\u2190 preprocess value)\n    | _,    _          =>\n      let newFVarId \u2190 mkFreshFVarId\n      pushToProcess \u27e8fvarId, newFVarId\u27e9\n      return mkFVar newFVarId\n  | e => pure e\n\ndef collectExpr (e : Expr) : ClosureM Expr := do\n  let e \u2190 preprocess e\n  visitExpr collectExprAux e\n\npartial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement)\n    : ToProcessElement \u00d7 Array ToProcessElement :=\n  if h : i < toProcess.size then\n    let elem' := toProcess.get \u27e8i, h\u27e9\n    if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then\n      pickNextToProcessAux lctx (i+1) (toProcess.set \u27e8i, h\u27e9 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 \u2190 getLCtx\n  let s \u2190 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 \u2190 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 (\u2190 pickNextToProcess?) with\n  | none => pure ()\n  | some \u27e8fvarId, newFVarId\u27e9 =>\n    let localDecl \u2190 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 \u2190 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 \u2190 collectExpr type\n        let val  \u2190 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 \u00d7 Expr) := do\n  resetZetaFVarIds\n  withTrackingZeta do\n    let type  \u2190 collectExpr type\n    let value \u2190 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) \u2190 ((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 \u2190 Closure.mkValueTypeClosure type value zeta\n  let env \u2190 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 \u2190 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) (\u03b1 : Type) := k \u2192 \u03b1\n\n\n-- | Extend the environment with a new variable.\n@[simp]\ndef Env.extend [DecidableEq k] (name : k) (v : \u03b1) (e: Env k \u03b1) : Env k \u03b1 :=\n  fun name' => if name = name' then v else e name'\n\n@[simp]\ndef Env.empty [Inhabited \u03b1] : Env k \u03b1 :=\n  fun _ => default\n\n@[simp]\ndef Env.map (f : \u03b1 \u2192 \u03b2) (e : Env k \u03b1) : Env k \u03b2 :=\n  fun name => f (e name)\n\nnotation \"\u2205\" => Env.empty\nnotation e \"[\" name \"\u21a6\" v \"]\" => Env.extend name v e\n\nabbrev VarEnv (\u03b1 : Type) := Env VarName \u03b1\nabbrev RgnEnv (\u03b1 : Type) := Env RgnName \u03b1\n\n-- The input semantics given by the user.\nclass UserSemantics (opcode : Type)  where\n  -- | Arguments given as (<args>, <rgn1>, ... <rgnN>)\n  -- | Consider not allowing users to not be access all of 'Env'.\n  opcodeEval (op: opcode) (vals : Int \u00d7 Int) (rgns : (Int \u00d7 Int \u2192 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 \u2192 Type where\n| assign (ret : VarName) (op : opcode)\n  (args : VarName \u00d7 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 \u00d7 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 \u2192 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) \u2192 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) := \u27e8Ops.ofList\u27e9\n\n@[simp, reducible]\ndef ASTKind.eval : ASTKind \u2192 Type\n| .O => Int\n| .Os => Int\n| .R => (Int \u00d7 Int \u2192 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 \u00d7 Int \u2192 Int)): AST opcode astk \u2192 astk.eval \u00d7 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 \u2192 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 \u00d7 Int \u2192 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 \u2192 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 \u2192 (astk.toCTree opcode) \u00d7 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 \u00d7 Int \u2192 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 \u00d7 Int \u2192 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 \u00d7 Int \u2192 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 \u00d7 Int \u2192 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 \u2192 Type\n| .O => Int\n| .R => Int \u00d7 Int \u2192 Int\n\n-- Note: is this literally \"just\" staging the partial evaluation against the environment?\ndef Ctree.eval [UserSemantics opcode] : Ctree opcode treek \u2192 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 \u2192 Opcode\nderiving Inhabited\n\ndef loopSemantics (n : Nat) (f : Int \u2192 Int) (v : Int) : Int :=\n  match n with\n  | 0 => v -- inline id\n  | n + 1 => f (loopSemantics n f v) -- inline \u2218\n\n@[simp]\ninstance :  UserSemantics Opcode  where\n  opcodeEval\n  | .not, \u27e8a, _\u27e9, _ => if a = 0 then 1 else 0\n  | .mul, \u27e8a, b\u27e9, _ => a * b\n  | .add, \u27e8a, b\u27e9, _ => a + b\n  | .const i, \u27e8_a, _b\u27e9, _ => i\n  | .run, \u27e8v, w\u27e9, r => r \u27e8v, w\u27e9\n  | .runnot, \u27e8v, w\u27e9, r => r \u27e8if v = 0 then 1 else 0, w\u27e9 -- execute: 'r(not v, w)'\n  | .loop, \u27e8n, init\u27e9, r => loopSemantics n.toNat (fun i => r \u27e8i, 0\u27e9) 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 \u27e8.x0, .x1\u27e9 $ Ops.ofList [\n      .assign .x2 .add (.x0, .x1) .rgn0 -- x2 := x0 + x1\n      ]\n  let q : AST Opcode .R :=\n    AST.rgn \u27e8.x0, .x1\u27e9 $ Ops.ofList [\n      .assign .x2 .run (.x0, .x1) (AST.rgn \u27e8.x5, .x6\u27e9 (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 \u27e8.x0, .x1\u27e9 $ Ops.ofList [\n      .assign .y1 .run \u27e8.x0, .x1\u27e9 (.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": "namespace tactic.interactive\n  open expr tactic\n\n  private meta def congr_aux : expr \u2192 expr \u2192 tactic unit\n  | (app f\u2081 a\u2081) (app f\u2082 a\u2082) :=\n  do apply ``(congr),\n     swap, reflexivity <|> swap,\n     congr_aux f\u2081 f\u2082\n  | _ _ := try reflexivity\n\n  /-- Given a goal of form `f a1 ... an = f' a1' ... an'`, this tactic breaks it down to subgoals\n      `f = f'`, `a1 = a1'`, ... Subgoals provable by reflexivity are dispensed automatically. -/\n  meta def congruence : tactic unit :=\n  do ```(%%lhs = %%rhs) \u2190 target | fail \"goal is not an equality\",\n     congr_aux lhs rhs\n\n  /-- Given a goal that equates two structure values, this tactic breaks it down to subgoals equating each\n      pair of fields. -/\n  meta def congr_struct : tactic unit :=\n  do ```(%%lhs = %%rhs) \u2190 target | fail \"goal is not an equality\",\n     ty \u2190 infer_type lhs,\n     [ctor] \u2190 get_constructors_for ty | fail \"equated type is not a structure\",\n     tactic.cases lhs,\n     tactic.cases rhs,\n     congruence\nend tactic.interactive\n\nstructure X := ( x : unit ) ( y :  unit )\n\nlemma test1 ( a b : X ) : a = b :=\nbegin\n  congr_struct,\n    -- x y x_1 y_1 : \u2115\n    -- \u22a2 x = x_1\n\n    -- x y x_1 y_1 : \u2115\n    -- \u22a2 y = y_1\n  {\n      induction x,\n    induction x_1,\n    reflexivity\n  },\n  {\n    induction y,\n    induction y_1,\n    reflexivity\n  }\n  -- Great!\nend\n\ndef f ( a : X ) : X := { x := a.y, y := a.x }\n\nlemma test2 ( a : X ) : a = f (f a) :=\nbegin\n  congr_struct,\n  -- breaks because cases.lhs messes up the right hand side!\nend\n\nstructure Y := ( x : nat ) ( y : nat )\ndef g ( x : nat ) : Y := { x := x, y := x }\ndef h ( a : Y ) : Y := { x := a.y, y := a.x }\n\nlemma test3 ( x : nat ) : g 0 = h ( g 0 ) :=\nbegin\n  congr_struct,\n  \nend", "meta": {"author": "semorrison", "repo": "proof", "sha": "5ee398aa239a379a431190edbb6022b1a0aa2c70", "save_path": "github-repos/lean/semorrison-proof", "path": "github-repos/lean/semorrison-proof/proof-5ee398aa239a379a431190edbb6022b1a0aa2c70/lean/20170425-congruence.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.05033063651478413, "lm_q1q2_score": 0.0247721421558526}}
{"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 \u2192 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' \u2192 weekday'\n\n-- open weekday'\n-- meta instance has_reflect_weekday' : has_reflect weekday'\n-- | weekday'.monday                  := `(monday)\n-- | (weekday'.another_day x)         := `(\u03bb 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}} : \u03a0{n : \u2115}, 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     : \u2115 \u2192 preterm_aux\n-- | func    : \u2200 k : \u2115, L.functions k \u2192 preterm_aux\n-- | app     : preterm_aux \u2192 preterm_aux \u2192 preterm_aux\n\n-- def to_aux {L : Language.{u}} : \u2200 {l : \u2115},  preterm L l \u2192 preterm_aux L\n-- | 0 (var n)      := preterm_aux.var _ n\n-- | k (func f)     := preterm_aux.func _ f\n-- | k (app t\u2081 t\u2082)  := preterm_aux.app (to_aux t\u2081) (to_aux t\u2082)\n\n\n-- def L_abel_plus' (t\u2081 t\u2082 : preterm L_abel 0) : preterm L_abel 0 :=\n-- @term_of_function L_abel 2 (abel_functions.plus : L_abel.functions 2) t\u2081 t\u2082\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 \u2192 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 : \u2115 \u2192 Type u\n-- | z {} : my_indexed_family 0\n-- | s : \u2200 {k}, my_indexed_family k \u2192 my_indexed_family (k+1)\n\n-- -- meta example : \u2200 {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'' : \u2115 \u2192 Type\n-- | fz {n} : dfin'' (n+1)\n-- | fs {n} : dfin'' n \u2192 dfin'' (n+1)\n\n-- inductive dfin' : \u2115 \u2192 Type u\n-- | gz {n} :  dfin' (n+1)\n-- | gs {n} :  dfin' n \u2192 dfin' (n+1)\n\n-- open dfin dfin'\n\n-- meta instance dfin.reflect : \u2200 {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 : \u2200 {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 : \u2115 \u2192 Type\n-- | pt : L_pt_functions 0\n\n-- def L_pt : Language.{0} := \u27e8L_pt_functions, \u03bb _, empty\u27e9\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 : \u2115 \u2192 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-- \u27e8L_pt_func_functions, \u03bb _, ulift empty\u27e9\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\u2081 <- tactic.mk_app ``preterm.func [`(my_foo)],\n--    e\u2082 <- tactic.mk_app ``preterm.func [`(my_pt)],\n--    tactic.mk_app ``preterm.app [e\u2081, e\u2082]\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 Minchao Wu. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Minchao Wu\n\n! This file was ported from Lean 3 source module tactic.explode_widget\n! leanprover-community/mathlib commit d13b3a4a392ea7273dfa4727dbd1892e26cfd518\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Explode\nimport Mathbin.Tactic.InteractiveExpr\n\n/-!\n# `#explode_widget` command\n\nRender a widget that displays an `#explode` proof, providing more\ninteractivity such as jumping to definitions and exploding constants\noccurring in the exploded proofs.\n-/\n\n\nopen Widget Tactic Tactic.Explode\n\nunsafe instance widget.string_to_html {\u03b1} : Coe String (html \u03b1) :=\n  \u27e8fun s => s\u27e9\n#align widget.string_to_html widget.string_to_html\n\nnamespace Tactic\n\nnamespace ExplodeWidget\n\nopen WidgetOverride.InteractiveExpression\n\nopen TaggedFormat\n\nopen Widget.Html Widget.Attr\n\n/-- Redefine some of the style attributes for better formatting. -/\nunsafe def get_block_attrs {\u03b3} : sf \u2192 tactic (sf \u00d7 List (attr \u03b3))\n  | sf.block i a => do\n    let s : attr \u03b3 :=\n      style [(\"display\", \"inline-block\"), (\"white-space\", \"pre-wrap\"), (\"vertical-align\", \"top\")]\n    let (a, rest) \u2190 get_block_attrs a\n    pure (a, s :: rest)\n  | sf.highlight c a => do\n    let (a, rest) \u2190 get_block_attrs a\n    pure (a, cn c :: rest)\n  | a => pure (a, [])\n#align tactic.explode_widget.get_block_attrs tactic.explode_widget.get_block_attrs\n\n/-- Explode button for subsequent exploding. -/\nunsafe def insert_explode {\u03b3} : expr \u2192 tactic (List (html (action \u03b3)))\n  | expr.const n _ =>\n    (do\n        pure <|\n            [h \"button\"\n                [cn \"pointer ba br3 mr1\",\n                  on_click fun _ =>\n                    action.effect <| widget.effect.insert_text (\"#explode_widget \" ++ n),\n                  attr.val \"title\" \"explode\"]\n                [\"\ud83d\udca5\"]]) <|>\n      pure []\n  | e => pure []\n#align tactic.explode_widget.insert_explode tactic.explode_widget.insert_explode\n\n/-- Render a subexpression as a list of html elements.\n-/\nunsafe def view {\u03b3} (tooltip_component : tc subexpr (action \u03b3))\n    (click_address : Option Expr.Address) (select_address : Option Expr.Address) :\n    subexpr \u2192 sf \u2192 tactic (List (html (action \u03b3)))\n  | \u27e8ce, current_address\u27e9, sf.tag_expr ea e m => do\n    let new_address := current_address ++ ea\n    let select_attrs : List (attr (action \u03b3)) :=\n      if some new_address = select_address then [className \"highlight\"] else []\n    let click_attrs : List (attr (action \u03b3)) \u2190\n      if some new_address = click_address then do\n          let content \u2190 tc.to_html tooltip_component (e, new_address)\n          let efmt : String \u2190 format.to_string <$> tactic.pp e\n          let gd_btn \u2190 goto_def_button e\n          let epld_btn \u2190 insert_explode e\n          pure\n              [tooltip <|\n                  h \"div\" []\n                    [h \"div\" [cn \"fr\"]\n                        (gd_btn ++ epld_btn ++\n                          [h \"button\"\n                              [cn \"pointer ba br3 mr1\",\n                                on_click fun _ => action.effect <| widget.effect.copy_text efmt,\n                                attr.val \"title\" \"copy expression to clipboard\"]\n                              [\"\ud83d\udccb\"],\n                            h \"button\"\n                              [cn \"pointer ba br3\", on_click fun _ => action.on_close_tooltip,\n                                attr.val \"title\" \"close\"]\n                              [\"\u00d7\"]]),\n                      content]]\n        else pure []\n    let (m, block_attrs) \u2190 get_block_attrs m\n    let as := [className \"expr-boundary\", key ea] ++ select_attrs ++ click_attrs ++ block_attrs\n    let inner \u2190 view (e, new_address) m\n    pure [h \"span\" as inner]\n  | ca, sf.compose x y => pure (\u00b7 ++ \u00b7) <*> view ca x <*> view ca y\n  | ca, sf.of_string s =>\n    pure\n      [h \"span\"\n          [on_mouse_enter fun _ => action.on_mouse_enter ca, on_click fun _ => action.on_click ca,\n            key s]\n          [html.of_string s]]\n  | ca, b@(sf.block _ _) => do\n    let (a, attrs) \u2190 get_block_attrs b\n    let inner \u2190 view ca a\n    pure [h \"span\" attrs inner]\n  | ca, b@(sf.highlight _ _) => do\n    let (a, attrs) \u2190 get_block_attrs b\n    let inner \u2190 view ca a\n    pure [h \"span\" attrs inner]\n#align tactic.explode_widget.view tactic.explode_widget.view\n\n/-- Make an interactive expression. -/\nunsafe def mk {\u03b3} (tooltip : tc subexpr \u03b3) : tc expr \u03b3 :=\n  let tooltip_comp :=\n    (component.with_should_update fun x y : tactic_state \u00d7 expr \u00d7 Expr.Address => x.2.2 \u2260 y.2.2) <|\n      component.map_action action.on_tooltip_action tooltip\n  (component.filter_map_action fun _ (a : Sum \u03b3 widget.effect) =>\n      Sum.casesOn a some fun _ => none) <|\n    (component.with_effects fun _ (a : Sum \u03b3 widget.effect) =>\n        match a with\n        | Sum.inl g => []\n        | Sum.inr s => [s]) <|\n      tc.mk_simple (action \u03b3) (Option subexpr \u00d7 Option subexpr) (fun e => pure <| (none, none))\n        (fun e \u27e8ca, sa\u27e9 act =>\n          pure <|\n            match act with\n            | action.on_mouse_enter \u27e8e, ea\u27e9 => ((ca, some (e, ea)), none)\n            | action.on_mouse_leave_all => ((ca, none), none)\n            | action.on_click \u27e8e, ea\u27e9 =>\n              if some (e, ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none)\n            | action.on_tooltip_action g => ((none, sa), some <| Sum.inl g)\n            | action.on_close_tooltip => ((none, sa), none)\n            | action.effect e => ((ca, sa), some <| Sum.inr <| e))\n        fun e \u27e8ca, sa\u27e9 => do\n        let m \u2190 sf.of_eformat <$> tactic.pp_tagged e\n        let m := m.elim_part_apps\n        let m := m.flatten\n        let m := m.tag_expr [] e\n        let v \u2190 view tooltip_comp (Prod.snd <$> ca) (Prod.snd <$> sa) \u27e8e, []\u27e9 m\n        pure <|\n            [h \"span\"\n                  [className \"expr\", key e, on_mouse_leave fun _ => action.on_mouse_leave_all] <|\n                v]\n#align tactic.explode_widget.mk tactic.explode_widget.mk\n\n/-- Render the implicit arguments for an expression in fancy, little pills. -/\nunsafe def implicit_arg_list (tooltip : tc subexpr Empty) (e : expr) : tactic <| html Empty := do\n  let fn \u2190 mk tooltip <| expr.get_app_fn e\n  let args \u2190 List.mapM (mk tooltip) <| expr.get_app_args e\n  pure <|\n      h \"div\" []\n        (h \"span\" [className \"bg-blue br3 ma1 ph2 white\"] [fn] ::\n          List.map (fun a => h \"span\" [className \"bg-gray br3 ma1 ph2 white\"] [a]) args)\n#align tactic.explode_widget.implicit_arg_list tactic.explode_widget.implicit_arg_list\n\n/-- Component for the type tooltip.\n-/\nunsafe def type_tooltip : tc subexpr Empty :=\n  tc.stateless fun \u27e8e, ea\u27e9 => do\n    let y \u2190 tactic.infer_type e\n    let y_comp \u2190 mk type_tooltip y\n    let implicit_args \u2190 implicit_arg_list type_tooltip e\n    pure\n        [h \"div\" [style [(\"minWidth\", \"12rem\")]]\n            [h \"div\" [cn \"pl1\"] [y_comp], h \"hr\" [] [], implicit_args]]\n#align tactic.explode_widget.type_tooltip tactic.explode_widget.type_tooltip\n\n/-- Component that shows a type.\n-/\nunsafe def show_type_component : tc expr Empty :=\n  tc.stateless fun x => do\n    let y \u2190 infer_type x\n    let y_comp \u2190 mk type_tooltip <| y\n    pure y_comp\n#align tactic.explode_widget.show_type_component tactic.explode_widget.show_type_component\n\n/-- Component that shows a constant.\n-/\nunsafe def show_constant_component : tc expr Empty :=\n  tc.stateless fun x => do\n    let y_comp \u2190 mk type_tooltip x\n    pure y_comp\n#align tactic.explode_widget.show_constant_component tactic.explode_widget.show_constant_component\n\n/-- Search for an entry that has the specified line number.\n-/\nunsafe def lookup_lines : entries \u2192 Nat \u2192 entry\n  | \u27e8_, []\u27e9, n => \u27e8default, 0, 0, Status.sintro, thm.string \"\", []\u27e9\n  | \u27e8rb, hd :: tl\u27e9, n => if hd.line = n then hd else lookup_lines \u27e8rb, tl\u27e9 n\n#align tactic.explode_widget.lookup_lines tactic.explode_widget.lookup_lines\n\n/-- Render a row that shows a goal.\n-/\nunsafe def goal_row (e : expr) (show_expr := true) : tactic (List (html Empty)) := do\n  let t \u2190 explode_widget.show_type_component e\n  return <|\n      [h \"td\" [cn \"ba bg-dark-green tc\"] \"Goal\",\n        h \"td\" [cn \"ba tc\"] (if show_expr then [html.of_name e, \" : \", t] else t)]\n#align tactic.explode_widget.goal_row tactic.explode_widget.goal_row\n\n/-- Render a row that shows the ID of a goal.\n-/\nunsafe def id_row {\u03b3} (l : Nat) : tactic (List (html \u03b3)) :=\n  return <| [h \"td\" [cn \"ba bg-dark-green tc\"] \"ID\", h \"td\" [cn \"ba tc\"] (toString l)]\n#align tactic.explode_widget.id_row tactic.explode_widget.id_row\n\n/-- Render a row that shows the rule or theorem being applied.\n-/\nunsafe def rule_row : thm \u2192 tactic (List (html Empty))\n  | thm.expr e => do\n    let t \u2190 explode_widget.show_constant_component e\n    return <| [h \"td\" [cn \"ba bg-dark-green tc\"] \"Rule\", h \"td\" [cn \"ba tc\"] t]\n  | t => return <| [h \"td\" [cn \"ba bg-dark-green tc\"] \"Rule\", h \"td\" [cn \"ba tc\"] t.toString]\n#align tactic.explode_widget.rule_row tactic.explode_widget.rule_row\n\n/-- Render a row that contains the sub-proofs, i.e., the proofs of the\narguments.\n-/\nunsafe def proof_row {\u03b3} (args : List (html \u03b3)) : List (html \u03b3) :=\n  [h \"td\" [cn \"ba bg-dark-green tc\"] \"Proofs\",\n    h \"td\" [cn \"ba tc\"]\n      [h \"details\" [] <| h \"summary\" [attr.style [(\"color\", \"orange\")]] \"Details\" :: args]]\n#align tactic.explode_widget.proof_row tactic.explode_widget.proof_row\n\n/-- Combine the goal row, id row, rule row and proof row to make them a table.\n-/\nunsafe def assemble_table {\u03b3} (gr ir rr) : List (html \u03b3) \u2192 html \u03b3\n  | [] => h \"table\" [cn \"collapse\"] [h \"tbody\" [] [h \"tr\" [] gr, h \"tr\" [] ir, h \"tr\" [] rr]]\n  | pr =>\n    h \"table\" [cn \"collapse\"]\n      [h \"tbody\" [] [h \"tr\" [] gr, h \"tr\" [] ir, h \"tr\" [] rr, h \"tr\" [] pr]]\n#align tactic.explode_widget.assemble_table tactic.explode_widget.assemble_table\n\n/-- Render a table for a given entry.\n-/\nunsafe def assemble (es : entries) : entry \u2192 tactic (html Empty)\n  | \u27e8e, l, d, status.sintro, t, ref\u27e9 => do\n    let gr \u2190 goal_row e\n    let ir \u2190 id_row l\n    let rr \u2190 rule_row <| thm.string \"Assumption\"\n    return <| assemble_table gr ir rr []\n  | \u27e8e, l, d, status.intro, t, ref\u27e9 => do\n    let gr \u2190 goal_row e\n    let ir \u2190 id_row l\n    let rr \u2190 rule_row <| thm.string \"Assumption\"\n    return <| assemble_table gr ir rr []\n  | \u27e8e, l, d, st, t, ref\u27e9 => do\n    let gr \u2190 goal_row e false\n    let ir \u2190 id_row l\n    let rr \u2190 rule_row t\n    let el : List entry := List.map (lookup_lines es) ref\n    let ls \u2190 Monad.mapM assemble el\n    let pr := proof_row <| ls.intersperse (h \"br\" [] [])\n    return <| assemble_table gr ir rr pr\n#align tactic.explode_widget.assemble tactic.explode_widget.assemble\n\n/-- Render a widget from given entries.\n-/\nunsafe def explode_component (es : entries) : tactic (html Empty) :=\n  let concl := lookup_lines es (es.l.length - 1)\n  assemble es concl\n#align tactic.explode_widget.explode_component tactic.explode_widget.explode_component\n\n/-- Explode a theorem and return entries.\n-/\nunsafe def explode_entries (n : Name) (hide_non_prop := true) : tactic entries := do\n  let expr.const n _ \u2190 resolve_name n |\n    fail \"cannot resolve name\"\n  let d \u2190 get_decl n\n  let v \u2190\n    match d with\n      | declaration.defn _ _ _ v _ _ => return v\n      | declaration.thm _ _ _ v => return v.get\n      | _ => fail \"not a definition\"\n  let t \u2190 pp d.type\n  explode_expr v hide_non_prop\n#align tactic.explode_widget.explode_entries tactic.explode_widget.explode_entries\n\nend ExplodeWidget\n\nopen ExplodeWidget\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\n/-- User command of the explode widget.\n-/\n@[user_command]\nunsafe def explode_widget_cmd (_ : parse <| tk \"#explode_widget\") : lean.parser Unit := do\n  let \u27e8li, co\u27e9 \u2190 cur_pos\n  let n \u2190 ident\n  let es \u2190 explode_entries n\n  let comp \u2190\n    parser.of_tactic do\n        let html \u2190 explode_component es\n        let c \u2190 pure <| component.stateless fun _ => [html]\n        pure <| component.ignore_props <| component.ignore_action <| c\n  save_widget \u27e8li, co - \"#explode_widget\".length - 1\u27e9 comp\n  trace \"successfully rendered widget\"\n  skip\n#align tactic.explode_widget_cmd tactic.explode_widget_cmd\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/ExplodeWidget.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748935136303, "lm_q2_score": 0.06954174788049289, "lm_q1q2_score": 0.02474120794693408}}
{"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 \u2192 foo\n| two : \u2200 x : fin 3, bar x \u2192 foo\n```\n\nThe list of elements that we generate is\n```\n{foo.zero}\n\u222a (finset.univ : bool).map (\u03bb b, finset.one b)\n\u222a (finset.univ : \u03a3' x : fin 3, bar x).map (\u03bb \u27e8x, y\u27e9, finset.two x y)\n```\nexcept that instead of `\u222a`, 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 \u2192 \u2115\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 \u2260 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 \u2208 s` have `n \u2264 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 `\u03bb 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 \u2208 {foo.zero}\n  \u222a (finset.univ : bool).map (\u03bb b, finset.one b)\n  \u222a (finset.univ : \u03a3' x : fin 3, bar x).map (\u03bb \u27e8x, y\u27e9, 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 `\u0393` 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 `\u2200 a, enum (f a) = k`\n* `mk_finset` constructs the finset `S = {foo.zero} \u222a ...` by recursion on the variants\n* `mk_finset_total` constructs the proof `|- foo.zero \u2208 S; |- foo.one a \u2208 S; |- foo.two a b \u2208 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 (\u03b1) (enum : \u03b1 \u2192 \u2115) (n : \u2115) :=\n{s : finset \u03b1 // \u2200 x \u2208 s, n \u2264 enum x}\n\n/-- Construct a fintype instance from a completed `finset_above`. -/\ndef mk_fintype {\u03b1} (enum : \u03b1 \u2192 \u2115) (s : finset_above \u03b1 enum 0) (H : \u2200 x, x \u2208 s.1) :\n  fintype \u03b1 := \u27e8s.1, H\u27e9\n\n/-- This is the case for a simple variant (no arguments) in an inductive type. -/\ndef finset_above.cons {\u03b1} {enum : \u03b1 \u2192 \u2115} (n)\n  (a : \u03b1) (h : enum a = n) (s : finset_above \u03b1 enum (n+1)) : finset_above \u03b1 enum n :=\nbegin\n  refine \u27e8finset.cons a s.1 _, _\u27e9,\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 {\u03b1} {enum : \u03b1 \u2192 \u2115} {n a h s} :\n  a \u2208 (@finset_above.cons \u03b1 enum n a h s).1 := multiset.mem_cons_self _ _\n\ntheorem finset_above.mem_cons_of_mem {\u03b1} {enum : \u03b1 \u2192 \u2115} {n a h s b} :\n  b \u2208 (s : finset_above _ _ _).1 \u2192 b \u2208 (@finset_above.cons \u03b1 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 {\u03b1} {enum : \u03b1 \u2192 \u2115} (n) : finset_above \u03b1 enum n := \u27e8\u2205, by rintro _ \u27e8\u27e9\u27e9\n\ninstance (\u03b1 enum n) : inhabited (finset_above \u03b1 enum n) := \u27e8finset_above.nil _\u27e9\n\n/-- This is a finset covering a nontrivial variant (with one or more constructor arguments).\nThe property `P` here is `\u03bb a, enum a = n` where `n` is the discriminant for the current\nvariant. -/\n@[nolint has_nonempty_instance]\ndef finset_in {\u03b1} (P : \u03b1 \u2192 Prop) := {s : finset \u03b1 // \u2200 x \u2208 s, P x}\n\n/-- To construct the finset, we use an injective map from the type `\u0393`, which will be the\nsigma over all constructor arguments. We use sigma instances and existing fintype instances\nto prove that `\u0393` is a fintype, and construct the function `f` that maps `\u27e8a, b, c, ...\u27e9`\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 {\u03b1} {P : \u03b1 \u2192 Prop} (\u0393) [fintype \u0393]\n  (f : \u0393 \u2192 \u03b1) (inj : function.injective f) (mem : \u2200 x, P (f x)) : finset_in P :=\n\u27e8finset.univ.map \u27e8f, inj\u27e9,\n \u03bb x h, by rcases finset.mem_map.1 h with \u27e8x, _, rfl\u27e9; exact mem x\u27e9\n\ntheorem finset_in.mem_mk {\u03b1} {P : \u03b1 \u2192 Prop} {\u0393} {s : fintype \u0393} {f : \u0393 \u2192 \u03b1} {inj mem a}\n  (b) (H : f b = a) : a \u2208 (@finset_in.mk \u03b1 P \u0393 s f inj mem).1 :=\nfinset.mem_map.2 \u27e8_, finset.mem_univ _, H\u27e9\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 {\u03b1} {enum : \u03b1 \u2192 \u2115} (n)\n  (s : finset_in (\u03bb a, enum a = n)) (t : finset_above \u03b1 enum (n+1)) : finset_above \u03b1 enum n :=\nbegin\n  refine \u27e8finset.disj_union s.1 t.1 _, _\u27e9,\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 {\u03b1} {enum : \u03b1 \u2192 \u2115} {n s t a}\n  (H : a \u2208 (s : finset_in _).1) : a \u2208 (@finset_above.union \u03b1 enum n s t).1 :=\nmultiset.mem_add.2 (or.inl H)\n\ntheorem finset_above.mem_union_right {\u03b1} {enum : \u03b1 \u2192 \u2115} {n s t a}\n  (H : a \u2208 (t : finset_above _ _ _).1) : a \u2208 (@finset_above.union \u03b1 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 `\u03a3' (a:A) (b:B a) (c:C a b), unit` from\n`\u03a0 (a:A) (b:B a), C a b \u2192 T` (the type of a constructor). -/\nmeta def mk_sigma : expr \u2192 tactic expr\n| (expr.pi n bi d b) := do\n  p \u2190 mk_local' n bi d,\n  e \u2190 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 `(\u03a3' (a:A) (b:B a) (c:C a b), unit) \u2192 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 \u2192 expr \u2192 tactic \u2115\n| (expr.pi n bi d b) c := do\n  refine ``(@psigma.elim %%d _ _ _),\n  i \u2190 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 \u2192 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 \u2192 \u27e8a1, ..., am\u27e9 = \u27e8b1, ..., bm\u27e9`, 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 : \u2115 \u2192 expr \u2192 expr \u2192 tactic unit\n| (m+1) x y := do\n  [(_, [x1, x2])] \u2190 cases x,\n  [(_, [y1, y2])] \u2190 cases y,\n  mk_sigma_elim_inj m x2 y2\n| 0 x y := do\n  cases x, cases y,\n  is \u2190 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 : \u2115 \u2192 expr \u2192 tactic unit\n| (n+1) x := do\n  [(_, [x1, x2])] \u2190 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) : \u2115 \u2192 list name \u2192 tactic unit\n| k (c::cs) := do\n  let e := (expr.const c ls).mk_app args,\n  t \u2190 infer_type e,\n  if is_pi t then do\n    to_expr ``(finset_above.union %%(reflect k)) tt ff >>=\n      (\u03bb c, apply c {new_goals := new_goals.all}),\n    \u0393 \u2190 mk_sigma t,\n    to_expr ``(finset_in.mk %%\u0393) tt ff >>= (\u03bb c, apply c {new_goals := new_goals.all}),\n    n \u2190 mk_sigma_elim t e,\n    intro1 >>= (\u03bb 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 \u2190 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 `|- \u03a3' (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 \u2192 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 \u2208 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 \u2192 list (name \u00d7 list expr) \u2192 tactic unit\n| tac [] := done\n| tac ((_, xs) :: gs) := do\n  tac,\n  b \u2190 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) \u2190 target >>= whnf,\n  (const I ls, args) \u2190 pure (get_app_fn_args e),\n  env \u2190 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 (\u00ac 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 >>= (\u03bb gs,\n    gs.enum.mmap' $ \u03bb \u27e8i, _\u27e9, 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 : \u2115)\n| zero : foo\n| one : bool \u2192 foo\n| two : fin n \u2192 fin m \u2192 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 `\u03b1`, then the generated instance will have an\nargument `fintype \u03b1`, 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": "import system.io\nimport query_api\nimport parse\n\nopen widget tactic\nsection json\nmeta def list.lookup_prod {\u03b1 \u03b2} : (list (\u03b1 \u00d7 \u03b2)) \u2192 (\u03b1 \u2192 bool) \u2192 option \u03b2\n| [] _ := none\n| (\u27e8a,b\u27e9::xs) p := if p a then pure b else xs.lookup_prod p\n\nopen except\n\nmeta def json.lookup : json \u2192 string \u2192 except string json\n| (json.object kvs) str :=\n  match kvs.lookup_prod $ \u03bb k, k = str with\n  | some v := except.ok v\n  | none := except.error (\"no key \" ++ str)\n  end\n| _ _ := except.error \"not an object\"\n\nmeta def json.as_string : json \u2192 except string string\n  | (json.of_string s) := except.ok s\n  | _ := except.error \"not a string\"\n\nmeta def json.as_array : json \u2192 except string (list json)\n  | (json.array xs) := ok xs\n  | _ := error \"not an array\"\n\nmeta def except.liftOption {\u03b1}: option \u03b1 \u2192 except string \u03b1\n  | none := except.error \"option was none\"\n  | (some a ) := except.ok a\n\nend json\n\nmeta def text_of_return_json (parsed : json) : except string string := do\n  choices_json \u2190 json.lookup parsed \"choices\",\n  head :: _ \u2190 json.as_array choices_json | except.error \"empty array\",\n  t \u2190 json.lookup head \"text\",\n  s \u2190 json.as_string t,\n  return s\n\nmeta def run_except {\u03b1} : except string \u03b1 \u2192 io \u03b1\n  | (except.ok a) := pure a\n  | (except.error e) := io.fail e\n\n\n\n@[derive inhabited]\nmeta structure bubble :=\n  (body : string) -- [todo] add formatting etc\n  (user : string)\n\nmeta def chat_props := unit\n\nmeta structure chat_state : Type :=\n  (bubbles : list bubble)\n  (current_text : string)\n\n/- @zhangir: write your code for getting response from codex here :-) -/\nmeta def get_response : chat_state \u2192 io string\n| state := do {\n    bubbles@(head :: tail) \u2190 pure $ state.bubbles | io.fail \"no chat yet\",\n    let statement :=\n      match tail with\n      | [] := head.body\n      | tail := (list.reverse tail).head.body\n      end,\n    let rest_of_context :=\n      match tail with\n      | [] := \"\"\n      | tail := (string.intercalate \"\\n\" $  list.map bubble.body $ list.tail $ list.reverse $ bubbles) ++ \" Try again:\\ntheorem\"\n        -- want this python command: \"\\n\".join([x.body for x in state.bubbles].reverse[1:])\n      end,\n    let prompt := prompt_of_nl_statement statement few_shot_prompt ++ rest_of_context,\n    --io.put_str_ln (prompt ++ \"<endoftext>\"),\n    return_json \u2190 get_completion_of_request {prompt:=prompt},\n    (some maybe_return_parsed) \u2190 pure (json.parse return_json) | io.fail \"not json\",\n    t : string \u2190 run_except $ text_of_return_json maybe_return_parsed,\n    return (t ++ \" :=\")\n  }\n\n/-- Use when testing formatting etc to avoid having to call api. -/\nmeta def get_response_dummy : chat_state \u2192 io string\n  | state := do {\n      return \"meta def unsafe_perform_io {\u03b1} (m : io \u03b1) : except io.error \u03b1 :=\nmatch (cast undefined m : unit \u2192 sum \u03b1 io.error) () with\n| sum.inl a := except.ok a\n| sum.inr err := except.error err\nend\"\n    }\n\n-- use some @gebner magic here\nmeta def unsafe_perform_io {\u03b1} (m : io \u03b1) : except io.error \u03b1 :=\nmatch (cast undefined m : unit \u2192 sum \u03b1 io.error) () with\n| sum.inl a := except.ok a\n| sum.inr err := except.error err\nend\n\nmeta def unsafe_get_response (input : chat_state) : string :=\n  match unsafe_perform_io (get_response input) with\n  | except.ok a := a\n  | except.error e := \"error\"\n  end\n\nmeta inductive chat_action\n  | submit\n  | demo_text\n  | text_change (s : string)\n  | copy_to_comment (s : string)\n  | copy_to_script (s : string)\n  | clear\n\nmeta def code_content (code : string) : html chat_action :=\n  h \"div\" [] [\n    h \"code\" [className \"font-code\", attr.style [(\"white-space\", \"break-spaces\")]] [\n      code\n    ],\n    h \"div\" [] [\n      button \"paste\" (chat_action.copy_to_script (\"theorem \" ++ code))\n    ]\n  ]\n\nmeta inductive nlrun\n  | math (s : string) : nlrun\n  | text (s : string) : nlrun\n\nmeta def nlrun.to_html {\u03b1 : Type} : nlrun \u2192 html \u03b1\n  | (nlrun.math s) := html.element \"InlineMath\" [attr.val \"math\" s] []\n  | (nlrun.text s) := html.of_string s\n\nmeta def to_nlrun_aux : list string \u2192 list nlrun\n  | (text :: latex :: rest) := (nlrun.text text) :: (nlrun.math latex) :: to_nlrun_aux rest\n  | [] := []\n  | [text] := [nlrun.text text]\n\nmeta def to_nlrun (s : string) : list nlrun :=\n  to_nlrun_aux $ string.split_on s '$'\n\nmeta def nl_content (s : string) : html chat_action :=\n  let nlruns := to_nlrun s in\n  h \"div\" [className \"f6\"] $ nlruns.map nlrun.to_html\n\nmeta def chat_view (props : chat_props) (state : chat_state) : list (html chat_action) :=\n  [h \"div\" [className \"f6\"] [\n    h \"div\" [className \"flex flex-column\"] (\n      state.bubbles.reverse.map (\u03bb bubble,\n        h \"div\" [className \"pa2 ma2 bg-lightest-blue\"] [\n          h \"div\" [className \"mr2\"] [bubble.user, \": \"],\n          if bubble.user \u2260 \"self\" then\n            code_content bubble.body\n          else\n            nl_content bubble.body\n        ]\n      )\n    ),\n    h \"div\" [] [\n      textbox state.current_text chat_action.text_change,\n      button \"submit\" chat_action.submit, -- [todo] how to get it to trigger on enter?\n      button \"demo\" chat_action.demo_text,\n      button \"clear\" chat_action.clear\n    ]\n  ]]\n\nmeta def push_bubble (b : bubble) (s : chat_state) : chat_state := {bubbles := b :: s.bubbles, ..s}\n\n\n#check tactic.unsafe_run_io\n/-- runs the lean parser on the response, if it's good then returns an error message, otherwise returns none.\n  I am not proud of this method, this should be considered bad Lean practice.\n-/\nmeta def unsafe_parse_result (response : string) : option string := do\n  empty_tactic_state \u2190 except.to_option $ unsafe_perform_io (io.run_tactic tactic.read),\n  let t := lean.parser.run_with_input parse_decl response empty_tactic_state,\n  match t with\n  | result.success a s := none\n  | result.exception (some msg) pos s := some (to_string $ msg())\n  | result.exception _ _ _ := some \"exception with no message!\"\n  end\n\nmeta def chat_update (props : chat_props)  : chat_state \u2192 chat_action \u2192 (chat_state \u00d7 option effect)\n  | state (chat_action.submit) :=\n    let text := state.current_text,\n        state := {current_text := \"\", ..state},\n        state := push_bubble {body := text, user := \"self\"} state,\n        response := unsafe_get_response state,\n        state := push_bubble {body := response, user := \"codex\"} state,\n        state := push_bubble {\n          body := match unsafe_parse_result (\"def \" ++ response) with\n                  | (some msg) := \"error:\\n\" ++ msg\n                  | none := \"check passes!\"\n                  end,\n          user := \"lean\"} state\n        in\n    (state, none)\n  | state (chat_action.text_change s) := ({current_text := s, ..state}, none)\n  | state (chat_action.copy_to_comment str) := (state, some $ effect.insert_text $ \"/--\\n\" ++ str ++ \"\\n-/\")\n  | state (chat_action.copy_to_script str) := (state, some $ effect.insert_text str)\n  | state chat_action.demo_text :=\n    -- @zhangir add your example here to avoid having to paste it in every time!\n    let state := {current_text := \"If $x$ is an element of infinite order in $G$, prove that the elements $x^n$, $n\\\\in\\\\mathbb{Z}$ are all distinct.\", ..state} in\n    chat_update state chat_action.submit\n  | state (chat_action.clear) := ({current_text:=\"\", bubbles:=[]}, none)\n\nmeta def chat_init (props : chat_props) (old_state : option chat_state) : chat_state :=\n  let s : chat_state := ({bubbles := [], current_text := \"\"} <| old_state) in\n  s\n\nmeta def chat_widget {\u03c0 \u03b1 : Type} : component \u03c0 \u03b1 :=\ncomponent.ignore_props\n$ component.ignore_action\n$ component.with_effects (\u03bb _ action, [action])\n$ component.stateful chat_action _ chat_init  chat_update chat_view\n\n-- @zhangir put your cursor on the #html token!\n#html chat_widget ()", "meta": {"author": "zhangir-azerbayev", "repo": "lean-chat", "sha": "cc2832852e1858b879234b0a0f3ac7017df4a195", "save_path": "github-repos/lean/zhangir-azerbayev-lean-chat", "path": "github-repos/lean/zhangir-azerbayev-lean-chat/lean-chat-cc2832852e1858b879234b0a0f3ac7017df4a195/src/widget.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.06008665354025421, "lm_q1q2_score": 0.024702276366186035}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Gabriel Ebner\n-/\nimport Lean\nimport Mathlib.Util.TermUnsafe\nimport Mathlib.Tactic.OpenPrivate\n\n/-!\nDefines a command wrapper that prints the changes the command makes to the\nenvironment.\n\n```\nwhatsnew in\ntheorem foo : 42 = 6 * 7 := rfl\n```\n-/\n\nopen Lean Elab Command\n\nnamespace Mathlib.WhatsNew\n\nprivate def throwUnknownId (id : Name) : CommandElabM Unit :=\n  throwError \"unknown identifier '{mkConst id}'\"\n\nprivate def levelParamsToMessageData (levelParams : List Name) : MessageData :=\n  match levelParams with\n  | []    => \"\"\n  | u::us => Id.run <| do\n    let mut m := m!\".\\{{u}\"\n    for u in us do\n      m := m ++ \", \" ++ toMessageData u\n    return m ++ \"}\"\n\nprivate def mkHeader (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (safety : DefinitionSafety) : CoreM MessageData := do\n  let m : MessageData :=\n    match safety with\n    | DefinitionSafety.unsafe  => \"unsafe \"\n    | DefinitionSafety.partial => \"partial \"\n    | DefinitionSafety.safe    => \"\"\n  let m := if isProtected (\u2190 getEnv) id then m ++ \"protected \" else m\n  let (m, id) := match privateToUserName? id with\n    | some id => (m ++ \"private \", id)\n    | none    => (m, id)\n  let m := m ++ kind ++ \" \" ++ id ++ levelParamsToMessageData levelParams ++ \" : \" ++ type\n  pure m\n\nprivate def mkHeader' (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (isUnsafe : Bool) : CoreM MessageData :=\n  mkHeader kind id levelParams type (if isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe)\n\nprivate def printDefLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (value : Expr) (safety := DefinitionSafety.safe) : CoreM MessageData :=\n  return (\u2190 mkHeader kind id levelParams type safety) ++ \" :=\" ++ Format.line ++ value\n\nprivate def printInduct (id : Name) (levelParams : List Name) (numParams : Nat) (numIndices : Nat) (type : Expr)\n    (ctors : List Name) (isUnsafe : Bool) : CoreM MessageData := do\n  let mut m \u2190 mkHeader' \"inductive\" id levelParams type isUnsafe\n  m := m ++ Format.line ++ \"constructors:\"\n  for ctor in ctors do\n    let cinfo \u2190 getConstInfo ctor\n    m := m ++ Format.line ++ ctor ++ \" : \" ++ cinfo.type\n  pure m\n\nprivate def printIdCore (id : Name) : ConstantInfo \u2192 CoreM MessageData\n  | ConstantInfo.axiomInfo { levelParams := us, type := t, isUnsafe := u, .. } =>\n    mkHeader' \"axiom\" id us t u\n  | ConstantInfo.defnInfo  { levelParams := us, type := t, value := v, safety := s, .. } =>\n    printDefLike \"def\" id us t v s\n  | ConstantInfo.thmInfo  { levelParams := us, type := t, value := v, .. } =>\n    printDefLike \"theorem\" id us t v\n  | ConstantInfo.opaqueInfo  { levelParams := us, type := t, isUnsafe := u, .. } =>\n    mkHeader' \"constant\" id us t u\n  | ConstantInfo.quotInfo  { kind := kind, levelParams := us, type := t, .. } =>\n    mkHeader' \"Quotient primitive\" id us t false\n  | ConstantInfo.ctorInfo { levelParams := us, type := t, isUnsafe := u, .. } =>\n    mkHeader' \"constructor\" id us t u\n  | ConstantInfo.recInfo { levelParams := us, type := t, isUnsafe := u, .. } =>\n    mkHeader' \"recursor\" id us t u\n  | ConstantInfo.inductInfo { levelParams := us, numParams := numParams, numIndices := numIndices, type := t, ctors := ctors, isUnsafe := u, .. } =>\n    printInduct id us numParams numIndices t ctors u\n\ndef diffExtension (old new : Environment)\n    (ext : PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState) :\n    CoreM (Option MessageData) := unsafe do\n  let oldSt := ext.toEnvExtension.getState old\n  let newSt := ext.toEnvExtension.getState new\n  if ptrAddrUnsafe oldSt == ptrAddrUnsafe newSt then return none\n  let oldEntries := ext.exportEntriesFn oldSt.state\n  let newEntries := ext.exportEntriesFn newSt.state\n  pure m!\"-- {ext.name} extension: {(newEntries.size - oldEntries.size : Int)} new entries\"\n\ndef whatsNew (old new : Environment) : CoreM MessageData := do\n  let mut diffs := #[]\n\n  for (c, i) in new.constants.map\u2082.toList do\n    unless old.constants.map\u2082.contains c do\n      diffs := diffs.push (\u2190 printIdCore c i)\n\n  for ext in \u2190 persistentEnvExtensionsRef.get do\n    if let some diff := \u2190 diffExtension old new ext then\n      diffs := diffs.push diff\n\n  if diffs.isEmpty then return \"no new constants\"\n\n  pure $ MessageData.joinSep diffs.toList \"\\n\\n\"\n\n/-- `whatsnew in $command` executes the command and then prints the\ndeclarations that were added to the environment. -/\nelab \"whatsnew\" \"in\" ppLine cmd:command : command => do\n  let oldEnv \u2190 getEnv\n  try\n    elabCommand cmd\n  finally\n    let newEnv \u2190 getEnv\n    logInfo (\u2190 liftCoreM <| whatsNew oldEnv newEnv)\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/Util/WhatsNew.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.06465348565285166, "lm_q1q2_score": 0.024647173757528323}}
{"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\u1d52\u1d56 \u2964 Type w) :=\n(obj : \u03a0 U, set (F.obj U))\n(map : \u03a0 {U V : C\u1d52\u1d56} (i : U \u27f6 V), (obj U) \u2286 (F.map i) \u207b\u00b9' (obj V))\n\nvariables {F F' F'' : C\u1d52\u1d56 \u2964 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\u27e8\u27e8\u03bb U, \u22a4, \u03bb U V i x h, _root_.trivial\u27e9\u27e9\n\ninstance : nonempty (subpresheaf F) := infer_instance\n\n/-- The subpresheaf as a presheaf. -/\n@[simps]\ndef subpresheaf.to_presheaf : C\u1d52\u1d56 \u2964 Type w :=\n{ obj := \u03bb U, G.obj U,\n  map := \u03bb U V i x, \u27e8F.map i x, G.map i x.prop\u27e9,\n  map_id' := \u03bb X, by { ext \u27e8x, _\u27e9, dsimp, rw F.map_id, refl },\n  map_comp' := \u03bb X Y Z i j, by { ext \u27e8x, _\u27e9, 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.\u03b9 : G.to_presheaf \u27f6 F :=\n{ app := \u03bb U x, x }\n\ninstance : mono G.\u03b9 :=\n\u27e8\u03bb H f\u2081 f\u2082 e, nat_trans.ext f\u2081 f\u2082 $ funext $ \u03bb U,\n  funext $ \u03bb x, subtype.ext $ congr_fun (congr_app e U) x\u27e9\n\n/-- The inclusion of a subpresheaf to a larger subpresheaf -/\n@[simps]\ndef subpresheaf.hom_of_le {G G' : subpresheaf F} (h : G \u2264 G') : G.to_presheaf \u27f6 G'.to_presheaf :=\n{ app := \u03bb U x, \u27e8x, h U x.prop\u27e9 }\n\ninstance {G G' : subpresheaf F} (h : G \u2264 G') : mono (subpresheaf.hom_of_le h) :=\n\u27e8\u03bb H f\u2081 f\u2082 e, nat_trans.ext f\u2081 f\u2082 $ funext $ \u03bb U,\n  funext $ \u03bb x, subtype.ext $ (congr_arg subtype.val $ (congr_fun (congr_app e U) x : _) : _)\u27e9\n\n@[simp, reassoc]\nlemma subpresheaf.hom_of_le_\u03b9  {G G' : subpresheaf F} (h : G \u2264 G') :\n  subpresheaf.hom_of_le h \u226b G'.\u03b9 = G.\u03b9 :=\nby { ext, refl }\n\ninstance : is_iso (subpresheaf.\u03b9 (\u22a4 : 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 \u27e8subtype.coe_injective, \u03bb x, \u27e8\u27e8x, _root_.trivial\u27e9, rfl\u27e9\u27e9 }\nend\n\nlemma subpresheaf.eq_top_iff_is_iso : G = \u22a4 \u2194 is_iso G.\u03b9 :=\nbegin\n  split,\n  { rintro rfl, apply_instance },\n  { introI H, ext U x, apply (iff_true _).mpr, rw \u2190 is_iso.inv_hom_id_apply (G.\u03b9.app U) x,\n    exact ((inv (G.\u03b9.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' \u27f6 F) (hf : \u2200 U x, f.app U x \u2208 G.obj U) : F' \u27f6 G.to_presheaf :=\n{ app := \u03bb U x, \u27e8f.app U x, hf U x\u27e9,\n  naturality' := by { have := elementwise_of f.naturality, intros, ext, simp [this] } }\n\n@[simp, reassoc]\nlemma subpresheaf.lift_\u03b9 (f : F' \u27f6 F) (hf : \u2200 U x, f.app U x \u2208 G.obj U) :\n  G.lift f hf \u226b G.\u03b9 = 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 \u27f6 U` such that the restriction of `s` along `f` is in `G`. -/\n@[simps]\ndef subpresheaf.sieve_of_section {U : C\u1d52\u1d56} (s : F.obj U) : sieve (unop U) :=\n{ arrows := \u03bb V f, F.map f.op s \u2208 G.obj (op V),\n  downward_closed' := \u03bb 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\u1d52\u1d56} (s : F.obj U) :\n  (G.sieve_of_section s).1.family_of_elements G.to_presheaf :=\n\u03bb V i hi, \u27e8F.map i.op s, hi\u27e9\n\nlemma subpresheaf.family_of_elements_compatible {U : C\u1d52\u1d56} (s : F.obj U) :\n  (G.family_of_elements_of_section s).compatible :=\nbegin\n  intros Y\u2081 Y\u2082 Z g\u2081 g\u2082 f\u2081 f\u2082 h\u2081 h\u2082 e,\n  ext1,\n  change F.map g\u2081.op (F.map f\u2081.op s) = F.map g\u2082.op (F.map f\u2082.op s),\n  rw [\u2190 functor_to_types.map_comp_apply, \u2190 functor_to_types.map_comp_apply,\n    \u2190 op_comp, \u2190 op_comp, e],\nend\n\nlemma subpresheaf.nat_trans_naturality (f : F' \u27f6 G.to_presheaf) {U V : C\u1d52\u1d56} (i : U \u27f6 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 := \u03bb U, { s | G.sieve_of_section s \u2208 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 \u22a2,\n    rwa \u2190 functor_to_types.map_comp_apply,\n  end }\n\nlemma subpresheaf.le_sheafify : G \u2264 G.sheafify J :=\nbegin\n  intros U s hs,\n  change _ \u2208 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 \u2190 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 (\u03bb Y f hf, G.sieve_of_section (x f hf).1),\n  have := \u03bb {V} {i : V \u27f6 U} (hi : S' i), hi,\n  choose W i\u2081 i\u2082 hi\u2082 h\u2081 h\u2082,\n  dsimp [-sieve.bind_apply] at *,\n  let x'' : presieve.family_of_elements F S' :=\n    \u03bb V i hi, F.map (i\u2081 hi).op (x _ (hi\u2082 hi)),\n  have H : \u2200 s, x.is_amalgamation s \u2194 x''.is_amalgamation s.1,\n  { intro s,\n    split,\n    { intros H V i hi,\n      dsimp only [x''],\n      conv_lhs { rw \u2190 h\u2082 hi },\n      rw \u2190 H _ (hi\u2082 hi),\n      exact functor_to_types.map_comp_apply F (i\u2082 hi).op (i\u2081 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' \u226b i) := \u27e8_, _, _, hi, hi', rfl\u27e9,\n      have := H _ hi'',\n      rw [op_comp, F.map_comp] at this,\n      refine this.trans (congr_arg subtype.val (hx _ _ (hi\u2082 hi'') hi (h\u2082 hi''))) } },\n  have : x''.compatible,\n  { intros V\u2081 V\u2082 V\u2083 g\u2081 g\u2082 g\u2083 g\u2084 S\u2081 S\u2082 e,\n    rw [\u2190 functor_to_types.map_comp_apply, \u2190 functor_to_types.map_comp_apply],\n    exact congr_arg subtype.val\n      (hx (g\u2081 \u226b i\u2081 S\u2081) (g\u2082 \u226b i\u2081 S\u2082) (hi\u2082 S\u2081) (hi\u2082 S\u2082) (by simp only [category.assoc, h\u2082, e])) },\n  obtain \u27e8t, ht, ht'\u27e9 := hF _ (J.bind_covering hS (\u03bb V i hi, (x i hi).2)) _ this,\n  refine \u27e8\u27e8t, _\u27e9, (H \u27e8t, _\u27e9).mpr ht, \u03bb y hy, subtype.ext (ht' _ ((H _).mp hy))\u27e9,\n  show G.sieve_of_section t \u2208 J _,\n  refine J.superset_covering _ (J.bind_covering hS (\u03bb V i hi, (x i hi).2)),\n  intros V i hi,\n  dsimp,\n  rw ht _ hi,\n  exact h\u2081 hi\nend\n\nlemma subpresheaf.eq_sheafify_iff (h : presieve.is_sheaf J F) :\n  G = G.sheafify J \u2194 presieve.is_sheaf J G.to_presheaf :=\n\u27e8\u03bb e, e.symm \u25b8 G.sheafify_is_sheaf h, G.eq_sheafify h\u27e9\n\nlemma subpresheaf.is_sheaf_iff (h : presieve.is_sheaf J F) :\n  presieve.is_sheaf J G.to_presheaf \u2194\n    \u2200 U (s : F.obj U), G.sieve_of_section s \u2208 J (unop U) \u2192 s \u2208 G.obj U :=\nbegin\n  rw \u2190 G.eq_sheafify_iff h,\n  change _ \u2194 G.sheafify J \u2264 G,\n  exact \u27e8eq.ge, (G.le_sheafify J).antisymm\u27e9\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 \u27f6 F') (h : presieve.is_sheaf J F') :\n  (G.sheafify J).to_presheaf \u27f6 F' :=\n{ app := \u03bb U s,\n    (h _ s.prop).amalgamate _ ((G.family_of_elements_compatible \u2191s).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 \u2190 functor_to_types.map_comp_apply },\n    change _ = F'.map (j \u226b i.unop).op _,\n    refine eq.trans _ (presieve.is_sheaf_for.valid_glue _ _ _ _).symm,\n    { dsimp at \u22a2 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 \u27f6 F') (h : presieve.is_sheaf J F') :\n  subpresheaf.hom_of_le (G.le_sheafify J) \u226b 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\u2081 l\u2082 : (G.sheafify J).to_presheaf \u27f6 F')\n  (e : subpresheaf.hom_of_le (G.le_sheafify J) \u226b l\u2081 =\n    subpresheaf.hom_of_le (G.le_sheafify J) \u226b l\u2082) : l\u2081 = l\u2082 :=\nbegin\n  ext U \u27e8s, hs\u27e9,\n  apply (h _ hs).is_separated_for.ext,\n  rintros V i hi,\n  dsimp at hi,\n  erw [\u2190 functor_to_types.naturality, \u2190 functor_to_types.naturality],\n  exact (congr_fun (congr_app e $ op V) \u27e8_, hi\u27e9 : _)\nend\n\nlemma subpresheaf.sheafify_le (h : G \u2264 G') (hF : presieve.is_sheaf J F)\n  (hG' : presieve.is_sheaf J G'.to_presheaf) :\n  G.sheafify J \u2264 G' :=\nbegin\n  intros U x hx,\n  convert ((G.sheafify_lift (subpresheaf.hom_of_le h) hG').app U \u27e8x, hx\u27e9).2,\n  apply (hF _ hx).is_separated_for.ext,\n  intros V i hi,\n  have := congr_arg (\u03bb f : G.to_presheaf \u27f6 G'.to_presheaf, (nat_trans.app f (op V) \u27e8_, hi\u27e9).1)\n    (G.to_sheafify_lift (subpresheaf.hom_of_le h) hG'),\n  convert this.symm,\n  erw \u2190 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' \u27f6 F) : subpresheaf F :=\n{ obj := \u03bb U, set.range (f.app U),\n  map := \u03bb U V i,\n    by { rintros _ \u27e8x, rfl\u27e9, have := elementwise_of f.naturality, exact \u27e8_, this i x\u27e9 } }\n\n@[simp] lemma top_subpresheaf_obj (U) : (\u22a4 : subpresheaf F).obj U = \u22a4 := rfl\n\n@[simp]\nlemma image_presheaf_id : image_presheaf (\ud835\udfd9 F) = \u22a4 :=\nby { ext, simp }\n\n/-- A morphism factors through the image presheaf. -/\n@[simps]\ndef to_image_presheaf (f : F' \u27f6 F) : F' \u27f6 (image_presheaf f).to_presheaf :=\n(image_presheaf f).lift f (\u03bb 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' \u27f6 F) : F' \u27f6 ((image_presheaf f).sheafify J).to_presheaf :=\n to_image_presheaf f \u226b subpresheaf.hom_of_le ((image_presheaf f).le_sheafify J)\n\nvariables {J}\n\n@[simp, reassoc]\nlemma to_image_presheaf_\u03b9 (f : F' \u27f6 F) : to_image_presheaf f \u226b (image_presheaf f).\u03b9 = f :=\n(image_presheaf f).lift_\u03b9 _ _\n\nlemma image_presheaf_comp_le (f\u2081 : F \u27f6 F') (f\u2082 : F' \u27f6 F'') :\n  image_presheaf (f\u2081 \u226b f\u2082) \u2264 image_presheaf f\u2082 :=\n\u03bb U x hx, \u27e8f\u2081.app U hx.some, hx.some_spec\u27e9\n\ninstance {F F' : C\u1d52\u1d56 \u2964 Type (max v w)} (f : F \u27f6 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 \u27e8_, \u27e8x, rfl\u27e9\u27e9, exact \u27e8x, rfl\u27e9 }\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 \u27f6 F') : Sheaf J (Type w) :=\n\u27e8((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 \u2190 is_sheaf_iff_is_sheaf_of_type, exact F'.2 }\u27e9\n\n/-- A morphism factors through the image sheaf. -/\n@[simps]\ndef to_image_sheaf {F F' : Sheaf J (Type w)} (f : F \u27f6 F') : F \u27f6 image_sheaf f :=\n\u27e8to_image_presheaf_sheafify J f.1\u27e9\n\n/-- The inclusion of the image sheaf to the target. -/\n@[simps]\ndef image_sheaf_\u03b9 {F F' : Sheaf J (Type w)} (f : F \u27f6 F') : image_sheaf f \u27f6 F' :=\n\u27e8subpresheaf.\u03b9 _\u27e9\n\n@[simp, reassoc]\nlemma to_image_sheaf_\u03b9 {F F' : Sheaf J (Type w)} (f : F \u27f6 F') :\n  to_image_sheaf f \u226b image_sheaf_\u03b9 f = f :=\nby { ext1, simp [to_image_presheaf_sheafify] }\n\ninstance {F F' : Sheaf J (Type w)} (f : F \u27f6 F') : mono (image_sheaf_\u03b9 f) :=\n(Sheaf_to_presheaf J _).mono_of_mono_map (by { dsimp, apply_instance })\n\ninstance {F F' : Sheaf J (Type w)} (f : F \u27f6 F') : epi (to_image_sheaf f) :=\nbegin\n  refine \u27e8\u03bb G' g\u2081 g\u2082 e, _\u27e9,\n  ext U \u27e8s, hx\u27e9,\n  apply ((is_sheaf_iff_is_sheaf_of_type J _).mp G'.2 _ hx).is_separated_for.ext,\n  rintros V i \u27e8y, e'\u27e9,\n  change (g\u2081.val.app _ \u226b G'.val.map _) _ = (g\u2082.val.app _ \u226b G'.val.map _) _,\n  rw [\u2190 nat_trans.naturality, \u2190 nat_trans.naturality],\n  have E : (to_image_sheaf f).val.app (op V) y =\n    (image_sheaf f).val.map i.op \u27e8s, hx\u27e9 := subtype.ext e',\n  have := congr_arg (\u03bb f : F \u27f6 G', (Sheaf.hom.val f).app _ y) e,\n  dsimp at this \u22a2,\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 \u27f6 F') :\n  limits.mono_factorisation f :=\n{ I := image_sheaf f,\n  m := image_sheaf_\u03b9 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 \u27f6 F') :\n  limits.image_factorisation f :=\n{ F := image_mono_factorization f,\n  is_image :=\n  { lift := \u03bb I, begin\n      haveI := (Sheaf.hom.mono_iff_presheaf_mono J _ _).mp I.m_mono,\n      refine \u27e8subpresheaf.hom_of_le _ \u226b inv (to_image_presheaf I.m.1)\u27e9,\n      apply subpresheaf.sheafify_le,\n      { conv_lhs { rw \u2190 I.fac }, apply image_presheaf_comp_le },\n      { rw \u2190 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 \u2190 is_sheaf_iff_is_sheaf_of_type, exact I.I.2 }\n    end,\n    lift_fac' := \u03bb I, begin\n      ext1,\n      dsimp [image_mono_factorization],\n      generalize_proofs h,\n      rw [\u2190 subpresheaf.hom_of_le_\u03b9 h, category.assoc],\n      congr' 1,\n      rw [is_iso.inv_comp_eq, to_image_presheaf_\u03b9],\n    end } }\n\ninstance : limits.has_images (Sheaf J (Type (max v u))) :=\n\u27e8\u03bb _ _ f, \u27e8\u27e8image_factorization f\u27e9\u27e9\u27e9\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": "/-\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.tactic init.meta.rb_map\nopen tactic\nopen native\nprivate meta def apply_replacement (replacements : name_map name) (e : expr) : expr :=\ne.replace (\u03bb 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    end\n  | _ := none\n  end)\n\n/-- Given 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 := ... -/\nmeta def copy_decl_updating_type (replacements : name_map name) (src_decl_name : name) (new_decl_name : name) : command :=\ndo env  \u2190 get_env,\n   decl \u2190 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\nmeta def copy_decl_using (replacements : name_map name) (src_decl_name : name) (new_decl_name : name) : command :=\ndo env      \u2190 get_env,\n   decl     \u2190 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", "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/decl_cmds.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.06560483471870812, "lm_q1q2_score": 0.024528060642873144}}
{"text": "/-\nThe contents of this file (apart from this comment) lifted from the natural number game by\nKevin Buzzard & Mohammad Pedramfar.\n-/\n\n-- Many many thanks to Rob Lewis for supplying 99.9% of this file.\n\nimport tactic.modded tactic.apply\n\nopen tactic\n\nmeta def copy_decl (d : declaration) : tactic unit :=\nadd_decl $ d.update_name $ d.to_name.update_prefix `pure_maths.interactive\n\n@[reducible] meta def filter (d : declaration) : bool :=\nd.to_name \u2209 [`tactic.interactive.induction, \n             `tactic.interactive.cases, \n             `tactic.interactive.rw,\n             `tactic.interactive.ring,\n             `tactic.interactive.symmetry,\n             `tactic.interactive.use]\n\nmeta def copy_decls : tactic unit :=\ndo env \u2190 get_env,\n  let ls := env.fold [] list.cons,\n  ls.mmap' $ \u03bb dec, when (dec.to_name.get_prefix = `tactic.interactive \u2227 filter dec) (copy_decl dec)\n\n@[reducible] meta def pure_maths := tactic\n\nnamespace pure_maths\n\n--meta instance : monad pure_maths := by delta pure_maths; apply_instance\n\n--meta instance : alternative pure_maths := by delta pure_maths; apply_instance\n\nmeta def step {\u03b1} (c : pure_maths \u03b1) : pure_maths unit := \nc >> return ()\n\nmeta def istep := @tactic.istep\n\nmeta def save_info := tactic.save_info\n\nmeta def execute (c : pure_maths unit) : pure_maths unit := \nc\n\nmeta def execute_with := @smt_tactic.execute_with\n--meta def trace_state {\u03b1 : Type}\n\nmeta def solve1 := @tactic.solve1\n\nend pure_maths\n\n--#check tactic.interactive.induction\n\nnamespace pure_maths.interactive\n\nmeta def induction\n:= tactic.interactive.induction'\n\nmeta def cases\n:= tactic.interactive.cases'\n\nmeta def rw\n:= tactic.interactive.rw'\n\nmeta def ring\n:= tactic.interactive.ring\n\nmeta def symmetry\n:= tactic.interactive.symmetry'\n\nmeta def use\n:= tactic.interactive.use'\n\nend pure_maths.interactive\n\nrun_cmd copy_decls\n\n--TODO : why is this broken?\n--#print tactic.interactive.rintro\n\n--#exit\n\n-- example just to check it's running\n/- example (n : \u2115) : true :=\nbegin [pure_maths]\n  induction n,\n    sorry, sorry  \nend -/", "meta": {"author": "gihanmarasingha", "repo": "lean-game-template", "sha": "75bb3c4cd17afb31062d74eb9b2ab9b232e49719", "save_path": "github-repos/lean/gihanmarasingha-lean-game-template", "path": "github-repos/lean/gihanmarasingha-lean-game-template/lean-game-template-75bb3c4cd17afb31062d74eb9b2ab9b232e49719/src/tactic/pure_maths.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.08151974704900902, "lm_q1q2_score": 0.02451670352139778}}
{"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 (\u03b1 : Type) := VarName \u2192 \u03b1\n\n-- | Extend the environment with a new variable.\n@[simp]\ndef Env.extend (name : VarName) (v : \u03b1) (e: Env \u03b1) : Env \u03b1 :=\n  fun name' => if name = name' then v else e name'\n\n@[simp]\ndef Env.empty [Inhabited \u03b1] : Env \u03b1 :=\n  fun _ => default\n\n@[simp]\ndef Env.map (f : \u03b1 \u2192 \u03b2) (e : Env \u03b1) : Env \u03b2 :=\n  fun name => f (e name)\n\nnotation \"\u2205\" => Env.empty\nnotation e \"[\" name \"\u21a6\" 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 (<args>, <rgn1>, ... <rgnN>)\n  -- | Consider not allowing users to not be access all of 'Env'.\n  opcodeEval (op: opcode) (vals : Int \u00d7 Int) (rgns : (Int \u00d7 Int \u2192 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 \u2192 Type where\n| assign (ret : VarName) (op : opcode)\n  (args : VarName \u00d7 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 \u00d7 VarName) (body : AST opcode .Os) : AST opcode .R\n| rgn0 : AST opcode .R\n\ndef AST.retname : AST opcode .O \u2192 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) \u2192 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) := \u27e8Ops.ofList\u27e9\n\n@[simp, reducible]\ndef ASTKind.eval : ASTKind \u2192 Type\n| .O => Int\n| .Os => Int\n| .R => (Int \u00d7 Int \u2192 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 \u2192 astk.eval \u00d7 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 \u2192 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 \u00d7 Int \u2192 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 \u2192 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 \u2192 (astk.toCTree opcode) \u00d7 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 \u2192 Type\n| .O => Int\n| .R => Int \u00d7 Int \u2192 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 \u2192 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 \u2192 Opcode\nderiving Inhabited\n\ndef loopSemantics (n : Nat) (f : Int \u2192 Int) (v : Int) : Int :=\n  match n with\n  | 0 => v -- inline id\n  | n + 1 => f (loopSemantics n f v) -- inline \u2218\n\n@[simp]\ninstance :  UserSemantics Opcode  where\n  opcodeEval\n  | .not, \u27e8a, _\u27e9, _ => if a = 0 then 1 else 0\n  | .mul, \u27e8a, b\u27e9, _ => a * b\n  | .add, \u27e8a, b\u27e9, _ => a + b\n  | .const i, \u27e8_a, _b\u27e9, _ => i\n  | .run, \u27e8v, w\u27e9, r => r \u27e8v, w\u27e9\n  | .runnot, \u27e8v, w\u27e9, r => r \u27e8if v = 0 then 1 else 0, w\u27e9 -- execute: 'r(not v, w)'\n  | .loop, \u27e8n, init\u27e9, r => loopSemantics n.toNat (fun i => r \u27e8i, 0\u27e9) 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 \u27e8.x0, .x1\u27e9 $ Ops.ofList [\n      .assign .x2 .add (.x0, .x1) .rgn0 -- x2 := x0 + x1\n      ]\n  let q : AST Opcode .R :=\n    AST.rgn \u27e8.x0, .x1\u27e9 $ Ops.ofList [\n      .assign .x2 .run (.x0, .x1) (AST.rgn \u27e8.x5, .x6\u27e9 (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 \u27e8.x0, .x1\u27e9 $ Ops.ofList [\n      .assign .y1 .run \u27e8.x0, .x1\u27e9 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 (\u0393) := \u0393 \u00d7 list \u0393 \u00d7 list \u0393\n\ndef tape.mk {\u0393} [inhabited \u0393] (l : list \u0393) : tape \u0393 :=\n(l.head, [], l.tail)\n\ndef tape.mk' {\u0393} [inhabited \u0393] (L R : list \u0393) : tape \u0393 :=\n(R.head, L, R.tail)\n\ndef tape.move {\u0393} [inhabited \u0393] : dir \u2192 tape \u0393 \u2192 tape \u0393\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 {\u0393} [inhabited \u0393] : tape \u0393 \u2192 \u2124 \u2192 \u0393\n| (a, L, R) 0 := a\n| (a, L, R) (n+1:\u2115) := R.inth n\n| (a, L, R) -[1+ n] := L.inth n\n\n@[simp] theorem tape.nth_zero {\u0393} [inhabited \u0393] :\n  \u2200 (T : tape \u0393), T.nth 0 = T.1\n| (a, L, R) := rfl\n\n@[simp] theorem tape.move_left_nth {\u0393} [inhabited \u0393] :\n  \u2200 (T : tape \u0393) (i : \u2124), (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:\u2115)+1) := by rw add_sub_cancel; refl\n\n@[simp] theorem tape.move_right_nth {\u0393} [inhabited \u0393] :\n  \u2200 (T : tape \u0393) (i : \u2124), (T.move dir.right).nth i = T.nth (i+1)\n| (a, L, R) (n+1:\u2115)    := 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 {\u0393} (b : \u0393) : tape \u0393 \u2192 tape \u0393\n| (a, LR) := (b, LR)\n\n@[simp] theorem tape.write_self {\u0393} : \u2200 (T : tape \u0393), T.write T.1 = T\n| (a, LR) := rfl\n\n@[simp] theorem tape.write_nth {\u0393} [inhabited \u0393] (b : \u0393) :\n  \u2200 (T : tape \u0393) {i : \u2124}, (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:\u2115) := rfl\n| (a, L, R) -[1+ n] := rfl\n\ndef tape.map {\u0393 \u0393'} (f : \u0393 \u2192 \u0393') : tape \u0393 \u2192 tape \u0393'\n| (a, L, R) := (f a, L.map f, R.map f)\n\n@[simp] theorem tape.map_fst {\u0393 \u0393'} (f : \u0393 \u2192 \u0393') : \u2200 (T : tape \u0393), (T.map f).1 = f T.1\n| (a, L, R) := rfl\n\n@[simp] theorem tape.map_write {\u0393 \u0393'} (f : \u0393 \u2192 \u0393') (b : \u0393) :\n  \u2200 (T : tape \u0393), (T.write b).map f = (T.map f).write (f b)\n| (a, L, R) := rfl\n\n@[class] def pointed_map {\u0393 \u0393'} [inhabited \u0393] [inhabited \u0393'] (f : \u0393 \u2192 \u0393') :=\nf (default _) = default _\n\ntheorem tape.map_move {\u0393 \u0393'} [inhabited \u0393] [inhabited \u0393']\n  (f : \u0393 \u2192 \u0393') [pointed_map f] :\n  \u2200 (T : tape \u0393) 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 {\u0393 \u0393'} [inhabited \u0393] [inhabited \u0393']\n  (f : \u0393 \u2192 \u0393') [f0 : pointed_map f] :\n  \u2200 (l : list \u0393), (tape.mk l).map f = tape.mk (l.map f)\n| []     := by simpa! [tape.mk]\n| (a::l) := rfl\n\ndef eval {\u03c3} (f : \u03c3 \u2192 option \u03c3) : \u03c3 \u2192 roption \u03c3 :=\npfun.fix (\u03bb s, roption.some $\n  match f s with none := sum.inl s | some s' := sum.inr s' end)\n\ndef reaches {\u03c3} (f : \u03c3 \u2192 option \u03c3) : \u03c3 \u2192 \u03c3 \u2192 Prop :=\nrefl_trans_gen (\u03bb a b, b \u2208 f a)\n\ndef reaches\u2081 {\u03c3} (f : \u03c3 \u2192 option \u03c3) : \u03c3 \u2192 \u03c3 \u2192 Prop :=\ntrans_gen (\u03bb a b, b \u2208 f a)\n\ntheorem reaches\u2081_eq {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b c}\n  (h : f a = f b) : reaches\u2081 f a c \u2194 reaches\u2081 f b c :=\ntrans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm\n\ntheorem reaches_total {\u03c3} {f : \u03c3 \u2192 option \u03c3}\n  {a b c} : reaches f a b \u2192 reaches f a c \u2192\n  reaches f b c \u2228 reaches f c b :=\nrefl_trans_gen.total_of_right_unique $ \u03bb _ _ _, option.mem_unique\n\ntheorem reaches\u2081_fwd {\u03c3} {f : \u03c3 \u2192 option \u03c3}\n  {a b c} (h\u2081 : reaches\u2081 f a c) (h\u2082 : b \u2208 f a) : reaches f b c :=\nbegin\n  rcases trans_gen.head'_iff.1 h\u2081 with \u27e8b', hab, hbc\u27e9,\n  cases option.mem_unique hab h\u2082, exact hbc\nend\n\ndef reaches\u2080 {\u03c3} (f : \u03c3 \u2192 option \u03c3) (a b : \u03c3) : Prop :=\n\u2200 c, reaches\u2081 f b c \u2192 reaches\u2081 f a c\n\ntheorem reaches\u2080.trans {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b c : \u03c3}\n  (h\u2081 : reaches\u2080 f a b) (h\u2082 : reaches\u2080 f b c) : reaches\u2080 f a c\n| d h\u2083 := h\u2081 _ (h\u2082 _ h\u2083)\n\n@[refl] theorem reaches\u2080.refl {\u03c3} {f : \u03c3 \u2192 option \u03c3} (a : \u03c3) : reaches\u2080 f a a\n| b h := h\n\ntheorem reaches\u2080.single {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b : \u03c3}\n  (h : b \u2208 f a) : reaches\u2080 f a b\n| c h\u2082 := h\u2082.head h\n\ntheorem reaches\u2080.head {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b c : \u03c3}\n  (h : b \u2208 f a) (h\u2082 : reaches\u2080 f b c) : reaches\u2080 f a c :=\n(reaches\u2080.single h).trans h\u2082\n\ntheorem reaches\u2080.tail {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b c : \u03c3}\n  (h\u2081 : reaches\u2080 f a b) (h : c \u2208 f b) : reaches\u2080 f a c :=\nh\u2081.trans (reaches\u2080.single h)\n\ntheorem reaches\u2080_eq {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b}\n  (e : f a = f b) : reaches\u2080 f a b\n| d h := (reaches\u2081_eq e).2 h\n\ntheorem reaches\u2081.to\u2080 {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b : \u03c3}\n  (h : reaches\u2081 f a b) : reaches\u2080 f a b\n| c h\u2082 := h.trans h\u2082\n\ntheorem reaches.to\u2080 {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b : \u03c3}\n  (h : reaches f a b) : reaches\u2080 f a b\n| c h\u2082 := h\u2082.trans_right h\n\ntheorem reaches\u2080.tail' {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b c : \u03c3}\n  (h : reaches\u2080 f a b) (h\u2082 : c \u2208 f b) : reaches\u2081 f a c :=\nh _ (trans_gen.single h\u2082)\n\ntheorem mem_eval {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b} :\n  b \u2208 eval f a \u2194 reaches f a b \u2227 f b = none :=\n\u27e8\u03bb h, begin\n  refine pfun.fix_induction h (\u03bb 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 \u27e8refl_trans_gen.refl, e\u27e9 },\n  { rcases pfun.mem_fix_iff.1 h with h | \u27e8_, h, h'\u27e9;\n      rw e at h; cases roption.mem_some_iff.1 h,\n    cases IH a' h' (by rwa e) with h\u2081 h\u2082,\n    exact \u27e8refl_trans_gen.head e h\u2081, h\u2082\u27e9 }\nend, \u03bb \u27e8h\u2081, h\u2082\u27e9, begin\n  refine refl_trans_gen.head_induction_on h\u2081 _ (\u03bb a a' h _ IH, _),\n  { refine pfun.mem_fix_iff.2 (or.inl _),\n    rw h\u2082, apply roption.mem_some },\n  { refine pfun.mem_fix_iff.2 (or.inr \u27e8_, _, IH\u27e9),\n    rw show f a = _, from h,\n    apply roption.mem_some }\nend\u27e9\n\ntheorem eval_maximal\u2081 {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b}\n  (h : b \u2208 eval f a) (c) : \u00ac reaches\u2081 f b c | bc :=\nlet \u27e8ab, b0\u27e9 := mem_eval.1 h, \u27e8b', h', _\u27e9 := trans_gen.head'_iff.1 bc in\nby cases b0.symm.trans h'\n\ntheorem eval_maximal {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b}\n  (h : b \u2208 eval f a) {c} : reaches f b c \u2194 c = b :=\nlet \u27e8ab, b0\u27e9 := mem_eval.1 h in\nrefl_trans_gen_iff_eq $ \u03bb b' h', by cases b0.symm.trans h'\n\ntheorem reaches_eval {\u03c3} {f : \u03c3 \u2192 option \u03c3} {a b}\n  (ab : reaches f a b) : eval f a = eval f b :=\nroption.ext $ \u03bb c,\n \u27e8\u03bb h, let \u27e8ac, c0\u27e9 := mem_eval.1 h in\n    mem_eval.2 \u27e8(or_iff_left_of_imp $ by exact\n      \u03bb cb, (eval_maximal h).1 cb \u25b8 refl_trans_gen.refl).1\n      (reaches_total ab ac), c0\u27e9,\n  \u03bb h, let \u27e8bc, c0\u27e9 := mem_eval.1 h in mem_eval.2 \u27e8ab.trans bc, c0\u27e9,\u27e9\n\ndef respects {\u03c3\u2081 \u03c3\u2082}\n  (f\u2081 : \u03c3\u2081 \u2192 option \u03c3\u2081) (f\u2082 : \u03c3\u2082 \u2192 option \u03c3\u2082) (tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop) :=\n\u2200 \u2983a\u2081 a\u2082\u2984, tr a\u2081 a\u2082 \u2192 (match f\u2081 a\u2081 with\n  | some b\u2081 := \u2203 b\u2082, tr b\u2081 b\u2082 \u2227 reaches\u2081 f\u2082 a\u2082 b\u2082\n  | none := f\u2082 a\u2082 = none\n  end : Prop)\n\ntheorem tr_reaches\u2081 {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop}\n  (H : respects f\u2081 f\u2082 tr) {a\u2081 a\u2082} (aa : tr a\u2081 a\u2082) {b\u2081} (ab : reaches\u2081 f\u2081 a\u2081 b\u2081) :\n  \u2203 b\u2082, tr b\u2081 b\u2082 \u2227 reaches\u2081 f\u2082 a\u2082 b\u2082 :=\nbegin\n  induction ab with c\u2081 ac c\u2081 d\u2081 ac cd IH,\n  { have := H aa,\n    rwa (show f\u2081 a\u2081 = _, from ac) at this },\n  { rcases IH with \u27e8c\u2082, cc, ac\u2082\u27e9,\n    have := H cc,\n    rw (show f\u2081 c\u2081 = _, from cd) at this,\n    rcases this with \u27e8d\u2082, dd, cd\u2082\u27e9,\n    exact \u27e8_, dd, ac\u2082.trans cd\u2082\u27e9 }\nend\n\ntheorem tr_reaches {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop}\n  (H : respects f\u2081 f\u2082 tr) {a\u2081 a\u2082} (aa : tr a\u2081 a\u2082) {b\u2081} (ab : reaches f\u2081 a\u2081 b\u2081) :\n  \u2203 b\u2082, tr b\u2081 b\u2082 \u2227 reaches f\u2082 a\u2082 b\u2082 :=\nbegin\n  rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab,\n  { exact \u27e8_, aa, refl_trans_gen.refl\u27e9 },\n  { exact let \u27e8b\u2082, bb, h\u27e9 := tr_reaches\u2081 H aa ab in\n    \u27e8b\u2082, bb, h.to_refl\u27e9 }\nend\n\ntheorem tr_reaches_rev {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop}\n  (H : respects f\u2081 f\u2082 tr) {a\u2081 a\u2082} (aa : tr a\u2081 a\u2082) {b\u2082} (ab : reaches f\u2082 a\u2082 b\u2082) :\n  \u2203 c\u2081 c\u2082, reaches f\u2082 b\u2082 c\u2082 \u2227 tr c\u2081 c\u2082 \u2227 reaches f\u2081 a\u2081 c\u2081 :=\nbegin\n  induction ab with c\u2082 d\u2082 ac cd IH,\n  { exact \u27e8_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl\u27e9 },\n  { rcases IH with \u27e8e\u2081, e\u2082, ce, ee, ae\u27e9,\n    rcases refl_trans_gen.cases_head ce with rfl | \u27e8d', cd', de\u27e9,\n    { have := H ee, revert this,\n      cases eg : f\u2081 e\u2081 with g\u2081; simp [respects],\n      { intro c0, cases cd.symm.trans c0 },\n      { intros g\u2082 gg cg,\n        rcases trans_gen.head'_iff.1 cg with \u27e8d', cd', dg\u27e9,\n        cases option.mem_unique cd cd',\n        exact \u27e8_, _, dg, gg, ae.tail eg\u27e9 } },\n    { cases option.mem_unique cd cd',\n      exact \u27e8_, _, de, ee, ae\u27e9 } }\nend\n\ntheorem tr_eval {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop}\n  (H : respects f\u2081 f\u2082 tr) {a\u2081 b\u2081 a\u2082} (aa : tr a\u2081 a\u2082)\n  (ab : b\u2081 \u2208 eval f\u2081 a\u2081) : \u2203 b\u2082, tr b\u2081 b\u2082 \u2227 b\u2082 \u2208 eval f\u2082 a\u2082 :=\nbegin\n  cases mem_eval.1 ab with ab b0,\n  rcases tr_reaches H aa ab with \u27e8b\u2082, bb, ab\u27e9,\n  refine \u27e8_, bb, mem_eval.2 \u27e8ab, _\u27e9\u27e9,\n  have := H bb, rwa b0 at this\nend\n\ntheorem tr_eval_rev {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop}\n  (H : respects f\u2081 f\u2082 tr) {a\u2081 b\u2082 a\u2082} (aa : tr a\u2081 a\u2082)\n  (ab : b\u2082 \u2208 eval f\u2082 a\u2082) : \u2203 b\u2081, tr b\u2081 b\u2082 \u2227 b\u2081 \u2208 eval f\u2081 a\u2081 :=\nbegin\n  cases mem_eval.1 ab with ab b0,\n  rcases tr_reaches_rev H aa ab with \u27e8c\u2081, c\u2082, bc, cc, ac\u27e9,\n  cases (refl_trans_gen_iff_eq\n    (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc,\n  refine \u27e8_, cc, mem_eval.2 \u27e8ac, _\u27e9\u27e9,\n  have := H cc, cases f\u2081 c\u2081 with d\u2081, {refl},\n  rcases this with \u27e8d\u2082, dd, bd\u27e9,\n  rcases trans_gen.head'_iff.1 bd with \u27e8e, h, _\u27e9,\n  cases b0.symm.trans h\nend\n\ntheorem tr_eval_dom {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082 \u2192 Prop}\n  (H : respects f\u2081 f\u2082 tr) {a\u2081 a\u2082} (aa : tr a\u2081 a\u2082) :\n  (eval f\u2082 a\u2082).dom \u2194 (eval f\u2081 a\u2081).dom :=\n\u27e8\u03bb h, let \u27e8b\u2082, tr, h, _\u27e9 := tr_eval_rev H aa \u27e8h, rfl\u27e9 in h,\n \u03bb h, let \u27e8b\u2082, tr, h, _\u27e9 := tr_eval H aa \u27e8h, rfl\u27e9 in h\u27e9\n\ndef frespects {\u03c3\u2081 \u03c3\u2082} (f\u2082 : \u03c3\u2082 \u2192 option \u03c3\u2082) (tr : \u03c3\u2081 \u2192 \u03c3\u2082) (a\u2082 : \u03c3\u2082) : option \u03c3\u2081 \u2192 Prop\n| (some b\u2081) := reaches\u2081 f\u2082 a\u2082 (tr b\u2081)\n| none := f\u2082 a\u2082 = none\n\ntheorem frespects_eq {\u03c3\u2081 \u03c3\u2082} {f\u2082 : \u03c3\u2082 \u2192 option \u03c3\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082} {a\u2082 b\u2082}\n  (h : f\u2082 a\u2082 = f\u2082 b\u2082) : \u2200 {b\u2081}, frespects f\u2082 tr a\u2082 b\u2081 \u2194 frespects f\u2082 tr b\u2082 b\u2081\n| (some b\u2081) := reaches\u2081_eq h\n| none := by simp [frespects, h]\n\ntheorem fun_respects {\u03c3\u2081 \u03c3\u2082 f\u2081 f\u2082} {tr : \u03c3\u2081 \u2192 \u03c3\u2082} :\n  respects f\u2081 f\u2082 (\u03bb a b, tr a = b) \u2194 \u2200 \u2983a\u2081\u2984, frespects f\u2082 tr (tr a\u2081) (f\u2081 a\u2081) :=\nforall_congr $ \u03bb a\u2081, by cases f\u2081 a\u2081; simp [frespects, respects]\n\ntheorem tr_eval' {\u03c3\u2081 \u03c3\u2082}\n  (f\u2081 : \u03c3\u2081 \u2192 option \u03c3\u2081) (f\u2082 : \u03c3\u2082 \u2192 option \u03c3\u2082) (tr : \u03c3\u2081 \u2192 \u03c3\u2082)\n  (H : respects f\u2081 f\u2082 (\u03bb a b, tr a = b))\n  (a\u2081) : eval f\u2082 (tr a\u2081) = tr <$> eval f\u2081 a\u2081 :=\nroption.ext $ \u03bb b\u2082, by simp; exact\n \u27e8\u03bb h, let \u27e8b\u2081, bb, hb\u27e9 :=\n    tr_eval_rev H rfl h in \u27e8b\u2081, hb, bb\u27e9,\n  \u03bb \u27e8b\u2081, ab, bb\u27e9, begin\n    rcases tr_eval H rfl ab with \u27e8_, rfl, h\u27e9,\n    rwa bb at h\n  end\u27e9\n\ndef dwrite {K} [decidable_eq K] {C : K \u2192 Type*}\n  (S : \u2200 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 \u2192 Type*}\n  (S : \u2200 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 \u2192 Type*}\n  (S : \u2200 k, C k) (k') (l : C k') (k) (h : \u00ac 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 \u2192 Type*}\n  (S : \u2200 k, C k) (k) : dwrite S k (S k) = S :=\nfunext $ \u03bb k', by unfold dwrite; split_ifs; [subst h, refl]\n\nnamespace TM0\n\nsection\nparameters (\u0393 : Type*) [inhabited \u0393] -- type of tape symbols\nparameters (\u039b : Type*) [inhabited \u039b] -- 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 \u2192 stmt\n| write {} : \u0393 \u2192 stmt\n\n/-- A Post-Turing machine with symbol type `\u0393` and label type `\u039b`\n  is a function which, given the current state `q : \u039b` and\n  the tape head `a : \u0393`, either halts (returns `none`) or returns\n  a new state `q' : \u039b` and a `stmt` describing what to do,\n  either a move left or right, or a write command.\n  \n  Both `\u039b` and `\u0393` are required to be inhabited; the default value\n  for `\u0393` is the \"blank\" tape value, and the default value of `\u039b` is\n  the initial state. -/\ndef machine := \u039b \u2192 \u0393 \u2192 option (\u039b \u00d7 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 : \u039b)\n(tape : tape \u0393)\n\nparameters {\u0393 \u039b}\n/-- Execution semantics of the Turing machine. -/\ndef step (M : machine) : cfg \u2192 option cfg\n| \u27e8q, T\u27e9 := (M q T.1).map (\u03bb \u27e8q', a\u27e9, \u27e8q',\n  match a with\n  | stmt.move d := T.move d\n  | stmt.write a := T.write a\n  end\u27e9)\n\n/-- The statement `reaches M s\u2081 s\u2082` means that `s\u2082` is obtained\n  starting from `s\u2081` after a finite number of steps from `s\u2082`. -/\ndef reaches (M : machine) : cfg \u2192 cfg \u2192 Prop :=\nrefl_trans_gen (\u03bb a b, b \u2208 step M a)\n\n/-- The initial configuration. -/\ndef init (l : list \u0393) : cfg :=\n\u27e8default \u039b, tape.mk l\u27e9\n\n/-- Evaluate a Turing machine on initial input to a final state,\n  if it terminates. -/\ndef eval (M : machine) (l : list \u0393) : roption (list \u0393) :=\n(eval (step M) (init l)).map (\u03bb c, c.tape.2.2)\n\n/-- The raw definition of a Turing machine does not require that\n  `\u0393` and `\u039b` are finite, and in practice we will be interested\n  in the infinite `\u039b` 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 \u2286 \u039b`\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 \u039b) :=\ndefault \u039b \u2208 S \u2227 \u2200 {q a q' s}, (q', s) \u2208 M q a \u2192 q \u2208 S \u2192 q' \u2208 S\n\ntheorem step_supports (M : machine) {S}\n  (ss : supports M S) : \u2200 {c c' : cfg},\n  c' \u2208 step M c \u2192 c.q \u2208 S \u2192 c'.q \u2208 S\n| \u27e8q, T\u27e9 c' h\u2081 h\u2082 := begin\n  rcases option.map_eq_some'.1 h\u2081 with \u27e8\u27e8q', a\u27e9, h, rfl\u27e9,\n  exact ss.2 h h\u2082,\nend\n\ntheorem univ_supports (M : machine) : supports M set.univ :=\n\u27e8trivial, \u03bb q a q' s h\u2081 h\u2082, trivial\u27e9\n\nend\n\nsection\nvariables {\u0393 : Type*} [inhabited \u0393]\nvariables {\u0393' : Type*} [inhabited \u0393']\nvariables {\u039b : Type*} [inhabited \u039b]\nvariables {\u039b' : Type*} [inhabited \u039b']\n\ndef stmt.map (f : \u0393 \u2192 \u0393') : stmt \u0393 \u2192 stmt \u0393'\n| (stmt.move d)  := stmt.move d\n| (stmt.write a) := stmt.write (f a)\n\ndef cfg.map (f : \u0393 \u2192 \u0393') (g : \u039b \u2192 \u039b') : cfg \u0393 \u039b \u2192 cfg \u0393' \u039b'\n| \u27e8q, T\u27e9 := \u27e8g q, T.map f\u27e9\n\nvariables (M : machine \u0393 \u039b)\n  (f\u2081 : \u0393 \u2192 \u0393') (f\u2082 : \u0393' \u2192 \u0393) (g\u2081 : \u039b \u2192 \u039b') (g\u2082 : \u039b' \u2192 \u039b)\n\ndef machine.map : machine \u0393' \u039b'\n| q l := (M (g\u2082 q) (f\u2082 l)).map (prod.map g\u2081 (stmt.map f\u2081))\n\ntheorem machine.map_step {S} (ss : supports M S)\n  [pointed_map f\u2081] (f\u2082\u2081 : function.right_inverse f\u2081 f\u2082)\n  (g\u2082\u2081 : \u2200 q \u2208 S, g\u2082 (g\u2081 q) = q) :\n  \u2200 c : cfg \u0393 \u039b, c.q \u2208 S \u2192 \n    (step M c).map (cfg.map f\u2081 g\u2081) =\n    step (M.map f\u2081 f\u2082 g\u2081 g\u2082) (cfg.map f\u2081 g\u2081 c)\n| \u27e8q, T\u27e9 h := begin\n  simp! [g\u2082\u2081 q h, f\u2082\u2081 _],\n  rcases M q T.1 with _|\u27e8q', d|a\u27e9, {refl},\n  { simp! [tape.map_move f\u2081] },\n  { simp! }\nend\n\ntheorem map_init [pointed_map f\u2081] [g0 : pointed_map g\u2081] (l : list \u0393) :\n  (init l).map f\u2081 g\u2081 = init (l.map f\u2081) :=\nby simp [init, cfg.map]; exact \u27e8g0, tape.map_mk _ _\u27e9\n\ntheorem machine.map_respects {S} (ss : supports M S)\n  [pointed_map f\u2081] [pointed_map g\u2081]\n  (f\u2082\u2081 : function.right_inverse f\u2081 f\u2082)\n  (g\u2082\u2081 : \u2200 q \u2208 S, g\u2082 (g\u2081 q) = q) :\n  respects (step M) (step (M.map f\u2081 f\u2082 g\u2081 g\u2082))\n    (\u03bb a b, a.q \u2208 S \u2227 cfg.map f\u2081 g\u2081 a = b)\n| c _ \u27e8cs, rfl\u27e9 := begin\n  cases e : step M c with c'; simp!,\n  { rw [\u2190 M.map_step f\u2081 f\u2082 g\u2081 g\u2082 ss f\u2082\u2081 g\u2082\u2081 _ cs, e], refl },\n  { refine \u27e8_, \u27e8step_supports M ss e cs, rfl\u27e9, trans_gen.single _\u27e9,\n    rw [\u2190 M.map_step f\u2081 f\u2082 g\u2081 g\u2082 ss f\u2082\u2081 g\u2082\u2081 _ cs, e], exact rfl }\nend\n\nend\n\nend TM0\n\nnamespace TM1\n\nsection\nparameters (\u0393 : Type*) [inhabited \u0393] -- Type of tape symbols\nparameters (\u039b : Type*) -- Type of function labels\nparameters (\u03c3 : 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 `\u03c3` of variables\n  that may be accessed and updated at any time.\n  A machine is given by a `\u039b` 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 \u2192 stmt \u2192 stmt\n| write : (\u0393 \u2192 \u03c3 \u2192 \u0393) \u2192 stmt \u2192 stmt\n| load : (\u0393 \u2192 \u03c3 \u2192 \u03c3) \u2192 stmt \u2192 stmt\n| branch : (\u0393 \u2192 \u03c3 \u2192 bool) \u2192 stmt \u2192 stmt \u2192 stmt\n| goto {} : (\u0393 \u2192 \u03c3 \u2192 \u039b) \u2192 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 \u039b)\n(var : \u03c3)\n(tape : tape \u0393)\n\nparameters {\u0393 \u039b \u03c3}\n/-- The semantics of TM1 evaluation. -/\ndef step_aux : stmt \u2192 \u03c3 \u2192 tape \u0393 \u2192 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\u2081 q\u2082) v T :=\n  cond (p T.1 v) (step_aux q\u2081 v T) (step_aux q\u2082 v T)\n| (goto l)         v T := \u27e8some (l T.1 v), v, T\u27e9\n| halt             v T := \u27e8none, v, T\u27e9\n\ndef step (M : \u039b \u2192 stmt) : cfg \u2192 option cfg\n| \u27e8none,   v, T\u27e9 := none\n| \u27e8some l, v, T\u27e9 := some (step_aux (M l) v T)\n\nvariables [inhabited \u039b] [inhabited \u03c3]\ndef init (l : list \u0393) : cfg :=\n\u27e8some (default _), default _, tape.mk l\u27e9\n\ndef eval (M : \u039b \u2192 stmt) (l : list \u0393) : roption (list \u0393) :=\n(eval (step M) (init l)).map (\u03bb c, c.tape.2.2)\n\nvariables [fintype \u0393]\ndef supports_stmt (S : finset \u039b) : stmt \u2192 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\u2081 q\u2082) := supports_stmt q\u2081 \u2227 supports_stmt q\u2082\n| (goto l)         := \u2200 a v, l a v \u2208 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 : \u039b \u2192 stmt) (S : finset \u039b) :=\ndefault \u039b \u2208 S \u2227 \u2200 q \u2208 S, supports_stmt S (M q)\n\nlocal attribute [instance] classical.dec\nnoncomputable def stmts\u2081 : stmt \u2192 finset stmt\n| Q@(move d q)       := insert Q (stmts\u2081 q)\n| Q@(write a q)      := insert Q (stmts\u2081 q)\n| Q@(load s q)       := insert Q (stmts\u2081 q)\n| Q@(branch p q\u2081 q\u2082) := insert Q (stmts\u2081 q\u2081 \u222a stmts\u2081 q\u2082)\n| Q                  := {Q}\n\ntheorem stmts\u2081_self {q} : q \u2208 stmts\u2081 q :=\nby cases q; simp [stmts\u2081]\n\ntheorem stmts\u2081_trans {q\u2081 q\u2082} :\n  q\u2081 \u2208 stmts\u2081 q\u2082 \u2192 stmts\u2081 q\u2081 \u2286 stmts\u2081 q\u2082 :=\nbegin\n  intros h\u2081\u2082 q\u2080 h\u2080\u2081,\n  induction q\u2082 with _ q IH _ q IH _ q IH;\n    simp [stmts\u2081, finset.subset_iff] at h\u2081\u2082 \u22a2,\n  iterate 3 {\n    rcases h\u2081\u2082 with rfl | h\u2081\u2082,\n    { simp [stmts\u2081] at h\u2080\u2081, rcases h\u2080\u2081 with rfl | h; simp * },\n    { exact or.inr (IH h\u2081\u2082) } },\n  case TM1.stmt.branch : p q\u2081 q\u2082 IH\u2081 IH\u2082 {\n    rcases h\u2081\u2082 with rfl | h\u2081\u2082 | h\u2081\u2082,\n    { simp [stmts\u2081] at h\u2080\u2081, rcases h\u2080\u2081 with rfl | h; simp * },\n    { simp [IH\u2081 h\u2081\u2082] }, { simp [IH\u2082 h\u2081\u2082] } },\n  case TM1.stmt.goto : l {\n    subst h\u2081\u2082, simpa [stmts\u2081] using h\u2080\u2081 },\n  case TM1.stmt.halt {\n    subst h\u2081\u2082, simpa [stmts\u2081] using h\u2080\u2081 }\nend\n\ntheorem stmts\u2081_supports_stmt_mono {S q\u2081 q\u2082}\n  (h : q\u2081 \u2208 stmts\u2081 q\u2082) (hs : supports_stmt S q\u2082) : supports_stmt S q\u2081 :=\nbegin\n  induction q\u2082 with _ q IH _ q IH _ q IH;\n    simp [stmts\u2081, 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\u2081 q\u2082 IH\u2081 IH\u2082 {\n    rcases h with rfl | h | h, exacts [hs, IH\u2081 h hs.1, IH\u2082 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 : \u039b \u2192 stmt) (S : finset \u039b) : finset (option stmt) :=\n(S.bind (\u03bb q, stmts\u2081 (M q))).insert_none\n\ntheorem stmts_trans {M : \u039b \u2192 stmt} {S q\u2081 q\u2082}\n  (h\u2081 : q\u2081 \u2208 stmts\u2081 q\u2082) : some q\u2082 \u2208 stmts M S \u2192 some q\u2081 \u2208 stmts M S :=\nby simp [stmts]; exact \u03bb l ls h\u2082, \u27e8_, ls, stmts\u2081_trans h\u2082 h\u2081\u27e9\n\ntheorem stmts_supports_stmt {M : \u039b \u2192 stmt} {S q}\n  (ss : supports M S) : some q \u2208 stmts M S \u2192 supports_stmt S q :=\nby simp [stmts]; exact\n\u03bb l ls h, stmts\u2081_supports_stmt_mono h (ss.2 _ ls)\n\nlocal attribute [-simp] finset.mem_insert_none\ntheorem step_supports (M : \u039b \u2192 stmt) {S}\n  (ss : supports M S) : \u2200 {c c' : cfg},\n  c' \u2208 step M c \u2192 c.l \u2208 S.insert_none \u2192 c'.l \u2208 S.insert_none\n| \u27e8some l\u2081, v, T\u27e9 c' h\u2081 h\u2082 := begin\n  replace h\u2082 := ss.2 _ (finset.some_mem_insert_none.1 h\u2082),\n  simp [step] at h\u2081, subst c',\n  revert h\u2082, induction M l\u2081 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\u2081' q\u2082' IH\u2081 IH\u2082 {\n    simp [step_aux], cases p T.1 v,\n    { exact IH\u2082 _ _ hs.2 },\n    { exact IH\u2081 _ _ 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 {\u0393 : Type*} [inhabited \u0393]\nparameters {\u039b : Type*} [inhabited \u039b]\nparameters {\u03c3 : Type*} [inhabited \u03c3]\n\nlocal notation `stmt\u2081` := TM1.stmt \u0393 \u039b \u03c3\nlocal notation `cfg\u2081` := TM1.cfg \u0393 \u039b \u03c3\nlocal notation `stmt\u2080` := TM0.stmt \u0393\n\nparameters (M : \u039b \u2192 stmt\u2081)\ninclude M\n\ndef \u039b' := option stmt\u2081 \u00d7 \u03c3\ninstance : inhabited \u039b' := \u27e8(some (M (default _)), default _)\u27e9\n\nopen TM0.stmt\n\ndef tr_aux (s : \u0393) : stmt\u2081 \u2192 \u03c3 \u2192 \u039b' \u00d7 stmt\u2080\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\u2081 q\u2082) v := cond (p s v) (tr_aux q\u2081 v) (tr_aux q\u2082 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\u2080` := TM0.cfg \u0393 \u039b'\n\ndef tr : TM0.machine \u0393 \u039b'\n| (none,   v) s := none\n| (some q, v) s := some (tr_aux s q v)\n\ndef tr_cfg : cfg\u2081 \u2192 cfg\u2080\n| \u27e8l, v, T\u27e9 := \u27e8(l.map M, v), T\u27e9\n\ntheorem tr_respects : respects (TM1.step M) (TM0.step tr)\n  (\u03bb c\u2081 c\u2082, tr_cfg c\u2081 = c\u2082) :=\nfun_respects.2 $ \u03bb \u27e8l\u2081, v, T\u27e9, begin\n  cases l\u2081 with l\u2081, {exact rfl},\n  simp!,\n  induction M l\u2081 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\u2081_eq (by refl)).2 (IH _ _) },\n  case TM1.stmt.branch : p q\u2081 q\u2082 IH\u2081 IH\u2082 {\n    simp [TM1.step_aux], cases e : p T.1 v,\n    { exact (reaches\u2081_eq (by simp! [e])).2 (IH\u2082 _ _) },\n    { exact (reaches\u2081_eq (by simp! [e])).2 (IH\u2081 _ _) } },\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 \u0393] [fintype \u03c3]\nnoncomputable def tr_stmts (S : finset \u039b) : finset \u039b' :=\n(TM1.stmts M S).product finset.univ\n\nlocal attribute [instance] classical.dec\nlocal attribute [simp] TM1.stmts\u2081_self\ntheorem tr_supports {S : finset \u039b} (ss : TM1.supports M S) :\n  TM0.supports tr (\u2191(tr_stmts S)) :=\n\u27e8by simp [tr_stmts]; exact finset.some_mem_insert_none.2\n  (finset.mem_bind.2 \u27e8_, ss.1, TM1.stmts\u2081_self\u27e9),\n \u03bb q a q' s h\u2081 h\u2082, begin\n  rcases q with \u27e8_|q, v\u27e9, {cases h\u2081},\n  cases q' with q' v', simp [tr_stmts] at h\u2082 \u22a2,\n  cases q', {simp [TM1.stmts]},\n  simp [tr] at h\u2081,\n  have := TM1.stmts_supports_stmt ss h\u2082,\n  revert this, induction q generalizing v; intro hs,\n  case TM1.stmt.move : d q {\n    cases h\u2081, refine TM1.stmts_trans _ h\u2082, simp [TM1.stmts\u2081] },\n  case TM1.stmt.write : b q {\n    cases h\u2081, refine TM1.stmts_trans _ h\u2082, simp [TM1.stmts\u2081] },\n  case TM1.stmt.load : b q IH {\n    refine IH (TM1.stmts_trans _ h\u2082) _ h\u2081 hs, simp [TM1.stmts\u2081] },\n  case TM1.stmt.branch : p q\u2081 q\u2082 IH\u2081 IH\u2082 {\n    simp! at h\u2081, cases p a v,\n    { refine IH\u2082 (TM1.stmts_trans _ h\u2082) _ h\u2081 hs.2, simp [TM1.stmts\u2081] },\n    { refine IH\u2081 (TM1.stmts_trans _ h\u2082) _ h\u2081 hs.1, simp [TM1.stmts\u2081] } },\n  case TM1.stmt.goto : l {\n    cases h\u2081, exact finset.some_mem_insert_none.2\n      (finset.mem_bind.2 \u27e8_, hs _ _, TM1.stmts\u2081_self\u27e9) },\n  case TM1.stmt.halt { cases h\u2081 }\nend\u27e9\n\ntheorem tr_eval (l : list \u0393) : TM0.eval tr l = TM1.eval M l :=\n(congr_arg _ (tr_eval' _ _ _ tr_respects \u27e8some _, _, _\u27e9)).trans begin\n  simp [tr_cfg],\n  rw [roption.map_map, TM1.eval],\n  congr', exact funext (\u03bb \u27e8_, _, _\u27e9, 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 {\u0393 : Type*} [inhabited \u0393]\n\ntheorem exists_enc_dec [fintype \u0393] :\n  \u2203 n (enc : \u0393 \u2192 vector bool n) (dec : vector bool n \u2192 \u0393),\n    enc (default _) = vector.repeat ff n \u2227 \u2200 a, dec (enc a) = a :=\nbegin\n  rcases fintype.exists_equiv_fin \u0393 with \u27e8n, \u27e8F\u27e9\u27e9,\n  let G : fin n \u21aa fin n \u2192 bool := \u27e8\u03bb a b, a = b,\n    \u03bb a b h, by simpa using congr_fun h b\u27e9,\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 \u27e8_, enc, function.inv_fun enc,\n    H.set_value_eq _ _, function.left_inverse_inv_fun enc.2\u27e9\nend\n\nparameters {\u039b : Type*} [inhabited \u039b]\nparameters {\u03c3 : Type*} [inhabited \u03c3]\n\nlocal notation `stmt\u2081` := stmt \u0393 \u039b \u03c3\nlocal notation `cfg\u2081` := cfg \u0393 \u039b \u03c3\n\ninductive \u039b' : Type (max u_1 u_2 u_3)\n| normal : \u039b \u2192 \u039b'\n| write : \u0393 \u2192 stmt\u2081 \u2192 \u039b'\ninstance : inhabited \u039b' := \u27e8\u039b'.normal (default _)\u27e9\n\nlocal notation `stmt'` := stmt bool \u039b' \u03c3\nlocal notation `cfg'` := cfg bool \u039b' \u03c3\n\ndef read_aux : \u2200 n, (vector bool n \u2192 stmt') \u2192 stmt'\n| 0     f := f vector.nil\n| (i+1) f := stmt.branch (\u03bb a s, a)\n    (stmt.move dir.right $ read_aux i (\u03bb v, f (tt :: v)))\n    (stmt.move dir.right $ read_aux i (\u03bb v, f (ff :: v)))\n\nparameters {n : \u2115} (enc : \u0393 \u2192 vector bool n) (dec : vector bool n \u2192 \u0393)\n\ndef move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q\n\ndef read (f : \u0393 \u2192 stmt') : stmt' :=\nread_aux n (\u03bb v, move dir.left $ f (dec v))\n\ndef write : list bool \u2192 stmt' \u2192 stmt'\n| []       q := q\n| (a :: l) q := stmt.write (\u03bb _ _, a) $ stmt.move dir.right $ write l q\n\ndef tr_normal : stmt\u2081 \u2192 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 $ \u03bb a, stmt.goto $ \u03bb _ s, \u039b'.write (f a s) q\n| (stmt.load f q)         := read $ \u03bb a, stmt.load (\u03bb _ s, f a s) $ tr_normal q\n| (stmt.branch p q\u2081 q\u2082)   := read $ \u03bb a,\n  stmt.branch (\u03bb _ s, p a s) (tr_normal q\u2081) (tr_normal q\u2082)\n| (stmt.goto l)           := read $ \u03bb a,\n  stmt.goto (\u03bb _ s, \u039b'.normal (l a s))\n| stmt.halt               := move dir.right $ move dir.left $ stmt.halt\n\ndef tr_tape' (L R : list \u0393) : tape bool :=\ntape.mk'\n  (L.bind (\u03bb x, (enc x).to_list.reverse))\n  (R.bind (\u03bb x, (enc x).to_list) ++ [default _])\n\ndef tr_tape : tape \u0393 \u2192 tape bool\n| (a, L, R) := tr_tape' L (a :: R)\n\ntheorem tr_tape_drop_right : \u2200 R : list \u0393,\n  list.drop n (R.bind (\u03bb x, (enc x).to_list)) =\n  R.tail.bind (\u03bb 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 : \u2200 R : list \u0393,\n  list.take' n (R.bind (\u03bb 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 : \u039b \u2192 stmt\u2081)\n\ndef tr : \u039b' \u2192 stmt'\n| (\u039b'.normal l)  := tr_normal (M l)\n| (\u039b'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q\n\ndef tr_cfg : cfg\u2081 \u2192 cfg'\n| \u27e8l, v, T\u27e9 := \u27e8l.map \u039b'.normal, v, tr_tape T\u27e9\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 : \u2200 i R', default _ \u2208 R' \u2192\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 : \u2200 L' R' l\u2081 l\u2082\n      (hR : default _ \u2208 R')\n      (e : vector.to_list (enc a) = list.reverse_core l\u2081 l\u2082),\n      (tape.move dir.left^[l\u2081.length]) (tape.mk' (l\u2081 ++ L') (l\u2082 ++ 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\u2081 with b l\u2081 IH generalizing l\u2082,\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 : \u2200 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 : \u2200 L' R' l\u2081 l\u2082 : list bool,\n      (tape.move dir.right^[l\u2082.length]) (tape.mk' (l\u2081 ++ L') (l\u2082 ++ R')) =\n      tape.mk' (list.reverse_core l\u2082 l\u2081 ++ L') R',\n    { simpa using this _ _ [] (enc a).to_list },\n    intros, induction l\u2082 with b l\u2082 IH generalizing l\u2081, {refl},\n    simp [-add_comm, nat.iterate_succ],\n    exact IH (b::l\u2081) }\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 : \u2200 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, \u2190 nat.iterate_succ]\nend\n\nparameters (encdec : \u2200 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 : \u2200 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 : \u2200 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 : \u2200 i f L' R' l\u2081 l\u2082 h,\n      step_aux (read_aux i f) v\n        (tape.mk' (l\u2081 ++ L') (l\u2082 ++ R')) =\n      step_aux (f \u27e8l\u2082, h\u27e9) v\n        (tape.mk' (l\u2082.reverse_core l\u2081 ++ 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\u2082 with a l\u2082 IH generalizing l\u2081, {refl},\n    dsimp [read_aux, step_aux],\n    change (tape.mk' (l\u2081 ++ L') (a :: (l\u2082 ++ R'))).1 with a,\n    transitivity step_aux\n      (read_aux l\u2082.length (\u03bb v, f (a :: v))) v\n      (tape.mk' (a :: l\u2081 ++ L') (l\u2082 ++ 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 : \u2200 {L' R'} (l\u2081 l\u2082 l\u2082' : list bool)\n    (e : l\u2082'.length = l\u2082.length),\n    step_aux (write l\u2082 q) v (tape.mk' (l\u2081 ++ L') (l\u2082' ++ R')) =\n    step_aux q v (tape.mk' (list.reverse_core l\u2082 l\u2081 ++ L') R'),\n  from this [] _ _ ((enc b).2.trans (enc a).2.symm),\n  clear a b L R, intros,\n  induction l\u2082 with a l\u2082 IH generalizing l\u2081 l\u2082',\n  { cases list.length_eq_zero.1 e, refl },\n  cases l\u2082' with b l\u2082'; 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  (\u03bb c\u2081 c\u2082, tr_cfg c\u2081 = c\u2082) :=\nfun_respects.2 $ \u03bb \u27e8l\u2081, v, (a, L, R)\u27e9, begin\n  cases l\u2081 with l\u2081, {exact rfl},\n  suffices : \u2200 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\u2081, 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\u2081 q\u2082 IH\u2081 IH\u2082 {\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\u2082, apply IH\u2081] },\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 \u0393]\nnoncomputable def writes : stmt\u2081 \u2192 finset \u039b'\n| (stmt.move d q)       := writes q\n| (stmt.write f q)      := finset.univ.image (\u03bb a, \u039b'.write a q) \u222a writes q\n| (stmt.load f q)       := writes q\n| (stmt.branch p q\u2081 q\u2082) := writes q\u2081 \u222a writes q\u2082\n| (stmt.goto l)         := \u2205\n| stmt.halt             := \u2205\n\nnoncomputable def tr_supp (S : finset \u039b) : finset \u039b' :=\nS.bind (\u03bb l, insert (\u039b'.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 \u2200 {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} : \u2200 {f : \u0393 \u2192 stmt'},\n  (\u2200 a, supports_stmt S (f a)) \u2192 supports_stmt S (read f) :=\nsuffices \u2200 i (f : vector bool i \u2192 stmt'),\n  (\u2200 v, supports_stmt S (f v)) \u2192 supports_stmt S (read_aux i f),\nfrom \u03bb f hf, this n _ (by simp [hf]),\n\u03bb 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\u27e8by simp [tr_supp]; exact \u27e8_, ss.1, or.inl rfl\u27e9, \u03bb q h, begin\n  simp [tr_supp] at h,\n  suffices : \u2200 q, supports_stmt S q \u2192\n    (\u2200 q' \u2208 writes q, q' \u2208 tr_supp M S) \u2192\n    supports_stmt (tr_supp M S) (tr_normal dec q) \u2227\n    \u2200 q' \u2208 writes q, supports_stmt (tr_supp M S) (tr enc dec M q'),\n  { rcases h with \u27e8l, hl, h\u27e9,\n    have := this _ (ss.2 _ hl) (\u03bb q' hq,\n      by simp [tr_supp]; exact \u27e8_, hl, or.inr hq\u27e9),\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 \u22a2,\n    replace IH := IH hs hw, refine \u27e8_, IH.2\u27e9,\n    cases d; simp [tr_normal, IH] },\n  case TM1.stmt.write : f q IH {\n    simp [writes] at hw \u22a2,\n    replace IH := IH hs (\u03bb q hq, hw q (or.inl hq)),\n    refine \u27e8supports_stmt_read _ $ \u03bb a _ s,\n      hw _ (or.inr \u27e8_, rfl\u27e9), \u03bb q' hq, _\u27e9,\n    rcases hq with hq | \u27e8a, q\u2082, rfl\u27e9,\n    { exact IH.2 _ hq }, { simp [tr, IH.1] } },\n  case TM1.stmt.load : a q IH {\n    dsimp [writes] at hw \u22a2,\n    replace IH := IH hs hw,\n    refine \u27e8supports_stmt_read _ (\u03bb a, _), IH.2\u27e9,\n    simp [tr_normal, supports_stmt, IH.1] },\n  case TM1.stmt.branch : p q\u2081 q\u2082 IH\u2081 IH\u2082 {\n    simp [writes] at hw \u22a2,\n    replace IH\u2081 := IH\u2081 hs.1 (\u03bb q hq, hw q (or.inl hq)),\n    replace IH\u2082 := IH\u2082 hs.2 (\u03bb q hq, hw q (or.inr hq)),\n    exact \u27e8supports_stmt_read _ (\u03bb a, \u27e8IH\u2081.1, IH\u2082.1\u27e9),\n      \u03bb q, or.rec (IH\u2081.2 _) (IH\u2082.2 _)\u27e9 },\n  case TM1.stmt.goto : l {\n    simp [writes],\n    refine supports_stmt_read _ (\u03bb a _ s, _),\n    simp [tr_supp], exact \u27e8_, hs _ _, or.inl rfl\u27e9 },\n  case TM1.stmt.halt {\n    simp [supports_stmt, writes, tr_normal] }\nend\u27e9\n\nend\n\nend TM1to1\n\nnamespace TM0to1\n\nsection\nparameters {\u0393 : Type*} [inhabited \u0393]\nparameters {\u039b : Type*} [inhabited \u039b]\n\ninductive \u039b'\n| normal : \u039b \u2192 \u039b'\n| act : TM0.stmt \u0393 \u2192 \u039b \u2192 \u039b'\ninstance : inhabited \u039b' := \u27e8\u039b'.normal (default _)\u27e9\n\nlocal notation `cfg\u2080` := TM0.cfg \u0393 \u039b\nlocal notation `stmt\u2081` := TM1.stmt \u0393 \u039b' unit\nlocal notation `cfg\u2081` := TM1.cfg \u0393 \u039b' unit\n\nparameters (M : TM0.machine \u0393 \u039b)\n\nopen TM1.stmt\n\ndef tr : \u039b' \u2192 stmt\u2081\n| (\u039b'.normal q) :=\n  branch (\u03bb a _, (M q a).is_none) halt $\n  goto (\u03bb a _, match M q a with\n  | none := default _\n  | some (q', s) := \u039b'.act s q'\n  end)\n| (\u039b'.act (TM0.stmt.move d) q) :=\n  move d $ goto (\u03bb _ _, \u039b'.normal q)\n| (\u039b'.act (TM0.stmt.write a) q) :=\n  write (\u03bb _ _, a) $ goto (\u03bb _ _, \u039b'.normal q)\n\ndef tr_cfg : cfg\u2080 \u2192 cfg\u2081\n| \u27e8q, T\u27e9 := \u27e8cond (M q T.1).is_some\n  (some (\u039b'.normal q)) none, (), T\u27e9\n\ntheorem tr_respects : respects (TM0.step M) (TM1.step tr)\n  (\u03bb a b, tr_cfg a = b) :=\nfun_respects.2 $ \u03bb \u27e8q, T\u27e9, 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) \u27e8some (\u039b'.act s q'), (), T\u27e9 =\n    some \u27e8some (\u039b'.normal q'), (), TM0.step._match_1 T s\u27e9,\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 (\u0393 : K \u2192 Type*) -- Type of stack elements\nparameters (\u039b : Type*) -- Type of function labels\nparameters (\u03c3 : 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 {} : \u2200 k, (\u03c3 \u2192 \u0393 k) \u2192 stmt \u2192 stmt\n| peek {} : \u2200 k, (\u03c3 \u2192 option (\u0393 k) \u2192 \u03c3) \u2192 stmt \u2192 stmt\n| pop {} : \u2200 k, (\u03c3 \u2192 option (\u0393 k) \u2192 \u03c3) \u2192 stmt \u2192 stmt\n| load : (\u03c3 \u2192 \u03c3) \u2192 stmt \u2192 stmt\n| branch : (\u03c3 \u2192 bool) \u2192 stmt \u2192 stmt \u2192 stmt\n| goto {} : (\u03c3 \u2192 \u039b) \u2192 stmt\n| halt {} : stmt\nopen stmt\n\nstructure cfg :=\n(l : option \u039b)\n(var : \u03c3)\n(stk : \u2200 k, list (\u0393 k))\n\nparameters {\u0393 \u039b \u03c3 K}\ndef step_aux : stmt \u2192 \u03c3 \u2192 (\u2200 k, list (\u0393 k)) \u2192 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\u2081 q\u2082) v S :=\n  cond (f v) (step_aux q\u2081 v S) (step_aux q\u2082 v S)\n| (goto f)         v S := \u27e8some (f v), v, S\u27e9\n| halt             v S := \u27e8none, v, S\u27e9\n\ndef step (M : \u039b \u2192 stmt) : cfg \u2192 option cfg\n| \u27e8none,   v, S\u27e9 := none\n| \u27e8some l, v, S\u27e9 := some (step_aux (M l) v S)\n\ndef reaches (M : \u039b \u2192 stmt) : cfg \u2192 cfg \u2192 Prop :=\nrefl_trans_gen (\u03bb a b, b \u2208 step M a)\n\nvariables [inhabited \u039b] [inhabited \u03c3]\ndef init (k) (L : list (\u0393 k)) : cfg :=\n\u27e8some (default _), default _, dwrite (\u03bb _, []) k L\u27e9\n\ndef eval (M : \u039b \u2192 stmt) (k) (L : list (\u0393 k)) : roption (list (\u0393 k)) :=\n(eval (step M) (init k L)).map $ \u03bb c, c.stk k\n\nvariables [fintype K] [\u2200 k, fintype (\u0393 k)] [fintype \u03c3]\ndef supports_stmt (S : finset \u039b) : stmt \u2192 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\u2081 q\u2082) := supports_stmt q\u2081 \u2227 supports_stmt q\u2082\n| (goto l)         := \u2200 v, l v \u2208 S\n| halt             := true\n\ndef supports (M : \u039b \u2192 stmt) (S : finset \u039b) :=\ndefault \u039b \u2208 S \u2227 \u2200 q \u2208 S, supports_stmt S (M q)\n\nlocal attribute [instance] classical.dec\nnoncomputable def stmts\u2081 : stmt \u2192 finset stmt\n| Q@(push k f q)     := insert Q (stmts\u2081 q)\n| Q@(peek k f q)     := insert Q (stmts\u2081 q)\n| Q@(pop k f q)      := insert Q (stmts\u2081 q)\n| Q@(load a q)       := insert Q (stmts\u2081 q)\n| Q@(branch f q\u2081 q\u2082) := insert Q (stmts\u2081 q\u2081 \u222a stmts\u2081 q\u2082)\n| Q@(goto l)         := {Q}\n| Q@halt             := {Q}\n\ntheorem stmts\u2081_self {q} : q \u2208 stmts\u2081 q :=\nby cases q; simp [stmts\u2081]\n\ntheorem stmts\u2081_trans {q\u2081 q\u2082} :\n  q\u2081 \u2208 stmts\u2081 q\u2082 \u2192 stmts\u2081 q\u2081 \u2286 stmts\u2081 q\u2082 :=\nbegin\n  intros h\u2081\u2082 q\u2080 h\u2080\u2081,\n  induction q\u2082 with _ _ q IH _ _ q IH _ _ q IH _ q IH;\n    simp [stmts\u2081, finset.subset_iff] at h\u2081\u2082 \u22a2,\n  iterate 4 {\n    rcases h\u2081\u2082 with rfl | h\u2081\u2082,\n    { simp [stmts\u2081] at h\u2080\u2081, rcases h\u2080\u2081 with rfl | h; simp * },\n    { exact or.inr (IH h\u2081\u2082) } },\n  case TM2.stmt.branch : f q\u2081 q\u2082 IH\u2081 IH\u2082 {\n    rcases h\u2081\u2082 with rfl | h\u2081\u2082 | h\u2081\u2082,\n    { simp [stmts\u2081] at h\u2080\u2081, rcases h\u2080\u2081 with rfl | h; simp * },\n    { simp [IH\u2081 h\u2081\u2082] }, { simp [IH\u2082 h\u2081\u2082] } },\n  case TM2.stmt.goto : l {\n    subst h\u2081\u2082, simpa [stmts\u2081] using h\u2080\u2081 },\n  case TM2.stmt.halt {\n    subst h\u2081\u2082, simpa [stmts\u2081] using h\u2080\u2081 }\nend\n\ntheorem stmts\u2081_supports_stmt_mono {S q\u2081 q\u2082}\n  (h : q\u2081 \u2208 stmts\u2081 q\u2082) (hs : supports_stmt S q\u2082) : supports_stmt S q\u2081 :=\nbegin\n  induction q\u2082 with _ _ q IH _ _ q IH _ _ q IH _ q IH;\n    simp [stmts\u2081, 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\u2081 q\u2082 IH\u2081 IH\u2082 {\n    rcases h with rfl | h | h, exacts [hs, IH\u2081 h hs.1, IH\u2082 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 : \u039b \u2192 stmt) (S : finset \u039b) : finset (option stmt) :=\n(S.bind (\u03bb q, stmts\u2081 (M q))).insert_none\n\ntheorem stmts_trans {M : \u039b \u2192 stmt} {S q\u2081 q\u2082}\n  (h\u2081 : q\u2081 \u2208 stmts\u2081 q\u2082) : some q\u2082 \u2208 stmts M S \u2192 some q\u2081 \u2208 stmts M S :=\nby simp [stmts]; exact \u03bb l ls h\u2082, \u27e8_, ls, stmts\u2081_trans h\u2082 h\u2081\u27e9\n\ntheorem stmts_supports_stmt {M : \u039b \u2192 stmt} {S q}\n  (ss : supports M S) : some q \u2208 stmts M S \u2192 supports_stmt S q :=\nby simp [stmts]; exact\n\u03bb l ls h, stmts\u2081_supports_stmt_mono h (ss.2 _ ls)\n\nlocal attribute [-simp] finset.mem_insert_none\ntheorem step_supports (M : \u039b \u2192 stmt) {S}\n  (ss : supports M S) : \u2200 {c c' : cfg},\n  c' \u2208 step M c \u2192 c.l \u2208 S.insert_none \u2192 c'.l \u2208 S.insert_none\n| \u27e8some l\u2081, v, T\u27e9 c' h\u2081 h\u2082 := begin\n  replace h\u2082 := ss.2 _ (finset.some_mem_insert_none.1 h\u2082),\n  simp [step] at h\u2081, subst c',\n  revert h\u2082, induction M l\u2081 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\u2081' q\u2082' IH\u2081 IH\u2082 {\n    simp [step_aux], cases p v,\n    { exact IH\u2082 _ _ hs.2 },\n    { exact IH\u2081 _ _ 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 {\u0393 : K \u2192 Type*}\nparameters {\u039b : Type*} [inhabited \u039b]\nparameters {\u03c3 : Type*} [inhabited \u03c3]\n\nlocal notation `stmt\u2082` := TM2.stmt \u0393 \u039b \u03c3\nlocal notation `cfg\u2082` := TM2.cfg \u0393 \u039b \u03c3\n\ninductive stackel (k : K)\n| val : \u0393 k \u2192 stackel\n| bottom : stackel\n| top : stackel\n\ninstance stackel.inhabited (k) : inhabited (stackel k) :=\n\u27e8stackel.top _\u27e9\n\ndef stackel.is_bottom {k} : stackel k \u2192 bool\n| (stackel.bottom _) := tt\n| _ := ff \n\ndef stackel.is_top {k} : stackel k \u2192 bool\n| (stackel.top _) := tt\n| _ := ff \n\ndef stackel.get {k} : stackel k \u2192 option (\u0393 k)\n| (stackel.val a) := some a\n| _ := none\n\nsection\nopen stackel\n\ndef stackel_equiv {k} : stackel k \u2243 option (option (\u0393 k)) :=\nbegin\n  refine \u27e8\u03bb s, _, \u03bb s, _, _, _\u27e9,\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 \u0393' := \u2200 k, stackel k\n\ninstance \u0393'.inhabited : inhabited \u0393' := \u27e8\u03bb _, default _\u27e9\n\ninstance stackel.fintype {k} [fintype (\u0393 k)] : fintype (stackel k) :=\nfintype.of_equiv _ stackel_equiv.symm\n\ninstance \u0393'.fintype [fintype K] [\u2200 k, fintype (\u0393 k)] : fintype \u0393' :=\npi.fintype\n\ninductive st_act (k : K)\n| push {} : (\u03c3 \u2192 \u0393 k) \u2192 st_act\n| pop {} : bool \u2192 (\u03c3 \u2192 option (\u0393 k) \u2192 \u03c3) \u2192 st_act\n\nsection\nopen st_act\n\ndef st_run {k : K} : st_act k \u2192 stmt\u2082 \u2192 stmt\u2082\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 : \u03c3) (l : list (\u0393 k)) : st_act k \u2192 \u03c3\n| (push f)  := v\n| (pop b f) := f v l.head'\n\ndef st_write {k : K} (v : \u03c3) (l : list (\u0393 k)) : st_act k \u2192 list (\u0393 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\u2082 \u2192 Sort l}\n  (H\u2081 : \u03a0 k (s : st_act k) q (IH : C q), C (st_run s q))\n  (H\u2082 : \u03a0 a q (IH : C q), C (TM2.stmt.load a q))\n  (H\u2083 : \u03a0 p q\u2081 q\u2082 (IH\u2081 : C q\u2081) (IH\u2082 : C q\u2082), C (TM2.stmt.branch p q\u2081 q\u2082))\n  (H\u2084 : \u03a0 l, C (TM2.stmt.goto l))\n  (H\u2085 : C TM2.stmt.halt) : \u2200 n, C n\n| (TM2.stmt.push k f q)     := H\u2081 _ (push f) _ (stmt_st_rec q)\n| (TM2.stmt.peek k f q)     := H\u2081 _ (pop ff f) _ (stmt_st_rec q)\n| (TM2.stmt.pop k f q)      := H\u2081 _ (pop tt f) _ (stmt_st_rec q)\n| (TM2.stmt.load a q)       := H\u2082 _ _ (stmt_st_rec q)\n| (TM2.stmt.branch a q\u2081 q\u2082) := H\u2083 _ _ _ (stmt_st_rec q\u2081) (stmt_st_rec q\u2082)\n| (TM2.stmt.goto l)         := H\u2084 _\n| TM2.stmt.halt             := H\u2085\n\ntheorem supports_run [fintype K] [\u2200 k, fintype (\u0393 k)] [fintype \u03c3]\n  (S : finset \u039b) {k} (s : st_act k) (q) :\n  TM2.supports_stmt S (st_run s q) \u2194 TM2.supports_stmt S q :=\nby rcases s with _|_|_; refl\n\nend\n\ninductive \u039b' : Type (max u_1 u_2 u_3 u_4)\n| normal {} : \u039b \u2192 \u039b'\n| go (k) : st_act k \u2192 stmt\u2082 \u2192 \u039b'\n| ret {} : K \u2192 stmt\u2082 \u2192 \u039b'\nopen \u039b'\ninstance : inhabited \u039b' := \u27e8normal (default _)\u27e9\n\nlocal notation `stmt\u2081` := TM1.stmt \u0393' \u039b' \u03c3\nlocal notation `cfg\u2081` := TM1.cfg \u0393' \u039b' \u03c3\n\nopen TM1.stmt\n\ndef tr_st_act {k} (q : stmt\u2081) : st_act k \u2192 stmt\u2081\n| (st_act.push f) :=\n  write (\u03bb a s, dwrite a k $ stackel.val $ f s) $\n  move dir.right $\n  write (\u03bb a s, dwrite a k $ stackel.top k) q\n| (st_act.pop b f) :=\n  move dir.left $\n  load (\u03bb a s, f s (a k).get) $\n  cond b\n  ( branch (\u03bb a s, (a k).is_bottom)\n    ( move dir.right q )\n    ( move dir.right $\n      write (\u03bb a s, dwrite a k $ default _) $\n      move dir.left $\n      write (\u03bb a s, dwrite a k $ stackel.top k) q ) )\n  ( move dir.right q )\n\ndef tr_init (k) (L : list (\u0393 k)) : list \u0393' :=\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) : \u2200 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\u2082 \u2192 stmt\u2081\n| (TM2.stmt.push k f q)     := goto (\u03bb _ _, go k (st_act.push f) q)\n| (TM2.stmt.peek k f q)     := goto (\u03bb _ _, go k (st_act.pop ff f) q)\n| (TM2.stmt.pop k f q)      := goto (\u03bb _ _, go k (st_act.pop tt f) q)\n| (TM2.stmt.load a q)       := load (\u03bb _, a) (tr_normal q)\n| (TM2.stmt.branch f q\u2081 q\u2082) := branch (\u03bb a, f) (tr_normal q\u2081) (tr_normal q\u2082)\n| (TM2.stmt.goto l)         := goto (\u03bb 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 (\u03bb _ _, go k s q) :=\nby rcases s with _|_|_; refl\n\nparameters (M : \u039b \u2192 stmt\u2082)\ninclude M\n\ndef tr : \u039b' \u2192 stmt\u2081\n| (normal q) := tr_normal (M q)\n| (go k s q) :=\n  branch (\u03bb a s, (a k).is_top) (tr_st_act (goto (\u03bb _ _, ret k q)) s)\n    (move dir.right $ goto (\u03bb _ _, go k s q))\n| (ret k q) :=\n  branch (\u03bb a s, (a k).is_bottom) (tr_normal q)\n    (move dir.left $ goto (\u03bb _ _, ret k q))\n\ndef tr_stk {k} (S : list (\u0393 k)) (L : list (stackel k)) : Prop :=\n\u2203 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\u2082 \u2192 cfg\u2081 \u2192 Prop\n| mk {q v} {S : \u2200 k, list (\u0393 k)} {L : list \u0393'} :\n  (\u2200 k, tr_stk (S k) (L.map (\u03bb a, a k))) \u2192\n  tr_cfg \u27e8q, v, S\u27e9 \u27e8q.map normal, v, (stackel.bottom, [], L)\u27e9\n\ntheorem tr_respects_aux\u2081 {k} (o q v) : \u2200 S\u2081 {s S\u2082} {T : list \u0393'},\n  T.map (\u03bb (a : \u0393'), a k) = (list.map stackel.val S\u2081).reverse_core (s :: S\u2082) \u2192\n  \u2203 a T\u2081 T\u2082,\n    T = list.reverse_core T\u2081 (a :: T\u2082) \u2227\n    a k = s \u2227\n    T\u2081.map (\u03bb (a : \u0393'), a k) = S\u2081.map stackel.val \u2227\n    T\u2082.map (\u03bb (a : \u0393'), a k) = S\u2082 \u2227\n    reaches\u2080 (TM1.step tr)\n      \u27e8some (go k o q), v, (stackel.bottom, [], T)\u27e9\n      \u27e8some (go k o q), v, (a, T\u2081 ++ [stackel.bottom], T\u2082)\u27e9\n| [] s S\u2082 (a :: T) hT := by injection hT with es e\u2082; exact\n  \u27e8a, [], _, rfl, es, rfl, e\u2082, reaches\u2080.single rfl\u27e9\n| (s' :: S\u2081) s S\u2082 T hT :=\n  let \u27e8a, T\u2081, b'::T\u2082, e, es', e\u2081, e\u2082, H\u27e9 := tr_respects_aux\u2081 S\u2081 hT in\n  by injection e\u2082 with es e\u2082; exact\n  \u27e8b', a::T\u2081, T\u2082, e, es, by simpa [es'], e\u2082, H.tail (by simp! [es'])\u27e9\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\u2082\n  {k q v} {S : \u03a0 k, list (\u0393 k)} {T\u2081 T\u2082 : list \u0393'} {a : \u0393'}\n  (hT : \u2200 k, tr_stk (S k) ((T\u2081.reverse_core (a :: T\u2082)).map (\u03bb (a : \u0393'), a k)))\n  (e\u2081 : T\u2081.map (\u03bb (a : \u0393'), 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' : \u2200 k, list (\u0393 k) := dwrite S k Sk' in\n  \u2203 b (T\u2081' T\u2082' : list \u0393'),\n    (\u2200 (k' : K), tr_stk (S' k') ((T\u2081'.reverse_core (b :: T\u2082')).map (\u03bb (a : \u0393'), a k'))) \u2227\n    T\u2081'.map (\u03bb a, a k) = Sk'.map stackel.val \u2227\n    b k = stackel.top k \u2227\n    TM1.step_aux (tr_st_act q o) v (a, T\u2081 ++ [stackel.bottom], T\u2082) =\n    TM1.step_aux q v' (b, T\u2081' ++ [stackel.bottom], T\u2082') :=\nbegin\n  dsimp, cases o with f b f,\n  { -- push\n    refine \u27e8_, dwrite a k (stackel.val (f v)) :: T\u2081,\n      _, _, by simp [e\u2081]; refl, by simp, rfl\u27e9,\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\u2081, list.append_left_inj] at e \u22a2,\n      simp [e] },\n    { cases T\u2082 with t T\u2082,\n      { existsi n+1,\n        simpa [h, list.reverse_core_eq, e\u2081, list.repeat_add] using\n          congr_arg (++ [default \u0393' k']) e },\n      { existsi n,\n        simpa [h, list.reverse_core_eq] using e } } },\n  have dw := dwrite_self S k,\n  cases T\u2081 with t T\u2081; cases eS : S k with s Sk;\n    rw eS at e\u2081 dw; injection e\u2081 with tk e\u2081'; cases b,\n  { -- peek nil\n    simp [eS, dw],\n    exact \u27e8_, [], _, hT, rfl, ea, rfl\u27e9 },\n  { -- pop nil\n    simp [eS, dw],\n    exact \u27e8_, [], _, hT, rfl, ea, rfl\u27e9 },\n  { -- peek cons\n    dsimp at tk,\n    simp [eS, tk, dw],\n    exact \u27e8_, t::T\u2081, _, hT, e\u2081, ea, rfl\u27e9 },\n  { -- pop cons\n    dsimp at tk,\n    simp [eS, tk],\n    refine \u27e8_, _, _, _, e\u2081', by simp, rfl\u27e9,\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\u2081', list.append_left_inj] at e \u22a2,\n      simp [e] },\n    { existsi n, simpa [h, list.map_reverse_core] using e } },\nend\n\ntheorem tr_respects_aux\u2083 {k q v}\n  {S : \u03a0 k, list (\u0393 k)} {T : list \u0393'}\n  (hT : \u2200 k, tr_stk (S k) (T.map (\u03bb (a : \u0393'), a k))) :\n  \u2200 (T\u2081 : list \u0393') {T\u2082 : list \u0393'} {a : \u0393'} {S\u2081}\n    (e : T = T\u2081.reverse_core (a :: T\u2082))\n    (ha : (a k).is_bottom = ff)\n    (e\u2081 : T\u2081.map (\u03bb (a : \u0393'), a k) = list.map stackel.val S\u2081),\n    reaches\u2080 (TM1.step tr)\n      \u27e8some (ret k q), v, (a, T\u2081 ++ [stackel.bottom], T\u2082)\u27e9\n      \u27e8some (ret k q), v, (stackel.bottom, [], T)\u27e9\n| [] T\u2082 a S\u2081 e ha e\u2081 := reaches\u2080.single (by simp [ha, e])\n| (b :: T\u2081) T\u2082 a (s :: S\u2081) e ha e\u2081 := begin\n    injection e\u2081 with es e\u2081, dsimp at es,\n    refine reaches\u2080.head _ (tr_respects_aux\u2083 T\u2081 e (by simp [es]) e\u2081),\n    simp [ha]\n  end\n\ntheorem tr_respects_aux {q v T k} {S : \u03a0 k, list (\u0393 k)}\n  (hT : \u2200 (k : K), tr_stk (S k) (list.map (\u03bb (a : \u0393'), a k) T))\n  (o : st_act k)\n  (IH : \u2200 {v : \u03c3} {S : \u03a0 (k : K), list (\u0393 k)} {T : list \u0393'},\n    (\u2200 (k : K), tr_stk (S k) (list.map (\u03bb (a : \u0393'), a k) T)) \u2192\n    (\u2203 b, tr_cfg (TM2.step_aux q v S) b \u2227\n      reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (stackel.bottom, [], T)) b)) :\n  \u2203 b, tr_cfg (TM2.step_aux (st_run o q) v S) b \u2227\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 \u27e8n, hTk\u27e9,\n  simp [tr_normal_run],\n  rcases tr_respects_aux\u2081 M o q v _ hTk with \u27e8a, T\u2081, T\u2082, rfl, ea, e\u2081, e\u2082, hgo\u27e9,\n  rcases tr_respects_aux\u2082 M hT e\u2081 ea _ with \u27e8b, T\u2081', T\u2082', hT', e\u2081', eb, hrun\u27e9,\n  have hret := tr_respects_aux\u2083 M hT' _ rfl (by simp [eb]) e\u2081',\n  have := hgo.tail' rfl,\n  simp [ea, tr] at this, rw [hrun, TM1.step_aux] at this,\n  rcases IH hT' with \u27e8c, gc, rc\u27e9,\n  simp [step_run],\n  refine \u27e8c, gc, (this.to\u2080.trans hret _ (trans_gen.head' rfl rc)).to_refl\u27e9\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\u03bb c\u2081 c\u2082 h, begin\n  cases h with l v S L hT, clear h,\n  cases l; simp!,\n  suffices : \u2203 b, _ \u2227 reaches (TM1.step (tr M)) _ _,\n  from let \u27e8b, c, r\u27e9 := this in \u27e8b, c, trans_gen.head' rfl r\u27e9,\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\u2082 hT, exact IH\u2081 hT] },\n  { exact \u27e8_, \u27e8hT\u27e9, refl_trans_gen.refl\u27e9 },\n  { exact \u27e8_, \u27e8hT\u27e9, refl_trans_gen.refl\u27e9 }\nend\n\ntheorem tr_cfg_init (k) (L : list (\u0393 k)) :\n  tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) :=\n\u27e8\u03bb k', begin\n  simp [tr_init, (\u2218)],\n  cases e : L.reverse with a L'; simp [tr_init],\n  { cases list.reverse_eq_nil.1 e, simp, exact \u27e80, rfl\u27e9 },\n  by_cases k' = k,\n  { subst k', existsi 0,\n    simp [list.reverse_core_eq, (\u2218)],\n    rw [\u2190 list.map_reverse, e], refl },\n  { simp [h, (\u2218)],\n    existsi L'.length + 1,\n    rw list.repeat_add, refl }\nend\u27e9\n\ntheorem tr_eval_dom (k) (L : list (\u0393 k)) :\n  (TM1.eval tr (tr_init k L)).dom \u2194 (TM2.eval M k L).dom :=\ntr_eval_dom tr_respects (tr_cfg_init _ _)\n\ntheorem tr_eval (k) (L : list (\u0393 k)) {L\u2081 L\u2082}\n  (H\u2081 : L\u2081 \u2208 TM1.eval tr (tr_init k L))\n  (H\u2082 : L\u2082 \u2208 TM2.eval M k L) :\n  \u2203 S : \u2200 k, list (\u0393 k),\n    (\u2200 k', tr_stk (S k') (L\u2081.map (\u03bb a, a k'))) \u2227 S k = L\u2082 :=\nbegin\n  rcases (roption.mem_map_iff _).1 H\u2081 with \u27e8c\u2081, h\u2081, rfl\u27e9,\n  rcases (roption.mem_map_iff _).1 H\u2082 with \u27e8c\u2082, h\u2082, rfl\u27e9,\n  rcases tr_eval (tr_respects M) (tr_cfg_init M k L) h\u2082\n    with \u27e8_, \u27e8q, v, S, L\u2081', hT\u27e9, h\u2083\u27e9,\n  cases roption.mem_unique h\u2081 h\u2083,\n  exact \u27e8S, hT, rfl\u27e9\nend\n\nvariables [fintype K] [\u2200 k, fintype (\u0393 k)] [fintype \u03c3]\nlocal attribute [instance] classical.dec\nlocal attribute [simp] TM2.stmts\u2081_self\n\nnoncomputable def tr_stmts\u2081 : stmt\u2082 \u2192 finset \u039b'\n| Q@(TM2.stmt.push k f q)     := {go k (st_act.push f) q, ret k q} \u222a tr_stmts\u2081 q\n| Q@(TM2.stmt.peek k f q)     := {go k (st_act.pop ff f) q, ret k q} \u222a tr_stmts\u2081 q\n| Q@(TM2.stmt.pop k f q)      := {go k (st_act.pop tt f) q, ret k q} \u222a tr_stmts\u2081 q\n| Q@(TM2.stmt.load a q)       := tr_stmts\u2081 q\n| Q@(TM2.stmt.branch f q\u2081 q\u2082) := tr_stmts\u2081 q\u2081 \u222a tr_stmts\u2081 q\u2082\n| _                           := \u2205\n\ntheorem tr_stmts\u2081_run {k s q} : tr_stmts\u2081 (st_run s q) = {go k s q, ret k q} \u222a tr_stmts\u2081 q :=\nby rcases s with _|_|_; dsimp [tr_stmts\u2081, st_run]; congr\n\nnoncomputable def tr_supp (S : finset \u039b) : finset \u039b' :=\nS.bind (\u03bb l, insert (normal l) (tr_stmts\u2081 (M l)))\n\nlocal attribute [simp] tr_stmts\u2081 tr_stmts\u2081_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\u27e8finset.mem_bind.2 \u27e8_, ss.1, finset.mem_insert.2 $ or.inl rfl\u27e9,\n\u03bb l' h, begin\n  suffices : \u2200 q (ss' : TM2.supports_stmt S q)\n    (sub : \u2200 x \u2208 tr_stmts\u2081 M q, x \u2208 tr_supp M S),\n    TM1.supports_stmt (tr_supp M S) (tr_normal q) \u2227\n    (\u2200 l' \u2208 tr_stmts\u2081 M q, TM1.supports_stmt (tr_supp M S) (tr M l')),\n  { simp [tr_supp] at h,\n    rcases h with \u27e8l, lS, h\u27e9,\n    have := this _ (ss.2 l lS) (\u03bb x hx,\n      finset.mem_bind.2 \u27e8_, lS, finset.mem_insert_of_mem hx\u27e9),\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' (\u03bb x hx, sub x $ or.inr $ or.inl hx) with IH\u2081 IH\u2082,\n    refine \u27e8by simp [hgo], \u03bb l h, _\u27e9,\n    rw [tr_stmts\u2081_run] at h, simp at h,\n    rcases h with rfl | h | rfl,\n    { simp [hret], exact IH\u2081 },\n    { exact IH\u2082 _ h },\n    { simp [hgo],\n      rcases s with _|_|_; simp! [hret] } },\n  { -- load\n    dsimp at sub \u22a2, exact IH ss' sub },\n  { -- branch\n    simp at sub,\n    cases IH\u2081 ss'.1 (\u03bb x hx, sub x $ or.inl hx) with IH\u2081\u2081 IH\u2081\u2082,\n    cases IH\u2082 ss'.2 (\u03bb x hx, sub x $ or.inr hx) with IH\u2082\u2081 IH\u2082\u2082,\n    refine \u27e8\u27e8IH\u2081\u2081, IH\u2082\u2081\u27e9, \u03bb l h, _\u27e9,\n    rw [tr_stmts\u2081] at h, simp at h,\n    rcases h with h | h; [exact IH\u2081\u2082 _ h, exact IH\u2082\u2082 _ h] },\n  { -- goto\n    rw tr_stmts\u2081, simp [tr_normal],\n    exact \u03bb v, finset.mem_bind.2 \u27e8_, ss' v, by simp\u27e9 },\n  { simp } -- halt\nend\u27e9\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": "import tactic.cache\n\nmeta def assert_frozen_instances : tactic unit := do\nfrozen \u2190 tactic.frozen_local_instances,\nwhen frozen.is_none $ tactic.fail \"instances are not frozen\"\n\nexample (\u03b1) (a : \u03b1) :=\nbegin\n  haveI h : inhabited \u03b1 := \u27e8a\u27e9,\n  assert_frozen_instances,\n  exact (default : \u03b1)\nend\n\nexample (\u03b1) (a : \u03b1) :=\nbegin\n  haveI h := inhabited.mk a,\n  assert_frozen_instances,\n  exact (default : \u03b1)\nend\n\nexample (\u03b1) (a : \u03b1) :=\nbegin\n  letI h : inhabited \u03b1 := \u27e8a\u27e9,\n  assert_frozen_instances,\n  exact (default : \u03b1)\nend\n\nexample (\u03b1) (a : \u03b1) :=\nbegin\n  letI h : inhabited \u03b1,\n  all_goals { assert_frozen_instances },\n  exact \u27e8a\u27e9,\n  exact (default : \u03b1)\nend\n\nexample (\u03b1) (a : \u03b1) :=\nbegin\n  letI h := inhabited.mk a,\n  exact (default : \u03b1)\nend\n\nexample (\u03b1) : inhabited \u03b1 \u2192 \u03b1 :=\nby intro a; exactI default\n\nexample (\u03b1) : inhabited \u03b1 \u2192 \u03b1 :=\nbegin\n  introsI a,\n  assert_frozen_instances,\n  exact default\nend\n\nexample (\u03b1 \u03b2) (h : \u03b1 = \u03b2) [inhabited \u03b1] : \u03b2 :=\nbegin\n  substI h,\n  assert_frozen_instances,\n  exact default\nend\n\nexample (\u03b1 \u03b2) (h : \u03b1 = \u03b2) [inhabited \u03b1] : \u03b2 :=\nbegin\n  unfreezingI { cases _inst_1 },\n  assert_frozen_instances,\n  subst h, assumption\nend\n\nexample (\u03b1 \u03b2) (h : \u03b1 = \u03b2) [inhabited \u03b1] : \u03b2 :=\nbegin\n  casesI _inst_1,\n  assert_frozen_instances,\n  subst h, assumption\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/instance_cache.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.058345840202334215, "lm_q1q2_score": 0.02442922296647811}}
{"text": "import \u00absmt-lean\u00bb\n\nexample {y : \u2124} (h1 : y < y)\n : false :=\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/lt_self_unsat.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.05340332942318685, "lm_q1q2_score": 0.02441262268017279}}
{"text": "open list tactic monad expr\n\nmeta def induction_on_pairs : tactic unit :=\nrepeat ( do l \u2190 local_context,\n   l.reverse.mfor' $ \u03bb h, do\n     ```(prod _ _) \u2190 infer_type h >>= whnf | skip,\n     induction h [ const_name h ] >> skip )\n\nlemma f ( p : \u2115 \u00d7 \u2115 ) : \u2115 :=\nbegin\n  induction_on_pairs\nend", "meta": {"author": "semorrison", "repo": "proof", "sha": "5ee398aa239a379a431190edbb6022b1a0aa2c70", "save_path": "github-repos/lean/semorrison-proof", "path": "github-repos/lean/semorrison-proof/proof-5ee398aa239a379a431190edbb6022b1a0aa2c70/lean/20170403-segfault.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.06853749778844886, "lm_q1q2_score": 0.02438392097737607}}
{"text": "namespace Ex1\n\ninductive T: Type :=\n  | mk: String \u2192 Option T \u2192 T\n\ndef runT: T \u2192 Nat\n  | .mk _ none => 0\n  | .mk _ (some t) => runT t\n\nclass Run (\u03b1: Type) where\n  run: \u03b1 \u2192 Nat\ninstance: Run T := \u27e8runT\u27e9\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 \u2192 (Unit \u00d7 Unit)\n  | .wrap => ((), ())\n\nmutual\ninductive Op where\n  | mk: String \u2192 Block \u2192 Op\n\ninductive Assign where\n  | mk : String \u2192 Op \u2192 Assign\n\ninductive Block where\n  | mk: Assign \u2192 Block\n  | empty: Block\nend\n\nmutual\ndef runOp: Op \u2192 Wrapper\n  | .mk _ r => let r' := runBlock r; .wrap\n\ndef runAssign: Assign \u2192 Wrapper\n  | .mk _ op => runOp op\n\ndef runBlock: Block \u2192 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) \u2192 Type :=\n  | mkOp: String \u2192 Block \u2192 Op\n  | mkAssign: String \u2192 Op \u2192 Assign\n  | mkBlock: Assign \u2192 Block\n  | emptyBlock: Block\n\ndef runBase: Program type \u2192 Nat\n  | .mkOp _ v => let _ := runBase v; 0\n  | .mkAssign _ t => runBase t\n  | .mkBlock u => runBase u\n  | .emptyBlock => 0\n\nclass Run (\u03b1: Type) where\n  run: \u03b1 \u2192 Nat\ninstance: Run Assign := \u27e8runBase\u27e9\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) 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: Abdalrhman Mohamed\n-/\n\nimport Lean\n\nimport Smt.Dsl.Sexp\nimport Smt.Query\nimport Smt.Reconstruction.Certifying\nimport Smt.Solver\n\nnamespace Smt\n\nopen Lean Elab Tactic\nopen Smt Query Solver\n\ninitialize\n  registerTraceClass `smt.debug\n  registerTraceClass `smt.debug.attr\n  registerTraceClass `smt.debug.reconstruct\n  registerTraceClass `smt.debug.translate.query\n  registerTraceClass `smt.debug.translate.expr\n\nsyntax smtHints := (\"[\" ident,* \"]\")?\nsyntax smtTimeout := (\"(timeout := \" num \")\")?\n\n/-- `smt` converts the current goal into an SMT query and checks if it is\nsatisfiable. By default, `smt` generates the minimum valid SMT query needed to\nassert the current goal. However, that is not always enough:\n```lean\ndef modus_ponens (p q : Prop) (hp : p) (hpq : p \u2192 q) : q := by\n  smt\n```\nFor the theorem above, `smt` generates the query below:\n```smt2\n(declare-const q Bool)\n(assert (not q))\n(check-sat)\n```\nwhich is missing the hypotheses `hp` and `hpq` required to prove the theorem. To\npass hypotheses to the solver, use `smt [h\u2081, h\u2082, ..., h\u2099]` syntax:\n```lean\ndef modus_ponens (p q : Prop) (hp : p) (hpq : p \u2192 q) : q := by\n  smt [hp, hpq]\n```\nThe tactic then generates the query below:\n```smt2\n(declare-const q Bool)\n(assert (not q))\n(declare-const p Bool)\n(assert p)\n(assert (=> p q))\n(check-sat)\n```\n-/\nsyntax (name := smt) \"smt\" smtHints smtTimeout : tactic\n\n/-- Like `smt`, but just shows the query without invoking a solver. -/\nsyntax (name := smtShow) \"smt_show\" smtHints : tactic\n\ndef parseHints : TSyntax `smtHints \u2192 TacticM (List Expr)\n  | `(smtHints| [ $[$hs],* ]) => hs.toList.mapM (fun h => elabTerm h.raw none)\n  | `(smtHints| ) => return []\n  | _ => throwUnsupportedSyntax\n\ndef parseTimeout : TSyntax `smtTimeout \u2192 TacticM (Option Nat)\n  | `(smtTimeout| (timeout := $n)) => return some n.getNat\n  | `(smtTimeout| ) => return some 5\n  | _ => throwUnsupportedSyntax\n\ndef prepareSmtQuery (hints : TSyntax `smtHints) : TacticM (List Command) := do\n  -- 1. Get the current main goal.\n  let goalType \u2190 Tactic.getMainTarget\n  let goalId \u2190 Lean.mkFreshMVarId\n  Lean.Meta.withLocalDeclD goalId.name (mkNot goalType) fun g => do\n  -- 2. Get the hints passed to the tactic.\n  let mut hs \u2190 parseHints hints\n  hs := hs.eraseDups\n  -- 3. Generate the SMT query.\n  Query.generateQuery g hs\n\ndef elabProof (text : String) : TacticM Unit := do\n  let (env, log) \u2190 process text (\u2190 getEnv) .empty \"<proof>\"\n  _ \u2190 modifyEnv (fun _ => env)\n  for m in log.msgs do\n    trace[smt.debug.reconstruct] (\u2190 m.toString)\n  if log.hasErrors then\n    throwError \"encountered errors elaborating cvc5 proof\"\n\ndef evalAnyGoals (tactic : TacticM Unit) : TacticM Unit := do\n  let mvarIds \u2190 getGoals\n  let mut mvarIdsNew := #[]\n  for mvarId in mvarIds do\n    unless (\u2190 mvarId.isAssigned) do\n      setGoals [mvarId]\n      try\n        tactic\n        mvarIdsNew := mvarIdsNew ++ (\u2190 getUnsolvedGoals)\n      catch _ =>\n        mvarIdsNew := mvarIdsNew.push mvarId\n  setGoals mvarIdsNew.toList\n\nprivate def addDeclToUnfoldOrTheorem (thms : Meta.SimpTheorems) (e : Expr) : MetaM Meta.SimpTheorems := do\n  if e.isConst then\n    let declName := e.constName!\n    let info \u2190 getConstInfo declName\n    if (\u2190 Meta.isProp info.type) then\n      thms.addConst declName\n    else\n      thms.addDeclToUnfold declName\n  else\n    thms.add (.fvar e.fvarId!) #[] e\n\nopen Reconstruction.Certifying in\ndef rconsProof (hints : List Expr) : TacticM Unit := do\n  let mut gs \u2190 (\u2190 Tactic.getMainGoal).apply (mkApp (mkConst ``notNotElim) (\u2190 Tactic.getMainTarget))\n  Tactic.replaceMainGoal gs\n  if (\u2190 getConstInfo `th0).levelParams == [] then\n    gs \u2190 (\u2190 Tactic.getMainGoal).apply (mkConst `th0)\n    trace[smt.debug.reconstruct] \"th0 : {\u2190 Meta.inferType (mkConst `th0)}\"\n  else\n    let u \u2190 Meta.mkFreshLevelMVar\n    gs \u2190 (\u2190 Tactic.getMainGoal).apply (mkConst `th0 [u])\n    trace[smt.debug.reconstruct] \"th0 : {\u2190 Meta.inferType (mkConst `th0 [u])}\"\n  Tactic.replaceMainGoal gs\n  for h in hints do\n    evalAnyGoals do\n      let gs \u2190 (\u2190 Tactic.getMainGoal).apply h\n      Tactic.replaceMainGoal gs\n  let mut some thms \u2190 (\u2190 Meta.getSimpExtension? `smt_simp).mapM (\u00b7.getTheorems)\n    | throwError \"smt tactic failed, 'smt_simp' simpset is not available\"\n  for h in hints do\n    thms \u2190 addDeclToUnfoldOrTheorem thms h\n  evalAnyGoals do\n    let (result?, _) \u2190 Meta.simpGoal (\u2190 Tactic.getMainGoal) {\n      simpTheorems := #[thms],\n      congrTheorems := (\u2190 Meta.getSimpCongrTheorems)\n    }\n    match result? with\n    | none => replaceMainGoal []\n    | some (_, mvarId) => replaceMainGoal [mvarId]\n\n@[tactic smt] def evalSmt : Tactic := fun stx => withMainContext do\n  let goalType \u2190 Tactic.getMainTarget\n  let cmds \u2190 prepareSmtQuery \u27e8stx[1]\u27e9\n  let query := setOption \"produce-models\" \"true\"\n            *> emitCommands cmds.reverse\n            *> checkSat\n  logInfo m!\"goal: {goalType}\"\n  logInfo m!\"\\nquery:\\n{Command.cmdsAsQuery (.checkSat :: cmds)}\"\n  -- 4. Run the solver.\n  let kind := smt.solver.kind.get (\u2190 getOptions)\n  let path := smt.solver.path.get? (\u2190 getOptions)\n  let timeout \u2190 parseTimeout \u27e8stx[2]\u27e9\n  let ss \u2190 createFromKind kind path timeout\n  let (res, ss) \u2190 (StateT.run query ss : MetaM _)\n  -- 5. Print the result.\n  logInfo m!\"\\nresult: {res}\"\n  if res = .sat then\n    -- 5a. Print model.\n    let (model, _) \u2190 StateT.run getModel ss\n    logInfo m!\"\\ncounter-model:\\n{model}\\n\"\n    throwError \"unable to prove goal, either it is false or you need to define more symbols with `smt [foo, bar]`\"\n  if res = .unknown then\n    throwError \"unable to prove goal\"\n  try\n    -- 5a. Reconstruct proof.\n    let (.expr [.atom \"proof\", .atom nnp], _) \u2190 StateT.run getProof ss\n      | throwError \"encountered error parsing cvc5 proof\"\n    let nnp := skipImports (unquote nnp)\n    trace[smt.debug.reconstruct] \"proof:\\n{nnp}\"\n    elabProof nnp\n    rconsProof (\u2190 parseHints \u27e8stx[1]\u27e9)\n  catch e =>\n    logInfo m!\"failed to reconstruct proof: {e.toMessageData}\"\nwhere\n  unquote s := s.extract \u27e81\u27e9 (s.endPos - \u27e81\u27e9)\n  skipImports (s : String) := Id.run do\n    let mut s := s\n    while s.startsWith \"import\" do\n      s := s.dropWhile (\u00b7 != '\\n')\n      s := s.drop 1\n    return s\n\n@[tactic smtShow] def evalSmtShow : Tactic := fun stx => withMainContext do\n  let goalType \u2190 Tactic.getMainTarget\n  let cmds := .checkSat :: (\u2190 prepareSmtQuery \u27e8stx[1]\u27e9)\n  -- 4. Print the query.\n  logInfo m!\"goal: {goalType}\\n\\nquery:\\n{Command.cmdsAsQuery cmds}\"\n\nend Smt\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/Tactic/Smt.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056074291438, "lm_q2_score": 0.08632347541098986, "lm_q1q2_score": 0.02429191003342436}}
{"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 \u27f6 Y` is locally of finite type if for each affine `U \u2286 Y` and\n`V \u2286 f \u207b\u00b9' U`, The induced map `\u0393(Y, U) \u27f6 \u0393(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 \u27f6 Y)\n\n/--\nA morphism of schemes `f : X \u27f6 Y` is locally of finite type if for each affine `U \u2286 Y` and\n`V \u2286 f \u207b\u00b9' U`, The induced map `\u0393(Y, U) \u27f6 \u0393(X, V)` is of finite type.\n-/\n@[mk_iff]\nclass locally_of_finite_type (f : X \u27f6 Y) : Prop :=\n(finite_type_of_affine_subset :\n  \u2200 (U : Y.affine_opens) (V : X.affine_opens) (e : V.1 \u2264 (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 \u27f6 Y)\n  [is_open_immersion f] : locally_of_finite_type f :=\nlocally_of_finite_type_eq.symm \u25b8\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 \u25b8\nring_hom.finite_type_is_local.affine_locally_stable_under_composition\n\ninstance locally_of_finite_type_comp {X Y Z : Scheme} (f : X \u27f6 Y) (g : Y \u27f6 Z)\n  [hf : locally_of_finite_type f] [hg : locally_of_finite_type g] :\n  locally_of_finite_type (f \u226b 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 \u27f6 Y) (g : Y \u27f6 Z)\n  [hf : locally_of_finite_type (f \u226b 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 \u27f6 Y)\n  (\ud835\udcb0 : Scheme.open_cover.{u} Y) [\u2200 i, is_affine (\ud835\udcb0.obj i)]\n  (\ud835\udcb0' : \u2200 i, Scheme.open_cover.{u} ((\ud835\udcb0.pullback_cover f).obj i))\n  [\u2200 i j, is_affine ((\ud835\udcb0' i).obj j)] :\n  locally_of_finite_type f \u2194\n    (\u2200 i j, (Scheme.\u0393.map ((\ud835\udcb0' i).map j \u226b pullback.snd).op).finite_type) :=\nlocally_of_finite_type_eq.symm \u25b8 ring_hom.finite_type_is_local.affine_open_cover_iff f \ud835\udcb0 \ud835\udcb0'\n\nlemma locally_of_finite_type.source_open_cover_iff {X Y : Scheme.{u}} (f : X \u27f6 Y)\n  (\ud835\udcb0 : Scheme.open_cover.{u} X) :\n  locally_of_finite_type f \u2194 (\u2200 i, locally_of_finite_type (\ud835\udcb0.map i \u226b f)) :=\nlocally_of_finite_type_eq.symm \u25b8 ring_hom.finite_type_is_local.source_open_cover_iff f \ud835\udcb0\n\nlemma locally_of_finite_type.open_cover_iff {X Y : Scheme.{u}} (f : X \u27f6 Y)\n  (\ud835\udcb0 : Scheme.open_cover.{u} Y) :\n  locally_of_finite_type f \u2194\n    (\u2200 i, locally_of_finite_type (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _)) :=\nlocally_of_finite_type_eq.symm \u25b8\n  ring_hom.finite_type_is_local.is_local_affine_locally.open_cover_iff f \ud835\udcb0\n\nlemma locally_of_finite_type_respects_iso :\n  morphism_property.respects_iso @locally_of_finite_type :=\nlocally_of_finite_type_eq.symm \u25b8 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 \u25b8\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 \u25b8\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 \u2192\u2090[R] T) : (\u22a4 : 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 \u27e8\u27e8s, hs\u27e9\u27e9,\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 (\u2191s : set T) = \u22a4,\n  { have : i7 = (algebra_map R T).to_algebra := algebra.algebra_ext _ _ (\u03bb _, rfl), convert hs },\n  refine \u27e8\u27e8s.image algebra.tensor_product.include_right, _\u27e9\u27e9,\n  rw [finset.coe_image, \u2190 @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 \u2022 ((1 : S) \u2297\u209c y) \u2208 _,\n    { rw [tensor_product.smul_tmul', \u2190 algebra.algebra_map_eq_smul_one], refl },\n    { exact subalgebra.smul_mem _ (algebra.subset_adjoin \u27e8y, rfl\u27e9) _ } },\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 \u25b8\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 \u27f6 Z) (g : Y \u27f6 Z) [locally_of_finite_type g] : \n  locally_of_finite_type (pullback.fst : pullback f g \u27f6 _) :=\nlocally_of_finite_type_stable_under_base_change.fst _ _ \u2039_\u203a\n\ninstance {X Y Z : Scheme} (f : X \u27f6 Z) (g : Y \u27f6 Z) [locally_of_finite_type f] : \n  locally_of_finite_type (pullback.snd : pullback f g \u27f6 _) :=\nlocally_of_finite_type_stable_under_base_change.snd _ _ \u2039_\u203a\n\n-- generalize me\nlemma locally_of_finite_type_Spec_iff {R S : CommRing} (f : R \u27f6 S) :\n  locally_of_finite_type (Scheme.Spec.map f.op) \u2194 ring_hom.finite_type f :=\nbegin\n  transitivity (@affine \u2293 @locally_of_finite_type) (Scheme.Spec.map f.op),\n  { refine (and_iff_right _).symm, apply_instance },\n  { rw [locally_of_finite_type_eq, \u2190 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 \ud835\udcb0 : X.open_cover := (Y.affine_cover.pullback_cover f).bind (\u03bb _, Scheme.affine_cover _),\n  rw is_jacobson_iff_of_supr_eq_top \ud835\udcb0.supr_opens_range,\n  intro i,\n  refine is_jacobson.of_closed_embedding _ (homeomorph.of_embedding (\ud835\udcb0.map i).1.base\n    (is_open_immersion.base_open _).to_embedding).symm.closed_embedding,\n  let g : \ud835\udcb0.obj i \u27f6 _ := (Scheme.affine_cover _).map _ \u226b 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 [\u2190 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 \u2192 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) 2020 Oliver Nash. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Oliver Nash\n\n! This file was ported from Lean 3 source module tactic.noncomm_ring\n! leanprover-community/mathlib commit abaabc8c03c8bdc430975669014d3e6c19de58e4\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Abel\n\nnamespace Tactic\n\nnamespace Interactive\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/-- A tactic for simplifying identities in not-necessarily-commutative rings.\n\nAn example:\n```lean\nexample {R : Type*} [ring R] (a b c : R) : a * (b + c + c - b) = 2*a*c :=\nby noncomm_ring\n```\n-/\nunsafe def noncomm_ring :=\n  sorry\n#align tactic.interactive.noncomm_ring tactic.interactive.noncomm_ring\n\n-- Expand everything out.\n-- Right associate all products.\n-- Expand powers to numerals.\n-- Replace multiplication by numerals with `zsmul`.\n-- Pull `zsmul n` out the front so `abel` can see them.\n-- Pull out negations.\nadd_tactic_doc\n  { Name := \"noncomm_ring\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.noncomm_ring]\n    tags := [\"arithmetic\", \"simplification\", \"decision procedure\"] }\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/NoncommRing.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.04885778121892747, "lm_q1q2_score": 0.024238043784350096}}
{"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 \u2192 Type v}\n\n-- The family of types already equipped with instances\nvariable (x y : \u2200 i, f i) (i : I)\n\nnamespace Pi\n\n#print Pi.smul' /-\n@[to_additive Pi.vadd']\ninstance smul' {g : I \u2192 Type _} [\u2200 i, SMul (f i) (g i)] : SMul (\u2200 i, f i) (\u2200 i : I, g i) :=\n  \u27e8fun s x => fun i => s i \u2022 x i\u27e9\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'\u2093'. -/\n@[simp, to_additive]\ntheorem smul_apply' {g : I \u2192 Type _} [\u2200 i, SMul (f i) (g i)] (s : \u2200 i, f i) (x : \u2200 i, g i) :\n    (s \u2022 x) i = s i \u2022 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 {\u03b1 \u03b2 : Type _} [SMul \u03b1 \u03b2] [\u2200 i, SMul \u03b2 <| f i] [\u2200 i, SMul \u03b1 <| f i]\n    [\u2200 i, IsScalarTower \u03b1 \u03b2 (f i)] : IsScalarTower \u03b1 \u03b2 (\u2200 i : I, f i) :=\n  \u27e8fun x y z => funext fun i => smul_assoc x y (z i)\u27e9\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 \u2192 Type _} {\u03b1 : Type _} [\u2200 i, SMul \u03b1 <| f i] [\u2200 i, SMul (f i) (g i)]\n    [\u2200 i, SMul \u03b1 <| g i] [\u2200 i, IsScalarTower \u03b1 (f i) (g i)] :\n    IsScalarTower \u03b1 (\u2200 i : I, f i) (\u2200 i : I, g i) :=\n  \u27e8fun x y z => funext fun i => smul_assoc x (y i) (z i)\u27e9\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 \u2192 Type _} {h : I \u2192 Type _} [\u2200 i, SMul (f i) (g i)]\n    [\u2200 i, SMul (g i) (h i)] [\u2200 i, SMul (f i) (h i)] [\u2200 i, IsScalarTower (f i) (g i) (h i)] :\n    IsScalarTower (\u2200 i, f i) (\u2200 i, g i) (\u2200 i, h i) :=\n  \u27e8fun x y z => funext fun i => smul_assoc (x i) (y i) (z i)\u27e9\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 {\u03b1 \u03b2 : Type _} [\u2200 i, SMul \u03b1 <| f i] [\u2200 i, SMul \u03b2 <| f i]\n    [\u2200 i, SMulCommClass \u03b1 \u03b2 (f i)] : SMulCommClass \u03b1 \u03b2 (\u2200 i : I, f i) :=\n  \u27e8fun x y z => funext fun i => smul_comm x y (z i)\u27e9\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 \u2192 Type _} {\u03b1 : Type _} [\u2200 i, SMul \u03b1 <| g i] [\u2200 i, SMul (f i) (g i)]\n    [\u2200 i, SMulCommClass \u03b1 (f i) (g i)] : SMulCommClass \u03b1 (\u2200 i : I, f i) (\u2200 i : I, g i) :=\n  \u27e8fun x y z => funext fun i => smul_comm x (y i) (z i)\u27e9\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 \u2192 Type _} {h : I \u2192 Type _} [\u2200 i, SMul (g i) (h i)]\n    [\u2200 i, SMul (f i) (h i)] [\u2200 i, SMulCommClass (f i) (g i) (h i)] :\n    SMulCommClass (\u2200 i, f i) (\u2200 i, g i) (\u2200 i, h i) :=\n  \u27e8fun x y z => funext fun i => smul_comm (x i) (y i) (z i)\u27e9\n#align pi.smul_comm_class'' Pi.smulCommClass''\n#align pi.vadd_comm_class'' Pi.vaddCommClass''\n-/\n\n@[to_additive]\ninstance {\u03b1 : Type _} [\u2200 i, SMul \u03b1 <| f i] [\u2200 i, SMul \u03b1\u1d50\u1d52\u1d56 <| f i] [\u2200 i, IsCentralScalar \u03b1 (f i)] :\n    IsCentralScalar \u03b1 (\u2200 i, f i) :=\n  \u27e8fun r m => funext fun i => op_smul_eq_smul _ _\u27e9\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}} {\u03b1 : Type.{u3}} [_inst_1 : forall (i : I), SMul.{u3, u2} \u03b1 (f i)] [_inst_2 : forall (i : I), Nonempty.{succ u2} (f i)] (i : I) [_inst_3 : FaithfulSMul.{u3, u2} \u03b1 (f i) (_inst_1 i)], FaithfulSMul.{u3, max u1 u2} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I \u03b1 (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}} {\u03b1 : Type.{u1}} [_inst_1 : forall (i : I), SMul.{u1, u3} \u03b1 (f i)] [_inst_2 : forall (i : I), Nonempty.{succ u3} (f i)] (i : I) [_inst_3 : FaithfulSMul.{u1, u3} \u03b1 (f i) (_inst_1 i)], FaithfulSMul.{u1, max u2 u3} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I \u03b1 (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\u2093'. -/\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `\u03a0 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 `\u03a0 i, f i`. This is not an instance as `i` cannot be inferred\"]\ntheorem faithfulSMul_at {\u03b1 : Type _} [\u2200 i, SMul \u03b1 <| f i] [\u2200 i, Nonempty (f i)] (i : I)\n    [FaithfulSMul \u03b1 (f i)] : FaithfulSMul \u03b1 (\u2200 i, f i) :=\n  \u27e8fun 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 (\u2039\u2200 i, Nonempty (f i)\u203a j)) i a)\n            i\n        simpa using this\u27e9\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 {\u03b1 : Type _} [Nonempty I] [\u2200 i, SMul \u03b1 <| f i] [\u2200 i, Nonempty (f i)]\n    [\u2200 i, FaithfulSMul \u03b1 (f i)] : FaithfulSMul \u03b1 (\u2200 i, f i) :=\n  let \u27e8i\u27e9 := \u2039Nonempty I\u203a\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 (\u03b1) {m : Monoid \u03b1} [\u2200 i, MulAction \u03b1 <| f i] : @MulAction \u03b1 (\u2200 i : I, f i) m\n    where\n  smul := (\u00b7 \u2022 \u00b7)\n  mul_smul r s f := funext fun i => mul_smul _ _ _\n  one_smul f := funext fun i => one_smul \u03b1 _\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 \u2192 Type _} {m : \u2200 i, Monoid (f i)} [\u2200 i, MulAction (f i) (g i)] :\n    @MulAction (\u2200 i, f i) (\u2200 i : I, g i) (@Pi.monoid I f m)\n    where\n  smul := (\u00b7 \u2022 \u00b7)\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 (\u03b1) {n : \u2200 i, Zero <| f i} [\u2200 i, SMulZeroClass \u03b1 <| f i] :\n    @SMulZeroClass \u03b1 (\u2200 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 \u2192 Type _} {n : \u2200 i, Zero <| g i} [\u2200 i, SMulZeroClass (f i) (g i)] :\n    @SMulZeroClass (\u2200 i, f i) (\u2200 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 (\u03b1) {n : \u2200 i, AddZeroClass <| f i} [\u2200 i, DistribSMul \u03b1 <| f i] :\n    @DistribSMul \u03b1 (\u2200 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 \u2192 Type _} {n : \u2200 i, AddZeroClass <| g i}\n    [\u2200 i, DistribSMul (f i) (g i)] : @DistribSMul (\u2200 i, f i) (\u2200 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 (\u03b1) {m : Monoid \u03b1} {n : \u2200 i, AddMonoid <| f i}\n    [\u2200 i, DistribMulAction \u03b1 <| f i] : @DistribMulAction \u03b1 (\u2200 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 \u2192 Type _} {m : \u2200 i, Monoid (f i)} {n : \u2200 i, AddMonoid <| g i}\n    [\u2200 i, DistribMulAction (f i) (g i)] :\n    @DistribMulAction (\u2200 i, f i) (\u2200 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}} {\u03b1 : Type.{u3}} [_inst_1 : Monoid.{u3} \u03b1] [_inst_2 : forall (i : I), AddMonoid.{u2} (f i)] [_inst_3 : forall (i : I), DistribMulAction.{u3, u2} \u03b1 (f i) _inst_1 (_inst_2 i)] [_inst_4 : DecidableEq.{succ u1} I] (i : I) (r : \u03b1) (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} \u03b1 (f i) (SMulZeroClass.toHasSmul.{u3, u2} \u03b1 (f i) (AddZeroClass.toHasZero.{u2} (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i))) (DistribSMul.toSmulZeroClass.{u3, u2} \u03b1 (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u3, u2} \u03b1 (f i) _inst_1 (_inst_2 i) (_inst_3 i)))) r x)) (SMul.smul.{u3, max u1 u2} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I \u03b1 (fun (i : I) => f i) (fun (i : I) => SMulZeroClass.toHasSmul.{u3, u2} \u03b1 (f i) (AddZeroClass.toHasZero.{u2} (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i))) (DistribSMul.toSmulZeroClass.{u3, u2} \u03b1 (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u3, u2} \u03b1 (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}} {\u03b1 : Type.{u1}} [_inst_1 : Monoid.{u1} \u03b1] [_inst_2 : forall (i : I), AddMonoid.{u3} (f i)] [_inst_3 : forall (i : I), DistribMulAction.{u1, u3} \u03b1 (f i) _inst_1 (_inst_2 i)] [_inst_4 : DecidableEq.{succ u2} I] (i : I) (r : \u03b1) (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} \u03b1 (f i) (f i) (instHSMul.{u1, u3} \u03b1 (f i) (SMulZeroClass.toSMul.{u1, u3} \u03b1 (f i) (AddMonoid.toZero.{u3} (f i) (_inst_2 i)) (DistribSMul.toSMulZeroClass.{u1, u3} \u03b1 (f i) (AddMonoid.toAddZeroClass.{u3} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u1, u3} \u03b1 (f i) _inst_1 (_inst_2 i) (_inst_3 i))))) r x)) (HSMul.hSMul.{u1, max u3 u2, max u2 u3} \u03b1 (forall (j : I), f j) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} \u03b1 (forall (j : I), f j) (Pi.instSMul.{u2, u3, u1} I \u03b1 (fun (j : I) => f j) (fun (i : I) => SMulZeroClass.toSMul.{u1, u3} \u03b1 (f i) (AddMonoid.toZero.{u3} (f i) (_inst_2 i)) (DistribSMul.toSMulZeroClass.{u1, u3} \u03b1 (f i) (AddMonoid.toAddZeroClass.{u3} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u1, u3} \u03b1 (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\u2093'. -/\ntheorem single_smul {\u03b1} [Monoid \u03b1] [\u2200 i, AddMonoid <| f i] [\u2200 i, DistribMulAction \u03b1 <| f i]\n    [DecidableEq I] (i : I) (r : \u03b1) (x : f i) : single i (r \u2022 x) = r \u2022 single i x :=\n  single_op (fun i : I => ((\u00b7 \u2022 \u00b7) r : f i \u2192 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}} {\u03b1 : Type.{u2}} {\u03b2 : Type.{u3}} [_inst_1 : Monoid.{u2} \u03b1] [_inst_2 : AddMonoid.{u3} \u03b2] [_inst_3 : DistribMulAction.{u2, u3} \u03b1 \u03b2 _inst_1 _inst_2] [_inst_4 : DecidableEq.{succ u1} I] (i : I) (r : \u03b1) (x : \u03b2), Eq.{max (succ u1) (succ u3)} (I -> \u03b2) (Pi.single.{u1, u3} I (fun (i : I) => \u03b2) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u3} \u03b2 (AddMonoid.toAddZeroClass.{u3} \u03b2 _inst_2)) i (SMul.smul.{u2, u3} \u03b1 \u03b2 (SMulZeroClass.toHasSmul.{u2, u3} \u03b1 \u03b2 (AddZeroClass.toHasZero.{u3} \u03b2 (AddMonoid.toAddZeroClass.{u3} \u03b2 _inst_2)) (DistribSMul.toSmulZeroClass.{u2, u3} \u03b1 \u03b2 (AddMonoid.toAddZeroClass.{u3} \u03b2 _inst_2) (DistribMulAction.toDistribSMul.{u2, u3} \u03b1 \u03b2 _inst_1 _inst_2 _inst_3))) r x)) (SMul.smul.{u2, max u1 u3} \u03b1 (I -> \u03b2) (Pi.instSMul.{u1, u3, u2} I \u03b1 (fun (i : I) => \u03b2) (fun (i : I) => SMulZeroClass.toHasSmul.{u2, u3} \u03b1 \u03b2 (AddZeroClass.toHasZero.{u3} \u03b2 (AddMonoid.toAddZeroClass.{u3} \u03b2 _inst_2)) (DistribSMul.toSmulZeroClass.{u2, u3} \u03b1 \u03b2 (AddMonoid.toAddZeroClass.{u3} \u03b2 _inst_2) (DistribMulAction.toDistribSMul.{u2, u3} \u03b1 \u03b2 _inst_1 _inst_2 _inst_3)))) r (Pi.single.{u1, u3} I (fun (i : I) => \u03b2) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u3} \u03b2 (AddMonoid.toAddZeroClass.{u3} \u03b2 _inst_2)) i x))\nbut is expected to have type\n  forall {I : Type.{u3}} {\u03b1 : Type.{u2}} {\u03b2 : Type.{u1}} [_inst_1 : Monoid.{u2} \u03b1] [_inst_2 : AddMonoid.{u1} \u03b2] [_inst_3 : DistribMulAction.{u2, u1} \u03b1 \u03b2 _inst_1 _inst_2] [_inst_4 : DecidableEq.{succ u3} I] (i : I) (r : \u03b1) (x : \u03b2), Eq.{max (succ u3) (succ u1)} (I -> \u03b2) (Pi.single.{u3, u1} I (fun (i : I) => \u03b2) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.1984 : I) => \u03b2) i) _inst_2) i (HSMul.hSMul.{u2, u1, u1} \u03b1 \u03b2 \u03b2 (instHSMul.{u2, u1} \u03b1 \u03b2 (SMulZeroClass.toSMul.{u2, u1} \u03b1 \u03b2 (AddMonoid.toZero.{u1} \u03b2 _inst_2) (DistribSMul.toSMulZeroClass.{u2, u1} \u03b1 \u03b2 (AddMonoid.toAddZeroClass.{u1} \u03b2 _inst_2) (DistribMulAction.toDistribSMul.{u2, u1} \u03b1 \u03b2 _inst_1 _inst_2 _inst_3)))) r x)) (HSMul.hSMul.{u2, max u1 u3, max u3 u1} \u03b1 (forall (j : I), (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) j) (forall (i : I), (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) (instHSMul.{u2, max u3 u1} \u03b1 (forall (j : I), (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) j) (Pi.instSMul.{u3, u1, u2} I \u03b1 (fun (j : I) => (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) j) (fun (i : I) => SMulZeroClass.toSMul.{u2, u1} \u03b1 ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) (AddMonoid.toZero.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) _inst_2) (DistribSMul.toSMulZeroClass.{u2, u1} \u03b1 ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) (AddMonoid.toAddZeroClass.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) _inst_2) (DistribMulAction.toDistribSMul.{u2, u1} \u03b1 ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) _inst_1 _inst_2 _inst_3))))) r (Pi.single.{u3, u1} I (fun (i : I) => \u03b2) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => \u03b2) i) _inst_2) i x))\nCase conversion may be inaccurate. Consider using '#align pi.single_smul' Pi.single_smul'\u2093'. -/\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' {\u03b1 \u03b2} [Monoid \u03b1] [AddMonoid \u03b2] [DistribMulAction \u03b1 \u03b2] [DecidableEq I] (i : I)\n    (r : \u03b1) (x : \u03b2) : single i (r \u2022 x) = r \u2022 single i x :=\n  single_smul i r x\n#align pi.single_smul' Pi.single_smul'\n\n/- warning: pi.single_smul\u2080 -> Pi.single_smul\u2080 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\u2080 Pi.single_smul\u2080\u2093'. -/\ntheorem single_smul\u2080 {g : I \u2192 Type _} [\u2200 i, MonoidWithZero (f i)] [\u2200 i, AddMonoid (g i)]\n    [\u2200 i, DistribMulAction (f i) (g i)] [DecidableEq I] (i : I) (r : f i) (x : g i) :\n    single i (r \u2022 x) = single i r \u2022 single i x :=\n  single_op\u2082 (fun i : I => ((\u00b7 \u2022 \u00b7) : f i \u2192 g i \u2192 g i)) (fun j => smul_zero _) _ _ _\n#align pi.single_smul\u2080 Pi.single_smul\u2080\n\n#print Pi.mulDistribMulAction /-\ninstance mulDistribMulAction (\u03b1) {m : Monoid \u03b1} {n : \u2200 i, Monoid <| f i}\n    [\u2200 i, MulDistribMulAction \u03b1 <| f i] :\n    @MulDistribMulAction \u03b1 (\u2200 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 \u2192 Type _} {m : \u2200 i, Monoid (f i)} {n : \u2200 i, Monoid <| g i}\n    [\u2200 i, MulDistribMulAction (f i) (g i)] :\n    @MulDistribMulAction (\u2200 i, f i) (\u2200 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 {\u03b9 R M : Type _} [SMul R M] : SMul R (\u03b9 \u2192 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 {\u03b9 \u03b1 \u03b2 M : Type _} [SMul \u03b1 M] [SMul \u03b2 M] [SMulCommClass \u03b1 \u03b2 M] :\n    SMulCommClass \u03b1 \u03b2 (\u03b9 \u2192 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}} {\u03b1 : Type.{u3}} [_inst_1 : forall (i : I), SMul.{u3, u2} \u03b1 (f i)] [_inst_2 : DecidableEq.{succ u1} I] (c : \u03b1) (f\u2081 : forall (i : I), f i) (i : I) (x\u2081 : 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} \u03b1 (forall (a : I), f a) (Pi.instSMul.{u1, u2, u3} I \u03b1 (fun (a : I) => f a) (fun (i : I) => _inst_1 i)) c f\u2081) i (SMul.smul.{u3, u2} \u03b1 (f i) (_inst_1 i) c x\u2081)) (SMul.smul.{u3, max u1 u2} \u03b1 (forall (a : I), f a) (Pi.instSMul.{u1, u2, u3} I \u03b1 (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\u2081 i x\u2081))\nbut is expected to have type\n  forall {I : Type.{u2}} {f : I -> Type.{u3}} {\u03b1 : Type.{u1}} [_inst_1 : forall (i : I), SMul.{u1, u3} \u03b1 (f i)] [_inst_2 : DecidableEq.{succ u2} I] (c : \u03b1) (f\u2081 : forall (i : I), f i) (i : I) (x\u2081 : 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} \u03b1 (forall (i : I), f i) (forall (a : I), f a) (instHSMul.{u1, max u2 u3} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I \u03b1 (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c f\u2081) i (HSMul.hSMul.{u1, u3, u3} \u03b1 (f i) (f i) (instHSMul.{u1, u3} \u03b1 (f i) (_inst_1 i)) c x\u2081)) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} \u03b1 (forall (a : I), f a) (forall (a : I), f a) (instHSMul.{u1, max u2 u3} \u03b1 (forall (a : I), f a) (Pi.instSMul.{u2, u3, u1} I \u03b1 (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\u2081 i x\u2081))\nCase conversion may be inaccurate. Consider using '#align function.update_smul Function.update_smul\u2093'. -/\n@[to_additive]\ntheorem update_smul {\u03b1 : Type _} [\u2200 i, SMul \u03b1 (f i)] [DecidableEq I] (c : \u03b1) (f\u2081 : \u2200 i, f i) (i : I)\n    (x\u2081 : f i) : update (c \u2022 f\u2081) i (c \u2022 x\u2081) = c \u2022 update f\u2081 i x\u2081 :=\n  funext fun j => (apply_update (fun i => (\u00b7 \u2022 \u00b7) c) f\u2081 i x\u2081 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}} {\u03b1 : Type.{u3}} [_inst_1 : forall (i : I), SMul.{u3, u2} \u03b1 (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 : \u03b1) (f\u2081 : forall (i : I), f i) (g\u2081 : 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} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I \u03b1 (fun (i : I) => f i) (fun (i : I) => _inst_1 i)) c f\u2081) (SMul.smul.{u3, max u1 u2} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I \u03b1 (fun (i : I) => f i) (fun (i : I) => _inst_1 i)) c g\u2081) (fun (j : I) => _inst_2 j)) (SMul.smul.{u3, max u1 u2} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I \u03b1 (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\u2081 g\u2081 (fun (j : I) => _inst_2 j)))\nbut is expected to have type\n  forall {I : Type.{u2}} {f : I -> Type.{u3}} {\u03b1 : Type.{u1}} [_inst_1 : forall (i : I), SMul.{u1, u3} \u03b1 (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 : \u03b1) (f\u2081 : forall (i : I), f i) (g\u2081 : 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} \u03b1 (forall (i : I), f i) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I \u03b1 (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c f\u2081) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} \u03b1 (forall (i : I), f i) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I \u03b1 (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c g\u2081) (fun (j : I) => _inst_2 j)) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} \u03b1 (forall (i : I), f i) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} \u03b1 (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I \u03b1 (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\u2081 g\u2081 (fun (j : I) => _inst_2 j)))\nCase conversion may be inaccurate. Consider using '#align set.piecewise_smul Set.piecewise_smul\u2093'. -/\n@[to_additive]\ntheorem piecewise_smul {\u03b1 : Type _} [\u2200 i, SMul \u03b1 (f i)] (s : Set I) [\u2200 i, Decidable (i \u2208 s)] (c : \u03b1)\n    (f\u2081 g\u2081 : \u2200 i, f i) : s.piecewise (c \u2022 f\u2081) (c \u2022 g\u2081) = c \u2022 s.piecewise f\u2081 g\u2081 :=\n  s.piecewise_op _ _ fun _ => (\u00b7 \u2022 \u00b7) 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}} {\u03b1 : Type.{u2}} {\u03b2 : Type.{u3}} {\u03b3 : Type.{u4}} [_inst_1 : SMul.{u1, u4} R \u03b3] (r : R) (f : \u03b1 -> \u03b2) (g : \u03b1 -> \u03b3) (e : \u03b2 -> \u03b3), Eq.{max (succ u3) (succ u4)} (\u03b2 -> \u03b3) (Function.extend.{succ u2, succ u3, succ u4} \u03b1 \u03b2 \u03b3 f (SMul.smul.{u1, max u2 u4} R (\u03b1 -> \u03b3) (Function.hasSMul.{u2, u1, u4} \u03b1 R \u03b3 _inst_1) r g) (SMul.smul.{u1, max u3 u4} R (\u03b2 -> \u03b3) (Function.hasSMul.{u3, u1, u4} \u03b2 R \u03b3 _inst_1) r e)) (SMul.smul.{u1, max u3 u4} R (\u03b2 -> \u03b3) (Function.hasSMul.{u3, u1, u4} \u03b2 R \u03b3 _inst_1) r (Function.extend.{succ u2, succ u3, succ u4} \u03b1 \u03b2 \u03b3 f g e))\nbut is expected to have type\n  forall {R : Type.{u4}} {\u03b1 : Type.{u3}} {\u03b2 : Type.{u2}} {\u03b3 : Type.{u1}} [_inst_1 : SMul.{u4, u1} R \u03b3] (r : R) (f : \u03b1 -> \u03b2) (g : \u03b1 -> \u03b3) (e : \u03b2 -> \u03b3), Eq.{max (succ u2) (succ u1)} (\u03b2 -> \u03b3) (Function.extend.{succ u3, succ u2, succ u1} \u03b1 \u03b2 \u03b3 f (HSMul.hSMul.{u4, max u3 u1, max u3 u1} R (\u03b1 -> \u03b3) (\u03b1 -> \u03b3) (instHSMul.{u4, max u3 u1} R (\u03b1 -> \u03b3) (Pi.instSMul.{u3, u1, u4} \u03b1 R (fun (a._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2657 : \u03b1) => \u03b3) (fun (i : \u03b1) => _inst_1))) r g) (HSMul.hSMul.{u4, max u2 u1, max u2 u1} R (\u03b2 -> \u03b3) (\u03b2 -> \u03b3) (instHSMul.{u4, max u2 u1} R (\u03b2 -> \u03b3) (Pi.instSMul.{u2, u1, u4} \u03b2 R (fun (a._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2660 : \u03b2) => \u03b3) (fun (i : \u03b2) => _inst_1))) r e)) (HSMul.hSMul.{u4, max u2 u1, max u2 u1} R (\u03b2 -> \u03b3) (\u03b2 -> \u03b3) (instHSMul.{u4, max u2 u1} R (\u03b2 -> \u03b3) (Pi.instSMul.{u2, u1, u4} \u03b2 R (fun (a._@.Mathlib.Logic.Function.Basic._hyg.7460 : \u03b2) => \u03b3) (fun (i : \u03b2) => _inst_1))) r (Function.extend.{succ u3, succ u2, succ u1} \u03b1 \u03b2 \u03b3 f g e))\nCase conversion may be inaccurate. Consider using '#align function.extend_smul Function.extend_smul\u2093'. -/\n@[to_additive]\ntheorem Function.extend_smul {R \u03b1 \u03b2 \u03b3 : Type _} [SMul R \u03b3] (r : R) (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3)\n    (e : \u03b2 \u2192 \u03b3) : Function.extend f (r \u2022 g) (r \u2022 e) = r \u2022 Function.extend f g e :=\n  funext fun _ => by convert(apply_dite ((\u00b7 \u2022 \u00b7) 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": "\n/- Global environments are a component of the dynamic semantics of\n  all languages involved in the compiler.  A global environment\n  maps symbol names (names of functions and of global variables)\n  to the corresponding memory addresses.  It also maps memory addresses\n  of functions to the corresponding function descriptions.\n\n  Global environments, along with the initial memory state at the beginning\n  of program execution, are built from the program of interest, as follows:\n- A distinct memory address is assigned to each function of the program.\n  These function addresses use negative numbers to distinguish them from\n  addresses of memory blocks.  The associations of function name to function\n  address and function address to function description are recorded in\n  the global environment.\n- For each global variable, a memory block is allocated and associated to\n  the name of the variable.\n\n  These operations reflect (at a high level of abstraction) what takes\n  place during program linking and program loading in a real operating\n  system. -/\n\nimport .memory .linking\n\nnamespace globalenvs\nopen memdata memory values ast integers maps linking errors\n     memdata.memval word floats memdata.quantity memory.perm_kind\n     ast.memory_chunk\n\n/- Auxiliary function for initialization of global variables. -/\n\ndef store_zeros : mem \u2192 block \u2192 \u2115 \u2192 \u2115 \u2192 option mem\n| m b p 0     := some m\n| m b p (n+1) := do m' \u2190 store Mint8unsigned m b p Vzero, store_zeros m' b (p + 1) n\n\n/- * Symbol environments -/\n\n/- Symbol environments are a restricted view of global environments,\n  focusing on symbol names and their associated blocks.  They do not\n  contain mappings from blocks to function or variable definitions. -/\n\nstructure Senv : Type :=\n(find_symbol : ident \u2192 option block)\n(public_symbol : ident \u2192 bool)\n(invert_symbol : block \u2192 option ident)\n(block_is_volatile : block \u2192 bool)\n(nextblock : block)\n  /- Properties -/\n(find_symbol_injective : \u2200 {id1 id2 b}, find_symbol id1 = some b \u2192 find_symbol id2 = some b \u2192 id1 = id2)\n(invert_find_symbol : \u2200 {id b}, invert_symbol b = some id \u2192 find_symbol id = some b)\n(find_invert_symbol : \u2200 {id b}, find_symbol id = some b \u2192 invert_symbol b = some id)\n(public_symbol_exists : \u2200 {id}, public_symbol id \u2192 \u2203 b, find_symbol id = some b)\n(find_symbol_below : \u2200 {id b}, find_symbol id = some b \u2192 b < nextblock)\n(block_is_volatile_below : \u2200 {b}, block_is_volatile b \u2192 b < nextblock)\n\nnamespace Senv\n\ndef symbol_address (ge : Senv) (id : ident) (ofs : ptrofs) : val :=\n  match find_symbol ge id with\n| some b := Vptr b ofs\n| none := Vundef\n  end\n\ntheorem shift_symbol_address {ge id ofs delta} :\n  symbol_address ge id (ofs + delta) = val.offset_ptr (symbol_address ge id ofs) delta := sorry'\n\ntheorem shift_symbol_address_32 {ge id ofs n} : \u00ac archi.ptr64 \u2192\n  symbol_address ge id (ofs + ptrofs.of_int n) = symbol_address ge id ofs + n := sorry'\n\ntheorem shift_symbol_address_64 {ge id ofs n} : archi.ptr64 \u2192\n  symbol_address ge id (ofs + ptrofs.of_int64 n) = (symbol_address ge id ofs).addl n := sorry'\n\ndef equiv (se1 se2 : Senv) : Prop :=\n     (\u2200 id, find_symbol se2 id = find_symbol se1 id)\n  \u2227 (\u2200 id, public_symbol se2 id = public_symbol se1 id)\n  \u2227 (\u2200 b, block_is_volatile se2 b = block_is_volatile se1 b)\n\nend Senv\n\n/- * Global environments -/\n\n/- The type of global environments. -/\n\nstructure Genv (F V : Type) : Type :=\n(public : list ident)              /- which symbol names are public -/\n(symb : PTree block)             /- mapping symbol -> block -/\n(defs : PTree (globdef F V))     /- mapping block -> definition -/\n(next : block)                     /- next symbol pointer -/\n(symb_range : \u2200 {id b}, PTree.get id symb = some b \u2192 b < next)\n(defs_range : \u2200 {b g}, PTree.get b defs = some g \u2192 b < next)\n(vars_inj : \u2200 {id1 id2 b},\n    PTree.get id1 symb = some b \u2192 PTree.get id2 symb = some b \u2192 id1 = id2)\n\nnamespace Genv\nsection\n\nvariable {F : Type}  /- The type of function descriptions -/\nvariable {V : Type}  /- The type of information attached to variables -/\n\n/- ** Lookup functions -/\n\n/- [find_symbol ge id] returns the block associated with the given name, if any -/\n\ndef find_symbol (ge : Genv F V) (id : ident) : option block :=\n  PTree.get id ge.symb\n\n/- [symbol_address ge id ofs] returns a pointer into the block associated\n  with [id], at byte offset [ofs].  [Vundef] is returned if no block is associated\n  to [id]. -/\n\ndef symbol_address (ge : Genv F V) (id : ident) (ofs : ptrofs) : val :=\n  match find_symbol ge id with\n| some b := Vptr b ofs\n| none := Vundef\n  end\n\n/- [public_symbol ge id] says whether the name [id] is public and defined. -/\n\ndef public_symbol (ge : Genv F V) (id : ident) : bool :=\n(find_symbol ge id).is_some && (id \u2208 ge.public)\n\n/- [find_def ge b] returns the global definition associated with the given address. -/\n\ndef find_def (ge : Genv F V) (b : block) : option (globdef F V) :=\nPTree.get b ge.defs\n\n/- [find_funct_ptr ge b] returns the function description associated with\n    the given address. -/\n\ndef find_funct_ptr (ge : Genv F V) (b : block) : option F :=\nmatch find_def ge b with some (Gfun f) := some f | _ := none end\n\n/- [find_funct] is similar to [find_funct_ptr], but the function address\n    is given as a value, which must be a pointer with offset 0. -/\n\ndef find_funct (ge : Genv F V) : val \u2192 option F\n| (Vptr b ofs) := if ofs = 0 then find_funct_ptr ge b else none\n| _ := none\n\n/- [invert_symbol ge b] returns the name associated with the given block, if any -/\n\ndef invert_symbol (ge : Genv F V) (b : block) : option ident :=\nPTree.fold\n  (\u03bb res id b', if b = b' then some id else res)\n  ge.symb none\n\n/- [find_var_info ge b] returns the information attached to the variable\n   at address [b]. -/\n\ndef find_var_info (ge : Genv F V) (b : block) : option (globvar V) :=\nmatch find_def ge b with some (Gvar v) := some v | _ := none end\n\n/- [block_is_volatile ge b] returns [true] if [b] points to a global variable\n  of volatile type, [false] otherwise. -/\n\ndef block_is_volatile (ge : Genv F V) (b : block) : bool :=\nmatch find_var_info ge b with\n| none := ff\n| some gv := gv.volatile\nend\n\n/- ** Constructing the global environment -/\n\ndef add_global (ge : Genv F V) : ident \u00d7 globdef F V \u2192 Genv F V | (id, g) :=\n{ public := ge.public,\n  symb := PTree.set id ge.next ge.symb,\n  defs := PTree.set ge.next g ge.defs,\n  next := ge.next.succ,\n  symb_range := \u03bbid' b h, show (_:\u2115)<_, begin\n    rw pos_num.succ_to_nat,\n    apply nat.lt_succ_of_le,\n    rw PTree.gsspec at h,\n    by_cases id' = id with ii; simp [ii] at h,\n    { injection h, rw h },\n    { exact le_of_lt (ge.symb_range h) }\n  end,\n  defs_range := \u03bbb g' h, show (_:\u2115)<_, begin\n    rw pos_num.succ_to_nat,\n    apply nat.lt_succ_of_le,\n    rw PTree.gsspec at h,\n    by_cases b = ge.next with bb,\n    { rw bb },\n    { simp [bb] at h, exact le_of_lt (ge.defs_range h) }\n  end,\n  vars_inj := \u03bbid1 id2 b h1 h2, begin\n    rw PTree.gsspec at h1 h2,\n    by_cases id1 = id with i1; simp [i1] at h1;\n    by_cases id2 = id with i2; simp [i2] at h2; try {simp [i1, i2]},\n    { rw -h1 at h2, exact absurd (ge.symb_range h2) (lt_irrefl _) },\n    { rw -h2 at h1, exact absurd (ge.symb_range h1) (lt_irrefl _) },\n    { exact ge.vars_inj h1 h2 },\n  end }\n\ndef add_globals (ge : Genv F V) (gl : list (ident \u00d7 globdef F V)) : Genv F V :=\ngl.foldl add_global ge\n\nlemma add_globals_app (ge : Genv F V) (gl2 gl1) :\n  add_globals ge (gl1 ++ gl2) = add_globals (add_globals ge gl1) gl2 := sorry'\n\ndef empty (pub : list ident) : Genv F V :=\n{ public := pub,\n  symb := \u2205,\n  defs := \u2205,\n  next := 1,\n  symb_range := \u03bbid' b h, by rw PTree.gempty at h; contradiction,\n  defs_range := \u03bbb g' h, by rw PTree.gempty at h; contradiction,\n  vars_inj := \u03bbid1 id2 b h, by rw PTree.gempty at h; contradiction }\n\ndef globalenv (p : program F V) : Genv F V := add_globals (empty p.public) p.defs\n\n/- Proof principles -/\n\nsection globalenv_principles\n\nvariable P : Genv F V \u2192 Prop\ninclude P\n\nlemma add_globals_preserves {gl ge} :\n  (\u2200 ge id g, P ge \u2192 (id, g) \u2208 gl \u2192 P (add_global ge (id, g))) \u2192\n  P ge \u2192 P (add_globals ge gl) := sorry'\n\nlemma add_globals_ensures {id g gl ge} :\n  (\u2200 ge id g, P ge \u2192 (id, g) \u2208 gl \u2192 P (add_global ge (id, g))) \u2192\n  (\u2200 ge, P (add_global ge (id, g))) \u2192\n  (id, g) \u2208 gl \u2192 P (add_globals ge gl) := sorry'\n\nlemma add_globals_unique_preserves {id gl ge} :\n  (\u2200 ge id1 g, P ge \u2192 (id1, g) \u2208 gl \u2192 id1 \u2260 id \u2192 P (add_global ge (id1, g))) \u2192\n  id \u2209 list.map prod.fst gl \u2192 P ge \u2192 P (add_globals ge gl) := sorry'\n\nlemma add_globals_unique_ensures {gl1 id g gl2 ge} :\n  (\u2200 ge id1 g1, P ge \u2192 (id1, g1) \u2208 gl2 \u2192 id1 \u2260 id \u2192 P (add_global ge (id1, g1))) \u2192\n  (\u2200 ge, P (add_global ge (id, g))) \u2192\n  id \u2209 list.map prod.fst gl2 \u2192 P (add_globals ge (gl1 ++ (id, g) :: gl2)) := sorry'\n\ntheorem in_norepet_unique {id g} {gl : list (ident \u00d7 globdef F V)} :\n  (id, g) \u2208 gl \u2192 (gl.map prod.fst).nodup \u2192\n  \u2203 gl1 gl2, gl = gl1 ++ (id, g) :: gl2 \u2227 id \u2208 gl2.map prod.fst := sorry'\n\nlemma add_globals_norepet_ensures {id g gl ge} :\n  (\u2200 ge id1 g1, P ge \u2192 (id1, g1) \u2208 gl \u2192 id1 \u2260 id \u2192 P (add_global ge (id1, g1))) \u2192\n  (\u2200 ge, P (add_global ge (id, g))) \u2192\n  (id, g) \u2208 gl \u2192 (list.map prod.fst gl).nodup \u2192 P (add_globals ge gl) := sorry'\n\nend globalenv_principles\n\n/- ** Properties of the operations over global environments -/\n\ntheorem public_symbol_exists {ge : Genv F V} {id} :\n  public_symbol ge id \u2192 \u2203 b, find_symbol ge id = some b := sorry'\n\ntheorem shift_symbol_address {ge : Genv F V} {id ofs delta} :\n  symbol_address ge id (ofs + delta) = (symbol_address ge id ofs).offset_ptr delta := sorry'\n\ntheorem shift_symbol_address_32 {ge : Genv F V} {id ofs n} :\n  \u00ac archi.ptr64 \u2192\n  symbol_address ge id (ofs + ptrofs.of_int n) = symbol_address ge id ofs + n := sorry'\n\ntheorem shift_symbol_address_64 {ge : Genv F V} {id ofs n} :\n  archi.ptr64 \u2192\n  symbol_address ge id (ofs + ptrofs.of_int64 n) = (symbol_address ge id ofs).addl n := sorry'\n\ntheorem find_funct_inv {ge : Genv F V} {v f} :\n  find_funct ge v = some f \u2192 \u2203 b, v = Vptr b 0 := sorry'\n\ntheorem find_funct_find_funct_ptr {ge : Genv F V} {b} :\n  find_funct ge (Vptr b 0) = find_funct_ptr ge b := sorry'\n\ntheorem find_funct_ptr_iff {ge : Genv F V} {b f} :\n  find_funct_ptr ge b = some f \u2194 find_def ge b = some (Gfun f) := sorry'\n\ntheorem find_var_info_iff {ge : Genv F V} {b v} :\n  find_var_info ge b = some v \u2194 find_def ge b = some (Gvar v) := sorry'\n\ntheorem find_def_symbol {p : program F V} {id g} :\n  (prog_defmap p^!id) = some g \u2194\n  \u2203 b, find_symbol (globalenv p) id = some b \u2227\n       find_def (globalenv p) b = some g := sorry'\n\ntheorem find_symbol_exists {p : program F V} {id g} :\n  (id, g) \u2208 p.defs \u2192\n  \u2203 b, find_symbol (globalenv p) id = some b := sorry'\n\ntheorem find_symbol_inversion {p : program F V} {x b} :\n  find_symbol (globalenv p) x = some b \u2192\n  x \u2208 p.defs_names := sorry'\n\ntheorem find_def_inversion {p : program F V} {b g} :\n  find_def (globalenv p) b = some g \u2192\n  \u2203 id, (id, g) \u2208 p.defs := sorry'\n\ntheorem find_funct_ptr_inversion {p : program F V} {b f} :\n  find_funct_ptr (globalenv p) b = some f \u2192\n  \u2203 id, (id, Gfun f) \u2208 p.defs := sorry'\n\ntheorem find_funct_inversion {p : program F V} {v f} :\n  find_funct (globalenv p) v = some f \u2192\n  \u2203 id, (id, Gfun f) \u2208 p.defs := sorry'\n\ntheorem find_funct_ptr_prop (P : F \u2192 Prop) {p : program F V} {b f} :\n  (\u2200 id f, (id, Gfun f) \u2208 p.defs \u2192 P f) \u2192\n  find_funct_ptr (globalenv p) b = some f \u2192\n  P f := sorry'\n\ntheorem find_funct_prop (P : F \u2192 Prop) {p : program F V} {v f} :\n  (\u2200 id f, (id, Gfun f) \u2208 p.defs \u2192 P f) \u2192\n  find_funct (globalenv p) v = some f \u2192\n  P f := sorry'\n\ntheorem global_addresses_distinct {ge : Genv F V} {id1 id2 b1 b2} :\n  id1 \u2260 id2 \u2192\n  find_symbol ge id1 = some b1 \u2192\n  find_symbol ge id2 = some b2 \u2192\n  b1 \u2260 b2 := sorry'\n\ntheorem invert_find_symbol {ge : Genv F V} {id b} :\n  invert_symbol ge b = some id \u2192 find_symbol ge id = some b := sorry'\n\ntheorem find_invert_symbol {ge : Genv F V} {id b} :\n  find_symbol ge id = some b \u2192 invert_symbol ge b = some id := sorry'\n\ndef advance_next (gl : list (ident \u00d7 globdef F V)) (x : pos_num) :=\ngl.foldl (\u03bb n g, pos_num.succ n) x\n\ntheorem genv_next_add_globals (gl) (ge : Genv F V) :\n  (add_globals ge gl).next = advance_next gl ge.next := sorry'\n\ntheorem genv_public_add_globals (gl) (ge : Genv F V) :\n  (add_globals ge gl).public = ge.public := sorry'\n\ntheorem globalenv_public (p : program F V) :\n  (globalenv p).public = p.public := sorry'\n\ntheorem block_is_volatile_below {ge : Genv F V} {b} :\n  block_is_volatile ge b \u2192 b < ge.next := sorry'\n\n/- ** Coercing a global environment into a symbol environment -/\n\ndef to_senv (ge : Genv F V) : Senv :=\n{ find_symbol := ge.find_symbol,\n  public_symbol := ge.public_symbol,\n  invert_symbol := ge.invert_symbol,\n  block_is_volatile := ge.block_is_volatile,\n  nextblock := ge.next,\n  find_symbol_injective := ge.vars_inj,\n  invert_find_symbol := ge.invert_find_symbol,\n  find_invert_symbol := ge.find_invert_symbol,\n  public_symbol_exists := ge.public_symbol_exists,\n  find_symbol_below := ge.symb_range,\n  block_is_volatile_below := ge.block_is_volatile_below }\n\ninstance : has_coe (Genv F V) Senv := \u27e8to_senv\u27e9\n\n/- * Construction of the initial memory state -/\n\nsection init_mem\n\nvariable ge : Genv F V\n\ndef store_init_data (m : mem) (b : block) (p : \u2115) : init_data \u2192 option mem\n| (init_data.int8 n) := store Mint8unsigned m b p (Vint n)\n| (init_data.int16 n) := store Mint16unsigned m b p (Vint n)\n| (init_data.int32 n) := store Mint32 m b p (Vint n)\n| (init_data.int64 n) := store Mint64 m b p (Vlong n)\n| (init_data.float32 n) := store Mfloat32 m b p (Vsingle n)\n| (init_data.float64 n) := store Mfloat64 m b p (Vfloat n)\n| (init_data.addrof symb ofs) :=\n  do b' \u2190 find_symbol ge symb, store Mptr m b p (Vptr b' ofs)\n| (init_data.space n) := some m\n\ndef store_init_data_list : mem \u2192 block \u2192 \u2115 \u2192 list init_data \u2192 option mem\n| m b p [] := some m\n| m b p (id :: idl') :=\n  do m' \u2190 store_init_data ge m b p id,\n     store_init_data_list m' b (p + id.size) idl'\n\ndef perm_globvar (gv : globvar V) : permission :=\n  if gv.volatile then Nonempty\n  else if gv.readonly then Readable\n  else Writable\n\ndef alloc_global (m : mem) : ident \u00d7 globdef F V \u2192 option mem\n| (id, Gfun f) :=\n  drop_perm (m.alloc 0 1) m.nextblock 0 1 Nonempty\n| (id, Gvar v) := do\n  let init := v.init,\n  let sz := init_data.list_size init,\n  let b := m.nextblock,\n  let m1 := m.alloc 0 sz,\n  m2 \u2190 store_zeros m1 b 0 sz,\n  m3 \u2190 store_init_data_list ge m2 b 0 init,\n  drop_perm m3 b 0 sz (perm_globvar v)\n\ndef alloc_globals : mem \u2192 list (ident \u00d7 globdef F V) \u2192 option mem :=\nmfoldl (alloc_global ge)\n\nlemma alloc_globals_app {gl1 gl2 m m1} :\n  alloc_globals ge m gl1 = some m1 \u2192\n  alloc_globals ge m1 gl2 = alloc_globals ge m (gl1 ++ gl2) := sorry'\n\n/- Next-block properties -/\n\ntheorem store_zeros_nextblock {m b p n m'} : store_zeros m b p n = some m' \u2192\n  m'.nextblock = m.nextblock := sorry'\n\ntheorem store_init_data_list_nextblock {idl b m p m'} :\n  store_init_data_list ge m b p idl = some m' \u2192\n  m'.nextblock = m.nextblock := sorry'\n\ntheorem alloc_global_nextblock {g m m'} :\n  alloc_global ge m g = some m' \u2192\n  m'.nextblock = m.nextblock.succ := sorry'\n\ntheorem alloc_globals_nextblock {gl m m'} :\n  alloc_globals ge m gl = some m' \u2192\n  m'.nextblock = advance_next gl m.nextblock := sorry'\n\n/- Permissions -/\n\ntheorem store_zeros_perm {k prm b' q m b p n m'} :\n  store_zeros m b p n = some m' \u2192\n  (perm m b' q k prm \u2194 perm m' b' q k prm) := sorry'\n\ntheorem store_init_data_perm {k prm b' q i b m p m'} :\n  store_init_data ge m b p i = some m' \u2192\n  (perm m b' q k prm \u2194 perm m' b' q k prm) := sorry'\n\ntheorem store_init_data_list_perm {k prm b' q idl b m p m'} :\n  store_init_data_list ge m b p idl = some m' \u2192\n  (perm m b' q k prm \u2194 perm m' b' q k prm) := sorry'\n\ntheorem alloc_global_perm {k prm b' q idg m m'} :\n  alloc_global ge m idg = some m' \u2192\n  valid_block m b' \u2192\n  (perm m b' q k prm \u2194 perm m' b' q k prm) := sorry'\n\ntheorem alloc_globals_perm {k prm b' q gl m m'} :\n  alloc_globals ge m gl = some m' \u2192\n  valid_block m b' \u2192\n  (perm m b' q k prm \u2194 perm m' b' q k prm) := sorry'\n\n/- Data preservation properties -/\n\ntheorem store_zeros_unchanged {P : block \u2192 \u2115 \u2192 Prop} {m b p n m'} :\n  store_zeros m b p n = some m' \u2192\n  (\u2200 i, p \u2264 i \u2192 i < p + n \u2192 \u00ac P b i) \u2192\n  unchanged_on P m m' := sorry'\n\ntheorem store_init_data_unchanged {P : block \u2192 \u2115 \u2192 Prop} {b i m p m'} :\n  store_init_data ge m b p i = some m' \u2192\n  (\u2200 ofs, p \u2264 ofs \u2192 ofs < p + i.size \u2192 \u00ac P b ofs) \u2192\n  unchanged_on P m m' := sorry'\n\ntheorem store_init_data_list_unchanged {P : block \u2192 \u2115 \u2192 Prop} {b il m p m'} :\n  store_init_data_list ge m b p il = some m' \u2192\n  (\u2200 ofs, p \u2264 ofs \u2192 \u00ac P b ofs) \u2192\n  unchanged_on P m m' := sorry'\n\n/- Properties related to [load_bytes] -/\n\ndef readbytes_as_zero (m : mem) (b : block) (ofs len : \u2115) : Prop :=\n  \u2200 p n,\n  ofs \u2264 p \u2192 p + n \u2264 ofs + len \u2192\n  load_bytes m b p n = some (list.repeat (Byte 0) n)\n\nlemma store_zeros_load_bytes {m b p n m'} :\n  store_zeros m b p n = some m' \u2192\n  readbytes_as_zero m' b p n := sorry'\n\ndef bytes_of_init_data (i : init_data) : list memval :=\n  match i with\n| (init_data.int8 n) := inj_bytes (encode_int 1 (unsigned n))\n| (init_data.int16 n) := inj_bytes (encode_int 2 (unsigned n))\n| (init_data.int32 n) := inj_bytes (encode_int 4 (unsigned n))\n| (init_data.int64 n) := inj_bytes (encode_int 8 (unsigned n))\n| (init_data.float32 n) := inj_bytes (encode_int 4 (unsigned (float32.to_bits n)))\n| (init_data.float64 n) := inj_bytes (encode_int 8 (unsigned (float.to_bits n)))\n| (init_data.space n) := list.repeat (Byte 0) n\n| (init_data.addrof id ofs) :=\n      match find_symbol ge id with\n      | some b := inj_value (if archi.ptr64 then Q64 else Q32) (Vptr b ofs)\n      | none   := list.repeat Undef (if archi.ptr64 then 8 else 4)\n      end\n  end\n\ntheorem init_data_size_addrof {id ofs} :\n  (init_data.addrof id ofs).size = (Mptr).size := sorry'\n\nlemma store_init_data_load_bytes {m b p i m'} :\n  store_init_data ge m b p i = some m' \u2192\n  readbytes_as_zero m b p i.size \u2192\n  load_bytes m' b p i.size = some (bytes_of_init_data ge i) := sorry'\n\ndef bytes_of_init_data_list (il : list init_data) : list memval :=\nil >>= bytes_of_init_data ge\n\nlemma store_init_data_list_load_bytes {b il m p m'} :\n  store_init_data_list ge m b p il = some m' \u2192\n  readbytes_as_zero m b p (init_data.list_size il) \u2192\n  load_bytes m' b p (init_data.list_size il) =\n    some (bytes_of_init_data_list ge il) := sorry'\n\n/- Properties related to [load] -/\n\ndef chunk_zero_val : memory_chunk \u2192 val\n| Mint8unsigned  := Vint 0\n| Mint8signed    := Vint 0\n| Mint16unsigned := Vint 0\n| Mint16signed   := Vint 0\n| Mint32         := Vint 0\n| Mint64         := Vlong 0\n| Mfloat32       := Vsingle 0\n| Mfloat64       := Vfloat 0\n| Many32         := Vundef\n| Many64         := Vundef\n\ndef read_as_zero (m : mem) (b : block) (ofs len : \u2115) : Prop :=\n\u2200 (chunk : memory_chunk) p,\n  ofs \u2264 p \u2192 p + chunk.size \u2264 ofs + len \u2192\n  chunk.align \u2223 p \u2192\n  load chunk m b p =\n  some (chunk_zero_val chunk)\n\ntheorem read_as_zero_unchanged {P : block \u2192 \u2115 \u2192 Prop} {m b ofs len m'} :\n  read_as_zero m b ofs len \u2192\n  unchanged_on P m m' \u2192\n  (\u2200 i, ofs \u2264 i \u2192 i < ofs + len \u2192 P b i) \u2192\n  read_as_zero m' b ofs len := sorry'\n\nlemma store_zeros_read_as_zero {m b p n m'} :\n  store_zeros m b p n = some m' \u2192\n  read_as_zero m' b p n := sorry'\n\ndef load_store_init_data (m : mem) (b : block) : \u2115 \u2192 list init_data \u2192 Prop\n| p [] := true\n| p (init_data.int8 n :: il') :=\n  load Mint8unsigned m b p = some (Vint (zero_ext 8 n))\n  \u2227 load_store_init_data (p + 1) il'\n| p (init_data.int16 n :: il') :=\n  load Mint16unsigned m b p = some (Vint (zero_ext 16 n))\n  \u2227 load_store_init_data (p + 2) il'\n| p (init_data.int32 n :: il') :=\n  load Mint32 m b p = some (Vint n)\n  \u2227 load_store_init_data (p + 4) il'\n| p (init_data.int64 n :: il') :=\n  load Mint64 m b p = some (Vlong n)\n  \u2227 load_store_init_data (p + 8) il'\n| p (init_data.float32 n :: il') :=\n  load Mfloat32 m b p = some (Vsingle n)\n  \u2227 load_store_init_data (p + 4) il'\n| p (init_data.float64 n :: il') :=\n  load Mfloat64 m b p = some (Vfloat n)\n  \u2227 load_store_init_data (p + 8) il'\n| p (init_data.addrof symb ofs :: il') :=\n  (\u2203 b', find_symbol ge symb = some b' \u2227 load Mptr m b p = some (Vptr b' ofs))\n  \u2227 load_store_init_data (p + (Mptr).size) il'\n| p (init_data.space n :: il') :=\n  read_as_zero m b p n\n  \u2227 load_store_init_data (p + n) il'\n\nlemma store_init_data_list_charact {b il m p m'} :\n  store_init_data_list ge m b p il = some m' \u2192\n  read_as_zero m b p (init_data.list_size il) \u2192\n  load_store_init_data ge m' b p il := sorry'\n\ntheorem alloc_global_unchanged {P : block \u2192 \u2115 \u2192 Prop} {m id g m'} :\n  alloc_global ge m (id, g) = some m' \u2192\n  unchanged_on P m m' := sorry'\n\ntheorem alloc_globals_unchanged {P : block \u2192 \u2115 \u2192 Prop} {gl m m'} :\n  alloc_globals ge m gl = some m' \u2192\n  unchanged_on P m m' := sorry'\n\ntheorem load_store_init_data_invariant {m m' b} :\n  (\u2200 chunk ofs, load chunk m' b ofs = load chunk m b ofs) \u2192\n  \u2200 il p,\n  load_store_init_data ge m b p il \u2192 load_store_init_data ge m' b p il := sorry'\n\ndef globdef_initialized (m : mem) (b : block) : globdef F V \u2192 Prop\n| (Gfun f) :=\n         perm m b 0 Cur Nonempty\n      \u2227 (\u2200 ofs k p, perm m b ofs k p \u2192 ofs = 0 \u2227 p = Nonempty)\n| (Gvar v) :=\n         range_perm m b 0 (init_data.list_size v.init) Cur (perm_globvar v)\n      \u2227 (\u2200 ofs k p, perm m b ofs k p \u2192\n            ofs < init_data.list_size v.init \u2227 perm_order (perm_globvar v) p)\n      \u2227 (\u00ac v.volatile \u2192 load_store_init_data ge m b 0 v.init)\n      \u2227 (\u00ac v.volatile \u2192 load_bytes m b 0 (init_data.list_size v.init) =\n                        some (bytes_of_init_data_list ge v.init))\n\ndef globals_initialized (g : Genv F V) (m : mem) :=\n\u2200 b gd, find_def g b = some gd \u2192 globdef_initialized ge m b gd\n\nlemma alloc_global_initialized {g : Genv F V} {m : mem} {id gd m'} :\n  g.next = m.nextblock \u2192\n  alloc_global ge m (id, gd) = some m' \u2192\n  globals_initialized ge g m \u2192\n     globals_initialized ge (add_global g (id, gd)) m'\n  \u2227 (add_global g (id, gd)).next = m'.nextblock := sorry'\n\nlemma alloc_globals_initialized {gl} {g : Genv F V} {m m'} :\n  alloc_globals g m gl = some m' \u2192\n  g.next = m.nextblock \u2192\n  globals_initialized ge g m \u2192\n  globals_initialized ge (add_globals g gl) m' := sorry'\n\nend init_mem\n\ndef init_mem (p : program F V) :=\nalloc_globals (globalenv p) \u2205 p.defs\n\nlemma init_mem_genv_next {p : program F V} {m} :\n  init_mem p = some m \u2192\n  (globalenv p).next = m.nextblock := sorry'\n\ntheorem find_symbol_not_fresh {p : program F V} {id b m} :\n  init_mem p = some m \u2192\n  find_symbol (globalenv p) id = some b \u2192 valid_block m b := sorry'\n\ntheorem find_def_not_fresh {p : program F V} {b g m} :\n  init_mem p = some m \u2192\n  find_def (globalenv p) b = some g \u2192 valid_block m b := sorry'\n\ntheorem find_funct_ptr_not_fresh {p : program F V} {b f m} :\n  init_mem p = some m \u2192\n  find_funct_ptr (globalenv p) b = some f \u2192 valid_block m b := sorry'\n\ntheorem find_var_info_not_fresh {p : program F V} {b gv m} :\n  init_mem p = some m \u2192\n  find_var_info (globalenv p) b = some gv \u2192 valid_block m b := sorry'\n\nlemma init_mem_characterization_gen {p : program F V} {m} :\n  init_mem p = some m \u2192\n  globals_initialized (globalenv p) (globalenv p) m := sorry'\n\ntheorem init_mem_characterization {p : program F V} {b gv m} :\n  find_var_info (globalenv p) b = some gv \u2192\n  init_mem p = some m \u2192\n  range_perm m b 0 (init_data.list_size gv.init) Cur (perm_globvar gv)\n  \u2227 (\u2200 ofs k p, perm m b ofs k p \u2192\n        ofs < init_data.list_size gv.init \u2227 perm_order (perm_globvar gv) p)\n  \u2227 (\u00ac gv.volatile \u2192\n      load_store_init_data (globalenv p) m b 0 gv.init)\n  \u2227 (\u00ac gv.volatile \u2192\n      load_bytes m b 0 (init_data.list_size gv.init) =\n      some (bytes_of_init_data_list (globalenv p) gv.init)) := sorry'\n\ntheorem init_mem_characterization_2 {p : program F V} {b fd m} :\n  find_funct_ptr (globalenv p) b = some fd \u2192\n  init_mem p = some m \u2192\n  perm m b 0 Cur Nonempty\n  \u2227 (\u2200 ofs k p, perm m b ofs k p \u2192 ofs = 0 \u2227 p = Nonempty) := sorry'\n\n/- ** Compatibility with memory injections -/\n\nsection init_mem_inj\n\nvariable {ge : Genv F V}\nvariable {thr : block}\nvariable (symb_inject : \u2200 id b, find_symbol ge id = some b \u2192 b < thr)\ninclude symb_inject\n\nlemma store_zeros_neutral {m b p n m'} :\n  inject_neutral thr m \u2192\n  b < thr \u2192\n  store_zeros m b p n = some m' \u2192\n  inject_neutral thr m' := sorry'\n\nlemma store_init_data_neutral {m b p id m'} :\n  inject_neutral thr m \u2192\n  b < thr \u2192\n  store_init_data ge m b p id = some m' \u2192\n  inject_neutral thr m' := sorry'\n\nlemma store_init_data_list_neutral {b idl m p m'} :\n  inject_neutral thr m \u2192\n  b < thr \u2192\n  store_init_data_list ge m b p idl = some m' \u2192\n  inject_neutral thr m' := sorry'\n\nlemma alloc_global_neutral {idg m m'} :\n  alloc_global ge m idg = some m' \u2192\n  inject_neutral thr m \u2192\n  m.nextblock < thr \u2192\n  inject_neutral thr m' := sorry'\n\ntheorem advance_next_le : \u2200 gl x, x \u2264 @advance_next F V gl x := sorry'\n\nlemma alloc_globals_neutral {gl m m'} :\n  alloc_globals ge m gl = some m' \u2192\n  inject_neutral thr m \u2192\n  m'.nextblock \u2264 thr \u2192\n  inject_neutral thr m' := sorry'\n\nend init_mem_inj\n\ntheorem initmem_inject {p : program F V} {m} :\n  init_mem p = some m \u2192\n  inject (flat_inj m.nextblock) m m := sorry'\n\n/- ** Sufficient and necessary conditions for the initial memory to exist. -/\n\n/- Alignment properties -/\n\nsection init_mem_inversion\n\nvariable (ge : Genv F V)\n\nlemma store_init_data_aligned {m b p i m'} :\n  store_init_data ge m b p i = some m' \u2192\n  i.align \u2223 p := sorry'\n\nlemma store_init_data_list_aligned {b il m p m'} :\n  store_init_data_list ge m b p il = some m' \u2192\n  init_data.list_aligned p il := sorry'\n\nlemma store_init_data_list_free_idents {b i o il m p m'} :\n  store_init_data_list ge m b p il = some m' \u2192\n  init_data.addrof i o \u2208 il \u2192\n  \u2203 b', find_symbol ge i = some b' := sorry'\n\nend init_mem_inversion\n\ntheorem init_mem_inversion {p : program F V} {m id v} :\n  init_mem p = some m \u2192\n  (id, Gvar v) \u2208 p.defs \u2192\n  init_data.list_aligned 0 v.init\n  \u2227 \u2200 i o, init_data.addrof i o \u2208 v.init \u2192\n    \u2203 b, find_symbol (globalenv p) i = some b := sorry'\n\nsection init_mem_exists\n\nvariable (ge : Genv F V)\n\nlemma store_zeros_exists {m b p n} :\n  range_perm m b p (p + n) Cur Writable \u2192\n  \u2203 m', store_zeros m b p n = some m' := sorry'\n\nlemma store_init_data_exists {m b p} {i : init_data} :\n  range_perm m b p (p + i.size) Cur Writable \u2192\n  i.align \u2223 p \u2192\n  (\u2200 id ofs, i = init_data.addrof id ofs \u2192 \u2203 b, find_symbol ge id = some b) \u2192\n  \u2203 m', store_init_data ge m b p i = some m' := sorry'\n\nlemma store_init_data_list_exists {b il m p} :\n  range_perm m b p (p + init_data.list_size il) Cur Writable \u2192\n  init_data.list_aligned p il \u2192\n  (\u2200 id ofs, init_data.addrof id ofs \u2208 il \u2192 \u2203 b, find_symbol ge id = some b) \u2192\n  \u2203 m', store_init_data_list ge m b p il = some m' := sorry'\n\ndef alloc_global_exists_ty : globdef F V \u2192 Prop\n| (Gfun f) := true\n| (Gvar v) := init_data.list_aligned 0 v.init\n     \u2227 \u2200 i o, init_data.addrof i o \u2208 v.init \u2192 \u2203 b, find_symbol ge i = some b\n\nlemma alloc_global_exists {m id g} :\n  alloc_global_exists_ty ge g \u2192\n  \u2203 m', alloc_global ge m (id, g) = some m' := sorry'\n\nend init_mem_exists\n\ntheorem init_mem_exists {p : program F V} :\n  (\u2200 id v, (id, Gvar v) \u2208 p.defs \u2192\n        init_data.list_aligned 0 v.init\n     \u2227 \u2200 i o, init_data.addrof i o \u2208 v.init \u2192\n        \u2203 b, find_symbol (globalenv p) i = some b) \u2192\n  \u2203 m, init_mem p = some m := sorry' \n\nend\n\n/- * Commutation with program transformations -/\n\nsection match_genvs\n\nparameters {A B V W : Type} (R : globdef A V \u2192 globdef B W \u2192 Prop)\n\nstructure match_genvs (ge1 : Genv A V) (ge2 : Genv B W) : Prop :=\n(next : ge2.next = ge1.next)\n(symb : \u2200 id, PTree.get id ge2.symb = PTree.get id ge1.symb)\n(defs : \u2200 b, option.rel R (PTree.get b ge1.defs) (PTree.get b ge2.defs))\n\nlemma add_global_match {ge1 ge2 id g1 g2} :\n  match_genvs ge1 ge2 \u2192\n  R g1 g2 \u2192\n  match_genvs (ge1.add_global (id, g1)) (ge2.add_global (id, g2)) := sorry'\n\nlemma add_globals_match {gl1 gl2} :\n  list.forall2 (\u03bb \u27e8id1, g1\u27e9 \u27e8id2, g2\u27e9, id1 = id2 \u2227 R g1 g2 :\n    (ident \u00d7 globdef A V) \u2192 (ident \u00d7 globdef B W) \u2192 Prop) gl1 gl2 \u2192\n  \u2200 {ge1 ge2}, match_genvs ge1 ge2 \u2192\n  match_genvs (ge1.add_globals gl1) (ge2.add_globals gl2) := sorry'\n\nend match_genvs\n\nsection match_programs\n\nparameters {C F1 V1 F2 V2 : Type} [linker C] [linker F1] [linker V1]\nparameter {match_fundef : C \u2192 F1 \u2192 F2 \u2192 Prop}\nparameter {match_varinfo : V1 \u2192 V2 \u2192 Prop}\nparameter {ctx : C}\nparameter {p : program F1 V1}\nparameter {tp : program F2 V2}\nparameter (progmatch : match_program_gen match_fundef match_varinfo ctx p tp)\n\nlemma globalenvs_match : match_genvs (match_globdef match_fundef match_varinfo ctx)\n  (globalenv p) (globalenv tp) := sorry'\n\ntheorem find_def_match_2 {b} : option.rel (match_globdef match_fundef match_varinfo ctx)\n  (find_def (globalenv p) b) (find_def (globalenv tp) b) := sorry'\n\ntheorem find_funct_ptr_match {b f} : find_funct_ptr (globalenv p) b = some f \u2192\n  \u2203 cunit tf, find_funct_ptr (globalenv tp) b = some tf \u2227 match_fundef cunit f tf \u2227\n    linkorder cunit ctx := sorry'\n\ntheorem find_funct_match {v f} : find_funct (globalenv p) v = some f \u2192\n  \u2203 cunit tf, find_funct (globalenv tp) v = some tf \u2227 match_fundef cunit f tf \u2227\n    linkorder cunit ctx := sorry'\n\ntheorem find_var_info_match {b v} : find_var_info (globalenv p) b = some v \u2192\n  \u2203 tv, find_var_info (globalenv tp) b = some tv \u2227 match_globvar match_varinfo v tv := sorry'\n\ntheorem find_symbol_match {s : ident} :\n  find_symbol (globalenv tp) s = find_symbol (globalenv p) s := sorry'\n\ntheorem senv_match : Senv.equiv (globalenv p) (globalenv tp) := sorry'\n\nlemma store_init_data_list_match {idl m b ofs m'} :\n  store_init_data_list (globalenv p) m b ofs idl = some m' \u2192\n  store_init_data_list (globalenv tp) m b ofs idl = some m' := sorry'\n\nlemma alloc_globals_match {gl1 gl2} :\n  list.forall2 (match_ident_globdef match_fundef match_varinfo ctx) gl1 gl2 \u2192\n  \u2200 m m', alloc_globals (globalenv p) m gl1 = some m' \u2192\n  alloc_globals (globalenv tp) m gl2 = some m' := sorry'\n\ntheorem init_mem_match {m} : init_mem p = some m \u2192 init_mem tp = some m := sorry'\n\nend match_programs\n\n/- Special case for partial transformations that do not depend on the compilation unit -/\n\nsection transform_partial\n\nparameters {A B V : Type} [linker A] [linker V]\nparameters {transf : A \u2192 res B} {p : program A V} {tp : program B V}\nparameter (progmatch : match_program (\u03bb cu f tf, transf f = OK tf) eq p tp)\n\ntheorem find_funct_ptr_transf_partial {b f} : find_funct_ptr (globalenv p) b = some f \u2192\n  \u2203 tf, find_funct_ptr (globalenv tp) b = some tf \u2227 transf f = OK tf := sorry'\n\ntheorem find_funct_transf_partial {v f} : find_funct (globalenv p) v = some f \u2192\n  \u2203 tf, find_funct (globalenv tp) v = some tf \u2227 transf f = OK tf := sorry'\n\ntheorem find_symbol_transf_partial {s : ident} :\n  find_symbol (globalenv tp) s = find_symbol (globalenv p) s := sorry'\n\ntheorem senv_transf_partial : Senv.equiv (globalenv p) (globalenv tp) := sorry'\n\ntheorem init_mem_transf_partial {m} : init_mem p = some m \u2192 init_mem tp = some m := sorry'\n\nend transform_partial\n\n/- Special case for total transformations that do not depend on the compilation unit -/\n\nsection transform_total\n\nparameters {A B V : Type} [linker A] [linker V]\nparameters {transf : A \u2192 B} {p : program A V} {tp : program B V}\nparameter (progmatch : match_program (\u03bb cu f tf, tf = transf f) eq p tp)\n\ntheorem find_funct_ptr_transf {b f} :\n  find_funct_ptr (globalenv p) b = some f \u2192\n  find_funct_ptr (globalenv tp) b = some (transf f) := sorry'\n\ntheorem find_funct_transf {v f} :\n  find_funct (globalenv p) v = some f \u2192\n  find_funct (globalenv tp) v = some (transf f) := sorry'\n\ntheorem find_symbol_transf {s : ident} :\n  find_symbol (globalenv tp) s = find_symbol (globalenv p) s := sorry'\n\ntheorem senv_transf : Senv.equiv (globalenv p) (globalenv tp) := sorry'\n\ntheorem init_mem_transf {m} : init_mem p = some m \u2192 init_mem tp = some m := sorry'\n\nend transform_total\n\nend Genv\n\nend globalenvs", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/globalenvs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.05834583692755956, "lm_q1q2_score": 0.024207621242525585}}
{"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-/\nprelude\nimport Init.Core\nimport Init.Control.Basic\nimport Init.Coe\n\nnamespace Option\n\ndef toMonad [Monad m] [Alternative m] : Option \u03b1 \u2192 m \u03b1\n  | none     => failure\n  | some a   => pure a\n\n@[inline] def toBool : Option \u03b1 \u2192 Bool\n  | some _ => true\n  | none   => false\n\n@[inline] def isSome : Option \u03b1 \u2192 Bool\n  | some _ => true\n  | none   => false\n\n@[inline] def isNone : Option \u03b1 \u2192 Bool\n  | some _ => false\n  | none   => true\n\n@[inline] protected def bind : Option \u03b1 \u2192 (\u03b1 \u2192 Option \u03b2) \u2192 Option \u03b2\n  | none,   b => none\n  | some a, b => b a\n\n@[inline] protected def map (f : \u03b1 \u2192 \u03b2) (o : Option \u03b1) : Option \u03b2 :=\n  Option.bind o (some \u2218 f)\n\ntheorem mapId : (Option.map id : Option \u03b1 \u2192 Option \u03b1) = id :=\n  funext (fun o => match o with | none => rfl | some x => rfl)\n\ninstance : Functor Option where\n  map := Option.map\n\n@[inline] protected def filter (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Option \u03b1\n  | some a => if p a then some a else none\n  | none   => none\n\n@[inline] protected def all (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Bool\n  | some a => p a\n  | none   => true\n\n@[inline] protected def any (p : \u03b1 \u2192 Bool) : Option \u03b1 \u2192 Bool\n  | some a => p a\n  | none   => false\n\n@[macroInline] protected def orElse : Option \u03b1 \u2192 Option \u03b1 \u2192 Option \u03b1\n  | some a, _ => some a\n  | none,   b => b\n\ninstance : OrElse (Option \u03b1) where\n  orElse := Option.orElse\n\n@[inline] protected def lt (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Option \u03b1 \u2192 Option \u03b1 \u2192 Prop\n  | none, some x     => True\n  | some x,   some y => r x y\n  | _, _             => False\n\ninstance (r : \u03b1 \u2192 \u03b1 \u2192 Prop) [s : DecidableRel r] : DecidableRel (Option.lt r)\n  | none,   some y => isTrue  trivial\n  | some x, some y => s x y\n  | some x, none   => isFalse notFalse\n  | none,   none   => isFalse notFalse\n\nend Option\n\nderiving instance DecidableEq for Option\nderiving instance BEq for Option\n\ninstance [LT \u03b1] : LT (Option \u03b1) where\n  lt := Option.lt (\u00b7 < \u00b7)\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/Option/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.05184547214356043, "lm_q1q2_score": 0.024103041468136483}}
{"text": "import tactic.lint\n\nvariables {\u03b1 : Type*}\n\n/-- A property which determins whether this option is inhabited. -/\ndef option.is_some' : option \u03b1 \u2192 Prop\n| (some _) := true\n| none := false\n\ninstance option.is_some'.decide : decidable_pred (@option.is_some' \u03b1)\n| (some _) := decidable.true\n| none := decidable.false\n\n/-- Extract the value of an option, given a proof it exists. -/\ndef option.get' : \u2200 {o : option \u03b1}, option.is_some' o \u2192 \u03b1\n| (some k) _ := k\n\nlemma option.eq_some_of_is_some' : \u2200 {o : option \u03b1} (h : option.is_some' o), o = some (option.get' h)\n| (some x) _ := rfl\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/option2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.04958902333517724, "lm_q1q2_score": 0.0240199353023065}}
{"text": "/-\nCopyright (c) 2021 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Lean.Aesop.Rule\nimport Lean.Aesop.RuleTac\n\nopen Lean.Meta\n\nnamespace Lean.Aesop\n\nstructure RegularRuleBuilderResult where\n  builderName : Name\n  tac : RuleTac\n  indexingMode : IndexingMode\n  deriving Inhabited\n\ninductive NormRuleBuilderResult\n  | regular (r : RegularRuleBuilderResult)\n  | simpEntries (es : Array SimpEntry)\n  deriving Inhabited\n\ninductive RuleIdent\n  | const (decl : Name)\n  | fvar (userName : Name)\n  deriving Inhabited\n\nnamespace RuleIdent\n\ninstance : ToFormat RuleIdent where\n  format\n    | const decl => format decl\n    | fvar userName => format userName\n\nprotected def type : RuleIdent \u2192 MetaM Expr\n  | const c => return (\u2190 getConstInfo c).type\n  | fvar userName => return (\u2190 getLocalDeclFromUserName userName).type\n\nprotected def ruleName : RuleIdent \u2192 Name\n  | const c => `global ++ c\n  | fvar userName => `local ++ userName\n\nprotected def ofName (n : Name) : MetaM RuleIdent := do\n  try\n    let _ \u2190 getLocalDeclFromUserName n\n    pure $ fvar n\n  catch _ =>\n    pure $ const n\n\nend RuleIdent\n\nabbrev RuleBuilder \u03b1 := RuleIdent \u2192 MetaM \u03b1\n\nnamespace RuleBuilder\n\ndef normSimpUnfold : RuleBuilder NormRuleBuilderResult\n  | RuleIdent.const decl => do\n    let info \u2190 getConstInfo decl\n    unless info.hasValue do\n      throwError \"aesop: expected {decl} to be a definition to unfold\"\n    return NormRuleBuilderResult.simpEntries #[SimpEntry.toUnfold decl]\n  | RuleIdent.fvar _ =>\n    throwError \"aesop: local hypotheses cannot be added as simp lemmas\"\n\ndef normSimpLemmas : RuleBuilder NormRuleBuilderResult\n  | RuleIdent.const decl => do\n    let info \u2190 getConstInfo decl\n    unless (\u2190 isProp info.type) do\n      throwError \"aesop: tried to add {decl} as a simp lemma, but it is not a proposition\"\n    let simpLemmas \u2190 mkSimpLemmasFromConst decl (post := true) (prio := 0)\n      -- TODO I don't really know what the `post` and `prio` above mean.\n    return NormRuleBuilderResult.simpEntries $ simpLemmas.map SimpEntry.lemma\n  | RuleIdent.fvar _ => do\n    throwError \"aesop: local hypotheses cannot be added as simp lemmas\"\n\ndef applyIndexingMode (type : Expr) : MetaM IndexingMode := do\n  let savedState \u2190 saveState\n  let path \u2190\n    try\n      let (_, _, conclusion) \u2190 forallMetaTelescope type\n      DiscrTree.mkPath conclusion\n    finally\n      restoreState savedState\n  -- We use a meta telescope because `DiscrTree.mkPath` ignores metas (they\n  -- turn into `Key.star`) but not fvars.\n  return IndexingMode.indexTarget path\n\ndef apply : RuleBuilder RegularRuleBuilderResult := \u03bb ruleIdent => do\n  let type := (\u2190 ruleIdent.type)\n  let tac \u2190\n    match ruleIdent with\n    | RuleIdent.const decl => RuleTacBuilder.apply decl\n    | RuleIdent.fvar userName => RuleTacBuilder.applyFVar userName\n  return {\n    builderName := `apply\n    tac := tac\n    indexingMode := (\u2190 applyIndexingMode type)\n  }\n\ndef tactic : RuleBuilder RegularRuleBuilderResult\n  | RuleIdent.const decl =>\n    return {\n      builderName := `tactic\n      tac := (\u2190 RuleTacBuilder.tactic decl)\n      indexingMode := IndexingMode.unindexed\n    }\n  | RuleIdent.fvar _ =>\n    throwError \"aesop: tactic builder does not support local hypotheses.\"\n\n-- TODO In the default builders below, we should distinguish between fatal and\n-- nonfatal errors. E.g. if the `tactic` builder finds a declaration that is not\n-- of tactic type, this is a nonfatal error and we should continue with the next\n-- builder. But if the simp builder finds an equation that cannot be interpreted\n-- as a simp lemma for some reason, this is a fatal error. Continuing with the\n-- next builder is more confusing than anything because the user probably\n-- intended to add a simp lemma.\n\ndef unsafeRuleDefault : RuleBuilder RegularRuleBuilderResult\n  | i@(RuleIdent.const _) => tactic i <|> apply i <|> err i\n  | i@(RuleIdent.fvar _) => apply i <|> err i\n  where\n    err i := throwError \"aesop: Unable to interpret {i} as an unsafe rule.\"\n\ndef safeRuleDefault : RuleBuilder RegularRuleBuilderResult\n  | i@(RuleIdent.const _) => tactic i <|> apply i <|> err i\n  | i@(RuleIdent.fvar _) => apply i <|> err i\n  where\n    err i := throwError \"aesop: Unable to interpret {i} as a safe rule.\"\n\ndef normRuleDefault : RuleBuilder NormRuleBuilderResult\n  | i@(RuleIdent.const _) =>\n    (NormRuleBuilderResult.regular <$> tactic i) <|>\n    normSimpLemmas i <|>\n    (NormRuleBuilderResult.regular <$> apply i) <|>\n    throwError \"aesop: Unable to interpret {i} as a normalization rule.\"\n  | i@(RuleIdent.fvar _) =>\n    throwError \"aesop: Please specify a builder for norm rule {i}.\"\n\nend Lean.Aesop.RuleBuilder\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/src/Lean/Aesop/RuleBuilder.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.05582314113461444, "lm_q1q2_score": 0.024012176964382032}}
{"text": "import tactic.interactive\n\nlemma a {\u03b1} [nonempty \u03b1] : \u2203 a : \u03b1, a = a :=\nby inhabit \u03b1; use default; refl\n\nnoncomputable def b {\u03b1} [nonempty \u03b1] : \u03b1 :=\nby inhabit \u03b1; apply default\n\nlemma c {\u03b1} [nonempty \u03b1] : \u2200 n : \u2115, \u2203 b : \u03b1, n = n :=\nby inhabit \u03b1; intro; use default; refl\n\nnoncomputable def d {\u03b1} [nonempty \u03b1] : \u2200 n : \u2115, \u03b1 :=\nby inhabit \u03b1; 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 \u2192 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 (\u03bb r (s:string), max r s.length) 0 in\nl.map $ \u03bb s, nat.iterate (\u03bb 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) : \u2115 := es.s.size\n\nmeta def entries.add : entries \u2192 entry \u2192 entries\n| es@\u27e8s, l\u27e9 e := if s.contains e.expr then es else \u27e8s.insert e.expr e, e :: l\u27e9\n\nmeta def entries.head (es : entries) : option entry := es.l.head'\n\nmeta def format_aux : list string \u2192 list string \u2192 list string \u2192 list entry \u2192 tactic format\n| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do\n  fmt \u2190 do {\n    let margin := string.join (list.repeat \" \u2502\" en.depth),\n    let margin := match en.status with\n      | status.sintro := \" \u251c\" ++ margin\n      | status.intro := \" \u2502\" ++ margin ++ \" \u250c\"\n      | status.reg := \" \u2502\" ++ margin ++ \"\"\n      | status.lam := \" \u2502\" ++ margin ++ \"\"\n      end,\n    p \u2190 infer_type en.expr >>= pp,\n    let lhs :=  line ++ \"\u2502\" ++ dep ++ \"\u2502 \" ++ 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\u27e8\u03bb es : entries,\n  let lines := pad_right $ es.l.map (\u03bb en, to_string en.line),\n      deps  := pad_right $ es.l.map (\u03bb en, string.intercalate \",\" (en.deps.map to_string)),\n      thms  := pad_right $ es.l.map (\u03bb en, (entry.thm en).to_string) in\n  format_aux lines deps thms es.l\u27e9\n\nmeta def append_dep (filter : expr \u2192 tactic unit)\n (es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=\ndo { ei \u2190 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 \u2190 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 \u2192 tactic unit)\nwith explode.core : expr \u2192 bool \u2192 nat \u2192 entries \u2192 tactic entries\n| e@(lam n bi d b) si depth es := do\n  m \u2190 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 := \u27e8l, es.size, depth, status.sintro, thm.name n, []\u27e9 in do\n    es' \u2190 explode.core b' si depth (es.add en),\n    return $ es'.add \u27e8e, es'.size, depth, status.lam, thm.string \"\u2200I\", [es.size, es'.size - 1]\u27e9\n  else do\n    let en : entry := \u27e8l, es.size, depth, status.intro, thm.name n, []\u27e9,\n    es' \u2190 explode.core b' si (depth + 1) (es.add en),\n    -- in case of a \"have\" clause, the b' here has an annotation\n    deps' \u2190 explode.append_dep filter es' b'.erase_annotations [],\n    deps' \u2190 explode.append_dep filter es' l deps',\n    return $ es'.add \u27e8e, es'.size, depth, status.lam, thm.string \"\u2200I\", deps'\u27e9\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 := \u27e8fn, es.size, depth, status.reg, thm.expr fn, []\u27e9,\n    return (es.add en)\n  | (fn, args) := do\n    es' \u2190 explode.core fn ff depth es,\n    -- in case of a \"have\" clause, the fn here has an annotation\n    deps \u2190 explode.append_dep filter es' fn.erase_annotations [],\n    explode.args e args depth es' (thm.string \"\u2200E\") deps\n  end\nwith explode.args : expr \u2192 list expr \u2192 nat \u2192 entries \u2192 thm \u2192 list nat \u2192 tactic entries\n| e (arg :: args) depth es thm deps := do\n  es' \u2190 explode.core arg ff depth es <|> return es,\n  deps' \u2190 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 \u27e8e, es.size, depth, status.reg, thm, deps.reverse\u27e9)\n\nmeta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=\nlet filter := if hide_non_prop then \u03bb e, may_be_proof e >>= guardb else \u03bb _, skip in\ntactic.explode.core filter e tt 0 (default _)\n\nmeta def explode (n : name) : tactic unit :=\ndo const n _ \u2190 resolve_name n | fail \"cannot resolve name\",\n  d \u2190 get_decl n,\n  v \u2190 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 \u2190 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 : \u2200 {a : Prop}, a \u2192 (a \u2194 true)\n0\u2502   \u2502 a         \u251c Prop\n1\u2502   \u2502 h         \u251c a\n2\u2502   \u2502 hl        \u2502 \u250c a\n3\u2502   \u2502 trivial   \u2502 \u2502 true\n4\u25022,3\u2502 \u2200I        \u2502 a \u2192 true\n5\u2502   \u2502 hr        \u2502 \u250c true\n6\u25025,1\u2502 \u2200I        \u2502 true \u2192 a\n7\u25024,6\u2502 iff.intro \u2502 a \u2194 true\n8\u25021,7\u2502 \u2200I        \u2502 a \u2192 (a \u2194 true)\n9\u25020,8\u2502 \u2200I        \u2502 \u2200 {a : Prop}, a \u2192 (a \u2194 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 `\u2200E` 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 `\u2200E h ha` where `\u2200E` is\n    (n-ary) modus ponens.\n  * If the proof term is a lambda, we will also use `\u2200I` 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 `\u2200I` 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 `\u2200I` 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 \u2190 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) 2022 Asta H. From. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Asta H. From, Jannis Limperg\n-/\nimport Aesop\n\nattribute [aesop safe (cases (patterns := [List.Mem _ []]))] List.Mem\nattribute [aesop unsafe 50% (cases (patterns := [List.Mem _ (_ :: _)]))] List.Mem\n\ntheorem Mem.split [DecidableEq \u03b1] (xs : List \u03b1) (v : \u03b1) (h : v \u2208 xs)\n  : \u2203 l r, xs = l ++ v :: r := by\n  induction xs\n  case nil =>\n    aesop\n  case cons x xs ih =>\n    have dec : Decidable (x = v) := inferInstance\n    cases dec\n    case isFalse no =>\n      aesop (options := { terminal := true })\n    case isTrue yes =>\n      apply Exists.intro []\n      apply Exists.intro xs\n      rw [yes]\n      rfl\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/golden/18.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4035668680822513, "lm_q2_score": 0.059210248251105387, "lm_q1q2_score": 0.023895294445071196}}
{"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\n \n\nuniverses u w u_1 \n\nnamespace Mathlib\n\ndef buffer (\u03b1 : Type u) :=\n  sigma fun (n : \u2115) => array n \u03b1\n\ndef mk_buffer {\u03b1 : Type u} : buffer \u03b1 :=\n  sigma.mk 0 (d_array.mk fun (i : fin 0) => fin.elim0 i)\n\ndef array.to_buffer {\u03b1 : Type u} {n : \u2115} (a : array n \u03b1) : buffer \u03b1 :=\n  sigma.mk n a\n\nnamespace buffer\n\n\ndef nil {\u03b1 : Type u} : buffer \u03b1 :=\n  mk_buffer\n\ndef size {\u03b1 : Type u} (b : buffer \u03b1) : \u2115 :=\n  sigma.fst b\n\ndef to_array {\u03b1 : Type u} (b : buffer \u03b1) : array (size b) \u03b1 :=\n  sigma.snd b\n\ndef push_back {\u03b1 : Type u} : buffer \u03b1 \u2192 \u03b1 \u2192 buffer \u03b1 :=\n  sorry\n\ndef pop_back {\u03b1 : Type u} : buffer \u03b1 \u2192 buffer \u03b1 :=\n  sorry\n\ndef read {\u03b1 : Type u} (b : buffer \u03b1) : fin (size b) \u2192 \u03b1 :=\n  sorry\n\ndef write {\u03b1 : Type u} (b : buffer \u03b1) : fin (size b) \u2192 \u03b1 \u2192 buffer \u03b1 :=\n  sorry\n\ndef read' {\u03b1 : Type u} [Inhabited \u03b1] : buffer \u03b1 \u2192 \u2115 \u2192 \u03b1 :=\n  sorry\n\ndef write' {\u03b1 : Type u} : buffer \u03b1 \u2192 \u2115 \u2192 \u03b1 \u2192 buffer \u03b1 :=\n  sorry\n\ntheorem read_eq_read' {\u03b1 : Type u} [Inhabited \u03b1] (b : buffer \u03b1) (i : \u2115) (h : i < size b) : read b { val := i, property := h } = read' b i := sorry\n\ntheorem write_eq_write' {\u03b1 : Type u} (b : buffer \u03b1) (i : \u2115) (h : i < size b) (v : \u03b1) : write b { val := i, property := h } v = write' b i v := sorry\n\ndef to_list {\u03b1 : Type u} (b : buffer \u03b1) : List \u03b1 :=\n  array.to_list (to_array b)\n\nprotected def to_string (b : buffer char) : string :=\n  list.as_string (array.to_list (to_array b))\n\ndef append_list {\u03b1 : Type u} : buffer \u03b1 \u2192 List \u03b1 \u2192 buffer \u03b1 :=\n  sorry\n\ndef append_string (b : buffer char) (s : string) : buffer char :=\n  append_list b (string.to_list s)\n\ntheorem lt_aux_1 {a : \u2115} {b : \u2115} {c : \u2115} (h : a + c < b) : a < b :=\n  lt_of_le_of_lt (nat.le_add_right a c) h\n\ntheorem lt_aux_2 {n : \u2115} (h : n > 0) : n - 1 < n :=\n  (fun (h\u2081 : 1 > 0) => nat.sub_lt h h\u2081) (of_as_true trivial)\n\ntheorem lt_aux_3 {n : \u2115} {i : \u2115} (h : i + 1 < n) : n - bit0 1 - i < n := sorry\n\ndef append_array {\u03b1 : Type u} {n : \u2115} (nz : n > 0) : buffer \u03b1 \u2192 array n \u03b1 \u2192 (i : \u2115) \u2192 i < n \u2192 buffer \u03b1 :=\n  sorry\n\nprotected def append {\u03b1 : Type u} : buffer \u03b1 \u2192 buffer \u03b1 \u2192 buffer \u03b1 :=\n  sorry\n\ndef iterate {\u03b1 : Type u} {\u03b2 : Type w} (b : buffer \u03b1) : \u03b2 \u2192 (fin (size b) \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2 :=\n  sorry\n\ndef foreach {\u03b1 : Type u} (b : buffer \u03b1) : (fin (size b) \u2192 \u03b1 \u2192 \u03b1) \u2192 buffer \u03b1 :=\n  sorry\n\n/-- Monadically map a function over the buffer. -/\ndef mmap {\u03b1 : Type u} {\u03b2 : Type w} {m : Type w \u2192 Type u_1} [Monad m] (b : buffer \u03b1) (f : \u03b1 \u2192 m \u03b2) : m (buffer \u03b2) :=\n  do \n    let b' \u2190 array.mmap (sigma.snd b) f \n    return (array.to_buffer b')\n\n/-- Map a function over the buffer. -/\ndef map {\u03b1 : Type u} {\u03b2 : Type w} : buffer \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 buffer \u03b2 :=\n  sorry\n\ndef foldl {\u03b1 : Type u} {\u03b2 : Type w} : buffer \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2 :=\n  sorry\n\ndef rev_iterate {\u03b1 : Type u} {\u03b2 : Type w} (b : buffer \u03b1) : \u03b2 \u2192 (fin (size b) \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) \u2192 \u03b2 :=\n  sorry\n\ndef take {\u03b1 : Type u} (b : buffer \u03b1) (n : \u2115) : buffer \u03b1 :=\n  dite (n \u2264 size b) (fun (h : n \u2264 size b) => sigma.mk n (array.take (to_array b) n h)) fun (h : \u00acn \u2264 size b) => b\n\ndef take_right {\u03b1 : Type u} (b : buffer \u03b1) (n : \u2115) : buffer \u03b1 :=\n  dite (n \u2264 size b) (fun (h : n \u2264 size b) => sigma.mk n (array.take_right (to_array b) n h)) fun (h : \u00acn \u2264 size b) => b\n\ndef drop {\u03b1 : Type u} (b : buffer \u03b1) (n : \u2115) : buffer \u03b1 :=\n  dite (n \u2264 size b) (fun (h : n \u2264 size b) => sigma.mk (size b - n) (array.drop (to_array b) n h))\n    fun (h : \u00acn \u2264 size b) => b\n\ndef reverse {\u03b1 : Type u} (b : buffer \u03b1) : buffer \u03b1 :=\n  sigma.mk (size b) (array.reverse (to_array b))\n\nprotected def mem {\u03b1 : Type u} (v : \u03b1) (a : buffer \u03b1) :=\n  \u2203 (i : fin (size a)), read a i = v\n\nprotected instance has_mem {\u03b1 : Type u} : has_mem \u03b1 (buffer \u03b1) :=\n  has_mem.mk buffer.mem\n\nprotected instance has_append {\u03b1 : Type u} : Append (buffer \u03b1) :=\n  { append := buffer.append }\n\nprotected instance has_repr {\u03b1 : Type u} [has_repr \u03b1] : has_repr (buffer \u03b1) :=\n  has_repr.mk (repr \u2218 to_list)\n\nend buffer\n\n\ndef list.to_buffer {\u03b1 : Type u} (l : List \u03b1) : buffer \u03b1 :=\n  buffer.append_list mk_buffer l\n\ndef char_buffer :=\n  buffer char\n\n/-- Convert a format object into a character buffer with the provided\n    formatting options. -/\ndef string.to_char_buffer (s : string) : char_buffer :=\n  buffer.append_string buffer.nil s\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/buffer.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.05500528713161718, "lm_q1q2_score": 0.023871275886691433}}
{"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 \u03b1 in the congruence generated from `f: \u03a0 {\u03b1 : Type} \u03b1 \u2192 \u03b1`.\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: \u03a0 {\u03b1 : Type}, \u03b1 \u2192 \u03b1`.\n- `cast`: corresponds to arguments that are subsingletons/propositions.\n  For example the `p` in the congruence generated from `f : \u03a0 (x y : \u2115) (p: x < y), \u2115`.\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 \u2192 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": "import tactic.tcache\n\nset_option trace.cache true\n\nnamespace charlie\n\ntheorem lol : 1 + 2 = 3 := by c begin\n  simp\nend\n\nend charlie\n", "meta": {"author": "khoek", "repo": "leancache", "sha": "5c8329f7b647b8d82966ab180c4473b20d1f249c", "save_path": "github-repos/lean/khoek-leancache", "path": "github-repos/lean/khoek-leancache/leancache-5c8329f7b647b8d82966ab180c4473b20d1f249c/test/test2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.05749327880038582, "lm_q1q2_score": 0.023853895015351918}}
{"text": "/-\nCopyright (c) 2022 Jo\u00ebl Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jo\u00ebl 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 \u2964 D) : (F \u27f6 G) \u2243 (to_karoubi _ \u22d9 F \u27f6 to_karoubi _ \u22d9 G) :=\n{ to_fun := \u03bb \u03c6,\n  { app := \u03bb X, \u03c6.app ((to_karoubi C).obj X),\n    naturality' := \u03bb X Y f, by simp only [nat_trans.naturality, functor.comp_map], },\n  inv_fun := \u03bb \u03c8,\n  { app := \u03bb P, F.map (decomp_id_i P) \u226b (\u03c8.app P.X) \u226b G.map (decomp_id_p P),\n    naturality' := \u03bb P Q f, by {\n      slice_lhs 1 2 { rw [\u2190 F.map_comp], },\n      slice_rhs 3 4 { rw [\u2190 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 \u03c8.naturality, },\n      simp only [assoc],\n      refl, }, },\n  left_inv := \u03bb \u03c6, by { ext P, exact (nat_trans_eq \u03c6 P).symm, },\n  right_inv := \u03bb \u03c8, 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 \u2964 D} (\u03c6 : to_karoubi _ \u22d9 F \u27f6 to_karoubi _ \u22d9 G)\n  (\u03c8 : to_karoubi _ \u22d9 G \u27f6 to_karoubi _ \u22d9  H) :\n  (whiskering_left_to_karoubi_hom_equiv F H).inv_fun (\u03c6 \u226b \u03c8) =\n  (whiskering_left_to_karoubi_hom_equiv F G).inv_fun \u03c6 \u226b\n  (whiskering_left_to_karoubi_hom_equiv G H).inv_fun \u03c8 :=\nbegin\n  ext P,\n  dsimp,\n  slice_rhs 3 4 { rw [\u2190 G.map_comp, \u2190 decomp_p], },\n  erw \u03c8.naturality P.p,\n  slice_rhs 4 5 { erw [\u2190 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 \u2964 D} :\n  (whiskering_left_to_karoubi_hom_equiv F F).inv_fun (\ud835\udfd9 _) = \ud835\udfd9 _ :=\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, \u2190 F.map_comp, \u2190 decomp_id, F.map_id],\nend\n\n@[simps]\ndef whiskering_left_to_karoubi_iso_equiv\n  (F G : karoubi C \u2964 D) : (F \u2245 G) \u2243 (to_karoubi _ \u22d9 F \u2245 to_karoubi _ \u22d9 G) :=\n{ to_fun := \u03bb \u03c6,\n  { hom := (whiskering_left_to_karoubi_hom_equiv F G).to_fun \u03c6.hom,\n    inv := (whiskering_left_to_karoubi_hom_equiv G F).to_fun \u03c6.inv, },\n  inv_fun := \u03bb \u03c8,\n  { hom := (whiskering_left_to_karoubi_hom_equiv F G).inv_fun \u03c8.hom,\n    inv := (whiskering_left_to_karoubi_hom_equiv G F).inv_fun \u03c8.inv,\n    hom_inv_id' := by rw [\u2190 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 [\u2190 whiskering_left_to_karoubi_hom_inv_fun_comp, iso.inv_hom_id, whiskering_left_to_karoubi_hom_inv_fun_id], },\n  left_inv := \u03bb \u03c6, by { ext P, simp only [equiv.to_fun_as_coe, equiv.symm_apply_apply,\n    equiv.inv_fun_as_coe], },\n  right_inv := \u03bb \u03c8, by { ext X, simp only [equiv.to_fun_as_coe, equiv.apply_symm_apply,\n    equiv.inv_fun_as_coe], } }\n\nlemma karoubi_universal\u2081_inverse_preimage (F G : karoubi C \u2964 karoubi D)\n  (\u03c6 : ((karoubi_universal\u2081 C D).inverse).obj F \u27f6 ((karoubi_universal\u2081 C D).inverse).obj G) :\n  (karoubi_universal\u2081 C D).inverse.preimage \u03c6 = (whiskering_left_to_karoubi_hom_equiv F G).inv_fun \u03c6 :=\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 \u2964 karoubi D)\n--  (e : ((karoubi_universal' C D).inverse).obj F \u2245 ((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 \u2964 D}\n  (\u03c8 : to_karoubi _ \u22d9 F \u27f6 to_karoubi _ \u22d9 G) (X : C) :\n  ((whiskering_left_to_karoubi_hom_equiv _ _).inv_fun \u03c8).app ((to_karoubi _).obj X) = \u03c8.app X :=\ncongr_app ((whiskering_left_to_karoubi_hom_equiv _ _).right_inv \u03c8) 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) \u2190 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 {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x : \u03b1} {y : \u03b1} (x' : \u03b1) (y' : \u03b1) (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} [linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nby mono*\n```\n\n-/\n/--\ntransforms a goal of the form `f x \u227c f y` into `x \u2264 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 : \u2115 \u2192 rep_arity\n| many : rep_arity\n\n/--\n\n`ac_mono` reduces the `f x \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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) 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 algebra.group.defs\nimport logic.equiv.defs\n\nuniverses u v w u\u2080 u\u2081 v\u2080 v\u2081\n\nstructure writer_t (\u03c9 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) : Type (max u v) :=\n(run : m (\u03b1 \u00d7 \u03c9))\n\n@[reducible] def writer (\u03c9 : Type u) := writer_t \u03c9 id\n\nattribute [pp_using_anonymous_constructor] writer_t\n\nnamespace writer_t\nsection\n  variable  {\u03c9 : Type u}\n  variable  {m : Type u \u2192 Type v}\n  variable  [monad m]\n  variables {\u03b1 \u03b2 : Type u}\n  open function\n\n  @[ext]\n  protected \n\n  @[inline] protected def tell (w : \u03c9) : writer_t \u03c9 m punit :=\n  \u27e8pure (punit.star, w)\u27e9\n\n  @[inline] protected def listen : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m (\u03b1 \u00d7 \u03c9)\n  | \u27e8 cmd \u27e9 := \u27e8 (\u03bb x : \u03b1 \u00d7 \u03c9, ((x.1,x.2),x.2)) <$> cmd \u27e9\n\n  @[inline] protected def pass : writer_t \u03c9 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 writer_t \u03c9 m \u03b1\n  | \u27e8 cmd \u27e9 := \u27e8 uncurry (uncurry $ \u03bb x (f : \u03c9 \u2192 \u03c9) w, (x,f w)) <$> cmd \u27e9\n\n  @[inline] protected def pure [has_one \u03c9] (a : \u03b1) : writer_t \u03c9 m \u03b1 :=\n  \u27e8 pure (a,1) \u27e9\n\n  @[inline] protected def bind [has_mul \u03c9] (x : writer_t \u03c9 m \u03b1) (f : \u03b1 \u2192 writer_t \u03c9 m \u03b2) :\n    writer_t \u03c9 m \u03b2 :=\n  \u27e8 do x  \u2190 x.run,\n       x' \u2190 (f x.1).run,\n       pure (x'.1,x.2 * x'.2) \u27e9\n\n  instance [has_one \u03c9] [has_mul \u03c9] : monad (writer_t \u03c9 m) :=\n  { pure := \u03bb \u03b1, writer_t.pure, bind := \u03bb \u03b1 \u03b2, writer_t.bind }\n\n  instance [monoid \u03c9] [is_lawful_monad m] : is_lawful_monad (writer_t \u03c9 m) :=\n  { id_map := by { intros, cases x, simp [(<$>),writer_t.bind,writer_t.pure] },\n    pure_bind := by { intros, simp [has_pure.pure,writer_t.pure,(>>=),writer_t.bind], ext; refl },\n    bind_assoc := by { intros, simp [(>>=),writer_t.bind,mul_assoc] with functor_norm } }\n\n  @[inline] protected def lift [has_one \u03c9] (a : m \u03b1) : writer_t \u03c9 m \u03b1 :=\n  \u27e8 flip prod.mk 1 <$> a \u27e9\n\n  instance (m) [monad m] [has_one \u03c9] : has_monad_lift m (writer_t \u03c9 m) :=\n  \u27e8 \u03bb \u03b1, writer_t.lift  \u27e9\n\n  @[inline] protected def monad_map {m m'} [monad m] [monad m'] {\u03b1} (f : \u03a0 {\u03b1}, m \u03b1 \u2192 m' \u03b1) :\n    writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m' \u03b1 :=\n  \u03bb x, \u27e8 f x.run \u27e9\n\n  instance (m m') [monad m] [monad m'] : monad_functor m m' (writer_t \u03c9 m) (writer_t \u03c9 m') :=\n  \u27e8@writer_t.monad_map \u03c9 m m' _ _\u27e9\n\n  @[inline] protected def adapt {\u03c9' : Type u} {\u03b1 : Type u} (f : \u03c9 \u2192 \u03c9') :\n    writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9' m \u03b1 :=\n  \u03bb x, \u27e8prod.map id f <$> x.run\u27e9\n\n  instance (\u03b5) [has_one \u03c9] [monad m] [monad_except \u03b5 m] : monad_except \u03b5 (writer_t \u03c9 m) :=\n  { throw := \u03bb \u03b1, writer_t.lift \u2218 throw,\n    catch := \u03bb \u03b1 x c, \u27e8catch x.run (\u03bb e, (c e).run)\u27e9 }\nend\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 (\u03c1 : out_param (Type u)) (n : Type u \u2192 Type u) :=\n(lift {\u03b1 : Type u} : (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1) \u2192 n \u03b1)\n```\n-/\nclass monad_writer (\u03c9 : out_param (Type u)) (m : Type u \u2192 Type v) :=\n(tell (w : \u03c9) : m punit)\n(listen {\u03b1} : m \u03b1 \u2192 m (\u03b1 \u00d7 \u03c9))\n(pass {\u03b1 : Type u} : m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 m \u03b1)\n\nexport monad_writer\n\ninstance {\u03c9 : Type u} {m : Type u \u2192 Type v} [monad m] : monad_writer \u03c9 (writer_t \u03c9 m) :=\n{ tell := writer_t.tell,\n  listen := \u03bb \u03b1, writer_t.listen,\n  pass := \u03bb \u03b1, writer_t.pass }\n\ninstance {\u03c9 \u03c1 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (reader_t \u03c1 m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, listen (cmd r) \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, pass (cmd r) \u27e9 }\n\ndef swap_right {\u03b1 \u03b2 \u03b3} : (\u03b1 \u00d7 \u03b2) \u00d7 \u03b3 \u2192 (\u03b1 \u00d7 \u03b3) \u00d7 \u03b2\n| \u27e8\u27e8x,y\u27e9,z\u27e9 := ((x,z),y)\n\ninstance {\u03c9 \u03c3 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (state_t \u03c3 m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, swap_right <$> listen (cmd r) \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 \u03bb r, pass (swap_right <$> cmd r) \u27e9 }\nopen function\n\ndef except_t.pass_aux {\u03b5 \u03b1 \u03c9} : except \u03b5 (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 except \u03b5 \u03b1 \u00d7 (\u03c9 \u2192 \u03c9)\n| (except.error a) := (except.error a,id)\n| (except.ok (x,y)) := (except.ok x,y)\n\ninstance {\u03c9 \u03b5 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (except_t \u03b5 m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 uncurry (\u03bb x y, flip prod.mk y <$> x) <$> listen cmd \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 pass (except_t.pass_aux <$> cmd) \u27e9 }\n\ndef option_t.pass_aux {\u03b1 \u03c9} : option (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 option \u03b1 \u00d7 (\u03c9 \u2192 \u03c9)\n| none := (none ,id)\n| (some (x,y)) := (some x,y)\n\ninstance {\u03c9 : Type u} {m : Type u \u2192 Type v} [monad m] [monad_writer \u03c9 m] :\n  monad_writer \u03c9 (option_t m) :=\n{ tell := \u03bb x, monad_lift (tell x : m punit),\n  listen := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 uncurry (\u03bb x y, flip prod.mk y <$> x) <$> listen cmd \u27e9,\n  pass := \u03bb \u03b1 \u27e8 cmd \u27e9, \u27e8 pass (option_t.pass_aux <$> cmd) \u27e9 }\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 (\u03c1 \u03c1' : out_param (Type u)) (n n' : Type u \u2192 Type u) :=\n(map {\u03b1 : Type u} :\n  (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1 \u2192 reader_t \u03c1' m \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1)\n```\n-/\nclass monad_writer_adapter (\u03c9 \u03c9' : out_param (Type u)) (m m' : Type u \u2192 Type v) :=\n(adapt_writer {\u03b1 : Type u} : (\u03c9 \u2192 \u03c9') \u2192 m \u03b1 \u2192 m' \u03b1)\nexport monad_writer_adapter (adapt_writer)\n\nsection\nvariables {\u03c9 \u03c9' : Type u} {m m' : Type u \u2192 Type v}\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] -/\n@[nolint dangerous_instance, priority 100]\ninstance monad_writer_adapter_trans {n n' : Type u \u2192 Type v} [monad_writer_adapter \u03c9 \u03c9' m m']\n  [monad_functor m m' n n'] : monad_writer_adapter \u03c9 \u03c9' n n' :=\n\u27e8\u03bb \u03b1 f, monad_map (\u03bb \u03b1, (adapt_writer f : m \u03b1 \u2192 m' \u03b1))\u27e9\n\ninstance [monad m] : monad_writer_adapter \u03c9 \u03c9' (writer_t \u03c9 m) (writer_t \u03c9' m) :=\n\u27e8\u03bb \u03b1, writer_t.adapt\u27e9\nend\n\ninstance (\u03c9 : Type u) (m out) [monad_run out m] : monad_run (\u03bb \u03b1, out (\u03b1 \u00d7 \u03c9)) (writer_t \u03c9 m) :=\n\u27e8\u03bb \u03b1 x, run $ x.run \u27e9\n\n/-- reduce the equivalence between two writer monads to the equivalence between\ntheir underlying monad -/\ndef writer_t.equiv {m\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081}\n  {\u03b1\u2081 \u03c9\u2081 : Type u\u2080} {\u03b1\u2082 \u03c9\u2082 : Type u\u2081} (F : (m\u2081 (\u03b1\u2081 \u00d7 \u03c9\u2081)) \u2243 (m\u2082 (\u03b1\u2082 \u00d7 \u03c9\u2082))) :\n  writer_t \u03c9\u2081 m\u2081 \u03b1\u2081 \u2243 writer_t \u03c9\u2082 m\u2082 \u03b1\u2082 :=\n{ to_fun := \u03bb \u27e8f\u27e9, \u27e8F f\u27e9,\n  inv_fun := \u03bb \u27e8f\u27e9, \u27e8F.symm f\u27e9,\n  left_inv := \u03bb \u27e8f\u27e9, congr_arg writer_t.mk $ F.left_inv _,\n  right_inv := \u03bb \u27e8f\u27e9, congr_arg writer_t.mk $ F.right_inv _ }\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/writer.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.05108273695705248, "lm_q1q2_score": 0.023748445438828415}}
{"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 \u2192 Type v} -- The family of types already equipped with instances\nvariables (x y : \u03a0 i, f i) (i : I)\n\nnamespace pi\n\n@[to_additive pi.has_vadd]\ninstance has_smul {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 $ f i] :\n  has_smul \u03b1 (\u03a0 i : I, f i) :=\n\u27e8\u03bb s x, \u03bb i, s \u2022 (x i)\u27e9\n\n@[to_additive]\nlemma smul_def {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 $ f i] (s : \u03b1) : s \u2022 x = \u03bb i, s \u2022 x i := rfl\n@[simp, to_additive]\nlemma smul_apply {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 $ f i] (s : \u03b1) : (s \u2022 x) i = s \u2022 x i := rfl\n\n@[to_additive pi.has_vadd']\ninstance has_smul' {g : I \u2192 Type*} [\u03a0 i, has_smul (f i) (g i)] :\n  has_smul (\u03a0 i, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb s x, \u03bb i, (s i) \u2022 (x i)\u27e9\n\n@[simp, to_additive]\nlemma smul_apply' {g : I \u2192 Type*} [\u2200 i, has_smul (f i) (g i)] (s : \u03a0 i, f i) (x : \u03a0 i, g i) :\n  (s \u2022 x) i = s i \u2022 x i :=\nrfl\ninstance is_scalar_tower {\u03b1 \u03b2 : Type*}\n  [has_smul \u03b1 \u03b2] [\u03a0 i, has_smul \u03b2 $ f i] [\u03a0 i, has_smul \u03b1 $ f i]\n  [\u03a0 i, is_scalar_tower \u03b1 \u03b2 (f i)] : is_scalar_tower \u03b1 \u03b2 (\u03a0 i : I, f i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc x y (z i)\u27e9\n\ninstance is_scalar_tower' {g : I \u2192 Type*} {\u03b1 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, has_smul (f i) (g i)] [\u03a0 i, has_smul \u03b1 $ g i]\n  [\u03a0 i, is_scalar_tower \u03b1 (f i) (g i)] : is_scalar_tower \u03b1 (\u03a0 i : I, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc x (y i) (z i)\u27e9\n\ninstance is_scalar_tower'' {g : I \u2192 Type*} {h : I \u2192 Type*}\n  [\u03a0 i, has_smul (f i) (g i)] [\u03a0 i, has_smul (g i) (h i)] [\u03a0 i, has_smul (f i) (h i)]\n  [\u03a0 i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (\u03a0 i, f i) (\u03a0 i, g i) (\u03a0 i, h i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc (x i) (y i) (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class {\u03b1 \u03b2 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, has_smul \u03b2 $ f i] [\u2200 i, smul_comm_class \u03b1 \u03b2 (f i)] :\n  smul_comm_class \u03b1 \u03b2 (\u03a0 i : I, f i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm x y (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class' {g : I \u2192 Type*} {\u03b1 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ g i] [\u03a0 i, has_smul (f i) (g i)] [\u2200 i, smul_comm_class \u03b1 (f i) (g i)] :\n  smul_comm_class \u03b1 (\u03a0 i : I, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm x (y i) (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class'' {g : I \u2192 Type*} {h : I \u2192 Type*}\n  [\u03a0 i, has_smul (g i) (h i)] [\u03a0 i, has_smul (f i) (h i)]\n  [\u2200 i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (\u03a0 i, f i) (\u03a0 i, g i) (\u03a0 i, h i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm (x i) (y i) (z i)\u27e9\n\ninstance {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, has_smul \u03b1\u1d50\u1d52\u1d56 $ f i]\n  [\u2200 i, is_central_scalar \u03b1 (f i)] : is_central_scalar \u03b1 (\u03a0 i, f i) :=\n\u27e8\u03bb r m, funext $ \u03bb i, op_smul_eq_smul _ _\u27e9\n\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `\u03a0 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 {\u03b1 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, nonempty (f i)] (i : I) [has_faithful_smul \u03b1 (f i)] :\n  has_faithful_smul \u03b1 (\u03a0 i, f i) :=\n\u27e8\u03bb x y h, eq_of_smul_eq_smul $ \u03bb a : f i, begin\n  classical,\n  have := congr_fun (h $ function.update (\u03bb j, classical.choice (\u2039\u03a0 i, nonempty (f i)\u203a j)) i a) i,\n  simpa using this,\nend\u27e9\n\n@[to_additive pi.has_faithful_vadd]\ninstance has_faithful_smul {\u03b1 : Type*}\n  [nonempty I] [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, nonempty (f i)] [\u03a0 i, has_faithful_smul \u03b1 (f i)] :\n  has_faithful_smul \u03b1 (\u03a0 i, f i) :=\nlet \u27e8i\u27e9 := \u2039nonempty I\u203a in has_faithful_smul_at i\n\n@[to_additive]\ninstance mul_action (\u03b1) {m : monoid \u03b1} [\u03a0 i, mul_action \u03b1 $ f i] :\n  @mul_action \u03b1 (\u03a0 i : I, f i) m :=\n{ smul := (\u2022),\n  mul_smul := \u03bb r s f, funext $ \u03bb i, mul_smul _ _ _,\n  one_smul := \u03bb f, funext $ \u03bb i, one_smul \u03b1 _ }\n\n@[to_additive]\ninstance mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} [\u03a0 i, mul_action (f i) (g i)] :\n  @mul_action (\u03a0 i, f i) (\u03a0 i : I, g i) (@pi.monoid I f m) :=\n{ smul := (\u2022),\n  mul_smul := \u03bb r s f, funext $ \u03bb i, mul_smul _ _ _,\n  one_smul := \u03bb f, funext $ \u03bb i, one_smul _ _ }\n\ninstance distrib_mul_action (\u03b1) {m : monoid \u03b1} {n : \u2200 i, add_monoid $ f i}\n  [\u2200 i, distrib_mul_action \u03b1 $ f i] :\n  @distrib_mul_action \u03b1 (\u03a0 i : I, f i) m (@pi.add_monoid I f n) :=\n{ smul_zero := \u03bb c, funext $ \u03bb i, smul_zero _,\n  smul_add := \u03bb c f g, funext $ \u03bb i, smul_add _ _ _,\n  ..pi.mul_action _ }\n\ninstance distrib_mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} {n : \u03a0 i, add_monoid $ g i}\n  [\u03a0 i, distrib_mul_action (f i) (g i)] :\n  @distrib_mul_action (\u03a0 i, f i) (\u03a0 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 {\u03b1} [monoid \u03b1] [\u03a0 i, add_monoid $ f i]\n  [\u03a0 i, distrib_mul_action \u03b1 $ f i] [decidable_eq I] (i : I) (r : \u03b1) (x : f i) :\n  single i (r \u2022 x) = r \u2022 single i x :=\nsingle_op (\u03bb i : I, ((\u2022) r : f i \u2192 f i)) (\u03bb 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' {\u03b1 \u03b2} [monoid \u03b1] [add_monoid \u03b2]\n  [distrib_mul_action \u03b1 \u03b2] [decidable_eq I] (i : I) (r : \u03b1) (x : \u03b2) :\n  single i (r \u2022 x) = r \u2022 single i x :=\nsingle_smul i r x\n\nlemma single_smul\u2080 {g : I \u2192 Type*} [\u03a0 i, monoid_with_zero (f i)] [\u03a0 i, add_monoid (g i)]\n  [\u03a0 i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) :\n  single i (r \u2022 x) = single i r \u2022 single i x :=\nsingle_op\u2082 (\u03bb i : I, ((\u2022) : f i \u2192 g i \u2192 g i)) (\u03bb j, smul_zero _) _ _ _\n\ninstance mul_distrib_mul_action (\u03b1) {m : monoid \u03b1} {n : \u03a0 i, monoid $ f i}\n  [\u03a0 i, mul_distrib_mul_action \u03b1 $ f i] :\n  @mul_distrib_mul_action \u03b1 (\u03a0 i : I, f i) m (@pi.monoid I f n) :=\n{ smul_one := \u03bb c, funext $ \u03bb i, smul_one _,\n  smul_mul := \u03bb c f g, funext $ \u03bb i, smul_mul' _ _ _,\n  ..pi.mul_action _ }\n\ninstance mul_distrib_mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} {n : \u03a0 i, monoid $ g i}\n  [\u03a0 i, mul_distrib_mul_action (f i) (g i)] :\n  @mul_distrib_mul_action (\u03a0 i, f i) (\u03a0 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 {\u03b9 R M : Type*} [has_smul R M] :\n  has_smul R (\u03b9 \u2192 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 {\u03b9 \u03b1 \u03b2 M : Type*}\n  [has_smul \u03b1 M] [has_smul \u03b2 M] [smul_comm_class \u03b1 \u03b2 M] :\n  smul_comm_class \u03b1 \u03b2 (\u03b9 \u2192 M) :=\npi.smul_comm_class\n\n@[to_additive]\nlemma update_smul {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 (f i)] [decidable_eq I]\n  (c : \u03b1) (f\u2081 : \u03a0 i, f i) (i : I) (x\u2081 : f i) :\n  update (c \u2022 f\u2081) i (c \u2022 x\u2081) = c \u2022 update f\u2081 i x\u2081 :=\nfunext $ \u03bb j, (apply_update (\u03bb i, (\u2022) c) f\u2081 i x\u2081 j).symm\n\nend function\n\nnamespace set\n\n@[to_additive]\nlemma piecewise_smul {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 (f i)] (s : set I) [\u03a0 i, decidable (i \u2208 s)]\n  (c : \u03b1) (f\u2081 g\u2081 : \u03a0 i, f i) :\n  s.piecewise (c \u2022 f\u2081) (c \u2022 g\u2081) = c \u2022 s.piecewise f\u2081 g\u2081 :=\ns.piecewise_op _ _ (\u03bb _, (\u2022) c)\n\nend set\n\nsection extend\n\n@[to_additive] lemma function.extend_smul {R \u03b1 \u03b2 \u03b3 : Type*} [has_smul R \u03b3]\n  (r : R) (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e : \u03b2 \u2192 \u03b3) :\n  function.extend f (r \u2022 g) (r \u2022 e) = r \u2022 function.extend f g e :=\nfunext $ \u03bb _, by convert (apply_dite ((\u2022) 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": "/-\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 \u03b1` is the type that describes a computation that can ingest a `char_buffer`\nand output, if successful, a term of type `\u03b1`.\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 \u03b1` 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 \u03b1`, 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 {\u03b1 : Type} : parse_result \u03b1 \u2192 \u2115 :=\n  sorry\n\nnamespace parser\n\n\n/--\nA `parser \u03b1` is defined to be `valid` if the result `p cb n` it gives,\nfor some `cb : char_buffer` and `n : \u2115`, (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 {\u03b1 : Type} (p : parser \u03b1) :=\n  \u2200 (cb : char_buffer) (n : \u2115),\n    n \u2264 parse_result.pos (p cb n) \u2227 (parse_result.pos (p cb n) \u2264 buffer.size cb \u2192 n \u2264 buffer.size cb)\n\ntheorem fail_iff {\u03b1 : Type} (p : parser \u03b1) (cb : char_buffer) (n : \u2115) : (\u2200 (pos' : \u2115) (result : \u03b1), p cb n \u2260 parse_result.done pos' result) \u2194\n  \u2203 (pos' : \u2115), \u2203 (err : dlist string), p cb n = parse_result.fail pos' err := sorry\n\ntheorem success_iff {\u03b1 : Type} (p : parser \u03b1) (cb : char_buffer) (n : \u2115) : (\u2200 (pos' : \u2115) (err : dlist string), p cb n \u2260 parse_result.fail pos' err) \u2194\n  \u2203 (pos' : \u2115), \u2203 (result : \u03b1), p cb n = parse_result.done pos' result := sorry\n\ntheorem decorate_errors_fail {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} (h : p cb n = parse_result.fail n' err) : decorate_errors msgs p cb n = parse_result.fail n (dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) := sorry\n\ntheorem decorate_errors_success {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} (h : p cb n = parse_result.done n' a) : decorate_errors msgs p cb n = parse_result.done n' a := sorry\n\ntheorem decorate_error_fail {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} (h : p cb n = parse_result.fail n' err) : decorate_error msg p cb n = parse_result.fail n (dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) :=\n  decorate_errors_fail h\n\ntheorem decorate_error_success {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} (h : p cb n = parse_result.done n' a) : decorate_error msg p cb n = parse_result.done n' a :=\n  decorate_errors_success h\n\n@[simp] theorem decorate_errors_eq_done {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} : decorate_errors msgs p cb n = parse_result.done n' a \u2194 p cb n = parse_result.done n' a := sorry\n\n@[simp] theorem decorate_error_eq_done {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} : decorate_error msg p cb n = parse_result.done n' a \u2194 p cb n = parse_result.done n' a :=\n  decorate_errors_eq_done\n\n@[simp] theorem decorate_errors_eq_fail {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {err : dlist string} : decorate_errors msgs p cb n = parse_result.fail n err \u2194\n  (err = dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) \u2227\n    \u2203 (np : \u2115), \u2203 (err' : dlist string), p cb n = parse_result.fail np err' := sorry\n\n@[simp] theorem decorate_error_eq_fail {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {err : dlist string} : decorate_error msg p cb n = parse_result.fail n err \u2194\n  (err = dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) \u2227\n    \u2203 (np : \u2115), \u2203 (err' : dlist string), p cb n = parse_result.fail np err' :=\n  decorate_errors_eq_fail\n\n@[simp] theorem return_eq_pure {\u03b1 : Type} {a : \u03b1} : return a = pure a :=\n  rfl\n\ntheorem pure_eq_done {\u03b1 : Type} {a : \u03b1} : pure a = fun (_x : char_buffer) (n : \u2115) => parse_result.done n a :=\n  rfl\n\n@[simp] theorem pure_ne_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {a : \u03b1} : pure a cb n \u2260 parse_result.fail n' err := sorry\n\n@[simp] theorem bind_eq_bind {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} (f : \u03b1 \u2192 parser \u03b2) : parser.bind p f = p >>= f :=\n  rfl\n\n@[simp] theorem bind_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 parser \u03b2} : bind p f cb n = parse_result.done n' b \u2194\n  \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 f a cb np = parse_result.done n' b := sorry\n\n@[simp] theorem bind_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {f : \u03b1 \u2192 parser \u03b2} : bind p f cb n = parse_result.fail n' err \u2194\n  p cb n = parse_result.fail n' err \u2228\n    \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 f a cb np = parse_result.fail n' err := sorry\n\n@[simp] theorem and_then_eq_bind {\u03b1 : Type} {\u03b2 : Type} {m : Type \u2192 Type} [Monad m] (a : m \u03b1) (b : m \u03b2) : a >> b =\n  do \n    a \n    b :=\n  rfl\n\ntheorem and_then_fail {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} : has_bind.and_then p (return Unit.unit) cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err := sorry\n\ntheorem and_then_success {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} : has_bind.and_then p (return Unit.unit) cb n = parse_result.done n' Unit.unit \u2194\n  \u2203 (a : \u03b1), p cb n = parse_result.done n' a := sorry\n\n@[simp] theorem map_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2} : Functor.map f p cb n = parse_result.done n' b \u2194 \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 f a = b := sorry\n\n@[simp] theorem map_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {f : \u03b1 \u2192 \u03b2} : Functor.map f p cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err := sorry\n\n@[simp] theorem map_const_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {b' : \u03b2} : Functor.mapConst b p cb n = parse_result.done n' b' \u2194 \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 b = b' := sorry\n\n@[simp] theorem map_const_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {b : \u03b2} : Functor.mapConst b p cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err := sorry\n\ntheorem map_const_rev_eq_done {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {b' : \u03b2} : functor.map_const_rev p b cb n = parse_result.done n' b' \u2194 \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 b = b' :=\n  map_const_eq_done\n\ntheorem map_rev_const_eq_fail {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {b : \u03b2} : functor.map_const_rev p b cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err :=\n  map_const_eq_fail\n\n@[simp] theorem orelse_eq_orelse {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} : parser.orelse p q = (p <|> q) :=\n  rfl\n\n@[simp] theorem orelse_eq_done {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} : has_orelse.orelse p q cb n = parse_result.done n' a \u2194\n  p cb n = parse_result.done n' a \u2228\n    q cb n = parse_result.done n' a \u2227 \u2203 (err : dlist string), p cb n = parse_result.fail n err := sorry\n\n@[simp] theorem orelse_eq_fail_eq {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer} {n : \u2115} {err : dlist string} : has_orelse.orelse p q cb n = parse_result.fail n err \u2194\n  (p cb n = parse_result.fail n err \u2227\n      \u2203 (nq : \u2115), \u2203 (errq : dlist string), n < nq \u2227 q cb n = parse_result.fail nq errq) \u2228\n    \u2203 (errp : dlist string),\n      \u2203 (errq : dlist string),\n        p cb n = parse_result.fail n errp \u2227 q cb n = parse_result.fail n errq \u2227 errp ++ errq = err := sorry\n\ntheorem orelse_eq_fail_invalid_lt {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} (hn : n' < n) : has_orelse.orelse p q cb n = parse_result.fail n' err \u2194\n  p cb n = parse_result.fail n' err \u2228\n    q cb n = parse_result.fail n' err \u2227 \u2203 (errp : dlist string), p cb n = parse_result.fail n errp := sorry\n\ntheorem orelse_eq_fail_of_valid_ne {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} (hv : valid q) (hn : n \u2260 n') : has_orelse.orelse p q cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err := sorry\n\n@[simp] theorem failure_eq_failure {\u03b1 : Type} : parser.failure = failure :=\n  rfl\n\n@[simp] theorem failure_def {\u03b1 : Type} {cb : char_buffer} {n : \u2115} : failure cb n = parse_result.fail n dlist.empty :=\n  rfl\n\ntheorem not_failure_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} : \u00acfailure cb n = parse_result.done n' a := sorry\n\ntheorem failure_eq_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} : failure cb n = parse_result.fail n' err \u2194 n = n' \u2227 err = dlist.empty := sorry\n\ntheorem seq_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : parser (\u03b1 \u2192 \u03b2)} {p : parser \u03b1} : Seq.seq f p cb n = parse_result.done n' b \u2194\n  \u2203 (nf : \u2115), \u2203 (f' : \u03b1 \u2192 \u03b2), \u2203 (a : \u03b1), f cb n = parse_result.done nf f' \u2227 p cb nf = parse_result.done n' a \u2227 f' a = b := sorry\n\ntheorem seq_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {f : parser (\u03b1 \u2192 \u03b2)} {p : parser \u03b1} : Seq.seq f p cb n = parse_result.fail n' err \u2194\n  f cb n = parse_result.fail n' err \u2228\n    \u2203 (nf : \u2115), \u2203 (f' : \u03b1 \u2192 \u03b2), f cb n = parse_result.done nf f' \u2227 p cb nf = parse_result.fail n' err := sorry\n\ntheorem seq_left_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {p : parser \u03b1} {q : parser \u03b2} : SeqLeft.seqLeft p q cb n = parse_result.done n' a \u2194\n  \u2203 (np : \u2115), \u2203 (b : \u03b2), p cb n = parse_result.done np a \u2227 q cb np = parse_result.done n' b := sorry\n\ntheorem seq_left_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {p : parser \u03b1} {q : parser \u03b2} : SeqLeft.seqLeft p q cb n = parse_result.fail n' err \u2194\n  p cb n = parse_result.fail n' err \u2228\n    \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 q cb np = parse_result.fail n' err := sorry\n\ntheorem seq_right_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {p : parser \u03b1} {q : parser \u03b2} : SeqRight.seqRight p q cb n = parse_result.done n' b \u2194\n  \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 q cb np = parse_result.done n' b := sorry\n\ntheorem seq_right_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {p : parser \u03b1} {q : parser \u03b2} : SeqRight.seqRight p q cb n = parse_result.fail n' err \u2194\n  p cb n = parse_result.fail n' err \u2228\n    \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 q cb np = parse_result.fail n' err := sorry\n\ntheorem mmap_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {f : \u03b1 \u2192 parser \u03b2} {a : \u03b1} {l : List \u03b1} {b : \u03b2} {l' : List \u03b2} : mmap f (a :: l) cb n = parse_result.done n' (b :: l') \u2194\n  \u2203 (np : \u2115), f a cb n = parse_result.done np b \u2227 mmap f l cb np = parse_result.done n' l' := sorry\n\ntheorem mmap'_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {f : \u03b1 \u2192 parser \u03b2} {a : \u03b1} {l : List \u03b1} : mmap' f (a :: l) cb n = parse_result.done n' Unit.unit \u2194\n  \u2203 (np : \u2115), \u2203 (b : \u03b2), f a cb n = parse_result.done np b \u2227 mmap' f l cb np = parse_result.done n' Unit.unit := sorry\n\ntheorem guard_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : Prop} [Decidable p] : guard p cb n = parse_result.done n' Unit.unit \u2194 p \u2227 n = n' := sorry\n\ntheorem guard_eq_fail {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {p : Prop} [Decidable p] : guard p cb n = parse_result.fail n' err \u2194 \u00acp \u2227 n = n' \u2227 err = dlist.empty := sorry\n\nnamespace valid\n\n\ntheorem mono_done {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} (hp : valid p) (h : p cb n = parse_result.done n' a) : n \u2264 n' := sorry\n\ntheorem mono_fail {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} (hp : valid p) (h : p cb n = parse_result.fail n' err) : n \u2264 n' := sorry\n\ntheorem pure {\u03b1 : Type} {a : \u03b1} : valid (pure a) := sorry\n\n@[simp] theorem bind {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b1 \u2192 parser \u03b2} (hp : valid p) (hf : \u2200 (a : \u03b1), valid (f a)) : valid (p >>= f) := sorry\n\ntheorem and_then {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {q : parser \u03b2} (hp : valid p) (hq : valid q) : valid (p >> q) :=\n  bind hp fun (_x : \u03b1) => hq\n\n@[simp] theorem map {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} (hp : valid p) {f : \u03b1 \u2192 \u03b2} : valid (f <$> p) :=\n  bind hp fun (_x : \u03b1) => pure\n\n@[simp] theorem seq {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : parser (\u03b1 \u2192 \u03b2)} (hf : valid f) (hp : valid p) : valid (f <*> p) :=\n  bind hf fun (_x : \u03b1 \u2192 \u03b2) => map hp\n\n@[simp] theorem mmap {\u03b1 : Type} {\u03b2 : Type} {l : List \u03b1} {f : \u03b1 \u2192 parser \u03b2} (h : \u2200 (a : \u03b1), a \u2208 l \u2192 valid (f a)) : valid (mmap f l) := sorry\n\n@[simp] theorem mmap' {\u03b1 : Type} {\u03b2 : Type} {l : List \u03b1} {f : \u03b1 \u2192 parser \u03b2} (h : \u2200 (a : \u03b1), a \u2208 l \u2192 valid (f a)) : valid (mmap' f l) := sorry\n\n@[simp] theorem failure {\u03b1 : Type} : valid failure := sorry\n\n@[simp] theorem guard {p : Prop} [Decidable p] : valid (guard p) := sorry\n\n@[simp] theorem orelse {\u03b1 : Type} {p : parser \u03b1} {q : parser \u03b1} (hp : valid p) (hq : valid q) : valid (p <|> q) := sorry\n\n@[simp] theorem decorate_errors {\u03b1 : Type} {msgs : thunk (List string)} {p : parser \u03b1} (hp : valid p) : valid (decorate_errors msgs p) := sorry\n\n@[simp] theorem decorate_error {\u03b1 : Type} {msg : thunk string} {p : parser \u03b1} (hp : valid p) : 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 \u2192 Prop} [decidable_pred p] : valid (sat p) := sorry\n\n@[simp] theorem eps : valid eps :=\n  pure\n\ntheorem ch {c : char} : valid (ch c) :=\n  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 \u2208 buffer.to_list s) => ch)\n\ntheorem one_of {cs : List char} : valid (one_of cs) :=\n  decorate_errors sat\n\ntheorem one_of' {cs : List char} : valid (one_of' cs) :=\n  and_then one_of eps\n\ntheorem str {s : string} : valid (str s) :=\n  decorate_error (mmap' fun (_x : char) (_x_1 : _x \u2208 string.to_list s) => ch)\n\ntheorem remaining : valid remaining :=\n  fun (_x : char_buffer) (_x_1 : \u2115) =>\n    { left := le_refl _x_1, right := fun (h : parse_result.pos (remaining _x _x_1) \u2264 buffer.size _x) => h }\n\ntheorem eof : valid eof :=\n  decorate_error (bind remaining fun (_x : \u2115) => guard)\n\ntheorem foldr_core_zero {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} : valid (foldr_core f p b 0) :=\n  failure\n\ntheorem foldr_core {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {b : \u03b2} (hp : valid p) {reps : \u2115} : valid (foldr_core f p b reps) := sorry\n\ntheorem foldr {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} (hp : valid p) : valid (foldr f p b) :=\n  fun (_x : char_buffer) (_x_1 : \u2115) => foldr_core hp _x _x_1\n\ntheorem foldl_core_zero {\u03b1 : Type} {\u03b2 : Type} {p : parser \u03b1} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {b : \u03b2} : valid (foldl_core f b p 0) :=\n  failure\n\ntheorem foldl_core {\u03b1 : Type} {\u03b2 : Type} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} (hp : valid p) {a : \u03b1} {reps : \u2115} : valid (foldl_core f a p reps) := sorry\n\ntheorem foldl {\u03b1 : Type} {\u03b2 : Type} {a : \u03b1} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b1} {p : parser \u03b2} (hp : valid p) : valid (foldl f a p) :=\n  fun (_x : char_buffer) (_x_1 : \u2115) => foldl_core hp _x _x_1\n\ntheorem many {\u03b1 : Type} {p : parser \u03b1} (hp : valid p) : valid (many p) :=\n  foldr hp\n\ntheorem many_char {p : parser char} (hp : valid p) : valid (many_char p) :=\n  map (many hp)\n\ntheorem many' {\u03b1 : Type} {p : parser \u03b1} (hp : valid p) : valid (many' p) :=\n  and_then (many hp) eps\n\ntheorem many1 {\u03b1 : Type} {p : parser \u03b1} (hp : valid p) : valid (many1 p) :=\n  seq (map hp) (many hp)\n\ntheorem many_char1 {p : parser char} (hp : valid p) : valid (many_char1 p) :=\n  map (many1 hp)\n\ntheorem sep_by1 {\u03b1 : Type} {p : parser \u03b1} {sep : parser Unit} (hp : valid p) (hs : valid sep) : valid (sep_by1 sep p) :=\n  seq (map hp) (many (and_then hs hp))\n\ntheorem sep_by {\u03b1 : Type} {p : parser \u03b1} {sep : parser Unit} (hp : valid p) (hs : valid sep) : valid (sep_by sep p) :=\n  orelse (sep_by1 hp hs) pure\n\ntheorem fix_core {\u03b1 : Type} {F : parser \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), valid p \u2192 valid (F p)) (max_depth : \u2115) : valid (fix_core F max_depth) := sorry\n\ntheorem digit : valid digit :=\n  decorate_error (bind sat fun (_x : char) => pure)\n\ntheorem nat : valid nat :=\n  decorate_error (bind (many1 digit) fun (_x : List \u2115) => pure)\n\ntheorem fix {\u03b1 : Type} {F : parser \u03b1 \u2192 parser \u03b1} (hF : \u2200 (p : parser \u03b1), valid p \u2192 valid (F p)) : valid (fix F) :=\n  fun (_x : char_buffer) (_x_1 : \u2115) => fix_core hF (buffer.size _x - _x_1 + 1) _x _x_1\n\nend valid\n\n\n@[simp] theorem orelse_pure_eq_fail {\u03b1 : Type} {p : parser \u03b1} {cb : char_buffer} {n : \u2115} {n' : \u2115} {err : dlist string} {a : \u03b1} : has_orelse.orelse p (pure a) cb n = parse_result.fail n' err \u2194 p cb n = parse_result.fail n' err \u2227 n \u2260 n' := sorry\n\ntheorem any_char_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char} : any_char cb n = parse_result.done n' c \u2194 n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c := sorry\n\ntheorem sat_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char} {p : char \u2192 Prop} [decidable_pred p] : sat p cb n = parse_result.done n' c \u2194 p c \u2227 n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c := sorry\n\ntheorem eps_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} : eps cb n = parse_result.done n' Unit.unit \u2194 n = n' := sorry\n\ntheorem ch_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char} : ch c cb n = parse_result.done n' Unit.unit \u2194 n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c := sorry\n\n-- TODO: add char_buf_eq_done, needs lemmas about matching buffers\n\ntheorem one_of_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {c : char} {cs : List char} : one_of cs cb n = parse_result.done n' c \u2194 c \u2208 cs \u2227 n' = n + 1 \u2227 buffer.read cb { val := n, property := hn } = c := sorry\n\ntheorem one_of'_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {cs : List char} : one_of' cs cb n = parse_result.done n' Unit.unit \u2194 buffer.read cb { val := n, property := hn } \u2208 cs \u2227 n' = n + 1 := sorry\n\ntheorem remaining_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} {r : \u2115} : remaining cb n = parse_result.done n' r \u2194 n = n' \u2227 buffer.size cb - n = r := sorry\n\ntheorem eof_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} : eof cb n = parse_result.done n' Unit.unit \u2194 n = n' \u2227 buffer.size cb \u2264 n := sorry\n\n@[simp] theorem foldr_core_zero_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} : foldr_core f p b 0 cb n \u2260 parse_result.done n' b' := sorry\n\ntheorem foldr_core_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {b' : \u03b2} : foldr_core f p b (reps + 1) cb n = parse_result.done n' b' \u2194\n  (\u2203 (np : \u2115),\n      \u2203 (a : \u03b1),\n        \u2203 (xs : \u03b2),\n          p cb n = parse_result.done np a \u2227 foldr_core f p b reps cb np = parse_result.done n' xs \u2227 f a xs = b') \u2228\n    n = n' \u2227\n      b = b' \u2227\n        \u2203 (err : dlist string),\n          p cb n = parse_result.fail n err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 foldr_core f p b reps cb np = parse_result.fail n err := sorry\n\n@[simp] theorem foldr_core_zero_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} : foldr_core f p b 0 cb n = parse_result.fail n' err \u2194 n = n' \u2227 err = dlist.empty := sorry\n\ntheorem foldr_core_succ_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {err : dlist string} : foldr_core f p b (reps + 1) cb n = parse_result.fail n' err \u2194\n  n \u2260 n' \u2227\n    (p cb n = parse_result.fail n' err \u2228\n      \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 foldr_core f p b reps cb np = parse_result.fail n' err) := sorry\n\ntheorem foldr_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} : foldr f p b cb n = parse_result.done n' b' \u2194\n  (\u2203 (np : \u2115),\n      \u2203 (a : \u03b1),\n        \u2203 (x : \u03b2),\n          p cb n = parse_result.done np a \u2227\n            foldr_core f p b (buffer.size cb - n) cb np = parse_result.done n' x \u2227 f a x = b') \u2228\n    n = n' \u2227\n      b = b' \u2227\n        \u2203 (err : dlist string),\n          p cb n = parse_result.fail n err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (x : \u03b1),\n                p cb n = parse_result.done np x \u2227 foldr_core f p b (buffer.size cb - n) cb np = parse_result.fail n err := sorry\n\ntheorem foldr_eq_fail_of_valid_at_end {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} (hp : valid p) (hc : buffer.size cb \u2264 n) : foldr f p b cb n = parse_result.fail n' err \u2194\n  n < n' \u2227 (p cb n = parse_result.fail n' err \u2228 \u2203 (a : \u03b1), p cb n = parse_result.done n' a \u2227 err = dlist.empty) := sorry\n\ntheorem foldr_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} : foldr f p b cb n = parse_result.fail n' err \u2194\n  n \u2260 n' \u2227\n    (p cb n = parse_result.fail n' err \u2228\n      \u2203 (np : \u2115),\n        \u2203 (a : \u03b1),\n          p cb n = parse_result.done np a \u2227 foldr_core f p b (buffer.size cb - n) cb np = parse_result.fail n' err) := sorry\n\n@[simp] theorem foldl_core_zero_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} : foldl_core f b p 0 cb n = parse_result.done n' b' \u2194 False := sorry\n\ntheorem foldl_core_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {b' : \u03b2} : foldl_core f b p (reps + 1) cb n = parse_result.done n' b' \u2194\n  (\u2203 (np : \u2115),\n      \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 foldl_core f (f b a) p reps cb np = parse_result.done n' b') \u2228\n    n = n' \u2227\n      b = b' \u2227\n        \u2203 (err : dlist string),\n          p cb n = parse_result.fail n err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 foldl_core f (f b a) p reps cb np = parse_result.fail n err := sorry\n\n@[simp] theorem foldl_core_zero_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} : foldl_core f b p 0 cb n = parse_result.fail n' err \u2194 n = n' \u2227 err = dlist.empty := sorry\n\ntheorem foldl_core_succ_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {reps : \u2115} {err : dlist string} : foldl_core f b p (reps + 1) cb n = parse_result.fail n' err \u2194\n  n \u2260 n' \u2227\n    (p cb n = parse_result.fail n' err \u2228\n      \u2203 (np : \u2115),\n        \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 foldl_core f (f b a) p reps cb np = parse_result.fail n' err) := sorry\n\ntheorem foldl_eq_done {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {b' : \u03b2} : foldl f b p cb n = parse_result.done n' b' \u2194\n  (\u2203 (np : \u2115),\n      \u2203 (a : \u03b1),\n        p cb n = parse_result.done np a \u2227 foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.done n' b') \u2228\n    n = n' \u2227\n      b = b' \u2227\n        \u2203 (err : dlist string),\n          p cb n = parse_result.fail n err \u2228\n            \u2203 (np : \u2115),\n              \u2203 (a : \u03b1),\n                p cb n = parse_result.done np a \u2227\n                  foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.fail n err := sorry\n\ntheorem foldl_eq_fail {\u03b1 : Type} {\u03b2 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {b : \u03b2} {f : \u03b2 \u2192 \u03b1 \u2192 \u03b2} {p : parser \u03b1} {err : dlist string} : foldl f b p cb n = parse_result.fail n' err \u2194\n  n \u2260 n' \u2227\n    (p cb n = parse_result.fail n' err \u2228\n      \u2203 (np : \u2115),\n        \u2203 (a : \u03b1),\n          p cb n = parse_result.done np a \u2227\n            foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.fail n' err) := sorry\n\ntheorem many_eq_done_nil {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} : many p cb n = parse_result.done n' [] \u2194\n  n = n' \u2227\n    \u2203 (err : dlist string),\n      p cb n = parse_result.fail n err \u2228\n        \u2203 (np : \u2115),\n          \u2203 (a : \u03b1),\n            p cb n = parse_result.done np a \u2227\n              foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.fail n err := sorry\n\ntheorem many_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} {x : \u03b1} {xs : List \u03b1} : many p cb n = parse_result.done n' (x :: xs) \u2194\n  \u2203 (np : \u2115),\n    p cb n = parse_result.done np x \u2227 foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' xs := sorry\n\ntheorem many_eq_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} {err : dlist string} : many p cb n = parse_result.fail n' err \u2194\n  n \u2260 n' \u2227\n    (p cb n = parse_result.fail n' err \u2228\n      \u2203 (np : \u2115),\n        \u2203 (a : \u03b1),\n          p cb n = parse_result.done np a \u2227\n            foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.fail n' err) := sorry\n\ntheorem many_char_eq_done_empty {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} : many_char p cb n = parse_result.done n' string.empty \u2194\n  n = n' \u2227\n    \u2203 (err : dlist string),\n      p cb n = parse_result.fail n err \u2228\n        \u2203 (np : \u2115),\n          \u2203 (c : char),\n            p cb n = parse_result.done np c \u2227\n              foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.fail n err := sorry\n\ntheorem many_char_eq_done_not_empty {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} {s : string} (h : s \u2260 string.empty) : many_char p cb n = parse_result.done n' s \u2194\n  \u2203 (np : \u2115),\n    p cb n = parse_result.done np (string.head s) \u2227\n      foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' (string.to_list (string.popn s 1)) := sorry\n\ntheorem many_char_eq_many_of_to_list {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} {s : string} : many_char p cb n = parse_result.done n' s \u2194 many p cb n = parse_result.done n' (string.to_list s) := sorry\n\ntheorem many'_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} : many' p cb n = parse_result.done n' Unit.unit \u2194\n  many p cb n = parse_result.done n' [] \u2228\n    \u2203 (np : \u2115),\n      \u2203 (a : \u03b1),\n        \u2203 (l : List \u03b1),\n          many p cb n = parse_result.done n' (a :: l) \u2227\n            p cb n = parse_result.done np a \u2227\n              foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' l := sorry\n\n@[simp] theorem many1_ne_done_nil {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} : many1 p cb n \u2260 parse_result.done n' [] := sorry\n\ntheorem many1_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {p : parser \u03b1} {l : List \u03b1} : many1 p cb n = parse_result.done n' (a :: l) \u2194\n  \u2203 (np : \u2115), p cb n = parse_result.done np a \u2227 many p cb np = parse_result.done n' l := sorry\n\ntheorem many1_eq_fail {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser \u03b1} {err : dlist string} : many1 p cb n = parse_result.fail n' err \u2194\n  p cb n = parse_result.fail n' err \u2228\n    \u2203 (np : \u2115), \u2203 (a : \u03b1), p cb n = parse_result.done np a \u2227 many p cb np = parse_result.fail n' err := sorry\n\n@[simp] theorem many_char1_ne_empty {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} : many_char1 p cb n \u2260 parse_result.done n' string.empty := sorry\n\ntheorem many_char1_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} {p : parser char} {s : string} (h : s \u2260 string.empty) : many_char1 p cb n = parse_result.done n' s \u2194\n  \u2203 (np : \u2115), p cb n = parse_result.done np (string.head s) \u2227 many_char p cb np = parse_result.done n' (string.popn s 1) := sorry\n\n@[simp] theorem sep_by1_ne_done_nil {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {sep : parser Unit} {p : parser \u03b1} : sep_by1 sep p cb n \u2260 parse_result.done n' [] := sorry\n\ntheorem sep_by1_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {sep : parser Unit} {p : parser \u03b1} {l : List \u03b1} : sep_by1 sep p cb n = parse_result.done n' (a :: l) \u2194\n  \u2203 (np : \u2115), p cb n = parse_result.done np a \u2227 many (sep >> p) cb np = parse_result.done n' l := sorry\n\ntheorem sep_by_eq_done_nil {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {sep : parser Unit} {p : parser \u03b1} : sep_by sep p cb n = parse_result.done n' [] \u2194\n  n = n' \u2227 \u2203 (err : dlist string), sep_by1 sep p cb n = parse_result.fail n err := sorry\n\n@[simp] theorem fix_core_ne_done_zero {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {F : parser \u03b1 \u2192 parser \u03b1} : fix_core F 0 cb n \u2260 parse_result.done n' a := sorry\n\ntheorem fix_core_eq_done {\u03b1 : Type} {cb : char_buffer} {n : \u2115} {n' : \u2115} {a : \u03b1} {F : parser \u03b1 \u2192 parser \u03b1} {max_depth : \u2115} : fix_core F (max_depth + 1) cb n = parse_result.done n' a \u2194 F (fix_core F max_depth) cb n = parse_result.done n' a := sorry\n\ntheorem digit_eq_done {cb : char_buffer} {n : \u2115} {n' : \u2115} (hn : n < buffer.size cb) {k : \u2115} : digit cb n = parse_result.done n' k \u2194\n  n' = n + 1 \u2227\n    k \u2264 bit1 (bit0 (bit0 1)) \u2227\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 \u2227\n        char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 1))))) \u2264 buffer.read cb { val := n, property := hn } \u2227\n          buffer.read cb { val := n, property := hn } \u2264 char.of_nat (bit1 (bit0 (bit0 (bit1 (bit1 1))))) := 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/buffer/parser/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.056652426104335525, "lm_q1q2_score": 0.02372019571738671}}
{"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": "/-\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.Tactic.Rewrite\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Eqns\n\nnamespace Lean.Elab.WF\nopen Meta\nopen Eqns\n\nstructure EqnInfo extends EqnInfoCore where\n  declNames      : Array Name\n  declNameNonRec : Name\n  deriving Inhabited\n\nprivate partial def deltaLHSUntilFix (mvarId : MVarId) : MetaM MVarId := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | throwTacticEx `deltaLHSUntilFix mvarId \"equality expected\"\n  if lhs.isAppOf ``WellFounded.fix then\n    return mvarId\n  else\n    deltaLHSUntilFix (\u2190 deltaLHS mvarId)\n\nprivate def rwFixEq (mvarId : MVarId) : MetaM MVarId := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | unreachable!\n  let h := mkAppN (mkConst ``WellFounded.fix_eq lhs.getAppFn.constLevels!) lhs.getAppArgs\n  let r \u2190 rewrite mvarId target h\n  replaceTargetEq mvarId r.eNew r.eqProof\n\nprivate partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do\n  trace[Elab.definition.wf.eqns] \"proving: {type}\"\n  withNewMCtxDepth do\n    let main \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let (_, mvarId) \u2190 intros main.mvarId!\n    go (\u2190 rwFixEq (\u2190 deltaLHSUntilFix mvarId))\n    instantiateMVars main\nwhere\n  go (mvarId : MVarId) : MetaM Unit := do\n    trace[Elab.definition.wf.eqns] \"step\\n{MessageData.ofGoal mvarId}\"\n    if (\u2190 tryURefl mvarId) then\n      return ()\n    else if (\u2190 tryContradiction mvarId) then\n      return ()\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpIf? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 whnfReducibleLHS? mvarId then\n      go mvarId\n    else if let some mvarIds \u2190 casesOnStuckLHS? mvarId then\n      mvarIds.forM go\n    else\n      throwError \"failed to generate equational theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n\ndef mkEqns (declName : Name) (info : EqnInfo) : MetaM (Array Name) :=\n  withOptions (tactic.hygienic.set . false) do\n  let baseName := mkPrivateName (\u2190 getEnv) declName\n  let eqnTypes \u2190 withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do\n    let us := info.levelParams.map mkLevelParam\n    let target \u2190 mkEq (mkAppN (Lean.mkConst declName us) xs) body\n    let goal \u2190 mkFreshExprSyntheticOpaqueMVar target\n    mkEqnTypes info.declNames goal.mvarId!\n  let mut thmNames := #[]\n  for i in [: eqnTypes.size] do\n    let type := eqnTypes[i]\n    trace[Elab.definition.wf.eqns] \"{eqnTypes[i]}\"\n    let name := baseName ++ (`_eq).appendIndexAfter (i+1)\n    thmNames := thmNames.push name\n    let value \u2190 mkProof declName type\n    addDecl <| Declaration.thmDecl {\n      name, type, value\n      levelParams := info.levelParams\n    }\n  return thmNames\n\nbuiltin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo \u2190 mkMapDeclarationExtension `wfEqInfo\n\ndef registerEqnsInfo (preDefs : Array PreDefinition) (declNameNonRec : Name) : CoreM Unit := do\n  let declNames := preDefs.map (\u00b7.declName)\n  modifyEnv fun env =>\n    preDefs.foldl (init := env) fun env preDef =>\n      eqnInfoExt.insert env preDef.declName { preDef with declNames, declNameNonRec }\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  let env \u2190 getEnv\n  if let some eqs := eqnsExt.getState env |>.map.find? declName then\n    return some eqs\n  else if let some info := eqnInfoExt.find? env declName then\n    let eqs \u2190 mkEqns declName info\n    modifyEnv fun env => eqnsExt.modifyState env fun s => { s with map := s.map.insert declName eqs }\n    return some eqs\n  else\n    return none\n\ndef getUnfoldFor? (declName : Name) : MetaM (Option Name) := do\n  let env \u2190 getEnv\n  Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (\u00b7.toEqnInfoCore)\n\nbuiltin_initialize\n  registerGetEqnsFn getEqnsFor?\n  registerGetUnfoldEqnFn getUnfoldFor?\n  registerTraceClass `Elab.definition.wf.eqns\n\nend Lean.Elab.WF\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/Elab/PreDefinition/WF/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.05184546976292211, "lm_q1q2_score": 0.02370046782980137}}
{"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 := \u27e8iotaInhabited\u27e9\n\ndef processThfDefinedType (ty : Syntax) : MacroM Syntax := do\n  match ty with\n  | `(defined_type|\ud83c\udf49$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|\ud83c\udf49$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 \u2190\n      pure $ \u2190 ((@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 \u2192 B \u2192 ... \u2192 Type`, then we also return\n    an Array containing the stx for `A`, `B`, etc. (in reverse order. So `A \u2192 B \u2192 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 \u00d7 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 \u2190 processThfAtomicType ty\n    let typeStx \u2190 `(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) \u2190 processThfType ret\n    let (arg, _) \u2190 processThfType arg\n    let res \u2190 `($arg \u2192 $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 \u2190 processThfAtomicType ret\n    let args : Array Syntax := @Syntax.SepArray.mk \"*\" args.raw[0].getArgs\n    let args \u2190 args.mapM (fun a => processThfAtomicType a)\n    let res \u2190 args.foldrM (fun (a acc : Syntax) => `($a \u2192 $acc)) ret\n    let typeStx \u2190 `(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, _) \u2190 processThfType ty\n    let vs : Array Syntax := vs\n    let res \u2190 vs.foldrM\n      fun v acc => do\n        let (v, v_ty) \u2190 match v with\n        | `(thf_variable| $v:ident) =>\n          -- throw Error?\n          pure (v, (\u2190 `(_) : Syntax))\n        | `(thf_variable| $v:ident : $v_ty:thf_type) =>\n          pure (v, (\u2190 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 _ \"!>\" => `(\u2200 ($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 \u2190 processThfTerm t is_untyped\n    `(\u00ac $t)\n  | `(thf_term| $t\u2081:thf_term @ $t\u2082:thf_term) => do\n    let t\u2081 \u2190 processThfTerm t\u2081 is_untyped\n    let t\u2082 \u2190 processThfTerm t\u2082 is_untyped\n    `(($t\u2081 $t\u2082))\n  | `(thf_term| $t\u2081:thf_term $conn:bexpOp $t\u2082:thf_term ) => do\n    let t\u2081 \u2190 processThfTerm t\u2081 is_untyped\n    let t\u2082 \u2190 processThfTerm t\u2082 is_untyped\n    match conn.raw[0].getKind with\n    | Name.str _ \"&\" => `($t\u2081 \u2227 $t\u2082)\n    | Name.str _ \"=>\" => `($t\u2081 \u2192 $t\u2082)\n    | Name.str _ \"|\"=> `($t\u2081 \u2228 $t\u2082)\n    | Name.str _ \"<=>\" => `($t\u2081 \u2194 $t\u2082)\n    | Name.str _ \"<~>\" => `(\u00ac ($t\u2081 \u2194 $t\u2082))\n    | Name.str _ \"~|\" => `(\u00ac ($t\u2081 \u2228 $t\u2082))\n    | Name.str _ \"~&\" => `(\u00ac ($t\u2081 \u2227 $t\u2082))\n    | _ => Macro.throwError s!\"Unsupported bexpOp: {conn.raw[0].getKind}\"\n  | `(thf_term| $t\u2081:thf_term $conn:eqOp $t\u2082:thf_term ) => do\n    let t\u2081 \u2190 processThfTerm t\u2081 is_untyped\n    let t\u2082 \u2190 processThfTerm t\u2082 is_untyped\n    match conn.raw[0].getKind with\n    | Name.str _ \"=\" => `($t\u2081 = $t\u2082)\n    | Name.str _ \"!=\" => `($t\u2081 \u2260 $t\u2082)\n    | _ => Macro.throwError s!\"Unsupported eqOp: {conn.raw[0].getKind}\"\n  | `(thf_term| $f:ident $args:thf_arguments ?) => do\n    let ts : Array Syntax \u2190 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 \u2190 processThfTerm body is_untyped\n    let vs : Array Syntax := vs\n    vs.foldrM\n      fun v acc => do\n        let (v, ty) \u2190 match v with\n        | `(thf_variable| $v:ident) =>\n          if is_untyped then\n            let iotaTypeSyntax \u2190 `(TPTP.iota)\n            pure (v, iotaTypeSyntax.raw)\n          else\n            -- throw Error?\n            pure (v, (\u2190 `(_) : Syntax))\n        | `(thf_variable| $v:ident : $ty:thf_type) =>\n          pure (v, (\u2190 processThfType ty).1)\n        | _ => Macro.throwError s!\"Unsupported thf_variable: {v}\"\n        match q.raw[0].getKind with\n        | Name.str _ \"!\" => `(\u2200 ($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 (\u2190 getVarsHelper t1).append (\u2190 getVarsHelper t2)\n  | `(thf_term| $t1:thf_term $conn:eqOp $t2:thf_term ) =>\n    return (\u2190 getVarsHelper t1).append (\u2190 getVarsHelper t2)\n  | `(thf_term| $f:ident $args:thf_arguments ?) =>\n    match args with\n    | none =>\n      if (\u2190 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 \u2190 args.mapM (fun arg => getVarsHelper arg)\n      let argsVars := argsVars.foldl\n        (fun acc varList => varList.append acc) []\n      if (\u2190 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 \u2190 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 \u2190 getVars stx\n  let iotaTypeSyntax \u2190 `(TPTP.iota)\n  let unquantifiedRes \u2190 processThfTerm stx true\n  let quantifiedRes \u2190 vars.foldlM\n    (fun acc (var : TSyntax `ident) => `(\u2200 ($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|\ud83c\udf49$id:ident) => return acc\n  | `(thf_term| ( $t:thf_term )) => getNonVarSymbols acc topType t\n  | `(thf_term| ~ $t:thf_term ) =>\n    if topType != (\u2190 `(Prop)) then Macro.throwError s!\"Error: cnf/fof term: {stx} is supposed to have type {topType}\"\n    else getNonVarSymbols acc (\u2190 `(Prop)) t\n  | `(thf_term| $t1:thf_term $conn:bexpOp $t2:thf_term ) =>\n    if topType != (\u2190 `(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 (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(Prop)) t2\n      | Name.str _ \"=>\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(Prop)) t2\n      | Name.str _ \"|\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(Prop)) t2\n      | Name.str _ \"<=>\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(Prop)) t2\n      | Name.str _ \"<~>\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(Prop)) t2\n      | Name.str _ \"~|\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(Prop)) t2\n      | Name.str _ \"~&\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(Prop)) t1) (\u2190 `(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 != (\u2190 `(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 (\u2190 getNonVarSymbols acc (\u2190 `(TPTP.iota)) t1) (\u2190 `(TPTP.iota)) t2\n      | Name.str _ \"!=\" => getNonVarSymbols (\u2190 getNonVarSymbols acc (\u2190 `(TPTP.iota)) t1) (\u2190 `(TPTP.iota)) t2\n      | _ => Macro.throwError s!\"Unsupported eqOp: {conn.raw[0].getKind}\"\n  | `(thf_term| $f:ident $args:thf_arguments ?) =>\n    if (\u2190 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 \u2190 `(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 \u2190 `(TPTP.iota)\n      let fType \u2190 args.foldlM (fun (acc _ : Syntax) => do\n        `($iotaTypeSyntax \u2192 $acc)) topType\n      let acc \u2190 args.foldlM (fun acc arg => do\n        getNonVarSymbols acc (\u2190 `(TPTP.iota)) arg) acc\n      let s := f.getId.getString!\n      let binder \u2190 `(explicitBinder| ($f : $fType))\n      return acc.insert s binder\n  | `(thf_term| $q:quantifier [ $vs,* ] : $body) =>\n    if topType != (\u2190 `(Prop)) then Macro.throwError s!\"Error: cnf/fof term: {stx} is supposed to have type {topType}\"\n    else getNonVarSymbols acc (\u2190 `(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 \u2190 getNonVarSymbols symtab (\u2190 `(Prop)) term\n    | `(TPTP_input| fof($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n      symtab \u2190 getNonVarSymbols symtab (\u2190 `(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 \u2190 processThfTerm term false\n      let name := (mkIdent $ name.getId.appendBefore \"h\")\n      if role.getId == `conjecture then\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : \u00ac $term)))\n      else\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : $term)))\n    | `(TPTP_input| tff($n:ident,type,$name:ident : $ty:thf_type $annotation:annotation ?).) =>\n      let (ty, stxArrOpt) \u2190 processThfType ty\n      hyps := hyps.push (\u2190 `(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 \u2190 `($name)\n        let mut typeArgs : Array Ident := #[]\n        for _ in stxArr do\n          let typeArg := mkIdent $ typeArgName.appendAfter (toString counter)\n          nameApp \u2190 `($nameApp $typeArg)\n          counter := counter + 1\n          typeArgs := typeArgs.push typeArg\n        let mut quantifiedNameApp \u2190 `(Inhabited $nameApp)\n        for (stx, typeArg) in stxArr.zip typeArgs.reverse do\n          quantifiedNameApp \u2190 `(\u2200 $typeArg : $stx, $quantifiedNameApp)\n        hyps := hyps.push (\u2190 `(explicitBinder| (_ : $quantifiedNameApp)))\n    | `(TPTP_input| thf($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n      let term \u2190 processThfTerm term false\n      let name := (mkIdent $ name.getId.appendBefore \"h\")\n      if role.getId == `conjecture then\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : \u00ac $term)))\n      else\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : $term)))\n    | `(TPTP_input| thf($n:ident,type,$name:ident : $ty:thf_type $annotation:annotation ?).) =>\n      let (ty, stxArrOpt) \u2190 processThfType ty\n      hyps := hyps.push (\u2190 `(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 \u2190 `($name)\n        let mut typeArgs : Array Ident := #[]\n        for _ in stxArr do\n          let typeArg := mkIdent $ typeArgName.appendAfter (toString counter)\n          nameApp \u2190 `($nameApp $typeArg)\n          counter := counter + 1\n          typeArgs := typeArgs.push typeArg\n        let mut quantifiedNameApp \u2190 `(Inhabited $nameApp)\n        for (stx, typeArg) in stxArr.zip typeArgs.reverse do\n          quantifiedNameApp \u2190 `(\u2200 $typeArg : $stx, $quantifiedNameApp)\n        hyps := hyps.push (\u2190 `(explicitBinder| (_ : $quantifiedNameApp)))\n    | `(TPTP_input| cnf($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n      let term \u2190 processCnfTerm term\n      let name := (mkIdent $ name.getId.appendBefore \"h\")\n      if role.getId == `conjecture then\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : \u00ac $term)))\n      else\n        hyps := hyps.push (\u2190 `(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 \u2190 processThfTerm term true\n      let name := (mkIdent $ name.getId.appendBefore \"h\")\n      if role.getId == `conjecture then\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : \u00ac $term)))\n      else\n        hyps := hyps.push (\u2190 `(explicitBinder| ($name : $term)))\n    | _ => Macro.throwError s!\"Unsupported TPTP_input: {input}\"\n  let hypall := mkNode ``many (nonVarSymbols.toArray.append hyps)\n  let spec \u2190 `(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\u03b1 := inferInstance\n  i\u03b5 := 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 \u0394)\n  (rgn: TypedArgs \u0394 \u2192 OpM \u0394 (TypedArgs \u0394)): OpM \u0394 (TypedArgs \u0394):= do\n  match n with\n  | 0 => return start\n  | .succ n' => do\n    let (_: TypedArgs \u0394) <- rgn [\u27e8MLIRType.index, ix\u27e9]\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 \u0394 \u2192 OpM \u0394 (TypedArgs \u0394)\n  | IOp.mk \"scf.if\" _ [\u27e8.i1, b\u27e9]  [rthen, relse] _ => do\n      (if b = 1 then rthen else relse) []\n  | IOp.mk \"scf.for\" _ [\u27e8.index, lo\u27e9, \u27e8.index, hi\u27e9, \u27e8.index, step\u27e9] [body] _ => do\n    let nsteps : Int := (hi - lo) / step\n    let _  \u2190 run_loop_bounded_stepped\n      (a := TypedArgs \u0394)\n      (n := nsteps.toNat)\n      (lo := lo)\n      (step := step)\n      (accum := default)\n      (eff := (fun i _ => body [\u27e8.index, i\u27e9]))\n    return []\n  | IOp.mk \"scf.for'\" _ [\u27e8.index, lo\u27e9, \u27e8.index, hi\u27e9] [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\" _ [\u27e8.i1, arg\u27e9] [] 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} <assert failed>\"\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\u2081 r\u2082: Region scf): Region scf := [mlir_region|\n{\n  \"scf.if\" (%b) ($(r\u2081), $(r\u2082)) : (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 \u27e6LHS r\u2081 r\u2082\u27e7 (INPUT b) =\n    run (TopM.scoped (denoteRegion\n          (\u0394 := scf)\n          (rgn := if b then r\u2081 else r\u2082)\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  \u27e8\"cn\", .index, n\u27e9,\n  \u27e8\"cn_plus_1\", .index, n + 1\u27e9,\n  \u27e8\"c0\", .index, 0\u27e9,\n  \u27e8\"c1\", .index, 1\u27e9]\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) (\u03c4: MLIRType scf) (v: MLIRType.eval \u03c4)\n  (ENV: SSAEnv.get name \u03c4 (INPUT n) = some v)\n  (k: BlockResult scf \u2192 \u03c4.eval \u2192 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 \u03c4 name) fun v => k discr v)) (INPUT n) =\n  run (Fitree.Vis (Sum.inl <| SSAEnvE.Get \u03c4 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\u2081 (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 \u27e6LHS r\u27e7 (INPUT n)) =\n    (run \u27e6RHS r\u27e7 (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 <num>' 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 [\u27e8.index, 0\u27e9]\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\u2081]\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  \u27e8\"cn\", .index, n\u27e9,\n  \u27e8\"cn_plus_m\", .index, n + m\u27e9,\n  \u27e8\"c0\", .index, 0\u27e9]\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 \u27e6LHS r\u27e7 (INPUT n m)) =\n    (run \u27e6RHS r\u27e7 (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 tactic --hide\n\n/-Lemma\nFalse implies false.\n-/\nlemma false_imp_false : false \u2192 false :=\nbegin\n  intro f,\n  exact f,\n\n\n\nend", "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/true_false/tf4.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2658804847339313, "lm_q2_score": 0.0888202960180265, "lm_q1q2_score": 0.023615583359484153}}
{"text": "import tactic\n\nnamespace blueprint\n\nlemma first_test (h : false) : true :=\nbegin\n  tauto,\nend\n\nlemma second_test (h : false) : true :=\nbegin\n  tauto,\nend\n\nend blueprint", "meta": {"author": "mariainesdff", "repo": "local_class_field_theory", "sha": "ffa8bc00cd45f6bee74e3a5ef7def8678bcee0b0", "save_path": "github-repos/lean/mariainesdff-local_class_field_theory", "path": "github-repos/lean/mariainesdff-local_class_field_theory/local_class_field_theory-ffa8bc00cd45f6bee74e3a5ef7def8678bcee0b0/src/blueprint_tests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3486451353339458, "lm_q2_score": 0.06754669160889748, "lm_q1q2_score": 0.023549825437344366}}
{"text": "example (h : 0 = 1) : False := by\n  first | trace_state; fail | contradiction\n\nexample (h : 0 = 1) : False := by\n  first | trace \"first branch\"; fail | contradiction\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/traceStateBactracking.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.0715912009301811, "lm_q1q2_score": 0.023458167162506757}}
{"text": "/-\nCopyright (c) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn\n-/\nimport data.string.defs\nimport tactic.derive_inhabited\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\nopen tactic\n\nattribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind\n\n@[priority 100] meta instance has_reflect.has_to_pexpr {\u03b1} [has_reflect \u03b1] : has_to_pexpr \u03b1 :=\n\u27e8\u03bb b, pexpr.of_expr (reflect b)\u27e9\n\nnamespace binder_info\n\n/-! ### Declarations about `binder_info` -/\n\ninstance : inhabited binder_info := \u27e8 binder_info.default \u27e9\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : binder_info \u2192 string \u00d7 string\n| binder_info.implicit        := (\"{\", \"}\")\n| binder_info.strict_implicit := (\"{{\", \"}}\")\n| binder_info.inst_implicit   := (\"[\", \"]\")\n| _                           := (\"(\", \")\")\n\nend binder_info\n\nnamespace name\n\n/-! ### Declarations about `name` -/\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef map_prefix (f : name \u2192 option name) : name \u2192 name\n| anonymous := anonymous\n| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')\n| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\nmeta def deinternalize_field : name \u2192 name\n| (mk_string s name.anonymous) :=\n  let i := s.mk_iterator in\n  if i.curr = '_' then i.next.next_to_string else s\n| n := n\n\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\nmeta def get_nth_prefix : name \u2192 \u2115 \u2192 name\n| nm 0 := nm\n| nm (n + 1) := get_nth_prefix nm.get_prefix n\n\n/-- Auxiliary definition for `pop_nth_prefix` -/\nprivate meta def pop_nth_prefix_aux : name \u2192 \u2115 \u2192 name \u00d7 \u2115\n| anonymous n := (anonymous, 1)\n| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in\n          if height \u2264 n then (anonymous, height + 1)\n          else (nm.update_prefix pfx, height + 1)\n\n/-- Pops the top `n` prefixes from the given name. -/\nmeta def pop_nth_prefix (nm : name) (n : \u2115) : name :=\nprod.fst $ pop_nth_prefix_aux nm n\n\n/-- Pop the prefix of a name -/\nmeta def pop_prefix (n : name) : name :=\npop_nth_prefix n 1\n\n/-- Auxiliary definition for `from_components` -/\nprivate def from_components_aux : name \u2192 list string \u2192 name\n| n [] := n\n| n (s :: rest) := from_components_aux (name.mk_string s n) rest\n\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef from_components : list string \u2192 name :=\nfrom_components_aux name.anonymous\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\nmeta def sanitize_name : name \u2192 name\n| name.anonymous := name.anonymous\n| (name.mk_string s p) := name.mk_string s $ sanitize_name p\n| (name.mk_numeral s p) := name.mk_string sformat!\"n{s}\" $ sanitize_name p\n\n/-- Append a string to the last component of a name. -/\ndef append_suffix : name \u2192 string \u2192 name\n| (mk_string s n) s' := mk_string (s ++ s') n\n| n _ := n\n\n/-- Update the last component of a name. -/\ndef update_last (f : string \u2192 string) : name \u2192 name\n| (mk_string s n) := mk_string (f s) n\n| n := n\n\n/-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`,\n  either as prefix or as suffix (specified by `is_prefix`), separated by `_`.\n  Used by `simps_add_projections`. -/\ndef append_to_last (nm : name) (s : string) (is_prefix : bool) : name :=\nnm.update_last $ \u03bb s', if is_prefix then s ++ \"_\" ++ s' else s' ++ \"_\" ++ s\n\n/-- The first component of a name, turning a number to a string -/\nmeta def head : name \u2192 string\n| (mk_string s anonymous) := s\n| (mk_string s p)         := head p\n| (mk_numeral n p)        := head p\n| anonymous               := \"[anonymous]\"\n\n/-- Tests whether the first component of a name is `\"_private\"` -/\nmeta def is_private (n : name) : bool :=\nn.head = \"_private\"\n\n/-- Get the last component of a name, and convert it to a string. -/\nmeta def last : name \u2192 string\n| (mk_string s _)  := s\n| (mk_numeral n _) := repr n\n| anonymous        := \"[anonymous]\"\n\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\nmeta def length : name \u2192 \u2115\n| (mk_string s anonymous) := s.length\n| (mk_string s p)         := s.length + 1 + p.length\n| (mk_numeral n p)        := p.length\n| anonymous               := \"[anonymous]\".length\n\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef has_prefix (P : name \u2192 bool) : name \u2192 bool\n| anonymous := ff\n| (mk_string s nm)  := P (mk_string s nm) \u2228 has_prefix nm\n| (mk_numeral s nm) := P (mk_numeral s nm) \u2228 has_prefix nm\n\n/-- Appends `'` to the end of a name. -/\nmeta def add_prime : name \u2192 name\n| (name.mk_string s p) := name.mk_string (s ++ \"'\") p\n| n := (name.mk_string \"x'\" n)\n\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef last_string : name \u2192 string\n| anonymous        := \"[anonymous]\"\n| (mk_string s _)  := s\n| (mk_numeral _ n) := last_string n\n\n/--\nConstructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\nmeta def from_string (s : string) : name :=\nfrom_components $ s.split (= '.')\n\n\n/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\nlibrary_note \"likely generated binder names\"\n\n/--\nCheck whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_simple_name : string \u2192 bool\n| \"\u1fb0\" := tt\n| n :=\n  match n.get_rest \"\u1fb0_\" with\n  | none := ff\n  | some suffix := suffix.is_nat\n  end\n\n/--\nCheck whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_name (n : name) : bool :=\nmatch n with\n| mk_string s anonymous := is_likely_generated_binder_simple_name s\n| _ := ff\nend\n\nend name\n\nnamespace level\n\n/-! ### Declarations about `level` -/\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\nmeta def nonzero : level \u2192 bool\n| (succ _) := tt\n| (max l\u2081 l\u2082) := l\u2081.nonzero || l\u2082.nonzero\n| (imax _ l\u2082) := l\u2082.nonzero\n| _ := ff\n\n/--\n`l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nmeta def fold_mvar {\u03b1} : level \u2192 (name \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 \u03b1\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 \u2218 fold_mvar b f\n| (imax a b) f := fold_mvar a f \u2218 fold_mvar b f\n\n/--\n`l.params` is the set of parameters occuring in `l`.\nFor example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`.\n-/\nprotected meta def params (u : level) : name_set :=\nu.fold mk_name_set $ \u03bb v l,\n  match v with\n  | (param nm) := l.insert nm\n  | _ := l\n  end\n\nend level\n\n/-! ### Declarations about `binder` -/\n\n/-- The type of binders containing a name, the binding info and the binding type -/\n@[derive decidable_eq, derive inhabited]\nmeta structure binder :=\n  (name : name)\n  (info : binder_info)\n  (type : expr)\n\nnamespace binder\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nprotected meta def to_string (b : binder) : string :=\nlet (l, r) := b.info.brackets in\nl ++ b.name.to_string ++ \" : \" ++ b.type.to_string ++ r\n\nmeta instance : has_to_string binder := \u27e8 binder.to_string \u27e9\nmeta instance : has_to_format binder := \u27e8 \u03bb b, b.to_string \u27e9\nmeta instance : has_to_tactic_format binder :=\n\u27e8 \u03bb b, let (l, r) := b.info.brackets in\n  (\u03bb e, l ++ b.name.to_string ++ \" : \" ++ e ++ r) <$> pp b.type \u27e9\n\nend binder\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n\n/--\n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def nat.mk_numeral (type has_zero has_one has_add : expr) : \u2115 \u2192 expr :=\nlet z : expr := `(@has_zero.zero.{0} %%type %%has_zero),\n    o : expr := `(@has_one.one.{0} %%type %%has_one) in\nnat.binary_rec z\n  (\u03bb b n e, if n = 0 then o else\n    if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)\n    else `(@bit0.{0} %%type %%has_add %%e))\n\n/--\n`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : \u2124 \u2192 expr\n| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add\n| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in\n            `(@has_neg.neg.{0} %%type %%has_neg %%ne)\n\n/--\n`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nmeta def nat.to_pexpr : \u2115 \u2192 pexpr\n| 0 := ``(0)\n| 1 := ``(1)\n| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))\nnamespace expr\n\n/--\nTurns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\nprotected meta def to_nat : expr \u2192 option \u2115\n| `(has_zero.zero) := some 0\n| `(has_one.one) := some 1\n| `(bit0 %%e) := bit0 <$> e.to_nat\n| `(bit1 %%e) := bit1 <$> e.to_nat\n| `(nat.succ %%e) := (+1) <$> e.to_nat\n| `(nat.zero) := some 0\n| _ := none\n\n/--\nTurns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\nprotected meta def to_int : expr \u2192 option \u2124\n| `(has_neg.neg %%e) := do n \u2190 e.to_nat, some (-n)\n| e                  := coe <$> e.to_nat\n\n/--\nTurns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`.\n-/\nprotected meta def to_list {\u03b1} (f : expr \u2192 option \u03b1) : expr \u2192 option (list \u03b1)\n| `(list.nil)          := some []\n| `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list\n| _                    := none\n\n/--\n`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\nignoring differences in type and type class arguments.\n-/\nmeta def is_num_eq : expr \u2192 expr \u2192 bool\n| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt\n| `(@has_one.one _ _) `(@has_one.one _ _) := tt\n| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b\n| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b\n| `(-%%a) `(-%%b) := a.is_num_eq b\n| `(%%a/%%a') `(%%b/%%b') :=  a.is_num_eq b\n| _ _ := ff\n\nend expr\n\n/-! ### Declarations about `expr` -/\n\nnamespace expr\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\nmeta def clean_ids : list name :=\n[``id, ``id_rhs, ``id_delta, ``hidden]\n\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\nmeta def clean (e : expr) : expr :=\ne.replace (\u03bb e n,\n     match e with\n     | (app (app (const n _) _) e') :=\n       if n \u2208 clean_ids then some e' else none\n     | (app (lam _ _ _ (var 0)) e') := some e'\n     | _ := none\n     end)\n\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\nmeta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=\ne.replace $ \u03bbc d, if c = s then some (s'.lift_vars 0 d) else none\n\n/-- Implementation of `expr.mreplace`. -/\nmeta def mreplace_aux {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) :\n  expr \u2192 \u2115 \u2192 m expr\n| (app f x) n := option.mget_or_else (R (app f x) n)\n  (do Rf \u2190 mreplace_aux f n, Rx \u2190 mreplace_aux x n, return $ app Rf Rx)\n| (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd)\n| (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd)\n| (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n)\n  (do Rty \u2190 mreplace_aux ty n,\n    Ra \u2190 mreplace_aux a n,\n    Rb \u2190 mreplace_aux b n,\n    return $ elet nm Rty Ra Rb)\n| (macro c es) n := option.mget_or_else (R (macro c es) n) $\n    macro c <$> es.mmap (\u03bb e, mreplace_aux e n)\n| e n := option.mget_or_else (R e n) (return e)\n\n/--\nMonadic analogue of `expr.replace`.\n\nThe `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where\n`n` is the number of binders above `e`.\nIf `R s n` fails, the whole replacement fails.\nIf `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit\nits subexpressions).\nIf `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.\n\nWARNING: This function performs exponentially worse on large terms than `expr.replace`,\nif a subexpression occurs more than once in an expression, `expr.replace` visits them only once,\nbut this function will visit every occurence of it. Do not use this on large expressions.\n-/\nmeta def mreplace {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) (e : expr) :\n  m expr :=\nmreplace_aux R e 0\n\n/-- Match a variable. -/\nmeta def match_var {elab} : expr elab \u2192 option \u2115\n| (var n) := some n\n| _ := none\n\n/-- Match a sort. -/\nmeta def match_sort {elab} : expr elab \u2192 option level\n| (sort u) := some u\n| _ := none\n\n/-- Match a constant. -/\nmeta def match_const {elab} : expr elab \u2192 option (name \u00d7 list level)\n| (const n lvls) := some (n, lvls)\n| _ := none\n\n/-- Match a metavariable. -/\nmeta def match_mvar {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 expr elab)\n| (mvar unique pretty type) := some (unique, pretty, type)\n| _ := none\n\n/-- Match a local constant. -/\nmeta def match_local_const {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 binder_info \u00d7 expr elab)\n| (local_const unique pretty bi type) := some (unique, pretty, bi, type)\n| _ := none\n\n/-- Match an application. -/\nmeta def match_app {elab} : expr elab \u2192 option (expr elab \u00d7 expr elab)\n| (app t u) := some (t, u)\n| _ := none\n\n/-- Match an application of `coe_fn`. -/\nmeta def match_app_coe_fn : expr \u2192 option (expr \u00d7 expr \u00d7 expr \u00d7 expr \u00d7 expr)\n| (app `(@coe_fn %%\u03b1 %%\u03b2 %%inst %%fexpr) x) := some (\u03b1, \u03b2, inst, fexpr, x)\n| _ := none\n\n/-- Match an abstraction. -/\nmeta def match_lam {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (lam var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a \u03a0 type. -/\nmeta def match_pi {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (pi var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a let. -/\nmeta def match_elet {elab} : expr elab \u2192\n  option (name \u00d7 expr elab \u00d7 expr elab \u00d7 expr elab)\n| (elet var_name type assignment body) := some (var_name, type, assignment, body)\n| _ := none\n\n/-- Match a macro. -/\nmeta def match_macro {elab} : expr elab \u2192\n  option (macro_def \u00d7 list (expr elab))\n| (macro df args) := some (df, args)\n| _ := none\n\n/-- Tests whether an expression is a meta-variable. -/\nmeta def is_mvar : expr \u2192 bool\n| (mvar _ _ _) := tt\n| _            := ff\n\n/-- Tests whether an expression is a sort. -/\nmeta def is_sort : expr \u2192 bool\n| (sort _) := tt\n| e         := ff\n\n/-- Get the universe levels of a `const` expression -/\nmeta def univ_levels : expr \u2192 list level\n| (const n ls) := ls\n| _            := []\n\n/--\nReplace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\nmeta def replace_mvars (e : expr) : expr :=\ne.replace (\u03bb e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)\n\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\nmeta def to_implicit_local_const : expr \u2192 expr\n| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t\n| e := e\n\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.\n-/\nmeta def to_implicit_binder : expr \u2192 expr\n| (local_const n\u2081 n\u2082 _ d) := local_const n\u2081 n\u2082 binder_info.implicit d\n| (lam n _ d b) := lam n binder_info.implicit d b\n| (pi n _ d b) := pi n binder_info.implicit d b\n| e  := e\n\n/-- Returns a list of all local constants in an expression (without duplicates). -/\nmeta def list_local_consts (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_local_constant then insert e' es else es)\n\n/-- Returns the set of all local constants in an expression. -/\nmeta def list_local_consts' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_local_constant then es.insert e' else es)\n\n/-- Returns the unique names of all local constants in an expression. -/\nmeta def list_local_const_unique_names (e : expr) : name_set :=\ne.fold mk_name_set\n  (\u03bb e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es)\n\n/-- Returns a name_set of all constants in an expression. -/\nmeta def list_constant (e : expr) : name_set :=\ne.fold mk_name_set (\u03bb e' _ es, if e'.is_constant then es.insert e'.const_name else es)\n\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\nmeta def list_meta_vars (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_mvar then insert e' es else es)\n\n/-- Returns the set of all meta-variables in an expression. -/\nmeta def list_meta_vars' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_mvar then es.insert e' else es)\n\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\nmeta def list_univ_meta_vars (e : expr) : list name :=\nnative.rb_set.to_list $ e.fold native.mk_rb_set $ \u03bb e' i s,\nmatch e' with\n| (sort u) := u.fold_mvar (flip native.rb_set.insert) s\n| (const _ ls) := ls.foldl (\u03bb s' l, l.fold_mvar (flip native.rb_set.insert) s') s\n| _ := s\nend\n\n/--\nTest `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\nmeta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=\n-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n\u00ac t.list_meta_vars.empty \u2228 e.occurs t\n\n/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/\nmeta def list_names_with_prefix (pre : name) (e : expr) : name_set :=\ne.fold mk_name_set $ \u03bb e' _ l,\n  match e' with\n  | expr.const n _ := if n.get_prefix = pre then l.insert n else l\n  | _ := l\n  end\n\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\nmeta def contains_constant (e : expr) (p : name \u2192 Prop) [decidable_pred p] : bool :=\ne.fold ff (\u03bb e' _ b, if p (e'.const_name) then tt else b)\n\n/--\nReturns true if `e` contains a `sorry`.\nSee also `name.contains_sorry`.\n-/\nmeta def contains_sorry (e : expr) : bool :=\ne.fold ff (\u03bb e' _ b, if (is_sorry e').is_some then tt else b)\n\n/--\n`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\nmeta def app_symbol_in (e : expr) (l : list name) : bool :=\nmatch e.get_app_fn with\n| (expr.const n _) := n \u2208 l\n| _ := ff\nend\n\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\nmeta def get_simp_args (e : expr) : tactic (list expr) :=\n-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\nif \u00ac e.is_app then pure [] else do\ncgr \u2190 mk_specialized_congr_lemma_simp e,\npure $ do\n  (arg_kind, arg) \u2190 cgr.arg_kinds.zip e.get_app_args,\n  guard $ arg_kind = congr_arg_kind.eq,\n  pure arg\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\nmeta def simp (t : expr)\n  (cfg : simp_config := {}) (discharger : tactic unit := failed)\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic (expr \u00d7 expr \u00d7 name_set) :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   simplify s to_unfold t cfg `eq discharger\n\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\nmeta def dsimp (t : expr)\n  (cfg : dsimp_config := {})\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic expr :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   s.dsimplify to_unfold t cfg\n\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\nmeta def binding_names : expr \u2192 list name\n| (pi n _ _ e)  := n :: e.binding_names\n| (lam n _ _ e) := n :: e.binding_names\n| e             := []\n\n/-- head-reduce a single let expression -/\nmeta def reduce_let : expr \u2192 expr\n| (elet _ _ v b) := b.instantiate_var v\n| e              := e\n\n/-- head-reduce all let expressions -/\nmeta def reduce_lets : expr \u2192 expr\n| (elet _ _ v b) := reduce_lets $ b.instantiate_var v\n| e              := e\n\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\nmeta def instantiate_lambdas : list expr \u2192 expr \u2192 expr\n| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')\n| _        e              := e\n\n/-- Repeatedly apply `expr.subst`. -/\nmeta def substs : expr \u2192 list expr \u2192 expr | e es := es.foldl expr.subst e\n\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\nmeta def instantiate_lambdas_or_apps : list expr \u2192 expr \u2192 expr\n| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      e              := mk_app e es\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/-- Get the codomain/target of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def pi_codomain : expr \u2192 expr\n| (pi n bi d b) := pi_codomain b\n| e             := e\n\n/-- Get the body/value of a lambda-expression.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def lambda_body : expr \u2192 expr\n| (lam n bi d b) := lambda_body b\n| e             := e\n\n/-- Auxiliary defintion for `pi_binders`.\n  See note [open expressions]. -/\nmeta def pi_binders_aux : list binder \u2192 expr \u2192 list binder \u00d7 expr\n| es (pi n bi d b) := pi_binders_aux (\u27e8n, bi, d\u27e9::es) b\n| es e             := (es, e)\n\n/-- Get the binders and codomain of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the\n  free variables.\n  See note [open expressions]. -/\nmeta def pi_binders (e : expr) : list binder \u00d7 expr :=\nlet (es, e) := pi_binders_aux [] e in (es.reverse, e)\n\n/-- Auxiliary defintion for `get_app_fn_args`. -/\nmeta def get_app_fn_args_aux : list expr \u2192 expr \u2192 expr \u00d7 list expr\n| r (app f a) := get_app_fn_args_aux (a::r) f\n| r e         := (e, r)\n\n/-- A combination of `get_app_fn` and `get_app_args`: lists both the\n  function and its arguments of an application -/\nmeta def get_app_fn_args : expr \u2192 expr \u00d7 list expr :=\nget_app_fn_args_aux []\n\n/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/\nmeta def drop_pis : list expr \u2192 expr \u2192 tactic expr\n| (v :: vs) (pi n bi d b) := do\n  t \u2190 infer_type v,\n  guard (t =\u2090 d),\n  drop_pis vs (b.instantiate_var v)\n| [] e := return e\n| _  _ := failed\n\n/-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`.\n  Does not check whether the result remains type-correct. -/\nmeta def instantiate_pis : list expr \u2192 expr \u2192 expr\n| (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v)\n| _ e := e\n\n/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.\n  Returns `empty` if the list is empty. -/\nmeta def mk_op_lst (op : expr) (empty : expr) : list expr \u2192 expr\n| []        := empty\n| [e]       := e\n| (e :: es) := op e $ mk_op_lst es\n\n/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 \u2227 (x2 \u2227 ...)`, or `true` if the list is empty. -/\nmeta def mk_and_lst : list expr \u2192 expr := mk_op_lst `(and) `(true)\n\n/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 \u2228 (x2 \u2228 ...)`, or `false` if the list is empty. -/\nmeta def mk_or_lst : list expr \u2192 expr := mk_op_lst `(or) `(false)\n\n/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.\nOtherwise returns `binder_info.default`. -/\nmeta def local_binding_info : expr \u2192 binder_info\n| (expr.local_const _ _ bi _) := bi\n| _ := binder_info.default\n\n/-- `is_default_local e` tests whether `e` is a local constant with binder info\n`binder_info.default` -/\nmeta def is_default_local : expr \u2192 bool\n| (expr.local_const _ _ binder_info.default _) := tt\n| _ := ff\n\n/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/\nmeta def has_local_constant (e l : expr) : bool :=\ne.has_local_in $ mk_name_set.insert l.local_uniq_name\n\n/-- Turns a local constant into a binder -/\nmeta def to_binder : expr \u2192 binder\n| (local_const _ nm bi t) := \u27e8nm, bi, t\u27e9\n| _                       := default binder\n\n/-- Strip-away the context-dependent unique id for the given local const and return: its friendly\n`name`, its `binder_info`, and its `type : expr`. -/\nmeta def get_local_const_kind : expr \u2192 name \u00d7 binder_info \u00d7 expr\n| (expr.local_const _ n bi e) := (n, bi, e)\n| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])\n\n/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/\nmeta def local_const_set_type {elab : bool} : expr elab \u2192 expr elab \u2192 expr elab\n| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t\n| e                           new_t := e\n\n/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to\naccess core `expr` manipulation functions for `pexpr`-based use, but which are restricted to\n`expr tt` at the site of definition unnecessarily.\n\nDANGER: Unless you know exactly what you are doing, this is probably not the function you are\nlooking for. For `pexpr \u2192 expr` see `tactic.to_expr`. For `expr \u2192 pexpr` see `to_pexpr`. -/\nmeta def unsafe_cast {elab\u2081 elab\u2082 : bool} : expr elab\u2081 \u2192 expr elab\u2082 := unchecked_cast\n\n/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr \u00d7 expr)` as\na collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says \"whenever\n`f` is encountered in `e` verbatim, replace it with `t`\". -/\nmeta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr \u00d7 expr)) :\n  expr elab :=\nunsafe_cast $ e.unsafe_cast.replace $ \u03bb e n,\n  (mappings.filter $ \u03bb ent : expr \u00d7 expr, ent.1 = e).head'.map prod.snd\n\n/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of\n    other `expr.local_const`s. It determines whether `e` should be considered \"available in context\"\n    as a variable by virtue of the fact that the variables `vs` have been deemed such.\n\n    For example, given `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that\n    the typeclass instance `prime n` should be included, but `ih : even n` should not.\n\n    DANGER: It is possible that for `f : expr` another `expr.local_const`, we have\n    `is_implicitly_included_variable f vs = ff` but\n    `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to\n    iteratively add a list of local constants (usually, the `variables` declared in the local scope)\n    which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables\n    were added in a particular iteration. The function `all_implicitly_included_variables` below\n    implements this behaviour.\n\n    Note that if `e \u2208 vs` then `is_implicitly_included_variable e vs = tt`. -/\nmeta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=\nif \u00ac(e.local_pp_name.to_string.starts_with \"_\") then\n  e \u2208 vs\nelse e.local_type.fold tt $ \u03bb se _ b,\n  if \u00acb then ff\n  else if \u00acse.is_local_constant then tt\n  else se \u2208 vs\n\n/-- Private work function for `all_implicitly_included_variables`, performing the actual series of\n    iterations, tracking with a boolean whether any updates occured this iteration. -/\nprivate meta def all_implicitly_included_variables_aux\n  : list expr \u2192 list expr \u2192 list expr \u2192 bool \u2192 list expr\n| []          vs rs tt := all_implicitly_included_variables_aux rs vs [] ff\n| []          vs rs ff := vs\n| (e :: rest) vs rs b :=\n  let (vs, rs, b) :=\n    if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in\n  all_implicitly_included_variables_aux rest vs rs b\n\n/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,\n    another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion\n    of the variables in `vs` into the local context implies that `e` should also be included. See\n    `is_implicitly_included_variable e vs` for the details.\n\n    In particular, those elements of `vs` are included automatically. -/\nmeta def all_implicitly_included_variables (es vs : list expr) : list expr :=\nall_implicitly_included_variables_aux es vs [] ff\n\n/-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier.\nThis also works if `x1, ... xn` contain free variables. -/\nprotected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do\n(@const tt n ls, es) \u2190 return e.get_app_fn_args |\n  exceptional.fail \"expression is not a constant applied to arguments\",\nd \u2190 env.get n,\nreturn $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls\n\n/-- Auxilliary function for `head_eta_expand`. -/\nmeta def head_eta_expand_aux : \u2115 \u2192 expr \u2192 expr \u2192 expr\n| (n+1) e (pi x bi d b) :=\n  lam x bi d $ head_eta_expand_aux n e b\n| _ e _ := e\n\n/-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained\n  by its type `t`. -/\nmeta def head_eta_expand (n : \u2115) (e t : expr) : expr :=\n((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t\n\n/-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in\n`dict`. They are expanded until they are applied to one more argument than the maximum in\n`dict.find n`. -/\nprotected meta def eta_expand (env : environment) (dict : name_map $ list \u2115) : expr \u2192 expr\n| e := e.replace $ \u03bb e _, do\n  let (e0, es) := e.get_app_fn_args,\n  let ns := (dict.find e0.const_name).iget,\n  guard (bnot ns.empty),\n  let e' := e0.mk_app $ es.map eta_expand,\n  let needed_n := ns.foldr max 0 + 1,\n  if needed_n \u2264 es.length then some e'\n  else do\n    e'_type \u2190 (e'.simple_infer_type env).to_option,\n    some $ head_eta_expand (needed_n - es.length) e' e'_type\n\n/--\n`e.apply_replacement_fun f test` applies `f` to each identifier\n(inductive type, defined function etc) in an expression, unless\n* The identifier occurs in an application with first argument `arg`; and\n* `test arg` is false.\nHowever, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`\nis tested, instead of the first argument.\n\nReorder contains the information about what arguments to reorder:\ne.g. `g x\u2081 x\u2082 x\u2083 ... x\u2099` becomes `g x\u2082 x\u2081 x\u2083 ... x\u2099` if `reorder.find g = some [1]`.\nWe assume that all functions where we want to reorder arguments are fully applied.\nThis can be done by applying `expr.eta_expand` first.\n-/\nprotected meta def apply_replacement_fun (f : name \u2192 name) (test : expr \u2192 bool)\n  (relevant : name_map \u2115) (reorder : name_map $ list \u2115) : expr \u2192 expr\n| e := e.replace $ \u03bb e _,\n  match e with\n  | const n ls := some $ const (f n) $\n      -- if the first two arguments are reordered, we also reorder the first two universe parameters\n      if 1 \u2208 (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls\n  | app g x :=\n    let f := g.get_app_fn,\n        nm := f.const_name,\n        n_args := g.get_app_num_args in -- this might be inefficient\n    if n_args \u2208 (reorder.find nm).iget \u2227 test g.get_app_args.head then\n    -- interchange `x` and the last argument of `g`\n    some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $\n      apply_replacement_fun g.app_arg else\n    if n_args = (relevant.find nm).lhoare 0 \u2227 f.is_constant \u2227 \u00ac test x then\n      some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else\n      none\n  | _ := none\n  end\n\nend expr\n\n/-! ### Declarations about `environment` -/\n\nnamespace environment\n\n/-- Tests whether `n` is a structure. -/\nmeta def is_structure (env : environment) (n : name) : bool :=\n(env.structure_fields n).is_some\n\n/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a\n  structure. -/\nmeta def structure_fields_full (env : environment) (n : name) : option (list name) :=\n(env.structure_fields n).map (list.map $ \u03bb n', n ++ n')\n\n/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.\n  Note that `is_ginductive` returns `tt` even on regular inductive types.\n  This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive\n  type. -/\nmeta def is_ginductive' (e : environment) (nm : name) : bool :=\ne.is_ginductive nm \u2227 \u00ac e.is_inductive nm\n\n/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list.  -/\nmeta def decl_filter_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 option \u03b1) : list \u03b1 :=\n  e.fold [] $ \u03bb d l, match f d with\n                     | some r := r :: l\n                     | none := l\n                     end\n\n/-- Maps `f` to all declarations in the environment. -/\nmeta def decl_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 \u03b1) : list \u03b1 :=\n  e.decl_filter_map $ \u03bb d, some (f d)\n\n/-- Lists all declarations in the environment -/\nmeta def get_decls (e : environment) : list declaration :=\n  e.decl_map id\n\n/-- Lists all trusted (non-meta) declarations in the environment -/\nmeta def get_trusted_decls (e : environment) : list declaration :=\n  e.decl_filter_map (\u03bb d, if d.is_trusted then some d else none)\n\n/-- Lists the name of all declarations in the environment -/\nmeta def get_decl_names (e : environment) : list name :=\n  e.decl_map declaration.to_name\n\n/-- Fold a monad over all declarations in the environment. -/\nmeta def mfold {\u03b1 : Type} {m : Type \u2192 Type} [monad m] (e : environment) (x : \u03b1)\n  (fn : declaration \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\ne.fold (return x) (\u03bb d t, t >>= fn d)\n\n/-- Filters all declarations in the environment. -/\nmeta def filter (e : environment) (test : declaration \u2192 bool) : list declaration :=\ne.fold [] $ \u03bb d ds, if test d then d::ds else ds\n\n/-- Filters all declarations in the environment. -/\nmeta def mfilter (e : environment) (test : declaration \u2192 tactic bool) : tactic (list declaration) :=\ne.mfold [] $ \u03bb d ds, do b \u2190 test d, return $ if b then d::ds else ds\n\n/-- Checks whether `s` is a prefix of the file where `n` is declared.\n  This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/\nmeta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=\ns.is_prefix_of $ (e.decl_olean n).get_or_else \"\"\n\nend environment\n\n/-!\n### `is_eta_expansion`\n\n In this section we define the tactic `is_eta_expansion` which checks whether an expression\n  is an eta-expansion of a structure. (not to be confused with eta-expanion for `\u03bb`).\n\n-/\n\nnamespace expr\n\n/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have\n  `pr = nm.{univs} args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name \u00d7 expr)) :\n  bool :=\nl.all $ \u03bb\u27e8proj, val\u27e9, val = (const proj univs).mk_app args\n\n/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all\n  elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_test : list (name \u00d7 expr) \u2192 option expr\n| []              := none\n| (\u27e8proj, val\u27e9::l) :=\n  match val.get_app_fn with\n  | (const nm univs : expr) :=\n    if nm = proj then\n      let args := val.get_app_args in\n      let e := args.ilast in\n      if is_eta_expansion_of args univs l then some e else none\n    else\n      none\n  | _                       := none\n  end\n\n/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.\n  Here `l` is intended to consists of the projections and the fields of `val`.\n  This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and\n  afterward checks whether the resulting expression `e` unifies with `val`.\n  This last check is necessary, because `val` and `e` might have different types. -/\nmeta def is_eta_expansion_aux (val : expr) (l : list (name \u00d7 expr)) : tactic (option expr) :=\ndo l' \u2190 l.mfilter (\u03bb\u27e8proj, val\u27e9, bnot <$> is_proof val),\n  match is_eta_expansion_test l' with\n  | some e := option.map (\u03bb _, e) <$> try_core (unify e val)\n  | none   := return none\n  end\n\n/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the\n  eta-expansion of `e`.\n  With eta-expansion we here mean the eta-expansion of a structure, not of a function.\n  For example, the eta-expansion of `x : \u03b1 \u00d7 \u03b2` is `\u27e8x.1, x.2\u27e9`.\n  This assumes that `val` is a fully-applied application of the constructor of a structure.\n\n  This is useful to reduce expressions generated by the notation\n    `{ field_1 := _, ..other_structure }`\n  If `other_structure` is itself a field of the structure, then the elaborator will insert an\n  eta-expanded version of `other_structure`. -/\nmeta def is_eta_expansion (val : expr) : tactic (option expr) := do\n  e \u2190 get_env,\n  type \u2190 infer_type val,\n  projs \u2190 e.structure_fields_full type.get_app_fn.const_name,\n  let args := (val.get_app_args).drop type.get_app_args.length,\n  is_eta_expansion_aux val (projs.zip args)\n\nend expr\n\n/-! ### Declarations about `declaration` -/\n\nnamespace declaration\n\n/--\n`declaration.update_with_fun f test tgt decl`\nsets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and\n`expr.apply_replacement_fun` to the value and type of `decl`.\n-/\nprotected meta def update_with_fun (env : environment) (f : name \u2192 name) (test : expr \u2192 bool)\n  (relevant : name_map \u2115) (reorder : name_map $ list \u2115) (tgt : name) (decl : declaration) :\n  declaration :=\nlet decl := decl.update_name $ tgt in\nlet decl := decl.update_type $\n  (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in\ndecl.update_value $\n  (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder\n\n/-- Checks whether the declaration is declared in the current file.\n  This is a simple wrapper around `environment.in_current_file`\n  Use `environment.in_current_file` instead if performance matters. -/\nmeta def in_current_file (d : declaration) : tactic bool :=\ndo e \u2190 get_env, return $ e.in_current_file d.to_name\n\n/-- Checks whether a declaration is a theorem -/\nmeta def is_theorem : declaration \u2192 bool\n| (thm _ _ _ _) := tt\n| _             := ff\n\n/-- Checks whether a declaration is a constant -/\nmeta def is_constant : declaration \u2192 bool\n| (cnst _ _ _ _) := tt\n| _              := ff\n\n/-- Checks whether a declaration is a axiom -/\nmeta def is_axiom : declaration \u2192 bool\n| (ax _ _ _) := tt\n| _          := ff\n\n/-- Checks whether a declaration is automatically generated in the environment.\n  There is no cheap way to check whether a declaration in the namespace of a generalized\n  inductive type is automatically generated, so for now we say that all of them are automatically\n  generated. -/\nmeta def is_auto_generated (e : environment) (d : declaration) : bool :=\ne.is_constructor d.to_name \u2228\n(e.is_projection d.to_name).is_some \u2228\n(e.is_constructor d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"inj\", \"inj_eq\", \"sizeof_spec\", \"inj_arrow\"]) \u2228\n(e.is_inductive d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"below\", \"binduction_on\", \"brec_on\", \"cases_on\", \"dcases_on\", \"drec_on\", \"drec\",\n  \"rec\", \"rec_on\", \"no_confusion\", \"no_confusion_type\", \"sizeof\", \"ibelow\", \"has_sizeof_inst\"]) \u2228\nd.to_name.has_prefix (\u03bb nm, e.is_ginductive' nm)\n\n/--\nReturns true iff `d` is an automatically-generated or internal declaration.\n-/\nmeta def is_auto_or_internal (env : environment) (d : declaration) : bool :=\nd.to_name.is_internal || d.is_auto_generated env\n\n/-- Returns the list of universe levels of a declaration. -/\nmeta def univ_levels (d : declaration) : list level :=\nd.univ_params.map level.param\n\n/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/\nprotected meta def reducibility_hints : declaration \u2192 reducibility_hints\n| (declaration.defn _ _ _ _ red _) := red\n| _ := _root_.reducibility_hints.opaque\n\n/-- formats the arguments of a `declaration.thm` -/\nprivate meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body.get,\n   return $ \"<theorem \" ++ to_fmt nm ++ \" : \" ++ tp ++ \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.defn` -/\nprivate meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :\n  tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body,\n   return $ \"<\" ++ (if is_trusted then \"def \" else \"meta def \") ++ to_fmt nm ++ \" : \" ++ tp ++\n     \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.cnst` -/\nprivate meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<\" ++ (if is_trusted then \"constant \" else \"meta constant \") ++ to_fmt nm ++ \" : \"\n     ++ tp ++ \">\"\n\n/-- formats the arguments of a `declaration.ax` -/\nprivate meta def print_ax (nm : name) (tp : expr) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<axiom \" ++ to_fmt nm ++ \" : \" ++ tp ++ \">\"\n\n/-- pretty-prints a `declaration` object. -/\nmeta def to_tactic_format : declaration \u2192 tactic format\n| (declaration.thm nm _ tp bd) := print_thm nm tp bd\n| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted\n| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted\n| (declaration.ax nm _ tp) := print_ax nm tp\n\nmeta instance : has_to_tactic_format declaration :=\n\u27e8to_tactic_format\u27e9\n\nend declaration\n\nmeta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=\nunchecked_cast\nexpr.has_decidable_eq\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/meta/expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766828768970435, "lm_q2_score": 0.0715912034062289, "lm_q1q2_score": 0.023458167033764354}}
{"text": "import fo.basic\nimport tactic\n\nopen signature\n\n\ndef signature.substitution.domain {\u03c3 : signature} (\u03bd : \u03c3.substitution) :=\n  subtype {v : \u03c3.var | \u03bd v \u2260 (term.var v)}\n\n\n@[simp]\ndef signature.substitution.is_ground {\u03c3 : signature} (\u03bd : \u03c3.substitution) :=\n  \u2200 v, (\u03bd v).is_ground\n\ndef signature.ground_substitution (\u03c3 : signature) : Type :=\n  subtype {\u03bd : \u03c3.substitution | \u03bd.is_ground}\n\ndef signature.variable_renaming (\u03c3 : signature) (r : \u03c3.var \u2192 \u03c3.var) (h : function.bijective r) : \u03c3.substitution :=\n  (\u03bb v, term.var (r v))\n\ndef signature.substitution.free {\u03c3 : signature} : \u03c3.substitution \u2192 \u03c3.var \u2192 \u03c3.substitution :=\n  (\u03bb \u03bd v v',\n      if (v = v') then\n        term.var v\n      else\n        (\u03bd v)\n  )\n\n@[reducible]\ndef signature.term.substitute {\u03c3 : signature} : \u03c3.term \u2192 \u03c3.substitution \u2192 \u03c3.term \n  | (term.var v) \u03bd := (\u03bd v)\n  | (term.func f ts) \u03bd := term.func f (\u03bb i, (ts i).substitute \u03bd)\n\n@[reducible]\ninstance signature.subst_term {\u03c3 : signature} : \u03c3.substitutable \u03c3.term :=\n  {substitute := signature.term.substitute}\n\n@[reducible]\ndef signature.substitution.substitute {\u03c3 : signature} (\u03c1 \u03bd : \u03c3.substitution) : \u03c3.substitution :=\n  (\u03bb v : \u03c3.var, (\u03c1 v) \u2193 \u03bd)\n\n@[reducible]\ninstance signature.subst_substitution {\u03c3 : signature} : \u03c3.substitutable \u03c3.substitution :=\n  {\n    substitute := signature.substitution.substitute\n  }\n\n@[reducible]\ndef signature.var.occurrs {\u03c3 : signature} : \u03c3.var \u2192 \u03c3.term \u2192 Prop \n  | v (term.var v') := v = v'\n  | v (term.func f ts) := \u2203 i, v.occurrs (ts i)\n\ndef signature.var.is_bound {\u03c3 : signature} (v : \u03c3.var) (\u03c6 : \u03c3.formula) : Prop :=\n  \u00ac\u03c6.is_free v\n\n@[simp]\ndef signature.formula.substitute {\u03c3 : signature} : \u03c3.formula \u2192 \u03c3.substitution \u2192 \u03c3.formula\n  | (formula.neg \u03c6) \u03bd := \u03c6.substitute \u03bd\n  | (formula.conj hn \u03a6) \u03bd := formula.conj hn (\u03bb i, (\u03a6 i).substitute \u03bd)\n  | (formula.disj hn \u03a6) \u03bd := formula.disj hn (\u03bb i, (\u03a6 i).substitute \u03bd)\n  | (formula.fall x \u03c6) \u03bd := formula.fall x (\u03c6.substitute (\u03bd.free x))\n  | (formula.xist x \u03c6) \u03bd := formula.xist x (\u03c6.substitute (\u03bd.free x))\n  | (formula.rel r ts) \u03bd := formula.rel r (\u03bb i, (ts i).substitute \u03bd)\n  | \u03c6 \u03bd := \u03c6\n\n@[reducible]\ninstance signature.sub_formula {\u03c3 : signature} : \u03c3.substitutable \u03c3.formula :=\n  {\n    substitute := signature.formula.substitute\n  }\n\ndef signature.term.contains {\u03c3 : signature} : \u03c3.term \u2192 \u03c3.var \u2192 Prop \n  | (term.var v') v := v' = v\n  | (term.func f ts) v := \u2203 i, (ts i).contains v\n  \n@[reducible]\ndef signature.formula.contains {\u03c3 : signature} : \u03c3.formula \u2192 \u03c3.var \u2192 Prop \n  | (formula.neg \u03c6) v := \u03c6.contains v\n  | (formula.conj hn \u03a6) v := \u2203 i, (\u03a6 i).contains v\n  | (formula.disj hn \u03a6) v := \u2203 i, (\u03a6 i).contains v\n  | (formula.fall x \u03c6) v := \u03c6.contains v\n  | (formula.xist x \u03c6) v := \u03c6.contains v\n  | (formula.rel r ts) v := (\u2203 i, v.occurrs (ts i))\n  | \u03c6 v := false\n\n@[reducible]\ndef signature.substitution.is_free {\u03c3 : signature} : \u03c3.substitution \u2192 \u03c3.formula \u2192 Prop \n  | \u03bd (formula.neg \u03c6) := \u03bd.is_free \u03c6\n  | \u03bd (formula.conj hn \u03a6) := \u2200 i, \u03bd.is_free (\u03a6 i)\n  | \u03bd (formula.disj hn \u03a6) := \u2200 i, \u03bd.is_free (\u03a6 i)\n  | \u03bd (formula.fall x \u03c6) := (\u2200 v : \u03c3.var, (\u03c6.contains v \u2192 \u03c6.is_free v \u2192 \u00ac(\u03bd v).contains x)) \u2227 \u03bd.is_free \u03c6\n  | \u03bd (formula.xist x \u03c6) := (\u2200 v : \u03c3.var, (\u03c6.contains v \u2192 \u03c6.is_free v \u2192 \u00ac(\u03bd v).contains x)) \u2227 \u03bd.is_free \u03c6\n  | \u03bd \u03c6 := true\n\n\n@[reducible]\ndef signature.substitution.is_free1 {\u03c3 : signature} (\u03bd : \u03c3.substitution) (\u03c6 : \u03c3.formula) : Prop :=\n  \u2200 (v : \u03c3.var), (\u03c6.is_free v) \u2192 \u2200 (v' : \u03c3.var), v'.occurrs (\u03bd v) \u2192 \u03c6.is_free v'\n \ndef signature.substitution.compose {\u03c3 : signature} (\u03bd\u2081 : \u03c3.substitution) (\u03bd\u2082 : \u03c3.substitution) : \u03c3.substitution :=\n  (\u03bb v, (\u03bd\u2081 v).substitute \u03bd\u2082)\n\ndef signature.substitution.id {\u03c3 : signature} : \u03c3.substitution :=\n  (\u03bb v, term.var v)\n\ndef signature.id_subst (\u03c3 : signature) : \u03c3.substitution :=\n  (\u03bb v : \u03c3.var, term.var v)\n\ndef subid {\u03c3 : signature} : \u03c3.substitution := \n  (\u03bb v : \u03c3.var, term.var v)\n\nlemma signature.term.term_eq_term_subst_id {\u03c3 : signature} : \u2200 t : \u03c3.term, t \u2193 \u03c3.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 {\u03c3 : signature} (t\u2081 t\u2082 : \u03c3.term) : Prop :=\n  \u2203 (\u03bd : \u03c3.substitution), t\u2081 \u2193 \u03bd = t\u2082\n\n\nsection more_general_preorder\n\n  variable \u03c3 : signature\n  variable t : \u03c3.term\n  variable \u03bd\u2081 : \u03c3.substitution\n  variable \u03bd\u2082 : \u03c3.substitution\n\n  lemma signature.compose_sub : ((t \u2193 \u03bd\u2081) \u2193 \u03bd\u2082) = t \u2193 (\u03bd\u2081 \u2193 \u03bd\u2082) :=\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 \u03c3)) :=\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 \u03c3)) :=\n    begin\n      intros x y z hxy hyz,\n      cases hxy with \u03bdx h\u03bdx,\n      cases hyz with \u03bdy h\u03bdy,\n      rw [\u2190 h\u03bdy, \u2190 h\u03bdx],\n      use (\u03bdx \u2193 \u03bdy),\n      rw signature.compose_sub,\n    end\n\nend more_general_preorder\n\n\nsection\n\n  variable \u03c3 : signature\n  variable t : \u03c3.term\n  variable \u03c6 : \u03c3.formula\n  variable \u03bd\u2081 : \u03c3.substitution\n  variable \u03bd\u2082 : \u03c3.substitution\n\n  lemma signature.compose_free (h : \u03bd\u2081.is_free \u03c6) : \u2200 v, (\u03c6 \u2193 (\u03bd\u2081.free v \u2193 \u03bd\u2082.free v)) = (\u03c6 \u2193 (\u03bd\u2081 \u2193 \u03bd\u2082).free v) :=\n    begin\n      sorry,\n    end\n\n  lemma signature.sub_free_eq_imp_sub_eq (h : \u03bd\u2081.is_free \u03c6) : \u2200 v, (\u03c6 \u2193 \u03bd\u2081) \u2193 \u03bd\u2082 = \u03c6 \u2193 (\u03bd\u2081 \u2193 \u03bd\u2082) \u2192 (\u03c6 \u2193 \u03bd\u2081.free v \u2193 \u03bd\u2082.free v) = (\u03c6 \u2193 (\u03bd\u2081.free v \u2193 \u03bd\u2082.free v)) :=\n    begin\n      intro v,\n      intro h',\n      induction \u03c6,\n      simp,\n      simp,\n      simp,\n      {\n        exact (\u03c6_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 \u03c6_ih,\n        exact \u03c6_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 : \u03bd\u2081.is_free \u03c6) : (\u03c6 \u2193 \u03bd\u2081) \u2193 \u03bd\u2082 = \u03c6 \u2193 (\u03bd\u2081 \u2193 \u03bd\u2082) :=\n    begin\n      induction \u03c6,\n      refl,refl,\n      {\n        simp [signature.formula.substitute],\n        exact \u03c6_ih h,\n      },\n      {\n        simp [signature.formula.substitute],\n        ext i,\n        dsimp at *,\n        have h' := \u03c6_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' := \u03c6_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 \u03c3 \u03c6_f \u03bd\u2081 \u03bd\u2082 (h.right) \u03c6_v,\n        simp [signature.formula.substitute] at h',\n        rw \u2190 h',\n        apply signature.sub_free_eq_imp_sub_eq,\n        exact h.right,\n        exact \u03c6_ih h.right,\n      },\n      {\n        simp [signature.formula.substitute],\n        simp [signature.substitution.is_free] at h,\n        have h' := signature.compose_free \u03c3 \u03c6_f \u03bd\u2081 \u03bd\u2082 (h.right) \u03c6_v,\n        simp [signature.formula.substitute] at h',\n        rw \u2190 h',\n        apply signature.sub_free_eq_imp_sub_eq,\n        exact h.right,\n        exact \u03c6_ih h.right,\n      },\n      {\n        simp [signature.formula.substitute],\n        ext i,\n        exact signature.compose_sub \u03c3 (\u03c6_ts i) _ _,\n      },\n    end\n\nend\n\n\n\n\ndef signature.term.equivalent {\u03c3 : signature} (t\u2081 t\u2082 : \u03c3.term) : Prop :=\n  t\u2081.more_general t\u2082 \u2227 t\u2082.more_general t\u2081\n\n\nlemma signature.term.refl_equivalent {\u03c3 : signature} : reflexive (@signature.term.equivalent \u03c3) :=\n  begin \n    intro t,\n    use \u03c3.id_subst,\n    rw signature.term.term_eq_term_subst_id,\n    use \u03c3.id_subst,\n    rw signature.term.term_eq_term_subst_id,\n  end\n\nlemma signature.term.trans_equivalent {\u03c3 : signature} : transitive (@signature.term.equivalent \u03c3) :=\n  begin \n    intros x y z hxy hyz,\n    split,\n    {\n      cases hxy.left with \u03bdxy h\u2081,\n      cases hyz.left with \u03bdyz h\u2082,\n      use (\u03bdxy \u2193 \u03bdyz),\n      rw \u2190 signature.compose_sub,\n      rw [h\u2081, h\u2082],\n    },\n    {\n      cases hxy.right with \u03bdxy h\u2081,\n      cases hyz.right with \u03bdyz h\u2082,\n      use (\u03bdyz \u2193 \u03bdxy),\n      rw \u2190 signature.compose_sub,\n      rw [h\u2082, h\u2081],\n    }\n  end\n\nlemma signature.term.symm_equivalent {\u03c3 : signature} : symmetric (@signature.term.equivalent \u03c3) :=\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 {\u03c3 : signature} : equivalence (@signature.term.equivalent \u03c3) :=\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 (\u03c3 : signature) : setoid \u03c3.term :=\n  {\n    r := signature.term.equivalent,\n    iseqv := signature.term.equiv_equivalent,\n  }\n\n@[reducible]\ndef signature.term_equiv (\u03c3 : signature) := quotient \u03c3.equiv_setoid\n\n\n\nexample (\u03c3 : signature) (t : \u03c3.term) : \u27e6t\u27e7 = quotient.mk t :=\n  begin\n    refl,\n  end \n\nlemma signature.term.substitution_is_well_defined {\u03c3 : signature} (\u03bd : \u03c3.substitution) (t\u2081 t\u2082 : \u03c3.term)  (h : t\u2081 \u2248 t\u2082) : \u27e6t\u2081 \u2193 \u03bd\u27e7 = \u27e6t\u2082 \u2193 \u03bd\u27e7 :=\n  begin\n    apply quotient.sound,\n    cases h,\n    split,\n    cases h_left with \u03bd_left h\u03bd_left,\n    cases h_right with \u03bd_right h\u03bd_right,\n    sorry, sorry,\n  end\n\ndef signature.term_equiv.substitute {\u03c3 : signature} (\u03bd : \u03c3.substitution) : \u03c3.term_equiv \u2192 \u03c3.term_equiv := \n  quotient.lift (\u03bb (t : \u03c3.term) , \u27e6t \u2193 \u03bd\u27e7) (signature.term.substitution_is_well_defined \u03bd)\n\n@[reducible]\ninstance signature.subst_term_equiv (\u03c3 : signature) : \u03c3.substitutable \u03c3.term_equiv :=\n  {\n    substitute := (\u03bb t \u03bd, signature.term_equiv.substitute \u03bd 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 (\u03b1 : Type)\n  | default (val : \u03b1)\n  | alt (name : String) (val : \u03b1)\n\ninductive Code where\n  | cases (alt: AltCore Code)\n  | return (id : Nat)\n\nabbrev Alt := AltCore Code\n\ndef AltCore.getCode : Alt \u2192 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 \u2192 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 : \u2115`. We prove that the obvious inclusion functor `Fintype.skeleton \u2964 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 \u21a5X := category_theory.bundled.str X\n\nprotected instance category_theory.category : category_theory.category Fintype :=\n  category_theory.induced_category.category category_theory.bundled.\u03b1\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.\u03b1)\n    (y : category_theory.induced_category (Type u_1) category_theory.bundled.\u03b1) (f : x \u27f6 y) :\n    \u2200 (\u1fb0 : category_theory.bundled.\u03b1 x), category_theory.functor.map incl f \u1fb0 = f \u1fb0 :=\n  fun (\u1fb0 : category_theory.bundled.\u03b1 x) => Eq.refl (f \u1fb0)\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 : \u2115`. We parameterize the objects of `Fintype.skeleton` directly as `\u2115`,\nas the type `fin m \u2243 fin n` is nonempty if and only if `n = m`.\n-/\ndef skeleton := \u2115\n\nnamespace skeleton\n\n\n/-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/\ndef mk : \u2115 \u2192 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 \u2192 \u2115 := 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 \u2964 Fintype :=\n  category_theory.functor.mk (fun (X : skeleton) => of (fin X))\n    fun (_x _x_1 : skeleton) (f : _x \u27f6 _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 \u27f6 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 : \u21a5X \u2243 fin (fintype.card \u21a5X) := trunc.out (fintype.equiv_fin \u21a5X);\n      Exists.intro (fintype.card \u21a5X) (Nonempty.intro (category_theory.iso.mk \u21d1(equiv.symm F) \u21d1F))\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 \u224c Fintype := category_theory.functor.as_equivalence incl\n\n@[simp] theorem incl_mk_nat_card (n : \u2115) :\n    fintype.card \u21a5(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 \u00d7 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 \u2194 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 \u2192 simp_lemmas \u2192 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 \u2192 List Name \u2192 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 \u2192 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 `\u03a0 (h\u2081 : _) ... (h\u2099 : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`).\n- Any of the hypotheses `h\u1d62` 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\u1d62`.\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 \u2227 b` to `c \u2227 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 \u2194 c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ...\nlemma imp_congr_right (h : a \u2192 (b \u2194 c)) : (a \u2192 b) \u2194 (a \u2192 c) := ...\nlemma and_congr (h\u2081 : a \u2194 c) (h\u2082 : b \u2194 d) : (a \u2227 b) \u2194 (c \u2227 d) := ...\n```\n-/\nunsafe axiom simp_lemmas.add_congr : simp_lemmas \u2192 Name \u2192 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 \u00d7 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 \u00d7 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 \u00d7 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 \u2192 tactic Bool\n#align is_valid_simp_lemma_cnst is_valid_simp_lemma_cnst\n\nunsafe axiom is_valid_simp_lemma : expr \u2192 tactic Bool\n#align is_valid_simp_lemma is_valid_simp_lemma\n\nunsafe axiom simp_lemmas.pp : simp_lemmas \u2192 tactic format\n#align simp_lemmas.pp simp_lemmas.pp\n\nunsafe instance : has_to_tactic_format simp_lemmas :=\n  \u27e8simp_lemmas.pp\u27e9\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 \u2192 tactic expr) (h : expr) : tactic Unit := do\n  let num_reverted : \u2115 \u2190 revert h\n  let t \u2190 target\n  match t with\n    | expr.pi n bi d b => do\n      let h_simp \u2190 transform d\n      unsafe_change <| expr.pi n bi h_simp b\n    | expr.elet n g e f => do\n      let h_simp \u2190 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 \u2190 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: `(\u03bb x, F $ x) \u219d F`\n  zeta : Bool := true\n  -- do zeta-reductions: `let x : a := b in c \u219d c[x/b]`.\n  beta : Bool := true\n  -- do beta-reductions: `(\u03bb x, E) $ (y) \u219d E[x/y]`.\n  proj : Bool := true\n  -- reduce projections: `\u27e8a,b\u27e9.1 \u219d a`.\n  iota : Bool := true\n  -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R \u219d 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    {\u03b1 : Type}\n    -- Initial user data\n    (a : \u03b1)\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 : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 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 : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 Bool))\n    (e : expr) (cfg : DsimpConfig := { }) : tactic (\u03b1 \u00d7 expr)\n#align tactic.dsimplify_core tactic.dsimplify_core\n\nunsafe def dsimplify (pre : expr \u2192 tactic (expr \u00d7 Bool)) (post : expr \u2192 tactic (expr \u00d7 Bool)) :\n    expr \u2192 tactic expr := fun e => do\n  let (a, new_e) \u2190\n    dsimplify_core ()\n        (fun u e => do\n          let r \u2190 pre e\n          return (u, r))\n        (fun u e => do\n          let r \u2190 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 \u2192 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 \u2190 get_simp_lemmas_or_default s\n  let t \u2190 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 \u2190 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 \u2190 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 \u00d7 expr \u00d7 Bool) := do\n    guard (is_delta_target e cs)\n    let expr.const f_name f_lvls \u2190 return e.get_app_fn\n    let env \u2190 get_env\n    let decl \u2190 env.get f_name\n    let new_f \u2190 decl.instantiate_value_univ_params f_lvls\n    let new_e \u2190 head_beta (expr.mk_app new_f e.get_app_args)\n    return (u, new_e, tt)\n  do\n  let (c, new_e) \u2190\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 \u2190 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 \u00d7 expr \u00d7 Bool) := do\n    let new_e \u2190 unfold_proj e cfg.md\n    return (tt, new_e, tt)\n  do\n  let (tt, new_e) \u2190 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 \u2190 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 \u00d7 expr \u00d7 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 \u2190 target >>= instantiate_mvars\n  let (new_t, pr, lms) \u2190 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 \u00d7 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 \u2190 infer_type h\n  let (h_new_type, pr, lms) \u2190 simplify s to_unfold htype cfg `eq discharger\n  let new_hyp \u2190 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 : \u03b1` - 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 : \u03b1 \u2192 tactic \u03b1` - tactic for dischaging hypothesis in conditional rewriting rules. The argument '\u03b1' 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 `\u2194`.\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 {\u03b1 : Type} (a : \u03b1) (c : SimpConfig) (s : simp_lemmas)\n    (discharger : \u03b1 \u2192 tactic \u03b1)\n    (pre : \u03b1 \u2192 simp_lemmas \u2192 Name \u2192 Option expr \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 Option expr \u00d7 Bool))\n    (post : \u03b1 \u2192 simp_lemmas \u2192 Name \u2192 Option expr \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 Option expr \u00d7 Bool))\n    (r : Name) : expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr)\n#align tactic.ext_simplify_core tactic.ext_simplify_core\n\nprivate unsafe def is_equation : expr \u2192 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 \u2192 List Name \u2192 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 \u2192 Bool \u2192 List Name \u2192 tactic simp_lemmas\n  | S, tt, [] => try (simp_target S to_unfold cfg) >> return S\n  | S, use_ns, ns => do\n    let t \u2190 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 \u2190 return t\n              let (new_d, h_d_eq_new_d, lms) \u2190 simplify S to_unfold d cfg\n              let h_d \u2190 intro1_aux use_ns ns\n              let h_new_d \u2190 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 \u2190 intro1\n              let new_S \u2190\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 \u2190 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 \u2227 \u00acns 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 \u2192 tactic (expr \u00d7 expr)) : tactic Unit := do\n  let (lhs, rhs) \u2190 target >>= match_eq\n  let (new_rhs, HEq) \u2190 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 \u2192 List Name \u2192 tactic simp_lemmas\n  | S, [] => return S\n  | S, n :: ns => do\n    let S' \u2190 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 \u2190 tactic.to_simp_lemmas simp_lemmas.mk ns\n                let s \u2190\n                  attr_deps.foldlM\n                      (fun s attr_name => do\n                        let ns \u2190 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 \u2192 List Name \u2192 tactic simp_lemmas\n  | S, [] => return S\n  | S, attr_name :: R => do\n    let S' \u2190 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 \u2190 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 {\u03b1} (a : \u03b1) (pre : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr)) (e : expr)\n    (cfg : SimpConfig := { }) : tactic (\u03b1 \u00d7 expr \u00d7 expr) :=\n  ext_simplify_core a cfg simp_lemmas.mk (fun _ => failed)\n    (fun a _ _ _ e => do\n      let (new_a, new_e, pr) \u2190 pre a e\n      guard \u00acnew_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 \u2192 tactic (expr \u00d7 expr)) (cfg : SimpConfig := { }) :\n    tactic Unit := do\n  let t \u2190 target\n  let (_, new_target, pr) \u2190\n    simplify_top_down ()\n        (fun _ e => do\n          let (new_e, pr) \u2190 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 {\u03b1} (a : \u03b1) (post : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr)) (e : expr)\n    (cfg : SimpConfig := { }) : tactic (\u03b1 \u00d7 expr \u00d7 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) \u2190 post a e\n      guard \u00acnew_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 \u2192 tactic (expr \u00d7 expr)) (cfg : SimpConfig := { }) :\n    tactic Unit := do\n  let t \u2190 target\n  let (_, new_target, pr) \u2190\n    simplify_bottom_up ()\n        (fun _ e => do\n          let (new_e, pr) \u2190 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\u2093 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 \u2190 local_context\n  let s \u2190\n    ctx.foldlM\n        (fun s h => do\n          let h_type \u2190 infer_type h\n          let s := remove_deps s h_type\n          let h_val \u2190 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 \u2190 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 \u2190 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 \u2192 simp_lemmas \u2192 List simp_all_entry \u2192 tactic (simp_lemmas \u00d7 List simp_all_entry)\n  | [], s, r => return (s, r)\n  | h :: hs, s, r => do\n    let new_r \u2190 update_simp_lemmas r h\n    let new_s \u2190 s.add h false\n    let h_type \u2190 infer_type h\n    init_aux hs new_s (\u27e8h, h_type, none, s\u27e9 :: 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 \u00d7 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 \u2260 none) (try (clear e.h))\n#align tactic.clear_old_hyps tactic.clear_old_hyps\n\nprivate unsafe def join_pr : Option expr \u2192 expr \u2192 tactic expr\n  | none, pr\u2082 => return pr\u2082\n  | some pr\u2081, pr\u2082 => mk_eq_trans pr\u2081 pr\u2082\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 \u2192 List simp_all_entry \u2192 simp_lemmas \u2192 Bool \u2192 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) \u2190\n        (simp_target s to_unfold cfg discharger >>= fun ns => return (ns, true)) <|>\n            return (mk_name_set, false)\n      guard (cfg = ff \u2228 target_changed \u2228 r fun e => e \u2260 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 \u27e8h, h_type, h_pr, s'\u27e9 := e\n    let (new_h_type, new_pr, lms) \u2190\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 \u2190 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 \u2190 join_pr h_pr new_pr\n        let new_fact_pr \u2190 mk_eq_mp new_pr h\n        if new_h_type = q(False) then do\n            let tgt \u2190 target\n            to_expr ``(@False.ndrec $(tgt) $(new_fact_pr)) >>= exact\n            return mk_name_set\n          else do\n            let h0_type \u2190 infer_type h\n            let new_fact_pr := mk_tagged_proof new_h_type new_fact_pr `` id_tag.simp\n            let new_es \u2190 update_simp_lemmas es new_fact_pr\n            let new_r \u2190 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 \u2190 s new_fact_pr ff\n            let new_lms \u2190 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 \u2190 non_dep_prop_hyps\n  let (s, es) \u2190 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 \u2192 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": "/-\nCopyright (c) 2019 Bruno Bentzen. All rights reserved.\nReleased under the Apache License 2.0 (see \"License\");\nAuthor: Bruno Bentzen\n-/\n\nimport ..core.interval\n\nopen interval\n\n-- degeneracy maps (weakening) for types and terms\n\nexample {A : Type} : I \u2192 Type := \u03bb _, A\n\nexample {A : Type} (a : A) : (I \u2192 A) := \u03bb _, a", "meta": {"author": "bbentzen", "repo": "cubicalean", "sha": "3b94cd2aefdfc2163c263bd3fc6f2086fef814b5", "save_path": "github-repos/lean/bbentzen-cubicalean", "path": "github-repos/lean/bbentzen-cubicalean/cubicalean-3b94cd2aefdfc2163c263bd3fc6f2086fef814b5/src/examples/degeneracy.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.061875983128724096, "lm_q1q2_score": 0.023360700052961262}}
{"text": "namespace Ex\n\nclass Get (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where\n  get (xs : Cont) (i : Idx) : Elem\n\nexport Get (get)\n\ninstance [Inhabited \u03b1] : Get (Array \u03b1) Nat \u03b1 where\n  get xs i := xs.get! i\n\nexample (as : Array (Nat \u00d7 Bool)) : Bool :=\n  (get as 0).2\n\nexample (as : Array (Nat \u00d7 Bool)) : Bool :=\n  let r1 (as : _) := (get as 0).2\n  r1 as\n\nend Ex\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/dotNotationAndDefaultInstance.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.06278920465107113, "lm_q1q2_score": 0.023246157942707443}}
{"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.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Util.ReplaceExpr\n\nnamespace Lean.Compiler\nnamespace CSimp\n\nstructure Entry where\n  fromDeclName : Name\n  toDeclName   : Name\n  deriving Inhabited\n\nabbrev State := SMap Name Name\n\nbuiltin_initialize ext : SimpleScopedEnvExtension Entry State \u2190\n  registerSimpleScopedEnvExtension {\n    name           := `csimp\n    initial        := {}\n    addEntry       := fun s { fromDeclName, toDeclName } => s.insert fromDeclName toDeclName\n    finalizeImport := fun s => s.switch\n  }\n\nprivate def isConstantReplacement? (declName : Name) : CoreM (Option Entry) := do\n  let info \u2190 getConstInfo declName\n  match info.type.eq? with\n  | some (_, Expr.const fromDeclName us .., Expr.const toDeclName vs ..) =>\n    if us == vs then\n      return some { fromDeclName, toDeclName }\n    else\n      return none\n  | _ => return none\n\ndef add (declName : Name) (kind : AttributeKind) : CoreM Unit := do\n  if let some entry \u2190 isConstantReplacement? declName then\n    ext.add entry kind\n  else\n    throwError \"invalid 'csimp' theorem, only constant replacement theorems (e.g., `@f = @g`) are currently supported.\"\n\nbuiltin_initialize\n  registerBuiltinAttribute {\n    name  := `csimp\n    descr := \"simplification theorem for the compiler\"\n    add   := fun declName stx attrKind => do\n      Attribute.Builtin.ensureNoArgs stx\n      discard <| add declName attrKind\n  }\n\n@[export lean_csimp_replace_constants]\ndef replaceConstants (env : Environment) (e : Expr) : Expr :=\n  let map := ext.getState env\n  e.replace fun e =>\n    if e.isConst then\n      match map.find? e.constName! with\n      | some declNameNew => some (mkConst declNameNew e.constLevels!)\n      | none => none\n    else\n      none\n\nend CSimp\nend Lean.Compiler\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/CSimpAttr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.05261895409053963, "lm_q1q2_score": 0.023240371608097582}}
{"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.Tactic.Rewrite\nimport Lean.Meta.Tactic.Split\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Eqns\n\nnamespace Lean.Elab.WF\nopen Meta\nopen Eqns\n\nstructure EqnInfo extends EqnInfoCore where\n  declNames       : Array Name\n  declNameNonRec  : Name\n  fixedPrefixSize : Nat\n  deriving Inhabited\n\nprivate partial def deltaLHSUntilFix (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do\n  let target \u2190 mvarId.getType'\n  let some (_, lhs, _) := target.eq? | throwTacticEx `deltaLHSUntilFix mvarId \"equality expected\"\n  if lhs.isAppOf ``WellFounded.fix then\n    return mvarId\n  else\n    deltaLHSUntilFix (\u2190 deltaLHS mvarId)\n\nprivate def rwFixEq (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do\n  let target \u2190 mvarId.getType'\n  let some (_, lhs, rhs) := target.eq? | unreachable!\n  let h := mkAppN (mkConst ``WellFounded.fix_eq lhs.getAppFn.constLevels!) lhs.getAppArgs\n  let some (_, _, lhsNew) := (\u2190 inferType h).eq? | unreachable!\n  let targetNew \u2190 mkEq lhsNew rhs\n  let mvarNew \u2190 mkFreshExprSyntheticOpaqueMVar targetNew\n  mvarId.assign (\u2190 mkEqTrans h mvarNew)\n  return mvarNew.mvarId!\n\nprivate def hasWellFoundedFix (e : Expr) : Bool :=\n  Option.isSome <| e.find? (\u00b7.isConstOf ``WellFounded.fix)\n\n/--\n  Helper function for decoding the packed argument for a `WellFounded.fix` application.\n  Recall that we use `PSum` and `PSigma` for packing the arguments of mutually recursive nary functions.\n-/\nprivate partial def decodePackedArg? (info : EqnInfo) (e : Expr) : Option (Name \u00d7 Array Expr) := do\n  if info.declNames.size == 1 then\n    let args := decodePSigma e #[]\n    return (info.declNames[0]!, args)\n  else\n    decodePSum? e 0\nwhere\n  decodePSum? (e : Expr) (i : Nat) : Option (Name \u00d7 Array Expr) := do\n    if e.isAppOfArity ``PSum.inl 3 then\n      decodePSum? e.appArg! i\n    else if e.isAppOfArity ``PSum.inr 3 then\n      decodePSum? e.appArg! (i+1)\n    else\n      guard (i < info.declNames.size)\n      return (info.declNames[i]!, decodePSigma e #[])\n\n  decodePSigma (e : Expr) (acc : Array Expr) : Array Expr :=\n    /- TODO: check arity of the given function. If it takes a PSigma as the last argument,\n       this function will produce incorrect results. -/\n    if e.isAppOfArity ``PSigma.mk 4 then\n       decodePSigma e.appArg! (acc.push e.appFn!.appArg!)\n    else\n       acc.push e\n\n/--\n  Try to fold `WellFounded.fix` applications that represent recursive applications of the functions in `info.declNames`.\n  We need that to make sure `simpMatchWF?` succeeds at goals such as\n  ```lean\n  ...\n  h : g x = 0\n  ...\n  |- (match (WellFounded.fix ...) with | ...) = ...\n  ```\n  where `WellFounded.fix ...` can be folded back to `g x`.\n-/\nprivate def tryToFoldWellFoundedFix (info : EqnInfo) (us : List Level) (fixedPrefix : Array Expr) (e : Expr) : MetaM Expr := do\n  if hasWellFoundedFix e then\n    transform e (pre := pre)\n  else\n    return e\nwhere\n  pre (e : Expr) : MetaM TransformStep := do\n    let e' := e.headBeta\n    if e'.isAppOf ``WellFounded.fix && e'.getAppNumArgs >= 6 then\n      let args := e'.getAppArgs\n      let packedArg := args[5]!\n      let extraArgs := args[6:]\n      if let some (declName, args) := decodePackedArg? info packedArg then\n        let candidate := mkAppN (mkAppN (mkAppN (mkConst declName us) fixedPrefix) args) extraArgs\n        trace[Elab.definition.wf] \"found nested WF at discr {candidate}\"\n        if (\u2190 withDefault <| isDefEq candidate e) then\n          return .visit candidate\n    return .continue\n\n/--\n  Simplify `match`-expressions when trying to prove equation theorems for a recursive declaration defined using well-founded recursion.\n  It is similar to `simpMatch?`, but is also tries to fold `WellFounded.fix` applications occurring in discriminants.\n  See comment at `tryToFoldWellFoundedFix`.\n-/\ndef simpMatchWF? (info : EqnInfo) (us : List Level) (fixedPrefix : Array Expr) (mvarId : MVarId) : MetaM (Option MVarId) :=\n  mvarId.withContext do\n    let target \u2190 instantiateMVars (\u2190 mvarId.getType)\n    let (targetNew, _) \u2190 Simp.main target (\u2190 Split.getSimpMatchContext) (methods := { pre })\n    let mvarIdNew \u2190 applySimpResultToTarget mvarId target targetNew\n    if mvarId != mvarIdNew then return some mvarIdNew else return none\nwhere\n  pre (e : Expr) : SimpM Simp.Step := do\n    let some app \u2190 matchMatcherApp? e | return Simp.Step.visit { expr := e }\n    if app.discrs.any hasWellFoundedFix then\n      let discrsNew \u2190 app.discrs.mapM (tryToFoldWellFoundedFix info us fixedPrefix \u00b7)\n      if discrsNew != app.discrs then\n        let app := { app with discrs := discrsNew }\n        let eNew := app.toExpr\n        trace[Elab.definition.wf] \"folded discriminants {indentExpr eNew}\"\n        return Simp.Step.visit { expr := app.toExpr }\n    -- First try to reduce matcher\n    match (\u2190 reduceRecMatcher? e) with\n    | some e' => return Simp.Step.done { expr := e' }\n    | none    =>\n      match (\u2190 Simp.simpMatchCore? app e SplitIf.discharge?) with\n      | some r => return r\n      | none => return Simp.Step.visit { expr := e }\n\nprivate def tryToFoldLHS? (info : EqnInfo) (us : List Level) (fixedPrefix : Array Expr) (mvarId : MVarId) : MetaM (Option MVarId) :=\n  mvarId.withContext do\n    let target \u2190 mvarId.getType'\n    let some (_, lhs, rhs) := target.eq? | unreachable!\n    let lhsNew \u2190 tryToFoldWellFoundedFix info us fixedPrefix lhs\n    if lhs == lhsNew then return none\n    let targetNew \u2190 mkEq lhsNew rhs\n    let mvarNew \u2190 mkFreshExprSyntheticOpaqueMVar targetNew\n    mvarId.assign mvarNew\n    return mvarNew.mvarId!\n\n/--\n  Given a goal of the form `|- f.{us} a_1 ... a_n b_1 ... b_m = ...`, return `(us, #[a_1, ..., a_n])`\n  where `f` is a constant named `declName`, and `n = info.fixedPrefixSize`.\n-/\nprivate def getFixedPrefix (declName : Name) (info : EqnInfo) (mvarId : MVarId) : MetaM (List Level \u00d7 Array Expr) := mvarId.withContext do\n  let target \u2190 mvarId.getType'\n  let some (_, lhs, _) := target.eq? | unreachable!\n  let lhsArgs := lhs.getAppArgs\n  if lhsArgs.size < info.fixedPrefixSize || !lhs.getAppFn matches .const .. then\n    throwError \"failed to generate equational theorem for '{declName}', unexpected number of arguments in the equation left-hand-side\\n{mvarId}\"\n  let result := lhsArgs[:info.fixedPrefixSize]\n  trace[Elab.definition.wf.eqns] \"fixedPrefix: {result}\"\n  return (lhs.getAppFn.constLevels!, result)\n\nprivate partial def mkProof (declName : Name) (info : EqnInfo) (type : Expr) : MetaM Expr := do\n  trace[Elab.definition.wf.eqns] \"proving: {type}\"\n  withNewMCtxDepth do\n    let main \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let (_, mvarId) \u2190 main.mvarId!.intros\n    let (us, fixedPrefix) \u2190 getFixedPrefix declName info mvarId\n    let rec go (mvarId : MVarId) : MetaM Unit := do\n      trace[Elab.definition.wf.eqns] \"step\\n{MessageData.ofGoal mvarId}\"\n      if (\u2190 tryURefl mvarId) then\n        return ()\n      else if (\u2190 tryContradiction mvarId) then\n        return ()\n      else if let some mvarId \u2190 simpMatchWF? info us fixedPrefix mvarId then\n        go mvarId\n      else if let some mvarId \u2190 simpIf? mvarId then\n        go mvarId\n      else if let some mvarId \u2190 whnfReducibleLHS? mvarId then\n        go mvarId\n      else match (\u2190 simpTargetStar mvarId { config.dsimp := false }).1 with\n        | TacticResultCNM.closed => return ()\n        | TacticResultCNM.modified mvarId => go mvarId\n        | TacticResultCNM.noChange =>\n          if let some mvarIds \u2190 casesOnStuckLHS? mvarId then\n            mvarIds.forM go\n          else if let some mvarIds \u2190 splitTarget? mvarId then\n            mvarIds.forM go\n          else if let some mvarId \u2190 tryToFoldLHS? info us fixedPrefix mvarId then\n            go mvarId\n          else\n            throwError \"failed to generate equational theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n    go (\u2190 rwFixEq (\u2190 deltaLHSUntilFix mvarId))\n    instantiateMVars main\n\ndef mkEqns (declName : Name) (info : EqnInfo) : MetaM (Array Name) :=\n  withOptions (tactic.hygienic.set \u00b7 false) do\n  let baseName := mkPrivateName (\u2190 getEnv) declName\n  let eqnTypes \u2190 withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do\n    let us := info.levelParams.map mkLevelParam\n    let target \u2190 mkEq (mkAppN (Lean.mkConst declName us) xs) body\n    let goal \u2190 mkFreshExprSyntheticOpaqueMVar target\n    mkEqnTypes info.declNames goal.mvarId!\n  let mut thmNames := #[]\n  for i in [: eqnTypes.size] do\n    let type := eqnTypes[i]!\n    trace[Elab.definition.wf.eqns] \"{eqnTypes[i]!}\"\n    let name := baseName ++ (`_eq).appendIndexAfter (i+1)\n    thmNames := thmNames.push name\n    let value \u2190 mkProof declName info type\n    let (type, value) \u2190 removeUnusedEqnHypotheses type value\n    addDecl <| Declaration.thmDecl {\n      name, type, value\n      levelParams := info.levelParams\n    }\n  return thmNames\n\nbuiltin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo \u2190 mkMapDeclarationExtension\n\ndef registerEqnsInfo (preDefs : Array PreDefinition) (declNameNonRec : Name) (fixedPrefixSize : Nat) : CoreM Unit := do\n  let declNames := preDefs.map (\u00b7.declName)\n  modifyEnv fun env =>\n    preDefs.foldl (init := env) fun env preDef =>\n      eqnInfoExt.insert env preDef.declName { preDef with declNames, declNameNonRec, fixedPrefixSize }\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  if let some info := eqnInfoExt.find? (\u2190 getEnv) declName then\n    mkEqns declName info\n  else\n    return none\n\ndef getUnfoldFor? (declName : Name) : MetaM (Option Name) := do\n  let env \u2190 getEnv\n  Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (\u00b7.toEqnInfoCore)\n\nbuiltin_initialize\n  registerGetEqnsFn getEqnsFor?\n  registerGetUnfoldEqnFn getUnfoldFor?\n  registerTraceClass `Elab.definition.wf.eqns\n\nend Lean.Elab.WF\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/WF/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04672495597119808, "lm_q1q2_score": 0.02317996233961176}}
{"text": "import .proper .hyp\nnamespace hp\n\n/-- Tracking the reason why some proposition is true.\nInput writeup type, shouldn't contain any writeup information and\nshould just track the salient parts of the derivation. -/\n@[derive_prisms, derive decidable_eq, derive has_to_tactic_format]\nmeta inductive SourceReason\n/-- \"by assumption `h`\" -/\n| Assumption (n: name) (value : expr) (type : expr)\n/-- Since x and y are prime. Use this if the source was expanded to something gnarly. -/\n| Since (r : expr)\n| Lemma (r : expr)\n/-- Forward reasoning was used -/\n| Forward (implication premiss : SourceReason)\n| And (r1 r2 : SourceReason) : SourceReason\n| ConjElim (conj : SourceReason) (index : nat)\n/-- Don't bother writing the reason -/\n| Omit\n/-- \"by expanding the definition of a given local\" -/\n| ExpandLocal (r : SourceReason) (src : hyp)\n/-- \"by setting x to be X and y to be Y\" -/\n| Setting (r : SourceReason) (setters : list (stub \u00d7 expr))\n\nmeta def SourceReason.mmap_children {m} [monad m] (f : telescope \u2192 expr \u2192 m expr) (\u0393 : telescope) : SourceReason \u2192 m SourceReason\n| (SourceReason.Assumption n e t ) := pure SourceReason.Assumption <*> pure n <*> (\u0393 \u2344 f $ e) <*> (\u0393 \u2344 f $ t)\n| (SourceReason.Since      h) := pure SourceReason.Since      <*> (\u0393 \u2344 f $ h)\n| (SourceReason.Lemma      h) := pure SourceReason.Lemma      <*> (\u0393 \u2344 f $ h)\n| (SourceReason.Forward    a b) := pure SourceReason.Forward <*> (SourceReason.mmap_children $ a) <*> (SourceReason.mmap_children $ b)\n| (SourceReason.And        a b) := pure SourceReason.And <*> (SourceReason.mmap_children $ a) <*> (SourceReason.mmap_children $ b)\n| (SourceReason.ConjElim   a index) := pure SourceReason.ConjElim <*> (SourceReason.mmap_children $ a) <*> pure index\n| (SourceReason.Omit) := pure SourceReason.Omit\n| (SourceReason.ExpandLocal r src) := pure SourceReason.ExpandLocal <*> (SourceReason.mmap_children $ r) <*> (\u0393 \u2344 f $ src)\n| (SourceReason.Setting r setters) := pure SourceReason.Setting <*> (SourceReason.mmap_children $ r) <*> (\u0393 \u2344 f $ setters)\n\nmeta instance SR.asn : assignable SourceReason :=\n\u27e8@SourceReason.mmap_children\u27e9\n\n/-- A source is an expression that is salient to the proof state.\nFor example: assumptions, partially applied assumptions, exists elims. -/\n@[derive_setters, derive decidable_eq]\nmeta structure source :=\n(story : SourceReason := SourceReason.Omit)\n(label : name)\n(value : expr)\n(type : expr)\n(show_value : bool := ff)\n(is_vuln : bool := ff)\n\nnamespace source\n\nmeta instance : has_to_tactic_format source := \u27e8\u03bb s,\n  match s with\n  | s := do\n    l \u2190 tactic.pp s.label,\n    v \u2190 tactic.pp s.value,\n    pure $ l ++ \" \u2190 \" ++ v\n  end\u27e9\n\nmeta def of_hyp : hyp \u2192 source\n| h := { story := SourceReason.Assumption h.pretty_name h.to_expr h.type, label := h.pretty_name, value := h.to_expr, type := h.type }\n\n\nmeta instance : has_coe hyp source := \u27e8of_hyp\u27e9\n\nmeta def to_expr : source \u2192 expr\n| s := s.value\n\nmeta def to_binder : source \u2192 binder\n| s := \u27e8s.label, binder_info.default, s.type\u27e9\n\nmeta def of_expr : name \u2192 expr \u2192 tactic source\n| n e := do\n  y \u2190 tactic.infer_type e,\n  pure { label := n, value := e, type := y }\n\nmeta def of_exists : name \u2192 expr \u2192 tactic source\n| n e := do\n  y \u2190 tactic.infer_type e,\n  pure {label := n, story := SourceReason.Omit, value := e, type := y, show_value := ff}\n\nmeta def of_lemma : expr \u2192 tactic source\n| e := do\n  y \u2190 tactic.infer_type e,\n  f \u2190 pure $ expr.get_app_fn e,\n  pure {\n    label := expr.const_name $ expr.get_app_fn e,\n    story := SourceReason.Lemma f,\n    type := y,\n    value := e,\n  }\n\nmeta def mmap_children {m} [monad m] (f : telescope \u2192 expr \u2192 m expr) : telescope \u2192 source \u2192 m source\n| \u0393 s := do\n  v \u2190 \u0393 \u2344 f $ s.value,\n  t \u2190 \u0393 \u2344 f $ s.type,\n  st \u2190 \u0393 \u2344 f $ s.story,\n  s \u2190 pure {value := v, type := t, story := st, ..s},\n  pure s\n\nmeta instance : assignable source := \u27e8@mmap_children\u27e9\nend source\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/source.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.055823143883494485, "lm_q1q2_score": 0.023160958773741358}}
{"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.rsimp\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.Smt.SmtTactic\nimport Leanbin.Init.Meta.FunInfo\nimport Leanbin.Init.Meta.RbMap\n\ndef Tactic.IdTag.rsimp : Unit :=\n  ()\n#align tactic.id_tag.rsimp Tactic.IdTag.rsimp\n\nopen Tactic\n\nprivate unsafe def add_lemma (m : Transparency) (h : Name) (hs : hinst_lemmas) :\n    tactic hinst_lemmas :=\n  (do\n      let h \u2190 hinst_lemma.mk_from_decl_core m h true\n      return <| hs h) <|>\n    return hs\n#align add_lemma add_lemma\n\nprivate unsafe def to_hinst_lemmas (m : Transparency) (ex : name_set) :\n    List Name \u2192 hinst_lemmas \u2192 tactic hinst_lemmas\n  | [], hs => return hs\n  | n :: ns, hs =>\n    if ex.contains n then to_hinst_lemmas ns hs\n    else\n      let add (n) := add_lemma m n hs >>= to_hinst_lemmas ns\n      do\n      let eqns \u2190 tactic.get_eqn_lemmas_for true n\n      match eqns with\n        | [] => add n\n        | _ => condM (is_prop_decl n) (add n) (to_hinst_lemmas eqns hs >>= to_hinst_lemmas ns)\n#align to_hinst_lemmas to_hinst_lemmas\n\n/-- Create a rsimp attribute named `attr_name`, the attribute declaration is named `attr_decl_name`.\n    The cached hinst_lemmas structure is built using the lemmas marked with simp attribute `simp_attr_name`,\n    but *not* marked with `ex_attr_name`.\n\n    We say `ex_attr_name` is the \"exception set\". It is useful for excluding lemmas in `simp_attr_name`\n    which are not good or redundant for ematching. -/\nunsafe def mk_hinst_lemma_attr_from_simp_attr (attr_decl_name attr_name : Name)\n    (simp_attr_name : Name) (ex_attr_name : Name) : Tactic := do\n  let t := q(user_attribute hinst_lemmas)\n  let v :=\n    q(({  Name := attr_name\n          descr := s! \"hinst_lemma attribute derived from '{simp_attr_name}'\"\n          cache_cfg :=\n            { mk_cache := fun ns =>\n                let aux := simp_attr_name\n                let ex_attr := ex_attr_name\n                do\n                let hs \u2190 to_hinst_lemmas reducible mk_name_set ns hinst_lemmas.mk\n                let ss \u2190 attribute.get_instances aux\n                let ex \u2190 get_name_set_for_attr ex_attr\n                to_hinst_lemmas reducible ex ss hs\n              dependencies := [`reducibility, simp_attr_name] } } :\n        user_attribute hinst_lemmas))\n  add_decl (declaration.defn attr_decl_name [] t v ReducibilityHints.abbrev ff)\n  attribute.register attr_decl_name\n#align mk_hinst_lemma_attr_from_simp_attr mk_hinst_lemma_attr_from_simp_attr\n\nrun_cmd\n  mk_name_set_attr `no_rsimp\n\nrun_cmd\n  mk_hinst_lemma_attr_from_simp_attr `rsimp_attr `rsimp `simp `no_rsimp\n\n/- The following lemmas are not needed by rsimp, and they actually hurt performance since they generate a lot of\n   instances. -/\nattribute [no_rsimp]\n  id.def Ne.def not_true not_false_iff ne_self_iff_false eq_self_iff_true hEq_self_iff_true iff_not_self not_iff_self true_iff_false false_iff_true and_comm and_assoc and_left_comm and_true_iff true_and_iff and_false_iff false_and_iff not_and_self_iff and_not_self_iff and_self_iff or_comm or_assoc or_left_comm or_true_iff true_or_iff or_false_iff false_or_iff or_self_iff iff_true_iff true_iff_iff iff_false_iff false_iff_iff iff_self_iff imp_true_iff false_imp_iff if_t_t if_true if_false\n\nnamespace Rsimp\n\nunsafe def is_value_like : expr \u2192 Bool\n  | e =>\n    if \u00ace.is_app then false\n    else\n      let fn := e.get_app_fn\n      if \u00acfn.is_constant then false\n      else\n        let nargs := e.get_app_num_args\n        let fname := fn.const_name\n        if fname = `` Zero.zero \u2227 nargs = 2 then true\n        else\n          if fname = `` One.one \u2227 nargs = 2 then true\n          else\n            if fname = `` bit0 \u2227 nargs = 3 then is_value_like e.app_arg\n            else\n              if fname = `` bit1 \u2227 nargs = 4 then is_value_like e.app_arg\n              else if fname = `` Char.ofNat \u2227 nargs = 1 then is_value_like e.app_arg else false\n#align rsimp.is_value_like rsimp.is_value_like\n\n/-- Return the size of term by considering only explicit arguments. -/\nunsafe def explicit_size : expr \u2192 tactic Nat\n  | e =>\n    if \u00ace.is_app then return 1\n    else\n      if is_value_like e then return 1\n      else\n        fold_explicit_args e 1 fun n arg => do\n          let r \u2190 explicit_size arg\n          return <| r + n\n#align rsimp.explicit_size rsimp.explicit_size\n\n/-- Choose smallest element (with respect to explicit_size) in `e`s equivalence class. -/\nunsafe def choose (ccs : cc_state) (e : expr) : tactic expr := do\n  let sz \u2190 explicit_size e\n  let p \u2190\n    ccs.mfold_eqc e (e, sz) fun p e' =>\n        if p.2 = 1 then return p\n        else do\n          let sz' \u2190 explicit_size e'\n          if sz' < p.2 then return (e', sz') else return p\n  return p.1\n#align rsimp.choose rsimp.choose\n\nunsafe def repr_map :=\n  expr_map expr\n#align rsimp.repr_map rsimp.repr_map\n\nunsafe def mk_repr_map :=\n  expr_map.mk expr\n#align rsimp.mk_repr_map rsimp.mk_repr_map\n\nunsafe def to_repr_map (ccs : cc_state) : tactic repr_map :=\n  ccs.roots.foldlM\n    (fun S e => do\n      let r \u2190 choose ccs e\n      return <| S e r)\n    mk_repr_map\n#align rsimp.to_repr_map rsimp.to_repr_map\n\nunsafe def rsimplify (ccs : cc_state) (e : expr) (m : Option repr_map := none) :\n    tactic (expr \u00d7 expr) := do\n  let m \u2190\n    match m with\n      | none => to_repr_map ccs\n      | some m => return m\n  let r \u2190\n    simplify_top_down ()\n        (fun _ t => do\n          let root \u2190 return <| ccs.root t\n          let new_t \u2190 m.find root\n          guard \u00acnew_t == t\n          let prf \u2190 ccs.eqv_proof t new_t\n          return ((), new_t, prf))\n        e\n  return r.2\n#align rsimp.rsimplify rsimp.rsimplify\n\nstructure Config where\n  attrName := `rsimp_attr\n  maxRounds := 8\n#align rsimp.config Rsimp.Config\n\nopen SmtTactic\n\nprivate def tagged_proof.rsimp : Unit :=\n  ()\n#align rsimp.tagged_proof.rsimp rsimp.tagged_proof.rsimp\n\nunsafe def collect_implied_eqs (cfg : Config := { }) (extra := hinst_lemmas.mk) : tactic cc_state :=\n  do\n  focus1 <|\n      using_smt_with { emAttr := cfg } do\n        add_lemmas_from_facts\n        add_lemmas extra\n        iterate_at_most cfg (ematch >> try smt_tactic.close)\n        done >> return cc_state.mk <|> to_cc_state\n#align rsimp.collect_implied_eqs rsimp.collect_implied_eqs\n\nunsafe def rsimplify_goal (ccs : cc_state) (m : Option repr_map := none) : tactic Unit := do\n  let t \u2190 target\n  let (new_t, pr) \u2190 rsimplify ccs t m\n  try (replace_target new_t pr `` id_tag.rsimp)\n#align rsimp.rsimplify_goal rsimp.rsimplify_goal\n\nunsafe def rsimplify_at (ccs : cc_state) (h : expr) (m : Option repr_map := none) : tactic Unit :=\n  do\n  when (expr.is_local_constant h = ff)\n      (tactic.fail \"tactic rsimplify_at failed, the given expression is not a hypothesis\")\n  let htype \u2190 infer_type h\n  let (new_htype, HEq) \u2190 rsimplify ccs htype m\n  try do\n      assert (expr.local_pp_name h) new_htype\n      mk_eq_mp HEq h >>= exact\n      try <| clear h\n#align rsimp.rsimplify_at rsimp.rsimplify_at\n\nend Rsimp\n\nopen Rsimp\n\nnamespace Tactic\n\nunsafe def rsimp (cfg : Config := { }) (extra := hinst_lemmas.mk) : tactic Unit := do\n  let ccs \u2190 collect_implied_eqs cfg extra\n  try <| rsimplify_goal ccs\n#align tactic.rsimp tactic.rsimp\n\nunsafe def rsimp_at (h : expr) (cfg : Config := { }) (extra := hinst_lemmas.mk) : tactic Unit := do\n  let ccs \u2190 collect_implied_eqs cfg extra\n  try <| rsimplify_at ccs h\n#align tactic.rsimp_at tactic.rsimp_at\n\nnamespace Interactive\n\n-- TODO(Leo): allow user to provide extra lemmas manually\nunsafe def rsimp : tactic Unit :=\n  tactic.rsimp\n#align tactic.interactive.rsimp tactic.interactive.rsimp\n\nend Interactive\n\nend Tactic\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/Rsimp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618332444286, "lm_q2_score": 0.0510827391239775, "lm_q1q2_score": 0.023153855982480938}}
{"text": "@[simp] theorem liftOn_mk (a : \u03b1) (f : \u03b1 \u2192 \u03b3) (h : \u2200 a\u2081 a\u2082, r a\u2081 a\u2082 \u2192 f a\u2081 = f a\u2082) :\n    Quot.liftOn (Quot.mk r a) f h = f a := rfl\n\ntheorem eq_iff_true_of_subsingleton [Subsingleton \u03b1] (x y : \u03b1) : x = y \u2194 True :=\n  iff_true _ \u25b8 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 \u2227 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 {\u03b1 : Sort u_1} {a : \u03b1} : \u03b1 :=\n  a\n\n/-- Ex falso, the nondependent eliminator for the `empty` type. -/\ndef empty.elim {C : Sort u_1} : empty \u2192 C :=\n  sorry\n\nprotected instance empty.subsingleton : subsingleton empty :=\n  subsingleton.intro fun (a : empty) => empty.elim a\n\nprotected instance subsingleton.prod {\u03b1 : Type u_1} {\u03b2 : Type u_2} [subsingleton \u03b1] [subsingleton \u03b2] : subsingleton (\u03b1 \u00d7 \u03b2) :=\n  subsingleton.intro\n    fun (a b : \u03b1 \u00d7 \u03b2) =>\n      prod.cases_on a\n        fun (a_fst : \u03b1) (a_snd : \u03b2) =>\n          prod.cases_on b\n            fun (b_fst : \u03b1) (b_snd : \u03b2) =>\n              (fun (fst fst_1 : \u03b1) (snd snd_1 : \u03b2) =>\n                  Eq.trans ((fun (fst : \u03b1) (snd : \u03b2) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [Inhabited \u03b1] : Inhabited (psum \u03b1 \u03b2) :=\n  { default := psum.inl Inhabited.default }\n\nprotected instance psum.inhabited_right {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [Inhabited \u03b2] : Inhabited (psum \u03b1 \u03b2) :=\n  { default := psum.inr Inhabited.default }\n\nprotected instance decidable_eq_of_subsingleton {\u03b1 : Sort u_1} [subsingleton \u03b1] : DecidableEq \u03b1 :=\n  sorry\n\n@[simp] theorem eq_iff_true_of_subsingleton {\u03b1 : Type u_1} [subsingleton \u03b1] (x : \u03b1) (y : \u03b1) : x = y \u2194 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} [has_coe \u03b1 \u03b2] [has_coe_t \u03b2 \u03b3] (a : \u03b1) : \u2191a = \u2191\u2191a :=\n  rfl\n\ntheorem coe_fn_coe_trans {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_fun \u03b3] (x : \u03b1) : \u21d1x = \u21d1\u2191x :=\n  rfl\n\n@[simp] theorem coe_fn_coe_base {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [has_coe \u03b1 \u03b2] [has_coe_to_fun \u03b2] (x : \u03b1) : \u21d1x = \u21d1\u2191x :=\n  rfl\n\ntheorem coe_sort_coe_trans {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_sort \u03b3] (x : \u03b1) : \u21a5x = \u21a5\u2191x :=\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 : \u03b1 \u2243 \u03b2` and `a : \u03b1`\nthen you can write `e a` and this is elaborated as `\u21d1e 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 (\u03b1 \u03b2) extends \u03b1 \u2243 \u03b2\n\n-- if we add a `has_coe` instance,\n\n-- if we add a `has_coe` instance,\ninstance {\u03b1 \u03b2} : has_coe (sparkling_equiv \u03b1 \u03b2) (\u03b1 \u2243 \u03b2) :=\n\u27e8sparkling_equiv.to_equiv\u27e9\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 {\u03b1 \u03b2} : has_coe_to_fun (sparkling_equiv \u03b1 \u03b2) :=\n\u27e8\u03bb _, \u03b1 \u2192 \u03b2, \u03bb f, f.to_equiv.to_fun\u27e9\n```\n\n(Rationale: if we do not declare the direct coercion, then `\u21d1e a` is not in\nsimp-normal form. The lemma `coe_fn_coe_base` will unfold it to `\u21d1\u2191e a`. This\noften causes loops in the simplifier.)\n-/\n@[simp] theorem coe_sort_coe_base {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [has_coe \u03b1 \u03b2] [has_coe_to_sort \u03b2] (x : \u03b1) : \u21a5x = \u21a5\u2191x :=\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 \u2192 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 : \u00acNonempty 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 \u2192 Prop} : (\u2200 (x : pempty), P x) \u2194 True :=\n  { mp := fun (h : \u2200 (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 \u2192 Prop} : (\u2203 (x : pempty), P x) \u2194 False := sorry\n\ntheorem congr_arg_heq {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (f : (a : \u03b1) \u2192 \u03b2 a) {a\u2081 : \u03b1} {a\u2082 : \u03b1} : a\u2081 = a\u2082 \u2192 f a\u2081 == f a\u2082 := sorry\n\ntheorem plift.down_inj {\u03b1 : Sort u_1} (a : plift \u03b1) (b : plift \u03b1) : plift.down a = plift.down b \u2192 a = b := sorry\n\n-- missing [symm] attribute for ne in core.\n\ntheorem ne_comm {\u03b1 : Sort u_1} {a : \u03b1} {b : \u03b1} : a \u2260 b \u2194 b \u2260 a :=\n  { mp := ne.symm, mpr := ne.symm }\n\n@[simp] theorem eq_iff_eq_cancel_left {\u03b1 : Type u_1} {b : \u03b1} {c : \u03b1} : (\u2200 {a : \u03b1}, a = b \u2194 a = c) \u2194 b = c :=\n  { mp :=\n      fun (h : \u2200 {a : \u03b1}, a = b \u2194 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 : \u03b1) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b \u2194 a = c)) h)) (iff.refl (a = c)) }\n\n@[simp] theorem eq_iff_eq_cancel_right {\u03b1 : Type u_1} {a : \u03b1} {b : \u03b1} : (\u2200 {c : \u03b1}, a = c \u2194 b = c) \u2194 a = b :=\n  { mp := fun (h : \u2200 {c : \u03b1}, a = c \u2194 b = c) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (propext h))) (Eq.refl b),\n    mpr := fun (h : a = b) (a_1 : \u03b1) => eq.mpr (id (Eq._oldrec (Eq.refl (a = a_1 \u2194 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 \u2260 True :=\n  fun (\u1fb0 : False = True) => idRhs ((fun (_x : Prop) => _x) False) (Eq.symm \u1fb0 \u25b8 trivial)\n\n/-! ### Declarations about `implies` -/\n\ntheorem iff_of_eq {a : Prop} {b : Prop} (e : a = b) : a \u2194 b :=\n  e \u25b8 iff.rfl\n\ntheorem iff_iff_eq {a : Prop} {b : Prop} : a \u2194 b \u2194 a = b :=\n  { mp := propext, mpr := iff_of_eq }\n\n@[simp] theorem eq_iff_iff {p : Prop} {q : Prop} : p = q \u2194 (p \u2194 q) :=\n  iff.symm iff_iff_eq\n\n@[simp] theorem imp_self {a : Prop} : a \u2192 a \u2194 True :=\n  iff_true_intro id\n\ntheorem imp_intro {\u03b1 : Prop} {\u03b2 : Prop} (h : \u03b1) : \u03b2 \u2192 \u03b1 :=\n  fun (_x : \u03b2) => h\n\ntheorem imp_false {a : Prop} : a \u2192 False \u2194 \u00aca :=\n  iff.rfl\n\ntheorem imp_and_distrib {b : Prop} {c : Prop} {\u03b1 : Sort u_1} : \u03b1 \u2192 b \u2227 c \u2194 (\u03b1 \u2192 b) \u2227 (\u03b1 \u2192 c) :=\n  { mp := fun (h : \u03b1 \u2192 b \u2227 c) => { left := fun (ha : \u03b1) => and.left (h ha), right := fun (ha : \u03b1) => and.right (h ha) },\n    mpr := fun (h : (\u03b1 \u2192 b) \u2227 (\u03b1 \u2192 c)) (ha : \u03b1) => { left := and.left h ha, right := and.right h ha } }\n\n@[simp] theorem and_imp {a : Prop} {b : Prop} {c : Prop} : a \u2227 b \u2192 c \u2194 a \u2192 b \u2192 c := sorry\n\ntheorem iff_def {a : Prop} {b : Prop} : a \u2194 b \u2194 (a \u2192 b) \u2227 (b \u2192 a) :=\n  iff_iff_implies_and_implies a b\n\ntheorem iff_def' {a : Prop} {b : Prop} : a \u2194 b \u2194 (b \u2192 a) \u2227 (a \u2192 b) :=\n  iff.trans iff_def and.comm\n\ntheorem imp_true_iff {\u03b1 : Sort u_1} : \u03b1 \u2192 True \u2194 True :=\n  iff_true_intro fun (_x : \u03b1) => trivial\n\n@[simp] theorem imp_iff_right {a : Prop} {b : Prop} (ha : a) : a \u2192 b \u2194 b :=\n  { mp := fun (f : a \u2192 b) => f ha, mpr := imp_intro }\n\n/-! ### Declarations about `not` -/\n\n/-- Ex falso for negation. From `\u00ac 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} {\u03b1 : Sort u_1} (H1 : \u00aca) (H2 : a) : \u03b1 :=\n  absurd H2 H1\n\ntheorem not.imp {a : Prop} {b : Prop} (H2 : \u00acb) (H1 : a \u2192 b) : \u00aca :=\n  mt H1 H2\n\ntheorem not_not_of_not_imp {a : Prop} {b : Prop} : \u00ac(a \u2192 b) \u2192 \u00ac\u00aca :=\n  mt not.elim\n\ntheorem not_of_not_imp {b : Prop} {a : Prop} : \u00ac(a \u2192 b) \u2192 \u00acb :=\n  mt imp_intro\n\ntheorem dec_em (p : Prop) [Decidable p] : p \u2228 \u00acp :=\n  decidable.em p\n\ntheorem em (p : Prop) : p \u2228 \u00acp :=\n  classical.em p\n\ntheorem or_not {p : Prop} : p \u2228 \u00acp :=\n  em p\n\ntheorem by_contradiction {p : Prop} : (\u00acp \u2192 False) \u2192 p :=\n  decidable.by_contradiction\n\n-- alias by_contradiction \u2190 by_contra\n\ntheorem by_contra {p : Prop} : (\u00acp \u2192 False) \u2192 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] : \u00ac\u00aca \u2194 a :=\n  { mp := decidable.by_contradiction, mpr := not_not_intro }\n\n/-- The Double Negation Theorem: `\u00ac \u00ac 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} : \u00ac\u00aca \u2194 a :=\n  decidable.not_not\n\ntheorem of_not_not {a : Prop} : \u00ac\u00aca \u2192 a :=\n  by_contra\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.of_not_imp {a : Prop} {b : Prop} [Decidable a] (h : \u00ac(a \u2192 b)) : a :=\n  decidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp {a : Prop} {b : Prop} : \u00ac(a \u2192 b) \u2192 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 : \u00aca \u2192 b) (hb : \u00acb) : a :=\n  decidable.by_contradiction (hb \u2218 h)\n\ntheorem not.decidable_imp_symm {a : Prop} {b : Prop} [Decidable a] : (\u00aca \u2192 b) \u2192 \u00acb \u2192 a :=\n  decidable.not_imp_symm\n\ntheorem not.imp_symm {a : Prop} {b : Prop} : (\u00aca \u2192 b) \u2192 \u00acb \u2192 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] : \u00aca \u2192 b \u2194 \u00acb \u2192 a :=\n  { mp := not.decidable_imp_symm, mpr := not.decidable_imp_symm }\n\ntheorem not_imp_comm {a : Prop} {b : Prop} : \u00aca \u2192 b \u2194 \u00acb \u2192 a :=\n  decidable.not_imp_comm\n\n@[simp] theorem imp_not_self {a : Prop} : a \u2192 \u00aca \u2194 \u00aca :=\n  { mp := fun (h : a \u2192 \u00aca) (ha : a) => h ha ha, mpr := fun (h : \u00aca) (_x : a) => h }\n\ntheorem decidable.not_imp_self {a : Prop} [Decidable a] : \u00aca \u2192 a \u2194 a :=\n  eq.mp (Eq._oldrec (Eq.refl (\u00aca \u2192 \u00ac\u00aca \u2194 \u00ac\u00aca)) (propext decidable.not_not)) imp_not_self\n\n@[simp] theorem not_imp_self {a : Prop} : \u00aca \u2192 a \u2194 a :=\n  decidable.not_imp_self\n\ntheorem imp.swap {a : Prop} {b : Prop} {c : Prop} : a \u2192 b \u2192 c \u2194 b \u2192 a \u2192 c :=\n  { mp := function.swap, mpr := function.swap }\n\ntheorem imp_not_comm {a : Prop} {b : Prop} : a \u2192 \u00acb \u2194 b \u2192 \u00aca :=\n  imp.swap\n\n/-! ### Declarations about `and` -/\n\ntheorem and_congr_left {a : Prop} {b : Prop} {c : Prop} (h : c \u2192 (a \u2194 b)) : a \u2227 c \u2194 b \u2227 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 \u2194 b) : a \u2227 c \u2194 b \u2227 c :=\n  and_congr h iff.rfl\n\ntheorem and_congr_right' {a : Prop} {b : Prop} {c : Prop} (h : b \u2194 c) : a \u2227 b \u2194 a \u2227 c :=\n  and_congr iff.rfl h\n\ntheorem not_and_of_not_left {a : Prop} (b : Prop) : \u00aca \u2192 \u00ac(a \u2227 b) :=\n  mt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : \u00acb \u2192 \u00ac(a \u2227 b) :=\n  mt and.right\n\ntheorem and.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a \u2192 b) : a \u2227 c \u2192 b \u2227 c :=\n  and.imp h id\n\ntheorem and.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a \u2192 b) : c \u2227 a \u2192 c \u2227 b :=\n  and.imp id h\n\ntheorem and.right_comm {a : Prop} {b : Prop} {c : Prop} : (a \u2227 b) \u2227 c \u2194 (a \u2227 c) \u2227 b := sorry\n\ntheorem and.rotate {a : Prop} {b : Prop} {c : Prop} : a \u2227 b \u2227 c \u2194 b \u2227 c \u2227 a := sorry\n\ntheorem and_not_self_iff (a : Prop) : a \u2227 \u00aca \u2194 False :=\n  { mp := fun (h : a \u2227 \u00aca) => and.right h (and.left h), mpr := fun (h : False) => false.elim h }\n\ntheorem not_and_self_iff (a : Prop) : \u00aca \u2227 a \u2194 False := sorry\n\ntheorem and_iff_left_of_imp {a : Prop} {b : Prop} (h : a \u2192 b) : a \u2227 b \u2194 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 \u2192 a) : a \u2227 b \u2194 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 \u2227 b \u2194 a \u2194 a \u2192 b :=\n  { mp := fun (h : a \u2227 b \u2194 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 \u2227 b \u2194 b \u2194 b \u2192 a :=\n  { mp := fun (h : a \u2227 b \u2194 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 \u2227 b \u2194 a \u2227 c \u2194 a \u2192 (b \u2194 c) := sorry\n\n@[simp] theorem and.congr_left_iff {a : Prop} {b : Prop} {c : Prop} : a \u2227 c \u2194 b \u2227 c \u2194 c \u2192 (a \u2194 b) := sorry\n\n@[simp] theorem and_self_left {a : Prop} {b : Prop} : a \u2227 a \u2227 b \u2194 a \u2227 b :=\n  { mp := fun (h : a \u2227 a \u2227 b) => { left := and.left h, right := and.right (and.right h) },\n    mpr := fun (h : a \u2227 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 \u2227 b) \u2227 b \u2194 a \u2227 b :=\n  { mp := fun (h : (a \u2227 b) \u2227 b) => { left := and.left (and.left h), right := and.right h },\n    mpr := fun (h : a \u2227 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 \u2194 b) : a \u2228 c \u2194 b \u2228 c :=\n  or_congr h iff.rfl\n\ntheorem or_congr_right {a : Prop} {b : Prop} {c : Prop} (h : b \u2194 c) : a \u2228 b \u2194 a \u2228 c :=\n  or_congr iff.rfl h\n\ntheorem or.right_comm {a : Prop} {b : Prop} {c : Prop} : (a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 b :=\n  eq.mpr (id (Eq._oldrec (Eq.refl ((a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 b)) (propext (or_assoc a b))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2228 c \u2194 (a \u2228 c) \u2228 b)) (propext (or_assoc a c))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2228 c \u2194 a \u2228 c \u2228 b)) (propext (or_comm b c)))) (iff.refl (a \u2228 c \u2228 b))))\n\ntheorem or_of_or_of_imp_of_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h\u2081 : a \u2228 b) (h\u2082 : a \u2192 c) (h\u2083 : b \u2192 d) : c \u2228 d :=\n  or.imp h\u2082 h\u2083 h\u2081\n\ntheorem or_of_or_of_imp_left {a : Prop} {b : Prop} {c : Prop} (h\u2081 : a \u2228 c) (h : a \u2192 b) : b \u2228 c :=\n  or.imp_left h h\u2081\n\ntheorem or_of_or_of_imp_right {a : Prop} {b : Prop} {c : Prop} (h\u2081 : c \u2228 a) (h : a \u2192 b) : c \u2228 b :=\n  or.imp_right h h\u2081\n\ntheorem or.elim3 {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h : a \u2228 b \u2228 c) (ha : a \u2192 d) (hb : b \u2192 d) (hc : c \u2192 d) : d :=\n  or.elim h ha fun (h\u2082 : b \u2228 c) => or.elim h\u2082 hb hc\n\ntheorem or_imp_distrib {a : Prop} {b : Prop} {c : Prop} : a \u2228 b \u2192 c \u2194 (a \u2192 c) \u2227 (b \u2192 c) := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_imp_left {a : Prop} {b : Prop} [Decidable a] : a \u2228 b \u2194 \u00aca \u2192 b :=\n  { mp := or.resolve_left, mpr := fun (h : \u00aca \u2192 b) => dite a Or.inl (Or.inr \u2218 h) }\n\ntheorem or_iff_not_imp_left {a : Prop} {b : Prop} : a \u2228 b \u2194 \u00aca \u2192 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 \u2228 b \u2194 \u00acb \u2192 a :=\n  iff.trans or.comm decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right {a : Prop} {b : Prop} : a \u2228 b \u2194 \u00acb \u2192 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] : \u00aca \u2192 \u00acb \u2194 b \u2192 a :=\n  { mp := fun (h : \u00aca \u2192 \u00acb) (hb : b) => decidable.by_contradiction fun (na : \u00aca) => h na hb, mpr := mt }\n\ntheorem not_imp_not {a : Prop} {b : Prop} : \u00aca \u2192 \u00acb \u2194 b \u2192 a :=\n  decidable.not_imp_not\n\n@[simp] theorem or_iff_left_iff_imp {a : Prop} {b : Prop} : a \u2228 b \u2194 a \u2194 b \u2192 a :=\n  { mp := fun (h : a \u2228 b \u2194 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 \u2228 b \u2194 b \u2194 a \u2192 b :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2194 b \u2194 a \u2192 b)) (propext (or_comm a b))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (b \u2228 a \u2194 b \u2194 a \u2192 b)) (propext or_iff_left_iff_imp))) (iff.refl (a \u2192 b)))\n\n/-! ### Declarations about distributivity -/\n\n/-- `\u2227` distributes over `\u2228` (on the left). -/\ntheorem and_or_distrib_left {a : Prop} {b : Prop} {c : Prop} : a \u2227 (b \u2228 c) \u2194 a \u2227 b \u2228 a \u2227 c := sorry\n\n/-- `\u2227` distributes over `\u2228` (on the right). -/\ntheorem or_and_distrib_right {a : Prop} {b : Prop} {c : Prop} : (a \u2228 b) \u2227 c \u2194 a \u2227 c \u2228 b \u2227 c :=\n  iff.trans (iff.trans and.comm and_or_distrib_left) (or_congr and.comm and.comm)\n\n/-- `\u2228` distributes over `\u2227` (on the left). -/\ntheorem or_and_distrib_left {a : Prop} {b : Prop} {c : Prop} : a \u2228 b \u2227 c \u2194 (a \u2228 b) \u2227 (a \u2228 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 \u2218 Or.inl) (or.imp_right \u2218 And.intro)) }\n\n/-- `\u2228` distributes over `\u2227` (on the right). -/\ntheorem and_or_distrib_right {a : Prop} {b : Prop} {c : Prop} : a \u2227 b \u2228 c \u2194 (a \u2228 c) \u2227 (b \u2228 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 \u2228 a \u2228 b \u2194 a \u2228 b :=\n  { mp := fun (h : a \u2228 a \u2228 b) => or.elim h Or.inl id, mpr := fun (h : a \u2228 b) => or.elim h Or.inl (Or.inr \u2218 Or.inr) }\n\n@[simp] theorem or_self_right {a : Prop} {b : Prop} : (a \u2228 b) \u2228 b \u2194 a \u2228 b :=\n  { mp := fun (h : (a \u2228 b) \u2228 b) => or.elim h id Or.inr, mpr := fun (h : a \u2228 b) => or.elim h (Or.inl \u2218 Or.inl) Or.inr }\n\n/-! Declarations about `iff` -/\n\ntheorem iff_of_true {a : Prop} {b : Prop} (ha : a) (hb : b) : a \u2194 b :=\n  { mp := fun (_x : a) => hb, mpr := fun (_x : b) => ha }\n\ntheorem iff_of_false {a : Prop} {b : Prop} (ha : \u00aca) (hb : \u00acb) : a \u2194 b :=\n  { mp := not.elim ha, mpr := not.elim hb }\n\ntheorem iff_true_left {a : Prop} {b : Prop} (ha : a) : a \u2194 b \u2194 b :=\n  { mp := fun (h : a \u2194 b) => iff.mp h ha, mpr := iff_of_true ha }\n\ntheorem iff_true_right {a : Prop} {b : Prop} (ha : a) : b \u2194 a \u2194 b :=\n  iff.trans iff.comm (iff_true_left ha)\n\ntheorem iff_false_left {a : Prop} {b : Prop} (ha : \u00aca) : a \u2194 b \u2194 \u00acb :=\n  { mp := fun (h : a \u2194 b) => mt (iff.mpr h) ha, mpr := iff_of_false ha }\n\ntheorem iff_false_right {a : Prop} {b : Prop} (ha : \u00aca) : b \u2194 a \u2194 \u00acb :=\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 \u2192 b) : \u00aca \u2228 b :=\n  dite a (fun (ha : a) => Or.inr (h ha)) fun (ha : \u00aca) => Or.inl ha\n\ntheorem not_or_of_imp {a : Prop} {b : Prop} : (a \u2192 b) \u2192 \u00aca \u2228 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 \u2192 b \u2194 \u00aca \u2228 b :=\n  { mp := decidable.not_or_of_imp, mpr := or.neg_resolve_left }\n\ntheorem imp_iff_not_or {a : Prop} {b : Prop} : a \u2192 b \u2194 \u00aca \u2228 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 \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 c) := sorry\n\ntheorem imp_or_distrib {a : Prop} {b : Prop} {c : Prop} : a \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 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 \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 c) := sorry\n\ntheorem imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} : a \u2192 b \u2228 c \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\n  decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not {a : Prop} {b : Prop} : a \u2227 \u00acb \u2192 \u00ac(a \u2192 b) :=\n  fun (\u1fb0 : a \u2227 \u00acb) (\u1fb0_1 : a \u2192 b) => and.dcases_on \u1fb0 fun (\u1fb0_left : a) (\u1fb0_right : \u00acb) => idRhs False (\u1fb0_right (\u1fb0_1 \u1fb0_left))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp {a : Prop} {b : Prop} [Decidable a] : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb :=\n  { mp := fun (h : \u00ac(a \u2192 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} : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb :=\n  decidable.not_imp\n\n-- for monotonicity\n\ntheorem imp_imp_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h\u2080 : c \u2192 a) (h\u2081 : b \u2192 d) : (a \u2192 b) \u2192 c \u2192 d :=\n  fun (h\u2082 : a \u2192 b) => h\u2081 \u2218 h\u2082 \u2218 h\u2080\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.peirce (a : Prop) (b : Prop) [Decidable a] : ((a \u2192 b) \u2192 a) \u2192 a :=\n  dite a (fun (ha : a) (h : (a \u2192 b) \u2192 a) => ha) fun (ha : \u00aca) (h : (a \u2192 b) \u2192 a) => h (not.elim ha)\n\ntheorem peirce (a : Prop) (b : Prop) : ((a \u2192 b) \u2192 a) \u2192 a :=\n  decidable.peirce a b\n\ntheorem peirce' {a : Prop} (H : \u2200 (b : Prop), (a \u2192 b) \u2192 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] : \u00aca \u2194 \u00acb \u2194 (a \u2194 b) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (\u00aca \u2194 \u00acb \u2194 (a \u2194 b))) (propext iff_def)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl ((\u00aca \u2192 \u00acb) \u2227 (\u00acb \u2192 \u00aca) \u2194 (a \u2194 b))) (propext iff_def')))\n      (and_congr decidable.not_imp_not decidable.not_imp_not))\n\ntheorem not_iff_not {a : Prop} {b : Prop} : \u00aca \u2194 \u00acb \u2194 (a \u2194 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] : \u00aca \u2194 b \u2194 (\u00acb \u2194 a) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (\u00aca \u2194 b \u2194 (\u00acb \u2194 a))) (propext iff_def)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl ((\u00aca \u2192 b) \u2227 (b \u2192 \u00aca) \u2194 (\u00acb \u2194 a))) (propext iff_def)))\n      (and_congr decidable.not_imp_comm imp_not_comm))\n\ntheorem not_iff_comm {a : Prop} {b : Prop} : \u00aca \u2194 b \u2194 (\u00acb \u2194 a) :=\n  decidable.not_iff_comm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff {a : Prop} {b : Prop} [Decidable b] : \u00ac(a \u2194 b) \u2194 (\u00aca \u2194 b) := sorry\n\ntheorem not_iff {a : Prop} {b : Prop} : \u00ac(a \u2194 b) \u2194 (\u00aca \u2194 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 \u2194 \u00acb \u2194 (b \u2194 \u00aca) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2194 \u00acb \u2194 (b \u2194 \u00aca))) (propext iff_def)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl ((a \u2192 \u00acb) \u2227 (\u00acb \u2192 a) \u2194 (b \u2194 \u00aca))) (propext iff_def)))\n      (and_congr imp_not_comm decidable.not_imp_comm))\n\ntheorem iff_not_comm {a : Prop} {b : Prop} : a \u2194 \u00acb \u2194 (b \u2194 \u00aca) :=\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 \u2194 b \u2194 a \u2227 b \u2228 \u00aca \u2227 \u00acb := sorry\n\ntheorem iff_iff_and_or_not_and_not {a : Prop} {b : Prop} : a \u2194 b \u2194 a \u2227 b \u2228 \u00aca \u2227 \u00acb :=\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 \u2194 b \u2194 (\u00aca \u2228 b) \u2227 (a \u2228 \u00acb) := sorry\n\ntheorem iff_iff_not_or_and_or_not {a : Prop} {b : Prop} : a \u2194 b \u2194 (\u00aca \u2228 b) \u2227 (a \u2228 \u00acb) :=\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] : \u00ac(a \u2227 \u00acb) \u2194 a \u2192 b := sorry\n\ntheorem not_and_not_right {a : Prop} {b : Prop} : \u00ac(a \u2227 \u00acb) \u2194 a \u2192 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 \u2194 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 \u2194 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 \u2194 a`.\n(This is sometimes taken as an alternate definition of decidability.) -/\ndef decidable_of_bool {a : Prop} (b : Bool) (h : \u21a5b \u2194 a) : Decidable a :=\n  sorry\n\n/-! ### De Morgan's laws -/\n\ntheorem not_and_of_not_or_not {a : Prop} {b : Prop} (h : \u00aca \u2228 \u00acb) : \u00ac(a \u2227 b) :=\n  fun (\u1fb0 : a \u2227 b) =>\n    and.dcases_on \u1fb0 fun (\u1fb0_left : a) (\u1fb0_right : b) => idRhs False (or.elim h (absurd \u1fb0_left) (absurd \u1fb0_right))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib {a : Prop} {b : Prop} [Decidable a] : \u00ac(a \u2227 b) \u2194 \u00aca \u2228 \u00acb := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib' {a : Prop} {b : Prop} [Decidable b] : \u00ac(a \u2227 b) \u2194 \u00aca \u2228 \u00acb := 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} : \u00ac(a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\n  decidable.not_and_distrib\n\n@[simp] theorem not_and {a : Prop} {b : Prop} : \u00ac(a \u2227 b) \u2194 a \u2192 \u00acb :=\n  and_imp\n\ntheorem not_and' {a : Prop} {b : Prop} : \u00ac(a \u2227 b) \u2194 b \u2192 \u00aca :=\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} : \u00ac(a \u2228 b) \u2194 \u00aca \u2227 \u00acb := 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 \u2228 b \u2194 \u00ac(\u00aca \u2227 \u00acb) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2194 \u00ac(\u00aca \u2227 \u00acb))) (Eq.symm (propext not_or_distrib))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2228 b \u2194 \u00ac\u00ac(a \u2228 b))) (propext decidable.not_not))) (iff.refl (a \u2228 b)))\n\ntheorem or_iff_not_and_not {a : Prop} {b : Prop} : a \u2228 b \u2194 \u00ac(\u00aca \u2227 \u00acb) :=\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 \u2227 b \u2194 \u00ac(\u00aca \u2228 \u00acb) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (a \u2227 b \u2194 \u00ac(\u00aca \u2228 \u00acb))) (Eq.symm (propext decidable.not_and_distrib))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (a \u2227 b \u2194 \u00ac\u00ac(a \u2227 b))) (propext decidable.not_not))) (iff.refl (a \u2227 b)))\n\ntheorem and_iff_not_or_not {a : Prop} {b : Prop} : a \u2227 b \u2194 \u00ac(\u00aca \u2228 \u00acb) :=\n  decidable.and_iff_not_or_not\n\n/-! ### Declarations about equality -/\n\n@[simp] theorem heq_iff_eq {\u03b1 : Sort u_1} {a : \u03b1} {b : \u03b1} : a == b \u2194 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 {\u03b1 : outParam (Type u_1)} {\u03b2 : Type u_2} [has_mem \u03b1 \u03b2] {s : \u03b2} {a : \u03b1} {b : \u03b1} (h : a \u2208 s) : \u00acb \u2208 s \u2192 a \u2260 b :=\n  mt fun (e : a = b) => e \u25b8 h\n\ntheorem eq_equivalence {\u03b1 : 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 {\u03b1 : Sort u_1} {a : \u03b1} {a' : \u03b1} {\u03b2 : Sort u_2} (y : \u03b2) (h : a = a') : Eq._oldrec y h = y := sorry\n\n@[simp] theorem eq_mp_rfl {\u03b1 : Sort u_1} {a : \u03b1} : eq.mp (Eq.refl \u03b1) a = a :=\n  rfl\n\n@[simp] theorem eq_mpr_rfl {\u03b1 : Sort u_1} {a : \u03b1} : eq.mpr (Eq.refl \u03b1) a = a :=\n  rfl\n\ntheorem heq_of_eq_mp {\u03b1 : Sort u_1} {\u03b2 : Sort u_1} {a : \u03b1} {a' : \u03b2} (e : \u03b1 = \u03b2) (h\u2082 : eq.mp e a = a') : a == a' := sorry\n\ntheorem rec_heq_of_heq {\u03b1 : Sort u_1} {a : \u03b1} {b : \u03b1} {\u03b2 : Sort u_2} {C : \u03b1 \u2192 Sort u_2} {x : C a} {y : \u03b2} (eq : a = b) (h : x == y) : Eq._oldrec x eq == y :=\n  eq.drec h eq\n\n@[simp] theorem eq_mpr_heq {\u03b1 : Sort u} {\u03b2 : Sort u} (h : \u03b2 = \u03b1) (x : \u03b1) : eq.mpr h x == x :=\n  eq.drec (fun (x : \u03b2) => HEq.refl (eq.mpr (Eq.refl \u03b2) x)) h x\n\nprotected theorem eq.congr {\u03b1 : Sort u_1} {x\u2081 : \u03b1} {x\u2082 : \u03b1} {y\u2081 : \u03b1} {y\u2082 : \u03b1} (h\u2081 : x\u2081 = y\u2081) (h\u2082 : x\u2082 = y\u2082) : x\u2081 = x\u2082 \u2194 y\u2081 = y\u2082 :=\n  Eq._oldrec (Eq._oldrec (iff.refl (x\u2081 = x\u2082)) h\u2082) h\u2081\n\ntheorem eq.congr_left {\u03b1 : Sort u_1} {x : \u03b1} {y : \u03b1} {z : \u03b1} (h : x = y) : x = z \u2194 y = z :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (x = z \u2194 y = z)) h)) (iff.refl (y = z))\n\ntheorem eq.congr_right {\u03b1 : Sort u_1} {x : \u03b1} {y : \u03b1} {z : \u03b1} (h : x = y) : z = x \u2194 z = y :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (z = x \u2194 z = y)) h)) (iff.refl (z = y))\n\ntheorem congr_arg2 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) {x : \u03b1} {x' : \u03b1} {y : \u03b2} {y' : \u03b2} (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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), p a \u2192 q a) : (\u2200 (a : \u03b1), p a) \u2192 \u2200 (a : \u03b1), q a :=\n  fun (h' : \u2200 (a : \u03b1), p a) (a : \u03b1) => h a (h' a)\n\ntheorem forall\u2082_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2), p a b \u2194 q a b) : (\u2200 (a : \u03b1) (b : \u03b2), p a b) \u2194 \u2200 (a : \u03b1) (b : \u03b2), q a b :=\n  forall_congr fun (a : \u03b1) => forall_congr (h a)\n\ntheorem forall\u2083_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), p a b c \u2194 q a b c) : (\u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), p a b c) \u2194 \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), q a b c :=\n  forall_congr fun (a : \u03b1) => forall\u2082_congr (h a)\n\ntheorem forall\u2084_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {\u03b4 : Sort u_4} {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), p a b c d \u2194 q a b c d) : (\u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), p a b c d) \u2194 \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), q a b c d :=\n  forall_congr fun (a : \u03b1) => forall\u2083_congr (h a)\n\ntheorem Exists.imp {\u03b1 : Sort u_1} {q : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), p a \u2192 q a) : (\u2203 (a : \u03b1), p a) \u2192 \u2203 (a : \u03b1), q a :=\n  fun (p_1 : \u2203 (a : \u03b1), p a) => exists_imp_exists h p_1\n\ntheorem exists_imp_exists' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2) (hpq : \u2200 (a : \u03b1), p a \u2192 q (f a)) (hp : \u2203 (a : \u03b1), p a) : \u2203 (b : \u03b2), q b :=\n  exists.elim hp fun (a : \u03b1) (hp' : p a) => Exists.intro (f a) (hpq a hp')\n\ntheorem exists\u2082_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2), p a b \u2194 q a b) : (\u2203 (a : \u03b1), \u2203 (b : \u03b2), p a b) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), q a b :=\n  exists_congr fun (a : \u03b1) => exists_congr (h a)\n\ntheorem exists\u2083_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3), p a b c \u2194 q a b c) : (\u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), p a b c) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), q a b c :=\n  exists_congr fun (a : \u03b1) => exists\u2082_congr (h a)\n\ntheorem exists\u2084_congr {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {\u03b4 : Sort u_4} {p : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop} {q : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 Prop} (h : \u2200 (a : \u03b1) (b : \u03b2) (c : \u03b3) (d : \u03b4), p a b c d \u2194 q a b c d) : (\u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), \u2203 (d : \u03b4), p a b c d) \u2194 \u2203 (a : \u03b1), \u2203 (b : \u03b2), \u2203 (c : \u03b3), \u2203 (d : \u03b4), q a b c d :=\n  exists_congr fun (a : \u03b1) => exists\u2083_congr (h a)\n\ntheorem forall_swap {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2200 (x : \u03b1) (y : \u03b2), p x y) \u2194 \u2200 (y : \u03b2) (x : \u03b1), p x y :=\n  { mp := function.swap, mpr := function.swap }\n\ntheorem exists_swap {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 (x : \u03b1), \u2203 (y : \u03b2), p x y) \u2194 \u2203 (y : \u03b2), \u2203 (x : \u03b1), p x y := sorry\n\n@[simp] theorem exists_imp_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} : (\u2203 (x : \u03b1), p x) \u2192 b \u2194 \u2200 (x : \u03b1), p x \u2192 b := sorry\n\n/--\nExtract an element from a existential statement, using `classical.some`.\n-/\n-- This enables projection notation.\n\ndef Exists.some {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (P : \u2203 (a : \u03b1), p a) : \u03b1 :=\n  classical.some P\n\n/--\nShow that an element extracted from `P : \u2203 a, p a` using `P.some` satisfies `p`.\n-/\ntheorem Exists.some_spec {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (P : \u2203 (a : \u03b1), p a) : p (Exists.some P) :=\n  classical.some_spec P\n\n--theorem forall_not_of_not_exists (h : \u00ac \u2203 x, p x) : \u2200 x, \u00ac p x :=\n\n--forall_imp_of_exists_imp h\n\ntheorem not_exists_of_forall_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2200 (x : \u03b1), \u00acp x) : \u00ac\u2203 (x : \u03b1), p x :=\n  iff.mpr exists_imp_distrib h\n\n@[simp] theorem not_exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2203 (x : \u03b1), p x) \u2194 \u2200 (x : \u03b1), \u00acp x :=\n  exists_imp_distrib\n\ntheorem not_forall_of_exists_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), \u00acp x) \u2192 \u00ac\u2200 (x : \u03b1), p x :=\n  fun (\u1fb0 : \u2203 (x : \u03b1), \u00acp x) (\u1fb0_1 : \u2200 (x : \u03b1), p x) =>\n    Exists.dcases_on \u1fb0 fun (\u1fb0_w : \u03b1) (\u1fb0_h : \u00acp \u1fb0_w) => idRhs False (\u1fb0_h (\u1fb0_1 \u1fb0_w))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [Decidable (\u2203 (x : \u03b1), \u00acp x)] [(x : \u03b1) \u2192 Decidable (p x)] : (\u00ac\u2200 (x : \u03b1), p x) \u2194 \u2203 (x : \u03b1), \u00acp x := sorry\n\n@[simp] theorem not_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2200 (x : \u03b1), p x) \u2194 \u2203 (x : \u03b1), \u00acp x :=\n  decidable.not_forall\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [Decidable (\u2203 (x : \u03b1), p x)] : (\u00ac\u2200 (x : \u03b1), \u00acp x) \u2194 \u2203 (x : \u03b1), p x :=\n  iff.mp decidable.not_iff_comm not_exists\n\ntheorem not_forall_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2200 (x : \u03b1), \u00acp x) \u2194 \u2203 (x : \u03b1), p x :=\n  decidable.not_forall_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_exists_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [(x : \u03b1) \u2192 Decidable (p x)] : (\u00ac\u2203 (x : \u03b1), \u00acp x) \u2194 \u2200 (x : \u03b1), p x := sorry\n\n@[simp] theorem not_exists_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : (\u00ac\u2203 (x : \u03b1), \u00acp x) \u2194 \u2200 (x : \u03b1), p x :=\n  decidable.not_exists_not\n\n@[simp] theorem forall_true_iff {\u03b1 : Sort u_1} : \u03b1 \u2192 True \u2194 True :=\n  iff_true_intro fun (_x : \u03b1) => 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' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), p a \u2194 True) : (\u2200 (a : \u03b1), p a) \u2194 True :=\n  iff_true_intro fun (_x : \u03b1) => of_iff_true (h _x)\n\n@[simp] theorem forall_2_true_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} : (\u2200 (a : \u03b1), \u03b2 a \u2192 True) \u2194 True :=\n  forall_true_iff' fun (_x : \u03b1) => forall_true_iff\n\n@[simp] theorem forall_3_true_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {\u03b3 : (a : \u03b1) \u2192 \u03b2 a \u2192 Sort u_3} : (\u2200 (a : \u03b1) (b : \u03b2 a), \u03b3 a b \u2192 True) \u2194 True :=\n  forall_true_iff' fun (_x : \u03b1) => forall_2_true_iff\n\n@[simp] theorem forall_const {b : Prop} (\u03b1 : Sort u_1) [i : Nonempty \u03b1] : \u03b1 \u2192 b \u2194 b :=\n  { mp := nonempty.elim i, mpr := fun (hb : b) (x : \u03b1) => hb }\n\n@[simp] theorem exists_const {b : Prop} (\u03b1 : Sort u_1) [i : Nonempty \u03b1] : (\u2203 (x : \u03b1), b) \u2194 b :=\n  { mp := fun (_x : \u2203 (x : \u03b1), b) => (fun (_a : \u2203 (x : \u03b1), b) => Exists.dcases_on _a fun (w : \u03b1) (h : b) => idRhs b h) _x,\n    mpr := nonempty.elim i exists.intro }\n\ntheorem forall_and_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} : (\u2200 (x : \u03b1), p x \u2227 q x) \u2194 (\u2200 (x : \u03b1), p x) \u2227 \u2200 (x : \u03b1), q x := sorry\n\ntheorem exists_or_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), p x \u2228 q x) \u2194 (\u2203 (x : \u03b1), p x) \u2228 \u2203 (x : \u03b1), q x := sorry\n\n@[simp] theorem exists_and_distrib_left {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), q \u2227 p x) \u2194 q \u2227 \u2203 (x : \u03b1), p x := sorry\n\n@[simp] theorem exists_and_distrib_right {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), p x \u2227 q) \u2194 (\u2203 (x : \u03b1), p x) \u2227 q := sorry\n\n@[simp] theorem forall_eq {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2200 (a : \u03b1), a = a' \u2192 p a) \u2194 p a' :=\n  { mp := fun (h : \u2200 (a : \u03b1), a = a' \u2192 p a) => h a' rfl, mpr := fun (h : p a') (a : \u03b1) (e : a = a') => Eq.symm e \u25b8 h }\n\n@[simp] theorem forall_eq' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2200 (a : \u03b1), a' = a \u2192 p a) \u2194 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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2200 (a : \u03b1), a = a' \u2228 q a \u2192 p a) \u2194 p a' \u2227 \u2200 (a : \u03b1), q a \u2192 p a := sorry\n\n@[simp] theorem exists_eq {\u03b1 : Sort u_1} {a' : \u03b1} : \u2203 (a : \u03b1), a = a' :=\n  Exists.intro a' rfl\n\n@[simp] theorem exists_eq' {\u03b1 : Sort u_1} {a' : \u03b1} : \u2203 (a : \u03b1), a' = a :=\n  Exists.intro a' rfl\n\n@[simp] theorem exists_eq_left {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2203 (a : \u03b1), a = a' \u2227 p a) \u2194 p a' := sorry\n\n@[simp] theorem exists_eq_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2203 (a : \u03b1), p a \u2227 a = a') \u2194 p a' :=\n  iff.trans (exists_congr fun (a : \u03b1) => and.comm) exists_eq_left\n\n@[simp] theorem exists_eq_right_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} {a' : \u03b1} : (\u2203 (a : \u03b1), p a \u2227 b \u2227 a = a') \u2194 p a' \u2227 b := sorry\n\n@[simp] theorem exists_eq_right_right' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} {a' : \u03b1} : (\u2203 (a : \u03b1), p a \u2227 b \u2227 a' = a) \u2194 p a' \u2227 b := sorry\n\n@[simp] theorem exists_apply_eq_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) : \u2203 (a : \u03b1), f a = f a' :=\n  Exists.intro a' rfl\n\n@[simp] theorem exists_apply_eq_apply' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) : \u2203 (a : \u03b1), f a' = f a :=\n  Exists.intro a' rfl\n\n@[simp] theorem exists_exists_and_eq_and {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : (\u2203 (b : \u03b2), (\u2203 (a : \u03b1), p a \u2227 f a = b) \u2227 q b) \u2194 \u2203 (a : \u03b1), p a \u2227 q (f a) := sorry\n\n@[simp] theorem exists_exists_eq_and {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} : (\u2203 (b : \u03b2), (\u2203 (a : \u03b1), f a = b) \u2227 p b) \u2194 \u2203 (a : \u03b1), p (f a) := sorry\n\n@[simp] theorem forall_apply_eq_imp_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} : (\u2200 (a : \u03b1) (b : \u03b2), f a = b \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) :=\n  { mp := fun (h : \u2200 (a : \u03b1) (b : \u03b2), f a = b \u2192 p b) (a : \u03b1) => h a (f a) rfl,\n    mpr := fun (h : \u2200 (a : \u03b1), p (f a)) (a : \u03b1) (b : \u03b2) (hab : f a = b) => hab \u25b8 h a }\n\n@[simp] theorem forall_apply_eq_imp_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} : (\u2200 (b : \u03b2) (a : \u03b1), f a = b \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) := sorry\n\n@[simp] theorem forall_eq_apply_imp_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} : (\u2200 (a : \u03b1) (b : \u03b2), b = f a \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) := sorry\n\n@[simp] theorem forall_eq_apply_imp_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} : (\u2200 (b : \u03b2) (a : \u03b1), b = f a \u2192 p b) \u2194 \u2200 (a : \u03b1), p (f a) := sorry\n\n@[simp] theorem forall_apply_eq_imp_iff\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} : (\u2200 (b : \u03b2) (a : \u03b1), p a \u2192 f a = b \u2192 q b) \u2194 \u2200 (a : \u03b1), p a \u2192 q (f a) :=\n  { mp := fun (h : \u2200 (b : \u03b2) (a : \u03b1), p a \u2192 f a = b \u2192 q b) (a : \u03b1) (ha : p a) => h (f a) a ha rfl,\n    mpr := fun (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) (b : \u03b2) (a : \u03b1) (ha : p a) (hb : f a = b) => hb \u25b8 h a ha }\n\n@[simp] theorem exists_eq_left' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2203 (a : \u03b1), a' = a \u2227 p a) \u2194 p a' := sorry\n\n@[simp] theorem exists_eq_right' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a' : \u03b1} : (\u2203 (a : \u03b1), p a \u2227 a' = a) \u2194 p a' := sorry\n\ntheorem exists_comm {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 (a : \u03b1), \u2203 (b : \u03b2), p a b) \u2194 \u2203 (b : \u03b2), \u2203 (a : \u03b1), p a b := sorry\n\ntheorem forall_or_of_or_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {b : Prop} (h : b \u2228 \u2200 (x : \u03b1), p x) (x : \u03b1) : b \u2228 p x :=\n  or.imp_right (fun (h\u2082 : \u2200 (x : \u03b1), p x) => h\u2082 x) h\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_left {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} [Decidable q] : (\u2200 (x : \u03b1), q \u2228 p x) \u2194 q \u2228 \u2200 (x : \u03b1), p x := sorry\n\ntheorem forall_or_distrib_left {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} : (\u2200 (x : \u03b1), q \u2228 p x) \u2194 q \u2228 \u2200 (x : \u03b1), p x :=\n  decidable.forall_or_distrib_left\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_right {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} [Decidable q] : (\u2200 (x : \u03b1), p x \u2228 q) \u2194 (\u2200 (x : \u03b1), p x) \u2228 q := sorry\n\ntheorem forall_or_distrib_right {\u03b1 : Sort u_1} {q : Prop} {p : \u03b1 \u2192 Prop} : (\u2200 (x : \u03b1), p x \u2228 q) \u2194 (\u2200 (x : \u03b1), p x) \u2228 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} (h : function.surjective f) {P : \u03b2 \u2192 Prop} : (\u2200 (a : \u03b1), P (f a)) \u2194 \u2200 (b : \u03b2), P b := sorry\n\n@[simp] theorem exists_prop {p : Prop} {q : Prop} : (\u2203 (h : p), q) \u2194 p \u2227 q := sorry\n\n@[simp] theorem exists_false {\u03b1 : Sort u_1} : \u00ac\u2203 (a : \u03b1), False :=\n  fun (_x : \u2203 (a : \u03b1), False) =>\n    (fun (_a : \u2203 (a : \u03b1), False) => Exists.dcases_on _a fun (w : \u03b1) (h : False) => idRhs False h) _x\n\n@[simp] theorem exists_unique_false {\u03b1 : Sort u_1} : \u00acexists_unique fun (a : \u03b1) => False := sorry\n\ntheorem Exists.fst {b : Prop} {p : b \u2192 Prop} : Exists p \u2192 b :=\n  fun (\u1fb0 : Exists p) => Exists.dcases_on \u1fb0 fun (\u1fb0_w : b) (\u1fb0_h : p \u1fb0_w) => idRhs b \u1fb0_w\n\ntheorem Exists.snd {b : Prop} {p : b \u2192 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 \u2192 Prop} (h : p) : (\u2200 (h' : p), q h') \u2194 q h :=\n  forall_const p\n\n@[simp] theorem exists_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2203 (h' : p), q h') \u2194 q h :=\n  exists_const p\n\n@[simp] theorem forall_prop_of_false {p : Prop} {q : p \u2192 Prop} (hn : \u00acp) : (\u2200 (h' : p), q h') \u2194 True :=\n  iff_true_intro fun (h : p) => not.elim hn h\n\n@[simp] theorem exists_prop_of_false {p : Prop} {q : p \u2192 Prop} : \u00acp \u2192 \u00ac\u2203 (h' : p), q h' :=\n  mt Exists.fst\n\ntheorem exists_unique.exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : exists_unique fun (x : \u03b1) => p x) : \u2203 (x : \u03b1), p x :=\n  exists.elim h fun (x : \u03b1) (hx : (fun (x : \u03b1) => p x) x \u2227 \u2200 (y : \u03b1), p y \u2192 y = x) => Exists.intro x (and.left hx)\n\ntheorem exists_unique.unique {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : exists_unique fun (x : \u03b1) => p x) {y\u2081 : \u03b1} {y\u2082 : \u03b1} (py\u2081 : p y\u2081) (py\u2082 : p y\u2082) : y\u2081 = y\u2082 :=\n  unique_of_exists_unique h py\u2081 py\u2082\n\n@[simp] theorem exists_unique_iff_exists {\u03b1 : Sort u_1} [subsingleton \u03b1] {p : \u03b1 \u2192 Prop} : (exists_unique fun (x : \u03b1) => p x) \u2194 \u2203 (x : \u03b1), p x :=\n  { mp := fun (h : exists_unique fun (x : \u03b1) => p x) => exists_unique.exists h,\n    mpr := Exists.imp fun (x : \u03b1) (hx : p x) => { left := hx, right := fun (y : \u03b1) (_x : p y) => subsingleton.elim y x } }\n\ntheorem exists_unique.elim2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} [\u2200 (x : \u03b1), subsingleton (p x)] {q : (x : \u03b1) \u2192 p x \u2192 Prop} {b : Prop} (h\u2082 : exists_unique fun (x : \u03b1) => exists_unique fun (h : p x) => q x h) (h\u2081 : \u2200 (x : \u03b1) (h : p x), q x h \u2192 (\u2200 (y : \u03b1) (hy : p y), q y hy \u2192 y = x) \u2192 b) : b := sorry\n\ntheorem exists_unique.intro2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} [\u2200 (x : \u03b1), subsingleton (p x)] {q : (x : \u03b1) \u2192 p x \u2192 Prop} (w : \u03b1) (hp : p w) (hq : q w hp) (H : \u2200 (y : \u03b1) (hy : p y), q y hy \u2192 y = w) : exists_unique fun (x : \u03b1) => exists_unique fun (hx : p x) => q x hx := sorry\n\ntheorem exists_unique.exists2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} {q : (x : \u03b1) \u2192 p x \u2192 Prop} (h : exists_unique fun (x : \u03b1) => exists_unique fun (hx : p x) => q x hx) : \u2203 (x : \u03b1), \u2203 (hx : p x), q x hx :=\n  Exists.imp (fun (x : \u03b1) (hx : exists_unique fun (hx : p x) => q x hx) => exists_unique.exists hx)\n    (exists_unique.exists h)\n\ntheorem exists_unique.unique2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Sort u_2} [\u2200 (x : \u03b1), subsingleton (p x)] {q : (x : \u03b1) \u2192 p x \u2192 Prop} (h : exists_unique fun (x : \u03b1) => exists_unique fun (hx : p x) => q x hx) {y\u2081 : \u03b1} {y\u2082 : \u03b1} (hpy\u2081 : p y\u2081) (hqy\u2081 : q y\u2081 hpy\u2081) (hpy\u2082 : p y\u2082) (hqy\u2082 : q y\u2082 hpy\u2082) : y\u2081 = y\u2082 := sorry\n\n/-! ### Classical lemmas -/\n\nnamespace classical\n\n\ntheorem cases {p : Prop \u2192 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 {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : decidable_pred p :=\n  fun (a : \u03b1) => prop_decidable (p a)\n\ntheorem dec_rel {\u03b1 : Sort u_1} (p : \u03b1 \u2192 \u03b1 \u2192 Prop) : DecidableRel p :=\n  fun (a b : \u03b1) => prop_decidable (p a b)\n\ntheorem dec_eq (\u03b1 : Sort u_1) : DecidableEq \u03b1 :=\n  fun (a b : \u03b1) => 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. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html>\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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {C : Sort u} (H0 : C) (H : (a : \u03b1) \u2192 p a \u2192 C) : C :=\n  dite (\u2203 (a : \u03b1), p a) (fun (h : \u2203 (a : \u03b1), p a) => H (some h) sorry) fun (h : \u00ac\u2203 (a : \u03b1), p a) => H0\n\ntheorem some_spec2 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {h : \u2203 (a : \u03b1), p a} (q : \u03b1 \u2192 Prop) (hpq : \u2200 (a : \u03b1), p a \u2192 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 {\u03b1 : Type u_1} {P : \u03b1 \u2192 Prop} (h : \u2203 (x : \u03b1), P x) : Subtype fun (x : \u03b1) => 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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2203 (a : \u03b1), p a) {C : Sort u} (H : (a : \u03b1) \u2192 p a \u2192 C) : C :=\n  H (classical.some h) sorry\n\n/-! ### Declarations about bounded quantifiers -/\n\ntheorem bex_def {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), \u2203 (h : p x), q x) \u2194 \u2203 (x : \u03b1), p x \u2227 q x := sorry\n\ntheorem bex.elim {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {b : Prop} : (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2192 (\u2200 (a : \u03b1) (h : p a), P a h \u2192 b) \u2192 b := sorry\n\ntheorem bex.intro {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} (a : \u03b1) (h\u2081 : p a) (h\u2082 : P a h\u2081) : \u2203 (x : \u03b1), \u2203 (h : p x), P x h :=\n  Exists.intro a (Exists.intro h\u2081 h\u2082)\n\ntheorem ball_congr {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2194 Q x h) : (\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2200 (x : \u03b1) (h : p x), Q x h :=\n  forall_congr fun (x : \u03b1) => forall_congr (H x)\n\ntheorem bex_congr {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2194 Q x h) : (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), Q x h :=\n  exists_congr fun (x : \u03b1) => exists_congr (H x)\n\ntheorem bex_eq_left {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a : \u03b1} : (\u2203 (x : \u03b1), \u2203 (_x : x = a), p x) \u2194 p a := sorry\n\ntheorem ball.imp_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2192 Q x h) (h\u2081 : \u2200 (x : \u03b1) (h : p x), P x h) (x : \u03b1) (h : p x) : Q x h :=\n  H x h (h\u2081 x h)\n\ntheorem bex.imp_right {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {Q : (x : \u03b1) \u2192 p x \u2192 Prop} (H : \u2200 (x : \u03b1) (h : p x), P x h \u2192 Q x h) : (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2192 \u2203 (x : \u03b1), \u2203 (h : p x), Q x h := sorry\n\ntheorem ball.imp_left {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (H : \u2200 (x : \u03b1), p x \u2192 q x) (h\u2081 : \u2200 (x : \u03b1), q x \u2192 r x) (x : \u03b1) (h : p x) : r x :=\n  h\u2081 x (H x h)\n\ntheorem bex.imp_left {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (H : \u2200 (x : \u03b1), p x \u2192 q x) : (\u2203 (x : \u03b1), \u2203 (_x : p x), r x) \u2192 \u2203 (x : \u03b1), \u2203 (_x : q x), r x := sorry\n\ntheorem ball_of_forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (h : \u2200 (x : \u03b1), p x) (x : \u03b1) : p x :=\n  h x\n\ntheorem forall_of_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (H : \u2200 (x : \u03b1), p x) (h : \u2200 (x : \u03b1), p x \u2192 q x) (x : \u03b1) : q x :=\n  h x (H x)\n\ntheorem bex_of_exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (H : \u2200 (x : \u03b1), p x) : (\u2203 (x : \u03b1), q x) \u2192 \u2203 (x : \u03b1), \u2203 (_x : p x), q x :=\n  fun (\u1fb0 : \u2203 (x : \u03b1), q x) =>\n    Exists.dcases_on \u1fb0\n      fun (\u1fb0_w : \u03b1) (\u1fb0_h : q \u1fb0_w) => idRhs (\u2203 (x : \u03b1), \u2203 (_x : p x), q x) (Exists.intro \u1fb0_w (Exists.intro (H \u1fb0_w) \u1fb0_h))\n\ntheorem exists_of_bex {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), \u2203 (_x : p x), q x) \u2192 \u2203 (x : \u03b1), q x := sorry\n\n@[simp] theorem bex_imp_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {b : Prop} : (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2192 b \u2194 \u2200 (x : \u03b1) (h : p x), P x h \u2192 b := sorry\n\ntheorem not_bex {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u00ac\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2194 \u2200 (x : \u03b1) (h : p x), \u00acP x h :=\n  bex_imp_distrib\n\ntheorem not_ball_of_bex_not {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h) \u2192 \u00ac\u2200 (x : \u03b1) (h : p x), P x h := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} [Decidable (\u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h)] [(x : \u03b1) \u2192 (h : p x) \u2192 Decidable (P x h)] : (\u00ac\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h := sorry\n\ntheorem not_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u00ac\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h :=\n  decidable.not_ball\n\ntheorem ball_true_iff {\u03b1 : Sort u_1} (p : \u03b1 \u2192 Prop) : (\u2200 (x : \u03b1), p x \u2192 True) \u2194 True :=\n  iff_true_intro fun (h : \u03b1) (hrx : p h) => trivial\n\ntheorem ball_and_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {Q : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u2200 (x : \u03b1) (h : p x), P x h \u2227 Q x h) \u2194 (\u2200 (x : \u03b1) (h : p x), P x h) \u2227 \u2200 (x : \u03b1) (h : p x), Q x h :=\n  iff.trans (forall_congr fun (x : \u03b1) => forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} {Q : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u2203 (x : \u03b1), \u2203 (h : p x), P x h \u2228 Q x h) \u2194 (\u2203 (x : \u03b1), \u2203 (h : p x), P x h) \u2228 \u2203 (x : \u03b1), \u2203 (h : p x), Q x h :=\n  iff.trans (exists_congr fun (x : \u03b1) => exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} : (\u2200 (x : \u03b1), p x \u2228 q x \u2192 r x) \u2194 (\u2200 (x : \u03b1), p x \u2192 r x) \u2227 \u2200 (x : \u03b1), q x \u2192 r x :=\n  iff.trans (forall_congr fun (x : \u03b1) => or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib {\u03b1 : Sort u_1} {r : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} : (\u2203 (x : \u03b1), \u2203 (_x : p x \u2228 q x), r x) \u2194 (\u2203 (x : \u03b1), \u2203 (_x : p x), r x) \u2228 \u2203 (x : \u03b1), \u2203 (_x : q x), r x := sorry\n\nnamespace classical\n\n\ntheorem not_ball {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {P : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u00ac\u2200 (x : \u03b1) (h : p x), P x h) \u2194 \u2203 (x : \u03b1), \u2203 (h : p x), \u00acP x h :=\n  not_ball\n\nend classical\n\n\ntheorem ite_eq_iff {\u03b1 : Sort u_1} {p : Prop} [Decidable p] {a : \u03b1} {b : \u03b1} {c : \u03b1} : ite p a b = c \u2194 p \u2227 a = c \u2228 \u00acp \u2227 b = c := sorry\n\n@[simp] theorem ite_eq_left_iff {\u03b1 : Sort u_1} {p : Prop} [Decidable p] {a : \u03b1} {b : \u03b1} : ite p a b = a \u2194 \u00acp \u2192 b = a := sorry\n\n@[simp] theorem ite_eq_right_iff {\u03b1 : Sort u_1} {p : Prop} [Decidable p] {a : \u03b1} {b : \u03b1} : ite p a b = b \u2194 p \u2192 a = b := sorry\n\n/-! ### Declarations about `nonempty` -/\n\nprotected instance has_zero.nonempty {\u03b1 : Type u} [HasZero \u03b1] : Nonempty \u03b1 :=\n  Nonempty.intro 0\n\nprotected instance has_one.nonempty {\u03b1 : Type u} [HasOne \u03b1] : Nonempty \u03b1 :=\n  Nonempty.intro 1\n\ntheorem exists_true_iff_nonempty {\u03b1 : Sort u_1} : (\u2203 (a : \u03b1), True) \u2194 Nonempty \u03b1 := sorry\n\n@[simp] theorem nonempty_Prop {p : Prop} : Nonempty p \u2194 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 {\u03b1 : Type u} : \u00acNonempty \u03b1 \u2194 \u03b1 \u2192 False := sorry\n\n@[simp] theorem nonempty_sigma {\u03b1 : Type u} {\u03b3 : \u03b1 \u2192 Type w} : Nonempty (sigma fun (a : \u03b1) => \u03b3 a) \u2194 \u2203 (a : \u03b1), Nonempty (\u03b3 a) := sorry\n\n@[simp] theorem nonempty_subtype {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : Nonempty (Subtype p) \u2194 \u2203 (a : \u03b1), p a := sorry\n\n@[simp] theorem nonempty_prod {\u03b1 : Type u} {\u03b2 : Type v} : Nonempty (\u03b1 \u00d7 \u03b2) \u2194 Nonempty \u03b1 \u2227 Nonempty \u03b2 := sorry\n\n@[simp] theorem nonempty_pprod {\u03b1 : Sort u} {\u03b2 : Sort v} : Nonempty (PProd \u03b1 \u03b2) \u2194 Nonempty \u03b1 \u2227 Nonempty \u03b2 := sorry\n\n@[simp] theorem nonempty_sum {\u03b1 : Type u} {\u03b2 : Type v} : Nonempty (\u03b1 \u2295 \u03b2) \u2194 Nonempty \u03b1 \u2228 Nonempty \u03b2 := sorry\n\n@[simp] theorem nonempty_psum {\u03b1 : Sort u} {\u03b2 : Sort v} : Nonempty (psum \u03b1 \u03b2) \u2194 Nonempty \u03b1 \u2228 Nonempty \u03b2 := sorry\n\n@[simp] theorem nonempty_psigma {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} : Nonempty (psigma \u03b2) \u2194 \u2203 (a : \u03b1), Nonempty (\u03b2 a) := sorry\n\n@[simp] theorem nonempty_empty : \u00acNonempty 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 {\u03b1 : Type u} : Nonempty (ulift \u03b1) \u2194 Nonempty \u03b1 := sorry\n\n@[simp] theorem nonempty_plift {\u03b1 : Sort u} : Nonempty (plift \u03b1) \u2194 Nonempty \u03b1 := sorry\n\n@[simp] theorem nonempty.forall {\u03b1 : Sort u} {p : Nonempty \u03b1 \u2192 Prop} : (\u2200 (h : Nonempty \u03b1), p h) \u2194 \u2200 (a : \u03b1), p (Nonempty.intro a) := sorry\n\n@[simp] theorem nonempty.exists {\u03b1 : Sort u} {p : Nonempty \u03b1 \u2192 Prop} : (\u2203 (h : Nonempty \u03b1), p h) \u2194 \u2203 (a : \u03b1), p (Nonempty.intro a) := sorry\n\ntheorem classical.nonempty_pi {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} : Nonempty ((a : \u03b1) \u2192 \u03b2 a) \u2194 \u2200 (a : \u03b1), Nonempty (\u03b2 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' {\u03b1 : Sort u} [h : Nonempty \u03b1] : Inhabited \u03b1 :=\n  { default := Classical.choice h }\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def nonempty.some {\u03b1 : Sort u} (h : Nonempty \u03b1) : \u03b1 :=\n  Classical.choice h\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def classical.arbitrary (\u03b1 : Sort u) [h : Nonempty \u03b1] : \u03b1 :=\n  Classical.choice h\n\n/-- Given `f : \u03b1 \u2192 \u03b2`, if `\u03b1` is nonempty then `\u03b2` is also nonempty.\n  `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/\ntheorem nonempty.map {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) : Nonempty \u03b1 \u2192 Nonempty \u03b2 :=\n  fun (\u1fb0 : Nonempty \u03b1) => nonempty.dcases_on \u1fb0 fun (\u1fb0 : \u03b1) => idRhs (Nonempty \u03b2) (Nonempty.intro (f \u1fb0))\n\nprotected theorem nonempty.map2 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : Nonempty \u03b1 \u2192 Nonempty \u03b2 \u2192 Nonempty \u03b3 :=\n  fun (\u1fb0 : Nonempty \u03b1) (\u1fb0_1 : Nonempty \u03b2) =>\n    nonempty.dcases_on \u1fb0\n      fun (\u1fb0_1_1 : \u03b1) => nonempty.dcases_on \u1fb0_1 fun (\u1fb0 : \u03b2) => idRhs (Nonempty \u03b3) (Nonempty.intro (f \u1fb0_1_1 \u1fb0))\n\nprotected theorem nonempty.congr {\u03b1 : Sort u} {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b1) : Nonempty \u03b1 \u2194 Nonempty \u03b2 :=\n  { mp := nonempty.map f, mpr := nonempty.map g }\n\ntheorem nonempty.elim_to_inhabited {\u03b1 : Sort u_1} [h : Nonempty \u03b1] {p : Prop} (f : Inhabited \u03b1 \u2192 p) : p :=\n  nonempty.elim h (f \u2218 Inhabited.mk)\n\nprotected instance prod.nonempty {\u03b1 : Type u_1} {\u03b2 : Type u_2} [h : Nonempty \u03b1] [h2 : Nonempty \u03b2] : Nonempty (\u03b1 \u00d7 \u03b2) :=\n  nonempty.elim h fun (g : \u03b1) => nonempty.elim h2 fun (g2 : \u03b2) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (P : Prop) [Decidable P] (x : P \u2192 \u03b1) (y : \u00acP \u2192 \u03b1) : f (dite P x y) = dite P (fun (h : P) => f (x h)) fun (h : \u00acP) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (P : Prop) [Decidable P] (x : \u03b1) (y : \u03b1) : f (ite P x y) = ite P (f x) (f y) :=\n  apply_dite f P (fun (_x : P) => x) fun (_x : \u00acP) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop) [Decidable P] (a : P \u2192 \u03b1) (b : \u00acP \u2192 \u03b1) (c : P \u2192 \u03b2) (d : \u00acP \u2192 \u03b2) : f (dite P a b) (dite P c d) = dite P (fun (h : P) => f (a h) (c h)) fun (h : \u00acP) => 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop) [Decidable P] (a : \u03b1) (b : \u03b1) (c : \u03b2) (d : \u03b2) : 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 : \u00acP) => b) (fun (_x : P) => c) fun (_x : \u00acP) => d\n\n/-- A 'dite' producing a `Pi` type `\u03a0 a, \u03b2 a`, applied to a value `x : \u03b1`\nis a `dite` that applies either branch to `x`. -/\ntheorem dite_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (P : Prop) [Decidable P] (f : P \u2192 (a : \u03b1) \u2192 \u03b2 a) (g : \u00acP \u2192 (a : \u03b1) \u2192 \u03b2 a) (x : \u03b1) : dite P f g x = dite P (fun (h : P) => f h x) fun (h : \u00acP) => g h x := sorry\n\n/-- A 'ite' producing a `Pi` type `\u03a0 a, \u03b2 a`, applied to a value `x : \u03b1`\nis a `ite` that applies either branch to `x` -/\ntheorem ite_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (P : Prop) [Decidable P] (f : (a : \u03b1) \u2192 \u03b2 a) (g : (a : \u03b1) \u2192 \u03b2 a) (x : \u03b1) : ite P f g x = ite P (f x) (g x) :=\n  dite_apply P (fun (_x : P) => f) (fun (_x : \u00acP) => 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 {\u03b1 : Sort u_1} (P : Prop) [Decidable P] (x : \u00acP \u2192 \u03b1) (y : \u00ac\u00acP \u2192 \u03b1) : dite (\u00acP) 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 {\u03b1 : Sort u_1} (P : Prop) [Decidable P] (x : \u03b1) (y : \u03b1) : ite (\u00acP) x y = ite P y x :=\n  dite_not P (fun (_x : \u00acP) => x) fun (_x : \u00ac\u00acP) => y\n\ntheorem ite_and {\u03b1 : Sort u_1} {p : Prop} {q : Prop} [Decidable p] [Decidable q] {x : \u03b1} {y : \u03b1} : ite (p \u2227 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  \u2200 {\u03b1 \u03b2 : Sort*} {a : \u03b1} {a' : \u03b2} (h\u2082 : a == a'), (eq.mp (type_eq_of_heq h\u2082) a) = a'\n| \u03b1 ._ a a' heq.rfl := rfl\n\nnamespace sigma\nvariables {\u03b1\u2081 \u03b1\u2082 \u03b1\u2083 : Type u}\nvariables {\u03b2\u2081 : \u03b1\u2081 \u2192 Type v} {\u03b2\u2082 : \u03b1\u2082 \u2192 Type v} {\u03b2\u2083 : \u03b1\u2083 \u2192 Type v}\nvariables {g : sigma \u03b2\u2082 \u2192 sigma \u03b2\u2083} {f : sigma \u03b2\u2081 \u2192 sigma \u03b2\u2082}\n\ntheorem eq_fst {s\u2081 s\u2082 : sigma \u03b2\u2081} : s\u2081 = s\u2082 \u2192 s\u2081.1 = s\u2082.1 :=\nby cases s\u2081; cases s\u2082; cc\n\ntheorem eq_snd {s\u2081 s\u2082 : sigma \u03b2\u2081} : s\u2081 = s\u2082 \u2192 s\u2081.2 == s\u2082.2 :=\nby cases s\u2081; cases s\u2082; cc\n\n@[extensionality]\nlemma ext {x\u2080 x\u2081 : sigma \u03b2\u2081}\n  (h\u2080 : x\u2080.1 = x\u2081.1)\n  (h\u2081 : x\u2080.1 = x\u2081.1 \u2192 x\u2080.2 == x\u2081.2) :\n  x\u2080 = x\u2081 :=\nby casesm* sigma _; cases h\u2080; cases h\u2081 h\u2080; refl\n\nlemma eta (x : sigma \u03b2\u2081) : sigma.mk x.1 x.2 = x :=\nby cases x; refl\n\nend sigma\n\nnamespace list\n\ndef zip_with\u2083 {\u03b1 \u03b2 \u03b3 \u03c6} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03c6) : list \u03b1 \u2192 list \u03b2 \u2192 list \u03b3 \u2192 list \u03c6\n| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with\u2083 xs ys zs\n| _ _ _ := []\n\nvariables {m : Type u \u2192 Type v} [applicative m]\n\ndef mzip_with\u2083 {\u03b1 \u03b2 \u03b3 \u03c6} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 m \u03c6) : list \u03b1 \u2192 list \u03b2 \u2192 list \u03b3 \u2192 m (list \u03c6)\n| (x::xs) (y::ys) (z::zs) := (::) <$> f x y z <*> mzip_with\u2083 xs ys zs\n| _ _ _ := pure []\n\ndef mzip_with\u2084 {\u03b1 \u03b2 \u03b3 \u03c6 \u03c8} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03c6 \u2192 m \u03c8) :\n  list \u03b1 \u2192 list \u03b2 \u2192 list \u03b3 \u2192 list \u03c6 \u2192 m (list \u03c8)\n| (w :: ws) (x::xs) (y::ys) (z::zs) := (::) <$> f w x y z <*> mzip_with\u2084 ws xs ys zs\n| _ _ _ _ := pure []\n\n-- def mmap_enum_if' {\u03b1} (p : \u03b1 \u2192 Prop) [decidable_pred p] (f : \u2115 \u2192 \u03b1 \u2192 m \u03b1) : \u2115 \u2192 list \u03b1 \u2192 m (list \u03b1)\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 {\u03b1} (p : \u03b1 \u2192 Prop) [decidable_pred p] (f : \u2115 \u2192 \u03b1 \u2192 m \u03b1) : list \u03b1 \u2192 m (list \u03b1) :=\n-- mmap_enum_if' p f 0\n\nend list\nnamespace roption\nvariables {\u03b1 : Type*} {\u03b2 : Type*} {\u03b3 : Type*}\n\nopen function\nlemma assert_if_neg {p : Prop}\n  (x : p \u2192 roption \u03b1)\n  (h : \u00ac p)\n: assert p x = roption.none :=\nby { dsimp [assert,roption.none],\n     have : (\u2203 (h : p), (x h).dom) \u2194 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 \u2192 roption \u03b1)\n  (h : p)\n: assert p x = x h :=\nby { dsimp [assert],\n     have : (\u2203 (h : p), (x h).dom) \u2194 (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 {\u03b1 \u03b2 : Type*} (f : \u03b1 \u2192 roption \u03b2)\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 >>= (\u03bb (_x : punit), pure punit.star : punit \u2192 m punit) = x :=\nby { transitivity,\n     { apply congr_arg, ext z, cases z, refl },\n     { simp } }\n\nvariables {\u03b1 \u03b2 \u03b3 : Type u}\nvariables {m : Type u \u2192 Type v} [monad m]\n\n@[reducible]\ndef pipe (a : \u03b1 \u2192 m \u03b2) (b : \u03b2 \u2192 m \u03b3) : \u03b1 \u2192 m \u03b3 :=\n\u03bb x, a x >>= b\n\ninfixr ` >=> `:55 := pipe\n\n@[functor_norm]\nlemma map_bind_eq_bind_comp {\u03b1 \u03b2 \u03b3} {m} [monad m] [is_lawful_monad m]\n  (f : \u03b1 \u2192 \u03b2) (cmd : m \u03b1) (g : \u03b2 \u2192 m \u03b3) :\n  (f <$> cmd) >>= g = cmd >>= g \u2218 f :=\nby rw [\u2190 bind_pure_comp_eq_map,bind_assoc,(\u2218)]; simp\n\n@[functor_norm]\nlemma bind_map {\u03b1 \u03b2 \u03b3} {m} [monad m] [is_lawful_monad m]\n  (f : \u03b1 \u2192 \u03b3 \u2192 \u03b2) (cmd : m \u03b1) (g : \u03b1 \u2192 m \u03b3) :\n  cmd >>= (\u03bb x, f x <$> g x) = do { x \u2190 cmd, y \u2190 g x, pure $ f x y }  :=\nby congr; ext; rw [\u2190 bind_pure (g x),map_bind]; simp\n\n@[functor_norm]\nlemma bind_seq {\u03b1 \u03b2 \u03b3 : Type u} {m} [monad m] [is_lawful_monad m]\n  (f : \u03b1 \u2192 m (\u03b3 \u2192 \u03b2)) (cmd : m \u03b1) (g : \u03b1 \u2192 m \u03b3) :\n  cmd >>= (\u03bb x, f x <*> g x) = do { x \u2190 cmd, h \u2190 f x, y \u2190 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} {\u03b1 \u03b2 : Type u}\n\nprotected def seq : \u03a0 (x : sum e (\u03b1 \u2192 \u03b2)) (f : sum e \u03b1), sum e \u03b2\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* _ \u2295 _; simp [(<*>),sum.seq,pure,(<$>)];\n   refl\n\nend sum\n\nnamespace functor\ndef foldl (\u03b1 : Type u) (\u03b2 : Type v) := \u03b1 \u2192 \u03b1\ndef foldr (\u03b1 : Type u) (\u03b2 : Type v) := \u03b1 \u2192 \u03b1\n\ninstance foldr.applicative {\u03b1} : applicative (foldr \u03b1) :=\n{ pure := \u03bb _ _, id,\n  seq := \u03bb _ _ f x, f \u2218 x }\n\ninstance foldl.applicative {\u03b1} : applicative (foldl \u03b1) :=\n{ pure := \u03bb _ _, id,\n  seq := \u03bb _ _ f x, x \u2218 f }\n\ninstance foldr.is_lawful_applicative {\u03b1} : is_lawful_applicative (foldr \u03b1) :=\nby refine { .. }; intros; refl\n\ninstance foldl.is_lawful_applicative {\u03b1} : is_lawful_applicative (foldl \u03b1) :=\nby refine { .. }; intros; refl\n\ndef foldr.eval {\u03b1 \u03b2} (x : foldr \u03b1 \u03b2) : \u03b1 \u2192 \u03b1 := x\n\ndef foldl.eval {\u03b1 \u03b2} (x : foldl \u03b1 \u03b2) : \u03b1 \u2192 \u03b1 := x\n\ndef foldl.cons {\u03b1 \u03b2} (x : \u03b1) : foldl (list \u03b1) \u03b2 :=\nlist.cons x\n\ndef foldr.cons {\u03b1 \u03b2} (x : \u03b1) : foldr (list \u03b1) \u03b2 :=\nlist.cons x\n\ndef foldl.cons' {\u03b1} (x : \u03b1) : foldl (list \u03b1) punit :=\nlist.cons x\n\ndef foldl.lift {\u03b1} (x : \u03b1 \u2192 \u03b1) : foldl \u03b1 punit := x\ndef foldr.lift {\u03b1} (x : \u03b1 \u2192 \u03b1) : foldr \u03b1 punit := x\n\nend functor\n\ninstance {\u03b1 : Type u} : traversable (prod.{u u} \u03b1) :=\n{ map := \u03bb \u03b2 \u03b3 f (x : \u03b1 \u00d7 \u03b2), prod.mk x.1 $ f x.2,\n  traverse := \u03bb m _ \u03b2 \u03b3 f (x : \u03b1 \u00d7 \u03b2), by exactI prod.mk x.1 <$> f x.2 }\n\nnamespace traversable\n\nvariables {t : Type u \u2192 Type u} [traversable t]\n\ndef to_list {\u03b1} (x : t \u03b1) : list \u03b1 :=\n@functor.foldr.eval _ (t punit) (traverse functor.foldr.cons x) []\n\nend traversable\n\n/-\nnamespace name\n\n-- def append_suffix : name \u2192 string \u2192 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 {\u03b1} : level \u2192 (name \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 \u03b1\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 \u2218 fold_mvar b f\n| (imax a b) f := fold_mvar a f \u2218 fold_mvar b f\n\nmeta def pred : level \u2192 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 \u2192 key \u2192 Prop)]\nvariables (f : val \u2192 val \u2192 val)\n\n-- def intersect' : list (key \u00d7 val) \u2192 list (key \u00d7 val) \u2192 list (key \u00d7 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 {\u03b1 : Type} (f : \u03b1 \u2192 key) : list \u03b1 \u2192 list \u03b1 := list.merge_sort (on_fun (<) f)\n\n-- end\n\nmeta def filter_map (f : key \u2192 val \u2192 option val') (x : rb_map key val) : rb_map key val' :=\nfold x (mk _ _) $ \u03bba 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 $ \u03bb 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 (\u03bb k x, guard (\u00ac m'.contains k) >> pure x)\n\nend rb_map\nend native\n\nnamespace expr\n\nmeta def replace_all (e : expr) (p : expr \u2192 Prop) [decidable_pred p] (r : expr) : expr :=\ne.replace $ \u03bb e i, guard (p e) >> pure (r.lift_vars 0 i)\n\nmeta def const_params : expr \u2192 list level\n| (const _ ls) := ls\n| _ := []\n\nmeta def sort_univ : expr \u2192 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 $ \u03bb e' i s,\nmatch e' with\n| (sort u) := u.fold_mvar (flip native.rb_set.insert) s\n| (const _ ls) := ls.foldl (\u03bb s' l, l.fold_mvar (flip native.rb_set.insert) s') s\n| _ := s\nend\n\nmeta def instantiate_pi : expr \u2192 list expr \u2192 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 \u2192 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 \u2190 infer_type e >>= pp,\n   e' \u2190 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 _ _) \u2190 get_decl n,\n   t \u2190 pp t, df \u2190 pp df,\n   trace format!\"\\ndef {n} : {t} :=\\n{df}\\n\"\n\nmeta def is_type (e : expr) : tactic bool :=\ndo (expr.sort _) \u2190 infer_type e | pure ff,\n   pure tt\n\nmeta def list_macros : expr \u2192 list (name \u00d7 list expr) | e :=\ne.fold [] (\u03bb 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 \u2190 target,\n   mv  \u2190 mk_meta_var tgt,\n   gs \u2190 get_goals,\n   set_goals [mv],\n   tac,\n   env \u2190 get_env,\n   pr \u2190 env.unfold_untrusted_macros <$> instantiate_mvars mv,\n   set_goals gs,\n   exact pr\n\nmeta def binders : expr \u2192 tactic (list expr)\n| (expr.pi n bi d b) :=\n  do v \u2190 mk_local' n bi d,\n     (::) v <$> binders (b.instantiate_var v)\n| _ := pure []\n\nmeta def rec_args_count (t c : name) : tactic \u2115 :=\ndo ct \u2190 mk_const c >>= infer_type,\n   (list.length \u2218 list.filter (\u03bb v : expr, v.local_type.is_app_of t)) <$> binders ct\n\nmeta def match_induct_hyp (n : name) : list expr \u2192 list expr \u2192 tactic (list $ expr \u00d7 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 \u2190 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 \u2190 get_env,\n   let cs := e.constructors_of n,\n   rs \u2190 cs.mmap (rec_args_count n),\n   pure $ rs.any (\u03bb r, r > 0)\n\nmeta def better_induction (e : expr) : tactic $ list (name \u00d7 list (expr \u00d7 option expr) \u00d7 list (name \u00d7 expr)) :=\ndo t \u2190 infer_type e,\n   let tn := t.get_app_fn.const_name,\n   env \u2190 get_env,\n   focus1 $\n   do vs \u2190 induction e,\n      gs \u2190 get_goals,\n      vs' \u2190 list.mzip_with\u2083 (\u03bb n g (pat : name \u00d7 list expr \u00d7 list (name \u00d7 expr)),\n        do let \u27e8_,args,\u03c3\u27e9 := pat,\n           set_goals [g],\n           nrec \u2190 rec_args_count tn n,\n           let \u27e8args,rec\u27e9 := args.split_at (args.length - nrec),\n           args \u2190 match_induct_hyp tn args rec,\n           pure ((n,args,\u03c3))) (env.constructors_of tn) gs vs,\n      set_goals gs,\n      pure vs'\n\nmeta def extract_def' {\u03b1} (n : name) (trusted : bool) (elab_def : tactic \u03b1) : tactic \u03b1 :=\ndo cxt \u2190 list.map to_implicit <$> local_context,\n   t \u2190 target,\n   (r,d) \u2190 solve_aux t elab_def,\n   d \u2190 instantiate_mvars d,\n   t' \u2190 pis cxt t,\n   d' \u2190 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 \u2192 tactic expr\n| v@(local_const uniq pp bi _) :=\n  do t \u2190 infer_type v,\n     pure $ local_const uniq pp bi t\n| e := pure e\n\nmeta def intron' : \u2115 \u2192 tactic (list expr)\n| 0 := pure []\n| (succ n) := (::) <$> intro1 <*> intron' n\n\nmeta def unpi : expr \u2192 tactic (list expr \u00d7 expr)\n| (pi n bi d b) :=\n  do v \u2190 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 \u2192 expr \u2192 list expr \u2192 tactic expr\n| e (pi _ _ d b) (a :: as) :=\ndo t \u2190 infer_type a,\n   unify t d,\n   e' \u2190 head_beta (e a),\n   b' \u2190 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 \u2190 infer_type e >>= whnf,\n   unify_app_aux e t args\n\nmeta def unify_mapp_aux : expr \u2192 expr \u2192 list (option expr) \u2192 tactic expr\n| e (pi _ _ d b) (none :: as) :=\ndo a \u2190 mk_mvar,\n   t \u2190 infer_type a,\n   unify t d,\n   e' \u2190 head_beta (e a),\n   b' \u2190 whnf (b.instantiate_var a),\n   unify_mapp_aux e' b' as\n| e (pi _ _ d b) (some a :: as) :=\ndo t \u2190 infer_type a,\n   unify t d,\n   e' \u2190 head_beta (e a),\n   b' \u2190 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 \u2190 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 \u2190 get_decl n,\n   let r : reducibility_hints := reducibility_hints.regular 1 tt,\n   env \u2190 get_env,\n   ls \u2190 local_context,\n   sig \u2190 to_expr ``(%%t \u2192 %%out),\n   of_string \u2190 mk_const of_string,\n   (_,df) \u2190 solve_aux sig $ do\n     { match env.structure_fields n with\n       | (some fs) :=\n       do a \u2190 intro1,\n          [(_,xs,_)] \u2190 cases_core a,\n          let l := xs.length,\n          fn' \u2190 mk_const fn,\n          out \u2190 list.mzip_with\u2084 (\u03bb 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 (\u03bb e acc, ``(%%e ++ %%acc)) ``(%%of_string %%(reflect \"\" : expr))) >>= exact,\n          pure ()\n       | none :=\n       do g \u2190 main_goal,\n          a \u2190 intro1,\n          xs \u2190 cases_core a,\n          fn \u2190 mk_const fn,\n          out \u2190 xs.mmap $ \u03bb \u27e8c,xs,_\u27e9,\n            do { out \u2190 xs.mmap $ \u03bb x, to_expr ``(%%of_string \" (\" ++ %%fn %%x ++ %%of_string \")\"),\n                 let c := (c.update_prefix name.anonymous).to_string,\n                 to_expr (out.foldr (\u03bb e acc, ``(%%e ++ %%acc)) ``(%%of_string %%(reflect c : expr))) >>= exact },\n          pure () end },\n   df \u2190 instantiate_mvars df >>= lambdas ls,\n   t \u2190 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) \u2190 target,\n   ls \u2190 local_context,\n   e \u2190 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) \u2190 target,\n   ls \u2190 local_context,\n   e \u2190 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 := \u03bb x, \"`\" ++ x.to_string }\n\nprivate meta def report_invalid_simp_lemma {\u03b1 : Type} (n : name): tactic \u03b1 :=\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 (\u03bb p, (to_fmt p).indent 4))\n  | _ := failed\n  end\n\nprivate meta def add_simps : simp_lemmas \u2192 list name \u2192 tactic simp_lemmas\n| s []      := return s\n| s (n::ns) := do s' \u2190 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 \u00d7 list name) :=\ndo\n  p \u2190 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 \u2190 is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s \u2190 s.add_simp n, return (s, u))\n    <|>\n    (do eqns \u2190 get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s \u2190 add_simps s eqns, return (s, u))\n    <|>\n    (do env \u2190 get_env, guard (env.is_projection n).is_some, return (s, n::u))\n    <|>\n    report_invalid_simp_lemma n\n  | _ :=\n    (do e \u2190 i_to_expr_no_subgoals p, b \u2190 is_valid_simp_lemma e, guard b, try (save_type_info e ref), s \u2190 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 \u00d7 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 \u2190 i_to_expr_no_subgoals p, s \u2190 s.add new_e, return (s, u)\nend\n\nmeta def simp_lemmas.append_pexprs : simp_lemmas \u2192 list name \u2192 list pexpr \u2192 tactic (simp_lemmas \u00d7 list name)\n| s u []      := return (s, u)\n| s u (l::ls) := do (s, u) \u2190 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 \u00d7 list (name \u00d7 expr)) :=\ndo vs' \u2190 intron' vs.length,\n   let \u03c3 := (vs.map expr.local_uniq_name).zip vs',\n   pure (vs', \u03c3)\nopen interactive.types interactive lean.parser\n\n@[user_command]\nmeta def test_signature_cmd (_ : parse $ tk \"#test\") : lean.parser unit :=\ndo e \u2190 ident,\nshow tactic unit, from\ndo d \u2190 get_decl e,\n   let e := @const tt d.to_name d.univ_levels,\n   t \u2190 infer_type e >>= pp,\n   e.collect_meta_univ.enum.mmap' $ \u03bb \u27e8i,v\u27e9, unify_univ (level.mvar v) (level.param (\"u_\" ++ to_string i : string)),\n   e \u2190 instantiate_mvars e,\n   e \u2190 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 := \u03bb es,\n    do t \u2190 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 {\u03b1} (tac : tactic \u03b1) : tactic \u03b1\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 {\u03b1} : subsingleton (fin 0 \u2192 \u03b1) :=\nsubsingleton.intro $ \u03bb a b, funext $ \u03bb 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 : \u2115) (fmt : format) (p' : \u2115) : format :=\nif p' < p then format.paren fmt else fmt\n\nmeta def fmt_binder (n : name) : binder_info \u2192 format \u2192 format\n| binder_info.default t := format!\"({n} : {t})\"\n| binder_info.implicit t := format!\"{{{n} : {t}}\"\n| binder_info.strict_implicit t := format!\"\u2983{n} : {t}\u2984\"\n| binder_info.inst_implicit t := format!\"[{n} : {t}]\"\n| binder_info.aux_decl t := \"_\"\n\nmeta def parsable_printer' : expr \u2192 list name \u2192 \u2115 \u2192 format\n| (expr.var a) l := \u03bb _, format!\"@{(l.nth a).get_or_else name.anonymous}\"\n| (expr.sort level.zero) l := \u03bb _, to_fmt \"Prop\"\n| (expr.sort (level.succ u)) l := \u03bb _, format!\"Type.{{{u}}\"\n| (expr.sort u) l := \u03bb _, format!\"Sort.{{{u}}\"\n| (expr.const a []) l := \u03bb _, format!\"@{a}\"\n| (expr.const a ls) l := \u03bb _, format!\"@{a}.{{{format.intercalate  \\\" \\\" $ list.map to_fmt ls}}\"\n| (expr.mvar a a_1 a_2) l := \u03bb _, to_fmt a\n| (expr.local_const a a_1 a_2 a_3) l := \u03bb _, 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!\"\u03bb {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!\"\u03a0 {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} \u2192 {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 := \u03bb _, 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 \u2115 :=\n{ init := 0,\n  step := \u03bb i,\n  do j \u2190 vm.stack_size,\n     if i = j then pure i else do\n       fn \u2190 vm.curr_fn,\n       vm.put_str $ (list.repeat ' ' j).as_string ++ fn.to_string,\n       pure j }\n\nlemma mpr_mpr : \u03a0 {\u03b1 \u03b2} (h : \u03b1 = \u03b2) (h' : \u03b2 = \u03b1) (x : \u03b1), 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 \u2192 (\u03b1: MLIRType \u03b4) \u00d7 \u03b1` 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 {\u03b1 \u03c3: Type} {\u03b5: \u03c3 \u2192 Type}\n\n-- SSAScope\n\ndef SSAScope (\u03b4: Dialect \u03b1 \u03c3 \u03b5) :=\n  List (SSAVal \u00d7 (\u03c4: MLIRType \u03b4) \u00d7 \u03c4.eval)\n\n@[simp]\ndef SSAScope.getT {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal):\n  SSAScope \u03b4 \u2192 Option ((\u03c4: MLIRType \u03b4) \u00d7 \u03c4.eval)\n  | [] => none\n  | \u27e8name', \u03c4, v\u27e9 :: l =>\n      if name' = name then some \u27e8\u03c4,v\u27e9 else getT name l\n\n@[simp]\ndef SSAScope.get {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal):\n  SSAScope \u03b4 \u2192 (\u03c4: MLIRType \u03b4) \u2192 Option \u03c4.eval\n  | [], _ => none\n  | \u27e8name', \u03c4', v'\u27e9 :: l, \u03c4 =>\n      if H: name' = name then\n        if H': \u03c4' = \u03c4 then\n          some (cast (by simp [H']) v')\n        else\n          none\n      else get name l \u03c4\n\n@[simp]\ndef SSAScope.set {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal) (\u03c4: MLIRType \u03b4) (v: \u03c4.eval):\n  SSAScope \u03b4 \u2192 SSAScope \u03b4\n  | [] => [\u27e8name, \u03c4, v\u27e9]\n  | \u27e8name', \u03c4', v'\u27e9 :: l =>\n      if name' = name\n      then \u27e8name', \u03c4, v\u27e9 :: l\n      else \u27e8name', \u03c4', v'\u27e9 :: set name \u03c4 v l\n\ndef SSAScope.str {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (scope: SSAScope \u03b4): String :=\n  \"\\n\".intercalate <| scope.map fun \u27e8name, \u03c4, v\u27e9 => s!\"{name} = {v} : {\u03c4}\"\n\n-- Leibniz-ish equality\ndef SSAScope.equiv {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (scope1 scope2: SSAScope \u03b4): Prop :=\n  \u2200 name \u03c4, scope1.get name \u03c4 = scope2.get name \u03c4\n\ninstance {\u03b4: Dialect \u03b1 \u03c3 \u03b5}: ToString (SSAScope \u03b4) 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 \u27e8name', _, _\u27e9 => name' == name)\n\ndef SSAScope.free (name: SSAVal) (l: SSAScope): Bool :=\n  l.all (fun \u27e8name', _, _\u27e9 => name' != name)\n\ndef SSAScope.maps (l: SSAScope) (name: SSAVal) (\u03c4: MLIRTy) (v: \u03c4.eval) :=\n  l.Mem \u27e8name, \u03c4, v\u27e9 -/\n\n/-\n### SSAScope proofs\n-/\n\ntheorem SSAScope.equiv_refl {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (scope: SSAScope \u03b4):\n  scope.equiv scope := by intros name \u03c4; rfl\n\ntheorem SSAScope.equiv_symm {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983scope scope': SSAScope \u03b4\u2984:\n    scope.equiv scope' \u2192 scope'.equiv scope := by\n  intros H name \u03c4\n  specialize H name \u03c4\n  simp [H]\n\ntheorem SSAScope.equiv_trans {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983scope\u2081 scope\u2082: SSAScope \u03b4\u2984:\n    scope\u2081.equiv scope\u2082 \u2192\n    \u2200 \u2983scope\u2083\u2984, scope\u2082.equiv scope\u2083 \u2192\n    scope\u2081.equiv scope\u2083 := by\n  intros H1 scope\u2083 H2 name \u03c4\n  specialize H1 name \u03c4\n  specialize H2 name \u03c4\n  simp [H1, H2]\n\ntheorem SSAScope.get_to_getT {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal)\n    (scope: SSAScope \u03b4) (\u03c4: MLIRType \u03b4):\n  scope.get name \u03c4 =\n    match scope.getT name with\n    | none => none\n    | some \u27e8\u03c4', v'\u27e9 =>\n      if H: \u03c4' = \u03c4 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 {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983name: SSAVal\u2984\n  \u2983scope: SSAScope \u03b4\u2984 \u2983\u03c4: MLIRType \u03b4\u2984 \u2983v\u2984:\n    scope.get name \u03c4 = some v \u2192\n    scope.getT name = some \u27e8\u03c4, v\u27e9 := by\n  rw [get_to_getT]\n  split <;> simp at * <;> try contradiction\n  case h_2 _ \u03c4' _ Hget =>\n  byCases H\u03c4: \u03c4' = \u03c4\n  intros H\n  rw [\u2190H, Hget]\n  rfl\n\ntheorem SSAScope.getT_none_get {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983name: SSAVal\u2984\n  \u2983scope: SSAScope \u03b4\u2984:\n    scope.getT name = none \u2192\n    \u2200 \u03c4, scope.get name \u03c4 = 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 {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983name: SSAVal\u2984\n  \u2983scope: SSAScope \u03b4\u2984 \u2983\u03c4 v\u2984:\n    scope.getT name = some \u27e8\u03c4, v\u27e9 \u2192\n    scope.get name \u03c4 = some v := by\n  induction scope <;> simp\n  case cons head tail HInd =>\n  byCases Hname: head.fst = name <;> try assumption\n  have \u27e8headName, head\u03c4, headVal\u27e9 := head; simp at *\n  intros H; cases H\n  simp;\n\ntheorem SSAScope.get_none_getT {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983name: SSAVal\u2984\n  \u2983scope: SSAScope \u03b4\u2984:\n    (\u2200 \u03c4, scope.get name \u03c4 = none) \u2192\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 \u2983v v': SSAVal\u2984:\n    v' \u2260 v \u2192\n    \u2200 \u2983scope: SSAScope \u03b4\u2984 \u2983\u03c4: MLIRType \u03b4\u2984 \u2983val\u2984,\n    getT v (set v' \u03c4 val scope) = getT v scope := by\n  intros Hne scope \u03c4 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 \u03b4) (v: SSAVal) (\u03c4: MLIRType \u03b4) val:\n    getT v (set v \u03c4 val scope) = some \u27e8\u03c4, val\u27e9  := 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 \u2983v v': SSAVal\u2984:\n    v' \u2260 v \u2192\n    \u2200 \u2983scope: SSAScope \u03b4\u2984 \u2983\u03c4 \u03c4' val\u2984,\n    get v (set v' \u03c4 val scope) \u03c4' = get v scope \u03c4' := by\n  intros Hne scope \u03c4 \u03c4' 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 \u2983\u03c4 \u03c4': MLIRType \u03b4\u2984:\n    \u03c4' \u2260 \u03c4 \u2192\n    \u2200 \u2983scope: SSAScope \u03b4\u2984 \u2983v: SSAVal\u2984 \u2983val\u2984,\n    get v (set v \u03c4' val scope) \u03c4 = 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 \u03b4) (\u03c4: MLIRType \u03b4) val:\n    get v (set v \u03c4 val scope) \u03c4 = 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 \u2983v v': SSAVal\u2984:\n    v' \u2260 v \u2192\n    \u2200 \u2983scope: SSAScope \u03b4\u2984 \u2983\u03c4 \u03c4' val val'\u2984,\n    (set v \u03c4 val (set v' \u03c4' val' scope)).equiv (set v' \u03c4' val' (set v \u03c4 val scope)) := by\n  intros Hne scope \u03c4 \u03c4' val val'\n  induction scope with\n  | nil =>\n    simp; simp [Hne, Hne.symm]\n    simp [equiv]; intros name \u03c4''\n    byCases Hv: v' = name\n    byCases H\u03c4: \u03c4' = \u03c4'' <;> 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 (\u03b4: Dialect \u03b1 \u03c3 \u03b5) :=\n  | One (scope: SSAScope \u03b4)\n  | Cons (head: SSAScope \u03b4) (tail: SSAEnv \u03b4)\n\ninstance: Inhabited (SSAEnv \u03b4) where\n  default := .One []\n\n-- An SSA environment with a single empty SSAScope\ndef SSAEnv.empty {\u03b4: Dialect \u03b1 \u03c3 \u03b5}: SSAEnv \u03b4 := One []\n\ndef SSAEnv.str {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (env: SSAEnv \u03b4): String :=\n  match env with\n  | One s => s.toString\n  | Cons head tail => head.toString ++ \"---\\n\" ++ tail.str\n\ninstance {\u03b4: Dialect \u03b1 \u03c3 \u03b5}: ToString (SSAEnv \u03b4) where\n  toString := SSAEnv.str\n\ndef SSAEnv.getT {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal):\n  SSAEnv \u03b4 \u2192 Option ((\u03c4: MLIRType \u03b4) \u00d7 \u03c4.eval)\n  | One s => s.getT name\n  | Cons s l => s.getT name <|> getT name l\n\ndef SSAEnv.get {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal) (\u03c4: MLIRType \u03b4) (env: SSAEnv \u03b4) : Option (\u03c4.eval) :=\n  match env.getT name with\n  | none => none\n  | some \u27e8\u03c4', v'\u27e9 =>\n      if H': \u03c4' = \u03c4 then\n        some (cast (by simp [H']) v')\n      else\n        none\n\ndef SSAEnv.set {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (name: SSAVal) (\u03c4: MLIRType \u03b4) (v: \u03c4.eval):\n  SSAEnv \u03b4 \u2192 SSAEnv \u03b4\n  | One s => One (s.set name \u03c4 v)\n  | Cons s l => Cons (s.set name \u03c4 v) l\n\n@[simp] def SSAEnv.set_One:\n  SSAEnv.set name \u03c4 v (.One scope) = .One (scope.set name \u03c4 v) := rfl\n\ninstance {\u03b4: Dialect \u03b1 \u03c3 \u03b5}: DecidableEq ((\u03c4: MLIRType \u03b4) \u00d7 \u03c4.eval) :=\n  fun \u27e8\u03c4\u2081, v\u2081\u27e9 \u27e8\u03c4\u2082, v\u2082\u27e9 =>\n    if H: \u03c4\u2081 = \u03c4\u2082 then\n      if H': cast (by simp [H]) v\u2081 = v\u2082 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\u2081 env\u2082: SSAEnv \u03b4): Bool :=\n  l.all (fun v => env\u2081.getT v == env\u2082.getT v)\n\n-- Leibniz-ish equality\ndef SSAEnv.equiv (env\u2081 env\u2082: SSAEnv \u03b4): Prop :=\n  \u2200 name \u03c4, env\u2081.get name \u03c4 = env\u2082.get name \u03c4\n\n-- SSAEnv theorems\n\ntheorem SSAEnv.equiv_rfl {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (env: SSAEnv \u03b4):\n  env.equiv env := by intros v \u03c4; rfl\n\ntheorem SSAEnv.equiv_symm {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983env env': SSAEnv \u03b4\u2984:\n    env.equiv env' \u2192 env'.equiv env := by\n  intros H name\n  specialize H name\n  simp [H]\n\ntheorem SSAEnv.equiv_trans {\u03b4: Dialect \u03b1 \u03c3 \u03b5}:\n    \u2200 \u2983env\u2081 env\u2082: SSAEnv \u03b4\u2984, env\u2081.equiv env\u2082 \u2192\n    \u2200 \u2983env\u2083\u2984, env\u2082.equiv env\u2083 \u2192\n    env\u2081.equiv env\u2083 := by\n  intros _ _ H1 _ H2 name\n  specialize H1 name\n  specialize H2 name\n  simp [H1, H2]\n\ntheorem SSAEnv.getT_set_ne \u2983v v': SSAVal\u2984:\n    v' \u2260 v \u2192\n    \u2200 \u2983env: SSAEnv \u03b4\u2984 \u2983\u03c4: MLIRType \u03b4\u2984 \u2983val\u2984,\n    getT v (set v' \u03c4 val env) = getT v env := by\n  intros Hne env \u03c4 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 \u03b4) (v: SSAVal) (\u03c4: MLIRType \u03b4) val:\n    getT v (SSAEnv.set v \u03c4 val env) = some \u27e8\u03c4, val\u27e9  := 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 \u2983v v': SSAVal\u2984:\n    v' \u2260 v \u2192\n    \u2200 \u2983env: SSAEnv \u03b4\u2984 \u2983\u03c4 \u03c4': MLIRType \u03b4\u2984 \u2983val\u2984,\n    get v \u03c4 (set v' \u03c4' val env) = get v \u03c4 env := by\n  intros Hne env \u03c4 \u03c4' val\n  simp [get]\n  rw [SSAEnv.getT_set_ne]\n  assumption\n\ntheorem SSAEnv.get_set_eq_val {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (\u03c4 \u03c4': MLIRType \u03b4)\n  (env: SSAEnv \u03b4) (v: SSAVal) (val: \u03c4'.eval):\n    get v \u03c4 (set v \u03c4' val env) =\n      if H': \u03c4' = \u03c4 then\n        some (cast (by simp [H']) val)\n      else\n        none := by\n  simp [get, getT_set_eq]\n\ntheorem SSAEnv.get_set {\u03b4: Dialect \u03b1 \u03c3 \u03b5} (\u03c4 \u03c4': MLIRType \u03b4)\n  (env: SSAEnv \u03b4) (v v': SSAVal) (val: \u03c4'.eval):\n    get v \u03c4 (set v' \u03c4' val env) =\n      if v' = v then\n        if H: \u03c4' = \u03c4 then\n          some (cast (by simp [H]) val)\n        else\n          none\n      else\n        get v \u03c4 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 \u03b4) (\u03c4: MLIRType \u03b4) val:\n    get v \u03c4 (set v \u03c4 val env) = some val := by\n  simp [get, getT_set_eq]\n\ntheorem SSAEnv.get_set_neq (v v': SSAVal) (NEQ: v' \u2260 v) (env: SSAEnv \u03b4) (\u03c4: MLIRType \u03b4) val:\n    get v \u03c4 (set v' \u03c4 val env) = get v \u03c4 env := by\n  simp[get];\n  rw[SSAEnv.getT_set_ne]; try assumption;\n\ntheorem SSAEnv.equiv_set {\u03b4: Dialect \u03b1 \u03c3 \u03b5} \u2983env\u2081 env\u2082: SSAEnv \u03b4\u2984:\n    env\u2081.equiv env\u2082 \u2192\n    \u2200 \u2983name \u03c4 v\u2984, (set name \u03c4 v env\u2081).equiv (set name \u03c4 v env\u2082) := by\n  intros HEnv name \u03c4 v name' \u03c4'\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 \u2983v v': SSAVal\u2984:\n    v' \u2260 v \u2192\n    \u2200 \u2983env: SSAEnv \u03b4\u2984 \u2983\u03c4 \u03c4': MLIRType \u03b4\u2984 \u2983val val'\u2984,\n    equiv (set v \u03c4 val (set v' \u03c4' val' env)) (set v' \u03c4' val' (set v \u03c4 val env)) := by\n  intros Hne env \u03c4 \u03c4' val val' v\u2082 \u03c4\u2082\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 (\u03b4: Dialect \u03b1 \u03c3 \u03b5): Type \u2192 Type where\n  | Get: (\u03c4: MLIRType \u03b4) \u2192 [Inhabited \u03c4.eval] \u2192 SSAVal \u2192 SSAEnvE \u03b4 \u03c4.eval\n  | Set: (\u03c4: MLIRType \u03b4) \u2192 SSAVal \u2192 \u03c4.eval \u2192 SSAEnvE \u03b4 Unit\n\n@[simp_itree]\ndef SSAEnvE.handle {E}: SSAEnvE \u03b4 ~> StateT (SSAEnv \u03b4) (Fitree E) :=\n  fun _ e env =>\n    match e with\n    | Get \u03c4 name =>\n        match env.get name \u03c4 with\n        | some v => return (v, env)\n        | none => return (default, env)\n    | Set \u03c4 name v =>\n        return (.unit, env.set name \u03c4 v)\n\ndef SSAEnvE.handleLogged {E}:\n    SSAEnvE \u03b4 ~> WriterT (StateT (SSAEnv \u03b4) (Fitree E)) :=\n  fun _ e => do\n    let env <- WriterT.lift StateT.get\n    match e with\n    | Get \u03c4 name =>\n        match env.get name \u03c4 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 \u03c4 name v =>\n        logWriterT s!\"set {name}={v}; \"\n        WriterT.lift $ StateT.set (env.set name \u03c4 v)\n        return ()\n\n@[simp_itree]\ndef SSAEnv.get? {E} (\u03b4: Dialect \u03b1 \u03c3 \u03b5) [Member (SSAEnvE \u03b4) E]\n  (\u03c4: MLIRType \u03b4) (name: SSAVal): Fitree E \u03c4.eval :=\n    Fitree.trigger (SSAEnvE.Get \u03c4 name)\n\n@[simp_itree]\ndef SSAEnv.set? {E} {\u03b4: Dialect \u03b1 \u03c3 \u03b5} [Member (SSAEnvE \u03b4) E]\n    (\u03c4: MLIRType \u03b4) (name?: Option SSAVal) (v: \u03c4.eval): Fitree E Unit :=\n  match name? with\n  | some name =>\n      Fitree.trigger (SSAEnvE.Set \u03c4 name v)\n  | none =>\n      return ()\n\n-- Handlers\n\ndef interpSSA (t: Fitree (SSAEnvE \u03b4) R): StateT (SSAEnv \u03b4) (Fitree Void1) R :=\n  t.interpState SSAEnvE.handle\n\ndef interpSSA' {E} (t: Fitree (SSAEnvE \u03b4 +' E) R):\n    StateT (SSAEnv \u03b4) (Fitree E) R :=\n  t.interpState (Fitree.case SSAEnvE.handle Fitree.liftHandler)\n\ndef interpSSALogged (t: Fitree (SSAEnvE \u03b4) R):\n    WriterT (StateT (SSAEnv \u03b4) (Fitree Void1)) R :=\n  t.interp SSAEnvE.handleLogged\n\ndef interpSSALogged' {E} (t: Fitree (SSAEnvE \u03b4 +' E) R):\n    WriterT (StateT (SSAEnv \u03b4) (Fitree E)) R :=\n  t.interp (Fitree.case SSAEnvE.handleLogged Fitree.liftHandler)\n\n@[simp] theorem interpSSA'_Vis_left {\u03b4: Dialect \u03b1 \u03c3 \u03b5}\n    (k: T \u2192 Fitree (SSAEnvE \u03b4 +' E) R) (e: SSAEnvE \u03b4 T) (s\u2081: SSAEnv \u03b4):\n  interpSSA' (Fitree.Vis (Sum.inl e) k) s\u2081 =\n  Fitree.bind (SSAEnvE.handle _ e s\u2081) (fun (x,s\u2082) => interpSSA' (k x) s\u2082) :=\n  rfl\n\n@[simp] theorem interpSSA'_Vis_right (k: T \u2192 Fitree (SSAEnvE \u0394 +' 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 {\u03b4: Dialect \u03b1 \u03c3 \u03b5}:\n  @interpSSA' _ _ _ \u03b4 _ E (Fitree.ret r) = fun s => Fitree.ret (r,s) := rfl\n\nprivate theorem pair_eta {\u03b1 \u03b2: Type} (x: \u03b1 \u00d7 \u03b2): (x.fst, x.snd) = x :=\n  match x with\n  | (_, _) => rfl\n\n@[simp] theorem interpSSA'_trigger_MemberSumL {\u0394: Dialect \u03b1' \u03c3' \u03b5'}\n    (e: SSAEnvE \u0394 T) (s\u2081: SSAEnv \u0394):\n  interpSSA' (@Fitree.trigger (SSAEnvE \u0394) (SSAEnvE \u0394 +' E) _ MemberSumL e) s\u2081 =\n  SSAEnvE.handle _ e s\u2081 := by\n  simp [Fitree.trigger, pair_eta]\n\ntheorem interpSSA'_bind {\u03b4: Dialect \u03b1 \u03c3 \u03b5}\n    (t: Fitree (SSAEnvE \u03b4 +' E) T) (k: T \u2192 Fitree (SSAEnvE \u03b4 +' E) R)\n    (s\u2081: SSAEnv \u03b4):\n  interpSSA' (\u03b4 := \u03b4) (Fitree.bind t k) s\u2081 =\n  Fitree.bind (interpSSA' t s\u2081) (fun (x,s\u2082) => interpSSA' (k x) s\u2082) := 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 : \u2115`. We prove that the obvious inclusion functor `Fintype.skeleton \u2964 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 \u21a5X :=\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.\u03b1\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.\u03b1) (y : category_theory.induced_category (Type u_1) category_theory.bundled.\u03b1) (f : x \u27f6 y) : \u2200 (\u1fb0 : category_theory.bundled.\u03b1 x), category_theory.functor.map incl f \u1fb0 = f \u1fb0 :=\n  fun (\u1fb0 : category_theory.bundled.\u03b1 x) => Eq.refl (f \u1fb0)\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 : \u2115`. We parameterize the objects of `Fintype.skeleton` directly as `\u2115`,\nas the type `fin m \u2243 fin n` is nonempty if and only if `n = m`.\n-/\ndef skeleton :=\n  \u2115\n\nnamespace skeleton\n\n\n/-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/\ndef mk : \u2115 \u2192 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 \u2192 \u2115 :=\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 \u2964 Fintype :=\n  category_theory.functor.mk (fun (X : skeleton) => of (fin X)) fun (_x _x_1 : skeleton) (f : _x \u27f6 _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 \u27f6 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 : \u21a5X \u2243 fin (fintype.card \u21a5X) := trunc.out (fintype.equiv_fin \u21a5X);\n      Exists.intro (fintype.card \u21a5X) (Nonempty.intro (category_theory.iso.mk \u21d1(equiv.symm F) \u21d1F))\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 \u224c Fintype :=\n  category_theory.functor.as_equivalence incl\n\n@[simp] theorem incl_mk_nat_card (n : \u2115) : fintype.card \u21a5(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 \u2964 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 \u2964 Top.{u}) : cone F :=\n{ X := Top.of {u : \u03a0 j : J, F.obj j | \u2200 {i j : J} (f : i \u27f6 j), F.map f (u i) = u j},\n  \u03c0 :=\n  { app := \u03bb j,\n    { to_fun := \u03bb u, u.val j,\n      continuous_to_fun := show continuous ((\u03bb u : \u03a0 j : J, F.obj j, u j) \u2218 subtype.val),\n        by continuity } } }\n\n/--\nA choice of limit cone for a functor `F : J \u2964 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 \u2964 Top.{u}) : cone F :=\n{ X := \u27e8(types.limit_cone (F \u22d9 forget)).X, \u2a05j,\n        (F.obj j).str.induced ((types.limit_cone (F \u22d9 forget)).\u03c0.app j)\u27e9,\n  \u03c0 :=\n  { app := \u03bb j, \u27e8(types.limit_cone (F \u22d9 forget)).\u03c0.app j,\n                 continuous_iff_le_induced.mpr (infi_le _ _)\u27e9,\n    naturality' := \u03bb j j' f,\n                   continuous_map.coe_inj ((types.limit_cone (F \u22d9 forget)).\u03c0.naturality f) } }\n\n/--\nThe chosen cone `Top.limit_cone F` for a functor `F : J \u2964 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 \u2964 Top.{u}) : is_limit (limit_cone F) :=\n{ lift := \u03bb S, { to_fun := \u03bb x, \u27e8\u03bb j, S.\u03c0.app _ x, \u03bb i j f, by { dsimp, erw \u2190 S.w f, refl }\u27e9 },\n  uniq' := \u03bb S m h, by { ext : 3, simpa [\u2190 h] } }\n\n/--\nThe chosen cone `Top.limit_cone_infi F` for a functor `F : J \u2964 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 \u2964 Top.{u}) : is_limit (limit_cone_infi F) :=\nby { refine is_limit.of_faithful forget (types.limit_cone_is_limit _) (\u03bb s, \u27e8_, _\u27e9) (\u03bb s, rfl),\n     exact continuous_iff_coinduced_le.mpr (le_infi $ \u03bb j,\n       coinduced_le_iff_le_induced.mp $ (continuous_iff_coinduced_le.mp (s.\u03c0.app j).continuous :\n         _) ) }\n\ninstance Top_has_limits : has_limits.{u} Top.{u} :=\n{ has_limits_of_shape := \u03bb J \ud835\udca5, by exactI\n  { has_limit := \u03bb 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} \u2964 Type u) :=\n{ preserves_limits_of_shape := \u03bb J \ud835\udca5,\n  { preserves_limit := \u03bb F,\n    by exactI preserves_limit_of_preserves_limit_cone\n      (limit_cone_is_limit F) (types.limit_cone_is_limit (F \u22d9 forget)) } }\n\n/--\nA choice of colimit cocone for a functor `F : J \u2964 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 \u2964 Top.{u}) : cocone F :=\n{ X := \u27e8(types.colimit_cocone (F \u22d9 forget)).X, \u2a06 j,\n        (F.obj j).str.coinduced ((types.colimit_cocone (F \u22d9 forget)).\u03b9.app j)\u27e9,\n  \u03b9 :=\n  { app := \u03bb j, \u27e8(types.colimit_cocone (F \u22d9 forget)).\u03b9.app j,\n                 continuous_iff_coinduced_le.mpr (le_supr _ j)\u27e9,\n    naturality' := \u03bb j j' f,\n                   continuous_map.coe_inj ((types.colimit_cocone (F \u22d9 forget)).\u03b9.naturality f) } }\n\n/--\nThe chosen cocone `Top.colimit_cocone F` for a functor `F : J \u2964 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 \u2964 Top.{u}) : is_colimit (colimit_cocone F) :=\nby { refine is_colimit.of_faithful forget (types.colimit_cocone_is_colimit _) (\u03bb s, \u27e8_, _\u27e9)\n       (\u03bb s, rfl),\n     exact continuous_iff_le_induced.mpr (supr_le $ \u03bb j,\n       coinduced_le_iff_le_induced.mp $ (continuous_iff_coinduced_le.mp (s.\u03b9.app j).continuous :\n         _) ) }\n\ninstance Top_has_colimits : has_colimits.{u} Top.{u} :=\n{ has_colimits_of_shape := \u03bb J \ud835\udca5, by exactI\n  { has_colimit := \u03bb 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} \u2964 Type u) :=\n{ preserves_colimits_of_shape := \u03bb J \ud835\udca5,\n  { preserves_colimit := \u03bb F,\n    by exactI preserves_colimit_of_preserves_colimit_cocone\n      (colimit_cocone_is_colimit F) (types.colimit_cocone_is_colimit (F \u22d9 forget)) } }\n\n/-- The projection from the product as a bundled continous map. -/\nabbreviation pi_\u03c0 {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) (i : \u03b9) : Top.of (\u03a0 i, \u03b1 i) \u27f6 \u03b1 i :=\n\u27e8\u03bb f, f i, continuous_apply i\u27e9\n\n/-- The explicit fan of a family of topological spaces given by the pi type. -/\n@[simps X \u03c0_app]\ndef pi_fan {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) : fan \u03b1 :=\nfan.mk (Top.of (\u03a0 i, \u03b1 i)) (pi_\u03c0 \u03b1)\n\n/-- The constructed fan is indeed a limit -/\ndef pi_fan_is_limit {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) : is_limit (pi_fan \u03b1) :=\n{ lift := \u03bb S, { to_fun := \u03bb s i, S.\u03c0.app i s },\n  uniq' := by { intros S m h, ext x i, simp [\u2190 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 {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) : \u220f \u03b1 \u2245 Top.of (\u03a0 i, \u03b1 i) :=\n(limit.is_limit _).cone_point_unique_up_to_iso (pi_fan_is_limit \u03b1)\n\n@[simp, reassoc]\nlemma pi_iso_pi_inv_\u03c0 {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top) (i : \u03b9) :\n  (pi_iso_pi \u03b1).inv \u226b pi.\u03c0 \u03b1 i = pi_\u03c0 \u03b1 i :=\nby simp [pi_iso_pi]\n\n@[simp]\nlemma pi_iso_pi_inv_\u03c0_apply {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) (i : \u03b9) (x : \u03a0 i, \u03b1 i) :\n  (pi.\u03c0 \u03b1 i : _) ((pi_iso_pi \u03b1).inv x) = x i :=\nconcrete_category.congr_hom (pi_iso_pi_inv_\u03c0 \u03b1 i) x\n\n@[simp]\nlemma pi_iso_pi_hom_apply {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) (i : \u03b9) (x : \u220f \u03b1) :\n  (pi_iso_pi \u03b1).hom x i = (pi.\u03c0 \u03b1 i : _) x :=\nbegin\n  have := pi_iso_pi_inv_\u03c0 \u03b1 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_\u03b9 {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) (i : \u03b9) : \u03b1 i \u27f6 Top.of (\u03a3 i, \u03b1 i) :=\n\u27e8sigma.mk i\u27e9\n\n/-- The explicit cofan of a family of topological spaces given by the sigma type. -/\n@[simps X \u03b9_app]\ndef sigma_cofan {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) : cofan \u03b1 :=\ncofan.mk (Top.of (\u03a3 i, \u03b1 i)) (sigma_\u03b9 \u03b1)\n\n/-- The constructed cofan is indeed a colimit -/\ndef sigma_cofan_is_colimit {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) : is_colimit (sigma_cofan \u03b1) :=\n{ desc := \u03bb S, { to_fun := \u03bb s, S.\u03b9.app s.1 s.2,\n    continuous_to_fun := by { continuity, dsimp only, continuity } },\n  uniq' := by { intros S m h,  ext \u27e8i, x\u27e9, simp [\u2190 h i] } }\n\n/--\nThe coproduct is homeomorphic to the disjoint union of the topological spaces.\n-/\ndef sigma_iso_sigma {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top.{u}) : \u2210 \u03b1 \u2245 Top.of (\u03a3 i, \u03b1 i) :=\n(colimit.is_colimit _).cocone_point_unique_up_to_iso (sigma_cofan_is_colimit \u03b1)\n\n@[simp, reassoc]\nlemma sigma_iso_sigma_hom_\u03b9 {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top) (i : \u03b9) :\n  sigma.\u03b9 \u03b1 i \u226b (sigma_iso_sigma \u03b1).hom = sigma_\u03b9 \u03b1 i :=\nby simp [sigma_iso_sigma]\n\n@[simp]\nlemma sigma_iso_sigma_hom_\u03b9_apply {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top) (i : \u03b9) (x : \u03b1 i) :\n  (sigma_iso_sigma \u03b1).hom ((sigma.\u03b9 \u03b1 i : _) x) = sigma.mk i x :=\nconcrete_category.congr_hom (sigma_iso_sigma_hom_\u03b9 \u03b1 i) x\n\n@[simp]\nlemma sigma_iso_sigma_inv_apply {\u03b9 : Type u} (\u03b1 : \u03b9 \u2192 Top) (i : \u03b9) (x : \u03b1 i) :\n  (sigma_iso_sigma \u03b1).inv \u27e8i, x\u27e9 = (sigma.\u03b9 \u03b1 i : _) x :=\nby { rw [\u2190 sigma_iso_sigma_hom_\u03b9_apply, \u2190 comp_app], simp, }\n\nlemma induced_of_is_limit {F : J \u2964 Top.{u}} (C : cone F) (hC : is_limit C) :\n  C.X.topological_space = \u2a05 j, (F.obj j).topological_space.induced (C.\u03c0.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 (\u2a05 (j : J), _) = _,\n  simpa [induced_infi, induced_compose],\nend\n\nlemma limit_topology (F : J \u2964 Top.{u}) :\n  (limit F).topological_space = \u2a05 j, (F.obj j).topological_space.induced (limit.\u03c0 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 \u00d7 Y) \u27f6 X := \u27e8prod.fst\u27e9\n\n/-- The second projection from the product. -/\nabbreviation prod_snd {X Y : Top.{u}} : Top.of (X \u00d7 Y) \u27f6 Y := \u27e8prod.snd\u27e9\n\n/-- The explicit binary cofan of `X, Y` given by `X \u00d7 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 := \u03bb (S : binary_fan X Y), { to_fun := \u03bb 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 (\u03bb e, (e x)) at h,\n      exact h },\n     { specialize h walking_pair.right,\n      apply_fun (\u03bb e, (e x)) at h,\n      exact h },\n  end }\n\n/--\nThe homeomorphism between `X \u2a2f 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 \u2a2f Y \u2245 Top.of (X \u00d7 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 \u226b prod_fst = limits.prod.fst :=\nby simpa [\u2190 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 \u226b prod_snd = limits.prod.snd :=\nby simpa [\u2190 iso.eq_inv_comp, prod_iso_prod]\n\n@[simp] lemma prod_iso_prod_hom_apply {X Y : Top.{u}} (x : X \u2a2f Y) :\n  (prod_iso_prod X Y).hom x =\n    ((limits.prod.fst : X \u2a2f Y \u27f6 _) x, (limits.prod.snd : X \u2a2f Y \u27f6 _) 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 \u226b 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 \u226b limits.prod.snd = prod_snd :=\nby simp [iso.inv_comp_eq]\n\nlemma prod_topology {X Y : Top} :\n  (X \u2a2f Y).topological_space =\n    induced (limits.prod.fst : X \u2a2f Y \u27f6 _) X.topological_space \u2293\n      induced (limits.prod.snd : X \u2a2f Y \u27f6 _) 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 (_ \u2293 _) = _,\n  simpa [induced_compose]\nend\n\nlemma range_prod_map {W X Y Z : Top.{u}} (f : W \u27f6 Y) (g : X \u27f6 Z) :\n  set.range (limits.prod.map f g) =\n    (limits.prod.fst : Y \u2a2f Z \u27f6 _) \u207b\u00b9' (set.range f) \u2229\n      (limits.prod.snd : Y \u2a2f Z \u27f6 _) \u207b\u00b9' (set.range g) :=\nbegin\n  ext,\n  split,\n  { rintros \u27e8y, rfl\u27e9,\n    simp only [set.mem_preimage, set.mem_range, set.mem_inter_eq, \u2190comp_apply],\n    simp only [limits.prod.map_fst, limits.prod.map_snd,\n      exists_apply_eq_apply, comp_apply, and_self] },\n  { rintros \u27e8\u27e8x\u2081, hx\u2081\u27e9, \u27e8x\u2082, hx\u2082\u27e9\u27e9,\n    use (prod_iso_prod W X).inv (x\u2081, x\u2082),\n    apply concrete.limit_ext,\n    rintro \u27e8\u27e9,\n    { simp only [\u2190 comp_apply, category.assoc], erw limits.prod.map_fst, simp [hx\u2081] },\n    { simp only [\u2190 comp_apply, category.assoc], erw limits.prod.map_snd, simp [hx\u2082] } }\nend\n\nlemma inducing_prod_map {W X Y Z : Top} {f : W \u27f6 X} {g : Y \u27f6 Z}\n  (hf : inducing f) (hg : inducing g) : inducing (limits.prod.map f g) :=\nbegin\n  constructor,\n  simp only [prod_topology, induced_compose, \u2190coe_comp, limits.prod.map_fst, limits.prod.map_snd,\n    induced_inf],\n  simp only [coe_comp],\n  rw [\u2190 @induced_compose _ _ _ _ _ f, \u2190 @induced_compose _ _ _ _ _ g, \u2190 hf.induced, \u2190 hg.induced]\nend\n\nlemma embedding_prod_map {W X Y Z : Top} {f : W \u27f6 X} {g : Y \u27f6 Z}\n  (hf : embedding f) (hg : embedding g) : embedding (limits.prod.map f g) :=\n\u27e8inducing_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\u27e9\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 \u27f6 Z) (g : Y \u27f6 Z) : Top.of { p : X \u00d7 Y // f p.1 = g p.2 } \u27f6 X :=\n\u27e8prod.fst \u2218 subtype.val\u27e9\n\n/-- The second projection from the pullback. -/\nabbreviation pullback_snd (f : X \u27f6 Z) (g : Y \u27f6 Z) : Top.of { p : X \u00d7 Y // f p.1 = g p.2 } \u27f6 Y :=\n\u27e8prod.snd \u2218 subtype.val\u27e9\n\n/-- The explicit pullback cone of `X, Y` given by `{ p : X \u00d7 Y // f p.1 = g p.2 }`. -/\ndef pullback_cone (f : X \u27f6 Z) (g : Y \u27f6 Z) : pullback_cone f g :=\npullback_cone.mk (pullback_fst f g) (pullback_snd f g) (by { ext \u27e8x, h\u27e9, simp [h] })\n\n/-- The constructed cone is a limit. -/\ndef pullback_cone_is_limit (f : X \u27f6 Z) (g : Y \u27f6 Z) :\n  is_limit (pullback_cone f g) := pullback_cone.is_limit_aux' _\nbegin\n  intro s,\n  split, swap,\n  exact { to_fun := \u03bb x, \u27e8\u27e8s.fst x, s.snd x\u27e9,\n    by simpa using concrete_category.congr_hom s.condition x\u27e9 },\n  refine \u27e8_,_,_\u27e9,\n  { ext, delta pullback_cone, simp },\n  { ext, delta pullback_cone, simp },\n  { intros m h\u2081 h\u2082,\n    ext x,\n    { simpa using concrete_category.congr_hom h\u2081 x },\n    { simpa using concrete_category.congr_hom h\u2082 x } }\nend\n\n/-- The pullback of two maps can be identified as a subspace of `X \u00d7 Y`. -/\ndef pullback_iso_prod_subtype (f : X \u27f6 Z) (g : Y \u27f6 Z) :\n  pullback f g \u2245 Top.of { p : X \u00d7 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 \u27f6 Z) (g : Y \u27f6 Z) :\n  (pullback_iso_prod_subtype f g).inv \u226b 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 \u27f6 Z) (g : Y \u27f6 Z)\n  (x : { p : X \u00d7 Y // f p.1 = g p.2 }) :\n  (pullback.fst : pullback f g \u27f6 _) ((pullback_iso_prod_subtype f g).inv x) = (x : X \u00d7 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 \u27f6 Z) (g : Y \u27f6 Z) :\n  (pullback_iso_prod_subtype f g).inv \u226b 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 \u27f6 Z) (g : Y \u27f6 Z)\n  (x : { p : X \u00d7 Y // f p.1 = g p.2 }) :\n  (pullback.snd : pullback f g \u27f6 _) ((pullback_iso_prod_subtype f g).inv x) = (x : X \u00d7 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 \u27f6 Z) (g : Y \u27f6 Z) :\n  (pullback_iso_prod_subtype f g).hom \u226b pullback_fst f g = pullback.fst :=\nby rw [\u2190iso.eq_inv_comp, pullback_iso_prod_subtype_inv_fst]\n\nlemma pullback_iso_prod_subtype_hom_snd (f : X \u27f6 Z) (g : Y \u27f6 Z) :\n  (pullback_iso_prod_subtype f g).hom \u226b pullback_snd f g = pullback.snd :=\nby rw [\u2190iso.eq_inv_comp, pullback_iso_prod_subtype_inv_snd]\n\n@[simp] lemma pullback_iso_prod_subtype_hom_apply {f : X \u27f6 Z} {g : Y \u27f6 Z}\n  (x : pullback f g) : (pullback_iso_prod_subtype f g).hom x =\n    \u27e8\u27e8(pullback.fst : pullback f g \u27f6 _) x, (pullback.snd : pullback f g \u27f6 _) x\u27e9,\n      by simpa using concrete_category.congr_hom pullback.condition x\u27e9 :=\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 \u27f6 Z) (g : Y \u27f6 Z) :\n  (pullback f g).topological_space =\n    induced (pullback.fst : pullback f g \u27f6 _) X.topological_space \u2293\n      induced (pullback.snd : pullback f g \u27f6 _) 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 _ (_ \u2293 _)) = _,\n  simpa [induced_compose]\nend\n\nlemma range_pullback_to_prod {X Y Z : Top} (f : X \u27f6 Z) (g : Y \u27f6 Z) :\n  set.range (prod.lift pullback.fst pullback.snd : pullback f g \u27f6 X \u2a2f Y) =\n  { x | (limits.prod.fst \u226b f) x = (limits.prod.snd \u226b g) x } :=\nbegin\n  ext x,\n  split,\n  { rintros \u27e8y, rfl\u27e9,\n    simp only [\u2190comp_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 \u27e8\u27e8_, _\u27e9, h\u27e9,\n    apply concrete.limit_ext,\n    rintro \u27e8\u27e9; simp }\nend\n\nlemma inducing_pullback_to_prod {X Y Z : Top} (f : X \u27f6 Z) (g : Y \u27f6 Z) :\n  inducing \u21d1(prod.lift pullback.fst pullback.snd : pullback f g \u27f6 X \u2a2f Y) :=\n\u27e8by simp [prod_topology, pullback_topology, induced_compose, \u2190coe_comp]\u27e9\n\nlemma embedding_pullback_to_prod {X Y Z : Top} (f : X \u27f6 Z) (g : Y \u27f6 Z) :\n  embedding \u21d1(prod.lift pullback.fst pullback.snd : pullback f g \u27f6 X \u2a2f Y) :=\n\u27e8inducing_pullback_to_prod f g, (Top.mono_iff_injective _).mp infer_instance\u27e9\n\n/-- If the map `S \u27f6 T` is mono, then there is a description of the image of `W \u00d7\u209b X \u27f6 Y \u00d7\u209c Z`. -/\nlemma range_pullback_map {W X Y Z S T : Top} (f\u2081 : W \u27f6 S) (f\u2082 : X \u27f6 S)\n  (g\u2081 : Y \u27f6 T) (g\u2082 : Z \u27f6 T) (i\u2081 : W \u27f6 Y) (i\u2082 : X \u27f6 Z) (i\u2083 : S \u27f6 T) [H\u2083 : mono i\u2083]\n  (eq\u2081 : f\u2081 \u226b i\u2083 = i\u2081 \u226b g\u2081) (eq\u2082 : f\u2082 \u226b i\u2083 = i\u2082 \u226b g\u2082) :\n  set.range (pullback.map f\u2081 f\u2082 g\u2081 g\u2082 i\u2081 i\u2082 i\u2083 eq\u2081 eq\u2082) =\n    (pullback.fst : pullback g\u2081 g\u2082 \u27f6 _) \u207b\u00b9' (set.range i\u2081) \u2229\n      (pullback.snd : pullback g\u2081 g\u2082 \u27f6 _) \u207b\u00b9' (set.range i\u2082) :=\nbegin\n  ext,\n  split,\n  { rintro \u27e8y, rfl\u27e9, simp, },\n  rintros \u27e8\u27e8x\u2081, hx\u2081\u27e9, \u27e8x\u2082, hx\u2082\u27e9\u27e9,\n  have : f\u2081 x\u2081 = f\u2082 x\u2082,\n  { apply (Top.mono_iff_injective _).mp H\u2083,\n    simp only [\u2190comp_apply, eq\u2081, eq\u2082],\n    simp only [comp_apply, hx\u2081, hx\u2082],\n    simp only [\u2190comp_apply, pullback.condition] },\n  use (pullback_iso_prod_subtype f\u2081 f\u2082).inv \u27e8\u27e8x\u2081, x\u2082\u27e9, this\u27e9,\n  apply concrete.limit_ext,\n  rintros (_|_|_),\n  { simp only [Top.comp_app, limit.lift_\u03c0_apply, category.assoc, pullback_cone.mk_\u03c0_app_one,\n      hx\u2081, pullback_iso_prod_subtype_inv_fst_apply, subtype.coe_mk],\n    simp only [\u2190 comp_apply],\n    congr,\n    apply limit.w _ walking_cospan.hom.inl },\n  { simp [hx\u2081] },\n  { simp [hx\u2082] },\nend\n\nlemma pullback_fst_range {X Y S : Top} (f : X \u27f6 S) (g : Y \u27f6 S) :\n  set.range (pullback.fst : pullback f g \u27f6 _) = { x : X | \u2203 y : Y, f x = g y} :=\nbegin\n  ext x,\n  split,\n  { rintro \u27e8y, rfl\u27e9,\n    use (pullback.snd : pullback f g \u27f6 _) y,\n    exact concrete_category.congr_hom pullback.condition y },\n  { rintro \u27e8y, eq\u27e9,\n    use (Top.pullback_iso_prod_subtype f g).inv \u27e8\u27e8x, y\u27e9, eq\u27e9,\n    simp },\nend\n\nlemma pullback_snd_range {X Y S : Top} (f : X \u27f6 S) (g : Y \u27f6 S) :\n  set.range (pullback.snd : pullback f g \u27f6 _) = { y : Y | \u2203 x : X, f x = g y} :=\nbegin\n  ext y,\n  split,\n  { rintro \u27e8x, rfl\u27e9,\n    use (pullback.fst : pullback f g \u27f6 _) x,\n    exact concrete_category.congr_hom pullback.condition x },\n  { rintro \u27e8x, eq\u27e9,\n    use (Top.pullback_iso_prod_subtype f g).inv \u27e8\u27e8x, y\u27e9, eq\u27e9,\n    simp },\nend\n\n/--\nIf there is a diagram where the morphisms `W \u27f6 Y` and `X \u27f6 Z` are embeddings,\nthen the induced morphism `W \u00d7\u209b X \u27f6 Y \u00d7\u209c Z` is also an embedding.\n\n  W  \u27f6  Y\n    \u2198      \u2198\n      S  \u27f6  T\n    \u2197      \u2197\n  X  \u27f6  Z\n-/\nlemma pullback_map_embedding_of_embeddings {W X Y Z S T : Top}\n  (f\u2081 : W \u27f6 S) (f\u2082 : X \u27f6 S) (g\u2081 : Y \u27f6 T) (g\u2082 : Z \u27f6 T) {i\u2081 : W \u27f6 Y} {i\u2082 : X \u27f6 Z}\n  (H\u2081 : embedding i\u2081) (H\u2082 : embedding i\u2082) (i\u2083 : S \u27f6 T)\n  (eq\u2081 : f\u2081 \u226b i\u2083 = i\u2081 \u226b g\u2081) (eq\u2082 : f\u2082 \u226b i\u2083 = i\u2082 \u226b g\u2082) :\n  embedding (pullback.map f\u2081 f\u2082 g\u2081 g\u2082 i\u2081 i\u2082 i\u2083 eq\u2081 eq\u2082) :=\nbegin\n  refine embedding_of_embedding_compose (continuous_map.continuous_to_fun _)\n    (show continuous (prod.lift pullback.fst pullback.snd : pullback g\u2081 g\u2082 \u27f6 Y \u2a2f Z), from\n      continuous_map.continuous_to_fun _) _,\n  suffices : embedding\n    (prod.lift pullback.fst pullback.snd \u226b limits.prod.map i\u2081 i\u2082 : pullback f\u2081 f\u2082 \u27f6 _),\n  { simpa [\u2190coe_comp] using this },\n  rw coe_comp,\n  refine embedding.comp (embedding_prod_map H\u2081 H\u2082)\n    (embedding_pullback_to_prod _ _)\nend\n\n/--\nIf there is a diagram where the morphisms `W \u27f6 Y` and `X \u27f6 Z` are open embeddings, and `S \u27f6 T`\nis mono, then the induced morphism `W \u00d7\u209b X \u27f6 Y \u00d7\u209c Z` is also an open embedding.\n  W  \u27f6  Y\n    \u2198      \u2198\n      S  \u27f6  T\n    \u2197       \u2197\n  X  \u27f6  Z\n-/\nlemma pullback_map_open_embedding_of_open_embeddings {W X Y Z S T : Top}\n  (f\u2081 : W \u27f6 S) (f\u2082 : X \u27f6 S) (g\u2081 : Y \u27f6 T) (g\u2082 : Z \u27f6 T) {i\u2081 : W \u27f6 Y} {i\u2082 : X \u27f6 Z}\n  (H\u2081 : open_embedding i\u2081) (H\u2082 : open_embedding i\u2082) (i\u2083 : S \u27f6 T) [H\u2083 : mono i\u2083]\n  (eq\u2081 : f\u2081 \u226b i\u2083 = i\u2081 \u226b g\u2081) (eq\u2082 : f\u2082 \u226b i\u2083 = i\u2082 \u226b g\u2082) :\n  open_embedding (pullback.map f\u2081 f\u2082 g\u2081 g\u2082 i\u2081 i\u2082 i\u2083 eq\u2081 eq\u2082) :=\nbegin\n  split,\n  { apply pullback_map_embedding_of_embeddings\n      f\u2081 f\u2082 g\u2081 g\u2082 H\u2081.to_embedding H\u2082.to_embedding i\u2083 eq\u2081 eq\u2082 },\n  { rw range_pullback_map,\n    apply is_open.inter; apply continuous.is_open_preimage,\n    continuity,\n    exacts [H\u2081.open_range, H\u2082.open_range] }\nend\n\nlemma snd_embedding_of_left_embedding {X Y S : Top}\n  {f : X \u27f6 S} (H : embedding f) (g : Y \u27f6 S) :\n  embedding \u21d1(pullback.snd : pullback f g \u27f6 Y) :=\nbegin\n  convert (homeo_of_iso (as_iso (pullback.snd : pullback (\ud835\udfd9 S) g \u27f6 _))).embedding.comp\n    (pullback_map_embedding_of_embeddings f g (\ud835\udfd9 _) g H\n      (homeo_of_iso (iso.refl _)).embedding (\ud835\udfd9 _) rfl (by simp)),\n  erw \u2190coe_comp,\n  simp\nend\n\nlemma fst_embedding_of_right_embedding {X Y S : Top}\n  (f : X \u27f6 S) {g : Y \u27f6 S} (H : embedding g) :\n  embedding \u21d1(pullback.fst : pullback f g \u27f6 X) :=\nbegin\n  convert (homeo_of_iso (as_iso (pullback.fst : pullback f (\ud835\udfd9 S) \u27f6 _))).embedding.comp\n    (pullback_map_embedding_of_embeddings f g f (\ud835\udfd9 _)\n      (homeo_of_iso (iso.refl _)).embedding H (\ud835\udfd9 _) rfl (by simp)),\n  erw \u2190coe_comp,\n  simp\nend\n\nlemma embedding_of_pullback_embeddings {X Y S : Top}\n  {f : X \u27f6 S} {g : Y \u27f6 S} (H\u2081 : embedding f) (H\u2082 : embedding g) :\n  embedding (limit.\u03c0 (cospan f g) walking_cospan.one) :=\nbegin\n  convert H\u2082.comp (snd_embedding_of_left_embedding H\u2081 g),\n  erw \u2190coe_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 \u27f6 S} (H : open_embedding f) (g : Y \u27f6 S) :\n  open_embedding \u21d1(pullback.snd : pullback f g \u27f6 Y) :=\nbegin\n  convert (homeo_of_iso (as_iso (pullback.snd : pullback (\ud835\udfd9 S) g \u27f6 _))).open_embedding.comp\n    (pullback_map_open_embedding_of_open_embeddings f g (\ud835\udfd9 _) g H\n      (homeo_of_iso (iso.refl _)).open_embedding (\ud835\udfd9 _) rfl (by simp)),\n  erw \u2190coe_comp,\n  simp\nend\n\nlemma fst_open_embedding_of_right_open_embedding {X Y S : Top}\n  (f : X \u27f6 S) {g : Y \u27f6 S} (H : open_embedding g) :\n  open_embedding \u21d1(pullback.fst : pullback f g \u27f6 X) :=\nbegin\n  convert (homeo_of_iso (as_iso (pullback.fst : pullback f (\ud835\udfd9 S) \u27f6 _))).open_embedding.comp\n    (pullback_map_open_embedding_of_open_embeddings f g f (\ud835\udfd9 _)\n      (homeo_of_iso (iso.refl _)).open_embedding H (\ud835\udfd9 _) rfl (by simp)),\n  erw \u2190coe_comp,\n  simp\nend\n\n/-- If `X \u27f6 S`, `Y \u27f6 S` are open embeddings, then so is `X \u00d7\u209b Y \u27f6 S`. -/\nlemma open_embedding_of_pullback_open_embeddings {X Y S : Top}\n  {f : X \u27f6 S} {g : Y \u27f6 S} (H\u2081 : open_embedding f) (H\u2082 : open_embedding g) :\n  open_embedding (limit.\u03c0 (cospan f g) walking_cospan.one) :=\nbegin\n  convert H\u2082.comp (snd_open_embedding_of_left_open_embedding H\u2081 g),\n  erw \u2190coe_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 \u27f6 S) {g : Y \u27f6 S}\n  (hg : embedding g) (H : set.range f \u2286 set.range g) : is_iso (pullback.fst : pullback f g \u27f6 X) :=\nbegin\n  let : (pullback f g : Top) \u2243\u209c X :=\n    (homeomorph.of_embedding _ (fst_embedding_of_right_embedding f hg)).trans\n    { to_fun := coe,\n      inv_fun := (\u03bb x, \u27e8x,\n        by { rw pullback_fst_range, exact \u27e8_, (H (set.mem_range_self x)).some_spec.symm\u27e9 }\u27e9),\n      left_inv := \u03bb \u27e8_,_\u27e9, rfl,\n      right_inv := \u03bb 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 \u27f6 S} (hf : embedding f)\n  (g : Y \u27f6 S) (H : set.range g \u2286 set.range f) : is_iso (pullback.snd : pullback f g \u27f6 Y) :=\nbegin\n  let : (pullback f g : Top) \u2243\u209c Y :=\n    (homeomorph.of_embedding _ (snd_embedding_of_left_embedding hf g)).trans\n    { to_fun := coe,\n      inv_fun := (\u03bb x, \u27e8x,\n        by { rw pullback_snd_range, exact \u27e8_, (H (set.mem_range_self x)).some_spec\u27e9 }\u27e9),\n      left_inv := \u03bb \u27e8_,_\u27e9, rfl,\n      right_inv := \u03bb 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 \u2964 Top.{u}} (c : cocone F) (hc : is_colimit c) :\n  c.X.topological_space = \u2a06 j, (F.obj j).topological_space.coinduced (c.\u03b9.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 \u2964 Top.{u}) :\n  (colimit F).topological_space = \u2a06 j, (F.obj j).topological_space.coinduced (colimit.\u03b9 F j) :=\ncoinduced_of_is_colimit _ (colimit.is_colimit F)\n\nlemma colimit_is_open_iff (F : J \u2964 Top.{u}) (U : set ((colimit F : _) : Type u)) :\n  is_open U \u2194 \u2200 j, is_open (colimit.\u03b9 F j \u207b\u00b9' 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} \u2964 Top.{u})\n  (U : set ((colimit F : _) : Type u)) :\n  is_open U \u2194 is_open (colimit.\u03b9 F walking_parallel_pair.one \u207b\u00b9' U) :=\nbegin\n  rw colimit_is_open_iff,\n  split,\n  { intro H, exact H _ },\n  { intros H j,\n    cases j,\n    { rw \u2190colimit.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 \u2964 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 : \u03a0 j, set (set (F.obj j))) (hT : \u2200 j, is_topological_basis (T j))\n  (univ : \u2200 (i : J), set.univ \u2208 T i)\n  (inter : \u2200 i (U1 U2 : set (F.obj i)), U1 \u2208 T i \u2192 U2 \u2208 T i \u2192 U1 \u2229 U2 \u2208 T i)\n  (compat : \u2200 (i j : J) (f : i \u27f6 j) (V : set (F.obj j)) (hV : V \u2208 T j), (F.map f) \u207b\u00b9' V \u2208 T i) :\n  is_topological_basis { U : set C.X | \u2203 j (V : set (F.obj j)), V \u2208 T j \u2227 U = C.\u03c0.app j \u207b\u00b9' 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 \u2245 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 | \u2203 j (V : set (F.obj j)), V \u2208 T j \u2227 U = D.\u03c0.app j \u207b\u00b9' V },\n  { convert this.inducing hE,\n    ext U0,\n    split,\n    { rintro \u27e8j, V, hV, rfl\u27e9,\n      refine \u27e8D.\u03c0.app j \u207b\u00b9' V, \u27e8j, V, hV, rfl\u27e9, rfl\u27e9 },\n    { rintro \u27e8W, \u27e8j, V, hV, rfl\u27e9, rfl\u27e9,\n      refine \u27e8j, V, hV, rfl\u27e9 } },\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 (\u03bb j (x : D.X), D.\u03c0.app j x),\n  ext U0,\n  split,\n  { rintros  \u27e8j, V, hV, rfl\u27e9,\n    let U : \u03a0 i, set (F.obj i) := \u03bb i, if h : i = j then (by {rw h, exact V}) else set.univ,\n    refine \u27e8U,{j},_,_\u27e9,\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 \u27e8U, G, h1, h2\u27e9,\n    obtain \u27e8j, hj\u27e9 := is_cofiltered.inf_objs_exists G,\n    let g : \u2200 e (he : e \u2208 G), j \u27f6 e := \u03bb _ he, (hj he).some,\n    let Vs : J \u2192 set (F.obj j) := \u03bb e, if h : e \u2208 G then F.map (g e h) \u207b\u00b9' (U e) else set.univ,\n    let V : set (F.obj j) := \u22c2 (e : J) (he : e \u2208 G), Vs e,\n    refine \u27e8j, V, _, _\u27e9,\n    { -- An intermediate claim used to apply induction along `G : finset J` later on.\n      have : \u2200 (S : set (set (F.obj j))) (E : finset J) (P : J \u2192 set (F.obj j))\n        (univ : set.univ \u2208 S)\n        (inter : \u2200 A B : set (F.obj j), A \u2208 S \u2192 B \u2208 S \u2192 A \u2229 B \u2208 S)\n        (cond : \u2200 (e : J) (he : e \u2208 E), P e \u2208 S), (\u22c2 e (he : e \u2208 E), P e) \u2208 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, \u2190 set.preimage_comp],\n      congr' 1,\n      change _ = \u21d1(D.\u03c0.app j \u226b F.map (g e he)),\n      rw D.w } }\nend\n\nend cofiltered_limit\n\nsection topological_konig\n\n/-!\n## Topological K\u0151nig's lemma\n\nA topological version of K\u0151nig'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\u1d52\u1d56 \u2964 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 \u2964 Top.{u})\n\nprivate abbreviation finite_diagram_arrow {J : Type u} [small_category J] (G : finset J) :=\n\u03a3' (X Y : J) (mX : X \u2208 G) (mY : Y \u2208 G), X \u27f6 Y\nprivate abbreviation finite_diagram (J : Type u) [small_category J] :=\n\u03a3 (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 \u2964 Top.{u})\n  {G : finset J} (H : finset (finite_diagram_arrow G)) : set (\u03a0 j, F.obj j) :=\n{ u | \u2200 {f : finite_diagram_arrow G} (hf : f \u2208 H), F.map f.2.2.2.2 (u f.1) = u f.2.1 }\n\nlemma partial_sections.nonempty [is_cofiltered J] [h : \u03a0 (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 \u03bb (j : J), if hj : j \u2208 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 \u27e8X, Y, hX, hY, f\u27e9 hf,\n  dsimp only,\n  rwa [dif_pos hX, dif_pos hY, \u2190comp_app, \u2190F.map_comp,\n       @is_cofiltered.inf_to_commutes _ _ _ G H],\nend\n\nlemma partial_sections.directed :\n  directed superset (\u03bb (G : finite_diagram J), partial_sections F G.2) :=\nbegin\n  classical,\n  intros A B,\n  let \u03b9A : finite_diagram_arrow A.1 \u2192 finite_diagram_arrow (A.1 \u2294 B.1) :=\n    \u03bb f, \u27e8f.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\u27e9,\n  let \u03b9B : finite_diagram_arrow B.1 \u2192 finite_diagram_arrow (A.1 \u2294 B.1) :=\n    \u03bb f, \u27e8f.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\u27e9,\n  refine \u27e8\u27e8A.1 \u2294 B.1, A.2.image \u03b9A \u2294 B.2.image \u03b9B\u27e9, _, _\u27e9,\n  { rintro u hu f hf,\n    have : \u03b9A f \u2208 A.2.image \u03b9A \u2294 B.2.image \u03b9B,\n    { apply finset.mem_union_left,\n      rw finset.mem_image,\n      refine \u27e8f, hf, rfl\u27e9 },\n    exact hu this },\n  { rintro u hu f hf,\n    have : \u03b9B f \u2208 A.2.image \u03b9A \u2294 B.2.image \u03b9B,\n    { apply finset.mem_union_right,\n      rw finset.mem_image,\n      refine \u27e8f, hf, rfl\u27e9 },\n    exact hu this }\nend\n\nlemma partial_sections.closed [\u03a0 (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    \u22c2 {f : finite_diagram_arrow G} (hf : f \u2208 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  [\u03a0 (j : J), nonempty (F.obj j)]\n  [\u03a0 (j : J), compact_space (F.obj j)]\n  [\u03a0 (j : J), t2_space (F.obj j)] :\n  nonempty (Top.limit_cone F).X :=\nbegin\n  classical,\n  obtain \u27e8u, hu\u27e9 := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed\n    (\u03bb G, partial_sections F _)\n    (partial_sections.directed F)\n    (\u03bb G, partial_sections.nonempty F _)\n    (\u03bb G, is_closed.is_compact (partial_sections.closed F _))\n    (\u03bb G, partial_sections.closed F _),\n  use u,\n  intros X Y f,\n  let G : finite_diagram J :=\n    \u27e8{X, Y},\n     {\u27e8X, 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\u27e9}\u27e9,\n  exact hu _ \u27e8G, rfl\u27e9 (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 \u2964 Type u)\n  [hf : \u03a0 (j : J), fintype (F.obj j)] [hne : \u03a0 (j : J), nonempty (F.obj j)] :\n  F.sections.nonempty :=\nbegin\n  let F' : J \u2964 Top := F \u22d9 Top.discrete,\n  haveI : \u03a0 (j : J), fintype (F'.obj j) := hf,\n  haveI : \u03a0 (j : J), nonempty (F'.obj j) := hne,\n  obtain \u27e8\u27e8u, hu\u27e9\u27e9 := Top.nonempty_limit_cone_of_compact_t2_cofiltered_system F',\n  exact \u27e8u, \u03bb _ _ f, hu f\u27e9,\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 \u2964 Type v)\n  [\u03a0 (j : J), fintype (F.obj j)] [\u03a0 (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' \u2964 J := as_small.down,\n  let F' : J' \u2964 Type (max u v w) := down \u22d9 F \u22d9 ulift_functor.{(max u w) v},\n  haveI : \u2200 i, nonempty (F'.obj i) := \u03bb i, \u27e8\u27e8classical.arbitrary (F.obj (down.obj i))\u27e9\u27e9,\n  haveI : \u2200 i, fintype (F'.obj i) := \u03bb i, fintype.of_equiv (F.obj (down.obj i)) equiv.ulift.symm,\n  -- Step 2: apply the bootstrap theorem\n  obtain \u27e8u, hu\u27e9 := nonempty_sections_of_fintype_cofiltered_system.init F',\n  -- Step 3: interpret the results\n  use \u03bb j, (u \u27e8j\u27e9).down,\n  intros j j' f,\n  have h := @hu (\u27e8j\u27e9 : J') (\u27e8j'\u27e9 : J') (ulift.up f),\n  simp only [as_small.down, functor.comp_map, ulift_functor_map, functor.op_map] at h,\n  simp_rw [\u2190h],\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\u0151nig's lemma.\nTo specialize: given a locally finite connected graph, take `J\u1d52\u1d56` to be `\u2115` 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\u1d52\u1d56 \u2964 Type v)\n  [\u03a0 (j : J\u1d52\u1d56), fintype (F.obj j)] [\u03a0 (j : J\u1d52\u1d56), 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 \u27e8\u03bb j, false.elim (h j.unop), \u03bb j, false.elim (h j.unop)\u27e9, },\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) \u27f9\u2099\u1d65 (env', R)\n  \u2192 (env, P, S) \u27f9\u1d65\u2098 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\u2081 E\u2082 E\u1d62 P\u2081 P\u2082 S S' I R} :\n    (E\u2081, P\u2081, S) \u27f9\u2099\u1d65 (E\u1d62, I)\n  \u2192 (E\u1d62, P\u2082, I ++ S') \u27f9\u2099\u1d65 (E\u2082, R)\n  \u2192 (E\u2081, P\u2081 ++ P\u2082, S ++ S') \u27f9\u2099\u1d65 (E\u2082, R) :=\nbegin\n  assume h1 h2,\n  induction' h1,\n  { exact h2 },\n  { apply ERunPush,\n    rw \u2190list.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 \u2190list.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\u2081 E\u2082 E\u1d62 P\u2081 P\u2082 S I R} :\n    (E\u2081, P\u2081, S) \u27f9\u2099\u1d65 (E\u1d62, I)\n  \u2192 (E\u1d62, P\u2082, I) \u27f9\u2099\u1d65 (E\u2082, R)\n  \u2192 (E\u2081, P\u2081 ++ P\u2082, S) \u27f9\u2099\u1d65 (E\u2082, R) :=\nbegin\n  assume h1 h2,\n  rw \u2190list.append_nil I at h2,\n  rw \u2190list.append_nil S,\n  exact from_interm_results h1 h2\nend\n\ntheorem to_interm_results {E\u2081 E\u2082 e P S S' r} :\n  (E\u2081, compile e ++ P, S) \u27f9\u2099\u1d65 (E\u2082, r :: S')\n  \u2192 \u2203 v, (E\u2081, compile e, S) \u27f9\u2099\u1d65 (E\u2081, v :: S) \u2227 \n         (E\u2081, P, v :: S) \u27f9\u2099\u1d65 (E\u2082, r :: S') :=\nbegin\n  assume hnv,\n  induction' e,\n  case EVal {\n    rw compile at hnv \u22a2,\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 \u22a2,\n    simp at hnv \u22a2,\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 \u22a2,\n    simp at hnv \u22a2,\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 \u22a2,\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 \u22a2,\n    simp at hnv \u22a2,\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 init.lean.parser.parser\nopen Lean\nopen Lean.Parser\n\nnamespace Foo\n\n@[builtinTestParser] def pairParser :=\nparser! \"(\" >> numLit >> \",\" >> ident >> \")\"\n\n@[builtinTestParser] def pairsParser :=\nparser! \"{\" >> sepBy1 testParser \",\" >> \"}\"\n\n@[builtinTestParser] def functionParser :=\nparser! \"fun\" >> ident >> \",\" >> testParser\n\n@[builtinTestParser] def identParser : Parser :=\nident\n\n@[builtinTestParser] def numParser : Parser :=\nnumLit\n\n@[builtinTestParser] def strParser : Parser :=\nstrLit\n\nend Foo\n\ndef testParser (input : String) : IO Unit :=\ndo\nenv \u2190 mkEmptyEnvironment;\ntestPTables \u2190 builtinTestParsingTable.get;\nstx \u2190 IO.ofExcept $ runParser env testPTables input;\nIO.println stx\n\ndef main (xs : List String) : IO Unit :=\ndo\ntestParser \"(10, hello)\";\ntestParser \"{ hello, 400, \\\"hello\\\", (10, hello), /- comment -/ (20, world), { fun x, (10, hello) }, { (30, foo) } }\";\n-- Following example has syntax error\ntestParser\n\"{ hello, 400, \\\"hello\\\", (10, hello), /- comment -/ (20, world), { fun x, [ (10, hello) }, { (30, 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/playground/parser1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.05749327355188846, "lm_q1q2_score": 0.02298648003028239}}
{"text": "import data.option.basic\n\nexample (\u03b1 : Type*) (a : \u03b1) [subsingleton \u03b1] : option.choice \u03b1 = 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 \u27f6 Y) [mono m] : \n  m \u226b 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 \u27f6 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 \u2245 s{ classifier_of m }s := \n  (limit.iso_limit_cone (limit_cone.mk _ (classifies m).is_pb)).symm\n\n/- Given\n       X ---> \u22a4\n       |      |\n  W -> Y ---> \u03a9 \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 \u27f6 Y) [mono m] (h : W \u27f6 Y)  \n  (w : h \u226b (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 \u27f6 Y) [mono m] (h : W \u27f6 Y)  \n  (w : h \u226b (classifier_of m) = lift_truth _) : \n  W \u27f6 X := \n(pb_lift_from_monic m h w).1\n\nlemma pb_lift_from_monic.comm {W X Y : C} (m : X \u27f6 Y) [mono m] (h : W \u27f6 Y)  \n  (w : h \u226b (classifier_of m) = lift_truth _) : \n  (pb_lift_from_monic.map m h w) \u226b 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 \u27f6 Y) [mono m] (h : W \u27f6 Y)  \n  (w : h \u226b (classifier_of m) = lift_truth _) : \n  \u2200 u : W \u27f6 X, u \u226b m = h \u2192 u = pb_lift_from_monic.map m h w := \nbegin\n  intros u h1,\n  have h :=\n  calc \n  u \u226b m = h                                   : by assumption\n  ...    = (pb_lift_from_monic.map m h w) \u226b m : by symmetry; apply pb_lift_from_monic.comm,\n  rw \u2190cancel_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 \u27f6 Z} {g : Y \u27f6 Z} \n  {s : pullback_cone f g} {h : U \u27f6 W} {k : V \u27f6 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 \u226b s.fst = u.fst \u226b fst \u2227 l \u226b s.snd = u.snd \u226b fst} \n\u00d7 {l // l \u226b t.fst = u.fst \u226b snd \u2227 l \u226b t.snd = u.snd \u226b 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, \u2190assoc, \u2190assoc] at u_fst,\n  rw [map_snd, map_snd, \u2190assoc, \u2190assoc] at u_snd,\n  exact (pullback_cone.is_limit.lift' s_lim (u.fst \u226b fst) (u.snd \u226b fst) u_fst, \n         pullback_cone.is_limit.lift' t_lim (u.fst \u226b snd) (u.snd \u226b 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, \u2190map_map] })) := \nbegin\n  apply pullback_cone.is_limit.mk _ \n    (\u03bb 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 [\u2190comp_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 [\u2190comp_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, \u2190map_fst s.fst t.fst, \u2190assoc, hfst], \n        erw [(map_lift s_lim t_lim u).1.prop.left],\n        \n        rw [lift_fst, assoc, \u2190map_fst s.snd t.snd, \u2190assoc, 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, \u2190map_snd s.fst t.fst, \u2190assoc, hfst], \n        erw [(map_lift s_lim t_lim u).2.prop.left],\n        \n        rw [lift_snd, assoc, \u2190map_snd s.snd t.snd, \u2190assoc, 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 \u27f6 d) : \n  is_limit (pullback_cone.mk f (\ud835\udfd9 c) (by simp) : pullback_cone (\ud835\udfd9 d) f) :=\nbegin\n  apply pullback_cone.is_limit.mk _ (\u03bb s, s.snd); simp only,\n  exact (\u03bb s, by { rw [\u2190s.condition, comp_id] }),\n  exact (\u03bb s, by rw comp_id s.snd),\n  exact (\u03bb s t h1 h2, by { rw [\u2190h2, comp_id] })\nend\n\nlemma is_pullback_square_ids_snd {c d : C} (f : c \u27f6 d) : \n  is_limit (pullback_cone.mk (\ud835\udfd9 c) f (by simp) : pullback_cone f (\ud835\udfd9 d)) :=\nbegin\n  apply pullback_cone.is_limit.mk _ (\u03bb s, s.fst); simp only,\n  exact (\u03bb s, by rw comp_id s.fst),\n  exact (\u03bb s, by { rw [s.condition, comp_id] }),\n  exact (\u03bb s t h1 h2, by { rw [\u2190h1, comp_id] })\nend\n\n\ndef lift_pullback_of_equalizer_coreflexive_pair {c d : C} {h k : c \u27f6 d} {u : fork k h} \n  [is_coreflexive_pair h k] (u_lim : is_limit u) (s : pullback_cone h k) : \n  {l // l \u226b u.\u03b9 = s.fst \u2227 l \u226b u.\u03b9 = 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 \u2190cond, 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 \u27f6 d} {u : fork k h} \n  (u_lim : is_limit u) [is_coreflexive_pair h k] : \n  is_limit (pullback_cone.mk u.\u03b9 u.\u03b9 (by rw u.condition) : pullback_cone h k) :=\nbegin\n  apply pullback_cone.is_limit.mk _ \n  (\u03bb 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 \u27f6 d) [mono k] :\n  is_limit (pullback_cone.mk (\ud835\udfd9 c) (\ud835\udfd9 c) (by rw id_comp) : pullback_cone k k) :=\nbegin\n  apply pullback_cone.is_limit.mk _ (\u03bb s, s.fst); intro s; simp only,\n  { rw comp_id },\n  { rw [comp_id, \u2190cancel_mono k, s.condition] },\n  { intros u hf hs, rw \u2190hf, 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 \u2192 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": "import CodeAction.Interface\nimport StatementAutoformalisation.Translate\nimport StatementAutoformalisation.Config.FixedPrompts\n\nnamespace SuggestName\n\ndef LLMParams : LLM.Params :=\n{\n  openAIModel := \"gpt-3.5-turbo\",\n  temperature := 4,\n  n := 5,\n  maxTokens := 200,\n  stopTokens := #[\"\\n\\n\"],\n  systemMessage := \"Please suggest a suitable name for the given theorem written in Lean.\"\n}\n\ndef PromptParams : Prompt.Params :=\n{\n  toLLMParams := LLMParams, \n  toSentenceSimilarityParams := #[], \n  toKeywordExtractionParams := #[],\n  fixedPrompts := leanChatPrompts,\n  useNames := #[],\n  useModules := #[],\n  useMainCtx? := false,\n  printMessage := fun decl => #[mkMessage \"user\" decl.printType, mkMessage \"assistant\" (decl.name.getD \"none\")],\n  mkSuffix := id,\n  processCompletion := fun type name => s!\"/-- -/ {name} {type}\"\n}\n\ndef InterfaceParams : Interface.Params DeclarationWithDocstring :=\n{\n  -- Use this code action by selecting the arguments and type of the declaration for which the name is to be generated.\n  title := \"Suggest a suitable name for the selected type.\",\n  useSelection? := true,\n  extractText? := some,\n  action := fun stmt =>\n    Prompt.translate \u27e8PromptParams, stmt\u27e9 >>= fun (_, suggestions) => return suggestions[0]!,\n  postProcess := fun type decl => s!\"{decl.name.getD \"\"} {type}\"\n}\n\n@[codeActionProvider] def Action := performCodeAction InterfaceParams\n\nend SuggestName", "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/StatementAutoformalisation/Config/SuggestName.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.0850990519679964, "lm_q1q2_score": 0.02288666099078651}}
{"text": "\nimport data.serial\n\nopen serial serializer\n\nstructure point :=\n(x y z : \u2115)\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 : \u2115 \u2192 my_sum\n| third (n : \u2115) (xs : list \u2115) : n \u2264 xs.length \u2192 my_sum\n\n@[derive serial]\nstructure my_struct :=\n(x : \u2115)\n(xs : list \u2115)\n(bounded : xs.length \u2264 x)\n\n@[derive [serial, decidable_eq]]\ninductive tree' (\u03b1 : Type)\n| leaf {} : tree'\n| node2 : \u03b1 \u2192 tree' \u2192 tree' \u2192 tree'\n| node3 : \u03b1 \u2192 tree' \u2192 tree' \u2192 tree' \u2192 tree'\n\nopen tree'\n\nmeta def tree'.repr {\u03b1} [has_repr \u03b1] : tree' \u03b1 \u2192 string\n| leaf := \"leaf\"\n| (node2 x t\u2080 t\u2081) := to_string $ format!\"(node2 {repr x} {tree'.repr t\u2080} {tree'.repr t\u2081})\"\n| (node3 x t\u2080 t\u2081 t\u2082) := to_string $ format!\"(node3 {repr x} {tree'.repr t\u2080} {tree'.repr t\u2081} {tree'.repr t\u2082})\"\n\nmeta instance {\u03b1} [has_repr \u03b1] : has_repr (tree' \u03b1) := \u27e8 tree'.repr \u27e9\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' \u2115) [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' \u2115) : 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": "import utils\nimport evaluation\nimport all\nimport basic.table\nimport system.io\n\nsection parse_nm\n\nmeta def parse_nm : string \u2192 tactic name := \u03bb nm_str, do {\n  flip lean.parser.run_with_input nm_str $ iterate_until lean.parser.ident (\u03bb nm, pure \u2218 bnot $ nm = name.anonymous) 100\n}\n\nend parse_nm\n\nmeta def unpack_tactic_strings : json \u2192 tactic (list string) := \u03bb msg, match msg with\n| (json.array $ msgs) := do {\n    msgs.mmap $ \u03bb msg, match msg with\n    | (json.of_string x) := pure x\n    | exc := tactic.fail format! \"UNEXPECTED {exc}\"\n    end\n  }\n| exc := tactic.fail format! \"UNEXPECTED {exc}\"\nend\n\nmeta def get_decl_name_and_tactics (msg : json) : tactic $ name \u00d7 list string := do {\n  decl_name_msg \u2190 msg.lookup \"task_id\",\n  decl_name_str \u2190 match decl_name_msg with\n    | (json.of_string x) := pure x\n    | exc := tactic.fail format! \"UNEXPECTED {exc}\"\n    end,\n  decl_name \u2190 parse_nm decl_name_str,\n  tacs_msg \u2190 msg.lookup \"tactics\",\n  tac_strings \u2190 unpack_tactic_strings tacs_msg,\n  pure \u27e8decl_name, tac_strings\u27e9\n}\n\n-- #eval do {\n--   msg \u2190 option.to_monad $ json.parse \" { \\\"task_id\\\":\\\"and.comm\\\", \\\"tactics\\\":[\\\"intros\\\", \\\"refine \u27e8_,_\u27e9; intro h; cases h; exact and.intro \u2039_\u203a \u2039_\u203a\\\"]}\",\n--   x@\u27e8nm, tacs\u27e9 \u2190 io.run_tactic' (get_decl_name_and_tactics msg),\n--   io.put_str_ln' format! \"{x}\"\n\n-- }\n\nexample : \u2200 {a b : Prop}, a \u2227 b \u2194 b \u2227 a :=\nbegin\n  intros, refine \u27e8_,_\u27e9; intro h; cases h; exact and.intro \u2039_\u203a \u2039_\u203a\nend\n\nmeta def example_msg : tactic json := json.parse\n  \" { \\\"task_id\\\":\\\"finset.filter_not\\\",\n      \\\"tactics\\\":[\n        \\\"intros a\\\",\n        \\\"intros\\\",\n        \\\"ext b\\\",\n        \\\"by_cases p b; simp *\\\"\n      ]\n    }\"\n\nmeta def buggy_example_msg : tactic json := json.parse $\n  \" { \\\"task_id\\\":\\\"mvqpf.cofix.bisim\\\",\n      \\\"tactics\\\":[\n        \\\"intros x y h\\\",\n        \\\"rintros x\u2080 y\u2080 q\u2080 hr\\\",\n        \\\"intros x y h\\\",\n        \\\"induction x using fin2.elim0\\\"\n      ]\n    }\"\n\nmeta def replay_proof (namespaces : list name := []) :\n  (name \u00d7 list string) \u2192 tactic expr := \u03bb \u27e8decl_name, tacs\u27e9, do {\n  env\u2080 \u2190 tactic.get_env,\n  tsd \u2190 get_tsd_at_decl decl_name,\n  env \u2190 get_env_at_decl decl_name,\n  tactic.set_env_core env,\n  rebuild_tactic_state tsd,\n  [g] \u2190 tactic.get_goals,\n  goal \u2190 tactic.infer_type g,\n  tactic.trace format! \"[replay_proof] TACTICS: {tacs}\",\n  for_ tacs $ \u03bb tac_str, do {\n    tac \u2190 parse_itactic tac_str,\n    tac\n  },\n\n  pf \u2190 tactic.get_assignment g >>= tactic.instantiate_mvars,\n  tactic.set_env_core env\u2080,\n  tactic.done <|> tactic.fail format! \"[replay_proof] ERROR: NOT DONE WITH {decl_name}\",\n  validate_proof pf,\n  pure pf\n}\n\n-- this should pass all checks\n-- run_cmd do {\n--   msg \u2190 example_msg,\n--   get_decl_name_and_tactics msg >>= replay_proof\n-- }\n\n-- this should pass `done` check but fail validation\n-- run_cmd do {\n--   msg \u2190 buggy_example_msg,\n--   get_decl_name_and_tactics msg >>= replay_proof\n-- }\n\nmeta def pf_term_size (pf : expr) : tactic \u2115 := do {\n  str \u2190 (format.to_string \u2218 format.flatten) <$> tactic.pp pf,\n  pure str.length\n}\n\nmeta def build_namespace_index (decls_file : string) : io $ dict name (list name) := do {\n    nm_strs \u2190 (io.mk_file_handle decls_file io.mode.read >>= \u03bb f,\n    (string.split (\u03bb c, c = '\\n') <$> buffer.to_string <$> io.fs.read_to_end f)),\n\n  -- io.put_str_ln' format!\"NM STRS: {nm_strs}\",\n\n  (nms : list (name \u00d7 list name)) \u2190 (nm_strs.filter $ \u03bb nm_str, string.length nm_str > 0).mmap $ \u03bb nm_str, do {\n    ((io.run_tactic' \u2218 parse_decl_nm_and_open_ns) $ nm_str)\n  },\n\n  io.put_str_ln' format!\"[evaluation_harness_from_decls_file] GOT {nms.length} NAMES\",\n\n  -- io.put_str_ln' format!\"NMS: {nms}\",\n\n  -- additionally filter out non-theorems\n  -- TODO(): do this offline in a separate Lean script\n  let nms_unfiltered_len := nms.length,\n  nms \u2190 io.run_tactic' $ do {\n    env \u2190 tactic.get_env,\n    nms.mfilter $ \u03bb \u27e8nm, _\u27e9, (do {\n      decl \u2190 env.get nm,\n      pure decl.is_theorem\n    } <|> pure ff)\n  },\n  pure $ dict.of_list nms\n}\n\nmeta def mk_shorter_proof_jsonline (old_size : \u2115) (new_size : \u2115)\n  (decl_nm : name) (tacs : list string) : json := do {\n  json.array $ [old_size, new_size, decl_nm.to_string, json.array $ json.of_string <$> tacs]\n}\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  jsons_file \u2190 args.nth_except 0 \"jsons_file\",\n  dest \u2190 args.nth_except 1 \"dest\",\n  ns_index_path \u2190 args.nth_except 2 \"ns_index\",\n  msg_strs \u2190 io.mk_file_handle jsons_file io.mode.read >>= \u03bb f,\n    (string.split (\u03bb c, c = '\\n') <$> buffer.to_string <$> io.fs.read_to_end f),\n  let msg_strs := msg_strs.filter (\u03bb x, x.length > 0),\n  msgs \u2190 msg_strs.mmap (\u03bb msg_str, lift_option $ json.parse msg_str),\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n  ns_index \u2190 build_namespace_index ns_index_path,\n  for_ msgs $ \u03bb msg, io.run_tactic' $ do {\n    x@\u27e8decl_nm, tacs\u27e9 \u2190 get_decl_name_and_tactics msg,\n    if tacs.length = 0 then tactic.trace format! \"SKIPPING {decl_nm}\" else do\n    tactic.trace format! \"REPLAYING {decl_nm}\",\n    old_pf_term \u2190 tactic.get_proof_from_env decl_nm,\n    tactic.trace format! \"PROCESSING DECL_NM {decl_nm}\",\n    env\u2080 \u2190 tactic.get_env,\n    tactic.try $ do {\n      open_ns \u2190 ns_index.get decl_nm,\n      new_pf_term \u2190 replay_proof open_ns x,\n      tactic.set_env_core env\u2080,\n      old_size \u2190 pf_term_size old_pf_term,\n      tactic.trace format! \"OLD SIZE: {old_size}\",\n      new_size \u2190 pf_term_size new_pf_term,\n      tactic.trace format! \"NEW SIZE: {new_size}\",\n      when (new_size < old_size) $ tactic.unsafe_run_io $ do {\n        io.put_str_ln \"FOUND SMALLER PROOF\",\n        io.fs.put_str_ln_flush dest_handle $\n          json.unparse $ mk_shorter_proof_jsonline old_size new_size decl_nm tacs\n      }},\n    tactic.set_env_core env\u2080\n  }\n}\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/tools/proof_replay.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692193015555, "lm_q2_score": 0.0627892042126289, "lm_q1q2_score": 0.022790548433623853}}
{"text": "inductive Con : Type\n| nil : Con\n| foo : Con\n\ninductive Conw : Con \u2192 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)_{\u2264 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 = \u2211 a_{n,s}T^n \u2208 T\u2124\u27e6T\u27e7` such that `\u2211_{n,s} |a_{n,s}|r'^n \u2264 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' : \u211d\u22650} {S : Type u} [fintype S] {c c\u2081 c\u2082 c\u2083 : \u211d\u22650}\n\n/-- `Lbar_le r' S c` is the set of power series\n`F_s = \u2211 a_{n,s}T^n \u2208 T\u2124[[T]]` such that `\u2211_{n,s} |a_{n,s}|r'^n \u2264 c` -/\ndef Lbar_le (r' : \u211d\u22650) (S : Type u) [fintype S] (c : \u211d\u22650) :=\n{ F : Lbar r' S // F \u2208 filtration (Lbar r' S) c }\n\nnamespace Lbar_le\n\ninstance has_coe : has_coe (Lbar_le r' S c) (Lbar r' S) := \u27e8subtype.val\u27e9\n\ninstance has_coe_to_fun : has_coe_to_fun (Lbar_le r' S c) (\u03bb F, S \u2192 \u2115 \u2192 \u2124) := \u27e8\u03bb F, F.1\u27e9\n\n@[simp] lemma coe_coe_to_fun (F : Lbar_le r' S c) : \u21d1(F : Lbar r' S) = F := rfl\n\n@[simp] lemma coe_mk (x h) : ((\u27e8x, h\u27e9 : Lbar_le r' S c) : S \u2192 \u2115 \u2192 \u2124) = 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 (\u03bb n, (\u2191(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 \u2208 filtration (Lbar r' S) c := x.property\n\n/-- The inclusion map `Lbar_le r' S c\u2081 \u2192 Lbar_le r' S c\u2082` for `c\u2081 \u2264 c\u2082`. -/\nprotected def cast_le [hc : fact (c\u2081 \u2264 c\u2082)] (x : Lbar_le r' S c\u2081) : Lbar_le r' S c\u2082 :=\n\u27e8\u27e8x, x.coeff_zero, x.summable\u27e9, filtration_mono hc.out x.mem_filtration\u27e9\n\n@[simp] lemma coe_cast_le [hc : fact (c\u2081 \u2264 c\u2082)] (x : Lbar_le r' S c\u2081) :\n  ((x.cast_le : Lbar_le r' S c\u2082) : Lbar r' S) = x :=\nby { ext, refl }\n\n@[simp] lemma cast_le_apply [hc : fact (c\u2081 \u2264 c\u2082)] (x : Lbar_le r' S c\u2081) (s : S) (i : \u2115) :\n  (x.cast_le : Lbar_le r' S c\u2082) s i = x s i :=\nrfl\n\nlemma injective_cast_le [fact (c\u2081 \u2264 c\u2082)] :\n  function.injective (Lbar_le.cast_le : Lbar_le r' S c\u2081 \u2192 Lbar_le r' S c\u2082) :=\n\u03bb 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 : (\u21d1x: S \u2192 \u2115 \u2192 \u2124) = y) : x = y :=\nby { ext:2, exact h }\n\ninstance : has_zero (Lbar_le r' S c) := \u27e8\u27e80, zero_mem_filtration _\u27e9\u27e9\n\ninstance : inhabited (Lbar_le r' S c) := \u27e80\u27e9\n\nend Lbar_le\n\nvariables (c\u2083)\n\n/-- The addition on `Lbar_le`.\nThis addition is not homogeneous, but has type\n`(Lbar_le r' S c\u2081) \u2192 (Lbar_le r' S c\u2082) \u2192 (Lbar_le r' S c\u2083)`\nfor `c\u2081 + c\u2082 \u2264 c\u2083`. -/\ndef Lbar_le.add [h : fact (c\u2081 + c\u2082 \u2264 c\u2083)]\n  (F : Lbar_le r' S c\u2081) (G : Lbar_le r' S c\u2082) :\n  Lbar_le r' S c\u2083 :=\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\u2081 + c\u2082 \u2264 c\u2083)] :\n  Lbar_le r' S c\u2081 \u00d7 Lbar_le r' S c\u2082 \u2192 Lbar_le r' S c\u2083 :=\n\u03bb x, Lbar_le.add c\u2083 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 : \u2115) (F : Lbar_le r' S c) : Lbar_bdd r' \u27e8S\u27e9 c M :=\n{ to_fun := \u03bb 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 (\u03bb i, (\u2191(F s i).nat_abs * r' ^i)) (M+1),\n    exact sum_le_tsum _ (\u03bb _ _, subtype.property (_ : \u211d\u22650)) (F.summable s),\n  end }\n\nlemma truncate_surjective (M : \u2115) :\n  function.surjective (truncate M : Lbar_le r' S c \u2192 Lbar_bdd r' \u27e8S\u27e9 c M) :=\nbegin\n  intro x,\n  have aux : _ := _,\n  let F : Lbar_le r' S c :=\n  \u27e8{ to_fun := \u03bb s n, if h : n < M + 1 then x s \u27e8n, h\u27e9 else 0,\n     summable' := aux, .. }, _\u27e9,\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 [\u2190 sum_add_tsum_nat_add' (M + 1), tsum_eq_zero, add_zero],\n    { rw \u2190 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 : \u2200 M, truncate M x = truncate M y) : x = y :=\nbegin\n  ext s n,\n  change (truncate n x).1 s \u27e8n, by linarith\u27e9 = (truncate n y).1 s \u27e8n,_\u27e9,\n  rw cond,\nend\n\nlemma truncate_cast_le (M : \u2115) [hc : fact (c\u2081 \u2264 c\u2082)] (x : Lbar_le r' S c\u2081) :\n  truncate M (Lbar_le.cast_le x : Lbar_le r' S c\u2082) = 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 : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M) : S \u2192 \u2115 \u2192 \u2124 :=\n\u03bb s n, (T n).1 s \u27e8n, lt_add_one n\u27e9\n\n@[simp] lemma mk_seq_zero {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M} (s : S) : mk_seq T s 0 = 0 :=\n(T 0).coeff_zero s\n\nlemma mk_seq_eq_of_compat {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M)\n  {s : S} {n : \u2115} {M : \u2115} (hnM : n < M + 1) :\n  mk_seq T s n = (T M).1 s \u27e8n, hnM\u27e9 :=\nbegin\n  have hnM : n \u2264 M := nat.lt_succ_iff.mp hnM,\n  unfold mk_seq,\n  rw \u2190 compat n M hnM,\n  apply Lbar_bdd.transition_eq,\nend\n\nlemma mk_seq_sum_range_eq (T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M)\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) (s : S) (n) :\n  \u2211 i in finset.range (n+1), (\u2191(mk_seq T s i).nat_abs * r'^i) =\n  \u2211 i : fin (n+1), (\u2191((T n).1 s i).nat_abs * r'^(i:\u2115)) :=\nbegin\n  rw \u2190 fin.sum_univ_eq_sum_range,\n  congr',\n  ext \u27e8i, hi\u27e9,\n  congr',\n  exact mk_seq_eq_of_compat compat _,\nend\n\nlemma mk_seq_summable {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) (s : S) :\n  summable (\u03bb (n : \u2115), (\u2191(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 (\u03bb _ _, _) (finset.mem_univ s),\n    apply zero_le' },\nend\n\nopen filter\n\nlemma mk_seq_tendsto {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) :\n  tendsto (\u03bb (n : \u2115), \u2211 (s : S), \u2211  i in finset.range n, (\u2191(mk_seq T s i).nat_abs * r'^i))\n  at_top (nhds $ \u2211 (s : S), \u2211' n, (\u2191(mk_seq T s n).nat_abs * r'^n)) :=\ntendsto_finset_sum _ $ \u03bb s _, has_sum.tendsto_sum_nat $ summable.has_sum $ mk_seq_summable compat s\n\nlemma mk_seq_sum_le {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) :\n  (\u2211 s, \u2211' (n : \u2115), (\u2191(mk_seq T s n).nat_abs * r' ^ n)) \u2264 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 : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) (M : \u2115) :\n  truncate M \u27e8\u27e8mk_seq T, mk_seq_zero, mk_seq_summable compat\u27e9, mk_seq_sum_le compat\u27e9 = T M :=\nbegin\n  ext s \u27e8i, hi\u27e9,\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' \u27e8S\u27e9 c M`.\nThis realizes `Lbar_le` as the profinite limit of the spaces `Lbar_bdd`,\nsee also `Lbar_le.eqv`. -/\ndef of_compat {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) : Lbar_le r' S c :=\n\u27e8\u27e8mk_seq T, mk_seq_zero, mk_seq_summable compat\u27e9, mk_seq_sum_le compat\u27e9\n\n@[simp] lemma truncate_of_compat {T : \u03a0 (M : \u2115), Lbar_bdd r' \u27e8S\u27e9 c M}\n  (compat : \u2200 (M N : \u2115) (h : M \u2264 N), Lbar_bdd.transition r' h (T N) = T M) (M : \u2115) :\n  truncate M (of_compat compat) = T M :=\nbegin\n  ext s \u27e8i, hi\u27e9,\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' \u27e8S\u27e9 c M`. -/\ndef eqv : Lbar_le r' S c \u2243 Lbar_bdd.limit r' \u27e8S\u27e9 c :=\n{ to_fun := \u03bb F, \u27e8\u03bb N, truncate _ F, by { intros, refl }\u27e9,\n  inv_fun := \u03bb F, of_compat F.2,\n  left_inv := \u03bb x, by { ext, refl },\n  right_inv := by { rintro \u27e8x, hx\u27e9, 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' \u27e8S\u27e9 c)} : is_open (eqv \u207b\u00b9' U) \u2194 is_open U :=\nbegin\n  rw is_open_induced_iff,\n  have := function.surjective.preimage_injective (equiv.surjective (eqv : Lbar_le r' S c \u2243 _)),\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' \u27e8S\u27e9 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 \u2243\u209c Lbar_bdd.limit r' \u27e8S\u27e9 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 [\u2190 eqv.image_eq_preimage, \u2190 is_open_iff],\n    rwa eqv.preimage_image U,\n  end,\n  ..eqv }\n\nlemma truncate_eq (M : \u2115) :\n  (truncate M : Lbar_le r' S c \u2192 Lbar_bdd r' \u27e8S\u27e9 c M) = (Lbar_bdd.proj M) \u2218 homeo := rfl\n\ninstance : t2_space (Lbar_le r' S c) :=\n\u27e8\u03bb x y h, separated_by_continuous homeo.continuous (\u03bb c, h $ homeo.injective c)\u27e9\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 \u27e8h\u27e9 := (by apply_instance : compact_space (Lbar_bdd.limit r' \u27e8S\u27e9 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 \u27e8h\u27e9 := (by apply_instance : totally_disconnected_space (Lbar_bdd.limit r' \u27e8S\u27e9 c)),\n    exact h _ (by tauto) (is_preconnected.image hA _ homeo.continuous.continuous_on)\n  end }\n\nlemma continuous_iff {\u03b1 : Type*} [topological_space \u03b1] (f : \u03b1 \u2192 Lbar_le r' S c) :\n  continuous f \u2194 (\u2200 M, continuous ((truncate M) \u2218 f)) :=\nbegin\n  split,\n  { intros hf M,\n    rw [truncate_eq, function.comp.assoc],\n    revert M,\n    rw \u2190 Lbar_bdd.continuous_iff,\n    refine continuous.comp homeo.continuous hf },\n  { intro h,\n    suffices : continuous (homeo \u2218 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\u2081 + c\u2082) : Lbar_le r' S c\u2081 \u00d7 Lbar_le r' S c\u2082 \u2192 Lbar_le r' S (c\u2081+c\u2082)) :=\nbegin\n  rw continuous_iff,\n  intros M,\n  have : truncate M \u2218 (\u03bb x : Lbar_le r' S c\u2081 \u00d7 Lbar_le r' S c\u2082, Lbar_le.add _ x.1 x.2) =\n    (\u03bb x : (Lbar_le r' S c\u2081 \u00d7 Lbar_le r' S c\u2082), Lbar_bdd.add (truncate M x.1) (truncate M x.2)) :=\n    by {ext; refl},\n  erw this,\n  suffices : continuous (\u03bb x : Lbar_bdd r' \u27e8S\u27e9 c\u2081 M \u00d7 Lbar_bdd r' \u27e8S\u27e9 c\u2082 M, Lbar_bdd.add x.1 x.2),\n  { have claim : (\u03bb x : (Lbar_le r' S c\u2081 \u00d7 Lbar_le r' S c\u2082),\n      Lbar_bdd.add (truncate M x.1) (truncate M x.2)) =\n      (\u03bb x : Lbar_bdd r' \u27e8S\u27e9 c\u2081 M \u00d7 Lbar_bdd r' \u27e8S\u27e9 c\u2082 M, Lbar_bdd.add x.1 x.2) \u2218\n      (\u03bb x : Lbar_le r' S c\u2081 \u00d7 Lbar_le r' S c\u2082, (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 \u2192 Lbar_le r' S c) :=\nbegin\n  rw continuous_iff,\n  intro M,\n  change continuous (\u03bb 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' : \u211d\u22650) (S : Type u) [fintype S] (c\u2081 c\u2082 : \u211d\u22650) [hc : fact (c\u2081 \u2264 c\u2082)] :\n  continuous (@Lbar_le.cast_le r' S _ c\u2081 c\u2082 _) :=\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\u207b\u00b9` is continuous. -/\n\nlemma continuous_of_normed_group_hom\n  (f : (Lbar r' S) \u2192+ (Lbar r' S))\n  (g : Lbar_le r' S c\u2081 \u2192 Lbar_le r' S c\u2082)\n  (h : \u2200 x, \u2191(g x) = f x)\n  (H : \u2200 M, \u2203 N, \u2200 (F : Lbar r' S),\n    (\u2200 s i, i < N + 1 \u2192 F s i = 0) \u2192 (\u2200 s i, i < M + 1 \u2192 f F s i = 0)) :\n  continuous g :=\nbegin\n  rw continuous_iff,\n  intros M,\n  rcases H M with \u27e8N, hN\u27e9,\n  let \u03c6 : Lbar_bdd r' \u27e8S\u27e9 c\u2081 N \u2192 Lbar_le r' S c\u2081 :=\n    classical.some (truncate_surjective N).has_right_inverse,\n  have h\u03c6 : function.right_inverse \u03c6 (truncate N) :=\n    classical.some_spec (truncate_surjective N).has_right_inverse,\n  suffices : truncate M \u2218 g = truncate M \u2218 g \u2218 \u03c6 \u2218 truncate N,\n  { rw [this, \u2190 function.comp.assoc, \u2190 function.comp.assoc],\n    apply continuous_bot.comp continuous_truncate },\n  ext1 x,\n  suffices : \u2200 s i, i < M + 1 \u2192 (g x) s i = (g (\u03c6 (truncate N x))) s i,\n  { ext s i, dsimp [function.comp], apply this, exact i.property },\n  intros s i hi,\n  rw [\u2190 coe_coe_to_fun, h, \u2190 coe_coe_to_fun, h, \u2190 sub_eq_zero],\n  show ((f x) - f (\u03c6 (truncate N x))) s i = 0,\n  rw [\u2190 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 : \u2200 s i, (truncate N x) s i = truncate N (\u03c6 (truncate N x)) s i,\n  { exact this s \u27e8i, hi\u27e9 },\n  intros s i, congr' 1,\n  rw h\u03c6 (truncate N x)\nend\n\n/-- Construct a map between `Lbar_le r' S c\u2081` and `Lbar_le r' S c\u2082`\nfrom a bounded group homomorphism `Lbar r' S \u2192 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 : \u211d\u22650} (c\u2081 c\u2082 : \u211d\u22650) [hc : fact (C * c\u2081 \u2264 c\u2082)]\n  (f : Lbar r' S \u2192+ Lbar r' S) (h : f \u2208 filtration (Lbar r' S \u2192+ Lbar r' S) C)\n  (F : Lbar_le r' S c\u2081) :\n  Lbar_le r' S c\u2082 :=\n\u27e8{ to_fun := \u03bb 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)\u27e9\n\nlemma continuous_hom_of_normed_group_hom {C : \u211d\u22650} (c\u2081 c\u2082 : \u211d\u22650)\n  [hc : fact (C * c\u2081 \u2264 c\u2082)]\n  (f : Lbar r' S \u2192+ Lbar r' S) (h : f \u2208 filtration (Lbar r' S \u2192+ Lbar r' S) C)\n  (H : \u2200 M, \u2203 N, \u2200 (F : Lbar r' S),\n    (\u2200 s i, i < N + 1 \u2192 F s i = 0) \u2192 (\u2200 s i, i < M + 1 \u2192 f F s i = 0)) :\n  continuous (hom_of_normed_group_hom c\u2081 c\u2082 f h) :=\ncontinuous_of_normed_group_hom f _ (\u03bb F, by { ext, refl }) H\n\n@[simp] lemma coe_hom_of_normed_group_hom_apply {C : \u211d\u22650} (c\u2081 c\u2082 : \u211d\u22650)\n  [hc : fact (C * c\u2081 \u2264 c\u2082)]\n  (f : Lbar r' S \u2192+ Lbar r' S) (h : f \u2208 filtration (Lbar r' S \u2192+ Lbar r' S) C)\n  (F : (Lbar_le r' S c\u2081)) (s : S) (i : \u2115) :\n  (hom_of_normed_group_hom c\u2081 c\u2082 f h) F s i = f F s i := rfl\n\nsection Tinv\n\n/-!\n### The action of T\u207b\u00b9\n-/\n\n/-- The action of `T\u207b\u00b9` as map `Lbar_le r S c\u2081 \u2192 Lbar_le r S c\u2082`.\n\nThis action is induced by the action of `T\u207b\u00b9` on power series modulo constants: `\u2124\u27e6T\u27e7/\u2124`.\nSo `T\u207b\u00b9` sends `T^(n+1)` to `T^n`, but `T^0 = 0`. -/\ndef Tinv {r : \u211d\u22650} {S : Type u} [fintype S] {c\u2081 c\u2082 : \u211d\u22650} [fact (0 < r)] [fact (r\u207b\u00b9 * c\u2081 \u2264 c\u2082)] :\n  Lbar_le r S c\u2081 \u2192 Lbar_le r S c\u2082 :=\nhom_of_normed_group_hom c\u2081 c\u2082 Lbar.Tinv Lbar.Tinv_mem_filtration\n\n@[simp] lemma Tinv_apply {r : \u211d\u22650} {S : Type u} [fintype S] {c\u2081 c\u2082 : \u211d\u22650}\n  [fact (0 < r)] [fact (r\u207b\u00b9 * c\u2081 \u2264 c\u2082)] (F : Lbar_le r S c\u2081) (s : S) (i : \u2115) :\n  (Tinv F : Lbar_le r S c\u2082) s i = Lbar.Tinv (F : Lbar r S) s i :=\nrfl\n\nlemma continuous_Tinv (r : \u211d\u22650) (S : Type u) [fintype S] (c\u2081 c\u2082 : \u211d\u22650)\n  [fact (0 < r)] [fact (r\u207b\u00b9 * c\u2081 \u2264 c\u2082)] :\n  continuous (@Tinv r S _ c\u2081 c\u2082 _ _) :=\ncontinuous_hom_of_normed_group_hom c\u2081 c\u2082 _ 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 \u27f6 T) : Lbar_le r' S c \u2192 Lbar_le r' T c := \u03bb F,\n\u27e8(F : Lbar r' S).map f, Lbar.nnnorm_map_le_of_nnnorm_le _ _ F.2\u27e9\n\nlemma map_truncate {S T : Fintype} (f : S \u27f6 T) (F : Lbar_le r' S c) (M : \u2115) :\n  ((F.truncate M).map f) = (F.map f).truncate M := rfl\n\nlemma map_continuous {S T : Fintype} (f : S \u27f6 T) : continuous\n  (map f : Lbar_le r' S c \u2192 Lbar_le r' T c) :=\nbegin\n  rw continuous_iff,\n  intros M,\n  have : truncate M \u2218 (map f : Lbar_le r' S c \u2192 Lbar_le r' T c) =\n    Lbar_bdd.map f \u2218 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} \u2964 Profinite.{u} :=\n{ obj := \u03bb S, Profinite.of $ Lbar_le r' S c,\n  map := \u03bb S T f,\n  { to_fun := map f,\n    continuous_to_fun := map_continuous _ },\n  map_id' := \u03bb S, begin\n    ext1,\n    exact subtype.ext x.1.map_id,\n  end,\n  map_comp' := \u03bb S T U f g, begin\n    ext1,\n    exact subtype.ext (x.1.map_comp f g),\n  end }\n\nvariables (c\u2081 c\u2082)\n/-- The functor sending `S` to the (categorical) product\n  of `Lbar_le r' S c\u2081` and `Lbar_le r' S c\u2082`. -/\n@[simps]\ndef Fintype_functor_prod [fact (0 < r')] : Fintype.{u} \u2964 Profinite.{u} :=\n{ obj := \u03bb S, (S,S),\n  map := \u03bb _ _ f, (f,f) } \u22d9\n    (Fintype_functor r' c\u2081).prod (Fintype_functor r' c\u2082) \u22d9\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\u2081 c\u2082 \u27f6 Fintype_functor.{u} r' (c\u2081 + c\u2082) :=\n{ app := \u03bb S, (Profinite.prod_iso _ _).hom \u226b \u27e8add' _, continuous_add'\u27e9,\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 : \u2200 {A B C : Profinite} (f : A \u27f6 B) (g : B \u27f6 C) (a : A),\n      (f \u226b g) a = g (f a) := \u03bb _ _ _ _ _ _, rfl,\n    congr,\n    { have : binary_fan.fst (limit.cone (pair (Profinite.of (Lbar_le r' \u21a5T c\u2081))\n        (Profinite.of (Lbar_le r' \u21a5T c\u2082)))) = category_theory.limits.prod.fst := rfl,\n      rw [this, \u2190 useful, category_theory.limits.prod.map_fst],\n      refl },\n    { have : binary_fan.snd (limit.cone (pair (Profinite.of (Lbar_le r' \u21a5T c\u2081))\n        (Profinite.of (Lbar_le r' \u21a5T c\u2082)))) = category_theory.limits.prod.snd := rfl,\n      rw [this, \u2190 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 \u27f6 Fintype_functor.{u} r' c :=\n{ app := \u03bb S, \u27e8Lbar_le.neg, Lbar_le.continuous_neg\u27e9,\n  naturality' := begin\n    intros A B f,\n    ext,\n    dsimp [map, neg],\n    simp,\n  end }\n\nvariables {c\u2081 c\u2082}\n\nopen category_theory\n\n/-- A bifunctor version of `Fintype_functor`, where `c` can vary. -/\n@[simps]\ndef Fintype_bifunctor [fact (0 < r')] : \u211d\u22650 \u2964 Fintype.{u} \u2964 Profinite.{u} :=\n{ obj := \u03bb c, Fintype_functor r' c,\n  map := \u03bb c\u2081 c\u2082 f,\n  { app := \u03bb S,\n    { to_fun := @Lbar_le.cast_le r' S _ c\u2081 c\u2082 \u27e8le_of_hom f\u27e9,\n      continuous_to_fun := by apply continuous_cast_le } },\n  map_id' := \u03bb c, by { ext, refl },\n  map_comp' := \u03bb 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} \u2964 Profinite.{u} :=\nProfinite.extend (Fintype_functor r' c)\n\nvariables (c\u2081 c\u2082)\n\n/-- The profinite variant of `Fintype_functor_prod`. -/\n@[simps]\ndef functor_prod [fact (0 < r')] : Profinite.{u} \u2964 Profinite.{u} :=\n{ obj := \u03bb S, (S,S), map := \u03bb _ _ f, (f, f) } \u22d9\n  (functor r' c\u2081).prod (functor r' c\u2082) \u22d9\n  (uncurry.obj prod.functor)\n\n/-- A cone over `(S.fintype_diagram \u22d9 Fintype_functor_prod r' c\u2081 c\u2082)` used in the definition\n  of `add_functor`. -/\ndef functor_prod_cone [fact (0 < r')] (S : Profinite) :\n  cone (S.fintype_diagram \u22d9 Fintype_functor_prod.{u} r' c\u2081 c\u2082) :=\n{ X := (functor_prod r' c\u2081 c\u2082).obj S,\n  \u03c0 :=\n  { app := \u03bb I, category_theory.limits.prod.map (limit.\u03c0 _ I) (limit.\u03c0 _ I),\n    naturality' := begin\n      intros I J f,\n      dsimp [Fintype_functor_prod],\n      simp [\u2190 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\u2081 c\u2082 \u27f6 functor.{u} r' (c\u2081 + c\u2082) :=\n-- Why doesn't this work without the \"by apply ...\"?\n{ app := \u03bb S, by apply limit.lift _ (functor_prod_cone r' c\u2081 c\u2082 S) \u226b\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_\u03c0],\n    change _ = _ \u226b limit.\u03c0 _ _ \u226b _,\n    simp_rw [\u2190 category.assoc, limits.limit.lift_\u03c0],\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) \u27f6 Fintype.of I := discrete_quotient.map (le_refl _),\n    erw \u2190 (Fintype_add_functor r' c\u2081 c\u2082).naturality e,\n    simp_rw \u2190 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_\u03c0],\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 \u27f6 functor.{u} r' c :=\n{ app := \u03bb 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\u2081 c\u2082}\n\n/-- A bifunctor version of `functor`, where `c` can vary. -/\n@[simps]\ndef bifunctor [fact (0 < r')] : \u211d\u22650 \u2964 Profinite.{u} \u2964 Profinite.{u} :=\n{ obj := \u03bb c, functor r' c,\n  map := \u03bb 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 \u03b1 \u03b2,\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 \u22d9 functor.{u} r' c \u2245 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 := \u03bb c, show topological_space (Lbar_le r' S c), by apply_instance,\n  t2 := \u03bb c, show t2_space (Lbar_le r' S c), by apply_instance,\n  td := \u03bb c, show totally_disconnected_space (Lbar_le r' S c), by apply_instance,\n  compact := \u03bb c, show compact_space (Lbar_le r' S c), by apply_instance,\n  continuous_add' := \u03bb c\u2081 c\u2082, Lbar_le.continuous_add',\n  continuous_neg' := \u03bb c, Lbar_le.continuous_neg,\n  continuous_cast_le := \u03bb c\u2081 c\u2082,\n  begin\n    introI h,\n    rw show pseudo_normed_group.cast_le = (Lbar_le.cast_le : Lbar_le r' S c\u2081 \u2192 Lbar_le r' S c\u2082),\n      by {ext, refl},\n    exact Lbar_le.continuous_cast_le r' S c\u2081 c\u2082,\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')] : \u211d\u22650 \u2964 Profinite.{u} \u2964 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 \u2964 Type*`. -/\n@[nolint check_univs] -- TODO remove this\ndef profinite [fact (0 < r')] : Profinite \u2964 Type* :=\n(as_small.down \u22d9 profinite_diagram r').flip \u22d9 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} \u2964 (as_small.{u+1} Profinite.{u})\u1d52\u1d56 \u2964 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  \u211d\u22650 \u2964 Profinite.{u} \u2964 (as_small.{u+1} Profinite.{u})\u1d52\u1d56 \u2964 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} \u2964 (as_small.{u+1} Profinite.{u})\u1d52\u1d56 \u2964 Type (u+1) :=\n(as_small.down.{_ _ (u+1)} \u22d9 precondensed_diagram.{u} r').flip  \u22d9 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": "/-\nCopyright (c) 2022 Jo\u00ebl Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jo\u00ebl Riou\n-/\n\nimport algebraic_topology.simplicial_object\nimport category_theory.limits.shapes.images\nimport for_mathlib.simplex_category.factorisations\nimport category_theory.limits.shapes.finite_products\nimport algebraic_topology.simplicial_set\nimport category_theory.limits.preserves.shapes.products\nimport algebraic_topology.split_simplicial_object\nimport for_mathlib.inclusions_mono\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.category\nopen category_theory.limits\nopen opposite\nopen simplex_category\nopen_locale simplicial\n\nuniverse u\n\nvariables {C : Type*} [category C]\n\nnamespace simplicial_object\n\nnamespace splitting\n\nnamespace index_set\n\nvariables {\u0394 : simplex_category\u1d52\u1d56} (A : index_set \u0394)\n\n/-\nlemma eq_id_iff_len_le : A.eq_id \u2194 \u0394.unop.len \u2264 A.1.unop.len :=\nbegin\n  split,\n  { intro h,\n    rw eq_id_iff_len_eq at h,\n    rw h, },\n  { intro h,\n    rw eq_id_iff_len_eq,\n    refine le_antisymm (len_le_of_epi (infer_instance : epi A.e)) h, },\nend\n\nlemma eq_id_iff_mono : A.eq_id \u2194 mono A.e :=\nbegin\n  split,\n  { intro h,\n    dsimp at h,\n    subst h,\n    dsimp only [id, e],\n    apply_instance, },\n  { intro h,\n    rw eq_id_iff_len_le,\n    exact len_le_of_mono h, }\nend-/\n\nend index_set\n\nend splitting\n\nend simplicial_object\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/split_simplicial_object.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.048136771970091786, "lm_q1q2_score": 0.022753456728107985}}
{"text": "/- \n# A list of all of the attributes that are in Lean that I have encountered.\n\n- `@[elab_as_eliminator]`\n- `@[simp]` When a lemma is tagged with `simp`, it becomes available to the `simp [*]` tactic.\n- `@[derive decidable_eq]` will automatically ad\n- `attribute [pp_using_anonymous_constructor] state_t`. Use this if your structure is a singleton and you want to skip the wrapper when you pretty print.\n\n\n# A list of all of non-declarations in Lean\n\n- `run_cmd` runs a `tactic _`. The tactic has a single goal `\u22a2 true`. \n- `set_option`\n    + `pp.all`\n    + ... [TODO] just the useful ones.\n- `#check` \n- `#eval`  \n- `#print` \n\n\n -/", "meta": {"author": "EdAyers", "repo": "edlib", "sha": "78b8c5d91f023f939c102837d748868e2f3ed27d", "save_path": "github-repos/lean/EdAyers-edlib", "path": "github-repos/lean/EdAyers-edlib/edlib-78b8c5d91f023f939c102837d748868e2f3ed27d/docs/attributes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.07159119993976201, "lm_q1q2_score": 0.0227249272458193}}
{"text": "/-\nCopyright (c) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis\n-/\nimport data.string.defs\nimport data.option.defs\nimport tactic.derive_inhabited\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\nattribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind\n\n@[priority 100] meta instance has_reflect.has_to_pexpr {\u03b1} [has_reflect \u03b1] : has_to_pexpr \u03b1 :=\n\u27e8\u03bb b, pexpr.of_expr (reflect b)\u27e9\n\nnamespace binder_info\n\n/-! ### Declarations about `binder_info` -/\n\ninstance : inhabited binder_info := \u27e8 binder_info.default \u27e9\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : binder_info \u2192 string \u00d7 string\n| binder_info.implicit        := (\"{\", \"}\")\n| binder_info.strict_implicit := (\"{{\", \"}}\")\n| binder_info.inst_implicit   := (\"[\", \"]\")\n| _                           := (\"(\", \")\")\n\nend binder_info\n\nnamespace name\n\n/-! ### Declarations about `name` -/\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef map_prefix (f : name \u2192 option name) : name \u2192 name\n| anonymous := anonymous\n| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')\n| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\nmeta def deinternalize_field : name \u2192 name\n| (mk_string s name.anonymous) :=\n  let i := s.mk_iterator in\n  if i.curr = '_' then i.next.next_to_string else s\n| n := n\n\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\nmeta def get_nth_prefix : name \u2192 \u2115 \u2192 name\n| nm 0 := nm\n| nm (n + 1) := get_nth_prefix nm.get_prefix n\n\n/-- Auxilliary definition for `pop_nth_prefix` -/\nprivate meta def pop_nth_prefix_aux : name \u2192 \u2115 \u2192 name \u00d7 \u2115\n| anonymous n := (anonymous, 1)\n| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in\n          if height \u2264 n then (anonymous, height + 1)\n          else (nm.update_prefix pfx, height + 1)\n\n/-- Pops the top `n` prefixes from the given name. -/\nmeta def pop_nth_prefix (nm : name) (n : \u2115) : name :=\nprod.fst $ pop_nth_prefix_aux nm n\n\n/-- Pop the prefix of a name -/\nmeta def pop_prefix (n : name) : name :=\npop_nth_prefix n 1\n\n/-- Auxilliary definition for `from_components` -/\nprivate def from_components_aux : name \u2192 list string \u2192 name\n| n [] := n\n| n (s :: rest) := from_components_aux (name.mk_string s n) rest\n\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef from_components : list string \u2192 name :=\nfrom_components_aux name.anonymous\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\nmeta def sanitize_name : name \u2192 name\n| name.anonymous := name.anonymous\n| (name.mk_string s p) := name.mk_string s $ sanitize_name p\n| (name.mk_numeral s p) := name.mk_string sformat!\"n{s}\" $ sanitize_name p\n\n/-- Append a string to the last component of a name -/\ndef append_suffix : name \u2192 string \u2192 name\n| (mk_string s n) s' := mk_string (s ++ s') n\n| n _ := n\n\n/-- The first component of a name, turning a number to a string -/\nmeta def head : name \u2192 string\n| (mk_string s anonymous) := s\n| (mk_string s p)         := head p\n| (mk_numeral n p)        := head p\n| anonymous               := \"[anonymous]\"\n\n/-- Tests whether the first component of a name is `\"_private\"` -/\nmeta def is_private (n : name) : bool :=\nn.head = \"_private\"\n\n/-- Get the last component of a name, and convert it to a string. -/\nmeta def last : name \u2192 string\n| (mk_string s _)  := s\n| (mk_numeral n _) := repr n\n| anonymous        := \"[anonymous]\"\n\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\nmeta def length : name \u2192 \u2115\n| (mk_string s anonymous) := s.length\n| (mk_string s p)         := s.length + 1 + p.length\n| (mk_numeral n p)        := p.length\n| anonymous               := \"[anonymous]\".length\n\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef has_prefix (P : name \u2192 bool) : name \u2192 bool\n| anonymous := ff\n| (mk_string s nm)  := P (mk_string s nm) \u2228 has_prefix nm\n| (mk_numeral s nm) := P (mk_numeral s nm) \u2228 has_prefix nm\n\n/-- Appends `'` to the end of a name. -/\nmeta def add_prime : name \u2192 name\n| (name.mk_string s p) := name.mk_string (s ++ \"'\") p\n| n := (name.mk_string \"x'\" n)\n\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef last_string : name \u2192 string\n| anonymous        := \"[anonymous]\"\n| (mk_string s _)  := s\n| (mk_numeral _ n) := last_string n\n\n/--\nConstructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\nmeta def from_string (s : string) : name :=\nfrom_components $ s.split (= '.')\n\n\n/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\nlibrary_note \"likely generated binder names\"\n\n/--\nCheck whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_simple_name : string \u2192 bool\n| \"\u1fb0\" := tt\n| n :=\n  match n.get_rest \"\u1fb0_\" with\n  | none := ff\n  | some suffix := suffix.is_nat\n  end\n\n/--\nCheck whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_name (n : name) : bool :=\nmatch n with\n| mk_string s anonymous := is_likely_generated_binder_simple_name s\n| _ := ff\nend\n\nend name\n\nnamespace level\n\n/-! ### Declarations about `level` -/\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\nmeta def nonzero : level \u2192 bool\n| (succ _) := tt\n| (max l\u2081 l\u2082) := l\u2081.nonzero || l\u2082.nonzero\n| (imax _ l\u2082) := l\u2082.nonzero\n| _ := ff\n\n/--\n`l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nmeta def fold_mvar {\u03b1} : level \u2192 (name \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 \u03b1\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 \u2218 fold_mvar b f\n| (imax a b) f := fold_mvar a f \u2218 fold_mvar b f\n\nend level\n\n/-! ### Declarations about `binder` -/\n\n/-- The type of binders containing a name, the binding info and the binding type -/\n@[derive decidable_eq, derive inhabited]\nmeta structure binder :=\n  (name : name)\n  (info : binder_info)\n  (type : expr)\n\nnamespace binder\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nprotected meta def to_string (b : binder) : string :=\nlet (l, r) := b.info.brackets in\nl ++ b.name.to_string ++ \" : \" ++ b.type.to_string ++ r\n\nopen tactic\nmeta instance : has_to_string binder := \u27e8 binder.to_string \u27e9\nmeta instance : has_to_format binder := \u27e8 \u03bb b, b.to_string \u27e9\nmeta instance : has_to_tactic_format binder :=\n\u27e8 \u03bb b, let (l, r) := b.info.brackets in\n  (\u03bb e, l ++ b.name.to_string ++ \" : \" ++ e ++ r) <$> pp b.type \u27e9\n\nend binder\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n\n/--\n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def nat.mk_numeral (type has_zero has_one has_add : expr) : \u2115 \u2192 expr :=\nlet z : expr := `(@has_zero.zero.{0} %%type %%has_zero),\n    o : expr := `(@has_one.one.{0} %%type %%has_one) in\nnat.binary_rec z\n  (\u03bb b n e, if n = 0 then o else\n    if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)\n    else `(@bit0.{0} %%type %%has_add %%e))\n\n/--\n`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : \u2124 \u2192 expr\n| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add\n| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in\n            `(@has_neg.neg.{0} %%type %%has_neg %%ne)\n\n/--\n`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nmeta def nat.to_pexpr : \u2115 \u2192 pexpr\n| 0 := ``(0)\n| 1 := ``(1)\n| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))\nnamespace expr\n\n/--\nTurns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\nprotected meta def to_nat : expr \u2192 option \u2115\n| `(has_zero.zero) := some 0\n| `(has_one.one) := some 1\n| `(bit0 %%e) := bit0 <$> e.to_nat\n| `(bit1 %%e) := bit1 <$> e.to_nat\n| `(nat.succ %%e) := (+1) <$> e.to_nat\n| `(nat.zero) := some 0\n| _ := none\n\n/--\nTurns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\nprotected meta def to_int : expr \u2192 option \u2124\n| `(has_neg.neg %%e) := do n \u2190 e.to_nat, some (-n)\n| e                  := coe <$> e.to_nat\n\n/--\n`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\nignoring differences in type and type class arguments.\n-/\nmeta def is_num_eq : expr \u2192 expr \u2192 bool\n| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt\n| `(@has_one.one _ _) `(@has_one.one _ _) := tt\n| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b\n| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b\n| `(-%%a) `(-%%b) := a.is_num_eq b\n| `(%%a/%%a') `(%%b/%%b') :=  a.is_num_eq b\n| _ _ := ff\n\nend expr\n\n/-! ### Declarations about `expr` -/\n\nnamespace expr\nopen tactic\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\nmeta def clean_ids : list name :=\n[``id, ``id_rhs, ``id_delta, ``hidden]\n\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\nmeta def clean (e : expr) : expr :=\ne.replace (\u03bb e n,\n     match e with\n     | (app (app (const n _) _) e') :=\n       if n \u2208 clean_ids then some e' else none\n     | (app (lam _ _ _ (var 0)) e') := some e'\n     | _ := none\n     end)\n\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\nmeta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=\ne.replace $ \u03bbc d, if c = s then some (s'.lift_vars 0 d) else none\n\n/-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/\nprotected meta def apply_replacement_fun (f : name \u2192 name) (e : expr) : expr :=\ne.replace $ \u03bb e d,\n  match e with\n  | expr.const n ls := some $ expr.const (f n) ls\n  | _ := none\n  end\n\n/-- Implementation of `expr.mreplace`. -/\nmeta def mreplace_aux {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) :\n  expr \u2192 \u2115 \u2192 m expr\n| (app f x) n := option.mget_or_else (R (app f x) n)\n  (do Rf \u2190 mreplace_aux f n, Rx \u2190 mreplace_aux x n, return $ app Rf Rx)\n| (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd)\n| (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd)\n| (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n)\n  (do Rty \u2190 mreplace_aux ty n,\n    Ra \u2190 mreplace_aux a n,\n    Rb \u2190 mreplace_aux b n,\n    return $ elet nm Rty Ra Rb)\n| e n := option.mget_or_else (R e n) (return e)\n\n/--\nMonadic analogue of `expr.replace`.\n\nThe `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where\n`n` is the number of binders above `e`.\nIf `R s n` fails, the whole replacement fails.\nIf `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit\nits subexpressions).\nIf `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.\n-/\nmeta def mreplace {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) (e : expr) :\n  m expr :=\nmreplace_aux R e 0\n\n/-- Match a variable. -/\nmeta def match_var {elab} : expr elab \u2192 option \u2115\n| (var n) := some n\n| _ := none\n\n/-- Match a sort. -/\nmeta def match_sort {elab} : expr elab \u2192 option level\n| (sort u) := some u\n| _ := none\n\n/-- Match a constant. -/\nmeta def match_const {elab} : expr elab \u2192 option (name \u00d7 list level)\n| (const n lvls) := some (n, lvls)\n| _ := none\n\n/-- Match a metavariable. -/\nmeta def match_mvar {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 expr elab)\n| (mvar unique pretty type) := some (unique, pretty, type)\n| _ := none\n\n/-- Match a local constant. -/\nmeta def match_local_const {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 binder_info \u00d7 expr elab)\n| (local_const unique pretty bi type) := some (unique, pretty, bi, type)\n| _ := none\n\n/-- Match an application. -/\nmeta def match_app {elab} : expr elab \u2192 option (expr elab \u00d7 expr elab)\n| (app t u) := some (t, u)\n| _ := none\n\n/-- Match an application of `coe_fn`. -/\nmeta def match_app_coe_fn : expr \u2192 option (expr \u00d7 expr \u00d7 expr \u00d7 expr)\n| (app `(@coe_fn %%\u03b1 %%inst %%fexpr) x) := some (\u03b1, inst, fexpr, x)\n| _ := none\n\n/-- Match an abstraction. -/\nmeta def match_lam {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (lam var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a \u03a0 type. -/\nmeta def match_pi {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (pi var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a let. -/\nmeta def match_elet {elab} : expr elab \u2192\n  option (name \u00d7 expr elab \u00d7 expr elab \u00d7 expr elab)\n| (elet var_name type assignment body) := some (var_name, type, assignment, body)\n| _ := none\n\n/-- Match a macro. -/\nmeta def match_macro {elab} : expr elab \u2192\n  option (macro_def \u00d7 list (expr elab))\n| (macro df args) := some (df, args)\n| _ := none\n\n/-- Tests whether an expression is a meta-variable. -/\nmeta def is_mvar : expr \u2192 bool\n| (mvar _ _ _) := tt\n| _            := ff\n\n/-- Tests whether an expression is a sort. -/\nmeta def is_sort : expr \u2192 bool\n| (sort _) := tt\n| e         := ff\n\n/-- Get the universe levels of a `const` expression -/\nmeta def univ_levels : expr \u2192 list level\n| (const n ls) := ls\n| _            := []\n\n/--\nReplace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\nmeta def replace_mvars (e : expr) : expr :=\ne.replace (\u03bb e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)\n\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\nmeta def to_implicit_local_const : expr \u2192 expr\n| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t\n| e := e\n\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.\n-/\nmeta def to_implicit_binder : expr \u2192 expr\n| (local_const n\u2081 n\u2082 _ d) := local_const n\u2081 n\u2082 binder_info.implicit d\n| (lam n _ d b) := lam n binder_info.implicit d b\n| (pi n _ d b) := pi n binder_info.implicit d b\n| e  := e\n\n/-- Returns a list of all local constants in an expression (without duplicates). -/\nmeta def list_local_consts (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_local_constant then insert e' es else es)\n\n/-- Returns the set of all local constants in an expression. -/\nmeta def list_local_consts' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_local_constant then es.insert e' else es)\n\n/-- Returns the unique names of all local constants in an expression. -/\nmeta def list_local_const_unique_names (e : expr) : name_set :=\ne.fold mk_name_set\n  (\u03bb e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es)\n\n/-- Returns a name_set of all constants in an expression. -/\nmeta def list_constant (e : expr) : name_set :=\ne.fold mk_name_set (\u03bb e' _ es, if e'.is_constant then es.insert e'.const_name else es)\n\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\nmeta def list_meta_vars (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_mvar then insert e' es else es)\n\n/-- Returns the set of all meta-variables in an expression. -/\nmeta def list_meta_vars' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_mvar then es.insert e' else es)\n\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\nmeta def list_univ_meta_vars (e : expr) : list name :=\nnative.rb_set.to_list $ e.fold native.mk_rb_set $ \u03bb e' i s,\nmatch e' with\n| (sort u) := u.fold_mvar (flip native.rb_set.insert) s\n| (const _ ls) := ls.foldl (\u03bb s' l, l.fold_mvar (flip native.rb_set.insert) s') s\n| _ := s\nend\n\n/--\nTest `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\nmeta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=\n-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n\u00ac t.list_meta_vars.empty \u2228 e.occurs t\n\n/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/\nmeta def list_names_with_prefix (pre : name) (e : expr) : name_set :=\ne.fold mk_name_set $ \u03bb e' _ l,\n  match e' with\n  | expr.const n _ := if n.get_prefix = pre then l.insert n else l\n  | _ := l\n  end\n\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\nmeta def contains_constant (e : expr) (p : name \u2192 Prop) [decidable_pred p] : bool :=\ne.fold ff (\u03bb e' _ b, if p (e'.const_name) then tt else b)\n\n/--\nReturns true if `e` contains a `sorry`.\n-/\nmeta def contains_sorry (e : expr) : bool :=\ne.fold ff (\u03bb e' _ b, if (is_sorry e').is_some then tt else b)\n\n/--\n`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\nmeta def app_symbol_in (e : expr) (l : list name) : bool :=\nmatch e.get_app_fn with\n| (expr.const n _) := n \u2208 l\n| _ := ff\nend\n\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\nmeta def get_simp_args (e : expr) : tactic (list expr) :=\n-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\nif \u00ac e.is_app then pure [] else do\ncgr \u2190 mk_specialized_congr_lemma_simp e,\npure $ do\n  (arg_kind, arg) \u2190 cgr.arg_kinds.zip e.get_app_args,\n  guard $ arg_kind = congr_arg_kind.eq,\n  pure arg\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\nmeta def simp (t : expr)\n  (cfg : simp_config := {}) (discharger : tactic unit := failed)\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic (expr \u00d7 expr \u00d7 name_set) :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   simplify s to_unfold t cfg `eq discharger\n\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\nmeta def dsimp (t : expr)\n  (cfg : dsimp_config := {})\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic expr :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   s.dsimplify to_unfold t cfg\n\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\nmeta def binding_names : expr \u2192 list name\n| (pi n _ _ e)  := n :: e.binding_names\n| (lam n _ _ e) := n :: e.binding_names\n| e             := []\n\n/-- head-reduce a single let expression -/\nmeta def reduce_let : expr \u2192 expr\n| (elet _ _ v b) := b.instantiate_var v\n| e              := e\n\n/-- head-reduce all let expressions -/\nmeta def reduce_lets : expr \u2192 expr\n| (elet _ _ v b) := reduce_lets $ b.instantiate_var v\n| e              := e\n\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\nmeta def instantiate_lambdas : list expr \u2192 expr \u2192 expr\n| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')\n| _        e              := e\n\n/-- Repeatedly apply `expr.subst`. -/\nmeta def substs : expr \u2192 list expr \u2192 expr | e es := es.foldl expr.subst e\n\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\nmeta def instantiate_lambdas_or_apps : list expr \u2192 expr \u2192 expr\n| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      e              := mk_app e es\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/-- Get the codomain/target of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def pi_codomain : expr \u2192 expr\n| (pi n bi d b) := pi_codomain b\n| e             := e\n\n/-- Get the body/value of a lambda-expression.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def lambda_body : expr \u2192 expr\n| (lam n bi d b) := lambda_body b\n| e             := e\n\n/-- Auxilliary defintion for `pi_binders`.\n  See note [open expressions]. -/\nmeta def pi_binders_aux : list binder \u2192 expr \u2192 list binder \u00d7 expr\n| es (pi n bi d b) := pi_binders_aux (\u27e8n, bi, d\u27e9::es) b\n| es e             := (es, e)\n\n/-- Get the binders and codomain of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the\n  free variables.\n  See note [open expressions]. -/\nmeta def pi_binders (e : expr) : list binder \u00d7 expr :=\nlet (es, e) := pi_binders_aux [] e in (es.reverse, e)\n\n/-- Auxilliary defintion for `get_app_fn_args`. -/\nmeta def get_app_fn_args_aux : list expr \u2192 expr \u2192 expr \u00d7 list expr\n| r (app f a) := get_app_fn_args_aux (a::r) f\n| r e         := (e, r)\n\n/-- A combination of `get_app_fn` and `get_app_args`: lists both the\n  function and its arguments of an application -/\nmeta def get_app_fn_args : expr \u2192 expr \u00d7 list expr :=\nget_app_fn_args_aux []\n\n/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/\nmeta def drop_pis : list expr \u2192 expr \u2192 tactic expr\n| (list.cons v vs) (pi n bi d b) := do\n  t \u2190 infer_type v,\n  guard (t =\u2090 d),\n  drop_pis vs (b.instantiate_var v)\n| [] e := return e\n| _  _ := failed\n\n/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.\n  Returns `empty` if the list is empty. -/\nmeta def mk_op_lst (op : expr) (empty : expr) : list expr \u2192 expr\n| []        := empty\n| [e]       := e\n| (e :: es) := op e $ mk_op_lst es\n\n/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 \u2227 (x2 \u2227 ...)`, or `true` if the list is empty. -/\nmeta def mk_and_lst : list expr \u2192 expr := mk_op_lst `(and) `(true)\n\n/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 \u2228 (x2 \u2228 ...)`, or `false` if the list is empty. -/\nmeta def mk_or_lst : list expr \u2192 expr := mk_op_lst `(or) `(false)\n\n/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.\nOtherwise returns `binder_info.default`. -/\nmeta def local_binding_info : expr \u2192 binder_info\n| (expr.local_const _ _ bi _) := bi\n| _ := binder_info.default\n\n/-- `is_default_local e` tests whether `e` is a local constant with binder info\n`binder_info.default` -/\nmeta def is_default_local : expr \u2192 bool\n| (expr.local_const _ _ binder_info.default _) := tt\n| _ := ff\n\n/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/\nmeta def has_local_constant (e l : expr) : bool :=\ne.has_local_in $ mk_name_set.insert l.local_uniq_name\n\n/-- Turns a local constant into a binder -/\nmeta def to_binder : expr \u2192 binder\n| (local_const _ nm bi t) := \u27e8nm, bi, t\u27e9\n| _                       := default binder\n\n/-- Strip-away the context-dependent unique id for the given local const and return: its friendly\n`name`, its `binder_info`, and its `type : expr`. -/\nmeta def get_local_const_kind : expr \u2192 name \u00d7 binder_info \u00d7 expr\n| (expr.local_const _ n bi e) := (n, bi, e)\n| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])\n\n/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/\nmeta def local_const_set_type {elab : bool} : expr elab \u2192 expr elab \u2192 expr elab\n| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t\n| e                           new_t := e\n\n/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to\naccess core `expr` manipulation functions for `pexpr`-based use, but which are restricted to\n`expr tt` at the site of definition unnecessarily.\n\nDANGER: Unless you know exactly what you are doing, this is probably not the function you are\nlooking for. For `pexpr \u2192 expr` see `tactic.to_expr`. For `expr \u2192 pexpr` see `to_pexpr`. -/\nmeta def unsafe_cast {elab\u2081 elab\u2082 : bool} : expr elab\u2081 \u2192 expr elab\u2082 := unchecked_cast\n\n/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr \u00d7 expr)` as\na collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says \"whenever\n`f` is encountered in `e` verbatim, replace it with `t`\". -/\nmeta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr \u00d7 expr)) :\n  expr elab :=\nunsafe_cast $ e.unsafe_cast.replace $ \u03bb e n,\n  (mappings.filter $ \u03bb ent : expr \u00d7 expr, ent.1 = e).head'.map prod.snd\n\n/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of\n    other `expr.local_const`s. It determines whether `e` should be considered \"available in context\"\n    as a variable by virtue of the fact that the variables `vs` have been deemed such.\n\n    For example, given `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that\n    the typeclass instance `prime n` should be included, but `ih : even n` should not.\n\n    DANGER: It is possible that for `f : expr` another `expr.local_const`, we have\n    `is_implicitly_included_variable f vs = ff` but\n    `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to\n    iteratively add a list of local constants (usually, the `variables` declared in the local scope)\n    which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables\n    were added in a particular iteration. The function `all_implicitly_included_variables` below\n    implements this behaviour.\n\n    Note that if `e \u2208 vs` then `is_implicitly_included_variable e vs = tt`. -/\nmeta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=\nif \u00ac(e.local_pp_name.to_string.starts_with \"_\") then\n  e \u2208 vs\nelse e.local_type.fold tt $ \u03bb se _ b,\n  if \u00acb then ff\n  else if \u00acse.is_local_constant then tt\n  else se \u2208 vs\n\n/-- Private work function for `all_implicitly_included_variables`, performing the actual series of\n    iterations, tracking with a boolean whether any updates occured this iteration. -/\nprivate meta def all_implicitly_included_variables_aux\n  : list expr \u2192 list expr \u2192 list expr \u2192 bool \u2192 list expr\n| []          vs rs tt := all_implicitly_included_variables_aux rs vs [] ff\n| []          vs rs ff := vs\n| (e :: rest) vs rs b :=\n  let (vs, rs, b) :=\n    if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in\n  all_implicitly_included_variables_aux rest vs rs b\n\n/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,\n    another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion\n    of the variables in `vs` into the local context implies that `e` should also be included. See\n    `is_implicitly_included_variable e vs` for the details.\n\n    In particular, those elements of `vs` are included automatically. -/\nmeta def all_implicitly_included_variables (es vs : list expr) : list expr :=\nall_implicitly_included_variables_aux es vs [] ff\n\nend expr\n\n/-! ### Declarations about `environment` -/\n\nnamespace environment\n\n/-- Tests whether `n` is a structure. -/\nmeta def is_structure (env : environment) (n : name) : bool :=\n(env.structure_fields n).is_some\n\n/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a\n  structure. -/\nmeta def structure_fields_full (env : environment) (n : name) : option (list name) :=\n(env.structure_fields n).map (list.map $ \u03bb n', n ++ n')\n\n/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.\n  Note that `is_ginductive` returns `tt` even on regular inductive types.\n  This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive\n  type. -/\nmeta def is_ginductive' (e : environment) (nm : name) : bool :=\ne.is_ginductive nm \u2227 \u00ac e.is_inductive nm\n\n/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list.  -/\nmeta def decl_filter_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 option \u03b1) : list \u03b1 :=\n  e.fold [] $ \u03bb d l, match f d with\n                     | some r := r :: l\n                     | none := l\n                     end\n\n/-- Maps `f` to all declarations in the environment. -/\nmeta def decl_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 \u03b1) : list \u03b1 :=\n  e.decl_filter_map $ \u03bb d, some (f d)\n\n/-- Lists all declarations in the environment -/\nmeta def get_decls (e : environment) : list declaration :=\n  e.decl_map id\n\n/-- Lists all trusted (non-meta) declarations in the environment -/\nmeta def get_trusted_decls (e : environment) : list declaration :=\n  e.decl_filter_map (\u03bb d, if d.is_trusted then some d else none)\n\n/-- Lists the name of all declarations in the environment -/\nmeta def get_decl_names (e : environment) : list name :=\n  e.decl_map declaration.to_name\n\n/-- Fold a monad over all declarations in the environment. -/\nmeta def mfold {\u03b1 : Type} {m : Type \u2192 Type} [monad m] (e : environment) (x : \u03b1)\n  (fn : declaration \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\ne.fold (return x) (\u03bb d t, t >>= fn d)\n\n/-- Filters all declarations in the environment. -/\nmeta def filter (e : environment) (test : declaration \u2192 bool) : list declaration :=\ne.fold [] $ \u03bb d ds, if test d then d::ds else ds\n\n/-- Filters all declarations in the environment. -/\nmeta def mfilter (e : environment) (test : declaration \u2192 tactic bool) : tactic (list declaration) :=\ne.mfold [] $ \u03bb d ds, do b \u2190 test d, return $ if b then d::ds else ds\n\n/-- Checks whether `s` is a prefix of the file where `n` is declared.\n  This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/\nmeta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=\ns.is_prefix_of $ (e.decl_olean n).get_or_else \"\"\n\nend environment\n\n/-!\n### `is_eta_expansion`\n\n In this section we define the tactic `is_eta_expansion` which checks whether an expression\n  is an eta-expansion of a structure. (not to be confused with eta-expanion for `\u03bb`).\n\n-/\n\nnamespace expr\n\nopen tactic\n\n/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have\n  `pr = nm.{univs} args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name \u00d7 expr)) :\n  bool :=\nl.all $ \u03bb\u27e8proj, val\u27e9, val = (const proj univs).mk_app args\n\n/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all\n  elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_test : list (name \u00d7 expr) \u2192 option expr\n| []              := none\n| (\u27e8proj, val\u27e9::l) :=\n  match val.get_app_fn with\n  | (const nm univs : expr) :=\n    if nm = proj then\n      let args := val.get_app_args in\n      let e := args.ilast in\n      if is_eta_expansion_of args univs l then some e else none\n    else\n      none\n  | _                       := none\n  end\n\n/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.\n  Here `l` is intended to consists of the projections and the fields of `val`.\n  This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and\n  afterward checks whether the resulting expression `e` unifies with `val`.\n  This last check is necessary, because `val` and `e` might have different types. -/\nmeta def is_eta_expansion_aux (val : expr) (l : list (name \u00d7 expr)) : tactic (option expr) :=\ndo l' \u2190 l.mfilter (\u03bb\u27e8proj, val\u27e9, bnot <$> is_proof val),\n  match is_eta_expansion_test l' with\n  | some e := option.map (\u03bb _, e) <$> try_core (unify e val)\n  | none   := return none\n  end\n\n/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the\n  eta-expansion of `e`.\n  With eta-expansion we here mean the eta-expansion of a structure, not of a function.\n  For example, the eta-expansion of `x : \u03b1 \u00d7 \u03b2` is `\u27e8x.1, x.2\u27e9`.\n  This assumes that `val` is a fully-applied application of the constructor of a structure.\n\n  This is useful to reduce expressions generated by the notation\n    `{ field_1 := _, ..other_structure }`\n  If `other_structure` is itself a field of the structure, then the elaborator will insert an\n  eta-expanded version of `other_structure`. -/\nmeta def is_eta_expansion (val : expr) : tactic (option expr) := do\n  e \u2190 get_env,\n  type \u2190 infer_type val,\n  projs \u2190 e.structure_fields_full type.get_app_fn.const_name,\n  let args := (val.get_app_args).drop type.get_app_args.length,\n  is_eta_expansion_aux val (projs.zip args)\n\nend expr\n\n/-! ### Declarations about `declaration` -/\n\nnamespace declaration\nopen tactic\n\n/--\n`declaration.update_with_fun f tgt decl`\nsets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names\nof all `expr.const`s which appear in the value or type of `decl`.\n-/\nprotected meta def update_with_fun (f : name \u2192 name) (tgt : name) (decl : declaration) :\n  declaration :=\nlet decl := decl.update_name $ tgt in\nlet decl := decl.update_type $ decl.type.apply_replacement_fun f in\ndecl.update_value $ decl.value.apply_replacement_fun f\n\n/-- Checks whether the declaration is declared in the current file.\n  This is a simple wrapper around `environment.in_current_file`\n  Use `environment.in_current_file` instead if performance matters. -/\nmeta def in_current_file (d : declaration) : tactic bool :=\ndo e \u2190 get_env, return $ e.in_current_file d.to_name\n\n/-- Checks whether a declaration is a theorem -/\nmeta def is_theorem : declaration \u2192 bool\n| (thm _ _ _ _) := tt\n| _             := ff\n\n/-- Checks whether a declaration is a constant -/\nmeta def is_constant : declaration \u2192 bool\n| (cnst _ _ _ _) := tt\n| _              := ff\n\n/-- Checks whether a declaration is a axiom -/\nmeta def is_axiom : declaration \u2192 bool\n| (ax _ _ _) := tt\n| _          := ff\n\n/-- Checks whether a declaration is automatically generated in the environment.\n  There is no cheap way to check whether a declaration in the namespace of a generalized\n  inductive type is automatically generated, so for now we say that all of them are automatically\n  generated. -/\nmeta def is_auto_generated (e : environment) (d : declaration) : bool :=\ne.is_constructor d.to_name \u2228\n(e.is_projection d.to_name).is_some \u2228\n(e.is_constructor d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"inj\", \"inj_eq\", \"sizeof_spec\", \"inj_arrow\"]) \u2228\n(e.is_inductive d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"below\", \"binduction_on\", \"brec_on\", \"cases_on\", \"dcases_on\", \"drec_on\", \"drec\",\n  \"rec\", \"rec_on\", \"no_confusion\", \"no_confusion_type\", \"sizeof\", \"ibelow\", \"has_sizeof_inst\"]) \u2228\nd.to_name.has_prefix (\u03bb nm, e.is_ginductive' nm)\n\n/--\nReturns true iff `d` is an automatically-generated or internal declaration.\n-/\nmeta def is_auto_or_internal (env : environment) (d : declaration) : bool :=\nd.to_name.is_internal || d.is_auto_generated env\n\n/-- Returns the list of universe levels of a declaration. -/\nmeta def univ_levels (d : declaration) : list level :=\nd.univ_params.map level.param\n\n/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/\nprotected meta def reducibility_hints : declaration \u2192 reducibility_hints\n| (declaration.defn _ _ _ _ red _) := red\n| _ := _root_.reducibility_hints.opaque\n\n/-- formats the arguments of a `declaration.thm` -/\nprivate meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body.get,\n   return $ \"<theorem \" ++ to_fmt nm ++ \" : \" ++ tp ++ \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.defn` -/\nprivate meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :\n  tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body,\n   return $ \"<\" ++ (if is_trusted then \"def \" else \"meta def \") ++ to_fmt nm ++ \" : \" ++ tp ++\n     \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.cnst` -/\nprivate meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<\" ++ (if is_trusted then \"constant \" else \"meta constant \") ++ to_fmt nm ++ \" : \"\n     ++ tp ++ \">\"\n\n/-- formats the arguments of a `declaration.ax` -/\nprivate meta def print_ax (nm : name) (tp : expr) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<axiom \" ++ to_fmt nm ++ \" : \" ++ tp ++ \">\"\n\n/-- pretty-prints a `declaration` object. -/\nmeta def to_tactic_format : declaration \u2192 tactic format\n| (declaration.thm nm _ tp bd) := print_thm nm tp bd\n| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted\n| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted\n| (declaration.ax nm _ tp) := print_ax nm tp\n\nmeta instance : has_to_tactic_format declaration :=\n\u27e8to_tactic_format\u27e9\n\nend declaration\n\nmeta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=\nunchecked_cast\nexpr.has_decidable_eq\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/meta/expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.06853748684859447, "lm_q1q2_score": 0.022694114800132024}}
{"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\u207b\u00b9 * a \u2243 1`)\nvs. a right inverse (`a * a\u207b\u00b9 \u2243 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- `\u03b1`: The `Sort` of the items to select.\n-/\nabbrev Hand.pick {\u03b1 : Sort u} : Hand \u2192 \u03b1 \u2192 \u03b1 \u2192 \u03b1\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 (\u03b1 : Sort u) where\n  sizeOf : \u03b1 \u2192 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 `\u03b1` has a default SizeOf instance that just returns 0 for every element of `\u03b1` -/\nprotected def default.sizeOf (\u03b1 : Sort u) : \u03b1 \u2192 Nat\n  | a => 0\n\ninstance (priority := low) (\u03b1 : Sort u) : SizeOf \u03b1 where\n  sizeOf := default.sizeOf \u03b1\n\n@[simp] theorem sizeOf_default (n : \u03b1) : 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 \u2192 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": "example (P Q R : Prop) (HP : P) (HQ : Q) : P :=\nbegin\n  sorry,\nend\n", "meta": {"author": "ImperialCollegeLondon", "repo": "xena-UROP-2018", "sha": "b111fb87f343cf79eca3b886f99ee15c1dd9884b", "save_path": "github-repos/lean/ImperialCollegeLondon-xena-UROP-2018", "path": "github-repos/lean/ImperialCollegeLondon-xena-UROP-2018/xena-UROP-2018-b111fb87f343cf79eca3b886f99ee15c1dd9884b/src/M1F/problem_bank/PB0001/Q0001.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.06278920289730222, "lm_q1q2_score": 0.022564189086083868}}
{"text": "import .fol .abel\n\nuniverse u\n\nsection weekdays\n@[derive has_reflect]\ninductive weekday : Type\n| monday          : weekday\n| another_day     : weekday \u2192 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' \u2192 weekday'\n\nopen weekday'\nmeta instance has_reflect_weekday' : has_reflect weekday'\n| weekday'.monday                  := `(monday)\n| (weekday'.another_day x)         := `(\u03bb 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}} : \u03a0{n : \u2115}, 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     : \u2115 \u2192 preterm_aux\n| func    : \u2200 k : \u2115, L.functions k \u2192 preterm_aux\n| app     : preterm_aux \u2192 preterm_aux \u2192 preterm_aux\n\ndef to_aux {L : Language.{u}} : \u2200 {l : \u2115},  preterm L l \u2192 preterm_aux L\n| 0 (var n)      := preterm_aux.var _ n\n| k (func f)     := preterm_aux.func _ f\n| k (app t\u2081 t\u2082)  := preterm_aux.app (to_aux t\u2081) (to_aux t\u2082)\n\n\ndef L_abel_plus' (t\u2081 t\u2082 : preterm L_abel 0) : preterm L_abel 0 :=\n@term_of_function L_abel 2 (abel_functions.plus : L_abel.functions 2) t\u2081 t\u2082\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 \u2192 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 : \u2115 \u2192 Type u\n| z {} : my_indexed_family 0\n| s : \u2200 {k}, my_indexed_family k \u2192 my_indexed_family (k+1)\n\n-- meta example : \u2200 {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'' : \u2115 \u2192 Type\n| fz {n} : dfin'' (n+1)\n| fs {n} : dfin'' n \u2192 dfin'' (n+1)\n\ninductive dfin' : \u2115 \u2192 Type u\n| gz {n} :  dfin' (n+1)\n| gs {n} :  dfin' n \u2192 dfin' (n+1)\n\nopen dfin dfin'\n\nmeta instance dfin.reflect : \u2200 {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 : \u2200 {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 : \u2115 \u2192 Type\n| pt : L_pt_functions 0\n\ndef L_pt : Language.{0} := \u27e8L_pt_functions, \u03bb _, empty\u27e9\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 : \u2115 \u2192 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\u27e8L_pt_func_functions, \u03bb _, ulift empty\u27e9\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\u2081 <- tactic.mk_app ``preterm.func [`(my_foo)],\n   e\u2082 <- tactic.mk_app ``preterm.func [`(my_pt)],\n   tactic.mk_app ``preterm.app [e\u2081, e\u2082]\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": "example : n.succ = 1 \u2192 n = 0 := by\n  intros h; injection h; assumption\n\nexample (h : n.succ = 1) : n = 0 := by\n  injection h; assumption\n\nconstant T : Type\nconstant T.Pred : T \u2192 T \u2192 Prop\n\nexample {\u03c1} (h\u03c1 : \u03c1.Pred \u03c3) : T.Pred \u03c1 \u03c1 := sorry\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/autoboundIssues.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.05582314309810017, "lm_q1q2_score": 0.022528369424832134}}
{"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 : \u2200 {n}, L.fn n \u2192 (fin n \u2192 dom) \u2192 dom)\n(pr : \u2200 {n}, L.pr n \u2192 (fin n \u2192 dom) \u2192 Prop)\n\ninstance Structure_coe {L : language} : has_coe_to_sort (Structure L) (Type*) := \u27e8Structure.dom\u27e9\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) := \u27e8nonempty_Structure.to_Structure\u27e9\n\ninstance nonempty_Structure_dom_coe {L : language} : has_coe_to_sort (nonempty_Structure L) (Type*) :=\n\u27e8\u03bb S, ((S : Structure L) : Type*)\u27e9\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) := \u27e8finite_Structure.to_Structure\u27e9\n\nvariables {L} {\u03bc : Type v} {\u03bc\u2081 : Type*} {\u03bc\u2082 : Type*}\n\nopen subterm subformula\n\nnamespace  subterm\nvariables (S : Structure L) {n : \u2115} (\u03a6 : \u03bc \u2192 S) (e : fin n \u2192 S)\n\n@[simp] def val (\u03a6 : \u03bc \u2192 S) (e : fin n \u2192 S) : subterm L \u03bc n \u2192 S\n| (&x)           := \u03a6 x\n| (#x)           := e x\n| (function f v) := S.fn f (\u03bb i, (v i).val)\n\nlemma val_rew (s : \u03bc\u2081 \u2192 subterm L \u03bc\u2082 n) (\u03a6 : \u03bc\u2082 \u2192 S) (e : fin n \u2192 S) (t : subterm L \u03bc\u2081 n) :\n  (rew s t).val S \u03a6 e = t.val S (\u03bb x, val S \u03a6 e (s x)) e :=\nby induction t; simp*\n\nlemma val_map (f : \u03bc\u2081 \u2192 \u03bc\u2082) (\u03a6 : \u03bc\u2082 \u2192 S) (e : fin n \u2192 S) (t : subterm L \u03bc\u2081 n) :\n  (map f t).val S \u03a6 e = t.val S (\u03bb x, \u03a6 (f x)) e :=\nby simp[map, val_rew]\n\nlemma val_subst (u : subterm L \u03bc n) (t : subterm L \u03bc (n + 1)) :\n  (subst u t).val S \u03a6 e = t.val S \u03a6 (e <* u.val S \u03a6 e) :=\nby { induction t; simp*, case var : x { refine fin.last_cases _ _ x; simp } }\n\nlemma val_lift (x : S) (t : subterm L \u03bc n) :\n  t.lift.val S \u03a6 (x *> e) = t.val S \u03a6 e :=\nby induction t; simp*\n\nsection bounded_subterm\nvariables {m : \u2115} {\u03a8 : fin m \u2192 S}\n\nlemma val_mlift (x : S) (t : bounded_subterm L m n) :\n  t.mlift.val S (\u03a8 <* x) e = t.val S \u03a8 e :=\nby simp[mlift, val_rew, val_map]\n\nlemma val_push (x : S) (e : fin n \u2192 S) (t : bounded_subterm L m (n + 1)) :\n  val S (\u03a8 <* x) e t.push = val S \u03a8 (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 \u2192 S) (t : bounded_subterm L (m + 1) n) :\n  val S \u03a8 (e <* x) t.pull = val S (\u03a8 <* 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 {\u03bc \u03bc\u2081 \u03bc\u2082} (S : Structure L) {n : \u2115} {\u03a6 : \u03bc \u2192 S} {e : fin n \u2192 S}\n\n@[simp] def subval' (\u03a6 : \u03bc \u2192 S) : \u2200 {n} (e : fin n \u2192 S), subformula L \u03bc n \u2192 Prop\n| n _ verum          := true\n| n e (relation p v) := S.pr p (subterm.val S \u03a6 e \u2218 v)\n| n e (imply p q)    := p.subval' e \u2192 q.subval' e\n| n e (neg p)        := \u00ac(p.subval' e)\n| n e (fal p)        := \u2200 x : S.dom, (p.subval' (x *> e))\n\n@[irreducible] def subval (\u03a6 : \u03bc \u2192 S) (e : fin n \u2192 S) : subformula L \u03bc n \u2192\u2097 Prop :=\n{ to_fun := subval' S \u03a6 e,\n  map_neg' := \u03bb _, by refl,\n  map_imply' := \u03bb _ _, by refl,\n  map_and' := \u03bb p q, by unfold has_inf.inf; simp[and]; refl,\n  map_or' := \u03bb p q, by unfold has_sup.sup; simp[or, \u2190or_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 (\u03a6 : \u03bc \u2192 S) : formula L \u03bc \u2192\u2097 Prop := subformula.subval S \u03a6 fin.nil\n\n@[simp] lemma subval_relation {p} {r : L.pr p} {v} :\n  subval S \u03a6 e (relation r v) \u2194 S.pr r (\u03bb i, subterm.val S \u03a6 e (v i)) :=  by simp[subval]; refl\n\n@[simp] lemma subval_fal {p : subformula L \u03bc (n + 1)} :\n  subval S \u03a6 e (\u2200'p) \u2194 \u2200 x : S, subval S \u03a6 (x *> e) p := by simp[subval]; refl\n\n@[simp] lemma subval_ex {p : subformula L \u03bc (n + 1)} :\n  subval S \u03a6 e (\u2203'p) \u2194 \u2203 x : S, subval S \u03a6 (x *> e) p := by simp[ex_def]\n\nlemma subval_rew {\u03a6 : \u03bc\u2082 \u2192 S} {n} {e : fin n \u2192 S} {s : \u03bc\u2081 \u2192 subterm L \u03bc\u2082 n} {p : subformula L \u03bc\u2081 n} :\n  subval S \u03a6 e (rew s p) \u2194 subval S (\u03bb x, subterm.val S \u03a6 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 {\u03a6 : \u03bc\u2082 \u2192 S} {n} {e : fin n \u2192 S} {f : \u03bc\u2081 \u2192 \u03bc\u2082} {p : subformula L \u03bc\u2081 n} :\n  subval S \u03a6 e (map f p) \u2194 subval S (\u03bb x, \u03a6 (f x)) e p :=\nby simp[map, subval_rew]\n\n@[simp] lemma subval_subst {n} {p : subformula L \u03bc (n + 1)} : \u2200 {e : fin n \u2192 S} {t : subterm L \u03bc n},\n  subval S \u03a6 e (subst t p) \u2194 subval S \u03a6 (e <* subterm.val S \u03a6 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 : \u2115} {\u03a8 : fin m \u2192 S}\n\nlemma subval_mlift {x} {p : bounded_subformula L m n} :\n  subval S (\u03a8 <* x) e p.mlift = subval S \u03a8 e p := by simp[mlift, (\u2218), subval_map]\n\nlemma subval_push {x} {n} {p : bounded_subformula L m (n + 1)} : \u2200 {e : fin n \u2192 S},\n  subval S (\u03a8 <* x) e p.push \u2194 subval S \u03a8 (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} : \u2200 {e : fin n \u2192 S},\n  subval S \u03a8 (e <* x) p.pull \u2194 subval S (\u03a8 <* x) e p :=\nby induction p using fol.subformula.ind_on generalizing \u03a8; intros; simp[*, subterm.val_pull, fin.left_right_concat_assoc]\n\nlemma subval_dummy {x} : \u2200 {n} {e : fin n \u2192 S} {p : bounded_subformula L m n},\n  subval S \u03a8 (e <* x) p.dummy \u2194 subval S \u03a8 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\u27e8{ dom := punit,\n   fn := \u03bb k f v, punit.star,\n   pr := \u03bb k r v, false,\n   dom_inhabited := punit.inhabited }\u27e9\n\nend nonempty_Structure\n\nnamespace Structure\n\n@[ext] lemma ext (S\u2081 S\u2082 : Structure L)\n  (hdom : @dom L S\u2081 = @dom L S\u2082)\n  (hfn : \u2200 {k} (f : L.fn k), @fn L S\u2081 k f == @fn L S\u2082 k f)\n  (hpr : \u2200 {k} (r : L.pr k), @pr L S\u2081 k r == @pr L S\u2082 k r) : S\u2081 = S\u2082 :=\nbegin\n  rcases S\u2081, rcases S\u2082, simp at hdom \u22a2 hfn hpr, refine \u27e8hdom, _, _\u27e9,\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 : \u2200 {n : \u2115} {t u : subterm L \u03bc n} {\u03a6 e}, subformula.subval S \u03a6 e (t =' u) \u2194 (t.val S \u03a6 e = u.val S \u03a6 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\u27e8(default : nonempty_Structure L)\u27e9\n\nend Structure\n\nnamespace subformula\nvariables (S : Structure L) {\u03a6 : \u03bc \u2192 S}\n\nnotation S` \u22a7[`:80 e`] `p :50 := val S e p\n\nvariables {S} {p q : formula L \u03bc}\n\n@[simp] lemma models_relation {k} {r : L.pr k} {v} :\n  S \u22a7[\u03a6] relation r v \u2194 S.pr r (\u03bb i, subterm.val S \u03a6 fin.nil (v i)) := by simp[val]\n\nsection bounded\nvariables {m : \u2115} {\u03a8 : fin m \u2192 S}\n\n@[simp] lemma val_fal {p : bounded_subformula L m 1} :\n  S \u22a7[\u03a8] \u2200'p \u2194 \u2200 x, S \u22a7[\u03a8 <* 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 \u22a7[\u03a8] \u2203'p \u2194 \u2203 x, S \u22a7[\u03a8 <* 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 \u22a7[\u03a8] subst t p \u2194 S \u22a7[\u03a8 <* subterm.val S \u03a8 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 \u22a7[\u03a8 <* x] p.mlift \u2194 S \u22a7[\u03a8] p :=\nby simp[val, subval_mlift]\n\nend bounded\n\nend subformula\n\ndef models (S : Structure L) (p : formula L \u03bc) : Prop := \u2200 e, S \u22a7[e] p\n\ninstance : semantics (formula L \u03bc) (Structure L) := \u27e8models\u27e9\n\ninstance : semantics (formula L \u03bc) (nonempty_Structure L) := \u27e8\u03bb S p, (S : Structure L) \u22a7 p\u27e9\n\nnamespace Structure\n\nvariables {S : Structure L} {\u03c3 \u03c4 : sentence L}\n\nlemma models_def {p : formula L \u03bc} : S \u22a7 p \u2194 (\u2200 e, S \u22a7[e] p) := by refl\n\nlemma sentence_models_def :\n  S \u22a7 \u03c3 \u2194 S \u22a7[fin.nil] \u03c3 := by simp[models_def, fin.nil]\n\n@[simp] lemma formula_verum : S \u22a7 (\u22a4 : formula L \u03bc) := by simp[models_def]\n\n@[simp] lemma sentence_falsum : \u00acS \u22a7 (\u22a5 : sentence L) := by simp[models_def]\n\n@[simp] lemma sentence_relation {k} (r : L.pr k) (v : fin k \u2192 bounded_subterm L 0 0) :\n  S \u22a7 (relation r v) \u2194 S.pr r (subterm.val S fin.nil fin.nil \u2218 v) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_imply : S \u22a7 \u03c3 \u27f6 \u03c4 \u2194 (S \u22a7 \u03c3 \u2192 S \u22a7 \u03c4) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_neg : S \u22a7 \u223c\u03c3 \u2194 \u00acS \u22a7 \u03c3 := by simp[sentence_models_def]\n\n@[simp] lemma sentence_and : S \u22a7 \u03c3 \u2293 \u03c4 \u2194 S \u22a7 \u03c3 \u2227 S \u22a7 \u03c4 := by simp[sentence_models_def]\n\n@[simp] lemma sentence_or : S \u22a7 \u03c3 \u2294 \u03c4 \u2194 S \u22a7 \u03c3 \u2228 S \u22a7 \u03c4 := by simp[sentence_models_def]\n\n@[simp] lemma sentence_equiv : S \u22a7 \u03c3 \u27f7 \u03c4 \u2194 (S \u22a7 \u03c3 \u2194 S \u22a7 \u03c4) := by simp[sentence_models_def]\n\ninstance : semantics.nontrivial (sentence L) (Structure L) :=\n\u27e8by simp[models_def], by simp[models_def]\u27e9\n\nabbreviation valid (p : formula L \u03bc) : Prop := semantics.valid (Structure L) p\n\nabbreviation satisfiable (p : formula L \u03bc) : Prop := semantics.satisfiable (Structure L) p\n\nlemma valid_def (p : formula L \u03bc) : valid p \u2194 \u2200 S : Structure L, S \u22a7 p := by refl\n\nlemma satisfiable_def (p : formula L \u03bc) : satisfiable p \u2194 \u2203 S : Structure L, S \u22a7 p := by refl\n\nabbreviation Satisfiable (T : preTheory L \u03bc) : Prop := semantics.Satisfiable (Structure L) T\n\nlemma Satisfiable_def (T : preTheory L \u03bc) : Satisfiable T \u2194 \u2203 S: Structure L, S \u22a7 T := by refl\n\n@[simp] lemma sentence_not_valid_iff_satisfiable (\u03c3 : sentence L) : \u00acvalid \u03c3 \u2194 satisfiable (\u223c\u03c3) :=\nby simp[valid_def, satisfiable_def]\n\n@[simp] lemma models_mlift [inhabited S] {m} {p : bounded_formula L m} : S \u22a7 p.mlift \u2194 S \u22a7 p :=\nby{ simp[models_def], split,\n    { intros h e,\n      have : S \u22a7[e <* default] p.mlift, from h _,\n      simpa using this },\n    { intros h e, rw \u2190fin.right_concat_eq e, simpa using h (e \u2218 fin.cast_succ)} }\n\nend Structure\n\nnamespace nonempty_Structure\n\nvariables {M : nonempty_Structure L} {\u03c3 \u03c4 : sentence L} {m : \u2115} {T : bounded_preTheory L m}\n\nlemma models_def {p : formula L \u03bc} :\n  M \u22a7 p \u2194 (\u2200 e, \u2191M \u22a7[e] p) := by refl\n\nlemma sentence_models_def {\u03c3 : sentence L} :\n  M \u22a7 \u03c3 \u2194 \u2191M \u22a7[fin.nil] \u03c3 := by simp[models_def, fin.nil]\n\n@[simp] lemma formula_verum : M \u22a7 (\u22a4 : formula L \u03bc) := by simp[models_def]\n\n@[simp] lemma formula_falsum : \u00acM \u22a7 (\u22a5 : formula L \u03bc) := by simp[models_def]\n\n@[simp] lemma sentence_relation {k} {r : L.pr k} {v : fin k \u2192 bounded_subterm L 0 0} :\n  M \u22a7 (relation r v) \u2194 M.pr r (subterm.val M fin.nil fin.nil \u2218 v) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_imply : M \u22a7 \u03c3 \u27f6 \u03c4 \u2194 (M \u22a7 \u03c3 \u2192 M \u22a7 \u03c4) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_neg : M \u22a7 \u223c\u03c3 \u2194 \u00acM \u22a7 \u03c3 := by simp[sentence_models_def]\n\n@[simp] lemma sentence_and : M \u22a7 \u03c3 \u2293 \u03c4 \u2194 M \u22a7 \u03c3 \u2227 M \u22a7 \u03c4 := by simp[sentence_models_def]\n\n@[simp] lemma sentence_or : M \u22a7 \u03c3 \u2294 \u03c4 \u2194 M \u22a7 \u03c3 \u2228 M \u22a7 \u03c4 := by simp[sentence_models_def]\n\n@[simp] lemma sentence_equiv : M \u22a7 \u03c3 \u27f7 \u03c4 \u2194 (M \u22a7 \u03c3 \u2194 M \u22a7 \u03c4) := by simp[sentence_models_def]\n\ninstance : semantics.nontrivial (formula L \u03bc) (nonempty_Structure L) :=\n\u27e8by simp[models_def], by simp[models_def]\u27e9\n\nabbreviation valid (p : formula L \u03bc) : Prop := semantics.valid (nonempty_Structure L) p\n\nabbreviation satisfiable (p : formula L \u03bc) : Prop := semantics.satisfiable (nonempty_Structure L) p\n\nlemma valid_def (p : formula L \u03bc) : valid p \u2194 \u2200 M : nonempty_Structure L, M \u22a7 p := by refl\n\nlemma satisfiable_def (p : formula L \u03bc) : satisfiable p \u2194 \u2203 M : nonempty_Structure L, M \u22a7 p := by refl\n\nabbreviation Satisfiable (T : preTheory L \u03bc) : Prop := semantics.Satisfiable (nonempty_Structure L) T\n\nlemma Satisfiable_def (T : preTheory L \u03bc) : Satisfiable T \u2194 \u2203 M : nonempty_Structure L, M \u22a7 T := by refl\n\n@[simp] lemma sentence_not_valid_iff_satisfiable (\u03c3 : sentence L) : \u00acvalid \u03c3 \u2194 satisfiable (\u223c\u03c3) :=\nby simp[valid_def, satisfiable_def]\n\nlemma coe_models_iff (p : formula L \u03bc) : (M : Structure L) \u22a7 p \u2194 M \u22a7 p := by refl\n\n@[simp] lemma models_mlift {m} {p : bounded_formula L m} : M \u22a7 p.mlift \u2194 M \u22a7 p :=\nby simp[\u2190coe_models_iff]\n\nlemma coe_models_Theory_iff (T : preTheory L \u03bc) : (M : Structure L) \u22a7 T \u2194 M \u22a7 T := by refl\n\nend nonempty_Structure\n\nnamespace Structure\nopen bounded_preTheory\nvariables {S : Structure L} {\u03c3 \u03c4 : sentence L} {m : \u2115} {T : bounded_preTheory L m}\n\nlemma nonempty_models_iff [inhabited S] (p : formula L \u03bc) : S.nonempty \u22a7 p \u2194 S \u22a7 p :=\nby simp[\u2190nonempty_Structure.coe_models_iff]\n\nlemma nonempty_models_Theory_iff [inhabited S] (T : preTheory L \u03bc) : S.nonempty \u22a7 T \u2194 S \u22a7 T :=\nby simp[\u2190nonempty_Structure.coe_models_Theory_iff]\n\n@[simp] lemma models_Theory_mlift [inhabited S] : S \u22a7 T.mlift \u2194 S \u22a7 T :=\n\u27e8by { intros h p hp,\n      have : S \u22a7 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 \u27e8q, hq, rfl\u27e9,\n      exact models_mlift.mpr (h hq) }\u27e9\n\ndef consequence : preTheory L \u03bc \u2192 formula L \u03bc \u2192 Prop := semantics.consequence (Structure L)\n\ninfix ` \u22a7\u2080 ` :55 := consequence\n\nlemma consequence_def {T : preTheory L \u03bc} {p : formula L \u03bc} :\n  T \u22a7\u2080 p \u2194 (\u2200 S : Structure L, S \u22a7 T \u2192 S \u22a7 p) := by refl\n\nend Structure\n\nnamespace nonempty_Structure\nopen bounded_preTheory\nvariables {M : nonempty_Structure L} {\u03c3 \u03c4 : sentence L} {m : \u2115} {T : bounded_preTheory L m}\n\n@[simp] lemma models_Theory_mlift : M \u22a7 T.mlift \u2194 M \u22a7 T :=\nby simp[\u2190coe_models_Theory_iff]\n\ninstance : has_double_turnstile (preTheory L \u03bc) (formula L \u03bc) := \u27e8semantics.consequence (nonempty_Structure L)\u27e9\n\nlemma consequence_def {T : preTheory L \u03bc} {p : formula L \u03bc} :\n  T \u22a7 p \u2194 (\u2200 M : nonempty_Structure L, M \u22a7 T \u2192 M \u22a7 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 \u22a2 p \u2192 T \u22a7\u2080 p :=\nbegin\n  intros h,\n  apply provable.rec_on h,\n  { intros m T p b IH S hT \u03a6,\n    simp[subformula.val], intros x,\n    haveI : inhabited S, from \u27e8x\u27e9,\n    have : S \u22a7 p, from @IH S (by simpa using hT),\n    exact this (\u03a6 <* x) },\n  { intros m T p q b\u2081 b\u2082 m\u2081 m\u2082 S hT \u03a6,\n    have h\u2081 : S \u22a7[\u03a6] p \u2192 S \u22a7[\u03a6] q, by simpa using m\u2081 hT \u03a6,\n    have h\u2082 : S \u22a7[\u03a6] p, from m\u2082 hT \u03a6,\n    exact h\u2081 h\u2082 },\n  { intros m T p hp S hS, exact hS hp },\n  { intros m T S h \u03a6, simp },\n  { intros m T p q S hS \u03a6, simp, intros h _, exact h },\n  { intros m T p q r S hS \u03a6, simp,  intros h\u2081 h\u2082 h\u2083, exact h\u2081 h\u2083 (h\u2082 h\u2083) },\n  { intros m T p q S hS \u03a6, simp, intros h\u2081, contrapose, exact h\u2081 },\n  { intros m T p t S hS \u03a6, simp, intros h, exact h _ },\n  { intros m T p q S hS \u03a6, simp, intros h\u2081 h\u2082 x, exact h\u2081 x h\u2082 }\nend\n\ninstance {m} : logic.sound (bounded_formula L m) (Structure L) :=\n\u27e8\u03bb T p, soundness\u27e9\n\ntheorem nonempty_soundness {m} {T : bounded_preTheory L m} {p} : T \u22a2 p \u2192 T \u22a7 p :=\nby intros h M hM; exact soundness h hM\n\ninstance {m} : logic.sound (bounded_formula L m) (nonempty_Structure L) :=\n\u27e8\u03bb T p, nonempty_soundness\u27e9\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 : \u211a) : q \u2260 0 := sorry\ntheorem fake_gt_zero_pf (q : \u211a) : q > 0 := sorry\ntheorem fake_lt_zero_pf (q : \u211a) : q < 0 := sorry\ntheorem fake_eq_zero_pf (q : \u211a) : q = 0 := sorry\ntheorem fake_ne_pf (q1 q2 : \u211a) : q1 \u2260 q2 := sorry\n\nprivate meta def solve_by_norm_num (e : expr) : tactic expr :=\ndo (_, pf) \u2190 solve_aux e `[norm_num, tactic.done],\n   return pf\n\nmeta def mk_ne_zero_pf (q : \u211a) : tactic expr :=\n--do qe \u2190 to_expr ``(%%(quote q) : \u211a),\n--   to_expr ``(fake_ne_zero_pf (%%qe : \u211a))\n--return `(fake_ne_zero_pf q) \nsolve_by_norm_num `(q \u2260 0)\n\n  \n-- proves that q > 0, q < 0, or q = 0\nmeta def mk_sign_pf (q : \u211a) : tactic expr :=\n/-do qe \u2190 to_expr `(%%(quote q) : \u211a),\n   if q > 0 then to_expr `(fake_gt_zero_pf (%%qe : \u211a))\n   else if q < 0 then to_expr `(fake_lt_zero_pf (%%qe : \u211a))\n   else to_expr ``(fake_eq_zero_pf (%%qe : \u211a))-/\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 : \u211a) : tactic expr :=\n/-do q1e \u2190 to_expr ``(%%(quote q1) : \u211a),\n   q2e \u2190 to_expr ``(%%(quote q2) : \u211a),\n   to_expr `(fake_ne_pf %%q1e %%q2e)-/\n--return `(fake_ne_pf q1 q2)\nsolve_by_norm_num `(q1 \u2260 q2)\n\nmeta def mk_int_sign_pf (z : \u2124) : 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 : \u2124) : 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 : \u211a) (pf : expr) : tactic expr :=\ndo mvc \u2190 mk_mvar,\n   pft \u2190 infer_type pf,\n   to_expr ``(%%lhs \u2260 %%mvc * %%rhs) >>= unify pft,\n   c' \u2190 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 : \u03a0 {lhs rhs : expr} {c : \u211a}, diseq_proof lhs rhs c \u2192 tactic expr)\n        {lhs rhs c} (dp : diseq_proof lhs rhs c) : tactic expr :=\ndo symp \u2190 rc dp,\n   cnep \u2190 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 : \u03a0 {lhs rhs : expr} {c : \u211a}, diseq_proof lhs rhs c \u2192 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 : \u211a) (pf : expr) : tactic expr :=\ndo mvc \u2190 mk_mvar,\n   pft \u2190 infer_type pf,\n   to_expr ``(%%lhs = %%mvc * %%rhs) >>= unify pft,\n   c' \u2190 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 : \u03a0 {lhs rhs : expr} {c : \u211a}, eq_proof lhs rhs c \u2192 tactic expr)\n        {lhs rhs c} (dp : eq_proof lhs rhs c) : tactic expr :=\ndo symp \u2190 rc dp,\n   cnep \u2190 mk_ne_zero_pf c, -- 5/1 \u2260 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 : \u03a0 {lhs rhs i}, ineq_proof lhs rhs i \u2192 tactic expr\n\nprivate meta def reconstruct_of_opp_ineqs_aux {lhs rhs i} (c : \u211a) (iep : ineq_proof lhs rhs i) \n        (iepr : ineq_proof lhs rhs i.reverse) : tactic expr :=\ndo guard (bnot i.strict),\n   pr1 \u2190 iepr_fn iep, pr2 \u2190 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 : \u211a} (hc1 : c1 \u2260 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 :=\nsorry\n\n\nprivate meta def reconstruct_of_sum_form_proof (sfpr : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) : expr \u2192 expr \u2192 \u211a \u2192 \u03a0 {sf},\n       \u03a0 (sp : sum_form_proof \u27e8sf, spec_comp.eq\u27e9), 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 \u2190 sfpr sp,\n  nez \u2190 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 : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) : \u03a0 {lhs rhs : expr} {c : \u211a}, eq_proof lhs rhs c \u2192 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 \u2190 mk_mvar, pft \u2190 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 \u2264 %%mvc * %%rhs) >>= unify pft >> return mvc\n| comp.gt := to_expr ``(%%lhs > %%mvc * %%rhs) >>= unify pft >> return mvc\n| comp.ge := to_expr ``(%%lhs \u2265 %%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 \u2190 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 \u2190 guard_is_ineq lhs rhs iq pf,\n     m' \u2190 eval_expr rat m,\n     if m' = c then return pf else fail \"ineq_proof.reconstruct_hyp failed\"\nend\n\nsection\nvariable (rc : \u03a0 {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq \u2192 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 \u2190 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 \u2190 rc ip, sgnp \u2190 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 \u2265 2y and x \u2260 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 \u2190 rc ip, dpp \u2190 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 : \u03a0 {e gc}, sign_proof e gc \u2192 tactic expr)\ninclude rcs\n\n-- x \u2264 0y and x \u2260 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 \u2190 rc ip, spp \u2190 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 \u2190 rc ip, spp \u2190 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 \u2265 0 implies x \u2265 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 \u2190 rcs sp, mk_app (zero_mul_name_of_comp iq.to_comp) [rhs, spp]\nelse do spp \u2190 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 : \u211a} (hc1 : c1 \u2260 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 :=\nsorry\n\n\nprivate meta def reconstruct_of_sum_form_proof (sfpr : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) : expr \u2192 expr \u2192 \u211a \u2192 \u03a0 {sf},\n       \u03a0 (sp : sum_form_proof \u27e8sf, spec_comp.eq\u27e9), 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 \u2190 sfpr sp,\n  nez \u2190 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 : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) :\n        expr \u2192 expr \u2192 ineq \u2192 \u03a0 {sfc}, sum_form_proof sfc \u2192 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' \u2190 to_expr ``(%%(\u2191(rat.reflect m) : expr) * %%rhs), -- better way to do this?\n  tp \u2190 i.to_comp.to_function lhs rhs',\n  sgnp \u2190 mk_sign_pf a,\n  pf \u2190 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 : \u03a0 {e gc}, sign_proof e gc \u2192 tactic expr) (sfpr : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) :\n     \u03a0 {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq \u2192 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 \u2265 0)\n| gen_comp.gt := ``(%%e > 0)\n| gen_comp.le := ``(%%e \u2264 0)\n| gen_comp.lt := ``(%%e < 0)\n| gen_comp.eq := ``(%%e = 0)\n| gen_comp.ne := ``(%%e \u2260 0)\nend in do tp \u2190 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 : \u211a) : tactic expr :=\ndo sp \u2190 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 : \u03a0 {e c}, sign_proof e c \u2192 tactic expr\nparameter sfpr : \u03a0 {sf}, \u03a0 (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 \u2264 0*y to x \u2264 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 \u2190 rci ip, mk_app (zero_mul'_name_of_comp iqp.to_comp) [ipp]\nelse do ipp \u2190 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 \u2190 rce ep1, epp2 \u2190 rce ep2, nep \u2190 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 \u2190 rce ep1, epp2 \u2190 rce ep2, nep \u2190 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 \u2190 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 \u2190 rce ep,\n   mk_app ``eq_zero_of_eq_mul_zero [epp]\n\n/-\nprivate meta def reconstruct_ineqs (rct : contrad \u2192 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 {\u03b1 : Type u} [linear_order \u03b1] {a b : \u03b1} (h : \u00ac a < b) : (a \u2265 b) := le_of_not_gt h\n\nprivate theorem {u} gt_of_not_le {\u03b1 : Type u} [linear_order \u03b1] {a b : \u03b1} (h : \u00ac a \u2264 b) : (a > b) := lt_of_not_ge h\n\n\nprivate meta def neg_op_lemma_name : comp \u2192 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 : \u03a0 {sf : sum_form_comp}, \u03a0 (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 \u2190 c'.to_comp.to_function pvt `(0 : \u211a),\n   (_, notpf) \u2190 solve_aux negt (do\n     applyc $ neg_op_lemma_name c'.to_comp,\n     hypv \u2190 intro `h,\n     let sfid := sum_form_comp_data.of_ineq_data \u27e8_, ip\u27e9 in\n     let sfed := sum_form_comp_data.of_eq_data \u27e8_, ep\u27e9 in\n     let sfsd := sum_form_comp_data.of_sign_data \u27e8c'.negate, hyp pvt _ hypv\u27e9 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 \u27e8_, sfp, _\u27e9 := do ctrp \u2190 sfpr sfp, fp \u2190 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 \u2190 c'.to_comp.to_function rhs `(0 : \u211a),\n   (_, notpf) \u2190 solve_aux negt (do\n     applyc $ neg_op_lemma_name c'.to_comp,\n     hypv \u2190 intro `h,\n     let sfid := sum_form_comp_data.of_ineq_data \u27e8_, ip\u27e9 in\n     let sfed := sum_form_comp_data.of_eq_data \u27e8_, ep\u27e9 in\n     let sfsd := sum_form_comp_data.of_sign_data \u27e8c', hyp rhs _ hypv\u27e9 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 \u27e8_, sfp, _\u27e9 := do ctrp \u2190 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 \u2190 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 : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) (e : expr) (c : gen_comp) {sfc}\n        (sp : sum_form_proof sfc) : tactic expr :=\ndo \n   pf' \u2190 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 \u2190 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 : \u03a0 {e c}, sign_proof e c \u2192 tactic expr) {e} (lep : sign_proof e gen_comp.le) (gep : sign_proof e gen_comp.ge) : tactic expr :=\ndo lep' \u2190 rct lep, gep' \u2190 rct gep,\n   mk_app ``le_antisymm' [lep', gep']\n\nmeta def reconstruct_aux (sfpr : \u03a0 {sf}, \u03a0 (sp : sum_form_proof sf), tactic expr) : \u03a0 {e c}, sign_proof e c \u2192 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 : \u03a0 {sfc}, sum_form_proof sfc \u2192 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        \u03a0 {lhs rhs iq}, ineq_proof lhs rhs iq \u2192 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 \u2191`(@polya.mul_lt_of_lt) >>= trace >>\nmatch iq.to_slope with\n| slope.horiz := \n  do ipp \u2190 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 \u2190 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        \u03a0 {lhs rhs c}, eq_proof lhs rhs c \u2192 tactic expr | lhs rhs c ep :=\nif expr.lt lhs rhs then reconstruct_of_eq_proof ep.sym else\ndo ipp \u2190 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        \u03a0 {e c}, sign_proof e c \u2192 tactic expr | e c sp :=\nif c.is_less then sprc sp \nelse do spp \u2190 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 \u27e8lhs.add_factor rhs m, spec_comp.strongest c1 c2\u27e9 \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 : \u211a) \n        (sfpl : sum_form_proof \u27e8lhs, c1\u27e9) (sfpr : sum_form_proof \u27e8rhs, c2\u27e9) : tactic expr :=\nlet sum := lhs + rhs.scale m in\ndo tp \u2190 sum_form.to_expr sum,\n   tp' \u2190 (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : \u211a),\n   pf1 \u2190 sfrc sfpl, pf2 \u2190 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 : \u211a) \n        (sfpl : sum_form_proof \u27e8lhs, c1\u27e9) (sfpr : sum_form_proof \u27e8rhs, spec_comp.eq\u27e9) : tactic expr :=\nlet sum := lhs + rhs.scale m in\ndo tp \u2190 sum_form.to_expr sum,\n   tp' \u2190 c1.to_comp.to_function tp `(0 : \u211a),\n   pf1 \u2190 sfrc sfpl, pf2 \u2190 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 : \u03a0 {sfc}, sum_form_proof sfc \u2192 tactic expr) \n        {sfc} (m : \u211a) (sfp : sum_form_proof sfc) : tactic expr :=\ndo tp \u2190 sum_form.to_expr (sfc.sf.scale m),\n   tp' \u2190 sfc.c.to_comp.to_function tp `(0 : \u211a),\n   pf \u2190 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 \u2190 sum_form.to_expr sf,\n   tp' \u2190 to_expr ``(%%tp = 0),\n--   (_, pf) \u2190 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 : \u03a0 {sfc}, sum_form_proof sfc \u2192 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 : \u03a0 {sfc}, sum_form_proof sfc \u2192 tactic expr | sfc sfp :=\nif sfc.sf.keys.length = 0 then do\n ex \u2190 sfc.c.to_comp.to_function ```(0 : \u211a) ```(0 : \u211a),\n to_expr `(sorry : %%ex) else\nlet sfcd : sum_form_comp_data := \u27e8_, sfp, mk_rb_set\u27e9 in\nmatch sfcd.to_ineq_data with\n| option.some \u27e8lhs, rhs, id\u27e9 := do ex \u2190 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 : \u211a)\n| slope.some m := if m = 0 then id.inq.to_comp.to_function lhs `(0 : \u211a)\n                  else do rhs' \u2190 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 \u2190 dd.prf.reconstruct, edp \u2190 ed.prf.reconstruct, return $ ddp.app edp\n\nprivate meta def reconstruct_two_ineq_data {lhs rhs} (rct : contrad \u2192 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 \u2192 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 \u2190 nepr.reconstruct, eqprp \u2190 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 \u2190 lepr.reconstruct, gtprp \u2190 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 \u2190 gepr.reconstruct, ltprp \u2190 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 \u2190 gtpr.reconstruct, ltprp \u2190 ltpr.reconstruct,\n   mk_app ``gt_lt_contr [gtprp, ltprp]\n\n\nprivate meta def reconstruct_sign {e} : sign_data e \u2192 sign_data e \u2192 tactic expr\n| \u27e8gen_comp.ne, prf1\u27e9 \u27e8gen_comp.eq, prf2\u27e9 := reconstruct_sign_ne_eq prf1 prf2\n| \u27e8gen_comp.eq, prf1\u27e9 \u27e8gen_comp.ne, prf2\u27e9 := reconstruct_sign_ne_eq prf2 prf1\n| \u27e8gen_comp.le, prf1\u27e9 \u27e8gen_comp.gt, prf2\u27e9 := reconstruct_sign_le_gt prf1 prf2\n| \u27e8gen_comp.gt, prf1\u27e9 \u27e8gen_comp.le, prf2\u27e9 := reconstruct_sign_le_gt prf2 prf1\n| \u27e8gen_comp.lt, prf1\u27e9 \u27e8gen_comp.ge, prf2\u27e9 := reconstruct_sign_ge_lt prf2 prf1\n| \u27e8gen_comp.ge, prf1\u27e9 \u27e8gen_comp.lt, prf2\u27e9 := reconstruct_sign_ge_lt prf1 prf2\n| \u27e8gen_comp.gt, prf1\u27e9 \u27e8gen_comp.lt, prf2\u27e9 := reconstruct_sign_gt_lt prf1 prf2\n| \u27e8gen_comp.lt, prf1\u27e9 \u27e8gen_comp.gt, prf2\u27e9 := 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 \u2190 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 \u2190 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 \u2190 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 \u2192 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 \u2192 list (\u03a3 e : expr, sign_proof e gen_comp.ne) \u2192 tactic expr\n| e [] := return e\n| e (\u27e8e', sp\u27e9::t) := do ene \u2190 sp.reconstruct, pf \u2190 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 : \u211a) : list (\u03a3 e : expr, sign_proof e gen_comp.ne) \u2192 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| (\u27e8e, sp\u27e9::t) :=\n  if c = 0 then fail \"mk_prod_ne_zero_prf failed, c = 0\" else\n  do cprf \u2190 mk_app ``fake_ne_zero_pf [`(c)],\n     hpf \u2190 sp.reconstruct,\n     prodprf \u2190 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 (\u03bb 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\u207b\u00b9*rhs)\n     idp \u2190 id.reconstruct,\n     spp \u2190 sp.reconstruct,\n     opp \u2190 mk_app ``one_op_inv_mul_of_op_of_pos [idp, spp], -- 1 r lhs\u207b\u00b9*rhs\n     if bnot flipped then \n        return opp\n     else do\n        mprf \u2190 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 : \u211a \u2192 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 \u2190 id.reconstruct, --trace \"idp_type:\", infer_type idp >>= trace,\n     splp \u2190 spl.reconstruct, --trace \"splp_type:\", infer_type splp >>= trace, trace \"c1 is:\", trace c1, trace spl,\n     opp \u2190 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 \u2190 mk_sign_pf m,\n        sprp \u2190 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 (\u03bb m, m \u2264 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 \u2264 0 then fail \"reconstruct_of_ineq_proof_pos_pos failed, m \u2264 0\"\n   else do\n     idp \u2190 id.reconstruct,\n     splp \u2190 spl.reconstruct,\n     opp \u2190 mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp],\n     if bnot flipped then return opp\n     else do\n        msgn \u2190 mk_sign_pf m,\n        sprp \u2190 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 (\u03bb m, m \u2265 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 (\u03bb m, m \u2265 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 (\u03bb m, m \u2264 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 \u2265 0 then fail \"reconstruct_of_ineq_proof_pos_neg failed, m \u2265 0\"\n   else do\n     idp \u2190 id.reconstruct,\n     splp \u2190 spl.reconstruct,\n     opp \u2190 mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp],\n     if bnot flipped then return opp\n     else do\n        msgn \u2190 mk_sign_pf m,\n        sprp \u2190 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        \u03a0 {cl cr}, sign_proof lhs cl \u2192 sign_proof rhs cr \u2192 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 (\u03bb 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 \u2190 lhsne.reconstruct,\n  idpf \u2190 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 \u2190 sum_form.to_expr sf,\n   tp' \u2190 to_expr ``(%%tp = 0),\n--   (_, pf) \u2190 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 \u2190 prod_form.to_expr pf,\n --  trace \"tp:\", trace tp,\n   tp' \u2190 to_expr ``(1 = %%tp),\n --  trace \"tp':\", trace tp',\n--   (_, pf) \u2190 solve_aux tp' (simp >> done),\n   mk_app ``reconstruct_of_expr_def_aux [tp']\n\nsection\nvariable (rct : \u03a0 {pfc}, prod_form_proof pfc \u2192 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 \u2192 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 \u2192 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 \u2190 simp_pow_aux prod',\n     pow_pf \u2190 mk_app ``rat.mul_pow [a, `(rat.pow %%b %%n), k],\n     one_pow_pf \u2190 simp_pow_aux_aux b n k,\n--     trace \"doing rewrite\",\n--     infer_type pow_pf >>= trace, trace e,\n     (e', pf1, []) \u2190 rewrite pow_pf e,\n     (e'', pf2, []) \u2190 rewrite one_pow_pf e',\n     (e''', pf3, []) \u2190 rewrite prod_pf e'',\n     t1 \u2190 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 \u2190 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 \u2190 simp_pow_aux prod',\n     pow_pf \u2190 mk_app ``rat.mul_pow [coeff, prod, k],\n     --trace \"doing rewrite\",\n     (e', pf1, []) \u2190 rewrite pow_pf e,\n     (e'', pf2, []) \u2190 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 : \u211a) (m n k : \u2124) : 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) \u2190 target >>= match_eq,\ne \u2190 simp_pow lhs,\ninfer_type e >>= trace,\nexact e-/\n\nprivate meta def simp_pow_expr (pf tgt : expr) : tactic expr :=\ndo sls \u2190 (simp_lemmas.mk.add_simp ``rat.mul_pow_rev) >>= \u03bb t, t.add pf,\n   --trace \"target\", trace tgt,\n   --trace \"pf tp\", infer_type pf >>= trace,\n   (do (_, npf) \u2190 simplify sls [] tgt,-- <|> do rpr \u2190 to_expr ``(eq.refl %%tgt), return (`(()), rpr),\n   --(_, npf) \u2190 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 \u2192 list name \u2192 tactic simp_lemmas\n| s [] := return s\n| s (h::t) := s.add_simp h >>= \u03bb s', simp_lemmas.add_simp_list s' t\n\n\nprivate meta def simp_pow_expr' (tgt : expr) : tactic expr :=\ndo --sls \u2190 (simp_lemmas.mk.add_simp ``rat.mul_pow) >>= (\u03bb s, simp_lemmas.add_simp s ``rat.pow_one) >>= (\u03bb s, simp_lemmas.add_simp s ``rat.pow_neg_one),\n   sls \u2190 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) \u2190 simplify sls [] tgt,-- <|> do rpr \u2190 to_expr ``(eq.refl %%tgt), return (`(()), rpr),\n   (_, npf) \u2190 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 : \u2124) (pfp : prod_form_proof pfc) : tactic expr :=\nif z \u2264 0 then fail \"reconstruct_of_pow_pos failed, given negative exponent\" else\ndo zsn \u2190 mk_int_sign_pf z,\n   pf1 \u2190 rct pfp,\n   --trace \"here\", /-trace pfc,-/ trace pfp, trace z, infer_type pf1 >>= trace,\n   pf2 \u2190 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 \u2190 infer_type pf2,\n   match pf2tp with\n   | (app (app (app o i) lhs) rhs) :=\n    do eqp \u2190 simp_pow rhs,\n       (new_type, prf, []) \u2190 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 \u2190 prod_form.to_expr (pfc.pf.pow z), pf \u2190 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' \u2190 return $ app (app (app o i) lhs) tgt,--to_expr ``(%%o %%lhs %%tgt),\n    trace \"new tgt:\", trace tgt',\n    pf1 \u2190 to_expr ``(eq.symm %%pf),\n    (_, pf') \u2190 solve_aux tgt' (rewrite_target pf1 >> apply pf2),\n    trace \"proved\", infer_type pf' >>= trace,\n    return pf'\n   | _ := failed\n   end\n--   tgt \u2190 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 : \u2124) (pfp : prod_form_proof pfc) : tactic expr :=\nif z \u2265 0 then fail \"reconstruct_of_pow_neg failed, given positive exponent\" else\nfailed-/\n\nprivate meta def reconstruct_of_pow_eq {pfc} (z : \u2124) (pfp : prod_form_proof pfc) : tactic expr :=\ndo --trace \"pfp is:\", trace pfp, \n   pf1 \u2190 rct pfp, --trace \"reconstructed\", infer_type pf1 >>= trace,\n   tpf \u2190 mk_app ``eq_pow [pf1, `(z)],\n   tpf' \u2190 mk_app ``eq_pow' [tpf],\n   tpf_tp \u2190 infer_type tpf',\n   tgt \u2190 prod_form.to_expr (pfc.pf.pow z),\n   --trace \"target is:\", trace tgt,\n   tgt' \u2190 to_expr ``(1 = %%tgt),\n   --trace \"tgt', tpf\", trace tgt', infer_type tpf >>= trace,\n   (_, pf') \u2190 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 : \u2124) (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 \u2192 R \u2192 P := sorry\n\nprivate meta def reconstruct_of_mul (rct : \u03a0 {pfc}, prod_form_proof pfc \u2192 tactic expr) \n        {lhs rhs c1 c2} (pfp1 : prod_form_proof \u27e8lhs, c1\u27e9) (pfp2 : prod_form_proof \u27e8rhs, c2\u27e9)\n        (sgns : list \u03a3 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  \u2190 prod_form.to_expr prod,\n   --trace tp,\n   tp' \u2190 (spec_comp.strongest c1 c2).to_comp.to_function `(1 : \u211a) tp,\n   --trace tp',\n   pf1 \u2190 rct pfp1, pf2 \u2190 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 \u2190 sum_form.to_expr sum,\n   tp' \u2190 (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : \u211a),\n   pf1 \u2190 sfrc sfpl, pf2 \u2190 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 : \u03a0 {pfc}, prod_form_proof pfc \u2192 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 (\u2190 `(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 \u00b7 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 \"\u2115\" => Nat\n\n#check \u2115\n     --^ textDocument/hover\n\n/-- My command -/\nmacro \"mycmd\" e:term : command => do\n  let seq \u2190 `(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 (\u2190 `(/-- 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 := \u27e8toString\u27e9\n--^ textDocument/hover\ninstance f : ToString Nat := \u27e8toString\u27e9\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 \u2192 Nat \u2192 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 \u2192 Nat \u2192 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 \u2227 False := by\n  constructor\n  \u00b7 constructor\n--^ textDocument/hover\n\nexample : Nat := Id.run do (\u2190 1)\n                          --^ textDocument/hover\n\n#check (\u00b7 + \u00b7)\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 : \u03b1 \u2192 \u03b1 := by intro x; assumption\n                          --^ textDocument/hover\nexample : \u03b1 \u2192 \u03b1 := by intro _; assumption\n                          --^ textDocument/hover\nexample : \u03b1 \u2192 \u03b1 := by my_intro x; assumption\n                             --^ textDocument/hover\nexample : \u03b1 \u2192 \u03b1 := by my_intro _; assumption\n                             --^ textDocument/hover\n\nexample : Nat \u2192 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 \u2192 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 \u2192 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 := \u27e8Nat.zero\u27e9\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": "/-\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.Check\nimport Lean.Meta.Match.MatcherInfo\nimport Lean.Meta.Match.CaseArraySizes\n\nnamespace Lean.Meta.Match\n\ninductive Pattern : Type where\n  | inaccessible (e : Expr) : Pattern\n  | var          (fvarId : FVarId) : Pattern\n  | ctor         (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern\n  | val          (e : Expr) : Pattern\n  | arrayLit     (type : Expr) (xs : List Pattern) : Pattern\n  | as           (varId : FVarId) (p : Pattern) (hId : FVarId) : Pattern\n  deriving Inhabited\n\nnamespace Pattern\n\npartial def toMessageData : Pattern \u2192 MessageData\n  | inaccessible e         => m!\".({e})\"\n  | var varId              => mkFVar varId\n  | ctor ctorName _ _ []   => ctorName\n  | ctor ctorName _ _ pats => m!\"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ \" \" ++ toMessageData pat) Format.nil})\"\n  | val e                  => e\n  | arrayLit _ pats        => m!\"#[{MessageData.joinSep (pats.map toMessageData) \", \"}]\"\n  | as varId p h           => m!\"{mkFVar varId}@{toMessageData p}\"\n\npartial def toExpr (p : Pattern) (annotate := false) : MetaM Expr :=\n  visit p\nwhere\n  visit (p : Pattern) := do\n    match p with\n    | inaccessible e                 =>\n      if annotate then\n        pure (mkInaccessible e)\n      else\n        pure e\n    | var fvarId                     => pure $ mkFVar fvarId\n    | val e                          => pure e\n    | as fvarId p hId                =>\n      -- TODO\n      if annotate then\n        mkAppM ``namedPattern #[mkFVar fvarId, (\u2190 visit p), mkFVar hId]\n      else\n        visit p\n    | arrayLit type xs               =>\n      let xs \u2190 xs.mapM visit\n      mkArrayLit type xs\n    | ctor ctorName us params fields =>\n      let fields \u2190 fields.mapM visit\n      pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray\n\n/- Apply the free variable substitution `s` to the given pattern -/\npartial def applyFVarSubst (s : FVarSubst) : Pattern \u2192 Pattern\n  | inaccessible e  => inaccessible $ s.apply e\n  | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s)\n  | val e           => val $ s.apply e\n  | arrayLit t xs   => arrayLit (s.apply t) $ xs.map (applyFVarSubst s)\n  | var fvarId      => match s.find? fvarId with\n    | some e => inaccessible e\n    | none   => var fvarId\n  | as fvarId p hId => match s.find? fvarId with\n    | none   => as fvarId (applyFVarSubst s p) hId\n    | some _ => applyFVarSubst s p\n\ndef replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern :=\n  let s : FVarSubst := {}\n  p.applyFVarSubst (s.insert fvarId v)\n\npartial def hasExprMVar : Pattern \u2192 Bool\n  | inaccessible e => e.hasExprMVar\n  | ctor _ _ ps fs => ps.any (\u00b7.hasExprMVar) || fs.any hasExprMVar\n  | val e          => e.hasExprMVar\n  | as _ p _       => hasExprMVar p\n  | arrayLit t xs  => t.hasExprMVar || xs.any hasExprMVar\n  | _              => false\n\nend Pattern\n\npartial def instantiatePatternMVars : Pattern \u2192 MetaM Pattern\n  | Pattern.inaccessible e      => return Pattern.inaccessible (\u2190 instantiateMVars e)\n  | Pattern.val e               => return Pattern.val (\u2190 instantiateMVars e)\n  | Pattern.ctor n us ps fields => return Pattern.ctor n us (\u2190 ps.mapM instantiateMVars) (\u2190 fields.mapM instantiatePatternMVars)\n  | Pattern.as x p h            => return Pattern.as x (\u2190 instantiatePatternMVars p) h\n  | Pattern.arrayLit t xs       => return Pattern.arrayLit (\u2190 instantiateMVars t) (\u2190 xs.mapM instantiatePatternMVars)\n  | p                   => return p\n\nstructure AltLHS where\n  ref        : Syntax\n  fvarDecls  : List LocalDecl -- Free variables used in the patterns.\n  patterns   : List Pattern   -- We use `List Pattern` since we have nary match-expressions.\n\ndef instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS :=\n  return { altLHS with\n    fvarDecls := (\u2190 altLHS.fvarDecls.mapM instantiateLocalDeclMVars),\n    patterns  := (\u2190 altLHS.patterns.mapM instantiatePatternMVars)\n  }\n\nstructure Alt where\n  ref       : Syntax\n  idx       : Nat -- for generating error messages\n  rhs       : Expr\n  fvarDecls : List LocalDecl\n  patterns  : List Pattern\n  deriving Inhabited\n\nnamespace Alt\n\npartial def toMessageData (alt : Alt) : MetaM MessageData := do\n  withExistingLocalDecls alt.fvarDecls do\n    let msg : List MessageData := alt.fvarDecls.map fun d => m!\"{d.toExpr}:({d.type})\"\n    let msg : MessageData := m!\"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}\"\n    addMessageContext msg\n\ndef applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt :=\n  { alt with\n    patterns  := alt.patterns.map fun p => p.applyFVarSubst s,\n    fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s,\n    rhs       := alt.rhs.applyFVarSubst s }\n\ndef replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt :=\n  { alt with\n    patterns  := alt.patterns.map fun p => p.replaceFVarId fvarId v,\n    fvarDecls :=\n      let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId\n      decls.map $ replaceFVarIdAtLocalDecl fvarId v,\n    rhs       := alt.rhs.replaceFVarId fvarId v }\n\n/-\n  Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`.\n  This extra check is necessary when performing dependent elimination and inaccessible terms have been used.\n  For example, consider the following code fragment:\n\n```\ninductive Vec (\u03b1 : Type u) : Nat \u2192 Type u where\n  | nil : Vec \u03b1 0\n  | cons {n} (head : \u03b1) (tail : Vec \u03b1 n) : Vec \u03b1 (n+1)\n\ninductive VecPred {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 Vec \u03b1 n \u2192 Prop where\n  | nil   : VecPred P Vec.nil\n  | cons  {n : Nat} {head : \u03b1} {tail : Vec \u03b1 n} : P head \u2192 VecPred P tail \u2192 VecPred P (Vec.cons head tail)\n\ntheorem ex {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 (v : Vec \u03b1 (n+1)) \u2192 VecPred P v \u2192 Exists P\n  | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => \u27e8head, h\u27e9\n```\nRecall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term.\nThe elaborator uses an inaccessible term when typing constraints restrict its value.\nThus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)`\nbecause the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`.\nAfter elaboration the alternative becomes:\n```\n  | .(0), @Vec.cons .(\u03b1) .(0) head .(Vec.nil), @VecPred.cons .(\u03b1) .(P) .(0) .(head) .(Vec.nil) h w => \u27e8head, h\u27e9\n```\nwhere\n```\n(head : \u03b1), (h: P head), (w : VecPred P Vec.nil)\n```\nThen, when we process this alternative in this module, the following check will detect that\n`w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`.\nNote that if we had written\n```\ntheorem ex {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 (v : Vec \u03b1 (n+1)) \u2192 VecPred P v \u2192 Exists P\n  | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => \u27e8head, h\u27e9\n```\nwe would get the easier to digest error message\n```\nmissing cases:\n_, (Vec.cons _ _ (Vec.cons _ _ _)), _\n```\n-/\ndef checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do\n  match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with\n  | none          => throwErrorAt alt.ref \"unknown free pattern variable\"\n  | some fvarDecl => do\n    let vType \u2190 inferType v\n    unless (\u2190 isDefEqGuarded fvarDecl.type vType) do\n      withExistingLocalDecls alt.fvarDecls do\n        let (expectedType, givenType) \u2190 addPPExplicitToExposeDiff vType fvarDecl.type\n        throwErrorAt alt.ref \"type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\\nexpected type{indentExpr expectedType}\"\n    pure $ replaceFVarId fvarId v alt\n\nend Alt\n\ninductive Example where\n  | var        : FVarId \u2192 Example\n  | underscore : Example\n  | ctor       : Name \u2192 List Example \u2192 Example\n  | val        : Expr \u2192 Example\n  | arrayLit   : List Example \u2192 Example\n\nnamespace Example\n\npartial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example \u2192 Example\n  | var x        => if x == fvarId then ex else var x\n  | ctor n exs   => ctor n $ exs.map (replaceFVarId fvarId ex)\n  | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex)\n  | ex           => ex\n\npartial def applyFVarSubst (s : FVarSubst) : Example \u2192 Example\n  | var fvarId =>\n    match s.get fvarId with\n    | Expr.fvar fvarId' _ => var fvarId'\n    | _                   => underscore\n  | ctor n exs   => ctor n $ exs.map (applyFVarSubst s)\n  | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s)\n  | ex           => ex\n\npartial def varsToUnderscore : Example \u2192 Example\n  | var x        => underscore\n  | ctor n exs   => ctor n $ exs.map varsToUnderscore\n  | arrayLit exs => arrayLit $ exs.map varsToUnderscore\n  | ex           => ex\n\npartial def toMessageData : Example \u2192 MessageData\n  | var fvarId        => mkFVar fvarId\n  | ctor ctorName []  => mkConst ctorName\n  | ctor ctorName exs => m!\"({mkConst ctorName}{exs.foldl (fun msg pat => m!\"{msg} {toMessageData pat}\") Format.nil})\"\n  | arrayLit exs      => \"#\" ++ MessageData.ofList (exs.map toMessageData)\n  | val e             => e\n  | underscore        => \"_\"\n\nend Example\n\ndef examplesToMessageData (cex : List Example) : MessageData :=\n  MessageData.joinSep (cex.map (Example.toMessageData \u2218 Example.varsToUnderscore)) \", \"\n\nstructure Problem where\n  mvarId        : MVarId\n  vars          : List Expr\n  alts          : List Alt\n  examples      : List Example\n  deriving Inhabited\n\ndef withGoalOf {\u03b1} (p : Problem) (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withMVarContext p.mvarId x\n\ndef Problem.toMessageData (p : Problem) : MetaM MessageData :=\n  withGoalOf p do\n    let alts \u2190 p.alts.mapM Alt.toMessageData\n    let vars \u2190 p.vars.mapM fun x => do let xType \u2190 inferType x; pure m!\"{x}:({xType})\"\n    return m!\"remaining variables: {vars}\\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\\nexamples:{examplesToMessageData p.examples}\\n\"\n\nabbrev CounterExample := List Example\n\ndef counterExampleToMessageData (cex : CounterExample) : MessageData :=\n  examplesToMessageData cex\n\ndef counterExamplesToMessageData (cexs : List CounterExample) : MessageData :=\n  MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line\n\nstructure MatcherResult where\n  matcher         : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables.\n  counterExamples : List CounterExample\n  unusedAltIdxs   : List Nat\n  addMatcher      : MetaM Unit\n\n/--\n  Convert a expression occurring as the argument of a `match` motive application back into a `Pattern`\n  For example, we can use this method to convert `x::y::xs` at\n  ```\n  ...\n  (motive : List Nat \u2192 Sort u_1) (xs : List Nat) (h_1 : (x y : Nat) \u2192 (xs : List Nat) \u2192 motive (x :: y :: xs))\n  ...\n  ```\n  into a pattern object\n-/\npartial def toPattern (e : Expr) : MetaM Pattern := do\n  match inaccessible? e with\n  | some t => return Pattern.inaccessible t\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) =>\n      return Pattern.arrayLit \u03b1 (\u2190 lits.mapM toPattern)\n    | none =>\n      if e.isAppOfArity ``namedPattern 4 then\n        let p \u2190 toPattern <| e.getArg! 2\n        match e.getArg! 1, e.getArg! 3 with\n        | Expr.fvar x _, Expr.fvar h _ => return Pattern.as x p h\n        | _,             _               => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if isMatchValue e then\n        return Pattern.val e\n      else if e.isFVar then\n        return Pattern.var e.fvarId!\n      else\n        let newE \u2190 whnf e\n        if newE != e then\n          toPattern newE\n        else matchConstCtor e.getAppFn (fun _ => throwError \"unexpected pattern{indentExpr e}\") fun v us => do\n          let args := e.getAppArgs\n          unless args.size == v.numParams + v.numFields do\n            throwError \"unexpected pattern{indentExpr e}\"\n          let params := args.extract 0 v.numParams\n          let fields := args.extract v.numParams args.size\n          let fields \u2190 fields.mapM toPattern\n          return Pattern.ctor v.name us params.toList fields.toList\n\nend Lean.Meta.Match\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/Match/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.055823143883494485, "lm_q1q2_score": 0.022318742747313585}}
{"text": "theorem False.intro : False := sorry\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/RejectSorry.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.05184546225475575, "lm_q1q2_score": 0.02230118812509058}}
{"text": "import tactic.interactive\n\nlemma a {\u03b1} [nonempty \u03b1] : \u2203 a : \u03b1, a = a :=\nby inhabit \u03b1; use default _; refl\n\nnoncomputable def b {\u03b1} [nonempty \u03b1] : \u03b1 :=\nby inhabit \u03b1; apply default\n\nlemma c {\u03b1} [nonempty \u03b1] : \u2200 n : \u2115, \u2203 b : \u03b1, n = n :=\nby inhabit \u03b1; intro; use default _; refl\n\nnoncomputable def d {\u03b1} [nonempty \u03b1] : \u2200 n : \u2115, \u03b1 :=\nby inhabit \u03b1; 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) : \u2200 x \u2208 (\u2205 : set \u2115), 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) : \u2200 x \u2208 (\u2205 : set \u2115), 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 : \u03b1 \u2192 option \u03b1`, we should be able to\niterate `f : \u03b1 \u2192 \u03b2 \u2295 \u03b1` and more easily convert between `f.fix x`, a sequence of applications `\u2115 \u2192 \u03b1` 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 {\u03b1 \u03b2 : Type*} {f : \u03b1 \u2192. \u03b2 \u2295 \u03b1} {a : \u03b1} {b : \u03b2} (h : b \u2208 f.fix a) :\n  \u2203 a', sum.inl b \u2208 f a' :=\nby apply fix_induction' _ _ h; tauto\n\nvariables {\u03b1\u2081 \u03b1\u2082 \u03b2\u2081 \u03b2\u2082 : Type*}\nvariables (f\u2081 : \u03b1\u2081 \u2192. \u03b2\u2081 \u2295 \u03b1\u2081) (f\u2082 : \u03b1\u2082 \u2192. \u03b2\u2082 \u2295 \u03b1\u2082)\n\n/-- We just extract a very special case, which is all we need here: two functions `f\u2081` and `f\u2082` satisfy\n`frespects_once` wrt `F` if whenever `f\u2081` takes a single step from `a\u2081 : \u03b1\u2081` to `a\u2081' : \u03b1\u2081`, `f\u2082` takes\nthe corresponding step from `a\u2082 = F a\u2081` to `a\u2082' = F a\u2081'`, and moreover, if `f\u2081` diverges on a state iff `f\u2082` diverges\non the corresponding one, and `f\u2081` halts on a state iff `f\u2082` halts on the corresponding one. \n\nWe use a slightly weaker definition which is equivalent to the above description. -/\ndef frespects_once (F : \u03b1\u2081 \u2192 \u03b1\u2082) : Prop :=\n\u2200 a\u2081, ((f\u2082 (F a\u2081)).dom \u2192 (f\u2081 a\u2081).dom) \u2227 (\u2200 a\u2081', sum.inr a\u2081' \u2208 f\u2081 a\u2081 \u2192 (sum.inr $ F a\u2081') \u2208 (f\u2082 (F a\u2081)))\n  \u2227 ((\u2203 b\u2081, sum.inl b\u2081 \u2208 f\u2081 a\u2081) \u2192 \u2203 b\u2082, sum.inl b\u2082 \u2208 f\u2082 (F a\u2081))\n\nvariables {F : \u03b1\u2081 \u2192 \u03b1\u2082} (hF : frespects_once f\u2081 f\u2082 F) {f\u2081 f\u2082}\ninclude hF\n\nlemma dom_iff_dom (a : \u03b1\u2081) : (f\u2081 a).dom \u2194 (f\u2082 (F a)).dom :=\nbegin\n  specialize hF a, split, swap, { exact hF.1, },\n  { intro h, \n    rw part.dom_iff_mem at h \u22a2,\n    obtain \u27e8y, hy\u27e9 := h,\n    cases y with ly ry,\n    { obtain \u27e8b\u2082, hb\u2082\u27e9 := hF.2.2 \u27e8ly, hy\u27e9, use sum.inl b\u2082, assumption, },\n    exact \u27e8_, hF.2.1 ry hy\u27e9, }\nend\n\nlemma fwd_preimage_of_fwd {a : \u03b1\u2081} {a' : \u03b1\u2082} (ha' : sum.inr a' \u2208 f\u2082 (F a)) : \u2203 a\u2081', sum.inr a\u2081' \u2208 f\u2081 a \u2227 F a\u2081' = a' :=\nbegin\n  have : (f\u2081 a).dom, { rw [dom_iff_dom hF a, part.dom_iff_mem], exact \u27e8_, ha'\u27e9, }, \n  specialize hF a,\n  suffices h : \u2203 a\u2081', sum.inr a\u2081' \u2208 f\u2081 a, \n  { obtain \u27e8a\u2081', h\u27e9 := h, use a\u2081', refine \u27e8h, _\u27e9, exact sum.inr_injective (part.mem_unique (hF.2.1 a\u2081' h) ha'), },\n  cases (f\u2081 a) with d v, cases e : v this with vb va,\n  { exfalso, cases hF.2.2 \u27e8vb, _\u27e9 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 : \u03b1\u2081) : (\u2203 a', sum.inr a' \u2208 f\u2081 a) \u2194 \u2203 a', sum.inr a' \u2208 f\u2082 (F a) :=\nbegin\n  split; rintro \u27e8a', ha'\u27e9,\n  { exact \u27e8_, (hF a).2.1 a' ha'\u27e9, },\n  { obtain \u27e8a\u2081', ha\u2081'\u27e9 := fwd_preimage_of_fwd hF ha', exact \u27e8a\u2081', ha\u2081'.1\u27e9, }\nend\n\nlemma stop_iff_stop (a : \u03b1\u2081) : (\u2203 b\u2081, sum.inl b\u2081 \u2208 f\u2081 a) \u2194 \u2203 b\u2082, sum.inl b\u2082 \u2208 f\u2082 (F a) :=\nbegin\n  split, { exact (hF a).2.2, },\n  rintro \u27e8b\u2082, hb\u2082\u27e9,\n  have : (f\u2081 a).dom, { rw [dom_iff_dom hF a, part.dom_iff_mem], exact \u27e8_, hb\u2082\u27e9, }, \n  have H := (fwd_iff_fwd hF a).mp,\n  cases (f\u2081 a) with d v, cases e : v this with vb va,\n  { use vb, use this, exact e, },\n  exfalso, specialize H \u27e8va, _\u27e9, { use this, exact e, },\n  obtain \u27e8a\u2082', ha\u2082'\u27e9 := H, have := part.mem_unique hb\u2082 ha\u2082', contradiction,\nend\n\nlemma frespects_last_step {a : \u03b1\u2081} {b\u2081 : \u03b2\u2081} {b\u2082 : \u03b2\u2082} (hb\u2081 : b\u2081 \u2208 f\u2081.fix a) (hb\u2082 : b\u2082 \u2208 f\u2082.fix (F a)) :\n  \u2203 a' : \u03b1\u2081, sum.inl b\u2081 \u2208 f\u2081 a' \u2227 sum.inl b\u2082 \u2208 f\u2082 (F a') :=\nbegin\n  revert hb\u2082,\n  apply fix_induction' _ _ hb\u2081; clear hb\u2081 a,\n  { intros a' ha' hb\u2082, use [a', ha'],\n    obtain \u27e8b\u2082', hb\u2082'\u27e9 := (stop_iff_stop hF a').mp \u27e8b\u2081, ha'\u27e9,\n    have : b\u2082 = b\u2082' := part.mem_unique hb\u2082 (fix_stop _ hb\u2082'), subst this,\n    assumption, },\n  intros a a' ha' ha ih hb\u2082,\n  refine ih _,\n  rwa \u2190 fix_fwd _ _ ((hF a).2.1 _ ha),\nend\n\nvariable (F)\ntheorem eq_dom_of_frespects_once (a : \u03b1\u2081) :\n  (f\u2081.fix a).dom \u2194 (f\u2082.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 \u27e8b\u2082, hb\u2082\u27e9 := (stop_iff_stop hF a).mp \u27e8_, h\u27e9,\n      rw [part.dom_iff_mem], use b\u2082, exact fix_stop _ hb\u2082, },\n    intros a a' hy ha ha',\n    rw part.dom_iff_mem at \u22a2 ha',\n    rw fix_fwd, { exact ha', }, exact (hF a).2.1 a' ha, },\n  suffices : \u2200 a', F a' = F a \u2192 (f\u2081.fix a').dom, { exact this a rfl, },\n  apply @fix_induction' _ _ f\u2082 y (\u03bb z, \u2200 a', F a' = z \u2192 (f\u2081.fix a').dom) _ h; clear h a,\n  { intros a ha a' ha', subst ha',\n    have : \u2203 y', sum.inl y' \u2208 f\u2081 a', { rw stop_iff_stop hF a', exact \u27e8_, ha\u27e9, },\n    rw part.dom_iff_mem, obtain \u27e8y', hy'\u27e9 := this, exact \u27e8y', fix_stop _ hy'\u27e9, },\n  intros a a' ha' ha ih x hx, subst hx,\n  rw part.dom_iff_mem,\n  obtain \u27e8y', hy', hyF\u27e9 := 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": "/-\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 \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 (\u03b1 : Type u) \nwhere\n  apply : List \u03b1 \u2192 List \u03b1\n  invariant : \u2200 (l : List \u03b1), apply l = apply [] ++ l\n\nnamespace dlist\n\n\n/-- Convert a list to a dlist -/\ndef of_list {\u03b1 : Type u} (l : List \u03b1) : dlist \u03b1 :=\n  mk (append l) sorry\n\n/-- Convert a lazily-evaluated list to a dlist -/\ndef lazy_of_list {\u03b1 : Type u} (l : thunk (List \u03b1)) : dlist \u03b1 :=\n  mk (fun (xs : List \u03b1) => l Unit.unit ++ xs) sorry\n\n/-- Convert a dlist to a list -/\ndef to_list {\u03b1 : Type u} : dlist \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n/--  Create a dlist containing no elements -/\ndef empty {\u03b1 : Type u} : dlist \u03b1 :=\n  mk id sorry\n\n/-- Create dlist with a single element -/\ndef singleton {\u03b1 : Type u} (x : \u03b1) : dlist \u03b1 :=\n  mk (List.cons x) sorry\n\n/-- `O(1)` Prepend a single element to a dlist -/\ndef cons {\u03b1 : Type u} (x : \u03b1) : dlist \u03b1 \u2192 dlist \u03b1 :=\n  sorry\n\n/-- `O(1)` Append a single element to a dlist -/\ndef concat {\u03b1 : Type u} (x : \u03b1) : dlist \u03b1 \u2192 dlist \u03b1 :=\n  sorry\n\n/-- `O(1)` Append dlists -/\nprotected def append {\u03b1 : Type u} : dlist \u03b1 \u2192 dlist \u03b1 \u2192 dlist \u03b1 :=\n  sorry\n\nprotected instance has_append {\u03b1 : Type u} : Append (dlist \u03b1) :=\n  { append := dlist.append }\n\ntheorem to_list_of_list {\u03b1 : Type u} (l : List \u03b1) : to_list (of_list l) = l := sorry\n\ntheorem of_list_to_list {\u03b1 : Type u} (l : dlist \u03b1) : of_list (to_list l) = l := sorry\n\ntheorem to_list_empty {\u03b1 : Type u} : to_list empty = [] := sorry\n\ntheorem to_list_singleton {\u03b1 : Type u} (x : \u03b1) : to_list (singleton x) = [x] := sorry\n\ntheorem to_list_append {\u03b1 : Type u} (l\u2081 : dlist \u03b1) (l\u2082 : dlist \u03b1) : to_list (l\u2081 ++ l\u2082) = to_list l\u2081 ++ to_list l\u2082 := sorry\n\ntheorem to_list_cons {\u03b1 : Type u} (x : \u03b1) (l : dlist \u03b1) : to_list (cons x l) = x :: to_list l := sorry\n\ntheorem to_list_concat {\u03b1 : Type u} (x : \u03b1) (l : dlist \u03b1) : to_list (concat x l) = to_list l ++ [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/Lean3Lib/data/dlist.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.057493275974271806, "lm_q1q2_score": 0.022129860148663572}}
{"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\u2082 $nm)\n    else `(dupOr $nm)\n  | (i' + 1) => do\n    let nm' := mkIdent (Name.mkSimple \"w\")\n    let r \u2190 congDupOr i' nm' last\n    let r: Term := \u27e8r\u27e9\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\u2081: move expr that is equal to the pivot to position i + 1\n      let step\u2081 \u2190\n        if j > i + 1 then\n          let fname \u2190 mkIdent <$> mkFreshId\n          let e \u2190 getTypeFromName nm.getId\n          let t \u2190 instantiateMVars e\n          pullIndex2 (i + 1) j nm t fname\n          pure fname\n        else pure nm\n\n      -- step\u2082: apply congOrLeft i times with dupOr\n      let step\u2082: Ident \u2190 do\n        let last := i + 1 == n - 1\n        let tactic \u2190 congDupOr i step\u2081 last \n        let tactic := \u27e8tactic\u27e9\n        let fname \u2190 mkIdent <$> mkFreshId\n        evalTactic (\u2190 `(tactic| have $fname := $tactic))\n        pure fname\n\n      loop i j (n - 1) pivot es step\u2082\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 \u2190 loop i (i + 1) (li.length + i) e es answer\n        let e \u2190 getTypeFromName answer.getId\n        let t \u2190 instantiateMVars e\n        li := collectPropsInOrChain t\n    evalTactic (\u2190 `(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 \u2190 elabTerm stx[1] none\n    let type \u2190 inferType e\n    let source := \u27e8stx[1]\u27e9\n    factorCore type source\n\nexample : A \u2228 A \u2228 A \u2228 A \u2228 B \u2228 A \u2228 B \u2228 A \u2228 C \u2228 B \u2228 C \u2228 B \u2228 A \u2192 A \u2228 B \u2228 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 \u00absmt-lean\u00bb\n\nexample {\u03b1 : Type} {z : \u03b1} {x y : list \u03b1}\n  (h : (z :: x : list \u03b1) = 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": "/-\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-/\nprelude\nimport init.meta.tactic init.meta.simp_tactic init.meta.interactive\nimport init.meta.congr_lemma init.meta.match_tactic\nopen tactic\n\ndef tactic.id_tag.conv : unit := ()\n\nuniverse u\n\n/-- `conv \u03b1` 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-/\nmeta def conv (\u03b1 : Type u) :=\ntactic \u03b1\n\nmeta instance : monad conv :=\nby dunfold conv; apply_instance\n\nmeta instance : monad_fail conv :=\nby dunfold conv; apply_instance\n\nmeta instance : alternative conv :=\nby dunfold conv; apply_instance\n\nnamespace conv\n/-- Applies the conversion `c`. Returns `(rhs,p)` where `p : r lhs rhs`. Throws away the return value of `c`.-/\nmeta def convert (c : conv unit) (lhs : expr) (rel : name := `eq) : tactic (expr \u00d7 expr) :=\ndo lhs_type   \u2190 infer_type lhs,\n   rhs        \u2190 mk_meta_var lhs_type,\n   new_target \u2190 mk_app rel [lhs, rhs],\n   new_g      \u2190 mk_meta_var new_target,\n   gs         \u2190 get_goals,\n   set_goals [new_g],\n   c,\n   try $ any_goals reflexivity,\n   n          \u2190 num_goals,\n   when (n \u2260 0) (fail \"convert tactic failed, there are unsolved goals\"),\n   set_goals gs,\n   rhs        \u2190 instantiate_mvars rhs,\n   new_g      \u2190 instantiate_mvars new_g,\n   return (rhs, new_g)\n\nmeta def lhs : conv expr :=\ndo (_, lhs, rhs) \u2190 target_lhs_rhs,\n   return lhs\n\nmeta def rhs : conv expr :=\ndo (_, lhs, rhs) \u2190 target_lhs_rhs,\n   return rhs\n\n/-- `\u22a2 lhs = rhs` ~~> `\u22a2 lhs' = rhs` using `h : lhs = lhs'`. -/\nmeta def update_lhs (new_lhs : expr) (h : expr) : conv unit :=\ndo transitivity,\n   rhs >>= unify new_lhs,\n   exact h,\n   t \u2190 target >>= instantiate_mvars,\n   change t\n\n/-- Change `lhs` to something definitionally equal to it. -/\nmeta def change (new_lhs : expr) : conv unit :=\ndo (r, lhs, rhs) \u2190 target_lhs_rhs,\n   new_target \u2190 mk_app r [new_lhs, rhs],\n   tactic.change new_target\n/-- Use reflexivity to prove. -/\nmeta def skip : conv unit :=\nreflexivity\n/-- Put LHS in WHNF. -/\nmeta def whnf : conv unit :=\nlhs >>= tactic.whnf >>= change\n\n/-- dsimp the LHS. -/\nmeta def dsimp (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : conv unit :=\ndo s \u2190 match s with\n       | some s := return s\n       | none   := simp_lemmas.mk_default\n       end,\n   l \u2190 lhs,\n   s.dsimplify u l cfg >>= change\n\nprivate meta def congr_aux : list congr_arg_kind \u2192 list expr \u2192 tactic (list expr \u00d7 list expr)\n| []      []      := return ([], [])\n| (k::ks) (a::as) := do\n  (gs, largs) \u2190 congr_aux ks as,\n  match k with\n  -- parameter for the congruence lemma\n  | congr_arg_kind.fixed            := return $ (gs, a::largs)\n  -- parameter which is a subsingleton\n  | congr_arg_kind.fixed_no_param   := return $ (gs, largs)\n  | congr_arg_kind.eq               := do\n      a_type  \u2190 infer_type a,\n      rhs     \u2190 mk_meta_var a_type,\n      g_type  \u2190 mk_app `eq [a, rhs],\n      g       \u2190 mk_meta_var g_type, -- proof that `a = rhs`\n      return (g::gs, a::rhs::g::largs)\n  | congr_arg_kind.cast             := return $ (gs, a::largs)\n  | _                               := fail \"congr tactic failed, unsupported congruence lemma\"\n  end\n| ks      as := fail \"congr tactic failed, unsupported congruence lemma\"\n\n/-- Take the target equality `f x y = X` and try to apply the congruence lemma for `f` to it (namely `x = x' \u2192 y = y' \u2192 f x y = f x' y'`). -/\nmeta def congr : conv unit :=\ndo (r, lhs, rhs) \u2190 target_lhs_rhs,\n   guard (r = `eq),\n   let fn   := lhs.get_app_fn,\n   let args := lhs.get_app_args,\n   cgr_lemma \u2190 mk_congr_lemma_simp fn (some args.length),\n   g::gs \u2190 get_goals,\n   (new_gs, lemma_args) \u2190 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\n/-- Create a conversion from the function extensionality tactic.-/\nmeta def funext : conv unit :=\niterate' $ do\n  (r, lhs, rhs) \u2190 target_lhs_rhs,\n  guard (r = `eq),\n  (expr.lam n _ _ _) \u2190 return lhs,\n  tactic.applyc `funext,\n  intro n,\n  return ()\n\nend conv\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/converter/conv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.053403330929736405, "lm_q1q2_score": 0.021954689798417054}}
{"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-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.logic\nimport Mathlib.Lean3Lib.init.control.monad\nimport Mathlib.Lean3Lib.init.control.alternative\n\nuniverses u v u_1 u_2 \n\nnamespace Mathlib\n\nnamespace option\n\n\ndef to_monad {m : Type \u2192 Type} [Monad m] [alternative m] {A : Type} : Option A \u2192 m A := sorry\n\ndef get_or_else {\u03b1 : Type u} : Option \u03b1 \u2192 \u03b1 \u2192 \u03b1 := sorry\n\ndef is_some {\u03b1 : Type u} : Option \u03b1 \u2192 Bool := sorry\n\ndef is_none {\u03b1 : Type u} : Option \u03b1 \u2192 Bool := sorry\n\ndef get {\u03b1 : Type u} {o : Option \u03b1} : \u21a5(is_some o) \u2192 \u03b1 := sorry\n\ndef rhoare {\u03b1 : Type u} : Bool \u2192 \u03b1 \u2192 Option \u03b1 := sorry\n\ndef lhoare {\u03b1 : Type u} : \u03b1 \u2192 Option \u03b1 \u2192 \u03b1 := sorry\n\ninfixr:1 \"|>\" => Mathlib.option.rhoare\n\ninfixr:1 \"<|\" => Mathlib.option.lhoare\n\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} : Option \u03b1 \u2192 (\u03b1 \u2192 Option \u03b2) \u2192 Option \u03b2 := sorry\n\nprotected def map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (o : Option \u03b1) : Option \u03b2 :=\n  option.bind o (some \u2218 f)\n\ntheorem map_id {\u03b1 : Type u_1} : option.map id = id := sorry\n\nprotected instance monad : Monad Option :=\n  { toApplicative :=\n      { toFunctor :=\n          { map := option.map, mapConst := fun (\u03b1 \u03b2 : Type u_1) => option.map \u2218 function.const \u03b2 },\n        toPure := { pure := some },\n        toSeq :=\n          { seq :=\n              fun (\u03b1 \u03b2 : Type u_1) (f : Option (\u03b1 \u2192 \u03b2)) (x : Option \u03b1) =>\n                option.bind f fun (_x : \u03b1 \u2192 \u03b2) => option.map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : Option \u03b1) (b : Option \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : Option (\u03b1 \u2192 \u03b2)) (x : Option \u03b1) =>\n                    option.bind f fun (_x : \u03b1 \u2192 \u03b2) => option.map _x x)\n                  \u03b2 \u03b1 (option.map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : Option \u03b1) (b : Option \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : Option (\u03b1 \u2192 \u03b2)) (x : Option \u03b1) =>\n                    option.bind f fun (_x : \u03b1 \u2192 \u03b2) => option.map _x x)\n                  \u03b2 \u03b2 (option.map (function.const \u03b1 id) a) b } },\n    toBind := { bind := option.bind } }\n\nprotected def orelse {\u03b1 : Type u} : Option \u03b1 \u2192 Option \u03b1 \u2192 Option \u03b1 := sorry\n\nprotected instance alternative : alternative Option := alternative.mk none\n\nend option\n\n\nprotected instance option.inhabited (\u03b1 : Type u) : Inhabited (Option \u03b1) := { default := none }\n\nprotected instance option.decidable_eq {\u03b1 : Type u} [d : DecidableEq \u03b1] : DecidableEq (Option \u03b1) :=\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/init/data/option/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.04603390305362163, "lm_q1q2_score": 0.02193882145439408}}
{"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\u2014programming the prover\u2014is 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\u2026sub)goals until it cannot\nbe applied any further. -/\n\nlemma repeat_example :\n  even 4 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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 \u2227 even 7 \u2227 even 3 \u2227 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  \u00ac 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\u2082 :\n  even 4 \u2227 even 7 \u2227 even 3 \u2227 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 \u2026\",\n  intro_and_even\n\nmeta def hello_then_intro_and_even : tactic unit :=\ndo\n  tactic.trace \"Proving evenness \u2026\",\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 \u2190 tactic.local_context,\n  tactic.trace ctx,\n  tactic.trace \"target:\",\n  P \u2190 tactic.target,\n  tactic.trace P,\n  tactic.trace \"all missing proofs:\",\n  Hs \u2190 tactic.get_goals,\n  tactic.trace Hs,\n  \u03c4s \u2190 list.mmap tactic.infer_type Hs,\n  tactic.trace \u03c4s\n\nlemma even_18_and_even_20 (\u03b1 : Type) (a : \u03b1) :\n  even 18 \u2227 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 \u2190 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  \u03c4 \u2190 tactic.infer_type h,\n  tactic.trace \u03c4,\n  tactic.trace \"type of type of h:\",\n  \u03c5 \u2190 tactic.infer_type \u03c4,\n  tactic.trace \u03c5,\n  tactic.apply h\n\nmeta def exact_list : list expr \u2192 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 \u2190 tactic.local_context,\n  exact_list hs\n\nlemma app_of_app {\u03b1 : Type} {p : \u03b1 \u2192 Prop} {a : \u03b1}\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 `\u2115 [] : 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  `(\u2115) : expr)\n#check (expr.mvar `uniq_name `pp_name `(\u2115) : expr)\n#check (expr.pi `pp_name binder_info.default `(\u2115)\n  (expr.sort level.zero) : expr)\n#check (expr.lam `pp_name binder_info.default `(\u2115)\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 (\u03bbn : \u2115, 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\u2081 : pexpr := ``(list.map (\u03bbn, n + 1) [1, 2, 3]),\n  let e\u2082 : pexpr := ``(list.map _ [1, 2, 3]),\n  tactic.trace e\u2081,\n  tactic.trace e\u2082\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 : \u2115),\n  let e : expr := `(%%x + 1),\n  tactic.trace e\n\nrun_cmd do\n  let x : expr  := `(@id \u2115),\n  let e : pexpr := ``(list.map %%x),\n  tactic.trace e\n\nrun_cmd do\n  let x : expr  := `(@id \u2115),\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) \u2190 tactic.target,\n  tactic.trace a,\n  tactic.trace b,\n  tactic.trace c,\n  `(@eq %%\u03b1 %%l %%r) \u2190 tactic.target,\n  tactic.trace \u03b1,\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 \u2190 tactic.get_env,\n  tactic.trace (environment.fold env 0 (\u03bbdecl n, n + 1))\n\n\n/-! ## First Example: A Conjuction-Destructing Tactic\n\nWe define a `destruct_and` tactic that automates the elimination of `\u2227` in\npremises, automating proofs such as these: -/\n\nlemma abcd_a (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  a :=\nand.elim_left h\n\nlemma abcd_b (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  b :=\nand.elim_left (and.elim_left (and.elim_right h))\n\nlemma abcd_bc (a b c d : Prop) (h : a \u2227 (b \u2227 c) \u2227 d) :\n  b \u2227 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 \u2192 tactic unit\n| h :=\n  do\n    t \u2190 tactic.infer_type h,\n    match t with\n    | `(%%a \u2227 %%b) :=\n      tactic.exact h\n      <|>\n      do {\n        ha \u2190 tactic.to_expr ``(and.elim_left %%h),\n        destruct_and_helper ha }\n      <|>\n      do {\n        hb \u2190 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 \u2190 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 \u2227 b \u2227 c) :\n  a :=\nby destruct_and `h\n\nlemma abc_b (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  b :=\nby destruct_and `h\n\nlemma abc_bc (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  b \u2227 c :=\nby destruct_and `h\n\nlemma abc_ac (a b c : Prop) (h : a \u2227 b \u2227 c) :\n  a \u2227 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 \u2192 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 \u2190 tactic.get_env,\n  pure (environment.fold env [] (\u03bbdecl 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 \u2190 get_all_theorems,\n  list.mfirst (\u03bbnam,\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 : \u2115) (h : x = y) :\n  y = x :=\nby prove_direct\n\nlemma nat.eq_symm\u2082 (x y : \u2115) (h : x = y) :\n  y = x :=\nby library_search\n\nlemma list.reverse_twice (xs : list \u2115) :\n  list.reverse (list.reverse xs) = xs :=\nby prove_direct\n\nlemma list.reverse_twice_symm (xs : list \u2115) :\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\u2082 (xs : list \u2115) :\n  list.reverse (list.reverse xs) = xs :=\nby prove_direct_symm\n\nlemma list.reverse_twice_symm\u2082 (xs : list \u2115) :\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\u2081 l\u2082` compares two lists of `Option LocalDecl`s (as returned from e.g.\n`(\u2190 (\u2190 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\u2081 l\u2082 : List (Option LocalDecl)) \u2192 MetaM Bool\n  | some d\u2081 :: l\u2081, some d\u2082 :: l\u2082 => do\n    unless (\u2190 withNewMCtxDepth <| isDefEq d\u2081.type d\u2082.type) do\n      return false\n    lctxIsDefEq l\u2081 l\u2082\n  | none :: l\u2081, none :: l\u2082 => lctxIsDefEq l\u2081 l\u2082\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 \u2190 run goal tacs\n  try\n    let [newGoal] := l | failure\n    guard <|\u2190 withNewMCtxDepth <| withReducible <| isDefEq (\u2190 newGoal.getType) (\u2190 goal.getType)\n    let ctxDecls := (\u2190 goal.getDecl).lctx.decls.toList\n    let newCtxDecls := (\u2190 newGoal.getDecl).lctx.decls.toList\n    guard <|\u2190 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 \u2190 getMainGoal\n  let l \u2190 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": "macro \"expensive_tactic\" : tactic => `(sleep 5000)\n\nexample (h\u2081 : x = y) (h\u2082 : y = z) : z = x := by\n  expensive_tactic\n  save\n  have : y = x := h\u2081.symm\n  have : z = y := h\u2082.symm\n  trace \"hello world\"\n  apply this.trans\n  exact \u2039y = x\u203a\n\nexample (h\u2081 : p \u2228 q) (h\u2082 : p \u2192 x = 0) (h\u2083 : q \u2192 y = 0) : x * y = 0 := by\n  expensive_tactic\n  save\n  match h\u2081 with\n  | .inr h =>\n    expensive_tactic\n    save\n    have : y = 0 := h\u2083 h\n    simp [*]\n  | .inl h => stop done\n\nexample (h\u2081 : p \u2228 q) (h\u2082 : p \u2192 x = 0) (h\u2083 : q \u2192 y = 0) : x * y = 0 := by\n  expensive_tactic\n  save\n  cases h\u2081 with\n  | inr h =>\n    expensive_tactic\n    save\n    have : y = 0 := h\u2083 h\n    simp [*]\n  | inl h => stop\n    expensive_tactic\n    save\n    have : x = 0 := h\u2082 h\n    simp [*]\n    done\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/sleep_save.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.049589021228304254, "lm_q1q2_score": 0.021902131324993596}}
{"text": "example [Subsingleton \u03b1] (p : \u03b1 \u2192 Prop) : Subsingleton (Subtype p) :=\n  \u27e8fun \u27e8x, _\u27e9 \u27e8y, _\u27e9 => Subsingleton.elim x y \u25b8 sorry\u27e9\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": "/-\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\n! This file was ported from Lean 3 source module init.data.string.basic\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.Data.List.Basic\nimport Leanbin.Init.Data.Char.Basic\n\n/-- In the VM, strings are implemented using a dynamic array and UTF-8 encoding.\n\n   TODO: we currently cannot mark string_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\nstructure StringImp where\n  data : List Char\n#align string_imp StringImp\n\n#print String /-\ndef String :=\n  StringImp\n#align string String\n-/\n\n#print List.asString /-\ndef List.asString (s : List Char) : String :=\n  \u27e8s\u27e9\n#align list.as_string List.asString\n-/\n\nnamespace String\n\ninstance : LT String :=\n  \u27e8fun s\u2081 s\u2082 => s\u2081.data < s\u2082.data\u27e9\n\n/-- Remark: this function has a VM builtin efficient implementation. -/\ninstance hasDecidableLt (s\u2081 s\u2082 : String) : Decidable (s\u2081 < s\u2082) :=\n  List.hasDecidableLt s\u2081.data s\u2082.data\n#align string.has_decidable_lt String.hasDecidableLt\n\ninstance hasDecidableEq : DecidableEq String := fun \u27e8x\u27e9 \u27e8y\u27e9 =>\n  match List.hasDecEq x y with\n  | is_true p => isTrue (congr_arg StringImp.mk p)\n  | is_false p => isFalse fun q => p (StringImp.mk.inj q)\n#align string.has_decidable_eq String.hasDecidableEq\n\ndef empty : String :=\n  \u27e8[]\u27e9\n#align string.empty String.empty\n\n#print String.length /-\ndef length : String \u2192 Nat\n  | \u27e8s\u27e9 => s.length\n#align string.length String.length\n-/\n\n#print String.push /-\n/-- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\ndef push : String \u2192 Char \u2192 String\n  | \u27e8s\u27e9, c => \u27e8s ++ [c]\u27e9\n#align string.push String.push\n-/\n\n#print String.append /-\n/-- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\ndef append : String \u2192 String \u2192 String\n  | \u27e8a\u27e9, \u27e8b\u27e9 => \u27e8a ++ b\u27e9\n#align string.append String.append\n-/\n\n#print String.toList /-\n/-- O(n) in the VM, where n is the length of the string -/\ndef toList : String \u2192 List Char\n  | \u27e8s\u27e9 => s\n#align string.to_list String.toList\n-/\n\ndef fold {\u03b1} (a : \u03b1) (f : \u03b1 \u2192 Char \u2192 \u03b1) (s : String) : \u03b1 :=\n  s.toList.foldl f a\n#align string.fold String.fold\n\n/-- In the VM, the string iterator is implemented as a pointer to the string being iterated + index.\n\n   TODO: we currently cannot mark interator_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\nstructure IteratorImp where\n  fst : List Char\n  snd : List Char\n#align string.iterator_imp String.IteratorImp\n\n#print String.Iterator /-\ndef Iterator :=\n  IteratorImp\n#align string.iterator String.Iterator\n-/\n\n#print String.mkIterator /-\ndef mkIterator : String \u2192 Iterator\n  | \u27e8s\u27e9 => \u27e8[], s\u27e9\n#align string.mk_iterator String.mkIterator\n-/\n\nnamespace Iterator\n\n#print String.Iterator.curr /-\ndef curr : Iterator \u2192 Char\n  | \u27e8p, c :: n\u27e9 => c\n  | _ => default\n#align string.iterator.curr String.Iterator.curr\n-/\n\n#print String.Iterator.setCurr /-\n/--\nIn the VM, `set_curr` is constant time if the string being iterated is not shared and linear time\n   if it is. -/\ndef setCurr : Iterator \u2192 Char \u2192 Iterator\n  | \u27e8p, c :: n\u27e9, c' => \u27e8p, c' :: n\u27e9\n  | it, c' => it\n#align string.iterator.set_curr String.Iterator.setCurr\n-/\n\n#print String.Iterator.next /-\ndef next : Iterator \u2192 Iterator\n  | \u27e8p, c :: n\u27e9 => \u27e8c :: p, n\u27e9\n  | \u27e8p, []\u27e9 => \u27e8p, []\u27e9\n#align string.iterator.next String.Iterator.next\n-/\n\n#print String.Iterator.prev /-\ndef prev : Iterator \u2192 Iterator\n  | \u27e8c :: p, n\u27e9 => \u27e8p, c :: n\u27e9\n  | \u27e8[], n\u27e9 => \u27e8[], n\u27e9\n#align string.iterator.prev String.Iterator.prev\n-/\n\n#print String.Iterator.hasNext /-\ndef hasNext : Iterator \u2192 Bool\n  | \u27e8p, []\u27e9 => false\n  | _ => true\n#align string.iterator.has_next String.Iterator.hasNext\n-/\n\n#print String.Iterator.hasPrev /-\ndef hasPrev : Iterator \u2192 Bool\n  | \u27e8[], n\u27e9 => false\n  | _ => true\n#align string.iterator.has_prev String.Iterator.hasPrev\n-/\n\ndef insert : Iterator \u2192 String \u2192 Iterator\n  | \u27e8p, n\u27e9, \u27e8s\u27e9 => \u27e8p, s ++ n\u27e9\n#align string.iterator.insert String.Iterator.insert\n\ndef remove : Iterator \u2192 Nat \u2192 Iterator\n  | \u27e8p, n\u27e9, m => \u27e8p, n.drop m\u27e9\n#align string.iterator.remove String.Iterator.remove\n\n#print String.Iterator.toString /-\n/-- In the VM, `to_string` is a constant time operation. -/\ndef toString : Iterator \u2192 String\n  | \u27e8p, n\u27e9 => \u27e8p.reverse ++ n\u27e9\n#align string.iterator.to_string String.Iterator.toString\n-/\n\n#print String.Iterator.toEnd /-\ndef toEnd : Iterator \u2192 Iterator\n  | \u27e8p, n\u27e9 => \u27e8n.reverse ++ p, []\u27e9\n#align string.iterator.to_end String.Iterator.toEnd\n-/\n\ndef nextToString : Iterator \u2192 String\n  | \u27e8p, n\u27e9 => \u27e8n\u27e9\n#align string.iterator.next_to_string String.Iterator.nextToString\n\ndef prevToString : Iterator \u2192 String\n  | \u27e8p, n\u27e9 => \u27e8p.reverse\u27e9\n#align string.iterator.prev_to_string String.Iterator.prevToString\n\nprotected def extractCore : List Char \u2192 List Char \u2192 Option (List Char)\n  | [], cs => none\n  | c :: cs\u2081, cs\u2082 =>\n    if cs\u2081 = cs\u2082 then some [c]\n    else\n      match extract_core cs\u2081 cs\u2082 with\n      | none => none\n      | some r => some (c :: r)\n#align string.iterator.extract_core String.Iterator.extractCore\n\n/- warning: string.iterator.extract -> String.Iterator.extract is a dubious translation:\nlean 3 declaration is\n  String.Iterator -> String.Iterator -> (Option.{0} String)\nbut is expected to have type\n  String.Iterator -> String.Iterator -> String\nCase conversion may be inaccurate. Consider using '#align string.iterator.extract String.Iterator.extract\u2093'. -/\ndef extract : Iterator \u2192 Iterator \u2192 Option String\n  | \u27e8p\u2081, n\u2081\u27e9, \u27e8p\u2082, n\u2082\u27e9 =>\n    if p\u2081.reverse ++ n\u2081 \u2260 p\u2082.reverse ++ n\u2082 then none\n    else\n      if n\u2081 = n\u2082 then some \"\"\n      else\n        match Iterator.extractCore n\u2081 n\u2082 with\n        | none => none\n        | some r => some \u27e8r\u27e9\n#align string.iterator.extract String.Iterator.extract\n\nend Iterator\n\nend String\n\n/-! The following definitions do not have builtin support in the VM -/\n\n\ninstance : Inhabited String :=\n  \u27e8String.empty\u27e9\n\ninstance : SizeOf String :=\n  \u27e8String.length\u27e9\n\ninstance : Append String :=\n  \u27e8String.append\u27e9\n\nnamespace String\n\n#print String.str /-\ndef str : String \u2192 Char \u2192 String :=\n  push\n#align string.str String.str\n-/\n\n#print String.isEmpty /-\ndef isEmpty (s : String) : Bool :=\n  decide (s.length = 0)\n#align string.is_empty String.isEmpty\n-/\n\n#print String.front /-\ndef front (s : String) : Char :=\n  s.mkIterator.curr\n#align string.front String.front\n-/\n\n#print String.back /-\ndef back (s : String) : Char :=\n  s.mkIterator.toEnd.prev.curr\n#align string.back String.back\n-/\n\n#print String.join /-\ndef join (l : List String) : String :=\n  l.foldl (fun r s => r ++ s) \"\"\n#align string.join String.join\n-/\n\n#print String.singleton /-\ndef singleton (c : Char) : String :=\n  empty.push c\n#align string.singleton String.singleton\n-/\n\n#print String.intercalate /-\ndef intercalate (s : String) (ss : List String) : String :=\n  (List.intercalate s.toList (ss.map toList)).asString\n#align string.intercalate String.intercalate\n-/\n\nnamespace Iterator\n\n#print String.Iterator.nextn /-\ndef nextn : Iterator \u2192 Nat \u2192 Iterator\n  | it, 0 => it\n  | it, i + 1 => nextn it.next i\n#align string.iterator.nextn String.Iterator.nextn\n-/\n\n#print String.Iterator.prevn /-\ndef prevn : Iterator \u2192 Nat \u2192 Iterator\n  | it, 0 => it\n  | it, i + 1 => prevn it.prev i\n#align string.iterator.prevn String.Iterator.prevn\n-/\n\nend Iterator\n\ndef popBack (s : String) : String :=\n  s.mkIterator.toEnd.prev.prevToString\n#align string.pop_back String.popBack\n\ndef popnBack (s : String) (n : Nat) : String :=\n  (s.mkIterator.toEnd.prevn n).prevToString\n#align string.popn_back String.popnBack\n\ndef backn (s : String) (n : Nat) : String :=\n  (s.mkIterator.toEnd.prevn n).nextToString\n#align string.backn String.backn\n\nend String\n\n#print Char.toString /-\nprotected def Char.toString (c : Char) : String :=\n  String.singleton c\n#align char.to_string Char.toString\n-/\n\nprivate def to_nat_core : String.Iterator \u2192 Nat \u2192 Nat \u2192 Nat\n  | it, 0, r => r\n  | it, i + 1, r =>\n    let c := it.curr\n    let r := r * 10 + c.toNat - '0'.toNat\n    to_nat_core it.next i r\n#align to_nat_core to_nat_core\n\ndef String.toNat (s : String) : Nat :=\n  toNatCore s.mkIterator s.length 0\n#align string.to_nat String.toNat\n\nnamespace String\n\nprivate theorem nil_ne_append_singleton : \u2200 (c : Char) (l : List Char), [] \u2260 l ++ [c]\n  | c, [] => fun h => List.noConfusion h\n  | c, d :: l => fun h => List.noConfusion h\n#align string.nil_ne_append_singleton string.nil_ne_append_singleton\n\ntheorem empty_ne_str : \u2200 (c : Char) (s : String), empty \u2260 str s c\n  | c, \u27e8l\u27e9 => fun h : StringImp.mk [] = StringImp.mk (l ++ [c]) =>\n    StringImp.noConfusion h fun h => nil_ne_append_singleton _ _ h\n#align string.empty_ne_str String.empty_ne_str\n\ntheorem str_ne_empty (c : Char) (s : String) : str s c \u2260 empty :=\n  (empty_ne_str c s).symm\n#align string.str_ne_empty String.str_ne_empty\n\nprivate theorem str_ne_str_left_aux :\n    \u2200 {c\u2081 c\u2082 : Char} (l\u2081 l\u2082 : List Char), c\u2081 \u2260 c\u2082 \u2192 l\u2081 ++ [c\u2081] \u2260 l\u2082 ++ [c\u2082]\n  | c\u2081, c\u2082, [], [], h\u2081, h\u2082 => List.noConfusion h\u2082 fun h _ => absurd h h\u2081\n  | c\u2081, c\u2082, d\u2081 :: l\u2081, [], h\u2081, h\u2082 =>\n    have : d\u2081 :: (l\u2081 ++ [c\u2081]) = [c\u2082] := h\u2082\n    have : l\u2081 ++ [c\u2081] = [] := List.noConfusion this fun _ h => h\n    absurd this.symm (nil_ne_append_singleton _ _)\n  | c\u2081, c\u2082, [], d\u2082 :: l\u2082, h\u2081, h\u2082 =>\n    have : [c\u2081] = d\u2082 :: (l\u2082 ++ [c\u2082]) := h\u2082\n    have : [] = l\u2082 ++ [c\u2082] := List.noConfusion this fun _ h => h\n    absurd this (nil_ne_append_singleton _ _)\n  | c\u2081, c\u2082, d\u2081 :: l\u2081, d\u2082 :: l\u2082, h\u2081, h\u2082 =>\n    have : d\u2081 :: (l\u2081 ++ [c\u2081]) = d\u2082 :: (l\u2082 ++ [c\u2082]) := h\u2082\n    have : l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082] := List.noConfusion this fun _ h => h\n    absurd this (str_ne_str_left_aux l\u2081 l\u2082 h\u2081)\n#align string.str_ne_str_left_aux string.str_ne_str_left_aux\n\ntheorem str_ne_str_left : \u2200 {c\u2081 c\u2082 : Char} (s\u2081 s\u2082 : String), c\u2081 \u2260 c\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082\n  | c\u2081, c\u2082, StringImp.mk l\u2081, StringImp.mk l\u2082, h\u2081, h\u2082 =>\n    have : l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082] := StringImp.noConfusion h\u2082 id\n    absurd this (str_ne_str_left_aux l\u2081 l\u2082 h\u2081)\n#align string.str_ne_str_left String.str_ne_str_left\n\nprivate theorem str_ne_str_right_aux :\n    \u2200 (c\u2081 c\u2082 : Char) {l\u2081 l\u2082 : List Char}, l\u2081 \u2260 l\u2082 \u2192 l\u2081 ++ [c\u2081] \u2260 l\u2082 ++ [c\u2082]\n  | c\u2081, c\u2082, [], [], h\u2081, h\u2082 => absurd rfl h\u2081\n  | c\u2081, c\u2082, d\u2081 :: l\u2081, [], h\u2081, h\u2082 =>\n    have : d\u2081 :: (l\u2081 ++ [c\u2081]) = [c\u2082] := h\u2082\n    have : l\u2081 ++ [c\u2081] = [] := List.noConfusion this fun _ h => h\n    absurd this.symm (nil_ne_append_singleton _ _)\n  | c\u2081, c\u2082, [], d\u2082 :: l\u2082, h\u2081, h\u2082 =>\n    have : [c\u2081] = d\u2082 :: (l\u2082 ++ [c\u2082]) := h\u2082\n    have : [] = l\u2082 ++ [c\u2082] := List.noConfusion this fun _ h => h\n    absurd this (nil_ne_append_singleton _ _)\n  | c\u2081, c\u2082, d\u2081 :: l\u2081, d\u2082 :: l\u2082, h\u2081, h\u2082 =>\n    have aux\u2081 : d\u2081 :: (l\u2081 ++ [c\u2081]) = d\u2082 :: (l\u2082 ++ [c\u2082]) := h\u2082\n    have : d\u2081 = d\u2082 := List.noConfusion aux\u2081 fun h _ => h\n    have aux\u2082 : l\u2081 \u2260 l\u2082 := fun h =>\n      have : d\u2081 :: l\u2081 = d\u2082 :: l\u2082 := Eq.subst h (Eq.subst this rfl)\n      absurd this h\u2081\n    have : l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082] := List.noConfusion aux\u2081 fun _ h => h\n    absurd this (str_ne_str_right_aux c\u2081 c\u2082 aux\u2082)\n#align string.str_ne_str_right_aux string.str_ne_str_right_aux\n\ntheorem str_ne_str_right : \u2200 (c\u2081 c\u2082 : Char) {s\u2081 s\u2082 : String}, s\u2081 \u2260 s\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082\n  | c\u2081, c\u2082, StringImp.mk l\u2081, StringImp.mk l\u2082, h\u2081, h\u2082 =>\n    have aux : l\u2081 \u2260 l\u2082 := fun h =>\n      have : StringImp.mk l\u2081 = StringImp.mk l\u2082 := Eq.subst h rfl\n      absurd this h\u2081\n    have : l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082] := StringImp.noConfusion h\u2082 id\n    absurd this (str_ne_str_right_aux c\u2081 c\u2082 aux)\n#align string.str_ne_str_right String.str_ne_str_right\n\nend String\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/Data/String/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.07585817688736327, "lm_q1q2_score": 0.021829541870492127}}
{"text": "/-\nCopyright (c) 2019-2022 by Microsoft Corporation and the authors listed in the file AUTHORS\nand their institutional affiliations. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Wojciech Nawrocki\n-/\nimport Lean.ToExpr\nimport Lean.AuxRecursor\nimport Lean.ProjFns\nimport Lean.Structure\nimport Lean.Util.Recognizers\nimport Lean.Meta.WHNF\nimport Lean.Meta.Basic\nimport Lean.Meta.GetConst\nimport Lean.Meta.Match.MatcherInfo\nimport Lean.Meta.Match.MatchPatternAttr\nimport Lean.Meta.FunInfo\nimport Lean.Util.MonadCache\n\nimport Smt.Tactic.WHNFConfigurableRef\n\nnamespace Lean.Meta\n\n/-- Use a fresh name if this one is already in the local context. While Lean seems to handle\nshadowing correctly, external tools don't always do so. -/\ndef bumpNameIfUsed (nm : Name) : MetaM Name :=\n  return (\u2190 getLCtx).getUnusedName nm\n\npartial def letTelescopeAbstractingAux (fvars : Array Expr) (abs : Expr \u2192 MetaM Expr)\n    (k : Array Expr \u2192 Expr \u2192 (Expr \u2192 MetaM Expr) \u2192 MetaM \u03b1)\n    : Expr \u2192 MetaM \u03b1\n  | Expr.letE nm t v b nonDep => do\n    let nm \u2190 bumpNameIfUsed nm\n    withLocalDeclD nm t fun x =>\n      letTelescopeAbstractingAux\n        (fvars.push x)\n        (fun e' => abs (Expr.letE nm t v (e'.abstract #[x]) nonDep))\n        k\n        (b.instantiate1 x)\n  | Expr.mdata md e@(Expr.letE ..) =>\n    letTelescopeAbstractingAux fvars (fun e' => abs (Expr.mdata md e')) k e\n  | e => k fvars e abs\n\n@[inline] def map3MetaM [MonadControlT MetaM m] [Monad m]\n    (f : forall {\u03b1}, (\u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1)\n    {\u03b1} (k : \u03b2 \u2192 \u03b3 \u2192 \u03b4 \u2192 m \u03b1)\n    : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b c d => runInBase <| k b c d\n\n/-- Like `lambdaTelescope` but just for `let` bindings, and the continuation is given an abstraction\nfunction which it can use to reintroduce all the surrounding `let` bindings. The `let` bindings are\ndefined as `cdecl`s, i.e. their values are not exposed in the local context.\n\nUnlike `lambdaTelescope` followed by `mkLetFVars`, this preserves `mdata` stored on `let` bindings. -/\ndef letTelescopeAbstracting [MonadControlT MetaM n] [Monad n] {\u03b1 : Type} (e : Expr)\n    (k : Array Expr \u2192 Expr \u2192 (Expr \u2192 MetaM Expr) \u2192 n \u03b1) : n \u03b1 :=\n  map3MetaM (fun k => letTelescopeAbstractingAux #[] pure k e) k\n\nend Lean.Meta\n\nnamespace Smt\n\nopen Lean Meta\n\n/- ===========================\n   Smart unfolding support\n   =========================== -/\n\ndef smartUnfoldingSuffix := \"_sunfold\"\n\n@[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name :=\n  Name.mkStr declName smartUnfoldingSuffix\n\ndef hasSmartUnfoldingDecl (env : Environment) (declName : Name) : Bool :=\n  env.contains (mkSmartUnfoldingNameFor declName)\n\n/-- Add auxiliary annotation to indicate the `match`-expression `e` must be reduced when performing smart unfolding. -/\ndef markSmartUnfoldingMatch (e : Expr) : Expr :=\n  mkAnnotation `sunfoldMatch e\n\ndef smartUnfoldingMatch? (e : Expr) : Option Expr :=\n  annotation? `sunfoldMatch e\n\n/-- Add auxiliary annotation to indicate expression `e` (a `match` alternative rhs) was successfully reduced by smart unfolding. -/\ndef markSmartUnfoldingMatchAlt (e : Expr) : Expr :=\n  mkAnnotation `sunfoldMatchAlt e\n\ndef smartUnfoldingMatchAlt? (e : Expr) : Option Expr :=\n  annotation? `sunfoldMatchAlt e\n\n/- ===========================\n   Helper methods\n   =========================== -/\ndef isAuxDef (constName : Name) : MetaM Bool := do\n  let env \u2190 getEnv\n  return isAuxRecursor env constName || isNoConfusion env constName\n\n@[inline] private def matchConstAux {\u03b1} (e : Expr) (failK : Unit \u2192 ReductionM \u03b1) (k : ConstantInfo \u2192 List Level \u2192 ReductionM \u03b1) : ReductionM \u03b1 :=\n  match e with\n  | Expr.const name lvls => do\n    let (some cinfo) \u2190 getConst? name | failK ()\n    k cinfo lvls\n  | _ => failK ()\n\n/- ===========================\n   Helper functions for reducing recursors\n   =========================== -/\n\nprivate def getFirstCtor (d : Name) : MetaM (Option Name) := do\n  let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) \u2190 getConstNoEx? d | pure none\n  return some ctor\n\nprivate def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do\n  match type.getAppFn with\n  | Expr.const d lvls =>\n    let (some ctor) \u2190 getFirstCtor d | pure none\n    return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams)\n  | _ =>\n    return none\n\ndef toCtorIfLit : Expr \u2192 Expr\n  | Expr.lit (Literal.natVal v) =>\n    if v == 0 then mkConst `Nat.zero\n    else mkApp (mkConst `Nat.succ) (mkRawNatLit (v-1))\n  | Expr.lit (Literal.strVal v) =>\n    mkApp (mkConst `String.mk) (toExpr v.toList)\n  | e => e\n\nprivate def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule :=\n  match major.getAppFn with\n  | Expr.const fn _ => recVal.rules.find? fun r => r.ctor == fn\n  | _               => none\n\nprivate def toCtorWhenK (recVal : RecursorVal) (major : Expr) : ReductionM Expr := do\n  let majorType \u2190 inferType major\n  let majorType \u2190 instantiateMVars (\u2190 whnf majorType)\n  let majorTypeI := majorType.getAppFn\n  if !majorTypeI.isConstOf recVal.getInduct then\n    return major\n  else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then\n    return major\n  else do\n    let (some newCtorApp) \u2190 mkNullaryCtor majorType recVal.numParams | pure major\n    let newType \u2190 inferType newCtorApp\n    /- TODO: check whether changing reducibility to default hurts performance here.\n       We do that to make sure auxiliary `Eq.rec` introduced by the `match`-compiler\n       are reduced even when `TransparencyMode.reducible` (like in `simp`).\n\n       We use `withNewMCtxDepth` to make sure metavariables at `majorType` are not assigned.\n       For example, given `major : Eq ?x y`, we don't want to apply K by assigning `?x := y`.\n    -/\n    if (\u2190 withAtLeastTransparency TransparencyMode.default <| withNewMCtxDepth <| isDefEq majorType newType) then\n      return newCtorApp\n    else\n      return major\n\n/--\n  Create the `i`th projection `major`. It tries to use the auto-generated projection functions if available. Otherwise falls back\n  to `Expr.proj`.\n-/\ndef mkProjFn (ctorVal : ConstructorVal) (us : List Level) (params : Array Expr) (i : Nat) (major : Expr) : CoreM Expr := do\n  match getStructureInfo? (\u2190 getEnv) ctorVal.induct with\n  | none => return mkProj ctorVal.induct i major\n  | some info => match info.getProjFn? i with\n    | none => return mkProj ctorVal.induct i major\n    | some projFn => return mkApp (mkAppN (mkConst projFn us) params) major\n\n/--\n  If `major` is not a constructor application, and its type is a structure `C ...`, then return `C.mk major.1 ... major.n`\n\n  \\pre `inductName` is `C`.\n\n  If `Meta.Config.etaStruct` is `false` or the condition above does not hold, this method just returns `major`. -/\nprivate def toCtorWhenStructure (inductName : Name) (major : Expr) : ReductionM Expr := do\n  unless (\u2190 useEtaStruct inductName) do\n    return major\n  let env \u2190 getEnv\n  if !isStructureLike env inductName then\n    return major\n  else if let some _ := major.isConstructorApp? env then\n    return major\n  else\n    let majorType \u2190 inferType major\n    let majorType \u2190 instantiateMVars (\u2190 whnf majorType)\n    let majorTypeI := majorType.getAppFn\n    if !majorTypeI.isConstOf inductName then\n      return major\n    match majorType.getAppFn with\n    | Expr.const d us =>\n      if (\u2190 whnfD (\u2190 inferType majorType)) == mkSort levelZero then\n        return major -- We do not perform eta for propositions, see implementation in the kernel\n      else\n        let some ctorName \u2190 getFirstCtor d | pure major\n        let ctorInfo \u2190 getConstInfoCtor ctorName\n        let params := majorType.getAppArgs.shrink ctorInfo.numParams\n        let mut result := mkAppN (mkConst ctorName us) params\n        for i in [:ctorInfo.numFields] do\n          result := mkApp result (\u2190 mkProjFn ctorInfo us params i major)\n        return result\n    | _ => return major\n\n/-- Auxiliary function for reducing recursor applications. -/\nprivate def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr)\n    (failK : Unit \u2192 ReductionM \u03b1) (successK : Expr \u2192 ReductionM \u03b1)\n    : ReductionM \u03b1 := do\n  let majorIdx := recVal.getMajorIdx\n  trace[Smt.reduce.rec] \"{recVal.name} with args (#{majorIdx} major){indentD recArgs}\"\n  if h : majorIdx < recArgs.size then\n    let cont (major : Expr) : ReductionM (Option Expr) := do\n      let mut major := major\n      if recVal.k then\n        major \u2190 toCtorWhenK recVal major\n      major := toCtorIfLit major\n      major \u2190 toCtorWhenStructure recVal.getInduct major\n      let some rule := getRecRuleFor recVal major | return none\n      let majorArgs := major.getAppArgs\n      guard (recLvls.length == recVal.levelParams.length)\n      let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls\n      -- Apply parameters, motives and minor premises from recursor application.\n      let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs\n      /- The number of parameters in the constructor is not necessarily\n        equal to the number of parameters in the recursor when we have\n        nested inductive types. -/\n      let nparams := majorArgs.size - rule.nfields\n      let rhs := mkAppRange rhs nparams majorArgs.size majorArgs\n      let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs\n      return rhs\n\n    let cont' : Option Expr \u2192 ReductionM \u03b1\n      | some res => do\n        trace[Smt.reduce.rec] \"\u2933 {res}\"\n        successK res\n      | none => do\n        trace[Smt.reduce.rec] \"failed.\"\n        failK ()\n\n    let major \u2190 whnf <| recArgs.get \u27e8majorIdx, h\u27e9\n    if (\u2190 read).letPushElim then\n      letTelescopeAbstracting major fun _ major abs => do\n        let e' \u2190 cont major\n        let e' \u2190 e'.mapM fun e => abs e\n        cont' e'\n    else\n      cont' (\u2190 cont major)\n  else\n    failK ()\n\n/- ===========================\n   Helper functions for reducing Quot.lift and Quot.ind\n   =========================== -/\n\n/-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/\nprivate def reduceQuotRec (recVal  : QuotVal) (recLvls : List Level) (recArgs : Array Expr)\n    (failK : Unit \u2192 ReductionM \u03b1) (successK : Expr \u2192 ReductionM \u03b1)\n    : ReductionM \u03b1 :=\n  let process (majorPos argPos : Nat) : ReductionM \u03b1 :=\n    if h : majorPos < recArgs.size then do\n      let major := recArgs.get \u27e8majorPos, h\u27e9\n      let major \u2190 whnf major\n      match major with\n      | Expr.app (Expr.app (Expr.app (Expr.const majorFn _) _) _) majorArg => do\n        let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) \u2190 getConstNoEx? majorFn | failK ()\n        let f := recArgs[argPos]!\n        let r := mkApp f majorArg\n        let recArity := majorPos + 1\n        successK <| mkAppRange r recArity recArgs.size recArgs\n      | _ => failK ()\n    else\n      failK ()\n  match recVal.kind with\n  | QuotKind.lift => process 5 3\n  | QuotKind.ind  => process 4 3\n  | _             => failK ()\n\n/- ===========================\n   Helper function for extracting \"stuck term\"\n   =========================== -/\n\nmutual\n  private partial def isRecStuck? (recVal : RecursorVal) (recArgs : Array Expr) : ReductionM (Option MVarId) :=\n    if recVal.k then\n      -- TODO: improve this case\n      return none\n    else do\n      let majorIdx := recVal.getMajorIdx\n      if h : majorIdx < recArgs.size then do\n        let major := recArgs.get \u27e8majorIdx, h\u27e9\n        let major \u2190 whnf major\n        getStuckMVar? major\n      else\n        return none\n\n  private partial def isQuotRecStuck? (recVal : QuotVal) (recArgs : Array Expr) : ReductionM (Option MVarId) :=\n    let process? (majorPos : Nat) : ReductionM (Option MVarId) :=\n      if h : majorPos < recArgs.size then do\n        let major := recArgs.get \u27e8majorPos, h\u27e9\n        let major \u2190 whnf major\n        getStuckMVar? major\n      else\n        return none\n    match recVal.kind with\n    | QuotKind.lift => process? 5\n    | QuotKind.ind  => process? 4\n    | _             => return none\n\n  /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/\n  partial def getStuckMVar? (e : Expr) : ReductionM (Option MVarId) := do\n    match e with\n    | Expr.mdata _ e  => getStuckMVar? e\n    | Expr.proj _ _ e => getStuckMVar? (\u2190 whnf e)\n    | Expr.mvar .. => do\n      let e \u2190 instantiateMVars e\n      match e with\n      | Expr.mvar mvarId => pure (some mvarId)\n      | _ => getStuckMVar? e\n    | Expr.app f .. =>\n      let f := f.getAppFn\n      match f with\n      | Expr.mvar mvarId   => return some mvarId\n      | Expr.const fName _ =>\n        let cinfo? \u2190 getConstNoEx? fName\n        match cinfo? with\n        | some $ ConstantInfo.recInfo recVal  => isRecStuck? recVal e.getAppArgs\n        | some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal e.getAppArgs\n        | _                                => return none\n      | Expr.proj _ _ e => getStuckMVar? (\u2190 whnf e)\n      | _ => return none\n    | _ => return none\nend\n\n/- ===========================\n   Weak Head Normal Form auxiliary combinators\n   =========================== -/\n\n/-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the \"hard\" cases as an argument -/\n@[specialize] partial def whnfEasyCases (e : Expr) (k : Expr \u2192 ReductionM Expr) : ReductionM Expr := do\n  match e with\n  | Expr.forallE ..    => return e\n  | Expr.lam ..        => return e\n  | Expr.sort ..       => return e\n  | Expr.lit ..        => return e\n  | Expr.bvar ..       => unreachable!\n  | Expr.letE ..       => k e\n  | Expr.const ..      => k e\n  | Expr.app ..        => k e\n  | Expr.proj ..       => k e\n  | Expr.mdata ..      => k e\n  | Expr.fvar fvarId   =>\n    let decl \u2190 fvarId.getDecl\n    match decl with\n    | LocalDecl.cdecl .. => return e\n    | LocalDecl.ldecl (value := v) (nonDep := nonDep) .. =>\n      let cfg \u2190 getConfig\n      if nonDep && !cfg.zetaNonDep then\n        return e\n      else\n        if cfg.trackZeta then\n          modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId }\n        whnfEasyCases v k\n  | Expr.mvar mvarId   =>\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some v => whnfEasyCases v k\n    | none   => return e\n\n@[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level)\n    (failK : Unit \u2192 MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  if c.levelParams.length != lvls.length then\n    failK ()\n  else\n    successK (\u2190 instantiateValueLevelParams c lvls)\n\n@[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr)\n    (failK : Unit \u2192 ReductionM \u03b1) (successK : Expr \u2192 ReductionM \u03b1) (preserveMData := false) : ReductionM \u03b1 := do\n  if c.levelParams.length != lvls.length then\n    failK ()\n  else\n    let val \u2190 instantiateValueLevelParams c lvls\n    let val := val.betaRev revArgs (preserveMData := preserveMData)\n    successK val\n\ninductive ReduceMatcherResult where\n  | reduced (val : Expr)\n  | stuck   (val : Expr)\n  | notMatcher\n  | partialApp\n\n/--\n  The \"match\" compiler uses `if-then-else` expressions and other auxiliary declarations to compile match-expressions such as\n  ```\n  match v with\n  | 'a' => 1\n  | 'b' => 2\n  | _   => 3\n  ```\n  because it is more efficient than using `casesOn` recursors.\n  The method `reduceMatcher?` fails if these auxiliary definitions (e.g., `ite`) cannot be unfolded in the current\n  transparency setting. This is problematic because tactics such as `simp` use `TransparencyMode.reducible`, and\n  most users assume that expressions such as\n  ```\n  match 0 with\n  | 0 => 1\n  | 100 => 2\n  | _ => 3\n  ```\n  should reduce in any transparency mode.\n  Thus, we define a custom `canUnfoldAtMatcher` predicate for `whnfMatcher`.\n\n  This solution is not very modular because modications at the `match` compiler require changes here.\n  We claim this is defensible because it is reducing the auxiliary declaration defined by the `match` compiler.\n\n  Alternative solution: tactics that use `TransparencyMode.reducible` should rely on the equations we generated for match-expressions.\n  This solution is also not perfect because the match-expression above will not reduce during type checking when we are not using\n  `TransparencyMode.default` or `TransparencyMode.all`.\n-/\ndef canUnfoldAtMatcher\n    (prevUnfoldAt? : Option (Meta.Config \u2192 ConstantInfo \u2192 CoreM Bool))\n    (cfg : Meta.Config) (info : ConstantInfo) : CoreM Bool := do\n  if let some prevUnfoldAt := prevUnfoldAt? then\n    prevUnfoldAt cfg info\n  else match cfg.transparency with\n  | TransparencyMode.all     => return true\n  | TransparencyMode.default => return true\n  | _ =>\n    if (\u2190 isReducible info.name) || isGlobalInstance (\u2190 getEnv) info.name then\n      return true\n    else if hasMatchPatternAttribute (\u2190 getEnv) info.name then\n      return true\n    else\n      return info.name == ``ite\n       || info.name == ``dite\n       || info.name == ``decEq\n       || info.name == ``Nat.decEq\n       || info.name == ``Char.ofNat   || info.name == ``Char.ofNatAux\n       || info.name == ``String.decEq || info.name == ``List.hasDecEq\n       || info.name == ``Fin.ofNat\n       || info.name == ``UInt8.ofNat  || info.name == ``UInt8.decEq\n       || info.name == ``UInt16.ofNat || info.name == ``UInt16.decEq\n       || info.name == ``UInt32.ofNat || info.name == ``UInt32.decEq\n       || info.name == ``UInt64.ofNat || info.name == ``UInt64.decEq\n       /- Remark: we need to unfold the following two definitions because they are used for `Fin`, and\n          lazy unfolding at `isDefEq` does not unfold projections.  -/\n       || info.name == ``HMod.hMod || info.name == ``Mod.mod\n\nprivate def whnfMatcher (e : Expr) : ReductionM Expr := do\n  /- When reducing `match` expressions, if the reducibility setting is at `TransparencyMode.reducible`,\n     we increase it to `TransparencyMode.instance`. We use the `TransparencyMode.reducible` in many places (e.g., `simp`),\n     and this setting prevents us from reducing `match` expressions where the discriminants are terms such as `OfNat.ofNat \u03b1 n inst`.\n     For example, `simp [Int.div]` will not unfold the application `Int.div 2 1` occuring in the target.\n\n     TODO: consider other solutions; investigate whether the solution above produces counterintuitive behavior.  -/\n  let mut transparency \u2190 getTransparency\n  if transparency == TransparencyMode.reducible then\n    transparency := TransparencyMode.instances\n  withTransparency transparency <|\n    withTheReader Meta.Context (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher ctx.canUnfold? }) do\n      whnf e\n\ndef reduceMatcher? (e : Expr) : ReductionM ReduceMatcherResult := do\n  trace[Smt.reduce.matcher] \"{e}\"\n  match e.getAppFn with\n  | Expr.const declName declLevels =>\n    let some info \u2190 getMatcherInfo? declName\n      | do\n        trace[Smt.reduce.matcher] \"not a matcher.\"\n        return ReduceMatcherResult.notMatcher\n    let args := e.getAppArgs\n    let prefixSz := info.numParams + 1 + info.numDiscrs\n    if args.size < prefixSz + info.numAlts then\n      trace[Smt.reduce.matcher] \"partial app.\"\n      return ReduceMatcherResult.partialApp\n    else\n      let constInfo \u2190 getConstInfo declName\n      let f \u2190 instantiateValueLevelParams constInfo declLevels\n      let auxApp := mkAppN f args[0:prefixSz]\n      let auxAppType \u2190 inferType auxApp\n      forallBoundedTelescope auxAppType info.numAlts fun hs _ => do\n        let auxApp \u2190 whnfMatcher (mkAppN auxApp hs)\n\n        let cont (auxApp : Expr) : ReductionM ReduceMatcherResult := do\n          let auxAppFn := auxApp.getAppFn\n          let mut i := prefixSz\n          for h in hs do\n            if auxAppFn == h then\n              let result := mkAppN args[i]! auxApp.getAppArgs\n              let result := mkAppN result args[prefixSz + info.numAlts:args.size]\n              let res := result.headBeta\n              trace[Smt.reduce.matcher] \"\u2933 {res}\"\n              return ReduceMatcherResult.reduced res\n            i := i + 1\n          trace[Smt.reduce.matcher] \"stuck at {auxApp}\"\n          return ReduceMatcherResult.stuck auxApp\n\n        if (\u2190 read).letPushElim then\n          letTelescopeAbstracting auxApp fun _ auxApp abs => do\n            match \u2190 cont auxApp with\n            | .reduced e => return .reduced (\u2190 abs e)\n            | .stuck e   => return .stuck (\u2190 abs e)\n            | res        => return res\n        else cont auxApp\n  | _ => do\n    trace[Smt.reduce.matcher] \"not a matcher.\"\n    return ReduceMatcherResult.notMatcher\n\nprivate def projectCore? (e : Expr) (i : Nat) : MetaM (Option Expr) := do\n  let e := toCtorIfLit e\n  matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ =>\n    let numArgs := e.getAppNumArgs\n    let idx := ctorVal.numParams + i\n    if idx < numArgs then\n      return some (e.getArg! idx)\n    else\n      return none\n\ndef project? (e : Expr) (i : Nat) : ReductionM (Option Expr) := do\n  projectCore? (\u2190 whnf e) i\n\n/-- Reduce kernel projection `Expr.proj ..` expression. -/\ndef reduceProj? (e : Expr) : ReductionM (Option Expr) := do\n  match e with\n  | Expr.proj _ i c => project? c i\n  | _               => return none\n\n/--\n  Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned.\n  Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been \"filled\".\n-/\nprivate def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do\n  if f'.isMVar then\n    match (\u2190 getDelayedMVarAssignment? f'.mvarId!) with\n    | none => return none\n    | some { fvars, mvarIdPending } =>\n      let args := e.getAppArgs\n      if fvars.size > args.size then\n        -- Insufficient number of argument to expand delayed assignment\n        return none\n      else\n        let newVal \u2190 instantiateMVars (mkMVar mvarIdPending)\n        if newVal.hasExprMVar then\n           -- Delayed assignment still contains metavariables\n           return none\n        else\n           let newVal := newVal.abstract fvars\n           let result := newVal.instantiateRevRange 0 fvars.size args\n           return mkAppRange result fvars.size args.size args\n  else\n    return none\n\ndef traceReduce [Monad m] (e : Expr) (e' : Except \u03b5 Expr) : m MessageData :=\n  return m!\"{e} \u2933 \" ++ match e' with\n    | .ok e'   => m!\"{e'}\"\n    | .error _ => m!\"{bombEmoji}\"\n\n/--\n  Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction,\n  expand let-expressions, expand assigned meta-variables.\n\n  The parameter `deltaAtProj` controls how to reduce projections `s.i`. If `deltaAtProj == true`,\n  then delta reduction is used to reduce `s` (i.e., `whnf` is used), otherwise `whnfCore`.\n  We only set this flag to `false` when implementing `isDefEq`.\n-/\npartial def whnfCore (e : Expr) (deltaAtProj : Bool := true) : ReductionM Expr :=\n  go e\nwhere\n  go (e : Expr) : ReductionM Expr := withTraceNode `Smt.reduce.whnfCore (traceReduce e \u00b7) <| do\n    whnfEasyCases e fun e => do\n      match e with\n      | Expr.const ..  => pure e\n      | Expr.letE _ _ v b _ => do\n        -- NOTE(WN): Should core Lean do a `zetaNonDep` check here?\n        if (\u2190 readThe Smt.Config).zeta then go <| b.instantiate1 v\n        else return e\n      | Expr.app f ..       =>\n        let f := f.getAppFn\n        let f \u2190 go f\n        -- NOTE(WN): We make a significant change to the evaluation order by not only WHNFing\n        -- arguments eagerly, CBV-style, but also doing so with the full procedure rather than\n        -- just `whnfCore` (so that a lack of delta-unfolding does not block let-lifting).\n        let revArgs \u2190 e.getAppRevArgs.mapM whnf\n\n        let mut k (f : Expr) (revArgs : Array Expr) : ReductionM Expr := do\n          let e := mkAppRev f revArgs\n          if f.isLambda then\n            go <| f.betaRev revArgs\n          else if let some eNew \u2190 whnfDelayedAssigned? f e then\n            go eNew\n          else\n            -- Is this just an optimization?\n            -- let e := if f == f' then e else e.updateFn f'\n            match (\u2190 reduceMatcher? e) with\n            | ReduceMatcherResult.reduced eNew => go eNew\n            | ReduceMatcherResult.partialApp   => pure e\n            | ReduceMatcherResult.stuck _      => pure e\n            | ReduceMatcherResult.notMatcher   =>\n              matchConstAux f (fun _ => return e) fun cinfo lvls =>\n                match cinfo with\n                | ConstantInfo.recInfo rec    => reduceRec rec lvls revArgs.reverse (fun _ => return e) go\n                | ConstantInfo.quotInfo rec   => reduceQuotRec rec lvls revArgs.reverse (fun _ => return e) go\n                | c@(ConstantInfo.defnInfo _) => do\n                  if (\u2190 isAuxDef c.name) then\n                    deltaBetaDefinition c lvls revArgs (fun _ => return e) go\n                  else\n                    return e\n                | _ => return e\n\n        if (\u2190 read).letPushElim then\n          for arg in revArgs.reverse do\n            k := fun f acc => do\n              letTelescopeAbstracting arg fun _ arg absFn => do\n                let res \u2190 k f (acc.push arg)\n                absFn res\n\n          letTelescopeAbstracting f fun _ f absFn => do\n            let res \u2190 k f #[]\n            absFn res\n        else\n          k f revArgs\n\n      | Expr.proj pNm i c =>\n        let c \u2190 if deltaAtProj then whnf c else whnfCore c\n\n        if (\u2190 read).letPushElim then\n        -- if false then\n          letTelescopeAbstracting c fun _ c absFn => do\n            match (\u2190 projectCore? c i) with\n            | some e => absFn e\n            | none => absFn (Expr.proj pNm i c)\n        else match (\u2190 projectCore? c i) with\n        | some e => go e\n        | none => return e\n      | Expr.mdata md (Expr.letE nm t v b nonDep) =>\n        let zeta := md.getBool `zeta (\u2190 read).zeta\n        if zeta then go <| b.instantiate1 v\n        else\n          let t' \u2190 go t\n          let v' \u2190 go v\n          let nm \u2190 bumpNameIfUsed nm\n          let b' \u2190 withLocalDeclD nm t' fun x => do\n            let b' \u2190 go (b.instantiate1 x)\n            return b'.abstract #[x]\n          return Expr.mdata md (Expr.letE nm t' v' b' nonDep)\n      | Expr.mdata _ e => go e\n      | _ => unreachable!\n\n/--\n  Recall that `_sunfold` auxiliary definitions contains the markers: `markSmartUnfoldingMatch` (*) and `markSmartUnfoldingMatchAlt` (**).\n  For example, consider the following definition\n  ```\n  def r (i j : Nat) : Nat :=\n    i +\n      match j with\n      | Nat.zero => 1\n      | Nat.succ j =>\n        i + match j with\n            | Nat.zero => 2\n            | Nat.succ j => r i j\n  ```\n  produces the following `_sunfold` auxiliary definition with the markers\n  ```\n  def r._sunfold (i j : Nat) : Nat :=\n    i +\n      (*) match j with\n      | Nat.zero => (**) 1\n      | Nat.succ j =>\n        i + (*) match j with\n            | Nat.zero => (**) 2\n            | Nat.succ j => (**) r i j\n  ```\n\n  `match` expressions marked with `markSmartUnfoldingMatch` (*) must be reduced, otherwise the resulting term is not definitionally\n   equal to the given expression. The recursion may be interrupted as soon as the annotation `markSmartUnfoldingAlt` (**) is reached.\n\n  For example, the term `r i j.succ.succ` reduces to the definitionally equal term `i + i * r i j`\n-/\npartial def smartUnfoldingReduce? (e : Expr) : ReductionM (Option Expr) := do\n  trace[Smt.reduce.smartUnfoldingReduce] \"{e}\"\n  match \u2190 go e |>.run with\n  | some e' => \n    trace[Smt.reduce.smartUnfoldingReduce] \"\u2933 {e'}\"\n    return some e'\n  | none =>\n    trace[Smt.reduce.smartUnfoldingReduce] \"failed.\"\n    return none\n\nwhere\n  go (e : Expr) : OptionT ReductionM Expr := do\n    match e with\n    | Expr.letE n t v b _ => withLetDecl n t (\u2190 go v) fun x => do mkLetFVars #[x] (\u2190 go (b.instantiate1 x))\n    | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (\u2190 go b)\n    | Expr.app f a .. => return mkApp (\u2190 go f) (\u2190 go a)\n    | Expr.proj _ _ s => return e.updateProj! (\u2190 go s)\n    | Expr.mdata _ b  =>\n      if let some m := smartUnfoldingMatch? e then\n        goMatch m\n      else\n        return e.updateMData! (\u2190 go b)\n    | _ => return e\n\n  goMatch (e : Expr) : OptionT ReductionM Expr := do\n    match (\u2190 reduceMatcher? e) with\n    | ReduceMatcherResult.reduced e =>\n      if let some alt := smartUnfoldingMatchAlt? e then\n        return alt\n      else\n        go e\n    | ReduceMatcherResult.stuck e' =>\n      let mvarId \u2190 getStuckMVar? e'\n      /- Try to \"unstuck\" by resolving pending TC problems -/\n      if (\u2190 Meta.synthPending mvarId) then\n        goMatch e\n      else\n        failure\n    | _ => failure\n\ndef shouldUnfold (ci : ConstantInfo) : ReductionM Bool := do\n  let some canUnfold := (\u2190 readThe Meta.Context).canUnfold? | return true\n  let cfg := (\u2190 readThe Meta.Context).config\n  canUnfold cfg ci\n\nmutual\n\n  /--\n    Auxiliary method for unfolding a class projection.\n  -/\n  partial def unfoldProjInst? (e : Expr) : ReductionM (Option Expr) := do\n    match e.getAppFn with\n    | Expr.const declName .. =>\n      match (\u2190 getProjectionFnInfo? declName) with\n      | some { fromClass := true, .. } =>\n        match (\u2190 withDefault <| unfoldDefinition? e) with\n        | none   => return none\n        | some e =>\n          match (\u2190 withReducibleAndInstances <| reduceProj? e.getAppFn) with\n          | none   => return none\n          | some r => return mkAppN r e.getAppArgs |>.headBeta\n      | _ => return none\n    | _ => return none\n\n  /--\n    Auxiliary method for unfolding a class projection. when transparency is set to `TransparencyMode.instances`.\n    Recall that class instance projections are not marked with `[reducible]` because we want them to be\n    in \"reducible canonical form\".\n  -/\n  partial def unfoldProjInstWhenIntances? (e : Expr) : ReductionM (Option Expr) := do\n    if (\u2190 getTransparency) != TransparencyMode.instances then\n      return none\n    else\n      unfoldProjInst? e\n\n  /-- Unfold definition using \"smart unfolding\" if possible. -/\n  partial def unfoldDefinition? (e : Expr) : ReductionM (Option Expr) :=\n    match e with\n    | Expr.app f _ =>\n      matchConstAux f.getAppFn (fun _ => unfoldProjInstWhenIntances? e) fun fInfo fLvls => do\n        -- NOTE(WN): this not being checked might be a Lean bug\n        unless \u2190 shouldUnfold fInfo do return none\n        if fInfo.levelParams.length != fLvls.length then\n          return none\n        else\n          let unfoldDefault (_ : Unit) : ReductionM (Option Expr) :=\n            if fInfo.hasValue then\n              deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))\n            else\n              return none\n          if smartUnfolding.get (\u2190 getOptions) then\n            match ((\u2190 getEnv).find? (mkSmartUnfoldingNameFor fInfo.name)) with\n            | some fAuxInfo@(ConstantInfo.defnInfo _) =>\n              -- We use `preserveMData := true` to make sure the smart unfolding annotation are not erased in an over-application.\n              deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (preserveMData := true) (fun _ => pure none) fun e\u2081 => do\n                let some r \u2190 smartUnfoldingReduce? e\u2081 | return none\n                /-\n                  If `smartUnfoldingReduce?` succeeds, we should still check whether the argument the\n                  structural recursion is recursing on reduces to a constructor.\n                  This extra check is necessary in definitions (see issue #1081) such as\n                  ```\n                  inductive Vector (\u03b1 : Type u) : Nat \u2192 Type u where\n                    | nil  : Vector \u03b1 0\n                    | cons : \u03b1 \u2192 Vector \u03b1 n \u2192 Vector \u03b1 (n+1)\n\n                  def Vector.insert (a: \u03b1) (i : Fin (n+1)) (xs : Vector \u03b1 n) : Vector \u03b1 (n+1) :=\n                    match i, xs with\n                    | \u27e80,   _\u27e9,        xs => cons a xs\n                    | \u27e8i+1, h\u27e9, cons x xs => cons x (xs.insert a \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9)\n                  ```\n                  The structural recursion is being performed using the vector `xs`. That is, we used `Vector.brecOn` to define\n                  `Vector.insert`. Thus, an application `xs.insert a \u27e80, h\u27e9` is **not** definitionally equal to\n                  `Vector.cons a xs` because `xs` is not a constructor application (the `Vector.brecOn` application is blocked).\n\n                  Remark 1: performing structural recursion on `Fin (n+1)` is not an option here because it is a `Subtype` and\n                  and the repacking in recursive applications confuses the structural recursion module.\n\n                  Remark 2: the match expression reduces reduces to `cons a xs` when the discriminants are `\u27e80, h\u27e9` and `xs`.\n\n                  Remark 3: this check is unnecessary in most cases, but we don't need dependent elimination to trigger the issue\n                  fixed by this extra check. Here is another example that triggers the issue fixed by this check.\n                  ```\n                  def f : Nat \u2192 Nat \u2192 Nat\n                    | 0,   y   => y\n                    | x+1, y+1 => f (x-2) y\n                    | x+1, 0   => 0\n\n                  theorem ex : f 0 y = y := rfl\n                  ```\n\n                  Remark 4: the `return some r` in the following `let` is not a typo. Binport generated .olean files do not\n                  store the position of recursive arguments for definitions using structural recursion.\n                  Thus, we should keep `return some r` until Mathlib has been ported to Lean 3.\n                  Note that the `Vector` example above does not even work in Lean 3.\n                -/\n                let some recArgPos \u2190 getStructuralRecArgPos? fInfo.name | return some r\n                let numArgs := e.getAppNumArgs\n                if recArgPos >= numArgs then return none\n                let recArg := e.getArg! recArgPos numArgs\n                if !(\u2190 whnfMatcher recArg).isConstructorApp (\u2190 getEnv) then return none\n                return some r\n            | _ =>\n              if (\u2190 getMatcherInfo? fInfo.name).isSome then\n                -- Recall that `whnfCore` tries to reduce \"matcher\" applications.\n                return none\n              else\n                unfoldDefault ()\n          else\n            unfoldDefault ()\n    | Expr.const declName lvls => do\n      if smartUnfolding.get (\u2190 getOptions) && (\u2190 getEnv).contains (mkSmartUnfoldingNameFor declName) then\n        return none\n      else\n        let (some (cinfo@(ConstantInfo.defnInfo _))) \u2190 getConstNoEx? declName | pure none\n        deltaDefinition cinfo lvls\n          (fun _ => pure none)\n          (fun e => pure (some e))\n    | _ => return none\nend\n\ndef unfoldDefinition (e : Expr) : ReductionM Expr := do\n  let some e \u2190 unfoldDefinition? e | throwError \"failed to unfold definition{indentExpr e}\"\n  return e\n\n@[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr \u2192 ReductionM Bool) : ReductionM Expr :=\n  whnfEasyCases e fun e => do\n    let e \u2190 whnfCore e\n    if (\u2190 pred e) then\n        match (\u2190 unfoldDefinition? e) with\n        | some e => whnfHeadPred e pred\n        | none   => return e\n    else\n      return e\n\ndef whnfUntil (e : Expr) (declName : Name) : ReductionM (Option Expr) := do\n  let e \u2190 whnfHeadPred e (fun e => return !e.isAppOf declName)\n  if e.isAppOf declName then\n    return e\n  else\n    return none\n\n/-- Try to reduce matcher/recursor/quot applications. We say they are all \"morally\" recursor applications. -/\ndef reduceRecMatcher? (e : Expr) : ReductionM (Option Expr) := do\n  if !e.isApp then\n    return none\n  else match (\u2190 reduceMatcher? e) with\n    | ReduceMatcherResult.reduced e => return e\n    | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do\n      match cinfo with\n      | ConstantInfo.recInfo \u00abrec\u00bb  => reduceRec \u00abrec\u00bb lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e))\n      | ConstantInfo.quotInfo \u00abrec\u00bb => reduceQuotRec \u00abrec\u00bb lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e))\n      | c@(ConstantInfo.defnInfo _) =>\n        if (\u2190 isAuxDef c.name) then\n          deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))\n        else\n          return none\n      | _ => return none\n\ndef reduceNative? (e : Expr) : MetaM (Option Expr) :=\n  match e with\n  | Expr.app (Expr.const fName _) (Expr.const argName _) =>\n    if fName == ``Lean.reduceBool then do\n      return toExpr (\u2190 reduceBoolNative argName)\n    else if fName == ``Lean.reduceNat then do\n      return toExpr (\u2190 reduceNatNative argName)\n    else\n      return none\n  | _ =>\n    return none\n\n@[inline] def withNatValue {\u03b1} (a : Expr) (k : Nat \u2192 ReductionM (Option \u03b1)) : ReductionM (Option \u03b1) := do\n  let a \u2190 whnf a\n  match a with\n  | Expr.const `Nat.zero _      => k 0\n  | Expr.lit (Literal.natVal v) => k v\n  | _                           => return none\n\ndef reduceUnaryNatOp (f : Nat \u2192 Nat) (a : Expr) : ReductionM (Option Expr) :=\n  withNatValue a fun a =>\n  return mkRawNatLit <| f a\n\ndef reduceBinNatOp (f : Nat \u2192 Nat \u2192 Nat) (a b : Expr) : ReductionM (Option Expr) :=\n  withNatValue a fun a =>\n  withNatValue b fun b => do\n  trace[Meta.isDefEq.whnf.reduceBinOp] \"{a} op {b}\"\n  return mkRawNatLit <| f a b\n\ndef reduceBinNatPred (f : Nat \u2192 Nat \u2192 Bool) (a b : Expr) : ReductionM (Option Expr) := do\n  withNatValue a fun a =>\n  withNatValue b fun b =>\n  return toExpr <| f a b\n\ndef reduceNat? (e : Expr) : ReductionM (Option Expr) :=\n  if e.hasFVar || e.hasMVar then\n    return none\n  else match e with\n    | Expr.app (Expr.const fn _) a                =>\n      if fn == ``Nat.succ then\n        reduceUnaryNatOp Nat.succ a\n      else\n        return none\n    | Expr.app (Expr.app (Expr.const fn _) a1) a2 =>\n      if fn == ``Nat.add then reduceBinNatOp Nat.add a1 a2\n      else if fn == ``Nat.sub then reduceBinNatOp Nat.sub a1 a2\n      else if fn == ``Nat.mul then reduceBinNatOp Nat.mul a1 a2\n      else if fn == ``Nat.div then reduceBinNatOp Nat.div a1 a2\n      else if fn == ``Nat.mod then reduceBinNatOp Nat.mod a1 a2\n      else if fn == ``Nat.beq then reduceBinNatPred Nat.beq a1 a2\n      else if fn == ``Nat.ble then reduceBinNatPred Nat.ble a1 a2\n      else return none\n    | _ =>\n      return none\n\n\n@[inline] private def useWHNFCache (_ : Expr) : MetaM Bool := do\n  -- Can't straightforwardly use the WHNF cache with configurable rules.\n  return false\n  -- We cache only closed terms without expr metavars.\n  -- Potential refinement: cache if `e` is not stuck at a metavariable\n  -- if e.hasFVar || e.hasExprMVar || (\u2190 read).canUnfold?.isSome then\n  --   return false\n  -- else\n  --   match (\u2190 getConfig).transparency with\n  --   | TransparencyMode.default => return true\n  --   | TransparencyMode.all     => return true\n  --   | _                        => return false\n\n@[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do\n  if useCache then\n    match (\u2190 getConfig).transparency with\n    | TransparencyMode.default => return (\u2190 get).cache.whnfDefault.find? e\n    | TransparencyMode.all     => return (\u2190 get).cache.whnfAll.find? e\n    | _                        => unreachable!\n  else\n    return none\n\nprivate def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do\n  if useCache then\n    match (\u2190 getConfig).transparency with\n    | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r }\n    | TransparencyMode.all     => modify fun s => { s with cache.whnfAll     := s.cache.whnfAll.insert e r }\n    | _                        => unreachable!\n  return r\n\npartial def whnfImp (e : Expr) : ReductionM Expr :=\n  withIncRecDepth <| withTraceNode `Smt.reduce.whnf  (traceReduce e \u00b7) <| whnfEasyCases e fun e => do\n    checkMaxHeartbeats \"Smt.whnf\"\n    let useCache \u2190 useWHNFCache e\n    let e' \u2190 match (\u2190 cached? useCache e) with\n    | some e' => pure e'\n    | none    =>\n      let e' \u2190 whnfCore e\n      match (\u2190 reduceNat? e') with\n      | some v => cache useCache e v\n      | none   =>\n        match (\u2190 reduceNative? e') with\n        | some v => cache useCache e v\n        | none   =>\n          match (\u2190 unfoldDefinition? e') with\n          | some e => whnfImp e\n          | none   => cache useCache e e'\n    return e'\n\n/-- If `e` is a projection function that satisfies `p`, then reduce it -/\ndef reduceProjOf? (e : Expr) (p : Name \u2192 Bool) : MetaM (Option Expr) := do\n  if !e.isApp then\n    pure none\n  else match e.getAppFn with\n    | Expr.const name .. => do\n      let env \u2190 getEnv\n      match env.getProjectionStructureName? name with\n      | some structName =>\n        if p structName then\n          Meta.unfoldDefinition? e\n        else\n          pure none\n      | none => pure none\n    | _ => pure none\n\npartial def reduce (e : Expr) (explicitOnly skipTypes skipProofs := true) : ReductionM Expr :=\n  let rec visit (e : Expr) : MonadCacheT Expr Expr ReductionM Expr :=\n    checkCache e fun _ => Core.withIncRecDepth <| withTraceNode `Smt.reduce (traceReduce e \u00b7) do\n      if (\u2190 (pure skipTypes <&&> isType e)) then\n        return e\n      else if (\u2190 (pure skipProofs <&&> isProof e)) then\n        return e\n      else\n        let e \u2190 whnf e\n        let e' \u2190 match e with\n        | Expr.app .. =>\n          -- This case happens when the application was not substituted by WHNF,\n          -- meaning that it must be stuck.\n          let f     \u2190 visit e.getAppFn\n          let nargs := e.getAppNumArgs\n          let finfo \u2190 getFunInfoNArgs f nargs\n          let mut args  := e.getAppArgs\n          for i in [:args.size] do\n            if i < finfo.paramInfo.size then\n              let info := finfo.paramInfo[i]!\n              if !explicitOnly || info.isExplicit then\n                args \u2190 args.modifyM i visit\n            else\n              args \u2190 args.modifyM i visit\n          if f.isConstOf ``Nat.succ && args.size == 1 && args[0]!.isNatLit then\n            pure <| mkRawNatLit (args[0]!.natLit?.get! + 1)\n          else\n            pure <| mkAppN f args\n        -- `let`-bindings are normally substituted by WHNF, but they are left alone when `zeta` is off,\n        -- so we must reduce their subterms here.\n        | Expr.letE nm t v b nonDep => do\n          let t' \u2190 visit t\n          -- Reduce body with the let-bound name in context to avoid name shadowing\n          let v' \u2190 withLocalDeclD nm t <| fun _ => visit v\n          let nm \u2190 bumpNameIfUsed nm\n          -- TODO: we use an opaque `cdecl` since this case only runs when `zeta` is off anyway.\n          -- Is this correct?\n          let b' \u2190 withLocalDeclD nm t' fun x => do\n            let b' \u2190 visit (b.instantiate1 x)\n            pure <| b'.abstract #[x]\n          let e' := Expr.letE nm t' v' b' nonDep\n          pure e'\n        | Expr.lam ..        => lambdaTelescope e fun xs b => do mkLambdaFVars xs (\u2190 visit b)\n        | Expr.forallE ..    => forallTelescope e fun xs b => do mkForallFVars xs (\u2190 visit b)\n        | Expr.proj n i s .. => pure <| mkProj n i (\u2190 visit s)\n        -- TODO: this case is pretty awkward; what we really want is a positional mdata context, I think\n        | Expr.mdata md (Expr.letE nm t v b nonDep) => do\n          let t' \u2190 visit t\n          -- Reduce body with the let-bound name in context to avoid name shadowing\n          let v' \u2190 withLocalDeclD nm t <| fun _ => visit v\n          let nm \u2190 bumpNameIfUsed nm\n          let b' \u2190 withLocalDeclD nm t' fun x => do\n            let b' \u2190 visit (b.instantiate1 x)\n            pure <| b'.abstract #[x]\n          let e' := Expr.letE nm t' v' b' nonDep\n          pure <| mkMData md e'\n        | _                  => pure e\n        return e'\n  visit e |>.run\n\ninitialize\n  registerTraceClass `Smt.reduce\n  registerTraceClass `Smt.reduce.whnf\n  registerTraceClass `Smt.reduce.whnfCore\n  registerTraceClass `Smt.reduce.rec\n  registerTraceClass `Smt.reduce.matcher\n  registerTraceClass `Smt.reduce.smartUnfoldingReduce\n\nend Smt\n\ninitialize Smt.whnfRef.set Smt.whnfImp\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/Tactic/WHNFConfigurable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.05108273695705249, "lm_q1q2_score": 0.021777673771215155}}
{"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\n! This file was ported from Lean 3 source module tactic.simpa\n! leanprover-community/mathlib commit 3d7987cda72abc473c7cdbbb075170e9ac620042\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.DocCommands\n\nopen Interactive\n\nopen Interactive.Types\n\nnamespace Tactic\n\nnamespace Interactive\n\nopen Expr Lean.Parser\n\n-- mathport name: parser.optional\nlocal postfix:1024 \"?\" => optional\n\n/-- This 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. -/\nunsafe 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 :=\n  let simp_at (lc) (close_tac : tactic Unit) :=\n    focus1 <|\n      simp use_iota_eqn trace_lemmas no_dflt hs attr_names (Loc.ns lc)\n          { cfg with failIfUnchanged := false } >>\n        ((close_tac <|> trivial) >> done <|> fail \"simpa failed\")\n  match tgt with\n  | none => get_local `this >> simp_at [some `this, none] assumption <|> simp_at [none] assumption\n  | some e =>\n    focus1 do\n      let e \u2190\n        i_to_expr e <|> do\n            let ty \u2190 target\n            let e\n              \u2190-- for positional error messages, we don't care about the result\n                  i_to_expr_strict\n                  ``(($(e) : $(ty)))\n            let pty \u2190 pp ty\n            let ptgt \u2190 pp e\n            -- Fail deliberately, to advise regarding `simp; exact` usage\n                fail\n                (\"simpa failed, 'using' expression type not directly \" ++\n                          \"inferrable. Try:\\n\\nsimpa ... using\\nshow \" ++\n                        to_fmt pty ++\n                      \",\\nfrom \" ++\n                    ptgt :\n                  format)\n      match e with\n        | local_const _ lc _ _ => simp_at [some lc, none] (get_local lc >>= tactic.exact)\n        | e => do\n          let t \u2190 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#align tactic.interactive.simpa tactic.interactive.simpa\n\nadd_tactic_doc\n  { Name := \"simpa\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.simpa]\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/Simpa.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.05184546555102378, "lm_q1q2_score": 0.021707536190320384}}
{"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, S\u00e9bastien Gou\u00ebzel, Scott Morrison\n-/\nimport tactic.lint\nimport tactic.dependencies\n\nsetup_tactic_parser\n\nnamespace tactic\nnamespace interactive\nopen interactive interactive.types expr\n\n/-- Similar to `constructor`, but does not reorder goals. -/\nmeta def fconstructor : tactic unit := concat_tags tactic.fconstructor\n\nadd_tactic_doc\n{ name       := \"fconstructor\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.fconstructor],\n  tags       := [\"logic\", \"goal management\"] }\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 \u2190 i_to_expr_strict max >>= tactic.eval_expr nat,\n  \u03bb 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 :=\npropagate_tags $ l.mmap' (\u03bb h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"substs\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.substs],\n  tags       := [\"rewriting\"] }\n\n/-- Unfold coercion-related definitions -/\nmeta def unfold_coes (loc : parse location) : tactic unit :=\nunfold [\n  ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,\n  ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,\n  ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc\n\nadd_tactic_doc\n{ name       := \"unfold_coes\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.unfold_coes],\n  tags       := [\"simplification\"] }\n\n\n/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/\nmeta def unfold_wf :=\npropagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof)\n\n/-- Unfold auxiliary definitions associated with the current declaration. -/\nmeta def unfold_aux : tactic unit :=\ndo tgt \u2190 target,\n   name \u2190 decl_name,\n   let to_unfold := (tgt.list_names_with_prefix name),\n   guard (\u00ac 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\u03bb s, result.cases_on (tac s)\n (\u03bb a, result.success ())\n (\u03bb e ref, result.success ())\n\n/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without\nrequiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a\nnon-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/\n@[inline] protected meta def id (tac : itactic) : tactic unit := tac\n\n/--\n`work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero),\nand does not require that the goal be solved at the end\n(any remaining subgoals are inserted back into the list of goals).\n\nTypically usage might look like:\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 2\n{ dsimp,\n  simp },\nrefl\n````\n\nSee also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`.\n-/\nmeta def work_on_goal : parse small_nat \u2192 itactic \u2192 tactic unit\n| n t := do\n  goals \u2190 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 \u2190 get_goals,\n  set_goals (earlier_goals ++ new_goals ++ later_goals)\n\n/--\n`swap n` will move the `n`th goal to the front.\n`swap` defaults to `swap 2`, and so interchanges the first and second goals.\n\nSee also `tactic.interactive.rotate`, which moves the first `n` goals to the back.\n-/\nmeta def swap (n := 2) : tactic unit :=\ndo gs \u2190 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\nadd_tactic_doc\n{ name       := \"swap\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.swap],\n  tags       := [\"goal management\"] }\n\n/--\n`rotate` moves the first goal to the back. `rotate n` will do this `n` times.\n\nSee also `tactic.interactive.swap`, which moves the `n`th goal to the front.\n-/\nmeta def rotate (n := 1) : tactic unit := tactic.rotate n\n\nadd_tactic_doc\n{ name       := \"rotate\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.rotate],\n  tags       := [\"goal management\"] }\n\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\nmeta def clear_ : tactic unit := tactic.repeat $ do\n  l \u2190 local_context,\n  l.reverse.mfirst $ \u03bb h, do\n    name.mk_string s p \u2190 return $ local_pp_name h,\n    guard (s.front = '_'),\n    cl \u2190 infer_type h >>= is_class, guard (\u00ac cl),\n    tactic.clear h\n\nadd_tactic_doc\n{ name       := \"clear_\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_],\n  tags       := [\"context management\"] }\n\n/--\nActs like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nmeta def replace (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?)\n  (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\ndo let h := h.get_or_else `this,\n  old \u2190 try_core (get_local h),\n  \u00abhave\u00bb h q\u2081 q\u2082,\n  match old, q\u2082 with\n  | none,   _      := skip\n  | some o, some _ := tactic.clear o\n  | some o, none   := swap >> tactic.clear o >> swap\n  end\n\nadd_tactic_doc\n{ name       := \"replace\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.replace],\n  tags       := [\"context management\"] }\n\n/-- Make every proposition in the context decidable. -/\nmeta def classical := tactic.classical\n\nadd_tactic_doc\n{ name       := \"classical\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.classical],\n  tags       := [\"classical logic\", \"type class\"] }\n\nprivate meta def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\n@[nolint def_lemma]\nlemma {u} generalize_a_aux {\u03b1 : Sort u}\n  (h : \u2200 x : Sort u, (\u03b1 \u2192 x) \u2192 x) : \u03b1 := h \u03b1 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' \u2190 get_unused_name `h,\n   x' \u2190 get_unused_name `x,\n   g \u2190 if \u00ac 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 \u2190 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\nadd_tactic_doc\n{ name       := \"generalize_hyp\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize_hyp],\n  tags       := [\"context management\"] }\n\nmeta def compact_decl_aux : list name \u2192 binder_info \u2192 expr \u2192 list expr \u2192\n  tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| ns bi t [] := pure [(ns.reverse, bi, t)]\n| ns bi t (v'@(local_const n pp bi' t') :: xs) :=\n  do t' \u2190 infer_type v',\n     if bi = bi' \u2227 t = t'\n       then compact_decl_aux (pp :: ns) bi t xs\n       else do vs \u2190 compact_decl_aux [pp] bi' t' xs,\n               pure $ (ns.reverse, bi, t) :: vs\n| ns bi t (_ :: xs) := compact_decl_aux ns bi t xs\n\n/-- go from (x\u2080 : t\u2080) (x\u2081 : t\u2080) (x\u2082 : t\u2080) to (x\u2080 x\u2081 x\u2082 : t\u2080) -/\nmeta def compact_decl : list expr \u2192 tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| [] := pure []\n| (v@(local_const n pp bi t) :: xs)  :=\n  do t \u2190 infer_type v,\n     compact_decl_aux [pp] bi t xs\n| (_ :: xs) := compact_decl xs\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.\n-/\nmeta def clean (q : parse texpr) : tactic unit :=\ndo tgt : expr \u2190 target,\n   e \u2190 i_to_expr_strict ``(%%q : %%tgt),\n   tactic.exact $ e.clean\n\nmeta def source_fields (missing : list name) (e : pexpr) : tactic (list (name \u00d7 pexpr)) :=\ndo e \u2190 to_expr e,\n   t \u2190 infer_type e,\n   let struct_n : name := t.get_app_fn.const_name,\n   fields \u2190 expanded_field_list struct_n,\n   let exp_fields := fields.filter (\u03bb x, x.2 \u2208 missing),\n   exp_fields.mmap $ \u03bb \u27e8p,n\u27e9,\n     (prod.mk n \u2218 to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]\n\nmeta def collect_struct' : pexpr \u2192 state_t (list $ expr\u00d7structure_instance_info) tactic pexpr | e :=\ndo some str \u2190 pure (e.get_structure_instance_info)\n       | e.traverse collect_struct',\n   v \u2190 monad_lift mk_mvar,\n   modify (list.cons (v,str)),\n   pure $ to_pexpr v\n\nmeta def collect_struct (e : pexpr) : tactic $ pexpr \u00d7 list (expr\u00d7structure_instance_info) :=\nprod.map id list.reverse <$> (collect_struct' e).run []\n\nmeta def refine_one (str : structure_instance_info) :\n  tactic $ list (expr\u00d7structure_instance_info) :=\ndo    tgt \u2190 target >>= whnf,\n      let struct_n : name := tgt.get_app_fn.const_name,\n      exp_fields \u2190 expanded_field_list struct_n,\n      let missing_f := exp_fields.filter (\u03bb f, (f.2 : name) \u2209 str.field_names),\n      (src_field_names,src_field_vals) \u2190 (@list.unzip name _ \u2218 list.join) <$>\n        str.sources.mmap (source_fields $ missing_f.map prod.snd),\n      let provided  := exp_fields.filter (\u03bb f, (f.2 : name) \u2208 str.field_names),\n      let missing_f' := missing_f.filter (\u03bb x, x.2 \u2209 src_field_names),\n      vs \u2190 mk_mvar_list missing_f'.length,\n      (field_values,new_goals) \u2190 list.unzip <$> (str.field_values.mmap collect_struct : tactic _),\n      e' \u2190 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 \u2190 with_enable_tags (\n        mzip_with (\u03bb (n : name \u00d7 name) v, do\n           set_goals [v],\n           try (dsimp_target simp_lemmas.mk),\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 \u00d7 structure_instance_info \u2192 tactic (list expr) | (e,str) :=\ndo set_goals [e],\n   rs \u2190 refine_one str,\n   gs \u2190 get_goals,\n   gs' \u2190 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 of semigroup\ninstances:\n\n```lean\nrefine_struct ( { .. } : semigroup \u03b1 ),\n-- case semigroup, mul\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nmeta def refine_struct : parse texpr \u2192 tactic unit | e :=\ndo (x,xs) \u2190 collect_struct e,\n   refine x,\n   gs \u2190 get_goals,\n   xs' \u2190 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 \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p\n\n/--\n`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).\nWe use this tactic for writing tests.\n-/\nmeta def match_hyp (n : parse ident) (p : parse $ tk \":\" *> texpr) (m := reducible) :\n  tactic (list expr) :=\ndo\n  h \u2190 get_local n >>= infer_type >>= instantiate_mvars,\n  match_expr p h m\n\n/--\n`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast\nto `guard_expr`, this tests strict (syntactic) equality.\nWe use this tactic for writing tests.\n-/\nmeta def guard_expr_strict (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, guard (t = e)\n\n/--\n`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_target_strict (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_strict t p\n\n/--\n`guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal\nto `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_hyp_strict (n : parse ident) (p : parse $ tk \":\" *> texpr) : tactic unit :=\ndo h \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p\n\n/-- Tests that there are `n` hypotheses in the current context. -/\nmeta def guard_hyp_nums (n : \u2115) : tactic unit :=\ndo k \u2190 local_context,\n   guard (n = k.length) <|> fail format!\"{k.length} hypotheses found\"\n\n/-- Test that `t` is the tag of the main goal. -/\nmeta def guard_tags (tags : parse ident*) : tactic unit :=\ndo (t : list name) \u2190 get_main_tag,\n   guard (t = tags)\n\n/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term\n  unifies with `p`. -/\nmeta def guard_proof_term (t : itactic) (p : parse texpr) : itactic :=\ndo\n  g :: _ \u2190 get_goals,\n  e \u2190 to_expr p,\n  t,\n  g \u2190 instantiate_mvars g,\n  unify e g\n\n/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with\nerror message `msg` (for test writing purposes). -/\nmeta def success_if_fail_with_msg (tac : tactic.interactive.itactic) :=\ntactic.success_if_fail_with_msg tac\n\n/-- Get the field of the current goal. -/\nmeta def get_current_field : tactic name :=\ndo [_,field,str] \u2190 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 \u2190 get_goals,\n   ts \u2190 gs.mmap get_tag,\n   ([g],gs') \u2190 pure $ (list.zip gs ts).partition (\u03bb 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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\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\nadd_tactic_doc\n{ name       := \"refine_struct\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field,\n                 `tactic.interactive.have_field],\n  tags       := [\"structures\"],\n  inherit_description_from := `tactic.interactive.refine_struct }\n\n/--\n`apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is optional, equal to 50 by default.\nYou can pass an `apply_cfg` option argument as `apply_rules hs n opt`.\n(A typical usage would be with `apply_rules hs n { md := reducible })`,\nwhich asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)\nwhen checking if a lemma matches the goal.)\n\n`hs` can contain user attributes: in this case all theorems with this\nattribute are added to the list of rules.\n\nFor instance:\n\n```lean\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 b + d * e + b + d + e :=\n-- any of the following lines solve the goal:\nadd_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\nby apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\nby apply_rules [mono_rules]\nby apply_rules mono_rules\n```\n-/\nmeta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) (opt : apply_cfg := {}) :\n  tactic unit :=\ntactic.apply_rules hs n opt\n\nadd_tactic_doc\n{ name       := \"apply_rules\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.apply_rules],\n  tags       := [\"lemma application\"] }\n\nmeta def return_cast (f : option expr) (t : option (expr \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr))\n  (e x x' eq_h : expr) :\n  tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 expr)) :=\n(do guard (\u00ac e.has_var),\n    unify x x',\n    u \u2190 mk_meta_univ,\n    f \u2190 f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],\n    t' \u2190 infer_type e,\n    some (f',t) \u2190 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 \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr)) :\n  expr \u2192 tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 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 %%\u03b1 %%p %%a %%b  %%eq_h %%x') := return_cast p t es e x x' eq_h\n| e@`(@eq.substr %%\u03b1 %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'\n| e@`(@eq.rec %%\u03b1 %%a %%f %%x' _  %%eq_h) := return_cast f t es e x x' eq_h\n| e@`(@eq.rec_on %%\u03b1 %%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 \u00d7 expr \u00d7 expr)) :=\n(list.reverse \u2218 prod.snd) <$> tgt.mfold (none, []) (\u03bb e i es, list_cast_of_aux x es.1 es.2 e)\n\nprivate meta def h_generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`;\n- `h_generalize Hx : e == x with _` chooses automatically chooses the name of\n  assumption `\u03b1 = \u03b2`;\n- `h_generalize! Hx : e == x` reverts `Hx`;\n- when `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' \u2190 (h' : tactic name) <|> get_unused_name (\"h\" ++ n.to_string : string),\n   e \u2190 to_expr e,\n   tgt \u2190 target,\n   ((e,x,eq_h)::es) \u2190 list_cast_of e tgt | fail \"no cast found\",\n   interactive.generalize h' () (to_pexpr e, n),\n   asm \u2190 get_local h',\n   v \u2190 get_local n,\n   hs \u2190 es.mmap (\u03bb \u27e8e,_\u27e9, mk_app `eq [e,v]),\n   (eqs_h.zip [e]).mmap' (\u03bb \u27e8h,e\u27e9, do\n        h \u2190 if h \u2260 `_ then pure h else get_unused_name `h,\n        () <$ note h none eq_h ),\n   hs.mmap' (\u03bb h,\n     do h' \u2190 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_cast_eq %%eq_h %%asm))\n     >>= note h' none >> pure ()),\n   tactic.clear asm,\n   when rev.is_some (interactive.revert [n])\n\nadd_tactic_doc\n{ name       := \"h_generalize\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.h_generalize],\n  tags       := [\"context management\"] }\n\n/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that\n  this uses definitional equality instead of alpha-equivalence. -/\nmeta def guard_expr_eq' (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, is_def_eq t e\n\n/--\n`guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.\nWe use this tactic for writing tests.\nThe difference with `guard_target` is that this uses definitional equality instead of\nalpha-equivalence.\n-/\nmeta def guard_target' (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_eq' t p\n\nadd_tactic_doc\n{ name       := \"guard_target'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.guard_target'],\n  tags       := [\"testing\"] }\n\n/--\na weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true,\nunfolding only `reducible` constants. -/\nmeta def triv : tactic unit :=\ntactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail \"triv tactic failed\"\n\nadd_tactic_doc\n{ name       := \"triv\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.triv],\n  tags       := [\"finishing\"] }\n\n/--\nSimilar to `existsi`. `use x` will instantiate the first term of an `\u2203` or `\u03a3` goal with `x`. It\nwill then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`.\nUnlike `existsi`, `x` is elaborated with respect to the expected type.\n`use` will alternatively take a list of terms `[x0, ..., xn]`.\n\n`use` will work with constructors of arbitrary inductive types.\n\nExamples:\n```lean\nexample (\u03b1 : Type) : \u2203 S : set \u03b1, S = S :=\nby use \u2205\n\nexample : \u2203 x : \u2124, x = x :=\nby use 42\n\nexample : \u2203 n > 0, n = n :=\nbegin\n  use 1,\n  -- goal is now 1 > 0 \u2227 1 = 1, whereas it would be \u2203 (H : 1 > 0), 1 = 1 after existsi 1.\n  exact \u27e8zero_lt_one, rfl\u27e9,\nend\n\nexample : \u2203 a b c : \u2124, a + b + c = 6 :=\nby use [1, 2, 3]\n\nexample : \u2203 p : \u2124 \u00d7 \u2124, p.1 = 1 :=\nby use \u27e81, 42\u27e9\n\nexample : \u03a3 x y : \u2124, (\u2124 \u00d7 \u2124) \u00d7 \u2124 :=\nby use [1, 2, 3, 4, 5]\n\ninductive foo\n| mk : \u2115 \u2192 bool \u00d7 \u2115 \u2192 \u2115 \u2192 foo\n\nexample : foo :=\nby use [100, tt, 4, 3]\n```\n-/\nmeta def use (l : parse pexpr_list_or_texpr) : tactic unit :=\nfocus1 $\n  tactic.use l;\n  try (triv <|> (do\n        `(Exists %%p) \u2190 target,\n        to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip))\n\nadd_tactic_doc\n{ name       := \"use\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.use, `tactic.interactive.existsi],\n  tags       := [\"logic\"],\n  inherit_description_from := `tactic.interactive.use }\n\n/--\n`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.\nThis includes the induction hypothesis when using the equation compiler and\n`_let_match` and `_fun_match`.\n\nIt is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these\nauxiliary declarations, and produce an error saying the recursion is not well founded.\n\n```lean\nexample (n m : \u2115) (h\u2081 : n = m) (h\u2082 : \u2203 a : \u2115, a = n \u2227 a = m) : 2 * m = 2 * n :=\nlet \u27e8a, ha\u27e9 := h\u2082 in\nbegin\n  clear_aux_decl, -- subst will fail without this line\n  subst h\u2081\nend\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl, -- finish produces an error without this line\n  finish\nend\n```\n-/\nmeta def clear_aux_decl : tactic unit := tactic.clear_aux_decl\n\nadd_tactic_doc\n{ name       := \"clear_aux_decl\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl],\n  tags       := [\"context management\"],\n  inherit_description_from := `tactic.interactive.clear_aux_decl }\n\nmeta def loc.get_local_pp_names : loc \u2192 tactic (list name)\n| loc.wildcard := list.map expr.local_pp_name <$> local_context\n| (loc.ns l) := return l.reduce_option\n\nmeta def loc.get_local_uniq_names (l : loc) : tactic (list name) :=\nlist.map expr.local_uniq_name <$> l.get_locals\n\n/--\nThe logic of `change x with y at l` fails when there are dependencies.\n`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.\nIn this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses\nin `l`. As long as `x` and `y` are defeq, it should never fail.\n-/\nmeta def change' (q : parse texpr) : parse (tk \"with\" *> texpr)? \u2192 parse location \u2192 tactic unit\n| none (loc.ns [none]) := do e \u2190 i_to_expr q, change_core e none\n| none (loc.ns [some h]) := do eq \u2190 i_to_expr q, eh \u2190 get_local h, change_core eq (some eh)\n| none _ := fail \"change-at does not support multiple locations\"\n| (some w) l :=\n  do l' \u2190 loc.get_local_pp_names l,\n     l'.mmap' (\u03bb e, try (change_with_at q w e)),\n     when l.include_goal $ change q w (loc.ns [none])\n\nadd_tactic_doc\n{ name       := \"change'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.change', `tactic.interactive.change],\n  tags       := [\"renaming\"],\n  inherit_description_from := `tactic.interactive.change' }\n\nprivate meta def opt_dir_with : parser (option (bool \u00d7 name)) :=\n(do tk \"with\",\n   arrow \u2190 (tk \"<-\")?,\n   h \u2190 ident,\n   return (arrow.is_some, h)) <|> return none\n\n/--\n`set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to\nthe local context and replaces `t` with `a` everywhere it can.\n\n`set a := t with \u2190h` will add `h : t = a` instead.\n\n`set! a := t with h` does not do any replacing.\n\n```lean\nexample (x : \u2115) (h : x = 3)  : x + x + x = 9 :=\nbegin\n  set y := x with \u2190h_xy,\n/-\nx : \u2115,\ny : \u2115 := x,\nh_xy : x = y,\nh : y = 3\n\u22a2 y + y + y = 9\n-/\nend\n```\n-/\nmeta def set (h_simp : parse (tk \"!\")?) (a : parse ident) (tp : parse ((tk \":\") >> texpr)?)\n  (_ : parse (tk \":=\")) (pv : parse texpr)\n  (rev_name : parse opt_dir_with) :=\ndo tp \u2190 i_to_expr $ tp.get_or_else pexpr.mk_placeholder,\n   pv \u2190 to_expr ``(%%pv : %%tp),\n   tp \u2190 instantiate_mvars tp,\n   definev a tp pv,\n   when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard,\n   match rev_name with\n   | some (flip, id) :=\n     do nv \u2190 get_local a,\n        mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id,\n        reflexivity\n   | none := skip\n   end\n\nadd_tactic_doc\n{ name       := \"set\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.set],\n  tags       := [\"context management\"] }\n\n/--\n`clear_except h\u2080 h\u2081` deletes all the assumptions it can except for `h\u2080` and `h\u2081`.\n-/\nmeta def clear_except (xs : parse ident *) : tactic unit :=\ndo n \u2190 xs.mmap (try_core \u2218 get_local) >>= revert_lst \u2218 list.filter_map id,\n   ls \u2190 local_context,\n   ls.reverse.mmap' $ try \u2218 tactic.clear,\n   intron_no_renames n\n\nadd_tactic_doc\n{ name       := \"clear_except\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_except],\n  tags       := [\"context management\"] }\n\n\nmeta def format_names (ns : list name) : format :=\nformat.join $ list.intersperse \" \" (ns.map to_fmt)\n\nprivate meta def indent_bindents (l r : string) : option (list name) \u2192 expr \u2192 tactic format\n| none e :=\n  do e \u2190 pp e,\n     pformat!\"{l}{format.nest l.length e}{r}\"\n| (some ns) e :=\n  do e \u2190 pp e,\n     let ns := format_names ns,\n     let margin := l.length + ns.to_string.length + \" : \".length,\n     pformat!\"{l}{ns} : {format.nest margin e}{r}\"\n\nprivate meta def format_binders : list name \u00d7 binder_info \u00d7 expr \u2192 tactic format\n| (ns, binder_info.default, t) := indent_bindents \"(\" \")\" ns t\n| (ns, binder_info.implicit, t) := indent_bindents \"{\" \"}\" ns t\n| (ns, binder_info.strict_implicit, t) := indent_bindents \"\u2983\" \"\u2984\" ns t\n| ([n], binder_info.inst_implicit, t) :=\n  if \"_\".is_prefix_of n.to_string\n    then indent_bindents \"[\" \"]\" none t\n    else indent_bindents \"[\" \"]\" [n] t\n| (ns, binder_info.inst_implicit, t) := indent_bindents \"[\" \"]\" ns t\n| (ns, binder_info.aux_decl, t) := indent_bindents \"(\" \")\" ns t\n\nprivate meta def partition_vars' (s : name_set) :\n  list expr \u2192 list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr)\n| [] as bs := pure (as.reverse, bs.reverse)\n| (x :: xs) as bs :=\ndo t \u2190 infer_type x,\n   if t.has_local_in s then partition_vars' xs as (x :: bs)\n     else partition_vars' xs (x :: as) bs\n\nprivate meta def partition_vars : tactic (list expr \u00d7 list expr) :=\ndo ls \u2190 local_context,\n   partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] []\n\n/--\nFormat the current goal as a stand-alone example. Useful for testing tactics\nor creating [minimal working examples](https://leanprover-community.github.io/mwe.html).\n\n* `extract_goal`: formats the statement as an `example` declaration\n* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration\n  called `my_decl`\n* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration\n\nExamples:\n\n```lean\nexample (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\nbegin\n  extract_goal,\n     -- prints:\n     -- example (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\n  extract_goal my_lemma\n     -- prints:\n     -- lemma my_lemma (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\nend\n\nexample {i j k x y z w p q r m n : \u2115} (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) (h\u2081 : k \u2264 p) (h\u2081 : p \u2264 q) : i \u2264 k :=\nbegin\n  extract_goal my_lemma,\n    -- prints:\n    -- lemma my_lemma {i j k x y z w p q r m n : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p)\n    --   (h\u2081 : p \u2264 q) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\n\n  extract_goal my_lemma with i j k\n    -- prints:\n    -- lemma my_lemma {p i j k : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\nend\n\nexample : true :=\nbegin\n  let n := 0,\n  have m : \u2115, admit,\n  have k : fin n, admit,\n  have : n + m + k.1 = 0, extract_goal,\n    -- prints:\n    -- example (m : \u2115)  : let n : \u2115 := 0 in \u2200 (k : fin n), n + m + k.val = 0 :=\n    -- begin\n    --   intros n k,\n    --   admit,\n    -- end\nend\n```\n\n-/\nmeta def extract_goal (print_use : parse $ tt <$ tk \"!\" <|> pure ff)\n  (n : parse ident?) (vs : parse (tk \"with\" *> ident*)?)\n  : tactic unit :=\ndo tgt \u2190 target,\n   solve_aux tgt $ do\n   { ((cxt\u2080,cxt\u2081,ls,tgt),_) \u2190 solve_aux tgt $ do\n       { vs.mmap clear_except,\n         ls \u2190 local_context,\n         ls \u2190 ls.mfilter $ succeeds \u2218 is_local_def,\n         n \u2190 revert_lst ls,\n         (c\u2080,c\u2081) \u2190 partition_vars,\n         tgt \u2190 target,\n         ls \u2190 intron' n,\n         pure (c\u2080,c\u2081,ls,tgt) },\n     is_prop \u2190 is_prop tgt,\n     let title := match n, is_prop with\n                  | none, _ := to_fmt \"example\"\n                  | (some n), tt := format!\"lemma {n}\"\n                  | (some n), ff := format!\"def {n}\"\n                  end,\n     cxt\u2080 \u2190 compact_decl cxt\u2080 >>= list.mmap format_binders,\n     cxt\u2081 \u2190 compact_decl cxt\u2081 >>= list.mmap format_binders,\n     stmt \u2190 pformat!\"{tgt} :=\",\n     let fmt :=\n       format.group $ format.nest 2 $\n         title ++ cxt\u2080.foldl (\u03bb acc x, acc ++ format.group (format.line ++ x)) \"\" ++\n         format.join (list.map (\u03bb x, format.line ++ x) cxt\u2081) ++ \" :\" ++\n         format.line ++ stmt,\n     trace $ fmt.to_string $ options.mk.set_nat `pp.width 80,\n     let var_names := format.intercalate \" \" $ ls.map (to_fmt \u2218 local_pp_name),\n     let call_intron := if ls.empty\n                     then to_fmt \"\"\n                     else format!\"\\n  intros {var_names},\",\n     trace!\"begin{call_intron}\\n  admit,\\nend\\n\" },\n   skip\n\nadd_tactic_doc\n{ name       := \"extract_goal\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.extract_goal],\n  tags       := [\"goal management\", \"proof extraction\", \"debugging\"] }\n\n/--\n`inhabit \u03b1` tries to derive a `nonempty \u03b1` instance and then upgrades this\nto an `inhabited \u03b1` instance.\nIf the target is a `Prop`, this is done constructively;\notherwise, it uses `classical.choice`.\n\n```lean\nexample (\u03b1) [nonempty \u03b1] : \u2203 a : \u03b1, true :=\nbegin\n  inhabit \u03b1,\n  existsi default \u03b1,\n  trivial\nend\n```\n-/\nmeta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit :=\ndo ty \u2190 i_to_expr t,\n   nm \u2190 returnopt inst_name <|> get_unused_name `inst,\n   tgt \u2190 target,\n   tgt_is_prop \u2190 is_prop tgt,\n   if tgt_is_prop then do\n     decorate_error \"could not infer nonempty instance:\" $\n       mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply,\n     introI nm\n   else do\n     decorate_error \"could not infer nonempty instance:\" $\n      mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none,\n     resetI\n\nadd_tactic_doc\n{ name       := \"inhabit\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.inhabit],\n  tags       := [\"context management\", \"type class\"] }\n\n/-- `revert_deps n\u2081 n\u2082 ...` reverts all the hypotheses that depend on one of `n\u2081, n\u2082, ...`\nIt does not revert `n\u2081, n\u2082, ...` themselves (unless they depend on another `n\u1d62`). -/\nmeta def revert_deps (ns : parse ident*) : tactic unit :=\npropagate_tags $\n  ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `revert_after n` reverts all the hypotheses after `n`. -/\nmeta def revert_after (n : parse ident) : tactic unit :=\npropagate_tags $ get_local n >>= tactic.revert_after >> skip\n\nadd_tactic_doc\n{ name       := \"revert_after\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_after],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- Reverts all local constants on which the target depends (recursively). -/\nmeta def revert_target_deps : tactic unit :=\npropagate_tags $ tactic.revert_target_deps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_target_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_target_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `clear_value n\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`. -/\nmeta def clear_value (ns : parse ident*) : tactic unit :=\npropagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value\n\nadd_tactic_doc\n{ name       := \"clear_value\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_value],\n  tags       := [\"context management\"] }\n\n/--\n`generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of\nthe same type.\n\n`generalize' h : e = x` in addition registers the hypothesis `h : e = x`.\n\n`generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also\nsucceeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis\n`x` is not a local definition.\n-/\nmeta def generalize' (h : parse ident?) (_ : parse $ tk \":\") (p : parse generalize_arg_p) :\n  tactic unit :=\npropagate_tags $\ndo let (p, x) := p,\n   e \u2190 i_to_expr p,\n   some h \u2190 pure h | tactic.generalize' e x >> skip,\n   -- `h` is given, the regular implementation of `generalize` works.\n   tgt \u2190 target,\n   tgt' \u2190 do\n   { \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize e x >> target),\n     to_expr ``(\u03a0 x, %%e = x \u2192 %%(tgt'.binding_body.lift_vars 0 1)) }\n   <|> to_expr ``(\u03a0 x, %%e = x \u2192 %%tgt),\n   t \u2190 assert h tgt',\n   swap,\n   exact ``(%%t %%e rfl),\n   intro x,\n   intro h\n\nadd_tactic_doc\n{ name       := \"generalize'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize'],\n  tags       := [\"context management\"] }\n\n/--\nIf the expression `q` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.interactive.subst' q` substitutes `x` by `t` everywhere in the main goal and\nthen clears `q`.\nIf `q` is another local variable, then we find a local constant with type `q = t` or `t = q` and\nsubstitute `t` for `q`.\n\nLike `tactic.interactive.subst`, but fails with a nicer error message if the substituted variable is\na local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nmeta def subst' (q : parse texpr) : tactic unit := do\ni_to_expr q >>= tactic.subst' >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"subst'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.subst'],\n  tags       := [\"context management\"] }\n\nend interactive\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.07369627733527158, "lm_q1q2_score": 0.02168254818471283}}
{"text": "namespace Foo\n-- The following declaration shadows the builtin parser alias `letDecl`\nsyntax letDecl := term \">==>\" term\n\nsyntax \"foo!\" letDecl : term\n\nmacro_rules\n  | `(foo! $x:term >==> $y) => `($x + $y)\n\nend Foo\n\n-- The following declaration shadows the builtin parser alias `letDecl`\nsyntax letDecl := term \">=>=>\" term\n\nsyntax \"bla!\" letDecl : term\n\nmacro_rules\n  | `(bla! $x:term >=>=> $y) => `($x * $y)\n\nsyntax \"boo!\" Foo.letDecl : term\n\nmacro_rules\n  | `(boo! $x:term >==> $y) => `($x - $y)\n\ntheorem ex1 : (foo! 10 >==> 20) = 30   := rfl\ntheorem ex2 : (bla! 10 >=>=> 20) = 200 := rfl\ntheorem ex3 : (boo! 30 >==> 20) = 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/parserAliasShadow.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.04401865221440602, "lm_q1q2_score": 0.02166545837035057}}
{"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\u207f\n-- and definable functions between them.\n\n/-- A bundled definable subset of some R\u207f. -/\nstructure Def : Type u :=\n(ambdim : \u2115)\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\u27e8Type u, \u03bb X, X.to_set\u27e9\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 \u2192 Y) : Prop :=\nS.def_coords {z : X \u00d7 Y | f z.1 = z.2}\n\nvariables {S}\n\n@[ext] structure Hom (X Y : Def S) : Type u :=\n(to_fun : X \u2192 Y)\n(is_definable : S.definable_fun to_fun)\n\ninstance {X Y : Def S} : has_coe_to_fun (Hom X Y) :=\n\u27e8_, \u03bb f, f.to_fun\u27e9\n\n--instance : category_theory.has_hom (Def S) := { hom := Hom }\nlocal infixr ` \u27f6 `:10 := Hom\n\n@[simp] lemma Hom.to_fun_eq_coe {X Y : Def S} (f : X \u27f6 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 \u27f6 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 \u27f6 Z) (f : X \u27f6 Y) : X \u27f6 Z :=\n{ to_fun := g.to_fun \u2218 f.to_fun,\n  is_definable := begin\n    suffices : S.def_coords {p : X \u00d7 Z | \u2203 y, f p.1 = y \u2227 g y = p.2},\n    { convert this,\n      ext \u27e8x, z\u27e9,\n      simp [struc.definable_fun] },\n    have dXZY : S.def_coords (set.univ : set ((X \u00d7 Z) \u00d7 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 \u03c6 : (X \u00d7 Z) \u00d7 Y \u2192 X \u00d7 Y := \u03bb p, (p.1.1, p.2),\n      have : is_reindexing R \u03c6 :=\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 \u03c6 : (X \u00d7 Z) \u00d7 Y \u2192 Y \u00d7 Z := \u03bb p, (p.2, p.1.2),\n      have : is_reindexing R \u03c6 :=\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 \u27f6 Y) : f.comp (Def.id X) = f :=\nby { ext, refl }\n\nlemma Hom.id_comp {X Y : Def S} (f : X \u27f6 Y) : (Def.id Y).comp f = f :=\nby { ext, refl }\n\nlemma Hom.comp_assoc {W X Y Z : Def S} (h : Y \u27f6 Z) (g : X \u27f6 Y) (f : W \u27f6 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\u27e8\u27e8\u27e8fin_zero_elim, trivial\u27e9\u27e9, \u03bb x, by { ext i, fin_cases i }\u27e9\n\n/-! ### Presheaf stuff -/\n\nvariables (S)\n\n-- TODO: generalize to Sort?\nclass definable_psh (X : Type*) :=\n(definable : \u03a0 {K : Def S}, (K \u2192 X) \u2192 Prop)\n(definable_precomp : \u2200 {L K : Def S} (\u03c6 : L \u27f6 K) {f : K \u2192 X},\n  definable f \u2192 definable (f \u2218 \u03c6))\n\n-- TODO: apply bug??\ndef definable {X : Type*} [definable_psh S X] (x : X) : Prop :=\ndefinable_psh.definable (\u03bb (_ : (pt : Def S)), x)\n\nvariables {S}\n\ndef definable_psh.definable' {X : Type*} (h : definable_psh S X) {K : Def S} (f : K \u2192 X) : Prop :=\ndefinable_psh.definable f\n\ninstance Def.definable_psh (X : Def S) : definable_psh S X :=\n{ definable := \u03bb K f, S.definable_fun f,\n  definable_precomp := begin\n    rintros L K \u03c6 f h,\n    exact ((\u27e8f, h\u27e9 : K \u27f6 X).comp \u03c6).is_definable\n  end }\n\nlemma pt.definable {K : Def S} {f : K \u2192 (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 \u27e8\u27e8k, p\u27e9, -, rfl\u27e9,\n    refine \u27e8k, trivial, _\u27e9,\n    simp },\n  { rintros \u27e8k, -, rfl\u27e9,\n    refine \u27e8\u27e8k, default _\u27e9, show _ = _, by cc, _\u27e9,\n    simp }\nend\n\ninstance {X Y : Type*} [definable_psh S X] [definable_psh S Y] : definable_psh S (X \u00d7 Y) :=\n{ definable := \u03bb K f, definable_psh.definable (prod.fst \u2218 f) \u2227 definable_psh.definable (prod.snd \u2218 f),\n  definable_precomp := begin\n    rintros L K \u03c6 _ \u27e8h\u2081, h\u2082\u27e9,\n    exact \u27e8definable_psh.definable_precomp \u03c6 h\u2081, definable_psh.definable_precomp \u03c6 h\u2082\u27e9,\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 \u2192 Y) :=\n{ definable := \u03bb K f, \u2200 (M : Def S) {g : M \u2192 K \u00d7 X} (h : definable_psh.definable g),\n    definable_psh.definable (function.uncurry f \u2218 g),\n  definable_precomp := \u03bb L K \u03c6 f hf M g hg, begin\n    suffices : definable_psh.definable (\u03bb m, (\u03c6 (g m).1, (g m).2)),\n    { apply hf M this },\n    split,\n    { exact definable_psh.definable_precomp \u27e8\u03bb m, (g m).1, hg.1\u27e9\n        (show definable_psh.definable \u03c6, from \u03c6.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 \u2192 Y} : definable S f \u2194\n  \u2200 {K : Def S} (\u03c6 : K \u2192 X), definable_psh.definable \u03c6 \u2192 definable_psh.definable (f \u2218 \u03c6) :=\nbegin\n  split; intro H,\n  { intros K \u03c6 h\u03c6,\n    -- TODO: This proof is awkward\n    specialize H K,\n    swap,\n    { exact (\u03bb k, (default _, \u03c6 k)) },\n    exact H \u27e8pt.definable, h\u03c6\u27e9 },\n  { intros K \u03c6 h\u03c6,\n    exact H _ h\u03c6.2 }\nend\n\nlemma definable_app {X Y : Type*} [definable_psh S X] [definable_psh S Y]\n  {f : X \u2192 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 {\u0393 X Y : Type*} [definable_psh S \u0393] [definable_psh S X] [definable_psh S Y]\n  {f : \u0393 \u2192 X \u2192 Y} (hf : definable S f) {x : \u0393 \u2192 X} (hx : definable S x) :\n  definable S (\u03bb \u03b3, f \u03b3 (x \u03b3)) :=\nbegin\n  rw definable_fun at \u22a2 hf hx,\n  intros K \u03c6 h\u03c6,\n  change definable_psh.definable (\u03bb k, f (\u03c6 k) (x (\u03c6 k))),\n  specialize hf \u03c6 h\u03c6,\n  specialize hf K,\n  swap, { exact \u03bb k, (k, x (\u03c6 k)) },\n  exact hf \u27e8(Def.id K).is_definable, hx \u03c6 h\u03c6\u27e9\nend\n\nlemma definable_yoneda {K : Def S} {X : Type*} [definable_psh S X]\n  {f : K \u2192 X} : definable_psh.definable f \u2194 definable S f :=\nbegin\n  rw definable_fun,\n  split,\n  { intros h L \u03c6 h\u03c6,\n    exact definable_psh.definable_precomp \u27e8\u03c6, h\u03c6\u27e9 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 \u2192 Y \u2192 X \u00d7 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 \u03c6 and its proof of definability separately\n-- so that Lean has a better chance of guessing what's happening?\n\u03bb L g h L' g' h',\n\u27e8definable_psh.definable_precomp \u27e8\u03bb x, (g' x).fst, h'.1\u27e9 h.2, h'.2\u27e9\n\nlemma definable_fst {X Y : Type*} [definable_psh S X] [definable_psh S Y] :\n  definable S (prod.fst : X \u00d7 Y \u2192 X) :=\nbegin\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  exact h\u03c6.1\nend\n\nlemma definable_snd {X Y : Type*} [definable_psh S X] [definable_psh S Y] :\n  definable S (prod.snd : X \u00d7 Y \u2192 Y) :=\nbegin\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  exact h\u03c6.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 \u2192 X} (hf : definable S f) {g : W \u2192 Y} (hg : definable S g) :\n  definable S (\u03bb w, (f w, g w)) :=\nbegin\n  rw definable_fun at \u22a2 hf hg,\n  intros K \u03c6 h\u03c6,\n  exact \u27e8hf \u03c6 h\u03c6, hg \u03c6 h\u03c6\u27e9\nend\n\nlemma definable_fun\u2082 {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z]\n  {f : X \u2192 Y \u2192 Z} :\n  (\u2200 {L : Def S} (\u03c6 : L \u2192 X), definable S \u03c6 \u2192 definable S (f \u2218 \u03c6)) \u2194\n  (\u2200 {L : Def S} (\u03c6 : L \u2192 X \u00d7 Y), definable S \u03c6 \u2192 definable S (function.uncurry f \u2218 \u03c6)) :=\nbegin\n  split; intro H,\n  { intros L \u03c6 h\u03c6,\n    rw definable_fun at \u22a2,\n    intros K \u03c8 h\u03c8,\n    have : definable S (prod.fst \u2218 \u03c6),\n    { rw \u2190definable_yoneda at \u22a2 h\u03c6,\n      exact h\u03c6.1 },\n    specialize H (\u03bb l, (\u03c6 l).1) this,\n    rw definable_fun at H,\n    specialize H \u03c8 h\u03c8,\n    specialize H K,\n    swap, { exact \u03bb k, (k, (\u03c6 (\u03c8 k)).2) },\n    refine H \u27e8(Def.id K).is_definable, _\u27e9, clear H,\n    rw \u2190definable_yoneda at h\u03c6,\n    exact definable_psh.definable_precomp \u27e8\u03c8, h\u03c8\u27e9 h\u03c6.2 },\n  { intros L \u03c6 h\u03c6,\n    rw definable_fun,\n    intros K \u03c8 h\u03c8,\n    intros K' \u03c8' h\u03c8',\n    dsimp [function.uncurry, function.comp],\n    specialize H (\u03bb k', (\u03c6 (\u03c8 (\u03c8' k').1), (\u03c8' k').2)),\n    have : definable S (\u03bb k', (\u03c6 (\u03c8 (\u03c8' k').1), (\u03c8' k').2)),\n    { rw \u2190definable_yoneda at \u22a2 h\u03c6,\n      split,\n      { refine definable_psh.definable_precomp \u27e8\u03bb k', \u03c8 (\u03c8' k').fst, _\u27e9 h\u03c6,\n        exact (Hom.comp \u27e8\u03c8, h\u03c8\u27e9 \u27e8_, h\u03c8'.1\u27e9).is_definable },\n      { exact h\u03c8'.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 \u2192 Z) \u2192 (X \u2192 Y) \u2192 (X \u2192 Z)) :=\nbegin\n  -- TODO: Make these 4 lines a lemma.\n  rw definable_fun,\n  intros L\u2081 \u03c6\u2081 h\u03c6\u2081,\n  rw definable_yoneda at \u22a2 h\u03c6\u2081,\n  revert L\u2081,\n  -- end lemma\n  rw definable_fun\u2082,\n  rw definable_fun\u2082,\n  rintros L \u03c6 h\u03c6,\n  rw \u2190definable_yoneda at h\u03c6,\n  obtain \u27e8\u27e8h\u03c6\u2081, h\u03c6\u2082\u27e9, h\u03c6\u2083\u27e9 := h\u03c6,\n  rw definable_yoneda at h\u03c6\u2081 h\u03c6\u2082 h\u03c6\u2083,\n  dsimp [function.uncurry, function.comp],\n  exact h\u03c6\u2081.app_ctx (h\u03c6\u2082.app_ctx h\u03c6\u2083)\nend\n\nlemma definable.comp {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z]\n  {g : Y \u2192 Z} (hg : definable S g) {f : X \u2192 Y} (hf : definable S f) :\n  definable S (g \u2218 f) :=\ndefinable_app (definable_app definable_comp hg) hf\n\nlemma definable.comp_ctx {\u0393 X Y Z : Type*} [definable_psh S \u0393] [definable_psh S X] [definable_psh S Y] [definable_psh S Z]\n  {g : \u0393 \u2192 Y \u2192 Z} (hg : definable S g) {f : \u0393 \u2192 X \u2192 Y} (hf : definable S f) :\n  definable S (\u03bb \u03b3, g \u03b3 \u2218 f \u03b3) :=\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 \u00d7 Y \u2192 Z) \u2192 X \u2192 Y \u2192 Z) :=\nbegin\n  -- TODO: Make these 4 lines a lemma.\n  rw definable_fun,\n  intros L\u2081 \u03c6\u2081 h\u03c6\u2081,\n  rw definable_yoneda at \u22a2 h\u03c6\u2081,\n  revert L\u2081,\n  -- end lemma\n  rw definable_fun\u2082,\n  rw definable_fun\u2082,\n  rintros L \u03c6 h\u03c6,\n  rw \u2190definable_yoneda at h\u03c6,\n  obtain \u27e8\u27e8h\u03c6\u2081, h\u03c6\u2082\u27e9, h\u03c6\u2083\u27e9 := h\u03c6,\n  rw definable_yoneda at h\u03c6\u2081 h\u03c6\u2082 h\u03c6\u2083,\n  exact definable.app_ctx h\u03c6\u2081 (h\u03c6\u2082.prod_mk h\u03c6\u2083)\nend\n\ninstance Prop.definable_psh : definable_psh S Prop :=\n{ definable := \u03bb K s, S.def_coords s,\n  definable_precomp := \u03bb L K \u03c6 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 \u2192 Prop), by apply_instance\n\nlemma definable_and : definable S (\u2227) :=\nbegin\n  suffices : definable S (\u03bb r : Prop \u00d7 Prop, r.1 \u2227 r.2),\n  { exact definable_app definable_curry this },\n  rw definable_fun,\n  rintros K \u03c6 \u27e8h\u03c6\u2081, h\u03c6\u2082\u27e9,\n  exact h\u03c6\u2081.inter h\u03c6\u2082\nend\n\nlemma definable.and {W : Type*} [definable_psh S W]\n  {f : W \u2192 Prop} (hf : definable S f) {g : W \u2192 Prop} (hg : definable S g) :\n  definable S (\u03bb w, f w \u2227 g w) :=\ndefinable.app_ctx (definable.comp definable_and hf) hg\n\nlemma definable_inter {X : Type*} [definable_psh S X] :\n  definable S ((\u2229) : set X \u2192 set X \u2192 set X) :=\nbegin\n  suffices : definable S (\u03bb (r : set X \u00d7 set X) (x : X), r.1 x \u2227 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\u2081 \u03c6\u2081 h\u03c6\u2081,\n  rw definable_yoneda at \u22a2 h\u03c6\u2081,\n  revert L\u2081,\n  -- end lemma\n  rw definable_fun\u2082,\n  intros L \u03c6 h\u03c6,\n  rw \u2190definable_yoneda at h\u03c6,\n  obtain \u27e8\u27e8h\u03c6\u2081, h\u03c6\u2082\u27e9, h\u03c6\u2083\u27e9 := h\u03c6,\n  rw definable_yoneda at h\u03c6\u2081 h\u03c6\u2082 h\u03c6\u2083,\n  apply definable.and,\n  { exact h\u03c6\u2081.app_ctx h\u03c6\u2083 },\n  { exact h\u03c6\u2082.app_ctx h\u03c6\u2083 }\nend\n\n/-\ninstance foo {X Y : Type*} [definable_psh S X] [definable_psh S Y]\n  {p : X \u2192 Prop}\n  : definable_psh S (\u03a0 (x : X) (h : p x), Y) :=\nsorry\n-/\n\nlemma definable_definable {X : Type*} [definable_psh S X] :\n  definable S (definable S : X \u2192 Prop) :=\nbegin\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\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 (\u03c6 x),\n  apply definable_app,\n  { rw \u2190definable_yoneda, exact h\u03c6 },\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 (\u211d, +, *) 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 \u2192 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 \u2192 Sort*) :=\n(definable : \u03a0 {K : Def S} (x : K \u2192 X) (hx : definable_psh.definable x), (\u03a0 k, Y (x k)) \u2192 Prop)\n-- s.t. blah blah blah...\n\ninstance moo {X : Type*} {Y : X \u2192 Type*} [definable_psh S X] [definable_fam S Y] :\n  definable_psh S (\u03a0 (x : X), Y x) :=\nsorry\n\nconstant choice : \u03a0 (X : set R), X.nonempty \u2192 X\n\nexample : definable S (set.nonempty : set R \u2192 Prop) :=\nsorry\n\ninstance : definable_fam S (set.nonempty : set R \u2192 Prop) := sorry\n\ninstance pi {X : Type*} [definable_psh S X] {Y Z : X \u2192 Sort*} [definable_fam S Y] [definable_fam S Z] :\n  definable_fam S (\u03bb x, Y x \u2192 Z x) :=\nsorry\n\ninstance subtype {X : Type*} [definable_psh S X] : definable_fam S (\u03bb (s : set X), s) :=\nsorry\n\nexample : definable S ((\u03bb x hx\u2081 hx\u2082, choice x hx\u2081) : \u03a0 (X : set R), X.nonempty \u2192 X.nonempty \u2192 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 \u2192 R \u2192 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) 2016 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.data.list.basic\nimport Mathlib.Lean3Lib.init.data.char.basic\n \n\nuniverses l u_1 \n\nnamespace Mathlib\n\n/- In the VM, strings are implemented using a dynamic array and UTF-8 encoding.\n\n   TODO: we currently cannot mark string_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\n\nstructure string_imp \nwhere\n  data : List char\n\ndef string :=\n  string_imp\n\ndef list.as_string (s : List char) : string :=\n  string_imp.mk s\n\nnamespace string\n\n\nprotected instance has_lt : HasLess string :=\n  { Less := fun (s\u2081 s\u2082 : string) => string_imp.data s\u2081 < string_imp.data s\u2082 }\n\n/- Remark: this function has a VM builtin efficient implementation. -/\n\nprotected instance has_decidable_lt (s\u2081 : string) (s\u2082 : string) : Decidable (s\u2081 < s\u2082) :=\n  list.has_decidable_lt (string_imp.data s\u2081) (string_imp.data s\u2082)\n\nprotected instance has_decidable_eq : DecidableEq string :=\n  fun (_x : string) => sorry\n\ndef empty : string :=\n  string_imp.mk []\n\ndef length : string \u2192 \u2115 :=\n  sorry\n\n/- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\n\ndef push : string \u2192 char \u2192 string :=\n  sorry\n\n/- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\n\ndef append : string \u2192 string \u2192 string :=\n  sorry\n\n/- O(n) in the VM, where n is the length of the string -/\n\ndef to_list : string \u2192 List char :=\n  sorry\n\ndef fold {\u03b1 : Type u_1} (a : \u03b1) (f : \u03b1 \u2192 char \u2192 \u03b1) (s : string) : \u03b1 :=\n  list.foldl f a (to_list s)\n\n/- In the VM, the string iterator is implemented as a pointer to the string being iterated + index.\n\n   TODO: we currently cannot mark interator_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\n\nstructure iterator_imp \nwhere\n  fst : List char\n  snd : List char\n\ndef iterator :=\n  iterator_imp\n\ndef mk_iterator : string \u2192 iterator :=\n  sorry\n\nnamespace iterator\n\n\ndef curr : iterator \u2192 char :=\n  sorry\n\n/- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time\n   if it is. -/\n\ndef set_curr : iterator \u2192 char \u2192 iterator :=\n  sorry\n\ndef next : iterator \u2192 iterator :=\n  sorry\n\ndef prev : iterator \u2192 iterator :=\n  sorry\n\ndef has_next : iterator \u2192 Bool :=\n  sorry\n\ndef has_prev : iterator \u2192 Bool :=\n  sorry\n\ndef insert : iterator \u2192 string \u2192 iterator :=\n  sorry\n\ndef remove : iterator \u2192 \u2115 \u2192 iterator :=\n  sorry\n\n/- In the VM, `to_string` is a constant time operation. -/\n\ndef to_string : iterator \u2192 string :=\n  sorry\n\ndef to_end : iterator \u2192 iterator :=\n  sorry\n\ndef next_to_string : iterator \u2192 string :=\n  sorry\n\ndef prev_to_string : iterator \u2192 string :=\n  sorry\n\nprotected def extract_core : List char \u2192 List char \u2192 Option (List char) :=\n  sorry\n\ndef extract : iterator \u2192 iterator \u2192 Option string :=\n  sorry\n\nend iterator\n\n\nend string\n\n\n/- The following definitions do not have builtin support in the VM -/\n\nprotected instance string.inhabited : Inhabited string :=\n  { default := string.empty }\n\nprotected instance string.has_sizeof : SizeOf string :=\n  { sizeOf := string.length }\n\nprotected instance string.has_append : Append string :=\n  { append := string.append }\n\nnamespace string\n\n\ndef str : string \u2192 char \u2192 string :=\n  push\n\ndef is_empty (s : string) : Bool :=\n  to_bool (length s = 0)\n\ndef front (s : string) : char :=\n  iterator.curr (mk_iterator s)\n\ndef back (s : string) : char :=\n  iterator.curr (iterator.prev (iterator.to_end (mk_iterator s)))\n\ndef join (l : List string) : string :=\n  list.foldl (fun (r s : string) => r ++ s) empty l\n\ndef singleton (c : char) : string :=\n  push empty c\n\ndef intercalate (s : string) (ss : List string) : string :=\n  list.as_string (list.intercalate (to_list s) (list.map to_list ss))\n\nnamespace iterator\n\n\ndef nextn : iterator \u2192 \u2115 \u2192 iterator :=\n  sorry\n\ndef prevn : iterator \u2192 \u2115 \u2192 iterator :=\n  sorry\n\nend iterator\n\n\ndef pop_back (s : string) : string :=\n  iterator.prev_to_string (iterator.prev (iterator.to_end (mk_iterator s)))\n\ndef popn_back (s : string) (n : \u2115) : string :=\n  iterator.prev_to_string (iterator.prevn (iterator.to_end (mk_iterator s)) n)\n\ndef backn (s : string) (n : \u2115) : string :=\n  iterator.next_to_string (iterator.prevn (iterator.to_end (mk_iterator s)) n)\n\nend string\n\n\nprotected def char.to_string (c : char) : string :=\n  string.singleton c\n\ndef string.to_nat (s : string) : \u2115 :=\n  to_nat_core (string.mk_iterator s) (string.length s) 0\n\nnamespace string\n\n\ntheorem empty_ne_str (c : char) (s : string) : empty \u2260 str s c := sorry\n\ntheorem str_ne_empty (c : char) (s : string) : str s c \u2260 empty :=\n  ne.symm (empty_ne_str c s)\n\ntheorem str_ne_str_left {c\u2081 : char} {c\u2082 : char} (s\u2081 : string) (s\u2082 : string) : c\u2081 \u2260 c\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082 := sorry\n\ntheorem str_ne_str_right (c\u2081 : char) (c\u2082 : char) {s\u2081 : string} {s\u2082 : string} : s\u2081 \u2260 s\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082 := 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/string/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.06465348925734801, "lm_q1q2_score": 0.02163237484568493}}
{"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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : PProd \u03b1 \u03b2} :\n    { fst := pprod.fst p, snd := pprod.snd p } = p :=\n  pprod.cases_on p fun (a : \u03b1) (b : \u03b2) => 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": "/-\nCopyright (c) 2020 Sebastian Ullrich. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\n\nimport Lean.PrettyPrinter.Delaborator.Basic\nimport Lean.Parser\n\nnamespace Lean.PrettyPrinter.Delaborator\nopen Lean.Meta\nopen Lean.Parser.Term\n\n@[builtinDelab fvar]\ndef delabFVar : Delab := do\nlet Expr.fvar id _ \u2190 getExpr | unreachable!\ntry\n  let l \u2190 getLocalDecl id\n  pure $ mkIdent l.userName\ncatch _ =>\n  -- loose free variable, use internal name\n  pure $ mkIdent id\n\n-- loose bound variable, use pseudo syntax\n@[builtinDelab bvar]\ndef delabBVar : Delab := do\n  let Expr.bvar idx _ \u2190 getExpr | unreachable!\n  pure $ mkIdent $ Name.mkSimple $ \"#\" ++ toString idx\n\n@[builtinDelab mvar]\ndef delabMVar : Delab := do\n  let Expr.mvar n _ \u2190 getExpr | unreachable!\n  let mvarDecl \u2190 getMVarDecl n\n  let n :=\n    match mvarDecl.userName with\n    | Name.anonymous => n.replacePrefix `_uniq `m\n    | n => n\n  `(?$(mkIdent n))\n\n@[builtinDelab sort]\ndef delabSort : Delab := do\n  let Expr.sort l _ \u2190 getExpr | unreachable!\n  match l with\n  | Level.zero _ => `(Prop)\n  | Level.succ (Level.zero _) _ => `(Type)\n  | _ => match l.dec with\n    | some l' => `(Type $(Level.quote l' max_prec))\n    | none    => `(Sort $(Level.quote l max_prec))\n\n-- find shorter names for constants, in reverse to Lean.Elab.ResolveName\n\nprivate def unresolveQualifiedName (ns : Name) (c : Name) : DelabM Name := do\n  let c' := c.replacePrefix ns Name.anonymous;\n  let env \u2190 getEnv\n  guard $ c' != c && !c'.isAnonymous && (!c'.isAtomic || !isProtected env c)\n  pure c'\n\nprivate def unresolveUsingNamespace (c : Name) : Name \u2192 DelabM Name\n  | ns@(Name.str p _ _) => unresolveQualifiedName ns c <|> unresolveUsingNamespace c p\n  | _ => failure\n\nprivate def unresolveOpenDecls (c : Name) : List OpenDecl \u2192 DelabM Name\n  | [] => failure\n  | OpenDecl.simple ns exs :: openDecls =>\n    let c' := c.replacePrefix ns Name.anonymous\n    if c' != c && exs.elem c' then unresolveOpenDecls c openDecls\n    else\n      unresolveQualifiedName ns c <|> unresolveOpenDecls c openDecls\n  | OpenDecl.explicit openedId resolvedId :: openDecls =>\n    guard (c == resolvedId) *> pure openedId <|> unresolveOpenDecls c openDecls\n\n-- NOTE: not a registered delaborator, as `const` is never called (see [delab] description)\ndef delabConst : Delab := do\n  let Expr.const c ls _ \u2190 getExpr | unreachable!\n  let c\u2080 := c\n  let mut c \u2190 if (\u2190 getPPOption getPPFullNames) then pure c else\n    let ctx \u2190 read\n    let env \u2190 getEnv\n    let as := getRevAliases env c\n    -- might want to use a more clever heuristic such as selecting the shortest alias...\n    let c := as.headD c\n    unresolveUsingNamespace c ctx.currNamespace <|> unresolveOpenDecls c ctx.openDecls <|> pure c\n  unless (\u2190 getPPOption getPPPrivateNames) do\n    c := (privateToUserName? c).getD c\n  let ppUnivs \u2190 getPPOption getPPUniverses\n  if ls.isEmpty || !ppUnivs then\n    if (\u2190 getLCtx).usesUserName c then\n      -- `c` is also a local declaration\n      if c == c\u2080 then\n        -- `c` is the fully qualified named. So, we append the `_root_` prefix\n        c := `_root_ ++ c\n      else\n        c := c\u2080\n    return mkIdent c\n  else\n    `($(mkIdent c).{$[$(ls.toArray.map quote)],*})\n\ninductive ParamKind where\n  | explicit\n  -- combines implicit params, optParams, and autoParams\n  | implicit (defVal : Option Expr)\n\n/-- Return array with n-th element set to kind of n-th parameter of `e`. -/\ndef getParamKinds (e : Expr) : MetaM (Array ParamKind) := do\n  let t \u2190 inferType e\n  forallTelescopeReducing t fun params _ =>\n    params.mapM fun param => do\n      let l \u2190 getLocalDecl param.fvarId!\n      match l.type.getOptParamDefault? with\n      | some val => pure $ ParamKind.implicit val\n      | _ =>\n        if l.type.isAutoParam || !l.binderInfo.isExplicit then\n          pure $ ParamKind.implicit none\n        else\n          pure ParamKind.explicit\n\n@[builtinDelab app]\ndef delabAppExplicit : Delab := do\n  let (fnStx, argStxs) \u2190 withAppFnArgs\n    (do\n      let fn \u2190 getExpr\n      let stx \u2190 if fn.isConst then delabConst else delab\n      let paramKinds \u2190 liftM <| getParamKinds fn <|> pure #[]\n      let stx \u2190 if paramKinds.any (fun | ParamKind.explicit => false | _ => true) then `(@$stx) else pure stx\n      pure (stx, #[]))\n    (fun \u27e8fnStx, argStxs\u27e9 => do\n      let argStx \u2190 delab\n      pure (fnStx, argStxs.push argStx))\n  Syntax.mkApp fnStx argStxs\n\n@[builtinDelab app]\ndef delabAppImplicit : Delab := whenNotPPOption getPPExplicit do\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (do\n      let fn \u2190 getExpr\n      let stx \u2190 if fn.isConst then delabConst else delab\n      let paramKinds \u2190 liftM (getParamKinds fn <|> pure #[])\n      pure (stx, paramKinds.toList, #[]))\n    (fun (fnStx, paramKinds, argStxs) => do\n      let arg \u2190 getExpr;\n      let implicit : Bool := match paramKinds with -- TODO: check why we need `: Bool` here\n        | [ParamKind.implicit (some v)] => !v.hasLooseBVars && v == arg\n        | ParamKind.implicit none :: _  => true\n        | _                             => false\n      if implicit then\n        pure (fnStx, paramKinds.tailD [], argStxs)\n      else do\n        let argStx \u2190 delab\n        pure (fnStx, paramKinds.tailD [], argStxs.push argStx))\n  Syntax.mkApp fnStx argStxs\n\n@[builtinDelab app]\ndef delabAppWithUnexpander : Delab := whenPPOption getPPNotation do\n  let Expr.const c _ _ \u2190 pure (\u2190 getExpr).getAppFn | failure\n  let stx \u2190 delabAppImplicit\n  match stx with\n  | `($cPP:ident $args*) => do go c stx\n  | `($cPP:ident) => do go c stx\n  | _ => pure stx\nwhere\n  go c stx := do\n    let some (f::_) \u2190 pure <| (appUnexpanderAttribute.ext.getState (\u2190 getEnv)).table.find? c\n      | pure stx\n    let EStateM.Result.ok stx _ \u2190 f stx |>.run ()\n      | pure stx\n    pure stx\n\n/-- State for `delabAppMatch` and helpers. -/\nstructure AppMatchState where\n  info      : MatcherInfo\n  matcherTy : Expr\n  params    : Array Expr := #[]\n  hasMotive : Bool := false\n  discrs    : Array Syntax := #[]\n  varNames  : Array (Array Name) := #[]\n  rhss      : Array Syntax := #[]\n  -- additional arguments applied to the result of the `match` expression\n  moreArgs  : Array Syntax := #[]\n/--\n  Extract arguments of motive applications from the matcher type.\n  For the example below: `#[#[`([])], #[`(a::as)]]` -/\nprivate partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) :=\n  withReader (fun ctx => { ctx with inPattern := true }) do\n    let ty \u2190 instantiateForall st.matcherTy st.params\n    forallTelescope ty fun params _ => do\n      -- skip motive and discriminators\n      let alts := Array.ofSubarray $ params[1 + st.discrs.size:]\n      alts.mapIdxM fun idx alt => do\n        let ty \u2190 inferType alt\n        withReader ({ \u00b7 with expr := ty }) $\n          usingNames st.varNames[idx] do\n            withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (\u2190 delab))\nwhere\n  usingNames {\u03b1} (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    usingNamesAux 0 varNames x\n  usingNamesAux {\u03b1} (i : Nat) (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    if i < varNames.size then\n      withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x\n    else\n      x\n\n/-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/\nprivate def skippingBinders {\u03b1} (numParams : Nat) (x : Array Name \u2192 DelabM \u03b1) : DelabM \u03b1 :=\n  loop numParams #[]\nwhere\n  loop : Nat \u2192 Array Name \u2192 DelabM \u03b1\n    | 0,   varNames => x varNames\n    | n+1, varNames => do\n      let varName \u2190 (\u2190 getExpr).bindingName!.eraseMacroScopes\n      -- Pattern variables cannot shadow each other\n      if varNames.contains varName then\n        let varName := (\u2190 getLCtx).getUnusedName varName\n        withBindingBody varName do\n          loop n (varNames.push varName)\n      else\n        withBindingBodyUnusedName fun id => do\n          loop n (varNames.push id.getId)\n\n/--\n  Delaborate applications of \"matchers\" such as\n  ```\n  List.map.match_1 : {\u03b1 : Type _} \u2192\n    (motive : List \u03b1 \u2192 Sort _) \u2192\n      (x : List \u03b1) \u2192 (Unit \u2192 motive List.nil) \u2192 ((a : \u03b1) \u2192 (as : List \u03b1) \u2192 motive (a :: as)) \u2192 motive x\n  ```\n-/\n@[builtinDelab app]\ndef delabAppMatch : Delab := whenPPOption getPPNotation do\n  -- incrementally fill `AppMatchState` from arguments\n  let st \u2190 withAppFnArgs\n    (do\n      let (Expr.const c us _) \u2190 getExpr | failure\n      let (some info) \u2190 getMatcherInfo? c | failure\n      { matcherTy := (\u2190 getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState })\n    (fun st => do\n      if st.params.size < st.info.numParams then\n        pure { st with params := st.params.push (\u2190 getExpr) }\n      else if !st.hasMotive then\n        -- discard motive argument\n        pure { st with hasMotive := true }\n      else if st.discrs.size < st.info.numDiscrs then\n        pure { st with discrs := st.discrs.push (\u2190 delab) }\n      else if st.rhss.size < st.info.altNumParams.size then\n        /- We save the variables names here to be able to implement safe_shadowing.\n           The pattern delaboration must use the names saved here. -/\n        let (varNames, rhs) \u2190 skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do\n          let rhs \u2190 delab\n          return (varNames, rhs)\n        pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }\n      else\n        pure { st with moreArgs := st.moreArgs.push (\u2190 delab) })\n\n  if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then\n    -- underapplied\n    failure\n\n  match st.discrs, st.rhss with\n  | #[discr], #[] =>\n    let stx \u2190 `(nomatch $discr)\n    Syntax.mkApp stx st.moreArgs\n  | _,        #[] => failure\n  | _,        _   =>\n    let pats \u2190 delabPatterns st\n    let stx \u2190 `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*)\n    Syntax.mkApp stx st.moreArgs\n\n@[builtinDelab mdata]\ndef delabMData : Delab := do\n  if let some _ := Lean.Meta.Match.inaccessible? (\u2190 getExpr) then\n    let s \u2190 withMDataExpr delab\n    if (\u2190 read).inPattern then\n      `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns\n    else\n      return s\n  else\n    -- only interpret `pp.` values by default\n    let Expr.mdata m _ _ \u2190 getExpr | unreachable!\n    let mut posOpts := (\u2190 read).optionsPerPos\n    let pos := (\u2190 read).pos\n    for (k, v) in m do\n      if (`pp).isPrefixOf k then\n        let opts := posOpts.find? pos |>.getD {}\n        posOpts := posOpts.insert pos (opts.insert k v)\n    withReader ({ \u00b7 with optionsPerPos := posOpts }) do\n      withMDataExpr delab\n\n/--\nCheck for a `Syntax.ident` of the given name anywhere in the tree.\nThis is usually a bad idea since it does not check for shadowing bindings,\nbut in the delaborator we assume that bindings are never shadowed.\n-/\npartial def hasIdent (id : Name) : Syntax \u2192 Bool\n  | Syntax.ident _ _ id' _ => id == id'\n  | Syntax.node _ args     => args.any (hasIdent id)\n  | _                      => false\n\n/--\nReturn `true` iff current binder should be merged with the nested\nbinder, if any, into a single binder group:\n* both binders must have same binder info and domain\n* they cannot be inst-implicit (`[a b : A]` is not valid syntax)\n* `pp.binder_types` must be the same value for both terms\n* prefer `fun a b` over `fun (a b)`\n-/\nprivate def shouldGroupWithNext : DelabM Bool := do\n  let e \u2190 getExpr\n  let ppEType \u2190 getPPOption getPPBinderTypes;\n  let go (e' : Expr) := do\n    let ppE'Type \u2190 withBindingBody `_ $ getPPOption getPPBinderTypes\n    pure $ e.binderInfo == e'.binderInfo &&\n      e.bindingDomain! == e'.bindingDomain! &&\n      e'.binderInfo != BinderInfo.instImplicit &&\n      ppEType == ppE'Type &&\n      (e'.binderInfo != BinderInfo.default || ppE'Type)\n  match e with\n  | Expr.lam _ _     e'@(Expr.lam _ _ _ _) _     => go e'\n  | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'\n  | _ => pure false\n\nprivate partial def delabBinders (delabGroup : Array Syntax \u2192 Syntax \u2192 Delab) : optParam (Array Syntax) #[] \u2192 Delab\n  -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished\n  -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping\n  -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.\n  | curNames => do\n    if (\u2190 shouldGroupWithNext) then\n      -- group with nested binder => recurse immediately\n      withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)\n    else\n      -- don't group => delab body and prepend current binder group\n      let (stx, stxN) \u2190 withBindingBodyUnusedName fun stxN => do (\u2190 delab, stxN)\n      delabGroup (curNames.push stxN) stx\n\n@[builtinDelab lam]\ndef delabLam : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let stxT \u2190 withBindingDomain delab\n    let ppTypes \u2190 getPPOption getPPBinderTypes\n    let expl \u2190 getPPOption getPPExplicit\n    -- leave lambda implicit if possible\n    let blockImplicitLambda := expl ||\n      e.binderInfo == BinderInfo.default ||\n      Elab.Term.blockImplicitLambda stxBody ||\n      curNames.any (fun n => hasIdent n.getId stxBody);\n    if !blockImplicitLambda then\n      pure stxBody\n    else\n      let group \u2190 match e.binderInfo, ppTypes with\n        | BinderInfo.default,     true   =>\n          -- \"default\" binder group is the only one that expects binder names\n          -- as a term, i.e. a single `Syntax.ident` or an application thereof\n          let stxCurNames \u2190\n            if curNames.size > 1 then\n              `($(curNames.get! 0) $(curNames.eraseIdx 0)*)\n            else\n              pure $ curNames.get! 0;\n          `(funBinder| ($stxCurNames : $stxT))\n        | BinderInfo.default,     false  => pure curNames.back  -- here `curNames.size == 1`\n        | BinderInfo.implicit,    true   => `(funBinder| {$curNames* : $stxT})\n        | BinderInfo.implicit,    false  => `(funBinder| {$curNames*})\n        | BinderInfo.instImplicit, _     => `(funBinder| [$curNames.back : $stxT])  -- here `curNames.size == 1`\n        | _                      , _     => unreachable!;\n      match stxBody with\n      | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody)\n      | _                                 => `(fun $group => $stxBody)\n\n@[builtinDelab forallE]\ndef delabForall : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let prop \u2190 try isProp e catch _ => false\n    let stxT \u2190 withBindingDomain delab\n    let group \u2190 match e.binderInfo with\n    | BinderInfo.implicit     => `(bracketedBinderF|{$curNames* : $stxT})\n    -- here `curNames.size == 1`\n    | BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT])\n    | _                       =>\n      -- heuristic: use non-dependent arrows only if possible for whole group to avoid\n      -- noisy mix like `(\u03b1 : Type) \u2192 Type \u2192 (\u03b3 : Type) \u2192 ...`.\n      let dependent := curNames.any $ fun n => hasIdent n.getId stxBody\n      -- NOTE: non-dependent arrows are available only for the default binder info\n      if dependent then\n        if prop && !(\u2190 getPPOption getPPBinderTypes) then\n          return \u2190 `(\u2200 $curNames:ident*, $stxBody)\n        else\n          `(bracketedBinderF|($curNames* : $stxT))\n      else\n        return \u2190 curNames.foldrM (fun _ stxBody => `($stxT \u2192 $stxBody)) stxBody\n    if prop then\n      match stxBody with\n      | `(\u2200 $groups*, $stxBody) => `(\u2200 $group $groups*, $stxBody)\n      | _                       => `(\u2200 $group, $stxBody)\n    else\n      `($group:bracketedBinder \u2192 $stxBody)\n\n@[builtinDelab letE]\ndef delabLetE : Delab := do\n  let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n  let n \u2190 getUnusedName n b\n  let stxT \u2190 descend t 0 delab\n  let stxV \u2190 descend v 1 delab\n  let stxB \u2190 withLetDecl n t v fun fvar =>\n    let b := b.instantiate1 fvar\n    descend b 2 delab\n  `(let $(mkIdent n) : $stxT := $stxV; $stxB)\n\n@[builtinDelab lit]\ndef delabLit : Delab := do\n  let Expr.lit l _ \u2190 getExpr | unreachable!\n  match l with\n  | Literal.natVal n => pure $ quote n\n  | Literal.strVal s => pure $ quote s\n\n-- `@OfNat.ofNat _ n _` ~> `n`\n@[builtinDelab app.OfNat.ofNat]\ndef delabOfNat : Delab := whenPPOption getPPCoercions do\n  let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) \u2190 getExpr | failure\n  return quote n\n\n-- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true`\n@[builtinDelab app.OfScientific.ofScientific]\ndef delabOfScientific : Delab := whenPPOption getPPCoercions do\n  let expr \u2190 getExpr\n  guard <| expr.getAppNumArgs == 5\n  let Expr.lit (Literal.natVal m) _ \u2190 pure (expr.getArg! 2) | failure\n  let Expr.lit (Literal.natVal e) _ \u2190 pure (expr.getArg! 4) | failure\n  let s \u2190 match expr.getArg! 3 with\n    | Expr.const `Bool.true _ _  => pure true\n    | Expr.const `Bool.false _ _ => pure false\n    | _ => failure\n  let str  := toString m\n  if s && e == str.length then\n    return Syntax.mkScientificLit (\"0.\" ++ str)\n  else if s && e < str.length then\n    let mStr := str.extract 0 (str.length - e)\n    let eStr := str.extract (str.length - e) str.length\n    return Syntax.mkScientificLit (mStr ++ \".\" ++ eStr)\n  else\n    return Syntax.mkScientificLit (str ++ \"e\" ++ (if s then \"-\" else \"\") ++ toString e)\n\n/--\nDelaborate a projection primitive. These do not usually occur in\nuser code, but are pretty-printed when e.g. `#print`ing a projection\nfunction.\n-/\n@[builtinDelab proj]\ndef delabProj : Delab := do\n  let Expr.proj _ idx _ _ \u2190 getExpr | unreachable!\n  let e \u2190 withProj delab\n  -- not perfectly authentic: elaborates to the `idx`-th named projection\n  -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual\n  -- `proj`.\n  let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1));\n  `($(e).$idx:fieldIdx)\n\n/-- Delaborate a call to a projection function such as `Prod.fst`. -/\n@[builtinDelab app]\ndef delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do\n  let e@(Expr.app fn _ _) \u2190 getExpr | failure\n  let Expr.const c@(Name.str _ f _) _ _ \u2190 pure fn.getAppFn | failure\n  let env \u2190 getEnv\n  let some info \u2190 pure $ env.getProjectionFnInfo? c | failure\n  -- can't use with classes since the instance parameter is implicit\n  guard $ !info.fromClass\n  -- projection function should be fully applied (#struct params + 1 instance parameter)\n  -- TODO: support over-application\n  guard $ e.getAppNumArgs == info.nparams + 1\n  -- If pp.explicit is true, and the structure has parameters, we should not\n  -- use field notation because we will not be able to see the parameters.\n  let expl \u2190 getPPOption getPPExplicit\n  guard $ !expl || info.nparams == 0\n  let appStx \u2190 withAppArg delab\n  `($(appStx).$(mkIdent f):ident)\n\n@[builtinDelab app]\ndef delabStructureInstance : Delab := whenPPOption getPPStructureInstances do\n  let env \u2190 getEnv\n  let e \u2190 getExpr\n  let some s \u2190 pure $ e.isConstructorApp? env | failure\n  guard $ isStructure env s.induct;\n  /- If implicit arguments should be shown, and the structure has parameters, we should not\n     pretty print using { ... }, because we will not be able to see the parameters. -/\n  let explicit \u2190 getPPOption getPPExplicit\n  guard !(explicit && s.numParams > 0)\n  let fieldNames := getStructureFields env s.induct\n  let (_, fields) \u2190 withAppFnArgs (pure (0, #[])) fun \u27e8idx, fields\u27e9 => do\n      if idx < s.numParams then\n        pure (idx + 1, fields)\n      else\n        let val \u2190 delab\n        let field \u2190 `(structInstField|$(mkIdent <| fieldNames.get! (idx - s.numParams)):ident := $val)\n        pure (idx + 1, fields.push field)\n  let lastField := fields[fields.size - 1]\n  let fields := fields.pop\n  let ty \u2190\n    if (\u2190 getPPOption getPPStructureInstanceType) then\n      let ty \u2190 inferType e\n      -- `ty` is not actually part of `e`, but since `e` must be an application or constant, we know that\n      -- index 2 is unused.\n      pure <| some (\u2190 descend ty 2 delab)\n    else pure <| none\n  `({ $[$fields, ]* $lastField $[: $ty]? })\n\n@[builtinDelab app.Prod.mk]\ndef delabTuple : Delab := whenPPOption getPPNotation do\n  let e \u2190 getExpr\n  guard $ e.getAppNumArgs == 4\n  let a \u2190 withAppFn $ withAppArg delab\n  let b \u2190 withAppArg delab\n  match b with\n  | `(($b, $bs,*)) => `(($a, $b, $bs,*))\n  | _              => `(($a, $b))\n\n-- abbrev coe {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeT \u03b1 a \u03b2] : \u03b2\n@[builtinDelab app.coe]\ndef delabCoe : Delab := whenPPOption getPPCoercions do\n  let e \u2190 getExpr\n  guard $ e.getAppNumArgs >= 4\n  -- delab as application, then discard function\n  let stx \u2190 delabAppImplicit\n  match stx with\n  | `($fn $arg)   => arg\n  | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*)\n  | _             => failure\n\n-- abbrev coeFun {\u03b1 : Sort u} {\u03b3 : \u03b1 \u2192 Sort v} (a : \u03b1) [CoeFun \u03b1 \u03b3] : \u03b3 a\n@[builtinDelab app.coeFun]\ndef delabCoeFun : Delab := delabCoe\n\n@[builtinDelab app.List.nil]\ndef delabNil : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 1\n  `([])\n\n@[builtinDelab app.List.cons]\ndef delabConsList : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 3\n  let x \u2190 withAppFn (withAppArg delab)\n  match (\u2190 withAppArg delab) with\n  | `([])      => `([$x])\n  | `([$xs,*]) => `([$x, $xs,*])\n  | _          => failure\n\n@[builtinDelab app.List.toArray]\ndef delabListToArray : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 2\n  match (\u2190 withAppArg delab) with\n  | `([$xs,*]) => `(#[$xs,*])\n  | _         => failure\n\n@[builtinDelab app.ite]\ndef delabIte : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 5\n  let c \u2190 withAppFn $ withAppFn $ withAppFn $ withAppArg delab\n  let t \u2190 withAppFn $ withAppArg delab\n  let e \u2190 withAppArg delab\n  `(if $c then $t else $e)\n\n@[builtinDelab app.dite]\ndef delabDIte : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 5\n  let c \u2190 withAppFn $ withAppFn $ withAppFn $ withAppArg delab\n  let (t, h) \u2190 withAppFn $ withAppArg $ delabBranch none\n  let (e, _) \u2190 withAppArg $ delabBranch h\n  `(if $(mkIdent h):ident : $c then $t else $e)\nwhere\n  delabBranch (h? : Option Name) : DelabM (Syntax \u00d7 Name) := do\n    let e \u2190 getExpr\n    guard e.isLambda\n    let h \u2190 match h? with\n      | some h => return (\u2190 withBindingBody h delab, h)\n      | none   => withBindingBodyUnusedName fun h => do\n        return (\u2190 delab, h.getId)\n\n@[builtinDelab app.namedPattern]\ndef delabNamedPattern : Delab := do\n  guard $ (\u2190 getExpr).getAppNumArgs == 3\n  let x \u2190 withAppFn $ withAppArg delab\n  let p \u2190 withAppArg delab\n  guard x.isIdent\n  `($x:ident@$p:term)\n\npartial def delabDoElems : DelabM (List Syntax) := do\n  let e \u2190 getExpr\n  if e.isAppOfArity `Bind.bind 6 then\n    -- Bind.bind.{u, v} : {m : Type u \u2192 Type v} \u2192 [self : Bind m] \u2192 {\u03b1 \u03b2 : Type u} \u2192 m \u03b1 \u2192 (\u03b1 \u2192 m \u03b2) \u2192 m \u03b2\n    let ma \u2190 withAppFn $ withAppArg delab\n    withAppArg do\n      match (\u2190 getExpr) with\n      | Expr.lam _ _ body _ =>\n        withBindingBodyUnusedName fun n => do\n          if body.hasLooseBVars then\n            prependAndRec `(doElem|let $n:term \u2190 $ma)\n          else\n            prependAndRec `(doElem|$ma:term)\n      | _ => failure\n  else if e.isLet then\n    let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxT \u2190 descend t 0 delab\n    let stxV \u2190 descend v 1 delab\n    withLetDecl n t v fun fvar =>\n      let b := b.instantiate1 fvar\n      descend b 2 $\n        prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV)\n  else\n    let stx \u2190 delab\n    [\u2190`(doElem|$stx:term)]\n  where\n    prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems\n\n@[builtinDelab app.Bind.bind]\ndef delabDo : Delab := whenPPOption getPPNotation do\n  guard <| (\u2190 getExpr).isAppOfArity `Bind.bind 6\n  let elems \u2190 delabDoElems\n  let items \u2190 elems.toArray.mapM (`(doSeqItem|$(\u00b7):doElem))\n  `(do $items:doSeqItem*)\n\n@[builtinDelab app.sorryAx]\ndef delabSorryAx : Delab := whenPPOption getPPNotation do\n  guard <| (\u2190 getExpr).isAppOfArity ``sorryAx 2\n  `(sorry)\n\n@[builtinDelab app.Eq.ndrec]\ndef delabEqNDRec : Delab := whenPPOption getPPNotation do\n  guard <| (\u2190 getExpr).getAppNumArgs == 6\n  -- Eq.ndrec.{u1, u2} : {\u03b1 : Sort u2} \u2192 {a : \u03b1} \u2192 {motive : \u03b1 \u2192 Sort u1} \u2192 (m : motive a) \u2192 {b : \u03b1} \u2192 (h : a = b) \u2192 motive b\n  let m \u2190 withAppFn <| withAppFn <| withAppArg delab\n  let h \u2190 withAppArg delab\n  `($h \u25b8 $m)\n\n@[builtinDelab app.Eq.rec]\ndef delabEqRec : Delab :=\n  -- relevant signature parts as in `Eq.ndrec`\n  delabEqNDRec\n\ndef reifyName : Expr \u2192 DelabM Name\n  | Expr.const ``Lean.Name.anonymous .. => Name.anonymous\n  | Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => do\n    (\u2190 reifyName n).mkStr s\n  | Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => do\n    (\u2190 reifyName n).mkNum i\n  | _ => failure\n\n@[builtinDelab app.Lean.Name.mkStr]\ndef delabNameMkStr : Delab := whenPPOption getPPNotation do\n  let n \u2190 reifyName (\u2190 getExpr)\n  -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version\n  mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{n}\"]\n\n@[builtinDelab app.Lean.Name.mkNum]\ndef delabNameMkNum : Delab := delabNameMkStr\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/Builtins.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.06954174354163817, "lm_q1q2_score": 0.02160622911733396}}
{"text": "import tactic.interactive\n\nexample (b : bool) (h : b = tt) : true :=\nbegin\n  let b\u2081 : bool := b,\n  /-\n  This test shows that `tactic.revert_target_deps`\n  will revert `b\u2081` 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\u2081`,\n  even though `b` doesn't occur directly in the `have` statement below.\n  -/\n  have : \u2200 b\u2082 : bool, b\u2082 \u2260 b\u2081 \u2192 b\u2082 = ff,\n  { revert_target_deps,\n    tactic.interactive.guard_target\n      ``(\u2200 (b : bool), b = tt \u2192 (let b\u2081 : bool := b in \u2200 (b\u2082 : bool), b\u2082 \u2260 b\u2081 \u2192 b\u2082 = 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 : \u2124) : cochain_complex C \u2124 \u2964 cochain_complex C \u2124 :=\n{ obj := \u03bb K,\n  { X := \u03bb i, K.X (i+n),\n    d := \u03bb i j, cochain_complex.hom_complex.\u03b5 n \u2022 K.d _ _,\n    shape' := \u03bb i j hij, begin\n      rw [K.shape, smul_zero],\n      intro hij',\n      apply hij,\n      dsimp [complex_shape.up] at hij' \u22a2,\n      linarith,\n    end, },\n  map := \u03bb K\u2081 K\u2082 \u03c6,\n  { f := \u03bb i, \u03c6.f _, }, }\n\nvariable {C}\n\n@[simp]\nlemma X_iso_of_eq_of_shift_functor (K : cochain_complex C \u2124) (n : \u2124) {i i' : \u2124} (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 \u2124) (n i m : \u2124) (hm : m = i + n) :\n  ((shift_functor C n).obj K).X i \u2245 K.X m :=\nX_iso_of_eq K hm.symm\n\nvariable (C)\n\n@[simp]\ndef shift_functor_congr {n n' : \u2124} (h : n = n') :\n  shift_functor C n \u2245 shift_functor C n' :=\nnat_iso.of_components\n  (\u03bb K, hom.iso_of_components (\u03bb i, K.X_iso_of_eq (by subst h))\n  (\u03bb i j hij, by { dsimp, simp [h], })) (\u03bb K\u2081 K\u2082 \u03c6, by { ext, dsimp, simp, })\n\n@[simps]\ndef shift_functor_zero' (n : \u2124) (h : n = 0) :\n  shift_functor C n \u2245 \ud835\udfed _ :=\nnat_iso.of_components (\u03bb K, hom.iso_of_components\n  (\u03bb i, K.shift_functor_obj_X_iso _ _ _ (by linarith))\n    (by { subst h, tidy, })) (by tidy)\n\n@[simps]\ndef shift_functor_add' (n\u2081 n\u2082 n\u2081\u2082 : \u2124) (h : n\u2081\u2082 = n\u2081 + n\u2082) :\n  shift_functor C n\u2081 \u22d9 shift_functor C n\u2082 \u2245 shift_functor C n\u2081\u2082 :=\nnat_iso.of_components\n  (\u03bb K, hom.iso_of_components (\u03bb i, K.X_iso_of_eq (by linarith))\n  (\u03bb 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, \u2190 mul_smul, \u2190 cochain_complex.hom_complex.\u03b5_add, add_comm n\u2081],\n  end)) (by tidy)\n\ninstance : has_shift (cochain_complex C \u2124) \u2124 :=\nhas_shift_mk _ _\n{ F := shift_functor C,\n  \u03b5 := (shift_functor_zero' C _ rfl).symm,\n  \u03bc := \u03bb n\u2081 n\u2082, shift_functor_add' C n\u2081 n\u2082 _ rfl,\n  associativity := \u03bb n\u2081 n\u2082 n\u2083 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 \u2124} (\u03c6 : K \u27f6 L) (n p : \u2124) :\n  ((category_theory.shift_functor (cochain_complex C \u2124) n).map \u03c6).f p = \u03c6.f (p+n) := rfl\n\n@[simp]\nlemma shift_functor_obj_d' (K : cochain_complex C \u2124) (n i j : \u2124) :\n  ((category_theory.shift_functor (cochain_complex C \u2124) n).obj K).d i j =\n    cochain_complex.hom_complex.\u03b5 n \u2022 K.d _ _ := rfl\n\nlemma shift_functor_add_inv_app_f (K : cochain_complex C \u2124) (a b n : \u2124) :\n  ((shift_functor_add (cochain_complex C \u2124) a b).inv.app K : _ \u27f6 _).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 \u2124) (a b n : \u2124) :\n  ((shift_functor_add (cochain_complex C \u2124) a b).hom.app K : _ \u27f6 _).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 \u2124) a b).inv.app K : _ \u27f6 _).f n),\n  { rw shift_functor_add_inv_app_f,\n    apply_instance, },\n  rw [\u2190 cancel_mono (((shift_functor_add (cochain_complex C \u2124) a b).inv.app K : _ \u27f6 _).f n),\n    \u2190 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 \u2124) (a b n : \u2124) :\n  ((shift_functor_add_comm (cochain_complex C \u2124) a b).hom.app K : _ \u27f6 _).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 : \u2124) (h : c = a + b) :\n  category_theory.shift_functor_add' (cochain_complex C \u2124) 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 : \u2124) :\n  category_theory.shift_functor_add (cochain_complex C \u2124) a b =\n    (shift_functor_add' C a b _ rfl).symm :=\nbegin\n  ext1,\n  rw \u2190 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 \u2124) \u2124) =\n    (shift_functor_zero' C 0 rfl) :=\nbegin\n  change (category_theory.shift_functor_zero (cochain_complex C \u2124) \u2124).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 \u2964 D) [preadditive D] [functor.additive F]\n\ndef map_cochain_complex_shift_iso (n : \u2124) :\n  shift_functor C n \u22d9 F.map_homological_complex (complex_shape.up \u2124) \u2245\n    F.map_homological_complex (complex_shape.up \u2124) \u22d9 shift_functor D n :=\nnat_iso.of_components (\u03bb K, hom.iso_of_components (\u03bb i, iso.refl _)\n  (\u03bb 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 \u2124)).has_comm_shift \u2124 :=\n{ iso := \u03bb 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 := \u03bb 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": "import Mathlib.Tactic.ClearExcept\n\n-- Most basic test\nexample (_delete_this : Nat) (dont_delete_this : Int) : Nat := by\n  clear * - dont_delete_this\n  fail_if_success assumption\n  exact dont_delete_this.toNat\n\n-- Confirms that clearExcept does not delete class instances\nexample [dont_delete_this : Inhabited Nat] (dont_delete_this2 : Prop) : Inhabited Nat := by\n  clear * - dont_delete_this2\n  assumption\n\n-- Confirms that clearExcept can clear hypotheses even when they have dependencies\nexample (delete_this : Nat) (_delete_this2 : delete_this = delete_this) (dont_delete_this : Int) : Nat := by\n  clear * - dont_delete_this\n  fail_if_success assumption\n  exact dont_delete_this.toNat\n\n-- Confirms that clearExcept does not clear hypotheses when they have dependencies that should not be cleared\nexample (dont_delete_this : Nat) (dont_delete_this2 : dont_delete_this = dont_delete_this) : Nat := by\n  clear * - dont_delete_this2\n  exact dont_delete_this\n\n-- Confirms that clearExcept can preserve multiple identifiers\nexample (_delete_this : Nat) (dont_delete_this : Int) (dont_delete_this2 : Int) : Nat := by\n  clear * - dont_delete_this dont_delete_this2\n  fail_if_success assumption\n  exact dont_delete_this.toNat + dont_delete_this2.toNat\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/ClearExcept.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.051845463536637736, "lm_q1q2_score": 0.021510622981149457}}
{"text": "class foo (F : Type) where\n  foo : F\n\nclass foobar (F : outParam Type) [foo F] where\n  bar : F\n\nclass C (\u03b1 : Type) where\n  val : \u03b1\n\nclass D (\u03b1 : Type) (\u03b2 : outParam Type) [C \u03b2] where\n  val1 : \u03b1\n  val2 : \u03b2 := 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 (\u03b1 : Type) {\u03b2 : Type} {_ : C \u03b2} [D \u03b1 \u03b2] : \u03b1 \u00d7 \u03b2 :=\n  (D.val1, D.val2 \u03b1)\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": "import Lean\n\nopen Lean\nopen Lean.Meta\nopen Lean.Elab\nopen Lean.Elab\n\nprivate partial def matchHyps : List Expr \u2192 List Expr \u2192 List Expr \u2192 MetaM Bool\n  | p::ps, oldHyps, h::newHyps => do\n    let pt \u2190 inferType p\n    let t \u2190 inferType h\n    --dbg_trace \"{pt} {t}\"\n    if (\u2190 isDefEq pt t) then\n      matchHyps ps [] (oldHyps ++ newHyps)\n    else\n      matchHyps (p::ps) (h::oldHyps) newHyps\n  | [], _, _    => pure true\n  | _::_, _, [] => pure false\n\n-- from Lean.Server.Completion\nprivate def isBlackListed (declName : Name) : MetaM Bool := do\n  let env \u2190 getEnv\n  declName.isInternal\n  <||> isAuxRecursor env declName\n  <||> isNoConfusion env declName\n  <||> isRec declName\n  <||> isMatcher declName\n\ninitialize findCache : IO.Ref (Option (Std.HashMap HeadIndex (Array Name))) \u2190 IO.mkRef none\n\ndef findType (t : Expr) : TermElabM Unit := withReducible do\n  let env \u2190 getEnv\n  let headMap \u2190 match (\u2190 findCache.get) with\n    | some headMap => pure headMap\n    | none => profileitM Exception \"#find: init cache\" (\u2190 getOptions) do\n      let mut headMap := Std.HashMap.empty\n      -- TODO: `ForIn` for `SMap`\n      for (_, c) in env.constants.map\u2081.toList do\n        if (\u2190 isBlackListed c.name) then\n          continue\n        let (_, _, ty) \u2190 forallMetaTelescopeReducing c.type\n        let head := ty.toHeadIndex\n        headMap := headMap.insert head (headMap.findD head #[] |>.push c.name)\n      findCache.set headMap\n      pure headMap\n\n  let t \u2190 instantiateMVars t\n  let head := (\u2190 forallMetaTelescopeReducing t).2.2.toHeadIndex\n  let pat \u2190 abstractMVars t\n\n  let mut numFound := 0\n  for n in headMap.findD head #[] ++ env.constants.map\u2082.toList.toArray.map (\u00b7.1) do\n    let c := env.find? n |>.get!\n    let us \u2190 mkFreshLevelMVars c.numLevelParams\n    let cTy \u2190 c.instantiateTypeLevelParams us\n    let found \u2190 forallTelescopeReducing cTy fun cParams cTy' => do\n      let pat \u2190 pat.expr.instantiateLevelParamsArray pat.paramNames (\u2190 mkFreshLevelMVars pat.numMVars).toArray\n      let (_, _, pat) \u2190 lambdaMetaTelescope pat\n      let (patParams, _, pat) \u2190 forallMetaTelescopeReducing pat\n      --dbg_trace \"{cTy'}\\n{pat}\"\n      isDefEq cTy' pat <&&> matchHyps patParams.toList [] cParams.toList\n    if found then\n      numFound := numFound + 1\n      if numFound > 20 then\n        logInfo m!\"maximum number of search results reached\"\n        break\n      logInfo m!\"{n}: {cTy}\"\n\nopen Lean.Elab.Command in\n/-\nThe `find` command finds definitions & lemmas using pattern matching on the type. For instance:\n```lean\n#find _ + _ = _ + _\n#find ?n + _ = _ + ?n\n#find (_ : Nat) + _ = _ + _\n#find Nat \u2192 Nat\n```\nInside tactic proofs, the `find` tactic can be used instead.\n-/\nelab \"#find\" t:term : command =>\n  liftTermElabM none do\n    let t \u2190 Term.elabTerm t none\n    Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)\n    findType t\n\n--#find _ + _ = _ + _\n--#find _ + _ = _ + _\n--#find ?n + _ = _ + ?n\n--#find (_ : Nat) + _ = _ + _\n--#find Nat \u2192 Nat\n--#find _ \u2264 _ \u2192 _ + _ \u2264 _ + _  -- TODO\n\nopen Lean.Elab.Tactic\n/-\nDisplay theorems (and definitions) whose result type matches the current goal, i.e. which should be `apply`able.\n```lean\nexample : True := by find\n```\n`find` will not affect the goal by itself and should be removed from the finished proof.\n\nFor a command that takes the type to search for as an argument, see `#find`, which is also available as a tactic.\n-/\nelab \"find\" : tactic => do\n  findType (\u2190 getMainTarget)\n\n/-\nTactic version of the `#find` command. See also the `find` tactic to search for theorems matching the current goal.\n-/\nelab \"#find\" t:term : tactic => do\n  let t \u2190 Term.elabTerm t none\n  Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)\n  findType t\n", "meta": {"author": "IPDSnelting", "repo": "tba-2021", "sha": "b6390e55b768423d3266969e81d19290129c5914", "save_path": "github-repos/lean/IPDSnelting-tba-2021", "path": "github-repos/lean/IPDSnelting-tba-2021/tba-2021-b6390e55b768423d3266969e81d19290129c5914/TBA/Util/Find.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047866316946014, "lm_q2_score": 0.04468087059067444, "lm_q1q2_score": 0.0214682049706549}}
{"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 \u03b1 n)\n(y : Vector \u03b1 20)\n```\nthe term `x = y` is correct. However, its closure using lambda abstractions\nis not.\n```lean\nfun (n : Nat) (x : Vector \u03b1 n) (y : Vector \u03b1 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 \u03b1 n) (y : Vector \u03b1 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 \u2192 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 } := \u27e820, rfl\u27e9; y.1 + n + f x, z + 10)\n```\nwe obtain\n```lean\ndef aux (x : Nat) (f : Nat \u2192 Nat) (z : Nat) : Nat\u00d7Nat :=\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 \u2192 ClosureM Level) (u : Level) : ClosureM Level := do\n  if !u.hasMVar && !u.hasParam then\n    pure u\n  else\n    let s \u2190 get\n    match s.visitedLevel.find? u with\n    | some v => pure v\n    | none   => do\n      let v \u2190 f u\n      modify fun s => { s with visitedLevel := s.visitedLevel.insert u v }\n      pure v\n\n@[inline] def visitExpr (f : Expr \u2192 ClosureM Expr) (e : Expr) : ClosureM Expr := do\n  if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then\n    pure e\n  else\n    let s \u2190 get\n    match s.visitedExpr.find? e with\n    | some r => pure r\n    | none   =>\n      let r \u2190 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 \u2190 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 \u2192 ClosureM Level\n  | u@(Level.succ v)   => return u.updateSucc! (\u2190 visitLevel collectLevelAux v)\n  | u@(Level.max v w)  => return u.updateMax! (\u2190 visitLevel collectLevelAux v) (\u2190 visitLevel collectLevelAux w)\n  | u@(Level.imax v w) => return u.updateIMax! (\u2190 visitLevel collectLevelAux v) (\u2190 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 \u2190 instantiateLevelMVars u\n  visitLevel collectLevelAux u\n\ndef preprocess (e : Expr) : ClosureM Expr := do\n  let e \u2190 instantiateMVars e\n  let ctx \u2190 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 \u2190 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! (\u2190 collect s)\n  | Expr.forallE _ d b _ => return e.updateForallE! (\u2190 collect d) (\u2190 collect b)\n  | Expr.lam _ d b _     => return e.updateLambdaE! (\u2190 collect d) (\u2190 collect b)\n  | Expr.letE _ t v b _  => return e.updateLet! (\u2190 collect t) (\u2190 collect v) (\u2190 collect b)\n  | Expr.app f a         => return e.updateApp! (\u2190 collect f) (\u2190 collect a)\n  | Expr.mdata _ b       => return e.updateMData! (\u2190 collect b)\n  | Expr.sort u          => return e.updateSort! (\u2190 collectLevel u)\n  | Expr.const _ us      => return e.updateConst! (\u2190 us.mapM collectLevel)\n  | Expr.mvar mvarId     =>\n    let mvarDecl \u2190 mvarId.getDecl\n    let type \u2190 preprocess mvarDecl.type\n    let type \u2190 collect type\n    let newFVarId \u2190 mkFreshFVarId\n    let userName \u2190 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 (\u2190 read).zeta, (\u2190 fvarId.getValue?) with\n    | true, some value => collect (\u2190 preprocess value)\n    | _,    _          =>\n      let newFVarId \u2190 mkFreshFVarId\n      pushToProcess \u27e8fvarId, newFVarId\u27e9\n      return mkFVar newFVarId\n  | e => pure e\n\ndef collectExpr (e : Expr) : ClosureM Expr := do\n  let e \u2190 preprocess e\n  visitExpr collectExprAux e\n\npartial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement)\n    : ToProcessElement \u00d7 Array ToProcessElement :=\n  if h : i < toProcess.size then\n    let elem' := toProcess.get \u27e8i, h\u27e9\n    if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then\n      pickNextToProcessAux lctx (i+1) (toProcess.set \u27e8i, h\u27e9 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 \u2190 getLCtx\n  let s \u2190 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 \u2190 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 (\u2190 pickNextToProcess?) with\n  | none => pure ()\n  | some \u27e8fvarId, newFVarId\u27e9 =>\n    match (\u2190 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 \u2190 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 \u2190 collectExpr type\n        let val  \u2190 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 (\u00b7.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 \u00d7 Expr) := do\n  resetZetaFVarIds\n  withTrackingZeta do\n    let type  \u2190 collectExpr type\n    let value \u2190 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) \u2190 ((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 \u2190 Closure.mkValueTypeClosure type value zeta\n  let env \u2190 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 \u2190 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 `\u2218\u209b` 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} {\u03b1 \u03b2 \u03b3 : 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 \u00d7 S') :=\n{ default_state := (so.default_state, so'.default_state),\n  o := \u03bb i x, simulate so' (so i (x.1, x.2.1)) x.2.2 >>= \u03bb 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' `\u2218\u209b` 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.\u03b9) (s : S \u00d7 S') : (so' \u2218\u209b so) i =\n  \u03bb x, simulate so' (so i (x.1, x.2.1)) x.2.2 >>= \u03bb 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 \u21a6 x + 2` or simply `x \u21a6 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 `\u21a6` notation for functions.\n-/\nimport Lean\n\nmacro x:ident \":\" t:term \" \u21a6 \" y:term : term => do\n  `(fun $x : $t => $y)\n\n#eval (x : Nat \u21a6 x + 2) 2 -- 4\n\nmacro x:ident \" \u21a6 \" y:term : term => do\n  `(fun $x  => $y)\n\n#eval (x \u21a6  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 <term> : <type>`\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 \u2190 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 \u2192 Arith \u2192 Arith -- e + f\n  | mul : Arith \u2192 Arith \u2192 Arith -- e * f\n  | nat : Nat \u2192 Arith           -- constant\n  | var : String \u2192 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 \" \u27ea \" arith \" \u27eb \" : term\n\n-- Our macro rules perform the \"obvious\" translation:\nmacro_rules\n  | `(\u27ea $s:str \u27eb)              => `(Arith.var $s)\n  | `(\u27ea $num:num \u27eb)            => `(Arith.nat $num)\n  | `(\u27ea $x:arith + $y:arith \u27eb) => `(Arith.add \u27ea $x \u27eb \u27ea $y \u27eb)\n  | `(\u27ea $x:arith * $y:arith \u27eb) => `(Arith.mul \u27ea $x \u27eb \u27ea $y \u27eb)\n  | `(\u27ea ( $x ) \u27eb)              => `( \u27ea $x \u27eb )\n\n#check \u27ea \"x\" * \"y\" \u27eb\n-- Arith.mul (Arith.var \"x\") (Arith.var \"y\") : Arith\n\n#check \u27ea \"x\" + \"y\" \u27eb\n-- Arith.add (Arith.var \"x\") (Arith.var \"y\") : Arith\n\n#check \u27ea \"x\" + 20 \u27eb\n-- Arith.add (Arith.var \"x\") (Arith.nat 20) : Arith\n\n#check \u27ea \"x\" + \"y\" * \"z\" \u27eb -- precedence\n-- Arith.add (Arith.var \"x\") (Arith.mul (Arith.var \"y\") (Arith.var \"z\")) : Arith\n\n#check \u27ea \"x\" * \"y\" + \"z\" \u27eb -- precedence\n-- Arith.add (Arith.mul (Arith.var \"x\") (Arith.var \"y\")) (Arith.var \"z\") : Arith\n\n#check \u27ea (\"x\" + \"y\") * \"z\" \u27eb -- 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 <name> : <type>`\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 \u2190 getMainGoal\n  mvarId.withContext do\n    let t \u2190 elabType t\n    let p \u2190 mkFreshExprMVar t MetavarKind.syntheticOpaque n\n    let (_, mvarIdNew) \u2190 intro1P $ \u2190 mvarId.assert n t p\n    replaceMainGoal [p.mvarId!, mvarIdNew]\n  evalTactic $ \u2190 `(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 \u27e8(\u00b7 \u25b8 rfl), (\u00b7 \u25b8 rfl)\u27e9\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 \u25b8 if_neg (not_not_intro hc) \u25b8 rfl)\n            (fun hnc => if_pos hnc \u25b8 if_neg hnc \u25b8 rfl)\n@[smt_simp] theorem ite_eq_branch [h : Decidable c] : ite c x x = x :=\n  h.byCases (if_pos \u00b7 \u25b8 rfl) (if_neg \u00b7 \u25b8 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}: \u00ac free_in_term x v :=\n  assume x_free_in_v: free_in_term x v,\n  show \u00abfalse\u00bb, by cases x_free_in_v\n\nlemma free_in_term.var.inv {x y: var}: free_in_term x y \u2192 (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) \u2192 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\u2081 t\u2082: term}:\n                              free_in_term x (term.binop op t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_binop: free_in_term x (term.binop op t\u2081 t\u2082),\n  begin\n    cases x_free_in_binop,\n    case free_in_term.binop\u2081 x_free_in_t\u2081 { from or.inl x_free_in_t\u2081 },\n    case free_in_term.binop\u2082 x_free_in_t\u2082 { from or.inr x_free_in_t\u2082 }\n  end\n\nlemma free_in_term.app.inv {x: var} {t\u2081 t\u2082: term}:\n                           free_in_term x (term.app t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_app: free_in_term x (term.app t\u2081 t\u2082),\n  begin\n    cases x_free_in_app,\n    case free_in_term.app\u2081 x_free_in_t\u2081 { from or.inl x_free_in_t\u2081 },\n    case free_in_term.app\u2082 x_free_in_t\u2082 { from or.inr x_free_in_t\u2082 }\n  end\n\nlemma free_in_prop.term.inv {t: term} {x: var}: free_in_prop x t \u2192 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 \u2192 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\u2081 P\u2082: prop} {x: var}: free_in_prop x (P\u2081 \u22c0 P\u2082) \u2192 free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082 :=\n  assume x_free_in_and: free_in_prop x (P\u2081 \u22c0 P\u2082),\n  begin\n    cases x_free_in_and,\n    case free_in_prop.and\u2081 free_in_P\u2081 {\n      show free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082, from or.inl free_in_P\u2081\n    },\n    case free_in_prop.and\u2082 free_in_P\u2082 {\n      show free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma free_in_prop.or.inv {P\u2081 P\u2082: prop} {x: var}: free_in_prop x (P\u2081 \u22c1 P\u2082) \u2192 free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082 :=\n  assume x_free_in_or: free_in_prop x (P\u2081 \u22c1 P\u2082),\n  begin\n    cases x_free_in_or,\n    case free_in_prop.or\u2081 free_in_P\u2081 {\n      show free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082, from or.inl free_in_P\u2081\n    },\n    case free_in_prop.or\u2082 free_in_P\u2082 {\n      show free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma free_in_prop.pre.inv {t\u2081 t\u2082: term} {x: var}:\n      free_in_prop x (prop.pre t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_pre: free_in_prop x (prop.pre t\u2081 t\u2082),\n  begin\n    cases x_free_in_pre,\n    case free_in_prop.pre\u2081 free_in_t\u2081 { from or.inl free_in_t\u2081 },\n    case free_in_prop.pre\u2082 free_in_t\u2082 { from or.inr free_in_t\u2082 } \n  end\n\nlemma free_in_prop.pre\u2081.inv {t: term} {op: unop} {x: var}:\n      free_in_prop x (prop.pre\u2081 op t) \u2192 free_in_term x t :=\n  assume x_free_in_pre: free_in_prop x (prop.pre\u2081 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\u2082.inv {t\u2081 t\u2082: term} {op: binop} {x: var}:\n      free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_pre: free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082),\n  begin\n    cases x_free_in_pre,\n    case free_in_prop.preop\u2081 free_in_t\u2081 { from or.inl free_in_t\u2081 },\n    case free_in_prop.preop\u2082 free_in_t\u2082 { from or.inr free_in_t\u2082 } \n  end\n\nlemma free_in_prop.post.inv {t\u2081 t\u2082: term} {x: var}:\n      free_in_prop x (prop.post t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_post: free_in_prop x (prop.post t\u2081 t\u2082),\n  begin\n    cases x_free_in_post,\n    case free_in_prop.post\u2081 free_in_t\u2081 { from or.inl free_in_t\u2081 },\n    case free_in_prop.post\u2082 free_in_t\u2082 { from or.inr free_in_t\u2082 } \n  end\n\nlemma free_in_prop.call.inv {t: term} {x: var}:\n      free_in_prop x (prop.call t) \u2192 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) \u2192 (x \u2260 fx) \u2227 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 \u27e8x_neq_fx, free_in_P\u27e9 \n    }\n  end\n\nlemma free_in_prop.forallc.same.inv {P: prop} {x: var}: \u00ac 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) \u2192 (x \u2260 fx) \u2227 (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 \u27e8x_neq_fx, free_in_P\u27e9 \n    }\n  end\n\nlemma free_in_prop.implies.inv {P\u2081 P\u2082: prop} {x: var}: free_in_prop x (prop.implies P\u2081 P\u2082) \u2192 free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082 :=\n  assume x_free_in_implies: free_in_prop x (prop.or P\u2081.not P\u2082),\n  begin\n    cases x_free_in_implies,\n    case free_in_prop.or\u2081 x_free_in_not_P\u2081 {\n      cases x_free_in_not_P\u2081,\n      case free_in_prop.not free_in_P\u2081 {\n        show free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082, from or.inl free_in_P\u2081\n      }\n    },\n    case free_in_prop.or\u2082 free_in_P\u2082 {\n      show free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma free_in_prop.func.inv {P\u2081 P\u2082: prop} {t: term} {x y: var}:\n      free_in_prop x (prop.func t y P\u2081 P\u2082) \u2192 free_in_term x t \u2228 (x \u2260 y \u2227 (free_in_prop x P\u2081 \u2228 free_in_prop x P\u2082)) :=\n  assume : free_in_prop x (prop.func t y P\u2081 P\u2082),\n  have free_in_prop x (term.unop unop.isFunc t \u22c0\n                      (prop.forallc y (prop.implies P\u2081 (prop.pre t y) \u22c0\n                                       prop.implies (prop.post t y) P\u2082))),\n  from this,\n  begin\n    cases this,\n    case free_in_prop.and\u2081 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\u2082 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\u2081 x_free_Rpre {\n          cases x_free_Rpre,\n          case free_in_prop.or\u2081 x_free_in_Pnot {\n            cases x_free_in_Pnot,\n            case free_in_prop.not x_free_in_P\u2081 {\n              right,\n              split,\n              from x_neq_y,\n              left,\n              from x_free_in_P\u2081\n            }\n          },\n          case free_in_prop.or\u2082 x_free_in_pre {\n            cases x_free_in_pre,\n            case free_in_prop.pre\u2081 x_free_in_t {\n              left,\n              from x_free_in_t\n            },\n            case free_in_prop.pre\u2082 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\u2082 x_free_postS {\n          cases x_free_postS,\n          case free_in_prop.or\u2081 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\u2081 x_free_in_t {\n                left,\n                from x_free_in_t\n              },\n              case free_in_prop.post\u2082 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\u2082 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 \u2192 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 \u2192 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\u2081 P\u2082: vc} {x: var}: free_in_vc x (P\u2081 \u22c0 P\u2082) \u2192 free_in_vc x P\u2081 \u2228 free_in_vc x P\u2082 :=\n  assume x_free_in_and: free_in_vc x (P\u2081 \u22c0 P\u2082),\n  begin\n    cases x_free_in_and,\n    case free_in_vc.and\u2081 free_in_P\u2081 {\n      show free_in_vc x P\u2081 \u2228 free_in_vc x P\u2082, from or.inl free_in_P\u2081\n    },\n    case free_in_vc.and\u2082 free_in_P\u2082 {\n      show free_in_vc x P\u2081 \u2228 free_in_vc x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma free_in_vc.or.inv {P\u2081 P\u2082: vc} {x: var}: free_in_vc x (P\u2081 \u22c1 P\u2082) \u2192 free_in_vc x P\u2081 \u2228 free_in_vc x P\u2082 :=\n  assume x_free_in_or: free_in_vc x (P\u2081 \u22c1 P\u2082),\n  begin\n    cases x_free_in_or,\n    case free_in_vc.or\u2081 free_in_P\u2081 {\n      show free_in_vc x P\u2081 \u2228 free_in_vc x P\u2082, from or.inl free_in_P\u2081\n    },\n    case free_in_vc.or\u2082 free_in_P\u2082 {\n      show free_in_vc x P\u2081 \u2228 free_in_vc x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma free_in_vc.pre.inv {t\u2081 t\u2082: term} {x: var}:\n      free_in_vc x (vc.pre t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_pre: free_in_vc x (vc.pre t\u2081 t\u2082),\n  begin\n    cases x_free_in_pre,\n    case free_in_vc.pre\u2081 free_in_t\u2081 { from or.inl free_in_t\u2081 },\n    case free_in_vc.pre\u2082 free_in_t\u2082 { from or.inr free_in_t\u2082 } \n  end\n\nlemma free_in_vc.pre\u2081.inv {t: term} {op: unop} {x: var}:\n      free_in_vc x (vc.pre\u2081 op t) \u2192 free_in_term x t :=\n  assume x_free_in_pre: free_in_vc x (vc.pre\u2081 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\u2082.inv {t\u2081 t\u2082: term} {op: binop} {x: var}:\n      free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_pre: free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082),\n  begin\n    cases x_free_in_pre,\n    case free_in_vc.preop\u2081 free_in_t\u2081 { from or.inl free_in_t\u2081 },\n    case free_in_vc.preop\u2082 free_in_t\u2082 { from or.inr free_in_t\u2082 } \n  end\n\nlemma free_in_vc.post.inv {t\u2081 t\u2082: term} {x: var}:\n      free_in_vc x (vc.post t\u2081 t\u2082) \u2192 free_in_term x t\u2081 \u2228 free_in_term x t\u2082 :=\n  assume x_free_in_post: free_in_vc x (vc.post t\u2081 t\u2082),\n  begin\n    cases x_free_in_post,\n    case free_in_vc.post\u2081 free_in_t\u2081 { from or.inl free_in_t\u2081 },\n    case free_in_vc.post\u2082 free_in_t\u2082 { from or.inr free_in_t\u2082 } \n  end\n\nlemma free_in_vc.univ.inv {P: vc} {x y: var}:\n      free_in_vc x (vc.univ y P) \u2192 (x \u2260 y) \u2227 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 \u27e8x_neq_y, free_in_P\u27e9 \n    }\n  end\n\nlemma free_in_vc.univ.same.inv {P: vc} {x: var}: \u00ac 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 \u2208 FV (\u2022 t) \u2192 x \u2208 FV t :=\n  assume x_free_in_t: x \u2208 FV (\u2022 t),\n  have (termctx.apply \u2022 t) = t, by unfold termctx.apply,\n  show x \u2208 FV t, from this \u25b8 x_free_in_t\n\nlemma free_in_termctx.binop.inv {x: var} {op: binop} {t\u2081 t\u2082: termctx} {t': term}:\n      x \u2208 FV ((termctx.binop op t\u2081 t\u2082) t') \u2192 x \u2208 FV (t\u2081 t') \u2228 x \u2208 FV (t\u2082 t') :=\n  assume x_free_in_t: x \u2208 FV ((termctx.binop op t\u2081 t\u2082) t'),\n  have (termctx.apply (termctx.binop op t\u2081 t\u2082) t') = term.binop op (t\u2081.apply t') (t\u2082.apply t'),\n  by unfold termctx.apply,\n  have x \u2208 FV (term.binop op (t\u2081.apply t') (t\u2082.apply t')), from this \u25b8 x_free_in_t,\n  show x \u2208 FV (t\u2081 t') \u2228 x \u2208 FV (t\u2082 t'), from free_in_term.binop.inv this\n\nlemma free_in_termctx.term.inv {x: var} {t t': term}:\n      x \u2208 FV (t.to_termctx t') \u2192 x \u2208 FV t :=\n  assume x_free_in_t: x \u2208 FV (t.to_termctx t'),\n  begin\n    induction t with v y unop t\u2081 ih\u2081 binop t\u2082 t\u2083 ih\u2082 ih\u2083 t\u2084 t\u2085 ih\u2084 ih\u2085,\n\n    show x \u2208 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 \u2208 FV ((termctx.value v) t'), from this \u25b8 x_free_in_t,\n      have termctx.apply (termctx.value v) t' = (term.value v), by unfold termctx.apply,\n      show x \u2208 FV (term.value v), from this.symm \u25b8 h\n    ),\n\n    show x \u2208 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 \u2208 FV ((termctx.var y) t'), from this \u25b8 x_free_in_t,\n      have termctx.apply (termctx.var y) t' = term.var y, by unfold termctx.apply,\n      show x \u2208 FV (term.var y), from this.symm \u25b8 h\n    ),\n\n    show x \u2208 FV (term.unop unop t\u2081), from (\n      have term.to_termctx (term.unop unop t\u2081) = termctx.unop unop t\u2081.to_termctx, by unfold term.to_termctx,\n      have h: x \u2208 FV ((termctx.unop unop t\u2081.to_termctx) t'), from this \u25b8 x_free_in_t,\n      have termctx.apply (termctx.unop unop t\u2081.to_termctx) t' = term.unop unop (t\u2081.to_termctx.apply t'),\n      by unfold termctx.apply,\n      have x \u2208 FV (term.unop unop (t\u2081.to_termctx.apply t')), from this \u25b8 h,\n      have x \u2208 FV (t\u2081.to_termctx.apply t'), from free_in_term.unop.inv this,\n      have x \u2208 FV t\u2081, from ih\u2081 this,\n      show x \u2208 FV (term.unop unop t\u2081), from free_in_term.unop this\n    ),\n\n    show x \u2208 FV (term.binop binop t\u2082 t\u2083), from (\n      have term.to_termctx (term.binop binop t\u2082 t\u2083) = termctx.binop binop t\u2082.to_termctx t\u2083.to_termctx,\n      by unfold term.to_termctx,\n      have h: x \u2208 FV ((termctx.binop binop t\u2082.to_termctx t\u2083.to_termctx) t'), from this \u25b8 x_free_in_t,\n      have termctx.apply (termctx.binop binop t\u2082.to_termctx t\u2083.to_termctx) t'\n         = term.binop binop (t\u2082.to_termctx.apply t') (t\u2083.to_termctx.apply t'),\n      by unfold termctx.apply,\n      have x \u2208 FV (term.binop binop (t\u2082.to_termctx.apply t') (t\u2083.to_termctx.apply t')), from this \u25b8 h,\n      have x \u2208 FV (t\u2082.to_termctx.apply t') \u2228 x \u2208 FV (t\u2083.to_termctx.apply t'), from free_in_term.binop.inv this,\n      or.elim this (\n        assume : x \u2208 FV (t\u2082.to_termctx.apply t'),\n        have x \u2208 FV t\u2082, from ih\u2082 this,\n        show x \u2208 FV (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2081 this\n      ) (\n        assume : x \u2208 FV (t\u2083.to_termctx.apply t'),\n        have x \u2208 FV t\u2083, from ih\u2083 this,\n        show x \u2208 FV (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2082 this\n      )\n    ),\n\n    show x \u2208 FV (term.app t\u2084 t\u2085), from (\n      have term.to_termctx (term.app t\u2084 t\u2085) = termctx.app t\u2084.to_termctx t\u2085.to_termctx,\n      by unfold term.to_termctx,\n      have h: x \u2208 FV ((termctx.app t\u2084.to_termctx t\u2085.to_termctx) t'), from this \u25b8 x_free_in_t,\n      have termctx.apply (termctx.app t\u2084.to_termctx t\u2085.to_termctx) t'\n         = term.app (t\u2084.to_termctx.apply t') (t\u2085.to_termctx.apply t'),\n      by unfold termctx.apply,\n      have x \u2208 FV (term.app (t\u2084.to_termctx.apply t') (t\u2085.to_termctx.apply t')), from this \u25b8 h,\n      have x \u2208 FV (t\u2084.to_termctx.apply t') \u2228 x \u2208 FV (t\u2085.to_termctx.apply t'), from free_in_term.app.inv this,\n      or.elim this (\n        assume : x \u2208 FV (t\u2084.to_termctx.apply t'),\n        have x \u2208 FV t\u2084, from ih\u2084 this,\n        show x \u2208 FV (term.app t\u2084 t\u2085), from free_in_term.app\u2081 this\n      ) (\n        assume : x \u2208 FV (t\u2085.to_termctx.apply t'),\n        have x \u2208 FV t\u2085, from ih\u2085 this,\n        show x \u2208 FV (term.app t\u2084 t\u2085), from free_in_term.app\u2082 this\n      )\n    )\n  end\n\nlemma free_in_propctx.prop.inv {x: var} {P: prop} {t': term}:\n      x \u2208 FV (P.to_propctx t') \u2192 x \u2208 FV P :=\n  assume x_free_in_P: x \u2208 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 \u2208 FV ((propctx.term t) t'), from this \u25b8 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 \u2208 FV (prop.term (t.to_termctx t')), from this.symm \u25b8 h,\n      have x \u2208 FV (t.to_termctx t'), from free_in_prop.term.inv this,\n      have x \u2208 FV t, from free_in_termctx.term.inv this,\n      show x \u2208 FV (prop.term t), from free_in_prop.term this\n    )},\n    case prop.not P\u2081 ih { from (\n      have prop.to_propctx (prop.not P\u2081) = (propctx.not P\u2081.to_propctx), by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.not P\u2081.to_propctx) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.not P\u2081.to_propctx) t' = prop.not (P\u2081.to_propctx.apply t'), by unfold propctx.apply,\n      have x \u2208 FV (prop.not (P\u2081.to_propctx.apply t')), from this.symm \u25b8 h,\n      have x \u2208 FV (P\u2081.to_propctx.apply t'), from free_in_prop.not.inv this,\n      have x \u2208 FV P\u2081, from ih this,\n      show x \u2208 FV P\u2081.not, from free_in_prop.not this\n    )},\n    case prop.and P\u2081 P\u2082 ih\u2081 ih\u2082 { from (\n      have prop.to_propctx (prop.and P\u2081 P\u2082) = (P\u2081.to_propctx \u22c0 P\u2082.to_propctx), by unfold prop.to_propctx,\n      have h: x \u2208 FV ((P\u2081.to_propctx \u22c0 P\u2082.to_propctx) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.and P\u2081.to_propctx P\u2082.to_propctx) t'\n         = (P\u2081.to_propctx.apply t' \u22c0 P\u2082.to_propctx.apply t'), by unfold propctx.apply,\n      have x \u2208 FV ((P\u2081.to_propctx.apply t') \u22c0 (P\u2082.to_propctx.apply t')), from this.symm \u25b8 h,\n      have x \u2208 FV (P\u2081.to_propctx.apply t') \u2228 x \u2208 FV (P\u2082.to_propctx.apply t'), from free_in_prop.and.inv this,\n      or.elim this (\n        assume : x \u2208 FV (P\u2081.to_propctx.apply t'),\n        have x \u2208 FV P\u2081, from ih\u2081 this,\n        show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n      ) (\n        assume : x \u2208 FV (P\u2082.to_propctx.apply t'),\n        have x \u2208 FV P\u2082, from ih\u2082 this,\n        show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this\n      )\n    )},\n    case prop.or P\u2081 P\u2082 ih\u2081 ih\u2082 { from (\n      have prop.to_propctx (prop.or P\u2081 P\u2082) = (P\u2081.to_propctx \u22c1 P\u2082.to_propctx), by unfold prop.to_propctx,\n      have h: x \u2208 FV ((P\u2081.to_propctx \u22c1 P\u2082.to_propctx) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.or P\u2081.to_propctx P\u2082.to_propctx) t'\n         = (P\u2081.to_propctx.apply t' \u22c1 P\u2082.to_propctx.apply t'), by unfold propctx.apply,\n      have x \u2208 FV ((P\u2081.to_propctx.apply t') \u22c1 (P\u2082.to_propctx.apply t')), from this.symm \u25b8 h,\n      have x \u2208 FV (P\u2081.to_propctx.apply t') \u2228 x \u2208 FV (P\u2082.to_propctx.apply t'), from free_in_prop.or.inv this,\n      or.elim this (\n        assume : x \u2208 FV (P\u2081.to_propctx.apply t'),\n        have x \u2208 FV P\u2081, from ih\u2081 this,\n        show x \u2208 FV (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2081 this\n      ) (\n        assume : x \u2208 FV (P\u2082.to_propctx.apply t'),\n        have x \u2208 FV P\u2082, from ih\u2082 this,\n        show x \u2208 FV (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2082 this\n      )\n    )},\n    case prop.pre t\u2081 t\u2082 { from (\n      have prop.to_propctx (prop.pre t\u2081 t\u2082) = propctx.pre t\u2081 t\u2082, by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.pre t\u2081 t\u2082) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.pre t\u2081.to_termctx t\u2082.to_termctx) t' = prop.pre (t\u2081.to_termctx t') (t\u2082.to_termctx t'),\n      by unfold propctx.apply,\n      have x \u2208 FV (prop.pre (t\u2081.to_termctx t') (t\u2082.to_termctx t')), from this.symm \u25b8 h,\n      have x \u2208 FV (t\u2081.to_termctx t') \u2228 x \u2208 FV (t\u2082.to_termctx t'), from free_in_prop.pre.inv this,\n      or.elim this (\n        assume : x \u2208 FV (t\u2081.to_termctx t'),\n        have x \u2208 FV t\u2081, from free_in_termctx.term.inv this,\n        show x \u2208 FV (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2081 this\n      ) (\n        assume : x \u2208 FV (t\u2082.to_termctx t'),\n        have x \u2208 FV t\u2082, from free_in_termctx.term.inv this,\n        show x \u2208 FV (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2082 this\n      )\n    )},\n    case prop.pre\u2081 op t { from (\n      have prop.to_propctx (prop.pre\u2081 op t) = propctx.pre\u2081 op t, by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.pre\u2081 op t) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.pre\u2081 op t.to_termctx) t' = prop.pre\u2081 op (t.to_termctx t'),\n      by unfold propctx.apply,\n      have x \u2208 FV (prop.pre\u2081 op (t.to_termctx t')), from this.symm \u25b8 h,\n      have x \u2208 FV (t.to_termctx t'), from free_in_prop.pre\u2081.inv this,\n      have x \u2208 FV t, from free_in_termctx.term.inv this,\n      show x \u2208 FV (prop.pre\u2081 op t), from free_in_prop.preop this\n    )},\n    case prop.pre\u2082 op t\u2081 t\u2082 { from (\n      have prop.to_propctx (prop.pre\u2082 op t\u2081 t\u2082) = propctx.pre\u2082 op t\u2081 t\u2082, by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.pre\u2082 op t\u2081 t\u2082) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.pre\u2082 op t\u2081.to_termctx t\u2082.to_termctx) t'\n         = prop.pre\u2082 op (t\u2081.to_termctx t') (t\u2082.to_termctx t'),\n      by unfold propctx.apply,\n      have x \u2208 FV (prop.pre\u2082 op (t\u2081.to_termctx t') (t\u2082.to_termctx t')), from this.symm \u25b8 h,\n      have x \u2208 FV (t\u2081.to_termctx t') \u2228 x \u2208 FV (t\u2082.to_termctx t'), from free_in_prop.pre\u2082.inv this,\n      or.elim this (\n        assume : x \u2208 FV (t\u2081.to_termctx t'),\n        have x \u2208 FV t\u2081, from free_in_termctx.term.inv this,\n        show x \u2208 FV (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2081 this\n      ) (\n        assume : x \u2208 FV (t\u2082.to_termctx t'),\n        have x \u2208 FV t\u2082, from free_in_termctx.term.inv this,\n        show x \u2208 FV (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2082 this\n      )\n    )},\n    case prop.post t\u2081 t\u2082 { from (\n      have prop.to_propctx (prop.post t\u2081 t\u2082) = propctx.post t\u2081 t\u2082, by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.post t\u2081 t\u2082) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.post t\u2081.to_termctx t\u2082.to_termctx) t' = prop.post (t\u2081.to_termctx t') (t\u2082.to_termctx t'),\n      by unfold propctx.apply,\n      have x \u2208 FV (prop.post (t\u2081.to_termctx t') (t\u2082.to_termctx t')), from this.symm \u25b8 h,\n      have x \u2208 FV (t\u2081.to_termctx t') \u2228 x \u2208 FV (t\u2082.to_termctx t'), from free_in_prop.post.inv this,\n      or.elim this (\n        assume : x \u2208 FV (t\u2081.to_termctx t'),\n        have x \u2208 FV t\u2081, from free_in_termctx.term.inv this,\n        show x \u2208 FV (prop.post t\u2081 t\u2082), from free_in_prop.post\u2081 this\n      ) (\n        assume : x \u2208 FV (t\u2082.to_termctx t'),\n        have x \u2208 FV t\u2082, from free_in_termctx.term.inv this,\n        show x \u2208 FV (prop.post t\u2081 t\u2082), from free_in_prop.post\u2082 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 \u2208 FV ((propctx.call t) t'), from this \u25b8 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 \u2208 FV (prop.call (t.to_termctx t')), from this.symm \u25b8 h,\n      have x \u2208 FV (t.to_termctx t'), from free_in_prop.call.inv this,\n      have x \u2208 FV t, from free_in_termctx.term.inv this,\n      show x \u2208 FV (prop.call t), from free_in_prop.call this\n    )},\n    case prop.forallc y P\u2081 ih { from (\n      have prop.to_propctx (prop.forallc y P\u2081) = propctx.forallc y P\u2081.to_propctx, by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.forallc y P\u2081.to_propctx) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.forallc y P\u2081.to_propctx) t'\n         = prop.forallc y (P\u2081.to_propctx.apply t'), by unfold propctx.apply,\n      have x \u2208 FV (prop.forallc y (P\u2081.to_propctx.apply t')), from this.symm \u25b8 h,\n      have x_neq_y: x \u2260 y, from (free_in_prop.forallc.inv this).left,\n      have x \u2208 FV (P\u2081.to_propctx.apply t'), from (free_in_prop.forallc.inv this).right,\n      have x \u2208 FV P\u2081, from ih this,\n      show x \u2208 FV (prop.forallc y P\u2081), from free_in_prop.forallc x_neq_y this\n    )},\n    case prop.exis y P\u2081 ih { from (\n      have prop.to_propctx (prop.exis y P\u2081) = (propctx.exis y P\u2081.to_propctx), by unfold prop.to_propctx,\n      have h: x \u2208 FV ((propctx.exis y P\u2081.to_propctx) t'), from this \u25b8 x_free_in_P,\n      have propctx.apply (propctx.exis y P\u2081.to_propctx) t' = prop.exis y (P\u2081.to_propctx.apply t'), by unfold propctx.apply,\n      have x \u2208 FV (prop.exis y (P\u2081.to_propctx.apply t')), from this.symm \u25b8 h,\n      have x_neq_y: x \u2260 y, from (free_in_prop.exis.inv this).left,\n      have x \u2208 FV (P\u2081.to_propctx.apply t'), from (free_in_prop.exis.inv this).right,\n      have x \u2208 FV P\u2081, from ih this,\n      show x \u2208 FV (prop.exis y P\u2081), 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 \u2208 FV ((propctx.term t) t') \u2192 x \u2208 FV (t t') :=\n  assume x_free_in_t: x \u2208 FV (propctx.apply (propctx.term t) t'),\n  have (propctx.apply (propctx.term t) t') = t t', by unfold propctx.apply,\n  have x \u2208 FV (prop.term (t t')), from this \u25b8 x_free_in_t,\n  show x \u2208 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 \u2208 FV (Q.not t) \u2192 x \u2208 FV (Q t) :=\n  assume x_free_in_Qn: x \u2208 FV (Q.not t),\n  have (propctx.apply (propctx.not Q) t) = prop.not (Q.apply t), by unfold propctx.apply,\n  have x \u2208 FV (prop.not (Q.apply t)), from this \u25b8 x_free_in_Qn,\n  show x \u2208 FV (Q t), from free_in_prop.not.inv this\n\nlemma free_in_propctx.and.inv {x: var} {Q\u2081 Q\u2082: propctx} {t: term}:\n      x \u2208 FV ((Q\u2081 \u22c0 Q\u2082) t) \u2192 x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t) :=\n  assume x_free_in_Q12: x \u2208 FV ((Q\u2081 \u22c0 Q\u2082) t),\n  have (propctx.apply (propctx.and Q\u2081 Q\u2082) t) = (Q\u2081.apply t \u22c0 Q\u2082.apply t), by unfold propctx.apply,\n  have x \u2208 FV (Q\u2081.apply t \u22c0 Q\u2082.apply t), from this \u25b8 x_free_in_Q12,\n  show x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t), from free_in_prop.and.inv this\n\nlemma free_in_propctx.or.inv {x: var} {Q\u2081 Q\u2082: propctx} {t: term}:\n      x \u2208 FV ((Q\u2081 \u22c1 Q\u2082) t) \u2192 x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t) :=\n  assume x_free_in_Q12: x \u2208 FV ((Q\u2081 \u22c1 Q\u2082) t),\n  have (propctx.apply (propctx.or Q\u2081 Q\u2082) t) = (Q\u2081.apply t \u22c1 Q\u2082.apply t), by unfold propctx.apply,\n  have x \u2208 FV (Q\u2081.apply t \u22c1 Q\u2082.apply t), from this \u25b8 x_free_in_Q12,\n  show x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t), from free_in_prop.or.inv this\n\nlemma free_in_propctx.implies.inv {x: var} {Q\u2081 Q\u2082: propctx} {t: term}:\n      x \u2208 FV ((propctx.implies Q\u2081 Q\u2082) t) \u2192 x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t) :=\n  assume : x \u2208 FV ((propctx.implies Q\u2081 Q\u2082) t),\n  have x \u2208 FV (Q\u2081.not t) \u2228 x \u2208 FV (Q\u2082 t), from free_in_propctx.or.inv this,\n  or.elim this (\n    assume : x \u2208 FV (Q\u2081.not t),\n    have x \u2208 FV (Q\u2081 t), from free_in_propctx.not.inv this,\n    show x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t), from or.inl this\n  ) (\n    assume : x \u2208 FV (Q\u2082 t),\n    show x \u2208 FV (Q\u2081 t) \u2228 x \u2208 FV (Q\u2082 t), from or.inr this\n  )\n\nlemma free_in_propctx.exis.inv {x fx: var} {Q: propctx} {t: term}:\n      x \u2208 FV ((propctx.exis fx Q) t) \u2192 x \u2260 fx \u2227 x \u2208 FV (Q t) :=\n  assume x_free_in_eQt: x \u2208 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 \u2208 FV (prop.exis fx (Q.apply t)), from this \u25b8 x_free_in_eQt,\n  show x \u2260 fx \u2227 x \u2208 FV (Q t), from free_in_prop.exis.inv this\n\nlemma free_in_prop.and_left_subset {P\u2081 P\u2082: prop}: FV P\u2081 \u2286 FV (P\u2081 \u22c0 P\u2082) :=\n  assume x: var,\n  assume : x \u2208 FV P\u2081,\n  show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n\nlemma free_in_prop.and_elim {P\u2081 P\u2082: prop}:\n      FV (P\u2081 \u22c0 P\u2082) = FV P\u2081 \u222a FV P\u2082 :=\n  set.eq_of_subset_of_subset (\n    assume x: var,\n    assume : x \u2208 FV (P\u2081 \u22c0 P\u2082),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2081,\n      show x \u2208 FV P\u2081 \u222a FV P\u2082, from set.mem_union_left (FV P\u2082) this\n    ) (\n      assume : x \u2208 FV P\u2082,\n      show x \u2208 FV P\u2081 \u222a FV P\u2082, from set.mem_union_right (FV P\u2081) this\n    )\n  ) (\n    assume x: var,\n    assume : x \u2208 FV P\u2081 \u222a FV P\u2082,\n    or.elim (set.mem_or_mem_of_mem_union this) (\n      assume : x \u2208 FV P\u2081,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n    ) (\n      assume : x \u2208 FV P\u2082,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this\n    )\n  )\n\nlemma free_in_prop.and_assoc {P\u2081 P\u2082 P\u2083: prop}:\n      FV (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083) = FV ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083) :=\n  set.eq_of_subset_of_subset (\n    assume x: var,\n    assume : x \u2208 FV (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2081,\n      have x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this,\n      show x \u2208 FV ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from free_in_prop.and\u2081 this\n    ) (\n      assume : x \u2208 FV (P\u2082 \u22c0 P\u2083),\n      or.elim (free_in_prop.and.inv this) (\n        assume : x \u2208 FV P\u2082,\n        have x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this,\n        show x \u2208 FV ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from free_in_prop.and\u2081 this\n      ) (\n        assume : x \u2208 FV P\u2083,\n        show x \u2208 FV ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from free_in_prop.and\u2082 this\n      )\n    )\n  ) (\n    assume x: var,\n    assume : x \u2208 FV ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV (P\u2081 \u22c0 P\u2082),\n      or.elim (free_in_prop.and.inv this) (\n        assume : x \u2208 FV P\u2081,\n        show x \u2208 FV (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2081 this\n      ) (\n        assume : x \u2208 FV P\u2082,\n        have x \u2208 FV (P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2081 this,\n        show x \u2208 FV (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n      )\n    ) (\n      assume : x \u2208 FV P\u2083,\n      have x \u2208 FV (P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2082 this,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n    )\n  )\n\nlemma free_in_prop.and_symm {P\u2081 P\u2082: prop}:\n      FV (P\u2081 \u22c0 P\u2082) = FV (P\u2082 \u22c0 P\u2081) :=\n  set.eq_of_subset_of_subset (\n    assume x: var,\n    assume : x \u2208 FV (P\u2081 \u22c0 P\u2082),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2081,\n      show x \u2208 FV (P\u2082 \u22c0 P\u2081), from free_in_prop.and\u2082 this\n    ) (\n      assume : x \u2208 FV P\u2082,\n      show x \u2208 FV (P\u2082 \u22c0 P\u2081), from free_in_prop.and\u2081 this\n    )\n  ) (\n    assume x: var,\n    assume : x \u2208 FV (P\u2082 \u22c0 P\u2081),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2082,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this\n    ) (\n      assume : x \u2208 FV P\u2081,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n    )\n  )\n\nlemma free_in_prop.same_left {P\u2081 P\u2082 P\u2083: prop}:\n      (FV P\u2082 = FV P\u2083) \u2192 (FV (P\u2081 \u22c0 P\u2082) = FV (P\u2081 \u22c0 P\u2083)) :=\n  assume h1: FV P\u2082 = FV P\u2083,\n  set.eq_of_subset_of_subset (\n    assume x: var,\n    assume : x \u2208 FV (P\u2081 \u22c0 P\u2082),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2081,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2083), from free_in_prop.and\u2081 this\n    ) (\n      assume : x \u2208 FV P\u2082,\n      have x \u2208 FV P\u2083, from h1 \u25b8 this,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n    )\n  ) (\n    assume x: var,\n    assume : x \u2208 FV (P\u2081 \u22c0 P\u2083),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2081,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n    ) (\n      assume : x \u2208 FV P\u2083,\n      have x \u2208 FV P\u2082, from h1.symm \u25b8 this,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this\n    )\n  )\n\nlemma free_in_prop.same_right {P\u2081 P\u2082 P\u2083: prop}:\n      (FV P\u2081 = FV P\u2082) \u2192 (FV (P\u2081 \u22c0 P\u2083) = FV (P\u2082 \u22c0 P\u2083)) :=\n  assume h1: FV P\u2081 = FV P\u2082,\n  set.eq_of_subset_of_subset (\n    assume x: var,\n    assume : x \u2208 FV (P\u2081 \u22c0 P\u2083),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2081,\n      have x \u2208 FV P\u2082, from h1 \u25b8 this,\n      show x \u2208 FV (P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2081 this\n    ) (\n      assume : x \u2208 FV P\u2083,\n      show x \u2208 FV (P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n    )\n  ) (\n    assume x: var,\n    assume : x \u2208 FV (P\u2082 \u22c0 P\u2083),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P\u2082,\n      have x \u2208 FV P\u2081, from h1.symm \u25b8 this,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2083), from free_in_prop.and\u2081 this\n    ) (\n      assume : x \u2208 FV P\u2083,\n      show x \u2208 FV (P\u2081 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n    )\n  )\n\nlemma free_in_prop.shuffle {P Q R S: prop}:\n      FV (P \u22c0 Q \u22c0 R \u22c0 S) = FV ((P \u22c0 Q \u22c0 R) \u22c0 S):=\n  have h1: FV (P \u22c0 Q \u22c0 R \u22c0 S) = FV ((Q \u22c0 R \u22c0 S) \u22c0 P), from free_in_prop.and_symm,\n  have h2: FV ((Q \u22c0 R \u22c0 S) \u22c0 P) = FV (((Q \u22c0 R) \u22c0 S) \u22c0 P),\n  from free_in_prop.same_right free_in_prop.and_assoc,\n  have h3: FV (((Q \u22c0 R) \u22c0 S) \u22c0 P) = FV ((Q \u22c0 R) \u22c0 S \u22c0 P), from free_in_prop.and_assoc.symm,\n  have h4: FV ((Q \u22c0 R) \u22c0 S \u22c0 P) = FV ((S \u22c0 P) \u22c0 Q \u22c0 R), from free_in_prop.and_symm,\n  have h5: FV ((S \u22c0 P) \u22c0 Q \u22c0 R) = FV (S \u22c0 P \u22c0 Q \u22c0 R), from free_in_prop.and_assoc.symm,\n  have h6: FV (S \u22c0 P \u22c0 Q \u22c0 R) = FV ((P \u22c0 Q \u22c0 R) \u22c0 S), from free_in_prop.and_symm,\n  show FV (P \u22c0 Q \u22c0 R \u22c0 S) = FV ((P \u22c0 Q \u22c0 R) \u22c0 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\u2081 P\u2082 P\u2083: prop}:\n      (FV P\u2082 \u2286 FV P\u2083) \u2192 (FV (P\u2081 \u22c0 P\u2082) \u2286 FV (P\u2081 \u22c0 P\u2083)) :=\n  assume h1: FV P\u2082 \u2286 FV P\u2083,\n  assume x: var,\n  assume : x \u2208 FV (P\u2081 \u22c0 P\u2082),\n  or.elim (free_in_prop.and.inv this) (\n    assume : x \u2208 FV P\u2081,\n    show x \u2208 FV (P\u2081 \u22c0 P\u2083), from free_in_prop.and\u2081 this\n  ) (\n    assume : x \u2208 FV P\u2082,\n    have x \u2208 FV P\u2083, from set.mem_of_subset_of_mem h1 this,\n    show x \u2208 FV (P\u2081 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n  )\n\nlemma free_in_prop.sub_same_right {P\u2081 P\u2082 P\u2083: prop}:\n      (FV P\u2081 \u2286 FV P\u2082) \u2192 (FV (P\u2081 \u22c0 P\u2083) \u2286 FV (P\u2082 \u22c0 P\u2083)) :=\n  assume h1: FV P\u2081 \u2286 FV P\u2082,\n  assume x: var,\n  assume : x \u2208 FV (P\u2081 \u22c0 P\u2083),\n  or.elim (free_in_prop.and.inv this) (\n    assume : x \u2208 FV P\u2081,\n    have x \u2208 FV P\u2082, from set.mem_of_subset_of_mem h1 this,\n    show x \u2208 FV (P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2081 this\n  ) (\n    assume : x \u2208 FV P\u2083,\n    show x \u2208 FV (P\u2082 \u22c0 P\u2083), from free_in_prop.and\u2082 this\n  )\n\nlemma prop.closed.and {P Q: prop}: closed P \u2192 closed Q \u2192 closed (P \u22c0 Q) :=\n  assume P_closed: closed P,\n  assume Q_closed: closed Q,\n  show closed (P \u22c0 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c0 Q),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P,\n      show \u00abfalse\u00bb, from P_closed x this\n    ) (\n      assume : x \u2208 FV Q,\n      show \u00abfalse\u00bb, from Q_closed x this\n    )\n  )\n\nlemma prop.closed.or {P Q: prop}: closed P \u2192 closed Q \u2192 closed (P \u22c1 Q) :=\n  assume P_closed: closed P,\n  assume Q_closed: closed Q,\n  show closed (P \u22c1 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c1 Q),\n    or.elim (free_in_prop.or.inv this) (\n      assume : x \u2208 FV P,\n      show \u00abfalse\u00bb, from P_closed x this\n    ) (\n      assume : x \u2208 FV Q,\n      show \u00abfalse\u00bb, from Q_closed x this\n    )\n  )\n\nlemma prop.closed.not {P: prop}: closed P \u2192 closed P.not :=\n  assume P_closed: closed P,\n  show closed P.not, from (\n    assume x: var,\n    assume : x \u2208 FV P.not,\n    have x \u2208 FV P, from free_in_prop.not.inv this,\n    show \u00abfalse\u00bb, from P_closed x this\n  )\n\nlemma prop.closed.implies {P Q: prop}: closed P \u2192 closed Q \u2192 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 \u22c1 Q), from prop.closed.or P_not_closed Q_closed\n\nlemma prop.closed.and.inv {P Q: prop}: closed (P \u22c0 Q) \u2192 (closed P \u2227 closed Q) :=\n  assume P_and_Q_closed: closed (P \u22c0 Q),\n  have P_closed: closed P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c0 Q), from free_in_prop.and\u2081 this,\n    show \u00abfalse\u00bb, from P_and_Q_closed x this\n  ),\n  have Q_closed: closed Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c0 Q), from free_in_prop.and\u2082 this,\n    show \u00abfalse\u00bb, from P_and_Q_closed x this\n  ),\n  \u27e8P_closed, Q_closed\u27e9\n\nlemma prop.closed.or.inv {P Q: prop}: closed (P \u22c1 Q) \u2192 (closed P \u2227 closed Q) :=\n  assume P_or_Q_closed: closed (P \u22c1 Q),\n  have P_closed: closed P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c1 Q), from free_in_prop.or\u2081 this,\n    show \u00abfalse\u00bb, from P_or_Q_closed x this\n  ),\n  have Q_closed: closed Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c1 Q), from free_in_prop.or\u2082 this,\n    show \u00abfalse\u00bb, from P_or_Q_closed x this\n  ),\n  \u27e8P_closed, Q_closed\u27e9\n\nlemma prop.closed.not.inv {P: prop}: closed P.not \u2192 closed P :=\n  assume P_not_closed: closed P.not,\n  show closed P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV P.not, from free_in_prop.not this,\n    show \u00abfalse\u00bb, from P_not_closed x this\n  )\n\nlemma prop.closed.implies.inv {P Q: prop}: closed (prop.implies P Q) \u2192 closed P \u2227 closed Q :=\n  assume P_not_or_Q_closed: closed (P.not \u22c1 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  \u27e8P_closed, Q_closed\u27e9\n\nlemma vc.closed.and {P Q: vc}: closed P \u2192 closed Q \u2192 closed (P \u22c0 Q) :=\n  assume P_closed: closed P,\n  assume Q_closed: closed Q,\n  show closed (P \u22c0 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c0 Q),\n    or.elim (free_in_vc.and.inv this) (\n      assume : x \u2208 FV P,\n      show \u00abfalse\u00bb, from P_closed x this\n    ) (\n      assume : x \u2208 FV Q,\n      show \u00abfalse\u00bb, from Q_closed x this\n    )\n  )\n\nlemma vc.closed.or {P Q: vc}: closed P \u2192 closed Q \u2192 closed (P \u22c1 Q) :=\n  assume P_closed: closed P,\n  assume Q_closed: closed Q,\n  show closed (P \u22c1 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c1 Q),\n    or.elim (free_in_vc.or.inv this) (\n      assume : x \u2208 FV P,\n      show \u00abfalse\u00bb, from P_closed x this\n    ) (\n      assume : x \u2208 FV Q,\n      show \u00abfalse\u00bb, from Q_closed x this\n    )\n  )\n\nlemma vc.closed.not {P: vc}: closed P \u2192 closed P.not :=\n  assume P_closed: closed P,\n  show closed P.not, from (\n    assume x: var,\n    assume : x \u2208 FV P.not,\n    have x \u2208 FV P, from free_in_vc.not.inv this,\n    show \u00abfalse\u00bb, from P_closed x this\n  )\n\nlemma vc.closed.implies {P Q: vc}: closed P \u2192 closed Q \u2192 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 \u22c1 Q), from vc.closed.or P_not_closed Q_closed\n\nlemma vc.closed.term.inv {t: term}: closed (vc.term t) \u2192 closed t :=\n  assume h: closed (vc.term t),\n  assume x: var,\n  assume : x \u2208 FV t,\n  have x \u2208 FV (vc.term t), from free_in_vc.term this,\n  show \u00abfalse\u00bb, from h x this\n\nlemma vc.closed.and.inv {P Q: vc}: closed (P \u22c0 Q) \u2192 (closed P \u2227 closed Q) :=\n  assume P_and_Q_closed: closed (P \u22c0 Q),\n  have P_closed: closed P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c0 Q), from free_in_vc.and\u2081 this,\n    show \u00abfalse\u00bb, from P_and_Q_closed x this\n  ),\n  have Q_closed: closed Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c0 Q), from free_in_vc.and\u2082 this,\n    show \u00abfalse\u00bb, from P_and_Q_closed x this\n  ),\n  \u27e8P_closed, Q_closed\u27e9\n\nlemma vc.closed.or.inv {P Q: vc}: closed (P \u22c1 Q) \u2192 (closed P \u2227 closed Q) :=\n  assume P_or_Q_closed: closed (P \u22c1 Q),\n  have P_closed: closed P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c1 Q), from free_in_vc.or\u2081 this,\n    show \u00abfalse\u00bb, from P_or_Q_closed x this\n  ),\n  have Q_closed: closed Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c1 Q), from free_in_vc.or\u2082 this,\n    show \u00abfalse\u00bb, from P_or_Q_closed x this\n  ),\n  \u27e8P_closed, Q_closed\u27e9\n\nlemma vc.closed.not.inv {P: vc}: closed P.not \u2192 closed P :=\n  assume P_not_closed: closed P.not,\n  show closed P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV P.not, from free_in_vc.not this,\n    show \u00abfalse\u00bb, from P_not_closed x this\n  )\n\nlemma vc.closed.implies.inv {P Q: vc}: closed (vc.implies P Q) \u2192 closed P \u2227 closed Q :=\n  assume P_not_or_Q_closed: closed (P.not \u22c1 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  \u27e8P_closed, Q_closed\u27e9\n\nlemma free_in_prop_of_free_in_to_vc {P: prop}: FV P.to_vc \u2286 FV P :=\n  begin\n    assume x: var,\n    assume x_free: x \u2208 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\u2081 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\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih a,\n\n      apply free_in_prop.and\u2082,\n      from P\u2082_ih a\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih a,\n\n      apply free_in_prop.or\u2082,\n      from P\u2082_ih a\n    },\n    case prop.pre t\u2081 t\u2082 {\n      unfold prop.to_vc at x_free,\n      cases (free_in_vc.pre.inv x_free),\n\n      apply free_in_prop.pre\u2081,\n      from a,\n\n      apply free_in_prop.pre\u2082,\n      from a\n    },\n    case prop.pre\u2081 op t {\n      unfold prop.to_vc at x_free,\n      apply free_in_prop.preop,\n      from free_in_vc.pre\u2081.inv x_free\n    },\n    case prop.pre\u2082 op t\u2081 t\u2082 {\n      unfold prop.to_vc at x_free,\n      cases (free_in_vc.pre\u2082.inv x_free),\n\n      apply free_in_prop.preop\u2081,\n      from a,\n\n      apply free_in_prop.preop\u2082,\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 \u2208 FV (prop.call t), from absurd h2 free_in_term.value.inv\n    },\n    case prop.post t\u2081 t\u2082 {\n      unfold prop.to_vc at x_free,\n      cases (free_in_vc.post.inv x_free),\n\n      apply free_in_prop.post\u2081,\n      from a,\n\n      apply free_in_prop.post\u2082,\n      from a\n    },\n    case prop.forallc y P\u2081 P\u2081_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\u2081_ih h1.right\n    },\n    case prop.exis y P\u2081 P\u2081_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\u2081_ih h3\n    }\n  end\n\nlemma free_in_prop_of_free_in_erased {P: prop}:\n      FV P.erased_p \u2286 FV P \u2227 FV P.erased_n \u2286 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 \u2208 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 \u2208 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\u2081 ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV P\u2081.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 \u2208 FV P\u2081.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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082).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\u2081,\n      from P\u2081_ih.left a,\n      apply free_in_prop.and\u2082,\n      from P\u2082_ih.left a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082).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\u2081,\n      from P\u2081_ih.right a,\n      apply free_in_prop.and\u2082,\n      from P\u2082_ih.right a\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082).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\u2081,\n      from P\u2081_ih.left a,\n      apply free_in_prop.or\u2082,\n      from P\u2082_ih.left a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082).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\u2081,\n      from P\u2081_ih.right a,\n      apply free_in_prop.or\u2082,\n      from P\u2082_ih.right a\n    },\n    case prop.pre t\u2081 t\u2082 {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.pre t\u2081 t\u2082).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\u2081,\n      from a,\n\n      apply free_in_prop.pre\u2082,\n      from a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.pre t\u2081 t\u2082).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\u2081,\n      from a,\n\n      apply free_in_prop.pre\u2082,\n      from a\n    },\n    case prop.pre\u2081 op t {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.pre\u2081 op t).erased_p,\n      unfold prop.erased_p at x_free,\n      apply free_in_prop.preop,\n      from free_in_vc.pre\u2081.inv x_free,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.pre\u2081 op t).erased_n,\n      unfold prop.erased_n at x_free,\n      apply free_in_prop.preop,\n      from free_in_vc.pre\u2081.inv x_free\n    },\n    case prop.pre\u2082 op t\u2081 t\u2082 {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.pre\u2082 op t\u2081 t\u2082).erased_p,\n      unfold prop.erased_p at x_free,\n      cases (free_in_vc.pre\u2082.inv x_free),\n\n      apply free_in_prop.preop\u2081,\n      from a,\n\n      apply free_in_prop.preop\u2082,\n      from a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.pre\u2082 op t\u2081 t\u2082).erased_n,\n      unfold prop.erased_n at x_free,\n      cases (free_in_vc.pre\u2082.inv x_free),\n\n      apply free_in_prop.preop\u2081,\n      from a,\n\n      apply free_in_prop.preop\u2082,\n      from a\n    },\n    case prop.call t {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 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 \u2208 FV (prop.call t), from absurd h2 free_in_term.value.inv,\n\n      assume x: var,\n      assume x_free: x \u2208 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 \u2208 FV (prop.call t), from absurd h2 free_in_term.value.inv\n    },\n    case prop.post t\u2081 t\u2082 {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.post t\u2081 t\u2082).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\u2081,\n      from a,\n\n      apply free_in_prop.post\u2082,\n      from a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.post t\u2081 t\u2082).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\u2081,\n      from a,\n\n      apply free_in_prop.post\u2082,\n      from a\n    },\n    case prop.forallc y P\u2081 P\u2081_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.forallc y P\u2081).erased_p,\n      unfold prop.erased_p at x_free,\n      have h2, from free_in_vc.term.inv x_free,\n      show x \u2208 FV (prop.forallc y P\u2081), from absurd h2 free_in_term.value.inv,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.forallc y P\u2081).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\u2081_ih.right h1.right\n    },\n    case prop.exis y P\u2081 P\u2081_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.exis y P\u2081).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\u2081_ih.left h3,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.exis y P\u2081).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\u2081_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 \u2286 FV (P.instantiate_with_p t).to_vc \u2227\n      FV P.to_vc \u2286 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\u2081 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 \u2208 FV (vc.not (prop.to_vc P\u2081)),\n      apply free_in_vc.not,\n      have h1, from free_in_vc.not.inv x_free,\n      change (x \u2208 FV (prop.to_vc (prop.instantiate_with_n P\u2081 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 \u2208 FV (vc.not (prop.to_vc P\u2081)),\n      apply free_in_vc.not,\n      have h1, from free_in_vc.not.inv x_free,\n      change (x \u2208 FV (prop.to_vc (prop.instantiate_with_p P\u2081 t))),\n      from set.mem_of_mem_of_subset h1 ih.left\n    },\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082).to_vc,\n      unfold prop.to_vc at x_free,\n      unfold prop.instantiate_with_p,\n      change (x \u2208 FV (prop.to_vc (prop.and (prop.instantiate_with_p P\u2081 t) (prop.instantiate_with_p P\u2082 t)))),\n      unfold prop.to_vc,\n      cases (free_in_vc.and.inv x_free),\n      apply free_in_vc.and\u2081,\n      from P\u2081_ih.left a,\n      apply free_in_vc.and\u2082,\n      from P\u2082_ih.left a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082).to_vc,\n      unfold prop.to_vc at x_free,\n      unfold prop.instantiate_with_n,\n      change (x \u2208 FV (prop.to_vc (prop.and (prop.instantiate_with_n P\u2081 t) (prop.instantiate_with_n P\u2082 t)))),\n      unfold prop.to_vc,\n      cases (free_in_vc.and.inv x_free),\n      apply free_in_vc.and\u2081,\n      from P\u2081_ih.right a,\n      apply free_in_vc.and\u2082,\n      from P\u2082_ih.right a\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082).to_vc,\n      unfold prop.to_vc at x_free,\n      unfold prop.instantiate_with_p,\n      change (x \u2208 FV (prop.to_vc (prop.or (prop.instantiate_with_p P\u2081 t) (prop.instantiate_with_p P\u2082 t)))),\n      unfold prop.to_vc,\n      cases (free_in_vc.or.inv x_free),\n      apply free_in_vc.or\u2081,\n      from P\u2081_ih.left a,\n      apply free_in_vc.or\u2082,\n      from P\u2082_ih.left a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082).to_vc,\n      unfold prop.to_vc at x_free,\n      unfold prop.instantiate_with_n,\n      change (x \u2208 FV (prop.to_vc (prop.or (prop.instantiate_with_n P\u2081 t) (prop.instantiate_with_n P\u2082 t)))),\n      unfold prop.to_vc,\n      cases (free_in_vc.or.inv x_free),\n      apply free_in_vc.or\u2081,\n      from P\u2081_ih.right a,\n      apply free_in_vc.or\u2082,\n      from P\u2082_ih.right a\n    },\n    case prop.pre t\u2081 t\u2082 {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.to_vc (prop.pre t\u2081 t\u2082))),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.to_vc (prop.pre t\u2081 t\u2082)))\n    },\n    case prop.pre\u2081 op t {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.to_vc (prop.pre\u2081 op t))),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.to_vc (prop.pre\u2081 op t)))\n    },\n    case prop.pre\u2082 op t\u2081 t\u2082 {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.to_vc (prop.pre\u2082 op t\u2081 t\u2082))),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.to_vc (prop.pre\u2082 op t\u2081 t\u2082)))\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\u2081 t\u2082 {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.to_vc (prop.post t\u2081 t\u2082))),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.to_vc (prop.post t\u2081 t\u2082)))\n    },\n    case prop.forallc y P\u2081 P\u2081_ih {\n      split,\n\n      unfold prop.instantiate_with_p,\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.to_vc (prop.forallc y P\u2081)),\n      change x \u2208 FV (prop.to_vc (prop.and (prop.forallc y P\u2081) (prop.substt y (t.x) P\u2081))),\n      unfold1 prop.to_vc,\n      apply free_in_vc.and\u2081,\n      from x_free,\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.to_vc (prop.forallc y P\u2081)))\n    },\n    case prop.exis y P\u2081 P\u2081_ih {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.to_vc (prop.exis y P\u2081))),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.to_vc (prop.exis y P\u2081)))\n    }\n  end\n\nlemma free_in_instantiate_with_of_free_in_prop {P: prop} {t: calltrigger}:\n      FV P \u2286 FV (P.instantiate_with_p t) \u2227\n      FV P \u2286 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\u2081 ih {\n      split,\n\n      unfold prop.instantiate_with_p,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.not P\u2081),\n      apply free_in_prop.not,\n      have h1, from free_in_prop.not.inv x_free,\n      change (x \u2208 FV (prop.instantiate_with_n P\u2081 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 \u2208 FV (prop.not P\u2081),\n      apply free_in_prop.not,\n      have h1, from free_in_prop.not.inv x_free,\n      change (x \u2208 FV (prop.instantiate_with_p P\u2081 t)),\n      from set.mem_of_mem_of_subset h1 ih.left\n    },\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082),\n      unfold prop.instantiate_with_p,\n      cases (free_in_prop.and.inv x_free),\n      apply free_in_prop.and\u2081,\n      from P\u2081_ih.left a,\n      apply free_in_prop.and\u2082,\n      from P\u2082_ih.left a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082),\n      unfold prop.instantiate_with_n,\n      cases (free_in_prop.and.inv x_free),\n      apply free_in_prop.and\u2081,\n      from P\u2081_ih.right a,\n      apply free_in_prop.and\u2082,\n      from P\u2082_ih.right a\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082),\n      unfold prop.instantiate_with_p,\n      cases (free_in_prop.or.inv x_free),\n      apply free_in_prop.or\u2081,\n      from P\u2081_ih.left a,\n      apply free_in_prop.or\u2082,\n      from P\u2082_ih.left a,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082),\n      unfold prop.instantiate_with_n,\n      cases (free_in_prop.or.inv x_free),\n      apply free_in_prop.or\u2081,\n      from P\u2081_ih.right a,\n      apply free_in_prop.or\u2082,\n      from P\u2082_ih.right a\n    },\n    case prop.pre t\u2081 t\u2082 {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.pre t\u2081 t\u2082)),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.pre t\u2081 t\u2082))\n    },\n    case prop.pre\u2081 op t {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.pre\u2081 op t)),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.pre\u2081 op t))\n    },\n    case prop.pre\u2082 op t\u2081 t\u2082 {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.pre\u2082 op t\u2081 t\u2082)),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.pre\u2082 op t\u2081 t\u2082))\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\u2081 t\u2082 {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.post t\u2081 t\u2082)),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.post t\u2081 t\u2082))\n    },\n    case prop.forallc y P\u2081 P\u2081_ih {\n      split,\n\n      unfold prop.instantiate_with_p,\n\n      assume x: var,\n      assume x_free: x \u2208 FV (prop.forallc y P\u2081),\n      apply free_in_prop.and\u2081,\n      from x_free,\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.forallc y P\u2081))\n    },\n    case prop.exis y P\u2081 P\u2081_ih {\n      split,\n\n      unfold prop.instantiate_with_p,\n      from set.subset.refl (FV (prop.exis y P\u2081)),\n\n      unfold prop.instantiate_with_n,\n      from set.subset.refl (FV (prop.exis y P\u2081))\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\u2081 ih\u2081 binop t\u2082 t\u2083 ih\u2082 ih\u2083 t\u2084 t\u2085 ih\u2084 ih\u2085,\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\u2081)), by begin\n      by_cases (free_in_term x t\u2081) 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\u2082 t\u2083)), by begin\n      by_cases (free_in_term x t\u2082) with h1,\n      from is_true (free_in_term.binop\u2081 h1),\n\n      by_cases (free_in_term x t\u2083) with h2,\n      from is_true (free_in_term.binop\u2082 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\u2084 t\u2085)), by begin\n      by_cases (free_in_term x t\u2084) with h1,\n      from is_true (free_in_term.app\u2081 h1),\n\n      by_cases (free_in_term x t\u2085) with h2,\n      from is_true (free_in_term.app\u2082 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\u2081 ih {\n      by_cases (free_in_prop x P\u2081) 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      by_cases (free_in_prop x P\u2081) with h1,\n      from is_true (free_in_prop.and\u2081 h1),\n\n      by_cases (free_in_prop x P\u2082) with h2,\n      from is_true (free_in_prop.and\u2082 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      by_cases (free_in_prop x P\u2081) with h1,\n      from is_true (free_in_prop.or\u2081 h1),\n\n      by_cases (free_in_prop x P\u2082) with h2,\n      from is_true (free_in_prop.or\u2082 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\u2081 t\u2082 {\n      by_cases (free_in_term x t\u2081) with h1,\n      from is_true (free_in_prop.pre\u2081 h1),\n\n      by_cases (free_in_term x t\u2082) with h2,\n      from is_true (free_in_prop.pre\u2082 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\u2081 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\u2081.inv h2,\n      contradiction\n    },\n    case prop.pre\u2082 op t\u2081 t\u2082 {\n      by_cases (free_in_term x t\u2081) with h1,\n      from is_true (free_in_prop.preop\u2081 h1),\n\n      by_cases (free_in_term x t\u2082) with h2,\n      from is_true (free_in_prop.preop\u2082 h2),\n      apply is_false,\n      assume h3,\n      have h4, from free_in_prop.pre\u2082.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\u2081 t\u2082 {\n      by_cases (free_in_term x t\u2081) with h1,\n      from is_true (free_in_prop.post\u2081 h1),\n\n      by_cases (free_in_term x t\u2082) with h2,\n      from is_true (free_in_prop.post\u2082 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\u2081 ih {\n      by_cases (free_in_vc x P\u2081) 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      by_cases (free_in_vc x P\u2081) with h1,\n      from is_true (free_in_vc.and\u2081 h1),\n\n      by_cases (free_in_vc x P\u2082) with h2,\n      from is_true (free_in_vc.and\u2082 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      by_cases (free_in_vc x P\u2081) with h1,\n      from is_true (free_in_vc.or\u2081 h1),\n\n      by_cases (free_in_vc x P\u2082) with h2,\n      from is_true (free_in_vc.or\u2082 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\u2081 t\u2082 {\n      by_cases (free_in_term x t\u2081) with h1,\n      from is_true (free_in_vc.pre\u2081 h1),\n\n      by_cases (free_in_term x t\u2082) with h2,\n      from is_true (free_in_vc.pre\u2082 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\u2081 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\u2081.inv h2,\n      contradiction\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      by_cases (free_in_term x t\u2081) with h1,\n      from is_true (free_in_vc.preop\u2081 h1),\n\n      by_cases (free_in_term x t\u2082) with h2,\n      from is_true (free_in_vc.preop\u2082 h2),\n      apply is_false,\n      assume h3,\n      have h4, from free_in_vc.pre\u2082.inv h3,\n      cases h4 with h5 h6,\n      contradiction,\n      contradiction\n    },\n    case vc.post t\u2081 t\u2082 {\n      by_cases (free_in_term x t\u2081) with h1,\n      from is_true (free_in_vc.post\u2081 h1),\n\n      by_cases (free_in_term x t\u2082) with h2,\n      from is_true (free_in_vc.post\u2082 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}: \u2200y, y \u2265 t.fresh_var \u2192 y \u2209 FV t :=\n  begin\n    induction t with v z unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n\n    show \u2200y : var, y \u2265 term.fresh_var (term.value v) \u2192 y \u2209 FV (term.value v), by begin\n      assume y,\n      assume h1,\n      from free_in_term.value.inv\n    end,\n\n    show \u2200y: var, y \u2265 term.fresh_var (term.var z) \u2192 y \u2209 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 \u2200y: var, y \u2265 term.fresh_var (term.unop unop t\u2081) \u2192 y \u2209 FV (term.unop unop t\u2081), 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\u2081_ih y h1 h3\n    end,\n\n    show \u2200y: var, y \u2265 term.fresh_var (term.binop binop t\u2082 t\u2083) \u2192 y \u2209 FV (term.binop binop t\u2082 t\u2083), 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\u2082 \u2264 max (term.fresh_var t\u2082) (term.fresh_var t\u2083)),\n      from le_max_left (term.fresh_var t\u2082) (term.fresh_var t\u2083),\n      have h5, from ge_trans h1 h4,\n      from t\u2082_ih y h5 h3,\n\n      have h4: (term.fresh_var t\u2083 \u2264 max (term.fresh_var t\u2082) (term.fresh_var t\u2083)),\n      from le_max_right (term.fresh_var t\u2082) (term.fresh_var t\u2083),\n      have h5, from ge_trans h1 h4,\n      from t\u2083_ih y h5 h3\n    end,\n\n    show \u2200y: var, y \u2265 term.fresh_var (term.app t\u2084 t\u2085) \u2192 y \u2209 FV (term.app t\u2084 t\u2085), 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\u2084 \u2264 max (term.fresh_var t\u2084) (term.fresh_var t\u2085)),\n      from le_max_left (term.fresh_var t\u2084) (term.fresh_var t\u2085),\n      have h5, from ge_trans h1 h4,\n      from t\u2084_ih y h5 h3,\n\n      have h4: (term.fresh_var t\u2085 \u2264 max (term.fresh_var t\u2084) (term.fresh_var t\u2085)),\n      from le_max_right (term.fresh_var t\u2084) (term.fresh_var t\u2085),\n      have h5, from ge_trans h1 h4,\n      from t\u2085_ih y h5 h3\n    end\n  end\n\nlemma prop.fresh_var_is_unused {P: prop}: \u2200x, x \u2265 P.fresh_var \u2192 \u00ac 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\u2081 P\u2081_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\u2081_ih y h1 h3\n    },\n\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081 \u2264 max (prop.fresh_var P\u2081) (prop.fresh_var P\u2082)),\n      from le_max_left (prop.fresh_var P\u2081) (prop.fresh_var P\u2082),\n      have h5, from ge_trans h1 h4,\n      from P\u2081_ih y h5 h3,\n\n      have h4: (prop.fresh_var P\u2082 \u2264 max (prop.fresh_var P\u2081) (prop.fresh_var P\u2082)),\n      from le_max_right (prop.fresh_var P\u2081) (prop.fresh_var P\u2082),\n      have h5, from ge_trans h1 h4,\n      from P\u2082_ih y h5 h3\n    },\n\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081 \u2264 max (prop.fresh_var P\u2081) (prop.fresh_var P\u2082)),\n      from le_max_left (prop.fresh_var P\u2081) (prop.fresh_var P\u2082),\n      have h5, from ge_trans h1 h4,\n      from P\u2081_ih y h5 h3,\n\n      have h4: (prop.fresh_var P\u2082 \u2264 max (prop.fresh_var P\u2081) (prop.fresh_var P\u2082)),\n      from le_max_right (prop.fresh_var P\u2081) (prop.fresh_var P\u2082),\n      have h5, from ge_trans h1 h4,\n      from P\u2082_ih y h5 h3\n    },\n\n    case prop.pre t\u2081 t\u2082 {\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\u2081 \u2264 max (term.fresh_var t\u2081) (term.fresh_var t\u2082)),\n      from le_max_left (term.fresh_var t\u2081) (term.fresh_var t\u2082),\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\u2082 \u2264 max (term.fresh_var t\u2081) (term.fresh_var t\u2082)),\n      from le_max_right (term.fresh_var t\u2081) (term.fresh_var t\u2082),\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\u2081 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\u2082 op t\u2081 t\u2082 {\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\u2081 \u2264 max (term.fresh_var t\u2081) (term.fresh_var t\u2082)),\n      from le_max_left (term.fresh_var t\u2081) (term.fresh_var t\u2082),\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\u2082 \u2264 max (term.fresh_var t\u2081) (term.fresh_var t\u2082)),\n      from le_max_right (term.fresh_var t\u2081) (term.fresh_var t\u2082),\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\u2081 t\u2082 {\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\u2081 \u2264 max (term.fresh_var t\u2081) (term.fresh_var t\u2082)),\n      from le_max_left (term.fresh_var t\u2081) (term.fresh_var t\u2082),\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\u2082 \u2264 max (term.fresh_var t\u2081) (term.fresh_var t\u2082)),\n      from le_max_right (term.fresh_var t\u2081) (term.fresh_var t\u2082),\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\u2081 P\u2081_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\u2081 \u2264 max (z + 1) (prop.fresh_var P\u2081)),\n      from le_max_right (z + 1) (prop.fresh_var P\u2081),\n      have h5, from ge_trans h1 h4,\n      from P\u2081_ih y h5 a,\n\n      have h4: (z + 1 \u2264 max (z + 1) (prop.fresh_var P\u2081)),\n      from le_max_left (z + 1) (prop.fresh_var P\u2081),\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\u2081 P\u2081_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\u2081 \u2264 max (z + 1) (prop.fresh_var P\u2081)),\n      from le_max_right (z + 1) (prop.fresh_var P\u2081),\n      have h5, from ge_trans h1 h4,\n      from P\u2081_ih y h5 a,\n\n      have h4: (z + 1 \u2264 max (z + 1) (prop.fresh_var P\u2081)),\n      from le_max_left (z + 1) (prop.fresh_var P\u2081),\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 \u2208 FV P \u2192 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\u2081 P\u2081_ih {\n      from vc.uses_var.not (P\u2081_ih (free_in_vc.not.inv h1))\n    },\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      cases (free_in_vc.and.inv h1) with h2 h3,\n\n      from vc.uses_var.and\u2081 (P\u2081_ih h2),\n      from vc.uses_var.and\u2082 (P\u2082_ih h3)\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      cases (free_in_vc.or.inv h1) with h2 h3,\n\n      from vc.uses_var.or\u2081 (P\u2081_ih h2),\n      from vc.uses_var.or\u2082 (P\u2082_ih h3)\n    },\n    case vc.pre t\u2081 t\u2082 {\n      cases (free_in_vc.pre.inv h1) with h2 h3,\n\n      from vc.uses_var.pre\u2081 h2,\n      from vc.uses_var.pre\u2082 h3\n    },\n    case vc.pre\u2081 op t {\n      from vc.uses_var.preop (free_in_vc.pre\u2081.inv h1)\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      cases (free_in_vc.pre\u2082.inv h1) with h2 h3,\n\n      from vc.uses_var.preop\u2081 h2,\n      from vc.uses_var.preop\u2082 h3\n    },\n    case vc.post t\u2081 t\u2082 {\n      cases (free_in_vc.post.inv h1) with h2 h3,\n\n      from vc.uses_var.post\u2081 h2,\n      from vc.uses_var.post\u2082 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 \u2192 x \u2208 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 \u2192 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\u2081 P\u2082: vc} {x: var}: vc.uses_var x (P\u2081 \u22c0 P\u2082) \u2192 vc.uses_var x P\u2081 \u2228 vc.uses_var x P\u2082 :=\n  assume x_free_in_and: vc.uses_var x (P\u2081 \u22c0 P\u2082),\n  begin\n    cases x_free_in_and,\n    case vc.uses_var.and\u2081 free_in_P\u2081 {\n      show vc.uses_var x P\u2081 \u2228 vc.uses_var x P\u2082, from or.inl free_in_P\u2081\n    },\n    case vc.uses_var.and\u2082 free_in_P\u2082 {\n      show vc.uses_var x P\u2081 \u2228 vc.uses_var x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma vc.uses_var.or.inv {P\u2081 P\u2082: vc} {x: var}: vc.uses_var x (P\u2081 \u22c1 P\u2082) \u2192 vc.uses_var x P\u2081 \u2228 vc.uses_var x P\u2082 :=\n  assume x_free_in_or: vc.uses_var x (P\u2081 \u22c1 P\u2082),\n  begin\n    cases x_free_in_or,\n    case vc.uses_var.or\u2081 free_in_P\u2081 {\n      show vc.uses_var x P\u2081 \u2228 vc.uses_var x P\u2082, from or.inl free_in_P\u2081\n    },\n    case vc.uses_var.or\u2082 free_in_P\u2082 {\n      show vc.uses_var x P\u2081 \u2228 vc.uses_var x P\u2082, from or.inr free_in_P\u2082\n    }\n  end\n\nlemma vc.uses_var.univ.inv {P: vc} {x y: var}: vc.uses_var x (vc.univ y P) \u2192 (x = y) \u2228 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 \u2192 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\u2081 P\u2081_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\u2081_ih h2\n    },\n\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih h2,\n      apply prop.uses_var.and\u2082,\n      from P\u2082_ih h3\n    },\n\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih h2,\n      apply prop.uses_var.or\u2082,\n      from P\u2082_ih h3\n    },\n\n    case prop.pre t\u2081 t\u2082 {\n      unfold prop.to_vc at h1,\n      cases h1,\n      from prop.uses_var.pre\u2081 a,\n      from prop.uses_var.pre\u2082 a\n    },\n\n    case prop.pre\u2081 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\u2082 op t\u2081 t\u2082 {\n      unfold prop.to_vc at h1,\n      cases h1,\n      from prop.uses_var.preop\u2081 a,\n      from prop.uses_var.preop\u2082 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: \u00ac free_in_term x value.true, from free_in_term.value.inv,\n      contradiction\n    },\n\n    case prop.post t\u2081 t\u2082 {\n      unfold prop.to_vc at h1,\n      cases h1,\n      from prop.uses_var.post\u2081 a,\n      from prop.uses_var.post\u2082 a\n    },\n\n    case prop.forallc z P\u2081 P\u2081_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\u2081_ih h3\n    },\n\n    case prop.exis z P\u2081 P\u2081_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\u2081_ih h5\n    }\n  end\n\nlemma to_vc_closed_of_closed {P: prop}: closed P \u2192 closed P.to_vc :=\n  assume P_closed: closed P,\n  assume x: var,\n  assume : x \u2208 FV P.to_vc,\n  have x \u2208 FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_to_vc,\n  show \u00abfalse\u00bb, from P_closed x this\n\nlemma free_in_prop.implies\u2081 {x: var} {P Q: prop}: free_in_prop x P \u2192 free_in_prop x (prop.implies P Q) :=\n  begin\n    assume h1,\n    unfold prop.implies,\n    apply free_in_prop.or\u2081,\n    from free_in_prop.not h1\n  end\n\nlemma free_in_prop.implies\u2082 {x: var} {P Q: prop}: free_in_prop x Q \u2192 free_in_prop x (prop.implies P Q) :=\n  begin\n    assume h1,\n    unfold prop.implies,\n    apply free_in_prop.or\u2082,\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": "-- 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\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-- \u03b1 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 {\u03b1 : 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 \u2192 itactic \u2192 tactic unit\n| n t := do goals \u2190 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 \u2190 get_goals,\n            set_goals (earlier_goals ++ new_goals ++ later_goals)\nend interactive\n\ninductive tactic_script (\u03b1 : Type) : Type\n| base : \u03b1 \u2192 tactic_script\n| work (index : \u2115) (first : \u03b1) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string \u2192 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(\u03bb m : tactic_script string, m.to_string))) ++ \" }\"\n\nmeta instance : has_to_string (tactic_script string) := \n{ to_string := \u03bb s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) := \n{ to_string := \u03bb s, \"[chain tactic]\" }\n\nmeta def abstract_if_success {\u03b1} (tac : expr \u2192 tactic \u03b1) (g : expr) : tactic \u03b1 :=\ndo \n  type \u2190 infer_type g,\n  is_lemma \u2190 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 \u2190 mk_meta_var type,\n    a \u2190 tac m,\n    do {\n      val \u2190 instantiate_mvars m,\n      guard (val.list_meta_vars = []),\n      c  \u2190 new_aux_decl_name,\n      gs \u2190 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 {\u03b1} (tac : tactic \u03b1)\nwith chain_single : expr \u2192 tactic (\u03b1 \u00d7 list (tactic_script \u03b1)) | g :=\ndo set_goals [g],\n  a \u2190 tac,\n  l \u2190 get_goals >>= chain_many,\n  return (a, l)\nwith chain_many : list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] := return []\n| [g] := do {\n  (a, l) \u2190 chain_single g,\n  return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr \u2192 list expr \u2192 tactic (list (tactic_script \u03b1))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do {\n  (a, l) \u2190 abstract_if_success chain_single g,\n  new_goals \u2190 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' \u2190 chain_many current_goals,\n  return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {\u03b1 : Type} [has_to_string (tactic_script \u03b1)] (tactics : list (tactic \u03b1)) : tactic (list string) :=\ndo results \u2190 (get_goals >>= chain_many (first tactics)),\n   when (results.empty) (fail \"`chain` tactic made no progress\"),\n   return (results.map (\u03bb r : tactic_script \u03b1, to_string r))\n\nvariables [has_to_string (tactic_script \u03b1)] [has_to_format \u03b1]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic \u03b1) : tactic \u03b1 :=\ndo tgt \u2190 target,\n   r \u2190 t,\n   name \u2190 decl_name,\n   trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n   tgt \u2190 pp tgt,\n   trace format!\"previous target: {tgt}\",\n   trace format!\"tactic result: {r}\",\n   tgt \u2190 try_core target,\n   tgt \u2190 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\nprivate meta def chain_handle_trace (tactics : list (tactic \u03b1)) : tactic (list string) :=\nif is_trace_enabled_for `chain then\n  chain_core (tactics.map trace_output)\nelse \n  chain_core tactics\n\nmeta def chain (tactics : list (tactic \u03b1)) : tactic (list string) :=\ndo sequence \u2190 chain_handle_trace tactics,\n   when (sequence.empty) (fail \"`chain` tactic made no progress\"),\n   pure sequence\n\nend tactic", "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/chain.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195803163617, "lm_q2_score": 0.05582313642224893, "lm_q1q2_score": 0.021280872638832743}}
{"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) \u2192 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) \u2192 (B : ByteArray) \u2192 (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 \u2192 Target)\n\nexport Into (into)\n\ninstance (A: Type u) : Into A A := \u27e8id\u27e9\n\ninstance (A: Type u) (h: A \u2192 Prop) : Into A (Subtype h) := \u27e8Subtype.val\u27e9\n\n/-\nTransitivity\n-/\ninstance (A B C: Type u) [Into B C] [Into A B] : Into A C := \u27e8fun c : C =>\n          let b: B := Into.into c;\n          Into.into b\u27e9\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 \u2192 Nat \u2192 Key simpleReduce\n  | fvar  : FVarId \u2192 Nat \u2192 Key simpleReduce\n  | lit   : Literal \u2192 Key simpleReduce\n  | star  : Key simpleReduce\n  | other : Key simpleReduce\n  | arrow : Key simpleReduce\n  | proj  : Name \u2192 Nat \u2192 Nat \u2192 Key simpleReduce\n  deriving Inhabited, BEq, Repr\n\nprotected def Key.hash : Key s \u2192 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) := \u27e8Key.hash\u27e9\n\n/--\nDiscrimination tree trie. See `DiscrTree`.\n-/\ninductive Trie (\u03b1 : Type) (simpleReduce : Bool) where\n  | node (vs : Array \u03b1) (children : Array (Key simpleReduce \u00d7 Trie \u03b1 simpleReduce)) : Trie \u03b1 simpleReduce\n\nend DiscrTree\n\nopen DiscrTree\n\n/--\nDiscrimination trees. It is an index from terms to values of type `\u03b1`.\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 : \u03b1) (f : \u03b1 \u2192 \u03b3) (h : \u2200 a\u2081 a\u2082, r a\u2081 a\u2082 \u2192 f a\u2081 = f a\u2082) :\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 \u2192 b.interp \u2192 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 (\u03b1 : Type) (simpleReduce : Bool) where\n  root : PersistentHashMap (Key simpleReduce) (Trie \u03b1 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": "import init.meta.expr\nimport data.multiset.basic\n\n-- Define a hole expression type in which holes can be annotated with hole expressions they have to contain or \n-- may nor contain. We directly generalize `expr`. For the moment, only annotate holes (`mvar`) and `app` to allow\n-- `contains` to `or`-distribute over the children.\n\n-- _ +(z, no x) (_ + _) = (_ + _) + _\n-- linear_indepent _ i(S) -> linear_independent _ j(S)\n\n-- _ = _(no x!!)\n\nmeta inductive gvar\n/- A bound variable with a de-Bruijn index. -/\n| var         (i : nat) : gvar\n/- A type universe: `Sort u` -/\n| sort        (l : level) : gvar\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 : name) (ls : list level) : gvar\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 : gvar) (contains : multiset gvar) (avoids : multiset gvar) : gvar\n/- A local constant. For example, if our tactic state was `h : P \u22a2 Q`, `h` would be a local constant. -/\n| local_const (unique : name) (pretty : name) (bi : binder_info) (type : gvar) : gvar\n/- Function application. -/\n| app         (f : gvar) (x : gvar) (contains : multiset gvar) (avoids : multiset gvar) : gvar\n/- Lambda abstraction. eg ```(\u03bb a : \u03b1, x)`` -/\n| lam         (var_name : name) (bi : binder_info) (var_type : gvar) (body : gvar) : gvar\n/- Pi type constructor. eg ```(\u03a0 a : \u03b1, x)`` and ```(\u03b1 \u2192 \u03b2)`` -/\n| pi          (var_name : name) (bi : binder_info) (var_type : gvar) (body : gvar) : gvar\n/- An explicit let binding. -/\n| elet        (var_name : name) (type : gvar) (assignment : gvar) (body : gvar) : gvar\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       (m : macro_def) (args : list expr) : gvar\n-- with annotation : Type\n-- | mk  : annotation\n\n\n-- Forget annotations to obtain usual `expr`. What do we need to add to prove termination?\nmeta def to_expr : gvar -> expr\n| (gvar.var i) := expr.var i\n| (gvar.sort l) := expr.sort l\n| (gvar.const nm ls) := expr.const nm ls\n| (gvar.mvar unm nm ty _ _) := expr.mvar unm nm (to_expr ty)\n| (gvar.local_const unm nm bi ty) := expr.local_const unm nm bi (to_expr ty)\n| (gvar.app f x _ _) := expr.app (to_expr f) (to_expr x)\n| (gvar.lam nm bi ty body) := expr.lam nm bi (to_expr ty) (to_expr body)\n| (gvar.pi nm bi ty body) := expr.pi nm bi (to_expr ty) (to_expr body)\n| (gvar.elet nm ty val body) := expr.elet nm (to_expr ty) (to_expr val) (to_expr body)\n| (gvar.macro m args) := expr.macro m args\n\n\n-- Unification procedure.\n\n-- Idea: use Lean's (higher-order) `unify` on the corresponding `expr`s. Then check whether the `mvar` assignments\n-- respected the `contains` and `avoids` requirements. `avoids` should `and`-distribute to children, `contains` should\n-- `or`-distribute. We will first implement a naive recursive version that propagates all conditions of the given\n-- level downward, then recurses to deeper levels. The HO unification procedure could in principle be swapped.\n\n-- TODO:\n-- Lean 3 vs Lean 4\n-- Access to unify internals?\n-- quantified MP?\n\n-- string bool name nat int syntax\n-- mdata: name\n-- hashmap: name \u2192 annotation\n\n-- quantified MP forward\nexample (P Q : \u2115 \u2192 Prop )(h : \u2200 a b c : \u2115, P c) (hh : \u2200 a b c : \u2115, P c \u2192 Q c) : \n  \u2200 a b c : \u2115, Q c :=\n\u03bb a b c, hh a b c (h a b c)\n\n-- quantified MT forward\nexample (P Q R : \u2115 \u2192 Prop )(h : \u2200 a b c : \u2115, P c \u2192 Q c) (hh : \u2200 a b c : \u2115, Q c \u2192 R c) : \n  \u2200 a b c : \u2115, P c \u2192 R c :=\n\u03bb a b c hp, hh a b c (h a b c hp)\n\n-- quantified MP backward\nexample (P Q : \u2115 \u2192 Prop ) (hh : \u2200 a b c : \u2115, P c \u2192 Q c) : \n  \u2200 a b c : \u2115, Q c :=\nbegin\n  intros,\n  apply hh,\n  rotate 2,\n  revert a b c,\n  repeat {sorry}\nend\n\n-- quantified MT backward\nexample (P Q R : \u2115 \u2192 Prop ) (hh : \u2200 a b c : \u2115, Q c \u2192 R c) : \n  \u2200 a b c : \u2115, P c \u2192 R c :=\nbegin\n  intros a b c hq,\n  apply hh,\n  rotate 2,\n  revert a b c,\n  repeat {sorry}\nend", "meta": {"author": "faabian", "repo": "hatp", "sha": "d477399063db85a43c0b998fd269bca427e5aaf9", "save_path": "github-repos/lean/faabian-hatp", "path": "github-repos/lean/faabian-hatp/hatp-d477399063db85a43c0b998fd269bca427e5aaf9/src/gvar.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04272219632766466, "lm_q1q2_score": 0.021194217979599618}}
{"text": "/-\nCopyright (c) 2022 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\nimport Aesop\n\nset_option aesop.check.all true\n\n-- When parsing the names of declarations for local rules, Aesop should take the\n-- currently opened namespaces into account.\n\nexample : List \u03b1 := by\n  aesop (add safe List.nil)\n\nnamespace List\n\nexample : List \u03b1 := by\n  aesop (add safe List.nil)\n\nexample : List \u03b1 := by\n  aesop (add safe nil)\n\nend List\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/run/NameResolution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.06008665354025421, "lm_q1q2_score": 0.02116262727129841}}
{"text": "import Lean\n\nset_option linter.all true\n\n/-- A doc string -/\ndef hasDoc (x : Nat) := x\n\ndef noDoc (x : Nat) := x\n\nprivate def auxDef (x : Nat) := x\n\nnamespace Foo\nprotected def noDoc2 (x : Nat) := x\nend Foo\n\nopen Foo in\ndef openIn (x : Nat) := x\n\nopen Foo in\n/-- A doc string -/\ndef openIn2 (x : Nat) := x\n\nset_option pp.all true in\ndef setOptionIn1 (x : Nat) := x\n\nset_option pp.all true in\n/-- A doc string -/\ndef setOptionIn2 (x : Nat) := x\n\nset_option linter.all false in\ndef nolintAll (x : Nat) := x\n\nset_option linter.all true in\nset_option linter.missingDocs false in\ndef nolintDoc (x : Nat) := x\n\nset_option linter.all false in\nset_option linter.missingDocs true in\ndef lintDoc (x : Nat) := x\n\ninductive Ind where\n  | ind1\n  | ind2 : Ind \u2192 Ind\n  /-- A doc string -/ | doc : Ind\nwith\n  @[computed_field] field : Ind \u2192 Nat\n  | _ => 1\n\nstructure Foo where\n  mk1 : Nat\n  /-- test -/\n  (mk2 mk3 : Nat)\n  {mk4 mk5 : Nat}\n  [mk6 mk7 : Nat]\n\nclass Bar (\u03b1 : Prop) := mk ::\n  (foo bar := 1)\n\nclass Bar2 (\u03b1 : Prop) where\n  bar := 2\n\nclass Bar3 (\u03b1 : Prop) extends Bar \u03b1 where\n  bar := 3\n  (foo baz := 3)\n\ntheorem aThm : True := trivial\nexample : True := trivial\ninstance : Bar True := {}\n\ninitialize init : Unit \u2190 return\ninitialize return\n\ndeclare_syntax_cat myCat\n\nsyntax \"my_syn\" : myCat\nsyntax (name := namedSyn) \"my_named_syn\" myCat : command\ninfixl:20 \"<my_infix>\" => Nat.add\ninfixr:20 (name := namedInfix) \"<my_named_infix>\" => Nat.add\nnotation:20 \"my_notation\" x y => Nat.add x y\nnotation:20 (name := namedNota) \"my_named_notation\" x y => Nat.add x y\n\nmacro_rules | `(my_named_syn my_syn) => `(def hygienic := 1)\nelab_rules : command | `(my_named_syn my_syn) => return\n\nmy_named_syn my_syn\n\nelab \"my_elab\" : term => return Lean.mkConst ``false\nmacro \"my_macro\" : term => `(my_elab)\n\nclass abbrev BarAbbrev (\u03b1 : Prop) := Bar \u03b1\n\nregister_option myOption : Bool := { defValue := my_macro, descr := \"hi mom\" }\n\nelab (name := myCmd) (docComment)? \"my_command\" ident : command => pure ()\n\nmy_command x\n\nopen Lean.Linter.MissingDocs in\n@[missing_docs_handler myCmd]\ndef handleMyCmd : SimpleHandler := fun\n  | `(my_command $x:ident) => lintNamed x \"my_command\"\n  | _ => pure ()\n\n/-- doc -/\nmy_command y\n\nmy_command z\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/linterMissingDocs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017684487511, "lm_q2_score": 0.060086647228542, "lm_q1q2_score": 0.02116262341404874}}
{"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 `\u2200 x, ...`,\n`\u2203 x, ...` and `\u03bb 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 `\u2200 x, ...`, `\u2203 x, ...` and `\u03bb 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 `\u2190` is applied in the reverse direction.\n  - `simp_rw [lemma_1, ..., lemma_n] at h\u2081 ... h\u2099` will rewrite the given hypotheses.\n  - `simp_rw [...] at \u22a2 h\u2081 ... h\u2099` 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 {\u03b1 \u03b2 : Type} {f : \u03b1 \u2192 \u03b2} {t : set \u03b2} :\n  (\u2200 s, f '' s \u2286 t) = \u2200 s : set \u03b1, \u2200 x \u2208 s, x \u2208 f \u207b\u00b9' 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' (\u03bb 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 Jun Yoshida. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n-/\n\nimport Dijkstra\n\nuniverse u\n\n@[reducible]\ndef WPExcept (\u03b5 : Type u) := ExceptT \u03b5 WPPure\n\ninstance (\u03b5 : Type u) : Monad (WPExcept \u03b5) :=\n  inferInstanceAs (Monad (ExceptT \u03b5 WPPure))\n\nprotected\ndef WPExcept.rel (\u03b5 : Type u) : MonadRel (WPExcept \u03b5) (WPExcept \u03b5) where\n  rel {\u03b1} x y := \u2200 (p : Except \u03b5 \u03b1 \u2192 Prop), y.predT p \u2192 x.predT p\n  pure a p := by dsimp; exact id\n  bind {\u03b1} {\u03b2} {x} {y} f g hxy hfg p := by\n    dsimp [bind] at *\n    dsimp [ExceptT.bind, ExceptT.mk]\n    apply mrel_bind (m:=WPPure) hxy\n    intro a\n    cases a\n    case a.error e =>\n      dsimp [ExceptT.bindCont]\n      exact mrel_pure (m:=WPPure) _\n    case a.ok a =>\n      dsimp [ExceptT.bindCont]\n      exact hfg a\n\ninstance (\u03b5 : Type u) : SpecMonad (WPExcept \u03b5) where\n  rel := WPExcept.rel \u03b5\n  trans := by\n    dsimp [WPExcept.rel]\n    intro \u03b1 x y z hxy hyz p hp\n    exact hxy p (hyz p hp)\n\nexample (\u03b5 : Type u) (\u03b1 : Type _) : WPPure \u03b1 \u2192 WPExcept \u03b5 \u03b1 := monadLift\n", "meta": {"author": "Junology", "repo": "dijkstra", "sha": "19ff3ddd7ff112c69848fa9c643f773008cdd5ff", "save_path": "github-repos/lean/Junology-dijkstra", "path": "github-repos/lean/Junology-dijkstra/dijkstra-19ff3ddd7ff112c69848fa9c643f773008cdd5ff/test/WPExcept.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.04958902456418654, "lm_q1q2_score": 0.021140871925080622}}
{"text": "/-\nCopyright (c) 2020 Minchao Wu. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Minchao Wu\n-/\nimport tactic.explode\nimport tactic.interactive_expr\n\n/-!\n# `#explode_widget` command\n\nRender a widget that displays an `#explode` proof, providing more\ninteractivity such as jumping to definitions and exploding constants\noccurring in the exploded proofs.\n-/\nopen widget tactic tactic.explode\n\nmeta instance widget.string_to_html {\u03b1} : has_coe string (html \u03b1) :=\n\u27e8\u03bb s, s\u27e9\n\nnamespace tactic\nnamespace explode_widget\nopen widget_override.interactive_expression\nopen tagged_format\nopen widget.html widget.attr\n\n/-- Redefine some of the style attributes for better formatting. -/\nmeta def get_block_attrs {\u03b3}: sf \u2192 tactic (sf \u00d7 list (attr \u03b3))\n| (sf.block i a) := do\n  let s : attr (\u03b3) := style [\n    (\"display\", \"inline-block\"),\n    (\"white-space\", \"pre-wrap\"),\n    (\"vertical-align\", \"top\")\n  ],\n  (a,rest) \u2190 get_block_attrs a,\n  pure (a, s :: rest)\n| (sf.highlight c a) := do\n  (a, rest) \u2190 get_block_attrs a,\n  pure (a, (cn c.to_string) :: rest)\n| a := pure (a,[])\n\n/-- Explode button for subsequent exploding. -/\nmeta def insert_explode {\u03b3} : expr \u2192 tactic (list (html (action \u03b3)))\n| (expr.const n _) := (do\n    pure $ [h \"button\" [\n      cn \"pointer ba br3 mr1\",\n      on_click (\u03bb _, action.effect $ widget.effect.insert_text (\"#explode_widget \" ++ n.to_string)),\n      attr.val \"title\" \"explode\"] [\"\ud83d\udca5\"]]\n  ) <|> pure []\n| e := pure []\n\n/--\nRender a subexpression as a list of html elements.\n-/\nmeta def view {\u03b3} (tooltip_component : tc subexpr (action \u03b3))\n  (click_address : option expr.address)\n  (select_address : option expr.address) :\n  subexpr \u2192 sf \u2192 tactic (list (html (action \u03b3)))\n| \u27e8ce, current_address\u27e9 (sf.tag_expr ea e m) := do\n  let new_address := current_address ++ ea,\n  let select_attrs : list (attr (action \u03b3)) :=\n    if some new_address = select_address then\n       [className \"highlight\"] else [],\n  click_attrs  : list (attr (action \u03b3)) \u2190\n    if some new_address = click_address then do\n      content \u2190 tc.to_html tooltip_component (e, new_address),\n      efmt : string \u2190 format.to_string <$> tactic.pp e,\n      gd_btn \u2190 goto_def_button e,\n      epld_btn \u2190 insert_explode e,\n      pure [tooltip $ h \"div\" [] [\n          h \"div\" [cn \"fr\"] (gd_btn ++ epld_btn ++ [\n            h \"button\" [cn \"pointer ba br3 mr1\", on_click\n                       (\u03bb _, action.effect $ widget.effect.copy_text efmt),\n                       attr.val \"title\" \"copy expression to clipboard\"] [\"\ud83d\udccb\"],\n            h \"button\" [cn \"pointer ba br3\", on_click\n                       (\u03bb _, action.on_close_tooltip),\n                       attr.val \"title\" \"close\"] [\"\u00d7\"]\n          ]),\n          content\n      ]]\n    else pure [],\n  (m, block_attrs) \u2190 get_block_attrs m,\n  let as := [className \"expr-boundary\", key (ea)] ++ select_attrs ++\n            click_attrs ++ block_attrs,\n  inner \u2190 view (e,new_address) m,\n  pure [h \"span\" as inner]\n| ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y\n| ca (sf.of_string s) := pure\n  [h \"span\" [\n    on_mouse_enter (\u03bb _, action.on_mouse_enter ca),\n    on_click (\u03bb _, action.on_click ca),\n    key s\n  ] [html.of_string s]]\n| ca b@(sf.block _ _) := do\n  (a, attrs) \u2190 get_block_attrs b,\n  inner \u2190 view ca a,\n  pure [h \"span\" attrs inner]\n| ca b@(sf.highlight _ _) := do\n  (a, attrs) \u2190 get_block_attrs b,\n  inner \u2190 view ca a,\n  pure [h \"span\" attrs inner]\n\n/-- Make an interactive expression. -/\nmeta def mk {\u03b3} (tooltip : tc subexpr \u03b3) : tc expr \u03b3 :=\nlet tooltip_comp :=\n   component.with_should_update\n   (\u03bb (x y : tactic_state \u00d7 expr \u00d7 expr.address), x.2.2 \u2260 y.2.2)\n   $ component.map_action (action.on_tooltip_action) tooltip in\n   component.filter_map_action\n   (\u03bb _ (a : \u03b3 \u2295 widget.effect), sum.cases_on a some (\u03bb _, none))\n$ component.with_effects (\u03bb _ (a : \u03b3 \u2295 widget.effect),\n  match a with\n  | (sum.inl g) := []\n  | (sum.inr s) := [s]\n  end\n)\n$ tc.mk_simple\n  (action \u03b3)\n  (option subexpr \u00d7 option subexpr)\n  (\u03bb e, pure $ (none, none))\n  (\u03bb e \u27e8ca, sa\u27e9 act, pure $\n    match act with\n    | (action.on_mouse_enter \u27e8e, ea\u27e9) := ((ca, some (e, ea)), none)\n    | (action.on_mouse_leave_all)     := ((ca, none), none)\n    | (action.on_click \u27e8e, ea\u27e9)       := if some (e,ea) = ca then\n                                         ((none, sa), none) else\n                                         ((some (e, ea), sa), none)\n    | (action.on_tooltip_action g)    := ((none, sa), some $ sum.inl g)\n    | (action.on_close_tooltip)       := ((none, sa), none)\n    | (action.effect e)               := ((ca,sa), some $ sum.inr $ e)\n    end\n  )\n  (\u03bb e \u27e8ca, sa\u27e9, do\n    m \u2190 sf.of_eformat <$> tactic.pp_tagged e,\n    let m := m.elim_part_apps,\n    let m := m.flatten,\n    let m := m.tag_expr [] e,\n    v \u2190 view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) \u27e8e, []\u27e9 m,\n    pure $\n    [ h \"span\" [\n          className \"expr\",\n          key e.hash,\n          on_mouse_leave (\u03bb _, action.on_mouse_leave_all) ] $ v\n      ]\n  )\n\n/-- Render the implicit arguments for an expression in fancy, little pills. -/\nmeta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do\n  fn \u2190 (mk tooltip) $ expr.get_app_fn e,\n  args \u2190 list.mmap (mk tooltip) $ expr.get_app_args e,\n  pure $ h \"div\" []\n    ( (h \"span\" [className \"bg-blue br3 ma1 ph2 white\"] [fn]) ::\n      list.map (\u03bb a, h \"span\" [className \"bg-gray br3 ma1 ph2 white\"] [a]) args\n    )\n\n/--\nComponent for the type tooltip.\n-/\nmeta def type_tooltip : tc subexpr empty :=\ntc.stateless (\u03bb \u27e8e,ea\u27e9, do\n    y \u2190 tactic.infer_type e,\n    y_comp \u2190 mk type_tooltip y,\n    implicit_args \u2190 implicit_arg_list type_tooltip e,\n    pure [h \"div\" [style [(\"minWidth\", \"12rem\")]] [\n          h \"div\" [cn \"pl1\"] [y_comp],\n          h \"hr\" [] [],\n          implicit_args\n        ]\n      ]\n  )\n\n/--\nComponent that shows a type.\n-/\nmeta def show_type_component : tc expr empty :=\ntc.stateless (\u03bb x, do\n  y \u2190 infer_type x,\n  y_comp \u2190 mk type_tooltip $ y,\n  pure y_comp\n)\n\n/--\nComponent that shows a constant.\n-/\nmeta def show_constant_component : tc expr empty :=\ntc.stateless (\u03bb x, do\n  y_comp \u2190 mk type_tooltip x,\n  pure y_comp\n)\n\n/--\nSearch for an entry that has the specified line number.\n-/\nmeta def lookup_lines : entries \u2192 nat \u2192 entry\n| \u27e8_, []\u27e9 n := \u27e8default, 0, 0, status.sintro, thm.string \"\", []\u27e9\n| \u27e8rb, (hd::tl)\u27e9 n := if hd.line = n then hd else lookup_lines \u27e8rb, tl\u27e9 n\n\n\n/--\nRender a row that shows a goal.\n-/\nmeta def goal_row (e : expr) (show_expr := tt): tactic (list (html empty)) :=\ndo t \u2190 explode_widget.show_type_component e,\nreturn $ [h \"td\" [cn \"ba bg-dark-green tc\"] \"Goal\",\n          h \"td\" [cn \"ba tc\"]\n          (if show_expr then [html.of_name e.local_pp_name, \" : \", t] else t)]\n\n/--\nRender a row that shows the ID of a goal.\n-/\nmeta def id_row {\u03b3} (l : nat): tactic (list (html \u03b3)) :=\nreturn $ [h \"td\" [cn \"ba bg-dark-green tc\"] \"ID\",\n          h \"td\" [cn \"ba tc\"] (to_string l)]\n\n/--\nRender a row that shows the rule or theorem being applied.\n-/\nmeta def rule_row : thm \u2192  tactic (list (html empty))\n| (thm.expr e) := do t \u2190 explode_widget.show_constant_component e,\n                     return $ [h \"td\" [cn \"ba bg-dark-green tc\"] \"Rule\",\n                               h \"td\" [cn \"ba tc\"] t]\n| t := return $ [h \"td\" [cn \"ba bg-dark-green tc\"] \"Rule\",\n                 h \"td\" [cn \"ba tc\"] t.to_string]\n\n/--\nRender a row that contains the sub-proofs, i.e., the proofs of the\narguments.\n-/\nmeta def proof_row {\u03b3} (args : list (html \u03b3)): list (html \u03b3) :=\n[h \"td\" [cn \"ba bg-dark-green tc\"] \"Proofs\", h \"td\" [cn \"ba tc\"]\n    [h \"details\" [] $\n        (h \"summary\"\n            [attr.style [(\"color\", \"orange\")]]\n                \"Details\")::args]\n]\n\n/--\nCombine the goal row, id row, rule row and proof row to make them a table.\n-/\nmeta def assemble_table {\u03b3} (gr ir rr) : list (html \u03b3) \u2192 html \u03b3\n| [] :=\nh \"table\" [cn \"collapse\"]\n    [h \"tbody\" []\n        [h \"tr\" [] gr, h \"tr\" [] ir, h \"tr\" [] rr]\n    ]\n| pr :=\nh \"table\" [cn \"collapse\"]\n    [h \"tbody\" []\n        [h \"tr\" [] gr, h \"tr\" [] ir, h \"tr\" [] rr, h \"tr\" [] pr]\n    ]\n\n/--\nRender a table for a given entry.\n-/\nmeta def assemble (es : entries): entry \u2192 tactic (html empty)\n| \u27e8e, l, d, status.sintro, t, ref\u27e9 := do\n    gr \u2190 goal_row e, ir \u2190 id_row l, rr \u2190 rule_row $ thm.string \"Assumption\",\n    return $ assemble_table gr ir rr []\n| \u27e8e, l, d, status.intro, t, ref\u27e9 := do\n    gr \u2190 goal_row e, ir \u2190 id_row l, rr \u2190 rule_row $ thm.string  \"Assumption\",\n    return $ assemble_table gr ir rr []\n| \u27e8e, l, d, st, t, ref\u27e9 := do\n    gr \u2190 goal_row e ff, ir \u2190 id_row l, rr \u2190 rule_row t,\n    let el : list entry := list.map (lookup_lines es) ref,\n    ls \u2190 monad.mapm assemble el,\n    let pr := proof_row $ ls.intersperse (h \"br\" [] []),\n    return $ assemble_table gr ir rr pr\n\n/--\nRender a widget from given entries.\n-/\nmeta def explode_component (es : entries) : tactic (html empty) :=\nlet concl := lookup_lines es (es.l.length - 1) in assemble es concl\n\n/--\nExplode a theorem and return entries.\n-/\nmeta def explode_entries (n : name) (hide_non_prop := tt) : tactic entries :=\ndo expr.const n _ \u2190 resolve_name n | fail \"cannot resolve name\",\n  d \u2190 get_decl n,\n  v \u2190 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 \u2190 pp d.type,\n  explode_expr v hide_non_prop\n\nend explode_widget\n\nopen explode_widget\n\nsetup_tactic_parser\n\n/--\nUser command of the explode widget.\n-/\n@[user_command]\nmeta def explode_widget_cmd (_ : parse $ tk \"#explode_widget\") : lean.parser unit :=\ndo \u27e8li,co\u27e9 \u2190 cur_pos,\n    n \u2190 ident,\n    es \u2190 explode_entries n,\n    comp \u2190 parser.of_tactic (do html \u2190 explode_component es,\n    c \u2190 pure $ component.stateless (\u03bb _, [html]),\n    pure $ component.ignore_props $ component.ignore_action $ c),\n    save_widget \u27e8li, co - \"#explode_widget\".length - 1\u27e9 comp,\n    trace \"successfully rendered widget\",\n    skip\n    .\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_widget.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415825128436339, "lm_q2_score": 0.06187598918353437, "lm_q1q2_score": 0.02113575586999718}}
{"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 \u27f6 Y)\n\n/--\nA morphism is `finite` if the preimages of finite open sets are finite.\n-/\n@[mk_iff]\nclass finite (f : X \u27f6 Y) extends affine f : Prop :=\n(is_finite_of_affine : \u2200 U : opens Y.carrier, is_affine_open U \u2192 (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 \u25b8 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 \u2264 @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\u2081 P\u2082 : morphism_property C} (h\u2081 : P\u2081.respects_iso) (h\u2082 : P\u2082.respects_iso) :\n    (P\u2081 \u2293 P\u2082).respects_iso :=\n\u27e8\u03bb _ _ _ _ _ \u27e8H\u2081, H\u2082\u27e9, \u27e8h\u2081.1 _ _ H\u2081, h\u2082.1 _ _ H\u2082\u27e9,\n    \u03bb _ _ _ _ _ \u27e8H\u2081, H\u2082\u27e9, \u27e8h\u2081.2 _ _ H\u2081, h\u2082.2 _ _ H\u2082\u27e9\u27e9\n\n-- move me\nlemma property_is_local_at_target.inf {P\u2081 P\u2082} (h\u2081 : property_is_local_at_target P\u2081)\n  (h\u2082 : property_is_local_at_target P\u2082) : property_is_local_at_target (P\u2081 \u2293 P\u2082) :=\n\u27e8h\u2081.1.inf h\u2082.1, \u03bb X Y f U H, \u27e8h\u2081.2 _ _ H.1, h\u2082.2 _ _ H.2\u27e9, \u03bb X Y f \ud835\udcb0 H,\n  \u27e8h\u2081.3 _ \ud835\udcb0 $ \u03bb i, (H i).1, h\u2082.3 _ \ud835\udcb0 $ \u03bb i, (H i).2\u27e9\u27e9\n\nlemma finite_Spec_iff {R S : CommRing} (f : R \u27f6 S) :\n  finite (Scheme.Spec.map f.op) \u2194 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 \u2293 @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 \u27e8ring_hom.finite.of_surjective _ H, infer_instance\u27e9 },\n  { rintro \u27e8h\u2081, h\u2082\u27e9,\n    rw functor.mono_map_iff_mono at h\u2082,\n    resetI,\n    refine ring_hom.surjective_of_epi_of_finite _ _ h\u2081,\n    convert @@category_theory.unop_epi_of_mono _ f.op h\u2082; exact CommRing.of_eq _ }\nend\n\n@[priority 100]\ninstance is_closed_immersion.to_finite {X Y : Scheme} (f : X \u27f6 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 \u27f6 Y) (g : Y \u27f6 Z)\n  [finite f] [finite g] : finite (f \u226b g) :=\nfinite_stable_under_composition _ _ infer_instance infer_instance\n\n-- lemma finite.affine_open_cover_tfae {X Y : Scheme.{u}} (f : X \u27f6 Y) :\n--   tfae [finite f,\n--     \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} Y) [\u2200 i, is_affine (\ud835\udcb0.obj i)],\n--       \u2200 (i : \ud835\udcb0.J), is_affine (pullback f (\ud835\udcb0.map i)) \u2227\n--         ring_hom.finite (Scheme.\u0393.map (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _).op),\n--     \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} Y) [\u2200 i, is_affine (\ud835\udcb0.obj i)] (i : \ud835\udcb0.J),\n--       is_affine (pullback f (\ud835\udcb0.map i)) \u2227\n--         ring_hom.finite (Scheme.\u0393.map (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _).op),\n--     \u2200 {U : Scheme} (g : U \u27f6 Y) [is_affine U] [is_open_immersion g],\n--       is_affine (pullback f g) \u2227\n--         ring_hom.finite (Scheme.\u0393.map (pullback.snd : pullback f g \u27f6 _).op)] :=\n-- finite_eq_affine_property.symm \u25b8\n--   finite.affine_property_is_local.affine_open_cover_tfae f\n\n-- lemma finite.open_cover_tfae {X Y : Scheme.{u}} (f : X \u27f6 Y) :\n--   tfae [finite f,\n--     \u2203 (\ud835\udcb0 : Scheme.open_cover.{u} Y), \u2200 (i : \ud835\udcb0.J),\n--       finite (pullback.snd : (\ud835\udcb0.pullback_cover f).obj i \u27f6 \ud835\udcb0.obj i),\n--     \u2200 (\ud835\udcb0 : Scheme.open_cover.{u} Y) (i : \ud835\udcb0.J),\n--       finite (pullback.snd : (\ud835\udcb0.pullback_cover f).obj i \u27f6 \ud835\udcb0.obj i),\n--     \u2200 (U : opens Y.carrier), finite (f \u2223_ U),\n--     \u2200 {U : Scheme} (g : U \u27f6 Y) [is_open_immersion g],\n--       finite (pullback.snd : pullback f g \u27f6 _)] :=\n-- affine_eq_affine_property.symm \u25b8\n--   affine_affine_property_is_local.open_cover_tfae f\n\nlemma finite_over_affine_iff [is_affine Y] :\n  finite f \u2194 is_affine X \u2227 ring_hom.finite (Scheme.\u0393.map f.op) :=\nfinite_eq_affine_property.symm \u25b8\n  finite.affine_property_is_local.affine_target_iff f\n\nlemma finite.affine_open_cover_iff {X Y : Scheme.{u}} (\ud835\udcb0 : Scheme.open_cover.{u} Y)\n  [\u2200 i, is_affine (\ud835\udcb0.obj i)] (f : X \u27f6 Y) :\n  finite f \u2194 \u2200 i, is_affine (pullback f (\ud835\udcb0.map i)) \u2227\n    ring_hom.finite (Scheme.\u0393.map (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _).op) :=\nfinite_eq_affine_property.symm \u25b8\n  finite.affine_property_is_local.affine_open_cover_iff f \ud835\udcb0\n\nlemma finite.open_cover_iff {X Y : Scheme.{u}} (\ud835\udcb0 : Scheme.open_cover.{u} Y)\n  [\u2200 i, is_affine (\ud835\udcb0.obj i)] (f : X \u27f6 Y) :\n  finite f \u2194 \u2200 i, finite (pullback.snd : pullback f (\ud835\udcb0.map i) \u27f6 _) :=\nfinite_eq_affine_property.symm \u25b8\n  finite.affine_property_is_local.target_affine_locally_is_local.open_cover_iff f \ud835\udcb0\n\ninstance {X Y S : Scheme} (f : X \u27f6 S) (g : Y \u27f6 S) [finite g] :\n  finite (pullback.fst : pullback f g \u27f6 X) :=\nfinite_stable_under_base_change (is_pullback.of_has_pullback f g).flip infer_instance\n\ninstance {X Y S : Scheme} (f : X \u27f6 S) (g : Y \u27f6 S) [finite f] :\n  finite (pullback.snd : pullback f g \u27f6 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\u2200 (value_1: Value) (type_1: Type) (op_1: Operation),\n  -- (non-unification-based constraints)\n  is_float_type type_1 \u2192\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 \u2192 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 \u00b7 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 (\u03b4: Dialect \u03b1 \u03c3 \u03b5) where mk ::\n  -- Unification problem\n  u: Unification \u03b4\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 \u00d7 MTerm \u03b4)\n  -- List of operations that we want to collect after unification\n  operations: List (MTerm \u03b4)\n  -- Names of results for each operation, and their types\n  opresults: List (String \u00d7 List (String \u00d7 MTerm \u03b4))\n  -- Whether translation completed successfully\n  success: Bool\n\ndef Translation.empty: Translation \u03b4 :=\n  { u           := Unification.empty,\n    allvars     := [],\n    judgements  := [],\n    operations  := [],\n    opresults   := [],\n    success     := false }\n\ninstance {\u03b4: Dialect \u03b1 \u03c3 \u03b5} : Inhabited (Translation \u03b4) := \u27e8Translation.empty\u27e9\n\ndef Translation.str: Translation \u03b4 \u2192 String := fun tr =>\n  \"Unification problem:\\n\" ++\n    (toString tr.u) ++\n  \"\\nAll variables:\\n \" ++\n    (String.join $ tr.allvars.map (s!\" %{\u00b7}\")) ++\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 (\u03b4: Dialect \u03b1 \u03c3 \u03b5) := StateT (Translation \u03b4) IO\n\ndef TranslationM.toIO {\u03b1} (tr: Translation \u03b4) (x: TranslationM \u03b4 \u03b1): IO \u03b1 :=\n  Prod.fst <$> StateT.run x tr\n\ndef TranslationM.error {\u03b1} (s: String): TranslationM \u03b4 \u03b1 :=\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 \u03b4 Unit := do\n  let tr \u2190 get\n  if name \u2208 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 \u03b4 Unit := do\n  let tr \u2190 get\n  if ! name \u2208 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 \u03b4 String := do\n  let tr \u2190 get\n  match n with\n  | 0 =>\n      return s\n  | m+1 =>\n      let s' := s!\"{s}{p}\"\n      if tr.allvars.all (\u00b7 != 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 \u03b4 String := do\n  let tr \u2190 get\n  if tr.allvars.all (\u00b7 != name) then\n    addName name\n    return name\n  else\n    let f \u2190 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 \u03b4 (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 \u03b4) (priority: Nat):\n    TranslationM \u03b4 (MTerm \u03b4) := do\n  let renameVars (done: List String) (vars: List (String \u00d7 MSort)):\n      TranslationM \u03b4 (List (String \u00d7 MTerm \u03b4) \u00d7 List String) :=\n    vars.foldlM\n      (fun (repl, done) (var, sort) => do\n        if var \u2208 done then\n          return (repl, done)\n        else\n          let var' \u2190 makeFreshName (prefix_ ++ var)\n          return (repl ++ [(var, MTerm.Var priority var' sort)], done ++ [var]))\n      ([], done)\n\n  let (repl, done) \u2190 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 \u03b4): TranslationM \u03b4 Unit := do\n  let tr \u2190 get\n  set { tr with u := { equations := tr.u.equations ++ [equation] } }\n\ndef TranslationM.addOperation (op: MTerm \u03b4): TranslationM \u03b4 Unit := do\n  let tr \u2190 get\n  set { tr with operations := tr.operations ++ [op] }\n\ndef TranslationM.addJudgement (s: String) (type: MTerm \u03b4): TranslationM \u03b4 Unit := do\n  let tr \u2190 get\n  set { tr with judgements := tr.judgements ++ [(s, type)] }\n\ndef TranslationM.addOpResults (name: String) (results: List (String \u00d7 MTerm \u03b4)):\n    TranslationM \u03b4 Unit := do\n  let tr \u2190 get\n  set { tr with opresults := tr.opresults ++ [(name, results)] }\n\n\ndef TranslationM.findJudgement? (s: String): TranslationM \u03b4 (Option (MTerm \u03b4)) := do\n  let cmpName := fun (name, type) => if name = s then some type else none\n  return (\u2190 get).judgements.findSome? cmpName\n\ndef TranslationM.findJudgement (s: String): TranslationM \u03b4 (MTerm \u03b4) := do\n  match \u2190 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 \u03b4 (List (String \u00d7 MTerm \u03b4)) :=\n  l.mapM (fun var => do return (var, \u2190 findJudgement var))\n\ndef TranslationM.findOpResult? (op: String) (idx: Nat):\n    TranslationM \u03b4 (Option (String \u00d7 MTerm \u03b4)) := do\n  let cmpName := fun (name, rets) => if name = op then rets.get? idx else none\n  return (\u2190 get).opresults.findSome? cmpName\n\ndef TranslationM.findOpResult (op: String) (idx: Nat):\n    TranslationM \u03b4 (String \u00d7 MTerm \u03b4) := do\n  match \u2190 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 \u2190 get\n\n  match op with\n  -- %name = pdl.type\n  | Op.mk \"pdl.type\" [\u27e8SSAVal.SSAVal name, .undefined \"pdl.type\"\u27e9]\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\" [\u27e8SSAVal.SSAVal name, .undefined \"pdl.type\"\u27e9]\n         [] [] (AttrDict.mk [AttrEntry.mk \"type\" (AttrValue.type \u03c4)]) => do\n      IO.println s!\"Found new type variable: {name} (= {\u03c4})\"\n      addName name\n      addEquation (.Var 1 name .MMLIRType, .ConstMLIRType \u03c4)\n\n  -- %name = pdl.operand\n  | Op.mk \"pdl.operand\" [\u27e8SSAVal.SSAVal name, .undefined \"pdl.value\"\u27e9]\n         [] [] (AttrDict.mk []) => do\n      IO.println s!\"Found new variable: {name}\"\n      addName name\n      let typeName \u2190 makeFreshName (name ++ \"_T\")\n      IO.println s!\"\u2192 Generated type name: {typeName}\"\n      addJudgement name (.Var 1 typeName .MMLIRType)\n\n  -- %name = pdl.operand: %typeName\n  | Op.mk \"pdl.operand\" [\u27e8SSAVal.SSAVal name, .undefined \"pdl.value\"\u27e9]\n        [\u27e8SSAVal.SSAVal typeName, .undefined \"pdl.type\"\u27e9] [] (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\" [\u27e8SSAVal.SSAVal name, _\u27e9] 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 (\u00b7.str)\n          let types  := (operandSegment argsVal oss 2).map (\u00b7.str)\n          IO.println s!\"Found new operation: {name} matching {opname}\"\n          addName name\n\n          IO.println s!\"\u2192 Arguments: {values}, return types: {types}\"\n          values.forM checkNameDefined\n          types.forM checkNameDefined\n\n          let valuesTypes \u2190 findJudgements values\n          let retNames \u2190 makeFreshNames (name ++ \"_res\") types.length\n          IO.println s!\"\u2192 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!\"\u2192 Using match term: {insPattern}\"\n          let ins \u2190 makeFreshOp (name ++ \"_\") insPattern 2\n          addOperation ins\n          IO.println s!\"\u2192 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 \u00b7 .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\" [\u27e8SSAVal.SSAVal name, .undefined \"pdl.value\"\u27e9]\n        [\u27e8SSAVal.SSAVal opname, .undefined \"pdl.operation\"\u27e9] []  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) \u2190 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 { \u2190 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 \u03b4 Unit := do\n  let tr \u2190 get\n  if ! tr.success then\n    error \"unify: translation did not complete successfully\"\n  if let some u_unified \u2190 tr.u.solve then\n    set { tr with u := u_unified }\n  else\n    error \"unify: unification failed\"\n\ndef PDLToMatch.getOperationMatchTerms: TranslationM \u03b4 (List (MTerm \u03b4)) := do\n  let tr \u2190 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\u00d7i32>} : (!\"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\u00d7i32>} : (!\"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\u00d7i32>} : (!\"pdl.operation\", !\"pdl.value\") -> ()\n    }) {operand_segment_sizes = dense<[1, 0]> : vector<2\u00d7i32>} : (!\"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\" ++ (\u2190 get).str\n    PDLToMatch.unify\n    let matchTerms \u2190 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": "import meta.tactic\nimport util.control.applicative\nimport util.meta.tactic\n\nnamespace tactic\n\nopen list applicative (mmapp)\n\nmeta def add_selector (obj : expr) (fs : list name) (n : name) (ft : expr) : tactic unit :=\ndo let t := (obj.imp ft),\n   (_,val) \u2190 solve_aux t (do\n       x \u2190 intro1, vs \u2190 induction x fs, get_local n >>= apply),\n   val \u2190 instantiate_mvars val,\n   add_decl $ mk_theorem (obj.const_name ++ n) [ ] t val\n\nmeta def const_pis : list (expr \u00d7 expr) \u2192 expr \u2192 tactic expr\n | [ ] e := return e\n | ((c, t) :: vs) e :=\n   do expr.const v _ \u2190 pure c,\n      l \u2190 mk_local_def v t,\n      const_pis vs ((e.subst c l).abstract_local v)\n\nmeta def mk_implicit (bi : binder_info) : expr \u2192 expr\n | (expr.local_const n u _ t) := expr.local_const n u bi t\n | e := e\n\nmeta def mk_rec_of (c : name) : tactic (expr \u00d7 list name) :=\ndo env  \u2190 get_env,\n   let r := c <.> \"rec\",\n   decl \u2190 env.get r,\n   let ps := decl.univ_params,\n   return (expr.const r $ map level.param ps, ps)\n\nmeta def mk_cases_on (n : name) (ps : list expr) (cs : list (list expr)) : tactic unit :=\ndo r \u2190 tactic.mk_app n ps,\n   let u := level.param `l,\n   C \u2190 mk_local' `C binder_info.implicit (expr.sort u),\n   rec \u2190 resolve_name (n <.> \"rec\"),\n   let ps' := map (mk_implicit binder_info.implicit) ps,\n   let inds := map (\u03bb fs, expr.pis fs C) cs,\n   vs \u2190 mmap (mk_local_def `_) inds,\n   let t := expr.pis (ps' ++ [C]) (r.imp (expr.pis vs C)),\n   i \u2190 mk_local_def `i r,\n   d' \u2190 to_expr ``(%%(foldl expr.app rec $ map to_pexpr vs) %%i : %%C),\n   let d := expr.lambdas (map (mk_implicit binder_info.implicit) ps ++ [C,i] ++ vs) d',\n   add_decl (mk_definition (n <.> \"cases_on\") [`l] t d)\n\nmeta def mk_drec (n : name) (ps : list expr) (fs : list expr) : tactic unit :=\ndo r \u2190 tactic.mk_app n ps,\n   (rec,ls) \u2190 mk_rec_of (n),\n   let u := level.param ls.head,\n   C \u2190 mk_local' `C binder_info.implicit (r.imp (expr.sort u)),\n   mk \u2190 mk_const (n <.> \"mk\"),\n   let C' : expr := C $ mk.mk_app (ps ++ fs),\n   let ind := expr.pis fs C',\n   let ind_val := expr.pis fs C',\n   let ps' := map (mk_implicit binder_info.implicit) ps,\n   let fs' := map (mk_implicit binder_info.implicit) fs,\n   i \u2190 mk_local_def `i r,\n   h \u2190 mk_local_def `h ind,\n   let t' := expr.pis (ps' ++ [C]) (expr.pis [i] (ind.imp $ C i)),\n   let t := expr.pis (ps' ++ [C]) (ind.imp (expr.pis [i] $ C i)),\n   h' \u2190 to_expr ``(%%(h.mk_app fs) : %%C'),\n   let d' := (rec.mk_app ps (C i)) (expr.lambdas fs h') i,\n   d \u2190 instantiate_mvars $ expr.lambdas (ps' ++ [C,h,i]) d',\n   infer_type d >>= unify t,\n   add_decl (mk_definition (n <.> \"drec\") [`l] t d),\n   (_,d') \u2190 solve_aux t' (intros >> apply d ; auto),\n   d' \u2190 instantiate_mvars d',\n   add_decl (mk_definition (n <.> \"drec_on\") [`l] t' d')\n\nmeta def add_enum_type (n : name) (vals : list name) : tactic unit :=\ndo updateex_env $ \u03bb e\u2080, return $ e\u2080.add_namespace n,\n   let t : expr := expr.const n [ ],\n   let constrs := map (\u03bb c : name, (c.update_prefix n, t)) vals,\n   add_inductive n [ ] 0 `(Type) constrs ff,\n   mk_cases_on n [ ] ([ ] <$ vals)\n\nmeta def add_record\n  (n : name) (ps : list expr) (rt : expr)\n  (fs : list expr)\n  (gen_drec : bool := ff)\n: tactic unit :=\ndo updateex_env $ \u03bb e\u2080, return $ e\u2080.add_namespace n,\n   let t : expr := expr.mk_app (expr.const n [ ]) ps,\n   let ts := expr.pis fs t,\n   let ts := expr.pis ps ts,\n   let type_type := expr.pis ps rt,\n   add_inductive n [ ] ps.length type_type [(n <.> \"mk\", ts)] ff,\n   mk_cases_on n ps [fs],\n   when gen_drec $ mk_drec n ps fs\n\nmeta inductive record_param\n | var : expr \u2192 record_param\n | record (var : expr) (record : name) (cases_on : name) (params fields : list expr) : record_param\n\nmeta def record_param.params : record_param \u2192 list expr\n | (record_param.var _) := [ ]\n | (record_param.record _ _ _ ps _) := ps\n\nmeta def record_param.vars : record_param \u2192 list expr\n | (record_param.var x) := [x]\n | (record_param.record _ _ _ _ fs) := fs\n\nmeta def record_param.local : record_param \u2192 expr\n | (record_param.var x) := x\n | (record_param.record x _ _ _ _) := x\n\nmeta def cases_on_records' : list record_param \u2192 expr \u2192 list expr \u2192 tactic unit\n | (record_param.var x :: xs) e vs := intro1 >>= \u03bb v, cases_on_records' xs e (v :: vs)\n | (record_param.record v n c ps fs :: xs) e\u2080 vs :=\n do v' \u2190 intro1,\n    cs \u2190 induction v',\n    mmap' (\u03bb c : list _ \u00d7 _, cases_on_records' xs e\u2080 $ c.1.reverse ++ vs) cs\n | [ ] e vs :=\n   do exact $ e.mk_app vs.reverse\n\nmeta def record_param.primed : record_param \u2192 tactic record_param\n | (record_param.var v) := record_param.var <$> primed_local v\n | (record_param.record v n cases ps vs) :=\ndo v' \u2190 primed_local v,\n   record_param.record v' n cases ps <$> mmap primed_local vs\n\nmeta def mk_pred (n : name) (ps : list record_param) (pred : list (name \u00d7 pexpr)) : tactic pexpr :=\ndo let vars := ps.bind record_param.vars,\n   pred' \u2190 mmapp (\u03bb n t, to_expr t >>= mk_local_def n) pred,\n   add_record n.primed vars `(Prop) pred' tt,\n   pred \u2190 resolve_name n.primed >>= to_expr,\n   let vs := map record_param.local ps,\n   let t := expr.pis vs `(Prop),\n   (_,d) \u2190 solve_aux t $ cases_on_records' ps pred [ ],\n   infer_type d >>= unify t,\n   d \u2190 instantiate_mvars d,\n   add_decl (mk_definition n [ ] t d),\n   resolve_name n\n\nend tactic\n", "meta": {"author": "unitb", "repo": "unitb-pointers", "sha": "c057420c1e72bba00181bc6db30cf369ef2bfd23", "save_path": "github-repos/lean/unitb-unitb-pointers", "path": "github-repos/lean/unitb-unitb-pointers/unitb-pointers-c057420c1e72bba00181bc6db30cf369ef2bfd23/src/meta/declaration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.05419872371237139, "lm_q1q2_score": 0.02106260105907727}}
{"text": "def HList (\u03b1s : List (Type u)) : Type u := \u03b1s.foldr Prod.{u, u} PUnit\n\n@[match_pattern] def HList.nil : HList [] := \u27e8\u27e9\n@[match_pattern] def HList.cons (a : \u03b1) (as : HList \u03b1s): HList (\u03b1 :: \u03b1s) := (a, as)\n\ndef HList.set : {\u03b1s : _} \u2192 HList \u03b1s \u2192 (i : Fin \u03b1s.length) \u2192 \u03b1s.get i \u2192 HList \u03b1s\n  | _ :: _, cons a as, \u27e80,          h\u27e9, b => cons b as\n  | _ :: _, cons a as, \u27e8Nat.succ n, h\u27e9, b => cons a (set as \u27e8n, Nat.le_of_succ_le_succ h\u27e9 b)\n  | [],     nil,       _,               _ => nil\n\ninstance : EmptyCollection (HList \u2205) where\n  emptyCollection := HList.nil\n\nnotation:30 \u0393 \" \u22a2 \" \u03b1 => HList \u0393 \u2192 \u03b1\n\n-- simplify well-founded recursion proofs by ignoring context sizes\nlocal instance : SizeOf (List \u03b1) := \u27e8fun _ => 0\u27e9 in\n\n-- m: base monad\n-- \u03c9: `return` type, `m \u03c9` is the type of the entire `do` block\n-- \u0393: `do`-local immutable context\n-- \u0394: `do`-local mutable context\n-- b: `break` allowed\n-- c: `continue` allowed\n-- \u03b1: local result type, `m \u03b1` is the type of the statement\ninductive Stmt (m : Type u \u2192 Type _) (\u03c9 : Type u) : (\u0393 \u0394 : List (Type u)) \u2192 (b c : Bool) \u2192 (\u03b1 : Type u) \u2192 Type _ where\n  | expr (e : \u0393 \u22a2 \u0394 \u22a2 m \u03b1) : Stmt m \u03c9 \u0393 \u0394 b c \u03b1\n  | bind (s\u2081 : Stmt m \u03c9 \u0393 \u0394 b c \u03b1) (s\u2082 : Stmt m \u03c9 (\u03b1 :: \u0393) \u0394 b c \u03b2) : Stmt m \u03c9 \u0393 \u0394 b c \u03b2\n  | letmut (e : \u0393 \u22a2 \u0394 \u22a2 \u03b1) (s : Stmt m \u03c9 \u0393 (\u03b1 :: \u0394) b c \u03b2) : Stmt m \u03c9 \u0393 \u0394 b c \u03b2\n  | ass (x : Fin \u0394.length) (e : \u0393 \u22a2 \u0394 \u22a2 \u0394.get x) : Stmt m \u03c9 \u0393 \u0394 b c PUnit\n  | ite (e : \u0393 \u22a2 \u0394 \u22a2 Bool) (s\u2081 s\u2082 : Stmt m \u03c9 \u0393 \u0394 b c \u03b1) : Stmt m \u03c9 \u0393 \u0394 b c \u03b1\n  | ret (e : \u0393 \u22a2 \u0394 \u22a2 \u03c9) : Stmt m \u03c9 \u0393 \u0394 b c \u03b1\n  --| sfor [ForM m \u03b3 \u03b1] (e : \u03a3 \u0393 \u2192 \u03b3) (body : \u03b1 \u2192 Stmt m \u03c9 \u0393 \u0394 true PUnit) : Stmt m \u03c9 \u0393 \u0394 b c PUnit\n  | sfor (e : \u0393 \u22a2 \u0394 \u22a2 List \u03b1) (body : Stmt m \u03c9 (\u03b1 :: \u0393) \u0394 true true PUnit) : Stmt m \u03c9 \u0393 \u0394 b c PUnit\n  | sbreak : Stmt m \u03c9 \u0393 \u0394 true c \u03b1\n  | scont : Stmt m \u03c9 \u0393 \u0394 b true \u03b1\n\n-- normal and abnormal result values\ninductive Res (\u03c9 \u03b1 : Type _) : (b c : Bool) \u2192 Type _ where\n  | val (a : \u03b1) : Res \u03c9 \u03b1 b c\n  | ret (o : \u03c9) : Res \u03c9 \u03b1 b c\n  | rbreak : Res \u03c9 \u03b1 true c\n  | rcont : Res \u03c9 \u03b1 b true\n\ninstance : Coe \u03b1 (Res \u03c9 \u03b1 b c) := \u27e8Res.val\u27e9\ninstance : Coe (Id \u03b1) (Res \u03c9 \u03b1 b c) := \u27e8Res.val\u27e9\n\ndef Ctx.extendBot (x : \u03b1) : {\u0393 : _} \u2192 HList \u0393 \u2192 HList (\u0393 ++ [\u03b1])\n  | [],     _               => HList.cons x HList.nil\n  | _ :: _, HList.cons a as => HList.cons a (extendBot x as)\n\ndef Ctx.extend (x : \u03b1) : HList \u0393 \u2192 HList (\u03b1 :: \u0393) :=\n  fun \u03c3 => HList.cons x \u03c3\n\ndef Ctx.drop : HList (\u03b1 :: \u0393) \u2192 HList \u0393\n  | HList.cons a as => as\n\n-- custom wf tactic\ntheorem Nat.le_add_right_of_le (n m : Nat) : n \u2264 m \u2192 n \u2264 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 \u0393' \u2192 HList \u0393) : Stmt m \u03c9 \u0393 \u0394 b c \u03b2 \u2192 Stmt m \u03c9 \u0393' \u0394 b c \u03b2\n  | expr e => expr (e \u2218 f)\n  | bind s\u2081 s\u2082 => bind (s\u2081.mapCtx f) (s\u2082.mapCtx (fun | HList.cons a as => HList.cons a (f as)))\n  | letmut e s => letmut (e \u2218 f) (s.mapCtx f)\n  | ass x e => ass x (e \u2218 f)\n  | ite e s\u2081 s\u2082 => ite (e \u2218 f) (s\u2081.mapCtx f) (s\u2082.mapCtx f)\n  | ret e => ret (e \u2218 f)\n  | sfor e body => sfor (e \u2218 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 \u2192 regular_mono` and\n* `regular_mono \u2192 mono`\nas well as the dual constructions for regular epimorphisms. Additionally, we give the construction\n* `regular_epi \u27f6 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\u2081 u\u2081 u\u2082\n\nvariables {C : Type u\u2081} [category.{v\u2081} 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 \u27f6 Y) :=\n(Z : C)\n(left right : Y \u27f6 Z)\n(w : f \u226b left = f \u226b right)\n(is_limit : is_limit (fork.of_\u03b9 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 \u27f6 Y) [regular_mono f] : mono f :=\nmono_of_is_limit_parallel_pair regular_mono.is_limit\n\ninstance equalizer_regular (g h : X \u27f6 Y) [has_limit (parallel_pair g h)] :\n  regular_mono (equalizer.\u03b9 g h) :=\n{ Z := Y,\n  left := g,\n  right := h,\n  w := equalizer.condition g h,\n  is_limit := fork.is_limit.mk _ (\u03bb s, limit.lift _ s) (by simp) (\u03bb s m w, by { ext1, simp [\u2190w] }) }\n\n/-- Every split monomorphism is a regular monomorphism. -/\n@[priority 100]\ninstance regular_mono.of_split_mono (f : X \u27f6 Y) [split_mono f] : regular_mono f :=\n{ Z     := Y,\n  left  := \ud835\udfd9 Y,\n  right := retraction f \u226b 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 \u27f6 Y` equalizing `regular_mono.left` and\n    `regular_mono.right` induces a morphism `l : W \u27f6 X` such that `l \u226b f = k`. -/\ndef regular_mono.lift' {W : C} (f : X \u27f6 Y) [regular_mono f] (k : W \u27f6 Y)\n  (h : k \u226b (regular_mono.left : Y \u27f6 @regular_mono.Z _ _ _ _ f _) = k \u226b regular_mono.right) :\n  {l : W \u27f6 X // l \u226b 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S}\n  {k : R \u27f6 S} [hr : regular_mono h] (comm : f \u226b h = g \u226b k)\n  (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono g :=\n{ Z := hr.Z,\n  left := k \u226b hr.left,\n  right := k \u226b hr.right,\n  w := by rw [\u2190 reassoc_of comm, \u2190 reassoc_of comm, hr.w],\n  is_limit :=\n  begin\n    apply fork.is_limit.mk' _ _,\n    intro s,\n    have l\u2081 : (fork.\u03b9 s \u226b k) \u226b regular_mono.left = (fork.\u03b9 s \u226b k) \u226b regular_mono.right,\n      rw [category.assoc, s.condition, category.assoc],\n    obtain \u27e8l, hl\u27e9 := fork.is_limit.lift' hr.is_limit _ l\u2081,\n    obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := pullback_cone.is_limit.lift' t _ _ hl,\n    refine \u27e8p, hp\u2082, _\u27e9,\n    intros m w,\n    have z : m \u226b g = p \u226b g := w.trans hp\u2082.symm,\n    apply t.hom_ext,\n    apply (pullback_cone.mk f g comm).equalizer_ext,\n    { erw [\u2190 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S}\n  {k : R \u27f6 S} [hr : regular_mono k] (comm : f \u226b h = g \u226b 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 \u27f6 Y) [regular_mono f] : strong_mono f :=\n{ mono := by apply_instance,\n  has_lift :=\n  begin\n    introsI,\n    have : v \u226b (regular_mono.left : Y \u27f6 regular_mono.Z f) = v \u226b regular_mono.right,\n    { apply (cancel_epi z).1,\n      simp only [regular_mono.w, \u2190 reassoc_of h] },\n    obtain \u27e8t, ht\u27e9 := regular_mono.lift' _ _ this,\n    refine arrow.has_lift.mk \u27e8t, (cancel_mono f).1 _, ht\u27e9,\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 \u27f6 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 : \u2200 {X Y : C} (f : X \u27f6 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 \u27f6 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 := \u03bb _ _ 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 := \u03bb _ _ 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 \u27f6 Y) :=\n(W : C)\n(left right : W \u27f6 X)\n(w : left \u226b f = right \u226b f)\n(is_colimit : is_colimit (cofork.of_\u03c0 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 \u27f6 Y) [regular_epi f] : epi f :=\nepi_of_is_colimit_parallel_pair regular_epi.is_colimit\n\ninstance coequalizer_regular (g h : X \u27f6 Y) [has_colimit (parallel_pair g h)] :\n  regular_epi (coequalizer.\u03c0 g h) :=\n{ W := X,\n  left := g,\n  right := h,\n  w := coequalizer.condition g h,\n  is_colimit := cofork.is_colimit.mk _ (\u03bb s, colimit.desc _ s) (by simp)\n    (\u03bb s m w, by { ext1, simp [\u2190w] }) }\n\n/-- Every split epimorphism is a regular epimorphism. -/\n@[priority 100]\ninstance regular_epi.of_split_epi (f : X \u27f6 Y) [split_epi f] : regular_epi f :=\n{ W     := X,\n  left  := \ud835\udfd9 X,\n  right := f \u226b 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 \u27f6 W` coequalizing `regular_epi.left` and\n    `regular_epi.right` induces `l : Y \u27f6 W` such that `f \u226b l = k`. -/\ndef regular_epi.desc' {W : C} (f : X \u27f6 Y) [regular_epi f] (k : X \u27f6 W)\n  (h : (regular_epi.left : regular_epi.W f \u27f6 X) \u226b k = regular_epi.right \u226b k) :\n  {l : Y \u27f6 W // f \u226b 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S} {k : R \u27f6 S}\n  [gr : regular_epi g] (comm : f \u226b h = g \u226b k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi h :=\n{ W := gr.W,\n  left := gr.left \u226b f,\n  right := gr.right \u226b 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\u2081 : gr.left \u226b f \u226b s.\u03c0 = gr.right \u226b f \u226b s.\u03c0,\n      rw [\u2190 category.assoc, \u2190 category.assoc, s.condition],\n    obtain \u27e8l, hl\u27e9 := cofork.is_colimit.desc' gr.is_colimit (f \u226b cofork.\u03c0 s) l\u2081,\n    obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := pushout_cocone.is_colimit.desc' t _ _ hl.symm,\n    refine \u27e8p, hp\u2081, _\u27e9,\n    intros m w,\n    have z := w.trans hp\u2081.symm,\n    apply t.hom_ext,\n    apply (pushout_cocone.mk _ _ comm).coequalizer_ext,\n    { exact z },\n    { erw [\u2190 cancel_epi g, \u2190 reassoc_of comm, \u2190 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S} {k : R \u27f6 S}\n  [fr : regular_epi f] (comm : f \u226b h = g \u226b 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 \u27f6 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 \u27f6 X) \u226b u = regular_epi.right \u226b u,\n    { apply (cancel_mono z).1,\n      simp only [category.assoc, h, regular_epi.w_assoc] },\n    obtain \u27e8t, ht\u27e9 := regular_epi.desc' f u this,\n    exact arrow.has_lift.mk \u27e8t, ht, (cancel_epi f).1\n      (by simp only [\u2190category.assoc, ht, \u2190h, arrow.mk_hom, arrow.hom_mk'_right])\u27e9,\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 \u27f6 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 : \u2200 {X Y : C} (f : X \u27f6 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 \u27f6 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 := \u03bb _ _ 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 := \u03bb _ _ 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": "/-\nCopyright (c) 2022 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.Notation\nset_option linter.missingDocs true -- keep it documented\n\nnamespace Lean.Parser.Tactic\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 tactic : tactic\n\n/--\nIntroduces one or more hypotheses, optionally naming and/or pattern-matching them.\nFor each hypothesis to be introduced, the remaining main goal's target type must\nbe a `let` or function type.\n\n* `intro` by itself introduces one anonymous hypothesis, which can be accessed\n  by e.g. `assumption`.\n* `intro x y` introduces two hypotheses and names them. Individual hypotheses\n  can be anonymized via `_`, or matched against a pattern:\n  ```lean\n  -- ... \u22a2 \u03b1 \u00d7 \u03b2 \u2192 ...\n  intro (a, b)\n  -- ..., a : \u03b1, b : \u03b2 \u22a2 ...\n  ```\n* Alternatively, `intro` can be combined with pattern matching much like `fun`:\n  ```lean\n  intro\n  | n + 1, 0 => tac\n  | ...\n  ```\n-/\nsyntax (name := intro) \"intro \" notFollowedBy(\"|\") (colGt term:max)* : tactic\n\n/--\n`intros x...` behaves like `intro x...`, but then keeps introducing (anonymous)\nhypotheses until goal is not of a function type.\n-/\nsyntax (name := intros) \"intros \" (colGt (ident <|> hole))* : tactic\n\n/--\n`rename t => x` renames the most recent hypothesis whose type matches `t`\n(which may contain placeholders) to `x`, or fails if no such hypothesis could be found.\n-/\nsyntax (name := rename) \"rename \" term \" => \" ident : tactic\n\n/--\n`revert x...` is the inverse of `intro x...`: it moves the given hypotheses\ninto the main goal's target type.\n-/\nsyntax (name := revert) \"revert \" (colGt term:max)+ : tactic\n\n/--\n`clear x...` removes the given hypotheses, or fails if there are remaining\nreferences to a hypothesis.\n-/\nsyntax (name := clear) \"clear \" (colGt term:max)+ : tactic\n\n/--\n`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis\nof type `x = e` or `e = x`.\nIf `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead.\n-/\nsyntax (name := subst) \"subst \" (colGt term:max)+ : tactic\n\n/--\nApplies `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.\n-/\nsyntax (name := substVars) \"subst_vars\" : tactic\n\n/--\n`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.\nNote also the `\u2039t\u203a` term notation, which is a shorthand for `show t by assumption`.\n-/\nsyntax (name := assumption) \"assumption\" : tactic\n\n/--\n`contradiction` closes the main goal if its hypotheses are \"trivially contradictory\".\n- Inductive type/family with no applicable constructors\n```lean\nexample (h : False) : p := by contradiction\n```\n- Injectivity of constructors\n```lean\nexample (h : none = some true) : p := by contradiction  --\n```\n- Decidable false proposition\n```lean\nexample (h : 2 + 2 = 3) : p := by contradiction\n```\n- Contradictory hypotheses\n```lean\nexample (h : p) (h' : \u00ac p) : q := by contradiction\n```\n- Other simple contradictions such as\n```lean\nexample (x : Nat) (h : x \u2260 x) : p := by contradiction\n```\n-/\nsyntax (name := contradiction) \"contradiction\" : tactic\n\n/--\n`apply e` tries to match the current goal against the conclusion of `e`'s type.\nIf it succeeds, then the tactic returns as many subgoals as the number of premises that\nhave not been fixed by type inference or type class resolution.\nNon-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution,\nand first-order unification with dependent types.\n-/\nsyntax (name := apply) \"apply \" term : tactic\n\n/--\n`exact e` closes the main goal if its target type matches that of `e`.\n-/\nsyntax (name := exact) \"exact \" term : tactic\n\n/--\n`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`)\nholes in `e` that are not solved by unification with the main goal's target type\nare converted into new goals, using the hole's name, if any, as the goal case name.\n-/\nsyntax (name := refine) \"refine \" term : tactic\n\n/--\n`refine' e` behaves like `refine e`, except that unsolved placeholders (`_`)\nand implicit parameters are also converted into new goals.\n-/\nsyntax (name := refine') \"refine' \" term : tactic\n\n/--\nIf the main goal's target type is an inductive type, `constructor` solves it with\nthe first matching constructor, or else fails.\n-/\nsyntax (name := constructor) \"constructor\" : tactic\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\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses\n  with inaccessible names to the given names.\n* `case tag\u2081 | tag\u2082 => tac` is equivalent to `(case tag\u2081 => tac); (case tag\u2082 => tac)`.\n-/\nsyntax (name := case) \"case \" sepBy1(caseArg, \" | \") \" => \" tacticSeq : tactic\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-/\nsyntax (name := case') \"case' \" sepBy1(caseArg, \" | \") \" => \" tacticSeq : tactic\n\n/--\n`next => tac` focuses on the next goal and solves it using `tac`, or else fails.\n`next x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with\ninaccessible names to the given names.\n-/\nmacro \"next \" args:binderIdent* \" => \" tac:tacticSeq : tactic => `(tactic| case _ $args* => $tac)\n\n/-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/\nsyntax (name := allGoals) \"all_goals \" tacticSeq : tactic\n\n/--\n`any_goals tac` applies the tactic `tac` to every goal, and succeeds if at\nleast one application succeeds.\n-/\nsyntax (name := anyGoals) \"any_goals \" tacticSeq : tactic\n\n/--\n`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.\nUsually `\u00b7 tac`, which enforces that the goal is closed by `tac`, should be preferred.\n-/\nsyntax (name := focus) \"focus \" tacticSeq : tactic\n\n/-- `skip` does nothing. -/\nsyntax (name := skip) \"skip\" : tactic\n\n/-- `done` succeeds iff there are no remaining goals. -/\nsyntax (name := done) \"done\" : tactic\n\n/-- `trace_state` displays the current state in the info view. -/\nsyntax (name := traceState) \"trace_state\" : tactic\n\n/-- `trace msg` displays `msg` in the info view. -/\nsyntax (name := traceMessage) \"trace \" str : tactic\n\n/-- `fail_if_success t` fails if the tactic `t` succeeds. -/\nsyntax (name := failIfSuccess) \"fail_if_success \" tacticSeq : tactic\n\n/--\n`(tacs)` executes a list of tactics in sequence, without requiring that\nthe goal be closed at the end like `\u00b7 tacs`. Like `by` itself, the tactics\ncan be either separated by newlines or `;`.\n-/\nsyntax (name := paren) \"(\" withoutPosition(tacticSeq) \")\" : tactic\n\n/--\n`with_reducible tacs` excutes `tacs` using the reducible transparency setting.\nIn this setting only definitions tagged as `[reducible]` are unfolded.\n-/\nsyntax (name := withReducible) \"with_reducible \" tacticSeq : tactic\n\n/--\n`with_reducible_and_instances tacs` excutes `tacs` using the `.instances` transparency setting.\nIn this setting only definitions tagged as `[reducible]` or type class instances are unfolded.\n-/\nsyntax (name := withReducibleAndInstances) \"with_reducible_and_instances \" tacticSeq : tactic\n\n/--\n`with_unfolding_all tacs` excutes `tacs` using the `.all` transparency setting.\nIn this setting all definitions that are not opaque are unfolded.\n-/\nsyntax (name := withUnfoldingAll) \"with_unfolding_all \" tacticSeq : tactic\n\n/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/\nsyntax (name := first) \"first \" withPosition((colGe \"|\" tacticSeq)+) : tactic\n\n/--\n`rotate_left n` rotates goals to the left by `n`. That is, `rotate_left 1`\ntakes the main goal and puts it to the back of the subgoal list.\nIf `n` is omitted, it defaults to `1`.\n-/\nsyntax (name := rotateLeft) \"rotate_left\" (num)? : tactic\n\n/--\nRotate the goals to the right by `n`. That is, take the goal at the back\nand push it to the front `n` times. If `n` is omitted, it defaults to `1`.\n-/\nsyntax (name := rotateRight) \"rotate_right\" (num)? : tactic\n\n/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/\nmacro \"try \" t:tacticSeq : tactic => `(tactic| first | $t | skip)\n\n/--\n`tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal,\nconcatenating all goals produced by `tac'`.\n-/\nmacro:1 x:tactic tk:\" <;> \" y:tactic:2 : tactic => `(tactic|\n  focus\n    $x:tactic\n    -- annotate token with state after executing `x`\n    with_annotate_state $tk skip\n    all_goals $y:tactic)\n\n/-- `eq_refl` is equivalent to `exact rfl`, but has a few optimizations. -/\nsyntax (name := refl) \"eq_refl\" : tactic\n\n/--\n`rfl` tries to close the current goal using reflexivity.\nThis is supposed to be an extensible tactic and users can add their own support\nfor new reflexive relations.\n-/\nmacro \"rfl\" : tactic => `(tactic| eq_refl)\n\n/--\n`rfl'` is similar to `rfl`, but disables smart unfolding and unfolds all kinds of definitions,\ntheorems included (relevant for declarations defined by well-founded recursion).\n-/\nmacro \"rfl'\" : tactic => `(tactic| set_option smartUnfolding false in with_unfolding_all rfl)\n\n/--\n`ac_rfl` proves equalities up to application of an associative and commutative operator.\n```\ninstance : IsAssociative (\u03b1 := Nat) (.+.) := \u27e8Nat.add_assoc\u27e9\ninstance : IsCommutative (\u03b1 := Nat) (.+.) := \u27e8Nat.add_comm\u27e9\n\nexample (a b c d : Nat) : a + b + c + d = d + (b + c) + a := by ac_rfl\n```\n-/\nsyntax (name := acRfl) \"ac_rfl\" : tactic\n\n/--\nThe `sorry` tactic closes the goal using `sorryAx`. This is intended for stubbing out incomplete\nparts of a proof while still having a syntactically correct proof skeleton. Lean will give\na warning whenever a proof uses `sorry`, so you aren't likely to miss it, but\nyou can double check if a theorem depends on `sorry` by using\n`#print axioms my_thm` and looking for `sorryAx` in the axiom list.\n-/\nmacro \"sorry\" : tactic => `(tactic| exact @sorryAx _ false)\n\n/-- `admit` is a shorthand for `exact sorry`. -/\nmacro \"admit\" : tactic => `(tactic| exact @sorryAx _ false)\n\n/--\n`infer_instance` is an abbreviation for `exact inferInstance`.\nIt synthesizes a value of any target type by typeclass inference.\n-/\nmacro \"infer_instance\" : tactic => `(tactic| exact inferInstance)\n\n/-- Optional configuration option for tactics -/\nsyntax config := atomic(\" (\" &\"config\") \" := \" withoutPosition(term) \")\"\n\n/-- The `*` location refers to all hypotheses and the goal. -/\nsyntax locationWildcard := \"*\"\n\n/--\nA hypothesis location specification consists of 1 or more hypothesis references\nand optionally `\u22a2` denoting the goal.\n-/\nsyntax locationHyp := (colGt term:max)+ patternIgnore(\"\u22a2\" <|> \"|-\")?\n\n/--\nLocation specifications are used by many tactics that can operate on either the\nhypotheses or the goal. It can have one of the forms:\n* 'empty' is not actually present in this syntax, but most tactics use\n  `(location)?` matchers. It means to target the goal only.\n* `at h\u2081 ... h\u2099`: target the hypotheses `h\u2081`, ..., `h\u2099`\n* `at h\u2081 h\u2082 \u22a2`: target the hypotheses `h\u2081` and `h\u2082`, and the goal\n* `at *`: target all hypotheses and the goal\n-/\nsyntax location := withPosition(\" at \" (locationWildcard <|> locationHyp))\n\n/--\n* `change tgt'` will change the goal from `tgt` to `tgt'`,\n  assuming these are definitionally equal.\n* `change t' at h` will change hypothesis `h : t` to have type `t'`, assuming\n  assuming `t` and `t'` are definitionally equal.\n-/\nsyntax (name := change) \"change \" term (location)? : tactic\n\n/--\n* `change a with b` will change occurrences of `a` to `b` in the goal,\n  assuming `a` and `b` are are definitionally equal.\n* `change a with b at h` similarly changes `a` to `b` in the type of hypothesis `h`.\n-/\nsyntax (name := changeWith) \"change \" term \" with \" term (location)? : tactic\n\n/--\nIf `thm` is a theorem `a = b`, then as a rewrite rule,\n* `thm` means to replace `a` with `b`, and\n* `\u2190 thm` means to replace `b` with `a`.\n-/\nsyntax rwRule    := patternIgnore(\"\u2190 \" <|> \"<- \")? term\n/-- A `rwRuleSeq` is a list of `rwRule` in brackets. -/\nsyntax rwRuleSeq := \" [\" withoutPosition(rwRule,*,?) \"]\"\n\n/--\n`rewrite [e]` applies identity `e` as a rewrite rule to the target of the main goal.\nIf `e` is preceded by left arrow (`\u2190` or `<-`), the rewrite is applied in the reverse direction.\nIf `e` is a defined constant, then the equational theorems associated with `e` are used.\nThis provides a convenient way to unfold `e`.\n- `rewrite [e\u2081, ..., e\u2099]` applies the given rules sequentially.\n- `rewrite [e] at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a\n  list of hypotheses in the local context. In the latter case, a turnstile `\u22a2` or `|-`\n  can also be used, to signify the target of the goal.\n-/\nsyntax (name := rewriteSeq) \"rewrite\" (config)? rwRuleSeq (location)? : tactic\n\n/--\n`rw` is like `rewrite`, but also tries to close the goal by \"cheap\" (reducible) `rfl` afterwards.\n-/\nmacro (name := rwSeq) \"rw\" c:(config)? s:rwRuleSeq l:(location)? : tactic =>\n  match s with\n  | `(rwRuleSeq| [$rs,*]%$rbrak) =>\n    -- We show the `rfl` state on `]`\n    `(tactic| (rewrite $(c)? [$rs,*] $(l)?; with_annotate_state $rbrak (try (with_reducible rfl))))\n  | _ => Macro.throwUnsupported\n\n/--\nThe `injection` tactic is based on the fact that constructors of inductive data\ntypes are injections.\nThat means that if `c` is a constructor of an inductive datatype, and if `(c t\u2081)`\nand `(c t\u2082)` are two terms that are equal then  `t\u2081` and `t\u2082` are equal too.\nIf `q` is a proof of a statement of conclusion `t\u2081 = t\u2082`, then injection applies\ninjectivity to derive the equality of all arguments of `t\u2081` and `t\u2082` placed in\nthe same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`.\nTo use this tactic `t\u2081` and `t\u2082` should be constructor applications of the same constructor.\nGiven `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types\n`a = c` and `b = d` to the main goal.\nThe tactic `injection h with h\u2081 h\u2082` uses the names `h\u2081` and `h\u2082` to name the new hypotheses.\n-/\nsyntax (name := injection) \"injection \" term (\" with \" (colGt (ident <|> hole))+)? : tactic\n\n/-- `injections` applies `injection` to all hypotheses recursively\n(since `injection` can produce new hypotheses). Useful for destructing nested\nconstructor equalities like `(a::b::c) = (d::e::f)`. -/\n-- TODO: add with\nsyntax (name := injections) \"injections\" (colGt (ident <|> hole))* : tactic\n\n/--\nThe discharger clause of `simp` and related tactics.\nThis is a tactic used to discharge the side conditions on conditional rewrite rules.\n-/\nsyntax discharger := atomic(\" (\" patternIgnore(&\"discharger\" <|> &\"disch\")) \" := \" withoutPosition(tacticSeq) \")\"\n\n/-- Use this rewrite rule before entering the subterms -/\nsyntax simpPre   := \"\u2193\"\n/-- Use this rewrite rule after entering the subterms -/\nsyntax simpPost  := \"\u2191\"\n/--\nA simp lemma specification is:\n* optional `\u2191` or `\u2193` to specify use before or after entering the subterm\n* optional `\u2190` to use the lemma backward\n* `thm` for the theorem to rewrite with\n-/\nsyntax simpLemma := (simpPre <|> simpPost)? patternIgnore(\"\u2190 \" <|> \"<- \")? term\n/-- An erasure specification `-thm` says to remove `thm` from the simp set -/\nsyntax simpErase := \"-\" term:max\n/-- The simp lemma specification `*` means to rewrite with all hypotheses -/\nsyntax simpStar  := \"*\"\n/--\nThe `simp` tactic uses lemmas and hypotheses to simplify the main goal target or\nnon-dependent hypotheses. It has many variants:\n- `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.\n- `simp [h\u2081, h\u2082, ..., h\u2099]` simplifies the main goal target using the lemmas tagged\n  with the attribute `[simp]` and the given `h\u1d62`'s, where the `h\u1d62`'s are expressions.\n  If an `h\u1d62` is a defined constant `f`, then the equational lemmas associated with\n  `f` are used. This provides a convenient way to unfold `f`.\n- `simp [*]` simplifies the main goal target using the lemmas tagged with the\n  attribute `[simp]` and all hypotheses.\n- `simp only [h\u2081, h\u2082, ..., h\u2099]` is like `simp [h\u2081, h\u2082, ..., h\u2099]` but does not use `[simp]` lemmas.\n- `simp [-id\u2081, ..., -id\u2099]` simplifies the main goal target using the lemmas tagged\n  with the attribute `[simp]`, but removes the ones named `id\u1d62`.\n- `simp at h\u2081 h\u2082 ... h\u2099` simplifies the hypotheses `h\u2081 : T\u2081` ... `h\u2099 : T\u2099`. If\n  the target or another hypothesis depends on `h\u1d62`, a new simplified hypothesis\n  `h\u1d62` is introduced, but the old one remains in the local context.\n- `simp at *` simplifies all the hypotheses and the target.\n- `simp [*] at *` simplifies target and all (propositional) hypotheses using the\n  other hypotheses.\n-/\nsyntax (name := simp) \"simp\" (config)? (discharger)? (&\" only\")?\n  (\" [\" withoutPosition((simpStar <|> simpErase <|> simpLemma),*) \"]\")? (location)? : tactic\n/--\n`simp_all` is a stronger version of `simp [*] at *` where the hypotheses and target\nare simplified multiple times until no simplication is applicable.\nOnly non-dependent propositional hypotheses are considered.\n-/\nsyntax (name := simpAll) \"simp_all\" (config)? (discharger)? (&\" only\")?\n  (\" [\" withoutPosition((simpErase <|> simpLemma),*) \"]\")? : tactic\n\n/--\nThe `dsimp` tactic is the definitional simplifier. It is similar to `simp` but only\napplies theorems that hold by reflexivity. Thus, the result is guaranteed to be\ndefinitionally equal to the input.\n-/\nsyntax (name := dsimp) \"dsimp\" (config)? (discharger)? (&\" only\")?\n  (\" [\" withoutPosition((simpErase <|> simpLemma),*) \"]\")? (location)? : tactic\n\n/--\n`delta id1 id2 ...` delta-expands the definitions `id1`, `id2`, ....\nThis is a low-level tactic, it will expose how recursive definitions have been\ncompiled by Lean.\n-/\nsyntax (name := delta) \"delta \" (colGt ident)+ (location)? : tactic\n\n/--\n* `unfold id` unfolds definition `id`.\n* `unfold id1 id2 ...` is equivalent to `unfold id1; unfold id2; ...`.\n\nFor non-recursive definitions, this tactic is identical to `delta`.\nFor definitions by pattern matching, it uses \"equation lemmas\" which are\nautogenerated for each match arm.\n-/\nsyntax (name := unfold) \"unfold \" (colGt ident)+ (location)? : tactic\n\n/--\nAuxiliary macro for lifting have/suffices/let/...\nIt makes sure the \"continuation\" `?_` is the main goal after refining.\n-/\nmacro \"refine_lift \" e:term : tactic => `(tactic| focus (refine no_implicit_lambda% $e; rotate_right))\n\n/--\n`have h : t := e` adds the hypothesis `h : t` to the current goal if `e` a term\nof type `t`.\n* If `t` is omitted, it will be inferred.\n* If `h` is omitted, the name `this` is used.\n* The variant `have pattern := e` is equivalent to `match e with | pattern => _`,\n  and it is convenient for types that have only one applicable constructor.\n  For example, given `h : p \u2227 q \u2227 r`, `have \u27e8h\u2081, h\u2082, h\u2083\u27e9 := h` produces the\n  hypotheses `h\u2081 : p`, `h\u2082 : q`, and `h\u2083 : r`.\n-/\nmacro \"have \" d:haveDecl : tactic => `(tactic| refine_lift have $d:haveDecl; ?_)\n\n/--\nGiven a main goal `ctx \u22a2 t`, `suffices h : t' from e` replaces the main goal with `ctx \u22a2 t'`,\n`e` must have type `t` in the context `ctx, h : t'`.\n\nThe variant `suffices h : t' by tac` is a shorthand for `suffices h : t' from by tac`.\nIf `h :` is omitted, the name `this` is used.\n -/\nmacro \"suffices \" d:sufficesDecl : tactic => `(tactic| refine_lift suffices $d; ?_)\n/--\n`let h : t := e` adds the hypothesis `h : t := e` to the current goal if `e` a term of type `t`.\nIf `t` is omitted, it will be inferred.\nThe variant `let pattern := e` is equivalent to `match e with | pattern => _`,\nand it is convenient for types that have only applicable constructor.\nExample: given `h : p \u2227 q \u2227 r`, `let \u27e8h\u2081, h\u2082, h\u2083\u27e9 := h` produces the hypotheses\n`h\u2081 : p`, `h\u2082 : q`, and `h\u2083 : r`.\n-/\nmacro \"let \" d:letDecl : tactic => `(tactic| refine_lift let $d:letDecl; ?_)\n/--\n`show t` finds the first goal whose target unifies with `t`. It makes that the main goal,\n performs the unification, and replaces the target with the unified version of `t`.\n-/\nmacro \"show \" e:term : tactic => `(tactic| refine_lift show $e from ?_) -- TODO: fix, see comment\n/-- `let rec f : t := e` adds a recursive definition `f` to the current goal.\nThe syntax is the same as term-mode `let rec`. -/\nsyntax (name := letrec) withPosition(atomic(\"let \" &\"rec \") letRecDecls) : tactic\nmacro_rules\n  | `(tactic| let rec $d) => `(tactic| refine_lift let rec $d; ?_)\n\n/-- Similar to `refine_lift`, but using `refine'` -/\nmacro \"refine_lift' \" e:term : tactic => `(tactic| focus (refine' no_implicit_lambda% $e; rotate_right))\n/-- Similar to `have`, but using `refine'` -/\nmacro \"have' \" d:haveDecl : tactic => `(tactic| refine_lift' have $d:haveDecl; ?_)\n/-- Similar to `have`, but using `refine'` -/\nmacro (priority := high) \"have'\" x:ident \" := \" p:term : tactic => `(tactic| have' $x : _ := $p)\n/-- Similar to `let`, but using `refine'` -/\nmacro \"let' \" d:letDecl : tactic => `(tactic| refine_lift' let $d:letDecl; ?_)\n\n/--\nThe left hand side of an induction arm, `| foo a b c` or `| @foo a b c`\nwhere `foo` is a constructor of the inductive type and `a b c` are the arguments\nto the contstructor.\n-/\nsyntax inductionAltLHS := \"| \" ((\"@\"? ident) <|> hole) (ident <|> hole)*\n/--\nIn induction alternative, which can have 1 or more cases on the left\nand `_`, `?_`, or a tactic sequence after the `=>`.\n-/\nsyntax inductionAlt  := ppDedent(ppLine) inductionAltLHS+ \" => \" (hole <|> syntheticHole <|> tacticSeq)\n/--\nAfter `with`, there is an optional tactic that runs on all branches, and\nthen a list of alternatives.\n-/\nsyntax inductionAlts := \"with \" (tactic)? withPosition((colGe inductionAlt)+)\n\n/--\nAssuming `x` is a variable in the local context with an inductive type,\n`induction x` applies induction on `x` to the main goal,\nproducing one goal for each constructor of the inductive type,\nin which the target is replaced by a general instance of that constructor\nand an inductive hypothesis is added for each recursive argument to the constructor.\nIf the type of an element in the local context depends on `x`,\nthat element is reverted and reintroduced afterward,\nso that the inductive hypothesis incorporates that hypothesis as well.\n\nFor example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`,\n`induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`,\nand one goal with hypotheses `h : P (Nat.succ a)` and `ih\u2081 : P a \u2192 Q a` and target `Q (Nat.succ a)`.\nHere the names `a` and `ih\u2081` are chosen automatically and are not accessible.\nYou can use `with` to provide the variables names for each constructor.\n- `induction e`, where `e` is an expression instead of a variable,\n  generalizes `e` in the goal, and then performs induction on the resulting variable.\n- `induction e using r` allows the user to specify the principle of induction that should be used.\n  Here `r` should be a theorem whose result type must be of the form `C t`,\n  where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables\n- `induction e generalizing z\u2081 ... z\u2099`, where `z\u2081 ... z\u2099` are variables in the local context,\n  generalizes over `z\u2081 ... z\u2099` before applying the induction but then introduces them in each goal.\n  In other words, the net effect is that each inductive hypothesis is generalized.\n- Given `x : Nat`, `induction x with | zero => tac\u2081 | succ x' ih => tac\u2082`\n  uses tactic `tac\u2081` for the `zero` case, and `tac\u2082` for the `succ` case.\n-/\nsyntax (name := induction) \"induction \" term,+ (\" using \" ident)?\n  (\"generalizing \" (colGt term:max)+)? (inductionAlts)? : tactic\n\n/-- A `generalize` argument, of the form `term = x` or `h : term = x`. -/\nsyntax generalizeArg := atomic(ident \" : \")? term:51 \" = \" ident\n\n/--\n* `generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal\n  with a fresh hypothesis `x`s. If `h` is given, `h : e = x` is introduced as well.\n* `generalize e = x at h\u2081 ... h\u2099` also generalizes occurrences of `e`\n  inside `h\u2081`, ..., `h\u2099`.\n* `generalize e = x at *` will generalize occurrences of `e` everywhere.\n-/\nsyntax (name := generalize) \"generalize \" generalizeArg,+ (location)? : tactic\n\n/--\nA `cases` argument, of the form `e` or `h : e` (where `h` asserts that\n`e = c\u1d62 a b` for each constructor `c\u1d62` of the inductive).\n-/\nsyntax casesTarget := atomic(ident \" : \")? term\n/--\nAssuming `x` is a variable in the local context with an inductive type,\n`cases x` splits the main goal, producing one goal for each constructor of the\ninductive type, in which the target is replaced by a general instance of that constructor.\nIf the type of an element in the local context depends on `x`,\nthat element is reverted and reintroduced afterward,\nso that the case split affects that hypothesis as well.\n`cases` detects unreachable cases and closes them automatically.\n\nFor example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`,\n`cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`,\nand one goal with hypothesis `h : P (Nat.succ a)` and target `Q (Nat.succ a)`.\nHere the name `a` is chosen automatically and is not accessible.\nYou can use `with` to provide the variables names for each constructor.\n- `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal,\n  and then cases on the resulting variable.\n- Given `as : List \u03b1`, `cases as with | nil => tac\u2081 | cons a as' => tac\u2082`,\n  uses tactic `tac\u2081` for the `nil` case, and `tac\u2082` for the `cons` case,\n  and `a` and `as'` are used as names for the new variables introduced.\n- `cases h : e`, where `e` is a variable or an expression,\n  performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis,\n  where `...` is the constructor instance for that particular case.\n-/\nsyntax (name := cases) \"cases \" casesTarget,+ (\" using \" ident)? (inductionAlts)? : tactic\n\n/-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/\nsyntax (name := renameI) \"rename_i \" (colGt binderIdent)+ : tactic\n\n/--\n`repeat tac` applies `tac` to main goal. If the application succeeds,\nthe tactic is applied recursively to the generated subgoals until it eventually fails.\n-/\nsyntax \"repeat \" tacticSeq : tactic\nmacro_rules\n  | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)\n\n/--\n`trivial` tries different simple tactics (e.g., `rfl`, `contradiction`, ...)\nto close the current goal.\nYou can use the command `macro_rules` to extend the set of tactics used. Example:\n```\nmacro_rules | `(tactic| trivial) => `(tactic| simp)\n```\n-/\nsyntax \"trivial\" : tactic\n\n/--\nThe `split` tactic is useful for breaking nested if-then-else and `match` expressions into separate cases.\nFor a `match` expression with `n` cases, the `split` tactic generates at most `n` subgoals.\n\nFor example, given `n : Nat`, and a target `if n = 0 then Q else R`, `split` will generate\none goal with hypothesis `n = 0` and target `Q`, and a second goal with hypothesis\n`\u00acn = 0` and target `R`.  Note that the introduced hypothesis is unnamed, and is commonly\nrenamed used the `case` or `next` tactics.\n\n- `split` will split the goal (target).\n- `split at h` will split the hypothesis `h`.\n-/\nsyntax (name := split) \"split \" (colGt term)? (location)? : tactic\n\n/-- `dbg_trace \"foo\"` prints `foo` when elaborated.\nUseful for debugging tactic control flow:\n```\nexample : False \u2228 True := by\n  first\n  | apply Or.inl; trivial; dbg_trace \"left\"\n  | apply Or.inr; trivial; dbg_trace \"right\"\n```\n-/\nsyntax (name := dbgTrace) \"dbg_trace \" str : tactic\n\n/--\n`stop` is a helper tactic for \"discarding\" the rest of a proof:\nit is defined as `repeat sorry`.\nIt is useful when working on the middle of a complex proofs,\nand less messy than commenting the remainder of the proof.\n-/\nmacro \"stop\" tacticSeq : tactic => `(tactic| repeat sorry)\n\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`.\nThe premises of this hypothesis, either universal quantifications or\nnon-dependent implications, are instantiated by concrete terms coming\nfrom arguments `a\u2081` ... `a\u2099`.\nThe tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099`\nand tries to clear the previous one.\n-/\nsyntax (name := specialize) \"specialize \" term : tactic\n\nmacro_rules | `(tactic| trivial) => `(tactic| assumption)\nmacro_rules | `(tactic| trivial) => `(tactic| rfl)\nmacro_rules | `(tactic| trivial) => `(tactic| contradiction)\nmacro_rules | `(tactic| trivial) => `(tactic| decide)\nmacro_rules | `(tactic| trivial) => `(tactic| apply True.intro)\nmacro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)\n\n/--\n`unhygienic tacs` runs `tacs` with name hygiene disabled.\nThis means that tactics that would normally create inaccessible names will instead\nmake regular variables. **Warning**: Tactics may change their variable naming\nstrategies at any time, so code that depends on autogenerated names is brittle.\nUsers should try not to use `unhygienic` if possible.\n```\nexample : \u2200 x : Nat, x = x := by unhygienic\n  intro            -- x would normally be intro'd as inaccessible\n  exact Eq.refl x  -- refer to x\n```\n-/\nmacro \"unhygienic \" t:tacticSeq : tactic => `(tactic| set_option tactic.hygienic false in $t)\n\n/-- `fail msg` is a tactic that always fails, and produces an error using the given message. -/\nsyntax (name := fail) \"fail \" (str)? : tactic\n\n/--\n`checkpoint tac` acts the same as `tac`, but it caches the input and output of `tac`,\nand if the file is re-elaborated and the input matches, the tactic is not re-run and\nits effects are reapplied to the state. This is useful for improving responsiveness\nwhen working on a long tactic proof, by wrapping expensive tactics with `checkpoint`.\n\nSee the `save` tactic, which may be more convenient to use.\n\n(TODO: do this automatically and transparently so that users don't have to use\nthis combinator explicitly.)\n-/\nsyntax (name := checkpoint) \"checkpoint \" tacticSeq : tactic\n\n/--\n`save` is defined to be the same as `skip`, but the elaborator has\nspecial handling for occurrences of `save` in tactic scripts and will transform\n`by tac1; save; tac2` to `by (checkpoint tac1); tac2`, meaning that the effect of `tac1`\nwill be cached and replayed. This is useful for improving responsiveness\nwhen working on a long tactic proof, by using `save` after expensive tactics.\n\n(TODO: do this automatically and transparently so that users don't have to use\nthis combinator explicitly.)\n-/\nmacro (name := save) \"save\" : tactic => `(tactic| skip)\n\n/--\nThe tactic `sleep ms` sleeps for `ms` milliseconds and does nothing.\nIt is used for debugging purposes only.\n-/\nsyntax (name := sleep) \"sleep\" num : tactic\n\n/--\n`exists e\u2081, e\u2082, ...` is shorthand for `refine \u27e8e\u2081, e\u2082, ...\u27e9; try trivial`.\nIt is useful for existential goals.\n-/\nmacro \"exists \" es:term,+ : tactic =>\n  `(tactic| (refine \u27e8$es,*, ?_\u27e9; try trivial))\n\n/--\nApply congruence (recursively) to goals of the form `\u22a2 f as = f bs` and `\u22a2 HEq (f as) (f bs)`.\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 `\u22a2 f (g (x + y)) = f (g (y + x))`,\n`congr` produces the goals `\u22a2 x = y` and `\u22a2 y = x`,\nwhile `congr 2` produces the intended `\u22a2 x + y = y + x`.\n-/\nsyntax (name := congr) \"congr \" (num)? : tactic\n\nend Tactic\n\nnamespace Attr\n/--\nTheorems tagged with the `simp` attribute are by the simplifier\n(i.e., the `simp` tactic, and its variants) to simplify expressions occurring in your goals.\nWe call theorems tagged with the `simp` attribute \"simp theorems\" or \"simp lemmas\".\nLean maintains a database/index containing all active simp theorems.\nHere is an example of a simp theorem.\n```lean\n@[simp] theorem ne_eq (a b : \u03b1) : (a \u2260 b) = Not (a = b) := rfl\n```\nThis simp theorem instructs the simplifier to replace instances of the term\n`a \u2260 b` (e.g. `x + 0 \u2260 y`) with `Not (a = b)` (e.g., `Not (x + 0 = y)`).\nThe simplifier applies simp theorems in one direction only:\nif `A = B` is a simp theorem, then `simp` replaces `A`s with `B`s,\nbut it doesn't replace `B`s with `A`s. Hence a simp theorem should have the\nproperty that its right-hand side is \"simpler\" than its left-hand side.\nIn particular, `=` and `\u2194` should not be viewed as symmetric operators in this situation.\nThe following would be a terrible simp theorem (if it were even allowed):\n```lean\n@[simp] lemma mul_right_inv_bad (a : G) : 1 = a * a\u207b\u00b9 := ...\n```\nReplacing 1 with a * a\u207b\u00b9 is not a sensible default direction to travel.\nEven worse would be a theorem that causes expressions to grow without bound,\ncausing simp to loop forever.\n\nBy default the simplifier applies `simp` theorems to an expression `e`\nafter its sub-expressions have been simplified.\nWe say it performs a bottom-up simplification.\nYou can instruct the simplifier to apply a theorem before its sub-expressions\nhave been simplified by using the modifier `\u2193`. Here is an example\n```lean\n@[simp\u2193] theorem not_and_eq (p q : Prop) : (\u00ac (p \u2227 q)) = (\u00acp \u2228 \u00acq) :=\n```\n\nWhen multiple simp theorems are applicable, the simplifier uses the one with highest priority.\nIf there are several with the same priority, it is uses the \"most recent one\". Example:\n```lean\n@[simp high] theorem cond_true (a b : \u03b1) : cond true a b = a := rfl\n@[simp low+1] theorem or_true (p : Prop) : (p \u2228 True) = True :=\n  propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inr trivial)\n@[simp 100] theorem ite_self {d : Decidable c} (a : \u03b1) : ite c a a = a := by\n  cases d <;> rfl\n```\n-/\nsyntax (name := simp) \"simp\" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr\nend Attr\n\nend Parser\nend Lean\n\n/--\n`\u2039t\u203a` resolves to an (arbitrary) hypothesis of type `t`.\nIt is useful for referring to hypotheses without accessible names.\n`t` may contain holes that are solved by unification with the expected type;\nin particular, `\u2039_\u203a` is a shortcut for `by assumption`.\n-/\nsyntax \"\u2039\" withoutPosition(term) \"\u203a\" : term\nmacro_rules | `(\u2039$type\u203a) => `((by assumption : $type))\n\n/--\n`get_elem_tactic_trivial` is an extensible tactic automatically called\nby the notation `arr[i]` to prove any side conditions that arise when\nconstructing the term (e.g. the index is in bounds of the array).\nThe default behavior is to just try `trivial` (which handles the case\nwhere `i < arr.size` is in the context) and `simp_arith`\n(for doing linear arithmetic in the index).\n-/\nsyntax \"get_elem_tactic_trivial\" : tactic\n\nmacro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| trivial)\nmacro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| simp (config := { arith := true }); done)\n\n/--\n`get_elem_tactic` is the tactic automatically called by the notation `arr[i]`\nto prove any side conditions that arise when constructing the term\n(e.g. the index is in bounds of the array). It just delegates to\n`get_elem_tactic_trivial` and gives a diagnostic error message otherwise;\nusers are encouraged to extend `get_elem_tactic_trivial` instead of this tactic.\n-/\nmacro \"get_elem_tactic\" : tactic =>\n  `(tactic| first\n    | get_elem_tactic_trivial\n    | fail \"failed to prove index is valid, possible solutions:\n  - Use `have`-expressions to prove the index is valid\n  - Use `a[i]!` notation instead, runtime check is perfomed, and 'Panic' error message is produced if index is not valid\n  - Use `a[i]?` notation instead, result is an `Option` type\n  - Use `a[i]'h` notation instead, where `h` is a proof that index is valid\"\n   )\n\n@[inherit_doc getElem]\nsyntax:max term noWs \"[\" withoutPosition(term) \"]\" : term\nmacro_rules | `($x[$i]) => `(getElem $x $i (by get_elem_tactic))\n\n@[inherit_doc getElem]\nsyntax term noWs \"[\" withoutPosition(term) \"]'\" term:max : term\nmacro_rules | `($x[$i]'$h) => `(getElem $x $i $h)\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/Tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510527095787247, "lm_q2_score": 0.06097517873196763, "lm_q1q2_score": 0.021042855578000393}}
{"text": "import Mathlib.Tactic.Recover\n\n/-- problematic tactic for testing recovery -/\nelab \"this\" \"is\" \"a\" \"problem\" : tactic =>\n  Lean.Elab.Tactic.setGoals []\n\n/- The main test-/\nexample : 1 = 1 := by\n  recover this is a problem\n  rfl\n\n/- Tests that recover does no harm -/\nexample : 3 < 4 := by\n    recover decide\n\nexample : 1 = 1 := by\n    recover skip ; rfl\n\nexample : 2 = 2 := by\n    recover skip\n    rfl\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/recover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.05261895167635563, "lm_q1q2_score": 0.02103766940373173}}
{"text": "import Mt.Reservation\nimport Mt.Task.Impl\n\nnamespace Mt\n\n/-- Monad to describe single threaded algorithms. Tasks can be iterated\n  step by step until they finally complete or panic.\n\n  `TaskM` is a monad, i.e. you can use the do-notation to write code:\n\n  ```\n  import Mt.Task.Basic\n  open Mt\n\n  abbrev spec : Spec :={\n    State := Nat,\n    Reservation := UnitReservation,\n    validate :=\u03bb _ _ => True\n  }\n\n  def sample_task : TaskM spec Bool :=do\n    if (<- TaskM.atomic_read \u03bb n => n) > 100 then\n      -- reset to 100\n      TaskM.atomic_read_modify \u03bb _ => 100\n      return false\n    \n    TaskM.atomic_assert \u03bb n => n < 500\n    \n    TaskM.atomic_read_modify \u03bb n => n + 7\n    return true \n  ```\n\n  Note: `TaskM` hat an associative bind operator, but it is not\n  a lawful monad: Binding two `pure` cannot be simplified into\n  a single pure, because it requires two iterations to complete.\n-/\ndef TaskM (spec : Spec) (T : Type) : Type :=TaskM.impl.TaskM spec T\n\n/-- The result of a single iteration of `TaskM`.\n\n  Independent of the result, the resulting shared state after\n  the iteration can be retrieved using `IterationResult.state`\n-/\ninductive TaskM.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) -> TaskM spec T -> IterationResult spec T\n\nvariable {spec : Spec}\n\ndef TaskM.IterationResult.state {T spec} : IterationResult spec T -> spec.State\n| Done s _ => s\n| Panic s _ => s\n| Running s .. => s\n\ninstance TaskM.instMonad : Monad (TaskM spec) where\n  pure :=impl.TaskM.pure\n  bind :=impl.TaskM.bind\n\ntheorem TaskM.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 >>= (fun u => (f u) >>= g) = (mu >>= f) >>= g :=by\n  simp only [Bind.bind]\n  exact impl.TaskM.bind_assoc ..\n\n/-- Atomic `TaskM` primitive with read/write-access to the shared state.\n\n  Additional to performing a read-modify operation, it returns a value.\n\n  Example: Compare Exchange (https://en.wikipedia.org/wiki/Compare-and-swap)\n -/\ndef TaskM.atomic_read_modify_read {T : Type}\n  (f : spec.State -> T \u00d7 spec.State)\n  : TaskM spec T :=impl.TaskM.atomic_read_modify_read f\n\n/-- Atomic `TaskM` primitive to perform read-modify operations on the\n  shared state. It does not return anything. -/\ndef TaskM.atomic_read_modify\n  (f : spec.State -> spec.State) : TaskM spec Unit :=\n  atomic_read_modify_read \u03bb s => \u27e8\u27e8\u27e9, f s\u27e9\n\n/-- Atomic `TaskM` primitive to perform read the shared state. It\n  does not change anything -/\ndef TaskM.atomic_read {T : Type}\n  (f : spec.State -> T)\n  : TaskM spec T :=\n  atomic_read_modify_read \u03bb s => match f s with\n    | t => \u27e8t, s\u27e9\n\n/-- Atomic `TaskM` primitive which throws an exception. The current thread\n  panics and will be removed from the system -/\ndef TaskM.panic {T : Type} (msg : String) : TaskM spec T :=\n  impl.TaskM.panic msg\n\n/-- Atomic `TaskM` primitive to assert a given condition. The condition\n  is checked atomically. If it returns `false`, the current thread panics. -/\ndef TaskM.atomic_assert\n  (cond : spec.State -> Bool)\n  : TaskM spec Unit :=impl.TaskM.atomic_assert cond\n\n/-- `TaskM` primitive which blocks the current thread until a given\n  condition holds, and executes a read-modify-read operation afterwards.\n  \n  There are neither spurious wakeups nor race conditions: The system will\n  only perform the read-modify-read operation if the provided condition\n  holds. If it does not, the thread will block. -/\ndef TaskM.atomic_blocking_rmr\n  (block_until : spec.State -> Bool)\n  (f : spec.State -> T \u00d7 spec.State)\n  : TaskM spec T :=impl.TaskM.atomic_blocking_rmr block_until f\n\n/-- Iterate a given thread on a given state and provides an `IterationResult`.\n\n  The task may complete or panic. If it is does not, it is still running\n  and a continuation will be provided in the result -/\ndef TaskM.iterate {T : Type} : TaskM spec T ->\n  spec.State -> IterationResult spec T :=\n  \u03bb p s => match p s with\n  | impl.IterationResult.Done s' t => IterationResult.Done s' t\n  | impl.IterationResult.Panic s' msg => IterationResult.Panic s' msg\n  | impl.IterationResult.Running s' block_until cont =>\n      IterationResult.Running s' block_until cont\n\n/-- Iteration of `pure t` always completes with result `t` -/\ntheorem TaskM.iterate_pure {T : Type} :\n  \u2200 (s : spec.State) (t : T),\n  iterate (pure t) s = IterationResult.Done s t :=by intros ; rfl\n\n/-- Iteration of `a >>= f` iterates `a` and returns a continuation.\n\n  * If the `a` iteration has completed with result `t`, the next\n    iteration will start work on `f t`\n  * If the `a` iteration has not completed yet, the next iteration\n    will continue.\n  * If `a` has panicked, the exception is propagated.\n -/\ntheorem TaskM.iterate_bind {U V : Type}\n  (mu : TaskM spec U)\n  (f : U -> TaskM spec V)\n  : \u2200 (s : spec.State),\n  iterate (mu >>= f) s = match iterate mu s with\n    | IterationResult.Done s' u => IterationResult.Running s' (\u03bb _ => 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 (cont >>= f) :=by\n  intro s\n  simp only [Bind.bind, iterate, impl.TaskM.bind]\n  cases mu s <;> rfl\n\n/-- Iteration of a read-modify-read-operation will perform the read modify\n  and complete with the computed result. -/\ntheorem TaskM.iterate_rmr {T : Type}\n  (f : spec.State -> T \u00d7 spec.State)\n  : \u2200 s,\n  iterate (atomic_read_modify_read f) s = match f s with\n    | \u27e8t, s'\u27e9 => IterationResult.Done s' t :=by intros ; rfl\n\n/-- Iteration of a read-modify operation will perform the read modify\n  operation and complete with `Unit.unit` -/\ntheorem TaskM.iterate_rm\n  (f : spec.State -> spec.State)\n  : \u2200 s,\n  iterate (atomic_read_modify f) s = match f s with\n    | s' => IterationResult.Done s' \u27e8\u27e9 :=by\n  apply iterate_rmr\n\n/-- Iteration of a read operation will compute a value based on the\n  current shared state and complete with the result -/\ntheorem TaskM.iterate_read\n  (f : spec.State -> T \u00d7 spec.Reservation)\n  : \u2200 s,\n  iterate (atomic_read f) s = match f s with\n    | t => IterationResult.Done s t :=by\n  apply iterate_rmr\n\n/-- Iteration of a panic will fail -/\ntheorem TaskM.iterate_panic {T : Type} (msg : String)\n  : \u2200 (s : spec.State),\n    iterate (panic (T :=T) msg) s = IterationResult.Panic s msg :=by\n  intros ; rfl\n\n/-- Iteration of an assertion will atomically check the condition\n  and succeed or fail depending on the result. -/\ntheorem TaskM.iterate_assert\n  (cond : spec.State -> Bool)\n  : \u2200 s,\n  iterate (atomic_assert cond) s = if cond s then\n    IterationResult.Done s \u27e8\u27e9\n  else\n    IterationResult.Panic s \"Assertion failed\" :=by\n  intro s\n  simp only [atomic_assert, impl.TaskM.atomic_assert, iterate]\n  cases cond s <;> simp only [ite_false, ite_true]\n\n/-- Iteration of a `atomic_blocking_rmr` operation will always\n  return a continuation.\n  \n  The `IterationResult` contains the blocking predicate and\n  the desired read-modify-read operation. The caller should ensure\n  that the read-modify-operation is only iterated when the blocking\n  predicate holds. -/\ntheorem TaskM.iterate_blocking_rmr\n  (block_until : spec.State -> Bool)\n  (f : spec.State -> T \u00d7 spec.State)\n  : \u2200 s,\n  iterate (atomic_blocking_rmr block_until f) s = IterationResult.Running s\n    block_until (atomic_read_modify_read f) :=by intros ; rfl\n\n/-- Well founded relation on `TaskM` fulfilled by continuations with their parents.\n\n  It can be used to perform well founded recursion `TaskM` without using the\n  implementation details of `TaskM`. Whenever `TaskM.iterate` returns a\n  continuation, the continuation will be *smaller* according to this\n  relation.\n  -/\ninductive TaskM.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.iterate s = IterationResult.Running s' block_until cont)\n    : is_direct_cont cont p \n\n/-- See `TaskM.is_direct_cont` -/\ntheorem TaskM.is_direct_cont_wf {T : Type} :\n  WellFounded (@is_direct_cont spec T) :=by\n  constructor ; intro (p : impl.TaskM spec T)\n\n  induction p using WellFounded.induction\n  . exact impl.TaskM.is_direct_cont.wf\n  . clear p ; rename_i p IH\n    constructor ; intro cont is_cont\n    apply IH\n    cases is_cont\n    rename_i s s' block_until iteration\n    rw [iterate] at iteration\n    cases h : p s <;> rw [h] at iteration <;> try contradiction\n    injection iteration\n    rename_i cont'_def ; rw [cont'_def] at h\n    exact \u27e8h\u27e9\n\ninstance TaskM.instWf {T : Type} :\n  WellFoundedRelation (TaskM spec T) where\n  rel :=is_direct_cont\n  wf  :=is_direct_cont_wf\n\nend Mt\n", "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/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.052618948890758833, "lm_q1q2_score": 0.021037668290017707}}
{"text": "import Lean.Meta\nimport LeanCodePrompts\nimport LeanCodePrompts.CheckParse\nimport LeanCodePrompts.Makecaps\nopen Lean\n\nset_option maxHeartbeats 10000000\nset_option maxRecDepth 1000\nset_option compiler.extract_closed false\n\ndef chkDocs : String :=\n\"Utility to check whether a theorem string can be parsed (and elaborated) in lean.\n\n- Give a single argument to check parsing.\n- Give two arguments to compare results (if parsing is successful).\n\nA theorem can be given in one of two forms\n\n- the word `theorem` followed by a name, then the arguments, a `:`, finally the statement, or\n- the arguments, a `:`, and the statement. \n\nThe following examples are of these two forms:\n\n- `theorem nonsense(n : Nat) (m : Nat) : n = m` \n- `(p : Nat)(q: Nat) : p = q`\n\nNote that the arguments can be implicit or explicit. \n\nThe underlying code also supports `open` for namespaces but this demo version does not use these. \n\"\n\ndef main (args: List String) : IO Unit := do\n  initSearchPath (\u2190 Lean.findSysroot) [\"build/lib\", \"lake-packages/mathlib/build/lib/\",  \"lake-packages/std/build/lib/\", \"lake-packages/Qq/build/lib/\", \"lake-packages/aesop/build/lib/\" ]\n  let env \u2190 \n    importModules [{module := `Mathlib},\n    {module := `LeanCodePrompts.Basic},\n    {module:= `LeanCodePrompts.CheckParse},\n    {module := `Mathlib}] {}\n  match args with\n  | [] => IO.println chkDocs\n  | s::[] => do\n    let core := elabThmCore <| mkCap s\n    let io? := \n    core.run' {fileName := \"\", fileMap := \u27e8\"\", #[], #[]\u27e9, maxHeartbeats := 100000000000, maxRecDepth := 1000000} {env := env}\n    match \u2190 io?.toIO' with\n    | Except.ok res =>\n      match res with \n      | Except.ok expr =>\n        IO.println \"success\"\n        IO.println expr\n      | Except.error err =>\n        IO.println \"failure\"\n        IO.println err\n    | Except.error e =>\n      IO.println \"error\"\n      let m := e.toMessageData\n      IO.println <| \u2190 m.toString\n  | s\u2081 :: s\u2082 :: [] => do\n    let core := compareThmsCore (mkCap s\u2081) (mkCap s\u2082)\n    let io? := \n    core.run' {fileName := \"\", fileMap := \u27e8\"\", #[], #[]\u27e9, maxHeartbeats := 100000000000, maxRecDepth := 1000000} {env := env}\n    match \u2190 io?.toIO' with\n    | Except.ok res =>\n      match res with \n      | Except.ok expr =>\n        IO.println \"success\"\n        IO.println expr\n      | Except.error err =>\n        IO.println \"failure\"\n        IO.println err\n    | Except.error e =>\n      IO.println \"error\"\n      let m := e.toMessageData\n      IO.println <| \u2190 m.toString\n  | _ => IO.println s!\"I don't know what to do with {args.length} arguments. Run with no arguments for help.\"", "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/chkthms.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.05834584429580277, "lm_q1q2_score": 0.020967404459005575}}
{"text": "import Std\nnamespace Days\n\nstructure Input := \n  text: String\n  deriving Repr, DecidableEq, Ord\n\ninstance : ToString Input where\n  toString := (\u00b7.text)\n\ndef Input.iter : (@& Input) \u2192 String.Iterator\n  | \u27e8s\u27e9 => s.iter\n\ndef Input.lines : (@& Input) \u2192 List Input\n  | \u27e8s\u27e9 => String.splitOn s \"\\n\" \n      |> .map Input.mk\n\ndef Input.trim : (@& Input) \u2192 Input\n  | \u27e8s\u27e9 => s.trim |> Input.mk\n\ndef Input.toInt? : (@& Input) \u2192 Option Int\n  | \u27e8s\u27e9 => s.toInt?\n\ndef Input.toNat? : (@& Input) \u2192 Option Nat\n  | \u27e8s\u27e9 => s.toNat?\n\ndef Input.intLines (i: Input) : List Int :=\n  i.lines |>.map (\u00b7.toInt?.get!)\n\ndef Input.natLines (i: Input) : List Nat :=\n  i.lines |>.map (\u00b7.toNat?) |>.filterMap id\n\ndef Input.splitOn : (@& Input) \u2192 String \u2192 List Input\n  | \u27e8s\u27e9, sep => String.splitOn s sep\n    |> List.map .mk\n\ninstance : Inhabited Input where\n  default := \u27e8 \"\" \u27e9 \n\nclass ToInput (\u03b1 : Type u) where\n  toInput : \u03b1 \u2192 Input\n\nexport ToInput (toInput)\n\ninstance : ToInput String where\n  toInput := Input.mk\n\ninstance : ToInput Input where\n  toInput := id\n\n/--\nA number type that models a problem number for a day. \nOnly the litteral 1-25 can be parsed into a number.\n-/\nstructure ProblemNumber : Type where\n  of ::\n  day: Nat \n  deriving Repr, Ord, DecidableEq, BEq\n\ninstance : Inhabited ProblemNumber where\n  default := ProblemNumber.of 1\n\ninstance : LT ProblemNumber := ltOfOrd\ninstance : LE ProblemNumber := leOfOrd\n\nexample : ProblemNumber := .of 1\n\ninstance : OfNat ProblemNumber 1 where ofNat := .of 1\ninstance : OfNat ProblemNumber 2 where ofNat := .of 2\ninstance : OfNat ProblemNumber 3 where ofNat := .of 3\ninstance : OfNat ProblemNumber 4 where ofNat := .of 4\ninstance : OfNat ProblemNumber 5 where ofNat := .of 5\ninstance : OfNat ProblemNumber 6 where ofNat := .of 6\ninstance : OfNat ProblemNumber 7 where ofNat := .of 7\ninstance : OfNat ProblemNumber 8 where ofNat := .of 8\ninstance : OfNat ProblemNumber 9 where ofNat := .of 9\n\ninstance : OfNat ProblemNumber 10 where ofNat := .of 10\ninstance : OfNat ProblemNumber 11 where ofNat := .of 11\ninstance : OfNat ProblemNumber 12 where ofNat := .of 12\ninstance : OfNat ProblemNumber 13 where ofNat := .of 13\ninstance : OfNat ProblemNumber 14 where ofNat := .of 14\ninstance : OfNat ProblemNumber 15 where ofNat := .of 15\ninstance : OfNat ProblemNumber 16 where ofNat := .of 16\ninstance : OfNat ProblemNumber 17 where ofNat := .of 17\ninstance : OfNat ProblemNumber 18 where ofNat := .of 18\ninstance : OfNat ProblemNumber 19 where ofNat := .of 19\n\ninstance : OfNat ProblemNumber 20 where ofNat := .of 20\ninstance : OfNat ProblemNumber 21 where ofNat := .of 21\ninstance : OfNat ProblemNumber 22 where ofNat := .of 22\ninstance : OfNat ProblemNumber 23 where ofNat := .of 23\ninstance : OfNat ProblemNumber 24 where ofNat := .of 24\ninstance : OfNat ProblemNumber 25 where ofNat := .of 25\n\ndef ProblemNumber.ofNat? (n: Nat) :=\n  match n with\n  | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n  | 10 | 11 | 12 | 13 | 14 | 15\n  | 16 | 17 | 18 | 19 | 20 \n  | 21 | 22 | 23 | 24 | 25  => some $ ProblemNumber.of n\n  | _ => none\n\ndef ProblemNumber.ofNat! (n: Nat) := \n  match ProblemNumber.ofNat? n with\n  | some n => n\n  | none => panic! s!\"Can't parse problem number from '{n}'; it should be between 1 and 25\"\n\nstructure Problem (\u03b1: Type) [ToString \u03b1]:=\n  define ::\n  day: ProblemNumber\n  part1: Input -> \u03b1\n  part2: Option $ Input -> \u03b1\n\ndef Problem.wrapString {\u03b1: Type} [ToString \u03b1] (p: Problem \u03b1) : Problem String :=\n  Problem.define p.day (toString \u2218 p.part1) (p.part2.map (\u03bb p\u2082 input => p\u2082 input |> toString))\n\ndef Problem.padDay (day: ProblemNumber) : String := \n  if day.day < 10 then s!\"0{day.day}\" else s!\"{day.day}\"\n\ninstance : ToString ProblemNumber where\n  toString p := Problem.padDay p\n\ndef Problem.run [ToString \u03b1] (p: Problem \u03b1) (i: Input) : IO Unit := do\n  let result\u2081 := p.part1 i\n\n  IO.println \"===========================\"\n  IO.println s!\"DAY {p.day}\"\n  IO.println \"===========================\"\n  IO.println s!\"Part 1: {result\u2081}\"\n  IO.println \"===========================\"\n  match p.part2 with\n  | some f => \n    let result\u2082 := f i\n    IO.println s!\"Part 2: {result\u2082}\"\n  | none => \n    IO.println s!\"Part 2: Not done yet\"\n\n  return ()\n\ndef testPart\u2081 [ToInput \u03ba] [ToString \u03b1] [DecidableEq \u03b1] (expect: \u03b1) (p: Problem \u03b1) (input: \u03ba) : IO \u03b1 := do\n  let result := p.part1 <| toInput input\n  if result = expect then\n    IO.println \"Part1 \u2705\"\n  else \n    IO.println \"Part1 \u274c\"\n  return result\n\ndef testPart\u2082 [ToInput \u03ba] [ToString \u03b1] [DecidableEq \u03b1] (expect: \u03b1) (p: Problem \u03b1) (input: \u03ba) : IO \u03b1 := do\n  match result with\n  | none => \n      IO.println \"Part 2 not done yet\"\n      return expect\n  | some result => \n    if result = expect then\n      IO.println \"Part2 \u2705\"\n    else \n      IO.println \"Part2 \u274c\"\n    return result\n  where\n    runPart2 (f: Input -> \u03b1) := f (toInput input)\n    result := p.part2.map runPart2\n", "meta": {"author": "jakeswenson", "repo": "advent2022", "sha": "af941092292ff0bc5552bce9c145d6b5b173c20d", "save_path": "github-repos/lean/jakeswenson-advent2022", "path": "github-repos/lean/jakeswenson-advent2022/advent2022-af941092292ff0bc5552bce9c145d6b5b173c20d/Days.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.06465349331240665, "lm_q1q2_score": 0.02096295119966051}}
{"text": "import data.stream.defs\nimport data.bool.all_any\nimport data.lazy_list\nimport tactic\n\nopen expr tactic widget\n\nmeta def ft : tactic unit :=\ntrace \"f\" >> trace \"t\"\n\nmeta def st : tactic unit :=\nfail \"st\"\n\nmeta def ot : tactic unit :=\nst <|> ft\n\nmeta def trace_goal : tactic unit :=\ntarget >>= trace\n\nmeta def trace_goal_is_eq : tactic unit :=\ndo t \u2190 target,\n  match t with\n  | `(%%l = %%r) := trace $ \"hmm \" ++ (to_string l) ++ \" ?= \" ++ (to_string r)\n  | _ := trace \"goal is not =\"\nend\n\nmeta def list_types : tactic unit :=\ndo\n  l \u2190 local_context,\n  trace l,\n  l.mmap' (\u03bb h, infer_type h >>= trace)\n\n#eval ft\n#eval st\n#eval ot\n#eval trace_goal\n#eval trace_goal_is_eq\n\n#eval trace $ to_raw_fmt $ (`(\u03bb x : \u2115, x) : expr)\n#eval trace $ succ_fn `(\u03bb x : \u2124, 2 * x)\n\nexample : true :=\nbegin\n  trace_goal,\n  trace_goal_is_eq,\n  have : 1 = 2,\n  {\n    trace_goal,\n    trace_goal_is_eq,\n    sorry,\n  },\n  let l := [1, 2, 3, 4],\n  list_types,\nend\n\n/-\nBelow are examples that deal with *raw* expr.\nThese are context-unaware and is not ideal for manipulation.\n-/\n\n-- helper function instead of `expr.mk_app`\nmeta def mk_app (e1 e2 : expr) : expr := app e1 e2\n\n-- function that takes a function `f` and returns essentially `f + 1`\nmeta def succ_fn : expr \u2192 option expr\n| (lam var_name bi var_type body) :=\n  let new_body := mk_app `(nat.succ) body in\n  lam var_name bi var_type new_body\n| _ := none\n\n/-\nBelow, we use `tactic` that allows context-aware metaprogramming\nTutorial: https://www.youtube.com/watch?v=qsmnBNXgZgc\n-/\n\nmeta def inspect_dump : tactic unit :=\ndo t \u2190 target,\n  trace t,\n  a_expr \u2190 get_local `a <|> return `(0),\n  trace (to_raw_fmt a_expr),\n  a_type \u2190 infer_type a_expr,\n  trace a_type,\n  ctx \u2190 local_context,\n  trace ctx,\n  -- new_nat \u2190 40 won't work since 40 is not a tactic\n  -- Either use `new_nat \u2190 return 40` or\n  let new_nat := 40,\n  trace new_nat\n\nexample (a b c : \u2124) : a = b := by do inspect_dump\nexample (b c : \u2124) : b = c := by do inspect_dump\n\n/-\nNow we implement the `assumption` tactic, which looks through local context\nand look for a hypothesis that closes the current goal.\n-/\n\nmeta def map_over_lc (tgt : expr) : list expr \u2192 tactic unit\n| [] := fail \"assump failed.\"\n| (f :: fs) := exact f <|> map_over_lc fs\n\nmeta def assump : tactic unit :=\ndo tgt \u2190 target,\n   ctx \u2190 local_context,\n   map_over_lc tgt ctx\n\n-- This pattern is common and has been implemented already\nmeta def assump' : tactic unit :=\nlocal_context >>= list.mfirst (\u03bb e, exact e)\n\nexample {A B C : Prop} (ha : A) (hb : B) (hc : C) : C := by assump\nexample {A B C : Prop} (ha : A) (hb : B) (hc : C) : C := by assump'\nexample {n : \u2115} (hn : n + 0 = 5) : n = 5 := by assump'\n\n/-\nMore ad-hoc tactic practices\n-/\n\n#check interactive.dec_trivial\n\nmeta def add_refl_hyp (e : expr) : tactic unit :=\ndo tp \u2190 infer_type e,\n   guard (tp = `(\u2115)),\n  --  pf \u2190 mk_app `eq.refl [e],\n   pf \u2190 to_expr ``(not_lt_of_ge (ge_of_eq (eq.refl %%e))),\n   nm \u2190 get_unused_name,\n   note nm none pf,\n   return ()\n\nmeta def add_refl : tactic unit :=\ndo tgt \u2190 target,\n   ctx \u2190 local_context,\n   trace ctx,\n   ctx.mmap' (\u03bb e, try (add_refl_hyp e)),\n   return ()\n\nexample {a b c : \u2115} (ha : a = b) : true := by do add_refl", "meta": {"author": "grhkm21", "repo": "lean", "sha": "52fe0ba1b5c78344c640b0813f11db71338fcba2", "save_path": "github-repos/lean/grhkm21-lean", "path": "github-repos/lean/grhkm21-lean/lean-52fe0ba1b5c78344c640b0813f11db71338fcba2/sketch/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.053403324715219753, "lm_q1q2_score": 0.020952091139154114}}
{"text": "import Lean\nopen List Lean\n\nexample (l : List \u03b1) (h : length l = length l) : length (a::l) = length (a::l) :=\n  congrArg (\u00b7+1) h\n\nelab:max \"(\" tm:term \":)\" : term => Elab.Term.elabTerm tm none\n\nexample (l : List \u03b1) (h : length l = length l) : length (a::l) = length (a::l) :=\n  (congrArg (\u00b7+1) h :)\n\nexample (l : List \u03b1) (h : length l = length l) : length (a::l) = length (a::l) :=\n  have := congrArg (\u00b7+1) h; this\n\nexample (l : List \u03b1) (h : length l = length l) : length (a::l) = length (a::l) := by\n  have := congrArg (\u00b7+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 \u2192 tactic smt_state\n#align smt_state.mk smt_state.mk\n\nunsafe axiom smt_state.to_format : smt_state \u2192 tactic_state \u2192 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 \u2192 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 (\u03b1 : Type) : tactic \u03b1 \u2192 smt_tactic \u03b1\n#align tactic_to_smt_tactic tactic_to_smt_tactic\n\nunsafe instance : HasMonadLift tactic smt_tactic :=\n  \u27e8tactic_to_smt_tactic\u27e9\n\nunsafe instance (\u03b1 : Type) : Coe (tactic \u03b1) (smt_tactic \u03b1) :=\n  \u27e8monadLift\u27e9\n\nunsafe instance : MonadFail smt_tactic :=\n  { smt_tactic.monad with fail := fun \u03b1 s => (tactic.fail (to_fmt s) : smt_tactic \u03b1) }\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 \u2192 smt_tactic Unit\n#align smt_tactic.intron smt_tactic.intron\n\nunsafe axiom intro_lst : List Name \u2192 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 \u2192 Bool) \u2192 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 \u2192 smt_tactic Unit\n#align smt_tactic.ematch_using smt_tactic.ematch_using\n\nunsafe axiom mk_ematch_eqn_lemmas_for_core : Transparency \u2192 Name \u2192 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 \u2192 smt_tactic (expr \u00d7 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 \u2192 smt_tactic Unit\n#align smt_tactic.set_lemmas smt_tactic.set_lemmas\n\nunsafe axiom add_lemmas : hinst_lemmas \u2192 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 \u2190 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 \u2190 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 \u2190 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 {\u03b1} : smt_tactic \u03b1 :=\n  tactic.failed\n#align smt_tactic.failed smt_tactic.failed\n\nunsafe def fail {\u03b1 : Type} {\u03b2 : Type u} [has_to_format \u03b2] (msg : \u03b2) : smt_tactic \u03b1 :=\n  tactic.fail msg\n#align smt_tactic.fail smt_tactic.fail\n\nunsafe def try {\u03b1 : Type} (t : smt_tactic \u03b1) : smt_tactic Unit :=\n  \u27e8fun ss ts =>\n    result.cases_on (t.run ss ts) (fun \u27e8a, new_ss\u27e9 => result.success ((), new_ss)) fun e ref s' =>\n      result.success ((), ss) ts\u27e9\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 \u2192 smt_tactic Unit \u2192 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 \u2192 smt_tactic Unit \u2192 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 \u2192 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 \u00d7 tactic_state) := do\n  let s\u2081 \u2190 get\n  let s\u2082 \u2190 tactic.read\n  return (s\u2081, s\u2082)\n#align smt_tactic.read smt_tactic.read\n\nprotected unsafe def write : smt_state \u00d7 tactic_state \u2192 smt_tactic Unit := fun \u27e8ss, ts\u27e9 =>\n  \u27e8fun _ _ => result.success ((), ss) ts\u27e9\n#align smt_tactic.write smt_tactic.write\n\nprivate unsafe def mk_smt_goals_for (cfg : SmtConfig) :\n    List expr \u2192 List smt_goal \u2192 List expr \u2192 tactic (List smt_goal \u00d7 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] \u2190 smt_state.mk cfg |\n      tactic.failed\n    let [new_tg] \u2190 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 {\u03b1 : Type} (t : tactic \u03b1) (cfg : SmtConfig) : smt_tactic \u03b1 :=\n  \u27e8fun ss => do\n    let _ :: sgs \u2190 return ss |\n      tactic.fail \"slift tactic failed, there no smt goals to be solved\"\n    let tg :: tgs \u2190 tactic.get_goals |\n      tactic.failed\n    tactic.set_goals [tg]\n    let a \u2190 t\n    let new_tgs \u2190 tactic.get_goals\n    let (new_sgs, new_tgs) \u2190 mk_smt_goals_for cfg new_tgs [] []\n    tactic.set_goals (new_tgs ++ tgs)\n    return (a, new_sgs ++ sgs)\u27e9\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 {\u03b1 : Type} (t : tactic \u03b1) : smt_tactic \u03b1 :=\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\u2081, s\u2082) \u2190 smt_tactic.read\n  trace (smt_state.to_format s\u2081 s\u2082)\n#align smt_tactic.trace_state smt_tactic.trace_state\n\nunsafe def trace {\u03b1 : Type} [has_to_tactic_format \u03b1] (a : \u03b1) : 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 \u2190 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 \u00d7 List expr) := do\n  let (g\u2081, _) \u2190 smt_tactic.read\n  let g\u2082 \u2190 tactic.get_goals\n  return (g\u2081, g\u2082)\n#align smt_tactic.get_goals smt_tactic.get_goals\n\nunsafe def set_goals : List smt_goal \u2192 List expr \u2192 smt_tactic Unit := fun g\u2081 g\u2082 =>\n  \u27e8fun ss => tactic.set_goals g\u2082 >> return ((), g\u2081)\u27e9\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 \u2192 List expr \u2192 List smt_goal \u2192 List expr \u2192 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) \u2190 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) \u2190 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) \u2190 get_goals\n  set_goals [s] [t]\n  tac1\n  all_goals tac2\n  let (new_ss, new_ts) \u2190 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  \u27e8seq\u27e9\n\nunsafe def focus1 {\u03b1} (tac : smt_tactic \u03b1) : smt_tactic \u03b1 := do\n  let (s :: ss, t :: ts) \u2190 get_goals\n  match ss with\n    | [] => tac\n    | _ => do\n      set_goals [s] [t]\n      let a \u2190 tac\n      let (ss', ts') \u2190 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) \u2190 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') \u2190 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) \u2190 get_goals\n  match ss, ts with\n    | s\u2081 :: s\u2082 :: ss, t\u2081 :: t\u2082 :: ts => set_goals (s\u2082 :: s\u2081 :: ss) (t\u2082 :: t\u2081 :: 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 \u2190 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 \u2190 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 \u2190 classical\n  if c then destruct (expr.app (expr.const `classical.em []) e)\n    else do\n      let dec_e \u2190\n        mk_app `decidable [e] <|> fail \"by_cases smt_tactic failed, type is not a proposition\"\n      let inst \u2190\n        mk_instance dec_e <|>\n            fail \"by_cases smt_tactic failed, type of given expression is not decidable\"\n      let em \u2190 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 \u2190 target\n  let c \u2190 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 \u2190\n          mk_app `decidable [t] <|>\n              fail \"by_contradiction smt_tactic failed, target is not a proposition\"\n        let inst \u2190\n          mk_instance dec_t <|> fail \"by_contradiction smt_tactic failed, target is not decidable\"\n        let a \u2190 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 \u2190 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 \u2190 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 \u2190 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 \u2190 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 {\u03b1} (t : smt_tactic \u03b1) (cfg : SmtConfig := { }) : tactic \u03b1 := do\n  let ss \u2190 smt_state.mk cfg\n  let (a, _) \u2190\n    (do\n            let a \u2190 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 {\u03b1} (cfg : SmtConfig) (t : smt_tactic \u03b1) : tactic \u03b1 :=\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 (\u03bb x => x)]\n  theorem chain_rule {\u03b1 \u03b2 \u03b3 : Type}\n    (f : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2)\n    : \u2202 (\u03bb x => f (g x)) = \u03bb x dx => \u2202 f (g x) (\u2202 g x dx) := ...\n```\n-/\nsyntax (name := simp_guard) \"simp_guard\" (ident term),+ : attr\n\ninitialize simpGuardAttr : ParametricAttribute (Array (Nat \u00d7 Expr \u00d7 Nat)) \u2190\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 \u03bb (id, val) => do\n          let info \u2190 getConstInfo name\n\n          let nth \u2190 forallTelescope info.type \u03bb args _ => do\n            let i? \u2190 args.findIdxM? \n              (\u03bb arg => do\n                let argDecl \u2190 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) \u2190 forallBoundedTelescope info.type nth \u03bb args _ => do\n            let value \u2190 elabTerm val none\n            let value \u2190 abstractMVars value\n\n            pure (\u2190 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": "/-\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 Init.Prelude\nimport Init.SizeOf\n\nuniverse u v w\n\ndef inline {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := a\n\n@[inline] def flip {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) : \u03b2 \u2192 \u03b1 \u2192 \u03c6 :=\n  fun b a => f a b\n\n@[simp] theorem Function.const_apply {y : \u03b2} {x : \u03b1} : const \u03b1 y x = y := rfl\n\n@[simp] theorem Function.comp_apply {f : \u03b2 \u2192 \u03b4} {g : \u03b1 \u2192 \u03b2} {x : \u03b1} : 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 (\u03b1 : Type u) : Type u where\n  private fn : Unit \u2192 \u03b1\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 : \u03b1) : Thunk \u03b1 :=\n  \u27e8fun _ => a\u27e9\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 \u03b1) : \u03b1 :=\n  x.fn ()\n@[inline] protected def Thunk.map (f : \u03b1 \u2192 \u03b2) (x : Thunk \u03b1) : Thunk \u03b2 :=\n  \u27e8fun _ => f x.get\u27e9\n@[inline] protected def Thunk.bind (x : Thunk \u03b1) (f : \u03b1 \u2192 Thunk \u03b2) : Thunk \u03b2 :=\n  \u27e8fun _ => (f x.get).get\u27e9\n\nabbrev Eq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} {b : \u03b1} (h : a = b) (m : motive a) : motive b :=\n  Eq.ndrec m h\n\nstructure Iff (a b : Prop) : Prop where\n  intro :: (mp : a \u2192 b) (mpr : b \u2192 a)\n\ninfix:20 \" <-> \" => Iff\ninfix:20 \" \u2194 \"   => Iff\n\ninductive Sum (\u03b1 : Type u) (\u03b2 : Type v) where\n  | inl (val : \u03b1) : Sum \u03b1 \u03b2\n  | inr (val : \u03b2) : Sum \u03b1 \u03b2\n\ninfixr:30 \" \u2295 \" => Sum\n\ninductive PSum (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  | inl (val : \u03b1) : PSum \u03b1 \u03b2\n  | inr (val : \u03b2) : PSum \u03b1 \u03b2\n\ninfixr:30 \" \u2295' \" => PSum\n\nstructure Sigma {\u03b1 : Type u} (\u03b2 : \u03b1 \u2192 Type v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\nattribute [unbox] Sigma\n\nstructure PSigma {\u03b1 : Sort u} (\u03b2 : \u03b1 \u2192 Sort v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\ninductive Exists {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) : Prop where\n  | intro (w : \u03b1) (h : p w) : Exists p\n\n/- Auxiliary type used to compile `for x in xs` notation. -/\ninductive ForInStep (\u03b1 : Type u) where\n  | done  : \u03b1 \u2192 ForInStep \u03b1\n  | yield : \u03b1 \u2192 ForInStep \u03b1\n\nclass ForIn (m : Type u\u2081 \u2192 Type u\u2082) (\u03c1 : Type u) (\u03b1 : outParam (Type v)) where\n  forIn {\u03b2} [Monad m] (x : \u03c1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2\n\nexport ForIn (forIn)\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPRBC (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPR (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultBC (\u03c3 : Type u) where\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultBC \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultBC \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultSBC (\u03b1 \u03c3 : Type u) where\n  | \u00abpureReturn\u00bb : \u03b1 \u2192 \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abbreak\u00bb      : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abcontinue\u00bb   : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n\nclass HasEquiv  (\u03b1 : Sort u) where\n  Equiv : \u03b1 \u2192 \u03b1 \u2192 Sort v\n\ninfix:50 \" \u2248 \"  => HasEquiv.Equiv\n\nclass EmptyCollection (\u03b1 : Type u) where\n  emptyCollection : \u03b1\n\nnotation \"{\" \"}\" => EmptyCollection.emptyCollection\nnotation \"\u2205\"     => EmptyCollection.emptyCollection\n\n/- Remark: tasks have an efficient implementation in the runtime. -/\nstructure Task (\u03b1 : Type u) : Type u where\n  pure :: (get : \u03b1)\n  deriving Inhabited\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\ndef Priority.default : Priority := 0\n-- see `LEAN_MAX_PRIO`\ndef Priority.max : Priority := 8\n/--\n  Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.\n  This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more\n  non-dedicated workers than the number of cores to reduce context switches. -/\ndef Priority.dedicated : Priority := 9\n\n@[noinline, extern \"lean_task_spawn\"]\nprotected def spawn {\u03b1 : Type u} (fn : Unit \u2192 \u03b1) (prio := Priority.default) : Task \u03b1 :=\n  \u27e8fn ()\u27e9\n\n@[noinline, extern \"lean_task_map\"]\nprotected def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (x : Task \u03b1) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8f x.get\u27e9\n\n@[noinline, extern \"lean_task_bind\"]\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} (x : Task \u03b1) (f : \u03b1 \u2192 Task \u03b2) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8(f x.get).get\u27e9\n\nend Task\n\n/- Some type that is not a scalar value in our runtime. -/\nstructure NonScalar where\n  val : Nat\n\n/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/\ninductive PNonScalar : Type u where\n  | mk (v : Nat) : PNonScalar\n\n@[simp] theorem Nat.add_zero (n : Nat) : n + 0 = n := rfl\n\ntheorem optParam_eq (\u03b1 : Sort u) (default : \u03b1) : optParam \u03b1 default = \u03b1 := rfl\n\n/- Boolean operators -/\n\n@[extern c inline \"#1 || #2\"] def strictOr  (b\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\n@[extern c inline \"#1 && #2\"] def strictAnd (b\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\n\n@[inline] def bne {\u03b1 : Type u} [BEq \u03b1] (a b : \u03b1) : Bool :=\n  !(a == b)\n\ninfix:50 \" != \" => bne\n\n/- Logical connectives an equality -/\n\ndef implies (a b : Prop) := a \u2192 b\n\ntheorem implies.trans {p q r : Prop} (h\u2081 : implies p q) (h\u2082 : implies q r) : implies p r :=\n  fun hp => h\u2082 (h\u2081 hp)\n\ndef trivial : True := \u27e8\u27e9\n\ntheorem mt {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : \u00acb) : \u00aca :=\n  fun ha => h\u2082 (h\u2081 ha)\n\ntheorem not_false : \u00acFalse := id\n\ntheorem not_not_intro {p : Prop} (h : p) : \u00ac \u00ac p :=\n  fun hn : \u00ac p => hn h\n\n-- proof irrelevance is built in\ntheorem proofIrrel {a : Prop} (h\u2081 h\u2082 : a) : h\u2081 = h\u2082 := rfl\n\ntheorem id.def {\u03b1 : Sort u} (a : \u03b1) : id a = a := rfl\n\n@[macroInline] def Eq.mp {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (a : \u03b1) : \u03b2 :=\n  h \u25b8 a\n\n@[macroInline] def Eq.mpr {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (b : \u03b2) : \u03b1 :=\n  h \u25b8 b\n\ntheorem Eq.substr {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : b = a) (h\u2082 : p a) : p b :=\n  h\u2081 \u25b8 h\u2082\n\ntheorem cast_eq {\u03b1 : Sort u} (h : \u03b1 = \u03b1) (a : \u03b1) : cast h a = a :=\n  rfl\n\n@[reducible] def Ne {\u03b1 : Sort u} (a b : \u03b1) :=\n  \u00ac(a = b)\n\ninfix:50 \" \u2260 \"  => Ne\n\nsection Ne\nvariable {\u03b1 : Sort u}\nvariable {a b : \u03b1} {p : Prop}\n\ntheorem Ne.intro (h : a = b \u2192 False) : a \u2260 b := h\n\ntheorem Ne.elim (h : a \u2260 b) : a = b \u2192 False := h\n\ntheorem Ne.irrefl (h : a \u2260 a) : False := h rfl\n\ntheorem Ne.symm (h : a \u2260 b) : b \u2260 a :=\n  fun h\u2081 => h (h\u2081.symm)\n\ntheorem false_of_ne : a \u2260 a \u2192 False := Ne.irrefl\n\ntheorem ne_false_of_self : p \u2192 p \u2260 False :=\n  fun (hp : p) (h : p = False) => h \u25b8 hp\n\ntheorem ne_true_of_not : \u00acp \u2192 p \u2260 True :=\n  fun (hnp : \u00acp) (h : p = True) =>\n    have : \u00acTrue := h \u25b8 hnp\n    this trivial\n\ntheorem true_ne_false : \u00acTrue = False :=\n  ne_false_of_self trivial\n\nend Ne\n\nsection\nvariable {\u03b1 \u03b2 \u03c6 : Sort u} {a a' : \u03b1} {b b' : \u03b2} {c : \u03c6}\n\ntheorem HEq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} (m : motive a) {\u03b2 : Sort u2} {b : \u03b2} (h : HEq a b) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} {\u03b2 : Sort u2} {b : \u03b2} (h : HEq a b) (m : motive a) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.elim {\u03b1 : Sort u} {a : \u03b1} {p : \u03b1 \u2192 Sort v} {b : \u03b1} (h\u2081 : HEq a b) (h\u2082 : p a) : p b :=\n  eq_of_heq h\u2081 \u25b8 h\u2082\n\ntheorem HEq.subst {p : (T : Sort u) \u2192 T \u2192 Prop} (h\u2081 : HEq a b) (h\u2082 : p \u03b1 a) : p \u03b2 b :=\n  HEq.ndrecOn h\u2081 h\u2082\n\ntheorem HEq.symm (h : HEq a b) : HEq b a :=\n  HEq.ndrecOn (motive := fun x => HEq x a) h (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\u2081 : HEq a b) (h\u2082 : HEq b c) : HEq a c :=\n  HEq.subst h\u2082 h\u2081\n\ntheorem heq_of_heq_of_eq (h\u2081 : HEq a b) (h\u2082 : b = b') : HEq a b' :=\n  HEq.trans h\u2081 (heq_of_eq h\u2082)\n\ntheorem heq_of_eq_of_heq (h\u2081 : a = a') (h\u2082 : HEq a' b) : HEq a b :=\n  HEq.trans (heq_of_eq h\u2081) h\u2082\n\ndef type_eq_of_heq (h : HEq a b) : \u03b1 = \u03b2 :=\n  HEq.ndrecOn (motive := @fun (x : Sort u) _ => \u03b1 = x) h (Eq.refl \u03b1)\n\nend\n\ntheorem eqRec_heq {\u03b1 : Sort u} {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} : (h : a = a') \u2192 (p : \u03c6 a) \u2192 HEq (Eq.recOn (motive := fun x _ => \u03c6 x) h p) p\n  | rfl, p => HEq.refl p\n\ntheorem heq_of_eqRec_eq {\u03b1 \u03b2 : Sort u} {a : \u03b1} {b : \u03b2} (h\u2081 : \u03b1 = \u03b2) (h\u2082 : Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\u2081 = b) : HEq a b := by\n  subst h\u2081\n  apply heq_of_eq\n  exact h\u2082\n\ntheorem cast_heq {\u03b1 \u03b2 : Sort u} : (h : \u03b1 = \u03b2) \u2192 (a : \u03b1) \u2192 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 \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 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 \u2194 a :=\n  Iff.intro (fun h => h) (fun h => h)\n\nprotected theorem Iff.rfl {a : Prop} : a \u2194 a :=\n  Iff.refl a\n\ntheorem Iff.trans (h\u2081 : a \u2194 b) (h\u2082 : b \u2194 c) : a \u2194 c :=\n  Iff.intro\n    (fun ha => Iff.mp h\u2082 (Iff.mp h\u2081 ha))\n    (fun hc => Iff.mpr h\u2081 (Iff.mpr h\u2082 hc))\n\ntheorem Iff.symm (h : a \u2194 b) : b \u2194 a :=\n  Iff.intro (Iff.mpr h) (Iff.mp h)\n\ntheorem Iff.comm : (a \u2194 b) \u2194 (b \u2194 a) :=\n  Iff.intro Iff.symm Iff.symm\n\n/- Exists -/\n\ntheorem Exists.elim {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {b : Prop}\n   (h\u2081 : Exists (fun x => p x)) (h\u2082 : \u2200 (a : \u03b1), p a \u2192 b) : b :=\n  h\u2082 h\u2081.1 h\u2081.2\n\n/- Decidable -/\n\ntheorem decide_true_eq_true (h : Decidable True) : @decide True h = true :=\n  match h with\n  | isTrue h  => rfl\n  | isFalse h => False.elim <| h \u27e8\u27e9\n\ntheorem decide_false_eq_false (h : Decidable False) : @decide False h = false :=\n  match h with\n  | isFalse h => 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 p (h := d)\n\ntheorem toBoolUsing_eq_true {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=\n  decide_eq_true (s := d) h\n\ntheorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=\n  of_decide_eq_true (s := d) h\n\ntheorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : \u00ac p :=\n  of_decide_eq_false (s := 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@[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p \u2192 q) (h2 : \u00acp \u2192 q) : q :=\n  match dec with\n  | isTrue h  => h1 h\n  | isFalse h => h2 h\n\ntheorem em (p : Prop) [Decidable p] : p \u2228 \u00acp :=\n  byCases Or.inl Or.inr\n\ntheorem byContradiction [dec : Decidable p] (h : \u00acp \u2192 False) : p :=\n  byCases id (fun np => False.elim (h np))\n\ntheorem of_not_not [Decidable p] : \u00ac \u00ac p \u2192 p :=\n  fun hnn => byContradiction (fun hn => absurd hn hnn)\n\ntheorem not_and_iff_or_not (p q : Prop) [d\u2081 : Decidable p] [d\u2082 : Decidable q] : \u00ac (p \u2227 q) \u2194 \u00ac p \u2228 \u00ac q :=\n  Iff.intro\n    (fun h => match d\u2081, d\u2082 with\n      | isTrue h\u2081,  isTrue h\u2082   => absurd (And.intro h\u2081 h\u2082) h\n      | _,           isFalse h\u2082 => Or.inr h\u2082\n      | isFalse h\u2081, _           => Or.inl h\u2081)\n    (fun (h) \u27e8hp, hq\u27e9 => 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@[inline] def  decidableOfDecidableOfIff (hp : Decidable p) (h : p \u2194 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@[inline] def  decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=\n  h \u25b8 hp\nend\n\n@[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p \u2192 q) :=\n  if hp : p then\n    if hq : q then isTrue (fun h => 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 \u2194 q) :=\n  if hp : p then\n    if hq : q then\n      isTrue \u27e8fun _ => hq, fun _ => hp\u27e9\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 \u27e8fun h => absurd h hp, fun h => absurd h hq\u27e9\n\n/- if-then-else expression theorems -/\n\ntheorem if_pos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = t :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem if_neg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = e :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\ntheorem dif_pos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = t hc :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem dif_neg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = e hnc :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\n-- Remark: dite and ite are \"defally equal\" when we ignore the proofs.\ntheorem dif_eq_if (c : Prop) [h : Decidable c] {\u03b1 : Sort u} (t : \u03b1) (e : \u03b1) : dite c (fun h => t) (fun h => e) = ite c t e :=\n  match h with\n  | isTrue hc   => rfl\n  | isFalse hnc => 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 hc  => dT\n  | isFalse hc => dE\n\ninstance {c : Prop} {t : c \u2192 Prop} {e : \u00acc \u2192 Prop} [dC : Decidable c] [dT : \u2200 h, Decidable (t h)] [dE : \u2200 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 definitions for generating compact `noConfusion` for enumeration types -/\nabbrev noConfusionTypeEnum {\u03b1 : Sort u} {\u03b2 : Sort v} [DecidableEq \u03b2] (f : \u03b1 \u2192 \u03b2) (P : Sort w) (x y : \u03b1) : Sort w :=\n  if f x = f y then P \u2192 P else P\n\nabbrev noConfusionEnum {\u03b1 : Sort u} {\u03b2 : Sort v} [DecidableEq \u03b2] (f : \u03b1 \u2192 \u03b2) {P : Sort w} {x y : \u03b1} (h : x = y) : noConfusionTypeEnum f P x y :=\n  if h' : f x = f y then\n    cast (@if_pos _ _ h' _ (P \u2192 P) (P)).symm (fun (h : P) => h)\n  else\n    False.elim (h' (congrArg f h))\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 {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : Exists (fun x => p x) \u2192 Nonempty \u03b1\n  | \u27e8w, h\u27e9 => \u27e8w\u27e9\n\n/- Subsingleton -/\n\nclass Subsingleton (\u03b1 : Sort u) : Prop where\n  intro :: allEq : (a b : \u03b1) \u2192 a = b\n\nprotected def Subsingleton.elim {\u03b1 : Sort u} [h : Subsingleton \u03b1] : (a b : \u03b1) \u2192 a = b :=\n  h.allEq\n\nprotected def Subsingleton.helim {\u03b1 \u03b2 : Sort u} [h\u2081 : Subsingleton \u03b1] (h\u2082 : \u03b1 = \u03b2) (a : \u03b1) (b : \u03b2) : HEq a b := by\n  subst h\u2082\n  apply heq_of_eq\n  apply Subsingleton.elim\n\ninstance (p : Prop) : Subsingleton p :=\n  \u27e8fun a b => proofIrrel a b\u27e9\n\ninstance (p : Prop) : Subsingleton (Decidable p) :=\n  Subsingleton.intro fun\n    | isTrue t\u2081 => fun\n      | isTrue t\u2082  => rfl\n      | isFalse f\u2082 => absurd t\u2081 f\u2082\n    | isFalse f\u2081 => fun\n      | isTrue t\u2082  => absurd t\u2082 f\u2081\n      | isFalse f\u2082 => rfl\n\ntheorem recSubsingleton\n     {p : Prop} [h : Decidable p]\n     {h\u2081 : p \u2192 Sort u}\n     {h\u2082 : \u00acp \u2192 Sort u}\n     [h\u2083 : \u2200 (h : p), Subsingleton (h\u2081 h)]\n     [h\u2084 : \u2200 (h : \u00acp), Subsingleton (h\u2082 h)]\n     : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h\u2082 h\u2081) :=\n  match h with\n  | isTrue h  => h\u2083 h\n  | isFalse h => h\u2084 h\n\nstructure Equivalence {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Prop where\n  refl  : \u2200 x, r x x\n  symm  : \u2200 {x y}, r x y \u2192 r y x\n  trans : \u2200 {x y z}, r x y \u2192 r y z \u2192 r x z\n\ndef emptyRelation {\u03b1 : Sort u} (a\u2081 a\u2082 : \u03b1) : Prop :=\n  False\n\ndef Subrelation {\u03b1 : Sort u} (q r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  \u2200 {x y}, q x y \u2192 r x y\n\ndef InvImage {\u03b1 : Sort u} {\u03b2 : Sort v} (r : \u03b2 \u2192 \u03b2 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b1 \u2192 Prop :=\n  fun a\u2081 a\u2082 => r (f a\u2081) (f a\u2082)\n\ninductive TC {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : \u03b1 \u2192 \u03b1 \u2192 Prop where\n  | base  : \u2200 a b, r a b \u2192 TC r a b\n  | trans : \u2200 a b c, TC r a b \u2192 TC r b c \u2192 TC r a c\n\n/- Subtype -/\n\nnamespace Subtype\ndef existsOfSubtype {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : { x // p x } \u2192 Exists (fun x => p x)\n  | \u27e8a, h\u27e9 => \u27e8a, h\u27e9\n\nvariable {\u03b1 : Type u} {p : \u03b1 \u2192 Prop}\n\nprotected theorem eq : \u2200 {a1 a2 : {x // p x}}, val a1 = val a2 \u2192 a1 = a2\n  | \u27e8x, h1\u27e9, \u27e8_, _\u27e9, 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 {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} {a : \u03b1} (h : p a) : Inhabited {x // p x} where\n  default := \u27e8a, h\u27e9\n\ninstance {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [DecidableEq \u03b1] : DecidableEq {x : \u03b1 // p x} :=\n  fun \u27e8a, h\u2081\u27e9 \u27e8b, h\u2082\u27e9 =>\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 {\u03b1 : Type u} {\u03b2 : Type v}\n\ninstance Sum.inhabitedLeft [h : Inhabited \u03b1] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inl default\n\ninstance Sum.inhabitedRight [h : Inhabited \u03b2] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inr default\n\ninstance {\u03b1 : Type u} {\u03b2 : Type v} [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (Sum \u03b1 \u03b2) := fun a b =>\n  match a, b with\n  | Sum.inl a, Sum.inl b =>\n    if h : a = b then isTrue (h \u25b8 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 \u25b8 rfl)\n    else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h\n  | Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h\n  | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h\n\nend\n\n/- Product -/\n\ninstance [Inhabited \u03b1] [Inhabited \u03b2] : Inhabited (\u03b1 \u00d7 \u03b2) where\n  default := (default, default)\n\ninstance [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (\u03b1 \u00d7 \u03b2) :=\n  fun (a, b) (a', b') =>\n    match decEq a a' with\n    | isTrue e\u2081 =>\n      match decEq b b' with\n      | isTrue e\u2082  => isTrue (e\u2081 \u25b8 e\u2082 \u25b8 rfl)\n      | isFalse n\u2082 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2082' n\u2082\n    | isFalse n\u2081 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2081' n\u2081\n\ninstance [BEq \u03b1] [BEq \u03b2] : BEq (\u03b1 \u00d7 \u03b2) where\n  beq := fun (a\u2081, b\u2081) (a\u2082, b\u2082) => a\u2081 == a\u2082 && b\u2081 == b\u2082\n\ninstance [LT \u03b1] [LT \u03b2] : LT (\u03b1 \u00d7 \u03b2) where\n  lt s t := s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)\n\ninstance prodHasDecidableLt\n    [LT \u03b1] [LT \u03b2] [DecidableEq \u03b1] [DecidableEq \u03b2]\n    [(a b : \u03b1) \u2192 Decidable (a < b)] [(a b : \u03b2) \u2192 Decidable (a < b)]\n    : (s t : \u03b1 \u00d7 \u03b2) \u2192 Decidable (s < t) :=\n  fun t s => inferInstanceAs (Decidable (_ \u2228 _))\n\ntheorem Prod.lt_def [LT \u03b1] [LT \u03b2] (s t : \u03b1 \u00d7 \u03b2) : (s < t) = (s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)) :=\n  rfl\n\ntheorem Prod.ext (p : \u03b1 \u00d7 \u03b2) : (p.1, p.2) = p := by\n  cases p; rfl\n\ndef Prod.map {\u03b1\u2081 : Type u\u2081} {\u03b1\u2082 : Type u\u2082} {\u03b2\u2081 : Type v\u2081} {\u03b2\u2082 : Type v\u2082}\n    (f : \u03b1\u2081 \u2192 \u03b1\u2082) (g : \u03b2\u2081 \u2192 \u03b2\u2082) : \u03b1\u2081 \u00d7 \u03b2\u2081 \u2192 \u03b1\u2082 \u00d7 \u03b2\u2082\n  | (a, b) => (f a, g b)\n\n/- Dependent products -/\n\ntheorem ex_of_PSigma {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : (PSigma (fun x => p x)) \u2192 Exists (fun x => p x)\n  | \u27e8x, hx\u27e9 => \u27e8x, hx\u27e9\n\nprotected theorem PSigma.eta {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {a\u2081 a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081} {b\u2082 : \u03b2 a\u2082}\n    (h\u2081 : a\u2081 = a\u2082) (h\u2082 : Eq.ndrec b\u2081 h\u2081 = b\u2082) : PSigma.mk a\u2081 b\u2081 = PSigma.mk a\u2082 b\u2082 := by\n  subst h\u2081\n  subst h\u2082\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 = \u27e8\u27e9 :=\n  PUnit.subsingleton a \u27e8\u27e9\n\ninstance : Subsingleton PUnit :=\n  Subsingleton.intro PUnit.subsingleton\n\ninstance : Inhabited PUnit where\n  default := \u27e8\u27e9\n\ninstance : DecidableEq PUnit :=\n  fun a b => isTrue (PUnit.subsingleton a b)\n\n/- Setoid -/\n\nclass Setoid (\u03b1 : Sort u) where\n  r : \u03b1 \u2192 \u03b1 \u2192 Prop\n  iseqv {} : Equivalence r\n\ninstance {\u03b1 : Sort u} [Setoid \u03b1] : HasEquiv \u03b1 :=\n  \u27e8Setoid.r\u27e9\n\nnamespace Setoid\n\nvariable {\u03b1 : Sort u} [Setoid \u03b1]\n\ntheorem refl (a : \u03b1) : a \u2248 a :=\n  (Setoid.iseqv \u03b1).refl a\n\ntheorem symm {a b : \u03b1} (hab : a \u2248 b) : b \u2248 a :=\n  (Setoid.iseqv \u03b1).symm hab\n\ntheorem trans {a b c : \u03b1} (hab : a \u2248 b) (hbc : b \u2248 c) : a \u2248 c :=\n  (Setoid.iseqv \u03b1).trans hab hbc\n\nend Setoid\n\n\n/- Propositional extensionality -/\n\naxiom propext {a b : Prop} : (a \u2194 b) \u2192 a = b\n\ntheorem Eq.propIntro {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : b \u2192 a) : a = b :=\n  propext <| Iff.intro h\u2081 h\u2082\n\n-- Eq for Prop is now decidable if the equivalent Iff is decidable\ninstance {p q : Prop} [d : Decidable (p \u2194 q)] : Decidable (p = q) :=\n  match d with\n  | isTrue h => isTrue (propext h)\n  | isFalse h => isFalse fun heq => h (heq \u25b8 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/- Quotients -/\n\n-- Iff can now be used to do substitutions in a calculation\ntheorem Iff.subst {a b : Prop} {p : Prop \u2192 Prop} (h\u2081 : a \u2194 b) (h\u2082 : p a) : p b :=\n  Eq.subst (propext h\u2081) h\u2082\n\nnamespace Quot\naxiom sound : \u2200 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a b : \u03b1}, r a b \u2192 Quot.mk r a = Quot.mk r b\n\nprotected theorem liftBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v}\n    (f : \u03b1 \u2192 \u03b2)\n    (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b)\n    (a : \u03b1)\n    : lift f c (Quot.mk r a) = f a :=\n  rfl\n\nprotected theorem indBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (p : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (a : \u03b1)\n    : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=\n  rfl\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b) : \u03b2 :=\n  lift f c q\n\nprotected theorem inductionOn {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (q : Quot r)\n    (h : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q :=\n  ind h q\n\ntheorem exists_rep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=\n  Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => \u27e8a, rfl\u27e9)\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\nvariable {motive : Quot r \u2192 Sort v}\n\n@[reducible, macroInline]\nprotected def indep (f : (a : \u03b1) \u2192 motive (Quot.mk r a)) (a : \u03b1) : PSigma motive :=\n  \u27e8Quot.mk r a, f a\u27e9\n\nprotected theorem indepCoherent\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : (a b : \u03b1) \u2192 r a b \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : \u2200 (a b : \u03b1) (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\nprotected abbrev rec\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 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\nprotected abbrev recOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : motive q :=\n Quot.rec f h q\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quot.mk r a))]\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q := by\n  induction q using Quot.rec\n  apply f\n  apply Subsingleton.elim\n\nprotected abbrev hrecOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (c : (a b : \u03b1) \u2192 (p : r a b) \u2192 HEq (f a) (f b))\n    : motive q :=\n  Quot.recOn q f fun a b p => eq_of_heq <|\n    have p\u2081 : HEq (Eq.ndrec (f a) (sound p)) (f a) := eqRec_heq (sound p) (f a)\n    HEq.trans p\u2081 (c a b p)\n\nend\nend Quot\n\ndef Quotient {\u03b1 : Sort u} (s : Setoid \u03b1) :=\n  @Quot \u03b1 Setoid.r\n\nnamespace Quotient\n\n@[inline]\nprotected def mk {\u03b1 : Sort u} (s : Setoid \u03b1) (a : \u03b1) : Quotient s :=\n  Quot.mk Setoid.r a\n\nprotected def mk' {\u03b1 : Sort u} [s : Setoid \u03b1] (a : \u03b1) : Quotient s :=\n  Quotient.mk s a\n\ndef sound {\u03b1 : Sort u} {s : Setoid \u03b1} {a b : \u03b1} : a \u2248 b \u2192 Quotient.mk s a = Quotient.mk s b :=\n  Quot.sound\n\nprotected abbrev lift {\u03b1 : Sort u} {\u03b2 : Sort v} {s : Setoid \u03b1} (f : \u03b1 \u2192 \u03b2) : ((a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) \u2192 Quotient s \u2192 \u03b2 :=\n  Quot.lift f\n\nprotected theorem ind {\u03b1 : Sort u} {s : Setoid \u03b1} {motive : Quotient s \u2192 Prop} : ((a : \u03b1) \u2192 motive (Quotient.mk s a)) \u2192 (q : Quot Setoid.r) \u2192 motive q :=\n  Quot.ind\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} {s : Setoid \u03b1} (q : Quotient s) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) : \u03b2 :=\n  Quot.liftOn q f c\n\nprotected theorem inductionOn {\u03b1 : Sort u} {s : Setoid \u03b1} {motive : Quotient s \u2192 Prop}\n    (q : Quotient s)\n    (h : (a : \u03b1) \u2192 motive (Quotient.mk s a))\n    : motive q :=\n  Quot.inductionOn q h\n\ntheorem exists_rep {\u03b1 : Sort u} {s : Setoid \u03b1} (q : Quotient s) : Exists (fun (a : \u03b1) => Quotient.mk s a = q) :=\n  Quot.exists_rep q\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {s : Setoid \u03b1}\nvariable {motive : Quotient s \u2192 Sort v}\n\n@[inline]\nprotected def rec\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk s a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    (q : Quotient s)\n    : motive q :=\n  Quot.rec f h q\n\nprotected abbrev recOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk s a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    : motive q :=\n  Quot.recOn q f h\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quotient.mk s a))]\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk s a))\n    : motive q :=\n  Quot.recOnSubsingleton (h := h) q f\n\nprotected abbrev hrecOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk s a))\n    (c : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 HEq (f a) (f b))\n    : motive q :=\n  Quot.hrecOn q f c\nend\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB} {\u03c6 : Sort uC}\nvariable {s\u2081 : Setoid \u03b1} {s\u2082 : Setoid \u03b2}\n\nprotected abbrev lift\u2082\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    (q\u2081 : Quotient s\u2081) (q\u2082 : Quotient s\u2082)\n    : \u03c6 := by\n  apply Quotient.lift (fun (a\u2081 : \u03b1) => Quotient.lift (f a\u2081) (fun (a b : \u03b2) => c a\u2081 a a\u2081 b (Setoid.refl a\u2081)) q\u2082) _ q\u2081\n  intros\n  induction q\u2082 using Quotient.ind\n  apply c; assumption; apply Setoid.refl\n\nprotected abbrev liftOn\u2082\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    : \u03c6 :=\n  Quotient.lift\u2082 f c q\u2081 q\u2082\n\nprotected theorem ind\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2083\n    {s\u2083 : Setoid \u03c6}\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Quotient s\u2083 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (q\u2083 : Quotient s\u2083)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 (c : \u03c6) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b) (Quotient.mk s\u2083 c))\n    : motive q\u2081 q\u2082 q\u2083 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  induction q\u2083 using Quotient.ind\n  apply h\n\nend\n\nsection Exact\n\nvariable   {\u03b1 : Sort u}\n\nprivate def rel {s : Setoid \u03b1} (q\u2081 q\u2082 : Quotient s) : Prop :=\n  Quotient.liftOn\u2082 q\u2081 q\u2082\n    (fun a\u2081 a\u2082 => a\u2081 \u2248 a\u2082)\n    (fun a\u2081 a\u2082 b\u2081 b\u2082 a\u2081b\u2081 a\u2082b\u2082 =>\n      propext (Iff.intro\n        (fun a\u2081a\u2082 => Setoid.trans (Setoid.symm a\u2081b\u2081) (Setoid.trans a\u2081a\u2082 a\u2082b\u2082))\n        (fun b\u2081b\u2082 => Setoid.trans a\u2081b\u2081 (Setoid.trans b\u2081b\u2082 (Setoid.symm a\u2082b\u2082)))))\n\nprivate theorem rel.refl {s : Setoid \u03b1} (q : Quotient s) : rel q q :=\n  Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a)\n\nprivate theorem rel_of_eq {s : Setoid \u03b1} {q\u2081 q\u2082 : Quotient s} : q\u2081 = q\u2082 \u2192 rel q\u2081 q\u2082 :=\n  fun h => Eq.ndrecOn h (rel.refl q\u2081)\n\ntheorem exact {s : Setoid \u03b1} {a b : \u03b1} : Quotient.mk s a = Quotient.mk s b \u2192 a \u2248 b :=\n  fun h => rel_of_eq h\n\nend Exact\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB}\nvariable {s\u2081 : Setoid \u03b1} {s\u2082 : Setoid \u03b2}\n\nprotected abbrev recOnSubsingleton\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Sort uC}\n    [s : (a : \u03b1) \u2192 (b : \u03b2) \u2192 Subsingleton (motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))]\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (g : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk s\u2081 a) (Quotient.mk s\u2082 b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quot.recOnSubsingleton\n  induction q\u2082 using Quot.recOnSubsingleton\n  apply g\n  intro a; apply s\n  induction q\u2082 using Quot.recOnSubsingleton\n  intro a; apply s\n  infer_instance\n\nend\nend Quotient\n\nsection\nvariable {\u03b1 : Type u}\nvariable (r : \u03b1 \u2192 \u03b1 \u2192 Prop)\n\ninstance {\u03b1 : Sort u} {s : Setoid \u03b1} [d : \u2200 (a b : \u03b1), Decidable (a \u2248 b)] : DecidableEq (Quotient s) :=\n  fun (q\u2081 q\u2082 : Quotient s) =>\n    Quotient.recOnSubsingleton\u2082 (motive := fun a b => Decidable (a = b)) q\u2081 q\u2082\n      fun a\u2081 a\u2082 =>\n        match d a\u2081 a\u2082 with\n        | isTrue h\u2081  => isTrue (Quotient.sound h\u2081)\n        | isFalse h\u2082 => isFalse fun h => absurd (Quotient.exact h) h\u2082\n\n/- Function extensionality -/\n\nnamespace Function\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\nprotected def Equiv (f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x) : Prop := \u2200 x, f\u2081 x = f\u2082 x\n\nprotected theorem Equiv.refl (f : \u2200 (x : \u03b1), \u03b2 x) : Function.Equiv f f :=\n  fun x => rfl\n\nprotected theorem Equiv.symm {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} : Function.Equiv f\u2081 f\u2082 \u2192 Function.Equiv f\u2082 f\u2081 :=\n  fun h x => Eq.symm (h x)\n\nprotected theorem Equiv.trans {f\u2081 f\u2082 f\u2083 : \u2200 (x : \u03b1), \u03b2 x} : Function.Equiv f\u2081 f\u2082 \u2192 Function.Equiv f\u2082 f\u2083 \u2192 Function.Equiv f\u2081 f\u2083 :=\n  fun h\u2081 h\u2082 x => Eq.trans (h\u2081 x) (h\u2082 x)\n\nprotected theorem Equiv.isEquivalence (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Equivalence (@Function.Equiv \u03b1 \u03b2) := {\n  refl := Equiv.refl\n  symm := Equiv.symm\n  trans := Equiv.trans\n}\n\nend Function\n\nsection\nopen Quotient\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\n@[instance]\nprivate def funSetoid (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Setoid (\u2200 (x : \u03b1), \u03b2 x) :=\n  Setoid.mk (@Function.Equiv \u03b1 \u03b2) (Function.Equiv.isEquivalence \u03b1 \u03b2)\n\nprivate def extfunApp (f : Quotient <| funSetoid \u03b1 \u03b2) (x : \u03b1) : \u03b2 x :=\n  Quot.liftOn f\n    (fun (f : \u2200 (x : \u03b1), \u03b2 x) => f x)\n    (fun f\u2081 f\u2082 h => h x)\n\ntheorem funext {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} (h : \u2200 x, f\u2081 x = f\u2082 x) : f\u2081 = f\u2082 := by\n  show extfunApp (Quotient.mk' f\u2081) = extfunApp (Quotient.mk' f\u2082)\n  apply congrArg\n  apply Quotient.sound\n  exact h\n\nend\n\ninstance {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton (\u2200 a, \u03b2 a) where\n  allEq f\u2081 f\u2082 :=\n    funext (fun a => Subsingleton.elim (f\u2081 a) (f\u2082 a))\n\n/- Squash -/\n\ndef Squash (\u03b1 : Type u) := Quot (fun (a b : \u03b1) => True)\n\ndef Squash.mk {\u03b1 : Type u} (x : \u03b1) : Squash \u03b1 := Quot.mk _ x\n\ntheorem Squash.ind {\u03b1 : Type u} {motive : Squash \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), motive (Squash.mk a)) : \u2200 (q : Squash \u03b1), motive q :=\n  Quot.ind h\n\n@[inline] def Squash.lift {\u03b1 \u03b2} [Subsingleton \u03b2] (s : Squash \u03b1) (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  Quot.lift f (fun a b _ => Subsingleton.elim _ _) s\n\ninstance : Subsingleton (Squash \u03b1) 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\nnamespace Lean\n/- Kernel reduction hints -/\n\n/--\n  When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.\n  The kernel will not use the interpreter if `c` is not a constant.\n  This feature is useful for performing proofs by reflection.\n\n  Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing\n  free 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\n  Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\n  This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using\n  external type checkers (e.g., Trepplein) that do not implement this feature.\n  Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\n  So, you are mainly losing the capability of type checking your developement using external checkers.\n\n  Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.\n  If an extern function is executed, then the trusted code base will also include the implementation of the associated\n  foreign function.\n-/\nconstant reduceBool (b : Bool) : Bool := b\n\n/--\n  Similar to `Lean.reduceBool` for closed `Nat` terms.\n\n  Remark: we do not have plans for supporting a generic `reduceValue {\u03b1} (a : \u03b1) : \u03b1 := a`.\n  The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.\n  We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/\nconstant reduceNat (n : Nat) : Nat := n\n\naxiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b\naxiom ofReduceNat (a b : Nat) (h : reduceNat a = b)    : a = b\n\nend Lean\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/Core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.05749328364515302, "lm_q1q2_score": 0.020868292279764084}}
{"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' {\u03b1 : Sort*} {p q : Prop}\n  (h : p \u2228 q) (f : p \u2192 \u03b1) (g : q \u2192 \u03b1) : \u03b1 :=\nif hp : p then f hp else g (h.resolve_left hp)\n\nlemma _root_.or.elim'_left {\u03b1 : Sort*} {p q : Prop}\n  (h : p \u2228 q) (f : p \u2192 \u03b1) (g : q \u2192 \u03b1) (hp : p) : h.elim' f g = f hp :=\nby rw [or.elim', dif_pos hp]\n\nlemma _root_.or.elim'_right {\u03b1 : Sort*} {p q : Prop}\n  (h : p \u2228 q) (f : p \u2192 \u03b1) (g : q \u2192 \u03b1) (hp : \u00acp) : 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 \u2192. atom)\n(litter_map : litter \u2192. near_litter)\n(atom_map_dom_small : small atom_map.dom)\n(litter_map_dom_small : small litter_map.dom)\n(atom_map_injective : \u2200 \u2983a b\u2984 ha hb, (atom_map a).get ha = (atom_map b).get hb \u2192 a = b)\n(litter_map_injective : \u2200 \u2983L\u2081 L\u2082 : litter\u2984 hL\u2081 hL\u2082,\n  (((litter_map L\u2081).get hL\u2081 : set atom) \u2229 (litter_map L\u2082).get hL\u2082).nonempty \u2192 L\u2081 = L\u2082)\n(atom_mem : \u2200 (a : atom) ha L hL, a.1 = L \u2194 (atom_map a).get ha \u2208 (litter_map L).get hL)\n\n/-- A `\u03b2`-weak structural approximation is a product that assigns a weak near-litter approximation\nto each `\u03b2`-extended index. -/\ndef weak_struct_approx (\u03b2 : type_index) := extended_index \u03b2 \u2192 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 \u2192 Prop\n| atom_dom (a : atom) : (w.atom_map a).dom \u2192 banned_litter a.1\n| litter_dom (L : litter) : (w.litter_map L).dom \u2192 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 \u2208 ((w.litter_map L).get h : set atom) \\ litter_set ((w.litter_map L).get h).1 \u2192\n    banned_litter a.1\n\nlemma banned_litter.mem_map (a : atom) (L : litter) (hL)\n  (ha : a \u2208 ((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 \u27e8ha, h\u27e9, },\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 \u27e8\u27e8\u03bb a, \u27e8_, a.prop.some_spec.1\u27e9, \u03bb a\u2081 a\u2082 h, _\u27e9\u27e9,\n    simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n    have := a\u2081.prop.some_spec.2,\n    rw h at this,\n    exact subtype.coe_injective (this.trans a\u2082.prop.some_spec.2.symm), },\n  { refine lt_of_le_of_lt _ w.litter_map_dom_small,\n    refine \u27e8\u27e8\u03bb L, \u27e8_, L.prop\u27e9, \u03bb L\u2081 L\u2082 h, _\u27e9\u27e9,\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 \u27e8\u27e8\u03bb L, \u27e8_, L.prop.some_spec.some\u27e9, \u03bb L\u2081 L\u2082 h, _\u27e9\u27e9,\n    simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n    have := L\u2081.prop.some_spec.some_spec,\n    simp_rw h at this,\n    exact subtype.coe_injective (this.trans L\u2082.prop.some_spec.some_spec.symm), },\n  { refine lt_of_le_of_lt _ w.litter_map_dom_small,\n    refine \u27e8\u27e8\u03bb L, \u27e8_, L.prop.some_spec.some\u27e9, \u03bb L\u2081 L\u2082 h, _\u27e9\u27e9,\n    simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n    have := L\u2081.prop.some_spec.some_spec,\n    simp_rw h at this,\n    exact subtype.coe_injective (this.trans L\u2082.prop.some_spec.some_spec.symm), },\n  { have : small \u22c3 (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 \u27e8\u27e8\u03bb N, \u27e8_, N.prop\u27e9, \u03bb N\u2081 N\u2082 h, _\u27e9\u27e9,\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 \u03bb x hx, or.inr hx, }, },\n    refine lt_of_le_of_lt _ this,\n    refine \u27e8\u27e8\u03bb L, \u27e8L.prop.some_spec.some_spec.some, _\u27e9, \u03bb L\u2081 L\u2082 h, _\u27e9\u27e9,\n    { simp only [mem_Union],\n      exact \u27e8_, _, L.prop.some_spec.some_spec.some_spec.1\u27e9, },\n    simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n    have := L\u2081.prop.some_spec.some_spec.some_spec.2,\n    rw h at this,\n    exact subtype.coe_injective\n      (this.trans L\u2082.prop.some_spec.some_spec.some_spec.2.symm), },\nend\n\nlemma mk_not_banned_litter : #{L | \u00acw.banned_litter L} = #\u03bc :=\nbegin\n  have := mk_sum_compl {L | w.banned_litter L},\n  rw [compl_set_of, mk_litter] at this,\n  rw [\u2190 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 \u03bc_strong_limit.is_limit.aleph_0_le \u03ba_lt_\u03bc _,\n    exact lt_of_le_of_lt \u03ba_regular.aleph_0_le \u03ba_lt_\u03bc, },\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 \u03bc_strong_limit.is_limit.aleph_0_le \u03ba_lt_\u03bc _,\n    exact lt_trans w.banned_litter_small \u03ba_lt_\u03bc, },\nend\n\nlemma not_banned_litter_nonempty : nonempty {L | \u00acw.banned_litter L} :=\nby simp only [\u2190 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 : \u00acw.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 \u2206 (w.atom_map_or_else '' w.atom_map.dom) : set atom) \u2264\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 \u03ba_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 \u222a 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 \u27e8ha\u2081, ha\u2082\u27e9,\n  rw mem_litter_set at ha\u2082,\n  have hnb := w.sandbox_litter_not_banned,\n  rw \u2190 ha\u2082 at hnb,\n  cases ha\u2081,\n  { exact hnb (banned_litter.atom_dom a ha\u2081), },\n  { refine hnb _,\n    simp only [mem_image, pfun.mem_dom] at ha\u2081,\n    obtain \u27e8b, \u27e8_, hb, rfl\u27e9, rfl\u27e9 := ha\u2081,\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\u27e8(w.litter_map_or_else N.fst).fst,\n  w.litter_map_or_else N.fst \u2206 (w.atom_map_or_else '' litter_set N.fst \u2206 N),\n  begin\n    rw [is_near_litter, is_near, \u2190 symm_diff_assoc],\n    exact (w.litter_map_or_else N.fst).snd.prop.symm_diff (small.image N.2.prop),\n  end\u27e9\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) \u2206 litter_set ((w.litter_map L).get hL).1 \u2286\n  w.atom_map.ran)\n(fwd : \u2200 a ha, (w.atom_map a).get ha \u2208 litter_set L \u2192 (w.atom_map ((w.atom_map a).get ha)).dom)\n(back : w.atom_map.dom \u2229 (w.litter_map L).get hL \u2286 w.atom_map.ran)\n\n/-- A weak approximation is precise if it is precise at every litter in its domain. -/\ndef precise : Prop := \u2200 \u2983L\u2984 (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  #\u21a5(w.litter_map.dom \u2206 (w.rough_litter_map_or_else '' w.litter_map.dom)) \u2264\n  #{L : litter | \u00acw.banned_litter L} :=\nbegin\n  rw mk_not_banned_litter,\n  refine le_trans (le_of_lt _) \u03ba_le_\u03bc,\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 : \u2135\u2080 \u2264 #{L | \u00acw.banned_litter L} :=\nbegin\n  rw mk_not_banned_litter,\n  exact \u03bc_strong_limit.is_limit.aleph_0_le,\nend\n\nlemma disjoint_dom_not_banned_litter :\n  disjoint (w.litter_map.dom \u222a w.rough_litter_map_or_else '' w.litter_map.dom)\n    {L : litter | \u00acw.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 _ (\u27e8_, hL, rfl\u27e9 | \u27e8L, \u27e8_, hL, rfl\u27e9, rfl\u27e9),\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\u2081 hL\u2081 L\u2082 hL\u2082 h,\n  rw [w.rough_litter_map_or_else_of_dom hL\u2081, w.rough_litter_map_or_else_of_dom hL\u2082] at h,\n  exact w.litter_map_injective hL\u2081 hL\u2082 (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 | \u00acw.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' := \u03bb L h, h,\n  inv_fun_domain' := \u03bb L h, h,\n  left_inv' := \u03bb L h, rfl,\n  right_inv' := \u03bb 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 \u2190 set.subset_compl_iff_disjoint_left; exact \u03bb L h, h.2)\n\nlemma litter_perm'_apply_eq (L : litter) (hL : L \u2208 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 \u2208 w.litter_map.dom) :\n  w.litter_perm L = w.rough_litter_map_or_else L :=\nbegin\n  rw \u2190 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 \u03ba_regular.aleph_0_le _ _;\n    refine (mul_lt_of_lt \u03ba_regular.aleph_0_le (lt_of_le_of_lt \u039b_limit.aleph_0_le \u039b_lt_\u03ba) _);\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 {\u03b1 : \u039b} [position_data.{}] [phase_2_assumptions \u03b1] {\u03b2 : Iio \u03b1} {A : extended_index \u03b2}\n\nlemma mk_not_banned_litter_and_flexible : #{L | \u00acw.banned_litter L \u2227 flexible \u03b1 L A} = #\u03bc :=\nbegin\n  refine le_antisymm ((mk_subtype_le _).trans mk_litter.le) _,\n  by_contra,\n  rw not_le at h,\n  have h\u2081 := cardinal.le_mk_diff_add_mk {L | flexible \u03b1 L A} {L | w.banned_litter L},\n  rw [mk_flexible, diff_eq, inter_comm] at h\u2081,\n  have h\u2082 := add_lt_of_lt \u03bc_strong_limit.is_limit.aleph_0_le h\n    (lt_trans w.banned_litter_small \u03ba_lt_\u03bc),\n  exact h\u2081.not_lt h\u2082,\nend\n\nlemma mk_dom_inter_flexible_symm_diff_le :\n  #\u21a5((w.litter_map.dom \u2229 {L | flexible \u03b1 L A}) \u2206\n    (w.rough_litter_map_or_else '' (w.litter_map.dom \u2229 {L | flexible \u03b1 L A}))) \u2264\n  #{L : litter | \u00acw.banned_litter L \u2227 flexible \u03b1 L A} :=\nbegin\n  rw mk_not_banned_litter_and_flexible,\n  refine le_trans (le_of_lt _) \u03ba_le_\u03bc,\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 : \u2135\u2080 \u2264 #{L | \u00acw.banned_litter L \u2227 flexible \u03b1 L A} :=\nbegin\n  rw mk_not_banned_litter_and_flexible,\n  exact \u03bc_strong_limit.is_limit.aleph_0_le,\nend\n\nlemma disjoint_dom_inter_flexible_not_banned_litter :\n  disjoint ((w.litter_map.dom \u2229 {L | flexible \u03b1 L A})\n    \u222a w.rough_litter_map_or_else '' (w.litter_map.dom \u2229 {L | flexible \u03b1 L A}))\n    {L : litter | \u00acw.banned_litter L \u2227 flexible \u03b1 L A} :=\nbegin\n  refine disjoint_of_subset _ (inter_subset_left _ _) w.disjoint_dom_not_banned_litter,\n  rintros a (ha | \u27e8b, hb, rfl\u27e9),\n  exact or.inl ha.1,\n  exact or.inr \u27e8b, hb.1, rfl\u27e9,\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 \u2229 {L | flexible \u03b1 L A}) :=\nw.rough_litter_map_or_else_inj_on.mono (inter_subset_left _ _)\n\nnoncomputable def flexible_litter_perm (A : extended_index \u03b2) :\n  local_perm litter :=\nlocal_perm.complete\n  w.rough_litter_map_or_else\n  (w.litter_map.dom \u2229 {L | flexible \u03b1 L A})\n  {L | \u00acw.banned_litter L \u2227 flexible \u03b1 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\u2081 : L \u2208 w.litter_map.dom) (hL\u2082 : flexible \u03b1 L A) :\n  w.flexible_litter_perm A L = w.rough_litter_map_or_else L :=\nlocal_perm.complete_apply_eq _ _ _ \u27e8hL\u2081, hL\u2082\u27e9\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 \u03ba_regular.aleph_0_le _ _;\n      refine (mul_lt_of_lt \u03ba_regular.aleph_0_le (lt_of_le_of_lt \u039b_limit.aleph_0_le \u039b_lt_\u03ba) _);\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 \u03ba_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 \u03ba_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 \u03ba_regular.aleph_0_le _ _;\n    refine (mul_lt_of_lt \u03ba_regular.aleph_0_le (lt_of_le_of_lt \u039b_limit.aleph_0_le \u039b_lt_\u03ba) _);\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 \u03b2) : near_litter_approx := {\n  atom_perm := w.complete_atom_perm,\n  litter_perm := w.flexible_litter_perm A,\n  domain_small := \u03bb 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 \u2022 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 \u2022 L = w.flexible_litter_perm A L := rfl\n\nlemma smul_atom_eq\n  {\u03c0 : near_litter_perm} (h\u03c0 : (w.complete A).exactly_approximates \u03c0)\n  {a : atom} (ha : (w.atom_map a).dom) :\n  \u03c0 \u2022 a = (w.atom_map a).get ha :=\nby rw [\u2190 h\u03c0.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  {\u03c0 : near_litter_perm} (h\u03c0 : (w.complete A).exactly_approximates \u03c0)\n  {L : litter} (hL : (w.litter_map L).dom) (hw : w.precise_at hL)\n  (h\u03c0L : \u03c0 \u2022 L = ((w.litter_map L).get hL).1) :\n  \u03c0 \u2022 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 \u03c0.is_exception a,\n    { suffices h' : \u03c0\u207b\u00b9 \u2022 a \u2208 w.atom_map.dom,\n      { rw w.atom_mem _ h' L hL at ha,\n        have := h\u03c0.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 \u2190 h\u03c0.symm_map_atom a (h\u03c0.exception_mem _ h) at ha \u22a2,\n      obtain ((hdom | hdom) | hdom) := (w.complete A).atom_perm.symm.map_domain\n        (h\u03c0.exception_mem _ h),\n      { exact hdom, },\n      { obtain \u27e8c, hc\u2081, hc\u2082\u27e9 := hdom,\n        rw w.atom_map_or_else_of_dom hc\u2081 at hc\u2082,\n        have := hw.fwd c hc\u2081 (by rwa hc\u2082),\n        rw hc\u2082 at this,\n        exact this, },\n      { cases w.sandbox_litter_not_banned _,\n        rw \u2190 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 \u27e8b, hb, rfl\u27e9 := hw.diff\n        (or.inr \u27e8by rw [\u2190 h\u03c0L, h.2, smul_inv_smul, mem_litter_set], h'\u27e9),\n      refine h' ((w.atom_mem b hb L hL).mp _),\n      have := h\u03c0.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 \u03c0\u207b\u00b9 \u2022 a \u2208 w.atom_map.dom,\n    { rw w.atom_mem _ h L hL,\n      have := h\u03c0.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 \u2208 litter_set ((w.litter_map L).get hL).fst,\n    { by_contradiction h',\n      obtain \u27e8b, hb, rfl\u27e9 := hw.diff (or.inl \u27e8ha, h'\u27e9),\n      have := h\u03c0.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 : \u03c0.is_exception a,\n    { refine or.inr (\u03bb h'', h' (h''.trans _)),\n      rw [inv_smul_eq_iff, h\u03c0L],\n      exact haL, },\n    obtain ((hdom | \u27e8b, hb\u2081, hb\u2082\u27e9) | hdom) := h\u03c0.exception_mem a hex,\n    { obtain \u27e8b, hb\u2081, hb\u2082\u27e9 := hw.back \u27e8hdom, ha\u27e9,\n      have := h\u03c0.map_atom b (or.inl (or.inl hb\u2081)),\n      rw [w.complete_smul_atom_eq hb\u2081] at this,\n      rw [this, smul_eq_iff_eq_inv_smul] at hb\u2082,\n      rw hb\u2082 at hb\u2081,\n      exact h hb\u2081, },\n    { rw w.atom_map_or_else_of_dom hb\u2081 at hb\u2082,\n      have := h\u03c0.map_atom b (or.inl (or.inl hb\u2081)),\n      rw [w.complete_smul_atom_eq hb\u2081, hb\u2082, \u2190 inv_smul_eq_iff] at this,\n      rw this at h,\n      exact h hb\u2081, },\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  {\u03c0 : near_litter_perm} (h\u03c0 : (w.complete A).exactly_approximates \u03c0)\n  {N : near_litter} (hN : (w.litter_map N.1).dom) (hw : w.precise_at hN)\n  (h\u03c0L : \u03c0 \u2022 N.1 = ((w.litter_map N.1).get hN).1) :\n  ((\u03c0 \u2022 N : near_litter) : set atom) = (w.litter_map N.1).get hN \u2206 (\u03c0 \u2022 (litter_set N.1 \u2206 N)) :=\nbegin\n  refine (near_litter_perm.smul_near_litter_eq_smul_symm_diff_smul _ _).trans _,\n  rw \u2190 w.smul_to_near_litter_eq_of_precise_at h\u03c0 hN hw h\u03c0L,\n  refl,\nend\n\nend weak_near_litter_approx\n\nnamespace weak_struct_approx\n\nsection\n\ndef precise {\u03b2 : type_index} (w : weak_struct_approx \u03b2) : Prop := \u2200 B, (w B).precise\n\nvariables {\u03b1 : \u039b} [position_data.{}] [phase_2_assumptions \u03b1] {\u03b2 : Iio \u03b1} (w : weak_struct_approx \u03b2)\n\nnoncomputable def complete : struct_approx \u03b2 :=\n\u03bb B, (w B).complete B\n\nlemma smul_atom_eq\n  {\u03c0 : struct_perm \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0)\n  {a : atom} {B : extended_index \u03b2} (ha : ((w B).atom_map a).dom) :\n  struct_perm.derivative B \u03c0 \u2022 a = ((w B).atom_map a).get ha :=\nbegin\n  have := (w B).smul_atom_eq (h\u03c0 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  {\u03c0 : struct_perm \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0)\n  {L : litter} {B : extended_index \u03b2} (hL : ((w B).litter_map L).dom)\n  (h\u03c0L : struct_perm.derivative B \u03c0 \u2022 L = (((w B).litter_map L).get hL).1) :\n  struct_perm.derivative B \u03c0 \u2022 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\u03c0 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\u03c0L, },\nend\n\nlemma smul_near_litter_eq_of_precise (hw : w.precise)\n  {\u03c0 : struct_perm \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0)\n  {N : near_litter} {B : extended_index \u03b2} (hN : ((w B).litter_map N.1).dom)\n  (h\u03c0L : struct_perm.derivative B \u03c0 \u2022 N.1 = (((w B).litter_map N.1).get hN).1) :\n  ((struct_perm.derivative B \u03c0 \u2022 N : near_litter) : set atom) =\n  ((w B).litter_map N.1).get hN \u2206 (struct_perm.derivative B \u03c0 \u2022 (litter_set N.1 \u2206 N)) :=\nbegin\n  have := (w B).smul_near_litter_eq_of_precise_at (h\u03c0 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\u03c0L, },\nend\n\nend\n\nvariables {\u03b1 : \u039b} [position_data.{}] [phase_2_assumptions \u03b1] {\u03b2 : Iio \u03b1}\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 \u03b2) (t : tangle \u03b2) : Prop :=\n(atom_mem : \u2200 a B, (inl a, B) \u2208 reduction \u03b1 (designated_support t : set (support_condition \u03b2)) \u2192\n  ((w B).atom_map a).dom)\n(litter_mem : \u2200 (L : litter) B,\n  (inr L.to_near_litter, B) \u2208 reduction \u03b1 (designated_support t : set (support_condition \u03b2)) \u2192\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 \u03b2) (t : tangle \u03b2) : Prop :=\n(w_supports : w.supports t)\n(v_supports : v.supports t)\n(atom_map : \u2200 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 : \u2200 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 \u03b2) :\n  support_condition \u03b2 \u2192 support_condition \u03b2\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 \u03b2) (t : tangle \u03b2) : Prop :=\n\u2200 {\u03c0 : allowable \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0.to_struct_perm)\n  (\u03b3 : Iic \u03b1) (\u03b4 \u03b5 : Iio \u03b1) (h\u03b4 : (\u03b4 : \u039b) < \u03b3) (h\u03b5 : (\u03b5 : \u039b) < \u03b3) (h\u03b4\u03b5 : \u03b4 \u2260 \u03b5)\n  (C : path (\u03b2 : type_index) \u03b3) (t' : tangle \u03b4) (hL)\n  (hc\u2081 : \u2203 (d : support_condition \u03b2), d \u2208 (designated_support t).carrier \u2227\n    relation.refl_trans_gen (constrains \u03b1 \u03b2)\n    (inr (f_map (coe_ne_coe.mpr (coe_ne' h\u03b4\u03b5)) t').to_near_litter,\n      (C.cons (coe_lt h\u03b5)).cons (bot_lt_coe _)) d)\n  (hc\u2082 : \u2200 (c : support_condition \u03b4), c \u2208 (designated_support t').carrier \u2192\n    \u03c0 \u2022 (show support_condition \u03b2, from (c.fst, (C.cons (coe_lt h\u03b4)).comp c.snd)) =\n      w.support_condition_map_or_else (c.fst, (C.cons (coe_lt h\u03b4)).comp c.snd)),\n  f_map (subtype.coe_injective.ne (Iio.coe_injective.ne h\u03b4\u03b5))\n      (show tangle \u03b4, from\n        (show allowable \u03b4, from allowable_derivative (\u03b3 : Iic_index \u03b1) \u03b4 (coe_lt_coe.mpr h\u03b4)\n          (allowable.derivative\n            (show path ((\u03b2 : Iic_index \u03b1) : type_index) (\u03b3 : Iic_index \u03b1), from C) \u03c0)) \u2022 t') =\n    (((w ((C.cons (coe_lt h\u03b5)).cons (bot_lt_coe _))).litter_map\n      (f_map (subtype.coe_injective.ne (Iio.coe_injective.ne h\u03b4\u03b5)) t')).get hL).fst\n\ndef coherent_bot (w : weak_struct_approx \u03b2) : Prop :=\n\u2200 {\u03c0 : allowable \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0.to_struct_perm)\n  (\u03b3 : Iic \u03b1) (\u03b5 : Iio \u03b1) (h\u03b5 : (\u03b5 : \u039b) < \u03b3)\n  (C : path (\u03b2 : type_index) \u03b3) (a : tangle \u22a5) (hL)\n  (hc : struct_perm.derivative (C.cons (bot_lt_coe _)) \u03c0.to_struct_perm \u2022 a =\n    (w (C.cons (bot_lt_coe _))).atom_map_or_else a),\n  f_map (show ((\u22a5 : Iio_index \u03b1) : type_index) \u2260 (\u03b5 : Iio_index \u03b1),\n    from subtype.coe_injective.ne Iio_index.bot_ne_coe)\n      ((struct_perm.derivative (C.cons (bot_lt_coe _))) \u03c0.to_struct_perm \u2022 a) =\n    (((w ((C.cons (coe_lt h\u03b5)).cons (bot_lt_coe _))).litter_map\n      (f_map (show (\u22a5 : type_index) \u2260 (\u03b5 : \u039b), from bot_ne_coe) a)).get hL).fst\n\n@[mk_iff] structure coherent (w : weak_struct_approx \u03b2) (t : tangle \u03b2) : Prop :=\n(coe : w.coherent_coe t)\n(bot : w.coherent_bot)\n\nlemma smul_litter_eq_of_supports (w : weak_struct_approx \u03b2)\n  {\u03c0 : allowable \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0.to_struct_perm)\n  (t : tangle \u03b2) (hwc : w.coherent t) (hws : w.supports t)\n  (d : support_condition \u03b2) (hd : d \u2208 designated_support t)\n  (B : extended_index \u03b2) (L : litter)\n  (ih : \u2200 (e : support_condition \u03b2),\n    relation.trans_gen (constrains \u03b1 \u03b2) e (inr L.to_near_litter, B) \u2192\n    \u03c0 \u2022 e = w.support_condition_map_or_else e)\n  (hc : relation.refl_trans_gen (constrains \u03b1 \u03b2) (inr L.to_near_litter, B) d) :\n  struct_perm.derivative B \u03c0.to_struct_perm \u2022 L =\n  (((w B).litter_map L).get\n    (hws.litter_mem L B \u27e8\u27e8d, hd, refl_trans_gen_near_litter hc\u27e9, reduced.mk_litter _ _\u27e9)).fst :=\nbegin\n  by_cases hflex : inflexible \u03b1 L B,\n  rw inflexible_iff at hflex,\n  obtain (\u27e8\u03b3, \u03b4, \u03b5, h\u03b4, h\u03b5, h\u03b4\u03b5, C, t', rfl, rfl\u27e9 | \u27e8\u03b3, \u03b5, h\u03b5, C, a, rfl, rfl\u27e9) := hflex,\n  { have hc\u2082 := \u03bb c hc, ih _ (relation.trans_gen.single $ constrains.f_map h\u03b4 h\u03b5 h\u03b4\u03b5 C t' c hc),\n    have := smul_f_map (\u03b4 : Iio_index \u03b1) \u03b5 _ _ (Iio.coe_injective.ne h\u03b4\u03b5)\n      (allowable.derivative\n        (show path ((\u03b2 : Iic_index \u03b1) : type_index) (\u03b3 : Iic_index \u03b1), from C) \u03c0) t',\n    rw [\u2190 allowable.derivative_cons_apply, allowable.derivative_smul,\n      \u2190 struct_perm.derivative_bot_smul, \u2190 struct_perm.derivative_cons] at this,\n    exact this.trans (hwc.coe h\u03c0 \u03b3 \u03b4 \u03b5 h\u03b4 h\u03b5 h\u03b4\u03b5 C t' _ \u27e8d, hd, hc\u27e9 hc\u2082), },\n  { have hc : (_, _) = (_, _) := ih _ (relation.trans_gen.single $ constrains.f_map_bot h\u03b5 C a),\n    simp only [smul_inl, prod.mk.inj_iff, eq_self_iff_true, and_true] at hc,\n    have := smul_f_map (\u22a5 : Iio_index \u03b1) \u03b5 _ _ _\n      (allowable.derivative\n        (show path ((\u03b2 : Iic_index \u03b1) : type_index) (\u03b3 : Iic_index \u03b1), from C) \u03c0) a,\n    rw [\u2190 allowable.derivative_cons_apply, allowable.derivative_smul,\n      \u2190 struct_perm.derivative_bot_smul, \u2190 struct_perm.derivative_cons] at this,\n    rw \u2190 hwc.bot h\u03c0 \u03b3 \u03b5 h\u03b5 C a _ hc,\n    refine this.trans _,\n    swap 3,\n    refine congr_arg _ _,\n    swap 3,\n    { rw \u2190 allowable.derivative_cons_apply,\n      rw \u2190 allowable.derivative_smul\n        (show path ((\u03b2 : Iic_index \u03b1) : type_index) ((\u22a5 : Iic_index \u03b1) : type_index),\n          from C.cons (bot_lt_coe _)) \u03c0 a,\n      congr,\n      sorry, },\n    all_goals { sorry, }, },\n  { have := hws.litter_mem L B \u27e8\u27e8d, hd, refl_trans_gen_near_litter hc\u27e9, reduced.mk_litter _ _\u27e9,\n    rw [\u2190 struct_perm.of_bot_smul, \u2190 (h\u03c0 B).map_litter _ (or.inl (or.inl \u27e8this, hflex\u27e9))],\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 \u03b2) (hw : w.precise)\n  {\u03c0 : allowable \u03b2} (h\u03c0 : w.complete.exactly_approximates \u03c0.to_struct_perm)\n  (t : tangle \u03b2) (hwc : w.coherent t) (hws : w.supports t)\n  (c d : support_condition \u03b2)\n  (hc : relation.refl_trans_gen (constrains \u03b1 \u03b2) c d)\n  (hd : d \u2208 designated_support t) :\n  \u03c0 \u2022 c = w.support_condition_map_or_else c :=\nbegin\n  revert d,\n  refine (constrains_wf \u03b1 \u03b2).trans_gen.induction c _,\n  rintros c ih d hc hd,\n  obtain \u27e8a | N, B\u27e9 := c,\n  { refine prod.ext _ rfl,\n    change inl _ = inl _,\n    refine congr_arg inl _,\n    rw [w.smul_atom_eq h\u03c0 (hws.atom_mem a B \u27e8\u27e8d, hd, hc\u27e9, reduced.mk_atom a B\u27e9),\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' := \u03bb 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\u03c0 (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 \u27e8b, hb\u2081, hb\u2082\u27e9,\n      have : (_, _) = (_, _) := ih' _ (constrains.symm_diff N _ hb\u2081 B),\n      simp only [smul_inl, smul_inv_smul, prod.mk.inj_iff] at this,\n      rw this.1 at hb\u2082,\n      exact \u27e8b, hb\u2081, hb\u2082\u27e9, },\n    { rintro \u27e8b, hb\u2081, hb\u2082\u27e9,\n      have : (_, _) = (_, _) := ih' _ (constrains.symm_diff N _ hb\u2081 B),\n      simp only [smul_inl, smul_inv_smul, prod.mk.inj_iff] at this,\n      rw \u2190 this.1 at hb\u2082,\n      exact \u27e8b, hb\u2081, hb\u2082\u27e9, },\n    { exact \u27e8\u27e8d, hd, refl_trans_gen_near_litter hc\u27e9, reduced.mk_litter _ _\u27e9, }, },\n  refine w.smul_litter_eq_of_supports h\u03c0 t hwc hws d hd B N.1 _ (refl_trans_gen_near_litter hc),\n  exact \u03bb 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 \u03b2)\n  (hw : w.precise) (hv : v.precise)\n  (t : tangle \u03b2) (h : compatible w v t)\n  (hwc : w.coherent t) (hvc : v.coherent t)\n  {\u03c0w \u03c0v : allowable \u03b2} (h\u03c0w : w.complete.exactly_approximates \u03c0w.to_struct_perm)\n  (h\u03c0v : v.complete.exactly_approximates \u03c0v.to_struct_perm) :\n  \u03c0w \u2022 t = \u03c0v \u2022 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\u03c0w t hwc h.w_supports c c relation.refl_trans_gen.refl hc,\n  rw smul_support_condition_eq v hv h\u03c0v t hvc h.v_supports c c relation.refl_trans_gen.refl hc,\n  obtain \u27e8a | N, B\u27e9 := 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 \u27e8\u27e8_, hc, relation.refl_trans_gen.refl\u27e9, reduced.mk_atom _ _\u27e9, },\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 \u27e8\u27e8_, hc, refl_trans_gen_near_litter relation.refl_trans_gen.refl\u27e9,\n        reduced.mk_litter _ _\u27e9, },\n    { ext a : 1,\n      rw [mem_image, mem_image],\n      split;\n      rintro \u27e8b, hb\u2081, hb\u2082\u27e9;\n      refine \u27e8b, hb\u2081, _\u27e9;\n      rw [\u2190 hb\u2082, (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 \u27e8\u27e8_, hc, relation.refl_trans_gen.single (constrains.symm_diff N b hb\u2081 B)\u27e9,\n          reduced.mk_atom _ _\u27e9, },\n      { refine h.atom_map b B _,\n        exact \u27e8\u27e8_, hc, relation.refl_trans_gen.single (constrains.symm_diff N b hb\u2081 B)\u27e9,\n          reduced.mk_atom _ _\u27e9, }, }, },\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 {\u03b1 : Type} {s : Bool} [BEq \u03b1] (d : DiscrTree \u03b1 s)\n    (keys : Array (DiscrTree.Key s)) (v : \u03b1) : DiscrTree \u03b1 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 \u2190 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 \u00d7 DeclMod) true) \u2190\n  DeclCache.mk \"librarySearch: init cache\" {} fun name constInfo lemmas => do\n    if constInfo.isUnsafe then return lemmas\n    if \u2190 isBlackListed name then return lemmas\n    withNewMCtxDepth do withReducible do\n      let (_, _, type) \u2190 forallMetaTelescopeReducing constInfo.type\n      let keys \u2190 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 \u2190 DiscrTree.mkPath (\u2190 mkEq rhs lhs)\n        pure (lemmas.insertIfSpecific keys_symm (name, .symm))\n      | (``Iff, #[lhs, rhs]) => do\n        let keys_mp \u2190 DiscrTree.mkPath rhs\n        let keys_mpr \u2190 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  _ \u2190 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 \u00d7 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 \u00d7 DeclMod) s) (required : List Expr)\n    (solveByElimDepth := 6) : MetaM <| Option (Array <| MetavarContext \u00d7 List MVarId) := do\n  profileitM Exception \"librarySearch\" (\u2190 getOptions) do\n  let ty \u2190 goal.getType\n  withTraceNode `Tactic.librarySearch (return m!\"{exceptOptionEmoji \u00b7} {ty}\") do\n\n  let mut suggestions := #[]\n\n  let state0 \u2190 get\n\n  try\n    solveByElim [goal] required solveByElimDepth\n    return none\n  catch _ =>\n    set state0\n\n  for (lem, mod) in \u2190 lemmas.getMatch ty do\n    trace[Tactic.librarySearch] \"{lem}\"\n    let result \u2190 withTraceNode `Tactic.librarySearch (return m!\"{exceptOptionEmoji \u00b7} trying {lem}\")\n      try\n        let lem \u2190 mkConstWithFreshMVarLevels lem\n        let lem \u2190 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 \u2190 goal.apply lem\n        (try\n          for newGoal in newGoals do\n            trace[Tactic.librarySearch] \"proving {\u2190 addMessageContextFull (mkMVar newGoal)}\"\n          solveByElim newGoals required solveByElimDepth\n          pure $ some $ Sum.inr ()\n        catch _ =>\n          let res := some $ Sum.inl (\u2190 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 \u2190 getMainGoal\n  let (_, goal) \u2190 (\u2190 getMainGoal).intros\n  goal.withContext do\n    let required := (\u2190 (required.getD #[]).mapM getFVarId).toList.map .fvar\n    if let some suggestions \u2190 librarySearch goal (\u2190 librarySearchLemmas.get) required then\n      for suggestion in suggestions do\n        withMCtx suggestion.1 do\n          addExactSuggestion tk (\u2190 instantiateMVars (mkMVar mvar)).headBeta\n      admitGoal goal\n    else\n      addExactSuggestion tk (\u2190 instantiateMVars (mkMVar mvar)).headBeta\n\nopen Elab Term in\nelab tk:\"library_search%\" : term <= expectedType => do\n  let goal \u2190 mkFreshExprMVar expectedType\n  let (_, introdGoal) \u2190 goal.mvarId!.intros\n  introdGoal.withContext do\n    if let some suggestions \u2190 librarySearch introdGoal (\u2190 librarySearchLemmas.get) [] then\n      for suggestion in suggestions do\n        withMCtx suggestion.1 do\n          addTermSuggestion tk (\u2190 instantiateMVars goal).headBeta\n      mkSorry expectedType (synthetic := true)\n    else\n      addTermSuggestion tk (\u2190 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 {\u03b1 : Type u} (encode : \u03b1 \u2192 put_m) (decode : get_m \u03b1) : Prop :=\n\u2200 w, decode -<< encode w = pure w\n\nclass serial (\u03b1 : Type u) :=\n  (encode : \u03b1 \u2192 put_m)\n  (decode : get_m \u03b1)\n  (correctness : \u2200 w, decode -<< encode w = pure w)\n\nclass serial1 (f : Type u \u2192 Type v) :=\n  (encode : \u03a0 {\u03b1}, (\u03b1 \u2192 put_m) \u2192 f \u03b1 \u2192 put_m)\n  (decode : \u03a0 {\u03b1}, get_m \u03b1 \u2192 get_m (f \u03b1))\n  (correctness : \u2200 {\u03b1} put get, serial_inverse.{u} put get \u2192\n                 \u2200 (w : f \u03b1), decode get -<< encode put w = pure w)\n\ninstance serial.serial1 {f \u03b1} [serial1 f] [serial \u03b1] : serial (f \u03b1) :=\n{ encode := \u03bb x, serial1.encode serial.encode x,\n  decode := serial1.decode f (serial.decode \u03b1),\n  correctness := serial1.correctness _ _ serial.correctness }\n\nclass serial2 (f : Type u \u2192 Type v \u2192 Type w) :=\n  (encode : \u03a0 {\u03b1 \u03b2}, (\u03b1 \u2192 put_m.{u}) \u2192 (\u03b2 \u2192 put_m.{v}) \u2192 f \u03b1 \u03b2 \u2192 put_m.{w})\n  (decode : \u03a0 {\u03b1 \u03b2}, get_m \u03b1 \u2192 get_m \u03b2 \u2192 get_m (f \u03b1 \u03b2))\n  (correctness : \u2200 {\u03b1 \u03b2} put\u03b1 get\u03b1 put\u03b2 get\u03b2,\n                   serial_inverse put\u03b1 get\u03b1 \u2192\n                   serial_inverse put\u03b2 get\u03b2 \u2192\n                 \u2200 (w : f \u03b1 \u03b2), decode get\u03b1 get\u03b2 -<< encode put\u03b1 put\u03b2 w = pure w)\n\ninstance serial.serial2 {f \u03b1 \u03b2} [serial2 f] [serial \u03b1] [serial \u03b2] : serial (f \u03b1 \u03b2) :=\n{ encode := \u03bb 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 \u03b1} [serial2 f] [serial \u03b1] : serial1 (f \u03b1) :=\n{ encode := \u03bb \u03b2 put x, serial2.encode serial.encode put x,\n  decode := \u03bb \u03b2 get, serial2.decode f (serial.decode _) get,\n  correctness := \u03bb \u03b2 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 {\u03b1 \u03b2 \u03c3 \u03b3 : Type u} {\u03c9 : Type}\n\ndef serialize [serial \u03b1] (x : \u03b1) : list unsigned := (encode x).eval\ndef deserialize (\u03b1 : Type u) [serial \u03b1] (bytes : list unsigned) : option \u03b1 := (decode \u03b1).eval bytes\n\nlemma deserialize_serialize  [serial \u03b1] (x : \u03b1) :\n  deserialize _ (serialize x) = some x :=\nby simp [deserialize,serialize,eval_eval,serial.correctness]; refl\n\nlemma encode_decode_bind [serial \u03b1]\n  (f : \u03b1 \u2192 get_m \u03b2) (f' : punit \u2192 put_m) (w : \u03b1) :\n  (decode \u03b1 >>= f) -<< (encode w >>= f') = f w -<< f' punit.star :=\nby { rw [read_write_mono]; rw serial.correctness; refl }\n\nlemma encode_decode_bind' [serial \u03b1]\n  (f : \u03b1 \u2192 get_m \u03b2) (w : \u03b1) :\n  (decode \u03b1 >>= 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' : \u03b1) (u : punit) :\n  (pure w : get_m \u03b1) -<< (pure u) = pure w' \u2194 w = w' :=\nby split; intro h; cases h; refl\n\nopen ulift\n\nprotected def ulift.encode [serial \u03b1] (w : ulift.{v} \u03b1) : 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 \u03b1] : get_m (ulift \u03b1) :=\nget_m.up ulift.up (decode \u03b1)\n\ninstance [serial \u03b1] : serial (ulift.{v u} \u03b1) :=\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 := \u03bb 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 {\u03b1 \u03b2 \u03b3 : Type u}\n  (w : unsigned) (x : \u03b1) (f : \u03b1 \u2192 unsigned \u2192 get_m (\u03b2 \u2295 \u03b1)) (g : \u03b2 \u2192 get_m \u03b3)\n  (rest : punit \u2192 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' {\u03b1 \u03b2 \u03b3 : Type u}\n  (w : unsigned) (x : \u03b1) (f : \u03b1 \u2192 unsigned \u2192 get_m (\u03b2 \u2295 \u03b1)) (g : \u03b2 \u2192 get_m \u03b3)  :\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 \u00d7 get_m \u03b1) \u2192 get_m \u03b1\n| [] := get_m.fail\n| ((w,x) :: xs) := if w = tag then x else select_tag' xs\n\ndef select_tag (xs : list (unsigned \u00d7 get_m \u03b1)) : get_m \u03b1 :=\ndo w \u2190 read_word,\n   select_tag' (down w) xs\n\n@[simp]\nlemma read_write_tag_hit {w w' : unsigned} {x : get_m \u03b1}\n  {xs : list (unsigned \u00d7 get_m \u03b1)} {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 \u03b1}\n  {xs : list (unsigned \u00d7 get_m \u03b1)}\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 \u03b1}\n  {xs : list (unsigned \u00d7 get_m \u03b1)} {y : put_m}\n  (h : w \u2260 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 {\u03b1} : \u2115 \u2192 (get_m \u03b1 \u2192 get_m \u03b1) \u2192 get_m \u03b1\n| 0 _ := get_m.fail\n| (nat.succ n) rec_fn := rec_fn $ recursive_parser n rec_fn\n\nlemma recursive_parser_unfold {\u03b1} (n : \u2115) (f : get_m \u03b1 \u2192 get_m \u03b1) (h : 1 \u2264 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 (\u03b1 : Type u) (\u03b2 : Type u) :=\n(encoder : \u03b1 \u2192 put_m.{u})\n(decoder : get_m \u03b2)\n\ndef serial.mk_serializer' (\u03b1) [serial \u03b1] : serializer \u03b1 \u03b1 :=\n{ encoder := encode,\n  decoder := decode \u03b1 }\n\nnamespace serializer\n\ndef valid_serializer {\u03b1} (x : serializer \u03b1 \u03b1) :=\nserial_inverse\n      (serializer.encoder x)\n      (serializer.decoder x)\n\nlemma serializer.eq {\u03b1 \u03b2} (x y : serializer \u03b1 \u03b2)\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 {\u03b1 : Type u} {i j : Type u}\nvariables (x : serializer \u03b1 (i \u2192 j))\nvariables (y : serializer \u03b1 i)\n\ndef encoder := \u03bb (k : \u03b1), (x.encoder k >> y.encoder k : put_m' _)\ndef decoder := x.decoder <*> y.decoder\n\nend serializer.seq\n\ninstance {\u03b1 : Type u} : applicative (serializer.{u} \u03b1) :=\n{ pure := \u03bb i x, { encoder := \u03bb _, (return punit.star : put_m' _), decoder := pure x }\n, seq := \u03bb i j x y,\n  { encoder := serializer.seq.encoder x y\n  , decoder := serializer.seq.decoder x y } }\n\nsection lawful_applicative\n\nvariables {\u03b1 \u03b2 : Type u} {\u03c3 : Type u}\n\n@[simp]\nlemma decoder_pure (x : \u03b2) :\n  (pure x : serializer \u03c3 \u03b2).decoder = pure x := rfl\n\n@[simp]\nlemma decoder_map (f : \u03b1 \u2192 \u03b2) (x : serializer \u03c3 \u03b1) :\n  (f <$> x).decoder = f <$> x.decoder := rfl\n\n@[simp]\nlemma decoder_seq (f : serializer \u03c3 (\u03b1 \u2192 \u03b2)) (x : serializer \u03c3 \u03b1) :\n  (f <*> x).decoder = f.decoder <*> x.decoder := rfl\n\n@[simp]\nlemma encoder_pure (x : \u03b2) (w : \u03c3) :\n  (pure x : serializer \u03c3 \u03b2).encoder w = (pure punit.star : put_m' _) := rfl\n\n@[simp]\nlemma encoder_map (f : \u03b1 \u2192 \u03b2) (w : \u03c3) (x : serializer \u03c3 \u03b1) :\n  (f <$> x : serializer \u03c3 \u03b2).encoder w = x.encoder w := rfl\n\n@[simp]\nlemma encoder_seq (f : serializer \u03c3 (\u03b1 \u2192 \u03b2)) (x : serializer \u03c3 \u03b1) (w : \u03c3) :\n  (f <*> x : serializer \u03c3 \u03b2).encoder w = (f.encoder w >> x.encoder w : put_m' _) := rfl\n\nend lawful_applicative\n\ninstance {\u03b1} : is_lawful_functor (serializer.{u} \u03b1) :=\nby refine { .. }; intros; apply serializer.eq; try { ext }; simp [map_map]\n\ninstance {\u03b1} : is_lawful_applicative (serializer.{u} \u03b1) :=\nby{  constructor; intros; apply serializer.eq; try { ext };\n     simp [(>>),pure_seq_eq_map,seq_assoc,bind_assoc],  }\n\nprotected def up {\u03b2} (ser : serializer \u03b2 \u03b2) : serializer (ulift.{u v} \u03b2) (ulift.{u v} \u03b2) :=\n{ encoder := pliftable.up' _ \u2218 ser.encoder \u2218 ulift.down,\n  decoder := medium.get_m.up ulift.up ser.decoder }\n\ndef ser_field_with {\u03b1 \u03b2} (ser : serializer \u03b2 \u03b2) (f : \u03b1 \u2192 \u03b2) : serializer \u03b1 \u03b2 :=\n{ encoder := ser.encoder \u2218 f,\n  decoder := ser.decoder }\n\n@[simp]\ndef ser_field_with' {\u03b1 \u03b2} (ser : serializer \u03b2 \u03b2) (f : \u03b1 \u2192 \u03b2) : serializer.{max u v} \u03b1 (ulift.{v} \u03b2) :=\nser_field_with ser.up (ulift.up \u2218 f)\n\n@[simp]\ndef ser_field {\u03b1 \u03b2} [serial \u03b2] (f : \u03b1 \u2192 \u03b2) : serializer \u03b1 \u03b2 :=\nser_field_with (serial.mk_serializer' \u03b2) f\n\n@[simp]\nlemma valid_mk_serializer (\u03b1) [serial \u03b1] :\n  valid_serializer (serial.mk_serializer' \u03b1) :=\nserial.correctness\n\nvariables {\u03b1 \u03b2 \u03c3 \u03b3 : Type u} {\u03c9 : Type}\n\ndef there_and_back_again\n  (y : serializer \u03b3 \u03b1) (w : \u03b3) : option \u03b1 :=\ny.decoder -<< y.encoder w\n\nopen medium (hiding put_m put_m' get_m)\n\nlemma there_and_back_again_seq {ser : serializer \u03b1 \u03b1}\n  {x : serializer \u03b3 (\u03b1 \u2192 \u03b2)} {f : \u03b1 \u2192 \u03b2} {y : \u03b3 \u2192 \u03b1} {w : \u03b3} {w' : \u03b2}\n  (h' : there_and_back_again x w = pure f)\n  (h : w' = f (y w))\n  (h\u2080 : 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\u2080], subst w', refl }\n\nlemma there_and_back_again_map {ser : serializer \u03b1 \u03b1}\n  {f : \u03b1 \u2192 \u03b2} {y : \u03b3 \u2192 \u03b1} {w : \u03b3}\n  (h\u2080 : valid_serializer ser) :\n  there_and_back_again (f <$> ser_field_with ser y) w = pure (f $ y w) :=\nby rw [\u2190 pure_seq_eq_map,there_and_back_again_seq]; refl <|> assumption\n\nlemma there_and_back_again_pure (x : \u03b2) (w : \u03b3) :\n  there_and_back_again (pure x) w =\n  pure x := rfl\n\nlemma valid_serializer_of_there_and_back_again\n      {\u03b1 : Type*} (y : serializer \u03b1 \u03b1) :\n  valid_serializer y \u2194\n  \u2200 (w : \u03b1), 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 \u03b1 \u03b1) :\n  valid_serializer (serializer.up.{v} x) \u2194 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' {\u03b1 \u03b2} [serial \u03b2] (f : \u03b1 \u2192 \u03b2) : serializer.{max u v} \u03b1 (ulift.{v} \u03b2) :=\nser_field (up \u2218 f)\n\ndef put\u2080 {\u03b1} (x : \u03b1) : put_m.{u} := (pure punit.star : put_m' _)\ndef get\u2080 {\u03b1} : get_m \u03b1 := get_m.fail\n\ndef of_encoder {\u03b1} (x : \u03b1 \u2192 put_m) : serializer \u03b1 \u03b1 :=\n\u27e8 x, get\u2080 \u27e9\n\ndef of_decoder {\u03b1} (x : get_m \u03b1) : serializer \u03b1 \u03b1 :=\n\u27e8 put\u2080, x \u27e9\n\nsection applicative\n\n@[simp]\nlemma encoder_ser_field (f : \u03b2 \u2192 \u03b1) (x : serializer \u03b1 \u03b1) (w : \u03b2) :\n  (ser_field_with x f).encoder w = x.encoder (f w) := rfl\n\n@[simp]\nlemma encoder_up (x : serializer \u03b1 \u03b1) (w : ulift \u03b1) :\n  (serializer.up x).encoder w = pliftable.up' _ (x.encoder $ w.down) := rfl\n\n@[simp]\nlemma encoder_of_encoder (x : \u03b1 \u2192 put_m) (w : \u03b1) :\n  (of_encoder x).encoder w = x w := rfl\n\n@[simp]\nlemma decoder_ser_field (f : \u03b2 \u2192 \u03b1) (x : serializer \u03b1 \u03b1) :\n  (ser_field_with x f).decoder = x.decoder := rfl\n\n@[simp]\nlemma decoder_up (x : serializer \u03b1 \u03b1) :\n  (serializer.up x).decoder = (x.decoder).up ulift.up := rfl\n\n@[simp]\nlemma decoder_of_decoder (x : get_m \u03b1) :\n  (of_decoder x).decoder = x := rfl\n\nend applicative\nend serializer\n\nnamespace serial\n\nopen serializer\n\ndef of_serializer {\u03b1} (s : serializer \u03b1 \u03b1)\n  (h : \u2200 w, there_and_back_again s w = pure w) : serial \u03b1 :=\n{ encode := s.encoder\n, decode := s.decoder\n, correctness := @h }\n\ndef of_serializer\u2081 {f : Type u \u2192 Type v}\n  (s : \u03a0 \u03b1, serializer \u03b1 \u03b1 \u2192 serializer (f \u03b1) (f \u03b1))\n  (h : \u2200 \u03b1 ser, valid_serializer ser \u2192\n       \u2200 w, there_and_back_again (s \u03b1 ser) w = pure w)\n  (h\u2080 : \u2200 {\u03b1} ser w, (s \u03b1 (of_encoder (encoder ser))).encoder w = (s \u03b1 ser).encoder w)\n  (h\u2081 : \u2200 {\u03b1} ser, (s \u03b1 (of_decoder (decoder ser))).decoder = (s \u03b1 ser).decoder) : serial1 f :=\n{ encode := \u03bb \u03b1 put, (s \u03b1 (of_encoder put)).encoder\n, decode := \u03bb \u03b1 get, (s \u03b1 (of_decoder get)).decoder\n, correctness := by { introv hh, simp [h\u2080 \u27e8put, get\u27e9,h\u2081 \u27e8put,get\u27e9], apply h; assumption } }\n\ndef of_serializer\u2082 {f : Type u \u2192 Type v \u2192 Type w}\n  (s : \u03a0 \u03b1 \u03b2, serializer \u03b1 \u03b1 \u2192\n              serializer \u03b2 \u03b2 \u2192\n              serializer (f \u03b1 \u03b2) (f \u03b1 \u03b2))\n  (h : \u2200 \u03b1 \u03b2 ser\u03b1 ser\u03b2, valid_serializer ser\u03b1 \u2192 valid_serializer ser\u03b2 \u2192\n       \u2200 w, there_and_back_again (s \u03b1 \u03b2 ser\u03b1 ser\u03b2) w = pure w)\n  (h\u2080 : \u2200 {\u03b1 \u03b2} ser\u03b1 ser\u03b2 w, (s \u03b1 \u03b2 (of_encoder (encoder ser\u03b1)) (of_encoder (encoder ser\u03b2))).encoder w = (s \u03b1 \u03b2 ser\u03b1 ser\u03b2).encoder w)\n  (h\u2081 : \u2200 {\u03b1 \u03b2} ser\u03b1 ser\u03b2, (s \u03b1 \u03b2 (of_decoder (decoder ser\u03b1)) (of_decoder (decoder ser\u03b2))).decoder = (s \u03b1 \u03b2 ser\u03b1 ser\u03b2).decoder) : serial2 f :=\n{ encode := \u03bb \u03b1 \u03b2 put\u03b1 put\u03b2, (s \u03b1 \u03b2 (of_encoder put\u03b1) (of_encoder put\u03b2)).encoder\n, decode := \u03bb \u03b1 \u03b2 get\u03b1 get\u03b2, (s \u03b1 \u03b2 (of_decoder get\u03b1) (of_decoder get\u03b2)).decoder\n, correctness := by { introv h\u03b1 h\u03b2, simp [h\u2080 \u27e8put\u03b1,get\u03b1\u27e9 \u27e8put\u03b2,get\u03b2\u27e9,h\u2081 \u27e8put\u03b1,get\u03b1\u27e9 \u27e8put\u03b2,get\u03b2\u27e9],\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 \u2190 mk_mvar,\n   refine ``(serial.of_serializer %%p %%g) <|>\n     refine ``(serial.of_serializer\u2081 (\u03bb \u03b1 ser, %%p) %%g _ _) <|>\n     refine ``(serial.of_serializer\u2082 (\u03bb \u03b1 \u03b2 ser_\u03b1 ser_\u03b2, %%p) %%g _ _),\n   gs \u2190 get_goals,\n   set_goals [g],\n   vs \u2190 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' \u2190 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": "/-\nCopyright (c) 2022 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Aesop\n\nexample : True := by\n  aesop (options := { noSuchOption := true })\n\nexample : True := by\n  aesop (simp_options := { noSuchOption := true })\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/golden/ElabConfig.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.051082739304554585, "lm_q1q2_score": 0.020807705884584096}}
{"text": "syntax \"tac\" : tactic\ntheorem a : True := by tac\n#check a -- should be declared\n\ntheorem a' : True \u2227 True := \u27e8by tac, by tac\u27e9\n#check a' -- should be declared\n\nsyntax \"term\" : term\ndef b (n : Nat) : Nat := term\n#print b -- should be declared\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/1301.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.055005293328081274, "lm_q1q2_score": 0.02076673523052197}}
{"text": "\nsyntax:1021 term:1021 \"\u00b7\" term:1022 : term\nmacro_rules\n  | `($a\u00b7$f $args*) => `($f $a $args*)\n  | `($a\u00b7$f)        => `($f $a)\n\nexample [Add a] (x y : a) (f : a \u2192 b) (g : b \u2192 c) (h : c \u2192 a) : a := y + x\u00b7f\u00b7g\u00b7h + x\u00b7id\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 {\u03b1 : Type} [Inhabited \u03b1] {\u03b2 : Type}\n\nprivate def depthFirstTraverseAux (g : Graph \u03b1 \u03b2) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (leave : (Nat -> \u03b3 -> \u03b3 )) (state : \u03b3) (sources : Array Nat) (visited : Array Bool) : Nat -> \u03b3 \u00d7 Bool \u00d7 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 (\u03bb 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 \u03b1 \u03b2) (sources : Array Nat) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (leave : Nat -> \u03b3 -> \u03b3  := (\u03bb _ x => x)) : \u03b3 :=\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 \u03b1 \u03b2) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (leave : Nat -> \u03b3 -> \u03b3  := (\u03bb _ x => x)) : \u03b3 :=\n  g.depthFirstTraverse g.getAllVertexIDs startingState visit leave\n\nprivate def breadthFirstTraverseAux (g : Graph \u03b1 \u03b2) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (state : \u03b3) (startingSources : Array Nat) (sources : Array Nat) (visited : Array Bool) : Nat -> \u03b3\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 (\u03bb edge => edge.target))\n      for targetId in adjacencyList do nextSources := nextSources.insert targetId\n\n    let sourcesArray : Array Nat := nextSources.fold (\u03bb 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 \u03b1 \u03b2) (sources : Array Nat) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (maxDepth : Nat := g.vertexCount + sources.size) : \u03b3 := 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 \u03b1 \u03b2) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (maxDepth : Nat := g.vertexCount) : \u03b3 :=\n  g.breadthFirstTraverse g.getAllVertexIDs startingState visit maxDepth\n\n\nnamespace UndirectedGraph\n\n/-- See directed graph. -/\ndef depthFirstTraverse (ug : UndirectedGraph \u03b1 \u03b2) (sources : Array Nat) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (leave : Nat -> \u03b3 -> \u03b3  := (\u03bb _ x => x)) : \u03b3 :=\n  ug.graph.depthFirstTraverse sources startingState visit leave\n\n/-- See directed graph. -/\ndef depthFirstCompleteTraverse (ug : UndirectedGraph \u03b1 \u03b2) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (leave : Nat -> \u03b3 -> \u03b3  := (\u03bb _ x => x)) : \u03b3 :=\n  ug.graph.depthFirstCompleteTraverse startingState visit leave\n\n/-- See directed graph. -/\ndef breadthFirstTraverse (ug : UndirectedGraph \u03b1 \u03b2) (sources : Array Nat) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (maxDepth : Nat := ug.vertexCount) : \u03b3 :=\n  ug.graph.breadthFirstTraverse sources startingState visit maxDepth\n\n/-- See directed graph. -/\ndef breadthFirstCompleteTraverse (ug : UndirectedGraph \u03b1 \u03b2) (startingState : \u03b3 ) (visit : Nat -> \u03b3 -> \u03b3 \u00d7 Bool) (maxDepth : Nat := ug.vertexCount) : \u03b3 :=\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 (\u03b1 \u03b2 \u03b3: Type)\nvariable (R\u03b1: relation \u03b1) (R\u03b2: relation \u03b2) (R\u03b3: relation \u03b3)\nvariable (P\u03b1: \u03b1 \u2192 Prop) (P\u03b2: \u03b2 \u2192 Prop) (P\u03b3: \u03b3 \u2192 Prop)\nvariable (P\u03b1\u03b2\u03b3: \u03b1 \u2192 \u03b2 \u2192 Prop)\nvariable (f\u03b1\u03b2: \u03b1 \u2192 \u03b2) (f\u03b2\u03b3: \u03b2 \u2192 \u03b3)\nvariable [Proper_f\u03b1\u03b2: Proper (R\u03b1 ==> R\u03b2) f\u03b1\u03b2]\nvariable [Proper_P\u03b1: Proper (R\u03b1 ==> Iff) P\u03b1]\nvariable [PER R\u03b1] [PER R\u03b2]\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\u03b1 a a') (finish: P\u03b1 a') : P\u03b1 a := by\n  grewrite h\n  exact finish\n\n-- Rewrite a PER within itself\nexample (h: R\u03b1 a a') (finish: R\u03b1 a' x) : R\u03b1 a x := by\n  grewrite h\n  exact finish\nexample (h: R\u03b1 a a') (finish: R\u03b1 x a') : R\u03b1 x a := by\n  grewrite h\n  exact finish\n\n-- Nested function call\nexample (h: R\u03b1 a a') (finish: R\u03b2 (f\u03b1\u03b2 a') x): R\u03b2 (f\u03b1\u03b2 a) x := by\n  grewrite h\n  exact finish\n\n-- Multiple occurrences\nexample (h: R\u03b1 a a') (finish: R\u03b1 a' a'): R\u03b1 a a := by\n  grewrite h\n  exact finish\nexample (h: R\u03b1 a a') (finish: R\u03b1 a' a): R\u03b1 a a := by\n  grewrite h at 1\n  exact finish\nexample (h: R\u03b1 a a') (finish: R\u03b1 a a'): R\u03b1 a a := by\n  grewrite h at 2\n  exact finish\nexample (h: R\u03b1 a a') (finish: R\u03b1 a' a'): R\u03b1 a a := by\n  grewrite h at -1\n  grewrite h at 1\n  exact finish\n\n-- More complex selection\nexample (h: R\u03b1 a a') (finish: P\u03b1 a'): P\u03b1 a \u2227 P\u03b1 a \u2227 P\u03b1 a \u2227 P\u03b1 a \u2227 P\u03b1 a \u2227 P\u03b1 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 \u2192 Type v} -- The family of types already equipped with instances\nvariables (x y : \u03a0 i, f i) (i : I)\n\nnamespace pi\n\n@[to_additive pi.has_vadd']\ninstance has_smul' {g : I \u2192 Type*} [\u03a0 i, has_smul (f i) (g i)] :\n  has_smul (\u03a0 i, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb s x, \u03bb i, (s i) \u2022 (x i)\u27e9\n\n@[simp, to_additive]\nlemma smul_apply' {g : I \u2192 Type*} [\u2200 i, has_smul (f i) (g i)] (s : \u03a0 i, f i) (x : \u03a0 i, g i) :\n  (s \u2022 x) i = s i \u2022 x i :=\nrfl\n\n@[to_additive]\ninstance is_scalar_tower {\u03b1 \u03b2 : Type*}\n  [has_smul \u03b1 \u03b2] [\u03a0 i, has_smul \u03b2 $ f i] [\u03a0 i, has_smul \u03b1 $ f i]\n  [\u03a0 i, is_scalar_tower \u03b1 \u03b2 (f i)] : is_scalar_tower \u03b1 \u03b2 (\u03a0 i : I, f i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc x y (z i)\u27e9\n\n@[to_additive]\ninstance is_scalar_tower' {g : I \u2192 Type*} {\u03b1 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, has_smul (f i) (g i)] [\u03a0 i, has_smul \u03b1 $ g i]\n  [\u03a0 i, is_scalar_tower \u03b1 (f i) (g i)] : is_scalar_tower \u03b1 (\u03a0 i : I, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc x (y i) (z i)\u27e9\n\n@[to_additive]\ninstance is_scalar_tower'' {g : I \u2192 Type*} {h : I \u2192 Type*}\n  [\u03a0 i, has_smul (f i) (g i)] [\u03a0 i, has_smul (g i) (h i)] [\u03a0 i, has_smul (f i) (h i)]\n  [\u03a0 i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (\u03a0 i, f i) (\u03a0 i, g i) (\u03a0 i, h i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc (x i) (y i) (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class {\u03b1 \u03b2 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, has_smul \u03b2 $ f i] [\u2200 i, smul_comm_class \u03b1 \u03b2 (f i)] :\n  smul_comm_class \u03b1 \u03b2 (\u03a0 i : I, f i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm x y (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class' {g : I \u2192 Type*} {\u03b1 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ g i] [\u03a0 i, has_smul (f i) (g i)] [\u2200 i, smul_comm_class \u03b1 (f i) (g i)] :\n  smul_comm_class \u03b1 (\u03a0 i : I, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm x (y i) (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class'' {g : I \u2192 Type*} {h : I \u2192 Type*}\n  [\u03a0 i, has_smul (g i) (h i)] [\u03a0 i, has_smul (f i) (h i)]\n  [\u2200 i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (\u03a0 i, f i) (\u03a0 i, g i) (\u03a0 i, h i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm (x i) (y i) (z i)\u27e9\n\n@[to_additive]\ninstance {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, has_smul \u03b1\u1d50\u1d52\u1d56 $ f i]\n  [\u2200 i, is_central_scalar \u03b1 (f i)] : is_central_scalar \u03b1 (\u03a0 i, f i) :=\n\u27e8\u03bb r m, funext $ \u03bb i, op_smul_eq_smul _ _\u27e9\n\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `\u03a0 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 `\u03a0 i, f i`. This is not an instance as `i` cannot be inferred\"]\nlemma has_faithful_smul_at {\u03b1 : Type*}\n  [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, nonempty (f i)] (i : I) [has_faithful_smul \u03b1 (f i)] :\n  has_faithful_smul \u03b1 (\u03a0 i, f i) :=\n\u27e8\u03bb x y h, eq_of_smul_eq_smul $ \u03bb a : f i, begin\n  classical,\n  have := congr_fun (h $ function.update (\u03bb j, classical.choice (\u2039\u03a0 i, nonempty (f i)\u203a j)) i a) i,\n  simpa using this,\nend\u27e9\n\n@[to_additive pi.has_faithful_vadd]\ninstance has_faithful_smul {\u03b1 : Type*}\n  [nonempty I] [\u03a0 i, has_smul \u03b1 $ f i] [\u03a0 i, nonempty (f i)] [\u03a0 i, has_faithful_smul \u03b1 (f i)] :\n  has_faithful_smul \u03b1 (\u03a0 i, f i) :=\nlet \u27e8i\u27e9 := \u2039nonempty I\u203a in has_faithful_smul_at i\n\n@[to_additive]\ninstance mul_action (\u03b1) {m : monoid \u03b1} [\u03a0 i, mul_action \u03b1 $ f i] :\n  @mul_action \u03b1 (\u03a0 i : I, f i) m :=\n{ smul := (\u2022),\n  mul_smul := \u03bb r s f, funext $ \u03bb i, mul_smul _ _ _,\n  one_smul := \u03bb f, funext $ \u03bb i, one_smul \u03b1 _ }\n\n@[to_additive]\ninstance mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} [\u03a0 i, mul_action (f i) (g i)] :\n  @mul_action (\u03a0 i, f i) (\u03a0 i : I, g i) (@pi.monoid I f m) :=\n{ smul := (\u2022),\n  mul_smul := \u03bb r s f, funext $ \u03bb i, mul_smul _ _ _,\n  one_smul := \u03bb f, funext $ \u03bb i, one_smul _ _ }\n\ninstance smul_zero_class (\u03b1) {n : \u2200 i, has_zero $ f i}\n  [\u2200 i, smul_zero_class \u03b1 $ f i] :\n  @smul_zero_class \u03b1 (\u03a0 i : I, f i) (@pi.has_zero I f n) :=\n{ smul_zero := \u03bb c, funext $ \u03bb i, smul_zero _ }\n\ninstance smul_zero_class' {g : I \u2192 Type*} {n : \u03a0 i, has_zero $ g i}\n  [\u03a0 i, smul_zero_class (f i) (g i)] :\n  @smul_zero_class (\u03a0 i, f i) (\u03a0 i : I, g i) (@pi.has_zero I g n) :=\n{ smul_zero := by { intros, ext x, apply smul_zero } }\n\ninstance distrib_smul (\u03b1) {n : \u2200 i, add_zero_class $ f i} [\u2200 i, distrib_smul \u03b1 $ f i] :\n  @distrib_smul \u03b1 (\u03a0 i : I, f i) (@pi.add_zero_class I f n) :=\n{ smul_add := \u03bb c f g, funext $ \u03bb i, smul_add _ _ _ }\n\ninstance distrib_smul' {g : I \u2192 Type*} {n : \u03a0 i, add_zero_class $ g i}\n  [\u03a0 i, distrib_smul (f i) (g i)] :\n  @distrib_smul (\u03a0 i, f i) (\u03a0 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 (\u03b1) {m : monoid \u03b1} {n : \u2200 i, add_monoid $ f i}\n  [\u2200 i, distrib_mul_action \u03b1 $ f i] :\n  @distrib_mul_action \u03b1 (\u03a0 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 \u2192 Type*} {m : \u03a0 i, monoid (f i)} {n : \u03a0 i, add_monoid $ g i}\n  [\u03a0 i, distrib_mul_action (f i) (g i)] :\n  @distrib_mul_action (\u03a0 i, f i) (\u03a0 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 {\u03b1} [monoid \u03b1] [\u03a0 i, add_monoid $ f i]\n  [\u03a0 i, distrib_mul_action \u03b1 $ f i] [decidable_eq I] (i : I) (r : \u03b1) (x : f i) :\n  single i (r \u2022 x) = r \u2022 single i x :=\nsingle_op (\u03bb i : I, ((\u2022) r : f i \u2192 f i)) (\u03bb 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' {\u03b1 \u03b2} [monoid \u03b1] [add_monoid \u03b2]\n  [distrib_mul_action \u03b1 \u03b2] [decidable_eq I] (i : I) (r : \u03b1) (x : \u03b2) :\n  single i (r \u2022 x) = r \u2022 single i x :=\nsingle_smul i r x\n\nlemma single_smul\u2080 {g : I \u2192 Type*} [\u03a0 i, monoid_with_zero (f i)] [\u03a0 i, add_monoid (g i)]\n  [\u03a0 i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) :\n  single i (r \u2022 x) = single i r \u2022 single i x :=\nsingle_op\u2082 (\u03bb i : I, ((\u2022) : f i \u2192 g i \u2192 g i)) (\u03bb j, smul_zero _) _ _ _\n\ninstance mul_distrib_mul_action (\u03b1) {m : monoid \u03b1} {n : \u03a0 i, monoid $ f i}\n  [\u03a0 i, mul_distrib_mul_action \u03b1 $ f i] :\n  @mul_distrib_mul_action \u03b1 (\u03a0 i : I, f i) m (@pi.monoid I f n) :=\n{ smul_one := \u03bb c, funext $ \u03bb i, smul_one _,\n  smul_mul := \u03bb c f g, funext $ \u03bb i, smul_mul' _ _ _,\n  ..pi.mul_action _ }\n\ninstance mul_distrib_mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} {n : \u03a0 i, monoid $ g i}\n  [\u03a0 i, mul_distrib_mul_action (f i) (g i)] :\n  @mul_distrib_mul_action (\u03a0 i, f i) (\u03a0 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 {\u03b9 R M : Type*} [has_smul R M] :\n  has_smul R (\u03b9 \u2192 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 {\u03b9 \u03b1 \u03b2 M : Type*}\n  [has_smul \u03b1 M] [has_smul \u03b2 M] [smul_comm_class \u03b1 \u03b2 M] :\n  smul_comm_class \u03b1 \u03b2 (\u03b9 \u2192 M) :=\npi.smul_comm_class\n\n@[to_additive]\nlemma update_smul {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 (f i)] [decidable_eq I]\n  (c : \u03b1) (f\u2081 : \u03a0 i, f i) (i : I) (x\u2081 : f i) :\n  update (c \u2022 f\u2081) i (c \u2022 x\u2081) = c \u2022 update f\u2081 i x\u2081 :=\nfunext $ \u03bb j, (apply_update (\u03bb i, (\u2022) c) f\u2081 i x\u2081 j).symm\n\nend function\n\nnamespace set\n\n@[to_additive]\nlemma piecewise_smul {\u03b1 : Type*} [\u03a0 i, has_smul \u03b1 (f i)] (s : set I) [\u03a0 i, decidable (i \u2208 s)]\n  (c : \u03b1) (f\u2081 g\u2081 : \u03a0 i, f i) :\n  s.piecewise (c \u2022 f\u2081) (c \u2022 g\u2081) = c \u2022 s.piecewise f\u2081 g\u2081 :=\ns.piecewise_op _ _ (\u03bb _, (\u2022) c)\n\nend set\n\nsection extend\n\n@[to_additive] lemma function.extend_smul {R \u03b1 \u03b2 \u03b3 : Type*} [has_smul R \u03b3]\n  (r : R) (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e : \u03b2 \u2192 \u03b3) :\n  function.extend f (r \u2022 g) (r \u2022 e) = r \u2022 function.extend f g e :=\nfunext $ \u03bb _, by convert (apply_dite ((\u2022) 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": "import basic hp.core\n\nnamespace hp\n\n/-- A relation and a directionality.\nSo eg `<` is encoded as `\u27e8has_lt, ff\u27e9` and `>` is encoded as `\u27e8has_lt, tt\u27e9`.\n`=` is encoded as `\u27e8eq,ff\u27e9`.\n-/\n@[derive decidable_eq]\nmeta structure rel_inst :=\n(r : name)\n(dir : bool)\n\nmeta def rel_inst.op : name \u2192 tactic name\n| `eq := pure `eq\n| _ := failure\n\nmeta def rel_inst.mk_app : rel_inst \u2192 expr \u2192 expr \u2192 tactic expr\n| \u27e8n,ff\u27e9 l r := tactic.mk_app n [l,r]\n| \u27e8n,tt\u27e9 l r := do n \u2190 rel_inst.op n, tactic.mk_app n [l,r]\n\nmeta def rel_inst.flip : rel_inst \u2192 rel_inst | \u27e8n,d\u27e9 := \u27e8n,bnot d\u27e9\n\nmeta instance : has_coe name rel_inst := \u27e8\u03bb n, \u27e8n,ff\u27e9\u27e9\n\n/-- A `rule` is a lemma of the form `pf : \u03a0 ..params, rel lhs rhs`. The parameters `params` should all be concrete.\nThat is, have types that are not dependent on other parameters.\nThe effects of setting `rel_inst.dir`:\nFor example, with `dir := false`, we have\n`lhs \u2264 rhs`\nand with dir true we have `lhs \u2265 rhs` or equivalently `rhs \u2264 lhs`.\nThe dir says that we should flip the ordering of lhs and rhs when using the proof term, but that we\n should still consider lhs to be on the left for the purposes of rule composition and rewriting.\n rewrites always occur lhs -> rhs.\n-/\n@[derive decidable_eq]\nmeta structure rule :=\n(type : expr) -- the type of LHS and RHS.\n(rel : rel_inst)\n(params : list expr) -- a list of local constants which lhs and rhs and type are in terms of.\n(lhs : expr)\n(rhs : expr)\n(pf : expr) -- if rel_inst.dir then reverse lhs and rhs before feeding to proof. each param is a pi binding\n\nopen expr expr.zipper\n\nnamespace rule\n\nmeta instance : has_lt rule := \u27e8\u03bb x y, x.pf < y.pf\u27e9\n\nmeta instance : decidable_rel ((<) : rule \u2192 rule \u2192 Prop) := by apply_instance\n\nmeta def of_proof : expr \u2192 tactic rule\n| pf := do\n    T \u2190 infer_type pf,\n    (ctxt, body) \u2190 pure $ telescope.of_pis T,\n    locals \u2190 telescope.to_locals ctxt,\n    body \u2190 pure $ expr.instantiate_vars body locals,\n    (rel_name, lhs, rhs) \u2190 tactic.relation_lhs_rhs body,\n    type \u2190 tactic.infer_type lhs,\n    pure { type := type\n         , rel := rel_inst.mk rel_name ff\n         , lhs := lhs\n         , rhs := rhs\n         , params := locals\n         , pf := expr.mk_app pf $ list.reverse locals\n         }\n\nmeta def flip : rule \u2192 rule\n| r := {rel := r.rel.flip, lhs := r.rhs, rhs := r.lhs, ..r}\n\nmeta def get_lhs_rhs : rule \u2192 tactic (expr \u00d7 expr)\n| r := pure $ (r.lhs, r.rhs)\n\nmeta def body : rule \u2192 tactic expr\n| r := tactic.mk_app r.rel.r $ if r.rel.dir then [r.rhs, r.lhs] else [r.lhs, r.rhs]\n\nmeta instance rule_has_to_tactic_format : has_to_tactic_format rule :=\n\u27e8\u03bb r, rel_inst.mk_app r.rel r.lhs r.rhs >>= tactic.pp\u27e9\n\nmeta def of_name (n : name) : tactic rule :=\ntactic.resolve_name n >>= pure \u2218 pexpr.mk_explicit >>= tactic.to_expr >>= of_proof\n\nmeta def is_commute_raw : expr \u2192 expr \u2192 option expr\n| (expr.app (expr.app f1 x1) y1) (expr.app (expr.app f2 x2) y2) := do\n    guard $ f1 = f2 \u2227 x1 = y2 \u2227 y1 = x2, pure f1\n| _ _ := none\n\nmeta def is_commutativity (r : rule) : option expr := is_commute_raw r.lhs r.rhs\n\nmeta def is_ground (r : rule)  : bool  := r.params.empty\n\n/-- Returns true when the left hand side is a variable or metavariable. -/\nmeta def lhs_wildcard : rule \u2192 bool := \u03bb r, expr.is_var r.lhs || expr.is_mvar r.lhs\n\n/-- Returns true when the right hand side is a variable or metavariable. -/\nmeta def rhs_wildcard : rule \u2192 bool := \u03bb r, expr.is_var r.rhs || expr.is_mvar r.rhs\n\nmeta def with_metas : rule \u2192 tactic (list expr \u00d7 rule) | r := do\n    ms \u2190 r.params.mmap (\u03bb lc, do\n        m \u2190 (tactic.mk_meta_var $ expr.local_type lc),\n        pure (expr.local_uniq_name lc, m)\n    ),\n    c \u2190 pure $ { rule\n                . params := []\n                , rel := r.rel\n                , type := r.type\n                , lhs := instantiate_locals ms r.lhs\n                , rhs := instantiate_locals ms r.rhs\n                , pf :=  instantiate_locals ms r.pf\n                },\n    pure (prod.snd <$> ms, c)\n\nmeta def instantiate_mvars : rule \u2192 tactic rule | r := do\n    lhs \u2190 tactic.instantiate_mvars r.lhs,\n    rhs \u2190 tactic.instantiate_mvars r.rhs ,\n    pf \u2190 tactic.instantiate_mvars r.pf,\n    pure $ { lhs := lhs, rhs := rhs, pf := pf , ..r}\n\nmeta def mk_trans_proof : expr \u2192 expr \u2192 tactic expr |p\u2081 p\u2082 := tactic.mk_sorry\n\nopen tactic\n\nmeta def instantiate_params : rule \u2192 list expr \u2192 tactic rule | r assignments := do\n    let zipples := list.zip (expr.local_uniq_name <$> r.params) assignments,\n    pure {rule\n         . lhs := instantiate_locals zipples r.lhs\n         , rhs := instantiate_locals zipples r.rhs\n         , pf := instantiate_locals zipples r.pf\n         , params := [], ..r }\n\n/-- Take a path entry and compute the right equality congruence rule to use. -/\nprivate meta def mk_congr : expr \u2192 zipper.path.entry \u2192 tactic expr\n| pf (zipper.path.entry.app_fn () a) := tactic.mk_congr_fun pf a\n| pf (zipper.path.entry.app_arg f ()) := tactic.mk_congr_arg f pf\n| pf _ := fail \"rewriting under binders not implemented\"\n\nmeta def make_congr_proof : expr \u2192 expr.zipper.path \u2192 tactic expr\n| pf z := z.mfoldl mk_congr pf\n\nmeta def mk_monotone_proof : expr \u2192 zipper \u2192 tactic expr\n| pf z := tactic.mk_sorry\n\n-- meta def head_rewrite : rule \u2192 zipper \u2192 tactic rule\n-- |r z := do\n--     guard (r.rel.r = `eq),\n--     pf \u2190 make_congr_proof r.pf z,\n\nopen tactic\n\n/-- Take an unparameterised rule - that is, a rule with params = [] - and\n    take a list of metavariable, local_const pairs and assign each unassigned mvar in the list to a new local_constant.\n    then return a rule with these new local constants as its parameters. -/\nprivate meta def reparameterise : list (expr \u00d7 expr) \u2192 rule \u2192 tactic rule | ps r := do\n        let mmapper := (\u03bb (p : expr\u00d7expr), do\n            \u27e8m,expr.local_const u_n pp_n bi y\u27e9 \u2190 pure p,\n            ia \u2190 tactic.is_assigned m <|> pure ff,\n            if ia then pure m else do\n            loc' \u2190 tactic.mk_local' pp_n bi y,\n            tactic.unsafe.assign m loc',\n            pure loc'\n        ),\n        ms \u2190 list.mmap mmapper $ ps,\n        locals \u2190 pure $ list.bfilter expr.is_local_constant ms,\n        ms \u2190 ms.mmap tactic.instantiate_mvars,\n        r \u2190 rule.instantiate_mvars r,\n        pure {\n            params := locals,\n            ..r\n        }\n\nmeta def same_statement : rule \u2192 rule \u2192 tactic bool |r1 r2 :=\n    if r1.params.length \u2260 r2.params.length then pure ff else do\n    -- [todo] if dirs are different and the rel is non-symmetric then fail.\n    if r1.rel.r \u2260 r2.rel.r then pure ff else do\n    tactic.hypothetically (do\n        r3 \u2190 instantiate_params r1 r2.params,\n        pure $ (r3.lhs = r2.lhs) && (r3.rhs = r2.rhs)\n    ) <|> pure ff\n\nmeta def compose : rule \u2192 rule \u2192 tactic (list rule) | r1 r2 := do\n    tactic.hypothetically (do\n        (ms1,mr1) \u2190 with_metas r1,\n        (ms2,mr2) \u2190 with_metas r2,\n        unify mr1.rhs mr2.lhs,\n        ps \u2190 pure $ list.zip (ms1 ++ ms2) (r1.params ++ r2.params),\n        pf \u2190 mk_trans_proof  mr1.pf mr2.pf,\n        r \u2190 pure {rule . type := r1.type, rel := r1.rel, lhs := mr1.lhs, rhs := mr2.rhs, params := [], pf := pf},\n        r \u2190 reparameterise ps r,\n        pure [r]\n    ) <|> pure []\n\nmeta structure subcomposition :=\n(l : rule)\n(r : rule)\n(rz : zipper)\n(l_assignments : list expr)\n(r_assignments : list expr)\n(intersection_symbols : list expr)\n(new_rule : rule)\n\n/-- Take a pair of rules `lc`, `rc` and find a subterm of lc.rhs that unifies with rc.lhs and then compose them.\n -/\nmeta def subcompose (lc : rule) (rc : rule) : tactic (list subcomposition) := do\n    tactic.hypothetically (do\n        (lm,l) \u2190 with_metas lc,\n        (rm,r) \u2190 with_metas rc,\n        results \u2190 hp.traverse_proper (\u03bb acc z, do -- [todo] replace 'traverse_proper' with traverse monotone.\n            if zipper.is_mvar z then pure acc else do\n            tactic.hypothetically (do\n                unify r.lhs z.cursor transparency.none,\n                -- trace_m \"subcompose: \" $ (lc, rc),\n                pf \u2190 tactic.mk_sorry, -- [hack] [todo] get below line to work.\n                -- pf  \u2190 make_congr_proof r.pf z >>= mk_trans_proof l.pf,\n                new_rule \u2190 pure { rule\n                          . type := l.type\n                          , params := []\n                          , rel := l.rel -- [todo] get from transitivity lemma\n                          , lhs := l.lhs\n                          , rhs := z.unzip_with r.rhs\n                          , pf := pf\n                          },\n                ps \u2190 pure $ list.zip (lm ++ rm) (lc.params ++ rc.params),\n                new_rule \u2190 reparameterise ps new_rule,\n                lm \u2190 lm.mmap tactic.instantiate_mvars,\n                rm \u2190 rm.mmap tactic.instantiate_mvars,\n                intersection_symbols \u2190 hp.get_shared_nodes r.lhs z,\n                sc \u2190 pure $ { subcomposition\n                             . l := lc\n                             , r := rc\n                             , rz := z\n                             , l_assignments := lm\n                             , r_assignments := rm\n                             , intersection_symbols := intersection_symbols\n                             , new_rule := new_rule\n                             },\n                pure $ list.cons sc acc\n            ) <|> pure acc\n        ) [] $ zipper.zip l.rhs,\n        pure results\n    )\n\nmeta def subsume : rule \u2192 rule \u2192 tactic (list rule)\n| r1 r2 := do\n    ss \u2190 same_statement r1 r2,\n    if ss then pure [] else do\n    tactic.hypothetically (do\n            (ms1,mr1) \u2190 with_metas r1,\n            (ms2,mr2) \u2190 with_metas r2,\n            unify mr1.lhs mr2.lhs,\n            unify mr1.rhs mr2.rhs,\n            ps \u2190 pure $ list.zip (ms1 ++ ms2) (r1.params ++ r2.params),\n            r \u2190 reparameterise ps mr1,\n            pure [r]\n    ) <|> pure []\n\n-- /-- Get the smallest terms on the lhs of rule which are not present on the rhs. [todo] rename to not be confused with `get_destroys`. -/\n-- meta def get_destructions (r : rule) : tactic (list zipper) := do\n--     (lhs,rhs) \u2190 rule.get_lhs_rhs r,\n--     destroys \u2190 minimal_monotone (\u03bb z_lhs, do\n--         occs \u2190 find_occurences rhs z_lhs.cursor,\n--         guard (occs.empty),\n--         pure z_lhs\n--     ) lhs,\n--     pure destroys\n\n-- /-- Get the smallest terms on the lhs of rule which are not present on the rhs. -/\n-- meta def get_creations (r : rule) : tactic (list zipper) := do\n--     (lhs,rhs) \u2190 rule.get_lhs_rhs r,\n--     creates \u2190 minimal_monotone (\u03bb z_rhs, do\n--         occs \u2190 find_occurences lhs z_rhs.cursor,\n--         guard (occs.empty),\n--         pure z_rhs\n--     ) rhs,\n--     pure creates\n\nmeta def get_creates_aux (rev : bool) : expr \u2192 rule \u2192 tactic (list rule)\n| e r := do\n    (ms,mr) \u2190 rule.with_metas r,\n    /- idea: `r` creates `e` when there exists a substitution \u03c3 such that e \u2209 lhs and e \u2208 rhs.\n       additionally, `e` can't appear in \u03c3. A part of `e` must be non-trivially involved in the rewrite.\n    -/\n     (lhs,rhs) \u2190 (if rev then prod.swap else id) <$> get_lhs_rhs r,\n     rs \u2190 maximal_monotone (\u03bb rhs,\n        if rhs.is_mvar || rhs.is_constant then failure else do\n        tactic.hypothetically (do\n            unify e rhs.cursor transparency.none,\n            occs \u2190 find_occurences lhs e, -- [todo] likely optimisable\n            guard $ occs.empty,\n            r \u2190 reparameterise (list.zip ms mr.params) mr,\n            pure r\n        )\n     ) rhs,\n    pure rs\n\nmeta def head_rewrite : expr \u2192 rule \u2192 tactic rule\n| e rc := do\n    (rm,r) \u2190 with_metas rc,\n    tactic.hypothetically (do\n        unify e r.lhs,\n        ps \u2190 pure $ list.zip rm rc.params,\n        new_rule \u2190 reparameterise ps r,\n        -- trace_m \"head_rewrite: \" $ new_rule,\n        pure new_rule\n    )\n\nmeta def congr : zipper.path \u2192 rule \u2192 tactic rule\n| p r := do\n   lhs \u2190 pure $ zipper.path.apply p r.lhs,\n   rhs \u2190 pure $ zipper.path.apply p r.rhs,\n   type \u2190 tactic.infer_type lhs,\n   pf \u2190 make_congr_proof r.pf p,\n--    trace_m \"congr: \" $ lhs,\n\n   pure $ { rule\n     . type := type\n     , rel := r.rel -- [todo] in general this needs to be deduced from monotone lemmas\n     , params := r.params\n     , lhs := lhs\n     , rhs := rhs\n     , pf := pf\n     }\n\n/-- moves up a zipper path until the rule can be applied. -/\nmeta def rewrite_on_zipper (r : rule) : zipper \u2192 tactic rule\n| z := (head_rewrite z.cursor r >>= congr z.get_path) <|> (up z >>= rewrite_on_zipper)\n\nmeta def get_creates := get_creates_aux tt\nmeta def get_destroys := get_creates_aux ff\n\n-- [todo] another case is an 'independent subcompose'. This is where you rw on a param in the upper rule. This also should require a 'target expression' to prevent too many cases from being made.\n/- That is,\n    a pair r\u2081, r\u2082 such that r\u2081(_,_,r\u2082,_,_).rhs =?= target and the lhs doesn't and r\u2081 independently doesn't.\n    It might also have to be that a subterm of the RHS unifies in a way that crosses the region between r\u2081 r\u2082.\n    It will be best to figure this out when I have some specific examples when the above methods are not good enough.\n -/\n\nmeta def mmap_children {t : Type \u2192 Type} [monad t] (f : telescope \u2192 expr \u2192 t expr) : telescope \u2192 rule \u2192 t rule\n| \u0393 r := pure rule.mk\n            <*> (\u0393 \u2344 f $ r.type)\n            <*> pure r.rel\n            <*> (\u0393 \u2344 f $ r.params) -- [bug] is this right?\n            <*> (\u0393 \u2344 f $ r.lhs)\n            <*> (\u0393 \u2344 f $ r.rhs)\n            <*> (\u0393 \u2344 f $ r.pf)\n\nmeta instance : assignable rule := \u27e8@mmap_children\u27e9\n\nmeta def is_def_eq (r\u2081 r\u2082 : rule) : tactic bool :=\n  tactic.is_success $ (do\n    tactic.is_def_eq r\u2081.lhs r\u2082.lhs,\n    tactic.is_def_eq r\u2081.rhs r\u2082.rhs\n  )\n\nmeta def lhs_param_at : address \u2192 rule \u2192 bool\n| a r := ff <| (do s \u2190 expr.address.follow a r.lhs,\n    pure $ (expr.is_local_constant s) \u2227 (r.params.any (\u03bb x, s = x)))\n\n-- /-- Alternative implementation of congr using rewrite instead of mk_congr. -/\n-- meta def mk_eq_congr : rule \u2192 zipper.path \u2192 tactic rule\n-- | r p := do\n--     guard (r.rel.r = `eq),\n--     new_type \u2190 tactic.to_expr ```(%%(zipper.unzip \u27e8p,r.lhs\u27e9) = %%(zipper.unzip \u27e8p,r.rhs\u27e9)),\n--     new_type \u2190 pure $ expr.pis r.params new_type,\n--     pf \u2190 tactic.fabricate new_type (do\n--         xs \u2190 intron r.params.length,\n--         tactic.rewrite_target r.pf\n--     ),\n--     rule.of_proof pf\n\n/-- Use the given rule application on the lhs of the target. Will look for congruences. -/\nmeta def rewrite_conv : rule \u2192 conv unit := \u03bb r, do\n        lhs \u2190 conv.lhs >>= tactic.instantiate_mvars,\n        sub \u2190 tactic.instantiate_mvars r.lhs,\n        l \u2190 find_occurences (zipper.zip lhs) r.lhs,\n        (z::rest) \u2190 pure l,\n        r \u2190 tactic.trace_fail $ rewrite_on_zipper r z,\n        -- tactic.trace_m \"rewrite_conv: \" $ r,\n        transitivity,\n        apply r.pf,\n        -- trace_state, trace r,\n        try $ all_goals $ apply_instance <|> prop_assumption,\n        pure ()\n\n/-- Checks whether the given rule is a local hyp or derived from one. -/\nmeta def is_local_hypothesis : rule \u2192 tactic bool\n| r := (do\n    p \u2190 pure $ r.pf,\n    ls \u2190 pure $ list_locals p,\n    ls \u2190 ls.m_some (\u03bb l, (do\n        y \u2190 tactic.infer_type l,\n        (`=,_,_) \u2190 tactic.relation_lhs_rhs y,\n        pure tt) <|> pure ff\n    ),\n    pure tt\n) <|> pure ff\n\nmeta def count_metas : rule \u2192 tactic nat\n| r := do\n    lhs \u2190 tactic.instantiate_mvars r.lhs,\n    uns \u2190 traverse_proper (\u03bb t e, pure $\n        match expr.as_mvar e.cursor with\n        | none := t\n        | (some \u27e8u,_,_\u27e9) := table.insert u t\n        end) \u2205 lhs,\n    pure $ table.size $ uns\n\nend rule\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/rewrite/rule.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.04813677009248645, "lm_q1q2_score": 0.020705904024769347}}
{"text": "/-\nCopyright (c) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\n\nimport data.buffer.parser\n\nopen lean.parser tactic interactive parser\n\n/-- \n`restate_axiom` takes a structure field, and makes a new, definitionally simplified copy of it, appending `_lemma` to the name.\nThe main application is to provide clean versions of structure fields that have been tagged with an auto_param.\n-/\nmeta def restate_axiom (d : declaration) (new_name : name) : tactic unit :=\ndo (levels, type, value, reducibility, trusted) \u2190 pure (match d.to_definition with\n  | declaration.defn name levels type value reducibility trusted :=\n    (levels, type, value, reducibility, trusted)\n  | _ := undefined\n  end),\n  (s, u) \u2190 mk_simp_set ff [] [],\n  new_type \u2190 (s.dsimplify [] type) <|> pure (type),\n  updateex_env $ \u03bb env, env.add (declaration.defn new_name levels new_type value reducibility trusted)\n\nprivate meta def name_lemma (old : name) (new : option name := none) : tactic name :=\nmatch new with\n| none :=\n  match old.components.reverse with\n  | last :: most := (do let last := last.to_string,\n                       let last := if last.to_list.ilast = ''' then\n                                     (last.to_list.reverse.drop 1).reverse.as_string\n                                   else last ++ \"_lemma\",\n                       return (mk_str_name old.get_prefix last)) <|> failed\n  | nil          := undefined\n  end\n| (some new) := return (mk_str_name old.get_prefix new.to_string)\nend\n\n@[user_command] meta def restate_axiom_cmd (meta_info : decl_meta_info)\n  (_ : parse $ tk \"restate_axiom\") : lean.parser unit :=\ndo from_lemma \u2190 ident,\n   new_name \u2190 optional ident,\n   from_lemma_fully_qualified \u2190 resolve_constant from_lemma,\n  d \u2190 get_decl from_lemma_fully_qualified <|>\n    fail (\"declaration \" ++ to_string from_lemma ++ \" not found\"),\n  do {\n    new_name \u2190 name_lemma from_lemma_fully_qualified new_name,\n    restate_axiom d new_name\n  }\n\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/restate_axiom.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33458942798284697, "lm_q2_score": 0.06187599048099379, "lm_q1q2_score": 0.0207030522609078}}
{"text": "import tactic\nimport tactic.induction\n\nimport .base\n\nlemma A_pw_1_not_hws : \u00acA_hws 1 :=\nbegin\n  sorry\nend", "meta": {"author": "user7230724", "repo": "lean-projects", "sha": "ab9a83874775efd18f8c5b867e480bae4d596b31", "save_path": "github-repos/lean/user7230724-lean-projects", "path": "github-repos/lean/user7230724-lean-projects/lean-projects-ab9a83874775efd18f8c5b867e480bae4d596b31/src/ap/pw_1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.06656919406308585, "lm_q1q2_score": 0.020682674690520406}}
{"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.data.bool.lemmas\nimport Mathlib.Lean3Lib.init.data.string.basic\nimport Mathlib.Lean3Lib.init.meta.well_founded_tactics\n\nnamespace Mathlib\n\nnamespace string\n\n\nnamespace iterator\n\n\n@[simp] theorem next_to_string_mk_iterator (s : string) : next_to_string (mk_iterator s) = s :=\n  string_imp.rec (fun (s : List char) => Eq.refl (next_to_string (mk_iterator (string_imp.mk s)))) s\n\n@[simp] theorem length_next_to_string_next (it : iterator) :\n    length (next_to_string (next it)) = length (next_to_string it) - 1 :=\n  sorry\n\ntheorem zero_lt_length_next_to_string_of_has_next {it : iterator} :\n    \u21a5(has_next it) \u2192 0 < length (next_to_string it) :=\n  sorry\n\nend iterator\n\n\n-- TODO(Sebastian): generalize to something like https://doc.rust-lang.org/std/primitive.str.html#method.split\n\ndef split (p : char \u2192 Bool) (s : string) : List string :=\n  split_core p (mk_iterator s) (mk_iterator s)\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/string/ops_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.05419873249666699, "lm_q1q2_score": 0.02066161729401249}}
{"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.Compiler.LCNF.InferType\nimport Lean.Compiler.LCNF.PrettyPrinter\nimport Lean.Compiler.LCNF.CompatibleTypes\n\nnamespace Lean.Compiler.LCNF\n\n/-!\n# Note: Type compatibility checking for LCNF\n\nWe used to have a type compatibility relation `\u2243` for LCNF types.\nIt treated erased types/values as wildcards. Examples:\n- `List Nat \u2243 List \u25fe`\n- `(List \u25fe \u2192 List \u25fe) \u2243 (List Nat \u2192 List Bool)`\n\nWe used this relation to sanity check compiler passes, and detect\nbuggy transformations that broke type compatibility. For example,\ngiven an application `f a`, we would check whether `a`s type as\ncompatible with the type expected by `f`.\n\nHowever, the type compatibility relation is not transitive. Example:\n- `List Nat \u2243 List \u25fe`, `List \u25fe \u2243 List String`, but `List Nat` and `List String` are **not** compatible.\n\nWe tried address the issue above by adding casts, which required us\nto then add `cast` elimination simplifications, and generated a significant overhead in\nthe code generator.\n\nHere is an example of transformation that would require the insertion of a cast operation.\n```\ndef foo (g : List A \u2192 List A) (a : List B) :=\n  fun f (x : List \u25fe) :=\n    let _x.1 := g x\n    ...\n  let _x.2 := f a\n  ...\n```\nThe code above would not trigger any type compatibility issue, but\nby inlining `f` without adding cast operations, we would get the\nfollowing type incorrect code.\n```\ndef foo (g : List A \u2192 List A) (a : List B) :=\nlet _x.2 := g a -- Type error\n...\n```\n\nWe have considered using a reflexive and transitive subtype relation `\u227a`.\n- `A \u227a A`\n- `(Nat \u00d7 Nat) \u227a (Nat \u00d7 \u25fe) \u227a (\u25fe \u00d7 \u25fe) \u227a \u25fe`\n- `List Nat \u227a List \u25fe \u2280 List String`\n- `(List \u25fe \u2192 List Nat) \u227a (List Bool \u2192 List \u25fe)`\nNote that `A \u227a B` implies `A \u2243 B`\n\nThe subtype relation has better properties, but also has problems.\nFirst, when converting to LCNF we would have to add more casts. Example:\nthe function takes a `List \u25fe`, but the value has type `\u25fe`.\nMoreover, recall that `(List Nat \u2192 List Nat) \u2280 (\u25fe \u2192 \u25fe)` forcing us\nto add many casts operations when moving to the mono phase where\nwe erase type parameters.\n\nRecall that type compatibility and subtype relationships do not help with memory layout.\nWe have that `(UInt32 \u00d7 UInt32) \u227a (\u25fe \u00d7 \u25fe) \u227a \u25fe` but elements of these types have\ndifferent runtime representation.\n\nThus, we have decided to abandon the type compatibility checks and cast operations\nin LCNF. The only drawback is that we lose the capability of catching simple bugs\nat compiler passes.\n\nIn the future, we can try to add a sanity check flag that instructs the compiler to use\nthe subtype relation in sanity checks and add the necessary casts.\n\n-/\n\nnamespace Check\nopen InferType\n\n/-\nType and structural properties checker for LCNF expressions.\n-/\n\nstructure Context where\n  /-- Join points that are in scope. -/\n  jps : FVarIdSet := {}\n  /-- Variables and local functions in scope -/\n  vars : FVarIdSet := {}\n\nstructure State where\n  /-- All free variables found -/\n  all : FVarIdHashSet := {}\n\nabbrev CheckM := ReaderT Context $ StateRefT State InferTypeM\n\ndef checkTypes : CheckM Bool := do\n  return (\u2190 getConfig).checkTypes\n\ndef checkFVar (fvarId : FVarId) : CheckM Unit :=\n  unless (\u2190 read).vars.contains fvarId do\n    throwError \"invalid out of scope free variable {\u2190 getBinderName fvarId}\"\n\n/-- Return true `f` is a constructor and `i` is less than its number of parameters. -/\ndef isCtorParam (f : Expr) (i : Nat) : CoreM Bool := do\n  let .const declName _ := f | return false\n  let .ctorInfo info \u2190 getConstInfo declName | return false\n  return i < info.numParams\n\ndef checkAppArgs (f : Expr) (args : Array Arg) : CheckM Unit := do\n  let mut fType \u2190 inferType f\n  let mut j := 0\n  for i in [:args.size] do\n    let arg := args[i]!\n    if fType.isErased then\n      return ()\n    fType := fType.headBeta\n    let (d, b) \u2190\n      match fType with\n      | .forallE _ d b _ => pure (d, b)\n      | _ =>\n        fType := instantiateRevRangeArgs fType j i args |>.headBeta\n        match fType with\n        | .forallE _ d b _ => j := i; pure (d, b)\n        | _ => return ()\n    let expectedType := instantiateRevRangeArgs d j i args\n    if (\u2190 checkTypes) then\n      let argType \u2190 arg.inferType\n      unless (\u2190 InferType.compatibleTypes argType expectedType) do\n        throwError \"type mismatch at LCNF application{indentExpr (mkAppN f (args.map Arg.toExpr))}\\nargument {arg.toExpr} has type{indentExpr argType}\\nbut is expected to have type{indentExpr expectedType}\"\n    unless (\u2190 pure (maybeTypeFormerType expectedType) <||> isErasedCompatible expectedType) do\n      match arg with\n      | .fvar fvarId => checkFVar fvarId\n      | .erased => pure ()\n      | .type _ =>\n        -- Constructor parameters that are not type formers are erased at phase .mono\n        unless (\u2190 getPhase) \u2265 .mono && (\u2190 isCtorParam f i) do\n          throwError \"invalid LCNF application{indentExpr (mkAppN f (args.map (\u00b7.toExpr)))}\\nargument{indentExpr arg.toExpr}\\nhas type{indentExpr expectedType}\\nmust be a free variable\"\n    fType := b\n\ndef checkLetValue (e : LetValue) : CheckM Unit := do\n  match e with\n  | .value .. | .erased => pure ()\n  | .const declName us args => checkAppArgs (mkConst declName us) args\n  | .fvar fvarId args => checkFVar fvarId; checkAppArgs (.fvar fvarId) args\n  | .proj _ _ fvarId => checkFVar fvarId\n\ndef checkJpInScope (jp : FVarId) : CheckM Unit := do\n  unless (\u2190 read).jps.contains jp do\n    /-\n    We cannot jump to join points defined out of the scope of a local function declaration.\n    For example, the following is an invalid LCNF.\n    ```\n    jp_1 := fun x => ... -- Some join point\n    let f := fun y => -- Local function declaration.\n      ...\n      jp_1 _x.n -- jump to a join point that is not in the scope of `f`.\n    ```\n    -/\n    throwError \"invalid jump to out of scope join point `{mkFVar jp}`\"\n\ndef checkParam (param : Param) : CheckM Unit := do\n  unless param == (\u2190 getParam param.fvarId) do\n    throwError \"LCNF parameter mismatch at `{param.binderName}`, does not value in local context\"\n\ndef checkParams (params : Array Param) : CheckM Unit :=\n  params.forM checkParam\n\ndef checkLetDecl (letDecl : LetDecl) : CheckM Unit := do\n  checkLetValue letDecl.value\n  if (\u2190 checkTypes) then\n    let valueType \u2190 letDecl.value.inferType\n    unless (\u2190 InferType.compatibleTypes letDecl.type valueType) do\n      throwError \"type mismatch at `{letDecl.binderName}`, value has type{indentExpr valueType}\\nbut is expected to have type{indentExpr letDecl.type}\"\n  unless letDecl == (\u2190 getLetDecl letDecl.fvarId) do\n    throwError \"LCNF let declaration mismatch at `{letDecl.binderName}`, does not match value in local context\"\n\ndef addFVarId (fvarId : FVarId) : CheckM Unit := do\n  if (\u2190 get).all.contains fvarId then\n    throwError \"invalid LCNF, free variables are not unique `{fvarId.name}`\"\n  modify fun s => { s with all := s.all.insert fvarId }\n\n@[inline] def withFVarId (fvarId : FVarId) (x : CheckM \u03b1) : CheckM \u03b1 := do\n  addFVarId fvarId\n  withReader (fun ctx => { ctx with vars := ctx.vars.insert fvarId }) x\n\n@[inline] def withJp (fvarId : FVarId) (x : CheckM \u03b1) : CheckM \u03b1 := do\n  addFVarId fvarId\n  withReader (fun ctx => { ctx with jps := ctx.jps.insert fvarId }) x\n\n@[inline] def withParams (params : Array Param) (x : CheckM \u03b1) : CheckM \u03b1 := do\n  params.forM (addFVarId \u00b7.fvarId)\n  withReader (fun ctx => { ctx with vars := params.foldl (init := ctx.vars) fun vars p => vars.insert p.fvarId })\n    x\n\nmutual\n\nset_option linter.all false\n\npartial def checkFunDeclCore (declName : Name) (params : Array Param) (type : Expr) (value : Code) : CheckM Unit := do\n  checkParams params\n  withParams params do\n    discard <| check value\n    if (\u2190 checkTypes) then\n      let valueType \u2190 mkForallParams params (\u2190 value.inferType)\n      unless (\u2190 InferType.compatibleTypes type valueType) do\n        throwError \"type mismatch at `{declName}`, value has type{indentExpr valueType}\\nbut is expected to have type{indentExpr type}\"\n\npartial def checkFunDecl (funDecl : FunDecl) : CheckM Unit := do\n  checkFunDeclCore funDecl.binderName funDecl.params funDecl.type funDecl.value\n  let decl \u2190 getFunDecl funDecl.fvarId\n  unless decl.binderName == funDecl.binderName do\n    throwError \"LCNF local function declaration mismatch at `{funDecl.binderName}`, binder name in local context `{decl.binderName}`\"\n  unless decl.type == funDecl.type do\n    throwError \"LCNF local function declaration mismatch at `{funDecl.binderName}`, type in local context{indentExpr decl.type}\\nexpected{indentExpr funDecl.type}\"\n  unless (\u2190 getFunDecl funDecl.fvarId) == funDecl do\n    throwError \"LCNF local function declaration mismatch at `{funDecl.binderName}`, declaration in local context does match\"\n\npartial def checkCases (c : Cases) : CheckM Unit := do\n  let mut ctorNames : NameSet := {}\n  let mut hasDefault := false\n  checkFVar c.discr\n  for alt in c.alts do\n    match alt with\n    | .default k => hasDefault := true; check k\n    | .alt ctorName params k =>\n      checkParams params\n      if ctorNames.contains ctorName then\n        throwError \"invalid LCNF `cases`, alternative `{ctorName}` occurs more than once\"\n      ctorNames := ctorNames.insert ctorName\n      let .ctorInfo val \u2190 getConstInfo ctorName | throwError \"invalid LCNF `cases`, `{ctorName}` is not a constructor name\"\n      unless val.induct == c.typeName do\n        throwError \"invalid LCNF `cases`, `{ctorName}` is not a constructor of `{c.typeName}`\"\n      unless params.size == val.numFields do\n        throwError \"invalid LCNF `cases`, `{ctorName}` has # {val.numFields} fields, but alternative has # {params.size} alternatives\"\n      withParams params do check k\n\npartial def check (code : Code) : CheckM Unit := do\n  match code with\n  | .let decl k => checkLetDecl decl; withFVarId decl.fvarId do check k\n  | .fun decl k =>\n    -- Remark: local function declarations should not jump to out of scope join points\n    withReader (fun ctx => { ctx with jps := {} }) do checkFunDecl decl\n    withFVarId decl.fvarId do check k\n  | .jp decl k => checkFunDecl decl; withJp decl.fvarId do check k\n  | .cases c => checkCases c\n  | .jmp fvarId args =>\n    checkJpInScope fvarId\n    let decl \u2190 getFunDecl fvarId\n    unless decl.getArity == args.size do\n      throwError \"invalid LCNF `goto`, join point {decl.binderName} has #{decl.getArity} parameters, but #{args.size} were provided\"\n    checkAppArgs (.fvar fvarId) args\n  | .return fvarId => checkFVar fvarId\n  | .unreach .. => pure ()\n\nend\n\ndef run (x : CheckM \u03b1) : CompilerM \u03b1 :=\n  x |>.run {} |>.run' {} |>.run {}\n\nend Check\n\ndef Decl.check (decl : Decl) : CompilerM Unit := do\n  Check.run do Check.checkFunDeclCore decl.name decl.params decl.type decl.value\n\n/--\nCheck whether every local declaration in the local context is used in one of given `decls`.\n-/\npartial def checkDeadLocalDecls (decls : Array Decl) : CompilerM Unit := do\n  let (_, s) := visitDecls decls |>.run {}\n  let usesFVar (binderName : Name) (fvarId : FVarId) :=\n    unless s.contains fvarId do\n      throwError \"LCNF local context contains unused local variable declaration `{binderName}`\"\n  let lctx := (\u2190 get).lctx\n  lctx.params.forM fun fvarId decl => usesFVar decl.binderName fvarId\n  lctx.letDecls.forM fun fvarId decl => usesFVar decl.binderName fvarId\n  lctx.funDecls.forM fun fvarId decl => usesFVar decl.binderName fvarId\nwhere\n  visitFVar (fvarId : FVarId) : StateM FVarIdHashSet Unit :=\n    modify (\u00b7.insert fvarId)\n\n  visitParam (param : Param) : StateM FVarIdHashSet Unit := do\n    visitFVar param.fvarId\n\n  visitParams (params : Array Param) : StateM FVarIdHashSet Unit := do\n    params.forM visitParam\n\n  visitCode (code : Code) : StateM FVarIdHashSet Unit := do\n    match code with\n    | .jmp .. | .return .. | .unreach .. => return ()\n    | .let decl k => visitFVar decl.fvarId; visitCode k\n    | .fun decl k | .jp decl k =>\n      visitFVar decl.fvarId; visitParams decl.params; visitCode decl.value\n      visitCode k\n    | .cases c => c.alts.forM fun alt => do\n      match alt with\n      | .default k => visitCode k\n      | .alt _ ps k => visitParams ps; visitCode k\n\n  visitDecl (decl : Decl) : StateM FVarIdHashSet Unit := do\n    visitParams decl.params\n    visitCode decl.value\n\n  visitDecls (decls : Array Decl) : StateM FVarIdHashSet Unit :=\n    decls.forM visitDecl\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/Check.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.057493272340696816, "lm_q1q2_score": 0.02066101987823301}}
{"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 {\u03b1} {P Q : \u03b1 \u2192 Prop} (h : P = Q) : (\u2200 x, P x \u2194 Q x) :=\n\u03bb _, h \u25b8 iff_of_eq rfl\n\nlemma mem_cons_iff {\u03b1} (xs : list \u03b1) (x y : \u03b1) : y \u2208 (x::xs) \u2194 y = x \u2228 y \u2208 xs :=\n(set.mem_union x (eq y) (\u03bb (x : \u03b1), list.mem y xs))\n\nexample {\u03b1 \u03b2} (xs : list \u03b1) {x : \u03b1} (f : \u03b1 \u2192 \u03b2) (H_mem : x \u2208 xs) : f x \u2208 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 := \u27e8\"\"\u27e9\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 : \u2115) (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 \u2208 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 \u2208 upper) : c.to_lower \u2208 lower :=\nby {rw[<-to_lower_upper_eq_lower], exact list.mem_map_of_mem _ \u2039_\u203a}\n\ndef lowercase : {c // c \u2208 upper} \u2192 {c // c \u2208 lower} :=\n\u03bb \u27e8c,H\u27e9, \u27e8char.to_lower c, mem_lower_of_to_lower_upper H\u27e9\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 := '\u2009'\n\ndef hair_space : char := '\u200a'\n\ndef no_break_space : char := ' '\n\ndef medium_mathematical_space : char := '\u205f'\n\ndef ideographic_space : char := '\u3000'\n\ndef zero_width_no_break_space := '\ufeff'\n\ndef zero_width_space := '\u200b'\n\ndef punctuation_space := '\u2008'\n\ndef figure_space := '\u2007'\n\ndef six_per_em_space := '\u2006'\n\ndef four_per_em_space := '\u2005'\n\ndef three_per_em_space := '\u2004'\n\ndef em_space := '\u2003'\n\ndef en_space := '\u2002'\n\ndef em_quad := '\u2001'\n\ndef en_quad := '\u2000'\n\ndef mongolian_vowel_separator := '\u180e'\n\ndef ogham_space_mark := '\u1680'\n\ndef tab := char.mk' 0x09\n\ndef narrow_no_break_space := '\u202f'\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 := \u27e8arg.data.map char.to_lower\u27e9\n\ndef reverse (arg : string) : string :=\n\u27e8arg.data.reverse\u27e9\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 {\u03b1 : Type}\n\nmeta def mk (run : string \u2192 tactic (\u03b1 \u00d7 string)) : parser_tactic \u03b1 :=\nstate_t.mk run\n\nmeta def lift {\u03b1} (val : tactic \u03b1) : parser_tactic \u03b1 := state_t.lift val\n\nmeta def run (p : parser_tactic \u03b1) : string \u2192 tactic (\u03b1 \u00d7 string) :=\nstate_t.run p\n\nmeta def result (p : parser_tactic \u03b1) (arg : string) : tactic \u03b1 :=\np.run arg >>= return \u2218 prod.fst\n\nmeta def get_result [has_reflect \u03b1] (p : parser_tactic \u03b1) (arg : string) : tactic unit :=\np.result arg >>= \u03bb 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 \u03b1) : string \u2192 parser_tactic \u03b1 :=\n\u03bb 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\u27e8\u03bb p\u2081 p\u2082, do a <- p\u2081, b <- p\u2082, return $ a ++ b\u27e9 \n\nmeta def fail : parser_tactic \u03b1 := parser_tactic.mk $ \u03bb _, tactic.failed\n\nmeta def trace_state : parser_tactic unit :=\nparser_tactic.mk $ \u03bb 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\u03bb arg, state_t.put arg\n\nmeta def modify_state : (string -> string) -> parser_tactic unit :=\n\u03bb m, state_t.modify m\n\nmeta def prepend_state : string -> parser_tactic unit :=\n\u03bb arg, modify_state (\u03bb \u03c3, arg ++ \u03c3)\n\nmeta def append_state : string -> parser_tactic unit :=\n\u03bb arg, modify_state (\u03bb \u03c3, \u03c3 ++ arg)\n\nmeta def run_parser' (p : parser_tactic \u03b1) : parser_tactic string \u2192 parser_tactic \u03b1 :=\n\u03bb q, q >>= run_parser p\n\nmeta def skip : parser_tactic unit :=\nparser_tactic.mk $ \u03bb str, return ((), str)\n\nmeta def trace (msg : string) : parser_tactic unit :=\nparser_tactic.mk $ \u03bb str, tactic.trace msg >> return ((), str)\n\nmeta def try_core (p : parser_tactic \u03b1) : parser_tactic (option \u03b1) :=\nmk $ (\u03bb 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 \u03b1) : parser_tactic unit :=\ntry_core p >>= \u03bb r, match r with\n                    | none := skip\n                    | some x := return ()\n                    end\n\nmeta def to_tactic (p : parser_tactic \u03b1) : string \u2192 tactic \u03b1 :=\n\u03bb arg, (p.run arg) >>= return \u2218 prod.fst\n\nmeta instance : has_coe (parser_tactic \u03b1) (string \u2192 tactic \u03b1) :=\n\u27e8to_tactic\u27e9\n\nmeta def parser_tactic_format {\u03b1} [H : has_to_format \u03b1] : \u03b1 \u00d7 string \u2192 format :=\n\u03bb \u27e8r,\u03c3\u27e9,\n    format.line ++ (\"Result:\") ++\n    format.line ++ format.line ++ (format.nest 5 $ to_fmt r) ++\n    format.line ++ format.line ++\n    \"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\" ++\n    format.line ++ format.line ++ (\"State:\") ++\n    format.line ++ format.line ++ (format.nest 5 $ to_fmt \u03c3)\n\n/-- For testing parsers on strings -/\nmeta def run' {\u03b1} [has_to_format \u03b1] (p : parser_tactic \u03b1) (arg : string) : tactic unit :=\n  p.run arg >>= \u03bb fmt, return $ _root_.trace_fmt (parser_tactic_format fmt) (\u03bb _, ())\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 $ \u03bb str,\n  match str with\n  | \u27e8[]\u27e9      := tactic.failed\n  | \u27e8(x::xs)\u27e9 := return (x, \u27e8xs\u27e9)\n  end\n\nmeta def eof : parser_tactic unit :=\nparser_tactic.mk $ \u03bb str,\n  match str with\n  | \u27e8[]\u27e9 := return \u27e8(), str\u27e9\n  | \u27e8(x::xs)\u27e9 := 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 $ \u03bb str,\n  match str with\n  | \u27e8[]\u27e9      := tactic.failed\n  | \u27e8(x::xs)\u27e9 := return (x, \u27e8x::xs\u27e9)\n  end\n\nmeta def to_string : parser_tactic char \u2192 parser_tactic string :=\n\u03bb p, do x <- p, return x.to_string\n\nmeta def to_string' : parser_tactic (list char) \u2192 parser_tactic string :=\n\u03bb p, do x <- p, return $ string_imp.mk x\n\nmeta instance parser_to_string : has_coe (parser_tactic (char)) (parser_tactic string) :=\n\u27e8to_string\u27e9\n\nmeta instance list_char_coe : has_coe (parser_tactic (list char)) (parser_tactic string) :=\n\u27e8to_string'\u27e9\n\nmeta def sat (P : char \u2192 Prop) [decidable_pred P] : parser_tactic char :=\nitem >>= \u03bb x, (if P x then return x else fail)\n\nsection eq_any\nvariables {\u03b1 : Type*} [decidable_eq \u03b1]\n\ndef eq_any (cs : list \u03b1) : \u03b1 \u2192 Prop :=\n\u03bb c, cs.foldr (\u03bb x, \u03bb b, (= c) x \u2294 b)  \u22a5 \n\n@[simp]lemma eq_any_cons {c : \u03b1} {cs} : eq_any (c::cs) = \u03bb x, c = x \u2228 eq_any cs x := rfl\n\ninstance eq_any_decidable_pred : \u2200 {cs : list \u03b1}, 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 \u03b1) : \u03b1 \u2192 Prop :=\n\u03bb c, cs.foldr (\u03bb x, \u03bb b, (= c) x \u2293 b)  \u22a4\n\n@[simp]lemma eq_all_cons {c : \u03b1} {cs} : eq_all (c::cs) = \u03bb x, c = x \u2227 eq_all cs x := rfl\n\ninstance eq_all_decidable_pred : \u2200 {cs : list \u03b1}, 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 (\u03bb c, \u00ac eq_any cs c)\n\nmeta def not_ch (c : char) : parser_tactic char := not_chs $ [c]\n\nmeta def str : string \u2192 parser_tactic string\n| \u27e8[]\u27e9    := pure \"\"\n| \u27e8x::xs\u27e9 := do y <- ch x,\n               z <- str \u27e8xs\u27e9,\n               return $ y.to_string ++ z\n\nmeta def nil_if_fail {\u03b1} : parser_tactic \u03b1 \u2192 parser_tactic (list \u03b1) := \n\u03bb p, (p >>= return \u2218 return) <|> return []\n\nmeta def fail_if_nil : parser_tactic string \u2192 parser_tactic string :=\n\u03bb p, do x <- p, guard (x \u2260 \"\"), return x\n\nmeta def fail_if_nil' {\u03b1} [decidable_eq \u03b1] : parser_tactic (list \u03b1) \u2192 parser_tactic (list \u03b1) :=\n\u03bb p, do x <- p, guard (x \u2260 []), return x\n\nmeta def fail_if_state_nil {\u03b1} (p : parser_tactic \u03b1) : parser_tactic \u03b1 :=\n(get_state >>= \u03bb arg, guard (arg \u2260 \"\")) >> p\n\nmeta def list.mcons {m} [monad m] {\u03b1} (x : \u03b1) (xs : list \u03b1) : m (list \u03b1) :=\nreturn (x::xs)\n\nmeta def repeat {\u03b1} (p : parser_tactic \u03b1) : parser_tactic (list \u03b1) :=\n(do a  <- p,\n    as <- repeat,\n    return (a::as)) <|> return []\n\nmeta def repeat1 {\u03b1 : Type} : parser_tactic \u03b1 \u2192 parser_tactic (list \u03b1) :=\n\u03bb 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' {\u03b1} (p : parser_tactic \u03b1) : parser_tactic bool :=\nsucceeds $ get_state >>= (run_parser p)\n\nmeta def fail_iff_succeeds {\u03b1} (p : parser_tactic \u03b1) : parser_tactic unit :=\nsucceeds' p >>= \u03bb 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 {\u03b1 \u03b2} (p : parser_tactic \u03b1) (q : parser_tactic \u03b2) : parser_tactic (\u03b1 \u00d7 list \u03b2) :=\n   repeat (fail_iff_succeeds p *> q) >>= \u03bb _, prod.mk <$> p <*> return \u2039_\u203a\n\n/--\n`until' p q` runs q until p succeeds, and returns the result of p\n-/\nmeta def until' {\u03b1 \u03b2} (p : parser_tactic \u03b1) (q : parser_tactic \u03b2) : parser_tactic \u03b1 :=\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'' {\u03b1 \u03b2} (p : parser_tactic \u03b1) (q : parser_tactic \u03b2) : parser_tactic (list \u03b2) :=\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 \u2192 parser_tactic string := \u03bb arg,\nuntil'' (str arg) item\n\nmeta def not_strs : list string \u2192 parser_tactic string := \u03bb arg,\nrepeat $ succeeds (list.mfirst str arg) >>= (\u03bb b, if b then fail else item)\n\nmeta def sepby_aux {\u03b1 \u03b2} : parser_tactic \u03b1 \u2192 parser_tactic \u03b2 \u2192 parser_tactic (list \u03b1) :=\n\u03bb p sep,\n  list.cons <$> p <*> repeat (sep *> p)\n\nmeta def sepby {\u03b1 \u03b2} : parser_tactic \u03b1 \u2192 parser_tactic \u03b2 \u2192 parser_tactic (list \u03b1) :=\n\u03bb 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 \u2018chainl1\u2018 op) +++ return a\n\nchainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a\np \u2018chainl1\u2018 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 {\u03b1} (p : parser_tactic \u03b1) (op : parser_tactic (\u03b1 \u2192 \u03b1 \u2192 \u03b1)) : \u03b1 \u2192 parser_tactic \u03b1 :=\n\u03bb a,\n  (do f <- op,\n     b <- p,\n     chainl_rest (f a b)) <|> return a\n\nmeta def chainl1 {\u03b1} (p : parser_tactic \u03b1) (op : parser_tactic (\u03b1 \u2192 \u03b1 \u2192 \u03b1)) : parser_tactic \u03b1 :=\ndo a <- p, chainl_rest p op a\n\nmeta def chainl {\u03b1} : parser_tactic \u03b1 \u2192 parser_tactic (\u03b1 \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 parser_tactic \u03b1 :=\n\u03bb p op a, (chainl1 p op) <|> return a\n\nmeta def chainr_rest {\u03b1} (p : parser_tactic \u03b1) (op : parser_tactic (\u03b1 \u2192 \u03b1 \u2192 \u03b1)) : \u03b1 \u2192 parser_tactic \u03b1 :=\n\u03bb a,\n  (do f <- op,\n     b <- p,\n     chainr_rest (f b a)) <|> return a\n\nmeta def chainr1 {\u03b1} (p : parser_tactic \u03b1) (op : parser_tactic (\u03b1 \u2192 \u03b1 \u2192 \u03b1)) : parser_tactic \u03b1 :=\ndo a <- p, chainr_rest p op a\n\nmeta def chainr {\u03b1} : parser_tactic \u03b1 \u2192 parser_tactic (\u03b1 \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 parser_tactic \u03b1 :=\n\u03bb 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 {\u03b1} (p : parser_tactic \u03b1) : parser_tactic \u03b1 := p <* space\n\n/-- `token' p runs p, then consumes as much whitespace as possible before discarding it. -/\nmeta def token' {\u03b1} (p : parser_tactic \u03b1) : parser_tactic \u03b1 := p <* whitespace\n\nmeta def symb : string \u2192 parser_tactic string := token \u2218 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 : \u2115 \u2192 list \u2115 \u2192 \u2115\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 \u2115 \u2192 \u2115 := \u03bb xs, from_base_10_aux xs.length xs\n\nmeta def digit' : parser_tactic \u2115 :=\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 \u2115 := (repeat digit') >>= return \u2218 from_base_10\n\nmeta def number : parser_tactic \u2115 := (fail_if_nil' (repeat digit')) >>= return \u2218 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) : \u03a0 k : \u2115, 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' {\u03b1} (p : parser_tactic \u03b1) (arg_right) (arg_left) : parser_tactic \u03b1 :=\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 \u2218 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 {\u03b1} (p : parser_tactic \u03b1) : string \u2192 tactic (\u03b1 \u00d7 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 \u2192 parser_tactic string) : string \u2192 parser_tactic string :=\n\u03bb 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-- \u27e8begin intro f, have := (reflected.has_to_tactic_format f).1 ,\n--        apply this, apply_instance end\u27e9\n\n-- meta def parse_preformula_aux : parser_tactic (preformula L_empty 0) :=\n-- token' (str \"\u2200\") >> parse_preformula_aux >>= (\u03bb x, return (preformula.all x)) <|>\n-- (repeat item) *> return (&0 \u2243 &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 : \u2115) :=\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 : \u2115} (\u03c3 : formula_state k) : tactic (list name) :=\n-- -- \u03c3.bound_var >>= (\u03bb x, (\u03c3.free_var >>= (\u03bb y, return (x ++ y))))\n\n-- meta def parse_preformula {k : \u2115} (\u03c3 : formula_state k) : parser_tactic (formula_state 0) :=\n-- do token' (str \"\u2200\"),\n--    v <- (alphanumeric_token),\n--    let foo := \u2115 in\n--    return (formula_state.mk (\u03c3.bound_var ++ [v]) (\u03c3.free_var) foo )\n-- -- TODO(jesse) finish this\n\n-- -- @formula_state.mk 0 (\u03c3.bound_var.append ([\u2191v] : list _)) \u03c3.free_var (parse_preformula >>= _\n\n-- -- meta def parse_preformula : parser_tactic (\u03a3k, preformula L_empty k) :=\n-- -- do token' (str \"\u2200\") >> (parse_preformula >>= \u03bb x, return \u27e8x.fst, x.2\u27e9)\n\n-- -- run_cmd run' parse_preformula_aux \"\u2200 \u2200 \u2200 \u2200 foo\"\n\n-- -- fol.preterm.var : \u03a0 {L : Language}, \u2115 \u2192 preterm L 0\n-- -- fol.preterm.func : \u03a0 {L : Language} {l : \u2115}, L.functions l \u2192 preterm L l\n-- -- fol.preterm.app : \u03a0 {L : Language} {l : \u2115}, preterm L (l + 1) \u2192 preterm L 0 \u2192 preterm L l\n\n-- -- fol.preformula.falsum : \u03a0 {L : Language}, preformula L 0\n-- -- fol.preformula.equal : \u03a0 {L : Language}, term L \u2192 term L \u2192 preformula L 0\n-- -- fol.preformula.rel : \u03a0 {L : Language} {l : \u2115}, L.relations l \u2192 preformula L l\n-- -- fol.preformula.apprel : \u03a0 {L : Language} {l : \u2115}, preformula L (l + 1) \u2192 term L \u2192 preformula L l\n-- -- fol.preformula.imp : \u03a0 {L : Language}, preformula L 0 \u2192 preformula L 0 \u2192 preformula L 0\n-- -- fol.preformula.all : \u03a0 {L : Language}, preformula L 0 \u2192 preformula L 0\n\n-- -- \u2200 x, x = x \u2227 (f x y = 3)\n\n-- meta def parse_eq : parser_tactic $ term L_empty \u2192 term L_empty \u2192 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\u2081 foo\u2082 foo\u2083 foo\u2084 foo\u2085\"\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 \u2192 factor\n     | of_expr          : expr  \u2192 factor\nwith term : Type\n     | of_factor        : factor \u2192 term\n     | of_mulop         : mulop \u2192 term \u2192 factor \u2192 term\nwith expr : Type\n     | of_term          : term \u2192 expr\n     | of_addop         : addop \u2192 expr \u2192 term \u2192 expr\n\ndef term.of_digit := term.of_factor \u2218 factor.of_digit\n\ndef expr.of_digit := expr.of_term \u2218 term.of_digit\n\nmeta mutual def eval_addop,eval_mulop,eval_digit,eval_factor,eval_term,eval_expr\nwith eval_addop                : addop \u2192 \u2115 \u2192 \u2115 \u2192 \u2115\n     | addop.plus              := (nat.add)\n     | addop.minus             := (nat.sub)\nwith eval_mulop                : mulop \u2192 \u2115 \u2192 \u2115 \u2192 \u2115\n     | mulop.mult              := (nat.mul)\n     | mulop.div               := (nat.div)\nwith eval_digit                : digit \u2192 \u2115\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 \u2192 \u2115\n     | (factor.of_digit k)     := eval_digit k         \n     | (factor.of_expr e)      := eval_expr e\nwith eval_term                 : term \u2192 \u2115\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 \u2192 \u2115\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 : \u2115 \u2192 format := nat.has_to_format.to_format\n\nmeta instance format_digit : has_to_format digit :=\n\u27e8\u03bb x, nat.to_fmt (eval_digit x)\u27e9\n\nmeta instance format_factor : has_to_format factor :=\n\u27e8\u03bb x, nat.to_fmt (eval_factor x)\u27e9\n\nmeta instance format_term : has_to_format term :=\n\u27e8\u03bb x, nat.to_fmt (eval_term x)\u27e9\n\nmeta instance format_expr : has_to_format expr := \n\u27e8\u03bb x, nat.to_fmt (eval_expr x)\u27e9\n\n\n\nmeta mutual def parse_addop,parse_mulop,parse_digit,parse_factor,parse_term,parse_expr\nwith parse_addop                : string \u2192 tactic (addop \u00d7 string)\n| arg := (token (str \"+\" >> return addop.plus <|> str \"-\" >> return addop.minus)).run arg\nwith parse_mulop                : string \u2192 tactic (mulop \u00d7 string)\n| arg := (token (str \"*\" >> return mulop.mult <|> str \"/\" >> return mulop.div)).run arg\nwith parse_digit                : string \u2192 tactic (digit \u00d7 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 \u2192 tactic (factor \u00d7 string)\n| arg := (fail_if_state_nil $ (trace \"hello\" >> (token $ (mk parse_digit) >>= return \u2218 factor.of_digit <|> (mk parse_expr) >>= return \u2218 factor.of_expr))).run arg\nwith parse_term                 : string \u2192 tactic (term \u00d7 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 \u2218 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 \u2192 tactic (expr \u00d7 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 \u2218 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\u2081 <- (mk parse_digit),\n--                  op <- (mk parse_addop),\n--                  d\u2082 <- (mk parse_digit),\n--                  return $ expr.of_addop op (expr.of_digit d\u2081) (term.of_digit d\u2082)\n\n--              )\n--         else (mk parse_digit) >>= return \u2218 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 : \u2115 \u2192 list \u2124 \u2192 \u2124\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 \u2124 \u2192 \u2124 := \u03bb xs, from_base_10_aux xs.length xs\n\nmeta def digit' : parser_tactic \u2124 :=\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 \u2124 := (repeat digit') >>= return \u2218 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 \u2192 factor\n     | of_expr          : expr  \u2192 factor\nwith term : Type\n     | of_factor        : factor \u2192 term\n     | of_mulop         : mulop \u2192 term \u2192 factor \u2192 term\nwith expr : Type\n     | of_term          : term \u2192 expr\n     | of_addop         : addop \u2192 expr \u2192 term \u2192 expr\n\ndef term.of_digit := term.of_factor \u2218 factor.of_digit\n\ndef expr.of_digit := expr.of_term \u2218 term.of_digit\n\nmeta mutual def eval_addop,eval_mulop,eval_digit,eval_factor,eval_term,eval_expr\nwith eval_addop                : addop \u2192 \u2115 \u2192 \u2115 \u2192 \u2115\n     | addop.plus              := (nat.add)\n     | addop.minus             := (nat.sub)\nwith eval_mulop                : mulop \u2192 \u2115 \u2192 \u2115 \u2192 \u2115\n     | mulop.mult              := (nat.mul)\n     | mulop.div               := (nat.div)\nwith eval_digit                : digit \u2192 \u2115\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 \u2192 \u2115\n     | (factor.of_digit k)     := eval_digit k         \n     | (factor.of_expr e)      := eval_expr e\nwith eval_term                 : term \u2192 \u2115\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 \u2192 \u2115\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 : \u2115 \u2192 format := nat.has_to_format.to_format\n\nmeta instance format_digit : has_to_format digit :=\n\u27e8\u03bb x, nat.to_fmt (eval_digit x)\u27e9\n\nmeta instance format_factor : has_to_format factor :=\n\u27e8\u03bb x, nat.to_fmt (eval_factor x)\u27e9\n\nmeta instance format_term : has_to_format term :=\n\u27e8\u03bb x, nat.to_fmt (eval_term x)\u27e9\n\nmeta instance format_expr : has_to_format expr := \n\u27e8\u03bb x, nat.to_fmt (eval_expr x)\u27e9\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 \u2192 tactic ((\u2124 \u2192 \u2124 \u2192 \u2124) \u00d7 string)\n| arg := (symb \"+\" >> return (+) <|> symb \"-\" >> return (\u03bb x y : \u2124, x - y)).run arg\nwith parse_mulop                : string \u2192 tactic ((\u2124 \u2192 \u2124 \u2192 \u2124) \u00d7 string)\n| arg := (symb \"*\" >> return (*) <|> symb \"/\" >> return (\u03bb x y : \u2124, x / y)).run arg\nwith parse_digit                : string \u2192 tactic (\u2124 \u00d7 string)\n| arg := (token $ digit').run arg\nwith parse_factor               : string \u2192 tactic (\u2124 \u00d7 string)\n| arg := (mk parse_digit <|> do symb \"(\", e <- (mk parse_expr), symb \")\", return e).run arg\nwith parse_term                 : string \u2192 tactic (\u2124 \u00d7 string)\n| arg := (chainl1 (mk parse_factor) (mk parse_mulop)).run arg\nwith parse_expr                 : string \u2192 tactic (\u2124 \u00d7 string)\n| arg := (chainl1 (mk parse_term) (mk parse_addop)).run arg\n\nmeta def calculator : parser_tactic \u2124 := 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 \u2192 my_tree\n| join : list my_tree \u2192 option string \u2192 my_tree\n\nopen my_tree\n\n-- def list.reflect {\u03b1} [has_reflect \u03b1] : has_reflect $ list \u03b1 :=\n-- begin\n--   sorry\n-- end\n\n\n\n\nmeta instance my_tree.reflect : has_reflect my_tree\n| (node arg)           := `(\u03bb x, node x).subst `(arg)\n| (join xs arg)        := (`(\u03bb 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 \u2192 format\n| (node none)           := \"\u2022 \"\n| (node $ some st)      := sformat!\"{st} \"\n| (join xs none)        := \"{\u2022 || \" ++ 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 := \u27e8my_tree_format\u27e9\n\n/-\n(a, b, c, (d, e), f) should be parsed as\n\n  none -------\u2510 \n / | \\ \\      | \na  b c  none  f\n        |  \\\n        d   e\n-/\n\nmeta mutual def my_tree_parser\u2081,my_tree_parser\u2082\nwith my_tree_parser\u2081 : string \u2192 tactic (my_tree \u00d7 string)\n| arg := ((do int <- (fail_if_nil $ delimiter'' \"(\" \")\"),\n               ts  <- (run_parser (mk my_tree_parser\u2082) 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\u2082 : string \u2192 tactic (list my_tree \u00d7 string)\n| arg := (sepby (mk my_tree_parser\u2081) (symb \",\")).run arg\n\nmeta def my_tree_parser : parser_tactic my_tree := mk my_tree_parser\u2081\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/- {\u2022 || a   |  b   |  c } -/\nrun_cmd my_tree_parser.run' \"(a, b, c)\"\n/- {\u2022 || a   |  b   |  c } -/\nrun_cmd my_tree_parser.run' \"(a,(b,c))\"\n/- {\u2022 || a   |  {\u2022 || b   |  c }} -/\nrun_cmd my_tree_parser.run' \"((a,b),c)\"\n/- {\u2022 || {\u2022 || a   |  b }  |  c } -/\nrun_cmd my_tree_parser.run' \"(a, b, c, (d, e), f)\"\n/- {\u2022 || a   |  b   |  c   |  {\u2022 || 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 \u2192 \u2115)\n\n@[derive has_reflect, derive decidable_eq]\ninductive arith_tks : Type\n| of_nat : \u2115 \u2192 arith_tks\n| plus : arith_tks\n| mul  : arith_tks\nexport arith_tks\n\nmeta def arith_tks.to_format : arith_tks \u2192 format := \u03bb x, arith_tks.cases_on x (\u03bb n, (to_fmt n)) (to_fmt \"+\") (to_fmt \"*\")\n\nmeta instance arith_tks.has_to_format : has_to_format arith_tks :=\n\u27e8arith_tks.to_format\u27e9\n\ninstance : has_coe \u2115 arith_tks :=\n\u27e8of_nat\u27e9\n\ndef arith_Tokens : Tokens :=\n{ tks := arith_tks,\n  prec := arith_tks.rec (\u03bb _, 0) 10 15 }\n\ninstance arith_tks_Tokens_coe : has_coe arith_tks arith_Tokens.tks := \u27e8id\u27e9\n\ninductive tdop_parse_tree (Tks : Tokens) : Type\n| node : Tks.tks \u2192 tdop_parse_tree\n| join : list tdop_parse_tree \u2192 Tks.tks \u2192 tdop_parse_tree\nexport tdop_parse_tree\n\nmeta instance arith_tree_reflect : \u03a0 \u03c4 : tdop_parse_tree arith_Tokens, reflected \u03c4\n| (node l)                  := `(\u03bb x, node x).subst `(l)\n| (join \u03c4s l)               := (\u03bb y, `(\u03bb x, join x y).subst (by {haveI := arith_tree_reflect, exact (list.reflect \u03c4s)})) l\n\ndef tdop_parse_tree.make_branch {Tks : Tokens} (\u03c4 : tdop_parse_tree Tks) (\u03c4\u2080 : tdop_parse_tree Tks) : tdop_parse_tree Tks :=\nbegin\n  induction \u03c4 with n j label,\n    { exact tdop_parse_tree.join ([\u03c4\u2080]) n },\n    { exact join (\u03c4\u2080 :: j) label }\nend\n\ndef tdop_parse_tree.insert {Tks : Tokens} (\u03c4 : tdop_parse_tree Tks) (tk : Tks.tks) : tdop_parse_tree Tks :=\n\u03c4.make_branch (node tk)\n\ndef my_tdop_parse_tree : tdop_parse_tree arith_Tokens :=\njoin [node (1 : \u2115), node (2 : \u2115)] plus\n\nmeta def of.mk {\u03b1 : Type} [has_reflect \u03b1] {Tks : Tokens} (Tks_eval : (tdop_parse_tree Tks) \u2192 tactic \u03b1) (\u03c4 : tdop_parse_tree Tks) : tactic unit :=\ndo a <- (Tks_eval \u03c4), tactic.exact `(a)\n\nsection arith_eval\n\ninstance : has_add $ option \u2115 :=\n\u27e8\u03bb k\u2081 k\u2082,\noption.cases_on k\u2081 (option.cases_on k\u2082 none (\u03bb _, none)) (option.cases_on k\u2082 (\u03bb _, none) (\u03bb n\u2081 n\u2082, return $ n\u2081 + n\u2082))\u27e9\n\ninstance : has_mul $ option \u2115 :=\n\u27e8\u03bb k\u2081 k\u2082,\noption.cases_on k\u2081 (option.cases_on k\u2082 none (\u03bb _, none)) (option.cases_on k\u2082 (\u03bb _, none) (\u03bb n\u2081 n\u2082, return $ n\u2081 * n\u2082))\u27e9\n\nmeta def arith_Tokens_eval : tdop_parse_tree arith_Tokens \u2192 option \u2115\n| (node arg) := arith_tks.cases_on arg pure none none\n| (join xs arg) := arith_tks.cases_on arg (\u03bb _, 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 \u2192 tactic unit :=\nof.mk (\u03bb x, arith_Tokens_eval x)\n\nmeta def my_three : \u2115 := 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 : \u03a0 (left : tdop_parse_tree arith_Tokens), string \u2192 tactic (tdop_parse_tree arith_Tokens \u00d7 string)\n| left arg := (do n <- (token number), return (left.insert (of_nat n))).run arg\n\nmeta def parse_plus : \u03a0 (left : tdop_parse_tree arith_Tokens), string \u2192 tactic (tdop_parse_tree arith_Tokens \u00d7 string)\n| left arg := (token (str \"+\") >> return ((node plus : tdop_parse_tree arith_Tokens).make_branch left)).run arg\n\nmeta def parse_mul  : \u03a0 (left : tdop_parse_tree arith_Tokens), string \u2192 tactic (tdop_parse_tree arith_Tokens \u00d7 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' : \u03a0 (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 : \u03a0 flag : bool, \u03a0 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 \u03c4 := (arith_tdop_parser' \u03c4 >>= arith_tdop_parser_aux tt) <|> return \u03c4\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) \u2192 format\n| (node l) := arith_tks.to_format l\n| (join \u03c4s l) := \"( \" ++ (tdop_arith.to_format $ node l) ++ \" || \" ++ (string.join (((\u03c4s.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) := \u27e8tdop_arith.to_format\u27e9\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": "import Lean\n\nset_option linter.missingDocs false\nset_option linter.all true\n\ndef explicitlyUsedVariable (x : Nat) : Nat :=\n  x\n\ntheorem implicitlyUsedVariable : P \u2227 Q \u2192 Q := by\n  intro HPQ\n  have HQ : Q := by exact And.right HPQ\n  assumption\n\naxiom axiomVariable (x : Prop) : True\n\ndef unusedVariables (x : Nat) : Nat :=\n  let y := 5\n  3\n\ndef usedAndUnusedVariables : Nat :=\n  let x : Nat :=\n    let x := 5\n    3\n  x\n\ndef unusedWhereVariable : Nat :=\n  3\nwhere\n  x := 5\n\ndef unusedWhereArgument : Nat :=\n  f 2\nwhere\n  f (x : Nat) := 3\n\ndef unusedWhereFunction : Nat :=\n  2\nwhere\n  f (x : Nat) := 3\n\ndef unusedFunctionArgument : Nat :=\n  (fun x => 3) (x := 2)\n\ndef unusedTypedFunctionArgument : Nat :=\n  (fun (x : Nat) => 3) 2\n\ndef pattern (x y : Option Nat) : Nat :=\n  match x with\n  | some z =>\n    match y with\n    | some z => 1\n    | none => 0\n  | none => 0\n\ndef patternLet (x : Option Nat) : Nat :=\n  if let some y := x then\n    0\n  else\n    1\n\ndef patternMatches (x : Option Nat) : Nat :=\n  if x matches some y then\n    0\n  else\n    1\n\ndef implicitVariables {\u03b1 : Type} [inst : ToString \u03b1] : Nat := 4\n\ndef autoImplicitVariable [Inhabited \u03b1] := 5\n\ndef unusedArrow : (x : Nat) \u2192 Nat := fun x => x\n\ndef mutVariable (x : Nat) : Nat := Id.run <| do\n  let mut y := 5\n  if x == 5 then\n    y := 3\n  y\n\ndef mutVariableDo (list : List Nat) : Nat := Id.run <| do\n  let mut sum := 0\n  for elem in list do\n    sum := sum + elem\n  return sum\n\ndef mutVariableDo2 (list : List Nat) : Nat := Id.run <| do\n  let mut sum := 0\n  for _ in list do\n    sum := sum.add 1\n  return sum\n\n\ndef unusedVariablesPattern (_x : Nat) : Nat :=\n  let _y := 5\n  3\n\nset_option linter.unusedVariables false in\ndef nolintUnusedVariables (x : Nat) : Nat :=\n  let y := 5\n  3\n\nset_option linter.all false in\ndef nolintAll (x : Nat) : Nat :=\n  let y := 5\n  3\n\nset_option linter.all false in\nset_option linter.unusedVariables true in\ndef lintUnusedVariables (x : Nat) : Nat :=\n  let y := 5\n  3\n\n\nset_option linter.unusedVariables.funArgs false in\ndef nolintFunArgs (w : Nat) : Nat :=\n  let a := 5\n  let f (x : Nat) := 3\n  let g := fun (y : Nat) => 3\n  f <| g <| h <| 2\nwhere\n  h (z : Nat) := 3\n\nset_option linter.unusedVariables.patternVars false in\ndef nolintPatternVars (x : Option (Option Nat)) : Nat :=\n  match x with\n  | some (some y) => (fun z => 1) 2\n  | _ => 0\n\nset_option linter.unusedVariables.patternVars false in\ntheorem nolintPatternVarsInduction (n : Nat) : True := by\n  induction n with\n  | zero => exact True.intro\n  | succ m =>\n    have h : True := by simp\n    exact True.intro\n\n\ninductive Foo (\u03b1 : Type)\n  | foo (x : Nat) (y : Nat)\n\nstructure Bar (\u03b1 : Type) where\n  bar (x : Nat) : Nat\n  bar' (x : Nat) : Nat := 3\n\nclass Baz (\u03b1 : Type) where\n  baz (x : Nat) : Nat\n  baz' (x : Nat) : Nat :=\n    let y := 5\n    3\n\ninstance instBaz (\u03b1 \u03b2 : Type) : Baz \u03b1 where\n  baz (x : Nat) := 5\n\n\nstructure State where\n  fieldA : Nat\n  fieldB : Nat\n\nabbrev M := StateT State Id\n\ndef modifyState : M Unit := do\n  let s \u2190 get\n  modify fun s => { s with fieldA := s.fieldA + 1 }\n\ndef modifyState' : M Unit := do\n  modify fun s => { s with fieldA := 1}\n\ndef modifyStateUnnecessaryWith : M Unit := do\n  modify fun s => { s with fieldA := 1, fieldB := 2 }\n\n\ndef universeParam.{u} (T : Type u) (t : T) : T := t\n\n\nopen Lean in\ninitialize tc : Unit \u2190 registerTraceClass `Baz\n\nregister_option opt : Nat := {\n  defValue := 3\n  descr := \"test option\"\n}\n\n\nopaque foo (x : Nat) : Nat\nopaque foo' (x : Nat) : Nat :=\n  let y := 5\n  3\nvariable (bar)\nvariable (bar' : (x : Nat) \u2192 Nat)\nvariable {\u03b1 \u03b2} [inst : ToString \u03b1]\n\n@[specialize]\ndef specializeDef (x : Nat) : Nat := 3\n\n@[implemented_by specializeDef]\ndef implementedByDef (x : Nat) : Nat :=\n  let y := 3\n  5\n\n@[extern \"test\"]\ndef externDef (x : Nat) : Nat :=\n  let y := 3\n  5\n\n@[extern \"test\"]\nopaque externConst (x : Nat) : Nat :=\n  let y := 3\n  5\n\n\nmacro \"useArg \" name:declId arg:ident : command => `(def $name ($arg : \u03b1) : \u03b1 := $arg)\nuseArg usedMacroVariable a\n\nmacro \"doNotUseArg \" name:declId arg:ident : command => `(def $name ($arg : \u03b1) : Nat := 3)\ndoNotUseArg unusedMacroVariable b\n\nmacro \"ignoreArg \" id:declId sig:declSig : command => `(opaque $id $sig)\nignoreArg ignoredMacroVariable (x : UInt32) : UInt32\n\n\ntheorem not_eq_zero_of_lt (h : b < a) : a \u2260 0 := by -- *not* unused\n  cases a\n  exact absurd h (Nat.not_lt_zero _)\n  apply Nat.noConfusion\n\n-- should not be reported either\nexample (a : Nat) : Nat := _\nexample (a : Nat) : Nat := sorry\nexample (a : sorry) : Nat := 0\nexample (a : Nat) : Nat := by\n\ntheorem Fin.eqq_of_val_eq {n : Nat} : \u2200 {x y : Fin n}, x.val = y.val \u2192 x = y\n  | \u27e8_, _\u27e9, _, rfl => rfl\n\ndef Nat.discriminate (n : Nat) (H1 : n = 0 \u2192 \u03b1) (H2 : \u2200 m, n = succ m \u2192 \u03b1) : \u03b1 :=\n  match n with\n  | 0 => H1 rfl\n  | succ m => H2 m rfl\n\n@[unused_variables_ignore_fn]\ndef ignoreEverything : Lean.Linter.IgnoreFunction :=\n  fun _ _ _ => true\n\ndef ignored (x : Nat) := 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/linterUnusedVariables.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.05834584224906846, "lm_q1q2_score": 0.020549509615206962}}
{"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.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Util.CollectMVars\nimport Lean.Meta.Basic\n\nnamespace Lean.Meta\n\n/--\n  Data for user-defined theorems marked with the `congr` attribute.\n\n  This type should be confused with `CongrTheorem` which reprents different kinds of automatically\n  generated congruence theorems. The `simp` tactic also uses some of them.\n-/\nstructure SimpCongrTheorem where\n  theoremName   : Name\n  funName       : Name\n  hypothesesPos : Array Nat\n  priority      : Nat\nderiving Inhabited, Repr\n\nstructure SimpCongrTheorems where\n  lemmas : SMap Name (List SimpCongrTheorem) := {}\n  deriving Inhabited, Repr\n\ndef SimpCongrTheorems.get (d : SimpCongrTheorems) (declName : Name) : List SimpCongrTheorem :=\n  match d.lemmas.find? declName with\n  | none    => []\n  | some cs => cs\n\ndef addSimpCongrTheoremEntry (d : SimpCongrTheorems) (e : SimpCongrTheorem) : SimpCongrTheorems :=\n  { d with lemmas :=\n      match d.lemmas.find? e.funName with\n      | none    => d.lemmas.insert e.funName [e]\n      | some es => d.lemmas.insert e.funName <| insert es }\nwhere\n  insert : List SimpCongrTheorem \u2192 List SimpCongrTheorem\n    | []     => [e]\n    | e'::es => if e.priority \u2265 e'.priority then e::e'::es else e' :: insert es\n\nbuiltin_initialize congrExtension : SimpleScopedEnvExtension SimpCongrTheorem SimpCongrTheorems \u2190\n  registerSimpleScopedEnvExtension {\n    name           := `congrExt\n    initial        := {}\n    addEntry       := addSimpCongrTheoremEntry\n    finalizeImport := fun s => { s with lemmas := s.lemmas.switch }\n  }\n\ndef mkSimpCongrTheorem (declName : Name) (prio : Nat) : MetaM SimpCongrTheorem := withReducible do\n  let c \u2190 mkConstWithLevelParams declName\n  let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType c)\n  match type.eq? with\n  | none => throwError \"invalid 'congr' theorem, equality expected{indentExpr type}\"\n  | some (_, lhs, rhs) =>\n    lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do\n      unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do\n        throwError \"invalid 'congr' theorem, equality left/right-hand sides must be applications of the same function{indentExpr type}\"\n      let mut foundMVars : MVarIdSet := {}\n      for lhsArg in lhsArgs do\n        for mvarId in (lhsArg.collectMVars {}).result do\n          foundMVars := foundMVars.insert mvarId\n      let mut i := 0\n      let mut hypothesesPos := #[]\n      for x in xs, bi in bis do\n        if bi.isExplicit && !foundMVars.contains x.mvarId! then\n          let rhsFn? \u2190 forallTelescopeReducing (\u2190 inferType x) fun ys xType => do\n            match xType.eq? with\n            | none => pure none -- skip\n            | some (_, xLhs, xRhs) =>\n              let mut j := 0\n              for y in ys do\n                let yType \u2190 inferType y\n                unless onlyMVarsAt yType foundMVars do\n                  throwError \"invalid 'congr' theorem, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}\"\n                j := j + 1\n              unless onlyMVarsAt xLhs foundMVars do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}\"\n              let xRhsFn := xRhs.getAppFn\n              unless xRhsFn.isMVar do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}\"\n              unless !foundMVars.contains xRhsFn.mvarId! do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}\"\n              for arg in xRhs.getAppArgs do\n                unless arg.isFVar do\n                  throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}\"\n              pure (some xRhsFn)\n          match rhsFn? with\n          | none       => pure ()\n          | some rhsFn =>\n            foundMVars    := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId!\n            hypothesesPos := hypothesesPos.push i\n        i := i + 1\n      trace[Meta.debug] \"c: {c} : {type}\"\n      return {\n        theoremName   := declName\n        funName       := lhsFn.constName!\n        hypothesesPos := hypothesesPos\n        priority      := prio\n      }\nwhere\n  /-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/\n  onlyMVarsAt (t : Expr) (mvarSet : MVarIdSet) : Bool :=\n    Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId!\n\ndef addSimpCongrTheorem (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n  let lemma \u2190 mkSimpCongrTheorem declName prio\n  congrExtension.add lemma attrKind\n\nbuiltin_initialize\n  registerBuiltinAttribute {\n    name  := `congr\n    descr := \"congruence theorem\"\n    add   := fun declName stx attrKind => do\n      let prio \u2190 getAttrParamOptPrio stx[1]\n      discard <| addSimpCongrTheorem declName attrKind prio |>.run {} {}\n  }\n\ndef getSimpCongrTheorems : MetaM SimpCongrTheorems :=\n  return congrExtension.getState (\u2190 getEnv)\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/SimpCongrTheorems.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.04603389847295305, "lm_q1q2_score": 0.020509461382713666}}
{"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<http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html>\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\u2080 u\u2081 v\u2080 v\u2081 \n\nnamespace Mathlib\n\nstructure monad_cont.label (\u03b1 : Type w) (m : Type u \u2192 Type v) (\u03b2 : Type u) \nwhere\n  apply : \u03b1 \u2192 m \u03b2\n\ndef monad_cont.goto {\u03b1 : Type u_1} {\u03b2 : Type u} {m : Type u \u2192 Type v} (f : monad_cont.label \u03b1 m \u03b2) (x : \u03b1) : m \u03b2 :=\n  monad_cont.label.apply f x\n\nclass monad_cont (m : Type u \u2192 Type v) \nwhere\n  call_cc : {\u03b1 \u03b2 : Type u} \u2192 (monad_cont.label \u03b1 m \u03b2 \u2192 m \u03b1) \u2192 m \u03b1\n\nclass is_lawful_monad_cont (m : Type u \u2192 Type v) [Monad m] [monad_cont m] \nextends is_lawful_monad m\nwhere\n  call_cc_bind_right : \u2200 {\u03b1 \u03c9 \u03b3 : Type u} (cmd : m \u03b1) (next : monad_cont.label \u03c9 m \u03b3 \u2192 \u03b1 \u2192 m \u03c9),\n  (monad_cont.call_cc fun (f : monad_cont.label \u03c9 m \u03b3) => cmd >>= next f) =\n    do \n      let x \u2190 cmd \n      monad_cont.call_cc fun (f : monad_cont.label \u03c9 m \u03b3) => next f x\n  call_cc_bind_left : \u2200 {\u03b1 : Type u} (\u03b2 : Type u) (x : \u03b1) (dead : monad_cont.label \u03b1 m \u03b2 \u2192 \u03b2 \u2192 m \u03b1),\n  (monad_cont.call_cc fun (f : monad_cont.label \u03b1 m \u03b2) => monad_cont.goto f x >>= dead f) = pure x\n  call_cc_dummy : \u2200 {\u03b1 \u03b2 : Type u} (dummy : m \u03b1), (monad_cont.call_cc fun (f : monad_cont.label \u03b1 m \u03b2) => dummy) = dummy\n\ndef cont_t (r : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type w) :=\n  (\u03b1 \u2192 m r) \u2192 m r\n\ndef cont (r : Type u) (\u03b1 : Type w) :=\n  cont_t r id \u03b1\n\nnamespace cont_t\n\n\ndef run {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} : cont_t r m \u03b1 \u2192 (\u03b1 \u2192 m r) \u2192 m r :=\n  id\n\ndef map {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} (f : m r \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b1 :=\n  f \u2218 x\n\ntheorem run_cont_t_map_cont_t {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} (f : m r \u2192 m r) (x : cont_t r m \u03b1) : run (map f x) = f \u2218 run x :=\n  rfl\n\ndef with_cont_t {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} {\u03b2 : Type w} (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b2 :=\n  fun (g : \u03b2 \u2192 m r) => x (f g)\n\ntheorem run_with_cont_t {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} {\u03b2 : Type w} (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) : run (with_cont_t f x) = run x \u2218 f :=\n  rfl\n\nprotected theorem ext {r : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type w} {x : cont_t r m \u03b1} {y : cont_t r m \u03b1} (h : \u2200 (f : \u03b1 \u2192 m r), run x f = run y f) : x = y :=\n  funext fun (x_1 : \u03b1 \u2192 m r) => h x_1\n\nprotected instance monad {r : Type u} {m : Type u \u2192 Type v} : Monad (cont_t r m) := sorry\n\nprotected instance is_lawful_monad {r : Type u} {m : Type u \u2192 Type v} : is_lawful_monad (cont_t r m) :=\n  is_lawful_monad.mk\n    (fun (\u03b1 \u03b2 : Type u_1) (x : \u03b1) (f : \u03b1 \u2192 cont_t r m \u03b2) =>\n      cont_t.ext fun (f_1 : \u03b2 \u2192 m r) => Eq.refl (run (pure x >>= f) f_1))\n    fun (\u03b1 \u03b2 \u03b3 : Type u_1) (x : cont_t r m \u03b1) (f : \u03b1 \u2192 cont_t r m \u03b2) (g : \u03b2 \u2192 cont_t r m \u03b3) =>\n      cont_t.ext fun (f_1 : \u03b3 \u2192 m r) => Eq.refl (run (x >>= f >>= g) f_1)\n\ndef monad_lift {r : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} : m \u03b1 \u2192 cont_t r m \u03b1 :=\n  fun (x : m \u03b1) (f : \u03b1 \u2192 m r) => x >>= f\n\nprotected instance has_monad_lift {r : Type u} {m : Type u \u2192 Type v} [Monad m] : has_monad_lift m (cont_t r m) :=\n  has_monad_lift.mk fun (\u03b1 : Type u) => monad_lift\n\ntheorem monad_lift_bind {r : Type u} {m : Type u \u2192 Type v} [Monad m] [is_lawful_monad m] {\u03b1 : Type u} {\u03b2 : Type u} (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) : monad_lift (x >>= f) = monad_lift x >>= monad_lift \u2218 f := sorry\n\nprotected instance monad_cont {r : Type u} {m : Type u \u2192 Type v} : monad_cont (cont_t r m) :=\n  monad_cont.mk\n    fun (\u03b1 \u03b2 : Type u_1) (f : label \u03b1 (cont_t r m) \u03b2 \u2192 cont_t r m \u03b1) (g : \u03b1 \u2192 m r) =>\n      f (monad_cont.label.mk fun (x : \u03b1) (h : \u03b2 \u2192 m r) => g x) g\n\nprotected instance is_lawful_monad_cont {r : Type u} {m : Type u \u2192 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 \u2192 Type v} (\u03b5 : outParam (Type u_1)) [monad_except \u03b5 m] : monad_except \u03b5 (cont_t r m) :=\n  monad_except.mk (fun (x : Type u_2) (e : \u03b5) (f : x \u2192 m r) => throw e)\n    fun (\u03b1 : Type u_2) (act : cont_t r m \u03b1) (h : \u03b5 \u2192 cont_t r m \u03b1) (f : \u03b1 \u2192 m r) => catch (act f) fun (e : \u03b5) => h e f\n\nprotected instance monad_run {r : Type u} {m : Type u \u2192 Type v} : monad_run (fun (\u03b1 : Type u) => (\u03b1 \u2192 m r) \u2192 ulift (m r)) (cont_t r m) :=\n  monad_run.mk fun (\u03b1 : Type u) (f : cont_t r m \u03b1) (x : \u03b1 \u2192 m r) => ulift.up (f x)\n\nend cont_t\n\n\ndef except_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b5 : Type u} : label (except \u03b5 \u03b1) m \u03b2 \u2192 label \u03b1 (except_t \u03b5 m) \u03b2 :=\n  sorry\n\ntheorem except_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03b5 : Type u} (x : label (except \u03b5 \u03b1) m \u03b2) (i : \u03b1) : 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 \u03b5 \u03b1 \u2192 m \u03b2) => Eq.refl (goto (except_t.mk_label (monad_cont.label.mk x)) i)\n\ndef except_t.call_cc {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u} (f : label \u03b1 (except_t \u03b5 m) \u03b2 \u2192 except_t \u03b5 m \u03b1) : except_t \u03b5 m \u03b1 :=\n  except_t.mk (monad_cont.call_cc fun (x : label (except \u03b5 \u03b1) m \u03b2) => except_t.run (f (except_t.mk_label x)))\n\nprotected instance except_t.monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] : monad_cont (except_t \u03b5 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => except_t.call_cc\n\nprotected instance except_t.is_lawful_monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t \u03b5 m) :=\n  is_lawful_monad_cont.mk sorry sorry sorry\n\ndef option_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} : label (Option \u03b1) m \u03b2 \u2192 label \u03b1 (option_t m) \u03b2 :=\n  sorry\n\ntheorem option_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} (x : label (Option \u03b1) m \u03b2) (i : \u03b1) : 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 \u03b1 \u2192 m \u03b2) => Eq.refl (goto (option_t.mk_label (monad_cont.label.mk x)) i)\n\ndef option_t.call_cc {m : Type u \u2192 Type v} [Monad m] [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u} (f : label \u03b1 (option_t m) \u03b2 \u2192 option_t m \u03b1) : option_t m \u03b1 :=\n  option_t.mk (monad_cont.call_cc fun (x : label (Option \u03b1) m \u03b2) => option_t.run (f (option_t.mk_label x)))\n\nprotected instance option_t.monad_cont {m : Type u \u2192 Type v} [Monad m] [monad_cont m] : monad_cont (option_t m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => option_t.call_cc\n\nprotected instance option_t.is_lawful_monad_cont {m : Type u \u2192 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 \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03b2 : Type u} {\u03c9 : Type u} [HasOne \u03c9] : label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 label \u03b1 (writer_t \u03c9 m) \u03b2 :=\n  sorry\n\ntheorem writer_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03b2 : Type u} {\u03c9 : Type u} [HasOne \u03c9] (x : label (\u03b1 \u00d7 \u03c9) m \u03b2) (i : \u03b1) : goto (writer_t.mk_label x) i = monad_lift (goto x (i, 1)) :=\n  monad_cont.label.cases_on x fun (x : \u03b1 \u00d7 \u03c9 \u2192 m \u03b2) => Eq.refl (goto (writer_t.mk_label (monad_cont.label.mk x)) i)\n\ndef writer_t.call_cc {m : Type u \u2192 Type v} [Monad m] [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03c9 : Type u} [HasOne \u03c9] (f : label \u03b1 (writer_t \u03c9 m) \u03b2 \u2192 writer_t \u03c9 m \u03b1) : writer_t \u03c9 m \u03b1 :=\n  writer_t.mk (monad_cont.call_cc (writer_t.run \u2218 f \u2218 writer_t.mk_label))\n\nprotected instance writer_t.monad_cont {m : Type u \u2192 Type v} [Monad m] (\u03c9 : Type u) [Monad m] [HasOne \u03c9] [monad_cont m] : monad_cont (writer_t \u03c9 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => writer_t.call_cc\n\ndef state_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03c3 : Type u} : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3) \u2192 label \u03b1 (state_t \u03c3 m) \u03b2 :=\n  sorry\n\ntheorem state_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} {\u03c3 : Type u} (x : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) (i : \u03b1) : goto (state_t.mk_label x) i = state_t.mk fun (s : \u03c3) => goto x (i, s) :=\n  monad_cont.label.cases_on x fun (x : \u03b1 \u00d7 \u03c3 \u2192 m (\u03b2 \u00d7 \u03c3)) => Eq.refl (goto (state_t.mk_label (monad_cont.label.mk x)) i)\n\ndef state_t.call_cc {m : Type u \u2192 Type v} [Monad m] {\u03c3 : Type u} [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u} (f : label \u03b1 (state_t \u03c3 m) \u03b2 \u2192 state_t \u03c3 m \u03b1) : state_t \u03c3 m \u03b1 :=\n  state_t.mk\n    fun (r : \u03c3) => monad_cont.call_cc fun (f' : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) => state_t.run (f (state_t.mk_label f')) r\n\nprotected instance state_t.monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c3 : Type u} [monad_cont m] : monad_cont (state_t \u03c3 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => state_t.call_cc\n\nprotected instance state_t.is_lawful_monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c3 : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t \u03c3 m) :=\n  is_lawful_monad_cont.mk sorry sorry sorry\n\ndef reader_t.mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03b2 : Type u} (\u03c1 : Type u) : label \u03b1 m \u03b2 \u2192 label \u03b1 (reader_t \u03c1 m) \u03b2 :=\n  sorry\n\ntheorem reader_t.goto_mk_label {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u_1} {\u03c1 : Type u} {\u03b2 : Type u} (x : label \u03b1 m \u03b2) (i : \u03b1) : goto (reader_t.mk_label \u03c1 x) i = monad_lift (goto x i) :=\n  monad_cont.label.cases_on x fun (x : \u03b1 \u2192 m \u03b2) => Eq.refl (goto (reader_t.mk_label \u03c1 (monad_cont.label.mk x)) i)\n\ndef reader_t.call_cc {m : Type u \u2192 Type v} [Monad m] {\u03b5 : Type u} [monad_cont m] {\u03b1 : Type u} {\u03b2 : Type u} (f : label \u03b1 (reader_t \u03b5 m) \u03b2 \u2192 reader_t \u03b5 m \u03b1) : reader_t \u03b5 m \u03b1 :=\n  reader_t.mk fun (r : \u03b5) => monad_cont.call_cc fun (f' : label \u03b1 m \u03b2) => reader_t.run (f (reader_t.mk_label \u03b5 f')) r\n\nprotected instance reader_t.monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c1 : Type u} [monad_cont m] : monad_cont (reader_t \u03c1 m) :=\n  monad_cont.mk fun (\u03b1 \u03b2 : Type u) => reader_t.call_cc\n\nprotected instance reader_t.is_lawful_monad_cont {m : Type u \u2192 Type v} [Monad m] {\u03c1 : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t \u03c1 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081} {\u03b1\u2081 : Type u\u2080} {r\u2081 : Type u\u2080} {\u03b1\u2082 : Type u\u2081} {r\u2082 : Type u\u2081} (F : m\u2081 r\u2081 \u2243 m\u2082 r\u2082) (G : \u03b1\u2081 \u2243 \u03b1\u2082) : cont_t r\u2081 m\u2081 \u03b1\u2081 \u2243 cont_t r\u2082 m\u2082 \u03b1\u2082 :=\n  equiv.mk\n    (fun (f : cont_t r\u2081 m\u2081 \u03b1\u2081) (r : \u03b1\u2082 \u2192 m\u2082 r\u2082) => coe_fn F (f fun (x : \u03b1\u2081) => coe_fn (equiv.symm F) (r (coe_fn G x))))\n    (fun (f : cont_t r\u2082 m\u2082 \u03b1\u2082) (r : \u03b1\u2081 \u2192 m\u2081 r\u2081) =>\n      coe_fn (equiv.symm F) (f fun (x : \u03b1\u2082) => 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 tactic.lint\nimport algebra.group.basic\n\n/-! ## Commutativity lemmas should be rejected  -/\n\nattribute [simp] add_comm add_left_comm\n\nopen tactic\nrun_cmd do\ndecl \u2190 get_decl ``add_comm,\nres \u2190 linter.simp_comm.test decl,\n-- linter complains\nguard res.is_some\n\nopen tactic\nrun_cmd do\ndecl \u2190 get_decl ``add_left_comm,\nres \u2190 linter.simp_comm.test decl,\n-- linter complains\nguard res.is_some\n\n/-! ## Floris' trick should be accepted -/\n\n@[simp] lemma list.filter_congr_decidable {\u03b1} (s : list \u03b1) (p : \u03b1 \u2192 Prop) (h : decidable_pred p)\n  [decidable_pred p] : @list.filter \u03b1 p h s = s.filter p :=\nby congr\n\n-- lemma is unproblematic\nexample : @list.filter _ (\u03bb x, x > 0) (\u03bb _, classical.prop_decidable _) [1,2,3] = [1,2,3] :=\nbegin\n  -- can rewrite once\n  simp only [list.filter_congr_decidable],\n  -- but not twice\n  success_if_fail { simp only [list.filter_congr_decidable] },\n  refl\nend\n\nopen tactic\nset_option pp.all true\nrun_cmd do\ndecl \u2190 get_decl ``list.filter_congr_decidable,\nres \u2190 linter.simp_comm.test decl,\n-- linter does not complain\nguard res.is_none\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/lint_simp_comm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.051082733526088074, "lm_q1q2_score": 0.02042347223516857}}
{"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 : \u2200 S : Profinite.{u}, limits.is_zero (A.val.obj (opposite.op S))) :\n  limits.is_zero A :=\n{ unique_to := \u03bb Y, nonempty.intro\n  { default := 0,\n    uniq := \u03bb a, begin\n      ext t : 3,\n      apply (hA t.unop).eq_of_src,\n    end },\n  unique_from := \u03bb Y, nonempty.intro\n  { default := 0,\n    uniq := \u03bb 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 \u22d9 free_pfpng_functor)) :=\n    ProFiltPseuNormGrp\u2081.bounded_cone \u27e8Ab.explicit_limit_cone.{u u} _,\n      Ab.explicit_limit_cone_is_limit _\u27e9,\n  let hE : limits.is_limit E :=\n    ProFiltPseuNormGrp\u2081.bounded_cone_is_limit _,\n  let ee : S.free_pfpng \u2245 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 \u27e8s\u27e9 := 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 \u27e8\u27e8f,hf\u27e9\u27e9, 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 \u27f6 Y) [mono f]\n  (hY : limits.is_zero Y) : is_iso f :=\nbegin\n  use 0, simp, split,\n  rw \u2190 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 \u27f6\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 \u226b\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 [\u2190 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 [\u2190 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 [\u2190 category.assoc, \u2190 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 \u27f6 T) :\n  f \u226b T.to_free_pfpng = S.to_free_pfpng \u226b\n    (ProFiltPseuNormGrp\u2081.level.obj 1).map\n    ((Profinite.extend free_pfpng_functor).map f) :=\nbegin\n  apply (limits.is_limit_of_preserves (ProFiltPseuNormGrp\u2081.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\u2081.level.obj 1)\n    (limits.limit.is_limit (T.fintype_diagram \u22d9 free_pfpng_functor))).fac,\n  erw limits.limit.lift_\u03c0,\n  swap, apply_instance,\n  simp only [\u2190 functor.map_comp, limits.limit.lift_\u03c0],\n  dsimp [Profinite.change_cone],\n  simp only [functor.map_comp],\n  erw (limits.is_limit_of_preserves (ProFiltPseuNormGrp\u2081.level.obj 1)\n    (limits.limit.is_limit (S.fintype_diagram \u22d9 free_pfpng_functor))).fac_assoc,\n  erw limits.limit.lift_\u03c0_assoc,\n  ext, dsimp [Profinite.as_limit_cone, Fintype.free_pfpng_unit, free_pfpng.map,\n    ProFiltPseuNormGrp\u2081.level],\n  rcases x with \u27e8x\u27e9,\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 \u27e8finset.mem_univ _, h, rfl\u27e9 },\n    { rintros \u27e8q\u27e9 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 \u27e8q\u27e9 -, push_neg, intros hh,\n    rw \u2190 hh at h,\n    erw discrete_quotient.map_proj_apply at h,\n    contrapose! h,\n    let e : (W.comap f.2) \u2192 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 \u22d9 CondensedSet_to_Condensed_Ab \u27f6\n  Profinite.extend free_pfpng_functor \u22d9\n  PFPNG\u2081_to_CHFPNG\u2081\u2091\u2097 \u22d9\n  CHFPNG\u2081_to_CHFPNG\u2091\u2097 \u22d9\n  CompHausFiltPseuNormGrp.to_Condensed :=\n{ app := \u03bb X, X.free_to_pfpng,\n  naturality' := \u03bb S T f, begin\n    -- we should be able to precompose with the natural map `S.to_Condensed \u27f6 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 \u2190 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 \u2190 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 \u2190 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 \u27e8t\u27e9 : 7, change W.unop \u27f6 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 \u2190 comp_apply,\n    erw \u2190 comp_apply,\n    erw \u2190 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 \u22d9 PFPNG\u2081_to_CHFPNG\u2081\u2091\u2097) \u2245\n  ((Profinite.extend free_pfpng_functor \u22d9 PFPNG\u2081_to_CHFPNG\u2081\u2091\u2097) \u22d9\n    CHFPNG\u2081_to_CHFPNG\u2091\u2097) \u22d9\n    CompHausFiltPseuNormGrp.to_Condensed :=\niso_whisker_right\n  (iso_whisker_right\n    (Profinite.extend_commutes free_pfpng_functor PFPNG\u2081_to_CHFPNG\u2081\u2091\u2097).symm\n    CHFPNG\u2081_to_CHFPNG\u2091\u2097)\n  CompHausFiltPseuNormGrp.to_Condensed\n\n/-- Prop 2.1 of Analytic.pdf -/\ndef free_pfpng_profinite_iso :\n  condensify (free_pfpng_functor \u22d9 PFPNG\u2081_to_CHFPNG\u2081\u2091\u2097) \u2245\n  Profinite_to_Condensed \u22d9 CondensedSet_to_Condensed_Ab :=\nfree_pfpng_profinite_iso_aux \u226a\u226b (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 : \u2200 t, \u27e8t\u27e9 \u2192 \u27e8\u27e6t\u2223\u27e7\u27e9 :=\nbegin intros, apply is_branch.left_nl, assumption end\n\nlemma branch_left_leaf : \u2200 t, \u27e8t\u27e9 \u2192 \u27e8\u27e6t,\u25cf\u27e7\u27e9 := \nbegin intros, apply is_branch.left_l, assumption end\n\nlemma branch_right : \u2200 t, \u27e8t\u27e9 \u2192 \u27e8\u27e6\u2223t\u27e7\u27e9 :=\nbegin intros, apply is_branch.right_nl, assumption end\n\nlemma branch_right_leaf : \u2200 t, \u27e8t\u27e9 \u2192 \u27e8\u27e6\u25cf,t\u27e7\u27e9 :=\nbegin intros, apply is_branch.right_l, assumption end \n  \nmeta def auto_branch_core : tactic unit := \ndo\n  h \u2190 tactic.target,\n  match h with \n  | `(is_branch %%b):= \n      match b with \n      | `(\u25cf)      := tactic.exact `(is_branch.single)\n      | `(\u27e6%%t\u2223\u27e7) := do tactic.applyc `branch_left, auto_branch_core  \n      | `(\u27e6\u2223%%t\u27e7) := do tactic.applyc `branch_right, auto_branch_core\n      | `(\u27e6%%t,\u25cf\u27e7):= do tactic.applyc `branch_left_leaf,\n                        auto_branch_core\n      | `(\u27e6\u25cf,%%t\u27e7):= 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 \u2192 tactic unit \n| [] := tactic.skip\n| (h :: hs) := do t \u2190 tactic.infer_type h, \n                  match t with \n                  | `(%%b \u21a3 \u25cf) := tactic.replace h.to_string ``(single_grow %%b %%h)\n                  | `(height %%b \u2264 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 \u2190 tactic.local_context,\n  reduce_trivial_tree_core h\n \nmeta def rewrite_ci_core : list expr \u2192 tactic unit\n| [] := tactic.skip\n| (h :: hs) := do t \u2190 tactic.infer_type h,\n                  match t with\n                  | `(%%b = \u25cf) := 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 \u2190 tactic.local_context,\n  rewrite_ci_core h\n\nmeta def auto_grow_core : tactic unit := \n do h \u2190 tactic.target, \n   match h with \n   | `(grow %%t %%t') :=  \n          match t, t' with \n          | `(\u25cf), _ := tactic.applyc `grow.single_grow\n          | `(\u27e6%%u\u2223\u27e7), `(\u27e6%%u'\u2223\u27e7) := \n                       do tactic.applyc `grow.left_grow, \n                          auto_grow_core\n          | `(\u27e6\u2223%%v\u27e7), `(\u27e6\u2223%%v'\u27e7) := \n                       do tactic.applyc `grow.right_grow,\n                          auto_grow_core\n          | `(\u27e6%%u, %%v\u27e7), `(\u27e6%%u', %%v'\u27e7) := \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 {\u03b1 : Type u} {\u03b2 : Type v} {e : Option (\u03b1 \u00d7 \u03b2)} {v : \u03b2} : to_value e = some v \u2192 \u2203 (k : \u03b1), e = some (k, v) := sorry\n\ntheorem eq_none_of_to_value_eq_none {\u03b1 : Type u} {\u03b2 : Type v} {e : Option (\u03b1 \u00d7 \u03b2)} : to_value e = none \u2192 e = none := sorry\n\n/- Lemmas -/\n\ntheorem not_mem_mk_rbmap {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} (k : \u03b1) : \u00ack \u2208 mk_rbmap \u03b1 \u03b2 := sorry\n\ntheorem not_mem_of_empty {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} {m : rbmap \u03b1 \u03b2} (k : \u03b1) : empty m = tt \u2192 \u00ack \u2208 m := sorry\n\ntheorem not_mem_of_find_entry_none {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k : \u03b1} {m : rbmap \u03b1 \u03b2} : find_entry m k = none \u2192 \u00ack \u2208 m := sorry\n\ntheorem not_mem_of_find_none {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k : \u03b1} {m : rbmap \u03b1 \u03b2} : find m k = none \u2192 \u00ack \u2208 m := sorry\n\ntheorem mem_of_find_entry_some {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {e : \u03b1 \u00d7 \u03b2} {m : rbmap \u03b1 \u03b2} : find_entry m k\u2081 = some e \u2192 k\u2081 \u2208 m := sorry\n\ntheorem mem_of_find_some {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : find m k = some v \u2192 k \u2208 m := sorry\n\ntheorem find_entry_eq_find_entry_of_eqv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {m : rbmap \u03b1 \u03b2} {k\u2081 : \u03b1} {k\u2082 : \u03b1} : strict_weak_order.equiv k\u2081 k\u2082 \u2192 find_entry m k\u2081 = find_entry m k\u2082 := sorry\n\ntheorem find_eq_find_of_eqv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) : strict_weak_order.equiv k\u2081 k\u2082 \u2192 find m k\u2081 = find m k\u2082 := sorry\n\ntheorem find_entry_correct {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (k : \u03b1) (m : rbmap \u03b1 \u03b2) : k \u2208 m \u2194 \u2203 (e : \u03b1 \u00d7 \u03b2), find_entry m k = some e \u2227 strict_weak_order.equiv k (prod.fst e) := sorry\n\ntheorem eqv_of_find_entry_some {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : find_entry m k\u2081 = some (k\u2082, v) \u2192 strict_weak_order.equiv k\u2081 k\u2082 := sorry\n\ntheorem eq_of_find_entry_some {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : find_entry m k\u2081 = some (k\u2082, v) \u2192 k\u2081 = k\u2082 :=\n  fun (h : find_entry m k\u2081 = some (k\u2082, v)) =>\n    (fun (this : strict_weak_order.equiv k\u2081 k\u2082) => eq_of_eqv_lt this) (eqv_of_find_entry_some h)\n\ntheorem find_correct {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (k : \u03b1) (m : rbmap \u03b1 \u03b2) : k \u2208 m \u2194 \u2203 (v : \u03b2), find m k = some v := sorry\n\ntheorem constains_correct {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (k : \u03b1) (m : rbmap \u03b1 \u03b2) : k \u2208 m \u2194 contains m k = tt := sorry\n\ntheorem mem_of_mem_of_eqv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {m : rbmap \u03b1 \u03b2} {k\u2081 : \u03b1} {k\u2082 : \u03b1} : k\u2081 \u2208 m \u2192 strict_weak_order.equiv k\u2081 k\u2082 \u2192 k\u2082 \u2208 m := sorry\n\ntheorem mem_insert_of_incomp {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : \u00aclt k\u2081 k\u2082 \u2227 \u00aclt k\u2082 k\u2081 \u2192 k\u2081 \u2208 insert m k\u2082 v :=\n  fun (h : \u00aclt k\u2081 k\u2082 \u2227 \u00aclt k\u2082 k\u2081) => to_rbmap_mem (rbtree.mem_insert_of_incomp m (eqv_entries_of_eqv_keys v v h))\n\ntheorem mem_insert {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (k : \u03b1) (m : rbmap \u03b1 \u03b2) (v : \u03b2) : k \u2208 insert m k v :=\n  to_rbmap_mem (rbtree.mem_insert (k, v) m)\n\ntheorem mem_insert_of_equiv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : strict_weak_order.equiv k\u2081 k\u2082 \u2192 k\u2081 \u2208 insert m k\u2082 v :=\n  mem_insert_of_incomp m v\n\ntheorem mem_insert_of_mem {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {m : rbmap \u03b1 \u03b2} (k\u2082 : \u03b1) (v : \u03b2) : k\u2081 \u2208 m \u2192 k\u2081 \u2208 insert m k\u2082 v :=\n  fun (h : k\u2081 \u2208 m) => to_rbmap_mem (rbtree.mem_insert_of_mem (k\u2082, v) (to_rbtree_mem' v h))\n\ntheorem equiv_or_mem_of_mem_insert {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : k\u2081 \u2208 insert m k\u2082 v \u2192 strict_weak_order.equiv k\u2081 k\u2082 \u2228 k\u2081 \u2208 m := sorry\n\ntheorem incomp_or_mem_of_mem_ins {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : k\u2081 \u2208 insert m k\u2082 v \u2192 \u00aclt k\u2081 k\u2082 \u2227 \u00aclt k\u2082 k\u2081 \u2228 k\u2081 \u2208 m :=\n  equiv_or_mem_of_mem_insert\n\ntheorem eq_or_mem_of_mem_ins {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : k\u2081 \u2208 insert m k\u2082 v \u2192 k\u2081 = k\u2082 \u2228 k\u2081 \u2208 m := sorry\n\ntheorem find_entry_insert_of_eqv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (m : rbmap \u03b1 \u03b2) {k\u2081 : \u03b1} {k\u2082 : \u03b1} (v : \u03b2) : strict_weak_order.equiv k\u2081 k\u2082 \u2192 find_entry (insert m k\u2081 v) k\u2082 = some (k\u2081, v) := sorry\n\ntheorem find_entry_insert {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (m : rbmap \u03b1 \u03b2) (k : \u03b1) (v : \u03b2) : 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 {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (m : rbmap \u03b1 \u03b2) {k\u2081 : \u03b1} {k\u2082 : \u03b1} (v : \u03b2) : strict_weak_order.equiv k\u2081 k\u2082 \u2192 find (insert m k\u2081 v) k\u2082 = some v := sorry\n\ntheorem find_insert {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] (m : rbmap \u03b1 \u03b2) (k : \u03b1) (v : \u03b2) : find (insert m k v) k = some v :=\n  find_insert_of_eqv m v (refl k)\n\ntheorem find_entry_insert_of_disj {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : lt k\u2081 k\u2082 \u2228 lt k\u2082 k\u2081 \u2192 find_entry (insert m k\u2081 v) k\u2082 = find_entry m k\u2082 := sorry\n\ntheorem find_entry_insert_of_not_eqv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : \u00acstrict_weak_order.equiv k\u2081 k\u2082 \u2192 find_entry (insert m k\u2081 v) k\u2082 = find_entry m k\u2082 := sorry\n\ntheorem find_entry_insert_of_ne {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : k\u2081 \u2260 k\u2082 \u2192 find_entry (insert m k\u2081 v) k\u2082 = find_entry m k\u2082 :=\n  fun (h : k\u2081 \u2260 k\u2082) => find_entry_insert_of_not_eqv m v fun (h' : strict_weak_order.equiv k\u2081 k\u2082) => h (eq_of_eqv_lt h')\n\ntheorem find_insert_of_disj {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : lt k\u2081 k\u2082 \u2228 lt k\u2082 k\u2081 \u2192 find (insert m k\u2081 v) k\u2082 = find m k\u2082 := sorry\n\ntheorem find_insert_of_not_eqv {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : \u00acstrict_weak_order.equiv k\u2081 k\u2082 \u2192 find (insert m k\u2081 v) k\u2082 = find m k\u2082 := sorry\n\ntheorem find_insert_of_ne {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k\u2081 : \u03b1} {k\u2082 : \u03b1} (m : rbmap \u03b1 \u03b2) (v : \u03b2) : k\u2081 \u2260 k\u2082 \u2192 find (insert m k\u2081 v) k\u2082 = find m k\u2082 := sorry\n\ntheorem mem_of_min_eq {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : min m = some (k, v) \u2192 k \u2208 m :=\n  fun (h : min m = some (k, v)) => to_rbmap_mem (rbtree.mem_of_min_eq h)\n\ntheorem mem_of_max_eq {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : max m = some (k, v) \u2192 k \u2208 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 {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {m : rbmap \u03b1 \u03b2} : min m = none \u2192 m = mk_rbmap \u03b1 \u03b2 :=\n  rbtree.eq_leaf_of_min_eq_none\n\ntheorem eq_leaf_of_max_eq_none {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {m : rbmap \u03b1 \u03b2} : max m = none \u2192 m = mk_rbmap \u03b1 \u03b2 :=\n  rbtree.eq_leaf_of_max_eq_none\n\ntheorem min_is_minimal {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : min m = some (k, v) \u2192 \u2200 {k' : \u03b1}, k' \u2208 m \u2192 strict_weak_order.equiv k k' \u2228 lt k k' := sorry\n\ntheorem max_is_maximal {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_weak_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : max m = some (k, v) \u2192 \u2200 {k' : \u03b1}, k' \u2208 m \u2192 strict_weak_order.equiv k k' \u2228 lt k' k := sorry\n\ntheorem min_is_minimal_of_total {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : min m = some (k, v) \u2192 \u2200 {k' : \u03b1}, k' \u2208 m \u2192 k = k' \u2228 lt k k' := sorry\n\ntheorem max_is_maximal_of_total {\u03b1 : Type u} {\u03b2 : Type v} {lt : \u03b1 \u2192 \u03b1 \u2192 Prop} [DecidableRel lt] [is_strict_total_order \u03b1 lt] {k : \u03b1} {v : \u03b2} {m : rbmap \u03b1 \u03b2} : max m = some (k, v) \u2192 \u2200 {k' : \u03b1}, k' \u2208 m \u2192 k = k' \u2228 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 \u03b1 \u2194\n  add_group (additive \u03b1)`.\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\u03bb 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 := \u27e8\u03bb ns,\n                ns.mfoldl\n                  (\u03bb 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 \u2190 aux_attr.get_param_untyped n',\n                    pure $ dict.insert n param.app_arg.const_name)\n                  mk_name_map, []\u27e9,\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 \u2192 string \u2192 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 \u2192 list string \u2192 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 \u2192 string :=\nstring.map_tokens ''' $\n\u03bb 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 \u2260 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 \u2260 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(\u03bb 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 \u2190 optional lean.parser.ident,\n  e \u2190 optional interactive.types.texpr,\n  doc \u2190 match e with\n      | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n      | none := pure none\n      end,\n  return \u27e8tgt.get_or_else name.anonymous, doc\u27e9\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : \u2115) (f : name \u2192 tactic (list string)) :\n  command :=\ndo\n  src_fields \u2190 f src,\n  tgt_fields \u2190 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    \u03bb 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 : \u2115) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (\u03bb n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (\u03bb n, (list.map (\u03bb (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (\u03bb n, (env.constructors_of n).mmap $\n          \u03bb 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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 \u00d7 N) := \u27e8\u03bb p q, \u27e8p.1 * q.1, p.2 * q.2\u27e9\u27e9\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 \u201cmain\u201d 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 \u201cmain\u201d 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 (\u201cmul\u201d, \u201cone\u201d, \u201cinv\u201d, \u201cprod\u201d) 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 $ \u03bb src prio persistent, do\n    guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n    env \u2190 get_env,\n    val \u2190 attr.get_param src,\n    dict \u2190 aux_attr.get_cache,\n    tgt \u2190 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 : \u03b1 \u2192 Bool} : filter p [] = [] := by\n  simp!\n\ntheorem cons_eq_append (a : \u03b1) (as : List \u03b1) : a :: as = [a] ++ as := rfl\n\ntheorem filter_cons (a : \u03b1) (as : List \u03b1) :\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 \u03b1} {p : \u03b1 \u2192 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 \u2192 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 (\u03b1 : Type) := state_t (heap value) set \u03b1\n\nopen state_t\nvariables {value} {\u03b1 : Type}\ninclude value\nlocal notation `ST` := ST value\n\ndef read (p : ptr) : ST value :=\ndo m \u2190 get,\n   match m.lookup p with\n   | none := @monad_lift set _ _ _ \u2205\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 $ (\u222a heap.mk (vs.enum_from p))\n\ndef choice (p : \u03b1 \u2192 Prop) : ST \u03b1 :=\n@monad_lift set (state_t _ set) _ _ (p : set \u03b1)\n\ndef alloc (vs : list value) : ST ptr :=\ndo m \u2190 get,\n   p \u2190 choice $ \u03bb p : ptr, \u2200 i < vs.length, (p + i) \u2209 m,\n   assign_vals p vs,\n   pure p\n\nsection\n\nvariable value\n\ndef alloc' (n : \u2115) : ST ptr :=\nchoice (\u03bb v : list value, v.length = n) >>= alloc\n\ndef dealloc (p : ptr) (n : \u2115) : ST unit :=\ndo m \u2190 get,\n   modify $ erase_all p n\n\nend\n\ndef for' : \u03a0  (k : \u2115) (n : \u2115) (f : \u2115 \u2192 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 : \u03a0 (n : \u2115) (f : \u2115 \u2192 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 : \u2115) : ST ptr :=\n-- do q \u2190 alloc' value n,\n--    for n (\u03bb i,\n--      do v \u2190 read (p + i),\n--         assign (q + i) v),\n--    pure q\n\n-- def map (p : ptr) (f : \u2115 \u2192 value \u2192 value) (n : \u2115) : ST punit :=\n-- for n (\u03bb i,\n--   do v \u2190 read (p + i),\n--      assign (p + i) (f i v) )\n\nsection talloc\n\n-- open\n\nvariables (value) (\u03b1) [fixed_storable value \u03b1] (n : \u2115)\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 \u03b1)) :=\ntptr.mk _ _ <$> alloc' value (n * fixed_size value \u03b1)\n\ndef ralloc1 : ST (tptr \u03b1) :=\ntptr.mk _ _ <$> alloc' value (fixed_size value \u03b1)\n\nvariables {\u03b1}\n\nvariables {value}\n\ndef free (p : tptr (list \u03b1)) (n : \u2115) : ST unit :=\ndealloc value p.get (n * fixed_size value \u03b1)\n\nend talloc\n\n@[simp]\nlemma mem_run_modify (x : punit) (h h' : heap value) (g : heap value \u2192 heap value) :\n  (x,h') \u2208 (modify g : ST punit).run h \u2194 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 {\u03b2} (x' : \u03b2) (h h' : heap value) (f : ST \u03b1) (g : \u03b1 \u2192 ST \u03b2) :\n  (x',h') \u2208 (f >>= g).run h \u2194 (\u2203 x'' h'', (x'',h'') \u2208 f.run h \u2227 (x',h') \u2208 (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' : \u03b1) (h h' : heap value) (p : \u03b1 \u2192 Prop) :\n  (x',h') \u2208 (choice p : ST \u03b1).run h \u2194 p x' \u2227 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' : \u03b1) (h h' : heap value) :\n  (x',h') \u2208 (pure x : ST \u03b1).run h \u2194  x' = x \u2227 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') \u2208 (get : ST _).run h \u2194  x' = h \u2227 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') \u2208 (read p : ST _).run h \u2194 h.lookup p = some x' \u2227 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 \u27e8a,b,\u27e8h'',H\u27e9,H'\u27e9, cases h : (lookup p b); subst_vars; rw h at H'; simp [read] at H', cases H', casesm* _ \u2227 _,\n    subst_vars, rw h, exact \u27e8rfl,rfl\u27e9 },\n  { rintro \u27e8h,\u27e8\u27e9,\u27e8\u27e9\u27e9, refine \u27e8_,_,\u27e8rfl,rfl\u27e9,_\u27e9, simp [h,read] }\nend\n\nsection tactic\n\nopen tactic\nomit value\n\nmeta def sane_names : tactic unit :=\ndo ls \u2190 local_context,\n   ls.reverse.mmap' $ \u03bb l,\n     when (l.local_pp_name.to_string.length > 5) $ do\n       t \u2190 infer_type l,\n       n \u2190 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 \u2190 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') \u2208 (alloc (v :: vs)).run h \u2194 \u2203 h'', some h' = some h'' \u2297 some (maplet p v) \u2227 p \u2209 h \u2227 (p+1, h'') \u2208 (alloc vs).run h :=\nbegin\n  simp [alloc,assign_vals,enum_from], split; intro h; casesm * [Exists _, _ \u2227 _]; subst_vars;\n  constructor_matching* [_ \u2227 _, 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 [\u2190 union_eq_add_of_disjoint,union_comm_of_disjoint this,union_assoc],\n    rw disjoint_union_left, refine \u27e8_,this.symm\u27e9,\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 \u2190 nat.add_assoc at h_1, exact h_1, },\n  { introv hi, cases i, { exact n },\n    specialize h_1 i, rw [\u2190 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, \u2190 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') \u2208 (alloc vs).run h \u2194 some h' = some h \u2297 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\u2080 H\u2081 H\u2082,\n      simp only [*, memory.add_assoc, and_true, eq_self_iff_true], congr' 1,\n      rw memory.add_comm, },\n    { rintro H\u2080, existsi h \u222a heap.mk (enum_from (p + 1) vs_tl),\n      rw [H\u2080,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": "/-                               2019-02-19, Oberharmersbach\n\n\n\n\nInteractive theorem proving with a computer \u2014 my experience\n\n\n--                 _\n--                | | ___  __ _ _ __\n--                | |/ _ \\/ _` | '_ \\\n--                | |  __| (_| | | | |\n--                |_|\\___|\\__,_|_| |_|\n--\n\n\nA rose-colored introduction\n\n\n\n\nby Johan Commelin -/\n", "meta": {"author": "jcommelin", "repo": "oberharmersbach2019", "sha": "d2cdf780a10baa8502a9b0cae01c7efa318649a6", "save_path": "github-repos/lean/jcommelin-oberharmersbach2019", "path": "github-repos/lean/jcommelin-oberharmersbach2019/oberharmersbach2019-d2cdf780a10baa8502a9b0cae01c7efa318649a6/src/page00.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.05834583488082549, "lm_q1q2_score": 0.020341991498197456}}
{"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 (\u0393 : Type u)\n| blank : language\n| start : language\n| chr   : \u0393 \u2192 language\n\nnotation `\u2423` := language.blank \nnotation `\u2424` := language.start\n\nnamespace language\nvariables {\u0393 : Type u}\n\ninstance : inhabited (language \u0393) := \u27e8\u2423\u27e9\n\ndef language_equiv_option_sum_bool : language \u0393 \u2243 bool \u2295 \u0393 :=\n{ to_fun := \u03bb l, match l with | \u2423 := sum.inl ff | \u2424 := sum.inl tt | chr x := sum.inr x end,\n  inv_fun := \u03bb l, match l with | (sum.inl ff) := \u2423 | (sum.inl tt) := \u2424 | sum.inr x := chr x end,\n  left_inv := \u03bb l, by rcases l; simp; refl,\n  right_inv := \u03bb l, by { rcases l; simp, { rcases l; refl }, refl } }\n\ninstance [fintype \u0393] : fintype (language \u0393) := fintype.of_equiv (bool \u2295 \u0393) 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 \u2295 R) := \u27e8sum.inl state_lang.start, sum.inr state_lang.halt\u27e9\n\nend turing_machine\n\nnamespace turing_machine\nopen state_lang\n\nvariables\n  (\u0393 : Type u) -- \u8a00\u8a9e\n  (Q : Type v) [state_lang Q] -- \u72b6\u614b\n  (\u03b9 : \u2115) -- \u30c6\u30fc\u30d7\u306e\u6570\n\ninductive instruction\n| stay  : instruction\n| right : instruction\n| left  : instruction\n\nnamespace instruction\n\ninstance : inhabited instruction := \u27e8stay\u27e9\n\n@[simp] def apply : instruction \u2192 \u2115 \u2192 \u2115\n| stay  \u03b9 := \u03b9\n| right \u03b9 := \u03b9 + 1\n| left  \u03b9 := \u03b9 - 1\n\n@[simp] lemma apply_default (n) : apply default n = n := rfl\n\n@[simp] lemma default_nth (\u03b9 : \u2115) (i) : (default : vector instruction \u03b9).nth i = stay :=\nby { unfold default, simp }\n\ndef equiv_unit_sums : instruction \u2243 unit \u2295 unit \u2295 unit :=\n{ to_fun := \u03bb i, match i with | stay := sum.inl () | right := sum.inr (sum.inl ()) | left := sum.inr (sum.inr ()) end,\n  inv_fun := \u03bb i, match i with | sum.inl () := stay | sum.inr (sum.inl ()) := right | sum.inr (sum.inr ()) := left end,\n  left_inv := \u03bb i, by rcases i; refl,\n  right_inv := \u03bb i, by { rcases i; simp, rcases i, refl, rcases i; rcases i; refl } }\n\ninstance : fintype instruction := fintype.of_equiv (unit \u2295 unit \u2295 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 {\u03b9}\n\ndef Stay : vector instruction \u03b9 := vector.repeat stay \u03b9\n\n@[simp] lemma Stay_nth (i : fin \u03b9) : Stay.nth i = stay := by simp[Stay]\n\ndef Right : vector instruction \u03b9 := vector.repeat right \u03b9\n\n@[simp] lemma Right_nth (i : fin \u03b9) : Right.nth i = right := by simp[Right]\n\ndef Left : vector instruction \u03b9 := vector.repeat left \u03b9\n\n@[simp] lemma Left_nth (i : fin \u03b9) : Left.nth i = left := by simp[Left]\n\nend instruction\n\nstructure word :=\n(c : Q)\n(z : vector \u0393 \u03b9)\n(u : vector instruction \u03b9)\n(q : Q)\n(x : vector \u0393 \u03b9)\n\nnotation `\u27ee` c `, ` z `; ` u ` | ` q `, ` x `\u27ef`:80 := word.mk c z u q x\n\nnamespace word\n\ndef equiv_prod : word \u0393 Q \u03b9 \u2243 Q \u00d7 vector \u0393 \u03b9 \u00d7 vector instruction \u03b9 \u00d7 Q \u00d7 vector \u0393 \u03b9 :=\n{ to_fun := \u03bb w, match w with \u27eec, z; u | q, x\u27ef := (c, z, u, q, x) end,\n  inv_fun := \u03bb w, match w with (c, z, u, q, x) := \u27eec, z; u | q, x\u27ef end,\n  left_inv := \u03bb w, by rcases w; refl,\n  right_inv := \u03bb w, by rcases w with \u27e8_, w\u27e9; rcases w with \u27e8_, w\u27e9; rcases w with \u27e8_, w\u27e9; rcases w with \u27e8_, w\u27e9; refl }\n\nopen fintype\n\ninstance [fintype \u0393] [fintype Q] : fintype (word \u0393 Q \u03b9) :=\nfintype.of_equiv (Q \u00d7 vector \u0393 \u03b9 \u00d7 vector instruction \u03b9 \u00d7 Q \u00d7 vector \u0393 \u03b9) (equiv_prod _ _ _).symm\n\nlemma card [fintype \u0393] [fintype Q] : card (word \u0393 Q \u03b9) = card Q^2 * (3 * card \u0393^2)^\u03b9 :=\ncalc card (word \u0393 Q \u03b9) = card Q * card \u0393^\u03b9 * 3^\u03b9 * card Q * card \u0393^\u03b9\n  : by simpa[mul_assoc] using fintype.card_congr (equiv_prod \u0393 Q \u03b9)\n                   ... = card Q * card Q * 3^\u03b9 * card \u0393^\u03b9 * card \u0393^\u03b9\n  : by ring\n                   ... = card Q^2 * (3 * card \u0393^2)^\u03b9\n  : by simp[pow_two, mul_pow]; ring\n\nend word\n\nstructure model :=\n(state : Q) \n(tape : vector (\u2115 \u2192 \u0393) \u03b9)\n(head : vector \u2115 \u03b9)\n\nnotation `\u27e6` q `, ` T `, ` H `\u27e7` := model.mk q T H\n\nstructure sentence :=\n(carrier : set (word \u0393 Q \u03b9))\n(proper' : \u2200 c z u q x, \u27eec, z; u | q, x\u27ef \u2208 carrier \u2192 q \u2260 state_lang.halt \u2227 c \u2260 state_lang.start)\n\nnamespace sentence\nvariables {\u0393 Q \u03b9}\nvariables (\u03c3 : sentence \u0393 Q \u03b9)\n\ninstance : set_like (sentence \u0393 Q \u03b9) (word \u0393 Q \u03b9) := \u27e8sentence.carrier, \u03bb \u27e8_, _\u27e9 \u27e8_, _\u27e9, by simp\u27e9\n\nlemma mem_def (w : word \u0393 Q \u03b9) : w \u2208 \u03c3 \u2194 w \u2208 \u03c3.carrier := iff.rfl\n\nlemma proper {c z u q x} : \u27eec, z; u | q, x\u27ef \u2208 \u03c3 \u2192 q \u2260 state_lang.halt \u2227 c \u2260 state_lang.start := \u03c3.proper' _ _ _ _ _\n\n@[simp] lemma start_notin (c z u x) : \u27eec, z; u | halt, x\u27ef \u2209 \u03c3 := \u03bb A, by simpa using \u03c3.proper A\n\n@[simp] lemma halt_notin (z u q x) : \u27eestart, z; u | q, x\u27ef \u2209 \u03c3 := \u03bb A, by simpa using \u03c3.proper A \n\nlemma carrier_finite [fintype \u0393] [fintype Q] : \u03c3.carrier.finite := set.to_finite _\n\nnoncomputable instance [fintype \u0393] [fintype Q] : fintype (sentence \u0393 Q \u03b9) := fintype.of_injective carrier (\u03bb \u27e8_, _\u27e9 \u27e8_, _\u27e9, by simp)\n\ndef is_halt (q : Q) : Prop := \u2200 \u2983c z u x\u2984, \u27eec, z; u | q, x\u27ef \u2209 \u03c3\n\ndef is_start (c : Q) : Prop := \u2200 \u2983z u x q\u2984, \u27eec, z; u | q, x\u27ef \u2209 \u03c3\n\nlemma coe_carrier : (\u03c3 : set (word \u0393 Q \u03b9)) = \u03c3.carrier := by refl\n\nend sentence\n\nvariables {\u0393 Q \u03b9}\n\nnamespace model\nvariables (\u03c3 : sentence \u0393 Q \u03b9)\n\n\n@[ext] lemma ext : \u2200 {m\u2081 m\u2082 : model \u0393 Q \u03b9}\n  (hs : m\u2081.state = m\u2082.state)\n  (ht : m\u2081.tape = m\u2082.tape)\n  (hh : m\u2081.head = m\u2082.head), m\u2081 = m\u2082\n| \u27e6q\u2081, T\u2081, H\u2081\u27e7 \u27e6q\u2082, T\u2082, H\u2082\u27e7 hs ht hh :=\n  by { simp at hs ht hh, simp[hs, ht, hh] }\n\ndef read (T : vector (\u2115 \u2192 \u0393) \u03b9) (H : vector \u2115 \u03b9) : vector \u0393 \u03b9 := @vector.zip_with (\u2115 \u2192 \u0393) \u2115 \u0393 \u03b9 (\u03bb t h, t h) T H\n\n@[simp] lemma read_nth (T : vector (\u2115 \u2192 \u0393) \u03b9) (H : vector \u2115 \u03b9) (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 \u0393 \u03b9) : vector (\u2115 \u2192 \u0393) \u03b9 :=\n  @vector.zip_with3 (\u2115 \u2192 \u0393) \u2115 \u0393 (\u2115 \u2192 \u0393) \u03b9 (\u03bb t h x, \u03bb n, if n = h then x else t n) T H x\n\n@[irreducible] def reduct_head (H) (u : vector instruction \u03b9) : vector \u2115 \u03b9 :=\n  vector.zip_with instruction.apply u H\n\n@[simp] lemma reduct_tape_nth (T H) (x : vector \u0393 \u03b9) (i) :\n  (reduct_tape T H x).nth i = (\u03bb 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 \u03b9) (i) :\n  (reduct_head H u).nth i = (u.nth i).apply (H.nth i) :=\nby simp[reduct_head]\n\ninductive reduction : model \u0393 Q \u03b9 \u2192 model \u0393 Q \u03b9 \u2192 Prop\n| intro : \u2200 (q : Q) (T : vector (\u2115 \u2192 \u0393) \u03b9) (H : vector \u2115 \u03b9) (c : Q) (z : vector \u0393 \u03b9) (u : vector instruction \u03b9),\n    \u27eec, z; u | q, read T H\u27ef \u2208 \u03c3 \u2192 reduction \u27e6q, T, H\u27e7 \u27e6c, reduct_tape T H z, reduct_head H u\u27e7\n\nnotation m\u2080 ` \u27f6\u00b9[`:60  \u03c3 `] ` :0 m\u2081 := reduction \u03c3 m\u2080 m\u2081 \n\ndef is_halt (m : model \u0393 Q \u03b9) : Prop := \u2200 m', \u00acm \u27f6\u00b9[\u03c3] m'\n\ndef time_reductions : \u2115 \u2192 model \u0393 Q \u03b9 \u2192 model \u0393 Q \u03b9 \u2192 Prop := relation.power (reduction \u03c3) \n\nnotation m\u2080 ` \u27f6^(`:80 s `)[`  \u03c3 `] ` :80 m\u2081 := time_reductions \u03c3 s m\u2080 m\u2081 \n\ndef time_bounded_reductions : \u2115 \u2192 model \u0393 Q \u03b9 \u2192 model \u0393 Q \u03b9 \u2192 Prop := relation.power_le (reduction \u03c3)\n\nnotation m\u2080 ` \u27f6^(\u2264 `:80 s `)[`  \u03c3 `] ` :80 m\u2081 := time_bounded_reductions \u03c3 s m\u2080 m\u2081 \n\ndef time_bounded_reductions_halt (s : \u2115) (m m' : model \u0393 Q \u03b9) : Prop := is_halt \u03c3 m' \u2227 m \u27f6^(\u2264 s)[\u03c3] m'\n\nnotation m\u2080 ` \u27f6^(\u2264 `:80 s `)[`  \u03c3 `]\u2193 ` :80 m\u2081 := time_bounded_reductions_halt \u03c3 s m\u2080 m\u2081 \n\ndef is_halt_in_step (s : \u2115) (m : model \u0393 Q \u03b9) : Prop := \u2200 (m') (s' > s), \u00ac m \u27f6^(s')[\u03c3] m' \n\ndef reductions : model \u0393 Q \u03b9 \u2192 model \u0393 Q \u03b9 \u2192 Prop := relation.trans_gen (reduction \u03c3) \n\nnotation m\u2080 ` \u27f6*[`:80  \u03c3 `] ` :0 m\u2081 := reductions \u03c3 m\u2080 m\u2081 \n\nend model\n\nvariables {\u0393 Q \u03b9} \ndef sentence.deterministic (\u03c3 : sentence \u0393 Q \u03b9) : Prop :=\n\u2200 \u2983q x c\u2081 c\u2082 z\u2081 z\u2082 u\u2081 u\u2082\u2984, \u27eec\u2081, z\u2081; u\u2081 | q, x\u27ef \u2208 \u03c3 \u2192 \u27eec\u2082, z\u2082; u\u2082 | q, x\u27ef \u2208 \u03c3 \u2192 c\u2081 = c\u2082 \u2227 z\u2081 = z\u2082 \u2227 u\u2081 = u\u2082\n\nnamespace sentence\n\ninductive of_fun_aux (\u03b4 : Q \u2192 vector \u0393 \u03b9 \u2192 option (Q \u00d7 vector \u0393 \u03b9 \u00d7 vector instruction \u03b9)) : set (word \u0393 Q \u03b9)\n| intro : \u2200 {q x c z u}, \u03b4 q x = some \u27e8c, z, u\u27e9 \u2192 of_fun_aux \u27eec, z; u | q, x\u27ef\n\ndef of_fun (\u03b4 : Q \u2192 vector \u0393 \u03b9 \u2192 option (Q \u00d7 vector \u0393 \u03b9 \u00d7 vector instruction \u03b9))\n  (H : \u2200 {q x c z u}, \u03b4 q x = some \u27e8c, z, u\u27e9 \u2192 q \u2260 halt \u2227 c \u2260 start) : sentence \u0393 Q \u03b9 :=\n{ carrier := of_fun_aux \u03b4,\n  proper' := \u03bb c z u q x, by { rintro \u27e8_, _, _, _, _, h\u27e9, exact H h } }\n\nnamespace of_fun\nvariables (\u03b4 : Q \u2192 vector \u0393 \u03b9 \u2192 option (Q \u00d7 vector \u0393 \u03b9 \u00d7 vector instruction \u03b9))\n\nlemma carrier_eq {H} : (of_fun \u03b4 H).carrier = of_fun_aux \u03b4 := rfl\n\n@[simp] lemma mem_iff {H} {c z u q x} : \u27eec, z; u | q, x\u27ef \u2208 of_fun \u03b4 H \u2194 \u03b4 q x = some \u27e8c, z, u\u27e9 :=\nby { simp[sentence.mem_def], split,\n  { rintros \u27e8_, _, _, _, _, h\u27e9, exact h }, { intros h, exact of_fun_aux.intro h } }\n\nlemma none_is_halt {q H} : (of_fun \u03b4 H).is_halt q \u2194 \u2200 x, \u03b4 q x = none :=\nby { simp [is_halt, mem_iff, option.eq_none_iff_forall_not_mem], split,\n  { rintros h x c \u27e8z, u\u27e9 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 \u03b4 H) :=\n\u03bb _ _ _ _ _ _ _ _, by { simp, intros h\u2081 h\u2082, simpa[h\u2081] using h\u2082 }\n\nend of_fun\n\nnamespace deterministic\nvariables {\u03c3 : sentence \u0393 Q \u03b9} {m\u2081 m\u2082 : model \u0393 Q \u03b9}\n\nlemma reduction (d : deterministic \u03c3) : relation.deterministic (model.reduction \u03c3) := \u03bb m m\u2081 m\u2082 h\u2081 h\u2082,\nbegin\n  rcases h\u2081 with \u27e8q\u2081, T\u2081, H\u2081, c\u2081, z\u2081, u\u2081, mem\u2081\u27e9,\n  rcases h\u2082 with \u27e8q\u2082, T\u2082, H\u2082, c\u2082, z\u2082, u\u2082, mem\u2082\u27e9,\n  rcases d mem\u2081 mem\u2082 with \u27e8rfl, rfl, rfl\u27e9,\n  refl\nend\n\nlemma time_reductions (d : deterministic \u03c3) {n} : relation.deterministic (model.time_reductions \u03c3 n) :=\nrelation.power.deterministic (reduction @d)\n\nend deterministic\n\nend sentence\n\nsection TM\n\ndef tape_of (x : list \u0393) : \u2115 \u2192 language \u0393\n| 0       := \u2424\n| (n + 1) := if h : n < x.length then language.chr (x.nth_le n h) else \u2423\n\n-- \u2424 x\u2081 x\u2082 ... x\u2099 \u2423 \u2423 \u2423 ...\n\n@[simp] lemma tape_of_of_zero {x : list \u0393} : tape_of x 0 = \u2424 := by simp[tape_of]\n\n@[simp] lemma tape_of_of_lt {n} {x : list \u0393} (gt : n > 0) (le : n \u2264 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 \u0393} (h : n \u2265 x.length + 1) : tape_of x n = \u2423 :=\nby { cases n, { simp at h, contradiction },\n     { simp[tape_of], have : n \u2265 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 \u0393) \u03b9 \u2192 vector (list \u0393) \u03b9) (T : \u2115 \u2192 \u2115) :=\n(Q : Type*)\n(Q_fin : finite Q)\n(Q_state : state_lang Q)\n(\u03c3 : sentence (language \u0393) Q \u03b9)\n(reduction : \u2200 (X : vector (list \u0393) \u03b9), \n  model.is_halt_in_step \u03c3 (T X.length) (\u27e6start, X.map tape_of, default\u27e7) \u2227\n  \u27e6start, X.map tape_of, default\u27e7 \u27f6^(\u2264 T X.length)[\u03c3]\u2193 \u27e6halt, (f X).map tape_of, default\u27e7)\n\nstructure fun_time_bounded_computable_by_TM (f : vector (list \u0393) \u03b9 \u2192 vector (list \u0393) \u03b9) (T : \u2115 \u2192 \u2115)\n  extends fun_time_bounded_computable_by_NDTM f T :=\n(deterministic : \u03c3.deterministic)\n\nend TM\n\nnamespace sentence\nopen model sentence.deterministic relation\nvariables {R : Type*} [state_lang R] (f : Q \u2192 R) {\u03c3 : sentence \u0393 Q \u03b9}\n\n@[simp] def word.map_q : word \u0393 Q \u03b9 \u2192 word \u0393 R \u03b9\n| \u27eec, z; u | q, x\u27ef := \u27eef c, z; u | f q, x\u27ef\n\n@[simp] def map_q (\u03c3 : sentence \u0393 Q \u03b9) (f : Q \u2192 R) (H : \u2200 c z u q x, \u27eec, z; u | q, x\u27ef \u2208 \u03c3 \u2192 f q \u2260 halt \u2227 f c \u2260 start) :\n  sentence \u0393 R \u03b9 :=\n{ carrier := word.map_q f '' \u03c3,\n  proper' := by { rintros c z u q x \u27e8\u27e8c', z', u', q', x'\u27e9, h, eqn\u27e9,\n                  simp at eqn, rcases eqn with \u27e8rfl, rfl, rfl, rfl, rfl\u27e9, exact H _ _ _ _ _ h } }\n\nend sentence\n\nnamespace model\nopen sentence sentence.deterministic relation\nvariables {m\u2081 m\u2082 m\u2083 : model \u0393 Q \u03b9} {\u03c3 : sentence \u0393 Q \u03b9}\n\n@[simp] lemma reduct_tape_read {T : vector (\u2115 \u2192 \u0393) \u03b9} {H : vector \u2115 \u03b9} : reduct_tape T H (read T H) = T :=\nby { ext, simp, rintros rfl, refl }\n\n@[simp] lemma reduct_head_Stay {H : vector \u2115 \u03b9} : reduct_head H instruction.Stay = H :=\nby { ext, simp, }\n\nlemma reduction.iff {q\u2081 q\u2082 : Q} {T\u2081 T\u2082 : vector (\u2115 \u2192 \u0393) \u03b9} {H\u2081 H\u2082 : vector \u2115 \u03b9}  :\n  (\u27e6q\u2081, T\u2081, H\u2081\u27e7 \u27f6\u00b9[\u03c3] \u27e6q\u2082, T\u2082, H\u2082\u27e7) \u2194\n  (\u2203 (z : vector \u0393 \u03b9) (u : vector instruction \u03b9), \u27eeq\u2082, z; u | q\u2081, read T\u2081 H\u2081\u27ef \u2208 \u03c3 \u2227 T\u2082 = reduct_tape T\u2081 H\u2081 z \u2227 H\u2082 = reduct_head H\u2081 u) :=\n\u27e8by { rintros \u27e8_, _, _, _, z, u, mem\u27e9, refine \u27e8z, u, mem, rfl, rfl\u27e9 },\n by { rintros \u27e8z, u, mem, rfl, rfl\u27e9, refine \u27e8_, _, _, _, z, u, mem\u27e9 }\u27e9\n\n@[simp] lemma time_bounded_reductions.refl {s} : m\u2081 \u27f6^(\u2264 s)[\u03c3] m\u2081 := power_le.refl\n\nlemma time_reductions.refl : m\u2081 \u27f6^(0)[\u03c3] m\u2081 := power.zero _\n\n@[simp] lemma time_reductions_zero_iff : (m\u2081 \u27f6^(0)[\u03c3] m\u2082) \u2194 m\u2081 = m\u2082 := power.zero_iff\n\nlemma time_bounded_reductions.of_le {s\u2081 s\u2082} (le : s\u2081 \u2264 s\u2082) (h : m\u2081 \u27f6^(\u2264 s\u2081)[\u03c3] m\u2082) :\n  m\u2081 \u27f6^(\u2264 s\u2082)[\u03c3] m\u2082 := power_le.of_le le h\n\nlemma time_reductions.add {s\u2081 s\u2082} (h\u2081 : m\u2081 \u27f6^(s\u2081)[\u03c3] m\u2082) (h\u2082 : m\u2082 \u27f6^(s\u2082)[\u03c3] m\u2083) :\n  m\u2081 \u27f6^(s\u2081 + s\u2082)[\u03c3] m\u2083 := power.add h\u2081 h\u2082\n\nlemma time_bounded_reductions.add {s\u2081 s\u2082} (h\u2081 : m\u2081 \u27f6^(\u2264 s\u2081)[\u03c3] m\u2082) (h\u2082 : m\u2082 \u27f6^(\u2264 s\u2082)[\u03c3] m\u2083) :\n  m\u2081 \u27f6^(\u2264 s\u2081 + s\u2082)[\u03c3] m\u2083 := power_le.add h\u2081 h\u2082\n\nlemma time_bounded_reductions.sum {m : \u2115 \u2192 model \u0393 Q \u03b9} {s : \u2115 \u2192 \u2115}\n  (h : \u2200 k, m k \u27f6^(\u2264 s k)[\u03c3] m (k + 1)) (k : \u2115) : (m 0) \u27f6^(\u2264 \u2211 i in finset.range k, s i)[\u03c3] (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\u2081 \u27f6\u00b9[\u03c3] m\u2082) {\u03c4 : sentence \u0393 Q \u03b9} (ss : \u03c3 \u2264 \u03c4) : m\u2081 \u27f6\u00b9[\u03c4] m\u2082 :=\nby { rcases r with \u27e8q, T, H, c, z, u, mem\u27e9, refine \u27e8_, _, _, _, _, _, ss mem\u27e9 }\n\nlemma time_reductions.of_ss {n} (r : m\u2081 \u27f6^(n)[\u03c3] m\u2082) {\u03c4 : sentence \u0393 Q \u03b9} (ss : \u03c3 \u2264 \u03c4) : m\u2081 \u27f6^(n)[\u03c4] m\u2082 :=\nby { induction n with n IH generalizing m\u2082, { rcases r, simp },\n     { rcases r with (_ | \u27e8_, _, m\u2081\u2081, _, r\u2081_\u2081\u2081, r\u2081\u2081_\u2082\u27e9), exact (IH r\u2081_\u2081\u2081).succ (r\u2081\u2081_\u2082.of_ss ss) } }\n\nlemma time_bounded_reductions.of_ss {k} (r : m\u2081 \u27f6^(\u2264 k)[\u03c3] m\u2082) {\u03c4 : sentence \u0393 Q \u03b9} (ss : \u03c3 \u2264 \u03c4) : m\u2081 \u27f6^(\u2264 k)[\u03c4] m\u2082 :=\nby { rcases r with \u27e8n, le, r\u27e9, refine \u27e8n, le, time_reductions.of_ss r ss\u27e9 }\n\nsection\nvariables {R : Type*} [state_lang R] (f : Q \u2192 R)\n\n@[simp] def map_q : model \u0393 Q \u03b9 \u2192 model \u0393 R \u03b9\n| \u27e6q, T, H\u27e7 := \u27e6f q, T, H\u27e7\n\ninstance [has_coe Q R] : has_coe (model \u0393 Q \u03b9) (model \u0393 R \u03b9) := \u27e8\u03bb m, m.map_q coe\u27e9 \n\nvariables (m m' : model \u0393 Q \u03b9) {f}\n\n@[simp] lemma map_q_tape (m : model \u0393 Q \u03b9) : (m.map_q f).tape = m.tape := by cases m; simp\n\n@[simp] lemma map_q_head (m : model \u0393 Q \u03b9) : (m.map_q f).head = m.head := by cases m; simp\n\n@[simp] lemma map_q_state (m : model \u0393 Q \u03b9) : (m.map_q f).state = f m.state := by cases m; simp\n\nvariables (f)\n\nlemma reduction.map_q {H} (h : m\u2081 \u27f6\u00b9[\u03c3] m\u2082) : m\u2081.map_q f \u27f6\u00b9[\u03c3.map_q f H] m\u2082.map_q f :=\nby { rcases h with \u27e8q, T, H, c, z, u, mem\u27e9, simp, refine \u27e8_, _, _, _, _, _, _\u27e9, simp[sentence.mem_def], refine \u27e8_, mem, by simp\u27e9 }\n\nlemma time_reductions.map_q {H} {n} (h : m\u2081 \u27f6^(n)[\u03c3] m\u2082) : m\u2081.map_q f \u27f6^(n)[\u03c3.map_q f H] m\u2082.map_q f :=\nby { induction n with n IH generalizing m\u2082, { rcases h, simp },\n     { rcases h with (_ | \u27e8_, _, m\u2081\u2081, _, r\u2081_\u2081\u2081, r\u2081\u2081_\u2082\u27e9), refine (IH r\u2081_\u2081\u2081).succ (r\u2081\u2081_\u2082.map_q f) } }\n\nlemma time_bounded_reduction.map_q {H} {k} (h : m\u2081 \u27f6^(\u2264 k)[\u03c3] m\u2082) : m\u2081.map_q f \u27f6^(\u2264 k)[\u03c3.map_q f H] m\u2082.map_q f :=\nby { rcases h with \u27e8n, le, r\u27e9, refine \u27e8n, le, time_reductions.map_q f r\u27e9 }\n\nvariables {f}\n\nlemma deterministic.map_q {H} (inj : function.injective f) (d : deterministic \u03c3) : deterministic (\u03c3.map_q f H) :=\nbegin\n  rintros r x d\u2081 d\u2082 z\u2081 z\u2082 u\u2081 u\u2082 h\u2081 h\u2082,\n  rcases h\u2081 with \u27e8\u27e8c\u2081, z\u2081', u\u2081', q\u2081, x\u2081'\u27e9, mem\u2081, eq\u2081\u27e9,\n  have : f c\u2081 = d\u2081 \u2227 z\u2081 = z\u2081' \u2227 u\u2081 = u\u2081' \u2227 f q\u2081 = r \u2227 x = x\u2081', { simp at eq\u2081, simp[eq\u2081] },\n  rcases this with \u27e8rfl, rfl, rfl, rfl, rfl\u27e9,\n  rcases h\u2082 with \u27e8\u27e8c\u2082, z\u2082', u\u2082', q\u2082, x\u2082'\u27e9, mem\u2082, eq\u2082\u27e9,\n  have : f c\u2082 = d\u2082 \u2227 z\u2082 = z\u2082' \u2227 u\u2082 = u\u2082' \u2227 f q\u2081 = f q\u2082 \u2227 x = x\u2082', { simp at eq\u2082, simp[eq\u2082] },\n  rcases this with \u27e8rfl, rfl, rfl, eqn, rfl\u27e9,\n  have : q\u2081 = q\u2082, from (inj eqn), rcases this with rfl,\n  simp [d mem\u2081 mem\u2082]\nend\n\nend\n\nvariables {R : Type v} [state_lang R]\n\nnamespace sentence\nvariables {Q R} (q c : Q) (h : q \u2260 halt \u2227 c \u2260 start) \n\ninductive fix_q_aux : word \u0393 Q \u03b9 \u2192 Prop\n| intro : \u2200 (z : vector \u0393 \u03b9), fix_q_aux \u27eec, z; instruction.Stay | q, z\u27ef\n\ndef fix_q (q c : Q) (h : q \u2260 halt \u2227 c \u2260 start) : sentence \u0393 Q \u03b9 :=\n{ carrier := fix_q_aux q c,\n  proper' := \u03bb c' z u q' x, by { rintros \u27e8\u27e9, exact h } } \n\n@[simp] lemma fix_q_mem (z : vector \u0393 \u03b9) :\n  \u27eec, z; instruction.Stay | q, z\u27ef \u2208 (fix_q q c h : sentence \u0393 Q \u03b9) :=\nfix_q_aux.intro _\n\nlemma fix_q_mem_iff {c z u q x q\u2081 q\u2082 h} :\n  \u27eec, z; u| q, x\u27ef \u2208 (fix_q q\u2081 q\u2082 h : sentence \u0393 Q \u03b9) \u2194 c = q\u2082 \u2227 z = x \u2227 q = q\u2081 \u2227 u = instruction.Stay :=\n\u27e8by { rintros \u27e8\u27e9, simp; refl }, by { rintros \u27e8rfl, rfl, rfl, rfl\u27e9, exact fix_q_aux.intro _ }\u27e9\n\nlemma fix_q.deterministic : deterministic (fix_q q c h : sentence \u0393 Q \u03b9) :=\nby { rintros q' x c\u2081 c\u2082 z\u2081 z\u2082 u\u2081 u\u2082 h\u2081 h\u2082, rcases h\u2081, rcases h\u2082, simp }\n\n@[simp] lemma fix_q_reduction (T : vector (\u2115 \u2192 \u0393) \u03b9) (H : vector \u2115 \u03b9) : \u27e6q, T, H\u27e7 \u27f6\u00b9[fix_q q c h] \u27e6c, T, H\u27e7 :=\nreduction.iff.mpr \u27e8read T H, instruction.Stay, by simp, by simp\u27e9\n\ninstance : has_union (sentence \u0393 Q \u03b9) := \u27e8\u03bb \u03c3 \u03c4,\n{ carrier := \u03c3 \u222a \u03c4,\n  proper' := by { rintros c z u q x (h | h), { exact \u03c3.proper h }, { exact \u03c4.proper h } } }\u27e9\n\ndef deterministic.union {\u03c3 \u03c4 : sentence \u0393 Q \u03b9} (d\u2081 : deterministic \u03c3) (d\u2082 : deterministic \u03c4) \n  (h : \u2200 {q x c\u2081 c\u2082 z\u2081 z\u2082 u\u2081 u\u2082}, \u27eec\u2081, z\u2081; u\u2081 | q, x\u27ef \u2208 \u03c3 \u2192 \u27eec\u2082, z\u2082; u\u2082 | q, x\u27ef \u2208 \u03c4 \u2192 c\u2081 = c\u2082 \u2227 z\u2081 = z\u2082 \u2227 u\u2081 = u\u2082) :\n  deterministic (\u03c3 \u222a \u03c4) :=\nbegin\n  rintros q x c\u2081 c\u2082 z\u2081 z\u2082 u\u2081 u\u2082 (h\u2081 | h\u2081) (h\u2082 | h\u2082),\n  { exact d\u2081 h\u2081 h\u2082 }, { exact h h\u2081 h\u2082 }, { simp [h h\u2082 h\u2081] }, { exact d\u2082 h\u2081 h\u2082 }\nend\n\ninstance : has_Sup (sentence \u0393 Q \u03b9) := \u27e8\u03bb s, \n{ carrier := \u22c3\u2080 (carrier '' s),\n  proper' := \u03bb c z u q x h, by { simp at h, rcases h with \u27e8\u03c3, _, h\u03c3\u27e9, exact \u03c3.proper h\u03c3 } }\u27e9\n\nlemma Sup_carrier (s : set (sentence \u0393 Q \u03b9)) : \u2191(Sup s) = \u22c3\u2080 (carrier '' s) := by refl\n\nlemma coe_supr {\u03b1 : Sort*} {f : \u03b1 \u2192 sentence \u0393 Q \u03b9} : (\u2191(\u2a06 i, f i) : set (word \u0393 Q \u03b9)) = \u22c3 i, (f i) :=\nby { unfold supr, rw [Sup_carrier], simp, refl }\n\ndef deterministic.Sup {s : set (sentence \u0393 Q \u03b9)} (d : \u2200 \u03c3 \u2208 s, deterministic \u03c3) \n  (h : \u2200 (\u03c3 \u2208 s) (\u03c4 \u2208 s) {q x c\u2081 c\u2082 z\u2081 z\u2082 u\u2081 u\u2082},\n    \u27eec\u2081, z\u2081; u\u2081 | q, x\u27ef \u2208 \u03c3 \u2192 \u27eec\u2082, z\u2082; u\u2082 | q, x\u27ef \u2208 \u03c4 \u2192 c\u2081 = c\u2082 \u2227 z\u2081 = z\u2082 \u2227 u\u2081 = u\u2082) :\n  deterministic (Sup s) :=\nbegin\n  rintros q x c\u2081 c\u2082 z\u2081 z\u2082 u\u2081 u\u2082 \u27e8_, \u27e8\u03c3, h\u03c3s, rfl\u27e9, h\u03c3\u27e9 \u27e8_, \u27e8\u03c4, h\u03c4s, rfl\u27e9, h\u03c4\u27e9, \n  refine h _ h\u03c3s _ h\u03c4s h\u03c3 h\u03c4\nend\n\ndef comp_suml (\u03c3 : sentence \u0393 Q \u03b9) : sentence \u0393 (Q \u2295 R) \u03b9 := \u03c3.map_q sum.inl (by { intros _ _ _ _ _ h, unfold halt start, simp[\u03c3.proper h] })\n\ndef comp_sumr (\u03c4 : sentence \u0393 R \u03b9) : sentence \u0393 (Q \u2295 R) \u03b9 := \u03c4.map_q sum.inr (by { intros _ _ _ _ _ h, unfold halt start, simp[\u03c4.proper h] })\n\ndef comp (\u03c3 : sentence \u0393 Q \u03b9) (\u03c4 : sentence \u0393 R \u03b9) : sentence \u0393 (Q \u2295 R) \u03b9 :=\n(\u03c3.map_q sum.inl (by { intros _ _ _ _ _ h, unfold halt start, simp[\u03c3.proper h] })) \u222a\n(\u03c4.map_q sum.inr (by { intros _ _ _ _ _ h, unfold halt start, simp[\u03c4.proper h] })) \u222a\n(fix_q (sum.inl (halt : Q)) (sum.inr (start : R)) (by unfold halt start; simp))\n\ninfix ` \u25b7 `:80 := comp\n\nlemma comp.deterministic {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9}\n  (d\u2081 : deterministic \u03c3) (d\u2082 : deterministic \u03c4) : deterministic (\u03c3 \u25b7 \u03c4) :=\nbegin\n  refine (deterministic.union (deterministic.union (deterministic.map_q sum.inl_injective d\u2081) (deterministic.map_q sum.inr_injective d\u2082) _)\n           (fix_q.deterministic _ _ _) _),\n  { rintros (q | r) _ _ _ _ _ _ _ \u27e8\u27e8c\u2081, z\u2081, u\u2081, q, x\u27e9, mem\u2081, eqn\u2081\u27e9 \u27e8\u27e8c\u2082, z\u2082, u\u2082, q', x'\u27e9, mem\u2082, eqn\u2082\u27e9,\n    { simp at eqn\u2082, contradiction },\n    { simp at eqn\u2081, contradiction } },\n  { rintros _ _ _ _ _ _ _ _ (\u27e8\u27e8c, z, u, q, x\u27e9, mem, eqn\u27e9 | \u27e8\u27e8c, z, u, q, x\u27e9, mem, eqn\u27e9) \u27e8\u27e9,\n    { simp at eqn, rcases eqn with \u27e8rfl, rfl, rfl, rfl, rfl\u27e9, exfalso, simpa using mem },\n    { simp at eqn, contradiction } }\nend\n\ndef dsum (\u03c3 : sentence \u0393 Q \u03b9) (\u03c4 : sentence \u0393 R \u03b9) (c : Q \u2192 R \u2192 Prop) : sentence \u0393 (Q \u2295 R) \u03b9 :=\n(\u03c3.map_q sum.inl (by { intros _ _ _ _ _ h, unfold halt start, simp[\u03c3.proper h] })) \u222a\n(\u03c4.map_q sum.inr (by { intros _ _ _ _ _ h, unfold halt start, simp[\u03c4.proper h] })) \u222a\n(\u2a06 (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 {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9}\n  (d\u2081 : deterministic \u03c3) (d\u2082 : deterministic \u03c4) (c : Q \u2192 R \u2192 Prop)\n  (dc : \u2200 q r\u2081 r\u2082, c q r\u2081 \u2192 c q r\u2082 \u2192 r\u2081 = r\u2082)\n  (hc : \u2200 q r, c q r \u2192 \u03c3.is_halt q) : deterministic (dsum \u03c3 \u03c4 c) :=\nbegin\n  refine (deterministic.union\n    (deterministic.union (deterministic.map_q sum.inl_injective d\u2081) (deterministic.map_q sum.inr_injective d\u2082) _)\n      (deterministic.Sup _ _) _),\n  { rintros (q | r) _ _ _ _ _ _ _ \u27e8\u27e8c\u2081, z\u2081, u\u2081, q, x\u27e9, mem\u2081, eqn\u2081\u27e9 \u27e8\u27e8c\u2082, z\u2082, u\u2082, q', x'\u27e9, mem\u2082, eqn\u2082\u27e9,\n    { simp at eqn\u2082, contradiction },\n    { simp at eqn\u2081, contradiction } },\n  { rintros \u03c3 \u27e8q, rfl\u27e9, show (\u2a06 r (h : c q r), fix_q (sum.inl q) (sum.inr r) _).deterministic,\n    refine deterministic.Sup _ _,\n    { rintros _ \u27e8r, rfl\u27e9, refine deterministic.Sup (by simpa using \u03bb _, fix_q.deterministic _ _ _) _,\n      { rintros _ \u27e8_, rfl\u27e9 _ \u27e8_, rfl\u27e9 (q | r); { intros _ _ _ _ _ _ _ h\u2081 h\u2082, exact fix_q.deterministic _ _ _ h\u2081 h\u2082 } } },\n    { rintros _ \u27e8r\u2081, rfl\u27e9 _ \u27e8r\u2082, rfl\u27e9 (q' | r');\n      { rintros _ _ _ _ _ _ _ \u27e8_, \u27e8_, \u27e8hc\u2081, rfl\u27e9, rfl\u27e9, h\u2081\u27e9 \u27e8_, \u27e8_, \u27e8hc\u2082, rfl\u27e9, rfl\u27e9, h\u2082\u27e9,\n        have : r\u2081 = r\u2082, from dc _ _ _ hc\u2081 hc\u2082, rcases this with rfl,\n        exact fix_q.deterministic _ _ (by unfold halt start; simp) h\u2081 h\u2082 } } },\n  { rintros _ \u27e8q\u2081, rfl\u27e9 _ \u27e8q\u2082, rfl\u27e9 (q | r),\n    { rintros _ _ _ _ _ _ _\n        \u27e8_, \u27e8_, \u27e8r\u2081, rfl\u27e9, rfl\u27e9, \u27e8_, \u27e8_, \u27e8hc\u2081, rfl\u27e9, rfl\u27e9, h\u2081\u27e9\u27e9\n        \u27e8_, \u27e8_, \u27e8r\u2082, rfl\u27e9, rfl\u27e9, \u27e8_, \u27e8_, \u27e8hc\u2082, rfl\u27e9, rfl\u27e9, h\u2082\u27e9\u27e9,\n      simp at h\u2081 h\u2082,\n      have : c\u2081 = sum.inr r\u2081 \u2227 z\u2081 = x \u2227 q = q\u2081 \u2227 u\u2081 = instruction.Stay,\n      { simpa using fix_q_mem_iff.mp h\u2081, unfold halt start; simp },\n      rcases this with \u27e8rfl, rfl, rfl, rfl\u27e9,\n      have : c\u2082 = sum.inr r\u2082 \u2227 z\u2082 = z\u2081 \u2227 q = q\u2082 \u2227 u\u2082 = instruction.Stay,\n      { simpa using fix_q_mem_iff.mp h\u2082, unfold halt start; simp },\n      rcases this with \u27e8rfl, rfl, rfl, rfl\u27e9,\n      have : r\u2081 = r\u2082, from dc _ _ _ hc\u2081 hc\u2082, rcases this with rfl,\n      simp },\n    { simp,  rintros _ _ _ _ _ _ _\n        \u27e8_, \u27e8_, \u27e8r\u2081, rfl\u27e9, rfl\u27e9, \u27e8_, \u27e8_, \u27e8hc\u2081, rfl\u27e9, rfl\u27e9, h\u2081\u27e9\u27e9 _,\n      have : false, { simpa using (fix_q_mem_iff.mp h\u2081), unfold start halt; simp },\n      contradiction } },\n  { rintros (q | r),\n    { rintros x _ _ _ _ _ _ (\u27e8\u27e8c\u2081, z\u2081, u\u2081, q\u2081, x\u2081\u27e9, wmem, hw\u27e9 | \u27e8\u27e8c\u2081, z\u2081, u\u2081, q\u2081, x\u2081\u27e9, wmem, hw\u27e9),\n      { simp at hw, rcases hw with \u27e8rfl, rfl, rfl, rfl, rfl\u27e9,\n        rintros \u27e8_, \u27e8_, \u27e8q', rfl\u27e9, rfl\u27e9, \u27e8_, \u27e8_, \u27e8r', rfl\u27e9, rfl\u27e9, H, \u27e8_, \u27e8hc', rfl\u27e9, rfl\u27e9, h\u2081\u27e9\u27e9,\n        have : q\u2081 = q',\n        { have := fix_q_mem_iff.mp h\u2081, simp at this, rcases this with \u27e8rfl, rfl, rfl, rfl\u27e9; 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 _ _ _ _ _ _ (\u27e8\u27e8c\u2081, z\u2081, u\u2081, q\u2081, x\u2081\u27e9, wmem, hw\u27e9 | \u27e8\u27e8c\u2081, z\u2081, u\u2081, q\u2081, x\u2081\u27e9, wmem, hw\u27e9), \n      { simp at hw, contradiction },\n      { simp at hw, rcases hw with \u27e8rfl, rfl, rfl, rfl, rfl\u27e9,\n        rintros \u27e8_, \u27e8_, \u27e8q', rfl\u27e9, rfl\u27e9, \u27e8_, \u27e8_, \u27e8r', rfl\u27e9, rfl\u27e9, H, \u27e8_, \u27e8hc', rfl\u27e9, rfl\u27e9, h\u2081\u27e9\u27e9,\n        have : false, { have := fix_q_mem_iff.mp h\u2081, simpa using this, unfold start halt; simp },\n        contradiction } } }\nend\n\nend sentence\n\nlemma time_reductions.comp_aux {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {n\u2081 n\u2082} {q r T\u2081 T\u2082 T\u2083 H\u2081 H\u2082 H\u2083}\n  (h\u2081 : \u27e6q, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081)[\u03c3] \u27e6halt, T\u2082, H\u2082\u27e7) (h\u2082 : \u27e6start, T\u2082, H\u2082\u27e7 \u27f6^(n\u2082)[\u03c4] \u27e6r, T\u2083, H\u2083\u27e7) :\n  \u27e6sum.inl q, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081 + n\u2082 + 1)[\u03c3 \u25b7 \u03c4] \u27e6sum.inr r, T\u2083, H\u2083\u27e7 :=\nbegin\n  have h\u2081 : \u27e6sum.inl q, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081)[\u03c3 \u25b7 \u03c4] \u27e6sum.inl halt, T\u2082, H\u2082\u27e7,\n  from time_reductions.of_ss (time_reductions.map_q sum.inl h\u2081)\n    (by { simp[(\u25b7)], refine set.subset_union_of_subset_left (set.subset_union_left _ _) _,\n          { intros _ _ _ _ _ h, unfold halt start, simp[\u03c3.proper h] } }),\n  have h : \u27e6sum.inl halt, T\u2082, H\u2082\u27e7 \u27f6\u00b9[\u03c3 \u25b7 \u03c4] \u27e6sum.inr start, T\u2082, H\u2082\u27e7,\n  from reduction.of_ss (sentence.fix_q_reduction _ _ _ _ _)\n    (by { simp[(\u25b7)], refine set.subset_union_right _ _, { unfold halt start; simp } }),\n  have h\u2082 : \u27e6sum.inr start, T\u2082, H\u2082\u27e7 \u27f6^(n\u2082)[\u03c3 \u25b7 \u03c4] \u27e6sum.inr r, T\u2083, H\u2083\u27e7,\n  from time_reductions.of_ss (time_reductions.map_q sum.inr h\u2082)\n    (by { simp[(\u25b7)], refine set.subset_union_of_subset_left (set.subset_union_right _ _) _,\n          { intros _ _ _ _ _ h, unfold halt start, simp[\u03c4.proper h] } }),\n  simpa[show n\u2081.succ + n\u2082 = n\u2081 + n\u2082 + 1, by omega] using (h\u2081.succ h).add h\u2082\nend\n\nlemma time_reductions.comp {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {n\u2081 n\u2082 : \u2115} {T\u2081 T\u2082 T\u2083 H\u2081 H\u2082 H\u2083}\n  (h\u2081 : \u27e6start, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081)[\u03c3] \u27e6halt, T\u2082, H\u2082\u27e7) (h\u2082 : \u27e6start, T\u2082, H\u2082\u27e7 \u27f6^(n\u2082)[\u03c4] \u27e6halt, T\u2083, H\u2083\u27e7) :\n  \u27e6start,  T\u2081, H\u2081\u27e7 \u27f6^(n\u2081 + n\u2082 + 1)[\u03c3 \u25b7 \u03c4] \u27e6halt, T\u2083, H\u2083\u27e7 :=\ntime_reductions.comp_aux h\u2081 h\u2082\n\nlemma time_bounded_reductions.comp {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {k\u2081 k\u2082 : \u2115} {T\u2081 T\u2082 T\u2083 H\u2081 H\u2082 H\u2083}\n  (h\u2081 : \u27e6start, T\u2081, H\u2081\u27e7 \u27f6^(\u2264 k\u2081)[\u03c3] \u27e6halt, T\u2082, H\u2082\u27e7) (h\u2082 : \u27e6start, T\u2082, H\u2082\u27e7 \u27f6^(\u2264 k\u2082)[\u03c4] \u27e6halt, T\u2083, H\u2083\u27e7) :\n  \u27e6start,  T\u2081, H\u2081\u27e7 \u27f6^(\u2264 k\u2081 + k\u2082 + 1)[\u03c3 \u25b7 \u03c4] \u27e6halt, T\u2083, H\u2083\u27e7 :=\nby { rcases h\u2081 with \u27e8n\u2081, le\u2081, h\u2081\u27e9, rcases h\u2082 with \u27e8n\u2082, le\u2082, h\u2082\u27e9, refine \u27e8n\u2081 + n\u2082 + 1, by linarith, time_reductions.comp h\u2081 h\u2082\u27e9 }\n\nlemma time_reductions.dsum_left {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {q\u2081 q\u2082 T\u2081 T\u2082 H\u2081 H\u2082} {n}\n  (h : \u27e6q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n)[\u03c3] \u27e6q\u2082, T\u2082, H\u2082\u27e7) (\u03c6 : Q \u2192 R \u2192 Prop) :\n  \u27e6sum.inl q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n)[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inl q\u2082, T\u2082, H\u2082\u27e7 :=\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[\u03c3.proper h] } })\n\nlemma time_reductions.dsum_right {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {r\u2081 r\u2082 T\u2081 T\u2082 H\u2081 H\u2082} {n}\n  (h : \u27e6r\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n)[\u03c4] \u27e6r\u2082, T\u2082, H\u2082\u27e7) (\u03c6 : Q \u2192 R \u2192 Prop) :\n  \u27e6sum.inr r\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n)[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inr r\u2082, T\u2082, H\u2082\u27e7 :=\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[\u03c4.proper h] } })\n\nlemma time_reductions.dsum {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {n\u2081 n\u2082} {q\u2081 q\u2082 r\u2082 r\u2083 T\u2081 T\u2082 T\u2083 H\u2081 H\u2082 H\u2083}\n  (\u03c6 : Q \u2192 R \u2192 Prop) (h : \u03c6 q\u2082 r\u2082)\n  (h\u2081 : \u27e6q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081)[\u03c3] \u27e6q\u2082, T\u2082, H\u2082\u27e7) (h\u2082 : \u27e6r\u2082, T\u2082, H\u2082\u27e7 \u27f6^(n\u2082)[\u03c4] \u27e6r\u2083, T\u2083, H\u2083\u27e7) :\n  \u27e6sum.inl q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081 + n\u2082 + 1)[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inr r\u2083, T\u2083, H\u2083\u27e7 :=\nbegin\n  have h\u2081 : \u27e6sum.inl q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(n\u2081)[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inl q\u2082, T\u2082, H\u2082\u27e7,\n  from time_reductions.dsum_left h\u2081 \u03c6,\n  have h : \u27e6sum.inl q\u2082, T\u2082, H\u2082\u27e7 \u27f6\u00b9[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inr r\u2082, T\u2082, H\u2082\u27e7,\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\u2083 q\u2082 r\u2082 h }),\n  have h\u2082 : \u27e6sum.inr r\u2082, T\u2082, H\u2082\u27e7 \u27f6^(n\u2082)[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inr r\u2083, T\u2083, H\u2083\u27e7,\n  from time_reductions.dsum_right h\u2082 \u03c6,\n  simpa[show n\u2081.succ + n\u2082 = n\u2081 + n\u2082 + 1, by omega] using (h\u2081.succ h).add h\u2082\nend\n\nlemma time_bounded_reductions.dsum {\u03c3 : sentence \u0393 Q \u03b9} {\u03c4 : sentence \u0393 R \u03b9} {n\u2081 n\u2082} {q\u2081 q\u2082 r\u2082 r\u2083 T\u2081 T\u2082 T\u2083 H\u2081 H\u2082 H\u2083}\n  (\u03c6 : Q \u2192 R \u2192 Prop) (h : \u03c6 q\u2082 r\u2082)\n  (h\u2081 : \u27e6q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(\u2264 n\u2081)[\u03c3] \u27e6q\u2082, T\u2082, H\u2082\u27e7) (h\u2082 : \u27e6r\u2082, T\u2082, H\u2082\u27e7 \u27f6^(\u2264 n\u2082)[\u03c4] \u27e6r\u2083, T\u2083, H\u2083\u27e7) :\n  \u27e6sum.inl q\u2081, T\u2081, H\u2081\u27e7 \u27f6^(\u2264 n\u2081 + n\u2082 + 1)[sentence.dsum \u03c3 \u03c4 \u03c6] \u27e6sum.inr r\u2083, T\u2083, H\u2083\u27e7 :=\nby{ rcases h\u2081 with \u27e8n\u2081, le\u2081, h\u2081\u27e9, rcases h\u2082 with \u27e8n\u2082, le\u2082, h\u2082\u27e9,\n    refine \u27e8n\u2081 + n\u2082 + 1, by linarith, time_reductions.dsum \u03c6 h h\u2081 h\u2082\u27e9 }\n\nend model\n\nnamespace blang\nopen instruction model\nvariables (\u0393 Q \u03b9) [inhabited \u0393] [bfin \u0393]\n\ndef list_less_than (k : \u2115) := {l : list (option bool) // l.length \u2264 k}\n\ninstance (k : \u2115) : inhabited (list_less_than k) := \u27e8\u27e8[], by simp\u27e9\u27e9\n\nnamespace read\n\ninductive state\n| intro (q : Q) (i : fin (bentropy \u0393).succ) (v : vector (vector bool (bentropy \u0393)) \u03b9) : state\n\nvariables {\u0393 Q \u03b9}\n\ninstance [state_lang Q] : state_lang (state \u0393 Q \u03b9) :=\n\u27e8state.intro start 0 default, state.intro halt \u22a4 default\u27e9\n\ndef \u03b4 : state \u0393 Q \u03b9 \u2192 vector bool \u03b9 \u2192 option (state \u0393 Q \u03b9 \u00d7 vector bool \u03b9 \u00d7 vector instruction \u03b9)\n| \u27e8q, i, v\u27e9 x := if h : i < \u22a4 then \n    let newstate : state \u0393 Q \u03b9 :=\n      \u27e8q, \u27e8i + 1, nat.succ_lt_succ (fin.lt_top_iff.mp h)\u27e9, (v.sim_update_nth (vector.rep \u27e8i, fin.lt_top_iff.mp h\u27e9) x)\u27e9 in \n  some \u27e8newstate, x, Right\u27e9 else none\n\n@[simp] lemma \u03b4_top {q v x} : \u03b4 (\u27e8q, \u22a4, v\u27e9 : state \u0393 Q \u03b9) x = none := by simp[\u03b4]\n\ndef \u03c3 : sentence bool (state \u0393 Q \u03b9) \u03b9 := sentence.of_fun \u03b4\n(by { unfold start halt,\n      intros q x c z u eqn, split; rintros rfl,\n      { simpa using eqn },\n      { rcases q with \u27e8q, i, v\u27e9, by_cases C : i < \u22a4; simp[C, \u03b4, fin.ext_iff] at eqn; contradiction } })\n\nsection\nvariables (v : vector (vector bool (bentropy \u0393)) \u03b9) (T : vector (\u2115 \u2192 bool) \u03b9) (H : vector \u2115 \u03b9)\n\nlemma \u03c3_reduction (q : Q) (i : fin (bentropy \u0393).succ) (h : i < \u22a4) :\n  \u27e6\u27e8q, i, v\u27e9, T, H\u27e7 \u27f6\u00b9[\u03c3]\n  \u27e6\u27e8q, \u27e8i + 1, nat.succ_lt_succ (fin.lt_top_iff.mp h)\u27e9, \n    v.sim_update_nth (vector.rep \u27e8i, fin.lt_top_iff.mp h\u27e9) (read T H)\u27e9, T, H.map nat.succ\u27e7 :=\nreduction.iff.mpr (\u27e8read T H, Right, by simp[\u03c3, \u03b4, h], by simp, by ext; simp\u27e9)\n\n@[simp] lemma \u03c3_is_halt (q : Q) (v : vector (vector bool (bentropy \u0393)) \u03b9) : \u03c3.is_halt \u27e8q, \u22a4, v\u27e9 :=\nby intros c z u x; simp[\u03c3]\n\ndef memory :\n  fin (bentropy \u0393).succ \u2192 vector (vector bool (bentropy \u0393)) \u03b9\n| \u27e80, _\u27e9      := v\n| \u27e8s + 1, hn\u27e9 := (memory \u27e8s, by omega\u27e9).sim_update_nth (vector.rep \u27e8s, by omega\u27e9) (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 \u03c3_time_reductions (q : Q) :\n  \u2200 (s : fin (bentropy \u0393).succ), \u27e6\u27e8q, 0, v\u27e9, T, H\u27e7 \u27f6^(s)[\u03c3] \u27e6\u27e8q, s, memory v T H s\u27e9, T, H.map ((+) s)\u27e7\n| \u27e80, _\u27e9      := by { simp, ext, simp, }\n| \u27e8s + 1, hs\u27e9 := by { \n    let s' : fin (bentropy \u0393).succ := \u27e8s, by omega\u27e9,\n    have r : \u27e6\u27e8q, 0, v\u27e9, T, H\u27e7 \u27f6^(s)[\u03c3] \u27e6\u27e8q, \u27e8s, _\u27e9, memory v T H \u27e8s, _\u27e9\u27e9, T, H.map ((+) s)\u27e7,\n    from \u03c3_time_reductions \u27e8s, by omega\u27e9,\n    have : \u27e6\u27e8q, \u27e8s, _\u27e9, memory v T H \u27e8s, _\u27e9\u27e9, T, H.map ((+) s)\u27e7 \u27f6\u00b9[\u03c3] \u27e6\u27e8q, \u27e8s + 1, _\u27e9, memory v T H \u27e8s + 1, _\u27e9\u27e9, T, _\u27e7,\n    by simpa[memory] using\n      \u03c3_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 : \u2200 (s : fin (bentropy \u0393).succ) k i (h : \u2191i < s), \n  ((memory v T H s).nth k).nth i = T.nth k (i + H.nth k)\n| \u27e80, _\u27e9 k i hi := by simp at hi; contradiction\n| \u27e8s + 1, hs\u27e9 k \u27e8i, hi\u27e9 h := by { \n    have : i = s \u2228 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 \u2260 i, from ne_of_gt lt,\n      simp[this],\n      simpa using memory_nth_nth_of_lt \u27e8s, lt_trans (lt_add_one s) hs\u27e9 k \u27e8i, hi\u27e9 (by simpa using lt) } }\n\nlemma \u03c3_time_reductions_top (q : Q) : \u27e6\u27e8q, 0, v\u27e9, T, H\u27e7 \u27f6^(bentropy \u0393)[\u03c3] \u27e6\u27e8q, \u22a4, memory v T H \u22a4\u27e9, T, H.map ((+) (bentropy \u0393))\u27e7 :=\n\u03c3_time_reductions v T H q \u22a4\n\nlemma memory_nth_nth (k i) : ((memory v T H \u22a4).nth k).nth i = T.nth k (i + H.nth k) :=\nmemory_nth_nth_of_lt v T H \u22a4 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 \u0393).succ) (v : vector (vector bool (bentropy \u0393)) \u03b9) (u : vector instruction \u03b9) : state\n\nvariables {\u0393 Q \u03b9}\n\ninstance [state_lang Q] : state_lang (state \u0393 Q \u03b9) :=\n\u27e8state.intro start \u22a4 default Stay, state.intro halt 0 default Stay\u27e9\n\ndef \u03b4 : state \u0393 Q \u03b9 \u2192 vector bool \u03b9 \u2192 option (state \u0393 Q \u03b9 \u00d7 vector bool \u03b9 \u00d7 vector instruction \u03b9)\n| \u27e8q, \u27e80, _\u27e9, v, u\u27e9      x := none\n| \u27e8q, \u27e8i + 1, hi\u27e9, v, u\u27e9 x := \n    let newstate : state \u0393 Q \u03b9 := \u27e8q, \u27e8i, by omega\u27e9, v, u\u27e9,\n        i' : fin (bentropy \u0393)  := \u27e8i, nat.succ_lt_succ_iff.mp hi\u27e9 in \n  some \u27e8newstate, v.map (\u03bb x, x.nth i'), Left\u27e9\n\n@[simp] lemma \u03b4_top {q v x u} : \u03b4 (\u27e8q, 0, v, u\u27e9 : state \u0393 Q \u03b9) x = none := by unfold has_zero.zero; rw [\u03b4]\n\ndef \u03c3 : sentence bool (state \u0393 Q \u03b9) \u03b9 := sentence.of_fun \u03b4\n(by { unfold start halt,\n      intros q x c z u eqn, split; rintros rfl,\n      { simpa using eqn },\n      { rcases q with \u27e8q, \u27e8i, hi\u27e9, v, u\u27e9, rcases i; simp[\u03b4] at eqn,\n        { contradiction },\n        { have lt : i < bentropy \u0393, from nat.succ_lt_succ_iff.mp hi,\n          have eq : i = bentropy \u0393, 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 \u0393)) \u03b9) (u : vector instruction \u03b9) (T : vector (\u2115 \u2192 bool) \u03b9) (H : vector \u2115 \u03b9)\n\ndef \u03c3_tape_reduct (i) :=\nvector.zip_with3 (\u03bb (t : \u2115 \u2192 bool) h (x : vector bool (bentropy \u0393)) n, if n = h then x.nth i else t n) T H v\n\nlemma \u03c3_reduction (q : Q) (i : \u2115) (hi) :\n  \u27e6\u27e8q, \u27e8i + 1, hi\u27e9, v, u\u27e9, T, H\u27e7 \u27f6\u00b9[\u03c3]\n  \u27e6\u27e8q, \u27e8i, by omega\u27e9, v, u\u27e9, \u03c3_tape_reduct v T H \u27e8i, nat.succ_lt_succ_iff.mp hi\u27e9, H.map nat.pred\u27e7 :=\nreduction.iff.mpr (\u27e8v.map (\u03bb x, x.nth \u27e8i, (by omega)\u27e9), Left, by simp[\u03c3, \u03b4]; refl,\n  by { simp[reduct_tape, \u03c3_tape_reduct], ext, simp }, by { ext, simp, exact nat.pred_eq_sub_one _ }\u27e9)\n\n@[simp] lemma \u03c3_is_halt (q : Q) : \u03c3.is_halt \u27e8q, 0, v, u\u27e9 :=\n\u03bb c z u x, by simp[\u03c3]\n\ndef Tape : fin (bentropy \u0393).succ \u2192 vector (vector bool (bentropy \u0393)) \u03b9 \u2192 vector (\u2115 \u2192 bool) \u03b9 \u2192 vector \u2115 \u03b9 \u2192 vector (\u2115 \u2192 bool) \u03b9\n| \u27e80, _\u27e9      v T H := T\n| \u27e8s + 1, hn\u27e9 v T H := Tape \u27e8s, by omega\u27e9 v (\u03c3_tape_reduct v T H \u27e8s, nat.succ_lt_succ_iff.mp hn\u27e9) (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 \u03c3_time_reductions (q : Q) :\n  \u2200 (s : fin (bentropy \u0393).succ) (T H), \u27e6\u27e8q, s, v, u\u27e9, T, H\u27e7 \u27f6^(s)[\u03c3] \u27e6\u27e8q, 0, v, u\u27e9, Tape s v T H, (H.map (\u03bb h, h - s))\u27e7\n| \u27e80, _\u27e9      T H := by { simp, ext, simp }\n| \u27e8s + 1, hs\u27e9 T H := by { \n    let s' : fin (bentropy \u0393).succ := \u27e8s, by omega\u27e9,\n    let s'' : fin (bentropy \u0393) := \u27e8s, by { exact nat.succ_lt_succ_iff.mp hs}\u27e9,\n    have r : \u27e6\u27e8q, \u27e8s, _\u27e9, v, u\u27e9, _, H.map nat.pred\u27e7 \u27f6^(s)[\u03c3] \u27e6\u27e8q, 0, v, u\u27e9, _, H.map (\u03bb h, h - (s + 1))\u27e7,\n    { have := \u03c3_time_reductions \u27e8s, by omega\u27e9 (\u03c3_tape_reduct v T H \u27e8s, by omega\u27e9) (H.map nat.pred), simp at this, \n      rw[show (H.map nat.pred).map (\u03bb h, h - s) = H.map (\u03bb 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 : \u27e6\u27e8q, \u27e8s + 1, _\u27e9, v, u\u27e9, T, H\u27e7 \u27f6\u00b9[\u03c3] \u27e6\u27e8q, \u27e8s, _\u27e9, v, u\u27e9, _, H.map nat.pred\u27e7,\n    from \u03c3_reduction v u T H q s hs,\n    have : \u27e6\u27e8q, \u27e8s + 1, _\u27e9, v, u\u27e9, T, H\u27e7 \u27f6^(s+1)[\u03c3] \u27e6\u27e8q, 0, v, u\u27e9, _, H.map (\u03bb h, h - (s + 1))\u27e7,\n    from relation.power.succ_inv this r,\n    simpa[Tape, @sub_add_eq_sub_sub \u2115] using this }\n\nend\n\nend write\n\nend blang\n\n\nnamespace universal_tm\nvariables {\u0393 Q \u03b9}\n\nabbreviation lang := word \u0393 Q \u03b9 \u2295 vector \u0393 \u03b9\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": "import Days\nimport Days.Common\nimport Std\nimport Lean.Data.Parsec\n\nopen Days\nopen Days.Common\nnamespace Days.Day07\ndef day: ProblemNumber := 07\n\nopen Std (RBMap mkRBMap)\n\nopen Lean.Parsec\nopen Lean (Parsec)\n\n/--\nYou can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?\n\nThe device the Elves gave you has problems with more than just its communication system. You try to run a system update:\n\n```\n$ system-update --please --pretty-please-with-sugar-on-top\nError: No space left on device\n```\n\nPerhaps you can delete some files to make space for the update?\n\nYou browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example:\n\n```\n$ cd /\n$ ls\ndir a\n14848514 b.txt\n8504156 c.dat\ndir d\n$ cd a\n$ ls\ndir e\n29116 f\n2557 g\n62596 h.lst\n$ cd e\n$ ls\n584 i\n$ cd ..\n$ cd ..\n$ cd d\n$ ls\n4060174 j\n8033020 d.log\n5626152 d.ext\n7214296 k\n```\n\nThe filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called `/`. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in.\n\nWithin the terminal output, lines that begin with `$` are **commands you executed**, very much like some modern computers:\n\n- `cd` means **change directory**. This changes which directory is the current directory, but the specific result depends on the argument:\n  - `cd x` moves **in** one level: it looks in the current directory for the directory named `x` and makes it the current directory.\n  - `cd ..` moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory.\n  - `cd /` switches the current directory to the outermost directory, `/`.\n- `ls` means list. It prints out all of the files and directories immediately contained by the current directory:\n  - `123 abc` means that the current directory contains a file named `abc` with size `123`.\n  - `dir xyz` means that the current directory contains a directory named `xyz`.\n\nGiven the commands and output in the example above, you can determine that the filesystem looks visually like this:\n\n```\n- / (dir)\n  - a (dir)\n    - e (dir)\n      - i (file, size=584)\n    - f (file, size=29116)\n    - g (file, size=2557)\n    - h.lst (file, size=62596)\n  - b.txt (file, size=14848514)\n  - c.dat (file, size=8504156)\n  - d (dir)\n    - j (file, size=4060174)\n    - d.log (file, size=8033020)\n    - d.ext (file, size=5626152)\n    - k (file, size=7214296)\n```\n\nHere, there are four directories: `/` (the outermost directory), `a` and `d` (which are in `/`), and `e` (which is in `a`). These directories also contain files of various sizes.\n\nSince the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the **total size** of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.)\n\nThe total sizes of the directories above can be found as follows:\n\n- The total size of directory `e` is **584** because it contains a single file `i` of size 584 and no other directories.\n- The directory `a` has total size **94853** because it contains files `f` (size 29116), `g` (size 2557), and `h.lst` (size 62596), plus file `i` indirectly (`a` contains `e` which contains `i`).\n- Directory `d` has total size **24933642**.\n- As the outermost directory, `/` contains every file. Its total size is **48381165**, the sum of the size of every file.\n\nTo begin, find all of the directories with a total size of **at most 100000**, then calculate the sum of their total sizes. In the example above, these directories are `a` and `e`; the sum of their total sizes is **95437** (94853 + 584). (As in this example, this process can count files more than once!)\n\nFind all of the directories with a total size of at most 100000. \n\n**What is the sum of the total sizes of those directories?**\n-/\n\nabbrev DirName := String\n\ninductive ChangeDir where\n  | up : ChangeDir\n  | root : ChangeDir\n  | dir (name: DirName) : ChangeDir\n  deriving Repr, BEq, DecidableEq\n\nabbrev FileSize := Nat\nabbrev FileName := String\n\ninductive FsEntry where\n  | directory (parent: List DirName) (name: DirName) : FsEntry\n  | file (size: FileSize) (name: FileName) : FsEntry\n  deriving Repr, BEq, DecidableEq\n\ninductive Command where\n  | cd (parent: List DirName) (target: ChangeDir) : Command\n  | ls (dir: List DirName) (children: List FsEntry) : Command\n  deriving Repr, BEq, DecidableEq\n\ndef mkAbsolutePath (dir: List DirName) := (String.intercalate \"/\" dir.reverse)\n\ndef wordUntilSpaceOrNewLine : Parsec String :=\n      many1Chars (do \n        let c \u2190 peek?\n        if c != some ' ' \u2227 c != some '\\n' \n        then anyChar\n        else fail \"Found space\")\n\ndef parseCd (parent: List DirName) : Parsec Command := do\n  _ \u2190 pstring \"cd\" <* pchar ' ' <* ws\n  return Command.cd parent <| match \u2190 (pstring \"/\" <|> pstring \"..\" <|> wordUntilSpaceOrNewLine) with \n  | \"/\" => ChangeDir.root\n  | \"..\" => ChangeDir.up\n  | dir => ChangeDir.dir dir\n\n#eval [\"cd /\".iter, \"cd ..\".iter, \"cd foo\".iter] |>.map $ parseCd []\n\ndef parseLs (parent: List DirName) : Parsec Command := do\n  _ \u2190 pstring \"ls\" <* ws\n  return Command.ls parent <| \u2190 parseChildren\n  where\n    parseDir := do \n      let dirName \u2190 pstring \"dir\" *>  ws *> wordUntilSpaceOrNewLine <* ws\n      return FsEntry.directory parent dirName\n    \n    parseFile := do\n      let size: Nat := (\u2190 ws *> many1Chars digit <* ws) |> String.toNat!\n      let fileName \u2190 wordUntilSpaceOrNewLine <* ws\n      return FsEntry.file size fileName\n\n    parseChildren := do\n      return Array.toList <| \u2190 ws *> many (parseDir <|> parseFile)\n\n#eval parseLs [] \"ls\ndir e\n29116 f\n2557 g\n62596 h.lst\".iter\n\ndef parseCommand (currentDir: List DirName) : Parsec Command := \n  ws *> (parseCd currentDir <|> parseLs currentDir) <* ws\n\n#eval [\"cd /\".iter, \"ls\\ndir name\\n1235 test\".iter] |>.map $ parseCommand [\"foo\", \"/\"]\n\nstructure ParseContext where\n  currentDir: List DirName\n  commands: Array Command\n\ndef parseCommands (input: String) : Except String $ List Command :=\n  commands.map (Array.toList $ \u00b7.commands)\n  where\n    commandLines := input.splitOn \"$ \" |>.filter (\u00ac\u00b7.isEmpty)\n    commands :=\n      commandLines\n      |>.map (\u00b7.iter)\n      |>.foldl (init:=Except.ok (ParseContext.mk [] #[])) \u03bb\n      | Except.error e, _ => .error e\n      | .ok ctx, line => match parseCommand ctx.currentDir line with\n      | .success _ cmd => Except.ok (match cmd with \n        | Command.ls _ _ => { ctx with commands := ctx.commands.push cmd }\n        | Command.cd _ dir => {\n            ctx with \n              commands := ctx.commands.push cmd, \n              currentDir := match dir with \n                | ChangeDir.root => [\"/\"]\n                | ChangeDir.up => ctx.currentDir.tail!\n                | ChangeDir.dir name => name::ctx.currentDir\n            } \n        )\n      | .error _ msg => Except.error s!\"Failed to parse commands: {msg}\"\n\ninductive FileSystemTree\n  | dir: DirName -> List FileSystemTree -> FileSystemTree\n  | file (size: FileSize) (name: FileName) : FileSystemTree\n\nabbrev FsMap := RBMap String (List FsEntry) compare\n\ndef buildDirMap (input: String) : Except String $ FsMap := \n  buildTree\n  where\n    buildTree :=\n      parseCommands input\n      |>.map (\u03bb res =>\n        res\n        |>.foldl (init:=mkRBMap String (List FsEntry) compare) \u03bb\n          | map, Command.cd _ _ => map\n          | map, Command.ls dir children => \n            map.insert (mkAbsolutePath dir) children\n      )\n\npartial def dirSize (map: FsMap) (dir: String): Nat :=\n  let entries := map.find? dir \n  (match entries with \n  | some a => a \n  | none => [])\n  |>.foldl (init:=0) (\u03bb\n  | acc, FsEntry.directory parent dir => \n    acc + dirSize map (mkAbsolutePath (dir::parent))\n  | acc, FsEntry.file size _ => \n    acc + size\n  )\n\ndef parseFsMap (input: String) : FsMap :=\n  match buildDirMap input with\n  | .ok res => res\n  | .error msg => panic! s!\"Failed to parse input! {msg}\"\n\ndef findDirSizesMatchingPredicate (filter: Nat \u2192 Bool) (map: FsMap) : List Nat :=\n  map.keysList\n  |>.map (dirSize map \u00b7)\n  |>.filter filter\n\ndef sumAllLessThanSize (filter: Nat \u2192 Bool) (map: FsMap): Nat :=\n  findDirSizesMatchingPredicate filter map \n  |> sum\n\ndef part\u2081 (input: Input) : Nat :=\n  parseFsMap input.text\n  |> sumAllLessThanSize (\u00b7 \u2264 100000)\n\n/--\nNow, you're ready to choose a directory to delete.\n\nThe total disk space available to the filesystem is **`70000000`**. To run the update, you need unused space of at least **`30000000`**. You need to find a directory you can delete that will **free up enough space** to run the update.\n\nIn the example above, the total size of the outermost directory (and thus the total amount of used space) is `48381165`; this means that the size of the **unused** space must currently be `21618835`, which isn't quite the `30000000` required by the update. Therefore, the update still requires a directory with total size of at least `8381165` to be deleted before it can run.\n\nTo achieve this, you have the following options:\n\nDelete directory `e`, which would increase unused space by `584`.\nDelete directory `a`, which would increase unused space by `94853`.\nDelete directory `d`, which would increase unused space by `24933642`.\nDelete directory `/`, which would increase unused space by `48381165`.\n\nDirectories `e` and `a` are both too small; deleting them would not free up enough space. However, directories `d` and `/` are both big enough! Between these, choose the smallest: `d`, increasing unused space by **`24933642`**.\n\nFind the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. \n**What is the total size of that directory?**\n-/\ndef HDSize := 70000000\ndef UpdateSizeRequired := 30000000\n\ndef findSmallestDirMatchingPredicate (filter: Nat \u2192 Bool) (map: FsMap): Nat :=\n  findDirSizesMatchingPredicate filter map\n  |>.minimum?\n  |>.get!\n\ndef part\u2082 (input: Input) : Nat :=\n  let fsMap := parseFsMap input.text\n  let totalSizeTaken := dirSize fsMap \"/\"\n  let availableSpace := HDSize - totalSizeTaken\n  let neededSpace := UpdateSizeRequired - availableSpace\n  findSmallestDirMatchingPredicate (. \u2265 neededSpace) fsMap\n  \n\ndef solution : Problem Nat := \u27e8 day, part\u2081, part\u2082 \u27e9 \n\ndef sample := \"$ cd /\n$ ls\ndir a\n14848514 b.txt\n8504156 c.dat\ndir d\n$ cd a\n$ ls\ndir e\n29116 f\n2557 g\n62596 h.lst\n$ cd e\n$ ls\n584 i\n$ cd ..\n$ cd ..\n$ cd d\n$ ls\n4060174 j\n8033020 d.log\n5626152 d.ext\n7214296 k\"\n\n#eval parseCommands sample\n\ndef sampleMap := parseFsMap sample\n\n#eval sampleMap\n\n#eval 584 = dirSize sampleMap \"//a/e\"\n#eval 94853 = dirSize sampleMap \"//a\"\n#eval 24933642 = dirSize sampleMap \"//d\"\n\n#eval testPart\u2081 solution sample (expect:=95437)\n#eval testPart\u2082 solution sample (expect:=24933642)\n\n", "meta": {"author": "jakeswenson", "repo": "advent2022", "sha": "af941092292ff0bc5552bce9c145d6b5b173c20d", "save_path": "github-repos/lean/jakeswenson-advent2022", "path": "github-repos/lean/jakeswenson-advent2022/advent2022-af941092292ff0bc5552bce9c145d6b5b173c20d/Days/Day07.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.061875983561210525, "lm_q1q2_score": 0.020274799207606428}}
{"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 \u27e8\"SAS912\", by simp\u27e9 (some \u27e8\"5100\", by simp\u27e9)\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 \u27e82, by simp\u27e9) (some \u27e8\"FK27\", by simp\u27e9) .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  : \u00ac (.b1 \u2208 f10b \u2227 .b2 \u2208 f10b) \u2227\n         \u00ac (.u1 \u2208 f10b \u2227 .u2 \u2208 f10b) \u2227\n         \u00ac (.v1 \u2208 f10b \u2227 .v2 \u2208 f10b)\n\n/-\n### Field 10 Example\n\n`-SAFR/SV1`\n-/\nexample := (\u27e8[.s, .a, .f, .r], [.s, .v1], by simp\u27e9 : 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 \u27e8\"EHAM\", by simp\u27e9)) 63072027000\n\n/-\n`-AFIL1625`\n-/\nexample : Field13 := \u27e8some .afil, 63072059100\u27e9\n\n/-\nThe designator in Field 13, if there is one.\n-/\ndef Field13.desigOf : Field13 \u2192 Option Doc7910.Designator\n  | \u27e8some (.adep desig), _\u27e9 => 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 := \u27e8\u27e8\u27e8540, sorry\u27e9, .kt, .ias, by simp\u27e9, sorry\u27e9\n  level := \u27e85500, .feet, .altitude\u27e9\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   : \u00ac (point.isNone \u2227 rte.isNone)\n\n/-\nThe named waypoint in a route element, if there is one.\n-/\ndef RouteElement.waypointOf : RouteElement \u2192 Option Waypoint\n  | \u27e8some rp, _, _\u27e9 => rp.pos.waypointOf\n  | _               => none \n\n/-\nThe ATS route designator in a route element, if there is one.\n-/\ndef RouteElement.atsRteOf : RouteElement \u2192 Option RouteDesignator\n  | \u27e8_, some (.rte rd), _\u27e9 => rd\n  | _                      => none \n\n/-\nDoes the route element indicate _direct_ to the next point?\n-/\ndef RouteElement.isDct : RouteElement \u2192 Bool\n  | \u27e8_, some .dct, _\u27e9 => true\n  | _                 => false \n\n/-\nThe flight rules change in a route element, if there is one.\n-/\ndef RouteElement.ruleOf : RouteElement \u2192 Option FlightRule\n  | \u27e8some rp, _, _\u27e9 => 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 \u2295 Truncate)\n  -- Must be at least one route element.\n  inv            : elements \u2260 \u2205 \u2227\n  -- Consecutive flight rules changes must be distinct.\n                   let rules := (elements.map RouteElement.ruleOf).reduceOption\n                   rules.Chain' (\u00b7 \u2260 \u00b7) \u2227\n  -- DCT must be followed by an explicit point.\n                   elements.Chain' (\u00b7.isDct \u2192 \u00b7.point.isSome) \u2227\n  -- An ATS route designator must connect to another designator or a named point.\n                   elements.Chain'\n                     (fun re\u2081 re\u2082 \u21a6 re\u2081.atsRteOf.isSome \u2192\n                        re\u2082.waypointOf.isSome \u2228 (re\u2082.point.isNone \u2227 re\u2082.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 \u27e8\"WOL\", by simp\u27e9) (some (.rte \u27e8\"H65\", by simp\u27e9)) (by simp),\n  RouteElement.mk (mkWpt \u27e8\"RAZZI\", by simp\u27e9) (some (.rte \u27e8\"Q29\", by simp\u27e9)) (by simp),\n  RouteElement.mk (mkWpt \u27e8\"LIZZI\", by simp\u27e9) (some .dct) (by simp)\n]\nwhere mkWpt (wpt : Waypoint) : Option RoutePoint :=\n  some \u27e8.wpt wpt, none, none\u27e9\n\nexample := {\n  f15a := \u27e8\u27e8\u27e80.79, sorry\u27e9, .mach, .tas, by simp\u27e9, by simp\u27e9,  -- M079\n  f15b := some \u27e8380, .feet, .flightLevel\u27e9,                   -- F380\n  f15c := \u27e8none, exElems, none, sorry\u27e9 : 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 \u2227\n  -- Upper limit on number of alternate aerodromes.\n         f16c.length \u2264 maxAlternateDestinations\n\n/-\n### Field 16 Example\n\n`-EHAM0645 EBBR ZZZZ`\n-/\nexample := Field16.mk (some \u27e8\"EHAM\", by simp\u27e9) 24300 [some \u27e8\"EBBR\", by simp\u27e9, none] (by simp)\n\n/-\nAre a departure and destination aerodrome the same?\n-/\ndef adepIsAdes : Field13a \u2192 Field16a \u2192 Bool\n  | none, none                       => True\n  | some (.adep desig\u2081), some desig\u2082 => desig\u2081 = desig\u2082\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 \u2194 f17c.isSome\n\n/-\n### Field 17 Example\n\n`-ZZZZ1620 DEN HELDER`\n-/\nexample := Field17.mk none 63072058800 (some \u27e8\"DEN HELDER\", by simp\u27e9)\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 \u2295 Position\n  duration : Duration\n\n/-\nThe `<` order relation on EET points. Ordered by the duration.\n-/\ninstance : LT ElapsedTimePoint where\n  lt et\u2081 et\u2082 := LT.lt et\u2081.duration et\u2082.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 \u2295 ATSUnit)\n  dest : Option NameAndPosition\n  reg  : List Registration\n  eet  : List ElapsedTimePoint\n  sel  : Option SelcalCode\n  typ  : List (Option NumberOfAircraft \u00d7 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 \u2264 maxPbnCodes \u2227\n  -- Upper limit on number of alternate aerodromes.\n         altn.length \u2264 maxAlternateDestinations \u2227\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 \u27e8\"RNP2\", by simp\u27e9,\n  com := none,\n  dat := none,\n  sur := none,\n  dep := none,\n  dest := none,\n  reg := [\u27e8\"VHXYZ\", by simp\u27e9]\n  eet := [],\n  sel := some \u27e8\"AFPQ\", by simp\u27e9,\n  typ := [],\n  code := some \u27e8\"7C6DDF\", by simp\u27e9,\n  dle := [],\n  opr := some \u27e8\"FLYOU\", by simp\u27e9,\n  orgn := some \u27e8\"YSSYABCO\", by simp\u27e9,\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 : \u00ac (f7.isNone \u2227f8.isNone \u2227 f9.isNone \u2227 f10.isNone \u2227 f13.isNone \u2227 f15.isNone \u2227 f16.isNone \u2227 f18.isNone)\n\n/-\n### Field 22 Example\n\n`-8/IX-13/EDDN1230`\n-/\nexample : Field22 where\n  f7 := none\n  f8 := some \u27e8.i, some .x\u27e9\n  f9 := none\n  f10 := none\n  f13 := some \u27e8some (.adep \u27e8\"EDDN\", by simp\u27e9), 63072027000\u27e9\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 \u2192 Field15 \u2192 Prop\n  | f8, \u27e8_, none, _\u27e9 => f8.f8a \u2208 [.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 \u2208 [.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 \u2192 Option Field18 \u2192 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 \u2192 Option Field18 \u2192 Prop\n  | f10, some f18 => \u00ac (.w \u2208 f10.f10a \u2227 .nonrvsm \u2208 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 \u2192 Option Field18 \u2192 Prop\n  | f10, none     => .r \u2209 f10.f10a\n  | f10, some f18 => .r \u2208 f10.f10a \u2194 f18.pbn \u2260 \u2205 \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 \u2192 Option Field18 \u2192 Prop\n  | f10, none     => .z \u2209 f10.f10a\n  | f10, some f18 => .z \u2208 f10.f10a \u2194 f18.com.isSome \u2228 f18.nav.isSome \u2228 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 \u2192 Option Field18 \u2192 Prop\n  | -- If designator in 13a, 18 DEP not populated.\n    \u27e8(some (.adep _)), _\u27e9, none\n  | \u27e8some (.adep _), _\u27e9, some {dep := none, ..}\n  | -- If ZZZZ in 13a, must have departure point in 18 DEP.\n    \u27e8none, _\u27e9, some {dep := some (.inl _), ..}\n  | -- If AFIL in 13a, must have ATS unit in 18 DEP.\n    \u27e8some .afil, _\u27e9, 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 \u2192 Option Field18 \u2192 Prop\n  | f15, some f18 => f18.dle.map (\u00b7.point) \u2286 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 \u2192 Option Field18 \u2192 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 \u2192 Option Field18 \u2192 Prop\n  | {f16b := teet, ..}, some f18 => f18.eet.all (\u00b7.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 \u2192 Option Field18 \u2192 Prop\n  | {f16b := teet, ..}, some f18 => (f18.dle.map (\u00b7.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 \u2192 Option Field18 \u2192 Prop\n  | {f16c := [], ..}, none => True\n  | {f16c := altn16, ..}, some {altn := altn18, ..}\n                           => (altn16.filter (\u00b7.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 \u2192 Option Field17 \u2192 Prop\n  | some dest, some {f17a := some arr, ..} => dest \u2260 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) 2022 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\n\nimport Std.Tactic.NormCast.Ext\nimport Lean.Elab.ElabRules\n\nopen Lean Meta\n/-- `add_elim foo` registers `foo` as an elim-lemma in `norm_cast`. -/\nlocal elab \"add_elim\" id:ident : command =>\n  Elab.Command.liftCoreM do MetaM.run' do\n    Std.Tactic.NormCast.addElim (\u2190 resolveGlobalConstNoOverload id)\n\nadd_elim ne_eq\n\nattribute [coe] Fin.val Array.ofSubarray\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/Lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.05419872829548198, "lm_q1q2_score": 0.02026359413465296}}
{"text": "/-\nCopyright (c) 2017 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl, 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 {\u03b1 : Type u} {\u03b9 : Sort v}\n\ndef complete_lattice.copy (c : complete_lattice \u03b1)\n  (le : \u03b1 \u2192 \u03b1 \u2192 Prop) (eq_le : le = @complete_lattice.le \u03b1 c)\n  (top : \u03b1) (eq_top : top = @complete_lattice.top \u03b1 c)\n  (bot : \u03b1) (eq_bot : bot = @complete_lattice.bot \u03b1 c)\n  (sup : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (eq_sup : sup = @complete_lattice.sup \u03b1 c)\n  (inf : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (eq_inf : inf = @complete_lattice.inf \u03b1 c)\n  (Sup : set \u03b1 \u2192 \u03b1) (eq_Sup : Sup = @complete_lattice.Sup \u03b1 c)\n  (Inf : set \u03b1 \u2192 \u03b1) (eq_Inf : Inf = @complete_lattice.Inf \u03b1 c) :\n  complete_lattice \u03b1 :=\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 \u03b1 c,\n  exact @complete_lattice.le_trans \u03b1 c,\n  exact @complete_lattice.le_antisymm \u03b1 c,\n  exact @complete_lattice.le_sup_left \u03b1 c,\n  exact @complete_lattice.le_sup_right \u03b1 c,\n  exact @complete_lattice.sup_le \u03b1 c,\n  exact @complete_lattice.inf_le_left \u03b1 c,\n  exact @complete_lattice.inf_le_right \u03b1 c,\n  exact @complete_lattice.le_inf \u03b1 c,\n  exact @complete_lattice.le_top \u03b1 c,\n  exact @complete_lattice.bot_le \u03b1 c,\n  exact @complete_lattice.le_Sup \u03b1 c,\n  exact @complete_lattice.Sup_le \u03b1 c,\n  exact @complete_lattice.Inf_le \u03b1 c,\n  exact @complete_lattice.le_Inf \u03b1 c\nend\n\nend lattice\n\nopen set lattice\n\nsection order\nvariables {\u03b1 : Type u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop)\nlocal infix `\u227c` : 50 := r\n\nlemma directed_on_Union {r} {\u03b9 : Sort v} {f : \u03b9 \u2192 set \u03b1} (hd : directed (\u2286) f)\n  (h : \u2200x, directed_on r (f x)) : directed_on r (\u22c3x, f x) :=\nby simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact\nassume a\u2081 b\u2081 fb\u2081 a\u2082 b\u2082 fb\u2082,\nlet \u27e8z, zb\u2081, zb\u2082\u27e9 := hd b\u2081 b\u2082,\n    \u27e8x, xf, xa\u2081, xa\u2082\u27e9 := h z a\u2081 (zb\u2081 fb\u2081) a\u2082 (zb\u2082 fb\u2082) in\n\u27e8x, \u27e8z, xf\u27e9, xa\u2081, xa\u2082\u27e9\n\nend order\n\ntheorem directed_of_chain {\u03b1 \u03b2 r} [is_refl \u03b2 r] {f : \u03b1 \u2192 \u03b2} {c : set \u03b1}\n  (h : zorn.chain (f \u207b\u00b9'o r) c) :\n  directed r (\u03bbx:{a:\u03b1 // a \u2208 c}, f (x.val)) :=\nassume \u27e8a, ha\u27e9 \u27e8b, hb\u27e9, classical.by_cases\n  (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists];\n    exact \u27e8b, hb, refl _\u27e9)\n  (assume : a \u2260 b, (h a ha b hb this).elim\n    (\u03bb h : r (f a) (f b), \u27e8\u27e8b, hb\u27e9, h, refl _\u27e9)\n    (\u03bb h : r (f b) (f a), \u27e8\u27e8a, ha\u27e9, refl _, h\u27e9))\n\nstructure filter (\u03b1 : Type*) :=\n(sets                   : set (set \u03b1))\n(univ_sets              : set.univ \u2208 sets)\n(sets_of_superset {x y} : x \u2208 sets \u2192 x \u2286 y \u2192 y \u2208 sets)\n(inter_sets {x y}       : x \u2208 sets \u2192 y \u2208 sets \u2192 x \u2229 y \u2208 sets)\n\n/-- If `F` is a filter on `\u03b1`, and `U` a subset of `\u03b1` then we can write `U \u2208 F` as on paper. -/\n@[reducible]\ninstance {\u03b1 : Type*}: has_mem (set \u03b1) (filter \u03b1) := \u27e8\u03bb U F, U \u2208 F.sets\u27e9\n\nnamespace filter\nvariables {\u03b1 : Type u} {f g : filter \u03b1} {s t : set \u03b1}\n\nlemma filter_eq : \u2200{f g : filter \u03b1}, f.sets = g.sets \u2192 f = g\n| \u27e8a, _, _, _\u27e9 \u27e8._, _, _, _\u27e9 rfl := rfl\n\nlemma filter_eq_iff : f = g \u2194 f.sets = g.sets :=\n\u27e8congr_arg _, filter_eq\u27e9\n\nprotected lemma ext_iff : f = g \u2194 \u2200 s, s \u2208 f \u2194 s \u2208 g :=\nby rw [filter_eq_iff, ext_iff]\n\n@[extensionality]\nprotected lemma ext : (\u2200 s, s \u2208 f \u2194 s \u2208 g) \u2192 f = g :=\nfilter.ext_iff.2\n\nlemma univ_mem_sets : univ \u2208 f :=\nf.univ_sets\n\nlemma mem_sets_of_superset : \u2200{x y : set \u03b1}, x \u2208 f \u2192 x \u2286 y \u2192 y \u2208 f :=\nf.sets_of_superset\n\nlemma inter_mem_sets : \u2200{s t}, s \u2208 f \u2192 t \u2208 f \u2192 s \u2229 t \u2208 f :=\nf.inter_sets\n\nlemma univ_mem_sets' (h : \u2200 a, a \u2208 s): s \u2208 f :=\nmem_sets_of_superset univ_mem_sets (assume x _, h x)\n\nlemma mp_sets (hs : s \u2208 f) (h : {x | x \u2208 s \u2192 x \u2208 t} \u2208 f) : t \u2208 f :=\nmem_sets_of_superset (inter_mem_sets hs h) $ assume x \u27e8h\u2081, h\u2082\u27e9, h\u2082 h\u2081\n\nlemma congr_sets (h : {x | x \u2208 s \u2194 x \u2208 t} \u2208 f) : s \u2208 f \u2194 t \u2208 f :=\n\u27e8\u03bb hs, mp_sets hs (mem_sets_of_superset h (\u03bb x, iff.mp)),\n \u03bb hs, mp_sets hs (mem_sets_of_superset h (\u03bb x, iff.mpr))\u27e9\n\nlemma Inter_mem_sets {\u03b2 : Type v} {s : \u03b2 \u2192 set \u03b1} {is : set \u03b2} (hf : finite is) :\n  (\u2200i\u2208is, s i \u2208 f) \u2192 (\u22c2i\u2208is, s i) \u2208 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\u2081 : s i \u2208 f, from hs i (by simp),\n    have h\u2082 : (\u22c2x\u2208is, s x) \u2208 f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true],\n    by simp [inter_mem_sets h\u2081 h\u2082])\n\nlemma exists_sets_subset_iff : (\u2203t \u2208 f, t \u2286 s) \u2194 s \u2208 f :=\n\u27e8assume \u27e8t, ht, ts\u27e9, mem_sets_of_superset ht ts, assume hs, \u27e8s, hs, subset.refl _\u27e9\u27e9\n\nlemma monotone_mem_sets {f : filter \u03b1} : monotone (\u03bbs, s \u2208 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, \u22ef, hn]` replaces a goal of the form `s \u2208 f`\nand terms `h1 : t1 \u2208 f, \u22ef, hn : tn \u2208 f` with `\u2200x, x \u2208 t1 \u2192 \u22ef \u2192 x \u2208 tn \u2192 x \u2208 s`.\n\n`filter_upwards [h1, \u22ef, hn] e` is a short form for `{ filter_upwards [h1, \u22ef, 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 (\u03bb 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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {\u03b9 : Sort x}\n\nsection principal\n\n/-- The principal filter of `s` is the collection of all supersets of `s`. -/\ndef principal (s : set \u03b1) : filter \u03b1 :=\n{ sets             := {t | s \u2286 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 \u03b1) :=\n\u27e8principal \u2205\u27e9\n\n@[simp] lemma mem_principal_sets {s t : set \u03b1} : s \u2208 principal t \u2194 t \u2286 s := iff.rfl\n\nlemma mem_principal_self (s : set \u03b1) : s \u2208 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 \u2208 join f \u2194 {t | s \u2208 t} \u2208 f`. -/\ndef join (f : filter (filter \u03b1)) : filter \u03b1 :=\n{ sets             := {s | {t : filter \u03b1 | s \u2208 t} \u2208 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 \u27e8h\u2081, h\u2082\u27e9, inter_mem_sets h\u2081 h\u2082 }\n\n@[simp] lemma mem_join_sets {s : set \u03b1} {f : filter (filter \u03b1)} :\n  s \u2208 join f \u2194 {t | s \u2208 filter.sets t} \u2208 f := iff.rfl\n\nend join\n\nsection lattice\n\ninstance : partial_order (filter \u03b1) :=\n{ le            := \u03bbf g, g.sets \u2286 f.sets,\n  le_antisymm   := assume a b h\u2081 h\u2082, filter_eq $ subset.antisymm h\u2082 h\u2081,\n  le_refl       := assume a, subset.refl _,\n  le_trans      := assume a b c h\u2081 h\u2082, subset.trans h\u2082 h\u2081 }\n\ntheorem le_def {f g : filter \u03b1} : f \u2264 g \u2194 \u2200 x \u2208 g, x \u2208 f := iff.rfl\n\n/-- `generate_sets g s`: `s` is in the filter closure of `g`. -/\ninductive generate_sets (g : set (set \u03b1)) : set \u03b1 \u2192 Prop\n| basic {s : set \u03b1}      : s \u2208 g \u2192 generate_sets s\n| univ {}                : generate_sets univ\n| superset {s t : set \u03b1} : generate_sets s \u2192 s \u2286 t \u2192 generate_sets t\n| inter {s t : set \u03b1}    : generate_sets s \u2192 generate_sets t \u2192 generate_sets (s \u2229 t)\n\n/-- `generate g` is the smallest filter containing the sets `g`. -/\ndef generate (g : set (set \u03b1)) : filter \u03b1 :=\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 \u03b1)} {f : filter \u03b1} : f \u2264 filter.generate s \u2194 s \u2286 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 \u03b1)) (hs : (generate s).sets = s) : filter \u03b1 :=\n{ sets             := s,\n  univ_sets        := hs \u25b8 (univ_mem_sets : univ \u2208 generate s),\n  sets_of_superset := assume x y, hs \u25b8 (mem_sets_of_superset : x \u2208 generate s \u2192 x \u2286 y \u2192 y \u2208 generate s),\n  inter_sets       := assume x y, hs \u25b8 (inter_mem_sets : x \u2208 generate s \u2192 y \u2208 generate s \u2192 x \u2229 y \u2208 generate s) }\n\nlemma mk_of_closure_sets {s : set (set \u03b1)} {hs : (generate s).sets = s} :\n  filter.mk_of_closure s hs = generate s :=\nfilter.ext $ assume u,\nshow u \u2208 (filter.mk_of_closure s hs).sets \u2194 u \u2208 (generate s).sets, from hs.symm \u25b8 iff.refl _\n\n/- Galois insertion from sets of sets into a filters. -/\ndef gi_generate (\u03b1 : Type*) :\n  @galois_insertion (set (set \u03b1)) (order_dual (filter \u03b1)) _ _ filter.generate filter.sets :=\n{ gc        := assume s f, sets_iff_generate,\n  le_l_u    := assume f u, generate_sets.basic,\n  choice    := \u03bbs 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 \u03b1) := \u27e8\u03bbf g : filter \u03b1,\n{ sets             := {s | \u2203 (a \u2208 f) (b \u2208 g), a \u2229 b \u2286 s },\n  univ_sets        := \u27e8_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _\u27e9,\n  sets_of_superset := assume x y \u27e8a, ha, b, hb, h\u27e9 xy, \u27e8a, ha, b, hb, subset.trans h xy\u27e9,\n  inter_sets       := assume x y \u27e8a, ha, b, hb, hx\u27e9 \u27e8c, hc, d, hd, hy\u27e9,\n    \u27e8_, inter_mem_sets ha hc, _, inter_mem_sets hb hd,\n      calc a \u2229 c \u2229 (b \u2229 d) = (a \u2229 b) \u2229 (c \u2229 d) : by ac_refl\n        ... \u2286 x \u2229 y : inter_subset_inter hx hy\u27e9 }\u27e9\n\n@[simp] lemma mem_inf_sets {f g : filter \u03b1} {s : set \u03b1} :\n  s \u2208 f \u2293 g \u2194 \u2203t\u2081\u2208f.sets, \u2203t\u2082\u2208g.sets, t\u2081 \u2229 t\u2082 \u2286 s := iff.rfl\n\nlemma mem_inf_sets_of_left {f g : filter \u03b1} {s : set \u03b1} (h : s \u2208 f) : s \u2208 f \u2293 g :=\n\u27e8s, h, univ, univ_mem_sets, inter_subset_left _ _\u27e9\n\nlemma mem_inf_sets_of_right {f g : filter \u03b1} {s : set \u03b1} (h : s \u2208 g) : s \u2208 f \u2293 g :=\n\u27e8univ, univ_mem_sets, s, h, inter_subset_right _ _\u27e9\n\nlemma inter_mem_inf_sets {\u03b1 : Type u} {f g : filter \u03b1} {s t : set \u03b1}\n  (hs : s \u2208 f) (ht : t \u2208 g) : s \u2229 t \u2208 f \u2293 g :=\ninter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht)\n\ninstance : has_top (filter \u03b1) :=\n\u27e8{ sets            := {s | \u2200x, x \u2208 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 _) }\u27e9\n\nlemma mem_top_sets_iff_forall {s : set \u03b1} : s \u2208 (\u22a4 : filter \u03b1) \u2194 (\u2200x, x \u2208 s) :=\niff.refl _\n\n@[simp] lemma mem_top_sets {s : set \u03b1} : s \u2208 (\u22a4 : filter \u03b1) \u2194 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 \u03b1) :=\n@order_dual.lattice.complete_lattice _ (gi_generate \u03b1).lift_complete_lattice\n\nlocal attribute [instance] original_complete_lattice\n\ninstance : complete_lattice (filter \u03b1) := 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 \u27e8a, ha, b, hb, hs\u27e9, show s \u2208 complete_lattice.inf f g, from\n      mem_sets_of_superset (inter_mem_sets\n        (@inf_le_left (filter \u03b1) _ _ _ _ ha)\n        (@inf_le_right (filter \u03b1) _ _ _ _ hb)) hs)\n  end\n  /- Sup -/ (join \u2218 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 : (\u22a5 : filter \u03b1).sets = univ := rfl\n\nlemma sup_sets_eq {f g : filter \u03b1} : (f \u2294 g).sets = f.sets \u2229 g.sets :=\n(gi_generate \u03b1).gc.u_inf\n\nlemma Sup_sets_eq {s : set (filter \u03b1)} : (Sup s).sets = (\u22c2f\u2208s, (f:filter \u03b1).sets) :=\n(gi_generate \u03b1).gc.u_Inf\n\nlemma supr_sets_eq {f : \u03b9 \u2192 filter \u03b1} : (supr f).sets = (\u22c2i, (f i).sets) :=\n(gi_generate \u03b1).gc.u_infi\n\nlemma generate_empty : filter.generate \u2205 = (\u22a4 : filter \u03b1) :=\n(gi_generate \u03b1).gc.l_bot\n\nlemma generate_univ : filter.generate univ = (\u22a5 : filter \u03b1) :=\nmk_of_closure_sets.symm\n\nlemma generate_union {s t : set (set \u03b1)} :\n  filter.generate (s \u222a t) = filter.generate s \u2293 filter.generate t :=\n(gi_generate \u03b1).gc.l_sup\n\nlemma generate_Union {s : \u03b9 \u2192 set (set \u03b1)} :\n  filter.generate (\u22c3 i, s i) = (\u2a05 i, filter.generate (s i)) :=\n(gi_generate \u03b1).gc.l_supr\n\n@[simp] lemma mem_bot_sets {s : set \u03b1} : s \u2208 (\u22a5 : filter \u03b1) :=\ntrivial\n\n@[simp] lemma mem_sup_sets {f g : filter \u03b1} {s : set \u03b1} :\n  s \u2208 f \u2294 g \u2194 s \u2208 f \u2227 s \u2208 g :=\niff.rfl\n\n@[simp] lemma mem_Sup_sets {x : set \u03b1} {s : set (filter \u03b1)} :\n  x \u2208 Sup s \u2194 (\u2200f\u2208s, x \u2208 (f:filter \u03b1)) :=\niff.rfl\n\n@[simp] lemma mem_supr_sets {x : set \u03b1} {f : \u03b9 \u2192 filter \u03b1} :\n  x \u2208 supr f \u2194 (\u2200i, x \u2208 f i) :=\nby simp only [supr_sets_eq, iff_self, mem_Inter]\n\n@[simp] lemma le_principal_iff {s : set \u03b1} {f : filter \u03b1} : f \u2264 principal s \u2194 s \u2208 f :=\nshow (\u2200{t}, s \u2286 t \u2192 t \u2208 f) \u2194 s \u2208 f,\n  from \u27e8assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht\u27e9\n\nlemma principal_mono {s t : set \u03b1} : principal s \u2264 principal t \u2194 s \u2286 t :=\nby simp only [le_principal_iff, iff_self, mem_principal_sets]\n\nlemma monotone_principal : monotone (principal : set \u03b1 \u2192 filter \u03b1) :=\nby simp only [monotone, principal_mono]; exact assume a b h, h\n\n@[simp] lemma principal_eq_iff_eq {s t : set \u03b1} : principal s = principal t \u2194 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 \u03b1)} : join (principal s) = Sup s := rfl\n\n/- lattice equations -/\n\nlemma empty_in_sets_eq_bot {f : filter \u03b1} : \u2205 \u2208 f \u2194 f = \u22a5 :=\n\u27e8assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s),\n  assume : f = \u22a5, this.symm \u25b8 mem_bot_sets\u27e9\n\nlemma inhabited_of_mem_sets {f : filter \u03b1} {s : set \u03b1} (hf : f \u2260 \u22a5) (hs : s \u2208 f) :\n  \u2203x, x \u2208 s :=\nhave \u2205 \u2209 f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h,\nhave s \u2260 \u2205, from assume h, this (h \u25b8 hs),\nexists_mem_of_ne_empty this\n\nlemma filter_eq_bot_of_not_nonempty {f : filter \u03b1} (ne : \u00ac nonempty \u03b1) : f = \u22a5 :=\nempty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne \u27e8x\u27e9)\n\nlemma forall_sets_neq_empty_iff_neq_bot {f : filter \u03b1} :\n  (\u2200 (s : set \u03b1), s \u2208 f \u2192 s \u2260 \u2205) \u2194 f \u2260 \u22a5 :=\nby\n  simp only [(@empty_in_sets_eq_bot \u03b1 f).symm, ne.def];\n  exact \u27e8assume h hs, h _ hs rfl, assume h s hs eq, h $ eq \u25b8 hs\u27e9\n\nlemma mem_sets_of_neq_bot {f : filter \u03b1} {s : set \u03b1} (h : f \u2293 principal (-s) = \u22a5) : s \u2208 f :=\nhave \u2205 \u2208 f \u2293 principal (- s), from h.symm \u25b8 mem_bot_sets,\nlet \u27e8s\u2081, hs\u2081, s\u2082, (hs\u2082 : -s \u2286 s\u2082), (hs : s\u2081 \u2229 s\u2082 \u2286 \u2205)\u27e9 := this in\nby filter_upwards [hs\u2081] assume a ha, classical.by_contradiction $ assume ha', hs \u27e8ha, hs\u2082 ha'\u27e9\n\nlemma infi_sets_eq {f : \u03b9 \u2192 filter \u03b1} (h : directed (\u2265) f) (ne : nonempty \u03b9) :\n  (infi f).sets = (\u22c3 i, (f i).sets) :=\nlet \u27e8i\u27e9 := ne, u := { filter .\n    sets             := (\u22c3 i, (f i).sets),\n    univ_sets        := by simp only [mem_Union]; exact \u27e8i, univ_mem_sets\u27e9,\n    sets_of_superset := by simp only [mem_Union, exists_imp_distrib];\n                        intros x y i hx hxy; exact \u27e8i, mem_sets_of_superset hx hxy\u27e9,\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 \u27e8c, ha, hb\u27e9,\n      exact \u27e8c, inter_mem_sets (ha hx) (hb hy)\u27e9\n    end } in\nsubset.antisymm\n  (show u \u2264 infi f, from le_infi $ assume i, le_supr (\u03bbi, (f i).sets) i)\n  (Union_subset $ assume i, infi_le f i)\n\nlemma mem_infi {f : \u03b9 \u2192 filter \u03b1} (h : directed (\u2265) f) (ne : nonempty \u03b9) (s):\n  s \u2208 infi f \u2194 s \u2208 \u22c3 i, (f i).sets :=\nshow  s  \u2208 (infi f).sets \u2194 s \u2208 \u22c3 i, (f i).sets, by rw infi_sets_eq h ne\n\nlemma infi_sets_eq' {f : \u03b2 \u2192 filter \u03b1} {s : set \u03b2}\n  (h : directed_on (f \u207b\u00b9'o (\u2265)) s) (ne : \u2203i, i \u2208 s) :\n  (\u2a05 i\u2208s, f i).sets = (\u22c3 i \u2208 s, (f i).sets) :=\nlet \u27e8i, hi\u27e9 := ne in\ncalc (\u2a05 i \u2208 s, f i).sets  = (\u2a05 t : {t // t \u2208 s}, (f t.val)).sets : by rw [infi_subtype]; refl\n  ... = (\u2a06 t : {t // t \u2208 s}, (f t.val).sets) : infi_sets_eq\n    (assume \u27e8x, hx\u27e9 \u27e8y, hy\u27e9, match h x hx y hy with \u27e8z, h\u2081, h\u2082, h\u2083\u27e9 := \u27e8\u27e8z, h\u2081\u27e9, h\u2082, h\u2083\u27e9 end)\n    \u27e8\u27e8i, hi\u27e9\u27e9\n  ... = (\u2a06 t \u2208 {t | t \u2208 s}, (f t).sets) : by rw [supr_subtype]; refl\n\nlemma infi_sets_eq_finite (f : \u03b9 \u2192 filter \u03b1) :\n  (\u2a05i, f i).sets = (\u22c3t:finset (plift \u03b9), (\u2a05i\u2208t, f (plift.down i)).sets) :=\nbegin\n  rw [infi_eq_infi_finset, infi_sets_eq],\n  exact (directed_of_sup $ \u03bbs\u2081 s\u2082 hs, infi_le_infi $ \u03bbi, infi_le_infi_const $ \u03bbh, hs h),\n  apply_instance\nend\n\nlemma mem_infi_finite {f : \u03b9 \u2192 filter \u03b1} (s):\n  s \u2208 infi f \u2194 s \u2208 \u22c3t:finset (plift \u03b9), (\u2a05i\u2208t, f (plift.down i)).sets :=\nshow  s \u2208 (infi f).sets \u2194 s \u2208 \u22c3t:finset (plift \u03b9), (\u2a05i\u2208t, f (plift.down i)).sets,\nby rw infi_sets_eq_finite\n\n@[simp] lemma sup_join {f\u2081 f\u2082 : filter (filter \u03b1)} : (join f\u2081 \u2294 join f\u2082) = join (f\u2081 \u2294 f\u2082) :=\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 {\u03b9 : Sort w} {f : \u03b9 \u2192 filter (filter \u03b1)} :\n  (\u2a06x, join (f x)) = join (\u2a06x, 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 \u03b1) :=\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\u2081 ht\u2081 t\u2082 ht\u2082 hts,\n    exact \u27e8s \u222a t\u2081,\n      x.sets_of_superset hs $ subset_union_left _ _,\n      y.sets_of_superset ht\u2081 $ subset_union_right _ _,\n      s \u222a t\u2082,\n      x.sets_of_superset hs $ subset_union_left _ _,\n      z.sets_of_superset ht\u2082 $ subset_union_right _ _,\n      subset.trans (@le_sup_inf (set \u03b1) _ _ _ _) (union_subset (subset.refl _) hts)\u27e9\n  end,\n  ..filter.lattice.complete_lattice }\n\n/- the complementary version with \u2a06i, f \u2293 g i does not hold! -/\nlemma infi_sup_eq {f : filter \u03b1} {g : \u03b9 \u2192 filter \u03b1} : (\u2a05 x, f \u2294 g x) = f \u2294 infi g :=\nbegin\n  refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _),\n  rintros t \u27e8h\u2081, h\u2082\u27e9,\n  rw [infi_sets_eq_finite] at h\u2082,\n  simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h\u2082,\n  rcases h\u2082 with \u27e8s, hs\u27e9,\n  suffices : (\u2a05i, f \u2294 g i) \u2264 f \u2294 s.inf (\u03bbi, g i.down), { exact this \u27e8h\u2081, hs\u27e9 },\n  refine finset.induction_on s _ _,\n  { exact le_sup_right_of_le le_top },\n  { rintros \u27e8i\u27e9 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 \u03b1} {f : \u03b1 \u2192 filter \u03b2} :\n  \u2200t, t \u2208 (\u2a05a\u2208s, f a) \u2194 (\u2203p:\u03b1 \u2192 set \u03b2, (\u2200a\u2208s, p a \u2208 f a) \u2227 (\u22c2a\u2208s, p a) \u2286 t) :=\nshow \u2200t, t \u2208 (\u2a05a\u2208s, f a) \u2194 (\u2203p:\u03b1 \u2192 set \u03b2, (\u2200a\u2208s, p a \u2208 f a) \u2227 (\u2a05a\u2208s, p a) \u2264 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\u2081 ht\u2081 t\u2082 p hp ht\u2082 ht,\n      existsi function.update p a t\u2081,\n      have : \u2200a'\u2208s, function.update p a t\u2081 a' = p a',\n        from assume a' ha',\n        have a' \u2260 a, from assume h, has $ h \u25b8 ha',\n        function.update_noteq this,\n      have eq : s.inf (\u03bbj, function.update p a t\u2081 j) = s.inf (\u03bbj, p j) :=\n        finset.inf_congr rfl this,\n      simp only [this, ht\u2081, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt},\n      exact subset.trans (inter_subset_inter (subset.refl _) ht\u2082) ht },\n    assume p hpa hp ht,\n    exact \u27e8p a, hpa, (s.inf p), \u27e8\u27e8p, hp, le_refl _\u27e9, ht\u27e9\u27e9 }\nend\n\n/- principal equations -/\n\n@[simp] lemma inf_principal {s t : set \u03b1} : principal s \u2293 principal t = principal (s \u2229 t) :=\nle_antisymm\n  (by simp; exact \u27e8s, subset.refl s, t, subset.refl t, by simp\u27e9)\n  (by simp [le_inf_iff, inter_subset_left, inter_subset_right])\n\n@[simp] lemma sup_principal {s t : set \u03b1} : principal s \u2294 principal t = principal (s \u222a 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 {\u03b9 : Sort w} {s : \u03b9 \u2192 set \u03b1} : (\u2a06x, principal (s x)) = principal (\u22c3i, s i) :=\nfilter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter];\nexact (@supr_le_iff (set \u03b1) _ _ _ _).symm\n\nlemma principal_univ : principal (univ : set \u03b1) = \u22a4 :=\ntop_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true]\n\nlemma principal_empty : principal (\u2205 : set \u03b1) = \u22a5 :=\nbot_unique $ assume s _, empty_subset _\n\n@[simp] lemma principal_eq_bot_iff {s : set \u03b1} : principal s = \u22a5 \u2194 s = \u2205 :=\n\u27e8assume 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]\u27e9\n\nlemma inf_principal_eq_bot {f : filter \u03b1} {s : set \u03b1} (hs : -s \u2208 f) : f \u2293 principal s = \u22a5 :=\nempty_in_sets_eq_bot.mp \u27e8_, hs, s, mem_principal_self s, assume x \u27e8h\u2081, h\u2082\u27e9, h\u2081 h\u2082\u27e9\n\ntheorem mem_inf_principal (f : filter \u03b1) (s t : set \u03b1) :\n  s \u2208 f \u2293 principal t \u2194 { x | x \u2208 t \u2192 x \u2208 s } \u2208 f :=\nbegin\n  simp only [mem_inf_sets, mem_principal_sets, exists_prop], split,\n  { rintros \u27e8u, ul, v, tsubv, uvinter\u27e9,\n    apply filter.mem_sets_of_superset ul,\n    intros x xu xt, exact uvinter \u27e8xu, tsubv xt\u27e9 },\n  intro h, refine \u27e8_, h, t, set.subset.refl t, _\u27e9,\n  rintros x \u27e8hx, xt\u27e9,\n  exact hx xt\nend\n\nend lattice\n\nsection map\n\n/-- The forward map of a filter -/\ndef map (m : \u03b1 \u2192 \u03b2) (f : filter \u03b1) : filter \u03b2 :=\n{ sets             := preimage m \u207b\u00b9' 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 \u03b1} {f : \u03b1 \u2192 \u03b2} :\n  map f (principal s) = principal (set.image f s) :=\nfilter_eq $ set.ext $ assume a, image_subset_iff.symm\n\nvariables {f : filter \u03b1} {m : \u03b1 \u2192 \u03b2} {m' : \u03b2 \u2192 \u03b3} {s : set \u03b1} {t : set \u03b2}\n\n@[simp] lemma mem_map : t \u2208 map m f \u2194 {x | m x \u2208 t} \u2208 f := iff.rfl\n\nlemma image_mem_map (hs : s \u2208 f) : m '' s \u2208 map m f :=\nf.sets_of_superset hs $ subset_preimage_image m s\n\nlemma range_mem_map : range m \u2208 map m f :=\nby rw \u2190image_univ; exact image_mem_map univ_mem_sets\n\nlemma mem_map_sets_iff : t \u2208 map m f \u2194 (\u2203s\u2208f, m '' s \u2286 t) :=\niff.intro\n  (assume ht, \u27e8set.preimage m t, ht, image_preimage_subset _ _\u27e9)\n  (assume \u27e8s, hs, ht\u27e9, 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' \u2218 filter.map m = filter.map (m' \u2218 m) :=\nfunext $ assume _, filter_eq $ rfl\n\n@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' \u2218 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 : \u03b1 \u2192 \u03b2) (f : filter \u03b2) : filter \u03b1 :=\n{ sets             := { s | \u2203t\u2208 f, m \u207b\u00b9' t \u2286 s },\n  univ_sets        := \u27e8univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]\u27e9,\n  sets_of_superset := assume a b \u27e8a', ha', ma'a\u27e9 ab,\n    \u27e8a', ha', subset.trans ma'a ab\u27e9,\n  inter_sets       := assume a b \u27e8a', ha\u2081, ha\u2082\u27e9 \u27e8b', hb\u2081, hb\u2082\u27e9,\n    \u27e8a' \u2229 b', inter_mem_sets ha\u2081 hb\u2081, inter_subset_inter ha\u2082 hb\u2082\u27e9 }\n\nend comap\n\n/-- The cofinite filter is the filter of subsets whose complements are finite. -/\ndef cofinite : filter \u03b1 :=\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 \u2286 t),\n    finite_subset hs $ @lattice.neg_le_neg (set \u03b1) _ _ _ 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 \u03b1)) : @cofinite \u03b1 \u2260 \u22a5 :=\nforall_sets_neq_empty_iff_neq_bot.mp \n  $ \u03bb 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 \u03b1) (m : \u03b1 \u2192 filter \u03b2) : filter \u03b2 := join (map m f)\n\n/-- The applicative sequentiation operation. This is not induced by the bind operation. -/\ndef seq (f : filter (\u03b1 \u2192 \u03b2)) (g : filter \u03b1) : filter \u03b2 :=\n\u27e8{ s | \u2203u\u2208 f, \u2203t\u2208 g, (\u2200m\u2208u, \u2200x\u2208t, (m : \u03b1 \u2192 \u03b2) x \u2208 s) },\n  \u27e8univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]\u27e9,\n  assume s\u2080 s\u2081 \u27e8t\u2080, t\u2081, h\u2080, h\u2081, h\u27e9 hst, \u27e8t\u2080, t\u2081, h\u2080, h\u2081, assume x hx y hy, hst $ h _ hx _ hy\u27e9,\n  assume s\u2080 s\u2081 \u27e8t\u2080, ht\u2080, t\u2081, ht\u2081, ht\u27e9 \u27e8u\u2080, hu\u2080, u\u2081, hu\u2081, hu\u27e9,\n    \u27e8t\u2080 \u2229 u\u2080, inter_mem_sets ht\u2080 hu\u2080, t\u2081 \u2229 u\u2081, inter_mem_sets ht\u2081 hu\u2081,\n      assume x \u27e8hx\u2080, hx\u2081\u27e9 x \u27e8hy\u2080, hy\u2081\u27e9, \u27e8ht _ hx\u2080 _ hy\u2080, hu _ hx\u2081 _ hy\u2081\u27e9\u27e9\u27e9\n\ninstance : has_pure filter := \u27e8\u03bb(\u03b1 : Type u) x, principal {x}\u27e9\n\ninstance : has_bind filter := \u27e8@filter.bind\u27e9\n\ninstance : has_seq filter := \u27e8@filter.seq\u27e9\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 \u03b1 f, filter_eq rfl,\n  pure_bind  := assume \u03b1 \u03b2 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 \u03b1 \u03b2 \u03b3 f m\u2081 m\u2082, filter_eq rfl,\n  bind_pure_comp_eq_map := assume \u03b1 \u03b2 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 := \u03bb\u03b1, \u22a5,\n  orelse  := \u03bb\u03b1 x y, x \u2294 y }\n\n@[simp] lemma pure_def (x : \u03b1) : pure x = principal {x} := rfl\n\n@[simp] lemma mem_pure {a : \u03b1} {s : set \u03b1} : a \u2208 s \u2192 s \u2208 (pure a : filter \u03b1) :=\nby simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id\n\n@[simp] lemma mem_pure_iff {a : \u03b1} {s : set \u03b1} : s \u2208 (pure a : filter \u03b1) \u2194 a \u2208 s :=\nby rw [pure_def, mem_principal_sets, set.singleton_subset_iff]\n\n@[simp] lemma map_def {\u03b1 \u03b2} (m : \u03b1 \u2192 \u03b2) (f : filter \u03b1) : m <$> f = map m f := rfl\n\n@[simp] lemma bind_def {\u03b1 \u03b2} (f : filter \u03b1) (m : \u03b1 \u2192 filter \u03b2) : f >>= m = bind f m := rfl\n\n/- map and comap equations -/\nsection map\nvariables {f f\u2081 f\u2082 : filter \u03b1} {g g\u2081 g\u2082 : filter \u03b2} {m : \u03b1 \u2192 \u03b2} {m' : \u03b2 \u2192 \u03b3} {s : set \u03b1} {t : set \u03b2}\n\n@[simp] theorem mem_comap_sets : s \u2208 comap m g \u2194 \u2203t\u2208 g, m \u207b\u00b9' t \u2286 s := iff.rfl\n\ntheorem preimage_mem_comap (ht : t \u2208 g) : m \u207b\u00b9' t \u2208 comap m g :=\n\u27e8t, ht, subset.refl _\u27e9\n\nlemma comap_id : comap id f = f :=\nle_antisymm (assume s, preimage_mem_comap) (assume s \u27e8t, ht, hst\u27e9, mem_sets_of_superset ht hst)\n\nlemma comap_comap_comp {m : \u03b3 \u2192 \u03b2} {n : \u03b2 \u2192 \u03b1} : comap m (comap n f) = comap (n \u2218 m) f :=\nle_antisymm\n  (assume c \u27e8b, hb, (h : preimage (n \u2218 m) b \u2286 c)\u27e9, \u27e8preimage n b, preimage_mem_comap hb, h\u27e9)\n  (assume c \u27e8b, \u27e8a, ha, (h\u2081 : preimage n a \u2286 b)\u27e9, (h\u2082 : preimage m b \u2286 c)\u27e9,\n    \u27e8a, ha, show preimage m (preimage n a) \u2286 c, from subset.trans (preimage_mono h\u2081) h\u2082\u27e9)\n\n@[simp] theorem comap_principal {t : set \u03b2} : comap m (principal t) = principal (m \u207b\u00b9' t) :=\nfilter_eq $ set.ext $ assume s,\n  \u27e8assume \u27e8u, (hu : t \u2286 u), (b : preimage m u \u2286 s)\u27e9, subset.trans (preimage_mono hu) b,\n    assume : preimage m t \u2286 s, \u27e8t, subset.refl t, this\u27e9\u27e9\n\nlemma map_le_iff_le_comap : map m f \u2264 g \u2194 f \u2264 comap m g :=\n\u27e8assume h s \u27e8t, ht, hts\u27e9, mem_sets_of_superset (h ht) hts, assume h s ht, h \u27e8_, ht, subset.refl _\u27e9\u27e9\n\nlemma gc_map_comap (m : \u03b1 \u2192 \u03b2) : galois_connection (map m) (comap m) :=\nassume f g, map_le_iff_le_comap\n\nlemma map_mono (h : f\u2081 \u2264 f\u2082) : map m f\u2081 \u2264 map m f\u2082 := (gc_map_comap m).monotone_l h\nlemma monotone_map : monotone (map m) | a b := map_mono\nlemma comap_mono (h : g\u2081 \u2264 g\u2082) : comap m g\u2081 \u2264 comap m g\u2082 := (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 \u22a5 = \u22a5 := (gc_map_comap m).l_bot\n@[simp] lemma map_sup : map m (f\u2081 \u2294 f\u2082) = map m f\u2081 \u2294 map m f\u2082 := (gc_map_comap m).l_sup\n@[simp] lemma map_supr {f : \u03b9 \u2192 filter \u03b1} : map m (\u2a06i, f i) = (\u2a06i, map m (f i)) :=\n(gc_map_comap m).l_supr\n\n@[simp] lemma comap_top : comap m \u22a4 = \u22a4 := (gc_map_comap m).u_top\n@[simp] lemma comap_inf : comap m (g\u2081 \u2293 g\u2082) = comap m g\u2081 \u2293 comap m g\u2082 := (gc_map_comap m).u_inf\n@[simp] lemma comap_infi {f : \u03b9 \u2192 filter \u03b2} : comap m (\u2a05i, f i) = (\u2a05i, comap m (f i)) :=\n(gc_map_comap m).u_infi\n\nlemma le_comap_top (f : \u03b1 \u2192 \u03b2) (l : filter \u03b1) : l \u2264 comap f \u22a4 :=\nby rw [comap_top]; exact le_top\n\nlemma map_comap_le : map m (comap m g) \u2264 g := (gc_map_comap m).l_u_le _\nlemma le_comap_map : f \u2264 comap m (map m f) := (gc_map_comap m).le_u_l _\n\n@[simp] lemma comap_bot : comap m \u22a5 = \u22a5 :=\nbot_unique $ assume s _, \u27e8\u2205, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]\u27e9\n\nlemma comap_supr {\u03b9} {f : \u03b9 \u2192 filter \u03b2} {m : \u03b1 \u2192 \u03b2} :\n  comap m (supr f) = (\u2a06i, comap m (f i)) :=\nle_antisymm\n  (assume s hs,\n    have \u2200i, \u2203t, t \u2208 f i \u2227 m \u207b\u00b9' t \u2286 s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs,\n    let \u27e8t, ht\u27e9 := classical.axiom_of_choice this in\n    \u27e8\u22c3i, 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\u27e9)\n  (supr_le $ assume i, monotone_comap $ le_supr _ _)\n\nlemma comap_Sup {s : set (filter \u03b2)} {m : \u03b1 \u2192 \u03b2} : comap m (Sup s) = (\u2a06f\u2208s, comap m f) :=\nby simp only [Sup_eq_supr, comap_supr, eq_self_iff_true]\n\nlemma comap_sup : comap m (g\u2081 \u2294 g\u2082) = comap m g\u2081 \u2294 comap m g\u2082 :=\nle_antisymm\n  (assume s \u27e8\u27e8t\u2081, ht\u2081, hs\u2081\u27e9, \u27e8t\u2082, ht\u2082, hs\u2082\u27e9\u27e9,\n    \u27e8t\u2081 \u222a t\u2082,\n      \u27e8g\u2081.sets_of_superset ht\u2081 (subset_union_left _ _), g\u2082.sets_of_superset ht\u2082 (subset_union_right _ _)\u27e9,\n      union_subset hs\u2081 hs\u2082\u27e9)\n  (sup_le (comap_mono le_sup_left) (comap_mono le_sup_right))\n\nlemma map_comap {f : filter \u03b2} {m : \u03b1 \u2192 \u03b2} (hf : range m \u2208 f) : (f.comap m).map m = f :=\nle_antisymm\n  map_comap_le\n  (assume t' \u27e8t, ht, sub\u27e9, by filter_upwards [ht, hf]; rintros x hxt \u27e8y, rfl\u27e9; exact sub hxt)\n\nlemma comap_map {f : filter \u03b1} {m : \u03b1 \u2192 \u03b2} (h : \u2200 x y, m x = m y \u2192 x = y) :\n  comap m (map m f) = f :=\nhave \u2200s, preimage m (image m s) = s,\n  from assume s, preimage_image_eq s h,\nle_antisymm\n  (assume s hs, \u27e8\n    image m s,\n    f.sets_of_superset hs $ by simp only [this, subset.refl],\n    by simp only [this, subset.refl]\u27e9)\n  le_comap_map\n\nlemma le_of_map_le_map_inj' {f g : filter \u03b1} {m : \u03b1 \u2192 \u03b2} {s : set \u03b1}\n  (hsf : s \u2208 f) (hsg : s \u2208 g) (hm : \u2200x\u2208s, \u2200y\u2208s, m x = m y \u2192 x = y)\n  (h : map m f \u2264 map m g) : f \u2264 g :=\nassume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)]\nassume a has \u27e8b, \u27e8hbs, hb\u27e9, h\u27e9,\nhave b = a, from hm _ hbs _ has h,\nthis \u25b8 hb\n\nlemma le_of_map_le_map_inj_iff {f g : filter \u03b1} {m : \u03b1 \u2192 \u03b2} {s : set \u03b1}\n  (hsf : s \u2208 f) (hsg : s \u2208 g) (hm : \u2200x\u2208s, \u2200y\u2208s, m x = m y \u2192 x = y) :\n  map m f \u2264 map m g \u2194 f \u2264 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 \u03b1} {m : \u03b1 \u2192 \u03b2} {s : set \u03b1}\n  (hsf : s \u2208 f) (hsg : s \u2208 g) (hm : \u2200x\u2208s, \u2200y\u2208s, m x = m y \u2192 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 \u03b1} {m : \u03b1 \u2192 \u03b2} (hm : \u2200 x y, m x = m y \u2192 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 : \u03b1 \u2192 \u03b2} {l : filter \u03b2} {u : set \u03b2} (ul : u \u2208 l)\n    (hf : \u2200 y \u2208 u, \u2203 x, f x = y) :\n  l \u2264 map f (comap f l) :=\nassume s \u27e8t, tl, ht\u27e9,\nhave t \u2229 u \u2286 s, from\n  assume x \u27e8xt, xu\u27e9,\n  exists.elim (hf x xu) $ \u03bb a faeq,\n  by { rw \u2190faeq, apply ht, change f a \u2208 t, rw faeq, exact xt },\nmem_sets_of_superset (inter_mem_sets tl ul) this\n\ntheorem map_comap_of_surjective' {f : \u03b1 \u2192 \u03b2} {l : filter \u03b2} {u : set \u03b2} (ul : u \u2208 l)\n    (hf : \u2200 y \u2208 u, \u2203 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 : \u03b1 \u2192 \u03b2} (hf : function.surjective f) (l : filter \u03b2) :\n  l \u2264 map f (comap f l) :=\nle_map_comap_of_surjective' univ_mem_sets (\u03bb y _, hf y)\n\ntheorem map_comap_of_surjective {f : \u03b1 \u2192 \u03b2} (hf : function.surjective f) (l : filter \u03b2) :\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 \u03b2} {m : \u03b1 \u2192 \u03b2}\n  (hm : \u2200t\u2208 f, \u2203a, m a \u2208 t) : comap m f \u2260 \u22a5 :=\nforall_sets_neq_empty_iff_neq_bot.mp $ assume s \u27e8t, ht, t_s\u27e9,\n  let \u27e8a, (ha : a \u2208 preimage m t)\u27e9 := 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 \u03b2} {m : \u03b1 \u2192 \u03b2}\n  (hf : f \u2260 \u22a5) (hm : \u2200b, \u2203a, m a = b) : comap m f \u2260 \u22a5 :=\ncomap_neq_bot $ assume t ht,\n  let\n    \u27e8b, (hx : b \u2208 t)\u27e9 := inhabited_of_mem_sets hf ht,\n    \u27e8a, (ha : m a = b)\u27e9 := hm b\n  in \u27e8a, ha.symm \u25b8 hx\u27e9\n\n@[simp] lemma map_eq_bot_iff : map m f = \u22a5 \u2194 f = \u22a5 :=\n\u27e8by rw [\u2190empty_in_sets_eq_bot, \u2190empty_in_sets_eq_bot]; exact id,\n  assume h, by simp only [h, eq_self_iff_true, map_bot]\u27e9\n\nlemma map_ne_bot (hf : f \u2260 \u22a5) : map m f \u2260 \u22a5 :=\nassume h, hf $ by rwa [map_eq_bot_iff] at h\n\nlemma sInter_comap_sets (f : \u03b1 \u2192 \u03b2) (F : filter \u03b2) :\n  \u22c2\u2080(comap f F).sets = \u22c2 U \u2208 F, f \u207b\u00b9' U :=\nbegin\n  ext x,\n  suffices : (\u2200 (A : set \u03b1) (B : set \u03b2), B \u2208 F \u2192 f \u207b\u00b9' B \u2286 A \u2192 x \u2208 A) \u2194\n    \u2200 (B : set \u03b2), B \u2208 F \u2192 f x \u2208 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 \u207b\u00b9' 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\u2081 m\u2082 : \u03b1 \u2192 \u03b2} {f : filter \u03b1} (h : {x | m\u2081 x = m\u2082 x} \u2208 f) :\n  map m\u2081 f = map m\u2082 f :=\nhave \u2200(m\u2081 m\u2082 : \u03b1 \u2192 \u03b2) (h : {x | m\u2081 x = m\u2082 x} \u2208 f), map m\u2081 f \u2264 map m\u2082 f,\nbegin\n  intros  m\u2081 m\u2082 h s hs,\n  show {x | m\u2081 x \u2208 s} \u2208 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\u2081 m\u2082 h) (this m\u2082 m\u2081 $ mem_sets_of_superset h $ assume x, eq.symm)\n\n-- this is a generic rule for monotone functions:\nlemma map_infi_le {f : \u03b9 \u2192 filter \u03b1} {m : \u03b1 \u2192 \u03b2} :\n  map m (infi f) \u2264 (\u2a05 i, map m (f i)) :=\nle_infi $ assume i, map_mono $ infi_le _ _\n\nlemma map_infi_eq {f : \u03b9 \u2192 filter \u03b1} {m : \u03b1 \u2192 \u03b2} (hf : directed (\u2265) f) (h\u03b9 : nonempty \u03b9) :\n  map m (infi f) = (\u2a05 i, map m (f i)) :=\nle_antisymm\n  map_infi_le\n  (assume s (hs : preimage m s \u2208 infi f),\n    have \u2203i, preimage m s \u2208 f i,\n      by simp only [infi_sets_eq hf h\u03b9, mem_Union] at hs; assumption,\n    let \u27e8i, hi\u27e9 := this in\n    have (\u2a05 i, map m (f i)) \u2264 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 {\u03b9 : Type w} {f : \u03b9 \u2192 filter \u03b1} {m : \u03b1 \u2192 \u03b2} {p : \u03b9 \u2192 Prop}\n  (h : directed_on (f \u207b\u00b9'o (\u2265)) {x | p x}) (ne : \u2203i, p i) :\n  map m (\u2a05i (h : p i), f i) = (\u2a05i (h: p i), map m (f i)) :=\nlet \u27e8i, hi\u27e9 := ne in\ncalc map m (\u2a05i (h : p i), f i) = map m (\u2a05i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true]\n  ... = (\u2a05i:subtype p, map m (f i.val)) : map_infi_eq\n    (assume \u27e8x, hx\u27e9 \u27e8y, hy\u27e9, match h x hx y hy with \u27e8z, h\u2081, h\u2082, h\u2083\u27e9 := \u27e8\u27e8z, h\u2081\u27e9, h\u2082, h\u2083\u27e9 end)\n    \u27e8\u27e8i, hi\u27e9\u27e9\n  ... = (\u2a05i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true]\n\nlemma map_inf' {f g : filter \u03b1} {m : \u03b1 \u2192 \u03b2} {t : set \u03b1} (htf : t \u2208 f) (htg : t \u2208 g)\n  (h : \u2200x\u2208t, \u2200y\u2208t, m x = m y \u2192 x = y) : map m (f \u2293 g) = map m f \u2293 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 \u22a2,\n  rcases hs with \u27e8t\u2081, h\u2081, t\u2082, h\u2082, hs\u27e9,\n  refine \u27e8m '' (t\u2081 \u2229 t), _, m '' (t\u2082 \u2229 t), _, _\u27e9,\n  { filter_upwards [h\u2081, htf] assume a h\u2081 h\u2082, mem_image_of_mem _ \u27e8h\u2081, h\u2082\u27e9 },\n  { filter_upwards [h\u2082, htg] assume a h\u2081 h\u2082, mem_image_of_mem _ \u27e8h\u2081, h\u2082\u27e9 },\n  { rw [image_inter_on],\n    { refine image_subset_iff.2 _,\n      exact \u03bb x \u27e8\u27e8h\u2081, _\u27e9, h\u2082, _\u27e9, hs \u27e8h\u2081, h\u2082\u27e9 },\n    { exact \u03bb x \u27e8_, hx\u27e9 y \u27e8_, hy\u27e9, h x hx y hy } }\nend\n\nlemma map_inf {f g : filter \u03b1} {m : \u03b1 \u2192 \u03b2} (h : \u2200 x y, m x = m y \u2192 x = y) :\n  map m (f \u2293 g) = map m f \u2293 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 \u03b1} {m : \u03b1 \u2192 \u03b2} {n : \u03b2 \u2192 \u03b1}\n  (h\u2081 : m \u2218 n = id) (h\u2082 : n \u2218 m = id) : map m f = comap n f :=\nle_antisymm\n  (assume b \u27e8a, ha, (h : preimage n a \u2286 b)\u27e9, f.sets_of_superset ha $\n    calc a = preimage (n \u2218 m) a : by simp only [h\u2082, preimage_id, eq_self_iff_true]\n      ... \u2286 preimage m b : preimage_mono h)\n  (assume b (hb : preimage m b \u2208 f),\n    \u27e8preimage m b, hb, show preimage (m \u2218 n) b \u2286 b, by simp only [h\u2081]; apply subset.refl\u27e9)\n\nlemma map_swap_eq_comap_swap {f : filter (\u03b1 \u00d7 \u03b2)} : 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 \u03b1} {m : \u03b1 \u2192 \u03b2} {g : filter \u03b2} (h : \u2200s\u2208 f, m '' s \u2208 g) :\n  g \u2264 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 : \u03b1} {s : set \u03b1} :\n  s \u2208 (pure a : filter \u03b1) \u2194 a \u2208 s :=\nby simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff]\n\nlemma singleton_mem_pure_sets {a : \u03b1} : {a} \u2208 (pure a : filter \u03b1) :=\nby simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]\n\n@[simp] lemma pure_neq_bot {\u03b1 : Type u} {a : \u03b1} : pure a \u2260 (\u22a5 : filter \u03b1) :=\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 (\u03b1 \u2192 \u03b2)} {g : filter \u03b1} {s : set \u03b2} :\n  s \u2208 f.seq g \u2194 (\u2203u \u2208 f, \u2203t \u2208 g, \u2200x\u2208u, \u2200y\u2208t, (x : \u03b1 \u2192 \u03b2) y \u2208 s) :=\niff.refl _\n\nlemma mem_seq_sets_iff {f : filter (\u03b1 \u2192 \u03b2)} {g : filter \u03b1} {s : set \u03b2} :\n  s \u2208 f.seq g \u2194 (\u2203u \u2208 f, \u2203t \u2208 g, set.seq u t \u2286 s) :=\nby simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self]\n\nlemma mem_map_seq_iff {f : filter \u03b1} {g : filter \u03b2} {m : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {s : set \u03b3} :\n  s \u2208 (f.map m).seq g \u2194 (\u2203t u, t \u2208 g \u2227 u \u2208 f \u2227 \u2200x\u2208u, \u2200y\u2208t, m x y \u2208 s) :=\niff.intro\n  (assume \u27e8t, ht, s, hs, hts\u27e9, \u27e8s, m \u207b\u00b9' t, hs, ht, assume a, hts _\u27e9)\n  (assume \u27e8t, s, ht, hs, hts\u27e9, \u27e8m '' s, image_mem_map hs, t, ht, assume f \u27e8a, has, eq\u27e9, eq \u25b8 hts _ has\u27e9)\n\nlemma seq_mem_seq_sets {f : filter (\u03b1 \u2192 \u03b2)} {g : filter \u03b1} {s : set (\u03b1 \u2192 \u03b2)} {t : set \u03b1}\n  (hs : s \u2208 f) (ht : t \u2208 g): s.seq t \u2208 f.seq g :=\n\u27e8s, hs, t, ht, assume f hf a ha, \u27e8f, hf, a, ha, rfl\u27e9\u27e9\n\nlemma le_seq {f : filter (\u03b1 \u2192 \u03b2)} {g : filter \u03b1} {h : filter \u03b2}\n  (hh : \u2200t \u2208 f, \u2200u \u2208 g, set.seq t u \u2208 h) : h \u2264 seq f g :=\nassume s \u27e8t, ht, u, hu, hs\u27e9, mem_sets_of_superset (hh _ ht _ hu) $\n  assume b \u27e8m, hm, a, ha, eq\u27e9, eq \u25b8 hs _ hm _ ha\n\nlemma seq_mono {f\u2081 f\u2082 : filter (\u03b1 \u2192 \u03b2)} {g\u2081 g\u2082 : filter \u03b1}\n  (hf : f\u2081 \u2264 f\u2082) (hg : g\u2081 \u2264 g\u2082) : f\u2081.seq g\u2081 \u2264 f\u2082.seq g\u2082 :=\nle_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht)\n\n@[simp] lemma pure_seq_eq_map (g : \u03b1 \u2192 \u03b2) (f : filter \u03b1) : 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 \u2190 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 \u27e8a, ha, rfl\u27e9, exact \u27e8g, hs, a, ha, rfl\u27e9 }\nend\n\n@[simp] lemma map_pure (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : 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, \u27e8a, has, rfl\u27e9\n  end)\n\n@[simp] lemma seq_pure (f : filter (\u03b1 \u2192 \u03b2)) (a : \u03b1) : seq f (pure a) = map (\u03bbg:\u03b1 \u2192 \u03b2, g a) f :=\nbegin\n  refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),\n  { rw \u2190 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 (\u03bbg:\u03b1\u2192\u03b2, g a) f) (image_mem_map hs) _,\n    rintros b \u27e8g, hg, rfl\u27e9, exact \u27e8g, hg, a, ht, rfl\u27e9 }\nend\n\n@[simp] lemma seq_assoc (x : filter \u03b1) (g : filter (\u03b1 \u2192 \u03b2)) (h : filter (\u03b2 \u2192 \u03b3)) :\n  seq h (seq g x) = seq (seq (map (\u2218) 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 \u27e8u, hu, v, hv, hs\u27e9,\n    rcases mem_map_sets_iff.1 hu with \u27e8w, hw, hu\u27e9,\n    refine mem_sets_of_superset _\n      (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)),\n    rw \u2190 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 \u27e8u, hu, v, hv, ht\u27e9,\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 \u03b1) (g : filter \u03b2) :\n  (map prod.mk f).seq g = seq (map (\u03bbb 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 \u27e8u, hu, hs\u27e9,\n    refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),\n    rw \u2190 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 \u27e8u, hu, hs\u27e9,\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 \u2192 Type u) :=\n{ id_map   := assume \u03b1 f, map_id,\n  comp_map := assume \u03b1 \u03b2 \u03b3 f g a, map_map.symm }\n\ninstance : is_lawful_applicative (filter : Type u \u2192 Type u) :=\n{ pure_seq_eq_map := assume \u03b1 \u03b2, pure_seq_eq_map,\n  map_pure        := assume \u03b1 \u03b2, map_pure,\n  seq_pure        := assume \u03b1 \u03b2, seq_pure,\n  seq_assoc       := assume \u03b1 \u03b2 \u03b3, seq_assoc }\n\ninstance : is_comm_applicative (filter : Type u \u2192 Type u) :=\n\u27e8assume \u03b1 \u03b2 f g, prod_map_seq_comm f g\u27e9\n\nlemma {l} seq_eq_filter_seq {\u03b1 \u03b2 : Type l} (f : filter (\u03b1 \u2192 \u03b2)) (g : filter \u03b1) :\n  f <*> g = seq f g := rfl\n\nend applicative\n\n/- bind equations -/\nsection bind\n@[simp] lemma mem_bind_sets {s : set \u03b2} {f : filter \u03b1} {m : \u03b1 \u2192 filter \u03b2} :\n  s \u2208 bind f m \u2194 \u2203t \u2208 f, \u2200x \u2208 t, s \u2208 m x :=\ncalc s \u2208 bind f m \u2194 {a | s \u2208 m a} \u2208 f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq]\n                     ... \u2194 (\u2203t \u2208 f, t \u2286 {a | s \u2208 m a}) : exists_sets_subset_iff.symm\n                     ... \u2194 (\u2203t \u2208 f, \u2200x \u2208 t, s \u2208 m x) : iff.refl _\n\nlemma bind_mono {f : filter \u03b1} {g h : \u03b1 \u2192 filter \u03b2} (h\u2081 : {a | g a \u2264 h a} \u2208 f) :\n  bind f g \u2264 bind f h :=\nassume x h\u2082, show (_ \u2208 f), by filter_upwards [h\u2081, h\u2082] assume s gh' h', gh' h'\n\nlemma bind_sup {f g : filter \u03b1} {h : \u03b1 \u2192 filter \u03b2} :\n  bind (f \u2294 g) h = bind f h \u2294 bind g h :=\nby simp only [bind, sup_join, map_sup, eq_self_iff_true]\n\nlemma bind_mono2 {f g : filter \u03b1} {h : \u03b1 \u2192 filter \u03b2} (h\u2081 : f \u2264 g) :\n  bind f h \u2264 bind g h :=\nassume s h', h\u2081 h'\n\nlemma principal_bind {s : set \u03b1} {f : \u03b1 \u2192 filter \u03b2} :\n  (bind (principal s) f) = (\u2a06x \u2208 s, f x) :=\nshow join (map f (principal s)) = (\u2a06x \u2208 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 : \u03b9 \u2192 filter \u03b1}\n  (hn : nonempty \u03b1) (hd : directed (\u2265) f) (hb : \u2200i, f i \u2260 \u22a5) : (infi f) \u2260 \u22a5 :=\nlet \u27e8x\u27e9 := hn in\nassume h, have he: \u2205  \u2208 (infi f), from h.symm \u25b8 (mem_bot_sets : \u2205 \u2208 (\u22a5 : filter \u03b1)),\nclassical.by_cases\n  (assume : nonempty \u03b9,\n    have \u2203i, \u2205 \u2208 f i,\n      by rw [mem_infi hd this] at he; simp only [mem_Union] at he; assumption,\n    let \u27e8i, hi\u27e9 := this in\n    hb i $ bot_unique $\n    assume s _, (f i).sets_of_superset hi $ empty_subset _)\n  (assume : \u00ac nonempty \u03b9,\n    have univ \u2286 (\u2205 : set \u03b1),\n    begin\n      rw [\u2190principal_mono, principal_univ, principal_empty, \u2190h],\n      exact (le_infi $ assume i, false.elim $ this \u27e8i\u27e9)\n    end,\n    this $ mem_univ x)\n\nlemma infi_neq_bot_iff_of_directed {f : \u03b9 \u2192 filter \u03b1}\n  (hn : nonempty \u03b1) (hd : directed (\u2265) f) : (infi f) \u2260 \u22a5 \u2194 (\u2200i, f i \u2260 \u22a5) :=\n\u27e8assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot \u25b8 le_refl _,\n  infi_neq_bot_of_directed hn hd\u27e9\n\nlemma mem_infi_sets {f : \u03b9 \u2192 filter \u03b1} (i : \u03b9) : \u2200{s}, s \u2208 f i \u2192 s \u2208 \u2a05i, f i :=\nshow (\u2a05i, f i) \u2264 f i, from infi_le _ _\n\n@[elab_as_eliminator]\nlemma infi_sets_induct {f : \u03b9 \u2192 filter \u03b1} {s : set \u03b1} (hs : s \u2208 infi f) {p : set \u03b1 \u2192 Prop}\n  (uni : p univ)\n  (ins : \u2200{i s\u2081 s\u2082}, s\u2081 \u2208 f i \u2192 p s\u2082 \u2192 p (s\u2081 \u2229 s\u2082))\n  (upw : \u2200{s\u2081 s\u2082}, s\u2081 \u2286 s\u2082 \u2192 p s\u2081 \u2192 p s\u2082) : 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 \u27e8is, his\u27e9,\n  revert s,\n  refine finset.induction_on is _ _,\n  { assume s hs, rwa [mem_top_sets.1 hs] },\n  { rintros \u27e8i\u27e9 js his ih s hs,\n    rw [finset.inf_insert, mem_inf_sets] at hs,\n    rcases hs with \u27e8s\u2081, hs\u2081, s\u2082, hs\u2082, hs\u27e9,\n    exact upw hs (ins hs\u2081 (ih hs\u2082)) }\nend\n\n/- tendsto -/\n\n/-- `tendsto` is the generic \"limit of a function\" predicate.\n  `tendsto f l\u2081 l\u2082` asserts that for every `l\u2082` neighborhood `a`,\n  the `f`-preimage of `a` is an `l\u2081` neighborhood. -/\ndef tendsto (f : \u03b1 \u2192 \u03b2) (l\u2081 : filter \u03b1) (l\u2082 : filter \u03b2) := l\u2081.map f \u2264 l\u2082\n\nlemma tendsto_def {f : \u03b1 \u2192 \u03b2} {l\u2081 : filter \u03b1} {l\u2082 : filter \u03b2} :\n  tendsto f l\u2081 l\u2082 \u2194 \u2200 s \u2208 l\u2082, f \u207b\u00b9' s \u2208 l\u2081 := iff.rfl\n\nlemma tendsto_iff_comap {f : \u03b1 \u2192 \u03b2} {l\u2081 : filter \u03b1} {l\u2082 : filter \u03b2} :\n  tendsto f l\u2081 l\u2082 \u2194 l\u2081 \u2264 l\u2082.comap f :=\nmap_le_iff_le_comap\n\nlemma tendsto.congr' {f\u2081 f\u2082 : \u03b1 \u2192 \u03b2} {l\u2081 : filter \u03b1} {l\u2082 : filter \u03b2}\n  (hl : {x | f\u2081 x = f\u2082 x} \u2208 l\u2081) (h : tendsto f\u2081 l\u2081 l\u2082) : tendsto f\u2082 l\u2081 l\u2082 :=\nby rwa [tendsto, \u2190map_cong hl]\n\ntheorem tendsto.congr'r {f\u2081 f\u2082 : \u03b1 \u2192 \u03b2} {l\u2081 : filter \u03b1} {l\u2082 : filter \u03b2}\n  (h : \u2200 x, f\u2081 x = f\u2082 x) : tendsto f\u2081 l\u2081 l\u2082 \u2194 tendsto f\u2082 l\u2081 l\u2082 :=\niff_of_eq (by congr'; exact funext h)\n\ntheorem tendsto.congr {f\u2081 f\u2082 : \u03b1 \u2192 \u03b2} {l\u2081 : filter \u03b1} {l\u2082 : filter \u03b2}\n  (h : \u2200 x, f\u2081 x = f\u2082 x) : tendsto f\u2081 l\u2081 l\u2082 \u2192 tendsto f\u2082 l\u2081 l\u2082 :=\n(tendsto.congr'r h).1\n\nlemma tendsto_id' {x y : filter \u03b1} : x \u2264 y \u2192 tendsto id x y :=\nby simp only [tendsto, map_id, forall_true_iff] {contextual := tt}\n\nlemma tendsto_id {x : filter \u03b1} : tendsto id x x := tendsto_id' $ le_refl x\n\nlemma tendsto.comp {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b3} {x : filter \u03b1} {y : filter \u03b2} {z : filter \u03b3}\n  (hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g \u2218 f) x z :=\ncalc map (g \u2218 f) x = map g (map f x) : by rw [map_map]\n  ... \u2264 map g y : map_mono hf\n  ... \u2264 z : hg\n\nlemma tendsto_le_left {f : \u03b1 \u2192 \u03b2} {x y : filter \u03b1} {z : filter \u03b2}\n  (h : y \u2264 x) : tendsto f x z \u2192 tendsto f y z :=\nle_trans (map_mono h)\n\nlemma tendsto_le_right {f : \u03b1 \u2192 \u03b2} {x : filter \u03b1} {y z : filter \u03b2}\n  (h\u2081 : y \u2264 z) (h\u2082 : tendsto f x y) : tendsto f x z :=\nle_trans h\u2082 h\u2081\n\nlemma tendsto_map {f : \u03b1 \u2192 \u03b2} {x : filter \u03b1} : tendsto f x (map f x) := le_refl (map f x)\n\nlemma tendsto_map' {f : \u03b2 \u2192 \u03b3} {g : \u03b1 \u2192 \u03b2} {x : filter \u03b1} {y : filter \u03b3}\n  (h : tendsto (f \u2218 g) x y) : tendsto f (map g x) y :=\nby rwa [tendsto, map_map]\n\nlemma tendsto_map'_iff {f : \u03b2 \u2192 \u03b3} {g : \u03b1 \u2192 \u03b2} {x : filter \u03b1} {y : filter \u03b3} :\n  tendsto f (map g x) y \u2194 tendsto (f \u2218 g) x y :=\nby rw [tendsto, map_map]; refl\n\nlemma tendsto_comap {f : \u03b1 \u2192 \u03b2} {x : filter \u03b2} : tendsto f (comap f x) x :=\nmap_comap_le\n\nlemma tendsto_comap_iff {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b3} {a : filter \u03b1} {c : filter \u03b3} :\n  tendsto f a (c.comap g) \u2194 tendsto (g \u2218 f) a c :=\n\u27e8assume h, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]\u27e9\n\nlemma tendsto_comap'_iff {m : \u03b1 \u2192 \u03b2} {f : filter \u03b1} {g : filter \u03b2} {i : \u03b3 \u2192 \u03b1}\n  (h : range i \u2208 f) : tendsto (m \u2218 i) (comap i f) g \u2194 tendsto m f g :=\nby rw [tendsto, \u2190 map_compose]; simp only [(\u2218), map_comap h, tendsto]\n\nlemma comap_eq_of_inverse {f : filter \u03b1} {g : filter \u03b2} {\u03c6 : \u03b1 \u2192 \u03b2} (\u03c8 : \u03b2 \u2192 \u03b1)\n  (eq : \u03c8 \u2218 \u03c6 = id) (h\u03c6 : tendsto \u03c6 f g) (h\u03c8 : tendsto \u03c8 g f) : comap \u03c6 g = f :=\nbegin\n  refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 h\u03c8) _) (map_le_iff_le_comap.1 h\u03c6),\n  rw [comap_comap_comp, eq, comap_id],\n  exact le_refl _\nend\n\nlemma map_eq_of_inverse {f : filter \u03b1} {g : filter \u03b2} {\u03c6 : \u03b1 \u2192 \u03b2} (\u03c8 : \u03b2 \u2192 \u03b1)\n  (eq : \u03c6 \u2218 \u03c8 = id) (h\u03c6 : tendsto \u03c6 f g) (h\u03c8 : tendsto \u03c8 g f) : map \u03c6 f = g :=\nbegin\n  refine le_antisymm h\u03c6 (le_trans _ (map_mono h\u03c8)),\n  rw [map_map, eq, map_id],\n  exact le_refl _\nend\n\nlemma tendsto_inf {f : \u03b1 \u2192 \u03b2} {x : filter \u03b1} {y\u2081 y\u2082 : filter \u03b2} :\n  tendsto f x (y\u2081 \u2293 y\u2082) \u2194 tendsto f x y\u2081 \u2227 tendsto f x y\u2082 :=\nby simp only [tendsto, lattice.le_inf_iff, iff_self]\n\nlemma tendsto_inf_left {f : \u03b1 \u2192 \u03b2} {x\u2081 x\u2082 : filter \u03b1} {y : filter \u03b2}\n  (h : tendsto f x\u2081 y) : tendsto f (x\u2081 \u2293 x\u2082) y  :=\nle_trans (map_mono inf_le_left) h\n\nlemma tendsto_inf_right {f : \u03b1 \u2192 \u03b2} {x\u2081 x\u2082 : filter \u03b1} {y : filter \u03b2}\n  (h : tendsto f x\u2082 y) : tendsto f (x\u2081 \u2293 x\u2082) y  :=\nle_trans (map_mono inf_le_right) h\n\nlemma tendsto_infi {f : \u03b1 \u2192 \u03b2} {x : filter \u03b1} {y : \u03b9 \u2192 filter \u03b2} :\n  tendsto f x (\u2a05i, y i) \u2194 \u2200i, tendsto f x (y i) :=\nby simp only [tendsto, iff_self, lattice.le_infi_iff]\n\nlemma tendsto_infi' {f : \u03b1 \u2192 \u03b2} {x : \u03b9 \u2192 filter \u03b1} {y : filter \u03b2} (i : \u03b9) :\n  tendsto f (x i) y \u2192 tendsto f (\u2a05i, x i) y :=\ntendsto_le_left (infi_le _ _)\n\nlemma tendsto_principal {f : \u03b1 \u2192 \u03b2} {a : filter \u03b1} {s : set \u03b2} :\n  tendsto f a (principal s) \u2194 {a | f a \u2208 s} \u2208 a :=\nby simp only [tendsto, le_principal_iff, mem_map, iff_self]\n\nlemma tendsto_principal_principal {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {t : set \u03b2} :\n  tendsto f (principal s) (principal t) \u2194 \u2200a\u2208s, f a \u2208 t :=\nby simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl\n\nlemma tendsto_pure_pure (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n  tendsto f (pure a) (pure (f a)) :=\nshow filter.map f (pure a) \u2264 pure (f a),\n  by rw [filter.map_pure]; exact le_refl _\n\nlemma tendsto_const_pure {a : filter \u03b1} {b : \u03b2} : tendsto (\u03bba, b) a (pure b) :=\nby simp [tendsto]; exact univ_mem_sets\n\nlemma tendsto_if {l\u2081 : filter \u03b1} {l\u2082 : filter \u03b2}\n    {f g : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} [decidable_pred p]\n    (h\u2080 : tendsto f (l\u2081 \u2293 principal p) l\u2082)\n    (h\u2081 : tendsto g (l\u2081 \u2293 principal { x | \u00ac p x }) l\u2082) :\n  tendsto (\u03bb x, if p x then f x else g x) l\u2081 l\u2082 :=\nbegin\n  revert h\u2080 h\u2081, simp only [tendsto_def, mem_inf_principal],\n  intros h\u2080 h\u2081 s hs,\n  apply mem_sets_of_superset (inter_mem_sets (h\u2080 s hs) (h\u2081 s hs)),\n  rintros x \u27e8hp\u2080, hp\u2081\u27e9, dsimp,\n  by_cases h : p x,\n  { rw if_pos h, exact hp\u2080 h },\n  rw if_neg h, exact hp\u2081 h\nend\n\n\nsection prod\nvariables {s : set \u03b1} {t : set \u03b2} {f : filter \u03b1} {g : filter \u03b2}\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 \u2208 F  <->  \u2203n, [n..\u221e] \u00d7 univ \u2286 s\n\n  G := do {y <- top, x <- seq, return (x, y)}\n  hence:\n    s \u2208 G  <->  \u2200i:\u2115, \u2203n, [n..\u221e] \u00d7 {i} \u2286 s\n\n  Now \u22c3i, [i..\u221e] \u00d7 {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 \u03b1) (g : filter \u03b2) : filter (\u03b1 \u00d7 \u03b2) :=\nf.comap prod.fst \u2293 g.comap prod.snd\n\nlemma prod_mem_prod {s : set \u03b1} {t : set \u03b2} {f : filter \u03b1} {g : filter \u03b2}\n  (hs : s \u2208 f) (ht : t \u2208 g) : set.prod s t \u2208 filter.prod f g :=\ninter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht)\n\nlemma mem_prod_iff {s : set (\u03b1\u00d7\u03b2)} {f : filter \u03b1} {g : filter \u03b2} :\n  s \u2208 filter.prod f g \u2194 (\u2203 t\u2081 \u2208 f, \u2203 t\u2082 \u2208 g, set.prod t\u2081 t\u2082 \u2286 s) :=\nbegin\n  simp only [filter.prod],\n  split,\n  exact assume \u27e8t\u2081, \u27e8s\u2081, hs\u2081, hts\u2081\u27e9, t\u2082, \u27e8s\u2082, hs\u2082, hts\u2082\u27e9, h\u27e9,\n    \u27e8s\u2081, hs\u2081, s\u2082, hs\u2082, subset.trans (inter_subset_inter hts\u2081 hts\u2082) h\u27e9,\n  exact assume \u27e8t\u2081, ht\u2081, t\u2082, ht\u2082, h\u27e9,\n    \u27e8prod.fst \u207b\u00b9' t\u2081, \u27e8t\u2081, ht\u2081, subset.refl _\u27e9, prod.snd \u207b\u00b9' t\u2082, \u27e8t\u2082, ht\u2082, subset.refl _\u27e9, h\u27e9\nend\n\nlemma tendsto_fst {f : filter \u03b1} {g : filter \u03b2} : tendsto prod.fst (filter.prod f g) f :=\ntendsto_inf_left tendsto_comap\n\nlemma tendsto_snd {f : filter \u03b1} {g : filter \u03b2} : tendsto prod.snd (filter.prod f g) g :=\ntendsto_inf_right tendsto_comap\n\nlemma tendsto.prod_mk {f : filter \u03b1} {g : filter \u03b2} {h : filter \u03b3} {m\u2081 : \u03b1 \u2192 \u03b2} {m\u2082 : \u03b1 \u2192 \u03b3}\n  (h\u2081 : tendsto m\u2081 f g) (h\u2082 : tendsto m\u2082 f h) : tendsto (\u03bbx, (m\u2081 x, m\u2082 x)) f (filter.prod g h) :=\ntendsto_inf.2 \u27e8tendsto_comap_iff.2 h\u2081, tendsto_comap_iff.2 h\u2082\u27e9\n\nlemma prod_infi_left {f : \u03b9 \u2192 filter \u03b1} {g : filter \u03b2} (i : \u03b9) :\n  filter.prod (\u2a05i, f i) g = (\u2a05i, 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 \u03b1} {g : \u03b9 \u2192 filter \u03b2} (i : \u03b9) :\n  filter.prod f (\u2a05i, g i) = (\u2a05i, 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\u2081 f\u2082 : filter \u03b1} {g\u2081 g\u2082 : filter \u03b2} (hf : f\u2081 \u2264 f\u2082) (hg : g\u2081 \u2264 g\u2082) :\n  filter.prod f\u2081 g\u2081 \u2264 filter.prod f\u2082 g\u2082 :=\ninf_le_inf (comap_mono hf) (comap_mono hg)\n\nlemma prod_comap_comap_eq {\u03b1\u2081 : Type u} {\u03b1\u2082 : Type v} {\u03b2\u2081 : Type w} {\u03b2\u2082 : Type x}\n  {f\u2081 : filter \u03b1\u2081} {f\u2082 : filter \u03b1\u2082} {m\u2081 : \u03b2\u2081 \u2192 \u03b1\u2081} {m\u2082 : \u03b2\u2082 \u2192 \u03b1\u2082} :\n  filter.prod (comap m\u2081 f\u2081) (comap m\u2082 f\u2082) = comap (\u03bbp:\u03b2\u2081\u00d7\u03b2\u2082, (m\u2081 p.1, m\u2082 p.2)) (filter.prod f\u2081 f\u2082) :=\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, (\u2218), inf_comm, prod.fst_swap,\n  eq_self_iff_true, prod.snd_swap, comap_inf]\n\nlemma prod_comm : filter.prod f g = map (\u03bbp:\u03b2\u00d7\u03b1, (p.2, p.1)) (filter.prod g f) :=\nby rw [prod_comm', \u2190 map_swap_eq_comap_swap]; refl\n\nlemma prod_map_map_eq {\u03b1\u2081 : Type u} {\u03b1\u2082 : Type v} {\u03b2\u2081 : Type w} {\u03b2\u2082 : Type x}\n  {f\u2081 : filter \u03b1\u2081} {f\u2082 : filter \u03b1\u2082} {m\u2081 : \u03b1\u2081 \u2192 \u03b2\u2081} {m\u2082 : \u03b1\u2082 \u2192 \u03b2\u2082} :\n  filter.prod (map m\u2081 f\u2081) (map m\u2082 f\u2082) = map (\u03bbp:\u03b1\u2081\u00d7\u03b1\u2082, (m\u2081 p.1, m\u2082 p.2)) (filter.prod f\u2081 f\u2082) :=\nle_antisymm\n  (assume s hs,\n    let \u27e8s\u2081, hs\u2081, s\u2082, hs\u2082, h\u27e9 := mem_prod_iff.mp hs in\n    filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs\u2081) (image_mem_map hs\u2082)) $\n      calc set.prod (m\u2081 '' s\u2081) (m\u2082 '' s\u2082) = (\u03bbp:\u03b1\u2081\u00d7\u03b1\u2082, (m\u2081 p.1, m\u2082 p.2)) '' set.prod s\u2081 s\u2082 :\n          set.prod_image_image_eq\n        ... \u2286 _ : by rwa [image_subset_iff])\n  ((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _)))\n\nlemma map_prod (m : \u03b1 \u00d7 \u03b2 \u2192 \u03b3) (f : filter \u03b1) (g : filter \u03b2) :\n  map m (f.prod g) = (f.map (\u03bba 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 \u27e8t, ht, s, hs, h\u27e9, \u27e8s, hs, t, ht, assume x hx y hy, @h \u27e8x, y\u27e9 \u27e8hx, hy\u27e9\u27e9,\n  exact assume \u27e8s, hs, t, ht, h\u27e9, \u27e8t, ht, s, hs, assume \u27e8x, y\u27e9 \u27e8hx, hy\u27e9, h x hx y hy\u27e9\nend\n\nlemma prod_eq {f : filter \u03b1} {g : filter \u03b2} : 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\u2081 f\u2082 : filter \u03b1} {g\u2081 g\u2082 : filter \u03b2} :\n  filter.prod f\u2081 g\u2081 \u2293 filter.prod f\u2082 g\u2082 = filter.prod (f\u2081 \u2293 f\u2082) (g\u2081 \u2293 g\u2082) :=\nby simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm]\n\n@[simp] lemma prod_bot {f : filter \u03b1} : filter.prod f (\u22a5 : filter \u03b2) = \u22a5 := by simp [filter.prod]\n@[simp] lemma bot_prod {g : filter \u03b2} : filter.prod (\u22a5 : filter \u03b1) g = \u22a5 := by simp [filter.prod]\n\n@[simp] lemma prod_principal_principal {s : set \u03b1} {t : set \u03b2} :\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 : \u03b1} {b : \u03b2} : filter.prod (pure a) (pure b) = pure (a, b) :=\nby simp\n\nlemma prod_eq_bot {f : filter \u03b1} {g : filter \u03b2} : filter.prod f g = \u22a5 \u2194 (f = \u22a5 \u2228 g = \u22a5) :=\nbegin\n  split,\n  { assume h,\n    rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with \u27e8s, hs, t, ht, hst\u27e9,\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 \u25b8 hs) },\n    { right, exact empty_in_sets_eq_bot.1 (t_eq \u25b8 ht) } },\n  { rintros (rfl | rfl),\n    exact bot_prod,\n    exact prod_bot }\nend\n\nlemma prod_neq_bot {f : filter \u03b1} {g : filter \u03b2} : filter.prod f g \u2260 \u22a5 \u2194 (f \u2260 \u22a5 \u2227 g \u2260 \u22a5) :=\nby rw [(\u2260), prod_eq_bot, not_or_distrib]\n\nlemma tendsto_prod_iff {f : \u03b1 \u00d7 \u03b2 \u2192 \u03b3} {x : filter \u03b1} {y : filter \u03b2} {z : filter \u03b3} :\n  filter.tendsto f (filter.prod x y) z \u2194\n  \u2200 W \u2208 z, \u2203 U \u2208 x,  \u2203 V \u2208 y, \u2200 x y, x \u2208 U \u2192 y \u2208 V \u2192 f (x, y) \u2208 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 `\u2192 \u221e` on an ordered set.\n  It is generated by the collection of up-sets `{b | a \u2264 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 \u03b1] : filter \u03b1 := \u2a05 a, principal {b | a \u2264 b}\n\n/-- `at_bot` is the filter representing the limit `\u2192 -\u221e` on an ordered set.\n  It is generated by the collection of down-sets `{b | b \u2264 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 \u03b1] : filter \u03b1 := \u2a05 a, principal {b | b \u2264 a}\n\nlemma mem_at_top [preorder \u03b1] (a : \u03b1) : {b : \u03b1 | a \u2264 b} \u2208 @at_top \u03b1 _ :=\nmem_infi_sets a $ subset.refl _\n\n@[simp] lemma at_top_ne_bot [nonempty \u03b1] [semilattice_sup \u03b1] : (at_top : filter \u03b1) \u2260 \u22a5 :=\ninfi_neq_bot_of_directed (by apply_instance)\n  (assume a b, \u27e8a \u2294 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}\u27e9)\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 \u03b1] [semilattice_sup \u03b1] {s : set \u03b1} :\n  s \u2208 (at_top : filter \u03b1) \u2194 \u2203a:\u03b1, \u2200b\u2265a, b \u2208 s :=\nlet \u27e8a\u27e9 := \u2039nonempty \u03b1\u203a in\niff.intro\n  (assume h, infi_sets_induct h \u27e8a, by simp only [forall_const, mem_univ, forall_true_iff]\u27e9\n    (assume a s\u2081 s\u2082 ha \u27e8b, hb\u27e9, \u27e8a \u2294 b,\n      assume c hc, \u27e8ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc\u27e9\u27e9)\n    (assume s\u2081 s\u2082 h \u27e8a, ha\u27e9, \u27e8a, assume b hb, h $ ha _ hb\u27e9))\n  (assume \u27e8a, h\u27e9, mem_infi_sets a $ assume x, h x)\n\nlemma map_at_top_eq [nonempty \u03b1] [semilattice_sup \u03b1] {f : \u03b1 \u2192 \u03b2} :\n  at_top.map f = (\u2a05a, principal $ f '' {a' | a \u2264 a'}) :=\ncalc map f (\u2a05a, principal {a' | a \u2264 a'}) = (\u2a05a, map f $ principal {a' | a \u2264 a'}) :\n    map_infi_eq (assume a b, \u27e8a \u2294 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}\u27e9)\n      (by apply_instance)\n  ... = (\u2a05a, principal $ f '' {a' | a \u2264 a'}) : by simp only [map_principal, eq_self_iff_true]\n\nlemma tendsto_at_top [preorder \u03b2] (m : \u03b1 \u2192 \u03b2) (f : filter \u03b1) :\n  tendsto m f at_top \u2194 (\u2200b, {a | b \u2264 m a} \u2208 f) :=\nby simp only [at_top, tendsto_infi, tendsto_principal]; refl\n\nlemma tendsto_at_top' [nonempty \u03b1] [semilattice_sup \u03b1] (f : \u03b1 \u2192 \u03b2) (l : filter \u03b2) :\n  tendsto f at_top l \u2194 (\u2200s \u2208 l, \u2203a, \u2200b\u2265a, f b \u2208 s) :=\nby simp only [tendsto_def, mem_at_top_sets]; refl\n\ntheorem tendsto_at_top_principal [nonempty \u03b2] [semilattice_sup \u03b2] {f : \u03b2 \u2192 \u03b1} {s : set \u03b1} :\n  tendsto f at_top (principal s) \u2194 \u2203N, \u2200n\u2265N, f n \u2208 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 {\u03b1 \u03b2 \u03b3 : Type*} [preorder \u03b2] [preorder \u03b3]\n  {f : \u03b1 \u2192 \u03b2} {e : \u03b2 \u2192 \u03b3} {l : filter \u03b1}\n  (hm : \u2200b\u2081 b\u2082, e b\u2081 \u2264 e b\u2082 \u2194 b\u2081 \u2264 b\u2082) (hu : \u2200c, \u2203b, c \u2264 e b) :\n  tendsto (e \u2218 f) l at_top \u2194 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 \u27e8b, hc\u27e9,\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 \u03b1] [semilattice_sup \u03b1] [preorder \u03b2] (f : \u03b1 \u2192 \u03b2) :\n  tendsto f at_top at_top \u2194 \u2200 b : \u03b2, \u2203 i : \u03b1, \u2200 a : \u03b1, i \u2264 a \u2192 b \u2264 f a :=\niff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal\n\nlemma tendsto_finset_image_at_top_at_top {i : \u03b2 \u2192 \u03b3} {j : \u03b3 \u2192 \u03b2} (h : \u2200x, j (i x) = x) :\n  tendsto (\u03bbs:finset \u03b3, 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 \u2286 t),\n  calc s = (s.image i).image j :\n      by simp only [finset.image_image, (\u2218), h]; exact finset.image_id.symm\n    ... \u2286  t.image j : finset.image_subset_image ht\n\nlemma prod_at_top_at_top_eq {\u03b2\u2081 \u03b2\u2082 : Type*} [inhabited \u03b2\u2081] [inhabited \u03b2\u2082] [semilattice_sup \u03b2\u2081]\n  [semilattice_sup \u03b2\u2082] : filter.prod (@at_top \u03b2\u2081 _) (@at_top \u03b2\u2082 _) = @at_top (\u03b2\u2081 \u00d7 \u03b2\u2082) _ :=\nby simp [at_top, prod_infi_left (default \u03b2\u2081), prod_infi_right (default \u03b2\u2082), infi_prod];\n    exact infi_comm\n\nlemma prod_map_at_top_eq {\u03b1\u2081 \u03b1\u2082 \u03b2\u2081 \u03b2\u2082 : Type*} [inhabited \u03b2\u2081] [inhabited \u03b2\u2082]\n  [semilattice_sup \u03b2\u2081] [semilattice_sup \u03b2\u2082] (u\u2081 : \u03b2\u2081 \u2192 \u03b1\u2081) (u\u2082 : \u03b2\u2082 \u2192 \u03b1\u2082) :\n  filter.prod (map u\u2081 at_top) (map u\u2082 at_top) = map (prod.map u\u2081 u\u2082) 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 \u03b1] [semilattice_sup \u03b2] {f : \u03b1 \u2192 \u03b2} (g : \u03b2 \u2192 \u03b1) (b' : \u03b2)(hf : monotone f) (gc : \u2200a, \u2200b\u2265b', f a \u2264 b \u2194 a \u2264 g b) (hgi : \u2200b\u2265b', b \u2264 f (g b)) :\n  map f at_top = at_top :=\nbegin\n  rw [@map_at_top_eq \u03b1 _ \u27e8g b'\u27e9],\n  refine le_antisymm\n    (le_infi $ assume b, infi_le_of_le (g (b \u2294 b')) $ principal_mono.2 $ image_subset_iff.2 _)\n    (le_infi $ assume a, infi_le_of_le (f a \u2294 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' \u2264 b := le_trans le_sup_right hb,\n    exact \u27e8g b, (gc _ _ hb').1 (le_trans le_sup_left hb),\n      le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')\u27e9 }\nend\n\nlemma map_add_at_top_eq_nat (k : \u2115) : map (\u03bba, a + k) at_top = at_top :=\nmap_at_top_eq_of_gc (\u03bba, 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 : \u2115) : map (\u03bba, a - k) at_top = at_top :=\nmap_at_top_eq_of_gc (\u03bba, 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 : \u2115) : tendsto (\u03bba, a + k) at_top at_top :=\nle_of_eq (map_add_at_top_eq_nat k)\n\nlemma tendso_sub_at_top_nat (k : \u2115) : tendsto (\u03bba, 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 : \u2115 \u2192 \u03b1} {l : filter \u03b1} (k : \u2115) :\n  tendsto (\u03bbn, f (n + k)) at_top l \u2194 tendsto f at_top l :=\nshow tendsto (f \u2218 (\u03bbn, n + k)) at_top l \u2194 tendsto f at_top l,\n  by rw [\u2190 tendsto_map'_iff, map_add_at_top_eq_nat]\n\nlemma map_div_at_top_eq_nat (k : \u2115) (hk : k > 0) : map (\u03bba, a / k) at_top = at_top :=\nmap_at_top_eq_of_gc (\u03bbb, b * k + (k - 1)) 1\n  (assume a b h, nat.div_le_div_right h)\n  (assume a b _,\n    calc a / k \u2264 b \u2194 a / k < b + 1 : by rw [\u2190 nat.succ_eq_add_one, nat.lt_succ_iff]\n      ... \u2194 a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk\n      ... \u2194 _ :\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      ... \u2264 (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 \u03b1}\n\n/-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/\ndef is_ultrafilter (f : filter \u03b1) := f \u2260 \u22a5 \u2227 \u2200g, g \u2260 \u22a5 \u2192 g \u2264 f \u2192 f \u2264 g\n\nlemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f \u2260 \u22a5) (h : f \u2264 g) : f = g :=\nle_antisymm h (hg.right _ hf h)\n\nlemma le_of_ultrafilter {g : filter \u03b1} (hf : is_ultrafilter f) (h : f \u2293 g \u2260 \u22a5) :\n  f \u2264 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 \u2194 (\u2200 s, -s \u2208 f \u2194 s \u2209 f) :=\n\u27e8assume hf s,\n   \u27e8assume 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 \u2264 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\u27e9,\n assume hf,\n   \u27e8mt empty_in_sets_eq_bot.mpr ((hf \u2205).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 \u2208 f,\n        have s \u2229 -s \u2208 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\u27e9\u27e9\n\nlemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set \u03b1) :\n  s \u2208 f \u2228 - s \u2208 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 \u03b1} (hf : is_ultrafilter f) (h : s \u222a t \u2208 f) :\n  s \u2208 f \u2228 t \u2208 f :=\n(mem_or_compl_mem_of_ultrafilter hf s).imp_right\n  (assume : -s \u2208 f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx)\n\nlemma mem_of_finite_sUnion_ultrafilter {s : set (set \u03b1)} (hf : is_ultrafilter f) (hs : finite s)\n  : \u22c3\u2080 s \u2208 f \u2192 \u2203t\u2208s, t \u2208 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\u03bb 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 \u2208 f, \u27e8t, or.inl rfl, this\u27e9)\n  (assume h, let \u27e8t, hts', ht\u27e9 := ih h in \u27e8t, or.inr hts', ht\u27e9)\n\nlemma mem_of_finite_Union_ultrafilter {is : set \u03b2} {s : \u03b2 \u2192 set \u03b1}\n  (hf : is_ultrafilter f) (his : finite is) (h : (\u22c3i\u2208is, s i) \u2208 f) : \u2203i\u2208is, s i \u2208 f :=\nhave his : finite (image s is), from finite_image s his,\nhave h : (\u22c3\u2080 image s is) \u2208 f, from by simp only [sUnion_image, set.sUnion_image]; assumption,\nlet \u27e8t, \u27e8i, hi, h_eq\u27e9, (ht : t \u2208 f)\u27e9 := mem_of_finite_sUnion_ultrafilter hf his h in\n\u27e8i, hi, h_eq.symm \u25b8 ht\u27e9\n\nlemma ultrafilter_map {f : filter \u03b1} {m : \u03b1 \u2192 \u03b2} (h : is_ultrafilter f) : is_ultrafilter (map m f) :=\nby rw ultrafilter_iff_compl_mem_iff_not_mem at \u22a2 h; exact assume s, h (m \u207b\u00b9' s)\n\nlemma ultrafilter_pure {a : \u03b1} : 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 \u03b1} (hf : is_ultrafilter f) {m : \u03b1 \u2192 filter \u03b2}\n  (hm : \u2200 a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) :=\nbegin\n  simp only [ultrafilter_iff_compl_mem_iff_not_mem] at \u22a2 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 \u2260 \u22a5) : \u2203u, u \u2264 f \u2227 is_ultrafilter u :=\nlet\n  \u03c4                := {f' // f' \u2260 \u22a5 \u2227 f' \u2264 f},\n  r : \u03c4 \u2192 \u03c4 \u2192 Prop := \u03bbt\u2081 t\u2082, t\u2082.val \u2264 t\u2081.val,\n  \u27e8a, ha\u27e9          := inhabited_of_mem_sets h univ_mem_sets,\n  top : \u03c4          := \u27e8f, h, le_refl f\u27e9,\n  sup : \u03a0(c:set \u03c4), chain r c \u2192 \u03c4 :=\n    \u03bbc hc, \u27e8\u2a05a:{a:\u03c4 // a \u2208 insert top c}, a.val.val,\n      infi_neq_bot_of_directed \u27e8a\u27e9\n        (directed_of_chain $ chain_insert hc $ assume \u27e8b, _, hb\u27e9 _ _, or.inl hb)\n        (assume \u27e8\u27e8a, ha, _\u27e9, _\u27e9, ha),\n      infi_le_of_le \u27e8top, mem_insert _ _\u27e9 (le_refl _)\u27e9\nin\nhave \u2200c (hc: chain r c) a (ha : a \u2208 c), r a (sup c hc),\n  from assume c hc a ha, infi_le_of_le \u27e8a, mem_insert_of_mem _ ha\u27e9 (le_refl _),\nhave (\u2203 (u : \u03c4), \u2200 (a : \u03c4), r u a \u2192 r a u),\n  from zorn (assume c hc, \u27e8sup c hc, this c hc\u27e9) (assume f\u2081 f\u2082 f\u2083 h\u2081 h\u2082, le_trans h\u2082 h\u2081),\nlet \u27e8u\u03c4, hmin\u27e9 := this in\n\u27e8u\u03c4.val, u\u03c4.property.right, u\u03c4.property.left, assume g hg\u2081 hg\u2082,\n  hmin \u27e8g, hg\u2081, le_trans hg\u2082 u\u03c4.property.right\u27e9 hg\u2082\u27e9\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 \u03b1) : filter \u03b1 :=\nif h : f = \u22a5 then \u22a5 else classical.epsilon (\u03bbu, u \u2264 f \u2227 is_ultrafilter u)\n\nlemma ultrafilter_of_spec (h : f \u2260 \u22a5) : ultrafilter_of f \u2264 f \u2227 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 \u2264 f :=\nif h : f = \u22a5 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 \u2260 \u22a5) : 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 \u03b1) : f = \u2a06 (g) (u : is_ultrafilter g) (H : g \u2264 f), g :=\nbegin\n  refine le_antisymm _ (supr_le $ \u03bb g, supr_le $ \u03bb u, supr_le $ \u03bb H, H),\n  intros s hs,\n  -- If s \u2209 f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s.\n  by_contradiction hs',\n  let j : (-s) \u2192 \u03b1 := subtype.val,\n  have j_inv_s : j \u207b\u00b9' s = \u2205, by\n    erw [\u2190preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty],\n  let f' := comap j f,\n  have : f' \u2260 \u22a5,\n  { apply mt empty_in_sets_eq_bot.mpr,\n    rintro \u27e8t, htf, ht\u27e9,\n    suffices : t \u2286 s, from absurd (f.sets_of_superset htf this) hs',\n    rw [subset_empty_iff] at ht,\n    have : j '' (j \u207b\u00b9' t) = \u2205, by rw [ht, image_empty],\n    erw [image_preimage_eq_inter_range, subtype.val_range, \u2190subset_compl_iff_disjoint,\n      set.compl_compl] at this,\n    exact this },\n  rcases exists_ultrafilter this with \u27e8g', g'f', u'\u27e9,\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 [\u2190le_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 : \u03b1 \u2192 \u03b2) (l\u2081 : filter \u03b1) (l\u2082 : filter \u03b2) :\n  tendsto f l\u2081 l\u2082 \u2194 \u2200 g, is_ultrafilter g \u2192 g \u2264 l\u2081 \u2192 g.map f \u2264 l\u2082 :=\n\u27e8assume h g u gx, le_trans (map_mono gx) h,\n assume h, by rw [sup_of_ultrafilters l\u2081]; simpa only [tendsto, map_supr, supr_le_iff]\u27e9\n\n/- The ultrafilter monad. The monad structure on ultrafilters is the\n  restriction of the one on filters. -/\n\ndef ultrafilter (\u03b1 : Type u) : Type u := {f : filter \u03b1 // is_ultrafilter f}\n\ndef ultrafilter.map (m : \u03b1 \u2192 \u03b2) (u : ultrafilter \u03b1) : ultrafilter \u03b2 :=\n\u27e8u.val.map m, ultrafilter_map u.property\u27e9\n\ndef ultrafilter.pure (x : \u03b1) : ultrafilter \u03b1 := \u27e8pure x, ultrafilter_pure\u27e9\n\ndef ultrafilter.bind (u : ultrafilter \u03b1) (m : \u03b1 \u2192 ultrafilter \u03b2) : ultrafilter \u03b2 :=\n\u27e8u.val.bind (\u03bb a, (m a).val), ultrafilter_bind u.property (\u03bb a, (m a).property)\u27e9\n\ninstance ultrafilter.has_pure : has_pure ultrafilter := \u27e8@ultrafilter.pure\u27e9\ninstance ultrafilter.has_bind : has_bind ultrafilter := \u27e8@ultrafilter.bind\u27e9\ninstance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map }\ninstance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map }\n\nnoncomputable def hyperfilter : filter \u03b1 := ultrafilter_of cofinite\n\nlemma hyperfilter_le_cofinite (hi : set.infinite (@set.univ \u03b1)) : @hyperfilter \u03b1 \u2264 cofinite := \n(ultrafilter_of_spec (cofinite_ne_bot hi)).1\n\nlemma is_ultrafilter_hyperfilter (hi : set.infinite (@set.univ \u03b1)) : is_ultrafilter (@hyperfilter \u03b1) := \n(ultrafilter_of_spec (cofinite_ne_bot hi)).2\n\ntheorem nmem_hyperfilter_of_finite (hi : set.infinite (@set.univ \u03b1)) {s : set \u03b1} (hf : set.finite s) :\n  s \u2209 @hyperfilter \u03b1 :=\n\u03bb hy, \nhave hx : -s \u2209 hyperfilter := \n  \u03bb hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mp hs hy,\nhave ht : -s \u2208 cofinite.sets := by show -s \u2208 {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 \u03b1)) {s : set \u03b1} (hf : set.finite s) :\n  -s \u2208 @hyperfilter \u03b1 :=\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 \u03b1)) {s : set \u03b1} (hf : set.finite (-s)) :\n  s \u2208 @hyperfilter \u03b1 := \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 \u03b1 f, subtype.eq (id_map f.val),\n  pure_bind := assume \u03b1 \u03b2 a f, subtype.eq (pure_bind a (subtype.val \u2218 f)),\n  bind_assoc := assume \u03b1 \u03b2 \u03b3 f m\u2081 m\u2082, subtype.eq (filter_eq rfl),\n  bind_pure_comp_eq_map := assume \u03b1 \u03b2 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 \u03b1} : u = v \u2194 u.val \u2264 v.val :=\n\u27e8assume h, by rw h; exact le_refl _,\n assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h\u27e9\n\nlemma exists_ultrafilter_iff (f : filter \u03b1) : (\u2203 (u : ultrafilter \u03b1), u.val \u2264 f) \u2194 f \u2260 \u22a5 :=\n\u27e8assume \u27e8u, uf\u27e9, lattice.neq_bot_of_le_neq_bot u.property.1 uf,\n assume h, let \u27e8u, uf, hu\u27e9 := exists_ultrafilter h in \u27e8\u27e8u, hu\u27e9, uf\u27e9\u27e9\n\nend ultrafilter\n\nend filter\n\nnamespace filter\nvariables {\u03b1 \u03b2 \u03b3 : Type u} {f : \u03b2 \u2192 filter \u03b1} {s : \u03b3 \u2192 set \u03b1}\nopen list\n\nlemma mem_traverse_sets :\n  \u2200(fs : list \u03b2) (us : list \u03b3),\n    forall\u2082 (\u03bbb c, s c \u2208 f b) fs us \u2192 traverse s us \u2208 traverse f fs\n| []      []      forall\u2082.nil         := mem_pure_sets.2 $ mem_singleton _\n| (f::fs) (u::us) (forall\u2082.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 \u03b2) (t : set (list \u03b1)) :\n  t \u2208 traverse f fs \u2194\n    (\u2203us:list (set \u03b1), forall\u2082 (\u03bbb (s : set \u03b1), s \u2208 f b) fs us \u2227 sequence us \u2286 t) :=\nbegin\n  split,\n  { induction fs generalizing t,\n    case nil { simp only [sequence, pure_def, imp_self, forall\u2082_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 \u27e8u, hu, v, hv, ht\u27e9,\n      rcases mem_map_sets_iff.1 hu with \u27e8w, hw, hwu\u27e9,\n      rcases ih v hv with \u27e8us, hus, hu\u27e9,\n      exact \u27e8w :: us, forall\u2082.cons hw hus, subset.trans (set.seq_mono hwu hu) ht\u27e9 } },\n  { rintros \u27e8us, hus, hs\u27e9,\n    exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs }\nend\n\nlemma sequence_mono :\n  \u2200(as bs : list (filter \u03b1)), forall\u2082 (\u2264) as bs \u2192 sequence as \u2264 sequence bs\n| []      []      forall\u2082.nil         := le_refl _\n| (a::as) (b::bs) (forall\u2082.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\u2081 c\u2082 : CtorInfo) : Bool :=\n  c\u2081.size == c\u2082.size && c\u2081.usize == c\u2082.usize && c\u2081.ssize == c\u2082.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\u2081.name.getPrefix == c\u2082.name.getPrefix\n\nprivate partial def S (w : VarId) (c : CtorInfo) : FnBody \u2192 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 \u2190 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 \u2190 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 \u00d7 Bool \u2192 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 \u2192 M (FnBody \u00d7 Bool)\n  | e@(FnBody.case tid y yType alts) => do\n    let ctx \u2190 read\n    if e.hasLiveVar ctx x then do\n      /- If `x` is live in `e`, we recursively process each branch. -/\n      let alts \u2190 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) \u2190 withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b)\n    let (v, _ /- found' -/) \u2190 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 \u2190 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) \u2190 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 \u2190 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 \u2192 M FnBody\n  | FnBody.case tid x xType alts   => do\n      let alts \u2190 alts.mapM fun alt => do\n        let alt \u2190 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 \u2190 R v\n    let b \u2190 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 \u2190 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) 2021 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\n\nnamespace Lean.Parser.Tactic\n\n-- syntax simpArg := simpStar <|> simpErase <|> simpLemma\n/--\nA `simpArg` is either a `*`, `-lemma` or a simp lemma specification\n(which includes the `\u2191` `\u2193` `\u2190` specifications for pre, post, reverse rewriting).\n-/\ndef simpArg := simpStar.binary `orelse (simpErase.binary `orelse simpLemma)\n\n/-- A simp args list is a list of `simpArg`. This is the main argument to `simp`. -/\nsyntax simpArgs := \" [\" simpArg,* \"] \"\n\n/-- Extract the arguments from a `simpArgs` syntax as an array of syntaxes -/\ndef getSimpArgs? : Syntax \u2192 Option (Array Syntax)\n  | `(simpArgs| [$args,*]) => pure args.getElems\n  | _ => none\n\n-- syntax dsimpArg := simpErase <|> simpLemma\n/--\nA `dsimpArg` is similar to `simpArg`, but it does not have the `simpStar` form\nbecause it does not make sense to use hypotheses in `dsimp`.\n-/\ndef dsimpArg := simpErase.binary `orelse simpLemma\n\n/-- A dsimp args list is a list of `dsimpArg`. This is the main argument to `dsimp`. -/\nsyntax dsimpArgs := \" [\" dsimpArg,* \"]\"\n\n/-- Extract the arguments from a `dsimpArgs` syntax as an array of syntaxes -/\ndef getDSimpArgs? : Syntax \u2192 Option (Array Syntax)\n  | `(dsimpArgs| [$args,*]) => pure args.getElems\n  | _                       => none\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Lean/Parser.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.05340333017646162, "lm_q1q2_score": 0.020161928242832357}}
{"text": "import tactic --hide\n\n/-Lemma\n$(\\mathrm{true} \\implies \\mathrm{false})^2$\n-/\nlemma lots_of_true_imp_false : true \u2192 false \u2192 true \u2192 false:=\nbegin\n  intros h1 h2 h3,\n  apply h2,\n\n\n  \nend", "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/true_false/tf7.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.04603390599833738, "lm_q1q2_score": 0.02015472580208632}}
{"text": "import tidy.forwards_reasoning\n\nlemma G (n : \u2115) : list \u2115 := [n]\nlemma F : \u2115 := 0\n\nsection\n\nlocal attribute [forward] G\n\nexample : 1 = 1 :=\nbegin\n  success_if_fail { forwards_library_reasoning },\n  refl\nend\n\nlocal attribute [forward] F\n\nexample : 1 = 1 :=\nbegin\n  forwards_library_reasoning,\n  forwards_library_reasoning,\n  success_if_fail { forwards_library_reasoning },\n  refl\nend\n\nexample : 1 = 1 :=\nbegin\n  have p := [0],\n  forwards_library_reasoning,\n  success_if_fail { forwards_library_reasoning },\n  refl\nend\nend\n\nsection\ninductive T (n : \u2115)\n| t : \u2115 \u2192 T\n\n@[forward] lemma H.H {n : \u2115} (v : T n) : string := \"hello\"\n\nexample : 1 = 1 :=\nbegin\n  success_if_fail { forwards_library_reasoning },\n  have p : T 3 := T.t 3 5,\n  forwards_library_reasoning,\n  guard_hyp H_p := string, -- check that we drop namespaces\n  refl\nend\n\nexample (P Q : Prop) (p : P) (h : P \u2192 Q): Q :=\nbegin\n  forwards_reasoning,\n  success_if_fail { forwards_reasoning },\n  exact h_p\nend\n\n\nend\n", "meta": {"author": "semorrison", "repo": "lean-tidy", "sha": "6c1d46de6cff05e1c2c4c9692af812bca3e13b6c", "save_path": "github-repos/lean/semorrison-lean-tidy", "path": "github-repos/lean/semorrison-lean-tidy/lean-tidy-6c1d46de6cff05e1c2c4c9692af812bca3e13b6c/test/forwards_reasoning.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.04813677418908, "lm_q1q2_score": 0.02015471857932039}}
{"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 : \u2115) (\u03b1 : fin n \u2192 Type u) \nwhere\n  data : (i : fin n) \u2192 \u03b1 i\n\nnamespace d_array\n\n\n/-- The empty array. -/\ndef nil {\u03b1 : fin 0 \u2192 Type u_1} : d_array 0 \u03b1 :=\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 : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) (i : fin n) : \u03b1 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 : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) (i : fin n) (v : \u03b1 i) : d_array n \u03b1 :=\n  mk fun (j : fin n) => dite (i = j) (fun (h : i = j) => eq.rec_on h v) fun (h : \u00aci = j) => read a j\n\ndef iterate_aux {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) (i : \u2115) : i \u2264 n \u2192 \u03b2 \u2192 \u03b2 :=\n  sorry\n\n/-- Fold over the elements of the given array in ascending order. Has builtin VM implementation. -/\ndef iterate {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (b : \u03b2) (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  iterate_aux a f n sorry b\n\n/-- Map the array. Has builtin VM implementation. -/\ndef foreach {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b1' : fin n \u2192 Type v} (a : d_array n \u03b1) (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b1' i) : d_array n \u03b1' :=\n  mk fun (i : fin n) => f i (read a i)\n\ndef map {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b1' : fin n \u2192 Type v} (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b1' i) (a : d_array n \u03b1) : d_array n \u03b1' :=\n  foreach a f\n\ndef map\u2082 {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b1' : fin n \u2192 Type v} {\u03b1'' : fin n \u2192 Type w} (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b1' i \u2192 \u03b1'' i) (a : d_array n \u03b1) (b : d_array n \u03b1') : d_array n \u03b1'' :=\n  foreach b fun (i : fin n) => f i (read a i)\n\ndef foldl {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (b : \u03b2) (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  iterate a b f\n\ndef rev_iterate_aux {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) (i : \u2115) : i \u2264 n \u2192 \u03b2 \u2192 \u03b2 :=\n  sorry\n\ndef rev_iterate {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (b : \u03b2) (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  rev_iterate_aux a f n sorry b\n\n@[simp] theorem read_write {n : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) (i : fin n) (v : \u03b1 i) : read (write a i v) i = v := sorry\n\n@[simp] theorem read_write_of_ne {n : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) {i : fin n} {j : fin n} (v : \u03b1 i) : i \u2260 j \u2192 read (write a i v) j = read a j := sorry\n\nprotected theorem ext {n : \u2115} {\u03b1 : fin n \u2192 Type u} {a : d_array n \u03b1} {b : d_array n \u03b1} (h : \u2200 (i : fin n), read a i = read b i) : a = b := sorry\n\nprotected theorem ext' {n : \u2115} {\u03b1 : fin n \u2192 Type u} {a : d_array n \u03b1} {b : d_array n \u03b1} (h : \u2200 (i : \u2115) (h : i < n), read a { val := i, property := h } = read b { val := i, property := h }) : a = b := sorry\n\nprotected def beq_aux {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] (a : d_array n \u03b1) (b : d_array n \u03b1) (i : \u2115) : i \u2264 n \u2192 Bool :=\n  sorry\n\n/-- Boolean element-wise equality check. -/\nprotected def beq {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] (a : d_array n \u03b1) (b : d_array n \u03b1) : Bool :=\n  d_array.beq_aux a b n sorry\n\ntheorem of_beq_aux_eq_tt {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] {a : d_array n \u03b1} {b : d_array n \u03b1} (i : \u2115) (h : i \u2264 n) : d_array.beq_aux a b i h = tt \u2192\n  \u2200 (j : \u2115) (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 : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] {a : d_array n \u03b1} {b : d_array n \u03b1} : d_array.beq a b = tt \u2192 a = b := sorry\n\ntheorem of_beq_aux_eq_ff {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] {a : d_array n \u03b1} {b : d_array n \u03b1} (i : \u2115) (h : i \u2264 n) : d_array.beq_aux a b i h = false \u2192\n  \u2203 (j : \u2115),\n    \u2203 (h' : j < i),\n      read a { val := j, property := lt_of_lt_of_le h' h } \u2260 read b { val := j, property := lt_of_lt_of_le h' h } := sorry\n\ntheorem of_beq_eq_ff {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] {a : d_array n \u03b1} {b : d_array n \u03b1} : d_array.beq a b = false \u2192 a \u2260 b := sorry\n\nprotected instance decidable_eq {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] : DecidableEq (d_array n \u03b1) :=\n  fun (a b : d_array n \u03b1) =>\n    dite (d_array.beq a b = tt) (fun (h : d_array.beq a b = tt) => is_true sorry)\n      fun (h : \u00acd_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 : \u2115) (\u03b1 : Type u) :=\n  d_array n fun (_x : fin n) => \u03b1\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 {\u03b1 : Type u_1} (n : \u2115) (v : \u03b1) : array n \u03b1 :=\n  d_array.mk fun (_x : fin n) => v\n\nnamespace array\n\n\ndef nil {\u03b1 : Type u_1} : array 0 \u03b1 :=\n  d_array.nil\n\ndef read {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) : \u03b1 :=\n  d_array.read a i\n\ndef write {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) (v : \u03b1) : array n \u03b1 :=\n  d_array.write a i v\n\n/-- Fold array starting from 0, folder function includes an index argument. -/\ndef iterate {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : fin n \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  d_array.iterate a b f\n\n/-- Map each element of the given array with an index argument. -/\ndef foreach {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (f : fin n \u2192 \u03b1 \u2192 \u03b2) : array n \u03b2 :=\n  d_array.foreach a f\n\ndef map\u2082 {n : \u2115} {\u03b1 : Type u} (f : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (a : array n \u03b1) (b : array n \u03b1) : array n \u03b1 :=\n  foreach b fun (i : fin n) => f (read a i)\n\ndef foldl {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  iterate a b fun (_x : fin n) => f\n\ndef rev_list {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) : List \u03b1 :=\n  foldl a [] fun (_x : \u03b1) (_y : List \u03b1) => _x :: _y\n\ndef rev_iterate {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : fin n \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  d_array.rev_iterate a b f\n\ndef rev_foldl {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  rev_iterate a b fun (_x : fin n) => f\n\ndef to_list {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) : List \u03b1 :=\n  rev_foldl a [] fun (_x : \u03b1) (_y : List \u03b1) => _x :: _y\n\ntheorem push_back_idx {j : \u2115} {n : \u2115} (h\u2081 : j < n + 1) (h\u2082 : j \u2260 n) : j < n :=\n  nat.lt_of_le_and_ne (nat.le_of_lt_succ h\u2081) h\u2082\n\n/-- `push_back a v` pushes value `v` to the end of the array. Has builtin VM implementation. -/\ndef push_back {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (v : \u03b1) : array (n + 1) \u03b1 :=\n  d_array.mk fun (_x : fin (n + 1)) => sorry\n\ntheorem pop_back_idx {j : \u2115} {n : \u2115} (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 : \u2115} {\u03b1 : Type u} (a : array (n + 1) \u03b1) : array n \u03b1 :=\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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (a : array n \u03b1) (f : \u03b1 \u2192 m \u03b2) (i : \u2115) (H : i \u2264 n) : m (array i \u03b2) :=\n  sorry\n\n/-- Monadically map a function over the array. -/\ndef mmap {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type u_1} [Monad m] (a : array n \u03b1) (f : \u03b1 \u2192 m \u03b2) : m (array n \u03b2) :=\n  mmap_core a f n sorry\n\n/-- Map a function over the array. -/\ndef map {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (f : \u03b1 \u2192 \u03b2) : array n \u03b2 :=\n  d_array.map (fun (_x : fin n) => f) a\n\nprotected def mem {n : \u2115} {\u03b1 : Type u} (v : \u03b1) (a : array n \u03b1) :=\n  \u2203 (i : fin n), read a i = v\n\nprotected instance has_mem {n : \u2115} {\u03b1 : Type u} : has_mem \u03b1 (array n \u03b1) :=\n  has_mem.mk array.mem\n\ntheorem read_mem {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) : read a i \u2208 a :=\n  exists.intro i rfl\n\nprotected instance has_repr {n : \u2115} {\u03b1 : Type u} [has_repr \u03b1] : has_repr (array n \u03b1) :=\n  has_repr.mk (repr \u2218 to_list)\n\n@[simp] theorem read_write {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) (v : \u03b1) : read (write a i v) i = v :=\n  d_array.read_write a i v\n\n@[simp] theorem read_write_of_ne {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) {i : fin n} {j : fin n} (v : \u03b1) : i \u2260 j \u2192 read (write a i v) j = read a j :=\n  d_array.read_write_of_ne a v\n\ndef read' {n : \u2115} {\u03b2 : Type v} [Inhabited \u03b2] (a : array n \u03b2) (i : \u2115) : \u03b2 :=\n  dite (i < n) (fun (h : i < n) => read a { val := i, property := h }) fun (h : \u00aci < n) => Inhabited.default\n\ndef write' {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : \u2115) (v : \u03b1) : array n \u03b1 :=\n  dite (i < n) (fun (h : i < n) => write a { val := i, property := h } v) fun (h : \u00aci < n) => a\n\ntheorem read_eq_read' {n : \u2115} {\u03b1 : Type u} [Inhabited \u03b1] (a : array n \u03b1) {i : \u2115} (h : i < n) : read a { val := i, property := h } = read' a i := sorry\n\ntheorem write_eq_write' {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) {i : \u2115} (h : i < n) (v : \u03b1) : write a { val := i, property := h } v = write' a i v := sorry\n\nprotected theorem ext {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {b : array n \u03b1} (h : \u2200 (i : fin n), read a i = read b i) : a = b :=\n  d_array.ext h\n\nprotected theorem ext' {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {b : array n \u03b1} (h : \u2200 (i : \u2115) (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 : \u2115} {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (array n \u03b1) :=\n  eq.mpr sorry fun (a b : d_array n fun (_x : fin n) => \u03b1) => 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 \u27f6 Y)\n\n/-- A morphism is `affine` if the preimages of affine open sets are affine. -/\n@[mk_iff]\nclass affine (f : X \u27f6 Y) : Prop :=\n(is_affine_preimage : \u2200 U : opens Y.carrier,\n  is_affine_open U \u2192 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\u03bb X Y f hf, is_affine X\n\n@[simp] lemma affine_affine_property_to_property {X Y : Scheme} (f : X \u27f6 Y) :\n  affine_target_morphism_property.to_property affine.affine_property f \u2194\n    is_affine Y \u2227 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 \u27f6 Y) [is_iso f] : affine f :=\n\u27e8\u03bb U hU, hU.map_is_iso f\u27e9\n\n@[priority 100]\ninstance affine.to_quasi_compact [affine f] : quasi_compact f :=\n(quasi_compact_iff_forall_affine f).mpr (\u03bb U hU, (affine.is_affine_preimage U hU).is_compact)\n\ninstance affine_comp {X Y Z : Scheme} (f : X \u27f6 Y) (g : Y \u27f6 Z)\n  [affine f] [affine g] : affine (f \u226b 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 \u2194 target_affine_locally affine.affine_property f :=\n(affine_iff f).trans \u27e8\u03bb H U, H U U.prop, \u03bb H U hU, H \u27e8U, hU\u27e9\u27e9\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 \u22a4)) :\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 \u27f6 Y) [affine f] (U : Y.affine_opens) :\n  X.affine_opens :=\n\u27e8(opens.map f.1.base).obj (U : opens Y.carrier), affine.is_affine_preimage _ U.prop\u27e9\n\nlemma is_affine_of_span_top_of_is_affine_open (X : Scheme) (s : set (X.presheaf.obj $ op \u22a4))\n  (h\u2081 : ideal.span s = \u22a4) (h\u2082 : \u2200 r : s, is_affine_open (X.basic_open r.1)) : is_affine X :=\nbegin\n  haveI hX' : quasi_separated_space X.carrier,\n  { obtain \u27e8s', hs', e\u27e9 := (ideal.span_eq_top_iff_finite _).mp h\u2081,\n    rw quasi_separated_space_iff_affine,\n    intros U V,\n    rw [\u2190 set.inter_univ (U \u2229 V : set X.carrier), \u2190 (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 \u2293 (X.basic_open i.val)) \u2293 (V.1 \u2293 (X.basic_open i.val))).1,\n    { conv_rhs { rw [inf_assoc, \u2190 @inf_assoc _ _ (X.basic_open i.1),\n        @inf_comm _ _ (X.basic_open i.1), inf_assoc, inf_idem, \u2190 inf_assoc] },\n      refl },\n    have : \u2200 (S : opens X.carrier), S \u2293 X.basic_open i.1 = X.basic_open\n      (X.presheaf.map (hom_of_le le_top : S \u27f6 _).op i.1) := \u03bb S, (X.basic_open_res _ _).symm,\n    apply (h\u2082 \u27e8i.1, hs' i.2\u27e9).is_quasi_separated,\n    { exact @inf_le_right _ _ U.1 _ },\n    { exact (U.val \u2293 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 \u2293 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 \u27e8s', hs', e\u27e9 := (ideal.span_eq_top_iff_finite _).mp h\u2081,\n    rw [\u2190 is_compact_univ_iff, \u2190 (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\u2082 \u27e8i.1, hs' i.2\u27e9).is_compact },\n  constructor,\n  rw (is_iso.open_cover_tfae (\u0393_Spec.adjunction.unit.app X)).out 0 5,\n  refine \u27e8s, \u03bb i, prime_spectrum.basic_open i.1, _, _\u27e9,\n  { rw prime_spectrum.Union_basic_open_eq_top_iff, convert h\u2081, 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\u2082 r },\n    { change is_affine_open _,\n      rw \u2190 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 : \u2200 (U = prime_spectrum.basic_open r.val),\n        is_iso ((\u0393_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 (\u0393_Spec.adjunction.unit.app X).val.base).obj _ \u27f6 _).op },\n      { apply structure_sheaf.is_localization.to_basic_open },\n      { dsimp,\n        rw \u2190 is_compact_univ_iff at hX,\n        rw \u2190 is_quasi_separated_univ_iff at hX',\n        convert is_localization_basic_open_of_qcqs\n          (show is_compact (\u22a4 : opens _).1, from hX) hX' r.1;\n          apply \u0393_Spec.adjunction.unit_app_map_basic_open },\n      { rw [ring_hom.algebra_map_to_algebra, ring_hom.algebra_map_to_algebra,\n          \u0393_Spec.adjunction_unit_app],\n        exact X.1.to_\u0393_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 \u22a4)) at hS,\n    rw [ideal.map_span, ideal.map_top] at hS,\n    delta affine.affine_property,\n    unfreezingI { change \u2200 (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 \u27e8_, r, hr, rfl\u27e9,\n    exact hS' \u27e8r, hr\u27e9 }\nend\n\nlemma affine_is_local_at_target :\n  property_is_local_at_target @affine :=\naffine_eq_affine_property.symm \u25b8\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 \u22a2,\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 \u25b8\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\u03bb X Y Z f g hf hg, by exactI infer_instance\n  \nlemma affine_over_affine_iff {X Y : Scheme} (f : X \u27f6 Y) [is_affine Y] :\n  affine f \u2194 is_affine X :=\naffine_eq_affine_property.symm \u25b8\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 \u2190 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": "import Lean.Parser.Command\n\nopen Lean Parser Command\n\nnamespace Papyrus.Internal\n\ndef mkSealedEnumReprInst (ty : Syntax) (ctors : Array Syntax) : MacroM Syntax := do\n  let currNamespace \u2190 Macro.getCurrNamespace\n  let ctorFmts \u2190 ctors.mapM fun ctor =>\n    `(Std.format $(quote <| toString (currNamespace ++ ctor[2].getId)))\n  `(def reprFormats : Array Std.Format := #[$[$ctorFmts],*]\n    instance : Repr $ty := \u27e8fun e _ => reprFormats[e.val.val]\u27e9)\n\ndef unpackOptDeriving : (stx : Syntax) \u2192 (Array Syntax \u00d7 Array (Option Syntax))\n| `(optDeriving| deriving $[$clss $[with $argss?]?],*) => (clss, argss?)\n| _ => (#[], #[])\n\n\nset_option hygiene false\n\n--------------------------------------------------------------------------------\n-- # Open Enums\n--------------------------------------------------------------------------------\n\nsyntax enumCtor := \"\\n| \" declModifiers ident \" := \" term\n\nscoped macro (name := enumDecl)\n  mods:declModifiers\n  \"enum \" id:ident \" : \" type:term optional(\" := \" <|> \" where \")\n  ctors:many(enumCtor)\n  deriv?:optDeriving\n: command => do\n  let mut defs : Array Syntax := #[]\n  -- structure\n  defs := defs.push <| \u2190\n    `($mods:declModifiers\n      structure $id where\n        val : $type\n        $deriv?:optDeriving)\n  -- constructors\n  for ctor in ctors do\n    let ctorId := ctor[2]\n    let ctorQualId := mkIdentFrom ctorId <|\n      id.getId.modifyBase (\u00b7 ++ ctorId.getId)\n    let ctorVal := ctor[4]\n    let ctorMods := ctor[1]\n    defs := defs.push <| \u2190\n      `($ctorMods:declModifiers def $ctorQualId:ident : $id := mk $ctorVal)\n  mkNullNode defs\n\n--------------------------------------------------------------------------------\n-- # Sealed Enums\n--------------------------------------------------------------------------------\n\nsyntax identCtor := \"\\n| \" declModifiers ident\n\nscoped macro (name := sealedEnumDecl)\n  mods:declModifiers\n  \"sealed-enum \" id:ident \" : \" type:term optional(\" := \" <|> \" where \")\n  ctors:many(identCtor)\n  deriv?:optDeriving\n: command => do\n  let mut innerDefs := #[]\n  let numCtors := ctors.size\n  let maxValLit := quote (numCtors - 1)\n  -- filter out special deriving instances\n  let mut derivBEq := false\n  let mut derivDecEq := false\n  let mut derivInhabited := false\n  let mut derivRepr := false\n  let mut remClasses := #[]\n  let mut remArgss? := #[]\n  let (classes, argss?) := unpackOptDeriving deriv?\n  for cls in classes, args? in argss? do\n    if cls.matchesIdent ``BEq then\n      derivBEq := true\n    else if cls.matchesIdent ``DecidableEq then\n      derivDecEq := true\n    else if cls.matchesIdent ``Inhabited then\n      derivInhabited := true\n    else if cls.matchesIdent ``Repr then\n      derivRepr := true\n    else\n      remClasses := remClasses.push cls\n      remArgss? := remArgss?.push args?\n  -- structure\n  let structDecl \u2190\n    `($mods:declModifiers\n      structure $id where\n        val : $type\n        h : val \u2264 $maxValLit\n        deriving $[$remClasses $[with $remArgss?]?],*)\n  -- maximum\n  innerDefs := innerDefs.push <| \u2190\n    `(def maxVal : $type := $maxValLit)\n  -- theorems\n  innerDefs := innerDefs.push <| \u2190\n    `(theorem eq_of_val_eq : {a b : $id} \u2192 a.val = b.val \u2192 a = b\n        | \u27e8v, h\u27e9, \u27e8_, _\u27e9, rfl => rfl\n      theorem val_eq_of_eq {a b : $id} (h : a = b) : a.val = b.val :=\n        h \u25b8 rfl\n      theorem ne_of_val_ne {a b : $id} (h : a.val \u2260 b.val) : a \u2260 b :=\n        fun h' => absurd (val_eq_of_eq h') h)\n  -- constructors\n  for ctor in ctors, i in [:numCtors] do\n    let ctorVal := quote i\n    let ctorMods := ctor[1]\n    let ctorId := ctor[2]\n    innerDefs := innerDefs.push <| \u2190\n      `($ctorMods:declModifiers def $ctorId:ident : $id := mk $ctorVal (by decide))\n  -- derive special instance\n  if derivBEq then\n    innerDefs := innerDefs.push <| \u2190\n      `(instance : BEq $id := \u27e8fun a b => a.val == b.val\u27e9)\n  if derivDecEq then\n    innerDefs := innerDefs.push <| \u2190\n      `(instance : DecidableEq $id := fun a b =>\n          if h : a.val = b.val\n            then isTrue (eq_of_val_eq h)\n            else isFalse (ne_of_val_ne h))\n  if derivInhabited then\n    innerDefs := innerDefs.push <| \u2190\n      `(instance : Inhabited $id := \u27e8mk maxVal (Nat.le_refl _)\u27e9)\n  if derivRepr then\n    innerDefs := innerDefs.push <| \u2190 mkSealedEnumReprInst id ctors\n  -- syntax\n  `($structDecl:command\n    namespace $id:ident\n    $(mkNullNode innerDefs)\n    end $id:ident)\n", "meta": {"author": "tydeu", "repo": "lean4-papyrus", "sha": "02e82973a5badda26fc0f9fd15b3d37e2eb309e0", "save_path": "github-repos/lean/tydeu-lean4-papyrus", "path": "github-repos/lean/tydeu-lean4-papyrus/lean4-papyrus-02e82973a5badda26fc0f9fd15b3d37e2eb309e0/Papyrus/Internal/Enum.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.0474258736824553, "lm_q1q2_score": 0.02003765213067374}}
{"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 : \u2115) (\u03b1 : fin n \u2192 Type u) where\n  data : (i : fin n) \u2192 \u03b1 i\n\nnamespace d_array\n\n\n/-- The empty array. -/\ndef nil {\u03b1 : fin 0 \u2192 Type u_1} : d_array 0 \u03b1 := 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 : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) (i : fin n) : \u03b1 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 : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) (i : fin n) (v : \u03b1 i) : d_array n \u03b1 :=\n  mk fun (j : fin n) => dite (i = j) (fun (h : i = j) => eq.rec_on h v) fun (h : \u00aci = j) => read a j\n\ndef iterate_aux {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1)\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) (i : \u2115) : i \u2264 n \u2192 \u03b2 \u2192 \u03b2 :=\n  sorry\n\n/-- Fold over the elements of the given array in ascending order. Has builtin VM implementation. -/\ndef iterate {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (b : \u03b2)\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  iterate_aux a f n sorry b\n\n/-- Map the array. Has builtin VM implementation. -/\ndef foreach {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b1' : fin n \u2192 Type v} (a : d_array n \u03b1)\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b1' i) : d_array n \u03b1' :=\n  mk fun (i : fin n) => f i (read a i)\n\ndef map {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b1' : fin n \u2192 Type v} (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b1' i)\n    (a : d_array n \u03b1) : d_array n \u03b1' :=\n  foreach a f\n\ndef map\u2082 {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b1' : fin n \u2192 Type v} {\u03b1'' : fin n \u2192 Type w}\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b1' i \u2192 \u03b1'' i) (a : d_array n \u03b1) (b : d_array n \u03b1') : d_array n \u03b1'' :=\n  foreach b fun (i : fin n) => f i (read a i)\n\ndef foldl {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (b : \u03b2)\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  iterate a b f\n\ndef rev_iterate_aux {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1)\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) (i : \u2115) : i \u2264 n \u2192 \u03b2 \u2192 \u03b2 :=\n  sorry\n\ndef rev_iterate {n : \u2115} {\u03b1 : fin n \u2192 Type u} {\u03b2 : Type w} (a : d_array n \u03b1) (b : \u03b2)\n    (f : (i : fin n) \u2192 \u03b1 i \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  rev_iterate_aux a f n sorry b\n\n@[simp] theorem read_write {n : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) (i : fin n) (v : \u03b1 i) :\n    read (write a i v) i = v :=\n  sorry\n\n@[simp] theorem read_write_of_ne {n : \u2115} {\u03b1 : fin n \u2192 Type u} (a : d_array n \u03b1) {i : fin n}\n    {j : fin n} (v : \u03b1 i) : i \u2260 j \u2192 read (write a i v) j = read a j :=\n  sorry\n\nprotected theorem ext {n : \u2115} {\u03b1 : fin n \u2192 Type u} {a : d_array n \u03b1} {b : d_array n \u03b1}\n    (h : \u2200 (i : fin n), read a i = read b i) : a = b :=\n  sorry\n\nprotected theorem ext' {n : \u2115} {\u03b1 : fin n \u2192 Type u} {a : d_array n \u03b1} {b : d_array n \u03b1}\n    (h :\n      \u2200 (i : \u2115) (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 : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)]\n    (a : d_array n \u03b1) (b : d_array n \u03b1) (i : \u2115) : i \u2264 n \u2192 Bool :=\n  sorry\n\n/-- Boolean element-wise equality check. -/\nprotected def beq {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] (a : d_array n \u03b1)\n    (b : d_array n \u03b1) : Bool :=\n  d_array.beq_aux a b n sorry\n\ntheorem of_beq_aux_eq_tt {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)]\n    {a : d_array n \u03b1} {b : d_array n \u03b1} (i : \u2115) (h : i \u2264 n) :\n    d_array.beq_aux a b i h = tt \u2192\n        \u2200 (j : \u2115) (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 : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)]\n    {a : d_array n \u03b1} {b : d_array n \u03b1} : d_array.beq a b = tt \u2192 a = b :=\n  sorry\n\ntheorem of_beq_aux_eq_ff {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)]\n    {a : d_array n \u03b1} {b : d_array n \u03b1} (i : \u2115) (h : i \u2264 n) :\n    d_array.beq_aux a b i h = false \u2192\n        \u2203 (j : \u2115),\n          \u2203 (h' : j < i),\n            read a { val := j, property := lt_of_lt_of_le h' h } \u2260\n              read b { val := j, property := lt_of_lt_of_le h' h } :=\n  sorry\n\ntheorem of_beq_eq_ff {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)]\n    {a : d_array n \u03b1} {b : d_array n \u03b1} : d_array.beq a b = false \u2192 a \u2260 b :=\n  sorry\n\nprotected instance decidable_eq {n : \u2115} {\u03b1 : fin n \u2192 Type u} [(i : fin n) \u2192 DecidableEq (\u03b1 i)] :\n    DecidableEq (d_array n \u03b1) :=\n  fun (a b : d_array n \u03b1) =>\n    dite (d_array.beq a b = tt) (fun (h : d_array.beq a b = tt) => is_true sorry)\n      fun (h : \u00acd_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 : \u2115) (\u03b1 : Type u) := d_array n fun (_x : fin n) => \u03b1\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 {\u03b1 : Type u_1} (n : \u2115) (v : \u03b1) : array n \u03b1 := d_array.mk fun (_x : fin n) => v\n\nnamespace array\n\n\ndef nil {\u03b1 : Type u_1} : array 0 \u03b1 := d_array.nil\n\ndef read {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) : \u03b1 := d_array.read a i\n\ndef write {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) (v : \u03b1) : array n \u03b1 :=\n  d_array.write a i v\n\n/-- Fold array starting from 0, folder function includes an index argument. -/\ndef iterate {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : fin n \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  d_array.iterate a b f\n\n/-- Map each element of the given array with an index argument. -/\ndef foreach {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (f : fin n \u2192 \u03b1 \u2192 \u03b2) : array n \u03b2 :=\n  d_array.foreach a f\n\ndef map\u2082 {n : \u2115} {\u03b1 : Type u} (f : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (a : array n \u03b1) (b : array n \u03b1) : array n \u03b1 :=\n  foreach b fun (i : fin n) => f (read a i)\n\ndef foldl {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  iterate a b fun (_x : fin n) => f\n\ndef rev_list {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) : List \u03b1 :=\n  foldl a [] fun (_x : \u03b1) (_y : List \u03b1) => _x :: _y\n\ndef rev_iterate {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : fin n \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2) :\n    \u03b2 :=\n  d_array.rev_iterate a b f\n\ndef rev_foldl {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) : \u03b2 :=\n  rev_iterate a b fun (_x : fin n) => f\n\ndef to_list {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) : List \u03b1 :=\n  rev_foldl a [] fun (_x : \u03b1) (_y : List \u03b1) => _x :: _y\n\ntheorem push_back_idx {j : \u2115} {n : \u2115} (h\u2081 : j < n + 1) (h\u2082 : j \u2260 n) : j < n :=\n  nat.lt_of_le_and_ne (nat.le_of_lt_succ h\u2081) h\u2082\n\n/-- `push_back a v` pushes value `v` to the end of the array. Has builtin VM implementation. -/\ndef push_back {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (v : \u03b1) : array (n + 1) \u03b1 :=\n  d_array.mk fun (_x : fin (n + 1)) => sorry\n\ntheorem pop_back_idx {j : \u2115} {n : \u2115} (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 : \u2115} {\u03b1 : Type u} (a : array (n + 1) \u03b1) : array n \u03b1 :=\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 : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (a : array n \u03b1)\n    (f : \u03b1 \u2192 m \u03b2) (i : \u2115) (H : i \u2264 n) : m (array i \u03b2) :=\n  sorry\n\n/-- Monadically map a function over the array. -/\ndef mmap {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type u_1} [Monad m] (a : array n \u03b1)\n    (f : \u03b1 \u2192 m \u03b2) : m (array n \u03b2) :=\n  mmap_core a f n sorry\n\n/-- Map a function over the array. -/\ndef map {n : \u2115} {\u03b1 : Type u} {\u03b2 : Type v} (a : array n \u03b1) (f : \u03b1 \u2192 \u03b2) : array n \u03b2 :=\n  d_array.map (fun (_x : fin n) => f) a\n\nprotected def mem {n : \u2115} {\u03b1 : Type u} (v : \u03b1) (a : array n \u03b1) := \u2203 (i : fin n), read a i = v\n\nprotected instance has_mem {n : \u2115} {\u03b1 : Type u} : has_mem \u03b1 (array n \u03b1) := has_mem.mk array.mem\n\ntheorem read_mem {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) : read a i \u2208 a :=\n  exists.intro i rfl\n\nprotected instance has_repr {n : \u2115} {\u03b1 : Type u} [has_repr \u03b1] : has_repr (array n \u03b1) :=\n  has_repr.mk (repr \u2218 to_list)\n\n@[simp] theorem read_write {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : fin n) (v : \u03b1) :\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 : \u2115} {\u03b1 : Type u} (a : array n \u03b1) {i : fin n} {j : fin n}\n    (v : \u03b1) : i \u2260 j \u2192 read (write a i v) j = read a j :=\n  d_array.read_write_of_ne a v\n\ndef read' {n : \u2115} {\u03b2 : Type v} [Inhabited \u03b2] (a : array n \u03b2) (i : \u2115) : \u03b2 :=\n  dite (i < n) (fun (h : i < n) => read a { val := i, property := h })\n    fun (h : \u00aci < n) => Inhabited.default\n\ndef write' {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) (i : \u2115) (v : \u03b1) : array n \u03b1 :=\n  dite (i < n) (fun (h : i < n) => write a { val := i, property := h } v) fun (h : \u00aci < n) => a\n\ntheorem read_eq_read' {n : \u2115} {\u03b1 : Type u} [Inhabited \u03b1] (a : array n \u03b1) {i : \u2115} (h : i < n) :\n    read a { val := i, property := h } = read' a i :=\n  sorry\n\ntheorem write_eq_write' {n : \u2115} {\u03b1 : Type u} (a : array n \u03b1) {i : \u2115} (h : i < n) (v : \u03b1) :\n    write a { val := i, property := h } v = write' a i v :=\n  sorry\n\nprotected theorem ext {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {b : array n \u03b1}\n    (h : \u2200 (i : fin n), read a i = read b i) : a = b :=\n  d_array.ext h\n\nprotected theorem ext' {n : \u2115} {\u03b1 : Type u} {a : array n \u03b1} {b : array n \u03b1}\n    (h :\n      \u2200 (i : \u2115) (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 : \u2115} {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (array n \u03b1) :=\n  eq.mpr sorry fun (a b : d_array n fun (_x : fin n) => \u03b1) => 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": "/-\nCopyright (c) 2021 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.project_dir\n! leanprover-community/mathlib commit 29079ba8bc53a8465448a577eb2fc41932b02301\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\n\n/-!\n\n# Project directory locator\n\nWe use the dummy declaration in this file to locate the project directory of mathlib.\n\n-/\n\n\n/-- This is a dummy declaration that is used to determine the project folder of mathlib, using the\n  tactic `tactic.decl_olean`. This is used in `tactic.get_mathlib_dir`. -/\ntheorem mathlib_dir_locator : True :=\n  trivial\n#align mathlib_dir_locator mathlib_dir_locator\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/ProjectDir.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.07263671037579263, "lm_q1q2_score": 0.019984518065115787}}
{"text": "example (h : x \u2260 true) : (x && y) = false := by\n  simp [h]\n\nexample (h : \u00ac (x = true)) : (x && y) = false := by\n  simp [h]\n\nexample (h : x \u2260 false) : (x && y) = y := by\n  simp [h]\n\nexample (h : \u00ac (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": "example : Nat \u2192 Nat := by\n  refine' (fun x => _)\n  trace_state\n  sorry\n\nexample : Nat \u2192 Nat := by\n  refine' (fun x => ?_)\n  trace_state\n  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/1681.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.05665242291888883, "lm_q1q2_score": 0.01995308430936335}}
{"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 \u2190  \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 \u2190 s\n      let expr0 \u2190  elabTerm s0 (some (Lean.mkConst `Nat)) \n      let name2 : Name := `Nat.succ\n      let expr : Expr \u2190  \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 \u2190 getEnv\n    IO.println s!\"{env.contains ``succ}\"\n    IO.println s!\"{env.contains `succ}\"\n    let decls \u2190 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 \u2190 `(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 \u2190 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  \u2190 isTypeCorrect expr\n      -- let cc \u2190 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 \u2190 shiftnat n e\n    return \u2190 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 \u2190  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  : {\u03b1 : Type} \u2192 (a: \u03b1 ) \u2192 Someterm\n  | nothing : Someterm\n\ndef Someterm.isEmpty : Someterm \u2192 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 \u2190  mkApp f x\n        let c \u2190  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 {\u03b1 \u03b2 \u03b3 : Type} (f : \u03b1 \u2192 \u03b2) (x : \u03b3)  :=\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 \u2190  (mkAppM n #[e2])\n    return \u2190 (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 \u2190 elabTerm t none\n        let z <- elabTerm u none\n        let expr : Expr \u2190  withLetDecl n type f fun x => do\n                              let b \u2190  (mkAppM n #[z])\n                              return \u2190 (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 \u2192 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 : {\u03b1 : Type} \u2192 (a: \u03b1 ) \u2192 WrapTerm\n  | wrapName : Name \u2192 WrapTerm\n  | wrapExpr : Array Expr \u2192 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 \u2192 Type := by\n  intro n\n  induction n with\n  | zero => \n    exact Nat\n  | succ k ih =>\n    exact Nat \u00d7 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 {\u03b1 \u03b2 : Type} (a: \u03b1) : (\u03b1 \u2192 \u03b2) \u2192 \u03b2  := \n    fun f => f a\n\ndef asPi {\u03b1 : Type}{motive : \u03b1 \u2192 Type} (a: \u03b1) : \n      ((x : \u03b1) \u2192 motive x) \u2192 motive a :=\n        fun f => f a    \n\ndef natGen : Nat := by\n    apply (asFunc 3)\n    exact Nat.succ\n\ndef piFactorizer (\u03b1 : Type)(motive : \u03b1 \u2192 Type) : Type :=\n    (a: \u03b1 ) \u2192 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 \u00d7 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 := \u03a3 A : Type, A\n\ndef WithType.mk (\u03b1 : Type) (a : \u03b1) : WithType := \u27e8\u03b1 , a\u27e9\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  \u2190 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 \u2190 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 (\u03b1 : Type)(a: \u03b1)(ts: ToString \u03b1) : 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 \u2190  inferType e\n    let tst \u2190 mkAppM ``ToString #[tp]\n    let ts \u2190 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 \u2190 mkAppM ``ToString.toString #[t] \n      let v \u2190 -- mkAppN tts #[e]\n         mkAppM ``explicitToString #[tp, e, t]\n      return \u2190 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 \u2190 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{\u03b1 : Type}{f: Nat \u2192 \u03b1}:\n        (\u2200 n: Nat, f n = f (succ n)) \u2192  (\u2200 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 [\u2190 ih]\n             apply Eq.symm\n             apply hyp\n\ntheorem constfuncGen{\u03b1 : Type}{f: Nat \u2192 \u03b1}:\n        (\u2200 n: Nat, f n = f (succ n)) \u2192  \n          (\u2203 c : \u03b1, \u2200 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 [\u2190 ih]\n             apply Eq.symm\n             apply hyp \n\ndef mvarMeta : MetaM Expr := do\n  let mvar \u2190 mkFreshExprMVar (some (mkConst ``Nat))\n  let mvarId := mvar.mvarId!\n  let mvar2 \u2190 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 \u2190 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 \u2192 Nat) (arg: Name) : MetaM Expr := \n  do\n    let lctx \u2190 getLCtx\n    match (\u2190 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 \u2190 getLCtx\n    let e \u2190 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 \u2190 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\u2081 c\u2082 : CtorInfo) : Bool :=\n  c\u2081.size == c\u2082.size && c\u2081.usize == c\u2082.usize && c\u2081.ssize == c\u2082.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\u2081.name.getPrefix == c\u2082.name.getPrefix\n\nprivate partial def S (w : VarId) (c : CtorInfo) : FnBody \u2192 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 \u2190 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 \u2190 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 \u00d7 Bool \u2192 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 \u2192 M (FnBody \u00d7 Bool)\n  | e@(FnBody.case tid y yType alts) => do\n    let ctx \u2190 read\n    if e.hasLiveVar ctx x then do\n      /- If `x` is live in `e`, we recursively process each branch. -/\n      let alts \u2190 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) \u2190 withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b)\n    let (v, _ /- found' -/) \u2190 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 \u2190 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) \u2190 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 \u2190 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 \u2192 M FnBody\n  | FnBody.case tid x xType alts   => do\n      let alts \u2190 alts.mapM fun alt => do\n        let alt \u2190 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 \u2190 R v\n    let b \u2190 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 \u2190 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) 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.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Util.CollectMVars\nimport Lean.Meta.Basic\n\nnamespace Lean.Meta\n\n/--\n  Data for user-defined theorems marked with the `congr` attribute.\n\n  This type should be confused with `CongrTheorem` which reprents different kinds of automatically\n  generated congruence theorems. The `simp` tactic also uses some of them.\n-/\nstructure SimpCongrTheorem where\n  theoremName   : Name\n  funName       : Name\n  hypothesesPos : Array Nat\n  priority      : Nat\nderiving Inhabited, Repr\n\nstructure SimpCongrTheorems where\n  lemmas : SMap Name (List SimpCongrTheorem) := {}\n  deriving Inhabited, Repr\n\ndef SimpCongrTheorems.get (d : SimpCongrTheorems) (declName : Name) : List SimpCongrTheorem :=\n  match d.lemmas.find? declName with\n  | none    => []\n  | some cs => cs\n\ndef addSimpCongrTheoremEntry (d : SimpCongrTheorems) (e : SimpCongrTheorem) : SimpCongrTheorems :=\n  { d with lemmas :=\n      match d.lemmas.find? e.funName with\n      | none    => d.lemmas.insert e.funName [e]\n      | some es => d.lemmas.insert e.funName <| insert es }\nwhere\n  insert : List SimpCongrTheorem \u2192 List SimpCongrTheorem\n    | []     => [e]\n    | e'::es => if e.priority \u2265 e'.priority then e::e'::es else e' :: insert es\n\nbuiltin_initialize congrExtension : SimpleScopedEnvExtension SimpCongrTheorem SimpCongrTheorems \u2190\n  registerSimpleScopedEnvExtension {\n    initial        := {}\n    addEntry       := addSimpCongrTheoremEntry\n    finalizeImport := fun s => { s with lemmas := s.lemmas.switch }\n  }\n\ndef mkSimpCongrTheorem (declName : Name) (prio : Nat) : MetaM SimpCongrTheorem := withReducible do\n  let c \u2190 mkConstWithLevelParams declName\n  let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType c)\n  match type.eqOrIff? with\n  | none => throwError \"invalid 'congr' theorem, equality expected{indentExpr type}\"\n  | some (lhs, rhs) =>\n    lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do\n      unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do\n        throwError \"invalid 'congr' theorem, equality left/right-hand sides must be applications of the same function{indentExpr type}\"\n      let mut foundMVars : MVarIdSet := {}\n      for lhsArg in lhsArgs do\n        for mvarId in (lhsArg.collectMVars {}).result do\n          foundMVars := foundMVars.insert mvarId\n      let mut i := 0\n      let mut hypothesesPos := #[]\n      for x in xs, bi in bis do\n        if bi.isExplicit && !foundMVars.contains x.mvarId! then\n          let rhsFn? \u2190 forallTelescopeReducing (\u2190 inferType x) fun ys xType => do\n            match xType.eqOrIff? with\n            | none => pure none -- skip\n            | some (xLhs, xRhs) =>\n              let mut j := 0\n              for y in ys do\n                let yType \u2190 inferType y\n                unless onlyMVarsAt yType foundMVars do\n                  throwError \"invalid 'congr' theorem, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}\"\n                j := j + 1\n              unless onlyMVarsAt xLhs foundMVars do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}\"\n              let xRhsFn := xRhs.getAppFn\n              unless xRhsFn.isMVar do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}\"\n              unless !foundMVars.contains xRhsFn.mvarId! do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}\"\n              for arg in xRhs.getAppArgs do\n                unless arg.isFVar do\n                  throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}\"\n              pure (some xRhsFn)\n          match rhsFn? with\n          | none       => pure ()\n          | some rhsFn =>\n            foundMVars    := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId!\n            hypothesesPos := hypothesesPos.push i\n        i := i + 1\n      return {\n        theoremName   := declName\n        funName       := lhsFn.constName!\n        hypothesesPos := hypothesesPos\n        priority      := prio\n      }\nwhere\n  /-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/\n  onlyMVarsAt (t : Expr) (mvarSet : MVarIdSet) : Bool :=\n    Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId!\n\ndef addSimpCongrTheorem (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n  let lemma \u2190 mkSimpCongrTheorem declName prio\n  congrExtension.add lemma attrKind\n\nbuiltin_initialize\n  registerBuiltinAttribute {\n    name  := `congr\n    descr := \"congruence theorem\"\n    add   := fun declName stx attrKind => do\n      let prio \u2190 getAttrParamOptPrio stx[1]\n      discard <| addSimpCongrTheorem declName attrKind prio |>.run {} {}\n  }\n\ndef getSimpCongrTheorems : MetaM SimpCongrTheorems :=\n  return congrExtension.getState (\u2190 getEnv)\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/Simp/SimpCongrTheorems.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.04468086534327484, "lm_q1q2_score": 0.019906645161555}}
{"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   => \"<unknown>\"\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\u2081 e\u2082 := e\u2081.proof == e\u2082.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 \u2192 SimpEntry\n  | toUnfold : Name \u2192 SimpEntry\n  deriving Inhabited\n\nbuiltin_initialize simpExtension : SimpleScopedEnvExtension SimpEntry SimpLemmas \u2190\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 \u2192 Expr \u2192 MetaM Bool\n  | Expr.app f\u2081 a\u2081 _, Expr.app f\u2082 a\u2082 _ => isPerm f\u2081 f\u2082 <&&> isPerm a\u2081 a\u2082\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\u2081 d\u2081 b\u2081 _, Expr.forallE n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.lam n\u2081 d\u2081 b\u2081 _, Expr.lam n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.letE n\u2081 t\u2081 v\u2081 b\u2081 _, Expr.letE n\u2082 t\u2082 v\u2082 b\u2082 _ =>\n    isPerm t\u2081 t\u2082 <&&> isPerm v\u2081 v\u2082 <&&> withLetDecl n\u2081 t\u2081 v\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.proj _ i\u2081 b\u2081 _, Expr.proj _ i\u2082 b\u2082 _ => i\u2081 == i\u2082 <&&> isPerm b\u2081 b\u2082\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 \u00d7 Expr)) := do\n  let type \u2190 whnf type\n  if type.isForall then\n    forallTelescopeReducing type fun xs type => do\n      let e := mkAppN e xs\n      let ps \u2190 preprocess e type\n      ps.mapM fun (e, type) =>\n        return (\u2190 mkLambdaFVars xs e, \u2190 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 \u2190 mkEq lhs rhs\n    let e    \u2190 mkPropExt e\n    return [(e, type)]\n  else if let some (_, lhs, rhs) := type.ne? then\n    let type \u2190 mkEq (\u2190 mkEq lhs rhs) (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some p := type.not? then\n    let type \u2190 mkEq p (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some (type\u2081, type\u2082) := type.and? then\n    let e\u2081 := mkProj ``And 0 e\n    let e\u2082 := mkProj ``And 1 e\n    return (\u2190 preprocess e\u2081 type\u2081) ++ (\u2190 preprocess e\u2082 type\u2082)\n  else\n    let type \u2190 mkEq type (mkConst ``True)\n    let e    \u2190 mkEqTrue e\n    return [(e, type)]\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n  unless (\u2190 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 \u2190 instantiateMVars (\u2190 inferType e)\n  withNewMCtxDepth do\n    let (xs, _, type) \u2190 withReducible <| forallMetaTelescopeReducing type\n    let type \u2190 whnfR type\n    let (keys, perm) \u2190\n      match type.eq? with\n      | some (_, lhs, rhs) => pure (\u2190 DiscrTree.mkPath lhs, \u2190 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 \u2190 getConstInfo declName\n  let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n  withReducible do\n    let type \u2190 inferType val\n    checkTypeIsProp type\n    if (\u2190 shouldPreprocess type) then\n      let mut r := #[]\n      for (val, type) in (\u2190 preprocess val type) do\n        let auxName \u2190 mkAuxLemma cinfo.levelParams type val\n        r := r.push <| (\u2190 mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n      return r\n    else\n      #[\u2190 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 \u2190 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 \u2190 getConstInfo declName\n        if (\u2190 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 \u2190 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 \u2190 simpExtension.getState (\u2190 getEnv)\n      let s \u2190 s.erase declName\n      modifyEnv fun env => simpExtension.modifyState env fun _ => s\n  }\n\ndef getSimpLemmas : MetaM SimpLemmas :=\n  return simpExtension.getState (\u2190 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 \u2190 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 \u2190 getConstInfo simpLemma.proof.constName!\n    if info.levelParams.isEmpty then\n      return simpLemma.proof\n    else\n      return simpLemma.proof.updateConst! (\u2190 info.levelParams.mapM (fun _ => mkFreshLevelMVar))\n  else\n    let us \u2190 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 \u2190 inferType val\n  checkTypeIsProp type\n  let ps \u2190 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    (\u2190 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 \u2190 mkSimpLemmas levelParams proof post prio (\u2190 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 \u2190 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 : \u03b1 \u2192 \u03b1) (a b : \u03b1) (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) 2021 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: 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 \u03b1` data structure is\nthe most generic version we define.\nIt is created using `Cache.mk f`\nwhere `f : MetaM \u03b1` performs\nthe initialization of the cache:\n```\ninitialize numberOfImports : Cache Nat \u2190 Cache.mk do\n  (\u2190 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 \u03b1` data structure computes\na fold over the environment's constants:\n`DeclCache.mk empty f` constructs such a cache\nwhere `empty : \u03b1` and `f : Name \u2192 ConstantInfo \u2192 \u03b1 \u2192 MetaM \u03b1`.\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 Tactic\n\n/-- Once-per-file cache. -/\ndef Cache (\u03b1 : Type) :=\n  IO.Ref <| Sum (MetaM \u03b1) <|\n    Task <| Except Exception \u03b1\n\ninstance : Nonempty (Cache \u03b1) :=\n  inferInstanceAs <| Nonempty (IO.Ref _)\n\n/-- Creates a cache with an initialization function. -/\ndef Cache.mk (init : MetaM \u03b1) : IO (Cache \u03b1) :=\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] [MonadOptions m] [MonadLiftT BaseIO m] [MonadExcept Exception m]\n    (cache : Cache \u03b1) : m \u03b1 := do\n  let t \u2190 match \u2190 show BaseIO _ from ST.Ref.get cache with\n    | Sum.inr t => pure t\n    | Sum.inl init =>\n      let env \u2190 getEnv\n      let options \u2190 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 \u2190 EIO.asTask do\n        let metaCtx : Meta.Context := {}\n        let metaState : Meta.State := {}\n        let coreCtx : Core.Context := {options}\n        let coreState : Core.State := {env}\n        pure (\u2190 ((init \u2039_\u203a).run \u2039_\u203a \u2039_\u203a).run \u2039_\u203a).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 `\u03b1` for every constant.\n-/\ndef DeclCache (\u03b1 : Type) :=\n  Cache \u03b1 \u00d7 (Name \u2192 ConstantInfo \u2192 \u03b1 \u2192 MetaM \u03b1)\n\ninstance : Nonempty (DeclCache \u03b1) :=\n  inferInstanceAs <| Nonempty (_ \u00d7 _)\n\n/--\nCreates a `DeclCache`.\nThe cached structure `\u03b1` 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 : \u03b1) (addDecl : Name \u2192 ConstantInfo \u2192 \u03b1 \u2192 MetaM \u03b1) : IO (DeclCache \u03b1) := do\n  let cache \u2190 Cache.mk do\n    profileitM Exception profilingName (\u2190 getOptions) do\n    let mut a := empty\n    for (n, c) in (\u2190 getEnv).constants.map\u2081.toList do\n      a \u2190 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 \u03b1) : MetaM \u03b1 := do\n  let mut a \u2190 cache.1.get\n  for (n, c) in (\u2190 getEnv).constants.map\u2082.toList do\n    a \u2190 cache.2 n c a\n  return a\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/Cache.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592736, "lm_q2_score": 0.09138210306717134, "lm_q1q2_score": 0.01986076067519698}}
{"text": "/-\nCopyright (c) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn\n\n! This file was ported from Lean 3 source module meta.expr\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.Option.Defs\nimport Mathbin.Data.String.Defs\nimport Mathbin.Tactic.DeriveInhabited\n\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\n\nopen Tactic\n\nderiving instance has_reflect, DecidableEq for BinderInfo, CongrArgKind\n\nnamespace BinderInfo\n\n/-! ### Declarations about `binder_info` -/\n\n\ninstance : Inhabited BinderInfo :=\n  \u27e8BinderInfo.default\u27e9\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : BinderInfo \u2192 String \u00d7 String\n  | BinderInfo.implicit => (\"{\", \"}\")\n  | BinderInfo.strict_implicit => (\"{{\", \"}}\")\n  | BinderInfo.inst_implicit => (\"[\", \"]\")\n  | _ => (\"(\", \")\")\n#align binder_info.brackets BinderInfo.brackets\n\nend BinderInfo\n\nnamespace Name\n\n/-! ### Declarations about `name` -/\n\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef mapPrefix (f : Name \u2192 Option Name) : Name \u2192 Name\n  | anonymous => anonymous\n  | mk_string s n' => (f (mk_string s n')).getD (mk_string s <| map_prefix n')\n  | mk_numeral d n' => (f (mk_numeral d n')).getD (mk_numeral d <| map_prefix n')\n#align name.map_prefix Name.mapPrefix\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\nunsafe def deinternalize_field : Name \u2192 Name\n  | mk_string s Name.anonymous =>\n    let i := s.mkIterator\n    if i.curr = '_' then i.next.nextToString else s\n  | n => n\n#align name.deinternalize_field name.deinternalize_field\n\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\nunsafe def get_nth_prefix : Name \u2192 \u2115 \u2192 Name\n  | nm, 0 => nm\n  | nm, n + 1 => get_nth_prefix nm.getPrefix n\n#align name.get_nth_prefix name.get_nth_prefix\n\n/-- Auxiliary definition for `pop_nth_prefix` -/\nprivate unsafe def pop_nth_prefix_aux : Name \u2192 \u2115 \u2192 Name \u00d7 \u2115\n  | anonymous, n => (anonymous, 1)\n  | nm, n =>\n    let (pfx, height) := pop_nth_prefix_aux nm.getPrefix n\n    if height \u2264 n then (anonymous, height + 1) else (nm.updatePrefix pfx, height + 1)\n#align name.pop_nth_prefix_aux name.pop_nth_prefix_aux\n\n/-- Pops the top `n` prefixes from the given name. -/\nunsafe def pop_nth_prefix (nm : Name) (n : \u2115) : Name :=\n  Prod.fst <| pop_nth_prefix_aux nm n\n#align name.pop_nth_prefix name.pop_nth_prefix\n\n/-- Pop the prefix of a name -/\nunsafe def pop_prefix (n : Name) : Name :=\n  pop_nth_prefix n 1\n#align name.pop_prefix name.pop_prefix\n\n/-- Auxiliary definition for `from_components` -/\nprivate def from_components_aux : Name \u2192 List String \u2192 Name\n  | n, [] => n\n  | n, s :: rest => from_components_aux (Name.mk_string s n) rest\n#align name.from_components_aux name.from_components_aux\n\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef fromComponents : List String \u2192 Name :=\n  fromComponentsAux Name.anonymous\n#align name.from_components Name.fromComponents\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\nunsafe def sanitize_name : Name \u2192 Name\n  | Name.anonymous => Name.anonymous\n  | Name.mk_string s p => Name.mk_string s <| sanitize_name p\n  | Name.mk_numeral s p => (Name.mk_string s! \"n{s}\") <| sanitize_name p\n#align name.sanitize_name name.sanitize_name\n\n/-- Append a string to the last component of a name. -/\ndef appendSuffix : Name \u2192 String \u2192 Name\n  | mk_string s n, s' => mk_string (s ++ s') n\n  | n, _ => n\n#align name.append_suffix Name.appendSuffix\n\n/-- Update the last component of a name. -/\ndef updateLast (f : String \u2192 String) : Name \u2192 Name\n  | mk_string s n => mk_string (f s) n\n  | n => n\n#align name.update_last Name.updateLast\n\n/-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`,\n  either as prefix or as suffix (specified by `is_prefix`), separated by `_`.\n  Used by `simps_add_projections`. -/\ndef appendToLast (nm : Name) (s : String) (is_prefix : Bool) : Name :=\n  nm.updateLast fun s' => if is_prefix then s ++ \"_\" ++ s' else s' ++ \"_\" ++ s\n#align name.append_to_last Name.appendToLast\n\n/-- The first component of a name, turning a number to a string -/\nunsafe def head : Name \u2192 String\n  | mk_string s anonymous => s\n  | mk_string s p => head p\n  | mk_numeral n p => head p\n  | anonymous => \"[anonymous]\"\n#align name.head name.head\n\n/-- Tests whether the first component of a name is `\"_private\"` -/\nunsafe def is_private (n : Name) : Bool :=\n  n.headI = \"_private\"\n#align name.is_private name.is_private\n\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\nunsafe def length : Name \u2192 \u2115\n  | mk_string s anonymous => s.length\n  | mk_string s p => s.length + 1 + p.length\n  | mk_numeral n p => p.length\n  | anonymous => \"[anonymous]\".length\n#align name.length name.length\n\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef hasPrefix (P : Name \u2192 Bool) : Name \u2192 Bool\n  | anonymous => false\n  | mk_string s nm => P (mk_string s nm) \u2228 has_prefix nm\n  | mk_numeral s nm => P (mk_numeral s nm) \u2228 has_prefix nm\n#align name.has_prefix Name.hasPrefix\n\n/-- Appends `'` to the end of a name. -/\nunsafe def add_prime : Name \u2192 Name\n  | Name.mk_string s p => Name.mk_string (s ++ \"'\") p\n  | n => Name.mk_string \"x'\" n\n#align name.add_prime name.add_prime\n\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef lastString : Name \u2192 String\n  | anonymous => \"[anonymous]\"\n  | mk_string s _ => s\n  | mk_numeral _ n => last_string n\n#align name.last_string Name.lastString\n\n/-- Like `++`, except that if the right argument starts with `_root_` the namespace will be\nignored.\n```\nappend_namespace `a.b `c.d = `a.b.c.d\nappend_namespace `a.b `_root_.c.d = `c.d\n```\n-/\nunsafe def append_namespace (ns : Name) : Name \u2192 Name\n  | mk_string s anonymous => if s = \"_root_\" then anonymous else mk_string s ns\n  | mk_string s p => mk_string s (append_namespace p)\n  | mk_numeral n p => mk_numeral n (append_namespace p)\n  | anonymous => ns\n#align name.append_namespace name.append_namespace\n\n/-- Constructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\nunsafe def from_string (s : String) : Name :=\n  fromComponents <| s.split (\u00b7 = '.')\n#align name.from_string name.from_string\n\nlibrary_note \"likely generated binder names\"/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\n\n\n/-- Check whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nunsafe def is_likely_generated_binder_simple_name : String \u2192 Bool\n  | \"\u1fb0\" => true\n  | n =>\n    match n.getRest \"\u1fb0_\" with\n    | none => false\n    | some suffix => suffix.isNat\n#align name.is_likely_generated_binder_simple_name name.is_likely_generated_binder_simple_name\n\n/-- Check whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nunsafe def is_likely_generated_binder_name (n : Name) : Bool :=\n  match n with\n  | mk_string s anonymous => is_likely_generated_binder_simple_name s\n  | _ => false\n#align name.is_likely_generated_binder_name name.is_likely_generated_binder_name\n\nend Name\n\nnamespace Level\n\n/-! ### Declarations about `level` -/\n\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\nunsafe def nonzero : level \u2192 Bool\n  | succ _ => true\n  | max l\u2081 l\u2082 => l\u2081.nonzero || l\u2082.nonzero\n  | imax _ l\u2082 => l\u2082.nonzero\n  | _ => false\n#align level.nonzero level.nonzero\n\n/-- `l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nunsafe def fold_mvar {\u03b1} : level \u2192 (Name \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 \u03b1\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 \u2218 fold_mvar b f\n  | imax a b, f => fold_mvar a f \u2218 fold_mvar b f\n#align level.fold_mvar level.fold_mvar\n\n/-- `l.params` is the set of parameters occuring in `l`.\nFor example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`.\n-/\nprotected unsafe def params (u : level) : name_set :=\n  u.fold mk_name_set fun v l =>\n    match v with\n    | param nm => l.insert nm\n    | _ => l\n#align level.params level.params\n\nend Level\n\n/-! ### Declarations about `binder` -/\n\n\n/-- The type of binders containing a name, the binding info and the binding type -/\nunsafe structure binder where\n  Name : Name\n  info : BinderInfo\n  type : expr\n  deriving DecidableEq, Inhabited\n#align binder binder\n\nnamespace Binder\n\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nprotected unsafe def to_string (b : binder) : String :=\n  let (l, r) := b.info.brackets\n  l ++ b.Name.toString ++ \" : \" ++ b.type.toString ++ r\n#align binder.to_string binder.to_string\n\nunsafe instance : ToString binder :=\n  \u27e8binder.to_string\u27e9\n\nunsafe instance : has_to_format binder :=\n  \u27e8fun b => b.toString\u27e9\n\nunsafe instance : has_to_tactic_format binder :=\n  \u27e8fun b =>\n    let (l, r) := b.info.brackets\n    (fun e => l ++ b.Name.toString ++ \" : \" ++ e ++ r) <$> pp b.type\u27e9\n\nend Binder\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n\n/-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\nunsafe def nat.mk_numeral (type has_zero has_one has_add : expr) : \u2115 \u2192 expr :=\n  let z : expr := q(@Zero.zero.{0} $(type) $(Zero))\n  let o : expr := q(@One.one.{0} $(type) $(One))\n  Nat.binaryRec z fun b n e =>\n    if n = 0 then o\n    else if b then q(@bit1.{0} $(type) $(One) $(Add) $(e)) else q(@bit0.{0} $(type) $(Add) $(e))\n#align nat.mk_numeral nat.mk_numeral\n\n/-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\nunsafe def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : \u2124 \u2192 expr\n  | Int.ofNat n => n.mk_numeral type Zero One Add\n  | -[n+1] =>\n    let ne := (n + 1).mk_numeral type Zero One Add\n    q(@Neg.neg.{0} $(type) $(Neg) $(Ne))\n#align int.mk_numeral int.mk_numeral\n\n/-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nunsafe def nat.to_pexpr : \u2115 \u2192 pexpr\n  | 0 => ``(0)\n  | 1 => ``(1)\n  | n => if n % 2 = 0 then ``(bit0 $(nat.to_pexpr n / 2)) else ``(bit1 $(nat.to_pexpr n / 2))\n#align nat.to_pexpr nat.to_pexpr\n\n/-- `int.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(int.to_pexpr (-5)) : \u211a))` will create a native `\u211a` numeral `(-5 : \u211a)`.\n-/\nunsafe def int.to_pexpr : \u2124 \u2192 pexpr\n  | Int.ofNat k => k.to_pexpr\n  | Int.negSucc k => ``(-$(k + 1.to_pexpr))\n#align int.to_pexpr int.to_pexpr\n\nnamespace Expr\n\n/-- Turns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\nprotected unsafe def to_nat : expr \u2192 Option \u2115\n  | q(Zero.zero) => some 0\n  | q(One.one) => some 1\n  | q(bit0 $(e)) => bit0 <$> e.toNat\n  | q(bit1 $(e)) => bit1 <$> e.toNat\n  | q(Nat.succ $(e)) => (\u00b7 + 1) <$> e.toNat\n  | q(Nat.zero) => some 0\n  | _ => none\n#align expr.to_nat expr.to_nat\n\n/-- Turns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\nprotected unsafe def to_int : expr \u2192 Option \u2124\n  | q(Neg.neg $(e)) => do\n    let n \u2190 e.toNat\n    some (-n)\n  | e => coe <$> e.toNat\n#align expr.to_int expr.to_int\n\n/-- Turns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`.\n-/\nprotected unsafe def to_list {\u03b1} (f : expr \u2192 Option \u03b1) : expr \u2192 Option (List \u03b1)\n  | q(List.nil) => some []\n  | q(List.cons $(x) $(l)) => List.cons <$> f x <*> l.toList\n  | _ => none\n#align expr.to_list expr.to_list\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n      `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\n      ignoring differences in type and type class arguments.\n      -/\n    unsafe\n  def\n    is_num_eq\n    : expr \u2192 expr \u2192 Bool\n    | q( @ Zero.zero _ _ ) , q( @ Zero.zero _ _ ) => true\n      | q( @ One.one _ _ ) , q( @ One.one _ _ ) => true\n      | q( bit0 $ ( a ) ) , q( bit0 $ ( b ) ) => a . is_num_eq b\n      | q( bit1 $ ( a ) ) , q( bit1 $ ( b ) ) => a . is_num_eq b\n      | q( - $ ( a ) ) , q( - $ ( b ) ) => a . is_num_eq b\n      | q( $ ( a ) / $ ( a' ) ) , q( $ ( b ) / $ ( b' ) ) => a . is_num_eq b\n      | _ , _ => false\n#align expr.is_num_eq expr.is_num_eq\n\nend Expr\n\n/-! ### Declarations about `pexpr` -/\n\n\nnamespace Pexpr\n\n/-- If `e` is an annotation of `frozen_name` to `expr.const n`,\n`e.get_frozen_name` returns `n`.\nOtherwise, returns `name.anonymous`.\n-/\nunsafe def get_frozen_name (e : pexpr) : Name :=\n  match e.is_annotation with\n  | some (`frozen_name, expr.const n _) => n\n  | _ => Name.anonymous\n#align pexpr.get_frozen_name pexpr.get_frozen_name\n\n/-- If `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_fn_args` returns `(f, [e\u2081, ... e\u2099])`.\nSee also `expr.get_app_fn_args`.\n-/\nunsafe def get_app_fn_args : pexpr \u2192 optParam (List pexpr) [] \u2192 pexpr \u00d7 List pexpr\n  | expr.app e1 e2, r => get_app_fn_args e1 (e2 :: r)\n  | e1, r => (e1, r)\n#align pexpr.get_app_fn_args pexpr.get_app_fn_args\n\n/-- If `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_fn` returns `f`.\nSee also `expr.get_app_fn`.\n-/\nunsafe def get_app_fn : pexpr \u2192 List pexpr :=\n  Prod.snd \u2218 get_app_fn_args\n#align pexpr.get_app_fn pexpr.get_app_fn\n\n/-- If `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_args` returns `[e\u2081, ... e\u2099]`.\nSee also `expr.get_app_args`.\n-/\nunsafe def get_app_args : pexpr \u2192 List pexpr :=\n  Prod.snd \u2218 get_app_fn_args\n#align pexpr.get_app_args pexpr.get_app_args\n\nend Pexpr\n\n/-! ### Declarations about `expr` -/\n\n\nnamespace Expr\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\nunsafe def clean_ids : List Name :=\n  [`` id, `` id, `` id, `` hidden]\n#align expr.clean_ids expr.clean_ids\n\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\nunsafe def clean (e : expr) : expr :=\n  e.replace fun e n =>\n    match e with\n    | app (app (const n _) _) e' => if n \u2208 clean_ids then some e' else none\n    | app (lam _ _ _ (var 0)) e' => some e'\n    | _ => none\n#align expr.clean expr.clean\n\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\nunsafe def replace_with (e : expr) (s : expr) (s' : expr) : expr :=\n  e.replace fun c d => if c = s then some (s'.lift_vars 0 d) else none\n#align expr.replace_with expr.replace_with\n\n/-- Implementation of `expr.mreplace`. -/\nunsafe def mreplace_aux {m : Type _ \u2192 Type _} [Monad m] (R : expr \u2192 Nat \u2192 m (Option expr)) :\n    expr \u2192 \u2115 \u2192 m expr\n  | app f x, n =>\n    Option.getDM' (R (app f x) n) do\n      let Rf \u2190 mreplace_aux f n\n      let Rx \u2190 mreplace_aux x n\n      return <| app Rf Rx\n  | lam nm bi ty bd, n =>\n    Option.getDM' (R (lam nm bi ty bd) n) do\n      let Rty \u2190 mreplace_aux ty n\n      let Rbd \u2190 mreplace_aux bd (n + 1)\n      return <| lam nm bi Rty Rbd\n  | pi nm bi ty bd, n =>\n    Option.getDM' (R (pi nm bi ty bd) n) do\n      let Rty \u2190 mreplace_aux ty n\n      let Rbd \u2190 mreplace_aux bd (n + 1)\n      return <| pi nm bi Rty Rbd\n  | elet nm ty a b, n =>\n    Option.getDM' (R (elet nm ty a b) n) do\n      let Rty \u2190 mreplace_aux ty n\n      let Ra \u2190 mreplace_aux a n\n      let Rb \u2190 mreplace_aux b n\n      return <| elet nm Rty Ra Rb\n  | macro c es, n =>\n    Option.getDM' (R (macro c es) n) <| macro c <$> es.mapM fun e => mreplace_aux e n\n  | e, n => Option.getDM' (R e n) (return e)\n#align expr.mreplace_aux expr.mreplace_aux\n\n/-- Monadic analogue of `expr.replace`.\n\nThe `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where\n`n` is the number of binders above `e`.\nIf `R s n` fails, the whole replacement fails.\nIf `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit\nits subexpressions).\nIf `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.\n\nWARNING: This function performs exponentially worse on large terms than `expr.replace`,\nif a subexpression occurs more than once in an expression, `expr.replace` visits them only once,\nbut this function will visit every occurence of it. Do not use this on large expressions.\n-/\nunsafe def mreplace {m : Type _ \u2192 Type _} [Monad m] (R : expr \u2192 Nat \u2192 m (Option expr)) (e : expr) :\n    m expr :=\n  mreplace_aux R e 0\n#align expr.mreplace expr.mreplace\n\n/-- Match a variable. -/\nunsafe def match_var {elab} : expr elab \u2192 Option \u2115\n  | var n => some n\n  | _ => none\n#align expr.match_var expr.match_var\n\n/-- Match a sort. -/\nunsafe def match_sort {elab} : expr elab \u2192 Option level\n  | sort u => some u\n  | _ => none\n#align expr.match_sort expr.match_sort\n\n/-- Match a constant. -/\nunsafe def match_const {elab} : expr elab \u2192 Option (Name \u00d7 List level)\n  | const n lvls => some (n, lvls)\n  | _ => none\n#align expr.match_const expr.match_const\n\n/-- Match a metavariable. -/\nunsafe def match_mvar {elab} : expr elab \u2192 Option (Name \u00d7 Name \u00d7 expr elab)\n  | mvar Unique pretty type => some (Unique, pretty, type)\n  | _ => none\n#align expr.match_mvar expr.match_mvar\n\n/-- Match a local constant. -/\nunsafe def match_local_const {elab} : expr elab \u2192 Option (Name \u00d7 Name \u00d7 BinderInfo \u00d7 expr elab)\n  | local_const Unique pretty bi type => some (Unique, pretty, bi, type)\n  | _ => none\n#align expr.match_local_const expr.match_local_const\n\n/-- Match an application. -/\nunsafe def match_app {elab} : expr elab \u2192 Option (expr elab \u00d7 expr elab)\n  | app t u => some (t, u)\n  | _ => none\n#align expr.match_app expr.match_app\n\n/-- Match an application of `coe_fn`. -/\nunsafe def match_app_coe_fn : expr \u2192 Option (expr \u00d7 expr \u00d7 expr \u00d7 expr \u00d7 expr)\n  | app q(@coeFn $(\u03b1) $(\u03b2) $(inst) $(fexpr)) x => some (\u03b1, \u03b2, inst, fexpr, x)\n  | _ => none\n#align expr.match_app_coe_fn expr.match_app_coe_fn\n\n/-- Match an abstraction. -/\nunsafe def match_lam {elab} : expr elab \u2192 Option (Name \u00d7 BinderInfo \u00d7 expr elab \u00d7 expr elab)\n  | lam var_name bi type body => some (var_name, bi, type, body)\n  | _ => none\n#align expr.match_lam expr.match_lam\n\n/-- Match a \u03a0 type. -/\nunsafe def match_pi {elab} : expr elab \u2192 Option (Name \u00d7 BinderInfo \u00d7 expr elab \u00d7 expr elab)\n  | pi var_name bi type body => some (var_name, bi, type, body)\n  | _ => none\n#align expr.match_pi expr.match_pi\n\n/-- Match a let. -/\nunsafe def match_elet {elab} : expr elab \u2192 Option (Name \u00d7 expr elab \u00d7 expr elab \u00d7 expr elab)\n  | elet var_name type assignment body => some (var_name, type, assignment, body)\n  | _ => none\n#align expr.match_elet expr.match_elet\n\n/-- Match a macro. -/\nunsafe def match_macro {elab} : expr elab \u2192 Option (macro_def \u00d7 List (expr elab))\n  | macro df args => some (df, args)\n  | _ => none\n#align expr.match_macro expr.match_macro\n\n/-- Tests whether an expression is a meta-variable. -/\nunsafe def is_mvar : expr \u2192 Bool\n  | mvar _ _ _ => true\n  | _ => false\n#align expr.is_mvar expr.is_mvar\n\n/-- Tests whether an expression is a sort. -/\nunsafe def is_sort : expr \u2192 Bool\n  | sort _ => true\n  | e => false\n#align expr.is_sort expr.is_sort\n\n/-- Get the universe levels of a `const` expression -/\nunsafe def univ_levels : expr \u2192 List level\n  | const n ls => ls\n  | _ => []\n#align expr.univ_levels expr.univ_levels\n\n/-- Replace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\nunsafe def replace_mvars (e : expr) : expr :=\n  e.replace fun e' _ => if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none\n#align expr.replace_mvars expr.replace_mvars\n\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\nunsafe def to_implicit_local_const : expr \u2192 expr\n  | expr.local_const uniq n bi t => expr.local_const uniq n BinderInfo.implicit t\n  | e => e\n#align expr.to_implicit_local_const expr.to_implicit_local_const\n\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.\n-/\nunsafe def to_implicit_binder : expr \u2192 expr\n  | local_const n\u2081 n\u2082 _ d => local_const n\u2081 n\u2082 BinderInfo.implicit d\n  | lam n _ d b => lam n BinderInfo.implicit d b\n  | pi n _ d b => pi n BinderInfo.implicit d b\n  | e => e\n#align expr.to_implicit_binder expr.to_implicit_binder\n\n/-- Returns a list of all local constants in an expression (without duplicates). -/\nunsafe def list_local_consts (e : expr) : List expr :=\n  e.fold [] fun e' _ es => if e'.is_local_constant then insert e' es else es\n#align expr.list_local_consts expr.list_local_consts\n\n/-- Returns the set of all local constants in an expression. -/\nunsafe def list_local_consts' (e : expr) : expr_set :=\n  e.fold mk_expr_set fun e' _ es => if e'.is_local_constant then es.insert e' else es\n#align expr.list_local_consts' expr.list_local_consts'\n\n/-- Returns the unique names of all local constants in an expression. -/\nunsafe def list_local_const_unique_names (e : expr) : name_set :=\n  e.fold mk_name_set fun e' _ es =>\n    if e'.is_local_constant then es.insert e'.local_uniq_name else es\n#align expr.list_local_const_unique_names expr.list_local_const_unique_names\n\n/-- Returns a `name_set` of all constants in an expression. -/\nunsafe def list_constant (e : expr) : name_set :=\n  e.fold mk_name_set fun e' _ es => if e'.is_constant then es.insert e'.const_name else es\n#align expr.list_constant expr.list_constant\n\n/-- Returns a `list name` containing the constant names of an `expr` in the same order\n  that `expr.fold` traverses it. -/\nunsafe def list_constant' (e : expr) : List Name :=\n  (e.fold [] fun e' _ es => if e'.is_constant then es.insert e'.const_name else es).reverse\n#align expr.list_constant' expr.list_constant'\n\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\nunsafe def list_meta_vars (e : expr) : List expr :=\n  e.fold [] fun e' _ es => if e'.is_mvar then insert e' es else es\n#align expr.list_meta_vars expr.list_meta_vars\n\n/-- Returns the set of all meta-variables in an expression. -/\nunsafe def list_meta_vars' (e : expr) : expr_set :=\n  e.fold mk_expr_set fun e' _ es => if e'.is_mvar then es.insert e' else es\n#align expr.list_meta_vars' expr.list_meta_vars'\n\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\nunsafe def list_univ_meta_vars (e : expr) : List Name :=\n  native.rb_set.to_list <|\n    e.fold native.mk_rb_set fun e' i s =>\n      match e' with\n      | sort u => u.fold_mvar (flip native.rb_set.insert) s\n      | const _ ls => ls.foldl (fun s' l => l.fold_mvar (flip native.rb_set.insert) s') s\n      | _ => s\n#align expr.list_univ_meta_vars expr.list_univ_meta_vars\n\n/-- Test `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\nunsafe def contains_expr_or_mvar (t : expr) (e : expr) : Bool :=\n  -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n    \u00act.list_meta_vars.Empty \u2228\n    e.occurs t\n#align expr.contains_expr_or_mvar expr.contains_expr_or_mvar\n\n/-- Returns a `name_set` of all constants in an expression starting with a certain prefix. -/\nunsafe def list_names_with_prefix (pre : Name) (e : expr) : name_set :=\n  e.fold mk_name_set fun e' _ l =>\n    match e' with\n    | expr.const n _ => if n.getPrefix = pre then l.insert n else l\n    | _ => l\n#align expr.list_names_with_prefix expr.list_names_with_prefix\n\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\nunsafe def contains_constant (e : expr) (p : Name \u2192 Prop) [DecidablePred p] : Bool :=\n  e.fold false fun e' _ b => if p e'.const_name then true else b\n#align expr.contains_constant expr.contains_constant\n\n/-- Returns true if `e` contains a `sorry`.\nSee also `name.contains_sorry`.\n-/\nunsafe def contains_sorry (e : expr) : Bool :=\n  e.fold false fun e' _ b => if (is_sorry e').isSome then true else b\n#align expr.contains_sorry expr.contains_sorry\n\n/-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\nunsafe def app_symbol_in (e : expr) (l : List Name) : Bool :=\n  match e.get_app_fn with\n  | expr.const n _ => n \u2208 l\n  | _ => false\n#align expr.app_symbol_in expr.app_symbol_in\n\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\nunsafe def get_simp_args (e : expr) : tactic (List expr) :=\n  if-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\n      \u00ace.is_app then\n    pure []\n  else do\n    let cgr \u2190 mk_specialized_congr_lemma_simp e\n    pure do\n        let (arg_kind, arg) \u2190 cgr e\n        guard <| arg_kind = CongrArgKind.eq\n        pure arg\n#align expr.get_simp_args expr.get_simp_args\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\nunsafe def simp (t : expr) (cfg : SimpConfig := { }) (discharger : tactic Unit := failed)\n    (no_defaults := false) (attr_names : List Name := []) (hs : List simp_arg_type := []) :\n    tactic (expr \u00d7 expr \u00d7 name_set) := do\n  let (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs\n  simplify s to_unfold t cfg `eq discharger\n#align expr.simp expr.simp\n\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\nunsafe def dsimp (t : expr) (cfg : DsimpConfig := { }) (no_defaults := false)\n    (attr_names : List Name := []) (hs : List simp_arg_type := []) : tactic expr := do\n  let (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs\n  s to_unfold t cfg\n#align expr.dsimp expr.dsimp\n\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\nunsafe def binding_names : expr \u2192 List Name\n  | pi n _ _ e => n :: e.binding_names\n  | lam n _ _ e => n :: e.binding_names\n  | e => []\n#align expr.binding_names expr.binding_names\n\n/-- head-reduce a single let expression -/\nunsafe def reduce_let : expr \u2192 expr\n  | elet _ _ v b => b.instantiate_var v\n  | e => e\n#align expr.reduce_let expr.reduce_let\n\n/-- head-reduce all let expressions -/\nunsafe def reduce_lets : expr \u2192 expr\n  | elet _ _ v b => reduce_lets <| b.instantiate_var v\n  | e => e\n#align expr.reduce_lets expr.reduce_lets\n\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\nunsafe def instantiate_lambdas : List expr \u2192 expr \u2192 expr\n  | e' :: es, lam n bi t e => instantiate_lambdas es (e.instantiate_var e')\n  | _, e => e\n#align expr.instantiate_lambdas expr.instantiate_lambdas\n\n/-- Repeatedly apply `expr.subst`. -/\nunsafe def substs : expr \u2192 List expr \u2192 expr\n  | e, es => es.foldl expr.subst e\n#align expr.substs expr.substs\n\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\nunsafe def instantiate_lambdas_or_apps : List expr \u2192 expr \u2192 expr\n  | v :: es, lam n bi t b => instantiate_lambdas_or_apps es <| b.instantiate_var v\n  | es, elet _ _ v b => instantiate_lambdas_or_apps es <| b.instantiate_var v\n  | es, e => mk_app e es\n#align expr.instantiate_lambdas_or_apps expr.instantiate_lambdas_or_apps\n\nlibrary_note \"open expressions\"/--\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\n\n/-- Get the codomain/target of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nunsafe def pi_codomain : expr \u2192 expr\n  | pi n bi d b => pi_codomain b\n  | e => e\n#align expr.pi_codomain expr.pi_codomain\n\n/-- Get the body/value of a lambda-expression.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nunsafe def lambda_body : expr \u2192 expr\n  | lam n bi d b => lambda_body b\n  | e => e\n#align expr.lambda_body expr.lambda_body\n\n/-- Auxiliary defintion for `pi_binders`.\n  See note [open expressions]. -/\nunsafe def pi_binders_aux : List binder \u2192 expr \u2192 List binder \u00d7 expr\n  | es, pi n bi d b => pi_binders_aux (\u27e8n, bi, d\u27e9 :: es) b\n  | es, e => (es, e)\n#align expr.pi_binders_aux expr.pi_binders_aux\n\n/-- Get the binders and codomain of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the\n  free variables.\n  See note [open expressions]. -/\nunsafe def pi_binders (e : expr) : List binder \u00d7 expr :=\n  let (es, e) := pi_binders_aux [] e\n  (es.reverse, e)\n#align expr.pi_binders expr.pi_binders\n\n/-- Auxiliary defintion for `get_app_fn_args`. -/\nunsafe def get_app_fn_args_aux : List expr \u2192 expr \u2192 expr \u00d7 List expr\n  | r, app f a => get_app_fn_args_aux (a :: r) f\n  | r, e => (e, r)\n#align expr.get_app_fn_args_aux expr.get_app_fn_args_aux\n\n/-- A combination of `get_app_fn` and `get_app_args`: lists both the\n  function and its arguments of an application -/\nunsafe def get_app_fn_args : expr \u2192 expr \u00d7 List expr :=\n  get_app_fn_args_aux []\n#align expr.get_app_fn_args expr.get_app_fn_args\n\n/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/\nunsafe def drop_pis : List expr \u2192 expr \u2192 tactic expr\n  | v :: vs, pi n bi d b => do\n    let t \u2190 infer_type v\n    guard (t == d)\n    drop_pis vs (b v)\n  | [], e => return e\n  | _, _ => failed\n#align expr.drop_pis expr.drop_pis\n\n/-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`.\n  Does not check whether the result remains type-correct. -/\nunsafe def instantiate_pis : List expr \u2192 expr \u2192 expr\n  | v :: vs, pi n bi d b => instantiate_pis vs (b.instantiate_var v)\n  | _, e => e\n#align expr.instantiate_pis expr.instantiate_pis\n\n/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.\n  Returns `empty` if the list is empty. -/\nunsafe def mk_op_lst (op : expr) (empty : expr) : List expr \u2192 expr\n  | [] => Empty\n  | [e] => e\n  | e :: es => op e <| mk_op_lst es\n#align expr.mk_op_lst expr.mk_op_lst\n\n/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 \u2227 (x2 \u2227 ...)`, or `true` if the list is empty. -/\nunsafe def mk_and_lst : List expr \u2192 expr :=\n  mk_op_lst q(And) q(True)\n#align expr.mk_and_lst expr.mk_and_lst\n\n/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 \u2228 (x2 \u2228 ...)`, or `false` if the list is empty. -/\nunsafe def mk_or_lst : List expr \u2192 expr :=\n  mk_op_lst q(Or) q(False)\n#align expr.mk_or_lst expr.mk_or_lst\n\n/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.\nOtherwise returns `binder_info.default`. -/\nunsafe def local_binding_info : expr \u2192 BinderInfo\n  | expr.local_const _ _ bi _ => bi\n  | _ => BinderInfo.default\n#align expr.local_binding_info expr.local_binding_info\n\n/-- `is_default_local e` tests whether `e` is a local constant with binder info\n`binder_info.default` -/\nunsafe def is_default_local : expr \u2192 Bool\n  | expr.local_const _ _ BinderInfo.default _ => true\n  | _ => false\n#align expr.is_default_local expr.is_default_local\n\n/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/\nunsafe def has_local_constant (e l : expr) : Bool :=\n  e.has_local_in <| mk_name_set.insert l.local_uniq_name\n#align expr.has_local_constant expr.has_local_constant\n\n/-- Turns a local constant into a binder -/\nunsafe def to_binder : expr \u2192 binder\n  | local_const _ nm bi t => \u27e8nm, bi, t\u27e9\n  | _ => default\n#align expr.to_binder expr.to_binder\n\n/-- Strip-away the context-dependent unique id for the given local const and return: its friendly\n`name`, its `binder_info`, and its `type : expr`. -/\nunsafe def get_local_const_kind : expr \u2192 Name \u00d7 BinderInfo \u00d7 expr\n  | expr.local_const _ n bi e => (n, bi, e)\n  | _ => (Name.anonymous, BinderInfo.default, expr.const Name.anonymous [])\n#align expr.get_local_const_kind expr.get_local_const_kind\n\n/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/\nunsafe def local_const_set_type {elab : Bool} : expr elab \u2192 expr elab \u2192 expr elab\n  | expr.local_const x n bi t, new_t => expr.local_const x n bi new_t\n  | e, new_t => e\n#align expr.local_const_set_type expr.local_const_set_type\n\n/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to\naccess core `expr` manipulation functions for `pexpr`-based use, but which are restricted to\n`expr tt` at the site of definition unnecessarily.\n\nDANGER: Unless you know exactly what you are doing, this is probably not the function you are\nlooking for. For `pexpr \u2192 expr` see `tactic.to_expr`. For `expr \u2192 pexpr` see `to_pexpr`. -/\nunsafe def unsafe_cast {elab\u2081 elab\u2082 : Bool} : expr elab\u2081 \u2192 expr elab\u2082 :=\n  unchecked_cast\n#align expr.unsafe_cast expr.unsafe_cast\n\n/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr \u00d7 expr)` as\na collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says \"whenever\n`f` is encountered in `e` verbatim, replace it with `t`\". -/\nunsafe def replace_subexprs {elab : Bool} (e : expr elab) (mappings : List (expr \u00d7 expr)) :\n    expr elab :=\n  unsafe_cast <|\n    e.unsafe_cast.replace fun e n =>\n      (mappings.filter\u2093 fun ent : expr \u00d7 expr => ent.1 = e).head?.map Prod.snd\n#align expr.replace_subexprs expr.replace_subexprs\n\n/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of\n    other `expr.local_const`s. It determines whether `e` should be considered \"available in context\"\n    as a variable by virtue of the fact that the variables `vs` have been deemed such.\n\n    For example, given `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that\n    the typeclass instance `prime n` should be included, but `ih : even n` should not.\n\n    DANGER: It is possible that for `f : expr` another `expr.local_const`, we have\n    `is_implicitly_included_variable f vs = ff` but\n    `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to\n    iteratively add a list of local constants (usually, the `variables` declared in the local scope)\n    which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables\n    were added in a particular iteration. The function `all_implicitly_included_variables` below\n    implements this behaviour.\n\n    Note that if `e \u2208 vs` then `is_implicitly_included_variable e vs = tt`. -/\nunsafe def is_implicitly_included_variable (e : expr) (vs : List expr) : Bool :=\n  if \u00ace.local_pp_name.toString.startsWith \"_\" then e \u2208 vs\n  else\n    e.local_type.fold true fun se _ b =>\n      if \u00acb then false else if \u00acse.is_local_constant then true else se \u2208 vs\n#align expr.is_implicitly_included_variable expr.is_implicitly_included_variable\n\n/-- Private work function for `all_implicitly_included_variables`, performing the actual series of\n    iterations, tracking with a boolean whether any updates occured this iteration. -/\nprivate unsafe def all_implicitly_included_variables_aux :\n    List expr \u2192 List expr \u2192 List expr \u2192 Bool \u2192 List expr\n  | [], vs, rs, tt => all_implicitly_included_variables_aux rs vs [] false\n  | [], vs, rs, ff => vs\n  | e :: rest, vs, rs, b =>\n    let (vs, rs, b) :=\n      if e.is_implicitly_included_variable vs then (e :: vs, rs, true) else (vs, e :: rs, b)\n    all_implicitly_included_variables_aux rest vs rs b\n#align expr.all_implicitly_included_variables_aux expr.all_implicitly_included_variables_aux\n\n/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,\n    another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion\n    of the variables in `vs` into the local context implies that `e` should also be included. See\n    `is_implicitly_included_variable e vs` for the details.\n\n    In particular, those elements of `vs` are included automatically. -/\nunsafe def all_implicitly_included_variables (es vs : List expr) : List expr :=\n  all_implicitly_included_variables_aux es vs [] false\n#align expr.all_implicitly_included_variables expr.all_implicitly_included_variables\n\n/-- Get the list of explicit arguments of a function. -/\nunsafe def list_explicit_args (f : expr) : tactic (List expr) :=\n  tactic.fold_explicit_args f [] fun ll e => return <| ll ++ [e]\n#align expr.list_explicit_args expr.list_explicit_args\n\n/-- `replace_explicit_args f parg` assumes that `f` is an expression corresponding to a function\napplication.  It replaces the explicit arguments of `f`, in succession, by the elements of `parg`.\nThe implicit arguments of `f` remain unchanged. -/\nunsafe def replace_explicit_args (f : expr) (parg : List expr) : tactic expr := do\n  let finf \u2190 get_fun_info f.get_app_fn\n  let is_ex_arg : List Bool := finf.params.map fun e => \u00ace.isImplicit \u2227 \u00ace.isInstImplicit\n  let nargs := List.replaceIf f.get_app_args is_ex_arg parg\n  return <| expr.mk_app f nargs\n#align expr.replace_explicit_args expr.replace_explicit_args\n\n/-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier.\nThis also works if `x1, ... xn` contain free variables. -/\nprotected unsafe def simple_infer_type (env : environment) (e : expr) : exceptional expr := do\n  let (@const tt n ls, es) \u2190 return e.get_app_fn_args |\n    exceptional.fail \"expression is not a constant applied to arguments\"\n  let d \u2190 env.get n\n  return <| (d es).instantiate_univ_params <| d ls\n#align expr.simple_infer_type expr.simple_infer_type\n\n/-- Auxilliary function for `head_eta_expand`. -/\nunsafe def head_eta_expand_aux : \u2115 \u2192 expr \u2192 expr \u2192 expr\n  | n + 1, e, pi x bi d b => lam x bi d <| head_eta_expand_aux n e b\n  | _, e, _ => e\n#align expr.head_eta_expand_aux expr.head_eta_expand_aux\n\n/-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained\n  by its type `t`. -/\nunsafe def head_eta_expand (n : \u2115) (e t : expr) : expr :=\n  ((e.lift_vars 0 n).mk_app <| (List.range n).reverse.map var).head_eta_expand_aux n t\n#align expr.head_eta_expand expr.head_eta_expand\n\n/-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in\n`dict`. They are expanded until they are applied to one more argument than the maximum in\n`dict.find n`. -/\nprotected unsafe def eta_expand (env : environment) (dict : name_map <| List \u2115) : expr \u2192 expr\n  | e =>\n    e.replace fun e _ => do\n      let (e0, es) := e.get_app_fn_args\n      let ns := (dict.find e0.const_name).iget\n      guard (not ns)\n      let e' := e0.mk_app <| es.map eta_expand\n      let needed_n := ns.foldr max 0 + 1\n      if needed_n \u2264 es then some e'\n        else do\n          let e'_type \u2190 (e' env).toOption\n          some <| head_eta_expand (needed_n - es) e' e'_type\n#align expr.eta_expand expr.eta_expand\n\n/-- `e.apply_replacement_fun f test` applies `f` to each identifier\n(inductive type, defined function etc) in an expression, unless\n* The identifier occurs in an application with first argument `arg`; and\n* `test arg` is false.\nHowever, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`\nis tested, instead of the first argument.\n\nReorder contains the information about what arguments to reorder:\ne.g. `g x\u2081 x\u2082 x\u2083 ... x\u2099` becomes `g x\u2082 x\u2081 x\u2083 ... x\u2099` if `reorder.find g = some [1]`.\nWe assume that all functions where we want to reorder arguments are fully applied.\nThis can be done by applying `expr.eta_expand` first.\n-/\nprotected unsafe def apply_replacement_fun (f : Name \u2192 Name) (test : expr \u2192 Bool)\n    (relevant : name_map \u2115) (reorder : name_map <| List \u2115) : expr \u2192 expr\n  | e =>\n    e.replace fun e _ =>\n      match e with\n      | const n ls =>\n        some <|\n          const\n              (f\n                n) <|-- if the first two arguments are reordered, we also reorder the first two universe parameters\n              if 1 \u2208 (reorder.find n).iget then ls.getI 1 :: ls.headI :: ls.drop 2\n            else ls\n      | app g x =>\n        let f := g.get_app_fn\n        let nm := f.const_name\n        let n_args := g.get_app_num_args\n        -- this might be inefficient\n          if n_args \u2208 (reorder.find nm).iget \u2227 test g.get_app_args.headI then\n          -- interchange `x` and the last argument of `g`\n            some <|\n            apply_replacement_fun g.app_fn (apply_replacement_fun x) <|\n              apply_replacement_fun g.app_arg\n        else\n          if n_args = (relevant.find nm).lhoare 0 \u2227 f.is_constant \u2227 \u00actest x then\n            some <| (f.mk_app <| g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x)\n          else none\n      | _ => none\n#align expr.apply_replacement_fun expr.apply_replacement_fun\n\nend Expr\n\n/-! ### Declarations about `environment` -/\n\n\nnamespace Environment\n\n/-- Tests whether `n` is a structure. -/\nunsafe def is_structure (env : environment) (n : Name) : Bool :=\n  (env.structure_fields n).isSome\n#align environment.is_structure environment.is_structure\n\n/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a\n  structure. -/\nunsafe def structure_fields_full (env : environment) (n : Name) : Option (List Name) :=\n  (env.structure_fields n).map (List.map fun n' => n ++ n')\n#align environment.structure_fields_full environment.structure_fields_full\n\n/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.\n  Note that `is_ginductive` returns `tt` even on regular inductive types.\n  This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive\n  type. -/\nunsafe def is_ginductive' (e : environment) (nm : Name) : Bool :=\n  e.is_ginductive nm \u2227 \u00ace.is_inductive nm\n#align environment.is_ginductive' environment.is_ginductive'\n\n/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list.  -/\nunsafe def decl_filter_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 Option \u03b1) : List \u03b1 :=\n  e.fold [] fun d l =>\n    match f d with\n    | some r => r :: l\n    | none => l\n#align environment.decl_filter_map environment.decl_filter_map\n\n/-- Maps `f` to all declarations in the environment. -/\nunsafe def decl_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 \u03b1) : List \u03b1 :=\n  e.decl_filter_map fun d => some (f d)\n#align environment.decl_map environment.decl_map\n\n/-- Lists all declarations in the environment -/\nunsafe def get_decls (e : environment) : List declaration :=\n  e.decl_map id\n#align environment.get_decls environment.get_decls\n\n/-- Lists all trusted (non-meta) declarations in the environment -/\nunsafe def get_trusted_decls (e : environment) : List declaration :=\n  e.decl_filter_map fun d => if d.is_trusted then some d else none\n#align environment.get_trusted_decls environment.get_trusted_decls\n\n/-- Lists the name of all declarations in the environment -/\nunsafe def get_decl_names (e : environment) : List Name :=\n  e.decl_map declaration.to_name\n#align environment.get_decl_names environment.get_decl_names\n\n/-- Fold a monad over all declarations in the environment. -/\nunsafe def mfold {\u03b1 : Type} {m : Type \u2192 Type} [Monad m] (e : environment) (x : \u03b1)\n    (fn : declaration \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\n  e.fold (return x) fun d t => t >>= fn d\n#align environment.mfold environment.mfold\n\n/-- Filters all declarations in the environment. -/\nunsafe def filter (e : environment) (test : declaration \u2192 Bool) : List declaration :=\n  e.fold [] fun d ds => if test d then d :: ds else ds\n#align environment.filter environment.filter\n\n/-- Filters all declarations in the environment. -/\nunsafe def mfilter (e : environment) (test : declaration \u2192 tactic Bool) :\n    tactic (List declaration) :=\n  e.mfold [] fun d ds => do\n    let b \u2190 test d\n    return <| if b then d :: ds else ds\n#align environment.mfilter environment.mfilter\n\n/-- Checks whether `s` is a prefix of the file where `n` is declared.\n  This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/\nunsafe def is_prefix_of_file (e : environment) (s : String) (n : Name) : Bool :=\n  s.isPrefixOf\u2093 <| (e.decl_olean n).getD \"\"\n#align environment.is_prefix_of_file environment.is_prefix_of_file\n\nend Environment\n\n/-!\n### `is_eta_expansion`\n\n In this section we define the tactic `is_eta_expansion` which checks whether an expression\n  is an eta-expansion of a structure. (not to be confused with eta-expanion for `\u03bb`).\n\n-/\n\n\nnamespace Expr\n\n/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have\n  `pr = nm.{univs} args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nunsafe def is_eta_expansion_of (args : List expr) (univs : List level) (l : List (Name \u00d7 expr)) :\n    Bool :=\n  l.all fun \u27e8proj, val\u27e9 => val = (const proj univs).mk_app args\n#align expr.is_eta_expansion_of expr.is_eta_expansion_of\n\n/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all\n  elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nunsafe def is_eta_expansion_test : List (Name \u00d7 expr) \u2192 Option expr\n  | [] => none\n  | \u27e8proj, val\u27e9 :: l =>\n    match val.get_app_fn with\n    | (const nm univs : expr) =>\n      if nm = proj then\n        let args := val.get_app_args\n        let e := args.getLastI\n        if is_eta_expansion_of args univs l then some e else none\n      else none\n    | _ => none\n#align expr.is_eta_expansion_test expr.is_eta_expansion_test\n\n/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.\n  Here `l` is intended to consists of the projections and the fields of `val`.\n  This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and\n  afterward checks whether the resulting expression `e` unifies with `val`.\n  This last check is necessary, because `val` and `e` might have different types. -/\nunsafe def is_eta_expansion_aux (val : expr) (l : List (Name \u00d7 expr)) : tactic (Option expr) := do\n  let l' \u2190 l.filterM fun \u27e8proj, val\u27e9 => not <$> is_proof val\n  match is_eta_expansion_test l' with\n    | some e => (Option.map fun _ => e) <$> try_core (unify e val)\n    | none => return none\n#align expr.is_eta_expansion_aux expr.is_eta_expansion_aux\n\n/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the\n  eta-expansion of `e`.\n  With eta-expansion we here mean the eta-expansion of a structure, not of a function.\n  For example, the eta-expansion of `x : \u03b1 \u00d7 \u03b2` is `\u27e8x.1, x.2\u27e9`.\n  This assumes that `val` is a fully-applied application of the constructor of a structure.\n\n  This is useful to reduce expressions generated by the notation\n    `{ field_1 := _, ..other_structure }`\n  If `other_structure` is itself a field of the structure, then the elaborator will insert an\n  eta-expanded version of `other_structure`. -/\nunsafe def is_eta_expansion (val : expr) : tactic (Option expr) := do\n  let e \u2190 get_env\n  let type \u2190 infer_type val\n  let projs \u2190 e.structure_fields_full type.get_app_fn.const_name\n  let args := val.get_app_args.drop type.get_app_args.length\n  is_eta_expansion_aux val (projs args)\n#align expr.is_eta_expansion expr.is_eta_expansion\n\nend Expr\n\n/-! ### Declarations about `declaration` -/\n\n\nnamespace Declaration\n\n/-- `declaration.update_with_fun f test tgt decl`\nsets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and\n`expr.apply_replacement_fun` to the value and type of `decl`.\n-/\nprotected unsafe def update_with_fun (env : environment) (f : Name \u2192 Name) (test : expr \u2192 Bool)\n    (relevant : name_map \u2115) (reorder : name_map <| List \u2115) (tgt : Name) (decl : declaration) :\n    declaration :=\n  let decl := decl.update_name <| tgt\n  let decl :=\n    decl.update_type <|\n      (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder\n  decl.update_value <|\n    (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder\n#align declaration.update_with_fun declaration.update_with_fun\n\n/-- Checks whether the declaration is declared in the current file.\n  This is a simple wrapper around `environment.in_current_file`\n  Use `environment.in_current_file` instead if performance matters. -/\nunsafe def in_current_file (d : declaration) : tactic Bool := do\n  let e \u2190 get_env\n  return <| e d\n#align declaration.in_current_file declaration.in_current_file\n\n/-- Checks whether a declaration is a theorem -/\nunsafe def is_theorem : declaration \u2192 Bool\n  | thm _ _ _ _ => true\n  | _ => false\n#align declaration.is_theorem declaration.is_theorem\n\n/-- Checks whether a declaration is a constant -/\nunsafe def is_constant : declaration \u2192 Bool\n  | cnst _ _ _ _ => true\n  | _ => false\n#align declaration.is_constant declaration.is_constant\n\n/-- Checks whether a declaration is a axiom -/\nunsafe def is_axiom : declaration \u2192 Bool\n  | ax _ _ _ => true\n  | _ => false\n#align declaration.is_axiom declaration.is_axiom\n\n/-- Checks whether a declaration is automatically generated in the environment.\n  There is no cheap way to check whether a declaration in the namespace of a generalized\n  inductive type is automatically generated, so for now we say that all of them are automatically\n  generated. -/\nunsafe def is_auto_generated (e : environment) (d : declaration) : Bool :=\n  e.is_constructor d.to_name \u2228\n    (e.is_projection d.to_name).isSome \u2228\n      e.is_constructor d.to_name.getPrefix \u2227\n          d.to_name.getLast \u2208 [\"inj\", \"inj_eq\", \"sizeof_spec\", \"inj_arrow\"] \u2228\n        e.is_inductive d.to_name.getPrefix \u2227\n            d.to_name.getLast \u2208\n              [\"below\", \"binduction_on\", \"brec_on\", \"cases_on\", \"dcases_on\", \"drec_on\", \"drec\",\n                \"rec\", \"rec_on\", \"no_confusion\", \"no_confusion_type\", \"sizeof\", \"ibelow\",\n                \"has_sizeof_inst\"] \u2228\n          d.to_name.hasPrefix fun nm => e.is_ginductive' nm\n#align declaration.is_auto_generated declaration.is_auto_generated\n\n/-- Returns true iff `d` is an automatically-generated or internal declaration.\n-/\nunsafe def is_auto_or_internal (env : environment) (d : declaration) : Bool :=\n  d.to_name.is_internal || d.is_auto_generated env\n#align declaration.is_auto_or_internal declaration.is_auto_or_internal\n\n/-- Returns the list of universe levels of a declaration. -/\nunsafe def univ_levels (d : declaration) : List level :=\n  d.univ_params.map level.param\n#align declaration.univ_levels declaration.univ_levels\n\n/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/\nprotected unsafe def reducibility_hints : declaration \u2192 ReducibilityHints\n  | declaration.defn _ _ _ _ red _ => red\n  | _ => ReducibilityHints.opaque\n#align declaration.reducibility_hints declaration.reducibility_hints\n\n/-- formats the arguments of a `declaration.thm` -/\nprivate unsafe def print_thm (nm : Name) (tp : expr) (body : task expr) : tactic format := do\n  let tp \u2190 pp tp\n  let body \u2190 pp body.get\n  return <| \"<theorem \" ++ to_fmt nm ++ \" : \" ++ tp ++ \" := \" ++ body ++ \">\"\n#align declaration.print_thm declaration.print_thm\n\n/-- formats the arguments of a `declaration.defn` -/\nprivate unsafe def print_defn (nm : Name) (tp : expr) (body : expr) (is_trusted : Bool) :\n    tactic format := do\n  let tp \u2190 pp tp\n  let body \u2190 pp body\n  return <|\n      (\"<\" ++ if is_trusted then \"def \" else \"meta def \") ++ to_fmt nm ++ \" : \" ++ tp ++ \" := \" ++\n          body ++\n        \">\"\n#align declaration.print_defn declaration.print_defn\n\n/-- formats the arguments of a `declaration.cnst` -/\nprivate unsafe def print_cnst (nm : Name) (tp : expr) (is_trusted : Bool) : tactic format := do\n  let tp \u2190 pp tp\n  return <|\n      (\"<\" ++ if is_trusted then \"constant \" else \"meta constant \") ++ to_fmt nm ++ \" : \" ++ tp ++\n        \">\"\n#align declaration.print_cnst declaration.print_cnst\n\n/-- formats the arguments of a `declaration.ax` -/\nprivate unsafe def print_ax (nm : Name) (tp : expr) : tactic format := do\n  let tp \u2190 pp tp\n  return <| \"<axiom \" ++ to_fmt nm ++ \" : \" ++ tp ++ \">\"\n#align declaration.print_ax declaration.print_ax\n\n/-- pretty-prints a `declaration` object. -/\nunsafe def to_tactic_format : declaration \u2192 tactic format\n  | declaration.thm nm _ tp bd => print_thm nm tp bd\n  | declaration.defn nm _ tp bd _ is_trusted => print_defn nm tp bd is_trusted\n  | declaration.cnst nm _ tp is_trusted => print_cnst nm tp is_trusted\n  | declaration.ax nm _ tp => print_ax nm tp\n#align declaration.to_tactic_format declaration.to_tactic_format\n\nunsafe instance : has_to_tactic_format declaration :=\n  \u27e8to_tactic_format\u27e9\n\nend Declaration\n\nunsafe instance pexpr.decidable_eq {elab} : DecidableEq (expr elab) :=\n  unchecked_cast expr.has_decidable_eq\n#align pexpr.decidable_eq pexpr.decidable_eq\n\nsection\n\nattribute [local semireducible] reflected\n\nunsafe instance {\u03b1} [has_reflect \u03b1] : has_reflect (Thunk \u03b1)\n  | a => expr.lam `x BinderInfo.default (reflect Unit) (reflect <| a ())\n\nend\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/Meta/Expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746994260479465, "lm_q2_score": 0.06656918665569081, "lm_q1q2_score": 0.019802332133716207}}
{"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.data.bool.lemmas\nimport Mathlib.Lean3Lib.init.data.string.basic\nimport Mathlib.Lean3Lib.init.meta.well_founded_tactics\n \n\nnamespace Mathlib\n\nnamespace string\n\n\nnamespace iterator\n\n\n@[simp] theorem next_to_string_mk_iterator (s : string) : next_to_string (mk_iterator s) = s :=\n  string_imp.rec (fun (s : List char) => Eq.refl (next_to_string (mk_iterator (string_imp.mk s)))) s\n\n@[simp] theorem length_next_to_string_next (it : iterator) : length (next_to_string (next it)) = length (next_to_string it) - 1 := sorry\n\ntheorem zero_lt_length_next_to_string_of_has_next {it : iterator} : \u21a5(has_next it) \u2192 0 < length (next_to_string it) := sorry\n\nend iterator\n\n\n-- TODO(Sebastian): generalize to something like https://doc.rust-lang.org/std/primitive.str.html#method.split\n\ndef split (p : char \u2192 Bool) (s : string) : List string :=\n  split_core p (mk_iterator s) (mk_iterator s)\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/string/ops.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.044018650646766244, "lm_q1q2_score": 0.01978165737973418}}
{"text": "\nimport util.classical\nimport util.predicate\nimport util.data.option\nimport util.control.applicative\nimport util.meta.tactic\nimport tactic.basic\n\nimport tactic\n\nimport temporal_logic.basic\nimport temporal_logic.persistent\nimport temporal_logic.pair\n\nopen predicate\n\n/-\n   The auto quotation currently supports two classes of tactics: tactic and smt_tactic.\n   To add a new class Tac, we have to\n   1) Make sure it is a monad. That is, we have an instance for (monad Tac)\n   2) There is a namespace Tac.interactive\n   3) There is a definition: Tac.step {\u03b1 : Type} (t : Tac \u03b1) : Tac unit\n   4) (Optional) Tac.istep {\u03b1 : Type} (line0 col0 : nat) (line col : nat) (tac : Tac \u03b1) : Tac unit\n      Similar to step but it should scope trace messages at the given line/col,\n      and ensure that the exception position is after (line0, col0)\n   6) There is a definition Tac.save_info (line col : nat) : Tac unit\n   7) There is a definition Tac.execute (tac : Tac unit) : tactic unit\n   8) There is a definition Tac.execute_with (cfg : config) (tac : Tac unit) : tactic unit\n      where config is an arbitrary type.\n   TODO(Leo): improve the \"recipe\" above. It is too ad hoc.\n-/\n\nmeta def temporal : Type \u2192 Type :=\ntactic\n\nopen format\n\nmeta def format.intercalate (x : format) : list format \u2192 format :=\nformat.join \u2218 list.intersperse x\n\nmeta def unlines : list format \u2192 format :=\nformat.intercalate line\n\nmeta instance : monad temporal :=\nby { dunfold temporal, apply_instance }\n\nmeta instance : monad_fail temporal :=\nby { dunfold temporal, apply_instance }\n\nmeta instance : alternative temporal :=\nby { dunfold temporal, apply_instance }\n\nmeta instance andthen_seq : has_andthen (temporal unit) (temporal unit) (temporal unit) :=\nby { dunfold temporal, apply_instance }\n\nmeta instance andthen_seq_focus : has_andthen (temporal unit) (list (temporal unit)) (temporal unit) :=\nby { dunfold temporal, apply_instance }\n\nnamespace temporal\nopen tactic applicative\nopen interactive\nopen tactic.interactive (resetI rw_rules rw_rules_t rw_rule get_rule_eqn_lemmas to_expr'\n                         unfreezeI solve_by_elim)\nopen has_to_tactic_format\nopen functor list (filter)\n\nsection expr\nopen expr\nvariable {elab : bool}\nmeta def get_app_args_aux' : list (expr elab) \u2192 expr elab \u2192 list (expr elab)\n| r (app f a) := get_app_args_aux' (a::r) f\n| r e         := r\n\nmeta def get_app_args' : (expr elab) \u2192 list (expr elab) :=\nget_app_args_aux' []\n\nend expr\n\nmeta def guarded {\u03b1 \u03b2} : list (tactic \u03b1 \u00d7 tactic \u03b2) \u2192 tactic \u03b2\n | [] := failed\n | ((x,y) :: xs) :=\ndo x \u2190 try_core x,\n   if x.is_some then\n     y\n   else guarded xs\n\nmeta def check_scope (e : expr) : tactic unit :=\ndo mmap' (get_local \u2218 expr.local_pp_name) e.list_local_consts\n\nmeta def type_check_result (msg : format) : tactic unit :=\nresult >>= type_check <|> fail msg\n\nmeta def mk_tmp_app {\u03b1} [has_to_pexpr \u03b1] (e\u2080 : expr) (e\u2081 : \u03b1) : temporal expr :=\ndo t \u2190 infer_type e\u2080,\n   (do e' \u2190 to_expr (to_pexpr e\u2081), e\u2080 e' <$ type_check (e\u2080 e'))\n   <|> to_expr ``(p_impl_revert %%e\u2080 %%e\u2081)\n   <|> to_expr ``(henceforth_deduction %%e\u2080 %%e\u2081)\n   <|> to_expr ``(p_forall_revert %%e\u2080 %%e\u2081)\n\nmeta def t_to_expr' : pexpr \u2192 temporal expr\n| e@(expr.app e\u2080 e\u2081) :=\n   to_expr e <|>\ndo e' \u2190 t_to_expr' e\u2080,\n   mk_tmp_app e' e\u2081\n| e := to_expr e\n\nmeta def t_to_expr (q : pexpr) : temporal expr :=\ndo p \u2190 t_to_expr' q <|> to_expr q,\n   check_scope p,\n   return p\n\nmeta def t_to_expr_for_apply (q : pexpr) : temporal expr :=\nlet aux (n : name) : tactic expr := do\n  p \u2190 resolve_name n,\n  match p with\n  | (expr.const c []) := do r \u2190 mk_const c, save_type_info r q, return r\n  | _                 := t_to_expr p\n  end\nin match q with\n| (expr.const c [])          := aux c\n| (expr.local_const c _ _ _) := aux c\n| _                          := t_to_expr q\nend\n\nmeta def beta_reduction' (eta := ff) : expr \u2192 temporal expr\n | (expr.app e\u2080 e\u2081) :=\n do e\u2081 \u2190 beta_reduction' e\u2081,\n    e\u2080 \u2190 beta_reduction' e\u2080,\n    head_beta $ expr.app e\u2080 e\u2081\n | e := do z \u2190 expr.traverse beta_reduction' e,\n           if eta then head_eta z\n                  else return z\n\n\nmeta def beta_reduction (e : expr) (eta := ff) : temporal expr :=\ninstantiate_mvars e >>= beta_reduction' eta\n\nmeta def succeeds {\u03b1} (tac : temporal \u03b1) : temporal bool :=\ntt <$ tac <|> pure ff\n\nmeta def decl_to_fmt (s : tactic_state) (vs : list expr) : expr \u00d7 option expr \u2192 format\n| (t,val) :=\nlet vs := map s.format_expr vs,\n    t := s.format_expr t,\n    vs' := format.join $ vs.intersperse \" \" in\nmatch val with\n | (some val) :=\n     format!\"{vs'} : {t} := {s.format_expr val}\"\n | none := format!\"{vs'} : {t}\"\nend\n\nmeta def get_assumptions : temporal (list expr) :=\ndo `(%%\u0393 \u22a2 _) \u2190 target,\n   ls \u2190 local_context,\n   mfilter (\u03bb l, succeeds $\n    do `(%%\u0393' \u22a2 %%e) \u2190 infer_type l,\n       is_def_eq \u0393 \u0393') ls\n\nmeta def asm_stmt (\u0393 e : expr) : temporal (expr \u00d7 expr \u00d7 option expr) :=\ndo t \u2190 infer_type e,\n   val \u2190 get_local_value e,\n   `(%%\u0393' \u22a2 %%p) \u2190 return t | return (e,t,val),\n   ( do (e,p,val) <$ is_def_eq \u0393 \u0393' ) <|> return (e,t,val)\n\ndef compact {\u03b1 \u03b2 : Type*} [decidable_eq \u03b2] : list (\u03b1 \u00d7 \u03b2) \u2192 list (list \u03b1 \u00d7 \u03b2)\n | [] := []\n | ( (x,y) :: xs ) :=\n   match compact xs with\n    | [] := [ ([x],y) ]\n    | ( (x',y') :: ys ) :=\n      if y = y' then (x::x', y) :: ys\n                else ([x],y) :: (x',y') :: ys\n   end\n\nmeta def temp_to_fmt (g : expr) : temporal (thunk format) :=\ndo  set_goals [g],\n    `(%%\u0393 \u22a2 %%p) \u2190 target | (\u03bb s _, to_fmt s) <$> read,\n    hs \u2190 local_context,\n    hs' \u2190 mmap (asm_stmt \u0393) hs,\n    hs' \u2190 mfilter (\u03bb x : _ \u00d7 _, bnot <$> succeeds (is_def_eq \u0393 x.1)) hs',\n    s \u2190 read,\n    let x := decl_to_fmt s ,\n    return $ \u03bb _, format.intercalate line [format.intercalate (\",\"++line) $ mapp (decl_to_fmt s) \u2218 compact $ hs',format!\"\u22a2 {s.format_expr p}\"]\n\nmeta def save_info (p : pos) : temporal unit :=\ndo cleanup,\n   gs  \u2190 get_goals,\n   let gs' := gs.pw_filter (\u2260),\n   fmt \u2190 mmap temp_to_fmt gs',\n   set_goals gs,\n   tactic.save_info_thunk p (\u03bb _,\n     let header := if fmt.length > 1 then format!\"{fmt.length} goals\\n\" else \"\",\n         eval : thunk format \u2192 format := \u03bb f, f () in\n     if fmt.empty\n       then \"no goals\"\n       else header ++ format.join ((fmt.map eval).intersperse $ line ++ line))\n\nmeta def step {\u03b1 : Type} (c : temporal \u03b1) : temporal unit :=\nc >>[tactic] cleanup\n\nmeta def istep {\u03b1 : Type} (line0 col0 line col : nat) (c : temporal \u03b1) : temporal unit :=\ntactic.istep line0 col0 line col c\n\nmeta def show_tags :=\nget_goals >>= mmap' (\u03bb g, get_tag g >>= (trace : list name \u2192 tactic unit))\n\nmeta def uniform_assumptions' (\u0393 : expr)\n: expr \u2192 expr \u2192 temporal (option (expr \u00d7 expr))\n| h t := do\n   t \u2190 head_beta t,\n   match t with\n    | (expr.pi n bi t' e) :=\n      do l \u2190 mk_local' n bi t',\n         (some (p,t)) \u2190 uniform_assumptions' (h l) (e.instantiate_var l) | return none,\n         let abs := t.lambdas [l],\n         let p' := p.lambdas [l],\n         p \u2190 some <$> (prod.mk <$> to_expr ``( (p_forall_to_fun %%\u0393 %%abs).mpr %%p' )\n                               <*> to_expr ``( p_forall %%abs )),\n         return p\n    | `(%%\u0393' \u22a2 %%p) := (is_def_eq \u0393 \u0393' >> some (h,p) <$ guard (\u00ac \u0393.occurs p))\n    | p := none <$ guard (\u00ac \u0393.occurs p) <|> none <$ match_expr ``(persistent %%\u0393) p\n   end\n\nmeta def protect_tags {\u03b1 : Sort*} (tac : temporal \u03b1) : temporal \u03b1 :=\nwith_enable_tags $\ndo t \u2190 get_main_tag,\n   tac <* set_main_tag t\n\n/-- `fix_assumptions \u0393 h` takes assumptions and reformulate it so that its type is\n    `\u0393 \u22a2 _`. It replaces `\u2200 _, \u0393 \u22a2 _` with `\u0393 \u22a2 \u2200\u2200 _, _` and `_ \u2192 \u0393 \u22a2 _` with\n    `\u0393 \u22a2 _ \u27f6 _`.\n  -/\nmeta def fix_assumptions (\u0393 h : expr) : temporal expr :=\ndo t \u2190 infer_type h,\n   (some r) \u2190 try_core (uniform_assumptions' \u0393 h t),\n   match r with\n    | (some (pr,t)) :=\n          do  p \u2190 to_expr ``(%%\u0393 \u22a2 %%t),\n              protect_tags (\n                assertv h.local_pp_name p pr\n                <* clear h)\n    | none := return h\n   end\n\nmeta def fix_or_clear_assumption (\u0393 h : expr) : temporal unit :=\n() <$ fix_assumptions \u0393 h <|> tactic.clear h\n\nmeta def semantic_assumption (\u03c4 h : expr) : temporal \u2115 :=\ndo `(%%\u03c4' \u22a8 _) \u2190 infer_type h | return 0,\n   (do is_def_eq \u03c4 \u03c4',\n       revert h, `[rw \u2190 eq_judgement],\n       return 1)\n    <|> return 0\n\nmeta def sem_to_syntactic : tactic unit :=\ndo `(%%\u03c4 \u22a8 _) \u2190 target,\n   \u03b1 \u2190 infer_type \u03c4,\n   `[rw \u2190 eq_judgement],\n   r \u2190 local_context >>= mfoldl (\u03bb a h, (+) a <$> semantic_assumption \u03c4 h) 0,\n   tactic.interactive.generalize none () (``(\u2191(eq %%\u03c4) : pred' %%\u03b1), `\u0393),\n   intron r\n\nmeta def execute (c : temporal unit) : tactic unit :=\ndo intros,\n   t \u2190 target,\n   t' \u2190 whnf t,\n   match t' with\n     | `(\u22a9 _) := () <$ tactic.intro `\u0393\n     | `(_ \u27f9 _) := () <$ tactic.intro `\u0393\n     | `(\u2200 \u0393 : pred' _, \u0393 \u22a2 _) := () <$ tactic.intro `\u0393\n     | `(%%\u0393 \u22a2 _) := local_context >>= mmap' (fix_or_clear_assumption \u0393)\n     | _ := to_expr ``(\u22a9 _) >>= tactic.change >> () <$ tactic.intro `\u0393\n          <|> refine ``(@id (_ \u22a8 _) _) >> sem_to_syntactic\n          <|> fail \"expecting a goal of the form `_ \u22a2 _` or `\u22a9 _ `\"\n   end,\n   target >>= whnf >>= unsafe_change,\n   c\n\nmeta def revert (e : expr) : tactic unit :=\ndo `(%%\u0393 \u22a2 _) \u2190 target >>= instantiate_mvars,\n   t \u2190 infer_type e,\n   match t with\n    | `(%%\u0393' \u22a2 _) :=\n      do pp\u0393 \u2190 pp \u0393, pp\u0393' \u2190 pp \u0393',\n         is_def_eq \u0393 \u0393' <|> fail format!\"{pp\u0393'} does not match {pp\u0393'}\",\n         tactic.revert e, applyc `predicate.p_impl_revert\n    | _ := tactic.revert e >> refine ``((p_forall_to_fun %%\u0393 _).mp _)\n   end\n\nsection\nopen tactic.interactive interactive.types\nmeta def interactive.strengthening (tac : itactic) : temporal unit :=\ndo lmms \u2190 attribute.get_instances `strengthening,\n   `(%%\u0393 \u22a2 _) \u2190 target,\n   p \u2190 infer_type \u0393 >>= mk_meta_var,\n   lmms.any_of $ \u03bb l, do\n     r \u2190 tactic.mk_app l [p,\u0393],\n     tactic.refine ``(p_impl_revert %%r _ ),\n     tac\n\nmeta def interactive.apply' (q : parse texpr) : temporal unit :=\ndo l \u2190 t_to_expr_for_apply q,\n   () <$ tactic.apply l <|> interactive.strengthening (() <$ tactic.apply l)\n                        <|> () <$ tactic.apply l -- we try `tactic.apply l` again\n                                                 -- knowing that if we go back to\n                                                 -- it, it will fail and we'll have\n                                                 -- a proper error message\n\nend\n\nmeta def split : temporal unit :=\ndo `(%%\u0393 \u22a2 %%p \u22c0 %%q) \u2190 target,\n   interactive.apply ``(p_and_intro %%p %%q %%\u0393 _ _)\n\nmeta def consequent (e : expr) : temporal expr :=\ndo `(_ \u22a2 %%p) \u2190 infer_type e,\n   return p\n\nlemma to_antecendent (xs : list (cpred))\n  (H : list_persistent xs)\n  (p : cpred)\n  (h : \u25fb xs.foldr (\u22c0) True \u22a2 p)\n: \u2200 \u0393, with_h_asms \u0393 xs p :=\nbegin\n  intro,\n  replace h := \u03bb h', judgement_trans \u0393 _ _ h' h,\n  induction H with x xs,\n  { simp at h, simp [with_h_asms,h] with tl_simp, },\n  { simp at h, simp_intros [with_h_asms], resetI,\n    apply H_ih , intros,\n    apply h,\n    rw henceforth_and,\n    simp [is_persistent],\n    begin [temporal]\n      split,\n      assumption,\n      assumption,\n    end }\nend\n\ninductive entails_all {\u03b2} (\u0393 : pred' \u03b2) : list (pred' \u03b2) \u2192 Prop\n | nil : entails_all []\n | cons (x : pred' \u03b2) (xs : list $ pred' \u03b2)\n   : \u0393 \u22a2 x \u2192 entails_all xs \u2192\n     entails_all (x :: xs)\n\nlemma entails_all_subst_left {\u03b2}\n  (p q : pred' \u03b2)\n  (rs : list $ pred' \u03b2)\n  (h : p \u27f9 q)\n  (h' : entails_all q rs)\n: entails_all p rs :=\nbegin\n  induction h'\n  ; constructor,\n  { revert h'_a,\n    apply revert_p_imp' h },\n  { assumption, }\nend\n\nlemma to_antecendent' (xs : list (cpred)) (p : cpred)\n  (ps : list_persistent xs)\n  (h : \u2200 \u0393 [persistent \u0393], with_h_asms \u0393 xs p)\n: \u2200 \u0393, with_h_asms \u0393 xs p :=\nbegin\n  apply to_antecendent _ ps,\n  have : entails_all (\u25fblist.foldr p_and True xs) xs,\n  { clear h ps,\n    induction xs with x xs ; constructor,\n    { apply indirect_judgement,\n      simp_intros \u0393 h [henceforth_and],\n      apply henceforth_str x \u0393 h.left, },\n    { revert xs_ih, apply entails_all_subst_left,\n      simp [henceforth_and] } },\n  specialize h (\u25fblist.foldr p_and True xs),\n  revert this h, generalize : \u25fblist.foldr p_and True xs = \u0393,\n  intros h' h,\n  induction ps with x xs,\n  { simp [with_h_asms] at h,\n    apply h },\n  { apply_assumption ; cases h', assumption,\n    simp [with_h_asms] at h,\n    solve_by_elim, }\nend\n\nopen tactic tactic.interactive (unfold_coes unfold itactic assert_or_rule)\nopen interactive interactive.types lean lean.parser\nopen applicative (mmap\u2082 lift\u2082)\nopen functor\nlocal postfix `?`:9001 := optional\nsection persistently\n\nmeta def is_henceforth (e : expr) : temporal bool :=\ndo `(_ \u22a2 %%t) \u2190 infer_type e | return tt,\n   succeeds $\n     to_expr ``(persistent %%t) >>= mk_instance\n\nprivate meta def mk_type_list (\u0393 pred_t : expr)  : list expr \u2192 temporal (expr \u00d7 expr)\n | [] := do\n   lift\u2082 prod.mk (to_expr ``(@list.nil cpred))\n                 (to_expr ``(temporal.list_persistent.nil_persistent))\n | (x :: xs) :=\n   do (es,is) \u2190 mk_type_list xs,\n      v  \u2190 mk_meta_var pred_t,\n      `(_ \u22a2 %%c) \u2190 infer_type x, c' \u2190 pp c,\n      ls \u2190 to_expr ``(list.cons %%c %%es),\n      inst\u2080 \u2190 to_expr ``(persistent %%c) >>= mk_instance,\n      inst \u2190 tactic.mk_mapp `temporal.list_persistent.cons_persistent [c,es,inst\u2080,is],\n      return (ls,inst)\n\nmeta def is_context_persistent : temporal bool :=\ndo `(%%\u0393 \u22a2 _) \u2190 target | return ff,\n   (tt <$ (to_expr ``(persistent %%\u0393) >>= mk_instance)) <|>\n     return ff\nopen list\nmeta def create_persistent_context : temporal unit :=\ndo b \u2190 is_context_persistent,\n   when (\u00ac b) $ do\n     asms \u2190 get_assumptions,\n     `(%%\u0393 \u22a2 %%p) \u2190 target >>= instantiate_mvars,\n     pred_t \u2190 infer_type \u0393,\n     \u0393 \u2190 get_local \u0393.local_pp_name,\n     (asms',inst) \u2190 mk_type_list \u0393 pred_t asms,\n     r \u2190 tactic.revert_lst (\u0393 :: asms : list _).reverse,\n     guard (r = asms.length + 1) <|> fail format!\"wrong use of context {\u0393}\",\n     ts \u2190 mmap consequent asms,\n     hnm \u2190 mk_fresh_name,\n     h \u2190 to_expr  ``(@to_antecendent' %%asms' %%p %%inst) >>= note hnm none,\n     tactic.interactive.simp none tt [simp_arg_type.expr ``(temporal.with_h_asms)] [] (loc.ns [hnm]),\n     h \u2190 get_local hnm,\n     refine ``(%%h _),\n     -- -- `[simp only [temporal.with_h_asms]],\n     intro_lst $ \u0393.local_pp_name :: `_ :: asms.map expr.local_pp_name,\n     resetI,\n     get_local hnm >>= tactic.clear\n\nmeta def interactive.persistent (excp : parse without_ident_list) : temporal unit :=\ndo b \u2190 is_context_persistent,\n   when (\u00ac b) $ do\n     hs  \u2190 get_assumptions,\n     hs' \u2190 hs.mfilter (map bnot \u2218 is_henceforth),\n     excp' \u2190 mmap get_local excp,\n     mmap' tactic.clear (hs'.diff excp'),\n     when excp.empty\n       create_persistent_context\n\nmeta def persistently (tac : itactic) : temporal unit :=\nfocus1 $\ndo create_persistent_context,\n      -- calling tac\n   x \u2190 focus1 tac,\n      -- restore context to \u0393\n   done <|> (do\n     to_expr ```(_ \u22a2 _) >>= change)\n   <|> (do\n     to_expr ```(\u22a9 _) >>= change,\n     `(\u22a9 %%q) \u2190 target,\n     () <$ intro `\u0393)\nend persistently\n\nsection lemmas\nopen list\n\nlemma judgement_congr {\u0393 p q : cpred}\n  (h : \u0393 \u22a2 p \u2261 q)\n: \u0393 \u22a2 p = \u0393 \u22a2 q :=\nby { apply iff.to_eq, split ; intro h' ;\n     lifted_pred using h h' ; cc }\n\ndef with_asms {\u03b2} (\u0393 : pred' \u03b2) : \u03a0 (xs : list (string \u00d7 pred' \u03b2)) (x : pred' \u03b2), Prop\n | [] x := \u0393 \u22a2 x\n | ((h,x) :: xs) y := \u0393 \u22a2 x \u2192 with_asms xs y\n\ndef tl_seq {\u03b2} (xs : list (string \u00d7 pred' \u03b2)) (x : pred' \u03b2) : Prop :=\n\u2200 \u0393, with_asms \u0393 xs x\n\nlemma p_forall_intro_asms_aux {\u03b2 t} (ps : list (string \u00d7 pred' \u03b2))\n  (\u03c6 : pred' \u03b2) (q : t \u2192 pred' \u03b2)\n  (h : \u2200 x \u0393, \u0393 \u22a2 \u03c6 \u2192 with_asms \u0393 ps (q x))\n  (\u0393 : pred' \u03b2)\n  (h' : \u0393 \u22a2 \u03c6 )\n: with_asms \u0393 ps (p_forall q) :=\nbegin\n  induction ps generalizing \u03c6,\n  case list.nil\n  { simp [with_asms] at h \u22a2,\n    rw p_forall_to_fun,\n    introv, apply h _ , exact h', },\n  case list.cons : p ps\n  { cases p with n p,\n    simp [with_asms] at h \u22a2,\n    intro hp,\n    have h_and := (p_and_intro \u03c6 p \u0393) h' hp,\n    revert h_and,\n    apply ps_ih,\n    intros, apply_assumption,\n    apply p_and_elim_left \u03c6 p \u0393_1 a,\n    apply p_and_elim_right \u03c6 p \u0393_1 a,  }\nend\n\nlemma p_forall_intro_asms {t \u03b2} (ps : list (string \u00d7 pred' \u03b2)) (q : t \u2192 pred' \u03b2)\n  (h : \u2200 x, tl_seq ps (q x))\n: tl_seq ps (p_forall q) :=\nbegin\n  intro,\n  apply p_forall_intro_asms_aux _ True,\n  { intros, apply h },\n  simp\nend\n\nlemma p_imp_intro_asms_aux {\u03b2} (ps : list (string \u00d7 pred' \u03b2))\n  (\u03c6 q r : pred' \u03b2) (n : string)\n  (h : \u2200 \u0393, \u0393 \u22a2 \u03c6 \u2192 with_asms \u0393 (ps ++ [(n,q)]) r)\n  (\u0393 : pred' \u03b2)\n  (h' : \u0393 \u22a2 \u03c6 )\n: with_asms \u0393 ps (q \u27f6 r) :=\nbegin\n  induction ps generalizing \u03c6,\n  case list.nil\n  { simp [with_asms] at h \u22a2,\n    apply p_imp_intro _,\n    { introv h\u2080, apply h _ , exact h\u2080, },\n    solve_by_elim, },\n  case list.cons : p ps\n  { cases p with n p,\n    simp [with_asms] at h \u22a2,\n    intro hp,\n    have h_and := (p_and_intro \u03c6 p \u0393) h' hp,\n    revert h_and,\n    apply ps_ih,\n    intros, apply_assumption,\n    apply p_and_elim_left \u03c6 p \u0393_1 a,\n    apply p_and_elim_right \u03c6 p \u0393_1 a,  }\nend\n\nlemma p_imp_intro_asms {\u03b2} (ps : list (string \u00d7 pred' \u03b2))\n  (q r : pred' \u03b2) (n : string)\n  (h : tl_seq (ps ++ [(n,q)]) r)\n: tl_seq ps (q \u27f6 r) :=\nbegin\n  intro, apply p_imp_intro_asms_aux _ True,\n  { intros, apply h },\n  simp\nend\n\n-- lemma canonical_sequent {\u03b2} (\u0393 p : pred' \u03b2)\n-- : \u0393 \u22a2 p \u2194 (\u2200 \u0393', \u0393' \u22a2 \u0393 \u2192 \u0393' \u22a2 p) :=\n-- begin\n--   split ; intro,\n--   { intros, transitivity ; assumption },\n--   apply_assumption, refl\n-- end\n\nend lemmas\n\nprivate meta def mk_type_list : list expr \u2192 temporal expr\n | [] := to_expr ``(list.nil)\n | (x :: xs) :=\n   do es \u2190 mk_type_list xs,\n      `(_ \u22a2 %%t) \u2190 infer_type x,\n      let n := x.local_pp_name.to_string,\n      to_expr ``(list.cons (%%(reflect n), %%t) %%es)\nopen list (cons)\n\nprivate meta def parse_list : expr \u2192 temporal (list (name \u00d7 expr))\n | `([]) := pure []\n | `( list.cons (%%n,%%e) %%es ) :=\n do n' \u2190 eval_expr _ n,\n    (::) (mk_simple_name n',e) <$> parse_list es\n | _ := pure []\n\nprivate meta def enter_list_state : temporal (expr \u00d7 list expr \u00d7 expr) :=\ndo `(%%\u0393 \u22a2 %%p) \u2190 target,\n   ls \u2190 get_assumptions,\n   ls' \u2190 mk_type_list ls,\n   r \u2190 revert_lst (\u0393 :: ls : list _).reverse,\n   let k := ls.length + 1,\n   guard (r = k)\n         <|> fail format!\"wrong use of context {\u0393}: {r} \u2260 {k}\",\n   to_expr ``(tl_seq %%ls' %%p) >>= unsafe_change,\n   return (\u0393, ls, ls')\n\nprivate meta def exit_list_state : temporal (list expr) :=\ndo `(tl_seq %%ps %%g) \u2190 target | return [],\n   tactic.interactive.unfold\n        [ `has_append.append\n        , `list.append] (loc.ns [none]),\n   `(tl_seq %%ps %%g) \u2190 target,\n   ps' \u2190 parse_list ps,\n   tactic.interactive.unfold\n        [ `temporal.tl_seq\n        , `temporal.with_asms ] (loc.ns [none]),\n   tactic.intro_lst (`\u0393 :: ps'.map prod.fst)\n\nprivate meta def within_list_state {\u03b1} (tac : expr \u2192 temporal \u03b1) : temporal \u03b1 :=\ndo (\u0393,ls,ls') \u2190 enter_list_state,\n   tac ls' <* do\n      tactic.interactive.unfold\n        [ `temporal.with_asms\n        , `temporal.tl_seq\n        , `has_append.append\n        , `list.append] (loc.ns [none]),\n      tactic.intro_lst ((\u0393 :: ls : list _).map expr.local_pp_name)\n\nmeta def intro_aux (n : option name) : temporal (expr \u2295 name) :=\ndo ( to_expr ``(tl_seq _ (_ \u27f6 _)) >>= change\n       <|> to_expr ``(tl_seq _ (p_forall _)) >>= change ),\n   `(tl_seq %%ps %%g) \u2190 target >>= instantiate_mvars,\n   match g with\n    | `(%%p \u27f6 %%q)  :=\n      do let h := n.get_or_else `_,\n         tactic.refine ``(p_imp_intro_asms %%ps %%p %%q %%(reflect h.to_string) _),\n         return $ sum.inr h\n    | `(p_forall %%P) :=\n      do let h := n.get_or_else `_,\n         tactic.refine ``(p_forall_intro_asms %%ps %%P _),\n         x \u2190 intro h,\n         P' \u2190 head_beta (P x),\n         to_expr ``(tl_seq %%ps %%P') >>= unsafe_change ,\n         return $ sum.inl x\n    | _ := fail \"expecting `_ \u27f6 _` or `\u2200\u2200 _, _`\"\n   end\n\ndef cons_opt {\u03b1 \u03b2} : \u03b1 \u2295 \u03b2 \u2192 list \u03b1 \u00d7 list \u03b2 \u2192 list \u03b1 \u00d7 list \u03b2\n | (sum.inr y) (xs,ys) := (xs,    y::ys)\n | (sum.inl x) (xs,ys) := (x::xs, ys   )\n\nmeta def intro_lst : option (list name) \u2192 temporal (list expr \u00d7 list name)\n | none := (cons_opt <$> intro_aux none <*> intro_lst none) <|> pure ([],[])\n | (some []) := return ([],[])\n | (some (x::xs)) := cons_opt <$> intro_aux (some x) <*> intro_lst (some xs)\n\nmeta def get_one_name : option (list name) \u2192 option (name \u00d7 option (list name))\n | none := some (`_, none)\n | (some []) := none\n | (some (x::xs)) := some (x, some xs)\n\nopen list (hiding map)\n\nmeta def intros : option (list name) \u2192 temporal (list expr)\n| ns :=\ndo some (n,ns') \u2190 pure (get_one_name ns) | return [],\n   mcond (succeeds $ to_expr ``(_ \u22a2 _ \u27f6 _) >>= change <|>\n                     to_expr ``(_ \u22a2 p_forall _) >>= change)\n   (do g \u2190 target,\n       match g with\n        | `(%%\u0393 \u22a2 %%p \u27f6 %%q)  := do\n          try (to_expr ``(persistent %%\u0393) >>= mk_instance >>= clear),\n          (es,ls') \u2190 within_list_state (\u03bb _, intro_lst ns),\n          (++) es <$> tactic.intro_lst ls'\n        | `(%%\u0393 \u22a2 p_forall (\u03bb _, %%P)) := do\n          refine ``((p_forall_to_fun %%\u0393 (\u03bb _, %%P)).mpr _),\n          n \u2190 tactic.intro n,\n          to_expr ``(%%\u0393 \u22a2 %%(P.instantiate_var n)) >>= change,\n          cons n <$> intros ns'\n        | _ := fail \"expecting `_ \u27f6 _` or `\u2200\u2200 _, _`\"\n       end)\n   (return [])\n\nmeta def intro1 (n : option name) : temporal expr :=\ndo to_expr ``(_ \u22a2 _ \u27f6 _) >>= change <|>\n      to_expr ``(_ \u22a2 p_forall _) >>= change <|>\n      fail \"expecting `_ \u27f6 _` or `\u2200\u2200 _, _`\",\n   g \u2190 target,\n   match g with\n    | `(%%\u0393 \u22a2 %%p \u27f6 %%q)  := do\n      try (to_expr ``(persistent %%\u0393) >>= mk_instance >>= clear),\n      let h := n.get_or_else `_,\n      within_list_state (\u03bb ps, tactic.refine ``(p_imp_intro_asms %%ps %%p %%q %%(reflect h.to_string) _)),\n      intro h\n    | `(%%\u0393 \u22a2 p_forall (\u03bb _, %%P)) := do\n      refine ``((p_forall_to_fun %%\u0393 (\u03bb _, %%P)).mpr _),\n      n \u2190 tactic.intro $ n.get_or_else `_,\n      n <$ (to_expr ``(%%\u0393 \u22a2 %%(P.instantiate_var n)) >>= change)\n    | _ := fail \"expecting `_ \u27f6 _` or `\u2200\u2200 _, _`\"\n   end\n\n/-- Introduces new hypotheses with forward dependencies -/\nmeta def intros_dep : tactic (list expr) :=\ndo g \u2190 target | return [],\n   match g with\n    | `(_ \u22a2 p_forall _) := lift\u2082 (::) (intro1 none) intros_dep\n    | `(tl_seq %%ps (p_forall %%P)) :=\n      do tactic.refine ``(p_forall_intro_asms %%ps %%P _),\n         x \u2190 intro  P.binding_name,\n         P' \u2190 head_beta (P x),\n         to_expr ``(tl_seq %%ps %%P') >>= unsafe_change ,\n         cons x <$> intros_dep\n    | _ := return []\n   end\n\n@[user_attribute]\nmeta def lifted_congr_attr : user_attribute :=\n{ name := `lifted_congr\n, descr := \"congruence lemmas for temporal logic\" }\n\n@[user_attribute]\nmeta def timeless_congr_attr : user_attribute :=\n{ name := `timeless_congr\n, descr := \"congruence lemmas for temporal logic\" }\n\nmeta def apply_lifted_congr : tactic unit :=\ndo xs \u2190 attribute.get_instances `lifted_congr,\n   xs.any_of (\u03bb thm, do l \u2190 resolve_name thm >>= to_expr, apply l),\n   return ()\n\nmeta def apply_timeless_congr : tactic unit :=\ndo xs \u2190 attribute.get_instances `timeless_congr,\n   xs.any_of (\u03bb thm, do l \u2190 resolve_name thm >>= to_expr, () <$ apply l) <|> apply_lifted_congr\n\nmeta def force (p : pexpr) (e : expr) : tactic expr :=\ndo p' \u2190 to_expr p,\n   unify e p',\n   instantiate_mvars p' <* cleanup\n\nmeta def app_ctx_aux (g : expr \u2192 expr)\n: list (expr \u2192 expr) \u2192 list expr \u2192 expr \u2192 list ( (expr \u2192 expr) \u00d7 expr )\n| r\u2080 r\u2081 (expr.app f a) := app_ctx_aux ((\u03bb e, g $ f.mk_app (e :: r\u2081)) :: r\u2080) (a :: r\u2081) f\n| r\u2080 r\u2081 e         := list.zip r\u2080 r\u2081\n\nmeta def app_ctx (g : expr \u2192 expr)\n: expr \u2192 list ( (expr \u2192 expr) \u00d7 expr ) :=\napp_ctx_aux g [] []\n\nmeta def match_context_core : pattern \u2192 list ((expr \u2192 expr) \u00d7 expr) \u2192 tactic (expr \u2192 expr)\n| p []      := failed\n| p ((f,e)::es) :=\n  f <$ match_pattern p e\n  <|>\n  match_context_core p es\n  <|>\n  if e.is_app\n  then match_context_core p (app_ctx f e)\n  else failed\n\nmeta def match_context (p : pexpr) (e : expr) : tactic (expr \u2192 expr) :=\ndo new_p \u2190 pexpr_to_pattern p,\n   match_context_core new_p [(id,e)]\n\nlemma v_eq_symm_h {\u03b1} {\u0393 : cpred} {v\u2080 v\u2081 : tvar \u03b1}\n  (h : \u0393 \u22a2 \u25fb(v\u2081 \u2243 v\u2080))\n: \u0393 \u22a2 \u25fb(v\u2080 \u2243 v\u2081) :=\nbegin\n  revert h, apply p_impl_revert,\n  revert \u0393, change (_ \u27f9 _),\n  mono,\n  lifted_pred, intro h, rw h\nend\n\nmeta def temporal_eq_proof (\u0393 h' x' y' t : expr) (hence : bool) (cfg : rewrite_cfg := {})\n: tactic (expr \u00d7 expr \u00d7 list expr) :=\ndo let (x,y) := if cfg.symm then (y',x')\n                            else (x',y'),\n   err \u2190 pp x,\n   ctx \u2190 match_context (to_pexpr x) t <|> fail format!\"no instance of {err} found\",\n   let t' := ctx y,\n   p \u2190 to_expr ``(%%\u0393 \u22a2 %%t \u2243 %%t'),\n   ((),prf) \u2190 solve_aux p (do\n   if hence then do\n     h \u2190 if cfg.symm then to_expr ``(v_eq_symm_h %%h')\n                     else return h',\n     h' \u2190 mk_fresh_name,\n     note h' none h,\n     interactive.persistent [],\n     h \u2190 get_local h',\n     `(%%\u0393 \u22a2 _) \u2190 target,\n     rule \u2190 to_expr ``(predicate.p_impl_revert (henceforth_str _ %%\u0393) %%h) <|> pure h,\n     repeat (() <$ apply rule <|> refine ``(v_eq_refl _ _) <|> apply_timeless_congr),\n     all_goals $\n       exact rule,\n     return ()\n   else do\n     h \u2190 if cfg.symm then to_expr ``(v_eq_symm %%h')\n                     else return h',\n     repeat (() <$ apply h <|> refine ``(v_eq_refl _ _) <|> apply_lifted_congr),\n     done),\n   prf' \u2190 to_expr ``(judgement_congr %%prf),\n   new_t \u2190 to_expr ``(%%\u0393 \u22a2 %%t'),\n   return (new_t,prf',[])\n\nmeta def tmp_head : expr \u2192 temporal expr | e :=\ndo t \u2190 infer_type e >>= whnf,\n   match t with\n     | (expr.pi v bi e\u2080 e\u2081) :=\n       do v \u2190 mk_meta_var e\u2080,\n          tmp_head (e v)\n     | `(_ \u22a2 _) :=\n       do v \u2190 mk_mvar,\n          t_to_expr ``(%%e %%v) >>= tmp_head <|> return e\n     | _ := return e\n   end\n\n-- this is to justify using `whnf` before pattern matching when dealing w\n-- with sequents\nrun_cmd do\nv\u2080 \u2190 mk_local_def `v `(cpred),\ne \u2190 to_expr ``(%%v\u2080 \u22a2 %%v\u2080 \u27f6 %%v\u2080),\ne' \u2190 whnf e,\nguard (e' = e) <|> fail \"_ \u22a2 _ \u27f6 _ does not reduce to itself\"\n\n/--\n Must distinguish between three cases on the shape of assumptions:\n h : \u0393 \u22a2 \u25fd(x \u2261 y)\n h : x = y\n h : x \u2194 y\n\n two cases on the shape of target:\n e: f x\n e: \u0393 \u22a2 f x\n\n two cases on the shape of target:\n h : \u0393 \u22a2 \u25fd(x \u2261 y) \u2192 \u0393 \u22a2 f x = f y\n\n h : \u0393 \u22a2 \u25fd(x \u2261 y) \u2192 \u0393 \u22a2 f x = \u0393 \u22a2 f y\n h : \u0393 \u22a2 \u25fd(x \u2261 y) \u2192 \u0393 \u22a2 f x \u2261 f y\n h : \u0393 \u22a2 \u25fd(x \u2261 y) \u27f6 f x \u2261 f y\n h : \u22a9 \u25fd(x \u2261 y) \u27f6 f x \u2261 f y\n -/\nmeta def rewrite_tmp (\u0393 h : expr) (e : expr) (cfg : rewrite_cfg := {}) : tactic (expr \u00d7 expr \u00d7 list expr) :=\ndo e \u2190 instantiate_mvars e >>= whnf,\n   match e with\n    | e'@`(%%\u0393t \u22a2 %%e) :=\n    do h \u2190 tmp_head h,\n       ht \u2190 infer_type h >>= whnf,\n       match ht with\n         | `(%%\u0393r \u22a2 \u25fb%%p) :=\n           do `(%%x \u2243 %%y) \u2190 force ``(_ \u2243 _) p,\n              temporal_eq_proof \u0393 h x y e tt cfg\n         | `(%%\u0393r \u22a2 %%p) :=\n           do `(%%x \u2243 %%y) \u2190 force ``(_ \u2243 _) p,\n              b \u2190 try_core $ to_expr ``(persistent %%\u0393r) >>= mk_instance,\n              temporal_eq_proof \u0393 h x y e b.is_some cfg\n         | _ :=\n           do (new_t, prf, metas) \u2190 rewrite_core h e cfg,\n              prf' \u2190 to_expr ``(congr_arg (judgement %%\u0393t) %%prf),\n              new_t' \u2190 to_expr ``(judgement %%\u0393t %%new_t),\n              try_apply_opt_auto_param cfg.to_apply_cfg metas,\n              (new_t', prf', metas) <$ is_def_eq \u0393 \u0393t <|> pure (new_t,prf,metas)\n       end\n     | _ := do\n          (new_t, prf, metas) \u2190 rewrite_core h e cfg,\n          try_apply_opt_auto_param cfg.to_apply_cfg metas,\n          return (new_t, prf, metas)\n   end\n\nmeta def rewrite_target (\u0393 h : expr) (cfg : rewrite_cfg := {}) : tactic unit :=\ndo t \u2190 target,\n   (new_t, prf, _) \u2190 rewrite_tmp \u0393 h t cfg,\n   e \u2190 to_expr ``(%%t = %%new_t),\n   replace_target new_t prf\n\nmeta def rewrite_hyp (\u0393 h : expr) (hyp : expr) (cfg : rewrite_cfg := {}) : tactic expr :=\ndo hyp_type \u2190 infer_type hyp,\n   (new_hyp_type, prf, _) \u2190 rewrite_tmp \u0393 h hyp_type cfg,\n   replace_hyp hyp new_hyp_type prf\n\nmeta def rw_goal (\u0393 : expr) (cfg : rewrite_cfg) (rs : list rw_rule) : temporal unit :=\nrs.mmap' $ \u03bb r, do\n save_info r.pos,\n eq_lemmas \u2190 get_rule_eqn_lemmas r,\n orelse'\n   (do e \u2190 to_expr' r.rule, rewrite_target \u0393 e {symm := r.symm, ..cfg})\n   (eq_lemmas.mfirst $ \u03bb n, do e \u2190 mk_const n, rewrite_target \u0393 e {symm := r.symm, ..cfg})\n   (eq_lemmas.empty)\n\nprivate meta def uses_hyp (e : expr) (h : expr) : bool :=\ne.fold ff $ \u03bb t _ r, r || to_bool (t = h)\n\nmeta def rw_hyp (\u0393 : expr) (cfg : rewrite_cfg) : list rw_rule \u2192 expr \u2192 temporal unit\n| []      hyp := skip\n| (r::rs) hyp := do\n  save_info r.pos,\n  eq_lemmas \u2190 get_rule_eqn_lemmas r,\n  orelse'\n    (do e \u2190 to_expr' r.rule,\n        when (not (uses_hyp e hyp)) $\n          rewrite_hyp \u0393 e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)\n    (eq_lemmas.mfirst $ \u03bb n, do e \u2190 mk_const n, rewrite_hyp \u0393 e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)\n    (eq_lemmas.empty)\n\nmeta def rewrite (rs : rw_rules_t) (loca : loc) (cfg : rewrite_cfg) : temporal unit :=\ndo `(%%\u0393 \u22a2 _) \u2190 target,\n   match loca with\n   | loc.wildcard := loca.try_apply (rw_hyp \u0393 cfg rs.rules) (rw_goal \u0393 cfg rs.rules)\n   | _            := loca.apply (rw_hyp \u0393 cfg rs.rules) (rw_goal \u0393 cfg rs.rules)\n   end,\n   try (reflexivity reducible : temporal _),\n   (returnopt rs.end_pos >>= save_info <|> skip)\n\nmeta def solve1 : temporal unit \u2192 temporal unit :=\ntactic.interactive.solve1\n\nprotected meta def note (h : name) : option expr \u2192 expr \u2192 temporal expr\n | none  pr :=\ndo p \u2190 infer_type pr >>= beta_reduction,\n   assertv h p pr\n | (some p)  pr := assertv h p pr\n\n/-- bind the initial value of state-dependent expression\n    `e` to global (through time) name `n`\n  -/\nmeta def bind_name (e : expr) (n h : name) : temporal expr :=\ndo refine ``(one_point_elim _ _ %%e _),\n   x \u2190 tactic.intro n,\n   temporal.intros (some [h]),\n   return x\n\nmeta def existsi (e : expr) (id : name) : temporal unit :=\ndo `(%%\u0393 \u22a2 \u2203\u2203 _ : %%t, %%intl) \u2190 target,\n   infer_type \u0393 >>= match_expr ``(cpred),\n   let r := e.get_app_fn,\n   let v := if r.is_constant\n            then update_name (\u03bb s, s ++ \"\u2080\") (strip_prefix r.const_name)\n            else if r.is_local_constant\n            then update_name (\u03bb s, s ++ \"\u2080\") r.local_pp_name\n            else `v\u2080,\n   t' \u2190 infer_type e,\n   w \u2190 (match_expr ``(tvar %%t) t' >> (bind_name e v id) <|> return e),\n   refine ``(p_exists_to_fun %%w _)\n\nmeta def specialized_apply (t : expr) : expr \u2192 temporal unit\n | e :=\ndo t' \u2190 infer_type e,\n   type_check e,\n   if sizeof t' < sizeof t then () <$ tactic.apply e\n   else\n     () <$ tactic.apply e <|>\n   do\n     v \u2190 mk_mvar,\n     e' \u2190 mk_tmp_app e v,\n     specialized_apply e'\n\nmeta def apply (e : expr) : temporal unit :=\ndo g :: gs \u2190 get_goals,\n   t \u2190 target,\n   specialized_apply t e\n         <|> interactive.strengthening (specialized_apply t e)\n         <|> () <$ tactic.apply e,    -- we try `tactic.apply l` again\n                                      -- knowing that if we go back to\n                                      -- it, it will fail and we'll have\n                                      -- a proper error message\n   gs' \u2190 get_goals, set_goals gs',\n   all_goals (try (execute (pure ()))),\n   gs' \u2190 get_goals, set_goals (gs' ++ gs)\n\nnamespace interactive\nopen lean.parser interactive interactive.types lean\nopen expr -- tactic.interactive (rcases_parse rcases_parse.invert)\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nprecedence `[|`:1024\nprecedence `|]`:0\n\nmeta def abstract_names_p (f : name \u2192 option \u2115) : \u2115 \u2192 pexpr \u2192 pexpr\n | k e@(expr.local_const _ n _ _) := option.cases_on (f n) e (\u03bb i, expr.var $ i + k)\n | k e@(expr.const n _) := option.cases_on (f n) e expr.var\n | k e@(var n)  := e\n | k e@(sort l) := e\n | k e@(mvar n m t)   := e\n | k (app e\u2080 e\u2081) := app (abstract_names_p k e\u2080) (abstract_names_p k e\u2081)\n | k (lam n bi e t) := lam n bi (abstract_names_p k e) (abstract_names_p (k+1) t)\n | k (pi n bi e t) := pi n bi (abstract_names_p k e) (abstract_names_p (k+1) t)\n | k (elet n g e b) := elet n (abstract_names_p k g) (abstract_names_p k e) (abstract_names_p (k+1) b)\n | k (macro d args) := macro d $ args.map (abstract_names_p k)\n\nmeta def var_type : pexpr \u2192 pexpr\n | (app _ t) := t\n | t := t\n\nmeta def lambdas_p_aux : list pexpr \u2192 pexpr \u2192 pexpr\n | (local_const _ n bi t :: ts) e := lambdas_p_aux ts $ lam n bi (var_type t) e\n | _ e := e\n\ndef index_of {\u03b1} [decidable_eq \u03b1] (xs : list \u03b1) (x : \u03b1) : option \u2115 :=\nlet r := list.index_of x xs in\nif r < xs.length then r\n                 else none\n\nmeta def lambdas_p (vs : list pexpr) (e : pexpr) : pexpr :=\nlambdas_p_aux vs (abstract_names_p (index_of (vs.map expr.local_pp_name)) 0 e)\n\nmeta def mk_app_p : pexpr \u2192 list pexpr \u2192 pexpr\n | e (e' :: es) := mk_app_p ``(var_seq %%e %%e') es\n | e [] := e\n\n@[user_notation]\nmeta def scoped_var (_ : parse $ tk \"[|\")\n  (ls : parse $ ident* <* tk \",\")\n  (e : parse  $ texpr  <* tk \"|]\") : lean.parser pexpr :=\ndo vs \u2190 ls.mmap (\u03bb pp_n, do (e,_) \u2190 with_input texpr pp_n.to_string,\n                            return e ),\n   let r := mk_app_p ``( \u27ea \u2115, %%(lambdas_p vs.reverse e) \u27eb ) vs,\n   return r\n\nmeta def skip : temporal unit :=\ntactic.skip\n\nmeta def done : temporal unit :=\ntactic.done\n\nmeta def itactic : Type :=\ntemporal unit\n\nmeta def timetac (s : string) (tac : itactic) : temporal unit :=\ntactic.timetac s tac\n\nmeta def solve1 : itactic \u2192 temporal unit :=\ntactic.interactive.solve1\n\nmeta def clear : parse ident* \u2192 tactic unit :=\ntactic.clear_lst\n\nmeta def explicit\n  (st : parse (ident <|> pure `\u03c3))\n  (tac : tactic.interactive.itactic) : temporal unit :=\ndo `(%%\u0393 \u22a2 _) \u2190 target,\n   asms \u2190 get_assumptions,\n   constructor,\n   st \u2190 tactic.intro st,\n   h\u0393 \u2190 tactic.intro `h\u0393,\n   asms.for_each (\u03bb h, do\n     e \u2190 to_expr ``(judgement.apply %%h %%st %%h\u0393),\n     note h.local_pp_name none e,\n     tactic.clear h),\n   try $ tactic.interactive.simp none ff\n       (map simp_arg_type.expr [``(function.comp),``(temporal.init)]) []\n       (loc.ns $ none :: map (some \u2218 expr.local_pp_name) asms),\n   done <|> solve1 (do\n     tactic.clear h\u0393,\n     try (to_expr ``(temporal.persistent %%\u0393) >>= mk_instance >>= tactic.clear),\n     tactic.clear \u0393,\n     tac)\n\nmeta def list_state_vars (t : expr) : tactic (list expr) :=\ndo ls \u2190 local_context,\n   pat \u2190 pexpr_to_pattern ``(var %%t _),\n   ls.mfilter (\u03bb v, do t \u2190 infer_type v,\n                       tt <$ match_pattern pat t <|> pure ff)\n\nmeta def reverting {\u03b1} (h : expr \u2192 tactic bool) (tac : tactic \u03b1) : tactic \u03b1 :=\ndo ls \u2190 local_context,\n   hs \u2190 ls.mfilter h,\n   tactic.revert_lst hs,\n   tac <* tactic.intro_lst (hs.map expr.local_pp_name)\n\nmeta def rename' (curr : expr) (new : name) : tactic expr :=\ndo n \u2190 tactic.revert curr,\n   tactic.intro new\n   <* tactic.intron (n - 1)\n\nstructure explicit_opts :=\n  (verbose := ff)\n\nmeta def subst_state_variables (\u03c3 : expr) (p : explicit_opts) : tactic unit :=\ndo vs \u2190 list_state_vars `(\u2115),\n   let ns := name_set.of_list (vs.map expr.local_uniq_name),\n   vs' \u2190 reverting (\u03bb h, do t \u2190 infer_type h, return $ t.has_local_in ns) (do\n     vs.mmap $ \u03bb v, do\n       let n := v.local_pp_name,\n       let n_primed := update_name (\u03bb s, s ++ \"'\") v.local_pp_name,\n       n' \u2190 mk_fresh_name,\n       v \u2190 rename v.local_pp_name n' >> get_local n',\n       p \u2190 to_expr ``(%%\u03c3 \u22a8 %%v),\n       try (generalize p n >> tactic.intro1),\n       p' \u2190 to_expr ``(nat.succ %%\u03c3 \u22a8 %%v),\n       try (generalize p' n_primed >> tactic.intro1),\n       return v),\n   -- ls \u2190 local_context >>= mfilter (\u03bb h, do t \u2190 infer_type h, return $ \u03c3.occurs t),\n   when p.verbose trace_state,\n   tactic.clear \u03c3,\n   mmap' tactic.clear vs'.reverse\n\nmeta def resetI : temporal unit := tactic.interactive.resetI\n\nopen function\nmeta def explicit'\n  (iota : parse (tk \"!\")?)\n  (keep_all : parse (tk \"*\")?)\n  (rs : parse simp_arg_list)\n  (hs : parse with_ident_list)\n  (tac : tactic.interactive.itactic)\n  (opt : explicit_opts := {})\n: temporal unit :=\nsolve1 $\ndo hs \u2190 hs.mmap get_local,\n   `(%%\u0393 \u22a2 _) \u2190 target >>= instantiate_mvars,\n   let st := `\u03c3,\n   when keep_all.is_none (do\n     asms \u2190 get_assumptions,\n     (asms.diff hs).mmap' tactic.clear),\n   asms \u2190 get_assumptions,\n   asms.mmap'\n     (\u03bb h, do b \u2190 is_henceforth h,\n              when b $ do\n                to_expr ``(p_impl_revert (henceforth_str _ _) %%h)\n                    >>= note h.local_pp_name none,\n                tactic.clear h),\n   asms \u2190 get_assumptions,\n   constructor,\n   st \u2190 tactic.intro st,\n   h\u0393 \u2190 tactic.intro `h\u0393,\n   asms.for_each (\u03bb h, do\n     e \u2190 to_expr ``(judgement.apply %%h %%st %%h\u0393),\n     note h.local_pp_name none e,\n     tactic.clear h),\n   let rs' := map simp_arg_type.expr\n       [``(function.comp),``(on_fun),``(prod.map),``(prod.map_left),``(prod.map_right)\n       ,``(coe),``(lift_t),``(has_lift_t.lift),``(coe_t),``(has_coe_t.coe)\n       ,``(coe_b),``(has_coe.coe)\n       ,``(coe_fn), ``(has_coe_to_fun.coe), ``(coe_sort), ``(has_coe_to_sort.coe)\n       ] ++\n       rs,\n   let l := (loc.ns $ none :: map (some \u2218 expr.local_pp_name) asms),\n   tactic.interactive.simp iota ff rs' [`predicate] l\n       { fail_if_unchanged := ff },\n   done <|> solve1 (do\n     tactic.clear h\u0393,\n     try (to_expr ``(temporal.persistent %%\u0393) >>= mk_instance >>= tactic.clear),\n     tactic.clear \u0393,\n     subst_state_variables st opt,\n     tac)\n     -- `[rw [models_to_fun_var']]\n\nmeta def same_type (e\u2080 e\u2081 : expr) : temporal unit :=\ndo t\u2080 \u2190 infer_type e\u2080,\n   t\u2081 \u2190 infer_type e\u2081,\n   is_def_eq t\u2080 t\u2081\n\nmeta def \u00ablet\u00bb := tactic.interactive.\u00ablet\u00bb\n\nmeta def \u00abhave\u00bb  (h : parse ident?)\n                 (q\u2081 : parse (tk \":\" *> texpr)?)\n                 (q\u2082 : parse $ (tk \":=\" *> texpr)?)\n: tactic expr :=\nlet h := h.get_or_else `this in\nmatch q\u2081, q\u2082 with\n| some e, some p := do\n  `(%%\u0393 \u22a2 _) \u2190 target,\n  t \u2190 i_to_expr e,\n  t' \u2190 to_expr ``(%%\u0393 \u22a2 %%t),\n  p \u2190 t_to_expr p,\n  v \u2190 to_expr ``(%%p : %%t'),\n  tactic.assertv h t' v\n| none, some p := do\n  `(%%\u0393 \u22a2 _) \u2190 target,\n  p \u2190 t_to_expr p,\n  h \u2190 temporal.note h none p,\n  (fix_assumptions \u0393 h) <|> return h\n| some e, none := do\n  `(%%\u0393 \u22a2 _) \u2190 target,\n  e' \u2190 i_to_expr e,\n  p \u2190 i_to_expr ``(%%\u0393 \u22a2 %%e),\n  tactic.assert h p\n| none, none := do\n  `(%%\u0393 \u22a2 _) \u2190 target,\n  t \u2190 infer_type \u0393 >>= beta_reduction,\n  e \u2190 mk_meta_var t,\n  i_to_expr ``(%%\u0393 \u22a2 %%e) >>= tactic.assert h\nend\n\nmeta def strengthen_to (e : parse texpr) : temporal unit :=\nstrengthening (to_expr ``(_ \u22a2 %%e) >>= change)\n\nmeta def intro (n : parse ident_?) : temporal unit :=\n() <$ temporal.intros (some [n.get_or_else `_])\n\nmeta def intros : parse ident_* \u2192 temporal unit\n | [] := () <$ temporal.intros none\n | xs := () <$ temporal.intros (some xs)\n\nmeta def introv' : parse ident_* \u2192 temporal (list expr)\n| []      := intros_dep\n| (n::ns) := do hs  \u2190 intros_dep,\n                try (enter_list_state),\n                h \u2190 intro_aux n,\n                hs' \u2190 introv ns,\n                return (hs ++ hs')\n\nmeta def introv (ls : parse ident_*) : temporal (list expr) :=\n(++) <$> introv' ls <*> exit_list_state\n\nmeta def revert (ns : parse ident*) : temporal unit :=\nmmap get_local ns >>= mmap' temporal.revert\n\nmeta def exact (e : parse texpr) : temporal unit :=\nt_to_expr e >>= tactic.exact\n\nmeta def refine (e : parse texpr) : temporal unit :=\ndo t \u2190 target,\n   to_expr ``(%%e : %%t) >>= tactic.exact\n\nmeta def apply (q : parse texpr) : temporal unit :=\nt_to_expr_for_apply q >>= temporal.apply\n\nmeta def trivial : temporal unit :=\n`[apply of_eq_true (True_eq_true _)]\n\nmeta def rw (rs : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := { }) : temporal unit :=\nrewrite rs l cfg ; (trivial <|> solve_by_elim <|> reflexivity <|> return ())\n\nmeta def rewrite  (rs : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := { }) : temporal unit :=\nrw rs l cfg\n\nprivate meta def cases_arg_p : lean.parser (option name \u00d7 pexpr) :=\nwith_desc \"(id :)? expr\" $ do\n  t \u2190 texpr,\n  match t with\n  | (local_const x _ _ _) :=\n    (tk \":\" *> do t \u2190 texpr, pure (some x, t)) <|> pure (none, t)\n  | _ := pure (none, t)\n  end\n\nmeta def sequent_type (p : expr) : tactic (option (expr \u00d7 expr \u00d7 expr)) :=\ndo t \u2190 infer_type p,\n   `(%%\u0393 \u22a2 _) \u2190 target,\n   match t with\n    | `(%%\u0393 \u22a2 %%q) := return (some (\u0393,p,q))\n    | `(\u22a9 %%q) := return (some (\u0393,p \u0393, q))\n    | _ := return none\n   end\n\nmeta def break_conj (\u0393 p p' a b : expr) (ids : list name) : temporal unit :=\ndo  let h\u2080 : name := (ids.nth 0).get_or_else `a,\n    let h\u2081 : name := (ids.nth 1).get_or_else `a,\n    h\u2080 \u2190 to_expr ``(p_and_elim_left %%a %%b %%\u0393 %%p') >>= note h\u2080 none,\n    h\u2081 \u2190 to_expr ``(p_and_elim_right %%a %%b %%\u0393 %%p') >>= note h\u2081 none,\n    when p.is_local_constant (tactic.clear p),\n    revert_lst [h\u2080,h\u2081],\n    intron 2\n\nmeta def break_disj (\u0393 p p' a b : expr) (ids : list name) : temporal unit :=\ndo let h\u2080 : name := (ids.nth 0).get_or_else `a,\n   let h\u2081 : name := (ids.nth 1).get_or_else `a,\n   g \u2190 target,\n   note `h none p',\n   revert [`h],\n   when p.is_local_constant (tactic.clear p),\n   apply ``(@p_or_entails_of_entails' _  %%\u0393 %%a %%b _ _)\n   ; [ intros [h\u2080] , intros [h\u2081] ],\n   tactic.swap\n\nmeta def cases_dt  (e : parse cases_arg_p) (ids : parse with_ident_list) : temporal unit :=\ndo e' \u2190 to_expr e.2,\n   t \u2190 infer_type e',\n   let h\u2080 : name := (ids.nth 0).get_or_else `a,\n   let h\u2081 : name := (ids.nth 1).get_or_else `a,\n   (do match_expr ``(tvar (_ \u00d7 _)) t,\n       reverting (\u03bb h, do t \u2190 infer_type h, return $ e'.occurs t) $ do\n       h \u2190 to_expr ``(eta_pair %%e') >>= note `h none,\n       tactic.revert h,\n       e' \u2190 if e'.is_local_constant\n       then mk_fresh_name >>= rename' e'\n       else return e',\n       to_expr ``(pair.fst ! %%e') >>= \u03bb e, tactic.generalize e h\u2080 >> tactic.intro1,\n       to_expr ``(pair.snd ! %%e') >>= \u03bb e, tactic.generalize e h\u2081 >> tactic.intro1,\n       h \u2190 tactic.intro1,\n       z \u2190 if e'.is_local_constant then return e'\n       else tactic.generalize e' `z >> tactic.intro1,\n       tactic.subst z )\n<|>\n   tactic.interactive.cases e ids\n\nmeta def match_pexpr (p : pexpr) (e : expr) : temporal unit :=\nto_expr p >>= unify e\n\nmeta def cases (e : parse cases_arg_p) (ids : parse with_ident_list) : temporal unit :=\ndo p' \u2190 to_expr e.2,\n   (some (\u0393,p,q)) \u2190 sequent_type p' | cases_dt e ids,\n   a \u2190 mk_mvar, b \u2190 mk_mvar,\n   (do match_pexpr ``(\u25fb(%%a \u22c0 %%b)) q,\n       p\u2081 \u2190 to_expr ``(eq.mp (congr_arg (judgement %%\u0393) (henceforth_and %%a %%b)) %%p),\n       a \u2190 to_expr ``(\u25fb%%a),\n       b \u2190 to_expr ``(\u25fb%%b),\n       -- p' \u2190 mk_app `eq.mp [p\u2080,p],\n       break_conj \u0393 p' p\u2081 a b ids) <|>\n   (do match_pexpr ``(%%a \u22c0 %%b) q,\n       break_conj \u0393 p p a b ids) <|>\n   (do match_pexpr ``(%%a \u22c1 %%b) q,\n       break_disj \u0393 p p a b ids) <|>\n   (do match_pexpr ``(\u25c7(%%a \u22c1 %%b)) q,\n       p\u2081 \u2190 to_expr ``(eq.mp (congr_arg (judgement %%\u0393) (eventually_or %%a %%b)) %%p),\n       a \u2190 to_expr ``(\u25c7%%a),\n       b \u2190 to_expr ``(\u25c7%%b),\n       break_disj \u0393 p' p\u2081 a b ids) <|>\n   (do match_pexpr ``(p_exists %%b) q,\n       let h\u2080 : name := (ids.nth 0).get_or_else `_,\n       let h\u2081 : name := (ids.nth 1).get_or_else `_,\n       h \u2190 note `h none p',\n       when p'.is_local_constant (tactic.clear p'),\n       revert [`h], h \u2190 to_expr ``(p_exists_imp_eq_p_forall_imp _ _),\n       tactic.rewrite_target h, intros [h\u2080,h\u2081]) <|>\n   (do q \u2190 pp q, fail format!\"case expression undefined on {q}\")\n\nprivate meta def cases_core (p : expr) : tactic unit :=\n() <$ cases (none,to_pexpr p) []\n\nmeta def by_cases : parse cases_arg_p \u2192 tactic unit\n| (n, q) := do\n  `(%%\u0393 \u22a2 _) \u2190 target,\n  p \u2190 t_to_expr q,\n  let ids : list _ := n.to_monad,\n  cases (none,``(predicate.em %%p %%\u0393)) $ ids ++ ids\n\nprivate meta def find_matching_hyp (ps : list pattern) : tactic expr :=\nany_hyp $ \u03bb h, do\n  type \u2190 infer_type h,\n  ps.mfirst $ \u03bb p, do\n    match_pattern p type,\n    return h\n\nopen temporal.interactive (rename')\nmeta def select (h : parse $ ident <* tk \":\") (p : parse texpr) : temporal unit :=\ndo `(%%\u0393 \u22a2 _) \u2190 target,\n   p\u2080 \u2190 pexpr_to_pattern ``(%%\u0393 \u22a2 %%p),\n   p\u2081 \u2190 pexpr_to_pattern p,\n   any_hyp (\u03bb h', infer_type h' >>= match_pattern p\u2080 >> () <$ rename' h' h)\n     <|> any_hyp (\u03bb h', infer_type h' >>= match_pattern p\u2081 >> () <$ rename' h' h)\n\nmeta def cases_matching (rec : parse $ (tk \"*\")?) (ps : parse pexpr_list_or_texpr) : temporal unit :=\ndo ps \u2190 lift\u2082 (++) (ps.mmap pexpr_to_pattern)\n                   (ps.mmap $ \u03bb p, pexpr_to_pattern ``(_ \u22a2 %%p)),\n   if rec.is_none\n   then find_matching_hyp ps >>= cases_core\n   else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core\n\n/-- Shorthand for `cases_matching` -/\nmeta def casesm (rec : parse $ (tk \"*\")?) (ps : parse pexpr_list_or_texpr) : temporal unit :=\ncases_matching rec ps\n\n\n-- meta def rcases (e : parse cases_arg_p)\n--   (ids : parse (tk \"with\" *> rcases_parse)?)\n-- : temporal unit :=\n-- do let patts := rcases_parse.invert $ ids.get_or_else [default _],\n--    _\n\nmeta def assume_negation (n : parse (tk \"with\" *> ident)?) : temporal unit :=\ndo `(_ \u22a2 %%t) \u2190 target,\n   let h := n.get_or_else `h,\n   cases (none, ``(predicate.em %%t)) [h,h],\n   solve1 (do h \u2190 get_local h, tactic.exact h)\n\nmeta def induction\n  (obj : parse interactive.cases_arg_p)\n  (rec_name : parse using_ident)\n  (ids : parse with_ident_list)\n  (revert : parse $ (tk \"generalizing\" *> ident*)?)\n: tactic unit :=\ndo `(%%\u0393 \u22a2 _) \u2190 target,\n   (tactic.interactive.induction obj rec_name ids revert) ;\n     (local_context >>= mmap' (fix_or_clear_assumption \u0393))\n\nmeta def case (ctor : parse ident*) (ids) (tac : itactic) : tactic unit :=\ntactic.interactive.case ctor ids tac\n\nmeta def focus_left' (id : option name) : temporal expr :=\ndo `(%%\u0393 \u22a2 _ \u22c1 _) \u2190 target | fail \"expecting `_ \u22c1 _`\",\n   `[rw [p_or_comm,\u2190 p_not_p_imp]],\n   temporal.intro1 id\n\nmeta def focus_left (ids : parse with_ident_list) : temporal unit :=\n() <$ focus_left' ids.head'\n\nmeta def focusing_left (ids : parse with_ident_list) (tac : itactic) : temporal unit :=\ndo x \u2190 focus_left' ids.head',\n   focus1 (do\n     tac,\n     get_local x.local_pp_name >>= temporal.revert,\n     `[rw [p_not_p_imp,\u2190 p_or_comm]])\n\nmeta def focus_right' (id : option name) : temporal expr :=\ndo `(%%\u0393 \u22a2 _ \u22c1 _) \u2190 target | fail \"expecting `_ \u22c1 _`\",\n   `[rw [\u2190 p_not_p_imp]],\n   temporal.intro1 id\n\nmeta def focus_right (ids : parse with_ident_list) : temporal unit :=\n() <$ focus_right' ids.head'\n\nmeta def focusing_right (ids : parse with_ident_list) (tac : itactic) : temporal unit :=\ndo x \u2190 focus_right' ids.head',\n   focus1 (do\n     tac,\n     get_local x.local_pp_name >>= temporal.revert,\n     `[rw [p_not_p_imp]])\n\nmeta def split (greedy : parse $ (tk \"!\")?) (rec : parse $ (tk \"*\")?) : temporal unit :=\nlet goal := if greedy.is_some\n               then target >>= force ``(_ \u22a2 _ \u22c0 _)\n               else target in\nif rec.is_some then\n  focus1 $ repeat $ do\n    `(%%\u0393 \u22a2 %%p \u22c0 %%q) \u2190 goal,\n    temporal.interactive.exact ``(p_and_intro %%p %%q %%\u0393 _ _)\nelse do\n  `(%%\u0393 \u22a2 %%p \u22c0 %%q) \u2190 target >>= force ``(_ \u22a2 _ \u22c0 _),\n  temporal.interactive.exact ``(p_and_intro %%p %%q %%\u0393 _ _)\n\nmeta def existsi : parse pexpr_list_or_texpr \u2192 parse with_ident_list \u2192 temporal unit\n| []      _ := return ()\n| (p::ps) xs :=\ndo e \u2190 i_to_expr p,\n   have h : inhabited name, from \u27e8 `_ \u27e9,\n   temporal.existsi e (@list.head _ h xs),\n   existsi ps xs.tail\n\nmeta def clear_except :=\ntactic.interactive.clear_except\n\nmeta def action (ids : parse with_ident_list) (tac : tactic.interactive.itactic) : temporal unit :=\ndo `[ try { simp only [predicate.p_not_comp,temporal.next_eq_action,temporal.next_eq_action',temporal.not_action] },\n      try { simp only [predicate.p_not_comp,temporal.init_eq_action,temporal.init_eq_action',temporal.not_action\n                      ,temporal.action_and_action,predicate.models_pred\n                      ,predicate.models_prop] },\n      repeat { rw \u2190 temporal.action_imp } ],\n   get_assumptions >>= list.mmap' tactic.clear,\n   `(%%\u0393 \u22a2 temporal.action %%A  %%v ) \u2190 target,\n   refine ``(temporal.unlift_action %%A %%v _),\n   tactic.intro_lst [`\u03c3,`\u03c3'],\n   mmap' tactic.intro ids,\n   solve1 tac\n\nmeta def print := tactic.print\n\nmeta def repeat (tac : itactic) : temporal unit :=\ntactic.repeat tac\n\nmeta def lifted_pred\n  (no_dflt : parse only_flag)\n  (rs : parse simp_arg_list)\n  (us : parse using_idents)\n: temporal unit :=\ntactic.interactive.lifted_pred ff no_dflt rs us\n\nmeta def propositional : temporal unit :=\ntactic.interactive.propositional\n\nmeta def match_head (e : expr) : expr \u2192 tactic unit\n| e' :=\n    unify e e'\n<|> (do `(_ \u2192 %%e') \u2190 whnf e',\n        v \u2190 mk_mvar,\n        match_head (e'.instantiate_var v))\n<|> (do `(%%\u0393 \u22a2 _ \u27f6 %%e') \u2190 whnf e',\n        e'' \u2190 to_expr ``(%%\u0393 \u22a2 %%e'),\n        match_head e'')\n<|> (do `(%%\u0393 \u22a2 p_forall %%(expr.lam _ _ t e')) \u2190 whnf e',\n        v \u2190 mk_meta_var t,\n        e'' \u2190 to_expr ``(%%\u0393 \u22a2 %%(e'.instantiate_var v)),\n        match_head e'')\n\nmeta def find_matching_head : expr \u2192 list expr \u2192 tactic (list expr)\n| e []         := return []\n| e (H :: Hs) :=\n  do t \u2190 infer_type H,\n     (list.cons H <$ match_head e t <|> pure id) <*> find_matching_head e Hs\n\nmeta def apply_assumption\n  (asms : option (list expr) := none)\n  (tac : temporal unit := return ()) : tactic unit :=\ndo { ctx \u2190 asms.to_monad <|> local_context,\n     t   \u2190 target,\n     hs   \u2190 find_matching_head t ctx,\n     hs.any_of (\u03bb H, (() <$ temporal.apply H ; tac : temporal unit)) } <|>\ndo { exfalso,\n     ctx \u2190 asms.to_monad <|> local_context,\n     t   \u2190 target,\n     hs   \u2190 find_matching_head t ctx,\n     hs.any_of (\u03bb H, (() <$ temporal.apply H ; tac : temporal unit)) }\n<|> fail \"assumption tactic failed\"\n\n\n/- TODO(Simon) Use  -/\nmeta def assumption (tac : temporal unit := return ()) : temporal unit :=\ndo `(_ \u22a2 _) \u2190 target | tactic.interactive.apply_assumption local_context tac,\n   apply_assumption none tac <|> strengthening (apply_assumption none tac)\n\nmeta def try (tac : itactic) : temporal unit :=\ntactic.try tac\n\nmeta def refl :=\ndo try (to_expr ``(ctx_impl _ _ _) >>= change),\n   tactic.reflexivity\n\nmeta def reflexivity :=\ndo try (to_expr ``(ctx_impl _ _ _) >>= change),\n   tactic.reflexivity\n\nmeta def ac_refl :=\ndo refine ``(entails_of_eq _ _ _ _) <|> refine ``(equiv_of_eq _ _ _ _),\n   tactic.ac_refl\n\nmeta def unfold_coes (ids : parse ident *) (l : parse location) (cfg : unfold_config := { }) : temporal unit :=\ntactic.interactive.unfold_coes l >>\ntactic.interactive.unfold ids l cfg\n\nmeta def unfold :=\ntactic.interactive.unfold\n\nmeta def dunfold :=\ntactic.interactive.dunfold\n\nmeta def dsimp :=\ntactic.interactive.dsimp\n\nmeta def simp (use_iota_eqn : parse (parser.tk \"!\")?)\n              (no_dflt : parse only_flag)\n              (hs : parse simp_arg_list)\n              (attr_names : parse with_ident_list)\n              (locat : parse location)\n              (cfg : simp_config_ext := {}) : temporal unit :=\n-- if locat.include_goal\n-- then strengthening $ tactic.interactive.simp no_dflt hs attr_names locat cfg\ndo let attr_names :=\n       if no_dflt\n         then attr_names\n         else (`tl_simp :: attr_names),\n   tactic.interactive.simp use_iota_eqn no_dflt hs attr_names locat cfg,\n   try refl\n\nmeta def simp_coes\n              (iota : parse (tk \"!\")?)\n              (no_dflt : parse only_flag)\n              (hs : parse simp_arg_list)\n              (attr_names : parse with_ident_list)\n              (locat : parse location)\n              (cfg : simp_config_ext := {}) : temporal unit :=\ndo let attr_names :=\n       if no_dflt\n         then attr_names\n         else (`tl_simp :: attr_names),\n   tactic.interactive.simp_coes iota no_dflt hs attr_names locat cfg,\n   try refl\n\nmeta def exfalso : temporal unit :=\ndo `(%%\u0393 \u22a2 %%p) \u2190 target,\n   `[apply False_entails %%p %%\u0393 _]\n\nmeta def admit : temporal unit :=\ntactic.admit\n\nmeta def left : temporal unit :=\ndo `(%%\u0393 \u22a2 %%p \u22c1 %%q) \u2190 target,\n   apply ``(p_or_intro_left %%p %%q %%\u0393 _)\n\nmeta def right : temporal unit :=\ndo `(%%\u0393 \u22a2 %%p \u22c1 %%q) \u2190 target,\n   apply ``(p_or_intro_right %%p %%q %%\u0393 _)\n\nmeta def solve_by_elim : temporal unit :=\nassumption $ assumption $ assumption done\n\nmeta def tauto (greedy : parse (tk \"!\")?) : temporal unit :=\n() <$ intros [] ;\ncasesm (some ()) [``(_ \u22c0 _),``(_ \u22c1 _)] ;\nsplit greedy (some ()) ;\nsolve_by_elim\n\nmeta def specialize (h : parse texpr) : temporal unit :=\ntactic.interactive.specialize h\n\nmeta def type_check\n   (e : parse texpr)\n: tactic unit :=\ndo e \u2190 t_to_expr e, tactic.type_check e, infer_type e >>= trace\n\ndef with_defaults {\u03b1} : list \u03b1 \u2192 list \u03b1 \u2192 list \u03b1\n | [] xs := xs\n | (x :: xs) (_ :: ys) := x :: with_defaults xs ys\n | xs [] := xs\nmeta def rename_bound (n : name) : expr \u2192 expr\n | (expr.app e\u2080 e\u2081) := expr.app e\u2080 (rename_bound e\u2081)\n | (expr.lam _ bi t e) := expr.lam n bi t e\n | e := e\n\nmeta def henceforth (pers : parse (tk \"!\")?) (l : parse location) : temporal unit :=\ndo when l.include_goal (do\n     when pers.is_some $ persistent [],\n     persistently $\n       refine ``(persistent_to_henceforth _)),\n   soft_apply l\n         (\u03bb h, do b \u2190 is_henceforth h,\n                  when (\u00ac b) $ fail format!\"{h} is not of the shape `\u25a1 _`\",\n                  to_expr ``(p_impl_revert (henceforth_str _ _) %%h)\n                    >>= note h.local_pp_name none,\n                  tactic.clear h)\n         (pure ())\n\nmeta def t_induction\n  (pers : parse $ (tk \"!\") ?)\n  (p : parse texpr?)\n  (specs : parse $ (tk \"using\" *> ident*) <|> pure [])\n  (ids : parse with_ident_list)\n: tactic unit :=\ndo `(%%\u0393 \u22a2 %%g) \u2190 target,\n   match g with\n    | `(\u25fb%%p) :=\n      do let xs := (with_defaults ids [`ih]).take 1,\n         ih \u2190 to_expr ``(%%\u0393 \u22a2 \u25fb(%%p \u27f6 \u2299%%p)) >>= assert `ih,\n         b \u2190 is_context_persistent,\n         when (b \u2228 pers.is_some) $\n           focus1 (do\n             interactive.henceforth (some ()) (loc.ns [none]),\n             intros xs),\n         interactive.henceforth none (loc.ns $ specs.map some),\n         tactic.swap,\n         h\u2080 \u2190 to_expr ``(%%\u0393 \u22a2 %%p) >>= assert `this,\n         tactic.swap,\n         t_to_expr ``(temporal.induct %%p %%ih %%h\u2080) >>=\n           tactic.exact\n    | `(\u25c7%%q \u22c1 \u25fb%%p) :=\n      do let xs := (with_defaults ids [`ih]).take 1,\n         ih \u2190 to_expr ``(%%\u0393 \u22a2 \u25fb(%%p \u27f6 -%%q \u27f6 \u2299(%%p \u22c1 %%q))) >>= assert `ih,\n         b \u2190 is_context_persistent,\n         when (b \u2228 pers.is_some) $\n           focus1 (do\n           interactive.henceforth (some ()) (loc.ns [none]),\n           intros xs),\n         tactic.swap,\n         h\u2080 \u2190 to_expr ``(%%\u0393 \u22a2 %%p) >>= assert `this,\n         tactic.swap,\n         t_to_expr ``(temporal.induct_evt %%p %%q %%ih %%h\u2080) >>= tactic.exact\n    | _ := fail \"expecting goal of the form `\u25fbp` or `\u25c7q \u22c1 \u25fbp`\"\n   end\n\nmeta def wf_induction\n  (p : parse texpr)\n  (rec_name : parse (tk \"using\" *> texpr)?)\n  (ids : parse with_ident_list)\n: tactic unit :=\ndo rec_name \u2190 (\u2191rec_name : tactic pexpr) <|> return ``(has_well_founded.wf _),\n   to_expr ``(well_founded.induction %%rec_name %%p) >>= tactic.apply,\n   try $ to_expr p >>= tactic.clear,\n   ids' \u2190 tactic.intro_lst $ (with_defaults ids [`x,`ih_1]).take 2 ,\n   h \u2190 ids'.nth 1,\n   hp \u2190 to_expr ``((p_forall_subtype_to_fun _ _ _).mpr %%h),\n   p \u2190 rename_bound `y <$> infer_type hp,\n   assertv h.local_pp_name p hp,\n   tactic.clear h,\n   return ()\n\nprivate meta def show_aux (p : pexpr) : list expr \u2192 list expr \u2192 tactic unit\n| []      r := fail \"show tactic failed\"\n| (g::gs) r := do\n  do { set_goals [g],\n       g_ty \u2190 target,\n       ty \u2190 i_to_expr p,\n       unify g_ty ty,\n       set_goals (g :: r.reverse ++ gs),\n       tactic.change ty}\n  <|>\n  show_aux gs (g::r)\n\nmeta def \u00abshow\u00bb (q : parse $ texpr <* tk \",\") (tac : tactic.interactive.itactic) : tactic unit :=\ndo gs \u2190 get_goals,\n   show_aux q gs [],\n   solve1 tac\n\nmeta def rename (n\u2080 n\u2081 : parse ident) : temporal unit :=\ntactic.rename n\u2080 n\u2081\n\nmeta def replace (n : parse ident)\n: parse (parser.tk \":\" *> texpr)? \u2192 parse (parser.tk \":=\" *> texpr)? \u2192 temporal unit\n| none (some prf) :=\ndo prf \u2190 t_to_expr prf,\n   tactic.interactive.replace n none (to_pexpr prf) >> try (simp none tt [] [] (loc.ns [some n]))\n| none none :=\ntactic.interactive.replace n none none\n| (some t) (some prf) :=\ndo t' \u2190 to_expr t >>= infer_type,\n   tl \u2190 tt <$ match_expr ``(pred' _) t' <|> pure ff,\n   if tl then do\n     `(%%\u0393 \u22a2 _) \u2190 target,\n     prf' \u2190 t_to_expr prf,\n     tactic.interactive.replace n ``(%%\u0393 \u22a2 %%t) (to_pexpr prf')\n   else tactic.interactive.replace n t prf\n| (some t) none :=\ndo t' \u2190 to_expr t >>= infer_type,\n   match_expr ``(pred' _) t' ,\n   `(%%\u0393 \u22a2 _) \u2190 target,\n   tactic.interactive.replace n ``(%%\u0393 \u22a2 %%t) none\n\nmeta def transitivity : parse texpr? \u2192 temporal unit\n | none := apply ``(predicate.p_imp_trans )\n | (some p) := apply ``(@predicate.p_imp_trans _ _ _ %%p _ _ _)\n\nlemma nonempty_of_tvar (\u03b1) {\u03b2} {\u0393 p : pred' \u03b1}\n  (v  : tvar \u03b2)\n  (h' : \u03a0 [nonempty \u03b2], \u0393 \u22a2 p)\n: \u0393 \u22a2 p :=\nby { lifted_pred keep,\n     have inst := nonempty.intro (0 \u22a8 v),\n     apply (@h' inst).apply _ a, }\n\nlemma nonempty_of_p_exists (\u03b1) {\u03b2} {\u0393 p : pred' \u03b1} {q : \u03b2 \u2192 pred' \u03b1}\n  (h  : \u0393 \u22a2 p_exists q)\n  (h' : \u03a0 [nonempty \u03b2], \u0393 \u22a2 p)\n: \u0393 \u22a2 p :=\nby { lifted_pred keep using h,\n     have inst := nonempty_of_exists h,\n     apply (@h' inst).apply _ a, }\n\nmeta def nonempty (t : parse texpr) : temporal unit :=\ndo `(%%\u0393 \u22a2 %%p) \u2190 target,\n   q  \u2190 mk_mvar,\n   do { v \u2190 to_expr ``(%%\u0393 \u22a2 @p_exists _ %%t %%q) >>= find_assumption,\n        refine ``(@nonempty_of_p_exists _ %%t %%\u0393 %%p %%q %%v _) } <|>\n   do { v \u2190 to_expr ``(tvar %%t) >>= find_assumption,\n        refine ``(@nonempty_of_tvar _ %%t %%\u0393 %%p %%v _) },\n   tactic.intro1,\n   resetI,\n   return ()\n\nsection historyI\nvariable {\u03b1 : Sort*}\n-- variable [nonempty \u03b1]\nvariable {\u0393 : cpred}\n-- variables I N : cpred\nvariables J HI : tvar (\u03b1 \u2192 Prop)\n\nopen classical nat\n\nvariables HN : tvar (act \u03b1)\n-- variables \u0393 : cpred\nvariable h_HI : \u0393 \u22a2 \u2203\u2203 h : \u03b1, HI h \u22c0 J h\nvariable h_HN : \u0393 \u22a2 \u25fb(\u2200\u2200 h : \u03b1, J h \u27f6 \u2203\u2203 h' : \u03b1, HN h h' \u22c0 \u2299J h')\n\n\n-- private def w : \u2115 \u2192 \u03b1\n--  | 0 := i \u22a8 x\u2080\n--  | (succ j) := (i + j \u22a8 f) (w j)\n\n\ninclude h_HI h_HN\n\nlemma historyI\n: \u0393 \u22a2 \u2203\u2203 w : tvar \u03b1, HI w \u22c0 \u25fbHN w (\u2299w) \u22c0 \u25fbJ w :=\nbegin [temporal]\n  nonempty \u03b1,\n  let x\u2080 : tvar \u03b1 := \u27e8 \u03bb i, \u03b5 x, i \u22a8 HI x \u2227 i \u22a8 J x \u27e9,\n  let f : tvar (\u03b1 \u2192 \u03b1) := \u27e8 \u03bb i x, \u03b5 x', i \u22a8 HN x x' \u2227 succ i \u22a8 J x' \u27e9 ,\n  have := fwd_witness x\u2080 f \u0393,\n  cases this with w H, cases H with H\u2080 Hnext,\n  existsi w,\n  have : \u25fbJ w,\n  { t_induction,\n    explicit' [x\u2080] with H\u2080 h_HI\n    { subst w, apply_epsilon_spec, },\n    henceforth! at *,\n    explicit' [f] with Hnext h_HN\n    { subst w', intro, apply_epsilon_spec, } },\n  split*,\n  explicit' with this H\u2080 h_HI\n  { revert this, subst w,\n    apply_epsilon_spec, },\n  { henceforth! at *,\n    explicit' [f] with this Hnext h_HN\n    { subst w', apply_epsilon_spec, }, },\n  assumption\nend\n\n-- variable (HN' : tvar \u03b1 \u2192 tvar \u03b1 \u2192 cpred)\n\nlemma witness_elim' {P : cpred}\n  (J' : tvar \u03b1 \u2192 cpred)\n  (HI' : tvar \u03b1 \u2192 cpred)\n  (HN' : tvar \u03b1 \u2192 tvar \u03b1 \u2192 cpred)\n  (hJ : \u2200 w, J w = J' w)\n  (hHI : \u2200 w, HI w = HI' w)\n  (hHN : \u2200 w, HN w (\u2299w) = HN' w (\u2299w))\n  (h : \u0393 \u22a2 \u2200\u2200 w, HI' w \u22c0 \u25fbHN' w (\u2299w) \u27f6 \u25fbJ' w \u27f6 P)\n: \u0393 \u22a2 P :=\nbegin [temporal]\n  have := historyI J HI HN h_HI h_HN,\n  revert this,\n  simp [hJ,hHI,hHN] at \u22a2 h,\n  exact h,\nend\n\nend historyI\n\nlemma witness_elim {\u03b1} {P : tvar \u03b1 \u2192 cpred} {\u0393 : cpred}\n  (x\u2080 : tvar \u03b1)\n  (f : tvar (\u03b1 \u2192 \u03b1))\n  (h : \u0393 \u22a2 \u2200\u2200 w, w \u2243 x\u2080 \u22c0 \u25fb( \u2299w \u2243 f w ) \u27f6 P w)\n: \u0393 \u22a2 \u2203\u2203 w, P w :=\nbegin [temporal]\n  have := fwd_witness x\u2080 f \u0393,\n  revert this,\n  apply p_exists_p_imp_p_exists,\n  solve_by_elim\nend\n\nmeta def lam_kabstract (e p : expr) (v : name := `_) : tactic expr :=\ndo t \u2190 infer_type p,\n   lam v binder_info.default t <$> kabstract e p\n-- do gs \u2190 get_goals,\n--    mv \u2190 to_expr ``(%%e = %%e) >>= mk_meta_var,\n--    set_goals [mv],\n--    t \u2190 infer_type p,\n--    tactic.generalize p v,\n--    v \u2190 tactic.intro1,\n--    tgt \u2190 target,\n--    (e,_) \u2190 is_eq tgt,\n\n--    lambdas' [v] e <* set_goals gs\n\n-- run_cmd do\n-- v  \u2190 mk_local_def `v `(\u2115),\n-- v' \u2190 mk_local_def `v `(\u2115),\n-- f \u2190 mk_local_def `f `(\u2115 \u2192 \u2115 \u2192 \u2115),\n-- e \u2190 to_expr ``(%%f (%%v + 1) (%%v + 2)),\n-- p \u2190 to_expr ``(%%v + 1),\n-- p' \u2190 to_expr ``(%%v + 2),\n-- timetac \"abstract_pattern\" $ do\n-- e' \u2190 lam_kabstract e p `x,\n-- e' \u2190 lam_kabstract e' p' `y,\n-- trace $ e',\n-- timetac \"kabstract\" $ do\n-- e' \u2190 kabstract e p,\n-- e' \u2190 kabstract (e'.instantiate_var v') p',\n-- trace $ e'.instantiate_var v\n\nmeta def brack_expr : lean.parser (name \u2295 pexpr) :=\nsum.inl <$> ident <|> sum.inr <$> brackets \"(\" \")\" texpr\n\n/-- select_witness w : P w\n      with h\u2080 h\u2081\n      using inv\n -/\nmeta def select_witness\n  (w : parse $ ident_ <* tk \":\")\n  (p : parse texpr)\n  (asm : parse $ (tk \"with\" *> prod.mk <$> ident <*> ident?)?)\n  (inv : parse $ ((tk \"using\" *> texpr) <|> pure (``(True))) <* tk \",\")\n  (tac : tactic.interactive.itactic)\n: temporal unit :=\ndo `(%%\u0393 \u22a2 %%q) \u2190 target,\n   u \u2190 mk_meta_univ,\n   t \u2190 mk_meta_var (expr.sort u),\n   u  \u2190 mk_app `temporal.tvar [t],\n   t' \u2190 to_expr ``(%%u \u2192 cpred),\n   (_,p) \u2190 solve_aux t' (do\n     tactic.intro w\n       <* (to_expr p >>= tactic.exact)),\n--        <|> fail\n-- \"in tactic `select_witness w : P w`, `P w` should be of the form\n-- `w \u2243 x\u2080 \u22c0 \u25fb(\u2299w \u2243 f w)`, where `x\u2080 : tvar \u03b1`, `f : tvar (\u03b1 \u2192 \u03b1)`\",\n   t' \u2190 to_expr ``(tvar %%t \u2192 cpred),\n   (_,J) \u2190 solve_aux t' (do\n     -- refine ``(to_fun_var _),\n     tactic.intro w,\n     to_expr inv  >>= tactic.exact ),\n   v \u2190 mk_local_def w u,\n   p' \u2190 head_beta (p v),\n   -- q' \u2190 head_beta (q v),\n   J' \u2190 head_beta (J v),\n   (HI,HN) \u2190 (do\n     mv \u2190 mk_mvar,\n     init \u2190 mk_mvar,\n     pat \u2190 to_expr  ``(%%init \u22c0 \u25fb %%mv),\n     unify p' pat,\n     init \u2190 instantiate_mvars init,\n     mv \u2190 instantiate_mvars mv,\n     nx_v \u2190 to_expr ``(\u2299 %%v),\n     v' \u2190 infer_type v >>= mk_local_def v.local_pp_name,\n     mv \u2190 lam_kabstract mv nx_v v.local_pp_name,\n     return (init.lambdas [v], mv.lambdas [v]) ),\n   new_g \u2190 to_expr ``(%%p' \u27f6 \u25fb%%J' \u27f6 %%q),\n   new_g \u2190 to_expr ``(%%\u0393 \u22a2 p_forall %%(new_g.lambdas [v])) >>= mk_meta_var,\n   h\u2080 \u2190 mk_mvar,h\u2081 \u2190 mk_mvar,h\u2082 \u2190 mk_mvar,h\u2083 \u2190 mk_mvar,h\u2084 \u2190 mk_mvar,\n   let (asm\u2080,asm\u2081) := asm.get_or_else (`_,`_),\n   let asm\u2081 := asm\u2081.get_or_else `_,\n   -- tactic.swap,\n   focus1 $ do\n       -- (hJ : \u2200 w, J w = J' w)\n       -- (hHI : \u2200 w, HI w = HI' w)\n       -- (hHN : \u2200 w w', HN w w' = HN' w w')\n       -- (h : \u0393 \u22a2 \u2200\u2200 w, HI' w \u22c0 \u25fbHN' w (\u2299w) \u27f6 \u25fbJ' w \u27f6 P)\n\n     refine  ``(temporal.interactive.witness_elim'\n               (to_fun_var %%J) (to_fun_var %%HI) (to_fun_var' %%HN)\n               -- %%h\u2080 %%h\u2081 %%J %%HI %%h\u2082 %%h\u2083 %%new_g),\n               %%h\u2080 %%h\u2081 %%J %%HI %%HN %%h\u2082 %%h\u2083 %%h\u2084 %%new_g),\n     set_goals [h\u2081],\n     henceforth (some ()) loc.wildcard <|> fail \"foo\",\n     h\u2081::_ \u2190 get_goals,\n     set_goals [new_g],\n     temporal.interactive.intros [w,asm\u2080,asm\u2081],\n     new_g::_ \u2190 get_goals,\n     hs \u2190 [h\u2082,h\u2083,h\u2084].mmap (\u03bb h, do\n       set_goals [h],\n       focus1 `[intros, simp! only with lifted_fn],\n       get_goals ),\n     set_goals hs.join >> trace_state >> tac >> done,\n     set_goals [new_g]\n\n#check witness_elim'\n\nend interactive\n\n/- end monotonicity -/\n\n\nsection\nopen tactic tactic.interactive (unfold_coes unfold itactic assert_or_rule)\nopen interactive interactive.types lean lean.parser\nopen applicative (mmap\u2082 lift\u2082)\nopen functor\nlocal postfix `?`:9001 := optional\n\nmeta def mono1 (only_pers : parse (tk \"!\")?) : temporal unit :=\ndo ex \u2190 (if \u00ac only_pers.is_some then do\n      asms \u2190 get_assumptions,\n      list.band <$> asms.mmap is_henceforth\n   else tt <$ interactive.persistent []),\n   if ex\n   then persistently $ do\n          to_expr ``(ctx_impl _ _ _) >>= change,\n          tactic.interactive.mono none interactive.mono_selection.both []\n   else do\n     to_expr ``(ctx_impl _ _ _) >>= change,\n     tactic.interactive.mono none interactive.mono_selection.both []\n\nmeta def mono_n (n : \u2115) (only_pers : parse (tk \"!\")?)\n  (dir : parse interactive.side) : temporal unit  :=\ndo ex \u2190 (if \u00ac only_pers.is_some then do\n      asms \u2190 get_assumptions,\n      list.band <$> asms.mmap is_henceforth\n   else tt <$ interactive.persistent []),\n   if ex\n   then persistently $ do\n          to_expr ``(ctx_impl _ _ _) >>= change,\n          tactic.iterate_exactly n (tactic.interactive.mono none dir [])\n   else do\n     to_expr ``(ctx_impl _ _ _) >>= change,\n     tactic.iterate_exactly n (tactic.interactive.mono none dir [])\n\nmeta def mk_assert : pexpr \u2295 pexpr \u2192 tactic expr\n| (sum.inl h) := to_expr h\n| (sum.inr p) := to_expr p >>= mk_meta_var\n\nmeta def mono\n  (only_pers : parse (tk \"!\")?)\n  (many : parse (tk \"*\")?)\n  (dir : parse interactive.side)\n  (e : parse assert_or_rule?) : temporal unit :=\ndo ex \u2190 (if \u00ac only_pers.is_some then do\n      asms \u2190 get_assumptions,\n      list.band <$> asms.mmap is_henceforth\n   else tt <$ interactive.persistent []),\n   -- trace ex,\n   if ex\n   then persistently $ do\n          -- trace \"foo\",\n          to_expr ``(ctx_impl _ _ _) >>= change,\n          -- trace \"bar\",\n          -- h \u2190 mk_assert e,\n          tactic.interactive.mono many dir []\n   else do\n     to_expr ``(ctx_impl _ _ _) >>= change,\n     tactic.interactive.mono many dir []\n\nmeta def interactive.apply_mono (f e : parse ident) : temporal unit :=\ndo get_local e >>= temporal.revert,\n   f \u2190 get_local f,\n   b \u2190 is_henceforth f,\n   if b then do\n     interactive.persistent [],\n     persistently  $ do\n          to_expr ``(ctx_impl _ _ _) >>= change,\n          tactic.interactive.ac_mono interactive.rep_arity.many (some $ sum.inl ``(%%f))\n   else tactic.interactive.ac_mono interactive.rep_arity.many (some $ sum.inl ``(%%f))\n\nprivate meta def goal_flag := optional $ tk \"\u22a2\" <|> tk \"|-\"\n\nmeta def interactive.guard_target\n     (e : parse texpr) : temporal unit :=\ndo `(_ \u22a2 %%t) \u2190 target,\n   e \u2190 to_expr e,\n   guard (t =\u2090 e)\n\nmeta def interactive.iterate\n     (n : parse small_nat)\n     (tac : temporal.interactive.itactic) : temporal unit :=\ndo iterate_exactly n tac\n\nmeta def interactive.eventually (h : parse ident) (goal : parse goal_flag) : temporal unit :=\ndo `(%%\u0393 \u22a2 %%p) \u2190 target,\n   h' \u2190 get_local h,\n   `(%%\u0393' \u22a2 \u25c7%%q) \u2190 infer_type h' | fail format!\"{h} should be a temporal formula of the form \u25c7_\",\n   is_def_eq \u0393 \u0393',\n   revert h',\n   if goal.is_some then do\n     `(\u25c7 %%p) \u2190 pure p | fail format!\"expecting a goal of the form `\u25c7 _`\",\n     mono1 (some ())\n   else\n     interactive.persistent [] >>\n     persistently (do `(%%\u0393 \u22a2 \u25c7%%q \u27f6 %%p) \u2190 target, refine ``(p_imp_postpone %%\u0393 %%q %%p _)),\n   () <$ intro1 (some h)\n\nmeta def timeless (h : expr) : temporal (option name) :=\ndo try $ interactive.henceforth none (loc.ns [some h.local_pp_name]),\n   h \u2190 get_local h.local_pp_name,\n   `(%%\u0393' \u22a2 %%p) \u2190 infer_type h | return none,\n   `(@coe Prop cpred _ %%p) \u2190 return p | none <$ clear h,\n   some h.local_pp_name <$ temporal.revert h\n\nmeta def interactive.note\n   (h : parse ident?)\n   (q\u2081 : parse (tk \":\" *> texpr))\n   (_ : parse $ tk \",\")\n   (tac : tactic.interactive.itactic)\n: tactic expr :=\ndo `(%%\u0393 \u22a2 _) \u2190 target,\n   h' \u2190 temporal.interactive.\u00abhave\u00bb h q\u2081 none,\n   solve1 (do\n     xs \u2190 local_context >>= mmap timeless,\n     let n := xs.filter_map id,\n     tactic.revert \u0393,\n     refine ``(ew_wk _),\n     \u03c4 \u2190 tactic.intro1,\n     try $ temporal.interactive.simp none tt [] [`predicate] (loc.ns [none]) ,\n     try $ tactic.interactive.TL_unfold [`init] (loc.ns [none]),\n     try $ tactic.interactive.generalize none () (``(%%\u03c4 0),`\u03c3),\n     target >>= (\u03bb e, beta_reduction e tt) >>= change,\n     intro_lst n,\n     tac),\n   tactic.revert h',\n   refine ``(lifting_prop_asm %%\u0393 _),\n   tactic.intro h'.local_pp_name\n\nopen tactic.interactive (rw_rules rw_rules_t rw_rule get_rule_eqn_lemmas to_expr')\nopen temporal.interactive (rw)\n\nmeta def interactive.rw_using\n   (p  : parse cur_pos)\n   (q\u2081 : parse (tk \":\" *> texpr))\n   (l : parse location)\n   (_ :  parse $ tk \",\")\n   (tac : tactic.interactive.itactic)\n: tactic unit :=\ndo h \u2190 mk_fresh_name,\n   h \u2190 temporal.interactive.note h q\u2081 () tac,\n   let rs : rw_rules_t := \u27e8[{ rw_rule\n                            . pos := p\n                            , symm := ff\n                            , rule := to_pexpr h }],none\u27e9,\n   rw rs l,\n   try (tactic.clear h)\n\nmeta def interactive.\u00absuffices\u00bb (h : parse ident?) (t : parse (tk \":\" *> texpr)?) : tactic unit :=\ninteractive.\u00abhave\u00bb h t none >> tactic.swap\n\nmeta def interactive.congr := tactic.interactive.congr\n\nmeta def interactive.ext := tactic.interactive.ext\n\nrun_cmd do\n  let ls := [``mono,``mono1,``persistently],\n  ls.for_each $ \u03bb l, do\n    env    \u2190 get_env,\n    d_name \u2190 resolve_constant l,\n    (declaration.defn _ ls ty val hints trusted) \u2190 env.get d_name,\n    (name.mk_string h _) \u2190 return d_name,\n    let new_name := `temporal.interactive <.> h,\n    add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted)\n\nend\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/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.04208772971790022, "lm_q1q2_score": 0.019730333187730428}}
{"text": "/- This file provides the no_meta_var tactics,\nwhich checks that target or context contains no meta var.\nAuthor: Fr\u00e9d\u00e9ric Le Roux\n-/\n\n\nimport tactic\n\n------------------------------------------------\n------------- tactic no_meta_vars --------------\n------------------------------------------------\nmeta def tactic.interactive.generic_no_meta_vars (s: string) (e: expr) : tactic unit :=\nmwhen (expr.has_meta_var <$> (tactic.instantiate_mvars e)) $ tactic.fail (s ++ \" contains metavars\")\n\n/- target_no_meta_vars fails if the target contains metavars-/\nmeta def tactic.interactive.target_no_meta_vars : tactic unit :=\n tactic.target  >>= tactic.interactive.generic_no_meta_vars \"target\"\n\n/- context_no_meta_vars fails if the local context contains metavars-/\nmeta def tactic.interactive.context_no_meta_vars : tactic (list unit) :=\ndo \n   context \u2190 tactic.local_context,\n   context_type \u2190 context.mmap (\u03bb h, tactic.infer_type h),\n   context_type.mmap (\u03bb h, tactic.interactive.generic_no_meta_vars \"context\" h)\n\n/- no_meta_vars succeeds if all goals are accomplished, \notherwise fails if there are metavariables either in the context or in the target-/\nmeta def tactic.interactive.no_meta_vars : tactic unit :=\ndo\n   tactic.done <|> \n      `[ tactic.interactive.context_no_meta_vars,\n         tactic.interactive.target_no_meta_vars ]\n      \n\nopen interactive (parse)\nopen tactic\nopen lean.parser (ident)\n\n/- -/\nmeta def tactic.interactive.no_meta_vars_test (id: parse ident): (tactic unit) :=\ndo e \u2190 get_local id, et \u2190 infer_type e,  trace et\n\n\n------------------------------------------------\n----------------- tactic todo ------------------\n------------------------------------------------\naxiom todo {p : Prop} : p\n\nnamespace tactic\nnamespace interactive\n\n/--\nAn axiomatic alternative to `sorry`, used in formal roadmaps.\n-/\nmeta def todo : tactic unit := `[exact todo]\n\nend interactive\nend tactic\n\n\n-- Tests\n-- open tactic.interactive\n-- example : \u2203 x : \u2115, x = 0 :=\n-- begin\n--    no_meta_vars,\n--    existsi _,\n--    context_no_meta_vars,\n--    have H: 0=0,\n--    {refl, trace \"toto\", no_meta_vars},\n--    -- no_meta_vars,\n--    sorry\n-- end\n\n\n-- example (H1 : \u2200 x:\u2115, x=0) (y:\u2115) : y = 0 :=\n-- begin\n--    sorry\n--    -- don't know how to produce metavars in context!\n-- end", "meta": {"author": "dEAduction", "repo": "dEAduction-lean", "sha": "4fe1d642078fc94f9081ccbed08e047e86a741fd", "save_path": "github-repos/lean/dEAduction-dEAduction-lean", "path": "github-repos/lean/dEAduction-dEAduction-lean/dEAduction-lean-4fe1d642078fc94f9081ccbed08e047e86a741fd/src/lean_src_deaduction_synchro/utils.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32766831395172374, "lm_q2_score": 0.06008665143635008, "lm_q1q2_score": 0.01968849176715375}}
{"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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u2124 \u2115`\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 {\u03b1} [has_to_tactic_format \u03b1] (msg : String) (a : \u03b1) : tactic Unit :=\n  when_tracing `norm_cast do\n    let a \u2190 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 \u2192 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  \u27e8Label.toString\u27e9\n\ninstance : Repr Label :=\n  \u27e8Label.toString\u27e9\n\nunsafe instance : has_to_format Label :=\n  \u27e8fun l => l.toString\u27e9\n\n/-- Convert `string` into `label`. -/\ndef ofString : String \u2192 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 \u2192 \u2115\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 \u2192 tactic \u2115\n  | q(coe $(e)) => (\u00b7 + 1) <$> count_coes e\n  | q(coeSort $(e)) => (\u00b7 + 1) <$> count_coes e\n  | q(coeFn $(e)) => (\u00b7 + 1) <$> count_coes e\n  | app q(coeFn $(e)) x => (\u00b7 + \u00b7) <$> count_coes x <*> (\u00b7 + 1) <$> count_coes e\n  | expr.lam n bi t e => do\n    let l \u2190 mk_local' n bi t\n    count_coes <| e l\n  | e => do\n    let as \u2190 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 \u2115 := do\n  let ncoes \u2190 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 ) \u2190 open_pis ty\n          let\n            ( lhs , rhs )\n              \u2190\n              match\n                ty\n                with\n                | q( $ ( lhs ) = $ ( rhs ) ) => pure ( lhs , rhs )\n                  | q( $ ( lhs ) \u2194 $ ( rhs ) ) => pure ( lhs , rhs )\n                  | _ => fail \"norm_cast: lemma must be = or \u2194\"\n          let lhs_coes \u2190 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 \u2190 count_internal_coes lhs\n          let rhs_head_coes := count_head_coes rhs\n          let rhs_internal_coes \u2190 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 \u2260 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  \u27e8empty_cache\u27e9\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 \u2190 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 \u2190 cache.up.add e true\n  let new_down \u2190 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 \u2190 cache.squash.add e\n  let new_down \u2190 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 \u2190 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 \u2190 mk_const decl\n  let param \u2190 get_label_param attr decl\n  let l \u2190 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 \u2265, > and \u2260 operators\nprivate theorem ge_from_le {\u03b1} [LE \u03b1] : \u2200 x y : \u03b1, x \u2265 y \u2194 y \u2264 x := fun _ _ => Iff.rfl\n#align norm_cast.ge_from_le norm_cast.ge_from_le\n\nprivate theorem gt_from_lt {\u03b1} [LT \u03b1] : \u2200 x y : \u03b1, x > y \u2194 y < x := fun _ _ => Iff.rfl\n#align norm_cast.gt_from_lt norm_cast.gt_from_lt\n\nprivate theorem ne_from_not_eq {\u03b1} : \u2200 x y : \u03b1, x \u2260 y \u2194 \u00acx = 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    \u2190-- 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 \u2190 up.add_simp `` ge_from_le\n  let up \u2190 up.add_simp `` gt_from_lt\n  let up \u2190 up.add_simp `` ne_from_not_eq\n  let down := cache.down\n  let down \u2190 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 \u2190 (Label.ofString \u2218 toString) <$> ident\n        return l) <|>\n      return none\n  after_set :=\n    some fun decl prio persistent => do\n      let param \u2190 get_label_param norm_cast_attr decl\n      match param with\n        | some l => when (l \u2260 elim) <| simp_attr.push_cast decl () tt prio\n        | none => do\n          let e \u2190 mk_const decl\n          let ty \u2190 infer_type e\n          let l \u2190 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 \u2190 mk_const decl\n  let ty \u2190 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 \u2190 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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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' , _ ) \u2190 simplify s [ ] a { failIfUnchanged := false }\n          let ( b' , b_b' , _ ) \u2190 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 \u2190 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 \u2190 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 (\u2191(x : \u03b1) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nis rewritten to:            op (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nwhen (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) = (\u2191(x : \u03b1) : \u03b3) can be proven with a squash lemma\n-/\nunsafe def splitting_procedure : expr \u2192 tactic (expr \u00d7 expr)\n  | app (app op x) y =>\n    (do\n        let q(@coe $(\u03b1) $(\u03b4) $(coe1) $(xx)) \u2190 return x\n        let q(@coe $(\u03b2) $(\u03b3) $(coe2) $(yy)) \u2190 return y\n        success_if_fail <| is_def_eq \u03b1 \u03b2\n        is_def_eq \u03b4 \u03b3\n        (do\n              let coe3 \u2190 mk_app `has_lift_t [\u03b1, \u03b2] >>= mk_instance_fast\n              let new_x \u2190 to_expr ``(@coe $(\u03b2) $(\u03b4) $(coe2) (@coe $(\u03b1) $(\u03b2) $(coe3) $(xx)))\n              let new_e := app (app op new_x) y\n              let eq_x \u2190 prove_eq_using_down x new_x\n              let pr \u2190 mk_congr_arg op eq_x\n              let pr \u2190 mk_congr_fun pr y\n              return (new_e, pr)) <|>\n            do\n            let coe3 \u2190 mk_app `has_lift_t [\u03b2, \u03b1] >>= mk_instance_fast\n            let new_y \u2190 to_expr ``(@coe $(\u03b1) $(\u03b4) $(coe1) (@coe $(\u03b2) $(\u03b1) $(coe3) $(yy)))\n            let new_e := app (app op x) new_y\n            let eq_y \u2190 prove_eq_using_down y new_y\n            let pr \u2190 mk_congr_arg (app op x) eq_y\n            return (new_e, pr)) <|>\n      (do\n          let q(@coe $(\u03b1) $(\u03b2) $(coe1) $(xx)) \u2190 return x\n          let q(@One.one $(\u03b2) $(h1)) \u2190 return y\n          let h2 \u2190 to_expr ``(One $(\u03b1)) >>= mk_instance_fast\n          let new_y \u2190 to_expr ``(@coe $(\u03b1) $(\u03b2) $(coe1) (@One.one $(\u03b1) $(h2)))\n          let eq_y \u2190 prove_eq_using_down y new_y\n          let new_e := app (app op x) new_y\n          let pr \u2190 mk_congr_arg (app op x) eq_y\n          return (new_e, pr)) <|>\n        (do\n            let q(@coe $(\u03b1) $(\u03b2) $(coe1) $(xx)) \u2190 return x\n            let q(@Zero.zero $(\u03b2) $(h1)) \u2190 return y\n            let h2 \u2190 to_expr ``(Zero $(\u03b1)) >>= mk_instance_fast\n            let new_y \u2190 to_expr ``(@coe $(\u03b1) $(\u03b2) $(coe1) (@Zero.zero $(\u03b1) $(h2)))\n            let eq_y \u2190 prove_eq_using_down y new_y\n            let new_e := app (app op x) new_y\n            let pr \u2190 mk_congr_arg (app op x) eq_y\n            return (new_e, pr)) <|>\n          (do\n              let q(@One.one $(\u03b2) $(h1)) \u2190 return x\n              let q(@coe $(\u03b1) $(\u03b2) $(coe1) $(xx)) \u2190 return y\n              let h1 \u2190 to_expr ``(One $(\u03b1)) >>= mk_instance_fast\n              let new_x \u2190 to_expr ``(@coe $(\u03b1) $(\u03b2) $(coe1) (@One.one $(\u03b1) $(h1)))\n              let eq_x \u2190 prove_eq_using_down x new_x\n              let new_e := app (app op new_x) y\n              let pr \u2190 mk_congr_arg (lam `x BinderInfo.default \u03b2 (app (app op (var 0)) y)) eq_x\n              return (new_e, pr)) <|>\n            do\n            let q(@Zero.zero $(\u03b2) $(h1)) \u2190 return x\n            let q(@coe $(\u03b1) $(\u03b2) $(coe1) $(xx)) \u2190 return y\n            let h1 \u2190 to_expr ``(Zero $(\u03b1)) >>= mk_instance_fast\n            let new_x \u2190 to_expr ``(@coe $(\u03b1) $(\u03b2) $(coe1) (@Zero.zero $(\u03b1) $(h1)))\n            let eq_x \u2190 prove_eq_using_down x new_x\n            let new_e := app (app op new_x) y\n            let pr \u2190 mk_congr_arg (lam `x BinderInfo.default \u03b2 (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 \u00d7 expr) :=\n  (do\n      let r \u2190 condM (is_prop e) (return `iff) (return `eq)\n      let (new_e, pr) \u2190 s.rewrite e prove r\n      let pr \u2190\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 : \u03b1)` to `((n : \u2115) : \u03b1)` where `n` is a numeral and `\u03b1 \u2260 \u2115`.\nReturns a pair of the new expression and proof that they are equal.\n-/\nunsafe def numeral_to_coe (e : expr) : tactic (expr \u00d7 expr) := do\n  let \u03b1 \u2190 infer_type e\n  success_if_fail <| is_def_eq \u03b1 q(\u2115)\n  let n \u2190 e.toNat\n  let h1 \u2190 mk_app `has_lift_t [q(\u2115), \u03b1] >>= mk_instance_fast\n  let new_e : expr := reflect n\n  let new_e \u2190 to_expr ``(@coe \u2115 $(\u03b1) $(h1) $(new_e))\n  let pr \u2190 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 : \u2115) : \u03b1)` to `(n : \u03b1)` 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 \u00d7 expr) := do\n  let q(@coe \u2115 $(\u03b1) $(h1) $(e')) \u2190 return e\n  let n \u2190 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 \u2190 expr.of_nat \u03b1 n\n  let pr \u2190 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' {\u03b1} (a : \u03b1) (pre : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr))\n    (e : expr) (cfg : SimpConfig := { }) : tactic (\u03b1 \u00d7 expr \u00d7 expr) :=\n  ext_simplify_core a cfg simp_lemmas.mk (fun _ => failed)\n    (fun a _ _ _ e => do\n      let (new_a, new_e, pr) \u2190 pre a e\n      guard \u00acnew_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 \u00d7 expr) := do\n  let cache \u2190 norm_cast_attr.get_cache\n  let e \u2190 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    \u2190 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    \u2190 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    \u2190 simplify cache.squash [] e2 cfg\n  trace_norm_cast \"after squashing: \" e3\n  let-- step 4: post-processing of numerals\n    ((), e4, pr4)\n    \u2190 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 \u00acnew_e == e\n  let pr \u2190 mk_eq_trans pr1 pr2\n  let pr \u2190 mk_eq_trans pr pr3\n  let pr \u2190 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 \u00d7 expr) :=\n  do\n  let (s, _) \u2190 mk_simp_set true [`push_cast] extra_lems\n  let (e, prf, _) \u2190\n    simplify (s.erase\u2093 [`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 \u2190 get_local lc\n    replace_at derive [e] include_goal\n    get_local lc\n  | e => do\n    let t \u2190 infer_type e\n    let e \u2190 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 \u2190 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 \u00d7 expr)) :=\n  decorate_error \"apply_mod_cast failed:\" do\n    let new_e \u2190 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 \u2190 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 \u2190 loc.get_locals\n  let tt \u2190 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 \u00acns <| 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 \u2190 loc.get_locals\n    Monad.mapM'\n        (fun r : rw_rule => do\n          save_info r\n          replace_at derive ns loc\n          rw \u27e8[r], none\u27e9 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 \u2190\n    i_to_expr e <|> do\n        let ty \u2190 target\n        let e \u2190 i_to_expr_strict ``(($(e) : $(ty)))\n        let pty \u2190 pp ty\n        let ptgt \u2190 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 \u2190 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 {\u03b1 \u03b2} [HasLiftT \u03b1 \u03b2] {c : Prop} [Decidable c] {a b : \u03b1} :\n    \u2191(ite c a b) = ite c (\u2191a : \u03b2) (\u2191b : \u03b2) := by by_cases h : c <;> simp [h]\n#align ite_cast ite_cast\n\n@[norm_cast]\ntheorem dite_cast {\u03b1 \u03b2} [HasLiftT \u03b1 \u03b2] {c : Prop} [Decidable c] {a : c \u2192 \u03b1} {b : \u00acc \u2192 \u03b1} :\n    \u2191(dite c a b) = dite c (fun h => (\u2191(a h) : \u03b2)) fun h => (\u2191(b h) : \u03b2) := 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 : \u2124\nh : \u2191a + \u2191b < (10 : \u211a)\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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 `\u2191`, `\u21d1` and `\u21a5`, 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 : \u2115} : (\u2191m : \u2124) = \u2191n \u2194 m = n\n\n@[norm_cast] theorem coe_int_denom (n : \u2124) : (n : \u211a).denom = 1\n\n@[norm_cast] theorem cast_id : \u2200 n : \u211a, \u2191n = n\n\n@[norm_cast] theorem coe_nat_add (m n : \u2115) : (\u2191(m + n) : \u2124) = \u2191m + \u2191n\n\n@[norm_cast] theorem cast_sub [add_group \u03b1] [has_one \u03b1] {m n} (h : m \u2264 n) :\n  ((n - m : \u2115) : \u03b1) = n - m\n\n@[norm_cast] theorem coe_nat_bit0 (n : \u2115) : (\u2191(bit0 n) : \u2124) = bit0 \u2191n\n\n@[norm_cast] theorem cast_coe_nat (n : \u2115) : ((n : \u2124) : \u03b1) = n\n\n@[norm_cast] theorem cast_one : ((1 : \u211a) : \u03b1) = 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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 : \u2115) : (n : \u2102).re = n :=\nby rw [\u2190 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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) \"\u27e8\" \"\u27e9\"  : term -- overload `\u27e8 \u27e9` 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 \u2190 `(Nat.zero)\n  withMacroExpansion stx stxNew $\n    elabTerm stxNew expectedType?\n\ndef foo (x : Unit) := x\n\ndef f1 : Unit :=\nlet x := \u27e8 \u27e9\nfoo x\n\ndef f2 : Unit :=\nlet x := \u27e8 \u27e9\nx\n\ndef f3 : Nat :=\nlet x := \u27e8 \u27e9\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": "example (h : {a b : \u03b1} \u2192 a = b) : 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/autoBoundErrorMsg.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.043365796136651424, "lm_q1q2_score": 0.01965606089755712}}
{"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 {\u03b1 : Type u_1} (s : multiset \u03b1) :=\n  quot.lift_on s list.nodup sorry\n\n@[simp] theorem coe_nodup {\u03b1 : Type u_1} {l : List \u03b1} : nodup \u2191l \u2194 list.nodup l :=\n  iff.rfl\n\n@[simp] theorem nodup_zero {\u03b1 : Type u_1} : nodup 0 :=\n  list.pairwise.nil\n\n@[simp] theorem nodup_cons {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} : nodup (a ::\u2098 s) \u2194 \u00aca \u2208 s \u2227 nodup s :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_cons\n\ntheorem nodup_cons_of_nodup {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} (m : \u00aca \u2208 s) (n : nodup s) : nodup (a ::\u2098 s) :=\n  iff.mpr nodup_cons { left := m, right := n }\n\ntheorem nodup_singleton {\u03b1 : Type u_1} (a : \u03b1) : nodup (a ::\u2098 0) :=\n  list.nodup_singleton\n\ntheorem nodup_of_nodup_cons {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} (h : nodup (a ::\u2098 s)) : nodup s :=\n  and.right (iff.mp nodup_cons h)\n\ntheorem not_mem_of_nodup_cons {\u03b1 : Type u_1} {a : \u03b1} {s : multiset \u03b1} (h : nodup (a ::\u2098 s)) : \u00aca \u2208 s :=\n  and.left (iff.mp nodup_cons h)\n\ntheorem nodup_of_le {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} (h : s \u2264 t) : nodup t \u2192 nodup s :=\n  le_induction_on h fun (l\u2081 l\u2082 : List \u03b1) => list.nodup_of_sublist\n\ntheorem not_nodup_pair {\u03b1 : Type u_1} (a : \u03b1) : \u00acnodup (a ::\u2098 a ::\u2098 0) :=\n  list.not_nodup_pair\n\ntheorem nodup_iff_le {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup s \u2194 \u2200 (a : \u03b1), \u00aca ::\u2098 a ::\u2098 0 \u2264 s :=\n  quot.induction_on s\n    fun (l : List \u03b1) => iff.trans list.nodup_iff_sublist (forall_congr fun (a : \u03b1) => not_congr (iff.symm repeat_le_coe))\n\ntheorem nodup_iff_ne_cons_cons {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup s \u2194 \u2200 (a : \u03b1) (t : multiset \u03b1), s \u2260 a ::\u2098 a ::\u2098 t := sorry\n\ntheorem nodup_iff_count_le_one {\u03b1 : Type u_1} [DecidableEq \u03b1] {s : multiset \u03b1} : nodup s \u2194 \u2200 (a : \u03b1), count a s \u2264 1 :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_iff_count_le_one\n\n@[simp] theorem count_eq_one_of_mem {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {s : multiset \u03b1} (d : nodup s) (h : a \u2208 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 {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup s \u2194 pairwise ne s :=\n  quotient.induction_on s fun (l : List \u03b1) => iff.symm (pairwise_coe_iff_pairwise fun (a b : \u03b1) => ne.symm)\n\ntheorem pairwise_of_nodup {\u03b1 : Type u_1} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {s : multiset \u03b1} : (\u2200 (a : \u03b1), a \u2208 s \u2192 \u2200 (b : \u03b1), b \u2208 s \u2192 a \u2260 b \u2192 r a b) \u2192 nodup s \u2192 pairwise r s := sorry\n\ntheorem forall_of_pairwise {\u03b1 : Type u_1} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (H : symmetric r) {s : multiset \u03b1} (hs : pairwise r s) (a : \u03b1) : a \u2208 s \u2192 \u2200 (b : \u03b1), b \u2208 s \u2192 a \u2260 b \u2192 r a b := sorry\n\ntheorem nodup_add {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} : nodup (s + t) \u2194 nodup s \u2227 nodup t \u2227 disjoint s t :=\n  quotient.induction_on\u2082 s t fun (l\u2081 l\u2082 : List \u03b1) => list.nodup_append\n\ntheorem disjoint_of_nodup_add {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} (d : nodup (s + t)) : disjoint s t :=\n  and.right (and.right (iff.mp nodup_add d))\n\ntheorem nodup_add_of_nodup {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} (d\u2081 : nodup s) (d\u2082 : nodup t) : nodup (s + t) \u2194 disjoint s t := sorry\n\ntheorem nodup_of_nodup_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) {s : multiset \u03b1} : nodup (map f s) \u2192 nodup s :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_of_nodup_map f\n\ntheorem nodup_map_on {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {s : multiset \u03b1} : (\u2200 (x : \u03b1), x \u2208 s \u2192 \u2200 (y : \u03b1), y \u2208 s \u2192 f x = f y \u2192 x = y) \u2192 nodup s \u2192 nodup (map f s) :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_map_on\n\ntheorem nodup_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {s : multiset \u03b1} (hf : function.injective f) : nodup s \u2192 nodup (map f s) :=\n  nodup_map_on fun (x : \u03b1) (_x : x \u2208 s) (y : \u03b1) (_x : y \u2208 s) (h : f x = f y) => hf h\n\ntheorem nodup_filter {\u03b1 : Type u_1} (p : \u03b1 \u2192 Prop) [decidable_pred p] {s : multiset \u03b1} : nodup s \u2192 nodup (filter p s) :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_filter p\n\n@[simp] theorem nodup_attach {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup (attach s) \u2194 nodup s :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_attach\n\ntheorem nodup_pmap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {s : multiset \u03b1} {H : \u2200 (a : \u03b1), a \u2208 s \u2192 p a} (hf : \u2200 (a : \u03b1) (ha : p a) (b : \u03b1) (hb : p b), f a ha = f b hb \u2192 a = b) : nodup s \u2192 nodup (pmap f s H) :=\n  quot.induction_on s (fun (l : List \u03b1) (H : \u2200 (a : \u03b1), a \u2208 Quot.mk setoid.r l \u2192 p a) => list.nodup_pmap hf) H\n\nprotected instance nodup_decidable {\u03b1 : Type u_1} [DecidableEq \u03b1] (s : multiset \u03b1) : Decidable (nodup s) :=\n  quotient.rec_on_subsingleton s fun (l : List \u03b1) => list.nodup_decidable l\n\ntheorem nodup_erase_eq_filter {\u03b1 : Type u_1} [DecidableEq \u03b1] (a : \u03b1) {s : multiset \u03b1} : nodup s \u2192 erase s a = filter (fun (_x : \u03b1) => _x \u2260 a) s :=\n  quot.induction_on s fun (l : List \u03b1) (d : nodup (Quot.mk setoid.r l)) => congr_arg coe (list.nodup_erase_eq_filter a d)\n\ntheorem nodup_erase_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] (a : \u03b1) {l : multiset \u03b1} : nodup l \u2192 nodup (erase l a) :=\n  nodup_of_le (erase_le a l)\n\ntheorem mem_erase_iff_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b1} {l : multiset \u03b1} (d : nodup l) : a \u2208 erase l b \u2194 a \u2260 b \u2227 a \u2208 l := sorry\n\ntheorem mem_erase_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {l : multiset \u03b1} (h : nodup l) : \u00aca \u2208 erase l a := sorry\n\ntheorem nodup_product {\u03b1 : Type u_1} {\u03b2 : Type u_2} {s : multiset \u03b1} {t : multiset \u03b2} : nodup s \u2192 nodup t \u2192 nodup (product s t) := sorry\n\ntheorem nodup_sigma {\u03b1 : Type u_1} {\u03c3 : \u03b1 \u2192 Type u_2} {s : multiset \u03b1} {t : (a : \u03b1) \u2192 multiset (\u03c3 a)} : nodup s \u2192 (\u2200 (a : \u03b1), nodup (t a)) \u2192 nodup (multiset.sigma s t) := sorry\n\ntheorem nodup_filter_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 Option \u03b2) {s : multiset \u03b1} (H : \u2200 (a a' : \u03b1) (b : \u03b2), b \u2208 f a \u2192 b \u2208 f a' \u2192 a = a') : nodup s \u2192 nodup (filter_map f s) :=\n  quot.induction_on s fun (l : List \u03b1) => list.nodup_filter_map H\n\ntheorem nodup_range (n : \u2115) : nodup (range n) :=\n  list.nodup_range n\n\ntheorem nodup_inter_left {\u03b1 : Type u_1} [DecidableEq \u03b1] {s : multiset \u03b1} (t : multiset \u03b1) : nodup s \u2192 nodup (s \u2229 t) :=\n  nodup_of_le (inter_le_left s t)\n\ntheorem nodup_inter_right {\u03b1 : Type u_1} [DecidableEq \u03b1] (s : multiset \u03b1) {t : multiset \u03b1} : nodup t \u2192 nodup (s \u2229 t) :=\n  nodup_of_le (inter_le_right s t)\n\n@[simp] theorem nodup_union {\u03b1 : Type u_1} [DecidableEq \u03b1] {s : multiset \u03b1} {t : multiset \u03b1} : nodup (s \u222a t) \u2194 nodup s \u2227 nodup t := sorry\n\n@[simp] theorem nodup_powerset {\u03b1 : Type u_1} {s : multiset \u03b1} : nodup (powerset s) \u2194 nodup s := sorry\n\ntheorem nodup_powerset_len {\u03b1 : Type u_1} {n : \u2115} {s : multiset \u03b1} (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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {s : multiset \u03b1} {t : \u03b1 \u2192 multiset \u03b2} : nodup (bind s t) \u2194 (\u2200 (a : \u03b1), a \u2208 s \u2192 nodup (t a)) \u2227 pairwise (fun (a b : \u03b1) => disjoint (t a) (t b)) s := sorry\n\ntheorem nodup_ext {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} : nodup s \u2192 nodup t \u2192 (s = t \u2194 \u2200 (a : \u03b1), a \u2208 s \u2194 a \u2208 t) :=\n  quotient.induction_on\u2082 s t\n    fun (l\u2081 l\u2082 : List \u03b1) (d\u2081 : nodup (quotient.mk l\u2081)) (d\u2082 : nodup (quotient.mk l\u2082)) =>\n      iff.trans quotient.eq (list.perm_ext d\u2081 d\u2082)\n\ntheorem le_iff_subset {\u03b1 : Type u_1} {s : multiset \u03b1} {t : multiset \u03b1} : nodup s \u2192 (s \u2264 t \u2194 s \u2286 t) :=\n  quotient.induction_on\u2082 s t\n    fun (l\u2081 l\u2082 : List \u03b1) (d : nodup (quotient.mk l\u2081)) => { mp := subset_of_le, mpr := list.subperm_of_subset_nodup d }\n\ntheorem range_le {m : \u2115} {n : \u2115} : range m \u2264 range n \u2194 m \u2264 n :=\n  iff.trans (le_iff_subset (nodup_range m)) range_subset\n\ntheorem mem_sub_of_nodup {\u03b1 : Type u_1} [DecidableEq \u03b1] {a : \u03b1} {s : multiset \u03b1} {t : multiset \u03b1} (d : nodup s) : a \u2208 s - t \u2194 a \u2208 s \u2227 \u00aca \u2208 t := sorry\n\ntheorem map_eq_map_of_bij_of_nodup {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b3) {s : multiset \u03b1} {t : multiset \u03b2} (hs : nodup s) (ht : nodup t) (i : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b2) (hi : \u2200 (a : \u03b1) (ha : a \u2208 s), i a ha \u2208 t) (h : \u2200 (a : \u03b1) (ha : a \u2208 s), f a = g (i a ha)) (i_inj : \u2200 (a\u2081 a\u2082 : \u03b1) (ha\u2081 : a\u2081 \u2208 s) (ha\u2082 : a\u2082 \u2208 s), i a\u2081 ha\u2081 = i a\u2082 ha\u2082 \u2192 a\u2081 = a\u2082) (i_surj : \u2200 (b : \u03b2), b \u2208 t \u2192 \u2203 (a : \u03b1), \u2203 (ha : a \u2208 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": "\n\ndef ex1 : IO Unit := do\nIO.println \"example 1\"\nfor x in [:100:10] do\n  IO.println s!\"x: {x}\"\n\n#eval ex1\n\ndef ex2 : IO Unit := do\nIO.println \"example 2\"\nfor x in [:10] do\n  IO.println s!\"x: {x}\"\n\n#eval ex2\n\ndef ex3 : IO Unit := do\nIO.println \"example 3\"\nfor x in [1:10] do\n  IO.println s!\"x: {x}\"\n\n#eval ex3\n\ndef ex4 : IO Unit := do\nIO.println \"example 4\"\nfor x in [1:10:3] do\n  IO.println s!\"x: {x}\"\n\n#eval ex4\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/range.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.27825679370240214, "lm_q2_score": 0.0705596020506861, "lm_q1q2_score": 0.01963368863154135}}
{"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 \u2192 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 \u2192 Z} (hg : definable S g) {f : X \u2192 Y} (hf : definable S f) :\n  definable S (g \u2218 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 \u27e8x.definable, y.definable\u27e9\nend\n\nlemma definable.fst : definable S (prod.fst : X \u00d7 Y \u2192 X) :=\nbegin [defin]\n  intro p,\n  exact p.definable.1\nend\n\nlemma definable.snd : definable S (prod.snd : X \u00d7 Y \u2192 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 := \u03bb K f, true,\n  definable_precomp := \u03bb L K \u03c6 f hf, trivial,\n  definable_cover := \u03bb K f \ud835\udcdb 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 := \u03bb K f, def_set S f,\n  definable_precomp := \u03bb L K \u03c6 f hf, \u03c6.is_definable.preimage hf,\n  definable_cover := \u03bb K f \ud835\udcdb h, Def.set_subcanonical \ud835\udcdb 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 ((\u2192) : Prop \u2192 Prop \u2192 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 \u2192 Prop), by apply_instance\n\nlemma definable.mem : definable S ((\u2208) : X \u2192 set X \u2192 Prop) :=\nbegin [defin]\n  intro x,\n  intro s,\n  app, var, var\nend\n\nlemma definable.inter : definable S ((\u2229) : set X \u2192 set X \u2192 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 ((\u222a) : set X \u2192 set X \u2192 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 \u2192 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 \u2192 set X \u2192 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 := \u03bb K f, definable_sheaf.definable (subtype.val \u2218 f),\n  definable_precomp := \u03bb L K \u03c6 f hf,\n    definable_sheaf.definable_precomp \u03c6 (subtype.val \u2218 f) hf,\n  definable_cover := \u03bb K f \ud835\udcdb hf,\n    definable_sheaf.definable_cover (subtype.val \u2218 f) \ud835\udcdb hf }\n\ninstance subtype.definable_sheaf {p : X \u2192 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 \u2192 X) :=\nbegin [defin]\n  intro v,\n  exact v.definable\nend\n\nlemma definable_of_subtype_val {s : set Y} {f : X \u2192 s}\n  (hf : definable S (subtype.val \u2218 f)) : definable S f :=\nbegin\n  cases hf with hf,\n  exact \u27e8\u03bb K, hf K\u27e9\nend\n\n-- How to state definable subtype.mk?\n/-\nlemma definable.subtype.mk {s : set X} :\n  definable S (subtype.mk : \u03a0 (x : X), x \u2208 s \u2192 s) :=\nbegin\nend\n-/\n\nlemma definable_subtype.map {s : set X} {t : set Y} {f : X \u2192 Y} (hf : definable S f)\n  (h : \u2200 x \u2208 s, f x \u2208 t) : definable S (subtype.map f h : s \u2192 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) \"\u27e8\" \"\u27e9\"  : term -- overload `\u27e8 \u27e9` 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 \u2190 `(Nat.zero)\n  withMacroExpansion stx stxNew $\n    elabTerm stxNew expectedType?\n\ndef foo (x : Unit) := x\n\ndef f1 : Unit :=\nlet x := \u27e8 \u27e9\nfoo x\n\ndef f2 : Unit :=\nlet x := \u27e8 \u27e9\nx\n\ndef f3 : Nat :=\nlet x := \u27e8 \u27e9\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 \u2192 Typ.Check\n| void\n| any\nderiving Inhabited\n\nnamespace Typ\n\ndef Primitive.toString : Typ.Primitive \u2192 String\n  | .int  => \"int\"\n  | .bool => \"bool\"\ninstance : ToString Primitive where toString := Primitive.toString\n\nmutual\ndef Memory.toString : Typ.Memory \u2192 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 \u2192 String\n  | .prim (p : Primitive) => Primitive.toString p\n  | .mem (m : Typ.Memory) => Memory.toString m\nend\n\ndef Check.toString : Check \u2192 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 \u2194 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 \u2194 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 \u2218 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 \u2218 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 \u2192 Bool\n  | .prim .int => true\n  | .prim .bool => true\n  | _ => false\ndef Check.isScalar : Typ.Check \u2192 Bool\n  | .type t => t.isScalar\n  | _ => false\n\ndef isSmall : Typ \u2192 Bool\n  | .mem (.struct _) => false\n  | _ => true\ndef Check.isSmall : Typ.Check \u2192 Bool\n  | .type t => t.isSmall\n  | _ => true\n\ndef sizeof : Typ \u2192 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 \u2192 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": "/- Basic theorems about bool -/\n\n@[simp]\nlemma coe_sort_bool_to_equality (b:bool) : @coe_sort _ coe_sort_bool b = (b = tt) :=\nbegin\n  cases b,\n  all_goals { simp [coe_sort, has_coe_to_sort.coe]},\nend\n", "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/bool.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.05033063384389279, "lm_q1q2_score": 0.019559390894500428}}
{"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.Tactic.Simp\nimport Lean.Meta.Tactic.Replace\nimport Lean.Elab.BuiltinNotation\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.Tactic.ElabTerm\nimport Lean.Elab.Tactic.Location\nimport Lean.Elab.Tactic.Config\n\nnamespace Lean.Elab.Tactic\nopen Meta\nopen TSyntax.Compat\nopen Simp (UsedSimps)\n\ndeclare_config_elab elabSimpConfigCore    Meta.Simp.Config\ndeclare_config_elab elabSimpConfigCtxCore Meta.Simp.ConfigCtx\ndeclare_config_elab elabDSimpConfigCore   Meta.DSimp.Config\n\ninductive SimpKind where\n  | simp\n  | simpAll\n  | dsimp\n  deriving Inhabited, BEq\n\n/--\n  Implement a `simp` discharge function using the given tactic syntax code.\n  Recall that `simp` dischargers are in `SimpM` which does not have access to `Term.State`.\n  We need access to `Term.State` to store messages and update the info tree.\n  Thus, we create an `IO.ref` to track these changes at `Term.State` when we execute `tacticCode`.\n  We must set this reference with the current `Term.State` before we execute `simp` using the\n  generated `Simp.Discharge`. -/\ndef tacticToDischarge (tacticCode : Syntax) : TacticM (IO.Ref Term.State \u00d7 Simp.Discharge) := do\n  let tacticCode \u2190 `(tactic| try ($tacticCode:tacticSeq))\n  let ref \u2190 IO.mkRef (\u2190 getThe Term.State)\n  let ctx \u2190 readThe Term.Context\n  let disch : Simp.Discharge := fun e => do\n    let mvar \u2190 mkFreshExprSyntheticOpaqueMVar e `simp.discharger\n    let s \u2190 ref.get\n    let runTac? : TermElabM (Option Expr) :=\n      try\n        /- We must only save messages and info tree changes. Recall that `simp` uses temporary metavariables (`withNewMCtxDepth`).\n           So, we must not save references to them at `Term.State`. -/\n        withoutModifyingStateWithInfoAndMessages do\n          Term.withSynthesize (mayPostpone := false) <| Term.runTactic mvar.mvarId! tacticCode\n          let result \u2190 instantiateMVars mvar\n          if result.hasExprMVar then\n            return none\n          else\n            return some result\n      catch _ =>\n        return none\n    let (result?, s) \u2190 liftM (m := MetaM) <| Term.TermElabM.run runTac? ctx s\n    ref.set s\n    return result?\n  return (ref, disch)\n\ninductive Simp.DischargeWrapper where\n  | default\n  | custom (ref : IO.Ref Term.State) (discharge : Simp.Discharge)\n\ndef Simp.DischargeWrapper.with (w : Simp.DischargeWrapper) (x : Option Simp.Discharge \u2192 TacticM \u03b1) : TacticM \u03b1 := do\n  match w with\n  | default => x none\n  | custom ref d =>\n    ref.set (\u2190 getThe Term.State)\n    try\n      x d\n    finally\n      set (\u2190 ref.get)\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) \u2190 tacticToDischarge optDischargeSyntax[0][3]\n    return Simp.DischargeWrapper.custom ref d\n\n/-\n  `optConfig` is of the form `(\"(\" \"config\" \":=\" term \")\")?`\n-/\ndef elabSimpConfig (optConfig : Syntax) (kind : SimpKind) : TermElabM Meta.Simp.Config := do\n  match kind with\n  | .simp    => elabSimpConfigCore optConfig\n  | .simpAll => return (\u2190 elabSimpConfigCtxCore optConfig).toConfig\n  | .dsimp   => return { (\u2190 elabDSimpConfigCore optConfig) with }\n\nprivate def addDeclToUnfoldOrTheorem (thms : Meta.SimpTheorems) (id : Origin) (e : Expr) (post : Bool) (inv : Bool) (kind : SimpKind) : MetaM Meta.SimpTheorems := do\n  if e.isConst then\n    let declName := e.constName!\n    let info \u2190 getConstInfo declName\n    if (\u2190 isProp info.type) then\n      thms.addConst declName (post := post) (inv := inv)\n    else\n      if inv then\n        throwError \"invalid '\u2190' modifier, '{declName}' is a declaration name to be unfolded\"\n      if kind == .dsimp then\n        return thms.addDeclToUnfoldCore declName\n      else\n        thms.addDeclToUnfold declName\n  else\n    thms.add id #[] e (post := post) (inv := inv)\n\nprivate def addSimpTheorem (thms : Meta.SimpTheorems) (id : Origin) (stx : Syntax) (post : Bool) (inv : Bool) : TermElabM Meta.SimpTheorems := do\n  let (levelParams, proof) \u2190 Term.withoutModifyingElabMetaStateWithInfo <| withRef stx <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx none\n    Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)\n    let e \u2190 instantiateMVars e\n    let e := e.eta\n    if e.hasMVar then\n      let r \u2190 abstractMVars e\n      return (r.paramNames, r.expr)\n    else\n      return (#[], e)\n  thms.add id levelParams proof (post := post) (inv := inv)\n\nstructure ElabSimpArgsResult where\n  ctx     : Simp.Context\n  starArg : Bool := false\n\ninductive ResolveSimpIdResult where\n  | none\n  | expr (e : Expr)\n  | ext  (ext : SimpExtension)\n\n/--\n  Elaborate extra simp theorems provided to `simp`. `stx` is of the form `\"[\" simpTheorem,* \"]\"`\n  If `eraseLocal == true`, then we consider local declarations when resolving names for erased theorems (`- id`),\n  this option only makes sense for `simp_all` or `*` is used.\n-/\ndef elabSimpArgs (stx : Syntax) (ctx : Simp.Context) (eraseLocal : Bool) (kind : SimpKind) : TacticM ElabSimpArgsResult := do\n  if stx.isNone then\n    return { ctx }\n  else\n    /-\n    syntax simpPre := \"\u2193\"\n    syntax simpPost := \"\u2191\"\n    syntax simpLemma := (simpPre <|> simpPost)? term\n\n    syntax simpErase := \"-\" ident\n    -/\n    withMainContext do\n      let mut thmsArray := ctx.simpTheorems\n      let mut thms      := thmsArray[0]!\n      let mut starArg   := false\n      for arg in stx[1].getSepArgs do\n        if arg.getKind == ``Lean.Parser.Tactic.simpErase then\n          let fvar \u2190 if eraseLocal || starArg then Term.isLocalIdent? arg[1] else pure none\n          if let some fvar := fvar then\n            -- We use `eraseCore` because the simp theorem for the hypothesis was not added yet\n            thms := thms.eraseCore (.fvar fvar.fvarId!)\n          else\n            let declName \u2190 resolveGlobalConstNoOverloadWithInfo arg[1]\n            if ctx.config.autoUnfold then\n              thms := thms.eraseCore (.decl declName)\n            else\n              thms \u2190 thms.erase (.decl 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\n          match (\u2190 resolveSimpIdTheorem? term) with\n          | .expr e  =>\n            let name \u2190 mkFreshId\n            thms \u2190 addDeclToUnfoldOrTheorem thms (.stx name arg) e post inv kind\n          | .ext ext =>\n            thmsArray := thmsArray.push (\u2190 ext.getTheorems)\n          | .none    =>\n            let name \u2190 mkFreshId\n            thms \u2190 addSimpTheorem thms (.stx name arg) 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 simpTheorems := thmsArray.set! 0 thms }, starArg }\nwhere\n  resolveSimpIdTheorem? (simpArgTerm : Term) : TacticM ResolveSimpIdResult := do\n    let resolveExt (n : Name) : TacticM ResolveSimpIdResult := do\n      if let some ext \u2190 getSimpExtension? n then\n        return .ext ext\n      else\n        return .none\n    match simpArgTerm with\n    | `($id:ident) =>\n      try\n        if let some e \u2190 Term.resolveId? simpArgTerm (withInfo := true) then\n          return .expr e\n        else\n          resolveExt id.getId.eraseMacroScopes\n      catch _ =>\n        resolveExt id.getId.eraseMacroScopes\n    | _ =>\n      if let some e \u2190 Term.elabCDotFunctionAlias? simpArgTerm then\n        return .expr e\n      else\n        return .none\n\n@[inline] def simpOnlyBuiltins : List Name := [``eq_self, ``iff_self]\n\nstructure MkSimpContextResult where\n  ctx              : Simp.Context\n  dischargeWrapper : Simp.DischargeWrapper\n\n/--\n   Create the `Simp.Context` for the `simp`, `dsimp`, and `simp_all` tactics.\n   If `kind != SimpKind.simp`, the `discharge` option must be `none`\n\n   TODO: generate error message if non `rfl` theorems are provided as arguments to `dsimp`.\n-/\ndef mkSimpContext (stx : Syntax) (eraseLocal : Bool) (kind := SimpKind.simp) (ignoreStarArg : Bool := false) : TacticM MkSimpContextResult := do\n  if !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 \u2190 mkDischargeWrapper stx[2]\n  let simpOnly := !stx[3].isNone\n  let simpTheorems \u2190 if simpOnly then\n    simpOnlyBuiltins.foldlM (\u00b7.addConst \u00b7) ({} : SimpTheorems)\n  else\n    getSimpTheorems\n  let congrTheorems \u2190 getSimpCongrTheorems\n  let r \u2190 elabSimpArgs stx[4] (eraseLocal := eraseLocal) (kind := kind) {\n    config      := (\u2190 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 ctx := r.ctx\n    let mut simpTheorems := ctx.simpTheorems\n    let hs \u2190 getPropHyps\n    for h in hs do\n      unless simpTheorems.isErased (.fvar h) do\n        simpTheorems \u2190 simpTheorems.addTheorem (.fvar h) (\u2190 h.getDecl).toExpr\n    let ctx := { ctx with simpTheorems }\n    return { ctx, dischargeWrapper }\n\nregister_builtin_option tactic.simp.trace : Bool := {\n  defValue := false\n  descr    := \"When tracing is enabled, calls to `simp` or `dsimp` will print an equivalent `simp only` call.\"\n}\n\ndef traceSimpCall (stx : Syntax) (usedSimps : UsedSimps) : MetaM Unit := 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 \u2190 getLCtx\n  let env \u2190 getEnv\n  for (thm, _) in usedSimps.toArray.qsort (\u00b7.2 < \u00b7.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 (\u2190 `(Parser.Tactic.simpLemma| $(mkIdent (\u2190 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 ++ (\u2190 locals.mapM fun id => `(Parser.Tactic.simpLemma| $(mkIdent id):ident))\n  else\n    args := args.push (\u2190 `(Parser.Tactic.simpStar| *))\n  let argsStx := if args.isEmpty then #[] else #[mkAtom \"[\", (mkAtom \",\").mkSep args, mkAtom \"]\"]\n  stx := stx.setArg 4 (mkNullNode argsStx)\n  logInfoAt stx[0] m!\"Try this: {stx}\"\n\n/--\n`simpLocation ctx discharge? varIdToLemmaId loc`\nruns the simplifier at locations specified by `loc`,\nusing the simp theorems collected in `ctx`\noptionally running a discharger specified in `discharge?` on generated subgoals.\n\nIts primary use is as the implementation of the\n`simp [...] at ...` and `simp only [...] at ...` syntaxes,\nbut can also be used by other tactics when a `Syntax` is not available.\n\nFor many tactics other than the simplifier,\none should use the `withLocation` tactic combinator\nwhen working with a `location`.\n-/\ndef simpLocation (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (loc : Location) : TacticM UsedSimps := do\n  match loc with\n  | Location.targets hyps simplifyTarget =>\n    withMainContext do\n      let fvarIds \u2190 getFVarIds hyps\n      go fvarIds simplifyTarget\n  | Location.wildcard =>\n    withMainContext do\n      go (\u2190 (\u2190 getMainGoal).getNondepPropHyps) (simplifyTarget := true)\nwhere\n  go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM UsedSimps := do\n    let mvarId \u2190 getMainGoal\n    let (result?, usedSimps) \u2190 simpGoal mvarId ctx (simplifyTarget := simplifyTarget) (discharge? := discharge?) (fvarIdsToSimp := fvarIdsToSimp)\n    match result? with\n    | none => replaceMainGoal []\n    | some (_, mvarId) => replaceMainGoal [mvarId]\n    return usedSimps\n\n/-\n  \"simp \" (config)? (discharger)? (\"only \")? (\"[\" simpLemma,* \"]\")? (location)?\n-/\n@[builtin_tactic Lean.Parser.Tactic.simp] def evalSimp : Tactic := fun stx => do\n  let { ctx, dischargeWrapper } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false)\n  let usedSimps \u2190 dischargeWrapper.with fun discharge? =>\n    simpLocation ctx discharge? (expandOptLocation stx[5])\n  if tactic.simp.trace.get (\u2190 getOptions) then\n    traceSimpCall stx usedSimps\n\n@[builtin_tactic Lean.Parser.Tactic.simpAll] def evalSimpAll : Tactic := fun stx => do\n  let { ctx, .. } \u2190 mkSimpContext stx (eraseLocal := true) (kind := .simpAll) (ignoreStarArg := true)\n  let (result?, usedSimps) \u2190 simpAll (\u2190 getMainGoal) ctx\n  match result? with\n  | none => replaceMainGoal []\n  | some mvarId => replaceMainGoal [mvarId]\n  if tactic.simp.trace.get (\u2190 getOptions) then\n    traceSimpCall stx usedSimps\n\ndef dsimpLocation (ctx : Simp.Context) (loc : Location) : TacticM Unit := do\n  match loc with\n  | Location.targets hyps simplifyTarget =>\n    withMainContext do\n      let fvarIds \u2190 getFVarIds hyps\n      go fvarIds simplifyTarget\n  | Location.wildcard =>\n    withMainContext do\n      go (\u2190 (\u2190 getMainGoal).getNondepPropHyps) (simplifyTarget := true)\nwhere\n  go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM Unit := do\n    let mvarId \u2190 getMainGoal\n    let (result?, usedSimps) \u2190 dsimpGoal mvarId ctx (simplifyTarget := simplifyTarget) (fvarIdsToSimp := fvarIdsToSimp)\n    match result? with\n    | none => replaceMainGoal []\n    | some mvarId => replaceMainGoal [mvarId]\n    if tactic.simp.trace.get (\u2190 getOptions) then\n      traceSimpCall (\u2190 getRef) usedSimps\n\n@[builtin_tactic Lean.Parser.Tactic.dsimp] def evalDSimp : Tactic := fun stx => do\n  let { ctx, .. } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false) (kind := .dsimp)\n  dsimpLocation ctx (expandOptLocation stx[5])\n\nend Lean.Elab.Tactic\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/Tactic/Simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3593641451601019, "lm_q2_score": 0.054198726767778406, "lm_q1q2_score": 0.01947707911366862}}
{"text": "import Lean\n\nopen Lean\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/-- Implementation of the `lemma` command, by macro expansion to `theorem`. -/\n@[macro \u00ablemma\u00bb] 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 \u00b7 \"theorem\")\n    stx.setKind ``Parser.Command.theorem\n  pure <| stx.setKind ``Parser.Command.declaration\n\nlemma l (x : Nat) : x  = x := rfl", "meta": {"author": "alexkassil", "repo": "natural_number_game_lean4", "sha": "69b60b72139403a64508494441d6c561c24ce66d", "save_path": "github-repos/lean/alexkassil-natural_number_game_lean4", "path": "github-repos/lean/alexkassil-natural_number_game_lean4/natural_number_game_lean4-69b60b72139403a64508494441d6c561c24ce66d/MyNat/lemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.061875982263751246, "lm_q1q2_score": 0.01943218595183449}}
{"text": "import data.set\n\nnamespace probability_theory\n\n-- TODO subtype.restrict?\ndef pi_subtype {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (mv : set \u03b1) := \u03bb (g : \u03a0 i, \u03b2 i) (i : mv), g i\n\n@[reducible]\ndef pi_subtype_img {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (mv : set \u03b1) :=\n  \u03bb (g : set (\u03a0 i, \u03b2 i)) , pi_subtype mv '' g\n\n@[reducible]\ndef pi_unsubtype_img {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (mv : set \u03b1) :=\n  \u03bb (g : set (\u03a0 i : mv, \u03b2 i)), pi_subtype mv \u207b\u00b9' 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 {\u03b1 : Type*} (A : set \u03b1) (B : set \u03b1) : set A := \u03bb x : A, \u2191x \u2208 B\n\ndef pi_set_to_subtype {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (B : set \u03b1)\n  (f : \u03a0 i : B, \u03b2 i) : \u03a0 i : set_to_subtype A B, \u03b2 i := \u03bb \u27e8i, hi\u27e9, f \u27e8i, hi\u27e9\n\nlemma pi_set_to_subtype_def {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (B : set \u03b1)\n  (f : \u03a0 i : B, \u03b2 i) (i : \u03b1) (hi : i \u2208 A) (hi' : i \u2208 B) :\n  pi_set_to_subtype A B f \u27e8\u27e8i, hi\u27e9, hi'\u27e9 = f \u27e8\u2191(\u27e8i, hi\u27e9 : A), hi'\u27e9 := rfl\n\nlemma pi_set_to_subtype_def' {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (B : set \u03b1)\n  (f : \u03a0 i : B, \u03b2 i) (i : set_to_subtype A B) :\n  pi_set_to_subtype A B f i = f \u27e8\u2191(\u27e8i.val.val, i.val.property\u27e9 : A), i.property\u27e9 :=\nbegin\n  obtain \u27e8\u27e8_, _\u27e9, _\u27e9 := i,\n  rw pi_set_to_subtype_def,\nend\n\nlemma pi_set_to_subtype_bijective {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} {A : set \u03b1} {B : set \u03b1} (hAB : B \u2286 A)\n  : function.bijective (@pi_set_to_subtype _ \u03b2 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 \u27e8\u27e8i, hAB i.property\u27e9, i.property\u27e9,\n    convert h; exact subtype.eq rfl },\n  { intro f,\n    refine \u27e8(\u03bb i, f \u27e8\u27e8i, hAB i.property\u27e9, i.property\u27e9), _\u27e9,\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 {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} {A : set \u03b1} {B : set \u03b1} (hAB : B \u2286 A) {b : B} (bs : set (\u03b2 b)) :\npi_set_to_subtype A B '' ((\u03bb (g : \u03a0 (i : B), \u03b2 i), g b) \u207b\u00b9' bs)\n= (\u03bb (g : \u03a0 (i : set_to_subtype A B), \u03b2 i), g \u27e8\u27e8b, hAB b.property\u27e9, b.property\u27e9) \u207b\u00b9' bs :=\nbegin\n  ext1 x,\n  split,\n  rintro \u27e8bs', hbs', hbsx'\u27e9,\n  change bs' _ \u2208 bs at hbs',\n  change _ \u2208 bs,\n  subst hbsx',\n  change bs' \u27e8_, _\u27e9 \u2208 _,\n  convert hbs',\n  exact subtype.eq rfl,\n  intro hx,\n  refine \u27e8\u03bb b : B, x \u27e8\u27e8b, hAB b.property\u27e9, b.property\u27e9, hx, _\u27e9, ext \u27e8\u27e8_, _\u27e9, _\u27e9, refl\nend\n\n@[reducible]\ndef pi_unsubtype_set {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (B : set \u03b1) :\n  set (\u03a0 i : B, \u03b2 i) \u2192 set (\u03a0 i : A, \u03b2 i)\n  := \u03bb 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 {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (a : set (\u03a0 i : A, \u03b2 i)) :\n  >>[A] a = a :=\nbegin\n  rw pi_unsubtype_set,\n  rw pi_unsubtype_img,\n  change (_ \u207b\u00b9' (_ '' a)) = a,\n  -- TODO extract\n  convert @set.preimage_image_eq _ _ (@pi_set_to_subtype _ \u03b2 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 {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} {A : set \u03b1}\n{f : \u03a0 i, \u03b2 i} {g : \u03a0 i : A, \u03b2 i} : pi_subtype A f = g \u2194 \u2200 i : A, f i = g i :=\nby rw function.funext_iff; refl\n\n--lemma pi_subtype_ext' {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} {A : set \u03b1} {f g : \u03a0 i, \u03b2 i} :\n--pi_subtype A f = pi_subtype A g \u2194 \u2200 i \u2208 A, f i = g i := sorry\n\nlemma pi_subtype_subtype {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (B : set \u03b1) \n  (x : \u03a0 i : \u03b1, \u03b2 i) :\n  pi_subtype (set_to_subtype A B) (pi_subtype A x) = \u03bb (i : set_to_subtype A B), x i := rfl\n\nlemma pi_unsubtype_union_img_def {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} [\u2200 i : \u03b1, inhabited (\u03b2 i)]\n  (A : set \u03b1) (B : set \u03b1) (sb : set (\u03a0 i : B, \u03b2 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 \u27e8x', h', h\u27e9 := h,\n    classical,\n    let y : \u03a0 i, \u03b2 i := \u03bb i, if h : i \u2208 B then x' \u27e8i, h\u27e9\n      else if h : i \u2208 A then x \u27e8i, h\u27e9 else default,\n    refine \u27e8y, _, _\u27e9,\n    change pi_subtype B y \u2208 sb,\n    convert h',\n    all_goals {refine pi_subtype_ext.mpr _, rintro \u27e8i, hi\u27e9},\n      exact dif_pos hi,\n    by_cases hi' : i \u2208 B,\n      convert dif_pos hi',\n      exact (congr_fun h \u27e8\u27e8_, hi\u27e9, hi'\u27e9).symm,\n    exact (dif_neg hi').trans (dif_pos hi) },\n  { obtain \u27e8_, h', rfl\u27e9 := h,\n    refine \u27e8pi_subtype B _, h', _\u27e9,\n    ext \u27e8\u27e8_, _\u27e9, _\u27e9, refl }\nend\n\ndef pi_subtype_subtype_subset {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} {A : set \u03b1} {B : set \u03b1}\n  (hba : B \u2286 A) (sb : set (\u03a0 i : B, \u03b2 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 \u27e8pi_subtype B x, h, _\u27e9, ext \u27e8\u27e8_, _\u27e9, _\u27e9, refl },\n  { obtain \u27e8_, h', h\u27e9 := h,\n    change pi_subtype B x \u2208 sb,\n    convert h',\n    refine pi_subtype_ext.mpr _,\n    rintro \u27e8_, hi\u27e9,\n    exact (congr_fun h \u27e8\u27e8_, hba hi\u27e9, _\u27e9).symm }\nend\n\nlemma pi_unsubtype_union_img_inter {\u03b1 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (A : set \u03b1) (B : set \u03b1)\n  (a : set (\u03a0 i : A, \u03b2 i)) (b : set (\u03a0 i : B, \u03b2 i)) :\n  >[] (>>[A \u222a B] a \u2229 >>[A \u222a B] b) = >[] a \u2229 >[] 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} (\u03b1 : Type u)\n| done  : \u03b1 \u2192 Step \u03b1\n| yield : \u03b1 \u2192 Step \u03b1\n\nclass Fold.{u, v, w, z} (m : Type w \u2192 Type z) [Monad m] (\u03b1 : outParam (Type u)) (s : Type v) : Type (max v u z (w+1)):=\n(fold {\u03b2 : Type w} (as : s) (init : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (Step \u03b2)) : m \u03b2)\n\nexport Fold (fold)\n\nclass FoldMap.{u, w} (m : Type u \u2192 Type w) [Monad m] (s : Type u \u2192 Type u) : Type (max (u+1) w):=\n(foldMap {\u03b1 \u03b2 : Type u} (as : s \u03b1) (init : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (Step (\u03b1 \u00d7 \u03b2))) : m (s \u03b1 \u00d7 \u03b2))\n\nexport FoldMap (foldMap)\n\n@[inline] instance {m} {\u03b1} [Monad m] : Fold m \u03b1 (List \u03b1) :=\n{ fold := fun as init f =>\n    let rec @[specialize] loop\n      | [], b    => pure b\n      | a::as, b => do\n        let s \u2190 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 \u2190 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) \u2190 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 \u03b1 \u03b2 \u03b3 \u03b4} [Monad m] [i\u2081 : Fold m \u03b1 \u03b3] [i\u2082 : Fold m \u03b2 \u03b4] : Fold m (\u03b1 \u00d7 \u03b2) (\u03b3 \u00d7 \u03b4) :=\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 \u2190 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 \u2192 _ \u2192 _\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 \u2190 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      => \u27e80, a\u27e9\n| some b    => \u27e8a, b\u27e9\n\ninstance : OfNat (Option Nat) :=\n\u27e8fun n => some n\u27e9\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} \u2192 a < b \u2192 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} {\u03b1} [Monad m] : Fold m \u03b1 (Array \u03b1) :=\n{ fold := fun as init f =>\n    let rec @[specialize] loop : (i : Nat) \u2192 i \u2264 as.size \u2192 _\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 \u2190 f (as.get \u27e8as.size - 1 - i, this\u27e9) 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 : \u03b1 \u2192 \u03b2) : none.map f = none := rfl\n@[simp] theorem map_some' (a) (f : \u03b1 \u2192 \u03b2) : (some a).map f = some (f a) := rfl\n\n@[simp] theorem none_bind (f : \u03b1 \u2192 Option \u03b2) : none.bind f = none := rfl\n@[simp] theorem some_bind (a) (f : \u03b1 \u2192 Option \u03b2) : (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) \u2192 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) \u2192 (B : ByteArray) \u2192 (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 \u2192 Target)\n\nexport Into (into)\n\ninstance (A: Type u) : Into A A := \u27e8id\u27e9\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": "/-\nCopyright (c) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn\n-/\nimport data.string.defs\nimport tactic.derive_inhabited\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\nopen tactic\n\nattribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind\n\nnamespace binder_info\n\n/-! ### Declarations about `binder_info` -/\n\ninstance : inhabited binder_info := \u27e8 binder_info.default \u27e9\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : binder_info \u2192 string \u00d7 string\n| binder_info.implicit        := (\"{\", \"}\")\n| binder_info.strict_implicit := (\"{{\", \"}}\")\n| binder_info.inst_implicit   := (\"[\", \"]\")\n| _                           := (\"(\", \")\")\n\nend binder_info\n\nnamespace name\n\n/-! ### Declarations about `name` -/\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef map_prefix (f : name \u2192 option name) : name \u2192 name\n| anonymous := anonymous\n| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')\n| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\nmeta def deinternalize_field : name \u2192 name\n| (mk_string s name.anonymous) :=\n  let i := s.mk_iterator in\n  if i.curr = '_' then i.next.next_to_string else s\n| n := n\n\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\nmeta def get_nth_prefix : name \u2192 \u2115 \u2192 name\n| nm 0 := nm\n| nm (n + 1) := get_nth_prefix nm.get_prefix n\n\n/-- Auxiliary definition for `pop_nth_prefix` -/\nprivate meta def pop_nth_prefix_aux : name \u2192 \u2115 \u2192 name \u00d7 \u2115\n| anonymous n := (anonymous, 1)\n| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in\n          if height \u2264 n then (anonymous, height + 1)\n          else (nm.update_prefix pfx, height + 1)\n\n/-- Pops the top `n` prefixes from the given name. -/\nmeta def pop_nth_prefix (nm : name) (n : \u2115) : name :=\nprod.fst $ pop_nth_prefix_aux nm n\n\n/-- Pop the prefix of a name -/\nmeta def pop_prefix (n : name) : name :=\npop_nth_prefix n 1\n\n/-- Auxiliary definition for `from_components` -/\nprivate def from_components_aux : name \u2192 list string \u2192 name\n| n [] := n\n| n (s :: rest) := from_components_aux (name.mk_string s n) rest\n\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef from_components : list string \u2192 name :=\nfrom_components_aux name.anonymous\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\nmeta def sanitize_name : name \u2192 name\n| name.anonymous := name.anonymous\n| (name.mk_string s p) := name.mk_string s $ sanitize_name p\n| (name.mk_numeral s p) := name.mk_string sformat!\"n{s}\" $ sanitize_name p\n\n/-- Append a string to the last component of a name. -/\ndef append_suffix : name \u2192 string \u2192 name\n| (mk_string s n) s' := mk_string (s ++ s') n\n| n _ := n\n\n/-- Update the last component of a name. -/\ndef update_last (f : string \u2192 string) : name \u2192 name\n| (mk_string s n) := mk_string (f s) n\n| n := n\n\n/-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`,\n  either as prefix or as suffix (specified by `is_prefix`), separated by `_`.\n  Used by `simps_add_projections`. -/\ndef append_to_last (nm : name) (s : string) (is_prefix : bool) : name :=\nnm.update_last $ \u03bb s', if is_prefix then s ++ \"_\" ++ s' else s' ++ \"_\" ++ s\n\n/-- The first component of a name, turning a number to a string -/\nmeta def head : name \u2192 string\n| (mk_string s anonymous) := s\n| (mk_string s p)         := head p\n| (mk_numeral n p)        := head p\n| anonymous               := \"[anonymous]\"\n\n/-- Tests whether the first component of a name is `\"_private\"` -/\nmeta def is_private (n : name) : bool :=\nn.head = \"_private\"\n\n/-- Get the last component of a name, and convert it to a string. -/\nmeta def last : name \u2192 string\n| (mk_string s _)  := s\n| (mk_numeral n _) := repr n\n| anonymous        := \"[anonymous]\"\n\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\nmeta def length : name \u2192 \u2115\n| (mk_string s anonymous) := s.length\n| (mk_string s p)         := s.length + 1 + p.length\n| (mk_numeral n p)        := p.length\n| anonymous               := \"[anonymous]\".length\n\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef has_prefix (P : name \u2192 bool) : name \u2192 bool\n| anonymous := ff\n| (mk_string s nm)  := P (mk_string s nm) \u2228 has_prefix nm\n| (mk_numeral s nm) := P (mk_numeral s nm) \u2228 has_prefix nm\n\n/-- Appends `'` to the end of a name. -/\nmeta def add_prime : name \u2192 name\n| (name.mk_string s p) := name.mk_string (s ++ \"'\") p\n| n := (name.mk_string \"x'\" n)\n\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef last_string : name \u2192 string\n| anonymous        := \"[anonymous]\"\n| (mk_string s _)  := s\n| (mk_numeral _ n) := last_string n\n\n/--\nConstructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\nmeta def from_string (s : string) : name :=\nfrom_components $ s.split (= '.')\n\n\n/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\nlibrary_note \"likely generated binder names\"\n\n/--\nCheck whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_simple_name : string \u2192 bool\n| \"\u1fb0\" := tt\n| n :=\n  match n.get_rest \"\u1fb0_\" with\n  | none := ff\n  | some suffix := suffix.is_nat\n  end\n\n/--\nCheck whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_name (n : name) : bool :=\nmatch n with\n| mk_string s anonymous := is_likely_generated_binder_simple_name s\n| _ := ff\nend\n\nend name\n\nnamespace level\n\n/-! ### Declarations about `level` -/\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\nmeta def nonzero : level \u2192 bool\n| (succ _) := tt\n| (max l\u2081 l\u2082) := l\u2081.nonzero || l\u2082.nonzero\n| (imax _ l\u2082) := l\u2082.nonzero\n| _ := ff\n\n/--\n`l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nmeta def fold_mvar {\u03b1} : level \u2192 (name \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 \u03b1\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 \u2218 fold_mvar b f\n| (imax a b) f := fold_mvar a f \u2218 fold_mvar b f\n\n/--\n`l.params` is the set of parameters occuring in `l`.\nFor example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`.\n-/\nprotected meta def params (u : level) : name_set :=\nu.fold mk_name_set $ \u03bb v l,\n  match v with\n  | (param nm) := l.insert nm\n  | _ := l\n  end\n\nend level\n\n/-! ### Declarations about `binder` -/\n\n/-- The type of binders containing a name, the binding info and the binding type -/\n@[derive decidable_eq, derive inhabited]\nmeta structure binder :=\n  (name : name)\n  (info : binder_info)\n  (type : expr)\n\nnamespace binder\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nprotected meta def to_string (b : binder) : string :=\nlet (l, r) := b.info.brackets in\nl ++ b.name.to_string ++ \" : \" ++ b.type.to_string ++ r\n\nmeta instance : has_to_string binder := \u27e8 binder.to_string \u27e9\nmeta instance : has_to_format binder := \u27e8 \u03bb b, b.to_string \u27e9\nmeta instance : has_to_tactic_format binder :=\n\u27e8 \u03bb b, let (l, r) := b.info.brackets in\n  (\u03bb e, l ++ b.name.to_string ++ \" : \" ++ e ++ r) <$> pp b.type \u27e9\n\nend binder\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n\n/--\n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def nat.mk_numeral (type has_zero has_one has_add : expr) : \u2115 \u2192 expr :=\nlet z : expr := `(@has_zero.zero.{0} %%type %%has_zero),\n    o : expr := `(@has_one.one.{0} %%type %%has_one) in\nnat.binary_rec z\n  (\u03bb b n e, if n = 0 then o else\n    if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)\n    else `(@bit0.{0} %%type %%has_add %%e))\n\n/--\n`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : \u2124 \u2192 expr\n| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add\n| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in\n            `(@has_neg.neg.{0} %%type %%has_neg %%ne)\n\n/--\n`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nmeta def nat.to_pexpr : \u2115 \u2192 pexpr\n| 0 := ``(0)\n| 1 := ``(1)\n| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))\n\n/--\n`int.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(int.to_pexpr (-5)) : \u211a))` will create a native `\u211a` numeral `(-5 : \u211a)`.\n-/\nmeta def int.to_pexpr : \u2124 \u2192 pexpr\n| (int.of_nat k) := k.to_pexpr\n| (int.neg_succ_of_nat k) := ``(-%%((k+1).to_pexpr))\n\nnamespace expr\n\n/--\nTurns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\nprotected meta def to_nat : expr \u2192 option \u2115\n| `(has_zero.zero) := some 0\n| `(has_one.one) := some 1\n| `(bit0 %%e) := bit0 <$> e.to_nat\n| `(bit1 %%e) := bit1 <$> e.to_nat\n| `(nat.succ %%e) := (+1) <$> e.to_nat\n| `(nat.zero) := some 0\n| _ := none\n\n/--\nTurns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\nprotected meta def to_int : expr \u2192 option \u2124\n| `(has_neg.neg %%e) := do n \u2190 e.to_nat, some (-n)\n| e                  := coe <$> e.to_nat\n\n/--\nTurns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`.\n-/\nprotected meta def to_list {\u03b1} (f : expr \u2192 option \u03b1) : expr \u2192 option (list \u03b1)\n| `(list.nil)          := some []\n| `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list\n| _                    := none\n\n/--\n`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\nignoring differences in type and type class arguments.\n-/\nmeta def is_num_eq : expr \u2192 expr \u2192 bool\n| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt\n| `(@has_one.one _ _) `(@has_one.one _ _) := tt\n| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b\n| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b\n| `(-%%a) `(-%%b) := a.is_num_eq b\n| `(%%a/%%a') `(%%b/%%b') :=  a.is_num_eq b\n| _ _ := ff\n\nend expr\n\n/-! ### Declarations about `pexpr` -/\n\nnamespace pexpr\n\n/--\nIf `e` is an annotation of `frozen_name` to `expr.const n`,\n`e.get_frozen_name` returns `n`.\nOtherwise, returns `name.anonymous`.\n-/\nmeta def get_frozen_name (e : pexpr) : name :=\nmatch e.is_annotation with\n| some (`frozen_name, expr.const n _) := n\n| _ := name.anonymous\nend\n\n/--\nIf `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_fn_args` returns `(f, [e\u2081, ... e\u2099])`.\nSee also `expr.get_app_fn_args`.\n-/\nmeta def get_app_fn_args : pexpr \u2192 opt_param (list pexpr) [] \u2192 pexpr \u00d7 list pexpr\n| (expr.app e1 e2) r := get_app_fn_args e1 (e2::r)\n| e1 r := (e1, r)\n\n/--\nIf `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_fn` returns `f`.\nSee also `expr.get_app_fn`.\n-/\nmeta def get_app_fn : pexpr \u2192 list pexpr :=\nprod.snd \u2218 get_app_fn_args\n\n/--\nIf `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_args` returns `[e\u2081, ... e\u2099]`.\nSee also `expr.get_app_args`.\n-/\nmeta def get_app_args : pexpr \u2192 list pexpr :=\nprod.snd \u2218 get_app_fn_args\n\nend pexpr\n\n/-! ### Declarations about `expr` -/\n\nnamespace expr\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\nmeta def clean_ids : list name :=\n[``id, ``id_rhs, ``id_delta, ``hidden]\n\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\nmeta def clean (e : expr) : expr :=\ne.replace (\u03bb e n,\n     match e with\n     | (app (app (const n _) _) e') :=\n       if n \u2208 clean_ids then some e' else none\n     | (app (lam _ _ _ (var 0)) e') := some e'\n     | _ := none\n     end)\n\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\nmeta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=\ne.replace $ \u03bbc d, if c = s then some (s'.lift_vars 0 d) else none\n\n/-- Implementation of `expr.mreplace`. -/\nmeta def mreplace_aux {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) :\n  expr \u2192 \u2115 \u2192 m expr\n| (app f x) n := option.mget_or_else (R (app f x) n)\n  (do Rf \u2190 mreplace_aux f n, Rx \u2190 mreplace_aux x n, return $ app Rf Rx)\n| (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd)\n| (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd)\n| (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n)\n  (do Rty \u2190 mreplace_aux ty n,\n    Ra \u2190 mreplace_aux a n,\n    Rb \u2190 mreplace_aux b n,\n    return $ elet nm Rty Ra Rb)\n| (macro c es) n := option.mget_or_else (R (macro c es) n) $\n    macro c <$> es.mmap (\u03bb e, mreplace_aux e n)\n| e n := option.mget_or_else (R e n) (return e)\n\n/--\nMonadic analogue of `expr.replace`.\n\nThe `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where\n`n` is the number of binders above `e`.\nIf `R s n` fails, the whole replacement fails.\nIf `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit\nits subexpressions).\nIf `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.\n\nWARNING: This function performs exponentially worse on large terms than `expr.replace`,\nif a subexpression occurs more than once in an expression, `expr.replace` visits them only once,\nbut this function will visit every occurence of it. Do not use this on large expressions.\n-/\nmeta def mreplace {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) (e : expr) :\n  m expr :=\nmreplace_aux R e 0\n\n/-- Match a variable. -/\nmeta def match_var {elab} : expr elab \u2192 option \u2115\n| (var n) := some n\n| _ := none\n\n/-- Match a sort. -/\nmeta def match_sort {elab} : expr elab \u2192 option level\n| (sort u) := some u\n| _ := none\n\n/-- Match a constant. -/\nmeta def match_const {elab} : expr elab \u2192 option (name \u00d7 list level)\n| (const n lvls) := some (n, lvls)\n| _ := none\n\n/-- Match a metavariable. -/\nmeta def match_mvar {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 expr elab)\n| (mvar unique pretty type) := some (unique, pretty, type)\n| _ := none\n\n/-- Match a local constant. -/\nmeta def match_local_const {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 binder_info \u00d7 expr elab)\n| (local_const unique pretty bi type) := some (unique, pretty, bi, type)\n| _ := none\n\n/-- Match an application. -/\nmeta def match_app {elab} : expr elab \u2192 option (expr elab \u00d7 expr elab)\n| (app t u) := some (t, u)\n| _ := none\n\n/-- Match an application of `coe_fn`. -/\nmeta def match_app_coe_fn : expr \u2192 option (expr \u00d7 expr \u00d7 expr \u00d7 expr \u00d7 expr)\n| (app `(@coe_fn %%\u03b1 %%\u03b2 %%inst %%fexpr) x) := some (\u03b1, \u03b2, inst, fexpr, x)\n| _ := none\n\n/-- Match an abstraction. -/\nmeta def match_lam {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (lam var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a \u03a0 type. -/\nmeta def match_pi {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (pi var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a let. -/\nmeta def match_elet {elab} : expr elab \u2192\n  option (name \u00d7 expr elab \u00d7 expr elab \u00d7 expr elab)\n| (elet var_name type assignment body) := some (var_name, type, assignment, body)\n| _ := none\n\n/-- Match a macro. -/\nmeta def match_macro {elab} : expr elab \u2192\n  option (macro_def \u00d7 list (expr elab))\n| (macro df args) := some (df, args)\n| _ := none\n\n/-- Tests whether an expression is a meta-variable. -/\nmeta def is_mvar : expr \u2192 bool\n| (mvar _ _ _) := tt\n| _            := ff\n\n/-- Tests whether an expression is a sort. -/\nmeta def is_sort : expr \u2192 bool\n| (sort _) := tt\n| e         := ff\n\n/-- Get the universe levels of a `const` expression -/\nmeta def univ_levels : expr \u2192 list level\n| (const n ls) := ls\n| _            := []\n\n/--\nReplace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\nmeta def replace_mvars (e : expr) : expr :=\ne.replace (\u03bb e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)\n\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\nmeta def to_implicit_local_const : expr \u2192 expr\n| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t\n| e := e\n\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.\n-/\nmeta def to_implicit_binder : expr \u2192 expr\n| (local_const n\u2081 n\u2082 _ d) := local_const n\u2081 n\u2082 binder_info.implicit d\n| (lam n _ d b) := lam n binder_info.implicit d b\n| (pi n _ d b) := pi n binder_info.implicit d b\n| e  := e\n\n/-- Returns a list of all local constants in an expression (without duplicates). -/\nmeta def list_local_consts (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_local_constant then insert e' es else es)\n\n/-- Returns the set of all local constants in an expression. -/\nmeta def list_local_consts' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_local_constant then es.insert e' else es)\n\n/-- Returns the unique names of all local constants in an expression. -/\nmeta def list_local_const_unique_names (e : expr) : name_set :=\ne.fold mk_name_set\n  (\u03bb e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es)\n\n/-- Returns a `name_set` of all constants in an expression. -/\nmeta def list_constant (e : expr) : name_set :=\ne.fold mk_name_set (\u03bb e' _ es, if e'.is_constant then es.insert e'.const_name else es)\n\n/-- Returns a `list name` containing the constant names of an `expr` in the same order\n  that `expr.fold` traverses it. -/\nmeta def list_constant' (e : expr) : list name :=\n(e.fold [] (\u03bb e' _ es, if e'.is_constant then es.insert e'.const_name else es)).reverse\n\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\nmeta def list_meta_vars (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_mvar then insert e' es else es)\n\n/-- Returns the set of all meta-variables in an expression. -/\nmeta def list_meta_vars' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_mvar then es.insert e' else es)\n\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\nmeta def list_univ_meta_vars (e : expr) : list name :=\nnative.rb_set.to_list $ e.fold native.mk_rb_set $ \u03bb e' i s,\nmatch e' with\n| (sort u) := u.fold_mvar (flip native.rb_set.insert) s\n| (const _ ls) := ls.foldl (\u03bb s' l, l.fold_mvar (flip native.rb_set.insert) s') s\n| _ := s\nend\n\n/--\nTest `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\nmeta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=\n-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n\u00ac t.list_meta_vars.empty \u2228 e.occurs t\n\n/-- Returns a `name_set` of all constants in an expression starting with a certain prefix. -/\nmeta def list_names_with_prefix (pre : name) (e : expr) : name_set :=\ne.fold mk_name_set $ \u03bb e' _ l,\n  match e' with\n  | expr.const n _ := if n.get_prefix = pre then l.insert n else l\n  | _ := l\n  end\n\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\nmeta def contains_constant (e : expr) (p : name \u2192 Prop) [decidable_pred p] : bool :=\ne.fold ff (\u03bb e' _ b, if p (e'.const_name) then tt else b)\n\n/--\nReturns true if `e` contains a `sorry`.\nSee also `name.contains_sorry`.\n-/\nmeta def contains_sorry (e : expr) : bool :=\ne.fold ff (\u03bb e' _ b, if (is_sorry e').is_some then tt else b)\n\n/--\n`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\nmeta def app_symbol_in (e : expr) (l : list name) : bool :=\nmatch e.get_app_fn with\n| (expr.const n _) := n \u2208 l\n| _ := ff\nend\n\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\nmeta def get_simp_args (e : expr) : tactic (list expr) :=\n-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\nif \u00ac e.is_app then pure [] else do\ncgr \u2190 mk_specialized_congr_lemma_simp e,\npure $ do\n  (arg_kind, arg) \u2190 cgr.arg_kinds.zip e.get_app_args,\n  guard $ arg_kind = congr_arg_kind.eq,\n  pure arg\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\nmeta def simp (t : expr)\n  (cfg : simp_config := {}) (discharger : tactic unit := failed)\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic (expr \u00d7 expr \u00d7 name_set) :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   simplify s to_unfold t cfg `eq discharger\n\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\nmeta def dsimp (t : expr)\n  (cfg : dsimp_config := {})\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic expr :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   s.dsimplify to_unfold t cfg\n\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\nmeta def binding_names : expr \u2192 list name\n| (pi n _ _ e)  := n :: e.binding_names\n| (lam n _ _ e) := n :: e.binding_names\n| e             := []\n\n/-- head-reduce a single let expression -/\nmeta def reduce_let : expr \u2192 expr\n| (elet _ _ v b) := b.instantiate_var v\n| e              := e\n\n/-- head-reduce all let expressions -/\nmeta def reduce_lets : expr \u2192 expr\n| (elet _ _ v b) := reduce_lets $ b.instantiate_var v\n| e              := e\n\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\nmeta def instantiate_lambdas : list expr \u2192 expr \u2192 expr\n| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')\n| _        e              := e\n\n/-- Repeatedly apply `expr.subst`. -/\nmeta def substs : expr \u2192 list expr \u2192 expr | e es := es.foldl expr.subst e\n\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\nmeta def instantiate_lambdas_or_apps : list expr \u2192 expr \u2192 expr\n| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      e              := mk_app e es\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/-- Get the codomain/target of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def pi_codomain : expr \u2192 expr\n| (pi n bi d b) := pi_codomain b\n| e             := e\n\n/-- Get the body/value of a lambda-expression.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def lambda_body : expr \u2192 expr\n| (lam n bi d b) := lambda_body b\n| e             := e\n\n/-- Auxiliary defintion for `pi_binders`.\n  See note [open expressions]. -/\nmeta def pi_binders_aux : list binder \u2192 expr \u2192 list binder \u00d7 expr\n| es (pi n bi d b) := pi_binders_aux (\u27e8n, bi, d\u27e9::es) b\n| es e             := (es, e)\n\n/-- Get the binders and codomain of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the\n  free variables.\n  See note [open expressions]. -/\nmeta def pi_binders (e : expr) : list binder \u00d7 expr :=\nlet (es, e) := pi_binders_aux [] e in (es.reverse, e)\n\n/-- Auxiliary defintion for `get_app_fn_args`. -/\nmeta def get_app_fn_args_aux : list expr \u2192 expr \u2192 expr \u00d7 list expr\n| r (app f a) := get_app_fn_args_aux (a::r) f\n| r e         := (e, r)\n\n/-- A combination of `get_app_fn` and `get_app_args`: lists both the\n  function and its arguments of an application -/\nmeta def get_app_fn_args : expr \u2192 expr \u00d7 list expr :=\nget_app_fn_args_aux []\n\n/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/\nmeta def drop_pis : list expr \u2192 expr \u2192 tactic expr\n| (v :: vs) (pi n bi d b) := do\n  t \u2190 infer_type v,\n  guard (t =\u2090 d),\n  drop_pis vs (b.instantiate_var v)\n| [] e := return e\n| _  _ := failed\n\n/-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`.\n  Does not check whether the result remains type-correct. -/\nmeta def instantiate_pis : list expr \u2192 expr \u2192 expr\n| (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v)\n| _ e := e\n\n/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.\n  Returns `empty` if the list is empty. -/\nmeta def mk_op_lst (op : expr) (empty : expr) : list expr \u2192 expr\n| []        := empty\n| [e]       := e\n| (e :: es) := op e $ mk_op_lst es\n\n/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 \u2227 (x2 \u2227 ...)`, or `true` if the list is empty. -/\nmeta def mk_and_lst : list expr \u2192 expr := mk_op_lst `(and) `(true)\n\n/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 \u2228 (x2 \u2228 ...)`, or `false` if the list is empty. -/\nmeta def mk_or_lst : list expr \u2192 expr := mk_op_lst `(or) `(false)\n\n/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.\nOtherwise returns `binder_info.default`. -/\nmeta def local_binding_info : expr \u2192 binder_info\n| (expr.local_const _ _ bi _) := bi\n| _ := binder_info.default\n\n/-- `is_default_local e` tests whether `e` is a local constant with binder info\n`binder_info.default` -/\nmeta def is_default_local : expr \u2192 bool\n| (expr.local_const _ _ binder_info.default _) := tt\n| _ := ff\n\n/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/\nmeta def has_local_constant (e l : expr) : bool :=\ne.has_local_in $ mk_name_set.insert l.local_uniq_name\n\n/-- Turns a local constant into a binder -/\nmeta def to_binder : expr \u2192 binder\n| (local_const _ nm bi t) := \u27e8nm, bi, t\u27e9\n| _                       := default\n\n/-- Strip-away the context-dependent unique id for the given local const and return: its friendly\n`name`, its `binder_info`, and its `type : expr`. -/\nmeta def get_local_const_kind : expr \u2192 name \u00d7 binder_info \u00d7 expr\n| (expr.local_const _ n bi e) := (n, bi, e)\n| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])\n\n/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/\nmeta def local_const_set_type {elab : bool} : expr elab \u2192 expr elab \u2192 expr elab\n| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t\n| e                           new_t := e\n\n/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to\naccess core `expr` manipulation functions for `pexpr`-based use, but which are restricted to\n`expr tt` at the site of definition unnecessarily.\n\nDANGER: Unless you know exactly what you are doing, this is probably not the function you are\nlooking for. For `pexpr \u2192 expr` see `tactic.to_expr`. For `expr \u2192 pexpr` see `to_pexpr`. -/\nmeta def unsafe_cast {elab\u2081 elab\u2082 : bool} : expr elab\u2081 \u2192 expr elab\u2082 := unchecked_cast\n\n/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr \u00d7 expr)` as\na collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says \"whenever\n`f` is encountered in `e` verbatim, replace it with `t`\". -/\nmeta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr \u00d7 expr)) :\n  expr elab :=\nunsafe_cast $ e.unsafe_cast.replace $ \u03bb e n,\n  (mappings.filter $ \u03bb ent : expr \u00d7 expr, ent.1 = e).head'.map prod.snd\n\n/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of\n    other `expr.local_const`s. It determines whether `e` should be considered \"available in context\"\n    as a variable by virtue of the fact that the variables `vs` have been deemed such.\n\n    For example, given `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that\n    the typeclass instance `prime n` should be included, but `ih : even n` should not.\n\n    DANGER: It is possible that for `f : expr` another `expr.local_const`, we have\n    `is_implicitly_included_variable f vs = ff` but\n    `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to\n    iteratively add a list of local constants (usually, the `variables` declared in the local scope)\n    which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables\n    were added in a particular iteration. The function `all_implicitly_included_variables` below\n    implements this behaviour.\n\n    Note that if `e \u2208 vs` then `is_implicitly_included_variable e vs = tt`. -/\nmeta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=\nif \u00ac(e.local_pp_name.to_string.starts_with \"_\") then\n  e \u2208 vs\nelse e.local_type.fold tt $ \u03bb se _ b,\n  if \u00acb then ff\n  else if \u00acse.is_local_constant then tt\n  else se \u2208 vs\n\n/-- Private work function for `all_implicitly_included_variables`, performing the actual series of\n    iterations, tracking with a boolean whether any updates occured this iteration. -/\nprivate meta def all_implicitly_included_variables_aux\n  : list expr \u2192 list expr \u2192 list expr \u2192 bool \u2192 list expr\n| []          vs rs tt := all_implicitly_included_variables_aux rs vs [] ff\n| []          vs rs ff := vs\n| (e :: rest) vs rs b :=\n  let (vs, rs, b) :=\n    if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in\n  all_implicitly_included_variables_aux rest vs rs b\n\n/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,\n    another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion\n    of the variables in `vs` into the local context implies that `e` should also be included. See\n    `is_implicitly_included_variable e vs` for the details.\n\n    In particular, those elements of `vs` are included automatically. -/\nmeta def all_implicitly_included_variables (es vs : list expr) : list expr :=\nall_implicitly_included_variables_aux es vs [] ff\n\n/-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier.\nThis also works if `x1, ... xn` contain free variables. -/\nprotected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do\n(@const tt n ls, es) \u2190 return e.get_app_fn_args |\n  exceptional.fail \"expression is not a constant applied to arguments\",\nd \u2190 env.get n,\nreturn $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls\n\n/-- Auxilliary function for `head_eta_expand`. -/\nmeta def head_eta_expand_aux : \u2115 \u2192 expr \u2192 expr \u2192 expr\n| (n+1) e (pi x bi d b) :=\n  lam x bi d $ head_eta_expand_aux n e b\n| _ e _ := e\n\n/-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained\n  by its type `t`. -/\nmeta def head_eta_expand (n : \u2115) (e t : expr) : expr :=\n((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t\n\n/-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in\n`dict`. They are expanded until they are applied to one more argument than the maximum in\n`dict.find n`. -/\nprotected meta def eta_expand (env : environment) (dict : name_map $ list \u2115) : expr \u2192 expr\n| e := e.replace $ \u03bb e _, do\n  let (e0, es) := e.get_app_fn_args,\n  let ns := (dict.find e0.const_name).iget,\n  guard (bnot ns.empty),\n  let e' := e0.mk_app $ es.map eta_expand,\n  let needed_n := ns.foldr max 0 + 1,\n  if needed_n \u2264 es.length then some e'\n  else do\n    e'_type \u2190 (e'.simple_infer_type env).to_option,\n    some $ head_eta_expand (needed_n - es.length) e' e'_type\n\n/--\n`e.apply_replacement_fun f test` applies `f` to each identifier\n(inductive type, defined function etc) in an expression, unless\n* The identifier occurs in an application with first argument `arg`; and\n* `test arg` is false.\nHowever, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`\nis tested, instead of the first argument.\n\nReorder contains the information about what arguments to reorder:\ne.g. `g x\u2081 x\u2082 x\u2083 ... x\u2099` becomes `g x\u2082 x\u2081 x\u2083 ... x\u2099` if `reorder.find g = some [1]`.\nWe assume that all functions where we want to reorder arguments are fully applied.\nThis can be done by applying `expr.eta_expand` first.\n-/\nprotected meta def apply_replacement_fun (f : name \u2192 name) (test : expr \u2192 bool)\n  (relevant : name_map \u2115) (reorder : name_map $ list \u2115) : expr \u2192 expr\n| e := e.replace $ \u03bb e _,\n  match e with\n  | const n ls := some $ const (f n) $\n      -- if the first two arguments are reordered, we also reorder the first two universe parameters\n      if 1 \u2208 (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls\n  | app g x :=\n    let f := g.get_app_fn,\n        nm := f.const_name,\n        n_args := g.get_app_num_args in -- this might be inefficient\n    if n_args \u2208 (reorder.find nm).iget \u2227 test g.get_app_args.head then\n    -- interchange `x` and the last argument of `g`\n    some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $\n      apply_replacement_fun g.app_arg else\n    if n_args = (relevant.find nm).lhoare 0 \u2227 f.is_constant \u2227 \u00ac test x then\n      some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else\n      none\n  | _ := none\n  end\n\nend expr\n\n/-! ### Declarations about `environment` -/\n\nnamespace environment\n\n/-- Tests whether `n` is a structure. -/\nmeta def is_structure (env : environment) (n : name) : bool :=\n(env.structure_fields n).is_some\n\n/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a\n  structure. -/\nmeta def structure_fields_full (env : environment) (n : name) : option (list name) :=\n(env.structure_fields n).map (list.map $ \u03bb n', n ++ n')\n\n/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.\n  Note that `is_ginductive` returns `tt` even on regular inductive types.\n  This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive\n  type. -/\nmeta def is_ginductive' (e : environment) (nm : name) : bool :=\ne.is_ginductive nm \u2227 \u00ac e.is_inductive nm\n\n/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list.  -/\nmeta def decl_filter_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 option \u03b1) : list \u03b1 :=\n  e.fold [] $ \u03bb d l, match f d with\n                     | some r := r :: l\n                     | none := l\n                     end\n\n/-- Maps `f` to all declarations in the environment. -/\nmeta def decl_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 \u03b1) : list \u03b1 :=\n  e.decl_filter_map $ \u03bb d, some (f d)\n\n/-- Lists all declarations in the environment -/\nmeta def get_decls (e : environment) : list declaration :=\n  e.decl_map id\n\n/-- Lists all trusted (non-meta) declarations in the environment -/\nmeta def get_trusted_decls (e : environment) : list declaration :=\n  e.decl_filter_map (\u03bb d, if d.is_trusted then some d else none)\n\n/-- Lists the name of all declarations in the environment -/\nmeta def get_decl_names (e : environment) : list name :=\n  e.decl_map declaration.to_name\n\n/-- Fold a monad over all declarations in the environment. -/\nmeta def mfold {\u03b1 : Type} {m : Type \u2192 Type} [monad m] (e : environment) (x : \u03b1)\n  (fn : declaration \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\ne.fold (return x) (\u03bb d t, t >>= fn d)\n\n/-- Filters all declarations in the environment. -/\nmeta def filter (e : environment) (test : declaration \u2192 bool) : list declaration :=\ne.fold [] $ \u03bb d ds, if test d then d::ds else ds\n\n/-- Filters all declarations in the environment. -/\nmeta def mfilter (e : environment) (test : declaration \u2192 tactic bool) : tactic (list declaration) :=\ne.mfold [] $ \u03bb d ds, do b \u2190 test d, return $ if b then d::ds else ds\n\n/-- Checks whether `s` is a prefix of the file where `n` is declared.\n  This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/\nmeta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=\ns.is_prefix_of $ (e.decl_olean n).get_or_else \"\"\n\nend environment\n\n/-!\n### `is_eta_expansion`\n\n In this section we define the tactic `is_eta_expansion` which checks whether an expression\n  is an eta-expansion of a structure. (not to be confused with eta-expanion for `\u03bb`).\n\n-/\n\nnamespace expr\n\n/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have\n  `pr = nm.{univs} args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name \u00d7 expr)) :\n  bool :=\nl.all $ \u03bb\u27e8proj, val\u27e9, val = (const proj univs).mk_app args\n\n/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all\n  elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_test : list (name \u00d7 expr) \u2192 option expr\n| []              := none\n| (\u27e8proj, val\u27e9::l) :=\n  match val.get_app_fn with\n  | (const nm univs : expr) :=\n    if nm = proj then\n      let args := val.get_app_args in\n      let e := args.ilast in\n      if is_eta_expansion_of args univs l then some e else none\n    else\n      none\n  | _                       := none\n  end\n\n/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.\n  Here `l` is intended to consists of the projections and the fields of `val`.\n  This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and\n  afterward checks whether the resulting expression `e` unifies with `val`.\n  This last check is necessary, because `val` and `e` might have different types. -/\nmeta def is_eta_expansion_aux (val : expr) (l : list (name \u00d7 expr)) : tactic (option expr) :=\ndo l' \u2190 l.mfilter (\u03bb\u27e8proj, val\u27e9, bnot <$> is_proof val),\n  match is_eta_expansion_test l' with\n  | some e := option.map (\u03bb _, e) <$> try_core (unify e val)\n  | none   := return none\n  end\n\n/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the\n  eta-expansion of `e`.\n  With eta-expansion we here mean the eta-expansion of a structure, not of a function.\n  For example, the eta-expansion of `x : \u03b1 \u00d7 \u03b2` is `\u27e8x.1, x.2\u27e9`.\n  This assumes that `val` is a fully-applied application of the constructor of a structure.\n\n  This is useful to reduce expressions generated by the notation\n    `{ field_1 := _, ..other_structure }`\n  If `other_structure` is itself a field of the structure, then the elaborator will insert an\n  eta-expanded version of `other_structure`. -/\nmeta def is_eta_expansion (val : expr) : tactic (option expr) := do\n  e \u2190 get_env,\n  type \u2190 infer_type val,\n  projs \u2190 e.structure_fields_full type.get_app_fn.const_name,\n  let args := (val.get_app_args).drop type.get_app_args.length,\n  is_eta_expansion_aux val (projs.zip args)\n\nend expr\n\n/-! ### Declarations about `declaration` -/\n\nnamespace declaration\n\n/--\n`declaration.update_with_fun f test tgt decl`\nsets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and\n`expr.apply_replacement_fun` to the value and type of `decl`.\n-/\nprotected meta def update_with_fun (env : environment) (f : name \u2192 name) (test : expr \u2192 bool)\n  (relevant : name_map \u2115) (reorder : name_map $ list \u2115) (tgt : name) (decl : declaration) :\n  declaration :=\nlet decl := decl.update_name $ tgt in\nlet decl := decl.update_type $\n  (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in\ndecl.update_value $\n  (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder\n\n/-- Checks whether the declaration is declared in the current file.\n  This is a simple wrapper around `environment.in_current_file`\n  Use `environment.in_current_file` instead if performance matters. -/\nmeta def in_current_file (d : declaration) : tactic bool :=\ndo e \u2190 get_env, return $ e.in_current_file d.to_name\n\n/-- Checks whether a declaration is a theorem -/\nmeta def is_theorem : declaration \u2192 bool\n| (thm _ _ _ _) := tt\n| _             := ff\n\n/-- Checks whether a declaration is a constant -/\nmeta def is_constant : declaration \u2192 bool\n| (cnst _ _ _ _) := tt\n| _              := ff\n\n/-- Checks whether a declaration is a axiom -/\nmeta def is_axiom : declaration \u2192 bool\n| (ax _ _ _) := tt\n| _          := ff\n\n/-- Checks whether a declaration is automatically generated in the environment.\n  There is no cheap way to check whether a declaration in the namespace of a generalized\n  inductive type is automatically generated, so for now we say that all of them are automatically\n  generated. -/\nmeta def is_auto_generated (e : environment) (d : declaration) : bool :=\ne.is_constructor d.to_name \u2228\n(e.is_projection d.to_name).is_some \u2228\n(e.is_constructor d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"inj\", \"inj_eq\", \"sizeof_spec\", \"inj_arrow\"]) \u2228\n(e.is_inductive d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"below\", \"binduction_on\", \"brec_on\", \"cases_on\", \"dcases_on\", \"drec_on\", \"drec\",\n  \"rec\", \"rec_on\", \"no_confusion\", \"no_confusion_type\", \"sizeof\", \"ibelow\", \"has_sizeof_inst\"]) \u2228\nd.to_name.has_prefix (\u03bb nm, e.is_ginductive' nm)\n\n/--\nReturns true iff `d` is an automatically-generated or internal declaration.\n-/\nmeta def is_auto_or_internal (env : environment) (d : declaration) : bool :=\nd.to_name.is_internal || d.is_auto_generated env\n\n/-- Returns the list of universe levels of a declaration. -/\nmeta def univ_levels (d : declaration) : list level :=\nd.univ_params.map level.param\n\n/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/\nprotected meta def reducibility_hints : declaration \u2192 reducibility_hints\n| (declaration.defn _ _ _ _ red _) := red\n| _ := _root_.reducibility_hints.opaque\n\n/-- formats the arguments of a `declaration.thm` -/\nprivate meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body.get,\n   return $ \"<theorem \" ++ to_fmt nm ++ \" : \" ++ tp ++ \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.defn` -/\nprivate meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :\n  tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body,\n   return $ \"<\" ++ (if is_trusted then \"def \" else \"meta def \") ++ to_fmt nm ++ \" : \" ++ tp ++\n     \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.cnst` -/\nprivate meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<\" ++ (if is_trusted then \"constant \" else \"meta constant \") ++ to_fmt nm ++ \" : \"\n     ++ tp ++ \">\"\n\n/-- formats the arguments of a `declaration.ax` -/\nprivate meta def print_ax (nm : name) (tp : expr) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<axiom \" ++ to_fmt nm ++ \" : \" ++ tp ++ \">\"\n\n/-- pretty-prints a `declaration` object. -/\nmeta def to_tactic_format : declaration \u2192 tactic format\n| (declaration.thm nm _ tp bd) := print_thm nm tp bd\n| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted\n| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted\n| (declaration.ax nm _ tp) := print_ax nm tp\n\nmeta instance : has_to_tactic_format declaration :=\n\u27e8to_tactic_format\u27e9\n\nend declaration\n\nmeta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=\nunchecked_cast\nexpr.has_decidable_eq\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/meta/expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.06371500091897545, "lm_q1q2_score": 0.019162004838619004}}
{"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\nimport tactic.dependencies\n\nopen tactic\nopen native.rb_map (set_of_list)\n\nnamespace native\n\nmeta def rb_set.equals {\u03b1} (xs ys : rb_set \u03b1) : bool :=\nxs.fold tt (\u03bb x b, b \u2227 ys.contains x) &&\nys.fold tt (\u03bb y b, b \u2227 xs.contains y)\n\nend native\n\nopen native\n\nexample (n m : \u2115) (f : fin n) : let k := m, o := k in o > 0 \u2192 true :=\nbegin\n  intros k o h,\n  (do [n, m, f, k, o, h] \u2190 [`n, `m, `f, `k, `o, `h].mmap get_local,\n\n      -- hyp_depends_on_locals\n      h_dep_m \u2190 hyp_depends_on_locals h [m],\n      guard h_dep_m <|> fail! \"h_dep_m = {h_dep_m}\",\n      h_dep_n \u2190 hyp_depends_on_locals h [n],\n      guard \u00ac h_dep_n <|> fail! \"h_dep_n = {h_dep_n}\",\n      m_dep_n \u2190 hyp_depends_on_locals m [n],\n      guard \u00ac m_dep_n <|> fail! \"m_dep_n = {m_dep_n}\",\n      f_dep_n \u2190 hyp_depends_on_locals f [n],\n      guard f_dep_n <|> fail! \"f_dep_n = {f_dep_n}\",\n      f_dep_n_m \u2190 hyp_depends_on_locals f [n, m],\n      guard f_dep_n_m <|> fail! \"f_dep_n_m = {f_dep_n_m}\",\n\n      -- hyps_depend_on_locals\n      dep_fk \u2190 hyps_depend_on_locals [n, m, f, k, o, h] [f, k],\n      guard (dep_fk = [ff, ff, ff, ff, tt, tt]) <|> fail! \"dep_fk = {dep_fk}\",\n      dep_m \u2190 hyps_depend_on_locals [n, m, f, k, o, h] [m],\n      guard (dep_m = [ff, ff, ff, tt, tt, tt]) <|> fail! \"dep_m = {dep_m}\",\n\n      -- hyp_depends_on_locals_inclusive\n      h_idep_h \u2190 hyp_depends_on_locals_inclusive h [h],\n      guard h_idep_h <|> fail! \"h_idep_h = {h_idep_h}\",\n      h_idep_n \u2190 hyp_depends_on_locals_inclusive h [n],\n      guard \u00ac h_idep_n <|> fail! \"h_idep_n = {h_idep_n}\",\n\n      -- hyps_depend_on_locals_inclusive\n      idep_fk \u2190 hyps_depend_on_locals_inclusive [n, m, f, k, o, h] [f, k],\n      guard (idep_fk = [ff, ff, tt, tt, tt, tt]) <|> fail! \"idep_fk = {idep_fk}\",\n      idep_m \u2190 hyps_depend_on_locals_inclusive [n, m, f, k, o, h] [m],\n      guard (idep_m = [ff, tt, ff, tt, tt, tt]) <|> fail! \"idep_m = {idep_m}\",\n\n      -- dependency_set_of_hyp\n      f_dep_set \u2190 dependency_set_of_hyp f,\n      guard (f_dep_set.equals (set_of_list [n])) <|> fail! \"f_dep_set = {f_dep_set}\",\n      h_dep_set \u2190 dependency_set_of_hyp h,\n      guard (h_dep_set.equals (set_of_list [o, k, m])) <|> fail! \"h_dep_set = {h_dep_set}\",\n      n_dep_set \u2190 dependency_set_of_hyp n,\n      guard n_dep_set.empty <|> fail! \"n_dep_set = {n_dep_set}\",\n\n      -- dependency_sets_of_hyps\n      fhn_dep_sets \u2190 dependency_sets_of_hyps [f, h, n],\n      guard ((fhn_dep_sets.zip_with rb_set.equals ([[n], [o, k, m], []].map set_of_list)).band) <|>\n        fail! \"fhn_dep_sets = {fhn_dep_sets}\",\n\n      -- dependency_set_of_hyp_inclusive\n      f_idep_set \u2190 dependency_set_of_hyp_inclusive f,\n      guard (f_idep_set.equals (set_of_list [n, f])) <|> fail! \"f_idep_set = {f_idep_set}\",\n      h_idep_set \u2190 dependency_set_of_hyp_inclusive h,\n      guard (h_idep_set.equals (set_of_list [o, k, m, h])) <|> fail! \"h_idep_set = {h_idep_set}\",\n      n_idep_set \u2190 dependency_set_of_hyp_inclusive n,\n      guard (n_idep_set.equals (set_of_list [n])) <|> fail! \"n_idep_set = {n_idep_set}\",\n\n      -- dependency_sets_of_hyps_inclusive\n      fhn_idep_sets \u2190 dependency_sets_of_hyps_inclusive [f, h, n],\n      guard ((fhn_idep_sets.zip_with rb_set.equals ([[f, n], [h, o, k, m], [n]].map set_of_list)).band) <|>\n        fail! \"fhn_idep_sets = {fhn_idep_sets}\",\n\n      -- reverse_dependencies_of_hyps\n      n_revdep_set \u2190 reverse_dependencies_of_hyps [n],\n      guard (n_revdep_set = [f]) <|> fail! \"n_revdep_set = {n_revdep_set}\",\n      n_f_revdep_set \u2190 reverse_dependencies_of_hyps [n, f],\n      guard (n_f_revdep_set = []) <|> fail! \"n_f_revdep_set = {n_f_revdep_set}\",\n      m_revdep_set \u2190 reverse_dependencies_of_hyps [m],\n      guard (m_revdep_set = [k, o, h]) <|> fail! \"m_revdep_set = {m_revdep_set}\",\n      m_o_revdep_set \u2190 reverse_dependencies_of_hyps [m, o],\n      guard (m_o_revdep_set = [k, h]) <|> fail! \"m_o_revdep_set = {m_o_revdep_set}\",\n      f_revdep_set \u2190 reverse_dependencies_of_hyps [f],\n      guard (f_revdep_set = []) <|> fail! \"f_revdep_set = {f_revdep_set}\",\n\n      -- reverse_dependencies_of_hyps_inclusive\n      n_irevdep_set \u2190 reverse_dependencies_of_hyps_inclusive [n],\n      guard (n_irevdep_set = [n, f]) <|> fail! \"n_irevdep_set = {n_irevdep_set}\",\n      n_f_irevdep_set \u2190 reverse_dependencies_of_hyps_inclusive [n, f],\n      guard (n_f_irevdep_set = [n, f]) <|> fail! \"n_f_irevdep_set = {n_f_irevdep_set}\",\n      m_irevdep_set \u2190 reverse_dependencies_of_hyps_inclusive [m],\n      guard (m_irevdep_set = [m, k, o, h]) <|> fail! \"m_irevdep_set = {m_irevdep_set}\",\n      m_o_irevdep_set \u2190 reverse_dependencies_of_hyps_inclusive [m, o],\n      guard (m_o_irevdep_set = [m, k, o, h]) <|> fail! \"m_o_irevdep_set = {m_o_irevdep_set}\",\n      f_irevdep_set \u2190 reverse_dependencies_of_hyps_inclusive [f],\n      guard (f_irevdep_set = [f]) <|> fail! \"f_irevdep_set = {f_irevdep_set}\",\n\n      -- revert_lst'\n      (n_reverted\u2081, reverted) \u2190 revert_lst' [n, m],\n      guard (n_reverted\u2081 = 6) <|> fail! \"n_reverted\u2081 = {n_reverted\u2081}\",\n      guard\n        (reverted.map expr.local_uniq_name =\n        [n, m, f, k, o, h].map expr.local_uniq_name),\n      `[ guard_target \u2200 (n m : \u2115) (f : fin n), let k := m, o := k in o > 0 \u2192 true ],\n\n      intros,\n      [n, m, f, k, o, h] \u2190 [`n, `m, `f, `k, `o, `h].mmap get_local,\n\n      -- revert_reverse_dependencies_of_hyps\n      n_reverted\u2082 \u2190 revert_reverse_dependencies_of_hyps [n, k],\n      guard (n_reverted\u2082 = 3) <|> fail! \"n_reverted\u2082 = {n_reverted\u2082}\",\n      `[ guard_hyp n : \u2115 ],\n      `[ guard_hyp m : \u2115 ],\n      `[ guard_hyp k : \u2115 := m ],\n      `[ guard_target \u2200 (f : fin n), let o := k in o > 0 \u2192 true ],\n\n      pure ()\n  ),\n  intros,\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/dependencies.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.041462272859464404, "lm_q1q2_score": 0.019114802882558395}}
{"text": "import tools.super\nopen super tactic monad\n\nexample (a b : \u2115 \u2192 Prop) (h : \u2200x, (\u00aca x \u2192 b x) \u2227 \u00acb x \u2227 \u00aca x) := by do\n\nc \u2190 get_local `h >>= clause.of_classical_proof,\ntrace c,\n\ncs \u2190 get_clauses_classical [c],\ntrace cs,\n\nc0 \u2190 returnopt $ cs^.nth 0,\nc1 \u2190 returnopt $ cs^.nth 1,\nc2 \u2190 returnopt $ cs^.nth 2,\n\ntrace c0^.type,\ntrace c0^.proof,\n\ntriv\n", "meta": {"author": "gebner", "repo": "POPL17_tutorial", "sha": "04aaaea171736317bf20bc849b96069188d73a55", "save_path": "github-repos/lean/gebner-POPL17_tutorial", "path": "github-repos/lean/gebner-POPL17_tutorial/POPL17_tutorial-04aaaea171736317bf20bc849b96069188d73a55/super/clauses.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.052618959290320906, "lm_q1q2_score": 0.01909906184887684}}
{"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 \u00b7 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", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/tests/lean/interactive/hover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.04208773212094216, "lm_q1q2_score": 0.01907676386159088}}
{"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.Meta.Tactic.Split\nimport Lean.Meta.Tactic.Apply\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 \u2192 Expr\n  | Expr.letE _ t 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 \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | return none\n  unless rhs.isLet || rhs.isMData do return none\n  return some (\u2190 replaceTargetDefEq mvarId (\u2190 mkEq lhs (expand rhs)))\n\ndef funext? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | return none\n  unless rhs.isLambda do return none\n  commitWhenSome? do\n    let [mvarId] \u2190 apply mvarId (\u2190 mkConstWithFreshMVarLevels ``funext) | return none\n    let (_, mvarId) \u2190 intro1 mvarId\n    return some mvarId\n\ndef simpMatch? (mvarId : MVarId) : MetaM (Option MVarId) := do\n  let mvarId' \u2190 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' \u2190 simpIfTarget mvarId (useDecide := true)\n  if mvarId != mvarId' then return some mvarId' else return none\n\nstructure Context where\n  declNames : Array Name\n\n/--\n  Auxiliary method for `mkEqnTypes`. We should \"keep going\"/\"processing\" the goal\n   `... |- f ... = rhs` at `mkEqnTypes` IF `rhs` contains a recursive application containing loose bound\n  variables. We do that to make sure we can create an elimination principle for the recursive functions.\n\n  Remark: we have considered using the same heuristic used in the `BRecOn` module.\n  That is we would do case-analysis on the `match` application because the recursive\n  argument (may) depend on it. We abandoned this approach because it was incompatible\n  with the generation of induction principles.\n\n  Remark: we could also always return `true` here, and split **all** match expressions on the `rhs`\n  even if they are not relevant for the `brecOn` construction.\n  TODO: reconsider this design decision in the future.\n  Another possible design option is to \"split\" other control structures such as `if-then-else`.\n-/\nprivate def keepGoing (mvarId : MVarId) : ReaderT Context (StateRefT (Array Expr) MetaM) Bool := do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | return false\n  let ctx \u2190 read\n  return Option.isSome <| rhs.find? fun e => ctx.declNames.any e.isAppOf && e.hasLooseBVars\n\nprivate def lhsDependsOn (type : Expr) (fvarId : FVarId) : MetaM Bool :=\n  forallTelescope type fun _ type => do\n    if let some (_, lhs, _) \u2190 matchEq? type then\n      dependsOn lhs fvarId\n    else\n      dependsOn type fvarId\n\n/--\n  Eliminate `namedPatterns` from equation, and trivial hypotheses.\n-/\ndef simpEqnType (eqnType : Expr) : MetaM Expr := do\n  forallTelescopeReducing (\u2190 instantiateMVars eqnType) fun ys type => do\n    let proofVars := collect type\n    trace[Meta.debug] \"simpEqnType: {type}\"\n    let mut type \u2190 Match.unfoldNamedPattern type\n    let mut eliminated : FVarIdSet := {}\n    for y in ys.reverse do\n      trace[Meta.debug] \">> simpEqnType: {\u2190 inferType y}, {type}\"\n      if proofVars.contains y.fvarId! then\n        let some (_, Expr.fvar fvarId _, rhs) \u2190 matchEq? (\u2190 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 (\u2190 dependsOn type y.fvarId!) then\n          type \u2190 mkForallFVars #[y] type\n      else\n        if let some (_, lhs, rhs) \u2190 matchEq? (\u2190 inferType y) then\n          if (\u2190 isDefEq lhs rhs) then\n            if !(\u2190 dependsOn type y.fvarId!) then\n              continue\n            else if !(\u2190 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 (\u2190 mkEqRefl lhs)\n              continue\n        type \u2190 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) (\u03c9) : ST \u03c9 FVarIdSet := do\n      let ref \u2190 ST.mkRef {}\n      e.forEach fun e => do\n        if e.isAppOfArity ``namedPattern 4 && e.appArg!.isFVar then\n          ST.Prim.Ref.modify ref (\u00b7.insert e.appArg!.fvarId!)\n      ST.Prim.Ref.get ref\n    runST (go e)\n\nprivate def saveEqn (mvarId : MVarId) : StateRefT (Array Expr) MetaM Unit := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let fvarState := collectFVars {} target\n  let fvarState \u2190 (\u2190 getLCtx).foldrM (init := fvarState) fun decl fvarState => do\n    if fvarState.fvarSet.contains decl.fvarId then\n      return collectFVars fvarState (\u2190 instantiateMVars decl.type)\n    else\n      return fvarState\n  let mut fvarIds \u2190 sortFVarIds <| fvarState.fvarSet.toArray\n  -- Include propositions that are not in fvarState.fvarSet, and only contains variables in\n  for decl in (\u2190 getLCtx) do\n    unless fvarState.fvarSet.contains decl.fvarId do\n      if (\u2190 isProp decl.type) then\n        let type \u2190 instantiateMVars decl.type\n        let missing? := type.find? fun e => e.isFVar && !fvarState.fvarSet.contains e.fvarId!\n        if missing?.isNone then\n          fvarIds := fvarIds.push decl.fvarId\n  let type \u2190 mkForallFVars (fvarIds.map mkFVar) target\n  let type \u2190 simpEqnType type\n  modify (\u00b7.push type)\n\npartial def mkEqnTypes (declNames : Array Name) (mvarId : MVarId) : MetaM (Array Expr) := do\n  let (_, eqnTypes) \u2190 go mvarId |>.run { declNames } |>.run #[]\n  return eqnTypes\nwhere\n  go (mvarId : MVarId) : ReaderT Context (StateRefT (Array Expr) MetaM) Unit := do\n    if !(\u2190 keepGoing mvarId) then\n      saveEqn mvarId\n    else if let some mvarId \u2190 expandRHS? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 funext? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarIds \u2190 splitTarget? mvarId then\n      mvarIds.forM go\n    else\n      saveEqn mvarId\n\nstructure EqnsExtState where\n  map : Std.PHashMap Name (Array Name) := {}\n  deriving Inhabited\n\n/- We generate the equations on demand, and do not save them on .olean files. -/\nbuiltin_initialize eqnsExt : EnvExtension EqnsExtState \u2190\n  registerEnvExtension (pure {})\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 applyRefl mvarId; return true catch _ => return false\n\n/-- Delta reduce the equation left-hand-side -/\ndef deltaLHS (mvarId : MVarId) : MetaM MVarId := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | throwTacticEx `deltaLHS mvarId \"equality expected\"\n  let some lhs \u2190 delta? lhs | throwTacticEx `deltaLHS mvarId \"failed to delta reduce lhs\"\n  replaceTargetDefEq mvarId (\u2190 mkEq lhs rhs)\n\ndef deltaRHS? (mvarId : MVarId) (declName : Name) : MetaM (Option MVarId) := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | throwTacticEx `deltaRHS mvarId \"equality expected\"\n  let some rhs \u2190 delta? rhs.consumeMData (. == declName) | return none\n  replaceTargetDefEq mvarId (\u2190 mkEq lhs rhs)\n\nprivate partial def whnfAux (e : Expr) : MetaM Expr := do\n  let e \u2190 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  | Expr.proj _ _ s _ => return mkAppN (f.updateProj! (\u2190 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) := withMVarContext mvarId do\n  let target \u2190 getMVarType' mvarId\n  let some (_, lhs, rhs) := target.eq? | throwTacticEx `whnfReducibleLHS mvarId \"equality expected\"\n  let lhs' \u2190 whnfAux lhs\n  if lhs' != lhs then\n    return some (\u2190 replaceTargetDefEq mvarId (\u2190 mkEq lhs' rhs))\n  else\n    return none\n\ndef tryContradiction (mvarId : MVarId) : MetaM Bool := do\n  try contradiction mvarId { genDiseq := true }; return true catch _ => return false\n\nstructure UnfoldEqnExtState where\n  map : Std.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 \u2190\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 \u2190 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 \u2190 apply mvarId (\u2190 mkConstWithFreshMVarLevels eq)\n        subgoals.allM assumptionCore\n      catch _ =>\n        return false\n  let rec go (mvarId : MVarId) : MetaM Unit := do\n    if (\u2190 tryEqns mvarId) then\n      return ()\n    else if let some mvarId \u2190 funext? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarIds \u2190 splitTarget? mvarId then\n      mvarIds.forM go\n    else\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 \u2190 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 \u2190 mkEq (mkAppN (Lean.mkConst declName us) xs) body\n      let goal \u2190 mkFreshExprSyntheticOpaqueMVar type\n      mkUnfoldProof declName goal.mvarId!\n      let type \u2190 mkForallFVars xs type\n      let value \u2190 mkLambdaFVars xs (\u2190 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 \u2192 Option EqnInfoCore) : MetaM (Option Name) := do\n  let env \u2190 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 \u2190 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\nend Lean.Elab.Eqns\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/Elab/PreDefinition/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.04208772866656941, "lm_q1q2_score": 0.01907676167417939}}
{"text": "namespace util.data.nonempty_list\n\nuniverse u\nvariable {\u03b1 : Type u}\n\n-- structure nonempty_list (\u03b1 : Type u) :=\n--   (head : \u03b1)\n--   (tail : list \u03b1)\n\ninductive nonempty_list (\u03b1 : Type u)\n| singleton : \u03b1 \u2192 nonempty_list\n| cons : \u03b1 \u2192 nonempty_list \u2192 nonempty_list\n\nnamespace nonempty_list\n\n-- def singleton : \u03b1 \u2192 nonempty_list \u03b1 := \u03bb x, { head := x, tail := [] }\n\n@[reducible] def head : nonempty_list \u03b1 \u2192 \u03b1\n| (nonempty_list.singleton x) := x\n| (nonempty_list.cons x _)    := x\n\n@[reducible] def to_list : nonempty_list \u03b1 \u2192 list \u03b1\n| (singleton x) := [x]\n| (cons x xs)   := x :: to_list xs\n\n@[reducible] def tail : nonempty_list \u03b1 \u2192 list \u03b1\n| (singleton _) := []\n| (cons _ xs)   := to_list xs\n\n-- def append (xs : nonempty_list \u03b1) (ys : nonempty_list \u03b1) : nonempty_list \u03b1 := {\n--   head := xs.head,\n--   tail := xs.tail ++ ys.to_list\n-- }\n\ndef append : nonempty_list \u03b1 \u2192 nonempty_list \u03b1 \u2192 nonempty_list \u03b1\n| (singleton x) ys := cons x ys\n| (cons x xs)   ys := cons x (append xs ys)\n\ninstance : has_append (nonempty_list \u03b1) := \u27e8 append \u27e9\n\n-- lemma append_assoc : \u03a0 (xs ys zs : nonempty_list \u03b1), 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 : \u03b1) (xs : nonempty_list \u03b1) : singleton x ++ xs = cons x xs :=\nrfl\n\n@[simp] lemma cons_append (x : \u03b1) (xs : nonempty_list \u03b1) (ys : nonempty_list \u03b1) : cons x xs ++ ys = cons x (xs ++ ys) :=\nrfl\n\nlemma append_assoc (xs ys zs : nonempty_list \u03b1) : (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 \u03b1) : monadLift x = x :=\n  rfl\n\nclass LawfulFunctor (f : Type u \u2192 Type v) [Functor f] : Prop where\n  map_const          : (Functor.mapConst : \u03b1 \u2192 f \u03b2 \u2192 f \u03b1) = Functor.map \u2218 const \u03b2\n  id_map   (x : f \u03b1) : id <$> x = x\n  comp_map (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) (x : f \u03b1) : (h \u2218 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 \u03b1) : (fun a => a) <$> x = x :=\n  id_map x\n\nclass LawfulApplicative (f : Type u \u2192 Type v) [Applicative f] extends LawfulFunctor f : Prop where\n  seqLeft_eq  (x : f \u03b1) (y : f \u03b2)     : x <* y = const \u03b2 <$> x <*> y\n  seqRight_eq (x : f \u03b1) (y : f \u03b2)     : x *> y = const \u03b1 id <$> x <*> y\n  pure_seq    (g : \u03b1 \u2192 \u03b2) (x : f \u03b1)   : pure g <*> x = g <$> x\n  map_pure    (g : \u03b1 \u2192 \u03b2) (x : \u03b1)     : g <$> (pure x : f \u03b1) = pure (g x)\n  seq_pure    {\u03b1 \u03b2 : Type u} (g : f (\u03b1 \u2192 \u03b2)) (x : \u03b1) : g <*> pure x = (fun h => h x) <$> g\n  seq_assoc   {\u03b1 \u03b2 \u03b3 : Type u} (x : f \u03b1) (g : f (\u03b1 \u2192 \u03b2)) (h : f (\u03b2 \u2192 \u03b3)) : h <*> (g <*> x) = ((@comp \u03b1 \u03b2 \u03b3) <$> h) <*> g <*> x\n  comp_map g h x := (by\n    repeat rw [\u2190 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 \u03b1) : pure id <*> x = x := by\n  simp [pure_seq]\n\nclass LawfulMonad (m : Type u \u2192 Type v) [Monad m] extends LawfulApplicative m : Prop where\n  bind_pure_comp (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : x >>= (fun a => pure (f a)) = f <$> x\n  bind_map       {\u03b1 \u03b2 : Type u} (f : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : f >>= (. <$> x) = f <*> x\n  pure_bind      (x : \u03b1) (f : \u03b1 \u2192 m \u03b2) : pure x >>= f = f x\n  bind_assoc     (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) (g : \u03b2 \u2192 m \u03b3) : x >>= f >>= g = x >>= fun x => f x >>= g\n  map_pure g x    := (by rw [\u2190 bind_pure_comp, pure_bind])\n  seq_pure g x    := (by rw [\u2190 bind_map]; simp [map_pure, bind_pure_comp])\n  seq_assoc x g h := (by simp [\u2190 bind_pure_comp, \u2190 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 \u03b1) : 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 : \u03b1 \u2192 \u03b2) (x : m \u03b1) : f <$> x = x >>= fun a => pure (f a) := by\n  rw [\u2190 bind_pure_comp]\n\ntheorem seq_eq_bind_map {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (f : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : f <*> x = f >>= (. <$> x) := by\n  rw [\u2190 bind_map]\n\ntheorem bind_congr [Bind m] {x : m \u03b1} {f g : \u03b1 \u2192 m \u03b2} (h : \u2200 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 \u27e8\u27e9) = x := by\n  rw [bind_pure]\n\ntheorem map_congr [Functor m] {x : m \u03b1} {f g : \u03b1 \u2192 \u03b2} (h : \u2200 a, f a = g a) : (f <$> x : m \u03b2) = g <$> x := by\n  simp [funext h]\n\ntheorem seq_eq_bind {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (mf : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : mf <*> x = mf >>= fun f => f <$> x := by\n  rw [bind_map]\n\ntheorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m \u03b1) (y : m \u03b2) : 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 \u03b1) (y : m \u03b2) : 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 \u03b1) (f : \u03b1 \u2192 \u03b2) : f <$> x = f x := rfl\n@[simp] theorem bind_eq (x : Id \u03b1) (f : \u03b1 \u2192 id \u03b2) : x >>= f = f x := rfl\n@[simp] theorem pure_eq (a : \u03b1) : (pure a : Id \u03b1) = 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 \u03b5 m \u03b1} (h : x.run = y.run) : x = y := by\n  simp [run] at h\n  assumption\n\n@[simp] theorem run_pure [Monad m] (x : \u03b1) : run (pure x : ExceptT \u03b5 m \u03b1) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift  [Monad.{u, v} m] (x : m \u03b1) : run (ExceptT.lift x : ExceptT \u03b5 m \u03b1) = (Except.ok <$> x : m (Except \u03b5 \u03b1)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT \u03b5 m \u03b2) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : run (ExceptT.lift x >>= f : ExceptT \u03b5 m \u03b2) = 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 : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : (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 \u03b5 m \u03b1)\n        : run (x >>= f : ExceptT \u03b5 m \u03b2)\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 : \u03b1) : ExceptT.lift (pure a) = (pure a : ExceptT \u03b5 m \u03b1) := by\n  simp [ExceptT.lift, pure, ExceptT.pure]\n\n@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1)\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 {\u03b1 \u03b2 \u03b5 : Type u} [Monad m] (mf : ExceptT \u03b5 m (\u03b1 \u2192 \u03b2)) (x : ExceptT \u03b5 m \u03b1) : mf <*> x = mf >>= fun f => f <$> x :=\n  rfl\n\nprotected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1) : x >>= pure \u2218 f = f <$> x := by\n  intros; rfl\n\nprotected theorem seqLeft_eq {\u03b1 \u03b2 \u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m] [LawfulMonad m] (x : ExceptT \u03b5 m \u03b1) (y : ExceptT \u03b5 m \u03b2) : x <* y = const \u03b2 <$> x <*> y := by\n  show (x >>= fun a => y >>= fun _ => pure a) = (const (\u03b1 := \u03b1) \u03b2 <$> x) >>= fun f => f <$> y\n  rw [\u2190 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 \u03b5 m \u03b1) (y : ExceptT \u03b5 m \u03b2) : x *> y = const \u03b1 id <$> x <*> y := by\n  show (x >>= fun _ => y) = (const \u03b1 id <$> x) >>= fun f => f <$> y\n  rw [\u2190 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 \u03b5 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 \u03c1 m \u03b1} (h : \u2200 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 : \u03b1) (ctx : \u03c1) : (pure a : ReaderT \u03c1 m \u03b1).run ctx = pure a := rfl\n\n@[simp] theorem run_bind [Monad m] (x : ReaderT \u03c1 m \u03b1) (f : \u03b1 \u2192 ReaderT \u03c1 m \u03b2) (ctx : \u03c1)\n    : (x >>= f).run ctx = x.run ctx >>= \u03bb a => (f a).run ctx := rfl\n\n@[simp] theorem run_mapConst [Monad m] (a : \u03b1) (x : ReaderT \u03c1 m \u03b2) (ctx : \u03c1)\n    : (Functor.mapConst a x).run ctx = Functor.mapConst a (x.run ctx) := rfl\n\n@[simp] theorem run_map [Monad m] (f : \u03b1 \u2192 \u03b2) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (f <$> x).run ctx = f <$> x.run ctx := rfl\n\n@[simp] theorem run_monadLift [MonadLiftT n m] (x : n \u03b1) (ctx : \u03c1)\n    : (monadLift x : ReaderT \u03c1 m \u03b1).run ctx = (monadLift x : m \u03b1) := rfl\n\n@[simp] theorem run_monadMap [MonadFunctor n m] (f : {\u03b2 : Type u} \u2192 n \u03b2 \u2192 n \u03b2) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (monadMap @f x : ReaderT \u03c1 m \u03b1).run ctx = monadMap @f (x.run ctx) := rfl\n\n@[simp] theorem run_read [Monad m] (ctx : \u03c1) : (ReaderT.read : ReaderT \u03c1 m \u03c1).run ctx = pure ctx := rfl\n\n@[simp] theorem run_seq {\u03b1 \u03b2 : Type u} [Monad m] (f : ReaderT \u03c1 m (\u03b1 \u2192 \u03b2)) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := rfl\n\n@[simp] theorem run_seqRight [Monad m] (x : ReaderT \u03c1 m \u03b1) (y : ReaderT \u03c1 m \u03b2) (ctx : \u03c1)\n    : (x *> y).run ctx = (x.run ctx *> y.run ctx) := rfl\n\n@[simp] theorem run_seqLeft [Monad m] (x : ReaderT \u03c1 m \u03b1) (y : ReaderT \u03c1 m \u03b2) (ctx : \u03c1)\n    : (x <* y).run ctx = (x.run ctx <* y.run ctx) := rfl\n\ninstance [Monad m] [LawfulFunctor m] : LawfulFunctor (ReaderT \u03c1 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 \u03c1 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 \u03c1 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' \u03c9 \u03c3 m) :=\n  inferInstanceAs (LawfulMonad (ReaderT (ST.Ref \u03c9 \u03c3) m))\n\n/-! # StateT -/\n\nnamespace StateT\n\ntheorem ext {x y : StateT \u03c3 m \u03b1} (h : \u2200 s, x.run s = y.run s) : x = y :=\n  funext h\n\n@[simp] theorem run'_eq [Monad m] (x : StateT \u03c3 m \u03b1) (s : \u03c3) : run' x s = (\u00b7.1) <$> run x s :=\n  rfl\n\n@[simp] theorem run_pure [Monad m] (a : \u03b1) (s : \u03c3) : (pure a : StateT \u03c3 m \u03b1).run s = pure (a, s) := rfl\n\n@[simp] theorem run_bind [Monad m] (x : StateT \u03c3 m \u03b1) (f : \u03b1 \u2192 StateT \u03c3 m \u03b2) (s : \u03c3)\n    : (x >>= f).run s = x.run s >>= \u03bb p => (f p.1).run p.2 := by\n  simp [bind, StateT.bind, run]\n\n@[simp] theorem run_map {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : StateT \u03c3 m \u03b1) (s : \u03c3) : (f <$> x).run s = (fun (p : \u03b1 \u00d7 \u03c3) => (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 : \u03c3)    : (get : StateT \u03c3 m \u03c3).run s = pure (s, s) := rfl\n\n@[simp] theorem run_set [Monad m] (s s' : \u03c3) : (set s' : StateT \u03c3 m PUnit).run s = pure (\u27e8\u27e9, s') := rfl\n\n@[simp] theorem run_modify [Monad m] (f : \u03c3 \u2192 \u03c3) (s : \u03c3) : (modify f : StateT \u03c3 m PUnit).run s = pure (\u27e8\u27e9, f s) := rfl\n\n@[simp] theorem run_modifyGet [Monad m] (f : \u03c3 \u2192 \u03b1 \u00d7 \u03c3) (s : \u03c3) : (modifyGet f : StateT \u03c3 m \u03b1).run s = pure ((f s).1, (f s).2) := by\n  simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run]\n\n@[simp] theorem run_lift {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (s : \u03c3) : (StateT.lift x : StateT \u03c3 m \u03b1).run s = x >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_bind_lift {\u03b1 \u03c3 : Type u} [Monad m] [LawfulMonad m] (x : m \u03b1) (f : \u03b1 \u2192 StateT \u03c3 m \u03b2) (s : \u03c3) : (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 {\u03b1 \u03c3 : Type u} [Monad m] [MonadLiftT n m] (x : n \u03b1) (s : \u03c3) : (monadLift x : StateT \u03c3 m \u03b1).run s = (monadLift x : m \u03b1) >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {\u03b2 : Type u} \u2192 n \u03b2 \u2192 n \u03b2) (x : StateT \u03c3 m \u03b1) (s : \u03c3)\n    : (monadMap @f x : StateT \u03c3 m \u03b1).run s = monadMap @f (x.run s) := rfl\n\n@[simp] theorem run_seq {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (f : StateT \u03c3 m (\u03b1 \u2192 \u03b2)) (x : StateT \u03c3 m \u03b1) (s : \u03c3) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : \u03b1 \u00d7 \u03c3) => (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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) (s : \u03c3) : (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 {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (x : StateT \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) (s : \u03c3) : (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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) : x *> y = const \u03b1 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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) : x <* y = const \u03b2 <$> x <*> y := by\n  apply ext; intro s\n  simp [map_eq_pure_bind]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateT \u03c3 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 \"\u25fe\" => 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 \u2192 Bool\n  | .forallE _ _ b _ => isPropFormerTypeQuick b\n  | .sort .zero => true\n  | _ => false\n\n/--\nReturn true iff `type` is `Prop` or `As \u2192 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 \u2190 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 \u2192 Prop`.\n-/\ndef isPropFormer (e : Expr) : MetaM Bool := do\n  isPropFormerType (\u2190 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 `\u25fe`. We use `\u25fe` to denote erased information.\n- All type definitions are expanded. If reduction gets stuck, it is replaced with `\u25fe`.\n\nRemark: you can view `\u25fe` occurring in a type position as the \"any type\".\nRemark: in our runtime, `\u25fe` 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 -> \u25fe`.\n      We convert the return type `(tupleN Nat n) to `\u25fe`, 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 \u25fe -> \u25fe`.\n      Since `(Fin n)` has dependency on `n`, we erase the `n` to get the\n      type `(Fin \u25fe)`.\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 (\u2190 isProp type) then\n    return erasedExpr\n  let type \u2190 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 \u2190 toLCNFType d\n      let b \u2190 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 \u2190 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 := (\u2190 toLCNFType d).abstract xs\n        return .forallE n d (\u2190 visitForall b (xs.push x)) bi\n    | _ =>\n      let e \u2190 toLCNFType (e.instantiateRev xs)\n      return e.abstract xs\n\n  visitApp (f : Expr) (args : Array Expr) := do\n    let fNew \u2190 match f with\n      | .const declName us =>\n        let .inductInfo _ \u2190 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 (\u2190 isProp arg) then\n        result := mkApp result erasedExpr\n      else if (\u2190 isPropFormer arg) then\n        result := mkApp result erasedExpr\n      else if (\u2190 isTypeFormer arg) then\n        result := mkApp result (\u2190 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 (\u2190 joinTypes? f g) (\u2190 joinTypes? a b))\n         <|>\n        return erasedExpr\n      | .forallE n d\u2081 b\u2081 _, .forallE _ d\u2082 b\u2082 _ =>\n        (do return .forallE n (\u2190 joinTypes? d\u2081 d\u2082) (joinTypes b\u2081 b\u2082) .default)\n        <|>\n        return erasedExpr\n      | .lam n d\u2081 b\u2081 _, .lam _ d\u2082 b\u2082 _ =>\n        (do return .lam n (\u2190 joinTypes? d\u2081 d\u2082) (joinTypes b\u2081 b\u2082) .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 \u2192 Prop`, `Prop`, `Int \u2192 Bool \u2192 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 `\u25fe` and `Nat \u2192 \u25fe`, 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 (\u2190 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) := (\u2190 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 \u2192 Nat \u2192 Key\n  | fvar  : FVarId \u2192 Nat \u2192 Key\n  | lit   : Literal \u2192 Key\n  | star  : Key\n  | other : Key\n  | arrow : Key\n  | proj  : Name \u2192 Nat \u2192 Key\n  deriving Inhabited, BEq, Repr\n\nprotected def Key.hash : Key \u2192 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 := \u27e8Key.hash\u27e9\n\ninductive Trie (\u03b1 : Type) where\n  | node (vs : Array \u03b1) (children : Array (Key \u00d7 Trie \u03b1)) : Trie \u03b1\n\nstructure DiscrTree (\u03b1 : Type) where\n  root : Std.PersistentHashMap Key (Trie \u03b1) := {}\n\ndef Key.ctorIdx : Key \u2192 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 \u2192 Key \u2192 Bool\n  | Key.lit v\u2081,      Key.lit v\u2082      => v\u2081 < v\u2082\n  | Key.fvar n\u2081 a\u2081,  Key.fvar n\u2082 a\u2082  => Name.quickLt n\u2081.name n\u2082.name || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | Key.const n\u2081 a\u2081, Key.const n\u2082 a\u2082 => Name.quickLt n\u2081 n\u2082 || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | Key.proj s\u2081 i\u2081,  Key.proj s\u2082 i\u2082  => Name.quickLt s\u2081 s\u2082 || (s\u2081 == s\u2082 && i\u2081 < i\u2082)\n  | k\u2081,              k\u2082              => k\u2081.ctorIdx < k\u2082.ctorIdx\n\ninstance : LT Key := \u27e8fun a b => Key.lt a b\u27e9\ninstance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key \u2192 Format\n  | Key.star                   => \"*\"\n  | Key.other                  => \"\u25fe\"\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                  => \"\u2192\"\n\ninstance : ToFormat Key := \u27e8Key.format\u27e9\n\ndef Key.arity : Key \u2192 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 \u03b1) := \u27e8Trie.node #[] #[]\u27e9\n\n\nnamespace DiscrTree\n\ndef empty : DiscrTree \u03b1 := { root := {} }\n\npartial def Trie.format [ToMessageData \u03b1] : Trie \u03b1 \u2192 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 \u27e8k, c\u27e9 => MessageData.paren (toMessageData k ++ \" => \" ++ format c)) \",\"\n\ninstance [ToMessageData \u03b1] : ToMessageData (Trie \u03b1) := \u27e8Trie.format\u27e9\n\npartial def format [ToMessageData \u03b1] (d : DiscrTree \u03b1) : MessageData :=\n  let (_, r) := d.root.foldl\n    (fun (p : Bool \u00d7 MessageData) k c =>\n      (false, p.2 ++ MessageData.paren (toMessageData k ++ \" => \" ++ toMessageData c)))\n    (true, Format.nil)\n  MessageData.group r\n\ninstance [ToMessageData \u03b1] : ToMessageData (DiscrTree \u03b1) := \u27e8fun dt => format dt\u27e9\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 \u03b1) 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 \u03b1]`) 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., `{\u03b1 : 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 \u27e8i, h\u27e9\n    if info.isInstImplicit then\n      return true\n    else if info.isImplicit || info.isStrictImplicit then\n      return not (\u2190 isType a)\n    else\n      isProof a\n  else\n    isProof a\n\nprivate partial def pushArgsAux (infos : Array Meta.ParamInfo) : Nat \u2192 Expr \u2192 Array Expr \u2192 MetaM (Array Expr)\n  | i, Expr.app f a, todo => do\n    if (\u2190 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 \u00d7 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 \u00d7 Array Expr) := do\n      let info \u2190 getFunInfoNArgs fn nargs\n      let todo \u2190 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) \u2190 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 : \u03b1) (i : Nat) : Trie \u03b1 :=\n  if h : i < keys.size then\n    let k := keys.get \u27e8i, h\u27e9\n    let c := createNodes keys v (i+1)\n    Trie.node #[] #[(k, c)]\n  else\n    Trie.node #[v] #[]\n\nprivate def insertVal [BEq \u03b1] (vs : Array \u03b1) (v : \u03b1) : Array \u03b1 :=\n  if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq \u03b1] (keys : Array Key) (v : \u03b1) : Nat \u2192 Trie \u03b1 \u2192 Trie \u03b1\n  | i, Trie.node vs cs =>\n    if h : i < keys.size then\n      let k := keys.get \u27e8i, h\u27e9\n      let c := Id.run $ cs.binInsertM\n          (fun a b => a.1 < b.1)\n          (fun \u27e8_, s\u27e9 => 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 \u03b1] (d : DiscrTree \u03b1) (keys : Array Key) (v : \u03b1) : DiscrTree \u03b1 :=\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 \u03b1] (d : DiscrTree \u03b1) (e : Expr) (v : \u03b1) : MetaM (DiscrTree \u03b1) := do\n  let keys \u2190 mkPath e\n  return d.insertCore keys v\n\nprivate def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key \u00d7 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 \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree \u03b1) : Array \u03b1 :=\n  let result : Array \u03b1 := 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 \u00d7 Trie \u03b1)) (k : Key) : Option (Key \u00d7 Trie \u03b1) :=\n  cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie \u03b1) (result : Array \u03b1) : MetaM (Array \u03b1) := 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) \u2190 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 \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) : MetaM (Array \u03b1) :=\n        match findKey cs k with\n        | none   => pure result\n        | some c => getMatchLoop (todo ++ args) c.2 result\n      let result \u2190 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 #[] (\u2190 visitNonStar k args result)\n      | _         => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree \u03b1) (k : Key) (args : Array Expr) (result : Array \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) (e : Expr) : MetaM (Array \u03b1) := do\n  Core.checkMaxHeartbeats \"getMatch\"\n  let result := getStarResult d\n  let (k, args) \u2190 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 \u03b1) (e : Expr) : MetaM (Array \u03b1) := do\n  Core.checkMaxHeartbeats \"getUnify\"\n  let (k, args) \u2190 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 \u03b1) (result : Array \u03b1) : MetaM (Array \u03b1) := 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 \u27e8k, c\u27e9 => 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) \u2190 getUnifyKeyArgs e (root := false)\n        let visitStar (result : Array \u03b1) : MetaM (Array \u03b1) :=\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 \u03b1) : MetaM (Array \u03b1) :=\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 \u27e8k, c\u27e9 => process k.arity todo c result\n        -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n        | Key.arrow => visitNonStar Key.other #[] (\u2190 visitNonStar k args (\u2190 visitStar result))\n        | _         => visitNonStar k args (\u2190 visitStar result)\n\nend DiscrTree\n\n-- From AESOP:\nnamespace Trie\n\nunsafe def foldMUnsafe [Monad m] (initialKeys : Array Key)\n    (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 m \u03c3) (init : \u03c3) : Trie \u03b1 \u2192 m \u03c3\n  | Trie.node vs children => do\n    let s \u2190 vs.foldlM (init := init) \u03bb s v => f s initialKeys v\n    children.foldlM (init := s) \u03bb s (k, t) =>\n      t.foldMUnsafe (initialKeys.push k) f s\n\n@[implementedBy foldMUnsafe]\nopaque foldM [Monad m] (initalKeys : Array Key)\n    (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 m \u03c3) (init : \u03c3) (t : Trie \u03b1) : m \u03c3 :=\n  pure init\n\n@[inline]\ndef fold (initialKeys : Array Key) (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 \u03c3) (init : \u03c3)\n    (t : Trie \u03b1) : \u03c3 :=\n  Id.run $ t.foldM initialKeys (init := init) \u03bb s k a => return f s k a\n\nend Trie\n\nnamespace DiscrTree\n\n@[inline]\ndef foldM [Monad m] (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 m \u03c3) (init : \u03c3) (t : DiscrTree \u03b1) :\n    m \u03c3 :=\n  t.root.foldlM (init := init) \u03bb s k t => t.foldM #[k] (init := s) f\n\n@[inline]\ndef fold (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 \u03c3) (init : \u03c3) (t : DiscrTree \u03b1) : \u03c3 :=\n  Id.run $ t.foldM (init := init) \u03bb 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 \u03b1] (t u : DiscrTree \u03b1) : DiscrTree \u03b1 :=\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 \u03b1) : Array \u03b1 :=\n  t.fold (init := #[]) \u03bb as _ a => as.push a\n\ndef toArray (t : DiscrTree \u03b1) : Array (Array Key \u00d7 \u03b1) :=\n  t.fold (init := #[]) \u03bb 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 : \u03b1 \u00d7 \u03b2 \u00d7 \u03b3) : True := by\n  rcases x with \u27e8a, b, c\u27e9\n  guard_hyp a : \u03b1\n  guard_hyp b : \u03b2\n  guard_hyp c : \u03b3\n  trivial\n\nexample (x : \u03b1 \u00d7 \u03b2 \u00d7 \u03b3) : True := by\n  rcases x with \u27e8(a : \u03b1) : id \u03b1, -, c : id \u03b3\u27e9\n  guard_hyp a : \u03b1\n  fail_if_success have : \u03b2 := by assumption\n  guard_hyp c : id \u03b3\n  trivial\n\nexample (x : (\u03b1 \u00d7 \u03b2) \u00d7 \u03b3) : True := by\n  fail_if_success rcases x with \u27e8_a, b, c\u27e9\n  fail_if_success rcases x with \u27e8\u27e8a:\u03b2, b\u27e9, c\u27e9\n  rcases x with \u27e8\u27e8a:\u03b1, b\u27e9, c\u27e9\n  guard_hyp a : \u03b1\n  guard_hyp b : \u03b2\n  guard_hyp c : \u03b3\n  trivial\n\nexample : @Inhabited.{1} \u03b1 \u00d7 Option \u03b2 \u2295 \u03b3 \u2192 True := by\n  rintro (\u27e8\u27e8a\u27e9, _ | b\u27e9 | c)\n  \u00b7 guard_hyp a : \u03b1; trivial\n  \u00b7 guard_hyp a : \u03b1; guard_hyp b : \u03b2; trivial\n  \u00b7 guard_hyp c : \u03b3; trivial\n\nexample : cond false Nat Int \u2192 cond true Int Nat \u2192 Nat \u2295 Unit \u2192 True := by\n  rintro (x y : Int) (z | u)\n  \u00b7 guard_hyp x : Int; guard_hyp y : Int; guard_hyp z : Nat; trivial\n  \u00b7 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 _|\u27e8\u27e9|z\n  \u00b7 guard_hyp h : Nat.zero = y; trivial\n  \u00b7 guard_hyp h : Nat.succ Nat.zero = y; trivial\n  \u00b7 guard_hyp z : Nat\n    guard_hyp h : Nat.succ (Nat.succ z) = y; trivial\n\nexample (h : x = 3) (h\u2082 : x < 4) : x < 4 := by\n  rcases h with \u27e8\u27e9\n  guard_hyp h\u2082 : 3 < 4; guard_target = 3 < 4; exact h\u2082\n\nexample (h : x = 3) (h\u2082 : x < 4) : x < 4 := by\n  rcases h with rfl\n  guard_hyp h\u2082 : 3 < 4; guard_target = 3 < 4; exact h\u2082\n\nexample (h : 3 = x) (h\u2082 : x < 4) : x < 4 := by\n  rcases h with \u27e8\u27e9\n  guard_hyp h\u2082 : 3 < 4; guard_target = 3 < 4; exact h\u2082\n\nexample (h : 3 = x) (h\u2082 : x < 4) : x < 4 := by\n  rcases h with rfl\n  guard_hyp h\u2082 : 3 < 4; guard_target = 3 < 4; exact h\u2082\n\nexample (s : \u03b1 \u2295 Empty) : True := by\n  rcases s with s|\u27e8\u27e8\u27e9\u27e9\n  guard_hyp s : \u03b1; trivial\n\nexample : True := by\n  obtain \u27e8n : Nat, _h : n = n, -\u27e9 : \u2203 n : Nat, n = n \u2227 True\n  \u00b7 exact \u27e80, rfl, trivial\u27e9\n  trivial\n\nexample : True := by\n  obtain (h : True) | \u27e8\u27e8\u27e9\u27e9 : True \u2228 False\n  \u00b7 exact Or.inl trivial\n  guard_hyp h : True; trivial\n\nexample : True := by\n  obtain h | \u27e8\u27e8\u27e9\u27e9 : True \u2228 False := Or.inl trivial\n  guard_hyp h : True; trivial\n\nexample : True := by\n  obtain \u27e8h, h2\u27e9 := And.intro trivial trivial\n  guard_hyp h : True; guard_hyp h2 : True; trivial\n\nexample : True := by\n  fail_if_success obtain \u27e8h, h2\u27e9\n  trivial\n\nexample (x y : \u03b1 \u00d7 \u03b2) : True := by\n  rcases x, y with \u27e8\u27e8a, b\u27e9, c, d\u27e9\n  guard_hyp a : \u03b1; guard_hyp b : \u03b2\n  guard_hyp c : \u03b1; guard_hyp d : \u03b2\n  trivial\n\nexample (x y : \u03b1 \u2295 \u03b2) : True := by\n  rcases x, y with \u27e8a|b, c|d\u27e9\n  \u00b7 guard_hyp a : \u03b1; guard_hyp c : \u03b1; trivial\n  \u00b7 guard_hyp a : \u03b1; guard_hyp d : \u03b2; trivial\n  \u00b7 guard_hyp b : \u03b2; guard_hyp c : \u03b1; trivial\n  \u00b7 guard_hyp b : \u03b2; guard_hyp d : \u03b2; trivial\n\nexample (i j : Nat) : (\u03a3' x, i \u2264 x \u2227 x \u2264 j) \u2192 i \u2264 j := by\n  intro h\n  rcases h' : h with \u27e8x, h\u2080, h\u2081\u27e9\n  guard_hyp h' : h = \u27e8x, h\u2080, h\u2081\u27e9\n  apply Nat.le_trans h\u2080 h\u2081\n\nexample (x : Quot fun _ _ : \u03b1 => True) (h : x = x): x = x := by\n  rcases x with \u27e8z\u27e9\n  guard_hyp z : \u03b1\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 \u2228 n + 1 \u2264 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 \u2264 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 $ (\u2190 getLCtx).foldl (fun i _ => i+1) 0 = n.1.toNat + 1\n\nexample (h : \u2203 x : Nat, x = x \u2227 1 = 1) : True := by\n  rcases h with \u27e8-, _\u27e9\n  check_num_hyps 0\n  trivial\n\nexample (h : \u2203 x : Nat, x = x \u2227 1 = 1) : True := by\n  rcases h with \u27e8-, _, h\u27e9\n  check_num_hyps 1\n  guard_hyp h : 1 = 1\n  trivial\n\nexample (h : True \u2228 True \u2228 True) : True := by\n  rcases h with - | - | -\n  iterate 3 \u00b7 check_num_hyps 0; trivial\n\nexample : Bool \u2192 False \u2192 True\n| false => by rintro \u27e8\u27e9\n| true => by rintro \u27e8\u27e9\n\nexample : (b : Bool) \u2192 cond b False False \u2192 True := by\n  rintro \u27e8\u27e9 \u27e8\u27e9\n\nstructure Baz {\u03b1 : Type _} (f : \u03b1 \u2192 \u03b1) : Prop where\n  [inst : Nonempty \u03b1]\n  h : f \u2218 f = id\n\nexample {\u03b1} (f : \u03b1 \u2192 \u03b1) (h : Baz f) : True := by rcases h with \u27e8_\u27e9; trivial\n\nexample {\u03b1} (f : \u03b1 \u2192 \u03b1) (h : Baz f) : True := by rcases h with @\u27e8_, _\u27e9; trivial\n\ninductive Test : Nat \u2192 Prop\n  | a (n) : Test (2 + n)\n  | b {n} : n > 5 \u2192 Test (n * n)\n\nexample {n} (h : Test n) : n = n := by\n  have : True := by\n    rcases h with (a | b)\n    \u00b7 guard_hyp a : Nat\n      trivial\n    \u00b7 guard_hyp b : \u2039Nat\u203a > 5\n      trivial\n  \u00b7 rcases h with (a | @\u27e8n, b\u27e9)\n    \u00b7 guard_hyp a : Nat\n      trivial\n    \u00b7 guard_hyp b : n > 5\n      trivial\n\nexample (h : a \u2264 2 \u2228 2 < a) : True := by\n  obtain ha1 | ha2 : a \u2264 2 \u2228 3 \u2264 a := h\n  \u00b7 guard_hyp ha1 : a \u2264 2; trivial\n  \u00b7 guard_hyp ha2 : 3 \u2264 a; trivial\n\nexample (h : a \u2264 2 \u2228 2 < a) : True := by\n  obtain ha1 | ha2 : a \u2264 2 \u2228 3 \u2264 a := id h\n  \u00b7 guard_hyp ha1 : a \u2264 2; trivial\n  \u00b7 guard_hyp ha2 : 3 \u2264 a; trivial\n\ninductive BaseType : Type where\n  | one\n\ninductive BaseTypeHom : BaseType \u2192 BaseType \u2192 Type where\n  | loop : BaseTypeHom one one\n  | id (X : BaseType) : BaseTypeHom X X\n\nexample : BaseTypeHom one one \u2192 Unit := by rintro \u27e8_\u27e9 <;> 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": "/-\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, S\u00e9bastien Gou\u00ebzel, Scott Morrison\n-/\nimport logic.nonempty\nimport tactic.lint\nimport tactic.dependencies\n\nsetup_tactic_parser\n\nnamespace tactic\nnamespace interactive\nopen interactive interactive.types expr\n\n/-- Similar to `constructor`, but does not reorder goals. -/\nmeta def fconstructor : tactic unit := concat_tags tactic.fconstructor\n\nadd_tactic_doc\n{ name       := \"fconstructor\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.fconstructor],\n  tags       := [\"logic\", \"goal management\"] }\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 \u2190 i_to_expr_strict max >>= tactic.eval_expr nat,\n  \u03bb 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 :=\npropagate_tags $ l.mmap' (\u03bb h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"substs\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.substs],\n  tags       := [\"rewriting\"] }\n\n/-- Unfold coercion-related definitions -/\nmeta def unfold_coes (loc : parse location) : tactic unit :=\nunfold [\n  ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,\n  ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,\n  ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc\n\nadd_tactic_doc\n{ name       := \"unfold_coes\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.unfold_coes],\n  tags       := [\"simplification\"] }\n\n\n/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/\nmeta def unfold_wf :=\npropagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof)\n\n/-- Unfold auxiliary definitions associated with the current declaration. -/\nmeta def unfold_aux : tactic unit :=\ndo tgt \u2190 target,\n   name \u2190 decl_name,\n   let to_unfold := (tgt.list_names_with_prefix name),\n   guard (\u00ac 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\u03bb s, result.cases_on (tac s)\n (\u03bb a, result.success ())\n (\u03bb e ref, result.success ())\n\n/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without\nrequiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a\nnon-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/\n@[inline] protected meta def id (tac : itactic) : tactic unit := tac\n\n/--\n`work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero),\nand does not require that the goal be solved at the end\n(any remaining subgoals are inserted back into the list of goals).\n\nTypically usage might look like:\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 2\n{ dsimp,\n  simp },\nrefl\n````\n\nSee also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`.\n-/\nmeta def work_on_goal : parse small_nat \u2192 itactic \u2192 tactic unit\n| n t := do\n  goals \u2190 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 \u2190 get_goals,\n  set_goals (earlier_goals ++ new_goals ++ later_goals)\n\n/--\n`swap n` will move the `n`th goal to the front.\n`swap` defaults to `swap 2`, and so interchanges the first and second goals.\n\nSee also `tactic.interactive.rotate`, which moves the first `n` goals to the back.\n-/\nmeta def swap (n := 2) : tactic unit :=\ndo gs \u2190 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\nadd_tactic_doc\n{ name       := \"swap\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.swap],\n  tags       := [\"goal management\"] }\n\n/--\n`rotate` moves the first goal to the back. `rotate n` will do this `n` times.\n\nSee also `tactic.interactive.swap`, which moves the `n`th goal to the front.\n-/\nmeta def rotate (n := 1) : tactic unit := tactic.rotate n\n\nadd_tactic_doc\n{ name       := \"rotate\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.rotate],\n  tags       := [\"goal management\"] }\n\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\nmeta def clear_ : tactic unit := tactic.repeat $ do\n  l \u2190 local_context,\n  l.reverse.mfirst $ \u03bb h, do\n    name.mk_string s p \u2190 return $ local_pp_name h,\n    guard (s.front = '_'),\n    cl \u2190 infer_type h >>= is_class, guard (\u00ac cl),\n    tactic.clear h\n\nadd_tactic_doc\n{ name       := \"clear_\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_],\n  tags       := [\"context management\"] }\n\n/--\nActs like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nmeta def replace (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?)\n  (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\ndo let h := h.get_or_else `this,\n  old \u2190 try_core (get_local h),\n  \u00abhave\u00bb h q\u2081 q\u2082,\n  match old, q\u2082 with\n  | none,   _      := skip\n  | some o, some _ := tactic.clear o\n  | some o, none   := swap >> tactic.clear o >> swap\n  end\n\nadd_tactic_doc\n{ name       := \"replace\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.replace],\n  tags       := [\"context management\"] }\n\n/-- Make every proposition in the context decidable. -/\nmeta def classical := tactic.classical\n\nadd_tactic_doc\n{ name       := \"classical\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.classical],\n  tags       := [\"classical logic\", \"type class\"] }\n\nprivate meta def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\n@[nolint def_lemma]\nlemma {u} generalize_a_aux {\u03b1 : Sort u}\n  (h : \u2200 x : Sort u, (\u03b1 \u2192 x) \u2192 x) : \u03b1 := h \u03b1 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' \u2190 get_unused_name `h,\n   x' \u2190 get_unused_name `x,\n   g \u2190 if \u00ac 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 \u2190 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\nadd_tactic_doc\n{ name       := \"generalize_hyp\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize_hyp],\n  tags       := [\"context management\"] }\n\nmeta def compact_decl_aux : list name \u2192 binder_info \u2192 expr \u2192 list expr \u2192\n  tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| ns bi t [] := pure [(ns.reverse, bi, t)]\n| ns bi t (v'@(local_const n pp bi' t') :: xs) :=\n  do t' \u2190 infer_type v',\n     if bi = bi' \u2227 t = t'\n       then compact_decl_aux (pp :: ns) bi t xs\n       else do vs \u2190 compact_decl_aux [pp] bi' t' xs,\n               pure $ (ns.reverse, bi, t) :: vs\n| ns bi t (_ :: xs) := compact_decl_aux ns bi t xs\n\n/-- go from (x\u2080 : t\u2080) (x\u2081 : t\u2080) (x\u2082 : t\u2080) to (x\u2080 x\u2081 x\u2082 : t\u2080) -/\nmeta def compact_decl : list expr \u2192 tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| [] := pure []\n| (v@(local_const n pp bi t) :: xs)  :=\n  do t \u2190 infer_type v,\n     compact_decl_aux [pp] bi t xs\n| (_ :: xs) := compact_decl xs\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.\n-/\nmeta def clean (q : parse texpr) : tactic unit :=\ndo tgt : expr \u2190 target,\n   e \u2190 i_to_expr_strict ``(%%q : %%tgt),\n   tactic.exact $ e.clean\n\nmeta def source_fields (missing : list name) (e : pexpr) : tactic (list (name \u00d7 pexpr)) :=\ndo e \u2190 to_expr e,\n   t \u2190 infer_type e,\n   let struct_n : name := t.get_app_fn.const_name,\n   fields \u2190 expanded_field_list struct_n,\n   let exp_fields := fields.filter (\u03bb x, x.2 \u2208 missing),\n   exp_fields.mmap $ \u03bb \u27e8p,n\u27e9,\n     (prod.mk n \u2218 to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]\n\nmeta def collect_struct' : pexpr \u2192 state_t (list $ expr\u00d7structure_instance_info) tactic pexpr | e :=\ndo some str \u2190 pure (e.get_structure_instance_info)\n       | e.traverse collect_struct',\n   v \u2190 monad_lift mk_mvar,\n   modify (list.cons (v,str)),\n   pure $ to_pexpr v\n\nmeta def collect_struct (e : pexpr) : tactic $ pexpr \u00d7 list (expr\u00d7structure_instance_info) :=\nprod.map id list.reverse <$> (collect_struct' e).run []\n\nmeta def refine_one (str : structure_instance_info) :\n  tactic $ list (expr\u00d7structure_instance_info) :=\ndo    tgt \u2190 target >>= whnf,\n      let struct_n : name := tgt.get_app_fn.const_name,\n      exp_fields \u2190 expanded_field_list struct_n,\n      let missing_f := exp_fields.filter (\u03bb f, (f.2 : name) \u2209 str.field_names),\n      (src_field_names,src_field_vals) \u2190 (@list.unzip name _ \u2218 list.join) <$>\n        str.sources.mmap (source_fields $ missing_f.map prod.snd),\n      let provided  := exp_fields.filter (\u03bb f, (f.2 : name) \u2208 str.field_names),\n      let missing_f' := missing_f.filter (\u03bb x, x.2 \u2209 src_field_names),\n      vs \u2190 mk_mvar_list missing_f'.length,\n      (field_values,new_goals) \u2190 list.unzip <$> (str.field_values.mmap collect_struct : tactic _),\n      e' \u2190 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 \u2190 with_enable_tags (\n        mzip_with (\u03bb (n : name \u00d7 name) v, do\n           set_goals [v],\n           try (dsimp_target simp_lemmas.mk),\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 \u00d7 structure_instance_info \u2192 tactic (list expr) | (e,str) :=\ndo set_goals [e],\n   rs \u2190 refine_one str,\n   gs \u2190 get_goals,\n   gs' \u2190 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 of semigroup\ninstances:\n\n```lean\nrefine_struct ( { .. } : semigroup \u03b1 ),\n-- case semigroup, mul\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nmeta def refine_struct : parse texpr \u2192 tactic unit | e :=\ndo (x,xs) \u2190 collect_struct e,\n   refine x,\n   gs \u2190 get_goals,\n   xs' \u2190 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 \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p\n\n/--\n`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).\nWe use this tactic for writing tests.\n-/\nmeta def match_hyp (n : parse ident) (p : parse $ tk \":\" *> texpr) (m := reducible) :\n  tactic (list expr) :=\ndo\n  h \u2190 get_local n >>= infer_type >>= instantiate_mvars,\n  match_expr p h m\n\n/--\n`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast\nto `guard_expr`, this tests strict (syntactic) equality.\nWe use this tactic for writing tests.\n-/\nmeta def guard_expr_strict (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, guard (t = e)\n\n/--\n`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_target_strict (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_strict t p\n\n/--\n`guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal\nto `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_hyp_strict (n : parse ident) (p : parse $ tk \":\" *> texpr) : tactic unit :=\ndo h \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p\n\n/-- Tests that there are `n` hypotheses in the current context. -/\nmeta def guard_hyp_nums (n : \u2115) : tactic unit :=\ndo k \u2190 local_context,\n   guard (n = k.length) <|> fail format!\"{k.length} hypotheses found\"\n\n/-- Test that `t` is the tag of the main goal. -/\nmeta def guard_tags (tags : parse ident*) : tactic unit :=\ndo (t : list name) \u2190 get_main_tag,\n   guard (t = tags)\n\n/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term\n  unifies with `p`. -/\nmeta def guard_proof_term (t : itactic) (p : parse texpr) : itactic :=\ndo\n  g :: _ \u2190 get_goals,\n  e \u2190 to_expr p,\n  t,\n  g \u2190 instantiate_mvars g,\n  unify e g\n\n/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with\nerror message `msg` (for test writing purposes). -/\nmeta def success_if_fail_with_msg (tac : tactic.interactive.itactic) :=\ntactic.success_if_fail_with_msg tac\n\n/-- Get the field of the current goal. -/\nmeta def get_current_field : tactic name :=\ndo [_,field,str] \u2190 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 \u2190 get_goals,\n   ts \u2190 gs.mmap get_tag,\n   ([g],gs') \u2190 pure $ (list.zip gs ts).partition (\u03bb 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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\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\nadd_tactic_doc\n{ name       := \"refine_struct\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field,\n                 `tactic.interactive.have_field],\n  tags       := [\"structures\"],\n  inherit_description_from := `tactic.interactive.refine_struct }\n\n/--\n`apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is optional, equal to 50 by default.\nYou can pass an `apply_cfg` option argument as `apply_rules hs n opt`.\n(A typical usage would be with `apply_rules hs n { md := reducible })`,\nwhich asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)\nwhen checking if a lemma matches the goal.)\n\n`hs` can contain user attributes: in this case all theorems with this\nattribute are added to the list of rules.\n\nFor instance:\n\n```lean\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 b + d * e + b + d + e :=\n-- any of the following lines solve the goal:\nadd_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\nby apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\nby apply_rules [mono_rules]\nby apply_rules mono_rules\n```\n-/\nmeta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) (opt : apply_cfg := {}) :\n  tactic unit :=\ntactic.apply_rules hs n opt\n\nadd_tactic_doc\n{ name       := \"apply_rules\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.apply_rules],\n  tags       := [\"lemma application\"] }\n\nmeta def return_cast (f : option expr) (t : option (expr \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr))\n  (e x x' eq_h : expr) :\n  tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 expr)) :=\n(do guard (\u00ac e.has_var),\n    unify x x',\n    u \u2190 mk_meta_univ,\n    f \u2190 f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],\n    t' \u2190 infer_type e,\n    some (f',t) \u2190 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 \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr)) :\n  expr \u2192 tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 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 %%\u03b1 %%p %%a %%b  %%eq_h %%x') := return_cast p t es e x x' eq_h\n| e@`(@eq.substr %%\u03b1 %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'\n| e@`(@eq.rec %%\u03b1 %%a %%f %%x' _  %%eq_h) := return_cast f t es e x x' eq_h\n| e@`(@eq.rec_on %%\u03b1 %%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 \u00d7 expr \u00d7 expr)) :=\n(list.reverse \u2218 prod.snd) <$> tgt.mfold (none, []) (\u03bb e i es, list_cast_of_aux x es.1 es.2 e)\n\nprivate meta def h_generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`;\n- `h_generalize Hx : e == x with _` chooses automatically chooses the name of\n  assumption `\u03b1 = \u03b2`;\n- `h_generalize! Hx : e == x` reverts `Hx`;\n- when `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' \u2190 (h' : tactic name) <|> get_unused_name (\"h\" ++ n.to_string : string),\n   e \u2190 to_expr e,\n   tgt \u2190 target,\n   ((e,x,eq_h)::es) \u2190 list_cast_of e tgt | fail \"no cast found\",\n   interactive.generalize h' () (to_pexpr e, n),\n   asm \u2190 get_local h',\n   v \u2190 get_local n,\n   hs \u2190 es.mmap (\u03bb \u27e8e,_\u27e9, mk_app `eq [e,v]),\n   (eqs_h.zip [e]).mmap' (\u03bb \u27e8h,e\u27e9, do\n        h \u2190 if h \u2260 `_ then pure h else get_unused_name `h,\n        () <$ note h none eq_h ),\n   hs.mmap' (\u03bb h,\n     do h' \u2190 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_cast_eq %%eq_h %%asm))\n     >>= note h' none >> pure ()),\n   tactic.clear asm,\n   when rev.is_some (interactive.revert [n])\n\nadd_tactic_doc\n{ name       := \"h_generalize\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.h_generalize],\n  tags       := [\"context management\"] }\n\n/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that\n  this uses definitional equality instead of alpha-equivalence. -/\nmeta def guard_expr_eq' (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, is_def_eq t e\n\n/--\n`guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.\nWe use this tactic for writing tests.\nThe difference with `guard_target` is that this uses definitional equality instead of\nalpha-equivalence.\n-/\nmeta def guard_target' (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_eq' t p\n\nadd_tactic_doc\n{ name       := \"guard_target'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.guard_target'],\n  tags       := [\"testing\"] }\n\n/--\nTries to solve the goal using a canonical proof of `true` or the `reflexivity` tactic.\nUnlike `trivial` or `trivial'`, does not the `contradiction` tactic.\n-/\nmeta def triv : tactic unit :=\ntactic.triv <|> tactic.reflexivity <|> fail \"triv tactic failed\"\n\nadd_tactic_doc\n{ name       := \"triv\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.triv],\n  tags       := [\"finishing\"] }\n\n/--\nA weaker version of `trivial` that tries to solve the goal using a canonical proof of `true` or the\n`reflexivity` tactic (unfolding only `reducible` constants, so can fail faster than `trivial`),\nand otherwise tries the `contradiction` tactic. -/\nmeta def trivial' : tactic unit :=\ntactic.triv'\n  <|> tactic.reflexivity reducible\n  <|> tactic.contradiction\n  <|> fail \"trivial' tactic failed\"\n\nadd_tactic_doc\n{ name       := \"trivial'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.trivial'],\n  tags       := [\"finishing\"] }\n\n/--\nSimilar to `existsi`. `use x` will instantiate the first term of an `\u2203` or `\u03a3` goal with `x`. It\nwill then try to close the new goal using `trivial'`, or try to simplify it by applying\n`exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type.\n`use` will alternatively take a list of terms `[x0, ..., xn]`.\n\n`use` will work with constructors of arbitrary inductive types.\n\nExamples:\n```lean\nexample (\u03b1 : Type) : \u2203 S : set \u03b1, S = S :=\nby use \u2205\n\nexample : \u2203 x : \u2124, x = x :=\nby use 42\n\nexample : \u2203 n > 0, n = n :=\nbegin\n  use 1,\n  -- goal is now 1 > 0 \u2227 1 = 1, whereas it would be \u2203 (H : 1 > 0), 1 = 1 after existsi 1.\n  exact \u27e8zero_lt_one, rfl\u27e9,\nend\n\nexample : \u2203 a b c : \u2124, a + b + c = 6 :=\nby use [1, 2, 3]\n\nexample : \u2203 p : \u2124 \u00d7 \u2124, p.1 = 1 :=\nby use \u27e81, 42\u27e9\n\nexample : \u03a3 x y : \u2124, (\u2124 \u00d7 \u2124) \u00d7 \u2124 :=\nby use [1, 2, 3, 4, 5]\n\ninductive foo\n| mk : \u2115 \u2192 bool \u00d7 \u2115 \u2192 \u2115 \u2192 foo\n\nexample : foo :=\nby use [100, tt, 4, 3]\n```\n-/\nmeta def use (l : parse pexpr_list_or_texpr) : tactic unit :=\nfocus1 $\n  tactic.use l;\n  try (trivial' <|> (do\n        `(Exists %%p) \u2190 target,\n        to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip))\n\nadd_tactic_doc\n{ name       := \"use\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.use, `tactic.interactive.existsi],\n  tags       := [\"logic\"],\n  inherit_description_from := `tactic.interactive.use }\n\n/--\n`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.\nThis includes the induction hypothesis when using the equation compiler and\n`_let_match` and `_fun_match`.\n\nIt is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these\nauxiliary declarations, and produce an error saying the recursion is not well founded.\n\n```lean\nexample (n m : \u2115) (h\u2081 : n = m) (h\u2082 : \u2203 a : \u2115, a = n \u2227 a = m) : 2 * m = 2 * n :=\nlet \u27e8a, ha\u27e9 := h\u2082 in\nbegin\n  clear_aux_decl, -- subst will fail without this line\n  subst h\u2081\nend\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl, -- finish produces an error without this line\n  finish\nend\n```\n-/\nmeta def clear_aux_decl : tactic unit := tactic.clear_aux_decl\n\nadd_tactic_doc\n{ name       := \"clear_aux_decl\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl],\n  tags       := [\"context management\"],\n  inherit_description_from := `tactic.interactive.clear_aux_decl }\n\nmeta def loc.get_local_pp_names : loc \u2192 tactic (list name)\n| loc.wildcard := list.map expr.local_pp_name <$> local_context\n| (loc.ns l) := return l.reduce_option\n\nmeta def loc.get_local_uniq_names (l : loc) : tactic (list name) :=\nlist.map expr.local_uniq_name <$> l.get_locals\n\n/--\nThe logic of `change x with y at l` fails when there are dependencies.\n`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.\nIn this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses\nin `l`. As long as `x` and `y` are defeq, it should never fail.\n-/\nmeta def change' (q : parse texpr) : parse (tk \"with\" *> texpr)? \u2192 parse location \u2192 tactic unit\n| none (loc.ns [none]) := do e \u2190 i_to_expr q, change_core e none\n| none (loc.ns [some h]) := do eq \u2190 i_to_expr q, eh \u2190 get_local h, change_core eq (some eh)\n| none _ := fail \"change-at does not support multiple locations\"\n| (some w) l :=\n  do l' \u2190 loc.get_local_pp_names l,\n     l'.mmap' (\u03bb e, try (change_with_at q w e)),\n     when l.include_goal $ change q w (loc.ns [none])\n\nadd_tactic_doc\n{ name       := \"change'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.change', `tactic.interactive.change],\n  tags       := [\"renaming\"],\n  inherit_description_from := `tactic.interactive.change' }\n\nprivate meta def opt_dir_with : parser (option (bool \u00d7 name)) :=\n(do tk \"with\",\n   arrow \u2190 (tk \"<-\")?,\n   h \u2190 ident,\n   return (arrow.is_some, h)) <|> return none\n\n/--\n`set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to\nthe local context and replaces `t` with `a` everywhere it can.\n\n`set a := t with \u2190h` will add `h : t = a` instead.\n\n`set! a := t with h` does not do any replacing.\n\n```lean\nexample (x : \u2115) (h : x = 3)  : x + x + x = 9 :=\nbegin\n  set y := x with \u2190h_xy,\n/-\nx : \u2115,\ny : \u2115 := x,\nh_xy : x = y,\nh : y = 3\n\u22a2 y + y + y = 9\n-/\nend\n```\n-/\nmeta def set (h_simp : parse (tk \"!\")?) (a : parse ident) (tp : parse ((tk \":\") >> texpr)?)\n  (_ : parse (tk \":=\")) (pv : parse texpr)\n  (rev_name : parse opt_dir_with) :=\ndo tp \u2190 i_to_expr $ tp.get_or_else pexpr.mk_placeholder,\n   pv \u2190 to_expr ``(%%pv : %%tp),\n   tp \u2190 instantiate_mvars tp,\n   definev a tp pv,\n   when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard,\n   match rev_name with\n   | some (flip, id) :=\n     do nv \u2190 get_local a,\n        mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id,\n        reflexivity\n   | none := skip\n   end\n\nadd_tactic_doc\n{ name       := \"set\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.set],\n  tags       := [\"context management\"] }\n\n/--\n`clear_except h\u2080 h\u2081` deletes all the assumptions it can except for `h\u2080` and `h\u2081`.\n-/\nmeta def clear_except (xs : parse ident *) : tactic unit :=\ndo n \u2190 xs.mmap (try_core \u2218 get_local) >>= revert_lst \u2218 list.filter_map id,\n   ls \u2190 local_context,\n   ls.reverse.mmap' $ try \u2218 tactic.clear,\n   intron_no_renames n\n\nadd_tactic_doc\n{ name       := \"clear_except\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_except],\n  tags       := [\"context management\"] }\n\n\nmeta def format_names (ns : list name) : format :=\nformat.join $ list.intersperse \" \" (ns.map to_fmt)\n\nprivate meta def indent_bindents (l r : string) : option (list name) \u2192 expr \u2192 tactic format\n| none e :=\n  do e \u2190 pp e,\n     pformat!\"{l}{format.nest l.length e}{r}\"\n| (some ns) e :=\n  do e \u2190 pp e,\n     let ns := format_names ns,\n     let margin := l.length + ns.to_string.length + \" : \".length,\n     pformat!\"{l}{ns} : {format.nest margin e}{r}\"\n\nprivate meta def format_binders : list name \u00d7 binder_info \u00d7 expr \u2192 tactic format\n| (ns, binder_info.default, t) := indent_bindents \"(\" \")\" ns t\n| (ns, binder_info.implicit, t) := indent_bindents \"{\" \"}\" ns t\n| (ns, binder_info.strict_implicit, t) := indent_bindents \"\u2983\" \"\u2984\" ns t\n| ([n], binder_info.inst_implicit, t) :=\n  if \"_\".is_prefix_of n.to_string\n    then indent_bindents \"[\" \"]\" none t\n    else indent_bindents \"[\" \"]\" [n] t\n| (ns, binder_info.inst_implicit, t) := indent_bindents \"[\" \"]\" ns t\n| (ns, binder_info.aux_decl, t) := indent_bindents \"(\" \")\" ns t\n\nprivate meta def partition_vars' (s : name_set) :\n  list expr \u2192 list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr)\n| [] as bs := pure (as.reverse, bs.reverse)\n| (x :: xs) as bs :=\ndo t \u2190 infer_type x,\n   if t.has_local_in s then partition_vars' xs as (x :: bs)\n     else partition_vars' xs (x :: as) bs\n\nprivate meta def partition_vars : tactic (list expr \u00d7 list expr) :=\ndo ls \u2190 local_context,\n   partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] []\n\n/--\nFormat the current goal as a stand-alone example. Useful for testing tactics\nor creating [minimal working examples](https://leanprover-community.github.io/mwe.html).\n\n* `extract_goal`: formats the statement as an `example` declaration\n* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration\n  called `my_decl`\n* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration\n\nExamples:\n\n```lean\nexample (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\nbegin\n  extract_goal,\n     -- prints:\n     -- example (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\n  extract_goal my_lemma\n     -- prints:\n     -- lemma my_lemma (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\nend\n\nexample {i j k x y z w p q r m n : \u2115} (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) (h\u2081 : k \u2264 p) (h\u2081 : p \u2264 q) : i \u2264 k :=\nbegin\n  extract_goal my_lemma,\n    -- prints:\n    -- lemma my_lemma {i j k x y z w p q r m n : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p)\n    --   (h\u2081 : p \u2264 q) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\n\n  extract_goal my_lemma with i j k\n    -- prints:\n    -- lemma my_lemma {p i j k : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\nend\n\nexample : true :=\nbegin\n  let n := 0,\n  have m : \u2115, admit,\n  have k : fin n, admit,\n  have : n + m + k.1 = 0, extract_goal,\n    -- prints:\n    -- example (m : \u2115)  : let n : \u2115 := 0 in \u2200 (k : fin n), n + m + k.val = 0 :=\n    -- begin\n    --   intros n k,\n    --   admit,\n    -- end\nend\n```\n\n-/\nmeta def extract_goal (print_use : parse $ tt <$ tk \"!\" <|> pure ff)\n  (n : parse ident?) (vs : parse (tk \"with\" *> ident*)?)\n  : tactic unit :=\ndo tgt \u2190 target,\n   solve_aux tgt $ do\n   { ((cxt\u2080,cxt\u2081,ls,tgt),_) \u2190 solve_aux tgt $ do\n       { vs.mmap clear_except,\n         ls \u2190 local_context,\n         ls \u2190 ls.mfilter $ succeeds \u2218 is_local_def,\n         n \u2190 revert_lst ls,\n         (c\u2080,c\u2081) \u2190 partition_vars,\n         tgt \u2190 target,\n         ls \u2190 intron' n,\n         pure (c\u2080,c\u2081,ls,tgt) },\n     is_prop \u2190 is_prop tgt,\n     let title := match n, is_prop with\n                  | none, _ := to_fmt \"example\"\n                  | (some n), tt := format!\"lemma {n}\"\n                  | (some n), ff := format!\"def {n}\"\n                  end,\n     cxt\u2080 \u2190 compact_decl cxt\u2080 >>= list.mmap format_binders,\n     cxt\u2081 \u2190 compact_decl cxt\u2081 >>= list.mmap format_binders,\n     stmt \u2190 pformat!\"{tgt} :=\",\n     let fmt :=\n       format.group $ format.nest 2 $\n         title ++ cxt\u2080.foldl (\u03bb acc x, acc ++ format.group (format.line ++ x)) \"\" ++\n         format.join (list.map (\u03bb x, format.line ++ x) cxt\u2081) ++ \" :\" ++\n         format.line ++ stmt,\n     trace $ fmt.to_string $ options.mk.set_nat `pp.width 80,\n     let var_names := format.intercalate \" \" $ ls.map (to_fmt \u2218 local_pp_name),\n     let call_intron := if ls.empty\n                     then to_fmt \"\"\n                     else format!\"\\n  intros {var_names},\",\n     trace!\"begin{call_intron}\\n  admit,\\nend\\n\" },\n   skip\n\nadd_tactic_doc\n{ name       := \"extract_goal\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.extract_goal],\n  tags       := [\"goal management\", \"proof extraction\", \"debugging\"] }\n\n/--\n`inhabit \u03b1` tries to derive a `nonempty \u03b1` instance and then upgrades this\nto an `inhabited \u03b1` instance.\nIf the target is a `Prop`, this is done constructively;\notherwise, it uses `classical.choice`.\n\n```lean\nexample (\u03b1) [nonempty \u03b1] : \u2203 a : \u03b1, true :=\nbegin\n  inhabit \u03b1,\n  existsi default,\n  trivial\nend\n```\n-/\nmeta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit :=\ndo ty \u2190 i_to_expr t,\n   nm \u2190 returnopt inst_name <|> get_unused_name `inst,\n   tgt \u2190 target,\n   tgt_is_prop \u2190 is_prop tgt,\n   if tgt_is_prop then do\n     decorate_error \"could not infer nonempty instance:\" $\n       mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply,\n     introI nm\n   else do\n     decorate_error \"could not infer nonempty instance:\" $\n      mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none,\n     resetI\n\nadd_tactic_doc\n{ name       := \"inhabit\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.inhabit],\n  tags       := [\"context management\", \"type class\"] }\n\n/-- `revert_deps n\u2081 n\u2082 ...` reverts all the hypotheses that depend on one of `n\u2081, n\u2082, ...`\nIt does not revert `n\u2081, n\u2082, ...` themselves (unless they depend on another `n\u1d62`). -/\nmeta def revert_deps (ns : parse ident*) : tactic unit :=\npropagate_tags $\n  ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `revert_after n` reverts all the hypotheses after `n`. -/\nmeta def revert_after (n : parse ident) : tactic unit :=\npropagate_tags $ get_local n >>= tactic.revert_after >> skip\n\nadd_tactic_doc\n{ name       := \"revert_after\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_after],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- Reverts all local constants on which the target depends (recursively). -/\nmeta def revert_target_deps : tactic unit :=\npropagate_tags $ tactic.revert_target_deps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_target_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_target_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `clear_value n\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`. -/\nmeta def clear_value (ns : parse ident*) : tactic unit :=\npropagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value\n\nadd_tactic_doc\n{ name       := \"clear_value\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_value],\n  tags       := [\"context management\"] }\n\n/--\n`generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of\nthe same type.\n\n`generalize' h : e = x` in addition registers the hypothesis `h : e = x`.\n\n`generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also\nsucceeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis\n`x` is not a local definition.\n-/\nmeta def generalize' (h : parse ident?) (_ : parse $ tk \":\") (p : parse generalize_arg_p) :\n  tactic unit :=\npropagate_tags $\ndo let (p, x) := p,\n   e \u2190 i_to_expr p,\n   some h \u2190 pure h | tactic.generalize' e x >> skip,\n   -- `h` is given, the regular implementation of `generalize` works.\n   tgt \u2190 target,\n   tgt' \u2190 do\n   { \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize e x >> target),\n     to_expr ``(\u03a0 x, %%e = x \u2192 %%(tgt'.binding_body.lift_vars 0 1)) }\n   <|> to_expr ``(\u03a0 x, %%e = x \u2192 %%tgt),\n   t \u2190 assert h tgt',\n   swap,\n   exact ``(%%t %%e rfl),\n   intro x,\n   intro h\n\nadd_tactic_doc\n{ name       := \"generalize'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize'],\n  tags       := [\"context management\"] }\n\n/--\nIf the expression `q` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.interactive.subst' q` substitutes `x` by `t` everywhere in the main goal and\nthen clears `q`.\nIf `q` is another local variable, then we find a local constant with type `q = t` or `t = q` and\nsubstitute `t` for `q`.\n\nLike `tactic.interactive.subst`, but fails with a nicer error message if the substituted variable is\na local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nmeta def subst' (q : parse texpr) : tactic unit := do\ni_to_expr q >>= tactic.subst' >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"subst'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.subst'],\n  tags       := [\"context management\"] }\n\nend interactive\nend tactic\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.07477004600052534, "lm_q1q2_score": 0.018981199168830423}}
{"text": "import data.list\nimport data.list.perm\nimport data.multiset.basic\n\nmk_iff_of_inductive_prop list.chain test.chain_iff\n\nmk_iff_of_inductive_prop false    test.false_iff\n\nmk_iff_of_inductive_prop true     test.true_iff\n\nmk_iff_of_inductive_prop nonempty test.non_empty_iff\n\nmk_iff_of_inductive_prop and      test.and_iff\n\nmk_iff_of_inductive_prop or       test.or_iff\n\nmk_iff_of_inductive_prop eq       test.eq_iff\n\nmk_iff_of_inductive_prop heq      test.heq_iff\n\nmk_iff_of_inductive_prop list.perm  test.perm_iff\n\nmk_iff_of_inductive_prop list.pairwise  test.pairwise_iff\n\ninductive test.is_true (p : Prop) : Prop\n| triviality : p \u2192 test.is_true\n\nmk_iff_of_inductive_prop test.is_true test.is_true_iff\n\n@[mk_iff] structure foo (m n : \u2115) : Prop :=\n(equal : m = n)\n(sum_eq_two : m + n = 2)\n\nexample (m n : \u2115) : foo m n \u2194 m = n \u2227 m + n = 2 := foo_iff m n\n\n@[mk_iff bar] structure foo2 (m n : \u2115) : Prop :=\n(equal : m = n)\n(sum_eq_two : m + n = 2)\n\nexample (m n : \u2115) : foo2 m n \u2194 m = n \u2227 m + n = 2 := bar m n\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/test/mk_iff_of_inductive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.04401864735472289, "lm_q1q2_score": 0.01893450444796928}}
{"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.Data.Options\n\n/- Basic support for auto bound implicit local names -/\n\nnamespace Lean.Elab\n\nregister_builtin_option autoBoundImplicitLocal : Bool := {\n    defValue := true\n    descr    := \"Unbound local variables in declaration headers become implicit arguments if they are a lower case or greek letter followed by numeric digits. For example, `def f (x : Vector \u03b1 n) : Vector \u03b1 n :=` automatically introduces the implicit variables {\u03b1 n}.\"\n  }\n\nprivate def isValidAutoBoundSuffix (s : String) : Bool :=\n  s.toSubstring.drop 1 |>.all fun c => c.isDigit || isSubScriptAlnum c || c == '_' || c == '\\''\n\n/-\nRemark: Issue #255 exposed a nasty interaction between macro scopes and auto-bound-implicit names.\n```\nlocal notation \"A\" => id x\ntheorem test : A = A := sorry\n```\nWe used to use `n.eraseMacroScopes` at `isValidAutoBoundImplicitName` and `isValidAutoBoundLevelName`.\nThus, in the example above, when `A` is expanded, a `x` with a fresh macro scope is created.\n`x`+macros-scope is not in scope and is a valid auto-bound implicit name after macro scopes are erased.\nSo, an auto-bound exception would be thrown, and `x`+macro-scope would be added as a new implicit.\nWhen, we try again, a `x` with a new macro scope is created and this process keeps repeating.\nTherefore, we do consider identifier with macro scopes anymore.\n-/\n\ndef isValidAutoBoundImplicitName (n : Name) : Bool :=\n  match n with\n  | Name.str Name.anonymous s _ => s.length > 0 && (isGreek s[0] || s[0].isLower) && isValidAutoBoundSuffix s\n  | _ => false\n\ndef isValidAutoBoundLevelName (n : Name) : Bool :=\n  match n with\n  | Name.str Name.anonymous s _ => s.length > 0 && s[0].isLower && isValidAutoBoundSuffix s\n  | _ => false\n\nend Lean.Elab\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/Elab/AutoBound.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.06954174113116343, "lm_q1q2_score": 0.018917060913501454}}
{"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.Elab.App\nimport Lean.Elab.BuiltinNotation\n\n/-! # Auxiliary elaboration functions: AKA custom elaborators -/\n\nnamespace Lean.Elab.Term\nopen Meta\n\nprivate def getMonadForIn (expectedType? : Option Expr) : TermElabM Expr := do\n    match expectedType? with\n    | none => throwError \"invalid 'for_in%' notation, expected type is not available\"\n    | some expectedType =>\n      match (\u2190 isTypeApp? expectedType) with\n      | some (m, _) => return m\n      | none => throwError \"invalid 'for_in%' notation, expected type is not of of the form `M \u03b1`{indentExpr expectedType}\"\n\nprivate def throwForInFailure (forInInstance : Expr) : TermElabM Expr :=\n  throwError \"failed to synthesize instance for 'for_in%' notation{indentExpr forInInstance}\"\n\n@[builtin_term_elab forInMacro] def elabForIn : TermElab :=  fun stx expectedType? => do\n  match stx with\n  | `(for_in% $col $init $body) =>\n      match (\u2190 isLocalIdent? col) with\n      | none   => elabTerm (\u2190 `(let col := $col; for_in% col $init $body)) expectedType?\n      | some colFVar =>\n        tryPostponeIfNoneOrMVar expectedType?\n        let m \u2190 getMonadForIn expectedType?\n        let colType \u2190 inferType colFVar\n        let elemType \u2190 mkFreshExprMVar (mkSort (mkLevelSucc (\u2190 mkFreshLevelMVar)))\n        let forInInstance \u2190 try\n          mkAppM ``ForIn #[m, colType, elemType]\n        catch _ =>\n          tryPostpone; throwError \"failed to construct 'ForIn' instance for collection{indentExpr colType}\\nand monad{indentExpr m}\"\n        match (\u2190 trySynthInstance forInInstance) with\n        | .some inst =>\n          let forInFn \u2190 mkConst ``forIn\n          elabAppArgs forInFn\n            (namedArgs := #[{ name := `m, val := Arg.expr m}, { name := `\u03b1, val := Arg.expr elemType }, { name := `self, val := Arg.expr inst }])\n            (args := #[Arg.stx col, Arg.stx init, Arg.stx body])\n            (expectedType? := expectedType?)\n            (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false)\n        | .undef    => tryPostpone; throwForInFailure forInInstance\n        | .none     => throwForInFailure forInInstance\n  | _ => throwUnsupportedSyntax\n\n@[builtin_term_elab forInMacro'] def elabForIn' : TermElab :=  fun stx expectedType? => do\n  match stx with\n  | `(for_in'% $col $init $body) =>\n      match (\u2190 isLocalIdent? col) with\n      | none   => elabTerm (\u2190 `(let col := $col; for_in'% col $init $body)) expectedType?\n      | some colFVar =>\n        tryPostponeIfNoneOrMVar expectedType?\n        let m \u2190 getMonadForIn expectedType?\n        let colType \u2190 inferType colFVar\n        let elemType \u2190 mkFreshExprMVar (mkSort (mkLevelSucc (\u2190 mkFreshLevelMVar)))\n        let forInInstance \u2190\n          try\n            let memType \u2190 mkFreshExprMVar (\u2190 mkAppM ``Membership #[elemType, colType])\n            mkAppM ``ForIn' #[m, colType, elemType, memType]\n          catch _ =>\n            tryPostpone; throwError \"failed to construct `ForIn'` instance for collection{indentExpr colType}\\nand monad{indentExpr m}\"\n        match (\u2190 trySynthInstance forInInstance) with\n        | .some inst  =>\n          let forInFn \u2190 mkConst ``forIn'\n          elabAppArgs forInFn\n            (namedArgs := #[{ name := `m, val := Arg.expr m}, { name := `\u03b1, val := Arg.expr elemType}, { name := `self, val := Arg.expr inst }])\n            (args := #[Arg.expr colFVar, Arg.stx init, Arg.stx body])\n            (expectedType? := expectedType?)\n            (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false)\n        | .undef    => tryPostpone; throwForInFailure forInInstance\n        | .none     => throwForInFailure forInInstance\n  | _ => throwUnsupportedSyntax\n\nnamespace Op\n/-!\n\nThe elaborator for `binop%`, `binop_lazy%`, and `unop%` terms.\n\nIt works as follows:\n\n1- Expand macros.\n2- Convert `Syntax` object corresponding to the `binop%` (`binop_lazy%` and `unop%`) term into a `Tree`.\n   The `toTree` method visits nested `binop%` (`binop_lazy%` and `unop%`) terms and parentheses.\n3- Synthesize pending metavariables without applying default instances and using the\n   `(mayPostpone := true)`.\n4- Tries to compute a maximal type for the tree computed at step 2.\n   We say a type \u03b1 is smaller than type \u03b2 if there is a (nondependent) coercion from \u03b1 to \u03b2.\n   We are currently ignoring the case we may have cycles in the coercion graph.\n   If there are \"uncomparable\" types \u03b1 and \u03b2 in the tree, we skip the next step.\n   We say two types are \"uncomparable\" if there isn't a coercion between them.\n   Note that two types may be \"uncomparable\" because some typing information may still be missing.\n5- We traverse the tree and inject coercions to the \"maximal\" type when needed.\n\nRecall that the coercions are expanded eagerly by the elaborator.\n\nProperties:\n\na) Given `n : Nat` and `i : Nat`, it can successfully elaborate `n + i` and `i + n`. Recall that Lean 3\n   fails on the former.\n\nb) The coercions are inserted in the \"leaves\" like in Lean 3.\n\nc) There are no coercions \"hidden\" inside instances, and we can elaborate\n```\naxiom Int.add_comm (i j : Int) : i + j = j + i\n\nexample (n : Nat) (i : Int) : n + i = i + n := by\n  rw [Int.add_comm]\n```\nRecall that the `rw` tactic used to fail because our old `binop%` elaborator would hide\ncoercions inside of a `HAdd` instance.\n\nRemarks:\n\nIn the new `binop%` and related elaborators the decision whether a coercion will be inserted or not\nis made at `binop%` elaboration time. This was not the case in the old elaborator.\nFor example, an instance, such as `HAdd Int ?m ?n`, could be created when executing\nthe `binop%` elaborator, and only resolved much later. We try to minimize this problem\nby synthesizing pending metavariables at step 3.\n\nFor types containing heterogeneous operators (e.g., matrix multiplication), step 4 will fail\nand we will skip coercion insertion. For example, `x : Matrix Real 5 4` and `y : Matrix Real 4 8`,\nthere is no coercion `Matrix Real 5 4` from `Matrix Real 4 8` and vice-versa, but\n`x * y` is elaborated successfully and has type `Matrix Real 5 8`.\n-/\n\nprivate inductive Tree where\n  /--\n  Leaf of the tree.\n  We store the `infoTrees` generated when elaborating `val`. These trees become\n  subtrees of the infotree nodes generated for `op` nodes.\n  -/\n  | term (ref : Syntax) (infoTrees : PersistentArray InfoTree) (val : Expr)\n  /--\n  `ref` is the original syntax that expanded into `binop%`.\n  -/\n  | binop (ref : Syntax) (lazy : Bool) (f : Expr) (lhs rhs : Tree)\n  /--\n  `ref` is the original syntax that expanded into `unop%`.\n  -/\n  | unop (ref : Syntax) (f : Expr) (arg : Tree)\n  /--\n  Used for assembling the info tree. We store this information\n  to make sure \"go to definition\" behaves similarly to notation defined without using `binop%` helper elaborator.\n  -/\n  | macroExpansion (macroName : Name) (stx stx' : Syntax) (nested : Tree)\n\n\nprivate partial def toTree (s : Syntax) : TermElabM Tree := do\n  /-\n  Remark: ew used to use `expandMacros` here, but this is a bad idiom\n  because we do not record the macro expansion information in the info tree.\n  We now manually expand the notation in the `go` function, and save\n  the macro declaration names in the `op` nodes.\n  -/\n  let result \u2190 go s\n  synthesizeSyntheticMVars (mayPostpone := true)\n  return result\nwhere\n  go (s : Syntax) := do\n    match s with\n    | `(binop% $f $lhs $rhs) => processBinOp (lazy := false) s f lhs rhs\n    | `(binop_lazy% $f $lhs $rhs) => processBinOp (lazy := true) s f lhs rhs\n    | `(unop% $f $arg) => processUnOp s f arg\n    | `(($e)) =>\n      if hasCDot e then\n        processLeaf s\n      else\n        go e\n    | _ =>\n      withRef s do\n        match (\u2190 liftMacroM <| expandMacroImpl? (\u2190 getEnv) s) with\n        | some (macroName, s?) =>\n          let s' \u2190 liftMacroM <| liftExcept s?\n          withPushMacroExpansionStack s s' do\n            return .macroExpansion macroName s s' (\u2190 go s')\n        | none => processLeaf s\n\n  processBinOp (ref : Syntax) (f lhs rhs : Syntax) (lazy : Bool) := do\n    let some f \u2190 resolveId? f | throwUnknownConstant f.getId\n    return .binop (lazy := lazy) ref f (\u2190 go lhs) (\u2190 go rhs)\n\n  processUnOp (ref : Syntax) (f arg : Syntax) := do\n    let some f \u2190 resolveId? f | throwUnknownConstant f.getId\n    return .unop ref f (\u2190 go arg)\n\n  processLeaf (s : Syntax) := do\n    let e \u2190 elabTerm s none\n    let info \u2190 getResetInfoTrees\n    return .term s info e\n\n-- Auxiliary function used at `analyze`\nprivate def hasCoe (fromType toType : Expr) : TermElabM Bool := do\n  if (\u2190 getEnv).contains ``CoeT then\n    withLocalDeclD `x fromType fun x => do\n    match \u2190 coerceSimple? x toType with\n    | .some _ => return true\n    | .none   => return false\n    | .undef  => return false -- TODO: should we do something smarter here?\n  else\n    return false\n\nprivate structure AnalyzeResult where\n  max?            : Option Expr := none\n  hasUncomparable : Bool := false -- `true` if there are two types `\u03b1` and `\u03b2` where we don't have coercions in any direction.\n\nprivate def isUnknow : Expr \u2192 Bool\n  | .mvar ..        => true\n  | .app f _        => isUnknow f\n  | .letE _ _ _ b _ => isUnknow b\n  | .mdata _ b      => isUnknow b\n  | _               => false\n\nprivate def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do\n  let max? \u2190\n    match expectedType? with\n    | none => pure none\n    | some expectedType =>\n      let expectedType \u2190 instantiateMVars expectedType\n      if isUnknow expectedType then pure none else pure (some expectedType)\n  (go t *> get).run' { max? }\nwhere\n   go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do\n     unless (\u2190 get).hasUncomparable do\n       match t with\n       | .macroExpansion _ _ _ nested => go nested\n       | .binop _ _ _ lhs rhs => go lhs; go rhs\n       | .unop _ _ arg => go arg\n       | .term _ _ val =>\n         let type \u2190 instantiateMVars (\u2190 inferType val)\n         unless isUnknow type do\n           match (\u2190 get).max? with\n           | none     => modify fun s => { s with max? := type }\n           | some max =>\n             unless (\u2190 withNewMCtxDepth <| isDefEqGuarded max type) do\n               if (\u2190 hasCoe type max) then\n                 return ()\n               else if (\u2190 hasCoe max type) then\n                 modify fun s => { s with max? := type }\n               else\n                 trace[Elab.binop] \"uncomparable types: {max}, {type}\"\n                 modify fun s => { s with hasUncomparable := true }\n\nprivate def mkBinOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr := do\n  elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false)\n\nprivate def mkUnOp (f : Expr) (arg : Expr) : TermElabM Expr := do\n  elabAppArgs f #[] #[Arg.expr arg] (expectedType? := none) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false)\n\nprivate def toExprCore (t : Tree) : TermElabM Expr := do\n  match t with\n  | .term _ trees e =>\n    modifyInfoState (fun s => { s with trees := s.trees ++ trees }); return e\n  | .binop ref lazy f lhs rhs =>\n    withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo .anonymous ref) do\n      let lhs \u2190 toExprCore lhs\n      let mut rhs \u2190 toExprCore rhs\n      if lazy then\n        rhs \u2190 mkFunUnit rhs\n      mkBinOp f lhs rhs\n  | .unop ref f arg =>\n    withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo .anonymous ref) do\n      mkUnOp f (\u2190 toExprCore arg)\n  | .macroExpansion macroName stx stx' nested =>\n    withRef stx <| withInfoContext' stx (mkInfo := mkTermInfo macroName stx) do\n      withMacroExpansion stx stx' do\n        toExprCore nested\n\n/--\n  Auxiliary function to decide whether we should coerce `f`'s argument to `maxType` or not.\n  - `f` is a binary operator.\n  - `lhs == true` (`lhs == false`) if are trying to coerce the left-argument (right-argument).\n  This function assumes `f` is a heterogeneous operator (e.g., `HAdd.hAdd`, `HMul.hMul`, etc).\n  It returns true IF\n  - `f` is a constant of the form `Cls.op` where `Cls` is a class name, and\n  - `maxType` is of the form `C ...` where `C` is a constant, and\n  - There are more than one default instance. That is, it assumes the class `Cls` for the heterogeneous operator `f`, and\n    always has the monomorphic instance. (e.g., for `HAdd`, we have `instance [Add \u03b1] : HAdd \u03b1 \u03b1 \u03b1`), and\n  - If `lhs == true`, then there is a default instance of the form `Cls _ (C ..) _`, and\n  - If `lhs == false`, then there is a default instance of the form `Cls (C ..) _ _`.\n\n  The motivation is to support default instances such as\n  ```\n  @[default_instance high]\n  instance [Mul \u03b1] : HMul \u03b1 (Array \u03b1) (Array \u03b1) where\n    hMul a as := as.map (a * \u00b7)\n\n  #eval 2 * #[3, 4, 5]\n  ```\n  If the type of an argument is unknown we should not coerce it to `maxType` because it would prevent\n  the default instance above from being even tried.\n-/\nprivate def hasHeterogeneousDefaultInstances (f : Expr) (maxType : Expr) (lhs : Bool) : MetaM Bool := do\n  let .const fName .. := f | return false\n  let .const typeName .. := maxType.getAppFn | return false\n  let className := fName.getPrefix\n  let defInstances \u2190 getDefaultInstances className\n  if defInstances.length \u2264 1 then return false\n  for (instName, _) in defInstances do\n    if let .app (.app (.app _heteroClass lhsType) rhsType) _resultType :=\n        (\u2190 getConstInfo instName).type.getForallBody then\n      if  lhs && rhsType.isAppOf typeName then return true\n      if !lhs && lhsType.isAppOf typeName then return true\n  return false\n\n/--\n  Return `true` if polymorphic function `f` has a homogenous instance of `maxType`.\n  The coercions to `maxType` only makes sense if such instance exists.\n\n  For example, suppose `maxType` is `Int`, and `f` is `HPow.hPow`. Then,\n  adding coercions to `maxType` only make sense if we have an instance `HPow Int Int Int`.\n-/\nprivate def hasHomogeneousInstance (f : Expr) (maxType : Expr) : MetaM Bool := do\n  let .const fName .. := f | return false\n  let className := fName.getPrefix\n  try\n    let inst \u2190 mkAppM className #[maxType, maxType, maxType]\n    return (\u2190 trySynthInstance inst) matches .some _\n  catch _ =>\n    return false\n\nmutual\n  /--\n    Try to coerce elements in the `t` to `maxType` when needed.\n    If the type of an element in `t` is unknown we only coerce it to `maxType` if `maxType` does not have heterogeneous\n    default instances. This extra check is approximated by `hasHeterogeneousDefaultInstances`.\n\n    Remark: If `maxType` does not implement heterogeneous default instances, we do want to assign unknown types `?m` to\n    `maxType` because it produces better type information propagation. Our test suite has many tests that would break if\n    we don't do this. For example, consider the term\n    ```\n    eq_of_isEqvAux a b hsz (i+1) (Nat.succ_le_of_lt h) heqv.2\n    ```\n    `Nat.succ_le_of_lt h` type depends on `i+1`, but `i+1` only reduces to `Nat.succ i` if we know that `1` is a `Nat`.\n    There are several other examples like that in our test suite, and one can find them by just replacing the\n    `\u2190 hasHeterogeneousDefaultInstances f maxType lhs` test with `true`\n\n\n    Remark: if `hasHeterogeneousDefaultInstances` implementation is not good enough we should refine it in the future.\n  -/\n  private partial def applyCoe (t : Tree) (maxType : Expr) (isPred : Bool) : TermElabM Tree := do\n    go t none false isPred\n  where\n    go (t : Tree) (f? : Option Expr) (lhs : Bool) (isPred : Bool) : TermElabM Tree := do\n      match t with\n      | .binop ref lazy f lhs rhs =>\n        /-\n          We only keep applying coercions to `maxType` if `f` is predicate or\n          `f` has a homogenous instance with `maxType`. See `hasHomogeneousInstance` for additional details.\n\n          Remark: We assume `binrel%` elaborator is only used with homogenous predicates.\n        -/\n        if (\u2190 pure isPred <||> hasHomogeneousInstance f maxType) then\n          return .binop ref lazy f (\u2190 go lhs f true false) (\u2190 go rhs f false false)\n        else\n          let r \u2190 withRef ref do\n            mkBinOp f (\u2190 toExpr lhs none) (\u2190 toExpr rhs none)\n          let infoTrees \u2190 getResetInfoTrees\n          return .term ref infoTrees r\n      | .unop ref f arg =>\n        return .unop ref f (\u2190 go arg none false false)\n      | .term ref trees e =>\n        let type \u2190 instantiateMVars (\u2190 inferType e)\n        trace[Elab.binop] \"visiting {e} : {type} =?= {maxType}\"\n        if isUnknow type then\n          if let some f := f? then\n            if (\u2190 hasHeterogeneousDefaultInstances f maxType lhs) then\n              -- See comment at `hasHeterogeneousDefaultInstances`\n              return t\n        if (\u2190 isDefEqGuarded maxType type) then\n          return t\n        else\n          trace[Elab.binop] \"added coercion: {e} : {type} => {maxType}\"\n          withRef ref <| return .term ref trees (\u2190 mkCoe maxType e)\n      | .macroExpansion macroName stx stx' nested =>\n        withRef stx <| withPushMacroExpansionStack stx stx' do\n          return .macroExpansion macroName stx stx' (\u2190 go nested f? lhs isPred)\n\n  private partial def toExpr (tree : Tree) (expectedType? : Option Expr) : TermElabM Expr := do\n    let r \u2190 analyze tree expectedType?\n    trace[Elab.binop] \"hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}\"\n    if r.hasUncomparable || r.max?.isNone then\n      let result \u2190 toExprCore tree\n      ensureHasType expectedType? result\n    else\n      let result \u2190 toExprCore (\u2190 applyCoe tree r.max?.get! (isPred := false))\n      trace[Elab.binop] \"result: {result}\"\n      ensureHasType expectedType? result\n\nend\n\ndef elabOp : TermElab := fun stx expectedType? => do\n  toExpr (\u2190 toTree stx) expectedType?\n\n@[builtin_term_elab binop]\ndef elabBinOp : TermElab := elabOp\n\n@[builtin_term_elab binop_lazy]\ndef elabBinOpLazy : TermElab := elabOp\n\n@[builtin_term_elab unop]\ndef elabUnOp : TermElab := elabOp\n\n/--\n  Elaboration functionf for `binrel%` and `binrel_no_prop%` notations.\n  We use the infrastructure for `binop%` to make sure we propagate information between the left and right hand sides\n  of a binary relation.\n\n  Recall that the `binrel_no_prop%` notation is used for relations such as `==` which do not support `Prop`, but\n  we still want to be able to write `(5 > 2) == (2 > 1)`.\n-/\ndef elabBinRelCore (noProp : Bool) (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=  do\n  match (\u2190 resolveId? stx[1]) with\n  | some f => withSynthesizeLight do\n    /-\n    We used to use `withSynthesize (mayPostpone := true)` here instead of `withSynthesizeLight` here.\n    Recall that `withSynthesizeLight` is equivalent to `withSynthesize (mayPostpone := true) (synthesizeDefault := false)`.\n    It seems too much to apply default instances at binary relations. For example, we cannot elaborate\n    ```\n    def as : List Int := [-1, 2, 0, -3, 4]\n    #eval as.map fun a => ite (a \u2265 0) [a] []\n    ```\n    The problem is that when elaborating `a \u2265 0` we don't know yet that `a` is an `Int`.\n    Then, by applying default instances, we apply the default instance to `0` that forces it to become an `Int`,\n    and Lean infers that `a` has type `Nat`.\n    Then, later we get a type error because `as` is `List Int` instead of `List Nat`.\n    This behavior is quite counterintuitive since if we avoid this elaborator by writing\n    ```\n    def as : List Int := [-1, 2, 0, -3, 4]\n    #eval as.map fun a => ite (GE.ge a 0) [a] []\n    ```\n    everything works.\n    However, there is a drawback of using `withSynthesizeLight` instead of `withSynthesize (mayPostpone := true)`.\n    The following cannot be elaborated\n    ```\n    have : (0 == 1) = false := rfl\n    ```\n    We get a type error at `rfl`. `0 == 1` only reduces to `false` after we have applied the default instances that force\n    the numeral to be `Nat`. We claim this is defensible behavior because the same happens if we do not use this elaborator.\n    ```\n    have : (BEq.beq 0 1) = false := rfl\n    ```\n    We can improve this failure in the future by applying default instances before reporting a type mismatch.\n    -/\n    let lhs \u2190 withRef stx[2] <| toTree stx[2]\n    let rhs \u2190 withRef stx[3] <| toTree stx[3]\n    let tree := .binop (lazy := false) stx f lhs rhs\n    let r \u2190 analyze tree none\n    trace[Elab.binrel] \"hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}\"\n    if r.hasUncomparable || r.max?.isNone then\n      -- Use default elaboration strategy + `toBoolIfNecessary`\n      let lhs \u2190 toExprCore lhs\n      let rhs \u2190 toExprCore rhs\n      let lhs \u2190 toBoolIfNecessary lhs\n      let rhs \u2190 toBoolIfNecessary rhs\n      let lhsType \u2190 inferType lhs\n      let rhs \u2190 ensureHasType lhsType rhs\n      elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false)\n    else\n      let mut maxType := r.max?.get!\n      /- If `noProp == true` and `maxType` is `Prop`, then set `maxType := Bool`. `See toBoolIfNecessary` -/\n      if noProp then\n        if (\u2190 withNewMCtxDepth <| isDefEq maxType (mkSort levelZero)) then\n          maxType := Lean.mkConst ``Bool\n      let result \u2190 toExprCore (\u2190 applyCoe tree maxType (isPred := true))\n      trace[Elab.binrel] \"result: {result}\"\n      return result\n  | none   => throwUnknownConstant stx[1].getId\nwhere\n  /-- If `noProp == true` and `e` has type `Prop`, then coerce it to `Bool`. -/\n  toBoolIfNecessary (e : Expr) : TermElabM Expr := do\n    if noProp then\n      -- We use `withNewMCtxDepth` to make sure metavariables are not assigned\n      if (\u2190 withNewMCtxDepth <| isDefEq (\u2190 inferType e) (mkSort levelZero)) then\n        return (\u2190 ensureHasType (Lean.mkConst ``Bool) e)\n    return e\n\n@[builtin_term_elab binrel] def elabBinRel : TermElab := elabBinRelCore false\n\n@[builtin_term_elab binrel_no_prop] def elabBinRelNoProp : TermElab := elabBinRelCore true\n\n@[builtin_term_elab defaultOrOfNonempty]\ndef elabDefaultOrNonempty : TermElab :=  fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  match expectedType? with\n  | none => throwError \"invalid 'default_or_ofNonempty%', expected type is not known\"\n  | some expectedType =>\n    try\n      mkDefault expectedType\n    catch ex => try\n      mkOfNonempty expectedType\n    catch _ =>\n      if stx[1].isNone then\n        throw ex\n      else\n        -- It is in the context of an `unsafe` constant. We can use sorry instead.\n        -- Another option is to make a recursive application since it is unsafe.\n        mkSorry expectedType false\n\nbuiltin_initialize\n  registerTraceClass `Elab.binop\n  registerTraceClass `Elab.binrel\n\nend Op\n\nend Lean.Elab.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/Lean/Elab/Extra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.06278921517368556, "lm_q1q2_score": 0.018883578868676254}}
{"text": "\nimport tactic.default\n\nuniverses u v\n-- #check @option.elim\n-- def option.elim {\u03b1 \u03b2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) : option \u03b1 \u2192 \u03b2\n-- | none := x\n-- | (some y) := f y\n-- #exit\nnamespace list\n\ndef mfilter_map {m} [applicative m] {\u03b1 \u03b2} (f : \u03b1 \u2192 m (option \u03b2)) : list \u03b1 \u2192 m (list.{v} \u03b2)\n| [] := pure []\n| (x :: xs) :=\n  (\u03bb a, option.elim a id (::)) <$> f x <*> mfilter_map xs\n\ndef mfilter_map' {m} [applicative m] [alternative m] {\u03b1 \u03b2} (f : \u03b1 \u2192 m \u03b2) : list \u03b1 \u2192 m (list.{v} \u03b2)\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 \u00d7 expr)) :=\ndo let hyp_name : expr \u2192 name :=\n     if use_unique_names then expr.local_uniq_name else expr.local_pp_name,\n   ctx \u2190 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 (\u03bb 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 (\u03bb h, \u00ac ctx_names.contains h),\n     when \u00ac 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 $ \u03bb h,\n       (renames.find $ hyp_name h).get_or_else h.local_pp_name,\n   revert_lst ctx_suffix,\n   -- trace_state,\n   xs \u2190 intro_lst new_names,\n   xs' \u2190 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 \u2192 tactic unit) : tactic unit := do\nls \u2190 local_context,\npat \u2190 pexpr_to_pattern pat,\nls.mfirst $ \u03bb h, do\n  t \u2190 infer_type h,\n  match_pattern pat t,\n  f h\n\nmeta def find_all_hyps (pat : pexpr) (f : expr \u2192 tactic unit) : tactic unit := do\nls \u2190 local_context,\npat \u2190 pexpr_to_pattern pat,\nls.mmap' $ \u03bb h, try $ do\n  t \u2190 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 \u2190 local_context,\npat \u2190 pexpr_to_pattern pat,\nls.mfirst $ \u03bb h, do\n  t \u2190 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 \u2190 local_context,\npat \u2190 pexpr_to_pattern pat,\nls.reverse.mmap' (\u03bb h,\n  -- trace \u03c3,\n  -- let h := h.instantiate_locals $ list.reverse \u03c3,\n  try_or_report_error $ do {\n    t \u2190 infer_type h,\n    match_pattern pat t,\n    -- trace!\"{h} : {t}\",\n    n \u2190 tactic.revert h,\n    intro id,\n    intron $ n-1,\n    -- xs \u2190 rename_many' (native.rb_map.of_list [(h.local_uniq_name, id)]) tt tt,\n    tac,\n    h' \u2190 get_local id,\n    n \u2190 tactic.revert h',\n    intro h.local_pp_name,\n    intron $ n-1,\n    skip }),\nskip\n\nmeta def match_le_or_lt : expr \u2192 option (expr \u00d7 expr)\n| `(%%x < %%y) := pure (x, y)\n| `(%%x \u2264 %%y) := pure (x, y)\n| `(%%x > %%y) := pure (y, x)\n| `(%%x \u2265 %%y) := pure (y, x)\n| _ := none\n\nmeta def match_le : expr \u2192 option (expr \u00d7 expr)\n| `(%%x \u2264 %%y) := pure (x, y)\n| `(%%x \u2265 %%y) := pure (y, x)\n| _ := none\n\nmeta def match_lt : expr \u2192 option (expr \u00d7 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\u27e8 \u03bb e, match e with\n      | edge.lt := \"lt\"\n      | edge.le := \"le\"\n      end \u27e9\n\nmeta instance edge.has_to_format : has_to_format edge :=\n\u27e8 \u03bb e, to_fmt $ to_string e \u27e9\n\nmeta instance rb_lmap.has_to_format {\u03b1 \u03b2} [has_to_tactic_format \u03b1] [has_to_tactic_format \u03b2] : has_to_tactic_format (native.rb_lmap \u03b1 \u03b2) :=\nby delta native.rb_lmap; apply_instance\n\nopen native\n\nmeta def graph := (native.rb_lmap expr (expr \u00d7 edge \u00d7 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 \u2192 expr \u2192 expr \u2192 tactic expr\n| e x h := do\n  x \u2190 instantiate_mvars x,\n  -- trace!\"visit {x}, going to {v}\",\n  vs \u2190 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 $ \u03bb \u27e8h',e',y\u27e9, do\n      -- trace!\"try: {x}, {y}\",\n      (e,h) \u2190 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 $ \u03bb r, do\n  h \u2190 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 {\u03b1} {R : \u03b1 \u2192 \u03b1 \u2192 Prop} {x x' y' y : \u03b1} (h\u2080 : x = x') (h\u2081 : R x' y') (h\u2082 : y' = y) :\n  R x y := by subst_vars; exact h\u2081\n\n-- lemma t_of_eq_of_lt_of_eq {\u03b1} [has_lt \u03b1] {x x' y' y : \u03b1} (h\u2080 : x = x') (h\u2081 : x' < y') (h\u2082 : y' = y) :\n--   x < y := by subst_vars; exact h\u2081\n\nmeta def chain_trans : tactic unit := do\ntgt \u2190 target,\n(x, y) \u2190 match_le_or_lt tgt,\n\u03b1 \u2190 infer_type x,\ns \u2190 cc_state.mk_using_hs,\nls \u2190 local_context >>= list.mfilter_map'\n  (\u03bb h, do t \u2190 infer_type h,\n           do { (e, x, y) \u2190 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 \u2190 s.eqv_proof x' x,\n                y_pr \u2190 s.eqv_proof y y',\n                h' \u2190 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 \u03b1,\n                pure [(h', e, x', y')] }),\n -- <|>\n --           do { (x, y) \u2190 match_eq t,\n --                infer_type x >>= is_def_eq \u03b1,\n --                h\u2080 \u2190 mk_eq_symm h >>= mk_app ``le_of_eq \u2218 list.ret,\n --                h\u2081 \u2190 mk_app ``le_of_eq [h],\n --                pure [(h\u2080, edge.le, y, x), (h\u2081, edge.le, x, y)] }),\nlet m := list.foldl  (\u03bb (m : graph) (e : _ \u00d7 _ \u00d7 _ \u00d7 _),\n  let \u27e8pr,e,x,y\u27e9 := e in\n  m.insert x (pr,e,y)) (native.rb_lmap.mk expr (expr \u00d7 edge \u00d7 expr)) ls.join,\nx \u2190 whnf x,\ny \u2190 whnf y,\npr \u2190 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 \u2190 to_expr x,\ny \u2190 to_expr y,\n\u03b1 \u2190 infer_type x,\ninst \u2190 mk_app ``linear_order [\u03b1] >>= mk_instance,\nh' \u2190 mk_mapp ``cmp_compares [\u03b1, inst, x, y] >>= note hyp none,\n\ne \u2190 mk_app ``cmp [x, y],\nn \u2190 revert_kdependencies e,\nx \u2190 get_unused_name,\ntactic.generalize e x,\n\nh \u2190 tactic.intro1,\ns \u2190 simp_lemmas.mk.add_simp ``ordering.compares,\nin_tag \u2190 get_main_tag,\nfocus1 $ do\n  hs \u2190 cases_core h,\n  set_cases_tags in_tag $ cases_postprocess hs,\n  gs \u2190 get_goals,\n  gs \u2190 (gs.zip hs).mmap $ \u03bb \u27e8g,h,_,\u03c3\u27e9, 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 : \u2124} (h : x \u2264 y) (h : x < y) : true :=\nbegin\n  find_hyp hh := x \u2264 _ then { replace hh : x = y, admit },\n  trivial\nend\n\nexample {x y z w u v : \u2115} {a b : \u2124} (h\u2080 : x \u2264 y) (h\u2081 : y < z) (h : y < u) (h\u2082 : z < w) (h\u2083 : w = u) (h\u2084 : u < v) : x \u2264 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 \u2192 TypeDecl\n   | gArr: \u2115 \u2192 TypeDecl \u2192 TypeDecl\n   | gStruct  (name: string) (fields: finset string)\n              (vals: \u2200 s \u2208 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 \u27e8\u27e9 }},\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 (\u2200 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 := \u27e8gInt\u27e9\n\n  inductive PrimType: TypeDecl \u2192 Type\n   | pInt:  \u2124 \u2192 PrimType gInt\n   | pStr:  string \u2192 PrimType gStr\n   | pErr:  string \u2192 PrimType gErr\n   | pBool: bool \u2192 PrimType gBool\n   | pPtr (t: TypeDecl): \u2124 \u2192 PrimType (gPtr t)\n   | pArr (t: TypeDecl) (n:\u2115): (\u2200 s: fin n, PrimType t)\n                               \u2192 PrimType (gArr n t)\n   | pStruct  (name: string) (fields: finset string)\n              (valtypes: \u2200 s \u2208 fields, TypeDecl)\n              (vals: \u2200 s \u2208 fields, PrimType (valtypes s H))\n              : PrimType (@gStruct name fields valtypes)\n  open PrimType\n  instance : \u2200 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 \u27e8\u27e9 }},\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 (\u2200 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 (\u2200 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: \u2200 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 (\u03bb _, inh t)\n   | (@gStruct  name fs vs) := @pStruct _ _ _\n      (\u03bb 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: \u2200 t, inhabited (PrimType t):= \u03bb t, \u27e8inh t\u27e9\n\n  @[derive decidable_eq]\n  structure Ptr (t: TypeDecl) := (val: \u2124)\n  @[derive decidable_eq]\n  structure Arr (n: \u2115) (t: TypeDecl) := (vals: (\u2200 s: fin n, PrimType t))\n\n  structure Struct (name: string) (fields: finset string)\n                         (valtypes: \u2200 s \u2208 fields, TypeDecl)\n                          :=\n    (vals: \u2200 s \u2208 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 \u2192 Type\n      | gStr    := string\n      | gErr    := string\n      | gInt    := \u2124\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: \u2200 t, (PrimType t) \u2192 (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) :=  \u27e8xs\u27e9\n\n  @[simp]\n  def from_td: \u2200 t, (type_dict t) \u2192 (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: \u2200 t:TypeDecl, equiv (PrimType t) (type_dict t) := \u03bb t,\n  { to_fun    := to_td t,\n    inv_fun   := from_td t,\n    left_inv  := by {rintro \u27e8n\u27e9; 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 \u03b2 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 \u2190 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 >>= \u03bb 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 : \u2200 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:\u2115) : option (fin n) :=\n    if h: i < n then some \u27e8i,h\u27e9 else none\n\n  def shrink' (f:finset string) (h1: f.nonempty) (ts : \u2200 s \u2208 f, TypeDecl):\n        \u2200 s \u2208 (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 : \u2200 s \u2208 f, TypeDecl)\n              (vals: \u2200 s \u2208 f, PrimType (ts s H))\n              : (\u03a3 (f': finset string) (ts': \u2200 s \u2208 f', TypeDecl),\n                  \u2200 s \u2208 f', PrimType (ts' s H)) :=\n    if h0: f = \u2205 then \u27e8f, ts, \u03bb a b, inh (ts a b)\u27e9\n    else\n      have h1: f.nonempty := finset.nonempty_of_ne_empty h0,\n      have h2: \u2203 a, a \u2208 f.min := finset.min_of_nonempty h1,\n      have mxmem: f.min' h1 \u2208 f := finset.min'_mem f h1,\n      have mxtyp: TypeDecl := ts (f.min' h1) mxmem,\n\n      have newvals: \u2200 s \u2208 (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      \u27e8f.erase (f.min' h1), shrink' f h1 ts, newvals\u27e9\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: \u2200 s \u2208 f, TypeDecl)\n                (v : \u2200 s \u2208 f, PrimType (ts s H))\n                : \u03a3(fields: finset string) (typs:\u2200 s \u2208 fields, TypeDecl ),\n                  \u2200 s \u2208 fields, PrimType (typs s H) :=\n      \u27e8insert k f, \u03bb 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 \u2208 f\n            simp only [h, false_or] at mem, -- rule out poss. of s=k with \u00ach\n            exact mem end\n        , \u03bb 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 \u2208 f\n        simp only [h, false_or] at mem, -- rule out poss. of s=k with \u00ach\n          have Q : (dite (s = k) (\u03bb (h : s = k), t) (\u03bb (h : \u00acs = k), ts s mem)\n                    = ts s _), by { simp [h]},\n        rw Q, exact v s mem\n       end\u27e9\n\n  def add_key: \u03a0 (s) (t), PrimType t \u2192 string\n              \u2192 (\u03a3 f v, Struct s f v) \u2192 (\u03a3 f v, Struct s f v)\n      | s t pt key \u27e8f', ts', \u27e8vs'\u27e9\u27e9  :=\n    match add_key' key t pt f' ts' vs' with\n      | \u27e8f, ts, vs\u27e9 := \u27e8f, ts, \u27e8vs\u27e9\u27e9\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: \u03a0(s) , list (string \u00d7 (\u03a3 t, PrimType t))\n                          \u2192 \u03a3 (f) (v), Struct s f v\n   | s  []        := \u27e8\u2205, (\u03bb _ _, gBool), \u27e8\u03bb _ _, pBool ff\u27e9\u27e9 -- impossible\n   | n ((k,\u27e8t,v\u27e9)::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 \u2192 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 := \u27e8str_typeddecl\u27e9\n  instance: has_repr      TypeDecl := \u27e8str_typeddecl\u27e9\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: \u2200 t, PrimType t \u2192 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: \u03a0{n} {t}, \u2115 \u2192 (fin n \u2192 PrimType t) \u2192 string\n   | _ _ 0 _ := \"\"\n   | n t (succ i) a := (to_fin n i).elim \"\" (\u03bb x, str_ptype t $ a x)\n                        ++ str_arr i a\n with str_fields: \u03a0(f:finset string) (ts: (\u2200 s \u2208 f, TypeDecl)),\n               (\u2200 s \u2208 f, PrimType (ts s H))  \u2192 string\n  | f ts v :=\n      begin\n      have e: decidable (f = \u2205) := finset.has_decidable_eq f \u2205,\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                 | \u27e8a,b,c\u27e9 := 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 :\u2200 t,  has_to_string (PrimType t):= \u03bb t, \u27e8str_ptype t\u27e9\n  meta instance :\u2200 t,  has_to_string (Ptr t):=\n    \u03bb t, \u27e8\u03bb \u27e8z\u27e9, str_ptype (gPtr t) (pPtr t z)\u27e9\n  meta instance :\u2200 n t,  has_to_string (Arr n t):=\n    \u03bb n t, \u27e8\u03bb \u27e8z\u27e9, str_ptype (gArr n t) (pArr t n z)\u27e9\n\n  meta instance: \u03a0(s) (f) (v), has_repr (Struct s f v)\n    | s f v := \u27e8str_gstruct s f v\u27e9.\n  meta instance: \u03a0(s) (f) (v), has_to_string (Struct s f v)\n    | s f v := \u27e8str_gstruct s f v\u27e9\n\n meta instance type_dict_to_string: \u03a0(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 \u2208 x.fieldlist \u2192 key \u2208 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 : \u03a0 {\u03b1: Type} (l : list \u03b1) (n),\n--                       n < l.length \u2192 psigma (\u03bb a:\u03b1, a \u2208 l)\n--    | _ []       n     h := absurd h (nat.not_lt_zero n)\n--    | _ (a :: l) 0     h := \u27e8a, by {simp}\u27e9\n--    | _ (a :: l) (n+1) h :=\n--       match (nth_le_mem l n (nat.le_of_succ_le_succ h)) with\n--             | \u27e8q, r\u27e9 := \u27e8q, list.mem_cons_of_mem a r\u27e9\n--       end\n\n--   lemma ltsucc : \u2200 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:\u2115} (x: GoStruct name)\n--                      (H: n < x.len) : psigma (\u03bb f, f \u2208 x.fields) := begin\n--     have z := nth_le_mem x.fieldlist n\n--                                     (by {rw fl_len_eq x, exact H}),\n--     exact \u27e8z.1, fl_mem z.2\u27e9\n--   end\n\n--   /-\n--    - Helper function from GoStruct.structvals\n--    -/\n--   def structvals': \u03a0 {n:\u2115} {s: string} {x:GoStruct s},\n--                     n < x.len \u2192 list (string \u00d7 GoPrimType)\n--     |  0 _  _ _  := []\n--     |  (n+1) _ x h := match x.index h with\n--                           | \u27e8u,v \u27e9 :=  (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 \u00d7 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 : \u03a0(\u03b1: GoTypeDecl) {s: string},\n--       option (GoStruct s) \u2192 string \u2192 option (type_dict \u03b1)\n--     | _ _ none                          _     := none\n--     | \u03b1 _ (some s) field := GoStruct.get s field >>=\n--                               \u03bbx, as_type (x.to_gotype.2) \u03b1\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": "import Lean\n\nopen Lean Elab Tactic\n\nsyntax \"Foo\" (ident <|> num) : tactic\n\nelab_rules : tactic \n  | `(tactic| Foo $x:num) => \n    logInfo \"num\"\n\nmacro_rules \n  | `(tactic| Foo $x:ident) => `(tactic| trace \"ident\")\n\nexample : True := by \n  Foo x -- should not fail\n  trivial \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/macroElabRulesIssue1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798741512455283, "lm_q2_score": 0.07585817323116974, "lm_q1q2_score": 0.01881187229566833}}
{"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 (\u03b1 : Type)\n  | done (pos : \u2115) (result : \u03b1) : ParseResult\n  | fail (pos : \u2115) (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 (\u03b1 : Type) :=\n  \u2200 (input : CharBuffer) (start : \u2115), ParseResult \u03b1\n#align parser Parser\n\nnamespace Parser\n\nvariable {\u03b1 \u03b2 \u03b3 : Type}\n\nprotected def bind (p : Parser \u03b1) (f : \u03b1 \u2192 Parser \u03b2) : Parser \u03b2 := 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 : \u03b1) : Parser \u03b1 := fun input pos => ParseResult.done Pos a\n#align parser.pure Parser.pure\n\nprivate theorem parser.id_map (p : Parser \u03b1) : 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 \u03b1) (q : \u03b1 \u2192 Parser \u03b2) (r : \u03b2 \u2192 Parser \u03b3) :\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 \u03b1 := 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 \u03b1 := fun _ pos => ParseResult.fail Pos Dlist.empty\n#align parser.failure Parser.failure\n\nprotected def orelse (p q : Parser \u03b1) : Parser \u03b1 := fun input pos =>\n  match p input Pos with\n  | ParseResult.fail pos\u2081 expected\u2081 =>\n    if pos\u2081 \u2260 Pos then ParseResult.fail pos\u2081 expected\u2081\n    else\n      match q input Pos with\n      | ParseResult.fail pos\u2082 expected\u2082 =>\n        if pos\u2081 < pos\u2082 then ParseResult.fail pos\u2081 expected\u2081\n        else\n          if pos\u2082 < pos\u2081 then ParseResult.fail pos\u2082 expected\u2082\n          else-- pos\u2081 = pos\u2082\n              ParseResult.fail\n              pos\u2081 (expected\u2081 ++ expected\u2082)\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 \u03b1) :=\n  \u27e8Parser.failure\u27e9\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorateErrors (msgs : Thunk (List String)) (p : Parser \u03b1) : Parser \u03b1 := 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 \u03b1) : Parser \u03b1 :=\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 \u27e8Pos, h\u27e9\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 \u2192 Prop) [DecidablePred p] : Parser Char := fun input pos =>\n  if h : Pos < input.size then\n    let c := input.read \u27e8Pos, h\u27e9\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 (\u00b7 = 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 \u2190 cs\n      return c) <|\n    sat (\u00b7 \u2208 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 \u2115 := 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 \"<end-of-file>\" do\n    let rem \u2190 remaining\n    guard <| rem = 0\n#align parser.eof Parser.eof\n\ndef foldrCore (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (p : Parser \u03b1) (b : \u03b2) : \u2200 reps : \u2115, Parser \u03b2\n  | 0 => failure\n  | reps + 1 =>\n    (do\n        let x \u2190 p\n        let xs \u2190 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (p : Parser \u03b1) (b : \u03b2) : Parser \u03b2 := fun input pos =>\n  foldrCore f p b (input.size - Pos + 1) input Pos\n#align parser.foldr Parser.foldr\n\ndef foldlCore (f : \u03b1 \u2192 \u03b2 \u2192 \u03b1) : \u2200 (a : \u03b1) (p : Parser \u03b2) (reps : \u2115), Parser \u03b1\n  | a, p, 0 => failure\n  | a, p, reps + 1 =>\n    (do\n        let x \u2190 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b1) (a : \u03b1) (p : Parser \u03b2) : Parser \u03b1 := 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 \u03b1) : Parser (List \u03b1) :=\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 \u03b1) : 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 \u03b1) : Parser (List \u03b1) :=\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 \u03b1) : Parser (List \u03b1) :=\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 \u03b1) : Parser (List \u03b1) :=\n  sepBy1 sep p <|> return []\n#align parser.sep_by Parser.sepBy\n\ndef fixCore (F : Parser \u03b1 \u2192 Parser \u03b1) : \u2200 max_depth : \u2115, Parser \u03b1\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 \"<digit>\" do\n    let c \u2190 sat fun c => '0' \u2264 c \u2227 c \u2264 '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 \"<natural>\" do\n    let digits \u2190 many1 digit\n    pure <|\n        Prod.fst <|\n          digits (fun digit \u27e8Sum, magnitude\u27e9 => \u27e8Sum + digit * magnitude, magnitude * 10\u27e9) \u27e80, 1\u27e9\n#align parser.nat Parser.nat\n\n/-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/\ndef fix (F : Parser \u03b1 \u2192 Parser \u03b1) : Parser \u03b1 := fun input pos =>\n  fixCore F (input.size - Pos + 1) input Pos\n#align parser.fix Parser.fix\n\nprivate def make_monospaced : Char \u2192 Char\n  | '\\n' => ' '\n  | '\\t' => ' '\n  | '\\x0d' => ' '\n  | c => c\n#align parser.make_monospaced parser.make_monospaced\n\ndef mkErrorMsg (input : CharBuffer) (pos : \u2115) (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 \u03b1) (input : CharBuffer) : Sum String \u03b1 :=\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 \u03b1) (input : String) : Sum String \u03b1 :=\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\u2081 c\u2082 : CtorInfo) : Bool :=\n  c\u2081.size == c\u2082.size && c\u2081.usize == c\u2082.usize && c\u2081.ssize == c\u2082.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\u2081.name.getPrefix == c\u2082.name.getPrefix\n\nprivate partial def S (w : VarId) (c : CtorInfo) : FnBody \u2192 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 \u2190 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 \u2190 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 \u00d7 Bool \u2192 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 \u2192 M (FnBody \u00d7 Bool)\n  | e@(FnBody.case tid y yType alts) => do\n    let ctx \u2190 read\n    if e.hasLiveVar ctx x then do\n      /- If `x` is live in `e`, we recursively process each branch. -/\n      let alts \u2190 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) \u2190 withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b)\n    let (v, _ /- found' -/) \u2190 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 \u2190 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) \u2190 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 \u2190 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 \u2192 M FnBody\n  | FnBody.case tid x xType alts   => do\n      let alts \u2190 alts.mapM fun alt => do\n        let alt \u2190 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 \u2190 R v\n    let b \u2190 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 \u2190 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": "/-\n# Flight Planning\n\nThis example is significantly larger than the previous examples and is in many ways more typical of the\ntype of system that would be encountered in industry. It is characterised by:\n- a state of information on flights is held;\n- messages are received concerning new and existing flights;\n- the state is updated based on the content of the received messages;\n- maintenance is performed on the state to, for example, remove expired entries;\n- the state is queried for information.\n\n## Background\n\nOne of the tasks required of an aircraft operator is to report an intent to fly to the Air Traffic\nServices (ATS) provider. The operator must indicate where and when they intend to fly, and provide\nvarious items of information concerning the flight and the aircraft with which the flight will\nbe conducted.\n\nThe reporting is carried out via a number of standard flight planning messages. These messages\nare defined by the International Civil Aviation Organisation (ICAO) and documented in the\n[Procedures for Air Navigation Services: Air Traffic Management (PANS-ATM)](https://store.icao.int/en/procedures-for-air-navigation-services-air-traffic-management-doc-4444).\nIt is document number 4444 published by ICAO, so is often referred to as _Doc 4444_.\n\nAppendix 3 of PANS-ATM describes a number of messages employed for communicating flight information.\nA subset of those specifically relate to flight planning:\n\n| Message Type | Purpose |\n| - | - |\n| FPL | File a plan for an intended flight |\n| DLA | Report a delay to a previously filed flight |\n| CHG | Modify a previously filed flight plan |\n| CNL | Cancel a planned flight |\n| DEP | Report a flight has departed |\n| ARR | Report a flight has arrived |\n\nAn example FPL message is:\n```\n(FPL-ABC123-IS\n-B738/M-SADE2E3GHIRWZ/LB1\n-YSSY0400\n-M079F380 DCT WOL H65 RAZZI Q29 LIZZI DCT\n-YMML0100\n-PBN/A1B1C1D1O2S2T1 NAV/RNP2 DOF/230220 REG/VHXYZ SEL/AFPQ CODE/7C6DDF OPR/FLYOU ORGN/YSSYABCO PER/C)\n```\nFlight _ABC123_ is flying from _YSSY_ (Sydney) to _YMML_ (Melbourne) departing _0400_ on _20/2/2023_ with an\nexpected flight time of one hour. The aircraft is a Boeing 737-800 (_B738_). The text _WOL H65 RAZZI Q29 LIZZI DCT_\nis a description of the route the flight will follow. The last line contains various pieces of additional information\nsuch as the aircraft registration (_VHXYZ_).\n\nA collection of numerically labelled fields are defined, each containing a subset of the information that relates to a flight.\nDifferent messages are then defined by selecting the appropriate set of fields for\nthe purpose of the message. In the above FPL, those fields are:\n\n| Field Number | Content |\n| - | - |\n| 7 | ABC123 |\n| 8 | IS |\n| 9 | B738/M |\n| 10 | SADE2E3GHIRWZ/LB1 |\n| 13 | YSSY0400 |\n| 15 | M079F380 DCT WOL H65 RAZZI Q29 LIZZI DCT |\n| 16 | YMML0100 |\n| 18 | PBN/A1B1C1D1O2S2T1 NAV/RNP2 DOF/230220 REG/VHXYZ SEL/AFPQ CODE/7C6DDF OPR/FLYOU ORGN/YSSYABCO PER/C |\n\n## The Specification\n\nThe specification is concerned with the processing of flight plan and related messages, and consists of:\n\n- a model of the data elements, fields, flights and messages;\n- definition of invariants on the flights and messages, which primarily capture consistency constraints between the different fields;\n- the definition of a state that models a collection of flight information that might be held by a system;\n- given a state and a received message, the specification of how a revised state is created from the supplied state and the message;\n- some maintenance activities on the state;\n- querying the state.\n\nThe model and program specification are contained in five modules:\n\n| Module | Purpose |\n| - | - |\n| [Core](FPL/Core.md)       | The core data elements from which higher level entities are built |\n| [Field](FPL/Field.md)     | The fields from which the messages are assembled |\n| [Flight](FPL/Flight.md)   | Data entity capturing all information on a flight |\n| [Message](FPL/Message.md) | The various messages employed for flight planning purposes |\n| [State](FPL/State.md)     | The processing of messages with respect to a state |\n\nThese modules depend on the general purpose definitions in [Util](lib/Util.md), [Geo](lib/Geo.md) and [Temporal](lib/Temporal.md).\n-/", "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.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.05921025157134613, "lm_q1q2_score": 0.018794889040799217}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Util.CollectFVars\nimport Lean.AuxRecursor\nimport Lean.Parser.Term\nimport Lean.Meta.RecursorInfo\nimport Lean.Meta.CollectMVars\nimport Lean.Meta.Tactic.ElimInfo\nimport Lean.Meta.Tactic.Induction\nimport Lean.Meta.Tactic.Cases\nimport Lean.Meta.GeneralizeVars\nimport Lean.Elab.App\nimport Lean.Elab.Tactic.ElabTerm\nimport Lean.Elab.Tactic.Generalize\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\n/-\n  Given an `inductionAlt` of the form\n  ```\n  syntax inductionAltLHS := \"| \" (group(\"@\"? ident) <|> hole) (ident <|> hole)*\n  syntax inductionAlt  := ppDedent(ppLine) inductionAltLHS+ \" => \" (hole <|> syntheticHole <|> tacticSeq)\n  ```\n-/\nprivate def getFirstAltLhs (alt : Syntax) : Syntax :=\n  alt[0][0]\n/-- Return `inductionAlt` name. It assumes `alt` does not have multiple `inductionAltLHS` -/\nprivate def getAltName (alt : Syntax) : Name :=\n  let lhs := getFirstAltLhs alt\n  if !lhs[1].isOfKind ``Parser.Term.hole then lhs[1][1].getId.eraseMacroScopes else `_\n/-- Returns the `inductionAlt` `ident <|> hole` -/\nprivate def getAltNameStx (alt : Syntax) : Syntax :=\n  let lhs := getFirstAltLhs alt\n  if lhs[1].isOfKind ``Parser.Term.hole then lhs[1] else lhs[1][1]\n/-- Return `true` if the first LHS of the given alternative contains `@`. -/\nprivate def altHasExplicitModifier (alt : Syntax) : Bool :=\n  let lhs := getFirstAltLhs alt\n  !lhs[1].isOfKind ``Parser.Term.hole && !lhs[1][0].isNone\n/-- Return the variables in the first LHS of the given alternative. -/\nprivate def getAltVars (alt : Syntax) : Array Syntax :=\n  let lhs := getFirstAltLhs alt\n  lhs[2].getArgs\nprivate def getAltRHS (alt : Syntax) : Syntax :=\n  alt[2]\nprivate def getAltDArrow (alt : Syntax) : Syntax :=\n  alt[1]\n\n-- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic\ndef isHoleRHS (rhs : Syntax) : Bool :=\n  rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole\n\ndef evalAlt (mvarId : MVarId) (alt : Syntax) (addInfo : TermElabM Unit) (remainingGoals : Array MVarId) : TacticM (Array MVarId) :=\n  let rhs := getAltRHS alt\n  withCaseRef (getAltDArrow alt) rhs do\n    if isHoleRHS rhs then\n      addInfo\n      let gs' \u2190 mvarId.withContext <| withRef rhs do\n        let mvarDecl \u2190 mvarId.getDecl\n        let val \u2190 elabTermEnsuringType rhs mvarDecl.type\n        mvarId.assign val\n        let gs' \u2190 getMVarsNoDelayed val\n        tagUntaggedGoals mvarDecl.userName `induction gs'.toList\n        pure gs'\n      return remainingGoals ++ gs'\n    else\n      setGoals [mvarId]\n      closeUsingOrAdmit (withTacticInfoContext alt (addInfo *> evalTactic rhs))\n      return remainingGoals\n\n/-!\n  Helper method for creating an user-defined eliminator/recursor application.\n-/\nnamespace ElimApp\n\nstructure Alt where\n  /-- The short name of the alternative, used in `| foo =>` cases -/\n  name      : Name\n  /-- A declaration corresponding to the inductive constructor.\n  (For custom recursors, the alternatives correspond to parameter names in the\n  recursor, so we may not have a declaration to point to.)\n  This is used for go-to-definition on the alternative name. -/\n  declName? : Option Name\n  /-- The subgoal metavariable for the alternative. -/\n  mvarId    : MVarId\n  deriving Inhabited\n\nstructure Context where\n  elimInfo : ElimInfo\n  targets  : Array Expr -- targets provided by the user\n\nstructure State where\n  argPos    : Nat := 0 -- current argument position\n  targetPos : Nat := 0 -- current target at targetsStx\n  f         : Expr\n  fType     : Expr\n  alts      : Array Alt := #[]\n  insts     : Array MVarId := #[]\n\nabbrev M := ReaderT Context $ StateRefT State TermElabM\n\nprivate def addNewArg (arg : Expr) : M Unit :=\n  modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }\n\n/-- Return the binder name at `fType`. This method assumes `fType` is a function type. -/\nprivate def getBindingName : M Name := return (\u2190 get).fType.bindingName!\n/-- Return the next argument expected type. This method assumes `fType` is a function type. -/\nprivate def getArgExpectedType : M Expr := return (\u2190 get).fType.bindingDomain!\n\nprivate def getFType : M Expr := do\n  let fType \u2190 whnfForall (\u2190 get).fType\n  modify fun s => { s with fType := fType }\n  pure fType\n\nstructure Result where\n  elimApp : Expr\n  alts    : Array Alt := #[]\n  others  : Array MVarId := #[]\n\n/--\n  Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for\n  the eliminator. For example, the indices of builtin recursors are considered implicit targets.\n  Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets\n  from the explicit ones.\n-/\npartial def mkElimApp (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do\n  let rec loop : M Unit := do\n    match (\u2190 getFType) with\n    | .forallE binderName _ _ c =>\n      let ctx \u2190 read\n      let argPos := (\u2190 get).argPos\n      if ctx.elimInfo.motivePos == argPos then\n        let motive \u2190 mkFreshExprMVar (\u2190 getArgExpectedType) MetavarKind.syntheticOpaque\n        addNewArg motive\n      else if ctx.elimInfo.targetsPos.contains argPos then\n        let s \u2190 get\n        let ctx \u2190 read\n        unless s.targetPos < ctx.targets.size do\n          throwError \"insufficient number of targets for '{elimInfo.name}'\"\n        let target := ctx.targets[s.targetPos]!\n        let expectedType \u2190 getArgExpectedType\n        let target \u2190 withAssignableSyntheticOpaque <| Term.ensureHasType expectedType target\n        modify fun s => { s with targetPos := s.targetPos + 1 }\n        addNewArg target\n      else match c with\n        | .implicit =>\n          let arg \u2190 mkFreshExprMVar (\u2190 getArgExpectedType)\n          addNewArg arg\n        | .strictImplicit =>\n          let arg \u2190 mkFreshExprMVar (\u2190 getArgExpectedType)\n          addNewArg arg\n        | .instImplicit =>\n          let arg \u2190 mkFreshExprMVar (\u2190 getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName)\n          modify fun s => { s with insts := s.insts.push arg.mvarId! }\n          addNewArg arg\n        | _ =>\n          let arg \u2190 mkFreshExprSyntheticOpaqueMVar (\u2190 getArgExpectedType) (tag := appendTag tag binderName)\n          let x   \u2190 getBindingName\n          modify fun s =>\n            let declName? := elimInfo.altsInfo[s.alts.size]!.declName?\n            { s with alts := s.alts.push \u27e8x, declName?, arg.mvarId!\u27e9 }\n          addNewArg arg\n      loop\n    | _ =>\n      pure ()\n  let f \u2190 Term.mkConst elimInfo.name\n  let fType \u2190 inferType f\n  let (_, s) \u2190 (loop).run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType }\n  let mut others := #[]\n  for mvarId in s.insts do\n    try\n      unless (\u2190 Term.synthesizeInstMVarCore mvarId) do\n        mvarId.setKind .syntheticOpaque\n        others := others.push mvarId\n    catch _ =>\n      mvarId.setKind .syntheticOpaque\n      others := others.push mvarId\n  let alts \u2190 s.alts.filterM fun alt => return !(\u2190 alt.mvarId.isAssigned)\n  return { elimApp := (\u2190 instantiateMVars s.f), alts, others := others }\n\n/-- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign\n  `motiveArg := fun targets => C[targets]` -/\ndef setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do\n  let type \u2190 inferType (mkMVar mvarId)\n  let motive \u2190 mkLambdaFVars (targets.map mkFVar) type\n  let motiverInferredType \u2190 inferType motive\n  let motiveType \u2190 inferType (mkMVar motiveArg)\n  unless (\u2190 isDefEqGuarded motiverInferredType motiveType) do\n    throwError \"type mismatch when assigning motive{indentExpr motive}\\n{\u2190 mkHasTypeButIsExpectedMsg motiverInferredType motiveType}\"\n  motiveArg.assign motive\n\nprivate def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do\n  for altInfo in elimInfo.altsInfo do\n    if altInfo.name == altName then\n      return altInfo.numFields\n  throwError \"unknown alternative name '{altName}'\"\n\nprivate def checkAltNames (alts : Array Alt) (altsSyntax : Array Syntax) : TacticM Unit :=\n  for i in [:altsSyntax.size] do\n    let altStx := altsSyntax[i]!\n    if getAltName altStx == `_ && i != altsSyntax.size - 1 then\n      withRef altStx <| throwError \"invalid occurrence of wildcard alternative, it must be the last alternative\"\n    let altName := getAltName altStx\n    if altName != `_ then\n      unless alts.any (\u00b7.name == altName) do\n        throwErrorAt altStx \"invalid alternative name '{altName}'\"\n\n/-- Given the goal `altMVarId` for a given alternative that introduces `numFields` new variables,\n    return the number of explicit variables. Recall that when the `@` is not used, only the explicit variables can\n    be named by the user. -/\nprivate def getNumExplicitFields (altMVarId : MVarId) (numFields : Nat) : MetaM Nat := altMVarId.withContext do\n  let target \u2190 altMVarId.getType\n  withoutModifyingState do\n    let (_, bis, _) \u2190 forallMetaBoundedTelescope target numFields\n    return bis.foldl (init := 0) fun r bi => if bi.isExplicit then r + 1 else r\n\nprivate def saveAltVarsInfo (altMVarId : MVarId) (altStx : Syntax) (fvarIds : Array FVarId) : TermElabM Unit :=\n  withSaveInfoContext <| altMVarId.withContext do\n    let useNamesForExplicitOnly := !altHasExplicitModifier altStx\n    let mut i := 0\n    let altVars := getAltVars altStx\n    for fvarId in fvarIds do\n      if !useNamesForExplicitOnly || (\u2190 fvarId.getDecl).binderInfo.isExplicit then\n        if i < altVars.size then\n          Term.addLocalVarInfo altVars[i]! (mkFVar fvarId)\n          i := i + 1\n\n/--\n  If `altsSyntax` is not empty we reorder `alts` using the order the alternatives have been provided\n  in `altsSyntax`. Motivations:\n\n  1- It improves the effectiveness of the `checkpoint` and `save` tactics. Consider the following example:\n  ```lean\n  example (h\u2081 : p \u2228 q) (h\u2082 : p \u2192 x = 0) (h\u2083 : q \u2192 y = 0) : x * y = 0 := by\n    cases h\u2081 with\n    | inr h =>\n      sleep 5000 -- sleeps for 5 seconds\n      save\n      have : y = 0 := h\u2083 h\n      -- We can confortably work here\n    | inl h => stop ...\n  ```\n  If we do reorder, the `inl` alternative will be executed first. Moreover, as we type in the `inr` alternative,\n  type errors will \"swallow\" the `inl` alternative and affect the tactic state at `save` making it ineffective.\n\n  2- The errors are produced in the same order the appear in the code above. This is not super important when using IDEs.\n-/\ndef reorderAlts (alts : Array Alt) (altsSyntax : Array Syntax) : Array Alt := Id.run do\n  if altsSyntax.isEmpty then\n    return alts\n  else\n    let mut alts := alts\n    let mut result := #[]\n    for altStx in altsSyntax do\n      let altName := getAltName altStx\n      let some i := alts.findIdx? (\u00b7.1 == altName) | return result ++ alts\n      result := result.push alts[i]!\n      alts := alts.eraseIdx i\n    return result ++ alts\n\ndef evalAlts (elimInfo : ElimInfo) (alts : Array Alt) (optPreTac : Syntax) (altsSyntax : Array Syntax)\n    (initialInfo : Info)\n    (numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do\n  checkAltNames alts altsSyntax\n  let hasAlts := altsSyntax.size > 0\n  if hasAlts then\n    -- default to initial state outside of alts\n    -- HACK: because this node has the same span as the original tactic,\n    -- we need to take all the info trees we have produced so far and re-nest them\n    -- inside this node as well\n    let treesSaved \u2190 getResetInfoTrees\n    withInfoContext ((modifyInfoState fun s => { s with trees := treesSaved }) *> go) (pure initialInfo)\n  else go\nwhere\n  go := do\n    let alts := reorderAlts alts altsSyntax\n    let hasAlts := altsSyntax.size > 0\n    let mut usedWildcard := false\n    let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here\n    let mut altsSyntax := altsSyntax\n    for { name := altName, declName?, mvarId := altMVarId } in alts do\n      let numFields \u2190 getAltNumFields elimInfo altName\n      let mut isWildcard := false\n      let altStx? \u2190\n        match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with\n        | some idx =>\n          let altStx := altsSyntax[idx]!\n          altsSyntax := altsSyntax.eraseIdx idx\n          pure (some altStx)\n        | none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with\n          | some idx =>\n            isWildcard := true\n            pure (some altsSyntax[idx]!)\n          | none =>\n            pure none\n      match altStx? with\n      | none =>\n        let mut (_, altMVarId) \u2190 altMVarId.introN numFields\n        match (\u2190 Cases.unifyEqs? numEqs altMVarId {}) with\n        | none   => pure () -- alternative is not reachable\n        | some (altMVarId', _) =>\n          (_, altMVarId) \u2190 altMVarId'.introNP numGeneralized\n          for fvarId in toClear do\n            altMVarId \u2190 altMVarId.tryClear fvarId\n          let altMVarIds \u2190 applyPreTac altMVarId\n          if !hasAlts then\n            -- User did not provide alternatives using `|`\n            subgoals := subgoals ++ altMVarIds.toArray\n          else if altMVarIds.isEmpty then\n            pure ()\n          else\n            logError m!\"alternative '{altName}' has not been provided\"\n            altMVarIds.forM fun mvarId => admitGoal mvarId\n      | some altStx =>\n        (subgoals, usedWildcard) \u2190 withRef altStx do\n          let altVars := getAltVars altStx\n          let numFieldsToName \u2190 if altHasExplicitModifier altStx then pure numFields else getNumExplicitFields altMVarId numFields\n          if altVars.size > numFieldsToName then\n            logError m!\"too many variable names provided at alternative '{altName}', #{altVars.size} provided, but #{numFieldsToName} expected\"\n          let mut (fvarIds, altMVarId) \u2190 altMVarId.introN numFields (altVars.toList.map getNameOfIdent') (useNamesForExplicitOnly := !altHasExplicitModifier altStx)\n          -- Delay adding the infos for the pattern LHS because we want them to nest\n          -- inside tacticInfo for the current alternative (in `evalAlt`)\n          let addInfo := do\n            if (\u2190 getInfoState).enabled then\n              if let some declName := declName? then\n                addConstInfo (getAltNameStx altStx) declName\n              saveAltVarsInfo altMVarId altStx fvarIds\n          let unusedAlt := do\n            addInfo\n            if isWildcard then\n              pure (#[], usedWildcard)\n            else\n              throwError \"alternative '{altName}' is not needed\"\n          match (\u2190 Cases.unifyEqs? numEqs altMVarId {}) with\n          | none => unusedAlt\n          | some (altMVarId', _) =>\n            (_, altMVarId) \u2190 altMVarId'.introNP numGeneralized\n            for fvarId in toClear do\n              altMVarId \u2190 altMVarId.tryClear fvarId\n            let altMVarIds \u2190 applyPreTac altMVarId\n            if altMVarIds.isEmpty then\n              unusedAlt\n            else\n              let mut subgoals := subgoals\n              for altMVarId' in altMVarIds do\n                subgoals \u2190 evalAlt altMVarId' altStx addInfo subgoals\n              pure (subgoals, usedWildcard || isWildcard)\n    if usedWildcard then\n      altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_\n    unless altsSyntax.isEmpty do\n      logErrorAt altsSyntax[0]! \"unused alternative\"\n    setGoals subgoals.toList\n  applyPreTac (mvarId : MVarId) : TacticM (List MVarId) :=\n    if optPreTac.isNone then\n      return [mvarId]\n    else\n      evalTacticAt optPreTac[0] mvarId\n\nend ElimApp\n\n/-\n  Recall that\n  ```\n  generalizingVars := optional (\" generalizing \" >> many1 ident)\n  \u00abinduction\u00bb  := leading_parser nonReservedSymbol \"induction \" >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts\n  ```\n  `stx` is syntax for `induction`. -/\nprivate def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) :=\n  withRef stx do\n    let generalizingStx := stx[3]\n    if generalizingStx.isNone then\n      pure #[]\n    else\n      trace[Elab.induction] \"{generalizingStx}\"\n      let vars := generalizingStx[1].getArgs\n      getFVarIds vars\n\n-- process `generalizingVars` subterm of induction Syntax `stx`.\nprivate def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat \u00d7 MVarId) :=\n  mvarId.withContext do\n    let userFVarIds \u2190 getUserGeneralizingFVarIds stx\n    let forbidden \u2190 mkGeneralizationForbiddenSet targets\n    let mut s \u2190 getFVarSetToGeneralize targets forbidden\n    for userFVarId in userFVarIds do\n      if forbidden.contains userFVarId then\n        throwError \"variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}\"\n      if s.contains userFVarId then\n        throwError \"unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically\"\n      s := s.insert userFVarId\n    let fvarIds \u2190 sortFVarIds s.toArray\n    let (fvarIds, mvarId') \u2190 mvarId.revert fvarIds\n    return (fvarIds.size, mvarId')\n\n/--\nGiven `inductionAlts` of the fom\n```\nsyntax inductionAlts := \"with \" (tactic)? withPosition( (colGe inductionAlt)+)\n```\nReturn an array containing its alternatives.\n-/\nprivate def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax :=\n  inductionAlts[2].getArgs\n\nprivate def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax :=\n  if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0]\n\nprivate def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax :=\n  if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1]\n\nprivate def isMultiAlt (alt : Syntax) : Bool :=\n  alt[0].getNumArgs > 1\n\n/-- Return `some #[alt_1, ..., alt_n]` if `alt` has multiple LHSs. -/\nprivate def expandMultiAlt? (alt : Syntax) : Option (Array Syntax) := Id.run do\n  if isMultiAlt alt then\n    some <| alt[0].getArgs.map fun lhs => alt.setArg 0 (mkNullNode #[lhs])\n  else\n    none\n\n/--\nGiven `inductionAlts` of the form\n```\nsyntax inductionAlts := \"with \" (tactic)? withPosition( (colGe inductionAlt)+)\n```\nReturn `some inductionAlts'` if one of the alternatives have multiple LHSs, in the new `inductionAlts'`\nall alternatives have a single LHS.\n\nRemark: the `RHS` of alternatives with multi LHSs is copied.\n-/\nprivate def expandInductionAlts? (inductionAlts : Syntax) : Option Syntax := Id.run do\n  let alts := getAltsOfInductionAlts inductionAlts\n  if alts.any isMultiAlt then\n    let mut altsNew := #[]\n    for alt in alts do\n      if let some alt' := expandMultiAlt? alt then\n        altsNew := altsNew ++ alt'\n      else\n        altsNew := altsNew.push alt\n    some <| inductionAlts.setArg 2 (mkNullNode altsNew)\n  else\n    none\n\n/--\nExpand\n```\nsyntax \"induction \" term,+ (\" using \" ident)?  (\"generalizing \" (colGt term:max)+)? (inductionAlts)? : tactic\n```\nif `inductionAlts` has an alternative with multiple LHSs.\n-/\nprivate def expandInduction? (induction : Syntax) : Option Syntax := do\n  let optInductionAlts := induction[4]\n  guard <| !optInductionAlts.isNone\n  let inductionAlts' \u2190 expandInductionAlts? optInductionAlts[0]\n  return induction.setArg 4 (mkNullNode #[inductionAlts'])\n\n/--\nExpand\n```\nsyntax \"cases \" casesTarget,+ (\" using \" ident)? (inductionAlts)? : tactic\n```\nif `inductionAlts` has an alternative with multiple LHSs.\n-/\nprivate def expandCases? (induction : Syntax) : Option Syntax := do\n  let optInductionAlts := induction[3]\n  guard <| !optInductionAlts.isNone\n  let inductionAlts' \u2190 expandInductionAlts? optInductionAlts[0]\n  return induction.setArg 3 (mkNullNode #[inductionAlts'])\n\n/--\n  We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names.\n  The idea is to make sure users do not write unstructured tactics. -/\nprivate def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit :=\n  unless optInductionAlts.isNone do\n    let mut found := false\n    for alt in getAltsOfInductionAlts optInductionAlts[0] do\n      let n := getAltName alt\n      if n == `_ then\n        unless (getAltVars alt).isEmpty do\n          throwErrorAt alt \"wildcard alternative must not specify variable names\"\n        if found then\n          throwErrorAt alt \"more than one wildcard alternative '| _ => ...' used\"\n        found := true\n\ndef getInductiveValFromMajor (major : Expr) : TacticM InductiveVal :=\n  liftMetaMAtMain fun mvarId => do\n    let majorType \u2190 inferType major\n    let majorType \u2190 whnf majorType\n    matchConstInduct majorType.getAppFn\n      (fun _ => Meta.throwTacticEx `induction mvarId m!\"major premise type is not an inductive type {indentExpr majorType}\")\n      (fun val _ => pure val)\n\n-- `optElimId` is of the form `(\"using\" ident)?`\nprivate def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM ElimInfo := do\n  if optElimId.isNone then\n    if let some elimInfo \u2190 getCustomEliminator? targets then\n      return elimInfo\n    unless targets.size == 1 do\n      throwError \"eliminator must be provided when multiple targets are used (use 'using <eliminator-name>'), and no default eliminator has been registered using attribute `[eliminator]`\"\n    let indVal \u2190 getInductiveValFromMajor targets[0]!\n    if induction && indVal.all.length != 1 then\n      throwError \"'induction' tactic does not support mutually inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives\"\n    if induction && indVal.isNested then\n      throwError \"'induction' tactic does not support nested inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives\"\n    let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name\n    getElimInfo elimName indVal.name\n  else\n    let elimId := optElimId[1]\n    let elimName \u2190 withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId\n    -- not a precise check, but covers the common cases of T.recOn / T.casesOn\n    -- as well as user defined T.myInductionOn to locate the constructors of T\n    let baseName? := if \u2190 isInductive elimName.getPrefix then some elimName.getPrefix else none\n    withRef elimId <| getElimInfo elimName baseName?\n\nprivate def shouldGeneralizeTarget (e : Expr) : MetaM Bool := do\n  if let .fvar fvarId .. := e then\n    return (\u2190  fvarId.getDecl).hasValue -- must generalize let-decls\n  else\n    return true\n\nprivate def generalizeTargets (exprs : Array Expr) : TacticM (Array Expr) := do\n  if (\u2190 withMainContext <| exprs.anyM (shouldGeneralizeTarget \u00b7)) then\n    liftMetaTacticAux fun mvarId => do\n      let (fvarIds, mvarId) \u2190 mvarId.generalize (exprs.map fun expr => { expr })\n      return (fvarIds.map mkFVar, [mvarId])\n  else\n    return exprs\n\n@[builtin_tactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx =>\n  match expandInduction? stx with\n  | some stxNew => withMacroExpansion stx stxNew <| evalTactic stxNew\n  | _ => focus do\n    let optInductionAlts := stx[4]\n    let alts := getAltsOfOptInductionAlts optInductionAlts\n    let targets \u2190 withMainContext <| stx[1].getSepArgs.mapM (elabTerm \u00b7 none)\n    let targets \u2190 generalizeTargets targets\n    let elimInfo \u2190 withMainContext <| getElimNameInfo stx[2] targets (induction := true)\n    let mvarId \u2190 getMainGoal\n    -- save initial info before main goal is reassigned\n    let initInfo \u2190 mkTacticInfo (\u2190 getMCtx) (\u2190 getUnsolvedGoals) (\u2190 getRef)\n    let tag \u2190 mvarId.getTag\n    mvarId.withContext do\n      let targets \u2190 addImplicitTargets elimInfo targets\n      checkTargets targets\n      let targetFVarIds := targets.map (\u00b7.fvarId!)\n      let (n, mvarId) \u2190 generalizeVars mvarId stx targets\n      mvarId.withContext do\n        let result \u2190 withRef stx[1] do -- use target position as reference\n          ElimApp.mkElimApp elimInfo targets tag\n        trace[Elab.induction] \"elimApp: {result.elimApp}\"\n        let elimArgs := result.elimApp.getAppArgs\n        ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos]!.mvarId! targetFVarIds\n        let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts\n        mvarId.assign result.elimApp\n        ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds)\n        appendGoals result.others.toList\nwhere\n  checkTargets (targets : Array Expr) : MetaM Unit := do\n    let mut foundFVars : FVarIdSet := {}\n    for target in targets do\n      unless target.isFVar do\n        throwError \"index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}\"\n      if foundFVars.contains target.fvarId! then\n        throwError \"target (or one of its indices) occurs more than once{indentExpr target}\"\n\ndef elabCasesTargets (targets : Array Syntax) : TacticM (Array Expr) :=\n  withMainContext do\n    let args \u2190 targets.mapM fun target => do\n      let hName? := if target[0].isNone then none else some target[0][0].getId\n      let expr \u2190 elabTerm target[1] none\n      return { expr, hName? : GeneralizeArg }\n    if (\u2190 withMainContext <| args.anyM fun arg => shouldGeneralizeTarget arg.expr <||> pure arg.hName?.isSome) then\n      liftMetaTacticAux fun mvarId => do\n        let argsToGeneralize \u2190 args.filterM fun arg => shouldGeneralizeTarget arg.expr <||> pure arg.hName?.isSome\n        let (fvarIdsNew, mvarId) \u2190 mvarId.generalize argsToGeneralize\n        let mut result := #[]\n        let mut j := 0\n        for arg in args do\n          if (\u2190 shouldGeneralizeTarget arg.expr) || arg.hName?.isSome then\n            result := result.push (mkFVar fvarIdsNew[j]!)\n            j := j+1\n          else\n            result := result.push arg.expr\n        return (result, [mvarId])\n    else\n      return args.map (\u00b7.expr)\n\n@[builtin_tactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx =>\n  match expandCases? stx with\n  | some stxNew => withMacroExpansion stx stxNew <| evalTactic stxNew\n  | _ => focus do\n    -- leading_parser nonReservedSymbol \"cases \" >> sepBy1 (group majorPremise) \", \" >> usingRec >> optInductionAlts\n    let targets \u2190 elabCasesTargets stx[1].getSepArgs\n    let optInductionAlts := stx[3]\n    let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts\n    let alts :=  getAltsOfOptInductionAlts optInductionAlts\n    let targetRef := stx[1]\n    let elimInfo \u2190 withMainContext <| getElimNameInfo stx[2] targets (induction := false)\n    let mvarId \u2190 getMainGoal\n    -- save initial info before main goal is reassigned\n    let initInfo \u2190 mkTacticInfo (\u2190 getMCtx) (\u2190 getUnsolvedGoals) (\u2190 getRef)\n    let tag \u2190 mvarId.getTag\n    mvarId.withContext do\n      let targets \u2190 addImplicitTargets elimInfo targets\n      let result \u2190 withRef targetRef <| ElimApp.mkElimApp elimInfo targets tag\n      let elimArgs := result.elimApp.getAppArgs\n      let targets \u2190 elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i]!\n      let motiveType \u2190 inferType elimArgs[elimInfo.motivePos]!\n      let mvarId \u2190 generalizeTargetsEq mvarId motiveType targets\n      let (targetsNew, mvarId) \u2190 mvarId.introN targets.size\n      mvarId.withContext do\n        ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos]!.mvarId! targetsNew\n        mvarId.assign result.elimApp\n        ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew)\n\nbuiltin_initialize\n  registerTraceClass `Elab.cases\n  registerTraceClass `Elab.induction\n\nend Lean.Elab.Tactic\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/Tactic/Induction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824994383169, "lm_q2_score": 0.05500528906801214, "lm_q1q2_score": 0.018788844122178718}}
{"text": "import meta_k.meta_sort\nimport meta_k.meta_var\nimport meta_k.meta_symbol\nimport meta_k.meta_pattern\nimport object_k.object_symbol\nimport object_k.object_pattern\nimport meta_k.sort_schemas\nimport meta_k.symbol_schemas\n\n\n/-\n\nThis file contains a definition of the 'working example' matching logic\ntheory described in chapter 8 of the \"Semantics of K\" document for illustration\npurposes. \nNotation used that differs from that in the document is\n1) the use of tilde (~) as a prefix for object theory elements (like # for meta)m\n2) the \u2191 up arrow is used to cast one type into another in a way that\n    is explicit. Matching Logic is based on many-sorted logic, and there are \n    implicit transofrmations happening all over the place, which is daunting for\n    the uninitiated, so I've made them explicit lifts instead of implicit coercions.\n3) The modified logical connective notation corresponds to its matching logic pattern\n   counterpart. IE #\u2227 is the #and pattern, ~s~> is implication parameterized by sort s, etc.\n\nFor the purposes of chapter 8, the definition of T here can just be thought of as the\nitems in scope. \nThe constructions and lifting used in chapters 7 and 8 are also surprisingly different\nfrom thos used in Kore; Symbols become 'head' objects, pattern constructions are all\nmade into independent production rules, and they object pattern/meta pattern constructors\nare parametric across all patterns, and the lifting process between object theory \nelements and meta theory elements is altered.\n\n-/\n\n\n-- object sort definition of Nat\ndef Nat : object_sort := ~sort \u27e8\"Nat\"\u27e9 ~nilSortList\n\n-- object sort definition of List{Nat}\ndef List_Nat : object_sort := ~sort \u27e8\"List\"\u27e9 \u2191[~sort \u27e8\"Nat\"\u27e9 ~nilSortList]\n\n\n-- specification of lift for sorts as defined in 8.3\nmutual def lift_object_sort, lift_object_sort_list \nwith lift_object_sort : object_sort \u2192 meta_sort \n| (object_sort.mk ident object_sort_list.nil) := #sort (repr ident) #nilSortList\n| (object_sort.mk ident L) := #sort (repr ident) (lift_object_sort_list L)\nwith lift_object_sort_list : object_sort_list \u2192 meta_sort_list\n| (object_sort_list.nil) := #nilSortList\n| (object_sort_list.cons hd tl) := #consSortList (lift_object_sort hd) (lift_object_sort_list tl)\n\ninstance : has_lift object_sort meta_sort := \u27e8 lift_object_sort \u27e9 \ninstance : has_lift object_sort_list meta_sort_list := \u27e8 lift_object_sort_list \u27e9 \n\ndef meta_Nat : meta_sort := \u2191Nat\ndef meta_List_Nat : meta_sort := \u2191List_Nat\n\n-- evaluation of lifting process from 8.3 on Nat and List_Nat; VM evaluation\n-- will show that they come out to\n-- #sort \"Nat\" \u03b5\n-- #sort \"List\" [#sort \"Nat\" \u03b5]\n-- respectively\n#eval meta_Nat\n#eval meta_List_Nat\n\n\n-- The literal definition of the sort helper functions for #'Nat and #'List\n-- given in 8.3 would be these two functions.\ndef nat_meta_rep : #Sort := #sort \"Nat\" #nilSortList\nnotation `#'Nat` := nat_meta_rep\n\ndef list_meta_rep : #Sort \u2192 #Sort \n| s := #sort \"List\" \u2191[s]\nnotation `#'List` := list_meta_rep\n\n-- The axioms which define them intensionally in matching logic would be as follows,\n-- so we add these patterns to our theory T.\ndef nat_constructor_axiom : #Pattern := \n    let s1 := #'Nat,\n        s2 := #sort \"Nat\" #nilSortList\n    in (\u2191s1 #= (s1, s2); \u2191s2)\n\ndef list_constructor_axiom {carrier s : #Sort} : #Pattern :=\n   let s1 := #'List s,\n       s2 := #sort \"List\" \u2191[s]\n    in #\u2200carrier, \"s\" : %Sort . (\u2191s1) #= (s1, s2); (\u2191s2)\n\n\n-- axiom schema about definedness of list parameters; for any sort s,\n-- if s is defined in the current theory, that implies that the sort List s\n-- is therefore defined.\ndef list_axiom_schema {carrier s : #Sort} {L : #SortList}: #Pattern :=\n    #\u2200carrier, \"s\" : %Sort . \n        (#apply (#symbol \"sortDeclared\" [%Sort] [%Sort, %SortList] %Sort) . [\u2191s, \u2191L])\n        ~carrier~> \n        (#apply (#symbol \"sortDeclared\" [%Sort] [%Sort, %SortList] %Sort) . [\u2191(#'List s), \u2191L])\n\n\n-- Generic function to lift object symbol declarations into meta theory\n-- based on specification in chapter 8. Uses already defined lifts for sort.\ndef object_symbol_lift_to_meta : object_symbol \u2192 meta_symbol\n| (~symbol ident params args ret) := \n    #symbol (name_fn ident) \u2191params \u2191args \u2191ret\n\ninstance : has_lift object_symbol meta_symbol := \u27e8 object_symbol_lift_to_meta \u27e9 \n\ndef object_nat_zero : ~Symbol := ~symbol \"O\" [] [] Nat\ndef meta_nat_zero : #Symbol := #symbol \"zero\" [] [] #'Nat\nnotation `~O` := object_nat_zero\n\n-- definition of object theory's 'zero' symbol in meta theory\n-- is as follows; #eval shows that the version produced by the \n-- lifting function is identical.\ndef zeros_eq : bool := \u2191object_nat_zero = meta_nat_zero\n#eval zeros_eq\n\n\ndef object_nat_succ : ~Symbol := ~symbol \"succ\" [] [Nat] Nat\ndef meta_nat_succ : #Symbol := #symbol \"succ\" [] [#'Nat] #'Nat\n\ndef succs_eq : bool := \u2191object_nat_succ = meta_nat_succ\n#eval succs_eq\n\ndef object_nat_plus : ~Symbol := ~symbol \"+\" [] [Nat, Nat] Nat\ndef meta_nat_plus : #Symbol := #symbol \"plus\" [] [#'Nat, #'Nat] #'Nat\nnotation `~+` := object_nat_plus\n\ndef pluses_eq : bool := \u2191object_nat_plus = meta_nat_plus\n#eval pluses_eq\n\ndef object_list_nat_nil : ~Symbol := ~symbol \"\u03b5\" [Nat] [] (List_Nat)\ndef meta_list_nat_nil : #Symbol := #symbol \"nil\" [#'Nat] [] (#'List(#'Nat))\n\ndef nils_eq : bool := \u2191object_list_nat_nil = meta_list_nat_nil\n#eval nils_eq\n\ndef object_list_nat_cons : ~Symbol := ~symbol \"::\" [Nat] [Nat, List_Nat] (List_Nat)\ndef meta_list_nat_cons : #Symbol := #symbol \"cons\" [#'Nat] [#'Nat, #'List(#'Nat)] (#'List(#'Nat))\n\n-- parametric list symbols\ndef meta_list_nil : #Sort \u2192 #Symbol\n| s := #symbol \"nil\" [%Sort] [] (#'List s)\nnotation `#'nil` := meta_list_nil\n\ndef meta_list_cons : #Sort \u2192 #Symbol\n| s := #symbol \"cons\" [%Sort] [s, #'List s] (#'List s)\nnotation `#'cons` := meta_list_cons\n\ndef meta_list_append : #Sort \u2192 #Symbol\n| s := #symbol \"append\" [%Sort] [#'List s, #'List s] (#'List s)\nnotation `#'append` := meta_list_append\n\ndef cons_eq : bool := \u2191object_list_nat_cons = meta_list_nat_cons\n#eval cons_eq\n\n\ndef object_list_nat_append : ~Symbol := ~symbol \"@\" [Nat] [List_Nat, List_Nat] (List_Nat)\ndef meta_list_nat_append : #Symbol := #symbol \"append\" [#'Nat] [#'List(#'Nat), #'List(#'Nat)] (#'List(#'Nat))\nnotation `#'append` := meta_list_nat_append\n\ndef append_eq : bool := \u2191object_list_nat_append = meta_list_nat_append\n#eval append_eq\n\ndef symbol_declared_pred {s : #Sort} := #symbol \"symbolDeclared\" [%Sort] [%Symbol, %SymbolList] %Pattern\ndef sort_declared_pred   {s : #Sort} := #symbol \"sortDeclared\" [%Sort] [%Sort, %SortList] %Pattern\ndef sorts_declared_pred  {s : #Sort} := #symbol \"sortsDeclared\" [%Sort] [%SortList, %SortList] %Pattern\ndef axiom_declared_pred  {s : #Sort} := #symbol \"axiomDeclared\" [%Sort] [%Pattern, %PatternList] %Pattern\n\n-- for any #s : Sort in T, the meta representation of the nat zero symbol\n-- is declared, but not for any other sorts.\n-- object_nat_zero gets lifted to meta_symbol, then to meta_pattern to\n-- satisfy the specification.\ndef non_parametric_axiom1 {\u00ab#s\u00bb : #Sort} {L : #SymbolList }: #Pattern :=\n    #apply (@symbol_declared_pred \u00ab#s\u00bb) . [\u2191object_nat_zero, \u2191L]\n\n-- for any #s : Sort in T, the meta representation of succ is declared,\n-- but not for any others.\ndef non_parametric_axiom2 {\u00ab#s\u00bb : #Sort} {L : #SymbolList} : #Pattern := \n    #apply (@symbol_declared_pred \u00ab#s\u00bb)  . [\u2191object_nat_succ, \u2191L]\n\ndef non_parametric_axiom3 {\u00ab#s\u00bb : #Sort} {L : #SymbolList} : #Pattern := \n    #apply (@symbol_declared_pred \u00ab#s\u00bb)  . [\u2191object_nat_plus, \u2191L]\n\ndef parametric_axiom1 {\u00ab#s\u00bb s  : #Sort} {LS : #SortList} {LSy : #SymbolList} : #Pattern :=\n    (#apply (@sort_declared_pred \u00ab#s\u00bb) . [\u2191s, \u2191LS])\n    ~s~> \n    (#apply (@symbol_declared_pred \u00ab#s\u00bb) . [\u2191object_list_nat_nil, \u2191LSy])\n\ndef parametric_axiom2 {\u00ab#s\u00bb s : #Sort} {LS : #SortList} {LSy : #SymbolList} : #Pattern :=\n    (#apply (@sort_declared_pred \u00ab#s\u00bb) . [\u2191s, \u2191LS])\n    ~s~> \n    (#apply (@symbol_declared_pred \u00ab#s\u00bb) . [\u2191object_list_nat_cons, \u2191LSy])\n\ndef parametric_axiom3 {\u00ab#s\u00bb s : #Sort} {LS : #SortList} {LSy : #SymbolList} : #Pattern :=\n    (#apply (@sort_declared_pred \u00ab#s\u00bb) . [\u2191s, \u2191LS])\n    ~s~> \n    (#apply (@symbol_declared_pred \u00ab#s\u00bb) . [\u2191object_list_nat_append, \u2191LSy])\n\n\ndef object_variable_lift_meta : ~Variable \u2192 #Variable\n| (~variable ident s) := #variable (name_fn ident) (\u2191s)\n\ninstance : has_lift object_variable meta_variable := \u27e8 object_variable_lift_meta \u27e9 \n\nopen object_pattern\nopen meta_pattern\n\nmutual def object_pattern_lift_meta, object_pattern_list_lift_meta \nwith object_pattern_lift_meta : ~Pattern \u2192 #Pattern\n| (~variableAsPattern v) := #variableAsPattern \u2191v\n| (object_application \u03c3 L) := #apply \u2191\u03c3  . (object_pattern_list_lift_meta L)\n| (object_and s \u03c61 \u03c62) := meta_and \u2191s (object_pattern_lift_meta \u03c61) (object_pattern_lift_meta \u03c62)\n| (object_not s \u03c6) := meta_not \u2191s (object_pattern_lift_meta \u03c6)\n| (object_exsts s v \u03c6) := meta_exsts \u2191s \u2191v (object_pattern_lift_meta \u03c6)\nwith object_pattern_list_lift_meta : ~PatternList \u2192 #PatternList\n| [] := []\n| (hd :: tl) := object_pattern_lift_meta hd :: (object_pattern_list_lift_meta tl)\n\ninstance object_pattern_to_meta_pattern_lift : has_lift object_pattern meta_pattern := \u27e8 object_pattern_lift_meta \u27e9 \n\ndef object_nat_var : ~Variable := \u27e8 \"x\", Nat \u27e9 \ndef meta_nat_var : #Variable := \u27e8 \"x\", #'Nat \u27e9 \n#eval ((((\u2191object_nat_var) : #Pattern) = (\u2191meta_nat_var))  : bool)\n\n\n-- for any x : Nat, x + O is equal to x\n-- extremely verbose version to clarify what's going on.\ndef object_aux_axiom1_verbose {c s' : ~Sort} : ~Pattern :=\n    ~\u2200c, \"x\" : Nat . ((~apply (~symbol \"+\" [] [Nat, Nat] Nat) . [(~variableAsPattern \u27e8\"x\", Nat\u27e9), \u2191(~symbol \"O\" [] [] Nat)]) ~= (Nat, s'); (~variableAsPattern \u27e8\"x\", Nat\u27e9))\n\n-- more comfortable version\ndef object_aux_axiom1 {c s' : ~Sort} : ~Pattern :=\n    let x : ~Variable := \u27e8 \"x\", Nat \u27e9\n    in ~\u2200c, x . ((~apply ~+ . [\u2191x, \u2191~O]) ~= (Nat, s'); (\u2191x))\n\ndef meta_aux_axiom1 {c s' : #Sort} : #Pattern :=\n    let x : #Variable := #variable \"x\" #'Nat\n    in #\u2200c, x . ((#apply meta_nat_plus . [\u2191x, \u2191meta_nat_zero]) #= (#'Nat, s'); (\u2191x))\n\ndef a_lift : #Pattern := \u2191(@object_aux_axiom1 object_sort.inhabited.default object_sort.inhabited.default)\n#eval a_lift \n\n\n-- example of naming helper functions given on p. 49-50, allowing\n-- #'zero to be used in place of the longer 'raw' representation\ndef \u00ab#'zero\u00bb : #Symbol := #symbol \"zero\" [] [] #'Nat\ndef zero_axiom {\u00ab#s\u00bb : #Sort} : #Pattern := \n    \u2191\u00ab#'zero\u00bb #= (#'Nat, \u00ab#s\u00bb); #apply (#symbol \"zero\" [] [] #'Nat) . []\n\n\ndef \u00ab#'nil\u00bb : #Sort \u2192 #Symbol \n| s := #symbol \"nil\" [%Sort] [] s\n\ndef nil_axiom {\u00ab#s\u00bb : #Sort} : #Sort \u2192 #Pattern\n| s' := #\u2200\u00ab#s\u00bb, \"s'\" : s' . \u2191(\u00ab#'nil\u00bb s') #= (s', \u00ab#s\u00bb); #apply (#symbol \"nil\" [%Sort] [] s') . []\n\ndef \u03a81 {s' : #Sort} : #Pattern :=\n    (#apply (#symbol \"#'plus\" [] [#'Nat, #'Nat] #'Nat) . [#variableAsPattern \u27e8 \"x\", #'Nat\u27e9, \u2191\u00ab#'zero\u00bb]) \n    #= (#'Nat, s'); \n    (#variableAsPattern \u27e8 \"x\", #'Nat \u27e9)\n\n-- append(s) (x :: L0) (L) == x :: (L0 ++ L)\ndef \u03a82 {s s' : #Sort} : #Pattern :=\n    (#apply (#'append s) . [(#apply (#'cons s) . [#variableAsPattern \u27e8\"L0\", (#'List s)\u27e9]), (#variableAsPattern \u27e8\"L\", (#'List s)\u27e9) ])\n    #= (#'List s, s');\n    (#apply (#'cons s) . [(#apply (#'append s) . [#variableAsPattern \u27e8\"L0\", (#'List s)\u27e9, #variableAsPattern \u27e8\"L\", (#'List s)\u27e9]) ])\n\ndef axiom_\u03a81 {\u00ab#s\u00bb s s' : #Sort} {Ss : #SortList} {\u03c6s : #PatternList} : #Pattern :=\n    #\u2200\u00ab#s\u00bb, \"s'\" : %Sort . (#apply (@sort_declared_pred \u00ab#s\u00bb) . [\u2191s'])\n    ~\u00ab#s\u00bb~> \n    (#apply (@axiom_declared_pred \u00ab#s\u00bb) . [@\u03a81 s'])\n    \ndef axiom_\u03a82 {\u00ab#s\u00bb s s' : #Sort} {Ss : #SortList} {\u03c6s : #PatternList} : #Pattern :=\n    #\u2200\u00ab#s\u00bb, \"s'\" : %Sort . ((#apply (@sort_declared_pred \u00ab#s\u00bb) . [\u2191s]) \n                            #\u2227(s'); (#apply (@sort_declared_pred \u00ab#s\u00bb) . [\u2191s']))\n                            ~\u00ab#s\u00bb~> \n                            (#apply (@axiom_declared_pred \u00ab#s\u00bb) . [@\u03a82 s s'])\n\n\n\n    \n\n       ", "meta": {"author": "ammkrn", "repo": "learning_semantics_of_k", "sha": "c1487b538e1decc0f1fd389cd36bc36d2da012ab", "save_path": "github-repos/lean/ammkrn-learning_semantics_of_k", "path": "github-repos/lean/ammkrn-learning_semantics_of_k/learning_semantics_of_k-c1487b538e1decc0f1fd389cd36bc36d2da012ab/src/main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03904829244665436, "lm_q1q2_score": 0.01876187193479656}}
{"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 : \u2115} {\u03c3 : Type} {\u03b9 : Type} {\u03c4 : \u03b9 \u2192 Type} [decidable_eq \u03b9]\n\n/-\nWe use the following conventions for type variables:\n\n `\u03c3` -- thread internal states\n `\u03b9` -- shared memory index\n `\u03c4` -- 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\u03a3 is constructor where the second argument may depend on the type of the first (in this case i). Can be constructed using \u27e8...\u27e9\n-/\ninductive kernel {\u03b9 : Type} (\u03c3 : Type) (\u03c4 : \u03b9 \u2192 Type) : Type\n| load       : (\u03c3 \u2192 (\u03a3i:\u03b9, (\u03c4 i \u2192 \u03c3))) \u2192 kernel\n| store      : (\u03c3 \u2192 (\u03a3i:\u03b9, \u03c4 i)) \u2192 kernel\n| compute {} : (\u03c3 \u2192 \u03c3) \u2192 kernel\n| seq        : kernel \u2192 kernel \u2192 kernel\n| ite        : (\u03c3 \u2192 bool) \u2192 kernel \u2192 kernel \u2192 kernel\n| loop       : (\u03c3 \u2192 bool) \u2192 kernel \u2192 kernel\n| sync {}    : kernel\n\ninfixr ` ;; `:90 := kernel.seq\nopen kernel\n\n/-- Memory view -/\ndef memory {\u03b9 : Type} (\u03c4 : \u03b9 \u2192 Type) := \u03a0 (i : \u03b9), \u03c4 i\n\nnamespace memory\n\ndef get (m : memory \u03c4) (i : \u03b9) : \u03c4 i := m i\n\ndef update (m : memory \u03c4) (i : \u03b9) (v : \u03c4 i) : memory \u03c4 := 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 {\u03b9 : Type} (\u03c3 : Type) (\u03c4 : \u03b9 \u2192 Type) : Type :=\n(tlocal : \u03c3)\n(shared : memory \u03c4)\n(loads  : set \u03b9 := \u2205)\n(stores : set \u03b9 := \u2205)\n\nnamespace thread_state\n\ndef load (f : \u03c3 \u2192 (\u03a3i:\u03b9, (\u03c4 i \u2192 \u03c3))) (t : thread_state \u03c3 \u03c4) : thread_state \u03c3 \u03c4 :=\nlet \u27e8i, tr\u27e9 := f t.tlocal in\n{ tlocal := tr (t.shared.get i),\n  loads := insert i t.loads,\n  .. t }\n\ndef store (f : \u03c3 \u2192 (\u03a3i:\u03b9, \u03c4 i)) (t : thread_state \u03c3 \u03c4) : thread_state \u03c3 \u03c4 :=\nlet \u27e8i, v\u27e9 := f t.tlocal in\n{ shared := t.shared.update i v,\n  stores := insert i t.stores,\n  .. t}\n\ndef compute (f : \u03c3 \u2192 \u03c3) (t : thread_state \u03c3 \u03c4) : thread_state \u03c3 \u03c4 :=\n{ tlocal := f t.tlocal,\n  .. t}\n\ndef sync (g : memory \u03c4) (t : thread_state \u03c3 \u03c4) : thread_state \u03c3 \u03c4 :=\n{ shared := g,\n  loads := \u2205,\n  stores := \u2205,\n  .. t}\n\ndef accesses (t : thread_state \u03c3 \u03c4) : set \u03b9 := t.stores \u222a t.loads\n\nend thread_state\n\ndef no_thread_active (ac : vector bool n) : bool := \u00acac.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\u2081 or ac\u2082 -/\ndef ac_distinct (ac\u2081 ac\u2082 : vector bool n) : Prop := \u2200 (i : fin n), ac\u2081.nth i = ff \u2228 ac\u2082.nth i = ff\n\ndef ac_ge (ac' : vector bool n) (ac : vector bool n) : Prop := \u2200 (t : fin n), \u00ac (ac.nth t) \u2192 \u00ac (ac'.nth t)\ninstance : has_le (vector bool n) := \u27e8ac_ge\u27e9\n\n/-- shared program state -/\nstructure state {\u03b9 : Type} (n : \u2115) (\u03c3 : Type) (\u03c4 : \u03b9 \u2192 Type) : Type :=\n(threads : vector (thread_state \u03c3 \u03c4) n)\n\nnamespace state\n\ndef map_threads (f : thread_state \u03c3 \u03c4 \u2192 thread_state \u03c3 \u03c4) (s : state n \u03c3 \u03c4) : state n \u03c3 \u03c4 :=\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 \u03c3 \u03c4 \u2192 thread_state \u03c3 \u03c4) (s : state n \u03c3 \u03c4) : state n \u03c3 \u03c4 :=\n{ threads := (s.threads.map\u2082 (\u03bb t (a : bool), if a then f t else t) ac), ..s }\n\ndef active_threads (ac : vector bool n) (s : state n \u03c3 \u03c4) : list (thread_state \u03c3 \u03c4) :=\n((s.threads.map\u2082 prod.mk ac).to_list.filter (\u03bb c : (thread_state \u03c3 \u03c4 \u00d7 bool), c.2)).map (\u03bb \u27e8t, a\u27e9, t)\n\n-- case 1: no thread changed \u03b9 and shadows must be equal at \u03b9\n-- case 2: thread t changed \u03b9 and all other threads must not access \u03b9\ndef syncable (s : state n \u03c3 \u03c4) (m : memory \u03c4) : Prop :=\n\u2200i:\u03b9,\n  (\u2200 tid, i \u2209 (s.threads.nth tid).stores \u2227 m i = (s.threads.nth tid).shared i) \u2228\n  (\u2203 tid, i \u2208 (s.threads.nth tid).stores \u2227 m i = (s.threads.nth tid).shared i \u2227\n    (\u2200 tid', tid \u2260 tid' \u2192 i \u2209 (s.threads.nth tid').accesses))\n\ndef precedes (s u : state n \u03c3 \u03c4) : Prop :=\n\u2200 (t : thread_state \u03c3 \u03c4 \u00d7 thread_state \u03c3 \u03c4), t \u2208 (s.threads.map\u2082 prod.mk u.threads) \u2192 t.1.stores \u2286 t.2.stores \u2227 t.1.loads \u2286 t.2.loads\n\nend state\n\n/-- If condition *f* evaluates to *tt*, the thread is deactivated -/\n@[irreducible]\ndef deactivate_threads (f : \u03c3 \u2192 bool) (ac : vector bool n) (s : state n \u03c3 \u03c4) : vector bool n := \nac.map\u2082 (\u03bb a (ts : thread_state \u03c3 \u03c4), (bnot \u2218 f) ts.tlocal && a) s.threads\n\ndef subkernel (q : kernel \u03c3 \u03c4) : kernel \u03c3 \u03c4 \u2192 Prop\n| (seq k\u2081 k\u2082) := k\u2081 = q \u2228 k\u2082 = q \u2228 subkernel k\u2081 \u2228 subkernel k\u2082\n| (ite c th el) := th = q \u2228 el = q \u2228 subkernel th \u2228 subkernel el\n| (loop c body) := body = q \u2228 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 : \u2115} : kernel \u03c3 \u03c4 \u2192 vector bool n \u2192 state n \u03c3 \u03c4 \u2192 state n \u03c3 \u03c4 \u2192 Prop\n| load (f) (s : state n \u03c3 \u03c4) (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 \u03c3 \u03c4) (ac : vector bool n) :\n  exec_state (store f) ac s (s.map_active_threads ac $ thread_state.store f)\n| compute (f : \u03c3 \u2192 \u03c3) (s : state n \u03c3 \u03c4) (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 \u03c3 \u03c4) (ac : vector bool n) (m : memory \u03c4) (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 \u03c3 \u03c4) (ac : vector bool n) (h : no_thread_active ac) :\n  exec_state sync ac s s\n| seq (s t u : state n \u03c3 \u03c4) (ac : vector bool n) (k\u2081 k\u2082 : kernel \u03c3 \u03c4) :\n  exec_state k\u2081 ac s t \u2192 exec_state k\u2082 ac t u \u2192 exec_state (seq k\u2081 k\u2082) 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 \u03c3 \u03c4) (ac : vector bool n) (f : \u03c3 \u2192 bool) (k\u2081 k\u2082 : kernel \u03c3 \u03c4) :\n  exec_state k\u2081 (deactivate_threads (bnot \u2218 f) ac s) s t \u2192\n  exec_state k\u2082 (deactivate_threads f ac s) t u \u2192\n  exec_state (ite f k\u2081 k\u2082) ac s u\n| loop_stop (s : state n \u03c3 \u03c4) (ac : vector bool n) (f : \u03c3 \u2192 bool) (k : kernel \u03c3 \u03c4) :\n  no_thread_active (deactivate_threads (bnot \u2218 f) ac s) \u2192\n  exec_state (loop f k) ac s s\n| loop_step (s t u : state n \u03c3 \u03c4) (ac : vector bool n) (f : \u03c3 \u2192 bool) (k : kernel \u03c3 \u03c4) :\n  any_thread_active (deactivate_threads (bnot \u2218 f) ac s) \u2192\n  exec_state k (deactivate_threads (bnot \u2218 f) ac s) s t \u2192\n  exec_state (loop f k) (deactivate_threads (bnot \u2218 f) ac s) t u \u2192\n  exec_state (loop f k) ac s u\n\ndef kernel_transform_func (k) (f) (n) (ac) : Prop := \u2200 (s u : state n \u03c3 \u03c4), exec_state k ac s u \u2194 (u = s.map_active_threads ac f)\n\ndef contains_sync : kernel \u03c3 \u03c4 \u2192 Prop\n| (sync) := true\n| (seq k\u2081 k\u2082) := contains_sync k\u2081 \u2228 contains_sync k\u2082\n| (load _) := false\n| (store _) := false\n| (compute _) := false\n| (ite c k\u2081 k\u2082) := contains_sync k\u2081 \u2228 contains_sync k\u2082\n| (loop c k) := contains_sync k\n\ninductive program {\u03b9 : Type} (\u03c3 : Type) (\u03c4 : \u03b9 \u2192 Type)\n| intro (f : memory \u03c4 \u2192 \u2115) (k : kernel \u03c3 \u03c4) : program\n\ndef state_initializer := \u2115 \u2192 \u03c3\n\n@[reducible]\ndef init_state (init : \u2115 \u2192 \u03c3) (f : memory \u03c4 \u2192 \u2115) (m : memory \u03c4) : state (f m) \u03c3 \u03c4 := \n{ threads := (vector.range (f m)).map (\u03bb n, { tlocal := init n, shared := m, loads := \u2205, stores := \u2205 })}\n\ninductive exec_prog : (\u2115 \u2192 \u03c3) \u2192 program \u03c3 \u03c4 \u2192 memory \u03c4 \u2192 memory \u03c4 \u2192 Prop\n| intro (k : kernel \u03c3 \u03c4) (f : memory \u03c4 \u2192 \u2115) (a b : memory \u03c4) (init : \u2115 \u2192 \u03c3) (s' : state (f a) \u03c3 \u03c4) (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 \u03c3 \u03c4)) : kernel \u03c3 \u03c4 := ks.foldl (\u03bb k\u2081 k\u2082, k\u2081 ;; k\u2082) (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 `\u03c8` which is an inductive datatype using a single constructor `mk (a : \u03b1) (b : \u03b2) : \u03c8`.\nLean will automatically make two projection functions `a : \u03c8 \u2192 \u03b1`, `b : \u03c8 \u2192 \u03b2`.\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 := \u27e8implicit_infer_kind.implicit\u27e9\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 \u2192 environment\n/-- Return the trust level of the given environment -/\nmeta constant trust_lvl       : environment \u2192 nat\n/-- Add a new declaration to the environment -/\nmeta constant add             : environment \u2192 declaration \u2192 exceptional environment\n/-- make declaration `n` protected -/\nmeta constant mk_protected   : environment \u2192 name \u2192 environment\n\n/-- add declaration `d` and make it protected -/\nmeta def add_protected (env : environment) (d : declaration) : exceptional environment := do\nenv \u2190 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 \u2192 name \u2192 bool\n/-- Retrieve a declaration from the environment -/\nmeta constant get             : environment \u2192 name \u2192 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) \u00d7 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 \u2192 name \u2192 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 \u2192 name \u2192 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 \u00d7 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 \u00d7 expr) \u00d7 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 \u2192 name \u2192 bool\n/-- Return tt iff the given name is a constructor -/\nmeta constant is_constructor  : environment \u2192 name \u2192 bool\n/-- Return tt iff the given name is a recursor -/\nmeta constant is_recursor     : environment \u2192 name \u2192 bool\n/-- Return tt iff the given name is a recursive inductive datatype -/\nmeta constant is_recursive    : environment \u2192 name \u2192 bool\n/-- Return the name of the inductive datatype of the given constructor. -/\nmeta constant inductive_type_of : environment \u2192 name \u2192 option name\n/-- Return the constructors of the inductive datatype with the given name -/\nmeta constant constructors_of : environment \u2192 name \u2192 list name\n/-- Return the recursor of the given inductive datatype -/\nmeta constant recursor_of     : environment \u2192 name \u2192 option name\n/-- Return the number of parameters of the inductive datatype -/\nmeta constant inductive_num_params : environment \u2192 name \u2192 nat\n/-- Return the number of indices of the inductive datatype -/\nmeta constant inductive_num_indices : environment \u2192 name \u2192 nat\n/-- Return tt iff the inductive datatype recursor supports dependent elimination -/\nmeta constant inductive_dep_elim : environment \u2192 name \u2192 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 \u2192 name \u2192 bool\n/-- See the docstring for `projection_info`. -/\nmeta constant is_projection : environment \u2192 name \u2192 option projection_info\n/-- Fold over declarations in the environment. -/\nmeta constant fold {\u03b1 :Type} : environment \u2192 \u03b1 \u2192 (declaration \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1\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 \u2192 name \u2192 option (nat \u00d7 nat \u00d7 nat)\n/-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/\nmeta constant refl_for : environment \u2192 name \u2192 option name\n/-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/\nmeta constant symm_for : environment \u2192 name \u2192 option name\n/-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/\nmeta constant trans_for : environment \u2192 name \u2192 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 \u2192 name \u2192 option string\n/-- `decl_pos env d` returns the source location of d if available. -/\nmeta constant decl_pos : environment \u2192 name \u2192 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 \u2192 name \u2192 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 \u2192 name \u2192 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 \u2192 name \u2192 name_set\n/-- The fingerprint of the environment is a hash formed from all of the declarations in the environment. -/\nmeta constant fingerprint : environment \u2192 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 \u2192 expr \u2192 expr\nmeta constant unfold_all_macros : environment \u2192 expr \u2192 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 \u00d7 expr \u00d7 expr) :=\nmatch (refl_for env (const_name (get_app_fn e))) with\n| (some n) :=\n    if get_app_num_args e \u2265 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 \u2209 [``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\u27e8\u03bb e, \"[environment]\"\u27e9\n\nmeta instance : inhabited environment :=\n\u27e8environment.mk_std 0\u27e9\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": "/- A transliteration of llvm-pretty https://github.com/elliottt/llvm-pretty/blob/master/src/Text/LLVM/AST.hs -/\n-- import data.bitvec\nimport Std.Data.RBMap\nimport Init.Data.String\nimport Init.Data.Int\n\nopen Std (RBMap)\n\nnamespace LLVM\n\n-- FIXME\n-- def float : Type 0 := sorry\n-- def double : Type 0 := sorry\n\ndef Strmap (a:Type) := RBMap String a Ord.compare\ndef Strmap.empty {a:Type} : Strmap a := Std.RBMap.empty\n\n-- Identifiers -----------------------------------------------------------------\n\ninductive Ident\n| named (nm:String)\n| anon (idx:Nat)\n\nnamespace Ident\n\ndef asString : Ident \u2192 String\n| named nm => \"%\" ++ nm\n| anon i   => \"%\" ++ (Nat.toDigits 10 i).asString\n\nprotected\ndef lt : Ident \u2192 Ident \u2192 Prop\n| named x, named y => x < y\n| named _, anon _  => True\n| anon x,  anon y  => x < y\n| anon _,  named _ => False\n\ninstance : LT Ident := \u27e8Ident.lt\u27e9\n\ninstance decideEq : \u2200(x y:Ident), Decidable (x = y)\n| named a, named b =>\n  match decEq a b with\n  | Decidable.isTrue p  => Decidable.isTrue (congrArg _ p)\n  | Decidable.isFalse p => Decidable.isFalse (fun H => Ident.noConfusion H p)\n| anon a,  anon b =>\n  match decEq a b with\n  | Decidable.isTrue p  => Decidable.isTrue (congrArg _ p)\n  | Decidable.isFalse p => Decidable.isFalse (fun H => Ident.noConfusion H p)\n| anon _,  named _ => Decidable.isFalse (fun H => Ident.noConfusion H)\n| named _, anon _  => Decidable.isFalse (fun H => Ident.noConfusion H)\n\ninstance decideLt : \u2200(x y:Ident), Decidable (x < y)\n| named x, named y =>\n  match String.decLt x y with\n  | Decidable.isTrue  p => Decidable.isTrue p\n  | Decidable.isFalse p => Decidable.isFalse p\n| anon x, anon y =>\n  match Nat.decLt x y with\n  | Decidable.isTrue  p => Decidable.isTrue p\n  | Decidable.isFalse p => Decidable.isFalse p\n| named _, anon _  => Decidable.isTrue True.intro\n| anon _,  named _ => Decidable.isFalse False.elim\n\ninstance : Ord Ident where\n  compare x y :=\n    match x, y with\n    | named x, named y => Ord.compare x y\n    | anon x, anon y => Ord.compare x y\n    | named _, anon _  => Ordering.lt\n    | anon _,  named _ => Ordering.gt\n\nend Ident\n\n-- Data Layout -----------------------------------------------------------------\n\ninductive AlignType\n| integer\n| vector\n| float\n\ninductive Mangling\n| elf\n| mips\n| mach_o\n| windows_coff\n| windows_coff_x86\n\ninductive Endian\n| big\n| little\n\n-- The labels are mainly for documentation, taken from parseSpecifier\ninductive LayoutSpec\n| endianness (e:Endian)\n| pointerSize (address_space : Nat)\n               (size : Nat)\n               (abi_align : Nat)\n               (pref_align : Nat)\n               (index_size : Option Nat)\n| alignSize (type : AlignType) (size : Nat) (abi_align : Nat) (pref_align : Option Nat)\n| nativeIntSize (legal_widths : List Nat)\n| stackAlign    (a:Nat)\n| aggregateAlign (abi_align : Nat) (pref_align:Nat)\n| functionAddressSpace (x:Nat)\n| stackAlloca  (sz:Nat)\n| mangling (m:Mangling)\n\n-- Types -----------------------------------------------------------------------\n\ninductive FloatType\n| half\n| float\n| double\n| fp128\n| x86FP80\n| ppcFP128\n\ninductive PrimType\n| label\n| token\n| void\n| integer (w:Nat)\n| floatType (tp:FloatType)\n| x86mmx\n| metadata\n\nnamespace PrimType\ninstance : Coe FloatType PrimType := \u27e8PrimType.floatType\u27e9\nend PrimType\n\ninductive LLVMType\n| prim (tp:PrimType)\n| alias (nm:String)\n| array (n:Nat) (elt:LLVMType)\n| funType (ret:LLVMType) (args:Array LLVMType) (varargs:Bool)\n| ptr (tp:LLVMType)\n| struct (packed:Bool) (fields:Array LLVMType)\n| vector (n:Nat) (elt:LLVMType)\n\nnamespace LLVMType\ninstance : Coe PrimType LLVMType := \u27e8LLVMType.prim\u27e9\ninstance : Inhabited LLVMType := \u27e8LLVMType.prim PrimType.void\u27e9\nend LLVMType\n\n-- Top-level Type Aliases ------------------------------------------------------\n\ninductive TypeDeclBody\n| opaque\n| defn (tp:LLVMType)\n\nstructure TypeDecl :=\n(name : String)\n(decl : TypeDeclBody)\n\n-- Symbols ---------------------------------------------------------------------\n\nstructure Symbol := (symbol : String)\n\n@[reducible]\ninstance symbolHasLess : LT Symbol := \u27e8 \u03bb(x y:Symbol) => x.symbol < y.symbol \u27e9\n\n@[reducible]\ninstance symbolLtDec (x y:Symbol) : Decidable (x < y) := String.decLt x.symbol y.symbol\n\ninstance : Ord Symbol where\n  compare x y := Ord.compare x.symbol y.symbol\n\nstructure BlockLabel := (label : Ident)\n\nnamespace BlockLabel\n\ninstance decideEq : \u2200(x y : BlockLabel), Decidable (x = y)\n| \u27e8a\u27e9, \u27e8b\u27e9 =>\n  match Ident.decideEq a b with\n  | Decidable.isTrue p  => Decidable.isTrue (congrArg _ p)\n  | Decidable.isFalse p => Decidable.isFalse (\u03bbH => BlockLabel.noConfusion H p)\n\ninstance : Ord BlockLabel where\n  compare x y := Ord.compare x.label y.label\n\nend BlockLabel\n\n\nstructure Typed (a : Type) :=\n  (type  : LLVMType)\n  (value : a)\n\n/-\nnamespace llvm.typed\nlemma sizeof_spec' (a:Type) [has_sizeof a] (x:typed a) :\n  typed.sizeof a x = 1 + sizeof (x.type) + sizeof (x.value) :=\nbegin\n  cases x, unfold typed.sizeof\nend\nend llvm.typed\n-/\n\n-- Instructions ----------------------------------------------------------------\n\ninductive ArithOp\n| add (uoverflow : Bool) (soverflow : Bool)\n| fadd\n| sub (uoverflow : Bool) (soverflow : Bool)\n| fsub\n| mul (uoverflow : Bool) (soverflow : Bool)\n| fmul\n| udiv (exact : Bool)\n| sdiv (exact : Bool)\n| fdiv\n| urem\n| srem\n| frem\n\n-- | binary bitwise operators.\ninductive BitOp\n| shl (uoverflow : Bool) (soverflow : Bool)\n| lshr (exact : Bool)\n| ashr (exact : Bool)\n| and\n| or\n| xor\n\n-- | Conversions from one type to another.\ninductive ConvOp\n| trunc\n| zext\n| sext\n| fp_trunc\n| fp_ext\n| fp_to_ui\n| fp_to_si\n| ui_to_fp\n| si_to_fp\n| ptr_to_int\n| int_to_ptr\n| bit_cast\n\ninductive AtomicRWOp\n| xchg\n| add\n| sub\n| and\n| nand\n| or\n| xor\n| max\n| min\n| u_max\n| u_min\n\n/-- Ordering constraint (https://llvm.org/docs/LangRef.html#ordering) -/\ninductive AtomicOrdering\n| unordered\n| monotonic\n| acquire\n| release\n| acqRel\n| seqCst\n\n-- | Integer comparison operators.\ninductive ICmpOp\n| ieq | ine | iugt | iuge | iult | iule | isgt | isge | islt | isle\n\n-- | Floating-point comparison operators.\ninductive FCmpOp\n| ffalse| foeq | fogt | foge | folt | fole | fone\n| ford  | fueq | fugt | fuge | fult | fule | fune\n| funo  | ftrue\n\n-- Values ----------------------------------------------------------------------\n\n\ninductive Clause : Type\n| catchExc\n| filterExc\n\ndef Float := UInt32\n\ndef Double := UInt64\n\nmutual -- Value ConstExpr, ValMD, and DebugLoc are mutually dependent\n\ninductive Value : Type\n     | integer : Int -> Value\n     | bool : Bool -> Value\n--     | float : Float -> Value\n--     | double : Double -> Value\n     | ident : Ident -> Value\n     | constExpr : ConstExpr -> Value\n     | symbol : Symbol -> Value\n     | null  : Value\n     | array : LLVMType -> Array Value -> Value\n     | vector : LLVMType -> Array Value -> Value\n     | struct : Array (Typed Value) -> Value\n     | packedStruct : Array (Typed Value) -> Value\n     | string : String -> Value -- FIXME, should probably actually be list of word8\n     | undef : Value\n     | label : BlockLabel -> Value\n     | zeroInit : Value\n     | md : ValMD -> Value\n     | asm : Bool -> Bool -> String -> String -> Value -- hasSideEffects isAlignStack asmString constraintString\n\ninductive ConstExpr : Type\n     | select : Typed Value -> Typed Value -> Typed Value -> ConstExpr\n     | gep : Bool -> Option Nat -> LLVMType -> Array (Typed Value) -> ConstExpr\n     | conv : ConvOp -> Typed Value -> LLVMType -> ConstExpr\n     | arith : ArithOp -> Typed Value -> Value -> ConstExpr\n     | fcmp : FCmpOp -> Typed Value -> Typed Value -> ConstExpr\n     | icmp : ICmpOp -> Typed Value -> Typed Value -> ConstExpr\n     | bit : BitOp -> Typed Value -> Value -> ConstExpr\n     | blockAddr : Symbol -> BlockLabel -> ConstExpr\n\ninductive ValMD : Type\n     | string (s:String) : ValMD\n     | value (val:Typed Value) : ValMD\n     | ref (r:Nat) : ValMD\n     | node (l:List (Option ValMD)) : ValMD\n     | loc (l:DebugLoc) : ValMD\n     | debugInfo  : ValMD -- FIXME , just a placeholder for now\n\ninductive DebugLoc : Type\n     | debugLoc (line : Nat) (col : Nat) (scope : ValMD) (IA : Option ValMD) : DebugLoc\n\nend\n\nnamespace Value\n\ninstance : Inhabited Value := \u27e8Value.integer 0\u27e9\n\nend Value\n\ninstance symbolIsValue    : Coe Symbol Value :=\n  \u27e8Value.symbol\u27e9\ninstance constExprIsValue : Coe ConstExpr Value :=\n  \u27e8Value.constExpr\u27e9\n\ninductive Instruction : Type\n| ret (val:Typed Value)\n| retVoid\n| arith (op:ArithOp) (x:Typed Value) (y:Value)\n| bit   (op:BitOp) (x:Typed Value) (y:Value)\n| conv  (op:ConvOp) (x:Typed Value) (res:LLVMType)\n| call (tailcall : Bool) (rtp:Option LLVMType) (fn:Value) (args:Array (Typed Value))\n| alloca (tp:LLVMType) (cnt:Option (Typed Value)) (align:Option Nat)\n| load (addr:Typed Value) (ord:Option AtomicOrdering) (align:Option Nat)\n| store (val:Typed Value) (addr:Typed Value) (align:Option Nat)\n/-\n| fence : option string -> atomic_ordering -> instruction\n| cmp_xchg (weak : bool) (volatile : bool) : Typed Value -> Typed Value -> Typed Value\n            -> option string -> atomic_ordering -> atomic_ordering -> instruction\n| atomic_rw (volatile : bool) : AtomicRWOp -> Typed Value -> Typed Value\n            -> option string -> atomic_ordering -> instruction\n-/\n| icmp (op:ICmpOp) (x:Typed Value) (y:Value)\n| fcmp (op:FCmpOp) (x:Typed Value) (y:Value)\n| phi (tp:LLVMType) (vals:Array (Value \u00d7 BlockLabel))\n| gep (bounds : Bool) (val:Typed Value) (idx:Array (Typed Value))\n| select (c:Typed Value) (t:Typed Value) (f:Value)\n| extractvalue (ag:Typed Value) (idxl:Array Nat)\n| insertvalue (ag:Typed Value) (elt:Typed Value) (idxl:Array Nat)\n| extractelement (vec:Typed Value) (idx:Value)\n| insertelement (vec:Typed Value) (elt:Typed Value) (idx:Value)\n| shufflevector (x:Typed Value) (y:Value) (mask:Typed Value)\n| jump (label:BlockLabel)\n| br (cond:Typed Value) (iftrue iffalse:BlockLabel)\n| invoke (rtype:LLVMType) (fn:Value) (args:List (Typed Value)) (normal unwind:BlockLabel)\n| comment (msg:String)\n| unreachable\n| unwind\n| va_arg (argl:Typed Value) (tp:LLVMType)\n| indirectbr (addr:Typed Value) (allowed:List BlockLabel)\n| switch (idx:Typed Value) (default:BlockLabel) (cases:List (Nat \u00d7 BlockLabel))\n| landingpad (res:LLVMType) (y:Option (Typed Value)) (x:Bool) (clauses:List (Clause \u00d7 Typed Value))\n| resume (exn:Typed Value)\n\n-- Named Metadata --------------------------------------------------------------\n\nstructure NamedMD :=\n(name   : String)\n(values : List Nat)\n\n-- Unnamed Metadata ------------------------------------------------------------\n\nstructure UnnamedMD :=\n(index  : Nat)\n(values : ValMD)\n(distinct : Bool)\n\n-- Comdat ----------------------------------------------------------------------\n\ninductive SelectionKind\n| any\n| exact_match\n| largest\n| no_duplicates\n| same_size\n\ninductive Linkage\n| private_linkage\n| linker_private\n| linker_private_weak\n| linker_private_weak_def_auto\n| internal\n| available_externally\n| linkonce\n| weak\n| common\n| appending\n| extern_weak\n| linkonce_odr\n| weak_odr\n| external\n| dll_import\n| dll_export\n\ninductive Visibility\n| default\n| hidden\n| protected_visibility\n\nstructure GlobalAttrs :=\n(linkage    : Option Linkage)\n(visibility : Option Visibility)\n(const      : Bool)\n\nstructure Global :=\n(sym   : Symbol)\n(attrs : GlobalAttrs)\n(type  : LLVMType)\n(value : Option Value)\n(align : Option Nat)\n(metadata : Strmap ValMD)\n\ninductive FunAttr\n | align_stack (a:Nat)\n | alwaysinline\n | builtin\n | cold\n | inlinehint\n | jumptable\n | minsize\n | naked\n | nobuiltin\n | noduplicate\n | noimplicitfloat\n | noinline\n | nonlazybind\n | noredzone\n | noreturn\n | nounwind\n | optnone\n | optsize\n | readnone\n | readonly\n | returns_twice\n | sanitize_address\n | sanitize_memory\n | sanitize_thread\n | ssp\n | ssp_req\n | ssp_strong\n | uwtable\n\nstructure Declare :=\n(retType : LLVMType)\n(name    : Symbol)\n(args    : Array LLVMType)\n(varArgs : Bool)\n(attrs   : Array FunAttr)\n(comdat  : Option String)\n\nstructure GC := (gc : String)\n\nstructure Stmt :=\n(assign : Option Ident)\n(instr : Instruction)\n(metadata : (Array (String \u00d7 ValMD)))\n\nstructure BasicBlock :=\n(label : BlockLabel)\n(stmts : Array Stmt)\n\nstructure Define :=\n(linkage  : Option Linkage)\n(retType  : LLVMType)\n(name     : Symbol)\n(args     : Array (Typed Ident))\n(varArgs  : Bool)\n(attrs    : Array FunAttr)\n(sec      : Option String)\n(gc       : Option GC)\n(body     : Array BasicBlock)\n(metadata : Strmap ValMD)\n(comdat   : Option String)\n\nstructure GlobalAlias :=\n(name   : Symbol)\n(type   : LLVMType)\n(target : Value)\n\n-- Modules ---------------------------------------------------------------------\nstructure Module :=\n(sourceName : Option String)\n(dataLayout : List LayoutSpec) -- ^ type size and alignment information\n(types      : Array TypeDecl) -- ^ top-level type aliases\n(namedMD    : Array NamedMD)\n(unnamedMD  : Array UnnamedMD)\n(comdat     : Strmap SelectionKind)\n(globals    : Array Global) -- ^ global value declarations\n(declares   : Array Declare) -- ^ external function declarations (without definitions)\n(defines    : Array Define) -- ^ internal function declarations (with definitions)\n(inlineAsm  : Array String)\n(aliases    : Array GlobalAlias)\n\n-- DWARF Debug Info ------------------------------------------------------------\n/-\ndata DebugInfo' lab\n  = DebugInfoBasicType DIBasicType\n| DebugInfoCompileUnit (DICompileUnit' lab)\n| DebugInfoCompositeType (DICompositeType' lab)\n| DebugInfoDerivedType (DIDerivedType' lab)\n| DebugInfoEnumerator String !Int64\n| DebugInfoExpression DIExpression\n| DebugInfoFile DIFile\n| DebugInfoGlobalVariable (DIGlobalVariable' lab)\n| DebugInfoGlobalVariableExpression (DIGlobalVariableExpression' lab)\n| DebugInfoLexicalBlock (DILexicalBlock' lab)\n| DebugInfoLexicalBlockFile (DILexicalBlockFile' lab)\n| DebugInfoLocalVariable (DILocalVariable' lab)\n| DebugInfoSubprogram (DISubprogram' lab)\n| DebugInfoSubrange DISubrange\n| DebugInfoSubroutineType (DISubroutineType' lab)\n| DebugInfoNameSpace (DINameSpace' lab)\n| DebugInfoTemplateTypeParameter (DITemplateTypeParameter' lab)\n| DebugInfoTemplateValueParameter (DITemplateValueParameter' lab)\n| DebugInfoImportedEntity (DIImportedEntity' lab)\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DebugInfo = DebugInfo' BlockLabel\n\ntype DIImportedEntity = DIImportedEntity' BlockLabel\ndata DIImportedEntity' lab = DIImportedEntity\n    { diieTag      :: DwarfTag\n    , diieName     :: String\n    , diieScope    :: Maybe (ValMd' lab)\n    , diieEntity   :: Maybe (ValMd' lab)\n    , diieLine     :: Word32\n    } deriving (Show,Functor,Generic,Generic1)\n\ntype DITemplateTypeParameter = DITemplateTypeParameter' BlockLabel\ndata DITemplateTypeParameter' lab = DITemplateTypeParameter\n    { dittpName :: String\n    , dittpType :: ValMd' lab\n    } deriving (Show,Functor,Generic,Generic1)\n\ntype DITemplateValueParameter = DITemplateValueParameter' BlockLabel\ndata DITemplateValueParameter' lab = DITemplateValueParameter\n    { ditvpName  :: String\n    , ditvpType  :: ValMd' lab\n    , ditvpValue :: ValMd' lab\n    } deriving (Show,Functor,Generic,Generic1)\n\ntype DINameSpace = DINameSpace' BlockLabel\ndata DINameSpace' lab = DINameSpace\n    { dinsName  :: String\n    , dinsScope :: ValMd' lab\n    , dinsFile  :: ValMd' lab\n    , dinsLine  :: Word32\n    } deriving (Show,Functor,Generic,Generic1)\n\n-- TODO: Turn these into sum types\n-- See https://github.com/llvm-mirror/llvm/blob/release_38/include/llvm/Support/Dwarf.def\ntype DwarfAttrEncoding = Word8\ntype DwarfLang = Word16\ntype DwarfTag = Word16\ntype DwarfVirtuality = Word8\n-- See https://github.com/llvm-mirror/llvm/blob/release_38/include/llvm/IR/DebugInfoMetadata.h#L175\ntype DIFlags = Word32\n-- This seems to be defined internally as a small enum, and defined\n-- differently across versions. Maybe turn this into a sum type once\n-- it stabilizes.\ntype DIEmissionKind = Word8\n\ndata DIBasicType = DIBasicType\n  { dibtTag :: DwarfTag\n  , dibtName :: String\n  , dibtSize :: Word64\n  , dibtAlign :: Word64\n  , dibtEncoding :: DwarfAttrEncoding\n  } deriving (Show,Generic)\n\ndata DICompileUnit' lab = DICompileUnit\n  { dicuLanguage           :: DwarfLang\n  , dicuFile               :: Maybe (ValMd' lab)\n  , dicuProducer           :: Maybe String\n  , dicuIsOptimized        :: Bool\n  , dicuFlags              :: Maybe String\n  , dicuRuntimeVersion     :: Word16\n  , dicuSplitDebugFilename :: Maybe FilePath\n  , dicuEmissionKind       :: DIEmissionKind\n  , dicuEnums              :: Maybe (ValMd' lab)\n  , dicuRetainedTypes      :: Maybe (ValMd' lab)\n  , dicuSubprograms        :: Maybe (ValMd' lab)\n  , dicuGlobals            :: Maybe (ValMd' lab)\n  , dicuImports            :: Maybe (ValMd' lab)\n  , dicuMacros             :: Maybe (ValMd' lab)\n  , dicuDWOId              :: Word64\n  , dicuSplitDebugInlining :: Bool\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DICompileUnit = DICompileUnit' BlockLabel\n\ndata DICompositeType' lab = DICompositeType\n  { dictTag            :: DwarfTag\n  , dictName           :: Maybe String\n  , dictFile           :: Maybe (ValMd' lab)\n  , dictLine           :: Word32\n  , dictScope          :: Maybe (ValMd' lab)\n  , dictBaseType       :: Maybe (ValMd' lab)\n  , dictSize           :: Word64\n  , dictAlign          :: Word64\n  , dictOffset         :: Word64\n  , dictFlags          :: DIFlags\n  , dictElements       :: Maybe (ValMd' lab)\n  , dictRuntimeLang    :: DwarfLang\n  , dictVTableHolder   :: Maybe (ValMd' lab)\n  , dictTemplateParams :: Maybe (ValMd' lab)\n  , dictIdentifier     :: Maybe String\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DICompositeType = DICompositeType' BlockLabel\n\ndata DIDerivedType' lab = DIDerivedType\n  { didtTag :: DwarfTag\n  , didtName :: Maybe String\n  , didtFile :: Maybe (ValMd' lab)\n  , didtLine :: Word32\n  , didtScope :: Maybe (ValMd' lab)\n  , didtBaseType :: Maybe (ValMd' lab)\n  , didtSize :: Word64\n  , didtAlign :: Word64\n  , didtOffset :: Word64\n  , didtFlags :: DIFlags\n  , didtExtraData :: Maybe (ValMd' lab)\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DIDerivedType = DIDerivedType' BlockLabel\n\ndata DIExpression = DIExpression\n  { dieElements :: [Word64]\n  }\n  deriving (Show,Generic)\n\ndata DIFile = DIFile\n  { difFilename  :: FilePath\n  , difDirectory :: FilePath\n  } deriving (Show,Generic)\n\ndata DIGlobalVariable' lab = DIGlobalVariable\n  { digvScope                :: Maybe (ValMd' lab)\n  , digvName                 :: Maybe String\n  , digvLinkageName          :: Maybe String\n  , digvFile                 :: Maybe (ValMd' lab)\n  , digvLine                 :: Word32\n  , digvType                 :: Maybe (ValMd' lab)\n  , digvIsLocal              :: Bool\n  , digvIsDefinition         :: Bool\n  , digvVariable             :: Maybe (ValMd' lab)\n  , digvDeclaration          :: Maybe (ValMd' lab)\n  , digvAlignment            :: Maybe Word32\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DIGlobalVariable = DIGlobalVariable' BlockLabel\n\ndata DIGlobalVariableExpression' lab = DIGlobalVariableExpression\n  { digveVariable   :: Maybe (ValMd' lab)\n  , digveExpression :: Maybe (ValMd' lab)\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DIGlobalVariableExpression = DIGlobalVariableExpression' BlockLabel\n\ndata DILexicalBlock' lab = DILexicalBlock\n  { dilbScope  :: Maybe (ValMd' lab)\n  , dilbFile   :: Maybe (ValMd' lab)\n  , dilbLine   :: Word32\n  , dilbColumn :: Word16\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DILexicalBlock = DILexicalBlock' BlockLabel\n\ndata DILexicalBlockFile' lab = DILexicalBlockFile\n  { dilbfScope         :: ValMd' lab\n  , dilbfFile          :: Maybe (ValMd' lab)\n  , dilbfDiscriminator :: Word32\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DILexicalBlockFile = DILexicalBlockFile' BlockLabel\n\ndata DILocalVariable' lab = DILocalVariable\n  { dilvScope :: Maybe (ValMd' lab)\n  , dilvName :: Maybe String\n  , dilvFile :: Maybe (ValMd' lab)\n  , dilvLine :: Word32\n  , dilvType :: Maybe (ValMd' lab)\n  , dilvArg :: Word16\n  , dilvFlags :: DIFlags\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DILocalVariable = DILocalVariable' BlockLabel\n\ndata DISubprogram' lab = DISubprogram\n  { dispScope          :: Maybe (ValMd' lab)\n  , dispName           :: Maybe String\n  , dispLinkageName    :: Maybe String\n  , dispFile           :: Maybe (ValMd' lab)\n  , dispLine           :: Word32\n  , dispType           :: Maybe (ValMd' lab)\n  , dispIsLocal        :: Bool\n  , dispIsDefinition   :: Bool\n  , dispScopeLine      :: Word32\n  , dispContainingType :: Maybe (ValMd' lab)\n  , dispVirtuality     :: DwarfVirtuality\n  , dispVirtualIndex   :: Word32\n  , dispThisAdjustment :: Int64\n  , dispThrownTypes    :: Maybe (ValMd' lab)\n  , dispFlags          :: DIFlags\n  , dispIsOptimized    :: Bool\n  , dispTemplateParams :: Maybe (ValMd' lab)\n  , dispDeclaration    :: Maybe (ValMd' lab)\n  , dispVariables      :: Maybe (ValMd' lab)\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DISubprogram = DISubprogram' BlockLabel\n\ndata DISubrange = DISubrange\n  { disrCount :: Int64\n  , disrLowerBound :: Int64\n  }\n  deriving (Show,Generic)\n\ndata DISubroutineType' lab = DISubroutineType\n  { distFlags :: DIFlags\n  , distTypeArray :: Maybe (ValMd' lab)\n  }\n  deriving (Show,Functor,Generic,Generic1)\n\ntype DISubroutineType = DISubroutineType' BlockLabel\n\n-- Aggregate Utilities ---------------------------------------------------------\n\ndata IndexResult\n  = Invalid                             -- ^ An invalid use of GEP\n| HasType Type                        -- ^ A resolved type\n| Resolve Ident (Type -> IndexResult) -- ^ Continue, after resolving an alias\n\nisInvalid :: IndexResult -> Bool\nisInvalid ir = case ir of\n  Invalid -> True\n  _       -> False\n\n-- | Resolves the type of a GEP instruction. Type aliases are resolved\n-- using the given function. An invalid use of GEP or one relying\n-- on unknown type aliases will return 'Nothing'\nresolveGepFull ::\n(Ident -> Maybe Type) {- ^ Type alias resolution -} ->\n  Type                  {- ^ Pointer type          -} ->\n  [Typed Value]  {- ^ Path                  -} ->\n  Maybe Type            {- ^ Type of result        -}\nresolveGepFull env t ixs = go (resolveGep t ixs)\n  where\n  go Invalid                = Nothing\n  go (HasType result)       = Just result\n  go (Resolve ident resume) = go . resume =<< env ident\n\n\n-- | Resolve the type of a GEP instruction.  Note that the type produced is the\n-- type of the result, not necessarily a pointer.\nresolveGep :: Type -> [Typed Value] -> IndexResult\nresolveGep (PtrTo ty0) (v:ixs0)\n| isGepIndex v =\n    resolveGepBody ty0 ixs0\nresolveGep ty0@PtrTo{} (v:ixs0)\n| Just i <- elimAlias (typedType v) =\n    Resolve i (\\ty' -> resolveGep ty0 (Typed ty' (typedValue v):ixs0))\nresolveGep (Alias i) ixs =\n    Resolve i (\\ty' -> resolveGep ty' ixs)\nresolveGep _ _ = Invalid\n\n-- | Resolve the type of a GEP instruction.  This assumes that the input has\n-- already been processed as a pointer.\nresolveGepBody :: Type -> [Typed Value] -> IndexResult\nresolveGepBody (Struct fs) (v:ixs)\n| Just i <- isGepStructIndex v, genericLength fs > i =\n    resolveGepBody (genericIndex fs i) ixs\nresolveGepBody (PackedStruct fs) (v:ixs)\n| Just i <- isGepStructIndex v, genericLength fs > i =\n    resolveGepBody (genericIndex fs i) ixs\nresolveGepBody (Alias name) is\n| not (null is) =\n    Resolve name (\\ty' -> resolveGepBody ty' is)\nresolveGepBody (Array _ ty') (v:ixs)\n| isGepIndex v =\n    resolveGepBody ty' ixs\nresolveGepBody (Vector _ tp) [val]\n| isGepIndex val =\n    HasType tp\nresolveGepBody ty (v:ixs)\n| Just i <- elimAlias (typedType v) =\n    Resolve i (\\ty' -> resolveGepBody ty (Typed ty' (typedValue v):ixs))\nresolveGepBody ty [] =\n    HasType ty\nresolveGepBody _ _ =\n    Invalid\n\nisGepIndex :: Typed Value -> Bool\nisGepIndex tv =\n  isPrimTypeOf isInteger (typedType tv) ||\n  isVectorOf (isPrimTypeOf isInteger) (typedType tv)\n\nisGepStructIndex :: Typed Value -> Maybe Integer\nisGepStructIndex tv = do\n  guard (isGepIndex tv)\n  elimValInteger (typedValue tv)\n\nresolveValueIndex :: Type -> [Int32] -> IndexResult\nresolveValueIndex ty is@(ix:ixs) = case ty of\n  Struct fs | genericLength fs > ix\n    -> resolveValueIndex (genericIndex fs ix) ixs\n\n  PackedStruct fs | genericLength fs > ix\n    -> resolveValueIndex (genericIndex fs ix) ixs\n\n  Array n ty' | fromIntegral ix < n\n    -> resolveValueIndex ty' ixs\n\n  Alias name\n    -> Resolve name (\\ty' -> resolveValueIndex ty' is)\n\n  _ -> Invalid\nresolveValueIndex ty [] = HasType ty\n-/\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/AST.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.04084571912078294, "lm_q1q2_score": 0.0186720785395084}}
{"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\u2081 v\u2082 u\u2081 u\u2082\n\nnamespace category_theory\n\nopen limits category\n\nvariables {C : Type u\u2081} {D : Type u\u2082} [category.{v\u2081} C] [category.{v\u2081} D] (i : D \u2964 C)\n\ndef coyoneda.ext {X Y : C} (p : \u03a0 {Z : C}, (X \u27f6 Z) \u2243 (Y \u27f6 Z))\n  (n : \u03a0 {Z Z' : C} (f : Z \u27f6 Z') (g : X \u27f6 Z), p (g \u226b f) = p g \u226b f) : X \u2245 Y :=\n{ hom := p.symm (\ud835\udfd9 Y),\n  inv := p (\ud835\udfd9 X),\n  hom_inv_id' := by rw [\u2190 p.injective.eq_iff, n, p.apply_symm_apply, id_comp],\n  inv_hom_id' := by rw [\u2190 n, id_comp, equiv.apply_symm_apply] }\n\nclass in_subcategory (A : C) :=\n(witness : D)\n(iso : i.obj witness \u2245 A)\n\ndef witness_in (A : C) [in_subcategory i A] : D := in_subcategory.witness.{v\u2081} i A\ndef witness_iso (A : C) [in_subcategory i A] : i.obj (witness_in i A) \u2245 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 \u2245 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) \u226b i.map (ir.adj.counit.app B) = \ud835\udfd9 (i.obj B) := ir.adj.right_triangle_components,\n    refine \u27e8i.map (ir.adj.counit.app B), ir.adj.right_triangle_components, _\u27e9,\n    dsimp,\n    rw [\u2190 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) \u27f6 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 := \u27e8ir.adj.unit.app A, split_mono.id (ir.adj.unit.app A)\u27e9,\n  suffices : epi (ir.adj.unit.app A),\n    refine \u27e8h, split_mono.id (ir.adj.unit.app A), _\u27e9,\n    resetI,\n    dsimp,\n    erw [\u2190 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 _ \u226b i.map (ir.left.map h)),\n    erw [\u2190 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 \u2245 A) : in_subcategory' i A :=\n{ returning :=\n  begin\n    apply unit_iso_of_split_mono _,\n    refine \u27e8i.map ((ir.adj.hom_equiv _ _).symm h.inv) \u226b h.hom, _\u27e9,\n    simp,\n  end }\n\n@[reducible]\ndef equiv_homset_left_of_iso\n  {X X' : C} (Y : C) (i : X \u2245 X') :\n  (X \u27f6 Y) \u2243 (X' \u27f6 Y) :=\n{ to_fun := \u03bb f, i.inv \u226b f,\n  inv_fun := \u03bb f, i.hom \u226b f,\n  left_inv := \u03bb f, by simp,\n  right_inv := \u03bb f, by simp }.\n\n@[reducible]\ndef equiv_homset_right_of_iso\n  (X : C) {Y Y' : C} (i : Y \u2245 Y') :\n  (X \u27f6 Y) \u2243 (X \u27f6 Y') :=\n{ to_fun := \u03bb f, f \u226b i.hom,\n  inv_fun := \u03bb f, f \u226b i.inv,\n  left_inv := \u03bb f, by simp,\n  right_inv := \u03bb f, by simp }.\n\nvariable (i)\nnoncomputable\ndef biject_inclusion [ir : reflective i] {A B : C} [in_subcategory' i B] : (A \u27f6 B) \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 B) :=\ncalc (A \u27f6 B) \u2243 (A \u27f6 i.obj ((left_adjoint i).obj B)) : equiv_homset_right_of_iso _ (containment_iso _ _)\n    ... \u2243 ((left_adjoint i).obj A \u27f6 (left_adjoint i).obj B) : (ir.adj.hom_equiv _ _).symm\n    ... \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 i.obj ((left_adjoint i).obj B)) : equiv_of_fully_faithful i\n    ... \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 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 \u27f6 B) (g : B \u27f6 B') :\n  biject_inclusion i (f \u226b g) = biject_inclusion i f \u226b 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 \u226b g) \u226b is_right_adjoint.adj.unit.app B')) \u226b\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 \u226b is_right_adjoint.adj.unit.app B)) \u226b\n         inv (is_right_adjoint.adj.unit.app B)) \u226b\n      g \u2194 _ = _ := (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, \u2190 functor.map_comp],\n  rw [\u2190 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 \u27f6 A') (g : A' \u27f6 B) :\n  biject_inclusion i (f \u226b g) = i.map ((left_adjoint i).map f) \u226b biject_inclusion i g :=\nbegin\n  dsimp [biject_inclusion],\n  erw [\u2190 i.map_comp_assoc, \u2190 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 (\ud835\udfd9 (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 \u03b7 := ir.adj.unit,\n  let \u03b5 := ir.adj.counit,\n  let L := left_adjoint i,\n  have : \ud835\udfd9 (i.obj ((left_adjoint i).obj A)) = _ \u226b inv (is_right_adjoint.adj.unit.app (i.obj ((left_adjoint i).obj A))) \u2194 _ = _ := (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 \u03b7.app (i.obj (L.obj A)) = i.map (L.map (\u03b7.app A \u226b \u03b7.app (i.obj (L.obj A))) \u226b \u03b5.app (L.obj (i.obj (L.obj A)))),\n  rw [L.map_comp, assoc],\n  haveI := nat_iso.is_iso_app_of_is_iso \u03b5 (L.obj A),\n  erw [ir.adj.left_triangle_components, comp_id, \u2190 cancel_mono (i.map (\u03b5.app (L.obj A))), ir.adj.right_triangle_components,\n       \u2190 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) \u27f6 B) :\n  (biject_inclusion i).symm f = ir.adj.unit.app _ \u226b f :=\nby rw [\u2190 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\u2081} C] [has_finite_products.{v\u2081} D] [cartesian_closed C] (i)\n\nclass exponential_ideal extends reflective i :=\n[ strength (A) {B} [in_subcategory' i B] : in_subcategory' i (A \u27f9 B) ]\n\nnoncomputable def exponential_ideal_of [z : reflective i]\n  (h : \u2200 (A : C) (B : D), in_subcategory' i (A \u27f9 i.obj B)) : exponential_ideal i :=\n{ strength := \u03bb A B inst,\n  begin\n    resetI,\n    let ir : is_right_adjoint i := by apply_instance,\n    let L := ir.left,\n    let \u03b7 := ir.adj.unit,\n    haveI := h A (L.obj B),\n    let i\u2081 : B \u2245 i.obj (L.obj B) := containment_iso i B,\n    let i\u2082 : A \u27f9 i.obj (L.obj B) \u2245 i.obj (L.obj (A \u27f9 (i.obj (L.obj B)))) := containment_iso i (A \u27f9 i.obj (L.obj B)),\n    let : A \u27f9 B \u2245 i.obj (L.obj (A \u27f9 B)),\n      apply (exp A).map_iso i\u2081 \u226a\u226b i\u2082 \u226a\u226b (exp A \u22d9 L \u22d9 i).map_iso i\u2081.symm,\n    refine \u27e8_\u27e9,\n    convert is_iso.of_iso this,\n    change \u03b7.app (A \u27f9 B) =\n      (exp _).map (containment_iso _ _).hom \u226b \u03b7.app _ \u226b i.map (L.map ((exp _).map (containment_iso _ _).inv)),\n    erw \u03b7.naturality_assoc,\n    change \u03b7.app (A \u27f9 B) = \u03b7.app (A \u27f9 B) \u226b (exp A \u22d9 L \u22d9 _).map _ \u226b (exp A \u22d9 L \u22d9 _).map _,\n    rw [\u2190 (exp A \u22d9 L \u22d9 _).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 \u2a2f B) \u27f6 C') \u2243 ((left_adjoint i).obj A \u2a2f (left_adjoint i).obj B \u27f6 C') :=\ncalc _ \u2243 (A \u2a2f B \u27f6 i.obj C') : _inst_6.to_reflective.adj.hom_equiv _ _\n... \u2243 (B \u2a2f A \u27f6 i.obj C') : equiv_homset_left_of_iso _ (limits.prod.braiding _ _)\n... \u2243 (A \u27f6 B \u27f9 i.obj C') : (exp.adjunction _).hom_equiv _ _\n... \u2243 (i.obj ((left_adjoint i).obj A) \u27f6 B \u27f9 i.obj C') :\n  begin\n    apply biject_inclusion i,\n    apply exponential_ideal.strength,\n  end\n... \u2243 (B \u2a2f i.obj ((left_adjoint i).obj A) \u27f6 i.obj C') : ((exp.adjunction _).hom_equiv _ _).symm\n... \u2243 (i.obj ((left_adjoint i).obj A) \u2a2f B \u27f6 i.obj C') : equiv_homset_left_of_iso _ (limits.prod.braiding _ _)\n... \u2243 (B \u27f6 i.obj ((left_adjoint i).obj A) \u27f9 i.obj C') : (exp.adjunction _).hom_equiv _ _\n... \u2243 (i.obj ((left_adjoint i).obj B) \u27f6 i.obj ((left_adjoint i).obj A) \u27f9 i.obj C') :\n  begin\n    apply biject_inclusion _,\n    apply exponential_ideal.strength,\n  end\n... \u2243 (i.obj ((left_adjoint i).obj A) \u2a2f i.obj ((left_adjoint i).obj B) \u27f6 i.obj C') : ((exp.adjunction _).hom_equiv _ _).symm\n... \u2243 (i.obj ((left_adjoint i).obj A \u2a2f (left_adjoint i).obj B) \u27f6 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... \u2243 ((left_adjoint i).obj A \u2a2f (left_adjoint i).obj B \u27f6 C') : (equiv_of_fully_faithful _).symm\n\nvariables {i}\n\nlemma comp_inv_eq {X Y Z : C} (f : X \u27f6 Y) (g : Z \u27f6 Y) (h : Z \u27f6 X) [is_iso f] :\n  g \u226b inv f = h \u2194 g = h \u226b f :=\n(as_iso f).comp_inv_eq.\n\n-- @[reassoc] lemma prod_comparison_natural (F : C \u2964 D) {A A' B B' : C} (f : A \u27f6 A') (g : B \u27f6 B') :\n--   F.map (prod.map f g) \u226b prod_comparison F A' B' = prod_comparison F A B \u226b prod.map (F.map f) (F.map g) :=\n\nlemma bijection_id (A B : C) : (bijection i A B _).symm (\ud835\udfd9 _) = 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 \u22a3 i := ir.adj,\n  let \u03b7 : _ \u27f6 L \u22d9 i := adj.unit,\n  let \u03b5 : i \u22d9 L \u27f6 _ := adj.counit,\n  change ((adj.hom_equiv (A \u2a2f B) (L.obj A \u2a2f L.obj B)).symm)\n      (prod.lift limits.prod.snd limits.prod.fst \u226b\n         cartesian_closed.uncurry (\u03b7.app A \u226b\n              cartesian_closed.curry (prod.lift limits.prod.snd limits.prod.fst \u226b\n                   cartesian_closed.uncurry (\u03b7.app B \u226b cartesian_closed.curry _)))) =\n    prod_comparison L A B,\n  rw [uncurry_natural_left, uncurry_curry, uncurry_natural_left, uncurry_curry,\n      \u2190 adjunction.eq_hom_equiv_apply, prod.lift_map_assoc, prod.lift_map_assoc,\n      comp_id, comp_id, \u2190 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, \u2190 i.map_comp, prod.lift_fst],\n  apply \u03b7.naturality,\n  rw [assoc, prod.lift_snd, prod.lift_fst_assoc, assoc, assoc, prod_comparison,\n      prod_comparison, prod.lift_snd, \u2190 i.map_comp, prod.lift_snd],\n  apply \u03b7.naturality,\nend .\n\nlemma bijection_natural (A B : C) (C' C'' : D) (f : ((left_adjoint i).obj (A \u2a2f B) \u27f6 C')) (g : C' \u27f6 C'') : bijection i _ _ _ (f \u226b g) = bijection i _ _ _ f \u226b g :=\nbegin\n  have : i.preimage (i.map g) = g := preimage_map g,\n  conv_rhs {congr, skip, rw \u2190 this},\n  dsimp [bijection],\n  rw [\u2190 preimage_comp, assoc, \u2190 adjunction.hom_equiv_naturality_right_symm,\n      is_right_adjoint.adj.hom_equiv_naturality_right, \u2190 assoc,\n      (exp.adjunction B).hom_equiv_naturality_right, \u2190 biject_inclusion_natural _ _,\n      \u2190 (exp.adjunction (i.obj _)).hom_equiv_naturality_right, assoc,\n      \u2190 (exp.adjunction B).hom_equiv_naturality_right_symm, \u2190 biject_inclusion_natural _ _],\nend\n\nopen limits.prod\n\nnoncomputable\ndef preserves_pair_of_exponential_ideal (A B : C) : preserves_limit (pair.{v\u2081} 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 \u2a2f B) \u2245 L.obj A \u2a2f L.obj B := coyoneda.ext (\u03bb Z, bijection i A B _) (\u03bb _ _ _ _, 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 := \u03bb 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\u1d52\u1d56 \u2964 D) (S : J.cover X) :=\n{ x : \u03a0 (I : S.arrow), P.obj (op I.Y) //\n  \u2200 (I : S.relation), P.map I.g\u2081.op (x I.fst) = P.map I.g\u2082.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\u1d52\u1d56 \u2964 D) (S : J.cover X) : has_coe_to_fun (meq P S)\n  (\u03bb x, \u03a0 (I : S.arrow), P.obj (op I.Y)) := \u27e8\u03bb x, x.1\u27e9\n\n@[ext]\nlemma ext {X} {P : C\u1d52\u1d56 \u2964 D} {S : J.cover X} (x y : meq P S)\n  (h : \u2200 I : S.arrow, x I = y I) : x = y := subtype.ext $ funext $ h\n\nlemma condition {X} {P : C\u1d52\u1d56 \u2964 D} {S : J.cover X} (x : meq P S) (I : S.relation) :\n  P.map I.g\u2081.op (x ((S.index P).fst_to I)) = P.map I.g\u2082.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 \u27f6 T` of covers. -/\ndef refine {X : C} {P : C\u1d52\u1d56 \u2964 D} {S T : J.cover X} (x : meq P T) (e : S \u27f6 T) :\n  meq P S :=\n\u27e8\u03bb I, x \u27e8I.Y, I.f, (le_of_hom e) _ I.hf\u27e9,\n  \u03bb I, x.condition \u27e8I.Y\u2081, I.Y\u2082, I.Z, I.g\u2081, I.g\u2082, I.f\u2081, I.f\u2082,\n    (le_of_hom e) _ I.h\u2081, (le_of_hom e) _ I.h\u2082, I.w\u27e9\u27e9\n\n@[simp]\nlemma refine_apply {X : C} {P : C\u1d52\u1d56 \u2964 D} {S T : J.cover X} (x : meq P T) (e : S \u27f6 T)\n  (I : S.arrow) : x.refine e I = x \u27e8I.Y, I.f, (le_of_hom e) _ I.hf\u27e9 := rfl\n\n/-- Pull back a term of `meq P S` with respect to a morphism `f : Y \u27f6 X` in `C`. -/\ndef pullback {Y X : C} {P : C\u1d52\u1d56 \u2964 D} {S : J.cover X} (x : meq P S) (f : Y \u27f6 X) :\n  meq P ((J.pullback f).obj S) :=\n\u27e8\u03bb I, x \u27e8_,I.f \u226b f, I.hf\u27e9, \u03bb I, x.condition\n  \u27e8I.Y\u2081, I.Y\u2082, I.Z, I.g\u2081, I.g\u2082, I.f\u2081 \u226b f, I.f\u2082 \u226b f, I.h\u2081, I.h\u2082, by simp [reassoc_of I.w]\u27e9 \u27e9\n\n@[simp]\nlemma pullback_apply {Y X : C} {P : C\u1d52\u1d56 \u2964 D} {S : J.cover X} (x : meq P S) (f : Y \u27f6 X)\n  (I : ((J.pullback f).obj S).arrow) : x.pullback f I = x \u27e8_, I.f \u226b f, I.hf\u27e9 := rfl\n\n@[simp]\nlemma pullback_refine {Y X : C} {P : C\u1d52\u1d56 \u2964 D} {S T : J.cover X} (h : S \u27f6 T)\n  (f : Y \u27f6 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\u1d52\u1d56 \u2964 D} (S : J.cover X) (x : P.obj (op X)) : meq P S :=\n\u27e8\u03bb I, P.map I.f.op x, \u03bb I, by { dsimp, simp only [\u2190 comp_apply, \u2190 P.map_comp, \u2190 op_comp, I.w] }\u27e9\n\nlemma mk_apply {X : C} {P : C\u1d52\u1d56 \u2964 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\u1d52\u1d56 \u2964 D) (S : J.cover X) [has_multiequalizer (S.index P)] :\n  (multiequalizer (S.index P) : D) \u2243 meq P S :=\nlimits.concrete.multiequalizer_equiv _\n\n@[simp]\nlemma equiv_apply {X : C} {P : C\u1d52\u1d56 \u2964 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.\u03b9 (S.index P) I x := rfl\n\n@[simp]\nlemma equiv_symm_eq_apply {X : C} {P : C\u1d52\u1d56 \u2964 D} {S : J.cover X} [has_multiequalizer (S.index P)]\n  (x : meq P S) (I : S.arrow) : multiequalizer.\u03b9 (S.index P) I ((meq.equiv P S).symm x) = x I :=\nbegin\n  let z := (meq.equiv P S).symm x,\n  rw \u2190 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 [\u2200 (X : C), has_colimits_of_shape (J.cover X)\u1d52\u1d56 D]\nvariables [\u2200 (P : C\u1d52\u1d56 \u2964 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\u1d52\u1d56 \u2964 D} {S : J.cover X} (x : meq P S) : (J.plus_obj P).obj (op X) :=\ncolimit.\u03b9 (J.diagram P X) (op S) ((meq.equiv P S).symm x)\n\nlemma res_mk_eq_mk_pullback {Y X : C} {P : C\u1d52\u1d56 \u2964 D} {S : J.cover X} (x : meq P S) (f : Y \u27f6 X) :\n  (J.plus_obj P).map f.op (mk x) = mk (x.pullback f) :=\nbegin\n  dsimp [mk, plus_obj],\n  simp only [\u2190 comp_apply, colimit.\u03b9_pre, \u03b9_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, \u2190 comp_apply],\n  erw [multiequalizer.lift_\u03b9, meq.equiv_symm_eq_apply],\n  cases i, refl,\nend\n\nlemma to_plus_mk {X : C} {P : C\u1d52\u1d56 \u2964 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 \u27f6 \u22a4 := hom_of_le (order_top.le_top _),\n  rw \u2190 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 [\u2190 comp_apply, category.assoc, multiequalizer.lift_\u03b9,\n    category.comp_id, meq.equiv_symm_eq_apply],\nend\n\nlemma to_plus_apply {X : C} {P : C\u1d52\u1d56 \u2964 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 [\u2190 comp_apply, colimit.\u03b9_pre, \u03b9_colim_map_assoc],\n  simp only [comp_apply],\n  dsimp only [functor.op],\n  let e : (J.pullback I.f).obj (unop (op S)) \u27f6 \u22a4 := hom_of_le (order_top.le_top _),\n  rw \u2190 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 [\u2190 comp_apply, category.assoc, multiequalizer.lift_\u03b9,\n    category.comp_id, meq.equiv_symm_eq_apply],\n  let RR : S.relation :=\n    \u27e8_, _, _, i.f, \ud835\udfd9 _, I.f, i.f \u226b I.f, I.hf, sieve.downward_closed _ I.hf _, by simp\u27e9,\n  cases I,\n  erw x.condition RR,\n  simpa [RR],\nend\n\nlemma to_plus_eq_mk {X : C} {P : C\u1d52\u1d56 \u2964 D} (x : P.obj (op X)) :\n  (J.to_plus P).app _ x = mk (meq.mk \u22a4 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 \u22a4),\n  ext i,\n  simpa,\nend\n\nvariables [\u2200 (X : C), preserves_colimits_of_shape (J.cover X)\u1d52\u1d56 (forget D)]\n\nlemma exists_rep {X : C} {P : C\u1d52\u1d56 \u2964 D} (x : (J.plus_obj P).obj (op X)) :\n  \u2203 (S : J.cover X) (y : meq P S), x = mk y :=\nbegin\n  obtain \u27e8S,y,h\u27e9 := concrete.colimit_exists_rep (J.diagram P X) x,\n  use [S.unop, meq.equiv _ _ y],\n  rw \u2190 h,\n  dsimp [mk],\n  simp,\nend\n\nlemma eq_mk_iff_exists {X : C} {P : C\u1d52\u1d56 \u2964 D} {S T : J.cover X}\n  (x : meq P S) (y : meq P T) : mk x = mk y \u2194 (\u2203 (W : J.cover X) (h1 : W \u27f6 S) (h2 : W \u27f6 T),\n    x.refine h1 = y.refine h2) :=\nbegin\n  split,\n  { intros h,\n    obtain \u27e8W, h1, h2, hh\u27e9 := concrete.colimit_exists_of_rep_eq _ _ _ h,\n    use [W.unop, h1.unop, h2.unop],\n    ext I,\n    apply_fun (multiequalizer.\u03b9 (W.unop.index P) I) at hh,\n    convert hh,\n    all_goals\n    { dsimp [diagram],\n      simp only [\u2190 comp_apply, multiequalizer.lift_\u03b9, category.comp_id, meq.equiv_symm_eq_apply],\n      cases I, refl } },\n  { rintros \u27e8S,h1,h2,e\u27e9,\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 (\u03bb ee, ee i) at e,\n    convert e,\n    all_goals\n    { dsimp [diagram],\n      simp only [\u2190 comp_apply, multiequalizer.lift_\u03b9, meq.equiv_symm_eq_apply],\n      cases i, refl } },\nend\n\n/-- `P\u207a` is always separated. -/\ntheorem sep {X : C} (P : C\u1d52\u1d56 \u2964 D) (S : J.cover X) (x y : (J.plus_obj P).obj (op X))\n  (h : \u2200 (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 \u27e8Sx,x,rfl\u27e9 := exists_rep x,\n  obtain \u27e8Sy,y,rfl\u27e9 := 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 \u03bb (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 \u27f6 Sx := hom_of_le begin\n    rintros Y f \u27e8Z,e1,e2,he2,he1,hee\u27e9,\n    rw \u2190 hee,\n    apply le_of_hom (h1 \u27e8_, _, he2\u27e9),\n    exact he1,\n  end,\n  let ey : B \u27f6 Sy := hom_of_le begin\n    rintros Y f \u27e8Z,e1,e2,he2,he1,hee\u27e9,\n    rw \u2190 hee,\n    apply le_of_hom (h2 \u27e8_, _, he2\u27e9),\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 (\u03bb e, e IW) at hh,\n  convert hh,\n  { let Rx : Sx.relation := \u27e8I.Y, I.Y, I.Y, \ud835\udfd9 _, \ud835\udfd9 _, I.f,\n      I.to_middle_hom \u226b I.from_middle_hom, _, _, by simp [I.middle_spec]\u27e9,\n    have := x.condition Rx,\n    simpa using this },\n  { let Ry : Sy.relation := \u27e8I.Y, I.Y, I.Y, \ud835\udfd9 _, \ud835\udfd9 _, I.f,\n      I.to_middle_hom \u226b I.from_middle_hom, _, _, by simp [I.middle_spec]\u27e9,\n    have := y.condition Ry,\n    simpa using this },\nend\n\nlemma inj_of_sep (P : C\u1d52\u1d56 \u2964 D) (hsep : \u2200 (X : C) (S : J.cover X) (x y : P.obj (op X)),\n  (\u2200 I : S.arrow, P.map I.f.op x = P.map I.f.op y) \u2192 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 \u27e8W, h1, h2, hh\u27e9 := h,\n  apply hsep X W,\n  intros I,\n  apply_fun (\u03bb 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\u207a`, 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\u1d52\u1d56 \u2964 D)\n  (hsep : \u2200 (X : C) (S : J.cover X) (x y : P.obj (op X)),\n    (\u2200 I : S.arrow, P.map I.f.op x = P.map I.f.op y) \u2192 x = y)\n  (X : C) (S : J.cover X)\n  (s : meq (J.plus_obj P) S)\n  (T : \u03a0 (I : S.arrow), J.cover I.Y)\n  (t : \u03a0 (I : S.arrow), meq P (T I))\n  (ht : \u2200 (I : S.arrow), s I = mk (t I)) : meq P (S.bind T) :=\n{ val := \u03bb I, t I.from_middle I.to_middle,\n  property := begin\n    intros II,\n    apply inj_of_sep P hsep,\n    rw [\u2190 comp_apply, \u2190 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         \u2190 ht, \u2190 ht, \u2190 comp_apply, \u2190 comp_apply, \u2190 (J.plus_obj P).map_comp,\n         \u2190 (J.plus_obj P).map_comp],\n    rw [\u2190 op_comp, \u2190 op_comp],\n    let IR : S.relation :=\n      \u27e8_, _, _, II.g\u2081 \u226b II.fst.to_middle_hom, II.g\u2082 \u226b 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, _\u27e9,\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\u1d52\u1d56 \u2964 D)\n  (hsep : \u2200 (X : C) (S : J.cover X) (x y : P.obj (op X)),\n    (\u2200 I : S.arrow, P.map I.f.op x = P.map I.f.op y) \u2192 x = y)\n  (X : C) (S : J.cover X)\n  (s : meq (J.plus_obj P) S) :\n  \u2203 t : (J.plus_obj P).obj (op X), meq.mk S t = s :=\nbegin\n  have inj : \u2200 (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 \u03bb 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 \u03bb 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\u207a` 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) \u27f6 (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, \ud835\udfd9 _],\n  ext IV,\n  dsimp only [meq.refine_apply, meq.pullback_apply, w],\n  let IA : B.arrow := \u27e8_, (IV.f \u226b II.f) \u226b I.f, _\u27e9,\n  swap,\n  { refine \u27e8I.Y, _, _, I.hf, _, rfl\u27e9,\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 := \u27e8IV.Y, IV.f \u226b II.f, sieve.downward_closed (T I) II.hf IV.f\u27e9,\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, \u2190 ht, \u2190 ht],\n\n  -- Conclude by constructing the relation showing equality...\n  let IR : S.relation := \u27e8_, _, IV.Y, IC.f, ID.f, IB.f, I.f, _, I.hf, IA.middle_spec\u27e9,\n  convert s.condition IR,\n  cases I, refl,\nend\n\nvariable [reflects_isomorphisms (forget D)]\n\n/-- If `P` is separated, then `P\u207a` is a sheaf. -/\ntheorem is_sheaf_of_sep (P : C\u1d52\u1d56 \u2964 D)\n  (hsep : \u2200 (X : C) (S : J.cover X) (x y : P.obj (op X)),\n    (\u2200 I : S.arrow, P.map I.f.op x = P.map I.f.op y) \u2192 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 (\u03bb e, e I) at h,\n    convert h,\n    { erw [meq.equiv_apply, \u2190 comp_apply, multiequalizer.lift_\u03b9] },\n    { erw [meq.equiv_apply, \u2190 comp_apply, multiequalizer.lift_\u03b9] } },\n  { rintros (x : (multiequalizer (S.index _) : D)),\n    obtain \u27e8t,ht\u27e9 := exists_of_sep P hsep X S (meq.equiv _ _ x),\n    use t,\n    apply_fun meq.equiv _ _,\n    swap, { apply_instance },\n    rw \u2190 ht,\n    ext i,\n    dsimp,\n    rw [\u2190 comp_apply, multiequalizer.lift_\u03b9],\n    refl }\nend\n\nvariable (J)\n\n/-- `P\u207a\u207a` is always a sheaf. -/\ntheorem is_sheaf_plus_plus (P : C\u1d52\u1d56 \u2964 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  [\u2200 (P : C\u1d52\u1d56 \u2964 D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]\n  [\u2200 (X : C), has_colimits_of_shape (J.cover X)\u1d52\u1d56 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\u1d52\u1d56 \u2964 D) : C\u1d52\u1d56 \u2964 D := J.plus_obj (J.plus_obj P)\n\n/-- The canonical map from `P` to its sheafification. -/\ndef to_sheafify (P : C\u1d52\u1d56 \u2964 D) : P \u27f6 J.sheafify P :=\nJ.to_plus P \u226b J.plus_map (J.to_plus P)\n\n/-- The canonical map on sheafifications induced by a morphism. -/\ndef sheafify_map {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) : J.sheafify P \u27f6 J.sheafify Q :=\nJ.plus_map $ J.plus_map \u03b7\n\n@[simp]\nlemma sheafify_map_id (P : C\u1d52\u1d56 \u2964 D) : J.sheafify_map (\ud835\udfd9 P) = \ud835\udfd9 (J.sheafify P) :=\nby { dsimp [sheafify_map, sheafify], simp }\n\n@[simp]\nlemma sheafify_map_comp {P Q R : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) (\u03b3 : Q \u27f6 R) :\n  J.sheafify_map (\u03b7 \u226b \u03b3) = J.sheafify_map \u03b7 \u226b J.sheafify_map \u03b3 :=\nby { dsimp [sheafify_map, sheafify], simp }\n\n@[simp, reassoc]\nlemma to_sheafify_naturality {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) :\n  \u03b7 \u226b J.to_sheafify _ = J.to_sheafify _ \u226b J.sheafify_map \u03b7 :=\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\u1d52\u1d56 \u2964 D) \u2964 C\u1d52\u1d56 \u2964 D := (J.plus_functor D \u22d9 J.plus_functor D)\n\n@[simp]\nlemma sheafification_obj (P : C\u1d52\u1d56 \u2964 D) : (J.sheafification D).obj P = J.sheafify P := rfl\n\n@[simp]\nlemma sheafification_map {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) : (J.sheafification D).map \u03b7 =\n  J.sheafify_map \u03b7 := 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 : \ud835\udfed _ \u27f6 sheafification J D :=\nJ.to_plus_nat_trans D \u226b whisker_right (J.to_plus_nat_trans D) (J.plus_functor D)\n\n@[simp]\nlemma to_sheafification_app (P : C\u1d52\u1d56 \u2964 D) : (J.to_sheafification D).app P = J.to_sheafify P := rfl\n\nvariable {D}\n\nlemma is_iso_to_sheafify {P : C\u1d52\u1d56 \u2964 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\u1d52\u1d56 \u2964 D} (hP : presheaf.is_sheaf J P) :\n  P \u2245 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\u1d52\u1d56 \u2964 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 \u27f6 Q`, construct a morphism from\n`J.sheafifcation P` to `Q`. -/\ndef sheafify_lift {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) (hQ : presheaf.is_sheaf J Q) :\n  J.sheafify P \u27f6 Q := J.plus_lift (J.plus_lift \u03b7 hQ) hQ\n\n@[simp, reassoc]\nlemma to_sheafify_sheafify_lift {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) (hQ : presheaf.is_sheaf J Q) :\n  J.to_sheafify P \u226b sheafify_lift J \u03b7 hQ = \u03b7 :=\nby { dsimp only [sheafify_lift, to_sheafify], simp }\n\nlemma sheafify_lift_unique {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) (hQ : presheaf.is_sheaf J Q)\n  (\u03b3 : J.sheafify P \u27f6 Q) :\n  J.to_sheafify P \u226b \u03b3 = \u03b7 \u2192 \u03b3 = sheafify_lift J \u03b7 hQ :=\nbegin\n  intros h,\n  apply plus_lift_unique,\n  apply plus_lift_unique,\n  rw [\u2190 category.assoc, \u2190 plus_map_to_plus],\n  exact h,\nend\n\n@[simp]\nlemma iso_sheafify_inv {P : C\u1d52\u1d56 \u2964 D} (hP : presheaf.is_sheaf J P) :\n  (J.iso_sheafify hP).inv = J.sheafify_lift (\ud835\udfd9 _) hP :=\nbegin\n  apply J.sheafify_lift_unique,\n  simp [iso.comp_inv_eq],\nend\n\nlemma sheafify_hom_ext {P Q : C\u1d52\u1d56 \u2964 D} (\u03b7 \u03b3 : J.sheafify P \u27f6 Q) (hQ : presheaf.is_sheaf J Q)\n  (h : J.to_sheafify P \u226b \u03b7 = J.to_sheafify P \u226b \u03b3) : \u03b7 = \u03b3 :=\nbegin\n  apply J.plus_hom_ext _ _ hQ,\n  apply J.plus_hom_ext _ _ hQ,\n  rw [\u2190 category.assoc, \u2190 category.assoc, \u2190 plus_map_to_plus],\n  exact h,\nend\n\n@[simp, reassoc]\nlemma sheafify_map_sheafify_lift {P Q R : C\u1d52\u1d56 \u2964 D} (\u03b7 : P \u27f6 Q) (\u03b3 : Q \u27f6 R)\n  (hR : presheaf.is_sheaf J R) :\n  J.sheafify_map \u03b7 \u226b J.sheafify_lift \u03b3 hR = J.sheafify_lift (\u03b7 \u226b \u03b3) hR :=\nbegin\n  apply J.sheafify_lift_unique,\n  rw [\u2190 category.assoc, \u2190 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  [\u2200 (P : C\u1d52\u1d56 \u2964 D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]\n  [\u2200 (X : C), has_colimits_of_shape (J.cover X)\u1d52\u1d56 D]\n  [\u2200 (X : C), preserves_colimits_of_shape (J.cover X)\u1d52\u1d56 (forget D)]\n  [reflects_isomorphisms (forget D)]\n\nlemma grothendieck_topology.sheafify_is_sheaf (P : C\u1d52\u1d56 \u2964 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\u1d52\u1d56 \u2964 D) \u2964 Sheaf J D :=\n{ obj := \u03bb P, \u27e8J.sheafify P, J.sheafify_is_sheaf P\u27e9,\n  map := \u03bb P Q \u03b7, \u27e8J.sheafify_map \u03b7\u27e9,\n  map_id' := \u03bb P, Sheaf.hom.ext _ _ $ J.sheafify_map_id _,\n  map_comp' := \u03bb 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' := \u03bb F G, by { ext, erw [colimit.\u03b9_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 \u22a3 Sheaf_to_presheaf J D :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := \u03bb P Q,\n  { to_fun := \u03bb e, J.to_sheafify P \u226b e.val,\n    inv_fun := \u03bb e, \u27e8J.sheafify_lift e Q.2\u27e9,\n    left_inv := \u03bb e, Sheaf.hom.ext _ _ $ (J.sheafify_lift_unique _ _ _ rfl).symm,\n    right_inv := \u03bb e, J.to_sheafify_sheafify_lift _ _ },\n  hom_equiv_naturality_left_symm' := begin\n    intros P Q R \u03b7 \u03b3, ext1, dsimp, symmetry,\n    apply J.sheafify_map_sheafify_lift,\n  end,\n  hom_equiv_naturality_right' := \u03bb P Q R \u03b7 \u03b3, by { dsimp, rw category.assoc } }\n\ninstance Sheaf_to_presheaf_is_right_adjoint : is_right_adjoint (Sheaf_to_presheaf J D) :=\n\u27e8_, sheafification_adjunction J D\u27e9\n\ninstance presheaf_mono_of_mono {F G : Sheaf J D} (f : F \u27f6 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 \u27f6 G) : mono f \u2194 mono f.1 :=\n\u27e8\u03bb m, by { resetI, apply_instance },\n \u03bb m, by { resetI, exact Sheaf.hom.mono_of_presheaf_mono J D f }\u27e9\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 \u2245 (presheaf_to_Sheaf J D).obj P.val :=\n{ hom := \u27e8(J.iso_sheafify P.2).hom\u27e9,\n  inv := \u27e8(J.iso_sheafify P.2).inv\u27e9,\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\u2093'. -/\n/-- A rudimentary hash function on strings. -/\ndef String.hash (s : String) : \u2115 :=\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 \u2192 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 \u2190 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 \u2192 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 \u2190 parser.ident\n  tk \"->\"\n  let to \u2190 parser.many parser.ident\n  let expr.const fr _ \u2190 resolve_name fr\n  let to \u2190 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 \u00d7 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 : \u2115 := 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.<note_name>` 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 \u2190 parser.pexpr\n  let note_name \u2190 eval_pexpr String note_name\n  let some doc_string \u2190 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 \u00d7 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 \u2192 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  \u27e8\u2191doc_category.to_string\u27e9\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 \u2218 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 \u00d7 String) :=\n  \u27e8fun \u27e8doc, desc\u27e9 => json.unparse (doc.to_json desc)\u27e9\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 \u00d7 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 \u2190\n    doc <|> do\n        let inh_id \u2190\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 \u2190 parser.pexpr\n  let e \u2190 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 : \u2115) (f : \u2115 \u2192 \u2115) (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 : \u2115 \u2192 \u2115) (x : \u2115)\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 <https://leanprover-community.github.io/extras/conv.html> 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 : \u2115) (h\u2081 : b = c) (h\u2082 : a + c = a + d) : a + b = a + d :=\nby conv\n{ to_lhs,\n  conv\n  { congr, skip,\n    rw h\u2081 },\n  rw h\u2082, }\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 {\u03c0 \u03b1 : Type} : component \u03c0 \u03b1 :=\ncomponent.ignore_props $ component.mk_simple int int 0 (\u03bb _ x y, (x + y, none)) (\u03bb _ 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 \u2190 parser.ident\n  let n \u2190 resolve_constant n\n  let some doc \u2190 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": "import system.io\nimport tactic.where\nimport tactic.tcache\n\nopen tactic\n\ntheorem lol : 1 + 1 = 2 := begin\n  simp\nend\n\ntheorem lol' (x : \u2115) : 1 = 1 := rfl\n\nrun_cmd (do\n  let n := `lol',\n  e \u2190 get_env,\n  d \u2190 e.get n,\n  let s := expr.deserialise d.type.serialise,\n  let t := expr.deserialise d.value.serialise,\n  -- tactic.trace d.value.serialise,\n  -- tactic.trace $ d.type.to_raw_fmt ++ \"\\n\",\n  -- tactic.trace $ s.to_raw_fmt ++ \"\\n\",\n  -- tactic.trace $ d.value.to_raw_fmt ++ \"\\n\",\n  -- tactic.trace t.to_raw_fmt,\n  e \u2190 e.add $ declaration.thm (n ++ \"v2\") [] s (task.pure t),\n  set_env e\n)\n\nrun_cmd (do\n  e \u2190 get_env,\n  d \u2190 e.get `lol,\n  match d with\n  | declaration.thm n l t v := tactic.trace v.get.to_raw_fmt\n  | _ := skip\n  end\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "khoek", "repo": "leancache", "sha": "5c8329f7b647b8d82966ab180c4473b20d1f249c", "save_path": "github-repos/lean/khoek-leancache", "path": "github-repos/lean/khoek-leancache/leancache-5c8329f7b647b8d82966ab180c4473b20d1f249c/test/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.03846619642746417, "lm_q1q2_score": 0.018632259467350126}}
{"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-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.simp_tactic\nimport Mathlib.Lean3Lib.init.meta.interactive\nimport Mathlib.Lean3Lib.init.meta.congr_lemma\nimport Mathlib.Lean3Lib.init.meta.match_tactic\n \n\nnamespace Mathlib\n\n/-- `conv \u03b1` 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-/\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/converter/conv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.04742587014823578, "lm_q1q2_score": 0.018606915561875714}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Daniel Selsam\n-/\nimport Lean\n\nnamespace Mathlib.Prelude.Rename\n\nopen Lean\nopen System (FilePath)\nopen Lean (HashMap)\n\n/-- This structure keeps track of alignments from lean 3 names to lean 4 names and vice versa. -/\nstructure RenameMap where\n  /-- This maps `n3 \u21a6 (dubious, n4)` where `n3` is the lean 3 name and `n4` is the corresponding\n  lean 4 name. `dubious` is either empty, or a warning message to be displayed when `n3` is\n  translated, which indicates that the translation from `n3` to `n4` is approximate and may cause\n  downstream errors. -/\n  toLean4 : NameMap (String \u00d7 Name) := {}\n  /-- This maps `n4 \u21a6 (n3, clashes)` where `n4` is the lean 4 name and `n3::clashes` is the list of\n  all (non-`synthetic`) declarations that map to `n4`. (That is, we do not assume the mapping\n  from lean 3 to lean 4 name is injective.) -/\n  toLean3 : NameMap (Name \u00d7 List Name) := {}\n  deriving Inhabited\n\n/-- An `olean` entry for the rename extension. -/\nstructure NameEntry where\n  /-- The lean 3 name. -/\n  n3 : Name\n  /-- The lean 4 name, or `.anonymous` for a `#noalign`. -/\n  n4 : Name\n  /-- If true, this lean 3 -> lean 4 mapping will not be entered into the converse map.\n  This is used for \"internal\" definitions that should never be referred to in the source syntax. -/\n  synthetic := false\n  /-- A dubious translation is one where there is a type mismatch\n  from the translated lean 3 definition to a pre-existing lean 4 definition.\n  Type errors are likely in downstream theorems.\n  The string stored here is printed in the event that `n3` is encountered by synport. -/\n  dubious := \"\"\n\n/-- Insert a name entry into the `RenameMap`. -/\ndef RenameMap.insert (m : RenameMap) (e : NameEntry) : RenameMap :=\n  let \u27e8to4, to3\u27e9 := m\n  let to4 := to4.insert e.n3 (e.dubious, e.n4)\n  let to3 := if e.synthetic || e.n4.isAnonymous then to3 else\n    match to3.find? e.n4 with\n    | none => to3.insert e.n4 (e.n3, [])\n    | some (a, l) => if (a::l).contains e.n3 then to3 else to3.insert e.n4 (a, e.n3 :: l)\n  \u27e8to4, to3\u27e9\n\n/-- Look up a lean 4 name from the lean 3 name. Also return the `dubious` error message. -/\ndef RenameMap.find? (m : RenameMap) : Name \u2192 Option (String \u00d7 Name) := m.toLean4.find?\n\ninitialize renameExtension : SimplePersistentEnvExtension NameEntry RenameMap \u2190\n  registerSimplePersistentEnvExtension {\n    addEntryFn := (\u00b7.insert)\n    addImportedFn := mkStateFromImportedEntries (\u00b7.insert) {}\n  }\n\ndef getRenameMap (env : Environment) : RenameMap :=\n  renameExtension.getState env\n\ndef addNameAlignment (n3 : Name) (n4 : Name) (synthetic := false) (dubious := \"\") : CoreM Unit := do\n  modifyEnv fun env \u21a6 renameExtension.addEntry env { n3, n4, synthetic, dubious }\n\n/-- The `@[binport]` attribute should not be added manually, it is added automatically by mathport\nto definitions that it created based on a lean 3 definition (as opposed to pre-existing\ndefinitions). -/\ninitialize binportTag : TagAttribute \u2190\n  registerTagAttribute `binport \"this definition was autogenerated by mathport\"\n\n/--\nRemoves all occurrences of `\u2093` from the name.\nThis is the same processing used by mathport to generate name references,\nand declarations with `\u2093` are used to align declarations that do not defeq match the originals.\n-/\ndef removeX : Name \u2192 Name\n  | .anonymous => .anonymous\n  | .str p s =>\n    let s := if s.contains '\u2093' then\n      s.foldl (fun acc c => if c = '\u2093' then acc else acc.push c) \"\"\n    else s\n    .str (removeX p) s\n  | .num p n => .num (removeX p) n\n\nopen Lean.Elab Lean.Elab.Command\n\n/-- Because lean 3 uses a lowercase snake case convention, it is expected that all lean 3\ndeclaration names should use lowercase, with a few rare exceptions for categories and the set union\noperator. This linter warns if you use uppercase in the lean 3 part of an `#align` statement,\nbecause this is most likely a typo. But if the declaration actually uses capitals it is not unusual\nto disable this lint locally or at file scope. -/\nregister_option linter.uppercaseLean3 : Bool := {\n  defValue := true\n  descr := \"enable the lean 3 casing lint\"\n}\n\n/-- Check that the referenced lean 4 definition exists in an `#align` directive. -/\nregister_option align.precheck : Bool := {\n  defValue := true\n  descr := \"Check that the referenced lean 4 definition exists in an `#align` directive.\"\n}\n\n/--\n`#align lean_3.def_name Lean4.defName` will record an \"alignment\" from the lean 3 name\nto the corresponding lean 4 name. This information is used by the\n[mathport](https://github.com/leanprover-community/mathport) utility to translate later uses of\nthe definition.\n\nIf there is no alignment for a given definition, mathport will attempt to convert\nfrom the lean 3 `snake_case` style to `UpperCamelCase` for namespaces and types and\n`lowerCamelCase` for definitions, and `snake_case` for theorems. But for various reasons,\nit may fail either to determine whether it is a type, definition, or theorem, or to determine\nthat a specific definition is in fact being called. Or a specific definition may need a different\nname altogether because the existing name is already taken in lean 4 for something else. For\nthese reasons, you should use `#align` on any theorem that needs to be renamed from the default.\n-/\nsyntax (name := align) \"#align \" ident ident : command\n\n/-- Checks that `id` has not already been `#align`ed or `#noalign`ed. -/\ndef ensureUnused [Monad m] [MonadEnv m] [MonadError m] (id : Name) : m Unit := do\n  if let some (_, n) := (getRenameMap (\u2190 getEnv)).toLean4.find? id then\n    if n.isAnonymous then\n      throwError \"{id} has already been no-aligned\"\n    else\n      throwError \"{id} has already been aligned (to {n})\"\n\n/--\nPurported Lean 3 names containing capital letters are suspicious.\nHowever, we disregard capital letters occurring in a few common names.\n-/\ndef suspiciousLean3Name (s : String) : Bool := Id.run do\n  let allowed : List String :=\n    [\"Prop\", \"Type\", \"Pi\", \"Exists\", \"End\",\n     \"Inf\", \"Sup\", \"Union\", \"Inter\",\n     \"Ioo\", \"Ico\", \"Iio\", \"Icc\", \"Iic\", \"Ioc\", \"Ici\", \"Ioi\", \"Ixx\"]\n  let mut s := s\n  for a in allowed do\n    s := s.replace a \"\"\n  return s.any (\u00b7.isUpper)\n\n/-- Elaborate an `#align` command. -/\n@[command_elab align] def elabAlign : CommandElab\n  | `(#align $id3:ident $id4:ident) => do\n    if (\u2190 getInfoState).enabled then\n      addCompletionInfo <| CompletionInfo.id id4 id4.getId (danglingDot := false) {} none\n      let c := removeX id4.getId\n      if (\u2190 getEnv).contains c then\n        addConstInfo id4 c none\n      else if align.precheck.get (\u2190 getOptions) then\n        let note := \"(add `set_option align.precheck false` to suppress this message)\"\n        let inner := match \u2190 try some <$> resolveGlobalConstWithInfos id4 catch _ => pure none with\n        | none => m!\"\"\n        | some cs => m!\" Did you mean:\\n\\n{\n            (\"\\n\":MessageData).joinSep (cs.map fun c' => m!\"  #align {id3} {c'}\")\n          }\\n\\n#align inputs have to be fully qualified.{\"\"\n          } (Double check the lean 3 name too, we can't check that!)\"\n        throwErrorAt id4 \"Declaration {c} not found.{inner}\\n{note}\"\n      if Linter.getLinterValue linter.uppercaseLean3 (\u2190 getOptions) then\n        if id3.getId.anyS suspiciousLean3Name then\n          Linter.logLint linter.uppercaseLean3 id3 $\n            \"Lean 3 names are usually lowercase. This might be a typo.\\n\" ++\n            \"If the Lean 3 name is correct, then above this line, add:\\n\" ++\n            \"set_option linter.uppercaseLean3 false in\\n\"\n    withRef id3 <| ensureUnused id3.getId\n    liftCoreM <| addNameAlignment id3.getId id4.getId\n  | _ => throwUnsupportedSyntax\n\n/--\n`#noalign lean_3.def_name` will record that `lean_3.def_name` has been marked for non-porting.\nThis information is used by the [mathport](https://github.com/leanprover-community/mathport)\nutility, which will remove the declaration from the corresponding mathport file, and later\nuses of the definition will be replaced by `sorry`.\n-/\nsyntax (name := noalign) \"#noalign \" ident : command\n\n/-- Elaborate a `#noalign` command. -/\n@[command_elab noalign] def elabNoAlign : CommandElab\n  | `(#noalign $id3:ident) => do\n    withRef id3 <| ensureUnused id3.getId\n    liftCoreM $ addNameAlignment id3.getId .anonymous\n  | _ => throwUnsupportedSyntax\n\n/-- Show information about the alignment status of a lean 3 definition. -/\nsyntax (name := lookup3) \"#lookup3 \" ident : command\n\n/-- Elaborate a `#lookup3` command. -/\n@[command_elab lookup3] def elabLookup3 : CommandElab\n  | `(#lookup3%$tk $id3:ident) => do\n    let n3 := id3.getId\n    let m := getRenameMap (\u2190 getEnv)\n    match m.find? n3 with\n    | none    => logInfoAt tk s!\"name `{n3} not found\"\n    | some (dubious, n4) => do\n      if n4.isAnonymous then\n        logInfoAt tk m!\"{n3} has been no-aligned\"\n      else\n        let mut msg := m!\"{n4}\"\n        if !dubious.isEmpty then\n          msg := msg ++ s!\" (dubious: {dubious})\"\n        logInfoAt tk <|\n          match m.toLean3.find? n4 with\n          | none | some (_, []) => msg\n          | some (n, l) => m!\"{msg} (aliases {n :: l})\"\n  | _ => throwUnsupportedSyntax\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/Mathport/Rename.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776781576105315, "lm_q2_score": 0.06465348745509981, "lm_q1q2_score": 0.018605192866288724}}
{"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 := \u27e8\u03bb _ _ _ _, id\u27e9\ninstance : is_lawful_traversable id := by refine {..}; intros; refl\n\nsection option\n\nopen function functor\n\nsection inst\n\nvariables {F : Type u \u2192 Type v} [applicative F]\n\ninstance : traversable option := \u27e8@option.traverse\u27e9\n\nend inst\n\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {\u03b1} (x : option \u03b1) : option.traverse id.mk x = x :=\nby cases x; refl\n\nlemma option.comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : option \u03b1) :\n  option.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : option \u03b1) :\n  traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nlemma option.naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : option \u03b1) :\n  \u03b7 (option.traverse f x) = option.traverse (@\u03b7 _ \u2218 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 \u2192 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 {\u03b1} (xs : list \u03b1) :\n  list.traverse id.mk xs = xs :=\nby induction xs; simp! * with functor_norm; refl\n\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : list \u03b1) :\n  list.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : list \u03b1) :\n  list.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : list \u03b1) :\n  \u03b7 (list.traverse f x) = list.traverse (@\u03b7 _ \u2218 f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : traversable list := \u27e8@list.traverse\u27e9\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 {\u03b1' \u03b2' : Type u} (f : \u03b1' \u2192 F \u03b2')\n\n@[simp] lemma traverse_nil : traverse f ([] : list \u03b1') = (pure [] : F (list \u03b2')) := rfl\n\n@[simp] lemma traverse_cons (a : \u03b1') (l : list \u03b1') :\n  traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n  \u2200 (as bs : list \u03b1'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n  have has_append.append ([] : list \u03b2') = 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 : \u03b1' \u2192 set \u03b2'} :\n  \u2200(l : list \u03b1') (n : list \u03b2'), n \u2208 traverse f l \u2194 forall\u2082 (\u03bbb a, b \u2208 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 \u03b2') \u2208 traverse f (a :: as) \u2194 b \u2208 f a \u2227 bs \u2208 traverse f as,\n    by simpa [mem_traverse as bs],\n  iff.intro\n    (assume \u27e8_, \u27e8b, hb, rfl\u27e9, _, hl, rfl\u27e9, \u27e8hb, hl\u27e9)\n    (assume \u27e8hb, hl\u27e9, \u27e8_, \u27e8b, hb, rfl\u27e9, _, hl, rfl\u27e9)\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {\u03c3 : Type u}\nvariables {F G : Type u \u2192 Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected def traverse {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) : \u03c3 \u2295 \u03b1 \u2192 F (\u03c3 \u2295 \u03b2)\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 {\u03c3 \u03b1} (x : \u03c3 \u2295 \u03b1) : sum.traverse id.mk x = x :=\nby cases x; refl\n\nprotected lemma comp_traverse {\u03b1 \u03b2 \u03b3} (f : \u03b2 \u2192 F \u03b3) (g : \u03b1 \u2192 G \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (comp.mk \u2218 (<$>) f \u2218 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 {\u03b1 \u03b2} (f : \u03b1 \u2192 \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse (id.mk \u2218 f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {\u03b1 \u03b2 \u03b3} (g : \u03b1 \u2192 G \u03b2) (f : \u03b2 \u2192 \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f \u2218 g) x :=\nby cases x; simp [(<$>), sum.mapr, sum.traverse, id_map] with functor_norm; congr\n\nprotected lemma traverse_map {\u03b1 \u03b2 \u03b3 : Type u} (g : \u03b1 \u2192 \u03b2) (f : \u03b2 \u2192 G \u03b3) (x : \u03c3 \u2295 \u03b1) :\n  sum.traverse f (g <$> x) = sum.traverse (f \u2218 g) x :=\nby cases x; simp [(<$>), sum.mapr, sum.traverse, id_map] with functor_norm\n\nvariable (\u03b7 : applicative_transformation F G)\n\nprotected lemma naturality {\u03b1 \u03b2} (f : \u03b1 \u2192 F \u03b2) (x : \u03c3 \u2295 \u03b1) :\n  \u03b7 (sum.traverse f x) = sum.traverse (@\u03b7 _ \u2218 f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {\u03c3 : Type u} : traversable.{u} (sum \u03c3) := \u27e8@sum.traverse _\u27e9\n\ninstance {\u03c3 : Type u} : is_lawful_traversable.{u} (sum \u03c3) :=\n{ id_traverse := @sum.id_traverse \u03c3,\n  comp_traverse := @sum.comp_traverse \u03c3,\n  traverse_eq_map_id := @sum.traverse_eq_map_id \u03c3,\n  naturality := @sum.naturality \u03c3 }\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": "import Mathlib.Tactic.Trace\n\nexample : True := by\n  trace 2 + 2 + 3\n  trivial\n\nexample : True := by\n  trace \"hello\" ++ \" world\"\n  trivial\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/trace.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.04603390338081226, "lm_q1q2_score": 0.018577757552552625}}
{"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  (\u03b1 : Type) : Type := (x : Unit)\nclass Zoo  (\u03b1 : Type) : Type := (x : Unit)\nclass Bar  (\u03b1 : Type) : Type := (x : Unit)\nclass HasParam (\u03b1 : Type) [Bar \u03b1] : Type := (x : Unit)\n\ninstance FooToBar (\u03b1 : Type) [f : Foo \u03b1] : Bar \u03b1 :=\nmatch f.x with\n| () => {x:=()}\n\ninstance ZooToBar (\u03b1 : Type) [z : Zoo \u03b1] : Bar \u03b1 :=\nmatch z.x with\n| () => {x:=()}\n\ninstance HasParamInst (\u03b1 : Type) [h : Foo \u03b1] : HasParam \u03b1 := {x:=()}\n\nclass Top : Type := (x : Unit)\n\ninstance FooInt : Foo Int := {x:=()}\ninstance AllZoo (\u03b1 : Type) : Zoo \u03b1 := {x:=()}\n\ninstance Bad (\u03b1 : Type) [HasParam \u03b1] : 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": "example (foo bar : Option Nat) : False := by\n  have : do { let x \u2190 bar; foo } = bar >>= fun x => foo := rfl\n  admit\n  done\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/500_lean3.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.042722194042366185, "lm_q1q2_score": 0.018540640350142464}}
{"text": "import tactic.find\n\n#find (ff = _)\n\nconstants \n(f : nat \u2192 nat)\n(f\u2080 : f 0 = 0)\n(f\u2081 : f 1 = 1)\n(f\u2082 : f 2 = 1)\n(f_next : \u2200 n : nat, f (n + 3) = f (n + 2) + f (n + 1) \u2228 f (n + 3) = f (n + 1) + f n)\n\nnamespace evaluation\n\nmeta def hasElement : list nat \u2192 nat \u2192 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 \u2192 list nat \u2192 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 \u2192 nat \u2192 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 \u2260 y) :\n  hasElement (x :: xs) y = hasElement xs y\n\nlemma empty_not_contains_any (x : nat) : \u00ac hasElement [] x = tt :=\nbegin\n  rw hasElement.base _,\n  -- change \u00ac 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 \u2260 y => hasElement [y] y => tt [by single]\n  by_cases (x = y),\n  {\n    rw \u2190h,\n    exact hasElement.step x [x],\n  },\n  {\n    change x \u2260 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 : \u00ac 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 : \u2115} {xs ys : list \u2115}\n\nconstant union : list nat \u2192 list nat \u2192 list nat\n\naxiom union_base (xs : list nat) :\n  union [] xs = xs\n\naxiom union_step\u2081 (h : hasElement ys x) :\n  union (x :: xs) ys = union xs ys\n\naxiom union_step\u2082 (h : hasElement ys x \u2192 false) :\n  union (x :: xs) ys = union xs (x :: ys)\n\n\nlemma union_single : union [x] [x] = [x] :=\nbegin\n  have h\u2081 :                    union []  [x] = [x]          := union_base [x],\n  have h\u2082 : hasElement [x] x \u2192 union [x] [x] = union [] [x] := union_step\u2081,\n  have h\u2083 :                    union [x] [x] = union [] [x] := h\u2082 hasElement.single,\n  apply eq.trans h\u2083,\n  exact h\u2081,\nend\n\nlemma union_single' : union [x] [x] = [x] :=\nbegin\n  rw union_step\u2081,\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 \u2190 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\u2081 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 \u2190 get_local `n\n, trace (infer_type n)\n\nexample (n : nat) : n = n := by { test_tactic, sorry }\n\nexample : (1 = 2) \u2192 (2 = 3) \u2192 (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 \u2190 get_local `a\n  , b \u2190 get_local `b\n  , c \u2190 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 : \u2115) : true := by {\n  do\n    a \u2190 get_local `a\n  , x \u2190 mk_app `nat.succ [a] -- x : expr\n  , r \u2190 to_expr ```(%%x + b * c + (\u03bb n, n) 100) -- to_expr : pexpr \u2192 tactic expr\n  , trace r -- a.succ + b * c + (\u03bb (n : \u2115), n) 100\n  , infer_type r >>= trace -- \u2115\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 \u2192 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]) \u222a (1 + 1) = [2, 3] \u222a [2] = [2, 3]\n\n#print add_lt_add_of_le_of_lt -- a \u2264 b \u2192 c < d \u2192 a + c < b + d\n\n#print add_pos_of_nonneg_of_pos -- 0 \u2264 a \u2192 0 < b \u2192 0 < a + b\n-- (ha : 0 \u2264 a) (hb : 0 < b),\n  -- zero_add 0 \u25b8 add_lt_add_of_le_of_lt ha hb\n\n#print notation \u25b8 -- 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": "example : True := by\n  simp (config := (fun (c : Lean.Meta.Simp.Config) => { c with arith := true }) {})\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/declareConfigElabIssue.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.052618947776520146, "lm_q1q2_score": 0.018532487176375238}}
{"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 \u2192 Y)\n(hf : continuous f)\n(f_flat : \u2200 V : opens Y, G V \u2192 F (hf.comap V))\n(f_flat_is_ring_hom : \u2200 V : opens Y, is_ring_hom (f_flat V))\n(presheaf_f_flat : \u2200 V W : opens Y, \u2200 (hWV : W \u2286 V),\n  \u2200 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 := \u03bb x, x,\n  hf := continuous_id,\n  f_flat := \u03bb U, F.res _ _ (\u03bb _ hx, hx),\n  f_flat_is_ring_hom := \u03bb U, presheaf_of_rings.res_is_ring_hom _ _ _ _,\n  presheaf_f_flat :=  \u03bb U V hVU s, begin\n      rw \u2190F.to_presheaf.Hcomp',\n      rw \u2190F.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 := \u03bb x, b.f (a.f x),\n  hf := b.hf.comp a.hf,\n  f_flat := \u03bb V s, (a.f_flat (b.hf.comap V)) ((b.f_flat V) s),\n  f_flat_is_ring_hom := \u03bb V, show (is_ring_hom ((a.f_flat (b.hf.comap V)) \u2218 (b.f_flat V))), from is_ring_hom.comp _ _,\n  presheaf_f_flat := \u03bb V W hWV s,\n  begin\n    rw \u2190b.presheaf_f_flat V W hWV s,\n    rw \u2190a.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 \u2190 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 \u2192 Y)\n(hf : continuous f)\n(f_flat : \u2200 V : opens Y, G V \u2192 F (hf.comap V))\n[f_flat_is_ring_hom : \u2200 V : opens Y, is_ring_hom (f_flat V)]\n(cont_f_flat : \u2200 V : opens Y, continuous (f_flat V))\n(presheaf_f_flat : \u2200 V W : opens Y, \u2200 (hWV : W \u2286 V),\n  \u2200 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 := \u03bb 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 := \u03bb 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 \u2218 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) \u2192 stalk_of_rings F x :=\nto_stalk.rec G (f.f x) (stalk_of_rings F x)\n  (\u03bb V hfx s, \u27e6\u27e8f.hf.comap V, hfx, f.f_flat V s\u27e9\u27e7)\n  (\u03bb 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 \u2208 V) :\n  is_ring_hom (\u03bb (s : G.F V), (\u27e6\u27e8f.hf.comap V, hfx, f.f_flat V s\u27e9\u27e7 : stalk_of_rings F x)) :=\nbegin\n  show is_ring_hom ((to_stalk F x (f.hf.comap V) hfx) \u2218 (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) \u2218 (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 := \u03bb V, G.F (topological_space.opens.map U V),\n  res := \u03bb V W HWV, G.res _ _ (topological_space.opens.map_mono HWV),\n  Hid := \u03bb V, G.Hid (topological_space.opens.map U V),\n  Hcomp := \u03bb V\u2081 V\u2082 V\u2083 H12 H23, G.Hcomp (topological_space.opens.map U V\u2081)\n    (topological_space.opens.map U V\u2082) (topological_space.opens.map U V\u2083)\n    (topological_space.opens.map_mono H12) (topological_space.opens.map_mono H23),\n  Fring := \u03bb V, G.Fring (topological_space.opens.map U V),\n  res_is_ring_hom := \u03bb 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 \u2192 stalk_of_rings G u :=\nto_stalk.rec (G.restrict U) u (stalk_of_rings G u)\n  (\u03bb V hu, to_stalk G u (topological_space.opens.map U V) ( opens.map_mem_of_mem hu))\n  (\u03bb 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 := \u03bb V, G.Ftop (topological_space.opens.map U V),\n  Ftop_ring := \u03bb V, G.Ftop_ring (topological_space.opens.map U V),\n  res_continuous := \u03bb 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   => \"<unknown>\"\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\u2081 e\u2082 := e\u2081.proof == e\u2082.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 \u2192 Expr \u2192 MetaM Bool\n  | Expr.app f\u2081 a\u2081 _, Expr.app f\u2082 a\u2082 _ => isPerm f\u2081 f\u2082 <&&> isPerm a\u2081 a\u2082\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\u2081 d\u2081 b\u2081 _, Expr.forallE n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.lam n\u2081 d\u2081 b\u2081 _, Expr.lam n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.letE n\u2081 t\u2081 v\u2081 b\u2081 _, Expr.letE n\u2082 t\u2082 v\u2082 b\u2082 _ =>\n    isPerm t\u2081 t\u2082 <&&> isPerm v\u2081 v\u2082 <&&> withLetDecl n\u2081 t\u2081 v\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.proj _ i\u2081 b\u2081 _, Expr.proj _ i\u2082 b\u2082 _ => i\u2081 == i\u2082 <&&> isPerm b\u2081 b\u2082\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 \u00d7 Expr)) := do\n  let type \u2190 whnf type\n  if type.isForall then\n    forallTelescopeReducing type fun xs type => do\n      let e := mkAppN e xs\n      let ps \u2190 preprocess e type inv\n      ps.mapM fun (e, type) =>\n        return (\u2190 mkLambdaFVars xs e, \u2190 mkForallFVars xs type)\n  else if let some (_, lhs, rhs) := type.eq? then\n    if inv then\n      let type \u2190 mkEq rhs lhs\n      let e    \u2190 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 \u2190 mkEq rhs lhs\n      let e    \u2190 mkEqSymm (\u2190 mkPropExt e)\n      return [(e, type)]\n    else\n      let type \u2190 mkEq lhs rhs\n      let e    \u2190 mkPropExt e\n      return [(e, type)]\n  else if let some (_, lhs, rhs) := type.ne? then\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'False'\"\n    let type \u2190 mkEq (\u2190 mkEq lhs rhs) (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some p := type.not? then\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'False'\"\n    let type \u2190 mkEq p (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some (type\u2081, type\u2082) := type.and? then\n    let e\u2081 := mkProj ``And 0 e\n    let e\u2082 := mkProj ``And 1 e\n    return (\u2190 preprocess e\u2081 type\u2081 inv) ++ (\u2190 preprocess e\u2082 type\u2082 inv)\n  else\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'True'\"\n    let type \u2190 mkEq type (mkConst ``True)\n    let e    \u2190 mkEqTrue e\n    return [(e, type)]\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n  unless (\u2190 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 \u2190 instantiateMVars (\u2190 inferType e)\n  withNewMCtxDepth do\n    let (xs, _, type) \u2190 withReducible <| forallMetaTelescopeReducing type\n    let type \u2190 whnfR type\n    let (keys, perm) \u2190\n      match type.eq? with\n      | some (_, lhs, rhs) => pure (\u2190 DiscrTree.mkPath lhs, \u2190 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 \u2190 getConstInfo declName\n  let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n  withReducible do\n    let type \u2190 inferType val\n    checkTypeIsProp type\n    if inv || (\u2190 shouldPreprocess type) then\n      let mut r := #[]\n      for (val, type) in (\u2190 preprocess val type inv) do\n        let auxName \u2190 mkAuxLemma cinfo.levelParams type val\n        r := r.push <| (\u2190 mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n      return r\n    else\n      #[\u2190 mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName]\n\ninductive SimpEntry where\n  | lemma    : SimpLemma \u2192 SimpEntry\n  | toUnfold : Name \u2192 SimpEntry\n  deriving Inhabited\n\nabbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpLemmas\n\ndef SimpExtension.getLemmas (ext : SimpExtension) : CoreM SimpLemmas :=\n  return ext.getState (\u2190 getEnv)\n\ndef addSimpLemma (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n  let simpLemmas \u2190 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 \u2190 getConstInfo declName\n        if (\u2190 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 \u2190 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 \u2190 ext.getState (\u2190 getEnv)\n      let s \u2190 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 \u2190 mkSimpExt extName\n  mkSimpAttr attrName attrDescr ext\n  return ext\n\nbuiltin_initialize simpExtension : SimpExtension \u2190 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 \u2190 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 \u2190 getConstInfo simpLemma.proof.constName!\n    if info.levelParams.isEmpty then\n      return simpLemma.proof\n    else\n      return simpLemma.proof.updateConst! (\u2190 info.levelParams.mapM (fun _ => mkFreshLevelMVar))\n  else\n    let us \u2190 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 \u2190 inferType val\n  checkTypeIsProp type\n  let ps \u2190 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    (\u2190 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 \u2190 mkSimpLemmas levelParams proof post inv prio (\u2190 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 \u2190 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 .run hp.core\n\nnamespace hp.writeup\n\nopen hp\n\n/-- Class predicate (CP). A class predicate is a predicate that can be used to declare a term.\nSo for example, you can say \"Let `f : A \u2192 B` be a function\" or \"Let H be a normal subgroup of G\" or \"Let x, y and z be primes\".\nBut you _can't_ write \"Let `f` be injective on `A`\", you have to write \"Let `f` be a function which is injective on `A`\"\n  the parameter `A` means it doesn't work as an adjective: \"Let `f` be an injective function on `A`\".\nThere are currently 4 different kinds of CP:\n- Adjective a predicate that should be treated as an adjective modifier.\n  Examples are: \"__open__ set\", \"__continuous__ function\", \"__normal__ subgroup\".\n- Fold Adjective is an adjective that applies to a collection of subjects.\n  That is, it is a predicate of type `list subject \u2192 Prop`.\n  Example: \"__parallel__ lines\".\n- SymbolicPostfix are math-mode symbols that can be used to introduce a variable. For example `\u03b5 > 0`, `x y \u2208 A`.\n- ClassNoun are nouns that the given subject _is_. Eg \"f is a __function__\", \"H is a __subgroup of G__\".\n-/\n@[derive_prisms, derive decidable_eq, derive has_to_tactic_format]\nmeta inductive cp\n| Adjective (r : run) -- adjectives must be strictly one word.\n| FoldAdjective (r : run)\n| SymbolicPostfix (e : run)\n| ClassNoun (s p : run) -- \"group\"/\"groups\"\n-- | ClassRelational (s p : run) (rhs : expr) -- \"is/are subset[s] of\" \"element of\" \"function of\". `s` and `p` come with `rhs` baked in but you need `rhs` for merging.\n-- [todo] definite article tricks; \"the least X such that Y\"\n-- [todo] ClassRelation packing; eg\n  -- \"(\u03c3 : \u2115 \u2192 \u2115) (_ : \u2200 n, prime (\u03c3 n))\" \u219d \"let \u03c3 be a sequence of prime numbers\"\n  -- \"(X : set \u2115) (_ : \u2200 x \u2208 X, prime x)\" \u219d \"let X be a set of prime numbers\"\n\n/-- Class predicate collection. A list of class predicates to be rendered together.-/\n@[derive_setters, derive decidable_eq, derive has_to_tactic_format]\nmeta structure cpc :=\n(subjects : list expr)\n(predicates : list cp)\n\n/-- Class predicate collection __list__. -/\n@[reducible]\nmeta def cpcs := list cpc\n\n/-- An apply tree is a record of how an `apply` operation was performed.\nNote that in HP, apply operations also unpack \u2203 and \u2227 propositions and automatically try discharging with `assumption`.\n\n- Match the result was matched directly with the goal, with the given metavariables assigned\n- ExistsElim value a: the applyer had the signature `\u2203 (x : X), P`\n- AndElim value a : applyer had the signature `X \u2227 Y` or `Y \u2227 X`\n- ApplyAssigned arg a; applyer had signature `\u03a0 (x : X), P` and `x` was assigned a value.\n- ApplyGoal g a; applyer had signature `\u03a0 (x : X), P` but `x` was not assigned and hence appears as a new metavariable.\n-/\n@[derive_prisms, derive decidable_eq, derive has_to_tactic_format]\nmeta inductive ApplyTree : Type\n| Match (result : expr) (goal : stub) (setters : list (stub \u00d7 expr))\n| ExistsElim (value : source) : ApplyTree -> ApplyTree\n| AndElim (value : source) : ApplyTree -> ApplyTree\n| ApplyAssigned (argument : expr) : ApplyTree -> ApplyTree\n| ApplyGoal (name : name) (bi : binder_info) (stub : expr) : ApplyTree \u2192 ApplyTree\n\nnamespace ApplyTree\n\nmeta def getChild : ApplyTree \u2192 option ApplyTree\n| (Match result goal setters) := none\n| (ExistsElim value a) := some a\n| (AndElim value a) := some a\n| (ApplyAssigned argument a) := some a\n| (ApplyGoal name bi stub a) := some a\n\nmeta def getAssigned : ApplyTree \u2192 list expr\n| a := (id <| (some list.cons <*> (prod.fst <$> as_ApplyAssigned a))) $ ([] <| (getAssigned <$> getChild a))\n\nmeta def getGoals : ApplyTree \u2192 list expr\n| a := (id <| (some list.cons <*> (as_ApplyGoal a >>= \u03bb \u27e8_,_,s,_\u27e9, some s))) $ ([] <| (getGoals <$> getChild a))\n\nmeta def getSources : ApplyTree \u2192 list source\n| a := (id <| (some list.cons <*> ((as_ExistsElim a <|> as_AndElim a) >>= some \u2218 prod.fst))) $ ([] <| (getSources <$> getChild a))\n\nend ApplyTree\n\n/-- A Statement corresponds to an intra-sentence proposition.\nThe proposition may be object-level or meta/context-level.\n\nA Reason is some additional information that is used to justify statements.\n-/\n@[derive_prisms]\nmeta mutual inductive Reason, Statement\n\nwith Reason : Type\n| BySetting (setters : list (stub \u00d7 expr)) : Reason\n-- \"since A is open, \"\n| Since (smt : Statement) : Reason\n| ofRun : run \u2192 Reason\n-- \"by applying norm_num, \", \"by applying `ring`\"...\n| Tactic : string \u2192 Reason\n-- don't include an explanation\n| Omit\n\nwith Statement : Type\n-- escape hatch for just writing out as string\n| ofRun : run \u2192 Statement\n| TermStatement (type : expr):  Statement\n| CPC (cpc : cpc) : Statement\n| Forall (binders : list cpc) (result : Statement) : Statement\n| Exists (binders : list cpc) (result : Statement) : Statement\n| Implies (premiss concl : Statement) : Statement\n/-- Same as `Implies` but with ordering flipped. -/\n| Whenever (premiss concl : Statement) : Statement\n| And : list Statement \u2192 Statement\n| By (s : Statement) (r : Reason) : Statement\n/-- \"`s` for some `...bs` where `where[bs]`\". This is different to Exists because the 'binders' are already present in the context.\nIt's a meta-level statement about the tactic context rather than a standalone statement.\nThe 'where' are just other facts that might be relevant. -/\n| ForSome (s : Statement) (binders : list cpc) (where : Statement) : Statement\n-- it suffices to find `decls` such that `s`.\n| Suffices (decls : list cpc) (s : Statement) : Statement\n| Have (s : Statement)\n| Provided (s1 s2 : Statement) : Statement\n| Either (ss : list Statement) : Statement\n| WeAreDone : Statement\n\nsection pp\n\nopen tactic Reason Statement format\nmeta mutual def Reason.pp, Statement.pp\n\nwith Reason.pp : Reason \u2192 tactic format\n| (BySetting setters) := nest_join \"BySetting\" $ [pp setters]\n| (Since smt) := nest_join \"Since\" $ [Statement.pp smt]\n| (ofRun r) := nest_join \"ofRun\" $ [pp r]\n| (Tactic t) := format.nest_join \"Tactic\" $ [pp t]\n| (Omit) := format.nest_join \"Omit\" []\n\nwith Statement.pp : Statement \u2192 tactic format\n| (ofRun r) := nest_join \"ofRun\" $ [pp r]\n| (TermStatement t) := nest_join \"TermStatement\" [pp t]\n| (CPC c) := nest_join \"CPC\" [pp c]\n| (Either ss) := nest_join \"Either\" $ list.map Statement.pp ss\n| (And ss) := nest_join \"And\" $ list.map Statement.pp ss\n| (Provided a b) := nest_join \"Provided\" $ list.map Statement.pp [a, b]\n| (Exists cpc b) := nest_join \"Exists\" $ [pp cpc, Statement.pp b]\n| (Forall cpc b) := nest_join \"Forall\" $ [pp cpc, Statement.pp b]\n| (Implies a b) := nest_join \"Implies\" $ list.map Statement.pp [a, b]\n| (Whenever a b) := nest_join \"Whenever\" $ list.map Statement.pp [a, b]\n| (By s r) := nest_join \"By\" $ [Statement.pp s, Reason.pp r]\n| (ForSome s bs where) := nest_join \"ForSome\" $ [Statement.pp s, pp bs, Statement.pp where]\n| (Suffices bs where) := nest_join \"Suffices\" $ [pp bs, Statement.pp where]\n| (Have s) := nest_join \"Have\" $ [Statement.pp s]\n| (WeAreDone) := nest_join \"WeAreDone\" $ []\n\nmeta instance Statement.has_pp : has_to_tactic_format Statement := \u27e8Statement.pp\u27e9\nmeta instance Reason.has_pp : has_to_tactic_format Reason := \u27e8Reason.pp\u27e9\n\nend pp\n\nmeta def Reason.is_Omit : Reason \u2192 bool\n| (Reason.Omit) := tt\n| _ := ff\n\n\n@[derive_prisms, derive has_to_tactic_format]\nmeta inductive Sentence -- [todo] merge with Statement?\n/-- Introduce some variables and assumptions. -/\n| Let (decls : list cpc) (where : Statement) : Sentence\n/-- Restate the target. -/\n| WeNeedToShow : Statement \u2192 Sentence\n/-- Just print the statement. -/\n| BareAssert : Statement \u2192 Sentence\n| ReasonedAssert: Reason \u2192 Statement \u2192 Sentence\n| WeAreDone\n| Suffices (s : Statement) (r : Reason)\n| Therefore : Sentence \u2192 Sentence\n| WeMustChoose (decls : list cpc) : Statement \u2192 Sentence\n/-- \"In the case that ${s}: \" -/\n| InCase (s : Statement) : Sentence\n| LineBreak : Sentence\n\n-- | Since (s : Statement) (r : Reason) (result : Statement) : Sentence\n\n/-- A high-level proof 'move'. The act type for the writeup procedure.\nGiven a stream of acts, one can produce a writeup.\n[todo] rename to `act`. -/\n@[derive_prisms, derive decidable_eq, derive has_to_tactic_format]\nmeta inductive act\n| ProofDone\n| Intro (h : list hyp)\n| Existsi (v : stub) (prop : stub)\n| Andi (l : stub) (r : stub)\n| Apply (target : stub) (src : source) (results : ApplyTree)\n| ExpandTarget\n| TargetTactic (target : stub) (tactic_label : string) (results : ApplyTree)\n/-- You can add a scope to an act to indicate that the microplanner should place it in its own paragraph.-/\n| Scope : binder \u2192 act \u2192 act\n| Cases : list binder \u2192 act\n\nopen tactic\n\nsection\n\nvariables {m : Type \u2192 Type} [monad m] (f : telescope \u2192 expr \u2192 m expr)\n\nmeta def ApplyTree.mmap_exprs : telescope \u2192 ApplyTree \u2192 m ApplyTree\n| \u0393 (ApplyTree.Match result goal setters) := pure ApplyTree.Match <*> assignable.mmap_children f \u0393 result <*> assignable.mmap_children f \u0393 goal <*> assignable.mmap_children f \u0393 setters\n| \u0393 (ApplyTree.ExistsElim value a) := pure ApplyTree.ExistsElim <*> assignable.mmap_children f \u0393 value <*> ApplyTree.mmap_exprs \u0393 a\n| \u0393 (ApplyTree.AndElim value a) := pure ApplyTree.AndElim <*> assignable.mmap_children f \u0393 value <*> ApplyTree.mmap_exprs \u0393 a\n| \u0393 (ApplyTree.ApplyAssigned argument a) := pure ApplyTree.ApplyAssigned <*> assignable.mmap_children f \u0393 argument <*> ApplyTree.mmap_exprs \u0393 a\n| \u0393 (ApplyTree.ApplyGoal name bi stub a) := pure ApplyTree.ApplyGoal <*> pure name <*> pure bi <*> assignable.mmap_children f \u0393  stub <*> ApplyTree.mmap_exprs \u0393 a\n\nmeta def act.mmap_exprs : telescope \u2192 act \u2192 m act\n| \u0393 act.ProofDone := pure act.ProofDone\n| \u0393 (act.Intro a) := pure act.Intro <*> assignable.mmap_children f \u0393 a\n| \u0393 (act.Existsi v prop) := pure act.Existsi <*> assignable.mmap_children f \u0393 v <*> assignable.mmap_children f \u0393 prop\n| \u0393 (act.Andi a b) := pure act.Andi <*> assignable.mmap_children f \u0393 a <*> assignable.mmap_children f \u0393 b\n| \u0393 (act.Apply target src results) := pure act.Apply <*> assignable.mmap_children f \u0393 target <*> assignable.mmap_children f \u0393 src <*> ApplyTree.mmap_exprs f \u0393 results\n| \u0393 act.ExpandTarget := pure act.ExpandTarget\n| \u0393 (act.TargetTactic target tactic_label results) := pure act.TargetTactic <*> assignable.mmap_children f \u0393 target <*> pure tactic_label <*> ApplyTree.mmap_exprs f \u0393 results\n| \u0393 (act.Scope n i) := pure ( act.Scope n ) <*> act.mmap_exprs \u0393 i\n| \u0393 (act.Cases s) := pure (act.Cases) <*> assignable.mmap_children f \u0393 s\n\nend\n\nmeta instance act.assignable : assignable act := \u27e8@act.mmap_exprs\u27e9\nmeta instance ApplyTree.assignable : assignable ApplyTree := \u27e8@ApplyTree.mmap_exprs\u27e9\n\nmeta def cp.pp : cp \u2192 tactic format\n| (cp.Adjective r)       := (format.compose \"Adjective \")       <$> tactic.pp r\n| (cp.FoldAdjective r)   := (format.compose \"FoldAdjective \")   <$> tactic.pp r\n| (cp.SymbolicPostfix e) := (format.compose \"SymbolicPostfix \") <$> tactic.pp e\n| (cp.ClassNoun s p)     := pure (\u03bb s p, \"ClassNoun \" ++ s ++ \" \" ++ p) <*> tactic.pp s <*> tactic.pp p\n-- | (cp.ClassRelational s p rhs) :=  pure (\u03bb s p r, \"ClassRelational \" ++ s ++ \" \" ++ p ++ \" \" ++ r) <*> tactic.pp s <*> tactic.pp p <*> tactic.pp rhs\n\nmeta def cp.to_string : cp \u2192 string\n| (cp.Adjective r)       := (\"Adjective \")       ++ to_string r\n| (cp.FoldAdjective r)   := (\"FoldAdjective \")   ++ to_string r\n| (cp.SymbolicPostfix e) := (\"SymbolicPostfix \") ++ to_string e\n| (cp.ClassNoun s p)     := \"ClassNoun \" ++ to_string s ++ \" \" ++ to_string p\n-- | (cp.ClassRelational s p rhs) :=  \"ClassRelational \" ++ to_string s ++ \" \" ++ to_string p ++ \" \" ++ to_string rhs\n\nmeta instance cp.has_pp : has_to_tactic_format cp := \u27e8cp.pp\u27e9\nmeta instance cp.has_to_string : has_to_string cp := \u27e8cp.to_string\u27e9\n\nmeta def cpc.to_string : cpc \u2192 string\n| \u27e8ss, ps\u27e9 := \"\u27e8\" ++ to_string ss ++ \", \" ++ to_string ps ++ \"\u27e9\"\n\nmeta def cpc.pp : cpc \u2192 tactic format\n| \u27e8ss, ps\u27e9 := do\n  ss \u2190 tactic.pp ss,\n  ps \u2190 tactic.pp ps,\n  pure $ \"\u27e8\" ++ ss ++ \", \" ++ ps ++ \"\u27e9\"\n\nmeta instance cpc.has_pp : has_to_tactic_format cpc := \u27e8cpc.pp\u27e9\n\nmeta instance cpc.has_to_string : has_to_string cpc := \u27e8cpc.to_string\u27e9\n\nmeta def contains_subject : expr \u2192 cpc \u2192 bool\n| e \u27e8xs, _\u27e9 := e \u2208 xs\n\nsection\nvariables {m : Type \u2192 Type} [monad m]\nmeta def cp.mmap_exprs  (f : telescope \u2192 expr \u2192 m expr) : telescope \u2192 cp \u2192 m cp\n| \u0393 (cp.Adjective r) := (pure cp.Adjective) <*> ((\u0393 \u2344 f) r)\n| \u0393 (cp.FoldAdjective r) := (pure cp.FoldAdjective) <*> ((\u0393 \u2344 f) r)\n| \u0393 (cp.SymbolicPostfix r) := (pure cp.SymbolicPostfix) <*> ((\u0393 \u2344 f) r)\n| \u0393 (cp.ClassNoun s p) := pure (cp.ClassNoun s p)\n\nmeta instance cp.has_assignable : assignable cp := \u27e8@cp.mmap_exprs\u27e9\n\nmeta def cpc.mmap_exprs (f : telescope \u2192 expr \u2192 m expr) : telescope \u2192 cpc \u2192 m cpc\n| \u0393 \u27e8subjects, cps\u27e9 := (pure cpc.mk) <*> (list.mmap (f \u0393) subjects) <*> (list.mmap (\u0393 \u2344 f) cps)\n\nmeta instance cpc.has_assignable : assignable cpc := \u27e8@cpc.mmap_exprs\u27e9\n\n-- meta def cpc.cpcs_assignable : assignable cpcs := by apply_instance\n\nend\nend hp.writeup", "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/writeup/data.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.043365796136651424, "lm_q1q2_score": 0.018487774638897943}}
{"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 (\u03b1 : Type u) := (ltb : \u03b1 \u2192 \u03b1 \u2192 bool)\ninstance lt_of_ltb (\u03b1 : Type u) [has_ltb \u03b1] : has_lt \u03b1 := \u27e8\u03bb x y, has_ltb.ltb x y\u27e9\ninstance dec_lt_of_ltb (\u03b1 : Type u) [has_ltb \u03b1] : decidable_rel ((<) : \u03b1 \u2192 \u03b1 \u2192 Prop) := by apply_instance\ninstance le_of_ltb (\u03b1 : Type u) [has_ltb \u03b1] : has_le \u03b1 := \u27e8\u03bb x y, x < y \u2228 x = y\u27e9\ninstance dec_le_of_ltb (\u03b1 : Type u) [has_ltb \u03b1] [decidable_eq \u03b1] : decidable_rel ((\u2264) : \u03b1 \u2192 \u03b1 \u2192 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 {\u03b1}` is a constructor with two arguments,\none being a normal with type \u03b1 and the second being recursive.\n-/\nmeta inductive ind_arg\n| normal : expr \u2192 ind_arg\n| recursive (arg : expr) (rr : expr) : ind_arg\n\nmeta def map_ind_arg (f : pexpr \u2192 pexpr): ind_arg \u2192 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 \u2192 tactic format\n| (ind_arg.normal a) := pp a >>= pure \u2218 (++ \"normal \")\n| (ind_arg.recursive a b) := pure (\u03bb a b, \"rec \" ++ a ++ \" \" ++ b) <*> pp a <*> pp b\n\nmeta instance : has_to_tactic_format ind_arg := \u27e8ind_arg.pp\u27e9\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 \u00d7 list ind_arg \u00d7 list (name \u00d7 expr) ) := do\n    xT \u2190 infer_type x,\n    cs \u2190 induction x,\n    gs \u2190 get_goals,\n    es \u2190 (list.zip cs gs).mmap (\u03bb c, do\n        \u27e8\u27e8n,ls, ss\u27e9, g\u27e9 \u2190 pure c,\n        set_goals [g],\n        e \u2190 resolve_name n >>= pure \u2218 pexpr.mk_explicit >>= to_expr,\n        T \u2190 infer_type e,\n        (ctx,b) \u2190 pure $ telescope.of_pis T,\n        args \u2190 pure $ ls.take $ ctx.length,\n        indos \u2190 pure $ ls.drop $ ctx.length,\n        \u27e8[], acc\u27e9 \u2190 args.mfoldl (\u03bb p a, do\n            \u27e8indos, acc\u27e9 \u2190 pure (p : (list expr) \u00d7 (list ind_arg)),\n            T \u2190 infer_type a,\n            if expr.get_app_fn xT = expr.get_app_fn T then do\n                h::indos \u2190 pure indos,\n                pure (indos, ind_arg.recursive a h :: acc) else\n            pure (indos, ind_arg.normal a :: acc)\n        ) (indos, []),\n        acc \u2190 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 \u2190 get_env,\n        split,\n        x \u2190 intro `x,\n        cs \u2190 induction_but_the_recursors_are_kept_with_the_arguments x,\n        cs.mmap (\u03bb c, do\n            \u27e8n,ls,ss\u27e9 \u2190 pure c,\n            constructor_name \u2190 pure $ reflect $ n.components.ilast,\n            if ls.empty then refine $ ```(to_string %%constructor_name) else do\n            str \u2190 pure $ list.foldl (\u03bb x y, ```(%%x ++ %%y)) ```(\"\") $ list.intersperse ```( \" \" ) $ list.map (\u03bb x, ```( \"(\" ++ %%x ++ \")\" )) $ ls.map (map_ind_arg (\u03bb 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 \u2192 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 \u2190 tactic.pp x,\n        T \u2190 tactic.infer_type x,\n        ppT \u2190 tactic.pp T,\n        msg : format \u2190 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 \u2190 intro `x,\n    cs \u2190 induction_but_the_recursors_are_kept_with_the_arguments x,\n    cs.mmap (\u03bb x, do\n        \u27e8n,ls,ss\u27e9 \u2190 pure x,\n        constructor_name \u2190 pure $ reflect $ n.components.ilast,\n        cnp \u2190 pure $ ```(tactic.pp %%constructor_name), -- : tactic format\n        if ls.empty then refine cnp else do\n        pps \u2190 ls.mmap (\u03bb x, do\n            g \u2190 mk_meta_var `(tactic format),\n            gs \u2190 get_goals,\n            set_goals [g],\n            pp_cases x,\n            set_goals gs,\n            instantiate_mvars g),\n        ppl \u2190 pure $ pps.foldr (\u03bb x acc, ```(%%x :: %%acc)) ```([]),\n        ppl \u2190 pure $ ```(list.mmap id %%ppl), -- : tactic (list format)\n        refine ```(pure (\u03bb 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 \u00d7 ind_arg) \u2192 pexpr \u2192 pexpr\n| (ind_arg.normal a_h, ind_arg.normal b_h) acc :=\n    ```((%%a_h < %%b_h) \u2228 ((%%a_h = %%b_h) \u2227 %%acc))\n| (ind_arg.recursive a_h ai, ind_arg.recursive b_h bi) acc :=\n    ```((%%ai %%b_h) \u2228 ((%%a_h = %%b_h) \u2227 %%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 \u2190 intro `a,\n    a_cs \u2190 induction_but_the_recursors_are_kept_with_the_arguments a,\n    a_goals \u2190 get_goals,\n    (list.zip a_cs a_goals).mmap (\u03bb c, do\n        \u27e8\u27e8a_cn,a_hs,a_subs\u27e9,g\u27e9 \u2190 pure c,\n        b \u2190 intro `b,\n        b_cs \u2190 induction_but_the_recursors_are_kept_with_the_arguments b,\n        b_goals \u2190 get_goals,\n        bz \u2190 pure $ list.zip b_cs b_goals,\n        bz.mmap(\u03bb c, do\n            \u27e8\u27e8b_cn,b_hs,b_subs\u27e9,g\u27e9 \u2190 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 \u2190 pure $ list.foldr lt_cases ```(false) $ list.zip a_hs b_hs,\n            r \u2190 to_expr r,\n            exact r\n        )\n    ),\n    set_goals a_goals,\n    pure ()\n\nprivate meta def ltb_cases : (ind_arg \u00d7 ind_arg) \u2192 pexpr \u2192 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 \u2190 intro `a,\n    (expr.const typename _) \u2190 infer_type a >>= pure \u2218 expr.get_app_fn,\n    e \u2190 get_env,\n    all_cases \u2190 pure $ environment.constructors_of e typename,\n    a_cs \u2190 induction_but_the_recursors_are_kept_with_the_arguments a,\n    a_goals \u2190 get_goals,\n    (list.zip a_cs a_goals).mmap (\u03bb c, do\n        \u27e8\u27e8a_cn,a_hs,a_subs\u27e9,g\u27e9 \u2190 pure c,\n        a_idx \u2190 pure $ list.find_index (= a_cn) all_cases,\n        b \u2190 intro `b,\n        b_cs \u2190 induction_but_the_recursors_are_kept_with_the_arguments b,\n        b_goals \u2190 get_goals,\n        bz \u2190 pure $ list.zip b_cs b_goals,\n        bz.mmap(\u03bb c, do\n            \u27e8\u27e8b_cn,b_hs,b_subs\u27e9,g\u27e9 \u2190 pure c,\n            b_idx \u2190 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 \u2190 pure $ list.foldr ltb_cases ```(ff) $ list.zip a_hs b_hs,\n            r \u2190 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 \u2192 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u2124 \u2115`\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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 \u2192 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 \u2192 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 \u2265, > and \u2260 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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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 (\u2191(x : \u03b1) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nis rewritten to:            op (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nwhen (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) = (\u2191(x : \u03b1) : \u03b3) 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 : \u03b1)` to `((n : \u2115) : \u03b1)` where `n` is a numeral and `\u03b1 \u2260 \u2115`.\nReturns a pair of the new expression and proof that they are equal.\n-/\n/--\nIf possible, rewrite `((n : \u2115) : \u03b1)` to `(n : \u03b1)` 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [has_lift_t \u03b1 \u03b2] {c : Prop} [Decidable c] {a : \u03b1} {b : \u03b1} : \u2191(ite c a b) = ite c \u2191a \u2191b := 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 : \u2124\nh : \u2191a + \u2191b < (10 : \u211a)\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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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": "/-\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.Parser.Term\nimport Lean.Meta.Closure\nimport Lean.Meta.Check\nimport Lean.Elab.Command\nimport Lean.Elab.DefView\nimport Lean.Elab.PreDefinition\nimport Lean.Elab.DeclarationRange\n\nnamespace Lean.Elab\nopen Lean.Parser.Term\n\n/- DefView after elaborating the header. -/\nstructure DefViewElabHeader where\n  ref           : Syntax\n  modifiers     : Modifiers\n  kind          : DefKind\n  shortDeclName : Name\n  declName      : Name\n  levelNames    : List Name\n  numParams     : Nat\n  type          : Expr -- including the parameters\n  valueStx      : Syntax\n  deriving Inhabited\n\nnamespace Term\n\nopen Meta\n\nprivate def checkModifiers (m\u2081 m\u2082 : Modifiers) : TermElabM Unit := do\n  unless m\u2081.isUnsafe == m\u2082.isUnsafe do\n    throwError \"cannot mix unsafe and safe definitions\"\n  unless m\u2081.isNoncomputable == m\u2082.isNoncomputable do\n    throwError \"cannot mix computable and non-computable definitions\"\n  unless m\u2081.isPartial == m\u2082.isPartial do\n    throwError \"cannot mix partial and non-partial definitions\"\n\nprivate def checkKinds (k\u2081 k\u2082 : DefKind) : TermElabM Unit := do\n  unless k\u2081.isExample == k\u2082.isExample do\n    throwError \"cannot mix examples and definitions\" -- Reason: we should discard examples\n  unless k\u2081.isTheorem == k\u2082.isTheorem do\n    throwError \"cannot mix theorems and definitions\" -- Reason: we will eventually elaborate theorems in `Task`s.\n\nprivate def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do\n  if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then\n    throwError \"'unsafe' theorems are not allowed\"\n  if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then\n    throwError \"'partial' theorems are not allowed, 'partial' is a code generation directive\"\n  if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then\n    throwError \"'theorem' subsumes 'noncomputable', code is not generated for theorems\"\n  if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then\n    throwError \"'noncomputable unsafe' is not allowed\"\n  if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then\n    throwError \"'noncomputable partial' is not allowed\"\n  if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then\n    throwError \"'unsafe' subsumes 'partial'\"\n  if h : 0 < prevHeaders.size then\n    let firstHeader := prevHeaders.get \u27e80, h\u27e9\n    try\n      unless newHeader.levelNames == firstHeader.levelNames do\n        throwError \"universe parameters mismatch\"\n      checkModifiers newHeader.modifiers firstHeader.modifiers\n      checkKinds newHeader.kind firstHeader.kind\n    catch\n       | Exception.error ref msg => throw (Exception.error ref m!\"invalid mutually recursive definitions, {msg}\")\n       | ex => throw ex\n  else\n    pure ()\n\nprivate def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit :=\n  registerCustomErrorIfMVar type ref \"failed to infer definition type\"\n\nprivate def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do\n  let mut headers := #[]\n  for view in views do\n    let newHeader \u2190 withRef view.ref do\n      let \u27e8shortDeclName, declName, levelNames\u27e9 \u2190 expandDeclId (\u2190 getCurrNamespace) (\u2190 getLevelNames) view.declId view.modifiers\n      addDeclarationRanges declName view.ref\n      applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration\n      withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <|\n        elabBinders view.binders.getArgs fun xs => do\n          let refForElabFunType := view.value\n          let type \u2190 match view.type? with\n            | some typeStx =>\n              let type \u2190 elabType typeStx\n              registerFailedToInferDefTypeInfo type typeStx\n              pure type\n            | none =>\n              let hole := mkHole refForElabFunType\n              let type \u2190 elabType hole\n              registerFailedToInferDefTypeInfo type refForElabFunType\n              pure type\n          Term.synthesizeSyntheticMVarsNoPostponing\n          let type \u2190 mkForallFVars xs type\n          let type \u2190 mkForallFVars (\u2190 read).autoBoundImplicits.toArray type\n          let type \u2190 instantiateMVars type\n          let xs \u2190 addAutoBoundImplicits xs\n          let levelNames \u2190 getLevelNames\n          if view.type?.isSome then\n            let pendingMVarIds \u2190 getMVars type\n            discard <| logUnassignedUsingErrorInfos pendingMVarIds <|\n              m!\"\\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed\"\n          let newHeader := {\n            ref           := view.ref,\n            modifiers     := view.modifiers,\n            kind          := view.kind,\n            shortDeclName := shortDeclName,\n            declName      := declName,\n            levelNames    := levelNames,\n            numParams     := xs.size,\n            type          := type,\n            valueStx      := view.value : DefViewElabHeader }\n          check headers newHeader\n          pure newHeader\n    headers := headers.push newHeader\n  pure headers\n\nprivate partial def withFunLocalDecls {\u03b1} (headers : Array DefViewElabHeader) (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (fvars : Array Expr) := do\n    if h : i < headers.size then\n      let header := headers.get \u27e8i, h\u27e9\n      withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar)\n    else\n      k fvars\n  loop 0 #[]\n\nprivate def expandWhereDeclsAsStructInst : Macro\n  | `(whereDecls|where $[$decls:letRecDecl$[;]?]*) => do\n    let letIdDecls \u2190 decls.mapM fun stx => match stx with\n      | `(letRecDecl|$attrs:attributes $decl:letDecl) => Macro.throwErrorAt stx \"attributes are 'where' elements are currently not supported here\"\n      | `(letRecDecl|$decl:letPatDecl)  => Macro.throwErrorAt stx \"patterns are not allowed here\"\n      | `(letRecDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl\n      | `(letRecDecl|$decl:letIdDecl)   => pure decl\n      | _                               => Macro.throwUnsupported\n    let structInstFields \u2190 letIdDecls.mapM fun\n      | stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do\n        let mut val := val\n        if let some ty := ty? then\n          val \u2190 `(($val : $ty))\n        val \u2190 if binders.size > 0 then `(fun $[$binders]* => $val:term) else val\n        `(structInstField|$id:ident := $val)\n      | _ => Macro.throwUnsupported\n    `({ $[$structInstFields,]* })\n  | _ => Macro.throwUnsupported\n\n/-\nRecall that\n```\ndef declValSimple    := leading_parser \" :=\\n\" >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef declVal          := declValSimple <|> declValEqns <|> Term.whereDecls\n```\n-/\nprivate def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do\n  if declVal.isOfKind `Lean.Parser.Command.declValSimple then\n    expandWhereDeclsOpt declVal[2] declVal[1]\n  else if declVal.isOfKind `Lean.Parser.Command.declValEqns then\n    expandMatchAltsWhereDecls declVal[0]\n  else if declVal.isOfKind `Lean.Parser.Term.whereDecls then\n    expandWhereDeclsAsStructInst declVal\n  else if declVal.isMissing then\n    Macro.throwErrorAt declVal \"declaration body is missing\"\n  else\n    Macro.throwErrorAt declVal \"unexpected declaration body\"\n\nprivate def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) :=\n  headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do\n    let valStx \u2190 liftMacroM $ declValToTerm header.valueStx\n    forallBoundedTelescope header.type header.numParams fun xs type => do\n      let val \u2190 elabTermEnsuringType valStx type\n      mkLambdaFVars xs val\n\nprivate def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    : StateRefT CollectFVars.State MetaM Unit := do\n  headers.forM fun header => collectUsedFVars header.type\n  values.forM collectUsedFVars\n  toLift.forM fun letRecToLift => do\n    collectUsedFVars letRecToLift.type\n    collectUsedFVars letRecToLift.val\n\nprivate def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed headers values toLift).run {}\n  removeUnused vars used\n\nprivate def withUsed {\u03b1} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnusedVars vars headers values toLift\n  withLCtx lctx localInsts $ k vars\n\nprivate def isExample (views : Array DefView) : Bool :=\n  views.any (\u00b7.kind.isExample)\n\nprivate def isTheorem (views : Array DefView) : Bool :=\n  views.any (\u00b7.kind.isTheorem)\n\nprivate def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do\n  let type \u2190 instantiateMVars header.type\n  pure { header with type := type }\n\nprivate def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do\n  let type \u2190 instantiateMVars toLift.type\n  let val \u2190 instantiateMVars toLift.val\n  pure { toLift with type := type, val := val }\n\nprivate def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId :=\n  let occ? := type.find? fun e => match e with\n    | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId\n    | _ => false\n  match occ? with\n  | some (Expr.fvar fvarId _) => some fvarId\n  | _ => none\n\nprivate def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do\n  match (\u2190 findLocalDecl? fvarId) with\n  | some decl => pure decl.userName\n  | none =>\n    /- Recall that the FVarId of nested let-recs are not in the current local context. -/\n    match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with\n    | none   => throwError \"unknown function\"\n    | some n => pure n\n\n/-\nEnsures that the of let-rec definition types do not contain functions being defined.\nIn principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components.\nHowever, this extra complication doesn't seem worth it.\n-/\nprivate def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit :=\n  letRecsToLift.forM fun toLift =>\n    match typeHasRecFun toLift.type funVars letRecsToLift with\n    | none        => pure ()\n    | some fvarId => do\n      let fnName \u2190 getFunName fvarId letRecsToLift\n      throwErrorAt toLift.ref \"invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously\"\n\nnamespace MutualClosure\n\n/- A mapping from FVarId to Set of FVarIds. -/\nabbrev UsedFVarsMap := NameMap NameSet\n\n/-\nCreate the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of\nfree variables in its definition.\n\nFor `mainFVars`, this is just the set of section variables `sectionVars` used.\nFor nested let-rec functions, we collect their free variables.\n\nRecall that a `let rec` expressions are encoded as follows in the elaborator.\n```lean\nlet rec\n  f : A := t,\n  g : B := s;\nbody\n```\nis encoded as\n```lean\nlet f : A := ?m\u2081;\nlet g : B := ?m\u2082;\nbody\n```\nwhere `?m\u2081` and `?m\u2082` are synthetic opaque metavariables. That are assigned by this module.\nWe may have nested `let rec`s.\n```lean\nlet rec f : A :=\n    let rec g : B := t;\n    s;\nbody\n```\nis encoded as\n```lean\nlet f : A := ?m\u2081;\nbody\n```\nand the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above,\nwe would have a `LetRecToLift` containing:\n```\n{\n  mvarId := m\u2081,\n  val    := `(let g : B := ?m\u2082; body)\n  ...\n}\n```\nNote that `g` is not a free variable at `(let g : B := ?m\u2082; body)`. We recover the fact that\n`f` depends on `g` because it contains `m\u2082`\n-/\nprivate def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift)\n    : UsedFVarsMap := do\n  let mut sectionVarSet := {}\n  for var in sectionVars do\n    sectionVarSet := sectionVarSet.insert var.fvarId!\n  let mut usedFVarMap := {}\n  for mainFVarId in mainFVarIds do\n    usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet\n  for toLift in letRecsToLift do\n    let state := Lean.collectFVars {} toLift.val\n    let state := Lean.collectFVars state toLift.type\n    let mut set := state.fvarSet\n    /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId\n       for the associated let-rec because we need this information to compute the fixpoint later. -/\n    let mvarIds := (toLift.val.collectMVars {}).result\n    for mvarId in mvarIds do\n      match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with\n      | some fvarId => set := set.insert fvarId\n      | none        => pure ()\n    usedFVarMap := usedFVarMap.insert toLift.fvarId set\n  pure usedFVarMap\n\n/-\nThe let-recs may invoke each other. Example:\n```\nlet rec\n  f (x : Nat) := g x + y\n  g : Nat \u2192 Nat\n    | 0   => 1\n    | x+1 => f x + z\n```\n`y` is free variable in `f`, and `z` is a free variable in `g`.\nTo close `f` and `g`, `y` and `z` must be in the closure of both.\nThat is, we need to generate the top-level definitions.\n```\ndef f (y z x : Nat) := g y z x + y\ndef g (y z : Nat) : Nat \u2192 Nat\n  | 0 => 1\n  | x+1 => f y z x + z\n```\n-/\nnamespace FixPoint\n\nstructure State where\n  usedFVarsMap : UsedFVarsMap := {}\n  modified     : Bool         := false\n\nabbrev M := ReaderT (List FVarId) $ StateM State\n\nprivate def isModified : M Bool := do pure (\u2190 get).modified\nprivate def resetModified : M Unit := modify fun s => { s with modified := false }\nprivate def markModified : M Unit := modify fun s => { s with modified := true }\nprivate def getUsedFVarsMap : M UsedFVarsMap := do pure (\u2190 get).usedFVarsMap\nprivate def modifyUsedFVars (f : UsedFVarsMap \u2192 UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap }\n\n-- merge s\u2082 into s\u2081\nprivate def merge (s\u2081 s\u2082 : NameSet) : M NameSet :=\n  s\u2082.foldM (init := s\u2081) fun s\u2081 k => do\n    if s\u2081.contains k then\n      pure s\u2081\n    else\n      markModified\n      pure $ s\u2081.insert k\n\nprivate def updateUsedVarsOf (fvarId : FVarId) : M Unit := do\n  let usedFVarsMap \u2190 getUsedFVarsMap\n  match usedFVarsMap.find? fvarId with\n  | none         => pure ()\n  | some fvarIds =>\n    let fvarIdsNew \u2190 fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' =>\n      if fvarId == fvarId' then\n        pure fvarIdsNew\n      else\n        match usedFVarsMap.find? fvarId' with\n        | none => pure fvarIdsNew\n          /- We are being sloppy here `otherFVarIds` may contain free variables that are\n             not in the context of the let-rec associated with fvarId.\n             We filter these out-of-context free variables later. -/\n        | some otherFVarIds => merge fvarIdsNew otherFVarIds\n    modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew\n\nprivate partial def fixpoint : Unit \u2192 M Unit\n  | _ => do\n    resetModified\n    let letRecFVarIds \u2190 read\n    letRecFVarIds.forM updateUsedVarsOf\n    if (\u2190 isModified) then\n      fixpoint ()\n\ndef run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap :=\n  let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap }\n  s.usedFVarsMap\n\nend FixPoint\n\nabbrev FreeVarMap := NameMap (Array FVarId)\n\nprivate def mkFreeVarMap\n    (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId)\n    (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := do\n  let usedFVarsMap  := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift\n  let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId\n  let usedFVarsMap  := FixPoint.run letRecFVarIds usedFVarsMap\n  let mut freeVarMap := {}\n  for toLift in letRecsToLift do\n    let lctx       := toLift.lctx\n    let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get!\n    let fvarIds    := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId =>\n      if lctx.contains fvarId && !recFVarIds.contains fvarId then\n        fvarIds.push fvarId\n      else\n        fvarIds\n    freeVarMap := freeVarMap.insert toLift.fvarId fvarIds\n  pure freeVarMap\n\nstructure ClosureState where\n  newLocalDecls : Array LocalDecl := #[]\n  localDecls    : Array LocalDecl := #[]\n  newLetDecls   : Array LocalDecl := #[]\n  exprArgs      : Array Expr      := #[]\n\nprivate def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId :=\n  fvarIds.getMax? fun fvarId\u2081 fvarId\u2082 => (lctx.get! fvarId\u2081).index < (lctx.get! fvarId\u2082).index\n\nprivate def preprocess (e : Expr) : TermElabM Expr := do\n  let e \u2190 instantiateMVars e\n  -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.\n  Meta.check e\n  pure e\n\n/- Push free variables in `s` to `toProcess` if they are not already there. -/\nprivate def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId :=\n  s.fvarSet.fold (init := toProcess) fun toProcess fvarId =>\n    if toProcess.contains fvarId then toProcess else toProcess.push fvarId\n\nprivate def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default)\n    : StateRefT ClosureState TermElabM (Array FVarId) := do\n  let type \u2190 preprocess type\n  modify fun s => { s with\n    newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl arbitrary fvarId userName type bi,\n    exprArgs      := s.exprArgs.push (mkFVar fvarId)\n  }\n  pure $ pushNewVars toProcess (collectFVars {} type)\n\nprivate partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do\n  let lctx \u2190 getLCtx\n  match pickMaxFVar? lctx toProcess with\n  | none        => pure ()\n  | some fvarId =>\n    trace[Elab.definition.mkClosure] \"toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}\"\n    let toProcess := toProcess.erase fvarId\n    let localDecl \u2190 getLocalDecl fvarId\n    match localDecl with\n    | LocalDecl.cdecl _ _ userName type bi =>\n      let toProcess \u2190 pushLocalDecl toProcess fvarId userName type bi\n      mkClosureForAux toProcess\n    | LocalDecl.ldecl _ _ userName type val _ =>\n      let zetaFVarIds \u2190 getZetaFVarIds\n      if !zetaFVarIds.contains fvarId then\n        /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/\n        let toProcess \u2190 pushLocalDecl toProcess fvarId userName type\n        mkClosureForAux toProcess\n      else\n        /- Dependent let-decl. -/\n        let type \u2190 preprocess type\n        let val  \u2190 preprocess val\n        modify fun s => { s with\n          newLetDecls   := s.newLetDecls.push $ LocalDecl.ldecl arbitrary fvarId userName type val false,\n          /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId\n             at `newLocalDecls` and `localDecls` -/\n          newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val),\n          localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val)\n        }\n        mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val))\n\nprivate partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do\n  let (_, s) \u2190 (mkClosureForAux freeVars).run { localDecls := localDecls }\n  pure { s with\n    newLocalDecls := s.newLocalDecls.reverse,\n    newLetDecls   := s.newLetDecls.reverse,\n    exprArgs      := s.exprArgs.reverse\n  }\n\nstructure LetRecClosure where\n  ref        : Syntax\n  localDecls : Array LocalDecl\n  closed     : Expr -- expression used to replace occurrences of the let-rec FVarId\n  toLift     : LetRecToLift\n\nprivate def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do\n  let lctx := toLift.lctx\n  withLCtx lctx toLift.localInstances do\n  lambdaTelescope toLift.val fun xs val => do\n    let type \u2190 instantiateForall toLift.type xs\n    let lctx \u2190 getLCtx\n    let s \u2190 mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId!\n    let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type\n    let val  := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val\n    let c    := mkAppN (Lean.mkConst toLift.declName) s.exprArgs\n    assignExprMVar toLift.mvarId c\n    return {\n      ref        := toLift.ref\n      localDecls := s.newLocalDecls\n      closed     := c\n      toLift     := { toLift with val := val, type := type }\n    }\n\nprivate def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) :=\n  letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get!\n\n/- Mapping from FVarId of mutually recursive functions being defined to \"closure\" expression. -/\nabbrev Replacement := NameMap Expr\n\ndef insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement :=\n  mainFVars.size.fold (init := r) fun i r =>\n    r.insert mainFVars[i].fvarId! (mkAppN (Lean.mkConst mainHeaders[i].declName) sectionVars)\n\n\ndef insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement :=\n  letRecClosures.foldl (init := r) fun r c =>\n    r.insert c.toLift.fvarId c.closed\n\ndef Replacement.apply (r : Replacement) (e : Expr) : Expr :=\n  e.replace fun e => match e with\n    | Expr.fvar fvarId _ => match r.find? fvarId with\n      | some c => some c\n      | _      => none\n    | _ => none\n\ndef pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr)\n    : TermElabM (Array PreDefinition) :=\n  mainHeaders.size.foldM (init := preDefs) fun i preDefs => do\n    let header := mainHeaders[i]\n    let val  \u2190 mkLambdaFVars sectionVars mainVals[i]\n    let type \u2190 mkForallFVars sectionVars header.type\n    return preDefs.push {\n      ref         := getDeclarationSelectionRef header.ref\n      kind        := header.kind\n      declName    := header.declName\n      levelParams := [], -- we set it later\n      modifiers   := header.modifiers\n      type        := type\n      value       := val\n    }\n\ndef pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition :=\n  letRecClosures.foldl (init := preDefs) fun preDefs c =>\n    let type := Closure.mkForall c.localDecls c.toLift.type\n    let val  := Closure.mkLambda c.localDecls c.toLift.val\n    preDefs.push {\n      ref         := c.ref\n      kind        := kind\n      declName    := c.toLift.declName\n      levelParams := [] -- we set it later\n      modifiers   := { modifiers with attrs := c.toLift.attrs }\n      type        := type\n      value       := val\n    }\n\ndef getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind :=\n  if mainHeaders.any fun h => h.kind.isTheorem then DefKind.\u00abtheorem\u00bb\n  else DefKind.\u00abdef\u00bb\n\ndef getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := {\n  isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable,\n  isPartial       := mainHeaders.any fun h => h.modifiers.isPartial,\n  isUnsafe        := mainHeaders.any fun h => h.modifiers.isUnsafe\n}\n\n/-\n- `sectionVars`:   The section variables used in the `mutual` block.\n- `mainHeaders`:   The elaborated header of the top-level definitions being defined by the mutual block.\n- `mainFVars`:     The auxiliary variables used to represent the top-level definitions being defined by the mutual block.\n- `mainVals`:      The elaborated value for the top-level definitions\n- `letRecsToLift`: The let-rec's definitions that need to be lifted\n-/\ndef main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift)\n    : TermElabM (Array PreDefinition) := do\n  -- Store in recFVarIds the fvarId of every function being defined by the mutual block.\n  let mainFVarIds := mainFVars.map Expr.fvarId!\n  let recFVarIds  := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds\n  -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec.\n  let mctx \u2190 getMCtx\n  let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift\n  resetZetaFVarIds\n  withTrackingZeta do\n    -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`.\n    letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val\n    let letRecClosures \u2190 mkLetRecClosures letRecsToLift freeVarMap\n    -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations.\n    let mainVals    \u2190 mainVals.mapM (instantiateMVars \u00b7)\n    let mainHeaders \u2190 mainHeaders.mapM instantiateMVarsAtHeader\n    let letRecClosures \u2190 letRecClosures.mapM fun closure => do pure { closure with toLift := (\u2190 instantiateMVarsAtLetRecToLift closure.toLift) }\n    -- Replace fvarIds for functions being defined with closed terms\n    let r              := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars\n    let r              := insertReplacementForLetRecs r letRecClosures\n    let mainVals       := mainVals.map r.apply\n    let mainHeaders    := mainHeaders.map fun h => { h with type := r.apply h.type }\n    let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } }\n    let letRecKind     := getKindForLetRecs mainHeaders\n    let letRecMods     := getModifiersForLetRecs mainHeaders\n    pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals\n\nend MutualClosure\n\nprivate def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name :=\n  if h : 0 < headers.size then\n    -- Recall that all top-level functions must have the same levels. See `check` method above\n    (headers.get \u27e80, h\u27e9).levelNames\n  else\n    []\n\n/-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/\nprivate def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do\n  let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do\n    let mut newHeaders := #[]\n    for view in views, header in headers do\n      if view.kind.isTheorem then\n        newHeaders := newHeaders.push { header with type := (\u2190 levelMVarToParam' header.type) }\n      else\n        newHeaders := newHeaders.push header\n    return newHeaders\n  let newHeaders \u2190 process.run' 1\n  newHeaders.mapM fun header => return { header with type := (\u2190 instantiateMVars header.type) }\n\ndef elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit :=\n  if isExample views then\n    withoutModifyingEnv go\n  else\n    go\nwhere go := do\n  let scopeLevelNames \u2190 getLevelNames\n  let headers \u2190 elabHeaders views\n  let headers \u2190 levelMVarToParamHeaders views headers\n  let allUserLevelNames := getAllUserLevelNames headers\n  withFunLocalDecls headers fun funFVars => do\n    let values \u2190 elabFunValues headers\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let values \u2190 values.mapM (instantiateMVars \u00b7)\n    let headers \u2190 headers.mapM instantiateMVarsAtHeader\n    let letRecsToLift \u2190 getLetRecsToLift\n    let letRecsToLift \u2190 letRecsToLift.mapM instantiateMVarsAtLetRecToLift\n    checkLetRecsToLiftTypes funFVars letRecsToLift\n    withUsed vars headers values letRecsToLift fun vars => do\n      let preDefs \u2190 MutualClosure.main vars headers funFVars values letRecsToLift\n      let preDefs \u2190 levelMVarToParamPreDecls preDefs\n      let preDefs \u2190 instantiateMVarsAtPreDecls preDefs\n      let preDefs \u2190 fixLevelParams preDefs scopeLevelNames allUserLevelNames\n      addPreDefinitions preDefs\n\nend Term\nnamespace Command\n\ndef elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do\n  let views \u2190 ds.mapM fun d => do\n    let modifiers \u2190 elabModifiers d[0]\n    mkDefView modifiers d[1]\n  runTermElabM none fun vars => Term.elabMutualDef vars views\n\nend Command\nend Lean.Elab\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/Elab/MutualDef.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.04742587317756678, "lm_q1q2_score": 0.01843054924906785}}
{"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 : \u03b1 \u27f6 \u03b2` with `\u03b1 \u03b2 : V` to be an instance of `V`, so that we can chain functors\n--   as in `\u03b1 \u27f6 \u03b2 \u27f6 \u03b3`.\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 `\u03b1 \u27f6 \u03b2` for the first\n-- kind and `\u03b1 \u27f6' \u03b2` 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 `\u03b1 \u27f6' \u03b2` is actually an instance of the type class\n-- `C`, so we can define `\u03b1 \u27f6 \u03b2` to be the same as `\u03b1 \u27f6' \u03b2`. However, in the case of `Sort u`, `\u03b1 \u27f6' \u03b2`\n-- is not an instance of `Sort u` if `u = 0` (i.e. `Sort u` is actually `Prop`).\n--\n-- Moreover, `\u03b1 \u27f6' \u03b2` is defined so that `\u03b1` and `\u03b2` can live in different universes.\n\nclass HasExternalFunctors (U : Universe.{u}) (V : Universe.{v}) : Type (max u v) where\n(IsFun {\u03b1 : U} {\u03b2 : V} : (\u03b1 \u2192 \u03b2) \u2192 Sort (max u v))\n\nstructure BundledFunctor {U : Universe.{u}} {V : Universe.{v}} [h : HasExternalFunctors U V]\n                         (\u03b1 : U) (\u03b2 : V) : Sort (max 1 u v) where\n(f     : \u03b1 \u2192 \u03b2)\n(isFun : h.IsFun f)\n\nnamespace BundledFunctor\n\n  infixr:20 \" \u27f6' \" => BundledFunctor\n\n  variable {U V : Universe} [h : HasExternalFunctors U V]\n\n  instance coeFun (\u03b1 : U) (\u03b2 : V) : CoeFun (\u03b1 \u27f6' \u03b2) (\u03bb _ => \u03b1 \u2192 \u03b2) := \u27e8BundledFunctor.f\u27e9\n\n  def mkFun {\u03b1 : U} {\u03b2 : V} {f : \u03b1 \u2192 \u03b2} (hf : h.IsFun f) : \u03b1 \u27f6' \u03b2 := \u27e8f, hf\u27e9\n\nend BundledFunctor\n\nclass HasInternalFunctors (U : Universe.{u}) extends HasExternalFunctors U U : Type u where\n(Fun                : U \u2192 U \u2192 U)\n(funEquiv (\u03b1 \u03b2 : U) : \u2308Fun \u03b1 \u03b2\u2309 \u2243 (\u03b1 \u27f6' \u03b2))\n\nnamespace HasInternalFunctors\n\n  infixr:20 \" \u27f6 \" => HasInternalFunctors.Fun\n\n  variable {U : Universe} [h : HasInternalFunctors U]\n\n  def toBundled   {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6  \u03b2) : \u03b1 \u27f6' \u03b2 := (h.funEquiv \u03b1 \u03b2).toFun  F\n  def fromBundled {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b2) : \u03b1 \u27f6  \u03b2 := (h.funEquiv \u03b1 \u03b2).invFun F\n\n  @[simp] theorem fromToBundled {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6  \u03b2) : fromBundled (toBundled F) = F := (h.funEquiv \u03b1 \u03b2).leftInv  F\n  @[simp] theorem toFromBundled {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b2) : toBundled (fromBundled F) = F := (h.funEquiv \u03b1 \u03b2).rightInv F\n\n  def funCoe {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6 \u03b2) : \u03b1 \u2192 \u03b2 := (toBundled F).f\n  instance (\u03b1 \u03b2 : U) : CoeFun \u2308\u03b1 \u27f6 \u03b2\u2309 (\u03bb _ => \u03b1 \u2192 \u03b2) := \u27e8funCoe\u27e9\n\n  -- Workaround for cases where `coeFun` doesn't work.\n  notation:max F:max \"\u27ee\" x:0 \"\u27ef\" => HasInternalFunctors.funCoe F x\n\n  def isFun {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6 \u03b2) : h.IsFun (funCoe F) := (toBundled F).isFun\n\n  theorem toBundled.eff {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6 \u03b2) (a : \u03b1) : (toBundled F) a = F a := rfl\n\n  @[simp] theorem fromBundled.coe {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b2) : funCoe (fromBundled F) = F.f :=\n  congrArg BundledFunctor.f (toFromBundled F)\n  @[simp] theorem fromBundled.eff {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b2) (a : \u03b1) : (fromBundled F) a = F a :=\n  congrFun (fromBundled.coe F) a\n\n  def mkFun {\u03b1 \u03b2 : U} {f : \u03b1 \u2192 \u03b2} (hf : h.IsFun f) : \u03b1 \u27f6 \u03b2 := fromBundled (BundledFunctor.mkFun hf)\n\n  @[simp] theorem mkFun.eff {\u03b1 \u03b2 : U} {f : \u03b1 \u2192 \u03b2} (hf : h.IsFun f) (a : \u03b1) :\n    (mkFun hf) a = f a :=\n  fromBundled.eff (BundledFunctor.mkFun hf) a\n\nend HasInternalFunctors\n\n\n\n@[simp] theorem elimRec {\u03b1 : Sort u} {a a' : \u03b1} {ha : a = a'}\n                        {T : \u03b1 \u2192 Sort v} {x : T a}\n                        {\u03b2 : Sort w} {f : {a : \u03b1} \u2192 T a \u2192 \u03b2} :\n  @f a' (ha \u25b8 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    : `\u03b1 \u27f6 \u03b1,                           a \u21a6 a`\n-- const : `\u03b2 \u27f6 (\u03b1 \u27f6 \u03b2),                     c \u21a6 (a \u21a6 c)`\n-- app   : `\u03b1 \u27f6 (\u03b1 \u27f6 \u03b2) \u27f6 \u03b2,                 a \u21a6 (F \u21a6 F a)`\n-- dup   : `(\u03b1 \u27f6 \u03b1 \u27f6 \u03b2) \u27f6 (\u03b1 \u27f6 \u03b2),           F \u21a6 (a \u21a6 F a a)`\n-- comp  : `(\u03b1 \u27f6 \u03b2) \u27f6 (\u03b2 \u27f6 \u03b3) \u27f6 (\u03b1 \u27f6 \u03b3),     F \u21a6 (G \u21a6 (a \u21a6 G (F a)))`\n--\n-- In `DerivedFunctors.lean`, we construct several other functors such as\n-- swap  : `(\u03b1 \u27f6 \u03b2 \u27f6 \u03b3) \u27f6 (\u03b2 \u27f6 \u03b1 \u27f6 \u03b3),       F \u21a6 (b \u21a6 (a \u21a6 F a b))`\n-- subst : `(\u03b1 \u27f6 \u03b2 \u27f6 \u03b3) \u27f6 (\u03b1 \u27f6 \u03b2) \u27f6 (\u03b1 \u27f6 \u03b3), F \u21a6 (G \u21a6 (a \u21a6 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 (\u03b1 : U) : h.IsFun (\u03bb a : \u03b1 => a))\n\nnamespace HasIdFun\n\n  variable {U : Universe} [HasExternalFunctors U U] [h : HasIdFun U]\n\n  def idFun' (\u03b1 : U) : \u03b1 \u27f6' \u03b1 := BundledFunctor.mkFun (h.idIsFun \u03b1)\n\nend HasIdFun\n\nclass HasConstFun (U V : Universe) [h : HasExternalFunctors U V] where\n(constIsFun (\u03b1 : U) {\u03b2 : V} (c : \u03b2) : h.IsFun (\u03bb a : \u03b1 => c))\n\nnamespace HasConstFun\n\n  variable {U V : Universe} [HasExternalFunctors U V] [h : HasConstFun U V]\n\n  def constFun' (\u03b1 : U) {\u03b2 : V} (c : \u03b2) : \u03b1 \u27f6' \u03b2 := BundledFunctor.mkFun (h.constIsFun \u03b1 c)\n\nend HasConstFun\n\nclass HasCompFun (U V W : Universe) [HasExternalFunctors U V] [HasExternalFunctors V W] [h : HasExternalFunctors U W] where\n(compIsFun {\u03b1 : U} {\u03b2 : V} {\u03b3 : W} (F : \u03b1 \u27f6' \u03b2) (G : \u03b2 \u27f6' \u03b3) : h.IsFun (\u03bb a : \u03b1 => 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' {\u03b1 : U} {\u03b2 : V} {\u03b3 : W} (F : \u03b1 \u27f6' \u03b2) (G : \u03b2 \u27f6' \u03b3) : \u03b1 \u27f6' \u03b3 := BundledFunctor.mkFun (h.compIsFun F G)\n\n  def revCompFun' {\u03b1 : U} {\u03b2 : V} {\u03b3 : W} (G : \u03b2 \u27f6' \u03b3) (F : \u03b1 \u27f6' \u03b2) : \u03b1 \u27f6' \u03b3 := compFun' F G\n  infixr:90 \" \u2299' \" => 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        {\u03b1 : U} (a : \u03b1) (\u03b2 : U)        : h.IsFun (\u03bb F : \u03b1 \u27f6 \u03b2     => F a))\n(appFunIsFun     (\u03b1 \u03b2 : U)                      : h.IsFun (\u03bb a : \u03b1         => HasInternalFunctors.mkFun (appIsFun a \u03b2)))\n(compFunIsFun    {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b2) (\u03b3 : U) : h.IsFun (\u03bb G : \u03b2 \u27f6 \u03b3     => HasInternalFunctors.mkFun (compIsFun F (HasInternalFunctors.toBundled G))))\n(compFunFunIsFun (\u03b1 \u03b2 \u03b3 : U)                    : h.IsFun (\u03bb F : \u03b1 \u27f6 \u03b2     => HasInternalFunctors.mkFun (compFunIsFun (HasInternalFunctors.toBundled F) \u03b3)))\n\nnamespace HasLinearFunOp\n\n  variable {U : Universe} [HasInternalFunctors U] [h : HasLinearFunOp U]\n\n  def idFun' (\u03b1 : U) : \u03b1 \u27f6' \u03b1 := HasIdFun.idFun' \u03b1\n  def idFun  (\u03b1 : U) : \u03b1 \u27f6  \u03b1 := HasInternalFunctors.fromBundled (idFun' \u03b1)\n\n  @[simp] theorem idFun.eff (\u03b1 : U) (a : \u03b1) : (idFun \u03b1) a = a :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  def appFun' {\u03b1 : U} (a : \u03b1) (\u03b2 : U) : (\u03b1 \u27f6 \u03b2) \u27f6' \u03b2 := BundledFunctor.mkFun (h.appIsFun a \u03b2)\n  def appFun  {\u03b1 : U} (a : \u03b1) (\u03b2 : U) : (\u03b1 \u27f6 \u03b2) \u27f6  \u03b2 := HasInternalFunctors.fromBundled (appFun' a \u03b2)\n\n  @[simp] theorem appFun.eff {\u03b1 : U} (a : \u03b1) (\u03b2 : U) (F : \u03b1 \u27f6 \u03b2) : (appFun a \u03b2) F = F a :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  def appFunFun' (\u03b1 \u03b2 : U) : \u03b1 \u27f6' (\u03b1 \u27f6 \u03b2) \u27f6 \u03b2 := BundledFunctor.mkFun (h.appFunIsFun \u03b1 \u03b2)\n  def appFunFun  (\u03b1 \u03b2 : U) : \u03b1 \u27f6  (\u03b1 \u27f6 \u03b2) \u27f6 \u03b2 := HasInternalFunctors.fromBundled (appFunFun' \u03b1 \u03b2)\n\n  @[simp] theorem appFunFun.eff (\u03b1 \u03b2 : U) (a : \u03b1) : (appFunFun \u03b1 \u03b2) a = appFun a \u03b2 :=\n  by apply HasInternalFunctors.fromBundled.eff\n  @[simp] theorem appFunFun.effEff (\u03b1 \u03b2 : U) (a : \u03b1) (F : \u03b1 \u27f6 \u03b2) : ((appFunFun \u03b1 \u03b2) a) F = F a :=\n  by simp\n\n  def compFun' {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2) (G : \u03b2 \u27f6' \u03b3) : \u03b1 \u27f6' \u03b3 := HasCompFun.compFun' F G\n  def compFun  {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6  \u03b2) (G : \u03b2 \u27f6  \u03b3) : \u03b1 \u27f6  \u03b3 :=\n  HasInternalFunctors.fromBundled (compFun' (HasInternalFunctors.toBundled F) (HasInternalFunctors.toBundled G))\n\n  @[simp] theorem compFun.eff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2) (G : \u03b2 \u27f6 \u03b3) (a : \u03b1) : (compFun F G) a = G (F a) :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  def compFunFun' {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b2) (\u03b3 : U) : (\u03b2 \u27f6 \u03b3) \u27f6' (\u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (h.compFunIsFun F \u03b3)\n  def compFunFun  {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6  \u03b2) (\u03b3 : U) : (\u03b2 \u27f6 \u03b3) \u27f6  (\u03b1 \u27f6 \u03b3) :=\n  HasInternalFunctors.fromBundled (compFunFun' (HasInternalFunctors.toBundled F) \u03b3)\n\n  @[simp] theorem compFunFun.eff {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6 \u03b2) (\u03b3 : U) (G : \u03b2 \u27f6 \u03b3) : (compFunFun F \u03b3) G = compFun F G :=\n  by apply HasInternalFunctors.fromBundled.eff\n  @[simp] theorem compFunFun.effEff {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6 \u03b2) (\u03b3 : U) (G : \u03b2 \u27f6 \u03b3) (a : \u03b1) : ((compFunFun F \u03b3) G) a = G (F a) :=\n  by simp\n\n  def compFunFunFun' (\u03b1 \u03b2 \u03b3 : U) : (\u03b1 \u27f6 \u03b2) \u27f6' (\u03b2 \u27f6 \u03b3) \u27f6 (\u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (h.compFunFunIsFun \u03b1 \u03b2 \u03b3)\n  def compFunFunFun  (\u03b1 \u03b2 \u03b3 : U) : (\u03b1 \u27f6 \u03b2) \u27f6  (\u03b2 \u27f6 \u03b3) \u27f6 (\u03b1 \u27f6 \u03b3) := HasInternalFunctors.fromBundled (compFunFunFun' \u03b1 \u03b2 \u03b3)\n  \n  @[simp] theorem compFunFunFun.eff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2) : (compFunFunFun \u03b1 \u03b2 \u03b3) F = compFunFun F \u03b3 :=\n  by apply HasInternalFunctors.fromBundled.eff\n  @[simp] theorem compFunFunFun.effEff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2) (G : \u03b2 \u27f6 \u03b3) : ((compFunFunFun \u03b1 \u03b2 \u03b3) F) G = compFun F G :=\n  by simp\n  @[simp] theorem compFunFunFun.effEffEff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2) (G : \u03b2 \u27f6 \u03b3) (a : \u03b1) : (((compFunFunFun \u03b1 \u03b2 \u03b3) 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 (\u03b1 \u03b2 : U) : h.IsFun (\u03bb c : \u03b2 => HasInternalFunctors.mkFun (constIsFun \u03b1 c)))\n\nnamespace HasSubLinearFunOp\n\n  variable {U : Universe} [HasInternalFunctors U] [h : HasSubLinearFunOp U]\n\n  def constFun' (\u03b1 : U) {\u03b2 : U} (c : \u03b2) : \u03b1 \u27f6' \u03b2 := HasConstFun.constFun' \u03b1 c\n  def constFun  (\u03b1 : U) {\u03b2 : U} (c : \u03b2) : \u03b1 \u27f6  \u03b2 := HasInternalFunctors.fromBundled (constFun' \u03b1 c)\n\n  @[simp] theorem constFun.eff (\u03b1 : U) {\u03b2 : U} (c : \u03b2) (a : \u03b1) : (constFun \u03b1 c) a = c :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  def constFunFun' (\u03b1 \u03b2 : U) : \u03b2 \u27f6' (\u03b1 \u27f6 \u03b2) := BundledFunctor.mkFun (h.constFunIsFun \u03b1 \u03b2)\n  def constFunFun  (\u03b1 \u03b2 : U) : \u03b2 \u27f6  (\u03b1 \u27f6 \u03b2) := HasInternalFunctors.fromBundled (constFunFun' \u03b1 \u03b2)\n\n  @[simp] theorem constFunFun.eff (\u03b1 \u03b2 : U) (c : \u03b2) : (constFunFun \u03b1 \u03b2) c = constFun \u03b1 c :=\n  by apply HasInternalFunctors.fromBundled.eff\n  @[simp] theorem constFunFun.effEff (\u03b1 \u03b2 : U) (c : \u03b2) (a : \u03b1) : ((constFunFun \u03b1 \u03b2) 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    {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b1 \u27f6 \u03b2) : h.IsFun (\u03bb a : \u03b1         => F a a))\n(dupFunIsFun (\u03b1 \u03b2 : U)                  : h.IsFun (\u03bb F : \u03b1 \u27f6 \u03b1 \u27f6 \u03b2 => HasInternalFunctors.mkFun (dupIsFun (HasInternalFunctors.toBundled F))))\n\nnamespace HasNonLinearFunOp\n\n  variable {U : Universe} [HasInternalFunctors U] [h : HasNonLinearFunOp U]\n\n  def dupFun' {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6' \u03b1 \u27f6 \u03b2) : \u03b1 \u27f6' \u03b2 := BundledFunctor.mkFun (h.dupIsFun F)\n  def dupFun  {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6  \u03b1 \u27f6 \u03b2) : \u03b1 \u27f6  \u03b2 :=\n  HasInternalFunctors.fromBundled (dupFun' (HasInternalFunctors.toBundled F))\n\n  @[simp] theorem dupFun.eff {\u03b1 \u03b2 : U} (F : \u03b1 \u27f6 \u03b1 \u27f6 \u03b2) (a : \u03b1) : (dupFun F) a = F a a :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  def dupFunFun' (\u03b1 \u03b2 : U) : (\u03b1 \u27f6 \u03b1 \u27f6 \u03b2) \u27f6' (\u03b1 \u27f6 \u03b2) := BundledFunctor.mkFun (h.dupFunIsFun \u03b1 \u03b2)\n  def dupFunFun  (\u03b1 \u03b2 : U) : (\u03b1 \u27f6 \u03b1 \u27f6 \u03b2) \u27f6  (\u03b1 \u27f6 \u03b2) := HasInternalFunctors.fromBundled (dupFunFun' \u03b1 \u03b2)\n\n  @[simp] theorem dupFunFun.eff (\u03b1 \u03b2 : U) (F : \u03b1 \u27f6 \u03b1 \u27f6 \u03b2) : (dupFunFun \u03b1 \u03b2) F = dupFun F :=\n  by apply HasInternalFunctors.fromBundled.eff\n  @[simp] theorem dupFunFun.effEff (\u03b1 \u03b2 : U) (F : \u03b1 \u27f6 \u03b1 \u27f6 \u03b2) (a : \u03b1) : ((dupFunFun \u03b1 \u03b2) 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": "import Yatima.Typechecker.TypecheckM\nimport Yatima.Typechecker.Printing\nimport Yatima.Common.ToLDON\nimport Lurk.Scalar\n\n/-!\n# Yatima typechecker: Eval\n\n## Basic Structure\n\nThis is the first of the three main files that constitute the Yatima typechecker: `Eval`, `Equal`,\nand `Infer`.\n\nTODO: Add a high level overview of Eval in the context of Eval-Equal-Infer.\n\n## Evaluate\n\nIn this module the evaluation (\u2194 reduction) of Yatima expressions is defined. Expressions that can\nbe reduced take a few forms, for example `.app fnc args`, constants, and suspdended evaluations.\nFunctions that can not be reduced further evaluate to unreduced Values or suspended thunks waiting\nto evaluate further.\n-/\n\nnamespace Yatima\n\nopen IR\nopen Lurk (F)\n\nnamespace Typechecker\n\n/--\nLooks for a constant by its hash `f : F` in a store and\nreturns it if found. Panics otherwise.\n\nIn the code generator, this function has to be overwritten with `(open f)`,\nignoring the second argument.\n-/\ndef derefConst (f : F) (store : Store) : Const :=\n  store.find! f\n\n/-- TODO document. This function is overwritten btw -/\ndef mkInductiveProjF (block : F) (idx : Nat) (quick : Bool) : F :=\n  let indF : Const := .inductiveProj \u27e8block, idx\u27e9\n  if quick then .ofNat $ (Hashable.hash indF).toNat\n  else indF.toLDON.commit default |>.1\n\n/-- TODO document. This function is overwritten btw -/\ndef mkConstructorProjF (block : F) (idx : Nat) (cidx : Nat) (quick : Bool) : F :=\n  let ctorF : Const := .constructorProj \u27e8block, idx, cidx\u27e9\n  if quick then .ofNat $ (Hashable.hash ctorF).toNat\n  else ctorF.toLDON.commit default |>.1\n\n/-- TODO document. This function is overwritten btw -/\ndef mkRecursorProjF (block : F) (idx : Nat) (ridx : Nat) (quick : Bool) : F :=\n  let recrF : Const := .recursorProj \u27e8block, idx, ridx\u27e9\n  if quick then .ofNat $ (Hashable.hash recrF).toNat\n  else recrF.toLDON.commit default |>.1\n\n/-- TODO document. This function is overwritten btw -/\ndef mkDefinitionProjF (block : F) (idx : Nat) (quick : Bool) : F :=\n  let defnF : Const := .definitionProj \u27e8block, idx\u27e9\n  if quick then .ofNat $ (Hashable.hash defnF).toNat\n  else defnF.toLDON.commit default |>.1\n\n/--\nLooks for a constant by its hash `f : F` in the `TypecheckState` cache of `TypedConst` and\nreturns it if it is found. If the constant is not found it throws an error.\nSpecifically, this function assumes that `checkConst name f` has previously been called\n(which populates this cache).\n\nNote: The `name : Name` is used only in the error messaging\n-/\ndef derefTypedConst (f : F) : TypecheckM TypedConst := do\n  match (\u2190 get).typedConsts.find? f with\n  | some const => pure const\n  | none => throw s!\"TypedConst for {f} not found\"\n\nend Typechecker\n\nnamespace IR\n\nopen Typechecker (TypecheckM derefConst)\n\ndef getIndFromProj : InductiveProj \u2192 TypecheckM Inductive\n  | \u27e8indBlockF, idx\u27e9 => do\n    let .mutIndBlock inds := derefConst indBlockF (\u2190 read).store\n      | throw \"Invalid Const kind. Expected mutIndBlock\"\n    let some ind := inds.get? idx\n      | throw s!\"Mutual inductive block doesn't contain index {idx}\"\n    pure ind\n\ndef getDefFromProj : DefinitionProj \u2192 TypecheckM Definition\n  | \u27e8defBlockF, idx\u27e9 => do\n    let .mutDefBlock defs := derefConst defBlockF (\u2190 read).store\n      | throw \"Invalid Const kind. Expected mutDefBlock\"\n    let some defn := defs.get? idx\n      | throw s!\"Mutual definition block doesn't contain index {idx}\"\n    pure defn\n\ndef getCtorFromProj : ConstructorProj \u2192 TypecheckM Constructor\n  | \u27e8indBlockF, idx, cidx\u27e9 => do\n    let ind \u2190 getIndFromProj \u27e8indBlockF, idx\u27e9\n    let some ctor := ind.ctors.get? cidx\n      | throw s!\"Inductive doesn't contain constructor with index {cidx}\"\n    pure ctor\n\ndef getRecrFromProj : RecursorProj \u2192 TypecheckM Recursor\n  | \u27e8indBlockF, idx, ridx\u27e9 => do\n    let ind \u2190 getIndFromProj \u27e8indBlockF, idx\u27e9\n    let some recr := ind.recrs.get? ridx\n      | throw s!\"Inductive doesn't contain recursor with index {ridx}\"\n    pure recr\n\nnamespace Const\n\ndef levels : Const \u2192 TypecheckM Nat\n  | .axiom      x\n  | .theorem    x\n  | .opaque     x\n  | .definition x\n  | .quotient   x => pure x.lvls\n  | .inductiveProj   p => do pure (\u2190 getIndFromProj  p).lvls\n  | .constructorProj p => do pure (\u2190 getCtorFromProj p).lvls\n  | .recursorProj    p => do pure (\u2190 getRecrFromProj p).lvls\n  | .definitionProj  p => do pure (\u2190 getDefFromProj  p).lvls\n  | _ => throw \"Can't retrieve universe levels of mutual blocks\"\n\ndef type : Const \u2192 TypecheckM Expr\n  | .axiom      x\n  | .theorem    x\n  | .opaque     x\n  | .definition x\n  | .quotient   x => pure x.type\n  | .inductiveProj   p => do pure (\u2190 getIndFromProj  p).type\n  | .constructorProj p => do pure (\u2190 getCtorFromProj p).type\n  | .recursorProj    p => do pure (\u2190 getRecrFromProj p).type\n  | .definitionProj  p => do pure (\u2190 getDefFromProj  p).type\n  | _ => throw \"Can't retrieve type of mutual blocks\"\n\nend Const\n\nend IR\n\nnamespace Typechecker\n\ndef TypeInfo.update (univs : List Univ) : TypeInfo \u2192 TypeInfo\n| .sort lvl => .sort $ lvl.instBulkReduce univs\n| .unit  => .unit\n| .proof => .proof\n| .none  => .none\n\nopen PP\n\nmutual\n  /--\n  Evaluates a `TypedExpr` into a `Value`.\n\n  Evaluation here means applying functions to arguments, resuming evaluation of suspended thunks,\n  evaluating a constant, instantiating a universe variable, evaluating the body of a let binding\n  and evaluating a projection.\n  -/\n  partial def eval (t : TypedExpr) : TypecheckM Value := match t.expr with\n    | .app fnc arg => do\n      let ctx \u2190 read\n      let argThunk := suspend arg ctx (\u2190 get)\n      let fnc \u2190 evalTyped fnc\n      apply fnc argThunk\n    | .lam dom bod => do\n      let ctx \u2190 read\n      let dom' := suspend dom ctx (\u2190 get)\n      pure $ .lam dom' bod ctx.env\n    | .var idx => do\n      let some thunk := (\u2190 read).env.exprs.get? idx\n        | throw s!\"Index {idx} is out of range for expression environment\"\n      pure $ thunk.get\n    | .const f const_univs => do\n      let env := (\u2190 read).env\n      let const_univs := const_univs.map (Univ.instBulkReduce env.univs)\n      evalConst f const_univs\n    | .letE _ val bod => do\n      let thunk := suspend val (\u2190 read) (\u2190 get)\n      withExtendedEnv thunk (eval bod)\n    | .pi dom img => do\n      let ctx \u2190 read\n      let dom' := suspend dom ctx (\u2190 get)\n      pure $ .pi dom' img ctx.env\n    | .sort univ => do\n      let env := (\u2190 read).env\n      pure $ .sort (Univ.instBulkReduce env.univs univ)\n    | .lit lit =>\n      pure $ .lit lit\n    | .proj ind idx expr => do\n      let val \u2190 eval expr\n      match val with\n      | .app (.const f _) args _ =>\n        match derefConst f (\u2190 read).store with\n        | .constructorProj p =>\n          let ctor \u2190 getCtorFromProj p\n          -- Since terms are well-typed, we can be sure that this constructor is of a structure-like inductive\n          -- and, furthermore, that the index is in range of `args`\n          let idx := ctor.params + idx\n          let some arg := args.reverse.get? idx\n            | throw s!\"Invalid projection of index {idx} but constructor has only {args.length} arguments\"\n          pure $ arg.get\n        | _ => pure $ .neu (.proj ind idx (.mk (expr.info.update (\u2190 read).env.univs) val))\n      | .app .. => pure $ .neu (.proj ind idx (.mk (expr.info.update (\u2190 read).env.univs) val))\n      | e => throw s!\"Value {\u2190 ppValue e} is impossible to project\"\n\n  @[inline]\n  partial def evalTyped (t : TypedExpr) : TypecheckM TypedValue := do\n    let reducedInfo := t.info.update (\u2190 read).env.univs\n    let value \u2190 eval t\n    pure \u27e8reducedInfo, value\u27e9\n\n  partial def evalConst' (f : F) (univs : List Univ) : TypecheckM Value := do\n    match derefConst f (\u2190 read).store with\n    | .theorem _\n    | .definition _ =>\n      match \u2190 derefTypedConst f with\n      | .theorem _ deref => withEnv \u27e8[], univs\u27e9 $ eval deref\n      | .definition _ deref part =>\n        if part then pure $ mkConst f univs\n        else withEnv \u27e8[], univs\u27e9 $ eval deref\n      | _ => throw \"Invalid const kind for evaluation\"\n    | _ => pure $ mkConst f univs\n\n  /-- Evaluates the `Yatima.Const` that's referenced by a constant index -/\n  partial def evalConst (const : F) (univs : List Univ) : TypecheckM Value := do\n    if \u2190 primFWith .natZero (pure false) (pure $ \u00b7 == const) then pure $ .lit (.natVal 0)\n    else if (\u2190 fPrim const) matches .some (.op _) then pure $ mkConst const univs\n    else evalConst' const univs\n\n  /--\n  Suspends the evaluation of a Yatima expression `expr : TypedExpr` in a particular `ctx : TypecheckCtx`\n\n  Suspended evaluations can be resumed by evaluating `Thunk.get` on the resulting Thunk.\n  -/\n  partial def suspend (expr : TypedExpr) (ctx : TypecheckCtx) (stt : TypecheckState) : SusValue :=\n    let thunk := { fn := fun _ =>\n      match TypecheckM.run ctx stt (eval expr) with\n      | .ok a =>\n        a\n      | .error e => .exception e }\n    let reducedInfo := expr.info.update ctx.env.univs\n    \u27e8reducedInfo, thunk\u27e9\n\n  /--\n  Applies `value : Value` to the argument `arg : SusValue`.\n\n  Applications are split into cases on whether `value` is a `Value.lam`, the application of a constant\n  or the application of a free variable.\n\n  * `Value.lam` : Descends into and evaluates the body of the lambda expression\n  * `Value.app (.const ..)` : Applies the constant to the argument as expected using `applyConst`\n  * `Value.app (.fvar ..)` : Returns an unevaluated `Value.app`\n  -/\n  partial def apply (val : TypedValue) (arg : SusValue) : TypecheckM Value :=\n    match val.value with\n    | .lam _ bod lamEnv =>\n      withNewExtendedEnv lamEnv arg (eval bod)\n    | .app (.const f kUnivs) args infos => applyConst f kUnivs arg args val.info infos\n    -- Note that `val.info` is being added to the `infos` field of the `app` nodes because it is the info\n    -- of the former partial application. That's because a stuck application like `h a1 .. an a(n+1)` must\n    -- hold the info of the sub stuck application `h a1 .. an` for quoting to be done correctly\n    | .app neu args infos => pure $ .app neu (arg :: args) (val.info :: infos)\n    -- Since terms are well-typed we know that any other case is impossible\n    | _ => throw \"Invalid case for apply\"\n\n  /--\n  Applies a named constant, referred by its constant index `f : F` to the list of arguments\n  `arg :: args`.\n\n  The application of the constant is split into cases on whether it is an inductive recursor,\n  a quotient, or any other constant (which returns an unreduced application)\n   -/\n  partial def applyConst (f : F) (univs : List Univ) (arg : SusValue) (args : List SusValue)\n      (info : TypeInfo) (infos : List TypeInfo) : TypecheckM Value := do\n    if let some $ .op p \u2190 fPrim f then\n      if args.length < p.numArgs - 1 then\n        pure $ .app (.const f univs) (arg :: args) (info :: infos)\n      else\n        let op := p.toPrimOp\n        let argsArr := (Array.mk $ arg :: args).reverse\n        match \u2190 op.op $ argsArr with\n        | .some v => pure v\n        | .none =>\n          if p.reducible then\n            let typArgs := (info :: infos).zip (arg :: args)\n            typArgs.foldrM (init := \u2190 evalConst' f univs)\n              fun (info, arg) acc => apply \u27e8info, acc\u27e9 arg\n          else pure $ .app (.const f univs) (arg :: args) (info :: infos)\n\n    -- Assumes a partial application of f to args, which means in particular,\n    -- that it is in normal form\n    else match \u2190 derefTypedConst f with\n    | .recursor _ params motives minors indices isK indProj rules =>\n      let majorIdx := params + motives + minors + indices\n      if args.length != majorIdx then\n        pure $ .app (.const f univs) (arg :: args) (info :: infos)\n      else if isK then\n        -- sanity check\n        let nArgs := args.length\n        let nDrop := params + motives + 1\n        if nArgs < nDrop then\n          throw s!\"Too few arguments ({nArgs}). At least {nDrop} needed\"\n        let minorIdx := nArgs - nDrop\n        let some minor := args.get? minorIdx | throw s!\"Index {minorIdx} is out of range\"\n        pure minor.get\n      else\n        let params := args.take params\n        match \u2190 toCtorIfLitOrStruct indProj params univs arg with\n        | .app (Neutral.const f _) args' _ => match \u2190 derefTypedConst f with\n          | .constructor _ idx _ =>\n            match rules.get? idx with\n            | some (fields, rhs) =>\n              let exprs := (args'.take fields) ++ (args.drop indices)\n              withEnv \u27e8exprs, univs\u27e9 $ eval rhs.toImplicitLambda\n            -- Since we assume expressions are previously type checked, we know that this constructor\n            -- must have an associated recursion rule\n            | none => throw s!\"Constructor {f} has no associated recursion rule\"\n          | _ => pure $ .app (Neutral.const f univs) (arg :: args) (info :: infos)\n        | _ => pure $ .app (Neutral.const f univs) (arg :: args) (info :: infos)\n    | .quotient _ kind => match kind with\n      | .lift => applyQuot arg args 6 1 (.app (.const f univs) (arg :: args) (info :: infos))\n      | .ind  => applyQuot arg args 5 0 (.app (.const f univs) (arg :: args) (info :: infos))\n      | _ => pure $ .app (.const f univs) (arg :: args) (info :: infos)\n    | _ => pure $ .app (.const f univs) (arg :: args) (info :: infos)\n\n  /--\n  Applies a quotient to a value. It might reduce if enough arguments are applied to it\n  -/\n  partial def applyQuot (major? : SusValue) (args : List SusValue)\n      (reduceSize argPos : Nat) (default : Value) : TypecheckM Value :=\n    let argsLength := args.length + 1\n    if argsLength == reduceSize then\n      match major?.get with\n      | .app (.const majorFn _) majorArgs _ => do\n        match \u2190 derefTypedConst majorFn with\n        | .quotient _ .ctor =>\n          -- Sanity check (`majorArgs` should have size 3 if the typechecking is correct)\n          if majorArgs.length != 3 then throw \"majorArgs should have size 3\"\n          let some majorArg := majorArgs.head? | throw \"majorArgs can't be empty\"\n          let some head := args.get? argPos | throw s!\"{argPos} is an invalid index for args\"\n          apply head.getTyped majorArg\n        | _ => pure default\n      | _ => pure default\n    else if argsLength < reduceSize then\n      pure default\n    else\n      throw s!\"argsLength {argsLength} can't be greater than reduceSize {reduceSize}\"\n\n  partial def toCtorIfLitOrStruct (indProj : InductiveProj) (params : List SusValue) (univs : List Univ) : SusValue \u2192 TypecheckM Value\n    | .mk info thunk =>\n      match thunk.get with\n      | .lit (.natVal v) => do\n        let zeroIdx \u2190 primF .natZero\n        let succIdx \u2190 primF (.op .natSucc)\n        if v == 0 then pure $ mkConst zeroIdx []\n        else\n          let thunk : SusValue := \u27e8info, Value.lit $ .natVal (v-1)\u27e9\n          pure $ .app (.const succIdx []) [thunk] [.none]\n      | .lit (.strVal _) => throw \"TODO Reduction of string\"\n      | e => do\n        -- do not eta expand structs in `Prop`\n        if info == .proof then return e\n        else match indProj with\n        | \u27e8f, i\u27e9 =>\n          let ind \u2190 getIndFromProj indProj\n          -- must be a struct to eta expand\n          if !ind.struct then\n            pure e\n          else\n            let quick := (\u2190 read).quick\n            let ctorF := mkConstructorProjF f i 0 quick\n            match e with\n            | .app (.const f _) _ _ => if ctorF == f then\n              -- already eta expanded\n              return e\n            | _ => pure ()\n            let ctor \u2190 match ind.ctors with\n              | [ctor] => pure ctor\n              | _ =>\n                let f := mkInductiveProjF f i (\u2190 read).quick\n                throw s!\"{(\u2190 read).constNames.getF f} should be a struct with only one constructor\"\n            let etaExpand (e : Value) : TypecheckM Value := do\n              let mut projArgs : List SusValue := params\n              for idx in [:ctor.fields] do\n                -- FIXME get the correct TypeInfo for the projection\n                projArgs := projArgs ++ [.mk .none $ .mk fun _ =>\n                  .neu (.proj (mkInductiveProjF f i quick) idx $ .mk info e)]\n              let len := projArgs.length\n              if h : len > 0 then\n                let lastIdx := len.pred\n                let lastArg := projArgs.get \u27e8lastIdx, Nat.pred_lt' h\u27e9\n                let annotatedArgs := projArgs.take lastIdx ++ [lastArg]\n                pure $ .app (.const ctorF univs) annotatedArgs $ annotatedArgs.map (fun _ => .none)\n              else\n                pure $ .neu (.const ctorF univs)\n            etaExpand e\nend\n\nmutual\n  /--\n  Quoting transforms a value into a (typed) expression. It is the right-inverse of evaluation:\n  evaluating a quoted value results in the value itself.\n  -/\n  partial def quote (lvl : Nat) (env : Env) : Value \u2192 TypecheckM Expr\n    | .sort univ => pure $ .sort (univ.instBulkReduce env.univs)\n    | .app neu args infos => do\n      -- Sanity check: `args` and `infos` should have the same size\n      if args.tail.length != infos.tail.length then throw \"Partial application does not have enough info\"\n      let argsInfos := args.zip infos\n      argsInfos.foldrM (init := \u2190 quoteNeutral lvl env neu) fun (arg, info) acc => do\n        pure $ .app \u27e8info, acc\u27e9 $ \u2190 quoteTyped lvl env arg.getTyped\n    | .lam dom bod env' => do\n      let dom \u2190 quoteTyped lvl env dom.getTyped\n      -- NOTE: although we add a value with `default` as `TypeInfo`, this is overwritten by the info of the expression's value\n      let var := mkSusVar default lvl\n      let bod \u2190 quoteTypedExpr (lvl+1) bod (env'.extendWith var)\n      pure $ .lam dom bod\n    | .pi dom img env' => do\n      let dom \u2190 quoteTyped lvl env dom.getTyped\n      let var := mkSusVar default lvl\n      let img \u2190 quoteTypedExpr (lvl+1) img (env'.extendWith var)\n      pure $ .pi dom img\n    | .lit lit => pure $ .lit lit\n    | .exception e => throw e\n\n  @[inline]\n  partial def quoteTyped (lvl : Nat) (env : Env) (val : TypedValue) : TypecheckM TypedExpr := do\n    pure \u27e8val.info, \u2190 quote lvl env val.value\u27e9\n\n  partial def quoteExpr (lvl : Nat) (expr : Expr) (env : Env) : TypecheckM Expr :=\n    match expr with\n    | .var idx => do\n      match env.exprs.get? idx with\n      -- NOTE: if everything is correct, then `info` should coincide with `val.info`. We will choose `info` since\n      -- this allows us to add values to the environment without knowing which `TypeInfo` it should take. See their\n      -- previous note\n     | some val => quote lvl env val.get\n     | none => throw s!\"Unbound variable _@{idx}\"\n    | .app fnc arg => do\n      let fnc \u2190 quoteTypedExpr lvl fnc env\n      let arg \u2190 quoteTypedExpr lvl arg env\n      pure $ .app fnc arg\n    | .lam dom bod => do\n      let dom \u2190 quoteTypedExpr lvl dom env\n      let var := mkSusVar default lvl\n      let bod \u2190 quoteTypedExpr (lvl+1) bod (env.extendWith var)\n      pure $ .lam dom bod\n    | .letE typ val bod => do\n      let typ \u2190 quoteTypedExpr lvl typ env\n      let val \u2190 quoteTypedExpr lvl val env\n      let var := mkSusVar default lvl\n      let bod \u2190 quoteTypedExpr (lvl+1) bod (env.extendWith var)\n      pure $ .letE typ val bod\n    | .pi dom img => do\n      let dom \u2190 quoteTypedExpr lvl dom env\n      let var := mkSusVar default lvl\n      let img \u2190 quoteTypedExpr (lvl+1) img (env.extendWith var)\n      pure $ .pi dom img\n    | .proj ind idx expr => do\n      let expr \u2190 quoteTypedExpr lvl expr env\n      pure $ .proj ind idx expr\n    | .const idx univs => pure $ .const idx (univs.map (Univ.instBulkReduce env.univs))\n    | .sort univ => pure $ .sort (univ.instBulkReduce env.univs)\n    | .lit .. => pure expr\n\n  @[inline]\n  partial def quoteTypedExpr (lvl : Nat) (t : TypedExpr) (env : Env) : TypecheckM TypedExpr := do\n    pure \u27e8t.info, \u2190 quoteExpr lvl t.expr env\u27e9\n\n  partial def quoteNeutral (lvl : Nat) (env : Env) : Neutral \u2192 TypecheckM Expr\n    | .fvar  idx => pure $ .var (lvl - idx - 1)\n    | .const cidx univs => pure $ .const cidx (univs.map (Univ.instBulkReduce env.univs))\n    | .proj  f ind val => do\n      pure $ .proj f ind (\u2190 quoteTyped lvl env val)\nend\n\nend Yatima.Typechecker\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/Yatima/Typechecker/Eval.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.04208773257151254, "lm_q1q2_score": 0.018426998961700344}}
{"text": "\nimport Lib.Meta.Opaque\n\nnamespace Bar\nnamespace Foo\n\nopaque def Term := Unit\n\nend Foo\n\nnamespace Foo\n\nopaque namespace Term\n\nopen Lean\n\ndef fvar (x : Name) : Term :=\n()\n\nopen Lean.Parser.Transport\n\ndef rec {motive : Term \u2192 Sort u} (f : \u2200 n, motive (fvar n)) : \u2200 t, motive t :=\nsorry\n\ntheorem foo (n) : fvar n = fvar n := sorry\n\n#check @Foo.Term.rec\n\nend Term\n\n#print Term.foo\n\nend Foo\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/test/test2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.04272220181238148, "lm_q1q2_score": 0.018376841835345187}}
{"text": "import data.list.perm\nimport data.multiset.basic\n\nmk_iff_of_inductive_prop list.chain test.chain_iff\n\nmk_iff_of_inductive_prop false    test.false_iff\n\nmk_iff_of_inductive_prop true     test.true_iff\n\nmk_iff_of_inductive_prop nonempty test.non_empty_iff\n\nmk_iff_of_inductive_prop and      test.and_iff\n\nmk_iff_of_inductive_prop or       test.or_iff\n\nmk_iff_of_inductive_prop eq       test.eq_iff\n\nmk_iff_of_inductive_prop heq      test.heq_iff\n\nmk_iff_of_inductive_prop list.perm  test.perm_iff\n\nmk_iff_of_inductive_prop list.pairwise  test.pairwise_iff\n\ninductive test.is_true (p : Prop) : Prop\n| triviality : p \u2192 test.is_true\n\nmk_iff_of_inductive_prop test.is_true test.is_true_iff\n\n@[mk_iff] structure foo (m n : \u2115) : Prop :=\n(equal : m = n)\n(sum_eq_two : m + n = 2)\n\nexample (m n : \u2115) : foo m n \u2194 m = n \u2227 m + n = 2 := foo_iff m n\n\n@[mk_iff bar] structure foo2 (m n : \u2115) : Prop :=\n(equal : m = n)\n(sum_eq_two : m + n = 2)\n\nexample (m n : \u2115) : foo2 m n \u2194 m = n \u2227 m + n = 2 := bar m 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/mk_iff_of_inductive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473485858429, "lm_q2_score": 0.04272219937472948, "lm_q1q2_score": 0.01837684078679564}}
{"text": "/-\nCopyright (c) 2018 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes H\u00f6lzl\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 \u2208 \u2205` is never\nsatisfied. -/\ndef pi.empty {\u03b1 : Type u_1} (\u03b2 : \u03b1 \u2192 Type u_2) (a : \u03b1) (h : a \u2208 \u2205) : \u03b2 a := multiset.pi.empty \u03b2 a h\n\n/-- Given a finset `s` of `\u03b1` and for all `a : \u03b1` a finset `t a` of `\u03b4 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 \u2208 s`.\nNote that the elements of `s.pi t` are only partially defined, on `s`. -/\ndef pi {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1)\n    (t : (a : \u03b1) \u2192 finset (\u03b4 a)) : finset ((a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) :=\n  mk (multiset.pi (val s) fun (a : \u03b1) => val (t a)) sorry\n\n@[simp] theorem pi_val {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1)\n    (t : (a : \u03b1) \u2192 finset (\u03b4 a)) : val (pi s t) = multiset.pi (val s) fun (a : \u03b1) => val (t a) :=\n  rfl\n\n@[simp] theorem mem_pi {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {s : finset \u03b1}\n    {t : (a : \u03b1) \u2192 finset (\u03b4 a)} {f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a} :\n    f \u2208 pi s t \u2194 \u2200 (a : \u03b1) (h : a \u2208 s), f a h \u2208 t a :=\n  multiset.mem_pi (val s) (fun (a : \u03b1) => (fun (a : \u03b1) => val (t a)) a) f\n\n/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s \u222a {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 {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1) (a : \u03b1) (b : \u03b4 a)\n    (f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) (a' : \u03b1) (h : a' \u2208 insert a s) : \u03b4 a' :=\n  multiset.pi.cons (val s) a b f a' sorry\n\n@[simp] theorem pi.cons_same {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1)\n    (a : \u03b1) (b : \u03b4 a) (f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) (h : a \u2208 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 {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {s : finset \u03b1} {a : \u03b1} {a' : \u03b1}\n    {b : \u03b4 a} {f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a} {h : a' \u2208 insert a s} (ha : a \u2260 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 {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b4 a}\n    {s : finset \u03b1} (hs : \u00aca \u2208 s) : function.injective (pi.cons s a b) :=\n  sorry\n\n@[simp] theorem pi_empty {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1]\n    {t : (a : \u03b1) \u2192 finset (\u03b4 a)} : pi \u2205 t = singleton (pi.empty \u03b4) :=\n  rfl\n\n@[simp] theorem pi_insert {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1]\n    [(a : \u03b1) \u2192 DecidableEq (\u03b4 a)] {s : finset \u03b1} {t : (a : \u03b1) \u2192 finset (\u03b4 a)} {a : \u03b1}\n    (ha : \u00aca \u2208 s) :\n    pi (insert a s) t = finset.bUnion (t a) fun (b : \u03b4 a) => image (pi.cons s a b) (pi s t) :=\n  sorry\n\ntheorem pi_singletons {\u03b1 : Type u_1} [DecidableEq \u03b1] {\u03b2 : Type u_2} (s : finset \u03b1) (f : \u03b1 \u2192 \u03b2) :\n    (pi s fun (a : \u03b1) => singleton (f a)) = singleton fun (a : \u03b1) (_x : a \u2208 s) => f a :=\n  sorry\n\ntheorem pi_const_singleton {\u03b1 : Type u_1} [DecidableEq \u03b1] {\u03b2 : Type u_2} (s : finset \u03b1) (i : \u03b2) :\n    (pi s fun (_x : \u03b1) => singleton i) = singleton fun (_x : \u03b1) (_x : _x \u2208 s) => i :=\n  pi_singletons s fun (_x : \u03b1) => i\n\ntheorem pi_subset {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {s : finset \u03b1}\n    (t\u2081 : (a : \u03b1) \u2192 finset (\u03b4 a)) (t\u2082 : (a : \u03b1) \u2192 finset (\u03b4 a))\n    (h : \u2200 (a : \u03b1), a \u2208 s \u2192 t\u2081 a \u2286 t\u2082 a) : pi s t\u2081 \u2286 pi s t\u2082 :=\n  fun (g : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) (hg : g \u2208 pi s t\u2081) =>\n    iff.mpr mem_pi fun (a : \u03b1) (ha : a \u2208 s) => h a ha (iff.mp mem_pi hg a ha)\n\ntheorem pi_disjoint_of_disjoint {\u03b1 : Type u_1} [DecidableEq \u03b1] {\u03b4 : \u03b1 \u2192 Type u_2}\n    [(a : \u03b1) \u2192 DecidableEq (\u03b4 a)] {s : finset \u03b1} [DecidableEq ((a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a)]\n    (t\u2081 : (a : \u03b1) \u2192 finset (\u03b4 a)) (t\u2082 : (a : \u03b1) \u2192 finset (\u03b4 a)) {a : \u03b1} (ha : a \u2208 s)\n    (h : disjoint (t\u2081 a) (t\u2082 a)) : disjoint (pi s t\u2081) (pi s t\u2082) :=\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": "/-\nCopyright (c) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.auto_cases\nimport Mathlib.tactic.chain\nimport Mathlib.tactic.norm_cast\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\nnamespace tactic\n\n\nnamespace tidy\n\n\n/-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics\ncalled by `tidy`. -/\nend tidy\n\n\nnamespace interactive\n\n\n/-- Use a variety of conservative tactics to solve goals.\n\n`tidy?` reports back the tactic script it found. As an example\n```lean\nexample : \u2200 x : unit, x = unit.star :=\nbegin\n  tidy? -- Prints the trace message: \"Try this: intros x, exact dec_trivial\"\nend\n```\n\nThe default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.\nThis list can be overridden using `tidy { tactics := ... }`.\n(The list must be a `list` of `tactic string`, so that `tidy?`\ncan report a usable tactic script.)\n\nTactics can also be added to the list by tagging them (locally) with the\n`[tidy]` attribute. -/\nend interactive\n\n\n/-- Invoking the hole command `tidy` (\"Use `tidy` to complete the goal\") runs the tactic of\nthe same name, replacing the hole with the tactic script `tidy` produces.\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/tidy.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.05419873058703739, "lm_q1q2_score": 0.01832335096944656}}
{"text": "import tactic\nimport data.list.alist\nimport control.monad.basic\n\ndef disableClangFormat := ff\n\nclass has_hmul (\u03b1 \u03b2 : Type*) (\u03b3 : out_param Type*) :=\n  (mul : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\ninstance hmul_of_mul {\u03b1 : Type*} [has_mul \u03b1] : has_hmul \u03b1 \u03b1 \u03b1 := \u27e8has_mul.mul\u27e9\ninfix ` \u22c6 `:71 := has_hmul.mul\n\n@[reducible] def Ident := string\n@[reducible] def Label := string\n\n@[derive [decidable_eq, fintype]]\ninductive BinOp | add | sub | mul | lt | eq | lit_eq | and | or | min | max\n\n/-- Expressions for a simple imperative language. -/\n@[derive decidable_eq]\ninductive E\n| lit     : \u2115 \u2192 E\n| ident   : Ident \u2192 E\n| not     : E \u2192 E\n| bin_op  : BinOp \u2192 E \u2192 E \u2192 E\n| access  : E \u2192 E \u2192 E\n| ternary : E \u2192 E \u2192 E \u2192 E\n| inline_code : string \u2192 E\n\n-- todo simplify\n| incr  : E \u2192 E\n| attr  : E \u2192 E \u2192 E\n| arrow_op : E \u2192 E \u2192 E\n| call0 : E \u2192 E\n| call1 : E \u2192 E \u2192 E\n| call2 : E \u2192 E \u2192 E \u2192 E\n\n\n/-- Statements for a simple imperative language, including sequencing. -/\ninductive Prog\n| skip\n| accum (dst : E) (val : E)\n| store (dst : E) (val : E)\n| \u00abif\u00bb (b : E) (cons : Prog) (alt : Prog)\n| seq (a b : Prog)\n\n| block (body : Prog)\n| time  (n : string) (body : Prog)\n\n| while (cond : E) (body : Prog)\n| for (var bound : E) (body : Prog)\n\n-- todo simplify\n| declare (var : E) (initializer : E)\n| auto (var : E) (initializer : E)\n\n| inline_code (code : string)\n| expr : E \u2192 Prog\n| comment (c : string)\n\n--def Prog.accum := \u03bb l r, Prog.store l (l + r)\n\n@[pattern]\ndef Prog.if1 (b : E) (cons : Prog) : Prog := Prog.if b cons Prog.skip\n\n@[pattern] def E.false : E := E.lit 0\n@[pattern] def E.true  : E := E.lit 1\n\nnamespace E\n\ndef neg : E \u2192 E\n| (E.true) := E.false\n| (E.false) := E.true\n| e := e.not\n\ninfixr ` <;> `:1 := Prog.seq\ninfixr ` ;; `:1 := Prog.seq\ninfixr (name := seq) ` ; `:1 := Prog.seq\n--instance : has_andthen Prog Prog Prog := \u27e8Prog.seq\u27e9\n\ninstance : has_zero E := \u27e8E.lit 0\u27e9\ninstance : has_one E  := \u27e8E.lit 1\u27e9\ninstance : inhabited E := \u27e80\u27e9\n\ninstance : has_coe string E := \u27e8E.ident\u27e9\nend E\n\ndef BinOp.mk_type : BinOp \u2192 Type\n| _ := E \u2192 E \u2192 E\n\n-- a little smart\ndef BinOp.mk : \u03a0 (b : BinOp), BinOp.mk_type b\n| BinOp.and := \u03bb x y,\n  match x, y with\n  | E.true, y := y\n  | x, E.true := x\n  | E.false, y := E.false\n  | x, E.false := E.false\n  | x, y := E.bin_op BinOp.and x y\n  end\n| BinOp.or := \u03bb x y,\n  match x, y with\n  | E.false, y := y\n  | x, E.false := x\n  | E.true, _ := E.true\n  | _, E.true := E.true\n  | x, y := E.bin_op BinOp.or x y\n  end\n| BinOp.add := \u03bb x y,\n  match x, y with\n  | E.lit a, E.lit b := E.lit (a+b)\n  | E.lit 0, x := x\n  | x, E.lit 0 := x\n  | _, _ := E.bin_op BinOp.add x y\n  end\n| BinOp.mul := \u03bb x y,\n  match x, y with\n  | E.lit a, E.lit b := E.lit (a*b)\n  | E.lit 0, x := E.lit 0\n  | x, E.lit 0 := E.lit 0\n  | E.lit 1, x := x\n  | x, E.lit 1 := x\n  | _, _ := E.bin_op BinOp.mul x y\n  end\n| b := E.bin_op b\n\ninstance : has_coe_to_fun BinOp BinOp.mk_type := \u27e8BinOp.mk\u27e9\n\ninstance : has_add E := \u27e8BinOp.add\u27e9\ninstance : has_sub E := \u27e8BinOp.sub\u27e9\ninstance : has_mul E := \u27e8BinOp.mul\u27e9\n\n\nnamespace E\ndef store   : E \u2192 E \u2192 Prog := Prog.store\ndef accum   : E \u2192 E \u2192 Prog := Prog.accum\ndef declare : E \u2192 E \u2192 Prog := Prog.declare\nend E\n\nsection codegen\n\ninductive ValueType | int | float\nopen ValueType\ninductive TensorType\n| atom (ty : ValueType)\n| storage (ty : TensorType)\n| sparse (ty : TensorType)\n\nopen TensorType\n\ninductive CType\n| double | int | storage (ty : CType) | sparse (ty : CType)\n\nnamespace TensorType\ndef toCType : TensorType \u2192 CType\n| (atom ValueType.int) := CType.int\n| (atom ValueType.float) := CType.double\n| (storage t) := CType.storage (toCType t)\n| (sparse t) := CType.sparse (toCType t)\nend TensorType\n\n@[reducible] def SymbolTable := alist (\u03bb (s : string), TensorType)\nstructure Context :=\n(true_conditions  : list E)\n(false_conditions : list E)\n\ndef emptyContext := Context.mk [1] [0]\n\nstructure MState :=\n(counter : \u2115)\n(symbolTable : SymbolTable)\n(buffer : buffer char)\n\ninstance : has_emptyc MState := \u27e8\u27e80, \u2205, buffer.nil\u27e9\u27e9\n\n-- note: inserting a writer_t for collecting output code kills performance\n@[reducible] def M := state_t MState (reader Context)\n\ndef symbolType (var : string) : M TensorType :=\ndo\n  s \u2190 get,\n  match s.symbolTable.lookup var with\n  | some r := return r\n  | none := return (atom ValueType.int) -- todo\n  end\n\ndef runM {\u03b1} (m : M \u03b1) : \u03b1 := ((m.run \u2205).run emptyContext).fst\ndef BinOp.to_c : BinOp \u2192 string\n| BinOp.add := \"+\"\n| BinOp.sub := \"-\"\n| BinOp.mul := \"*\"\n| BinOp.lt := \"int_lt\"\n| BinOp.eq := \"int_eq\"\n| BinOp.lit_eq := \"==\"\n| BinOp.and := \"&&\"\n| BinOp.or := \"||\"\n| BinOp.min := \"min\"\n| BinOp.max := \"max\"\n\ndef wrap (s : string) : string := \"(\" ++ s ++ \")\"\n\ndef E.to_c : E \u2192 string\n| (E.lit i)                  := repr i\n| (E.ident i)                := i\n| (E.incr i)                 := wrap $ i.to_c ++ \"++\"\n| (E.not i)                  := \"!\" ++ wrap i.to_c\n| (E.bin_op BinOp.min e1 e2) := BinOp.min.to_c ++ (wrap $ e1.to_c ++ \",\" ++ e2.to_c)\n| (E.bin_op BinOp.max e1 e2) := BinOp.max.to_c ++ (wrap $ e1.to_c ++ \",\" ++ e2.to_c)\n| (E.bin_op BinOp.lt e1 e2)  := BinOp.lt.to_c ++ (wrap $ e1.to_c ++ \",\" ++ e2.to_c)\n| (E.bin_op BinOp.eq e1 e2)  := BinOp.eq.to_c ++ (wrap $ e1.to_c ++ \",\" ++ e2.to_c)\n| (E.bin_op op e1 e2)        := wrap $ e1.to_c ++ op.to_c ++ e2.to_c\n| (E.ternary c t e)          := wrap $ wrap c.to_c ++ \"?\" ++ t.to_c ++ \":\" ++ e.to_c\n| (E.access e i)             := e.to_c ++ \"[\" ++ i.to_c ++ \"]\"\n| (E.attr e i)               := e.to_c ++ \".\" ++ i.to_c\n| (E.arrow_op e i)              := e.to_c ++ \"->\" ++ i.to_c\n| (E.inline_code s)          := s\n| (E.call0 f)                := f.to_c ++ wrap \"\"\n| (E.call1 f a1)             := f.to_c ++ (wrap a1.to_c)\n| (E.call2 f a1 a2)          := f.to_c ++ (wrap $ a1.to_c ++ \",\" ++ a2.to_c)\n\ndef emit (str : string) : M unit := modify $ \u03bb s : MState,\n{ s with buffer := s.buffer.append_string str }\ndef emitLine (s : string) : M unit := do emit $ s ++ \";\"\n\nnamespace Prog\n\ndef to_c : Prog \u2192 M unit\n| (expr e)          := emitLine $ e.to_c\n| (accum dst val)   := emitLine $ dst.to_c ++ \" += \" ++ val.to_c\n| (store dst val)   := emitLine $ dst.to_c ++ \" = \" ++ val.to_c\n| (declare dst val) := emitLine $ \"index \" ++ dst.to_c ++ \" = \" ++ val.to_c\n| (auto dst val)    := emitLine $ \"auto \" ++ dst.to_c ++ \" = \" ++ val.to_c\n| (seq a b)         := a.to_c >> b.to_c\n| (while c body)    := emit (\"while\" ++ wrap c.to_c ++ \"{\") >> body.to_c >> emit \"}\"\n| (for i n body)    := emit ( \"for\" ++ wrap (i.to_c ++ \"= 0;\" ++ i.to_c ++ \"<\" ++ n.to_c ++ \";\" ++ i.to_c++\"++\") ++ \"{\"\n                          ) >> body.to_c >> emit \"}\"\n| (inline_code s)   := emit s\n| (skip)            := emit \"\"\n| (comment s)       := emit $ \"// \" ++ s ++ \"\\n\"\n| (if1 E.false t)   := emit \"\"\n| (if1 E.true t)    := t.to_c\n| (if1 c t)         := do\n    emit \"if (\" >> emit c.to_c >> emit \") {\",\n      t.to_c,\n    emit \"}\"\n| (\u00abif\u00bb c t e)      := do\n    emit \"if (\" >> emit c.to_c >> emit \") {\",\n      t.to_c,\n    emit \"}\", emit \" else {\",\n      e.to_c,\n    emit \"}\"\n| (block p)         := emit \"{\" >> p.to_c >> emit \"}\"\n| (time n p)          :=\n  emit \"{\" >>\n  ( emit (\"cout << \\\"\\\\ntiming (\" ++ n ++ \"):\\\" << endl;\") >>\n    emit \"out_val = 0.0; auto t1 = std::chrono::high_resolution_clock::now();\" >>\n    p.to_c >>\n    emit \"auto t2 = std::chrono::high_resolution_clock::now();\" >>\n    emit \"cout << \\\"out: \\\" << out_val << endl;\" >>\n    emit \"std::cout << \\\"took: \\\" << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count() << std::endl;\"\n  ) >> emit \"}\"\nend Prog\n\ndef M.runInfo {\u03b1} (m : M \u03b1) : SymbolTable \u00d7 buffer char :=\n(\u03bb s : MState, (s.symbolTable, s.buffer)) ((m.run \u2205).run emptyContext).snd\n\ndef M.runBuffer {\u03b1} (m : M \u03b1) : string := m.runInfo.snd.to_string\n\ndef addHeaderFooter : string \u2192 string :=\n\u03bb s, \"#include \\\"prefix.cpp\\\"\\n\" ++ s ++ \"#include \\\"suffix.cpp\\\"\\n\"\n\ndef compile (progs : (list Prog)) : io unit :=\n  let outName := \"out_lean.cpp\" in do\n  handle \u2190 io.mk_file_handle outName io.mode.write,\n  let result : string := addHeaderFooter $ (progs.mmap (Prog.to_c \u2218 Prog.block)).runBuffer,\n  io.fs.write handle result.to_char_buffer,\n  io.fs.close handle,\n  if disableClangFormat then return () else io.cmd {cmd := \"clang-format\", args := [\"-i\", outName]} >> return ()\n\ndef comp : Prog \u2192 io unit := compile \u2218 pure\n\n-- #check monad.mapm\n\nend codegen\n\nsection G\n\nvariables {\u03b1 \u03b9 \u03b3 \u03b2 : Type}\n\nlocal infixl (name := and) ` && `:70 := BinOp.and\nlocal infixl (name := or)  ` || `:65 := BinOp.or\nlocal infix  (name := lt)  ` < `:71  := BinOp.lt\ninfix  (name := eq)  ` == `:71 := BinOp.eq\ninfix  (name := teq) ` === `:71 := BinOp.lit_eq\ninfix  (name := ne)  ` != `:71 := \u03bb a b, (BinOp.eq a b).neg\n@[pattern] def E.le : E \u2192 E \u2192 E := \u03bb a b, BinOp.or (a < b) (a == b)\nlocal infix  (name := le) ` \u2264 `:71  := E.le\n\n--notation e `\u27e6` k `\u27e7` := e.access k\n\nstructure G (\u03b9 \u03b1 : Type) :=\n  (index : \u03b9)   (value : \u03b1)\n  (ready : E)   (valid : E)\n  (init : Prog) (next : Prog)\n\ndef G.empty [inhabited \u03b9] [inhabited \u03b1] : G \u03b9 \u03b1 :=\n{ index := default, value := default, ready := E.false, valid := E.false, init := Prog.skip, next := Prog.skip }\n\nstructure View (\u03b9 \u03b1 : Type) := (value : \u03b9 \u2192 \u03b1)\n\ndef constView (\u03b9 : Type) (v : \u03b1) : View \u03b9 \u03b1 := \u27e8\u03bb _, v\u27e9\nprefix (name := const) ` \u21d1 ` := constView\n-- instance : has_coe (\u03b1 \u2192 \u03b2) (View \u03b1 \u03b2) := \u27e8View.mk\u27e9\n\ninstance {\u03b9 : Type*} : functor (G \u03b9) :=\n{ map := \u03bb _ _ f g, { g with value := f g.value } }\n\ninstance {\u03b9 : Type*} : functor (View \u03b9) :=\n{ map := \u03bb _ _ f v, { v with value := f \u2218 v.value } }\n\ninstance View.has_hmul [has_hmul \u03b1 \u03b2 \u03b3] : has_hmul (View \u03b9 \u03b1) (View \u03b9 \u03b2) (View \u03b9 \u03b3) :=\n\u27e8\u03bb a b, \u27e8\u03bb i, a.value i \u22c6 b.value i\u27e9\u27e9\n\nnamespace G\ndef iv {\u03b9 \u03b9' \u03b1 \u03b1'} (i : \u03b9 \u2192 \u03b9') (v : \u03b1 \u2192 \u03b1') : G \u03b9 \u03b1 \u2192 G \u03b9' \u03b1'\n:= \u03bb g, { g with value := v g.value, index := i g.index }\n\ndef mul [has_hmul \u03b1 \u03b2 \u03b3] (a : G E \u03b1) (b : G E \u03b2) : G E \u03b3 :=\n{ index := BinOp.max a.index b.index,\n  value := a.value \u22c6 b.value,\n  ready := a.ready && b.ready && a.index == b.index,\n  next  := Prog.if (a.index < b.index ||\n                   (a.index == b.index && a.ready.neg))\n                        a.next\n                        b.next,\n  valid := a.valid && b.valid,\n  init  := a.init; b.init,\n}\ninstance [has_hmul \u03b1 \u03b2 \u03b3] : has_hmul (G E \u03b1) (G E \u03b2) (G E \u03b3) := \u27e8mul\u27e9\n\ninstance smul_G [has_smul E \u03b1] : has_smul E (G E \u03b1) :=\n\u27e8\u03bb s v, { v with value := s \u2022 v.value } \u27e9\ninstance smul_unit [has_smul E \u03b1] : has_smul E (G unit \u03b1) :=\n\u27e8\u03bb s v, { v with value := s \u2022 v.value } \u27e9\ninstance smul_base [has_hmul E \u03b1 \u03b1] : has_smul E \u03b1 := \u27e8(\u22c6)\u27e9\n\nexample : has_smul E E := infer_instance\n\ndef add [has_smul E \u03b1] [has_mul \u03b1] [has_add \u03b1] (a b : G E \u03b1) : G E \u03b1 :=\nlet current := BinOp.min a.index b.index in\n{ index := current,\n  value := (a.index == current) \u2022 a.value + (b.index == current) \u2022 b.value,\n  ready := a.ready || b.ready,\n  next  := Prog.if (a.index < b.index ||\n                   (a.index == b.index && a.ready.neg && b.ready)) -- ($) <$>\n             a.next\n             $ (Prog.if (b.index < a.index ||\n                        (a.index == b.index && b.ready.neg && a.ready))\n                  b.next\n                  (a.next; b.next)),\n  valid := a.valid || b.valid,\n  init  := a.init; b.init,\n}\n\ninstance [has_mul \u03b1] [has_smul E \u03b1] [has_add \u03b1] : has_add (G E \u03b1) := \u27e8add\u27e9\n\ndef mul_unit_const_r [has_hmul \u03b1 \u03b2 \u03b3] (a : G unit \u03b1) (b : \u03b2) : G unit \u03b3 := (\u22c6 b) <$> a\ndef mul_unit_const_l [has_hmul \u03b1 \u03b2 \u03b3] (a : \u03b1) (b : G unit \u03b2) : G unit \u03b3 := (\u03bb v, a \u22c6 v) <$> b\ndef mulViewR [has_hmul \u03b1 \u03b2 \u03b3] (a : G \u03b9 \u03b1) (b : View \u03b9 \u03b2) : G \u03b9 \u03b3 :=\n(\u22c6 b.value a.index) <$> a\ndef mulViewL [has_hmul \u03b1 \u03b2 \u03b3] (a : View \u03b9 \u03b1) (b : G \u03b9 \u03b2) : G \u03b9 \u03b3 :=\n(\u03bb v, a.value b.index \u22c6 v) <$> b\n\ninstance GV.has_hmul [has_hmul \u03b1 \u03b2 \u03b3] : has_hmul (G \u03b9 \u03b1) (View \u03b9 \u03b2) (G \u03b9 \u03b3) := \u27e8G.mulViewR\u27e9\ninstance VG.has_hmul [has_hmul \u03b1 \u03b2 \u03b3] : has_hmul (View \u03b9 \u03b1) (G \u03b9 \u03b2) (G \u03b9 \u03b3) := \u27e8G.mulViewL\u27e9\ninstance unit_const_r.has_hmul [has_hmul \u03b1 \u03b2 \u03b3] : has_hmul (G unit \u03b1) \u03b2 (G unit \u03b3) := \u27e8mul_unit_const_r\u27e9\ninstance unit_const_l.has_hmul [has_hmul \u03b1 \u03b2 \u03b3] : has_hmul \u03b1 (G unit \u03b2) (G unit \u03b3) := \u27e8mul_unit_const_l\u27e9\ninstance [has_mul \u03b1] : has_mul (G E \u03b1) := \u27e8(\u22c6)\u27e9\n\nend G\n\nsection simple_streams\n\ndef interval (i : E) (counter : E) (lower upper : E) : G E E :=\n{ index := i.access counter, value := counter, ready := E.true, valid := counter < upper,\n  init  := counter.declare lower, next  := counter.accum 1,\n}\n\ndef range (counter bound : E) : G E E :=\n{ index := counter, value := counter, ready := E.true, valid := counter < bound,\n  init  := counter.declare 0, next  := counter.accum 1 }\n\ndef View.to_gen (counter bound : E) (view : View E \u03b1) : G E \u03b1 := view.value <$> range counter bound\n\nend simple_streams\n\nsection csr\n\n/- implementation of composable sparse rval level -/\nsection rval\n\n-- in TACO terminology, i = n_crd, v = n_pos. var indexes i.\nstructure csr := (i v var : E)\n\ndef csr.of (name : string) (n : \u2115) : csr :=\n  let field (x : string) := E.ident $ name ++ n.repr ++ x in\n  { i := field \"_crd\", v := field \"_pos\", var := field \"_i\" }\n\ndef csr'.of (name : string) (n : \u2115) : csr :=\n  let field  (x : string) := E.ident $ name ++ n.repr ++ x in\n  let field' (x : string) := E.ident $ name ++ (n+1).repr ++ x in\n  { i := field \"_crd\", v := field' \"_pos\", var := field \"_i\" }\n\ndef csr.level : csr \u2192 E \u2192 G E E := \u03bb csr loc,\ninterval csr.i csr.var (csr.v.access loc) (csr.v.access (loc+1))\ndef G.level   : csr \u2192 G E E \u2192 G E (G E E) := functor.map \u2218 csr.level\ndef G.leaf    :   E \u2192 G E E \u2192 G E E       := functor.map \u2218 E.access -- \u03bb v, functor.map $ \u03bb i, E.access v i\n\nend rval\n\n/- csr lval v3 -/\n/- implementation of composable sparse lval level -/\nsection csr_lval\n@[reducible] def loc := E\nstructure il :=\n  (crd  : loc \u2192 E)\n  (push : E \u2192 (loc \u2192 Prog) \u2192 Prog \u00d7 loc)\nstructure vl  (\u03b1 : Type) :=\n  (pos  : loc \u2192 \u03b1)\n  (init : loc \u2192 Prog)\nstructure lvl (\u03b1 : Type) extends il, vl \u03b1.\ninstance : functor lvl := { map := \u03bb _ _ f l, { l with pos := f \u2218 l.pos } }\n\ndef sparse_index (indices : E) (bounds : E \u00d7 E) : il :=\nlet upper := bounds.2, lower := bounds.1, current := indices.access (upper-1) in\nlet loc := upper-1 in\n{ crd  := indices.access,\n  push := \u03bb i init,\n    let prog := Prog.if1 (lower == upper || i != current)\n                      ((upper.accum 1); init loc);\n                     current.store i\n    in (prog, loc) }\n\ndef dense_index (dim : E) (counter : E) (base : E) : il :=\n{ crd  := id,\n  push := \u03bb i init,\n    let l i  : loc := base * dim + i,\n        prog : Prog := Prog.while (counter \u2264 i) (init (l counter); counter.accum 1)\n    in (prog, l i) }\n\ndef interval_vl (array : E) : vl (E \u00d7 E) :=\nlet fn := array.access in\n{ pos  := \u03bb loc, (array.access loc, array.access (loc + 1)),\n  init := \u03bb loc, (fn (loc + 1)).store (fn loc) }\n\ndef dense_vl    (array : E) : vl E :=\n{ pos := \u03bb loc, array.access loc,\n  init := \u03bb loc, (array.access loc).store 0 }\n\ndef implicit_vl : vl E := { pos := id, init := \u03bb _, Prog.skip }\n\n-- def base (array : E) : lvl E := { i_shift := \u03bb _ i, array.access i,  }\n\ndef rev_fmap_comp {f} [functor f] (x : \u03b1 \u2192 f \u03b2) (y : \u03b2 \u2192 f \u03b3) := functor.map y \u2218 x\ninfixr ` \u229a `:90 := rev_fmap_comp\ndef rev_app : \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2 := function.swap ($)\ninfixr ` & `:9 := rev_app\n\n-- this combinator combines an il with a vl to form a lvl.\n-- the extra parameter \u03b1 is used to thread the primary argument to a level through \u229a.\n--   see dcsr/csr_mat/dense below\ndef with_values : (\u03b1 \u2192 il) \u2192 vl \u03b2 \u2192 \u03b1 \u2192 lvl \u03b2 := \u03bb i v e, lvl.mk (i e) v\n\ndef dense_mat (d\u2081 d\u2082 : E) := 0 &\n  (with_values (dense_index d\u2081 \"i1\") implicit_vl) \u229a\n  (with_values (dense_index d\u2082 \"i2\") $ dense_vl \"values\")\n\ndef cube_lvl := 0 &\n  (with_values (dense_index 11 \"i1\") implicit_vl) \u229a\n  (with_values (dense_index 7 \"i2\") implicit_vl) \u229a\n  (with_values (dense_index 5 \"i3\") $ dense_vl \"values\")\n\ndef sparse_vec := (0, E.ident \"size\") &\n  (with_values (sparse_index \"A1_crd\") (dense_vl \"A_vals\"))\n\ndef dcsr := (interval_vl \"A1_pos\").pos 0 &\n  (with_values (sparse_index \"A1_crd\") (interval_vl \"A2_pos\")) \u229a\n  (with_values (sparse_index \"A2_crd\") (dense_vl \"A_vals\"))\n\ndef csr_mat := 0 &\n  (with_values (dense_index 2000 \"i1\") (interval_vl \"B2_pos\")) \u229a\n  (with_values (sparse_index \"B2_crd\") (dense_vl \"B_vals\"))\n\nend csr_lval\n\n/- csr lval v2. TODO remove -/\nstructure lval (\u03b1 : Type) := (push : E \u2192 Prog \u00d7 \u03b1)\ninstance : functor lval := { map := \u03bb _ _ f l, { l with push := prod.map id f \u2218 l.push } }\n\ndef csr.base (csr : csr) : E\u00d7E := ((csr.v.access 0), (csr.v.access 1))\ndef csr.lval (csr : csr) (bounds : E\u00d7E) : lval (E\u00d7E)  :=\nlet upper := bounds.2, lower := bounds.1 in\n{ push := \u03bb i,\n  let prog := Prog.if1 (lower == upper || (i != csr.i.access (upper-1) &&\n                                            (csr.v.access upper != csr.v.access (upper-1))))\n                 (upper.accum 1; (csr.v.access upper).store (csr.v.access (upper-1)));\n               (csr.i.access (upper-1)).store i,\n      value := ((csr.v.access (upper-1)), (csr.v.access upper)) in (prog, value)\n}\n\ndef csr.vec (csr : csr) (bounds : E\u00d7E) : lval E :=\nlet upper := bounds.2, lower := bounds.1 in\n{ push := \u03bb i, (Prog.if1 (lower == upper || (i != csr.i.access (upper-1) &&\n                                            (0 != csr.v.access (upper-1))))\n                 (upper.accum 1; (csr.v.access (upper-1)).store 0);\n               (csr.i.access (upper-1)).store i, csr.v.access (upper-1))\n}\n\n/- csr lval v1. TODO remove -/\nstructure pre  := (pre : Prog)\nstructure new  := (new : Prog) -- (acc : E \u2192 \u03b1)\nstructure post := (post : Prog)\n\n-- push values at the leaf level\ndef push_value (var val_array outer_var : E) : new \u00d7 post \u00d7 E :=\n({new := (val_array.access outer_var).store 0}, \u27e8Prog.skip\u27e9, (val_array.access var))\n\n-- if pack is true, we allow for an rval that produces duplicate coordinates and de-duplicate them as they are aggregated\ndef push_level_pack' (pack : bool) (csr : csr) (k : E \u2192 new \u00d7 post \u00d7 \u03b1) : (E \u2192 new \u00d7 post \u00d7 (E \u2192 pre \u00d7 \u03b1))\n:= \u03bb outer_var,\n( { new := (csr.v.access outer_var).store (csr.var+1) },\n  { post := (csr.v.access (outer_var+1)).store (csr.var+1); (k csr.var).2.1.post },\n   \u03bb i, (\u27e8(if pack then Prog.if1 (csr.var < csr.v.access outer_var || i != csr.i.access csr.var) else id) $\n             csr.var.accum 1; (csr.i.access csr.var).store i; (k csr.var).1.new\u27e9,\n         (k csr.var).2.2))\n\ndef push_level_pack : csr \u2192 (E \u2192 new \u00d7 post \u00d7 \u03b1) \u2192 (E \u2192 new \u00d7 post \u00d7 (E \u2192 pre \u00d7 \u03b1)) :=\npush_level_pack' tt\ndef push_level      : csr \u2192 (E \u2192 new \u00d7 post \u00d7 \u03b1) \u2192 (E \u2192 new \u00d7 post \u00d7 (E \u2192 pre \u00d7 \u03b1)) :=\npush_level_pack' ff\n\ndef vec_lval' (n : string) :=\nprod.snd $ (push_level_pack (csr.of n 1) $ push_value (csr.of n 1).var (E.ident $ n ++ \"_vals\")) 0\ndef mat_lval' (n : string) :=\nprod.snd $ (push_level_pack (csr.of n 1) $ push_level_pack (csr.of n 2) $ push_value (csr.of n 2).var (E.ident $ n ++ \"_vals\")) 0\ndef mval (n : string) :=\nprod.snd $ (push_level (csr.of n 1) $ push_level (csr.of n 2) $ push_value (csr.of n 2).var (E.ident $ n ++ \"_vals\")) 0\ndef cub_lval' (n : string) :=\nprod.snd $ (push_level_pack (csr.of n 1) $ push_level_pack (csr.of n 2) $ push_level_pack (csr.of n 3) $ push_value (csr.of n 3).var (E.ident $ n ++ \"_vals\")) 0\ndef cub_lval'' (n : string) :=\nprod.snd $ (push_level (csr.of n 1) $ push_level (csr.of n 2) $ push_level (csr.of n 3) $ push_value (csr.of n 3).var (E.ident $ n ++ \"_vals\")) 0\n#check mat_lval'\n\nend csr\n\ndef indexed_mat_lval (var : E) (i j v : E) := ((var.access i).access j).accum v\n\ndef fmap1 {\u03b1 \u03b2 f} [functor f] : (\u03b1 \u2192 \u03b2) \u2192 f \u03b1 \u2192 f \u03b2 := functor.map\ndef fmap2 {\u03b1 \u03b2 f} [functor f] : (\u03b1 \u2192 \u03b2) \u2192 f (f \u03b1) \u2192 f (f \u03b2) := functor.map \u2218 functor.map\n\nclass Compile (l r : Type) := (eval : l \u2192 r \u2192 Prog)\nclass Scalar (\u03b1 : Type) := (fold : \u03b1 \u2192 E \u2192 Prog) (value : \u03b1 \u2192 E)\ninstance : Scalar E := \u27e8\u03bb l r, l.accum r, id\u27e9\n\n-- offset into array:\ninstance : Scalar (E \u00d7 E) := \u27e8\u03bb l r, (l.2.access l.1).accum r, \u03bb l, l.2.access l.1\u27e9\n\n--instance discard.eval : Compile unit E := \u27e8\u03bb _ _, Prog.skip\u27e9\ninstance base.eval [Scalar \u03b1] : Compile \u03b1 E :=\n{ eval := \u03bb l v, Scalar.fold l v }\n-- todo remove\ninstance base.eval' : Compile (E \u2192 Prog) E :=\n{ eval := \u03bb acc v, acc v }\n\ninstance unit.eval [Compile \u03b1 \u03b2] : Compile \u03b1 (G unit \u03b2) :=\n{ eval := \u03bb acc v,\n    v.init; Prog.while v.valid\n      (Prog.if1 v.ready (Compile.eval acc v.value) ; v.next) }\n\ninstance lvl.eval [Compile \u03b1 \u03b2] : Compile (lvl \u03b1) (G E \u03b2) :=\n{ eval := \u03bb storage v,\n    let (push_i, loc) := storage.push v.index storage.init in\n    v.init ;\n    Prog.while v.valid\n      (Prog.if1 v.ready\n        (push_i;\n         Compile.eval (storage.pos loc) v.value);\n      v.next) }\n\ninstance lval.eval [Compile \u03b1 \u03b2] : Compile (lval \u03b1) (G E \u03b2) :=\n{ eval := \u03bb acc v,\n    let loop_body := acc.push v.index in\n    v.init ;\n    Prog.while v.valid\n      (Prog.if1 v.ready\n        (loop_body.1;\n         Compile.eval loop_body.2 v.value);\n      v.next) }\n\n-- instance unit.bool [Scalar \u03b1] [Compile \u03b1 \u03b2] : Compile \u03b1 (G unit \u03b2) :=\n-- { eval := \u03bb acc v,\n--     v.init; Prog.while (v.valid && (Scalar.value acc).neg)\n--       (Prog.if1 v.ready (Compile.eval acc v.value) ; v.next) }\n\ninstance level.eval  [Compile \u03b1 \u03b2] : Compile (E \u2192 \u03b1) (G E \u03b2) :=\n{ eval := \u03bb acc v,\n    v.init; Prog.while v.valid\n      (Prog.if1 v.ready (Compile.eval (acc v.index) v.value);\n      v.next) }\n\ninstance level_pre.eval [Compile \u03b1 \u03b2] : Compile (E \u2192 pre \u00d7 \u03b1) (G E \u03b2) :=\n{ eval := \u03bb acc v,\n    let loop_body := acc v.index in\n    v.init ;\n    Prog.while v.valid\n      (Prog.if1 v.ready\n        (loop_body.1.pre;\n         Compile.eval loop_body.2 v.value);\n      v.next) }\n\ninstance level_outer_post.eval [Compile \u03b1 \u03b2] : Compile (post \u00d7 \u03b1) \u03b2 :=\n{ eval := \u03bb lhs v, let (x, acc) := lhs in Compile.eval acc v; x.post }\n\n-- janky map-based generator:\n-- i   = get<0>(x->first)\n-- j   = get<1>(x->first)\n-- val = x.second\ndef coo_rval (n : \u2115) (matrix var : E) : (G E E) :=\nlet call (a b : E) := E.call0 (a.attr b) in\n{ index := E.call1 (E.ident $ \"get<\" ++ n.repr ++ \">\") $ var.arrow_op \"first\",\n  value := var.arrow_op \"second\",\n  ready := E.true,\n  valid := E.neg $ var === call matrix \"end\",\n  init  := Prog.auto var $ call matrix \"begin\",\n  next  := Prog.expr $ var.incr,\n}\ndef coo_rval_inner (n : \u2115) (matrix var : E) : (G E E) :=\n{ coo_rval n matrix var with\n  next := Prog.inline_code \"break;\",\n  valid := E.true,\n  init := Prog.skip }\n\ndef coo_vector_rval (matrix var : E) : (G E E) := coo_rval 0 matrix var\ndef coo_matrix_rval (matrix var : E) : G E (G E E) :=\nfmap1 (\u03bb _, coo_rval_inner 1 matrix var) $ coo_vector_rval matrix var\ndef coo_cube_rval   (matrix var : E) : G E (G E (G E E)) :=\nfmap2 (\u03bb _, coo_rval_inner 2 matrix var) $ coo_matrix_rval matrix var\n\nnamespace G\ndef contract (g : G \u03b9 \u03b1) : G unit \u03b1 := { g with index := () }\ndef sum1 : G E \u03b1 \u2192 G unit \u03b1 := contract\ndef sum2 : (G E (G E \u03b1)) \u2192 (G unit (G unit \u03b1)) :=\n(functor.map $ sum1) \u2218 contract\ndef sum2' : (G E (G E E)) \u2192 (G unit (G unit E)) :=\n(functor.map $ sum1) \u2218 contract\ndef sum3'  : G E (G E (G E \u03b1)) \u2192 G unit (G unit (G unit \u03b1)) :=\n(functor.map $ sum2) \u2218 contract\ndef sum3 : G E (G E (G E E)) \u2192 G unit (G unit (G unit E)) :=\n(functor.map $ sum2) \u2218 contract\ndef sum_inner : G E (G E (G E E)) \u2192 G E (G E (G unit E)) := functor.map $ functor.map G.contract\n\nend G\n\ndef v  : G E E       := G.leaf \"V_vals\" $ ((csr.of \"V\" 1).level 0)\ndef A  : G E (G E E) := (csr.of \"A\" 1).level 0 & G.level (csr.of \"A\" 2) \u229a G.leaf \"A_vals\"\ndef A_csr  : G E (G E E) :=\n  let dense : G E E := range \"_i\" 2000 in\n  dense & G.level (csr.of \"A\" 2) \u229a G.leaf \"A_vals\"\ndef B_csr  : G E (G E E) :=\n  let dense : G E E := range \"_i\" 2000 in\n  dense & G.level (csr.of \"B\" 2) \u229a G.leaf \"B_vals\"\ndef B  : G E (G E E) := (csr.of \"B\" 1).level 0 & G.level (csr.of \"B\" 2) \u229a G.leaf \"B_vals\"\ndef C  : G E (G E (G E E)) := (csr.of \"C\" 1).level 0 & G.level (csr.of \"C\" 2) \u229a G.level (csr.of \"C\" 3) \u229a G.leaf \"C_vals\"\ndef D  : G E (G E (G E E)) := (csr.of \"D\" 1).level 0 & G.level (csr.of \"D\" 2) \u229a G.level (csr.of \"D\" 3) \u229a G.leaf \"D_vals\"\ndef M_  : G E (G E E) := G.leaf \"M_vals\" <$> ((csr.of \"M\" 1).level 0).level (csr.of \"M\" 2)\n\ndef exec {l r} [Compile l r] := @Compile.eval l r\n\ndef single (x : \u03b1) := (\u21d1 E x).to_gen \"i\" 1\n#eval (single (3 : E)).ready.to_c\ndef eg00  := exec (E.ident \"out\") (E.lit 2)\ndef eg00' := exec (E.ident \"out\") (v.contract)\ndef eg01 := exec (Prog.accum \"out\") (G.contract <$> A.contract)\ndef eg02 := exec (Prog.accum \"out\") (G.sum2 $ A\u22c6B)\ndef eg03 := exec (Prog.accum \"out\") (G.sum2 $ (\u21d1 E v) \u22c6 A)\ndef eg04 := exec (Prog.accum \"out\") (G.sum3 $ ((\u21d1 E) <$> A) \u22c6 \u21d1 E B ) -- (i,k)*(j,k)\n\ndef inner_prod := (fmap1 (\u21d1 E) A) \u22c6 \u21d1 E B -- (i,k)*(j,k)\n-- (i,j)*(j,k)\ndef comb_rows : G E (G E (G unit E)) := G.sum_inner $ (fmap2 (\u21d1 E) A) \u22c6 \u21d1 E B\n\ndef me := Prog.time \"me\"\ndef ta := Prog.time \"taco\"\n\ndef c0 : csr := { i := \"\", v := \"A1_pos\", var := \"\" }\ndef c1 : csr := csr'.of \"A\" 1\ndef c2 : csr := { i := \"A2_crd\", v := \"A_vals\", var := \"\" }\ndef A_lval := c0.base & ( c1.lval \u229a c2.vec )\n\ndef out : E := \"out_val\"\n\ndef eg05 := exec (Prog.accum \"out\") $ G.sum3 $ (fmap2 (\u21d1 E) A) \u22c6 (fmap1 (\u21d1 E) B) -- (i,j)*(i,k)\ndef matsum := comb_rows.sum2\ndef eg06 := exec (Prog.accum \"out\") matsum\ndef eg07 := exec (indexed_mat_lval \"out\") (A\u22c6B)\ndef ref_vector (n : string) := (coo_vector_rval (E.ident $ n ++ \".data\") \"entry\")\ndef ref_matrix (n : string) := (coo_matrix_rval (E.ident $ n ++ \".data\") \"entry\")\ndef ref_cube   (n : string) := (coo_cube_rval   (E.ident $ n ++ \".data\") \"entry\")\ndef ref_x := ref_matrix \"x\"\ndef ref_y := ref_matrix \"y\"\ndef ref_M := ref_matrix \"M\"\ndef eg18 := exec (\u03bb (_ _ : E), Prog.accum \"out\") A\ndef load_AB' := [exec (mat_lval' \"A\") ref_x, exec (mat_lval' \"B\") ref_x]\ndef load_AB : list Prog := [\n  Prog.time \"gen A\" $ exec (mat_lval' \"A\") (ref_matrix \"x\"),\n  Prog.time \"gen B\" $ exec (mat_lval' \"B\") (ref_matrix \"y\") ]\ndef eg19 := load_AB' ++ [Prog.time \"me\" $ exec (mat_lval' \"out\") $ A\u22c6B]\ndef taco_ijk := Prog.inline_code \"taco_ijk_sum();\"\ndef eg21 := exec (vec_lval' \"out\") v\ndef eg22 := me $ exec (mat_lval' \"out\") A\ndef eg23 := load_AB' ++ [Prog.time \"me\" $ exec (mval \"out\") $ inner_prod.sum_inner]\ndef eg24 := exec (\u03bb i, (Prog.accum $ out.access i)) ((\u03bb (i : E), 2*i) <$> (range \"i\" 10))\ndef eg25 := exec (Prog.accum out) ((\u03bb (i : E), 2*i) <$> (range \"i\" 10)).contract\ndef eg20 := load_AB ++ [me $ eg06, Prog.time \"taco\" $ taco_ijk]\ndef eg26 := load_AB ++ [me $ exec out $ G.sum2 (comb_rows), Prog.time \"taco\" $ taco_ijk]\ndef eg27 := load_AB ++ [me $ exec (mval \"out\") $ comb_rows]\n\ndef load := [\n  exec A_lval (ref_matrix \"x\"),\n  exec (mat_lval' \"B\") (ref_matrix \"y\"),\n  exec (cub_lval' \"C\") (ref_cube \"c\"),\n  exec (cub_lval' \"D\") (ref_cube \"c\"),\n  exec (vec_lval' \"V\") (ref_vector \"v\")]\n\ndef eg28 := load_AB ++ [\n  Prog.time \"me\" $ exec (mval \"out\") $ inner_prod.sum_inner,\n  Prog.time \"taco\" $ Prog.inline_code \"taco_ikjk();\" ]\n\ndef eg29 := load ++ [exec (mval \"out\") (A + B)]\ndef eg30 := exec out (C + D).sum3\n\n--#eval comp $ exec A_lval A\n--#eval compile $ [exec A_lval (ref_matrix \"x\"), me $ exec out $ G.sum2 $ A ]\n--#eval compile $ [exec sparse_vec (ref_vector \"v\")] -- , me $ exec out $ G.sum2 $ A ]\n--#eval compile $ [exec dcsr (ref_matrix \"x\"), me $ exec out $ G.sum2 $ A ]\n\n-- compare dcsr anc csr:\ndef eg31 := compile $\n[ exec dcsr (ref_matrix \"x\"),\n  exec csr_mat (ref_matrix \"x\"),\n  me $ exec out $ B_csr.sum2,\n  me $ exec out $ (ref_matrix \"x\").sum2 ]\n--#eval eg31\n\nend G\n", "meta": {"author": "kovach", "repo": "etch", "sha": "26ef67eb83cf7c5cfd1667059e16c3873b9098ca", "save_path": "github-repos/lean/kovach-etch", "path": "github-repos/lean/kovach-etch/etch-26ef67eb83cf7c5cfd1667059e16c3873b9098ca/src/compile_fast.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.041462273599738315, "lm_q1q2_score": 0.018312767002485478}}
{"text": "import classes.unrestricted.basics.toolbox\nimport utilities.list_utils\n\n\nsection functions_lift_sink\n\nvariables {T N\u2080 N : Type}\n\ndef lift_symbol_ (lift_N : N\u2080 \u2192 N) : symbol T N\u2080 \u2192 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 \u2192 option N\u2080) : symbol T N \u2192 option (symbol T N\u2080)\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\u2080 \u2192 N) : list (symbol T N\u2080) \u2192 list (symbol T N) :=\nlist.map (lift_symbol_ lift_N)\n\ndef sink_string_ (sink_N : N \u2192 option N\u2080) : list (symbol T N) \u2192 list (symbol T N\u2080) :=\nlist.filter_map (sink_symbol_ sink_N)\n\ndef lift_rule_ (lift_N : N\u2080 \u2192 N) : grule T N\u2080 \u2192 grule T N :=\n\u03bb r : grule T N\u2080, 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\u2080 g : grammar T)\n(lift_nt : g\u2080.nt \u2192 g.nt)\n(sink_nt : g.nt \u2192 option g\u2080.nt)\n(lift_inj : function.injective lift_nt)\n(sink_inj : \u2200 x y, sink_nt x = sink_nt y \u2192\n  x = y  \u2228  sink_nt x = none\n)\n(lift_nt_sink : \u2200 n\u2080 : g\u2080.nt, sink_nt (lift_nt n\u2080) = some n\u2080)\n(corresponding_rules : \u2200 r : grule T g\u2080.nt,\n  r \u2208 g\u2080.rules \u2192\n    lift_rule_ lift_nt r \u2208 g.rules\n)\n(preimage_of_rules : \u2200 r : grule T g.nt,\n  (r \u2208 g.rules \u2227 \u2203 n\u2080 : g\u2080.nt, lift_nt n\u2080 = r.input_N) \u2192\n    (\u2203 r\u2080 \u2208 g\u2080.rules, lift_rule_ lift_nt r\u2080 = r)\n)\n\nprivate lemma lifted_grammar_inverse {T : Type} (lg : lifted_grammar_ T) :\n  \u2200 x : lg.g.nt,\n    (\u2203 val, lg.sink_nt x = some val) \u2192\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\u2081 w\u2082 : list (symbol T lg.g\u2080.nt)}\n    (hyp : grammar_transforms lg.g\u2080 w\u2081 w\u2082) :\n  grammar_transforms lg.g (lift_string_ lg.lift_nt w\u2081) (lift_string_ lg.lift_nt w\u2082) :=\nbegin\n  rcases hyp with \u27e8r, rin, u, v, bef, aft\u27e9,\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\u2081 w\u2082 : list (symbol T lg.g\u2080.nt)}\n    (hyp : grammar_derives lg.g\u2080 w\u2081 w\u2082) :\n  grammar_derives lg.g (lift_string_ lg.lift_nt w\u2081) (lift_string_ lg.lift_nt w\u2082) :=\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 \u2192 Prop\n| (symbol.terminal t)    := true\n| (symbol.nonterminal n) := (\u2203 n\u2080 : lg.g\u2080.nt, lg.sink_nt n = n\u2080)\n\ndef good_string_ {lg : lifted_grammar_ T} (s : list (symbol T lg.g.nt)) :=\n\u2200 a \u2208 s, good_letter_ a\n\nprivate lemma sink_tran_ {lg : lifted_grammar_ T} {w\u2081 w\u2082 : list (symbol T lg.g.nt)}\n    (hyp : grammar_transforms lg.g w\u2081 w\u2082)\n    (ok_input : good_string_ w\u2081) :\n  grammar_transforms lg.g\u2080 (sink_string_ lg.sink_nt w\u2081) (sink_string_ lg.sink_nt w\u2082)\n  \u2227 good_string_ w\u2082 :=\nbegin\n  rcases hyp with \u27e8r, rin, u, v, bef, aft\u27e9,\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 \u2203 n\u2080 : lg.g\u2080.nt, lg.sink_nt r.input_N = some n\u2080 at good_matched_nonterminal,\n    cases good_matched_nonterminal with n\u2080 hn\u2080,\n    use n\u2080,\n    have almost := congr_arg (option.map lg.lift_nt) hn\u2080,\n    rw lifted_grammar_inverse lg r.input_N \u27e8n\u2080, hn\u2080\u27e9 at almost,\n    rw option.map_some' at almost,\n    apply option.some_injective,\n    exact almost.symm,\n  }) with \u27e8r\u2080, pre_in, preimage\u27e9,\n\n  split, swap,\n  {\n    rw bef at ok_input,\n    rw aft,\n    unfold good_string_ at ok_input \u22a2,\n    rw \u2190preimage,\n    clear_except ok_input,\n    rw list.forall_mem_append_append at ok_input \u22a2,\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 \u27e8s, trash, a_from_s\u27e9,\n    rw \u2190a_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\u2080,\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 \u2218 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 \u2190preimage;\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\u2080.input_N] =\n        list.filter_map (sink_symbol_ lg.sink_nt)\n          (list.map (lift_symbol_ lg.lift_nt) [symbol.nonterminal r\u2080.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 \u2190preimage,\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\u2081 w\u2082 : list (symbol T lg.g.nt)}\n    (hyp : grammar_derives lg.g w\u2081 w\u2082)\n    (ok_input : good_string_ w\u2081) :\n  grammar_derives lg.g\u2080 (sink_string_ lg.sink_nt w\u2081) (sink_string_ lg.sink_nt w\u2082)\n  \u2227 good_string_ w\u2082 :=\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\u2081 w\u2082 : list (symbol T lg.g.nt)}\n    (hyp : grammar_derives lg.g w\u2081 w\u2082)\n    (ok_input : good_string_ w\u2081) :\n  grammar_derives lg.g\u2080 (sink_string_ lg.sink_nt w\u2081) (sink_string_ lg.sink_nt w\u2082) :=\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 Std\n\nopen Lean (Name FVarId getConstInfo MessageData MonadEnv)\nopen Lean.Meta\nopen Std.Tactic.Lint\n\nnamespace NamingConvention\n  open Lean\n\n  /-- If a name is part of the whitelist, then it won't be flagged as wrong even if it conflicts with\n      the convention.\n\n      Mostly used for automatically generated definitions that don't fit Mathlibs naming convention\n\n-/\n  def whitelist : List String := [\n    \"noConfusion\",\n    \"noConfusionType\",\n    \"injEq\",\n    \"casesOn\",\n    \"brecOn\",\n    \"recOn\"\n  ]\n\n\n  /-- Checks that `name` is in snake_case -/\n  def snakeCaseTest (name : String) (reason : String) : MetaM (Option MessageData) := do\n    let chars := name.toList\n    let parts := (chars.splitOn '_').filter (fun x => !x.isEmpty)\n\n    if parts.length == 1 then\n      -- There are no `_`, so there should not be any upper case characters\n      if chars.any Char.isUpper then\n        return m!\"`{name}` should be in snake_case ({reason})\"\n      else\n        return none\n    else\n      let errors := List.reduceOption <| parts.map fun p =>\n        if (p.get! 0).isUpper then\n          some p\n        else\n          none\n\n      if errors.isEmpty then\n        return none\n      else\n        let errors := String.join <| errors.map fun error =>\n          \"\\n * \" ++ String.mk error ++ \" should be in lowerCamelCase\"\n        return m!\n          \"When something named with UpperCamelCase is part of something named with snake_case,\"\n           ++ m!\"it is referenced in lowerCamelCase ({reason}){errors}\\n\"\n\n\n  /-- Checks whether the passed list contains a non-trailing underscore (`_`)\n      An underscore is considered trailing if it is followed by only characters in [_,] until the end of the string\n   -/\n  def isSnakeCase : List Char \u2192 Bool\n    | [] => false\n    | '_' :: as => as.any (fun \n                            | '_' | ',' => false\n                            | _ => true\n        )\n    | _   :: as => isSnakeCase as\n\n  /-- Checks that `name` is in lowerCamelCase, i.e., the first character is lowercase, and there\n      are no `_` characters\n   -/\n  def lowerCamelCaseTest (name : String) (reason : String) : MetaM (Option MessageData) := do\n    let chars := name.toList\n\n    if (chars.get! 0).isUpper || isSnakeCase chars then\n      return m!\"`{name}` should be in lowerCamelCase ({reason})\"\n    else\n      return none\n\n\n  /-- Checks that `name` is in UpperCamelCase, i.e., the first character is Uppercase, and there\n      are no `_` characters\n    -/\n  def upperCamelCaseTest (name : String) (reason : String) : MetaM (Option MessageData) := do\n    let chars := name.toList\n\n    if (chars.get! 0).isLower || isSnakeCase chars then\n      return m!\"`{name}` should be in UpperCamelCase ({reason})\"\n    else\n      return none\n\n  /--\n    Checks that a `def` or `theorem` conforms to the naming convention\n\n    https://github.com/leanprover-community/mathlib4/wiki/Porting-wiki#naming-convention\n  -/\n  def definitionTest (name : Name) (value : Expr) : MetaM (Option MessageData) := do\n    if name.isInternal then\n      return none\n\n    -- Extract only the last element of the name\n    let name \u2190 match name with\n      | .str _ name => pure name\n      | _ => return none\n\n    if whitelist.contains name then\n      return none\n\n    -- If a name starts with `inst` we assume it is a typeclass instance and don't flag it when misnamed\n    -- TODO: proper detection when a definition is actually an instance, rather than relying on this heuristic\n    if name.toList.take 4 == \"inst\".toList then\n      return none\n\n    let type \u2190 try\n      inferType value\n    catch _ =>\n      return none\n    let type \u2190 whnf type\n\n    -- Functions are named the same way as their return values\n    -- (e.g. a function of type A \u2192 B \u2192 C is named as though it is a term of type C\n    forallTelescopeReducing type fun _ type => do\n      if type.isSort then\n        upperCamelCaseTest name \"Props and Types (or Sort) (inductive types, structures, classes) are in UpperCamelCase\"\n      else\n        let typeOfType \u2190 inferType type\n\n        if typeOfType.isProp then\n          snakeCaseTest name \"Terms of Props (e.g. proofs, theorem names) are in snake_case\"\n        else if typeOfType.isType then\n          lowerCamelCaseTest name \"Terms of Types (most definitions) are in lowerCamelCase\"\n        else\n          pure none\n\nend NamingConvention\n\nopen NamingConvention\n\n/--\n  Check whether the definition of the given name is consistent with the mathlib4 naming convention\n-/\ndef namingConventionTest (name : Name) : MetaM (Option MessageData) := do\n  let decl \u2190 match (\u2190 MonadEnv.getEnv).find? name with\n    | some decl => pure decl\n    | none => return none\n\n  match decl with\n    | .defnInfo val => definitionTest name val.value\n    | .thmInfo val  => definitionTest name val.value\n    | _ => pure none\n\n\n@[std_linter]\ndef namingConvention : Linter where\n  test := namingConventionTest\n  noErrorsFound := \"No naming convention violations found\"\n  errorsFound := \"Some definitions seem to be inconsistent with the naming convention\"\n", "meta": {"author": "alexkeizer", "repo": "lean-naming-lint", "sha": "6906589521ab21a2ab3a147a1b3c626007738d74", "save_path": "github-repos/lean/alexkeizer-lean-naming-lint", "path": "github-repos/lean/alexkeizer-lean-naming-lint/lean-naming-lint-6906589521ab21a2ab3a147a1b3c626007738d74/NamingLint.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.06754669817865512, "lm_q1q2_score": 0.018166105017017566}}
{"text": "import tidy.lib.list\nimport tidy.lib.env\nimport tidy.lib.tactic\nimport tidy.lib.pretty_print\n\nopen tactic tactic.interactive\nopen interactive\n\nnamespace tidy.rewrite_search.discovery\n\n-- TODO make sure this didn't break anything\nmeta def is_acceptable_rewrite (t : expr) : bool :=\n  is_eq_or_iff_after_binders t\n\nmeta def is_acceptable_lemma (r : expr) : tactic bool :=\n  is_acceptable_rewrite <$> infer_type r\n\nmeta def is_acceptable_hyp (r : expr) : tactic bool :=\n  do t \u2190 infer_type r, return $ is_acceptable_rewrite t \u2227 \u00act.has_meta_var\n\nmeta def assert_acceptable_lemma (r : expr) : tactic unit := do\n  ret \u2190 is_acceptable_lemma r,\n  if ret then return ()\n  else do\n    pp \u2190 pretty_print r,\n    fail format!\"\\\"{pp}\\\" is not a valid rewrite lemma!\"\n\nmeta def load_attr_list : list name \u2192 tactic (list name)\n| [] := return []\n| (a :: rest) := do\n  names \u2190 attribute.get_instances a,\n  l \u2190 load_attr_list rest,\n  return $ names ++ l\n\nmeta def load_names (l : list name) : tactic (list expr) :=\n  l.mmap mk_const\n\nmeta def rewrite_list_from_rw_rules (rws : list rw_rule) : tactic (list (expr \u00d7 bool)) :=\n  rws.mmap (\u03bb r, do e \u2190 to_expr' r.rule, pure (e, r.symm))\n\nmeta def rewrite_list_from_lemmas (l : list expr) : list (expr \u00d7 bool) :=\n  l.map (\u03bb e, (e, ff)) ++ l.map (\u03bb e, (e, tt))\n\nmeta def rewrite_list_from_lemma (e : expr) : list (expr \u00d7 bool) :=\n  rewrite_list_from_lemmas [e]\n\nmeta def rewrite_list_from_hyps : tactic (list (expr \u00d7 bool)) := do\n  hyps \u2190 local_context,\n  rewrite_list_from_lemmas <$> hyps.mfilter is_acceptable_hyp\n\n-- TODO mk_apps recursively\nmeta def inflate_under_apps (locals : list expr) : expr \u2192 tactic (list expr)\n| e := do\n  rws \u2190 list.map prod.fst <$> mk_apps e locals,\n  rws_extras \u2190 list.join <$> rws.mmap inflate_under_apps,\n  return $ e :: (rws ++ rws_extras)\n\nmeta def inflate_rw (locals : list expr) : expr \u00d7 bool \u2192 tactic (list (expr \u00d7 bool))\n| (e, sy) := do\n  as \u2190 inflate_under_apps locals e,\n  return $ as.map $ \u03bb a, (a, sy)\n\nmeta def is_rewrite_lemma (d : declaration) : option (name \u00d7 expr) :=\n  let t := d.type in if is_acceptable_rewrite t then some (d.to_name, t) else none\n\nmeta def find_all_rewrites : tactic (list (name \u00d7 expr)) := do\n  e \u2190 get_env,\n  return $ e.decl_omap is_rewrite_lemma\n\nend tidy.rewrite_search.discovery", "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/tidy/rewrite_search/discovery/screening.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.03963884080272446, "lm_q1q2_score": 0.018120368957081263}}
{"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 : \u2115 \u2192 telescope\n| preserve : telescope\n\n/-- Apply a telescope to a context. -/\ndef telescope.apply : telescope \u2192 context \u2192 context\n| (telescope.extend n) \u0393 := context.extend n \u0393\n| telescope.preserve \u0393 := \u0393\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 \u03c0) = augment \u03c0', while preserving type safety.\n-/\n@[derive decidable_eq, nolint has_inhabited_instance]\ninductive prefix_expr (\u210d : Type) : context \u2192 telescope \u2192 Type\n| communicate {} {\u0393} (a :  name \u0393) (b : list (name \u0393)) (y : \u2115) : prefix_expr \u0393 (telescope.extend y)\n| spontaneous {} {\u0393} (k : \u210d) : prefix_expr \u0393 telescope.preserve\n\nvariables {\u210d : 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 `#\u27e8` b `\u27e9` := prefix_expr.communicate a b 0\nnotation a `#` := prefix_expr.communicate a [] 0\n\nnotation `\u03c4@`: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 \u210d] {\u0393} : \u2200 {f}, prefix_expr \u210d \u0393 f \u2192 string\n  | ._ (a #( []; 0)) := repr a ++ \"#\"\n  | ._ (a #( b; 0)) := repr a ++ \"#<  \" ++ repr b ++ \"\u27e9\"\n  | ._ (a #( []; y)) := repr a ++ \"#(\" ++ repr y ++ \")\"\n  | ._ (a #( b; y)) := repr a ++ \"#(\" ++ repr b ++ \";\" ++ repr y ++ \")\"\n  | ._ (\u03c4@ k) := \"\u03c4@\" ++ repr k\n\n  instance [has_repr \u210d] {\u0393 f} : has_repr (prefix_expr \u210d \u0393 f) := \u27e8 prefix_expr.to_string \u27e9\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 (\u210d : Type) : context \u2192 Type\n  | intro {} {\u0393} {f} (\u03c0 : prefix_expr \u210d \u0393 f) : wrap \u0393\n\n  section free\n    /-- Determine if any variable with a given level occurs within this prefix.\n    -/\n    def free_in : \u2200 {\u0393} {f}, level \u0393 \u2192 prefix_expr \u210d \u0393 f \u2192 Prop\n    | ._ ._ l (a#(b; y)) := l \u2208 a \u2228 \u2203 x \u2208 b, l \u2208 x\n    | ._ ._ l \u03c4@_ := false\n\n    instance {\u0393} {f} : has_mem (level \u0393) (prefix_expr \u210d \u0393 f) := \u27e8 free_in \u27e9\n\n    private def free_in_decide : \u2200 {\u0393} {f}\n      (l : level \u0393) (\u03c0 : prefix_expr \u210d \u0393 f), decidable (free_in l \u03c0)\n    | \u0393 ._ l (a#(b; y)) := if h : l \u2208 a \u2228 \u2203 x \u2208 b, l \u2208 x then is_true h else is_false h\n    | ._ ._ l \u03c4@_ := decidable.false\n\n    instance free_in.decidable {\u0393} {f} {l} {\u03c0 : prefix_expr \u210d \u0393 f}\n      : decidable (free_in l \u03c0)\n      := free_in_decide l \u03c0\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      \u2200 {\u0393 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u03b7 f)\n      , level \u0393 \u2192 level (f.apply \u0393)\n    | \u0393 ._ ._ (a#(b; y)) l := level.extend l\n    | \u0393 ._ ._ \u03c4@_ 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 {\u0393 \u0394} :\n      \u03a0 {f} (\u03c0 : prefix_expr \u210d \u0393 f)\n      , (\u03a0 (a : name \u0393), name.to_level a \u2208 \u03c0 \u2192 name \u0394) \u2192 prefix_expr \u210d \u0394 f\n    | f (a#(b; y)) \u03c1 :=\n      let a' := \u03c1 a (or.inl (name.to_level_at a)) in\n      let b' := list.map_witness b\n        (\u03bb x mem, \u03c1 x (or.inr \u27e8 x, mem, name.to_level_at x \u27e9))\n      in\n      a'#( b' ; y)\n    | f \u03c4@k \u03c1 := \u03c4@k\n\n    /-- Simple renaming function, not taking any witness. -/\n    @[reducible]\n    def rename {\u0393 \u0394} {f} (\u03c1 : name \u0393 \u2192 name \u0394) (\u03c0 : prefix_expr \u210d \u0393 f)\n      : prefix_expr \u210d \u0394 f\n      := rename_with \u03c0 (\u03bb a _, \u03c1 a)\n\n    /-- Renaming with the identity function does nothing. -/\n    lemma rename_with_id {\u0393} : \u2200 {f} (\u03c0 : prefix_expr \u210d \u0393 f)\n      , rename_with \u03c0 (\u03bb a _, a) = \u03c0\n    | ._ (a#(b; y)) := by simp [rename_with]\n    | ._ \u03c4@k := rfl\n\n    /-- Renaming with the identity function is the identity. -/\n    lemma rename_id {\u0393} {f} (\u03c0 : prefix_expr \u210d \u0393 f) : rename id \u03c0 = \u03c0\n      := rename_with_id \u03c0\n\n    /-- Renaming twice is the same as renaming with a composed function. -/\n    lemma rename_with_compose {\u0393 \u0394 \u03b7} :\n      \u2200 {f} (\u03c0 : prefix_expr \u210d \u0393 f)\n        (\u03c1 : \u03a0 (a : name \u0393), name.to_level a \u2208 \u03c0 \u2192 name \u0394)\n        (\u03c3 : name \u0394 \u2192 name \u03b7)\n      , rename \u03c3 (rename_with \u03c0 \u03c1) = rename_with \u03c0 (\u03bb a free, \u03c3 (\u03c1 a free))\n    | f (a#(b; y)) \u03c1 \u03c3 := by simp [rename_with, rename, list.map_witness_to_map]\n    | f (\u03c4@_) \u03c1 \u03c3 := rfl\n\n    /-- Renaming twice is the same as renaming with a composed function. -/\n    lemma rename_compose {\u0393 \u0394 \u03b7} {f}\n        (\u03c0 : prefix_expr \u210d \u0393 f) (\u03c1 : name \u0393 \u2192 name \u0394) (\u03c3 : name \u0394 \u2192 name \u03b7)\n      : rename \u03c3 (rename \u03c1 \u03c0) = rename (\u03c3 \u2218 \u03c1) \u03c0\n    := rename_with_compose \u03c0 _ _\n\n    /-- Wrap a renaming function, making it suitable for a nested context. -/\n    def ext_with {\u0393 \u0394 \u03b7} :\n      \u2200 {f} (\u03c0 : prefix_expr \u210d \u03b7 f)\n        (P : level (f.apply \u0393) \u2192 Prop)\n        (\u03c1 : \u03a0 (x : name \u0393), P (prefix_expr.raise \u03c0 (name.to_level x)) \u2192 name \u0394)\n      , \u03a0 (x : name (f.apply \u0393)), P (name.to_level x) \u2192 name (f.apply \u0394)\n    | f (_#(_; y)) P \u03c1 a p := name.ext_with P \u03c1 a p\n    | f \u03c4@_ P \u03c1 a p := \u03c1 a p\n\n    /-- Extending with the identity does nothing. -/\n    lemma ext_with_identity :\n      \u2200 {\u0393 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u03b7 f)\n        (P : level (f.apply \u0393) \u2192 Prop)\n        (a : name (f.apply \u0393)) (p : P (name.to_level a))\n      , ext_with \u03c0 P (\u03bb x _, x) a p = a\n    | \u0393 \u03b7 ._ (_#(_; _)) P a p := name.ext_with_identity P a p\n    | \u0393 \u03b7 ._ \u03c4@k P a p := rfl\n\n    /-- Extending with the identity does nothing. -/\n    lemma ext_with_id {\u0393 \u03b7} {f}\n        (\u03c0 : prefix_expr \u210d \u03b7 f) (P : level (f.apply \u0393) \u2192 Prop)\n      : ext_with \u03c0 P (\u03bb x _, x) = \u03bb x _, x\n      := funext $ \u03bb a, funext (ext_with_identity \u03c0 P a)\n\n    /-- Wrap a simple renaming function, making it suitable for a nested context. -/\n    def ext {\u0393 \u0394 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u03b7 f) (\u03c1 : name \u0393 \u2192 name \u0394)\n          : name (f.apply \u0393) \u2192 name (f.apply \u0394)\n    | a := ext_with \u03c0 (\u03bb _, true) (\u03bb x _, \u03c1 x) a true.intro\n\n    /-- Extending with the identity does nothing. -/\n    lemma ext_identity {\u0393 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u03b7 f) (a : name (f.apply \u0393))\n      : ext \u03c0 id a = a := ext_with_identity \u03c0 _ a _\n\n    /-- Extending with the identity yields the identity function. -/\n    lemma ext_id : \u2200 {\u0393 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u03b7 f), @ext \u210d \u0393 \u0393 \u03b7 f \u03c0 id = id\n    | \u0393 \u03b7 f \u03c0 := funext (ext_identity \u03c0)\n\n    /-- Composing extensions is equivalent extending a composition. -/\n    lemma ext_with_compose :\n      \u2200 {\u0393 \u0394 \u03b7 \u03c6} {f} (\u03c0 : prefix_expr \u210d \u03c6 f)\n        (P : level (f.apply \u0393) \u2192 Prop)\n        (\u03c1 : \u03a0 (x : name \u0393), P (raise \u03c0 (name.to_level x)) \u2192 name \u0394)\n        (\u03c3 : name \u0394 \u2192 name \u03b7)\n        (a : name (f.apply \u0393)) (p : P (name.to_level a))\n      , ext \u03c0 \u03c3 (ext_with \u03c0 P \u03c1 a p) = ext_with \u03c0 P (\u03bb a p, \u03c3 (\u03c1 a p)) a p\n    | \u0393 \u0394 \u03b7 \u03c6 f (_#(_;_)) P \u03c1 \u03c3 a p := name.ext_with_compose P \u03c1 \u03c3 a p\n    | \u0393 \u0394 \u03b7 \u03c6 f \u03c4@_ P \u03c1 \u03c3 _ _ := rfl\n\n    /-- Composing extensions is equivalent extending a composition. -/\n    lemma ext_with_comp {\u0393 \u0394 \u03b7 \u03c6} {f} (\u03c0 : prefix_expr \u210d \u03c6 f)\n        (P : level (f.apply \u0393) \u2192 Prop)\n        (\u03c1 : \u03a0 (x : name \u0393), P (raise \u03c0 (name.to_level x)) \u2192 name \u0394)\n        (\u03c3 : name \u0394 \u2192 name \u03b7)\n      : (\u03bb a p, ext \u03c0 \u03c3 (ext_with \u03c0 P \u03c1 a p)) = ext_with \u03c0 P (\u03bb a p, \u03c3 (\u03c1 a p))\n      := funext $ \u03bb a, funext (ext_with_compose \u03c0 P \u03c1 \u03c3 a)\n\n    /-- Composing extensions is equivalent extending a composition. -/\n    lemma ext_compose :\n      \u2200 {\u0393 \u0394 \u03b7 \u03c6} {f} (\u03c1 : name \u0393 \u2192 name \u0394) (\u03c3 : name \u0394 \u2192 name \u03b7)\n        (\u03c0 : prefix_expr \u210d \u03c6 f) (\u03b1 : name (f.apply \u0393))\n      , ext \u03c0 \u03c3 (ext \u03c0 \u03c1 \u03b1) = ext \u03c0 (\u03c3 \u2218 \u03c1) \u03b1\n    | \u0393 \u0394 \u03b7 \u03c6 f \u03c1 \u03c3 (a#(b; y)) \u03b1 := name.ext_compose \u03c1 \u03c3 \u03b1\n    | \u0393 \u0394 \u03b7 \u03c6 f \u03c1 \u03c3 \u03c4@k \u03b1 := rfl\n\n    /-- Composing extensions is equivalent extending a composition. -/\n    lemma ext_comp :\n      \u2200 {\u0393 \u0394 \u03b7 \u03c6} {f} (\u03c1 : name \u0393 \u2192 name \u0394) (\u03c3 : name \u0394 \u2192 name \u03b7)\n        (\u03c0 : prefix_expr \u210d \u03c6 f)\n      , (ext \u03c0 \u03c3 \u2218 ext \u03c0 \u03c1) = ext \u03c0 (\u03c3 \u2218 \u03c1)\n    | \u0393 \u0394 \u03b7 \u03c6 f \u03c1 \u03c3 \u03c0 := funext (ext_compose \u03c1 \u03c3 \u03c0)\n\n    /-- Rewrite one ext_with to another -/\n    lemma ext_with_discard :\n      \u2200 {\u0393 \u0394 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u03b7 f)\n        (P : level (f.apply \u0393) \u2192 Prop)\n        (\u03c1 : name \u0393 \u2192 name \u0394)\n      , (ext_with \u03c0 P (\u03bb a _, \u03c1 a))\n      = (\u03bb a _, ext_with \u03c0 (\u03bb _x, true) (\u03bb x _, \u03c1 x) a true.intro)\n    | \u0393 \u0394 \u03b7 f (a'#(b; y)) P \u03c1 := funext $ \u03bb a, funext $ \u03bb free, begin\n        have : (\u03bb (a : name \u0393) (_x : P (@raise \u210d _ _ _ (a'#(b ; y)) (name.to_level a))), \u03c1 a)\n             = (\u03bb (a : name \u0393) (_x : P (level.extend (name.to_level a))), \u03c1 a)\n             := rfl,\n        unfold ext_with,\n        rw [this, name.ext_with_discard P],\n        from rfl,\n      end\n    | \u0393 \u0394 \u03b7 f \u03c4@_ P \u03c1 := funext $ \u03bb a, funext $ \u03bb free, rfl\n\n    /-- Raising with a renamed prefix has the same effect as the original one. -/\n    lemma rename_with_raise\n        {\u0393 \u0394 \u03b7} {f} (\u03c0 : prefix_expr \u210d \u0393 f)\n        (\u03c1 : \u03a0 (x : name \u0393), name.to_level x \u2208 \u03c0 \u2192 name \u0394)\n        (l : level \u03b7)\n      : raise \u03c0 l = raise (rename_with \u03c0 \u03c1) l\n      := by { cases \u03c0; from rfl }\n\n    /-- Extending with a renamed prefix has the same effect as the original one. -/\n    lemma rename_with_ext_with\n        {\u0393 \u0394 \u03b7 \u03c6} {f} (\u03c0 : prefix_expr \u210d \u03b7 f)\n        (P : level (f.apply \u0393) \u2192 Prop)\n        (\u03c1 : name \u0393 \u2192 name \u0394)\n        (\u03c3 : \u03a0 (x : name \u03b7), name.to_level x \u2208 \u03c0 \u2192 name \u03c6)\n      : ext_with (rename_with \u03c0 \u03c3) P (\u03bb a _, \u03c1 a) = ext_with \u03c0 P (\u03bb a _, \u03c1 a)\n      := funext $ \u03bb a, funext $ \u03bb free, by { cases \u03c0; from rfl }\n\n    /-- Extending with a renamed prefix has the same effect as the original one. -/\n    lemma rename_ext\n        {\u0393 \u0394 \u03b7 \u03c6} {f} (\u03c1 : name \u0393 \u2192 name \u0394) (\u03c3 : name \u03b7 \u2192 name \u03c6)\n        (\u03c0 : prefix_expr \u210d \u0393 f)\n      : @ext \u210d \u03b7 \u03c6 \u0393 f \u03c0 \u03c3 = (ext (rename \u03c1 \u03c0) \u03c3)\n      := funext $ \u03bb a, by { cases \u03c0; from rfl }\n  end rename\n\n  section rename_equations\n    variables {\u0393 \u0394 : context} {\u03c1 : name \u0393 \u2192 name \u0394}\n\n    @[simp]\n    lemma rename_communicate (a :  name \u0393) (b : list (name \u0393)) (y : \u2115)\n      : rename \u03c1 (a#(b; y) : prefix_expr \u210d _ _) = ((\u03c1 a)#(list.map \u03c1 b; y))\n      := by simp [rename, rename_with, list.map_witness_to_map]\n\n    @[simp]\n    lemma rename_spontaneous (k : \u210d)\n      : rename \u03c1 \u03c4@k = \u03c4@k\n      := by simp only [rename, rename_with]\n\n    @[simp]\n    lemma ext_communicate {\u03b7} (a :  name \u03b7) (b : list (name \u03b7)) (y : \u2115)\n      : ext (a#(b; y) : prefix_expr \u210d _ _) \u03c1 = name.ext \u03c1\n      := funext $ \u03bb x, by { unfold ext ext_with, from rfl }\n\n    @[simp]\n    lemma ext_spontaneous {\u03b7} (k : \u210d)\n      : ext (@spontaneous \u210d \u03b7 k) \u03c1 = \u03c1\n      := funext $ \u03bb x, by unfold ext ext_with\n\n    private lemma rename_inj {\u0393 \u0394} {\u03c1 : name \u0393 \u2192 name \u0394} (inj : function.injective \u03c1)\n      : \u2200 {f\u2081 f\u2082} {\u03c0\u2081 : prefix_expr \u210d \u0393 f\u2081} {\u03c0\u2082 : prefix_expr \u210d \u0393 f\u2082}\n      , wrap.intro (rename \u03c1 \u03c0\u2081) = wrap.intro (rename \u03c1 \u03c0\u2082)\n      \u2192 \u03c0\u2081 == \u03c0\u2082\n    | _ _ (a#(b; y)) (a'#(b'; y')) eq := begin\n        simp only [rename_communicate] at eq,\n        rcases eq with \u27e8 \u27e8 _ \u27e9, eq\u03c0 \u27e9,\n        simp only [heq_iff_eq] at eq\u03c0 \u22a2,\n        from \u27e8 inj eq\u03c0.left, list.injective_map_iff.mpr inj eq\u03c0.right \u27e9,\n      end\n    | _ _ (a#(b; y)) \u03c4@k eq := begin\n      simp only [rename_communicate, rename_spontaneous] at eq,\n      exfalso, from eq.1,\n    end\n    | _ _ \u03c4@k (a#(b; y)) eq := begin\n        simp only [rename_communicate, rename_spontaneous] at eq,\n        exfalso, from eq.1,\n      end\n    | _ _ \u03c4@k \u03c4@k' eq := begin\n        simp only [rename_spontaneous] at eq,\n        rcases eq with \u27e8 eqC, eq\u03c0 \u27e9,\n        cases eq\u03c0, from heq.refl _,\n      end\n\n    lemma rename.inj {\u0393 \u0394} {\u03c1 : name \u0393 \u2192 name \u0394} (inj : function.injective \u03c1)\n      : \u2200 {f}, function.injective (@rename \u210d \u0393 \u0394 f \u03c1)\n    | f \u03c0\u2081 \u03c0\u2082 eq := eq_of_heq (rename_inj inj (congr_arg wrap.intro eq))\n\n    lemma ext.inj {\u0393 \u0394 \u03b7} {\u03c1 : name \u0393 \u2192 name \u0394}\n      : \u2200 {f} (\u03c0 : prefix_expr \u210d \u03b7 f), function.injective \u03c1 \u2192 function.injective (ext \u03c0 \u03c1)\n    | ._ (_#(_; y)) inj a b eq := begin\n        simp only [ext_communicate] at eq,\n        from name.ext.inj inj eq,\n      end\n    | ._ (\u03c4@_) 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 \u2192 tactic smt_state\nmeta constant smt_state.to_format       : smt_state \u2192 tactic_state \u2192 format\n/-- Return tt iff classical excluded middle was enabled at  smt_state.mk -/\nmeta constant smt_state.classical       : smt_state \u2192 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 (\u03b1 : Type) : tactic \u03b1 \u2192 smt_tactic \u03b1\n\nmeta instance : has_monad_lift tactic smt_tactic :=\n\u27e8tactic_to_smt_tactic\u27e9\n\nmeta instance (\u03b1 : Type) : has_coe (tactic \u03b1) (smt_tactic \u03b1) :=\n\u27e8monad_lift\u27e9\n\nmeta instance : monad_fail smt_tactic :=\n{ fail := \u03bb \u03b1 s, (tactic.fail (to_fmt s) : smt_tactic \u03b1), ..smt_tactic.monad }\n\nnamespace smt_tactic\nopen tactic (transparency)\nmeta constant intros                     : smt_tactic unit\nmeta constant intron                     : nat  \u2192 smt_tactic unit\nmeta constant intro_lst                  : list name \u2192 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 \u2192 bool) \u2192 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 \u2192 smt_tactic unit\nmeta constant mk_ematch_eqn_lemmas_for_core   : transparency \u2192 name \u2192 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 \u2192 smt_tactic (expr \u00d7 expr)\nmeta constant get_lemmas                      : smt_tactic hinst_lemmas\nmeta constant set_lemmas                      : hinst_lemmas \u2192 smt_tactic unit\nmeta constant add_lemmas                      : hinst_lemmas \u2192 smt_tactic unit\n\nmeta def add_ematch_lemma_core (md : transparency) (as_simp : bool) (e : expr) : smt_tactic unit :=\ndo h  \u2190 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  \u2190 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 \u2190 mk_ematch_eqn_lemmas_for_core md n,\n   add_lemmas hs\n\nmeta def ematch : smt_tactic unit :=\nematch_core (\u03bb _, tt)\n\nmeta def failed {\u03b1} : smt_tactic \u03b1 :=\ntactic.failed\n\nmeta def fail {\u03b1 : Type} {\u03b2 : Type u} [has_to_format \u03b2] (msg : \u03b2) : smt_tactic \u03b1 :=\ntactic.fail msg\n\nmeta def try {\u03b1 : Type} (t : smt_tactic \u03b1) : smt_tactic unit :=\n\u27e8\u03bb ss ts, result.cases_on (t.run ss ts)\n (\u03bb \u27e8a, new_ss\u27e9, result.success ((), new_ss))\n (\u03bb e ref s', result.success ((), ss) ts)\u27e9\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 \u2192 smt_tactic unit \u2192 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 \u2192 smt_tactic unit \u2192 smt_tactic unit\n| 0     t := return ()\n| (n+1) t := do t, iterate_exactly n t\n\nmeta def iterate : smt_tactic unit \u2192 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 \u00d7 tactic_state) :=\ndo s\u2081 \u2190 get,\n   s\u2082 \u2190 tactic.read,\n   return (s\u2081, s\u2082)\n\nprotected meta def write : smt_state \u00d7 tactic_state \u2192 smt_tactic unit :=\n\u03bb \u27e8ss, ts\u27e9, \u27e8\u03bb _ _, result.success ((), ss) ts\u27e9\n\nprivate meta def mk_smt_goals_for (cfg : smt_config) : list expr \u2192 list smt_goal \u2192 list expr\n                                  \u2192 tactic (list smt_goal \u00d7 list expr)\n| []        sr tr := return (sr.reverse, tr.reverse)\n| (tg::tgs) sr tr := do\n  tactic.set_goals [tg],\n  [new_sg] \u2190 smt_state.mk cfg | tactic.failed,\n  [new_tg] \u2190 get_goals | tactic.failed,\n  mk_smt_goals_for tgs (new_sg::sr) (new_tg::tr)\n\n/- See slift -/\nmeta def slift_aux {\u03b1 : Type} (t : tactic \u03b1) (cfg : smt_config) : smt_tactic \u03b1 :=\n\u27e8\u03bb ss, do\n   _::sgs  \u2190 return ss | tactic.fail \"slift tactic failed, there no smt goals to be solved\",\n   tg::tgs \u2190 tactic.get_goals | tactic.failed,\n   tactic.set_goals [tg], a \u2190 t,\n   new_tgs \u2190 tactic.get_goals,\n   (new_sgs, new_tgs) \u2190 mk_smt_goals_for cfg new_tgs [] [],\n   tactic.set_goals (new_tgs ++ tgs),\n   return (a, new_sgs ++ sgs)\u27e9\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 {\u03b1 : Type} (t : tactic \u03b1) : smt_tactic \u03b1 :=\nget_config >>= slift_aux t\n\nmeta def trace_state : smt_tactic unit :=\ndo (s\u2081, s\u2082) \u2190 smt_tactic.read,\n   trace (smt_state.to_format s\u2081 s\u2082)\n\nmeta def trace {\u03b1 : Type} [has_to_tactic_format \u03b1] (a : \u03b1) : 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 \u2190 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 \u00d7 list expr) :=\ndo (g\u2081, _) \u2190 smt_tactic.read,\n   g\u2082 \u2190 tactic.get_goals,\n   return (g\u2081, g\u2082)\n\nmeta def set_goals : list smt_goal \u2192 list expr \u2192 smt_tactic unit :=\n\u03bb g\u2081 g\u2082, \u27e8\u03bb ss, tactic.set_goals g\u2082 >> return ((), g\u2081)\u27e9\n\nprivate meta def all_goals_core (tac : smt_tactic unit) : list smt_goal \u2192 list expr \u2192 list smt_goal \u2192 list expr \u2192 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) \u2190 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) \u2190 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) \u2190 get_goals,\n   set_goals [s] [t],\n   tac1, all_goals tac2,\n   (new_ss, new_ts) \u2190 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\u27e8seq\u27e9\n\nmeta def focus1 {\u03b1} (tac : smt_tactic \u03b1) : smt_tactic \u03b1 :=\ndo (s::ss, t::ts) \u2190 get_goals,\n   match ss with\n   | []  := tac\n   | _   := do\n     set_goals [s] [t],\n     a \u2190 tac,\n     (ss', ts') \u2190 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) \u2190 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') \u2190 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) \u2190 get_goals,\n   match ss, ts with\n   | (s\u2081 :: s\u2082 :: ss), (t\u2081 :: t\u2082 :: ts) := set_goals (s\u2082 :: s\u2081 :: ss) (t\u2082 :: t\u2081 :: 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 \u2190 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 \u2190 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 \u2190 classical,\n   if c then\n     destruct (expr.app (expr.const `classical.em []) e)\n   else do\n     dec_e \u2190 (mk_app `decidable [e] <|> fail \"by_cases smt_tactic failed, type is not a proposition\"),\n     inst  \u2190 (mk_instance dec_e <|> fail \"by_cases smt_tactic failed, type of given expression is not decidable\"),\n     em    \u2190 mk_app `decidable.em [e, inst],\n     destruct em\n\nmeta def by_contradiction : smt_tactic unit :=\ndo t \u2190 target,\n   c \u2190 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 \u2190 (mk_app `decidable [t] <|> fail \"by_contradiction smt_tactic failed, target is not a proposition\"),\n     inst  \u2190 (mk_instance dec_t <|> fail \"by_contradiction smt_tactic failed, target is not decidable\"),\n     a     \u2190 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 \u2190 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 \u2190 to_cc_state, cc.refutation_for e\n\nmeta def get_facts : smt_tactic (list expr) :=\ndo cc \u2190 to_cc_state,\n   return $ cc.eqc_of expr.mk_true\n\nmeta def get_refuted_facts : smt_tactic (list expr) :=\ndo cc \u2190 to_cc_state,\n   return $ cc.eqc_of expr.mk_false\n\nmeta def add_ematch_lemma : expr \u2192 smt_tactic unit :=\nadd_ematch_lemma_core reducible ff\n\nmeta def add_ematch_lhs_lemma : expr \u2192 smt_tactic unit :=\nadd_ematch_lemma_core reducible tt\n\nmeta def add_ematch_lemma_from_decl : name \u2192 smt_tactic unit :=\nadd_ematch_lemma_from_decl_core reducible ff\n\nmeta def add_ematch_lhs_lemma_from_decl : name \u2192 smt_tactic unit :=\nadd_ematch_lemma_from_decl_core reducible ff\n\nmeta def add_ematch_eqn_lemmas_for : name \u2192 smt_tactic unit :=\nadd_ematch_eqn_lemmas_for_core reducible\n\nmeta def add_lemmas_from_facts_core : list expr \u2192 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 {\u03b1} (t : smt_tactic \u03b1) (cfg : smt_config := {}) : tactic \u03b1 :=\ndo ss \u2190 smt_state.mk cfg,\n   (a, _) \u2190 (do a \u2190 t, iterate close, return a).run ss,\n   return a\n\nmeta def using_smt_with {\u03b1} (cfg : smt_config) (t : smt_tactic \u03b1) : tactic \u03b1 :=\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": "import Days\nimport Days.Common\nimport Std\nimport Lean.Data.Parsec\n\nnamespace Days.Day05\nopen Days\nopen Common\nopen Std (RBMap)\n\nopen Lean.Parsec\nopen Lean (Parsec)\n\n/--\nThe expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.\n\nThe ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.\n\nThe Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.\n\nThey do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example:\n\n    [D]    \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \n\nmove 1 from 2 to 1\nmove 3 from 1 to 3\nmove 2 from 2 to 1\nmove 1 from 1 to 2\nIn this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P.\n\nThen, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:\n\n[D]        \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \nIn the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates:\n\n        [Z]\n        [N]\n    [C] [D]\n    [M] [P]\n 1   2   3\nThen, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M:\n\n        [Z]\n        [N]\n[M]     [D]\n[C]     [P]\n 1   2   3\nFinally, one crate is moved from stack 1 to stack 2:\n\n        [Z]\n        [N]\n        [D]\n[C] [M] [P]\n 1   2   3\nThe Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ.\n\nAfter the rearrangement procedure completes, what crate ends up on top of each stack?\n-/\nstructure Stacks where\n  stacks: RBMap Nat (List Char) compare\n  deriving Repr\n\ndef stackItem : Parsec $ Option Char := do\n  _ \u2190 pchar '['\n  let c \u2190 asciiLetter\n  _ \u2190 pchar ']'\n  if (\u2190 peek?) = ' '\n  then skip\n  return some c\n\n#eval stackItem \"[A]\".iter\n\ndef Stacks.parseLine: Parsec $ List $ Option Char :=\n  parse\n  where \n    noItem : Parsec $ Option Char := do\n      _ \u2190 pstring \"   \"\n      if (\u2190 peek?) = some ' '\n      then skip\n      return none\n\n    parse : Parsec $ List $ Option Char := do \n      let array \u2190 many (stackItem <|> noItem)\n      return array.toList\n\n#eval Stacks.parseLine \"        [Z]\".iter\n\ndef Stacks.parseLines (i: Input) : List $ List $ Option Char := \n  i.lines\n  |>.map (\u00b7.iter)\n  |>.map Stacks.parseLine\n  |>.filterMap (\u03bb\n  | .success _ res => some res\n  | .error _ _ => none)\n\n\n#eval Input.mk \"        [Z]\n        [N]\n        [D]\n[C] [M] [P]\n 1   2   3\" |> Stacks.parseLines\n\ndef Stacks.parse (input: Input) : Stacks :=\n  input\n  |> Stacks.parseLines\n  |>.map (\u03bb l =>\n    l.enumFrom 1\n    |>.foldl (init:=Std.mkRBMap Nat (List Char) compare) (\u03bb (state: RBMap Nat (List Char) compare) (pair: Nat \u00d7 Option Char) => \n      state.insert pair.fst (match pair.snd with \n      | some c => [c]\n      | none => [])\n    )\n  )\n  |>.foldl (init:=Stacks.mk (Std.mkRBMap Nat (List Char) compare)) (\u03bb (stacks: Stacks) (map: RBMap Nat (List Char) compare) =>\n    stacks.stacks.mergeWith (\u03bb _ l\u2081 l\u2082 => l\u2081 ++ l\u2082)  map\n    |> Stacks.mk\n  )\n\n#eval Input.mk \"        [Z]\n        [N]\n        [D]\n[C] [M] [P]\n 1   2   3\" |> Stacks.parse\n\nstructure Operation where\n  count: Nat\n  fromStack: Nat\n  toStack: Nat\n  deriving Repr, DecidableEq, Inhabited\n\ndef problemSeperator := \"\\n\\n\"\n\ndef toOp (countStr fromStackStr toStackStr: String) : Option Operation := do \n  let count \u2190 String.toNat? countStr\n  let fromStack \u2190 String.toNat? fromStackStr\n  let toStack \u2190 String.toNat? toStackStr\n  return Operation.mk count fromStack toStack\n\n-- move 1 from 2 to 1\ndef opParser := do\n  let _ \u2190 pstring \"move \"\n  let countStr \u2190 many1Chars digit\n  let _ \u2190 pstring \" from \"\n  let fromStackStr \u2190 many1Chars digit\n  let _ \u2190 pstring \" to \"\n  let toStackStr \u2190 many1Chars digit\n  return toOp countStr fromStackStr toStackStr \n\n#eval opParser \"move 1 from 2 to 1\".iter\n\ndef Operation.parse [ToString \u03b1] (i: \u03b1) : Option Operation :=\n  match opParser (ToString.toString i).iter with\n  | .success _ res => res\n  | .error _ _ => none\n\n#eval Operation.parse \"move 1 from 2 to 1\"\n\ndef Operation.parseMany (i: Input) : List Operation :=\n  i.lines \n  |>.map Operation.parse\n  |>.filterMap id\n\n#eval Operation.parseMany \u27e8 \"move 1 from 2 to 1\nmove 1 from 2 to 3\" \u27e9 = [Operation.mk 1 2 1, Operation.mk 1 2 3]\n\ndef stacker (mover: List Char -> List Char) (input: Input): Stacks :=\n  runOps\n  where\n    problemParts := input.splitOn problemSeperator\n    startingStacksText := problemParts.get! 0\n    operationsText := problemParts.get! 1\n    stacks : Stacks := Stacks.parse startingStacksText \n    ops : List Operation := Operation.parseMany operationsText\n    runOps := \n      ops.foldl (init:=stacks) (\u03bb \n      | state, Operation.mk count fromStack toStack => \n        let source: List Char := state.stacks.find? fromStack |>.get!\n        let target: List Char := state.stacks.find? toStack |>.get!\n        let newSource := source.drop count \n        let moved := source.take count |> mover\n        let newTarget: List Char := moved.foldr (init:=target) (\u03bb (el: Char) t => el::t)\n        state.stacks.insert fromStack newSource \n        |>.insert toStack newTarget\n        |> Stacks.mk\n      )\n\ndef stacker\u2089\u2080\u2080\u2080 : Input \u2192 Stacks := stacker (\u00b7.reverse)\n\n#eval \"    [D]    \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \n\nmove 1 from 2 to 1\" |> Input.mk |> stacker\u2089\u2080\u2080\u2080\n\n#eval \"    [D]    \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \n\nmove 1 from 2 to 1\nmove 3 from 1 to 3\" |> Input.mk |> stacker\u2089\u2080\u2080\u2080\n\ndef part\u2081 (input: Input) : String := \n  stacker\u2089\u2080\u2080\u2080 input\n  |>.stacks\n  |>.valuesList\n  |>.map List.head!\n  |> String.mk \n\n/--\nAs you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction.\n\nSome mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001.\n\nThe CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.\n\nAgain considering the example above, the crates begin in the same configuration:\n\n    [D]    \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \nMoving a single crate from stack 2 to stack 1 behaves the same as before:\n\n[D]        \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \nHowever, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration:\n\n        [D]\n        [N]\n    [C] [Z]\n    [M] [P]\n 1   2   3\nNext, as both crates are moved from stack 2 to stack 1, they retain their order as well:\n\n        [D]\n        [N]\n[C]     [Z]\n[M]     [P]\n 1   2   3\nFinally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved:\n\n        [D]\n        [N]\n        [Z]\n[M] [C] [P]\n 1   2   3\nIn this example, the CrateMover 9001 has put the crates in a totally different order: MCD.\n\nBefore the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack?\n-/\ndef stacker\u2089\u2080\u2080\u2081 : Input \u2192 Stacks := stacker id\n\ndef part\u2082 (input: Input) : String :=\n  stacker\u2089\u2080\u2080\u2081 input\n  |>.stacks\n  |>.valuesList\n  |>.map List.head!\n  |> String.mk \n\ndef solution : Problem String := \u27e8 5, part\u2081, part\u2082 \u27e9 \n\ndef sample := \"    [D]    \n[N] [C]    \n[Z] [M] [P]\n 1   2   3 \n\nmove 1 from 2 to 1\nmove 3 from 1 to 3\nmove 2 from 2 to 1\nmove 1 from 1 to 2\"\n\n\ndef sampleInput := Input.mk sample\n\n#eval stacker\u2089\u2080\u2080\u2080 sampleInput\n\n#eval testPart\u2081 solution sample (expect:=\"CMZ\")\n#eval testPart\u2082 solution sample (expect:=\"MCD\")\n", "meta": {"author": "jakeswenson", "repo": "advent2022", "sha": "af941092292ff0bc5552bce9c145d6b5b173c20d", "save_path": "github-repos/lean/jakeswenson-advent2022", "path": "github-repos/lean/jakeswenson-advent2022/advent2022-af941092292ff0bc5552bce9c145d6b5b173c20d/Days/Day05.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.341582499438317, "lm_q2_score": 0.05261895743325611, "lm_q1q2_score": 0.01797371499789003}}
{"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 \u2964 ((C\u1d52\u1d56) \u2964 (Type v\u2081))`,\n   along with instances that it is `full` and `faithful`.\n   \n   Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) \u2245 (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\u2081 v\u2081 u\u2082\n\nvariables (C : Type u\u2081) [\ud835\udc9e : category.{u\u2081 v\u2081} C]\ninclude \ud835\udc9e\n\ndef yoneda : C \u2964 ((C\u1d52\u1d56) \u2964 (Type v\u2081)) := \n{ obj := \u03bb X,\n  { obj := \u03bb Y : C, Y \u27f6 X,\n    map' := \u03bb Y Y' f g, f \u226b 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' := \u03bb X X' f, { app := \u03bb Y g, g \u226b f } }\n\nnamespace yoneda\n@[simp] lemma obj_obj (X Y : C) : ((yoneda C) X) Y = (Y \u27f6 X) := rfl\n@[simp] lemma obj_map (X : C) {Y Y' : C} (f : Y \u27f6 Y') : ((yoneda C) X).map f = \u03bb g, f \u226b g := rfl\n@[simp] lemma map_app {X X' : C} (f : X \u27f6 X') (Y : C) : ((yoneda C).map f) Y = \u03bb g, g \u226b f := rfl\n\nlemma obj_map_id {X Y : C\u1d52\u1d56} (f : X \u27f6 Y) : ((yoneda C) X).map f (\ud835\udfd9 X) = ((yoneda C).map f) Y (\ud835\udfd9 Y) := \nby obviously\n\n@[simp] lemma naturality {X Y : C} (\u03b1 : (yoneda C) X \u27f6 (yoneda C) Y) \n  {Z Z' : C} (f : Z \u27f6 Z') (h : Z' \u27f6 X) : f \u226b \u03b1 Z' h = \u03b1 Z (f \u226b h) :=\nbegin erw [functor_to_types.naturality], refl end\n\ninstance full : full (yoneda C) := \n{ preimage := \u03bb X Y f, (f X) (\ud835\udfd9 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) (\ud835\udfd9 X)) ; simp\nend\n\n/-- Extensionality via Yoneda. The typical usage would be\n```\n-- Goal is `X \u2245 Y`\napply yoneda.ext,\n-- Goals are now functions `(Z \u27f6 X) \u2192 (Z \u27f6 Y)`, `(Z \u27f6 Y) \u2192 (Z \u27f6 X)`, and the fact that these\nfunctions are inverses and natural in `Z`.\n```\n-/\ndef ext (X Y : C)\n  (p : \u03a0 {Z : C}, (Z \u27f6 X) \u2192 (Z \u27f6 Y)) (q : \u03a0 {Z : C}, (Z \u27f6 Y) \u2192 (Z \u27f6 X))\n  (h\u2081 : \u03a0 {Z : C} (f : Z \u27f6 X), q (p f) = f) (h\u2082 : \u03a0 {Z : C} (f : Z \u27f6 Y), p (q f) = f) \n  (n : \u03a0 {Z Z' : C} (f : Z' \u27f6 Z) (g : Z \u27f6 X), p (f \u226b g) = f \u226b p g) : X \u2245 Y := \n@preimage_iso _ _ _ _ (yoneda C) _ _ _ _ \n  (nat_iso.of_components (\u03bb 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\u1d52\u1d56) \u2964 Type v\u2081) \u00d7 (C\u1d52\u1d56)) := \ncategory_theory.prod.{(max u\u2081 (v\u2081+1)) (max u\u2081 v\u2081) u\u2081 v\u2081} (C\u1d52\u1d56 \u2964 Type v\u2081) (C\u1d52\u1d56)\n\ninstance prod_category_instance_2 : category ((C\u1d52\u1d56) \u00d7 ((C\u1d52\u1d56) \u2964 Type v\u2081)) := \ncategory_theory.prod.{u\u2081 v\u2081 (max u\u2081 (v\u2081+1)) (max u\u2081 v\u2081)} (C\u1d52\u1d56) (C\u1d52\u1d56 \u2964 Type v\u2081) \n\nend yoneda\n\nopen yoneda\n\ndef yoneda_evaluation : (((C\u1d52\u1d56) \u2964 (Type v\u2081)) \u00d7 (C\u1d52\u1d56)) \u2964 (Type (max u\u2081 v\u2081)) := \n(evaluation (C\u1d52\u1d56) (Type v\u2081)) \u22d9 ulift_functor.{v\u2081 u\u2081}\n\n@[simp] lemma yoneda_evaluation_map_down\n  (P Q : (C\u1d52\u1d56 \u2964 Type v\u2081) \u00d7  (C\u1d52\u1d56)) (\u03b1 : P \u27f6 Q) (x : (yoneda_evaluation C) P) : \n  ((yoneda_evaluation C).map \u03b1 x).down = (\u03b1.1) (Q.2) ((P.1).map (\u03b1.2) (x.down)) := rfl\n\ndef yoneda_pairing : (((C\u1d52\u1d56) \u2964 (Type v\u2081)) \u00d7 (C\u1d52\u1d56)) \u2964 (Type (max u\u2081 v\u2081)) := \nlet F := (category_theory.prod.swap ((C\u1d52\u1d56) \u2964 (Type v\u2081)) (C\u1d52\u1d56)) in\nlet G := (functor.prod ((yoneda C).op) (functor.id ((C\u1d52\u1d56) \u2964 (Type v\u2081)))) in\nlet H := (functor.hom ((C\u1d52\u1d56) \u2964 (Type v\u2081))) in\n  (F \u22d9 G \u22d9 H)      \n\n@[simp] lemma yoneda_pairing_map\n  (P Q : (C\u1d52\u1d56 \u2964 Type v\u2081) \u00d7  (C\u1d52\u1d56)) (\u03b1 : P \u27f6 Q) (\u03b2 : (yoneda_pairing C) (P.1, P.2)) : \n  (yoneda_pairing C).map \u03b1 \u03b2 = (yoneda C).map (\u03b1.snd) \u226b \u03b2 \u226b \u03b1.fst := rfl\n\ndef yoneda_lemma : (yoneda_pairing C) \u2245 (yoneda_evaluation C) := \n{ hom := \n  { app := \u03bb F x, ulift.up ((x.app F.2) (\ud835\udfd9 F.2)),\n    naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp at *, simp at *, \n      erw [\u2190functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end },\n  inv := \n  { app := \u03bb F x, \n    { app := \u03bb 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 [\u2190functor_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 [\u2190functor_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": "/-\n  Runs theorem naming evaluation.\n-/\n\nimport all\nimport backends.bfs.openai\nimport utils.util\nimport evaluation\n\nsection main\n\nmeta structure TheoremNamingEvalResult : Type :=\n(decl_nm : name) -- name of top-level theorem (i.e. ground truth)\n(decl_tp : expr) -- goal of top-level theorem\n(predictions : list (string \u00d7 native.float)) -- sorted list of predictions\n\nmeta instance : has_to_tactic_json TheoremNamingEvalResult :=\nlet fn : \u03a0 (\u03c3 : TheoremNamingEvalResult), tactic json := \u03bb \u03c3, match \u03c3 with\n| \u27e8nm, tp, preds\u27e9 := do {\n  tp_msg \u2190 json.of_string <$> format.to_string <$> format.flatten <$> tactic.pp tp,\n  let pred_msg : json := json.array $ preds.map (\u03bb \u27e8candidate_name, score\u27e9, json.array $ [candidate_name, score]),\n  pure $ json.object $ [\n      (\"name\", nm.to_string)\n    , (\"type\", tp_msg)\n    , (\"predictions\", pred_msg)\n  ]\n}\nend\nin \u27e8fn\u27e9\nopen openai\n\nmeta def autoname_core (e : expr) (req : CompletionRequest) (engine_id : string) (api_key : string) : tactic (list $ string \u00d7 native.float) := do {\n  ts_str \u2190 format.to_string <$> format.flatten <$> (tactic.with_full_names $ tactic.pp e),\n  let prompt : string := \"[LN] GOAL \" ++ ts_str ++ (format!\" {req.prompt_token} \").to_string,\n  let completion_request := {prompt := prompt, ..req},\n  response_msg \u2190 tactic.unsafe_run_io $ (openai_api engine_id api_key).query completion_request,\n  responses \u2190\n    ((list.qsort (\u03bb x y : string \u00d7 native.float, prod.snd x > prod.snd y) <$>\n      unwrap_lm_response_logprobs \"autonamer\" response_msg) -- >>= list.dedup'\n      ),\n  eval_trace format! \"[autoname_core] RESPONSES: {responses}\",\n  pure responses\n}\n\nmeta def get_theorem_naming_result\n  (decl_nm : name)\n  (decl_tp : expr)\n  (req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  : tactic TheoremNamingEvalResult := do {\n  predictions \u2190 autoname_core decl_tp req engine_id api_key,\n  pure $ {decl_nm := decl_nm, decl_tp := decl_tp, predictions := predictions}\n}\n\nmeta def theorem_naming_eval_core\n  (decls_file : string)\n  (dest : string)\n  (engine_id : string)\n  (api_key : string)\n  (req : openai.CompletionRequest)\n  : io unit := do {\n  nm_strs \u2190 (io.mk_file_handle decls_file io.mode.read >>= \u03bb f,\n  (string.split (\u03bb c, c = '\\n') <$> buffer.to_string <$> io.fs.read_to_end f)),\n\n  -- io.put_str_ln' format!\"NM STRS: {nm_strs}\",\n\n  (nms : list (name \u00d7 list name)) \u2190 (nm_strs.filter $ \u03bb nm_str, string.length nm_str > 0).mmap $ \u03bb nm_str, do {\n    ((io.run_tactic' \u2218 parse_decl_nm_and_open_ns) $ nm_str)\n  },  \n  io.put_str_ln' format!\"[theorem_naming_eval_core] GOT {nms.length} NAMES\",\n\n  let nms_unfiltered_len := nms.length,\n  nms \u2190 io.run_tactic' $ do {\n    env \u2190 tactic.get_env,\n    nms.mfilter $ \u03bb \u27e8nm, _\u27e9, (do {\n      decl \u2190 env.get nm,\n      pure decl.is_theorem\n    } <|> pure ff)\n  },\n\n  io.put_str_ln' format! \"[evaluation_harness_from_decls_file] WARNING: SKIPPING {nms_unfiltered_len - nms.length}\",\n\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n\n  let process_result : TheoremNamingEvalResult \u2192 io unit := \u03bb result, do {\n    msg \u2190 json.unparse <$> (io.run_tactic' $ has_to_tactic_json.to_tactic_json result),\n    io.fs.put_str_ln_flush dest_handle msg\n  },\n  for_ nms $ \u03bb \u27e8nm, _\u27e9, do {\n    tp \u2190 io.run_tactic' $ do {\n      env \u2190 tactic.get_env,\n      decl \u2190 env.get nm,\n      pure $ decl.type\n    },\n    result \u2190 io.run_tactic' $ get_theorem_naming_result nm tp req engine_id api_key,\n    process_result result\n  }\n}\n\n/--\n  Loops through all the names in `names_file`, queries the model given by `engine_id` for `n` completions,\n  and records the predictions\n-/\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  decls_file \u2190 args.nth_except 0 \"decls_file\",\n  dest \u2190 args.nth_except 1 \"dest\",\n  max_tokens \u2190 string.to_nat <$> args.nth_except 2 \"max_tokens\",\n  (some temperature) \u2190 (native.float.of_string <$> (args.nth_except 3 \"temperature\")) | io.fail \"failed to parse temperature\",\n  (some top_p) \u2190 (native.float.of_string <$> (args.nth_except 4 \"top_p\")) | io.fail \"failed to parse top_p\",\n  n \u2190 string.to_nat <$> args.nth_except 5 \"n\",\n  best_of \u2190 string.to_nat <$> args.nth_except 6 \"best_of\",\n  fuel \u2190 string.to_nat <$> args.nth_except 7 \"fuel\",\n  max_width \u2190 string.to_nat <$> args.nth_except 8 \"max_width\",\n  max_depth \u2190 string.to_nat <$> args.nth_except 9 \"max_depth\",\n  engine_id \u2190 args.nth_except 10 \"engine_id\",\n  api_key \u2190 args.nth_except 11 \"api_key\",\n  tac_timeout \u2190 string.to_nat <$> args.nth_except 12 \"tac_timeout in seconds\",\n  global_timeout \u2190 string.to_nat <$> args.nth_except 13 \"global_timeout in seconds\",\n\n  let req : openai.CompletionRequest := {\n    max_tokens := max_tokens,\n    temperature := temperature,\n    top_p := top_p,\n    n := n,\n    best_of := best_of,\n    prompt_token := \"PREDICTNAME\",\n    ..openai.default_partial_req\n  },\n\n  theorem_naming_eval_core decls_file dest engine_id api_key req\n  -- evaluation_harness_from_decls_file (SEARCH_CORE req engine_id api_key fuel)\n  --   decls_file dest global_timeout\n  --    $ BFSState.of_current_state 0 max_width max_depth tac_timeout\n}\nend main\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/tools/theorem_naming_eval.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.03676946831858503, "lm_q1q2_score": 0.017953920833821326}}
{"text": "import LMT\n\nvariable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]\n\nexample {a1 a2 a3 : A I E} :\n        (v3) = ((a2).read i1) \u2192 ((a2).write i1 (v3)) \u2260 (a2) \u2192 False := by\n  arr\n", "meta": {"author": "abdoo8080", "repo": "ar-project", "sha": "303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8", "save_path": "github-repos/lean/abdoo8080-ar-project", "path": "github-repos/lean/abdoo8080-ar-project/ar-project-303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8/Test/Lean/Test70.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03676946739500242, "lm_q1q2_score": 0.01795392038285127}}
{"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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_assert_nn_le \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_0 : mem_at mem code_assert_nn (\u03c3.pc  - 9))\n    (h_mem_1 : mem_at mem code_assert_le (\u03c3.pc  - 5))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 5))\n    (hin_a : a = mem (\u03c3.fp - 4))\n    (hin_b : b = mem (\u03c3.fp - 3))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u03c4.ap = \u03c3.ap + 14 \u2227\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 5)) (mem $ \u03c4.ap - 1)\n        (spec_assert_nn_le mem \u03ba range_check_ptr a b (mem (\u03c4.ap - 1)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  have h_mem_rec := h_mem,\n  unpack_memory code_assert_nn_le at h_mem with \u27e8hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8\u27e9,\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 \u03ba_call4 ap4 h_call4,\n  rcases h_call4 with \u27e8h_call4_ap_offset, h_call4\u27e9,\n  rcases h_call4 with \u27e8rc_m4, rc_mle4, hl_range_check_ptr\u2081, h_call4\u27e9,\n  generalize' hr_rev_range_check_ptr\u2081: mem (ap4 - 1) = range_check_ptr\u2081,\n  have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\n  try { simp only [arg0 ,arg1] at hl_range_check_ptr\u2081 },\n  rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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\u2081 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\u2081] },\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\u2081] },\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\u2081] },\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 \u03ba_call8 ap8 h_call8,\n  rcases h_call8 with \u27e8h_call8_ap_offset, h_call8\u27e9,\n  rcases h_call8 with \u27e8rc_m8, rc_mle8, hl_range_check_ptr\u2082, h_call8\u27e9,\n  generalize' hr_rev_range_check_ptr\u2082: mem (ap8 - 1) = range_check_ptr\u2082,\n  have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\n  try { simp only [arg0 ,arg1] at hl_range_check_ptr\u2082 },\n  rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\n  try { simp only [arg0 ,arg1] at h_call8 },\n  rw [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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 [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03ba_call4],\n  use_only [range_check_ptr\u2081],\n  have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n  have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n  have spec4 := h_call4 rc_h_range_check_ptr',\n  rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] at spec4,\n  try { dsimp at spec4, arith_simps at spec4 },\n  use_only [spec4],\n  use_only [\u03ba_call8],\n  use_only [range_check_ptr\u2082],\n  have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n  have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n  have spec8 := h_call8 rc_h_range_check_ptr\u2081',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190htv_range_check_ptr\u2082] 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\u2081, htv_range_check_ptr\u2082] }, },\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": "structure Foo where\n  foo : Nat\n\ndef baz {x : _} := Foo.mk x -- works fine\nexample {x : _} := Foo.mk x\ndef qux {x : _} : Foo := Foo.mk x\nexample {x : _} : Foo := Foo.mk x\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/331.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.054198730587037405, "lm_q1q2_score": 0.01794626956020168}}
{"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Arthur Paulino, Gabriel Ebner, Mario Carneiro\n-/\nimport Lean\nimport Mathlib.Tactic.Core\n\nnamespace Mathlib.Tactic\n\nopen Lean Parser.Tactic Elab.Tactic\n\nsyntax simpaArgsRest := (config)? (discharger)? &\" only \"? (simpArgs)? (withArgs)? (usingArg)?\n\nsyntax \"simpa\" \"!\"? \"?\"? simpaArgsRest : tactic\nmacro \"simpa!\" rest:simpaArgsRest : tactic => `(tactic| simpa ! $rest:simpaArgsRest)\nmacro \"simpa?\" rest:simpaArgsRest : tactic => `(tactic| simpa ? $rest:simpaArgsRest)\nmacro \"simpa!?\" rest:simpaArgsRest : tactic => `(tactic| simpa !? $rest:simpaArgsRest)\n\n-- TODO\nsyntax \"squeeze_simpa\" \"!\"? \"?\"? simpaArgsRest : tactic\nmacro \"squeeze_simpa!\" rest:simpaArgsRest : tactic => `(tactic| squeeze_simpa ! $rest:simpaArgsRest)\nmacro \"squeeze_simpa?\" rest:simpaArgsRest : tactic => `(tactic| squeeze_simpa ? $rest:simpaArgsRest)\nmacro \"squeeze_simpa!?\" rest:simpaArgsRest : tactic => `(tactic| squeeze_simpa !? $rest:simpaArgsRest)\n\n/--\nThis is a \"finishing\" tactic modification of `simp`. It has two forms.\n\n* `simpa [rules, \u22ef] 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, \u22ef]` 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.\n\n#TODO: implement `with \u22ef` behavior\n#TODO: implement `!`\n#TODO: implement `?`\n-/\nelab_rules : tactic\n| `(tactic| simpa $[!%$unfold]? $[?%$squeeze]? $[$cfg:config]? $[$disch:discharger]? $[only%$only]?\n      $[[$args,*]]? $[with $wth]? $[using $usingArg]?) => do\n  let nGoals := (\u2190 getUnsolvedGoals).length\n  evalTactic $ \u2190 `(tactic|simp $(cfg)? $(disch)? $[only%$only]? $[[$[$args],*]]?)\n  if (\u2190 getUnsolvedGoals).length < nGoals then\n    throwError \"try 'simp' instead of 'simpa'\"\n  match usingArg with\n  | none   =>\n    evalTactic $ \u2190 `(tactic|try simp $(cfg)? $(disch)? $[only%$only]? $[[$[$args],*]]? at this)\n    evalTactic $ \u2190 `(tactic|assumption)\n  | some e =>\n    evalTactic $ \u2190 `(tactic|have h := $e)\n    evalTactic $ \u2190 `(tactic|try simp $(cfg)? $(disch)? $[only%$only]? $[[$[$args],*]]? at h)\n    evalTactic $ \u2190 `(tactic|exact h)\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/Simpa.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215779698935, "lm_q2_score": 0.04208773167037179, "lm_q1q2_score": 0.017942908178886365}}
{"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 \u2192 option (\u2115 \u00d7 \u2115)\ndef emp\u0393 : FTContext := \u03bb_, none \n\ndef VarStore (vars : finset Identifier) := \u2200 i : Identifier, (i \u2208 vars) \u2192 Literal\ndef empStore : VarStore \u2205\n  | i i_in_emp := absurd i_in_emp (finset.not_mem_empty i)\n\nnamespace YulCommands\n\nvariable \u0393 : 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 \u2192 finset Identifier \u2192 IsInFor \u2192 IsInFunc \u2192 TermType\n| CBlock : finset Identifier \u2192 IsInFor \u2192 IsInFunc \u2192 TermType\n| SwitchBody : finset Identifier \u2192 IsInFor \u2192 IsInFunc \u2192 TermType\n| CExpr : finset Identifier \u2192 \u2115 \u2192 TermType\n| CStatement : finset Identifier \u2192 finset Identifier \u2192 IsInFor \u2192 IsInFunc \u2192 TermType\n\nopen IsInFor\nopen IsInFunc\nopen TermType\n\ninductive YulTerm : TermType \u2192 Type\n| EmpCBlock : \n    \u2200{vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm (BlockList vars vars b b')\n| SeqCBlock  : \n    \u2200 {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') \u2192 \n    YulTerm (BlockList vars vars'' b b')\n\n| NestedScope : \n    \u2200 {vars : finset Identifier} (inner_vars inner_vars' : finset Identifier) \n      {b : IsInFor} {b' : IsInFunc}, \n    VarStore inner_vars \u2192 \n    YulTerm (BlockList (inner_vars \u222a vars) (inner_vars' \u222a vars) b b') \u2192 \n    YulTerm (CBlock vars b b')\n\n| CCase : \n    \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc},\n      Literal \u2192 YulTerm (CBlock vars b b') \u2192 YulTerm (SwitchBody vars b b') \u2192 \n      YulTerm (SwitchBody vars b b')\n| CDefault : \n    \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc},\n      YulTerm (CBlock vars b b') \u2192 YulTerm (SwitchBody vars b b')\n| CNone : \n    \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc},\n      YulTerm (SwitchBody vars b b')\n\n| CFunctionCall : \n    \u2200 {vars : finset Identifier} \n      (f_id : Identifier) (n : \u2115) {m : \u2115}, \n        (\u0393 f_id = some (n,m)) \u2192 \n        (fin n \u2192 YulTerm (CExpr vars 1)) \u2192\n        YulTerm (CExpr vars m)\n| CId : \n    \u2200 {vars : finset Identifier} (id : Identifier), \n    id \u2208 vars \u2192 YulTerm (CExpr vars 1)\n| CLit : \n    \u2200 {vars : finset Identifier}, \n      Literal \u2192 YulTerm (CExpr vars 1)\n| Scope : \u2200 {vars_outer : finset Identifier} (vars_inner vars_fin : finset Identifier) \n               {n : \u2115} (ret_vars : vector Identifier n), \n    VarStore (vars_inner \u222a (tofinset' ret_vars)) \u2192\n    YulTerm (BlockList (vars_inner \u222a (tofinset' ret_vars)) (vars_fin \u222a (tofinset' ret_vars)) NotNestedInFor InFunc) \u2192 \n    YulTerm (CExpr vars_outer n)\n| Result : \n    \u2200 {vars : finset Identifier} {n : \u2115},\n      vector Literal n \u2192 YulTerm (CExpr vars n)\n    \n| CBlock : \n  \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm (CBlock vars b b') \u2192 YulTerm (CStatement vars vars b b')\n  -- Function definitions already parsed into FTContext.\n| CVariableDeclarationAss : \n    \u2200 {vars : finset Identifier} (n : \u2115) \n        (new_vars : fin n -> Identifier) {b : IsInFor} {b' : IsInFunc},\n      YulTerm (CExpr vars n) \u2192 \n      YulTerm (CStatement vars (vars \u222a (tofinset new_vars)) b b')\n| CVariableDeclaration : \n    \u2200 {vars : finset Identifier} (n : \u2115) \n        (new_vars : fin n -> Identifier) {b : IsInFor} {b' : IsInFunc},\n      YulTerm (CStatement vars (vars \u222a (tofinset new_vars)) b b')\n| CAssignment :\n    \u2200 {vars : finset Identifier} (n : \u2115) \n        (ids : fin n -> Identifier) {b : IsInFor} {b' : IsInFunc},\n      tofinset ids \u2286 vars \u2192 YulTerm (CExpr vars n) \u2192 \n      YulTerm (CStatement vars vars b b')\n| CIf : \n    \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n      YulTerm (CExpr vars 1) \u2192 YulTerm (CBlock vars b b') \u2192 \n      YulTerm (CStatement vars vars b b')\n| CExpressionStatement : \n    \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm (CExpr vars 0) -> YulTerm (CStatement vars vars b b')\n| CSwitch : \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm (CExpr vars 1) \u2192 \n    YulTerm (SwitchBody vars b b') \u2192 \n    YulTerm (CStatement vars vars b b')\n| CFor : \n  \u2200 {vars : finset Identifier} (inner_vars inner_vars' inner_vars'' : finset Identifier)\n      {b : IsInFor} {b' : IsInFunc},  \n    YulTerm (BlockList vars (vars \u222a inner_vars) NotNestedInFor b') \u2192 \n    YulTerm (CExpr (vars \u222a inner_vars) 1) \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars) (vars \u222a inner_vars') NestedInFor b') \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars') (vars \u222a inner_vars'') NotNestedInFor b') \u2192 \n    YulTerm (CStatement vars vars b b')\n| CBreak : \n    \u2200 {vars : finset Identifier} {b' : IsInFunc}, \n      YulTerm (CStatement vars vars NestedInFor b')\n| CContinue : \n    \u2200 {vars : finset Identifier} {b' : IsInFunc}, \n      YulTerm (CStatement vars vars NestedInFor b')\n| CLeave : \n    \u2200 {vars : finset Identifier} {b : IsInFor}, \n      YulTerm (CStatement vars vars b InFunc)\n| ForExecInit :\n  \u2200 {vars : finset Identifier} (curr_inner_vars inner_vars inner_vars' inner_vars'' : finset Identifier) \n      {b : IsInFor} {b' : IsInFunc}, \n    VarStore curr_inner_vars \u2192\n    YulTerm (CExpr (vars \u222a inner_vars) 1) \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars) (vars \u222a inner_vars') NestedInFor b') \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars') (vars \u222a inner_vars'') NotNestedInFor b') \u2192\n    YulTerm (BlockList (vars \u222a curr_inner_vars) (vars \u222a inner_vars) NotNestedInFor b') \u2192\n     YulTerm (CStatement vars vars b b')\n| ForCheckCond : \n  \u2200 {vars : finset Identifier} (inner_vars inner_vars' inner_vars'' : finset Identifier) \n      {b : IsInFor} {b' : IsInFunc}, \n    VarStore inner_vars \u2192\n    YulTerm (CExpr (vars \u222a inner_vars) 1) \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars) (vars \u222a inner_vars') NestedInFor b') \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars') (vars \u222a inner_vars'') NotNestedInFor b') \u2192\n    YulTerm (CExpr (vars \u222a inner_vars) 1) \u2192\n    YulTerm (CStatement vars vars b b')\n| ForExecBody : \n  \u2200 {vars : finset Identifier} (curr_inner_vars inner_vars inner_vars' inner_vars'' : finset Identifier) \n      {b : IsInFor} {b' : IsInFunc}, \n    VarStore curr_inner_vars \u2192\n    vars \u222a inner_vars \u2286 vars \u222a curr_inner_vars \u2192\n    YulTerm (CExpr (vars \u222a inner_vars) 1) \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars) (vars \u222a inner_vars') NestedInFor b') \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars') (vars \u222a inner_vars'') NotNestedInFor b') \u2192\n    YulTerm (BlockList (vars \u222a curr_inner_vars) (vars \u222a inner_vars') NestedInFor b') \u2192\n    YulTerm (CStatement vars vars b b')\n| ForExecPost : \n  \u2200 {vars : finset Identifier} (curr_inner_vars inner_vars inner_vars' inner_vars'' : finset Identifier) \n      {b : IsInFor} {b' : IsInFunc}, \n    VarStore curr_inner_vars \u2192\n    YulTerm (CExpr (vars \u222a inner_vars) 1) \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars) (vars \u222a inner_vars') NestedInFor b') \u2192 \n    YulTerm (BlockList (vars \u222a inner_vars') (vars \u222a inner_vars'') NotNestedInFor b') \u2192\n    YulTerm (BlockList (vars \u222a curr_inner_vars) (vars \u222a inner_vars'') NotNestedInFor b') \u2192\n    YulTerm (CStatement vars vars b b')\n| Skip : \n    \u2200 {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 : \u2200 {t : TermType} , YulTerm \u0393 t \u2192 option (finset Identifier \u00d7 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        \u2200 {t : TermType} (term : YulTerm \u0393 t) (vars vars' : finset Identifier),\n        getVariableUpdate \u0393 term = some (vars, vars') \u2192 vars \u2286 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 [\u2190tvars_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_\u1fb0,\n    have int\u2081 := t_ih_\u1fb0 vars t_vars' _ i_in_vars,\n    rw tvars''_eq_vars' at t_\u1fb0_1,\n    have int\u2082 := t_ih_\u1fb0_1 t_vars' vars' _ int\u2081,\n    exact int\u2082,\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 [\u2190tvars_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 [\u2190vars_eq,\u2190eq_vars'],\n      exact finset.subset_union_left _ _,\n    },\n\n  end      \n\ndef frame_TermType : TermType \u2192 finset Identifier \u2192 TermType\n| (BlockList vars vars' b b') fvars := \n    BlockList (vars \u222a fvars) (vars' \u222a fvars) b b'\n| (CBlock vars b b') fvars := CBlock (vars \u222a fvars) b b'\n| (SwitchBody vars b b') fvars := SwitchBody (vars \u222a fvars) b b'\n| (CExpr vars n) fvars := CExpr (vars \u222a fvars) n\n| (CStatement vars vars' b b') fvars := \n    CStatement (vars \u222a fvars) (vars' \u222a fvars) b b'\n\nlemma frame_lemma : \n  \u2200 s\u2081 s\u2082 s\u2083 : finset Identifier, \n    s\u2081 \u222a s\u2082 \u222a s\u2083 = s\u2081 \u222a s\u2083 \u222a s\u2082 :=\n  begin\n    intros s\u2081 s\u2082 s\u2083,\n    rw (finset.union_assoc s\u2081 s\u2082 s\u2083),\n    rw (finset.union_assoc s\u2081 s\u2083 s\u2082),\n    rw (finset.union_comm s\u2082 s\u2083),\n  end\n\ndef frame : \n  \u2200 {t : TermType} (fvars : finset Identifier), \n    YulTerm \u0393 t \u2192 YulTerm \u0393 (frame_TermType t fvars)\n| (BlockList _ _ _ _) fvars EmpCBlock := EmpCBlock\n| (BlockList _ _ _ _) fvars (SeqCBlock vars' cstmnt cblklst') :=\n    SeqCBlock (vars' \u222a fvars) (frame fvars cstmnt) (frame fvars cblklst')\n| (CBlock vars b b') fvars (NestedScope inner_vars inner_vars' \u03c3 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 \u0393 (BlockList((inner_vars \u222a vars) \u222a fvars) ((inner_vars' \u222a vars) \u222a fvars) b b')) : \n                 YulTerm \u0393 (BlockList (inner_vars \u222a (vars \u222a fvars)) (inner_vars' \u222a (vars \u222a fvars)) b b') :=\n              eq.rec (eq.rec cblklst inner_vars_eq) inner_vars'_eq\n      in NestedScope inner_vars inner_vars' \u03c3 (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 (\u03bbi, 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 \u03c3 stmnt) :=\n    Scope vars_inner vars_inner' ret_vars \u03c3 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 \u0393 (CStatement (vars \u222a fvars) (vars \u222a fvars \u222a tofinset new_vars) b b'))\n            : YulTerm \u0393 (CStatement (vars \u222a fvars) (vars \u222a tofinset new_vars \u222a 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 \u0393 (CStatement (vars \u222a fvars) (vars \u222a fvars \u222a tofinset new_vars) b b'))\n            : YulTerm \u0393 (CStatement (vars \u222a fvars) (vars \u222a tofinset new_vars \u222a 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 \u0393 (BlockList (vars \u222a fvars) (vars \u222a fvars \u222a 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 \u0393 (CExpr (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars) (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars') (vars \u222a fvars \u222a 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'' \u03c3 cond loop post eval_init) :=\n    let cond_framed : YulTerm \u0393 (CExpr (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars) (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars') (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a curr_inner_vars) (vars \u222a fvars \u222a 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'' \u03c3\n        cond_framed loop_framed post_framed eval_init_framed\n| (CStatement vars _ b b') fvars \n      (ForCheckCond inner_vars inner_vars' inner_vars'' \u03c3 cond loop post eval_cond) :=\n    let cond_framed : YulTerm \u0393 (CExpr (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars) (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars') (vars \u222a fvars \u222a 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 \u0393 (CExpr (vars \u222a fvars \u222a 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'' \u03c3\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'' \u03c3 p cond loop post eval_loop) :=\n    let cond_framed : YulTerm \u0393 (CExpr (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars) (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars') (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a curr_inner_vars) (vars \u222a fvars \u222a 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 \u222a fvars \u222a inner_vars \u2286 vars \u222a fvars \u222a 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'' \u03c3 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'' \u03c3 cond loop post eval_post) :=\n    let cond_framed : YulTerm \u0393 (CExpr (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars) (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a inner_vars') (vars \u222a fvars \u222a 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 \u0393 (BlockList (vars \u222a fvars \u222a curr_inner_vars) (vars \u222a fvars \u222a 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'' \u03c3\n        cond_framed loop_framed post_framed eval_post_framed\n| (CStatement vars _ b b') fvars Skip := Skip \n\ndef are_args_reduced : \n  \u2200 {vars : finset Identifier} {n : \u2115}, \n    vector (YulTerm \u0393 (CExpr vars 1)) n \u2192 Prop\n| _ 0 _ := true\n| vars (nat.succ n) \u27e8 (Result _) :: cexprs, p \u27e9 := \n  are_args_reduced \n    (\u27e8 \n      cexprs, \n      by {\n            rw list.length at p,\n            exact (nat.add_right_cancel p),\n          }\n     \u27e9 : vector (YulTerm \u0393 (CExpr vars 1)) n)\n| _ (nat.succ n) \u27e8 _ :: _, _ \u27e9 := false\n\ninstance (vars : finset Identifier) (n : \u2115) \n  (cexprs : vector (YulTerm \u0393 (CExpr vars 1)) n) : \n    decidable (are_args_reduced \u0393 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 \u27e8 cexprs_val_tl, _ \u27e9,\n  end\n\nlemma nil_reduced : \n  \u2200 {\u0393 : FTContext} {vars : finset Identifier}, \n    @are_args_reduced \u0393 vars 0 vector.nil :=\n  begin\n    intros \u0393 vars,\n    rw are_args_reduced,\n    trivial,\n  end \n\ndef is_result : \n  \u2200 {vars : finset Identifier} {n : \u2115}, \n    YulTerm \u0393 (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 : \u2115) \n    (cexpr : YulTerm \u0393 (CExpr vars n)) : decidable (is_result \u0393 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  \u2200 {vars vars': finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm \u0393 (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  \u2200 {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc} \n      {cstmnt : YulTerm \u0393 (CStatement vars vars' b b')},\n    is_skip \u0393 cstmnt \u2192 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 \u0393 (CStatement vars vars' b b')} : decidable (is_skip \u0393 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  \u2200 {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm \u0393 (BlockList vars vars' b b') \u2192 Prop \n| _ _ _ _ EmpCBlock := true\n| _ _ _ _ _ := false\n\ninstance empcblock_decidable \n  {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc}\n    {blklst : YulTerm \u0393 (BlockList vars vars' b b')} : \n  decidable (is_empcblock \u0393 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  \u2200 {vars vars' : finset Identifier} {b : IsInFor} \n      {b' : IsInFunc} {cblk : YulTerm \u0393 (BlockList vars vars' b b')},\n    is_empcblock \u0393 cblk \u2192 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  \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    YulTerm \u0393 (CBlock vars b b') \u2192 Prop\n| _ _ _ (NestedScope _ _ _ blklst) := is_empcblock \u0393 blklst\n\ninstance (vars : finset Identifier) (b : IsInFor) (b' : IsInFunc)\n  (blk : YulTerm \u0393 (CBlock vars b b')) : decidable (is_empblock \u0393 blk) :=\n  begin\n    cases blk,\n    rw is_empblock,\n    exact YulCommands.empcblock_decidable \u0393,\n  end\n\ndef to_literal : \u2200 {vars : finset Identifier} {n : \u2115}\n      (cexpr : YulTerm \u0393 (CExpr vars n)), is_result \u0393 cexpr \u2192 vector Literal n\n  | _ _ cexpr@(CFunctionCall _ _ _ _) cexpr_is_res := \n    let cexpr_n_is_res : \u00ac is_result \u0393 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 : \u00ac is_result \u0393 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 : \u00ac is_result \u0393 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 : \u00ac is_result \u0393 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  \u2200 {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n    Literal -> YulTerm \u0393 (SwitchBody vars b b') \u2192 YulTerm \u0393 (CBlock vars b b')\n| _ _ _ _ CNone := NestedScope \u2205 \u2205 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 \u0393 (CExpr vars 1))\n  {n : \u2115}\n  (cexprs : vector (YulTerm \u0393 (CExpr vars 1)) n) :\n    \u00ac (are_args_reduced \u0393 (vector.cons cexpr cexprs)) \u2192 are_args_reduced \u0393 cexprs \u2192 \n      \u00ac is_result \u0393 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  \u2200 {vars : finset Identifier} {n : \u2115} \n    (arg_cexprs : vector (YulTerm \u0393 (CExpr vars 1)) n),\n  are_args_reduced \u0393 arg_cexprs \u2192 vector Literal n \n| _ 0 _ _ := vector.nil\n| vars (nat.succ n) \u27e8(Result lit) :: lit_cexprs, len_p\u27e9 p :=\n  let lit_cexprs_vec' : vector (YulTerm \u0393 (CExpr vars 1)) n := \n        \u27e8 lit_cexprs, \n          by {\n            rw list.length at len_p,\n            exact (nat.add_right_cancel len_p),\n          }\n        \u27e9\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": "import Lean.Meta\nimport Lean.Elab\nimport Scratch.IntrosRwFind\nopen Lean\nopen Meta\nopen Lean.Elab.Tactic\nopen Elab\nopen introsRwFind\n\n-- copied from source\n\n\ndef g (x : Nat) : Nat :=\ndbgTrace (\"g: \" ++ toString x) $ fun _ =>\n  x + 1\n\ndef f1 (x : Nat) : Nat :=\ndbgSleep 1000 $ fun _ =>\ndbgTrace (\"f1: \" ++ toString x) $ fun _ =>\n  g (x + 1)\n\ndef f2 (x : Nat) : Nat :=\ndbgSleep 100 $ fun _ =>\ndbgTrace (\"f2: \" ++ toString x) $ fun  _ =>\n  g x\n\ndef tst (n : Nat) : IO Nat :=\nlet t1 := Task.spawn fun _ => f1 n;\nlet t2 := Task.spawn fun _ => f2 n;\ndbgSleep 1000 $ fun _ =>\nIO.println (toString t1.get ++ \" \" ++ toString t2.get) *>\npure t1.get\n\n#eval tst 10\n\n#check tst 20\n\nsyntax (name:= tasktac) \"tasktac\" : tactic\n@[tactic tasktac] def tasktacImp : Tactic :=\n  fun stx =>\n    do \n      let res \u2190 tst 20\n      let value \u2190 ToExpr.toExpr res\n      logInfo m!\"got {res}\"\n      let type := mkConst `Nat\n      liftMetaTactic $  addToContextM `result type value \n      return ()\n\ndef tt : Nat := by\n  tasktac\n  exact result\n\n#eval tt\n\ndef tstDirect(n: Nat) : Nat :=\n   let t1 := Task.spawn fun _ => n * 2\n   let t2 := Task.spawn fun _ => n * 3\n   t1.get + t2.get\n\n#eval tstDirect 3\n\ndef egRef := IO.mkRef 3\n\ndef egRefVal : IO Nat :=\n  do\n    let ref \u2190 egRef\n    let val \u2190 ref.get\n    return val\n\n#eval egRefVal\n\ndef doubleEgRef : IO Nat :=\n  do\n    let ref \u2190 egRef\n    let val \u2190 ref.get\n    ref.set (val * 2)\n    let val2 \u2190 ref.get\n    return val2\n\ndef egRefVal2 : IO Nat :=\n  do\n    let ref \u2190 egRef\n    let val \u2190 ref.get\n    return val\n\n#eval egRefVal2\n#eval doubleEgRef \n\nopen Lean.Elab.Term\n\n-- copied from source, removed error registering and so syntax\n/- whnfCore + implicit consumption.\n   Example: given `e` with `eType := {\u03b1 : Type} \u2192 (fun \u03b2 => List \u03b2) \u03b1 `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/\npartial def consumeImplicits  (e eType : Expr) (hasArgs : Bool) : \n          TermElabM (Expr \u00d7 Expr) := do\n  let eType \u2190 whnfCore eType\n  match eType with\n  | Expr.forallE n d b c =>\n    if c.binderInfo.isImplicit || (hasArgs && c.binderInfo.isStrictImplicit) then\n      let mvar \u2190 mkFreshExprMVar d\n      consumeImplicits (mkApp e mvar) (b.instantiate1 mvar) hasArgs\n    else if c.binderInfo.isInstImplicit then\n      let mvar \u2190 mkInstMVar d\n      let r := mkApp e mvar\n      consumeImplicits  r (b.instantiate1 mvar) hasArgs\n    else match d.getOptParamDefault? with\n      | some defVal => \n          consumeImplicits (mkApp e defVal) (b.instantiate1 defVal) hasArgs\n      -- TODO: we do not handle autoParams here.\n      | _ => pure (e, eType)\n  | _ => pure (e, eType)\n\npartial def lambdaImplicits  (e  : Expr) (makeExplicit : Bool) : \n          MetaM Expr := do\n  let eType \u2190 inferType e\n  let eType \u2190 whnfCore eType\n  match eType with\n  | Expr.forallE n d b c =>\n    let bind := if makeExplicit then BinderInfo.default else c.binderInfo \n    if c.binderInfo.isImplicit || c.binderInfo.isStrictImplicit then\n      withLocalDecl Name.anonymous bind d  $ fun x => \n        do\n          let prev \u2190 lambdaImplicits (mkApp e x)  makeExplicit\n          return \u2190  mkLambdaFVars #[x] prev\n    else if c.binderInfo.isInstImplicit then\n      withLocalDecl Name.anonymous bind d  $ fun x => \n        do\n          let prev \u2190 lambdaImplicits (mkApp e x)  makeExplicit\n          return \u2190  mkLambdaFVars #[x] prev\n\n    else match d.getOptParamDefault? with\n      | some defVal => \n          lambdaImplicits (mkApp e defVal)  makeExplicit\n      -- TODO: we do not handle autoParams here.\n      | _ => pure e\n  | _ => pure e\n\n#check @Prod.mk\n\ndef three3 := PProd.mk \"three\" 3\n\n#check three3\n\ndef checkProdMeta : TermElabM Expr :=\n  do\n    let env \u2190 getEnv\n    let ee \u2190 Term.mkConst `three3\n    let u \u2190 mkFreshLevelMVar\n    let v \u2190 mkFreshLevelMVar\n    let \u03b1 \u2190 mkFreshExprMVar (mkSort u)\n    let \u03b2  \u2190 mkFreshExprMVar (mkSort v)\n    let a \u2190 mkFreshExprMVar \u03b1 \n    let b \u2190 mkFreshExprMVar \u03b2 \n    let f := mkAppN (Lean.mkConst ``PProd.mk [u, v]) #[\u03b1, \u03b2, a, b]\n    logInfo f\n    if \u2190 isDefEq f ee\n      then\n        logInfo m!\"unified\"  \n        return b\n      else \n        logInfo m!\"did not unify\"\n        return a\n\nsyntax (name:= checkmeta) \"checkMeta!\" : term\n@[termElab checkmeta] def chkmImpl : TermElab :=\n  fun _ _ => return \u2190 checkProdMeta\n\ndef chk : Nat := checkMeta!\n\n#eval chk\n\n#eval checkProdMeta\n\ndef getFnsAux : Expr \u2192 List Expr \u2192 List Expr\n  | Expr.app f a _, l  => getFnsAux f (f :: a :: l) \n  | e, l => e :: l\n\ndef getFnsArgs : Expr \u2192 MetaM (List Expr)\n  | Expr.app f a _ => \n    do \n      let ft \u2190 inferType f\n      let expl := ft.data.binderInfo.isExplicit\n      if expl then\n      (\u2190  getFnsArgs f) ++ (\u2190 getFnsArgs a) ++ [f, a]\n      else [f]\n  | e => try \n         do  [\u2190 lambdaImplicits e true]\n        catch _ => []\n\ndef consImpl (e: Expr) : TermElabM Expr := do\n  let eType \u2190 inferType e\n  let (e, eType) \u2190 consumeImplicits e eType true\n  return e\n\ndef lamImpl (e: Expr) (mkExplicit : Bool) : TermElabM Expr := do\n  let e \u2190 lambdaImplicits e  mkExplicit\n  return e\n\n\ninductive \u0398 {\u03b1 : Type u}: \u03b1 \u2192  Type u where\n  | mk :  (a : \u03b1) \u2192 \u0398  a\n  \ndef \u0398.value {\u03b1 : Type u}{a: \u03b1} : \u0398 a \u2192 \u03b1 \n  | \u0398.mk a => a\n\ntheorem \u0398.value.eq {\u03b1 : Type u}{a: \u03b1} : \n    \u2200 (s : \u0398 a), \u0398.value s = a := \n            by intro s; cases s; rfl \n\ninitialize xxx : IO.Ref (Nat) \u2190 IO.mkRef 0\n\n#check xxx\n\ndef getX : IO Nat :=\n  do\n    let ref \u2190 xxx\n    return \u2190 ref.get\n\ndef incX : IO Nat :=\n  do\n    let ref \u2190 xxx\n    let value \u2190 ref.get\n    ref.set (value + 1)\n    return value\n\ndef getXRef (ref: IO.Ref Nat) : IO Nat :=\n  do\n    return \u2190 ref.get\n\ndef incXRef(ref: IO.Ref Nat) : IO Nat :=\n  do\n    let value \u2190 ref.get\n    ref.set (value + 1)\n    return value\n\n#check getX\n\n\n-- def incTask : IO Unit  :=\n--   do \n--     let tsk := IO.asTask (dbgSleep 600 $ fun _ => incX)\n--     tsk.map (fun _ => ())\n--     return ()\n\n-- #check incTask\n\n\n\ndef update (snap: IO Nat) : IO Unit :=\n  do\n    let ref \u2190 xxx\n    let value \u2190 snap\n    ref.set value\n    return ()\n\nsyntax (name:= snapmem) \"snap!\" : tactic\n@[tactic snapmem] def snapImpl : Tactic :=\n  fun stx =>\n    liftMetaTactic $ fun mvar => do\n      let value \u2190 getX\n      assignExprMVar mvar (ToExpr.toExpr value)\n      return [] \n\nsyntax (name:= nrmlform)\"whnf!\" term : term\n@[termElab nrmlform] def normalformImpl : TermElab :=\n  fun stx expectedType? =>\n  match stx with\n  | `(whnf! $s) => \n      do\n        let t \u2190 Term.elabTerm s none \n        let e \u2190 whnf t\n        logInfo m!\"whnf : {e}\"\n        return e\n  | _ => Lean.Elab.throwIllFormedSyntax\n\n-- expanded form of initialize\ndef initFn: IO (IO.Ref Nat) := do \u2190 IO.mkRef 0\n@[init initFn] constant yyy : IO.Ref Nat\n\ndef pad (s: String)(n: Nat) : String :=\n  match n with\n  | 0 => s\n  | m + 1 => s ++ \u27e8Char.ofNat (64 + n) :: []\u27e9\n\ndef addSingletonsToContextM (values : List Expr) : \n     MVarId \u2192 TermElabM (List MVarId) :=\n     match values with\n      | [] => fun m => \n      return [m]\n      | h::t => fun m => \n        do\n          let f := Lean.mkConst `mkSingleton\n          let htype \u2190 inferType h\n          let exprOpt : Option Expr \u2190 \n            try\n              let expr \u2190  mkAppM `\u0398.mk #[h]\n              some expr\n            catch _ => none\n          match exprOpt with\n          | some expr =>\n            let n := values.length\n            let name := Name.mkSimple (pad \"piece\" n)\n            let newMVarIds \u2190 addToContextM name (\u2190 inferType expr) expr m\n            addSingletonsToContextM t newMVarIds.head!\n          | none => \n            addSingletonsToContextM t m\n\nsyntax (name:= exppieces) \"exppieces\" : tactic\n@[tactic exppieces] def exppiecesImp : Tactic :=\n  fun stx =>\n    withMainContext\n    do\n      let e \u2190 getMainTarget \n      let eType \u2190 inferType e\n      let e \u2190 instantiateMVars e\n      let pieces \u2190 (\u2190 getFnsArgs e).eraseDups\n      logInfo m!\"got {pieces}\"\n      let fedPieces \u2190 pieces.mapM (fun exp => consImpl exp)\n      logInfo m!\"refined {fedPieces}\"\n      let repieces \u2190 pieces.mapM (fun exp => do whnf (\u2190 instantiateMVars exp))\n      logInfo m!\"rebuilt {repieces}\"\n      let h := fedPieces.head!\n      let comp \u2190 fedPieces.mapM (fun e => isDefEq h e)\n      logInfo m!\"compare {comp}\"\n      logInfo m!\"post compare: {\u2190 fedPieces.mapM (fun e => whnf e)}\"\n      let unchanged \u2190 pieces.mapM (fun exp =>\n          do \n          let fed \u2190 consImpl exp\n          return exp == fed\n      )      \n      logInfo m!\"equal? {unchanged}\"\n      let lamPieces \u2190 pieces.mapM (fun exp => lamImpl exp true)\n      let lamImplPieces \u2190 pieces.mapM (fun exp => lamImpl exp false)\n      logInfo m!\"lambda {lamPieces}\"\n      let lamTypes \u2190  lamPieces.mapM (fun x => inferType x)\n      logInfo m!\"lambdaTypes {lamTypes}\"\n      liftMetaTactic $ fun mvar =>  \n        (addSingletonsToContextM  (lamImplPieces ++ lamPieces) mvar).run' \n      return ()\n\n-- set_option pp.all true\n\ndef transitPf {\u03b1 : Type}:{a b c : \u03b1} \u2192 \n          a = b \u2192 b = c \u2192 a = c := by\n          intros a b c eq1 eq2\n          exppieces\n          let p := pieceA.value\n          let pg := pieceG.value\n          have h1 : p  = @Eq \u03b1 a  := by \n              apply \u0398.value.eq\n          rw [eq2] at eq1\n          exact eq1\n\nvariable {M: Type u}[Mul M]\n\n-- example : (\u2200 a b : M, (a * b) * b = a) \u2192 (\u2200 a b : M, a * (a * b) = b) \u2192\n--             (m n : M) \u2192  (m * n) = n * m := by\n--             intros eq1 eq2 m n\n--             exppieces\n--             exact sorry\n            \n\n#check @HMul.hMul Nat Nat Nat (inferInstance)\n\ndef op : Type := Nat \u2192 Nat \u2192 Nat \n\n#check Eq", "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/Eg5.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.0440186509602942, "lm_q1q2_score": 0.017930267394490593}}
{"text": "/-\nCopyright (c) 2020 Jason Rute. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Jason Rute and Jesse Michael Han\n\nREPL for interacting with Lean\n-/\nimport data.nat.basic\nimport system.io\nimport tactic.core\nimport tactic\n\nimport utils\nimport .tactic_state\nimport basic.queue\n\nsection tactic_state\nopen interaction_monad.result\nsetup_tactic_parser\n\n/- set this to tt to enable tracing\n  `tactic.set_bool_option` is tactic state specific,\n  and is difficult to globally set -/\n\nmeta def num_goals' : tactic_state \u2192 option \u2115 :=\n\u03bb ts, match tactic.num_goals ts with | (success val _) := pure val | _ := none end\n\n-- TODO(jesse): this is a hack. might be better to do this in python\nmeta def consume_with_parser {\u03b1} (p : lean.parser \u03b1) : string \u2192 io string := \u03bb inp, do {\n  io.run_tactic' $ do\n    prod.snd <$> (lean.parser.run_with_input (with_input p inp) \"\")\n}\n\n-- TODO(jesse): performance\nmeta def consume_spaces : string \u2192 string\n| arg@\u27e8[]\u27e9 := arg\n| arg@\u27e8(x::xs)\u27e9 := if x = ' ' then consume_spaces \u27e8xs\u27e9 else arg\n\n-- WARNING: this is a hack\nmeta def remove_indents_with_split (c : char := '\\t'): string \u2192 string := \u03bb str,\nlet strs := str.split (= '\\t') in\nstring.intercalate (\u27e8['\\t']\u27e9 : string) (consume_spaces <$> strs)\n\nmeta def postprocess_tactic_state : tactic_state \u2192 tactic string := \u03bb ts, do\n  let main : tactic string := do {\n    let ts_str := ts.to_format.to_string,\n    tabbed_ts_str \u2190 do {\n      if (num_goals' ts).get_or_else 0 \u2264 1\n      then pure $ ts_str.replace_char '\\n' '\\t'\n      else tactic.unsafe_run_io $ (\u03bb x, string.replace_char x '\\n' '\\t')\n             <$> (consume_with_parser small_nat >=>\n               consume_with_parser ident) ts_str},\n    pure $ remove_indents_with_split '\\t' tabbed_ts_str\n  },\n  main <|> (let msg := \"[postprocess_tactic_state] WARNING: POSTPROCESSING FAILED\" in tactic.trace msg *> tactic.fail msg)\n\nend tactic_state\n\nmeta def add_open_namespace : name \u2192 tactic unit := \u03bb nm, do\nenv \u2190 tactic.get_env, tactic.set_env (env.execute_open nm)\n\nmeta def add_open_namespaces (nms : list name) : tactic unit :=\nnms.mmap' add_open_namespace\n\nsection run_with_state'\n\nnamespace interaction_monad\nopen interaction_monad.result\nmeta def run_with_state' {\u03c3\u2081 \u03c3\u2082 : Type} {\u03b1 : Type*} (state : \u03c3\u2081) (tac : interaction_monad \u03c3\u2081 \u03b1) : interaction_monad \u03c3\u2082 \u03b1 :=\n\u03bb s, match (tac state) with\n     | (success val _) := success val s\n     | (exception fn pos _) := exception fn pos s\n     end\nend interaction_monad\nend run_with_state'\n\nnamespace tactic\n\nopen interaction_monad.result\nmeta def run (tac : tactic unit) : tactic (interaction_monad.result tactic_state unit) := do {\n  \u03c3 \u2190 get_state,\n  match tac \u03c3 with\n  | r@(success _ new_state) := interaction_monad.set_state new_state *> pure r\n  | r@(exception fn pos new_state) := pure r\n  end\n}\n\n-- meta instance has_format_result {\u03b1 \u03c3} [has_to_format \u03c3] [has_to_format \u03b1] : has_to_format (interaction_monad.result \u03c3 \u03b1) := \u27e8by mk_to_format `interaction_monad.result\u27e9 -- ayyy\n\nmeta instance has_to_format_tactic_result {\u03b1 : Type*} [has_to_format \u03b1] : has_to_format (interaction_monad.result tactic_state \u03b1) :=\n\u27e8\u03bb r,\n  match r with\n  | (success val new_state) := format!\"SUCCESS!\\nNEW_STATE: {new_state}\\nVAL: {val}\"\n  | (exception fn pos old_state) := do {\n    let msg := (fn.get_or_else (\u03bb _, format.of_string \"n/a\")) (),\n    format!\"EXCEPTION!\\nMSG: {msg}\\nPOS: {pos}\\nOLD_STATE: {old_state}\"\n  }\n  end\n\u27e9\n\nmeta instance has_to_tactic_format_tactic_result {\u03b1 : Type*} [has_to_format \u03b1] : has_to_tactic_format (interaction_monad.result tactic_state \u03b1) :=\n\u27e8\u03bb \u03c3, pure $ has_to_format.to_format \u03c3\u27e9\n\nend tactic\n\nsection parse_eval_tac\nsetup_tactic_parser\nopen tactic\n\nmeta def parse_eval_tac\n  (ps : parser_state)\n  (tactic_string : string)\n  : tactic (tactic unit \u00d7 format) := do {\n  let itactic_string := \"{\" ++ tactic_string ++ \"}\",\n  texpr \u2190 (reflected_value.expr \u2218 prod.fst) <$>\n    (interaction_monad.run_with_state' ps $ with_input parser.itactic_reflected itactic_string),\n  prod.mk <$> (eval_expr (tactic unit) texpr) <*> has_to_tactic_format.to_tactic_format texpr\n}\n\nend parse_eval_tac\n\nsection frontend\n\nopen tactic lean lean.parser interactive\nmeta def read_eval_print_loop (ps : parser_state) : tactic unit :=\ndo\n  trace \"\\nTactic state:\",\n  trace_state,\n  let rest : tactic unit := do\n  {trace \"\\nEnter a tactic command:\",\n  tactic_string <- tactic.unsafe_run_io $ io.get_line,\n  (t, fmt) \u2190 parse_eval_tac ps tactic_string,\n  trace \"\",\n  trace (\"Running tactic:\\n\" ++ fmt.to_string),\n  tactic.run t >>= eval_trace,  -- runs the tactic on the goal.  It is crashing\n  read_eval_print_loop},  --- loops forever\n  done <|> rest\n\n--- like main_t, but sets the goal and environment to a user-supplied theorem in mathlib\n--- note: if the environment contains all declarations in mathlib,\n--- and olean files exist,\n--- we don't need to supply the lean file as env.decl_olean will find it automatically.\nmeta def main_t_at : parser_state \u2192 tactic unit := \u03bb ps, do {\n  trace \"enter declaration to prove\",\n  goal_nm_string \u2190 tactic.unsafe_run_io $ io.get_line,\n  \u27e8nm, _\u27e9 \u2190 interaction_monad.run_with_state' ps $ with_input ident goal_nm_string,\n  env \u2190 get_env,\n  decl \u2190 env.get nm,\n  let g := decl.type,\n  set_goal_to g,\n  lean_file \u2190 env.decl_olean nm,\n  set_env_core $ environment.for_decl_of_imported_module lean_file nm,\n  read_eval_print_loop ps\n}\n\n@[user_command]\nmeta def main_app_at\n(meta_info : decl_meta_info) (_ : parse (tk \"main_app_at\")) : lean.parser unit :=\nget_state >>= of_tactic \u2218 (main_t_at)\n\nend frontend\n\nsection main\n\nsetup_tactic_parser\n\nopen tactic\nmeta def main_t : parser_state \u2192 tactic unit := \u03bb ps,\ndo\n  trace \"Enter a goal:\",\n  set_goal_to `(true),\n  goal_string <- tactic.unsafe_run_io $ io.get_line,\n  trace \"GOAL STRING: \" *> trace goal_string,\n  (goal_pexpr, _) \u2190 interaction_monad.run_with_state' ps $ with_input types.texpr goal_string,\n  eval_trace ps.cur_pos,\n  set_goal_to <e> goal_pexpr,\n  (read_eval_print_loop ps) *> main_t ps  -- loops forever\n\n@[user_command]\nmeta def main_app\n(meta_info : decl_meta_info) (_ : parse (tk \"main_app\")) : lean.parser unit :=\n(get_state >>= of_tactic \u2218 main_t)\n\nend main\n\nsection parse_tac\n\nsetup_tactic_parser\n\nopen tactic\n\n/-- Parse a reflected interactive tactic from a string.\n    The result can be evaluated to a `tactic unit` by using\n    `eval_expr (tactic unit)`. -/\nmeta def parse_itactic_reflected (tactic_string : string) : tactic expr :=\nlet itactic_string := \"{ \" ++ tactic_string ++  \" }\" in\nlean.parser.run $ do\n  get_state >>= \u03bb ps, of_tactic $ do\n    tactic.set_env ps.env,\n    -- eval_trace format!\"[parse_itactic_reflected] TRYING TO PARSE {itactic_string}\",\n    (reflected_value.expr \u2218 prod.fst) <$>\n      (@interaction_monad.run_with_state' parser_state _ _ ps $\n         with_input parser.itactic_reflected itactic_string)\n\n/-- Parse an interactive tactic from a string. -/\nmeta def parse_itactic (tactic_string : string) : tactic (tactic unit) := do\n  rtac \u2190 parse_itactic_reflected tactic_string,\n  eval_expr (tactic unit) rtac\n\nend parse_tac\n\nsection evaluation_harness\n\nmeta def run_tac_with_tactic_state\n  (tac : tactic unit)\n  (ts : tactic_state)\n  : tactic (result _ _) := do {\n  tactic.write ts,\n  pure $ tac ts\n}\n\nmeta structure EvaluationInput : Type :=\n(decl_nm : name)\n(ts_data : tactic_state_data)\n(tactic_string : string)\n(open_namespaces : list name)\n\n/- (before_state, action, after_state) tuple -/\nmeta structure EvaluationResult : Type :=\n(before_state : tactic_state)\n(tactic_string : string)\n(result : result tactic_state unit)\n\nmeta instance : has_to_format EvaluationResult :=\n\u27e8\u03bb \u27e8\u03c3, tac_str, r\u27e9,\n  format.join [\n    -- hmm. why doesn't the highlighting work?\n    format.highlight \"INPUT STATE:\\n\" format.color.pink,\n    \u03c3.to_format,\n    \"\\n\\n\",\n    format.highlight \"ACTION:\\n\" format.color.pink,\n    tac_str,\n    \"\\n\\n\",\n    format.highlight  \"RESULT:\\n\" format.color.pink,\n    (has_to_format.to_format r)\n  ]\n\u27e9\n\n/-- Creates an empty tactic state. -/\nmeta def mk_tactic_state : tactic tactic_state :=\ntactic.unsafe_run_io $ io.run_tactic' $ tactic.exact `(trivial) *> tactic.read\n\n/-- creates tactic_state_data as if we were proving the declaration\n (currently only theorems are supported) with name `decl_nm`. -/\nmeta def get_tsd_at_decl (decl_nm : name) : tactic tactic_state_data := do {\n  env \u2190 tactic.get_env,\n  decl \u2190 env.get decl_nm,\n  mk_tactic_state >>= tactic.write,\n  ts \u2190 tactic.read,\n  tactic.set_goal_to decl.type,\n  result \u2190 tactic_state_data.get,\n  tactic.write ts,\n  pure result\n}\n\nmeta def run_evaluation : EvaluationInput \u2192 tactic EvaluationResult :=\n\u03bb \u27e8decl, ts_data, tactic_string, ns\u27e9, (tactic.unsafe_run_io \u2218 io.run_tactic') $ do {\n  tac \u2190 parse_itactic tactic_string,\n  env \u2190 get_env_at_decl decl,\n  tactic.set_env_core env,\n  add_open_namespaces ns,\n  ts \u2190 rebuild_tactic_state ts_data *> tactic.read,\n  EvaluationResult.mk ts tactic_string <$> run_tac_with_tactic_state tac ts\n}\n\nsection greedy_proof_search\n\nmeta structure ModelAPI (input_format : Type := json) : Type :=\n(query : input_format \u2192 io json)\n\n/- for testing -/\nmeta def dummy_api {\u03b1} : ModelAPI \u03b1 :=\n\u27e8\u03bb _, pure $ json.of_string \"[DummyAPI] FAILURE\"\u27e9\n\nnamespace tactic\nopen interaction_monad interaction_monad.result\n\n/- capture but backtrack the state -/\nmeta def capture' {\u03b1} (t : tactic \u03b1) : tactic (tactic_result \u03b1) :=\n\u03bb s, match t s with\n| (success r s') := success (success r s') s\n| (exception f p s') := success (exception f p s') s\nend\n\nend tactic\n\nmeta def tactic_hash : tactic \u2115 := do {\n  gs \u2190 tactic.get_goals,\n  hs \u2190 gs.mmap $ \u03bb g, do {\n    tactic.set_goal_to g,\n    es \u2190 (::) <$> tactic.target <*> tactic.local_context,\n    pure $ es.foldl (\u03bb acc e, acc + e.hash) 0},\n  pure $ hs.sum\n}\n\nmeta def compare_tactic_state : tactic_state \u2192 tactic_state \u2192 tactic bool := \u03bb ts\u2081 ts\u2082, do {\n  ts \u2190 tactic.read,\n  h\u2081 \u2190 (tactic.write ts\u2081 *> tactic_hash),\n  h\u2082 \u2190 (tactic.write ts\u2082 *> tactic_hash),\n  tactic.write ts,\n  pure $ h\u2081 = h\u2082\n}\n    -- let done_handler : state_t GreedyProofSearchState tactic bool := do {\n    --   state_t.lift $ do {\n    --     tactic.done,\n    --     tactic.result >>= (\u03bb x, tactic.guard_sorry x <|>\n    --       eval_trace format! \"[greedy_proof_search_step] WARNING: result contains sorry\" *> tactic.failed),\n    --     tactic.result >>= (\u03bb x, tactic.type_check x <|>\n    --       eval_trace format! \"[greedy_proof_search_step] WARNING: result failed typechecking\" *> tactic.failed)\n    --   },\n\nmeta def validate_proof (pf : expr) : tactic unit := do {\n  let tac (e : expr) : tactic unit := do {\n    mk_tactic_state >>= tactic.write,\n    guard (bnot pf.has_meta_var),\n    tactic.guard_sorry e,\n    tactic.type_check e\n  },\n  result \u2190 tactic.capture' (tac pf),\n  match result with\n  | (interaction_monad.result.success r s') := pure ()\n  | (interaction_monad.result.exception f p s') := tactic.fail \"[validate_proof] ERROR: VALIDATION FAILED\"\n  end\n}\n\nmeta def tactic_state.is_done (state : tactic_state) : tactic bool := do {\n  ts \u2190 tactic.read,\n  result_flag \u2190 do {\n    tactic.write state,\n    (do {\n       tactic.done *> pure tt\n     }) <|> pure ff\n  },\n  tactic.write ts,\n  pure result_flag\n}\n\nmeta def tactic_result.is_done {\u03b1} (tr : tactic_result \u03b1) : tactic bool := do {\n  match tr with\n  | (interaction_monad.result.success val state) := state.is_done\n  | (interaction_monad.result.exception _ _ _) := pure ff\n  end\n}\n\nmeta def get_tac_and_capture_result (next_candidate : string) (timeout : \u2115 := 5000) : tactic (tactic_result unit) := do {\n  tac \u2190 do {\n    env \u2190 tactic.get_env,\n    eval_trace format!\"[get_tac_and_capture_result] PARSING TACTIC: {next_candidate}\",\n    tac \u2190 parse_itactic next_candidate,\n    eval_trace format!\"[get_tac_and_capture_result] PARSE SUCCESSFUL\",\n    tactic.set_env env,\n    pure tac\n  },\n  eval_trace format!\"[get_tac_and_capture_result] TRYING TACTIC: {next_candidate}\",\n  result \u2190 tactic.capture' (tactic.try_for_time timeout $ tactic.try_for 200000 tac), -- if `tac` fails, exception is captured here\n  eval_trace format!\"[get_tac_and_capture_result] RESULT: {result}\",\n\n  /- use tactic state hashing to fail on no-ops modulo permutation -/\n  result \u2190 match result with\n    | (interaction_monad.result.success val ts') := do {\n        ts \u2190 tactic.read,\n        mcond (compare_tactic_state ts ts')\n        (pure $ interaction_monad.mk_exception \"tactic state no-op\" none ts')\n        (pure result)\n      }\n    | exc := pure exc\n  end,\n  pure result\n}\n\nmeta def try_get_tac_and_capture_result (tac_string : string) (timeout : \u2115 := 5000) : tactic (tactic_result unit) := do {\n  get_tac_and_capture_result tac_string timeout <|> do {\n    let msg : format := format!\"[try_get_tac_and_capture_result] parse_itactic failed on {tac_string}\",\n    eval_trace msg,\n    interaction_monad.mk_exception msg none <$> tactic.read\n  }\n}\n\n-- caller of this function is responsible for inspecting results and stopping the search\nmeta def run_all_beam_candidates\n  (get_candidates : json \u2192 tactic (list (string \u00d7 native.float)))\n  (msg : json)\n  (tac_timeout : \u2115 := 5000)\n  : tactic (list (tactic_result unit \u00d7 string \u00d7 native.float) \u00d7 list string) := do {\n\n  let try_candidate_state := (list (string \u00d7 native.float) \u00d7 (list $ option $ tactic_result unit \u00d7 string \u00d7 native.float)),\n  let stop : option (tactic_result unit \u00d7 string \u00d7 native.float) \u2192 state_t try_candidate_state tactic bool :=\n    \u03bb arg, match arg with\n    | some \u27e8result, candidate\u27e9 := do {\n      state_t.lift result.is_done\n    }\n    | none := pure ff\n    end,\n\n  /- TODO(jesse): get rid of this state_t and just use `run_async <$> ...` instead -/\n  let try_candidate : state_t try_candidate_state tactic (option $ tactic_result unit \u00d7 string \u00d7 native.float) := do {\n    state_t.lift $ eval_trace format!\"[try_candidate] ENTERING\",\n    ts \u2190 state_t.lift tactic.read,\n    state_t.lift $ eval_trace format!\"[try_candidate] READ TACTIC STATE\",\n    \u27e8rest, _\u27e9 \u2190 state_t.get,\n    match rest with\n    | [] := do {\n      state_t.lift $ eval_trace format!\"[try_candidate] END OF LOOP\",\n      pure $ some \u27e8interaction_monad.fail \"all candidates failed\" ts, \"FAILURE\", 0.0\u27e9\n    }\n    | (next_candidate::candidates) := do  {\n      state_t.modify (\u03bb \u27e8_, rs\u27e9, \u27e8candidates, rs\u27e9),\n      result \u2190 monad_lift $ try_get_tac_and_capture_result next_candidate.fst tac_timeout,\n      when (interaction_monad.result.is_success $ result) $\n        state_t.modify $ \u03bb \u27e8candidates, rs\u27e9, \u27e8candidates, rs ++ [some $ \u27e8result, next_candidate\u27e9]\u27e9,\n      state_t.lift $ eval_trace format!\"[try_candidate] CAPTURED RESULT: {result}\",\n      pure $ some \u27e8result, next_candidate\u27e9\n    }\n    end\n  },\n\n  -- let find_successful_candidates\n  --   (candidates : list (string \u00d7 native.float))\n  --   : tactic (list (tactic_result unit \u00d7 string \u00d7 native.float)) := do {\n  --   tasks \u2190 candidates.mmap (\u03bb arg, flip prod.mk arg <$> tactic.run_async (try_get_tac_and_capture_result arg.fst : tactic $ tactic_result unit)),\n  --   tactic.using_new_ref ff $ \u03bb flag, do \n  --   tasks.iterM [] $ \u03bb acc \u27e8task, tac_string, score\u27e9, do {\n  --     mcond (tactic.read_ref flag) (pure acc) $ do {\n  --       let result := task.get,\n  --       if (interaction_monad.result.is_success result) then do {\n  --         whenM (result.is_done) $ tactic.write_ref flag tt,\n  --         pure $ acc ++ [\u27e8result, tac_string, score\u27e9]\n  --       } else do {\n  --         pure acc\n  --       }\n  --     }\n  --   }\n  -- },\n\n  -- this is responsible for gracefully handling \"error\" JSON messages and should return an empty list of candidates\n  unwrapped_candidates \u2190 get_candidates msg,\n  -- eval_trace format!\"[run_all_beam_candidates] UNWRAPPED CANDIDATES: {unwrapped_candidates}\",\n  dedup_unwrapped_candidates \u2190 list.dedup' unwrapped_candidates,\n  eval_trace format!\"[run_all_beam_candidates] DEDUP_UNWRAPPED CANDIDATES: {dedup_unwrapped_candidates}\",\n  let candidates := list.filter (\u03bb x, \u00ac \"tidy\".is_prefix_of (prod.fst x)) dedup_unwrapped_candidates,\n  \n  eval_trace format!\"[run_all_beam_candidates] CANDIDATES: {candidates}\",\n  -- old failure callback\n  -- let failure_callback := do {\n  -- -- do ts \u2190 state_t.lift tactic.read, pure \u27e8interaction_monad.fail \"all candidates failed\" ts, \"FAILURE\", 0.0\u27e9\n  -- }\n  -- \n  successful_candidates \u2190 (prod.snd <$> prod.snd <$> state_t.run (iterate_until try_candidate stop candidates.length $ pure none) \u27e8candidates, []\u27e9),\n  -- successful_candidates \u2190 find_successful_candidates candidates,\n  eval_trace format!\"[run_all_beam_candidates] EXITING TRY_CANDIDATE LOOP\",\n  eval_trace format!\"[run_all_beam_candidates] SUCCESSFUL CANDIDATES: {successful_candidates}\",\n  pure \u27e8successful_candidates.filter_map id, prod.fst <$> candidates\u27e9\n}\n\nmeta def run_best_beam_candidate\n  (get_candidates : json \u2192 tactic (list string))\n  (msg : json)\n  (tac_timeout : \u2115 := 5000)\n  : tactic (tactic_result unit \u00d7 string \u00d7 list string) := do {\n  let try_candidates : state_t (list string) tactic ((tactic_result unit) \u00d7 string) := do {\n      ts \u2190 state_t.lift (tactic.read),\n      (next_candidate::candidates) \u2190 state_t.get | pure (interaction_monad.fail \"all candidates failed\" ts, \"FAILURE\"),\n      state_t.modify (\u03bb _, candidates),\n      flip prod.mk next_candidate <$> (state_t.lift $ try_get_tac_and_capture_result next_candidate tac_timeout)\n\n      -- let get_tac_and_capture_result : state_t (list string) tactic ((tactic_result unit) \u00d7 string) := do {\n      -- tac \u2190 state_t.lift $ do {\n      --     env \u2190 tactic.get_env,\n      --     eval_trace format!\"[run_best_beam_candidate] PARSING TACTIC: {next_candidate}\",\n      --     tac \u2190 parse_itactic next_candidate, -- this is the only possible point of program failure\n      --     eval_trace format!\"[run_best_beam_candidate] PARSE SUCCESSFUL\",\n      --     tactic.set_env env,\n      --     pure tac\n      --   },\n      --   state_t.lift $ do\n      --     eval_trace format!\"[run_best_beam_candidate] TRYING TACTIC: {next_candidate}\",\n      --     result \u2190 tactic.capture' (tactic.try_for 200000 tac), -- if `tac` fails, exception is captured here\n      --     eval_trace format!\"[run_best_beam_candidate] RESULT: {result}\",\n\n      --     result \u2190 match result with\n      --     | (interaction_monad.result.success val ts') := do {\n      --       ts \u2190 tactic.read,\n      --       -- ite ((format.to_string $ has_to_format.to_format ts) = (format.to_string $ has_to_format.to_format ts'))\n      --       mcond (compare_tactic_state ts ts')\n      --        (pure $ interaction_monad.mk_exception \"tactic state no-op\" none ts')\n      --        (pure result)\n      --     }\n      --     | exc := pure exc\n      --     end,\n      --     pure \u27e8result, next_candidate\u27e9\n      -- },\n      -- get_tac_and_capture_result <|> -- handle `parse_itactic` failure here\n      --   let msg : format := format!\"[run_best_beam_candidate.try_candidates] parse_itactic failed on {next_candidate}\" in do\n      --   state_t.lift (eval_trace msg),\n      --   (pure \u27e8interaction_monad.mk_exception\n      --     msg none ts, next_candidate\u27e9)\n  },\n  let stop : tactic_result unit \u00d7 string \u2192 state_t (list string) tactic bool :=\n    pure \u2218 interaction_monad.result.is_success \u2218 prod.fst,\n  candidates \u2190 list.filter (\u03bb x, \u00ac \"tidy\".is_prefix_of x) <$> (get_candidates msg >>= list.dedup),\n  eval_trace format!\"[run_best_beam_candidate] CANDIDATES: {candidates}\",\n  try_candidates_result@\u27e8result, tac_string\u27e9 \u2190 ((prod.fst <$> state_t.run (iterate_until try_candidates stop) candidates) <|>\n  do {\n       old_state \u2190 tactic.read,\n       pure (prod.mk (interaction_monad.mk_exception \"all candidates failed\" none old_state) \"all failed\")\n  }),\n  eval_trace format!\"[run_best_beam_candidate] TRY_CANDIDATES_RESULT: {try_candidates_result}\",\n  pure \u27e8result, tac_string, candidates\u27e9\n}\n\n-- TODO(jesse): finalize JSON format for serialize_ts/decode_response protocol\nmeta structure GreedyProofSearchState : Type :=\n(depth : \u2115 := 0)\n(tactics : list string := [])\n(predictions : list (list string) := [])\n(states : list tactic_state := []) -- TODO(jesse): this might make the logs extremely verbose\n(success : bool := ff)\n(all_failed : bool := ff)\n(task_id : string := \"\")\n(global_timeout : bool := ff)\n(tac_timeout : \u2115 := 5)\n(fuel_exhausted : bool := ff)\n(decl_goal : string := \"\")\n\nattribute [derive has_to_format] GreedyProofSearchState\n\nmeta instance : has_mark_global_timeout GreedyProofSearchState :=\n\u27e8\u03bb \u03c3, {global_timeout := tt, ..\u03c3}\u27e9\n\nmeta instance : has_register_task_id GreedyProofSearchState :=\n\u27e8\u03bb \u03c3 task, {task_id := task, ..\u03c3}\u27e9\n\nmeta instance : has_set_tac_timeout GreedyProofSearchState :=\n\u27e8\u03bb \u03c3 timeout, {tac_timeout := timeout, ..\u03c3}\u27e9\n\nmeta instance : has_get_tac_timeout GreedyProofSearchState :=\n\u27e8GreedyProofSearchState.tac_timeout\u27e9\n\nmeta instance : has_mark_fuel_exhausted GreedyProofSearchState :=\n\u27e8\u03bb \u03c3, {fuel_exhausted := tt, ..\u03c3}\u27e9\n\nmeta instance : has_register_decl_goal GreedyProofSearchState :=\n\u27e8\u03bb \u03c3 decl_goal, {decl_goal := decl_goal, ..\u03c3}\u27e9\n\nmeta def serialize_list_string : list string \u2192 json := \u03bb xs,\n  json.array $ json.of_string <$> xs\n\n-- we supply our own instance since the default derive handler is too verbose\nmeta instance : has_to_tactic_json GreedyProofSearchState :=\nlet fn : GreedyProofSearchState \u2192 tactic json := \u03bb \u03c3, do {\n  (serialized_states : list string) \u2190 do {\n    \u03c3.states.mmap postprocess_tactic_state\n  },\n  pure $ json.object $\n  [\n      (\"depth\", json.of_int \u03c3.depth)\n    , (\"tactics\", serialize_list_string \u03c3.tactics)\n    , (\"predictions\", json.array $ serialize_list_string <$> \u03c3.predictions)\n    -- store only pretty-printed tactic states for now, with newlines replaced by tabs\n    , (\"states\", json.array $ json.of_string <$> serialized_states)\n    , (\"success\", json.of_bool \u03c3.success)\n    , (\"all_failed\", json.of_bool \u03c3.all_failed)\n    , (\"task_id\", json.of_string \u03c3.task_id)\n    , (\"global_timeout\", json.of_bool \u03c3.global_timeout)\n    , (\"fuel_exhausted\", json.of_bool \u03c3.fuel_exhausted)\n    , (\"decl_goal\", json.of_string \u03c3.decl_goal)\n  ]\n} in \u27e8fn\u27e9\n\nnamespace GreedyProofSearchState\n\nmeta def add_tac : GreedyProofSearchState \u2192 string \u2192  GreedyProofSearchState :=\n\u03bb \u03c3 tac, {tactics := \u03c3.tactics ++ [tac], ..\u03c3}\n\nmeta def bump_depth : GreedyProofSearchState \u2192 GreedyProofSearchState :=\n\u03bb \u03c3, {depth := nat.succ \u03c3.depth, ..\u03c3}\n\nmeta def add_prediction : GreedyProofSearchState \u2192 list string \u2192 GreedyProofSearchState :=\n\u03bb \u03c3 pred, {predictions := \u03c3.predictions ++ [pred], ..\u03c3}\n\nmeta def add_state : GreedyProofSearchState \u2192 tactic_state \u2192 GreedyProofSearchState :=\n\u03bb \u03c3 ts, {states := \u03c3.states ++ [ts], ..\u03c3}\n\nmeta def mark_all_failed : GreedyProofSearchState \u2192 GreedyProofSearchState :=\n\u03bb \u03c3, {all_failed := tt, ..\u03c3}\n\nend GreedyProofSearchState\n\nmeta def greedy_proof_search_step\n  {input_format : Type}\n  (api : ModelAPI input_format)\n  (serialize_ts : tactic_state \u2192 tactic input_format)\n   -- note(jesse): this is responsible for e.g. selecting a candidate from the beam\n  (decode_response : json \u2192 \u2115 \u2192 tactic (tactic_result unit \u00d7 string \u00d7 list string))\n  : state_t GreedyProofSearchState tactic (bool \u00d7 GreedyProofSearchState) := do {\n  state_t.lift $ eval_trace \"[greedy_proof_search_step] ENTERING\",\n  let handle_response (response : tactic_result unit \u00d7 string \u00d7 list string) : state_t GreedyProofSearchState tactic unit :=\n     match response with | response@\u27e8result, tac_string, candidates\u27e9 :=  do {\n       if not result.is_success\n       then do {\n         -- let msg := format!\"[greedy_proof_search_step.handle_response] UNEXPECTED\n         --   interaction_monad.result.exception: {result}\",\n         -- eval_trace msg *> tactic.fail msg\n         modify $ \u03bb \u03c3, \u03c3.mark_all_failed,\n         old_state \u2190 state_t.lift $ tactic.read,\n         modify $ \u03bb \u03c3, \u03c3.add_state old_state,\n         modify $ \u03bb \u03c3, \u03c3.add_prediction candidates\n       }\n       else do {\n         (interaction_monad.result.success _ ts) \u2190 pure result,\n         -- state_t.lift $ tactic.unsafe_run_io $ io.run_tactic' $ _\n         modify $ \u03bb \u03c3, \u03c3.bump_depth,\n         modify $ \u03bb \u03c3, \u03c3.add_tac tac_string,\n         modify $ \u03bb \u03c3, \u03c3.add_prediction candidates,\n         old_state \u2190 state_t.lift $ tactic.read,\n         modify $ \u03bb \u03c3, \u03c3.add_state old_state\n       }\n     }\n     end,\n\n  let get_response_and_resume : state_t GreedyProofSearchState tactic bool := do {\n    tac_timeout_seconds \u2190 GreedyProofSearchState.tac_timeout <$> get,\n    response@\u27e8result, tac_string, candidates\u27e9 \u2190 state_t.lift $ do {\n      ts_msg \u2190 tactic.read >>= serialize_ts,\n      eval_trace \"[greedy_proof_search_step] QUERYING API\",\n      response_msg \u2190 tactic.unsafe_run_io $ api.query ts_msg,\n      eval_trace format!\"[greedy_proof_search_step] RESPONSE MSG {response_msg}\",\n      eval_trace format!\"[greedy_proof_search_step] RUNNING DECODE RESPONSE WITH TIMEOUT {tac_timeout_seconds*1000}\",\n      response \u2190 decode_response response_msg $ tac_timeout_seconds*1000,\n      pure response\n    },\n    state_t.lift $ eval_trace \"[greedy_proof_search_step] HANDLING RESPONSE\",\n    handle_response response,\n    state_t.lift $ eval_trace \"[greedy_proof_search_step] HANDLED RESPONSE\",\n    state_t.lift $ do {\n      eval_trace format!\"DECODED RESPONSE: {result}\",\n      when result.is_success $ tactic.resume result,\n      eval_trace format!\"RESUMED\"\n    },\n\n    let done_handler : state_t GreedyProofSearchState tactic bool := do {\n      state_t.lift $ do {\n        tactic.done,\n        tactic.result >>= (\u03bb x, tactic.guard_sorry x <|>\n          eval_trace format! \"[greedy_proof_search_step] WARNING: result contains sorry\" *> tactic.failed),\n        tactic.result >>= (\u03bb x, tactic.type_check x <|>\n          eval_trace format! \"[greedy_proof_search_step] WARNING: result failed typechecking\" *> tactic.failed)\n      },\n      modify $ \u03bb \u03c3, {success := tt, ..\u03c3},\n      pure tt\n    } <|> pure ff,\n\n    let tactic_exception_handler : state_t GreedyProofSearchState tactic bool := do {\n      pure (bnot result.is_success)\n    },\n\n    done_flag \u2190 done_handler,\n    exception_flag \u2190 tactic_exception_handler,\n    pure (done_flag || exception_flag)\n\n  },\n\n  done_flag \u2190 get_response_and_resume,\n\n  -- let done_handler : state_t GreedyProofSearchState tactic bool := do {\n  --   state_t.lift done,\n  --   modify $ \u03bb \u03c3, {success := tt, ..\u03c3},\n  --   pure tt\n  -- },\n\n  -- done_flag \u2190 done_handler <|> pure ff,\n\n  state_t.lift $ eval_trace format! \"DONE FLAG: {done_flag}\",\n\n  -- pure \u27e8done_flag\u27e9\n  prod.mk done_flag <$> get  /- in second branch, no predictions succeeded and the proof search halts early -/\n}\n\n/- TODO(jesse): record proof search state + search statistics; wrap this in a state_t -/\n/- `decode_response` should not modify the tactic state and currently\n    should only return successful `tactic_result`s -/\n/-\n   in the full BFS case, `decode_response` should return a list of\n   `tactic_result unit`s, which may be ```success` or `exception`\n   these should then be logged by the `handle_response` function in\n   `greedy_proof_search_step`, and the successful applications\n   should be added to the search queue.\n-/\nmeta def greedy_proof_search_core\n  {input_format : Type}\n  (api : ModelAPI input_format)\n  (serialize_ts : tactic_state \u2192 tactic input_format)\n  (decode_response : json \u2192 \u2115 \u2192 tactic (tactic_result unit \u00d7 string \u00d7 list string))\n  (fuel := 100000)\n  : state_t GreedyProofSearchState tactic unit :=\n  let fuel_exhausted_callback : state_t GreedyProofSearchState tactic (bool \u00d7 GreedyProofSearchState) := do {\n    state_t.modify has_mark_fuel_exhausted.mark_fuel_exhausted,\n    prod.mk ff <$> get\n  } in\n  iterate_until\n    (greedy_proof_search_step api serialize_ts decode_response)\n      (\u03bb x, pure $ x.fst = tt)\n        fuel\n          fuel_exhausted_callback *> pure ()\n\nmeta def greedy_proof_search\n  {input_format : Type}\n  (api : ModelAPI input_format)\n  (serialize_ts : tactic_state \u2192 tactic input_format)\n  (decode_response : json \u2192 \u2115 \u2192 tactic (tactic_result unit \u00d7 string \u00d7 list string))\n  (fuel := 100000)\n  (verbose := ff)\n  : tactic unit := do {\n  \u27e8_, \u03c3\u27e9 \u2190 state_t.run (greedy_proof_search_core api serialize_ts decode_response fuel) {},\n  when verbose $ eval_trace \u03c3\n}\n\nend greedy_proof_search\n\n\nsection bfs\n\nmeta structure BFSNode : Type :=\n(state : tactic_state)\n(score : \u2124 := 0)\n(tactics : list string := [])\n(depth : \u2115 := 0)\n\nattribute [derive has_to_format] BFSNode\n\nnamespace BFSNode\n\nmeta def of_current_state (score : \u2124 := 0) (tacs : list string := []) : tactic BFSNode := do {\n  ts \u2190 tactic.read,\n  pure $ \u27e8ts, score, tacs, 0\u27e9\n}\n\nend BFSNode\n\nmeta structure BFSState : Type :=\n(depth : \u2115 := 0)\n(num_queries : \u2115 := 0)\n(tactics : list string := [])\n(predictions : list (list string) := [])\n(states : list tactic_state := []) -- TODO(jesse): this might make the logs extremely verbose\n(success : bool := ff)\n(all_failed : bool := ff)\n(task_id : string := \"\")\n(max_width : \u2115 := 25) -- max qsize\n(max_depth : \u2115 := 50)\n(nodes : pqueue BFSNode.score := pqueue.empty)\n(api_failure_count : \u2115 := 0)\n(all_failed_count : \u2115 := 0)\n(global_timeout : bool := ff)\n(tac_timeout : \u2115 := 5)\n(fuel_exhausted : bool := ff)\n(decl_goal : string := \"\")\n\nattribute [derive has_to_format] BFSState\n\nmeta instance : has_mark_global_timeout BFSState :=\n\u27e8\u03bb \u03c3, {global_timeout := tt, ..\u03c3}\u27e9\n\nmeta instance : has_register_task_id BFSState :=\n\u27e8\u03bb \u03c3 task, {task_id := task, ..\u03c3}\u27e9\n\nmeta instance : has_set_tac_timeout BFSState :=\n\u27e8\u03bb \u03c3 timeout, {tac_timeout := timeout, ..\u03c3}\u27e9\n\nmeta instance : has_mark_fuel_exhausted BFSState :=\n\u27e8\u03bb \u03c3, {fuel_exhausted := tt, ..\u03c3}\u27e9\n\nmeta instance : has_get_tac_timeout BFSState :=\n\u27e8BFSState.tac_timeout\u27e9\n\nmeta instance : has_register_decl_goal BFSState :=\n\u27e8\u03bb \u03c3 decl_goal, {decl_goal := decl_goal, ..\u03c3}\u27e9\n\n-- meta instance : has_to_tactic_json GreedyProofSearchState :=\n-- let fn : GreedyProofSearchState \u2192 tactic json := \u03bb \u03c3, do {\n--   let serialize_list_string : list string \u2192 json := \u03bb xs,\n--     json.array $ json.of_string <$> xs,\n--   (serialized_states : list string) \u2190 do {\n--     \u03c3.states.mmap postprocess_tactic_state\n--   },\n--   pure $ json.object $\n--   [\n--       (\"depth\", json.of_int \u03c3.depth)\n--     , (\"tactics\", serialize_list_string \u03c3.tactics)\n--     , (\"predictions\", json.array $ serialize_list_string <$> \u03c3.predictions)\n--     -- store only pretty-printed tactic states for now, with newlines replaced by tabs\n--     , (\"states\", json.array $ json.of_string <$> serialized_states)\n--     , (\"success\", json.of_bool \u03c3.success)\n--     , (\"all_failed\", json.of_bool \u03c3.all_failed)\n--     , (\"task_id\", json.of_string \u03c3.task_id)\n--   ]\n-- } in \u27e8fn\u27e9\n\n-- TODO(jesse): upgrade to full instance\nmeta instance : has_to_tactic_json BFSState :=\nlet fn : BFSState \u2192 tactic json := \u03bb \u03c3, do {\n  (serialized_states : list string) \u2190 do {\n    \u03c3.states.mmap $ \u03bb x, tactic.with_full_names $ postprocess_tactic_state x\n  },\n  pure $ json.object\n  [\n      (\"depth\", json.of_int (\u03c3.depth))\n    , (\"tactics\", json.array $ (json.of_string <$> \u03c3.tactics))\n    -- , (\"predictions\", json.array $ serialize_list_string <$> \u03c3.predictions)\n    , (\"states\", json.array $ json.of_string <$> serialized_states)\n    , (\"success\", json.of_bool (\u03c3.success))\n    , (\"num_queries\", json.of_int (\u03c3.num_queries))\n    , (\"task_id\", json.of_string $ \u03c3.task_id)\n    , (\"api_failure_count\", json.of_int $ \u03c3.api_failure_count)\n    , (\"all_failed_count\", json.of_int $ \u03c3.all_failed_count)\n    , (\"global_timeout\", json.of_bool (\u03c3.global_timeout))\n    , (\"fuel_exhausted\", json.of_bool \u03c3.fuel_exhausted)\n    , (\"decl_goal\", json.of_string \u03c3.decl_goal)\n  ]\n}\nin \u27e8fn\u27e9\n\nsection BFSState\nnamespace BFSState\n\nmeta def register_task_id : BFSState \u2192 string \u2192 BFSState :=\n \u03bb \u03c3 task_id, {task_id := task_id, ..\u03c3}\n\nmeta def bump_num_queries : BFSState \u2192 BFSState :=\n\u03bb \u03c3, {num_queries := nat.succ \u03c3.num_queries, ..\u03c3}\n\nmeta def push_nodes : BFSState \u2192 list BFSNode \u2192 BFSState :=\n\u03bb \u03c3 nodes, {nodes := \u03c3.nodes.enqueue_many nodes, ..\u03c3}\n\nmeta def push_node : BFSState \u2192 BFSNode \u2192 BFSState := \u03bb S \u03c3, S.push_nodes [\u03c3]\n\nmeta def add_tac : BFSState \u2192 string \u2192 BFSState :=\n\u03bb \u03c3 tac, {tactics := \u03c3.tactics ++ [tac], ..\u03c3}\n\nmeta def add_tacs : BFSState \u2192 list string \u2192 BFSState :=\n\u03bb \u03c3 tacs, {tactics := \u03c3.tactics ++ tacs, ..\u03c3}\n\nmeta def bump_depth : BFSState \u2192 BFSState :=\n-- \u03bb \u27e8d, tacs, preds\u27e9, \u27e8nat.succ d, tacs, preds\u27e9\n\u03bb \u03c3, {depth := nat.succ \u03c3.depth, ..\u03c3}\n\nmeta def add_prediction : BFSState \u2192 list string \u2192 BFSState :=\n-- \u03bb \u27e8d, tacs, preds\u27e9 pred, \u27e8d, tacs, preds ++ [pred]\u27e9\n\u03bb \u03c3 pred, {predictions := \u03c3.predictions ++ [pred], ..\u03c3}\n\nmeta def add_state : BFSState \u2192 tactic_state \u2192 BFSState :=\n\u03bb \u03c3 ts, {states := \u03c3.states ++ [ts], ..\u03c3}\n\nmeta def mark_all_failed : BFSState \u2192 BFSState :=\n\u03bb \u03c3, {all_failed := tt, ..\u03c3}\n\nmeta def mark_success : BFSState \u2192 BFSState :=\n\u03bb \u03c3, {success := tt, ..\u03c3}\n\nmeta def of_current_state (score : \u2124 := 0) (max_width : \u2115 := 25) (max_depth : \u2115 := 50) (tac_timeout : \u2115 := 5000) : tactic BFSState := do {\n  init_node \u2190 BFSNode.of_current_state score,\n  pure {nodes := pqueue.empty.enqueue init_node, max_width := max_width, max_depth := max_depth, tac_timeout := tac_timeout}\n}\n\nmeta def bump_api_failure_count : BFSState \u2192 BFSState :=\n\u03bb \u03c3, {api_failure_count := \u03c3.api_failure_count + 1, ..\u03c3}\n\nmeta def bump_all_failed_count : BFSState \u2192 BFSState :=\n\u03bb \u03c3, {all_failed_count := \u03c3.all_failed_count + 1, ..\u03c3}\n\nend BFSState\nend BFSState\n\nmeta def score_of_float : native.float \u2192 int :=\n\u03bb x, native.float.floor ((1000.0 : native.float) * x)\n\nmeta def pop_node : state_t BFSState tactic BFSNode := do {\n  tss \u2190 BFSState.nodes <$> get,\n  match tss.dequeue with\n  | (some (next, new_nodes)) := do {\n      modify $ \u03bb S, {nodes := new_nodes, ..S},\n      pure next\n    }\n  | none := state_t.lift \u2218 tactic.fail $ format!\"[pop_node] pqueue empty\"\n  end\n}\n\n/-\n  Each step of BFS does the following:\n    - pops a node off the queue\n    - expands the node, producing a list of descendant nodes\n    - if any descendant node represents a completed proof search,\n      extract the result and use it to fill the main goal\n      - this is accomplished by setting the tactic state\n-/\n\nmeta def bfs_step\n  {input_format : Type}\n  (api : ModelAPI input_format)\n  (serialize_ts : tactic_state \u2192 tactic input_format)\n   -- note(jesse): this is responsible for e.g. selecting a candidate from the beam\n  (decode_response : json \u2192 \u2115 \u2192 tactic (list (tactic_result unit \u00d7 string \u00d7 native.float) \u00d7 list string))\n  : state_t BFSState tactic (bool \u00d7 BFSState) := do {\n  \u03c3 \u2190 get,\n  state_t.lift $ eval_trace format!\"[bfs_step] ENTERING, QUEUE STATE: {\u03c3.nodes}\",\n\n  (some next_node) \u2190 (some <$> pop_node <|> pure none) | (state_t.lift $ eval_trace format!\"[bfs_step] queue empty\") *> pure \u27e8tt, \u03c3\u27e9, -- yikes\n\n  ts \u2190 state_t.lift $ tactic.read,\n\n  state_t.lift $ tactic.write next_node.state,\n\n  let handle_response\n    (response : list (tactic_result unit \u00d7 string \u00d7 native.float) \u00d7 (list string))\n    : state_t BFSState tactic unit :=\n     match response with | response@\u27e8successes, candidates\u27e9 :=  do {\n       modify $ \u03bb \u03c3, \u03c3.add_prediction candidates,\n       modify $ \u03bb \u03c3, \u03c3.bump_num_queries,\n       when (successes.length = 0) $ modify $ \u03bb \u03c3, \u03c3.bump_all_failed_count,\n       when (candidates.length = 0) $ modify $ \u03bb \u03c3, \u03c3.bump_api_failure_count\n       -- successes.mmap' $ \u03bb \u27e8result, tac_string, score\u27e9, do {\n       --   pure ()\n       -- }\n     }\n     end,\n\n  let get_response_and_resume : state_t BFSState tactic bool := do {\n    -- TODO(jesse): `successes` needs to be generalized from `string` to an arbitrary datatype `\u03b1`\n    -- for the best-first case. for now, we just score everything 0 to get this working\n    tac_timeout_seconds \u2190 BFSState.tac_timeout <$> get,\n    decl_nm \u2190 BFSState.task_id <$> get,\n    response@\u27e8successes, candidates\u27e9 \u2190 state_t.lift $ do {\n      ts_msg \u2190 tactic.read >>= serialize_ts,\n      eval_trace \"[bfs_step] QUERYING API\",\n      response_msg \u2190 tactic.unsafe_run_io $ api.query ts_msg,\n      eval_trace format!\"[bfs_step] RESPONSE MSG {response_msg}\",\n      eval_trace format!\"[bfs_step] RUNNING DECODE RESPONSE WITH TAC_TIMEOUT {tac_timeout_seconds * 1000}\",\n      \n      do {env \u2190 tactic.get_env, d \u2190 env.get decl_nm, tactic.trace format! \"[run_proof_search_step] WARNING: GOT DECL {decl_nm}\"} <|> do {tactic.trace format! \"[run_proof_search_step] NO GOT DECL {decl_nm}\"},\n      decoded_response@\u27e8successes, _\u27e9 \u2190 decode_response response_msg $ tac_timeout_seconds * 1000,\n      eval_trace $ format!\"[bfs_step] SUCCESSFUL CANDIDATES: {successes}\",\n      pure decoded_response\n    },\n    handle_response response,\n\n    -- turn the successes into a list of new BFSNodes\n    (new_nodes : list BFSNode) \u2190 successes.mmap (\u03bb \u27e8tr, tac, score\u27e9, match tr with\n      | (interaction_monad.result.success _ state) := do {\n        -- assumes that higher float score is better\n        let scale_factor := (-100000.0 : native.float),\n        let int_score : int := native.float.floor $ (score * scale_factor) + next_node.score,\n        pure $ BFSNode.mk state int_score (next_node.tactics ++ [tac]) (next_node.depth + 1)\n      }\n      | exc := state_t.lift (tactic.fail format!\"[bfs_step] UNEXPECTED TACTIC RESULT WHEN CONVERTING TO new_nodes: {exc}\")\n      end\n    ),\n\n    monad_lift $ eval_trace format! \"[bfs_step] NODES BEFORE SORTING: {new_nodes}\",\n\n    let new_nodes : list BFSNode := @list.merge_sort _ (\u03bb x y : BFSNode, x.score < y.score) _ new_nodes,\n\n    monad_lift $ eval_trace format! \"[bfs_step] NODES AFTER SORTING: {new_nodes}\",\n\n    /- loop through the new nodes. if any of them are finished (no open goals),\n       the proof search is done. otherwise, we add all of them to the BFSState pqueue\n       and continue the search.\n    -/\n\n    -- modify (\u03bb \u03c3, \u03c3.push_nodes new_nodes),\n\n    -- for_ new_nodes $ \u03bb \u27e8state, score\u27e9, do {\n\n    -- }\n    let BFSM := state_t BFSState tactic,\n    let push_node_state := (list BFSNode),\n\n    /- note(jesse): this version of `push_node_state_tac` does not quite replicate\n      the behavior of greedy_proof_search at\n      max_width := 1, because it will loop over all the successful candidates anyways and check\n      if the proof is finished regardless of the state of the queue\n    -/\n\n    -- let push_node_state_tac : state_t push_node_state BFSM (option BFSNode) := do {\n    --   (next_node::xs) \u2190 get | pure none,\n    --   done_flag \u2190 state_t.lift $ state_t.lift $ next_node.state.is_done,\n\n    --   result \u2190 if done_flag then pure (some next_node) else do {\n    --     q \u2190 BFSState.nodes <$> state_t.lift get,\n    --     let qsize := q.size,\n    --     state_t.lift $ state_t.lift $ eval_trace format!\"[push_tac] QSIZE: {qsize}\",\n    --     state_t.lift $ state_t.lift $ eval_trace format!\"[push_tac] QUEUE: {q}\",\n    --     size_exceeded \u2190 (do \u03c3 \u2190 state_t.lift get,\n    --       pure $ to_bool $ (\u03c3.max_width <= \u03c3.nodes.size \u2228 \u03c3.max_depth < next_node.tactics.length)),\n\n    --     -- TODO(jesse): more informative trace message\n    --     -- TODO(jesse): currently we are erasing open tactic_states which exceed the depth limit.\n    --     -- consider storing them in a pqueue of \"frozen\" nodes instead, and display them in the trace\n    --     when size_exceeded $ monad_lift $ eval_trace format!\"[push_tac] SIZE EXCEEDED\",\n    --     unless size_exceeded $ do {\n    --       state_t.lift $ state_t.lift $ eval_trace format!\"[push_tac] PUSHING NODE\",\n    --       state_t.lift $ state_t.modify (\u03bb \u03c3, \u03c3.push_node next_node)\n    --     },\n    --     pure none\n    --   },\n    --   state_t.modify (\u03bb _, xs),\n    --   pure result\n    -- },\n\n    /- \n      note(jesse): this version of `push_node_state_tac` checks that the queue is OK\n      before proceeding with the rest of the loop\n      currently, if max_width := 0 (this is an off-by-one misnomer), this\n      reproduces the logic of greedy_proof_search.\n    -/\n    let push_node_state_tac : state_t push_node_state BFSM (option BFSNode) := do {\n      limits_exceeded \u2190 do {\n        \u03c3 \u2190 state_t.lift get,\n        pure $ to_bool $ (\u03c3.max_width < \u03c3.nodes.size \u2228 \u03c3.max_depth < next_node.tactics.length)\n      },\n      \n     if limits_exceeded then do {\n       monad_lift $ eval_trace format!\"[push_tac] SIZE EXCEEDED\",\n       pure none\n     } else do {\n       (next_node::xs) \u2190 get | pure none,\n       done_flag \u2190 monad_lift $ next_node.state.is_done,\n       if done_flag then pure (some next_node) else do {\n         q \u2190 BFSState.nodes <$> state_t.lift get,\n         let qsize := q.size,\n         -- monad_lift $ eval_trace format!\"[push_tac] QSIZE: {qsize}\",\n         -- monad_lift $ eval_trace format!\"[push_tac] QUEUE: {q}\",\n         -- monad_lift $ eval_trace format!\"[push_tac] PUSHING NODE\",\n         state_t.lift $ do {\n           state_t.modify (\u03bb \u03c3 : BFSState, \u03c3.push_node next_node),\n           state_t.modify $ \u03bb \u03c3,\n             if \u03c3.depth < next_node.depth then {depth := next_node.depth, ..\u03c3} else \u03c3\n\n           /- note(jesse, January 22 2021, 01:08 AM) temporarily disabling for faster evals -/\n           -- state_t.modify $ \u03bb \u03c3, \u03c3.add_state next_node.state -- TODO(jesse): store previous states per-node, not globally\n         },\n         state_t.modify (\u03bb _, xs),\n         pure none\n       }\n     }\n    },\n\n    (done_node) \u2190 prod.fst <$>\n      state_t.run\n        (iterate_until\n          push_node_state_tac\n            (pure \u2218 option.is_some)\n              (new_nodes.length) (pure none)) new_nodes,\n\n    match done_node with\n    | (some node) := do {\n      state_t.lift $ tactic.write node.state,\n      state_t.modify (\u03bb \u03c3, \u03c3.mark_success),\n      state_t.modify (\u03bb \u03c3, \u03c3.add_tacs node.tactics),\n      pure tt\n    }\n    | none := pure ff\n    end\n  },\n  done_flag \u2190 get_response_and_resume,\n  state_t.lift $ eval_trace format! \"DONE FLAG: {done_flag}\",\n\n  -- if we are done, then the state has already been set to the successful one\n  -- otherwise, backtrack to the original state\n  unlessM (pure done_flag) $ state_t.lift (tactic.write ts),\n  prod.mk done_flag <$> get\n}\n\nmeta def bfs_core\n  {input_format : Type}\n  (api : ModelAPI input_format)\n  (serialize_ts : tactic_state \u2192 tactic input_format)\n  (decode_response : json \u2192 \u2115 \u2192 tactic (list (tactic_result unit \u00d7 string \u00d7 native.float) \u00d7 list string))\n  (fuel := 100000)\n  : state_t BFSState tactic unit :=\n  let fuel_exhausted_callback : state_t BFSState tactic (bool \u00d7 BFSState) := do {\n    state_t.modify has_mark_fuel_exhausted.mark_fuel_exhausted,\n    prod.mk ff <$> get\n  } in do {\n    ts\u2080 \u2190 monad_lift $ tactic.read,\n    [g] \u2190 monad_lift $ tactic.get_goals,\n    iterate_until\n      (bfs_step api serialize_ts decode_response)\n        (\u03bb x, pure $ x.fst = tt)\n          fuel\n            fuel_exhausted_callback *> pure (),\n    \u03c3 \u2190 get,\n    when \u03c3.success $\n    do {pf \u2190 monad_lift $ tactic.get_assignment g >>= tactic.instantiate_mvars,\n    (monad_lift (do {-- tactic.set_goals [g], \n    pf \u2190 tactic.get_assignment g >>= tactic.instantiate_mvars,\n    tgt \u2190 tactic.infer_type pf,\n    ts\u2081 \u2190 tactic.read,\n    tactic.write ts\u2080, -- important to backtrack to the old state for validation\n    validate_proof pf,\n    tactic.write ts\u2081\n    }) <|>\n      (do monad_lift (eval_trace \"[bfs_core] WARNING: VALIDATE_PROOF FAILED\"),\n       modify $ \u03bb \u03c3, {success := ff, ..\u03c3}))\n    }\n  }\n\nmeta def bfs\n  {input_format : Type}\n  (api : ModelAPI input_format)\n  (serialize_ts : tactic_state \u2192 tactic input_format)\n  (decode_response : json \u2192 \u2115 \u2192 tactic (list (tactic_result unit \u00d7 string \u00d7 native.float) \u00d7 list string))\n  (fuel := 100000)\n  (verbose : bool := ff)\n  (max_width : \u2115 := 25)\n  (max_depth : \u2115 := 50)\n  : tactic unit := do\n  init_state \u2190 BFSState.of_current_state 0 max_width max_depth,\n  \u03c3 \u2190 prod.snd <$> state_t.run (bfs_core api serialize_ts decode_response fuel) init_state,\n  when verbose $ eval_trace \u03c3\n\nend bfs\n\nnamespace io.process\n\nmeta instance : has_to_format spawn_args :=\n\u27e8\u03bb args, args.cmd ++ \" \" ++ string.intercalate \" \" args.args\u27e9\n\nend io.process\n\n\nsection run_proof_search\n\n-- warning: do not use, buggy\nmeta def try_import (m : module_info.module_name) : tactic unit := do\nlet env := environment.from_imported_module_name m,\nenv.fold (pure () : tactic unit) (\u03bb decl acc, acc *> tactic.try (tactic.add_decl decl))\n\nmeta def run_proof_search_step\n  {search_state : Type}\n  (search_core : state_t search_state tactic unit)\n  (decl_nm : name)\n  (open_ns : list name)\n  (show_trace : bool)\n  (global_timeout : \u2115)\n  (init_state : tactic search_state)\n  [has_mark_global_timeout search_state]\n  [has_register_decl_goal search_state]\n  : io (search_state \u00d7 string) := do\n  io.run_tactic' $ do {\n    tsd \u2190 get_tsd_at_decl decl_nm,\n    eval_trace format!\"[run_proof_search_step] GOT TSD AT DECL {decl_nm}\",\n    --- set the environment at decl\n    env \u2190 get_env_at_decl decl_nm,\n    eval_trace format!\"[run_proof_search_step] GOT ENV AT DECL {decl_nm}\",\n    tactic.set_env_core env,\n    eval_trace format!\"[run_proof_search_step] SET ENV AT DECL {decl_nm}\",\n\n    add_open_namespaces open_ns,\n    eval_trace format!\"[run_proof_search_step] ADDED OPEN NAMESPACES {open_ns}\",\n\n    /- note(jesse, January 14 2021, 09:52 AM): commented out because now we should always have namespaces in the .names files -/\n    -- additionally open namespaces in decl_nm\n    -- for_ decl_nm.components\n    --   (\u03bb nm, do env \u2190 tactic.get_env, when (env.is_namespace nm) $\n    --      (eval_trace format! \"[run_proof_search_step] ADDING OPEN NAMESPACE {nm}\") *>\n    --        add_open_namespace nm),\n\n    -- eval_trace \"[run_proof_search_step] GOT TSD\",\n\n\n    -- eval_trace format!\"[run_proof_search_step] SET ENV AT DECL {decl_nm}\",\n    rebuild_tactic_state tsd,\n    eval_trace format!\"[run_proof_search_step] REBUILT TACTIC STATE, ENTERING SEARCH CORE WITH TIMEOUT {global_timeout * 1000}\",\n    decl_goal_string \u2190 format.to_string <$> (tactic.target >>= tactic.pp),\n    tactic.read >>= \u03bb ts, eval_trace format!\"[run_proof_search_step] TACTIC STATE BEFORE SEARCH CORE: {ts}\",\n    env \u2190 tactic.get_env,\n    do {d \u2190 env.get decl_nm, tactic.trace \"[run_proof_search_step] WARNING: GOT DECL\"} <|> do {tactic.trace \"[run_proof_search_step] NO GOT DECL\"},\n    \u03c3\u2080 \u2190 flip has_register_decl_goal.register_decl_goal decl_goal_string <$> init_state,\n    \u03c3 \u2190 (prod.snd <$> tactic.try_for_time (global_timeout * 1000) (state_t.run (search_core) \u03c3\u2080) <|> do {\n      eval_trace format!\"[run_proof_search_step] GLOBAL TIMEOUT REACHED, ABORTING \",\n      pure (has_mark_global_timeout.mark_global_timeout \u03c3\u2080)\n    }),\n    -- pure $ {task_id := decl_nm.to_string, ..\u03c3}\n    pure \u27e8\u03c3, decl_nm.to_string\u27e9\n  }\n\n-- to be called in an environment which imports all declarations in `mathlib`\n-- ideally called on a shard of the test theorems\nmeta def run_proof_search_core\n  {search_state : Type}\n  [has_to_tactic_json search_state]\n  (search_core : state_t search_state tactic unit)\n  (decl_nms : list (name \u00d7 list name))\n  (process_search_state : search_state \u2192 io unit)\n  (show_trace : bool)\n  (global_timeout : \u2115) -- seconds\n  -- (register_task_id : search_state \u2192 string \u2192 search_state)\n  [has_register_task_id search_state]\n  [has_mark_global_timeout search_state]\n  [has_register_decl_goal search_state]\n  (init_state : tactic search_state)\n  : io unit := do {\n    let run_proof_search_core_body : name \u2192 list name \u2192 io unit := \u03bb decl_nm open_ns, do {\n      when (decl_nm.length > 0) $ do\n      when show_trace $ io.put_str_ln' format!\"[run_proof_search_core] OUTER LOOP: PROCESSING DECL {decl_nm}\",\n      env\u2080 \u2190 io.run_tactic' $ tactic.get_env,\n      when show_trace $ io.put_str_ln' format!\"[run_proof_search_core] GOT ENV\",\n      \u27e8search_state, decl_nm\u27e9 \u2190 (run_proof_search_step search_core decl_nm open_ns show_trace global_timeout init_state),\n      let search_state := has_register_task_id.register_task_id search_state decl_nm,\n      when show_trace $ io.put_str_ln' format!\"[run_proof_search_core] GOT SEARCH STATE\",\n      io.run_tactic' $ tactic.set_env_core env\u2080,\n      process_search_state search_state\n    },\n\n    for_ decl_nms (\u03bb \u27e8decl_nm, open_ns\u27e9, do\n      run_proof_search_core_body decl_nm open_ns <|> io.put_str_ln' format!\"[run_proof_search_core] WARNING: SKIPPING {decl_nm}\"\n)}\n\nend run_proof_search\n\nend evaluation_harness\n\n\nsection playground\n\n-- example : \u2124 \u2192 bool\n-- | (of_int k) := if\n-- set_option pp.notation false\n-- #reduce (-3 : \u2124)\n\n-- example (x : \u2115) : nat.zero.gcd x = x :=\n-- begin\n--   simp [nat.gcd]\n-- end\n\nend playground\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/evaluation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.05033062974852633, "lm_q1q2_score": 0.017906374439255912}}
{"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 \u2192 Type v} -- The family of types already equipped with instances\nvariables (x y : \u03a0 i, f i) (i : I)\n\nnamespace pi\n\n@[to_additive pi.has_vadd]\ninstance has_scalar {\u03b1 : Type*} [\u03a0 i, has_scalar \u03b1 $ f i] :\n  has_scalar \u03b1 (\u03a0 i : I, f i) :=\n\u27e8\u03bb s x, \u03bb i, s \u2022 (x i)\u27e9\n\n@[to_additive]\nlemma smul_def {\u03b1 : Type*} [\u03a0 i, has_scalar \u03b1 $ f i] (s : \u03b1) : s \u2022 x = \u03bb i, s \u2022 x i := rfl\n@[simp, to_additive]\nlemma smul_apply {\u03b1 : Type*} [\u03a0 i, has_scalar \u03b1 $ f i] (s : \u03b1) : (s \u2022 x) i = s \u2022 x i := rfl\n\n@[to_additive pi.has_vadd']\ninstance has_scalar' {g : I \u2192 Type*} [\u03a0 i, has_scalar (f i) (g i)] :\n  has_scalar (\u03a0 i, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb s x, \u03bb i, (s i) \u2022 (x i)\u27e9\n\n@[simp, to_additive]\nlemma smul_apply' {g : I \u2192 Type*} [\u2200 i, has_scalar (f i) (g i)] (s : \u03a0 i, f i) (x : \u03a0 i, g i) :\n  (s \u2022 x) i = s i \u2022 x i :=\nrfl\ninstance is_scalar_tower {\u03b1 \u03b2 : Type*}\n  [has_scalar \u03b1 \u03b2] [\u03a0 i, has_scalar \u03b2 $ f i] [\u03a0 i, has_scalar \u03b1 $ f i]\n  [\u03a0 i, is_scalar_tower \u03b1 \u03b2 (f i)] : is_scalar_tower \u03b1 \u03b2 (\u03a0 i : I, f i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc x y (z i)\u27e9\n\ninstance is_scalar_tower' {g : I \u2192 Type*} {\u03b1 : Type*}\n  [\u03a0 i, has_scalar \u03b1 $ f i] [\u03a0 i, has_scalar (f i) (g i)] [\u03a0 i, has_scalar \u03b1 $ g i]\n  [\u03a0 i, is_scalar_tower \u03b1 (f i) (g i)] : is_scalar_tower \u03b1 (\u03a0 i : I, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc x (y i) (z i)\u27e9\n\ninstance is_scalar_tower'' {g : I \u2192 Type*} {h : I \u2192 Type*}\n  [\u03a0 i, has_scalar (f i) (g i)] [\u03a0 i, has_scalar (g i) (h i)] [\u03a0 i, has_scalar (f i) (h i)]\n  [\u03a0 i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (\u03a0 i, f i) (\u03a0 i, g i) (\u03a0 i, h i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_assoc (x i) (y i) (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class {\u03b1 \u03b2 : Type*}\n  [\u03a0 i, has_scalar \u03b1 $ f i] [\u03a0 i, has_scalar \u03b2 $ f i] [\u2200 i, smul_comm_class \u03b1 \u03b2 (f i)] :\n  smul_comm_class \u03b1 \u03b2 (\u03a0 i : I, f i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm x y (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class' {g : I \u2192 Type*} {\u03b1 : Type*}\n  [\u03a0 i, has_scalar \u03b1 $ g i] [\u03a0 i, has_scalar (f i) (g i)] [\u2200 i, smul_comm_class \u03b1 (f i) (g i)] :\n  smul_comm_class \u03b1 (\u03a0 i : I, f i) (\u03a0 i : I, g i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm x (y i) (z i)\u27e9\n\n@[to_additive]\ninstance smul_comm_class'' {g : I \u2192 Type*} {h : I \u2192 Type*}\n  [\u03a0 i, has_scalar (g i) (h i)] [\u03a0 i, has_scalar (f i) (h i)]\n  [\u2200 i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (\u03a0 i, f i) (\u03a0 i, g i) (\u03a0 i, h i) :=\n\u27e8\u03bb x y z, funext $ \u03bb i, smul_comm (x i) (y i) (z i)\u27e9\n\ninstance {\u03b1 : Type*} [\u03a0 i, has_scalar \u03b1 $ f i] [\u03a0 i, has_scalar \u03b1\u1d50\u1d52\u1d56 $ f i]\n  [\u2200 i, is_central_scalar \u03b1 (f i)] : is_central_scalar \u03b1 (\u03a0 i, f i) :=\n\u27e8\u03bb r m, funext $ \u03bb i, op_smul_eq_smul _ _\u27e9\n\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `\u03a0 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 {\u03b1 : Type*}\n  [\u03a0 i, has_scalar \u03b1 $ f i] [\u03a0 i, nonempty (f i)] (i : I) [has_faithful_smul \u03b1 (f i)] :\n  has_faithful_smul \u03b1 (\u03a0 i, f i) :=\n\u27e8\u03bb x y h, eq_of_smul_eq_smul $ \u03bb a : f i, begin\n  classical,\n  have := congr_fun (h $ function.update (\u03bb j, classical.choice (\u2039\u03a0 i, nonempty (f i)\u203a j)) i a) i,\n  simpa using this,\nend\u27e9\n\n@[to_additive pi.has_faithful_vadd]\ninstance has_faithful_smul {\u03b1 : Type*}\n  [nonempty I] [\u03a0 i, has_scalar \u03b1 $ f i] [\u03a0 i, nonempty (f i)] [\u03a0 i, has_faithful_smul \u03b1 (f i)] :\n  has_faithful_smul \u03b1 (\u03a0 i, f i) :=\nlet \u27e8i\u27e9 := \u2039nonempty I\u203a in has_faithful_smul_at i\n\n@[to_additive]\ninstance mul_action (\u03b1) {m : monoid \u03b1} [\u03a0 i, mul_action \u03b1 $ f i] :\n  @mul_action \u03b1 (\u03a0 i : I, f i) m :=\n{ smul := (\u2022),\n  mul_smul := \u03bb r s f, funext $ \u03bb i, mul_smul _ _ _,\n  one_smul := \u03bb f, funext $ \u03bb i, one_smul \u03b1 _ }\n\n@[to_additive]\ninstance mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} [\u03a0 i, mul_action (f i) (g i)] :\n  @mul_action (\u03a0 i, f i) (\u03a0 i : I, g i) (@pi.monoid I f m) :=\n{ smul := (\u2022),\n  mul_smul := \u03bb r s f, funext $ \u03bb i, mul_smul _ _ _,\n  one_smul := \u03bb f, funext $ \u03bb i, one_smul _ _ }\n\ninstance distrib_mul_action (\u03b1) {m : monoid \u03b1} {n : \u2200 i, add_monoid $ f i}\n  [\u2200 i, distrib_mul_action \u03b1 $ f i] :\n  @distrib_mul_action \u03b1 (\u03a0 i : I, f i) m (@pi.add_monoid I f n) :=\n{ smul_zero := \u03bb c, funext $ \u03bb i, smul_zero _,\n  smul_add := \u03bb c f g, funext $ \u03bb i, smul_add _ _ _,\n  ..pi.mul_action _ }\n\ninstance distrib_mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} {n : \u03a0 i, add_monoid $ g i}\n  [\u03a0 i, distrib_mul_action (f i) (g i)] :\n  @distrib_mul_action (\u03a0 i, f i) (\u03a0 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 {\u03b1} [monoid \u03b1] [\u03a0 i, add_monoid $ f i]\n  [\u03a0 i, distrib_mul_action \u03b1 $ f i] [decidable_eq I] (i : I) (r : \u03b1) (x : f i) :\n  single i (r \u2022 x) = r \u2022 single i x :=\nsingle_op (\u03bb i : I, ((\u2022) r : f i \u2192 f i)) (\u03bb 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' {\u03b1 \u03b2} [monoid \u03b1] [add_monoid \u03b2]\n  [distrib_mul_action \u03b1 \u03b2] [decidable_eq I] (i : I) (r : \u03b1) (x : \u03b2) :\n  single i (r \u2022 x) = r \u2022 single i x :=\nsingle_smul i r x\n\nlemma single_smul\u2080 {g : I \u2192 Type*} [\u03a0 i, monoid_with_zero (f i)] [\u03a0 i, add_monoid (g i)]\n  [\u03a0 i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) :\n  single i (r \u2022 x) = single i r \u2022 single i x :=\nsingle_op\u2082 (\u03bb i : I, ((\u2022) : f i \u2192 g i \u2192 g i)) (\u03bb j, smul_zero _) _ _ _\n\ninstance mul_distrib_mul_action (\u03b1) {m : monoid \u03b1} {n : \u03a0 i, monoid $ f i}\n  [\u03a0 i, mul_distrib_mul_action \u03b1 $ f i] :\n  @mul_distrib_mul_action \u03b1 (\u03a0 i : I, f i) m (@pi.monoid I f n) :=\n{ smul_one := \u03bb c, funext $ \u03bb i, smul_one _,\n  smul_mul := \u03bb c f g, funext $ \u03bb i, smul_mul' _ _ _,\n  ..pi.mul_action _ }\n\ninstance mul_distrib_mul_action' {g : I \u2192 Type*} {m : \u03a0 i, monoid (f i)} {n : \u03a0 i, monoid $ g i}\n  [\u03a0 i, mul_distrib_mul_action (f i) (g i)] :\n  @mul_distrib_mul_action (\u03a0 i, f i) (\u03a0 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 {\u03b9 R M : Type*} [has_scalar R M] :\n  has_scalar R (\u03b9 \u2192 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 {\u03b9 \u03b1 \u03b2 M : Type*}\n  [has_scalar \u03b1 M] [has_scalar \u03b2 M] [smul_comm_class \u03b1 \u03b2 M] :\n  smul_comm_class \u03b1 \u03b2 (\u03b9 \u2192 M) :=\npi.smul_comm_class\n\n@[to_additive]\nlemma update_smul {\u03b1 : Type*} [\u03a0 i, has_scalar \u03b1 (f i)] [decidable_eq I]\n  (c : \u03b1) (f\u2081 : \u03a0 i, f i) (i : I) (x\u2081 : f i) :\n  update (c \u2022 f\u2081) i (c \u2022 x\u2081) = c \u2022 update f\u2081 i x\u2081 :=\nfunext $ \u03bb j, (apply_update (\u03bb i, (\u2022) c) f\u2081 i x\u2081 j).symm\n\nend function\n\nnamespace set\n\n@[to_additive]\nlemma piecewise_smul {\u03b1 : Type*} [\u03a0 i, has_scalar \u03b1 (f i)] (s : set I) [\u03a0 i, decidable (i \u2208 s)]\n  (c : \u03b1) (f\u2081 g\u2081 : \u03a0 i, f i) :\n  s.piecewise (c \u2022 f\u2081) (c \u2022 g\u2081) = c \u2022 s.piecewise f\u2081 g\u2081 :=\ns.piecewise_op _ _ (\u03bb _, (\u2022) c)\n\nend set\n\nsection extend\n\n@[to_additive] lemma function.extend_smul {R \u03b1 \u03b2 \u03b3 : Type*} [has_scalar R \u03b3]\n  (r : R) (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e : \u03b2 \u2192 \u03b3) :\n  function.extend f (r \u2022 g) (r \u2022 e) = r \u2022 function.extend f g e :=\nfunext $ \u03bb _, by convert (apply_dite ((\u2022) 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:= \u27e8{ avail := [[tt]], ini := {boxes := [], storekeeper := (0,0)}, goal := \u27e8[]\u27e9 }\u27e9\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 \u2208 level.goal \u2227\n    goal_state.reachable level.avail level.ini\n\nlemma solvable.triv (level : sokolevel)\n: level.ini \u2208 level.goal \u2192 level.solvable\n:= \u03bb Hin, \u27e8level.ini, \u27e8Hin, sokostate.reachable.triv\u27e9\u27e9\n\nlemma solvable.move (d : direction) (level : sokolevel)\n: (level.move d).solvable \u2192 level.solvable\n:= \u03bb Hsol, exists.elim Hsol (\u03bb goal Hsol,\n  \u27e8goal, \u27e8Hsol.1, sokostate.reachable.move d Hsol.2\u27e9\u27e9 )\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 \u2192 option (sokolevel \u00d7 bool)\n| [] := some ( \u27e8 [], \u27e8[], (0,0)\u27e9, \u27e8[]\u27e9\u27e9 , 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 \u2192 bool \u2192 bool \u2192 bool \u2192 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 \u00d7 bool \u00d7 bool \u00d7 bool) \u2192 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 \u00d7 bool \u00d7 bool \u00d7 bool) \u2192 list char\n| [] := []\n| (h::t) := to_string_aux1 ('\\n'::(to_string_aux2 t)) h\n\ninstance : has_to_string sokolevel := \u27e8\u03bb 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\u27e9\n\ninstance : has_repr sokolevel\n:= \u27e8\u03bb lev, (string.append (string.append \"from_string \\\"\" (to_string lev)) \"\\\"\")\u27e9\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) \u2190 tactic.target,\n  lev \u2190 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 \u2190 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 \u2190 tactic.to_expr p,\n  name \u2190 tactic.get_unused_name,\n  H \u2190 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) \u2190 tactic.target,\n  soko_simp_root lev\n\nmeta def soko_check_depth : expr \u2192 \u2115 \u2192 tactic unit\n| _ 0 := return ()\n| e (n+1) := do\n  `(sokolevel.move %%lev _) \u2190 return e,\n  soko_check_depth lev n\n\nmeta def soko_simp_if_deep : tactic unit :=\ndo\n  `(sokolevel.solvable %%lev) \u2190 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: \u2200 vssrc vstgt (\u03b7:freevar.env),\n  \u03b7\u27e6opt.check_val irsem_smt vssrc vstgt\u27e7' = opt.check_val irsem_smt (\u03b7\u27e6vssrc\u27e7) (\u03b7\u27e6vstgt\u27e7)\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: \u2200 {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 (\u03bb 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 \u2260 vetgt_sz,\n    { rw \u2190 HEQS, rw \u2190 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 \u2190 HEQS, rw \u2190 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: \u2200 {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 (\u03bb 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 \u2260 vetgt_sz,\n    {\n      rw \u2190 HSSZEQ, rw \u2190 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 [\u2190 HSSZEQ, \u2190 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: \u2200 psrc ptgt root ss0 (\u03b7:freevar.env),\n    \u03b7\u27e6opt.check_single_reg0 irsem_smt psrc ptgt root ss0\u27e7' =\n        opt.check_single_reg0 irsem_smt psrc ptgt root (\u03b7\u27e6ss0\u27e7)\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 \u2190 bigstep_replace,\n  rw \u2190 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 \u2190 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: \u2200 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 (\u03bb 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' (\u03bb 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 (\u03bb 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 \u2190 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 \u2190 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 \u2190 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 (\u03b7\u27e6sb\u27e7) = check_single_reg0 irsem_smt psrc ptgt root (\u03b7\u27e6ss0\u27e7),\n  {\n    rw \u2190 check_single_reg0_replace,\n    rw \u2190 HSREF\n  },\n  have HCHKEQ: none_or_some (some (\u03b7\u27e6sb\u27e7)) oeb (\u03bb 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 \u03b7 eb HCHKEQ,\n  \n  unfold root_refines,\n  unfold check_single_reg0 at HEREF,\n  rw [\u2190 a_1, \u2190 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": "/-\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-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.logic\nimport Mathlib.Lean3Lib.init.control.monad\nimport Mathlib.Lean3Lib.init.control.alternative\n \n\nuniverses u v u_1 u_2 \n\nnamespace Mathlib\n\nnamespace option\n\n\ndef to_monad {m : Type \u2192 Type} [Monad m] [alternative m] {A : Type} : Option A \u2192 m A :=\n  sorry\n\ndef get_or_else {\u03b1 : Type u} : Option \u03b1 \u2192 \u03b1 \u2192 \u03b1 :=\n  sorry\n\ndef is_some {\u03b1 : Type u} : Option \u03b1 \u2192 Bool :=\n  sorry\n\ndef is_none {\u03b1 : Type u} : Option \u03b1 \u2192 Bool :=\n  sorry\n\ndef get {\u03b1 : Type u} {o : Option \u03b1} : \u21a5(is_some o) \u2192 \u03b1 :=\n  sorry\n\ndef rhoare {\u03b1 : Type u} : Bool \u2192 \u03b1 \u2192 Option \u03b1 :=\n  sorry\n\ndef lhoare {\u03b1 : Type u} : \u03b1 \u2192 Option \u03b1 \u2192 \u03b1 :=\n  sorry\n\ninfixr:1 \"|>\" => Mathlib.option.rhoare\n\ninfixr:1 \"<|\" => Mathlib.option.lhoare\n\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} : Option \u03b1 \u2192 (\u03b1 \u2192 Option \u03b2) \u2192 Option \u03b2 :=\n  sorry\n\nprotected def map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (o : Option \u03b1) : Option \u03b2 :=\n  option.bind o (some \u2218 f)\n\ntheorem map_id {\u03b1 : Type u_1} : option.map id = id := sorry\n\nprotected instance monad : Monad Option :=\n  { toApplicative :=\n      { toFunctor := { map := option.map, mapConst := fun (\u03b1 \u03b2 : Type u_1) => option.map \u2218 function.const \u03b2 },\n        toPure := { pure := some },\n        toSeq :=\n          { seq :=\n              fun (\u03b1 \u03b2 : Type u_1) (f : Option (\u03b1 \u2192 \u03b2)) (x : Option \u03b1) =>\n                option.bind f fun (_x : \u03b1 \u2192 \u03b2) => option.map _x x },\n        toSeqLeft :=\n          { seqLeft :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : Option \u03b1) (b : Option \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : Option (\u03b1 \u2192 \u03b2)) (x : Option \u03b1) =>\n                    option.bind f fun (_x : \u03b1 \u2192 \u03b2) => option.map _x x)\n                  \u03b2 \u03b1 (option.map (function.const \u03b2) a) b },\n        toSeqRight :=\n          { seqRight :=\n              fun (\u03b1 \u03b2 : Type u_1) (a : Option \u03b1) (b : Option \u03b2) =>\n                (fun (\u03b1 \u03b2 : Type u_1) (f : Option (\u03b1 \u2192 \u03b2)) (x : Option \u03b1) =>\n                    option.bind f fun (_x : \u03b1 \u2192 \u03b2) => option.map _x x)\n                  \u03b2 \u03b2 (option.map (function.const \u03b1 id) a) b } },\n    toBind := { bind := option.bind } }\n\nprotected def orelse {\u03b1 : Type u} : Option \u03b1 \u2192 Option \u03b1 \u2192 Option \u03b1 :=\n  sorry\n\nprotected instance alternative : alternative Option :=\n  alternative.mk none\n\nend option\n\n\nprotected instance option.inhabited (\u03b1 : Type u) : Inhabited (Option \u03b1) :=\n  { default := none }\n\nprotected instance option.decidable_eq {\u03b1 : Type u} [d : DecidableEq \u03b1] : DecidableEq (Option \u03b1) :=\n  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/option/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.03846618871146969, "lm_q1q2_score": 0.017882991576707554}}
{"text": "/-\nCopyright (c) 2022 Henrik B\u00f6ving. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Henrik B\u00f6ving\n-/\nimport Lean.Attributes\nimport Lean.Environment\nimport Lean.Meta.Basic\nimport Lean.Compiler.LCNF.CompilerM\n\nnamespace Lean.Compiler.LCNF\n\ndef Phase.toNat : Phase \u2192 Nat\n  | .base => 0\n  | .mono => 1\n  | .impure => 2\n\ninstance : LT Phase where\n  lt l r := l.toNat < r.toNat\n\ninstance : LE Phase where\n  le l r := l.toNat \u2264 r.toNat\n\ninstance {p1 p2 : Phase} : Decidable (p1 < p2) := Nat.decLt p1.toNat p2.toNat\ninstance {p1 p2 : Phase} : Decidable (p1 \u2264 p2) := Nat.decLe p1.toNat p2.toNat\n\n@[simp] theorem Phase.le_refl (p : Phase) : p \u2264 p := by\n  cases p <;> decide\n\n/--\nA single compiler `Pass`, consisting of the actual pass function operating\non the `Decl`s as well as meta information.\n-/\nstructure Pass where\n  /--\n  Which occurrence of the pass in the pipeline this is.\n  Some passes, like simp, can occur multiple times in the pipeline.\n  For most passes this value does not matter.\n  -/\n  occurrence : Nat := 0\n  /--\n  Which phase this `Pass` is supposed to run in\n  -/\n  phase : Phase\n  /--\n  Resulting phase.\n  -/\n  phaseOut : Phase := phase\n  phaseInv : phaseOut \u2265 phase := by simp\n  /--\n  The name of the `Pass`\n  -/\n  name : Name\n  /--\n  The actual pass function, operating on the `Decl`s.\n  -/\n  run : Array Decl \u2192 CompilerM (Array Decl)\n\ninstance : Inhabited Pass where\n  default := { phase := .base, name := default, run := fun decls => return decls }\n\n/--\nCan be used to install, remove, replace etc. passes by tagging a declaration\nof type `PassInstaller` with the `cpass` attribute.\n-/\nstructure PassInstaller where\n  /--\n  When the installer is run this function will receive a list of all\n  current `Pass`es and return a new one, this can modify the list (and\n  the `Pass`es contained within) in any way it wants.\n  -/\n  install : Array Pass \u2192 CoreM (Array Pass)\n  deriving Inhabited\n\n/--\nThe `PassManager` used to store all `Pass`es that will be run within\npipeline.\n-/\nstructure PassManager where\n  passes : Array Pass\n  deriving Inhabited\n\ninstance : ToString Phase where\n  toString\n    | .base => \"base\"\n    | .mono => \"mono\"\n    | .impure => \"impure\"\n\nnamespace Pass\n\ndef mkPerDeclaration (name : Name) (run : Decl \u2192 CompilerM Decl) (phase : Phase) (occurrence : Nat := 0) : Pass where\n  occurrence := occurrence\n  phase := phase\n  name := name\n  run := fun xs => xs.mapM run\n\nend Pass\n\nnamespace PassManager\n\ndef validate (manager : PassManager) : CoreM Unit := do\n  let mut current := .base\n  for pass in manager.passes do\n    if \u00ac(current \u2264 pass.phase) then\n      throwError s!\"{pass.name} has phase {pass.phase} but should at least have {current}\"\n    current := pass.phase\n\ndef findHighestOccurrence (targetName : Name) (passes : Array Pass) : CoreM Nat := do\n  let mut highest := none\n  for pass in passes do\n      if pass.name == targetName then\n        highest := some pass.occurrence\n  let some val := highest | throwError s!\"Could not find any occurrence of {targetName}\"\n  return val\n\nend PassManager\n\nnamespace PassInstaller\n\ndef installAtEnd (p : Pass) : PassInstaller where\n  install passes := return passes.push p\n\ndef append (passesNew : Array Pass) : PassInstaller where\n  install passes := return passes ++ passesNew\n\ndef withEachOccurrence (targetName : Name) (f : Nat \u2192 PassInstaller) : PassInstaller where\n  install passes := do\n    let highestOccurrence \u2190 PassManager.findHighestOccurrence targetName passes\n    let mut passes := passes\n    for occurrence in [0:highestOccurrence+1] do\n      passes \u2190 f occurrence |>.install passes\n    return passes\n\ndef installAfter (targetName : Name) (p : Pass \u2192 Pass) (occurrence : Nat := 0) : PassInstaller where\n  install passes :=\n    if let some idx := passes.findIdx? (fun p => p.name == targetName && p.occurrence == occurrence) then\n      let passUnderTest := passes[idx]!\n      return passes.insertAt! (idx + 1) (p passUnderTest)\n    else\n      throwError s!\"Tried to insert pass after {targetName}, occurrence {occurrence} but {targetName} is not in the pass list\"\n\ndef installAfterEach (targetName : Name) (p : Pass \u2192 Pass) : PassInstaller :=\n    withEachOccurrence targetName (installAfter targetName p \u00b7)\n\ndef installBefore (targetName : Name) (p : Pass \u2192 Pass) (occurrence : Nat := 0): PassInstaller where\n  install passes :=\n    if let some idx := passes.findIdx? (fun p => p.name == targetName && p.occurrence == occurrence) then\n      let passUnderTest := passes[idx]!\n      return passes.insertAt! idx (p passUnderTest)\n    else\n      throwError s!\"Tried to insert pass after {targetName}, occurrence {occurrence} but {targetName} is not in the pass list\"\n\ndef installBeforeEachOccurrence (targetName : Name) (p : Pass \u2192 Pass) : PassInstaller :=\n    withEachOccurrence targetName (installBefore targetName p \u00b7)\n\ndef replacePass (targetName : Name) (p : Pass \u2192 Pass) (occurrence : Nat := 0) : PassInstaller where\n  install passes := do\n    let some idx := passes.findIdx? (fun p => p.name == targetName && p.occurrence == occurrence) | throwError s!\"Tried to replace {targetName}, occurrence {occurrence} but {targetName} is not in the pass list\"\n    let target := passes[idx]!\n    let replacement := p target\n    return passes.set! idx replacement\n\ndef replaceEachOccurrence (targetName : Name) (p : Pass \u2192 Pass) : PassInstaller :=\n    withEachOccurrence targetName (replacePass targetName p \u00b7)\n\ndef run (manager : PassManager) (installer : PassInstaller) : CoreM PassManager := do\n  return { manager with passes := (\u2190 installer.install manager.passes) }\n\nprivate unsafe def getPassInstallerUnsafe (declName : Name) : CoreM PassInstaller := do\n  ofExcept <| (\u2190 getEnv).evalConstCheck PassInstaller (\u2190 getOptions) ``PassInstaller declName\n\n@[implemented_by getPassInstallerUnsafe]\nprivate opaque getPassInstaller (declName : Name) : CoreM PassInstaller\n\ndef runFromDecl (manager : PassManager) (declName : Name) : CoreM PassManager := do\n  let installer \u2190 getPassInstaller declName\n  let newState \u2190 installer.run manager\n  newState.validate\n  return newState\n\nend PassInstaller\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/PassManager.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.03904829594130494, "lm_q1q2_score": 0.017850409804316528}}
{"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.congruence_closure\n! leanprover-community/mathlib commit 9eae65f7144bcc692858b9dadf2e48181f4270b9\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.InteractiveBase\nimport Leanbin.Init.Meta.Tactic\nimport Leanbin.Init.Meta.SetGetOptionTactics\n\nstructure CcConfig where\n  -- If tt, congruence closure will treat implicit instance arguments as constants.\n  ignoreInstances : Bool := true\n  -- If tt, congruence closure modulo AC.\n  ac : Bool := true\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  hoFns : Option (List Name) := none\n  -- If true, then use excluded middle\n  em : Bool := true\n#align cc_config CcConfig\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 -/\nunsafe axiom cc_state : Type\n#align cc_state cc_state\n\nunsafe axiom cc_state.mk_core : CcConfig \u2192 cc_state\n#align cc_state.mk_core cc_state.mk_core\n\n/-- Create a congruence closure state object using the hypotheses in the current goal. -/\nunsafe axiom cc_state.mk_using_hs_core : CcConfig \u2192 tactic cc_state\n#align cc_state.mk_using_hs_core cc_state.mk_using_hs_core\n\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. -/\nunsafe axiom cc_state.next : cc_state \u2192 expr \u2192 expr\n#align cc_state.next cc_state.next\n\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. -/\nunsafe axiom cc_state.roots_core : cc_state \u2192 Bool \u2192 List expr\n#align cc_state.roots_core cc_state.roots_core\n\n/-- Get the root representative of the given expression. -/\nunsafe axiom cc_state.root : cc_state \u2192 expr \u2192 expr\n#align cc_state.root cc_state.root\n\n/--\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. -/\nunsafe axiom cc_state.mt : cc_state \u2192 expr \u2192 Nat\n#align cc_state.mt cc_state.mt\n\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`. -/\nunsafe axiom cc_state.gmt : cc_state \u2192 Nat\n#align cc_state.gmt cc_state.gmt\n\n/-- Increment the Global Modification time. -/\nunsafe axiom cc_state.inc_gmt : cc_state \u2192 cc_state\n#align cc_state.inc_gmt cc_state.inc_gmt\n\n/-- Check if `e` is the root of the congruence class. -/\nunsafe axiom cc_state.is_cg_root : cc_state \u2192 expr \u2192 Bool\n#align cc_state.is_cg_root cc_state.is_cg_root\n\n/-- Pretty print the entry associated with the given expression. -/\nunsafe axiom cc_state.pp_eqc : cc_state \u2192 expr \u2192 tactic format\n#align cc_state.pp_eqc cc_state.pp_eqc\n\n/-- Pretty print the entire cc graph.\nIf the bool argument is set to true then singleton equivalence classes will be omitted. -/\nunsafe axiom cc_state.pp_core : cc_state \u2192 Bool \u2192 tactic format\n#align cc_state.pp_core cc_state.pp_core\n\n/-- Add the given expression to the graph. -/\nunsafe axiom cc_state.internalize : cc_state \u2192 expr \u2192 tactic cc_state\n#align cc_state.internalize cc_state.internalize\n\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. -/\nunsafe axiom cc_state.add : cc_state \u2192 expr \u2192 tactic cc_state\n#align cc_state.add cc_state.add\n\n/-- Check whether two expressions are in the same equivalence class. -/\nunsafe axiom cc_state.is_eqv : cc_state \u2192 expr \u2192 expr \u2192 tactic Bool\n#align cc_state.is_eqv cc_state.is_eqv\n\n/-- Check whether two expressions are not in the same equivalence class. -/\nunsafe axiom cc_state.is_not_eqv : cc_state \u2192 expr \u2192 expr \u2192 tactic Bool\n#align cc_state.is_not_eqv cc_state.is_not_eqv\n\n/-- Returns a proof term that the given terms are equivalent in the given cc_state-/\nunsafe axiom cc_state.eqv_proof : cc_state \u2192 expr \u2192 expr \u2192 tactic expr\n#align cc_state.eqv_proof cc_state.eqv_proof\n\n/--\nReturns true if the cc_state is inconsistent. For example if it had both `a = b` and `a \u2260 b` in it.-/\nunsafe axiom cc_state.inconsistent : cc_state \u2192 Bool\n#align cc_state.inconsistent cc_state.inconsistent\n\n/-- `proof_for cc e` constructs a proof for e if it is equivalent to true in cc_state -/\nunsafe axiom cc_state.proof_for : cc_state \u2192 expr \u2192 tactic expr\n#align cc_state.proof_for cc_state.proof_for\n\n/-- `refutation_for cc e` constructs a proof for `not e` if it is equivalent to false in cc_state -/\nunsafe axiom cc_state.refutation_for : cc_state \u2192 expr \u2192 tactic expr\n#align cc_state.refutation_for cc_state.refutation_for\n\n/-- If the given state is inconsistent, return a proof for false. Otherwise fail. -/\nunsafe axiom cc_state.proof_for_false : cc_state \u2192 tactic expr\n#align cc_state.proof_for_false cc_state.proof_for_false\n\nnamespace CcState\n\nunsafe def mk : cc_state :=\n  cc_state.mk_core { }\n#align cc_state.mk cc_state.mk\n\nunsafe def mk_using_hs : tactic cc_state :=\n  cc_state.mk_using_hs_core { }\n#align cc_state.mk_using_hs cc_state.mk_using_hs\n\nunsafe def roots (s : cc_state) : List expr :=\n  cc_state.roots_core s true\n#align cc_state.roots cc_state.roots\n\nunsafe instance : has_to_tactic_format cc_state :=\n  \u27e8fun s => cc_state.pp_core s true\u27e9\n\nunsafe def eqc_of_core (s : cc_state) : expr \u2192 expr \u2192 List expr \u2192 List expr\n  | e, f, r =>\n    let n := s.next e\n    if n = f then e :: r else eqc_of_core n f (e :: r)\n#align cc_state.eqc_of_core cc_state.eqc_of_core\n\nunsafe def eqc_of (s : cc_state) (e : expr) : List expr :=\n  s.eqc_of_core e e []\n#align cc_state.eqc_of cc_state.eqc_of\n\nunsafe def in_singlenton_eqc (s : cc_state) (e : expr) : Bool :=\n  s.next e = e\n#align cc_state.in_singlenton_eqc cc_state.in_singlenton_eqc\n\nunsafe def eqc_size (s : cc_state) (e : expr) : Nat :=\n  (s.eqc_of e).length\n#align cc_state.eqc_size cc_state.eqc_size\n\nunsafe def fold_eqc_core {\u03b1} (s : cc_state) (f : \u03b1 \u2192 expr \u2192 \u03b1) (first : expr) : expr \u2192 \u03b1 \u2192 \u03b1\n  | c, a =>\n    let new_a := f a c\n    let next := s.next c\n    if next == first then new_a else fold_eqc_core next new_a\n#align cc_state.fold_eqc_core cc_state.fold_eqc_core\n\nunsafe def fold_eqc {\u03b1} (s : cc_state) (e : expr) (a : \u03b1) (f : \u03b1 \u2192 expr \u2192 \u03b1) : \u03b1 :=\n  fold_eqc_core s f e e a\n#align cc_state.fold_eqc cc_state.fold_eqc\n\nunsafe def mfold_eqc {\u03b1} {m : Type \u2192 Type} [Monad m] (s : cc_state) (e : expr) (a : \u03b1)\n    (f : \u03b1 \u2192 expr \u2192 m \u03b1) : m \u03b1 :=\n  fold_eqc s e (return a) fun act e => do\n    let a \u2190 act\n    f a e\n#align cc_state.mfold_eqc cc_state.mfold_eqc\n\nend CcState\n\nopen Tactic\n\nunsafe def tactic.cc_core (cfg : CcConfig) : tactic Unit := do\n  intros\n  let s \u2190 cc_state.mk_using_hs_core cfg\n  let t \u2190 target\n  let s \u2190 s.internalize t\n  if s then do\n      let pr \u2190 s\n      mk_app `false.elim [t, pr] >>= exact\n    else do\n      let tr \u2190 return <| expr.const `true []\n      let b \u2190 s t tr\n      if b then do\n          let pr \u2190 s t tr\n          mk_app `of_eq_true [pr] >>= exact\n        else do\n          let dbg \u2190 get_bool_option `trace.cc.failure ff\n          if dbg then do\n              let ccf \u2190 pp s\n              fail\n                  f! \"cc tactic failed, equivalence classes: \n                    {ccf}\"\n            else do\n              fail \"cc tactic failed\"\n#align tactic.cc_core tactic.cc_core\n\nunsafe def tactic.cc : tactic Unit :=\n  tactic.cc_core { }\n#align tactic.cc tactic.cc\n\nunsafe def tactic.cc_dbg_core (cfg : CcConfig) : tactic Unit :=\n  save_options <| set_bool_option `trace.cc.failure true >> tactic.cc_core cfg\n#align tactic.cc_dbg_core tactic.cc_dbg_core\n\nunsafe def tactic.cc_dbg : tactic Unit :=\n  tactic.cc_dbg_core { }\n#align tactic.cc_dbg tactic.cc_dbg\n\nunsafe def tactic.ac_refl : tactic Unit := do\n  let (lhs, rhs) \u2190 target >>= match_eq\n  let s \u2190 return <| cc_state.mk\n  let s \u2190 s.internalize lhs\n  let s \u2190 s.internalize rhs\n  let b \u2190 s.is_eqv lhs rhs\n  if b then do\n      s lhs rhs >>= exact\n    else do\n      fail \"ac_refl failed\"\n#align tactic.ac_refl tactic.ac_refl\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/CongruenceClosure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.048136773847697205, "lm_q1q2_score": 0.017821456665021426}}
{"text": "import Table.API\nimport Table.ExampleTables\nimport Table.Notation\n\n-- Table equality typeclass resolution requires a lot of instances\nset_option synthInstance.maxSize 12000\nset_option synthInstance.maxHeartbeats 0\n\n-- TODO: come up with a better testing system\n-- Modified version of `elabEvalUnsafe` (src/lean/lean/elab/builtincommand.lean)\nsyntax (name := test) \"#test\" term : command\n@[commandElab test]\nunsafe def elabTest : Lean.Elab.Command.CommandElab\n| `(#test%$tk $term) => do\n    let n := `_eval\n    let ctx \u2190 read\n    let addAndCompile (value : Lean.Expr) : Lean.Elab.TermElabM Unit := do\n      -- the type really should be `Bool` at this point (b/c of `mkDecide`)\n      -- (but could enforcing that explicitly lead to less-graceful failures?)\n      let type \u2190 Lean.Meta.inferType value\n      let us := Lean.collectLevelParams {} value |>.params\n      -- let value \u2190 Lean.Meta.instantiateMVars value\n      let decl := Lean.Declaration.defnDecl {\n        name        := n\n        levelParams := us.toList\n        type        := type\n        value       := value\n        hints       := Lean.ReducibilityHints.opaque\n        safety      := Lean.DefinitionSafety.unsafe\n      }\n      Lean.Elab.Term.ensureNoUnassignedMVars decl\n      Lean.addAndCompile decl\n    let elabEvalTerm : Lean.Elab.TermElabM Lean.Expr := do\n      let ebool \u2190 Lean.Elab.Term.elabTerm (\u2190 `(Bool)) none\n      let e \u2190 Lean.Elab.Term.elabTerm term none\n      Lean.Elab.Term.synthesizeSyntheticMVarsNoPostponing\n\n      -- Need to do this here so we can ensure the type is correct and return\n      -- a meaningful error message otherwise\n      let (e, _) \u2190 Lean.Elab.Term.levelMVarToParam\n                    (\u2190 Lean.Meta.instantiateMVars e)\n      let e_type \u2190 Lean.Meta.inferType e\n      if (\u2190 Lean.Meta.isProp e) then\n        Lean.Meta.mkDecide e\n      else if (\u2190 Lean.Meta.isDefEq e_type ebool) then\n        return e\n      else\n        throwError m!\"Tests must be of type Bool or Prop, but got '{e_type}'\"\n    let elabEval : Lean.Elab.Command.CommandElabM Unit :=\n    Lean.Elab.Command.runTermElabM (some n) (\u03bb _ => do\n      let e \u2190 elabEvalTerm\n      let env \u2190 Lean.getEnv\n      let res \u2190 try addAndCompile e; Lean.evalConst Bool n\n                finally Lean.setEnv env\n      if res\n      then Lean.Elab.logInfoAt tk \"Test passed\"\n      else Lean.Elab.logErrorAt tk \"Test failed\")\n    elabEval\n| _ => Lean.Elab.throwUnsupportedSyntax\n\n-- Ways of making type class inference work where Lean struggles\ndef instHint (\u03b1 : Type _) (x : \u03b1) (y : \u03b1) (inst : DecidableEq \u03b1) :=\n  decide (x = y)\n\nmacro \"inst\" : tactic =>\n  `(repeat (first\n    | apply instDecidableEqTable (inst := _)\n    | apply instDecidableEqRowConsHeaderMkType (it := _) (ic := _) (ir := _)\n    | apply instDecidableEqRowNilHeader\n    | apply instDecidableEqCell (inst := _)\n    | infer_instance))\n\nnotation lhs \"=(\" tp \")\" rhs => instHint tp lhs rhs inferInstance\n\nnotation lhs \"=[\" inst \"]\" rhs => instHint _ lhs rhs inst\n\nnotation lhs \"=(\" tp \")[\" inst \"]\" rhs => instHint tp lhs rhs inst\n\n-- `addRows`\n#test\naddRows students [/[\"Colton\", 19, \"blue\"]]\n=\nTable.mk [\n  /[\"Bob\"  , 12, \"blue\" ],\n  /[\"Alice\", 17, \"green\"],\n  /[\"Eve\"  , 13, \"red\"  ],\n  /[\"Colton\", 19, \"blue\"]\n]\n\n#test\naddRows gradebook []\n=\nTable.mk [\n  /[\"Bob\"  , 12, 8, 9, 77, 7, 9, 87],\n  /[\"Alice\", 17, 6, 8, 88, 8, 7, 85],\n  /[\"Eve\"  , 13, 7, 9, 84, 8, 8, 77]\n]\n\n-- `addColumn`\ndef hairColor := [some \"brown\", some \"red\", some \"blonde\"]\n#test\naddColumn students \"hair-color\" hairColor\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , \"brown\"    ],\n  /[ \"Alice\" , 17  , \"green\"        , \"red\"      ],\n  /[ \"Eve\"   , 13  , \"red\"          , \"blonde\"   ]\n]\n\ndef presentation := [some 9, some 9, some 6]\n#test\naddColumn gradebook \"presentation\" presentation\n=[by inst]\nTable.mk [\n  /[ \"Bob\"  , 12, 8, 9, 77, 7, 9, 87, 9],\n  /[ \"Alice\", 17, 6, 8, 88, 8, 7, 85, 9],\n  /[ \"Eve\"  , 13, 7, 9, 84, 8, 8, 77, 6]\n]\n\n-- `buildColumn`\ndef isTeenagerBuilder := \u03bb (r : Row $ schema students) =>\n  match getValue r \"age\" (by header) with\n  | some age => some (12 < age && age < 20)\n  | _ => some false\n#test\nbuildColumn students \"is-teenager\" isTeenagerBuilder\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , false       ],\n  /[ \"Alice\" , 17  , \"green\"        , true        ],\n  /[ \"Eve\"   , 13  , \"red\"          , true        ]\n]\n\ndef didWellOnFinal : Row (schema gradebook) \u2192 Option Bool := \u03bb r =>\n  match getValue r \"final\" (by header) with\n  | some score => some $ 85 <= score\n  | _ => some false\n#test\nbuildColumn gradebook \"did-well-on-final\" didWellOnFinal\n=[by inst]\nTable.mk [\n  /[ \"Bob\"  , 12, 8, 9, 77, 7, 9, 87, true ],\n  /[ \"Alice\", 17, 6, 8, 88, 8, 7, 85, true ],\n  /[ \"Eve\"  , 13, 7, 9, 84, 8, 8, 77, false]\n]\n\n-- `vcat`\ndef increaseAge := \u03bb (r : Row $ schema students) =>\n  ((\n    Row.cons\n      (Cell.fromOption $ (getValue r \"age\" (by header)).map (\u03bb x => x + 1))\n      Row.nil\n  )\n  : Row [(\"age\", Nat)])\n\n#test\nvcat students (update [\u27e8(\"age\", Nat), by header\u27e9] students increaseAge)\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         ],\n  /[ \"Alice\" , 17  , \"green\"        ],\n  /[ \"Eve\"   , 13  , \"red\"          ],\n  /[ \"Bob\"   , 13  , \"blue\"         ],\n  /[ \"Alice\" , 18  , \"green\"        ],\n  /[ \"Eve\"   , 14  , \"red\"          ]\n]\n\ndef curveMidtermAndFinal := \u03bb (r : Row $ schema gradebook) =>\n  let curve := \u03bb | some n => some (n + 5)\n                 | _ => none\n  let midterm := getValue r \"midterm\" (by header)\n  let final := getValue r \"final\" (by header)\n  (Row.cons (Cell.fromOption $ curve midterm) $\n     Row.cons (Cell.fromOption $ curve final) Row.nil\n   : Row [(\"midterm\", Nat), (\"final\", Nat)])\n\n#test\nvcat gradebook (update [\u27e8(\"midterm\", Nat), by header\u27e9,  \n                        \u27e8(\"final\", Nat), by header\u27e9] gradebook\n                                                     curveMidtermAndFinal)\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     , 77    ],\n  /[ \"Bob\"   , 12  , 8     , 9     , 82      , 7     , 9     , 92    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 93      , 8     , 7     , 90    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 89      , 8     , 8     , 82    ]\n]\n\n-- `hcat`\n#test\nhcat students (dropColumns gradebook A[\u27e8\"name\", by name\u27e9, \u27e8\"age\", by name\u27e9])\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , 8     , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"Alice\" , 17  , \"green\"        , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , \"red\"          , 7     , 9     , 84      , 8     , 8     , 77    ]\n]\n\n#test\nhcat (dropColumns students A[\u27e8\"name\", by name\u27e9, \u27e8\"age\", by name\u27e9]) gradebook\n=\nTable.mk [\n  /[ \"blue\"         , \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"green\"        , \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"red\"          , \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     , 77    ]\n]\n\n-- `values`\n#test\nvalues [/[\"Alice\"], /[\"Bob\"]]\n=\n(Table.mk [\n  /[\"Alice\"],\n  /[\"Bob\"]\n] : Table [(\"name\", String)])\n\n#test\nvalues [/[\"Alice\", 12], /[\"Bob\", 13]]\n=\n(Table.mk [\n  /[\"Alice\", 12],\n  /[\"Bob\", 13]\n] : Table [(\"name\", String), (\"age\", Nat)])\n\n-- `crossJoin`\ndef petiteJelly :=\nselectRows1 (selectColumns2 jellyAnon [\u27e80, by simp\u27e9, \u27e81, by simp\u27e9, \u27e82, by simp\u27e9])\n            [\u27e80, by simp\u27e9, \u27e81, by simp\u27e9]\n#test\ncrossJoin students petiteJelly\n=[by simp [List.nth, List.nths, List.map]; inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , true     , false , false ],\n  /[ \"Bob\"   , 12  , \"blue\"         , true     , false , true  ],\n  /[ \"Alice\" , 17  , \"green\"        , true     , false , false ],\n  /[ \"Alice\" , 17  , \"green\"        , true     , false , true  ],\n  /[ \"Eve\"   , 13  , \"red\"          , true     , false , false ],\n  /[ \"Eve\"   , 13  , \"red\"          , true     , false , true  ]\n]\n\n#test\ncrossJoin emptyTable petiteJelly\n=[by simp [List.nth, List.nths, List.map]; inst]\nTable.mk []\n\n-- `leftJoin`\n-- TODO: we need the `header` (and probably `name`) tactic to be able to \"see\n-- through\" the various Schema ActionList functions like `removeOtherDecCH`\n#test\nleftJoin students gradebook A[\u27e8(\"name\", _), inferInstance, by header, by header\u27e9,\n                               \u27e8(\"age\", _), inferInstance, by simp only [Schema.removeOtherDecCH]; header, by header\u27e9]\n=(Table [(\"name\", String), (\"age\", Nat), (\"favorite color\", String),\n         (\"quiz1\", Nat), (\"quiz2\", Nat), (\"midterm\", Nat), (\"quiz3\", Nat),\n         (\"quiz4\", Nat), (\"final\", Nat)])\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , 8     , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"Alice\" , 17  , \"green\"        , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , \"red\"          , 7     , 9     , 84      , 8     , 8     , 77    ]\n]\n\n#test\nleftJoin employees departments A[\u27e8(\"Department ID\", _), inferInstance, by header, by header\u27e9]\n=\nTable.mk [\n  /[ \"Rafferty\"   , 31            , \"Sales\"         ],\n  /[ \"Jones\"      , 32            , EMP             ],\n  /[ \"Heisenberg\" , 33            , \"Engineering\"   ],\n  /[ \"Robinson\"   , 34            , \"Clerical\"      ],\n  /[ \"Smith\"      , 34            , \"Clerical\"      ],\n  /[ \"Williams\"   , EMP           , EMP             ]\n]\n\n#eval leftJoin\n(Table.mk [\n  /[\"name\" := \"Bob\", \"age\" := 18]\n])\n(Table.mk [\n  /[\"name\" := \"Bob\", \"location\" := \"USA\"],\n  /[\"name\" := \"Bob\", \"location\" := \"UK\"]\n])\nA[\u27e8(\"name\", _), inferInstance, by header, by header\u27e9]\n\n-- `nrows`\n#test nrows (@emptyTable String _) = 0\n\n#test nrows studentsMissing = 3\n\n-- `ncols`\n#test ncols students = 3\n\n#test ncols studentsMissing = 3\n\n-- `header`\n#test header students = [\"name\", \"age\", \"favorite color\"]\n\n#test\nheader gradebook\n=\n[\"name\", \"age\", \"quiz1\", \"quiz2\", \"midterm\", \"quiz3\", \"quiz4\", \"final\"]\n\n-- `getRow`\n#test\ngetRow students 0 (by simp)\n=\n/[\"Bob\", 12, \"blue\"]\n\n#test\ngetRow gradebook 1 (by simp)\n=\n/[\"Alice\", 17, 6, 8, 88, 8, 7, 85]\n\n-- `getValue`\n#test\ngetValue /[\"name\" := \"Bob\", \"age\" := 12] \"name\" (by header)\n=\nsome \"Bob\"\n\n#test\ngetValue /[\"name\" := \"Bob\", \"age\" := 12] \"age\" (by header)\n=\nsome 12\n\n-- `getColumn1`\n#test\ngetColumn1 students 1 (by simp)\n=(List $ Option Nat)\n[some 12, some 17, some 13]\n\n#test\ngetColumn1 gradebook 0 (by simp)\n=(List $ Option String)\n[some \"Bob\", some \"Alice\", some \"Eve\"]\n\n-- `getColumn2`\n#test\ngetColumn2 students \"age\" (by header)\n=\n[some 12, some 17, some 13]\n\n#test\ngetColumn2 gradebook \"name\" (by header)\n=\n[some \"Bob\", some \"Alice\", some \"Eve\"]\n\n-- `selectRows1`\n#test\nselectRows1 students [\u27e82, by simp\u27e9, \u27e80, by simp\u27e9, \u27e82, by simp\u27e9, \u27e81, by simp\u27e9]\n=\nTable.mk [\n  /[ \"Eve\"   , 13  , \"red\"          ],\n  /[ \"Bob\"   , 12  , \"blue\"         ],\n  /[ \"Eve\"   , 13  , \"red\"          ],\n  /[ \"Alice\" , 17  , \"green\"        ]\n]\n\n#test\nselectRows1 gradebook [\u27e82, by simp\u27e9, \u27e81, by simp\u27e9]\n=\nTable.mk [\n  /[ \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     , 77    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     , 85    ]\n]\n\n-- `selectRows2`\n#test\nselectRows2 students [true, false, true] (by simp)\n=\nTable.mk [\n  /[ \"Bob\" , 12  , \"blue\"         ],\n  /[ \"Eve\" , 13  , \"red\"          ]\n]\n\n#test\nselectRows2 gradebook [false, false, true] (by simp)\n=\nTable.mk [/[\"Eve\", 13, 7, 9, 84, 8, 8, 77]]\n\n-- `selectColumns1`\n#test\nselectColumns1 students [true, true, false] (by simp)\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  ],\n  /[ \"Alice\" , 17  ],\n  /[ \"Eve\"   , 13  ]\n]\n\n#test\nselectColumns1 gradebook [true, false, false, false, true, false, false, true] (by simp)\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 77      , 87    ],\n  /[ \"Alice\" , 88      , 85    ],\n  /[ \"Eve\"   , 84      , 77    ]\n]\n\n-- `selectColumns2`\n#test\nselectColumns2 students [\u27e82, by simp\u27e9, \u27e81, by simp\u27e9]\n=(Table [(\"favorite color\", String), (\"age\", Nat)])\nTable.mk [\n  /[ \"blue\"         , 12  ],\n  /[ \"green\"        , 17  ],\n  /[ \"red\"          , 13  ]\n]\n\n#test\nselectColumns2 gradebook [\u27e87, by simp\u27e9, \u27e80, by simp\u27e9, \u27e84, by simp\u27e9]\n=(Table [(_, Nat), (_, String), (_, Nat)])\nTable.mk [\n  /[ 87    , \"Bob\"   , 77      ],\n  /[ 85    , \"Alice\" , 88      ],\n  /[ 77    , \"Eve\"   , 84      ]\n]\n\n-- `selectColumns3`\n#test\nselectColumns3 students [\u27e8(\"favorite color\", _), by header\u27e9, \u27e8(\"age\", _), by header\u27e9]\n=(Table [(\"favorite color\", String), (\"age\", Nat)])\nTable.mk [\n  /[ \"blue\"         , 12  ],\n  /[ \"green\"        , 17  ],\n  /[ \"red\"          , 13  ]\n]\n\n#test\nselectColumns3 gradebook [\u27e8(\"final\", _), by header\u27e9, \u27e8(\"name\", _), by header\u27e9, \u27e8(\"midterm\", _), by header\u27e9]\n=(Table [(\"final\", Nat), (\"name\", String), (\"midterm\", Nat)])\nTable.mk [\n  /[ 87    , \"Bob\"   , 77      ],\n  /[ 85    , \"Alice\" , 88      ],\n  /[ 77    , \"Eve\"   , 84      ]\n]\n\n-- `head`\n#test\nhead students \u27e81, by simp\u27e9\n=\nTable.mk [ /[\"Bob\", 12, \"blue\"]]\n\n#test\nhead students \u27e8-2, by simp\u27e9\n=\nTable.mk [ /[\"Bob\", 12, \"blue\"]]\n\n-- `distinct`\n#test\ndistinct students\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         ],\n  /[ \"Alice\" , 17  , \"green\"        ],\n  /[ \"Eve\"   , 13  , \"red\"          ]\n]\n\n#test\ndistinct (selectColumns3 gradebook [\u27e8(\"quiz3\", _), by header\u27e9])\n=(Table [(\"quiz3\", Nat)])\nTable.mk [ /[7], /[8] ]\n\n-- `dropColumn`\n#test\ndropColumn students \u27e8\"age\", by name\u27e9\n=(Table [(\"name\", String), (\"favorite color\", String)])\nTable.mk [\n  /[ \"Bob\"   , \"blue\"         ],\n  /[ \"Alice\" , \"green\"        ],\n  /[ \"Eve\"   , \"red\"          ]\n]\n\n#test\ndropColumn gradebook \u27e8\"final\", by name\u27e9\n=(Table [(\"name\", String), (\"age\", Nat), (\"quiz1\", Nat), (\"quiz2\", Nat), (\"midterm\", Nat), (\"quiz3\", Nat), (\"quiz4\", Nat)])\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     ],\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     ]\n]\n\n-- `dropColumns`\n#test\ndropColumns students A[\u27e8\"age\", by name\u27e9]\n=(Table [(\"name\", String), (\"favorite color\", String)])\nTable.mk [\n  /[ \"Bob\"   , \"blue\"         ],\n  /[ \"Alice\" , \"green\"        ],\n  /[ \"Eve\"   , \"red\"          ]\n]\n\n#test\ndropColumns gradebook A[\u27e8\"final\", by name\u27e9, \u27e8\"midterm\", by name\u27e9]\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 7     , 9     ],\n  /[ \"Alice\" , 17  , 6     , 8     , 8     , 7     ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 8     , 8     ]\n]\n\n-- `tfilter`\ndef ageUnderFifteen : (Row $ schema students) \u2192 Bool := \u03bb r =>\n  match getValue r \"age\" (by header) with\n  | some a => a < 15\n  | _ => false\n\n#test\ntfilter students ageUnderFifteen\n=\nTable.mk [\n  /[ \"Bob\" , 12  , \"blue\"         ],\n  /[ \"Eve\" , 13  , \"red\"          ]\n]\n\ndef nameLongerThan3Letters : (Row $ schema gradebook) \u2192 Bool := \u03bb r =>\n  match getValue r \"name\" (by header) with\n  | some name => String.length name > 3\n  | _ => false\n\n#test\ntfilter gradebook nameLongerThan3Letters\n=\nTable.mk [/[\"Alice\", 17, 6, 8, 88, 8, 7, 85]]\n\n-- `tsort`\n#test\ntsort students \u27e8\"age\", by header\u27e9 true\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         ],\n  /[ \"Eve\"   , 13  , \"red\"          ],\n  /[ \"Alice\" , 17  , \"green\"        ]\n]\n\n#test\ntsort gradebook \u27e8\"final\", by header\u27e9 false\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     , 77    ]\n]\n\n-- `sortByColumns`\n#test\nsortByColumns students [\u27e8(\"age\", Nat), by header, inferInstance\u27e9]\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         ],\n  /[ \"Eve\"   , 13  , \"red\"          ],\n  /[ \"Alice\" , 17  , \"green\"        ]\n]\n\n#test\nsortByColumns gradebook [\u27e8(\"quiz2\", Nat), by header, inferInstance\u27e9,\n                         \u27e8(\"quiz1\", Nat), by header, inferInstance\u27e9]\n=\nTable.mk [\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     , 77    ],\n  /[ \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     , 87    ]\n]\n\n-- `orderBy`\ndef nameLengthOB (r : Row $ schema students) :=\n  match getValue r \"name\" (by header) with\n  | some s => String.length s\n  | _ => 0\n\ndef leOB := (\u03bb (a : Nat) b => decide $ a \u2264 b)\n\n#test\norderBy students [\u27e8_, nameLengthOB, leOB\u27e9]\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         ],\n  /[ \"Eve\"   , 13  , \"red\"          ],\n  /[ \"Alice\" , 17  , \"green\"        ]\n]\n\ndef geOB := (\u03bb (a : Nat) b => decide $ a \u2265 b)\n\ndef nameLengthOB' (r : Row $ schema gradebook) :=\n  match getValue r \"name\" (by header) with\n  | some s => String.length s\n  | _ => 0\n\ndef averageOB (xs : List $ Option Nat) :=\n  List.foldl (\u03bb acc => \u03bb | none => acc | some x => x + acc) 0 xs / xs.length\n\ndef midtermAndFinalOB (r : Row $ schema gradebook) : List $ Option Nat :=\n  [getValue r \"midterm\" (by header), getValue r \"final\" (by header)]\n\ndef compareGradeOB (g1 : List $ Option Nat) (g2 : List $ Option Nat) :=\n  leOB (averageOB g1) (averageOB g2)\n\n#test\norderBy gradebook [\u27e8_, nameLengthOB', geOB\u27e9, \u27e8_, midtermAndFinalOB, compareGradeOB\u27e9]\n=\nTable.mk [\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 84      , 8     , 8     , 77    ],\n  /[ \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     , 87    ]\n]\n\n-- `count`\n#test\ncount students \u27e8\"favorite color\", by header\u27e9\n=\nTable.mk [\n  /[ some \"blue\"  , 1     ],\n  /[ some \"green\" , 1     ],\n  /[ some \"red\"   , 1     ]\n]\n\n#test\ncount gradebook \u27e8\"age\", by header\u27e9\n=\nTable.mk [\n  /[ some 12    , 1     ],\n  /[ some 17    , 1     ],\n  /[ some 13    , 1     ]\n]\n\n-- `bin`\n#test\nbin students \u27e8\"age\", by header\u27e9 \u27e85, by simp\u27e9\n=\nTable.mk [\n  /[ \"10 <= age < 15\" , 2     ],\n  /[ \"15 <= age < 20\" , 1     ]\n]\n\n-- TODO: tell B2T2 that there's a typo in this test (\"final,\" not \"age\")\n#test\nbin gradebook \u27e8\"final\", by header\u27e9 \u27e85, by simp\u27e9\n=\nTable.mk [\n  /[ \"75 <= final < 80\" , 1     ],\n  /[ \"80 <= final < 85\" , 0     ],\n  /[ \"85 <= final < 90\" , 2     ]\n]\n\n-- `pivotTable`\ndef oAverage (xs : List $ Option Nat) : Option Nat := some $\n  List.foldl (\u03bb acc => \u03bb | none => acc | some x => x + acc) 0 xs / xs.length\n\n#test\npivotTable students [\u27e8(\"favorite color\", _), by header\u27e9] (by inst) [\u27e8(\"age-average\", _), \u27e8(\"age\", _), by header\u27e9, oAverage\u27e9]\n=[by inst]\nTable.mk [\n  /[ \"blue\"         , 12          ],\n  /[ \"green\"        , 17          ],\n  /[ \"red\"          , 13          ]\n]\n\n-- Slightly modified since we aren't using decimals\ndef proportion (bs : List $ Option Bool) : Option Nat := some $\n  (100 * (bs.filter (\u03bb | some true => true | _ => false)).length) / bs.length\n\n-- TODO: does order matter?\n#test\npivotTable\n  jellyNamed\n  [\u27e8(\"get acne\", Bool), by header\u27e9, \u27e8(\"brown\", _), by header\u27e9]\n  (by inst)\n  [\u27e8(\"red-proportion\", _), \u27e8(\"red\", _), by header\u27e9, proportion\u27e9,\n   \u27e8(\"pink-proportion\", _), \u27e8(\"pink\", _), by header\u27e9, proportion\u27e9]\n=[by inst]\nTable.mk [\n  /[ false    , false , 0              , 75              ],\n  /[ false    , true  , 100            , 100             ],\n  /[ true     , false , 0              , 25              ],\n  /[ true     , true  , 0              , 0               ]\n]\n\n-- `groupBy`\n-- TODO: handle `none` case?\ndef colorTemp : (Row $ schema students) \u2192 String := \u03bb r =>\n  match getValue r \"favorite color\" (by header) with\n  | some \"red\" => \"warm\"\n  | _ => \"cool\"\n\ndef nameLength : (Row $ schema students) \u2192 Nat := \u03bb r =>\n  match getValue r \"name\" (by header) with\n  | some s => String.length s\n  | _ => 0\n\ndef average (xs : List Nat) := List.foldl (\u00b7+\u00b7) 0 xs / xs.length\n\ndef aggregate := \u03bb (k : String) vs =>\n/[\"key\" := k, \"average\" := average vs]\n\n-- TODO: Need to double-check, but this seems to me like the correct output --\n-- the first row matches \"cool,\" so order preservation would tell us that this\n-- order (and not the reversed order in the B2T2 docs) is most reasonable\n-- (B2T2 TS is using unordered maps in the implementation of `groupBy`, which is\n-- probably why its order is different)\n#test\ngroupBy students colorTemp nameLength aggregate\n=\nTable.mk [\n  /[ \"cool\" , 4       ],\n  /[ \"warm\" , 3       ]\n]\n\ndef abstractAge := \u03bb (r : Row $ schema gradebook) =>\n  match getValue r \"age\" (by header) with\n  | some age =>\n    match (age \u2264 12 : Bool), (age \u2264 19 : Bool) with\n    | true, _ => \"kid\"\n    | _, true => \"teenager\"\n    | _, _ => \"adult\"\n  | _ => \"\"\n\ndef finalGrade := \u03bb (r : Row $ schema gradebook) =>\n  match getValue r \"final\" (by header) with\n  | some grade => grade\n  | _ => 0\n\n#test\ngroupBy gradebook abstractAge finalGrade aggregate\n=\nTable.mk [\n  /[ \"kid\"      , 87      ],\n  /[ \"teenager\" , 81      ]\n]\n\n-- `completeCases`\n#test\ncompleteCases students \u27e8\"age\", by header\u27e9\n=\n[true, true, true]\n\n#test\ncompleteCases studentsMissing \u27e8\"age\", by header\u27e9\n=\n[false, true, true]\n\n-- `dropna`\n#test\ndropna studentsMissing\n=\nTable.mk [/[\"Alice\", 17, \"green\"]]\n\n#test\ndropna gradebookMissing\n=\nTable.mk [/[\"Bob\", 12, 8, 9, 77, 7, 9, 87]]\n\n-- `fillna`\n#test\nfillna studentsMissing \u27e8\"favorite color\", by header\u27e9 \"white\"\n=\nTable.mk [\n  /[ \"Bob\"   , EMP, \"blue\"],\n  /[ \"Alice\" , 17 , \"green\"],\n  /[ \"Eve\"   , 13 , \"white\"]\n]\n\n#test\nfillna gradebookMissing \u27e8\"quiz1\", by header\u27e9 0\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 88      , EMP   , 7     , 85    ],\n  /[ \"Eve\"   , 13  , 0     , 9     , 84      , 8     , 8     , 77    ]\n]\n\n-- `pivotLonger`\n-- TODO: more typeclass issues...\n#test\npivotLonger gradebook A[\u27e8\"midterm\", by header\u27e9, \u27e8\"final\", by header\u27e9] \"exam\" \"score\"\n=[by simp [Schema.removeTypedNames, Schema.removeTypedName, Schema.removeHeader, Schema.removeName]; inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 7     , 9     , \"midterm\" , 77    ],\n  /[ \"Bob\"   , 12  , 8     , 9     , 7     , 9     , \"final\"   , 87    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 8     , 7     , \"midterm\" , 88    ],\n  /[ \"Alice\" , 17  , 6     , 8     , 8     , 7     , \"final\"   , 85    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 8     , 8     , \"midterm\" , 84    ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 8     , 8     , \"final\"   , 77    ]\n]\n\n#test\npivotLonger gradebook A[\u27e8\"quiz1\", by header\u27e9, \u27e8\"quiz2\", by header\u27e9,\n                        \u27e8\"quiz3\", by header\u27e9, \u27e8\"quiz4\", by header\u27e9,\n                        \u27e8\"midterm\", by header\u27e9, \u27e8\"final\", by header\u27e9]\n            \"test\" \"score\"\n=(Table [(\"name\", String), (\"age\", Nat), (\"test\", String), (\"score\", Nat)])\nTable.mk [\n  /[ \"Bob\"   , 12  , \"quiz1\"   , 8     ],\n  /[ \"Bob\"   , 12  , \"quiz2\"   , 9     ],\n  /[ \"Bob\"   , 12  , \"quiz3\"   , 7     ],\n  /[ \"Bob\"   , 12  , \"quiz4\"   , 9     ],\n  /[ \"Bob\"   , 12  , \"midterm\" , 77    ],\n  /[ \"Bob\"   , 12  , \"final\"   , 87    ],\n  /[ \"Alice\" , 17  , \"quiz1\"   , 6     ],\n  /[ \"Alice\" , 17  , \"quiz2\"   , 8     ],\n  /[ \"Alice\" , 17  , \"quiz3\"   , 8     ],\n  /[ \"Alice\" , 17  , \"quiz4\"   , 7     ],\n  /[ \"Alice\" , 17  , \"midterm\" , 88    ],\n  /[ \"Alice\" , 17  , \"final\"   , 85    ],\n  /[ \"Eve\"   , 13  , \"quiz1\"   , 7     ],\n  /[ \"Eve\"   , 13  , \"quiz2\"   , 9     ],\n  /[ \"Eve\"   , 13  , \"quiz3\"   , 8     ],\n  /[ \"Eve\"   , 13  , \"quiz4\"   , 8     ],\n  /[ \"Eve\"   , 13  , \"midterm\" , 84    ],\n  /[ \"Eve\"   , 13  , \"final\"   , 77    ]\n]\n\n-- TODO: `pivotWider`\n\n-- `flatten`\n#test\nflatten gradebookSeq A[\u27e8\"quizzes\", _, by header\u27e9]\n=(Table [(\"name\", String), (\"age\", Nat), (\"quizzes\", Nat), (\"midterm\", Nat), (\"final\", Nat)])\nTable.mk [\n  /[ \"Bob\"   , 12  , 8       , 77      , 87    ],\n  /[ \"Bob\"   , 12  , 9       , 77      , 87    ],\n  /[ \"Bob\"   , 12  , 7       , 77      , 87    ],\n  /[ \"Bob\"   , 12  , 9       , 77      , 87    ],\n  /[ \"Alice\" , 17  , 6       , 88      , 85    ],\n  /[ \"Alice\" , 17  , 8       , 88      , 85    ],\n  /[ \"Alice\" , 17  , 8       , 88      , 85    ],\n  /[ \"Alice\" , 17  , 7       , 88      , 85    ],\n  /[ \"Eve\"   , 13  , 7       , 84      , 77    ],\n  /[ \"Eve\"   , 13  , 9       , 84      , 77    ],\n  /[ \"Eve\"   , 13  , 8       , 84      , 77    ],\n  /[ \"Eve\"   , 13  , 8       , 84      , 77    ]\n]\n\ndef t := buildColumn gradebookSeq \"quiz-pass?\" (\u03bb r => \n  let isPass : Nat \u2192 Bool := \u03bb n => n >= 8\n  (getValue r \"quizzes\" (by header)).map (List.map isPass)\n)\n\n#test\nflatten t A[\u27e8\"quiz-pass?\", _, by header\u27e9, \u27e8\"quizzes\", _, by header\u27e9]\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , 8       , 77      , 87    , true       ],\n  /[ \"Bob\"   , 12  , 9       , 77      , 87    , true       ],\n  /[ \"Bob\"   , 12  , 7       , 77      , 87    , false      ],\n  /[ \"Bob\"   , 12  , 9       , 77      , 87    , true       ],\n  /[ \"Alice\" , 17  , 6       , 88      , 85    , false      ],\n  /[ \"Alice\" , 17  , 8       , 88      , 85    , true       ],\n  /[ \"Alice\" , 17  , 8       , 88      , 85    , true       ],\n  /[ \"Alice\" , 17  , 7       , 88      , 85    , false      ],\n  /[ \"Eve\"   , 13  , 7       , 84      , 77    , false      ],\n  /[ \"Eve\"   , 13  , 9       , 84      , 77    , true       ],\n  /[ \"Eve\"   , 13  , 8       , 84      , 77    , true       ],\n  /[ \"Eve\"   , 13  , 8       , 84      , 77    , true       ]\n]\n\n\ndef unbalancedTable :\n  Table [(\"id\", Nat), (\"seq1\", List Nat), (\"seq2\", List String)] :=\nTable.mk [\n  /[0, [0, 1, 2], [\"a\", \"b\"]],\n  /[1, [], [\"c\"]],\n  /[2, [3, 4], [\"d\", \"e\", \"f\"]],\n  /[3, [5, 6], []],\n  /[4, [], []]\n]\n\n-- This behavior matches the B2T2 implementation, although I don't think the\n-- behavior of leaving row 4 in the first eval is actually what we'd want.\n-- (And I'd argue that leaving the last row in the second example actually\n-- violates the spec.)\n-- One potential workaround would be to check after each flattening to see if\n-- the last row we get is equal (up to cell emptiness -- no need for DecEq)\n-- to the clean template row and ditch it if so. (Even more ugly dynamicity, but\n-- so it goes...)\n-- TODO: notify B2T2 that their implementation crashes on the (valid) example\n-- given by the row with ID 4.\n#eval flatten unbalancedTable A[\u27e8\"seq1\", _, by header\u27e9]\n#eval flatten unbalancedTable A[\u27e8\"seq1\", _, by header\u27e9, \u27e8\"seq2\", _, by header\u27e9]\n\n-- FIXME: more typeclass issues\n-- `transformColumn`\ndef addLastName := Option.map (\u00b7 ++ \" Smith\")\n\n#test\ntransformColumn students \u27e8\"name\", by header\u27e9 addLastName\n=(Table [(\"name\", String), (\"age\", Nat), (\"favorite color\", String)])\nTable.mk [\n  /[ \"Bob Smith\"   , 12  , \"blue\"         ],\n  /[ \"Alice Smith\" , 17  , \"green\"        ],\n  /[ \"Eve Smith\"   , 13  , \"red\"          ]\n]\n\ndef quizScoreToPassFail := Option.map (\u03bb n =>\n  if n <= 6\n  then \"fail\"\n  else \"pass\")\n\n#test\ntransformColumn gradebook \u27e8\"quiz1\", by header\u27e9 quizScoreToPassFail\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , \"pass\" , 9     , 77      , 7     , 9     , 87    ],\n  /[ \"Alice\" , 17  , \"fail\" , 8     , 88      , 8     , 7     , 85    ],\n  /[ \"Eve\"   , 13  , \"pass\" , 9     , 84      , 8     , 8     , 77    ]\n]\n\n-- `renameColumns`\n#test\nrenameColumns students A[\u27e8\u27e8\"favorite color\", by name\u27e9, \"preferred color\"\u27e9,\n                         \u27e8\u27e8\"name\", by name\u27e9, \"first name\"\u27e9]\n=(Table [(\"first name\", String), (\"age\", Nat), (\"preferred color\", String)])\nTable.mk [\n  /[ \"Bob\"      , 12  , \"blue\"          ],\n  /[ \"Alice\"    , 17  , \"green\"         ],\n  /[ \"Eve\"      , 13  , \"red\"           ]\n]\n\n#test\nrenameColumns gradebook A[\u27e8\u27e8\"midterm\", by name\u27e9, \"final\"\u27e9,\n                          \u27e8\u27e8\"final\", by name\u27e9, \"midterm\"\u27e9]\n=(Table [(\"name\", String), (\"age\", Nat), (\"quiz1\", Nat), (\"quiz2\", Nat),\n         (\"final\", Nat), (\"quiz3\", Nat), (\"quiz4\", Nat), (\"final\", Nat)])\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , 77    , 7     , 9     , 87      ],\n  /[ \"Alice\" , 17  , 6     , 8     , 88    , 8     , 7     , 85      ],\n  /[ \"Eve\"   , 13  , 7     , 9     , 84    , 8     , 8     , 77      ]\n]\n\n-- `find`\n#test\nfind [\u27e8(\"age\", Nat), by header, inferInstance\u27e9] students /[\"age\" := 13]\n=\nsome \u27e82, by simp\u27e9\n\n#test\nfind [\u27e8(\"age\", _), by header, inferInstance\u27e9] students /[\"age\" := 14]\n=\nnone\n\n-- `groupByRetentive`\n-- Deal with ULift decidable equality\nderiving instance DecidableEq for ULift\n\n#test\ngroupByRetentive students \u27e8\"favorite color\", by header\u27e9\n=\nTable.mk [\n  /[ULift.up \"blue\" , Table.mk [\n                        /[\"Bob\"  , 12, \"blue\" ]]],\n  /[ULift.up \"green\", Table.mk [\n                        /[\"Alice\", 17, \"green\"]]],\n  /[ULift.up \"red\"  , Table.mk [\n                        /[\"Eve\"  , 13, \"red\"  ]]]\n]\n\n#test\ngroupByRetentive jellyAnon \u27e8\"brown\", by header\u27e9\n=[by inst]\nTable.mk [\n  /[ULift.up false, Table.mk [\n    /[ true     , false , false , false , true  , false  , false , true   , false , false  ],\n    /[ true     , false , true  , false , true  , true   , false , false  , false , false  ],\n    /[ false    , false , false , false , true  , false  , false , false  , true  , false  ],\n    /[ false    , false , false , false , false , true   , false , false  , false , false  ],\n    /[ false    , false , false , false , false , true   , false , false  , true  , false  ],\n    /[ true     , false , true  , false , false , false  , false , true   , true  , false  ],\n    /[ false    , false , true  , false , false , false  , false , false  , true  , false  ],\n    /[ true     , false , false , false , false , false  , false , true   , false , false  ]\n  ]],\n  /[ULift.up true, Table.mk [\n    /[ true     , false , false , false , false , false  , true  , true   , false , false  ],\n    /[ false    , true  , false , false , false , true   , true  , false  , true  , false  ]\n  ]]\n]\n\n-- `groupBySubtractive`\n-- TODO: why does the `header` tactic fail here?\n-- Interestingly, only fails when we have the equality test -- evaluating\n-- `groupBySubtractive` alone works just fine\n#test\ngroupBySubtractive students \u27e8\"favorite color\", Schema.HasCol.tl (Schema.HasCol.tl (Schema.HasCol.hd))\u27e9\n=[by inst]\nTable.mk [\n  /[ULift.up \"blue\" , Table.mk [/[\"Bob\"  , 12]]],\n  /[ULift.up \"green\", Table.mk [/[\"Alice\", 17]]],\n  /[ULift.up \"red\", Table.mk [/[\"Eve\"  , 13]]]\n]\n\n#test\ngroupBySubtractive jellyAnon \u27e8\"brown\",\n  Schema.HasCol.tl $ Schema.HasCol.tl $ Schema.HasCol.tl $ Schema.HasCol.tl $\n    Schema.HasCol.tl $ Schema.HasCol.tl $ Schema.HasCol.hd\u27e9\n=[by inst]\nTable.mk [\n  /[ULift.up false, Table.mk [\n    /[ true     , false , false , false , true  , false  , true   , false , false  ],\n    /[ true     , false , true  , false , true  , true   , false  , false , false  ],\n    /[ false    , false , false , false , true  , false  , false  , true  , false  ],\n    /[ false    , false , false , false , false , true   , false  , false , false  ],\n    /[ false    , false , false , false , false , true   , false  , true  , false  ],\n    /[ true     , false , true  , false , false , false  , true   , true  , false  ],\n    /[ false    , false , true  , false , false , false  , false  , true  , false  ],\n    /[ true     , false , false , false , false , false  , true   , false , false  ]\n  ]],\n  /[ULift.up true, Table.mk [\n    /[ true     , false , false , false , false , false  , true   , false , false  ],\n    /[ false    , true  , false , false , false , true   , false  , true  , false  ]\n  ]]\n]\n\n-- `update`\ndef abstractAgeUpdate := \u03bb (r : Row $ schema students) =>\n  match getValue r \"age\" (by header) with\n  | some age =>\n    match (age \u2264 12 : Bool), (age \u2264 19 : Bool) with\n    | true, _ => /[\"age\" := \"kid\"]\n    | _, true => /[\"age\" := \"teenager\"]\n    | _, _ => /[\"age\" := \"adult\"]\n  | _ => /[\"age\" := EMP]\n\n#test\nupdate [\u27e8(\"age\", String), _\u27e9] students abstractAgeUpdate\n=(Table [(\"name\", String), (\"age\", String), (\"favorite color\", String)])\nTable.mk [\n  /[ \"Bob\"   , \"kid\"      , \"blue\"         ],\n  /[ \"Alice\" , \"teenager\" , \"green\"        ],\n  /[ \"Eve\"   , \"teenager\" , \"red\"          ]\n]\n\ndef didWellUpdate := \u03bb (r : Row $ schema gradebook) =>\n  match getValue r \"midterm\" (by header), getValue r \"final\" (by header) with\n  | some (m : Nat), some (f : Nat) => /[\"midterm\" := (85 \u2264 m : Bool), \"final\" := (85 \u2264 f : Bool)]\n  | some m, none   => /[\"midterm\" := (85 \u2264 m : Bool), \"final\" := EMP]\n  | none, some f   => /[\"midterm\" := EMP, \"final\" := (85 \u2264 f : Bool)]\n  | none, none   => /[\"midterm\" := EMP, \"final\" := EMP]\n\n#test\nupdate [\u27e8(\"midterm\", Bool), _\u27e9, \u27e8(\"final\", Bool), _\u27e9] gradebook didWellUpdate\n=\nTable.mk [\n  /[ \"Bob\"   , 12  , 8     , 9     , false   , 7     , 9     , true  ],\n  /[ \"Alice\" , 17  , 6     , 8     , true    , 8     , 7     , true  ],\n  /[ \"Eve\"   , 13  , 7     , 9     , false   , 8     , 8     , false ]\n]\n\n-- `select`\n#test\nselect students (\u03bb (r : Row $ schema students) (n : Fin (nrows students)) =>\n  let colorCell : Cell \"COLOR\" String := Cell.fromOption $ getValue r \"favorite color\" (by header)\n  let ageCell : Cell \"AGE\" Nat := Cell.fromOption $ getValue r \"age\" (by header)\n  (Row.cons (Cell.val n.val : Cell \"ID\" Nat) $\n  Row.cons colorCell $\n  Row.cons ageCell\n  Row.nil))\n=\nTable.mk [\n  /[ 0  , \"blue\"  , 12  ],\n  /[ 1  , \"green\" , 17  ],\n  /[ 2  , \"red\"   , 13  ]\n]\n\n#test\nselect gradebook (\u03bb (r : Row $ schema gradebook) (n : Fin (nrows gradebook)) =>\n  let nameCell : Cell \"full name\" String :=\n    Cell.fromOption $ (getValue r \"name\" (by header)).map (\u00b7 ++ \" Smith\")\n  let mf2 : Cell \"(midterm + final) / 2\" Nat :=\n    match getValue r \"midterm\" (by header), getValue r \"final\" (by header) with\n    | some m, some f => Cell.val ((m + f) / 2)\n    | _, _ => Cell.emp\n  Row.cons nameCell $ Row.cons mf2 Row.nil\n)\n=\nTable.mk [\n  /[ \"Bob Smith\"   , 82                    ],\n  /[ \"Alice Smith\" , 86                    ],\n  /[ \"Eve Smith\"   , 80                    ]\n]\n\n-- `selectMany`\n-- TODO: type class resolution fails if we annotate `r : Row $ schema students`\n#test\nselectMany students\n(\u03bb r n =>\n  if n.val % 2 == 0\n  then Table.mk [r]\n  else head (Table.mk [r]) \u27e80, by simp [Int.abs, nrows]\u27e9)\n(\u03bb r\u2081 r\u2082 => r\u2082)\n=\nTable.mk [\n  /[ \"Bob\" , 12  , \"blue\"         ],\n  /[ \"Eve\" , 13  , \"red\"          ]\n]\n\ndef repeatRow {sch : @Schema String} : Row sch \u2192 Nat \u2192 Table sch\n| r, 0 => Table.mk [r]\n| r, n+1 => addRows (repeatRow r n) [r]\n\ndef decertify {sch : @Schema String}\n              (f : Row sch \u2192 Nat \u2192 Table sch)\n              (r : Row sch)\n              (nhn : Fin (nrows gradebook)) :=\nf r nhn.1\n\n#test\nselectMany gradebook (decertify repeatRow)\n(\u03bb r\u2081 r\u2082 =>\n  Row.cons (Cell.fromOption (nm := \"midterm\") $\n              getValue r\u2082 \"midterm\" (by header))\n  Row.nil)\n=\nTable.mk [\n  /[ 77      ],\n  /[ 88      ],\n  /[ 88      ],\n  /[ 84      ],\n  /[ 84      ],\n  /[ 84      ]\n]\n\n-- `groupJoin`\ndef getName :=\n\u03bb {schema} (h : schema.HasCol (\"name\", String)) (r : Row schema) =>\n  getValue r \"name\" h\n\ndef averageFinal := \u03bb (r : Row $ schema students) (t : Table $ schema gradebook) =>\n  r.addColumn \"final\"\n              (some $ average $ List.filterMap id (getColumn2 t \"final\" (by header)))\n\n#test\ngroupJoin students gradebook (getName (by header)) (getName (by header)) averageFinal\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , 87    ],\n  /[ \"Alice\" , 17  , \"green\"        , 85    ],\n  /[ \"Eve\"   , 13  , \"red\"          , 77    ]\n]\n\ndef nameLength' :=\n\u03bb {schema} (h : schema.HasCol (\"name\", String)) (r : Row schema) =>\n  (getValue r \"name\" h).map String.length\n\ndef tableNRows := \u03bb (r : Row $ schema students) (t : Table $ schema gradebook) =>\n  Row.addColumn r \"nrows\" (some $ nrows t)\n\n#test\ngroupJoin students gradebook (nameLength' (by header)) (nameLength' (by header)) tableNRows\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , 2     ],\n  /[ \"Alice\" , 17  , \"green\"        , 1     ],\n  /[ \"Eve\"   , 13  , \"red\"          , 2     ]\n]\n\n-- `join`\ndef getName' :=\n\u03bb {schema} (h : schema.HasCol (\"name\", String)) (r : Row schema) =>\n  getValue r \"name\" h\n\ndef addGradeColumn := \u03bb (r\u2081 : Row $ schema students) (r\u2082 : Row $ schema gradebook) =>\n  Row.addColumn r\u2081 \"grade\" (getValue r\u2082 \"final\" (by header))\n\n#test\njoin students gradebook (getName' (by header)) (getName' (by header)) addGradeColumn\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , 87    ],\n  /[ \"Alice\" , 17  , \"green\"        , 85    ],\n  /[ \"Eve\"   , 13  , \"red\"          , 77    ]\n]\n\ndef nameLength'' :=\n\u03bb {schema} (h : schema.HasCol (\"name\", String)) (r : Row schema) =>\n  (getValue r \"name\" h).map String.length\n\n#test\njoin students gradebook (nameLength'' $ by header) (nameLength'' $ by header) addGradeColumn\n=[by inst]\nTable.mk [\n  /[ \"Bob\"   , 12  , \"blue\"         , 87    ],\n  /[ \"Bob\"   , 12  , \"blue\"         , 77    ],\n  /[ \"Alice\" , 17  , \"green\"        , 85    ],\n  /[ \"Eve\"   , 13  , \"red\"          , 87    ],\n  /[ \"Eve\"   , 13  , \"red\"          , 77    ]\n]\n", "meta": {"author": "jrr6", "repo": "lean-tables", "sha": "4eb550d12b6e68639c0c0ae6451bcd55cf8a52d0", "save_path": "github-repos/lean/jrr6-lean-tables", "path": "github-repos/lean/jrr6-lean-tables/lean-tables-4eb550d12b6e68639c0c0ae6451bcd55cf8a52d0/Table/ExampleTests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.05108273623474417, "lm_q1q2_score": 0.017809747487790635}}
{"text": "/-\nCopyright (c) E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: E.W.Ayers\n\n! This file was ported from Lean 3 source module init.meta.widget.basic\n! leanprover-community/mathlib commit 93ae212fb944163e6df29a036182fdea83173e3f\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.Function\nimport Leanbin.Init.Data.Option.Basic\nimport Leanbin.Init.Util\nimport Leanbin.Init.Meta.Tactic\nimport Leanbin.Init.Meta.MkDecEqInstance\nimport Leanbin.Init.Meta.Json\n\n/-! A component is a piece of UI which may contain internal state. Use component.mk to build new components.\n\n## Using widgets.\n\nTo make a widget, you need to make a custom executor object and then instead of calling `save_info_thunk` you call `save_widget`.\n\nAdditionally, you will need a compatible build of the vscode extension or web app to use widgets in vscode.\n\n## How it works:\n\nThe design is inspired by React.\nIf you are familiar with using React or Elm or a similar functional UI framework then that's helpful for this.\nThe [React article on reconciliation](https://reactjs.org/docs/reconciliation.html) might be helpful.\n\nOne can imagine making a UI for a particular object as just being a function `f : \u03b1 \u2192 UI` where `UI` is some inductive datatype for buttons, textboxes, lists and so on.\nThe process of evaluating `f` is called __rendering__.\nSo for example `\u03b1` could be `tactic_state` and the function renders a goal view.\n\n## HTML\n\nFor our purposes, `UI` is an HTML tree and is written `html \u03b1 : Type`. I'm going to assume some familiarity with HTML for the purposes of this document.\nAn HTML tree is composed of elements and strings.\nEach element has a tag such as \"div\", \"span\", \"article\" and so on and a set of attributes and child html.\nUse the helper function `h : string \u2192 list (attr \u03b1) \u2192 list (html \u03b1) \u2192 html \u03b1` to build new pieces of `html`. So for example:\n\n```lean\nh \"ul\" [] [\n     h \"li\" [] [\"this is list item 1\"],\n     h \"li\" [style [(\"color\", \"blue\")]] [\"this is list item 2\"],\n     h \"hr\" [] [],\n     h \"li\" [] [\n          h \"span\" [] [\"there is a button here\"],\n          h \"button\" [on_click (\u03bb _, 3)] [\"click me!\"]\n     ]\n]\n```\nHas the type `html nat`.\nThe `nat` type is called the __action__ and whenever the user interacts with the UI, the html will emit an object of type `nat`.\nSo for example if the user clicks the button above, the html will 'emit' `3`.\nThe above example is compiled to the following piece of html:\n\n```html\n<ul>\n  <li>this is list item 1</li>\n  <li style=\"{ color: blue; }\">this is list item 2</li>\n  <hr/>\n  <li>\n     <span>There is a button here</span>\n     <button onClick=\"[handler]\">click me!</button>\n  </li>\n</ul>\n```\n\n## Components\n\nIn order for the UI to react to events, you need to be able to take these actions \u03b1 and alter some state.\nTo do this we use __components__. `component` takes two type arguments: `\u03c0` and `\u03b1`. `\u03b1` is called the 'action' and `\u03c0` are the 'props'.\nThe props can be thought of as a kind of wrapped function domain for `component`. So given `C : component nat \u03b1`, one can turn this into html with\n`html.of_component 4 C : html \u03b1`.\n\nThe base constructor for a component is `pure`:\n```lean\nmeta def Hello : component string \u03b1 := component.pure (\u03bb s, [\"hello, \", s, \", good day!\"])\n\n#html Hello \"lean\" -- renders \"hello, lean, good day!\"\n```\nSo here a pure component is just a simple function `\u03c0 \u2192 list (html \u03b1)`.\nHowever, one can augment components with __hooks__.\nThe hooks available for compoenents are listed in the inductive definition for component.\n\nHere we will just look at the `with_state` hook, which can be used to build components with inner state.\n\n```\nmeta inductive my_action\n| increment\n| decrement\nopen my_action\n\nmeta def Counter : component unit \u03b1 :=\ncomponent.with_state\n     my_action          -- the action of the inner component\n     int                -- the state\n     (\u03bb _, 0)           -- initialise the state\n     (\u03bb _ _ s, s)       -- update the state if the props change\n     (\u03bb _ s a,          -- update the state if an action was received\n          match a with\n          | increment := (s + 1, none) -- replace `none` with `some _` to emit an action\n          | decrement := (s - 1, none)\n          end\n     )\n$ component.pure (\u03bb \u27e8state, \u27e8\u27e9\u27e9, [\n     button \"+\" (\u03bb _, increment),\n     to_string state,\n     button \"-\" (\u03bb _, decrement)\n  ])\n\n#html Counter ()\n```\n\nYou can add many hooks to a component.\n\n- `filter_map_action` lets you filter or map actions that are emmitted by the component\n- `map_props` lets you map the props.\n- `with_should_update` will not re-render the child component if the given test returns false. This can be useful for efficiency.\n- `with_state` discussed above.`\n- `with_mouse` subscribes the component to the mouse state, for example whether or not the mouse is over the component. See the `tests/lean/widget/widget_mouse.lean` test for an example.\n\nGiven an active document, Lean (in server mode) maintains a set of __widgets__ for the document.\nA widget is a component `c`, some `p : Props` and an internal state-manager which manages the states\nof the component and subcomponents and also handles the routing of events from the UI.\n\n## Reconciliation\n\nIf a parent component's state changes, this can cause child components to change position or to appear and dissappear.\nHowever we want to preserve the state of these child components where we can.\nThe UI system will try to match up these child components through a process called __reconciliation__.\n\nReconciliation will make sure that the states are carried over correctly and will also not rerender subcomponents if they haven't changed their props or state.\nTo compute whether two components are the same, the system will perform a hash on their VM objects.\nNot all VM objects can be hashed, so it's important to make sure that any items that you expect to change over the lifetime of the component are fed through the 'Props' argument.\nThis is why we need the props argument on `component`.\nThe reconciliation engine uses the `props_eq` predicate passed to the component constructor to determine whether the props have changed and hence whether the component should be re-rendered.\n\n## Keys\n\nIf you have some list of components and the list changes according to some state, it is important to add keys to the components so\nthat if two components change order in the list their states are preserved.\nIf you don't provide keys or there are duplicate keys then you may get some strange behaviour in both the Lean widget engine and react.\n\nIt is possible to use incorrect HTML tags and attributes, there is (currently) no type checking that the result is a valid piece of HTML.\nSo for example, the client widget system will error if you add a `text_change_event` attribute to anything other than an element tagged with `input`.\n\n## Styles with Tachyons\n\nThe widget system assumes that a stylesheet called 'tachyons' is present.\nYou can find documentation for this stylesheet at [Tachyons.io](http://tachyons.io/).\nTachyons was chosen because it is very terse and allows arbitrary styling without using inline styles and without needing to dynamically load a stylesheet.\n\n## Further work (up for grabs!)\n\n- Add type checking for html.\n- Better error handling when the html tree is malformed.\n- Better error handling when keys are malformed.\n- Add a 'with_task' which lets long-running operations (eg running `simp`) not block the UI update.\n- Timers, animation (ambitious).\n- More event handlers\n- Drag and drop support.\n- The current perf bottleneck is sending the full UI across to the server for every update.\n  Instead, it should be possible to send a smaller [JSON Patch](http://jsonpatch.com).\n  Which is already supported by `json.hpp` and javascript ecosystem.\n\n-/\n\n\nnamespace Widget\n\ninductive MouseEventKind\n  | on_click\n  | on_mouse_enter\n  | on_mouse_leave\n#align widget.mouse_event_kind Widget.MouseEventKind\n\n/-- An effect is some change that the widget makes outside of its own state.\nUsually, giving instructions to the editor to perform some task.\n- `insert_text_relative` will insert at a line relative to the position of the widget.\n- `insert_text_absolute` will insert text at the precise position given.\n- `reveal_position` will move the editor to view the given position.\n- `highlight_position` will add a text highlight to the given position.\n- `clear_highlighting` will remove all highlights created with `highlight_position`.\n- `copy_text` will copy the given text to the clipboard.\n- `custom` can be used to pass custom effects to the client without having to recompile Lean.\n-/\nunsafe inductive effect : Type\n  | insert_text_absolute (file_name : Option String) (p : Pos) (text : String)\n  | insert_text_relative (relative_line : Int) (text : String)\n  | reveal_position (file_name : Option String) (p : Pos)\n  | highlight_position (file_name : Option String) (p : Pos)\n  | clear_highlighting\n  | copy_text (text : String)\n  | custom (key : String) (value : String)\n#align widget.effect widget.effect\n\nunsafe def effects :=\n  List effect\n#align widget.effects widget.effects\n\nmutual\n  unsafe inductive component : Type \u2192 Type \u2192 Type\n    | pure {Props Action : Type} (view : Props \u2192 List (html Action)) : component Props Action\n    |\n    filter_map_action {Props InnerAction OuterAction}\n      (action_map : Props \u2192 InnerAction \u2192 Option OuterAction) :\n      component Props InnerAction \u2192 component Props OuterAction\n    |\n    map_props {Props1 Props2 Action} (map : Props2 \u2192 Props1) :\n      component Props1 Action \u2192 component Props2 Action\n    |\n    with_should_update {Props Action : Type} (should_update : \u2200 old new : Props, Bool) :\n      component Props Action \u2192 component Props Action\n    |\n    with_state {Props Action : Type} (InnerAction State : Type) (init : Props \u2192 State)\n      (props_changed : Props \u2192 Props \u2192 State \u2192 State)\n      (update : Props \u2192 State \u2192 InnerAction \u2192 State \u00d7 Option Action) :\n      component (State \u00d7 Props) InnerAction \u2192 component Props Action\n    |\n    with_effects {Props Action : Type} (emit : Props \u2192 Action \u2192 effects) :\n      component Props Action \u2192 component Props Action\n  unsafe inductive html : Type \u2192 Type\n    | element {\u03b1 : Type} (tag : String) (attrs : List (attr \u03b1)) (children : List (html \u03b1)) : html \u03b1\n    | of_string {\u03b1 : Type} : String \u2192 html \u03b1\n    | of_component {\u03b1 : Type} {Props : Type} : Props \u2192 component Props \u03b1 \u2192 html \u03b1\n  unsafe inductive attr : Type \u2192 Type\n    | val {\u03b1 : Type} (name : String) (value : json) : attr \u03b1\n    | mouse_event {\u03b1 : Type} (kind : MouseEventKind) (handler : Unit \u2192 \u03b1) : attr \u03b1\n    | style {\u03b1 : Type} : List (String \u00d7 String) \u2192 attr \u03b1\n    | tooltip {\u03b1 : Type} : html \u03b1 \u2192 attr \u03b1\n    | text_change_event {\u03b1 : Type} (handler : String \u2192 \u03b1) : attr \u03b1\nend\n#align widget.component widget.component\n#align widget.html widget.html\n#align widget.attr widget.attr\n\nvariable {\u03b1 \u03b2 : Type} {\u03c0 : Type}\n\nnamespace Component\n\nunsafe def map_action (f : \u03b1 \u2192 \u03b2) : component \u03c0 \u03b1 \u2192 component \u03c0 \u03b2\n  | c => filter_map_action (fun p a => some <| f a) c\n#align widget.component.map_action widget.component.map_action\n\n/-- Returns a component that will never trigger an action. -/\nunsafe def ignore_action : component \u03c0 \u03b1 \u2192 component \u03c0 \u03b2\n  | c => component.filter_map_action (fun p a => none) c\n#align widget.component.ignore_action widget.component.ignore_action\n\nunsafe def ignore_props : component Unit \u03b1 \u2192 component \u03c0 \u03b1\n  | c => (with_should_update fun a b => false) <| component.map_props (fun p => ()) c\n#align widget.component.ignore_props widget.component.ignore_props\n\nunsafe instance : Coe (component \u03c0 Empty) (component \u03c0 \u03b1) :=\n  \u27e8component.filter_map_action fun p x => none\u27e9\n\nunsafe instance : CoeFun (component \u03c0 \u03b1) fun c => \u03c0 \u2192 html \u03b1 :=\n  \u27e8fun c p => html.of_component p c\u27e9\n\nunsafe def stateful {\u03c0 \u03b1 : Type} (\u03b2 \u03c3 : Type) (init : \u03c0 \u2192 Option \u03c3 \u2192 \u03c3)\n    (update : \u03c0 \u2192 \u03c3 \u2192 \u03b2 \u2192 \u03c3 \u00d7 Option \u03b1) (view : \u03c0 \u2192 \u03c3 \u2192 List (html \u03b2)) : component \u03c0 \u03b1 :=\n  with_state \u03b2 \u03c3 (fun p => init p none) (fun _ p s => init p <| some s) update\n    (component.pure fun \u27e8s, p\u27e9 => view p s)\n#align widget.component.stateful widget.component.stateful\n\nunsafe def stateless {\u03c0 \u03b1 : Type} [DecidableEq \u03c0] (view : \u03c0 \u2192 List (html \u03b1)) : component \u03c0 \u03b1 :=\n  (component.with_should_update fun p1 p2 => p1 \u2260 p2) <| component.pure view\n#align widget.component.stateless widget.component.stateless\n\n/--\nCauses the component to only update on a props change when `test old_props new_props` yields `ff`. -/\nunsafe def with_props_eq (test : \u03c0 \u2192 \u03c0 \u2192 Bool) : component \u03c0 \u03b1 \u2192 component \u03c0 \u03b1\n  | c => component.with_should_update (fun x y => not <| test x y) c\n#align widget.component.with_props_eq widget.component.with_props_eq\n\nend Component\n\nmutual\n  unsafe def attr.map_action (f : \u03b1 \u2192 \u03b2) : attr \u03b1 \u2192 attr \u03b2\n    | attr.val k v => attr.val k v\n    | attr.style s => attr.style s\n    | attr.tooltip h => attr.tooltip <| html.map_action h\n    | attr.mouse_event k a => attr.mouse_event k (f \u2218 a)\n    | attr.text_change_event a => attr.text_change_event (f \u2218 a)\n  unsafe def html.map_action (f : \u03b1 \u2192 \u03b2) : html \u03b1 \u2192 html \u03b2\n    | html.element t a c => html.element t (List.map attr.map_action a) (List.map html.map_action c)\n    | html.of_string s => html.of_string s\n    | html.of_component p c => html.of_component p <| component.map_action f c\nend\n#align widget.attr.map_action widget.attr.map_action\n#align widget.html.map_action widget.html.map_action\n\nunsafe instance attr.is_functor : Functor attr where map := @attr.map_action\n#align widget.attr.is_functor widget.attr.is_functor\n\nunsafe instance html.is_functor : Functor html where map _ _ := html.map_action\n#align widget.html.is_functor widget.html.is_functor\n\nnamespace Html\n\n/-- See Note [use has_coe_t]. -/\nunsafe instance to_string_coe [ToString \u03b2] : CoeTC \u03b2 (html \u03b1) :=\n  \u27e8html.of_string \u2218 toString\u27e9\n#align widget.html.to_string_coe widget.html.to_string_coe\n\nunsafe instance : EmptyCollection (html \u03b1) :=\n  \u27e8of_string \"\"\u27e9\n\nunsafe instance list_coe : Coe (html \u03b1) (List (html \u03b1)) :=\n  \u27e8fun x => [x]\u27e9\n#align widget.html.list_coe widget.html.list_coe\n\nend Html\n\nunsafe def as_element : html \u03b1 \u2192 Option (String \u00d7 List (attr \u03b1) \u00d7 List (html \u03b1))\n  | html.element t a c => some \u27e8t, a, c\u27e9\n  | _ => none\n#align widget.as_element widget.as_element\n\nunsafe def key [ToString \u03b2] : \u03b2 \u2192 attr \u03b1\n  | s => attr.val \"key\" <| toString s\n#align widget.key widget.key\n\nunsafe def className : String \u2192 attr \u03b1\n  | s => attr.val \"className\" <| s\n#align widget.className widget.className\n\nunsafe def on_click : (Unit \u2192 \u03b1) \u2192 attr \u03b1\n  | a => attr.mouse_event MouseEventKind.on_click a\n#align widget.on_click widget.on_click\n\nunsafe def on_mouse_enter : (Unit \u2192 \u03b1) \u2192 attr \u03b1\n  | a => attr.mouse_event MouseEventKind.on_mouse_enter a\n#align widget.on_mouse_enter widget.on_mouse_enter\n\nunsafe def on_mouse_leave : (Unit \u2192 \u03b1) \u2192 attr \u03b1\n  | a => attr.mouse_event MouseEventKind.on_mouse_leave a\n#align widget.on_mouse_leave widget.on_mouse_leave\n\n/-- Alias for `html.element`. -/\nunsafe def h : String \u2192 List (attr \u03b1) \u2192 List (html \u03b1) \u2192 html \u03b1 :=\n  html.element\n#align widget.h widget.h\n\n/-- Alias for className. -/\nunsafe def cn : String \u2192 attr \u03b1 :=\n  className\n#align widget.cn widget.cn\n\nunsafe def button : String \u2192 Thunk \u03b1 \u2192 html \u03b1\n  | s, t => h \"button\" [on_click t] [s]\n#align widget.button widget.button\n\nunsafe def textbox : String \u2192 (String \u2192 \u03b1) \u2192 html \u03b1\n  | s, t => h \"input\" [attr.val \"type\" \"text\", attr.val \"value\" s, attr.text_change_event t] []\n#align widget.textbox widget.textbox\n\nunsafe structure select_item (\u03b1 : Type) where\n  result : \u03b1\n  key : String\n  view : List (html \u03b1)\n#align widget.select_item widget.select_item\n\n/-- Choose from a dropdown selection list. -/\nunsafe def select {\u03b1} [DecidableEq \u03b1] : List (select_item \u03b1) \u2192 \u03b1 \u2192 html \u03b1\n  | items, value =>\n    let k :=\n      match List.filter (fun i => select_item.result i = value) items with\n      | [] => \"\"\n      | h :: _ => select_item.key h\n    h \"select\"\n        [attr.val \"value\" k, attr.val \"key\" k,\n          attr.text_change_event fun k =>\n            match items.filter\u2093 fun i => select_item.key i = k with\n            | [] => undefined\n            | h :: _ => h.result] <|\n      items.map fun i => h \"option\" [attr.val \"value\" i.key] <| select_item.view i\n#align widget.select widget.select\n\n/-- If the html is not an of_element it will wrap it in a div. -/\nunsafe def with_attrs : List (attr \u03b1) \u2192 html \u03b1 \u2192 html \u03b1\n  | a, x =>\n    match as_element x with\n    | some \u27e8t, as, c\u27e9 => html.element t (a ++ as) c\n    | none => html.element \"div\" a [x]\n#align widget.with_attrs widget.with_attrs\n\n/-- If the html is not an of_element it will wrap it in a div. -/\nunsafe def with_attr : attr \u03b1 \u2192 html \u03b1 \u2192 html \u03b1\n  | a, x => with_attrs [a] x\n#align widget.with_attr widget.with_attr\n\nunsafe def with_style : String \u2192 String \u2192 html \u03b1 \u2192 html \u03b1\n  | k, v, h => with_attr (attr.style [(k, v)]) h\n#align widget.with_style widget.with_style\n\nunsafe def with_cn : String \u2192 html \u03b1 \u2192 html \u03b1\n  | s, h => with_attr (className s) h\n#align widget.with_cn widget.with_cn\n\nunsafe def with_key {\u03b2} [ToString \u03b2] : \u03b2 \u2192 html \u03b1 \u2192 html \u03b1\n  | s, h => with_attr (key s) h\n#align widget.with_key widget.with_key\n\nunsafe def effect.insert_text : String \u2192 effect :=\n  effect.insert_text_relative 0\n#align widget.effect.insert_text widget.effect.insert_text\n\nend Widget\n\nnamespace Tactic\n\n/--\nSame as `tactic.save_info_thunk` except saves a widget to be displayed by a compatible infoviewer. -/\nunsafe axiom save_widget : Pos \u2192 widget.component tactic_state Empty \u2192 tactic Unit\n#align tactic.save_widget tactic.save_widget\n\n/-- Outputs a widget trace position at the given position. -/\nunsafe axiom trace_widget_at (p : Pos) (w : widget.component tactic_state Empty)\n    (text := \"(widget)\") : tactic Unit\n#align tactic.trace_widget_at tactic.trace_widget_at\n\n/-- Outputs a widget trace position at the current default trace position. -/\nunsafe def trace_widget (w : widget.component tactic_state Empty) (text := \"(widget)\") :\n    tactic Unit := do\n  let p \u2190 get_trace_msg_pos\n  trace_widget_at p w text\n#align tactic.trace_widget tactic.trace_widget\n\nend Tactic\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/Widget/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508500210441886, "lm_q2_score": 0.07263670033827889, "lm_q1q2_score": 0.017802165855265124}}
{"text": "syntax \"my_trivial\" : tactic -- extensible tactic\n\nmacro_rules | `(tactic| my_trivial) => `(tactic| decide)\nmacro_rules | `(tactic| my_trivial) => `(tactic| assumption)\n\ndef f (a : Nat) (h : a > 3) := a\n\nexample : True := by\n  have : f 4 (by my_trivial) = 4 := rfl\n  constructor\n\nexample : True :=\n  have : f 4 (by my_trivial) = 4 := rfl\n  \u27e8\u27e9\n\nexample : 4 > 3 := by\n  my_trivial\n\nexample : True :=\n  have : f 4 (have : 4 > 3 := (by my_trivial); this) = 4 := rfl\n  \u27e8\u27e9\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/extensibleTacticBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.05665242451161216, "lm_q1q2_score": 0.01779172479297903}}
{"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 \u2192 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 \u00d7 String := do\n    let c := runParserCategory (\u2190 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 \u00d7 Syntax := do\n    let info? := ((\u2190 getEnv).find? name)\n    let info := info?.get!\n    let exp := info.value?.get!\n    let type := info.type\n    let (stx, _) \u2190  delabCore exp {} (delabVerbose)\n    let (tstx, _) \u2190  delabCore type {} (delabVerbose)\n    return (stx, tstx)\n\ndef nameDefSyntax (name: Name) : MetaM <| Option Syntax := do\n    let exp? \u2190 nameExpr? name\n    match exp? with\n    | none => pure none\n    | some exp => do\n        let stx \u2190  delab exp\n        pure (some stx)\n\ndef premisesFromName (name : Name) : MetaM (List PremiseData) := do\n    let (pf, prop) \u2190 nameDefTypeSyntax name\n    Lean.Syntax.premiseDataM #[] pf prop true name name\n\ndef _root_.PremiseData.view : PremiseData \u2192 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 \u2190 premisesFromName name\n    premises.mapM (fun p => p.view)\n\n\ndef premisesJsonFromName (name: Name) : MetaM <| Json := do\n    let premises \u2190 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? \u2190 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? \u2190 nameDefSyntax name\n    return (stx?.get!.reprint.get!)\n\ndef nameDefCleanView (name: Name) : MetaM String := do\n    let stx? \u2190 nameDefSyntax name\n    return ((stx?.get!.purge).reprint.get!)\n\ndef nameDefSyntaxVerbose (name: Name) : MetaM <| Option Syntax := do\n    let exp? \u2190 nameExpr? name\n    match exp? with\n    | none => pure none\n    | some exp => do\n        let (stx, _) \u2190  delabCore exp {} (delabVerbose)\n        pure (some stx)\n\ndef nameDefViewVerbose (name: Name) : MetaM String := do\n    let stx? \u2190 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 \u00d7 Array Syntax) := do\n--     let stx? \u2190 nameDefSyntax ``Nat.gcd_eq_zero_iff\n--     lambdaStx? stx?.get!\n\n-- #eval egSplit\n\n-- def egSplitView : MetaM <| Option (String \u00d7 Array String) := do\n--     let stx? \u2190 nameDefSyntax ``Nat.gcd_eq_zero_iff\n--     let pair? \u2190 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 : \u2200 (n : Nat), \u2203 m, m > n \u2227 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 `\u2227` to split goals\n--   \u00b7 linarith -- solve the first goal using `linarith` \n--   \u00b7 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 \u2190 constantNameTypes\n    let mut definitions := HashMap.empty\n    let mut theorems := HashMap.empty\n    for (c, type) in consts do\n        let tstx \u2190 delab type\n        let tstx := tstx.raw.purge\n        if \u2190 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 \u00d7 Nat  := do\n    if maxDepth? = some 0 then\n        pure []\n    else\n    match \u2190 namedArgument? stx with\n    | some (arg, _) =>\n        -- IO.println s!\"Named: {arg}\"\n        let prev \u2190  identsM  arg context (maxDepth?.map (\u00b7 -1))\n        return prev.map (fun (s, m) => (s, m + 1))\n    | none =>\n    match \u2190 proofWithProp? stx with\n    | some (proof, _) =>\n        -- IO.println s!\"Proof: {proof}\"\n        let prev \u2190  identsM  proof context (maxDepth?.map (\u00b7 -1))\n        return prev.map (fun (s, m) => (s, m + 1))\n    | none =>\n    match \u2190 lambdaStx? stx with\n    | some (body, args) =>\n        -- IO.println s!\"Lambda: {args}\"\n        let prev \u2190  identsM  body (context ++ args) (maxDepth?.map (\u00b7 -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 \u2190 args.mapM (identsM \u00b7 context (maxDepth?.map (\u00b7 -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 \u2190 termKindList\n    let tks := tks.map (\u00b7.1)\n    if maxDepth? = some 0 then\n        pure []\n    else\n    match \u2190 namedArgument? stx with\n    | some (arg, _) =>\n        -- IO.println s!\"Named: {arg}\"\n        let prev \u2190  termsM  context arg (maxDepth?.map (\u00b7 -1))\n        return prev.map (fun s => s.increaseDepth 1 )\n    | none =>\n    match \u2190 proofWithProp? stx with\n    | some (proof, _) =>\n        -- IO.println s!\"Proof: {proof}\"\n        let prev \u2190  termsM context  proof (maxDepth?.map (\u00b7 -1))\n        return prev.map (fun s => s.increaseDepth 1)\n    | none =>\n    match \u2190 lambdaStx? stx with\n    | some (body, args) =>\n        -- IO.println s!\"Lambda: {args}\"\n        let prev \u2190  termsM (context ++ args) body (maxDepth?.map (\u00b7 -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 \u2190 args.mapM (termsM context \u00b7 (maxDepth?.map (\u00b7 -1)))\n            let head : TermData := \u27e8context, stx.purge, stx.purge.size, 0\u27e9\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 \u2190 namedArgument? stx with\n    | some (arg, _) =>\n        -- IO.println s!\"Named: {arg}\"\n        let prev \u2190  proofsM  context arg (maxDepth?.map (\u00b7 -1))\n        return prev.map (fun s => s.increaseDepth 1)\n    | none =>\n    match \u2190 proofWithProp? stx with\n    | some (proof, prop) =>\n        -- IO.println s!\"Proof: {proof}\"\n        let prev \u2190  proofsM context  proof (maxDepth?.map (\u00b7 -1))\n        let head : PropProofData := \n            \u27e8context, prop, proof, prop.size, proof.size, 0\u27e9\n        return  (head) :: prev.map (fun s => s.increaseDepth 1)\n    | none =>\n    match \u2190 lambdaStx? stx with\n    | some (body, args) =>\n        -- IO.println s!\"Lambda: {args}\"\n        let prev \u2190  proofsM (context ++ args) body (maxDepth?.map (\u00b7 -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 \u2190 args.mapM (proofsM context \u00b7 (maxDepth?.map (\u00b7 -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) \u2190  pf.proofsM ctx\n    let subTerms : List (TermData)  \u2190 Syntax.termsM ctx pf\n    let ids : List (Name  \u00d7 Nat) \u2190 pf.identsM ctx \n    return \u27e8ctx, some name, name, prop.purge, prop.purge, pf.purge, prop.purge.size, pf.purge.size, subTerms.toArray, subProofs.toArray, ids.toArray\u27e9\n\ndef viewData (name: Name) : MetaM <| String := do\n    let (stx, tstx) \u2190 nameDefTypeSyntax name\n    -- IO.println s!\"{stx.reprint.get!}\"\n    -- IO.println s!\"{\u2190 proofWithProp? stx}\"\n    let data \u2190  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 (\u00b7 |>.toString)\n        match head? with\n        | some head => head :: (args.map (kinds \u00b7 (maxDepth?.map (\u00b7 -1))) |>.toList.join)\n        | none => args.map (kinds \u00b7 (maxDepth?.map (\u00b7 -1))) |>.toList.join\n    | _ => []\n\npartial def Lean.Syntax.idents (stx: Syntax)(maxDepth? : Option Nat := none) : List <| Name \u00d7 Nat  :=\n    if maxDepth? = some 0 then\n        []\n    else\n    match stx with\n    | Syntax.node _ _ args => \n         args.map (idents \u00b7 (maxDepth?.map (\u00b7 -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 \u00d7 Nat \u00d7 List Name := do\n    let tks \u2190 termKindList\n    let tks := tks.map (\u00b7.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 \u2208 tks \n            then\n                \u2190 stx.reprint\n            else\n                none\n        let argTerms \u2190 args.mapM (terms \u00b7 (maxDepth?.map (\u00b7 -1))) \n        let argTerms := argTerms.toList.join\n        match head? with\n        | some head =>             \n            return (head.trim, 0, stx.idents.map (\u00b7.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 \u00d7 Nat \u00d7 List Name\n    defIdents : List <| Name \u00d7 Nat\n    typeTerms : List <| String \u00d7 Nat \u00d7 List Name\n    typeIdents : List <| Name \u00d7 Nat \nderiving Repr, Inhabited\n\ndef Premises.defMainTerms (p: Premises) : List <| String \u00d7 Nat \u00d7 List Name  :=\n    p.defTerms.filter (\n            fun (s, _) => s.1.length < 20)\n\ndef Premises.typeMainTerms (p: Premises) : List <| String \u00d7 Nat \u00d7 List Name :=\n    p.typeTerms.filter (fun (s, _) => (s.splitOn \"=>\").length == 1  \n                && (s.splitOn \"\u21a6\").length == 1)\n\n\n\ndef getPremises (name: Name)(maxDepth? : Option Nat := none ) : MetaM <| Premises := do\n    let termStx? \u2190 nameDefSyntaxVerbose name\n    let term \u2190  mkConstWithLevelParams name\n    let type \u2190 inferType term\n    let typeView \u2190 Meta.ppExpr type\n    let typeStx \u2190 delab type\n    let defTerms \u2190  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 := \u2190  typeStx.raw |>.terms maxDepth?, typeIdents := typeStx.raw |>.idents maxDepth?}\n\n\n-- Testing\n\n\n\ndef showTerms (s: String) : MetaM <| List <| String \u00d7 Nat \u00d7 List Name  := do\n    let c := runParserCategory (\u2190 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 \u00d7 Nat := do\n    let c := runParserCategory (\u2190 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 (\u2190 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 \u00d7 Nat \u00d7 List Name  := do\n    let stx? \u2190 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 \u00d7 Nat := do\n    let stx? \u2190 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 \u21a6 Nat.succ n\"\n\n-- #eval showIdents \"fun n \u21a6 Nat.succ n\"\n\n-- #eval showTerms \"fun n \u21a6 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 \u2192 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 \u00d7 Nat \u00d7 List Name := do\n--     let p \u2190  getPremises ``oddExample (some 30) \n--     return p.defMainTerms\n\n-- #eval egTerms\n\n-- def egIdents : MetaM <| List <| Name \u00d7 Nat:= do\n--     let p \u2190  getPremises ``oddExample (some 50) \n--     return p.defIdents\n\n-- #eval egIdents\n\n-- def egGpIdents : MetaM NameGroups := do\n--     let nd \u2190 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 \u2190 constantNames\n    return names.size \n\n-- #eval dataSize\n\ndef boundedDataSize (n: Nat) : MetaM Nat := do\n    let names \u2190 constantNames\n    let names \u2190 names.filterM (boundedDef n)\n    return names.size\n\n-- #eval boundedDataSize 50\n\ndef sampleExtract (n: Nat := 100) : MetaM <|\n        List (Name \u00d7 (List <| String \u00d7 Nat \u00d7 List Name) \u00d7\n        (List <| Name \u00d7 Nat)) := do\n    let names \u2190 constantNames\n    let names := names.toList.take n\n    names.mapM (fun n => do \n        let p \u2190 nameDefTerms n\n        let q \u2190 nameDefIdents n\n        pure (n, p, q)\n        )\n\ndef batchPremiseExtractM (start stop: Nat) : MetaM Nat  := do\n    let names \u2190 constantNames\n    let premisesFile := System.mkFilePath [\"rawdata\",\n    s!\"outer-premises.jsonl\"]\n    let h \u2190 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 \u2190 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 : \u2200 (n : Nat), (2 ^ n + 1) % 7 \u2260 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) 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, Jon Eugster\nPorted by: E.W.Ayers\n-/\nimport Mathlib.Init.Data.Nat.Notation\nimport Mathlib.Data.String.Defs\nimport Mathlib.Data.KVMap\nimport Mathlib.Lean.Expr.ReplaceRec\nimport Mathlib.Lean.EnvExtension\nimport Mathlib.Lean.Meta.Simp\nimport Std.Lean.NameMapAttribute\nimport Std.Data.Option.Basic\nimport Std.Tactic.CoeExt -- just to copy the attribute\nimport Std.Tactic.Ext.Attr -- just to copy the attribute\nimport Std.Tactic.Lint -- useful to lint this file and for for DiscrTree.elements\nimport Mathlib.Tactic.Relation.Rfl -- just to copy the attribute\nimport Mathlib.Tactic.Relation.Symm -- just to copy the attribute\nimport Mathlib.Tactic.Relation.Trans -- just to copy the attribute\nimport Mathlib.Tactic.Simps.Basic\n\n/-!\n# The `@[to_additive]` attribute.\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-/\n\nopen Lean Meta Elab Command Std\n\n/-- The  `to_additive_ignore_args` attribute. -/\nsyntax (name := to_additive_ignore_args) \"to_additive_ignore_args\" num* : attr\n/-- The  `to_additive_relevant_arg` attribute. -/\nsyntax (name := to_additive_relevant_arg) \"to_additive_relevant_arg\" num : attr\n/-- The  `to_additive_reorder` attribute. -/\nsyntax (name := to_additive_reorder) \"to_additive_reorder\" num* : attr\n/-- The  `to_additive_change_numeral` attribute. -/\nsyntax (name := to_additive_change_numeral) \"to_additive_change_numeral\" num* : attr\n/-- An `attr := ...` option for `to_additive`. -/\nsyntax toAdditiveAttrOption := &\"attr\" \":=\" Parser.Term.attrInstance,*\n/-- An `reorder := ...` option for `to_additive`. -/\nsyntax toAdditiveReorderOption := &\"reorder\" \":=\" num+\n/-- Options to `to_additive`. -/\nsyntax toAdditiveParenthesizedOption := \"(\" toAdditiveAttrOption <|> toAdditiveReorderOption \")\"\n/-- Options to `to_additive`. -/\nsyntax toAdditiveOption := toAdditiveParenthesizedOption <|> &\"existing\"\n/-- Remaining arguments of `to_additive`. -/\nsyntax toAdditiveRest := toAdditiveOption* (ppSpace ident)? (ppSpace str)?\n/-- The `to_additive` attribute. -/\nsyntax (name := to_additive) \"to_additive\" \"?\"? toAdditiveRest : attr\n\n/-- The `to_additive` attribute. -/\nmacro \"to_additive?\" rest:toAdditiveRest : attr => `(attr| to_additive ? $rest)\n\n/-- A set of strings of names that end in a capital letter.\n* If the string contains a lowercase letter, the string should be split between the first occurrence\n  of a lower-case letter followed by a upper-case letter.\n* If multiple strings have the same prefix, they should be grouped by prefix\n* In this case, the second list should be prefix-free\n  (no element can be a prefix of a later element)\n\nTodo: automate the translation from `String` to an element in this `RBMap`\n  (but this would require having something similar to the `rb_lmap` from Lean 3). -/\ndef endCapitalNames : Lean.RBMap String (List String) compare :=\n-- todo: we want something like\n-- endCapitalNamesOfList [\"LE\", \"LT\", \"WF\", \"CoeTC\", \"CoeT\", \"CoeHTCT\"]\n.ofList [(\"LE\", [\"\"]), (\"LT\", [\"\"]), (\"WF\", [\"\"]), (\"Coe\", [\"TC\", \"T\", \"HTCT\"])]\n\n/--\nThis function takes a String and splits it into separate parts based on the following\n(naming conventions)[https://github.com/leanprover-community/mathlib4/wiki#naming-convention].\n\nE.g. `#eval  \"InvHMulLEConjugate\u2082SMul_ne_top\".splitCase` yields\n`[\"Inv\", \"HMul\", \"LE\", \"Conjugate\u2082\", \"SMul\", \"_\", \"ne\", \"_\", \"top\"]`.\n-/\npartial def String.splitCase (s : String) (i\u2080 : Pos := 0) (r : List String := []) : List String :=\nId.run do\n  -- We test if we need to split between `i\u2080` and `i\u2081`.\n  let i\u2081 := s.next i\u2080\n  if s.atEnd i\u2081 then\n    -- If `i\u2080` is the last position, return the list.\n    let r := s::r\n    return r.reverse\n  /- We split the string in three cases\n  * We split on both sides of `_` to keep them there when rejoining the string;\n  * We split after a name in `endCapitalNames`;\n  * We split after a lower-case letter that is followed by an upper-case letter\n    (unless it is part of a name in `endCapitalNames`). -/\n  if s.get i\u2080 == '_' || s.get i\u2081 == '_' then\n    return splitCase (s.extract i\u2081 s.endPos) 0 <| (s.extract 0 i\u2081)::r\n  if (s.get i\u2081).isUpper then\n    if let some strs := endCapitalNames.find? (s.extract 0 i\u2081) then\n      if let some (pref, newS) := strs.findSome?\n        fun x \u21a6 x.isPrefixOf? (s.extract i\u2081 s.endPos) |>.map (x, \u00b7) then\n        return splitCase newS 0 <| (s.extract 0 i\u2081 ++ pref)::r\n    if !(s.get i\u2080).isUpper then\n      return splitCase (s.extract i\u2081 s.endPos) 0 <| (s.extract 0 i\u2081)::r\n  return splitCase s i\u2081 r\n\nnamespace ToAdditive\n\ninitialize registerTraceClass `to_additive\ninitialize registerTraceClass `to_additive_detail\n\n/-- Linter to check that the reorder attribute is not given manually -/\nregister_option linter.toAdditiveReorder : Bool := {\n  defValue := true\n  descr := \"Linter to check that the reorder attribute is not given manually.\" }\n\n/-- Linter, mostly used by `@[to_additive]`, that checks that the source declaration doesn't have\ncertain attributes -/\nregister_option linter.existingAttributeWarning : Bool := {\n  defValue := true\n  descr := \"Linter, mostly used by `@[to_additive]`, that checks that the source declaration \" ++\n    \"doesn't have certain attributes\" }\n\n/-- Linter to check that the reorder attribute is not given manually -/\nregister_option linter.toAdditiveGenerateName : Bool := {\n  defValue := true\n  descr := \"Linter used by `@[to_additive]` that checks if `@[to_additive]` automatically \" ++\n    \"generates the user-given name\" }\n\n/-- Linter to check whether the user correctly specified that the additive declaration already\nexists -/\nregister_option linter.toAdditiveExisting : Bool := {\n  defValue := true\n  descr := \"Linter used by `@[to_additive]` that checks whether the user correctly specified that\n    the additive declaration already exists\" }\n\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 `\u2115` or another\nfixed type occurs as one of these arguments.\n-/\ninitialize ignoreArgsAttr : NameMapExtension (List Nat) \u2190\n  registerNameMapAttribute {\n    name  := `to_additive_ignore_args\n    descr :=\n      \"Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.\"\n    add   := fun _ stx \u21a6 do\n        let ids \u2190 match stx with\n          | `(attr| to_additive_ignore_args $[$ids:num]*) => pure <| ids.map (\u00b7.1.isNatLit?.get!)\n          | _ => throwUnsupportedSyntax\n        return ids.toList }\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-/\ninitialize reorderAttr : NameMapExtension (List Nat) \u2190\n  registerNameMapAttribute {\n    name := `to_additive_reorder\n    descr :=\n      \"Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.\n        This should not appear in any file.\n        We keep it as an attribute for now so that mathport can still use it, and it can generate a\n        warning.\"\n    add := fun\n    | _, stx@`(attr| to_additive_reorder $[$ids:num]*) => do\n      Linter.logLintIf linter.toAdditiveReorder stx\n        m!\"Using this attribute is deprecated. Use `@[to_additive (reorder := <num>)]` {\"\"\n        }instead.\\nThat will also generate the additive version with the arguments swapped, {\"\"\n        }so you are probably able to remove the manually written additive declaration.\"\n      pure <| Array.toList <| ids.map (\u00b7.1.isNatLit?.get!)\n    | _, _ => throwUnsupportedSyntax }\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 `\u2115 \u00d7 \u03b1`\nanyway.\n\nWarning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this\nattribute is currently not supported.\n-/\ninitialize relevantArgAttr : NameMapExtension Nat \u2190\n  registerNameMapAttribute {\n    name := `to_additive_relevant_arg\n    descr := \"Auxiliary attribute for `to_additive` stating\" ++\n      \" which arguments are the types with a multiplicative structure.\"\n    add := fun\n    | _, `(attr| to_additive_relevant_arg $id) => pure <| id.1.isNatLit?.get!.pred\n    | _, _ => throwUnsupportedSyntax }\n\n/--\nAn attribute that stores all the declarations that deal with numeric literals on variable types.\n\nNumeral literals occur in expressions without type information, so in order to decide whether `1`\nneeds to be changed to `0`, the context around the numeral is relevant.\nMost numerals will be in an `OfNat.ofNat` application, though tactics can add numeral literals\ninside arbitrary functions. By default we assume that we do not change numerals, unless it is\nin a function application with the `to_additive_change_numeral` attribute.\n\n`@[to_additive_change_numeral n\u2081 ...]` should be added to all functions that take one or more\nnumerals as argument that should be changed if `additiveTest` succeeds on the first argument,\ni.e. when the numeral is only translated if the first argument is a variable\n(or consists of variables).\nThe arguments `n\u2081 ...` are the positions of the numeral arguments (starting counting from 1).\n-/\ninitialize changeNumeralAttr : NameMapExtension (List Nat) \u2190\n  registerNameMapAttribute {\n    name := `to_additive_change_numeral\n    descr :=\n      \"Auxiliary attribute for `to_additive` that stores functions that have numerals as argument.\"\n    add := fun\n    | _, `(attr| to_additive_change_numeral $[$arg]*) =>\n      pure <| arg.map (\u00b7.1.isNatLit?.get!.pred) |>.toList\n    | _, _ => throwUnsupportedSyntax }\n\n/-- Maps multiplicative names to their additive counterparts. -/\ninitialize translations : NameMapExtension Name \u2190 registerNameMapExtension _\n\n/-- Get the multiplicative \u2192 additive translation for the given name. -/\ndef findTranslation? (env : Environment) : Name \u2192 Option Name :=\n  (ToAdditive.translations.getState env).find?\n\n/-- Add a (multiplicative \u2192 additive) name translation to the translations map. -/\ndef insertTranslation (src tgt : Name) (failIfExists := true) : CoreM Unit := do\n  if let some tgt' := findTranslation? (\u2190 getEnv) src then\n    if failIfExists then\n      throwError \"The translation {src} \u21a6 {tgt'} already exists\"\n    else\n      trace[to_additive] \"The translation {src} \u21a6 {tgt'} already exists\"\n      return\n  modifyEnv (ToAdditive.translations.addEntry \u00b7 (src, tgt))\n  trace[to_additive] \"Added translation {src} \u21a6 {tgt}\"\n\n/-- `Config` is the type of the arguments that can be provided to `to_additive`. -/\nstructure Config : Type where\n  /-- View the trace of the to_additive procedure.\n  Equivalent to `set_option trace.to_additive true`. -/\n  trace : Bool := false\n  /-- The name of the target (the additive declaration).-/\n  tgt : Name := Name.anonymous\n  /-- An optional doc string.-/\n  doc : Option String := none\n  /-- If `allowAutoName` is `false` (default) then\n  `@[to_additive]` will check whether the given name can be auto-generated. -/\n  allowAutoName : Bool := false\n  /-- The arguments that should be reordered by `to_additive` -/\n  reorder : List Nat := []\n  /-- The attributes which we want to give to both the multiplicative and additive versions.\n  For certain attributes (such as `simp` and `simps`) this will also add generated lemmas to the\n  translation dictionary. -/\n  attrs : Array Syntax := #[]\n  /-- The `Syntax` element corresponding to the original multiplicative declaration\n  (or the `to_additive` attribute if it is added later),\n  which we need for adding definition ranges. -/\n  ref : Syntax\n  /-- An optional flag stating whether the additive declaration already exists.\n    If this flag is set but wrong about whether the additive declaration exists, `to_additive` will\n    raise a linter error.\n    Note: the linter will never raise an error for inductive types and structures. -/\n  existing : Option Bool := none\n  deriving Repr\n\nvariable [Monad M] [MonadOptions M] [MonadEnv M]\n\n/-- Auxilliary function for `additiveTest`. The bool argument *only* matters when applied\nto exactly a constant. -/\ndef additiveTestAux (findTranslation? : Name \u2192 Option Name)\n  (ignore : Name \u2192 Option (List \u2115)) : Bool \u2192 Expr \u2192 Bool := visit where\n  /-- see `additiveTestAux` -/\n  visit : Bool \u2192 Expr \u2192 Bool\n  | b, .const n _         => b || (findTranslation? n).isSome\n  | _, x@(.app e a)       => Id.run do\n      if !visit true e then\n        return false\n      -- make sure that we don't treat `(fun x => \u03b1) (n + 1)` as a type that depends on `Nat`\n      if x.isConstantApplication then\n        return true\n      if let some n := e.getAppFn.constName? then\n        if let some l := ignore n then\n          if e.getAppNumArgs + 1 \u2208 l then\n            return true\n      visit false a\n  | _, .lam _ _ t _       => visit false t\n  | _, .forallE _ _ t _   => visit false t\n  | _, .letE _ _ e body _ => visit false e && visit false body\n  | _, _                  => true\n\n/--\n`additiveTest e` tests whether the expression `e` contains no constant\n`nm` that is not applied to any arguments, and such that `translations.find?[nm] = none`.\nThis is used in `@[to_additive]` for deciding which subexpressions to transform: we only transform\nconstants if `additiveTest` applied to their first argument returns `true`.\nThis means we will replace expression applied to e.g. `\u03b1` or `\u03b1 \u00d7 \u03b2`, but not when applied to\ne.g. `\u2115` or `\u211d \u00d7 \u03b1`.\nWe ignore all arguments specified by the `ignore` `NameMap`.\n-/\ndef additiveTest (findTranslation? : Name \u2192 Option Name)\n  (ignore : Name \u2192 Option (List \u2115)) (e : Expr) : Bool :=\n  additiveTestAux findTranslation? ignore false e\n\n/-- Swap the first two elements of a list -/\ndef _root_.List.swapFirstTwo {\u03b1 : Type _} : List \u03b1 \u2192 List \u03b1\n| []      => []\n| [x]     => [x]\n| x::y::l => y::x::l\n\n/-- Change the numeral `nat_lit 1` to the numeral `nat_lit 0`.\nLeave all other expressions unchanged. -/\ndef changeNumeral : Expr \u2192 Expr\n| .lit (.natVal 1) => mkRawNatLit 0\n| e                => e\n\n/--\n`applyReplacementFun e` replaces the expression `e` with its additive counterpart.\nIt translates each identifier (inductive type, defined function etc) in an expression, unless\n* The identifier occurs in an application with first argument `arg`; and\n* `test arg` is false.\nHowever, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`\nis tested, instead of the first argument.\n\nIt will also reorder arguments of certain functions, using `reorderFn`:\ne.g. `g x\u2081 x\u2082 x\u2083 ... x\u2099` becomes `g x\u2082 x\u2081 x\u2083 ... x\u2099` if `reorderFn g = some [1]`.\n-/\ndef applyReplacementFun (e : Expr) : MetaM Expr := do\n  let env \u2190 getEnv\n  let reorderFn : Name \u2192 List \u2115 := fun nm \u21a6 (reorderAttr.find? env nm |>.getD [])\n  let isRelevant : Name \u2192 \u2115 \u2192 Bool := fun nm i \u21a6 i == (relevantArgAttr.find? env nm).getD 0\n  return aux\n      (findTranslation? <| \u2190 getEnv) reorderFn (ignoreArgsAttr.find? env)\n      (changeNumeralAttr.find? env) isRelevant (\u2190 getBoolOption `trace.to_additive_detail) e\nwhere /-- Implementation of `applyReplacementFun`. -/\n  aux (findTranslation? : Name \u2192 Option Name)\n    (reorderFn : Name \u2192 List \u2115) (ignore : Name \u2192 Option (List \u2115))\n    (changeNumeral? : Name \u2192 Option (List Nat)) (isRelevant : Name \u2192 \u2115 \u2192 Bool) (trace : Bool) :\n    Expr \u2192 Expr :=\n  Lean.Expr.replaceRec fun r e \u21a6 Id.run do\n    if trace then\n      dbg_trace s!\"replacing at {e}\"\n    match e with\n    | .const n\u2080 ls => do\n      let n\u2081 := n\u2080.mapPrefix findTranslation?\n      if trace && n\u2080 != n\u2081 then\n        dbg_trace s!\"changing {n\u2080} to {n\u2081}\"\n      let ls : List Level := if 1 \u2208 reorderFn n\u2080 then ls.swapFirstTwo else ls\n      return some <| Lean.mkConst n\u2081 ls\n    | .app g x => do\n      let gf := g.getAppFn\n      if gf.isBVar && x.isLit then\n        if trace then\n          dbg_trace s!\"applyReplacementFun: Variables applied to numerals are not changed {g.app x}\"\n        return some <| g.app x\n      if let some nm := gf.constName? then\n        let gArgs := g.getAppArgs\n        -- e = `(nm y\u2081 .. y\u2099 x)\n        /- Test if arguments should be reordered. -/\n        if h : gArgs.size > 0 then\n          let c1 : Bool := gArgs.size \u2208 reorderFn nm\n          let c2 := additiveTest findTranslation? ignore gArgs[0]\n          if c1 && c2 then\n            -- interchange `x` and the last argument of `g`\n            let x := r x\n            let gf := r g.appFn!\n            let ga := r g.appArg!\n            let e\u2082 := mkApp2 gf x ga\n            if trace then\n              dbg_trace s!\"reordering {nm}: {x} \u2194 {ga}\\nBefore: {e}\\nAfter: {e\u2082}\"\n            return some e\u2082\n        /- Test if the head should not be replaced. -/\n        let c1 := isRelevant nm gArgs.size\n        let c2 := gf.isConst\n        let c3 := additiveTest findTranslation? ignore x\n        if trace && c1 && c2 && c3 then\n          dbg_trace s!\"{x} doesn't contain a fixed type, so we will change {nm}\"\n        if c1 && c2 && not c3 then\n          if trace then\n            dbg_trace s!\"{x} contains a fixed type, so {nm} is not changed\"\n          let x \u2190 r x\n          let args \u2190 gArgs.mapM r\n          return some $ mkApp (mkAppN gf args) x\n        /- Do not replace numerals in specific types. -/\n        let gAllArgs := gArgs.push x\n        let firstArg := gAllArgs[0]\n        if let some changedArgNrs := changeNumeral? nm then\n          if additiveTest findTranslation? ignore firstArg then\n            if trace then\n              dbg_trace s!\"applyReplacementFun: We change the numerals in {g.app x}. {\n                \"\"}However, we will still recurse into all the non-numeral arguments.\"\n            -- In this case, we still update all arguments of `g` that are not numerals,\n            -- since all other arguments can contain subexpressions like\n            -- `(fun x \u21a6 \u2115) (1 : G)`, and we have to update the `(1 : G)` to `(0 : G)`\n            let newArgs \u2190 gAllArgs.mapIdx fun argNr arg \u21a6\n              if changedArgNrs.contains argNr then\n                r <| changeNumeral arg\n              else\n                r arg\n            return some <| mkAppN gf newArgs\n      return e.updateApp! (\u2190 r g) (\u2190 r x)\n    | .proj n\u2080 idx e => do\n      let n\u2081 := n\u2080.mapPrefix findTranslation?\n      if trace then\n        dbg_trace s!\"applyReplacementFun: in projection {e}.{idx} of type {n\u2080}, {\"\"\n          }replace type with {n\u2081}\"\n      return some <| .proj n\u2081 idx <| \u2190 r e\n    | _ => return none\n\n/-- Eta expands `e` at most `n` times.-/\ndef etaExpandN (n : Nat) (e : Expr): MetaM Expr := do\n  forallBoundedTelescope (\u2190 inferType e) (some n) fun xs _ \u21a6 mkLambdaFVars xs (mkAppN e xs)\n\n/-- `e.expand` eta-expands all expressions that have as head a constant `n` in\n`reorder`. They are expanded until they are applied to one more argument than the maximum in\n`reorder.find n`. -/\ndef expand (e : Expr) : MetaM Expr := do\n  let env \u2190 getEnv\n  let reorderFn : Name \u2192 List \u2115 := fun nm \u21a6 (reorderAttr.find? env nm |>.getD [])\n  let e\u2082 \u2190 Lean.Meta.transform (input := e) (post := fun e => return .done e) <| fun e \u21a6 do\n    let e0 := e.getAppFn\n    let es := e.getAppArgs\n    let some e0n := e0.constName? | return .continue\n    let reorder := reorderFn e0n\n    if reorder.isEmpty then\n      -- no need to expand if nothing needs reordering\n      return .continue\n    let needed_n := reorder.foldr Nat.max 0 + 1\n    -- the second disjunct is a temporary fix to avoid infinite loops.\n    -- We may need to use `replaceRec` or something similar to not change the head of an application\n    if needed_n \u2264 es.size || es.size == 0 then\n      return .continue\n    else\n      -- in this case, we need to reorder arguments that are not yet\n      -- applied, so first \u03b7-expand the function.\n      let e' \u2190 etaExpandN (needed_n - es.size) e\n      trace[to_additive_detail] \"expanded {e} to {e'}\"\n      return .continue e'\n  if e != e\u2082 then\n    trace[to_additive_detail] \"expand:\\nBefore: {e}\\nAfter:  {e\u2082}\"\n  return e\u2082\n\n/-- Reorder pi-binders. See doc of `reorderAttr` for the interpretation of the argument -/\ndef reorderForall (src : Expr) (reorder : List Nat := []) : MetaM Expr := do\n  if reorder == [] then\n    return src\n  forallTelescope src fun xs e => do\n    let xs \u2190 reorder.foldrM (init := xs) fun i xs =>\n      if h : i < xs.size then\n        pure <| xs.swap \u27e8i - 1, Nat.lt_of_le_of_lt i.pred_le h\u27e9 \u27e8i, h\u27e9\n      else\n        throwError \"the declaration does not have enough arguments to reorder the given arguments: {\n          xs.size} \u2264 {i}\"\n    mkForallFVars xs e\n\n/-- Reorder lambda-binders. See doc of `reorderAttr` for the interpretation of the argument -/\ndef reorderLambda (src : Expr) (reorder : List Nat := []) : MetaM Expr := do\n  if reorder == [] then\n    return src\n  lambdaTelescope src fun xs e => do\n    let xs \u2190 reorder.foldrM (init := xs) fun i xs =>\n      if h : i < xs.size then\n        pure <| xs.swap \u27e8i - 1, Nat.lt_of_le_of_lt i.pred_le h\u27e9 \u27e8i, h\u27e9\n      else\n        throwError \"the declaration does not have enough arguments to reorder the given arguments. {\n          xs.size} \u2264 {i}.\\nIf this is a field projection, make sure to use `@[to_additive]` on {\"\"\n          }the field first.\"\n    mkLambdaFVars xs e\n\n/-- Run applyReplacementFun on the given `srcDecl` to make a new declaration with name `tgt` -/\ndef updateDecl\n  (tgt : Name) (srcDecl : ConstantInfo) (reorder : List Nat := [])\n  : MetaM ConstantInfo := do\n  let mut decl := srcDecl.updateName tgt\n  if 1 \u2208 reorder then\n    decl := decl.updateLevelParams decl.levelParams.swapFirstTwo\n  decl := decl.updateType <| \u2190 applyReplacementFun <| \u2190 reorderForall (\u2190 expand decl.type) reorder\n  if let some v := decl.value? then\n    decl := decl.updateValue <| \u2190 applyReplacementFun <| \u2190 reorderLambda (\u2190 expand v) reorder\n  return decl\n\n/-- Find the target name of `pre` and all created auxiliary declarations. -/\ndef findTargetName (env : Environment) (src pre tgt_pre : Name) : CoreM Name :=\n  /- This covers auxiliary declarations like `match_i` and `proof_i`. -/\n  if let some post := pre.isPrefixOf? src then\n    return tgt_pre ++ post\n  /- This covers equation lemmas (for other declarations). -/\n  else if let some post := privateToUserName? src then\n    match findTranslation? env post.getPrefix with\n    -- this is an equation lemma for a declaration without `to_additive`. We will skip this.\n    | none => return src\n    -- this is an equation lemma for a declaration with `to_additive`. We will additivize this.\n    -- Note: if this errors we could do this instead by calling `getEqnsFor?`\n    | some addName => return src.updatePrefix <| mkPrivateName env addName\n  -- Note: this additivizes lemmas generated by `simp`.\n  -- Todo: we do not currently check whether such lemmas actually should be additivized.\n  else if let some post := env.mainModule ++ `_auxLemma |>.isPrefixOf? src then\n    return env.mainModule ++ `_auxAddLemma ++ post\n  else\n    throwError \"internal @[to_additive] error.\"\n\n/-- Returns a `NameSet` of all auxiliary constants in `e` that might have been generated\nwhen adding `pre` to the environment.\nExamples include `pre.match_5`, `Mathlib.MyFile._auxLemma.3` and\n`_private.Mathlib.MyFile.someOtherNamespace.someOtherDeclaration._eq_2`.\nThe last two examples may or may not have been generated by this declaration.\nThe last example may or may not be the equation lemma of a declaration with the `@[to_additive]`\nattribute. We will only translate it has the `@[to_additive]` attribute.\n-/\ndef findAuxDecls (e : Expr) (pre mainModule : Name) : NameSet :=\nlet auxLemma := mainModule ++ `_auxLemma\ne.foldConsts \u2205 fun n l \u21a6\n  if n.getPrefix == pre || n.getPrefix == auxLemma || isPrivateName n then\n    l.insert n\n  else\n    l\n\n/-- transform the declaration `src` and all declarations `pre._proof_i` occurring in `src`\nusing the transforms dictionary.\n`replace_all`, `trace`, `ignore` and `reorder` are configuration options.\n`pre` is the declaration that got the `@[to_additive]` attribute and `tgt_pre` is the target of this\ndeclaration. -/\npartial def transformDeclAux\n  (cfg : Config) (pre tgt_pre : Name) : Name \u2192 CoreM Unit := fun src \u21a6 do\n  let env \u2190 getEnv\n  trace[to_additive_detail] \"visiting {src}\"\n  -- if we have already translated this declaration, we do nothing.\n  if (findTranslation? env src).isSome && src != pre then\n      return\n  -- if this declaration is not `pre` and not an internal declaration, we return an error,\n  -- since we should have already translated this declaration.\n  if src != pre && !src.isInternal' then\n    throwError \"The declaration {pre} depends on the declaration {src} which is in the namespace {\n      pre}, but does not have the `@[to_additive]` attribute. This is not supported.\\n{\"\"\n      }Workaround: move {src} to a different namespace.\"\n  -- we find the additive name of `src`\n  let tgt \u2190 findTargetName env src pre tgt_pre\n  -- we skip if we already transformed this declaration before.\n  if env.contains tgt then\n    if tgt == src then\n      -- Note: this can happen for equation lemmas of declarations without `@[to_additive]`.\n      trace[to_additive_detail] \"Auxiliary declaration {src} will be translated to itself.\"\n    else\n      trace[to_additive_detail] \"Already visited {tgt} as translation of {src}.\"\n    return\n  let srcDecl \u2190 getConstInfo src\n  -- we first transform all auxiliary declarations generated when elaborating `pre`\n  for n in findAuxDecls srcDecl.type pre env.mainModule do\n    transformDeclAux cfg pre tgt_pre n\n  if let some value := srcDecl.value? then\n    for n in findAuxDecls value pre env.mainModule do\n      transformDeclAux cfg pre tgt_pre n\n  -- if the auxilliary declaration doesn't have prefix `pre`, then we have to add this declaration\n  -- to the translation dictionary, since otherwise we cannot find the additive name.\n  if !pre.isPrefixOf src then\n    insertTranslation src tgt\n  -- now transform the source declaration\n  let trgDecl : ConstantInfo \u2190\n    MetaM.run' <| updateDecl tgt srcDecl <| if src == pre then cfg.reorder else []\n  if !trgDecl.hasValue then\n    throwError \"Expected {tgt} to have a value.\"\n  trace[to_additive] \"generating\\n{tgt} : {trgDecl.type} :=\\n  {trgDecl.value!}\"\n  try\n    -- make sure that the type is correct,\n    -- and emit a more helpful error message if it fails\n    discard <| MetaM.run' <| inferType trgDecl.value!\n  catch\n    | Exception.error _ msg => throwError \"@[to_additive] failed.\n      Type mismatch in additive declaration. For help, see the docstring\n      of `to_additive.attr`, section `Troubleshooting`.\n      Failed to add declaration\\n{tgt}:\\n{msg}\"\n    | _ => panic! \"unreachable\"\n  if isNoncomputable env src then\n    addDecl trgDecl.toDeclaration!\n    setEnv $ addNoncomputable (\u2190 getEnv) tgt\n  else\n    addAndCompile trgDecl.toDeclaration!\n  -- now add declaration ranges so jump-to-definition works\n  -- note: we currently also do this for auxiliary declarations, while they are not normally\n  -- generated for those. We could change that.\n  addDeclarationRanges tgt {\n    range := \u2190 getDeclarationRange (\u2190 getRef)\n    selectionRange := \u2190 getDeclarationRange cfg.ref }\n  if isProtected (\u2190 getEnv) src then\n    setEnv $ addProtected (\u2190 getEnv) tgt\n\n/-- Copy the instance attribute in a `to_additive`\n\n[todo] it seems not to work when the `to_additive` is added as an attribute later. -/\ndef copyInstanceAttribute (src tgt : Name) : CoreM Unit := do\n  if (\u2190 isInstance src) then\n    let prio := (\u2190 getInstancePriority? src).getD 100\n    let attr_kind := (\u2190 getInstanceAttrKind? src).getD .global\n    trace[to_additive_detail] \"Making {tgt} an instance with priority {prio}.\"\n    addInstance tgt attr_kind prio |>.run'\n\n/-- Warn the user when the multiplicative declaration has an attribute. -/\ndef warnExt [Inhabited \u03c3] (stx : Syntax) (ext : PersistentEnvExtension \u03b1 \u03b2 \u03c3) (f : \u03c3 \u2192 Name \u2192 Bool)\n  (thisAttr attrName src tgt : Name) : CoreM Unit := do\n  if f (ext.getState (\u2190 getEnv)) src then\n    Linter.logLintIf linter.existingAttributeWarning stx <|\n      m!\"The source declaration {src} was given attribute {attrName} before calling @[{thisAttr}]. {\n      \"\"}The preferred method is to use `@[{thisAttr} (attr := {attrName})]` to apply the {\n      \"\"}attribute to both {src} and the target declaration {tgt}.\" ++\n      if thisAttr == `to_additive then\n      m!\"\\nSpecial case: If this declaration was generated by @[to_additive] {\n      \"\"}itself, you can use @[to_additive (attr := to_additive, {attrName})] on the original {\n      \"\"}declaration.\" else \"\"\n\n/-- Warn the user when the multiplicative declaration has a simple scoped attribute. -/\ndef warnAttr [Inhabited \u03b2] (stx : Syntax) (attr : SimpleScopedEnvExtension \u03b1 \u03b2)\n  (f : \u03b2 \u2192 Name \u2192 Bool) (thisAttr attrName src tgt : Name) : CoreM Unit :=\nwarnExt stx attr.ext (f \u00b7.stateStack.head!.state \u00b7) thisAttr attrName src tgt\n\n/-- Warn the user when the multiplicative declaration has a parametric attribute. -/\ndef warnParametricAttr (stx : Syntax) (attr : ParametricAttribute \u03b2)\n  (thisAttr attrName src tgt : Name) : CoreM Unit :=\nwarnExt stx attr.ext (\u00b7.contains \u00b7) thisAttr attrName src tgt\n\n/-- `runAndAdditivize names desc t` runs `t` on all elements of `names`\nand adds translations between the generated lemmas (the output of `t`).\n`names` must be non-empty. -/\ndef additivizeLemmas [Monad m] [MonadError m] [MonadLiftT CoreM m]\n  (names : Array Name) (desc : String) (t : Name \u2192 m (Array Name)) : m Unit := do\n  let auxLemmas \u2190 names.mapM t\n  let nLemmas := auxLemmas[0]!.size\n  for (nm, lemmas) in names.zip auxLemmas do\n    unless lemmas.size == nLemmas do\n      throwError \"{names[0]!} and {nm} do not generate the same number of {desc}.\"\n  for (srcLemmas, tgtLemmas) in auxLemmas.zip <| auxLemmas.eraseIdx 0 do\n    for (srcLemma, tgtLemma) in srcLemmas.zip tgtLemmas do\n      insertTranslation srcLemma tgtLemma\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.One` returns 2.\nNote: we only consider the first argument of each type-class.\nE.g. `[Pow A N]` is a multiplicative type-class on `A`, not on `N`.\n-/\ndef firstMultiplicativeArg (nm : Name) : MetaM Nat := do\n  forallTelescopeReducing (\u2190 getConstInfo nm).type fun xs _ \u21a6 do\n    -- xs are the arguments to the constant\n    let xs := xs.toList\n    let l \u2190 xs.filterMapM fun x \u21a6 do\n      -- x is an argument and i is the index\n      -- write `x : (y\u2080 : \u03b1\u2080) \u2192 ... \u2192 (y\u2099 : \u03b1\u2099) \u2192 tgt_fn tgt_args\u2080 ... tgt_args\u2098`\n      forallTelescopeReducing (\u2190 inferType x) fun _ys tgt \u21a6 do\n        let (_tgt_fn, tgt_args) := tgt.getAppFnArgs\n        if let some c := tgt.getAppFn.constName? then\n          if findTranslation? (\u2190 getEnv) c |>.isNone then\n            return none\n        return tgt_args[0]?.bind fun tgtArg \u21a6\n          xs.findIdx? fun x \u21a6 Expr.containsFVar tgtArg x.fvarId!\n    trace[to_additive_detail] \"firstMultiplicativeArg: {l}\"\n    match l with\n    | [] => return 0\n    | (head :: tail) => return tail.foldr Nat.min head\n\n/-- Helper for `capitalizeLike`. -/\npartial def capitalizeLikeAux (s : String) (i : String.Pos := 0) (p : String) : String :=\n  if p.atEnd i || s.atEnd i then\n    p\n  else\n    let j := p.next i\n    if (s.get i).isLower then\n      capitalizeLikeAux s j <| p.set i (p.get i |>.toLower)\n    else if (s.get i).isUpper then\n      capitalizeLikeAux s j <| p.set i (p.get i |>.toUpper)\n    else\n      capitalizeLikeAux s j p\n\n/-- Capitalizes `s` char-by-char like `r`. If `s` is longer, it leaves the tail untouched. -/\ndef capitalizeLike (r : String) (s : String) :=\n  capitalizeLikeAux r 0 s\n\n/-- Capitalize First element of a list like `s`.\nNote that we need to capitalize multiple characters in some cases,\nin examples like `HMul` or `hAdd`. -/\ndef capitalizeFirstLike (s : String) : List String \u2192 List String\n  | x :: r => capitalizeLike s x :: r\n  | [] => []\n\n/--\nDictionary used by `guessName` to autogenerate names.\n\nNote: `guessName` capitalizes first element of the output according to\ncapitalization of the input. Input and first element should therefore be lower-case,\n2nd element should be capitalized properly.\n-/\ndef nameDict : String \u2192 List String\n| \"one\"         => [\"zero\"]\n| \"mul\"         => [\"add\"]\n| \"smul\"        => [\"vadd\"]\n| \"inv\"         => [\"neg\"]\n| \"div\"         => [\"sub\"]\n| \"prod\"        => [\"sum\"]\n| \"hmul\"        => [\"hadd\"]\n| \"hsmul\"       => [\"hvadd\"]\n| \"hdiv\"        => [\"hsub\"]\n| \"hpow\"        => [\"hsmul\"]\n| \"finprod\"     => [\"finsum\"]\n| \"pow\"         => [\"nsmul\"]\n| \"npow\"        => [\"nsmul\"]\n| \"zpow\"        => [\"zsmul\"]\n| \"monoid\"      => [\"add\", \"Monoid\"]\n| \"submonoid\"   => [\"add\", \"Submonoid\"]\n| \"group\"       => [\"add\", \"Group\"]\n| \"subgroup\"    => [\"add\", \"Subgroup\"]\n| \"semigroup\"   => [\"add\", \"Semigroup\"]\n| \"magma\"       => [\"add\", \"Magma\"]\n| \"haar\"        => [\"add\", \"Haar\"]\n| \"prehaar\"     => [\"add\", \"Prehaar\"]\n| \"unit\"        => [\"add\", \"Unit\"]\n| \"units\"       => [\"add\", \"Units\"]\n| \"rootable\"    => [\"divisible\"]\n| x             => [x]\n\n/--\nTurn each element to lower-case, apply the `nameDict` and\ncapitalize the output like the input.\n-/\ndef applyNameDict : List String \u2192 List String\n| x :: s => (capitalizeFirstLike x (nameDict x.toLower)) ++ applyNameDict s\n| [] => []\n\n/--\nThere are a few abbreviations we use. For example \"Nonneg\" instead of \"ZeroLE\"\nor \"addComm\" instead of \"commAdd\".\nNote: The input to this function is case sensitive!\nTodo: A lot of abbreviations here are manual fixes and there might be room to\n      improve the naming logic to reduce the size of `fixAbbreviation`.\n-/\ndef fixAbbreviation : List String \u2192 List String\n| \"cancel\" :: \"Add\" :: s            => \"addCancel\" :: fixAbbreviation s\n| \"Cancel\" :: \"Add\" :: s            => \"AddCancel\" :: fixAbbreviation s\n| \"left\" :: \"Cancel\" :: \"Add\" :: s  => \"addLeftCancel\" :: fixAbbreviation s\n| \"Left\" :: \"Cancel\" :: \"Add\" :: s  => \"AddLeftCancel\" :: fixAbbreviation s\n| \"right\" :: \"Cancel\" :: \"Add\" :: s => \"addRightCancel\" :: fixAbbreviation s\n| \"Right\" :: \"Cancel\" :: \"Add\" :: s => \"AddRightCancel\" :: fixAbbreviation s\n| \"cancel\" :: \"Comm\" :: \"Add\" :: s  => \"addCancelComm\" :: fixAbbreviation s\n| \"Cancel\" :: \"Comm\" :: \"Add\" :: s  => \"AddCancelComm\" :: fixAbbreviation s\n| \"comm\" :: \"Add\" :: s              => \"addComm\" :: fixAbbreviation s\n| \"Comm\" :: \"Add\" :: s              => \"AddComm\" :: fixAbbreviation s\n| \"Zero\" :: \"LE\" :: s               => \"Nonneg\" :: fixAbbreviation s\n| \"zero\" :: \"_\" :: \"le\" :: s        => \"nonneg\" :: fixAbbreviation s\n| \"Zero\" :: \"LT\" :: s               => \"Pos\" :: fixAbbreviation s\n| \"zero\" :: \"_\" :: \"lt\" :: s        => \"pos\" :: fixAbbreviation s\n| \"LE\" :: \"Zero\" :: s               => \"Nonpos\" :: fixAbbreviation s\n| \"le\" :: \"_\" :: \"zero\" :: s        => \"nonpos\" :: fixAbbreviation s\n| \"LT\" :: \"Zero\" :: s               => \"Neg\" :: fixAbbreviation s\n| \"lt\" :: \"_\" :: \"zero\" :: s        => \"neg\" :: fixAbbreviation s\n| \"Add\" :: \"Single\" :: s            => \"Single\" :: fixAbbreviation s\n| \"add\" :: \"Single\" :: s            => \"single\" :: fixAbbreviation s\n| \"add\" :: \"_\" :: \"single\" :: s     => \"single\" :: fixAbbreviation s\n| \"Add\" :: \"Support\" :: s           => \"Support\" :: fixAbbreviation s\n| \"add\" :: \"Support\" :: s           => \"support\" :: fixAbbreviation s\n| \"add\" :: \"_\" :: \"support\" :: s    => \"support\" :: fixAbbreviation s\n| \"Add\" :: \"TSupport\" :: s          => \"TSupport\" :: fixAbbreviation s\n| \"add\" :: \"TSupport\" :: s          => \"tsupport\" :: fixAbbreviation s\n| \"add\" :: \"_\" :: \"tsupport\" :: s   => \"tsupport\" :: fixAbbreviation s\n| \"Add\" :: \"Indicator\" :: s         => \"Indicator\" :: fixAbbreviation s\n| \"add\" :: \"Indicator\" :: s         => \"indicator\" :: fixAbbreviation s\n| \"add\" :: \"_\" :: \"indicator\" :: s  => \"indicator\" :: fixAbbreviation s\n| \"is\" :: \"Square\" :: s             => \"even\" :: fixAbbreviation s\n| \"Is\" :: \"Square\" :: s             => \"Even\" :: fixAbbreviation s\n-- \"Regular\" is well-used in mathlib3 with various meanings (e.g. in\n-- measure theory) and a direct translation\n-- \"regular\" --> [\"add\", \"Regular\"] in `nameDict` above seems error-prone.\n| \"is\" :: \"Regular\" :: s            => \"isAddRegular\" :: fixAbbreviation s\n| \"Is\" :: \"Regular\" :: s            => \"IsAddRegular\" :: fixAbbreviation s\n| \"is\" :: \"Left\" :: \"Regular\" :: s  => \"isAddLeftRegular\" :: fixAbbreviation s\n| \"Is\" :: \"Left\" :: \"Regular\" :: s  => \"IsAddLeftRegular\" :: fixAbbreviation s\n| \"is\" :: \"Right\" :: \"Regular\" :: s => \"isAddRightRegular\" :: fixAbbreviation s\n| \"Is\" :: \"Right\" :: \"Regular\" :: s => \"IsAddRightRegular\" :: fixAbbreviation s\n-- the capitalization heuristic of `applyNameDict` doesn't work in the following cases\n| \"HSmul\" :: s                      => \"HSMul\" :: fixAbbreviation s -- from `HPow`\n| \"NSmul\" :: s                      => \"NSMul\" :: fixAbbreviation s -- from `NPow`\n| \"Nsmul\" :: s                      => \"NSMul\" :: fixAbbreviation s -- from `Pow`\n| \"ZSmul\" :: s                      => \"ZSMul\" :: fixAbbreviation s -- from `ZPow`\n| \"neg\" :: \"Fun\" :: s               => \"invFun\" :: fixAbbreviation s\n| \"Neg\" :: \"Fun\" :: s               => \"InvFun\" :: fixAbbreviation s\n| \"order\" :: \"Of\" :: s              => \"addOrderOf\" :: fixAbbreviation s\n| \"Order\" :: \"Of\" :: s              => \"AddOrderOf\" :: fixAbbreviation s\n| \"is\"::\"Of\"::\"Fin\"::\"Order\"::s     => \"isOfFinAddOrder\" :: fixAbbreviation s\n| \"Is\"::\"Of\"::\"Fin\"::\"Order\"::s     => \"IsOfFinAddOrder\" :: fixAbbreviation s\n| \"is\" :: \"Central\" :: \"Scalar\" :: s  => \"isCentralVAdd\" :: fixAbbreviation s\n| \"Is\" :: \"Central\" :: \"Scalar\" :: s  => \"IsCentralVAdd\" :: fixAbbreviation s\n| x :: s                            => x :: fixAbbreviation s\n| []                                => []\n\n/--\nAutogenerate additive name.\nThis runs in several steps:\n1) Split according to capitalisation rule and at `_`.\n2) Apply word-by-word translation rules.\n3) Fix up abbreviations that are not word-by-word translations, like \"addComm\" or \"Nonneg\".\n-/\ndef guessName : String \u2192 String :=\n  String.mapTokens '\\'' <|\n  fun s =>\n    String.join <|\n    fixAbbreviation <|\n    applyNameDict <|\n    s.splitCase\n\n/-- Return the provided target name or autogenerate one if one was not provided. -/\ndef targetName (cfg : Config) (src : Name) : CoreM Name := do\n  let .str pre s := src | throwError \"to_additive: can't transport {src}\"\n  trace[to_additive_detail] \"The name {s} splits as {s.splitCase}\"\n  let tgt_auto := guessName s\n  let depth := cfg.tgt.getNumParts\n  let pre := pre.mapPrefix <| findTranslation? (\u2190 getEnv)\n  let (pre1, pre2) := pre.splitAt (depth - 1)\n  if cfg.tgt == pre2.str tgt_auto && !cfg.allowAutoName && cfg.tgt != src then\n    Linter.logLintIf linter.toAdditiveGenerateName cfg.ref\n      m!\"to_additive correctly autogenerated target name for {src}. {\"\\n\"\n      }You may remove the explicit argument {cfg.tgt}.\"\n  let res := if cfg.tgt == .anonymous then pre.str tgt_auto else pre1 ++ cfg.tgt\n  -- we allow translating to itself if `tgt == src`, which is occasionally useful for `additiveTest`\n  if res == src && cfg.tgt != src then\n    throwError \"to_additive: can't transport {src} to itself.\"\n  if cfg.tgt != .anonymous then\n    trace[to_additive_detail] \"The automatically generated name would be {pre.str tgt_auto}\"\n  return res\n\n/-- if `f src = #[a_1, ..., a_n]` and `f tgt = #[b_1, ... b_n]` then `proceedFieldsAux src tgt f`\n  will insert translations from `src.a_i` to `tgt.b_i`. -/\ndef proceedFieldsAux (src tgt : Name) (f : Name \u2192 CoreM (Array Name)) : CoreM Unit := do\n  let srcFields \u2190 f src\n  let tgtFields \u2190 f tgt\n  if srcFields.size != tgtFields.size then\n    throwError \"Failed to map fields of {src}, {tgt} with {srcFields} \u21a6 {tgtFields}\"\n  for (srcField, tgtField) in srcFields.zip tgtFields do\n    if srcField != tgtField then\n      insertTranslation (src ++ srcField) (tgt ++ tgtField)\n    else\n      trace[to_additive] \"Translation {src ++ srcField} \u21a6 {tgt ++ tgtField} is automatic.\"\n\n/-- Add the structure fields of `src` to the translations dictionary\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\ndef proceedFields (src tgt : Name) : CoreM Unit := do\n  let aux := proceedFieldsAux src tgt\n  aux fun declName \u21a6 do\n    if isStructure (\u2190 getEnv) declName then\n      return getStructureFields (\u2190 getEnv) declName\n    else\n      return #[]\n  aux fun declName \u21a6 do match (\u2190 getEnv).find? declName with\n    | some (ConstantInfo.inductInfo {ctors := ctors, ..}) => return ctors.toArray.map (\u00b7.getString)\n    | _ => pure #[]\n\n/-- Elaboration of the configuration options for `to_additive`. -/\ndef elabToAdditive : Syntax \u2192 CoreM Config\n  | `(attr| to_additive%$tk $[?%$trace]? $[$opts:toAdditiveOption]* $[$tgt]? $[$doc]?) => do\n    let mut attrs : Array Syntax := #[]\n    let mut reorder := []\n    let mut existing := some false\n    for stx in opts do\n      match stx with\n      | `(toAdditiveOption| (attr := $[$stxs],*)) =>\n        attrs := attrs ++ stxs\n      | `(toAdditiveOption| (reorder := $[$reorders:num]*)) =>\n        reorder := reorder ++ reorders.toList.map (\u00b7.raw.isNatLit?.get!)\n      | `(toAdditiveOption| existing) =>\n        existing := some true\n      | _ => throwUnsupportedSyntax\n    trace[to_additive_detail] \"attributes: {attrs}; reorder arguments: {reorder}\"\n    return { trace := trace.isSome\n             tgt := match tgt with | some tgt => tgt.getId | none => Name.anonymous\n             doc := doc.bind (\u00b7.raw.isStrLit?)\n             allowAutoName := false\n             attrs\n             reorder\n             existing\n             ref := (tgt.map (\u00b7.raw)).getD tk }\n  | _ => throwUnsupportedSyntax\n\nmutual\n/-- Apply attributes to the multiplicative and additive declarations. -/\npartial def applyAttributes (stx : Syntax) (rawAttrs : Array Syntax) (thisAttr src tgt : Name) :\n  TermElabM (Array Name) := do\n  -- we only copy the `instance` attribute, since `@[to_additive] instance` is nice to allow\n  copyInstanceAttribute src tgt\n  -- Warn users if the multiplicative version has an attribute\n  if linter.existingAttributeWarning.get (\u2190 getOptions) then\n    let appliedAttrs \u2190 getAllSimpAttrs src\n    if appliedAttrs.size > 0 then\n      Linter.logLintIf linter.existingAttributeWarning stx <|\n        m!\"The source declaration {src} was given the simp-attribute(s) {appliedAttrs} before {\n        \"\"}calling @[{thisAttr}]. The preferred method is to use {\n        \"\"}`@[{thisAttr} (attr := {appliedAttrs})]` to apply the attribute to both {\n        src} and the target declaration {tgt}.\"\n    warnAttr stx Std.Tactic.Ext.extExtension (fun b n => (b.elements.any fun t => t.declName = n))\n      thisAttr `ext src tgt\n    warnAttr stx Mathlib.Tactic.reflExt (\u00b7.elements.contains \u00b7) thisAttr `refl src tgt\n    warnAttr stx Mathlib.Tactic.symmExt (\u00b7.elements.contains \u00b7) thisAttr `symm src tgt\n    warnAttr stx Mathlib.Tactic.transExt (\u00b7.elements.contains \u00b7) thisAttr `trans src tgt\n    warnAttr stx Std.Tactic.Coe.coeExt (\u00b7.contains \u00b7) thisAttr `coe src tgt\n    warnParametricAttr stx Lean.Linter.deprecatedAttr thisAttr `deprecated src tgt\n    -- the next line also warns for `@[to_additive, simps]`, because of the application times\n    warnParametricAttr stx simpsAttr thisAttr `simps src tgt\n    warnExt stx Term.elabAsElim.ext (\u00b7.contains \u00b7) thisAttr `elab_as_elim src tgt\n  -- add attributes\n  -- the following is similar to `Term.ApplyAttributesCore`, but we hijack the implementation of\n  -- `simp`, `simps` and `to_additive`.\n  let attrs \u2190 elabAttrs rawAttrs\n  let (additiveAttrs, attrs) := attrs.partition (\u00b7.name == `to_additive)\n  let nestedDecls \u2190\n    match additiveAttrs.size with\n      | 0 => pure #[]\n      | 1 => addToAdditiveAttr tgt (\u2190 elabToAdditive additiveAttrs[0]!.stx) additiveAttrs[0]!.kind\n      | _ => throwError \"cannot apply {thisAttr} multiple times.\"\n  let allDecls := #[src, tgt] ++ nestedDecls\n  if attrs.size > 0 then\n    trace[to_additive_detail] \"Applying attributes {attrs.map (\u00b7.stx)} to {allDecls}\"\n  for attr in attrs do\n    withRef attr.stx do withLogging do\n    -- todo: also support other simp-attributes,\n    -- and attributes that generate simp-attributes, like `norm_cast`\n    if attr.name == `simp then\n      additivizeLemmas allDecls \"simp lemmas\"\n        (Meta.Simp.addSimpAttrFromSyntax \u00b7 simpExtension attr.kind attr.stx)\n      return\n    if attr.name == `simps then\n      additivizeLemmas allDecls \"simps lemmas\" (simpsTacFromSyntax \u00b7 attr.stx)\n      return\n    let env \u2190 getEnv\n    match getAttributeImpl env attr.name with\n    | Except.error errMsg => throwError errMsg\n    | Except.ok attrImpl  =>\n      let runAttr := do\n        attrImpl.add src attr.stx attr.kind\n        attrImpl.add tgt attr.stx attr.kind\n      -- not truly an elaborator, but a sensible target for go-to-definition\n      let elaborator := attrImpl.ref\n      if (\u2190 getInfoState).enabled && (\u2190 getEnv).contains elaborator then\n        withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do\n          try runAttr\n          finally if attr.stx[0].isIdent || attr.stx[0].isAtom then\n            -- Add an additional node over the leading identifier if there is one\n            -- to make it look more function-like.\n            -- Do this last because we want user-created infos to take precedence\n            pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] }\n      else\n        runAttr\n  return nestedDecls\n\n/--\nCopies equation lemmas and attributes from `src` to `tgt`\n-/\npartial def copyMetaData (cfg : Config) (src tgt : Name) : CoreM (Array Name) := do\n  /- We need to generate all equation lemmas for `src` and `tgt`, even for non-recursive\n  definitions. If we don't do that, the equation lemma for `src` might be generated later\n  when doing a `rw`, but it won't be generated for `tgt`. -/\n  additivizeLemmas #[src, tgt] \"equation lemmas\" fun nm \u21a6\n    (\u00b7.getD #[]) <$> MetaM.run' (getEqnsFor? nm true)\n  MetaM.run' <| Elab.Term.TermElabM.run' <|\n    applyAttributes cfg.ref cfg.attrs `to_additive src tgt\n\n/--\nMake a new copy of a declaration, replacing fragments of the names of identifiers in the type and\nthe body using the `translations` dictionary.\nThis is used to implement `@[to_additive]`.\n-/\npartial def transformDecl (cfg : Config) (src tgt : Name) : CoreM (Array Name) := do\n  transformDeclAux cfg src tgt src\n  copyMetaData cfg src tgt\n\n/-- `addToAdditiveAttr src cfg` adds a `@[to_additive]` attribute to `src` with configuration `cfg`.\nSee the attribute implementation for more details.\nIt returns an array with names of additive declarations (usually 1, but more if there are nested\n`to_additive` calls. -/\npartial def addToAdditiveAttr (src : Name) (cfg : Config) (kind := AttributeKind.global) :\n  AttrM (Array Name) := do\n  if (kind != AttributeKind.global) then\n    throwError \"`to_additive` can only be used as a global attribute\"\n  withOptions (\u00b7 |>.updateBool `trace.to_additive (cfg.trace || \u00b7)) <| do\n  let tgt \u2190 targetName cfg src\n  let alreadyExists := (\u2190 getEnv).contains tgt\n  if cfg.existing == some !alreadyExists && !(\u2190 isInductive src) then\n    Linter.logLintIf linter.toAdditiveExisting cfg.ref <|\n      if alreadyExists then\n        m!\"The additive declaration already exists. Please specify this explicitly using {\n          \"\"}`@[to_additive existing]`.\"\n      else\n        \"The additive declaration doesn't exist. Please remove the option `existing`.\"\n  if cfg.reorder != [] then\n    trace[to_additive] \"@[to_additive] will reorder the arguments of {tgt}.\"\n    reorderAttr.add src cfg.reorder\n    -- we allow using this attribute if it's only to add the reorder configuration\n    if findTranslation? (\u2190 getEnv) src |>.isSome then\n      return #[tgt]\n  let firstMultArg \u2190 MetaM.run' <| firstMultiplicativeArg src\n  if firstMultArg != 0 then\n    trace[to_additive_detail] \"Setting relevant_arg for {src} to be {firstMultArg}.\"\n    relevantArgAttr.add src firstMultArg\n  insertTranslation src tgt alreadyExists\n  let nestedNames \u2190\n    if alreadyExists then\n      -- since `tgt` already exists, we just need to copy metadata and\n      -- add translations `src.x \u21a6 tgt.x'` for any subfields.\n      trace[to_additive_detail] \"declaration {tgt} already exists.\"\n      proceedFields src tgt\n      copyMetaData cfg src tgt\n    else\n      -- tgt doesn't exist, so let's make it\n      transformDecl cfg src tgt\n  -- add pop-up information when mousing over `additive_name` of `@[to_additive additive_name]`\n  -- (the information will be over the attribute of no additive name is given)\n  pushInfoLeaf <| .ofTermInfo {\n    elaborator := .anonymous, lctx := {}, expectedType? := none, isBinder := !alreadyExists,\n    stx := cfg.ref, expr := \u2190 mkConstWithLevelParams tgt }\n  if let some doc := cfg.doc then\n    addDocString tgt doc\n  return nestedNames.push tgt\n\nend\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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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' {\u03b1} [comm_semigroup \u03b1] (x y : \u03b1) : 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\nUse the `(attr := ...)` syntax to apply attributes to both the multiplicative and the additive\nversion:\n\n```\n@[to_additive (attr := simp)] lemma mul_one' {G : Type _} [group G] (x : G) : x * 1 = x := mul_one x\n```\n\nFor `simp` and `simps` this also ensures that some generated lemmas are added to the additive\ndictionary.\n`@[to_additive (attr := to_additive)]` is a special case, where the `to_additive`\nattribute is added to the generated lemma only, to additivize it again.\nThis is useful for lemmas about `Pow` to generate both lemmas about `SMul` and `VAdd`. Example:\n```\n@[to_additive (attr := to_additive VAdd_lemma, simp) SMul_lemma]\nlemma Pow_lemma ...\n```\nIn the above example, the `simp` is added to all 3 lemmas. All other options to `to_additive`\n(like the generated name or `(reorder := ...)`) are not passed down,\nand can be given manually to each individual `to_additive` call.\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* `@Mul.mul Nat n m` (i.e. `(n * m : Nat)`) will not change to `+`, since its\n  first argument is `\u2115`, an identifier not applied to any arguments.\n* `@Mul.mul (\u03b1 \u00d7 \u03b2) x y` will change to `+`. It's first argument contains only the identifier\n  `prod`, but this is applied to arguments, `\u03b1` and `\u03b2`.\n* `@Mul.mul (\u03b1 \u00d7 Int) x y` will not change to `+`, since its first argument contains `Int`.\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 `\u21a5Semigroup` is replaced by addition in `\u21a5AddSemigroup`.\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 : WithTop Nat)` can contain `\u2115`\n  (usually in the form `Top.top Nat ...`) and still be additivized.\n  So `@Mul.mul (C^\u221e\u27eeI, N; I', G\u27ef) _ 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 `\u2115` or `\u211d`. 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      #eval (do isRelevant `d >>= 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 `\u2115` or `\u211d`. Solutions:\n  * If the fixed type has an additive counterpart (like `\u21a5Semigroup`), 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* 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 `AddMonoid.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 \u201cmain\u201d 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 \u201cmain\u201d declaration, `to_additive` transports\nits equational lemmas and tags them as equational lemmas for the new declaration.\n\n### Structure fields and constructors\n\nIf `src` is a structure, then the additive version has to be already written manually.\nIn this case `to_additive` adds all structure fields to its mapping.\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 (\u201cmul\u201d, \u201cone\u201d, \u201cinv\u201d, \u201cprod\u201d) with their additive versions.\n\n* [todo] 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-/\ninitialize registerBuiltinAttribute {\n    name := `to_additive\n    descr := \"Transport multiplicative to additive\"\n    add := fun src stx kind \u21a6 do _ \u2190 addToAdditiveAttr src (\u2190 elabToAdditive stx) kind\n    -- we (presumably) need to run after compilation to properly add the `simp` attribute\n    applicationTime := .afterCompilation\n  }\n\nend ToAdditive\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/ToAdditive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.05582314113461443, "lm_q1q2_score": 0.017719731223734436}}
{"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.Eqns\nimport Lean.Meta.Tactic.Split\nimport Lean.Meta.Tactic.Apply\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Eqns\nimport Lean.Elab.PreDefinition.Structural.Basic\n\nnamespace Lean.Elab\nopen Meta\nopen Eqns\n\nnamespace Structural\n\nstructure EqnInfo extends EqnInfoCore where\n  recArgPos   : Nat\n  deriving Inhabited\n\nprivate partial def mkProof (declName : Name) (type : Expr) : MetaM Expr := do\n  trace[Elab.definition.structural.eqns] \"proving: {type}\"\n  withNewMCtxDepth do\n    let main \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let (_, mvarId) \u2190 intros main.mvarId!\n    unless (\u2190 tryURefl mvarId) do -- catch easy cases\n      go (\u2190 deltaLHS mvarId)\n    instantiateMVars main\nwhere\n  go (mvarId : MVarId) : MetaM Unit := do\n    trace[Elab.definition.structural.eqns] \"step\\n{MessageData.ofGoal mvarId}\"\n    if (\u2190 tryURefl mvarId) then\n      return ()\n    else if (\u2190 tryContradiction mvarId) then\n      return ()\n    else if let some mvarId \u2190 simpMatch? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 simpIf? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 whnfReducibleLHS? mvarId then\n      go mvarId\n    else if let some mvarId \u2190 deltaRHS? mvarId declName then\n      go mvarId\n    else if let some mvarIds \u2190 casesOnStuckLHS? mvarId then\n      mvarIds.forM go\n    else\n      throwError \"failed to generate equational theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n\ndef mkEqns (info : EqnInfo) : MetaM (Array Name) :=\n  withOptions (tactic.hygienic.set . false) do\n  let eqnTypes \u2190 withNewMCtxDepth <| lambdaTelescope info.value fun xs body => do\n    let us := info.levelParams.map mkLevelParam\n    let target \u2190 mkEq (mkAppN (Lean.mkConst info.declName us) xs) body\n    let goal \u2190 mkFreshExprSyntheticOpaqueMVar target\n    mkEqnTypes #[info.declName] goal.mvarId!\n  let baseName := mkPrivateName (\u2190 getEnv) info.declName\n  let mut thmNames := #[]\n  for i in [: eqnTypes.size] do\n    let type := eqnTypes[i]\n    trace[Elab.definition.structural.eqns] \"{eqnTypes[i]}\"\n    let name := baseName ++ (`_eq).appendIndexAfter (i+1)\n    thmNames := thmNames.push name\n    let value \u2190 mkProof info.declName type\n    addDecl <| Declaration.thmDecl {\n      name, type, value\n      levelParams := info.levelParams\n    }\n  return thmNames\n\nbuiltin_initialize eqnInfoExt : MapDeclarationExtension EqnInfo \u2190 mkMapDeclarationExtension `structEqInfo\n\ndef registerEqnsInfo (preDef : PreDefinition) (recArgPos : Nat) : CoreM Unit := do\n  modifyEnv fun env => eqnInfoExt.insert env preDef.declName { preDef with recArgPos }\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  let env \u2190 getEnv\n  if let some eqs := eqnsExt.getState env |>.map.find? declName then\n    return some eqs\n  else if let some info := eqnInfoExt.find? env declName then\n    let eqs \u2190 mkEqns info\n    modifyEnv fun env => eqnsExt.modifyState env fun s => { s with map := s.map.insert declName eqs }\n    return some eqs\n  else\n    return none\n\ndef getUnfoldFor? (declName : Name) : MetaM (Option Name) := do\n  let env \u2190 getEnv\n  Eqns.getUnfoldFor? declName fun _ => eqnInfoExt.find? env declName |>.map (\u00b7.toEqnInfoCore)\n\nbuiltin_initialize\n  registerGetEqnsFn getEqnsFor?\n  registerGetUnfoldEqnFn getUnfoldFor?\n  registerTraceClass `Elab.definition.structural.eqns\n\nend Structural\nend Lean.Elab\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/Elab/PreDefinition/Structural/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.046033904853170125, "lm_q1q2_score": 0.01771900968561903}}
{"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\u2081 v\u2082 u\u2081 u\u2082 -- morphism levels before object levels. See note [category_theory universes].\n\nnamespace monad\n\nvariables {C : Type u\u2081} [category.{v\u2081} C]\nvariables {T : monad C}\n\nvariables {J : Type v\u2081} [small_category J]\n\nnamespace forget_creates_limits\n\nvariables (D : J \u2964 algebra T) (c : cone (D \u22d9 forget T)) (t : is_limit c)\n\n/-- (Impl) The natural transformation used to define the new cone -/\n@[simps] def \u03b3 : (D \u22d9 forget T \u22d9 \u2191T) \u27f6 (D \u22d9 forget T) := { app := \u03bb 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 \u22d9 forget T) :=\n{ X := T.obj c.X,\n  \u03c0 := (functor.const_comp _ _ \u2191T).inv \u226b whisker_right c.\u03c0 T \u226b (\u03b3 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, \u2190 category.assoc, \u2190 T.\u03b7.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 \u2190 T.\u03bc.naturality},\n    slice_lhs 2 3 {rw (D.obj j).assoc},\n    slice_rhs 1 2 {rw \u2190 (T : C \u2964 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  \u03c0 := { app := \u03bb j, { f := c.\u03c0.app j },\n         naturality' := \u03bb 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 := \u03bb 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 \u2190 (T : C \u2964 C).map_comp},\n      rw t.fac ((forget T).map_cone s) j,\n      exact (s.\u03c0.app j).h\n    end },\n  uniq' := \u03bb 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 := \u03bb J \ud835\udca5, by exactI\n  { creates_limit := \u03bb D,\n    creates_limit_of_reflects_iso (\u03bb c t,\n    { lifted_cone := forget_creates_limits.lifted_cone D c t,\n      valid_lift := cones.ext (iso.refl _) (\u03bb j, (id_comp _).symm),\n      makes_limit := forget_creates_limits.lifted_cone_is_limit _ _ _ } ) } }\n\n/-- `D \u22d9 forget T` has a limit, then `D` has a limit. -/\nlemma has_limit_of_comp_forget_has_limit (D : J \u2964 algebra T) [has_limit (D \u22d9 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 \u2964 algebra T} (c : cocone (D \u22d9 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 \u22d9 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 \u27f6 L. Since T preserves colimits, TL is also a colimit.\n-- In particular, it is a colimit for the diagram `(D \u22d9 forget T) \u22d9 T`\n-- so to construct a map TL \u27f6 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 \u22d9 forget T) \u22d9 T`.\n-- But we already know that L is the apex of a cocone for the diagram `D \u22d9 forget T`, so it\n-- suffices to give a natural transformation `((D \u22d9 forget T) \u22d9 T) \u27f6 (D \u22d9 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 \u22d9 forget T)`.\n -/\n@[simps] def \u03b3 : ((D \u22d9 forget T) \u22d9 \u2191T) \u27f6 (D \u22d9 forget T) := { app := \u03bb j, (D.obj j).a }\n\n/--\n(Impl)\nA cocone for the diagram `(D \u22d9 forget T) \u22d9 T` found by composing the natural transformation `\u03b3`\nwith the colimiting cocone for `D \u22d9 forget T`.\n-/\n@[simps]\ndef new_cocone : cocone ((D \u22d9 forget T) \u22d9 \u2191T) :=\n{ X := c.X,\n  \u03b9 := \u03b3 \u226b c.\u03b9 }\n\nvariables [preserves_colimit (D \u22d9 forget T) (T : C \u2964 C)]\n\n/--\n(Impl)\nDefine the map `\u03bb : TL \u27f6 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 \u2964 C).map_cocone c).X \u27f6 c.X :=\n(preserves_colimit.preserves t).desc (new_cocone c)\n\n/-- (Impl) The key property defining the map `\u03bb : TL \u27f6 L`. -/\nlemma commuting (j : J) :\nT.map (c.\u03b9.app j) \u226b lambda c t = (D.obj j).a \u226b c.\u03b9.app j :=\nis_colimit.fac (preserves_colimit.preserves t) (new_cocone c) j\n\nvariables [preserves_colimit ((D \u22d9 forget T) \u22d9 \u2191T) (T : C \u2964 C)]\n\n/--\n(Impl)\nConstruct the colimiting algebra from the map `\u03bb : TL \u27f6 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, \u2190 category.assoc, T.\u03b7.naturality, category.assoc, commuting, \u2190 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 [\u2190 category.assoc, T.\u03bc.naturality, \u2190 functor.map_cocone_\u03b9_app, category.assoc,\n         is_colimit.fac _ (new_cocone c) j],\n    rw \u2190 category.assoc,\n    erw [\u2190 functor.map_comp, commuting],\n    dsimp,\n    erw [\u2190 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  \u03b9 := { app := \u03bb j, { f := c.\u03b9.app j, h' := commuting _ _ _ },\n         naturality' := \u03bb 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 := \u03bb 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 \u2190 category.assoc, erw \u2190 functor.map_comp,\n      erw t.fac',\n      rw \u2190 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' := \u03bb 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 \u2964 algebra T)\n  [preserves_colimit (D \u22d9 forget T) (T : C \u2964 C)]\n  [preserves_colimit ((D \u22d9 forget T) \u22d9 \u2191T) (T : C \u2964 C)] :\n  creates_colimit D (forget T) :=\ncreates_colimit_of_reflects_iso $ \u03bb c t,\n{ lifted_cocone :=\n  { X := cocone_point c t,\n    \u03b9 :=\n    { app := \u03bb j, { f := c.\u03b9.app j, h' := commuting _ _ _ },\n      naturality' := \u03bb 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 \u2964 C)] :\n  creates_colimits_of_shape J (forget T) :=\n{ creates_colimit := \u03bb K, by apply_instance }\n\nnoncomputable\ninstance forget_creates_colimits\n  [preserves_colimits (T : C \u2964 C)] :\n  creates_colimits (forget T) :=\n{ creates_colimits_of_shape := \u03bb J \ud835\udca5\u2081, by apply_instance }\n\n/--\nFor `D : J \u2964 algebra T`, `D \u22d9 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 \u2964 C)] (D : J \u2964 algebra T) [has_colimit (D \u22d9 forget T)] :\nhas_colimit D :=\nhas_colimit_of_created D (forget T)\n\nend monad\n\nvariables {C : Type u\u2081} [category.{v\u2081} C] {D : Type u\u2082} [category.{v\u2081} D]\nvariables {J : Type v\u2081} [small_category J]\n\ninstance comp_comparison_forget_has_limit\n  (F : J \u2964 D) (R : D \u2964 C) [monadic_right_adjoint R] [has_limit (F \u22d9 R)] :\n  has_limit ((F \u22d9 monad.comparison (adjunction.of_right_adjoint R)) \u22d9 monad.forget _) :=\n@has_limit_of_iso _ _ _ _ (F \u22d9 R) _ _\n  (iso_whisker_left F (monad.comparison_forget (adjunction.of_right_adjoint R)).symm)\n\ninstance comp_comparison_has_limit\n  (F : J \u2964 D) (R : D \u2964 C) [monadic_right_adjoint R] [has_limit (F \u22d9 R)] :\n  has_limit (F \u22d9 monad.comparison (adjunction.of_right_adjoint R)) :=\nmonad.has_limit_of_comp_forget_has_limit (F \u22d9 monad.comparison (adjunction.of_right_adjoint R))\n\n/-- Any monadic functor creates limits. -/\nnoncomputable\ndef monadic_creates_limits (R : D \u2964 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 \u2964 C) (K : J \u2964 D)\n  [monadic_right_adjoint R]\n  [preserves_colimit (K \u22d9 R) (left_adjoint R \u22d9 R)]\n  [preserves_colimit ((K \u22d9 R) \u22d9 left_adjoint R \u22d9 R) (left_adjoint R \u22d9 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 \u22d9 monad.comparison (adjunction.of_right_adjoint R)) \u22d9 monad.forget _) \u2245 K \u22d9 R :=\n    functor.associator _ _ _ \u226a\u226b\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 \u22d9 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 \u2964 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 \u22d9 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 \u27e8\u03bb K, monadic_creates_colimit_of_preserves_colimit _ _\u27e9,\nend\n\n/-- A monadic functor creates colimits if it preserves colimits. -/\nnoncomputable\ndef monadic_creates_colimits_of_preserves_colimits (R : D \u2964 C) [monadic_right_adjoint R]\n  [preserves_colimits R] : creates_colimits R :=\n{ creates_colimits_of_shape := \u03bb J \ud835\udca5\u2081,\n    by exactI monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape _ }\n\nsection\n\nlemma has_limit_of_reflective (F : J \u2964 D) (R : D \u2964 C) [has_limit (F \u22d9 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 \u2964 C) [reflective R] :\n  has_limits_of_shape J D :=\n{ has_limit := \u03bb 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 \u2964 C) [has_limits C] [reflective R] : has_limits D :=\n{ has_limits_of_shape := \u03bb J \ud835\udca5\u2081, 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 \u2964 C)\n  [reflective R] [has_colimits_of_shape J C] : has_colimits_of_shape J D :=\n{ has_colimit := \u03bb F,\nbegin\n  let c := (left_adjoint R).map_cocone (colimit.cocone (F \u22d9 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 \u27e8_, (is_colimit.precompose_inv_equiv _ _).symm t\u27e9,\n  apply (iso_whisker_left F (as_iso (adjunction.of_right_adjoint R).counit) : _) \u226a\u226b F.right_unitor,\nend }\n\n/-- If `C` has colimits then any reflective subcategory has colimits. -/\nlemma has_colimits_of_reflective (R : D \u2964 C) [reflective R] [has_colimits C] :\n  has_colimits D :=\n{ has_colimits_of_shape := \u03bb J \ud835\udca5, 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 \u2964 C) [reflective R] [has_terminal C] :\n  preserves_limits_of_shape (discrete pempty) (left_adjoint R) :=\n{ preserves_limit := \u03bb 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 _ \u226a\u226b as_iso ((adjunction.of_right_adjoint R).counit.app (\u22a4_ 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 {\u03b1 : Type u_1} [preorder \u03b1] (f : \u2115 \u2192 \u03b1) {m : \u2115}\n    (h : \u2200 (n : \u2115), n \u2265 m \u2192 f (Nat.succ n) \u2264 f n) {l : \u2115} (k : \u2115) (H : k \u2265 m) : k \u2264 l \u2192 f l \u2264 f k :=\n  sorry\n\ntheorem is_cau_of_decreasing_bounded {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1]\n    (f : \u2115 \u2192 \u03b1) {a : \u03b1} {m : \u2115} (ham : \u2200 (n : \u2115), n \u2265 m \u2192 abs (f n) \u2264 a)\n    (hnm : \u2200 (n : \u2115), n \u2265 m \u2192 f (Nat.succ n) \u2264 f n) : is_cau_seq abs f :=\n  sorry\n\ntheorem is_cau_of_mono_bounded {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] (f : \u2115 \u2192 \u03b1)\n    {a : \u03b1} {m : \u2115} (ham : \u2200 (n : \u2115), n \u2265 m \u2192 abs (f n) \u2264 a)\n    (hnm : \u2200 (n : \u2115), n \u2265 m \u2192 f n \u2264 f (Nat.succ n)) : is_cau_seq abs f :=\n  sorry\n\ntheorem is_cau_series_of_abv_le_cau {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1]\n    {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {f : \u2115 \u2192 \u03b2} {g : \u2115 \u2192 \u03b1} (n : \u2115) :\n    (\u2200 (m : \u2115), n \u2264 m \u2192 abv (f m) \u2264 g m) \u2192\n        (is_cau_seq abs fun (n : \u2115) => finset.sum (finset.range n) fun (i : \u2115) => g i) \u2192\n          is_cau_seq abv fun (n : \u2115) => finset.sum (finset.range n) fun (i : \u2115) => f i :=\n  sorry\n\ntheorem is_cau_series_of_abv_cau {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1]\n    {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {f : \u2115 \u2192 \u03b2} :\n    (is_cau_seq abs fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => abv (f n)) \u2192\n        is_cau_seq abv fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => f n :=\n  is_cau_series_of_abv_le_cau 0 fun (n : \u2115) (h : 0 \u2264 n) => le_refl (abv (f n))\n\ntheorem is_cau_geo_series {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] {\u03b2 : Type u_2}\n    [field \u03b2] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] (x : \u03b2) (hx1 : abv x < 1) :\n    is_cau_seq abv fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => x ^ m :=\n  sorry\n\ntheorem is_cau_geo_series_const {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] (a : \u03b1)\n    {x : \u03b1} (hx1 : abs x < 1) :\n    is_cau_seq abs fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => a * x ^ n :=\n  sorry\n\ntheorem series_ratio_test {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1]\n    [archimedean \u03b1] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {f : \u2115 \u2192 \u03b2} (n : \u2115) (r : \u03b1) (hr0 : 0 \u2264 r)\n    (hr1 : r < 1) (h : \u2200 (m : \u2115), n \u2264 m \u2192 abv (f (Nat.succ m)) \u2264 r * abv (f m)) :\n    is_cau_seq abv fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => f n :=\n  sorry\n\ntheorem sum_range_diag_flip {\u03b1 : Type u_1} [add_comm_monoid \u03b1] (n : \u2115) (f : \u2115 \u2192 \u2115 \u2192 \u03b1) :\n    (finset.sum (finset.range n)\n          fun (m : \u2115) => finset.sum (finset.range (m + 1)) fun (k : \u2115) => f k (m - k)) =\n        finset.sum (finset.range n)\n          fun (m : \u2115) => finset.sum (finset.range (n - m)) fun (k : \u2115) => f m k :=\n  sorry\n\ntheorem sum_range_sub_sum_range {\u03b1 : Type u_1} [add_comm_group \u03b1] {f : \u2115 \u2192 \u03b1} {n : \u2115} {m : \u2115}\n    (hnm : n \u2264 m) :\n    ((finset.sum (finset.range m) fun (k : \u2115) => f k) -\n          finset.sum (finset.range n) fun (k : \u2115) => f k) =\n        finset.sum (finset.filter (fun (k : \u2115) => n \u2264 k) (finset.range m)) fun (k : \u2115) => f k :=\n  sorry\n\ntheorem abv_sum_le_sum_abv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1]\n    {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {\u03b3 : Type u_3} (f : \u03b3 \u2192 \u03b2) (s : finset \u03b3) :\n    abv (finset.sum s fun (k : \u03b3) => f k) \u2264 finset.sum s fun (k : \u03b3) => abv (f k) :=\n  sorry\n\ntheorem cauchy_product {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1] {abv : \u03b2 \u2192 \u03b1}\n    [is_absolute_value abv] {a : \u2115 \u2192 \u03b2} {b : \u2115 \u2192 \u03b2}\n    (ha : is_cau_seq abs fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => abv (a n))\n    (hb : is_cau_seq abv fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => b n) (\u03b5 : \u03b1)\n    (\u03b50 : 0 < \u03b5) :\n    \u2203 (i : \u2115),\n        \u2200 (j : \u2115),\n          j \u2265 i \u2192\n            abv\n                (((finset.sum (finset.range j) fun (k : \u2115) => a k) *\n                    finset.sum (finset.range j) fun (n : \u2115) => b n) -\n                  finset.sum (finset.range j)\n                    fun (n : \u2115) =>\n                      finset.sum (finset.range (n + 1)) fun (m : \u2115) => a m * b (n - m)) <\n              \u03b5 :=\n  sorry\n\nnamespace complex\n\n\ntheorem is_cau_abs_exp (z : \u2102) :\n    is_cau_seq abs\n        fun (n : \u2115) =>\n          finset.sum (finset.range n) fun (m : \u2115) => abs (z ^ m / \u2191(nat.factorial m)) :=\n  sorry\n\ntheorem is_cau_exp (z : \u2102) :\n    is_cau_seq abs\n        fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => z ^ m / \u2191(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 : \u2102) : cau_seq \u2102 abs :=\n  { val := fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => z ^ m / \u2191(nat.factorial m),\n    property := is_cau_exp z }\n\n/-- The complex exponential function, defined via its Taylor series -/\ndef exp (z : \u2102) : \u2102 := cau_seq.lim (exp' z)\n\n/-- The complex sine function, defined via `exp` -/\ndef sin (z : \u2102) : \u2102 := (exp (-z * I) - exp (z * I)) * I / bit0 1\n\n/-- The complex cosine function, defined via `exp` -/\ndef cos (z : \u2102) : \u2102 := (exp (z * I) + exp (-z * I)) / bit0 1\n\n/-- The complex tangent function, defined as `sin z / cos z` -/\ndef tan (z : \u2102) : \u2102 := sin z / cos z\n\n/-- The complex hyperbolic sine function, defined via `exp` -/\ndef sinh (z : \u2102) : \u2102 := (exp z - exp (-z)) / bit0 1\n\n/-- The complex hyperbolic cosine function, defined via `exp` -/\ndef cosh (z : \u2102) : \u2102 := (exp z + exp (-z)) / bit0 1\n\n/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/\ndef tanh (z : \u2102) : \u2102 := 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 : \u211d) : \u211d := complex.re (complex.exp \u2191x)\n\n/-- The real sine function, defined as the real part of the complex sine -/\ndef sin (x : \u211d) : \u211d := complex.re (complex.sin \u2191x)\n\n/-- The real cosine function, defined as the real part of the complex cosine -/\ndef cos (x : \u211d) : \u211d := complex.re (complex.cos \u2191x)\n\n/-- The real tangent function, defined as the real part of the complex tangent -/\ndef tan (x : \u211d) : \u211d := complex.re (complex.tan \u2191x)\n\n/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/\ndef sinh (x : \u211d) : \u211d := complex.re (complex.sinh \u2191x)\n\n/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/\ndef cosh (x : \u211d) : \u211d := complex.re (complex.cosh \u2191x)\n\n/-- The real hypebolic tangent function, defined as the real part of\nthe complex hyperbolic tangent -/\ndef tanh (x : \u211d) : \u211d := complex.re (complex.tanh \u2191x)\n\nend real\n\n\nnamespace complex\n\n\n@[simp] theorem exp_zero : exp 0 = 1 := sorry\n\ntheorem exp_add (x : \u2102) (y : \u2102) : exp (x + y) = exp x * exp y := sorry\n\ntheorem exp_list_sum (l : List \u2102) : 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 \u2102) :\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 {\u03b1 : Type u_1} (s : finset \u03b1) (f : \u03b1 \u2192 \u2102) :\n    exp (finset.sum s fun (x : \u03b1) => f x) = finset.prod s fun (x : \u03b1) => exp (f x) :=\n  monoid_hom.map_prod (monoid_hom.mk exp exp_zero exp_add) f s\n\ntheorem exp_nat_mul (x : \u2102) (n : \u2115) : exp (\u2191n * x) = exp x ^ n := sorry\n\ntheorem exp_ne_zero (x : \u2102) : exp x \u2260 0 := sorry\n\ntheorem exp_neg (x : \u2102) : exp (-x) = (exp x\u207b\u00b9) := sorry\n\ntheorem exp_sub (x : \u2102) (y : \u2102) : exp (x - y) = exp x / exp y := sorry\n\n@[simp] theorem exp_conj (x : \u2102) : exp (coe_fn conj x) = coe_fn conj (exp x) := sorry\n\n@[simp] theorem of_real_exp_of_real_re (x : \u211d) : \u2191(re (exp \u2191x)) = exp \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (exp \u2191x) = exp \u2191x)) (Eq.symm (exp_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (exp (coe_fn conj \u2191x) = exp \u2191x)) (conj_of_real x)))\n        (Eq.refl (exp \u2191x))))\n\n@[simp] theorem of_real_exp (x : \u211d) : \u2191(real.exp x) = exp \u2191x := of_real_exp_of_real_re x\n\n@[simp] theorem exp_of_real_im (x : \u211d) : im (exp \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (exp \u2191x) = 0)) (Eq.symm (of_real_exp_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (exp \u2191x)) = 0)) (of_real_im (re (exp \u2191x)))))\n      (Eq.refl 0))\n\ntheorem exp_of_real_re (x : \u211d) : re (exp \u2191x) = real.exp x := rfl\n\ntheorem two_sinh (x : \u2102) : bit0 1 * sinh x = exp x - exp (-x) :=\n  mul_div_cancel' (exp x - exp (-x)) two_ne_zero'\n\ntheorem two_cosh (x : \u2102) : 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 : \u2102) : sinh (-x) = -sinh x := sorry\n\ntheorem sinh_add (x : \u2102) (y : \u2102) : 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 : \u2102) : cosh (-x) = cosh x := sorry\n\ntheorem cosh_add (x : \u2102) (y : \u2102) : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := sorry\n\ntheorem sinh_sub (x : \u2102) (y : \u2102) : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := sorry\n\ntheorem cosh_sub (x : \u2102) (y : \u2102) : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := sorry\n\ntheorem sinh_conj (x : \u2102) : sinh (coe_fn conj x) = coe_fn conj (sinh x) := sorry\n\n@[simp] theorem of_real_sinh_of_real_re (x : \u211d) : \u2191(re (sinh \u2191x)) = sinh \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (sinh \u2191x) = sinh \u2191x)) (Eq.symm (sinh_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (sinh (coe_fn conj \u2191x) = sinh \u2191x)) (conj_of_real x)))\n        (Eq.refl (sinh \u2191x))))\n\n@[simp] theorem of_real_sinh (x : \u211d) : \u2191(real.sinh x) = sinh \u2191x := of_real_sinh_of_real_re x\n\n@[simp] theorem sinh_of_real_im (x : \u211d) : im (sinh \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (sinh \u2191x) = 0)) (Eq.symm (of_real_sinh_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (sinh \u2191x)) = 0)) (of_real_im (re (sinh \u2191x)))))\n      (Eq.refl 0))\n\ntheorem sinh_of_real_re (x : \u211d) : re (sinh \u2191x) = real.sinh x := rfl\n\ntheorem cosh_conj (x : \u2102) : cosh (coe_fn conj x) = coe_fn conj (cosh x) := sorry\n\n@[simp] theorem of_real_cosh_of_real_re (x : \u211d) : \u2191(re (cosh \u2191x)) = cosh \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (cosh \u2191x) = cosh \u2191x)) (Eq.symm (cosh_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (cosh (coe_fn conj \u2191x) = cosh \u2191x)) (conj_of_real x)))\n        (Eq.refl (cosh \u2191x))))\n\n@[simp] theorem of_real_cosh (x : \u211d) : \u2191(real.cosh x) = cosh \u2191x := of_real_cosh_of_real_re x\n\n@[simp] theorem cosh_of_real_im (x : \u211d) : im (cosh \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (cosh \u2191x) = 0)) (Eq.symm (of_real_cosh_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (cosh \u2191x)) = 0)) (of_real_im (re (cosh \u2191x)))))\n      (Eq.refl 0))\n\ntheorem cosh_of_real_re (x : \u211d) : re (cosh \u2191x) = real.cosh x := rfl\n\ntheorem tanh_eq_sinh_div_cosh (x : \u2102) : tanh x = sinh x / cosh x := rfl\n\n@[simp] theorem tanh_zero : tanh 0 = 0 := sorry\n\n@[simp] theorem tanh_neg (x : \u2102) : 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 Scratch.ExprAppl\nimport Lean.Meta\nopen Lean\nopen Meta\nopen Lean.Elab.Tactic\n\nsyntax (name:= introsFind) \"introsFind\" (term)? : tactic\n@[tactic introsFind] def introsfindImpl : Tactic :=\n  fun stx  =>\n  match stx with\n  | `(tactic|introsFind) => \n    withMainContext do\n      let mvar \u2190 getMainGoal\n      let \u27e8intVars, codmvar\u27e9 \u2190 Meta.intros mvar\n      withMVarContext codmvar do\n        let expVars := intVars.toList.map (fun x => mkFVar x)\n        let target \u2190  getMVarType codmvar\n        let oneStep \u2190 applyPairsMeta expVars \n        let found \u2190 typInList? target oneStep\n        match found with\n        | some x => \n          do\n            assignExprMVar codmvar x\n            replaceMainGoal []\n            return ()\n        | none => \n          throwTacticEx `findInSeq mvar m!\"did not find {target} in sequence\"\n          return ()\n  | `(tactic|introsFind $t) => \n    withMainContext do\n      let n : Nat <- t.isNatLit?.getD 0\n      let mvar \u2190 getMainGoal\n      let \u27e8intVars, codmvar\u27e9 \u2190 Meta.intros mvar\n      withMVarContext codmvar do\n        let expVars := intVars.toList.map (fun x => mkFVar x)\n        let target \u2190  getMVarType codmvar\n        let oneStep \u2190 iterApplyPairsMeta n expVars \n        let found \u2190 typInList? target oneStep\n        match found with\n        | some x => \n          do\n            assignExprMVar codmvar x\n            replaceMainGoal []\n            return ()\n        | none => \n          throwTacticEx `findInSeq mvar m!\"did not find {target} in sequence\"\n          return ()\n  | _ => Elab.throwIllFormedSyntax\n\n\ndef mmodusPonens {\u03b1 \u03b2 : Type} : \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2 := by\n      introsFind\n\ndef mmodus_ponens (\u03b1 \u03b2 : Prop) : \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2 := by\n      introsFind\n\n#print mmodusPonens\n#print mmodus_ponens\n\ndef constantFunc (\u03b1 \u03b2 : Type)  : \u03b1 \u2192 \u03b2 \u2192 \u03b1  := by\n      introsFind\n\ndef constant_implica (\u03b1 \u03b2 : Prop)  : \u03b1 \u2192 \u03b2 \u2192 \u03b1 := by\n      introsFind\n\ndef reflImpll (\u03b1 : Prop) : \u03b1 \u2192 \u03b1  := by\n      introsFind\n\ndef autoIdd (\u03b1 : Type) : \u03b1 \u2192 \u03b1 := by\n      introsFind \n\n#print autoIdd\n\ntheorem doublleMP{\u03b1 \u03b2 \u03b3 : Prop} : \u03b1 \u2192 (\u03b1 \u2192 \u03b2) \u2192  (\u03b2 \u2192  \u03b3) \u2192 \u03b3  := by\n      introsFind 2\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/IntrosFind.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.04336580015480671, "lm_q1q2_score": 0.017664338822769746}}
{"text": "/-\nCopyright (c) 2020 Johan Commelin. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johan Commelin\n-/\nimport tactic.interactive\n\n/-!\n# `dec_trivial` tactic\n\nThe `dec_trivial` tactic tries to use decidability to prove a goal.\nIt is basically a glorified wrapper around `exact dec_trivial`.\n\nThere is an extra option to make it a little bit smarter:\n`dec_trivial!` will revert all hypotheses on which the target depends,\nbefore it tries `exact dec_trivial`.\n-/\nopen tactic.interactive\n\nsetup_tactic_parser\n\n/-- `dec_trivial` tries to use decidability to prove a goal\n(i.e., using `exact dec_trivial`).\nThe variant `dec_trivial!` will revert all hypotheses on which the target depends,\nbefore it tries `exact dec_trivial`.\n\nExample:\n```lean\nexample (n : \u2115) (h : n < 2) : n = 0 \u2228 n = 1 :=\nby dec_trivial!\n```\n-/\nmeta def tactic.interactive.dec_trivial (revert_deps : parse (tk \"!\")?) : tactic unit :=\nif revert_deps.is_some\nthen revert_target_deps; tactic.exact_dec_trivial\nelse tactic.exact_dec_trivial\n\nadd_tactic_doc\n{ name       := \"dec_trivial\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.dec_trivial],\n  tags       := [\"basic\", \"finishing\"] }\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/dec_trivial.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.18242551936144574, "lm_q2_score": 0.09670579915364932, "lm_q1q2_score": 0.017641605635868137}}
{"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-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.simp_tactic\nimport Mathlib.Lean3Lib.init.meta.interactive\nimport Mathlib.Lean3Lib.init.meta.congr_lemma\nimport Mathlib.Lean3Lib.init.meta.match_tactic\n\nnamespace Mathlib\n\n/-- `conv \u03b1` 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-/\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/converter/conv_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3345894279828469, "lm_q2_score": 0.05261895390483316, "lm_q1q2_score": 0.017605745688073916}}
{"text": "theorem very_easy : true :=\nbegin\n  sorry\nend\n", "meta": {"author": "ImperialCollegeLondon", "repo": "xena-UROP-2018", "sha": "b111fb87f343cf79eca3b886f99ee15c1dd9884b", "save_path": "github-repos/lean/ImperialCollegeLondon-xena-UROP-2018", "path": "github-repos/lean/ImperialCollegeLondon-xena-UROP-2018/xena-UROP-2018-b111fb87f343cf79eca3b886f99ee15c1dd9884b/src/M1F/problem_bank/PB0006/Q0006.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22541661583507674, "lm_q2_score": 0.07807816353602866, "lm_q1q2_score": 0.017600115394909268}}
{"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 \u2964 Profinite.{u}) (C : cone F)\n\nlemma image_eq (hC : is_limit C) (i : J) :\n  set.range (C.\u03c0.app i) = \u22c2 (j : J) (h : j \u2264 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 \u2190 C.w (hom_of_le hj),\n    apply set.range_comp_subset_range },\n  { rintro x hx,\n    have cond : \u2200 (j : J) (hj : j \u2264 i), \u2203 y : F.obj j, (F.map (hom_of_le hj)) y = x,\n    { intros j hj,\n      exact hx _ \u27e8j,rfl\u27e9 _ \u27e8hj, rfl\u27e9 },\n    let Js := \u03a3' (a b : J), a \u2264 b,\n    let P := \u03a0 (j : J), F.obj j,\n    let Us : Js \u2192 set P := \u03bb e, { p | F.map (hom_of_le e.2.2) (p (e.1)) = p (e.2.1) \u2227 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 \u27e8z,hz\u27e9,\n      let IC : (limit_cone F) \u2245 C := (limit_cone_is_limit F).unique_up_to_iso hC,\n      let ICX : (limit_cone F).X \u2245 C.X := (cones.forget _).map_iso IC,\n      let z : (limit_cone F).X := \u27e8z,_\u27e9,\n      swap,\n      { intros a b h,\n        convert (hz.2 _ \u27e8\u27e8a, b, le_of_hom h\u27e9, rfl\u27e9).1 },\n      use ICX.hom z,\n      change (hC.lift _ \u226b _) _ = _,\n      rw hC.fac,\n      exact (hz.2 _ \u27e8\u27e8i,i,le_refl _\u27e9,rfl\u27e9).2 },\n    { intros i,\n      refine is_closed.inter (is_closed_eq _ _) (is_closed_eq _ _);\n      continuity },\n    { have : \u2200 e : J, nonempty (F.obj e),\n      { intros e,\n        rcases cond (e \u2293 i) inf_le_right with \u27e8y,rfl\u27e9,\n        use F.map (hom_of_le inf_le_left) y },\n      haveI : \u2200 j : J, inhabited (F.obj j) :=\n        by {intros j, refine \u27e8nonempty.some (this j)\u27e9},\n      intros G,\n      let GG := G.image (\u03bb e : Js, e.1),\n      haveI : inhabited J := \u27e8i\u27e9,\n      have := exists_le_finset (insert i GG),\n      obtain \u27e8j0,hj0\u27e9 := this,\n      obtain \u27e8x0,rfl\u27e9 := cond j0 (hj0 _ (finset.mem_insert_self _ _)),\n      let z : P := \u03bb e, if h : j0 \u2264 e then F.map (hom_of_le h) x0 else default,\n      use z,\n      refine \u27e8trivial, _\u27e9,\n      rintros S \u27e8e,rfl\u27e9,\n      rintro T \u27e8k,rfl\u27e9,\n      dsimp [z],\n      refine \u27e8_, by erw dif_pos\u27e9,\n      have : j0 \u2264 e.fst,\n      { apply hj0,\n        apply finset.mem_insert_of_mem,\n        rw finset.mem_image,\n        refine \u27e8e,k,rfl\u27e9 },\n      erw [dif_pos this, dif_pos (le_trans this e.2.2)],\n      change (F.map _ \u226b F.map _) _ = _,\n      rw \u2190 F.map_comp,\n      refl } }\nend\n\nset_option pp.proofs true\n\nlemma image_stabilizes [inhabited J] [\u2200 i, fintype (F.obj i)]\n  (i : J) : \u2203 (j : J) (hj : j \u2264 i), \u2200 (k : J) (hk : k \u2264 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    (\u03bb 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) \u226b (hom_of_le hb) := rfl,\n    rw [this, F.map_comp, Profinite.coe_comp],\n    apply set.range_comp_subset_range },\n  obtain \u27e8j0,hj0,hh\u27e9 := 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] [\u2200 i, fintype (F.obj i)]\n  (hC : is_limit C) (i : J) : \u2203 (j : J) (hj : j \u2264 i),\n  set.range (C.\u03c0.app i) = set.range (F.map $ hom_of_le $ hj) :=\nbegin\n  have := Inter_eq i (\u03bb 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 \u226b hom_of_le hb, refl,\n    rw [this, F.map_comp, Profinite.coe_comp],\n    apply set.range_comp_subset_range },\n  obtain \u27e8j0,hj0,hh\u27e9 := this,\n  dsimp at hh,\n  use j0, use hj0,\n  rw [image_eq _ _ hC, \u2190 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 \u00b7 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 \u2192 A \u2192 option A)\n(linkorder : A \u2192 A \u2192 Prop)\n(linkorder_refl : \u2200 x, linkorder x x)\n(linkorder_trans : \u2200 {x y z}, linkorder x y \u2192 linkorder y z \u2192 linkorder x z)\n(link_linkorder : \u2200 {x y z}, link x y = some z \u2192 linkorder x z \u2227 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 \u2192 Type\n| extern : init_class []\n| common (sz) : init_class [init_data.space sz]\n| definitive (il) : init_class il\n\ndef classify_init : \u03a0 (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 \u2192 list init_data \u2192 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 \u2260 list.nil \u2192 init_data.list_size il = sz \u2192\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 \u2227\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 \u2192 globvar V \u2192 Prop\n| intro {info1 info2 i1 i2} {ro vo} :\n    linkorder info1 info2 \u2192\n    linkorder i1 i2 \u2192\n    linkorder_vardef \u27e8info1, i1, ro, vo\u27e9 \u27e8info2, i2, ro, vo\u27e9\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 \u2192 globdef F V \u2192 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 \u2192 globdef F V \u2192 Prop\n| linkorder_def_fun (fd1 fd2) :\n    linkorder fd1 fd2 \u2192\n    linkorder_def (Gfun fd1) (Gfun fd2)\n| linkorder_def_var (v1 v2) :\n    linkorder v1 v2 \u2192\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 \u2208 p1.public) && (x \u2208 p2.public) && (link gd1 gd2).is_some\nend\n\ndef link_prog_merge : option (globdef F V) \u2192 option (globdef F V) \u2192 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 \u2227 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   \u2227 (\u2200 (id : ident) gd1 gd2,\n         (dm1^!id) = some gd1 \u2192 (dm2^!id) = some gd2 \u2192\n         id \u2208 p1.public \u2227 id \u2208 p2.public \u2227 \u2203 gd, link gd1 gd2 = some gd)\n  \u2227 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 : \u2200 (id : ident) gd1 gd2,\n       (dm1^!id) = some gd1 \u2192 (dm2^!id) = some gd2 \u2192\n       id \u2208 p1.public \u2227 id \u2208 p2.public \u2227 (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 \u27e8PTree.elements m, pub, mn\u27e9 ^! x) = (m^!x) := sorry'\nend\n\ninstance linker_prog : linker (program F V) :=\n{ link := link_prog,\n  linkorder := \u03bbp1 p2, p1.main = p2.main\n  \u2227 p1.public \u2286 p2.public\n  \u2227 \u2200 (id : ident) gd1, (prog_defmap p1^!id) = some gd1 \u2192\n     \u2203 gd2, (prog_defmap p2^!id) = some gd2 \u2227\n       linkorder gd1 gd2 \u2227 (id \u2209 p2.public \u2192 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 \u2192\n  (prog_defmap p1^!id) = some gd1 \u2192\n  \u2203 gd2, (prog_defmap p2^!id) = some gd2 \u2227 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 \u2192 F1 \u2192 F2 \u2192 Prop\nparameter match_varinfo : V1 \u2192 V2 \u2192 Prop\n\ninductive match_globvar : globvar V1 \u2192 globvar V2 \u2192 Prop\n| mk (i1 i2 init ro vo) :\n  match_varinfo i1 i2 \u2192\n  match_globvar \u27e8i1, init, ro, vo\u27e9 \u27e8i2, init, ro, vo\u27e9\n\nvariable [linker C]\n\ninductive match_globdef (ctx : C) : globdef F1 V1 \u2192 globdef F2 V2 \u2192 Prop\n| func (ctx' f1 f2) :\n  linkorder ctx' ctx \u2192\n  match_fundef ctx' f1 f2 \u2192\n  match_globdef (Gfun f1) (Gfun f2)\n| var {v1 v2} :\n  match_globvar v1 v2 \u2192\n  match_globdef (Gvar v1) (Gvar v2).\n\ndef match_ident_globdef (ctx : C) : ident \u00d7 globdef F1 V1 \u2192 ident \u00d7 globdef F2 V2 \u2192 Prop\n| (i1, g1) (i2, g2) := i1 = i2 \u2227 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\u2227 p2.main = p1.main\n\u2227 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 \u2192 F1 \u2192 F2 \u2192 Prop)\n  (match_varinfo : V1 \u2192 V2 \u2192 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 \u2192 F1 \u2192 F2 \u2192 Prop}\n  {match_varinfo : V1 \u2192 V2 \u2192 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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl, 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 : (\u03a0 x, \u03b2 x) \u2192 \u03b2 x`. -/\ndef eval {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (x : \u03b1) (f : (x : \u03b1) \u2192 \u03b2 x) : \u03b2 x := f x\n\n@[simp] theorem eval_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (x : \u03b1) (f : (x : \u03b1) \u2192 \u03b2 x) :\n    eval x f = f x :=\n  rfl\n\ntheorem comp_apply {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b2 \u2192 \u03c6) (g : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n    comp f g a = f (g a) :=\n  rfl\n\ntheorem const_def {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {y : \u03b2} : (fun (x : \u03b1) => y) = const \u03b1 y := rfl\n\n@[simp] theorem const_apply {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {y : \u03b2} {x : \u03b1} : const \u03b1 y x = y := rfl\n\n@[simp] theorem const_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {c : \u03b3} :\n    const \u03b2 c \u2218 f = const \u03b1 c :=\n  rfl\n\n@[simp] theorem comp_const {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b2 \u2192 \u03b3} {b : \u03b2} :\n    f \u2218 const \u03b1 b = const \u03b1 (f b) :=\n  rfl\n\ntheorem id_def {\u03b1 : Sort u_1} : id = fun (x : \u03b1) => x := rfl\n\ntheorem hfunext {\u03b1 : Sort u} {\u03b1' : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {\u03b2' : \u03b1' \u2192 Sort v} {f : (a : \u03b1) \u2192 \u03b2 a}\n    {f' : (a : \u03b1') \u2192 \u03b2' a} (h\u03b1 : \u03b1 = \u03b1') (h : \u2200 (a : \u03b1) (a' : \u03b1'), a == a' \u2192 f a == f' a') :\n    f == f' :=\n  sorry\n\ntheorem funext_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {f\u2081 : (x : \u03b1) \u2192 \u03b2 x} {f\u2082 : (x : \u03b1) \u2192 \u03b2 x} :\n    f\u2081 = f\u2082 \u2194 \u2200 (a : \u03b1), f\u2081 a = f\u2082 a :=\n  { mp := fun (h : f\u2081 = f\u2082) (a : \u03b1) => h \u25b8 rfl, mpr := funext }\n\n@[simp] theorem injective.eq_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) {a : \u03b1}\n    {b : \u03b1} : f a = f b \u2194 a = b :=\n  { mp := I, mpr := congr_arg f }\n\ntheorem injective.eq_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) {a : \u03b1}\n    {b : \u03b1} {c : \u03b2} (h : f b = c) : f a = c \u2194 a = b :=\n  h \u25b8 injective.eq_iff I\n\ntheorem injective.ne {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : injective f) {a\u2081 : \u03b1}\n    {a\u2082 : \u03b1} : a\u2081 \u2260 a\u2082 \u2192 f a\u2081 \u2260 f a\u2082 :=\n  mt fun (h : f a\u2081 = f a\u2082) => hf h\n\ntheorem injective.ne_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : injective f) {x : \u03b1}\n    {y : \u03b1} : f x \u2260 f y \u2194 x \u2260 y :=\n  { mp := mt (congr_arg f), mpr := injective.ne hf }\n\ntheorem injective.ne_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : injective f) {x : \u03b1}\n    {y : \u03b1} {z : \u03b2} (h : f y = z) : f x \u2260 z \u2194 x \u2260 y :=\n  h \u25b8 injective.ne_iff hf\n\n/-- If the co-domain `\u03b2` of an injective function `f : \u03b1 \u2192 \u03b2` has decidable equality, then\nthe domain `\u03b1` also has decidable equality. -/\ndef injective.decidable_eq {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} [DecidableEq \u03b2]\n    (I : injective f) : DecidableEq \u03b1 :=\n  fun (a b : \u03b1) => decidable_of_iff (f a = f b) (injective.eq_iff I)\n\ntheorem injective.of_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b3 \u2192 \u03b1}\n    (I : injective (f \u2218 g)) : injective g :=\n  fun (x y : \u03b3) (h : g x = g y) => I ((fun (this : f (g x) = f (g y)) => this) (congr_arg f h))\n\ntheorem surjective.of_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b3 \u2192 \u03b1}\n    (S : surjective (f \u2218 g)) : surjective f :=\n  sorry\n\nprotected instance decidable_eq_pfun (p : Prop) [Decidable p] (\u03b1 : p \u2192 Type u_1)\n    [(hp : p) \u2192 DecidableEq (\u03b1 hp)] : DecidableEq ((hp : p) \u2192 \u03b1 hp) :=\n  sorry\n\ntheorem surjective.forall {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f)\n    {p : \u03b2 \u2192 Prop} : (\u2200 (y : \u03b2), p y) \u2194 \u2200 (x : \u03b1), p (f x) :=\n  sorry\n\ntheorem surjective.forall\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f)\n    {p : \u03b2 \u2192 \u03b2 \u2192 Prop} : (\u2200 (y\u2081 y\u2082 : \u03b2), p y\u2081 y\u2082) \u2194 \u2200 (x\u2081 x\u2082 : \u03b1), p (f x\u2081) (f x\u2082) :=\n  iff.trans (surjective.forall hf) (forall_congr fun (x : \u03b1) => surjective.forall hf)\n\ntheorem surjective.forall\u2083 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f)\n    {p : \u03b2 \u2192 \u03b2 \u2192 \u03b2 \u2192 Prop} :\n    (\u2200 (y\u2081 y\u2082 y\u2083 : \u03b2), p y\u2081 y\u2082 y\u2083) \u2194 \u2200 (x\u2081 x\u2082 x\u2083 : \u03b1), p (f x\u2081) (f x\u2082) (f x\u2083) :=\n  iff.trans (surjective.forall hf) (forall_congr fun (x : \u03b1) => surjective.forall\u2082 hf)\n\ntheorem surjective.exists {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f)\n    {p : \u03b2 \u2192 Prop} : (\u2203 (y : \u03b2), p y) \u2194 \u2203 (x : \u03b1), p (f x) :=\n  sorry\n\ntheorem surjective.exists\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f)\n    {p : \u03b2 \u2192 \u03b2 \u2192 Prop} :\n    (\u2203 (y\u2081 : \u03b2), \u2203 (y\u2082 : \u03b2), p y\u2081 y\u2082) \u2194 \u2203 (x\u2081 : \u03b1), \u2203 (x\u2082 : \u03b1), p (f x\u2081) (f x\u2082) :=\n  iff.trans (surjective.exists hf) (exists_congr fun (x : \u03b1) => surjective.exists hf)\n\ntheorem surjective.exists\u2083 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f)\n    {p : \u03b2 \u2192 \u03b2 \u2192 \u03b2 \u2192 Prop} :\n    (\u2203 (y\u2081 : \u03b2), \u2203 (y\u2082 : \u03b2), \u2203 (y\u2083 : \u03b2), p y\u2081 y\u2082 y\u2083) \u2194\n        \u2203 (x\u2081 : \u03b1), \u2203 (x\u2082 : \u03b1), \u2203 (x\u2083 : \u03b1), p (f x\u2081) (f x\u2082) (f x\u2083) :=\n  iff.trans (surjective.exists hf) (exists_congr fun (x : \u03b1) => surjective.exists\u2082 hf)\n\n/-- Cantor's diagonal argument implies that there are no surjective functions from `\u03b1`\nto `set \u03b1`. -/\ntheorem cantor_surjective {\u03b1 : Type u_1} (f : \u03b1 \u2192 set \u03b1) : \u00acsurjective f := sorry\n\n/-- Cantor's diagonal argument implies that there are no injective functions from `set \u03b1` to `\u03b1`. -/\ntheorem cantor_injective {\u03b1 : Type u_1} (f : set \u03b1 \u2192 \u03b1) : \u00acinjective 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 {\u03b1 : Type u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 Option \u03b1) :=\n  \u2200 (x : \u03b1) (y : \u03b2), g y = some x \u2194 f x = y\n\ntheorem is_partial_inv_left {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 Option \u03b1}\n    (H : is_partial_inv f g) (x : \u03b1) : g (f x) = some x :=\n  iff.mpr (H x (f x)) rfl\n\ntheorem injective_of_partial_inv {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 Option \u03b1}\n    (H : is_partial_inv f g) : injective f :=\n  fun (a b : \u03b1) (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 {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 Option \u03b1}\n    (H : is_partial_inv f g) (x : \u03b2) (y : \u03b2) (b : \u03b1) (h\u2081 : b \u2208 g x) (h\u2082 : b \u2208 g y) : x = y :=\n  Eq.trans (Eq.symm (iff.mp (H b x) h\u2081)) (iff.mp (H b y) h\u2082)\n\ntheorem left_inverse.comp_eq_id {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    (h : left_inverse f g) : f \u2218 g = id :=\n  funext h\n\ntheorem left_inverse_iff_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} :\n    left_inverse f g \u2194 f \u2218 g = id :=\n  { mp := left_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem right_inverse.comp_eq_id {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    (h : right_inverse f g) : g \u2218 f = id :=\n  funext h\n\ntheorem right_inverse_iff_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} :\n    right_inverse f g \u2194 g \u2218 f = id :=\n  { mp := right_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem left_inverse.comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    {h : \u03b2 \u2192 \u03b3} {i : \u03b3 \u2192 \u03b2} (hf : left_inverse f g) (hh : left_inverse h i) :\n    left_inverse (h \u2218 f) (g \u2218 i) :=\n  sorry\n\ntheorem right_inverse.comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    {h : \u03b2 \u2192 \u03b3} {i : \u03b3 \u2192 \u03b2} (hf : right_inverse f g) (hh : right_inverse h i) :\n    right_inverse (h \u2218 f) (g \u2218 i) :=\n  left_inverse.comp hh hf\n\ntheorem left_inverse.right_inverse {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    (h : left_inverse g f) : right_inverse f g :=\n  h\n\ntheorem right_inverse.left_inverse {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    (h : right_inverse g f) : left_inverse f g :=\n  h\n\ntheorem left_inverse.surjective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    (h : left_inverse f g) : surjective f :=\n  right_inverse.surjective (left_inverse.right_inverse h)\n\ntheorem right_inverse.injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1}\n    (h : right_inverse f g) : injective f :=\n  left_inverse.injective (right_inverse.left_inverse h)\n\ntheorem left_inverse.eq_right_inverse {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g\u2081 : \u03b2 \u2192 \u03b1}\n    {g\u2082 : \u03b2 \u2192 \u03b1} (h\u2081 : left_inverse g\u2081 f) (h\u2082 : right_inverse g\u2082 f) : g\u2081 = g\u2082 :=\n  sorry\n\n/-- We can use choice to construct explicitly a partial inverse for\n  a given injective function `f`. -/\ndef partial_inv {\u03b1 : Type u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (b : \u03b2) : Option \u03b1 :=\n  dite (\u2203 (a : \u03b1), f a = b) (fun (h : \u2203 (a : \u03b1), f a = b) => some (classical.some h))\n    fun (h : \u00ac\u2203 (a : \u03b1), f a = b) => none\n\ntheorem partial_inv_of_injective {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) :\n    is_partial_inv f (partial_inv f) :=\n  sorry\n\ntheorem partial_inv_left {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) (x : \u03b1) :\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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (b : \u03b2) : \u03b1 :=\n  dite (\u2203 (a : \u03b1), a \u2208 s \u2227 f a = b) (fun (h : \u2203 (a : \u03b1), a \u2208 s \u2227 f a = b) => classical.some h)\n    fun (h : \u00ac\u2203 (a : \u03b1), a \u2208 s \u2227 f a = b) => Classical.choice n\n\ntheorem inv_fun_on_pos {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2}\n    (h : \u2203 (a : \u03b1), \u2203 (H : a \u2208 s), f a = b) : inv_fun_on f s b \u2208 s \u2227 f (inv_fun_on f s b) = b :=\n  sorry\n\ntheorem inv_fun_on_mem {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2}\n    (h : \u2203 (a : \u03b1), \u2203 (H : a \u2208 s), f a = b) : inv_fun_on f s b \u2208 s :=\n  and.left (inv_fun_on_pos h)\n\ntheorem inv_fun_on_eq {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2}\n    (h : \u2203 (a : \u03b1), \u2203 (H : a \u2208 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' {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {a : \u03b1}\n    (h : \u2200 (x : \u03b1), x \u2208 s \u2192 \u2200 (y : \u03b1), y \u2208 s \u2192 f x = f y \u2192 x = y) (ha : a \u2208 s) :\n    inv_fun_on f s (f a) = a :=\n  (fun (this : \u2203 (a' : \u03b1), \u2203 (H : a' \u2208 s), f a' = f a) =>\n      h (inv_fun_on (fun (a' : \u03b1) => 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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2}\n    (h : \u00ac\u2203 (a : \u03b1), \u2203 (H : a \u2208 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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) : \u03b2 \u2192 \u03b1 := inv_fun_on f set.univ\n\ntheorem inv_fun_eq {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {b : \u03b2}\n    (h : \u2203 (a : \u03b1), f a = b) : f (inv_fun f b) = b :=\n  sorry\n\ntheorem inv_fun_neg {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {b : \u03b2}\n    (h : \u00ac\u2203 (a : \u03b1), f a = b) : inv_fun f b = Classical.choice n :=\n  sorry\n\ntheorem inv_fun_eq_of_injective_of_right_inverse {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v}\n    {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=\n  funext\n    fun (b : \u03b2) =>\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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2}\n    (hf : surjective f) : right_inverse (inv_fun f) f :=\n  fun (b : \u03b2) => inv_fun_eq (hf b)\n\ntheorem left_inverse_inv_fun {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2}\n    (hf : injective f) : left_inverse (inv_fun f) f :=\n  fun (b : \u03b1) =>\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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2}\n    (hf : injective f) : surjective (inv_fun f) :=\n  left_inverse.surjective (left_inverse_inv_fun hf)\n\ntheorem inv_fun_comp {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : injective f) :\n    inv_fun f \u2218 f = id :=\n  funext (left_inverse_inv_fun hf)\n\ntheorem injective.has_left_inverse {\u03b1 : Type u} [i : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2}\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 {\u03b1 : Type u} [i : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} :\n    injective f \u2194 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  `\u03b1` to be inhabited.) -/\ndef surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (h : surjective f) (b : \u03b2) : \u03b1 :=\n  classical.some (h b)\n\ntheorem surj_inv_eq {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (h : surjective f) (b : \u03b2) :\n    f (surj_inv h b) = b :=\n  classical.some_spec (h b)\n\ntheorem right_inverse_surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) :\n    right_inverse (surj_inv hf) f :=\n  surj_inv_eq hf\n\ntheorem left_inverse_surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} :\n    surjective f \u2194 has_right_inverse f :=\n  { mp := surjective.has_right_inverse, mpr := has_right_inverse.surjective }\n\ntheorem bijective_iff_has_inverse {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} :\n    bijective f \u2194 \u2203 (g : \u03b2 \u2192 \u03b1), left_inverse g f \u2227 right_inverse g f :=\n  sorry\n\ntheorem injective_surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (f : (a : \u03b1) \u2192 \u03b2 a) (a' : \u03b1) (v : \u03b2 a')\n    (a : \u03b1) : \u03b2 a :=\n  dite (a = a') (fun (h : a = a') => Eq._oldrec v (Eq.symm h)) fun (h : \u00aca = a') => f a\n\n/-- On non-dependent functions, `function.update` can be expressed as an `ite` -/\ntheorem update_apply {\u03b1 : Sort u} [DecidableEq \u03b1] {\u03b2 : Sort u_1} (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) (b : \u03b2)\n    (a : \u03b1) : update f a' b a = ite (a = a') b (f a) :=\n  sorry\n\n@[simp] theorem update_same {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (a : \u03b1) (v : \u03b2 a)\n    (f : (a : \u03b1) \u2192 \u03b2 a) : update f a v a = v :=\n  dif_pos rfl\n\ntheorem update_injective {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (f : (a : \u03b1) \u2192 \u03b2 a)\n    (a' : \u03b1) : injective (update f a') :=\n  sorry\n\n@[simp] theorem update_noteq {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {a : \u03b1} {a' : \u03b1}\n    (h : a \u2260 a') (v : \u03b2 a') (f : (a : \u03b1) \u2192 \u03b2 a) : update f a' v a = f a :=\n  dif_neg h\n\ntheorem forall_update_iff {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (f : (a : \u03b1) \u2192 \u03b2 a) {a : \u03b1}\n    {b : \u03b2 a} (p : (a : \u03b1) \u2192 \u03b2 a \u2192 Prop) :\n    (\u2200 (x : \u03b1), p x (update f a b x)) \u2194 p a b \u2227 \u2200 (x : \u03b1), x \u2260 a \u2192 p x (f x) :=\n  sorry\n\ntheorem update_eq_iff {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b2 a}\n    {f : (a : \u03b1) \u2192 \u03b2 a} {g : (a : \u03b1) \u2192 \u03b2 a} :\n    update f a b = g \u2194 b = g a \u2227 \u2200 (x : \u03b1), x \u2260 a \u2192 f x = g x :=\n  iff.trans funext_iff (forall_update_iff f fun (x : \u03b1) (y : \u03b2 x) => y = g x)\n\ntheorem eq_update_iff {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b2 a}\n    {f : (a : \u03b1) \u2192 \u03b2 a} {g : (a : \u03b1) \u2192 \u03b2 a} :\n    g = update f a b \u2194 g a = b \u2227 \u2200 (x : \u03b1), x \u2260 a \u2192 g x = f x :=\n  iff.trans funext_iff (forall_update_iff f fun (x : \u03b1) (y : \u03b2 x) => g x = y)\n\n@[simp] theorem update_eq_self {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (a : \u03b1)\n    (f : (a : \u03b1) \u2192 \u03b2 a) : update f a (f a) = f :=\n  iff.mpr update_eq_iff { left := rfl, right := fun (_x : \u03b1) (_x_1 : _x \u2260 a) => rfl }\n\ntheorem update_comp_eq_of_forall_ne' {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {\u03b1' : Sort u_1}\n    (g : (a : \u03b1) \u2192 \u03b2 a) {f : \u03b1' \u2192 \u03b1} {i : \u03b1} (a : \u03b2 i) (h : \u2200 (x : \u03b1'), f x \u2260 i) :\n    (fun (j : \u03b1') => update g i a (f j)) = fun (j : \u03b1') => g (f j) :=\n  funext fun (x : \u03b1') => 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 {\u03b1' : Sort w} [DecidableEq \u03b1'] {\u03b1 : Sort u_1} {\u03b2 : Sort u_2}\n    (g : \u03b1' \u2192 \u03b2) {f : \u03b1 \u2192 \u03b1'} {i : \u03b1'} (a : \u03b2) (h : \u2200 (x : \u03b1), f x \u2260 i) :\n    update g i a \u2218 f = g \u2218 f :=\n  update_comp_eq_of_forall_ne' g a h\n\ntheorem update_comp_eq_of_injective' {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {\u03b1' : Sort w} [DecidableEq \u03b1]\n    [DecidableEq \u03b1'] (g : (a : \u03b1) \u2192 \u03b2 a) {f : \u03b1' \u2192 \u03b1} (hf : injective f) (i : \u03b1') (a : \u03b2 (f i)) :\n    (fun (j : \u03b1') => update g (f i) a (f j)) = update (fun (i : \u03b1') => g (f i)) i a :=\n  iff.mpr eq_update_iff\n    { left := update_same (f i) a g,\n      right := fun (j : \u03b1') (hj : j \u2260 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 {\u03b1 : Sort u} {\u03b1' : Sort w} [DecidableEq \u03b1] [DecidableEq \u03b1']\n    {\u03b2 : Sort u_1} (g : \u03b1' \u2192 \u03b2) {f : \u03b1 \u2192 \u03b1'} (hf : injective f) (i : \u03b1) (a : \u03b2) :\n    update g (f i) a \u2218 f = update (g \u2218 f) i a :=\n  update_comp_eq_of_injective' g hf i a\n\ntheorem apply_update {\u03b9 : Sort u_1} [DecidableEq \u03b9] {\u03b1 : \u03b9 \u2192 Sort u_2} {\u03b2 : \u03b9 \u2192 Sort u_3}\n    (f : (i : \u03b9) \u2192 \u03b1 i \u2192 \u03b2 i) (g : (i : \u03b9) \u2192 \u03b1 i) (i : \u03b9) (v : \u03b1 i) (j : \u03b9) :\n    f j (update g i v j) = update (fun (k : \u03b9) => f k (g k)) i (f i v) j :=\n  sorry\n\ntheorem comp_update {\u03b1 : Sort u} [DecidableEq \u03b1] {\u03b1' : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1' \u2192 \u03b2)\n    (g : \u03b1 \u2192 \u03b1') (i : \u03b1) (v : \u03b1') : f \u2218 update g i v = update (f \u2218 g) i (f v) :=\n  funext (apply_update (fun (x : \u03b1) => f) g i v)\n\ntheorem update_comm {\u03b1 : Sort u_1} [DecidableEq \u03b1] {\u03b2 : \u03b1 \u2192 Sort u_2} {a : \u03b1} {b : \u03b1} (h : a \u2260 b)\n    (v : \u03b2 a) (w : \u03b2 b) (f : (a : \u03b1) \u2192 \u03b2 a) :\n    update (update f a v) b w = update (update f b w) a v :=\n  sorry\n\n@[simp] theorem update_idem {\u03b1 : Sort u_1} [DecidableEq \u03b1] {\u03b2 : \u03b1 \u2192 Sort u_2} {a : \u03b1} (v : \u03b2 a)\n    (w : \u03b2 a) (f : (a : \u03b1) \u2192 \u03b2 a) : update (update f a v) a w = update f a w :=\n  sorry\n\n/-- `extend f g e'` extends a function `g : \u03b1 \u2192 \u03b3`\nalong a function `f : \u03b1 \u2192 \u03b2` to a function `\u03b2 \u2192 \u03b3`,\nby using the values of `g` on the range of `f`\nand the values of an auxiliary function `e' : \u03b2 \u2192 \u03b3` elsewhere.\n\nMostly useful when `f` is injective. -/\ndef extend {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) :\n    \u03b2 \u2192 \u03b3 :=\n  fun (b : \u03b2) =>\n    dite (\u2203 (a : \u03b1), f a = b) (fun (h : \u2203 (a : \u03b1), f a = b) => g (classical.some h))\n      fun (h : \u00ac\u2203 (a : \u03b1), f a = b) => e' b\n\ntheorem extend_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3)\n    (b : \u03b2) :\n    extend f g e' b =\n        dite (\u2203 (a : \u03b1), f a = b) (fun (h : \u2203 (a : \u03b1), f a = b) => g (classical.some h))\n          fun (h : \u00ac\u2203 (a : \u03b1), f a = b) => e' b :=\n  rfl\n\n@[simp] theorem extend_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {f : \u03b1 \u2192 \u03b2}\n    (hf : injective f) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) (a : \u03b1) : extend f g e' (f a) = g a :=\n  sorry\n\n@[simp] theorem extend_comp {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {f : \u03b1 \u2192 \u03b2}\n    (hf : injective f) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) : extend f g e' \u2218 f = g :=\n  funext fun (a : \u03b1) => extend_apply hf g e' a\n\ntheorem uncurry_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) :\n    uncurry f = fun (p : \u03b1 \u00d7 \u03b2) => f (prod.fst p) (prod.snd p) :=\n  rfl\n\n@[simp] theorem uncurry_apply_pair {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (x : \u03b1) (y : \u03b2) : uncurry f (x, y) = f x y :=\n  rfl\n\n@[simp] theorem curry_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u00d7 \u03b2 \u2192 \u03b3) (x : \u03b1)\n    (y : \u03b2) : 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {\u03b5 : Type u_5}\n    (f : \u03b3 \u2192 \u03b4 \u2192 \u03b5) (g : \u03b1 \u2192 \u03b3) (h : \u03b2 \u2192 \u03b4) (a : \u03b1) (b : \u03b2) : \u03b5 :=\n  f (g a) (h b)\n\n/-- Compose an unary function `f` with a binary function `g`. -/\ndef bicompr {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b3 \u2192 \u03b4) (g : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (a : \u03b1) (b : \u03b2) : \u03b4 :=\n  f (g a b)\n\n-- Suggested local notation:\n\ntheorem uncurry_bicompr {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (g : \u03b3 \u2192 \u03b4) : uncurry (bicompr g f) = g \u2218 uncurry f :=\n  rfl\n\ntheorem uncurry_bicompl {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {\u03b5 : Type u_5}\n    (f : \u03b3 \u2192 \u03b4 \u2192 \u03b5) (g : \u03b1 \u2192 \u03b3) (h : \u03b2 \u2192 \u03b4) : uncurry (bicompl f g h) = uncurry f \u2218 prod.map g h :=\n  rfl\n\n/-- Records a way to turn an element of `\u03b1` into a function from `\u03b2` to `\u03b3`. The most generic use\nis to recursively uncurry. For instance `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4` will be turned into\n`\u21bff : \u03b1 \u00d7 \u03b2 \u00d7 \u03b3 \u2192 \u03b4`. One can also add instances for bundled maps. -/\nclass has_uncurry (\u03b1 : Type u_5) (\u03b2 : outParam (Type u_6)) (\u03b3 : outParam (Type u_7)) where\n  uncurry : \u03b1 \u2192 \u03b2 \u2192 \u03b3\n\nprefix:1024 \"\u21bf\" => Mathlib.function.has_uncurry.uncurry\n\n/-- Uncurrying operator. The most generic use is to recursively uncurry. For instance\n`f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4` will be turned into `\u21bff : \u03b1 \u00d7 \u03b2 \u00d7 \u03b3 \u2192 \u03b4`. One can also add instances\nfor bundled maps.-/\nprotected instance has_uncurry_base {\u03b1 : Type u_1} {\u03b2 : Type u_2} : has_uncurry (\u03b1 \u2192 \u03b2) \u03b1 \u03b2 :=\n  has_uncurry.mk id\n\nprotected instance has_uncurry_induction {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4}\n    [has_uncurry \u03b2 \u03b3 \u03b4] : has_uncurry (\u03b1 \u2192 \u03b2) (\u03b1 \u00d7 \u03b3) \u03b4 :=\n  has_uncurry.mk fun (f : \u03b1 \u2192 \u03b2) (p : \u03b1 \u00d7 \u03b3) => has_uncurry.uncurry (f (prod.fst p)) (prod.snd p)\n\n/-- A function is involutive, if `f \u2218 f = id`. -/\ndef involutive {\u03b1 : Sort u_1} (f : \u03b1 \u2192 \u03b1) := \u2200 (x : \u03b1), f (f x) = x\n\ntheorem involutive_iff_iter_2_eq_id {\u03b1 : Sort u_1} {f : \u03b1 \u2192 \u03b1} :\n    involutive f \u2194 nat.iterate f (bit0 1) = id :=\n  iff.symm funext_iff\n\nnamespace involutive\n\n\n@[simp] theorem comp_self {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : f \u2218 f = id := funext h\n\nprotected theorem left_inverse {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : left_inverse f f := h\n\nprotected theorem right_inverse {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : right_inverse f f := h\n\nprotected theorem injective {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : injective f :=\n  left_inverse.injective (involutive.left_inverse h)\n\nprotected theorem surjective {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : surjective f :=\n  fun (x : \u03b1) => Exists.intro (f x) (h x)\n\nprotected theorem bijective {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : bijective f :=\n  { left := involutive.injective h, right := involutive.surjective h }\n\n/-- Involuting an `ite` of an involuted value `x : \u03b1` negates the `Prop` condition in the `ite`. -/\nprotected theorem ite_not {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) (P : Prop) [Decidable P]\n    (x : \u03b1) : f (ite P x (f x)) = ite (\u00acP) x (f x) :=\n  sorry\n\nend involutive\n\n\n/-- The property of a binary function `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3` being injective.\n  Mathematically this should be thought of as the corresponding function `\u03b1 \u00d7 \u03b2 \u2192 \u03b3` being injective.\n-/\ndef injective2 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) :=\n  \u2200 {a\u2081 a\u2082 : \u03b1} {b\u2081 b\u2082 : \u03b2}, f a\u2081 b\u2081 = f a\u2082 b\u2082 \u2192 a\u2081 = a\u2082 \u2227 b\u2081 = b\u2082\n\nnamespace injective2\n\n\nprotected theorem left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (hf : injective2 f) {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} (h : f a\u2081 b\u2081 = f a\u2082 b\u2082) : a\u2081 = a\u2082 :=\n  and.left (hf h)\n\nprotected theorem right {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (hf : injective2 f) {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} (h : f a\u2081 b\u2081 = f a\u2082 b\u2082) : b\u2081 = b\u2082 :=\n  and.right (hf h)\n\ntheorem eq_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hf : injective2 f)\n    {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} : f a\u2081 b\u2081 = f a\u2082 b\u2082 \u2194 a\u2081 = a\u2082 \u2227 b\u2081 = b\u2082 :=\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 `\u03b1` is a proposition, in which case `f` is necessarily a\nconstant function, so that `sometimes f = f a` for all `a`. -/\ndef sometimes {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [Nonempty \u03b2] (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  dite (Nonempty \u03b1) (fun (h : Nonempty \u03b1) => f (Classical.choice h))\n    fun (h : \u00acNonempty \u03b1) => Classical.choice _inst_1\n\ntheorem sometimes_eq {p : Prop} {\u03b1 : Sort u_1} [Nonempty \u03b1] (f : p \u2192 \u03b1) (a : p) :\n    sometimes f = f a :=\n  dif_pos (Nonempty.intro a)\n\ntheorem sometimes_spec {p : Prop} {\u03b1 : Sort u_1} [Nonempty \u03b1] (P : \u03b1 \u2192 Prop) (f : p \u2192 \u03b1) (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 {\u03b1 : Type u} {\u03b2 : \u03b1 \u2192 Sort v} (s : set \u03b1) (f : (i : \u03b1) \u2192 \u03b2 i) (g : (i : \u03b1) \u2192 \u03b2 i)\n    [(j : \u03b1) \u2192 Decidable (j \u2208 s)] (i : \u03b1) : \u03b2 i :=\n  ite (i \u2208 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": "import tactic.core\n\nopen tactic lean.parser interactive.types\n\nrun_parser do\n  e \u2190 with_input texpr \"\u03bb x:\u2115, x\",\n  e \u2190 to_expr e.1,\n  guard (e =\u2090 `(\u03bb x:\u2115, x)),\n  emit_code_here \"def foo := 1\"\n\nexample : foo = 1 := rfl\n\n-- check that `emit_code_here` terminates properly\nrun_parser emit_code_here \"\\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/run_parser.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.060086644283076515, "lm_q1q2_score": 0.01748406380143658}}
{"text": "/-\nCopyright (c) 2017 Mario Carneiro All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Floris van Doorn\n-/\nimport tactic.core\n\nnamespace tactic\n\n/-- `copy_attribute' attr_name src tgt p d_name` copy (user) attribute `attr_name` from\n   `src` to `tgt` if it is defined for `src`; unlike `copy_attribute` the primed version also copies\n   the parameter of the user attribute, in the user attribute case. Make it persistent if `p` is\n   `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src`  -/\nmeta def copy_attribute' (attr_name : name) (src : name) (tgt : name) (p : option bool := none) :\ntactic unit := do\n  get_decl tgt <|> fail!\"unknown declaration {tgt}\",\n  -- if the source doesn't have the attribute we do not error and simply return\n  mwhen (succeeds (has_attribute attr_name src)) $\n    do (p', prio) \u2190 has_attribute attr_name src,\n      let p := p.get_or_else p',\n      s \u2190 try_or_report_error (set_basic_attribute attr_name tgt p prio),\n      sum.inr msg \u2190 return s | skip,\n      if msg =\n        (format!(\"set_basic_attribute tactic failed, '{attr_name}' \" ++\n          \"is not a basic attribute\")).to_string\n      then do\n        user_attr_const \u2190 (get_user_attribute_name attr_name >>= mk_const),\n        tac \u2190 eval_pexpr (tactic unit)\n        ``(user_attribute.get_param_untyped %%user_attr_const %%src >>=\n          \u03bb x, user_attribute.set_untyped %%user_attr_const %%tgt x %%p %%prio),\n        tac\n      else fail msg\n\nopen expr\n/-- Auxilliary function for `additive_test`. The bool argument *only* matters when applied\nto exactly a constant. -/\nmeta def additive_test_aux (f : name \u2192 option name) (ignore : name_map $ list \u2115) :\n  bool \u2192 expr \u2192 bool\n| b (var n)                := tt\n| b (sort l)               := tt\n| b (const n ls)           := b || (f n).is_some\n| b (mvar n m t)           := tt\n| b (local_const n m bi t) := tt\n| b (app e f)              := additive_test_aux tt e &&\n  -- this might be inefficient.\n  -- If it becomes a performance problem: we can give this info for the recursive call to `e`.\n    match ignore.find e.get_app_fn.const_name with\n    | some l := if e.get_app_num_args + 1 \u2208 l then tt else additive_test_aux ff f\n    | none   := additive_test_aux ff f\n    end\n| b (lam n bi e t)         := additive_test_aux ff t\n| b (pi n bi e t)          := additive_test_aux ff t\n| b (elet n g e f)         := additive_test_aux ff e && additive_test_aux ff f\n| b (macro d args)         := tt\n\n/--\n`additive_test f replace_all ignore e` tests whether the expression `e` contains no constant\n`nm` that is not applied to any arguments, and such that `f nm = none`.\nThis is used in `@[to_additive]` for deciding which subexpressions to transform: we only transform\nconstants if `additive_test` applied to their first argument returns `tt`.\nThis means we will replace expression applied to e.g. `\u03b1` or `\u03b1 \u00d7 \u03b2`, but not when applied to\ne.g. `\u2115` or `\u211d \u00d7 \u03b1`.\n`f` is the dictionary of declarations that are in the `to_additive` dictionary.\nWe ignore all arguments specified in the `name_map` `ignore`.\nIf `replace_all` is `tt` the test always return `tt`.\n-/\nmeta def additive_test (f : name \u2192 option name) (replace_all : bool) (ignore : name_map $ list \u2115)\n  (e : expr) : bool :=\nif replace_all then tt else additive_test_aux f ignore ff e\n\n/-- transform the declaration `src` and all declarations `pre._proof_i` occurring in `src`\nusing the dictionary `f`.\n`replace_all`, `trace`, `ignore` and `reorder` are configuration options.\n`pre` is the declaration that got the `@[to_additive]` attribute and `tgt_pre` is the target of this\ndeclaration. -/\nmeta def transform_decl_with_prefix_fun_aux (f : name \u2192 option name)\n  (replace_all trace : bool) (relevant : name_map \u2115) (ignore reorder : name_map $ list \u2115)\n  (pre tgt_pre : name) : name \u2192 command :=\n\u03bb src,\ndo\n  -- if this declaration is not `pre` or an internal declaration, we do nothing.\n  tt \u2190 return (src = pre \u2228 src.is_internal : bool) |\n    if (f src).is_some then skip else fail!(\"@[to_additive] failed.\nThe declaration {pre} depends on the declaration {src} which is in the namespace {pre}, but \" ++\n\"does not have the `@[to_additive]` attribute. This is not supported. Workaround: move {src} to \" ++\n\"a different namespace.\"),\n  env \u2190 get_env,\n  -- we find the additive name of `src`\n  let tgt := src.map_prefix (\u03bb n, if n = pre then some tgt_pre else none),\n  -- we skip if we already transformed this declaration before\n  ff \u2190 return $ env.contains tgt | skip,\n  decl \u2190 get_decl src,\n  -- we first transform all the declarations of the form `pre._proof_i`\n  (decl.type.list_names_with_prefix pre).mfold () (\u03bb n _, transform_decl_with_prefix_fun_aux n),\n  (decl.value.list_names_with_prefix pre).mfold () (\u03bb n _, transform_decl_with_prefix_fun_aux n),\n  -- we transform `decl` using `f` and the configuration options.\n  let decl :=\n    decl.update_with_fun env (name.map_prefix f) (additive_test f replace_all ignore)\n      relevant reorder tgt,\n  -- o \u2190 get_options, set_options $ o.set_bool `pp.all tt, -- print with pp.all (for debugging)\n  pp_decl \u2190 pp decl,\n  when trace $ trace!\"[to_additive] > generating\\n{pp_decl}\",\n  decorate_error (format!\"@[to_additive] failed. Type mismatch in additive declaration.\nFor help, see the docstring of `to_additive.attr`, section `Troubleshooting`.\nFailed to add declaration\\n{pp_decl}\n\nNested error message:\\n\").to_string $ do\n  { if env.is_protected src then add_protected_decl decl else add_decl decl,\n    -- we test that the declaration value type-checks, so that we get the decorated error message\n    -- without this line, the type-checking might fail outside the `decorate_error`.\n    decorate_error \"proof doesn't type-check. \" $ type_check decl.value }\n\n/--\nMake a new copy of a declaration,\nreplacing fragments of the names of identifiers in the type and the body using the function `f`.\nThis is used to implement `@[to_additive]`.\n-/\nmeta def transform_decl_with_prefix_fun (f : name \u2192 option name) (replace_all trace : bool)\n  (relevant : name_map \u2115) (ignore reorder : name_map $ list \u2115) (src tgt : name) (attrs : list name)\n  : command :=\ndo -- In order to ensure that attributes are copied correctly we must transform declarations and\n   -- attributes in the right order:\n   -- first generate the transformed main declaration\n   transform_decl_with_prefix_fun_aux f replace_all trace relevant ignore reorder src tgt src,\n   ls \u2190 get_eqn_lemmas_for tt src,\n   -- now transform all of the equational lemmas\n   ls.mmap' $\n    transform_decl_with_prefix_fun_aux f replace_all trace relevant ignore reorder src tgt,\n   -- copy attributes for the equational lemmas so that they know if they are refl lemmas\n   ls.mmap' (\u03bb src_eqn, do\n    let tgt_eqn := src_eqn.map_prefix (\u03bb n, if n = src then some tgt else none),\n    attrs.mmap' (\u03bb n, copy_attribute' n src_eqn tgt_eqn)),\n   -- set the transformed equation lemmas as equation lemmas for the new declaration\n   ls.mmap' (\u03bb src_eqn, do\n    e \u2190 get_env,\n    let tgt_eqn := src_eqn.map_prefix (\u03bb n, if n = src then some tgt else none),\n    set_env (e.add_eqn_lemma tgt_eqn)),\n   -- copy attributes for the main declaration, this needs the equational lemmas to exist already\n   attrs.mmap' (\u03bb n, copy_attribute' n src tgt)\n\n/--\nMake a new copy of a declaration, replacing fragments of the names of identifiers in the type and\nthe body using the dictionary `dict`.\nThis is used to implement `@[to_additive]`.\n-/\nmeta def transform_decl_with_prefix_dict (dict : name_map name) (replace_all trace : bool)\n  (relevant : name_map \u2115) (ignore reorder : name_map $ list \u2115) (src tgt : name) (attrs : list name)\n  : command :=\ntransform_decl_with_prefix_fun dict.find replace_all trace relevant ignore reorder src tgt attrs\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/transform_decl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.03789242364175707, "lm_q1q2_score": 0.017469043107660703}}
{"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 : \u2211 j : J, biproduct.\u03c0 f j \u226b biproduct.\u03b9 f j = \ud835\udfd9 (\u2a01 f)`,\n  or, in the binary case, `total : fst \u226b inl + snd \u226b inr = \ud835\udfd9 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\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082` whose `X\u2081 \u27f6 Y\u2081` entry is an isomorphism,\n  then we can construct isomorphisms `L : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082` and `R : Y\u2081 \u229e Y\u2082 \u2245 Y\u2081 \u229e Y\u2082`\n  so that `L.hom \u226b g \u226b R.hom` is diagonal (with `X\u2081 \u27f6 Y\u2081` component still `f`),\n  via Gaussian elimination.\n\n* As a corollary of the previous two facts,\n  if we have an isomorphism `X\u2081 \u229e X\u2082 \u2245 Y\u2081 \u229e Y\u2082` whose `X\u2081 \u27f6 Y\u2081` entry is an isomorphism,\n  we can construct an isomorphism `X\u2082 \u2245 Y\u2082`.\n\n* If `f : W \u229e X \u27f6 Y \u229e Z` is an isomorphism, either `\ud835\udfd9 W = 0`,\n  or at least one of the component maps `W \u27f6 Y` and `W \u27f6 Z` is nonzero.\n\n* If `f : \u2a01 S \u27f6 \u2a01 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 \u2192 C` from\nany bicone `b` for `f` satisfying `total : \u2211 j : J, b.\u03c0 j \u226b b.\u03b9 j = \ud835\udfd9 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 \u2192 C} (b : bicone f) (total : \u2211 j : J, b.\u03c0 j \u226b b.\u03b9 j = \ud835\udfd9 b.X) :\n  b.is_bilimit :=\n{ is_limit :=\n  { lift := \u03bb s, \u2211 (j : J), s.\u03c0.app \u27e8j\u27e9 \u226b b.\u03b9 j,\n    uniq' := \u03bb s m h,\n    begin\n      erw [\u2190category.comp_id m, \u2190total, comp_sum],\n      apply finset.sum_congr rfl,\n      intros j m,\n      erw [reassoc_of (h \u27e8j\u27e9)],\n    end,\n    fac' := \u03bb s j,\n    begin\n      cases j,\n      simp only [sum_comp, category.assoc, bicone.to_cone_\u03c0_app, b.\u03b9_\u03c0, comp_dite],\n      -- See note [dsimp, simp].\n      dsimp, simp,\n    end },\n  is_colimit :=\n  { desc := \u03bb s, \u2211 (j : J), b.\u03c0 j \u226b s.\u03b9.app \u27e8j\u27e9,\n    uniq' := \u03bb s m h,\n    begin\n      erw [\u2190category.id_comp m, \u2190total, sum_comp],\n            apply finset.sum_congr rfl,\n      intros j m,\n      erw [category.assoc, h \u27e8j\u27e9],\n    end,\n    fac' := \u03bb s j,\n    begin\n      cases j,\n      simp only [comp_sum, \u2190category.assoc, bicone.to_cocone_\u03b9_app, b.\u03b9_\u03c0, dite_comp],\n      dsimp, simp,\n    end } }\n\nlemma is_bilimit.total {f : J \u2192 C} {b : bicone f} (i : b.is_bilimit) :\n  \u2211 j : J, b.\u03c0 j \u226b b.\u03b9 j = \ud835\udfd9 b.X :=\ni.is_limit.hom_ext (\u03bb j, by { cases j, simp [sum_comp, b.\u03b9_\u03c0, comp_dite] })\n\n/--\nIn a preadditive category, we can construct a biproduct for `f : J \u2192 C` from\nany bicone `b` for `f` satisfying `total : \u2211 j : J, b.\u03c0 j \u226b b.\u03b9 j = \ud835\udfd9 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 \u2192 C} (b : bicone f) (total : \u2211 j : J, b.\u03c0 j \u226b b.\u03b9 j = \ud835\udfd9 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 \u2192 C} (t : bicone f) (ht : is_limit t.to_cone) : t.is_bilimit :=\nis_bilimit_of_total _ $ ht.hom_ext $\n  \u03bb j, by { cases j, simp [sum_comp, t.\u03b9_\u03c0, 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 \u2192 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 \u27e8j\u27e9, tidy })\n\n/-- In a preadditive category, if the product over `f : J \u2192 C` exists,\n    then the biproduct over `f` exists. -/\nlemma has_biproduct.of_has_product {J : Type} [finite J] (f : J \u2192 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 \u2192 C} (t : bicone f) (ht : is_colimit t.to_cocone) :\n  t.is_bilimit :=\nis_bilimit_of_total _ $ ht.hom_ext $ \u03bb j, begin\n  cases j,\n  simp_rw [bicone.to_cocone_\u03b9_app, comp_sum, \u2190 category.assoc, t.\u03b9_\u03c0, 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 \u2192 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 \u27e8j\u27e9, tidy })\n\n/-- In a preadditive category, if the coproduct over `f : J \u2192 C` exists,\n    then the biproduct over `f` exists. -/\nlemma has_biproduct.of_has_coproduct {J : Type} [finite J] (f : J \u2192 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\u27e8\u03bb n, { has_biproduct := \u03bb F, has_biproduct.of_has_product _ }\u27e9\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\u27e8\u03bb n, { has_biproduct := \u03bb F, has_biproduct.of_has_coproduct _ }\u27e9\n\nsection\nvariables {f : J \u2192 C} [has_biproduct f]\n\n/--\nIn any preadditive category, any biproduct satsifies\n`\u2211 j : J, biproduct.\u03c0 f j \u226b biproduct.\u03b9 f j = \ud835\udfd9 (\u2a01 f)`\n-/\n@[simp] lemma biproduct.total : \u2211 j : J, biproduct.\u03c0 f j \u226b biproduct.\u03b9 f j = \ud835\udfd9 (\u2a01 f) :=\nis_bilimit.total (biproduct.is_bilimit _)\n\nlemma biproduct.lift_eq {T : C} {g : \u03a0 j, T \u27f6 f j} :\n  biproduct.lift g = \u2211 j, g j \u226b biproduct.\u03b9 f j :=\nbegin\n  ext j,\n  simp only [sum_comp, biproduct.\u03b9_\u03c0, comp_dite, biproduct.lift_\u03c0, 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 : \u03a0 j, f j \u27f6 T} :\n  biproduct.desc g = \u2211 j, biproduct.\u03c0 f j \u226b g j :=\nbegin\n  ext j,\n  simp [comp_sum, biproduct.\u03b9_\u03c0_assoc, dite_comp],\nend\n\n@[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : \u03a0 j, T \u27f6 f j} {h : \u03a0 j, f j \u27f6 U} :\n  biproduct.lift g \u226b biproduct.desc h = \u2211 j : J, g j \u226b h j :=\nby simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.\u03b9_\u03c0_assoc,\n  comp_dite, dite_comp]\n\nlemma biproduct.map_eq [has_finite_biproducts C] {f g : J \u2192 C} {h : \u03a0 j, f j \u27f6 g j} :\n  biproduct.map h = \u2211 j : J, biproduct.\u03c0 f j \u226b h j \u226b biproduct.\u03b9 g j :=\nbegin\n  ext,\n  simp [biproduct.\u03b9_\u03c0, biproduct.\u03b9_\u03c0_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 \u2192 C} {g : K \u2192 C} (m : \u03a0 j k, f j \u27f6 g k) {P} (x : \u03a0 k, g k \u27f6 P) :\n  biproduct.matrix m \u226b biproduct.desc x = biproduct.desc (\u03bb j, \u2211 k, m j k \u226b 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 \u2192 C} {g : K \u2192 C} {P} (x : \u03a0 j, P \u27f6 f j) (m : \u03a0 j k, f j \u27f6 g k)  :\n  biproduct.lift x \u226b biproduct.matrix m = biproduct.lift (\u03bb k, \u2211 j, x j \u226b 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 \u2192 C} {g : K \u2192 C} {h : K \u2192 C} (m : \u03a0 j k, f j \u27f6 g k) (n : \u03a0 k, g k \u27f6 h k) :\n  biproduct.matrix m \u226b biproduct.map n = biproduct.matrix (\u03bb j k, m j k \u226b n k) :=\nby { ext, simp, }\n\n@[reassoc]\nlemma biproduct.map_matrix\n  {K : Type} [fintype K] [has_finite_biproducts C]\n  {f : J \u2192 C} {g : J \u2192 C} {h : K \u2192 C} (m : \u03a0 k, f k \u27f6 g k) (n : \u03a0 j k, g j \u27f6 h k) :\n  biproduct.map m \u226b biproduct.matrix n = biproduct.matrix (\u03bb j k, m j \u226b 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 {\u03b2 \u03b3 : Type} [fintype \u03b2] [decidable_eq \u03b2] [decidable_eq \u03b3]\n  (\u03b5 : \u03b2 \u2243 \u03b3) (f : \u03b3 \u2192 C) [has_biproduct f] [has_biproduct (f \u2218 \u03b5)] : (\u2a01 (f \u2218 \u03b5)) \u2245 (\u2a01 f) :=\n{ hom := biproduct.desc (\u03bb b, biproduct.\u03b9 f (\u03b5 b)),\n  inv := biproduct.lift (\u03bb b, biproduct.\u03c0 f (\u03b5 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.\u03b9_\u03c0, biproduct.\u03b9_\u03c0_assoc, comp_dite,\n      equiv.apply_eq_iff_eq_symm_apply, finset.sum_dite_eq' finset.univ (\u03b5.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 \u226b b.inl + b.snd \u226b b.inr = \ud835\udfd9 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 \u226b b.inl + b.snd \u226b b.inr = \ud835\udfd9 b.X) : b.is_bilimit :=\n{ is_limit :=\n  { lift := \u03bb s, binary_fan.fst s \u226b b.inl +\n      binary_fan.snd s \u226b b.inr,\n    uniq' := \u03bb s m h, by erw [\u2190category.comp_id m, \u2190total,\n      comp_add, reassoc_of (h \u27e8walking_pair.left\u27e9), reassoc_of (h \u27e8walking_pair.right\u27e9)],\n    fac' := \u03bb s j, by rcases j with \u27e8\u27e8\u27e9\u27e9; simp, },\n  is_colimit :=\n  { desc := \u03bb s, b.fst \u226b binary_cofan.inl s +\n      b.snd \u226b binary_cofan.inr s,\n    uniq' := \u03bb s m h, by erw [\u2190category.id_comp m, \u2190total,\n      add_comp, category.assoc, category.assoc, h \u27e8walking_pair.left\u27e9, h \u27e8walking_pair.right\u27e9],\n    fac' := \u03bb s j, by rcases j with \u27e8\u27e8\u27e9\u27e9; simp, } }\n\nlemma is_bilimit.binary_total {X Y : C} {b : binary_bicone X Y} (i : b.is_bilimit) :\n  b.fst \u226b b.inl + b.snd \u226b b.inr = \ud835\udfd9 b.X :=\ni.is_limit.hom_ext (\u03bb j, by { rcases j with \u27e8\u27e8\u27e9\u27e9; 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 \u226b b.inl + b.snd \u226b b.inr = \ud835\udfd9 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 \u226b b.inl + b.snd \u226b b.inr = \ud835\udfd9 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.\u03c0.app \u27e8walking_pair.left\u27e9,\n  snd := t.\u03c0.app \u27e8walking_pair.right\u27e9,\n  inl := ht.lift (binary_fan.mk (\ud835\udfd9 X) 0),\n  inr := ht.lift (binary_fan.mk 0 (\ud835\udfd9 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 (\ud835\udfd9 X) 0) :=\nby apply ht.uniq (binary_fan.mk (\ud835\udfd9 X) 0); rintro \u27e8\u27e8\u27e9\u27e9; 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 (\ud835\udfd9 Y)) :=\nby apply ht.uniq (binary_fan.mk 0 (\ud835\udfd9 Y)); rintro \u27e8\u27e8\u27e9\u27e9; 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 := \u03bb 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 (\ud835\udfd9 X) 0),\n  snd := ht.desc (binary_cofan.mk 0 (\ud835\udfd9 Y)),\n  inl := t.\u03b9.app \u27e8walking_pair.left\u27e9,\n  inr := t.\u03b9.app \u27e8walking_pair.right\u27e9 }\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 (\ud835\udfd9 X) 0) :=\nbegin\n  apply ht.uniq (binary_cofan.mk (\ud835\udfd9 X) 0),\n  rintro \u27e8\u27e8\u27e9\u27e9; 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 (\ud835\udfd9 Y)) :=\nbegin\n  apply ht.uniq (binary_cofan.mk 0 (\ud835\udfd9 Y)),\n  rintro \u27e8\u27e8\u27e9\u27e9; 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 _) $ \u03bb j, by { rcases j with \u27e8\u27e8\u27e9\u27e9, 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 := \u03bb 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 \u226b biprod.inl + biprod.snd \u226b biprod.inr = \ud835\udfd9 (X \u229e Y)`.\n-/\n@[simp] lemma biprod.total : biprod.fst \u226b biprod.inl + biprod.snd \u226b biprod.inr = \ud835\udfd9 (X \u229e Y) :=\nbegin\n  ext; simp [add_comp],\nend\n\nlemma biprod.lift_eq {T : C} {f : T \u27f6 X} {g : T \u27f6 Y} :\n  biprod.lift f g = f \u226b biprod.inl + g \u226b biprod.inr :=\nbegin\n  ext; simp [add_comp],\nend\n\n\n\n@[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T \u27f6 X} {g : T \u27f6 Y} {h : X \u27f6 U} {i : Y \u27f6 U} :\n  biprod.lift f g \u226b biprod.desc h i = f \u226b h + g \u226b 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 \u27f6 Y} {g : X \u27f6 Z} :\n  biprod.map f g = biprod.fst \u226b f \u226b biprod.inl + biprod.snd \u226b g \u226b 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 \u27f6 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.\u03c0,\n  inl := f,\n  inr :=\n    let c' : cokernel_cofork (\ud835\udfd9 Y - (\ud835\udfd9 Y - retraction f \u226b f)) :=\n      cokernel_cofork.of_\u03c0 (cofork.\u03c0 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_\u03c0],\n    letI := epi_of_is_colimit_cofork i,\n    apply zero_of_epi_comp c.\u03c0,\n    simp only [sub_comp, comp_sub, category.comp_id, category.assoc, is_split_mono.id, sub_self,\n      cofork.is_colimit.\u03c0_desc_assoc, cokernel_cofork.\u03c0_of_\u03c0, 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 \u27f6 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.\u03c0_desc,\n    cokernel_cofork_of_cofork_\u03c0, cofork.\u03c0_of_\u03c0, 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  (\u03bb T f g, f \u226b b.inl + g \u226b b.inr) (\u03bb T f g, by simp) (\u03bb T f g, by simp) $ \u03bb T f g m h\u2081 h\u2082,\n  begin\n    have h\u2081' : (m - (f \u226b b.inl + g \u226b b.inr)) \u226b b.fst = 0 := by simpa using sub_eq_zero.2 h\u2081,\n    have h\u2082' : (m - (f \u226b b.inl + g \u226b b.inr)) \u226b b.snd = 0 := by simpa using sub_eq_zero.2 h\u2082,\n    obtain \u27e8q : T \u27f6 X, hq : q \u226b b.inl = m - (f \u226b b.inl + g \u226b b.inr)\u27e9 :=\n      kernel_fork.is_limit.lift' hb _ h\u2082',\n    rw [\u2190sub_eq_zero, \u2190hq, \u2190category.comp_id q, \u2190b.inl_fst, \u2190category.assoc, hq, h\u2081', 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  (\u03bb T f g, f \u226b b.inl + g \u226b b.inr) (\u03bb t f g, by simp) (\u03bb t f g, by simp) $ \u03bb T f g m h\u2081 h\u2082,\n  begin\n    have h\u2081' : (m - (f \u226b b.inl + g \u226b b.inr)) \u226b b.fst = 0 := by simpa using sub_eq_zero.2 h\u2081,\n    have h\u2082' : (m - (f \u226b b.inl + g \u226b b.inr)) \u226b b.snd = 0 := by simpa using sub_eq_zero.2 h\u2082,\n    obtain \u27e8q : T \u27f6 Y, hq : q \u226b b.inr = m - (f \u226b b.inl + g \u226b b.inr)\u27e9 :=\n      kernel_fork.is_limit.lift' hb _ h\u2081',\n    rw [\u2190sub_eq_zero, \u2190hq, \u2190category.comp_id q, \u2190b.inr_snd, \u2190category.assoc, hq, h\u2082', 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  (\u03bb T f g, b.fst \u226b f + b.snd \u226b g) (\u03bb T f g, by simp) (\u03bb T f g, by simp) $ \u03bb T f g m h\u2081 h\u2082,\n  begin\n    have h\u2081' : b.inl \u226b (m - (b.fst \u226b f + b.snd \u226b g)) = 0 := by simpa using sub_eq_zero.2 h\u2081,\n    have h\u2082' : b.inr \u226b (m - (b.fst \u226b f + b.snd \u226b g)) = 0 := by simpa using sub_eq_zero.2 h\u2082,\n    obtain \u27e8q : X \u27f6 T, hq : b.fst \u226b q = m - (b.fst \u226b f + b.snd \u226b g)\u27e9 :=\n      cokernel_cofork.is_colimit.desc' hb _ h\u2082',\n    rw [\u2190sub_eq_zero, \u2190hq, \u2190category.id_comp q, \u2190b.inl_fst, category.assoc, hq, h\u2081', 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  (\u03bb T f g, b.fst \u226b f + b.snd \u226b g) (\u03bb T f g, by simp) (\u03bb T f g, by simp) $ \u03bb T f g m h\u2081 h\u2082,\n  begin\n    have h\u2081' : b.inl \u226b (m - (b.fst \u226b f + b.snd \u226b g)) = 0 := by simpa using sub_eq_zero.2 h\u2081,\n    have h\u2082' : b.inr \u226b (m - (b.fst \u226b f + b.snd \u226b g)) = 0 := by simpa using sub_eq_zero.2 h\u2082,\n    obtain \u27e8q : Y \u27f6 T, hq : b.snd \u226b q = m - (b.fst \u226b f + b.snd \u226b g)\u27e9 :=\n      cokernel_cofork.is_colimit.desc' hb _ h\u2081',\n    rw [\u2190sub_eq_zero, \u2190hq, \u2190category.id_comp q, \u2190b.inr_snd, category.assoc, hq, h\u2082', 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 \u27f6 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 (\ud835\udfd9 X - (\ud835\udfd9 X - f \u226b section_ f)) :=\n      kernel_fork.of_\u03b9 (fork.\u03b9 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.\u03b9,\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_\u03b9],\n    letI := mono_of_is_limit_fork i,\n    apply zero_of_comp_mono c.\u03b9,\n    simp only [comp_sub, category.comp_id, category.assoc, sub_self, fork.is_limit.lift_\u03b9,\n      fork.\u03b9_of_\u03b9, 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 \u27f6 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 \u27f6 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 (\ud835\udfd9 X) (\ud835\udfd9 X) \u226b 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 \u226b biprod.desc (\ud835\udfd9 Y) (\ud835\udfd9 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 $ \u03bb a b,\nbegin\n  ext X Y f g,\n  have h\u2081 := @biprod.add_eq_lift_id_desc _ _ a _ _ f g\n    (by convert (infer_instance : has_binary_biproduct X X)),\n  have h\u2082 := @biprod.add_eq_lift_id_desc _ _ b _ _ f g\n    (by convert (infer_instance : has_binary_biproduct X X)),\n  refine h\u2081.trans (eq.trans _ h\u2082.symm),\n  congr' 2;\n  exact subsingleton.elim _ _\nend\nend\n\nsection\nvariables  [has_binary_biproducts.{v} C]\n\nvariables {X\u2081 X\u2082 Y\u2081 Y\u2082 : C}\nvariables (f\u2081\u2081 : X\u2081 \u27f6 Y\u2081) (f\u2081\u2082 : X\u2081 \u27f6 Y\u2082) (f\u2082\u2081 : X\u2082 \u27f6 Y\u2081) (f\u2082\u2082 : X\u2082 \u27f6 Y\u2082)\n\n/--\nThe \"matrix\" morphism `X\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082` with specified components.\n-/\ndef biprod.of_components : X\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082 :=\nbiprod.fst \u226b f\u2081\u2081 \u226b biprod.inl +\nbiprod.fst \u226b f\u2081\u2082 \u226b biprod.inr +\nbiprod.snd \u226b f\u2082\u2081 \u226b biprod.inl +\nbiprod.snd \u226b f\u2082\u2082 \u226b biprod.inr\n\n@[simp]\nlemma biprod.inl_of_components :\n  biprod.inl \u226b biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082 =\n    f\u2081\u2081 \u226b biprod.inl + f\u2081\u2082 \u226b biprod.inr :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.inr_of_components :\n  biprod.inr \u226b biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082 =\n    f\u2082\u2081 \u226b biprod.inl + f\u2082\u2082 \u226b biprod.inr :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.of_components_fst :\n  biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082 \u226b biprod.fst =\n    biprod.fst \u226b f\u2081\u2081 + biprod.snd \u226b f\u2082\u2081 :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.of_components_snd :\n  biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082 \u226b biprod.snd =\n    biprod.fst \u226b f\u2081\u2082 + biprod.snd \u226b f\u2082\u2082 :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.of_components_eq (f : X\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082) :\n  biprod.of_components (biprod.inl \u226b f \u226b biprod.fst) (biprod.inl \u226b f \u226b biprod.snd)\n    (biprod.inr \u226b f \u226b biprod.fst) (biprod.inr \u226b f \u226b 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\u2081 X\u2082 Y\u2081 Y\u2082 Z\u2081 Z\u2082 : C}\n  (f\u2081\u2081 : X\u2081 \u27f6 Y\u2081) (f\u2081\u2082 : X\u2081 \u27f6 Y\u2082) (f\u2082\u2081 : X\u2082 \u27f6 Y\u2081) (f\u2082\u2082 : X\u2082 \u27f6 Y\u2082)\n  (g\u2081\u2081 : Y\u2081 \u27f6 Z\u2081) (g\u2081\u2082 : Y\u2081 \u27f6 Z\u2082) (g\u2082\u2081 : Y\u2082 \u27f6 Z\u2081) (g\u2082\u2082 : Y\u2082 \u27f6 Z\u2082) :\n  biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082 \u226b biprod.of_components g\u2081\u2081 g\u2081\u2082 g\u2082\u2081 g\u2082\u2082 =\n    biprod.of_components\n      (f\u2081\u2081 \u226b g\u2081\u2081 + f\u2081\u2082 \u226b g\u2082\u2081) (f\u2081\u2081 \u226b g\u2081\u2082 + f\u2081\u2082 \u226b g\u2082\u2082)\n      (f\u2082\u2081 \u226b g\u2081\u2081 + f\u2082\u2082 \u226b g\u2082\u2081) (f\u2082\u2081 \u226b g\u2081\u2082 + f\u2082\u2082 \u226b g\u2082\u2082) :=\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\u2081 X\u2082 : C} (r : X\u2081 \u27f6 X\u2082) : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082 :=\n{ hom := biprod.of_components (\ud835\udfd9 _) r 0 (\ud835\udfd9 _),\n  inv := biprod.of_components (\ud835\udfd9 _) (-r) 0 (\ud835\udfd9 _), }\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\u2081 X\u2082 : C} (r : X\u2082 \u27f6 X\u2081) : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082 :=\n{ hom := biprod.of_components (\ud835\udfd9 _) 0 r (\ud835\udfd9 _),\n  inv := biprod.of_components (\ud835\udfd9 _) 0 (-r) (\ud835\udfd9 _), }\n\n/--\nIf `f` is a morphism `X\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082` whose `X\u2081 \u27f6 Y\u2081` entry is an isomorphism,\nthen we can construct isomorphisms `L : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082` and `R : Y\u2081 \u229e Y\u2082 \u2245 Y\u2081 \u229e Y\u2082`\nso that `L.hom \u226b g \u226b R.hom` is diagonal (with `X\u2081 \u27f6 Y\u2081` 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\u2081\u2081] :\n  \u03a3' (L : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082) (R : Y\u2081 \u229e Y\u2082 \u2245 Y\u2081 \u229e Y\u2082) (g\u2082\u2082 : X\u2082 \u27f6 Y\u2082),\n    L.hom \u226b (biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082) \u226b R.hom = biprod.map f\u2081\u2081 g\u2082\u2082 :=\n\u27e8biprod.unipotent_lower (-(f\u2082\u2081 \u226b inv f\u2081\u2081)),\n biprod.unipotent_upper (-(inv f\u2081\u2081 \u226b f\u2081\u2082)),\n f\u2082\u2082 - f\u2082\u2081 \u226b (inv f\u2081\u2081) \u226b f\u2081\u2082,\n by ext; simp; abel\u27e9\n\n/--\nIf `f` is a morphism `X\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082` whose `X\u2081 \u27f6 Y\u2081` entry is an isomorphism,\nthen we can construct isomorphisms `L : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082` and `R : Y\u2081 \u229e Y\u2082 \u2245 Y\u2081 \u229e Y\u2082`\nso that `L.hom \u226b g \u226b R.hom` is diagonal (with `X\u2081 \u27f6 Y\u2081` component still `f`),\nvia Gaussian elimination.\n-/\ndef biprod.gaussian (f : X\u2081 \u229e X\u2082 \u27f6 Y\u2081 \u229e Y\u2082) [is_iso (biprod.inl \u226b f \u226b biprod.fst)] :\n  \u03a3' (L : X\u2081 \u229e X\u2082 \u2245 X\u2081 \u229e X\u2082) (R : Y\u2081 \u229e Y\u2082 \u2245 Y\u2081 \u229e Y\u2082) (g\u2082\u2082 : X\u2082 \u27f6 Y\u2082),\n    L.hom \u226b f \u226b R.hom = biprod.map (biprod.inl \u226b f \u226b biprod.fst) g\u2082\u2082 :=\nbegin\n  let := biprod.gaussian'\n    (biprod.inl \u226b f \u226b biprod.fst) (biprod.inl \u226b f \u226b biprod.snd)\n    (biprod.inr \u226b f \u226b biprod.fst) (biprod.inr \u226b f \u226b biprod.snd),\n  simpa [biprod.of_components_eq],\nend\n\n/--\nIf `X\u2081 \u229e X\u2082 \u2245 Y\u2081 \u229e Y\u2082` via a two-by-two matrix whose `X\u2081 \u27f6 Y\u2081` entry is an isomorphism,\nthen we can construct an isomorphism `X\u2082 \u2245 Y\u2082`, via Gaussian elimination.\n-/\ndef biprod.iso_elim' [is_iso f\u2081\u2081] [is_iso (biprod.of_components f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082)] : X\u2082 \u2245 Y\u2082 :=\nbegin\n  obtain \u27e8L, R, g, w\u27e9 := biprod.gaussian' f\u2081\u2081 f\u2081\u2082 f\u2082\u2081 f\u2082\u2082,\n  letI : is_iso (biprod.map f\u2081\u2081 g) := by { rw \u2190w, apply_instance, },\n  letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f\u2081\u2081 g),\n  exact as_iso g,\nend\n\n/--\nIf `f` is an isomorphism `X\u2081 \u229e X\u2082 \u2245 Y\u2081 \u229e Y\u2082` whose `X\u2081 \u27f6 Y\u2081` entry is an isomorphism,\nthen we can construct an isomorphism `X\u2082 \u2245 Y\u2082`, via Gaussian elimination.\n-/\ndef biprod.iso_elim (f : X\u2081 \u229e X\u2082 \u2245 Y\u2081 \u229e Y\u2082) [is_iso (biprod.inl \u226b f.hom \u226b biprod.fst)] : X\u2082 \u2245 Y\u2082 :=\nbegin\n  letI : is_iso (biprod.of_components\n       (biprod.inl \u226b f.hom \u226b biprod.fst)\n       (biprod.inl \u226b f.hom \u226b biprod.snd)\n       (biprod.inr \u226b f.hom \u226b biprod.fst)\n       (biprod.inr \u226b f.hom \u226b biprod.snd)) :=\n  by { simp only [biprod.of_components_eq], apply_instance, },\n  exact biprod.iso_elim'\n    (biprod.inl \u226b f.hom \u226b biprod.fst)\n    (biprod.inl \u226b f.hom \u226b biprod.snd)\n    (biprod.inr \u226b f.hom \u226b biprod.fst)\n    (biprod.inr \u226b f.hom \u226b biprod.snd)\nend\n\nlemma biprod.column_nonzero_of_iso {W X Y Z : C}\n  (f : W \u229e X \u27f6 Y \u229e Z) [is_iso f] :\n  \ud835\udfd9 W = 0 \u2228 biprod.inl \u226b f \u226b biprod.fst \u2260 0 \u2228 biprod.inl \u226b f \u226b biprod.snd \u2260 0 :=\nbegin\n  by_contra' h,\n  rcases h with \u27e8nz, a\u2081, a\u2082\u27e9,\n  set x := biprod.inl \u226b f \u226b inv f \u226b biprod.fst,\n  have h\u2081 : x = \ud835\udfd9 W, by simp [x],\n  have h\u2080 : x = 0,\n  { dsimp [x],\n    rw [\u2190category.id_comp (inv f), category.assoc, \u2190biprod.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\u2082, },\n    simp only [zero_comp, add_zero],\n    conv_lhs { slice 1 3, rw a\u2081, },\n    simp only [zero_comp], },\n  exact nz (h\u2081.symm.trans h\u2080),\nend\n\nend\n\nlemma biproduct.column_nonzero_of_iso'\n  {\u03c3 \u03c4 : Type} [finite \u03c4]\n  {S : \u03c3 \u2192 C} [has_biproduct S] {T : \u03c4 \u2192 C} [has_biproduct T]\n  (s : \u03c3) (f : \u2a01 S \u27f6 \u2a01 T) [is_iso f] :\n  (\u2200 t : \u03c4, biproduct.\u03b9 S s \u226b f \u226b biproduct.\u03c0 T t = 0) \u2192 \ud835\udfd9 (S s) = 0 :=\nbegin\n  casesI nonempty_fintype \u03c4,\n  intro z,\n  set x := biproduct.\u03b9 S s \u226b f \u226b inv f \u226b biproduct.\u03c0 S s,\n  have h\u2081 : x = \ud835\udfd9 (S s), by simp [x],\n  have h\u2080 : x = 0,\n  { dsimp [x],\n    rw [\u2190category.id_comp (inv f), category.assoc, \u2190biproduct.total],\n    simp only [comp_sum_assoc],\n    conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], },\n    simp, },\n  exact h\u2081.symm.trans h\u2080,\nend\n\n/--\nIf `f : \u2a01 S \u27f6 \u2a01 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  {\u03c3 \u03c4 : Type} [fintype \u03c4]\n  {S : \u03c3 \u2192 C} [has_biproduct S] {T : \u03c4 \u2192 C} [has_biproduct T]\n  (s : \u03c3) (nz : \ud835\udfd9 (S s) \u2260 0)\n  (f : \u2a01 S \u27f6 \u2a01 T) [is_iso f] :\n  trunc (\u03a3' t : \u03c4, biproduct.\u03b9 S s \u226b f \u226b biproduct.\u03c0 T t \u2260 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 \u2964 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 \u2192 C} [preserves_biproduct f F] :\n  preserves_limit (discrete.functor f) F :=\n{ preserves := \u03bb 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 := \u03bb 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 \u2192 C} [preserves_limit (discrete.functor f) F] :\n  preserves_biproduct f F :=\n{ preserves := \u03bb 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 \u2192 C} [has_biproduct f]\n  [has_biproduct (F.obj \u2218 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 \u226b\n    biproduct_comparison F f \u226b (biproduct.iso_product _).hom,\n  { ext, convert pi_comparison_comp_\u03c0 F f j.as; simp [\u2190 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 \u2192 C} [has_biproduct f]\n  [has_biproduct (F.obj \u2218 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 := \u03bb 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 \u2192 C} [preserves_biproduct f F] :\n  preserves_colimit (discrete.functor f) F :=\n{ preserves := \u03bb 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 := \u03bb 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 \u2192 C}\n  [preserves_colimit (discrete.functor f) F] : preserves_biproduct f F :=\n{ preserves := \u03bb 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 := \u03bb 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 := \u03bb 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 _) (\u03bb j, by { rcases j with \u27e8\u27e8\u27e9\u27e9, 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 := \u03bb 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 := \u03bb 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 _) (\u03bb j, by { rcases j with \u27e8\u27e8\u27e9\u27e9, 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 \u226b\n    biprod_comparison F X Y \u226b (biprod.iso_prod _ _).hom := by { ext; simp [\u2190 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 := \u03bb 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 := \u03bb 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 _) (\u03bb j, by { rcases j with \u27e8\u27e8\u27e9\u27e9, 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 := \u03bb 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 := \u03bb 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 _) (\u03bb j, by { rcases j with \u27e8\u27e8\u27e9\u27e9, 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 := \u03bb 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 Cla.Dsl\n\n\n\n/-! # An example of using `Cla` -/\n\nnamespace Cla.Example\n\n\n\nstructure Conf where\n  verb : Nat\n  inputs : List String\n  output : Option String\nderiving Repr, Inhabited\n\n\n\ndef Conf.default : Conf where\n  verb := 1\n  inputs := []\n  output := none\n\nsection Conf\n  variable\n    (self : Conf)\n\n  def Conf.verbDo\n    (action : Nat \u2192 Nat)\n  : Conf := {\n    self with\n      verb := action self.verb\n  }\n\n  def Conf.addInputs\n    (inputs : List String)\n  : Conf := {\n    self with\n      inputs := self.inputs ++ inputs\n  }\n\n  def Conf.addInput\n    (input : String)\n  : Conf :=\n    self.addInputs [input]\n\n  def Conf.revInputs : Conf := {\n    self with inputs := self.inputs.reverse\n  }\nend Conf\n\n\n\nsection Parse\n  variable\n    (self : Conf)\n\n  def Conf.clap.short\n  : Char \u2192 IParseM Conf\n    | 'v' =>\n      self.verbDo (\u00b7 + 1)\n      |> pure\n    | flag =>\n      EStateM.throw s! \"unexpected flag `-{flag}`\"\n\n  def Conf.clap.long\n  : String \u2192 IParseM Conf\n    | \"verb\"\n    | \"verbose\" =>\n      do\n        let arg \u2190\n          Parse.nextFlagArg\n        if let some verb := arg.toNat? then\n          self.verbDo (\ud835\udd42 verb)\n          |> pure\n        else\n          EStateM.throw s! \"expected natural, got `{arg}`\"\n    | \"input\" =>\n      do\n        let arg \u2190\n          Parse.nextFlagArg\n        self.addInput arg\n        |> pure\n    | \"inputs\" =>\n      do\n        Parse.foldFlagArgs\n          (min := 1)\n          (max := none)\n          (fold := Conf.addInput)\n          (init := self)\n    | flag =>\n      EStateM.throw s! \"unexpected flag `--{flag}`\"\n\n  def Conf.clap.val\n  : String \u2192 Nat \u2192 IParseM Conf\n    | output, 0 =>\n      { self with output := output }\n      |> pure\n    | spurious, _ =>\n      EStateM.throw\n        s! \"already have one value (`{self.output}`), value `{spurious}` is unexpected\"\n\n  def Conf.clap\n  : EParseM Parse.Err Conf :=\n    do\n      let conf \u2190\n        Parse.loopDo\n          clap.long\n          clap.short\n          clap.val\n          (fun _ conf => conf)\n          Conf.default\n      if conf.output.isNone then\n        Parse.Err.mk\n          none\n          s! \"no output file was provided, expected exactly one\"\n        |> EStateM.throw\n      else if conf.inputs.isEmpty then\n        Parse.Err.mk\n          none\n          s! \"no input file was provided, expected at least one\"\n        |> EStateM.throw\n      else\n        conf.revInputs\n        |> pure\nend Parse\n\n\n\nnamespace Tests\n\n  def test\n    (args : String)\n  : String :=\n    let parser :=\n      Parse.mk args.splitOn\n    match EStateM.run Conf.clap parser with\n    | .ok conf _ =>\n      s! \"okay: {reprPrec conf 1}\"\n    | .error err _ =>\n      s! \"error: {err}\"\n\n  def test\u2081 :=\n    test \"--input input\u2081 -v -v --input input\u2082 output\"\n  #eval test\u2081\n\n  def test\u2082 :=\n    test \"--input input\u2081 -v -v --input input\u2082 output --verbose 27\"\n  #eval test\u2082\n\n  def test\u2083 :=\n    test \"--input input\u2081 -v -v --input input\u2082 output --verbose 27 -v -v\"\n  #eval test\u2083\n\n  def test\u2084 :=\n    test \"--inputs input\u2081 input\u2082 -- output\"\n  #eval test\u2084\n\n\n\n  def error\u2080 :=\n    test \"output\"\n  #eval error\u2080\n\n  def error\u2081 :=\n    test \"output\u2081 output\u2082\"\n  #eval error\u2081\n\n  def error\u2082 :=\n    test \"--input input\u2081 output\u2081 output\u2082\"\n  #eval error\u2082\n\n  def error\u2083 :=\n    test \"--inputs input\u2081 input\u2082 output\"\n  #eval error\u2083\n\n\nend Tests\n\n\n\nnamespace Conf.flag\n  def v : Flag Conf :=\n    Flag.withDesc\n      \"increases verbosity\"\n    |>.withShort 'v'\n    |>.effect (\n      fun () =>\n        do\n          let conf \u2190 get\n          conf.verbDo (fun v => v + 1)\n          |> set\n    )\n\n  def q : Flag Conf :=\n    Flag.withDesc\n      \"decreases verbosity\"\n    |>.withShort 'q'\n    |>.effect (\n      fun () =>\n        do\n          let conf \u2190 get\n          conf.verbDo (fun v => v - 1)\n          |> set\n    )\n\n  def verb : Flag Conf :=\n    Flag.withDesc\n      s! \"sets the verbosity (default {Conf.default.verb})\"\n    |>.withLong \"verb\"\n    |>.argsTake 1\n    |>.effect (\n      fun verb =>\n        do\n          if let some verb := verb.toNat?\n          then\n            let conf \u2190 get\n            conf.verbDo (\ud835\udd42 verb)\n            |> set\n    )\n\n  def quiet : Flag Conf :=\n    Flag.withDesc\n      \"sets verbosity to zero\"\n    |>.withLong \"quiet\"\n    |>.effect (\n      fun () =>\n        do\n          let conf \u2190 get\n          conf.verbDo (\ud835\udd42 0)\n          |> set\n    )\n\n  def inputs : Flag Conf :=\n    Flag.withDesc\n      \"inputs, requires two values or more\"\n    |>.withLong \"inputs\"\n    |>.argsAtLeast 2\n    |>.effect (\n      fun (h\u2081, h\u2082, tail) =>\n        do\n          let conf \u2190 get\n          conf\n          |>.addInputs [h\u2081, h\u2082]\n          |>.addInputs tail\n          |> set\n    )\nend Conf.flag\n\nprotected def Conf.com : Com Conf :=\n  let com? :=\n    Com.mkBuilder\n      Conf\n      \"myProgram\"\n    |>.withFlags [\n      flag.v,\n      flag.q,\n      flag.verb,\n      flag.quiet,\n      flag.inputs\n    ]\n    |>.build\n  match com? with\n  | .ok com => com\n  | .error err =>\n    panic! s! \"Failed to build command: {err}\"\n\ndef Conf.parse : List String \u2192 Except Parse.Err Conf :=\n  Parse.run Conf.com Conf.default\n\n\n#eval Conf.parse [\n  \"--verb\", \"662\",\n  \"-vvvv\",\n  \"--inputs\", \"in\u2081\", \"in\u2082\", \"in\u2083\", \"in\u2084\"\n]\n\nprotected def Conf.com' : Except String <| Com Conf :=\n  open Cla.Dsl in\n  clap! my_app (conf : Conf) where\n  | -v\n    \"increases verbosity\"\n    := pure (conf.verbDo <| Nat.add 1)\n  | -q\n    \"decreases verbosity\"\n    := pure (conf.verbDo <| Nat.sub 1)\n  | \u2500verb\n    \"sets the verbosity\"\n    taking (v : String) :=\n      if let some v := String.toNat? v then\n        .ok <| conf.verbDo <| \ud835\udd42 v\n      else\n        .error s! \"expected natural number, got {v}\"\n  | \u2500inputs\n    \"input files\"\n    taking (in\u2081 in\u2082 : String) (inTail : List String \u2264 3) :=\n      conf.addInputs (in\u2081 :: in\u2082 :: inTail)\n      |> .ok\n", "meta": {"author": "AdrienChampion", "repo": "experimentalean4", "sha": "5071a8b007029f61b2e996d9ac89d90999603fcc", "save_path": "github-repos/lean/AdrienChampion-experimentalean4", "path": "github-repos/lean/AdrienChampion-experimentalean4/experimentalean4-5071a8b007029f61b2e996d9ac89d90999603fcc/cla/Cla/Example.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421495978593415, "lm_q2_score": 0.05921024534589487, "lm_q1q2_score": 0.017420539953357753}}
{"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 \u2124} {i : \u2124}\n  (\u03b3 \u03b3\u2082 : cochain K L i) (n : \u2124) (\u03b3' \u03b3'\u2082: cochain K (L\u27e6n\u27e7) i)\n\ndef right_shift (j : \u2124) (hj : i = j + n) : cochain K (L\u27e6n\u27e7) j :=\ncochain.mk (\u03bb p q hpq, \u03b3.v p (p+i) rfl \u226b\n  (L.shift_functor_obj_X_iso n q (p+i) (by linarith)).inv)\n\nlemma right_shift_v (j : \u2124) (hj : i = j + n) (p q : \u2124) (hpq : q = p + j)\n  (p' : \u2124) (hp' : p' = p + i) :\n  (\u03b3.right_shift n j hj).v p q hpq = \u03b3.v p p' hp' \u226b\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 : \u2124) (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 : \u2124) (hj : i = j + n) (a : \u2124) :\n  (a \u2022 \u03b3).right_shift n j hj = a \u2022 \u03b3.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 : \u2124) (hj : i = j + n) :\n  (\u03b3 + \u03b3\u2082).right_shift n j hj = \u03b3.right_shift n j hj + \u03b3\u2082.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 : \u2124) (hj : j = i + n) : cochain K L j :=\ncochain.mk (\u03bb p q hpq, \u03b3'.v p (p+i) rfl \u226b\n  (L.shift_functor_obj_X_iso n (p+i) q (by linarith)).hom)\n\nlemma right_unshift_v (j : \u2124) (hj : j = i + n) (p q : \u2124) (hpq : q = p + j)\n  (p' : \u2124) (hp' : p' = p + i):\n  (\u03b3'.right_unshift j hj).v p q hpq = \u03b3'.v p p' hp' \u226b\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 : \u2124) (hj : j = i + n) :\n  (0 : cochain K (L\u27e6n\u27e7) i).right_unshift j hj = 0 :=\nby { dsimp [right_unshift], tidy, }\n\n@[simp]\nlemma right_unshift_smul (j : \u2124) (hj : j = i + n) (a : \u2124) :\n  (a \u2022 \u03b3').right_unshift j hj = a \u2022 \u03b3'.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 : \u2124) (hj : j = i + n) :\n  (\u03b3' + \u03b3'\u2082).right_unshift j hj = \u03b3'.right_unshift j hj + \u03b3'\u2082.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 : \u2124) (hj : j = i + n) :\n  (\u03b3'.right_unshift j hj).right_shift n i hj = \u03b3' :=\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 : \u2124) (hj : i = j + n) :\n  (\u03b3.right_shift n j hj).right_unshift i hj = \u03b3 :=\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 \u03b4_right_shift (i' j j' : \u2124) (hj : i = j + n) (hj' : i' = j' + n) :\n  \u03b4 j j' (\u03b3.right_shift n j hj) = \u03b5 n \u2022 (\u03b4 i i' \u03b3).right_shift n j' hj' :=\nbegin\n  by_cases h\u2081 : i+1 = i', swap,\n  { have h\u2082 : j+1 \u2260 j' := \u03bb h\u2083, by { exfalso, apply h\u2081, linarith, },\n    simp only [\u03b4_shape _ _ h\u2081, \u03b4_shape _ _ h\u2082, right_shift_zero, smul_zero], },\n  { have h\u2082 : j' = j+1 := by linarith,\n    substs h\u2081 h\u2082,\n    ext p q hpq,\n    simp only [\u03b4_v j _ rfl _ p q hpq (p+j) (p+1) (by linarith) rfl,\n      \u03b3.right_shift_v n j hj p (p+j) rfl (p+j+n) (by linarith),\n      \u03b3.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      \u03b4_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, \u2190 \u03b5_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 [\u03b5_eq_iff],\n      exact \u27e8-n, by linarith\u27e9, }, },\nend\n\nvariable {n}\n\nlemma \u03b4_right_unshift (i' j j' : \u2124) (hj : j = i + n) (hj' : j' = i' + n) :\n  \u03b4 j j' (\u03b3'.right_unshift j hj) = \u03b5 n \u2022 (\u03b4 i i' \u03b3').right_unshift j' hj' :=\nbegin\n  conv_rhs { rw \u2190 \u03b3'.right_unshift_shift j hj, },\n  rw [(\u03b3'.right_unshift j hj).\u03b4_right_shift n j' i i' hj hj',\n    right_unshift_smul, cochain.right_shift_unshift, smul_smul,\n    \u2190 \u03b5_add, \u03b5_even _ (even_add_self n), one_smul],\nend\n\n@[simps]\ndef right_shift_equiv (K L : cochain_complex C \u2124) (n i j : \u2124) (h : i = j + n) :\n  cochain K L i \u2243+ cochain K (L\u27e6n\u27e7) j :=\n{ to_fun := \u03bb \u03b3, \u03b3.right_shift n j h,\n  inv_fun := \u03bb \u03b3', \u03b3'.right_unshift i h,\n  left_inv := \u03bb \u03b3, \u03b3.right_shift_unshift _ _ _,\n  right_inv := \u03bb \u03b3', \u03b3'.right_unshift_shift _ _,\n  map_add' := \u03bb \u03b3\u2081 \u03b3\u2082, cochain.right_shift_add \u03b3\u2081 \u03b3\u2082 _ _ _, }\n\nend cochain\n\nnamespace cocycle\n\nvariables {K L : cochain_complex C \u2124} {i : \u2124}\n  (\u03b3 : cocycle K L i) (n : \u2124) (\u03b3' : cocycle K (L\u27e6n\u27e7) i)\n\n@[simps]\ndef right_shift (j : \u2124) (hj : i = j + n) : cocycle K (L\u27e6n\u27e7) j :=\n\u27e8(\u03b3 : cochain K L i).right_shift n j hj, begin\n  rw [cocycle.mem_iff j (j+1) rfl, cochain.\u03b4_right_shift _ n (i+1) j (j+1) hj (by linarith)],\n  simp only [subtype.val_eq_coe, \u03b4_eq_zero, cochain.right_shift_zero, smul_zero],\nend\u27e9\n\nvariable {n}\n\n@[simps]\ndef right_unshift (j : \u2124) (hj : j = i + n) : cocycle K L j :=\n\u27e8(\u03b3' : cochain K (L\u27e6n\u27e7) i).right_unshift j hj, begin\n  rw [cocycle.mem_iff j (j+1) rfl, cochain.\u03b4_right_unshift _ (i+1) j (j+1) hj (by linarith)],\n  simp only [subtype.val_eq_coe, \u03b4_eq_zero, cochain.right_unshift_zero, smul_zero],\nend\u27e9\n\n@[simps]\ndef right_shift_equiv (K L : cochain_complex C \u2124) (n i j : \u2124) (h : i = j + n) :\n  cocycle K L i \u2243+ cocycle K (L\u27e6n\u27e7) j :=\n{ to_fun := \u03bb \u03b3, right_shift \u03b3 n j h,\n  inv_fun := \u03bb \u03b3', right_unshift \u03b3' i h,\n  left_inv := \u03bb \u03b3, by { ext1, exact \u03b3.1.right_shift_unshift _ _ _, },\n  right_inv := \u03bb \u03b3', by { ext1, exact \u03b3'.1.right_unshift_shift _ _, },\n  map_add' := \u03bb \u03b3\u2081 \u03b3\u2082, by { ext1, exact cochain.right_shift_add \u03b3\u2081.1 \u03b3\u2082.1 _ _ _, }, }\n\nend cocycle\n\n@[simps]\ndef right_shift_iso (K L : cochain_complex C \u2124) (n : \u2124) :\n  (hom_complex K L)\u27e6n\u27e7 \u2245 hom_complex K (L\u27e6n\u27e7) :=\nhomological_complex.hom.iso_of_components\n  (\u03bb i, add_equiv.to_AddCommGroup_iso (cochain.right_shift_equiv K L n (i+n) i rfl))\n  (\u03bb i j hij, begin\n    ext1 \u03b3,\n    simp only [comp_apply],\n    dsimp [hom_complex, \u03b4_hom],\n    erw [\u03b3.\u03b4_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 \u2124} {i : \u2124}\n  (\u03b3 \u03b3\u2082 : cochain K L i) (n : \u2124) (\u03b3' \u03b3'\u2082: cochain (K\u27e6n\u27e7) L i)\n\ndef left_shift (j : \u2124) (hj : j = i + n) : cochain (K\u27e6n\u27e7) L j :=\ncochain.mk (\u03bb p q hpq,\n  \u03b5 (n*j + (n*(n-1)/2)) \u2022 (K.shift_functor_obj_X_iso n p (p+n) rfl).hom \u226b \u03b3.v (p+n) q (by { dsimp, linarith, }))\n\nlemma left_shift_v (j : \u2124) (hj : j = i + n) (p q : \u2124) (hpq : q = p + j)\n  (p' : \u2124) (hp' : p' = p + n) :\n  (\u03b3.left_shift n j hj).v p q hpq = \u03b5 (n*j + (n*(n-1)/2)) \u2022 (K.shift_functor_obj_X_iso n p p' hp').hom \u226b\n    \u03b3.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 : \u2124) (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 : \u2124) (hj : j = i + n) (a : \u2124) :\n  (a \u2022 \u03b3).left_shift n j hj = a \u2022 \u03b3.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    \u2190 mul_smul, mul_comm a],\nend\n\n@[simp]\nlemma left_shift_add (j : \u2124) (hj : j = i + n) :\n  (\u03b3 + \u03b3\u2082).left_shift n j hj = \u03b3.left_shift n j hj + \u03b3\u2082.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 : \u2124) (hj : i = j + n) : cochain K L j :=\ncochain.mk (\u03bb p q hpq,\n  \u03b5 (n*i + (n*(n-1)/2)) \u2022 (K.shift_functor_obj_X_iso n (p-n) p (by linarith)).inv \u226b\n    \u03b3'.v (p-n) q (by { change _ = _ - _ + _, linarith,}))\n\n\nlemma left_unshift_v (j : \u2124) (hj : i = j + n) (p q : \u2124) (hpq : q = p + j)\n  (p' : \u2124) (hp' : p' = p - n):\n  (\u03b3'.left_unshift j hj).v p q hpq =\n  \u03b5 (n*i + (n*(n-1)/2)) \u2022 (K.shift_functor_obj_X_iso n p' p (by rw [hp', sub_add_cancel])).inv \u226b\n    \u03b3'.v p' q (by rw [hpq, hp', hj, sub_add_add_cancel]) :=\nby { subst hp', refl, }\n\n@[simp]\nlemma left_unshift_zero (j : \u2124) (hj : i = j + n) :\n  (0 : cochain (K\u27e6n\u27e7) L i).left_unshift j hj = 0 :=\nby { dsimp [left_unshift], tidy, }\n\n@[simp]\nlemma left_unshift_smul (j : \u2124) (hj : i = j + n) (a : \u2124) :\n  (a \u2022 \u03b3').left_unshift j hj = a \u2022 \u03b3'.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    \u2190 mul_smul, mul_comm a],\nend\n\n@[simp]\nlemma left_unshift_add (j : \u2124) (hj : i = j + n) :\n  (\u03b3' + \u03b3'\u2082).left_unshift j hj = \u03b3'.left_unshift j hj + \u03b3'\u2082.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 : \u2124) (hj : i = j + n) :\n  (\u03b3'.left_unshift j hj).left_shift n i hj = \u03b3' :=\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    \u03b5_add, linear.comp_smul, iso.hom_inv_id_assoc, \u2190 mul_smul],\n  nth_rewrite 0 mul_comm (\u03b5 (n*i)),\n  rw \u2190 mul_assoc,\n  nth_rewrite 1 mul_assoc,\n  rw [\u2190 \u03b5_add, \u03b5_even _ (even_add_self _), mul_one],\n  rw [\u2190 \u03b5_add, \u03b5_even _ (even_add_self _), one_smul],\nend\n\nvariable (n)\n\n@[simp]\nlemma left_shift_unshift (j : \u2124) (hj : j = i + n) :\n  (\u03b3.left_shift n j hj).left_unshift i hj = \u03b3 :=\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, \u03b5_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, \u2190 mul_smul],\n  nth_rewrite 0 mul_comm (\u03b5 (n*j)),\n  rw \u2190 mul_assoc,\n  nth_rewrite 1 mul_assoc,\n  rw [\u2190 \u03b5_add, \u03b5_even _ (even_add_self _), mul_one],\n  rw [\u2190 \u03b5_add, \u03b5_even _ (even_add_self _), one_smul],\nend\n\n\nvariable (n)\n\nlemma \u03b4_left_shift (i' j j' : \u2124) (hj : j = i + n) (hj' : j' = i' + n) :\n  \u03b4 j j' (\u03b3.left_shift n j hj) = \u03b5 (n) \u2022 (\u03b4 i i' \u03b3).left_shift n j' hj' :=\nbegin\n  by_cases h\u2081 : i+1 = i', swap,\n  { have h\u2082 : j+1 \u2260 j' := \u03bb h\u2083, by { exfalso, apply h\u2081, linarith, },\n    simp only [\u03b4_shape _ _ h\u2081, \u03b4_shape _ _ h\u2082, left_shift_zero, smul_zero], },\n  { have h\u2082 : j' = j+1 := by linarith,\n    substs h\u2081 h\u2082,\n    ext p q hpq,\n    rw \u03b4_v j _ rfl _ p q hpq (p+j) (p+1) (by linarith) rfl,\n    rw \u03b3.left_shift_v n j hj p _ rfl _ rfl,\n    rw \u03b3.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 \u03b4_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, \u03b5_succ, linear.comp_smul, neg_smul, preadditive.comp_add,\n      preadditive.comp_neg, smul_add, zsmul_neg', add_right_inj, neg_inj, \u2190 mul_smul],\n    dsimp [iso.refl],\n    simp only [preadditive.zsmul_comp, \u2190 mul_smul],\n    erw [category.id_comp, category.id_comp, category.id_comp],\n    congr' 2,\n    { simp only [mul_add, \u03b5_add, mul_one, mul_comm _ (\u03b5 n)],\n      simp only [\u2190 mul_assoc, \u2190 \u03b5_add n n, \u03b5_even _ (even_add_self n)],\n      ring, },\n    { rw [hj],\n      simp only [\u03b5_add, neg_mul, mul_neg, neg_inj, mul_add],\n      ring_nf, }, },\nend\n\nvariable {n}\n\nlemma \u03b4_left_unshift (i' j j' : \u2124) (hj : i = j + n) (hj' : i' = j' + n) :\n  \u03b4 j j' (\u03b3'.left_unshift j hj) = \u03b5 n \u2022 (\u03b4 i i' \u03b3').left_unshift j' hj' :=\nbegin\n  conv_rhs { rw \u2190 \u03b3'.left_unshift_shift j hj, },\n  rw [(\u03b3'.left_unshift j hj).\u03b4_left_shift n j' i i' hj hj',\n    left_unshift_smul, cochain.left_shift_unshift, smul_smul,\n    \u2190 \u03b5_add, \u03b5_even _ (even_add_self n), one_smul],\nend\n\n@[simps]\ndef left_shift_equiv (K L : cochain_complex C \u2124) (n i j : \u2124) (h : j = i + n) :\n  cochain K L i \u2243+ cochain (K\u27e6n\u27e7) L j :=\n{ to_fun := \u03bb \u03b3, \u03b3.left_shift n j h,\n  inv_fun := \u03bb \u03b3', \u03b3'.left_unshift i h,\n  left_inv := \u03bb \u03b3, \u03b3.left_shift_unshift _ _ _,\n  right_inv := \u03bb \u03b3', \u03b3'.left_unshift_shift _ _,\n  map_add' := \u03bb \u03b3\u2081 \u03b3\u2082, cochain.left_shift_add \u03b3\u2081 \u03b3\u2082 _ _ _, }\n\nend cochain\n\nnamespace cocycle\n\nvariables {K L : cochain_complex C \u2124} {i : \u2124}\n  (\u03b3 : cocycle K L i) (n : \u2124) (\u03b3' : cocycle (K\u27e6n\u27e7) L i)\n\n@[simps]\ndef left_shift (j : \u2124) (hj : j = i + n) : cocycle (K\u27e6n\u27e7) L j :=\n\u27e8(\u03b3 : cochain K L i).left_shift n j hj, begin\n  rw [cocycle.mem_iff j (j+1) rfl, cochain.\u03b4_left_shift _ n (i+1) j (j+1) hj (by linarith)],\n  simp only [subtype.val_eq_coe, \u03b4_eq_zero, cochain.left_shift_zero, smul_zero],\nend\u27e9\n\nvariable {n}\n\n@[simps]\ndef left_unshift (j : \u2124) (hj : i = j + n) : cocycle K L j :=\n\u27e8(\u03b3' : cochain (K\u27e6n\u27e7) L i).left_unshift j hj, begin\n  rw [cocycle.mem_iff j (j+1) rfl, cochain.\u03b4_left_unshift _ (i+1) j (j+1) hj (by linarith)],\n  simp only [subtype.val_eq_coe, \u03b4_eq_zero, cochain.left_unshift_zero, smul_zero],\nend\u27e9\n\nvariables (K L)\n\n@[simps]\ndef left_shift_equiv (n i j : \u2124) (h : j = i + n) :\n  cocycle K L i \u2243+ cocycle (K\u27e6n\u27e7) L j :=\n{ to_fun := \u03bb \u03b3, left_shift \u03b3 n j h,\n  inv_fun := \u03bb \u03b3', left_unshift \u03b3' i h,\n  left_inv := \u03bb \u03b3, by { ext1, exact \u03b3.1.left_shift_unshift _ _ _, },\n  right_inv := \u03bb \u03b3', by { ext1, exact \u03b3'.1.left_unshift_shift _ _, },\n  map_add' := \u03bb \u03b3\u2081 \u03b3\u2082, by { ext1, exact cochain.left_shift_add \u03b3\u2081.1 \u03b3\u2082.1 _ _ _, }, }\n\nend cocycle\n\n@[simps]\ndef left_shift_iso (K L : cochain_complex C \u2124) (n : \u2124) :\n  (hom_complex K L) \u2245 (hom_complex (K\u27e6n\u27e7) L)\u27e6n\u27e7 :=\nhomological_complex.hom.iso_of_components\n  (\u03bb i, add_equiv.to_AddCommGroup_iso (cochain.left_shift_equiv K L n i (i+n) rfl))\n  (\u03bb i j hij, begin\n    ext1 \u03b3,\n    simp only [comp_apply],\n    dsimp [hom_complex, \u03b4_hom],\n    rw [\u03b3.\u03b4_left_shift n j (i+n) (j+n) rfl rfl, \u2190 mul_smul, \u2190 \u03b5_add,\n      \u03b5_even _ (even_add_self n), one_smul],\n  end)\n\ndef shift_iso (K L : cochain_complex C \u2124) (n : \u2124) :\n  hom_complex K L \u2245 hom_complex (K\u27e6n\u27e7) (L\u27e6n\u27e7) :=\nleft_shift_iso K L n \u226a\u226b right_shift_iso (K\u27e6n\u27e7) L n\n\nlemma \u03b4_shift_iso_hom_f {K L : cochain_complex C \u2124} (n i j : \u2124) (\u03b3 : cochain K L i) :\n  \u03b4 i j ((shift_iso K L n).hom.f i \u03b3) = (shift_iso K L n).hom.f j (\u03b4 i j \u03b3) :=\ncongr_hom (((shift_iso K L n).hom.comm i j)) \u03b3\n\nlemma even_mul_succ (n : \u2124) : even (n * (n+1)) :=\nbegin\n  by_cases hn : even n,\n  { obtain \u27e8k, rfl\u27e9 := hn,\n    exact \u27e8k * (2*k+1), by ring\u27e9, },\n  { rw \u2190 int.odd_iff_not_even at hn,\n    obtain \u27e8k, rfl\u27e9 := hn,\n    exact \u27e8(2*k+1)*(k+1), by ring\u27e9, },\nend\n\nlemma even_mul_pred (n : \u2124) : 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 : \u2124) : ((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 : \u2124) : ((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 : \u2124) : ((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 : \u2124) : ((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 : \u2124) : (n * (n+1))/2 = (n*(n-1))/2 + n :=\nbegin\n  by_cases hn : even n,\n  { obtain \u27e8k, rfl\u27e9 := hn,\n    rw [mul_pred_div_two_of_even, mul_succ_div_two_of_even],\n    ring, },\n  { rw \u2190 int.odd_iff_not_even at hn,\n    obtain \u27e8k, rfl\u27e9 := 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 \u2124} (f : K \u27f6 L) (n : \u2124) :\n  ((shift_iso K L n).hom.f 0) (cochain.of_hom f) = \u03b5 ((n * (n+1))/2) \u2022 cochain.of_hom (f\u27e6n\u27e7') :=\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 : \u03b5 (n * n + n * (n - 1) / 2) = \u03b5 (( n * (n+1)/2)),\n  { simp only [mul_succ_div_two, \u03b5_add, mul_comm _ (\u03b5 n)],\n    congr' 1,\n    by_cases hn : even n,\n    { rw [\u03b5_even _ hn, \u03b5_even],\n      obtain \u27e8k, rfl\u27e9 := hn,\n      exact \u27e82*k*k, by ring\u27e9, },\n    { rw \u2190 int.odd_iff_not_even at hn,\n      rw [\u03b5_odd _ hn, \u03b5_odd],\n      obtain \u27e8k, rfl\u27e9 := hn,\n      exact \u27e82*k*k+2*k, by ring\u27e9, }, },\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 \u2124} {f\u2081 f\u2082 : K \u27f6 L} (h : homotopy f\u2081 f\u2082) (n : \u2124) :\n  homotopy (f\u2081\u27e6n\u27e7') (f\u2082\u27e6n\u27e7') :=\n(cochain_complex.hom_complex.equiv_homotopy _ _).symm begin\n  obtain \u27e8\u03b3, h\u03b3\u27e9 := (cochain_complex.hom_complex.equiv_homotopy _ _) h,\n  replace h\u03b3 := congr_arg ((shift_iso K L n).hom.f 0) h\u03b3.symm,\n  simp only [map_add, shift_iso_hom_f_of_hom, \u2190 \u03b4_shift_iso_hom_f] at h\u03b3,\n  refine \u27e8\u03b5 ((n*(n+1)/2)) \u2022 (shift_iso K L n).hom.f (-1) \u03b3, _\u27e9,\n  simp only [\u03b4_zsmul, eq_sub_of_add_eq h\u03b3, zsmul_sub, \u2190 mul_smul, \u2190 \u03b5_add,\n    \u03b5_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 \u2124)) \u2124 :=\nquotient.shift (\u03bb n K L f\u2081 f\u2082, by { rintro \u27e8h\u27e9, exact \u27e8h.shift n\u27e9, })\n\nlemma quotient_map_shift {K L : cochain_complex C \u2124} (\u03c6 : K \u27f6 L) (n : \u2124) :\n  (homotopy_category.quotient _ _).map (\u03c6\u27e6n\u27e7') = ((homotopy_category.quotient _ _).map \u03c6)\u27e6n\u27e7' := 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 \u03b1 in the congruence generated from `f: \u03a0 {\u03b1 : Type} \u03b1 \u2192 \u03b1`.\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: \u03a0 {\u03b1 : Type}, \u03b1 \u2192 \u03b1`.\n- `cast`: corresponds to arguments that are subsingletons/propositions.\n  For example the `p` in the congruence generated from `f : \u03a0 (x y : \u2115) (p: x < y), \u2115`.\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 \u2192 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": "/-\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.data.list.basic\nimport init.data.char.basic\n\n/- In the VM, strings are implemented using a dynamic array and UTF-8 encoding.\n\n   TODO: we currently cannot mark string_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\nstructure string_imp :=\n(data : list char)\n\ndef string := string_imp\n\ndef list.as_string (s : list char) : string :=\n\u27e8s\u27e9\n\nnamespace string\n\ninstance : has_lt string :=\n\u27e8\u03bb s\u2081 s\u2082, s\u2081.data < s\u2082.data\u27e9\n\n/- Remark: this function has a VM builtin efficient implementation. -/\ninstance has_decidable_lt (s\u2081 s\u2082 : string) : decidable (s\u2081 < s\u2082) :=\nlist.has_decidable_lt s\u2081.data s\u2082.data\n\ninstance has_decidable_eq : decidable_eq string := \u03bb \u27e8x\u27e9 \u27e8y\u27e9,\nmatch list.has_dec_eq x y with\n| is_true p := is_true (congr_arg string_imp.mk p)\n| is_false p := is_false (\u03bb q, p (string_imp.mk.inj q))\nend\n\ndef empty : string :=\n\u27e8[]\u27e9\n\ndef length : string \u2192 nat\n| \u27e8s\u27e9  := s.length\n\n/- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\ndef push : string \u2192 char \u2192 string\n| \u27e8s\u27e9 c := \u27e8s ++ [c]\u27e9\n\n/- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\ndef append : string \u2192 string \u2192 string\n| \u27e8a\u27e9 \u27e8b\u27e9 := \u27e8a ++ b\u27e9\n\n/- O(n) in the VM, where n is the length of the string -/\ndef to_list : string \u2192 list char\n| \u27e8s\u27e9 := s\n\ndef fold {\u03b1} (a : \u03b1) (f : \u03b1 \u2192 char \u2192 \u03b1) (s : string) : \u03b1 :=\ns.to_list.foldl f a\n\n/- In the VM, the string iterator is implemented as a pointer to the string being iterated + index.\n\n   TODO: we currently cannot mark interator_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\nstructure iterator_imp :=\n(fst : list char) (snd : list char)\n\ndef iterator := iterator_imp\n\ndef mk_iterator : string \u2192 iterator\n| \u27e8s\u27e9 := \u27e8[], s\u27e9\n\nnamespace iterator\ndef curr : iterator \u2192 char\n| \u27e8p, c::n\u27e9 := c\n| _         := default\n\n/- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time\n   if it is. -/\ndef set_curr : iterator \u2192 char \u2192 iterator\n| \u27e8p, c::n\u27e9 c' := \u27e8p, c'::n\u27e9\n| it        c' := it\n\ndef next : iterator \u2192 iterator\n| \u27e8p, c::n\u27e9 := \u27e8c::p, n\u27e9\n| \u27e8p, []\u27e9   := \u27e8p, []\u27e9\n\ndef prev : iterator \u2192 iterator\n| \u27e8c::p, n\u27e9 := \u27e8p, c::n\u27e9\n| \u27e8[],   n\u27e9 := \u27e8[], n\u27e9\n\ndef has_next : iterator \u2192 bool\n| \u27e8p, []\u27e9 := ff\n| _       := tt\n\ndef has_prev : iterator \u2192 bool\n| \u27e8[], n\u27e9 := ff\n| _       := tt\n\ndef insert : iterator \u2192 string \u2192 iterator\n| \u27e8p, n\u27e9 \u27e8s\u27e9 := \u27e8p, s++n\u27e9\n\ndef remove : iterator \u2192 nat \u2192 iterator\n| \u27e8p, n\u27e9 m := \u27e8p, n.drop m\u27e9\n\n/- In the VM, `to_string` is a constant time operation. -/\ndef to_string : iterator \u2192 string\n| \u27e8p, n\u27e9 := \u27e8p.reverse ++ n\u27e9\n\ndef to_end : iterator \u2192 iterator\n| \u27e8p, n\u27e9 := \u27e8n.reverse ++ p, []\u27e9\n\ndef next_to_string : iterator \u2192 string\n| \u27e8p, n\u27e9 := \u27e8n\u27e9\n\ndef prev_to_string : iterator \u2192 string\n| \u27e8p, n\u27e9 := \u27e8p.reverse\u27e9\n\nprotected def extract_core : list char \u2192 list char \u2192 option (list char)\n| []       cs  := none\n| (c::cs\u2081) cs\u2082 :=\n  if cs\u2081 = cs\u2082 then some [c] else\n  match extract_core cs\u2081 cs\u2082 with\n  | none   := none\n  | some r := some (c::r)\n  end\n\ndef extract : iterator \u2192 iterator \u2192 option string\n| \u27e8p\u2081, n\u2081\u27e9 \u27e8p\u2082, n\u2082\u27e9 :=\n  if p\u2081.reverse ++ n\u2081 \u2260 p\u2082.reverse ++ n\u2082 then none\n  else if n\u2081 = n\u2082 then some \"\"\n  else match iterator.extract_core n\u2081 n\u2082 with\n       | none := none\n       | some r := some \u27e8r\u27e9\n       end\n\nend iterator\nend string\n\n/- The following definitions do not have builtin support in the VM -/\n\ninstance : inhabited string :=\n\u27e8string.empty\u27e9\n\ninstance : has_sizeof string :=\n\u27e8string.length\u27e9\n\ninstance : has_append string :=\n\u27e8string.append\u27e9\n\nnamespace string\ndef str : string \u2192 char \u2192 string := push\n\ndef is_empty (s : string) : bool :=\nto_bool (s.length = 0)\n\ndef front (s : string) : char :=\ns.mk_iterator.curr\n\ndef back (s : string) : char :=\ns.mk_iterator.to_end.prev.curr\n\ndef join (l : list string) : string :=\nl.foldl (\u03bb r s, r ++ s) \"\"\n\ndef singleton (c : char) : string :=\nempty.push c\n\ndef intercalate (s : string) (ss : list string) : string :=\n(list.intercalate s.to_list (ss.map to_list)).as_string\n\nnamespace iterator\ndef nextn : iterator \u2192 nat \u2192 iterator\n| it 0     := it\n| it (i+1) := nextn it.next i\n\ndef prevn : iterator \u2192 nat \u2192 iterator\n| it 0     := it\n| it (i+1) := prevn it.prev i\nend iterator\n\ndef pop_back (s : string) : string :=\ns.mk_iterator.to_end.prev.prev_to_string\n\ndef popn_back (s : string) (n : nat) : string :=\n(s.mk_iterator.to_end.prevn n).prev_to_string\n\ndef backn (s : string) (n : nat) : string :=\n(s.mk_iterator.to_end.prevn n).next_to_string\n\nend string\n\nprotected def char.to_string (c : char) : string :=\nstring.singleton c\n\nprivate def to_nat_core : string.iterator \u2192 nat \u2192 nat \u2192 nat\n| it      0     r := r\n| it      (i+1) r :=\n  let c := it.curr in\n  let r := r*10 + c.to_nat - '0'.to_nat in\n  to_nat_core it.next i r\n\ndef string.to_nat (s : string) : nat :=\nto_nat_core s.mk_iterator s.length 0\n\nnamespace string\n\nprivate lemma nil_ne_append_singleton : \u2200 (c : char) (l : list char), [] \u2260 l ++ [c]\n| c []     := \u03bb h, list.no_confusion h\n| c (d::l) := \u03bb h, list.no_confusion h\n\nlemma empty_ne_str : \u2200 (c : char) (s : string), empty \u2260 str s c\n| c \u27e8l\u27e9 :=\n  \u03bb h : string_imp.mk [] = string_imp.mk (l ++ [c]),\n    string_imp.no_confusion h $ \u03bb h, nil_ne_append_singleton _ _ h\n\nlemma str_ne_empty (c : char) (s : string) : str s c \u2260 empty :=\n(empty_ne_str c s).symm\n\nprivate lemma str_ne_str_left_aux : \u2200 {c\u2081 c\u2082 : char} (l\u2081 l\u2082 : list char), c\u2081 \u2260 c\u2082 \u2192 l\u2081 ++ [c\u2081] \u2260 l\u2082 ++ [c\u2082]\n| c\u2081 c\u2082 []       [] h\u2081 h\u2082 := list.no_confusion h\u2082 (\u03bb h _, absurd h h\u2081)\n| c\u2081 c\u2082 (d\u2081::l\u2081) [] h\u2081 h\u2082 :=\n  have d\u2081 :: (l\u2081 ++ [c\u2081]) = [c\u2082], from h\u2082,\n  have l\u2081 ++ [c\u2081] = [], from list.no_confusion this (\u03bb _ h, h),\n  absurd this.symm (nil_ne_append_singleton _ _)\n| c\u2081 c\u2082 [] (d\u2082::l\u2082) h\u2081 h\u2082 :=\n  have [c\u2081] = d\u2082 :: (l\u2082 ++ [c\u2082]), from h\u2082,\n  have []   = l\u2082 ++ [c\u2082], from list.no_confusion this (\u03bb _ h, h),\n  absurd this (nil_ne_append_singleton _ _)\n| c\u2081 c\u2082 (d\u2081::l\u2081) (d\u2082::l\u2082) h\u2081 h\u2082 :=\n  have d\u2081 :: (l\u2081 ++ [c\u2081]) = d\u2082 :: (l\u2082 ++ [c\u2082]), from h\u2082,\n  have l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082], from list.no_confusion this (\u03bb _ h, h),\n  absurd this (str_ne_str_left_aux l\u2081 l\u2082 h\u2081)\n\n\n\nprivate lemma str_ne_str_right_aux : \u2200 (c\u2081 c\u2082 : char) {l\u2081 l\u2082 : list char}, l\u2081 \u2260 l\u2082 \u2192 l\u2081 ++ [c\u2081] \u2260 l\u2082 ++ [c\u2082]\n| c\u2081 c\u2082 []       [] h\u2081 h\u2082 := absurd rfl h\u2081\n| c\u2081 c\u2082 (d\u2081::l\u2081) [] h\u2081 h\u2082 :=\n  have d\u2081 :: (l\u2081 ++ [c\u2081]) = [c\u2082], from h\u2082,\n  have l\u2081 ++ [c\u2081] = [], from list.no_confusion this (\u03bb _ h, h),\n  absurd this.symm (nil_ne_append_singleton _ _)\n| c\u2081 c\u2082 [] (d\u2082::l\u2082) h\u2081 h\u2082 :=\n  have [c\u2081] = d\u2082 :: (l\u2082 ++ [c\u2082]), from h\u2082,\n  have []   = l\u2082 ++ [c\u2082], from list.no_confusion this (\u03bb _ h, h),\n  absurd this (nil_ne_append_singleton _ _)\n| c\u2081 c\u2082 (d\u2081::l\u2081) (d\u2082::l\u2082) h\u2081 h\u2082 :=\n  have aux\u2081 : d\u2081 :: (l\u2081 ++ [c\u2081]) = d\u2082 :: (l\u2082 ++ [c\u2082]), from h\u2082,\n  have d\u2081 = d\u2082, from list.no_confusion aux\u2081 (\u03bb h _, h),\n  have aux\u2082 : l\u2081 \u2260 l\u2082, from \u03bb h,\n    have d\u2081 :: l\u2081 = d\u2082 :: l\u2082, from eq.subst h (eq.subst this rfl),\n    absurd this h\u2081,\n  have l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082], from list.no_confusion aux\u2081 (\u03bb _ h, h),\n  absurd this (str_ne_str_right_aux c\u2081 c\u2082 aux\u2082)\n\nlemma str_ne_str_right : \u2200 (c\u2081 c\u2082 : char) {s\u2081 s\u2082 : string}, s\u2081 \u2260 s\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082\n| c\u2081 c\u2082 (string_imp.mk l\u2081) (string_imp.mk l\u2082) h\u2081 h\u2082 :=\n  have aux : l\u2081 \u2260 l\u2082, from \u03bb h,\n    have string_imp.mk l\u2081 = string_imp.mk l\u2082, from eq.subst h rfl,\n    absurd this h\u2081,\n  have l\u2081 ++ [c\u2081] = l\u2082 ++ [c\u2082], from string_imp.no_confusion h\u2082 id,\n  absurd this (str_ne_str_right_aux c\u2081 c\u2082 aux)\n\nend string\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/string/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845759920814681, "lm_q2_score": 0.06097517787876877, "lm_q1q2_score": 0.01735207173719461}}
{"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 (\u03b9 : Type) (\u03b1 : Type u) : Type (max 1 u) :=\n(\u03c3 : Type)\n(valid : \u03c3 \u2192 Prop)\n(ready : \u03c3 \u2192 Prop)\n(next  : \u03a0 (x : \u03c3), valid x \u2192 \u03c3)\n(index : \u03a0 (x : \u03c3), valid x \u2192 \u03b9)\n(value : \u03a0 (x : \u03c3), ready x \u2192 \u03b1)\n\n@[ext]\nlemma Stream.ext {\u03b9 \u03b1} {s\u2081 s\u2082 : Stream \u03b9 \u03b1} (h\u2080 : s\u2081.\u03c3 = s\u2082.\u03c3)\n  (h\u2081 : \u2200 x y, x == y \u2192 (s\u2081.valid x \u2194 s\u2082.valid y)) (h\u2082 : \u2200 x y, x == y \u2192 (s\u2081.ready x \u2194 s\u2082.ready y)) (h\u2083 : \u2200 x y H\u2081 H\u2082, x == y \u2192 s\u2081.next x H\u2081 == s\u2082.next y H\u2082)\n  (h\u2084 : \u2200 x y H\u2081 H\u2082, x == y \u2192 s\u2081.index x H\u2081 == s\u2082.index y H\u2082) (h\u2085 : \u2200 x y H\u2081 H\u2082, x == y \u2192 s\u2081.value x H\u2081 == s\u2082.value y H\u2082) :\n  s\u2081 = s\u2082 :=\nbegin\n  cases s\u2081 with \u03c3\u2081 v\u2081 r\u2081 n\u2081 i\u2081 l\u2081, cases s\u2082 with \u03c3\u2082 v\u2082 r\u2082 n\u2082 i\u2082 l\u2082, dsimp only at *,\n  subst h\u2080, simp only [heq_iff_eq] at *,\n  obtain rfl : v\u2081 = v\u2082 := funext (\u03bb x, propext $ h\u2081 x x rfl), obtain rfl : r\u2081 = r\u2082 := funext (\u03bb x, propext $ h\u2082 x x rfl),\n  refine \u27e8rfl, rfl, rfl, _, _, _\u27e9; simp only [heq_iff_eq] at *; ext, { apply h\u2083 x x _ _ rfl; assumption, }, { apply h\u2084 x x _ _ rfl; assumption, },\n  { apply h\u2085 x x _ _ rfl; assumption, },\nend\n\nsection stream_defs\nvariables {\u03b9 : Type} {\u03b1 : Type*}\n\ndef Stream.eval\u2080 [has_zero \u03b1] (s : Stream \u03b9 \u03b1) (\u03c3\u2080 : s.\u03c3) (h\u2081 : s.valid \u03c3\u2080) : \u03b9 \u2192\u2080 \u03b1 :=\nif h\u2082 : s.ready \u03c3\u2080 then finsupp.single (s.index _ h\u2081) (s.value _ h\u2082) else 0\n\n@[simp]\nnoncomputable def Stream.eval_steps [add_zero_class \u03b1] (s : Stream \u03b9 \u03b1) :\n  \u2115 \u2192 s.\u03c3 \u2192 \u03b9 \u2192\u2080 \u03b1\n| 0 _ := 0\n| (n + 1) \u03c3\u2080 := if h\u2081 : s.valid \u03c3\u2080 then (Stream.eval_steps n (s.next \u03c3\u2080 h\u2081)) + (s.eval\u2080 _ h\u2081) else 0\n\nlemma Stream.eval_invalid [add_zero_class \u03b1] {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} (h : \u00acs.valid \u03c3\u2080) (n : \u2115) :\n  s.eval_steps n \u03c3\u2080 = 0 :=\nby cases n; simp [h]\n\ninductive Stream.bound_valid : \u2115 \u2192 \u2200 (s : Stream \u03b9 \u03b1), s.\u03c3 \u2192 Prop\n| start (n : \u2115) {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} : \u00acs.valid \u03c3\u2080 \u2192 Stream.bound_valid n s \u03c3\u2080\n| step {n : \u2115} {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} : \u2200 (h : s.valid \u03c3\u2080), Stream.bound_valid n s (s.next \u03c3\u2080 h) \u2192 Stream.bound_valid (n + 1) s \u03c3\u2080\n\nend stream_defs\n\n@[ext]\nstructure StreamExec (\u03b9 : Type) (\u03b1 : Type u) :=\n(stream : Stream \u03b9 \u03b1)\n(state : stream.\u03c3)\n(bound : \u2115)\n(bound_valid : stream.bound_valid bound state)\n\n\nuniverses v w\nvariables {\u03b9 \u03b9' \u03b9'' : Type} {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : 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 (\u03bb t, tactic.try t)) >> tactic.skip\n\n@[simps]\ndef Stream.bimap (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) : Stream \u03b9' \u03b2 :=\n{ s with value := \u03bb x hx, g (s.value x hx), index := \u03bb x hx, f (s.index x hx) }\n\n@[simp] lemma Stream.id_bimap (s : Stream \u03b9 \u03b1) : s.bimap id id = s :=\nby ext; solve_refl\n\n@[simp] lemma Stream.bimap_bimap (s : Stream \u03b9 \u03b1)\n  (f : \u03b9 \u2192 \u03b9') (f' : \u03b9' \u2192 \u03b9'') (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) :\n  (s.bimap f g).bimap f' h = s.bimap (f' \u2218 f) (h \u2218 g) :=\nby ext; solve_refl\n\nnotation f ` <$\u2081> `:1 s := s.bimap f id\nnotation g ` <$\u2082> `:1 s := s.bimap id g\n\n@[reducible, inline]\ndef StreamExec.valid (s : StreamExec \u03b9 \u03b1) : Prop := s.stream.valid s.state\n\n@[reducible, inline]\ndef StreamExec.ready (s : StreamExec \u03b9 \u03b1) : Prop := s.stream.ready s.state\n\nopen Stream.bound_valid (start step)\n\n@[simp] lemma Stream.bound_valid_zero {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} :\n  s.bound_valid 0 \u03c3\u2080 \u2194 \u00acs.valid \u03c3\u2080 :=\n\u27e8\u03bb h, by { cases h, assumption, }, \u03bb h, start _ h\u27e9\n\nlemma Stream.bound_valid.mono {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} {n m : \u2115} (h : s.bound_valid n \u03c3\u2080) (n_le : n \u2264 m) :\n  s.bound_valid m \u03c3\u2080 :=\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 \u03b1] {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} {n b : \u2115} (hb : s.bound_valid b \u03c3\u2080) (hn : b \u2264 n) :\n  s.eval_steps n \u03c3\u2080 = s.eval_steps b \u03c3\u2080 :=\nbegin\n  induction hb with _ _ _ _ n' \u03c3\u2080' 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 \u03b1] {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} {n b : \u2115} (hb : s.bound_valid b \u03c3\u2080) :\n  s.eval_steps (min b n) \u03c3\u2080 = s.eval_steps n \u03c3\u2080 :=\nby { rw min_def, split_ifs, { rw Stream.eval_ge_bound hb h, }, refl, }\n\nlemma Stream.valid.bound_pos {s : Stream \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} (h : s.valid \u03c3\u2080) :\n  \u00acs.bound_valid 0 \u03c3\u2080 := by simpa\n\nlemma Stream.eval\u2080_support [has_zero \u03b1] (s : Stream \u03b9 \u03b1) (x : s.\u03c3) (h : s.valid x) :\n  (s.eval\u2080 x h).support \u2286 {s.index x h} :=\nby { rw Stream.eval\u2080, split_ifs, { exact finsupp.support_single_subset, }, simp, }\n\n@[simp] lemma Stream.bound_valid_succ {s : Stream \u03b9 \u03b1} {n : \u2115} {\u03c3\u2080 : s.\u03c3} :\n  s.bound_valid (n + 1) \u03c3\u2080 \u2194 (\u2200 (h : s.valid \u03c3\u2080), s.bound_valid n (s.next \u03c3\u2080 h)) :=\n\u27e8\u03bb h, by { cases h, { intro, contradiction, }, intro, assumption, }, \u03bb h, if H : s.valid \u03c3\u2080 then step H (h H) else start _ H\u27e9\n\ndef StreamExec.eval [add_zero_class \u03b1] (s : StreamExec \u03b9 \u03b1) : \u03b9 \u2192\u2080 \u03b1 :=\ns.stream.eval_steps s.bound s.state\n\nsection defs\n\n@[simp] lemma imap_eval\u2080_spec [add_comm_monoid \u03b1] (f : \u03b9 \u2192 \u03b9') (s : Stream \u03b9 \u03b1) (\u03c3\u2080 : s.\u03c3) (h : s.valid \u03c3\u2080) :\n  (f <$\u2081> s).eval\u2080 _ h = (s.eval\u2080 _ h).map_domain f :=\nby { simp only [Stream.eval\u2080], split_ifs; simp, }\n\n@[simp] lemma imap_eval_steps_spec [add_comm_monoid \u03b1] (f : \u03b9 \u2192 \u03b9') (s : Stream \u03b9 \u03b1) (\u03c3\u2080 : s.\u03c3) (n : \u2115) :\n  (f <$\u2081> s).eval_steps n \u03c3\u2080 = (s.eval_steps n \u03c3\u2080).map_domain f :=\nbegin\n  induction n with n ih generalizing s \u03c3\u2080; simp,\n  split_ifs; simp [ih, finsupp.map_domain_add], refl,\nend\n\n@[simp] lemma bimap_bound_valid_iff (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) (s : Stream \u03b9 \u03b1) (n : \u2115) (x : s.\u03c3) :\n  (s.bimap f g).bound_valid n x \u2194 s.bound_valid n x :=\nby { induction n with n ih generalizing x; simp [*]; refl, }\n\ninstance bimap_\u03c3.has_zero {f : \u03b9 \u2192 \u03b9'} {g : \u03b1 \u2192 \u03b2} {s : Stream \u03b9 \u03b1} [z : has_zero s.\u03c3] :\nhas_zero (s.bimap f g).\u03c3 := z\n\n@[simp] lemma Stream.bifunctor_bimap_valid (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) :\n  (s.bimap f g).valid = s.valid := rfl\n\n@[simp] lemma Stream.bifunctor_bimap_valid_apply (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) (x : s.\u03c3) :\n  (s.bimap f g).valid x \u2194 s.valid x := iff.rfl\n\n@[simp] lemma Stream.bifunctor_bimap_ready (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) :\n  (s.bimap f g).ready = s.ready := rfl\n\n@[simp] lemma Stream.bifunctor_bimap_ready_apply (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) (x : s.\u03c3) :\n  (s.bimap f g).ready x \u2194 s.ready x := iff.rfl\n\n@[simps]\ndef StreamExec.bimap (s : StreamExec \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) : StreamExec \u03b9' \u03b2 :=\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 \u03b9 \u03b1) : s.bimap id id = s :=\nby ext; solve_refl\n\n@[simp] lemma StreamExec.bimap_bimap (s : StreamExec \u03b9 \u03b1)\n  (f : \u03b9 \u2192 \u03b9') (f' : \u03b9' \u2192 \u03b9'') (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) :\n  (s.bimap f g).bimap f' h = s.bimap (f' \u2218 f) (h \u2218 g) :=\nby ext; solve_refl\n\n@[simp] lemma imap_stream (s : StreamExec \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') :\n  (f <$\u2081> s).stream = (f <$\u2081> s.stream) := rfl\n\n@[simp] lemma imap_stream_eval [add_zero_class \u03b1] (s : StreamExec \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (n : \u2115) :\n  (f <$\u2081> s).stream.eval_steps n s.state = (f <$\u2081> s.stream).eval_steps n s.state := rfl\n\n@[simp] lemma StreamExec.bifunctor_bimap_valid (s : StreamExec \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) :\n  (s.bimap f g).valid \u2194 s.valid := iff.rfl\n\n@[simp] lemma StreamExec.bifunctor_bimap_ready (s : StreamExec \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) :\n  (s.bimap f g).ready \u2194 s.ready := iff.rfl\n\n@[simp] lemma StreamExec.bimap_eval [add_comm_monoid \u03b1] (s : StreamExec \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') :\n  (f <$\u2081> s).eval = s.eval.map_domain f :=\nby simp [StreamExec.eval]\n\ndef contract_stream (s : StreamExec \u03b9 \u03b1) : StreamExec unit \u03b1 :=\n(\u03bb _, ()) <$\u2081> s\n\n@[simp] lemma contract_stream_spec_apply [add_comm_monoid \u03b1] (s : StreamExec \u03b9 \u03b1) :\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 \u03b1] (s : StreamExec \u03b9 \u03b1) :\n  (contract_stream s).eval = finsupp.single () (finsupp.sum_range s.eval) :=\nby { ext, simp, }\n\ndef Stream.index' (s : Stream \u03b9 \u03b1) (x : s.\u03c3) : with_top \u03b9 :=\nif h : s.valid x then s.index x h else \u22a4 \n\ndef Stream.value' [has_zero \u03b1] (s : Stream \u03b9 \u03b1) (x : s.\u03c3) : \u03b1 :=\nif h : s.ready x then s.value _ h else 0\n\ndef Stream.next' (s : Stream \u03b9 \u03b1) (x : s.\u03c3) : s.\u03c3 :=\nif h : s.valid x then s.next x h else x\n\n@[simp] lemma Stream.index'_lt_top_iff [preorder \u03b9] {s : Stream \u03b9 \u03b1} {x : s.\u03c3} :\n  s.index' x < \u22a4 \u2194 s.valid x :=\nby { rw Stream.index', split_ifs; simp [h], exact with_top.coe_lt_top _, }\n\nlemma Stream.eval\u2080_eq_single [has_zero \u03b1] (s : Stream \u03b9 \u03b1) (x : s.\u03c3) (h : s.valid x) :\n  s.eval\u2080 x h = finsupp.single (s.index _ h) (s.value' x) :=\nby { rw [Stream.eval\u2080, Stream.value'], split_ifs with hr; simp, }\n\nlemma Stream.index'_val {s : Stream \u03b9 \u03b1} {x : s.\u03c3} (h : s.valid x) : s.index' x = s.index x h := dif_pos h\n\nlemma Stream.index'_invalid {s : Stream \u03b9 \u03b1} {x : s.\u03c3} (h : \u00acs.valid x) : s.index' x = \u22a4 := dif_neg h\n\nlemma Stream.value'_val [has_zero \u03b1] {s : Stream \u03b9 \u03b1} {x : s.\u03c3} (h : s.ready x) : s.value' x = s.value x h := dif_pos h\n\n@[simp] lemma Stream.next'_val {s : Stream \u03b9 \u03b1} {x : s.\u03c3} (hx) : s.next' x = s.next x hx := dif_pos hx\n\n@[simp] lemma Stream.next'_val_invalid {s : Stream \u03b9 \u03b1} {x : s.\u03c3} (hx : \u00acs.valid x) : s.next' x = x := dif_neg hx\n\n@[simp] lemma Stream.next'_val_invalid' {s : Stream \u03b9 \u03b1} {x : s.\u03c3} (hx : \u00acs.valid x) (n : \u2115) :\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 \u03b9 \u03b1} {x : s.\u03c3} {n : \u2115} :\n  s.bound_valid n x \u2194 \u00acs.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 \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} {n b : \u2115} (hb : s.bound_valid b \u03c3\u2080) (hn : b \u2264 n) :\n  (s.next'^[n] \u03c3\u2080) = (s.next'^[b] \u03c3\u2080) :=\nbegin\n  obtain \u27e8k, rfl\u27e9 := 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 \u03b9 \u03b1} {\u03c3\u2080 : s.\u03c3} {n b : \u2115} (hb : s.bound_valid b \u03c3\u2080) :\n  (s.next'^[min b n] \u03c3\u2080) = (s.next'^[n] \u03c3\u2080) :=\nby { rw min_def, split_ifs, { rw Stream.next'_ge_bound hb h, }, refl, }\n\nlemma Stream.bound_valid.next'_iff {s : Stream \u03b9 \u03b1} {x : s.\u03c3} {B : \u2115} (hB : s.bound_valid B x) :\n  \u00acs.valid x \u2194 s.next'.is_fixed_pt x :=\n\u27e8Stream.next'_val_invalid, \u03bb h\u2081, by simpa [bound_valid_iff_next'_iterate, function.iterate_fixed h\u2081] using hB\u27e9\n\nlemma Stream.bound_valid.iterate_is_fixed_point {s : Stream \u03b9 \u03b1} {x : s.\u03c3} {B : \u2115} (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 \u03b9 \u03b1} {x : s.\u03c3} {B : \u2115} (hB : s.bound_valid B x) :\n  s.next'.is_fixed_pt x \u2194 x \u2208 s.next'.periodic_pts :=\n\u27e8\u03bb h, function.mk_mem_periodic_pts zero_lt_one h, \u03bb 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\u27e9\n\nlemma Stream.next'_valid {s : Stream \u03b9 \u03b1} {x : s.\u03c3}\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 \u03b9 \u03b1} {x : s.\u03c3} (n : \u2115)\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 \u03b9 \u03b1} {x : s.\u03c3} {B : \u2115}\n  (bv : s.bound_valid B x) (h : s.valid x) (n : \u2115) : s.next'^[n.succ] x \u2260 x :=\n\u03bb h', bv.fixed_pt_iff_periodic_pt.not.mp (bv.next'_iff.not_right.mp h) \u27e8n + 1, nat.zero_lt_succ _, h'\u27e9\n\ntheorem Stream.bound_valid.no_repeat {s : Stream \u03b9 \u03b1} {x : s.\u03c3} {B : \u2115}\n  (bv : s.bound_valid B x) (h : s.valid x) : s.next' x \u2260 x := bv.no_repeat' h 0\n\nlemma Stream.bimap_value' [has_zero \u03b1] [has_zero \u03b2] (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) (hg : g 0 = 0) :\n  (s.bimap f g).value' = g \u2218 s.value' :=\nby { ext x, simp [Stream.value', apply_dite g, hg], refl, }\n\nlemma Stream.bimap_value'_apply [has_zero \u03b1] [has_zero \u03b2] (s : Stream \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) (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 \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) (x : s.\u03c3) :\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 \u03b9 \u03b1) (f : \u03b9 \u2192 \u03b9') (g : \u03b1 \u2192 \u03b2) :\n  (s.bimap f g).index' = with_top.map f \u2218 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 \u03b1] (s : Stream \u03b9 \u03b1) (m n : \u2115) (q : s.\u03c3) :\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 \u03b1] (s : Stream \u03b9 \u03b1)\n  (B : \u2115) (\u03c3\u2080 : s.\u03c3) (h : \u2200 i < B, s.valid (s.next'^[i] \u03c3\u2080)) :\n  s.eval_steps B \u03c3\u2080 = \u2211 i : fin B, finsupp.single (s.index (s.next'^[i] \u03c3\u2080) (h i i.prop)) (s.value' (s.next'^[i] \u03c3\u2080)) :=\nbegin\n  induction B with B ih generalizing \u03c3\u2080,\n  { simp, },\n  have hv : s.valid \u03c3\u2080, { exact h 0 (nat.zero_lt_succ _), },\n  specialize ih (s.next _ hv) (\u03bb 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\u2080_eq_single _ _ hv, Stream.next'_val hv],\n  rw add_comm,\nend\n\nnamespace primitives\n\n@[simps]\ndef externSparseVec_stream {len : \u2115} (inds : vector \u03b9 len) (vals : vector \u03b1 len) :\n  Stream \u03b9 \u03b1 :=\n{ \u03c3 := \u2115,\n  valid := \u03bb i, i < len,\n  ready := \u03bb i, i < len,\n  next := \u03bb i hi, i + 1,\n  index := \u03bb i hi, inds.nth \u27e8i, hi\u27e9,\n  value := \u03bb i hi, vals.nth \u27e8i, hi\u27e9 }\n\n@[simp] lemma externSparseVec_stream_value' [has_zero \u03b1] {len : \u2115} (inds : vector \u03b9 len) (vals : vector \u03b1 len) (i : fin len) :\n  (externSparseVec_stream inds vals).value' (i : \u2115) = vals.nth i := \nby { rw Stream.value'_val, swap, { exact i.prop, }, simp, }\n\n@[simp] lemma externSparseVec_next'_iterate {len : \u2115} (inds : vector \u03b9 len) (vals : vector \u03b1 len) (i : \u2115) :\n  ((externSparseVec_stream inds vals).next'^[i] 0 : \u2115) = 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 : \u2115} (inds : vector \u03b9 len) (vals : vector \u03b1 len) :\n  StreamExec \u03b9 \u03b1 :=\n{ stream := externSparseVec_stream inds vals,\n  state := (0 : \u2115),\n  bound := len,\n  bound_valid := by simp [bound_valid_iff_next'_iterate] }\n\n@[simp] lemma externSparseVec.spec [add_comm_monoid \u03b1] {len : \u2115} (inds : vector \u03b9 len) (vals : vector \u03b1 len) :\n  (externSparseVec inds vals).eval = \u2211 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 : \u2115) : Stream \u2115 \u2115 :=\n{ \u03c3 := \u2115,\n  next  := \u03bb k _, k+1,\n  index := \u03bb k _, k,\n  value := \u03bb k _, k,\n  ready := \u03bb _, true,\n  valid := \u03bb k, k < n, }\n\n@[simp] lemma range_iterate {n : \u2115} (i : \u2115) :\n  ((range n).next'^[i] 0 : \u2115) = 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 : \u2115) : StreamExec \u2115 \u2115 :=\n{ stream := range n,\n  state := (0 : \u2115),\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": "/-\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\nNotation for operators defined at Prelude.lean\n-/\nprelude\nimport Init.Prelude\n\n-- DSL for specifying parser precedences and priorities\n\nnamespace Lean.Parser.Syntax\n\nsyntax:65 (name := addPrec) prec \" + \" prec:66 : prec\nsyntax:65 (name := subPrec) prec \" - \" prec:66 : prec\n\nsyntax:65 (name := addPrio) prio \" + \" prio:66 : prio\nsyntax:65 (name := subPrio) prio \" - \" prio:66 : prio\n\nend Lean.Parser.Syntax\n\nmacro \"max\"  : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...)\nmacro \"arg\"  : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...)\nmacro \"lead\" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...)\nmacro \"(\" p:prec \")\" : prec => p\nmacro \"min\"  : prec => `(10)   -- minimum precedence used in term parsers\nmacro \"min1\" : prec => `(11)   -- `(min+1) we can only `min+1` after `Meta.lean`\n/-\n  `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.\n  We use `max_prec` to workaround bootstrapping issues. -/\nmacro \"max_prec\" : term => `(1024)\n\nmacro \"default\" : prio => `(1000)\nmacro \"low\"     : prio => `(100)\nmacro \"mid\"     : prio => `(1000)\nmacro \"high\"    : prio => `(10000)\nmacro \"(\" p:prio \")\" : prio => p\n\n-- Basic notation for defining parsers\nsyntax   stx \"+\" : stx\nsyntax   stx \"*\" : stx\nsyntax   stx \"?\" : stx\nsyntax:2 stx \" <|> \" 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\u2081 <|> $p\u2082) => `(stx| orelse($p\u2081, $p\u2082))\n\n/- Comma-separated sequence. -/\nmacro:max x:stx \",*\"   : stx => `(stx| sepBy($x, \",\", \", \"))\nmacro:max x:stx \",+\"   : stx => `(stx| sepBy1($x, \",\", \", \"))\n/- Comma-separated sequence with optional trailing comma. -/\nmacro:max x:stx \",*,?\" : stx => `(stx| sepBy($x, \",\", \", \", allowTrailingSep))\nmacro:max x:stx \",+,?\" : stx => `(stx| sepBy1($x, \",\", \", \", allowTrailingSep))\n\nmacro \"!\" x:stx : stx => `(stx| notFollowedBy($x))\n\nsyntax (name := rawNatLit) \"nat_lit \" num : term\n\ninfixr:90 \" \u2218 \"  => Function.comp\ninfixr:35 \" \u00d7 \"  => Prod\n\ninfixl:55 \" ||| \"  => HOr.hOr\ninfixl:58 \" ^^^ \"  => HXor.hXor\ninfixl:60 \" &&& \"  => HAnd.hAnd\ninfixl:65 \" + \"  => HAdd.hAdd\ninfixl:65 \" - \"  => HSub.hSub\ninfixl:70 \" * \"  => HMul.hMul\ninfixl:70 \" / \"  => HDiv.hDiv\ninfixl:70 \" % \"  => HMod.hMod\ninfixl:75 \" <<< \"  => HShiftLeft.hShiftLeft\ninfixl:75 \" >>> \"  => HShiftRight.hShiftRight\ninfixr:80 \" ^ \"  => HPow.hPow\nprefix:100 \"-\"   => Neg.neg\nprefix:100 \"~~~\"   => Complement.complement\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% HShiftLeft.hShiftLeft $x $y)\nmacro_rules | `($x >>> $y) => `(binop% HShiftRight.hShiftRight $x $y)\nmacro_rules | `($x ^ $y)   => `(binop% HPow.hPow $x $y)\n\n-- declare ASCII alternatives first so that the latter Unicode unexpander wins\ninfix:50 \" <= \" => LE.le\ninfix:50 \" \u2264 \"  => LE.le\ninfix:50 \" < \"  => LT.lt\ninfix:50 \" >= \" => GE.ge\ninfix:50 \" \u2265 \"  => GE.ge\ninfix:50 \" > \"  => GT.gt\ninfix:50 \" = \"  => Eq\ninfix:50 \" == \" => BEq.beq\ninfix:50 \" ~= \" => HEq\ninfix:50 \" \u2245 \"  => HEq\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 \u2264 $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 \u2265 $y)  => `(binrel% GE.ge $x $y)\nmacro_rules | `($x = $y)  => `(binrel% Eq $x $y)\nmacro_rules | `($x == $y) => `(binrel% BEq.beq $x $y)\n\ninfixr:35 \" /\\\\ \" => And\ninfixr:35 \" \u2227 \"   => And\ninfixr:30 \" \\\\/ \" => Or\ninfixr:30 \" \u2228  \"  => Or\nnotation:max \"\u00ac\" p:40 => Not p\n\ninfixl:35 \" && \" => and\ninfixl:30 \" || \" => or\nnotation:max \"!\" b:40 => not b\n\ninfixl:65 \" ++ \" => HAppend.hAppend\ninfixr:67 \" :: \" => List.cons\n\ninfixr:20  \" <|> \" => HOrElse.hOrElse\ninfixr:60  \" >> \"  => HAndThen.hAndThen\ninfixl:55  \" >>= \" => Bind.bind\ninfixl:60  \" <*> \" => Seq.seq\ninfixl:60  \" <* \"  => SeqLeft.seqLeft\ninfixr:60  \" *> \"  => SeqRight.seqRight\ninfixr:100 \" <$> \" => Functor.map\n\nsyntax (name := termDepIfThenElse) ppGroup(ppDedent(\"if \" ident \" : \" term \" then\" ppSpace term ppDedent(ppSpace \"else\") ppSpace term)) : term\n\nmacro_rules\n  | `(if $h:ident : $c then $t:term else $e:term) => ``(dite $c (fun $h:ident => $t) (fun $h:ident => $e))\n\nsyntax (name := termIfThenElse) ppGroup(ppDedent(\"if \" term \" then\" ppSpace term ppDedent(ppSpace \"else\") ppSpace term)) : term\n\nmacro_rules\n  | `(if $c then $t:term else $e:term) => ``(ite $c $t $e)\n\nmacro \"if \" \"let \" pat:term \" := \" d:term \" then \" t:term \" else \" e:term : term =>\n  `(match $d:term with | $pat:term => $t | _ => $e)\n\nsyntax:min term \"<|\" term:min : term\n\nmacro_rules\n  | `($f $args* <| $a) => let args := args.push a; `($f $args*)\n  | `($f <| $a) => `($f $a)\n\nsyntax:min term \"|>\" term:min1 : term\n\nmacro_rules\n  | `($a |> $f $args*) => let args := args.push a; `($f $args*)\n  | `($a |> $f)        => `($f $a)\n\n-- Haskell-like pipe <|\n-- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations.\nsyntax:min term atomic(\"$\" ws) term:min : term\n\nmacro_rules\n  | `($f $args* $ $a) => let args := args.push a; `($f $args*)\n  | `($f $ $a) => `($f $a)\n\nsyntax \"{ \" 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.\n  Recall that terms such as `match ... with ...` and `\u27e8...\u27e9` will postpone elaboration until\n  expected type is known. So, `without_expected_type` is not effective in this case. -/\nmacro \"without_expected_type \" x:term : term => `(let aux := $x; aux)\n\nsyntax \"[\" term,* \"]\"  : term\nsyntax \"%[\" term,* \"|\" term \"]\" : term -- auxiliary notation for creating big list literals\n\nnamespace Lean\n\nmacro_rules\n  | `([ $elems,* ]) => do\n    let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : 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  (\u2190 ``(List.cons $(elems.elemsAndSeps[i]) $result))\n    if elems.elemsAndSeps.size < 64 then\n      expandListLit elems.elemsAndSeps.size false (\u2190 ``(List.nil))\n    else\n      `(%[ $elems,* | List.nil ])\n\nnotation:50 e:51 \" matches \" p:51 => match e with | p => true | _ => false\n\nnamespace Parser.Tactic\n/--\nIntroduce one or more hypotheses, optionally naming and/or pattern-matching them.\nFor each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type.\n* `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`.\n* `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`,\n  or matched against a pattern:\n  ```lean\n  -- ... \u22a2 \u03b1 \u00d7 \u03b2 \u2192 ...\n  intro (a, b)\n  -- ..., a : \u03b1, b : \u03b2 \u22a2 ...\n  ```\n* Alternatively, `intro` can be combined with pattern matching much like `fun`:\n  ```lean\n  intro\n  | n + 1, 0 => tac\n  | ...\n  ```\n-/\nsyntax (name := intro) \"intro \" notFollowedBy(\"|\") (colGt term:max)* : tactic\n/-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/\nsyntax (name := intros) \"intros \" (colGt (ident <|> \"_\"))* : tactic\n/--\n`rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`,\nor fails if no such hypothesis could be found. -/\nsyntax (name := rename) \"rename \" term \" => \" ident : tactic\n/-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/\nsyntax (name := revert) \"revert \" (colGt ident)+ : tactic\n/-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/\nsyntax (name := clear) \"clear \" (colGt ident)+ : tactic\n/--\n`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`.\nIf `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/\nsyntax (name := subst) \"subst \" (colGt ident)+ : tactic\n/--\n`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.\nNote also the `\u2039t\u203a` term notation, which is a shorthand for `show t by assumption`. -/\nsyntax (name := assumption) \"assumption\" : tactic\n/--\n`contradiction` closes the main goal if its hypotheses are \"trivially contradictory\".\n```lean\nexample (h : False) : p := by contradiction  -- inductive type/family with no applicable constructors\nexample (h : none = some true) : p := by contradiction  -- injectivity of constructors\nexample (h : 2 + 2 = 3) : p := by contradiction  -- decidable false proposition\nexample (h : p) (h' : \u00ac p) : q := by contradiction\nexample (x : Nat) (h : x \u2260 x) : p := by contradiction\n```\n-/\nsyntax (name := contradiction) \"contradiction\" : tactic\n/--\n`apply e` tries to match the current goal against the conclusion of `e`'s type.\nIf it succeeds, then the tactic returns as many subgoals as the number of premises that\nhave not been fixed by type inference or type class resolution.\nNon-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\nsyntax (name := apply) \"apply \" term : tactic\n/--\n`exact e` closes the main goal if its target type matches that of `e`.\n-/\nsyntax (name := exact) \"exact \" term : tactic\n/--\n`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved\nby unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name.\n-/\nsyntax (name := refine) \"refine \" term : tactic\n/-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/\nsyntax (name := refine') \"refine' \" term : tactic\n/-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/\nsyntax (name := constructor) \"constructor\" : tactic\n/--\n`case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails.\n`case tag x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/\nsyntax (name := case) \"case \" ident (ident <|> \"_\")* \" => \" tacticSeq : tactic\n/-- `allGoals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/\nsyntax (name := allGoals) \"allGoals \" tacticSeq : tactic\n/--\n`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.\nUsually `\u00b7 tac`, which enforces that the goal is closed by `tac`, should be preferred. -/\nsyntax (name := focus) \"focus \" tacticSeq : tactic\n/-- `skip` does nothing. -/\nsyntax (name := skip) \"skip\" : tactic\n/-- `done` succeeds iff there are no remaining goals. -/\nsyntax (name := done) \"done\" : tactic\nsyntax (name := traceState) \"traceState\" : tactic\nsyntax (name := failIfSuccess) \"failIfSuccess \" tacticSeq : tactic\n/--\n`generalize [h :] e = x` replaces all occurrences of the term `e` in the main goal with a fresh hypothesis `x`.\nIf `h` is given, `h : e = x` is introduced as well. -/\nsyntax (name := generalize) \"generalize \" atomic(ident \" : \")? term:51 \" = \" ident : tactic\nsyntax (name := paren) \"(\" tacticSeq \")\" : tactic\nsyntax (name := withReducible) \"withReducible \" tacticSeq : tactic\nsyntax (name := withReducibleAndInstances) \"withReducibleAndInstances \" tacticSeq : tactic\n/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/\nsyntax (name := first) \"first \" withPosition((group(colGe \"|\" tacticSeq))+) : tactic\nsyntax (name := rotateLeft) \"rotateLeft\" (num)? : tactic\nsyntax (name := rotateRight) \"rotateRight\" (num)? : tactic\n/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/\nmacro \"try \" t:tacticSeq : tactic => `(first | $t | skip)\n/-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/\nmacro:1 x:tactic \" <;> \" y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic))\n\n/-- `\u00b7 tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/\nmacro dot:(\"\u00b7\" <|> \".\") ts:tacticSeq : tactic => `(tactic| {%$dot ($ts:tacticSeq) })\n\n/-- `rfl` is a shorthand for `exact rfl`. -/\nmacro \"rfl\" : tactic => `(exact rfl)\n/-- `admit` is a shorthand for `exact sorry`. -/\nmacro \"admit\" : tactic => `(exact sorry)\nmacro \"inferInstance\" : tactic => `(exact inferInstance)\n\nsyntax locationWildcard := \"*\"\nsyntax locationHyp      := (colGt ident)+ (\"\u22a2\" <|> \"|-\")? -- TODO: delete\nsyntax locationTargets  := (colGt ident)+ (\"\u22a2\" <|> \"|-\")?\nsyntax location         := withPosition(\"at \" locationWildcard <|> locationHyp)\n\nsyntax (name := change) \"change \" term (location)? : tactic\nsyntax (name := changeWith) \"change \" term \" with \" term (location)? : tactic\n\nsyntax rwRule    := (\"\u2190\" <|> \"<-\")? term\nsyntax rwRuleSeq := \"[\" rwRule,+,? \"]\"\n\nsyntax (name := rewriteSeq) \"rewrite \" rwRuleSeq (location)? : tactic\nsyntax (name := erewriteSeq) \"erewrite \" rwRuleSeq (location)? : tactic\n\nsyntax (name := rwSeq) \"rw \" rwRuleSeq (location)? : tactic\nsyntax (name := erwSeq) \"erw \" rwRuleSeq (location)? : tactic\n\ndef rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do\n  -- We show the `rfl` state on `]`\n  let seq   := stx[1]\n  let rbrak := seq[2]\n  -- Replace `]` token with one without position information in the expanded tactic\n  let seq   := seq.setArg 2 (mkAtom \"]\")\n  let tac   := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 1 seq\n  `(tactic| $tac; try (withReducible rfl%$rbrak))\n\n@[macro rwSeq] def expandRwSeq : Macro :=\n  rwWithRfl ``Lean.Parser.Tactic.rewriteSeq \"rewrite\"\n\n@[macro erwSeq] def expandERwSeq : Macro :=\n  rwWithRfl ``Lean.Parser.Tactic.erewriteSeq \"erewrite\"\n\nsyntax (name := injection) \"injection \" term (\" with \" (colGt (ident <|> \"_\"))+)? : tactic\n\nsyntax simpPre   := \"\u2193\"\nsyntax simpPost  := \"\u2191\"\nsyntax simpLemma := (simpPre <|> simpPost)? term\nsyntax simpErase := \"-\" ident\nsyntax (name := simp) \"simp \" (\"(\" &\"config\" \" := \" term \")\")? (&\"only \")? (\"[\" (simpErase <|> simpLemma),* \"]\")? (location)? : tactic\nsyntax (name := simpAll) \"simp_all \" (\"(\" &\"config\" \" := \" term \")\")? (&\"only \")? (\"[\" (simpErase <|> simpLemma),* \"]\")? : tactic\n\n-- Auxiliary macro for lifting have/suffices/let/...\n-- It makes sure the \"continuation\" `?_` is the main goal after refining\nmacro \"refineLift \" e:term : tactic => `(focus (refine noImplicitLambda% $e; rotateRight))\n\nmacro \"have \" d:haveDecl : tactic => `(refineLift have $d:haveDecl; ?_)\n/- We use a priority > default, to avoid ambiguity with previous `have` notation -/\nmacro (priority := high) \"have\" x:ident \" := \" p:term : tactic => `(have $x:ident : _ := $p)\nmacro \"suffices \" d:sufficesDecl : tactic => `(refineLift suffices $d:sufficesDecl; ?_)\nmacro \"let \" d:letDecl : tactic => `(refineLift let $d:letDecl; ?_)\nmacro \"show \" e:term : tactic => `(refineLift show $e:term from ?_)\nsyntax (name := letrec) withPosition(atomic(group(\"let \" &\"rec \")) letRecDecls) : tactic\nmacro_rules\n  | `(tactic| let rec $d:letRecDecls) => `(tactic| refineLift let rec $d:letRecDecls; ?_)\n\n-- Similar to `refineLift`, but using `refine'`\nmacro \"refineLift' \" e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotateRight))\nmacro \"have' \" d:haveDecl : tactic => `(refineLift' have $d:haveDecl; ?_)\nmacro (priority := high) \"have'\" x:ident \" := \" p:term : tactic => `(have' $x:ident : _ := $p)\nmacro \"let' \" d:letDecl : tactic => `(refineLift' let $d:letDecl; ?_)\n\nsyntax inductionAlt  := \"| \" (group(\"@\"? ident) <|> \"_\") (ident <|> \"_\")* \" => \" (hole <|> syntheticHole <|> tacticSeq)\nsyntax inductionAlts := \"with \" (tactic)? withPosition( (colGe inductionAlt)+)\nsyntax (name := induction) \"induction \" term,+ (\" using \" ident)?  (\"generalizing \" ident+)? (inductionAlts)? : tactic\nsyntax casesTarget := atomic(ident \" : \")? term\nsyntax (name := cases) \"cases \" casesTarget,+ (\" using \" ident)? (inductionAlts)? : tactic\n\nsyntax (name := existsIntro) \"exists \" term : tactic\n\n\nsyntax \"repeat \" tacticSeq : tactic\nmacro_rules\n  | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)\n\nsyntax \"trivial\" : tactic\n\nmacro_rules | `(tactic| trivial) => `(tactic| assumption)\nmacro_rules | `(tactic| trivial) => `(tactic| rfl)\nmacro_rules | `(tactic| trivial) => `(tactic| contradiction)\nmacro_rules | `(tactic| trivial) => `(tactic| apply True.intro)\nmacro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)\n\nmacro \"unhygienic \" t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq)\n\nend Tactic\n\nnamespace Attr\n-- simp attribute syntax\nsyntax (name := simp) \"simp\" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr\nend Attr\n\nend Parser\nend Lean\n\nmacro \"\u2039\" type:term \"\u203a\" : term => `((by assumption : $type))\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Init/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981162643692797, "lm_q2_score": 0.04336580015480672, "lm_q1q2_score": 0.017338151091632056}}
{"text": "import LMT\n\nvariable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]\n\nexample {a1 a2 a3 : A I E} :\n        (v1) \u2260 (((((a3).write i2 (v1)).write i1 (v1)).write i2 (v1)).read i1) \u2192 False := by\n  arr\n", "meta": {"author": "abdoo8080", "repo": "ar-project", "sha": "303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8", "save_path": "github-repos/lean/abdoo8080-ar-project", "path": "github-repos/lean/abdoo8080-ar-project/ar-project-303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8/Test/Lean/Test47.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.03461884058218425, "lm_q1q2_score": 0.017309420291092125}}
{"text": "namespace Cached\n\nstructure Cached {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (x : \u03b1) :=\n  val : \u03b2\n  isFX : f x = val\n  deriving Repr\n\ninstance : EmptyCollection (Cached f x) where emptyCollection := \u27e8f x, rfl\u27e9\ninstance : Inhabited (Cached f x) where default := {}\ninstance : Subsingleton (Cached f x) where\n  allEq := fun \u27e8b, hb\u27e9 \u27e8c, hc\u27e9 => by subst hb; subst hc; rfl\ninstance : DecidableEq (Cached f x) := fun _ _ => isTrue (Subsingleton.allEq ..)\ninstance [ToString \u03b2] : ToString (@Cached \u03b1 \u03b2 f x) where\n  toString c := toString c.val\n\n@[simp]\ntheorem eq_of_subsingleton [Subsingleton \u03b1] {a b : \u03b1} : (a = b) = True := by\n  simp [Subsingleton.allEq a b]\n\nabbrev Cached' (a : \u03b1) := 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": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Jannis Limperg\n\n! This file was ported from Lean 3 source module init.meta.interactive\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.TypeContext\nimport Leanbin.Init.Meta.RewriteTactic\nimport Leanbin.Init.Meta.SimpTactic\nimport Leanbin.Init.Meta.Smt.CongruenceClosure\nimport Leanbin.Init.Control.Combinators\nimport Leanbin.Init.Meta.InteractiveBase\nimport Leanbin.Init.Meta.Derive\nimport Leanbin.Init.Meta.MatchTactic\nimport Leanbin.Init.Meta.CongrTactic\nimport Leanbin.Init.Meta.CaseTag\n\nopen Lean\n\nopen Lean.Parser\n\nopen Native\n\n/- ./././Mathport/Syntax/Translate/Command.lean:681:29: warning: unsupported: precedence command -/\n-- mathport name: \u00abexpr ?\u00bb\nlocal postfix:1024 \"?\" => optional\n\n-- mathport name: \u00abexpr *\u00bb\nlocal postfix:1024 \"*\" => many\n\nnamespace Tactic\n\n/-- allows metavars -/\nunsafe def i_to_expr (q : pexpr) : tactic expr :=\n  to_expr q true\n#align tactic.i_to_expr tactic.i_to_expr\n\n/-- allow metavars and no subgoals -/\nunsafe def i_to_expr_no_subgoals (q : pexpr) : tactic expr :=\n  to_expr q true false\n#align tactic.i_to_expr_no_subgoals tactic.i_to_expr_no_subgoals\n\n/-- doesn't allows metavars -/\nunsafe def i_to_expr_strict (q : pexpr) : tactic expr :=\n  to_expr q false\n#align tactic.i_to_expr_strict tactic.i_to_expr_strict\n\n/-- Auxiliary version of i_to_expr for apply-like tactics.\n   This is a workaround for comment\n      https://github.com/leanprover/lean/issues/1342#issuecomment-307912291\n   at issue #1342.\n\n   In interactive mode, given a tactic\n\n        apply f\n\n   we want the apply tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n\n   Before we added `i_to_expr_for_apply`, the tactic\n\n       apply le_antisymm\n\n   would first elaborate `le_antisymm`, and create\n\n       @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4\n\n   The type class resolution problem\n        ?m_2 : weak_order ?m_1\n   by the elaborator since ?m_1 is not assigned yet, and the problem is\n   discarded.\n\n   Then, we would invoke `apply_core`, which would create two\n   new metavariables for the explicit arguments, and try to unify the resulting\n   type with the current target. After the unification,\n   the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost\n   the information about the pending type class resolution problem.\n\n   With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,\n   the apply_core tactic creates all metavariables, and solves the ones that\n   can be solved by type class resolution.\n\n   Another possible fix: we modify the elaborator to return pending\n   type class resolution problems, and store them in the tactic_state.\n-/\nunsafe def i_to_expr_for_apply (q : pexpr) : tactic expr :=\n  let aux (n : Name) : tactic expr := do\n    let p \u2190 resolve_name n\n    match p with\n      | expr.const c [] => do\n        let r \u2190 mk_const c\n        save_type_info r q\n        return r\n      | _ => i_to_expr p\n  match q with\n  | expr.const c [] => aux c\n  | expr.local_const c _ _ _ => aux c\n  | _ => i_to_expr q\n#align tactic.i_to_expr_for_apply tactic.i_to_expr_for_apply\n\nnamespace Interactive\n\nopen _Root_.Interactive Interactive.Types Expr\n\n/-- itactic: parse a nested \"interactive\" tactic. That is, parse\n  `{` tactic `}`\n-/\nunsafe def itactic : Type :=\n  tactic Unit\n#align tactic.interactive.itactic tactic.interactive.itactic\n\nunsafe def propagate_tags (tac : itactic) : tactic Unit := do\n  let tag \u2190 get_main_tag\n  if tag = [] then tac\n    else\n      focus1 do\n        tac\n        let gs \u2190 get_goals\n        when (not gs) do\n            let new_tag \u2190 get_main_tag\n            when new_tag <| with_enable_tags (set_main_tag tag)\n#align tactic.interactive.propagate_tags tactic.interactive.propagate_tags\n\nunsafe def concat_tags (tac : tactic (List (Name \u00d7 expr))) : tactic Unit :=\n  condM tags_enabled\n    (do\n      let in_tag \u2190 get_main_tag\n      let r \u2190 tac\n      let r\n        \u2190-- remove assigned metavars\n              r.filterM\n            fun \u27e8n, m\u27e9 => not <$> is_assigned m\n      match r with\n        | [(_, m)] => set_tag m in_tag\n        |-- if there is only new subgoal, we just propagate `in_tag`\n          _ =>\n          r fun \u27e8n, m\u27e9 => set_tag m (n :: in_tag))\n    (tac >> skip)\n#align tactic.interactive.concat_tags tactic.interactive.concat_tags\n\n/--\nIf the current goal is a Pi/forall `\u2200 x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.\n\nIf the goal is an arrow `t \u2192 u`, then it puts `h : t` in the local context and the new goal target is `u`.\n\nIf the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.\n-/\nunsafe def intro : parse ident_ ? \u2192 tactic Unit\n  | none => propagate_tags (intro1 >> skip)\n  | some h => propagate_tags (tactic.intro h >> skip)\n#align tactic.interactive.intro tactic.interactive.intro\n\n/--\nSimilar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.\n\nThe variant `intros h\u2081 ... h\u2099` introduces `n` new hypotheses using the given identifiers to name them.\n-/\nunsafe def intros : parse ident_* \u2192 tactic Unit\n  | [] => propagate_tags (tactic.intros >> skip)\n  | hs => propagate_tags (intro_lst hs >> skip)\n#align tactic.interactive.intros tactic.interactive.intros\n\n/--\nThe tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.\n\nExamples:\n```\nexample : \u2200 a b : nat, a = b \u2192 b = a :=\nbegin\n  introv h,\n  exact h.symm\nend\n```\nThe state after `introv h` is\n```\na b : \u2115,\nh : a = b\n\u22a2 b = a\n```\n\n```\nexample : \u2200 a b : nat, a = b \u2192 \u2200 c, b = c \u2192 a = c :=\nbegin\n  introv h\u2081 h\u2082,\n  exact h\u2081.trans h\u2082\nend\n```\nThe state after `introv h\u2081 h\u2082` is\n```\na b : \u2115,\nh\u2081 : a = b,\nc : \u2115,\nh\u2082 : b = c\n\u22a2 a = c\n```\n-/\nunsafe def introv (ns : parse ident_*) : tactic Unit :=\n  propagate_tags (tactic.introv ns >> return ())\n#align tactic.interactive.introv tactic.interactive.introv\n\n/-- Parse a current name and new name for `rename`. -/\nprivate unsafe def rename_arg_parser : parser (Name \u00d7 Name) :=\n  Prod.mk <$> ident <*> (optional (tk \"->\") *> ident)\n#align tactic.interactive.rename_arg_parser tactic.interactive.rename_arg_parser\n\n/-- Parse the arguments of `rename`. -/\nprivate unsafe def rename_args_parser : parser (List (Name \u00d7 Name)) :=\n  Functor.map (fun x => [x]) rename_arg_parser <|>\n    tk \"[\" *> sep_by (tk \",\") rename_arg_parser <* tk \"]\"\n#align tactic.interactive.rename_args_parser tactic.interactive.rename_args_parser\n\n/-- Rename one or more local hypotheses. The renamings are given as follows:\n\n```\nrename x y             -- rename x to y\nrename x \u2192 y           -- ditto\nrename [x y, a b]      -- rename x to y and a to b\nrename [x \u2192 y, a \u2192 b]  -- ditto\n```\n\nNote that if there are multiple hypotheses called `x` in the context, then\n`rename x y` will rename *all* of them. If you want to rename only one, use\n`dedup` first.\n-/\nunsafe def rename (renames : parse rename_args_parser) : tactic Unit :=\n  propagate_tags <| tactic.rename_many <| native.rb_map.of_list renames\n#align tactic.interactive.rename tactic.interactive.rename\n\n/--\nThe `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\nunsafe def apply (q : parse texpr) : tactic Unit :=\n  concat_tags do\n    let h \u2190 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 been 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 \u2190 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`apply_match 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 \u2190 i_to_expr_for_apply q\n    tactic.apply e { unify := ff }\n#align tactic.interactive.mapply tactic.interactive.mapply\n\n/--\nThis tactic tries to close the main goal `... \u22a2 t` by generating a term of type `t` using type class resolution.\n-/\nunsafe def apply_instance : tactic Unit :=\n  tactic.apply_instance\n#align tactic.interactive.apply_instance tactic.interactive.apply_instance\n\n/--\nThis tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.\n\nNote that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat \u2192 Prop)`.\n-/\nunsafe def refine (q : parse texpr) : tactic Unit :=\n  tactic.refine q\n#align tactic.interactive.refine tactic.interactive.refine\n\n/--\nThis tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.\n-/\nunsafe def assumption : tactic Unit :=\n  tactic.assumption\n#align tactic.interactive.assumption tactic.interactive.assumption\n\n/-- Try to apply `assumption` to all goals. -/\nunsafe def assumption' : tactic Unit :=\n  tactic.any_goals' tactic.assumption\n#align tactic.interactive.assumption' tactic.interactive.assumption'\n\nprivate unsafe def change_core (e : expr) : Option expr \u2192 tactic Unit\n  | none => tactic.change e\n  | some h => do\n    let num_reverted : \u2115 \u2190 revert h\n    let expr.pi n bi d b \u2190 target\n    tactic.change <| expr.pi n bi e b\n    intron num_reverted\n#align tactic.interactive.change_core tactic.interactive.change_core\n\n/--\n`change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.\n\n`change u at h` will change a local hypothesis to `u`.\n\n`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.\n-/\nunsafe def change (q : parse texpr) : parse (tk \"with\" *> texpr)? \u2192 parse location \u2192 tactic Unit\n  | none, loc.ns [none] => do\n    let e \u2190 i_to_expr q\n    change_core e none\n  | none, loc.ns [some h] => do\n    let eq \u2190 i_to_expr q\n    let eh \u2190 get_local h\n    change_core Eq (some eh)\n  | none, _ => fail \"change-at does not support multiple locations\"\n  | some w, l => do\n    let u \u2190 mk_meta_univ\n    let ty \u2190 mk_meta_var (sort u)\n    let eq \u2190 i_to_expr ``(($(q) : $(ty)))\n    let ew \u2190 i_to_expr ``(($(w) : $(ty)))\n    let repl := fun e : expr => e.replace fun a n => if a = Eq then some ew else none\n    l\n        (fun h => do\n          let e \u2190 infer_type h\n          change_core (repl e) (some h))\n        do\n        let g \u2190 target\n        change_core (repl g) none\n#align tactic.interactive.change tactic.interactive.change\n\n/--\nThis tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.\n-/\nunsafe def exact (q : parse texpr) : tactic Unit := do\n  let tgt : expr \u2190 target\n  i_to_expr_strict ``(($(q) : $(tgt))) >>= tactic.exact\n#align tactic.interactive.exact tactic.interactive.exact\n\n/--\nLike `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.\n-/\nunsafe def exacts : parse pexpr_list_or_texpr \u2192 tactic Unit\n  | [] => done\n  | t :: ts => exact t >> exacts ts\n#align tactic.interactive.exacts tactic.interactive.exacts\n\n/-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.\n-/\nunsafe def from :=\n  exact\n#align tactic.interactive.from tactic.interactive.from\n\n/--\n`revert h\u2081 ... h\u2099` applies to any goal with hypotheses `h\u2081` ... `h\u2099`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.\n-/\nunsafe def revert (ids : parse ident*) : tactic Unit :=\n  propagate_tags do\n    let hs \u2190 mapM tactic.get_local ids\n    revert_lst hs\n    skip\n#align tactic.interactive.revert tactic.interactive.revert\n\nprivate unsafe def resolve_name' (n : Name) : tactic expr := do\n  let p \u2190 resolve_name n\n  match p with\n    | expr.const n _ => mk_const n\n    |-- create metavars for universe levels\n      _ =>\n      i_to_expr p\n#align tactic.interactive.resolve_name' tactic.interactive.resolve_name'\n\n/--\nVersion of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.\n   This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.\n   Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.\n   Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/\nunsafe def to_expr' (p : pexpr) : tactic expr :=\n  match p with\n  | const c [] => do\n    let new_e \u2190 resolve_name' c\n    save_type_info new_e p\n    return new_e\n  | local_const c _ _ _ => do\n    let new_e \u2190 resolve_name' c\n    save_type_info new_e p\n    return new_e\n  | _ => i_to_expr p\n#align tactic.interactive.to_expr' tactic.interactive.to_expr'\n\nunsafe structure rw_rule where\n  Pos : Pos\n  symm : Bool\n  rule : pexpr\n  deriving has_reflect\n#align tactic.interactive.rw_rule tactic.interactive.rw_rule\n\nunsafe def get_rule_eqn_lemmas (r : rw_rule) : tactic (List Name) :=\n  let aux (n : Name) : tactic (List Name) :=\n    (-- unpack local refs\n      do\n        let p \u2190 resolve_name n\n        let e := p.erase_annotations.get_app_fn.erase_annotations\n        match e with\n          | const n _ => get_eqn_lemmas_for tt n\n          | _ => return []) <|>\n      return []\n  match r.rule with\n  | const n _ => aux n\n  | local_const n _ _ _ => aux n\n  | _ => return []\n#align tactic.interactive.get_rule_eqn_lemmas tactic.interactive.get_rule_eqn_lemmas\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `eq_lemmas -/\nprivate unsafe def rw_goal (cfg : RewriteCfg) (rs : List rw_rule) : tactic Unit :=\n  rs.mapM' fun r => do\n    save_info r\n    let eq_lemmas \u2190 get_rule_eqn_lemmas r\n    orelse'\n        (do\n          let e \u2190 to_expr' r\n          rewrite_target e { cfg with symm := r })\n        (eq_lemmas fun n => do\n          let e \u2190 mk_const n\n          rewrite_target e { cfg with symm := r })\n        (eq_lemmas eq_lemmas.empty)\n#align tactic.interactive.rw_goal tactic.interactive.rw_goal\n\nprivate unsafe def uses_hyp (e : expr) (h : expr) : Bool :=\n  e.fold false fun t _ r => r || decide (t = h)\n#align tactic.interactive.uses_hyp tactic.interactive.uses_hyp\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `eq_lemmas -/\nprivate unsafe def rw_hyp (cfg : RewriteCfg) : List rw_rule \u2192 expr \u2192 tactic Unit\n  | [], hyp => skip\n  | r :: rs, hyp => do\n    save_info r\n    let eq_lemmas \u2190 get_rule_eqn_lemmas r\n    orelse'\n        (do\n          let e \u2190 to_expr' r\n          (if uses_hyp e hyp then pure e else rewrite_hyp e hyp { cfg with symm := r }) >>=\n              rw_hyp rs)\n        (eq_lemmas fun n => do\n          let e \u2190 mk_const n\n          rewrite_hyp e hyp { cfg with symm := r } >>= rw_hyp rs)\n        (eq_lemmas eq_lemmas.empty)\n#align tactic.interactive.rw_hyp tactic.interactive.rw_hyp\n\nunsafe def rw_rule_p (ep : parser pexpr) : parser rw_rule :=\n  rw_rule.mk <$> cur_pos <*> Option.isSome <$> (with_desc \"\u2190\" (tk \"\u2190\" <|> tk \"<-\"))? <*> ep\n#align tactic.interactive.rw_rule_p tactic.interactive.rw_rule_p\n\nunsafe structure rw_rules_t where\n  rules : List rw_rule\n  end_pos : Option Pos\n  deriving has_reflect\n#align tactic.interactive.rw_rules_t tactic.interactive.rw_rules_t\n\n-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations\nunsafe def rw_rules : parser rw_rules_t :=\n  tk \"[\" *>\n        rw_rules_t.mk <$>\n          sep_by (skip_info (tk \",\")) (set_goal_info_pos <| rw_rule_p (parser.pexpr 0)) <*>\n      (some <$> cur_pos <* set_goal_info_pos (tk \"]\")) <|>\n    rw_rules_t.mk <$> List.ret <$> rw_rule_p texpr <*> return none\n#align tactic.interactive.rw_rules tactic.interactive.rw_rules\n\nprivate unsafe def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : RewriteCfg) :\n    tactic Unit :=\n  ((match loca with\n      | loc.wildcard => loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)\n      | _ => loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)) >>\n      try (reflexivity reducible)) >>\n    (returnopt rs.end_pos >>= save_info <|> skip)\n#align tactic.interactive.rw_core tactic.interactive.rw_core\n\n/--\n`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`\u2190` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.\n\n`rewrite [e\u2081, ..., e\u2099]` applies the given rules sequentially.\n\n`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `\u22a2` or `|-` can also be used, to signify the target of the goal.\n-/\nunsafe def rewrite (q : parse rw_rules) (l : parse location) (cfg : RewriteCfg := { }) :\n    tactic Unit :=\n  propagate_tags (rw_core q l cfg)\n#align tactic.interactive.rewrite tactic.interactive.rewrite\n\n/-- An abbreviation for `rewrite`.\n-/\nunsafe def rw (q : parse rw_rules) (l : parse location) (cfg : RewriteCfg := { }) : tactic Unit :=\n  propagate_tags (rw_core q l cfg)\n#align tactic.interactive.rw tactic.interactive.rw\n\n/-- `rewrite` followed by `assumption`.\n-/\nunsafe def rwa (q : parse rw_rules) (l : parse location) (cfg : RewriteCfg := { }) : tactic Unit :=\n  rewrite q l cfg >> try assumption\n#align tactic.interactive.rwa tactic.interactive.rwa\n\n/--\nA variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.\n-/\nunsafe def erewrite (q : parse rw_rules) (l : parse location)\n    (cfg : RewriteCfg := { md := semireducible }) : tactic Unit :=\n  propagate_tags (rw_core q l cfg)\n#align tactic.interactive.erewrite tactic.interactive.erewrite\n\n/-- An abbreviation for `erewrite`.\n-/\nunsafe def erw (q : parse rw_rules) (l : parse location)\n    (cfg : RewriteCfg := { md := semireducible }) : tactic Unit :=\n  propagate_tags (rw_core q l cfg)\n#align tactic.interactive.erw tactic.interactive.erw\n\n/-- Returns the unique names of all hypotheses (local constants) in the context.\n-/\nprivate unsafe def hyp_unique_names : tactic name_set := do\n  let ctx \u2190 local_context\n  pure <| ctx (fun r h => r h) mk_name_set\n#align tactic.interactive.hyp_unique_names tactic.interactive.hyp_unique_names\n\n/-- Returns all hypotheses (local constants) from the context except those whose\nunique names are in `hyp_uids`.\n-/\nprivate unsafe def hyps_except (hyp_uids : name_set) : tactic (List expr) := do\n  let ctx \u2190 local_context\n  pure <| ctx fun h : expr => \u00achyp_uids h\n#align tactic.interactive.hyps_except tactic.interactive.hyps_except\n\n/-- Apply `t` to the main goal and revert any new hypothesis in the generated goals.\nIf `t` is a supported tactic or chain of supported tactics (e.g. `induction`,\n`cases`, `apply`, `constructor`), the generated goals are also tagged with case\ntags. You can then use `case` to focus such tagged goals.\n\nTwo typical uses of `with_cases`:\n\n1. Applying a custom eliminator:\n\n   ```\n   lemma my_nat_rec :\n     \u2200 n {P : \u2115 \u2192 Prop} (zero : P 0) (succ : \u2200 n, P n \u2192 P (n + 1)), P n := ...\n\n   example (n : \u2115) : n = n :=\n   begin\n     with_cases { apply my_nat_rec n },\n     case zero { refl },\n     case succ : m ih { refl }\n   end\n   ```\n\n2. Enabling the use of `case` after a chain of case-splitting tactics:\n\n   ```\n   example (n m : \u2115) : unit :=\n   begin\n     with_cases { cases n; induction m },\n     case nat.zero nat.zero { exact () },\n     case nat.zero nat.succ : k { exact () },\n     case nat.succ nat.zero : i { exact () },\n     case nat.succ nat.succ : k i ih_i { exact () }\n   end\n   ```\n-/\nunsafe def with_cases (t : itactic) : tactic Unit :=\n  with_enable_tags <|\n    focus1 do\n      let input_hyp_uids \u2190 hyp_unique_names\n      t\n      all_goals' do\n          let in_tag \u2190 get_main_tag\n          let new_hyps \u2190 hyps_except input_hyp_uids\n          let n \u2190 revert_lst new_hyps\n          set_main_tag (case_tag.from_tag_pi in_tag n).render\n#align tactic.interactive.with_cases tactic.interactive.with_cases\n\nprivate unsafe def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 Name)\n  | app (app (macro _ [const `eq _]) h) (local_const x _ _ _) => pure (h, x)\n  | _ => fail \"parse error\"\n#align tactic.interactive.generalize_arg_p_aux tactic.interactive.generalize_arg_p_aux\n\nprivate unsafe def generalize_arg_p : parser (pexpr \u00d7 Name) :=\n  with_desc \"expr = id\" <| parser.pexpr 0 >>= generalize_arg_p_aux\n#align tactic.interactive.generalize_arg_p tactic.interactive.generalize_arg_p\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n      `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.\n      \n      `generalize h : e = x` in addition registers the hypothesis `h : e = x`.\n      -/\n    unsafe\n  def\n    generalize\n    ( h : parse ident ? ) ( _ : parse <| tk \":\" ) ( p : parse generalize_arg_p ) : tactic Unit\n    :=\n      propagate_tags\n        do\n          let ( p , x ) := p\n            let e \u2190 i_to_expr p\n            let some h \u2190 pure h | ( tactic.generalize e x >> intro1 ) >> skip\n            let tgt \u2190 target\n            let\n              tgt'\n                \u2190\n                (\n                    do\n                      let \u27e8 tgt' , _ \u27e9 \u2190 solve_aux tgt ( tactic.generalize e x >> target )\n                        to_expr ` `( \u2200 x , $ ( e ) = x \u2192 $ ( tgt' 0 1 ) )\n                    )\n                  <|>\n                  to_expr ` `( \u2200 x , $ ( e ) = x \u2192 $ ( tgt ) )\n            let t \u2190 assert h tgt'\n            swap\n            exact ` `( $ ( t ) $ ( e ) rfl )\n            intro x\n            intro h\n#align tactic.interactive.generalize tactic.interactive.generalize\n\nunsafe def cases_arg_p : parser (Option Name \u00d7 pexpr) :=\n  with_desc \"(id :)? expr\" do\n    let t \u2190 texpr\n    match t with\n      | local_const x _ _ _ =>\n        (tk \":\" *> do\n            let t \u2190 texpr\n            pure (some x, t)) <|>\n          pure (none, t)\n      | _ => pure (none, t)\n#align tactic.interactive.cases_arg_p tactic.interactive.cases_arg_p\n\n/-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag`\n  is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was\n  applied. `rs` should contain, for each subgoal, the constructor name\n  associated with that goal and the hypotheses that were introduced.\n-/\nprivate unsafe def set_cases_tags (in_tag : Tag) (rs : List (Name \u00d7 List expr)) : tactic Unit := do\n  let gs \u2190 get_goals\n  match gs with\n    |-- if only one goal was produced, we should not make the tag longer\n      [g] =>\n      set_tag g in_tag\n    | _ =>\n      let tgs : List (Name \u00d7 List expr \u00d7 expr) := rs (fun \u27e8n, new_hyps\u27e9 g => \u27e8n, new_hyps, g\u27e9) gs\n      tgs fun \u27e8n, new_hyps, g\u27e9 =>\n        with_enable_tags <|\n          set_tag g <| (case_tag.from_tag_hyps (n :: in_tag) (new_hyps expr.local_uniq_name)).render\n#align tactic.interactive.set_cases_tags tactic.interactive.set_cases_tags\n\n/- ./././Mathport/Syntax/Translate/Command.lean:681:29: warning: unsupported: precedence command -/\n/--\nAssuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih\u2081 : P a \u2192 Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih\u2081` ire chosen automatically.\n\n`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.\n\n`induction e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.\n\n`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables\n\n`induction e generalizing z\u2081 ... z\u2099`, where `z\u2081 ... z\u2099` are variables in the local context, generalizes over `z\u2081 ... z\u2099` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.\n\n`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.\n-/\nunsafe def induction (hp : parse cases_arg_p) (rec_name : parse using_ident)\n    (ids : parse with_ident_list) (revert : parse <| (tk \"generalizing\" *> ident*)?) :\n    tactic Unit := do\n  let in_tag \u2190 get_main_tag\n  focus1 do\n      let e\n        \u2190-- process `h : t` case\n          match hp with\n          | (some h, p) => do\n            let x \u2190 get_unused_name\n            generalize h () (p, x)\n            get_local x\n          | (none, p) => i_to_expr p\n      let e\n        \u2190-- generalize major premise\n            if e then pure e\n          else tactic.generalize e >> intro1\n      let-- generalize major premise args\n        (e, newvars, locals)\n        \u2190\n        do\n          let none \u2190 pure rec_name |\n            pure (e, [], [])\n          let t \u2190 infer_type e\n          let t \u2190 whnf_ginductive t\n          let const n _ \u2190 pure t |\n            pure (e, [], [])\n          let env \u2190 get_env\n          let tt \u2190 pure <| env n |\n            pure (e, [], [])\n          let (locals, nonlocals) := (t <| env n).partition\u2093 fun arg : expr => arg\n          let _ :: _ \u2190 pure nonlocals |\n            pure (e, [], [])\n          let n \u2190 tactic.revert e\n          let newvars \u2190\n            nonlocals fun arg => do\n                let n \u2190 revert_kdeps arg\n                tactic.generalize arg\n                let h \u2190 intro1\n                intron n\n                let-- now try to clear hypotheses that may have been abstracted away\n                locals := arg [] fun e _ acc => if e then e :: Acc else Acc\n                locals (try \u2218 clear)\n                pure h\n          intron (n - 1)\n          let e \u2190 intro1\n          pure (e, newvars, locals)\n      let to_generalize \u2190\n        (-- revert `generalizing` params (and their dependencies, if any)\n                revert\n                []).mapM\n            tactic.get_local\n      let num_generalized \u2190 revert_lst to_generalize\n      let rs\n        \u2190-- perform the induction\n            tactic.induction\n            e ids rec_name\n      let gen_hyps\n        \u2190-- re-introduce the generalized hypotheses\n            all_goals\n            do\n            let new_hyps \u2190 intron' num_generalized\n            clear_lst (newvars local_pp_name)\n            (e :: locals).mapM' (try \u2218 clear)\n            pure new_hyps\n      set_cases_tags in_tag <|\n          @List.zipWith (Name \u00d7 List expr \u00d7 List (Name \u00d7 expr)) _ (Name \u00d7 List expr)\n            (fun \u27e8n, hyps, _\u27e9 gen_hyps => \u27e8n, hyps ++ gen_hyps\u27e9) rs gen_hyps\n#align tactic.interactive.induction tactic.interactive.induction\n\nopen CaseTag.MatchResult\n\nprivate unsafe def goals_with_matching_tag (ns : List Name) :\n    tactic (List (expr \u00d7 CaseTag) \u00d7 List (expr \u00d7 CaseTag)) := do\n  let gs \u2190 get_goals\n  let (gs : List (expr \u00d7 tag)) \u2190\n    gs.mapM fun g => do\n        let t \u2190 get_tag g\n        pure (g, t)\n  pure <|\n      gs\n        (fun \u27e8g, t\u27e9 \u27e8exact_matches, suffix_matches\u27e9 =>\n          match case_tag.parse t with\n          | none => \u27e8exact_matches, suffix_matches\u27e9\n          | some t =>\n            match case_tag.match_tag ns t with\n            | exact_match => \u27e8\u27e8g, t\u27e9 :: exact_matches, suffix_matches\u27e9\n            | fuzzy_match => \u27e8exact_matches, \u27e8g, t\u27e9 :: suffix_matches\u27e9\n            | no_match => \u27e8exact_matches, suffix_matches\u27e9)\n        ([], [])\n#align tactic.interactive.goals_with_matching_tag tactic.interactive.goals_with_matching_tag\n\nprivate unsafe def goal_with_matching_tag (ns : List Name) : tactic (expr \u00d7 CaseTag) := do\n  let \u27e8exact_matches, suffix_matches\u27e9 \u2190 goals_with_matching_tag ns\n  match exact_matches, suffix_matches with\n    | [], [] => fail f! \"Invalid `case`: there is no goal tagged with suffix {ns}.\"\n    | [], [g] => pure g\n    | [], _ =>\n      let tags : List (List Name) := suffix_matches fun \u27e8_, t\u27e9 => t\n      fail\n        f! \"Invalid `case`: there is more than one goal tagged with suffix {ns }.\n          Matching tags: {tags}\"\n    | [g], _ => pure g\n    | _, _ => fail f! \"Invalid `case`: there is more than one goal tagged with tag {ns}.\"\n#align tactic.interactive.goal_with_matching_tag tactic.interactive.goal_with_matching_tag\n\nunsafe def case_arg_parser : lean.parser (List Name \u00d7 Option (List Name)) :=\n  Prod.mk <$> ident_* <*> (tk \":\" *> ident_*)?\n#align tactic.interactive.case_arg_parser tactic.interactive.case_arg_parser\n\nunsafe def case_parser : lean.parser (List (List Name \u00d7 Option (List Name))) :=\n  list_of case_arg_parser <|> Functor.map (fun x => [x]) case_arg_parser\n#align tactic.interactive.case_parser tactic.interactive.case_parser\n\n/-\nTODO `case` could be generalised to work with zero names as well. The form\n\n  case : x y z { ... }\n\nwould select the first goal (or the first goal with a case tag), renaming\nhypotheses to `x, y, z`. The renaming functionality would be available only if\nthe goal has a case tag.\n-/\n/-- Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`.\n\nThe goal is selected by giving one or more names which must match exactly one\ngoal. A goal is matched if the given names are a suffix of its goal tag.\nAdditionally, each name in the sequence can be abbreviated to a suffix of the\ncorresponding name in the goal tag. Thus, a goal with tag\n```\nnat.zero, list.nil\n```\ncan be selected with any of these invocations (among others):\n```\ncase nat.zero list.nil {...}\ncase nat.zero nil      {...}\ncase zero     nil      {...}\ncase          nil      {...}\n```\n\nAdditionally, the form\n```\ncase C : N\u2080 ... N\u2099 {...}\n```\ncan be used to rename hypotheses introduced by the preceding\n`cases`/`induction`/`with_cases`, using the names `N\u1d62`. For example:\n```\nexample (xs : list \u2115) : xs = xs :=\nbegin\n  induction xs,\n  case nil { reflexivity },\n  case cons : x xs ih {\n    -- x : \u2115, xs : list \u2115, ih : xs = xs\n    reflexivity }\nend\n```\n\nNote that this renaming functionality only work reliably *directly after* an\n`induction`/`cases`/`with_cases`. If you need to perform additional work after\nan `induction` or `cases` (e.g. introduce hypotheses in all goals), use\n`with_cases`.\n\nMultiple cases can be handled by the same tactic block with\n```\ncase [A : N\u2080 ... N\u2099, B : M\u2080 ... M\u2099] {...}\n```\n-/\nunsafe def case (args : parse case_parser) (tac : itactic) : tactic Unit := do\n  let target_goals \u2190\n    args.mapM fun \u27e8ns, ids\u27e9 => do\n        let \u27e8goal, tag\u27e9 \u2190 goal_with_matching_tag ns\n        let ids := ids.getD []\n        let num_ids := ids.length\n        let goals \u2190 get_goals\n        let other_goals := goals.filter\u2093 (\u00b7 \u2260 goal)\n        set_goals [goal]\n        match tag with\n          | case_tag.pi _ num_args => do\n            intro_lst ids\n            when (num_ids < num_args) <| intron (num_args - num_ids)\n          | case_tag.hyps _ new_hyp_names => do\n            let num_new_hyps := new_hyp_names\n            when (num_ids > num_new_hyps) <|\n                fail\n                  f! \"Invalid `case`: You gave {num_ids } names, but the case introduces {num_new_hyps} new hypotheses.\"\n            let renamings := native.rb_map.of_list (new_hyp_names ids)\n            propagate_tags <| tactic.rename_many renamings tt tt\n        let goals \u2190 get_goals\n        set_goals other_goals\n        match goals with\n          | [g] => return g\n          | _ => fail \"Unexpected goals introduced by renaming\"\n  let remaining_goals \u2190 get_goals\n  set_goals target_goals\n  tac\n  let unsolved_goals \u2190 get_goals\n  match unsolved_goals with\n    | [] => set_goals remaining_goals\n    | _ => fail \"case tactic failed, focused goals have not been solved\"\n#align tactic.interactive.case tactic.interactive.case\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 \u2192 Q n`, and one goal with target `\u2200 (a : \u2115), (\u03bb (w : \u2115), n = w \u2192 Q n) (nat.succ a)`. Here the name `a` is chosen automatically.\n-/\nunsafe def destruct (p : parse texpr) : tactic Unit :=\n  i_to_expr p >>= tactic.destruct\n#align tactic.interactive.destruct tactic.interactive.destruct\n\nunsafe def cases_core (e : expr) (ids : List Name := []) : tactic Unit := do\n  let in_tag \u2190 get_main_tag\n  focus1 do\n      let rs \u2190 tactic.cases e ids\n      set_cases_tags in_tag rs\n#align tactic.interactive.cases_core tactic.interactive.cases_core\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.\n\n`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.\n\n`cases e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.\n\n`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.\n-/\nunsafe def cases : parse cases_arg_p \u2192 parse with_ident_list \u2192 tactic Unit\n  | (none, p), ids => do\n    let e \u2190 i_to_expr p\n    cases_core e ids\n  | (some h, p), ids => do\n    let x \u2190 get_unused_name\n    generalize h () (p, x)\n    let hx \u2190 get_local x\n    cases_core hx ids\n#align tactic.interactive.cases tactic.interactive.cases\n\nprivate unsafe def find_matching_hyp (ps : List pattern) : tactic expr :=\n  any_hyp fun h => do\n    let type \u2190 infer_type h\n    ps fun p => do\n        match_pattern p type\n        return h\n#align tactic.interactive.find_matching_hyp tactic.interactive.find_matching_hyp\n\n/--\n`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.\n`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.\n`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_matching* [_ \u2228 _, _ \u2227 _]\n```\n-/\nunsafe def cases_matching (rec : parse <| (tk \"*\")?) (ps : parse pexpr_list_or_texpr) :\n    tactic Unit := do\n  let ps \u2190 ps.mapM pexpr_to_pattern\n  if rec then find_matching_hyp ps >>= cases_core\n    else tactic.focus1 <| tactic.repeat <| find_matching_hyp ps >>= cases_core\n#align tactic.interactive.cases_matching tactic.interactive.cases_matching\n\n/-- Shorthand for `cases_matching` -/\nunsafe def casesm (rec : parse <| (tk \"*\")?) (ps : parse pexpr_list_or_texpr) : tactic Unit :=\n  cases_matching rec ps\n#align tactic.interactive.casesm tactic.interactive.casesm\n\nprivate unsafe def try_cases_for_types (type_names : List Name) (at_most_one : Bool) :\n    tactic Unit :=\n  any_hyp fun h => do\n    let I \u2190 expr.get_app_fn <$> (infer_type h >>= head_beta)\n    guard I\n    guard (I \u2208 type_names)\n    tactic.focus1\n        (cases_core h >>\n          if at_most_one then do\n            let n \u2190 num_goals\n            guard (n \u2264 1)\n          else skip)\n#align tactic.interactive.try_cases_for_types tactic.interactive.try_cases_for_types\n\n/-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`\n`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`\n`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`\n`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_type* or and\n```\n-/\nunsafe def cases_type (one : parse <| (tk \"!\")?) (rec : parse <| (tk \"*\")?)\n    (type_names : parse ident*) : tactic Unit := do\n  let type_names \u2190 type_names.mapM resolve_constant\n  if rec then try_cases_for_types type_names (not one)\n    else tactic.focus1 <| tactic.repeat <| try_cases_for_types type_names (not one)\n#align tactic.interactive.cases_type tactic.interactive.cases_type\n\n/--\nTries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.\n-/\nunsafe def trivial : tactic Unit :=\n  tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail \"trivial tactic failed\"\n#align tactic.interactive.trivial tactic.interactive.trivial\n\n/-- Closes the main goal using `sorry`. Takes an optional ignored tactic block.\n\nThe ignored tactic block is useful for \"commenting out\" part of a proof during development:\n```lean\nbegin\n  split,\n  admit { expensive_tactic },\n\nend\n```\n-/\nunsafe def admit (t : parse (with_desc \"{...}\" parser.itactic)?) : tactic Unit :=\n  tactic.admit\n#align tactic.interactive.admit tactic.interactive.admit\n\n/-- Closes the main goal using `sorry`. Takes an optional ignored tactic block.\n\nThe ignored tactic block is useful for \"commenting out\" part of a proof during development:\n```lean\nbegin\n  split,\n  sorry { expensive_tactic },\n\nend\n```\n-/\nunsafe def sorry (t : parse (with_desc \"{...}\" parser.itactic)?) : tactic Unit :=\n  tactic.admit\n#align tactic.interactive.sorry tactic.interactive.sorry\n\n/--\nThe contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.\n-/\nunsafe def contradiction : tactic Unit :=\n  tactic.contradiction\n#align tactic.interactive.contradiction tactic.interactive.contradiction\n\n/-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.\n\n`iterate n { t }` applies `t` `n` times.\n-/\nunsafe def iterate (n : parse small_nat ?) (t : itactic) : tactic Unit :=\n  match n with\n  | none => tactic.iterate' t\n  | some n => iterate_exactly' n t\n#align tactic.interactive.iterate tactic.interactive.iterate\n\n/-- `repeat { t }` applies `t` to each goal. If the application succeeds,\nthe tactic is applied recursively to all the generated subgoals until it eventually fails.\nThe recursion stops in a subgoal when the tactic has failed to make progress.\nThe tactic `repeat { t }` never fails.\n-/\nunsafe def repeat : itactic \u2192 tactic Unit :=\n  tactic.repeat\n#align tactic.interactive.repeat tactic.interactive.repeat\n\n/-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.\n-/\nunsafe def try : itactic \u2192 tactic Unit :=\n  tactic.try\n#align tactic.interactive.try tactic.interactive.try\n\n/-- A do-nothing tactic that always succeeds.\n-/\nunsafe def skip : tactic Unit :=\n  tactic.skip\n#align tactic.interactive.skip tactic.interactive.skip\n\n/-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.\n-/\nunsafe def solve1 : itactic \u2192 tactic Unit :=\n  tactic.solve1\n#align tactic.interactive.solve1 tactic.interactive.solve1\n\n/--\n`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.\n-/\nunsafe def abstract (id : parse ident ?) (tac : itactic) : tactic Unit :=\n  tactic.abstract tac id\n#align tactic.interactive.abstract tactic.interactive.abstract\n\n/--\n`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.\n-/\nunsafe def all_goals : itactic \u2192 tactic Unit :=\n  tactic.all_goals'\n#align tactic.interactive.all_goals tactic.interactive.all_goals\n\n/--\n`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.\n-/\nunsafe def any_goals : itactic \u2192 tactic Unit :=\n  tactic.any_goals'\n#align tactic.interactive.any_goals tactic.interactive.any_goals\n\n/--\n`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.\n-/\nunsafe def focus (tac : itactic) : tactic Unit :=\n  tactic.focus1 tac\n#align tactic.interactive.focus tactic.interactive.focus\n\nprivate unsafe def assume_core (n : Name) (ty : pexpr) := do\n  let t \u2190 target\n  when (Not <| t \u2228 t) whnf_target\n  let t \u2190 target\n  when (Not <| t \u2228 t) <| fail \"assume tactic failed, Pi/let expression expected\"\n  let ty \u2190 i_to_expr ``(($(ty) : Sort _))\n  unify ty t\n  intro_core n >> skip\n#align tactic.interactive.assume_core tactic.interactive.assume_core\n\n/--\nAssuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.\n\n`assume (h\u2081 : t\u2081) ... (h\u2099 : t\u2099)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.\n-/\nunsafe def assume :\n    parse (Sum.inl <$> (tk \":\" *> texpr) <|> Sum.inr <$> parse_binders tac_rbp) \u2192 tactic Unit\n  | Sum.inl ty => assume_core `this ty\n  | Sum.inr binders => binders.mapM' fun b => assume_core b.local_pp_name b.local_type\n#align tactic.interactive.assume tactic.interactive.assume\n\n/--\n`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\nunsafe def have (h : parse ident ?) (q\u2081 : parse (tk \":\" *> texpr)?)\n    (q\u2082 : parse <| (tk \":=\" *> texpr)?) : tactic Unit :=\n  let h := h.getD `this\n  (match q\u2081, q\u2082 with\n    | some e, some p => do\n      let t \u2190 i_to_expr ``(($(e) : Sort _))\n      let v \u2190 i_to_expr ``(($(p) : $(t)))\n      tactic.assertv h t v\n    | none, some p => do\n      let p \u2190 i_to_expr p\n      tactic.note h none p\n    | some e, none => i_to_expr ``(($(e) : Sort _)) >>= tactic.assert h\n    | none, none => do\n      let u \u2190 mk_meta_univ\n      let e \u2190 mk_meta_var (sort u)\n      tactic.assert h e) >>\n    skip\n#align tactic.interactive.have tactic.interactive.have\n\n/--\n`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\nunsafe def let (h : parse ident ?) (q\u2081 : parse (tk \":\" *> texpr)?)\n    (q\u2082 : parse <| (tk \":=\" *> texpr)?) : tactic Unit :=\n  let h := h.getD `this\n  (match q\u2081, q\u2082 with\n    | some e, some p => do\n      let t \u2190 i_to_expr ``(($(e) : Sort _))\n      let v \u2190 i_to_expr ``(($(p) : $(t)))\n      tactic.definev h t v\n    | none, some p => do\n      let p \u2190 i_to_expr p\n      tactic.pose h none p\n    | some e, none => i_to_expr ``(($(e) : Sort _)) >>= tactic.define h\n    | none, none => do\n      let u \u2190 mk_meta_univ\n      let e \u2190 mk_meta_var (sort u)\n      tactic.define h e) >>\n    skip\n#align tactic.interactive.let tactic.interactive.let\n\n/--\n`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.\n-/\nunsafe def suffices (h : parse ident ?) (t : parse (tk \":\" *> texpr)?) : tactic Unit :=\n  have h t none >> tactic.swap\n#align tactic.interactive.suffices tactic.interactive.suffices\n\n/-- This tactic displays the current state in the tracing buffer.\n-/\nunsafe def trace_state : tactic Unit :=\n  tactic.trace_state\n#align tactic.interactive.trace_state tactic.interactive.trace_state\n\n/-- `trace a` displays `a` in the tracing buffer.\n-/\nunsafe def trace {\u03b1 : Type} [has_to_tactic_format \u03b1] (a : \u03b1) : tactic Unit :=\n  tactic.trace a\n#align tactic.interactive.trace tactic.interactive.trace\n\n/--\n`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.\n\n`existsi [e\u2081, ..., e\u2099]` iteratively does the same for each expression in the list.\n-/\nunsafe def existsi : parse pexpr_list_or_texpr \u2192 tactic Unit\n  | [] => return ()\n  | p :: ps => (i_to_expr p >>= tactic.existsi) >> existsi ps\n#align tactic.interactive.existsi tactic.interactive.existsi\n\n/--\nThis tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.\n-/\nunsafe def constructor : tactic Unit :=\n  concat_tags tactic.constructor\n#align tactic.interactive.constructor tactic.interactive.constructor\n\n/-- Similar to `constructor`, but only non-dependent premises are added as new goals.\n-/\nunsafe def econstructor : tactic Unit :=\n  concat_tags tactic.econstructor\n#align tactic.interactive.econstructor tactic.interactive.econstructor\n\n/--\nApplies the first constructor when the type of the target is an inductive data type with two constructors.\n-/\nunsafe def left : tactic Unit :=\n  concat_tags tactic.left\n#align tactic.interactive.left tactic.interactive.left\n\n/--\nApplies the second constructor when the type of the target is an inductive data type with two constructors.\n-/\nunsafe def right : tactic Unit :=\n  concat_tags tactic.right\n#align tactic.interactive.right tactic.interactive.right\n\n/--\nApplies the constructor when the type of the target is an inductive data type with one constructor.\n-/\nunsafe def split : tactic Unit :=\n  concat_tags tactic.split\n#align tactic.interactive.split tactic.interactive.split\n\nprivate unsafe def constructor_matching_aux (ps : List pattern) : tactic Unit := do\n  let t \u2190 target\n  ps fun p => match_pattern p t\n  constructor\n#align tactic.interactive.constructor_matching_aux tactic.interactive.constructor_matching_aux\n\nunsafe def constructor_matching (rec : parse <| (tk \"*\")?) (ps : parse pexpr_list_or_texpr) :\n    tactic Unit := do\n  let ps \u2190 ps.mapM pexpr_to_pattern\n  if rec then constructor_matching_aux ps\n    else tactic.focus1 <| tactic.repeat <| constructor_matching_aux ps\n#align tactic.interactive.constructor_matching tactic.interactive.constructor_matching\n\n/-- Replaces the target of the main goal by `false`.\n-/\nunsafe def exfalso : tactic Unit :=\n  tactic.exfalso\n#align tactic.interactive.exfalso tactic.interactive.exfalso\n\n/--\nThe `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t\u2081)` and `(c t\u2082)` are two terms that are equal then  `t\u2081` and `t\u2082` are equal too.\n\nIf `q` is a proof of a statement of conclusion `t\u2081 = t\u2082`, then injection applies injectivity to derive the equality of all arguments of `t\u2081` and `t\u2082` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t\u2081` and `t\u2082` should be constructor applications of the same constructor.\n\nGiven `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h\u2081 h\u2082` uses the names `h\u2081` and `h\u2082` to name the new hypotheses.\n-/\nunsafe def injection (q : parse texpr) (hs : parse with_ident_list) : tactic Unit := do\n  let e \u2190 i_to_expr q\n  tactic.injection_with e hs\n  try assumption\n#align tactic.interactive.injection tactic.interactive.injection\n\n/--\n`injections with h\u2081 ... h\u2099` iteratively applies `injection` to hypotheses using the names `h\u2081 ... h\u2099`.\n-/\nunsafe def injections (hs : parse with_ident_list) : tactic Unit := do\n  tactic.injections_with hs\n  try assumption\n#align tactic.interactive.injections tactic.interactive.injections\n\nend Interactive\n\nunsafe structure simp_config_ext extends SimpConfig where\n  discharger : tactic Unit := failed\n#align tactic.simp_config_ext tactic.simp_config_ext\n\nsection MkSimpSet\n\nopen Expr Interactive.Types\n\nunsafe inductive simp_arg_type : Type\n  | all_hyps : simp_arg_type\n  | except : Name \u2192 simp_arg_type\n  | expr : pexpr \u2192 simp_arg_type\n  | symm_expr : pexpr \u2192 simp_arg_type\n  deriving has_reflect\n#align tactic.simp_arg_type tactic.simp_arg_type\n\nunsafe instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type :=\n  \u27e8fun a =>\n    match a with\n    | simp_arg_type.all_hyps => pure \"*\"\n    | simp_arg_type.except n => pure f! \"-{n}\"\n    | simp_arg_type.expr e => i_to_expr_no_subgoals e >>= pp\n    | simp_arg_type.symm_expr e => (\u00b7 ++ \u00b7) \"\u2190\" <$> (i_to_expr_no_subgoals e >>= pp)\u27e9\n#align tactic.simp_arg_type_to_tactic_format tactic.simp_arg_type_to_tactic_format\n\nunsafe def simp_arg : parser simp_arg_type :=\n  tk \"*\" *> return simp_arg_type.all_hyps <|>\n    tk \"-\" *> simp_arg_type.except <$> ident <|>\n      tk \"<-\" *> simp_arg_type.symm_expr <$> texpr <|> simp_arg_type.expr <$> texpr\n#align tactic.simp_arg tactic.simp_arg\n\nunsafe def simp_arg_list : parser (List simp_arg_type) :=\n  tk \"*\" *> return [simp_arg_type.all_hyps] <|> list_of simp_arg <|> return []\n#align tactic.simp_arg_list tactic.simp_arg_list\n\nprivate unsafe def resolve_exception_ids (all_hyps : Bool) :\n    List Name \u2192 List Name \u2192 List Name \u2192 tactic (List Name \u00d7 List Name)\n  | [], gex, hex => return (gex.reverse, hex.reverse)\n  | id :: ids, gex, hex => do\n    let p \u2190 resolve_name id\n    let e := p.erase_annotations.get_app_fn.erase_annotations\n    match e with\n      | const n _ => resolve_exception_ids ids (n :: gex) hex\n      | local_const n _ _ _ =>\n        when (Not all_hyps) (fail <| s! \"invalid local exception {id}, '*' was not used\") >>\n          resolve_exception_ids ids gex (n :: hex)\n      | _ => fail <| s! \"invalid exception {id}, unknown identifier\"\n#align tactic.resolve_exception_ids tactic.resolve_exception_ids\n\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`.\n  This version fails when an argument of the form `simp_arg_type.symm_expr`\n  is included, so that `simp`-like tactics that do not (yet) support backwards rewriting\n  should properly report an error but function normally on other inputs.\n-/\nunsafe def decode_simp_arg_list (hs : List simp_arg_type) :\n    tactic <| List pexpr \u00d7 List Name \u00d7 List Name \u00d7 Bool := do\n  let (hs, ex, all) \u2190\n    hs.foldlM\n        (fun (r : List pexpr \u00d7 List Name \u00d7 Bool) h => do\n          let (es, ex, all) := r\n          match h with\n            | simp_arg_type.all_hyps => pure (es, ex, tt)\n            | simp_arg_type.except id => pure (es, id :: ex, all)\n            | simp_arg_type.expr e => pure (e :: es, ex, all)\n            | simp_arg_type.symm_expr _ => fail \"arguments of the form '\u2190...' are not supported\")\n        ([], [], false)\n  let (gex, hex) \u2190 resolve_exception_ids all ex [] []\n  return (hs, gex, hex, all)\n#align tactic.decode_simp_arg_list tactic.decode_simp_arg_list\n\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is the newer version of `decode_simp_arg_list`,\n  and has a new name for backwards compatibility.\n  This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`.\n-/\nunsafe def decode_simp_arg_list_with_symm (hs : List simp_arg_type) :\n    tactic <| List (pexpr \u00d7 Bool) \u00d7 List Name \u00d7 List Name \u00d7 Bool := do\n  let (hs, ex, all) :=\n    hs.foldl\n      (fun r h =>\n        match r, h with\n        | (es, ex, all), simp_arg_type.all_hyps => (es, ex, true)\n        | (es, ex, all), simp_arg_type.except id => (es, id :: ex, all)\n        | (es, ex, all), simp_arg_type.expr e => ((e, false) :: es, ex, all)\n        | (es, ex, all), simp_arg_type.symm_expr e => ((e, true) :: es, ex, all))\n      ([], [], false)\n  let (gex, hex) \u2190 resolve_exception_ids all ex [] []\n  return (hs, gex, hex, all)\n#align tactic.decode_simp_arg_list_with_symm tactic.decode_simp_arg_list_with_symm\n\nprivate unsafe def add_simps : simp_lemmas \u2192 List (Name \u00d7 Bool) \u2192 tactic simp_lemmas\n  | s, [] => return s\n  | s, n :: ns => do\n    let s' \u2190 s.add_simp n.fst n.snd\n    add_simps s' ns\n#align tactic.add_simps tactic.add_simps\n\nprivate unsafe def report_invalid_simp_lemma {\u03b1 : Type} (n : Name) : tactic \u03b1 :=\n  fail\n    f! \"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)\"\n#align tactic.report_invalid_simp_lemma tactic.report_invalid_simp_lemma\n\nprivate unsafe def check_no_overload (p : pexpr) : tactic Unit :=\n  when p.is_choice_macro <|\n    match p with\n    | macro _ ps =>\n      fail <|\n        to_fmt \"ambiguous overload, possible interpretations\" ++\n          format.join (ps.map fun p => (to_fmt p).indent 4)\n    | _ => failed\n#align tactic.check_no_overload tactic.check_no_overload\n\nprivate unsafe def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : List Name) (n : Name)\n    (ref : pexpr) (symm : Bool) : tactic (simp_lemmas \u00d7 List Name) := do\n  let p \u2190 resolve_name n\n  check_no_overload p\n  let-- unpack local refs\n  e := p.erase_annotations.get_app_fn.erase_annotations\n  match e with\n    | const n _ =>\n      (do\n          guard \u00acsymm\n          has_attribute `congr n\n          let s \u2190 s n\n          pure (s, u)) <|>\n        (do\n            let b \u2190 is_valid_simp_lemma_cnst n\n            guard b\n            save_const_type_info n ref\n            let s \u2190 s n symm\n            return (s, u)) <|>\n          (do\n              let eqns \u2190 get_eqn_lemmas_for tt n\n              guard (eqns > 0)\n              save_const_type_info n ref\n              let s \u2190 add_simps s (eqns fun e => (e, ff))\n              return (s, u)) <|>\n            (do\n                let env \u2190 get_env\n                guard (env n).isSome\n                return (s, n :: u)) <|>\n              report_invalid_simp_lemma n\n    | _ =>\n      (do\n          let e \u2190 i_to_expr_no_subgoals p\n          let b \u2190 is_valid_simp_lemma e\n          guard b\n          try (save_type_info e ref)\n          let s \u2190 s e symm\n          return (s, u)) <|>\n        report_invalid_simp_lemma n\n#align tactic.simp_lemmas.resolve_and_add tactic.simp_lemmas.resolve_and_add\n\nprivate unsafe def simp_lemmas.add_pexpr (s : simp_lemmas) (u : List Name) (p : pexpr)\n    (symm : Bool) : tactic (simp_lemmas \u00d7 List Name) :=\n  match p with\n  | const c [] => simp_lemmas.resolve_and_add s u c p symm\n  | local_const c _ _ _ => simp_lemmas.resolve_and_add s u c p symm\n  | _ => do\n    let new_e \u2190 i_to_expr_no_subgoals p\n    let s \u2190 s.add new_e symm\n    return (s, u)\n#align tactic.simp_lemmas.add_pexpr tactic.simp_lemmas.add_pexpr\n\nprivate unsafe def simp_lemmas.append_pexprs :\n    simp_lemmas \u2192 List Name \u2192 List (pexpr \u00d7 Bool) \u2192 tactic (simp_lemmas \u00d7 List Name)\n  | s, u, [] => return (s, u)\n  | s, u, l :: ls => do\n    let (s, u) \u2190 simp_lemmas.add_pexpr s u l.fst l.snd\n    simp_lemmas.append_pexprs s u ls\n#align tactic.simp_lemmas.append_pexprs tactic.simp_lemmas.append_pexprs\n\nunsafe def mk_simp_set_core (no_dflt : Bool) (attr_names : List Name) (hs : List simp_arg_type)\n    (at_star : Bool) : tactic (Bool \u00d7 simp_lemmas \u00d7 List Name) := do\n  let (hs, gex, hex, all_hyps) \u2190 decode_simp_arg_list_with_symm hs\n  when (all_hyps \u2227 at_star \u2227 Not hex) <|\n      fail \"A tactic of the form `simp [*, -h] at *` is currently not supported\"\n  let s \u2190 join_user_simp_lemmas no_dflt attr_names\n  let-- Erase `h` from the default simp set for calls of the form `simp [\u2190h]`.\n  to_erase :=\n    hs.foldl\n      (fun l h =>\n        match h with\n        | (const id _, tt) => id :: l\n        | (local_const id _ _ _, tt) => id :: l\n        | _ => l)\n      []\n  let s := s.erase\u2093 to_erase\n  let (s, u) \u2190 simp_lemmas.append_pexprs s [] hs\n  let s \u2190\n    if Not at_star \u2227 all_hyps then do\n        let ctx \u2190 collect_ctx_simps\n        let ctx := ctx.filter\u2093 fun h => h.local_uniq_name \u2209 hex\n        -- remove local exceptions\n            s\n            ctx\n      else return s\n  let gex\n    \u2190-- add equational lemmas, if any\n          gex.mapM\n        fun n => List.cons n <$> get_eqn_lemmas_for true n\n  return (all_hyps, simp_lemmas.erase s <| gex, u)\n#align tactic.mk_simp_set_core tactic.mk_simp_set_core\n\nunsafe def mk_simp_set (no_dflt : Bool) (attr_names : List Name) (hs : List simp_arg_type) :\n    tactic (simp_lemmas \u00d7 List Name) :=\n  Prod.snd <$> mk_simp_set_core no_dflt attr_names hs false\n#align tactic.mk_simp_set tactic.mk_simp_set\n\nend MkSimpSet\n\nnamespace Interactive\n\nopen _Root_.Interactive Interactive.Types Expr\n\nunsafe def simp_core_aux (cfg : SimpConfig) (discharger : tactic Unit) (s : simp_lemmas)\n    (u : List Name) (hs : List expr) (tgt : Bool) : tactic name_set := do\n  let (to_remove, lmss) \u2190\n    @List.foldlM tactic _ (List expr \u00d7 name_set) _\n        (fun \u27e8hs, lms\u27e9 h => do\n          let h_type \u2190 infer_type h\n          (do\n                let (new_h_type, pr, new_lms) \u2190 simplify s u h_type cfg `eq discharger\n                assert h new_h_type\n                (mk_eq_mp pr h >>= tactic.exact) >> return (h :: hs, lms new_lms)) <|>\n              return (hs, lms))\n        ([], mk_name_set) hs\n  let (lms, goal_simplified) \u2190\n    if tgt then\n        (simp_target s u cfg discharger >>= fun ns => return (ns, true)) <|>\n          return (mk_name_set, false)\n      else return (mk_name_set, false)\n  guard (cfg = ff \u2228 to_remove > 0 \u2228 goal_simplified) <|> fail \"simplify tactic failed to simplify\"\n  to_remove fun h => try (clear h)\n  return (lmss lms)\n#align tactic.interactive.simp_core_aux tactic.interactive.simp_core_aux\n\nunsafe def simp_core (cfg : SimpConfig) (discharger : tactic Unit) (no_dflt : Bool)\n    (hs : List simp_arg_type) (attr_names : List Name) (locat : Loc) : tactic name_set := do\n  let lms \u2190\n    match locat with\n      | loc.wildcard => do\n        let (all_hyps, s, u) \u2190 mk_simp_set_core no_dflt attr_names hs true\n        if all_hyps then tactic.simp_all s u cfg discharger\n          else do\n            let hyps \u2190 non_dep_prop_hyps\n            simp_core_aux cfg discharger s u hyps tt\n      | _ => do\n        let (s, u) \u2190 mk_simp_set no_dflt attr_names hs\n        let ns \u2190 locat.get_locals\n        simp_core_aux cfg discharger s u ns locat\n  try tactic.triv\n  try (tactic.reflexivity reducible)\n  return lms\n#align tactic.interactive.simp_core tactic.interactive.simp_core\n\n/--\nThe `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.\n\n`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.\n\n`simp [h\u2081 h\u2082 ... h\u2099]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h\u1d62`'s, where the `h\u1d62`'s are expressions. If `h\u1d62` is preceded by left arrow (`\u2190` or `<-`), the simplification is performed in the reverse direction. If an `h\u1d62` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.\n\n`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.\n\n`simp *` is a shorthand for `simp [*]`.\n\n`simp only [h\u2081 h\u2082 ... h\u2099]` is like `simp [h\u2081 h\u2082 ... h\u2099]` but does not use `[simp]` lemmas\n\n`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id\u1d62`.\n\n`simp at h\u2081 h\u2082 ... h\u2099` simplifies the non-dependent hypotheses `h\u2081 : T\u2081` ... `h\u2099 : T\u2099`. The tactic fails if the target or another hypothesis depends on one of them. The token `\u22a2` or `|-` can be added to the list to include the target.\n\n`simp at *` simplifies all the hypotheses and the target.\n\n`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.\n\n`simp with attr\u2081 ... attr\u2099` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr\u2081]`, ..., `[attr\u2099]` or `[simp]`.\n-/\nunsafe def simp (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    (locat : parse location) (cfg : simp_config_ext := { }) : tactic Unit :=\n  let cfg :=\n    match use_iota_eqn, trace_lemmas with\n    | none, none => cfg\n    | some _, none => { cfg with iotaEqn := true }\n    | none, some _ => { cfg with traceLemmas := true }\n    | some _, some _ =>\n      { cfg with\n        iotaEqn := true\n        traceLemmas := true }\n  propagate_tags do\n    let lms \u2190 simp_core cfg.toSimpConfig cfg.discharger no_dflt hs attr_names locat\n    if cfg then trace (\u2191\"Try this: simp only \" ++ to_fmt lms) else skip\n#align tactic.interactive.simp tactic.interactive.simp\n\n/-- Just construct the simp set and trace it. Used for debugging.\n-/\nunsafe def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n    (attr_names : parse with_ident_list) : tactic Unit := do\n  let (s, _) \u2190 mk_simp_set no_dflt attr_names hs\n  s >>= trace\n#align tactic.interactive.trace_simp_set tactic.interactive.trace_simp_set\n\n/--\n`simp_intros h\u2081 h\u2082 ... h\u2099` is similar to `intros h\u2081 h\u2082 ... h\u2099` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.\n\nAs with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.\n-/\nunsafe def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n    (attr_names : parse with_ident_list) (cfg : SimpIntrosConfig := { }) : tactic Unit := do\n  let (s, u) \u2190 mk_simp_set no_dflt attr_names hs\n  when (\u00acu) (fail s! \"simp_intros tactic does not support {u}\")\n  tactic.simp_intros s u ids cfg\n  try triv >> try (reflexivity reducible)\n#align tactic.interactive.simp_intros tactic.interactive.simp_intros\n\nprivate unsafe def to_simp_arg_list (symms : List Bool) (es : List pexpr) : List simp_arg_type :=\n  (symms.zip es).map fun \u27e8s, e\u27e9 => if s then simp_arg_type.symm_expr e else simp_arg_type.expr e\n#align tactic.interactive.to_simp_arg_list tactic.interactive.to_simp_arg_list\n\n/-- `dsimp` is similar to `simp`, except that it only uses definitional equalities.\n-/\nunsafe def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list)\n    (attr_names : parse with_ident_list) (l : parse location) (cfg : DsimpConfig := { }) :\n    tactic Unit := do\n  let (s, u) \u2190 mk_simp_set no_dflt attr_names es\n  match l with\n    | loc.wildcard =>/- Remark: we cannot revert frozen local instances.\n         We disable zeta expansion because to prevent `intron n` from failing.\n         Another option is to put a \"marker\" at the current target, and\n         implement `intro_upto_marker`. -/\n    do\n      let n \u2190 revert_all\n      dsimp_target s u { cfg with zeta := ff }\n      intron n\n    | _ => l (fun h => dsimp_hyp h s u cfg) (dsimp_target s u cfg)\n#align tactic.interactive.dsimp tactic.interactive.dsimp\n\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.\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/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.\n-/\nunsafe def symmetry : tactic Unit :=\n  tactic.symmetry\n#align tactic.interactive.symmetry tactic.interactive.symmetry\n\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.\n\n`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.\n-/\nunsafe def transitivity (q : parse texpr ?) : tactic Unit :=\n  tactic.transitivity >>\n    match q with\n    | none => skip\n    | some q => do\n      let (r, lhs, rhs) \u2190 target_lhs_rhs\n      i_to_expr q >>= unify rhs\n#align tactic.interactive.transitivity tactic.interactive.transitivity\n\n/--\nProves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.\n-/\nunsafe def ac_reflexivity : tactic Unit :=\n  tactic.ac_refl\n#align tactic.interactive.ac_reflexivity tactic.interactive.ac_reflexivity\n\n/-- An abbreviation for `ac_reflexivity`.\n-/\nunsafe def ac_refl : tactic Unit :=\n  tactic.ac_refl\n#align tactic.interactive.ac_refl tactic.interactive.ac_refl\n\n/-- Tries to prove the main goal using congruence closure.\n-/\nunsafe def cc : tactic Unit :=\n  tactic.cc\n#align tactic.interactive.cc tactic.interactive.cc\n\n/--\nGiven hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\n-/\nunsafe def subst (q : parse texpr) : tactic Unit :=\n  (i_to_expr q >>= tactic.subst) >> try (tactic.reflexivity reducible)\n#align tactic.interactive.subst tactic.interactive.subst\n\n/-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.\n-/\nunsafe def subst_vars : tactic Unit :=\n  tactic.subst_vars\n#align tactic.interactive.subst_vars tactic.interactive.subst_vars\n\n/-- `clear h\u2081 ... h\u2099` tries to clear each hypothesis `h\u1d62` from the local context.\n-/\nunsafe def clear : parse ident* \u2192 tactic Unit :=\n  tactic.clear_lst\n#align tactic.interactive.clear tactic.interactive.clear\n\nprivate unsafe def to_qualified_name_core : Name \u2192 List Name \u2192 tactic Name\n  | n, [] => fail <| \"unknown declaration '\" ++ toString n ++ \"'\"\n  | n, ns :: nss => do\n    let curr \u2190 return <| ns ++ n\n    let env \u2190 get_env\n    if env curr then return curr else to_qualified_name_core n nss\n#align tactic.interactive.to_qualified_name_core tactic.interactive.to_qualified_name_core\n\nprivate unsafe def to_qualified_name (n : Name) : tactic Name := do\n  let env \u2190 get_env\n  if env n then return n\n    else do\n      let ns \u2190 open_namespaces\n      to_qualified_name_core n ns\n#align tactic.interactive.to_qualified_name tactic.interactive.to_qualified_name\n\nprivate unsafe def to_qualified_names : List Name \u2192 tactic (List Name)\n  | [] => return []\n  | c :: cs => do\n    let new_c \u2190 to_qualified_name c\n    let new_cs \u2190 to_qualified_names cs\n    return (new_c :: new_cs)\n#align tactic.interactive.to_qualified_names tactic.interactive.to_qualified_names\n\n/-- Similar to `unfold`, but only uses definitional equalities.\n-/\nunsafe def dunfold (cs : parse ident*) (l : parse location) (cfg : DunfoldConfig := { }) :\n    tactic Unit :=\n  match l with\n  | loc.wildcard => do\n    let ls \u2190 tactic.local_context\n    let n \u2190 revert_lst ls\n    let new_cs \u2190 to_qualified_names cs\n    dunfold_target new_cs cfg\n    intron n\n  | _ => do\n    let new_cs \u2190 to_qualified_names cs\n    l (fun h => dunfold_hyp cs h cfg) (dunfold_target new_cs cfg)\n#align tactic.interactive.dunfold tactic.interactive.dunfold\n\nprivate unsafe def delta_hyps : List Name \u2192 List Name \u2192 tactic Unit\n  | cs, [] => skip\n  | cs, h :: hs => (get_local h >>= delta_hyp cs) >> delta_hyps cs hs\n#align tactic.interactive.delta_hyps tactic.interactive.delta_hyps\n\n/--\nSimilar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.\n-/\nunsafe def delta : parse ident* \u2192 parse location \u2192 tactic Unit\n  | cs, loc.wildcard => do\n    let ls \u2190 tactic.local_context\n    let n \u2190 revert_lst ls\n    let new_cs \u2190 to_qualified_names cs\n    delta_target new_cs\n    intron n\n  | cs, l => do\n    let new_cs \u2190 to_qualified_names cs\n    l (delta_hyp new_cs) (delta_target new_cs)\n#align tactic.interactive.delta tactic.interactive.delta\n\nprivate unsafe def unfold_projs_hyps (cfg : UnfoldProjConfig := { }) (hs : List Name) :\n    tactic Bool :=\n  hs.foldlM\n    (fun r h => do\n      let h \u2190 get_local h\n      unfold_projs_hyp h cfg >> return tt <|> return r)\n    false\n#align tactic.interactive.unfold_projs_hyps tactic.interactive.unfold_projs_hyps\n\n/-- This tactic unfolds all structure projections.\n-/\nunsafe def unfold_projs (l : parse location) (cfg : UnfoldProjConfig := { }) : tactic Unit :=\n  match l with\n  | loc.wildcard => do\n    let ls \u2190 local_context\n    let b\u2081 \u2190 unfold_projs_hyps cfg (ls.map expr.local_pp_name)\n    let b\u2082 \u2190 tactic.unfold_projs_target cfg >> return true <|> return false\n    when (Not b\u2081 \u2227 Not b\u2082) (fail \"unfold_projs failed to simplify\")\n  | _ =>\n    l.try_apply (fun h => unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|>\n      fail \"unfold_projs failed to simplify\"\n#align tactic.interactive.unfold_projs tactic.interactive.unfold_projs\n\nend Interactive\n\nunsafe def ids_to_simp_arg_list (tac_name : Name) (cs : List Name) : tactic (List simp_arg_type) :=\n  cs.mapM fun c => do\n    let n \u2190 resolve_name c\n    let hs \u2190 get_eqn_lemmas_for false n.const_name\n    let env \u2190 get_env\n    let p := env.is_projection n.const_name\n    when (hs \u2227 p)\n        (fail\n          s! \"{tac_name } tactic failed, {c} does not have equational lemmas nor is a projection\")\n    return <| simp_arg_type.expr (expr.const c [])\n#align tactic.ids_to_simp_arg_list tactic.ids_to_simp_arg_list\n\nstructure UnfoldConfig extends SimpConfig where\n  zeta := false\n  proj := false\n  eta := false\n  canonizeInstances := false\n  constructorEq := false\n#align tactic.unfold_config Tactic.UnfoldConfig\n\nnamespace Interactive\n\nopen _Root_.Interactive Interactive.Types Expr\n\n/--\nGiven defined constants `e\u2081 ... e\u2099`, `unfold e\u2081 ... e\u2099` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.\n\nAs with `simp`, the `at` modifier can be used to specify locations for the unfolding.\n-/\nunsafe def unfold (cs : parse ident*) (locat : parse location) (cfg : UnfoldConfig := { }) :\n    tactic Unit := do\n  let es \u2190 ids_to_simp_arg_list \"unfold\" cs\n  let no_dflt := true\n  simp_core cfg failed no_dflt es [] locat\n  skip\n#align tactic.interactive.unfold tactic.interactive.unfold\n\n/-- Similar to `unfold`, but does not iterate the unfolding.\n-/\nunsafe def unfold1 (cs : parse ident*) (locat : parse location)\n    (cfg : UnfoldConfig := { singlePass := true }) : tactic Unit :=\n  unfold cs locat cfg\n#align tactic.interactive.unfold1 tactic.interactive.unfold1\n\n/-- If the target of the main goal is an `opt_param`, assigns the default value.\n-/\nunsafe def apply_opt_param : tactic Unit :=\n  tactic.apply_opt_param\n#align tactic.interactive.apply_opt_param tactic.interactive.apply_opt_param\n\n/-- If the target of the main goal is an `auto_param`, executes the associated tactic.\n-/\nunsafe def apply_auto_param : tactic Unit :=\n  tactic.apply_auto_param\n#align tactic.interactive.apply_auto_param tactic.interactive.apply_auto_param\n\n/-- Fails if the given tactic succeeds.\n-/\nunsafe def fail_if_success (tac : itactic) : tactic Unit :=\n  tactic.fail_if_success tac\n#align tactic.interactive.fail_if_success tactic.interactive.fail_if_success\n\n/-- Succeeds if the given tactic fails.\n-/\nunsafe def success_if_fail (tac : itactic) : tactic Unit :=\n  tactic.success_if_fail tac\n#align tactic.interactive.success_if_fail tactic.interactive.success_if_fail\n\nunsafe def guard_expr_eq (t : expr) (p : parse <| tk \":=\" *> texpr) : tactic Unit := do\n  let e \u2190 to_expr p\n  guard (alpha_eqv t e)\n#align tactic.interactive.guard_expr_eq tactic.interactive.guard_expr_eq\n\n/-- `guard_target t` fails if the target of the main goal is not `t`.\nWe use this tactic for writing tests.\n-/\nunsafe def guard_target (p : parse texpr) : tactic Unit := do\n  let t \u2190 target\n  guard_expr_eq t p\n#align tactic.interactive.guard_target tactic.interactive.guard_target\n\n/-- `guard_hyp h : t` fails if the hypothesis `h` does not have type `t`.\nWe use this tactic for writing tests.\n-/\nunsafe def guard_hyp (n : parse ident) (ty : parse (tk \":\" *> texpr)?)\n    (val : parse (tk \":=\" *> texpr)?) : tactic Unit := do\n  let h \u2190 get_local n\n  let ldecl \u2190\n    tactic.unsafe.type_context.run do\n        let lctx \u2190 unsafe.type_context.get_local_context\n        pure <| lctx h\n  let ldecl \u2190 ldecl |\n    fail f! \"hypothesis {h} not found\"\n  match ty with\n    | some p => guard_expr_eq ldecl p\n    | none => skip\n  match ldecl, val with\n    | none, some _ => fail f! \"{h} is not a let binding\"\n    | some _, none => fail f! \"{h} is a let binding\"\n    | some hval, some val => guard_expr_eq hval val\n    | none, none => skip\n#align tactic.interactive.guard_hyp tactic.interactive.guard_hyp\n\n/-- `match_target t` fails if target does not match pattern `t`.\n-/\nunsafe def match_target (t : parse texpr) (m := reducible) : tactic Unit :=\n  tactic.match_target t m >> skip\n#align tactic.interactive.match_target tactic.interactive.match_target\n\n/-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and\n`h : \u00ac p` in the second branch. You can specify the name of the new hypothesis using the syntax\n`by_cases h : p`.\n-/\nunsafe def by_cases : parse cases_arg_p \u2192 tactic Unit\n  | (n, q) =>\n    concat_tags do\n      let p \u2190 tactic.to_expr_strict q\n      tactic.by_cases p (n `h)\n      let pos_g :: neg_g :: rest \u2190 get_goals\n      return [(`pos, pos_g), (`neg, neg_g)]\n#align tactic.interactive.by_cases tactic.interactive.by_cases\n\n/-- Apply function extensionality and introduce new hypotheses.\nThe tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to\n```\n  |-  ((fun x, ...) = (fun x, ...))\n```\nThe variant `funext h\u2081 ... h\u2099` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.\n-/\nunsafe def funext : parse ident_* \u2192 tactic Unit\n  | [] => tactic.funext >> skip\n  | hs => funext_lst hs >> skip\n#align tactic.interactive.funext tactic.interactive.funext\n\n/--\nIf the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contradiction h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\nunsafe def by_contradiction (n : parse ident ?) : tactic Unit :=\n  tactic.by_contradiction (n.getD `h) $> ()\n#align tactic.interactive.by_contradiction tactic.interactive.by_contradiction\n\n/--\nIf the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contra h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\nunsafe def by_contra (n : parse ident ?) : tactic Unit :=\n  by_contradiction n\n#align tactic.interactive.by_contra tactic.interactive.by_contra\n\n/-- Type check the given expression, and trace its type.\n-/\nunsafe def type_check (p : parse texpr) : tactic Unit := do\n  let e \u2190 to_expr p\n  tactic.type_check e\n  infer_type e >>= trace\n#align tactic.interactive.type_check tactic.interactive.type_check\n\n/-- Fail if there are unsolved goals.\n-/\nunsafe def done : tactic Unit :=\n  tactic.done\n#align tactic.interactive.done tactic.interactive.done\n\nprivate unsafe def show_aux (p : pexpr) : List expr \u2192 List expr \u2192 tactic Unit\n  | [], r => fail \"show tactic failed\"\n  | g :: gs, r => do\n    (do\n          set_goals [g]\n          let g_ty \u2190 target\n          let ty \u2190 i_to_expr p\n          unify g_ty ty\n          set_goals (g :: r ++ gs)\n          tactic.change ty) <|>\n        show_aux gs (g :: r)\n#align tactic.interactive.show_aux tactic.interactive.show_aux\n\n/--\n`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.\n-/\nunsafe def show (q : parse texpr) : tactic Unit := do\n  let gs \u2190 get_goals\n  show_aux q gs []\n#align tactic.interactive.show tactic.interactive.show\n\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a\u2081` ... `a\u2099`. The tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099` and tries to clear the previous one.\n-/\nunsafe def specialize (p : parse texpr) : tactic Unit :=\n  focus1 do\n    let e \u2190 i_to_expr p\n    let h := expr.get_app_fn e\n    if h then (tactic.note h none e >> try (tactic.clear h)) >> rotate 1\n      else\n        tactic.fail\n          \"specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context\"\n#align tactic.interactive.specialize tactic.interactive.specialize\n\nunsafe def congr :=\n  tactic.congr\n#align tactic.interactive.congr tactic.interactive.congr\n\nend Interactive\n\nend Tactic\n\nsection AddInteractive\n\nopen Tactic\n\n-- See add_interactive\nprivate unsafe def add_interactive_aux (new_namespace : Name) : List Name \u2192 Tactic\n  | [] => return ()\n  | n :: ns => do\n    let env \u2190 get_env\n    let d_name \u2190 resolve_constant n\n    let declaration.defn _ ls ty val hints trusted \u2190 env.get d_name\n    let Name.mk_string h _ \u2190 return d_name\n    let new_name := .str new_namespace h\n    add_decl (declaration.defn new_name ls ty (expr.const d_name (ls level.param)) hints trusted)\n    (do\n          let doc \u2190 doc_string d_name\n          add_doc_string new_name doc) <|>\n        skip\n    add_interactive_aux ns\n#align add_interactive_aux add_interactive_aux\n\n/-- Copy a list of meta definitions in the current namespace to tactic.interactive.\n\nThis command is useful when we want to update tactic.interactive without closing the current namespace.\n-/\nunsafe def add_interactive (ns : List Name) (p : Name := `tactic.interactive) : Tactic :=\n  add_interactive_aux p ns\n#align add_interactive add_interactive\n\nunsafe def has_dup : tactic Bool := do\n  let ctx \u2190 local_context\n  let p : name_set \u00d7 Bool :=\n    ctx.foldl\n      (fun \u27e8s, r\u27e9 h =>\n        if r then (s, r)\n        else if s.contains h.local_pp_name then (s, true) else (s.insert h.local_pp_name, false))\n      (mk_name_set, false)\n  return p.2\n#align has_dup has_dup\n\n/-- Renames hypotheses with the same name.\n-/\nunsafe def dedup : tactic Unit :=\n  whenM has_dup do\n    let ctx \u2190 local_context\n    let n \u2190 revert_lst ctx\n    intron n\n#align dedup dedup\n\nend AddInteractive\n\nnamespace Tactic\n\n-- Helper tactic for `mk_inj_eq\nprotected unsafe def apply_inj_lemma : tactic Unit := do\n  let h \u2190 intro `h\n  let some (lhs, rhs) \u2190 expr.is_eq <$> infer_type h\n  let expr.const C _ \u2190 return lhs.get_app_fn\n  -- We disable auto_param and opt_param support to address issue #1943\n      applyc\n      (Name.mk_string \"inj\" C)\n      { autoParam\u2093 := ff\n        optParam := ff }\n  assumption\n#align tactic.apply_inj_lemma tactic.apply_inj_lemma\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.\n   These lemmas are automatically generated by the equation compiler.\n   Example:\n   ```\n   list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 \u2227 t1 = t2) :=\n   by mk_inj_eq\n   ```\n-/\nunsafe def mk_inj_eq : tactic Unit :=\n  sorry\n#align tactic.mk_inj_eq tactic.mk_inj_eq\n\n/-\n     We use `_root_.*` in the following tactics because\n     names are resolved at tactic execution time in interactive mode.\n     See PR #1913\n\n     TODO(Leo): This is probably not the only instance of this problem.\n     `[ ... ] blocks are convenient to use because they allow us to use the interactive\n     mode to write non interactive tactics.\n     One potential fix for this issue is to resolve names in `[ ... ] at tactic\n     compilation time.\n     After this issue is fixed, we should remove the `_root_.*` workaround.\n  -/\nend Tactic\n\n/-! Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/\n\n\nuniverse u v\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem Sum.inl.inj_eq {\u03b1 : Type u} (\u03b2 : Type v) (a\u2081 a\u2082 : \u03b1) :\n    (@Sum.inl \u03b1 \u03b2 a\u2081 = Sum.inl a\u2082) = (a\u2081 = a\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align sum.inl.inj_eq Sum.inl.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem Sum.inr.inj_eq (\u03b1 : Type u) {\u03b2 : Type v} (b\u2081 b\u2082 : \u03b2) :\n    (@Sum.inr \u03b1 \u03b2 b\u2081 = Sum.inr b\u2082) = (b\u2081 = b\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align sum.inr.inj_eq Sum.inr.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem PSum.inl.inj_eq {\u03b1 : Sort u} (\u03b2 : Sort v) (a\u2081 a\u2082 : \u03b1) :\n    (@PSum.inl \u03b1 \u03b2 a\u2081 = PSum.inl a\u2082) = (a\u2081 = a\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align psum.inl.inj_eq PSum.inl.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem PSum.inr.inj_eq (\u03b1 : Sort u) {\u03b2 : Sort v} (b\u2081 b\u2082 : \u03b2) :\n    (@PSum.inr \u03b1 \u03b2 b\u2081 = PSum.inr b\u2082) = (b\u2081 = b\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align psum.inr.inj_eq PSum.inr.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem Sigma.mk.inj_eq {\u03b1 : Type u} {\u03b2 : \u03b1 \u2192 Type v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) :\n    (Sigma.mk a\u2081 b\u2081 = Sigma.mk a\u2082 b\u2082) = (a\u2081 = a\u2082 \u2227 HEq b\u2081 b\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align sigma.mk.inj_eq Sigma.mk.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem PSigma.mk.inj_eq {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) :\n    (PSigma.mk a\u2081 b\u2081 = PSigma.mk a\u2082 b\u2082) = (a\u2081 = a\u2082 \u2227 HEq b\u2081 b\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align psigma.mk.inj_eq PSigma.mk.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem Subtype.mk.inj_eq {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} (a\u2081 : \u03b1) (h\u2081 : p a\u2081) (a\u2082 : \u03b1) (h\u2082 : p a\u2082) :\n    (Subtype.mk a\u2081 h\u2081 = Subtype.mk a\u2082 h\u2082) = (a\u2081 = a\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align subtype.mk.inj_eq Subtype.mk.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem Option.some.inj_eq {\u03b1 : Type u} (a\u2081 a\u2082 : \u03b1) : (some a\u2081 = some a\u2082) = (a\u2081 = a\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align option.some.inj_eq Option.some.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem List.cons.inj_eq {\u03b1 : Type u} (h\u2081 : \u03b1) (t\u2081 : List \u03b1) (h\u2082 : \u03b1) (t\u2082 : List \u03b1) :\n    (List.cons h\u2081 t\u2081 = List.cons h\u2082 t\u2082) = (h\u2081 = h\u2082 \u2227 t\u2081 = t\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align list.cons.inj_eq List.cons.inj_eq\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_inj_eq -/\ntheorem Nat.succ.inj_eq (n\u2081 n\u2082 : Nat) : (Nat.succ n\u2081 = Nat.succ n\u2082) = (n\u2081 = n\u2082) := by\n  run_tac\n    tactic.mk_inj_eq\n#align nat.succ.inj_eq Nat.succ.inj_eq\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/Interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074556640652345, "lm_q2_score": 0.057493284452614264, "lm_q1q2_score": 0.017290850397272847}}
{"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 \u27e8.nil, .nil\u27e9 P \u2192\n  \u22a2 P\n:= by\n  simp only [envs_entails, of_envs, big_op]\n  rw' [intuitionistically_True_emp, (left_id : emp \u2217 _ \u22a3\u22a2 _)]\n  intro h\n  exact h\n\ntheorem tac_stop [BI PROP] {\u0393\u209a \u0393\u209b : Env PROP} (P : PROP) :\n  let Ps := match \u0393\u209a, \u0393\u209b with\n    | .nil, .nil => `[iprop| emp]\n    | _   , .nil => `[iprop| \u25a1 [\u2227] \u0393\u209a]\n    | .nil, _    => `[iprop| [\u2217] \u0393\u209b]\n    | _   , _    => `[iprop| \u25a1 [\u2227] \u0393\u209a \u2217 [\u2217] \u0393\u209b]\n  (Ps \u22a2 P) \u2192\n  envs_entails \u27e8\u0393\u209a, \u0393\u209b\u27e9 P\n:= by\n  cases \u0393\u209a\n  <;> cases \u0393\u209b\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 : _ \u2217 emp \u22a3\u22a2 _)]\n  all_goals\n    rw' [intuitionistically_True_emp, (left_id : emp \u2217 _ \u22a3\u22a2 _)]\n\ntheorem tac_clear [BI PROP] {\u0394 : Envs PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [TCIte p TCTrue (TCOr (Affine P) (Absorbing Q))] \u2192\n  envs_entails (\u0394.delete true i) Q \u2192\n  envs_entails \u0394 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] {\u0394 : Envs PROP} {a : Bool} {\u03c6 : Prop} (Q : PROP) :\n  [FromPure a Q \u03c6] \u2192\n  [TCIte a (AffineEnv \u0394.spatial) TCTrue] \u2192\n  \u03c6 \u2192\n  envs_entails \u0394 Q\n:= by\n  simp only [envs_entails]\n  intro _ inst_affine_env h\u03c6\n  rw' [\u2190 from_pure]\n  cases a\n  case false =>\n    apply pure_intro\n    exact h\u03c6\n  case true =>\n    cases inst_affine_env\n    simp only [of_envs, bi_affinely_if]\n    rw' [\n      affine,\n      pure_True h\u03c6,\n      affinely_True_emp,\n      affinely_emp]\n\n-- implication and wand\ntheorem tac_impl_intro [BI PROP] {\u0394 : Envs PROP} {P Q : PROP} (R : PROP) :\n  [FromImpl R P Q] \u2192\n  [TCIte \u0394.spatial.isEmpty TCTrue (Persistent P)] \u2192\n  [FromAffinely P' P] \u2192\n  envs_entails (\u0394.append false P') Q \u2192\n  envs_entails \u0394 R\n:= by\n  simp only [envs_entails]\n  intro _ inst_pers _ h_entails\n  rw' [\u2190 from_impl]\n  cases h_empty : \u0394.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 : <affine>?true P \u22a2 _),\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 : <affine>?true P \u22a2 _)]\n    simp only [bi_intuitionistically]\n    rw' [\n      \u2190 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] {\u0394 : Envs PROP} {P P' Q : PROP} (R : PROP) :\n  [FromImpl R P Q] \u2192\n  [IntoPersistent false P P'] \u2192\n  envs_entails (\u0394.append true P') Q \u2192\n  envs_entails \u0394 R\n:= by\n  simp only [envs_entails]\n  intro _ _ h_entails\n  rw' [\u2190 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] {\u0394 : Envs PROP} {P Q : PROP} (R : PROP) :\n  [FromImpl R P Q] \u2192\n  envs_entails \u0394 Q \u2192\n  envs_entails \u0394 R\n:= by\n  simp only [envs_entails]\n  intro _ h_entails\n  rw' [\u2190 from_impl]\n  apply impl_intro_l\n  rw' [and_elim_r, h_entails]\n\ntheorem tac_wand_intro [BI PROP] {\u0394 : Envs PROP} {P Q : PROP} (R : PROP) :\n  [FromWand R P Q] \u2192\n  envs_entails (\u0394.append false P) Q \u2192\n  envs_entails \u0394 R\n:= by\n  simp only [envs_entails]\n  intro _ h_entails\n  rw' [\n    \u2190 from_wand,\n    envs_append_sound false P,\n    h_entails]\n\ntheorem tac_wand_intro_intuitionistic [BI PROP] {\u0394 : Envs PROP} {P P' Q : PROP} (R : PROP) :\n  [FromWand R P Q] \u2192\n  [IntoPersistent false P P'] \u2192\n  [TCOr (Affine P) (Absorbing Q)] \u2192\n  envs_entails (\u0394.append true P') Q \u2192\n  envs_entails \u0394 R\n:= by\n  simp only [envs_entails]\n  intro _ _ inst_affine_absorbing h_entails\n  rw' [\u2190 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      \u2190 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      \u2190 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] {\u0394 : Envs PROP} (rpPremise rpWand : Bool) (i j : EnvsIndex.of \u0394) (h_ne : i.type = j.type \u2192 i.val \u2260 j.val) {P2 : PROP} (R : PROP) :\n  let (p, P1) := \u0394.lookup i\n  let \u0394' := \u0394.delete rpPremise i\n  let j' := \u0394.updateIndexAfterDelete rpPremise i j h_ne\n  let (q, Q) := \u0394'.lookup j'\n  [IntoWand q p Q P1 P2] \u2192\n  envs_entails (\u0394'.replace rpWand j' (p && q) P2) R \u2192\n  envs_entails \u0394 R\n:= by\n  intro_let p P1 h_lookup_i\n  intro \u0394' 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 : \u25a1?q Q \u22a2 \u25a1?false P1 -\u2217 P2)]\n    simp only [bi_intuitionistically_if, Bool.false_and, ite_false]\n    rw' [(assoc : P1 \u2217 _ \u22a3\u22a2 _), !wand_elim_r, h_entails]\n  case true =>\n    simp only [Bool.true_and, \u2190 intuitionistically_if_intro_true]\n    rw' [\n      \u2190 intuitionistically_idemp,\n      \u2190 intuitionistically_if_idemp,\n      intuitionistically_intuitionistically_if q,\n      (IntoWand.into_wand : \u25a1?q Q \u22a2 \u25a1?true P1 -\u2217 P2),\n      (assoc : \u25a1?q \u25a1 P1 \u2217 _ \u22a3\u22a2 _),\n      intuitionistically_if_sep_2,\n      !wand_elim_r,\n      h_entails]\n\ntheorem tac_specialize_forall [BI PROP] {\u0394 : Envs PROP} (rpWand : Bool) (i : EnvsIndex.of \u0394) {\u03a6 : \u03b1 \u2192 PROP} (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [IntoForall P \u03a6] \u2192\n  (\u2203 x, envs_entails (\u0394.replace rpWand i p (\u03a6 x)) Q) \u2192\n  envs_entails \u0394 Q\n:= by\n  intro_let p P h_lookup\n  simp only [envs_entails]\n  intro _ \u27e8x, h_entails\u27e9\n  rw' [\n    envs_lookup_replace_sound rpWand p (\u03a6 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] {\u0394 : Envs PROP} {\u03a8 : \u03b1 \u2192 PROP} (Q : PROP) :\n  [FromForall Q \u03a8] \u2192\n  (\u2200 a, envs_entails \u0394 `[iprop| \u03a8 a]) \u2192\n  envs_entails \u0394 Q\n:= by\n  simp only [envs_entails]\n  intro _ h_entails\n  rw' [\u2190 from_forall]\n  apply forall_intro\n  exact h_entails\n\n-- exist\ntheorem tac_exist [BI PROP] {\u0394 : Envs PROP} {\u03a6 : \u03b1 \u2192 PROP} (P : PROP) :\n  [FromExist P \u03a6] \u2192\n  (\u2203 a, envs_entails \u0394 `[iprop| \u03a6 a]) \u2192\n  envs_entails \u0394 P\n:= by\n  simp only [envs_entails]\n  intro _ \u27e8a, h_entails\u27e9\n  rw' [\u2190 from_exist, \u2190 exist_intro a, h_entails]\n\ntheorem tac_exist_destruct [BI PROP] {\u0394 : Envs PROP} (i : EnvsIndex.of \u0394) {\u03a6 : \u03b1 \u2192 PROP} (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [IntoExist P \u03a6] \u2192\n  (\u2200 a, envs_entails (\u0394.replace true i p (\u03a6 a)) Q) \u2192\n  envs_entails \u0394 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 (\u03a6 a),\n    wand_elim_r,\n    h_entails a]\n\n-- emp\ntheorem tac_emp_intro [BI PROP] {\u0393\u209a \u0393\u209b : Env PROP} :\n  [AffineEnv \u0393\u209b] \u2192\n  envs_entails \u27e8\u0393\u209a, \u0393\u209b\u27e9 `[iprop| emp]\n:= by\n  intro _\n  simp only [envs_entails, of_envs]\n  rw' [\n    affinely_elim_emp,\n    (affine : [\u2217] \u0393\u209b.toList \u22a2 emp),\n    (left_id : emp \u2217 _ \u22a3\u22a2 _)]\n\n-- assumptions\ntheorem tac_assumption_lean [BI PROP] {\u0394 : Envs PROP} {P : PROP} (Q : PROP) :\n  (\u22a2 P) \u2192\n  [FromAssumption true P Q] \u2192\n  [TCIte \u0394.spatial.isEmpty TCTrue (TCOr (Absorbing Q) (AffineEnv \u0394.spatial))] \u2192\n  envs_entails \u0394 Q\n:= by\n  simp only [envs_entails]\n  intro h_P _ inst_absorbing_affine_env\n  rw' [\n    \u2190 (left_id : emp \u2217 of_envs \u0394 \u22a3\u22a2 _),\n    \u2190 intuitionistically_emp,\n    h_P,\n    (from_assumption : \u25a1?true P \u22a2 Q)]\n  cases h_empty : \u0394.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] {\u0394 : Envs PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [FromAssumption p P Q] \u2192\n  let \u0394' := \u0394.delete true i\n  [TCIte \u0394'.spatial.isEmpty TCTrue (TCOr (Absorbing Q) (AffineEnv \u0394'.spatial))] \u2192\n  envs_entails \u0394 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 : (\u0394.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 : \u25a1?p P \u22a2 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] {\u0394 : Envs PROP} (Q : PROP) :\n  envs_entails \u0394 `[iprop| False] \u2192\n  envs_entails \u0394 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] {\u0394 : Envs PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (_, P) := \u0394.lookup i\n  P = `[iprop| False] \u2192\n  envs_entails \u0394 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] {\u0394 : Envs PROP} {\u03c6 : Prop} (i : EnvsIndex.of \u0394) (Q : PROP) :\n   let (p, P) := \u0394.lookup i\n  [IntoPure P \u03c6] \u2192\n  [TCIte p TCTrue (TCOr (Affine P) (Absorbing Q))] \u2192\n  (\u03c6 \u2192 envs_entails (\u0394.delete true i) Q) \u2192\n  envs_entails \u0394 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        \u2190 affine_affinely P,\n        into_pure,\n        \u2190 persistent_and_affinely_sep_l]\n      apply pure_elim \u03c6\n      \u00b7 exact and_elim_l\n      \u00b7 intro h_\u03c6\n        rw' [h_entails h_\u03c6, and_elim_r]\n    case r =>\n      rw' [\n        into_pure,\n        persistent_absorbingly_affinely_2,\n        absorbingly_sep_lr,\n        \u2190 persistent_and_affinely_sep_l]\n      apply pure_elim_l\n      intro h_\u03c6\n      rw' [h_entails h_\u03c6, absorbing]\n  case true.t =>\n    rw' [\n      into_pure,\n      \u2190 persistently_and_intuitionistically_sep_l,\n      persistently_pure]\n    apply pure_elim_l\n    intro h_\u03c6\n    rw' [h_entails h_\u03c6]\n\ntheorem tac_intuitionistic [BI PROP] {\u0394 : Envs PROP} {P' : PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [IntoPersistent p P P'] \u2192\n  [TCIte p TCTrue (TCOr (Affine P) (Absorbing Q))] \u2192\n  envs_entails (\u0394.replace true i true P') Q \u2192\n  envs_entails \u0394 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        \u2190 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 [\u2190 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] {\u0394 : Envs PROP} {P' : PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [FromAffinely P' P p] \u2192\n  envs_entails (\u0394.replace true i false P') Q \u2192\n  envs_entails \u0394 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] {\u0394 : Envs PROP} {Q1 Q2 : PROP} (P : PROP) :\n  [FromAnd P Q1 Q2] \u2192\n  envs_entails \u0394 Q1 \u2192\n  envs_entails \u0394 Q2 \u2192\n  envs_entails \u0394 P\n:= by\n  simp only [envs_entails]\n  intro _ h_entails_1 h_entails_2\n  rw' [\u2190 from_and]\n  apply and_intro\n  \u00b7 exact h_entails_1\n  \u00b7 exact h_entails_2\n\ntheorem tac_sep_split [BI PROP] {\u0394 : Envs PROP} {Q1 Q2 : PROP} (mask : List Bool) (h : mask.length = \u0394.spatial.length) (P : PROP) :\n  let (\u0394\u2081, \u0394\u2082) := \u0394.split mask h\n  [FromSep P Q1 Q2] \u2192\n  envs_entails \u0394\u2081 Q1 \u2192\n  envs_entails \u0394\u2082 Q2 \u2192\n  envs_entails \u0394 P\n:= by\n  intro_let \u0394\u2081 \u0394\u2082 h_split\n  simp only [envs_entails]\n  intro _ h_entails_1 h_entails_2\n  rw' [\n    envs_split_sound h_split,\n    \u2190 from_sep,\n    h_entails_1,\n    h_entails_2]\n\n-- disjunction selection\ntheorem tac_disjunction_l [BI PROP] {\u0394 : Envs PROP} {Q1 Q2 : PROP} (P : PROP) :\n  [FromOr P Q1 Q2] \u2192\n  envs_entails \u0394 Q1 \u2192\n  envs_entails \u0394 P\n:= by\n  simp only [envs_entails]\n  intro _ h_entails\n  rw' [\u2190 from_or]\n  apply or_intro_l'\n  exact h_entails\n\ntheorem tac_disjunction_r [BI PROP] {\u0394 : Envs PROP} {Q1 Q2 : PROP} (P : PROP) :\n  [FromOr P Q1 Q2] \u2192\n  envs_entails \u0394 Q2 \u2192\n  envs_entails \u0394 P\n:= by\n  simp only [envs_entails]\n  intro _ h_entails\n  rw' [\u2190 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 \u2192 Type\n  | and : [IntoAnd true P P1 P2] \u2192 IntoConjunction P P1 P2 true\n  | sep : [IntoSep P P1 P2] \u2192 IntoConjunction P P1 P2 false\n\nattribute [instance] IntoConjunction.and\nattribute [instance] IntoConjunction.sep\n\ntheorem tac_conjunction_destruct [BI PROP] {\u0394 : Envs PROP} {P1 P2 : PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [IntoConjunction P P1 P2 p] \u2192\n  envs_entails (\u0394 |>.delete true i |>.append p P1 |>.append p P2) Q \u2192\n  envs_entails \u0394 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 \u2217 P2 \u22a3\u22a2 _),\n      \u2190 (assoc : _ \u22a3\u22a2 (P2 \u2217 P1) \u2217 _),\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 : \u25a1 P1 \u2217 \u25a1 P2 \u22a3\u22a2 _),\n      \u2190 (assoc : _ \u22a3\u22a2 (\u25a1 P2 \u2217 \u25a1 P1) \u2217 _),\n      wand_elim_r,\n      wand_elim_r,\n      h_entails]\n\ntheorem tac_conjunction_destruct_choice [BI PROP] {\u0394 : Envs PROP} {P1 P2 : PROP} (i : EnvsIndex.of \u0394) (d : Bool) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [IntoAnd p P P1 P2] \u2192\n  envs_entails (if d then \u0394.replace true i p P1 else \u0394.replace true i p P2) Q \u2192\n  envs_entails \u0394 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] {\u0394 : Envs PROP} {P1 P2 : PROP} (i : EnvsIndex.of \u0394) (Q : PROP) :\n  let (p, P) := \u0394.lookup i\n  [IntoOr P P1 P2] \u2192\n  envs_entails (\u0394.replace true i p P1) Q \u2192\n  envs_entails (\u0394.replace true i p P2) Q \u2192\n  envs_entails \u0394 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  \u00b7 rw' [envs_append_sound p P1, wand_elim_r, h_entails_1]\n  \u00b7 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": "inductive A : Type\n| ctor : A \u2192 A\n| inh\n\n-- set_option trace.Elab true in\ndef f : A \u2192 A \u2192 Bool\n| banana, a b | _, lol how => 1 + \"test\" + f1 -- Error\n| _, _ => false\n\n\ndef g : A \u2192 A \u2192 Bool\n| A.inh, _ | _, A.inh => true\n| _, _ => false\n\nexample : g .inh (.ctor a) = true := rfl\nexample : g .inh .inh = true := rfl\nexample : g (.ctor a) .inh = true := rfl\nexample : g (.ctor a) (.ctor b) = false := 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/matchOrIssue.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.042722195870604954, "lm_q1q2_score": 0.01724126217216645}}
{"text": "/- Tactic combinators -/\n\nexample : p \u2192 q \u2192 r \u2192 p \u2227 ((p \u2227 q) \u2227 r) \u2227 (q \u2227 r \u2227 p) := by\n  intros\n  repeat (any_goals constructor)\n  all_goals assumption\n\nexample : p \u2192 q \u2192 r \u2192 p \u2227 ((p \u2227 q) \u2227 r) \u2227 (q \u2227 r \u2227 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": "/-\nCopyright (c) E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: E.W.Ayers\n\n! This file was ported from Lean 3 source module init.meta.tagged_format\n! leanprover-community/mathlib commit aa3b5836dd026e4a02f0bd270ac27f2953880417\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.ExprAddress\nimport Leanbin.Init.Control.Default\n\nuniverse u\n\n/-- An alternative to format that keeps structural information stored as a tag. -/\nunsafe inductive tagged_format (\u03b1 : Type u)\n  | tag : \u03b1 \u2192 tagged_format \u2192 tagged_format\n  | compose : tagged_format \u2192 tagged_format \u2192 tagged_format\n  | Group : tagged_format \u2192 tagged_format\n  | nest : Nat \u2192 tagged_format \u2192 tagged_format\n  | highlight : Format.Color \u2192 tagged_format \u2192 tagged_format\n  | of_format : format \u2192 tagged_format\n#align tagged_format tagged_format\n\nnamespace TaggedFormat\n\nvariable {\u03b1 \u03b2 : Type u}\n\nprotected unsafe def map (f : \u03b1 \u2192 \u03b2) : tagged_format \u03b1 \u2192 tagged_format \u03b2\n  | compose x y => compose (map x) (map y)\n  | Group x => group <| map x\n  | nest i x => nest i <| map x\n  | highlight c x => highlight c <| map x\n  | of_format x => of_format x\n  | tag a x => tag (f a) (map x)\n#align tagged_format.map tagged_format.map\n\nunsafe instance is_functor : Functor tagged_format where map := @tagged_format.map\n#align tagged_format.is_functor tagged_format.is_functor\n\nunsafe def m_untag {t : Type \u2192 Type} [Monad t] (f : \u03b1 \u2192 format \u2192 t format) :\n    tagged_format \u03b1 \u2192 t format\n  | compose x y => pure format.compose <*> m_untag x <*> m_untag y\n  | Group x => pure format.group <*> m_untag x\n  | nest i x => pure (format.nest i) <*> m_untag x\n  | highlight c x => pure format.highlight <*> m_untag x <*> pure c\n  | of_format x => pure <| x\n  | tag a x => m_untag x >>= f a\n#align tagged_format.m_untag tagged_format.m_untag\n\nunsafe def untag (f : \u03b1 \u2192 format \u2192 format) : tagged_format \u03b1 \u2192 format :=\n  @m_untag _ id _ f\n#align tagged_format.untag tagged_format.untag\n\nunsafe instance has_to_fmt : has_to_format (tagged_format \u03b1) :=\n  \u27e8tagged_format.untag fun a f => f\u27e9\n#align tagged_format.has_to_fmt tagged_format.has_to_fmt\n\nend TaggedFormat\n\n/-- tagged_format with information about subexpressions. -/\nunsafe def eformat :=\n  tagged_format (Expr.Address \u00d7 expr)\n#align eformat eformat\n\n/-- A special version of pp which also preserves expression boundary information.\n\nOn a tag \u27e8e,a\u27e9, note that the given expr `e` is _not_ necessarily the subexpression of the root\nexpression that `tactic_state.pp_tagged` was called with. For example if the subexpression is\nunder a binder then all of the `expr.var 0`s will be replaced with a local constant not in\nthe local context with the name and type set to that of the binder.-/\nunsafe axiom tactic_state.pp_tagged : tactic_state \u2192 expr \u2192 eformat\n#align tactic_state.pp_tagged tactic_state.pp_tagged\n\nunsafe def tactic.pp_tagged : expr \u2192 tactic eformat\n  | e => tactic.read >>= fun ts => pure <| tactic_state.pp_tagged ts e\n#align tactic.pp_tagged tactic.pp_tagged\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/TaggedFormat.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489883132727684, "lm_q2_score": 0.041462269602259336, "lm_q1q2_score": 0.017202647202153875}}
{"text": "example {a : \u03b1} {as bs : List \u03b1} (h : bs = a::as) : as.length + 1 = bs.length := by\n  rw [\u2190 List.length]\n  trace_state -- lhs was folded\n  rw [h]\n\nexample {a : \u03b1} {as bs : List \u03b1} (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 : \u03b1} {as bs : List \u03b1} (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 : \u03b1} {as bs : List \u03b1} (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": "import LMT\n\nvariable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]\n\nexample {a1 a2 a3 : A I E} :\n        (v1) \u2260 (((((a3).write i1 (v1)).write i2 (v1)).write i3 (v1)).read i2) \u2192 False := by\n  arr\n", "meta": {"author": "abdoo8080", "repo": "ar-project", "sha": "303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8", "save_path": "github-repos/lean/abdoo8080-ar-project", "path": "github-repos/lean/abdoo8080-ar-project/ar-project-303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8/Test/Lean/Test77.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03514484501123562, "lm_q1q2_score": 0.017160644249232002}}
{"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, S\u00e9bastien Gou\u00ebzel, Scott Morrison\n-/\nimport tactic.lint\nimport tactic.dependencies\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/-- Similar to `constructor`, but does not reorder goals. -/\nmeta def fconstructor : tactic unit := concat_tags tactic.fconstructor\n\nadd_tactic_doc\n{ name       := \"fconstructor\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.fconstructor],\n  tags       := [\"logic\", \"goal management\"] }\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 \u2190 i_to_expr_strict max >>= tactic.eval_expr nat,\n  \u03bb 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 :=\npropagate_tags $ l.mmap' (\u03bb h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"substs\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.substs],\n  tags       := [\"rewriting\"] }\n\n/-- Unfold coercion-related definitions -/\nmeta def unfold_coes (loc : parse location) : tactic unit :=\nunfold [\n  ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,\n  ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,\n  ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc\n\nadd_tactic_doc\n{ name       := \"unfold_coes\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.unfold_coes],\n  tags       := [\"simplification\"] }\n\n\n/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/\nmeta def unfold_wf :=\npropagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof)\n\n/-- Unfold auxiliary definitions associated with the current declaration. -/\nmeta def unfold_aux : tactic unit :=\ndo tgt \u2190 target,\n   name \u2190 decl_name,\n   let to_unfold := (tgt.list_names_with_prefix name),\n   guard (\u00ac 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\u03bb s, result.cases_on (tac s)\n (\u03bb a, result.success ())\n (\u03bb e ref, result.success ())\n\n/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without\nrequiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a\nnon-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/\n@[inline] protected meta def id (tac : itactic) : tactic unit := tac\n\n/--\n`work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero),\nand does not require that the goal be solved at the end\n(any remaining subgoals are inserted back into the list of goals).\n\nTypically usage might look like:\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 2 {\n  dsimp,\n  simp\n},\nrefl\n````\n\nSee also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`.\n-/\nmeta def work_on_goal : parse small_nat \u2192 itactic \u2192 tactic unit\n| n t := do\n  goals \u2190 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 \u2190 get_goals,\n  set_goals (earlier_goals ++ new_goals ++ later_goals)\n\n/--\n`swap n` will move the `n`th goal to the front.\n`swap` defaults to `swap 2`, and so interchanges the first and second goals.\n-/\nmeta def swap (n := 2) : tactic unit :=\ndo gs \u2190 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\nadd_tactic_doc\n{ name       := \"swap\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.swap],\n  tags       := [\"goal management\"] }\n\n/-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. -/\nmeta def rotate (n := 1) : tactic unit := tactic.rotate n\n\nadd_tactic_doc\n{ name       := \"rotate\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.rotate],\n  tags       := [\"goal management\"] }\n\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\nmeta def clear_ : tactic unit := tactic.repeat $ do\n  l \u2190 local_context,\n  l.reverse.mfirst $ \u03bb h, do\n    name.mk_string s p \u2190 return $ local_pp_name h,\n    guard (s.front = '_'),\n    cl \u2190 infer_type h >>= is_class, guard (\u00ac cl),\n    tactic.clear h\n\nadd_tactic_doc\n{ name       := \"clear_\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_],\n  tags       := [\"context management\"] }\n\n/--\nActs like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nmeta def replace (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?)\n  (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\ndo let h := h.get_or_else `this,\n  old \u2190 try_core (get_local h),\n  \u00abhave\u00bb h q\u2081 q\u2082,\n  match old, q\u2082 with\n  | none,   _      := skip\n  | some o, some _ := tactic.clear o\n  | some o, none   := swap >> tactic.clear o >> swap\n  end\n\nadd_tactic_doc\n{ name       := \"replace\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.replace],\n  tags       := [\"context management\"] }\n\n/-- Make every proposition in the context decidable. -/\nmeta def classical := tactic.classical\n\nadd_tactic_doc\n{ name       := \"classical\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.classical],\n  tags       := [\"classical logic\", \"type class\"] }\n\nprivate meta def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\n@[nolint def_lemma]\nlemma {u} generalize_a_aux {\u03b1 : Sort u}\n  (h : \u2200 x : Sort u, (\u03b1 \u2192 x) \u2192 x) : \u03b1 := h \u03b1 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' \u2190 get_unused_name `h,\n   x' \u2190 get_unused_name `x,\n   g \u2190 if \u00ac 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 \u2190 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\nadd_tactic_doc\n{ name       := \"generalize_hyp\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize_hyp],\n  tags       := [\"context management\"] }\n\nmeta def compact_decl_aux : list name \u2192 binder_info \u2192 expr \u2192 list expr \u2192\n  tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| ns bi t [] := pure [(ns.reverse, bi, t)]\n| ns bi t (v'@(local_const n pp bi' t') :: xs) :=\n  do t' \u2190 infer_type v',\n     if bi = bi' \u2227 t = t'\n       then compact_decl_aux (pp :: ns) bi t xs\n       else do vs \u2190 compact_decl_aux [pp] bi' t' xs,\n               pure $ (ns.reverse, bi, t) :: vs\n| ns bi t (_ :: xs) := compact_decl_aux ns bi t xs\n\n/-- go from (x\u2080 : t\u2080) (x\u2081 : t\u2080) (x\u2082 : t\u2080) to (x\u2080 x\u2081 x\u2082 : t\u2080) -/\nmeta def compact_decl : list expr \u2192 tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| [] := pure []\n| (v@(local_const n pp bi t) :: xs)  :=\n  do t \u2190 infer_type v,\n     compact_decl_aux [pp] bi t xs\n| (_ :: xs) := compact_decl xs\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.\n-/\nmeta def clean (q : parse texpr) : tactic unit :=\ndo tgt : expr \u2190 target,\n   e \u2190 i_to_expr_strict ``(%%q : %%tgt),\n   tactic.exact $ e.clean\n\nmeta def source_fields (missing : list name) (e : pexpr) : tactic (list (name \u00d7 pexpr)) :=\ndo e \u2190 to_expr e,\n   t \u2190 infer_type e,\n   let struct_n : name := t.get_app_fn.const_name,\n   fields \u2190 expanded_field_list struct_n,\n   let exp_fields := fields.filter (\u03bb x, x.2 \u2208 missing),\n   exp_fields.mmap $ \u03bb \u27e8p,n\u27e9,\n     (prod.mk n \u2218 to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]\n\nmeta def collect_struct' : pexpr \u2192 state_t (list $ expr\u00d7structure_instance_info) tactic pexpr | e :=\ndo some str \u2190 pure (e.get_structure_instance_info)\n       | e.traverse collect_struct',\n   v \u2190 monad_lift mk_mvar,\n   modify (list.cons (v,str)),\n   pure $ to_pexpr v\n\nmeta def collect_struct (e : pexpr) : tactic $ pexpr \u00d7 list (expr\u00d7structure_instance_info) :=\nprod.map id list.reverse <$> (collect_struct' e).run []\n\nmeta def refine_one (str : structure_instance_info) :\n  tactic $ list (expr\u00d7structure_instance_info) :=\ndo    tgt \u2190 target >>= whnf,\n      let struct_n : name := tgt.get_app_fn.const_name,\n      exp_fields \u2190 expanded_field_list struct_n,\n      let missing_f := exp_fields.filter (\u03bb f, (f.2 : name) \u2209 str.field_names),\n      (src_field_names,src_field_vals) \u2190 (@list.unzip name _ \u2218 list.join) <$>\n        str.sources.mmap (source_fields $ missing_f.map prod.snd),\n      let provided  := exp_fields.filter (\u03bb f, (f.2 : name) \u2208 str.field_names),\n      let missing_f' := missing_f.filter (\u03bb x, x.2 \u2209 src_field_names),\n      vs \u2190 mk_mvar_list missing_f'.length,\n      (field_values,new_goals) \u2190 list.unzip <$> (str.field_values.mmap collect_struct : tactic _),\n      e' \u2190 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 \u2190 with_enable_tags (\n        mzip_with (\u03bb (n : name \u00d7 name) v, do\n           set_goals [v],\n           try (dsimp_target simp_lemmas.mk),\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 \u00d7 structure_instance_info \u2192 tactic (list expr) | (e,str) :=\ndo set_goals [e],\n   rs \u2190 refine_one str,\n   gs \u2190 get_goals,\n   gs' \u2190 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 of semigroup\ninstances:\n\n```lean\nrefine_struct ( { .. } : semigroup \u03b1 ),\n-- case semigroup, mul\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nmeta def refine_struct : parse texpr \u2192 tactic unit | e :=\ndo (x,xs) \u2190 collect_struct e,\n   refine x,\n   gs \u2190 get_goals,\n   xs' \u2190 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 \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p\n\n/--\n`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).\nWe use this tactic for writing tests.\n-/\nmeta def match_hyp (n : parse ident) (p : parse $ tk \":\" *> texpr) (m := reducible) : tactic (list expr) :=\ndo\n  h \u2190 get_local n >>= infer_type >>= instantiate_mvars,\n  match_expr p h m\n\n/--\n`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast\nto `guard_expr`, this tests strict (syntactic) equality.\nWe use this tactic for writing tests.\n-/\nmeta def guard_expr_strict (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, guard (t = e)\n\n/--\n`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_target_strict (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_strict t p\n\n/--\n`guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal\nto `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_hyp_strict (n : parse ident) (p : parse $ tk \":\" *> texpr) : tactic unit :=\ndo h \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p\n\n/-- Tests that there are `n` hypotheses in the current context. -/\nmeta def guard_hyp_nums (n : \u2115) : tactic unit :=\ndo k \u2190 local_context,\n   guard (n = k.length) <|> fail format!\"{k.length} hypotheses found\"\n\n/-- Test that `t` is the tag of the main goal. -/\nmeta def guard_tags (tags : parse ident*) : tactic unit :=\ndo (t : list name) \u2190 get_main_tag,\n   guard (t = tags)\n\n/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term\n  unifies with `p`. -/\nmeta def guard_proof_term (t : itactic) (p : parse texpr) : itactic :=\ndo\n  g :: _ \u2190 get_goals,\n  e \u2190 to_expr p,\n  t,\n  g \u2190 instantiate_mvars g,\n  unify e g\n\n/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with\nerror message `msg` (for test writing purposes). -/\nmeta def success_if_fail_with_msg (tac : tactic.interactive.itactic) :=\ntactic.success_if_fail_with_msg tac\n\n/-- Get the field of the current goal. -/\nmeta def get_current_field : tactic name :=\ndo [_,field,str] \u2190 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 \u2190 get_goals,\n   ts \u2190 gs.mmap get_tag,\n   ([g],gs') \u2190 pure $ (list.zip gs ts).partition (\u03bb 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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\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\nadd_tactic_doc\n{ name       := \"refine_struct\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field,\n                 `tactic.interactive.have_field],\n  tags       := [\"structures\"],\n  inherit_description_from := `tactic.interactive.refine_struct }\n\n/--\n`apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is optional, equal to 50 by default.\nYou can pass an `apply_cfg` option argument as `apply_rules hs n opt`.\n(A typical usage would be with `apply_rules hs n { md := reducible })`,\nwhich asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)\nwhen checking if a lemma matches the goal.)\n\n`hs` can contain user attributes: in this case all theorems with this\nattribute are added to the list of rules.\n\nFor instance:\n\n```lean\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 b + d * e + b + d + e :=\n-- any of the following lines solve the goal:\nadd_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\nby apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\nby apply_rules [mono_rules]\nby apply_rules mono_rules\n```\n-/\nmeta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) (opt : apply_cfg := {}) :\n  tactic unit :=\ntactic.apply_rules hs n opt\n\nadd_tactic_doc\n{ name       := \"apply_rules\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.apply_rules],\n  tags       := [\"lemma application\"] }\n\nmeta def return_cast (f : option expr) (t : option (expr \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr))\n  (e x x' eq_h : expr) :\n  tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 expr)) :=\n(do guard (\u00ac e.has_var),\n    unify x x',\n    u \u2190 mk_meta_univ,\n    f \u2190 f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],\n    t' \u2190 infer_type e,\n    some (f',t) \u2190 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 \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr)) :\n  expr \u2192 tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 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 %%\u03b1 %%p %%a %%b  %%eq_h %%x') := return_cast p t es e x x' eq_h\n| e@`(@eq.substr %%\u03b1 %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'\n| e@`(@eq.rec %%\u03b1 %%a %%f %%x' _  %%eq_h) := return_cast f t es e x x' eq_h\n| e@`(@eq.rec_on %%\u03b1 %%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 \u00d7 expr \u00d7 expr)) :=\n(list.reverse \u2218 prod.snd) <$> tgt.mfold (none, []) (\u03bb e i es, list_cast_of_aux x es.1 es.2 e)\n\nprivate meta def h_generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`;\n- `h_generalize Hx : e == x with _` chooses automatically chooses the name of\n  assumption `\u03b1 = \u03b2`;\n- `h_generalize! Hx : e == x` reverts `Hx`;\n- when `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' \u2190 (h' : tactic name) <|> get_unused_name (\"h\" ++ n.to_string : string),\n   e \u2190 to_expr e,\n   tgt \u2190 target,\n   ((e,x,eq_h)::es) \u2190 list_cast_of e tgt | fail \"no cast found\",\n   interactive.generalize h' () (to_pexpr e, n),\n   asm \u2190 get_local h',\n   v \u2190 get_local n,\n   hs \u2190 es.mmap (\u03bb \u27e8e,_\u27e9, mk_app `eq [e,v]),\n   (eqs_h.zip [e]).mmap' (\u03bb \u27e8h,e\u27e9, do\n        h \u2190 if h \u2260 `_ then pure h else get_unused_name `h,\n        () <$ note h none eq_h ),\n   hs.mmap' (\u03bb h,\n     do h' \u2190 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_cast_eq %%eq_h %%asm))\n     >>= note h' none >> pure ()),\n   tactic.clear asm,\n   when rev.is_some (interactive.revert [n])\n\nadd_tactic_doc\n{ name       := \"h_generalize\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.h_generalize],\n  tags       := [\"context management\"] }\n\n/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that\n  this uses definitional equality instead of alpha-equivalence. -/\nmeta def guard_expr_eq' (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, is_def_eq t e\n\n/--\n`guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.\nWe use this tactic for writing tests.\nThe difference with `guard_target` is that this uses definitional equality instead of\nalpha-equivalence.\n-/\nmeta def guard_target' (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_eq' t p\n\nadd_tactic_doc\n{ name       := \"guard_target'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.guard_target'],\n  tags       := [\"testing\"] }\n\n/--\na weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true,\nunfolding only `reducible` constants. -/\nmeta def triv : tactic unit :=\ntactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail \"triv tactic failed\"\n\nadd_tactic_doc\n{ name       := \"triv\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.triv],\n  tags       := [\"finishing\"] }\n\n/--\nSimilar to `existsi`. `use x` will instantiate the first term of an `\u2203` or `\u03a3` goal with `x`.\nIt will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`.\nUnlike `existsi`, `x` is elaborated with respect to the expected type.\n`use` will alternatively take a list of terms `[x0, ..., xn]`.\n\n`use` will work with constructors of arbitrary inductive types.\n\nExamples:\n```lean\nexample (\u03b1 : Type) : \u2203 S : set \u03b1, S = S :=\nby use \u2205\n\nexample : \u2203 x : \u2124, x = x :=\nby use 42\n\nexample : \u2203 n > 0, n = n :=\nbegin\n  use 1,\n  -- goal is now 1 > 0 \u2227 1 = 1, whereas it would be \u2203 (H : 1 > 0), 1 = 1 after existsi 1.\n  exact \u27e8zero_lt_one, rfl\u27e9,\nend\n\nexample : \u2203 a b c : \u2124, a + b + c = 6 :=\nby use [1, 2, 3]\n\nexample : \u2203 p : \u2124 \u00d7 \u2124, p.1 = 1 :=\nby use \u27e81, 42\u27e9\n\nexample : \u03a3 x y : \u2124, (\u2124 \u00d7 \u2124) \u00d7 \u2124 :=\nby use [1, 2, 3, 4, 5]\n\ninductive foo\n| mk : \u2115 \u2192 bool \u00d7 \u2115 \u2192 \u2115 \u2192 foo\n\nexample : foo :=\nby use [100, tt, 4, 3]\n```\n-/\nmeta def use (l : parse pexpr_list_or_texpr) : tactic unit :=\nfocus1 $\n  tactic.use l;\n  try (triv <|> (do\n        `(Exists %%p) \u2190 target,\n        to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip))\n\nadd_tactic_doc\n{ name       := \"use\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.use, `tactic.interactive.existsi],\n  tags       := [\"logic\"],\n  inherit_description_from := `tactic.interactive.use }\n\n/--\n`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.\nThis includes the induction hypothesis when using the equation compiler and\n`_let_match` and `_fun_match`.\n\nIt is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these\nauxiliary declarations, and produce an error saying the recursion is not well founded.\n\n```lean\nexample (n m : \u2115) (h\u2081 : n = m) (h\u2082 : \u2203 a : \u2115, a = n \u2227 a = m) : 2 * m = 2 * n :=\nlet \u27e8a, ha\u27e9 := h\u2082 in\nbegin\n  clear_aux_decl, -- subst will fail without this line\n  subst h\u2081\nend\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl, -- finish produces an error without this line\n  finish\nend\n```\n-/\nmeta def clear_aux_decl : tactic unit := tactic.clear_aux_decl\n\nadd_tactic_doc\n{ name       := \"clear_aux_decl\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl],\n  tags       := [\"context management\"],\n  inherit_description_from := `tactic.interactive.clear_aux_decl }\n\nmeta def loc.get_local_pp_names : loc \u2192 tactic (list name)\n| loc.wildcard := list.map expr.local_pp_name <$> local_context\n| (loc.ns l) := return l.reduce_option\n\nmeta def loc.get_local_uniq_names (l : loc) : tactic (list name) :=\nlist.map expr.local_uniq_name <$> l.get_locals\n\n/--\nThe logic of `change x with y at l` fails when there are dependencies.\n`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.\nIn this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses\nin `l`. As long as `x` and `y` are defeq, it should never fail.\n-/\nmeta def change' (q : parse texpr) : parse (tk \"with\" *> texpr)? \u2192 parse location \u2192 tactic unit\n| none (loc.ns [none]) := do e \u2190 i_to_expr q, change_core e none\n| none (loc.ns [some h]) := do eq \u2190 i_to_expr q, eh \u2190 get_local h, change_core eq (some eh)\n| none _ := fail \"change-at does not support multiple locations\"\n| (some w) l :=\n  do l' \u2190 loc.get_local_pp_names l,\n     l'.mmap' (\u03bb e, try (change_with_at q w e)),\n     when l.include_goal $ change q w (loc.ns [none])\n\nadd_tactic_doc\n{ name       := \"change'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.change', `tactic.interactive.change],\n  tags       := [\"renaming\"],\n  inherit_description_from := `tactic.interactive.change' }\n\nprivate meta def opt_dir_with : parser (option (bool \u00d7 name)) :=\n(do tk \"with\",\n   arrow \u2190 (tk \"<-\")?,\n   h \u2190 ident,\n   return (arrow.is_some, h)) <|> return none\n\n/--\n`set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to\nthe local context and replaces `t` with `a` everywhere it can.\n\n`set a := t with \u2190h` will add `h : t = a` instead.\n\n`set! a := t with h` does not do any replacing.\n\n```lean\nexample (x : \u2115) (h : x = 3)  : x + x + x = 9 :=\nbegin\n  set y := x with \u2190h_xy,\n/-\nx : \u2115,\ny : \u2115 := x,\nh_xy : x = y,\nh : y = 3\n\u22a2 y + y + y = 9\n-/\nend\n```\n-/\nmeta def set (h_simp : parse (tk \"!\")?) (a : parse ident) (tp : parse ((tk \":\") >> texpr)?)\n  (_ : parse (tk \":=\")) (pv : parse texpr)\n  (rev_name : parse opt_dir_with) :=\ndo tp \u2190 i_to_expr $ tp.get_or_else pexpr.mk_placeholder,\n   pv \u2190 to_expr ``(%%pv : %%tp),\n   tp \u2190 instantiate_mvars tp,\n   definev a tp pv,\n   when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard,\n   match rev_name with\n   | some (flip, id) :=\n     do nv \u2190 get_local a,\n        mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id,\n        reflexivity\n   | none := skip\n   end\n\nadd_tactic_doc\n{ name       := \"set\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.set],\n  tags       := [\"context management\"] }\n\n/--\n`clear_except h\u2080 h\u2081` deletes all the assumptions it can except for `h\u2080` and `h\u2081`.\n-/\nmeta def clear_except (xs : parse ident *) : tactic unit :=\ndo n \u2190 xs.mmap (try_core \u2218 get_local) >>= revert_lst \u2218 list.filter_map id,\n   ls \u2190 local_context,\n   ls.reverse.mmap' $ try \u2218 tactic.clear,\n   intron_no_renames n\n\nadd_tactic_doc\n{ name       := \"clear_except\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_except],\n  tags       := [\"context management\"] }\n\n\nmeta def format_names (ns : list name) : format :=\nformat.join $ list.intersperse \" \" (ns.map to_fmt)\n\nprivate meta def indent_bindents (l r : string) : option (list name) \u2192 expr \u2192 tactic format\n| none e :=\n  do e \u2190 pp e,\n     pformat!\"{l}{format.nest l.length e}{r}\"\n| (some ns) e :=\n  do e \u2190 pp e,\n     let ns := format_names ns,\n     let margin := l.length + ns.to_string.length + \" : \".length,\n     pformat!\"{l}{ns} : {format.nest margin e}{r}\"\n\nprivate meta def format_binders : list name \u00d7 binder_info \u00d7 expr \u2192 tactic format\n| (ns, binder_info.default, t) := indent_bindents \"(\" \")\" ns t\n| (ns, binder_info.implicit, t) := indent_bindents \"{\" \"}\" ns t\n| (ns, binder_info.strict_implicit, t) := indent_bindents \"\u2983\" \"\u2984\" ns t\n| ([n], binder_info.inst_implicit, t) :=\n  if \"_\".is_prefix_of n.to_string\n    then indent_bindents \"[\" \"]\" none t\n    else indent_bindents \"[\" \"]\" [n] t\n| (ns, binder_info.inst_implicit, t) := indent_bindents \"[\" \"]\" ns t\n| (ns, binder_info.aux_decl, t) := indent_bindents \"(\" \")\" ns t\n\nprivate meta def partition_vars' (s : name_set) : list expr \u2192 list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr)\n| [] as bs := pure (as.reverse, bs.reverse)\n| (x :: xs) as bs :=\ndo t \u2190 infer_type x,\n   if t.has_local_in s then partition_vars' xs as (x :: bs)\n     else partition_vars' xs (x :: as) bs\n\nprivate meta def partition_vars : tactic (list expr \u00d7 list expr) :=\ndo ls \u2190 local_context,\n   partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] []\n\n/--\nFormat the current goal as a stand-alone example. Useful for testing tactics\nor creating [minimal working examples](https://leanprover-community.github.io/mwe.html).\n\n* `extract_goal`: formats the statement as an `example` declaration\n* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration\n  called `my_decl`\n* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration\n\nExamples:\n\n```lean\nexample (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\nbegin\n  extract_goal,\n     -- prints:\n     -- example (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\n  extract_goal my_lemma\n     -- prints:\n     -- lemma my_lemma (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\nend\n\nexample {i j k x y z w p q r m n : \u2115} (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) (h\u2081 : k \u2264 p) (h\u2081 : p \u2264 q) : i \u2264 k :=\nbegin\n  extract_goal my_lemma,\n    -- prints:\n    -- lemma my_lemma {i j k x y z w p q r m n : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p)\n    --   (h\u2081 : p \u2264 q) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\n\n  extract_goal my_lemma with i j k\n    -- prints:\n    -- lemma my_lemma {p i j k : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\nend\n\nexample : true :=\nbegin\n  let n := 0,\n  have m : \u2115, admit,\n  have k : fin n, admit,\n  have : n + m + k.1 = 0, extract_goal,\n    -- prints:\n    -- example (m : \u2115)  : let n : \u2115 := 0 in \u2200 (k : fin n), n + m + k.val = 0 :=\n    -- begin\n    --   intros n k,\n    --   admit,\n    -- end\nend\n```\n\n-/\nmeta def extract_goal (print_use : parse $ tt <$ tk \"!\" <|> pure ff)\n  (n : parse ident?) (vs : parse with_ident_list)\n  : tactic unit :=\ndo tgt \u2190 target,\n   solve_aux tgt $ do {\n     ((cxt\u2080,cxt\u2081,ls,tgt),_) \u2190 solve_aux tgt $ do {\n         when (\u00ac vs.empty) (clear_except vs),\n         ls \u2190 local_context,\n         ls \u2190 ls.mfilter $ succeeds \u2218 is_local_def,\n         n \u2190 revert_lst ls,\n         (c\u2080,c\u2081) \u2190 partition_vars,\n         tgt \u2190 target,\n         ls \u2190 intron' n,\n         pure (c\u2080,c\u2081,ls,tgt) },\n     is_prop \u2190 is_prop tgt,\n     let title := match n, is_prop with\n                  | none, _ := to_fmt \"example\"\n                  | (some n), tt := format!\"lemma {n}\"\n                  | (some n), ff := format!\"def {n}\"\n                  end,\n     cxt\u2080 \u2190 compact_decl cxt\u2080 >>= list.mmap format_binders,\n     cxt\u2081 \u2190 compact_decl cxt\u2081 >>= list.mmap format_binders,\n     stmt \u2190 pformat!\"{tgt} :=\",\n     let fmt :=\n       format.group $ format.nest 2 $\n         title ++ cxt\u2080.foldl (\u03bb acc x, acc ++ format.group (format.line ++ x)) \"\" ++\n         format.join (list.map (\u03bb x, format.line ++ x) cxt\u2081) ++ \" :\" ++\n         format.line ++ stmt,\n     trace $ fmt.to_string $ options.mk.set_nat `pp.width 80,\n     let var_names := format.intercalate \" \" $ ls.map (to_fmt \u2218 local_pp_name),\n     let call_intron := if ls.empty\n                     then to_fmt \"\"\n                     else format!\"\\n  intros {var_names},\",\n     trace!\"begin{call_intron}\\n  admit,\\nend\\n\" },\n   skip\n\nadd_tactic_doc\n{ name       := \"extract_goal\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.extract_goal],\n  tags       := [\"goal management\", \"proof extraction\", \"debugging\"] }\n\n/--\n`inhabit \u03b1` tries to derive a `nonempty \u03b1` instance and then upgrades this\nto an `inhabited \u03b1` instance.\nIf the target is a `Prop`, this is done constructively;\notherwise, it uses `classical.choice`.\n\n```lean\nexample (\u03b1) [nonempty \u03b1] : \u2203 a : \u03b1, true :=\nbegin\n  inhabit \u03b1,\n  existsi default \u03b1,\n  trivial\nend\n```\n-/\nmeta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit :=\ndo ty \u2190 i_to_expr t,\n   nm \u2190 returnopt inst_name <|> get_unused_name `inst,\n   tgt \u2190 target,\n   tgt_is_prop \u2190 is_prop tgt,\n   if tgt_is_prop then do\n     decorate_error \"could not infer nonempty instance:\" $\n       mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply,\n     introI nm\n   else do\n     decorate_error \"could not infer nonempty instance:\" $\n      mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none,\n     resetI\n\nadd_tactic_doc\n{ name       := \"inhabit\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.inhabit],\n  tags       := [\"context management\", \"type class\"] }\n\n/-- `revert_deps n\u2081 n\u2082 ...` reverts all the hypotheses that depend on one of `n\u2081, n\u2082, ...`\nIt does not revert `n\u2081, n\u2082, ...` themselves (unless they depend on another `n\u1d62`). -/\nmeta def revert_deps (ns : parse ident*) : tactic unit :=\npropagate_tags $\n  ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `revert_after n` reverts all the hypotheses after `n`. -/\nmeta def revert_after (n : parse ident) : tactic unit :=\npropagate_tags $ get_local n >>= tactic.revert_after >> skip\n\nadd_tactic_doc\n{ name       := \"revert_after\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_after],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- Reverts all local constants on which the target depends (recursively). -/\nmeta def revert_target_deps : tactic unit :=\npropagate_tags $ tactic.revert_target_deps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_target_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_target_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `clear_value n\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`. -/\nmeta def clear_value (ns : parse ident*) : tactic unit :=\npropagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value\n\nadd_tactic_doc\n{ name       := \"clear_value\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_value],\n  tags       := [\"context management\"] }\n\n/--\n`generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of\nthe same type.\n\n`generalize' h : e = x` in addition registers the hypothesis `h : e = x`.\n\n`generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also\nsucceeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis\n`x` is not a local definition.\n-/\nmeta def generalize' (h : parse ident?) (_ : parse $ tk \":\") (p : parse generalize_arg_p) : tactic unit :=\npropagate_tags $\ndo let (p, x) := p,\n   e \u2190 i_to_expr p,\n   some h \u2190 pure h | tactic.generalize' e x >> skip,\n   -- `h` is given, the regular implementation of `generalize` works.\n   tgt \u2190 target,\n   tgt' \u2190 do {\n     \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize e x >> target),\n     to_expr ``(\u03a0 x, %%e = x \u2192 %%(tgt'.binding_body.lift_vars 0 1))\n   } <|> to_expr ``(\u03a0 x, %%e = x \u2192 %%tgt),\n   t \u2190 assert h tgt',\n   swap,\n   exact ``(%%t %%e rfl),\n   intro x,\n   intro h\n\nadd_tactic_doc\n{ name       := \"generalize'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize'],\n  tags       := [\"context management\"] }\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934935817440725, "lm_q2_score": 0.07159120588227677, "lm_q1q2_score": 0.017135309178854793}}
{"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 (\u03b1 : Type)\n| done (pos : \u2115) (result : \u03b1) : parse_result\n| fail (pos : \u2115) (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 (\u03b1 : Type) :=\n\u2200 (input : char_buffer) (start : \u2115), parse_result \u03b1\n\nnamespace parser\nvariables {\u03b1 \u03b2 \u03b3 : Type}\n\nprotected def bind (p : parser \u03b1) (f : \u03b1 \u2192 parser \u03b2) : parser \u03b2 :=\n\u03bb 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 : \u03b1) : parser \u03b1 :=\n\u03bb input pos, parse_result.done pos a\n\nprivate lemma parser.id_map (p : parser \u03b1) : 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 \u03b1) (q : \u03b1 \u2192 parser \u03b2) (r : \u03b2 \u2192 parser \u03b3) :\n  parser.bind (parser.bind p q) r = parser.bind p (\u03bb 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 \u03b1 :=\n\u03bb _ 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 := \u03bb _ _ _ _, rfl,\n  bind_assoc := @parser.bind_assoc }\n\ninstance : monad_fail parser :=\n{ fail := @parser.fail, ..parser.monad }\n\nprotected def failure : parser \u03b1 :=\n\u03bb _ pos, parse_result.fail pos dlist.empty\n\nprotected def orelse (p q : parser \u03b1) : parser \u03b1 :=\n\u03bb input pos, match p input pos with\n| parse_result.fail pos\u2081 expected\u2081 :=\n  if pos\u2081 \u2260 pos then parse_result.fail pos\u2081 expected\u2081 else\n  match q input pos with\n  | parse_result.fail pos\u2082 expected\u2082 :=\n    if pos\u2081 < pos\u2082 then\n      parse_result.fail pos\u2081 expected\u2081\n    else if pos\u2082 < pos\u2081 then\n      parse_result.fail pos\u2082 expected\u2082\n    else -- pos\u2081 = pos\u2082\n      parse_result.fail pos\u2081 (expected\u2081 ++ expected\u2082)\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 \u03b1) :=\n\u27e8parser.failure\u27e9\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorate_errors (msgs : thunk (list string)) (p : parser \u03b1) : parser \u03b1 :=\n\u03bb 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 \u03b1) : parser \u03b1 :=\ndecorate_errors [msg ()] p\n\n/-- Matches a single character. Fails only if there is no more input. -/\ndef any_char : parser char :=\n\u03bb input pos,\nif h : pos < input.size\n  then\n    let c := input.read \u27e8pos, h\u27e9 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 \u2192 Prop) [decidable_pred p] : parser char :=\n\u03bb input pos,\nif h : pos < input.size\n  then\n    let c := input.read \u27e8pos, h\u27e9 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 \u2190 cs, return c.to_string) $\nsat (\u2208 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 \u2115 :=\n\u03bb input pos, parse_result.done pos (input.size - pos)\n\n/-- Matches the end of the input. -/\ndef eof : parser unit :=\ndecorate_error \"<end-of-file>\" $\ndo rem \u2190 remaining, guard $ rem = 0\n\ndef foldr_core (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (p : parser \u03b1) (b : \u03b2) : \u2200 (reps : \u2115), parser \u03b2\n| 0 := failure\n| (reps+1) := (do x \u2190 p, xs \u2190 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (p : parser \u03b1) (b : \u03b2) : parser \u03b2 :=\n\u03bb input pos, foldr_core f p b (input.size - pos + 1) input pos\n\ndef foldl_core (f : \u03b1 \u2192 \u03b2 \u2192 \u03b1) : \u2200 (a : \u03b1) (p : parser \u03b2) (reps : \u2115), parser \u03b1\n| a p 0 := failure\n| a p (reps+1) := (do x \u2190 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 : \u03b1 \u2192 \u03b2 \u2192 \u03b1) (a : \u03b1) (p : parser \u03b2) : parser \u03b1 :=\n\u03bb 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 \u03b1) : parser (list \u03b1) :=\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 \u03b1) : parser unit :=\nmany p >> eps\n\n/-- Matches one or more occurrences of `p`. -/\ndef many1 (p : parser \u03b1) : parser (list \u03b1) :=\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 \u03b1) : parser (list \u03b1) :=\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 \u03b1) : parser (list \u03b1) :=\nsep_by1 sep p <|> return []\n\ndef fix_core (F : parser \u03b1 \u2192 parser \u03b1) : \u2200 (max_depth : \u2115), parser \u03b1\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 \"<digit>\" $ do\n  c \u2190 sat (\u03bb c, '0' \u2264 c \u2227 c \u2264 '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 \"<natural>\" $ do\n  digits \u2190 many1 digit,\n  pure $ prod.fst $ digits.foldr\n    (\u03bb digit \u27e8sum, magnitude\u27e9, \u27e8sum + digit * magnitude, magnitude * 10\u27e9)\n    \u27e80, 1\u27e9\n\n/-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/\ndef fix (F : parser \u03b1 \u2192 parser \u03b1) : parser \u03b1 :=\n\u03bb input pos, fix_core F (input.size - pos + 1) input pos\n\nprivate def make_monospaced : char \u2192 char\n| '\\n' := ' '\n| '\\t' := ' '\n| '\\x0d' := ' '\n| c := c\n\ndef mk_error_msg (input : char_buffer) (pos : \u2115) (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 (\u03bb _, ' ') ++ \"^\\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 \u03b1) (input : char_buffer) : sum string \u03b1 :=\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 \u03b1) (input : string) : sum string \u03b1 :=\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 \u27f6 Y) :\n  (quotient.functor r).map f = quot.mk _ f := rfl\n\nvariables [add_monoid A] [has_shift C A]\n  (h : \u2200 (a : A) \u2983X Y : C\u2984 (f\u2081 f\u2082 : X \u27f6 Y), r f\u2081 f\u2082 \u2192 r (f\u2081\u27e6a\u27e7') (f\u2082\u27e6a\u27e7'))\n\nvariable {r}\n\nnamespace quotient\n\n@[protected]\ndef shift_functor (a : A) : quotient r \u2964 quotient r :=\nlift r (shift_functor C a \u22d9 functor r) (\u03bb X Y f\u2081 f\u2082 rel, quotient.sound r (h a f\u2081 f\u2082 rel))\n\ndef comm_shift (a : A) :\n  shift_functor C a \u22d9 functor r \u2245 functor r \u22d9 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 = \ud835\udfd9 _ := rfl\n\n@[simp]\nlemma comm_shift_inv_app (a : A) (X : C) :\n  (comm_shift h a).inv.app X = \ud835\udfd9 _ := rfl\n\ndef shift_\u03b5 : \ud835\udfed _ \u2245 quotient.shift_functor h 0 :=\nquotient.lift_nat_iso _ _ (functor.right_unitor _ \u226a\u226b (functor.left_unitor _).symm \u226a\u226b\n      iso_whisker_right (shift_functor_zero C A).symm _ \u226a\u226b comm_shift h 0)\n\n@[simp]\nlemma shift_\u03b5_hom_app (X : C) :\n  (shift_\u03b5 h).hom.app ((functor r).obj X) =\n    (functor r).map ((shift_functor_zero C A).inv.app X) :=\nbegin\n  dsimp [shift_\u03b5],\n  simp only [id_comp, comp_id],\nend\n\ndef shift_\u03bc (a b : A) :\n  quotient.shift_functor h a \u22d9 quotient.shift_functor h b \u2245\n  quotient.shift_functor h (a + b) :=\nquotient.lift_nat_iso _ _ ((functor.associator _ _ _).symm \u226a\u226b\n  iso_whisker_right (comm_shift h a).symm _ \u226a\u226b functor.associator _ _ _ \u226a\u226b\n  iso_whisker_left _ (comm_shift h b).symm \u226a\u226b (functor.associator _ _ _).symm \u226a\u226b\n  iso_whisker_right (shift_functor_add C a b).symm _ \u226a\u226b comm_shift h (a + b))\n\n@[simp]\nlemma shift_\u03bc_hom_app (a b : A) (X : C) :\n  (shift_\u03bc 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_\u03bc],\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) \u226b\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) \u226b\n  (shift_functor_add C a (b + c)).inv.app X \u226b 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 \u2190 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_\u03bc h a b).hom \u25eb \ud835\udfd9 (quotient.shift_functor h c) \u226b\n    (shift_\u03bc h (a + b) c).hom \u226b eq_to_hom (by rw add_assoc) =\n  (functor.associator _ _ _).hom \u226b \ud835\udfd9 (quotient.shift_functor h a) \u25eb (shift_\u03bc h b c).hom \u226b\n    (shift_\u03bc h a (b + c)).hom :=\nquotient.nat_trans_ext _ _ (\u03bb 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_\u03bc_hom_app, shift_\u03bc_hom_app, shift_\u03bc_hom_app,\n    shift_\u03bc_hom_app, assoc, functor.map_id, id_comp, lift_map_functor_map],\n  dsimp only ,\n  simp only [functor.comp_map, \u2190 functor.map_comp, \u2190 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_\u03b5 h).hom \u25eb \ud835\udfd9 (quotient.shift_functor h a) \u226b (shift_\u03bc h 0 a).hom =\n    eq_to_hom (congr_arg (quotient.shift_functor h) (zero_add a).symm) :=\nquotient.nat_trans_ext _ _ (\u03bb X, begin\n  dsimp [shift_\u03b5, shift_\u03bc, 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 [\u2190 functor_map_eq, \u2190 functor_map_eq, \u2190 functor.map_comp],\n  transitivity (functor r).map (eq_to_hom _), swap,\n  { rw zero_add, },\n  { congr' 1,\n    simp only [obj_\u03b5_app, eq_to_iso.inv, assoc, \u03bc_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  \ud835\udfd9 (quotient.shift_functor h a) \u25eb (shift_\u03b5 h).hom \u226b (shift_\u03bc h a 0).hom =\n    eq_to_hom (congr_arg (quotient.shift_functor h) (add_zero a).symm) :=\nquotient.nat_trans_ext _ _ (\u03bb X, begin\n  dsimp only [shift_\u03b5, shift_\u03bc, 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 [\u2190 functor_map_eq, \u2190 functor_map_eq, \u2190 functor.map_comp],\n  transitivity (functor r).map (eq_to_hom _), swap,\n  { rw add_zero, },\n  { congr' 1,\n    simp only [\u03b5_app_obj, eq_to_iso.inv, assoc, \u03bc_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  \u03b5 := shift_\u03b5 h,\n  \u03bc := shift_\u03bc h,\n  associativity := \u03bb a b c X, by simpa using congr_app (shift_associativity h a b c) X,\n  left_unitality := \u03bb a X, by simpa using congr_app (shift_left_unitality h a) X,\n  right_unitality := \u03bb 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 := \u03bb 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 _ \u226b (shift_\u03bc h a b).hom.app ((functor r).obj K) = _,\n    erw [shift_\u03bc_hom_app, \u2190 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_\u03b5_hom_app, \u2190 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 \u2964 D} {F' : quotient r \u2964 D} (e : functor r \u22d9 F' \u2245 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 \u22d9 F' \u2245 F' \u22d9 shift_functor D a :=\nlift_nat_iso _ _ ((functor.associator _ _ _).symm \u226a\u226b\n    iso_whisker_right ((functor r).comm_shift_iso a).symm F' \u226a\u226b\n    functor.associator _ _ _ \u226a\u226b iso_whisker_left _ e \u226a\u226b\n    F.comm_shift_iso a \u226a\u226b iso_whisker_right e.symm _ \u226a\u226b 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) \u226b\n    e.hom.app ((shift_functor C a).obj X) \u226b\n    (F.comm_shift_iso a).hom.app X \u226b\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) \u226b\n    (F.comm_shift_iso a).inv.app X \u226b\n    e.inv.app ((shift_functor C a).obj X) \u226b\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 := \u03bb a, comm_shift_iso_of_fac e a,\n  iso_zero := begin\n    ext1,\n    refine nat_trans_ext _ _ (\u03bb 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, \u2190 e.hom.naturality_assoc, functor.comp_map],\n    nth_rewrite 1 \u2190 functor.map_comp_assoc,\n    erw [\u2190 functor.map_comp, iso.inv_hom_id_app, (functor r).map_id, F'.map_id, id_comp,\n      \u2190 nat_trans.naturality],\n    dsimp only [functor.id],\n    rw e.hom_inv_id_app_assoc,\n  end,\n  iso_add := \u03bb a b, begin\n    ext1,\n    refine nat_trans_ext _ _ (\u03bb 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 [\u2190 nat_trans.naturality_assoc, \u2190 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 \u2190 functor.map_comp_assoc,\n    erw [\u2190 functor.map_comp, iso.inv_hom_id_app, (functor r).map_id, F'.map_id, id_comp],\n    nth_rewrite 4 \u2190 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 : \u2200 (x y : C) (f\u2081 f\u2082 : x \u27f6 y), r f\u2081 f\u2082 \u2192 F.map f\u2081 = F.map f\u2082) :\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 LMT\n\nvariable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]\n\nexample {a1 a2 a3 : A I E} :\n        (v3) \u2260 (((((a1).write i3 (v1)).write i2 (v3)).write i1 (v3)).read i2) \u2192 False := by\n  arr\n", "meta": {"author": "abdoo8080", "repo": "ar-project", "sha": "303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8", "save_path": "github-repos/lean/abdoo8080-ar-project", "path": "github-repos/lean/abdoo8080-ar-project/ar-project-303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8/Test/Lean/Test39.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.03461884145368849, "lm_q1q2_score": 0.017038983035904735}}
{"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\u0103dulescu-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 \u27f6 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 \u27f6 b') (r : b' \u27f6 b) (s : b \u27f6 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' \u226b r = f)\n(hsr : s \u226b r = \ud835\udfd9 b)\n\nlemma brown_factorization.hr {a b : C} {f : a \u27f6 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 \u27f6 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 \u27f6 b) :\n  nonempty (brown_factorization f) :=\nlet ab := pushout_by_cof (! a) (! b) ha,\n    \u27e8b', j, g, hj, hg, hf\u27e9 :=\n      factorization (ab.is_pushout.induced f (\ud835\udfd9 b) (initial.uniqueness _ _)) in\n\u27e8\u27e8ab, b', ab.map\u2080 \u226b j, g, ab.map\u2081 \u226b 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\u27e9\u27e9\n\n--- R-B, Lemma 1.3.3\nlemma relative_factorization {a\u2081 a\u2081' b\u2081 a\u2082 b\u2082 : C}\n  (ha\u2081 : cofibrant a\u2081) (ha\u2082 : cofibrant a\u2082)\n  (f\u2081' : a\u2081 \u27f6 a\u2081') (r\u2081 : a\u2081' \u27f6 b\u2081) (hf\u2081' : is_cof f\u2081') (hr : is_weq r\u2081)\n  (f\u2082 : a\u2082 \u27f6 b\u2082) (a : a\u2081 \u27f6 a\u2082) (b : b\u2081 \u27f6 b\u2082) (s : (f\u2081' \u226b r\u2081) \u226b b = a \u226b f\u2082) :\n  \u2203 a\u2082' (a' : a\u2081' \u27f6 a\u2082') (f\u2082' : a\u2082 \u27f6 a\u2082') (r\u2082 : a\u2082' \u27f6 b\u2082)\n  (hf' : f\u2081' \u226b a' = a \u226b f\u2082'), r\u2081 \u226b b = a' \u226b r\u2082 \u2227 f\u2082' \u226b r\u2082 = f\u2082 \u2227 is_cof f\u2082' \u2227 is_weq r\u2082 \u2227\n  is_cof ((pushout_by_cof f\u2081' a hf\u2081').is_pushout.induced a' f\u2082' hf') :=\nlet po := pushout_by_cof f\u2081' a hf\u2081',\n    g := po.is_pushout.induced (r\u2081 \u226b b) f\u2082 (by rw [\u2190s, assoc]),\n    \u27e8a\u2082', s, r\u2082, hs, hr\u2082, hg\u27e9 := factorization g in\n\u27e8a\u2082', po.map\u2080 \u226b s, po.map\u2081 \u226b s, r\u2082,\n by rw [\u2190assoc, \u2190assoc, po.is_pushout.commutes],\n by rw [assoc, hg]; simp,\n by simp [hg],\n cof_comp (pushout_is_cof po.is_pushout hf\u2081') hs,\n hr\u2082,\n by convert hs; apply po.is_pushout.uniqueness; simp\u27e9\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\u2081 b\u2081 a\u2082 b\u2082 : C}\n  (ha\u2081 : cofibrant a\u2081) (hb\u2081 : cofibrant b\u2081) (ha\u2082 : cofibrant a\u2082) (hb\u2082 : cofibrant b\u2082)\n  (f\u2081 : a\u2081 \u27f6 b\u2081) (f\u2082 : a\u2082 \u27f6 b\u2082) (a : a\u2081 \u27f6 a\u2082) (b : b\u2081 \u27f6 b\u2082) (S : f\u2081 \u226b b = a \u226b f\u2082)\n  (c\u2081 : brown_factorization f\u2081) : \u2203 (c\u2082 : brown_factorization f\u2082) (b' : c\u2081.b' \u27f6 c\u2082.b')\n  (hf' : c\u2081.f' \u226b b' = a \u226b c\u2082.f') (hr : c\u2081.r \u226b b = b' \u226b c\u2082.r) (hs : c\u2081.s \u226b b' = b \u226b c\u2082.s),\n  (is_cof b \u2192 is_cof ((pushout_by_cof c\u2081.f' a c\u2081.hf').is_pushout.induced b' c\u2082.f' hf')) \u2227\n  (is_cof a \u2192 is_acof ((pushout_by_cof c\u2081.s b c\u2081.hs.1).is_pushout.induced b' c\u2082.s hs)) :=\nlet po_a := pushout_by_cof c\u2081.f' a c\u2081.hf',\n    a\u2083 := po_a.ob,\n    f' := po_a.map\u2081,\n    cof_f' : is_cof f' := pushout_is_cof po_a.is_pushout c\u2081.hf',\n    po_b := pushout_by_cof c\u2081.s b c\u2081.hs.1,\n    b\u2083 := po_b.ob,\n    s := po_b.map\u2081,\n    acof_s : is_acof s := pushout_is_acof po_b.is_pushout c\u2081.hs,\n    r := po_b.is_pushout.induced (c\u2081.r \u226b b) (\ud835\udfd9 _) (by rw [\u2190assoc, c\u2081.hsr]; simp),\n    f\u2083 : a\u2083 \u27f6 b\u2083 := po_a.is_pushout.induced (c\u2081.r \u226b b \u226b s) (f\u2082 \u226b s) begin\n      conv { to_rhs, rw [\u2190assoc, \u2190S], rw [\u2190c\u2081.hf'r, assoc] }, simp\n    end,\n    a\u2082b\u2082 := pushout_by_cof (! a\u2082) (! b\u2082) ha\u2082,\n    -- TODO: lemma here?\n    cof_a\u2083 : cofibrant a\u2083 := begin\n      change is_cof _,\n      convert cof_comp ha\u2082 (pushout_is_cof po_a.is_pushout c\u2081.hf'),\n      apply initial.uniqueness\n    end,\n    cof_b\u2083 : cofibrant b\u2083 := begin\n      change is_cof _,\n      convert cof_comp hb\u2082 (pushout_is_cof po_b.is_pushout c\u2081.hs.1),\n      apply initial.uniqueness\n    end,\n    a\u2083b\u2083 := pushout_by_cof (! a\u2083) (! b\u2083) cof_a\u2083,\n    a\u2081_b\u2081 := c\u2081.ab.ob,\n    cof_a\u2081_b\u2081 : cofibrant a\u2081_b\u2081 := begin\n      change is_cof _,\n      convert cof_comp hb\u2081 (pushout_is_cof c\u2081.ab.is_pushout ha\u2081),\n      apply initial.uniqueness\n    end,\n    a\u2083_b\u2083 := a\u2083b\u2083.ob,\n    cof_a\u2083_b\u2083 : cofibrant a\u2083_b\u2083 := begin\n      change is_cof _,\n      convert cof_comp cof_b\u2083 (pushout_is_cof a\u2083b\u2083.is_pushout cof_a\u2083),\n      apply initial.uniqueness\n    end,\n    \u27e8b\u2082', b', fs\u2083', r\u2083, hfs\u2083', hr\u2083, hf'sr, cof_fs\u2083', weq_r\u2083, cof_p\u27e9 := begin\n      refine relative_factorization cof_a\u2081_b\u2081 cof_a\u2083_b\u2083 _ c\u2081.r c\u2081.hf's c\u2081.hr\n        (a\u2083b\u2083.is_pushout.induced f\u2083 (\ud835\udfd9 b\u2083) (initial.uniqueness _ _))\n        (pushout_of_maps c\u2081.ab.is_pushout a\u2083b\u2083.is_pushout (\ud835\udfd9 _) (a \u226b f') (b \u226b s)\n          (initial.uniqueness _ _) (initial.uniqueness _ _))\n        (b \u226b s) _,\n      apply c\u2081.ab.is_pushout.uniqueness,\n      { slice_lhs 1 2 { simp }, conv { to_lhs, rw [c\u2081.hf'r, S, assoc] },\n        rw induced_pushout_of_maps, simp },\n      { slice_lhs 1 2 { simp }, conv { to_lhs, rw [c\u2081.hsr, id_comp] },\n        rw induced_pushout_of_maps, simp }\n    end,\n    f\u2083' := a\u2083b\u2083.map\u2080 \u226b fs\u2083',\n    s\u2083 := a\u2083b\u2083.map\u2081 \u226b fs\u2083',\n    f\u2082' := f' \u226b f\u2083',\n    r\u2082 := r\u2083 \u226b r,\n    s\u2082 := s \u226b s\u2083 in\nhave sr : s \u226b r = \ud835\udfd9 _, by simp,\nhave s\u2082r\u2082 : s\u2082 \u226b r\u2082 = \ud835\udfd9 _, begin\n  slice_lhs 3 4 { rw hf'sr },\n  slice_lhs 2 3 { rw Is_pushout.induced_commutes\u2081 },\n  simp\nend,\nhave weq_r\u2082 : is_weq r\u2082, begin\n  refine weq_comp weq_r\u2083 _,\n  rw \u2190weq_iff_weq_inv sr,\n  exact acof_s.2\nend,\n\u27e8\u27e8a\u2082b\u2082, b\u2082', f\u2082', r\u2082, s\u2082,\n  cof_comp (pushout_is_cof po_a.is_pushout c\u2081.hf')\n    (cof_comp (pushout_is_cof a\u2083b\u2083.is_pushout.transpose cof_b\u2083) cof_fs\u2083'),\n  begin\n    have := cof_pushout cof_f' acof_s.1 a\u2082b\u2082.is_pushout\n      (by convert a\u2083b\u2083.is_pushout; apply initial.uniqueness) (by apply initial.uniqueness),\n    convert cof_comp this cof_fs\u2083',\n    apply a\u2082b\u2082.is_pushout.uniqueness; conv { to_rhs, rw \u2190assoc }; simp\n  end,\n  begin\n    refine \u27e8_, (weq_iff_weq_inv s\u2082r\u2082).mpr weq_r\u2082\u27e9,\n    exact cof_comp acof_s.1 (cof_comp (pushout_is_cof a\u2083b\u2083.is_pushout cof_a\u2083) cof_fs\u2083')\n  end,\n  begin\n    slice_lhs 3 4 { rw hf'sr },\n    slice_lhs 2 3 { rw Is_pushout.induced_commutes\u2080 },\n    slice_lhs 1 2 { rw Is_pushout.induced_commutes\u2081 },\n    simp [sr]\n  end,\n  s\u2082r\u2082\u27e9,\n b',\n begin\n   convert congr_arg (\u03bb z, c\u2081.ab.map\u2080 \u226b z) hfs\u2083' using 1,\n   { slice_rhs 1 2 { rw Is_pushout.induced_commutes\u2080 } },\n   { slice_rhs 1 2 { dsimp [pushout_of_maps], rw Is_pushout.induced_commutes\u2080 }, simp }\n end,\n begin\n   have : c\u2081.r \u226b b = c\u2081.r \u226b b \u226b (s \u226b r), by rw [sr]; simp,\n   rw this,\n   slice_lhs 1 3 { rw hr\u2083 },\n   simp\n end,\n begin\n   convert congr_arg (\u03bb z, c\u2081.ab.map\u2081 \u226b z) hfs\u2083' using 1,\n   { slice_rhs 1 2 { rw Is_pushout.induced_commutes\u2081 } },\n   { slice_rhs 1 2 { dsimp [pushout_of_maps], rw Is_pushout.induced_commutes\u2081 }, simp }\n end,\n begin\n   intro hb,\n   let v := _,\n   let S\u2082 : cof_square v b' := \u27e8_, _, _, _, cof_p\u27e9,\n   let S\u2081 : cof_square a v,\n   { refine \u27e8c\u2081.ab.map\u2080, f' \u226b a\u2083b\u2083.map\u2080,\n       by simp [v, pushout_of_maps], pushout_is_cof c\u2081.ab.is_pushout.transpose hb\u2081, _\u27e9,\n     let po : pushout _ _ := _,\n     change is_cof (po.is_pushout.induced _ _ _),\n     have : is_cof (b \u226b s) := cof_comp hb acof_s.1,\n     convert cof_pushout this cof_f'\n       (Is_pushout_of_Is_pushout_of_Is_pushout c\u2081.ab.is_pushout.transpose po.is_pushout)\n       (by convert a\u2083b\u2083.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\u2081.f' = S\u2081.f\u2081 \u226b S\u2082.f\u2081, by simp,\n   have S : is_cof_square a b' c\u2081.f' _ :=\n     is_cof_square_comp \u27e8S\u2081, rfl, rfl\u27e9 \u27e8S\u2082, rfl, rfl\u27e9 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 \u27e8this, _\u27e9,\n     have sG : s \u226b G = s\u2082, by simp,\n     have : is_acof s := pushout_is_acof po_b.is_pushout c\u2081.hs,\n     refine category_with_weak_equivalences.weq_of_comp_weq_left this.2 _,\n     rw sG,\n     exact (weq_iff_weq_inv s\u2082r\u2082).mpr weq_r\u2082 },\n   -- From here on, the proof resembles the previous one\n   let v := _,\n   let S\u2082 : cof_square v b' := \u27e8_, _, _, _, cof_p\u27e9,\n   let S\u2081 : cof_square b v,\n   { refine \u27e8c\u2081.ab.map\u2081, s \u226b a\u2083b\u2083.map\u2081,\n       by simp [v, pushout_of_maps], pushout_is_cof c\u2081.ab.is_pushout ha\u2081, _\u27e9,\n     let po : pushout _ _ := _,\n     change is_cof (po.is_pushout.induced _ _ _),\n     have : is_cof (a \u226b f') := cof_comp ha cof_f',\n     convert cof_pushout this acof_s.1\n       (Is_pushout_of_Is_pushout_of_Is_pushout c\u2081.ab.is_pushout po.is_pushout)\n       (by convert a\u2083b\u2083.is_pushout; apply initial.uniqueness)\n       (by apply initial.uniqueness) using 1,\n     symmetry,\n     apply pushout_induced_eq_iff; simp },\n   have : c\u2081.s = S\u2081.f\u2081 \u226b S\u2082.f\u2081, by simp,\n   have S : is_cof_square b b' c\u2081.s _ :=\n     is_cof_square_comp \u27e8S\u2081, rfl, rfl\u27e9 \u27e8S\u2082, rfl, rfl\u27e9 this rfl,\n   convert S.corner_cof.snd.snd,\n   simp\n end\u27e9\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": "/-\nCopyright (c) 2022 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.Notation\nset_option linter.all false -- prevent error messages from runFrontend\n\nnamespace Lean.Parser.Tactic\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 tactic : tactic\n\n/--\nIntroduces one or more hypotheses, optionally naming and/or pattern-matching them.\nFor each hypothesis to be introduced, the remaining main goal's target type must\nbe a `let` or function type.\n\n* `intro` by itself introduces one anonymous hypothesis, which can be accessed\n  by e.g. `assumption`.\n* `intro x y` introduces two hypotheses and names them. Individual hypotheses\n  can be anonymized via `_`, or matched against a pattern:\n  ```lean\n  -- ... \u22a2 \u03b1 \u00d7 \u03b2 \u2192 ...\n  intro (a, b)\n  -- ..., a : \u03b1, b : \u03b2 \u22a2 ...\n  ```\n* Alternatively, `intro` can be combined with pattern matching much like `fun`:\n  ```lean\n  intro\n  | n + 1, 0 => tac\n  | ...\n  ```\n-/\nsyntax (name := intro) \"intro \" notFollowedBy(\"|\") (colGt term:max)* : tactic\n\n/--\n`intros x...` behaves like `intro x...`, but then keeps introducing (anonymous)\nhypotheses until goal is not of a function type.\n-/\nsyntax (name := intros) \"intros \" (colGt (ident <|> hole))* : tactic\n\n/--\n`rename t => x` renames the most recent hypothesis whose type matches `t`\n(which may contain placeholders) to `x`, or fails if no such hypothesis could be found.\n-/\nsyntax (name := rename) \"rename \" term \" => \" ident : tactic\n\n/--\n`revert x...` is the inverse of `intro x...`: it moves the given hypotheses\ninto the main goal's target type.\n-/\nsyntax (name := revert) \"revert \" (colGt term:max)+ : tactic\n\n/--\n`clear x...` removes the given hypotheses, or fails if there are remaining\nreferences to a hypothesis.\n-/\nsyntax (name := clear) \"clear \" (colGt term:max)+ : tactic\n\n/--\n`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis\nof type `x = e` or `e = x`.\nIf `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead.\n-/\nsyntax (name := subst) \"subst \" (colGt term:max)+ : tactic\n\n/--\nApplies `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.\n-/\nsyntax (name := substVars) \"subst_vars\" : tactic\n\n/--\n`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.\nNote also the `\u2039t\u203a` term notation, which is a shorthand for `show t by assumption`.\n-/\nsyntax (name := assumption) \"assumption\" : tactic\n\n/--\n`contradiction` closes the main goal if its hypotheses are \"trivially contradictory\".\n- Inductive type/family with no applicable constructors\n```lean\nexample (h : False) : p := by contradiction\n```\n- Injectivity of constructors\n```lean\nexample (h : none = some true) : p := by contradiction  --\n```\n- Decidable false proposition\n```lean\nexample (h : 2 + 2 = 3) : p := by contradiction\n```\n- Contradictory hypotheses\n```lean\nexample (h : p) (h' : \u00ac p) : q := by contradiction\n```\n- Other simple contradictions such as\n```lean\nexample (x : Nat) (h : x \u2260 x) : p := by contradiction\n```\n-/\nsyntax (name := contradiction) \"contradiction\" : tactic\n\n/--\n`apply e` tries to match the current goal against the conclusion of `e`'s type.\nIf it succeeds, then the tactic returns as many subgoals as the number of premises that\nhave not been fixed by type inference or type class resolution.\nNon-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution,\nand first-order unification with dependent types.\n-/\nsyntax (name := apply) \"apply \" term : tactic\n\n/--\n`exact e` closes the main goal if its target type matches that of `e`.\n-/\nsyntax (name := exact) \"exact \" term : tactic\n\n/--\n`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`)\nholes in `e` that are not solved by unification with the main goal's target type\nare converted into new goals, using the hole's name, if any, as the goal case name.\n-/\nsyntax (name := refine) \"refine \" term : tactic\n\n/--\n`refine' e` behaves like `refine e`, except that unsolved placeholders (`_`)\nand implicit parameters are also converted into new goals.\n-/\nsyntax (name := refine') \"refine' \" term : tactic\n\n/--\nIf the main goal's target type is an inductive type, `constructor` solves it with\nthe first matching constructor, or else fails.\n-/\nsyntax (name := constructor) \"constructor\" : tactic\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\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses\n  with inaccessible names to the given names.\n* `case tag\u2081 | tag\u2082 => tac` is equivalent to `(case tag\u2081 => tac); (case tag\u2082 => tac)`.\n-/\nsyntax (name := case) \"case \" sepBy1(caseArg, \" | \") \" => \" tacticSeq : tactic\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-/\nsyntax (name := case') \"case' \" sepBy1(caseArg, \" | \") \" => \" tacticSeq : tactic\n\n/--\n`next => tac` focuses on the next goal and solves it using `tac`, or else fails.\n`next x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with\ninaccessible names to the given names.\n-/\nmacro \"next \" args:binderIdent* \" => \" tac:tacticSeq : tactic => `(tactic| case _ $args* => $tac)\n\n/-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/\nsyntax (name := allGoals) \"all_goals \" tacticSeq : tactic\n\n/--\n`any_goals tac` applies the tactic `tac` to every goal, and succeeds if at\nleast one application succeeds.\n-/\nsyntax (name := anyGoals) \"any_goals \" tacticSeq : tactic\n\n/--\n`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.\nUsually `\u00b7 tac`, which enforces that the goal is closed by `tac`, should be preferred.\n-/\nsyntax (name := focus) \"focus \" tacticSeq : tactic\n\n/-- `skip` does nothing. -/\nsyntax (name := skip) \"skip\" : tactic\n\n/-- `done` succeeds iff there are no remaining goals. -/\nsyntax (name := done) \"done\" : tactic\n\n/-- `trace_state` displays the current state in the info view. -/\nsyntax (name := traceState) \"trace_state\" : tactic\n\n/-- `trace msg` displays `msg` in the info view. -/\nsyntax (name := traceMessage) \"trace \" str : tactic\n\n/-- `fail_if_success t` fails if the tactic `t` succeeds. -/\nsyntax (name := failIfSuccess) \"fail_if_success \" tacticSeq : tactic\n\n/--\n`(tacs)` executes a list of tactics in sequence, without requiring that\nthe goal be closed at the end like `\u00b7 tacs`. Like `by` itself, the tactics\ncan be either separated by newlines or `;`.\n-/\nsyntax (name := paren) \"(\" withoutPosition(tacticSeq) \")\" : tactic\n\n/--\n`with_reducible tacs` excutes `tacs` using the reducible transparency setting.\nIn this setting only definitions tagged as `[reducible]` are unfolded.\n-/\nsyntax (name := withReducible) \"with_reducible \" tacticSeq : tactic\n\n/--\n`with_reducible_and_instances tacs` excutes `tacs` using the `.instances` transparency setting.\nIn this setting only definitions tagged as `[reducible]` or type class instances are unfolded.\n-/\nsyntax (name := withReducibleAndInstances) \"with_reducible_and_instances \" tacticSeq : tactic\n\n/--\n`with_unfolding_all tacs` excutes `tacs` using the `.all` transparency setting.\nIn this setting all definitions that are not opaque are unfolded.\n-/\nsyntax (name := withUnfoldingAll) \"with_unfolding_all \" tacticSeq : tactic\n\n/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/\nsyntax (name := first) \"first \" withPosition((colGe \"|\" tacticSeq)+) : tactic\n\n/--\n`rotate_left n` rotates goals to the left by `n`. That is, `rotate_left 1`\ntakes the main goal and puts it to the back of the subgoal list.\nIf `n` is omitted, it defaults to `1`.\n-/\nsyntax (name := rotateLeft) \"rotate_left\" (num)? : tactic\n\n/--\nRotate the goals to the right by `n`. That is, take the goal at the back\nand push it to the front `n` times. If `n` is omitted, it defaults to `1`.\n-/\nsyntax (name := rotateRight) \"rotate_right\" (num)? : tactic\n\n/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/\nmacro \"try \" t:tacticSeq : tactic => `(tactic| first | $t | skip)\n\n/--\n`tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal,\nconcatenating all goals produced by `tac'`.\n-/\nmacro:1 x:tactic tk:\" <;> \" y:tactic:2 : tactic => `(tactic|\n  focus\n    $x:tactic\n    -- annotate token with state after executing `x`\n    with_annotate_state $tk skip\n    all_goals $y:tactic)\n\n/-- `eq_refl` is equivalent to `exact rfl`, but has a few optimizations. -/\nsyntax (name := refl) \"eq_refl\" : tactic\n\n/--\n`rfl` tries to close the current goal using reflexivity.\nThis is supposed to be an extensible tactic and users can add their own support\nfor new reflexive relations.\n-/\nmacro \"rfl\" : tactic => `(tactic| eq_refl)\n\n/--\n`rfl'` is similar to `rfl`, but disables smart unfolding and unfolds all kinds of definitions,\ntheorems included (relevant for declarations defined by well-founded recursion).\n-/\nmacro \"rfl'\" : tactic => `(tactic| set_option smartUnfolding false in with_unfolding_all rfl)\n\n/--\n`ac_rfl` proves equalities up to application of an associative and commutative operator.\n```\ninstance : IsAssociative (\u03b1 := Nat) (.+.) := \u27e8Nat.add_assoc\u27e9\ninstance : IsCommutative (\u03b1 := Nat) (.+.) := \u27e8Nat.add_comm\u27e9\n\nexample (a b c d : Nat) : a + b + c + d = d + (b + c) + a := by ac_rfl\n```\n-/\nsyntax (name := acRfl) \"ac_rfl\" : tactic\n\n/--\nThe `sorry` tactic closes the goal using `sorryAx`. This is intended for stubbing out incomplete\nparts of a proof while still having a syntactically correct proof skeleton. Lean will give\na warning whenever a proof uses `sorry`, so you aren't likely to miss it, but\nyou can double check if a theorem depends on `sorry` by using\n`#print axioms my_thm` and looking for `sorryAx` in the axiom list.\n-/\nmacro \"sorry\" : tactic => `(tactic| exact @sorryAx _ false)\n\n/-- `admit` is a shorthand for `exact sorry`. -/\nmacro \"admit\" : tactic => `(tactic| exact @sorryAx _ false)\n\n/--\n`infer_instance` is an abbreviation for `exact inferInstance`.\nIt synthesizes a value of any target type by typeclass inference.\n-/\nmacro \"infer_instance\" : tactic => `(tactic| exact inferInstance)\n\n/-- Optional configuration option for tactics -/\nsyntax config := atomic(\" (\" &\"config\") \" := \" withoutPosition(term) \")\"\n\n/-- The `*` location refers to all hypotheses and the goal. -/\nsyntax locationWildcard := \"*\"\n\n/--\nA hypothesis location specification consists of 1 or more hypothesis references\nand optionally `\u22a2` denoting the goal.\n-/\nsyntax locationHyp := (colGt term:max)+ patternIgnore(\"\u22a2\" <|> \"|-\")?\n\n/--\nLocation specifications are used by many tactics that can operate on either the\nhypotheses or the goal. It can have one of the forms:\n* 'empty' is not actually present in this syntax, but most tactics use\n  `(location)?` matchers. It means to target the goal only.\n* `at h\u2081 ... h\u2099`: target the hypotheses `h\u2081`, ..., `h\u2099`\n* `at h\u2081 h\u2082 \u22a2`: target the hypotheses `h\u2081` and `h\u2082`, and the goal\n* `at *`: target all hypotheses and the goal\n-/\nsyntax location := withPosition(\" at \" (locationWildcard <|> locationHyp))\n\n/--\n* `change tgt'` will change the goal from `tgt` to `tgt'`,\n  assuming these are definitionally equal.\n* `change t' at h` will change hypothesis `h : t` to have type `t'`, assuming\n  assuming `t` and `t'` are definitionally equal.\n-/\nsyntax (name := change) \"change \" term (location)? : tactic\n\n/--\n* `change a with b` will change occurrences of `a` to `b` in the goal,\n  assuming `a` and `b` are are definitionally equal.\n* `change a with b at h` similarly changes `a` to `b` in the type of hypothesis `h`.\n-/\nsyntax (name := changeWith) \"change \" term \" with \" term (location)? : tactic\n\n/--\nIf `thm` is a theorem `a = b`, then as a rewrite rule,\n* `thm` means to replace `a` with `b`, and\n* `\u2190 thm` means to replace `b` with `a`.\n-/\nsyntax rwRule    := patternIgnore(\"\u2190 \" <|> \"<- \")? term\n/-- A `rwRuleSeq` is a list of `rwRule` in brackets. -/\nsyntax rwRuleSeq := \" [\" withoutPosition(rwRule,*,?) \"]\"\n\n/--\n`rewrite [e]` applies identity `e` as a rewrite rule to the target of the main goal.\nIf `e` is preceded by left arrow (`\u2190` or `<-`), the rewrite is applied in the reverse direction.\nIf `e` is a defined constant, then the equational theorems associated with `e` are used.\nThis provides a convenient way to unfold `e`.\n- `rewrite [e\u2081, ..., e\u2099]` applies the given rules sequentially.\n- `rewrite [e] at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a\n  list of hypotheses in the local context. In the latter case, a turnstile `\u22a2` or `|-`\n  can also be used, to signify the target of the goal.\n-/\nsyntax (name := rewriteSeq) \"rewrite\" (config)? rwRuleSeq (location)? : tactic\n\n/--\n`rw` is like `rewrite`, but also tries to close the goal by \"cheap\" (reducible) `rfl` afterwards.\n-/\nmacro (name := rwSeq) \"rw\" c:(config)? s:rwRuleSeq l:(location)? : tactic =>\n  match s with\n  | `(rwRuleSeq| [$rs,*]%$rbrak) =>\n    -- We show the `rfl` state on `]`\n    `(tactic| (rewrite $(c)? [$rs,*] $(l)?; with_annotate_state $rbrak (try (with_reducible rfl))))\n  | _ => Macro.throwUnsupported\n\n/--\nThe `injection` tactic is based on the fact that constructors of inductive data\ntypes are injections.\nThat means that if `c` is a constructor of an inductive datatype, and if `(c t\u2081)`\nand `(c t\u2082)` are two terms that are equal then  `t\u2081` and `t\u2082` are equal too.\nIf `q` is a proof of a statement of conclusion `t\u2081 = t\u2082`, then injection applies\ninjectivity to derive the equality of all arguments of `t\u2081` and `t\u2082` placed in\nthe same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`.\nTo use this tactic `t\u2081` and `t\u2082` should be constructor applications of the same constructor.\nGiven `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types\n`a = c` and `b = d` to the main goal.\nThe tactic `injection h with h\u2081 h\u2082` uses the names `h\u2081` and `h\u2082` to name the new hypotheses.\n-/\nsyntax (name := injection) \"injection \" term (\" with \" (colGt (ident <|> hole))+)? : tactic\n\n/-- `injections` applies `injection` to all hypotheses recursively\n(since `injection` can produce new hypotheses). Useful for destructing nested\nconstructor equalities like `(a::b::c) = (d::e::f)`. -/\n-- TODO: add with\nsyntax (name := injections) \"injections\" (colGt (ident <|> hole))* : tactic\n\n/--\nThe discharger clause of `simp` and related tactics.\nThis is a tactic used to discharge the side conditions on conditional rewrite rules.\n-/\nsyntax discharger := atomic(\" (\" patternIgnore(&\"discharger\" <|> &\"disch\")) \" := \" withoutPosition(tacticSeq) \")\"\n\n/-- Use this rewrite rule before entering the subterms -/\nsyntax simpPre   := \"\u2193\"\n/-- Use this rewrite rule after entering the subterms -/\nsyntax simpPost  := \"\u2191\"\n/--\nA simp lemma specification is:\n* optional `\u2191` or `\u2193` to specify use before or after entering the subterm\n* optional `\u2190` to use the lemma backward\n* `thm` for the theorem to rewrite with\n-/\nsyntax simpLemma := (simpPre <|> simpPost)? patternIgnore(\"\u2190 \" <|> \"<- \")? term\n/-- An erasure specification `-thm` says to remove `thm` from the simp set -/\nsyntax simpErase := \"-\" term:max\n/-- The simp lemma specification `*` means to rewrite with all hypotheses -/\nsyntax simpStar  := \"*\"\n/--\nThe `simp` tactic uses lemmas and hypotheses to simplify the main goal target or\nnon-dependent hypotheses. It has many variants:\n- `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.\n- `simp [h\u2081, h\u2082, ..., h\u2099]` simplifies the main goal target using the lemmas tagged\n  with the attribute `[simp]` and the given `h\u1d62`'s, where the `h\u1d62`'s are expressions.\n  If an `h\u1d62` is a defined constant `f`, then the equational lemmas associated with\n  `f` are used. This provides a convenient way to unfold `f`.\n- `simp [*]` simplifies the main goal target using the lemmas tagged with the\n  attribute `[simp]` and all hypotheses.\n- `simp only [h\u2081, h\u2082, ..., h\u2099]` is like `simp [h\u2081, h\u2082, ..., h\u2099]` but does not use `[simp]` lemmas.\n- `simp [-id\u2081, ..., -id\u2099]` simplifies the main goal target using the lemmas tagged\n  with the attribute `[simp]`, but removes the ones named `id\u1d62`.\n- `simp at h\u2081 h\u2082 ... h\u2099` simplifies the hypotheses `h\u2081 : T\u2081` ... `h\u2099 : T\u2099`. If\n  the target or another hypothesis depends on `h\u1d62`, a new simplified hypothesis\n  `h\u1d62` is introduced, but the old one remains in the local context.\n- `simp at *` simplifies all the hypotheses and the target.\n- `simp [*] at *` simplifies target and all (propositional) hypotheses using the\n  other hypotheses.\n-/\nsyntax (name := simp) \"simp\" (config)? (discharger)? (&\" only\")?\n  (\" [\" withoutPosition((simpStar <|> simpErase <|> simpLemma),*) \"]\")? (location)? : tactic\n/--\n`simp_all` is a stronger version of `simp [*] at *` where the hypotheses and target\nare simplified multiple times until no simplication is applicable.\nOnly non-dependent propositional hypotheses are considered.\n-/\nsyntax (name := simpAll) \"simp_all\" (config)? (discharger)? (&\" only\")?\n  (\" [\" withoutPosition((simpErase <|> simpLemma),*) \"]\")? : tactic\n\n/--\nThe `dsimp` tactic is the definitional simplifier. It is similar to `simp` but only\napplies theorems that hold by reflexivity. Thus, the result is guaranteed to be\ndefinitionally equal to the input.\n-/\nsyntax (name := dsimp) \"dsimp\" (config)? (discharger)? (&\" only\")?\n  (\" [\" withoutPosition((simpErase <|> simpLemma),*) \"]\")? (location)? : tactic\n\n/--\n`delta id1 id2 ...` delta-expands the definitions `id1`, `id2`, ....\nThis is a low-level tactic, it will expose how recursive definitions have been\ncompiled by Lean.\n-/\nsyntax (name := delta) \"delta \" (colGt ident)+ (location)? : tactic\n\n/--\n* `unfold id` unfolds definition `id`.\n* `unfold id1 id2 ...` is equivalent to `unfold id1; unfold id2; ...`.\n\nFor non-recursive definitions, this tactic is identical to `delta`.\nFor definitions by pattern matching, it uses \"equation lemmas\" which are\nautogenerated for each match arm.\n-/\nsyntax (name := unfold) \"unfold \" (colGt ident)+ (location)? : tactic\n\n/--\nAuxiliary macro for lifting have/suffices/let/...\nIt makes sure the \"continuation\" `?_` is the main goal after refining.\n-/\nmacro \"refine_lift \" e:term : tactic => `(tactic| focus (refine no_implicit_lambda% $e; rotate_right))\n\n/--\n`have h : t := e` adds the hypothesis `h : t` to the current goal if `e` a term\nof type `t`.\n* If `t` is omitted, it will be inferred.\n* If `h` is omitted, the name `this` is used.\n* The variant `have pattern := e` is equivalent to `match e with | pattern => _`,\n  and it is convenient for types that have only one applicable constructor.\n  For example, given `h : p \u2227 q \u2227 r`, `have \u27e8h\u2081, h\u2082, h\u2083\u27e9 := h` produces the\n  hypotheses `h\u2081 : p`, `h\u2082 : q`, and `h\u2083 : r`.\n-/\nmacro \"have \" d:haveDecl : tactic => `(tactic| refine_lift have $d:haveDecl; ?_)\n\n/--\nGiven a main goal `ctx \u22a2 t`, `suffices h : t' from e` replaces the main goal with `ctx \u22a2 t'`,\n`e` must have type `t` in the context `ctx, h : t'`.\n\nThe variant `suffices h : t' by tac` is a shorthand for `suffices h : t' from by tac`.\nIf `h :` is omitted, the name `this` is used.\n -/\nmacro \"suffices \" d:sufficesDecl : tactic => `(tactic| refine_lift suffices $d; ?_)\n/--\n`let h : t := e` adds the hypothesis `h : t := e` to the current goal if `e` a term of type `t`.\nIf `t` is omitted, it will be inferred.\nThe variant `let pattern := e` is equivalent to `match e with | pattern => _`,\nand it is convenient for types that have only applicable constructor.\nExample: given `h : p \u2227 q \u2227 r`, `let \u27e8h\u2081, h\u2082, h\u2083\u27e9 := h` produces the hypotheses\n`h\u2081 : p`, `h\u2082 : q`, and `h\u2083 : r`.\n-/\nmacro \"let \" d:letDecl : tactic => `(tactic| refine_lift let $d:letDecl; ?_)\n/--\n`show t` finds the first goal whose target unifies with `t`. It makes that the main goal,\n performs the unification, and replaces the target with the unified version of `t`.\n-/\nmacro \"show \" e:term : tactic => `(tactic| refine_lift show $e from ?_) -- TODO: fix, see comment\n/-- `let rec f : t := e` adds a recursive definition `f` to the current goal.\nThe syntax is the same as term-mode `let rec`. -/\nsyntax (name := letrec) withPosition(atomic(\"let \" &\"rec \") letRecDecls) : tactic\nmacro_rules\n  | `(tactic| let rec $d) => `(tactic| refine_lift let rec $d; ?_)\n\n/-- Similar to `refine_lift`, but using `refine'` -/\nmacro \"refine_lift' \" e:term : tactic => `(tactic| focus (refine' no_implicit_lambda% $e; rotate_right))\n/-- Similar to `have`, but using `refine'` -/\nmacro \"have' \" d:haveDecl : tactic => `(tactic| refine_lift' have $d:haveDecl; ?_)\n/-- Similar to `have`, but using `refine'` -/\nmacro (priority := high) \"have'\" x:ident \" := \" p:term : tactic => `(tactic| have' $x : _ := $p)\n/-- Similar to `let`, but using `refine'` -/\nmacro \"let' \" d:letDecl : tactic => `(tactic| refine_lift' let $d:letDecl; ?_)\n\n/--\nThe left hand side of an induction arm, `| foo a b c` or `| @foo a b c`\nwhere `foo` is a constructor of the inductive type and `a b c` are the arguments\nto the contstructor.\n-/\nsyntax inductionAltLHS := \"| \" ((\"@\"? ident) <|> hole) (ident <|> hole)*\n/--\nIn induction alternative, which can have 1 or more cases on the left\nand `_`, `?_`, or a tactic sequence after the `=>`.\n-/\nsyntax inductionAlt  := ppDedent(ppLine) inductionAltLHS+ \" => \" (hole <|> syntheticHole <|> tacticSeq)\n/--\nAfter `with`, there is an optional tactic that runs on all branches, and\nthen a list of alternatives.\n-/\nsyntax inductionAlts := \"with \" (tactic)? withPosition((colGe inductionAlt)+)\n\n/--\nAssuming `x` is a variable in the local context with an inductive type,\n`induction x` applies induction on `x` to the main goal,\nproducing one goal for each constructor of the inductive type,\nin which the target is replaced by a general instance of that constructor\nand an inductive hypothesis is added for each recursive argument to the constructor.\nIf the type of an element in the local context depends on `x`,\nthat element is reverted and reintroduced afterward,\nso that the inductive hypothesis incorporates that hypothesis as well.\n\nFor example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`,\n`induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`,\nand one goal with hypotheses `h : P (Nat.succ a)` and `ih\u2081 : P a \u2192 Q a` and target `Q (Nat.succ a)`.\nHere the names `a` and `ih\u2081` are chosen automatically and are not accessible.\nYou can use `with` to provide the variables names for each constructor.\n- `induction e`, where `e` is an expression instead of a variable,\n  generalizes `e` in the goal, and then performs induction on the resulting variable.\n- `induction e using r` allows the user to specify the principle of induction that should be used.\n  Here `r` should be a theorem whose result type must be of the form `C t`,\n  where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables\n- `induction e generalizing z\u2081 ... z\u2099`, where `z\u2081 ... z\u2099` are variables in the local context,\n  generalizes over `z\u2081 ... z\u2099` before applying the induction but then introduces them in each goal.\n  In other words, the net effect is that each inductive hypothesis is generalized.\n- Given `x : Nat`, `induction x with | zero => tac\u2081 | succ x' ih => tac\u2082`\n  uses tactic `tac\u2081` for the `zero` case, and `tac\u2082` for the `succ` case.\n-/\nsyntax (name := induction) \"induction \" term,+ (\" using \" ident)?\n  (\"generalizing \" (colGt term:max)+)? (inductionAlts)? : tactic\n\n/-- A `generalize` argument, of the form `term = x` or `h : term = x`. -/\nsyntax generalizeArg := atomic(ident \" : \")? term:51 \" = \" ident\n\n/--\n* `generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal\n  with a fresh hypothesis `x`s. If `h` is given, `h : e = x` is introduced as well.\n* `generalize e = x at h\u2081 ... h\u2099` also generalizes occurrences of `e`\n  inside `h\u2081`, ..., `h\u2099`.\n* `generalize e = x at *` will generalize occurrences of `e` everywhere.\n-/\nsyntax (name := generalize) \"generalize \" generalizeArg,+ (location)? : tactic\n\n/--\nA `cases` argument, of the form `e` or `h : e` (where `h` asserts that\n`e = c\u1d62 a b` for each constructor `c\u1d62` of the inductive).\n-/\nsyntax casesTarget := atomic(ident \" : \")? term\n/--\nAssuming `x` is a variable in the local context with an inductive type,\n`cases x` splits the main goal, producing one goal for each constructor of the\ninductive type, in which the target is replaced by a general instance of that constructor.\nIf the type of an element in the local context depends on `x`,\nthat element is reverted and reintroduced afterward,\nso that the case split affects that hypothesis as well.\n`cases` detects unreachable cases and closes them automatically.\n\nFor example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`,\n`cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`,\nand one goal with hypothesis `h : P (Nat.succ a)` and target `Q (Nat.succ a)`.\nHere the name `a` is chosen automatically and is not accessible.\nYou can use `with` to provide the variables names for each constructor.\n- `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal,\n  and then cases on the resulting variable.\n- Given `as : List \u03b1`, `cases as with | nil => tac\u2081 | cons a as' => tac\u2082`,\n  uses tactic `tac\u2081` for the `nil` case, and `tac\u2082` for the `cons` case,\n  and `a` and `as'` are used as names for the new variables introduced.\n- `cases h : e`, where `e` is a variable or an expression,\n  performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis,\n  where `...` is the constructor instance for that particular case.\n-/\nsyntax (name := cases) \"cases \" casesTarget,+ (\" using \" ident)? (inductionAlts)? : tactic\n\n/-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/\nsyntax (name := renameI) \"rename_i \" (colGt binderIdent)+ : tactic\n\n/--\n`repeat tac` applies `tac` to main goal. If the application succeeds,\nthe tactic is applied recursively to the generated subgoals until it eventually fails.\n-/\nsyntax \"repeat \" tacticSeq : tactic\nmacro_rules\n  | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)\n\n/--\n`trivial` tries different simple tactics (e.g., `rfl`, `contradiction`, ...)\nto close the current goal.\nYou can use the command `macro_rules` to extend the set of tactics used. Example:\n```\nmacro_rules | `(tactic| trivial) => `(tactic| simp)\n```\n-/\nsyntax \"trivial\" : tactic\n\n/--\nThe `split` tactic is useful for breaking nested if-then-else and `match` expressions into separate cases.\nFor a `match` expression with `n` cases, the `split` tactic generates at most `n` subgoals.\n\nFor example, given `n : Nat`, and a target `if n = 0 then Q else R`, `split` will generate\none goal with hypothesis `n = 0` and target `Q`, and a second goal with hypothesis\n`\u00acn = 0` and target `R`.  Note that the introduced hypothesis is unnamed, and is commonly\nrenamed used the `case` or `next` tactics.\n\n- `split` will split the goal (target).\n- `split at h` will split the hypothesis `h`.\n-/\nsyntax (name := split) \"split \" (colGt term)? (location)? : tactic\n\n/-- `dbg_trace \"foo\"` prints `foo` when elaborated.\nUseful for debugging tactic control flow:\n```\nexample : False \u2228 True := by\n  first\n  | apply Or.inl; trivial; dbg_trace \"left\"\n  | apply Or.inr; trivial; dbg_trace \"right\"\n```\n-/\nsyntax (name := dbgTrace) \"dbg_trace \" str : tactic\n\n/--\n`stop` is a helper tactic for \"discarding\" the rest of a proof:\nit is defined as `repeat sorry`.\nIt is useful when working on the middle of a complex proofs,\nand less messy than commenting the remainder of the proof.\n-/\nmacro \"stop\" tacticSeq : tactic => `(tactic| repeat sorry)\n\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`.\nThe premises of this hypothesis, either universal quantifications or\nnon-dependent implications, are instantiated by concrete terms coming\nfrom arguments `a\u2081` ... `a\u2099`.\nThe tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099`\nand tries to clear the previous one.\n-/\nsyntax (name := specialize) \"specialize \" term : tactic\n\nmacro_rules | `(tactic| trivial) => `(tactic| assumption)\nmacro_rules | `(tactic| trivial) => `(tactic| rfl)\nmacro_rules | `(tactic| trivial) => `(tactic| contradiction)\nmacro_rules | `(tactic| trivial) => `(tactic| decide)\nmacro_rules | `(tactic| trivial) => `(tactic| apply True.intro)\nmacro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)\n\n/--\n`unhygienic tacs` runs `tacs` with name hygiene disabled.\nThis means that tactics that would normally create inaccessible names will instead\nmake regular variables. **Warning**: Tactics may change their variable naming\nstrategies at any time, so code that depends on autogenerated names is brittle.\nUsers should try not to use `unhygienic` if possible.\n```\nexample : \u2200 x : Nat, x = x := by unhygienic\n  intro            -- x would normally be intro'd as inaccessible\n  exact Eq.refl x  -- refer to x\n```\n-/\nmacro \"unhygienic \" t:tacticSeq : tactic => `(tactic| set_option tactic.hygienic false in $t)\n\n/-- `fail msg` is a tactic that always fails, and produces an error using the given message. -/\nsyntax (name := fail) \"fail \" (str)? : tactic\n\n/--\n`checkpoint tac` acts the same as `tac`, but it caches the input and output of `tac`,\nand if the file is re-elaborated and the input matches, the tactic is not re-run and\nits effects are reapplied to the state. This is useful for improving responsiveness\nwhen working on a long tactic proof, by wrapping expensive tactics with `checkpoint`.\n\nSee the `save` tactic, which may be more convenient to use.\n\n(TODO: do this automatically and transparently so that users don't have to use\nthis combinator explicitly.)\n-/\nsyntax (name := checkpoint) \"checkpoint \" tacticSeq : tactic\n\n/--\n`save` is defined to be the same as `skip`, but the elaborator has\nspecial handling for occurrences of `save` in tactic scripts and will transform\n`by tac1; save; tac2` to `by (checkpoint tac1); tac2`, meaning that the effect of `tac1`\nwill be cached and replayed. This is useful for improving responsiveness\nwhen working on a long tactic proof, by using `save` after expensive tactics.\n\n(TODO: do this automatically and transparently so that users don't have to use\nthis combinator explicitly.)\n-/\nmacro (name := save) \"save\" : tactic => `(tactic| skip)\n\n/--\nThe tactic `sleep ms` sleeps for `ms` milliseconds and does nothing.\nIt is used for debugging purposes only.\n-/\nsyntax (name := sleep) \"sleep\" num : tactic\n\n/--\n`exists e\u2081, e\u2082, ...` is shorthand for `refine \u27e8e\u2081, e\u2082, ...\u27e9; try trivial`.\nIt is useful for existential goals.\n-/\nmacro \"exists \" es:term,+ : tactic =>\n  `(tactic| (refine \u27e8$es,*, ?_\u27e9; try trivial))\n\n/--\nApply congruence (recursively) to goals of the form `\u22a2 f as = f bs` and `\u22a2 HEq (f as) (f bs)`.\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 `\u22a2 f (g (x + y)) = f (g (y + x))`,\n`congr` produces the goals `\u22a2 x = y` and `\u22a2 y = x`,\nwhile `congr 2` produces the intended `\u22a2 x + y = y + x`.\n-/\nsyntax (name := congr) \"congr \" (num)? : tactic\n\nend Tactic\n\nnamespace Attr\n/--\nTheorems tagged with the `simp` attribute are by the simplifier\n(i.e., the `simp` tactic, and its variants) to simplify expressions occurring in your goals.\nWe call theorems tagged with the `simp` attribute \"simp theorems\" or \"simp lemmas\".\nLean maintains a database/index containing all active simp theorems.\nHere is an example of a simp theorem.\n```lean\n@[simp] theorem ne_eq (a b : \u03b1) : (a \u2260 b) = Not (a = b) := rfl\n```\nThis simp theorem instructs the simplifier to replace instances of the term\n`a \u2260 b` (e.g. `x + 0 \u2260 y`) with `Not (a = b)` (e.g., `Not (x + 0 = y)`).\nThe simplifier applies simp theorems in one direction only:\nif `A = B` is a simp theorem, then `simp` replaces `A`s with `B`s,\nbut it doesn't replace `B`s with `A`s. Hence a simp theorem should have the\nproperty that its right-hand side is \"simpler\" than its left-hand side.\nIn particular, `=` and `\u2194` should not be viewed as symmetric operators in this situation.\nThe following would be a terrible simp theorem (if it were even allowed):\n```lean\n@[simp] lemma mul_right_inv_bad (a : G) : 1 = a * a\u207b\u00b9 := ...\n```\nReplacing 1 with a * a\u207b\u00b9 is not a sensible default direction to travel.\nEven worse would be a theorem that causes expressions to grow without bound,\ncausing simp to loop forever.\n\nBy default the simplifier applies `simp` theorems to an expression `e`\nafter its sub-expressions have been simplified.\nWe say it performs a bottom-up simplification.\nYou can instruct the simplifier to apply a theorem before its sub-expressions\nhave been simplified by using the modifier `\u2193`. Here is an example\n```lean\n@[simp\u2193] theorem not_and_eq (p q : Prop) : (\u00ac (p \u2227 q)) = (\u00acp \u2228 \u00acq) :=\n```\n\nWhen multiple simp theorems are applicable, the simplifier uses the one with highest priority.\nIf there are several with the same priority, it is uses the \"most recent one\". Example:\n```lean\n@[simp high] theorem cond_true (a b : \u03b1) : cond true a b = a := rfl\n@[simp low+1] theorem or_true (p : Prop) : (p \u2228 True) = True :=\n  propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inr trivial)\n@[simp 100] theorem ite_self {d : Decidable c} (a : \u03b1) : ite c a a = a := by\n  cases d <;> rfl\n```\n-/\nsyntax (name := simp) \"simp\" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr\nend Attr\n\nend Parser\nend Lean\n\n/--\n`\u2039t\u203a` resolves to an (arbitrary) hypothesis of type `t`.\nIt is useful for referring to hypotheses without accessible names.\n`t` may contain holes that are solved by unification with the expected type;\nin particular, `\u2039_\u203a` is a shortcut for `by assumption`.\n-/\nsyntax \"\u2039\" withoutPosition(term) \"\u203a\" : term\nmacro_rules | `(\u2039$type\u203a) => `((by assumption : $type))\n\n/--\n`get_elem_tactic_trivial` is an extensible tactic automatically called\nby the notation `arr[i]` to prove any side conditions that arise when\nconstructing the term (e.g. the index is in bounds of the array).\nThe default behavior is to just try `trivial` (which handles the case\nwhere `i < arr.size` is in the context) and `simp_arith`\n(for doing linear arithmetic in the index).\n-/\nsyntax \"get_elem_tactic_trivial\" : tactic\n\nmacro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| trivial)\nmacro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| simp (config := { arith := true }); done)\n\n/--\n`get_elem_tactic` is the tactic automatically called by the notation `arr[i]`\nto prove any side conditions that arise when constructing the term\n(e.g. the index is in bounds of the array). It just delegates to\n`get_elem_tactic_trivial` and gives a diagnostic error message otherwise;\nusers are encouraged to extend `get_elem_tactic_trivial` instead of this tactic.\n-/\nmacro \"get_elem_tactic\" : tactic =>\n  `(tactic| first\n    | get_elem_tactic_trivial\n    | fail \"failed to prove index is valid, possible solutions:\n  - Use `have`-expressions to prove the index is valid\n  - Use `a[i]!` notation instead, runtime check is perfomed, and 'Panic' error message is produced if index is not valid\n  - Use `a[i]?` notation instead, result is an `Option` type\n  - Use `a[i]'h` notation instead, where `h` is a proof that index is valid\"\n   )\n\n@[inherit_doc getElem]\nsyntax:max term noWs \"[\" withoutPosition(term) \"]\" : term\nmacro_rules | `($x[$i]) => `(getElem $x $i (by get_elem_tactic))\n\n@[inherit_doc getElem]\nsyntax term noWs \"[\" withoutPosition(term) \"]'\" term:max : term\nmacro_rules | `($x[$i]'$h) => `(getElem $x $i $h)\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/Tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081161995, "lm_q2_score": 0.050330637048962415, "lm_q1q2_score": 0.01701563635882149}}
{"text": "import tools.super\nopen list\n\nprint prefix list.reverse_core\n\nprint tactic.interactive.generalize\n\nlemma reverse_reverse_core {\u03b1} (xs ys : list \u03b1) : reverse_core (reverse_core xs ys) nil = reverse_core ys xs :=\nbegin generalize ys ys, induction xs, intro, refl, super list.reverse_core.equations._eqn_2 end", "meta": {"author": "gebner", "repo": "POPL17_tutorial", "sha": "04aaaea171736317bf20bc849b96069188d73a55", "save_path": "github-repos/lean/gebner-POPL17_tutorial", "path": "github-repos/lean/gebner-POPL17_tutorial/POPL17_tutorial-04aaaea171736317bf20bc849b96069188d73a55/super/quickrev.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.04336579984571784, "lm_q1q2_score": 0.017014000449130217}}
{"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\u2081 v\u2082 u\u2081 u\u2082\n\nstructure idempotent (C : Sort u\u2081) [category.{v\u2081+1} C] :=\n(X : C)\n(idem : X \u27f6 X)\n(w' : idem \u226b idem = idem . obviously)\n\nrestate_axiom idempotent.w'\nattribute [simp] idempotent.w -- search\n\nvariables {C : Sort u\u2081} [\ud835\udc9e : category.{v\u2081+1} C]\ninclude \ud835\udc9e\n\nnamespace idempotent\n\nstructure morphism (P Q : idempotent.{v\u2081} C) :=\n(hom : P.X \u27f6 Q.X)\n(left' : P.idem \u226b hom = hom . obviously)\n(right' : hom \u226b 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\u2081+1} (idempotent C) :=\n{ hom  := idempotent.morphism,\n  id   := \u03bb P, \u27e8 P.idem \u27e9,\n  comp := \u03bb _ _ _ f g,\n  { hom := f.hom \u226b g.hom,\n    left'  := by rw [\u2190category.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) : ((\ud835\udfd9 P) : idempotent.morphism P P).hom = P.idem := rfl\n@[simp] lemma comp_hom {P Q R : idempotent C} (f : P \u27f6 Q) (g : Q \u27f6 R) : (f \u226b g).hom = f.hom \u226b g.hom := rfl\n\ndef to_completion (C : Type u\u2081) [\ud835\udc9e : category.{v\u2081+1} C] : C \u2964 (idempotent.{v\u2081} C) :=\n{ obj := \u03bb P, { X := P, idem := \ud835\udfd9 P },\n  map := \u03bb _ _ f, { hom := f } }\n\n@[simp] private lemma double_idempotent_morphism_left (P Q : idempotent (idempotent C)) (f : P \u27f6 Q)\n  : (P.idem).hom \u226b (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 \u27f6 Q)\n  : (f.hom).hom \u226b (Q.idem).hom = (f.hom).hom := congr_arg idempotent.morphism.hom f.right\n\n@[simp] private def idempotent_functor : (idempotent (idempotent C)) \u2964 (idempotent C) :=\n{ obj := \u03bb P, \u27e8 P.X.X, P.idem.hom, congr_arg idempotent.morphism.hom P.w \u27e9,\n  map := \u03bb _ _ f, \u27e8 f.hom.hom, by obviously \u27e9 }.\n@[simp] private def idempotent_inverse : (idempotent C) \u2964 (idempotent (idempotent C)) :=\n{ obj := \u03bb P, \u27e8 P, \u27e8 P.idem, by obviously \u27e9, by obviously \u27e9,\n  map := \u03bb _ _ f, \u27e8 f, by obviously \u27e9 }.\n\n@[simp] lemma idem_hom_idempotent (X : idempotent (idempotent C)) : X.idem.hom \u226b X.idem.hom = X.idem.hom :=\nbegin\n  rw \u2190comp_hom,\n  simp,\nend\n\nlemma idempotent_idempotent :\n  equivalence (idempotent (idempotent C)) (idempotent C) :=\nequivalence.mk idempotent_functor idempotent_inverse\n  { hom := { app := \u03bb X, { hom := { hom := X.idem.hom } } },\n    inv := { app := \u03bb X, { hom := { hom := X.idem.hom } } } }\n  { hom := { app := \u03bb X, { hom := X.idem } },\n    inv := { app := \u03bb X, { hom := X.idem } } }\n\nvariable {D : Type u\u2082}\nvariable [\ud835\udc9f : category.{v\u2082+1} D]\ninclude \ud835\udc9f\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 \u2964 (idempotent D)) : (idempotent C) \u2964 (idempotent D) :=\n{ obj := \u03bb P,\n  { X := (F.obj P.X).X,\n    idem := (F.map P.idem).hom,\n    w' := begin rw [\u2190comp_hom, \u2190functor.map_comp, idempotent.w], end },\n  map := \u03bb 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 \u2190 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 (\u2190 getLCtx) |> setBinderInfosD ys |> setBinderInfosD xs\n      withLCtx lctx (\u2190 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 \u2190 if xType == yType then mkEq xType yType else mkHEq xType yType\n        let congrType \u2190 mkForallFVars hs resultType\n        return {\n          type  := congrType\n          proof := (\u2190 mkProof congrType)\n          argKinds\n        }\nwhere\n  withNewEqs {\u03b1} (xs ys : Array Expr) (k : Array Expr \u2192 Array CongrArgKind \u2192 MetaM \u03b1) : MetaM \u03b1 :=\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 := (\u2190 inferType x).consumeAutoOptParam\n        let yType := (\u2190 inferType y).consumeAutoOptParam\n        if xType == yType then\n          withLocalDeclD ((`e).appendIndexAfter (i+1)) (\u2190 mkEq x y) fun h =>\n            loop (i+1) (eqs.push h) (kinds.push CongrArgKind.eq)\n        else\n          withLocalDeclD ((`e).appendIndexAfter (i+1)) (\u2190 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 \u2190 mkProof type\n      let mut major := eqPr\n      if (\u2190 whnf (\u2190 inferType eqPr)).isHEq then\n        major \u2190 mkEqOfHEq major\n      let motive \u2190 mkLambdaFVars #[b] motive\n      mkLambdaFVars #[a, b, eqPr] (\u2190 mkEqNDRec motive minor major)\n\ndef mkHCongr (f : Expr) : MetaM CongrTheorem := do\n  mkHCongrWithArity f (\u2190 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\u2096 m/m\u00b2 = 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 : \u00ac is_field R) (h' : (maximal_ideal R).is_principal) (I : ideal R) (hI : I \u2260 \u22a5) :\n    \u2203 n : \u2115, I = (maximal_ideal R) ^ n :=\nbegin\n  classical,\n  unfreezingI { obtain \u27e8x, hx : _ = ideal.span _\u27e9 := h' },\n  by_cases hI' : I = \u22a4, { use 0, rw [pow_zero, hI', ideal.one_eq_top] },\n  have H : \u2200 r : R, \u00ac (is_unit r) \u2194 x \u2223 r :=\n    \u03bb r, (set_like.ext_iff.mp hx r).trans ideal.mem_span_singleton,\n  have : x \u2260 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' : \u2200 r : R, r \u2260 0 \u2192 r \u2208 nonunits R \u2192 \u2203 (n : \u2115), associated (x ^ n) r,\n  { intros r hr\u2081 hr\u2082,\n    obtain \u27e8f, hf\u2081, rfl, hf\u2082\u27e9 := (wf_dvd_monoid.not_unit_iff_exists_factors_eq r hr\u2081).mp hr\u2082,\n    have : \u2200 b \u2208 f, associated x b,\n    { intros b hb,\n      exact irreducible.associated_of_dvd hx' (hf\u2081 b hb) ((H b).mp (hf\u2081 b hb).1) },\n    clear hr\u2081 hr\u2082 hf\u2081,\n    induction f using multiset.induction with fa fs fh,\n    { exact (hf\u2082 rfl).elim },\n    rcases eq_or_ne fs \u2205 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 \u27e8n, hn\u27e9 := fh hf' (\u03bb 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 : \u2203 n : \u2115, x ^ n \u2208 I,\n  { obtain \u27e8r, hr\u2081, hr\u2082\u27e9 : \u2203 r : R, r \u2208 I \u2227 r \u2260 0,\n    { by_contra h, push_neg at h, apply hI, rw eq_bot_iff, exact h },\n    obtain \u27e8n, u, rfl\u27e9 := H' r hr\u2082 (le_maximal_ideal hI' hr\u2081),\n    use n,\n    rwa [\u2190 I.unit_mul_mem_iff_mem u.is_unit, mul_comm] },\n  use nat.find this,\n  apply le_antisymm,\n  { change \u2200 s \u2208 I, s \u2208 _,\n    by_contra hI'',\n    push_neg at hI'',\n    obtain \u27e8s, hs\u2081, hs\u2082\u27e9 := hI'',\n    apply hs\u2082,\n    by_cases hs\u2083 : s = 0, { rw hs\u2083, exact zero_mem _ },\n    obtain \u27e8n, u, rfl\u27e9 := H' s hs\u2083 (le_maximal_ideal hI' hs\u2081),\n    rw [mul_comm, ideal.unit_mul_mem_iff_mem _ u.is_unit] at \u22a2 hs\u2081,\n    apply ideal.pow_le_pow (nat.find_min' this hs\u2081),\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 = \u22a5,\n  { rw ne_bot, apply_instance },\n  obtain \u27e8a, ha\u2081, ha\u2082\u27e9 : \u2203 a \u2208 maximal_ideal R, a \u2260 (0 : R),\n  { by_contra h', push_neg at h', apply ne_bot, rwa eq_bot_iff },\n  have hle : ideal.span {a} \u2264 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 \u27e8hle, infer_instance\u27e9 },\n    { refine le_Inf (\u03bb I hI, (eq_maximal_ideal $\n        is_dedekind_domain.dimension_le_one _ (\u03bb e, ha\u2082 _) hI.2).ge),\n      rw [\u2190 ideal.span_singleton_eq_bot, eq_bot_iff, \u2190 e], exact hI.1 } },\n  have : \u2203 n, maximal_ideal R ^ n \u2264 ideal.span {a},\n  { rw \u2190 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 \u27e8b, hb\u2081, hb\u2082\u27e9 : \u2203 b \u2208 maximal_ideal R ^ n, \u00ac b \u2208 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 (\u03bb x hx, not_not.mp (h' x hx)) },\n  have hb\u2083 : \u2200 m \u2208 maximal_ideal R, \u2203 k : R, k * a = b * m,\n  { intros m hm, rw \u2190 ideal.mem_span_singleton', apply nat.find_spec this,\n    rw [hn, pow_succ'], exact ideal.mul_mem_mul hb\u2081 hm },\n  have hb\u2084 : b \u2260 0,\n  { rintro rfl, apply hb\u2082, 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\u2083 : algebra_map R K a \u2260 0 := is_fraction_ring.to_map_eq_zero_iff.not.mpr ha\u2082,\n  by_cases hx : \u2200 y \u2208 M, x * y \u2208 M,\n  { have := is_integral_of_smul_mem_submodule M _ _ x hx,\n    { obtain \u27e8y, e\u27e9 := is_integrally_closed.algebra_map_eq_of_integral this,\n      refine (hb\u2082 (ideal.mem_span_singleton'.mpr \u27e8y, _\u27e9)).elim,\n      apply is_fraction_ring.injective R K,\n      rw [map_mul, e, div_mul_cancel _ ha\u2083] },\n    { rw submodule.ne_bot_iff, refine \u27e8_, \u27e8a, ha\u2081, rfl\u27e9, _\u27e9,\n      exact is_fraction_ring.to_map_eq_zero_iff.not.mpr ha\u2082 },\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 = \u22a4,\n    { by_contra h, apply hx,\n      rintros m' \u27e8m, hm, (rfl : algebra_map R K m = m')\u27e9,\n      obtain \u27e8k, hk\u27e9 := hb\u2083 m hm,\n      have hk' : x * algebra_map R K m = algebra_map R K k,\n      { rw [\u2190 mul_div_right_comm, \u2190 map_mul, \u2190 hk, map_mul, mul_div_cancel _ ha\u2083] },\n      exact \u27e8k, le_maximal_ideal h \u27e8_, \u27e8_, hm, rfl\u27e9, hk'\u27e9, hk'.symm\u27e9 },\n    obtain \u27e8y, hy\u2081, hy\u2082\u27e9 : \u2203 y \u2208 maximal_ideal R, b * y = a,\n    { rw [ideal.eq_top_iff_one, submodule.mem_comap] at this,\n      obtain \u27e8_, \u27e8y, hy, rfl\u27e9, hy' : x * algebra_map R K y = algebra_map R K 1\u27e9 := this,\n      rw [map_one, \u2190 mul_div_right_comm, div_eq_one_iff_eq ha\u2083, \u2190 map_mul] at hy',\n      exact \u27e8y, hy, is_fraction_ring.injective R K hy'\u27e9 },\n    refine \u27e8\u27e8y, _\u27e9\u27e9,\n    apply le_antisymm,\n    { intros m hm, obtain \u27e8k, hk\u27e9 := hb\u2083 m hm, rw [\u2190 hy\u2082, mul_comm, mul_assoc] at hk,\n      rw [\u2190 mul_left_cancel\u2080 hb\u2084 hk, mul_comm], exact ideal.mem_span_singleton'.mpr \u27e8_, rfl\u27e9 },\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 : \u00ac is_field R) :\n  tfae [discrete_valuation_ring R,\n    valuation_ring R,\n    is_dedekind_domain R,\n    is_integrally_closed R \u2227 \u2203! P : ideal R, P \u2260 \u22a5 \u2227 P.is_prime,\n    (maximal_ideal R).is_principal,\n    finite_dimensional.finrank (residue_field R) (cotangent_space R) = 1,\n    \u2200 I \u2260 \u22a5, \u2203 n : \u2115, 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 \u2192 2,\n  { introI _, apply_instance },\n  tfae_have : 2 \u2192 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 \u27e8x, hx\u2081, hx\u2082\u27e9 := ring.exists_not_is_unit_of_not_is_field h,\n      obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := wf_dvd_monoid.exists_irreducible_factor hx\u2082 hx\u2081,\n      exact \u27e8p, hp\u2081\u27e9 },\n    { exact valuation_ring.unique_irreducible } },\n  tfae_have : 1 \u2192 4,\n  { introI H,\n    exact \u27e8infer_instance, ((discrete_valuation_ring.iff_pid_with_one_nonzero_prime R).mp H).2\u27e9 },\n  tfae_have : 4 \u2192 3,\n  { rintros \u27e8h\u2081, h\u2082\u27e9, exact \u27e8infer_instance, \u03bb I hI hI', unique_of_exists_unique h\u2082\n      \u27e8ne_bot, infer_instance\u27e9 \u27e8hI, hI'\u27e9 \u25b8 maximal_ideal.is_maximal R, h\u2081\u27e9 },\n  tfae_have : 3 \u2192 5,\n  { introI h, exact maximal_ideal_is_principal_of_is_dedekind_domain R },\n  tfae_have : 5 \u2192 6,\n  { rintro \u27e8x, hx\u27e9,\n    have : x \u2208 maximal_ideal R := by { rw hx, exact submodule.subset_span (set.mem_singleton x) },\n    let x' : maximal_ideal R := \u27e8x, this\u27e9,\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 \u27e8{x}, (finset.coe_singleton x).symm \u25b8 hx.symm\u27e9 },\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 (\u22a5 : ideal R) bot_ne_top, exact le_refl _ } },\n    { refine \u03bb w, quotient.induction_on' w $ \u03bb y, _,\n      obtain \u27e8y, hy\u27e9 := y,\n      rw [hx, submodule.mem_span_singleton] at hy,\n      obtain \u27e8a, rfl\u27e9 := hy,\n      exact \u27e8ideal.quotient.mk _ a, rfl\u27e9 } },\n  tfae_have : 6 \u2192 5,\n  { rintro \u27e8x, hx, hx'\u27e9,\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\u2081 : (ideal.span {x} : ideal R) \u2294 maximal_ideal R \u2264\n      ideal.span {x} \u2294 (maximal_ideal R) \u2022 (maximal_ideal R),\n    { refine sup_le le_sup_left _,\n      rintros m hm,\n      obtain \u27e8c, hc\u27e9 := hx' (submodule.quotient.mk \u27e8m, hm\u27e9),\n      induction c using quotient.induction_on',\n      rw \u2190 sub_sub_cancel (c * x) m,\n      apply sub_mem _ _,\n      { apply_instance },\n      { refine ideal.mem_sup_left (ideal.mem_span_singleton'.mpr \u27e8c, rfl\u27e9) },\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\u2082 : maximal_ideal R \u2264 (\u22a5 : 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\u2082 h\u2081,\n    rw [submodule.bot_smul, sup_bot_eq] at this,\n    rw [\u2190 sup_eq_left, eq_comm],\n    exact le_sup_left.antisymm (h\u2081.trans $ le_of_eq this) },\n  tfae_have : 5 \u2192 7,\n  { exact exists_maximal_ideal_pow_eq_of_principal R h },\n  tfae_have : 7 \u2192 2,\n  { rw valuation_ring.iff_ideal_total,\n    intro H,\n    constructor,\n    intros I J,\n    by_cases hI : I = \u22a5, { subst hI,  left, exact bot_le },\n    by_cases hJ : J = \u22a5, { subst hJ, right, exact bot_le },\n    obtain \u27e8n, rfl\u27e9 := H I hI,\n    obtain \u27e8m, rfl\u27e9 := 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": "import tactic.lint\nimport algebra.ring.basic\n\ndef foo1 (n m : \u2115) : \u2115 := n + 1\ndef foo2 (n m : \u2115) : m = m := by refl\nlemma foo3 (n m : \u2115) : \u2115 := n - m\nlemma foo.foo (n m : \u2115) : n \u2265 n := le_refl n\ninstance bar.bar : has_add \u2115 := by apply_instance  -- we don't check the name of instances\nlemma foo.bar (\u03b5 > 0) : \u03b5 = \u03b5 := rfl -- >/\u2265 is allowed in binders (and in fact, in all hypotheses)\n-- section\n-- local attribute [instance, priority 1001] classical.prop_decidable\n-- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)\n-- end\n\nopen tactic\n\nmeta def fold_over_with_cond {\u03b1} (l : list declaration) (tac : declaration \u2192 tactic (option \u03b1)) :\n  tactic (list (declaration \u00d7 \u03b1)) :=\nl.mmap_filter $ \u03bb d, option.map (\u03bb x, (d, x)) <$> tac d\n\nrun_cmd do\n  let t := name \u00d7 list \u2115,\n  e \u2190 get_env,\n  let l := e.filter (\u03bb d, e.in_current_file d.to_name \u2227 \u00ac d.is_auto_or_internal e),\n  l2 \u2190 fold_over_with_cond l (return \u2218 check_unused_arguments),\n  guard $ l2.length = 4,\n  let l2 : list t := l2.map $ \u03bb x, \u27e8x.1.to_name, x.2\u27e9,\n  guard $ (\u27e8`foo1, [2]\u27e9 : t) \u2208 l2,\n  guard $ (\u27e8`foo2, [1]\u27e9 : t) \u2208 l2,\n  guard $ (\u27e8`foo.foo, [2]\u27e9 : t) \u2208 l2,\n  guard $ (\u27e8`foo.bar, [2]\u27e9 : t) \u2208 l2,\n  l2 \u2190 fold_over_with_cond l linter.def_lemma.test,\n  guard $ l2.length = 2,\n  let l2 : list (name \u00d7 _) := l2.map $ \u03bb x, \u27e8x.1.to_name, x.2\u27e9,\n  guard $ \u2203(x \u2208 l2), (x : name \u00d7 _).1 = `foo2,\n  guard $ \u2203(x \u2208 l2), (x : name \u00d7 _).1 = `foo3,\n  l3 \u2190 fold_over_with_cond l linter.dup_namespace.test,\n  guard $ l3.length = 1,\n  guard $ \u2203(x \u2208 l3), (x : declaration \u00d7 _).1.to_name = `foo.foo,\n  l4 \u2190 fold_over_with_cond l linter.ge_or_gt.test,\n  guard $ l4.length = 1,\n  guard $ \u2203(x \u2208 l4), (x : declaration \u00d7 _).1.to_name = `foo.foo,\n  -- guard $ \u2203(x \u2208 l4), (x : declaration \u00d7 _).1.to_name = `foo4,\n  (_, s) \u2190 lint ff,\n  guard $ \"/- (slow tests skipped) -/\\n\".is_suffix_of s.to_string,\n  (_, s2) \u2190 lint tt,\n  guard $ s.to_string \u2260 s2.to_string,\n  skip\n\n/- check customizability and nolint -/\n\nmeta def dummy_check (d : declaration) : tactic (option string) :=\nreturn $ if d.to_name.last = \"foo\" then some \"gotcha!\" else none\n\nmeta def linter.dummy_linter : linter :=\n{ test := dummy_check,\n  auto_decls := ff,\n  no_errors_found := \"found nothing\",\n  errors_found := \"found something\" }\n\n@[nolint dummy_linter]\ndef bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)\n\nrun_cmd do\n  (_, s) \u2190 lint tt lint_verbosity.medium [`linter.dummy_linter] tt,\n  guard $ \"/- found something: -/\\n#print foo.foo /- gotcha! -/\\n\".is_suffix_of s.to_string\n\ndef incorrect_type_class_argument_test {\u03b1 : Type} (x : \u03b1) [x = x] [decidable_eq \u03b1] [group \u03b1] :\n  unit := ()\n\nrun_cmd do\n  d \u2190 get_decl `incorrect_type_class_argument_test,\n  x \u2190 linter.incorrect_type_class_argument.test d,\n  guard $ x = some \"These are not classes. argument 3: [_inst_1 : x = x]\"\n\nsection\ndef impossible_instance_test {\u03b1 \u03b2 : Type} [add_group \u03b1] : has_add \u03b1 := infer_instance\nlocal attribute [instance] impossible_instance_test\nrun_cmd do\n  d \u2190 get_decl `impossible_instance_test,\n  x \u2190 linter.impossible_instance.test d,\n  guard $ x = some \"Impossible to infer argument 2: {\u03b2 : Type}\"\n\ndef dangerous_instance_test {\u03b1 \u03b2 \u03b3 : Type} [ring \u03b1] [add_comm_group \u03b2] [has_coe \u03b1 \u03b2]\n  [has_inv \u03b3] : has_add \u03b2 := infer_instance\nlocal attribute [instance] dangerous_instance_test\nrun_cmd do\n  d \u2190 get_decl `dangerous_instance_test,\n  x \u2190 linter.dangerous_instance.test d,\n  guard $ x = some\n    \"The following arguments become metavariables. argument 1: {\u03b1 : Type}, argument 3: {\u03b3 : Type}\"\nend\n\nsection\ndef foo_has_mul {\u03b1} [has_mul \u03b1] : has_mul \u03b1 := infer_instance\nlocal attribute [instance, priority 1] foo_has_mul\nrun_cmd do\n  d \u2190 get_decl `has_mul,\n  some s \u2190 fails_quickly 20 d,\n  guard $ s = \"type-class inference timed out\"\nlocal attribute [instance, priority 10000] foo_has_mul\nrun_cmd do\n  d \u2190 get_decl `has_mul,\n  some s \u2190 fails_quickly 3000 d,\n  guard $ \"maximum class-instance resolution depth has been reached\".is_prefix_of s\nend\n\ninstance beta_redex_test {\u03b1} [monoid \u03b1] : (\u03bb (X : Type), has_mul X) \u03b1 := \u27e8(*)\u27e9\nrun_cmd do\n  d \u2190 get_decl `beta_redex_test,\n  x \u2190 linter.instance_priority.test d,\n  guard $ x = some \"set priority below 1000\"\n\n/- test of `apply_to_fresh_variables` -/\nrun_cmd do\n  e \u2190 mk_const `id,\n  e2 \u2190 apply_to_fresh_variables e,\n  type_check e2,\n  `(@id %%\u03b1 %%a) \u2190 instantiate_mvars e2,\n  expr.sort (level.succ $ level.mvar u) \u2190 infer_type \u03b1,\n  skip\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/test/lint.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353746, "lm_q2_score": 0.0420877295677101, "lm_q1q2_score": 0.016985212602506062}}
{"text": "import ..utils.util\nimport all\n\nsection main\nopen tactic\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  -- let dest : string := ((args.nth 0).get_or_else \"./data/mathlib_decls.log\"),\n  dest \u2190 args.nth_except 0 \"dest\",\n  let ignore_decls_fn : environment \u2192 declaration \u2192 bool :=\n    (\u03bb e d, declaration.is_auto_or_internal e d || bnot (declaration.is_theorem d) || d.to_name.is_aux),\n  f \u2190 io.mk_file_handle dest io.mode.append,\n\n  let mk_decl_msg (d : declaration) : tactic string := do {\n    decl_type \u2190 do {\n      (format.to_string \u2218 format.flatten) <$> tactic.pp d.type\n    },\n    let msg : json := json.object $ [\n      (\"decl_name\", d.to_name.to_string),\n      (\"decl_type\", (decl_type : string))\n    ],\n    pure $ json.unparse msg\n  },\n\n  io.run_tactic' $ do {\n    env \u2190 get_env,\n    decls \u2190 list.filter (\u03bb d, !(ignore_decls_fn env d)) <$> lint_mathlib_decls,\n    for_ decls $ \u03bb decl, do {\n      msg \u2190 mk_decl_msg decl,\n      tactic.unsafe_run_io $ io.fs.put_str_ln f msg,\n      tactic.trace format!\"DECL: {decl.to_name}\"\n    }\n  }\n}\n\nend main\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/tools/all_decls_jsonline.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.044018649235890495, "lm_q1q2_score": 0.01694331267467267}}
{"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 \u2190 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 \u2190 mkEq lhs rhs\n      let mut eqs := #[]\n      for arg1 in args1, arg2 in args2 do\n        let arg1Type \u2190 inferType arg1\n        if !(\u2190 isProp arg1Type) && arg1 != arg2 then\n          eqs := eqs.push (\u2190 mkEqHEq arg1 arg2)\n      if let some andEqs := mkAnd? eqs then\n        let result \u2190 if useEq then\n          mkEq eq andEqs\n        else\n          mkArrow eq andEqs\n        mkForallFVars params (\u2190 mkForallFVars args1 (\u2190 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 (\u2190 whnf type) with\n        | Expr.forallE n d b _ =>\n          let arg1 := args1.get \u27e8i, h\u27e9\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 {\u03b1} (ctorName : Name) (mvarId : MVarId) : MetaM \u03b1 :=\n  throwError \"{injTheoremFailureHeader ctorName}{indentD <| MessageData.ofGoal mvarId}\"\n\nprivate def solveEqOfCtorEq (ctorName : Name) (mvarId : MVarId) (h : FVarId) : MetaM Unit := do\n  match (\u2190 injection mvarId h) with\n  | InjectionResult.solved => unreachable!\n  | InjectionResult.subgoal mvarId .. =>\n    (\u2190  mvarId.splitAnd).forM fun mvarId =>\n      unless (\u2190 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 \u2190 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 \u2190 mkInjectiveTheoremType? ctorVal\n    | return ()\n  let value \u2190 mkInjectiveTheoremValue ctorVal.name type\n  let name := mkInjectiveTheoremNameFor ctorVal.name\n  addDecl <| Declaration.thmDecl {\n    name\n    levelParams := ctorVal.levelParams\n    type        := (\u2190 instantiateMVars type)\n    value       := (\u2190 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 \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let [mvarId\u2081, mvarId\u2082] \u2190 mvar.mvarId!.apply (mkConst ``Eq.propIntro)\n      | throwError \"unexpected number of subgoals when proving injective theorem for constructor '{ctorName}'\"\n    let (h, mvarId\u2081) \u2190 mvarId\u2081.intro1\n    let (_, mvarId\u2082) \u2190 mvarId\u2082.intro1\n    solveEqOfCtorEq ctorName mvarId\u2081 h\n    let mvarId\u2082 \u2190 mvarId\u2082.casesAnd\n    if let some mvarId\u2082 \u2190 mvarId\u2082.substEqs then\n      try mvarId\u2082.refl catch _ => throwError (injTheoremFailureHeader ctorName)\n    mkLambdaFVars xs mvar\n\nprivate def mkInjectiveEqTheorem (ctorVal : ConstructorVal) : MetaM Unit := do\n  let some type \u2190 mkInjectiveEqTheoremType? ctorVal\n    | return ()\n  let value \u2190 mkInjectiveEqTheoremValue ctorVal.name type\n  let name := mkInjectiveEqTheoremNameFor ctorVal.name\n  addDecl <| Declaration.thmDecl {\n    name\n    levelParams := ctorVal.levelParams\n    type        := (\u2190 instantiateMVars type)\n    value       := (\u2190 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 (\u2190 getEnv).contains ``Eq.propIntro && genInjectivity.get (\u2190 getOptions) &&  !(\u2190 isInductivePredicate declName) then\n    let info \u2190 getConstInfoInduct declName\n    unless info.isUnsafe do\n      for ctor in info.ctors do\n        let ctorVal \u2190 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": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Daniel Selsam\n-/\nimport Lean.Expr\nimport Mathport.Util.Misc\nimport Mathport.Util.Json\nimport Mathport.Syntax.AST3\n\nnamespace Mathport\n\nopen Lean (Json FromJson Position Name BinderInfo HashMap)\nopen Lean.FromJson (fromJson?)\n\nnamespace Parse\n\n-- The following instance temporarily overrides the Lean4 instance\n-- It is a minor convenience to avoid needing to translate `RawName` -> `Name` throughout the file.\nlocal instance (priority := high) : FromJson Name where\n  fromJson?\n  | Json.null => pure Name.anonymous\n  | Json.str s => pure s\n  | Json.arr a => a.foldlM (init := Name.anonymous) fun\n    | n, (i : Nat) => pure $ n.mkNum i\n    | n, (s : String) => pure $ n.mkStr s\n    | _, _ => throw \"JSON string expected\"\n  | _ => throw \"JSON array expected\"\n\nabbrev AstId := Nat\nabbrev LevelId := Nat\nabbrev ExprId := Nat\nabbrev TacticStateId := Nat\nabbrev Tag := Option AstId\n\nstructure RawNode3 where\n  start    : Position\n  \u00abend\u00bb    : Option Position\n  kind     : String\n  value    : Name\n  children : Option (Array AstId)\n  pexpr    : Option ExprId\n  expr     : Option ExprId\n  deriving FromJson, Repr, Inhabited\n\ndef RawNode3.children' (n : RawNode3) : Array AstId := n.children.getD #[]\ndef RawNode3.end' (n : RawNode3) : Position := n.end.getD n.start\n\nsection\nopen AST3\nopen Lean3 (Proj)\n\nstructure State where\n  notations : Array Notation := #[]\n  cmds : Array Command := #[]\n  tactics : HashMap AstId (Spanned AST3.Tactic) := {}\n\nabbrev NotationKind := Option MixfixKind\n\nstructure Context where\n  ast : Array (Option RawNode3)\n  expr : Array Lean3.Expr\n  getNotationId : NotationKind \u2192 Subarray AstId \u2192 StateT State (Except String) NotationId\n  getInductiveId : Array AstId \u2192 StateT State (Except String) CommandId\n  getCommandId : AstId \u2192 StateT State (Except String) CommandId\n  deriving Inhabited\n\nabbrev M := ReaderT Context $ StateT State $ Except String\n\ndef getNotationId (nk : NotationKind) (args : Subarray AstId) : M NotationId :=\n  fun r => r.getNotationId nk args\n\ndef getInductiveId (args : Array AstId) : M NotationId :=\n  fun r => r.getInductiveId args\n\ndef getCommandId (i : AstId) : M NotationId :=\n  fun r => r.getCommandId i\n\ndef RawNode3.map (i : AstId) (n : RawNode3)\n  (f : String \u2192 Name \u2192 Array AstId \u2192 M \u03b1) : M (Spanned \u03b1) := do\n  pure \u27e8some \u27e8i, n.start, n.end'\u27e9, \u2190 f n.kind n.value n.children'\u27e9\n\ndef RawNode3.pexpr' (n : RawNode3) : M Lean3.Expr :=\n  match n.pexpr with\n  | none => default\n  | some e => return (\u2190 read).expr[e]!\n\ndef RawNode3.expr' (n : RawNode3) : M Lean3.Expr :=\n  match n.expr with\n  | none => default\n  | some e => return (\u2190 read).expr[e]!\n\ndef opt (f : AstId \u2192 M \u03b1) (i : AstId) : M (Option \u03b1) :=\n  if i = 0 then pure none else some <$> f i\n\ndef getRaw (i : AstId) : M RawNode3 := do\n  match (\u2190 read).ast[i]! with\n  | some a => pure a\n  | none => dbgStackTrace fun _ =>\n    throw $ if i = 0 then \"unexpected null node\" else \"missing node\"\n\ndef withNodeK (f : String \u2192 Name \u2192 Array AstId \u2192 M \u03b1) (i : AstId) : M \u03b1 := do\n  let r \u2190 getRaw i\n  f r.kind r.value r.children'\n\ndef withNode (f : String \u2192 Name \u2192 Array AstId \u2192 M \u03b1) (i : AstId) : M (Spanned \u03b1) := do\n  let r \u2190 getRaw i\n  pure { meta := some \u27e8i, r.start, r.end'\u27e9, kind := \u2190 f r.kind r.value r.children' }\n\ndef withNodeP (f : String \u2192 Name \u2192 Array AstId \u2192 Option ExprId \u2192 M \u03b1) (i : AstId) : M (Spanned \u03b1) := do\n  let r \u2190 getRaw i\n  pure { meta := some \u27e8i, r.start, r.end'\u27e9, kind := \u2190 f r.kind r.value r.children' r.pexpr }\n\ndef withNodeR (f : RawNode3 \u2192 M \u03b1) (i : AstId) : M (Spanned \u03b1) := do\n  let r \u2190 getRaw i\n  pure { meta := some \u27e8i, r.start, r.end'\u27e9, kind := \u2190 f r }\n\ndef getRaw? : AstId \u2192 M (Option RawNode3) := opt getRaw\n\ninductive NodeK : Type\n  | mk (kind : String) (value : Name) (children : Array (Option (Spanned NodeK))) : NodeK\n  deriving Inhabited\n\ndef Node := Spanned NodeK\ninstance : Inhabited Node := inferInstanceAs (Inhabited (Spanned NodeK))\n\nopen Std (Format) in\nmutual\n\n  partial def optNode_repr : Option Node \u2192 Format\n    | none => (\"\u2b1d\" : Format)\n    | some a => NodeK_repr a.kind\n\n  partial def NodeK_repr : NodeK \u2192 Format\n    | \u27e8k, v, c\u27e9 =>\n      let s := (Lean.Name.escapePart k).getD k ++\n        if v.isAnonymous then \"\" else \"[\" ++ v.toString ++ \"]\"\n      if c.isEmpty then s else\n        \"(\" ++ s ++ Format.join (c.toList.map fun c => Format.line ++ optNode_repr c) ++ \")\"\n          |>.nest 2 |>.group\n\nend\n\ninstance : Repr NodeK := \u27e8fun n _ => NodeK_repr n\u27e9\ninstance : Repr Node := inferInstanceAs (Repr (Spanned NodeK))\n\nmutual\n\n  partial def getNode : AstId \u2192 M Node := withNode mkNodeK\n\n  partial def mkNodeK (k : String) (v : Name) (c : Array AstId) : M NodeK := NodeK.mk k v <$> c.mapM (opt getNode)\n\nend\n\ndef decodeNat! (v : Name) : Nat :=\n  (Lean.Syntax.decodeNatLitVal? v.getString!).get!\n\ndef decodeDecimal! (v : Name) : Nat \u00d7 Nat :=\n  match String.split v.getString! (\u00b7 = '/') with\n  | [n, d] => ((Lean.Syntax.decodeNatLitVal? n).get!, (Lean.Syntax.decodeNatLitVal? d).get!)\n  | _ => panic! \"decodeDecimal! failed\"\n\ndef getNat : AstId \u2192 M (Spanned Nat) := withNode fun _ v _ => pure $ decodeNat! v\n\ndef getNameK : AstId \u2192 M Name := withNodeK fun _ v _ => pure v\ndef getName : AstId \u2192 M (Spanned Name) := withNode fun _ v _ => pure v\n\ndef getStrK : AstId \u2192 M String := withNodeK fun _ v _ => pure v.getString!\ndef getStr : AstId \u2192 M (Spanned String) := withNode fun _ v _ => pure v.getString!\n\ndef getSym : AstId \u2192 M (Spanned Symbol) :=\n  withNode fun\n  | \"quoted\", v, _ => pure $ Symbol.quoted v.getString!\n  | \"ident\", v, _ => pure $ Symbol.ident v.getString!\n  | k, _, _ => throw s!\"getSym parse error, unknown kind {k}\"\n\ndef getBinderName : AstId \u2192 M (Spanned BinderName) :=\n  withNode fun\n  | \"_\", _, _ => pure BinderName.\u00ab_\u00bb\n  | \"ident\", v, _ => pure $ BinderName.ident v\n  | k, _, _ => throw s!\"getBinderName parse error, unknown kind {k}\"\n\ndef getChoice : AstId \u2192 M Choice :=\n  withNodeK fun\n  | \"choice\", _, args => Choice.many <$> args.mapM getNameK\n  | \"notation\", v, _ => pure $ Choice.one v\n  | k, _, _ => throw s!\"getChoice parse error, unknown kind {k}\"\n\ndef getProj : AstId \u2192 M (Spanned Proj) :=\n  withNode fun\n  | \"nat\", v, _ => pure $ Proj.nat (decodeNat! v)\n  | \"ident\", v, _ => pure $ Proj.ident v\n  | k, _, _ => throw s!\"getSym parse error, unknown kind {k}\"\n\ndef getOptionVal : AstId \u2192 M (Spanned OptionVal) :=\n  withNode fun\n  | \"nat\", v, _ => pure $ OptionVal.nat (decodeNat! v)\n  | \"ident\", v, _ => pure $ OptionVal.str v.getString!\n  | \"bool\", v, _ => pure $ OptionVal.bool (v == `true)\n  | \"decimal\", v, _ => let (n, d) := decodeDecimal! v; pure $ OptionVal.decimal n d\n  | k, _, _ => throw s!\"getOptionVal parse error, unknown kind {k}\"\n\ndef getInferKind : AstId \u2192 M InferKind :=\n  withNodeK fun\n  | \"{}\", _, _ => pure InferKind.relaxedImplicit\n  | \"()\", _, _ => pure InferKind.none\n  | \"[]\", _, _ => pure InferKind.implicit\n  | k, _, _ => throw s!\"getInferKind parse error, unknown kind {k}\"\n\ndef arr (f : AstId \u2192 M \u03b1) (i : AstId) : M (Array \u03b1) := do\n  match \u2190 getRaw? i with\n  | some n => n.children'.mapM f\n  | none => pure #[]\n\ndef ctx (s : String) (m : M \u03b1) : M \u03b1 := do\n  try m catch e => throw $ \"at \" ++ s ++ \": \" ++ e\n\n\ndef toNotationKind : String \u2192 Option NotationKind\n| \"infix\" => some (some MixfixKind.infix)\n| \"infixl\" => some (some MixfixKind.infixl)\n| \"infixr\" => some (some MixfixKind.infixr)\n| \"postfix\" => some (some MixfixKind.postfix)\n| \"prefix\" => some (some MixfixKind.prefix)\n| \"notation\" => some none\n| _ => none\n\nopen Level in\npartial def getLevel : AstId \u2192 M (Spanned Level) :=\n  withNode fun\n  | \"_\", _, _ => pure \u00ab_\u00bb\n  | \"param\", v, _ => pure $ \u00abparam\u00bb v\n  | \"max\", _, args => Level.\u00abmax\u00bb <$> args.mapM getLevel\n  | \"imax\", _, args => Level.\u00abimax\u00bb <$> args.mapM getLevel\n  | \"nat\", v, _ => pure $ Level.nat $ decodeNat! v\n  | \"+\", _, #[a, b] => return Level.add (\u2190 getLevel a) (\u2190 getNat b)\n  | \"(\", _, #[e] => Level.paren <$> getLevel e\n  | k, _, _ => throw s!\"getLevel parse error, unknown kind {k}\"\n\ndef getLevels : AstId \u2192 M Levels := opt (arr getLevel)\ndef getLevelDecl : AstId \u2192 M LevelDecl := opt (arr getName)\n\ndef wrapperNotations : Lean.NameHashSet :=\n  List.foldl (\u00b7.insert \u00b7) {} [\n    `by, `have, `assume, `show, `suffices, `if, `\u00ab(\u00bb, `\u00ab\u27e8\u00bb, `\u00ab{\u00bb, `\u00ab{!\u00bb, `\u00ab.(\u00bb, `\u00ab._\u00bb,\n    `\u00ab```(\u00bb, `\u00ab``(\u00bb, `\u00ab`(\u00bb, `\u00ab`[\u00bb, `\u00ab`\u00bb, `\u00ab%%\u00bb, `\u00ab#[\u00bb, `\u00ab(:\u00bb, `\u00ab()\u00bb, `\u00ab(::)\u00bb, `fun, `Type,\n    `\u00abType*\u00bb, `Sort, `\u00abSort*\u00bb, `let, `calc, `\u00ab@\u00bb, `\u00ab@@\u00bb, `begin, `sorry, `match, `do]\n\nmutual\n\n  partial def getDefaultOrCollection :\n    AstId \u2192 M (Sum Default (Name \u00d7 Spanned Expr)) := withNodeK fun\n    | \":=\", _, #[e] => return Sum.inl $ Default.\u00ab:=\u00bb $ \u2190 getExpr e\n    | \".\", _, #[e] => return Sum.inl $ Default.\u00ab.\u00bb $ \u2190 getName e\n    | \"collection\", v, #[rhs] => return Sum.inr (v, \u2190 getExpr rhs)\n    | k, _, _ => throw s!\"getDefault parse error, unknown kind {k}\"\n\n  partial def getDefault (n : AstId) : M (Option Default) := do\n    match \u2190 opt getDefaultOrCollection n with\n    | none => pure none\n    | some (Sum.inl dflt) => pure $ some dflt\n    | _ => throw s!\"getDefault parse error\"\n\n  partial def getBinder : AstId \u2192 M (Spanned Binder) := withNode getBinder_aux\n\n  partial def getBinder_aux\n    | \"binder_0\", _, args => binder BinderInfo.default args\n    | \"binder_1\", _, args => binder BinderInfo.instImplicit args\n    | \"binder_2\", _, args => binder BinderInfo.strictImplicit args\n    | \"binder_4\", _, args => binder BinderInfo.implicit args\n    | \"binder_8\", _, args => binder BinderInfo.default args -- aux decl binders not supported\n    | k, _, args => match toNotationKind k with\n      | some nk => Binder.notation <$> getNotationId nk args\n      | none => throw s!\"getBinder parse error, unknown kind {k}\"\n  where\n    binder (bi : BinderInfo) (args : Array AstId) : M Binder := do\n      match \u2190 opt (arr getBinderName) args[0]!, \u2190 getBinders args[1]!, \u2190 opt getExpr args[2]!,\n        \u2190 opt getDefaultOrCollection (args.getD 3 0) with\n      | vars, bis, ty, none => pure $ Binder.binder bi vars bis ty none\n      | vars, bis, ty, some (Sum.inl dflt) => pure $ Binder.binder bi vars bis ty dflt\n      | some vars, #[], none, some (Sum.inr (c, rhs)) => pure $ Binder.collection bi vars c rhs\n      | _, _, _, _ => throw s!\"getBinder parse error\"\n  partial def getBinders : AstId \u2192 M Binders := arr getBinder\n\n  partial def getLambdaBinder : AstId \u2192 M (Spanned LambdaBinder) := withNode fun\n    | \"\u27e8\", _, args => LambdaBinder.\u00ab\u27e8\u27e9\u00bb <$> args.mapM getExpr\n    | k, v, args => LambdaBinder.reg <$> getBinder_aux k v args\n\n  partial def getLetDecl : AstId \u2192 M (Spanned LetDecl) := withNode fun\n    | \"var\", _, #[x, bis, ty, e] => return (LetDecl.var (\u2190 getBinderName x)\n      (\u2190 getBinders bis) (\u2190 opt getExpr ty) (\u2190 getExpr e))\n    | \"pat\", _, #[pat, e] => return LetDecl.pat (\u2190 getExpr pat) (\u2190 getExpr e)\n    | k, _, args => match toNotationKind k with\n      | some nk => LetDecl.notation <$> getNotationId nk args\n      | none => throw s!\"getBinder parse error, unknown kind {k}\"\n\n  partial def getArg : AstId \u2192 M (Spanned Arg) :=\n    withNodeP fun\n    | \"exprs\", _, args, _ => Arg.exprs <$> args.mapM getExpr\n    | \"binders\", _, args, _ => Arg.binders <$> args.mapM getBinder\n    | k, v, args, pexpr => if k.startsWith \"binder\"\n      then Arg.binder <$> getBinder_aux k v args\n      else Arg.expr <$> getExpr_aux k v args pexpr\n\n  partial def getExpr_aux : String \u2192 Name \u2192 Array AstId \u2192 Option ExprId \u2192 M Expr\n    | \"notation\", v, args, _ => match v with\n      | `\u00ab->\u00bb => return Expr.\u00ab\u2192\u00bb (\u2190 getExpr args[0]!) (\u2190 getExpr args[1]!)\n      | `Pi => return Expr.\u00abPi\u00bb (\u2190 getBinders args[0]!) (\u2190 getExpr args[1]!)\n      | `\u00ab^.\u00bb => Spanned.kind <$> getExpr args[1]!\n      | _ => if wrapperNotations.contains v\n        then Spanned.kind <$> getExpr args[0]!\n        else Expr.notation (Choice.one v) <$> args.mapM getArg\n    | \"sorry\", _, _, _ => pure Expr.\u00absorry\u00bb\n    | \"_\", _, _, _ => pure Expr.\u00ab_\u00bb\n    | \"()\", _, _, _ => pure Expr.\u00ab()\u00bb\n    | \"{}\", _, _, _ => pure Expr.\u00ab{}\u00bb\n    | \"ident\", v, _, _ => pure $ Expr.ident v\n    | \"const\", _, #[n, us], none => return Expr.const (\u2190 getName n) (\u2190 opt (arr getLevel) us) #[]\n    | \"const\", _, #[n, us], some pexprId => do\n      match (\u2190 read).expr[pexprId]! with\n      | Lean3.Expr.const resolved _ =>\n        return Expr.const (\u2190 getName n) (\u2190 opt (arr getLevel) us) #[resolved]\n      | pexpr => throw s!\"[const.pexpr] not a const: {repr pexpr}\"\n    | \"choice_const\", _, #[n, us], none => do\n        dbg_trace \"[getExpr_aux.warn] choice_const {(\u2190 getName n).kind} has no choices\"\n        pure $ Expr.const (\u2190 getName n) (\u2190 opt (arr getLevel) us) #[]\n    | \"choice_const\", _, #[n, us], some pexprId => do\n      match (\u2190 read).expr[pexprId]! with\n      | Lean3.Expr.choice args =>\n        let choices \u2190 args.mapM fun\n        | Lean3.Expr.const n _ => pure n\n        | choice => do throw s!\"[getExpr_aux.error] choice_const {\n          (\u2190 getName n).kind} expecting constants, found {repr choice}\"\n        return Expr.const (\u2190 getName n) (\u2190 opt (arr getLevel) us) choices\n      | _ => throw s!\"choice_const: expecting choice\"\n    | \"nat\", v, _, _ => pure $ Expr.nat $ decodeNat! v\n    | \"decimal\", v, _, _ => let (n, d) := decodeDecimal! v; pure $ Expr.decimal n d\n    | \"string\", v, _, _ => pure $ Expr.string v.getString!\n    | \"char\", v, _, _ => pure $ Expr.char v.getString!.front\n    | \"(\", _, #[e], _ => Expr.paren <$> getExpr e\n    | \"Sort*\", _, _, _ => pure $ Expr.sort false true none\n    | \"Type*\", _, _, _ => pure $ Expr.sort true true none\n    | \"Sort\", _, #[l], _ => Expr.sort false false <$> opt getLevel l\n    | \"Type\", _, #[l], _ => Expr.sort true false <$> opt getLevel l\n    | \"app\", _, #[f, x], _ => return Expr.app (\u2190 getExpr f) (\u2190 getExpr x)\n    | \"fun\", _, #[bis, e], _ => return Expr.fun false (\u2190 arr getLambdaBinder bis) (\u2190 getExpr e)\n    | \"assume\", _, #[bis, e], _ => return Expr.fun true (\u2190 arr getLambdaBinder bis) (\u2190 getExpr e)\n    | \"show\", _, #[ty, e], _ => return Expr.show (\u2190 getExpr ty) (\u2190 getProof e)\n    | \"have\", _, args, _ => getHave false args\n    | \"suffices\", _, args, _ => getHave true args\n    | \"field\", _, #[e, pr], _ => return Expr.\u00ab.\u00bb true (\u2190 getExpr e) (\u2190 getProj pr)\n    | \"^.\", _, #[e, pr], _ => return Expr.\u00ab.\u00bb false (\u2190 getExpr e) (\u2190 getProj pr)\n    | \"if\", _, #[h, c, t, e], _ =>\n      return Expr.if (\u2190 opt getName h) (\u2190 getExpr c) (\u2190 getExpr t) (\u2190 getExpr e)\n    | \"calc\", _, args, _ => Expr.calc <$> args.mapM getStep\n    | \"@\", _, #[e], _ => Expr.\u00ab@\u00bb false <$> getExpr e\n    | \"@@\", _, #[e], _ => Expr.\u00ab@\u00bb true <$> getExpr e\n    | \"(:\", _, #[e], _ => Expr.pattern <$> getExpr e\n    | \"```()\", _, #[e], _ => Expr.\u00ab`()\u00bb true false <$> getExpr e\n    | \"``()\", _, #[e], _ => Expr.\u00ab`()\u00bb false false <$> getExpr e\n    | \"`()\", _, #[e], _ => Expr.\u00ab`()\u00bb false true <$> getExpr e\n    | \"%%\", _, #[e], _ => Expr.\u00ab%%\u00bb <$> getExpr e\n    | \"`[\", _, args, _ => Expr.\u00ab`[]\u00bb <$> args.mapM getTactic\n    | \"`\", v, _, _ => pure $ Expr.\u00ab`\u00bb false v\n    | \"``\", v, _, _ => pure $ Expr.\u00ab`\u00bb true v\n    | \"\u27e8\", _, args, _ => Expr.\u00ab\u27e8\u27e9\u00bb <$> args.mapM getExpr\n    | \"infix_fn\", _, #[f, e], _ => return Expr.infix_fn (\u2190 getChoice f) (\u2190 opt getExpr e)\n    | \"tuple\", _, args, _ => Expr.\u00ab(,)\u00bb <$> args.mapM getExpr\n    | \":\", _, #[e, ty], _ => return Expr.\u00ab:\u00bb (\u2190 getExpr e) (\u2190 getExpr ty)\n    | \"{!\", _, args, _ => Expr.hole <$> args.mapM getExpr\n    | \"#[\", _, args, _ => Expr.\u00ab#[]\u00bb <$> args.mapM getExpr\n    | \"by\", _, #[tac], _ => Expr.by <$> getTactic tac\n    | \"begin\", _, args, _ => Expr.begin <$> getBlock false args\n    | \"let\", _, #[decls, e], _ => return Expr.let (\u2190 arr getLetDecl decls) (\u2190 getExpr e)\n    | \"match\", _, #[e, ty, arms], _ =>\n      return Expr.match (\u2190 arr getExpr e) (\u2190 opt getExpr ty) (\u2190 arr getArm arms)\n    | \"do\", v, args, _ => Expr.do (!v.isAnonymous) <$> args.mapM getDoElem\n    | \"fin_set\", _, args, _ => Expr.\u00ab{,}\u00bb <$> args.mapM getExpr\n    | \"subtype\", _, args, _ => getSubtype false args\n    | \"set_of\", _, args, _ => getSubtype true args\n    | \"sep\", _, #[x, S, p], _ => return Expr.sep (\u2190 getName x) (\u2190 getExpr S) (\u2190 getExpr p)\n    | \"set_replacement\", _, #[e, bis], _ => return Expr.setReplacement (\u2190 getExpr e) (\u2190 getBinders bis)\n    | \"structinst\", _, #[S, src, flds, srcs, catchall], _ =>\n      return Expr.structInst (\u2190 opt getName S) (\u2190 opt getExpr src)\n        (\u2190 arr getField flds) (\u2190 arr getExpr srcs) (catchall \u2260 0)\n    | \"at_pat\", _, #[n, pat], _ => return Expr.atPat (\u2190 getName n) (\u2190 getExpr pat)\n    | \".(\", _, #[e], _ => Expr.\u00ab.()\u00bb <$> getExpr e\n    | \"...\", _, _, _ => pure Expr.\u00ab...\u00bb\n    | \"choice\", _, args, _ =>\n      return Expr.notation (Choice.many (\u2190 arr getNameK args[0]!)) (\u2190 args[1:].toArray.mapM getArg)\n    | \"user_notation\", v, args, _ => Expr.userNotation v <$> args.mapM getParam\n    | k, _v, _args, _ => do\n      throw s!\"getExpr parse error, unknown kind {k}\" -- at\\n {repr (\u2190 Expr.other <$> mkNodeK k v args)}\"\n  where\n    getHave (suff : Bool) (args) : M _ :=\n      return Expr.have suff (\u2190 opt getName args[0]!)\n        (\u2190 getExpr args[1]!) (\u2190 getProof args[2]!) (\u2190 getExpr args[3]!)\n    getStep := withNodeK fun _ _ args => do pure (\u2190 getExpr args[0]!, \u2190 getExpr args[1]!)\n    getField := withNodeK fun _ _ args => do pure (\u2190 getName args[0]!, \u2190 getExpr args[1]!)\n    getSubtype (setOf : Bool) (args) : M _ :=\n      return Expr.subtype setOf (\u2190 getName args[0]!) (\u2190 opt getExpr args[1]!) (\u2190 getExpr args[2]!)\n\n  partial def getExpr : AstId \u2192 M (Spanned Expr) := withNodeP getExpr_aux\n\n  partial def getArm : AstId \u2192 M Arm := withNodeK fun _ _ args => do\n    pure \u27e8\u2190 arr getExpr args[0]!, \u2190 getExpr args[1]!\u27e9\n\n  partial def getDoElem : AstId \u2192 M (Spanned DoElem) :=\n    withNode fun\n    | \"let\", _, #[decl] => DoElem.let <$> getLetDecl decl\n    | \"<-\", _, #[pat, ty, rhs, els] =>\n      return DoElem.\u00ab\u2190\u00bb (\u2190 getExpr pat) (\u2190 opt getExpr ty) (\u2190 getExpr rhs) (\u2190 opt getExpr els)\n    | \"eval\", _, #[e] => DoElem.eval <$> getExpr e\n    | k, _, _ => throw s!\"getDoElem parse error, unknown kind {k}\"\n\n  partial def getProof : AstId \u2192 M (Spanned Proof) :=\n    withNode fun\n    | \":=\", _, #[e] => Proof.from true <$> getExpr e\n    | \"from\", _, #[e] => Proof.from false <$> getExpr e\n    | \"begin\", _, args => Proof.block <$> getBlock false args\n    | \"{\", _, args => Proof.block <$> getBlock true args\n    | \"by\", _, #[tac] => Proof.by <$> getTactic tac\n    | k, _, _ => throw s!\"getProof parse error, unknown kind {k}\"\n\n  partial def getTactic (i : AstId) : M (Spanned Tactic) := do\n    let getTactic' := withNode fun\n    | \";\", _, args => Tactic.\u00ab;\u00bb <$> args.mapM getTactic\n    | \"<|>\", _, args => Tactic.\u00ab<|>\u00bb <$> args.mapM getTactic\n    | \"[\", _, args => Tactic.\u00ab[]\u00bb <$> args.mapM getTactic\n    | \"begin\", _, args => Tactic.block <$> getBlock false args\n    | \"{\", _, args => Tactic.block <$> getBlock true args\n    | \"by\", _, #[tac] => Tactic.by <$> getTactic tac\n    | \"exact_shortcut\", _, #[e] => Tactic.exact_shortcut <$> getExpr e\n    | \"(\", _, #[e] => Tactic.expr <$> getExpr e\n    | \"tactic\", v, args => Tactic.interactive v <$> args.mapM getParam\n    | k, _, _ => throw s!\"getTactic parse error, unknown kind {k}\"\n    let t \u2190 getTactic' i\n    modify fun s => { s with tactics := s.tactics.insert i t }\n    pure t\n\n  partial def getBlock (curly : Bool) (args : Array AstId) : M Block := do\n    pure \u27e8curly, \u2190 opt getName args[0]!, \u2190 opt getExpr args[1]!, \u2190 args[2:].toArray.mapM getTactic\u27e9\n\n  partial def getParam : AstId \u2192 M (Spanned Param) :=\n    withNodeR fun r => match r.kind with\n    | \"parse\" => return Param.parse (\u2190 r.pexpr') (\u2190 r.children'.mapM getVMCall)\n    | \"expr\" => Param.expr <$> getExpr r.children'[0]!\n    | \"begin\" => Param.block <$> getBlock false r.children'\n    | \"{\" => Param.block <$> getBlock true r.children'\n    | k => throw s!\"getParam parse error, unknown kind {k}\"\n\n  partial def getVMCall : AstId \u2192 M (Spanned VMCall) :=\n    withNode fun\n    | \"ident\", v, _ => pure $ VMCall.ident v\n    | \"nat\", v, _ => pure $ VMCall.nat $ decodeNat! v\n    | \"token\", v, _ => pure $ VMCall.token v.getString!\n    | \"pat\", _, #[e] => return VMCall.pat (\u2190 getExpr e).kind\n    | \"expr\", _, #[e] => return VMCall.expr (\u2190 getExpr e).kind\n    | \"binders\", _, args => VMCall.binders <$> args.mapM getBinder\n    | \"begin\", _, args => VMCall.block <$> getBlock false args\n    | \"{\", _, args => VMCall.block <$> getBlock true args\n    | \"inductive\", _, args => VMCall.inductive <$> getInductiveId args\n    | \"command\", _, args => VMCall.command <$> opt getCommandId (args.getD 0 0)\n    | \"with_input\", v, args => return VMCall.withInput (\u2190 args.mapM getVMCall) (decodeNat! v)\n    | k, _, _ => throw s!\"getVMCall parse error, unknown kind {k}\"\n\nend\n\npartial def getPrec : AstId \u2192 M (Spanned Precedence) :=\n  withNode fun\n  | \"nat\", v, _ => pure $ Precedence.nat $ decodeNat! v\n  | \"expr\", _, #[e] => Precedence.expr <$> getExpr e\n  | k, _, _ => throw s!\"getPrec parse error, unknown kind {k}\"\n\npartial def getPrecSym_aux (args : Array AstId) : M PrecSymbol :=\n  return (\u2190 getSym args[0]!, \u2190 opt getPrec args[1]!)\n\npartial def getPrecSym : AstId \u2192 M PrecSymbol := withNodeK fun _ _ => getPrecSym_aux\n\npartial def getAction : AstId \u2192 M (Spanned Action) :=\n  withNode fun\n  | \"nat\", v, _ => pure $ Action.prec $ Precedence.nat $ decodeNat! v\n  | \"expr\", _, #[e] => return Action.prec $ Precedence.expr $ \u2190 getExpr e\n  | \"prev\", _, _ => pure Action.prev\n  | \"scoped\", _, #[p, sc] => do\n    let scope i := do\n      let args := (\u2190 getRaw i).children'\n      pure (\u2190 getName args[0]!, \u2190 getExpr args[1]!)\n    pure $ Action.scoped (\u2190 opt getPrec p) (\u2190 opt scope sc)\n  | \"foldl\", _, args => getFold false args\n  | \"foldr\", _, args => getFold true args\n  | k, _, _ => throw s!\"getAction parse error, unknown kind {k}\"\nwhere\n  getFold (r) (args : Array AstId) : M Action := do\n    let sc := (\u2190 getRaw args[2]!).children'\n    pure $ Action.fold r\n      (\u2190 opt getPrec args[0]!) (\u2190 getPrecSym args[1]!)\n      (\u2190 getName sc[0]!, \u2190 getName sc[1]!, \u2190 getExpr sc[2]!)\n      (\u2190 opt getExpr args[3]!) (\u2190 opt getPrecSym args[4]!)\n\npartial def getLiteral : AstId \u2192 M (Spanned Literal) :=\n  withNode fun\n  | \"nat\", v, _ => pure $ Literal.nat $ decodeNat! v\n  | \"var\", _, #[v, act] => return Literal.var (\u2190 getName v) (\u2190 opt getAction act)\n  | \"sym\", _,  args => Literal.sym <$> getPrecSym_aux args\n  | \"binder\", _, #[p] => Literal.binder <$> opt getPrec p\n  | \"binders\", _, #[p] => Literal.binders <$> opt getPrec p\n  | k, _, _ => throw s!\"getLiteral parse error, unknown kind {k}\"\n\npartial def getNotationDef (nk : NotationKind) (args : Subarray AstId) : M Notation :=\n  match nk with\n  | some nk =>\n    return Notation.mixfix nk (\u2190 opt getName args[0]!)\n      (\u2190 getSym args[1]!, \u2190 opt getPrec args[2]!) (\u2190 opt getExpr args[3]!)\n  | none =>\n    return Notation.notation (\u2190 opt getName args[0]!)\n      (\u2190 arr getLiteral args[1]!) (\u2190 opt getExpr args[2]!)\n\npartial def getNotation' : AstId \u2192 M Notation :=\n  withNodeK fun k _ a => getNotationDef (toNotationKind k).get! a\n\npartial def getNotation : AstId \u2192 M NotationId :=\n  withNodeK fun k _ a => getNotationId (toNotationKind k).get! a\n\npartial def getField : AstId \u2192 M (Spanned Field) := withNode fun\n  | \"field_0\", _, args => field BinderInfo.default args\n  | \"field_1\", _, args => field BinderInfo.instImplicit args\n  | \"field_2\", _, args => field BinderInfo.strictImplicit args\n  | \"field_4\", _, args => field BinderInfo.implicit args\n  | \"field_8\", _, args => field BinderInfo.default args -- aux decl binders not supported\n  | k, _, args => match toNotationKind k with\n    | some nk => Field.notation <$> getNotationDef nk args\n    | none => throw s!\"getField parse error, unknown kind {k}\"\nwhere\n  field (bi : BinderInfo) (args : Array AstId) : M Field :=\n    return Field.binder bi (\u2190 arr getName args[0]!) (\u2190 opt getInferKind args[1]!)\n      (\u2190 getBinders args[2]!) (\u2190 opt getExpr args[3]!) (\u2190 getDefault (args.getD 4 0))\n\ndef getAttrArg : AstId \u2192 M (Spanned AttrArg) := withNodeR fun r =>\n  match r.kind with\n  | \"!\" => pure AttrArg.eager\n  | \"indices\" => AttrArg.indices <$> r.children'.mapM getNat\n  | \"key_value\" => return AttrArg.keyValue (\u2190 getStr r.children'[0]!) (\u2190 getStr r.children'[1]!)\n  | \"vm_override\" =>\n    return AttrArg.vmOverride (\u2190 getName r.children'[0]!) (\u2190 opt getName r.children'[1]!)\n  | \"parse\" => return AttrArg.user (\u2190 r.pexpr') (\u2190 r.children'.mapM getVMCall)\n  | k => throw s!\"getAttrArg parse error, unknown kind {k}\"\n\ndef getAttr : AstId \u2192 M (Spanned Attribute) := withNode fun\n  | \"priority\", _, #[e] => Attribute.priority <$> getExpr e\n  | \"attr\", v, #[del, arg] =>\n    if del = 0 then Attribute.add v <$> opt getAttrArg arg\n    else pure $ Attribute.del v\n  | k, _, _ => throw s!\"getAttr parse error, unknown kind {k}\"\n\nopen DeclVal in\ndef getDeclVal : AstId \u2192 M (Spanned DeclVal) :=\n  withNodeP fun\n  | \"eqns\", _, args, _ => eqns <$> args.mapM getArm\n  | k, v, args, pexpr => expr <$> getExpr_aux k v args pexpr\n\nopen Modifier in\ndef getModifier : AstId \u2192 M (Spanned Modifier) := withNode fun\n  | \"private\", _, _ => pure \u00abprivate\u00bb\n  | \"protected\", _, _ => pure \u00abprotected\u00bb\n  | \"noncomputable\", _, _ => pure \u00abnoncomputable\u00bb\n  | \"meta\", _, _ => pure \u00abmeta\u00bb\n  | \"mutual\", _, _ => pure \u00abmutual\u00bb\n  | \"doc\", v, _ => pure $ doc v.getString!\n  | \"@[\", _, #[a] => attr false true <$> arr getAttr a\n  | \"attribute\", _, #[loc, a] => attr (loc \u2260 0) false <$> arr getAttr a\n  | k, _, _ => throw s!\"getModifier parse error, unknown kind {k}\"\n\ndef getModifiers : AstId \u2192 M Modifiers := arr getModifier\n\ndef getLocal (i : AstId) : M LocalReserve := do\n  match (\u2190 getRaw? i).map fun n => n.kind with\n  | some \"local\"   => pure (true, false)\n  | some \"reserve\" => pure (false, true)\n  | none           => pure (false, false)\n  | _ => throw \"getLocal parse error\"\n\ndef getIntro : AstId \u2192 M (Spanned Intro) := withNode fun _ _ args => do\n  pure \u27e8\u2190 opt getStrK args[0]!, \u2190 getName args[1]!,\n    \u2190 opt getInferKind args[2]!, \u2190 getBinders args[3]!, \u2190 opt getExpr args[4]!\u27e9\n\ndef getRename : AstId \u2192 M Rename := withNodeK fun _ _ args => do\n  pure \u27e8\u2190 getName args[0]!, \u2190 getName args[1]!\u27e9\n\ndef getParent : AstId \u2192 M (Spanned Parent) := withNode fun _ _ args => do\n  pure \u27e8args[0]! \u2260 0, \u2190 opt getName args[1]!, \u2190 getExpr args[2]!, \u2190 arr getRename args[3]!\u27e9\n\ndef getMk : AstId \u2192 M (Spanned Mk) := withNode fun _ _ args => do\n  pure \u27e8\u2190 getName args[0]!, \u2190 opt getInferKind args[1]!\u27e9\n\ndef getMutual {\u03b1} (f : AstId \u2192 M \u03b1) : AstId \u2192 M (Mutual \u03b1) := withNodeK fun _ _ args => do\n  pure \u27e8\u2190 arr getAttr args[0]!, \u2190 getName args[1]!, \u2190 getExpr args[2]!, \u2190 arr f args[3]!\u27e9\n\nopen OpenClause in\ndef getOpenClause : AstId \u2192 M (Spanned OpenClause) :=\n  withNode fun\n  | \"explicit\", _, args => explicit <$> args.mapM getName\n  | \"renaming\", _, args => \u00abrenaming\u00bb <$> args.mapM getRename\n  | \"hiding\", _, args => \u00abhiding\u00bb <$> args.mapM getName\n  | k, _, _ => throw s!\"getOpenClause parse error, unknown kind {k}\"\n\ndef getOpen : AstId \u2192 M Open := withNodeK fun _ _ args => do\n  pure \u27e8\u2190 getName args[0]!, \u2190 opt getName args[1]!, \u2190 args[2:].toArray.mapM getOpenClause\u27e9\n\nopen HelpCmd in\ndef getHelpCmd : AstId \u2192 M HelpCmd := withNodeK fun\n  | \"options\", _, _ => pure options\n  | \"commands\", _, _ => pure commands\n  | k, _, _ => throw s!\"getHelpCmd parse error, unknown kind {k}\"\n\nopen PrintAttrCmd in\ndef getPrintAttrCmd : AstId \u2192 M (Spanned PrintAttrCmd) := withNode fun\n  | \"recursor\", _, _ => pure recursor\n  | \"unify\", _, _ => pure unify\n  | \"simp\", _, _ => pure simp\n  | \"congr\", _, _ => pure congr\n  | \"attr\", v, _ => pure $ attr v\n  | k, _, _ => throw s!\"getPrintAttrCmd parse error, unknown kind {k}\"\n\nopen PrintCmd in\ndef getPrintCmd (args : Array AstId) : M PrintCmd := do\n  let r \u2190 getRaw args[0]!\n  match r.kind with\n  | \"string\" => pure $ str r.value.getString!\n  | \"raw\" => raw <$> getExpr args[1]!\n  | \"options\" => pure options\n  | \"trust\" => pure trust\n  | \"key_equivalences\" => pure keyEquivalences\n  | \"definition\" => \u00abdef\u00bb <$> getName args[1]!\n  | \"instances\" => instances <$> getName args[1]!\n  | \"classes\" => pure classes\n  | \"attributes\" => pure attributes\n  | \"prefix\" => \u00abprefix\u00bb <$> getName args[1]!\n  | \"aliases\" => pure aliases\n  | \"axioms\" => axioms <$> opt getName args[1]!\n  | \"fields\" => fields <$> getName args[1]!\n  | \"notation\" => \u00abnotation\u00bb <$> args.mapM getName\n  | \"inductive\" => \u00abinductive\u00bb <$> getName args[1]!\n  | \"attribute\" => attr <$> getPrintAttrCmd args[1]!\n  | \"token\" => token <$> r.map args[0]! fun _ v _ => pure v\n  | \"ident\" => ident <$> r.map args[0]! fun _ v _ => pure v\n  | k => throw s!\"getPrintCmd parse error, unknown kind {k}\"\n\ndef getHeader (args : Subarray AstId) :\n  M (LevelDecl \u00d7 Option (Spanned Name) \u00d7 Binders \u00d7 Option (Spanned Expr)) := do\n  pure (\u2190 getLevelDecl args[0]!, \u2190 opt getName args[1]!, \u2190 getBinders args[2]!, \u2190 opt getExpr args[3]!)\n\ndef getMutualHeader (args : Subarray AstId) : M (LevelDecl \u00d7 Binders) := do\n  pure (\u2190 getLevelDecl args[0]!, /- \u2190 arr getName args[1]!, -/ \u2190 getBinders args[2]!)\n\ndef getInductive (cl : Bool) (args : Array AstId) : M InductiveCmd := do\n  let mods \u2190 getModifiers args[0]!\n  if args[1]! = 0 then\n    let (us, n, bis, ty) \u2190 getHeader args[2:6]\n    let nota \u2190 opt getNotation' args[6]!\n    pure $ InductiveCmd.reg cl mods n.get! us bis ty nota (\u2190 arr getIntro args[7]!)\n  else\n    let (us, bis) \u2190 getMutualHeader args[2:5]\n    let nota \u2190 opt getNotation' args[5]!\n    pure $ InductiveCmd.mutual cl mods us bis nota (\u2190 arr (getMutual getIntro) args[6]!)\n\nopen Command in\ndef getCommand : AstId \u2192 M (Spanned Command) :=\n  withNode fun\n  -- | \"prelude\", _, _ => \u00abprelude\u00bb\n  | \"init_quotient\", _, _ => pure initQuotient\n  -- | \"import\", _, args => \u00abimport\u00bb <$> args.mapM getName\n  | \"mdoc\", v, _ => pure $ mdoc v.getString!\n  | \"namespace\", _, #[n] => \u00abnamespace\u00bb <$> getName n\n  | \"section\", _, #[n] => \u00absection\u00bb <$> opt getName n\n  | \"end\", _, #[n] => \u00abend\u00bb <$> opt getName n\n  | \"universe\", _, args => \u00abuniverse\u00bb false false <$> args.mapM getName\n  | \"universes\", _, args => \u00abuniverse\u00bb false true <$> args.mapM getName\n  | \"universe_variable\", _, args => \u00abuniverse\u00bb true false <$> args.mapM getName\n  | \"universe_variables\", _, args => \u00abuniverse\u00bb true true <$> args.mapM getName\n  | \"axiom\", _, args => getAxiom AxiomKind.axiom args\n  | \"constant\", _, args => getAxiom AxiomKind.constant args\n  | \"axioms\", _, args => getVars args $ \u00abaxioms\u00bb AxiomKind.axiom\n  | \"constants\", _, args => getVars args $ \u00abaxioms\u00bb AxiomKind.constant\n  | \"variable\", _, args => getVars args $ \u00abvariable\u00bb VariableKind.variable false\n  | \"parameter\", _, args => getVars args $ \u00abvariable\u00bb VariableKind.parameter false\n  | \"variables\", _, args => getVars args $ \u00abvariable\u00bb VariableKind.variable true\n  | \"parameters\", _, args => getVars args $ \u00abvariable\u00bb VariableKind.parameter true\n  | \"definition\", _, args => getDecl DeclKind.def args\n  | \"theorem\", _, args => getDecl DeclKind.theorem args\n  | \"abbreviation\", _, args => getDecl DeclKind.abbrev args\n  | \"example\", _, args => getDecl DeclKind.example args\n  | \"instance\", _, args => getDecl DeclKind.instance args\n  | \"inductive\", _, args => Command.inductive <$> getInductive false args\n  | \"class_inductive\", _, args => Command.inductive <$> getInductive true args\n  | \"structure\", _, args => getStructure false args\n  | \"class\", _, args => getStructure true args\n  | \"attribute\", _, args => getAttribute args\n  | \"precedence\", _, #[c, p] => return precedence (\u2190 getSym c) (\u2190 getPrec p)\n  | \"open\", _, args => \u00abopen\u00bb false <$> args.mapM getOpen\n  | \"export\", _, args => \u00abopen\u00bb true <$> args.mapM getOpen\n  | \"include\", _, args => \u00abinclude\u00bb true <$> args.mapM getName\n  | \"omit\", _, args => \u00abinclude\u00bb false <$> args.mapM getName\n  | \"hide\", _, args => \u00abhide\u00bb <$> args.mapM getName\n  | \"theory\", _, #[mods] => \u00abtheory\u00bb <$> getModifiers mods\n  | \"set_option\", _, #[opt, val] => return setOption (\u2190 getName opt) (\u2190 getOptionVal val)\n  | \"declare_trace\", _, #[n] => declareTrace <$> getName n\n  | \"add_key_equivalence\", _, #[n1, n2] => return addKeyEquivalence (\u2190 getName n1) (\u2190 getName n2)\n  | \"run_cmd\", _, #[e] => runCmd <$> getExpr e\n  | \"#check\", _, #[e] => check <$> getExpr e\n  | \"#reduce\", _, #[whnf, e] => reduce (whnf \u2260 0) <$> getExpr e\n  | \"#eval\", _, #[e] => eval <$> getExpr e\n  | \"#unify\", _, #[e1, e2] => return unify (\u2190 getExpr e1) (\u2190 getExpr e2)\n  | \"#compile\", _, #[e] => eval <$> getExpr e\n  | \"#help\", _, #[arg] => help <$> getHelpCmd arg\n  | \"#print\", _, args => print <$> getPrintCmd args\n  | \"user_command\", v, args =>\n    return userCommand v (\u2190 getModifiers args[0]!) (\u2190 args[1:].toArray.mapM getParam)\n  | k, _, args => match toNotationKind k with\n    | some nk => getNotationCmd nk args\n    | none => throw s!\"getCommand parse error, unknown kind {k}\"\nwhere\n  getAxiom (ak) (args : Array AstId) : M Command :=\n    return Command.axiom ak\n      (\u2190 getModifiers args[0]!) (\u2190 getName args[2]!) (\u2190 getLevelDecl args[1]!)\n      (\u2190 getBinders args[3]!) (\u2190 getExpr args[4]!)\n\n  getVars (args : Array AstId) (f : Modifiers \u2192 Binders \u2192 Command) : M Command := do\n    f (\u2190 getModifiers args[0]!) <$> args[1:].toArray.mapM getBinder\n\n  getUWF : AstId \u2192 M (Spanned Expr) := withNodeK fun _ _ args => getExpr args[0]!\n\n  getDecl (dk) (args : Array AstId) : M Command := do\n    let mods \u2190 getModifiers args[0]!\n    if args[1]! = 0 then\n      let (us, n, bis, ty) \u2190 getHeader args[2:6]\n      let val \u2190 getDeclVal args[6]!\n      let uwf \u2190 if let .expr _ := val.kind then pure none else opt getUWF args[7]!\n      pure $ .decl dk mods n us bis ty val uwf\n    else\n      let (us, bis) \u2190 getMutualHeader args[2:5]\n      pure $ .mutualDecl dk mods us bis (\u2190 arr (getMutual getArm) args[5]!) (\u2190 opt getUWF args[6]!)\n\n  getNotationCmd (mk : Option MixfixKind) (args : Array AstId) : M Command :=\n    return Command.notation\n      (\u2190 getLocal args[0]!) (\u2190 arr getAttr args[1]!) (\u2190 getNotationDef mk args[2:])\n\n  getStructure (cl args) : M Command := do\n    return Command.structure cl (\u2190 getModifiers args[0]!) (\u2190 getName args[2]!)\n      (\u2190 getLevelDecl args[1]!) (\u2190 getBinders args[3]!) (\u2190 arr getParent args[4]!)\n      (\u2190 opt getExpr args[5]!) (\u2190 opt getMk args[6]!) (\u2190 arr getField args[7]!)\n\n  getAttribute (args) : M Command := do\n    let mods \u2190 getModifiers args[0]!\n    pure $ \u00abattribute\u00bb (args[1]! \u2260 0) mods (\u2190 arr getAttr args[2]!) (\u2190 args[3:].toArray.mapM getName)\n\ndef getAST (comments : Array Comment) : AstId \u2192 M (AST3 \u00d7 HashMap AstId (Spanned AST3.Tactic)) := withNodeK fun\n  | \"file\", _, #[prel, imp, cmds] => do\n    let prel \u2190 opt (withNode fun _ _ _ => pure ()) prel\n    let imp \u2190 arr (withNodeK fun _ _ args => args.mapM getName) imp\n    let cmds \u2190 arr getCommand cmds\n    let \u27e8inota, icmds, tacs\u27e9 \u2190 get\n    pure (\u27e8prel, imp, cmds, inota, icmds, comments\u27e9, tacs)\n  | k, _, args => throw s!\"getAST parse error, unknown kind {k}, {args}\"\n\npartial def M.run (ast : Array (Option RawNode3)) (expr : Array Lean3.Expr) :\n  M \u03b1 \u2192 Except String \u03b1 :=\n  fun m => (m ctx).run' {}\nwhere\n  pushCmd c := do\n    let n := (\u2190 get).cmds.size\n    modify fun s => { s with cmds := s.cmds.push c }\n    pure n\n  pushNota nota := do\n    let n := (\u2190 get).notations.size\n    modify fun s => { s with notations := s.notations.push nota }\n    pure n\n  ctx := {\n    ast, expr\n    getNotationId := fun nk args => do pushNota (\u2190 getNotationDef nk args ctx)\n    getInductiveId := fun args => do pushCmd (Command.inductive (\u2190 getInductive false args ctx))\n    getCommandId := fun i => do pushCmd (\u2190 getCommand i ctx).kind }\n\nend\n\ninductive RawLevel where\n  | \u00ab0\u00bb\n  | suc : LevelId \u2192 RawLevel\n  | max : Array LevelId \u2192 RawLevel\n  | imax : Array LevelId \u2192 RawLevel\n  | param : Name \u2192 RawLevel\n  | mvar : Name \u2192 RawLevel\n  deriving FromJson\n\ninstance : FromJson RawLevel :=\n  \u27e8fun x => do\n    try fromJson? x\n    catch e => throw s!\"at: {x}\\n{e}\"\u27e9\n\ninstance : FromJson BinderInfo where\n  fromJson? j := do\n    match \u2190 j.getNat? with\n    | 0 => pure BinderInfo.default\n    | 1 => pure BinderInfo.instImplicit\n    | 2 => pure BinderInfo.strictImplicit\n    | 4 => pure BinderInfo.implicit\n    | 8 => pure BinderInfo.default -- aux decl binders not supported\n    | _ => throw \"unknown binder type\"\n\ninductive Annotation\n  | no_univ\n  | do_failure_eq\n  | infix_fn\n  | begin_hole\n  | end_hole\n  | anonymous_constructor\n  | \u00abcalc\u00bb\n  | no_info\n  | frozen_name\n  | \u00abhave\u00bb\n  | \u00abshow\u00bb\n  | \u00absuffices\u00bb\n  | checkpoint\n  | \u00ab@\u00bb\n  | \u00ab@@\u00bb\n  | as_atomic\n  | as_is\n  | antiquote\n  | expr_quote_pre\n  | comp_irrel\n  | inaccessible\n  | \u00abby\u00bb\n  | pattern_hint\n  | th_proof\n  deriving FromJson\n\ninductive RawExpr where\n  | var : Nat \u2192 RawExpr\n  | sort : LevelId \u2192 RawExpr\n  | const : Name \u2192 Array LevelId \u2192 RawExpr\n  | app : ExprId \u2192 ExprId \u2192 RawExpr\n  | lam (name : Name) (bi : BinderInfo) (dom body : ExprId)\n  | Pi (name : Name) (bi : BinderInfo) (dom body : ExprId)\n  | \u00ablet\u00bb (name : Name) (type value body : ExprId)\n  | \u00ablocal\u00bb (name pp : Name) (bi : BinderInfo) (type : ExprId)\n  | mvar (name pp : Name) (type : ExprId)\n  | annotation (name : Annotation) (args : Array ExprId)\n  | field_notation (field : Name) (idx : Nat) (args : Array ExprId)\n  | typed_expr (args : Array ExprId)\n  | \u00abstructure instance\u00bb (struct : Name) (catchall : Bool) (fields : Array Name) (args : Array ExprId)\n  | projection_macro (I constr proj : Name) (idx : Nat) (params : Array Name)\n    (type val : ExprId) (args : Array ExprId)\n  | \u00absorry\u00bb (synthetic : Bool) (args : Array ExprId)\n  | prenum (value : String)\n  | nat_value (value : String)\n  | string_macro (value : String)\n  | expr_quote_macro (value : ExprId) (reflected : Bool)\n  | choice (args : Array ExprId)\n  | as_pattern (args : Array ExprId)\n  | rec_fn (name : Name) (args : Array ExprId)\n  | delayed_abstraction (value : Array Name) (args : Array ExprId)\n  | no_equation : Unit \u2192 RawExpr\n  | equation (ignore_if_unused : Bool) (args : Array ExprId)\n  | equations (num_fns : Nat) (fn_names fn_actual_names : Array Name)\n    (prev_errors is_private is_noncomputable is_meta is_lemma gen_code aux_lemmas : Bool)\n    (args : Array ExprId)\n  | equations_result (args : Array ExprId)\n  | ac_app (args : Array ExprId)\n  | perm_ac (args : Array ExprId)\n  | cc_proof (args : Array ExprId)\n  deriving FromJson\n\ninstance : FromJson RawExpr :=\n  \u27e8fun x => do\n    try fromJson? x\n    catch e => throw s!\"at: {x}\\n{e}\"\u27e9\n\nstructure RawTacticInvocation where\n  ast : AstId\n  start : TacticStateId\n  \u00abend\u00bb : TacticStateId\n  success : Bool\n  deriving FromJson\n\nstructure RawHyp where\n  name : Name\n  pp : Name\n  type : ExprId\n  value : Option ExprId\n  deriving FromJson\n\nstructure RawGoal where\n  hyps : Array RawHyp\n  target : ExprId\n\ninstance : FromJson RawGoal where\n  fromJson? j := do pure \u27e8\u2190 fromJson? (\u2190 j.getArrVal? 0), \u2190 fromJson? (\u2190 j.getArrVal? 1)\u27e9\n\nstructure RawTacticState where\n  decl : Name\n  goals : Array RawGoal\n  deriving FromJson\n\nderiving instance FromJson for AST3.Comment\n\nstructure RawAST3 where\n  ast      : Array (Option RawNode3)\n  file     : AstId\n  level    : Array RawLevel\n  expr     : Array (Option RawExpr)\n  tactics  : Option (Array RawTacticInvocation)\n  states   : Option (Array RawTacticState)\n  comments : Array AST3.Comment\n  deriving FromJson\n\nsection\nopen Lean (Level)\nopen Lean3 (EquationsHeader LambdaEquation Expr Proj)\n\nvariable (lvls : Array Level)\ndef buildLevel : RawLevel \u2192 Level\n  | RawLevel.\u00ab0\u00bb => Lean.levelZero\n  | RawLevel.suc l => Lean.mkLevelSucc lvls[l]!\n  | RawLevel.max ls => Lean.mkLevelMax lvls[ls[0]!]! lvls[ls[1]!]!\n  | RawLevel.imax ls => Lean.mkLevelIMax lvls[ls[0]!]! lvls[ls[1]!]!\n  | RawLevel.param n => Lean.mkLevelParam n\n  | RawLevel.mvar n => Lean.mkLevelMVar \u27e8n\u27e9\n\nvariable (exprs : Array Expr)\n\ndef buildLevels (ls : Array RawLevel) : Array Level := Id.run do\n  let mut out := #[]\n  for l in ls do\n    let l' := buildLevel out l\n    out := out.push l'\n  out\n\ndef Annotation.build : Annotation \u2192 Lean3.Annotation\n  | no_univ => Lean3.Annotation.no_univ\n  | do_failure_eq => Lean3.Annotation.do_failure_eq\n  | infix_fn => Lean3.Annotation.infix_fn\n  | begin_hole => Lean3.Annotation.begin_hole\n  | end_hole => Lean3.Annotation.end_hole\n  | anonymous_constructor => Lean3.Annotation.anonymous_constructor\n  | \u00abcalc\u00bb => Lean3.Annotation.\u00abcalc\u00bb\n  | no_info => Lean3.Annotation.no_info\n  | frozen_name => Lean3.Annotation.frozen_name\n  | \u00abhave\u00bb => Lean3.Annotation.\u00abhave\u00bb\n  | \u00abshow\u00bb => Lean3.Annotation.\u00abshow\u00bb\n  | \u00absuffices\u00bb => Lean3.Annotation.\u00absuffices\u00bb\n  | checkpoint => Lean3.Annotation.checkpoint\n  | \u00ab@\u00bb => Lean3.Annotation.\u00ab@\u00bb\n  | \u00ab@@\u00bb => Lean3.Annotation.\u00ab@@\u00bb\n  | as_atomic => Lean3.Annotation.as_atomic\n  | as_is => Lean3.Annotation.as_is\n  | antiquote => Lean3.Annotation.antiquote\n  | expr_quote_pre => Lean3.Annotation.expr_quote_pre\n  | comp_irrel => Lean3.Annotation.comp_irrel\n  | inaccessible => Lean3.Annotation.inaccessible\n  | \u00abby\u00bb => Lean3.Annotation.\u00abby\u00bb\n  | pattern_hint => Lean3.Annotation.pattern_hint\n  | th_proof => Lean3.Annotation.th_proof\n\ndef RawExpr.build : RawExpr \u2192 Expr\n  | var i => Expr.var i\n  | sort l => Expr.sort lvls[l]!\n  | const c ls => Expr.const c $ ls.map fun l => lvls[l]!\n  | app f a => Expr.app exprs[f]! exprs[a]!\n  | lam n bi d b => Expr.lam n bi exprs[d]! exprs[b]!\n  | Pi n bi d b => Expr.Pi n bi exprs[d]! exprs[b]!\n  | \u00ablet\u00bb n t v b => Expr.let n exprs[t]! exprs[v]! exprs[b]!\n  | mvar n pp t => Expr.mvar n pp exprs[t]!\n  | \u00ablocal\u00bb n pp bi t => Expr.local n pp bi exprs[t]!\n  | annotation n args => Expr.annotation n.build exprs[args[0]!]!\n  | field_notation field idx args => Expr.field exprs[args[0]!]! $\n    if field.isAnonymous then Proj.ident field else Proj.nat idx\n  | typed_expr args => Expr.typed_expr exprs[args[0]!]! exprs[args[1]!]!\n  | \u00abstructure instance\u00bb s ca flds args => Expr.structinst s ca\n    (flds.zipWith args fun n a => (n, exprs[a]!))\n    (args[flds.size:].toArray.map fun a => exprs[a]!)\n  | projection_macro I c p i ps ty val args =>\n    Expr.proj I c p i ps exprs[ty]! exprs[val]! exprs[args[0]!]!\n  | \u00absorry\u00bb s args => Expr.sorry s exprs[args[0]!]!\n  | prenum n => Expr.prenum (Lean.Syntax.decodeNatLitVal? n).get!\n  | nat_value n => Expr.nat (Lean.Syntax.decodeNatLitVal? n).get!\n  | string_macro v => Expr.string v\n  | expr_quote_macro v r => Expr.quote exprs[v]! r\n  | choice args => Expr.choice $ args.map fun v => exprs[v]!\n  | as_pattern args => Expr.as_pattern exprs[args[0]!]! exprs[args[1]!]!\n  | rec_fn n args => Expr.rec_fn n exprs[args[0]!]!\n  | delayed_abstraction ns args =>\n    let args := args.map fun a => exprs[a]!\n    Expr.delayed_abstraction args.back (ns.zip args.pop)\n  | no_equation _ => Expr.no_equation\n  | equation iu args => Expr.equation exprs[args[0]!]! exprs[args[1]!]! iu\n  | equations n ns as _ p nc m l gc al args =>\n    let args : Array Expr := args.map fun a => exprs[a]!\n    let h := EquationsHeader.mk n ns as p nc m l gc al\n    let (args, wf) :=\n      if args.size \u2265 2 \u2227 args.back.toLambdaEqn.isNone then (args.pop, some args.back)\n      else (args, none)\n    Expr.equations h (args.map fun e => e.toLambdaEqn.get!) wf\n  | equations_result args => Expr.equations_result $ args.map fun a => exprs[a]!\n  | ac_app args =>\n    let args : Array Expr := args.map fun a => exprs[a]!\n    Expr.ac_app args.pop args.back\n  | perm_ac args => Expr.perm_ac exprs[args[0]!]! exprs[args[1]!]! exprs[args[2]!]! exprs[args[3]!]!\n  | cc_proof args => Expr.cc_proof exprs[args[0]!]! exprs[args[1]!]!\n\ndef buildExprs (es : Array (Option RawExpr)) : Array Expr := Id.run do\n  let mut out := #[]\n  for e in es do\n    let e' : Expr := match e with\n    | some e => e.build lvls out\n    | none => default\n    out := out.push e'\n  out\n\ndef RawHyp.build : RawHyp \u2192 AST3.Hyp\n  | \u27e8name, pp, ty, val\u27e9 => \u27e8name, pp, exprs[ty]!, val.map fun e => exprs[e]!\u27e9\n\ndef RawGoal.build : RawGoal \u2192 AST3.Goal\n  | \u27e8hyps, target\u27e9 => \u27e8hyps.map (\u00b7.build exprs), exprs[target]!\u27e9\n\ndef RawTacticState.build : RawTacticState \u2192 Name \u00d7 Array AST3.Goal\n  | \u27e8declName, goals\u27e9 => (declName, goals.map (\u00b7.build exprs))\n\ndef RawTacticInvocation.build\n  (states : Array (Name \u00d7 Array AST3.Goal))\n  (tacs : HashMap AstId (Spanned AST3.Tactic)) :\n  RawTacticInvocation \u2192 AST3.TacticInvocation\n  | \u27e8ast, start, end_, success\u27e9 => \u27e8states[start]!.1, tacs.find? ast, states[start]!.2, states[end_]!.2, success\u27e9\n\nend\n\ndef RawAST3.build : RawAST3 \u2192 (invocs :_:= true) \u2192 Except String (AST3 \u00d7 Array AST3.TacticInvocation)\n| \u27e8ast, file, level, expr, tactics, states, comments\u27e9, invocs => do\n  let level := buildLevels level\n  let expr := buildExprs level expr\n  M.run ast expr $ do\n    let (ast, tacs) \u2190 getAST comments file\n    let invocs :=\n      if invocs then\n        let states := (states.getD #[]).map (fun (s : RawTacticState) => s.build expr)\n        (tactics.getD #[]).map (\u00b7.build states tacs)\n      else #[]\n    pure (ast, invocs)\n\nend Parse\n\ndef parseAST3 (filename : System.FilePath) (invocs :_:= true) :\n  IO (AST3 \u00d7 Array AST3.TacticInvocation) := do\n  -- println! \"Reading {filename}...\"\n  let s \u2190 IO.FS.readFile filename\n  -- println! \"Parsing Json...\"\n  let json \u2190 Json.parse s\n  -- println! \"Decoding RawAST3...\"\n  let rawAST3 \u2190 fromJson? json (\u03b1 := Parse.RawAST3)\n  -- println! \"Converting RawAST3 to AST3...\"\n  rawAST3.build invocs\n\n-- #eval show IO Unit from do\n--   let (_, invocs) \u2190 parseAST3 \"/home/mario/Documents/lean/lean/library/init/data/nat/lemmas.ast.json\"\n--   for i in invocs[0:10] do\n--     println! \"{repr i}\\n\\n\"\n\n-- #eval show IO Unit from do\n--   let s \u2190 IO.FS.readFile \"/home/mario/Documents/lean/lean/library/init/data/nat/lemmas.ast.json\"\n--   let json \u2190 Json.parse s\n--   let rawAST3@\u27e8ast, file, level, expr\u27e9 \u2190 fromJson? json (\u03b1 := Parse.RawAST3)\n--   let level := Parse.buildLevels level\n--   let expr := Parse.buildExprs level expr\n--   -- println! \"{repr rawAST3.toAST3}\"\n--   let commands := ast[ast[file].get!.children'[2]].get!.children'\n--   for c in commands[0:] do\n--     println! (repr (\u2190 Parse.getNode c |>.run \u27e8ast, expr\u27e9)).group ++ \"\\n\"\n--     println! (repr (\u2190 Parse.getCommand c |>.run \u27e8ast, expr\u27e9).kind).group ++ \"\\n\"\n", "meta": {"author": "leanprover-community", "repo": "mathport", "sha": "b5459df41774820ca21861417fafd8ff7a662fc5", "save_path": "github-repos/lean/leanprover-community-mathport", "path": "github-repos/lean/leanprover-community-mathport/mathport-b5459df41774820ca21861417fafd8ff7a662fc5/Mathport/Syntax/Parse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.057493282433961186, "lm_q1q2_score": 0.016915383779269242}}
{"text": "import evaluation\nimport backends.bfs.openai\n\n/-- A tactic that will ring up GPT to ask for help solving a goal.\nRemember to set the `OPEN_AI_KEY` environment variable.\nEg:\n```sh\n# ~/.zshenv\nexport OPEN_AI_KEY=\"<PUT YOUR SECRET KEY IN HERE>\"\n```\nyou may need to relogin to update.\n\n`n` is the number of iterations for the greedy search.\n`temperature` is a float between 0 and 1, and controls how deterministic the predictions are.\n-/\n\nmeta def try_lookup_key (env : environment) : tactic string := do {\n  key_decl \u2190 env.get `OPENAI_API_KEY,\n  val \u2190 tactic.eval_expr string key_decl.value,\n  pure val\n}\n\nmeta def get_openai_api_key : tactic string := do {\n  env \u2190 tactic.get_env,\n  -- TODO(jesse): for some reason try_lookup_key fails to resolve the name\n  (try_lookup_key env <|> (tactic.unsafe_run_io $ io.env.get \"OPENAI_API_KEY\") >>= lift_option) <|>\n    tactic.fail \"can't find a key at OPENAI_API_KEY\"\n}\n\nmeta def lookup_key : tactic string := do {\n  env \u2190 tactic.get_env,\n  d \u2190 env.get `OPEN_AI_KEY,\n  tactic.eval_expr string d.value\n}\n\nnamespace tactic\nnamespace interactive\n\nsetup_tactic_parser\n\n/-\n`n` is the number of parallel requests for the greedy search.\n`depth` is the number of iterations to run the greedy search\n`temperature` is a float between 0 and 1, and controls how\n deterministic the predictions are.\n-/\nmeta structure GPTSuggestConfig : Type :=\n(n : \u2115 := 32)\n(fuel : \u2115 := 0)\n(temp : native.float := 1.0)\n(silent := ff)\n(max_depth : \u2115 := 50)\n(max_width : \u2115 := 10)\n\nopen openai\n\n--- meta def gptf (cfg : GPTSuggestConfig := {}) : tactic unit :=\n-- tactic.success_if_fail done *> do {\n--   let \u27e8n, fuel, temperature, silent\u27e9 := cfg,\n--   let partial_req := { n := n, temperature := temperature, .. default_partial_req },\n--   let engine_id := \"formal-3b-lean-webmath-1230-v2-c4\",\n--   api_key \u2190 get_openai_api_key,\n--   ps \u2190 prod.snd <$> state_t.run\n--          (openai_greedy_proof_search_core partial_req engine_id api_key fuel) {},\n--   when (not silent) $ do {\n--     tactic.trace \"Predictions\\n\",\n--     ps.predictions.head.mmap' tactic.trythis,\n--     tactic.trace \"\\nTactics:\\n\",\n--     tactic.trythis $ string.intercalate \", \" (ps.tactics)\n--   }\n-- }\n\nmeta def gptf_core (cfg : GPTSuggestConfig := {}) : tactic (list string \u00d7 list string) := do {\ntactic.success_if_fail done *> do {\n  let \u27e8n, fuel, temperature, silent, max_depth, max_width\u27e9 := cfg,\n  let partial_req := { n := n, temperature := temperature, .. default_partial_req },\n  -- let engine_id := \"formal-3b-lean-webmath-1230-v2-c4\",\n  let engine_id := \"formal-large-lean-0119-mix-v1-c4\",\n  api_key \u2190 get_openai_api_key,\n  init_state \u2190 BFSState.of_current_state fuel max_width max_depth 3,\n  ps \u2190 prod.snd <$> state_t.run\n         (openai_bfs_proof_search_core partial_req engine_id api_key fuel) init_state,\n  -- two cases: either the proof has finished and `tactics` field is populated\n  -- or proof is not finished and we have to inpsect the open nodes on the search queue\n  let predictions := ps.predictions.head,\n  if ps.tactics.length = 0 then prod.mk predictions <$> ps.nodes.mfold (\u03bb acc node, pure $ list.append acc [string.intercalate \",\" node.tactics]) []\n    else pure $ prod.mk predictions $ pure $ \",\".intercalate ps.tactics\n  }\n}\n\nmeta def gptf (cfg : GPTSuggestConfig := {}) : tactic unit := do {\n  \u27e8predictions, tactics\u27e9 \u2190 gptf_core cfg,    \n  tactic.trace \"\\nPredictions:\\n\",\n  predictions.mmap' tactic.trythis,\n  tactic.trace \"\\nTactics:\\n\",\n  tactics.mmap' tactic.trythis\n}\n\nprivate meta def gptf_string (cfg : GPTSuggestConfig := {}) : tactic string := do {\n  \u27e8_, tactics\u27e9 \u2190 gptf_core cfg,\n  match tactics with\n  | (x::xs) := pure x\n  | [] := tactic.fail \"[gptf'] NO CANDIDATES FOUND\"\n  end\n}\n\n-- TODO(jesse): try running with low max_width, high max_depth, and relatively low fuel (25-50)\nmeta def neuroblast (fuel : \u2115 := 50) : tactic unit := gptf {fuel := fuel, max_width := 5, max_depth := 25}\n\n-- TODO(jesse): distribution of states induced by `tidy` is unfamiliar for the model\n-- might get more gains by augmenting with synthetic data/RL\nmeta def neuroblast\u2082 (trace : parse $ optional (tk \"?\")) : tactic unit := do {\n  let neuroblast_cfg : tidy.cfg := {trace_result := trace.is_some, tactics := \n  tidy.default_tactics ++ [gptf_string]},\n  tactic.tidy.core neuroblast_cfg *> pure ()\n}\n\nend interactive\nend tactic\n\n-- `gpt` Hello World\nexample {\u03b1} (a : \u03b1) : a = a :=\nbegin\n  refl\nend\n\nexample : \u2203 n : \u2115, 8 = 2*n :=\nbegin\n  exact \u27e84, rfl\u27e9\nend\n\nexample {P Q R : Prop} : P \u2192 (P \u2192 R) \u2192 R :=\nbegin\n  intros h1 h2, exact h2 h1\nend\n\nexample {p q r : Prop} (h\u2081 : p) (h\u2082 : q) : (p \u2227 q) \u2228 r :=\nbegin\n  exact or.inl \u27e8h\u2081, h\u2082\u27e9\nend\n\nexample {P Q : Prop} : (\u00ac P) \u2227 (\u00ac Q) \u2192 \u00ac (P \u2228 Q) :=\nbegin\n  intro h, simp [h]\nend\n\nexample {P Q R : Prop} : (P \u2227 Q) \u2192 ((P \u2192 R) \u2192 \u00ac (Q \u2192 \u00ac R)) := \nbegin\n  rintros \u27e8h\u2081, h\u2082\u27e9 hh, apply not_imp_of_and_not; intros; cc\n  -- intros h1 h2, intros h3, cases h1 with p h1, apply h3 _ (h2 p), exact h1\nend\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/trythis.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.057493279607847, "lm_q1q2_score": 0.016915383659381635}}
{"text": "\nimport tactic.basic data.list.defs data.prod data.sum tactic.rcases\nuniverses u\u2081 u\u2082\n\nopen interactive interactive.types\nopen lean.parser nat tactic\n\nmeta def get_ext_subject : expr \u2192 tactic name\n| (expr.pi n bi d b) :=\n  do v  \u2190 mk_local' n bi d,\n     b' \u2190 whnf $ b.instantiate_var v,\n     get_ext_subject b'\n| (expr.app _ e) :=\n  do t \u2190 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 \u2190 pp t,\n       fail format!\"only constants and Pi types are supported: {t}\"\n| e := fail format!\"Only expressions of the form `_ \u2192 _ \u2192 ... \u2192 R ... e are supported: {e}\"\n\nopen native\n\n@[reducible] def ext_param_type := option name \u2295 option name\n\nmeta def opt_minus : lean.parser (option name \u2192 ext_param_type) :=\nsum.inl <$ tk \"-\" <|> pure sum.inr\n\nmeta def ext_param :=\nopt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets \"(\" \")\" (tk \"\u2192\" <|> tk \"->\") <|>\n                none <$  tk \"*\" <|>\n                some <$> ident )\n\nmeta def saturate_fun : name \u2192 tactic expr\n| (name.mk_numeral 0 name.anonymous) :=\ndo v\u2080 \u2190 mk_mvar,\n   v\u2081 \u2190 mk_mvar,\n   return $ v\u2080.imp v\u2081\n| (name.mk_numeral 1 name.anonymous) :=\ndo u \u2190 mk_meta_univ,\n   pure $ expr.sort u\n| n :=\ndo e \u2190 resolve_constant n >>= mk_const,\n   a \u2190 get_arity e,\n   e.mk_app <$> (list.iota a).mmap (\u03bb _, mk_mvar)\n\nmeta def equiv_type_constr (n n' : name) : tactic unit :=\ndo e  \u2190 saturate_fun n,\n   e' \u2190 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 : \u2200 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 [(\u2192),thunk,stream]] funext\n ```\n\n Those parameters are cumulative. The following are equivalent:\n\n ```\n attribute [extensionality [(\u2192),thunk]] funext\n attribute [extensionality [stream]] funext\n ```\n and\n ```\n attribute [extensionality [(\u2192),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 : \u2200 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 : \u2200 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 : \u2200 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 \u00d7 list ext_param_type \u00d7 list name \u00d7 list (name \u00d7 name)) :=\n{ name := `extensionality,\n  descr := \"lemmas usable by `ext` tactic\",\n  cache_cfg := { mk_cache := \u03bb ls,\n                          do { attrs \u2190 ls.mmap $ \u03bb l,\n                                     do { \u27e8_,_,ls,_\u27e9 \u2190 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 \u2190 pure <$> ext_param <|> list_of ext_param <|> pure [],\n         m \u2190 extensional_attribute.get_cache,\n         pure $ (ff,ls,[],m.to_list)  },\n  after_set := some $ \u03bb n _ b,\n    do (ff,ls,_,ls') \u2190 extensional_attribute.get_param n | pure (),\n       s \u2190 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'' \u222a (ls'.filter $ \u03bb 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 [(\u2192),thunk]] _root_.funext\n\nnamespace ulift\n@[extensionality] lemma ext {\u03b1 : Type u\u2081} (X Y : ulift.{u\u2082} \u03b1) (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 \u2192 tactic ext_patt\n| [] := try intros $> []\n| (x::xs) :=\ndo tgt \u2190 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 \u2190 target >>= get_ext_subject,\n   m \u2190 extensional_attribute.get_cache,\n   do { rule \u2190 m.find subject,\n        applyc rule cfg } <|>\n     do { ls \u2190 attribute.get_instances `extensionality,\n          ls.any_of (\u03bb n, applyc n cfg) } <|>\n     fail format!\"no applicable extensionality rule found for {subject}\",\n   try_intros xs\n\nmeta def ext : ext_patt \u2192 option \u2115 \u2192 tactic unit\n| _  (some 0) := skip\n| xs n        := focus1 $ do\n  ys \u2190 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  \u03b1 \u03b2 : Type,\n  f g : \u03b1 \u2192 set \u03b2\n  \u22a2 f = g\n  ```\n\n  applying `ext x y` yields:\n\n  ```\n  \u03b1 \u03b2 : Type,\n  f g : \u03b1 \u2192 set \u03b2,\n  x : \u03b1,\n  y : \u03b2\n  \u22a2 y \u2208 f x \u2194 y \u2208 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 \u2192 parse (tk \":\" *> small_nat)? \u2192 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 \u2295 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 \u2260 @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 \u2260 @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) \u2260 (2 : fin 3), dec_trivial,\n  exact zero_ne_two imposs,\nend\n\nprivate lemma H_neq_R {N : Type} :  H \u2260 @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) \u2260 (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 \u2192 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 (\u03bb 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 : \u2200 w\u1d62 \u2208 w.reverse, grammar_generates g w\u1d62) :\n  grammar_derives (star_grammar g) [Z] (Z ::\n      list.join (list.map (++ [H]) (list.map (list.map symbol.terminal) w.reverse))\n    )  \u2227\n  \u2200 p \u2208 w, \u2200 t \u2208 p, symbol.terminal t \u2208 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\u1d62 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 \u27e8rin, n, nrn\u27e9,\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 \u2208 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 \u27e8r\u2080, rin\u2080, r_of_r\u2080\u27e9,\n            use r\u2080,\n            split,\n            {\n              exact rin\u2080,\n            },\n            convert r_of_r\u2080,\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 \u27e8t, tin, r_of_tg\u27e9,\n            rw \u2190r_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 \u2190list.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 \u2208 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 \u27e8r, rin, stirn\u27e9,\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 : \u2115) (n_lt_wl : n \u2264 w.length)\n    (terminals : \u2200 v \u2208 w, \u2200 t \u2208 v, symbol.terminal t \u2208 list.join (list.map grule.output_string g.rules)) :\n  grammar_derives (star_grammar g)\n    ((list.map (\u03bb u, list.map symbol.terminal u) (list.take (w.length - n) w)).join ++ [R] ++\n      (list.map (\u03bb 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 \u2190list.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 \u2190list.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, \u2190list.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, \u2190list.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 : \u2200 m : \u2115, m \u2264 (w.nth_le (w.length - k.succ) lt_wl).length \u2192\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 \u2190list.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 \u27e8[], (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]\u27e9,\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 \u2190list.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 \u2190list.map_take,\n        rw list_take_one_drop,\n        rw list.map_singleton,\n      },\n      {\n        rw \u2190list.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 : \u2200 v \u2208 w, \u2200 t \u2208 v, symbol.terminal t \u2208 list.join (list.map grule.output_string g.rules)) :\n  grammar_derives (star_grammar g)\n    ([R] ++ (list.map (\u03bb 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 : \u2115} (not_pos : \u00ac (n \u2265 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 {\u03b1 : Type*} {l : list \u03b1} (lnn : l \u2260 []) :  l.length \u2265 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 : \u2115} (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 \u2260 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 \u2260 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 \u2260 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 \u2260 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) \u2209 list.map wrap_sym l  :=\nbegin\n  intro contra,\n  rw list.mem_map at contra,\n  rcases contra with \u27e8s, -, imposs\u27e9,\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 \u2209 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 \u2209 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 \u2209 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 (\u03bb 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\u2099,\n  {\n    cases y.nth n with y\u2099,\n    {\n      refl,\n    },\n    {\n      exfalso,\n      exact option.no_confusion eqnth,\n    },\n  },\n  {\n    cases y.nth n with y\u2099,\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 \u2209 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) \u2260 @H T g.nt) :\n  symbol.nonterminal (sum.inr i) \u2209 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 \u27e8l, l_in, in_l\u27e9,\n  rw list.mem_map at l_in,\n  rcases l_in with \u27e8y, -, eq_l\u27e9,\n  rw \u2190eq_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 \u2209 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 \u2209 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\u2080 : grule T g.nt}\n    {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)} (xnn : x \u2260 [])\n    (hyp : (list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))) =\n      u ++ list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++\n        list.map wrap_sym r\u2080.input_R ++ v) :\n  \u2203 m : \u2115, \u2203 u\u2081 v\u2081 : 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\u2081\n    \u2227  list.nth x m = some (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)  \u2227\n    v = list.map wrap_sym v\u2081 ++ [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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.input_R\n    ) ++ v,\n  {\n    simpa [list.append_assoc] using hyp,\n  },\n  have mid_brack : \u2200 u', \u2200 v',\n    u' ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v' =\n    u' ++ (r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.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 (\u03bb 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 \u27e8m, k, mlt, klt, init_ul\u27e9,\n\n  have vnn : v \u2260 [],\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 (\u03bb 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\u2080.input_R).reverse ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ (list.map wrap_sym r\u2080.input_L).reverse ++ u.reverse).nth 0,\n    {\n      convert hlast,\n      rw list.map_map,\n      change some H = (list.map (\u03bb 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 (\u03bb l, [H].reverse ++ (list.map wrap_sym l).reverse) x).reverse.join.nth 0,\n      rw \u2190list.map_reverse,\n      have xrnn : x.reverse \u2260 [],\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 \u2190list.map_reverse at hhh,\n    cases r\u2080.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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.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 \u27e8m', k', mlt', klt', last_vl\u27e9,\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 \u22a2,\n    iterate 2 {\n      swap, {\n        exact mxl,\n      },\n    },\n    rw list.length_map at klt \u22a2,\n    rw nat.lt_succ_iff at klt,\n    exact klt,\n  },\n  rw \u2190hyp_u at count_Hs,\n\n  have hyp_v :=\n    congr_arg (list.drop (list.length (u ++ (\n        list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.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' \u22a2,\n    iterate 2 {\n      swap, {\n        exact mxl',\n      },\n    },\n    rw list.length_map at klt' \u22a2,\n    rw nat.lt_succ_iff at klt',\n    exact klt',\n  },\n  rw \u2190hyp_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, \u2190list.map_take, list.map_map,\n      list.count_in_join, \u2190list.map_drop, list.map_map\n    ] at count_Hs,\n    change\n      (list.map (\u03bb w, list.count_in (list.map wrap_sym w ++ [H]) H) x).sum =\n      (list.map (\u03bb w, list.count_in (list.map wrap_sym w ++ [H]) H) (list.take m x)).sum + _ +\n        (_ + (list.map (\u03bb 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 : \u2200 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 : \u2200 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 \u2190list.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 \u2190list.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, \u2190add_assoc, \u2190nat.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 \u2190mm 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 [\u2190hyp_u, \u2190hyp_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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.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    \u2190list.append_assoc, \u2190list.append_assoc, \u2190list.append_assoc, \u2190list.append_assoc, \u2190list.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 \u2190list.append_assoc,\n  rw \u2190list.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\u2080 : 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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++\n        list.map wrap_sym r\u2080.input_R ++ v) :\n  \u2203 m : \u2115, \u2203 u\u2081 v\u2081 : 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\u2081\n    \u2227  list.nth x m = some (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)  \u2227\n    v = list.map wrap_sym v\u2081 ++ [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\u2080.input_L = [],\n    {\n      rw \u2190list.length_eq_zero,\n      rw list.length_append,\n      omega,\n    },\n    have right_nil : list.map wrap_sym r\u2080.input_R ++ v = [],\n    {\n      rw \u2190list.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 \u2260 [],\n  {\n    by_contradiction u_nil,\n    rw [u_nil, list.nil_append] at hyp,\n    cases r\u2080.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 \u2190list.append_assoc at hypr,\n  },\n  rcases cases_1_and_2_and_3a_match_aux is_x_nil hypr with \u27e8m, u\u2081, v\u2081, u_eq, xm_eq, v_eq\u27e9,\n  use [m, u\u2081, v\u2081],\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} {\u03b1 \u03b1' : list (ns T g.nt)}\n    (orig : grammar_transforms (star_grammar g) \u03b1 \u03b1')\n    (hyp : \u2203 x : list (list (symbol T g.nt)),\n      (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n      (\u03b1 = [Z] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :\n  (\u2203 x : list (list (symbol T g.nt)),\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1' = [Z] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 x : list (list (symbol T g.nt)),\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1' = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  :=\nbegin\n  rcases hyp with \u27e8x, valid, cat\u27e9,\n  have no_R_in_alpha : R \u2209 \u03b1,\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 \u27e8r, rin, u, v, bef, aft\u27e9,\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\u1d62 xin,\n      cases xin,\n      {\n        rw xin,\n        apply grammar_deri_self,\n      },\n      {\n        exact valid x\u1d62 xin,\n      },\n    },\n    have u_nil : u = [],\n    {\n      clear_except bef,\n      rw \u2190list.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 \u2208 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 \u2190bef_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 \u2190list.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 \u2208 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 \u2190bef_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 \u2208 rules_that_scan_terminals g \u2228 r \u2208 list.map wrap_gr g.rules,\n  {\n    rw or_comm,\n    rwa \u2190list.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 \u27e8t, -, form\u27e9,\n    rw \u2190form,\n    refl,\n  },\n  left,\n  rw list.mem_map at rin',\n  rcases rin' with \u27e8r\u2080, orig_in, wrap_orig\u27e9,\n  unfold wrap_gr at wrap_orig,\n  rw \u2190wrap_orig at *,\n  clear wrap_orig,\n  dsimp only at *,\n  rcases case_1_match_rule bef with \u27e8m, u\u2081, v\u2081, u_eq, xm_eq, v_eq\u27e9,\n  clear bef,\n  rw [u_eq, v_eq] at aft,\n  use (list.take m x ++ [u\u2081 ++ r\u2080.output_string ++ v\u2081] ++ list.drop m.succ x),\n  split,\n  {\n    intros x\u1d62 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\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)\n        (u\u2081 ++ r\u2080.output_string ++ v\u2081),\n    {\n      use r\u2080,\n      split,\n      {\n        exact orig_in,\n      },\n      use [u\u2081, v\u2081],\n      split;\n      refl,\n    },\n    apply grammar_deri_of_deri_tran _ last_step,\n    apply valid (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081),\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 \u2190list.map_take,\n  },\n  repeat {\n    rw \u2190list.append_assoc,\n  },\n  apply congr_arg2,\n  swap, {\n    rw \u2190list.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 = []  \u2227  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 \u2190list.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 (\u03bb 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\u2080 : 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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++\n        list.map wrap_sym r\u2080.input_R ++ v) :\n  \u2203 m : \u2115, \u2203 u\u2081 v\u2081 : 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\u2081\n    \u2227  list.nth x m = some (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)  \u2227\n    v = list.map wrap_sym v\u2081 ++ [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\u2080.input_N) = R \u2228 symbol.nonterminal (sum.inl r\u2080.input_N) = H,\n    {\n      simpa using congr_arg (\u03bb l, symbol.nonterminal (sum.inl r\u2080.input_N) \u2208 l) hyp,\n    },\n    cases imposs;\n    exact sum.no_confusion (symbol.nonterminal.inj imposs),\n  },\n  have unn : u \u2260 [],\n  {\n    by_contradiction u_nil,\n    rw [u_nil, list.nil_append] at hyp,\n    cases r\u2080.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 \u2260 [],\n  {\n    by_contradiction ut_nil,\n    rw [ut_nil, list.nil_append] at hypt,\n    cases r\u2080.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 \u2190list.append_assoc at hyptt,\n  },\n  rcases cases_1_and_2_and_3a_match_aux is_x_nil hyptt with \u27e8m, u\u2081, v\u2081, u_eq, xm_eq, v_eq\u27e9,\n  use [m, u\u2081, v\u2081],\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} {\u03b1 \u03b1' : list (symbol T (star_grammar g).nt)}\n    (orig : grammar_transforms (star_grammar g) \u03b1 \u03b1')\n    (hyp : \u2203 x : list (list (symbol T g.nt)),\n      (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n      (\u03b1 = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :\n  (\u2203 x : list (list (symbol T g.nt)),\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1' = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 w : list (list T), \u2203 \u03b2 : list T, \u2203 \u03b3 : list (symbol T g.nt), \u2203 x : list (list (symbol T g.nt)),\n    (\u2200 w\u1d62 \u2208 w, grammar_generates g w\u1d62) \u2227\n    (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal \u03b2 ++ \u03b3)) \u2227\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1' = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++ [R] ++\n      list.map wrap_sym \u03b3 ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 u : list T, u \u2208 language.star (grammar_language g) \u2227 \u03b1' = list.map symbol.terminal u)  \u2228\n  (\u2203 \u03c3 : list (symbol T g.nt), \u03b1' = list.map wrap_sym \u03c3 ++ [R])  \u2228\n  (\u2203 \u03c9 : list (ns T g.nt), \u03b1' = \u03c9 ++ [H]) \u2227 Z \u2209 \u03b1' \u2227 R \u2209 \u03b1'  :=\nbegin\n  rcases hyp with \u27e8x, valid, cat\u27e9,\n  have no_Z_in_alpha : Z \u2209 \u03b1,\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 \u2190list.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 \u27e8r, rin, u, v, bef, aft\u27e9,\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\u2080 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 = [] \u2227 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\u2080, L],\n      split,\n      {\n        intros w\u1d62 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\u2080 (list.mem_cons_self x\u2080 L),\n      },\n      split,\n      {\n        intros x\u1d62 xiin,\n        exact valid x\u1d62 (list.mem_cons_of_mem x\u2080 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 \u22a2,\n      dsimp only at bef \u22a2,\n      have u_nil := u_nil_when_RH bef,\n      rw [u_nil, list.nil_append] at bef \u22a2,\n      have eq_v := list.append_inj_right bef (by refl),\n      rw \u2190eq_v,\n      rw [list.map_cons, list.map_cons, list.join],\n      rw [\u2190list.append_assoc, \u2190list.append_assoc],\n    },\n  },\n  cases rin,\n  {\n    cases x with x\u2080 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 = [] \u2227 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, \u2190list.append_assoc\n      ] at aft,\n      split,\n      {\n        use list.map wrap_sym x\u2080 ++ (list.map (\u03bb l, [H] ++ l) (list.map (list.map wrap_sym) L)).join,\n        rw aft,\n        trim,\n      },\n      rw [list.append_assoc, \u2190list.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 \u2208 rules_that_scan_terminals g \u2228 r \u2208 list.map wrap_gr g.rules,\n  {\n    rw or_comm,\n    rwa \u2190list.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 \u27e8t, -, form\u27e9,\n    rw \u2190form 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 (\u03bb l, R \u2208 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 \u27e8p, pin, Rinp\u27e9,\n        rw list.mem_map at pin,\n        rcases pin with \u27e8q, qin, eq_p\u27e9,\n        rw \u2190eq_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 \u27e8p', -, eq_q\u27e9,\n          rw \u2190eq_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 \u27e8r\u2080, orig_in, wrap_orig\u27e9,\n  unfold wrap_gr at wrap_orig,\n  rw \u2190wrap_orig at *,\n  clear wrap_orig,\n  dsimp only at bef,\n  rcases case_2_match_rule  bef with \u27e8m, u\u2081, v\u2081, u_eq, xm_eq, v_eq\u27e9,\n  clear bef,\n  rw [u_eq, v_eq] at aft,\n  use (list.take m x ++ [u\u2081 ++ r\u2080.output_string ++ v\u2081] ++ list.drop m.succ x),\n  split,\n  {\n    intros x\u1d62 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\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)\n        (u\u2081 ++ r\u2080.output_string ++ v\u2081),\n    {\n      use r\u2080,\n      split,\n      {\n        exact orig_in,\n      },\n      use [u\u2081, v\u2081],\n      split;\n      refl,\n    },\n    apply grammar_deri_of_deri_tran _ last_step,\n    apply valid (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081),\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 \u2190list.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)} {\u03b2 : list T} {i : fin 3} :\n  @symbol.nonterminal T (nn g.nt) (sum.inr i) \u2209\n    list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map (@symbol.terminal T (nn g.nt)) \u03b2  :=\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 \u27e8t, -, imposs\u27e9,\n    exact symbol.no_confusion imposs,\n  },\nend\n\nprivate lemma case_3_ni_u {g : grammar T}\n    {w : list (list T)} {\u03b2 : list T} {\u03b3 : 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 \u03b2 ++ [R] ++ list.map wrap_sym \u03b3 ++ [H] ++\n        (list.map (++ [H]) (list.map (list.map wrap_sym) x)).join =\n      u ++ [R] ++ [s] ++ v\n    ) :\n  R \u2209 u  :=\nbegin\n  intro R_in_u,\n  classical,\n  have count_R := congr_arg (\u03bb 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 \u2209 list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2,\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 \u2190list.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)} {\u03b2 : list T} {\u03b3 : 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 \u03b2 ++ [R] ++ list.map wrap_sym \u03b3 ++ [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)) \u03b2  :=\nbegin\n  have R_ni_u : R \u2209 u,\n  {\n    exact case_3_ni_u ass,\n  },\n  have R_ni_wb : R \u2209 list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2,\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 \u2190list.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 [\u2190R, list.index_of_cons_self, add_zero] at index_of_first_R,\n    rw [\u2190list.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)} {\u03b2 : list T} {\u03b3 : 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 \u03b2 ++ [symbol.nonterminal (sum.inr 2)] ++\n        list.map wrap_sym \u03b3 ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) =\n      u ++ [symbol.nonterminal (sum.inr 2)] ++ [H] ++ v\n    ) :\n  \u03b3 = []  :=\nbegin\n  have R_ni_wb : R \u2209 list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2,\n  {\n    apply @case_3_ni_wb T g,\n  },\n  have H_ni_wb : H \u2209 list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2,\n  {\n    apply @case_3_ni_wb T g,\n  },\n  have H_ni_wbrg : H \u2209\n    list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal \u03b2 ++\n      [symbol.nonterminal (sum.inr 2)] ++ list.map wrap_sym \u03b3,\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) \u2209 u,\n  {\n    exact case_3_ni_u ass,\n  },\n  have H_ni_u : H \u2209 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 \u03b2) at first_R,\n  },\n  rw list.append_assoc\n    (list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2 ++\n      [symbol.nonterminal (sum.inr 2)] ++ list.map wrap_sym \u03b3)\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, \u2190R, 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 \u2190first_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 \u2190add_zero ((list.map symbol.terminal w.join).length + (list.map symbol.terminal \u03b2).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)} {\u03b2 : list T} {u v : list (ns T g.nt)}\n    (ass :\n      list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2 ++ [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 \u2190list.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 \u03b2).reverse ++ (list.map symbol.terminal w.join).reverse =\n      [symbol.nonterminal (sum.inr 2)] ++ u.reverse\n    at brtt,\n    have imposs := congr_arg (\u03bb a, R \u2208 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 (\u03bb a, H \u2208 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\u2080 : grule T g.nt}\n    {w : list (list T)} {\u03b2 : list T} {u z : list (ns T g.nt)}\n    (contradictory_equality :\n      list.map symbol.terminal w.join ++ list.map symbol.terminal \u03b2 ++ [R] =\n      u ++ list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ z) :\n  false :=\nbegin\n  apply false_of_true_eq_false,\n  convert congr_arg ((\u2208) (symbol.nonterminal (sum.inl r\u2080.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 \u27e8t, -, impos\u27e9,\n      exact symbol.no_confusion impos,\n    },\n  },\nend\n\nprivate lemma case_3_match_rule {g : grammar T} {r\u2080 : grule T g.nt}\n    {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)}\n    {w : list (list T)} {\u03b2 : list T} {\u03b3 : list (symbol T g.nt)}\n    (hyp :\n      list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++ [R] ++\n        list.map wrap_sym \u03b3 ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) =\n      u ++ list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++\n        list.map wrap_sym r\u2080.input_R ++ v) :\n  (\u2203 m : \u2115, \u2203 u\u2081 v\u2081 : list (symbol T g.nt),\n    u = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++\n        [R] ++ list.map wrap_sym \u03b3 ++ [H] ++\n        list.join (list.map (++ [H]) (list.take m (list.map (list.map wrap_sym) x))) ++ list.map wrap_sym u\u2081\n    \u2227  list.nth x m = some (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)  \u2227\n    v = list.map wrap_sym v\u2081 ++ [H] ++\n        list.join (list.map (++ [H]) (list.drop m.succ (list.map (list.map wrap_sym) x)))) \u2228\n  (\u2203 u\u2081 v\u2081 : list (symbol T g.nt),\n    u = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++ [R] ++ list.map wrap_sym u\u2081\n    \u2227  \u03b3 = u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081  \u2227\n    v = list.map wrap_sym v\u2081 ++ [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 \u27e8u', u_eq, xj_eq\u27e9,\n    left,\n    repeat {\n      rw \u2190list.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 \u27e8m, u\u2081, v\u2081, u'_eq, xm_eq, v_eq\u27e9,\n    use [m, u\u2081, v\u2081],\n    split,\n    {\n      rw u_eq,\n      rw u'_eq,\n      rw \u2190list.append_assoc,\n    },\n    split,\n    {\n      exact xm_eq,\n    },\n    {\n      exact v_eq,\n    },\n  },\n  {\n    rcases hyp with \u27e8v', left_half, right_half\u27e9,\n    have very_middle :\n      [symbol.nonterminal (sum.inl r\u2080.input_N)] = list.map wrap_sym [symbol.nonterminal r\u2080.input_N],\n    {\n      rw list.map_singleton,\n      refl,\n    },\n    cases x with x\u2080 x\u2097,\n    {\n      rw [list.map_nil, list.map_nil, list.join, list.append_nil] at right_half,\n      rw \u2190right_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 \u2190list.reverse_reverse v,\n      cases v.reverse with e z,\n      {\n        exfalso,\n        rw list.nil_append at backwards,\n        rw \u2190list.map_reverse _ r\u2080.input_R at backwards,\n        cases r\u2080.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\u2080.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 \u2190He 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 \u2190list.append_assoc at forward,\n      rw list.append_eq_append_iff at forward,\n      cases forward,\n      swap, {\n        exfalso,\n        rcases forward with \u27e8a, imposs, -\u27e9,\n        rw list.append_assoc u at imposs,\n        rw list.append_assoc _ (list.map wrap_sym r\u2080.input_R) at imposs,\n        rw \u2190list.append_assoc u at imposs,\n        rw \u2190list.append_assoc u at imposs,\n        exact case_3_false_of_wbr_eq_urz imposs,\n      },\n      rcases forward with \u27e8a', left_side, gamma_is\u27e9,\n      repeat {\n        rw \u2190list.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 \u27e8a, imposs, -\u27e9,\n        exact case_3_false_of_wbr_eq_urz imposs,\n      },\n      rcases left_side with \u27e8c', the_left, the_a'\u27e9,\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 \u27e8a, -, imposs\u27e9,\n        apply false_of_true_eq_false,\n        convert congr_arg ((\u2208) 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 \u27e8u\u2080, u_eq, rule_side\u27e9,\n      rw u_eq at *,\n      clear u_eq u,\n      have zr_eq : z.reverse = list.drop (c' ++ list.map wrap_sym r\u2080.input_R).length (list.map wrap_sym \u03b3),\n      {\n        have gamma_suffix := congr_arg (list.drop (c' ++ list.map wrap_sym r\u2080.input_R).length) gamma_is,\n        rw list.drop_left at gamma_suffix,\n        exact gamma_suffix.symm,\n      },\n      cases u\u2080 with d l,\n      {\n        exfalso,\n        rw list.nil_append at rule_side,\n        cases r\u2080.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 \u2190Rd at *,\n      clear Rd d,\n      rw c'_eq at gamma_is,\n      use [list.take l.length \u03b3, list.drop (c' ++ list.map wrap_sym r\u2080.input_R).length \u03b3],\n      split,\n      {\n        rw \u2190list.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 \u2190list.append_assoc,\n      },\n      split,\n      {\n        rw c'_eq,\n        convert_to list.take l.length \u03b3 ++ list.drop l.length \u03b3 = _,\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, \u2190list.map_drop, \u2190list.map_drop] at gamma_minus_initial_l,\n        repeat {\n          rw \u2190list.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\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R).length x\u2080],\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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.input_R\n        ) =\n        list.length (r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R),\n      {\n        rw [very_middle, \u2190list.map_append_append],\n        apply list.length_map,\n      },\n      have len_r\u1d62_le_len_x\u2080 :\n        (r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R).length \u2264 (list.map wrap_sym x\u2080).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, \u2190list.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\u2080 =\n            list.take (r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R).length x\u2080 ++\n            list.drop (r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R).length x\u2080,\n        {\n          trim,\n          apply wrap_str_inj,\n          rw list.map_append_append,\n          have right_left :=\n            congr_arg (list.take (r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R).length) right_half,\n          rw list.take_left' lengths_trivi at right_left,\n          rw [\u2190very_middle, right_left],\n          rw list.append_assoc _ [H],\n          rw list.take_append_of_le_length len_r\u1d62_le_len_x\u2080,\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\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.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\u1d62_le_len_x\u2080,\n        rw list.map_drop,\n        rw list.append_assoc _ [H],\n        refl,\n      },\n    },\n    right,\n    obtain \u27e8z, v'_eq\u27e9 : \u2203 z,  v' =\n        list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.input_R ++ z,\n    {\n      obtain \u27e8v'', without_final_H\u27e9 : \u2203 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 \u27e8a', -, matters\u27e9,\n          use list.nil,\n          cases a' with d l,\n          {\n            rw list.nil_append at matters \u22a2,\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 \u27e8c', -, v_c'\u27e9,\n          exact \u27e8c', v_c'\u27e9,\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\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.input_R\n        ) \u2264\n        v''.length,\n      {\n        classical,\n        have first_H := congr_arg (list.index_of H) right_half,\n        rw [very_middle, \u2190list.map_append_append, list.index_of_append_of_notin map_wrap_never_contains_H] at first_H,\n        have H_not_in_v'' : H \u2209 v'',\n        {\n          rw [without_final_H, \u2190list.append_assoc] at left_half,\n          intro contra,\n          apply false_of_true_eq_false,\n          convert congr_arg ((\u2208) 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 \u27e8t, -, impos\u27e9,\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 \u27e8s, -, imposs\u27e9,\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, \u2190list.map_append_append],\n        exact nat.le.intro first_H,\n      },\n      obtain \u27e8n, key_prop'\u27e9 := 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 \u2190key_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 \u2190right_take,\n      repeat {\n        rw \u2190list.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 \u27e8u\u2081, v\u2081, gamma_parts, z_eq\u27e9 : \u2203 u\u2081, \u2203 v\u2081,\n      list.map wrap_sym \u03b3 =\n      list.map wrap_sym u\u2081 ++ (\n        list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++ list.map wrap_sym r\u2080.input_R\n      ) ++ list.map wrap_sym v\u2081  \u2227\n      z = list.map wrap_sym v\u2081 ++ [H],\n    {\n      repeat {\n        rw \u2190list.append_assoc at left_half,\n      },\n      rw list.append_assoc _ (list.map wrap_sym \u03b3) 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 \u27e8c', imposs, -\u27e9,\n        exact case_3_false_of_wbr_eq_urz imposs,\n      },\n      rcases left_half with \u27e8a', lhl, lhr\u27e9,\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 \u2190list.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 \u2190eq_d' at lhr,\n      clear eq_d' d',\n      rw \u2190list.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 \u27e8c'', imposs, -\u27e9,\n        rw list.reverse_singleton at imposs,\n        apply false_of_true_eq_false,\n        convert congr_arg ((\u2208) 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 \u27e8b', lhlr', lhll'\u27e9,\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 \u2190list.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\u2080.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 \u2190eq_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 \u03b3,\n      use list.drop (l''\n            ++ list.map wrap_sym r\u2080.input_L\n            ++ [symbol.nonterminal (sum.inl r\u2080.input_N)]\n            ++ list.map wrap_sym r\u2080.input_R\n          ).length \u03b3,\n      have z_expr :  z =\n        list.map wrap_sym (\n            list.drop (l''\n              ++ list.map wrap_sym r\u2080.input_L\n              ++ [symbol.nonterminal (sum.inl r\u2080.input_N)]\n              ++ list.map wrap_sym r\u2080.input_R\n            ).length \u03b3\n          ) ++ [H],\n      {\n        have lhdr :=\n          congr_arg\n            (list.drop (l''\n              ++ list.map wrap_sym r\u2080.input_L\n              ++ [symbol.nonterminal (sum.inl r\u2080.input_N)]\n              ++ list.map wrap_sym r\u2080.input_R\n            ).length) lhr,\n        rw list.drop_append_of_le_length at lhdr,\n        {\n          rw [list.map_drop, lhdr, \u2190list.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 \u2190list.map_reverse _ r\u2080.input_R at lhr',\n          cases r\u2080.input_R.reverse with d\u1d63 l\u1d63,\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 \u03b3 =\n        l'' ++ list.map wrap_sym r\u2080.input_L ++ [symbol.nonterminal (sum.inl r\u2080.input_N)] ++\n          (list.map wrap_sym r\u2080.input_R ++\n            (list.map wrap_sym\n              (list.drop (l''\n                ++ list.map wrap_sym r\u2080.input_L\n                ++ [symbol.nonterminal (sum.inl r\u2080.input_N)]\n                ++ list.map wrap_sym r\u2080.input_R\n              ).length \u03b3))),\n      {\n        repeat {\n          rw \u2190list.append_assoc at lhr,\n        },\n        repeat {\n          rw \u2190list.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\u2081, v\u2081],\n    split, swap, split,\n    {\n      apply wrap_str_inj,\n      rwa [\n        very_middle, \u2190list.map_append_append, \u2190list.map_append_append,\n        \u2190list.append_assoc, \u2190list.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\u2081) at left_half,\n    rw \u2190list.append_assoc _ (list.map wrap_sym u\u2081) 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\u2081).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 \u2190add_assoc at lh_len,\n    },\n    rwa add_left_inj at lh_len,\n  },\nend\n\nprivate lemma star_case_3 {g : grammar T} {\u03b1 \u03b1' : list (ns T g.nt)}\n    (orig : grammar_transforms (star_grammar g) \u03b1 \u03b1')\n    (hyp : \u2203 w : list (list T), \u2203 \u03b2 : list T, \u2203 \u03b3 : list (symbol T g.nt), \u2203 x : list (list (symbol T g.nt)),\n      (\u2200 w\u1d62 \u2208 w, grammar_generates g w\u1d62) \u2227\n      (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal \u03b2 ++ \u03b3)) \u2227\n      (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n      (\u03b1 = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++ [R] ++\n        list.map wrap_sym \u03b3 ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :\n  (\u2203 w : list (list T), \u2203 \u03b2 : list T, \u2203 \u03b3 : list (symbol T g.nt), \u2203 x : list (list (symbol T g.nt)),\n    (\u2200 w\u1d62 \u2208 w, grammar_generates g w\u1d62) \u2227\n    (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal \u03b2 ++ \u03b3)) \u2227\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1' = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++ [R] ++\n      list.map wrap_sym \u03b3 ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 u : list T, u \u2208 language.star (grammar_language g) \u2227 \u03b1' = list.map symbol.terminal u)  \u2228\n  (\u2203 \u03c3 : list (symbol T g.nt), \u03b1' = list.map wrap_sym \u03c3 ++ [R])  \u2228\n  (\u2203 \u03c9 : list (ns T g.nt), \u03b1' = \u03c9 ++ [H]) \u2227 Z \u2209 \u03b1' \u2227 R \u2209 \u03b1'  :=\nbegin\n  rcases hyp with \u27e8w, \u03b2, \u03b3, x, valid_w, valid_middle, valid_x, cat\u27e9,\n  have no_Z_in_alpha : Z \u2209 \u03b1,\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 \u27e8s, -, imposs\u27e9,\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 \u27e8r, rin, u, v, bef, aft\u27e9,\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\u2080 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 \u03b2,\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 \u2190bef_minus_RH,\n      rw [list.map_append, list.map_map, list.map_map],\n      refl,\n    },\n    {\n      left,\n      use [w ++ [\u03b2], x\u2080, L],\n      split,\n      {\n        intros w\u1d62 wiin,\n        rw list.mem_append at wiin,\n        cases wiin,\n        {\n          exact valid_w w\u1d62 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\u2080 (list.mem_cons_self x\u2080 L),\n      },\n      split,\n      {\n        intros x\u1d62 xiin,\n        exact valid_x x\u1d62 (list.mem_cons_of_mem x\u2080 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)) \u03b2,\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\u2080 :: 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 [\u2190list.append_assoc, \u2190list.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 \u2190list.reverse_reverse x at *,\n    cases x.reverse with x\u2098 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 ++ \u03b2,\n      split,\n      {\n        use w ++ [\u03b2],\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 \u2190bef_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 \u2209 list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal \u03b2,\n      {\n        apply case_3_ni_wb,\n      },\n      have R_ni_wb : R \u2209 list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal \u03b2,\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 \u03b2,\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\u2098]))),\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 \u03b2 ++\n            list.join (list.map (++ [H]) (list.map (list.map wrap_sym) L.reverse)) ++ list.map wrap_sym x\u2098,\n        rw [\n          list.map_append, list.map_append, list.join_append,\n          list.map_singleton, list.map_singleton, list.join_singleton,\n          \u2190list.append_assoc, \u2190list.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 \u2208 rules_that_scan_terminals g \u2228 r \u2208 list.map wrap_gr g.rules,\n  {\n    rw or_comm,\n    rwa \u2190list.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 \u27e8t, -, r_is\u27e9,\n    rw \u2190r_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 \u03b2,\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 \u03b3 ++ [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 \u2190list.append_assoc at almost,\n      exact almost.symm,\n    },\n    cases \u03b3 with a \u03b4,\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, \u03b2 ++ [t], \u03b4, 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 \u27e8r\u2080, orig_in, wrap_orig\u27e9,\n  unfold wrap_gr at wrap_orig,\n  rw \u2190wrap_orig at *,\n  clear wrap_orig,\n  cases case_3_match_rule bef,\n  {\n    rcases h with \u27e8m, u\u2081, v\u2081, u_eq, xm_eq, v_eq\u27e9,\n    clear bef,\n    dsimp only at aft,\n    rw [u_eq, v_eq] at aft,\n    use w,\n    use \u03b2,\n    use \u03b3,\n    use (list.take m x ++ [u\u2081 ++ r\u2080.output_string ++ v\u2081] ++ 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\u1d62 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\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081)\n            (u\u2081 ++ r\u2080.output_string ++ v\u2081),\n        {\n          use r\u2080,\n          split,\n          {\n            exact orig_in,\n          },\n          use [u\u2081, v\u2081],\n          split;\n          refl,\n        },\n        apply grammar_deri_of_deri_tran _ last_step,\n        apply valid_x (u\u2081 ++ r\u2080.input_L ++ [symbol.nonterminal r\u2080.input_N] ++ r\u2080.input_R ++ v\u2081),\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        \u2190list.map_take,\n        \u2190list.map_drop,\n        list.map_singleton,\n        list.map_singleton,\n        list.join_singleton,\n        list.map_append_append,\n        \u2190list.append_assoc,\n        \u2190list.append_assoc,\n        \u2190list.append_assoc\n      ],\n    },\n  },\n  {\n    rcases h with \u27e8u\u2081, v\u2081, u_eq, \u03b3_eq, v_eq\u27e9,\n    clear bef,\n    dsimp only at aft,\n    rw [u_eq, v_eq] at aft,\n    use w,\n    use \u03b2,\n    use u\u2081 ++ r\u2080.output_string ++ v\u2081,\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 \u03b3_eq,\n      use r\u2080,\n      split,\n      {\n        exact orig_in,\n      },\n      use [list.map symbol.terminal \u03b2 ++ u\u2081, v\u2081],\n      split,\n      repeat {\n        rw \u2190list.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} {\u03b1 \u03b1' : list (ns T g.nt)}\n    (orig : grammar_transforms (star_grammar g) \u03b1 \u03b1')\n    (hyp : \u2203 u : list T, u \u2208 (grammar_language g).star \u2227 \u03b1 = list.map symbol.terminal u) :\n  false :=\nbegin\n  rcases hyp with \u27e8w, -, alpha_of_w\u27e9,\n  rw alpha_of_w at orig,\n  rcases orig with \u27e8r, -, u, v, bef, -\u27e9,\n  simpa using congr_arg (\u03bb l, symbol.nonterminal r.input_N \u2208 l) bef,\nend\n\nprivate lemma star_case_5 {g : grammar T} {\u03b1 \u03b1' : list (ns T g.nt)}\n    (orig : grammar_transforms (star_grammar g) \u03b1 \u03b1')\n    (hyp : \u2203 \u03c3 : list (symbol T g.nt), \u03b1 = list.map wrap_sym \u03c3 ++ [R]) :\n  (\u2203 \u03c3 : list (symbol T g.nt), \u03b1' = list.map wrap_sym \u03c3 ++ [R])  :=\nbegin\n  rcases hyp with \u27e8w, ends_with_R\u27e9,\n  rcases orig with \u27e8r, rin, u, v, bef, aft\u27e9,\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 (\u03bb l, Z \u2208 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 \u2190list.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 (\u03bb l, H \u2208 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 \u2208 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 \u27e8r\u2080, -, r_of_r\u2080\u27e9,\n    rw list.append_eq_append_iff at bef,\n    cases bef,\n    {\n      rcases bef with \u27e8x, ur_eq, singleR\u27e9,\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 \u2190list.map_take at u_from_w,\n        rw u_from_w at aft,\n        rw \u2190r_of_r\u2080 at aft,\n        dsimp only [wrap_gr] at aft,\n        use list.take u.length w ++ r\u2080.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 \u2190r_of_r\u2080 at ru_eq,\n        dsimp only [wrap_gr, R] at ru_eq,\n        rw \u2190list.map_reverse at ru_eq,\n        cases r\u2080.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 \u27e8y, w_eq, v_eq\u27e9,\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\u2080.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 \u2190r_of_r\u2080,\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 \u27e8t, -, eq_r\u27e9,\n    rw \u2190eq_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 \u2190list.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 (\u03bb l, R \u2208 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} {\u03b1 \u03b1' : list (ns T g.nt)}\n    (orig : grammar_transforms (star_grammar g) \u03b1 \u03b1')\n    (hyp : (\u2203 \u03c9 : list (ns T g.nt), \u03b1 = \u03c9 ++ [H]) \u2227 Z \u2209 \u03b1 \u2227 R \u2209 \u03b1) :\n  (\u2203 \u03c9 : list (ns T g.nt), \u03b1' = \u03c9 ++ [H]) \u2227 Z \u2209 \u03b1' \u2227 R \u2209 \u03b1'  :=\nbegin\n  rcases hyp with \u27e8\u27e8w, ends_with_H\u27e9, no_Z, no_R\u27e9,\n  rcases orig with \u27e8r, rin, u, v, bef, aft\u27e9,\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 \u2208 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 \u27e8r\u2080, -, r_of_r\u2080\u27e9,\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 \u2190r_of_r\u2080 at contra,\n        unfold wrap_gr at contra,\n        rw list.mem_map at contra,\n        rcases contra with \u27e8s, -, imposs\u27e9,\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 \u2190r_of_r\u2080 at contra,\n        unfold wrap_gr at contra,\n        rw list.mem_map at contra,\n        rcases contra with \u27e8s, -, imposs\u27e9,\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 \u2265 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 \u2190r_of_r\u2080 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 \u2190list.map_reverse _ r\u2080.input_R at rev,\n      rw list.reverse_singleton at rev,\n      cases r\u2080.input_R.reverse with d l,\n      {\n        have H_eq_N : H = symbol.nonterminal (sum.inl r\u2080.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 \u27e8t, -, eq_r\u27e9,\n    rw \u2190eq_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} {\u03b1 : list (ns T g.nt)}\n    (ass : grammar_derives (star_grammar g) [Z] \u03b1) :\n  (\u2203 x : list (list (symbol T g.nt)),\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1 = [Z] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 x : list (list (symbol T g.nt)),\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1 = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 w : list (list T), \u2203 \u03b2 : list T, \u2203 \u03b3 : list (symbol T g.nt), \u2203 x : list (list (symbol T g.nt)),\n    (\u2200 w\u1d62 \u2208 w, grammar_generates g w\u1d62) \u2227\n    (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal \u03b2 ++ \u03b3)) \u2227\n    (\u2200 x\u1d62 \u2208 x, grammar_derives g [symbol.nonterminal g.initial] x\u1d62) \u2227\n    (\u03b1 = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal \u03b2 ++ [R] ++\n      list.map wrap_sym \u03b3 ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))))  \u2228\n  (\u2203 u : list T, u \u2208 language.star (grammar_language g) \u2227 \u03b1 = list.map symbol.terminal u)  \u2228\n  (\u2203 \u03c3 : list (symbol T g.nt), \u03b1 = list.map wrap_sym \u03c3 ++ [R])  \u2228\n  (\u2203 \u03c9 : list (ns T g.nt), \u03b1 = \u03c9 ++ [H]) \u2227 Z \u2209 \u03b1 \u2227 R \u2209 \u03b1  :=\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 \u2190or_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  \u2192  is_RE L.star  :=\nbegin\n  rintro \u27e8g, hg\u27e9,\n  use star_grammar g,\n\n  apply set.eq_of_subset_of_subset,\n  {\n    -- prove `L.star \u2287` 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 \u27e8x, -, contr\u27e9,\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 \u27e8x, -, contr\u27e9,\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 \u27e8\u03b1, \u03b2, \u03b3, x, -, -, -, contr\u27e9,\n      have output_contains_R : R \u2208 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 \u27e8t, -, terminal_eq_R\u27e9,\n      exact symbol.no_confusion terminal_eq_R,\n    },\n    cases result,\n    {\n      rcases result with \u27e8u, win, map_eq_map\u27e9,\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 \u2190list.map_injective_iff at st_inj,\n        exact st_inj map_eq_map,\n      },\n      rw [w_eq_u, \u2190hg],\n      exact win,\n    },\n    cases result,\n    {\n      exfalso,\n      cases result with \u03c3 contr,\n      have last_symbols := congr_fun (congr_arg list.nth (congr_arg list.reverse contr)) 0,\n      rw [\n        \u2190list.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 \u27e8\u27e8\u03c9, contr\u27e9, -\u27e9,\n      have last_symbols := congr_fun (congr_arg list.nth (congr_arg list.reverse contr)) 0,\n      rw [\n        \u2190list.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 \u2286` here\n    intros p ass,\n    unfold grammar_language,\n    rw language.star at ass,\n    rw set.mem_set_of_eq at \u22a2 ass,\n    rcases ass with \u27e8w, w_join, parts_in_L\u27e9,\n    let v := w.reverse,\n    have v_reverse : v.reverse = w,\n    {\n      apply list.reverse_reverse,\n    },\n    rw \u2190v_reverse at *,\n    rw w_join,\n    clear w_join p,\n    unfold grammar_generates,\n    rw \u2190hg 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 (\u03bb 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 \u2190list.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": "example : Id Nat := do\n  let mut x := 1\n  have x : Nat := 2\n  x\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/916.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.047425874692232355, "lm_q1q2_score": 0.016872935518419743}}
{"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\u2081 X\u2082 X\u2083 : C} (f : X\u2081 \u27f6 X\u2082) (g : X\u2082 \u27f6 X\u2083) [epi f]:\n  epi (f \u226b g) \u2194 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\u2081 X\u2082 X\u2083 : C} (f : X\u2081 \u27f6 X\u2082) (g : X\u2082 \u27f6 X\u2083) [is_iso g] :\n  epi (f \u226b g) \u2194 epi f :=\nbegin\n  split,\n  { introI,\n    exact \u27e8\u03bb Z h\u2081 h\u2082 eq, by simpa only [\u2190 cancel_epi (inv g), \u2190 cancel_epi (f \u226b g),\n      assoc, is_iso.hom_inv_id_assoc] using eq\u27e9, },\n  { introI,\n    apply epi_comp, },\nend\n\n@[simp]\nlemma category_theory.mono_comp_right_iff_mono {C : Type*} [category C]\n  {X\u2081 X\u2082 X\u2083 : C} (f : X\u2081 \u27f6 X\u2082) (g : X\u2082 \u27f6 X\u2083) [mono g] :\n  mono (f \u226b g) \u2194 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\u2081 X\u2082 X\u2083 : C} (f : X\u2081 \u27f6 X\u2082) (g : X\u2082 \u27f6 X\u2083) [is_iso f] :\n  mono (f \u226b g) \u2194 mono g :=\nbegin\n  split,\n  { introI,\n    exact \u27e8\u03bb Z h\u2081 h\u2082 eq, by simpa only [\u2190 cancel_mono (inv f), \u2190 cancel_mono (f \u226b g),\n      assoc, is_iso.inv_hom_id_assoc] using eq\u27e9, },\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\u2081 S\u2082 : short_complex C} (\u03c6 : S\u2081 \u27f6 S\u2082) (hf\u2081 : S\u2081.f = 0) (hg\u2081 : S\u2081.g = 0) (hf\u2082 : S\u2082.f = 0)\n  (c : kernel_fork S\u2082.g) (hc : is_limit c) :\n  homology_map_data \u03c6\n    (homology_data.of_zeros S\u2081 hf\u2081 hg\u2081)\n    (homology_data.of_limit_kernel_fork S\u2082 hf\u2082 c hc) :=\nbegin\n  let \u03b1 := hc.lift (kernel_fork.of_\u03b9 \u03c6.\u03c4\u2082 (by rw [\u03c6.comm\u2082\u2083, hg\u2081, zero_comp])),\n  have h\u03b1 : \u03b1 \u226b c.\u03b9 = \u03c6.\u03c4\u2082 := by simp only [fork.is_limit.lift_\u03b9', kernel_fork.\u03b9_of_\u03b9],\n  exact { left :=\n    { \u03c6K := \u03b1,\n      \u03c6H := \u03b1,\n      commf'' := by { dsimp, simp only [hf\u2081, left_homology_data.of_zeros_f',\n        zero_comp, left_homology_data.of_limit_kernel_fork_f', comp_zero], }, },\n    right :=\n    { \u03c6Q := \u03c6.\u03c4\u2082,\n      \u03c6H := \u03b1,\n      commg'' := by { dsimp, simp only [\u03c6.comm\u2082\u2083, 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\u2081 S\u2082 : short_complex C} (\u03c6 : S\u2081 \u27f6 S\u2082) [S\u2081.has_left_homology] [S\u2082.has_left_homology]\n  [is_iso \u03c6.\u03c4\u2082] [mono \u03c6.\u03c4\u2083] :\n  is_iso (cycles_map \u03c6) :=\nbegin\n  refine \u27e8\u27e8S\u2081.lift_cycles (S\u2082.cycles_i \u226b inv \u03c6.\u03c4\u2082) _, _, _\u27e9\u27e9,\n  { simp only [\u2190 cancel_mono \u03c6.\u03c4\u2083, assoc, \u2190 \u03c6.comm\u2082\u2083, is_iso.inv_hom_id_assoc, lift_cycles_i,\n      cycles_i_g, zero_comp], },\n  { simp only [\u2190 cancel_mono S\u2081.cycles_i, assoc, lift_cycles_i, cycles_map_i_assoc,\n      is_iso.hom_inv_id, comp_id, id_comp], },\n  { simp only [\u2190 cancel_mono S\u2082.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\u2081 S\u2082 : short_complex C} (\u03c6 : S\u2081 \u27f6 S\u2082) [S\u2081.has_right_homology] [S\u2082.has_right_homology]\n  [is_iso \u03c6.\u03c4\u2082] [epi \u03c6.\u03c4\u2081] :\n  is_iso (cycles_co_map \u03c6) :=\nbegin\n  refine \u27e8\u27e8S\u2082.desc_cycles_co (inv \u03c6.\u03c4\u2082 \u226b S\u2081.p_cycles_co) _, _ ,_\u27e9\u27e9,\n  { simp only [\u2190 cancel_epi \u03c6.\u03c4\u2081, \u03c6.comm\u2081\u2082_assoc, is_iso.hom_inv_id_assoc,\n      f_cycles_co_p, comp_zero], },\n  { simp only [\u2190cancel_epi S\u2081.p_cycles_co, is_iso.hom_inv_id_assoc,\n      p_cycles_co_map_assoc, p_desc_cycles_co, comp_id], },\n  { simp only [\u2190cancel_epi S\u2082.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\u2081 S\u2082 : short_complex C} (\u03c6 : S\u2081 \u27f6 S\u2082) [S\u2081.has_homology] [S\u2082.has_homology]\n  [mono \u03c6.\u03c4\u2082] [mono \u03c6.\u03c4\u2083] : mono (cycles_map \u03c6) :=\nbegin\n  simp only [\u2190 mono_comp_right_iff_mono _ S\u2082.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\u2081 S\u2082 : short_complex C} (\u03c6 : S\u2081 \u27f6 S\u2082) [S\u2081.has_homology] [S\u2082.has_homology]\n  [epi \u03c6.\u03c4\u2082] [epi \u03c6.\u03c4\u2081] : epi (cycles_co_map \u03c6) :=\nbegin\n  simp only [\u2190 epi_comp_left_iff_epi S\u2081.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\u2081 S\u2082 : short_complex C}\n  (\u03c6 : S\u2081 \u27f6 S\u2082) (hf\u2081 : S\u2081.f = 0) (hg\u2081 : S\u2081.g = 0) (hf\u2082 : S\u2082.f = 0) :\n  short_complex.quasi_iso \u03c6 \u2194\n    (mk \u03c6.\u03c4\u2082 S\u2082.g (by rw [\u03c6.comm\u2082\u2083, hg\u2081, zero_comp])).exact \u2227 mono \u03c6.\u03c4\u2082 :=\nbegin\n  rw [exact_iff_epi_to_cycles,\n    (homology_map_data.of_zeros_of_limit_kernel_fork \u03c6 hf\u2081 hg\u2081 hf\u2082\n    _ S\u2082.cycles_is_kernel).left.quasi_iso_iff,\n    homology_map_data.of_zeros_of_limit_kernel_fork_left_\u03c6H],\n  have w : \u03c6.\u03c4\u2082 \u226b S\u2082.g = 0 := by rw [\u03c6.comm\u2082\u2083, hg\u2081, zero_comp],\n  let S := mk \u03c6.\u03c4\u2082 S\u2082.g w,\n  change is_iso (S\u2082.lift_cycles \u03c6.\u03c4\u2082 w) \u2194 epi S.to_cycles \u2227 _,\n  let \u03b3 : S\u2082 \u27f6 S :=\n  { \u03c4\u2081 := 0,\n    \u03c4\u2082 := \ud835\udfd9 _,\n    \u03c4\u2083 := \ud835\udfd9 _,\n    comm\u2081\u2082' := by simp only [hf\u2082, zero_comp], },\n  have eq : S\u2082.lift_cycles \u03c6.\u03c4\u2082 w \u226b cycles_map \u03b3 = S.to_cycles,\n  { simp only [\u2190 cancel_mono S.cycles_i, comp_id, lift_cycles_comp_cycles_map,\n      lift_cycles_i, to_cycles_i], },\n  conv_rhs { rw \u2190 S\u2082.lift_cycles_i \u03c6.\u03c4\u2082 w, },\n  simp only [is_iso_iff_mono_and_epi, \u2190 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 : \u2124} (h : a+1=b)\n  [has_zero_morphisms C] [has_zero_object C] {A B : C} (\u03c6 : A \u27f6 B)\n\nnamespace double\n\ninclude h \u03c6\n@[nolint unused_arguments]\ndef X (n : \u2124) : C := if n = a then A else if n = b then B else 0\nomit h \u03c6\n\ndef X_iso\u2081 {n : \u2124} (hn : n = a) :\n  X h \u03c6 n \u2245 A :=\neq_to_iso (by { subst hn, dsimp [X], simp, })\n\ndef X_iso\u2082 {n : \u2124} (hn : n = b) :\n  X h \u03c6 n \u2245 B :=\neq_to_iso (begin\n  subst hn,\n  simp only [X, if_neg (show \u00acn=a, by linarith), eq_self_iff_true, if_true, ite_eq_right_iff],\nend)\n\nlemma X_is_zero (n : \u2124) (hn\u2081 : n \u2260 a) (hn\u2082 : n \u2260 b) :\n  is_zero (X h \u03c6 n) :=\nby simpa only [X, if_neg hn\u2081, if_neg hn\u2082] using is_zero_zero C\n\ndef d (i j : \u2124) :\n  X h \u03c6 i \u27f6 X h \u03c6 j :=\nbegin\n  by_cases hi : i = a,\n  { by_cases hj : j = b,\n    { exact (X_iso\u2081 h \u03c6 hi).hom \u226b \u03c6 \u226b (X_iso\u2082 h \u03c6 hj).inv, },\n    { exact 0, }, },\n  { exact 0, },\nend\n\nlemma d_eq' {i j : \u2124} (hi : i = a) (hj : j = b) :\n  double.d h \u03c6 i j = (X_iso\u2081 h \u03c6 hi).hom \u226b \u03c6 \u226b (X_iso\u2082 h \u03c6 hj).inv :=\nby simp only [d, dif_pos hi, dif_pos hj]\n\n@[simp]\nlemma d_eq :\n  double.d h \u03c6 a b = (X_iso\u2081 h \u03c6 rfl).hom \u226b \u03c6 \u226b (X_iso\u2082 h \u03c6 rfl).inv :=\nd_eq' _ _ rfl rfl\n\nlemma d_eq_zero\u2081 {i j : \u2124} (hi : i \u2260 a) :\n  double.d h \u03c6 i j = 0 :=\nby simp only [d, dif_neg hi]\n\nlemma d_eq_zero\u2082 {i j : \u2124} (hj : j \u2260 b) :\n  double.d h \u03c6 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\u2081 _ _ hi], },\nend\n\n@[simp, reassoc]\nlemma d_comp_d {i j k : \u2124} :\n  double.d h \u03c6 i j \u226b double.d h \u03c6 j k = 0 :=\nbegin\n  by_cases hi : i = a,\n  { by_cases hj : j = b,\n    { have hk : j \u2260 a := by linarith,\n      rw [d_eq_zero\u2081 _ _ hk, comp_zero], },\n    { simp only [d_eq_zero\u2082 _ _ hj, zero_comp], }, },\n  { simp only [d_eq_zero\u2081 _ _ hi, zero_comp], },\nend\n\nend double\n\n@[simps]\ndef double : cochain_complex C \u2124 :=\n{ X := double.X h \u03c6,\n  d := \u03bb i j, double.d h \u03c6 i j,\n  shape' := \u03bb i j hij, begin\n    change i+1 \u2260 j at hij,\n    by_cases hi : i = a,\n    { rw double.d_eq_zero\u2082,\n      exact \u03bb hj, hij (by linarith), },\n    { rw double.d_eq_zero\u2081 _ _ hi, },\n  end, }\n\nnamespace double\n\nsection desc\n\nvariables (K : cochain_complex C \u2124) (fa : A \u27f6 K.X a) (fb : B \u27f6 K.X b)\n  (comm : fa \u226b K.d a b = \u03c6 \u226b fb) {c : \u2124} (hc : b+1 = c)\n  (w : fb \u226b K.d b c = 0)\n\ninclude fa fb\n\ndef desc.f (n : \u2124) : (double h \u03c6).X n \u27f6 K.X n :=\nbegin\n  by_cases ha : n = a,\n  { exact (double.X_iso\u2081 h \u03c6 ha).hom \u226b fa \u226b eq_to_hom (by rw ha), },\n  { by_cases hb : n = b,\n    { exact (double.X_iso\u2082 h \u03c6 hb).hom \u226b fb \u226b eq_to_hom (by rw hb), },\n    { exact 0, }, },\nend\n\n@[simp]\nlemma desc.f\u2081 : desc.f h \u03c6 K fa fb a = (double.X_iso\u2081 h \u03c6 rfl).hom \u226b fa :=\nby simp only [desc.f, dif_pos rfl, eq_to_hom_refl, comp_id]\n\n@[simp]\nlemma desc.f\u2082 : desc.f h \u03c6 K fa fb b = (double.X_iso\u2082 h \u03c6 rfl).hom \u226b fb :=\nby simp only [desc.f, dif_neg (show b \u2260 a, by linarith), dif_pos rfl, eq_to_hom_refl, comp_id]\n\nlemma desc.f_eq_zero (n : \u2124) (ha : n \u2260 a) (hb : n \u2260 b) : desc.f h \u03c6 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 \u03c6 \u27f6 K :=\n{ f := desc.f h \u03c6 K fa fb,\n  comm' := \u03bb 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\u2081, assoc, double_d, d_eq, desc.f\u2082, iso.inv_hom_id_assoc,\n        iso.cancel_iso_hom_left, comm], },\n    { simp only [double_d, d_eq_zero\u2081 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\u2082, 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 \u2124) (fa : K.X a \u27f6 A) (fb : K.X b \u27f6 B)\n  (comm : fa \u226b \u03c6 = K.d a b \u226b fb) {c : \u2124} (hc : c+1 = a)\n  (w : K.d c a \u226b fa = 0)\n\ninclude fa fb\n\ndef lift.f (n : \u2124) : K.X n \u27f6 (double h \u03c6).X n :=\nbegin\n  by_cases ha : n = a,\n  { exact eq_to_hom (by rw ha) \u226b fa \u226b (double.X_iso\u2081 h \u03c6 ha).inv, },\n  { by_cases hb : n = b,\n    { exact eq_to_hom (by rw hb) \u226b fb \u226b (double.X_iso\u2082 h \u03c6 hb).inv, },\n    { exact 0, }, },\nend\n\n@[simp]\nlemma lift.f\u2081 : lift.f h \u03c6 K fa fb a = fa \u226b (double.X_iso\u2081 h \u03c6 rfl).inv :=\nby simp only [lift.f, dif_pos rfl, eq_to_hom_refl, id_comp]\n\n@[simp]\nlemma lift.f\u2082 : lift.f h \u03c6 K fa fb b = fb \u226b (double.X_iso\u2082 h \u03c6 rfl).inv :=\nby simp only [lift.f, dif_neg (show b \u2260 a, by linarith), dif_pos rfl, eq_to_hom_refl, id_comp]\n\nlemma lift.f_eq_zero (n : \u2124) (ha : n \u2260 a) (hb : n \u2260 b) : lift.f h \u03c6 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 \u27f6 double h \u03c6 :=\n{ f := lift.f h \u03c6 K fa fb,\n  comm' := \u03bb 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\u2081, double_d, d_eq, assoc, iso.inv_hom_id_assoc, lift.f\u2082,\n        iso.cancel_iso_inv_right_assoc, comm], },\n    { simp only [double_d, d_eq_zero\u2082 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\u2081, 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 (\u03c6) {A' B' : C} (\u03c6' : A' \u27f6 B') (\u03b1 : A \u27f6 A') (\u03b2 : B \u27f6 B') (comm : \u03c6 \u226b \u03b2 = \u03b1 \u226b \u03c6')\n\ninclude comm\n\ndef map : double h \u03c6 \u27f6 double h \u03c6' :=\ndouble.desc h \u03c6 _ (\u03b1 \u226b (double.X_iso\u2081 h \u03c6' rfl).inv)\n  (\u03b2  \u226b (double.X_iso\u2082 h \u03c6' rfl).inv) (by tidy) rfl\n  (is_zero.eq_of_tgt (double.X_is_zero h \u03c6' (b+1) (by linarith) (by linarith)) _ _)\n\n@[simp]\nlemma map_f\u2081 :\n  (map h \u03c6 \u03c6' \u03b1 \u03b2 comm).f a = (double.X_iso\u2081 h \u03c6 rfl).hom \u226b \u03b1 \u226b (double.X_iso\u2081 h \u03c6' rfl).inv :=\nby simp only [map, desc_f, desc.f\u2081]\n\n@[simp]\nlemma map_f\u2082 :\n  (map h \u03c6 \u03c6' \u03b1 \u03b2 comm).f b = (double.X_iso\u2082 h \u03c6 rfl).hom \u226b \u03b2 \u226b (double.X_iso\u2082 h \u03c6' rfl).inv :=\nby simp only [map, desc_f, desc.f\u2082]\n\nend map\n\nvariables {h \u03c6}\n\n@[ext]\nlemma ext {K : cochain_complex C \u2124} (f\u2081 f\u2082 : double h \u03c6 \u27f6 K)\n  (ha : f\u2081.f a = f\u2082.f a) (hb : f\u2081.f b = f\u2082.f b) : f\u2081 = f\u2082 :=\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 \u03c6 _ ha' hb', }, },\nend\n\n@[ext]\nlemma ext' {K : cochain_complex C \u2124} (f\u2081 f\u2082 : K \u27f6 double h \u03c6)\n  (ha : f\u2081.f a = f\u2082.f a) (hb : f\u2081.f b = f\u2082.f b) : f\u2081 = f\u2082 :=\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 \u03c6 _ ha' hb', }, },\nend\n\n@[simp, reassoc]\nlemma w_from {K : cochain_complex C \u2124} (f : double h \u03c6 \u27f6 K) (c : \u2124) :\n  f.f b \u226b K.d b c = 0 :=\nbegin\n  by_cases hc : b+1 = c,\n  { rw [f.comm b c, double_d, d_eq_zero\u2081 h \u03c6 (show b \u2260 a, by linarith), zero_comp], },\n  { rw [K.shape _ _ hc, comp_zero], },\nend\n\n@[simp, reassoc]\nlemma w_to {K : cochain_complex C \u2124} (f : K \u27f6 double h \u03c6) (c : \u2124) :\n  K.d c a \u226b f.f a = 0 :=\nbegin\n  by_cases hc : c+1 = a,\n  { rw [\u2190 f.comm c a, double_d, d_eq_zero\u2082 h \u03c6 (show a \u2260 b, by linarith), comp_zero], },\n  { rw [K.shape _ _ hc, zero_comp], },\nend\n\nvariables (h \u03c6)\n\n@[simps]\ndef \u03b9 : (homological_complex.single _ _ b).obj B \u27f6 double h \u03c6 :=\ndouble.lift h \u03c6 _ 0 (homological_complex.single_obj_X_self _ _ _ _).hom (by simp)\n  (sub_add_cancel a 1) (by simp)\n\n@[simps]\ndef \u03c0 : double h \u03c6 \u27f6 (homological_complex.single _ _ a).obj A :=\ndouble.desc h \u03c6 _ (homological_complex.single_obj_X_self _ _ _ _).inv 0 (by simp) rfl (by simp)\n\n@[simp, reassoc]\nlemma \u03b9_\u03c0 : \u03b9 h \u03c6 \u226b \u03c0 h \u03c6 = 0 :=\nbegin\n  ext n,\n  by_cases ha : n = a,\n  { subst ha,\n    simp only [homological_complex.comp_f, \u03b9_f, lift.f\u2081, 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 : \u2124} (h : a+1=b) {A B A' B' : C} {\u03c6 : A \u27f6 B} {\u03c6' : A' \u27f6 B'}\n\ndef homotopy_mk (f\u2081 f\u2082 : double h \u03c6 \u27f6 double h \u03c6') (\u03b3 : B \u27f6 A')\n  (h\u03b3\u2081 : f\u2081.f a = (double h \u03c6).d a b \u226b (X_iso\u2082 h \u03c6 rfl).hom \u226b\n    \u03b3 \u226b (X_iso\u2081 h \u03c6' rfl).inv + f\u2082.f a)\n  (h\u03b3\u2082 : f\u2081.f b = ((X_iso\u2082 h \u03c6 rfl).hom \u226b \u03b3 \u226b (X_iso\u2081 h \u03c6' rfl).inv) \u226b\n    (double h \u03c6').d a b + f\u2082.f b) :\n  homotopy f\u2081 f\u2082 :=\n{ hom := \u03bb i j, begin\n    by_cases hb : i = b,\n    { by_cases ha : j = a,\n      { exact (X_iso\u2082 h \u03c6 hb).hom \u226b \u03b3 \u226b (X_iso\u2081 h \u03c6' ha).inv, },\n      { exact 0,}, },\n    { exact 0, },\n  end,\n  zero' := \u03bb i j (hij : j+1 \u2260 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 := \u03bb i, begin\n    have h' : (complex_shape.up \u2124).rel a b := h,\n    by_cases ha : i = a,\n    { subst ha,\n      have h'' : (complex_shape.up \u2124).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 \u2260 b, by linarith), zero_comp, add_zero, h\u03b3\u2081], },\n    { by_cases hb : i = b,\n      { subst hb,\n        have h'' : (complex_shape.up \u2124).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\u03b3\u2082], },\n      { exact is_zero.eq_of_src (X_is_zero h \u03c6 i ha hb) _ _, }, },\n  end, }\n\n/-- should be moved -/\nlemma four_cases {a b : \u2124} (h : a+1=b) (n : \u2124) :\n  (n < a \u2228 b < n) \u2228 n = a \u2228 n = b :=\nbegin\n  by_cases h\u2081 : n < a,\n  { exact or.inl (or.inl h\u2081), },\n  { by_cases h\u2082 : b < n,\n    { exact or.inl (or.inr h\u2082), },\n    { refine or.inr _,\n      simp only [not_lt] at h\u2081 h\u2082,\n      cases h\u2081.lt_or_eq with h\u2083 h\u2083,\n      { cases h\u2082.lt_or_eq with h\u2084 h\u2084,\n        { exfalso,\n          linarith, },\n        { exact or.inr h\u2084, }, },\n      { exact or.inl h\u2083.symm, }, }, },\nend\n\nend double\n\nend preadditive\n\nsection abelian\n\nvariables {C : Type*} [category C] [abelian C] {a b : \u2124} (h : a+1=b) {A B E : C} (\u03c6 : A \u27f6 B)\n  {i : B \u27f6 E} {p : E \u27f6 A} (w : i \u226b p = 0)\n\ninstance double_strictly_le :\n  (double h \u03c6).is_strictly_le b :=\n\u27e8\u03bb n hn, double.X_is_zero h \u03c6 n (by linarith) (by linarith)\u27e9\n\ninstance double_strictly_ge :\n  (double h \u03c6).is_strictly_ge a :=\n\u27e8\u03bb n hn, double.X_is_zero h \u03c6 n (by linarith) (by linarith)\u27e9\n\ninclude h\n\nlemma double.is_le_iff_epi : (double h \u03c6).is_le a \u2194 epi \u03c6 :=\nbegin\n  rw [is_le_iff_of_is_le_next (double h \u03c6) h, \u2190 short_complex.exact_iff_is_zero_homology,\n    short_complex.exact_iff_epi],\n  { have ha : a = (complex_shape.up \u2124).prev b := by { rw prev, linarith, },\n    subst ha,\n    change epi (double.d _ _ _ _) \u2194 _,\n    rw double.d_eq,\n    split,\n    { intro h\u03c6,\n      haveI := @epi_of_epi _ _ _ _ _ _ _ h\u03c6,\n      have eq := \u03c6 \u226b= (double.X_iso\u2082 h \u03c6 rfl).inv_hom_id,\n      rw [comp_id, \u2190 assoc] at eq,\n      rw \u2190 eq,\n      apply epi_comp, },\n    { introI,\n      haveI := epi_comp \u03c6 (double.X_iso\u2082 h \u03c6 rfl).inv,\n      apply epi_comp, }, },\n  { apply is_zero.eq_of_tgt,\n    exact double.X_is_zero h \u03c6 _ (by { rw [next], linarith, })\n      (by simpa only [next] using succ_ne_self b), },\nend\n\ninstance double_le [epi \u03c6] :\n  (double h \u03c6).is_le a :=\nby { rw double.is_le_iff_epi, apply_instance, }\n\nlemma double.is_ge_iff_mono : (double h \u03c6).is_ge b \u2194 mono \u03c6 :=\nbegin\n  rw [is_ge_iff_of_is_ge_prev (double h \u03c6) h, \u2190 short_complex.exact_iff_is_zero_homology,\n    short_complex.exact_iff_mono],\n  { have hb : b = (complex_shape.up \u2124).next a := by rw [next, h],\n    subst hb,\n    change mono (double.d _ _ _ _) \u2194 _,\n    rw double.d_eq,\n    split,\n    { intro h\u03c6,\n      rw \u2190 assoc at h\u03c6,\n      haveI := @mono_of_mono _ _ _ _ _ _ _ h\u03c6,\n      have eq := (double.X_iso\u2081 h \u03c6 rfl).inv_hom_id =\u226b \u03c6,\n      rw [id_comp, assoc] at eq,\n      rw \u2190 eq,\n      apply mono_comp, },\n    { introI,\n      haveI := mono_comp \u03c6 (double.X_iso\u2082 h \u03c6 rfl).inv,\n      apply mono_comp, }, },\n  { apply is_zero.eq_of_src,\n    exact double.X_is_zero h \u03c6 _ (by simpa only [prev] using pred_ne_self a)\n      (by { rw [prev], linarith, }), },\nend\n\ninstance double_ge [mono \u03c6] :\n  (double h \u03c6).is_ge b :=\nby { rw double.is_ge_iff_mono, apply_instance, }\n\ninclude w\n\ndef double.\u03c3 : (double h i) \u27f6 (homological_complex.single _ (complex_shape.up \u2124) b).obj A :=\nlift_single _ _ ((double.X_iso\u2082 h i rfl).hom \u226b p \u226b\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.\u03c3_f\u2081 : (double.\u03c3 h w).f a = 0 :=\nbegin\n  dsimp [double.\u03c3, lift_single],\n  rw dif_neg (show \u00ac a=b, by linarith),\nend\n\n@[simp]\nlemma double.\u03c3_f\u2082 :\n  (double.\u03c3 h w).f b = (double.X_iso\u2082 h i rfl).hom \u226b p\n    \u226b (homological_complex.single_obj_X_self C (complex_shape.up \u2124) b A).inv :=\nbegin\n  dsimp only [double.\u03c3, lift_single],\n  rw dif_pos rfl,\nend\n\ndef double.\u03c3' : (homological_complex.single _ (complex_shape.up \u2124) a).obj B \u27f6\n  double h p :=\nbegin\n  refine desc_single _ _ ((homological_complex.single_obj_X_self _ _ _ B).hom \u226b i \u226b\n    (double.X_iso\u2081 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_\u03c0\u03c3'_\u03c3\u03b9 : homotopy (double.\u03c0 h i \u226b double.\u03c3' h w)\n  (-double.\u03c3 h w \u226b double.\u03b9 h p) :=\ndouble.homotopy_mk _ _ _ (\ud835\udfd9 _)\n  (by { dsimp, simp [double.\u03c0, double.\u03c3', double.\u03b9], })\n  (by { dsimp, simp [double.\u03c0, double.\u03c3, double.\u03b9], })\n\nlemma double.quasi_iso_\u03c3' (ex : (short_complex.mk _ _ w).short_exact) :\n  quasi_iso (double.\u03c3' h w) :=\nbegin\n  have hb : b = (complex_shape.up \u2124).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.\u03c3' h w) a,\n  apply short_complex.quasi_iso.of_kernel_fork _ _ _,\n  { refine \u27e8\u03bb Z f\u2081 f\u2082 eq, is_zero.eq_of_src _ _ _\u27e9,\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 \u2245\n      parallel_pair (((double h) p).sc' a).g 0 :=\n      parallel_pair.ext (double.X_iso\u2081 h p rfl).symm\n        ((double.X_iso\u2082 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 \u2124) a B).symm _,\n    dsimp only [cones.postcompose, fork.\u03b9],\n    dsimp [e, double.\u03c3'],\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_\u03c3 (ex : (short_complex.mk _ _ w).short_exact) :\n  quasi_iso (double.\u03c3 h w) :=\nbegin\n  have ha : a = (complex_shape.up \u2124).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.\u03c3 h w) b,\n  apply short_complex.quasi_iso.of_cokernel_cofork _ _ _,\n  { refine \u27e8\u03bb Z f\u2081 f\u2082 eq, is_zero.eq_of_tgt _ _ _\u27e9,\n    refine double.X_is_zero h i _\n      (by { rw [next, prev], linarith, })\n      (by { rw [next], linarith, }), },\n  { refl, },\n  { dsimp [double.\u03c3],\n    let e : parallel_pair i 0 \u2245\n      parallel_pair (((double h) i).sc' b).f 0 :=\n      parallel_pair.ext (double.X_iso\u2081 h i rfl).symm (double.X_iso\u2082 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 \u2124) b A).symm _,\n    dsimp only [cocones.precompose, cofork.\u03c0],\n    dsimp [e, double.\u03c3],\n    simp only [lift_single_f, iso.inv_hom_id_assoc], },\nend\n\nlemma double.is_iso_iff {K L : cochain_complex C \u2124} [K.is_strictly_le b] [K.is_strictly_ge a]\n  [L.is_strictly_le b] [L.is_strictly_ge a] (\u03c6 : K \u27f6 L) :\n  is_iso \u03c6 \u2194 (is_iso (\u03c6.f a) \u2227 is_iso (\u03c6.f b)) :=\nbegin\n  split,\n  { introI,\n    split; exact (infer_instance : is_iso ((homological_complex.eval _ _ _).map \u03c6)), },\n  { intro h\u03c6,\n    haveI : \u2200 (n : \u2124), is_iso (\u03c6.f n),\n    { intro n,\n      rcases double.four_cases h n with \u27e8h' | h'\u27e9 | \u27e8h' | h'\u27e9,\n      { refine \u27e8\u27e80, (is_strictly_ge.is_zero K a _ h').eq_of_src _ _,\n          (is_strictly_ge.is_zero L a _ h').eq_of_src _ _\u27e9\u27e9, },\n      { refine \u27e8\u27e80, (is_strictly_le.is_zero K b _ h').eq_of_src _ _,\n          (is_strictly_le.is_zero L b _ h').eq_of_src _ _\u27e9\u27e9, },\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 \u2124) [K.is_strictly_le b] [K.is_strictly_ge a] :\n  \u2203 (A B : C) (\u03c6 : A \u27f6 B), nonempty (K \u2245 double h \u03c6) :=\nbegin\n  let \u03b1 := double.lift h (K.d a b) K (\ud835\udfd9 _) (\ud835\udfd9 _) (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 \u03b1,\n  { simp only [double.is_iso_iff h \u03b1, id_comp, double.lift_f, double.lift.f\u2081, double.lift.f\u2082],\n    split; apply_instance, },\n  exact \u27e8_, _, K.d a b, \u27e8as_iso \u03b1\u27e9\u27e9,\nend\n\nvariables {X\u2081 X\u2082 X\u2083 : C}\n\n@[simp]\ndef single_to_double (i : X\u2081 \u27f6 X\u2082) (p : X\u2082 \u27f6 X\u2083) (w : i \u226b p = 0) :\n  ((homological_complex.single C _ a).obj X\u2081) \u27f6 double h p :=\ndesc_single _ _  ((homological_complex.single_obj_X_self C\n    (complex_shape.up \u2124) a X\u2081).hom \u226b i \u226b (double.X_iso\u2081 h p rfl).inv) _ h\n    (by simp [reassoc_of w])\n\n@[simp]\ndef single_to_double' (g : X\u2081 \u27f6 X\u2083) (p : X\u2082 \u27f6 X\u2083) :\n  ((homological_complex.single C _ b).obj X\u2081) \u27f6 double h p :=\n   desc_single _ (double h p) ((homological_complex.single_obj_X_self C\n    (complex_shape.up \u2124) b X\u2081).hom \u226b g \u226b (double.X_iso\u2082 h p rfl).inv) (b+1) rfl\n    (is_zero.eq_of_tgt (double.X_is_zero h p (b+1) (by simp only [\u2190 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 \u03c6}\n\nlemma eq_single_to_double {Z : C} (f : ((homological_complex.single C _ a).obj Z) \u27f6 double h \u03c6) :\n  \u2203 (g : Z \u27f6 A) (hg : g \u226b \u03c6 = 0), f = single_to_double h g \u03c6 hg :=\n\u27e8(homological_complex.single_obj_X_self C\n  (complex_shape.up \u2124) a Z).inv \u226b f.f a \u226b (double.X_iso\u2081 h \u03c6 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 =\u226b (double.X_iso\u2082 h \u03c6 rfl).hom,\n  from_single_ext _ _ a (by simp)\u27e9\n\nlemma eq_single_to_double' {Z : C} (f : ((homological_complex.single C _ b).obj Z) \u27f6 double h \u03c6) :\n  \u2203 (g : Z \u27f6 B), f = single_to_double' h g \u03c6 :=\n\u27e8(homological_complex.single_obj_X_self C\n    (complex_shape.up \u2124) b Z).inv \u226b f.f b \u226b (double.X_iso\u2082 h \u03c6 rfl).hom,\n    from_single_ext _ _ b (by simp)\u27e9\n\nvariables (h \u03c6)\n\nlemma double.is_zero_homology\u2081_iff :\n  is_zero ((double h \u03c6).homology a) \u2194 mono \u03c6 :=\nbegin\n  have hb : b = (complex_shape.up \u2124).next a := by { rw next, linarith, },\n  subst hb,\n  rw [\u2190 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 \u03c6) a = _ := double.d_eq h \u03c6,\n    simp only [eq, mono_comp_left_iff_mono, mono_comp_right_iff_mono], },\n  { exact double.d_eq_zero\u2082 h \u03c6 (by linarith), }\nend\n\nlemma double.is_zero_homology\u2082_iff :\n  is_zero ((double h \u03c6).homology b) \u2194 epi \u03c6 :=\nbegin\n  have ha : a = (complex_shape.up \u2124).prev b := by { rw prev, linarith, },\n  subst ha,\n  rw [\u2190 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 \u03c6) b = _ := double.d_eq h \u03c6,\n    simp only [eq, \u2190 assoc, epi_comp_right_iff_epi, epi_comp_left_iff_epi], },\n  { exact double.d_eq_zero\u2081 h \u03c6 (by linarith), },\nend\n\nlemma is_iso_homology_map\u2081_single_to_double_iff_exact_and_mono\n  (i : X\u2081 \u27f6 X\u2082) (p : X\u2082 \u27f6 X\u2083) (w : i \u226b p = 0) :\nis_iso (homology_map (single_to_double h i p w) a) \u2194\n  (short_complex.mk _ _ w).exact \u2227 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\u2082 h p (by linarith), },\n  apply iff.and,\n  { apply short_complex.exact_iff_of_iso,\n    have hb : (complex_shape.up \u2124).next a = b := by { rw next, linarith, },\n    refine short_complex.mk_iso\n      (homological_complex.single_obj_X_self  _ (complex_shape.up \u2124) _ X\u2081)\n      (double.X_iso\u2081 h p rfl) (double.X_iso\u2082 h p hb) _ _ ,\n    { dsimp,\n      simp only [desc_single_f, assoc, iso.inv_hom_id, comp_id], },\n    { dsimp,\n      simpa only [\u2190 cancel_mono (double.X_iso\u2082 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_\u03c4\u2082,\n      desc_single_f, mono_comp_left_iff_mono, mono_comp_right_iff_mono], },\nend\n\nvariable {\u03c6}\n\nlemma single_to_double_quasi_iso_iff (i : X\u2081 \u27f6 X\u2082) (p : X\u2082 \u27f6 X\u2083) (w : i \u226b p = 0) :\n  quasi_iso (single_to_double h i p w) \u2194 (short_complex.mk _ _ w).short_exact :=\nbegin\n  split,\n  { intro hw,\n    have hw' := (is_iso_homology_map\u2081_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 [\u2190 double.is_zero_homology\u2082_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 \u27e8\u03bb n, _\u27e9,\n    rcases double.four_cases h n with hn | \u27e8hn | hn\u27e9,\n    { refine \u27e8\u27e80, is_zero.eq_of_src _ _ _, is_zero.eq_of_src _ _ _\u27e9\u27e9,\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\u2081_single_to_double_iff_exact_and_mono h i p w).2 \u27e8hw.exact, hw.mono_f\u27e9, },\n    { subst hn,\n      exact \u27e8\u27e80, 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\u2082_iff] using hw.epi_g) _ _\u27e9\u27e9, }, },\nend\n\nlemma from_double_ext {K L : cochain_complex C \u2124} [K.is_strictly_le b] [K.is_strictly_ge a]\n  (f\u2081 f\u2082 : K \u27f6 L) (h\u2081 : f\u2081.f a = f\u2082.f a) (h\u2082 : f\u2081.f b = f\u2082.f b) : f\u2081 = f\u2082 :=\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\u2081, },\n  { unfreezingI { subst h', },\n    exact h\u2082, },\nend\n\nomit h\nvariable (\u03c6)\n\ninstance mapping_cone_single_map_is_strictly_le :\n  (mapping_cone ((homological_complex.single _ _ 0).map \u03c6)).is_strictly_le 0 :=\n\u27e8\u03bb n hn, begin\n  rw mapping_cone.X_is_zero_iff,\n  split; exact is_strictly_le.is_zero _ 0 _ (by linarith),\nend\u27e9\n\ninstance mapping_cone_single_map_is_strictly_ge :\n  (mapping_cone ((homological_complex.single _ _ 0).map \u03c6)).is_strictly_ge (-1) :=\n\u27e8\u03bb n hn, begin\n  rw mapping_cone.X_is_zero_iff,\n  split; exact is_strictly_ge.is_zero _ 0 _ (by linarith),\nend\u27e9\n\n@[simps]\ndef double_iso_mapping_cone : double (neg_add_self 1) \u03c6 \u2245\n  mapping_cone ((homological_complex.single _ _ 0).map \u03c6) :=\n{ hom := double.desc (neg_add_self 1) \u03c6 _\n      ((homological_complex.single_obj_X_self _ _ 0 A).inv \u226b\n        (mapping_cone.inl _).v _ _ (zero_add (-1)).symm)\n      ((homological_complex.single_obj_X_self _ _ 0 B).inv \u226b\n        (mapping_cone.inr ((homological_complex.single _ _ 0).map \u03c6)).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) \u03c6 _\n      ((mapping_cone.fst _).1.v (-1) 0 (neg_add_self 1).symm \u226b\n          (homological_complex.single_obj_X_self _ _ 0 A).hom)\n      ((mapping_cone.snd _ ).v _ _ (zero_add 0).symm \u226b\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 : \u2124) +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\u2081, double.lift_f,\n        double.lift.f\u2081, 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\u2082, double.lift_f, double.lift.f\u2082,\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\u2081, double.desc_f,\n        double.desc.f\u2081, 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\u2082, double.desc_f, double.desc.f\u2082, 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) 2016 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.data.list.basic\nimport Mathlib.Lean3Lib.init.data.char.basic\n\nuniverses l u_1 \n\nnamespace Mathlib\n\n/- In the VM, strings are implemented using a dynamic array and UTF-8 encoding.\n\n   TODO: we currently cannot mark string_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\n\nstructure string_imp where\n  data : List char\n\ndef string := string_imp\n\ndef list.as_string (s : List char) : string := string_imp.mk s\n\nnamespace string\n\n\nprotected instance has_lt : HasLess string :=\n  { Less := fun (s\u2081 s\u2082 : string) => string_imp.data s\u2081 < string_imp.data s\u2082 }\n\n/- Remark: this function has a VM builtin efficient implementation. -/\n\nprotected instance has_decidable_lt (s\u2081 : string) (s\u2082 : string) : Decidable (s\u2081 < s\u2082) :=\n  list.has_decidable_lt (string_imp.data s\u2081) (string_imp.data s\u2082)\n\nprotected instance has_decidable_eq : DecidableEq string := fun (_x : string) => sorry\n\ndef empty : string := string_imp.mk []\n\ndef length : string \u2192 \u2115 := sorry\n\n/- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\n\ndef push : string \u2192 char \u2192 string := sorry\n\n/- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the string is not shared. -/\n\ndef append : string \u2192 string \u2192 string := sorry\n\n/- O(n) in the VM, where n is the length of the string -/\n\ndef to_list : string \u2192 List char := sorry\n\ndef fold {\u03b1 : Type u_1} (a : \u03b1) (f : \u03b1 \u2192 char \u2192 \u03b1) (s : string) : \u03b1 := list.foldl f a (to_list s)\n\n/- In the VM, the string iterator is implemented as a pointer to the string being iterated + index.\n\n   TODO: we currently cannot mark interator_imp as private because\n   we need to bind string_imp.mk and string_imp.cases_on in the VM.\n-/\n\nstructure iterator_imp where\n  fst : List char\n  snd : List char\n\ndef iterator := iterator_imp\n\ndef mk_iterator : string \u2192 iterator := sorry\n\nnamespace iterator\n\n\ndef curr : iterator \u2192 char := sorry\n\n/- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time\n   if it is. -/\n\ndef set_curr : iterator \u2192 char \u2192 iterator := sorry\n\ndef next : iterator \u2192 iterator := sorry\n\ndef prev : iterator \u2192 iterator := sorry\n\ndef has_next : iterator \u2192 Bool := sorry\n\ndef has_prev : iterator \u2192 Bool := sorry\n\ndef insert : iterator \u2192 string \u2192 iterator := sorry\n\ndef remove : iterator \u2192 \u2115 \u2192 iterator := sorry\n\n/- In the VM, `to_string` is a constant time operation. -/\n\ndef to_string : iterator \u2192 string := sorry\n\ndef to_end : iterator \u2192 iterator := sorry\n\ndef next_to_string : iterator \u2192 string := sorry\n\ndef prev_to_string : iterator \u2192 string := sorry\n\nprotected def extract_core : List char \u2192 List char \u2192 Option (List char) := sorry\n\ndef extract : iterator \u2192 iterator \u2192 Option string := sorry\n\nend iterator\n\n\nend string\n\n\n/- The following definitions do not have builtin support in the VM -/\n\nprotected instance string.inhabited : Inhabited string := { default := string.empty }\n\nprotected instance string.has_sizeof : SizeOf string := { sizeOf := string.length }\n\nprotected instance string.has_append : Append string := { append := string.append }\n\nnamespace string\n\n\ndef str : string \u2192 char \u2192 string := push\n\ndef is_empty (s : string) : Bool := to_bool (length s = 0)\n\ndef front (s : string) : char := iterator.curr (mk_iterator s)\n\ndef back (s : string) : char := iterator.curr (iterator.prev (iterator.to_end (mk_iterator s)))\n\ndef join (l : List string) : string := list.foldl (fun (r s : string) => r ++ s) empty l\n\ndef singleton (c : char) : string := push empty c\n\ndef intercalate (s : string) (ss : List string) : string :=\n  list.as_string (list.intercalate (to_list s) (list.map to_list ss))\n\nnamespace iterator\n\n\ndef nextn : iterator \u2192 \u2115 \u2192 iterator := sorry\n\ndef prevn : iterator \u2192 \u2115 \u2192 iterator := sorry\n\nend iterator\n\n\ndef pop_back (s : string) : string :=\n  iterator.prev_to_string (iterator.prev (iterator.to_end (mk_iterator s)))\n\ndef popn_back (s : string) (n : \u2115) : string :=\n  iterator.prev_to_string (iterator.prevn (iterator.to_end (mk_iterator s)) n)\n\ndef backn (s : string) (n : \u2115) : string :=\n  iterator.next_to_string (iterator.prevn (iterator.to_end (mk_iterator s)) n)\n\nend string\n\n\nprotected def char.to_string (c : char) : string := string.singleton c\n\ndef string.to_nat (s : string) : \u2115 := to_nat_core (string.mk_iterator s) (string.length s) 0\n\nnamespace string\n\n\ntheorem empty_ne_str (c : char) (s : string) : empty \u2260 str s c := sorry\n\ntheorem str_ne_empty (c : char) (s : string) : str s c \u2260 empty := ne.symm (empty_ne_str c s)\n\ntheorem str_ne_str_left {c\u2081 : char} {c\u2082 : char} (s\u2081 : string) (s\u2082 : string) :\n    c\u2081 \u2260 c\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082 :=\n  sorry\n\ntheorem str_ne_str_right (c\u2081 : char) (c\u2082 : char) {s\u2081 : string} {s\u2082 : string} :\n    s\u2081 \u2260 s\u2082 \u2192 str s\u2081 c\u2081 \u2260 str s\u2082 c\u2082 :=\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/init/data/string/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.05921024493086481, "lm_q1q2_score": 0.016849814911107364}}
{"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 \u2192 List (expr elab) \u2192 List (expr elab) \u2192 mono_function\n  | assoc : expr elab \u2192 Option (expr elab) \u2192 Option (expr elab) \u2192 mono_function\n  | assoc_comm : expr elab \u2192 expr elab \u2192 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 \u2192 tactic format\n  | mono_function.non_assoc fn xs ys => do\n    let fn' \u2190 pp fn\n    let xs' \u2190 mapM pp xs\n    let ys' \u2190 mapM pp ys\n    return f! \"{fn' } {xs' } _ {ys'}\"\n  | mono_function.assoc fn xs ys => do\n    let fn' \u2190 pp fn\n    let xs' \u2190 pp xs\n    let ys' \u2190 pp ys\n    return f! \"{fn' } {xs' } _ {ys'}\"\n  | mono_function.assoc_comm fn xs => do\n    let fn' \u2190 pp fn\n    let xs' \u2190 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 \u2192 expr \u2192 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 \u2192 expr \u2192 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 \u2190 pp ctx.function\n  let l \u2190 pp ctx.left\n  let r \u2190 pp ctx.right\n  let rel \u2190 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 \u2190 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 \u2192 expr \u2192 expr \u2192 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 \u2190 return t |\n        failed\n      let v \u2190 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 \u2192 tactic expr\n  | expr.pi n _ t b => do\n    let v \u2190 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 \u2192 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 \u2192 List expr \u2192 tactic (List expr \u00d7 List expr \u00d7 List expr)\n  | es, x :: xs => do\n    let es' \u2190 delete_expr x es\n    match es' with\n      | some es' => do\n        let (c, l, r) \u2190 match_ac' es' xs\n        return (x :: c, l, r)\n      | none => do\n        let (c, l, r) \u2190 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 \u00d7 List expr \u00d7 List expr) :=\n  do\n  let (s', l', r') \u2190 match_ac' l r\n  let s' \u2190 mapM instantiate_mvars s'\n  let l' \u2190 mapM instantiate_mvars l'\n  let r' \u2190 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 \u2192 List expr \u2192 tactic (List expr \u00d7 List expr \u00d7 List expr)\n  | x :: xs, y :: ys =>\n    (do\n        compare opt x y\n        Prod.map ((\u00b7 :: \u00b7) 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) \u2190 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 \u00d7 List expr \u00d7 List expr \u00d7 List expr) := do\n  let (pre, l\u2081, r\u2081) \u2190 match_prefix l r\n  let (suf, l\u2082, r\u2082) \u2190 match_prefix (reverse l\u2081) (reverse r\u2081)\n  return (pre, reverse l\u2082, reverse r\u2082, reverse suf)\n#align tactic.interactive.match_assoc tactic.interactive.match_assoc\n\nunsafe def check_ac : expr \u2192 tactic (Bool \u00d7 Bool \u00d7 Option (expr \u00d7 expr \u00d7 expr) \u00d7 expr)\n  | expr.app (expr.app f x) y => do\n    let t \u2190 infer_type x\n    let a \u2190 try_core <| to_expr ``(IsAssociative $(t) $(f)) >>= mk_instance\n    let c \u2190 try_core <| to_expr ``(IsCommutative $(t) $(f)) >>= mk_instance\n    let i \u2190\n      try_core do\n          let v \u2190 mk_meta_var t\n          let l_inst_p \u2190 to_expr ``(IsLeftId $(t) $(f) $(v))\n          let r_inst_p \u2190 to_expr ``(IsRightId $(t) $(f) $(v))\n          let l_v \u2190 mk_meta_var l_inst_p\n          let r_v \u2190 mk_meta_var r_inst_p\n          let l_id \u2190 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 \u2190 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' \u2190 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 \u2192 tactic (Dlist expr)\n  | e =>\n    (do\n        let expr.app (expr.app f' x) y \u2190 return e\n        is_def_eq f f'\n        (\u00b7 ++ \u00b7) <$> 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 \u2192 tactic (List expr) :=\n  map Dlist.toList \u2218 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 \u00d7 expr \u00d7 expr) \u2192 List expr \u2192 Option (expr \u00d7 List expr)\n  | _, x :: xs => some (foldl (expr.app \u2218 expr.app op) x xs, [])\n  | none, [] => none\n  | some (l_id, r_id, x\u2080), [] => some (x\u2080, [l_id, r_id])\n#align tactic.interactive.fold_assoc tactic.interactive.fold_assoc\n\nunsafe def fold_assoc1 (op : expr) : List expr \u2192 Option expr\n  | x :: xs => some <| foldl (expr.app \u2218 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 \u2192 List expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 List expr \u00d7 List expr)\n  | xs\u2080, xs\u2081, expr.app f\u2080 a\u2080, expr.app f\u2081 a\u2081 => same_function_aux (a\u2080 :: xs\u2080) (a\u2081 :: xs\u2081) f\u2080 f\u2081\n  | xs\u2080, xs\u2081, e\u2080, e\u2081 => is_def_eq e\u2080 e\u2081 >> return (e\u2080, xs\u2080, xs\u2081)\n#align tactic.interactive.same_function_aux tactic.interactive.same_function_aux\n\nunsafe def same_function : expr \u2192 expr \u2192 tactic (expr \u00d7 List expr \u00d7 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 \u00d7 expr \u00d7 List expr \u00d7 mono_function) :=\n  do\n  let (full_f, ls, rs) \u2190 same_function l r\n  let (a, c, i, f) \u2190 check_ac l\n  if a then\n      if c then do\n        let (s, ls, rs) \u2190 Monad.join (match_ac <$> parse_assoc_chain f l <*> parse_assoc_chain f r)\n        let (l', l_id) \u2190 fold_assoc f i ls\n        let (r', r_id) \u2190 fold_assoc f i rs\n        let s' \u2190 fold_assoc1 f s\n        return (l', r', l_id ++ r_id, mono_function.assoc_comm f s')\n      else do\n        let-- a \u2227 \u00ac c\n          (pre, ls, rs, suff)\n          \u2190 Monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r)\n        let (l', l_id) \u2190 fold_assoc f i ls\n        let (r', r_id) \u2190 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-- \u00ac a\n        (xs\u2080, x\u2080, x\u2081, xs\u2081)\n        \u2190 find_one_difference opt ls rs\n      return (x\u2080, x\u2081, [], mono_function.non_assoc full_f xs\u2080 xs\u2081)\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' \u2190 to_expr l\n  let r' \u2190 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 \u2192 tactic ( expr \u00d7 expr \u00d7 List expr \u00d7 ac_mono_ctx )\n    |\n        q( $ ( e\u2080 ) \u2192 $ ( e\u2081 ) )\n        =>\n        do\n          let ( l , r , id_rs , f ) \u2190 parse_ac_mono_function e\u2080 e\u2081\n            let t\u2080 \u2190 infer_type e\u2080\n            let t\u2081 \u2190 infer_type e\u2081\n            let rel_def \u2190 to_expr ` `( fun x\u2080 x\u2081 => ( x\u2080 : $ ( t\u2080 ) ) \u2192 ( x\u2081 : $ ( t\u2081 ) ) )\n            return\n              (\n                e\u2080\n                  ,\n                  e\u2081\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\u2080 ) = $ ( e\u2081 ) )\n        =>\n        do\n          let ( l , r , id_rs , f ) \u2190 parse_ac_mono_function e\u2080 e\u2081\n            let t\u2080 \u2190 infer_type e\u2080\n            let t\u2081 \u2190 infer_type e\u2081\n            let rel_def \u2190 to_expr ` `( fun x\u2080 x\u2081 => ( x\u2080 : $ ( t\u2080 ) ) = ( x\u2081 : $ ( t\u2081 ) ) )\n            return\n              ( e\u2080 , e\u2081 , id_rs , { function := f left := l right := r to_rel := none rel_def } )\n      |\n        expr.app ( expr.app Rel e\u2080 ) e\u2081\n        =>\n        do\n          let ( l , r , id_rs , f ) \u2190 parse_ac_mono_function e\u2080 e\u2081\n            return\n              (\n                e\u2080\n                  ,\n                  e\u2081\n                    ,\n                    id_rs\n                    ,\n                    {\n                      function := f\n                        left := l\n                        right := r\n                        to_rel := expr.app \u2218 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 \u2192 expr \u2192 expr\n  | none, e => e\n  | some e\u2080, e\u2081 => f.mk_app [e\u2080, e\u2081]\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 \u2192 Option expr \u2192 expr\n  | e, none => e\n  | e\u2080, some e\u2081 => f.mk_app [e\u2080, e\u2081]\n#align tactic.interactive.bin_op_right tactic.interactive.bin_op_right\n\nunsafe def mk_fun_app : mono_function \u2192 expr \u2192 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\u2080,r\u2080) (r\u2081,l\u2081)` gives first how to find rules to prove\n      x+(y\u2080+z) R x+(y\u2081+z);\n      if that fails, helps prove (x+y\u2080)+z R (x+y\u2081)+z -/\n\n  |\n  assoc :\n    expr \u00d7 expr \u2192 expr \u00d7 expr \u2192 mono_law-- `congr r` gives the rule to prove `x = y \u2192 f x = f y`\n\n  | congr : expr \u2192 mono_law\n  | other : expr \u2192 mono_law\n#align tactic.interactive.mono_law tactic.interactive.mono_law\n\nunsafe def mono_law.to_tactic_format : mono_law \u2192 tactic format\n  | mono_law.other e => do\n    let e \u2190 pp e\n    return f! \"other {e}\"\n  | mono_law.congr r => do\n    let e \u2190 pp r\n    return f! \"congr {e}\"\n  | mono_law.assoc (x\u2080, x\u2081) (y\u2080, y\u2081) => do\n    let x\u2080 \u2190 pp x\u2080\n    let x\u2081 \u2190 pp x\u2081\n    let y\u2080 \u2190 pp y\u2080\n    let y\u2081 \u2190 pp y\u2081\n    return f! \"assoc {x\u2080 }; {x\u2081 } | {y\u2080 }; {y\u2081}\"\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 \u2192 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\u2081 -/\nunsafe def mk_congr_args (fn : expr) (xs\u2080 xs\u2081 : List expr) (l r : expr) : tactic expr := do\n  let p \u2190 mk_app `eq [fn.mk_app <| xs\u2080 ++ l :: xs\u2081, fn.mk_app <| xs\u2080 ++ r :: xs\u2081]\n  Prod.snd <$>\n      solve_aux p do\n        iterate_exactly (xs\u2081 xs\u2081.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\u2080 x\u2081 =>\n    if (x\u2080 <|> x\u2081).isSome then mk_congr_args f x\u2080.toMonad x\u2081.toMonad ctx.left ctx.right else failed\n  | mono_function.assoc_comm f x\u2080 => mk_congr_args f [x\u2080] [] ctx.left ctx.right\n  | mono_function.non_assoc f x\u2080 x\u2081 => mk_congr_args f x\u2080 x\u2081 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' \u2190 mk_const r\n  let t \u2190 infer_type r'\n  let t \u2190\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 \u2192 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\u2080 x\u2081 : expr ) : tactic ( List expr )\n    :=\n      do\n        let x' \u2190 to_expr ` `( $ ( x\u2081 ) \u2192 $ ( x\u2080 ) )\n          let r\u2080 \u2190 find_lemma x' ls\n          let r\u2081 \u2190 find_lemma x\u2081 ls\n          return ( expr.app <$> r\u2080 <*> r\u2081 )\n#align tactic.interactive.match_chaining_rules tactic.interactive.match_chaining_rules\n\nunsafe def find_rule (ls : List Name) : mono_law \u2192 tactic (List expr)\n  | mono_law.assoc (x\u2080, x\u2081) (y\u2080, y\u2081) =>\n    match_chaining_rules ls x\u2080 x\u2081 <|> match_chaining_rules ls y\u2080 y\u2081\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 {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x y : \u03b1} (x' y' : \u03b1) (h : R x y) (hx : x = x')\n    (hy : y = y') : R x' y' := by\n  rw [\u2190 hx, \u2190 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 \u2190 pp e\n  let asm \u2190 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 \u2190 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 \u00d7 expr )\n    :=\n      do\n        let tgt \u2190 target\n          let t \u2190 infer_type v\n          let\n            tgt'\n              \u2190\n              (\n                  do\n                    let \u27e8 tgt' , _ \u27e9 \u2190 solve_aux tgt ( tactic.generalize v x >> target )\n                      to_expr ` `( fun y : $ ( t ) => \u2200 x , y = x \u2192 $ ( tgt' 0 1 ) )\n                  )\n                <|>\n                to_expr ` `( fun y : $ ( t ) => \u2200 x , $ ( v ) = x \u2192 $ ( tgt ) )\n          let t \u2190 head_beta ( tgt' v ) >>= assert h\n          swap\n          let r \u2190 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 \u2192 tactic Unit) : tactic Unit :=\n  focus1 do\n    let tgt \u2190 target >>= instantiate_mvars\n    tactic.change tgt\n    let ctx \u2190 local_context\n    let vs := tgt.list_meta_vars\n    let vs' \u2190\n      mapM\n          (fun v => do\n            let h \u2190 get_unused_name `h\n            let x \u2190 get_unused_name `x\n            Prod.snd <$> monotonicity.generalize' h v x)\n          vs\n    andthen (tac ctx) (vs' (try \u2218 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 \u2190 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 {\u03b1 \u03b2} [LinearOrder \u03b2] (f : \u03b1 \u2192 \u03b2) : List \u03b1 \u2192 List \u03b1\n  | [] => []\n  | x :: xs =>\n    Prod.snd <|\n      xs.foldl\n        (fun \u27e8k, a\u27e9 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 {\u03b2} (xs : List expr) (tac : expr \u2192 tactic \u03b2) : tactic Unit := do\n  let t \u2190 target\n  let xs \u2190 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 \u2218 Prod.fst \u2218 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 \u2190\n        r fun \u27e8l, gs, _\u27e9 => do\n            let ts \u2190 gs infer_type\n            let msg \u2190 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 \u2190 target >>= instantiate_mvars\n  let ns \u2190 get_monotonicity_lemmas t dir\n  let asms \u2190 local_context\n  let rs \u2190 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 \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (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 \u2190 hyps.mapM fun p => to_expr p >>= mk_meta_var\n  hyps fun pr => do\n      let h \u2190 get_unused_name `h\n      note h none pr\n  when (\u00acsimp_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 \u2190 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 \u227c f y` into `x \u2264 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 \u2190 target >>= instantiate_mvars\n    let (l, r, id_rs, g) \u2190 ac_monotonicity_goal cfg tgt <|> fail \"monotonic context not found\"\n    let ns \u2190 get_monotonicity_lemmas tgt both\n    let p \u2190 mk_pattern g\n    let rules \u2190 find_rule asms ns p <|> fail \"no applicable rules found\"\n    when (rules = []) (fail \"no applicable rules found\")\n    let err \u2190 format.join <$> mapM side_conditions rules\n    focus1 <|\n        best_match rules fun rule => do\n          let t\u2080 \u2190 mk_meta_var q(Prop)\n          let v\u2080 \u2190 mk_meta_var t\u2080\n          let t\u2081 \u2190 mk_meta_var q(Prop)\n          let v\u2081 \u2190 mk_meta_var t\u2081\n          tactic.refine <| ``(applyRel (g $(g.rel_def)) $(l) $(r) $(rule) $(v\u2080) $(v\u2081))\n          solve_mvar v\u2080 (try (any_of id_rs rewrite_target) >> (done <|> refl <|> ac_refl <|> sorry))\n          solve_mvar v\u2081 (try (any_of id_rs rewrite_target) >> (done <|> refl <|> ac_refl <|> sorry))\n          let n \u2190 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 \u2192 tactic Unit \u2192 tactic Unit \u2192 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 \u2192 tactic Unit \u2192 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 : \u2115)\n  | many\n  deriving _root_.has_reflect, Inhabited\n#align tactic.interactive.rep_arity Tactic.Interactive.RepArity\n\nunsafe def repeat_or_not : RepArity \u2192 tactic Unit \u2192 Option (tactic Unit) \u2192 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 \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* := h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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 ? \u2192 optParam MonoCfg { } \u2192 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 \u2190 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 (\u03bb (f : X \u27f6 Y), (functor r).map f) := surjective_quot_mk _\n\nlemma nat_trans_ext {F G : quotient r \u2964 D} (\u03c4\u2081 \u03c4\u2082 : F \u27f6 G)\n  (h : \u2200 (X : C), \u03c4\u2081.app ((functor r).obj X) = \u03c4\u2082.app ((functor r).obj X)) : \u03c4\u2081 = \u03c4\u2082 :=\nby { ext X, cases X, exact h X, }\n\ndef lift_nat_trans (F G : quotient r \u2964 D) (\u03c4 : functor _ \u22d9 F \u27f6 functor _ \u22d9 G) :\n  F \u27f6 G :=\n{ app := by { rintro \u27e8X\u27e9, exact \u03c4.app X, },\n  naturality' := by { rintros \u27e8X\u27e9 \u27e8Y\u27e9 \u27e8f\u27e9, exact \u03c4.naturality f, }, }\n\n@[simp]\nlemma lift_nat_trans_app (F G : quotient r \u2964 D) (\u03c4 : functor _ \u22d9 F \u27f6 functor _ \u22d9 G) (X : C) :\n  (lift_nat_trans F G \u03c4).app ((functor r).obj X) = \u03c4.app X := rfl\n\n@[simp]\nlemma lift_nat_trans_id (F : quotient r \u2964 D) :\n  lift_nat_trans F F (\ud835\udfd9 _) = \ud835\udfd9 _ :=\nnat_trans_ext _ _ (\u03bb X, rfl)\n\n@[simp, reassoc]\nlemma lift_nat_trans_comp (F G H : quotient r \u2964 D) (\u03c4 : functor _ \u22d9 F \u27f6 functor _ \u22d9 G)\n  (\u03c4' : functor _ \u22d9 G \u27f6 functor _ \u22d9 H) :\n  lift_nat_trans F G \u03c4 \u226b lift_nat_trans G H \u03c4' = lift_nat_trans F H (\u03c4 \u226b \u03c4') :=\nnat_trans_ext _ _ (\u03bb X, by simp)\n\n@[simps]\ndef lift_nat_iso (F G : quotient r \u2964 D) (e : functor _ \u22d9 F \u2245 functor _ \u22d9 G) :\n  F \u2245 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 \u2964 D} (\u03c4 : F \u27f6 G)\n  (hF : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), F.map f\u2081 = F.map f\u2082)\n  (hG : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), G.map f\u2081 = G.map f\u2082) :\n  lift r F hF \u27f6 lift r G hG :=\nlift_nat_trans _ _\n    ((quotient.lift.is_lift r F hF).hom \u226b \u03c4 \u226b (quotient.lift.is_lift r G hG).inv)\n\n@[simp]\nlemma lift_nat_trans'_app {F G : C \u2964 D} (\u03c4 : F \u27f6 G)\n  (hF : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), F.map f\u2081 = F.map f\u2082)\n  (hG : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), G.map f\u2081 = G.map f\u2082) (X : C) :\n  (lift_nat_trans' r \u03c4 hF hG).app ((functor r).obj X) = \u03c4.app X :=\nbegin\n  dsimp [lift_nat_trans'],\n  simp,\nend\n\n@[simp]\nlemma lift_nat_trans'_id (F : C \u2964 D)\n  (hF : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), F.map f\u2081 = F.map f\u2082) :\n  lift_nat_trans' r (\ud835\udfd9 F) hF hF = \ud835\udfd9 _ :=\nnat_trans_ext _ _ (\u03bb X, by { dsimp, simp, })\n\n@[simp]\nlemma lift_nat_trans'_comp {F G H : C \u2964 D} (\u03c4 : F \u27f6 G) (\u03c4' : G \u27f6 H)\n  (hF : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), F.map f\u2081 = F.map f\u2082)\n  (hG : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), G.map f\u2081 = G.map f\u2082)\n  (hH : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), H.map f\u2081 = H.map f\u2082) :\n  lift_nat_trans' r \u03c4 hF hG \u226b lift_nat_trans' r \u03c4' hG hH =\n    lift_nat_trans' r (\u03c4 \u226b \u03c4') hF hH :=\nnat_trans_ext _ _ (\u03bb X, by simp)\n\n@[simps]\ndef lift_nat_iso' {F G : C \u2964 D} (e : F \u2245 G)\n  (hF : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), F.map f\u2081 = F.map f\u2082)\n  (hG : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), G.map f\u2081 = G.map f\u2082) :\n  lift r F hF \u2245 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 \u2964 D)\n  (hF : \u2200 (X Y : C) (f\u2081 f\u2082 : X \u27f6 Y) (h : r f\u2081 f\u2082), F.map f\u2081 = F.map f\u2082)\n  {X Y : C} (f : X \u27f6 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 := \u27e8\u27e8_, hX\u27e9\u27e9,\n  refine limits.is_zero.of_iso _ ((functor r).map_iso (is_zero.iso_zero hX)),\n  split,\n  { rintro \u27e8Y\u27e9,\n    haveI := (has_zero_object.unique_from Y),\n    refine \u27e8\u27e8\u27e8(functor r).map default\u27e9, _\u27e9\u27e9,\n    intro f,\n    obtain \u27e8g, rfl\u27e9 := functor_map_surjective _ _ f,\n    rw subsingleton.elim g default, },\n  { rintro \u27e8Y\u27e9,\n    haveI := (has_zero_object.unique_to Y),\n    refine \u27e8\u27e8\u27e8(functor r).map default\u27e9, _\u27e9\u27e9,\n    intro f,\n    obtain \u27e8g, rfl\u27e9 := functor_map_surjective _ _ f,\n    rw subsingleton.elim g default, },\nend\n\ninstance [has_zero_object C] : has_zero_object (quotient r) :=\n\u27e8\u27e8_, is_zero_of_is_zero _ (is_zero_zero C)\u27e9\u27e9\n\nsection preadditive\n\nvariables [preadditive C] [congruence r]\n  (add : \u2200 \u2983X Y : C\u2984 \u2983f\u2081 g\u2081 f\u2082 g\u2082 : X \u27f6 Y\u2984 (h\u2081 : r f\u2081 g\u2081) (h\u2082 : r f\u2082 g\u2082), (r (f\u2081 + f\u2082) (g\u2081 + g\u2082)))\n  (neg : \u2200 \u2983X Y : C\u2984 \u2983f g : X \u27f6 Y\u2984 (h : r f g), r (-f) (-g))\n\nlemma comp_closure_eq_self : comp_closure r = r :=\nbegin\n  ext X Y f\u2081 f\u2082,\n  split,\n  { intro h,\n    simpa only [\u2190 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} (\u03c6 \u03c6' : X \u27f6 Y) : X \u27f6 Y :=\nbegin\n  refine quot.lift\u2082 (\u03bb x y, quot.mk _ (x+y)) _ _ \u03c6 \u03c6',\n  { intros x y\u2081 y\u2082 h,\n    rw comp_closure_eq_self at h,\n    change (functor r).map (x+y\u2081) = (functor r).map (x+y\u2082),\n    rw functor_map_eq_iff,\n    exact add (refl _) h, },\n  { intros x\u2081 x\u2082 y h,\n    rw comp_closure_eq_self at h,\n    change (functor r).map (x\u2081+y) = (functor r).map (x\u2082+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} (\u03c6 : X \u27f6 Y) : X \u27f6 Y :=\nbegin\n  refine quot.lift (\u03bb x, quot.mk _ (-x)) _ \u03c6,\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 \u27f6 Y) :=\n{ add := preadditive.add add,\n  add_assoc := by { rintros \u27e8x\u27e9 \u27e8y\u27e9 \u27e8z\u27e9, exact (functor r).congr_map (add_assoc x y z), },\n  zero := (functor r).map 0,\n  zero_add := by { rintro \u27e8x\u27e9, exact (functor r).congr_map (zero_add x), },\n  add_zero := by { rintro \u27e8x\u27e9, exact (functor r).congr_map (add_zero x), },\n  neg := preadditive.neg neg,\n  add_left_neg := by { rintro \u27e8x\u27e9, exact (functor r).congr_map (add_left_neg x), },\n  add_comm := by { rintros \u27e8x\u27e9 \u27e8y\u27e9, 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' := \u03bb X Y Z, begin\n    rintros \u27e8x\u2081\u27e9 \u27e8x\u2082\u27e9 \u27e8y\u27e9,\n    exact (functor r).congr_map (preadditive.add_comp _ _ _ x\u2081 x\u2082 y),\n  end,\n  comp_add' := \u03bb X Y Z, begin\n    rintros \u27e8x\u27e9 \u27e8y\u2081\u27e9 \u27e8y\u2082\u27e9,\n    exact (functor r).congr_map (preadditive.comp_add _ _ _ x y\u2081 y\u2082),\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 \u2964 D) [F.additive]\n  (H : \u2200 (x y : C) (f\u2081 f\u2082 : x \u27f6 y), r f\u2081 f\u2082 \u2192 F.map f\u2081 = F.map f\u2082) :\n  (lift r F H).additive :=\n\u27e8begin\n  rintro \u27e8X\u27e9 \u27e8Y\u27e9 \u27e8f\u2081 : X \u27f6 Y\u27e9 \u27e8f\u2082 : X \u27f6 Y\u27e9,\n  change (lift r F H).map ((functor r).map f\u2081 + (functor r).map f\u2082) = F.map f\u2081 + F.map f\u2082,\n  simpa only [\u2190 functor.map_add],\nend\u27e9\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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u2124 \u2115`\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 \u2265 1 internal coe\n* move lemma:   LHS has 1 head coe and 0 internal coes,    RHS has 0 head coes and \u2265 1 internal coes\n* squash lemma: LHS has \u2265 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 \u2192 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 \u2192 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 \u2265, > and \u2260 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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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 (\u2191(x : \u03b1) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nis rewritten to:            op (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) (\u2191(y : \u03b2) : \u03b3)\nwhen (\u2191(\u2191(x : \u03b1) : \u03b2) : \u03b3) = (\u2191(x : \u03b1) : \u03b3) 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 : \u03b1)` to `((n : \u2115) : \u03b1)` where `n` is a numeral and `\u03b1 \u2260 \u2115`.\nReturns a pair of the new expression and proof that they are equal.\n-/\n/--\nIf possible, rewrite `((n : \u2115) : \u03b1)` to `(n : \u03b1)` 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [has_lift_t \u03b1 \u03b2] {c : Prop} [Decidable c] {a : \u03b1}\n    {b : \u03b1} : \u2191(ite c a b) = ite c \u2191a \u2191b :=\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 : \u2124\nh : \u2191a + \u2191b < (10 : \u211a)\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, `\u2191(a + b)` will be written to `\u2191a + \u2191b`.\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 : \u2115) (h1 : ((a + b : \u2115) : \u2124) = 10) (h2 : ((a + b + 0 : \u2115) : \u2124) = 10) :\n  ((a + b : \u2115) : \u2124) = 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<https://lean-forward.github.io/norm_cast/norm_cast.pdf>.\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 \u2192 b \u2192 a \u2227 b := by _\n\n-- example : a \u2192 b \u2192 a \u2227 b := by do\n--   eh1 \u2190 intro `h1,\n--   eh2 \u2190 intro `h2,\n--   target >>= trace\n\n-- example : a \u2192 b \u2192 a \u2227 b := by do\n--   eh1 \u2190 intro `h1,\n--   eh2 \u2190 intro `h2,\n--   local_context >>= trace\n\n-- example : a \u2192 b \u2192 a \u2227 b := by do\n--   intro `h1,\n--   intro `h2,\n--   ea \u2190 get_local `a,\n--   eb \u2190 get_local `b,\n--   trace (to_string ea ++ \", \" ++ to_string eb),\n--   skip\n\nexample : a \u2192 b \u2192 a \u2227 b := by do\n  eh1 \u2190 intro `h1,\n  eh2 \u2190 intro `h2,\n  mk_const ``and.intro >>= apply,\n    exact eh1,\n  exact eh2\n\nexample : a \u2192 b \u2192 a \u2227 b := by do\n  eh1 \u2190 intro `h1,\n  eh2 \u2190 intro `h2,\n  applyc ``and.intro,\n  exact eh1,\n  exact eh2\n\nexample : a \u2192 b \u2192 a \u2227 b :=\nby do eh1 \u2190 intro `h1,\n      eh2 \u2190 intro `h2,\n      e \u2190 to_expr ```(and.intro h1 h2),\n      exact e\n\nmeta def my_tactic : tactic unit :=\ndo eh1 \u2190 intro `h1,\n   eh2 \u2190 intro `h2,\n   e \u2190 to_expr ``(and.intro %%eh1 %%eh2),\n   exact e\n\nexample : a \u2192 b \u2192 a \u2227 b :=\nby my_tactic\n\nexample (a b : Prop) (h : a \u2227 b) : b \u2227 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 \u2192 a :=\nby do n \u2190 mk_fresh_name,\n      intro n,\n      hyp \u2190 get_local n,\n      exact hyp\n\nexample (a b : Prop) (h : a \u2227 b) : b \u2227 a :=\nby do split,\n   eh \u2190 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 \u2227 b) : b \u2227 a :=\nby do split,\n      ea \u2190 get_local `a,\n      eb \u2190 get_local `b,\n      eh \u2190 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 \u2227 b) : b \u2227 a :=\nby do split,\n      eh \u2190 get_local `h,\n      mk_app ``and.right [eh] >>= exact,\n      mk_app ``and.left [eh] >>= exact\n\nexample (a b : Prop) (h : a \u2227 b) : b \u2227 a :=\nby do split,\n      eh \u2190 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 \u2227 b) : b \u2227 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 \u2227 b) : b \u2227 a := by do\n  split,\n  eh \u2190 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 \u2192 list expr \u2192 tactic expr\n| e []         := failed\n| e (h :: hs) :=\n  do t \u2190 infer_type h,\n     (unify e t >> return h) <|> find_same_type e hs\n\nmeta def assumption : tactic unit :=\ndo ctx \u2190 local_context,\n   t   \u2190 target,\n   h   \u2190 find_same_type t ctx,\n   exact h\n<|> fail \"assumption tactic failed\"\n\nmeta def first {\u03b1 : Type} : list (tactic \u03b1) \u2192 tactic \u03b1\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 \u2190 local_context,\n  first $ l.map (\u03bb h, do\n    ht \u2190 infer_type h >>= whnf,\n    match ht with\n    | `(and %%a %%b) := do\n      n \u2190 get_unused_name `h none,\n      mk_mapp ``and.left [none, none, some h] >>= assertv n a,\n      n \u2190 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 \u2192 tactic unit \u2192 tactic unit\n| 0        t := skip\n| (succ n) t := (do t, repeat_at_most n t) <|> skip\n\nmeta def repeat : tactic unit \u2192 tactic unit :=\nrepeat_at_most 100000\n\nend hidden\n\nset_option pp.beta false\n\nsection\n  variables {\u03b1 : Type} (a b : \u03b1)\n\n  example : (\u03bb x : \u03b1, a) b = a :=\n  by do goal \u2190 target,\n        match expr.is_eq goal with\n        | (some (e\u2081, e\u2082)) := do trace e\u2081,\n                                whnf e\u2081 >>= trace,\n                                reflexivity\n        | none            := failed\n        end\n\n  example : (\u03bb x : \u03b1, a) b = a :=\n  by do goal \u2190 target,\n        match expr.is_eq goal with\n        | (some (e\u2081, e\u2082)) := do trace e\u2081,\n                                whnf e\u2081 transparency.none >>= trace,\n                                reflexivity\n        | none            := failed\n        end\n\n  attribute [reducible]\n  definition foo (a b : \u03b1) : \u03b1 := a\n\n  example : foo a b = a :=\n  by do goal \u2190 target,\n        match expr.is_eq goal with\n        | (some (e\u2081, e\u2082)) := do trace e\u2081,\n                                whnf e\u2081 transparency.none >>= trace,\n                                reflexivity\n        | none            := failed\n        end\n\n  example : foo a b = a :=\n  by do goal \u2190 target,\n        match expr.is_eq goal with\n        | (some (e\u2081, e\u2082)) := do trace e\u2081,\n                                whnf e\u2081 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 \u2192 String\n| atom s => atomToString s\n| slist ss => \"(\" ++ listToString ss ++ \")\"\n\ndef listToString : List Sexp \u2192 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 \u2192 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 \" \u2295 \" r:term:11 : term => `((!$l && $r) || ($l && !$r))\n\n#eval true \u2295 true -- false\n#eval true \u2295 false -- true\n#eval false \u2295 true -- true\n#eval false \u2295 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 := \u27e8s.raw\u27e9\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 \u2192 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 \u00d7 Nat\n#check cut_tuple (1, 2, 3) -- (2, 3) : Nat \u00d7 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<actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes>\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 \u2192 Type) where\n  getRef      : m Syntax\n  withRef {\u03b1} : Syntax \u2192 m \u03b1 \u2192 m \u03b1\n\nclass MonadQuotation (m : Type \u2192 Type) extends MonadRef m where\n  getCurrMacroScope : m MacroScope\n  getMainModule     : m Name\n  withFreshMacroScope {\u03b1 : Type} : m \u03b1 \u2192 m \u03b1\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 \u03b1` 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 \u03b1` 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 (\u03b1 : Type u) := \u03b1 \u2192 Prop\ndef Set.mem (x : \u03b1) (X : Set \u03b1) : Prop := X x\n\n-- Integrate into the already existing typeclass for membership notation\ninstance : Membership \u03b1 (Set \u03b1) where\n  mem := Set.mem\n\ndef Set.empty : Set \u03b1 := \u03bb _ => False\n\n-- the basic \"all elements such that\" function for the notation\ndef setOf {\u03b1 : Type} (p : \u03b1 \u2192 Prop) : Set \u03b1 := p\n\n/-!\nThe goal for this section will be to allow for both `{x : X | p x}`\nand `{x \u2208 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 `\u03a3` or `\u03a0` 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 \" \u2208 \" 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 \u2208 $s:term | $body:term }) => `(setOf (fun $var => $var \u2208 $s \u2227 $body))\n\n-- Old examples with better syntax:\n#check { x : Nat | x \u2264 1 } -- setOf fun x => x \u2264 1 : Set Nat\n\nexample : 1 \u2208 { y : Nat | y \u2264 1 } := by simp[Membership.mem, Set.mem, setOf]\nexample : 2 \u2208 { y : Nat | y \u2264 3 \u2227 1 \u2264 y } := by simp[Membership.mem, Set.mem, setOf]\n\n-- New examples:\ndef oneSet : Set Nat := \u03bb x => x = 1\n#check { x \u2208 oneSet | 10 \u2264 x } -- setOf fun x => x \u2208 oneSet \u2227 10 \u2264 x : Set Nat\n\nexample : \u2200 x, \u00ac(x \u2208 { y \u2208 oneSet | y \u2260 1 }) := by\n  intro x h\n  -- h : x \u2208 setOf fun y => y \u2208 oneSet \u2227 y \u2260 1\n  -- \u22a2 False\n  cases h\n  -- : x \u2208 oneSet\n  -- : x \u2260 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": "/-\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, S\u00e9bastien Gou\u00ebzel, Scott Morrison\n\n! This file was ported from Lean 3 source module tactic.interactive\n! leanprover-community/mathlib commit f89fa08bb6455c96c58e860902fadc8eb2c854ed\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Logic.Nonempty\nimport Mathbin.Tactic.Lint.Default\nimport Mathbin.Tactic.Dependencies\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nnamespace Tactic\n\nnamespace Interactive\n\nopen Interactive Interactive.Types Expr\n\n/-- Similar to `constructor`, but does not reorder goals. -/\nunsafe def fconstructor : tactic Unit :=\n  concat_tags tactic.fconstructor\n#align tactic.interactive.fconstructor tactic.interactive.fconstructor\n\nadd_tactic_doc\n  { Name := \"fconstructor\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.fconstructor]\n    tags := [\"logic\", \"goal management\"] }\n\n/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.\nNever fails. Useful for debugging. -/\nunsafe def try_for (max : parse parser.pexpr) (tac : itactic) : tactic Unit := do\n  let max \u2190 i_to_expr_strict max >>= tactic.eval_expr Nat\n  fun s =>\n    match _root_.try_for max (tac s) with\n    | some r => r\n    | none => (tactic.trace \"try_for timeout, using sorry\" >> tactic.admit) s\n#align tactic.interactive.try_for tactic.interactive.try_for\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/\nunsafe def substs (l : parse (parser.many ident)) : tactic Unit :=\n  propagate_tags <|\n    (l.mapM' fun h => get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)\n#align tactic.interactive.substs tactic.interactive.substs\n\nadd_tactic_doc\n  { Name := \"substs\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.substs]\n    tags := [\"rewriting\"] }\n\n/-- Unfold coercion-related definitions -/\nunsafe def unfold_coes (loc : parse location) : tactic Unit :=\n  unfold\n    [`` coe, `` coeT, `` CoeTC.coe, `` coeB, `` Coe.coe, `` lift, `` HasLift.lift, `` liftT,\n      `` HasLiftT.lift, `` coeFn, `` CoeFun.coe, `` coeSort, `` CoeSort.coe]\n    loc\n#align tactic.interactive.unfold_coes tactic.interactive.unfold_coes\n\nadd_tactic_doc\n  { Name := \"unfold_coes\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.unfold_coes]\n    tags := [\"simplification\"] }\n\n/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/\nunsafe def unfold_wf :=\n  propagate_tags (andthen well_founded_tactics.unfold_wf_rel well_founded_tactics.unfold_sizeof)\n#align tactic.interactive.unfold_wf tactic.interactive.unfold_wf\n\n/-- Unfold auxiliary definitions associated with the current declaration. -/\nunsafe def unfold_aux : tactic Unit := do\n  let tgt \u2190 target\n  let name \u2190 decl_name\n  let to_unfold := tgt.list_names_with_prefix Name\n  guard \u00acto_unfold\n  -- should we be using simp_lemmas.mk_default?\n        simp_lemmas.mk\n        to_unfold tgt >>=\n      tactic.change\n#align tactic.interactive.unfold_aux tactic.interactive.unfold_aux\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\". -/\nunsafe def recover : tactic Unit :=\n  metavariables >>= tactic.set_goals\n#align tactic.interactive.recover tactic.interactive.recover\n\n/-- Like `try { tac }`, but in the case of failure it continues\nfrom the failure state instead of reverting to the original state. -/\nunsafe def continue (tac : itactic) : tactic Unit := fun s =>\n  result.cases_on (tac s) (fun a => result.success ()) fun e ref => result.success ()\n#align tactic.interactive.continue tactic.interactive.continue\n\n/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without\nrequiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a\nnon-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/\n@[inline]\nprotected unsafe def id (tac : itactic) : tactic Unit :=\n  tac\n#align tactic.interactive.id tactic.interactive.id\n\n/-- `work_on_goal n { tac }` creates a block scope for the `n`-goal,\nand does not require that the goal be solved at the end\n(any remaining subgoals are inserted back into the list of goals).\n\nTypically usage might look like:\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 3\n{ dsimp,\n  simp },\nrefl\n````\n\nSee also `id { tac }`, which is equivalent to `work_on_goal 1 { tac }`.\n-/\nunsafe def work_on_goal : parse small_nat \u2192 itactic \u2192 tactic Unit\n  | 0, t => fail \"work_on_goal failed: goals are 1-indexed\"\n  | n + 1, t => do\n    let goals \u2190 get_goals\n    let earlier_goals := goals.take n\n    let later_goals := goals.drop (n + 1)\n    set_goals (goals n).toList\n    t\n    let new_goals \u2190 get_goals\n    set_goals (earlier_goals ++ new_goals ++ later_goals)\n#align tactic.interactive.work_on_goal tactic.interactive.work_on_goal\n\n/-- `swap n` will move the `n`th goal to the front.\n`swap` defaults to `swap 2`, and so interchanges the first and second goals.\n\nSee also `tactic.interactive.rotate`, which moves the first `n` goals to the back.\n-/\nunsafe def swap (n := 2) : tactic Unit := do\n  let gs \u2190 get_goals\n  match gs (n - 1) with\n    | some g => set_goals (g :: gs (n - 1))\n    | _ => skip\n#align tactic.interactive.swap tactic.interactive.swap\n\nadd_tactic_doc\n  { Name := \"swap\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.swap]\n    tags := [\"goal management\"] }\n\n/-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times.\n\nSee also `tactic.interactive.swap`, which moves the `n`th goal to the front.\n-/\nunsafe def rotate (n := 1) : tactic Unit :=\n  tactic.rotate n\n#align tactic.interactive.rotate tactic.interactive.rotate\n\nadd_tactic_doc\n  { Name := \"rotate\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.rotate]\n    tags := [\"goal management\"] }\n\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\nunsafe def clear_ : tactic Unit :=\n  tactic.repeat do\n    let l \u2190 local_context\n    l fun h => do\n        let Name.mk_string s p \u2190 return <| local_pp_name h\n        guard (s = '_')\n        let cl \u2190 infer_type h >>= is_class\n        guard \u00accl\n        tactic.clear h\n#align tactic.interactive.clear_ tactic.interactive.clear_\n\nadd_tactic_doc\n  { Name := \"clear_\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.clear_]\n    tags := [\"context management\"] }\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/-- Acts like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nunsafe def replace (h : parse (parser.optional ident))\n    (q\u2081 : parse (parser.optional (tk \":\" *> texpr)))\n    (q\u2082 : parse <| parser.optional (tk \":=\" *> texpr)) : tactic Unit := do\n  let h := h.getD `this\n  let old \u2190 try_core (get_local h)\n  have h q\u2081 q\u2082\n  match old, q\u2082 with\n    | none, _ => skip\n    | some o, some _ => tactic.clear o\n    | some o, none => (swap >> tactic.clear o) >> swap\n#align tactic.interactive.replace tactic.interactive.replace\n\nadd_tactic_doc\n  { Name := \"replace\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.replace]\n    tags := [\"context management\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- Make every proposition in the context decidable.\n\n`classical!` does this more aggressively, such that even if a decidable instance is already\navailable for a specific proposition, the noncomputable one will be used instead. -/\nunsafe def classical (bang : parse <| parser.optional (tk \"!\")) :=\n  tactic.classical bang.isSome\n#align tactic.interactive.classical tactic.interactive.classical\n\nadd_tactic_doc\n  { Name := \"classical\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.classical]\n    tags := [\"classical logic\", \"type class\"] }\n\nprivate unsafe def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 Name)\n  | app (app (macro _ [const `eq _]) h) (local_const x _ _ _) => pure (h, x)\n  | _ => fail \"parse error\"\n#align tactic.interactive.generalize_arg_p_aux tactic.interactive.generalize_arg_p_aux\n\nprivate unsafe def generalize_arg_p : parser (pexpr \u00d7 Name) :=\n  with_desc \"expr = id\" <| parser.pexpr 0 >>= generalize_arg_p_aux\n#align tactic.interactive.generalize_arg_p tactic.interactive.generalize_arg_p\n\n@[nolint def_lemma]\nnoncomputable theorem generalizeAAux.{u} {\u03b1 : Sort u} (h : \u2200 x : Sort u, (\u03b1 \u2192 x) \u2192 x) : \u03b1 :=\n  h \u03b1 id\n#align tactic.interactive.generalize_a_aux Tactic.Interactive.generalizeAAux\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- Like `generalize` but also considers assumptions\nspecified by the user. The user can also specify to\nomit the goal.\n-/\nunsafe def generalize_hyp (h : parse (parser.optional ident)) (_ : parse <| tk \":\")\n    (p : parse generalize_arg_p) (l : parse location) : tactic Unit := do\n  let h' \u2190 get_unused_name `h\n  let x' \u2190 get_unused_name `x\n  let g \u2190\n    if \u00acl.include_goal then do\n        refine ``(generalizeAAux _)\n        some <$> (Prod.mk <$> tactic.intro x' <*> tactic.intro h')\n      else pure none\n  let n \u2190 l.get_locals >>= tactic.revert_lst\n  generalize h () p\n  intron n\n  match g with\n    | some (x', h') => do\n      tactic.apply h'\n      tactic.clear h'\n      tactic.clear x'\n    | none => return ()\n#align tactic.interactive.generalize_hyp tactic.interactive.generalize_hyp\n\nadd_tactic_doc\n  { Name := \"generalize_hyp\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.generalize_hyp]\n    tags := [\"context management\"] }\n\nunsafe def compact_decl_aux :\n    List Name \u2192 BinderInfo \u2192 expr \u2192 List expr \u2192 tactic (List (List Name \u00d7 BinderInfo \u00d7 expr))\n  | ns, bi, t, [] => pure [(ns.reverse, bi, t)]\n  | ns, bi, t, v'@(local_const n pp bi' t') :: xs => do\n    let t' \u2190 infer_type v'\n    if bi = bi' \u2227 t = t' then compact_decl_aux (pp :: ns) bi t xs\n      else do\n        let vs \u2190 compact_decl_aux [pp] bi' t' xs\n        pure <| (ns, bi, t) :: vs\n  | ns, bi, t, _ :: xs => compact_decl_aux ns bi t xs\n#align tactic.interactive.compact_decl_aux tactic.interactive.compact_decl_aux\n\n/-- go from (x\u2080 : t\u2080) (x\u2081 : t\u2080) (x\u2082 : t\u2080) to (x\u2080 x\u2081 x\u2082 : t\u2080) -/\nunsafe def compact_decl : List expr \u2192 tactic (List (List Name \u00d7 BinderInfo \u00d7 expr))\n  | [] => pure []\n  | v@(local_const n pp bi t) :: xs => do\n    let t \u2190 infer_type v\n    compact_decl_aux [pp] bi t xs\n  | _ :: xs => compact_decl xs\n#align tactic.interactive.compact_decl tactic.interactive.compact_decl\n\n/-- Remove 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.\n-/\nunsafe def clean (q : parse texpr) : tactic Unit := do\n  let tgt : expr \u2190 target\n  let e \u2190 i_to_expr_strict ``(($(q) : $(tgt)))\n  tactic.exact <| e\n#align tactic.interactive.clean tactic.interactive.clean\n\nunsafe def source_fields (missing : List Name) (e : pexpr) : tactic (List (Name \u00d7 pexpr)) := do\n  let e \u2190 to_expr e\n  let t \u2190 infer_type e\n  let struct_n : Name := t.get_app_fn.const_name\n  let fields \u2190 expanded_field_list struct_n\n  let exp_fields := fields.filter\u2093 fun x => x.2 \u2208 missing\n  exp_fields fun \u27e8p, n\u27e9 => (Prod.mk n \u2218 to_pexpr) <$> mk_mapp (n p) [none, some e]\n#align tactic.interactive.source_fields tactic.interactive.source_fields\n\nunsafe def collect_struct' : pexpr \u2192 StateT (List <| expr \u00d7 structure_instance_info) tactic pexpr\n  | e => do\n    let some str \u2190 pure e.get_structure_instance_info |\n      e.traverse collect_struct'\n    let v \u2190 monadLift mk_mvar\n    modify (List.cons (v, str))\n    pure <| to_pexpr v\n#align tactic.interactive.collect_struct' tactic.interactive.collect_struct'\n\nunsafe def collect_struct (e : pexpr) : tactic <| pexpr \u00d7 List (expr \u00d7 structure_instance_info) :=\n  Prod.map id List.reverse <$> (collect_struct' e).run []\n#align tactic.interactive.collect_struct tactic.interactive.collect_struct\n\nunsafe def refine_one (str : structure_instance_info) :\n    tactic <| List (expr \u00d7 structure_instance_info) := do\n  let tgt \u2190 target >>= whnf\n  let struct_n : Name := tgt.get_app_fn.const_name\n  let exp_fields \u2190 expanded_field_list struct_n\n  let missing_f := exp_fields.filter\u2093 fun f => (f.2 : Name) \u2209 str.field_names\n  let (src_field_names, src_field_vals) \u2190\n    (@List.unzip Name _ \u2218 List.join) <$> str.sources.mapM (source_fields <| missing_f.map Prod.snd)\n  let provided := exp_fields.filter\u2093 fun f => (f.2 : Name) \u2208 str.field_names\n  let missing_f' := missing_f.filter\u2093 fun x => x.2 \u2209 src_field_names\n  let vs \u2190 mk_mvar_list missing_f'.length\n  let (field_values, new_goals) \u2190 List.unzip <$> (str.field_values.mapM collect_struct : tactic _)\n  let e' \u2190\n    to_expr <|\n        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  let gs \u2190\n    with_enable_tags\n        (zipWithM\n          (fun (n : Name \u00d7 Name) v => do\n            set_goals [v]\n            try (dsimp_target simp_lemmas.mk)\n            apply_auto_param <|> apply_opt_param <|> set_main_tag [`_field, n.2, n.1]\n            get_goals)\n          missing_f' vs)\n  set_goals gs\n  return new_goals\n#align tactic.interactive.refine_one tactic.interactive.refine_one\n\nunsafe def refine_recursively : expr \u00d7 structure_instance_info \u2192 tactic (List expr)\n  | (e, str) => do\n    set_goals [e]\n    let rs \u2190 refine_one str\n    let gs \u2190 get_goals\n    let gs' \u2190 rs.mapM refine_recursively\n    return <| gs' ++ gs\n#align tactic.interactive.refine_recursively tactic.interactive.refine_recursively\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 of semigroup\ninstances:\n\n```lean\nrefine_struct ( { .. } : semigroup \u03b1 ),\n-- case semigroup, mul\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nunsafe def refine_struct : parse texpr \u2192 tactic Unit\n  | e => do\n    let (x, xs) \u2190 collect_struct e\n    refine x\n    let gs \u2190 get_goals\n    let xs' \u2190 xs.mapM refine_recursively\n    set_goals (xs' ++ gs)\n#align tactic.interactive.refine_struct tactic.interactive.refine_struct\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-/\nunsafe def guard_hyp' (n : parse ident) (p : parse <| tk \":\" *> texpr) : tactic Unit := do\n  let h \u2190 get_local n >>= infer_type >>= instantiate_mvars\n  guard_expr_eq h p\n#align tactic.interactive.guard_hyp' tactic.interactive.guard_hyp'\n\n/--\n`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).\nWe use this tactic for writing tests.\n-/\nunsafe def match_hyp (n : parse ident) (p : parse <| tk \":\" *> texpr) (m := reducible) :\n    tactic (List expr) := do\n  let h \u2190 get_local n >>= infer_type >>= instantiate_mvars\n  match_expr p h m\n#align tactic.interactive.match_hyp tactic.interactive.match_hyp\n\n/-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast\nto `guard_expr`, this tests strict (syntactic) equality.\nWe use this tactic for writing tests.\n-/\nunsafe def guard_expr_strict (t : expr) (p : parse <| tk \":=\" *> texpr) : tactic Unit := do\n  let e \u2190 to_expr p\n  guard (t = e)\n#align tactic.interactive.guard_expr_strict tactic.interactive.guard_expr_strict\n\n/-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`.\nWe use this tactic for writing tests.\n-/\nunsafe def guard_target_strict (p : parse texpr) : tactic Unit := do\n  let t \u2190 target\n  guard_expr_strict t p\n#align tactic.interactive.guard_target_strict tactic.interactive.guard_target_strict\n\n/-- `guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal\nto `t`.\nWe use this tactic for writing tests.\n-/\nunsafe def guard_hyp_strict (n : parse ident) (p : parse <| tk \":\" *> texpr) : tactic Unit := do\n  let h \u2190 get_local n >>= infer_type >>= instantiate_mvars\n  guard_expr_strict h p\n#align tactic.interactive.guard_hyp_strict tactic.interactive.guard_hyp_strict\n\n/-- Tests that there are `n` hypotheses in the current context. -/\nunsafe def guard_hyp_nums (n : \u2115) : tactic Unit := do\n  let k \u2190 local_context\n  guard (n = k) <|> fail f! \"{k} hypotheses found\"\n#align tactic.interactive.guard_hyp_nums tactic.interactive.guard_hyp_nums\n\n/-- `guard_hyp_mod_implicit h : t` fails if the type of the hypothesis `h`\nis not definitionally equal to `t` modulo none transparency\n(i.e., unifying the implicit arguments modulo semireducible transparency).\nWe use this tactic for writing tests.\n-/\nunsafe def guard_hyp_mod_implicit (n : parse ident) (p : parse <| tk \":\" *> texpr) : tactic Unit :=\n  do\n  let h \u2190 get_local n >>= infer_type >>= instantiate_mvars\n  let e \u2190 to_expr p\n  is_def_eq h e transparency.none\n#align tactic.interactive.guard_hyp_mod_implicit tactic.interactive.guard_hyp_mod_implicit\n\n/-- `guard_target_mod_implicit t` fails if the target of the main goal\nis not definitionally equal to `t` modulo none transparency\n(i.e., unifying the implicit arguments modulo semireducible transparency).\nWe use this tactic for writing tests.\n-/\nunsafe def guard_target_mod_implicit (p : parse texpr) : tactic Unit := do\n  let tgt \u2190 target\n  let e \u2190 to_expr p\n  is_def_eq tgt e transparency.none\n#align tactic.interactive.guard_target_mod_implicit tactic.interactive.guard_target_mod_implicit\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- Test that `t` is the tag of the main goal. -/\nunsafe def guard_tags (tags : parse (parser.many ident)) : tactic Unit := do\n  let (t : List Name) \u2190 get_main_tag\n  guard (t = tags)\n#align tactic.interactive.guard_tags tactic.interactive.guard_tags\n\n/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term\n  unifies with `p`. -/\nunsafe def guard_proof_term (t : itactic) (p : parse texpr) : itactic := do\n  let g :: _ \u2190 get_goals\n  let e \u2190 to_expr p\n  t\n  let g \u2190 instantiate_mvars g\n  unify e g\n#align tactic.interactive.guard_proof_term tactic.interactive.guard_proof_term\n\n/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with\nerror message `msg` (for test writing purposes). -/\nunsafe def success_if_fail_with_msg (tac : tactic.interactive.itactic) :=\n  tactic.success_if_fail_with_msg tac\n#align tactic.interactive.success_if_fail_with_msg tactic.interactive.success_if_fail_with_msg\n\n/-- Get the field of the current goal. -/\nunsafe def get_current_field : tactic Name := do\n  let [_, Field, str] \u2190 get_main_tag\n  expr.const_name <$> resolve_name (Field str)\n#align tactic.interactive.get_current_field tactic.interactive.get_current_field\n\nunsafe def field (n : parse ident) (tac : itactic) : tactic Unit := do\n  let gs \u2190 get_goals\n  let ts \u2190 gs.mapM get_tag\n  let ([g], gs') \u2190 pure <| (List.zip gs ts).partition\u2093 fun x => x.snd.get? 1 = some n\n  set_goals [g.1]\n  tac\n  done\n  set_goals <| gs' Prod.fst\n#align tactic.interactive.field tactic.interactive.field\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nunsafe def have_field : tactic Unit :=\n  propagate_tags <| (get_current_field >>= mk_const >>= note `field none) >> return ()\n#align tactic.interactive.have_field tactic.interactive.have_field\n\n/-- `apply_field` functions as `have_field, apply field, clear field` -/\nunsafe def apply_field : tactic Unit :=\n  propagate_tags <| get_current_field >>= applyc\n#align tactic.interactive.apply_field tactic.interactive.apply_field\n\nadd_tactic_doc\n  { Name := \"refine_struct\"\n    category := DocCategory.tactic\n    declNames :=\n      [`tactic.interactive.refine_struct, `tactic.interactive.apply_field,\n        `tactic.interactive.have_field]\n    tags := [\"structures\"]\n    inheritDescriptionFrom := `tactic.interactive.refine_struct }\n\n/-- `apply_rules hs with attrs n` applies the list of lemmas `hs` and all lemmas tagged with an\nattribute from the list `attrs`, as well as the `assumption` tactic on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is optional, equal to 50 by default.\nYou can pass an `apply_cfg` option argument as `apply_rules hs n opt`.\n(A typical usage would be with `apply_rules hs n { md := reducible }`,\nwhich asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)\nwhen checking if a lemma matches the goal.)\n\nFor instance:\n\n```lean\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 b + d * e + b + d + e :=\n-- any of the following lines solve the goal:\nadd_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\nby apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\nby apply_rules with mono_rules\nby apply_rules [add_le_add] with mono_rules\n```\n-/\nunsafe def apply_rules (args : parse opt_pexpr_list) (attrs : parse with_ident_list) (n : Nat := 50)\n    (opt : ApplyCfg := { }) : tactic Unit :=\n  tactic.apply_rules args attrs n opt\n#align tactic.interactive.apply_rules tactic.interactive.apply_rules\n\nadd_tactic_doc\n  { Name := \"apply_rules\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.apply_rules]\n    tags := [\"lemma application\"] }\n\nunsafe def return_cast (f : Option expr) (t : Option (expr \u00d7 expr)) (es : List (expr \u00d7 expr \u00d7 expr))\n    (e x x' eq_h : expr) : tactic (Option (expr \u00d7 expr) \u00d7 List (expr \u00d7 expr \u00d7 expr)) :=\n  (do\n      guard \u00ace\n      unify x x'\n      let u \u2190 mk_meta_univ\n      let f \u2190 f <|> mk_mapp `` _root_.id [(expr.sort u : expr)]\n      let t' \u2190 infer_type e\n      let some (f', t) \u2190 pure t |\n        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)) <|>\n    return (t, es)\n#align tactic.interactive.return_cast tactic.interactive.return_cast\n\nunsafe def list_cast_of_aux (x : expr) (t : Option (expr \u00d7 expr)) (es : List (expr \u00d7 expr \u00d7 expr)) :\n    expr \u2192 tactic (Option (expr \u00d7 expr) \u00d7 List (expr \u00d7 expr \u00d7 expr))\n  | e@q(cast $(eq_h) $(x')) => return_cast none t es e x x' eq_h\n  | e@q(Eq.mp $(eq_h) $(x')) => return_cast none t es e x x' eq_h\n  | e@q(Eq.mpr $(eq_h) $(x')) => mk_eq_symm eq_h >>= return_cast none t es e x x'\n  | e@q(@Eq.subst $(\u03b1) $(p) $(a) $(b) $(eq_h) $(x')) => return_cast p t es e x x' eq_h\n  | e@q(@Eq.substr $(\u03b1) $(p) $(a) $(b) $(eq_h) $(x')) =>\n    mk_eq_symm eq_h >>= return_cast p t es e x x'\n  | e@q(@Eq.ndrec $(\u03b1) $(a) $(f) $(x') _ $(eq_h)) => return_cast f t es e x x' eq_h\n  | e@q(@Eq.recOn $(\u03b1) $(a) $(f) $(b) $(eq_h) $(x')) => return_cast f t es e x x' eq_h\n  | e => return (t, es)\n#align tactic.interactive.list_cast_of_aux tactic.interactive.list_cast_of_aux\n\nunsafe def list_cast_of (x tgt : expr) : tactic (List (expr \u00d7 expr \u00d7 expr)) :=\n  (List.reverse \u2218 Prod.snd) <$> tgt.mfold (none, []) fun e i es => list_cast_of_aux x es.1 es.2 e\n#align tactic.interactive.list_cast_of tactic.interactive.list_cast_of\n\nprivate unsafe def h_generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 Name)\n  | app (app (macro _ [const `heq _]) h) (local_const x _ _ _) => pure (h, x)\n  | _ => fail \"parse error\"\n#align tactic.interactive.h_generalize_arg_p_aux tactic.interactive.h_generalize_arg_p_aux\n\nprivate unsafe def h_generalize_arg_p : parser (pexpr \u00d7 Name) :=\n  with_desc \"expr == id\" <| parser.pexpr 0 >>= h_generalize_arg_p_aux\n#align tactic.interactive.h_generalize_arg_p tactic.interactive.h_generalize_arg_p\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/-- `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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`;\n- `h_generalize Hx : e == x with _` chooses automatically chooses the name of\n  assumption `\u03b1 = \u03b2`;\n- `h_generalize! Hx : e == x` reverts `Hx`;\n- when `Hx` is omitted, assumption `Hx : e == x` is not added.\n-/\nunsafe def h_generalize (rev : parse (parser.optional (tk \"!\")))\n    (h : parse (parser.optional ident_)) (_ : parse (tk \":\")) (arg : parse h_generalize_arg_p)\n    (eqs_h : parse (tk \"with\" *> pure <$> ident_ <|> pure [])) : tactic Unit := do\n  let (e, n) := arg\n  let h' := if h = `_ then none else h\n  let h' \u2190 (h' : tactic Name) <|> get_unused_name (\"h\" ++ n.toString : String)\n  let e \u2190 to_expr e\n  let tgt \u2190 target\n  let (e, x, eq_h) :: es \u2190 list_cast_of e tgt |\n    fail \"no cast found\"\n  interactive.generalize h' () (to_pexpr e, n)\n  let asm \u2190 get_local h'\n  let v \u2190 get_local n\n  let hs \u2190 es.mapM fun \u27e8e, _\u27e9 => mk_app `eq [e, v]\n  (eqs_h [e]).mapM' fun \u27e8h, e\u27e9 => do\n      let h \u2190 if h \u2260 `_ then pure h else get_unused_name `h\n      () <$ note h none eq_h\n  hs fun h => do\n      let h' \u2190 assert `h h\n      tactic.exact asm\n      try (rewrite_target h')\n      tactic.clear h'\n  when h do\n      ((to_expr ``(hEq_of_eq_rec_left $(eq_h) $(asm)) <|>\n              to_expr ``(heq_of_cast_eq $(eq_h) $(asm))) >>=\n            note h' none) >>\n          pure ()\n  tactic.clear asm\n  when rev (interactive.revert [n])\n#align tactic.interactive.h_generalize tactic.interactive.h_generalize\n\nadd_tactic_doc\n  { Name := \"h_generalize\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.h_generalize]\n    tags := [\"context management\"] }\n\n/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that\n  this uses definitional equality instead of alpha-equivalence. -/\nunsafe def guard_expr_eq' (t : expr) (p : parse <| tk \":=\" *> texpr) : tactic Unit := do\n  let e \u2190 to_expr p\n  is_def_eq t e\n#align tactic.interactive.guard_expr_eq' tactic.interactive.guard_expr_eq'\n\n/-- `guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.\nWe use this tactic for writing tests.\nThe difference with `guard_target` is that this uses definitional equality instead of\nalpha-equivalence.\n-/\nunsafe def guard_target' (p : parse texpr) : tactic Unit := do\n  let t \u2190 target\n  guard_expr_eq' t p\n#align tactic.interactive.guard_target' tactic.interactive.guard_target'\n\nadd_tactic_doc\n  { Name := \"guard_target'\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.guard_target']\n    tags := [\"testing\"] }\n\n/-- Tries to solve the goal using a canonical proof of `true` or the `reflexivity` tactic.\nUnlike `trivial` or `trivial'`, does not the `contradiction` tactic.\n-/\nunsafe def triv : tactic Unit :=\n  tactic.triv <|> tactic.reflexivity <|> fail \"triv tactic failed\"\n#align tactic.interactive.triv tactic.interactive.triv\n\nadd_tactic_doc\n  { Name := \"triv\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.triv]\n    tags := [\"finishing\"] }\n\n/--\nA weaker version of `trivial` that tries to solve the goal using a canonical proof of `true` or the\n`reflexivity` tactic (unfolding only `reducible` constants, so can fail faster than `trivial`),\nand otherwise tries the `contradiction` tactic. -/\nunsafe def trivial' : tactic Unit :=\n  tactic.triv' <|>\n    tactic.reflexivity reducible <|> tactic.contradiction <|> fail \"trivial' tactic failed\"\n#align tactic.interactive.trivial' tactic.interactive.trivial'\n\nadd_tactic_doc\n  { Name := \"trivial'\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.trivial']\n    tags := [\"finishing\"] }\n\n/-- Similar to `existsi`. `use x` will instantiate the first term of an `\u2203` or `\u03a3` goal with `x`. It\nwill then try to close the new goal using `trivial'`, or try to simplify it by applying\n`exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type.\n`use` will alternatively take a list of terms `[x0, ..., xn]`.\n\n`use` will work with constructors of arbitrary inductive types.\n\nExamples:\n```lean\nexample (\u03b1 : Type) : \u2203 S : set \u03b1, S = S :=\nby use \u2205\n\nexample : \u2203 x : \u2124, x = x :=\nby use 42\n\nexample : \u2203 n > 0, n = n :=\nbegin\n  use 1,\n  -- goal is now 1 > 0 \u2227 1 = 1, whereas it would be \u2203 (H : 1 > 0), 1 = 1 after existsi 1.\n  exact \u27e8zero_lt_one, rfl\u27e9,\nend\n\nexample : \u2203 a b c : \u2124, a + b + c = 6 :=\nby use [1, 2, 3]\n\nexample : \u2203 p : \u2124 \u00d7 \u2124, p.1 = 1 :=\nby use \u27e81, 42\u27e9\n\nexample : \u03a3 x y : \u2124, (\u2124 \u00d7 \u2124) \u00d7 \u2124 :=\nby use [1, 2, 3, 4, 5]\n\ninductive foo\n| mk : \u2115 \u2192 bool \u00d7 \u2115 \u2192 \u2115 \u2192 foo\n\nexample : foo :=\nby use [100, tt, 4, 3]\n```\n-/\nunsafe def use (l : parse pexpr_list_or_texpr) : tactic Unit :=\n  focus1 <|\n    andthen (tactic.use l)\n      (try\n        (trivial' <|> do\n          let q(Exists $(p)) \u2190 target\n          (to_expr ``(exists_prop.mpr) >>= tactic.apply) >> skip))\n#align tactic.interactive.use tactic.interactive.use\n\nadd_tactic_doc\n  { Name := \"use\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.use, `tactic.interactive.existsi]\n    tags := [\"logic\"]\n    inheritDescriptionFrom := `tactic.interactive.use }\n\n/-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal.\nThis includes the induction hypothesis when using the equation compiler and\n`_let_match` and `_fun_match`.\n\nIt is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these\nauxiliary declarations, and produce an error saying the recursion is not well founded.\n\n```lean\nexample (n m : \u2115) (h\u2081 : n = m) (h\u2082 : \u2203 a : \u2115, a = n \u2227 a = m) : 2 * m = 2 * n :=\nlet \u27e8a, ha\u27e9 := h\u2082 in\nbegin\n  clear_aux_decl, -- subst will fail without this line\n  subst h\u2081\nend\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl, -- finish produces an error without this line\n  finish\nend\n```\n-/\nunsafe def clear_aux_decl : tactic Unit :=\n  tactic.clear_aux_decl\n#align tactic.interactive.clear_aux_decl tactic.interactive.clear_aux_decl\n\nadd_tactic_doc\n  { Name := \"clear_aux_decl\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl]\n    tags := [\"context management\"]\n    inheritDescriptionFrom := `tactic.interactive.clear_aux_decl }\n\nunsafe def loc.get_local_pp_names : Loc \u2192 tactic (List Name)\n  | loc.wildcard => List.map expr.local_pp_name <$> local_context\n  | loc.ns l => return l.reduceOption\n#align tactic.interactive.loc.get_local_pp_names tactic.interactive.loc.get_local_pp_names\n\nunsafe def loc.get_local_uniq_names (l : Loc) : tactic (List Name) :=\n  List.map expr.local_uniq_name <$> l.get_locals\n#align tactic.interactive.loc.get_local_uniq_names tactic.interactive.loc.get_local_uniq_names\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- The logic of `change x with y at l` fails when there are dependencies.\n`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.\nIn this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses\nin `l`. As long as `x` and `y` are defeq, it should never fail.\n-/\nunsafe def change' (q : parse texpr) :\n    parse (parser.optional (tk \"with\" *> texpr)) \u2192 parse location \u2192 tactic Unit\n  | none, loc.ns [none] => do\n    let e \u2190 i_to_expr q\n    change_core e none\n  | none, loc.ns [some h] => do\n    let eq \u2190 i_to_expr q\n    let eh \u2190 get_local h\n    change_core Eq (some eh)\n  | none, _ => fail \"change-at does not support multiple locations\"\n  | some w, l => do\n    let l' \u2190 loc.get_local_pp_names l\n    l' fun e => try (change_with_at q w e)\n    when l <| change q w (loc.ns [none])\n#align tactic.interactive.change' tactic.interactive.change'\n\nadd_tactic_doc\n  { Name := \"change'\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.change', `tactic.interactive.change]\n    tags := [\"renaming\"]\n    inheritDescriptionFrom := `tactic.interactive.change' }\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 -/\nprivate unsafe def opt_dir_with : parser (Option (Bool \u00d7 Name)) :=\n  parser.optional\n    (tk \"with\" *>\n      ((fun arrow h => (Option.isSome arrow, h)) <$> parser.optional (tk \"<-\") <*> ident))\n#align tactic.interactive.opt_dir_with tactic.interactive.opt_dir_with\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/-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to\nthe local context and replaces `t` with `a` everywhere it can.\n\n`set a := t with \u2190h` will add `h : t = a` instead.\n\n`set! a := t with h` does not do any replacing.\n\n```lean\nexample (x : \u2115) (h : x = 3)  : x + x + x = 9 :=\nbegin\n  set y := x with \u2190h_xy,\n/-\nx : \u2115,\ny : \u2115 := x,\nh_xy : x = y,\nh : y = 3\n\u22a2 y + y + y = 9\n-/\nend\n```\n-/\nunsafe def set (h_simp : parse (parser.optional (tk \"!\"))) (a : parse ident)\n    (tp : parse (parser.optional (tk \":\" *> texpr))) (_ : parse (tk \":=\")) (pv : parse texpr)\n    (rev_name : parse opt_dir_with) := do\n  let tp \u2190\n    i_to_expr <|\n        let t := tp.getD pexpr.mk_placeholder\n        ``(($(t) : Sort _))\n  let pv \u2190 to_expr ``(($(pv) : $(tp)))\n  let tp \u2190 instantiate_mvars tp\n  definev a tp pv\n  when h_simp <| change' ``($(pv)) (some (expr.const a [])) <| Interactive.Loc.wildcard\n  match rev_name with\n    | some (flip, id) => do\n      let nv \u2190 get_local a\n      mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id\n      reflexivity\n    | none => skip\n#align tactic.interactive.set tactic.interactive.set\n\nadd_tactic_doc\n  { Name := \"set\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.set]\n    tags := [\"context management\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- `clear_except h\u2080 h\u2081` deletes all the assumptions it can except for `h\u2080` and `h\u2081`.\n-/\nunsafe def clear_except (xs : parse (parser.many ident)) : tactic Unit := do\n  let n \u2190 xs.mapM (try_core \u2218 get_local) >>= revert_lst \u2218 List.filterMap id\n  let ls \u2190 local_context\n  ls <| try \u2218 tactic.clear\n  intron_no_renames n\n#align tactic.interactive.clear_except tactic.interactive.clear_except\n\nadd_tactic_doc\n  { Name := \"clear_except\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.clear_except]\n    tags := [\"context management\"] }\n\nunsafe def format_names (ns : List Name) : format :=\n  format.join <| List.intersperse \" \" (ns.map to_fmt)\n#align tactic.interactive.format_names tactic.interactive.format_names\n\nprivate unsafe def indent_bindents (l r : String) : Option (List Name) \u2192 expr \u2192 tactic format\n  | none, e => do\n    let e \u2190 pp e\n    f!\"{(\u2190 l)}{(\u2190 format.nest l e)}{\u2190 r}\"\n  | some ns, e => do\n    let e \u2190 pp e\n    let ns := format_names ns\n    let margin := l.length + ns.toString.length + \" : \".length\n    f!\"{(\u2190 l)}{(\u2190 ns)} : {(\u2190 format.nest margin e)}{\u2190 r}\"\n#align tactic.interactive.indent_bindents tactic.interactive.indent_bindents\n\nprivate unsafe def format_binders : List Name \u00d7 BinderInfo \u00d7 expr \u2192 tactic format\n  | (ns, BinderInfo.default, t) => indent_bindents \"(\" \")\" ns t\n  | (ns, BinderInfo.implicit, t) => indent_bindents \"{\" \"}\" ns t\n  | (ns, BinderInfo.strict_implicit, t) => indent_bindents \"\u2983\" \"\u2984\" ns t\n  | ([n], BinderInfo.inst_implicit, t) =>\n    if \"_\".isPrefixOf\u2093 n.toString then indent_bindents \"[\" \"]\" none t\n    else indent_bindents \"[\" \"]\" [n] t\n  | (ns, BinderInfo.inst_implicit, t) => indent_bindents \"[\" \"]\" ns t\n  | (ns, BinderInfo.aux_decl, t) => indent_bindents \"(\" \")\" ns t\n#align tactic.interactive.format_binders tactic.interactive.format_binders\n\nprivate unsafe def partition_vars' (s : name_set) :\n    List expr \u2192 List expr \u2192 List expr \u2192 tactic (List expr \u00d7 List expr)\n  | [], as, bs => pure (as.reverse, bs.reverse)\n  | x :: xs, as, bs => do\n    let t \u2190 infer_type x\n    if t s then partition_vars' xs as (x :: bs) else partition_vars' xs (x :: as) bs\n#align tactic.interactive.partition_vars' tactic.interactive.partition_vars'\n\nprivate unsafe def partition_vars : tactic (List expr \u00d7 List expr) := do\n  let ls \u2190 local_context\n  partition_vars' (name_set.of_list <| ls expr.local_uniq_name) ls [] []\n#align tactic.interactive.partition_vars tactic.interactive.partition_vars\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/-- Format the current goal as a stand-alone example. Useful for testing tactics\nor creating [minimal working examples](https://leanprover-community.github.io/mwe.html).\n\n* `extract_goal`: formats the statement as an `example` declaration\n* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration\n  called `my_decl`\n* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration\n\nExamples:\n\n```lean\nexample (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\nbegin\n  extract_goal,\n     -- prints:\n     -- example (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\n  extract_goal my_lemma\n     -- prints:\n     -- lemma my_lemma (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\nend\n\nexample {i j k x y z w p q r m n : \u2115} (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) (h\u2081 : k \u2264 p) (h\u2081 : p \u2264 q) : i \u2264 k :=\nbegin\n  extract_goal my_lemma,\n    -- prints:\n    -- lemma my_lemma {i j k x y z w p q r m n : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p)\n    --   (h\u2081 : p \u2264 q) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\n\n  extract_goal my_lemma with i j k\n    -- prints:\n    -- lemma my_lemma {p i j k : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\nend\n\nexample : true :=\nbegin\n  let n := 0,\n  have m : \u2115, admit,\n  have k : fin n, admit,\n  have : n + m + k.1 = 0, extract_goal,\n    -- prints:\n    -- example (m : \u2115)  : let n : \u2115 := 0 in \u2200 (k : fin n), n + m + k.val = 0 :=\n    -- begin\n    --   intros n k,\n    --   admit,\n    -- end\nend\n```\n\n-/\nunsafe def extract_goal (print_use : parse <| tk \"!\" *> pure true <|> pure false)\n    (n : parse (parser.optional ident))\n    (vs : parse (parser.optional (tk \"with\" *> parser.many ident))) : tactic Unit := do\n  let tgt \u2190 target\n  solve_aux tgt do\n      let ((cxt\u2080, cxt\u2081, ls, tgt), _) \u2190\n        solve_aux tgt do\n            vs clear_except\n            let ls \u2190 local_context\n            let ls \u2190 ls <| succeeds \u2218 is_local_def\n            let n \u2190 revert_lst ls\n            let (c\u2080, c\u2081) \u2190 partition_vars\n            let tgt \u2190 target\n            let ls \u2190 intron' n\n            pure (c\u2080, c\u2081, ls, tgt)\n      let is_prop \u2190 is_prop tgt\n      let title :=\n        match n, is_prop with\n        | none, _ => to_fmt \"example\"\n        | some n, tt => f! \"lemma {n}\"\n        | some n, ff => f! \"def {n}\"\n      let cxt\u2080 \u2190 compact_decl cxt\u2080 >>= List.mapM format_binders\n      let cxt\u2081 \u2190 compact_decl cxt\u2081 >>= List.mapM format_binders\n      let stmt \u2190 f!\"{\u2190 tgt} :=\"\n      let fmt :=\n        format.group <|\n          format.nest 2 <|\n            title ++ cxt\u2080 (fun acc x => Acc ++ format.group (format.line ++ x)) \"\" ++\n                    format.join (List.map (fun x => format.line ++ x) cxt\u2081) ++\n                  \" :\" ++\n                format.line ++\n              stmt\n      trace <| fmt <| options.mk `pp.width 80\n      let var_names := format.intercalate \" \" <| ls (to_fmt \u2218 local_pp_name)\n      let call_intron :=\n        if ls then to_fmt \"\"\n        else\n          f! \"\n              intros {var_names},\"\n      \u2190 do\n          dbg_trace \"begin{\u2190 call_intron}\n              admit,\n            end\n            \"\n  skip\n#align tactic.interactive.extract_goal tactic.interactive.extract_goal\n\nadd_tactic_doc\n  { Name := \"extract_goal\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.extract_goal]\n    tags := [\"goal management\", \"proof extraction\", \"debugging\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `inhabit \u03b1` tries to derive a `nonempty \u03b1` instance and then upgrades this\nto an `inhabited \u03b1` instance.\nIf the target is a `Prop`, this is done constructively;\notherwise, it uses `classical.choice`.\n\n```lean\nexample (\u03b1) [nonempty \u03b1] : \u2203 a : \u03b1, true :=\nbegin\n  inhabit \u03b1,\n  existsi default,\n  trivial\nend\n```\n-/\nunsafe def inhabit (t : parse parser.pexpr) (inst_name : parse (parser.optional ident)) :\n    tactic Unit := do\n  let ty \u2190 i_to_expr t\n  let nm \u2190 returnopt inst_name <|> get_unused_name `inst\n  let tgt \u2190 target\n  let tgt_is_prop \u2190 is_prop tgt\n  if tgt_is_prop then do\n      decorate_error \"could not infer nonempty instance:\" <|\n          mk_mapp `` Nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply\n      introI nm\n    else do\n      decorate_error \"could not infer nonempty instance:\" <|\n          mk_mapp `` Classical.inhabited_of_nonempty' [ty, none] >>= note nm none\n      resetI\n#align tactic.interactive.inhabit tactic.interactive.inhabit\n\nadd_tactic_doc\n  { Name := \"inhabit\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.inhabit]\n    tags := [\"context management\", \"type class\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- `revert_deps n\u2081 n\u2082 ...` reverts all the hypotheses that depend on one of `n\u2081, n\u2082, ...`\nIt does not revert `n\u2081, n\u2082, ...` themselves (unless they depend on another `n\u1d62`). -/\nunsafe def revert_deps (ns : parse (parser.many ident)) : tactic Unit :=\n  propagate_tags <| (ns.mapM get_local >>= revert_reverse_dependencies_of_hyps) >> skip\n#align tactic.interactive.revert_deps tactic.interactive.revert_deps\n\nadd_tactic_doc\n  { Name := \"revert_deps\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.revert_deps]\n    tags := [\"context management\", \"goal management\"] }\n\n/-- `revert_after n` reverts all the hypotheses after `n`. -/\nunsafe def revert_after (n : parse ident) : tactic Unit :=\n  propagate_tags <| (get_local n >>= tactic.revert_after) >> skip\n#align tactic.interactive.revert_after tactic.interactive.revert_after\n\nadd_tactic_doc\n  { Name := \"revert_after\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.revert_after]\n    tags := [\"context management\", \"goal management\"] }\n\n/-- Reverts all local constants on which the target depends (recursively). -/\nunsafe def revert_target_deps : tactic Unit :=\n  propagate_tags <| tactic.revert_target_deps >> skip\n#align tactic.interactive.revert_target_deps tactic.interactive.revert_target_deps\n\nadd_tactic_doc\n  { Name := \"revert_target_deps\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.revert_target_deps]\n    tags := [\"context management\", \"goal management\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- `clear_value n\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`. -/\nunsafe def clear_value (ns : parse (parser.many ident)) : tactic Unit :=\n  propagate_tags <| ns.reverse.mapM get_local >>= tactic.clear_value\n#align tactic.interactive.clear_value tactic.interactive.clear_value\n\nadd_tactic_doc\n  { Name := \"clear_value\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.clear_value]\n    tags := [\"context management\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n      `generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of\n      the same type.\n      \n      `generalize' h : e = x` in addition registers the hypothesis `h : e = x`.\n      \n      `generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also\n      succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis\n      `x` is not a local definition.\n      -/\n    unsafe\n  def\n    generalize'\n    ( h : parse ( parser.optional ident ) ) ( _ : parse <| tk \":\" ) ( p : parse generalize_arg_p )\n      : tactic Unit\n    :=\n      propagate_tags\n        do\n          let ( p , x ) := p\n            let e \u2190 i_to_expr p\n            let some h \u2190 pure h | tactic.generalize' e x >> skip\n            let tgt \u2190 target\n            let\n              tgt'\n                \u2190\n                (\n                    do\n                      let \u27e8 tgt' , _ \u27e9 \u2190 solve_aux tgt ( tactic.generalize e x >> target )\n                        to_expr ` `( \u2200 x , $ ( e ) = x \u2192 $ ( tgt' 0 1 ) )\n                    )\n                  <|>\n                  to_expr ` `( \u2200 x , $ ( e ) = x \u2192 $ ( tgt ) )\n            let t \u2190 assert h tgt'\n            swap\n            exact ` `( $ ( t ) $ ( e ) rfl )\n            intro x\n            intro h\n#align tactic.interactive.generalize' tactic.interactive.generalize'\n\nadd_tactic_doc\n  { Name := \"generalize'\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.generalize']\n    tags := [\"context management\"] }\n\n/-- If the expression `q` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.interactive.subst' q` substitutes `x` by `t` everywhere in the main goal and\nthen clears `q`.\nIf `q` is another local variable, then we find a local constant with type `q = t` or `t = q` and\nsubstitute `t` for `q`.\n\nLike `tactic.interactive.subst`, but fails with a nicer error message if the substituted variable is\na local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nunsafe def subst' (q : parse texpr) : tactic Unit := do\n  (i_to_expr q >>= tactic.subst') >> try (tactic.reflexivity reducible)\n#align tactic.interactive.subst' tactic.interactive.subst'\n\nadd_tactic_doc\n  { Name := \"subst'\"\n    category := DocCategory.tactic\n    declNames := [`tactic.interactive.subst']\n    tags := [\"context management\"] }\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/Interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.059210248251105387, "lm_q1q2_score": 0.01666209658879634}}
{"text": "-- Author(s): Andr\u00e9s 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 \u2192 ConditionalValue\n  | tentative : Nat \u2192 ConditionalValue\n  --| transaction : Nat \u2192 ConditionalValue\n  | fetchAndAdd : ConditionalValue\n  | failed : ConditionalValue\n  deriving BEq, Inhabited\n\ndef ConditionalValue.update : ConditionalValue \u2192 Value \u2192 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 \u2192 ConditionalValue\n  | .tentative v => .const v\n  | c => c\n\ndef RequestId.toNat : RequestId \u2192 Nat := \u03bb x => x\ndef ThreadId.toNat : ThreadId \u2192 Nat := \u03bb x => x\ndef RequestId.ofNat : Nat \u2192 RequestId := \u03bb x => x\ndef ThreadId.ofNat : Nat \u2192 ThreadId := \u03bb x => x\ndef Address.ofNat : Nat \u2192 Address := \u03bb x => x\ndef Value.ofNat : Nat \u2192 Value := \u03bb x => some x\ndef Value.ofOptionNat : Option Nat \u2192 Value := \u03bb 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 := \u03bb 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 \u2192 String\n  | .Read2ReadPred => \"R \u2192 R (P)\"\n  | .Read2ReadNoPred => \"R \u2192 R (NP)\"\n  | .Read2WritePred => \"R \u2192 W (P)\"\n  | .Read2WriteNoPred => \"R \u2192 W (NP)\"\n  | .Write2Read => \"W \u2192 R\"\n  | .Write2Write => \"W \u2192 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 \u2192 String := instToString.toString)\n  (isPermanentRead : type \u2192 Bool := \u03bb _ => 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 \u2192 ArchReq.type \u2192 BasicRequest\n | write : WriteRequest \u2192 ArchReq.type \u2192 BasicRequest\n | fence : ArchReq.type \u2192 BasicRequest\n deriving BEq\n\ninstance : Inhabited BasicRequest where default := BasicRequest.fence default\n\ndef BasicRequest.atomicity : BasicRequest \u2192 Atomicity\n  | .read rr _ => rr.atomicity\n  | .write wr _ => wr.atomicity\n  | .fence _ => .nonatomic\n\ndef BasicRequest.toString : BasicRequest \u2192 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 \u2192 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 \u2192 ArchReq.type\n  | BasicRequest.read  _ t => t\n  | BasicRequest.write  _ t => t\n  | BasicRequest.fence t => t\n\ndef BasicRequest.readRequest? : BasicRequest \u2192 Option ReadRequest\n  | BasicRequest.read  rr _ => some rr\n  | BasicRequest.write  _ _ => none\n  | BasicRequest.fence _ => none\n\ndef BasicRequest.writeRequest? : BasicRequest \u2192 Option WriteRequest\n  | BasicRequest.read  _ _ => none\n  | BasicRequest.write  wr _ => some wr\n  | BasicRequest.fence _ => none\n\ndef BasicRequest.updateType : BasicRequest \u2192 (ArchReq.type \u2192 ArchReq.type) \u2192 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 \u2192 Value \u2192 BasicRequest\n  | BasicRequest.read rr rt, v => BasicRequest.read {rr with val := v} rt\n  | br, _ => br\n\ndef BasicRequest.updateValue : BasicRequest \u2192 Value \u2192 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 \u2192 BasicRequest\n  | BasicRequest.write wr rt => BasicRequest.write {wr with val := wr.val.validate} rt\n  | br => br\n\ndef BasicRequest.value? : BasicRequest \u2192 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 \u2192 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 : \u2200 s, scopes.elem s \u2192 s.sublist system_scope\n  --system_scope_is_scope : system_scope \u2208 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 [ (\u00b7 \u2208 \u00b7) ])\n    }\n\ninstance : Inhabited ValidScopes where default := ValidScopes.default\n\ndef ValidScopes.toStringHet (threadType : Option (ThreadId \u2192 String)) (scopes : ValidScopes) : String :=\n  let scopeFun := match threadType with\n    | none => \u03bb _ => \"\"\n    | some f => \u03bb 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 := \u03bb 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 \u2192 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 \u2208 V.scopes\n\ninstance {V : ValidScopes} : ToString (@Scope V) where toString := \u03bb \u27e8threads,_\u27e9 => s!\"{threads}\"\n\ninstance {V : ValidScopes} : BEq (@Scope V) where\n  beq := \u03bb scope\u2081 scope\u2082 => scope\u2081.threads == scope\u2082.threads\n\ninstance {V : ValidScopes} : BEq (@Scope V) where\n  beq := \u03bb scope\u2081 scope\u2082 => scope\u2081.threads == scope\u2082.threads\n\ninstance {V : ValidScopes} : LE (@Scope V) where\n  le := \u03bb scope\u2081 scope\u2082 => List.sublist scope\u2081.threads scope\u2082.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 : \u03b1\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 \u2192 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 \u2192 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\u2081 r\u2082 : Request) : Bool :=\n  if r\u2081.isFence then r\u2081.basic_type == r\u2082.basic_type\n  else r\u2081.address? == r\u2082.address? && r\u2081.value? == r\u2082.value? && r\u2081.thread == r\u2082.thread &&\n       ((r\u2081.isWrite && r\u2082.isWrite) || (r\u2081.isRead && r\u2082.isRead))\n\n-- Read, Write\ndef SatisfiedRead := RequestId \u00d7 RequestId deriving ToString, BEq\n\n--instance [BEq \u03b1] : Membership (List \u03b1) (ListTree \u03b1) where\n--  mem lst tree := tree.elem lst = true\n\ndef decideThreadsValid (threads : List ThreadId) (V : ValidScopes) : Decidable (threads \u2208 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 \u2208 V.scopes) := decideThreadsValid threads V\n\ndef ValidScopes.validate (V : ValidScopes) (threads : List ThreadId) : Option (@Scope V) :=\n    if h : threads \u2208 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) \u2192 ThreadId \u2192 ThreadId \u2192 (@Scope V)\n | valid, t\u2081, t\u2082 => match valid.scopes.meet t\u2081 t\u2082 with\n   | some scope => {threads := scope, valid := sorry}\n   | none => panic! s!\"can't find the joint scope of {t\u2081} and {t\u2082} 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) \u2192 @Scope V \u2192 @Scope V \u2192 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 (\u03bb 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\u2081,r\u2082) : RequestId \u00d7 RequestId,\n which is true \u2194 there is an order constraint r\u2081 \u2192s r\u2082, for the scope s.\n\n However, we have a property (by construction) that if s' \u2264 s and r\u2081 \u2192s r\u2082, then\n also r\u2081 \u2192s' r\u2082. 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 \u00d7 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 \u03bb 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\u2081 req\u2082 : 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\u2081, req\u2082) 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 (\u03bb 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 (\u03bb 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         \u03bb x => succ'.any\n           \u03bb s => x == s || sc_oc s x\n     return succ'\n\ndef OrderConstraints.between {V : ValidScopes} (S : @Scope V) (req\u2081 req\u2082 : RequestId)\n  (reqs : List RequestId) (constraints : @OrderConstraints V)  : List RequestId :=\n  let preds\u2081 := constraints.predecessors S req\u2081 reqs\n  let preds\u2082 := constraints.predecessors S req\u2082 reqs\n  preds\u2082.removeAll (req\u2081::preds\u2081)\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 (\u03bb r\u2081 r\u2082 => constraints.lookup S r\u2081.id r\u2082.id) |>.toList\n\n/-\ndef SystemState.betweenRequests (state : SystemState) (req\u2081 req\u2082 : Request) : List Request :=\n  let betweenIds := state.orderConstraints.between\n    req\u2081.id req\u2082.id (reqIds state.requests)\n  state.idsToReqs betweenIds\n  -/\n\ndef OrderConstraints.compare {V\u2081 V\u2082 : ValidScopes} ( oc\u2081 : @OrderConstraints V\u2081) (oc\u2082 : @OrderConstraints V\u2082)\n  (requests : List RequestId) : Bool :=\n  if V\u2081.scopes.toList != V\u2082.scopes.toList\n    then false\n    else\n      let scopes\u2081 := V\u2081.scopes.toList.map V\u2081.validate\n      let scopes\u2082 := V\u2082.scopes.toList.map V\u2082.validate\n      let scopes := scopes\u2081.zip scopes\u2082 -- pretty hacky: should get types to match\n      let reqPairs := List.join $ requests.map \u03bb r\u2081 => requests.foldl (init := []) \u03bb reqs r\u2082 => (r\u2081,r\u2082)::reqs\n      let keys := List.join $ scopes.map \u03bb s => reqPairs.foldl (init := []) \u03bb ks (r\u2081,r\u2082) => (s,r\u2081,r\u2082)::ks\n      keys.all \u03bb (s,r\u2081,r\u2082) => match s with\n        | (some s\u2081, some s\u2082) => (oc\u2081.lookup s\u2081 r\u2081 r\u2082 == oc\u2082.lookup s\u2082 r\u2081 r\u2082)\n        | _ => panic! s!\"invalid scopes {scopes\u2081} or {scopes\u2082}\"\n\ndef OrderConstraints.addSingleScope {V : ValidScopes} (constraints : @OrderConstraints V)\n  (scope : @Scope V) (reqs : List (RequestId \u00d7 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) \u03bb 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 \u00d7 RequestId)) (val := true) : @OrderConstraints V :=\n  let subscopes := V.subscopes scope\n  --dbg_trace s!\"{scope.threads}.subscopes: {subscopes.map \u03bb s => s.threads}\"\n  subscopes.foldl (init := constraints) \u03bb oc sc => oc.addSingleScope sc reqs (val := val)\n\ndef OrderConstraints.swap {V : ValidScopes} (oc : @OrderConstraints V)\n  (scope : @Scope V) (req\u2081 req\u2082 : RequestId) : @OrderConstraints V :=\n  let c\u2081\u2082 := oc.lookup scope req\u2081 req\u2082\n  let c\u2082\u2081 := oc.lookup scope req\u2082 req\u2081\n  Id.run do\n    if c\u2081\u2082 == c\u2082\u2081 then\n      panic! \"cycle {req\u2081.id} \u2194 {req\u2082.id} detected in order constraints.\"\n    let mut add := []\n    let mut remove := []\n    if c\u2081\u2082 then\n      add :=( req\u2082,req\u2081) :: add\n      remove :=( req\u2081,req\u2082) :: remove\n    if c\u2082\u2081 then\n      add :=( req\u2081,req\u2082) :: add\n      remove :=( req\u2082,req\u2081) :: 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 \u2192 List Request \u2192 String\n  | [],_ => \"\"\n  | _,[] => \"\"\n  | reqs\u2081, reqs\u2082 =>\n    let vars\u2081 := removeDuplicates $ reqs\u2081  |>.map Request.address?\n    let vars\u2082 := removeDuplicates $ reqs\u2082  |>.map Request.address?\n    let vars := vars\u2081.filter vars\u2082.contains\n    let colorFun := \u03bb r => if vars.contains r.address? && r.address?.isSome then\n      colorString Color.magenta r.toShortString else r.toShortString\n    let (r\u2081strings, r\u2082strings) := (reqs\u2081.map colorFun, reqs\u2082.map colorFun)\n    \"{\" ++ (String.intercalate \", \" $ r\u2081strings) ++\n                    \"} \u2192 {\" ++ (String.intercalate \", \" $ r\u2082strings) ++ \"}\"\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 \u03bb 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 \u00d7 List Request) := []\n   for (req,deps) in pairs do\n     if res.any \u03bb (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 \u03bb (lhs,rhs) => OrderConstraints.groupsToString lhs rhs\n\nprivate def opReqId? : Option (Request) \u2192 Option RequestId := Option.map \u03bb r => r.id\n\nprivate def valConsistent (vals :  Array (Option (Request))) : Bool :=\n  let valOpIds := vals.map opReqId?\n  let valConsistent := \u03bb 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 := \u03bb arr\u2081 arr\u2082 => arr\u2081.val == arr\u2082.val\n\ndef RequestArray.getReq? : RequestArray \u2192 RequestId \u2192 Option (Request)\n  | arr, rId => match arr.val[rId.toNat]? with\n    | some (some req) => some req\n    | _ => none\n\ndef RequestArray.getReq! : RequestArray \u2192 RequestId \u2192 Request\n  | arr, rId => arr.val[rId.toNat]?.get!.get!\n\ndef RequestArray.printReq : RequestArray \u2192 RequestId \u2192 String\n  | arr, rId => match arr.getReq? rId with\n    | none => \"\"\n    | some r => r.toShortString\n\ndef RequestArray.seen : RequestArray \u2192 List RequestId\n  | arr => List.range arr.val.size\n\ndef RequestArray.map {\u03b2 : Type} : RequestArray \u2192 (Request \u2192 \u03b2) \u2192 Array \u03b2\n | rarr, f => filterNonesArr $ rarr.val.map \u03bb 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 \u2192 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 \u2192 (Request \u2192 Bool) \u2192 List Request\n  | ra, f =>\n  let fOp : Option Request \u2192 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 \u00d7 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 (\u03bb 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    (\u03bb th => th.toArray.qsort\n      (\u03bb r\u2081 r\u2082 => order.lookup (V.jointScope r\u2081.2.thread r\u2082.2.thread) r\u2081.2.id r\u2082.2.id)\n        |>.toList)\n  while threads.any (!\u00b7.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) \u2192 List RequestId\n | arr =>\n   let opIds :=  Array.toList $ arr.val.map (Option.map Request.id)\n   filterNones opIds\n\ndef growArray {\u03b1 : Type} (a : Array (Option \u03b1)) (n : Nat) : Array (Option \u03b1) :=\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 \u2192 Request \u2192 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 \u2192 Option (Request) \u2192 USize \u2192 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 \u2192 Request \u2192 RequestArray\n  | arr, req =>\n    let i := req.id.toNat.toUSize\n    arr.insertAtPosition (some req) i\n\ndef RequestArray.remove : RequestArray \u2192 RequestId \u2192 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 \u2192 String\n  orderConstraints : @OrderConstraints scopes\n  removedCoherent : \u2200 id : RequestId, id \u2208 (removed.map Request.id) \u2192 id \u2208 reqIds requests\n\ndef SystemState.beq (state\u2081 state\u2082 : SystemState)\n  -- (samesystem : state\u2081.system = state\u2082.system)\n  : Bool :=\n  state\u2081.requests == state\u2082.requests &&\n  state\u2081.removed == state\u2082.removed &&\n  state\u2081.satisfied == state\u2082.satisfied &&\n  -- this will be expensive!\n  state\u2081.orderConstraints.compare state\u2082.orderConstraints (reqIds state\u2081.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? (\u00b7.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 \u2192 List ThreadId\n | s => s.scopes.system_scope\n\ndef SystemState.prettyPrint (state : SystemState) (highlight : optParam (Option $ ThreadId \u00d7 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      \u03bb scope => s!\"constraints (scope {scope}) : {state.oderConstraintsString (state.scopes.validate scope).get!}\"\n  let satisfiedStr := state.satisfied.map\n    \u03bb (r\u2081, r\u2082) => s!\"{(state.findMaybeRemoved? r\u2081).get!.toShortString} with {state.requests.printReq r\u2082}\"\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 \u2192 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      \u03bb scope => s!\"constraints (scope {scope}) : {state.oderConstraintsString (state.scopes.validate scope).get!}\"\n  let satisfiedStr := state.satisfied.map\n    \u03bb (r\u2081, r\u2082) => s!\"{(state.findMaybeRemoved? r\u2081).get!.toShortString} with {state.requests.printReq r\u2082}\"\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  \u2200 id : RequestId, id \u2208 [] \u2192 id \u2208 reqIds requests := by\n  intros id h\n  contradiction\n\ntheorem empty2Coherent (seen : List RequestId) :\n  \u2200 id\u2081 id\u2082 : RequestId, (id\u2081,id\u2082) \u2208 [] \u2192 id\u2081 \u2208 seen \u2227 id\u2082 \u2208 seen := by\n  intros\n  contradiction\n\ndef SystemState.init (S : ValidScopes) (threadTypes : ThreadId \u2192 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 (\u03bb _ => \"default\")\ninstance : Inhabited (SystemState) where default := SystemState.default\n\ndef SystemState.seen : SystemState \u2192 List RequestId\n  | state => state.requests.seen\n\ndef SystemState.idsToReqs : SystemState \u2192 List RequestId \u2192 List (Request)\n  | state, ids => filterNones $ ids.map (\u03bb id => state.requests.getReq? id)\n\ndef SystemState.isSatisfied : SystemState \u2192 RequestId \u2192 Bool\n  | state, rid =>\n  !(state.satisfied.filter \u03bb (srd,_) => srd == rid).isEmpty\n\ndef SystemState.reqPropagatedTo : SystemState \u2192 RequestId \u2192 ThreadId \u2192 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 \u2192 Request \u2192 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 \u2192 Request \u2192 Request \u2192 Bool)\n  (blockingSemantics : Request \u2192 BlockingSemantics)\n  (scopeIntersection : (valid : ValidScopes) \u2192 Request \u2192 Request \u2192 @Scope valid := \u03bb v _ _ => v.systemScope)\n  (predecessorConstraints : SystemState \u2192 RequestId \u2192 RequestId \u2192 Bool := \u03bb _ _ _ => true)\n  (acceptConstraints : SystemState \u2192 BasicRequest \u2192 ThreadId \u2192 Bool := \u03bb _ _ _ => true)\n  (acceptEffects : SystemState \u2192 RequestId \u2192 ThreadId \u2192 SystemState := \u03bb st _ _ => st)\n  (propagateConstraints : SystemState \u2192 RequestId \u2192 ThreadId \u2192 Bool := \u03bb _ _ _ => true)\n  (propagateEffects : SystemState \u2192 RequestId \u2192 ThreadId \u2192 SystemState := \u03bb st _ _ => st)\n  (satisfyReadConstraints : SystemState \u2192 RequestId \u2192 RequestId \u2192 Bool := \u03bb _ _ _ => true)\n  (satisfyReadEffects : SystemState \u2192 RequestId \u2192 RequestId \u2192 SystemState := \u03bb 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": "/-\nCopyright (c) 2020 Sebastian Ullrich. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\n\nimport Lean.PrettyPrinter.Delaborator.Basic\nimport Lean.PrettyPrinter.Delaborator.SubExpr\nimport Lean.PrettyPrinter.Delaborator.TopDownAnalyze\nimport Lean.Parser\n\nnamespace Lean.PrettyPrinter.Delaborator\nopen Lean.Meta\nopen Lean.Parser.Term\nopen SubExpr\n\ndef maybeAddBlockImplicit (ident : Syntax) : DelabM Syntax := do\n  if \u2190 getPPOption getPPAnalysisBlockImplicit then `(@$ident:ident) else ident\n\ndef unfoldMDatas : Expr \u2192 Expr\n  | Expr.mdata _ e _ => unfoldMDatas e\n  | e                => e\n\n@[builtinDelab fvar]\ndef delabFVar : Delab := do\nlet Expr.fvar id _ \u2190 getExpr | unreachable!\ntry\n  let l \u2190 getLocalDecl id\n  maybeAddBlockImplicit (mkIdent l.userName)\ncatch _ =>\n  -- loose free variable, use internal name\n  maybeAddBlockImplicit $ mkIdent id.name\n\n-- loose bound variable, use pseudo syntax\n@[builtinDelab bvar]\ndef delabBVar : Delab := do\n  let Expr.bvar idx _ \u2190 getExpr | unreachable!\n  pure $ mkIdent $ Name.mkSimple $ \"#\" ++ toString idx\n\n@[builtinDelab mvar]\ndef delabMVar : Delab := do\n  let Expr.mvar n _ \u2190 getExpr | unreachable!\n  let mvarDecl \u2190 getMVarDecl n\n  let n :=\n    match mvarDecl.userName with\n    | Name.anonymous => n.name.replacePrefix `_uniq `m\n    | n => n\n  `(?$(mkIdent n))\n\n@[builtinDelab sort]\ndef delabSort : Delab := do\n  let Expr.sort l _ \u2190 getExpr | unreachable!\n  match l with\n  | Level.zero _ => `(Prop)\n  | Level.succ (Level.zero _) _ => `(Type)\n  | _ => match l.dec with\n    | some l' => `(Type $(Level.quote l' max_prec))\n    | none    => `(Sort $(Level.quote l max_prec))\n\n\ndef unresolveNameGlobal (n\u2080 : Name) : DelabM Name := do\n  if n\u2080.hasMacroScopes then return n\u2080\n  let mut initialNames := #[]\n  if !(\u2190 getPPOption getPPFullNames) then initialNames := initialNames ++ getRevAliases (\u2190 getEnv) n\u2080\n  initialNames := initialNames.push (rootNamespace ++ n\u2080)\n  for initialName in initialNames do\n    match (\u2190 unresolveNameCore initialName) with\n    | none => continue\n    | some n => return n\n  return n\u2080 -- if can't resolve, return the original\nwhere\n  unresolveNameCore (n : Name) : DelabM (Option Name) := do\n    let mut revComponents := n.components'\n    let mut candidate := Name.anonymous\n    for i in [:revComponents.length] do\n      match revComponents with\n      | [] => return none\n      | cmpt::rest => candidate := cmpt ++ candidate; revComponents := rest\n      match (\u2190 resolveGlobalName candidate) with\n      | [(potentialMatch, _)] => if potentialMatch == n\u2080 then return some candidate else continue\n      | _ => continue\n    return none\n\n-- NOTE: not a registered delaborator, as `const` is never called (see [delab] description)\ndef delabConst : Delab := do\n  let Expr.const c\u2080 ls _ \u2190 getExpr | unreachable!\n  let ctx \u2190 read\n  let c\u2080 := if (\u2190 getPPOption getPPPrivateNames) then c\u2080 else (privateToUserName? c\u2080).getD c\u2080\n\n  let mut c \u2190 unresolveNameGlobal c\u2080\n  let stx \u2190\n    if ls.isEmpty || !(\u2190 getPPOption getPPUniverses) then\n      if (\u2190 getLCtx).usesUserName c then\n        -- `c` is also a local declaration\n        if c == c\u2080 && !(\u2190 read).inPattern then\n          -- `c` is the fully qualified named. So, we append the `_root_` prefix\n          c := `_root_ ++ c\n        else\n          c := c\u2080\n      return mkIdent c\n    else\n      `($(mkIdent c).{$[$(ls.toArray.map quote)],*})\n\n  maybeAddBlockImplicit stx\n\nstructure ParamKind where\n  name        : Name\n  bInfo       : BinderInfo\n  defVal      : Option Expr := none\n  isAutoParam : Bool := false\n\ndef ParamKind.isRegularExplicit (param : ParamKind) : Bool :=\n  param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone\n\n/-- Return array with n-th element set to kind of n-th parameter of `e`. -/\npartial def getParamKinds : DelabM (Array ParamKind) := do\n  let e \u2190 getExpr\n  try\n    withTransparency TransparencyMode.all do\n      forallTelescopeArgs e.getAppFn e.getAppArgs fun params _ => do\n        params.mapM fun param => do\n          let l \u2190 getLocalDecl param.fvarId!\n          pure { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam }\n  catch _ => pure #[] -- recall that expr may be nonsensical\nwhere\n  forallTelescopeArgs f args k := do\n    forallBoundedTelescope (\u2190 inferType f) args.size fun xs b =>\n      if xs.isEmpty || xs.size == args.size then\n        -- we still want to consider optParams\n        forallTelescopeReducing b fun ys b => k (xs ++ ys) b\n      else\n        forallTelescopeArgs (mkAppN f $ args.shrink xs.size) (args.extract xs.size args.size) fun ys b =>\n          k (xs ++ ys) b\n\n@[builtinDelab app]\ndef delabAppExplicit : Delab := whenPPOption getPPExplicit do\n  let paramKinds \u2190 getParamKinds\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (do\n      let fn \u2190 getExpr\n      let stx \u2190 if fn.isConst then delabConst else delab\n      let needsExplicit := paramKinds.any (fun param => !param.isRegularExplicit) && stx.getKind != `Lean.Parser.Term.explicit\n      let stx \u2190 if needsExplicit then `(@$stx) else pure stx\n      pure (stx, paramKinds.toList, #[]))\n    (fun \u27e8fnStx, paramKinds, argStxs\u27e9 => do\n      let isInstImplicit := match paramKinds with\n                            | [] => false\n                            | param :: _ => param.bInfo == BinderInfo.instImplicit\n      let argStx \u2190 if \u2190 getPPOption getPPAnalysisHole then `(_)\n                   else if isInstImplicit == true then\n                     let stx \u2190 if \u2190 getPPOption getPPInstances then delab else `(_)\n                     if \u2190 getPPOption getPPInstanceTypes then\n                       let typeStx \u2190 withType delab\n                       `(($stx : $typeStx))\n                     else stx\n                   else delab\n      pure (fnStx, paramKinds.tailD [], argStxs.push argStx))\n  Syntax.mkApp fnStx argStxs\n\ndef shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do\n  getPPMotivesAll opts\n  <||> (\u2190 getPPMotivesPi opts <&&> returnsPi motive)\n  <||> (\u2190 getPPMotivesNonConst opts <&&> isNonConstFun motive)\n\ndef withMDataOptions [Inhabited \u03b1] (x : DelabM \u03b1) : DelabM \u03b1 := do\n  match \u2190 getExpr with\n  | Expr.mdata m .. =>\n    let mut posOpts := (\u2190 read).optionsPerPos\n    let pos \u2190 getPos\n    for (k, v) in m do\n      if (`pp).isPrefixOf k then\n        let opts := posOpts.find? pos |>.getD {}\n        posOpts := posOpts.insert pos (opts.insert k v)\n    withReader ({ \u00b7 with optionsPerPos := posOpts }) $ withMDataExpr x\n  | _ => x\n\npartial def withMDatasOptions [Inhabited \u03b1] (x : DelabM \u03b1) : DelabM \u03b1 := do\n  if (\u2190 getExpr).isMData then withMDataOptions (withMDatasOptions x) else x\n\ndef isRegularApp : DelabM Bool := do\n  let e \u2190 getExpr\n  if not (unfoldMDatas e.getAppFn).isConst then return false\n  if \u2190 withNaryFn (withMDatasOptions (getPPOption getPPUniverses <||> getPPOption getPPAnalysisBlockImplicit)) then return false\n  for i in [:e.getAppNumArgs] do\n    if \u2190 withNaryArg i (getPPOption getPPAnalysisNamedArg) then return false\n  return true\n\ndef unexpandRegularApp (stx : Syntax) : Delab := do\n  let Expr.const c .. \u2190 pure (unfoldMDatas (\u2190 getExpr).getAppFn) | unreachable!\n  let fs \u2190 appUnexpanderAttribute.getValues (\u2190 getEnv) c\n  fs.firstM fun f =>\n    match f stx |>.run () with\n    | EStateM.Result.ok stx _ => pure stx\n    | _ => failure\n\n-- abbrev coe {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeT \u03b1 a \u03b2] : \u03b2\n-- abbrev coeFun {\u03b1 : Sort u} {\u03b3 : \u03b1 \u2192 Sort v} (a : \u03b1) [CoeFun \u03b1 \u03b3] : \u03b3 a\ndef unexpandCoe (stx : Syntax) : Delab := whenPPOption getPPCoercions do\n  if not (\u2190 isCoe (\u2190 getExpr)) then failure\n  let e \u2190 getExpr\n  match stx with\n  | `($fn $arg)   => arg\n  | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*)\n  | _             => failure\n\ndef unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do\n  let env \u2190 getEnv\n  let e \u2190 getExpr\n  let some s \u2190 pure $ e.isConstructorApp? env | failure\n  guard $ isStructure env s.induct;\n  /- If implicit arguments should be shown, and the structure has parameters, we should not\n     pretty print using { ... }, because we will not be able to see the parameters. -/\n  let fieldNames := getStructureFields env s.induct\n  let mut fields := #[]\n  guard $ fieldNames.size == stx[1].getNumArgs\n  let args := e.getAppArgs\n  let fieldVals := args.extract s.numParams args.size\n  for idx in [:fieldNames.size] do\n    let fieldName := fieldNames[idx]\n    let fieldId := mkIdent fieldName\n    let fieldPos \u2190 nextExtraPos\n    let fieldId := annotatePos fieldPos fieldId\n    addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx]\n    let field \u2190 `(structInstField|$fieldId:ident := $(stx[1][idx]):term)\n    fields := fields.push field\n  let tyStx \u2190 withType do\n    if (\u2190 getPPOption getPPStructureInstanceType) then delab >>= pure \u2218 some else pure none\n  if fields.isEmpty then\n    `({ $[: $tyStx]? })\n  else\n    let lastField := fields.back\n    fields := fields.pop\n    `({ $[$fields, ]* $lastField $[: $tyStx]? })\n\n@[builtinDelab app]\ndef delabAppImplicit : Delab := do\n  -- TODO: always call the unexpanders, make them guard on the right # args?\n  let paramKinds \u2190 getParamKinds\n  if \u2190 getPPOption getPPExplicit then\n    if paramKinds.any (fun param => !param.isRegularExplicit) then failure\n\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (do\n      let fn \u2190 getExpr\n      let stx \u2190 if fn.isConst then delabConst else delab\n      pure (stx, paramKinds.toList, #[]))\n    (fun (fnStx, paramKinds, argStxs) => do\n      let arg \u2190 getExpr\n      let opts \u2190 getOptions\n      let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do\n        `(Parser.Term.namedArgument| ($(\u2190 mkIdent name):ident := $argStx:term))\n      let argStx? : Option Syntax \u2190\n        if \u2190 getPPOption getPPAnalysisSkip then pure none\n        else if \u2190 getPPOption getPPAnalysisHole then `(_)\n        else\n          match paramKinds with\n          | [] => delab\n          | param :: rest =>\n            if param.defVal.isSome && rest.isEmpty then\n              let v := param.defVal.get!\n              if !v.hasLooseBVars && v == arg then none else delab\n            else if !param.isRegularExplicit && param.defVal.isNone then\n              if \u2190 getPPOption getPPAnalysisNamedArg <||> (param.name == `motive <&&> shouldShowMotive arg opts) then mkNamedArg param.name (\u2190 delab) else none\n            else delab\n      let argStxs := match argStx? with\n        | none => argStxs\n        | some stx => argStxs.push stx\n      pure (fnStx, paramKinds.tailD [], argStxs))\n  let stx := Syntax.mkApp fnStx argStxs\n\n  if \u2190 isRegularApp then\n    (guard (\u2190 getPPOption getPPNotation) *> unexpandRegularApp stx)\n    <|> (guard (\u2190 getPPOption getPPStructureInstances) *> unexpandStructureInstance stx)\n    <|> (guard (\u2190 getPPOption getPPNotation) *> unexpandCoe stx)\n    <|> pure stx\n  else pure stx\n\n/-- State for `delabAppMatch` and helpers. -/\nstructure AppMatchState where\n  info        : MatcherInfo\n  matcherTy   : Expr\n  params      : Array Expr := #[]\n  motive      : Option (Syntax \u00d7 Expr) := none\n  motiveNamed : Bool := false\n  discrs      : Array Syntax := #[]\n  varNames    : Array (Array Name) := #[]\n  rhss        : Array Syntax := #[]\n  -- additional arguments applied to the result of the `match` expression\n  moreArgs    : Array Syntax := #[]\n/--\n  Extract arguments of motive applications from the matcher type.\n  For the example below: `#[#[`([])], #[`(a::as)]]` -/\nprivate partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) :=\n  withReader (fun ctx => { ctx with inPattern := true, optionsPerPos := {} }) do\n    let ty \u2190 instantiateForall st.matcherTy st.params\n    forallTelescope ty fun params _ => do\n      -- skip motive and discriminators\n      let alts := Array.ofSubarray params[1 + st.discrs.size:]\n      alts.mapIdxM fun idx alt => do\n        let ty \u2190 inferType alt\n        -- TODO: this is a hack; we are accessing the expression out-of-sync with the position\n        -- Currently, we reset `optionsPerPos` at the beginning of `delabPatterns` to avoid\n        -- incorrectly considering annotations.\n        withTheReader SubExpr ({ \u00b7 with expr := ty }) $\n          usingNames st.varNames[idx] do\n            withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (\u2190 delab))\nwhere\n  usingNames {\u03b1} (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    usingNamesAux 0 varNames x\n  usingNamesAux {\u03b1} (i : Nat) (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    if i < varNames.size then\n      withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x\n    else\n      x\n\n/-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/\nprivate partial def skippingBinders {\u03b1} (numParams : Nat) (x : Array Name \u2192 DelabM \u03b1) : DelabM \u03b1 :=\n  loop numParams #[]\nwhere\n  loop : Nat \u2192 Array Name \u2192 DelabM \u03b1\n    | 0,   varNames => x varNames\n    | n+1, varNames => do\n      let rec visitLambda : DelabM \u03b1 := do\n        let varName \u2190 (\u2190 getExpr).bindingName!.eraseMacroScopes\n        -- Pattern variables cannot shadow each other\n        if varNames.contains varName then\n          let varName := (\u2190 getLCtx).getUnusedName varName\n          withBindingBody varName do\n            loop n (varNames.push varName)\n        else\n          withBindingBodyUnusedName fun id => do\n            loop n (varNames.push id.getId)\n      let e \u2190 getExpr\n      if e.isLambda then\n        visitLambda\n      else\n        -- eta expand `e`\n        let e \u2190 forallTelescopeReducing (\u2190 inferType e) fun xs _ => do\n          if xs.size == 1 && (\u2190 inferType xs[0]).isConstOf ``Unit then\n            -- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable.\n            -- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable.\n            -- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure\n            -- it adds an annotation to distinguish these two cases.\n            mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit))\n          else\n            mkLambdaFVars xs (mkAppN e xs)\n        withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda\n\n/--\n  Delaborate applications of \"matchers\" such as\n  ```\n  List.map.match_1 : {\u03b1 : Type _} \u2192\n    (motive : List \u03b1 \u2192 Sort _) \u2192\n      (x : List \u03b1) \u2192 (Unit \u2192 motive List.nil) \u2192 ((a : \u03b1) \u2192 (as : List \u03b1) \u2192 motive (a :: as)) \u2192 motive x\n  ```\n-/\n@[builtinDelab app]\ndef delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do\n  -- incrementally fill `AppMatchState` from arguments\n  let st \u2190 withAppFnArgs\n    (do\n      let (Expr.const c us _) \u2190 getExpr | failure\n      let (some info) \u2190 getMatcherInfo? c | failure\n      { matcherTy := (\u2190 getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState })\n    (fun st => do\n      if st.params.size < st.info.numParams then\n        pure { st with params := st.params.push (\u2190 getExpr) }\n      else if st.motive.isNone then\n         -- store motive argument separately\n         let lamMotive \u2190 getExpr\n         let piMotive \u2190 lambdaTelescope lamMotive fun xs body => mkForallFVars xs body\n         -- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive`\n         -- Thus the binder types won't have any annotations\n         let piStx \u2190 withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab\n         let named \u2190 getPPOption getPPAnalysisNamedArg\n         pure { st with motive := (piStx, lamMotive), motiveNamed := named }\n      else if st.discrs.size < st.info.numDiscrs then\n        pure { st with discrs := st.discrs.push (\u2190 delab) }\n      else if st.rhss.size < st.info.altNumParams.size then\n        /- We save the variables names here to be able to implement safe_shadowing.\n           The pattern delaboration must use the names saved here. -/\n        let (varNames, rhs) \u2190 skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do\n          let rhs \u2190 delab\n          return (varNames, rhs)\n        pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }\n      else\n        pure { st with moreArgs := st.moreArgs.push (\u2190 delab) })\n\n  if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then\n    -- underapplied\n    failure\n\n  match st.discrs, st.rhss with\n  | #[discr], #[] =>\n    let stx \u2190 `(nomatch $discr)\n    Syntax.mkApp stx st.moreArgs\n  | _,        #[] => failure\n  | _,        _   =>\n    let pats \u2190 delabPatterns st\n    let stx \u2190 do\n      let (piStx, lamMotive) := st.motive.get!\n      let opts \u2190 getOptions\n      -- TODO: disable the match if other implicits are needed?\n      if \u2190 st.motiveNamed <||> shouldShowMotive lamMotive opts then\n        `(match $[$st.discrs:term],* : $piStx with $[| $pats,* => $st.rhss]*)\n      else\n        `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*)\n    Syntax.mkApp stx st.moreArgs\n\n/--\n  Delaborate applications of the form `(fun x => b) v` as `let_fun x := v; b`\n-/\ndef delabLetFun : Delab := do\n  let stxV \u2190 withAppArg delab\n  withAppFn do\n    let Expr.lam n t b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxB \u2190 withBindingBody n delab\n    if \u2190 getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then\n      let stxT \u2190 withBindingDomain delab\n      `(let_fun $(mkIdent n) : $stxT := $stxV; $stxB)\n    else\n      `(let_fun $(mkIdent n) := $stxV; $stxB)\n\n@[builtinDelab mdata]\ndef delabMData : Delab := do\n  if let some _ := Lean.Meta.Match.inaccessible? (\u2190 getExpr) then\n    let s \u2190 withMDataExpr delab\n    if (\u2190 read).inPattern then\n      `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns\n    else\n      return s\n  else if isLetFun (\u2190 getExpr) then\n    withMDataExpr <| delabLetFun\n  else if let some _ := isLHSGoal? (\u2190 getExpr) then\n    withMDataExpr <| withAppFn <| withAppArg <| delab\n  else\n    withMDataOptions delab\n\n/--\nCheck for a `Syntax.ident` of the given name anywhere in the tree.\nThis is usually a bad idea since it does not check for shadowing bindings,\nbut in the delaborator we assume that bindings are never shadowed.\n-/\npartial def hasIdent (id : Name) : Syntax \u2192 Bool\n  | Syntax.ident _ _ id' _ => id == id'\n  | Syntax.node _ args     => args.any (hasIdent id)\n  | _                      => false\n\n/--\nReturn `true` iff current binder should be merged with the nested\nbinder, if any, into a single binder group:\n* both binders must have same binder info and domain\n* they cannot be inst-implicit (`[a b : A]` is not valid syntax)\n* `pp.binderTypes` must be the same value for both terms\n* prefer `fun a b` over `fun (a b)`\n-/\nprivate def shouldGroupWithNext : DelabM Bool := do\n  let e \u2190 getExpr\n  let ppEType \u2190 getPPOption (getPPBinderTypes e)\n  let go (e' : Expr) := do\n    let ppE'Type \u2190 withBindingBody `_ $ getPPOption (getPPBinderTypes e)\n    pure $ e.binderInfo == e'.binderInfo &&\n      e.bindingDomain! == e'.bindingDomain! &&\n      e'.binderInfo != BinderInfo.instImplicit &&\n      ppEType == ppE'Type &&\n      (e'.binderInfo != BinderInfo.default || ppE'Type)\n  match e with\n  | Expr.lam _ _     e'@(Expr.lam _ _ _ _) _     => go e'\n  | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'\n  | _ => pure false\nwhere\n  getPPBinderTypes (e : Expr) :=\n    if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes\n\nprivate partial def delabBinders (delabGroup : Array Syntax \u2192 Syntax \u2192 Delab) : optParam (Array Syntax) #[] \u2192 Delab\n  -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished\n  -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping\n  -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.\n  | curNames => do\n    if \u2190 shouldGroupWithNext then\n      -- group with nested binder => recurse immediately\n      withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)\n    else\n      -- don't group => delab body and prepend current binder group\n      let (stx, stxN) \u2190 withBindingBodyUnusedName fun stxN => do (\u2190 delab, stxN)\n      delabGroup (curNames.push stxN) stx\n\n@[builtinDelab lam]\ndef delabLam : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let stxT \u2190 withBindingDomain delab\n    let ppTypes \u2190 getPPOption getPPFunBinderTypes\n    let expl \u2190 getPPOption getPPExplicit\n    let usedDownstream \u2190 curNames.any (fun n => hasIdent n.getId stxBody)\n\n    -- leave lambda implicit if possible\n    -- TODO: for now we just always block implicit lambdas when delaborating. We can revisit.\n    -- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit,\n    -- it doesn't seem like we can leave a subsequent binder implicit.\n    let blockImplicitLambda := true\n    /-\n    let blockImplicitLambda := expl ||\n      e.binderInfo == BinderInfo.default ||\n      -- Note: the following restriction fixes many issues with roundtripping,\n      -- but this condition may still not be perfectly in sync with the elaborator.\n      e.binderInfo == BinderInfo.instImplicit ||\n      Elab.Term.blockImplicitLambda stxBody ||\n      usedDownstream\n    -/\n\n    if !blockImplicitLambda then\n      pure stxBody\n    else\n      let group \u2190 match e.binderInfo, ppTypes with\n        | BinderInfo.default,     true   =>\n          -- \"default\" binder group is the only one that expects binder names\n          -- as a term, i.e. a single `Syntax.ident` or an application thereof\n          let stxCurNames \u2190\n            if curNames.size > 1 then\n              `($(curNames.get! 0) $(curNames.eraseIdx 0)*)\n            else\n              pure $ curNames.get! 0;\n          `(funBinder| ($stxCurNames : $stxT))\n        | BinderInfo.default,        false  => pure curNames.back  -- here `curNames.size == 1`\n        | BinderInfo.implicit,       true   => `(funBinder| {$curNames* : $stxT})\n        | BinderInfo.implicit,       false  => `(funBinder| {$curNames*})\n        | BinderInfo.strictImplicit, true   => `(funBinder| \u2983$curNames* : $stxT\u2984)\n        | BinderInfo.strictImplicit, false  => `(funBinder| \u2983$curNames*\u2984)\n        | BinderInfo.instImplicit,   _     =>\n          if usedDownstream then `(funBinder| [$curNames.back : $stxT])  -- here `curNames.size == 1`\n          else  `(funBinder| [$stxT])\n        | _                      , _     => unreachable!;\n      match stxBody with\n      | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody)\n      | _                                 => `(fun $group => $stxBody)\n\n@[builtinDelab forallE]\ndef delabForall : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let prop \u2190 try isProp e catch _ => false\n    let stxT \u2190 withBindingDomain delab\n    let group \u2190 match e.binderInfo with\n    | BinderInfo.implicit       => `(bracketedBinderF|{$curNames* : $stxT})\n    | BinderInfo.strictImplicit => `(bracketedBinderF|\u2983$curNames* : $stxT\u2984)\n    -- here `curNames.size == 1`\n    | BinderInfo.instImplicit   => `(bracketedBinderF|[$curNames.back : $stxT])\n    | _                         =>\n      -- heuristic: use non-dependent arrows only if possible for whole group to avoid\n      -- noisy mix like `(\u03b1 : Type) \u2192 Type \u2192 (\u03b3 : Type) \u2192 ...`.\n      let dependent := curNames.any $ fun n => hasIdent n.getId stxBody\n      -- NOTE: non-dependent arrows are available only for the default binder info\n      if dependent then\n        if prop && !(\u2190 getPPOption getPPPiBinderTypes) then\n          return \u2190 `(\u2200 $curNames:ident*, $stxBody)\n        else\n          `(bracketedBinderF|($curNames* : $stxT))\n      else\n        return \u2190 curNames.foldrM (fun _ stxBody => `($stxT \u2192 $stxBody)) stxBody\n    if prop then\n      match stxBody with\n      | `(\u2200 $groups*, $stxBody) => `(\u2200 $group $groups*, $stxBody)\n      | _                       => `(\u2200 $group, $stxBody)\n    else\n      `($group:bracketedBinder \u2192 $stxBody)\n\n@[builtinDelab letE]\ndef delabLetE : Delab := do\n  let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n  let n \u2190 getUnusedName n b\n  let stxV \u2190 descend v 1 delab\n  let stxB \u2190 withLetDecl n t v fun fvar =>\n    let b := b.instantiate1 fvar\n    descend b 2 delab\n  if \u2190 getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then\n    let stxT \u2190 descend t 0 delab\n    `(let $(mkIdent n) : $stxT := $stxV; $stxB)\n  else `(let $(mkIdent n) := $stxV; $stxB)\n\n@[builtinDelab lit]\ndef delabLit : Delab := do\n  let Expr.lit l _ \u2190 getExpr | unreachable!\n  match l with\n  | Literal.natVal n => pure $ quote n\n  | Literal.strVal s => pure $ quote s\n\n-- `@OfNat.ofNat _ n _` ~> `n`\n@[builtinDelab app.OfNat.ofNat]\ndef delabOfNat : Delab := whenPPOption getPPCoercions do\n  let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) \u2190 getExpr | failure\n  return quote n\n\n-- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true`\n@[builtinDelab app.OfScientific.ofScientific]\ndef delabOfScientific : Delab := whenPPOption getPPCoercions do\n  let expr \u2190 getExpr\n  guard <| expr.getAppNumArgs == 5\n  let Expr.lit (Literal.natVal m) _ \u2190 pure (expr.getArg! 2) | failure\n  let Expr.lit (Literal.natVal e) _ \u2190 pure (expr.getArg! 4) | failure\n  let s \u2190 match expr.getArg! 3 with\n    | Expr.const `Bool.true _ _  => pure true\n    | Expr.const `Bool.false _ _ => pure false\n    | _ => failure\n  let str  := toString m\n  if s && e == str.length then\n    return Syntax.mkScientificLit (\"0.\" ++ str)\n  else if s && e < str.length then\n    let mStr := str.extract 0 (str.length - e)\n    let eStr := str.extract (str.length - e) str.length\n    return Syntax.mkScientificLit (mStr ++ \".\" ++ eStr)\n  else\n    return Syntax.mkScientificLit (str ++ \"e\" ++ (if s then \"-\" else \"\") ++ toString e)\n\n/--\nDelaborate a projection primitive. These do not usually occur in\nuser code, but are pretty-printed when e.g. `#print`ing a projection\nfunction.\n-/\n@[builtinDelab proj]\ndef delabProj : Delab := do\n  let Expr.proj _ idx _ _ \u2190 getExpr | unreachable!\n  let e \u2190 withProj delab\n  -- not perfectly authentic: elaborates to the `idx`-th named projection\n  -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual\n  -- `proj`.\n  let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1));\n  `($(e).$idx:fieldIdx)\n\n/-- Delaborate a call to a projection function such as `Prod.fst`. -/\n@[builtinDelab app]\ndef delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do\n  let e@(Expr.app fn _ _) \u2190 getExpr | failure\n  let Expr.const c@(Name.str _ f _) _ _ \u2190 pure fn.getAppFn | failure\n  let env \u2190 getEnv\n  let some info \u2190 pure $ env.getProjectionFnInfo? c | failure\n  -- can't use with classes since the instance parameter is implicit\n  guard $ !info.fromClass\n  -- projection function should be fully applied (#struct params + 1 instance parameter)\n  -- TODO: support over-application\n  guard $ e.getAppNumArgs == info.numParams + 1\n  -- If pp.explicit is true, and the structure has parameters, we should not\n  -- use field notation because we will not be able to see the parameters.\n  let expl \u2190 getPPOption getPPExplicit\n  guard $ !expl || info.numParams == 0\n  let appStx \u2190 withAppArg delab\n  `($(appStx).$(mkIdent f):ident)\n\n@[builtinDelab app.dite]\ndef delabDIte : Delab := whenPPOption getPPNotation do\n  -- Note: we keep this as a delaborator for now because it actually accesses the expression.\n  guard $ (\u2190 getExpr).getAppNumArgs == 5\n  let c \u2190 withAppFn $ withAppFn $ withAppFn $ withAppArg delab\n  let (t, h) \u2190 withAppFn $ withAppArg $ delabBranch none\n  let (e, _) \u2190 withAppArg $ delabBranch h\n  `(if $(mkIdent h):ident : $c then $t else $e)\nwhere\n  delabBranch (h? : Option Name) : DelabM (Syntax \u00d7 Name) := do\n    let e \u2190 getExpr\n    guard e.isLambda\n    let h \u2190 match h? with\n      | some h => return (\u2190 withBindingBody h delab, h)\n      | none   => withBindingBodyUnusedName fun h => do\n        return (\u2190 delab, h.getId)\n\n@[builtinDelab app.namedPattern]\ndef delabNamedPattern : Delab := do\n  -- Note: we keep this as a delaborator because it accesses the DelabM context\n  guard (\u2190 read).inPattern\n  guard $ (\u2190 getExpr).getAppNumArgs == 3\n  let x \u2190 withAppFn $ withAppArg delab\n  let p \u2190 withAppArg delab\n  guard x.isIdent\n  `($x:ident@$p:term)\n\npartial def delabDoElems : DelabM (List Syntax) := do\n  let e \u2190 getExpr\n  if e.isAppOfArity `Bind.bind 6 then\n    -- Bind.bind.{u, v} : {m : Type u \u2192 Type v} \u2192 [self : Bind m] \u2192 {\u03b1 \u03b2 : Type u} \u2192 m \u03b1 \u2192 (\u03b1 \u2192 m \u03b2) \u2192 m \u03b2\n    let \u03b1 := e.getAppArgs[2]\n    let ma \u2190 withAppFn $ withAppArg delab\n    withAppArg do\n      match (\u2190 getExpr) with\n      | Expr.lam _ _ body _ =>\n        withBindingBodyUnusedName fun n => do\n          if body.hasLooseBVars then\n            prependAndRec `(doElem|let $n:term \u2190 $ma:term)\n          else if \u03b1.isConstOf `Unit || \u03b1.isConstOf `PUnit then\n            prependAndRec `(doElem|$ma:term)\n          else\n            prependAndRec `(doElem|let _ \u2190 $ma:term)\n      | _ => failure\n  else if e.isLet then\n    let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxT \u2190 descend t 0 delab\n    let stxV \u2190 descend v 1 delab\n    withLetDecl n t v fun fvar =>\n      let b := b.instantiate1 fvar\n      descend b 2 $\n        prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV)\n  else\n    let stx \u2190 delab\n    [\u2190`(doElem|$stx:term)]\n  where\n    prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems\n\n@[builtinDelab app.Bind.bind]\ndef delabDo : Delab := whenPPOption getPPNotation do\n  guard <| (\u2190 getExpr).isAppOfArity `Bind.bind 6\n  let elems \u2190 delabDoElems\n  let items \u2190 elems.toArray.mapM (`(doSeqItem|$(\u00b7):doElem))\n  `(do $items:doSeqItem*)\n\ndef reifyName : Expr \u2192 DelabM Name\n  | Expr.const ``Lean.Name.anonymous .. => Name.anonymous\n  | Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => do\n    (\u2190 reifyName n).mkStr s\n  | Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => do\n    (\u2190 reifyName n).mkNum i\n  | _ => failure\n\n@[builtinDelab app.Lean.Name.mkStr]\ndef delabNameMkStr : Delab := whenPPOption getPPNotation do\n  let n \u2190 reifyName (\u2190 getExpr)\n  -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version\n  mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{n}\"]\n\n@[builtinDelab app.Lean.Name.mkNum]\ndef delabNameMkNum : Delab := delabNameMkStr\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/Builtins.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510525748676846, "lm_q2_score": 0.048136770775252025, "lm_q1q2_score": 0.016612252672974902}}
{"text": "import Mathlib.Tactic.UnsetOption\nimport Mathlib.Tactic.RunCmd\n\nset_option pp.all true\n\nexample : True := by\n  run_tac\n    let t : Option Bool := (\u2190 Lean.MonadOptions.getOptions).get? `pp.all\n    -- should be true as set\n    guard (t == true)\n  trivial\n\nsection\n\nunset_option pp.all\n\nexample : True := by\n  run_tac\n    let t : Option Bool := (\u2190 Lean.MonadOptions.getOptions).get? `pp.all\n    -- should be none as unset\n    guard (t == Option.none)\n  trivial\n\nend\n\nexample : True := by\n  run_tac\n    let t : Option Bool := (\u2190 Lean.MonadOptions.getOptions).get? `pp.all\n    -- should be true as only unset within section\n    guard (t == true)\n  trivial\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/UnsetOption.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.04272219617531143, "lm_q1q2_score": 0.016602615574189693}}
{"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 \u2227 1000 = 2*500 :=\nbegin\n  let h :\u2115 :=1,\n  exact \u27e8rfl, rfl\u27e9\nend\n#print another\n#lint\n\nlemma foo (p : Prop) : p \u2192 p :=\nassume hp : p,\nhave hp2 : p, from hp,\nshow p, from hp\n#print foo\n\nlemma fun_problem (p : Prop) : \u00ac (p \u2194 \u00ac p) :=\nassume hpnp,\nhave hnp : \u00ac p, from\n  assume hp : p,\n  have hnp : \u00ac p, from hpnp.mp hp,\n  show false, from hnp hp,\nhave hp : p, from\n  have unnecessary : \u00ac 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 \u2192 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 \u2190 l.mmap find_unused_have_macro, return ls.join\n| _ := return []\n\nmeta def find_unused_let_macro : expr \u2192 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 \u2190 l.mmap find_unused_let_macro, return ls.join\n| _ := return []\n\nmeta def unused_of_decl : declaration \u2192 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 \u2190 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 := \u03bb d,\n  (do\n  --trace d.to_name,\n  ns \u2190 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 : \u2203 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": "import ..utils.util\nimport all\n\nsection main\nopen tactic\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  let dest : string := ((args.nth 0).get_or_else \"./data/mathlib_decls.log\"),\n  let ignore_decls_fn : environment \u2192 declaration \u2192 bool :=\n    (\u03bb e d, declaration.is_auto_or_internal e d || bnot (declaration.is_theorem d) || d.to_name.is_aux),\n  f \u2190 io.mk_file_handle dest io.mode.append,\n  io.run_tactic' $ do {\n    env \u2190 get_env,\n    decls \u2190 list.filter (\u03bb d, !(ignore_decls_fn env d)) <$> lint_mathlib_decls,\n    for_ decls $ \u03bb decl, do {\n      let decl_name := decl.to_name.to_string,\n      tactic.unsafe_run_io $ io.fs.put_str_ln f decl_name,\n      tactic.trace format!\"DECL: {decl_name}\"\n    }\n  }\n}\n\nend main\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/tools/all_decls.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.04535257910270417, "lm_q1q2_score": 0.016461589605174107}}
{"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 {\u03b1 : Type u}\n\nopen Color Nat\n\ninductive IsNodeOf : Rbnode \u03b1 \u2192 Rbnode \u03b1 \u2192 \u03b1 \u2192 Rbnode \u03b1 \u2192 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 : \u03b1 \u2192 \u03b1 \u2192 Prop) : Option \u03b1 \u2192 Option \u03b1 \u2192 Prop\n  | some a, some b => lt a b\n  | _, _ => True\n#align rbnode.lift Rbnode.Lift\n\ninductive IsSearchable (lt : \u03b1 \u2192 \u03b1 \u2192 Prop) : Rbnode \u03b1 \u2192 Option \u03b1 \u2192 Option \u03b1 \u2192 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\u2081 : is_searchable l lo (some v)) (hs\u2082 : 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\u2081 : is_searchable l lo (some v)) (hs\u2082 : 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 : \u03b1 \u2192 \u03b1 \u2192 Prop}\n\ntheorem lo_lt_hi {t : Rbnode \u03b1} {lt} [IsTrans \u03b1 lt] :\n    \u2200 {lo hi}, IsSearchable lt t lo hi \u2192 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\u2081 := t_ih_lchild hs_hs\u2081\n    have h\u2082 := t_ih_rchild hs_hs\u2082\n    cases lo <;> cases hi <;> simp [lift] at *\n    apply trans_of lt h\u2081 h\u2082\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 \u03b1 lt] {t} :\n    \u2200 {lo hi hi'} (hc : \u00aclt hi' hi \u2227 \u00aclt 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    \u00b7 cases lo <;> simp_all [lift]\n      apply lt_of_lt_of_incomp\n      assumption\n      exact \u27e8hc.2, hc.1\u27e9\n    all_goals apply t_ih_rchild hc hs_hs\u2082\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 \u03b1 lt] {t} :\n    \u2200 {lo lo' hi} (hc : \u00aclt lo' lo \u2227 \u00aclt 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    \u00b7 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\u2081\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 \u03b1 lt] :\n    \u2200 {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  \u00b7 cases hi <;> simp_all [lift]\n    apply trans_of lt hlt\n    assumption\n  all_goals apply t_ih_lchild hlt hs_hs\u2081\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    \u2200 {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  \u00b7 simp [lift]\n  all_goals apply t_ih_lchild hlt_hs\u2081\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 \u03b1 lt] :\n    \u2200 {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  \u00b7 cases lo <;> simp_all [lift]\n    apply trans_of lt\n    assumption\n    assumption\n  all_goals apply t_ih_rchild hlt hs_hs\u2082\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    \u2200 {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  \u00b7 cases lo <;> simp [lift]\n  all_goals apply t_ih_rchild hlt_hs\u2082\n#align rbnode.is_searchable_none_high_of_is_searchable_some_high Rbnode.isSearchable_none_high_of_isSearchable_some_high\n\ntheorem range [IsStrictWeakOrder \u03b1 lt] {t : Rbnode \u03b1} {x} :\n    \u2200 {lo hi}, IsSearchable lt t lo hi \u2192 Mem lt x t \u2192 Lift lt lo (some x) \u2227 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\u2081 h\u2082\n      cases h\u2081\n      simp only [mem] at h\u2082\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      \u00b7 have h\u2083 : lift lt lo (some x) \u2227 lift lt (some x) (some t_val) :=\n          by\n          apply t_ih_lchild\n          assumption\n          assumption\n        cases' h\u2083 with lo_x x_val\n        constructor\n        show lift lt lo (some x)\n        \u00b7 assumption\n        show lift lt (some x) hi\n        \u00b7 cases' hi with hi <;> simp [lift] at *\n          apply trans_of lt x_val val_hi\n      \u00b7 cases h\u2082\n        cases' lo with lo <;> cases' hi with hi <;> simp [lift] at *\n        \u00b7 apply lt_of_incomp_of_lt _ val_hi\n          simp [*]\n        \u00b7 apply lt_of_lt_of_incomp lo_val\n          simp [*]\n        constructor\n        \u00b7 apply lt_of_lt_of_incomp lo_val\n          simp [*]\n        \u00b7 apply lt_of_incomp_of_lt _ val_hi\n          simp [*]\n      \u00b7 have h\u2083 : lift lt (some t_val) (some x) \u2227 lift lt (some x) hi :=\n          by\n          apply t_ih_rchild\n          assumption\n          assumption\n        cases' h\u2083 with val_x x_hi\n        cases' lo with lo <;> cases' hi with hi <;> simp [lift] at *\n        \u00b7 assumption\n        \u00b7 apply trans_of lt lo_val val_x\n        constructor\n        \u00b7 apply trans_of lt lo_val val_x\n        \u00b7 assumption\n#align rbnode.range Rbnode.range\n\ntheorem lt_of_mem_left [IsStrictWeakOrder \u03b1 lt] {y : \u03b1} {t l r : Rbnode \u03b1} :\n    \u2200 {lo hi}, IsSearchable lt t lo hi \u2192 IsNodeOf t l y r \u2192 \u2200 {x}, Mem lt x l \u2192 lt x y :=\n  by\n  intro _ _ hs hn x hm; cases hn <;> cases hs\n  all_goals exact (range hs_hs\u2081 hm).2\n#align rbnode.lt_of_mem_left Rbnode.lt_of_mem_left\n\ntheorem lt_of_mem_right [IsStrictWeakOrder \u03b1 lt] {y : \u03b1} {t l r : Rbnode \u03b1} :\n    \u2200 {lo hi}, IsSearchable lt t lo hi \u2192 IsNodeOf t l y r \u2192 \u2200 {z}, Mem lt z r \u2192 lt y z :=\n  by\n  intro _ _ hs hn z hm; cases hn <;> cases hs\n  all_goals exact (range hs_hs\u2082 hm).1\n#align rbnode.lt_of_mem_right Rbnode.lt_of_mem_right\n\ntheorem lt_of_mem_left_right [IsStrictWeakOrder \u03b1 lt] {y : \u03b1} {t l r : Rbnode \u03b1} :\n    \u2200 {lo hi},\n      IsSearchable lt t lo hi \u2192 IsNodeOf t l y r \u2192 \u2200 {x z}, Mem lt x l \u2192 Mem lt z r \u2192 lt x z :=\n  by\n  intro _ _ hs hn x z hm\u2081 hm\u2082; cases hn <;> cases hs\n  all_goals\n    have h\u2081 := range hs_hs\u2081 hm\u2081\n    have h\u2082 := range hs_hs\u2082 hm\u2082\n    exact trans_of lt h\u2081.2 h\u2082.1\n#align rbnode.lt_of_mem_left_right Rbnode.lt_of_mem_left_right\n\nend IsSearchableLemmas\n\ninductive IsRedBlack : Rbnode \u03b1 \u2192 Color \u2192 Nat \u2192 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\u2081 c\u2082} (rb_l : is_red_black l c\u2081 n) (rb_r : is_red_black r c\u2082 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 : \u2200 {c n} {t : Rbnode \u03b1}, IsRedBlack t c n \u2192 n \u2264 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) \u2265 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 \u2192 Nat \u2192 Nat\n  | red, n => 2 * n + 1\n  | black, n => 2 * n\n#align rbnode.upper rbnode.upper\n\nprivate theorem upper_le : \u2200 c n, upper c n \u2264 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' : \u2200 {c n} {t : Rbnode \u03b1}, IsRedBlack t c n \u2192 depth max t \u2264 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)) \u2264 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 \u2264 2 * h_n + 1 := le_trans h_ih_rb_l (upper_le _ _)\n    have : depth max h_r \u2264 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 \u2264 2 * h_n + 2 * 1\n    \u00b7 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 \u03b1} (h : IsRedBlack t c n) : depth max t \u2264 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 \u03b1} (h : IsRedBlack t c n) : depth max t \u2264 2 * depth min t + 1 :=\n  by\n  have : 2 * depth min t + 1 \u2265 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 LMT\n\nvariable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]\n\nexample {a1 a2 a3 : A I E} :\n        ((a3).read i3) \u2260 (v1) \u2192 (a3) = ((a3).write i3 (v1)) \u2192 False := by\n  arr\n", "meta": {"author": "abdoo8080", "repo": "ar-project", "sha": "303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8", "save_path": "github-repos/lean/abdoo8080-ar-project", "path": "github-repos/lean/abdoo8080-ar-project/ar-project-303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8/Test/Lean/Test45.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.033589502505986975, "lm_q1q2_score": 0.016401196329921267}}
{"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.Compiler.LCNF.InferType\n\nnamespace Lean.Compiler.LCNF\n\n/-!\n# Compatible Types\n\nWe used to type check LCNF after each compiler pass. However, we disable this capability because cast management was too costly.\nThe casts may be needed to ensure the result of each pass is still typeable.\nHowever, these sanity checks are useful for catching silly mistakes.\nThus, we have added an \"LCNF type linter\". When turned on, this \"linter\" option instructs the compiler to perform compatibility type checking\nin the LCNF code after some compiler passes.\nRecall most casts are only needed in functions that make heavy use of dependent types.\nWe claim it is \"defensible\" to say this sanity checker is a linter. If the sanity checker fails, it means the user is \"abusing\" dependent types\nand performance may suffer at runtime.\nHere is an example of code that \"abuses\" dependent types:\n```\ndef Tuple (\u03b1 : Type u) : Nat \u2192 Type u\n  | 0   => PUnit\n  | 1   => \u03b1\n  | n+2 => \u03b1 \u00d7 Tuple \u03b1 (n+1)\n\ndef mkConstTuple (a : \u03b1) : (n : Nat) \u2192 Tuple \u03b1 n\n  | 0 => \u27e8\u27e9\n  | 1 => a\n  | n+2 => (a, mkConstTuple a (n+1))\n\ndef Tuple.map (f : \u03b1 \u2192 \u03b2) (xs : Tuple \u03b1 n) : Tuple \u03b2 n :=\n  match n with\n  | 0 => \u27e8\u27e9\n  | 1 => f xs\n  | _+2 => match xs with\n    | (a, xs) => (f a, Tuple.map f xs)\n```\n-/\n\n\n/--\nQuick check for `compatibleTypes`. It is not monadic, but it is incomplete\nbecause it does not eta-expand type formers. See comment at `compatibleTypes`.\nRemark: if the result is `true`, then `a` and `b` are indeed compatible.\nIf it is `false`, we must use the full-check.\n-/\npartial def compatibleTypesQuick (a b : Expr) : Bool :=\n  if a.isErased || b.isErased then\n    true\n  else\n    let a' := a.headBeta\n    let b' := b.headBeta\n    if a != a' || b != b' then\n      compatibleTypesQuick a' b'\n    else if a == b then\n      true\n    else\n      match a, b with\n      -- Note that even after reducing to head-beta, we can still have `.app` terms. For example,\n      -- an inductive constructor application such as `List Int`\n      | .app f a, .app g b => compatibleTypesQuick f g && compatibleTypesQuick a b\n      | .forallE _ d\u2081 b\u2081 _, .forallE _ d\u2082 b\u2082 _ => compatibleTypesQuick d\u2081 d\u2082 && compatibleTypesQuick b\u2081 b\u2082\n      | .lam _ d\u2081 b\u2081 _, .lam _ d\u2082 b\u2082 _ => compatibleTypesQuick d\u2081 d\u2082 && compatibleTypesQuick b\u2081 b\u2082\n      | .sort u, .sort v => Level.isEquiv u v\n      | .const n us, .const m vs => n == m && List.isEqv us vs Level.isEquiv\n      | _, _ => false\n\n/--\nComplete check for `compatibleTypes`. It eta-expands type formers. See comment at `compatibleTypes`.\n-/\npartial def InferType.compatibleTypesFull (a b : Expr) : InferTypeM Bool := do\n  if a.isErased || b.isErased then\n    return true\n  else\n    let a' := a.headBeta\n    let b' := b.headBeta\n    if a != a' || b != b' then\n      compatibleTypesFull a' b'\n    else if a == b then\n      return true\n    else\n      match a, b with\n      -- Note that even after reducing to head-beta, we can still have `.app` terms. For example,\n      -- an inductive constructor application such as `List Int`\n      | .app f a, .app g b => compatibleTypesFull f g <&&> compatibleTypesFull a b\n      | .forallE n d\u2081 b\u2081 bi, .forallE _ d\u2082 b\u2082 _ =>\n        unless (\u2190 compatibleTypesFull d\u2081 d\u2082) do return false\n        withLocalDecl n d\u2081 bi fun x =>\n          compatibleTypesFull (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n      | .lam n d\u2081 b\u2081 bi, .lam _ d\u2082 b\u2082 _ =>\n        unless (\u2190 compatibleTypesFull d\u2081 d\u2082) do return false\n        withLocalDecl n d\u2081 bi fun x =>\n          compatibleTypesFull (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n      | .sort u, .sort v => return Level.isEquiv u v\n      | .const n us, .const m vs => return n == m && List.isEqv us vs Level.isEquiv\n      | _, _ =>\n        if a.isLambda then\n          let some b \u2190 etaExpand? b | return false\n          compatibleTypesFull a b\n        else if b.isLambda then\n          let some a \u2190 etaExpand? a | return false\n          compatibleTypesFull a b\n        else\n          return false\nwhere\n  etaExpand? (e : Expr) : InferTypeM (Option Expr) := do\n    match (\u2190 inferType e).headBeta with\n    | .forallE n d _ bi =>\n      /-\n      In principle, `.app e (.bvar 0)` may not be a valid LCNF type sub-expression\n      because `d` may not be a type former type, See remark `compatibleTypes` for\n      a justification why this is ok.\n      -/\n      return some (.lam n d (.app e (.bvar 0)) bi)\n    | _ => return none\n\n/--\nReturn true if the LCNF types `a` and `b` are compatible.\nRemark: `a` and `b` can be type formers (e.g., `List`, or `fun (\u03b1 : Type) => Nat \u2192 Nat \u00d7 \u03b1`)\nRemark: We may need to eta-expand type formers to establish whether they are compatible or not.\nFor example, suppose we have\n```\nfun (x : B) => Id B \u25fe \u25fe\nId B \u25fe\n```\nWe must eta-expand `Id B \u25fe` to `fun (x : B) => Id B \u25fe x`. Note that, we use `x` instead of `\u25fe` to\nmake the implementation simpler and skip the check whether `B` is a type former type. However,\nthis simplification should not affect correctness since `\u25fe` is compatible with everything.\nRemark: see comment at `isErasedCompatible`.\nRemark: because of \"erasure confusion\" see note above, we assume `\u25fe` (aka `lcErasure`) is compatible with everything.\nThis is a simplification. We used to use `isErasedCompatible`, but this only address item 1.\nFor item 2, we would have to modify the `toLCNFType` function and make sure a type former is erased if the expected\ntype is not always a type former (see `S.mk` type and example in the note above).\n-/\ndef InferType.compatibleTypes (a b : Expr) : InferTypeM Bool := do\n  if compatibleTypesQuick a b then\n    return true\n  else\n    compatibleTypesFull a b\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/CompatibleTypes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.05108273460955049, "lm_q1q2_score": 0.01638842936711416}}
{"text": "import Lean.Data.HashMap\n\ninductive NEList (\u03b1 : Type)\n  | uno  : \u03b1 \u2192 NEList \u03b1\n  | cons : \u03b1 \u2192 NEList \u03b1 \u2192 NEList \u03b1\n\ndef NEList.contains [BEq \u03b1] : NEList \u03b1 \u2192 \u03b1 \u2192 Bool\n  | uno  a,    x => a == x\n  | cons a as, x => a == x || as.contains x\n\ndef NEList.noDup [BEq \u03b1] : NEList \u03b1 \u2192 Bool\n  | uno  a    => true\n  | cons a as => \u00acas.contains a && as.noDup\n\n@[specialize]\ndef NEList.foldl (f : \u03b1 \u2192 \u03b2 \u2192 \u03b1) : (init : \u03b1) \u2192 NEList \u03b2 \u2192 \u03b1\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 : \u03b1 \u2192 \u03b2) : NEList \u03b1 \u2192 NEList \u03b2\n  | uno  a     => uno  (f a)\n  | cons a  as => cons (f a) (map f as)\n\ninductive Literal\n  | bool  : Bool   \u2192 Literal\n  | int   : Int    \u2192 Literal\n  | float : Float  \u2192 Literal\n  | str   : String \u2192 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) \u2192 l.noDup \u2192 Program \u2192 Lambda\n\n  inductive Expression\n    | lit   : Literal \u2192 Expression\n    | var   : String \u2192 Expression\n    | lam   : Lambda \u2192 Expression\n    | list  : List Literal \u2192 Expression\n    | app   : Expression \u2192 NEList Expression \u2192 Expression\n    | unOp  : UnOp  \u2192 Expression \u2192 Expression\n    | binOp : BinOp \u2192 Expression \u2192 Expression \u2192 Expression\n\n  inductive Program\n    | skip  : Program\n    | eval  : Expression \u2192 Program\n    | decl  : String  \u2192 Program \u2192 Program\n    | seq   : Program \u2192 Program \u2192 Program\n    | fork  : Expression \u2192 Program \u2192 Program \u2192 Program\n    | loop  : Expression \u2192 Program \u2192 Program\n    | print : Expression \u2192 Program\n    deriving Inhabited\n\nend\n\ninductive Value\n  | nil  : Value\n  | lit  : Literal \u2192 Value\n  | list : List Literal \u2192 Value\n  | lam  : Lambda \u2192 Value\n  deriving Inhabited\n\nabbrev Context := Lean.HashMap String Value\n\ninductive ErrorType\n  | name | type | runTime\n\ndef Literal.typeStr : Literal \u2192 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 \u2192 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  \u27e8aux [] [] s.data\u27e9\n\nprotected def Literal.toString : Literal \u2192 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 \u2192 String\n  | mk l .. => (l.foldl (init := \"\") fun acc _ => acc ++ \"_ \u2192 \") ++ \"_\"\n\ndef Value.typeStr : Value \u2192 String\n  | nil    => \"nil\"\n  | lit  l => l.typeStr\n  | list _ => \"list\"\n  | lam  l => l.typeStr\n\ndef Literal.eq : Literal \u2192 Literal \u2192 Bool\n  | bool  b\u2097, bool  b\u1d63 => b\u2097 == b\u1d63\n  | int   i\u2097, int   i\u1d63 => i\u2097 == i\u1d63\n  | float f\u2097, float f\u1d63 => f\u2097 == f\u1d63\n  | int   i\u2097, float f\u1d63 => (.ofInt i\u2097) == f\u1d63\n  | float f\u2097, int   i\u1d63 => f\u2097 == (.ofInt i\u1d63)\n  | str   s\u2097, str   s\u1d63 => s\u2097 == s\u1d63\n  | _       , _        => false\n\ndef listLiteralEq : List Literal \u2192 List Literal \u2192 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 \u2192 Except String Value\n  | lit $ .bool b => return lit $ .bool !b\n  | v             => throw $ opError1 \"!\" v.typeStr\n\ndef Value.add : Value \u2192 Value \u2192 Except String Value\n  | lit $ .bool  b\u2097, lit $ .bool  b\u1d63 => return lit $ .bool $ b\u2097 || b\u1d63\n  | lit $ .int   i\u2097, lit $ .int   i\u1d63 => return lit $ .int  $ i\u2097 +  i\u1d63\n  | lit $ .float f\u2097, lit $ .float f\u1d63 => return lit $ .float $ f\u2097 +  f\u1d63\n  | lit $ .int   i\u2097, lit $ .float f\u1d63 => return lit $ .float $ (.ofInt i\u2097) +  f\u1d63\n  | lit $ .float f\u2097, lit $ .int   i\u1d63 => return lit $ .float $ f\u2097 +  (.ofInt i\u1d63)\n  | lit $ .str   s\u2097, lit $ .str   s\u1d63 => return lit $ .str   $ s\u2097 ++ s\u1d63\n  | list         l\u2097, list         l\u1d63 => return list  $ l\u2097 ++ l\u1d63\n  | list         l,  lit          r  => return list  $ l.concat r\n  | l,               r               => throw $ opError \"+\" l.typeStr r.typeStr\n\ndef Value.mul : Value \u2192 Value \u2192 Except String Value\n  | lit $ .bool  b\u2097, lit $ .bool  b\u1d63 => return .lit $ .bool  $ b\u2097 && b\u1d63\n  | lit $ .int   i\u2097, lit $ .int   i\u1d63 => return .lit $ .int   $ i\u2097 *  i\u1d63\n  | lit $ .float f\u2097, lit $ .float f\u1d63 => return .lit $ .float $ f\u2097 *  f\u1d63\n  | lit $ .int   i\u2097, lit $ .float f\u1d63 => return .lit $ .float $ (.ofInt i\u2097) *  f\u1d63\n  | lit $ .float f\u2097, lit $ .int   i\u1d63 => return .lit $ .float $ f\u2097 *  (.ofInt i\u1d63)\n  | l,               r               => throw $ opError \"*\" l.typeStr r.typeStr\n\ndef Bool.toNat : Bool \u2192 Nat\n  | false => 0\n  | true  => 1\n\ndef Value.lt : Value \u2192 Value \u2192 Except String Value\n  | lit $ .bool  b\u2097, lit $ .bool  b\u1d63 => return lit $ .bool $ b\u2097.toNat < b\u1d63.toNat\n  | lit $ .int   i\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ i\u2097 < i\u1d63\n  | lit $ .float f\u2097, lit $ .float f\u1d63 => return lit $ .bool $ f\u2097 < f\u1d63\n  | lit $ .int   i\u2097, lit $ .float f\u1d63 => return lit $ .bool $ (.ofInt i\u2097) < f\u1d63\n  | lit $ .float f\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ f\u2097 < (.ofInt i\u1d63)\n  | lit $ .str   s\u2097, lit $ .str   s\u1d63 => return lit $ .bool $ s\u2097 < s\u1d63\n  | list l\u2097, list l\u1d63 => return lit $ .bool $ l\u2097.length < l\u1d63.length\n  | l,               r               => throw $ opError \"<\" l.typeStr r.typeStr\n\ndef Value.le : Value \u2192 Value \u2192 Except String Value\n  | lit $ .bool  b\u2097, lit $ .bool  b\u1d63 => return lit $ .bool $ b\u2097.toNat \u2264 b\u1d63.toNat\n  | lit $ .int   i\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ i\u2097 \u2264 i\u1d63\n  | lit $ .float f\u2097, lit $ .float f\u1d63 => return lit $ .bool $ f\u2097 \u2264 f\u1d63\n  | lit $ .int   i\u2097, lit $ .float f\u1d63 => return lit $ .bool $ (.ofInt i\u2097) \u2264 f\u1d63\n  | lit $ .float f\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ f\u2097 \u2264 (.ofInt i\u1d63)\n  | lit $ .str   s\u2097, lit $ .str   s\u1d63 => return lit $ .bool $ s\u2097 < s\u1d63 || s\u2097 == s\u1d63\n  | list l\u2097, list  l\u1d63 => return lit $ .bool $ l\u2097.length \u2264 l\u1d63.length\n  | l,         r      => throw $ opError \"<=\" l.typeStr r.typeStr\n\ndef Value.gt : Value \u2192 Value \u2192 Except String Value\n  | lit $ .bool  b\u2097, lit $ .bool  b\u1d63 => return lit $ .bool $ b\u2097.toNat > b\u1d63.toNat\n  | lit $ .int   i\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ i\u2097 > i\u1d63\n  | lit $ .float f\u2097, lit $ .float f\u1d63 => return lit $ .bool $ f\u2097 > f\u1d63\n  | lit $ .int   i\u2097, lit $ .float f\u1d63 => return lit $ .bool $ (.ofInt i\u2097) > f\u1d63\n  | lit $ .float f\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ f\u2097 > (.ofInt i\u1d63)\n  | lit $ .str   s\u2097, lit $ .str   s\u1d63 => return lit $ .bool $ s\u2097 > s\u1d63\n  | list l\u2097, list l\u1d63 => return lit $ .bool $ l\u2097.length > l\u1d63.length\n  | l,       r       => throw $ opError \">\" l.typeStr r.typeStr\n\ndef Value.ge : Value \u2192 Value \u2192 Except String Value\n  | lit $ .bool  b\u2097, lit $ .bool  b\u1d63 => return lit $ .bool $ b\u2097.toNat \u2265 b\u1d63.toNat\n  | lit $ .int   i\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ i\u2097 \u2265 i\u1d63\n  | lit $ .float f\u2097, lit $ .float f\u1d63 => return lit $ .bool $ f\u2097 \u2265 f\u1d63\n  | lit $ .int   i\u2097, lit $ .float f\u1d63 => return lit $ .bool $ (.ofInt i\u2097) \u2265 f\u1d63\n  | lit $ .float f\u2097, lit $ .int   i\u1d63 => return lit $ .bool $ f\u2097 \u2265 (.ofInt i\u1d63)\n  | lit $ .str   s\u2097, lit $ .str   s\u1d63 => return lit $ .bool $ s\u2097 > s\u1d63 || s\u2097 == s\u1d63\n  | list l\u2097, list  l\u1d63 => return lit $ .bool $ l\u2097.length \u2265 l\u1d63.length\n  | l,       r        => throw $ opError \">=\" l.typeStr r.typeStr\n\ndef Value.eq : Value \u2192 Value \u2192 Except String Value\n  | nil,     nil      => return lit $ .bool true\n  | lit  l\u2097, lit l\u1d63   => return lit $ .bool $ l\u2097.eq l\u1d63\n  | list l\u2097, list  l\u1d63 => return lit $ .bool (listLiteralEq l\u2097 l\u1d63)\n  | lam .. , lam ..   => throw \"I can't compare functions\"\n  | _,       _        => return lit $ .bool false\n\ndef Value.ne : Value \u2192 Value \u2192 Except String Value\n  | nil,     nil      => return lit $ .bool false\n  | lit  l\u2097, lit l\u1d63   => return lit $ .bool $ !(l\u2097.eq l\u1d63)\n  | list l\u2097, list  l\u1d63 => return lit $ .bool !(listLiteralEq l\u2097 l\u1d63)\n  | lam ..,  lam ..   => throw \"I can't compare functions\"\n  | _,       _        => return lit $ .bool true\n\ndef Value.unOp : Value \u2192 UnOp \u2192 Except String Value\n  | v, .not => v.not\n\ndef Value.binOp : Value \u2192 Value \u2192 BinOp \u2192 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 \u2192 String\n    | .var  n    => n\n    | .lit  l    => l.toString\n    | .list l    => toString $ l.map Literal.toString\n    | .lam  _    => \"\u00abfunction\u00bb\"\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 := \u27e8exprToString\u27e9\n\ndef valToString : Value \u2192 String\n    | .nil    => \"\u00abnil\u00bb\"\n    | .lit  l => l.toString\n    | .list l => toString $ l.map Literal.toString\n    | .lam  _ => \"\u00abfunction\u00bb\"\n\ninstance : ToString Value := \u27e8valToString\u27e9\n\ndef consume (p : Program) :\n    NEList String \u2192 NEList Expression \u2192\n      Option ((Option (NEList String)) \u00d7 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, \u2190 h'.1]\n    | cons _ _ => exact hi h.2 h'\n\ninductive Continuation\n  | exit   : Continuation\n  | seq    : Program \u2192 Continuation \u2192 Continuation\n  | decl   : String \u2192 Continuation \u2192 Continuation\n  | fork   : Expression \u2192 Program \u2192 Program \u2192 Continuation \u2192 Continuation\n  | loop   : Expression \u2192 Program \u2192 Continuation \u2192 Continuation\n  | unOp   : UnOp \u2192 Expression \u2192 Continuation \u2192 Continuation\n  | binOp\u2081 : BinOp \u2192 Expression \u2192 Continuation \u2192 Continuation\n  | binOp\u2082 : BinOp \u2192 Value \u2192 Continuation \u2192 Continuation\n  | app    : Expression \u2192 NEList Expression \u2192 Continuation \u2192 Continuation\n  | block  : Context \u2192 Continuation \u2192 Continuation\n  | print  : Continuation \u2192 Continuation\n\ninductive State\n  | ret   : Value      \u2192 Context \u2192 Continuation \u2192 State\n  | prog  : Program    \u2192 Context \u2192 Continuation \u2192 State\n  | expr  : Expression \u2192 Context \u2192 Continuation \u2192 State\n  | error : ErrorType  \u2192 Context \u2192 String \u2192 State\n  | done  : Value      \u2192 Context \u2192 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 \u03b1 \u2192 Nat\n  | uno  _   => 1\n  | cons _ l => 1 + l.length\n\ndef State.step : State \u2192 State\n  | prog .skip c k => ret .nil c k\n  | prog (.eval e) c k => expr e c k\n  | prog (.seq p\u2081 p\u2082) c k => prog p\u2081 c (.seq p\u2082 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\u2081 e\u2082) c k => expr e\u2081 c (.binOp\u2081 o e\u2082 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\u2081 c (.binOp\u2081 o e\u2082 k) => expr e\u2082 c (.binOp\u2082 o v\u2081 k)\n  | ret v\u2082 c (.binOp\u2082 o v\u2081 k) => match v\u2081.binOp v\u2082 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 \u2192 Bool\n  | prog .. => true\n  | _       => false\n\ndef State.isEnd : State \u2192 Bool\n  | done  .. => true\n  | error .. => true\n  | _        => false\n\ndef State.stepN : State \u2192 Nat \u2192 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    \u2203 n, (ret v c k^[n]).isEnd \u2228 (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 \u27e81, by simp [stepN, step, isEnd]\u27e9\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 {\u03b1 : Sort u} {\u03b2 : Sort v} (op : \u03b1 \u2192 \u03b1 \u2192 \u03b2) {\u03c9 : Sort w} (m : \u03c9 \u2192 \u03b1) :\n  \u03c9 \u2192 \u03c9 \u2192 \u03b2 :=\n\u03bb a b => op (m a) (m b)\n\n\n\nnamespace GeneralizedProperty\n\n  variable {\u03b1 : Sort u} {V : Universe} (P : GeneralizedProperty \u03b1 V)\n           {\u03c9 : Sort w} (m : \u03c9 \u2192 \u03b1)\n\n  instance mapInst [h : HasInst P] : HasInst (P \u2218 m) := \u27e8\u03bb a => h.inst (m a)\u27e9\n\nend GeneralizedProperty\n\n\n\nnamespace GeneralizedRelation\n\n  variable {\u03b1 : Sort u} {V : Universe} (R : GeneralizedRelation \u03b1 V)\n\n  section Mapping\n\n    variable {\u03c9 : Sort w} (m : \u03c9 \u2192 \u03b1)\n\n    instance mapRefl  [h : HasRefl  R] : HasRefl  (mapOperation R m) := \u27e8\u03bb a => h.refl (m a)\u27e9\n\n    variable [HasInternalFunctors V]\n\n    instance mapSymm  [h : HasSymm  R] : HasSymm  (mapOperation R m) := \u27e8h.symm\u27e9\n    instance mapTrans [h : HasTrans R] : HasTrans (mapOperation R m) := \u27e8h.trans\u27e9\n\n    instance mapPreorder    [IsPreorder    R] : IsPreorder    (mapOperation R m) := \u27e8\u27e9\n    instance mapEquivalence [IsEquivalence R] : IsEquivalence (mapOperation R m) := \u27e8\u27e9\n\n  end Mapping\n\n  section Identity\n\n    @[simp] theorem mapRefl.id  [h : HasRefl  R] : mapRefl  R id = h := match h with | \u27e8_\u27e9 => rfl\n\n    variable [HasInternalFunctors V]\n\n    @[simp] theorem mapSymm.id  [h : HasSymm  R] : mapSymm  R id = h := match h with | \u27e8_\u27e9 => rfl\n    @[simp] theorem mapTrans.id [h : HasTrans R] : mapTrans R id = h := match h with | \u27e8_\u27e9 => 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 {\u03b1 : Sort u} {V : Universe} [HasInternalFunctors V] [HasInstanceArrows V]\n           (R : GeneralizedRelation \u03b1 V)\n           {\u03c9 : Sort w} (m : \u03c9 \u2192 \u03b1)\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    := \u03bb a => h.idInv (m a) }\n\nend Morphisms\n\n\n\nsection Functors\n\n  variable {\u03b1 : Sort u} {V W : Universe} [HasInstanceArrows W] [HasExternalFunctors V W]\n           (R : GeneralizedRelation \u03b1 V) (S : GeneralizedRelation \u03b1 W)\n           (F : BaseFunctor R S)\n           {\u03c9 : Sort w} (m : \u03c9 \u2192 \u03b1)\n\n  instance mapReflFunctor  [HasRefl  R] [HasRefl  S] [h : IsReflFunctor  R S F] :\n    IsReflFunctor  (mapOperation R m) (mapOperation S m) F :=\n  \u27e8\u03bb a => h.respectsRefl (m a)\u27e9\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  \u27e8h.respectsSymm\u27e9\n\n  instance mapTransFunctor [HasTrans R] [HasTrans S] [h : IsTransFunctor R S F] :\n    IsTransFunctor (mapOperation R m) (mapOperation S m) F :=\n  \u27e8h.respectsTrans\u27e9\n\n  instance mapPreorderFunctor    [IsPreorder    R] [IsPreorder    S] [IsPreorderFunctor    R S F] :\n    IsPreorderFunctor    (mapOperation R m) (mapOperation S m) F := \u27e8\u27e9\n  instance mapEquivalenceFunctor [IsEquivalence R] [IsEquivalence S] [IsEquivalenceFunctor R S F] :\n    IsEquivalenceFunctor (mapOperation R m) (mapOperation S m) F := \u27e8\u27e9\n\nend Functors\n\n\n\nsection NaturalTransformations\n\n  variable {\u03b1 : Sort u} {\u03b2 : Sort v} {V W : Universe} [HasInternalFunctors W] [HasInstanceEquivalences W] [HasExternalFunctors V W]\n           (R : GeneralizedRelation \u03b1 V) (S : GeneralizedRelation \u03b2 W) [h : HasTrans S]\n           {mF mG : \u03b1 \u2192 \u03b2} (F : \u2200 {a b}, R a b \u27f6' S (mF a) (mF b)) (G : \u2200 {a b}, R a b \u27f6' S (mG a) (mG b))\n           (n : \u2200 a, S (mF a) (mG a))\n           {\u03c9 : Sort w} (m : \u03c9 \u2192 \u03b1)\n  \n  instance mapNaturality [h : IsNatural R S F G n] :\n    IsNatural (mapOperation R m) S F G (\u03bb a => n (m a)) :=\n  \u27e8h.nat\u27e9\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": "/-\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, S\u00e9bastien Gou\u00ebzel, Scott Morrison\n-/\nimport logic.nonempty\nimport tactic.lint\nimport tactic.dependencies\n\nsetup_tactic_parser\n\nnamespace tactic\nnamespace interactive\nopen interactive interactive.types expr\n\n/-- Similar to `constructor`, but does not reorder goals. -/\nmeta def fconstructor : tactic unit := concat_tags tactic.fconstructor\n\nadd_tactic_doc\n{ name       := \"fconstructor\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.fconstructor],\n  tags       := [\"logic\", \"goal management\"] }\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 \u2190 i_to_expr_strict max >>= tactic.eval_expr nat,\n  \u03bb s, match _root_.try_for max (tac s) with\n  | some r := r\n  | none   := (tactic.trace \"try_for timeout, using sorry\" >> tactic.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 :=\npropagate_tags $ l.mmap' (\u03bb h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"substs\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.substs],\n  tags       := [\"rewriting\"] }\n\n/-- Unfold coercion-related definitions -/\nmeta def unfold_coes (loc : parse location) : tactic unit :=\nunfold [\n  ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,\n  ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,\n  ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc\n\nadd_tactic_doc\n{ name       := \"unfold_coes\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.unfold_coes],\n  tags       := [\"simplification\"] }\n\n\n/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/\nmeta def unfold_wf :=\npropagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof)\n\n/-- Unfold auxiliary definitions associated with the current declaration. -/\nmeta def unfold_aux : tactic unit :=\ndo tgt \u2190 target,\n   name \u2190 decl_name,\n   let to_unfold := (tgt.list_names_with_prefix name),\n   guard (\u00ac 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\u03bb s, result.cases_on (tac s)\n (\u03bb a, result.success ())\n (\u03bb e ref, result.success ())\n\n/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without\nrequiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a\nnon-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/\n@[inline] protected meta def id (tac : itactic) : tactic unit := tac\n\n/--\n`work_on_goal n { tac }` creates a block scope for the `n`-goal,\nand does not require that the goal be solved at the end\n(any remaining subgoals are inserted back into the list of goals).\n\nTypically usage might look like:\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 3\n{ dsimp,\n  simp },\nrefl\n````\n\nSee also `id { tac }`, which is equivalent to `work_on_goal 1 { tac }`.\n-/\nmeta def work_on_goal : parse small_nat \u2192 itactic \u2192 tactic unit\n| 0 t := fail \"work_on_goal failed: goals are 1-indexed\"\n| (n+1) t := do\n  goals \u2190 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 \u2190 get_goals,\n  set_goals (earlier_goals ++ new_goals ++ later_goals)\n\n/--\n`swap n` will move the `n`th goal to the front.\n`swap` defaults to `swap 2`, and so interchanges the first and second goals.\n\nSee also `tactic.interactive.rotate`, which moves the first `n` goals to the back.\n-/\nmeta def swap (n := 2) : tactic unit :=\ndo gs \u2190 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\nadd_tactic_doc\n{ name       := \"swap\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.swap],\n  tags       := [\"goal management\"] }\n\n/--\n`rotate` moves the first goal to the back. `rotate n` will do this `n` times.\n\nSee also `tactic.interactive.swap`, which moves the `n`th goal to the front.\n-/\nmeta def rotate (n := 1) : tactic unit := tactic.rotate n\n\nadd_tactic_doc\n{ name       := \"rotate\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.rotate],\n  tags       := [\"goal management\"] }\n\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\nmeta def clear_ : tactic unit := tactic.repeat $ do\n  l \u2190 local_context,\n  l.reverse.mfirst $ \u03bb h, do\n    name.mk_string s p \u2190 return $ local_pp_name h,\n    guard (s.front = '_'),\n    cl \u2190 infer_type h >>= is_class, guard (\u00ac cl),\n    tactic.clear h\n\nadd_tactic_doc\n{ name       := \"clear_\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_],\n  tags       := [\"context management\"] }\n\n/--\nActs like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p \u22a2 goal` and `f : p \u2192 q`,\nthen after `replace h := f h` the goal will be `h : q \u22a2 goal`,\nwhere `have h := f h` would result in the state `h : p, h : q \u22a2 goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nmeta def replace (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?)\n  (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\ndo let h := h.get_or_else `this,\n  old \u2190 try_core (get_local h),\n  \u00abhave\u00bb h q\u2081 q\u2082,\n  match old, q\u2082 with\n  | none,   _      := skip\n  | some o, some _ := tactic.clear o\n  | some o, none   := swap >> tactic.clear o >> swap\n  end\n\nadd_tactic_doc\n{ name       := \"replace\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.replace],\n  tags       := [\"context management\"] }\n\n/-- Make every proposition in the context decidable.\n\n`classical!` does this more aggressively, such that even if a decidable instance is already\navailable for a specific proposition, the noncomputable one will be used instead. -/\nmeta def classical (bang : parse $ (tk \"!\")?) :=\ntactic.classical bang.is_some\n\nadd_tactic_doc\n{ name       := \"classical\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.classical],\n  tags       := [\"classical logic\", \"type class\"] }\n\nprivate meta def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\n@[nolint def_lemma]\nnoncomputable\nlemma {u} generalize_a_aux {\u03b1 : Sort u}\n  (h : \u2200 x : Sort u, (\u03b1 \u2192 x) \u2192 x) : \u03b1 := h \u03b1 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' \u2190 get_unused_name `h,\n   x' \u2190 get_unused_name `x,\n   g \u2190 if \u00ac 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 \u2190 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\nadd_tactic_doc\n{ name       := \"generalize_hyp\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize_hyp],\n  tags       := [\"context management\"] }\n\nmeta def compact_decl_aux : list name \u2192 binder_info \u2192 expr \u2192 list expr \u2192\n  tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| ns bi t [] := pure [(ns.reverse, bi, t)]\n| ns bi t (v'@(local_const n pp bi' t') :: xs) :=\n  do t' \u2190 infer_type v',\n     if bi = bi' \u2227 t = t'\n       then compact_decl_aux (pp :: ns) bi t xs\n       else do vs \u2190 compact_decl_aux [pp] bi' t' xs,\n               pure $ (ns.reverse, bi, t) :: vs\n| ns bi t (_ :: xs) := compact_decl_aux ns bi t xs\n\n/-- go from (x\u2080 : t\u2080) (x\u2081 : t\u2080) (x\u2082 : t\u2080) to (x\u2080 x\u2081 x\u2082 : t\u2080) -/\nmeta def compact_decl : list expr \u2192 tactic (list (list name \u00d7 binder_info \u00d7 expr))\n| [] := pure []\n| (v@(local_const n pp bi t) :: xs)  :=\n  do t \u2190 infer_type v,\n     compact_decl_aux [pp] bi t xs\n| (_ :: xs) := compact_decl xs\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.\n-/\nmeta def clean (q : parse texpr) : tactic unit :=\ndo tgt : expr \u2190 target,\n   e \u2190 i_to_expr_strict ``(%%q : %%tgt),\n   tactic.exact $ e.clean\n\nmeta def source_fields (missing : list name) (e : pexpr) : tactic (list (name \u00d7 pexpr)) :=\ndo e \u2190 to_expr e,\n   t \u2190 infer_type e,\n   let struct_n : name := t.get_app_fn.const_name,\n   fields \u2190 expanded_field_list struct_n,\n   let exp_fields := fields.filter (\u03bb x, x.2 \u2208 missing),\n   exp_fields.mmap $ \u03bb \u27e8p,n\u27e9,\n     (prod.mk n \u2218 to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]\n\nmeta def collect_struct' : pexpr \u2192 state_t (list $ expr\u00d7structure_instance_info) tactic pexpr | e :=\ndo some str \u2190 pure (e.get_structure_instance_info)\n       | e.traverse collect_struct',\n   v \u2190 monad_lift mk_mvar,\n   modify (list.cons (v,str)),\n   pure $ to_pexpr v\n\nmeta def collect_struct (e : pexpr) : tactic $ pexpr \u00d7 list (expr\u00d7structure_instance_info) :=\nprod.map id list.reverse <$> (collect_struct' e).run []\n\nmeta def refine_one (str : structure_instance_info) :\n  tactic $ list (expr\u00d7structure_instance_info) :=\ndo    tgt \u2190 target >>= whnf,\n      let struct_n : name := tgt.get_app_fn.const_name,\n      exp_fields \u2190 expanded_field_list struct_n,\n      let missing_f := exp_fields.filter (\u03bb f, (f.2 : name) \u2209 str.field_names),\n      (src_field_names,src_field_vals) \u2190 (@list.unzip name _ \u2218 list.join) <$>\n        str.sources.mmap (source_fields $ missing_f.map prod.snd),\n      let provided  := exp_fields.filter (\u03bb f, (f.2 : name) \u2208 str.field_names),\n      let missing_f' := missing_f.filter (\u03bb x, x.2 \u2209 src_field_names),\n      vs \u2190 mk_mvar_list missing_f'.length,\n      (field_values,new_goals) \u2190 list.unzip <$> (str.field_values.mmap collect_struct : tactic _),\n      e' \u2190 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 \u2190 with_enable_tags (\n        mzip_with (\u03bb (n : name \u00d7 name) v, do\n           set_goals [v],\n           try (dsimp_target simp_lemmas.mk),\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 \u00d7 structure_instance_info \u2192 tactic (list expr) | (e,str) :=\ndo set_goals [e],\n   rs \u2190 refine_one str,\n   gs \u2190 get_goals,\n   gs' \u2190 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 of semigroup\ninstances:\n\n```lean\nrefine_struct ( { .. } : semigroup \u03b1 ),\n-- case semigroup, mul\n-- \u03b1 : Type u,\n-- \u22a2 \u03b1 \u2192 \u03b1 \u2192 \u03b1\n\n-- case semigroup, mul_assoc\n-- \u03b1 : Type u,\n-- \u22a2 \u2200 (a b c : \u03b1), a * b * c = a * (b * c)\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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nmeta def refine_struct : parse texpr \u2192 tactic unit | e :=\ndo (x,xs) \u2190 collect_struct e,\n   refine x,\n   gs \u2190 get_goals,\n   xs' \u2190 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 \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p\n\n/--\n`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).\nWe use this tactic for writing tests.\n-/\nmeta def match_hyp (n : parse ident) (p : parse $ tk \":\" *> texpr) (m := reducible) :\n  tactic (list expr) :=\ndo\n  h \u2190 get_local n >>= infer_type >>= instantiate_mvars,\n  match_expr p h m\n\n/--\n`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast\nto `guard_expr`, this tests strict (syntactic) equality.\nWe use this tactic for writing tests.\n-/\nmeta def guard_expr_strict (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, guard (t = e)\n\n/--\n`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_target_strict (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_strict t p\n\n/--\n`guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal\nto `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_hyp_strict (n : parse ident) (p : parse $ tk \":\" *> texpr) : tactic unit :=\ndo h \u2190 get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p\n\n/-- Tests that there are `n` hypotheses in the current context. -/\nmeta def guard_hyp_nums (n : \u2115) : tactic unit :=\ndo k \u2190 local_context,\n   guard (n = k.length) <|> fail format!\"{k.length} hypotheses found\"\n\n/--\n`guard_hyp_mod_implicit h : t` fails if the type of the hypothesis `h`\nis not definitionally equal to `t` modulo none transparency\n(i.e., unifying the implicit arguments modulo semireducible transparency).\nWe use this tactic for writing tests.\n-/\nmeta def guard_hyp_mod_implicit (n : parse ident) (p : parse $ tk \":\" *> texpr) : tactic unit := do\nh \u2190 get_local n >>= infer_type >>= instantiate_mvars,\ne \u2190 to_expr p,\nis_def_eq h e transparency.none\n\n/--\n`guard_target_mod_implicit t` fails if the target of the main goal\nis not definitionally equal to `t` modulo none transparency\n(i.e., unifying the implicit arguments modulo semireducible transparency).\nWe use this tactic for writing tests.\n-/\nmeta def guard_target_mod_implicit (p : parse texpr) : tactic unit := do\ntgt \u2190 target,\ne \u2190 to_expr p,\nis_def_eq tgt e transparency.none\n\n/-- Test that `t` is the tag of the main goal. -/\nmeta def guard_tags (tags : parse ident*) : tactic unit :=\ndo (t : list name) \u2190 get_main_tag,\n   guard (t = tags)\n\n/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term\n  unifies with `p`. -/\nmeta def guard_proof_term (t : itactic) (p : parse texpr) : itactic :=\ndo\n  g :: _ \u2190 get_goals,\n  e \u2190 to_expr p,\n  t,\n  g \u2190 instantiate_mvars g,\n  unify e g\n\n/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with\nerror message `msg` (for test writing purposes). -/\nmeta def success_if_fail_with_msg (tac : tactic.interactive.itactic) :=\ntactic.success_if_fail_with_msg tac\n\n/-- Get the field of the current goal. -/\nmeta def get_current_field : tactic name :=\ndo [_,field,str] \u2190 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 \u2190 get_goals,\n   ts \u2190 gs.mmap get_tag,\n   ([g],gs') \u2190 pure $ (list.zip gs ts).partition (\u03bb 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```lean\nrefine_struct ({ .. } : semigroup \u03b1),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```lean\nrefine_struct ({ .. } : semigroup \u03b1),\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\nadd_tactic_doc\n{ name       := \"refine_struct\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field,\n                 `tactic.interactive.have_field],\n  tags       := [\"structures\"],\n  inherit_description_from := `tactic.interactive.refine_struct }\n\n/--\n`apply_rules hs with attrs n` applies the list of lemmas `hs` and all lemmas tagged with an\nattribute from the list `attrs`, as well as the `assumption` tactic on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is optional, equal to 50 by default.\nYou can pass an `apply_cfg` option argument as `apply_rules hs n opt`.\n(A typical usage would be with `apply_rules hs n { md := reducible }`,\nwhich asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)\nwhen checking if a lemma matches the goal.)\n\nFor instance:\n\n```lean\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 \u2264 b) (h2 : c \u2264 d) (h3 : 0 \u2264 e) :\na + c * e + a + c + 0 \u2264 b + d * e + b + d + e :=\n-- any of the following lines solve the goal:\nadd_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\nby apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\nby apply_rules with mono_rules\nby apply_rules [add_le_add] with mono_rules\n```\n-/\nmeta def apply_rules (args : parse opt_pexpr_list) (attrs : parse with_ident_list)\n  (n : nat := 50) (opt : apply_cfg := {}) :\n  tactic unit :=\ntactic.apply_rules args attrs n opt\n\nadd_tactic_doc\n{ name       := \"apply_rules\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.apply_rules],\n  tags       := [\"lemma application\"] }\n\nmeta def return_cast (f : option expr) (t : option (expr \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr))\n  (e x x' eq_h : expr) :\n  tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 expr)) :=\n(do guard (\u00ac e.has_var),\n    unify x x',\n    u \u2190 mk_meta_univ,\n    f \u2190 f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],\n    t' \u2190 infer_type e,\n    some (f',t) \u2190 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 \u00d7 expr))\n  (es : list (expr \u00d7 expr \u00d7 expr)) :\n  expr \u2192 tactic (option (expr \u00d7 expr) \u00d7 list (expr \u00d7 expr \u00d7 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 %%\u03b1 %%p %%a %%b  %%eq_h %%x') := return_cast p t es e x x' eq_h\n| e@`(@eq.substr %%\u03b1 %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'\n| e@`(@eq.rec %%\u03b1 %%a %%f %%x' _  %%eq_h) := return_cast f t es e x x' eq_h\n| e@`(@eq.rec_on %%\u03b1 %%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 \u00d7 expr \u00d7 expr)) :=\n(list.reverse \u2218 prod.snd) <$> tgt.mfold (none, []) (\u03bb e i es, list_cast_of_aux x es.1 es.2 e)\n\nprivate meta def h_generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 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 \u00d7 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 `\u03b1 = \u03b2` with `e : \u03b1, x : \u03b2`;\n- `h_generalize Hx : e == x with _` chooses automatically chooses the name of\n  assumption `\u03b1 = \u03b2`;\n- `h_generalize! Hx : e == x` reverts `Hx`;\n- when `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' \u2190 (h' : tactic name) <|> get_unused_name (\"h\" ++ n.to_string : string),\n   e \u2190 to_expr e,\n   tgt \u2190 target,\n   ((e,x,eq_h)::es) \u2190 list_cast_of e tgt | fail \"no cast found\",\n   interactive.generalize h' () (to_pexpr e, n),\n   asm \u2190 get_local h',\n   v \u2190 get_local n,\n   hs \u2190 es.mmap (\u03bb \u27e8e,_\u27e9, mk_app `eq [e,v]),\n   (eqs_h.zip [e]).mmap' (\u03bb \u27e8h,e\u27e9, do\n        h \u2190 if h \u2260 `_ then pure h else get_unused_name `h,\n        () <$ note h none eq_h ),\n   hs.mmap' (\u03bb h,\n     do h' \u2190 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_cast_eq %%eq_h %%asm))\n     >>= note h' none >> pure ()),\n   tactic.clear asm,\n   when rev.is_some (interactive.revert [n])\n\nadd_tactic_doc\n{ name       := \"h_generalize\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.h_generalize],\n  tags       := [\"context management\"] }\n\n/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that\n  this uses definitional equality instead of alpha-equivalence. -/\nmeta def guard_expr_eq' (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, is_def_eq t e\n\n/--\n`guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.\nWe use this tactic for writing tests.\nThe difference with `guard_target` is that this uses definitional equality instead of\nalpha-equivalence.\n-/\nmeta def guard_target' (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_eq' t p\n\nadd_tactic_doc\n{ name       := \"guard_target'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.guard_target'],\n  tags       := [\"testing\"] }\n\n/--\nTries to solve the goal using a canonical proof of `true` or the `reflexivity` tactic.\nUnlike `trivial` or `trivial'`, does not the `contradiction` tactic.\n-/\nmeta def triv : tactic unit :=\ntactic.triv <|> tactic.reflexivity <|> fail \"triv tactic failed\"\n\nadd_tactic_doc\n{ name       := \"triv\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.triv],\n  tags       := [\"finishing\"] }\n\n/--\nA weaker version of `trivial` that tries to solve the goal using a canonical proof of `true` or the\n`reflexivity` tactic (unfolding only `reducible` constants, so can fail faster than `trivial`),\nand otherwise tries the `contradiction` tactic. -/\nmeta def trivial' : tactic unit :=\ntactic.triv'\n  <|> tactic.reflexivity reducible\n  <|> tactic.contradiction\n  <|> fail \"trivial' tactic failed\"\n\nadd_tactic_doc\n{ name       := \"trivial'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.trivial'],\n  tags       := [\"finishing\"] }\n\n/--\nSimilar to `existsi`. `use x` will instantiate the first term of an `\u2203` or `\u03a3` goal with `x`. It\nwill then try to close the new goal using `trivial'`, or try to simplify it by applying\n`exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type.\n`use` will alternatively take a list of terms `[x0, ..., xn]`.\n\n`use` will work with constructors of arbitrary inductive types.\n\nExamples:\n```lean\nexample (\u03b1 : Type) : \u2203 S : set \u03b1, S = S :=\nby use \u2205\n\nexample : \u2203 x : \u2124, x = x :=\nby use 42\n\nexample : \u2203 n > 0, n = n :=\nbegin\n  use 1,\n  -- goal is now 1 > 0 \u2227 1 = 1, whereas it would be \u2203 (H : 1 > 0), 1 = 1 after existsi 1.\n  exact \u27e8zero_lt_one, rfl\u27e9,\nend\n\nexample : \u2203 a b c : \u2124, a + b + c = 6 :=\nby use [1, 2, 3]\n\nexample : \u2203 p : \u2124 \u00d7 \u2124, p.1 = 1 :=\nby use \u27e81, 42\u27e9\n\nexample : \u03a3 x y : \u2124, (\u2124 \u00d7 \u2124) \u00d7 \u2124 :=\nby use [1, 2, 3, 4, 5]\n\ninductive foo\n| mk : \u2115 \u2192 bool \u00d7 \u2115 \u2192 \u2115 \u2192 foo\n\nexample : foo :=\nby use [100, tt, 4, 3]\n```\n-/\nmeta def use (l : parse pexpr_list_or_texpr) : tactic unit :=\nfocus1 $\n  tactic.use l;\n  try (trivial' <|> (do\n        `(Exists %%p) \u2190 target,\n        to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip))\n\nadd_tactic_doc\n{ name       := \"use\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.use, `tactic.interactive.existsi],\n  tags       := [\"logic\"],\n  inherit_description_from := `tactic.interactive.use }\n\n/--\n`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.\nThis includes the induction hypothesis when using the equation compiler and\n`_let_match` and `_fun_match`.\n\nIt is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these\nauxiliary declarations, and produce an error saying the recursion is not well founded.\n\n```lean\nexample (n m : \u2115) (h\u2081 : n = m) (h\u2082 : \u2203 a : \u2115, a = n \u2227 a = m) : 2 * m = 2 * n :=\nlet \u27e8a, ha\u27e9 := h\u2082 in\nbegin\n  clear_aux_decl, -- subst will fail without this line\n  subst h\u2081\nend\n\nexample (x y : \u2115) (h\u2081 : \u2203 n : \u2115, n * 1 = 2) (h\u2082 : 1 + 1 = 2 \u2192 x * 1 = y) : x = y :=\nlet \u27e8n, hn\u27e9 := h\u2081 in\nbegin\n  clear_aux_decl, -- finish produces an error without this line\n  finish\nend\n```\n-/\nmeta def clear_aux_decl : tactic unit := tactic.clear_aux_decl\n\nadd_tactic_doc\n{ name       := \"clear_aux_decl\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl],\n  tags       := [\"context management\"],\n  inherit_description_from := `tactic.interactive.clear_aux_decl }\n\nmeta def loc.get_local_pp_names : loc \u2192 tactic (list name)\n| loc.wildcard := list.map expr.local_pp_name <$> local_context\n| (loc.ns l) := return l.reduce_option\n\nmeta def loc.get_local_uniq_names (l : loc) : tactic (list name) :=\nlist.map expr.local_uniq_name <$> l.get_locals\n\n/--\nThe logic of `change x with y at l` fails when there are dependencies.\n`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.\nIn this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses\nin `l`. As long as `x` and `y` are defeq, it should never fail.\n-/\nmeta def change' (q : parse texpr) : parse (tk \"with\" *> texpr)? \u2192 parse location \u2192 tactic unit\n| none (loc.ns [none]) := do e \u2190 i_to_expr q, change_core e none\n| none (loc.ns [some h]) := do eq \u2190 i_to_expr q, eh \u2190 get_local h, change_core eq (some eh)\n| none _ := fail \"change-at does not support multiple locations\"\n| (some w) l :=\n  do l' \u2190 loc.get_local_pp_names l,\n     l'.mmap' (\u03bb e, try (change_with_at q w e)),\n     when l.include_goal $ change q w (loc.ns [none])\n\nadd_tactic_doc\n{ name       := \"change'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.change', `tactic.interactive.change],\n  tags       := [\"renaming\"],\n  inherit_description_from := `tactic.interactive.change' }\n\nprivate meta def opt_dir_with : parser (option (bool \u00d7 name)) :=\n(tk \"with\" *> ((\u03bb arrow h, (option.is_some arrow, h)) <$> (tk \"<-\")? <*> ident))?\n\n/--\n`set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to\nthe local context and replaces `t` with `a` everywhere it can.\n\n`set a := t with \u2190h` will add `h : t = a` instead.\n\n`set! a := t with h` does not do any replacing.\n\n```lean\nexample (x : \u2115) (h : x = 3)  : x + x + x = 9 :=\nbegin\n  set y := x with \u2190h_xy,\n/-\nx : \u2115,\ny : \u2115 := x,\nh_xy : x = y,\nh : y = 3\n\u22a2 y + y + y = 9\n-/\nend\n```\n-/\nmeta def set (h_simp : parse (tk \"!\")?) (a : parse ident) (tp : parse ((tk \":\") *> texpr)?)\n  (_ : parse (tk \":=\")) (pv : parse texpr)\n  (rev_name : parse opt_dir_with) :=\ndo tp \u2190 i_to_expr $ let t := tp.get_or_else pexpr.mk_placeholder in ``(%%t : Sort*),\n   pv \u2190 to_expr ``(%%pv : %%tp),\n   tp \u2190 instantiate_mvars tp,\n   definev a tp pv,\n   when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard,\n   match rev_name with\n   | some (flip, id) :=\n     do nv \u2190 get_local a,\n        mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id,\n        reflexivity\n   | none := skip\n   end\n\nadd_tactic_doc\n{ name       := \"set\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.set],\n  tags       := [\"context management\"] }\n\n/--\n`clear_except h\u2080 h\u2081` deletes all the assumptions it can except for `h\u2080` and `h\u2081`.\n-/\nmeta def clear_except (xs : parse ident *) : tactic unit :=\ndo n \u2190 xs.mmap (try_core \u2218 get_local) >>= revert_lst \u2218 list.filter_map id,\n   ls \u2190 local_context,\n   ls.reverse.mmap' $ try \u2218 tactic.clear,\n   intron_no_renames n\n\nadd_tactic_doc\n{ name       := \"clear_except\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_except],\n  tags       := [\"context management\"] }\n\n\nmeta def format_names (ns : list name) : format :=\nformat.join $ list.intersperse \" \" (ns.map to_fmt)\n\nprivate meta def indent_bindents (l r : string) : option (list name) \u2192 expr \u2192 tactic format\n| none e :=\n  do e \u2190 pp e,\n     pformat!\"{l}{format.nest l.length e}{r}\"\n| (some ns) e :=\n  do e \u2190 pp e,\n     let ns := format_names ns,\n     let margin := l.length + ns.to_string.length + \" : \".length,\n     pformat!\"{l}{ns} : {format.nest margin e}{r}\"\n\nprivate meta def format_binders : list name \u00d7 binder_info \u00d7 expr \u2192 tactic format\n| (ns, binder_info.default, t) := indent_bindents \"(\" \")\" ns t\n| (ns, binder_info.implicit, t) := indent_bindents \"{\" \"}\" ns t\n| (ns, binder_info.strict_implicit, t) := indent_bindents \"\u2983\" \"\u2984\" ns t\n| ([n], binder_info.inst_implicit, t) :=\n  if \"_\".is_prefix_of n.to_string\n    then indent_bindents \"[\" \"]\" none t\n    else indent_bindents \"[\" \"]\" [n] t\n| (ns, binder_info.inst_implicit, t) := indent_bindents \"[\" \"]\" ns t\n| (ns, binder_info.aux_decl, t) := indent_bindents \"(\" \")\" ns t\n\nprivate meta def partition_vars' (s : name_set) :\n  list expr \u2192 list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr)\n| [] as bs := pure (as.reverse, bs.reverse)\n| (x :: xs) as bs :=\ndo t \u2190 infer_type x,\n   if t.has_local_in s then partition_vars' xs as (x :: bs)\n     else partition_vars' xs (x :: as) bs\n\nprivate meta def partition_vars : tactic (list expr \u00d7 list expr) :=\ndo ls \u2190 local_context,\n   partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] []\n\n/--\nFormat the current goal as a stand-alone example. Useful for testing tactics\nor creating [minimal working examples](https://leanprover-community.github.io/mwe.html).\n\n* `extract_goal`: formats the statement as an `example` declaration\n* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration\n  called `my_decl`\n* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration\n\nExamples:\n\n```lean\nexample (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\nbegin\n  extract_goal,\n     -- prints:\n     -- example (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\n  extract_goal my_lemma\n     -- prints:\n     -- lemma my_lemma (i j k : \u2115) (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) : i \u2264 k :=\n     -- begin\n     --   admit,\n     -- end\nend\n\nexample {i j k x y z w p q r m n : \u2115} (h\u2080 : i \u2264 j) (h\u2081 : j \u2264 k) (h\u2081 : k \u2264 p) (h\u2081 : p \u2264 q) : i \u2264 k :=\nbegin\n  extract_goal my_lemma,\n    -- prints:\n    -- lemma my_lemma {i j k x y z w p q r m n : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p)\n    --   (h\u2081 : p \u2264 q) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\n\n  extract_goal my_lemma with i j k\n    -- prints:\n    -- lemma my_lemma {p i j k : \u2115}\n    --   (h\u2080 : i \u2264 j)\n    --   (h\u2081 : j \u2264 k)\n    --   (h\u2081 : k \u2264 p) :\n    --   i \u2264 k :=\n    -- begin\n    --   admit,\n    -- end\nend\n\nexample : true :=\nbegin\n  let n := 0,\n  have m : \u2115, admit,\n  have k : fin n, admit,\n  have : n + m + k.1 = 0, extract_goal,\n    -- prints:\n    -- example (m : \u2115)  : let n : \u2115 := 0 in \u2200 (k : fin n), n + m + k.val = 0 :=\n    -- begin\n    --   intros n k,\n    --   admit,\n    -- end\nend\n```\n\n-/\nmeta def extract_goal (print_use : parse $ (tk \"!\" *> pure tt) <|> pure ff)\n  (n : parse ident?) (vs : parse (tk \"with\" *> ident*)?)\n  : tactic unit :=\ndo tgt \u2190 target,\n   solve_aux tgt $ do\n   { ((cxt\u2080,cxt\u2081,ls,tgt),_) \u2190 solve_aux tgt $ do\n       { vs.mmap clear_except,\n         ls \u2190 local_context,\n         ls \u2190 ls.mfilter $ succeeds \u2218 is_local_def,\n         n \u2190 revert_lst ls,\n         (c\u2080,c\u2081) \u2190 partition_vars,\n         tgt \u2190 target,\n         ls \u2190 intron' n,\n         pure (c\u2080,c\u2081,ls,tgt) },\n     is_prop \u2190 is_prop tgt,\n     let title := match n, is_prop with\n                  | none, _ := to_fmt \"example\"\n                  | (some n), tt := format!\"lemma {n}\"\n                  | (some n), ff := format!\"def {n}\"\n                  end,\n     cxt\u2080 \u2190 compact_decl cxt\u2080 >>= list.mmap format_binders,\n     cxt\u2081 \u2190 compact_decl cxt\u2081 >>= list.mmap format_binders,\n     stmt \u2190 pformat!\"{tgt} :=\",\n     let fmt :=\n       format.group $ format.nest 2 $\n         title ++ cxt\u2080.foldl (\u03bb acc x, acc ++ format.group (format.line ++ x)) \"\" ++\n         format.join (list.map (\u03bb x, format.line ++ x) cxt\u2081) ++ \" :\" ++\n         format.line ++ stmt,\n     trace $ fmt.to_string $ options.mk.set_nat `pp.width 80,\n     let var_names := format.intercalate \" \" $ ls.map (to_fmt \u2218 local_pp_name),\n     let call_intron := if ls.empty\n                     then to_fmt \"\"\n                     else format!\"\\n  intros {var_names},\",\n     trace!\"begin{call_intron}\\n  admit,\\nend\\n\" },\n   skip\n\nadd_tactic_doc\n{ name       := \"extract_goal\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.extract_goal],\n  tags       := [\"goal management\", \"proof extraction\", \"debugging\"] }\n\n/--\n`inhabit \u03b1` tries to derive a `nonempty \u03b1` instance and then upgrades this\nto an `inhabited \u03b1` instance.\nIf the target is a `Prop`, this is done constructively;\notherwise, it uses `classical.choice`.\n\n```lean\nexample (\u03b1) [nonempty \u03b1] : \u2203 a : \u03b1, true :=\nbegin\n  inhabit \u03b1,\n  existsi default,\n  trivial\nend\n```\n-/\nmeta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit :=\ndo ty \u2190 i_to_expr t,\n   nm \u2190 returnopt inst_name <|> get_unused_name `inst,\n   tgt \u2190 target,\n   tgt_is_prop \u2190 is_prop tgt,\n   if tgt_is_prop then do\n     decorate_error \"could not infer nonempty instance:\" $\n       mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply,\n     introI nm\n   else do\n     decorate_error \"could not infer nonempty instance:\" $\n      mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none,\n     resetI\n\nadd_tactic_doc\n{ name       := \"inhabit\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.inhabit],\n  tags       := [\"context management\", \"type class\"] }\n\n/-- `revert_deps n\u2081 n\u2082 ...` reverts all the hypotheses that depend on one of `n\u2081, n\u2082, ...`\nIt does not revert `n\u2081, n\u2082, ...` themselves (unless they depend on another `n\u1d62`). -/\nmeta def revert_deps (ns : parse ident*) : tactic unit :=\npropagate_tags $\n  ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `revert_after n` reverts all the hypotheses after `n`. -/\nmeta def revert_after (n : parse ident) : tactic unit :=\npropagate_tags $ get_local n >>= tactic.revert_after >> skip\n\nadd_tactic_doc\n{ name       := \"revert_after\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_after],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- Reverts all local constants on which the target depends (recursively). -/\nmeta def revert_target_deps : tactic unit :=\npropagate_tags $ tactic.revert_target_deps >> skip\n\nadd_tactic_doc\n{ name       := \"revert_target_deps\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.revert_target_deps],\n  tags       := [\"context management\", \"goal management\"] }\n\n/-- `clear_value n\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`. -/\nmeta def clear_value (ns : parse ident*) : tactic unit :=\npropagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value\n\nadd_tactic_doc\n{ name       := \"clear_value\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.clear_value],\n  tags       := [\"context management\"] }\n\n/--\n`generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of\nthe same type.\n\n`generalize' h : e = x` in addition registers the hypothesis `h : e = x`.\n\n`generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also\nsucceeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis\n`x` is not a local definition.\n-/\nmeta def generalize' (h : parse ident?) (_ : parse $ tk \":\") (p : parse generalize_arg_p) :\n  tactic unit :=\npropagate_tags $\ndo let (p, x) := p,\n   e \u2190 i_to_expr p,\n   some h \u2190 pure h | tactic.generalize' e x >> skip,\n   -- `h` is given, the regular implementation of `generalize` works.\n   tgt \u2190 target,\n   tgt' \u2190 do\n   { \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize e x >> target),\n     to_expr ``(\u03a0 x, %%e = x \u2192 %%(tgt'.binding_body.lift_vars 0 1)) }\n   <|> to_expr ``(\u03a0 x, %%e = x \u2192 %%tgt),\n   t \u2190 assert h tgt',\n   swap,\n   exact ``(%%t %%e rfl),\n   intro x,\n   intro h\n\nadd_tactic_doc\n{ name       := \"generalize'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.generalize'],\n  tags       := [\"context management\"] }\n\n/--\nIf the expression `q` is a local variable with type `x = t` or `t = x`, where `x` is a local\nconstant, `tactic.interactive.subst' q` substitutes `x` by `t` everywhere in the main goal and\nthen clears `q`.\nIf `q` is another local variable, then we find a local constant with type `q = t` or `t = q` and\nsubstitute `t` for `q`.\n\nLike `tactic.interactive.subst`, but fails with a nicer error message if the substituted variable is\na local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.\n-/\nmeta def subst' (q : parse texpr) : tactic unit := do\ni_to_expr q >>= tactic.subst' >> try (tactic.reflexivity reducible)\n\nadd_tactic_doc\n{ name       := \"subst'\",\n  category   := doc_category.tactic,\n  decl_names := [`tactic.interactive.subst'],\n  tags       := [\"context management\"] }\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220563966531905, "lm_q2_score": 0.0675466911396291, "lm_q1q2_score": 0.016360189534749606}}
{"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 \u27f6 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 := \u27e8x, y, _, e, rfl\u27e9,\n  obtain \u27e8z, hz, hz'\u27e9 := T.exists_preimage,\n  obtain \u27e8z', rfl\u27e9 := h z,\n  simp only [\u2190 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 \u27f6 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 := \u27e8x, y, _, e, rfl\u27e9,\n  obtain \u27e8z, hz, hz'\u27e9 := T.exists_preimage,\n  obtain \u27e8z', rfl\u27e9 := h z,\n  simp only [\u2190 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 \u27f6 Y) [mono f] : \n  function.injective f.1.base :=\nbegin\n  apply injective_of_surjective_diagonal,\n  exact (as_iso $ (Scheme.forget_to_Top \u22d9 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 \u27f6 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": "import Lean\nimport Lean.Elab.Command\nimport Lean.Elab.Tactic.Basic\nimport Mathlib.Lean.Expr\nimport Lean.Meta\nimport AssertCmd\n\nopen Lean Elab Elab.Tactic\n\n-- #print mkIdent\n\n-- #reduce Parser.Term.quot\n\ndef doWork : Command.CommandElabM Unit := do\n  for i in [0:256] do    -- stxs := stxs.push $  \n    -- let name := Syntax.mkNameLit s!\"name{i}\"\n    Command.elabCommand (\u2190 `(theorem $(mkIdent s!\"number{i}_lt\") : $(quote i) < 256 := by simp ))\n    Command.elabCommand (\u2190 `(def $(mkIdent s!\"number{i}\") : UInt8 := \u27e8 $(quote i), $(mkIdent s!\"number{i}_lt\") \u27e9 ))\n    -- Command.elabCommand (\u2190 `(theorem $(quote name) : $i < 256 := by simp))\n    pure ()\n\n  let mut matchArms : Array Syntax := #[]\n  for i in [0:256] do    -- stxs := stxs.push $  \n      -- let name := Syntax.mkNameLit s!\"name{i}\"\n      matchArms := matchArms.push (\u2190 `(Parser.Term.matchAltExpr| | $(quote i) => $(mkIdent s!\"number{i}\")))\n      -- Command.elabCommand (\u2190 `(theorem $(quote name) : $i < 256 := by simp))\n      pure ()\n\n  matchArms := matchArms.push (\u2190 `(Parser.Term.matchAltExpr| | n => \u27e8 0, by simp\u27e9 ))\n  \n  let dfn \u2190 `(def $(mkIdent \"fofNat\") (n : Nat) : UInt8 := match n % 256 with $matchArms:matchAlt*)\n  Command.elabCommand dfn\n\n-- constant a : 4 < 5 := by simp\n\n--   pure ()\n\nsyntax (name := genTest) \"gen_uint_helper_theorems\" : command\n@[commandElab genTest]\nunsafe def elabAssert : Command.CommandElab\n  | _ => do doWork\n\n-- set_option maxHeartbeats 500000\n-- gen_uint_helper_theorems\n\n-- def fofNat : Nat -> UInt8\n-- | n => UInt8.ofNat n\n\n-- -- opaque mod_lt_o (x : Nat) {y : Nat} : y > 0 \u2192 x % y < y := Nat.mod_lt\n-- @[irreducible] \n-- def tofNat (a : Nat) : UInt8 :=\n--   \u27e8a % 256, let x := Nat.mod_lt a (Nat.zero_lt_succ 255); x\u27e9\n\n\n-- local instance : OfNat UInt8 n where\n--   ofNat := match n with \n--   | 0 => \u27e8 0, name0\u27e9 \n--   | 1 => \u27e8 1, name1\u27e9 \n--   | _ => UInt8.ofNat n\n\n\n-- set_option maxRecDepth 10000\n-- set_option pp.all true\n\n@[inline]\ndef hexChar (c: Char): Option Nat :=\n  if '0' \u2264 c \u2227 c \u2264 '9' then\n    some $ c.val.toNat - '0'.val.toNat\n  else if 'a' \u2264 c \u2227 c \u2264 'f' then\n    some $ c.val.toNat - 'a'.val.toNat + 10\n  else if 'A' \u2264 c \u2227 c \u2264 'F' then\n    some $ c.val.toNat - 'A'.val.toNat + 10\n  else\n    none\n\ndef hexToByteArray(s: String): Option ByteArray := Id.run do\n  if s.length % 2 != 0 then return none\n  let mut res := ByteArray.mkEmpty $ s.length / 2\n  for i in [:((s.length)/2)] do\n    let v1 := hexChar (s[2*i])\n    let v2 := hexChar (s[2*i+1])\n    match (v1, v2) with \n    | (some v1, some v2) => res := res.push $ UInt8.ofNat ((16 * v1) + v2)\n    | _ => return none\n  return res\n\ndef hexToByteArray!(s: String): ByteArray := Id.run do\n  if s.length % 2 != 0 then return ByteArray.empty\n  let mut res := ByteArray.mkEmpty $ s.length / 2\n  for i in [:((s.length)/2)] do\n    let v1 := match hexChar (s[2*i]) with | Option.none => panic! \"Bad hex\" | Option.some x => x\n    let v2 := match hexChar (s[2*i+1]) with | Option.none => panic! \"Bad hex\" | Option.some x => x\n    let val := (16 * v1) + v2\n    -- res := res.push $ UInt8.ofNat val\n    res := res.push $ \u27e8 val, sorry \u27e9 \n  return res\n\ndef hexToByteList!(s: String): List UInt8 := Id.run do\n  if s.length % 2 != 0 then return []\n  let mut res : List UInt8 := []\n  for i in [:((s.length)/2)] do\n    let v1 := match hexChar (s[2*i]) with | Option.none => panic! \"Bad hex\" | Option.some x => x\n    let v2 := match hexChar (s[2*i+1]) with | Option.none => panic! \"Bad hex\" | Option.some x => x\n    let val := (16 * v1) + v2\n    -- res := res.push $ UInt8.ofNat val\n    res := List.cons \u27e8 val, sorry \u27e9 res\n  return res.reverse\n\ndef ByteArray.mkZeros (n:Nat) := Id.run do\n  let mut b := ByteArray.mkEmpty n\n  for i in [0:n] do\n    b := b.push 0\n  b\n\n\ndef byteArrayToHex(b: ByteArray) : String := \n  let parts := b.data.map (fun x => String.singleton (Nat.digitChar (x.toNat / 16)) ++ String.singleton (Nat.digitChar (x.toNat % 16)))\n  String.join parts.toList\n\n\nsyntax \"b[\" sepBy(term, \", \") \"]\" : term\nmacro_rules\n  | `(b[ $elems,* ]) => `(ByteArray.mk #[ $elems,* ])\n\n\n-- syntax (name := redComp) \"#redComp\" : command\n@[commandParser] def redComp := leading_parser \"#redComp \" >> Lean.Parser.termParser\n\n@[commandElab redComp]\ndef elabRedComp : Command.CommandElab\n  | `(#redComp%$tk $term) => withoutModifyingEnv <| Command.runTermElabM (some `_check) fun _ => do\n    let e \u2190 Term.elabTerm term none\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let (e, _) \u2190 Term.levelMVarToParam (\u2190 Meta.instantiateMVars e)\n    -- TODO: add options or notation for setting the following parameters\n    withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding true }) do\n      let e \u2190 Meta.withTransparency (mode := Meta.TransparencyMode.default) <| Meta.reduce e (skipProofs := true) (skipTypes := false)\n      logInfoAt tk e\n  | _ => throwUnsupportedSyntax\n\n@[commandParser] def red' := leading_parser \"#reduce' \" >> Lean.Parser.termParser\n@[commandElab red']\ndef elabRed' : Command.CommandElab\n  | `(#reduce'%$tk $term) => withoutModifyingEnv <| Command.runTermElabM (some `_check) fun _ => do\n    let e \u2190 Term.elabTerm term none\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let (e, _) \u2190 Term.levelMVarToParam (\u2190 Meta.instantiateMVars e)\n    -- TODO: add options or notation for setting the following parameters\n    withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding true }) do\n      let e \u2190 Meta.withTransparency (mode := Meta.TransparencyMode.default) <| Meta.reduce e (skipProofs := false) (skipTypes := false)\n      logInfoAt tk e\n  | _ => throwUnsupportedSyntax\n\n\n@[commandParser] def redDontPrint := leading_parser \"#redDontPrint \" >> Lean.Parser.termParser\n@[commandElab redDontPrint]\ndef elabRedDontPrint : Command.CommandElab\n  | `(#redDontPrint%$tk $term) => withoutModifyingEnv <| Command.runTermElabM (some `_check) fun _ => do\n    let e \u2190 Term.elabTerm term none\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let (e, _) \u2190 Term.levelMVarToParam (\u2190 Meta.instantiateMVars e)\n    -- TODO: add options or notation for setting the following parameters\n    withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding true }) do\n      let e \u2190 Meta.withTransparency (mode := Meta.TransparencyMode.default) <| Meta.reduce e (skipProofs := false) (skipTypes := false)\n      -- logInfoAt tk e\n  | _ => throwUnsupportedSyntax\n\n-- #print Lean.Parser.Command.reduce\n-- #reduce (\u27e85, sorry\u27e9 : UInt8)\n-- #reduce (5 : UInt8)\n\n-- #reduce String.foldr\n\n-- let rec loop (i : Pos) (a : \u03b1) :=\n--     if i == stopPos then a\n--     else loop (s.next i) (f a (s.get i))\n--   loop i a\n\ntheorem termination (t: String) (i: String.Pos) : String.length t - String.next t i < String.length t - i := by admit\n  -- simp [Nat.le_of_add_le_add_right, Nat.lt_of_succ_le]\n  -- simp [String.length, String.next, String.get, String.csize]\n\n@[specialize] private def loop [Monad m] (d: \u03c3) (t: String) (i : String.Pos) (f : Char \u2192 \u03c3 \u2192 m (ForInStep \u03c3)) : m \u03c3 := do\n    if i == t.length then pure d else\n    match (\u2190 f (t.get i) d) with\n      | ForInStep.done d  => pure d\n      | ForInStep.yield d => loop d t (t.next i) f\ntermination_by _ t i _ => (t.length - i)\ndecreasing_by apply termination\n\n@[inline] private def forIn [Monad m] (t : String) (init : \u03c3) (f : Char \u2192 \u03c3 \u2192 m (ForInStep \u03c3)) : m \u03c3 :=\n  loop init t 0 f\n\ninstance : ForIn m String Char where\n  forIn := forIn\n\n\n-- #redComp fofNat 5\ndef hexToByteArray'(s: String): Option ByteArray := Id.run do\n  if s.length % 2 != 0 then return none\n  let mut res := ByteArray.mkEmpty $ s.length / 2\n  let mut mem : Option UInt8 := Option.none\n  -- s.foldl \n  for c in s do\n    let Option.some r := hexChar c | return none    \n    (res, mem) := match mem with \n    | none => (res, Option.some \u27e8 r , sorry \u27e9 )\n    | some r2 => (res.push $ (16 * (\u27e8 r , sorry \u27e9 : UInt8) ) + r2, Option.none)\n    pure ()\n  return res\n\ndef hexToByteArray!'_aux (l: List Char) (r: ByteArray) : ByteArray := match l with\n| List.cons v1 (List.cons v2 l) => match hexChar v1 with\n  | none => panic! \"Asdf\"\n  | some v1 => match hexChar v2 with\n    | none => panic! \"asdf\"\n    | some v2 =>\n      (hexToByteArray!'_aux l r).push \u27e8 16 * v1 + v2 , sorry \u27e9\n| List.nil => r\n| _ => panic! \"wrong size\"\n\ndef hexToByteArray!' (s: String) :=\n  let d := hexToByteArray!'_aux s.data ByteArray.empty\n  ByteArray.mk (d.data.reverse)\n\n\ndef hexToByteList!'_aux (l: List Char) (r: List UInt8) : List UInt8 := match l with\n| List.cons v1 (List.cons v2 l) => match hexChar v1 with\n  | none => panic! \"Asdf\"\n  | some v1 => match hexChar v2 with\n    | none => panic! \"asdf\"\n    | some v2 =>\n      List.cons \u27e8 16 * v1 + v2 , sorry \u27e9 (hexToByteList!'_aux l r)\n| List.nil => r\n| _ => panic! \"wrong size\"\n\ndef hexToByteList!' (s: String) :=\n  let d := hexToByteList!'_aux s.data []\n  d\n\n\n#assert (hexToByteList! \"deadbeef00\") == (hexToByteList!' \"deadbeef00\")\n-- def hexToByteArray''(s: String): Option ByteArray := \n--   let fn (st : (Option UInt8 \u00d7 ))\n-- s.foldl\n\n-- #print hexToByteArray'\n\n-- local instance : OfNat UInt8 n where\n--   -- ofNat := fofNat n\n--   ofNat := \u27e8 n % 256, sorry \u27e9\n\n\n-- set_option pp.all true\n-- #reduce (5: UInt8)\n\n\n-- -- private def throwFailedToEval (e : Expr) : MetaM \u03b1 :=\n-- --   throwError \"reduceEval: failed to evaluate argument{indentExpr e}\"\n    \n-- -- instance : Meta.ReduceEval UInt8 where\n-- --   reduceEval e := do\n-- --     let e \u2190 Meta.whnf e\n-- --     let Expr.const c .. \u2190 pure e.getAppFn | throwFailedToEval e\n-- --     let nargs := e.getAppNumArgs\n-- --     if      c == `UInt8.mk && nargs == 0 then pure none\n-- --     else if c == `Option.some && nargs == 1 then some <$> reduceEval e.appArg!\n-- --     else throwFailedToEval e\n\n-- #reduce fofNat 5\n\n-- def basicInput := hexToByteArray \"604260005260206000F3\"\n-- -- -- #reduce (22 : UInt8)\n-- -- -- set_option maxHeartbeats 200000\n-- -- -- #reduce basicInput\n\n-- -- -- #reduce basicInput\n\n-- -- def basicSolcInput := hexToByteArray! \"6080604052348015600f57600080fd5b5060405160e338038060e38339818101604052810190602d9190604c565b80600081905550506097565b6000815190506046816083565b92915050565b600060208284031215605f57605e607e565b5b6000606b848285016039565b91505092915050565b6000819050919050565b600080fd5b608a816074565b8114609457600080fd5b50565b603f8060a46000396000f3fe6080604052600080fdfea26469706673582212209c130309b4505633bae9459145bea0f6138a99c38947f11384f39beca020bc9a64736f6c63430008070033\"\n\n\n\n-- def basicInlined : ByteArray := {data := #[96, 128, 96, 64, 82, 52, 128, 21, 96, 15, 87, 96, 0, 128, 253, 91, 80, 96, 64, 81, 96,\n-- 227, 56, 3, 128, 96, 227, 131, 57, 129, 129, 1, 96, 64, 82, 129, 1, 144,\n-- 96, 45, 145, 144, 96, 76, 86, 91, 128, 96, 0, 129, 144, 85, 80, 80, 96, 151, 86, 91, 96, 0, 129, 81, 144, 80, 96, 70, 129, 96,\n-- 131, 86, 91, 146, 145, 80, 80, 86, 91, 96, 0, 96, 32, 130, 132, 3, 18, 21, 96, 95, 87, 96, 94, 96, 126, 86, 91, 91, 96, 0, 96,\n-- 107, 132, 130, 133, 1, 96, 57, 86, 91, 145, 80, 80, 146, 145, 80, 80, 86, 91, 96, 0, 129, 144, 80, 145, 144, 80, 86, 91, 96]}\n-- --, 0, 128, 253, 91, 96, 138, 129, 96, 116, 86, 91, 129, 20, 96, 148, 87, 96, 0, 128, 253, 91, 80, 86, 91, 96, 63, 128, 96, 164, 96, 0, 57, 96, 0, 243, 254, 96, 128, 96, 64, 82, 96, 0, 128, 253, 254, 162, 100, 105, 112, 102, 115, 88, 34, 18, 32, 156, 19, 3, 9, 180, 80, 86, 51, 186, 233, 69, 145, 69, 190, 160, 246, 19, 138, 153, 195, 137, 71, 241, 19, 132, 243, 155, 236, 160, 32, 188, 154, 100, 115, 111, 108, 99, 67, 0, 8, 7, 0, 51]}\n\n-- -- set_option pp.all true\n-- -- #eval basicInlined\n-- set_option maxRecDepth 10000\n\n-- #reduce basicInlined[100]\n\n-- #reduce (20 : UInt8)\n-- #reduce {data := #[96, 128, 96, 64, 82, 52, 128, 21, 96, 15] : ByteArray}\n\n-- #redComp hexToByteArray!' \"aabbccccdd\"\n-- #redComp basicInput\n-- #redComp (1 : UInt8)\n\n", "meta": {"author": "zygi", "repo": "contractome", "sha": "d4d59ce817e47578d8764e26d77050ce72c18c18", "save_path": "github-repos/lean/zygi-contractome", "path": "github-repos/lean/zygi-contractome/contractome-d4d59ce817e47578d8764e26d77050ce72c18c18/Contractome/Utils.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.035678553825659445, "lm_q1q2_score": 0.016309976957015016}}
{"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\n! This file was ported from Lean 3 source module tactic.explode\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.Meta.RbMap\nimport Mathbin.Tactic.Core\n\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\n\nopen Expr Tactic\n\nnamespace Tactic\n\nnamespace Explode\n\ninductive Status : Type\n  | reg\n  | intro\n  | lam\n  | sintro\n  deriving Inhabited\n#align tactic.explode.status Tactic.Explode.Status\n\n/-- A type to distinguish introduction or elimination rules represented as\nstrings from theorems referred to by their names.\n-/\nunsafe inductive thm : Type\n  | expr (e : expr)\n  | Name (n : Name)\n  | String (s : String)\n#align tactic.explode.thm tactic.explode.thm\n\n/-- Turn a thm into a string.\n-/\nunsafe def thm.to_string : thm \u2192 String\n  | thm.expr e => e.toString\n  | thm.name n => n.toString\n  | thm.string s => s\n#align tactic.explode.thm.to_string tactic.explode.thm.to_string\n\nunsafe structure entry : Type where\n  expr : expr\n  line : Nat\n  depth : Nat\n  Status : Status\n  thm : thm\n  deps : List Nat\n#align tactic.explode.entry tactic.explode.entry\n\nunsafe def pad_right (l : List String) : List String :=\n  let n := l.foldl (fun r (s : String) => max r s.length) 0\n  l.map fun s => Nat.iterate (fun s => s.push ' ') (n - s.length) s\n#align tactic.explode.pad_right tactic.explode.pad_right\n\nunsafe structure entries : Type where mk' ::\n  s : expr_map entry\n  l : List entry\n  deriving Inhabited\n#align tactic.explode.entries tactic.explode.entries\n\nunsafe def entries.find (es : entries) (e : expr) : Option entry :=\n  es.s.find e\n#align tactic.explode.entries.find tactic.explode.entries.find\n\nunsafe def entries.size (es : entries) : \u2115 :=\n  es.s.size\n#align tactic.explode.entries.size tactic.explode.entries.size\n\nunsafe def entries.add : entries \u2192 entry \u2192 entries\n  | es@\u27e8s, l\u27e9, e => if s.contains e.expr then es else \u27e8s.insert e.expr e, e :: l\u27e9\n#align tactic.explode.entries.add tactic.explode.entries.add\n\nunsafe def entries.head (es : entries) : Option entry :=\n  es.l.head?\n#align tactic.explode.entries.head tactic.explode.entries.head\n\nunsafe def format_aux : List String \u2192 List String \u2192 List String \u2192 List entry \u2192 tactic format\n  | line :: lines, dep :: deps, thm :: thms, en :: es => do\n    let fmt \u2190\n      do\n        let margin := String.join (List.replicate en.depth \" \u2502\")\n        let margin :=\n          match en.Status with\n          | status.sintro => \" \u251c\" ++ margin\n          | status.intro => \" \u2502\" ++ margin ++ \" \u250c\"\n          | status.reg => \" \u2502\" ++ margin ++ \"\"\n          | status.lam => \" \u2502\" ++ margin ++ \"\"\n        let p \u2190 infer_type en.expr >>= pp\n        let lhs := line ++ \"\u2502\" ++ dep ++ \"\u2502 \" ++ thm ++ margin ++ \" \"\n        return <| format.of_string lhs ++ (p lhs).group ++ format.line\n    (\u00b7 ++ fmt) <$> format_aux lines deps thms es\n  | _, _, _, _ => return format.nil\n#align tactic.explode.format_aux tactic.explode.format_aux\n\nunsafe instance : has_to_tactic_format entries :=\n  \u27e8fun es : entries =>\n    let lines := pad_right <| es.l.map fun en => toString en.line\n    let deps := pad_right <| es.l.map fun en => String.intercalate \",\" (en.deps.map toString)\n    let thms := pad_right <| es.l.map fun en => (entry.thm en).toString\n    format_aux lines deps thms es.l\u27e9\n\nunsafe def append_dep (filter : expr \u2192 tactic Unit) (es : entries) (e : expr) (deps : List Nat) :\n    tactic (List Nat) :=\n  (do\n      let ei \u2190 es.find e\n      Filter ei\n      return (ei :: deps)) <|>\n    return deps\n#align tactic.explode.append_dep tactic.explode.append_dep\n\nunsafe def may_be_proof (e : expr) : tactic Bool := do\n  let expr.sort u \u2190 infer_type e >>= infer_type\n  return <| not u\n#align tactic.explode.may_be_proof tactic.explode.may_be_proof\n\nend Explode\n\nopen Explode\n\nmutual\n  unsafe def explode.core (filter : expr \u2192 tactic Unit) :\n      expr \u2192 Bool \u2192 Nat \u2192 entries \u2192 tactic entries\n    | e@(lam n bi d b), si, depth, es => do\n      let m \u2190 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 := \u27e8l, es, depth, status.sintro, thm.name n, []\u27e9\n          do\n          let es' \u2190 explode.core b' si depth (es en)\n          return <| es' \u27e8e, es', depth, status.lam, thm.string \"\u2200I\", [es, es' - 1]\u27e9\n        else do\n          let en : entry := \u27e8l, es, depth, status.intro, thm.name n, []\u27e9\n          let es' \u2190 explode.core b' si (depth + 1) (es en)\n          let deps'\n            \u2190-- in case of a \"have\" clause, the b' here has an annotation\n                explode.append_dep\n                Filter es' b' []\n          let deps' \u2190 explode.append_dep Filter es' l deps'\n          return <| es' \u27e8e, es', depth, status.lam, thm.string \"\u2200I\", deps'\u27e9\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.headI si depth es\n    | e, si, depth, es =>\n      Filter e >>\n        match get_app_fn_args e with\n        | (nm@(const n _), args) => explode.args e args depth es (thm.expr nm) []\n        | (fn, []) => do\n          let en : entry := \u27e8fn, es.size, depth, Status.reg, thm.expr fn, []\u27e9\n          return (es en)\n        | (fn, args) => do\n          let es' \u2190 explode.core fn false depth es\n          let deps\n            \u2190-- in case of a \"have\" clause, the fn here has an annotation\n                explode.append_dep\n                Filter es' fn.erase_annotations []\n          explode.args e args depth es' (thm.string \"\u2200E\") deps\n  unsafe def explode.args (filter : expr \u2192 tactic Unit) :\n      expr \u2192 List expr \u2192 Nat \u2192 entries \u2192 thm \u2192 List Nat \u2192 tactic entries\n    | e, arg :: args, depth, es, thm, deps => do\n      let es' \u2190 explode.core arg false depth es <|> return es\n      let deps' \u2190 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 \u27e8e, es.size, depth, Status.reg, thm, deps.reverse\u27e9)\nend\n#align tactic.explode.core tactic.explode.core\n#align tactic.explode.args tactic.explode.args\n\nunsafe def explode_expr (e : expr) (hide_non_prop := true) : tactic entries :=\n  let filter := if hide_non_prop then fun e => may_be_proof e >>= guardb else fun _ => skip\n  tactic.explode.core Filter e true 0 default\n#align tactic.explode_expr tactic.explode_expr\n\nunsafe def explode (n : Name) : tactic Unit := do\n  let const n _ \u2190 resolve_name n |\n    fail \"cannot resolve name\"\n  let d \u2190 get_decl n\n  let v \u2190\n    match d with\n      | declaration.defn _ _ _ v _ _ => return v\n      | declaration.thm _ _ _ v => return v.get\n      | _ => fail \"not a definition\"\n  let t \u2190 pp d.type\n  explode_expr v <* trace (to_fmt n ++ \" : \" ++ t) >>= trace\n#align tactic.explode tactic.explode\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\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 : \u2200 {a : Prop}, a \u2192 (a \u2194 true)\n0\u2502   \u2502 a         \u251c Prop\n1\u2502   \u2502 h         \u251c a\n2\u2502   \u2502 hl        \u2502 \u250c a\n3\u2502   \u2502 trivial   \u2502 \u2502 true\n4\u25022,3\u2502 \u2200I        \u2502 a \u2192 true\n5\u2502   \u2502 hr        \u2502 \u250c true\n6\u25025,1\u2502 \u2200I        \u2502 true \u2192 a\n7\u25024,6\u2502 iff.intro \u2502 a \u2194 true\n8\u25021,7\u2502 \u2200I        \u2502 a \u2192 (a \u2194 true)\n9\u25020,8\u2502 \u2200I        \u2502 \u2200 {a : Prop}, a \u2192 (a \u2194 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 `\u2200E` 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 `\u2200E h ha` where `\u2200E` is\n    (n-ary) modus ponens.\n  * If the proof term is a lambda, we will also use `\u2200I` 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 `\u2200I` 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 `\u2200I` 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]\nunsafe def explode_cmd (_ : parse <| tk \"#explode\") : parser Unit := do\n  let n \u2190 ident\n  explode n\n#align tactic.explode_cmd tactic.explode_cmd\n\nadd_tactic_doc\n  { Name := \"#explode / #explode_widget\"\n    category := DocCategory.cmd\n    declNames := [`tactic.explode_cmd, `tactic.explode_widget_cmd]\n    inheritDescriptionFrom := `tactic.explode_cmd\n    tags := [\"proof display\", \"widgets\"] }\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/Explode.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455664065234, "lm_q2_score": 0.054198734024370705, "lm_q1q2_score": 0.016300028962675878}}
{"text": "open tactic\nopen interactive\nopen lean.parser\nopen interactive.types expr\nopen expr interactive.types\n\nlocal postfix `?`:9001 := optional\n\nmeta def propagate_tags (tac : tactic unit) : tactic unit :=\ndo tag \u2190 get_main_tag,\n   if tag = [] then tac\n   else focus1 $ do\n     tac,\n     gs \u2190 get_goals,\n     when (bnot gs.empty) $ do\n       new_tag \u2190 get_main_tag,\n       when new_tag.empty $ with_enable_tags (set_main_tag tag)\n\nmeta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit :=\ndo to_remove \u2190 hs.mfilter $ \u03bb h, do {\n         h_type \u2190 infer_type h,\n         (do (new_h_type, pr) \u2190 simplify s u h_type cfg `eq discharger,\n             assert h.local_pp_name new_h_type,\n             mk_eq_mp pr h >>= tactic.exact >> return tt)\n         <|>\n         (return ff) },\n   goal_simplified \u2190 if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff,\n   guard (cfg.fail_if_unchanged = ff \u2228 to_remove.length > 0 \u2228 goal_simplified) <|> fail \"simplify tactic failed to simplify\",\n   to_remove.mmap' (\u03bb h, try (clear h))\n\nmeta def simp_core' (cfg : simp_config) (discharger : tactic unit)\n                   (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name)\n                   (locat : loc) : tactic unit :=\nmatch locat with\n| loc.wildcard := do (all_hyps, s, u) \u2190 mk_simp_set_core no_dflt attr_names hs tt,\n                     trace all_hyps,\n                     if all_hyps then tactic.simp_all s u cfg discharger\n                     else do hyps \u2190 non_dep_prop_hyps, \n                             trace hyps,\n                             simp_core_aux cfg discharger s u hyps tt\n| _            := do (s, u) \u2190 mk_simp_set no_dflt attr_names hs,\n                     ns \u2190 locat.get_locals,\n                     simp_core_aux cfg discharger s u ns locat.include_goal\nend\n>> try tactic.triv >> try (tactic.reflexivity reducible)\n\nnamespace tactic.interactive\nmeta def simp' (use_iota_eqn : parse $ (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n              (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit :=\nlet cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in\npropagate_tags (simp_core' cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat)\nend tactic.interactive\n\nlemma foo (p : ite (tt = ff) unit empty) : false :=\nbegin\nsimp_all,\nsimp' at *, -- FIXME this works, but `simp at *` doesn't\ninduction p\nend\n", "meta": {"author": "semorrison", "repo": "proof", "sha": "5ee398aa239a379a431190edbb6022b1a0aa2c70", "save_path": "github-repos/lean/semorrison-proof", "path": "github-repos/lean/semorrison-proof/proof-5ee398aa239a379a431190edbb6022b1a0aa2c70/lean/20180124-simp-at.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.045352582651065294, "lm_q1q2_score": 0.01629809209520295}}
{"text": "import tactic.lint\nimport algebra.ring.basic\n\nopen tactic\n\ndef foo1 (n m : \u2115) : \u2115 := n + 1\ndef foo2 (n m : \u2115) : m = m := by refl\nnoncomputable lemma foo3 (n m : \u2115) : \u2115 := n - m\nlemma foo.foo (n m : \u2115) : n \u2265 n := le_refl n\ninstance bar.bar : has_add \u2115 := by apply_instance  -- we don't check the name of instances\nlemma foo.bar (\u03b5 > 0) : \u03b5 = \u03b5 := rfl -- >/\u2265 is allowed in binders (and in fact, in all hypotheses)\n/-- Test exception in `def_lemma` linter. -/\n@[pattern] def my_exists_intro := @Exists.intro\n\nmeta def fold_over_with_cond {\u03b1} (l : list declaration) (tac : declaration \u2192 tactic (option \u03b1)) :\n  tactic (list (declaration \u00d7 \u03b1)) :=\nl.mmap_filter $ \u03bb d, option.map (\u03bb x, (d, x)) <$> tac d\n\nrun_cmd do\n  let t := name \u00d7 list \u2115,\n  e \u2190 get_env,\n  let l := e.filter (\u03bb d, e.in_current_file d.to_name \u2227 \u00ac d.is_auto_or_internal e),\n  l2 \u2190 fold_over_with_cond l (return \u2218 check_unused_arguments),\n  guard (l2.length = 4) <|> fail \"wrong length\",\n  let l2 : list (name \u00d7 list \u2115) := l2.map (\u03bb x, \u27e8x.1.to_name, x.2\u27e9),\n  guard ((\u27e8`foo1, [2]\u27e9 : t) \u2208 l2) <|> fail \"foo1\",\n  guard ((\u27e8`foo2, [1]\u27e9 : t) \u2208 l2) <|> fail \"foo2\",\n  guard ((\u27e8`foo.foo, [2]\u27e9 : t) \u2208 l2) <|> fail \"foofoo\",\n  guard ((\u27e8`foo.bar, [2]\u27e9 : t) \u2208 l2) <|> fail \"foobar\",\n  l2 \u2190 fold_over_with_cond l linter.def_lemma.test,\n  guard $ l2.length = 2,\n  let l2 : list (name \u00d7 _) := l2.map $ \u03bb x, \u27e8x.1.to_name, x.2\u27e9,\n  guard $ \u2203(x \u2208 l2), (x : name \u00d7 _).1 = `foo2,\n  guard $ \u2203(x \u2208 l2), (x : name \u00d7 _).1 = `foo3,\n  l3 \u2190 fold_over_with_cond l linter.dup_namespace.test,\n  guard $ l3.length = 1,\n  guard $ \u2203(x \u2208 l3), (x : declaration \u00d7 _).1.to_name = `foo.foo,\n  l4 \u2190 fold_over_with_cond l linter.ge_or_gt.test,\n  guard $ l4.length = 1,\n  guard $ \u2203(x \u2208 l4), (x : declaration \u00d7 _).1.to_name = `foo.foo,\n  -- guard $ \u2203(x \u2208 l4), (x : declaration \u00d7 _).1.to_name = `foo4,\n  (_, s) \u2190 lint ff,\n  guard $ \"/- (slow tests skipped) -/\\n\".is_suffix_of s.to_string,\n  (_, s2) \u2190 lint tt,\n  guard $ s.to_string \u2260 s2.to_string,\n  skip\n\n/- check customizability and nolint -/\n\nmeta def dummy_check (d : declaration) : tactic (option string) :=\nreturn $ if d.to_name.last = \"foo\" then some \"gotcha!\" else none\n\nmeta def linter.dummy_linter : linter :=\n{ test := dummy_check,\n  auto_decls := ff,\n  no_errors_found := \"found nothing.\",\n  errors_found := \"found something:\" }\n\n@[nolint dummy_linter]\ndef bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)\n\nrun_cmd do\n  (_, s) \u2190 lint tt lint_verbosity.medium [`linter.dummy_linter] tt,\n  guard $ \"/- found something: -/\\n#check @foo.foo /- gotcha! -/\\n\".is_suffix_of s.to_string\n\ndef incorrect_type_class_argument_test {\u03b1 : Type} (x : \u03b1) [x = x] [decidable_eq \u03b1] [group \u03b1] :\n  unit := ()\n\nrun_cmd do\n  d \u2190 get_decl `incorrect_type_class_argument_test,\n  x \u2190 linter.incorrect_type_class_argument.test d,\n  guard $ x = some \"These are not classes. argument 3: [_inst_1 : x = x]\"\n\nsection\ndef impossible_instance_test {\u03b1 \u03b2 : Type} [add_group \u03b1] : has_add \u03b1 := infer_instance\nlocal attribute [instance] impossible_instance_test\nrun_cmd do\n  d \u2190 get_decl `impossible_instance_test,\n  x \u2190 linter.impossible_instance.test d,\n  guard $ x = some \"Impossible to infer argument 2: {\u03b2 : Type}\"\n\ndef dangerous_instance_test {\u03b1 \u03b2 \u03b3 : Type} [ring \u03b1] [add_comm_group \u03b2] [has_coe \u03b1 \u03b2]\n  [has_inv \u03b3] : has_add \u03b2 := infer_instance\nlocal attribute [instance] dangerous_instance_test\nrun_cmd do\n  d \u2190 get_decl `dangerous_instance_test,\n  x \u2190 linter.dangerous_instance.test d,\n  guard $ x = some\n    \"The following arguments become metavariables. argument 1: {\u03b1 : Type}, argument 3: {\u03b3 : Type}\"\nend\n\nsection\ndef foo_has_mul {\u03b1} [has_mul \u03b1] : has_mul \u03b1 := infer_instance\nlocal attribute [instance, priority 1] foo_has_mul\nrun_cmd do\n  d \u2190 get_decl `foo_has_mul,\n  some s \u2190 fails_quickly 20 d,\n  guard $ \"type-class inference timed out\".is_prefix_of s\nlocal attribute [instance, priority 10000] foo_has_mul\nrun_cmd do\n  d \u2190 get_decl `foo_has_mul,\n  some s \u2190 fails_quickly 3000 d,\n  guard $ \"maximum class-instance resolution depth has been reached\".is_prefix_of s\nend\n\ninstance beta_redex_test {\u03b1} [monoid \u03b1] : (\u03bb (X : Type), has_mul X) \u03b1 := \u27e8(*)\u27e9\nrun_cmd do\n  d \u2190 get_decl `beta_redex_test,\n  x \u2190 linter.instance_priority.test d,\n  guard $ x = some \"set priority below 1000\"\n\n/- Test exception in `def_lemma` linter. -/\nrun_cmd do\n  d \u2190 get_decl `my_exists_intro,\n  t \u2190 linter.def_lemma.test d,\n  guard $ t = none\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/lint.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.042722193128246835, "lm_q1q2_score": 0.01628653593386173}}
{"text": "example : n.succ = 1 \u2192 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 \u2192 T \u2192 Prop\n\nexample {\u03c1} (h\u03c1 : \u03c1.Pred \u03c3) : T.Pred \u03c1 \u03c1 := 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} [\ud835\udc9e : category.{v} C] [abelian.{v} C]\ninclude \ud835\udc9e\n\nlocal attribute [instance] object_to_sort\nlocal attribute [instance] hom_to_fun\n\nlemma pseudo_congr {X Y : C} {f g : X \u27f6 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  \u2115 \u2192 diagram_term \u2192 option (diagram_term)\n| 0 \u27e8ms, elem\u27e9 :=\n  match list.is_prefix_of l.lhs ms with\n  | ff := none\n  | tt := some \u27e8list.append l.rhs (list.drop l.lhs.length ms), elem\u27e9\n  end\n| (n + 1) \u27e8[], e\u27e9 := none\n| (n + 1) \u27e8t::ts, e\u27e9 :=\n  match try_apply_comm_lemma_at_aux n \u27e8ts, e\u27e9 with\n  | none := none\n  | some \u27e8nt, ne\u27e9 := some \u27e8t::nt, ne\u27e9\n  end\n\nmeta def try_apply_element_lemma_at_aux (l : element_lemma) :\n  \u2115 \u2192 diagram_term \u2192 option (diagram_term)\n| 0 \u27e8ms, elem\u27e9 := if l.lhs = \u27e8ms, elem\u27e9 then some l.rhs else none\n| (n + 1) \u27e8[], e\u27e9 := none\n| (n + 1) \u27e8t :: ts, e\u27e9 :=\n  match try_apply_element_lemma_at_aux n \u27e8ts, e\u27e9 with\n  | none := none\n  | some \u27e8nt, ne\u27e9 := some \u27e8t::nt, ne\u27e9\n  end\n\nmeta inductive lemma_app\n| comm : commutativity_lemma \u2192 \u2115 \u2192 diagram_term \u2192 lemma_app\n| elem : element_lemma \u2192 \u2115 \u2192 diagram_term \u2192 lemma_app\n\nmeta instance format_lemma_app : has_to_format lemma_app :=\n{ to_format := \u03bb 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 \u2192 diagram_term\n| (lemma_app.comm _ _ t) := t\n| (lemma_app.elem _ _ t) := t\n\nmeta def apply_comm_lemma_at_aux : \u2115 \u2192 diagram_term \u2192 tactic (option expr)\n| 0 t := some <$> (mk_eq_refl $ as_expr t)\n| 1 \u27e8t::[], e\u27e9 := some <$> (mk_eq_refl $ as_expr \u27e8[t], e\u27e9)\n| (n + 1) \u27e8[], _\u27e9 := return none\n| (n + 1) \u27e8t::[], e\u27e9 := return none\n| (n + 1) \u27e8t::(u::ts), e\u27e9 :=\ndo\n  some x \u2190 i_to_expr ``(%%(u.ex) \u226b %%(t.ex)) >>= as_morphism,\n  lhs \u2190 mk_app `category_theory.abelian.pseudoelements.comp_apply [u.ex, t.ex, as_expr \u27e8ts, e\u27e9] >>= mk_eq_symm,\n  some rhs \u2190 apply_comm_lemma_at_aux n \u27e8x::ts, e\u27e9,\n  some <$> mk_eq_trans lhs rhs\n\nmeta def apply_comm_lemma_at (l : commutativity_lemma) :\n  \u2115 \u2192 diagram_term \u2192 diagram_term \u2192 tactic (option expr)\n| 0 \u27e8ms, elem\u27e9 goal :=\ndo\n  some one \u2190 apply_comm_lemma_at_aux (l.lhs.length - 1) \u27e8ms, elem\u27e9,\n  let inner := as_expr \u27e8list.drop (l.lhs.length) ms, elem\u27e9,\n  two \u2190 mk_app `tactic.chase.pseudo_congr [l.ex, inner],\n  some three \u2190 apply_comm_lemma_at_aux (l.rhs.length - 1) goal,\n  three' \u2190 mk_eq_symm three,\n  onetwo \u2190 mk_eq_trans one two,\n  some <$> mk_eq_trans onetwo three'\n| (n + 1) \u27e8[], e\u27e9 goal := none\n| (n + 1) fr \u27e8[], e\u27e9 := none\n| (n + 1) \u27e8t::ts, e\u27e9 \u27e8u::us, f\u27e9 :=\ndo\n  some inner \u2190 apply_comm_lemma_at n \u27e8ts, e\u27e9 \u27e8us, f\u27e9,\n  some <$> mk_app `congr_arg [t.app, inner]\n\nmeta def apply_elem_lemma_at (l : element_lemma) :\n  \u2115 \u2192 diagram_term \u2192 tactic (option expr)\n| 0 \u27e8ms, elem\u27e9 := return $ some l.ex\n| (n + 1) \u27e8[], _\u27e9 := none\n| (n + 1) \u27e8t::ts, e\u27e9 :=\ndo\n  some inner \u2190 apply_elem_lemma_at n \u27e8ts, e\u27e9,\n  some <$> mk_app `congr_arg [t.app, inner]\n\nmeta def build_proof (t : diagram_term) : lemma_app \u2192 tactic expr\n| (lemma_app.comm x y z) :=\ndo\n  some u \u2190 apply_comm_lemma_at x y t z,\n  return u\n| (lemma_app.elem x y z) :=\ndo\n  some u \u2190 apply_elem_lemma_at x y t,\n  return u\n\nmeta def try_apply_comm_lemma_at (l : commutativity_lemma) (n : \u2115) (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 : \u2115) (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 : \u2115 \u2192 list \u2115\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 (\u03bb 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 (\u03bb 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 \u2190 get,\n  return $ list.join $ list.map (\u03bb 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 \u2190 get,\n  return $ list.join $ list.map (\u03bb 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 \u2192 diagram_term \u2192 chase_tactic (option expr)\n| cur goal := do\n  l \u2190 diagram_term.to_zero cur,\n  match l with\n  | none := return none\n  | some e := do\n    zer \u2190 goal.zero,\n    r \u2190 find_proof_dfs goal zer [],\n    match r with\n    | none := return none\n    | some f := (mk_eq_symm f) >>= (\u03bb g, some <$> mk_eq_trans e g)\n    end\n  end\nwith find_proof_dfs :\ndiagram_term \u2192 diagram_term \u2192 list diagram_term \u2192 chase_tactic (option expr)\n| cur goal seen := if cur = goal then some <$> mk_eq_refl (as_expr cur) else\ndo\n  via_zero \u2190 show_via_zero cur goal,\n  match via_zero with\n  | some e := return $ some e\n  | none := do\n    cands_comm \u2190 try_all_comm cur,\n    cands_elem \u2190 try_all_elem cur,\n    let cands := list.append cands_comm cands_elem,\n\n    list.mfoldl (\u03bb r s,\n      match r with\n      | some q := return $ some q\n      | none :=\n        ite (list.any seen (\u03bb e, to_bool $ e = (next_term s))) (return none) $\n        do\n          --trace format!\"trying {s}...\",\n          l \u2190 find_proof_dfs (next_term s) goal (cur::seen),\n          match l with\n          | none := none\n          | some q := do\n            f \u2190 build_proof cur s,\n            t \u2190 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 \u2192 diagram_term \u2192 chase_tactic (option expr)\n| \u27e8t, e\u27e9 \u27e8t', e'\u27e9 := do\n  mm \u2190 diagram_term.type \u27e8t, e\u27e9 >>= mono_with_domain,\n  match mm with\n  | none := find_direct_proof \u27e8t, e\u27e9 \u27e8t', e'\u27e9\n  | some m := do\n    ii \u2190 find_proof \u27e8m::t, e\u27e9 \u27e8m::t', e'\u27e9,\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) \u2190 target_lhs_rhs,\n  some lhs \u2190 as_diagram_term l,\n  some rhs \u2190 as_diagram_term r,\n  some p \u2190 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 \u2190 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": "/-\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-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.logic\nimport Mathlib.Lean3Lib.init.data.nat.basic\nimport Mathlib.Lean3Lib.init.data.bool.basic\nimport Mathlib.Lean3Lib.init.propext\n \n\nuniverses u u_1 v w \n\nnamespace Mathlib\n\nprotected instance list.inhabited (\u03b1 : Type u) : Inhabited (List \u03b1) :=\n  { default := [] }\n\nnamespace list\n\n\nprotected def has_dec_eq {\u03b1 : Type u} [s : DecidableEq \u03b1] : DecidableEq (List \u03b1) :=\n  sorry\n\nprotected instance decidable_eq {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (List \u03b1) :=\n  list.has_dec_eq\n\n@[simp] protected def append {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\nprotected instance has_append {\u03b1 : Type u} : Append (List \u03b1) :=\n  { append := list.append }\n\nprotected def mem {\u03b1 : Type u} : \u03b1 \u2192 List \u03b1 \u2192 Prop :=\n  sorry\n\nprotected instance has_mem {\u03b1 : Type u} : has_mem \u03b1 (List \u03b1) :=\n  has_mem.mk list.mem\n\nprotected instance decidable_mem {\u03b1 : Type u} [DecidableEq \u03b1] (a : \u03b1) (l : List \u03b1) : Decidable (a \u2208 l) :=\n  sorry\n\nprotected instance has_emptyc {\u03b1 : Type u} : has_emptyc (List \u03b1) :=\n  has_emptyc.mk []\n\nprotected def erase {\u03b1 : Type u_1} [DecidableEq \u03b1] : List \u03b1 \u2192 \u03b1 \u2192 List \u03b1 :=\n  sorry\n\nprotected def bag_inter {\u03b1 : Type u_1} [DecidableEq \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\nprotected def diff {\u03b1 : Type u_1} [DecidableEq \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n@[simp] def length {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 :=\n  sorry\n\ndef empty {\u03b1 : Type u} : List \u03b1 \u2192 Bool :=\n  sorry\n\n@[simp] def nth {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 \u2192 Option \u03b1 :=\n  sorry\n\n@[simp] def nth_le {\u03b1 : Type u} (l : List \u03b1) (n : \u2115) : n < length l \u2192 \u03b1 :=\n  sorry\n\n@[simp] def head {\u03b1 : Type u} [Inhabited \u03b1] : List \u03b1 \u2192 \u03b1 :=\n  sorry\n\n@[simp] def tail {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef reverse_core {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef reverse {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 :=\n  fun (l : List \u03b1) => reverse_core l []\n\n@[simp] def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) : List \u03b1 \u2192 List \u03b2 :=\n  sorry\n\n@[simp] def map\u2082 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : List \u03b1 \u2192 List \u03b2 \u2192 List \u03b3 :=\n  sorry\n\ndef map_with_index_core {\u03b1 : Type u} {\u03b2 : Type v} (f : \u2115 \u2192 \u03b1 \u2192 \u03b2) : \u2115 \u2192 List \u03b1 \u2192 List \u03b2 :=\n  sorry\n\n/-- Given a function `f : \u2115 \u2192 \u03b1 \u2192 \u03b2` and `as : list \u03b1`, `as = [a\u2080, a\u2081, ...]`, returns the list\n`[f 0 a\u2080, f 1 a\u2081, ...]`. -/\ndef map_with_index {\u03b1 : Type u} {\u03b2 : Type v} (f : \u2115 \u2192 \u03b1 \u2192 \u03b2) (as : List \u03b1) : List \u03b2 :=\n  map_with_index_core f 0 as\n\ndef join {\u03b1 : Type u} : List (List \u03b1) \u2192 List \u03b1 :=\n  sorry\n\ndef filter_map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 Option \u03b2) : List \u03b1 \u2192 List \u03b2 :=\n  sorry\n\ndef filter {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef partition {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 \u00d7 List \u03b1 :=\n  sorry\n\ndef drop_while {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n/-- `after p xs` is the suffix of `xs` after the first element that satisfies\n  `p`, not including that element.\n\n  ```lean\n  after      (eq 1)       [0, 1, 2, 3] = [2, 3]\n  drop_while (not \u2218 eq 1) [0, 1, 2, 3] = [1, 2, 3]\n  ```\n-/\ndef after {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef span {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 \u00d7 List \u03b1 :=\n  sorry\n\ndef find_index {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 \u2115 :=\n  sorry\n\ndef index_of {\u03b1 : Type u} [DecidableEq \u03b1] (a : \u03b1) : List \u03b1 \u2192 \u2115 :=\n  find_index (Eq a)\n\ndef remove_all {\u03b1 : Type u} [DecidableEq \u03b1] (xs : List \u03b1) (ys : List \u03b1) : List \u03b1 :=\n  filter (fun (_x : \u03b1) => \u00ac_x \u2208 ys) xs\n\ndef update_nth {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 \u2192 \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef remove_nth {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 \u2192 List \u03b1 :=\n  sorry\n\n@[simp] def drop {\u03b1 : Type u} : \u2115 \u2192 List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n@[simp] def take {\u03b1 : Type u} : \u2115 \u2192 List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\n@[simp] def foldl {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b1) : \u03b1 \u2192 List \u03b2 \u2192 \u03b1 :=\n  sorry\n\n@[simp] def foldr {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (b : \u03b2) : List \u03b1 \u2192 \u03b2 :=\n  sorry\n\ndef any {\u03b1 : Type u} (l : List \u03b1) (p : \u03b1 \u2192 Bool) : Bool :=\n  foldr (fun (a : \u03b1) (r : Bool) => p a || r) false l\n\ndef all {\u03b1 : Type u} (l : List \u03b1) (p : \u03b1 \u2192 Bool) : Bool :=\n  foldr (fun (a : \u03b1) (r : Bool) => p a && r) tt l\n\ndef bor (l : List Bool) : Bool :=\n  any l id\n\ndef band (l : List Bool) : Bool :=\n  all l id\n\ndef zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : List \u03b1 \u2192 List \u03b2 \u2192 List \u03b3 :=\n  sorry\n\ndef zip {\u03b1 : Type u} {\u03b2 : Type v} : List \u03b1 \u2192 List \u03b2 \u2192 List (\u03b1 \u00d7 \u03b2) :=\n  zip_with Prod.mk\n\ndef unzip {\u03b1 : Type u} {\u03b2 : Type v} : List (\u03b1 \u00d7 \u03b2) \u2192 List \u03b1 \u00d7 List \u03b2 :=\n  sorry\n\nprotected def insert {\u03b1 : Type u} [DecidableEq \u03b1] (a : \u03b1) (l : List \u03b1) : List \u03b1 :=\n  ite (a \u2208 l) l (a :: l)\n\nprotected instance has_insert {\u03b1 : Type u} [DecidableEq \u03b1] : has_insert \u03b1 (List \u03b1) :=\n  has_insert.mk list.insert\n\nprotected instance has_singleton {\u03b1 : Type u} : has_singleton \u03b1 (List \u03b1) :=\n  has_singleton.mk fun (x : \u03b1) => [x]\n\nprotected instance is_lawful_singleton {\u03b1 : Type u} [DecidableEq \u03b1] : is_lawful_singleton \u03b1 (List \u03b1) :=\n  is_lawful_singleton.mk fun (x : \u03b1) => (fun (this : ite (x \u2208 []) [] [x] = [x]) => this) (if_neg not_false)\n\nprotected def union {\u03b1 : Type u} [DecidableEq \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : List \u03b1 :=\n  foldr insert l\u2082 l\u2081\n\nprotected instance has_union {\u03b1 : Type u} [DecidableEq \u03b1] : has_union (List \u03b1) :=\n  has_union.mk list.union\n\nprotected def inter {\u03b1 : Type u} [DecidableEq \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : List \u03b1 :=\n  filter (fun (_x : \u03b1) => _x \u2208 l\u2082) l\u2081\n\nprotected instance has_inter {\u03b1 : Type u} [DecidableEq \u03b1] : has_inter (List \u03b1) :=\n  has_inter.mk list.inter\n\n@[simp] def repeat {\u03b1 : Type u} (a : \u03b1) : \u2115 \u2192 List \u03b1 :=\n  sorry\n\ndef range_core : \u2115 \u2192 List \u2115 \u2192 List \u2115 :=\n  sorry\n\ndef range (n : \u2115) : List \u2115 :=\n  range_core n []\n\ndef iota : \u2115 \u2192 List \u2115 :=\n  sorry\n\ndef enum_from {\u03b1 : Type u} : \u2115 \u2192 List \u03b1 \u2192 List (\u2115 \u00d7 \u03b1) :=\n  sorry\n\ndef enum {\u03b1 : Type u} : List \u03b1 \u2192 List (\u2115 \u00d7 \u03b1) :=\n  enum_from 0\n\n@[simp] def last {\u03b1 : Type u} (l : List \u03b1) : l \u2260 [] \u2192 \u03b1 :=\n  sorry\n\ndef ilast {\u03b1 : Type u} [Inhabited \u03b1] : List \u03b1 \u2192 \u03b1 :=\n  sorry\n\ndef init {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef intersperse {\u03b1 : Type u} (sep : \u03b1) : List \u03b1 \u2192 List \u03b1 :=\n  sorry\n\ndef intercalate {\u03b1 : Type u} (sep : List \u03b1) (xs : List (List \u03b1)) : List \u03b1 :=\n  join (intersperse sep xs)\n\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} (a : List \u03b1) (b : \u03b1 \u2192 List \u03b2) : List \u03b2 :=\n  join (map b a)\n\nprotected def ret {\u03b1 : Type u} (a : \u03b1) : List \u03b1 :=\n  [a]\n\nprotected def lt {\u03b1 : Type u} [HasLess \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 Prop :=\n  sorry\n\nprotected instance has_lt {\u03b1 : Type u} [HasLess \u03b1] : HasLess (List \u03b1) :=\n  { Less := list.lt }\n\nprotected instance has_decidable_lt {\u03b1 : Type u} [HasLess \u03b1] [h : DecidableRel Less] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : Decidable (l\u2081 < l\u2082) :=\n  sorry\n\nprotected def le {\u03b1 : Type u} [HasLess \u03b1] (a : List \u03b1) (b : List \u03b1) :=\n  \u00acb < a\n\nprotected instance has_le {\u03b1 : Type u} [HasLess \u03b1] : HasLessEq (List \u03b1) :=\n  { LessEq := list.le }\n\nprotected instance has_decidable_le {\u03b1 : Type u} [HasLess \u03b1] [h : DecidableRel Less] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : Decidable (l\u2081 \u2264 l\u2082) :=\n  not.decidable\n\ntheorem le_eq_not_gt {\u03b1 : Type u} [HasLess \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : l\u2081 \u2264 l\u2082 = (\u00acl\u2082 < l\u2081) :=\n  rfl\n\ntheorem lt_eq_not_ge {\u03b1 : Type u} [HasLess \u03b1] [DecidableRel Less] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : l\u2081 < l\u2082 = (\u00acl\u2082 \u2264 l\u2081) :=\n  (fun (this : l\u2081 < l\u2082 = (\u00ac\u00acl\u2081 < l\u2082)) => this) (Eq.symm (propext (decidable.not_not_iff (l\u2081 < l\u2082))) \u25b8 rfl)\n\n/--  `is_prefix_of l\u2081 l\u2082` returns `tt` iff `l\u2081` is a prefix of `l\u2082`. -/\ndef is_prefix_of {\u03b1 : Type u} [DecidableEq \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 Bool :=\n  sorry\n\n/--  `is_suffix_of l\u2081 l\u2082` returns `tt` iff `l\u2081` is a suffix of `l\u2082`. -/\ndef is_suffix_of {\u03b1 : Type u} [DecidableEq \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : Bool :=\n  is_prefix_of (reverse l\u2081) (reverse l\u2082)\n\nend list\n\n\nnamespace bin_tree\n\n\ndef to_list {\u03b1 : Type u} (t : bin_tree \u03b1) : List \u03b1 :=\n  to_list_aux t []\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/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.05582313524415761, "lm_q1q2_score": 0.01624346424817687}}
{"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\u2081 v\u2081 u\u2082 v\u2082 u\u2083 v\u2083 u\u2084 v\u2084\n\nsection\nvariables (C : Type u\u2081) [\ud835\udc9e : category.{v\u2081} C]\n          (D : Type u\u2082) [\ud835\udc9f : category.{v\u2082} D]\n          (E : Type u\u2083) [\u2130 : category.{v\u2083} E]\ninclude \ud835\udc9e \ud835\udc9f \u2130\n\ndef whiskering_left : (C \u2964 D) \u2964 ((D \u2964 E) \u2964 (C \u2964 E)) :=\n{ obj := \u03bb F,\n  { obj := \u03bb G, F \u22d9 G,\n    map := \u03bb G H \u03b1,\n    { app := \u03bb c, \u03b1.app (F.obj c),\n      naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, \u03b1.naturality] } },\n  map := \u03bb F G \u03c4,\n  { app := \u03bb H,\n    { app := \u03bb c, H.map (\u03c4.app c),\n      naturality' := \u03bb X Y f, begin dsimp at *, rw [\u2190H.map_comp, \u2190H.map_comp, \u2190\u03c4.naturality] end },\n    naturality' := \u03bb X Y f, begin ext1, dsimp at *, rw [\u2190nat_trans.naturality] end } }\n\ndef whiskering_right : (D \u2964 E) \u2964 ((C \u2964 D) \u2964 (C \u2964 E)) :=\n{ obj := \u03bb H,\n  { obj := \u03bb F, F \u22d9 H,\n    map := \u03bb _ _ \u03b1,\n    { app := \u03bb c, H.map (\u03b1.app c),\n      naturality' := by intros X Y f;\n        rw [functor.comp_map, functor.comp_map, \u2190H.map_comp, \u2190H.map_comp, \u03b1.naturality] } },\n  map := \u03bb G H \u03c4,\n  { app := \u03bb F,\n    { app := \u03bb c, \u03c4.app (F.obj c),\n      naturality' := \u03bb X Y f, begin dsimp at *, rw [\u03c4.naturality] end },\n    naturality' := \u03bb X Y f, begin ext1, dsimp at *, rw [\u2190nat_trans.naturality] end } }\n\nvariables {C} {D} {E}\n\ndef whisker_left (F : C \u2964 D) {G H : D \u2964 E} (\u03b1 : G \u27f9 H) : (F \u22d9 G) \u27f9 (F \u22d9 H) :=\n((whiskering_left C D E).obj F).map \u03b1\n\n@[simp] lemma whisker_left.app (F : C \u2964 D) {G H : D \u2964 E} (\u03b1 : G \u27f9 H) (X : C) :\n  (whisker_left F \u03b1).app X = \u03b1.app (F.obj X) :=\nrfl\n\ndef whisker_right {G H : C \u2964 D} (\u03b1 : G \u27f9 H) (F : D \u2964 E) : (G \u22d9 F) \u27f9 (H \u22d9 F) :=\n((whiskering_right C D E).obj F).map \u03b1\n\n@[simp] lemma whisker_right.app {G H : C \u2964 D} (\u03b1 : G \u27f9 H) (F : D \u2964 E) (X : C) :\n   (whisker_right \u03b1 F).app X = F.map (\u03b1.app X) :=\nrfl\n\n@[simp] lemma whisker_left_id (F : C \u2964 D) {G : D \u2964 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 \u2964 D} (F : D \u2964 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 \u2964 D) {G H K : D \u2964 E} (\u03b1 : G \u27f9 H) (\u03b2 : H \u27f9 K) :\n  whisker_left F (\u03b1 \u229f \u03b2) = (whisker_left F \u03b1) \u229f (whisker_left F \u03b2) :=\nrfl\n\n@[simp] lemma whisker_right_vcomp {G H K : C \u2964 D} (\u03b1 : G \u27f9 H) (\u03b2 : H \u27f9 K) (F : D \u2964 E)  :\n  whisker_right (\u03b1 \u229f \u03b2) F = (whisker_right \u03b1 F) \u229f (whisker_right \u03b2 F) :=\n((whiskering_right C D E).obj F).map_comp \u03b1 \u03b2\n\nvariables {B : Type u\u2084} [\u212c : category.{v\u2084} B]\ninclude \u212c\n\nlocal attribute [elab_simple] whisker_left whisker_right\n\n@[simp] lemma whisker_left_twice (F : B \u2964 C) (G : C \u2964 D) {H K : D \u2964 E} (\u03b1 : H \u27f9 K) :\n  whisker_left F (whisker_left G \u03b1) = whisker_left (F \u22d9 G) \u03b1 :=\nrfl\n\n@[simp] lemma whisker_right_twice {H K : B \u2964 C} (F : C \u2964 D) (G : D \u2964 E) (\u03b1 : H \u27f9 K) :\n  whisker_right (whisker_right \u03b1 F) G = whisker_right \u03b1 (F \u22d9 G) :=\nrfl\n\nlemma whisker_right_left (F : B \u2964 C) {G H : C \u2964 D} (\u03b1 : G \u27f9 H) (K : D \u2964 E) :\n  whisker_right (whisker_left F \u03b1) K = whisker_left F (whisker_right \u03b1 K) :=\nrfl\nend\n\nnamespace functor\n\nuniverses u\u2085 v\u2085\n\nvariables {A : Type u\u2081} [\ud835\udc9c : category.{v\u2081} A]\nvariables {B : Type u\u2082} [\u212c : category.{v\u2082} B]\ninclude \ud835\udc9c \u212c\n\ndef left_unitor (F : A \u2964 B) : ((functor.id _) \u22d9 F) \u2245 F :=\n{ hom := { app := \u03bb X, \ud835\udfd9 (F.obj X) },\n  inv := { app := \u03bb X, \ud835\udfd9 (F.obj X) } }\n\n@[simp] lemma left_unitor_hom_app {F : A \u2964 B} {X} : F.left_unitor.hom.app X = \ud835\udfd9 _ := rfl\n@[simp] lemma left_unitor_inv_app {F : A \u2964 B} {X} : F.left_unitor.inv.app X = \ud835\udfd9 _ := rfl\n\ndef right_unitor (F : A \u2964 B) : (F \u22d9 (functor.id _)) \u2245 F :=\n{ hom := { app := \u03bb X, \ud835\udfd9 (F.obj X) },\n  inv := { app := \u03bb X, \ud835\udfd9 (F.obj X) } }\n\n@[simp] lemma right_unitor_hom_app {F : A \u2964 B} {X} : F.right_unitor.hom.app X = \ud835\udfd9 _ := rfl\n@[simp] lemma right_unitor_inv_app {F : A \u2964 B} {X} : F.right_unitor.inv.app X = \ud835\udfd9 _ := rfl\n\nvariables {C : Type u\u2083} [\ud835\udc9e : category.{v\u2083} C]\nvariables {D : Type u\u2084} [\ud835\udc9f : category.{v\u2084} D]\ninclude \ud835\udc9e \ud835\udc9f\n\ndef associator (F : A \u2964 B) (G : B \u2964 C) (H : C \u2964 D) : ((F \u22d9 G) \u22d9 H) \u2245 (F \u22d9 (G \u22d9 H)) :=\n{ hom := { app := \u03bb _, \ud835\udfd9 _ },\n  inv := { app := \u03bb _, \ud835\udfd9 _ } }\n\n@[simp] lemma associator_hom_app {F : A \u2964 B} {G : B \u2964 C} {H : C \u2964 D} {X} :\n(associator F G H).hom.app X = \ud835\udfd9 _ := rfl\n@[simp] lemma associator_inv_app {F : A \u2964 B} {G : B \u2964 C} {H : C \u2964 D} {X} :\n(associator F G H).inv.app X = \ud835\udfd9 _ := rfl\n\nomit \ud835\udc9f\n\nlemma triangle (F : A \u2964 B) (G : B \u2964 C) :\n  (associator F (functor.id B) G).hom \u229f (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\u2085} [\u2130 : category.{v\u2085} E]\ninclude \ud835\udc9f \u2130\n\nvariables (F : A \u2964 B) (G : B \u2964 C) (H : C \u2964 D) (K : D \u2964 E)\n\nlemma pentagon :\n  (whisker_right (associator F G H).hom K) \u229f (associator F (G \u22d9 H) K).hom \u229f (whisker_left F (associator G H K).hom) =\n    ((associator (F \u22d9 G) H K).hom \u229f (associator F G (H \u22d9 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 \u2227 q \u2192 p := by\n  refine fun \u27e8a, b\u27e9 => a\n\nexample (p q : Prop) : p \u2227 q \u2192 p := by\n  refine fun a => ?hp\n  trace_state\n  exact a.1\n\nexample (p q : Prop) : p \u2227 q \u2192 p := by\n  refine fun \u27e8a, b\u27e9 => a\n\nexample (p q : Prop) : p \u2227 q \u2192 p := by\n  refine fun \u27e8a, b\u27e9 => ?hp\n  trace_state\n  exact a\n\nexample (p q : Prop) : p \u2227 q \u2192 p := by\n  refine fun a => ?hp\n  case hp => exact a.1\n\nexample (p q : Prop) : p \u2227 q \u2192 p := by\n  refine fun \u27e8a, b\u27e9 => ?hp\n  case hp => exact a\n\nexample (p q : Prop) : p \u2227 q \u2192 p := by\n  refine \u03bb \u27e8a, b\u27e9 => ?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 \u00a9 2019 Fran\u00e7ois 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(\u03b1_0 : Sort u_0) (\u03b1_1 : Sort u_1) ... (\u03b1_{n-1} : Sort u_{n-1})\n(\u03b2_0 : Sort v_0) (\u03b2_1 : Sort v_1) ... (\u03b2_{n-1} : Sort v_{n-1}) :=\nmk :: (fn_0 : \u03b1_0 \u2192 \u03b2_0) (fn_1 : \u03b1_1 \u2192 \u03b2_1) ... (fn_{n-1} : \u03b1_{n-1} \u2192 \u03b2_{n-1})\n\ntheorem multi_function_n.mk.eta {\u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1}} (f : multi_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{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 {\u03b1_0 \u03b1_1 ... \u03b1_{n-1}} :\nmulti_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b1_0 \u03b1_1 ... \u03b1_{n-1}\n\ndefinition multi_function_n.comp {\u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1} \u03b3_0 \u03b3_1 ... \u03b3_{n-1}} :\nmulti_function_n \u03b2_0 \u03b2_1 ... \u03b2_{n-1} \u03b3_0 \u03b3_1 ... \u03b3_{n-1} \u2192 \nmulti_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1} \u2192 \nmulti_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b3_0 \u03b3_1 ... \u03b3_{n-1}\n\ntheorem multi_function_n.comp.assoc {\u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1} \u03b3_0 \u03b3_1 ... \u03b3_{n-1} \u03b4_0 \u03b4_1 ... \u03b4_{n-1}} \n(f : multi_function_n \u03b3_0 \u03b3_1 ... \u03b3_{n-1} \u03b4_0 \u03b4_1 ... \u03b4_{n-1})\n(g : multi_function_n \u03b2_0 \u03b2_1 ... \u03b2_{n-1} \u03b3_0 \u03b3_1 ... \u03b3_{n-1})\n(h : multi_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{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 {\u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1}}\n(f : multi_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1}) : \nmulti_function_n.comp multi_function_n.id f = f\n\ntheorem multi_function_n.comp.right_id {\u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{n-1}}\n(f : multi_function_n \u03b1_0 \u03b1_1 ... \u03b1_{n-1} \u03b2_0 \u03b2_1 ... \u03b2_{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 `\u03b1 n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `\u03b2 n in\nlet ctx : expr_ctx :=\n  (dns ++ cns).reverse.zip $\n  (dls ++ cls).reverse.map $\n  \u03bb 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 (\u03bb \u27e8n, t, _\u27e9, (n, t, binder_info.implicit)) in\nlet ctx : expr_ctx := (mk_sub_names `fn n).reverse.enum.foldr (\u03bb \u27e8k, fn\u27e9 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 `\u03b1 n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `\u03b2 n in\nlet ctx : expr_ctx :=\n  (dns ++ cns).reverse.zip $\n  (dls ++ cls).reverse.map $\n  \u03bb 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 (\u03bb 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 (\u03bb 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 (\u03bb 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 (\u03bb \u27e8k, t, v\u27e9,\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 `\u03b1 n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `\u03b2 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  \u03bb 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 (\u03bb 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 (\u03bb 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 `\u03b1 n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `\u03b2 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  \u03bb 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 (\u03bb tctx \u27e8k, dl, cl\u27e9,\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 `\u03b1 n in\nlet ctx : expr_ctx := ts.reverse.zip $ ls.reverse.map (\u03bb 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 (\u03bb 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 `\u03b1 n in\nlet tvs := mk_sub_names `\u03b2 n in\nlet tws := mk_sub_names `\u03b3 n in\nlet ctx : expr_ctx := \n  (tus ++ tvs ++ tws).reverse.zip $\n  (lus ++ lvs ++ lws).reverse.map $\n    \u03bb 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 (\u03bb 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 (\u03bb 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 (\u03bb \u27e8k, fuv, fvw\u27e9,\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 `\u03b1 n in\nlet tus := mk_sub_names `\u03b2 n in\nlet tvs := mk_sub_names `\u03b3 n in\nlet tws := mk_sub_names `\u03b4 n in\nlet ctx : expr_ctx := \n  (tts ++ tus ++ tvs ++ tws).reverse.zip $\n  (lts ++ lus ++ lvs ++ lws).reverse.map $\n    \u03bb 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 `\u03b1 n in\nlet tvs := mk_sub_names `\u03b2 n in\nlet ctx : expr_ctx := (list.zip (tus ++ tvs) (lus ++ lvs)).reverse.map (\u03bb \u27e8n, l\u27e9,\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 `\u03b1 n in\nlet tvs := mk_sub_names `\u03b2 n in\nlet ctx : expr_ctx := (list.zip (tus ++ tvs) (lus ++ lvs)).reverse.map (\u03bb \u27e8n, l\u27e9,\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 >>= \u03bb 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 $ \u03bb env, env.add_multi_function n,\n  -- vm needs code for cases_on ...\n  ron \u2190 get_decl (mfn ++ `rec_on),\n  add_decl (ron.update_name $ mfn ++ `cases_on),\n  -- set attributes\n  (list.range n).mmap (\u03bb 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 {\u03b1} {\u03b2} : has_coe_to_fun (multi_function_1 \u03b1 \u03b2) := \u27e8_, multi_function_1.fn_0\u27e9\n\ntheorem multi_function_1.eq {\u03b1} {\u03b2} {f g : multi_function_1 \u03b1 \u03b2} : f.fn_0 = g.fn_0 \u2192 f = g :=\n\u03bb 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 {\u03b1_0} {\u03b1_1} {\u03b2_0} {\u03b2_1} {f g : multi_function_2 \u03b1_0 \u03b1_1 \u03b2_0 \u03b2_1} : f.fn_0 = g.fn_0 \u2192 f.fn_1 = g.fn_1 \u2192 f = g :=\n\u03bb 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 Lean\nopen Lean Elab\n\ndeclare_syntax_cat fixDecl\nsyntax ident : fixDecl\nsyntax ident \"<\" term : fixDecl\n\nsyntax \"Fix\u2081 \" fixDecl : tactic\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident) => logInfo \"simple\"\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident < $bound:term) =>\n    throwError \"Failed at elab_rules\"\n\nmacro_rules\n| `(\u2115) => `(Nat)\n\nexample : \u2200 b : \u2115, \u2200 a : Nat, a \u2265 2 \u2192 a / a = 1 := by\n  Fix\u2081 b\n  Fix\u2081 a < 2  -- should produce `Failed at elab_rules`\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/macroElabRulesIssue2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.39606818053136394, "lm_q2_score": 0.04084571605589629, "lm_q1q2_score": 0.016177688440759563}}
{"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-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.logic\nimport Mathlib.Lean3Lib.init.data.nat.basic\nimport Mathlib.Lean3Lib.init.data.bool.basic\nimport Mathlib.Lean3Lib.init.propext\n\nuniverses u u_1 v w \n\nnamespace Mathlib\n\nprotected instance list.inhabited (\u03b1 : Type u) : Inhabited (List \u03b1) := { default := [] }\n\nnamespace list\n\n\nprotected def has_dec_eq {\u03b1 : Type u} [s : DecidableEq \u03b1] : DecidableEq (List \u03b1) := sorry\n\nprotected instance decidable_eq {\u03b1 : Type u} [DecidableEq \u03b1] : DecidableEq (List \u03b1) :=\n  list.has_dec_eq\n\n@[simp] protected def append {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 := sorry\n\nprotected instance has_append {\u03b1 : Type u} : Append (List \u03b1) := { append := list.append }\n\nprotected def mem {\u03b1 : Type u} : \u03b1 \u2192 List \u03b1 \u2192 Prop := sorry\n\nprotected instance has_mem {\u03b1 : Type u} : has_mem \u03b1 (List \u03b1) := has_mem.mk list.mem\n\nprotected instance decidable_mem {\u03b1 : Type u} [DecidableEq \u03b1] (a : \u03b1) (l : List \u03b1) :\n    Decidable (a \u2208 l) :=\n  sorry\n\nprotected instance has_emptyc {\u03b1 : Type u} : has_emptyc (List \u03b1) := has_emptyc.mk []\n\nprotected def erase {\u03b1 : Type u_1} [DecidableEq \u03b1] : List \u03b1 \u2192 \u03b1 \u2192 List \u03b1 := sorry\n\nprotected def bag_inter {\u03b1 : Type u_1} [DecidableEq \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 := sorry\n\nprotected def diff {\u03b1 : Type u_1} [DecidableEq \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 := sorry\n\n@[simp] def length {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 := sorry\n\ndef empty {\u03b1 : Type u} : List \u03b1 \u2192 Bool := sorry\n\n@[simp] def nth {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 \u2192 Option \u03b1 := sorry\n\n@[simp] def nth_le {\u03b1 : Type u} (l : List \u03b1) (n : \u2115) : n < length l \u2192 \u03b1 := sorry\n\n@[simp] def head {\u03b1 : Type u} [Inhabited \u03b1] : List \u03b1 \u2192 \u03b1 := sorry\n\n@[simp] def tail {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 := sorry\n\ndef reverse_core {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 := sorry\n\ndef reverse {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 := fun (l : List \u03b1) => reverse_core l []\n\n@[simp] def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) : List \u03b1 \u2192 List \u03b2 := sorry\n\n@[simp] def map\u2082 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) :\n    List \u03b1 \u2192 List \u03b2 \u2192 List \u03b3 :=\n  sorry\n\ndef map_with_index_core {\u03b1 : Type u} {\u03b2 : Type v} (f : \u2115 \u2192 \u03b1 \u2192 \u03b2) : \u2115 \u2192 List \u03b1 \u2192 List \u03b2 := sorry\n\n/-- Given a function `f : \u2115 \u2192 \u03b1 \u2192 \u03b2` and `as : list \u03b1`, `as = [a\u2080, a\u2081, ...]`, returns the list\n`[f 0 a\u2080, f 1 a\u2081, ...]`. -/\ndef map_with_index {\u03b1 : Type u} {\u03b2 : Type v} (f : \u2115 \u2192 \u03b1 \u2192 \u03b2) (as : List \u03b1) : List \u03b2 :=\n  map_with_index_core f 0 as\n\ndef join {\u03b1 : Type u} : List (List \u03b1) \u2192 List \u03b1 := sorry\n\ndef filter_map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 Option \u03b2) : List \u03b1 \u2192 List \u03b2 := sorry\n\ndef filter {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 := sorry\n\ndef partition {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 \u00d7 List \u03b1 := sorry\n\ndef drop_while {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 := sorry\n\n/-- `after p xs` is the suffix of `xs` after the first element that satisfies\n  `p`, not including that element.\n\n  ```lean\n  after      (eq 1)       [0, 1, 2, 3] = [2, 3]\n  drop_while (not \u2218 eq 1) [0, 1, 2, 3] = [1, 2, 3]\n  ```\n-/\ndef after {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 := sorry\n\ndef span {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 List \u03b1 \u00d7 List \u03b1 := sorry\n\ndef find_index {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) [decidable_pred p] : List \u03b1 \u2192 \u2115 := sorry\n\ndef index_of {\u03b1 : Type u} [DecidableEq \u03b1] (a : \u03b1) : List \u03b1 \u2192 \u2115 := find_index (Eq a)\n\ndef remove_all {\u03b1 : Type u} [DecidableEq \u03b1] (xs : List \u03b1) (ys : List \u03b1) : List \u03b1 :=\n  filter (fun (_x : \u03b1) => \u00ac_x \u2208 ys) xs\n\ndef update_nth {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 \u2192 \u03b1 \u2192 List \u03b1 := sorry\n\ndef remove_nth {\u03b1 : Type u} : List \u03b1 \u2192 \u2115 \u2192 List \u03b1 := sorry\n\n@[simp] def drop {\u03b1 : Type u} : \u2115 \u2192 List \u03b1 \u2192 List \u03b1 := sorry\n\n@[simp] def take {\u03b1 : Type u} : \u2115 \u2192 List \u03b1 \u2192 List \u03b1 := sorry\n\n@[simp] def foldl {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b1) : \u03b1 \u2192 List \u03b2 \u2192 \u03b1 := sorry\n\n@[simp] def foldr {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2) (b : \u03b2) : List \u03b1 \u2192 \u03b2 := sorry\n\ndef any {\u03b1 : Type u} (l : List \u03b1) (p : \u03b1 \u2192 Bool) : Bool :=\n  foldr (fun (a : \u03b1) (r : Bool) => p a || r) false l\n\ndef all {\u03b1 : Type u} (l : List \u03b1) (p : \u03b1 \u2192 Bool) : Bool :=\n  foldr (fun (a : \u03b1) (r : Bool) => p a && r) tt l\n\ndef bor (l : List Bool) : Bool := any l id\n\ndef band (l : List Bool) : Bool := all l id\n\ndef zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : List \u03b1 \u2192 List \u03b2 \u2192 List \u03b3 :=\n  sorry\n\ndef zip {\u03b1 : Type u} {\u03b2 : Type v} : List \u03b1 \u2192 List \u03b2 \u2192 List (\u03b1 \u00d7 \u03b2) := zip_with Prod.mk\n\ndef unzip {\u03b1 : Type u} {\u03b2 : Type v} : List (\u03b1 \u00d7 \u03b2) \u2192 List \u03b1 \u00d7 List \u03b2 := sorry\n\nprotected def insert {\u03b1 : Type u} [DecidableEq \u03b1] (a : \u03b1) (l : List \u03b1) : List \u03b1 :=\n  ite (a \u2208 l) l (a :: l)\n\nprotected instance has_insert {\u03b1 : Type u} [DecidableEq \u03b1] : has_insert \u03b1 (List \u03b1) :=\n  has_insert.mk list.insert\n\nprotected instance has_singleton {\u03b1 : Type u} : has_singleton \u03b1 (List \u03b1) :=\n  has_singleton.mk fun (x : \u03b1) => [x]\n\nprotected instance is_lawful_singleton {\u03b1 : Type u} [DecidableEq \u03b1] :\n    is_lawful_singleton \u03b1 (List \u03b1) :=\n  is_lawful_singleton.mk\n    fun (x : \u03b1) => (fun (this : ite (x \u2208 []) [] [x] = [x]) => this) (if_neg not_false)\n\nprotected def union {\u03b1 : Type u} [DecidableEq \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : List \u03b1 :=\n  foldr insert l\u2082 l\u2081\n\nprotected instance has_union {\u03b1 : Type u} [DecidableEq \u03b1] : has_union (List \u03b1) :=\n  has_union.mk list.union\n\nprotected def inter {\u03b1 : Type u} [DecidableEq \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : List \u03b1 :=\n  filter (fun (_x : \u03b1) => _x \u2208 l\u2082) l\u2081\n\nprotected instance has_inter {\u03b1 : Type u} [DecidableEq \u03b1] : has_inter (List \u03b1) :=\n  has_inter.mk list.inter\n\n@[simp] def repeat {\u03b1 : Type u} (a : \u03b1) : \u2115 \u2192 List \u03b1 := sorry\n\ndef range_core : \u2115 \u2192 List \u2115 \u2192 List \u2115 := sorry\n\ndef range (n : \u2115) : List \u2115 := range_core n []\n\ndef iota : \u2115 \u2192 List \u2115 := sorry\n\ndef enum_from {\u03b1 : Type u} : \u2115 \u2192 List \u03b1 \u2192 List (\u2115 \u00d7 \u03b1) := sorry\n\ndef enum {\u03b1 : Type u} : List \u03b1 \u2192 List (\u2115 \u00d7 \u03b1) := enum_from 0\n\n@[simp] def last {\u03b1 : Type u} (l : List \u03b1) : l \u2260 [] \u2192 \u03b1 := sorry\n\ndef ilast {\u03b1 : Type u} [Inhabited \u03b1] : List \u03b1 \u2192 \u03b1 := sorry\n\ndef init {\u03b1 : Type u} : List \u03b1 \u2192 List \u03b1 := sorry\n\ndef intersperse {\u03b1 : Type u} (sep : \u03b1) : List \u03b1 \u2192 List \u03b1 := sorry\n\ndef intercalate {\u03b1 : Type u} (sep : List \u03b1) (xs : List (List \u03b1)) : List \u03b1 :=\n  join (intersperse sep xs)\n\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} (a : List \u03b1) (b : \u03b1 \u2192 List \u03b2) : List \u03b2 :=\n  join (map b a)\n\nprotected def ret {\u03b1 : Type u} (a : \u03b1) : List \u03b1 := [a]\n\nprotected def lt {\u03b1 : Type u} [HasLess \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 Prop := sorry\n\nprotected instance has_lt {\u03b1 : Type u} [HasLess \u03b1] : HasLess (List \u03b1) := { Less := list.lt }\n\nprotected instance has_decidable_lt {\u03b1 : Type u} [HasLess \u03b1] [h : DecidableRel Less] (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b1) : Decidable (l\u2081 < l\u2082) :=\n  sorry\n\nprotected def le {\u03b1 : Type u} [HasLess \u03b1] (a : List \u03b1) (b : List \u03b1) := \u00acb < a\n\nprotected instance has_le {\u03b1 : Type u} [HasLess \u03b1] : HasLessEq (List \u03b1) := { LessEq := list.le }\n\nprotected instance has_decidable_le {\u03b1 : Type u} [HasLess \u03b1] [h : DecidableRel Less] (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b1) : Decidable (l\u2081 \u2264 l\u2082) :=\n  not.decidable\n\ntheorem le_eq_not_gt {\u03b1 : Type u} [HasLess \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : l\u2081 \u2264 l\u2082 = (\u00acl\u2082 < l\u2081) :=\n  rfl\n\ntheorem lt_eq_not_ge {\u03b1 : Type u} [HasLess \u03b1] [DecidableRel Less] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) :\n    l\u2081 < l\u2082 = (\u00acl\u2082 \u2264 l\u2081) :=\n  (fun (this : l\u2081 < l\u2082 = (\u00ac\u00acl\u2081 < l\u2082)) => this)\n    (Eq.symm (propext (decidable.not_not_iff (l\u2081 < l\u2082))) \u25b8 rfl)\n\n/--  `is_prefix_of l\u2081 l\u2082` returns `tt` iff `l\u2081` is a prefix of `l\u2082`. -/\ndef is_prefix_of {\u03b1 : Type u} [DecidableEq \u03b1] : List \u03b1 \u2192 List \u03b1 \u2192 Bool := sorry\n\n/--  `is_suffix_of l\u2081 l\u2082` returns `tt` iff `l\u2081` is a suffix of `l\u2082`. -/\ndef is_suffix_of {\u03b1 : Type u} [DecidableEq \u03b1] (l\u2081 : List \u03b1) (l\u2082 : List \u03b1) : Bool :=\n  is_prefix_of (reverse l\u2081) (reverse l\u2082)\n\nend list\n\n\nnamespace bin_tree\n\n\ndef to_list {\u03b1 : Type u} (t : bin_tree \u03b1) : List \u03b1 := to_list_aux t []\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/list/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.05261895557619137, "lm_q1q2_score": 0.016172857167728354}}
{"text": "import LMT\n\nvariable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)]\n\nexample {a1 a2 a3 : A I E} :\n        ((((a2).write i2 ((a3).read i2)).write i1 (v3)).read i2) \u2260 (((a3).write i1 (v3)).read i2) \u2192 False := by\n  arr\n", "meta": {"author": "abdoo8080", "repo": "ar-project", "sha": "303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8", "save_path": "github-repos/lean/abdoo8080-ar-project", "path": "github-repos/lean/abdoo8080-ar-project/ar-project-303af2d62cf8c8fe996c9670f9fe5a0cc90e5bb8/Test/Lean/Test71.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.03258974629287097, "lm_q1q2_score": 0.01616757203991606}}
{"text": "\nimport data.bitvec\nimport data.dlist\nimport util.meta.tactic\nimport util.logic\nimport util.control.applicative\nimport util.control.monad.non_termination\nimport separation.heap\n\nuniverses u v w w'\n\nopen nat list function\n\nnamespace separation\n\nstructure hstate :=\n  (heap : heap)\n  (next : \u2115)\n  (free : \u2200 p, next \u2264 p \u2192 heap p = none)\n@[reducible]\ndef program := state_t hstate nonterm\n\nlocal attribute [instance, priority 0] classical.prop_decidable\n\ndef is_free {s : hstate} {p : pointer}\n  (h : s.next \u2264 p)\n  (vs : list word)\n: heap.mk p vs ## s.heap :=\nby { intro, apply or_iff_not_imp_left.mpr, intro, apply s.free,\n     apply le_trans h,\n     by_contradiction, apply a, clear a,\n     induction vs generalizing p; dsimp [heap.mk], { refl },\n     { simp [-heap.heap_mk_eq_none], split,\n       { have : p \u2260 p_1,\n         { intro, apply a_1, subst p_1, },\n         simp! *,  },\n       apply vs_ih, apply le_trans h, simp [zero_le_one],\n       intro, apply a_1, transitivity; [skip, apply a],\n       simp [(\u2265),zero_le_one], },\n     { apply_instance } }\n\nexport nonterm (run_to)\n\nnamespace program\n\nvariables {\u03b1 : Type u} {\u03b2 : Type}\n\nsection mfix\n\n@[extensionality]\nprotected def ext (x y : program \u03b2)\n: (\u2200 i, x.run i = y.run i) \u2192 x = y :=\nby { casesm* program _, intro,\n     congr, apply funext a, }\n\nprotected def le (x y : program \u03b2) : Prop :=\n\u2200 i, x.run i \u2264 y.run i\n\ninstance : has_le (program \u03b2) :=\n { le := program.le }\n\nprotected def le_refl (x : program \u03b2)\n: x \u2264 x :=\nby { intro, apply le_refl _ }\n\nprotected def le_antisymm (x y : program \u03b2)\n  (h\u2080 : x \u2264 y)\n  (h\u2081 : y \u2264 x)\n: x = y :=\nby { ext i, apply le_antisymm (h\u2080 i) (h\u2081 i) }\n\nprotected def le_trans (x y z : program \u03b2)\n  (h\u2080 : x \u2264 y)\n  (h\u2081 : y \u2264 z)\n: x \u2264 z :=\nby { intro i, apply le_trans (h\u2080 i) (h\u2081 i) }\n\ninstance : partial_order (program \u03b2) :=\n { le := program.le\n , le_refl := @program.le_refl \u03b2\n , le_antisymm := program.le_antisymm\n , le_trans := program.le_trans }\n\ninstance has_mono_program : has_mono program :=\n { to_monad := by apply_instance\n , le := by apply_instance\n , input_t  := hstate\n , result_t := \u03bb \u03b1, \u03b1 \u00d7 hstate\n , run_to := \u03bb \u03b1 m i s s', nonterm.run_to (m.run s) i s'\n , run_to_imp_run_to_of_le := by { introv h, apply h } }\n\n@[reducible]\nprotected def monotonic (f : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 program \u03b2) : Prop :=\n@monotonic nonterm _ (\u03b1 \u00d7 hstate) (\u03b2 \u00d7 hstate) $\n\u03bb rec, uncurry' $\n\u03bb x y, (f (state_t.mk \u2218 curry rec) x).run y\n\nprotected lemma lift_mono {\u03b1 \u03b2} (f : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 program \u03b2)\n  (h : monotonic f)\n: @monotonic nonterm _ (\u03b1 \u00d7 hstate) (\u03b2 \u00d7 hstate) $\n  \u03bb rec, uncurry' $\n  \u03bb x y, (f (state_t.mk \u2218 curry rec) x).run y :=\nbegin\n  unfold monotonic,\n  intros v\u2080 i v' v1 v2 h' x,\n  apply h,\n  { intros x y,\n    apply h' }\nend\n\nprotected def mfix {\u03b1 : Type} {\u03b2 : Type}\n  (f : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 program \u03b2)\n  (Hf : monotonic f)\n: \u03b1 \u2192 program \u03b2 :=\n state_t.mk \u2218 curry (@nonterm.fix (\u03b1 \u00d7 hstate) (\u03b2 \u00d7 hstate) _ (program.lift_mono _ Hf))\n\n-- @[reducible]\n-- def monotonic2 {\u03b1 : Type} {\u03b3 : Type} {\u03b2 : Type}\n--   (f : (\u03b1 \u2192 \u03b3 \u2192 program \u03b2) \u2192 \u03b1 \u2192 \u03b3 \u2192 program \u03b2) :=\n-- monotonic (\u03bb rec, uncurry' (f $ curry rec))\n\nprotected def program.mfix2 {\u03b1 : Type} {\u03b1' : Type} {\u03b2 : Type}\n  (f : (\u03b1 \u2192 \u03b1' \u2192 program \u03b2) \u2192 \u03b1 \u2192 \u03b1' \u2192 program \u03b2)\n  (Hf : monotonic2 f)\n: \u03b1 \u2192 \u03b1' \u2192 program \u03b2 :=\ncurry $ program.mfix (\u03bb g, uncurry' (f $ curry g)) Hf\n\ndef program.fix_unroll {\u03b1 : Type} {\u03b2 : Type}\n  (f : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 program \u03b2)\n  (Hf : monotonic f)\n: program.mfix f Hf = f (program.mfix f Hf) :=\nbegin\n  admit\nend\n\ndef program.fix2_unroll {\u03b1 : Type} {\u03b1' : Type} {\u03b2 : Type}\n  (f : (\u03b1 \u2192 \u03b1' \u2192 program \u03b2) \u2192 \u03b1 \u2192 \u03b1' \u2192 program \u03b2)\n  (Hf : monotonic2 f)\n: program.mfix2 f Hf = f (program.mfix2 f Hf) :=\nbegin\n  admit\nend\n\nend mfix\n\nend program\n\nnamespace program\n\nsection\n\nvariables {\u03b1 \u03b2 \u03b3 : Type}\nvariable f  : \u03b1 \u2192 program \u03b3\nvariable g  : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 \u03b3 \u2192 program \u03b2\nvariable Hg  : \u2200 y, monotonic (\u03bb rec x, g rec x y)\n\ninclude Hg\n\nprotected lemma bind_monotonic'\n: monotonic (\u03bb rec x, f x >>= g rec x) :=\nsorry\n\nend\n\nsection\n\nvariables {\u03b1 : Type}\nvariables {\u03b2 : Type}\nvariable f : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 program \u03b2\nvariable g : (\u03b1 \u2192 program \u03b2) \u2192 \u03b1 \u2192 \u03b2 \u2192 program \u03b2\nvariable Hf : monotonic (\u03bb rec x, f rec x)\nvariable Hg : \u2200 y, monotonic (\u03bb rec x, g rec x y)\ninclude Hf\n\nprotected lemma pre_fixpoint (x : \u03b1)\n: program.mfix f Hf x \u2264 f (program.mfix f Hf) x :=\nsorry\n\ninclude Hg\n\nprotected lemma bind_monotonic\n: monotonic (\u03bb rec x, f rec x >>= g rec x) :=\nsorry\n\nend\n\nend program\n\ninstance has_fix_program : has_fix program :=\n { to_has_mono := by apply_instance\n , mfix := \u03bb \u03b1 \u03b2 f h, @program.mfix \u03b1 \u03b2 _ h\n , bind_monotonic := by { introv h\u2080 h\u2081, apply program.bind_monotonic _ _ h\u2080 h\u2081, }\n , bind_monotonic' := @program.bind_monotonic'\n , pre_fixpoint := by { introv, apply program.pre_fixpoint } }\n\ndef read (p : pointer) : program word := do\nh \u2190 state_t.get,\nstate_t.lift $ option.rec_on (h.heap p) nonterm.diverge return\n\nmeta def decide : tactic unit :=\n`[apply of_as_true, exact trivial]\n\ndef read_nth (p : pointer) (i j : \u2115) (h : i < j . decide) : program word :=\nread $ p+i\n\nexample : \u2200 x : read_nth 100 1 2 = return 3, true :=\nby { intro, trivial }\n\ndef write (p : pointer) (v : word) : program unit := do\ns \u2190 state_t.get,\nif h : (s.heap p).is_some then\n  state_t.put\n    { s with\n      heap := s.heap.insert p v\n    , free :=\n      begin\n        intros q h',\n        simp [heap.insert],\n        by_cases h'' : p = q,\n        { rw [if_pos h''],\n          exfalso, subst q,\n          have h\u2083 := s.free p h',\n          admit },\n        { rw [if_neg h''], apply s.free _ h' }\n      end }\nelse state_t.lift nonterm.diverge\n\ndef write_nth (p : pointer) (i j : \u2115) (v : word) (h : i < j . decide) : program unit :=\nwrite (p+i) v\n\ndef modify (p : pointer) (f : word \u2192 word) : program unit :=\nread p >>= write p \u2218 f\n\ndef modify_nth (p : pointer) (i j : \u2115) (f : word \u2192 word) (h : i < j . decide) : program unit :=\nmodify (p+i) f\n\ndef alloc (vs : list word) : program pointer := do\ns \u2190 state_t.get,\nlet r := s.next + 1,\nstate_t.put\n  { s with next := s.next + vs.length,\n           heap := heap.mk r vs <+ s.heap,\n           free := by { intros, simp!, split,\n                        { sorry }, sorry } },\nreturn r\n\ndef alloc1 (v : word) : program pointer := do\nalloc [v]\n\ndef free (p : pointer) (ln : \u2115) : program unit := do\ns \u2190 state_t.get,\nstate_t.put\n  { s with heap := heap.delete p ln s.heap,\n           free := by { intros, induction ln generalizing p,\n                        apply s.free _ a,\n                        simp!, split_ifs, refl,\n                        apply_assumption } }\n\ndef free1 (p : pointer) : program unit := do\nfree p 1\n\ndef copy (p q : pointer) : program unit := do\nv \u2190 read q,\nwrite p v\n\nend separation\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/program.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.032589741359985346, "lm_q1q2_score": 0.016167569592741942}}
{"text": "import polycodable_init\nimport polytime_tac\n\nvariables {\u03b1 \u03b2 \u03b3 : Type*} [polycodable \u03b1] [polycodable \u03b2] [polycodable \u03b3]\nopen ptree.pencodable (encode decode)\n\nsection bool\n\ninstance : polycodable bool :=\n{ polytime_decode := \u27e8_, \n  (polytime_ite polytime_id polytime_nil (polytime_const ptree.non_nil)), \u03bb x, by cases x; simp [ptree.of_option, encode, decode]\u27e9 }\n\n@[polyfun]\nlemma polytime_fun.ite' {f : \u03b1 \u2192 bool} {g h : \u03b1 \u2192 \u03b2} : polytime_fun f \u2192 polytime_fun g \u2192 polytime_fun h \u2192 polytime_fun (\u03bb x, cond (f x) (g x) (h x))\n| \u27e8cf, pf, sf\u27e9 \u27e8cg, pg, sg\u27e9 \u27e8ch, ph, sh\u27e9 :=\n\u27e8_, polytime_ite pf pg ph, \u03bb x, by cases H : (f x); simp [sf, sg, sh, \u2190 apply_ite part.some, \u2190 apply_ite encode, encode, H]\u27e9 \n\n@[polyfun]\nlemma polytime_fun.ite {P : \u03b1 \u2192 Prop} [decidable_pred P] {g h : \u03b1 \u2192 \u03b2} (hP : polytime_fun (\u03bb x, (P x : bool))) (hg : polytime_fun g) (hh : polytime_fun h) :\n  polytime_fun (\u03bb x, if P x then g x else h x) :=\nbegin\n  convert_to polytime_fun (\u03bb 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 (\u03bb x', (x' = ptree.nil : bool)) :=\n\u27e8_, polytime_ite polytime_id polytime_nil (polytime_const ptree.non_nil), \u03bb x, by cases x; simp [encode]\u27e9\n\nlocal attribute [polyfun] polytime_fun.eq_nil_aux\n\n@[polyfun]\nlemma polytime_fun.band : polytime_fun\u2082 (&&) :=\nbegin\n  convert_to polytime_fun\u2082 (\u03bb b\u2081 b\u2082 : bool, cond b\u2081 b\u2082 ff),\n  { ext b\u2081, cases b\u2081; simp, }, polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.bor : polytime_fun\u2082 (||) :=\nbegin\n  convert_to polytime_fun\u2082 (\u03bb b\u2081 b\u2082 : bool, cond b\u2081 tt b\u2082),\n  { ext b\u2081, cases b\u2081; simp, }, polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.bnot : polytime_fun bnot :=\nby { convert_to polytime_fun (\u03bb b, cond b ff tt), { ext b, cases b; refl, }, polyfun, }\n\nlemma ptree_children {f g : ptree \u2192 bool} (hf : polytime_fun f) (hg : polytime_fun g) :\n  polytime_fun (\u03bb x : ptree, (x \u2260 ptree.nil) && (f x.left && g x.right)) :=\nby polyfun\n\nprivate lemma polytime_fun.eq_const_aux : \u2200 (x : ptree), polytime_fun (\u03bb 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 : \u03b1 \u2192 \u03b2} [decidable_eq \u03b2] (hf : polytime_fun f) (x : \u03b2) : polytime_fun (\u03bb x', (f x' = x : bool)) :=\nbegin\n  convert_to polytime_fun (\u03bb 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 \u03b1) :=\n{ polytime_decode :=\nbegin\n  convert_to polytime_fun (\u03bb x : ptree, if x = ptree.nil then ptree.nil else ptree.of_option (some (encode (decode x.right : \u03b1)))),\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 \u03b1) :=\nby { apply polytime_fun.decode, simp [encode, function.comp, ptree.of_option], polyfun, }\n\n@[polyfun]\nlemma polytime_fun.iget [inhabited \u03b1] : polytime_fun (@option.iget \u03b1 _) :=\n\u27e8code.ite code.id (code.const (encode (default : \u03b1))) code.right, polytime_ite polytime_id (polytime_const _) polytime_right, \u03bb x,\nby { cases x; simp [encode, ptree.of_option], }\u27e9\n\n@[polyfun]\nlemma polytime_fun.is_none : polytime_fun (@option.is_none \u03b1) :=\n\u27e8code.ite code.id (code.const $ encode tt) (code.const $ encode ff), polytime_ite polytime_id (polytime_const _) (polytime_const _), \u03bb x,\nby { cases x; simp [encode, ptree.of_option], }\u27e9\n\n@[polyfun]\nlemma polytime_fun.option_elim {f : \u03b1 \u2192 option \u03b2} {g : \u03b1 \u2192 \u03b3} {h : \u03b1 \u2192 \u03b2 \u2192 \u03b3} (hf : polytime_fun f) (hg : polytime_fun g) (hh : polytime_fun\u2082 h) :\n  polytime_fun (\u03bb x, (f x).elim (g x) (h x)) :=\nbegin\n  apply polytime_fun.decode,\n  haveI : inhabited \u03b2 := \u27e8decode ptree.nil\u27e9,\n  convert_to polytime_fun (\u03bb x : \u03b1, 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 : \u03b1 \u2192 option \u03b2} {g : \u03b1 \u2192 \u03b2 \u2192 \u03b3} (hf : polytime_fun f) (hg : polytime_fun\u2082 g) :\n  polytime_fun (\u03bb x, (f x).map (g x)) :=\nbegin\n  convert_to polytime_fun (\u03bb x, (f x).elim none (\u03bb 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\u2082 (@option.get_or_else \u03b1) :=\nbegin\n  convert_to polytime_fun\u2082 (\u03bb (a : option \u03b1) (b : \u03b1), 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 \u03b1) :=\nbegin\n  convert_to polytime_fun (\u03bb (a : option \u03b1), a.elim ff (\u03bb _, tt)),\n  { ext x, cases x; simp, }, polyfun,\nend\n\nend option\n\nsection mk\n\ndef polycodable.mk' {\u03b4 : Type*} (encode : \u03b4 \u2192 \u03b1) (decode : \u03b1 \u2192 \u03b4) (encode_decode : \u2200 x, decode (encode x) = x)\n  (polytime_decode : polytime_fun (encode \u2218 decode)) : polycodable \u03b4 :=\n{ polytime_decode :=\nby { apply polytime_fun.comp polytime_decode, polyfun, },\n  ..ptree.pencodable.mk' encode decode encode_decode, }\n\nlemma polycodable.mk_encode {\u03b4 : Type*} (encode : \u03b4 \u2192 \u03b1) (decode : \u03b1 \u2192 \u03b4) (encode_decode : \u2200 x, decode (encode x) = x) :\n  @polytime_fun \u03b4 \u03b1 (ptree.pencodable.mk' encode decode encode_decode) _ encode :=\nby { apply polytime_fun.id, }\n\nlemma polycodable.mk_decode' {\u03b4 : Type*} (encode : \u03b4 \u2192 \u03b1) (decode : \u03b1 \u2192 \u03b4) (encode_decode : \u2200 x, decode (encode x) = x)\n  (polytime_decode : polytime_fun (encode \u2218 decode)) :\n  @polytime_fun \u03b1 \u03b4 _ (polycodable.mk' encode decode encode_decode polytime_decode).to_pencodable decode :=\npolytime_decode\n\nlemma polycodable.mk_decode {\u03b4 : Type*} (encode : \u03b4 \u2192 \u03b1) (decode : \u03b1 \u2192 \u03b4) (encode_decode : \u2200 x, decode (encode x) = x)\n  (f : \u03b2 \u2192 \u03b4) (hf : polytime_fun (encode \u2218 f)) :\n  @polytime_fun \u03b2 \u03b4 _ (ptree.pencodable.mk' encode decode encode_decode) f :=\nhf\n\ndef polycodable.of_equiv {\u03b4 : Type*} (eqv : \u03b4 \u2243 \u03b1) : polycodable \u03b4 :=\npolycodable.mk'\n(\u03bb x, eqv x)\n(\u03bb y, eqv.symm y)\n(by simp)\n(by simpa using polytime_fun.id)\n\n@[polyfun]\nlemma polycodable.of_equiv_polytime {\u03b4 : Type*} (eqv : \u03b4 \u2243 \u03b1) :\n  @polytime_fun \u03b4 \u03b1 (ptree.pencodable.of_equiv eqv) _ eqv :=\nby { apply polytime_fun.id, }\n\n@[polyfun]\nlemma polycodable.of_equiv_polytime_symm {\u03b4 : Type*} (eqv : \u03b4 \u2243 \u03b1) :\n  @polytime_fun \u03b1 \u03b4 _ (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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_is_zero \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 71))\n    (h_mem_5 : mem_at mem code_unreduced_mul (\u03c3.pc  - 59))\n    (h_mem_7 : mem_at mem code_verify_zero (\u03c3.pc  - 23))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 6))\n    (hin_x : x = cast_BigInt3 mem (\u03c3.fp - 5))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 6)) (mem $ \u03c4.ap - 2)\n        (spec_is_zero mem \u03ba range_check_ptr x (mem (\u03c4.ap - 2)) (mem (\u03c4.ap - 1)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  have h_mem_rec := h_mem,\n  unpack_memory code_is_zero at h_mem with \u27e8hpc0, 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\u27e9,\n  -- if statement\n  -- tempvar\n  apply of_register_state,\n  intros regstate_\u03b9\u03c7__temp40 regstateeq_\u03b9\u03c7__temp40,\n  generalize' hl_rev_\u03b9\u03c7__temp40: mem regstate_\u03b9\u03c7__temp40.ap = \u03b9\u03c7__temp40,\n  have hl_\u03b9\u03c7__temp40 := hl_rev_\u03b9\u03c7__temp40.symm,\n  rw [regstateeq_\u03b9\u03c7__temp40] at hl_\u03b9\u03c7__temp40, try { dsimp at hl_\u03b9\u03c7__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 : \u03b9\u03c7__temp40 = 0, {\n      try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_\u03b9\u03c7__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_\u03b9\u03c7__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 \u03ba_call18 ap18 h_call18,\n    rcases h_call18 with \u27e8h_call18_ap_offset, h_call18\u27e9,\n    rcases h_call18 with \u27e8rc_m18, rc_mle18, hl_range_check_ptr\u2081, h_call18\u27e9,\n    generalize' hr_rev_range_check_ptr\u2081: mem (ap18 - 4) = range_check_ptr\u2081,\n    have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\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\u2081 },\n    rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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_\u03b9\u03c7__temp40, htv_range_check_ptr\u2081, 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_\u03b9\u03c7__temp40, htv_range_check_ptr\u2081, 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 \u03ba_call26 ap26 h_call26,\n    rcases h_call26 with \u27e8h_call26_ap_offset, h_call26\u27e9,\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\u2081 {\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_\u03b9\u03c7__temp40, htv_range_check_ptr\u2081, 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_\u03b9\u03c7__temp40, htv_range_check_ptr\u2081, 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 \u03ba_call33 ap33 h_call33,\n    rcases h_call33 with \u27e8h_call33_ap_offset, h_call33\u27e9,\n    rcases h_call33 with \u27e8rc_m33, rc_mle33, hl_range_check_ptr\u2082, h_call33\u27e9,\n    generalize' hr_rev_range_check_ptr\u2082: mem (ap33 - 1) = range_check_ptr\u2082,\n    have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\n    try { simp only [arg0 ,arg1 ,arg2 ,arg3] at hl_range_check_ptr\u2082 },\n    try { rw [h_call26_ap_offset] at hl_range_check_ptr\u2082 }, try { arith_simps at hl_range_check_ptr\u2082 },\n    rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\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 [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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 [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03b9\u03c7__temp40],\n    right,\n    use_only [a0],\n    use_only [\u03ba_call18],\n    use_only [range_check_ptr\u2081],\n    use_only [x_inv],\n    have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n    have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n    have spec18 := h_call18 rc_h_range_check_ptr',\n    rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] at spec18,\n    try { dsimp at spec18, arith_simps at spec18 },\n    use_only [spec18],\n    use_only [\u03ba_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 [\u03ba_call33],\n    use_only [range_check_ptr\u2082],\n    have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n    have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n    have spec33 := h_call33 rc_h_range_check_ptr\u2081',\n    rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190htv_range_check_ptr\u2082] 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_\u03b9\u03c7__temp40, htv_range_check_ptr\u2081, htv_x_inv, htv_x_x_inv, htv_range_check_ptr\u2082] }, },\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 : \u03b9\u03c7__temp40 \u2260 0, {\n      try { simp only [ne.def] },\n      try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_\u03b9\u03c7__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_\u03b9\u03c7__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_\u03b9\u03c7__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 \u03ba_call12 ap12 h_call12,\n    rcases h_call12 with \u27e8h_call12_ap_offset, h_call12\u27e9,\n    rcases h_call12 with \u27e8rc_m12, rc_mle12, hl_range_check_ptr\u2081, h_call12\u27e9,\n    generalize' hr_rev_range_check_ptr\u2081: mem (ap12 - 1) = range_check_ptr\u2081,\n    have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\n    try { simp only [arg0 ,arg1 ,arg2 ,arg3] at hl_range_check_ptr\u2081 },\n    rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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 [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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 [\u03b9\u03c7__temp40],\n    left,\n    use_only [a0],\n    use_only [\u03ba_call12],\n    use_only [range_check_ptr\u2081],\n    have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n    have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n    have spec12 := h_call12 rc_h_range_check_ptr',\n    rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] 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_\u03b9\u03c7__temp40, htv_range_check_ptr\u2081] }, },\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 \u2190 pure 0\n   return {\n      val := v\n      H := by {\n         /-\n         M: Type \u2192 Type ?u.380\n         Mon: Monad M\n         v: \u2115\n         \u22a2 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\u03b1 := inferInstance\n  i\u03b5 := 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 {\u0394: Dialect \u03b1 \u03c3 \u03b5} (r: Region \u0394) (f: Int \u2192 FinInt 32 \u2192 FinInt 32) :=\n  forall (i: Int) (v: FinInt 32),\n  OpM.denoteRegion r 0 [\u27e8.index, i\u27e9, \u27e8.i32, v\u27e9] = return [\u27e8.i32, f i v\u27e9]\n\n\ndef OpM.findIndex (d: AttrDict \u03b4) (key: String): OpM \u0394 Nat :=\n match d.find_int key with\n | .some \u27e8v, MLIRType.index\u27e9 => return v.toNat\n | _ => OpM.Error s!\"{d}.lookup {key} failed to find int\"\n\ndef OpM.findI32 (d: AttrDict \u03b4) (key: String): OpM \u0394 (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 {\u0394: Dialect \u03b1 \u03c3 \u03b5}: IOp \u0394 \u2192 OpM \u0394 (TypedArgs \u0394)\n | IOp.mk \"linalg.extractslice1d\" _ [\u27e8.tensor1d, t\u27e9] [] dict => do\n    let len \u2190  OpM.findIndex dict \"len\"\n    let t' := t.extract len\n    return [\u27e8.tensor1d, t'\u27e9]\n | IOp.mk \"linalg.fill1d\" _ [\u27e8.tensor1d, t\u27e9]  [] dict => do\n     let cst \u2190  OpM.findI32 dict \"cst\"\n     let t' := t.fill cst\n     return [\u27e8.tensor1d, t'\u27e9]\n | IOp.mk \"linalg.generic1d'\" _ [\u27e8.tensor1d, t\u27e9] [r] _ => do -- generic1d without array index.\n      let t' <- t.mapM (fun val => do\n            let rets \u2190 r [\u27e8.i32, val\u27e9]\n            match rets with\n            | [\u27e8.i32, v\u27e9] => pure v\n            | _ => OpM.Error s!\"linalg.generic1d: unknown return value '{rets}'\")\n      return [\u27e8.tensor1d, t'\u27e9]\n | IOp.mk \"linalg.generic1d\" _ [\u27e8.tensor1d, t\u27e9] [r] _ => do\n      let t' <- t.mapMWithFlatIndex (fun idx val => do\n            let rets \u2190 r [\u27e8.index, idx.ix\u27e9, \u27e8.i32, val\u27e9]\n            match rets with\n            | [\u27e8.i32, v\u27e9] => pure v\n            | _ => OpM.Error s!\"linalg.generic1d: unknown return value '{rets}'\")\n      return [\u27e8.tensor1d, t'\u27e9]\n | IOp.mk \"linalg.extractslice2d\" _ [\u27e8.tensor2d, t\u27e9]  [r] dict =>  do\n      let len0 \u2190  OpM.findIndex dict \"len0\"\n      let len1 \u2190  OpM.findIndex dict \"len1\"\n      dite (\u03b1 := OpM \u0394 (TypedArgs \u0394))\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 [\u27e8.tensor2d, t'\u27e9])\n               (fun GT0 => OpM.Error \"expected index inbounds\"))\n         (fun GT1 => OpM.Error \"expected index inbounds\")\n | IOp.mk \"linalg.fill2d\" _ [\u27e8.tensor2d, t\u27e9]  [r] dict => do\n     let cst \u2190  OpM.findI32 dict \"cst\"\n     let t' := t.fill (FinInt.toSint cst)\n     return [\u27e8.tensor2d, t'\u27e9]\n | IOp.mk \"linalg.transpose2d\"   _ [\u27e8.tensor2d, t\u27e9]  [r] dict => do\n     let t' := t.transpose\n     return [\u27e8.tensor2d, t'\u27e9]\n | IOp.mk \"linalg.insertslice2d\" _ [\u27e8.tensor1d, t\u27e9]  [r] dict => sorry\n | IOp.mk \"linalg.generic2d\" _ [\u27e8.tensor1d, t\u27e9]  [r] dict => sorry\n | IOp.mk \"linalg.parallel2d\" _ [\u27e8.tensor1d, t\u27e9]  [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 {\u0394: Dialect \u03b1 \u03c3 \u03b5} {r: Region \u0394} {rSpec types attrs}:\n  validGenericRegion r rSpec \u2192\n  linalg_semantics_op (\u0394 := \u0394)\n      (IOp.mk \"linalg.generic1d\"\n         types [\u27e8.tensor1d, t\u27e9]\n         [OpM.denoteRegion r 0]\n         attrs) =\n    return [\u27e8.tensor1d, t.mapWithFlatIndex (fun idx val => rSpec idx.ix val)\u27e9] := 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 \u27e6LHS\u27e7 (SSAEnv.One [ (\"t\", \u27e8.tensor1d, t\u27e9) ]) =\n    run \u27e6RHS\u27e7 (SSAEnv.One [ (\"t\", \u27e8.tensor1d, t\u27e9) ]) := 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 {\u0394: Dialect \u03b1 \u03c3 \u03b5} (a: \u03b1) (k: \u03b1 \u2192 OpM \u0394 \u03b2):\n  bind (OpM.Ret a) k = k a := rfl\n\n@[simp]\ntheorem OpM.toTopM_pure {r: TypedArgs \u0394}:\n  OpM.toTopM rs (pure r) env = Except.ok (r, env) := rfl\n\ntheorem equiv (t: Tensor1D) r rSpec:\n   validGenericRegion r rSpec \u2192\n   run \u27e6LHS r\u27e7 (SSAEnv.One [ (\"t\", \u27e8.tensor1d, t\u27e9) ]) =\n   run \u27e6RHS r\u27e7 (SSAEnv.One [ (\"t\", \u27e8.tensor1d, t\u27e9) ]) := 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": "theorem r:0:=do\n0if 0then 0\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/lean/297.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.03622005807570653, "lm_q1q2_score": 0.015997421915644596}}
{"text": "/-\nCopyright (c) 2018 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes H\u00f6lzl\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 \u2208 \u2205` is never\nsatisfied. -/\ndef pi.empty {\u03b1 : Type u_1} (\u03b2 : \u03b1 \u2192 Type u_2) (a : \u03b1) (h : a \u2208 \u2205) : \u03b2 a :=\n  multiset.pi.empty \u03b2 a h\n\n/-- Given a finset `s` of `\u03b1` and for all `a : \u03b1` a finset `t a` of `\u03b4 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 \u2208 s`.\nNote that the elements of `s.pi t` are only partially defined, on `s`. -/\ndef pi {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1) (t : (a : \u03b1) \u2192 finset (\u03b4 a)) : finset ((a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) :=\n  mk (multiset.pi (val s) fun (a : \u03b1) => val (t a)) sorry\n\n@[simp] theorem pi_val {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1) (t : (a : \u03b1) \u2192 finset (\u03b4 a)) : val (pi s t) = multiset.pi (val s) fun (a : \u03b1) => val (t a) :=\n  rfl\n\n@[simp] theorem mem_pi {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {s : finset \u03b1} {t : (a : \u03b1) \u2192 finset (\u03b4 a)} {f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a} : f \u2208 pi s t \u2194 \u2200 (a : \u03b1) (h : a \u2208 s), f a h \u2208 t a :=\n  multiset.mem_pi (val s) (fun (a : \u03b1) => (fun (a : \u03b1) => val (t a)) a) f\n\n/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s \u222a {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 {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1) (a : \u03b1) (b : \u03b4 a) (f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) (a' : \u03b1) (h : a' \u2208 insert a s) : \u03b4 a' :=\n  multiset.pi.cons (val s) a b f a' sorry\n\n@[simp] theorem pi.cons_same {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] (s : finset \u03b1) (a : \u03b1) (b : \u03b4 a) (f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) (h : a \u2208 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 {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {s : finset \u03b1} {a : \u03b1} {a' : \u03b1} {b : \u03b4 a} {f : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a} {h : a' \u2208 insert a s} (ha : a \u2260 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 {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b4 a} {s : finset \u03b1} (hs : \u00aca \u2208 s) : function.injective (pi.cons s a b) := sorry\n\n@[simp] theorem pi_empty {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {t : (a : \u03b1) \u2192 finset (\u03b4 a)} : pi \u2205 t = singleton (pi.empty \u03b4) :=\n  rfl\n\n@[simp] theorem pi_insert {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] [(a : \u03b1) \u2192 DecidableEq (\u03b4 a)] {s : finset \u03b1} {t : (a : \u03b1) \u2192 finset (\u03b4 a)} {a : \u03b1} (ha : \u00aca \u2208 s) : pi (insert a s) t = finset.bUnion (t a) fun (b : \u03b4 a) => image (pi.cons s a b) (pi s t) := sorry\n\ntheorem pi_singletons {\u03b1 : Type u_1} [DecidableEq \u03b1] {\u03b2 : Type u_2} (s : finset \u03b1) (f : \u03b1 \u2192 \u03b2) : (pi s fun (a : \u03b1) => singleton (f a)) = singleton fun (a : \u03b1) (_x : a \u2208 s) => f a := sorry\n\ntheorem pi_const_singleton {\u03b1 : Type u_1} [DecidableEq \u03b1] {\u03b2 : Type u_2} (s : finset \u03b1) (i : \u03b2) : (pi s fun (_x : \u03b1) => singleton i) = singleton fun (_x : \u03b1) (_x : _x \u2208 s) => i :=\n  pi_singletons s fun (_x : \u03b1) => i\n\ntheorem pi_subset {\u03b1 : Type u_1} {\u03b4 : \u03b1 \u2192 Type u_2} [DecidableEq \u03b1] {s : finset \u03b1} (t\u2081 : (a : \u03b1) \u2192 finset (\u03b4 a)) (t\u2082 : (a : \u03b1) \u2192 finset (\u03b4 a)) (h : \u2200 (a : \u03b1), a \u2208 s \u2192 t\u2081 a \u2286 t\u2082 a) : pi s t\u2081 \u2286 pi s t\u2082 :=\n  fun (g : (a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a) (hg : g \u2208 pi s t\u2081) =>\n    iff.mpr mem_pi fun (a : \u03b1) (ha : a \u2208 s) => h a ha (iff.mp mem_pi hg a ha)\n\ntheorem pi_disjoint_of_disjoint {\u03b1 : Type u_1} [DecidableEq \u03b1] {\u03b4 : \u03b1 \u2192 Type u_2} [(a : \u03b1) \u2192 DecidableEq (\u03b4 a)] {s : finset \u03b1} [DecidableEq ((a : \u03b1) \u2192 a \u2208 s \u2192 \u03b4 a)] (t\u2081 : (a : \u03b1) \u2192 finset (\u03b4 a)) (t\u2082 : (a : \u03b1) \u2192 finset (\u03b4 a)) {a : \u03b1} (ha : a \u2208 s) (h : disjoint (t\u2081 a) (t\u2082 a)) : disjoint (pi s t\u2081) (pi s t\u2082) := 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 \u224c D)\n  {X Y B : D} (f : X \u27f6 B) (g : Y \u27f6 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 \u27f6 e.functor.obj Y)\n  (g : X \u27f6 Y) : e.inverse.map f = e.symm.counit.app _ \u226b g \u226b e.unit.app _ \u2192\n  f = e.functor.map g :=\nbegin\n  intros h,\n  change _ = (e.unit_iso.app _).inv \u226b g \u226b (e.unit_iso.app _).hom at h,\n  rw iso.eq_inv_comp at h,\n  replace h := h.symm,\n  rw \u2190 iso.eq_comp_inv at h,\n  rw h,\n  simp,\n  nth_rewrite 0 \u2190 category.id_comp f,\n  simp_rw \u2190 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  \u03c0 :=\n  { app := \u03bb i,\n    match i with\n    | none := e.functor.map pullback.fst \u226b e.counit.app X \u226b f\n    | walking_cospan.left := e.functor.map pullback.fst \u226b e.counit.app X\n    | walking_cospan.right := e.functor.map pullback.snd \u226b 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 \u226b f = e.functor.map (e.inverse.map f) \u226b e.counit.app B, by tidy,\n        rw this, clear this,\n        have : e.counit.app Y \u226b g = e.functor.map (e.inverse.map g) \u226b e.counit.app B, by tidy,\n        rw this, clear this,\n        simp_rw [\u2190 category.assoc, \u2190 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 := \u03bb S, e.symm.unit.app S.X \u226b\n    e.functor.map (pullback.lift (e.inverse.map (S.\u03c0.app walking_cospan.left))\n      (e.inverse.map (S.\u03c0.app walking_cospan.right)) begin\n        simp_rw \u2190 e.inverse.map_comp,\n        change e.inverse.map (_ \u226b (cospan f g).map walking_cospan.hom.inl) =\n          e.inverse.map (_ \u226b (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 \u226b f = e.functor.map (e.inverse.map f) \u226b 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 [\u2190 category.assoc _ _ (e.counit.app B), \u2190 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 _ \u226b (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 [\u2190 category.assoc _ _ (e.counit.app X), \u2190 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 [\u2190 category.assoc _ _ (e.counit.app Y), \u2190 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 \u226b _,\n    rw iso.eq_inv_comp,\n    apply equivalence.hom_eq_map,\n    change _ = (e.unit_iso.app _).inv \u226b _ \u226b (e.unit_iso.app _).hom,\n    rw iso.eq_inv_comp,\n    symmetry,\n    rw \u2190 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 \u2190 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_\u03c0_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 \u2190 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_\u03c0_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 \u27f6 B) (g : Y \u27f6 B)\n  [has_pullback (e.inverse.map f) (e.inverse.map g)] : has_pullback f g :=\nlimits.has_limit.mk \u27e8e.pullback_cone _ _, e.is_limit_pullback_cone _ _\u27e9\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": "/-\nCopyright (c) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\nPorted by: E.W.Ayers\n-/\nimport Lean\nimport Lean.Data\n\nopen Lean\nopen Lean.Elab\nopen Lean.Elab.Command\n\n/--\n__DEPRECATED__: `restate_axiom` was necessary in Lean 3 but is no longer needed for Lean 4.\nIt is still present for backwards compatibility but will probably be removed in the future.\n\n# Original Docstring\n\n`restate_axiom` makes a new copy of a structure field, first definitionally simplifying the type.\nThis is useful to remove `auto_param` or `opt_param` from the statement.\n\nAs an example, we have:\n```lean\nstructure A :=\n(x : \u2115)\n(a' : x = 1 . skip)\n\nexample (z : A) : z.x = 1 := by rw A.a' -- rewrite tactic failed, lemma is not an equality nor a iff\n\nrestate_axiom A.a'\nexample (z : A) : z.x = 1 := by rw A.a\n```\n\nBy default, `restate_axiom` names the new lemma by removing a trailing `'`, or otherwise appending\n`_lemma` if there is no trailing `'`. You can also give `restate_axiom` a second argument to\nspecify the new name, as in\n```lean\nrestate_axiom A.a f\nexample (z : A) : z.x = 1 := by rw A.f\n```\n-/\nelab \"restate_axiom \" oldName:ident newName:optional(ident) : command => do\n  let oldName \u2190 resolveGlobalConstNoOverloadWithInfo oldName\n  let newName : Name :=\n    match newName with\n      | none =>\n        match oldName with\n        | Name.str n s _  =>\n          if s.back = ''' then\n            Name.mkStr n $ s.extract 0 (s.endPos - \u27e81\u27e9)\n          else\n            Name.mkStr n $ s ++ \"_lemma\"\n        | x => x\n      | some n => Name.getPrefix oldName ++ n.getId\n  match \u2190 getConstInfo oldName with\n  | ConstantInfo.defnInfo info =>\n    addAndCompile $  Declaration.defnDecl { info with name := newName }\n  | ConstantInfo.thmInfo info =>\n    addAndCompile $  Declaration.thmDecl { info with name := newName }\n  | x => throwError \"Constant {oldName} is not a definition or theorem.\"\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/RestateAxiom.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.06187599048099379, "lm_q1q2_score": 0.015891733854308795}}
{"text": "/- -----------------------------------------------------------------------\nThe topos of trees.\n----------------------------------------------------------------------- -/\n\nimport ..c1_basic\nimport ..c2_limits\n\nnamespace qp\n\nopen stdaux\n\nuniverse variables \u2113objx \u2113homx\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    : \u2200 (n : \u2115), 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    : \u2200 (n\u2082 n\u2081 : \u2115) (\u03c9n : n\u2081 \u2264 n\u2082)\n      , LaterObj.obj F n\u2082 \u2192 LaterObj.obj F n\u2081\n| n\u2082 0 \u03c9n x := punit.star\n| 0 (nat.succ n\u2081) \u03c9n x := false.rec _ (by cases \u03c9n)\n| (nat.succ n\u2082) (nat.succ n\u2081) \u03c9n x := F^.hom (nat.le_of_succ_le_succ \u03c9n) x\n\n/-! #brief Action of the later endofunctor on objects.\n-/\ntheorem LaterObj.hom.id\n    (F : TreeTopos^.obj)\n    : \u2200 (n : \u2115)\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    : \u2200 (n\u2083 n\u2082 n\u2081 : \u2115) (\u03c9n\u2081\u2082 : n\u2081 \u2264 n\u2082) (\u03c9n\u2082\u2083 : n\u2082 \u2264 n\u2083)\n      , LaterObj.hom F n\u2083 n\u2081 (nat.le_trans \u03c9n\u2081\u2082 \u03c9n\u2082\u2083)\n         = \u03bb x, LaterObj.hom F n\u2082 n\u2081 \u03c9n\u2081\u2082 (LaterObj.hom F n\u2083 n\u2082 \u03c9n\u2082\u2083 x)\n| 0 0 0 \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := rfl\n| 0 0 (nat.succ n\u2081) \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := rfl\n| 0 (nat.succ n\u2082) 0 \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := rfl\n| (nat.succ n\u2083) 0 0 \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := rfl\n| 0 (nat.succ n\u2082) (nat.succ n\u2081) \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := by cases \u03c9n\u2082\u2083\n| (nat.succ n\u2083) 0 (nat.succ n\u2081) \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := by cases \u03c9n\u2081\u2082\n| (nat.succ n\u2083) (nat.succ n\u2082) 0 \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := rfl\n| (nat.succ n\u2083) (nat.succ n\u2082) (nat.succ n\u2081) \u03c9n\u2081\u2082 \u03c9n\u2082\u2083 := 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\u2081 F\u2082 : TreeTopos^.obj}\n    (\u03b7 : TreeTopos^.hom F\u2081 F\u2082)\n    : \u2200 (n : \u2115)\n      , LaterObj.obj F\u2081 n \u2192 LaterObj.obj F\u2082 n\n| 0 := id\n| (nat.succ n) := \u03b7^.com n\n\n/-! #brief Action of the later endofunctor on homs.\n-/\ntheorem LaterHom.natural\n    {F\u2081 F\u2082 : TreeTopos^.obj}\n    (\u03b7 : TreeTopos^.hom F\u2081 F\u2082)\n    : \u2200 (n\u2082 n\u2081 : \u2115) (\u03c9n : n\u2081 \u2264 n\u2082)\n      , (\u03bb x, LaterHom.com \u03b7 n\u2081 (LaterObj.hom F\u2081 n\u2082 n\u2081 \u03c9n x))\n         = \u03bb x, LaterObj.hom F\u2082 n\u2082 n\u2081 \u03c9n (LaterHom.com \u03b7 n\u2082 x)\n| 0 0 \u03c9n := rfl\n| 0 (nat.succ n\u2081) \u03c9n := by cases \u03c9n\n| (nat.succ n\u2082) 0 \u03c9n := rfl\n| (nat.succ n\u2082) (nat.succ n\u2081) \u03c9n := \u03b7^.natural _\n\n\n/-! #brief Action of the later endofunctor on homs.\n-/\ndefinition LaterHom\n    (F\u2081 F\u2082 : TreeTopos^.obj)\n    (\u03b7 : TreeTopos^.hom F\u2081 F\u2082)\n    : TreeTopos^.hom (LaterObj F\u2081) (LaterObj F\u2082)\n:= { com := LaterHom.com \u03b7\n   , natural := LaterHom.natural \u03b7\n   }\n\n/-! #brief The later endofunctor.\n-/\ndefinition LaterFun : Fun TreeTopos TreeTopos\n:= { obj := LaterObj\n   , hom := LaterHom\n   , hom_id\n      := \u03bb F\n         , begin\n             apply NatTrans.eq,\n             apply funext, intro n, cases n,\n             { trivial },\n             { trivial }\n           end\n   , hom_circ\n      := \u03bb F\u2081 F\u2082 F\u2083 \u03b7\u2082\u2083 \u03b7\u2081\u2082\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 := \u03bb F, { obj := \u03bb n, F^.obj (nat.succ n)\n                 , hom := \u03bb n\u2082 n\u2081 \u03c9n, F^.hom (nat.succ_le_succ \u03c9n)\n                 , hom_id := \u03bb n, F^.hom_id\n                 , hom_circ := \u03bb n\u2083 n\u2082 n\u2081 \u03c9n\u2081\u2082 \u03c9n\u2082\u2083, F^.hom_circ\n                 }\n   , hom := \u03bb F\u2081 F\u2082 \u03b7, { com := \u03bb n, \u03b7^.com (nat.succ n)\n                      , natural := \u03bb n\u2082 n\u2081 \u03c9n, \u03b7^.natural _\n                      }\n   , hom_id\n      := \u03bb F\n         , begin\n             apply NatTrans.eq,\n             apply funext, intro n,\n             trivial\n           end\n   , hom_circ\n      := \u03bb F\u2081 F\u2082 F\u2083 \u03b7\u2082\u2083 \u03b7\u2081\u2082\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 := \u03bb F, { com := \u03bb n x, x\n                       , natural := \u03bb n\u2082 n\u2081 f, funext (\u03bb x, rfl)\n                       }\n         , natural := \u03bb F\u2081 F\u2082 \u03b7, NatTrans.eq (funext (\u03bb n, funext (\u03bb x, rfl)))\n         }\n   , unit\n      := { com := \u03bb F, { com := \u03bb n x, cast sorry x\n                       , natural := \u03bb n\u2082 n\u2081 f, funext (\u03bb x, sorry)\n                       }\n         , natural := \u03bb F\u2081 F\u2082 \u03b7, NatTrans.eq (funext (\u03bb n, funext (\u03bb x, sorry)))\n         }\n   , id_left := \u03bb F, NatTrans.eq sorry\n   , id_right := \u03bb F, NatTrans.eq sorry\n   }\n\n/-! #brief LaterFun preserves all limits.\n-/\ndefinition LaterFun.PresLimit\n    {X : Cat.{\u2113objx \u2113homx}} (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    : \u2200 (n : \u2115)\n      , X^.obj n \u2192 LaterObj.obj X n\n| 0 := \u03bb 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    : \u2200 (n\u2082 n\u2081 : \u2115) (\u03c9n : n\u2081 \u2264 n\u2082)\n      , Cat.circ LeanCat (NextTrans.com X n\u2081) (X^.hom \u03c9n)\n         = Cat.circ LeanCat (LaterObj.hom X n\u2082 n\u2081 \u03c9n) (NextTrans.com X n\u2082)\n| 0 0 \u03c9n := rfl\n| 0 (nat.succ n\u2081) \u03c9n := by cases \u03c9n\n| (nat.succ n\u2082) 0 \u03c9n := rfl\n| (nat.succ n\u2082) (nat.succ n\u2081) \u03c9n\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\u2082_AddCommGroup_preserves_zero_morphisms {R : Type*} [ring R]\n  : (forget\u2082 (Module R) AddCommGroup).preserves_zero_morphisms := \u27e8\u27e9\n\ninstance Module.forget\u2082_AddCommGroup_faithful {R : Type*} [ring R]\n  : faithful (forget\u2082 (Module R) AddCommGroup) :=\nbegin\n  refine \u27e8_\u27e9,\n  intros X Y f g H,\n  ext x, \n  rw [\u2190 linear_map.to_add_monoid_hom_coe, \u2190 linear_map.to_add_monoid_hom_coe],\n  exact congr_arg2 _ H (refl x)\nend.\n\nnoncomputable\ninstance Module.forget\u2082_AddCommGroup_reflects_exact_sequences {R : Type*} [ring R]\n  : functor.reflects_exact_sequences (forget\u2082 (Module R) AddCommGroup) := \nbegin\n  apply functor.reflects_exact_sequences_of_preserves_zero_morphisms_of_faithful\nend\n\ninstance Module.forget\u2082_AddCommGroup_reflects_mono {R : Type*} [ring R]\n  : functor.reflects_monomorphisms (forget\u2082 (Module R) AddCommGroup) := by apply_instance\n\ninstance Module.forget\u2082_AddCommGroup_preserves_mono {R : Type*} [ring R]\n  : functor.preserves_monomorphisms (forget\u2082 (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 \u2192+ G) := {\n    smul := \u03bb r f, \u27e8(\u03bb x, f (x * r)), (by simp), (by { intros, simp [add_mul] })\u27e9,\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  (\u03d5 : G \u2192+ H) : (R \u2192+ G) \u2192\u2097[R] (R \u2192+ H) := {\n    to_fun := \u03bb f, \u27e8\u03d5.comp f, by simp, by { intros, simp }\u27e9,\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 \u2964 Module R := {\n  obj := \u03bb G, Module.of R (R \u2192+ G),\n  map := \u03bb G H \u03d5, Module.of_hom (coextension.map' R \u03d5)\n}.\n\ndef Module.restriction_coextension_adj_unit (R : Type*) [ring R]\n  (M : Type*) [add_comm_group M] [module R M] : M \u2192\u2097[R] (R \u2192+ M) := {\n    to_fun := \u03bb x, \u27e8(\u03bb r, r \u2022 x), zero_smul R x, (\u03bb r s, add_smul r s x)\u27e9,\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 \u2192+ G) \u2192+ G := {\n    to_fun := \u03bb f, f 1,\n    map_zero' := rfl,\n    map_add' := \u03bb x y, rfl\n  }.\n\ndef Module.restriction_coextension_adj (R : Type*) [ring R]\n  : forget\u2082 (Module R) AddCommGroup \u22a3 Module.coextension R := \n  adjunction.mk_of_unit_counit {\n    unit := {\n      app := \u03bb M, Module.restriction_coextension_adj_unit R M,\n      naturality' := by { intros, ext, symmetry, apply map_smul f }\n    },\n    counit := {\n      app := \u03bb 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\u2082_AddCommGroup_preserves_coproduct {R : Type*} [ring R]\n  {J : Type*} (f : J \u2192 Module R)\n  : limits.preserves_colimit (discrete.functor f) (forget\u2082 (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 {\u03b2 : Type*} {C : Type*} [category C] {D : Type*} [category D]\n  (G : C \u2964 D) {f g : \u03b2 \u2192 C} (\u03b7 : \u03a0 (b : \u03b2), f b \u27f6 g b) [has_coproduct f] [has_coproduct g]\n  [has_coproduct (\u03bb (b : \u03b2), G.obj (f b))]  [has_coproduct (\u03bb (b : \u03b2), G.obj (g b))] \n  : sigma_comparison G f\n  \u226b G.map (colim_map (discrete.nat_trans (\u03bb b', \u03b7 b'.as) : discrete.functor f \u27f6 discrete.functor g))\n  = colim_map (discrete.nat_trans (\u03bb b', G.map (\u03b7 b'.as)) : discrete.functor (\u03bb (b : \u03b2), G.obj (f b)) \u27f6 discrete.functor (\u03bb (b : \u03b2), G.obj (g b)))\n  \u226b sigma_comparison G g :=\nbegin\n  ext,\n  simp [sigma_comparison],\n  rw [\u2190 G.map_comp, \u2190 G.map_comp],\n  refine congr_arg _ _,\n  delta sigma.\u03b9,\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 \u2964 W) [F.reflects_monomorphisms] [F.preserves_monomorphisms]\n  [\u2200 (J : Type v) (f : J \u2192 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 (\u03bb a', f a'.as) : discrete.functor X \u27f6 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 \u2190 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 \u2218 X) (F.obj \u2218 Y) (\u03bb a, F.map (f a)) (\u03bb 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\u2082 (Module.{(max v u) u} R) AddCommGroup.{max v u})\n    _ _ \n    (\u03bb 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!\"<h1>{1}</h1>\"\n\ndef Set (\u03b1 : Type u) := \u03b1 \u2192 Prop\ndef Set.in (s : Set \u03b1) (a : \u03b1) := s a\n\nnotation:50 a \" \u2208 \" s:50 => Set.in s a\n\ndef Set.pred (p : \u03b1 \u2192 Prop) : Set \u03b1 := p\n\nnotation \"{\" a \"|\" p \"}\" => Set.pred (fun a => p)\n\ndef Set.union (s\u2081 s\u2082 : Set \u03b1) : Set \u03b1 :=\n  { a | a \u2208 s\u2081 \u2228 a \u2208 s\u2082 }\n\ninfix:65 \" \u222a \" => Set.union\n\ndef Set.inter (s\u2081 s\u2082 : Set \u03b1) : Set \u03b1 :=\n  { a | a \u2208 s\u2081 \u2227 a \u2208 s\u2082 }\n\ninfix:70 \" \u2229 \" => Set.inter\n\ninstance (s : Set \u03b1) [h : Decidable (s a)] : Decidable (a \u2208 Set.pred s) := h\n\ninstance (s\u2081 s\u2082 : Set \u03b1) [Decidable (a \u2208 s\u2081)] [Decidable (a \u2208 s\u2082)] : Decidable (a \u2208 s\u2081 \u2229 s\u2082) :=\n  inferInstanceAs (Decidable (_ \u2227 _))\n\ninstance (s\u2081 s\u2082 : Set \u03b1) [Decidable (a \u2208 s\u2081)] [Decidable (a \u2208 s\u2082)] : Decidable (a \u2208 s\u2081 \u222a s\u2082) :=\n  inferInstanceAs (Decidable (_ \u2228 _))\n\ndef main : IO Unit :=\n  IO.println \"Hello, world!\"\n\nabbrev \u2115 := Nat\n\ndef a := 1\n\n#check \u2115\n#check evalpoyo\n#check (1,2,3)\n#check 3 * 3 = 9\n#check (\u27e89, \u27e83, rfl\u27e9\u27e9:{m: \u2115 // \u2203r, r * r = m})\n\n\ntheorem test1 {\u03b1} (a b : \u03b1) (as bs : List \u03b1) (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 \u2115) //\u2203m r, ll.length = m \u2227 r * r = m \u2227 m > 0} :=\n  \u27e8[[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  }\u27e9\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: \u2203x, x = 0 := Subtype.existsOfSubtype \u27e80, by rfl\u27e9\nnoncomputable def aaaa: Nat := sorry\n#check Classical.choice\nnoncomputable def indefiniteDescription {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} (h : \u2203 x, p x) : {x // p x} :=\n  Classical.choice <| let \u27e8x, px\u27e9 := h; \u27e8\u27e8x, px\u27e9\u27e9\nnoncomputable def hoge {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} (h : \u2203 x, p x) : Nonempty {x // p x} :=\nlet \u27e8w, prop\u27e9 := h; \u27e8w, prop\u27e9\n--\u3066\u3059\u3068,\u30ab\u30bf\u30ab\u30ca\uff0c\u6f22\u5b57\uff0e\uff11\uff12\uff13\uff42\uff43\uff53\n\nconstant magic (h : \u2203 n : \u2115, n > 0) : \u2115\naxiom magic_extract (n h) : magic \u27e8n, h\u27e9 = n\n\nexample : false :=\nhave h1 : magic \u27e81, sorry\u27e9 = 1 := magic_extract _ _;\nhave h2 : magic \u27e82, sorry\u27e9 = 2 := magic_extract _ _;\nhave proof_irrel : magic \u27e81, sorry\u27e9 = magic \u27e82, sorry\u27e9 := 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 \u2194 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 \u00acp) :\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 {\u03b1} {A : set \u03b1} (D0 D1 : decidable_pred A) :\n  (\u03bb n, (@to_bool (A n) (D0 n))) = (\u03bb n, (@to_bool (A n) (D1 n))) := funext (\u03bb x, by rw bool.to_bool_ext)\n\nlemma decidable_pred.compl {\u03b1} {A : set \u03b1} :\n  decidable_pred A \u2192 decidable_pred A\u1d9c := \u03bb h x, @not.decidable _ (h x)\n\nnoncomputable def chr {\u03b1} (p : set \u03b1)  : \u03b1 \u2192 bool := \u03bb x : \u03b1,\ndecidable.cases_on (classical.dec (p x)) (\u03bb h\u2081, bool.ff) (\u03bb h\u2082, bool.tt)\n\n@[simp] theorem chr_tt_iff {\u03b1} (A : set \u03b1) (x : \u03b1) : chr A x = tt \u2194 A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\n@[simp] theorem chr_tt_iff_r {\u03b1} (A : set \u03b1) (x : \u03b1) : tt = chr A x \u2194 A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\n@[simp] theorem chr_ff_iff {\u03b1} (A : set \u03b1) (x : \u03b1) : chr A x = ff \u2194 \u00acA x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\n@[simp] theorem chr_ff_iff_r {\u03b1} (A : set \u03b1) (x : \u03b1) : ff = chr A x \u2194 \u00acA x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\ntheorem chr_iff {\u03b1} (A : set \u03b1) (x : \u03b1) (b : bool) : chr A x = b \u2194 (A x \u2194 b = tt) :=\nby cases b; simp\n\n@[simp] theorem chr_app_iff {\u03b1} (A : set \u03b1) (x : \u03b1) : chr A x \u2194 A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\ntheorem chr_eq_to_bool {\u03b1} (A : set \u03b1) (x : \u03b1) [decidable (A x)] : chr A x = to_bool (A x) :=\nby simp[chr_iff]\n\ntheorem to_bool_chr_eq {\u03b1} (A : set \u03b1) (x : \u03b1) (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 {\u03b1 \u03b2} {A : set \u03b1} {B : set \u03b2} {x y} : chr A x = chr B y \u2194 (A x \u2194 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[\u2190h, e]), simp[ax,bx],\n    have ax := (chr_tt_iff _ _).mp e,\n    have bx := (chr_tt_iff B y).mp (by simp[\u2190h, 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 {\u03b1} (f : \u03b1 \u2192 bool) : chr {x | f x = tt} = f :=\nby funext a; cases C : f a; simp; exact C\n\ndef rre_pred {\u03b1 \u03b2 \u03c3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03c3]\n  (p : set \u03b1) (f : \u03b2 \u2192. \u03c3) : Prop :=\n(\u03bb a, part.assert (p a) (\u03bb _, part.some ())) partrec_in f\n\ninfix ` re_in `:80 := rre_pred\nprefix `r.e. `:80 := re_pred\n\ndef rre_pred_tot {\u03b1 \u03b2 \u03c3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03c3]\n  (p : set \u03b1) (f : \u03b2 \u2192 \u03c3) : Prop := p re_in \u2191\u1d63f\n\ninfix ` re_in! `:80 := rre_pred_tot\n\ntheorem rre_pred.re {\u03b1 \u03b2 \u03c3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03c3]\n  {A : set \u03b1} {f : \u03b2 \u2192. \u03c3} (hA : A re_in f) (hf : partrec f) : r.e. A :=\nhA.le_part_part hf\n\ntheorem rre_pred.re0 {\u03b1} [primcodable \u03b1]\n  {A : set \u03b1} (hA : A re_in! chr (\u2205 : set \u2115)) : r.e. A :=\nby { have : partrec \u2191\u1d63(chr \u2205 : \u2115 \u2192 bool),\n     { exact ((computable.const ff).of_eq $ \u03bb x,\n       by { symmetry, simp [chr_ff_iff], exact not_false }) },\n     exact hA.re this }\n\ntheorem rre_in_0_iff_re {\u03b1} [primcodable \u03b1] {A : set \u03b1} :\n  A re_in! chr (\u2205 : set \u2115) \u2194 r.e. A :=\n\u27e8rre_pred.re0, partrec.to_rpart\u27e9\n\ndef rcomputable_pred {\u03b1 \u03b2 \u03b3} [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] (A : set \u03b1) (o : \u03b2 \u2192. \u03b3) : Prop := \n\u2203 [D0 : decidable_pred A],\nby exactI (\u03bb x, to_bool (A x)) computable_in o\n\ndef t_reducible {\u03b1 \u03b2} [primcodable \u03b1] [primcodable \u03b2] (A : set \u03b1) (B : set \u03b2) : Prop := \n\u2203 [D0 : decidable_pred A] [D1 : decidable_pred B],\nby exactI (\u03bb x, to_bool (A x)) computable_in! (\u03bb x, to_bool (B x)) \n\ninfix ` \u2264\u209c `:50 := t_reducible\n\n@[reducible] def t_irreducible {\u03b1 \u03b2} [primcodable \u03b1] [primcodable \u03b2] (A : set \u03b1) (B : set \u03b2) : Prop := \u00acA \u2264\u209c B\n\ninfix ` \u2270\u209c ` :50 := t_irreducible\n\n@[reducible] def t_reducible_lt {\u03b1 \u03b2} [primcodable \u03b1] [primcodable \u03b2] (A : set \u03b1) (B : set \u03b2) : Prop :=\nA \u2264\u209c B \u2227 \u00acB \u2264\u209c A\n\ninfix ` <\u209c `:50 := t_reducible_lt\n\ndef t_reducible_equiv {\u03b1 \u03b2} [primcodable \u03b1] [primcodable \u03b2] (A : set \u03b1) (B : set \u03b2) : Prop :=\nA \u2264\u209c B \u2227 B \u2264\u209c A\n\ninfix ` \u2261\u209c `:50 := t_reducible_equiv\n\ndef productive (A : set \u2115) : Prop :=\n\u2203 \u03c6 : \u2115 \u2192. \u2115, partrec \u03c6 \u2227 \u2200 i : \u2115, W\u27e6i\u27e7\u2099\u2070 \u2286 A \u2192 \u2203 z, z \u2208 \u03c6 i \u2227 z \u2208 A \u2227 z \u2209 W\u27e6i\u27e7\u2099\u2070\n\ndef creative (A : set \u2115) : Prop := r.e. A \u2227 productive A\u1d9c\n\ndef immune (A : set \u2115) : Prop := infinite A \u2227 \u2200 e, infinite W\u27e6e\u27e7\u2099\u2070 \u2192 W\u27e6e\u27e7\u2099\u2070 \u2229 A\u1d9c \u2260 \u2205\n\ndef simple (A : set \u2115) : Prop := r.e. A \u2227 immune A\u1d9c \n\nvariables {\u03b1 : Type*} {\u03b2 : Type*} {\u03b3 : Type*} {\u03c3 : Type*} {\u03c4 : Type*} {\u03bc : Type*}\nvariables [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] [primcodable \u03c3] [primcodable \u03c4] [primcodable \u03bc]\n\ntheorem classical_iff {A : set \u03b1} {B : set \u03b2} :\n  A \u2264\u209c B \u2194 chr A computable_in! (chr B) :=\nby simp[t_reducible, to_bool_chr_eq]; exact\n  \u27e8\u03bb \u27e8_, _, h\u27e9, h, \u03bb h, \u27e8classical.dec_pred _, classical.dec_pred _, h\u27e9\u27e9\n\ntheorem t_reducible.of_eq {A B : set \u03b1} {C : set \u03b2} (hA : A \u2264\u209c C) (H : \u2200 n, A n \u2194 B n) : B \u2264\u209c C :=\n(set.ext H : A = B) \u25b8 hA\n\n@[refl] theorem t_reducible.refl (A : set \u03b1) [D : decidable_pred A] : A \u2264\u209c A := \u27e8D, D, nat.rpartrec.refl\u27e9\n\n@[trans] theorem t_reducible.trans {A : set \u03b1} {B : set \u03b2} {C : set \u03b3} :\n  A \u2264\u209c B \u2192 B \u2264\u209c C \u2192 A \u2264\u209c C :=\n\u03bb \u27e8Da, Db, hab\u27e9 \u27e8Db0, Dc, hbc\u27e9,\n\u27e8Da, Dc, by simp only [encode_to_bool_eq Db Db0] at hab; exact nat.rpartrec.trans hab hbc\u27e9\n\n@[refl] theorem t_reducible_equiv.refl\n  (A : set \u03b1) [D : decidable_pred A] :\n  A \u2261\u209c A :=\n\u27e8t_reducible.refl A, t_reducible.refl A\u27e9\n\n@[symm] theorem t_reducible_equiv.symm\n  {A : set \u03b1} {B : set \u03b2} :\n  A \u2261\u209c B \u2192 B \u2261\u209c A :=\nand.swap\n\n@[trans] theorem t_reducible_equiv.trans \n  {A : set \u03b1} {B : set \u03b2} {C : set \u03b3} :\n  A \u2261\u209c B \u2192 B \u2261\u209c C \u2192 A \u2261\u209c C :=\n\u03bb \u27e8ab, ba\u27e9 \u27e8bc, cb\u27e9, \u27e8t_reducible.trans ab bc, t_reducible.trans cb ba\u27e9\n\ntheorem many_one_reducible.to_turing {A : set \u03b1} {B : set \u03b2} [DA : decidable_pred A] [DB : decidable_pred B] :\n  A \u2264\u2080 B \u2192 A \u2264\u209c B := \u03bb h,\n\u27e8DA, DB, by { rcases h with \u27e8f, cf, hf\u27e9,\n exact ((rcomputable.refl.comp (cf.to_rcomp)).of_eq $ \u03bb n, by simp [hf]) }\u27e9\n\ntheorem one_one_reducible.to_turing {A : set \u03b1} {B : set \u03b2} [DA : decidable_pred A] [DB : decidable_pred B] :\n  A \u2264\u2081 B \u2192 A \u2264\u209c B := \u03bb h, h.to_many_one.to_turing\n\ntheorem reducible_compl (A : set \u03b1) [D : decidable_pred A] : A\u1d9c \u2264\u209c A :=\nhave Dc : decidable_pred A\u1d9c, from D.compl,\nhave e0 : \u2200 x, @to_bool (A\u1d9c x) (Dc x) = !to_bool (A x), from \u03bb x, bool.to_bool_ext_bnot _ _ _,\nhave cb : computable bnot, from (primrec.dom_bool _).to_comp,\n\u27e8Dc, D, (cb.to_rpart.comp rcomputable.refl).of_eq $ \u03bb x, by simp[e0]\u27e9\n\ntheorem equiv_compl (A : set \u03b1) [D : decidable_pred A] : A\u1d9c \u2261\u209c A :=\nhave cc : A\u1d9c\u1d9c = A, from compl_compl A,\n\u27e8reducible_compl A, by { \n  suffices : A\u1d9c\u1d9c \u2264\u209c A\u1d9c, rw cc at this, exact this, exact @reducible_compl _ _ A\u1d9c D.compl, }\u27e9 \n\ntheorem computable_le {A : set \u03b1} (B : set \u03b2) [D : decidable_pred B] :\n  computable_pred A \u2192 A \u2264\u209c B :=\n\u03bb \u27e8D0, hA\u27e9, \u27e8D0, D, nat.rpartrec.of_partrec _ hA\u27e9\n\ntheorem le_computable_computable {A : set \u03b1} {B : set \u03b2} :\n  B \u2264\u209c A \u2192 computable_pred A \u2192 computable_pred B := \u03bb \u27e8Db, Da, h\u27e9 \u27e8Da0, hA\u27e9,\n\u27e8Db, by { simp only [computable, partrec, encode_to_bool_eq Da0 Da] at hA,\n          exact rpartrec.le_part_part h hA}\u27e9\n\ntheorem computable_equiv {A : set \u03b1} {B : set \u03b2} :\n  computable_pred A \u2192 computable_pred B \u2192 A \u2261\u209c B :=\n\u03bb \u27e8Da, ca\u27e9 \u27e8Db, cb\u27e9, \u27e8@computable_le _ _ _ _ A B Db \u27e8Da, ca\u27e9, @computable_le _ _ _ _ B A Da \u27e8Db, cb\u27e9\u27e9\n\ntheorem computable_0 : computable_pred (\u2205 : set \u03b1) := \n\u27e8\u03bb x, decidable.false, ((computable.const ff).of_eq $ \u03bb x, rfl)\u27e9\n\ntheorem re_pred_0 : r.e. (\u2205 : set \u03b1) := \npartrec.none.of_eq (\u03bb x, by {rw[show (\u2205 : set \u03b1) x = false, by refl], symmetry, simp[part.eq_none_iff] })\n\ntheorem degree0 (A : set \u03b1) :\n  computable_pred A \u2194 A \u2261\u209c (\u2205 : set \u03b2) := \n\u27e8\u03bb \u27e8D, h\u27e9, \u27e8computable_le _ \u27e8D, h\u27e9, @computable_le _ _ _ _ _ _ D computable_0\u27e9,\n \u03bb \u27e8h, _\u27e9, le_computable_computable h computable_0\u27e9\n\n theorem computable_pred_iff_le {A : set \u03b1} :\n  computable_pred A \u2194 A \u2264\u209c (\u2205 : set \u2115) := \n\u27e8\u03bb \u27e8D, h\u27e9, computable_le _ \u27e8D, h\u27e9,\n \u03bb h, le_computable_computable h computable_0\u27e9\n\ntheorem degree0' (A : set \u03b1) : computable_pred A \u2194 A \u2261\u209c (\u2205 : set \u2115) := degree0 A\n\ndef Join (A : \u2115 \u2192 set \u2115) : set \u2115 := {x | x.unpair.1 \u2208 A x.unpair.2}\n\nprefix `\u2a01`:90 := Join\n\ntheorem Join_one_one_reducible (A : \u2115 \u2192 set \u2115) [D : \u2200 n, decidable_pred (A n)] (n) : A n \u2264\u2081 \u2a01A :=\nbegin\n  let f := (\u03bb m : \u2115, m.mkpair n),\n  have cf : computable f := (primrec\u2082.mkpair.comp primrec.id (primrec.const n)).to_comp,\n  refine \u27e8f, cf, _, _\u27e9,\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 : \u2115 \u2192 set \u2115) [DA : \u2200 n, decidable_pred (A n)] \n  (B : set \u2115) [DB : decidable_pred B] (hA : (\u03bb x y, to_bool (A x y)) computable\u2082_in! \u03bb x, to_bool (B x)) : \u2a01A \u2264\u209c B :=\n\u27e8\u03bb 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) }\u27e9\n\ndef Join\u2082 (A B : set \u2115) := \u2a01(\u03bb n, if n = 0 then A else if n = 1 then B else {})\n\ntheorem le_Join\u2082_left (A B : set \u2115) [DA : decidable_pred A] [DB : decidable_pred B] : A \u2264\u2081 Join\u2082 A B :=\n@Join_one_one_reducible (\u03bb n, if n = 0 then A else if n = 1 then B else {})\n  (\u03bb n a, by { cases n; simp, { exact DA a }, cases n; simp, { exact DB a }, { exact decidable.false } }) 0\n\ntheorem le_Join\u2082_right (A B : set \u2115) [DA : decidable_pred A] [DB : decidable_pred B] : B \u2264\u2081 Join\u2082 A B :=\n@Join_one_one_reducible (\u03bb n, if n = 0 then A else if n = 1 then B else {})\n  (\u03bb n a, by { cases n; simp, { exact DA a }, cases n; simp, { exact DB a }, { exact decidable.false } }) 1\n\ntheorem Join\u2082_le  (A B C : set \u2115) [DA : decidable_pred A] [DB : decidable_pred B] [DC : decidable_pred C]\n  (hA : A \u2264\u209c C) (hB : B \u2264\u209c C) : Join\u2082 A B \u2264\u209c C :=\n@Join_le (\u03bb n, if n = 0 then A else if n = 1 then B else {})\n  (\u03bb 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 \u27e8_, _, cA\u27e9, rcases hB with \u27e8_, _, cB\u27e9,\n    simp,\n    suffices : (\u03bb (x y : \u2115), if x = 0 then (to_bool (A y)) else if x = 1 then to_bool (B y) else ff) computable\u2082_in! \u03bb x, to_bool (C x),\n    exact this.of_eq (\u03bb n m, by { cases n; simp, cases n; simp[has_emptyc.emptyc] }),\n    refine rcomputable.ite (rcomputable.to_bool_eq \u2115 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 \u2115 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 {\u03b1 \u03b2} (p : set \u03b1) (x) (a b : \u03b2) :\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 \u2115) : set \u2115 := {x | (\u27e6x.unpair.1\u27e7\u2099^(chr A) x.unpair.2).dom}\n\nnotation A`\u2032`:1200 := Jump A\n\n@[simp] def Jump_itr : \u2115 \u2192 set \u2115 \u2192 set \u2115\n| 0     A := A\n| (n+1) A := (Jump_itr n A)\u2032\n\ntheorem lt_Jump (A : set \u2115) : A <\u209c A\u2032 := \n\u27e8classical_iff.mpr\n  begin\n    show chr A computable_in! chr A\u2032,\n    have : \u2203 e, \u2200 x, (\u27e6e\u27e7\u2099^(chr A) x).dom \u2194 A x,\n    { have : \u2203 e, \u27e6e\u27e7\u2099^(chr A) = \u03bb a, cond (chr A a) (some 0) none :=\n        exists_index.mp (bool_to_part (chr A)),\n      rcases this with \u27e8e, he\u27e9,\n      refine \u27e8e, \u03bb x, _\u27e9,\n      show (\u27e6e\u27e7\u2099^(chr A) x).dom \u2194 A x,\n      simp [he],\n      cases e : chr A x,\n      simp[(chr_ff_iff _ _).1 e], rintros \u27e8f, _\u27e9, \n      simp[(chr_tt_iff _ _).1 e] },\n    rcases this with \u27e8e, he\u27e9,\n    let f := \u03bb x, chr A\u2032 (e.mkpair x),\n    have lmm_f : f computable_in! chr A\u2032 :=\n        (rcomputable.refl.comp (primrec\u2082.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 [\u2190this], exact lmm_f,\n  end,\n  \u03bb h : A\u2032 \u2264\u209c A,\n  begin\n    have l0 : chr A\u2032 computable_in! chr A := classical_iff.mp h,\n    have : \u2203 e, \u2200 x : \u2115, (\u27e6e\u27e7\u2099^(chr A) x).dom \u2194 (x.mkpair x) \u2209 A\u2032,\n    { let f : \u2115 \u2192. \u2115 := (\u03bb a, cond (chr A\u2032 (a.mkpair a)) none (some 0)),\n      have : f partrec_in! chr A := \n        ((rpartrec.cond (rpartrec.refl_in $ (chr A\u2032 : \u2115 \u2192. bool))\n        partrec.none.to_rpart (rcomputable.const 0)).comp\n          (primrec\u2082.mkpair.comp primrec.id primrec.id).to_rcomp).trans l0,\n      have : \u2203 e, \u27e6e\u27e7\u2099^(chr A) = f := exists_index.mp this,\n      rcases this with \u27e8e, he\u27e9,\n      refine \u27e8e, \u03bb x, _\u27e9,\n      simp[he, set.mem_def, f],\n      cases e : chr A\u2032 (x.mkpair x),\n      simp[(chr_ff_iff _ _).1 e],\n      simp[(chr_tt_iff _ _).1 e], rintros \u27e8_, _\u27e9 },\n    rcases this with \u27e8e, he\u27e9,\n    have : (e.mkpair e) \u2209 A\u2032 \u2194 (e.mkpair e) \u2208 A\u2032,\n    calc\n      (e.mkpair e) \u2209 A\u2032 \u2194 \u00ac(\u27e6e\u27e7\u2099^(chr A) e).dom : by simp[Jump]\n                    ... \u2194 (e.mkpair e) \u2208 A\u2032     : by simp[he],\n    show false, from (not_iff_self _).mp this\n  end\u27e9\n\ntheorem le_le_Jump {A B : set \u2115} : A \u2264\u209c B \u2192 A\u2032 \u2264\u2081 B\u2032 := \u03bb h,\nbegin\n  have h' := classical_iff.mp h,\n  let f := (\u03bb x : \u2115, \u27e6x.unpair.1\u27e7\u2099^(chr A) x.unpair.2),\n  have : \u2203 e, \u27e6e\u27e7\u2099^(chr B) = f,\n  { have := (rpartrec.univ_tot \u2115 \u2115 (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 \u27e8e, lmm_e\u27e9,\n  have iff : \u2200 x, A\u2032 x \u2194 B\u2032 (e.mkpair x),\n  { simp [Jump, lmm_e] },\n  have pi : primrec e.mkpair := primrec\u2082.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 \u27e8e.mkpair, pi.to_comp, inj, iff\u27e9,\nend\n\ntheorem le_compl_of_le {A B : set \u2115} : A \u2264\u2081 B \u2192 A\u1d9c \u2264\u2081 B\u1d9c := \u03bb \u27e8f, comp, inj, h\u27e9,\n\u27e8f, comp, inj, \u03bb x, \u27e8\u03bb h\u2081 h\u2082, h\u2081 ((h x).mpr h\u2082), \u03bb h\u2081 h\u2082, h\u2081 ((h x).mp h\u2082)\u27e9\u27e9\n\ntheorem le1_compl_iff {A B : set \u2115} : A\u1d9c \u2264\u2081 B\u1d9c \u2194 A \u2264\u2081 B :=\n\u27e8\u03bb h, by { have := le_compl_of_le h, simp at this, exact this }, le_compl_of_le\u27e9\n\nopen primrec\n\nlemma rre_pred_iff {p : set \u03b1} {f : \u03b2 \u2192. \u03c3} :\n  p re_in f \u2194 \u2203 q : \u2115 \u2192. \u2115, q partrec_in f \u2227 (\u2200 x, p x \u2194 (q $ encode x).dom) :=\nbegin\n  split; assume h,\n  { let q : \u2115 \u2192. \u2115 := \n      \u03bb n, part.bind (decode \u03b1 n) (\u03bb a, part.assert (p a) (\u03bb (_ : 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 \u27e8q, c, \u03bb x, _\u27e9, \n    simp [q, part.some, part.assert, encodek] },\n  { rcases h with \u27e8q, pq, hq\u27e9,\n    let g : \u03b1 \u2192. unit := (\u03bb x, (q (encode x)).map (\u03bb x, ())),\n    have : g partrec_in f :=\n      (pq.comp computable.encode.to_rpart).map (rcomputable.const ()),\n    exact (this.of_eq $ \u03bb x, by {\n      simp[g], apply part.ext, intros u, simp[hq, dom_iff_mem] }) }\nend\n\nlemma rre_pred_iff' {A : set \u03b1} {f : \u03b2 \u2192. \u03c3} :\n  A re_in f \u2194 \u2203 q : \u03b1 \u2192. \u2115, q partrec_in f \u2227 (\u2200 x, A x \u2194 (q x).dom) :=\nbegin\n  split; assume h,\n  { let q : \u03b1 \u2192. \u2115 := (\u03bb a, part.assert (A a) (\u03bb (_ : A a), some 0)),\n    refine \u27e8q, h, \u03bb x, _\u27e9, \n    simp [q, part.some, part.assert, encodek] },\n  { rcases h with \u27e8q, pq, hq\u27e9,\n    let g : \u03b1 \u2192. unit := (\u03bb x, (q x).map (\u03bb x, ())),\n    have : g partrec_in f :=\n      (pq.comp computable.encode.to_rpart).map (rcomputable.const ()),\n    exact (this.of_eq $ \u03bb 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 \u03b1} {f : \u03b2 \u2192 \u03c3} :\n  A re_in! f \u2194 \u2203 e : \u2115, A = re_set \u03b1 \u2115 \u2191\u2092f e :=\n\u27e8\u03bb h, begin\n    rcases rre_pred_iff'.mp h with \u27e8q, partrec, h\u27e9,\n    rcases exists_index.mp partrec with \u27e8e, rfl\u27e9,\n    refine \u27e8e, set.ext h\u27e9 \n  end,\n  by {rintros \u27e8e, rfl\u27e9, refine rre_pred_iff'.mpr \u27e8\u27e6e\u27e7^f, univ_partrec_in, \u03bb x, by simp[re_set]\u27e9 }\u27e9\n\nlemma rre_pred.rre {f : \u03b1 \u2192. \u03c3} {g : \u03b2 \u2192. \u03c4} {A : set \u03b3} :\n  A re_in f \u2192 f partrec_in g \u2192 A re_in g :=\nby simp [rre_pred_iff]; exact \u03bb q pq h pf, \u27e8q, pq.trans pf, h\u27e9\n\nlemma rre_pred.rre' {A : set \u03b1} {B : set \u03b2} {C : set \u03b3} :\n  A re_in! chr B \u2192 B \u2264\u209c C \u2192 A re_in! chr C :=\nby simp[classical_iff]; exact rre_pred.rre\n\ntheorem t_reducible.rre {A : set \u03b1} {B : set \u03b2} :\n  A \u2264\u209c B \u2192 A re_in! chr B := \u03bb h,\nbegin\n  have : (\u03bb 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 $ \u03bb a,\n    by { apply part.ext, simp, intros u, cases C : chr A a; simp at C \u22a2; exact C })\nend\n\ntheorem t_reducible.compl_rre {A : set \u03b1} {B : set \u03b2} :\n  A \u2264\u209c B \u2192 A\u1d9c re_in! chr B := \u03bb h,\nbegin\n  have : (\u03bb 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 $ \u03bb a, by {\n    apply part.ext, simp, intros u, cases C : chr A a; simp at C \u22a2, exact C,\n    exact not_not.mpr C })\nend\n\ntheorem t_reducible_iff_rre {A : set \u03b1} {B : set \u03b2} :\n  A \u2264\u209c B \u2194 A re_in! chr B \u2227 A\u1d9c re_in! chr B :=\n\u27e8\u03bb h, \u27e8h.rre, h.compl_rre\u27e9, begin\n  rintros \u27e8h\u2081, h\u2082\u27e9, apply classical_iff.mpr,\n  show chr A computable_in! chr B,\n  rcases rre_pred_iff'.mp h\u2081 with \u27e8\u03c7, pA, hA\u27e9,\n  rcases rre_pred_iff'.mp h\u2082 with \u27e8\u03c7c, pAc, hAc\u27e9,\n  rcases exists_index.mp pA with \u27e8e\u2081, rfl\u27e9,\n  rcases exists_index.mp pAc with \u27e8e\u2082, rfl\u27e9,\n  let f\u2080 : \u03b1 \u2192 \u2115 \u2192 option bool :=\n    \u03bb x s, ((\u27e6e\u2081\u27e7^(chr B) [s] x : option \u2115).map (\u03bb _, tt)) <|> ((\u27e6e\u2082\u27e7^(chr B) [s] x : option \u2115).map (\u03bb _, ff)),\n  let f : \u03b1 \u2192. bool := \u03bb x, nat.rfind_opt (f\u2080 x),\n  have total : \u2200 x, (f x).dom,\n  { intros x, simp[f, f\u2080, nat.rfind_opt_dom], by_cases C : A x,\n    { rcases univn_dom_complete.mp ((hA x).mp C) with \u27e8n, h_n\u27e9,\n      refine \u27e8n, or.inr _\u27e9,\n      rw \u2190option.some_get h_n, simp only [option.map, option.bind, option.some_orelse] },\n    { rcases univn_dom_complete.mp ((hAc x).mp C) with \u27e8n, h_n\u27e9, refine \u27e8n, _\u27e9,\n      rw \u2190option.some_get h_n,\n      cases \u27e6e\u2081\u27e7^(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' : \u03b1 \u2192 bool := \u03bb x, (f x).get (total x),\n  have : chr A = f',\n  { sorry },\n  have mono : \u2200 {x : \u03b1} {a} {m n : \u2115}, m \u2264 n \u2192 a \u2208 f\u2080 x m \u2192 a \u2208 f\u2080 x n,\n  { sorry },\n  sorry\n end\u27e9\n\ntheorem rre_Jumpcomputable {A : set \u03b1} {B : set \u2115} : A re_in! chr B \u2192 A \u2264\u209c B\u2032 := \n\u03bb h, classical_iff.mpr \nbegin\n  show chr A computable_in! chr B\u2032,\n  rcases rre_pred_iff.mp h with \u27e8a, pa, ha\u27e9,\n  rcases exists_index.mp pa with \u27e8e, he\u27e9,\n  let f : \u03b1 \u2192 bool := (\u03bb x, chr B\u2032 (e.mkpair (encode x))),\n  have l0 : f computable_in (chr B\u2032 : \u2115 \u2192. bool) :=\n    rcomputable.refl.comp (primrec\u2082.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\u2032, from (l0.of_eq $ by simp[l1])\nend\n\ntheorem rre_iff_one_one_reducible {A B : set \u2115} : A re_in! chr B \u2194 A \u2264\u2081 B\u2032 := \n\u27e8 begin\n    assume h, show A \u2264\u2081 B\u2032,\n    rcases rre_pred_iff.mp h with \u27e8a, pa, ha\u27e9,\n    rcases exists_index.mp pa with \u27e8e, eqn_e\u27e9,\n    have lmm1 : primrec e.mkpair := primrec\u2082.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 : \u2200 n, A n \u2194 B\u2032 (e.mkpair n),\n    { simp[Jump, chr_ext, set.set_of_app_iff, eqn_e, ha], },  \n    refine \u27e8e.mkpair, lmm1.to_comp, lmm2, lmm3\u27e9,\n  end,\n  begin\n    assume h, show A re_in! chr B,\n    rcases h with \u27e8i, ci, inj, hi\u27e9,\n    apply rre_pred_iff.mpr,\n    let q : \u2115 \u2192. \u2115 := (\u03bb x, \u27e6(i x).unpair.1\u27e7\u2099^(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 : \u2200 n, A n \u2194 (q n).dom,\n    { intros x, simp [hi, q, Jump] },\n    refine \u27e8q, lmm, lmm1\u27e9,\n  end\u27e9\n\ntheorem re_many_one_reducible_to_0' {A : set \u2115} : r.e. A \u2194 A \u2264\u2081 \u2205\u2032 :=\n\u27e8\u03bb h, rre_iff_one_one_reducible.mp (h.to_rpart),\n \u03bb h, (rre_iff_one_one_reducible.mpr h).re0 \u27e9\n\ntheorem re_pred_Jump_0 : r.e. \u2205\u2032 :=\nre_many_one_reducible_to_0'.mpr (by refl)\n\nlemma dom_rre (f : \u03b1 \u2192. \u03c3) : {x | (f x).dom} re_in f :=\nbegin\n  let g := (\u03bb a, (f a).map (\u03bb x, ())),\n  have := rpartrec.refl.map ((computable.const ()).comp computable.snd).to_rcomp.to\u2082,\n  exact (this.of_eq $ \u03bb 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 \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {g : \u03b3 \u2192 \u03c4} :\n  {x : \u03b1 \u00d7 \u03b2 | p x.1 x.2} re_in! g \u2192 {x | \u2203 y, p x y} re_in! g := \u03bb h,\nbegin\n  have := rpartrec.exists_index.mp h,\n  rcases this with \u27e8e, eqn_e\u27e9,\n  have eqn_e1 : \u2200 x y, p x y \u2194 (\u27e6e\u27e7^g (x, y) : part unit).dom,\n  { simp [eqn_e, part.assert, part.some] },\n  let p' := (\u03bb x : \u03b1, nat.rfind (\u03bb u, (\u27e6e\u27e7^g [u.unpair.2]\n    (x, (decode \u03b2 u.unpair.1).get_or_else (default \u03b2)) : option unit).is_some)),\n  have lmm : \u2200 x, (\u2203 y, p x y) \u2194 (p' x).dom,\n  { intros x, simp only [p'], split,\n    { rintros \u27e8y, hb\u27e9, rw eqn_e1 at hb,\n      apply rfind_dom_total,\n      simp [part.dom_iff_mem, part.some] at hb \u22a2, rcases hb with \u27e8z, hz\u27e9,\n      rcases univn_complete.mp hz with \u27e8s, hs\u27e9,\n      use (encode y).mkpair s,\n      simp [hs] },\n    { simp, intros u h0 h1, \n      use (decode \u03b2 u.unpair.fst).get_or_else (default \u03b2),\n      cases e : (\u27e6e\u27e7^g [u.unpair.snd] (x, \n        (decode \u03b2 u.unpair.fst).get_or_else (default \u03b2)) : 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 | \u2203 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 \u03b2))))), 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 \u2115} :\n  A re_in! chr B \u2192 A\u1d9c re_in! chr B\u2032 := \u03bb h,\nbegin\n  have lmm\u2081 : A\u1d9c \u2264\u2081 B\u2032\u1d9c,\n  { simp[le1_compl_iff], exact rre_iff_one_one_reducible.mp h },\n  have lmm\u2082 : B\u2032\u1d9c \u2264\u2081 B\u2032\u2032, from rre_iff_one_one_reducible.mp (t_reducible.rre (reducible_compl B\u2032)),\n  exact rre_iff_one_one_reducible.mpr (lmm\u2081.trans lmm\u2082)\nend\n\nlemma rre_pred.rre_of_le {A : set \u03b1} {B : set \u03b2} {C : set \u03b3} :\n  A re_in! chr B \u2192 C \u2264\u2080 A \u2192 C re_in! chr B := \u03bb h \u27e8f, comp, fh\u27e9,\nbegin\n  rcases rre_pred_iff'.mp h with \u27e8q, partrec, qh\u27e9,\n  refine rre_pred_iff'.mpr \u27e8q \u2218 f, partrec.comp comp.to_rcomp, \u03bb x, by simp[fh, qh]\u27e9,\nend\n\ntheorem exists_reducible [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {A : set \u2115} :\n  {x : \u03b1 \u00d7 \u03b2 | p x.1 x.2} \u2264\u209c A \u2192 {x | \u2203 y, p x y} \u2264\u209c A\u2032 :=\n\u03bb h, rre_Jumpcomputable (exists_rre h.rre)\n\ntheorem forall_reducible [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192 Prop} {A : set \u2115} :\n  {x : \u03b1 \u00d7 \u03b2 | p x.1 x.2} \u2264\u209c A \u2192 {x | \u2200 y, p x y} \u2264\u209c A\u2032 := \u03bb h,\nbegin\n  have : {x | \u2200 y, p x y}\u1d9c \u2264\u209c A\u2032,\n  { have : {x | \u2203 y, \u00acp x y} \u2264\u209c A\u2032,\n    { apply exists_reducible, \n      have := (equiv_compl {x : \u03b1 \u00d7 \u03b2 | p x.1 x.2}).1.trans (h.of_eq $ by { intros a, simp }),\n      exact (this.of_eq $ \u03bb a, by refl) },\n    exact (this.of_eq $ \u03bb a, by { simp, exact not_forall.symm }) },\n  apply (equiv_compl {x | \u2200 y, p x y}).2.trans this\nend\n\ndef Kleene (A : set \u2115) : set \u2115 := {x | (\u27e6x\u27e7\u2099^(chr A) x).dom}\n\ndef Tot (A : set \u2115) : set \u2115 := {e | \u2200 x, (\u27e6e\u27e7\u2099^(chr A) x).dom}\n\ndef Unbound (A : set \u2115) : set \u2115 := {e | \u2200 x, \u2203 y, x \u2264 y \u2227 (\u27e6e\u27e7\u2099^(chr A) y).dom}\n\ndef Rec (A : set \u2115) : set \u2115 := {e | W\u27e6e\u27e7\u2099^(chr A) \u2264\u209c A}\n\ntheorem Kleene_equiv_Jump (A : set \u2115) : Kleene A \u2261\u209c A\u2032 :=\n\u27e8classical_iff.mpr \n  begin\n    show chr (Kleene A) computable_in! chr A\u2032,\n    let f := (\u03bb n : \u2115, chr A\u2032 (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\u2082.mkpair.comp primrec.id primrec.id).to_rcomp,\n    exact this\n  end, classical_iff.mpr\n  begin\n    show chr A\u2032 computable_in! chr (Kleene A),\n    let t := (\u03bb x : \u2115 \u00d7 (\u2115 \u00d7 \u2115), \u27e6x.1\u27e7\u2099^(chr A) x.2.1),\n    have : \u2203 e, \u27e6e\u27e7^(chr A) = t,\n    { have : t partrec_in! chr A :=\n        (rpartrec.univ_tot \u2115 \u2115 rcomputable.fst rcomputable.refl (fst.comp snd).to_rcomp),\n      exact exists_index.mp this },\n    rcases this with \u27e8e, eqn_e\u27e9,\n    let k := (\u03bb n m : \u2115, curry (curry e n) m),\n    have eqn_k : \u2200 z i x, \u27e6k i x\u27e7\u2099^(chr A) z = \u27e6i\u27e7\u2099^(chr A) x,\n    { intros z i x, simp [k, eqn_e] },\n    let f := (\u03bb x : \u2115, chr (Kleene A) (k x.unpair.1 x.unpair.2)),\n    have : chr A\u2032 = f,\n    { funext n, apply chr_ext.mpr,\n      simp [Kleene, f, Jump, eqn_k, eqn_e] },\n    rw this,\n    have : primrec\u2082 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\u27e9\n\ntheorem Tot_equiv_Jump2 (A : set \u2115) : Tot A \u2264\u209c A\u2032\u2032 :=\nbegin\n  have : Tot A = {e | \u2200 x, \u2203 s, (\u27e6e\u27e7\u2099^(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 \u2115) : Unbound A \u2264\u209c A\u2032\u2032 :=\nbegin\n  have : Unbound A = {e | \u2200 x, \u2203 y : \u2115 \u00d7 \u2115, x \u2264 y.2 \u2227 (\u27e6e\u27e7\u2099^(chr A) [y.1] y.2).is_some},\n  { simp[Unbound, rpartrec.univn_dom_complete], funext n,\n    simp, refine forall_congr (\u03bb x, _), split,\n    { rintros \u27e8y, eqn, s, h\u27e9, refine \u27e8s, y, eqn, h\u27e9 },\n    { rintros \u27e8s, y, eqn, h\u27e9, refine \u27e8y, eqn, s, h\u27e9 } },\n  rw this,\n  refine forall_reducible (exists_reducible $ classical_iff.mpr _),\n  let f := (\u03bb x : (\u2115 \u00d7 \u2115) \u00d7 \u2115 \u00d7 \u2115, to_bool (x.fst.snd \u2264 x.snd.snd) &&\n    (\u27e6x.fst.fst\u27e7\u2099^(chr A) [x.snd.fst] x.snd.snd).is_some),\n  have : f computable_in! chr A,\n  { refine (primrec.dom_bool\u2082 (&&)).to_rcomp.comp\u2082'\n      (primrec\u2082.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 $ \u03bb x, by symmetry; simp[f, chr_iff])\nend\n\ntheorem Rec_equiv_Jump3 (A : set \u2115) : Rec A \u2264\u209c A\u2032\u2032\u2032 :=\nbegin\n  have : Rec A = {e : \u2115 | \u2203 i, \u2200 x, \u2203 s, (\u27e6i\u27e7\u1d6a^(chr A) [s] x = some tt \u2194 (\u27e6e\u27e7\u2099^(chr A) [s] x).is_some)},\n  { simp[Rec, re_set], ext e, simp, sorry }, sorry\nend\n\nlemma rre_enumeration_iff {A : set \u03b1} {f : \u03b2 \u2192 \u03c3} (h : \u2203 a, a \u2208 A) :\n  A re_in! f \u2192 (\u2203 e : \u2115 \u2192 \u03b1, e computable_in! f \u2227 (\u2200 x, x \u2208 A \u2194 \u2203 n, e n = x)) :=\nbegin\n  rcases h with \u27e8a\u2080, hyp_a\u2080\u27e9,\n  { intros hyp,\n    rcases rre_pred_iff.mp hyp with \u27e8q, hyp_q, hyp_q1\u27e9,\n    let q' := (\u03bb x : \u03b1, 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 \u27e8i, eqn_i\u27e9,\n    let e := (\u03bb n : \u2115, cond (\u27e6i\u27e7^f [n.unpair.1] \n      ((decode \u03b1 n.unpair.2).get_or_else a\u2080) : option \u2115).is_some\n      ((decode \u03b1 n.unpair.2).get_or_else a\u2080) a\u2080),\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 : \u2200 x, x \u2208 A \u2194 \u2203 n, e n = x,\n    { simp [e], intros a, split,\n      { intros hyp_a,\n        have : \u2203 y : \u2115, y \u2208 (\u27e6i\u27e7^f a : part \u2115),\n        { simp [\u2190part.dom_iff_mem, eqn_i, q', \u2190hyp_q1], exact hyp_a },\n        rcases this with \u27e8y, lmm_y\u27e9,\n        have := univn_complete.mp lmm_y, rcases this with \u27e8s, lmm_s\u27e9,\n        refine \u27e8s.mkpair (encode a), _\u27e9, simp, simp[lmm_s] },\n      { rintros \u27e8n, hyp_n\u27e9,\n        cases C : (\u27e6i\u27e7^f [n.unpair.fst] ((decode \u03b1 n.unpair.snd).get_or_else a\u2080) : option \u2115) with v;\n        simp[C] at hyp_n, simp[\u2190hyp_n], exact hyp_a\u2080,\n        suffices : (\u27e6i\u27e7^f a : part \u2115).dom,\n        { simp[eqn_i, q', \u2190hyp_q1] at this, exact this },\n        have := univn_sound C,\n        simp[\u2190hyp_n, this] } },\n    refine \u27e8e, lmm1, lmm2\u27e9 }\nend\n\nlemma re_enumeration_iff {A : set \u03b1} {f : \u03b2 \u2192 \u03c3} (h : \u2203 a, a \u2208 A) :\n  r.e. A \u2192 \u2203 e : \u2115 \u2192 \u03b1, computable e \u2227 (\u2200 x, x \u2208 A \u2194 \u2203 n, e n = x) := \u03bb hyp,\nby { rcases rre_enumeration_iff h (hyp.to_rpart_in \u2191\u1d63(@id \u2115)) with \u27e8e, lmm1, lmm2\u27e9,\n     refine \u27e8e, rcomputable.le_comp_comp lmm1 computable.id, lmm2\u27e9 }\n\nmutual def pie_pred, sigma_pred\nwith pie_pred : \u2115 \u2192 set \u2115 \u2192 Prop\n| 0       A := computable_pred A\n| (n + 1) A := \u2203 B : set \u2115, sigma_pred n B \u2227 A = {x | \u2200 y, (x.mkpair y) \u2208 B}\nwith sigma_pred : \u2115 \u2192 set \u2115 \u2192 Prop\n| 0       A := computable_pred A\n| (n + 1) A := \u2203 B : set \u2115, pie_pred n B \u2227 A = {x | \u2203 y, (x.mkpair y) \u2208 B}\n\nprefix `\ud835\udeb7\u2070`:max := pie_pred\n\nprefix `\ud835\udeba\u2070`:max := sigma_pred\n\ndef delta_pred (n : \u2115) (A : set \u2115) : Prop := \ud835\udeb7\u2070n A \u2227 \ud835\udeba\u2070n A\n\nprefix `\ud835\udeab\u2070`:max := delta_pred\n\n@[simp] lemma pie_pred0_iff {A : set \u2115} : \ud835\udeb7\u20700 A \u2194 computable_pred A := by simp[pie_pred]\n\n@[simp] lemma sigma_pred0_iff {A : set \u2115} : \ud835\udeba\u20700 A \u2194 computable_pred A := by simp[sigma_pred]\n\nlemma pie_pred2_iff {A : set \u2115} {n : \u2115} :\n  \ud835\udeb7\u2070(n + 2) A \u2194 \u2203 B : set \u2115, \ud835\udeb7\u2070n B \u2227 A = {x | \u2200 y, \u2203 z, (x.mkpair y).mkpair z \u2208 B} :=\nby { simp[sigma_pred, pie_pred], split,\n     { rintros \u27e8B\u2081, \u27e8B\u2082, sigma, rfl\u27e9, rfl\u27e9, refine \u27e8B\u2082, sigma, by refl\u27e9 },\n     { rintros \u27e8B\u2081, sigma, rfl\u27e9, refine \u27e8_, \u27e8B\u2081, sigma, rfl\u27e9, by refl\u27e9 } }\n\nlemma sigma_pred2_iff {A : set \u2115} {n : \u2115} :\n  \ud835\udeba\u2070(n + 2) A \u2194 \u2203 B : set \u2115, \ud835\udeba\u2070n B \u2227 A = {x | \u2203 y, \u2200 z, (x.mkpair y).mkpair z \u2208 B} :=\nby { simp[sigma_pred, pie_pred], split,\n     { rintros \u27e8B\u2081, \u27e8B\u2082, sigma, rfl\u27e9, rfl\u27e9, refine \u27e8B\u2082, sigma, by refl\u27e9 },\n     { rintros \u27e8B\u2081, sigma, rfl\u27e9, refine \u27e8_, \u27e8B\u2081, sigma, rfl\u27e9, by refl\u27e9 } }\n\nlemma arith_hie_compl : \u2200 {n : \u2115} {A : set \u2115},\n  \ud835\udeb7\u2070n A \u2194 \ud835\udeba\u2070n A\u1d9c\n| 0       A := by { simp[degree0'], exactI \u27e8\u03bb h, (equiv_compl A).trans h, \u03bb h, (equiv_compl A).symm.trans h\u27e9 }\n| (n + 1) A := by { simp[sigma_pred, pie_pred], split,\n    { rintros \u27e8B, sigma, rfl\u27e9,\n      refine \u27e8B\u1d9c, (@arith_hie_compl n B\u1d9c).mpr (by simp[sigma]), by simp[set.compl_set_of]\u27e9 },\n    { rintros \u27e8B, pie, eqn\u27e9,\n      refine \u27e8B\u1d9c, (@arith_hie_compl n B).mp pie, \n        by rw \u2190(compl_compl A); rw eqn; simp[set.compl_set_of]\u27e9 } }\n\nlemma pie_pred.many_one : \u2200 {n : \u2115} {A B : set \u2115} (pie : \ud835\udeb7\u2070n B) (le : A \u2264\u2080 B), \ud835\udeb7\u2070n A\n| 0       A B pie le := by { simp at*, exact le_computable_computable le.to_turing pie }\n| 1       A B pie \u27e8f, f_comp, le\u27e9 := by { simp[pie_pred] at pie,\n    rcases pie with \u27e8B', sigma, rfl\u27e9,\n    let C : set \u2115 := {x | (f x.unpair.1).mkpair x.unpair.2 \u2208 B'},\n    have : C \u2264\u2080 B',\n    { refine \u27e8\u03bb x, (f x.unpair.1).mkpair x.unpair.2, _, \u03bb x, by simp[C]; refl\u27e9,\n      refine primrec\u2082.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 | \u2200 y, x.mkpair y \u2208 C}, { simp[C], exact set.ext le },\n    simp [pie_pred], refine \u27e8C, sigma', this\u27e9 }\n| (n + 2) A B pie \u27e8f, f_comp, le\u27e9 := by {\n    rcases pie_pred2_iff.mp pie with \u27e8B', pie', rfl\u27e9,\n    let C : set \u2115 := {x | ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2 \u2208 B'},\n    have : C \u2264\u2080 B',\n    { refine \u27e8\u03bb x, ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2,\n        _, \u03bb x, by simp[C]; refl\u27e9,\n      refine primrec\u2082.mkpair.to_comp.comp\n        (primrec\u2082.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 : \ud835\udeb7\u2070n C, from pie_pred.many_one pie' this,\n    have : A = {x | \u2200 y, \u2203 z, (x.mkpair y).mkpair z \u2208 C},\n    { simp[C], exact set.ext le },\n    refine pie_pred2_iff.mpr \u27e8C, IH, this\u27e9 }\n\nlemma sigma_pred.many_one : \u2200 {n : \u2115} {A B : set \u2115} (sigma : \ud835\udeba\u2070n B) (le : A \u2264\u2080 B), \ud835\udeba\u2070n A\n| 0       A B sigma le := by { simp at*, exact le_computable_computable le.to_turing sigma }\n| 1       A B sigma \u27e8f, f_comp, le\u27e9 := by { simp[sigma_pred] at sigma,\n    rcases sigma with \u27e8B', pie, rfl\u27e9,\n    let C : set \u2115 := {x | (f x.unpair.1).mkpair x.unpair.2 \u2208 B'},\n    have : C \u2264\u2080 B',\n    { refine \u27e8\u03bb x, (f x.unpair.1).mkpair x.unpair.2, _, \u03bb x, by simp[C]; refl\u27e9,\n      refine primrec\u2082.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 | \u2203 y, x.mkpair y \u2208 C}, { simp[C], exact set.ext le },\n    simp[sigma_pred], refine \u27e8C, pie', this\u27e9 }\n| (n + 2) A B sigma \u27e8f, f_comp, le\u27e9 := by {\n    rcases sigma_pred2_iff.mp sigma with \u27e8B', sigma', rfl\u27e9,\n    let C : set \u2115 := {x | ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2 \u2208 B'},\n    have : C \u2264\u2080 B',\n    { refine \u27e8\u03bb x, ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2,\n        _, \u03bb x, by simp[C]; refl\u27e9,\n      refine primrec\u2082.mkpair.to_comp.comp\n        (primrec\u2082.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 : \ud835\udeba\u2070n C, from sigma_pred.many_one sigma' this,\n    have : A = {x : \u2115 | \u2203 (y : \u2115), \u2200 (z : \u2115), (x.mkpair y).mkpair z \u2208 C},\n    { simp[C], exact set.ext le },\n    refine sigma_pred2_iff.mpr \u27e8C, IH, this\u27e9 }\n\nlemma pie_pred_iff {p : \u2115 \u2192 \u2115 \u2192 Prop} {n : \u2115}\n  (h : \ud835\udeba\u2070n {x | p x.unpair.1 x.unpair.2}) : \ud835\udeb7\u2070(n + 1) {x | \u2200 y, p x y} :=\n  by simp[pie_pred]; refine \u27e8{x : \u2115 | p (nat.unpair x).fst (nat.unpair x).snd}, h, by simp\u27e9\n\nlemma sigma_pred_iff {p : \u2115 \u2192 \u2115 \u2192 Prop} {n : \u2115}\n  (h : \ud835\udeb7\u2070n {x | p x.unpair.1 x.unpair.2}) : \ud835\udeba\u2070(n + 1) {x | \u2203 y, p x y} :=\n  by simp[sigma_pred]; refine \u27e8{x : \u2115 | p (nat.unpair x).fst (nat.unpair x).snd}, h, by simp\u27e9\n\nlemma pie_pred_bforall {p : \u2115 \u2192 \u2115 \u2192 Prop} {n : \u2115} {b : \u2115}\n  (h : \ud835\udeba\u2070n {x | p x.unpair.1 x.unpair.2}) : \ud835\udeba\u2070n {x | \u2200 y < b, p x y} :=\n  by {  }\n\nlemma sigma_pred.exists {n : \u2115} {A : set \u2115} (h : \ud835\udeba\u2070(n + 1) A) :\n  \ud835\udeba\u2070(n + 1) {x | \u2203 y, (x.mkpair y) \u2208 A} :=\nbegin\n  simp[sigma_pred] at h \u22a2,\n  rcases (h) with \u27e8B, pie, rfl\u27e9,\n  simp,\n  let B' : set \u2115 := {x | (x.unpair.1.mkpair x.unpair.2.unpair.1).mkpair x.unpair.2.unpair.2 \u2208 B},\n  have eqn : {x : \u2115 | \u2203 y n, ((x.mkpair y).mkpair n) \u2208 B} = {x | \u2203 y : \u2115, (x.mkpair y) \u2208 B' },\n  { apply set.ext, intros x, simp[B'], split,\n    { rintros \u27e8y, n, mem\u27e9, refine \u27e8y.mkpair n, _\u27e9, simp[mem] },\n    { rintros \u27e8y, mem\u27e9, refine \u27e8y.unpair.1, y.unpair.2, mem\u27e9 } },\n  have le : B' \u2264\u2080 B,\n  { refine \u27e8\u03bb x, (x.unpair.1.mkpair x.unpair.2.unpair.1).mkpair x.unpair.2.unpair.2, _, \u03bb x, by simp[B']; refl\u27e9,\n    refine (primrec\u2082.mkpair.comp\n      (primrec\u2082.mkpair.comp (fst.comp unpair) $ fst.comp $ unpair.comp $ snd.comp unpair)\n      (snd.comp $ unpair.comp $ snd.comp unpair)).to_comp },\n  refine \u27e8B', pie.many_one le, eqn\u27e9\nend\n\nlemma sigma_pred.exists' {n : \u2115} {p : \u2115 \u2192 \u2115 \u2192 Prop} (h : \ud835\udeba\u2070(n + 1) {x | p x.unpair.1 x.unpair.2}) :\n  \ud835\udeba\u2070(n + 1) {x | \u2203 y, p x y} :=\nby have := h.exists; simp at this; exact this\n\nlemma sigma_pred.exists'' [inhabited \u03b1] {n : \u2115} {p : \u2115 \u2192 \u03b1 \u2192 Prop}\n  (h : \ud835\udeba\u2070(n + 1) {x | p x.unpair.1 ((encodable.decode \u03b1 x.unpair.2 ).get_or_else (default \u03b1))}) :\n  \ud835\udeba\u2070(n + 1) {x | \u2203 y, p x y} :=\nby { have := h.exists, simp at this, sorry }\n\nlemma pie_pred.forall {n : \u2115} {A : set \u2115} (h : \ud835\udeb7\u2070(n + 1) A) :\n  \ud835\udeb7\u2070(n + 1) {x | \u2200 y, (x.mkpair y) \u2208 A} :=\nby simp[arith_hie_compl, set.compl_set_of] at h \u22a2; exact h.exists\n\nlemma pie_pred.forall' {n : \u2115} {p : \u2115 \u2192 \u2115 \u2192 Prop} (h : \ud835\udeb7\u2070(n + 1) {x | p x.unpair.1 x.unpair.2}) :\n  \ud835\udeb7\u2070(n + 1) {x | \u2200 y, p x y} :=\nby have := h.forall; simp at this; exact this\n\nlemma sigma_pred1_iff_re {A : set \u2115} : \ud835\udeba\u20701 A \u2194 r.e. A :=\nbegin\n  simp[sigma_pred, \u2190rre_in_0_iff_re], split,\n  { rintros \u27e8B, comp, rfl\u27e9, refine exists_rre (t_reducible.rre _),\n    have : {x : \u2115 \u00d7 \u2115 | x.1.mkpair x.2 \u2208 B} \u2264\u209c B,\n      from classical_iff.mpr (rcomputable.refl.comp (primrec\u2082.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 \u27e8e, rfl\u27e9,\n    let B : set \u2115 := {x | (\u27e6e\u27e7\u2099^(chr \u2205 : \u2115 \u2192 bool) [x.unpair.2] x.unpair.1).is_some},\n    have lmm\u2081 : computable_pred B,\n    { refine computable_pred_iff_le.mpr (classical_iff.mpr _),\n      have : (\u03bb x : \u2115, (\u27e6e\u27e7\u2099^(chr \u2205 : \u2115 \u2192 bool) [x.unpair.2] x.unpair.1).is_some) computable_in! chr (\u2205 : set \u2115),\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 (\u03bb x, by simp[B]) },\n    have lmm\u2082 : W\u27e6e\u27e7\u2099^(chr (\u2205 : set \u2115)) = {x | \u2203 y, x.mkpair y \u2208 B},\n    { refine set.ext (\u03bb x, _), simp[B], exact univn_dom_complete },\n    exact \u27e8B, lmm\u2081, lmm\u2082\u27e9 }\nend\n\nlemma pie_pred1_iff_co_re {A : set \u2115} : \ud835\udeb7\u20701 A \u2194 r.e. A\u1d9c :=\nby simp[arith_hie_compl, sigma_pred1_iff_re]\n\nlemma sigma_Jump_of_pie {n : \u2115} {A : set \u2115} (sigma : \ud835\udeba\u2070 n A) : \ud835\udeba\u2070 (n + 1) A\u2032 :=\nbegin\n  simp[Jump], sorry\nend\n\ntheorem sigma_complete : \u2200 {n : \u2115} {A : set \u2115},\n  \ud835\udeba\u2070(n + 1) A \u2194 A re_in! chr (Jump_itr n \u2205)\n| 0       A := by simp[rre_in_0_iff_re]; exact sigma_pred1_iff_re\n| (n + 1) A := begin\n    have IH_sigma : \u2200 {A}, \ud835\udeba\u2070(n + 1) A \u2194 A re_in! chr (Jump_itr n \u2205), from @sigma_complete n,\n    have IH_pie : \u2200 {A}, \ud835\udeb7\u2070(n + 1) A \u2194 A\u1d9c re_in! chr (Jump_itr n \u2205),\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\u2081 : B re_in! chr (Jump_itr n \u2205)\u2032,\n      { have := rre_compl_of_rre (IH_pie.mp pie), simp at this, exact this },\n      have lmm\u2082 : {x : \u2115 \u00d7 \u2115 | nat.mkpair x.fst x.snd \u2208 B} \u2264\u2080 B,\n        from \u27e8\u03bb x, nat.mkpair x.fst x.snd, (primrec\u2082.mkpair.comp fst snd).to_comp, by simp[set.mem_def]\u27e9,\n      exact rre_pred.rre_of_le lmm\u2081 lmm\u2082 },\n    { intros h, simp at h,\n      have : \ud835\udeba\u2070(n + 1) (Jump_itr n \u2205)\u2032, 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 \u2115} : computable_pred A \u2194 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 \u2115} (hA : r.e. A) (hB : r.e. B) : r.e. Join\u2082 A B :=\nbegin\n  simp[Join\u2082, Join, \u2190sigma_pred1_iff_re, sigma_pred, computable_pred_iff_chr_computable] at *,\n  rcases hA with \u27e8A, hA, rfl\u27e9,\n  rcases hB with \u27e8B, hB, rfl\u27e9,\n  let C : set \u2115 := {n : \u2115 |\n    if (nat.unpair n).1.unpair.2 = 0 then nat.mkpair n.unpair.1.unpair.1 n.unpair.2 \u2208 A else\n    if (nat.unpair n).1.unpair.2 = 1 then nat.mkpair n.unpair.1.unpair.1 n.unpair.2 \u2208 B else false },\n  refine \u27e8C, by { simp[C],\n    suffices :\n      computable\n      (\u03bb 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 (\u03bb n, by { by_cases C\u2081 : (nat.unpair (nat.unpair n).fst).snd = 0; simp[C\u2081, set.mem_def, chr_eq_to_bool],\n      by_cases C\u2082 : (nat.unpair (nat.unpair n).fst).snd = 1; simp[C\u2082] }),\n    refine rcomputable.computable_of_rcomp (rcomputable.ite\n      (rcomputable.to_bool_eq \u2115\n        (rcomputable.snd.comp (rcomputable.nat_unpaired.comp (rcomputable.fst.comp rcomputable.nat_unpaired)))\n        (rcomputable.const 0))\n      (hA.to_rcomp.comp (rcomputable\u2082.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 \u2115\n        (rcomputable.snd.comp (rcomputable.nat_unpaired.comp (rcomputable.fst.comp rcomputable.nat_unpaired)))\n        (rcomputable.const 1)) (hB.to_rcomp.comp\n      (rcomputable\u2082.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 }}\u27e9,\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 utils\n\n/-!\n\nScripts to query\n- The OpenAI Codex model for translations\n- The `LeanAide` server to retrieve `mathlib` theorems similar to a given one.\n\n-/\n\n\n/-- Fetches the OpenAI key from the environment to query OpenAI Codex for translation. -/\nmeta def get_openai_key : io string := do\n  some key \u2190 io.env.get \"OPENAI_API_KEY\" | io.fail \n      \"`OPENAI_API_KEY` environment variable not found.\n        This is required for the statement translation tool.\n        Set it using the bash command `export OPENAI_API_KEY=<key>`,\n        where `<key>` is your personal OpenAI key.\",\n  return key\n\n/-- Fetch the IP address of the `LeanAide` server. -/\nmeta def lean_aide_ip : io string := do\n  -- the permanent IP is `34.100.184.111:5000`\n  -- this should be set as an environment variable \n  some ip \u2190 io.env.get \"LEANAIDE_IP\" | (do io.print_ln \"Defaulting to local IP...\", pure \"localhost:5000\"),\n  return ip\n\n\nsection completion_request\n\n/-! The code in this section is modified from `Lean Chat`. -/\n\n/-- A structure for storing data for querying Codex. -/\nstructure completion_request : Type :=\n  (prompt : string)\n  (model : string := \"code-davinci-002\")\n  (temperature : nat := 6) -- the actual temperature times `10`\n  (n : nat := 7)\n  (max_tokens : int := 150)\n  (stop : list string := [\":=\", \"/-\", \"-/\", \"\\n\\n\"])\n  \ninstance completion_request.from_str : has_coe string completion_request :=\n  { coe := \u03bb s, {prompt := s} }\n\n-- An example completion request\ndef test_completion_request : completion_request := \n{ prompt := \"For every epsilon greater than zero, \",  stop := [\".\"] }\n\n/-- Export a `completion_request` to `json` format. -/\nmeta def completion_request.to_json : completion_request \u2192 json\n | \u27e8prompt, model, temperature, n, max_tokens, stop\u27e9 :=\n    json.object [\n    (\"prompt\", json.of_string prompt), \n    (\"model\", json.of_string model), \n    (\"temperature\", json.of_float $ native.float.div temperature 10), \n    (\"n\", json.of_int n),\n    (\"max_tokens\", json.of_int max_tokens), \n    (\"stop\", json.array $ json.of_string <$> stop)\n    ]\n\n/-- Query OpenAI Codex for completions. -/\nmeta def completion_request.query_codex (request : completion_request) : io json := do\n    api_key \u2190 get_openai_key,\n    out \u2190 io.cmd {cmd := \"curl\", args := [\n      \"--silent\",\n      \"https://api.openai.com/v1/completions\",\n      \"-X\", \"POST\",\n      \"-H\", \"Content-Type: application/json\",\n      \"-H\", \"Authorization: Bearer \" ++ api_key,\n      \"--data\", json.unparse request.to_json\n    ]},\n    some codex_completion \u2190 pure (json.parse out) | io.fail \"failed to parse json\",\n    return codex_completion\n\n/-- Get the list of Codex completions as strings. -/\nmeta def completion_request.get_codex_completions (request : completion_request) : io (list string) := do\n  codex_out \u2190 completion_request.query_codex request,\n  io.of_except $ do\n    choices \u2190 codex_out.lookup_as \"choices\" json.as_array,\n    choices.mmap $ \u03bb choice, choice.lookup_as \"text\" json.as_string\n\nmeta def test_completions : io unit := do\n  s \u2190 test_completion_request.get_codex_completions,\n  io.print s\n\n-- #eval test_completions\n\nend completion_request\n\n\nsection similarity_prompts\n\n/-- Query the `LeanAide` server to get `mathlib` theorems similar to a given statement. -/\nmeta def get_similarity_prompts (s : string) (n : nat := 15) : io (list json) := do\n  let data := json.object [\n    (\"filename\", \"data/prompts.json\"),\n    (\"field\", \"doc_string\"),\n    (\"doc_string\", s),\n    (\"n\", n),\n    (\"model_name\", \"all-mpnet-base-v2\")\n    ],\n  ip \u2190 lean_aide_ip,\n  out \u2190 io.cmd {cmd := \"curl\", args := [\n    \"-X\", \"POST\",\n    \"-H\", \"Content-Type: application/json\",\n    \"--data\", json.unparse data,\n    sformat!\"{ip}/nearest_prompts\"\n  ]},\n  io.of_except $\n    let sim_prompts := except.of_option (json.parse out) \"failed to parse json\" in\n      sim_prompts >>= json.as_array \n\n\nmeta def test_similarity_prompts : io unit := do\n  let stmt := \"Every prime number is either `2` or odd.\",\n  prompts \u2190 get_similarity_prompts stmt 5,\n  io.print prompts\n\nend similarity_prompts", "meta": {"author": "0art0", "repo": "lean3-statement-translation-tool", "sha": "5bf00c4f3d7ddcae938e4d78349395061b866aab", "save_path": "github-repos/lean/0art0-lean3-statement-translation-tool", "path": "github-repos/lean/0art0-lean3-statement-translation-tool/lean3-statement-translation-tool-5bf00c4f3d7ddcae938e4d78349395061b866aab/src/querying.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.05033063188523923, "lm_q1q2_score": 0.01580636237334142}}
{"text": "variable (C : Type) [Inhabited C]\n\nexample : C := arbitrary\n\nvariable {C}\n\nexample : C := arbitrary\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/tests/lean/run/536.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.059210253646496694, "lm_q1q2_score": 0.0157428502518907}}
{"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.tactic init.meta.set_get_option_tactics\n\nnamespace tactic\nmeta constant back_lemmas : Type\n\n/- Create a datastructure containing all lemmas tagged as [intro].\n   Lemmas are indexed using their head-symbol.\n   The head-symbol is computed with respect to the given transparency setting. -/\nmeta constant mk_back_lemmas_core     : transparency \u2192 tactic back_lemmas\n/- (back_lemmas_insert_core m lemmas lemma) adds the given lemma to the set back_lemmas.\n   It infers the type of the lemma, and uses its head-symbol as an index.\n   The head-symbol is computed with respect to the given transparency setting. -/\nmeta constant back_lemmas_insert_core : transparency \u2192 back_lemmas \u2192 expr \u2192 tactic back_lemmas\n/- Return the lemmas that have the same head symbol of the given expression -/\nmeta constant back_lemmas_find        : back_lemmas \u2192 expr \u2192 tactic (list expr)\n\nmeta def mk_back_lemmas : tactic back_lemmas :=\nmk_back_lemmas_core reducible\n\nmeta def back_lemmas_insert : back_lemmas \u2192 expr \u2192 tactic back_lemmas :=\nback_lemmas_insert_core reducible\n\n\n/- (backward_chaining_core t insts max_depth pre_tactic leaf_tactic lemmas): perform backward chaining using\n   the lemmas marked as [intro] and extra_lemmas.\n\n   The search maximum depth is \\c max_depth.\n\n   Before processing each goal, the tactic pre_tactic is invoked. The possible outcomes are:\n      1) it closes the goal\n      2) it does nothing, and backward_chaining_core tries applicable lemmas.\n      3) it fails, and backward_chaining_core backtracks.\n\n   Whenever no lemma is applicable, the leaf_tactic is invoked, to try to close the goal.\n   If insts is tt, then type class resolution is used to discharge goals.\n\n   Remark pre_tactic may also be used to trace the execution of backward_chaining_core -/\nmeta constant backward_chaining_core : transparency \u2192 bool \u2192 nat \u2192 tactic unit \u2192 tactic unit \u2192 back_lemmas \u2192 tactic unit\n\nmeta def back_lemmas_add_extra : transparency \u2192 back_lemmas \u2192 list expr \u2192 tactic back_lemmas\n| m bls []      := return bls\n| m bls (l::ls) := do\n  new_bls \u2190 back_lemmas_insert_core m bls l,\n  back_lemmas_add_extra m new_bls ls\n\nmeta def back_chaining_core (pre_tactic : tactic unit) (leaf_tactic : tactic unit) (extra_lemmas : list expr) : tactic unit :=\ndo intro_lemmas \u2190 mk_back_lemmas_core reducible,\n   new_lemmas   \u2190 back_lemmas_add_extra reducible intro_lemmas extra_lemmas,\n   max \u2190 get_nat_option `back_chaining.max_depth 8,\n   backward_chaining_core reducible tt max pre_tactic leaf_tactic new_lemmas\n\nmeta def back_chaining : tactic unit :=\nback_chaining_core skip assumption []\n\nmeta def back_chaining_using : list expr \u2192 tactic unit :=\nback_chaining_core skip assumption\n\nmeta def back_chaining_using_hs : tactic unit :=\nlocal_context >>= back_chaining_core skip failed\n\nend tactic\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/backward.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961687, "lm_q2_score": 0.04336579459120718, "lm_q1q2_score": 0.01574044800949737}}
{"text": "import lib.tactic\n\nimport tactic.rewrite_search.core.common\n\nopen tactic tactic.interactive\n\nnamespace tactic.rewrite_search.discovery\n\nmeta def assert_acceptable_lemma (r : expr) : tactic unit := do\n  -- FIXME: unfold definitions to see if there is an eq or iff\n  ret \u2190 pure tt, -- is_acceptable_lemma r,\n  if ret then return ()\n  else do\n    pp \u2190 pp r,\n    fail format!\"\\\"{pp}\\\" is not a valid rewrite lemma!\"\n\nmeta def load_attr_list : list name \u2192 tactic (list name)\n| [] := return []\n| (a :: rest) := do\n  names \u2190 attribute.get_instances a,\n  l \u2190 load_attr_list rest,\n  return $ names ++ l\n\nmeta def load_names (l : list name) : tactic (list expr) :=\n  l.mmap mk_const\n\nmeta def rewrite_list_from_rw_rules (rws : list rw_rule) : tactic (list (expr \u00d7 bool)) :=\n  rws.mmap (\u03bb r, do e \u2190 to_expr' r.rule, pure (e, r.symm))\n\nmeta def rewrite_list_from_lemmas (l : list expr) : list (expr \u00d7 bool) :=\n  l.map (\u03bb e, (e, ff)) ++ l.map (\u03bb e, (e, tt))\n\nmeta def rewrite_list_from_lemma (e : expr) : list (expr \u00d7 bool) :=\n  rewrite_list_from_lemmas [e]\n\nmeta def rewrite_list_from_hyps : tactic (list (expr \u00d7 bool)) := do\n  hyps \u2190 local_context,\n  rewrite_list_from_lemmas <$> hyps.mfilter is_acceptable_hyp\n\n-- TODO mk_apps recursively\nmeta def inflate_under_apps (locals : list expr) : expr \u2192 tactic (list expr)\n| e := do\n  rws \u2190 list.map prod.fst <$> mk_apps e locals,\n  rws_extras \u2190 list.join <$> rws.mmap inflate_under_apps,\n  return $ e :: (rws ++ rws_extras)\n\nmeta def inflate_rw (locals : list expr) : expr \u00d7 bool \u2192 tactic (list (expr \u00d7 bool))\n| (e, sy) := do\n  as \u2190 inflate_under_apps locals e,\n  return $ as.map $ \u03bb a, (a, sy)\n\nmeta def is_rewrite_lemma (d : declaration) : option (name \u00d7 expr) :=\n  let t := d.type in if is_acceptable_rewrite t then some (d.to_name, t) else none\n\nmeta def find_all_rewrites : tactic (list (name \u00d7 expr)) := do\n  e \u2190 get_env,\n  return $ e.decl_filter_map is_rewrite_lemma\n\nend tactic.rewrite_search.discovery\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/src/tactic/rewrite_search/discovery/screening.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.03789242948164655, "lm_q1q2_score": 0.01572152525637061}}
{"text": "import tactic.iconfig\n\nsection\n\niconfig_mk my_tac\n\nset_option formatter.hide_full_terms false\n\niconfig_add my_tac [\n  abool  : bool, -- (TODO:) := tt ! iconfig.overload_policy.ignore\u27e9,\n  anum   : nat,\n  aenum  : enat,\n  astr   : string,\n  aident : name,\n]\n\nend\n\nnamespace tactic\nnamespace interactive\n\nmeta def cfgdump (c : iconfig my_tac) : tactic unit := do\n  l \u2190 iconfig.read c,\n  l.bool \"abool\" >>= tactic.trace,\n  return ()\n\nend interactive\nend tactic\n\nexample : tt := begin\n  cfgdump {\n    abool := ff,\n    anum := 113,\n    aenum := inf,\n    astr := \"ello\",\n    aident s.sss4,\n  },\n\n  simp\nend\n\n", "meta": {"author": "khoek", "repo": "libiconfig", "sha": "6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5", "save_path": "github-repos/lean/khoek-libiconfig", "path": "github-repos/lean/khoek-libiconfig/libiconfig-6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5/test/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.047425876711786524, "lm_q1q2_score": 0.015703643948483403}}
{"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.attribute\nimport Mathlib.Lean3Lib.init.meta.constructor_tactic\nimport Mathlib.Lean3Lib.init.meta.relation_tactics\nimport Mathlib.Lean3Lib.init.meta.occurrences\nimport Mathlib.Lean3Lib.init.data.option.basic\n\nuniverses l \n\nnamespace Mathlib\n\ndef simp.default_max_steps : \u2115 :=\n  bit0\n    (bit0\n      (bit0\n        (bit0\n          (bit0\n            (bit0\n              (bit0\n                (bit1\n                  (bit0\n                    (bit1\n                      (bit1\n                        (bit0\n                          (bit1\n                            (bit0\n                              (bit0\n                                (bit1\n                                  (bit0 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 1))))))))))))))))))))))\n\n/-- Prefix the given `attr_name` with `\"simp_attr\"`. -/\n/-- Simp lemmas are used by the \"simplifier\" family of tactics.\n`simp_lemmas` is essentially a pair of tables `rb_map (expr_type \u00d7 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 \u2194 r`.\n- A list of the metavariables that must be filled before the proof can be applied.\n- A priority number\n-/\n/-- Make a new table of simp lemmas -/\n/-- Merge the simp_lemma tables. -/\n/-- Remove the given lemmas from the table. Use the names of the lemmas. -/\n/-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/\n/-- Add 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 `\u03a0 (h\u2081 : _) ... (h\u2099 : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`).\n- Any of the hypotheses `h\u1d62` 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\u1d62`.\n\n -/\n/-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/\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 \u2227 b` to `c \u2227 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 \u2194 c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ...\nlemma imp_congr_right (h : a \u2192 (b \u2194 c)) : (a \u2192 b) \u2194 (a \u2192 c) := ...\nlemma and_congr (h\u2081 : a \u2194 c) (h\u2082 : b \u2194 d) : (a \u2227 b) \u2194 (c \u2227 d) := ...\n```\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-/\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-/\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) -/\n/-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/\nnamespace tactic\n\n\n/- Remark: `transform` should not change the target. -/\n\n/-- Revert a local constant, change its type using `transform`.  -/\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. -/\nstructure dsimp_config where\n  md : transparency\n  max_steps : \u2115\n  canonize_instances : Bool\n  single_pass : Bool\n  fail_if_unchanged : Bool\n  eta : Bool\n  zeta : Bool\n  beta : Bool\n  proj : Bool\n  iota : Bool\n  unfold_reducible : Bool\n  memoize : Bool\n\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.-/\nnamespace tactic\n\n\n/- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/\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\n/-- Tries to unfold `e` if it is a constant or a constant application.\n    Remark: this is not a recursive procedure. -/\nstructure dunfold_config extends dsimp_config where\n\n/- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for\n   performance reasons. -/\n\nstructure delta_config where\n  max_steps : \u2115\n  visit_instances : Bool\n\n/-- Delta reduce the given constant names -/\nstructure unfold_proj_config extends dsimp_config where\n\n/-- If `e` is a projection application, try to unfold it, otherwise fail. -/\nstructure simp_config where\n  max_steps : \u2115\n  contextual : Bool\n  lift_eq : Bool\n  canonize_instances : Bool\n  canonize_proofs : Bool\n  use_axioms : Bool\n  zeta : Bool\n  beta : Bool\n  eta : Bool\n  proj : Bool\n  iota : Bool\n  iota_eqn : Bool\n  constructor_eq : Bool\n  single_pass : Bool\n  fail_if_unchanged : Bool\n  memoize : Bool\n  trace_lemmas : Bool\n\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-/\n/--\n`ext_simplify_core a c s discharger pre post r e`:\n\n- `a : \u03b1` - 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 : \u03b1 \u2192 tactic \u03b1` - tactic for dischaging hypothesis in conditional rewriting rules. The argument '\u03b1' 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 `\u2194`.\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-/\nstructure simp_intros_config extends simp_config where\n  use_hyps : Bool\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/simp_tactic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.03963883952640862, "lm_q1q2_score": 0.015699682484455666}}
{"text": "import model_theory.substructures\nimport model_theory.bundled\n\n\n--OUTPUT 1\ntheorem overflow {L : first_order.language} {F : L.Theory} (h : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin) : \u2203 (M : F.Model), infinite M :=\nbegin\n  let A : \u2115 \u2192 L.Theory,\n  have h1 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h2 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h3 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h4 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h5 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h6 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h7 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h8 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h9 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h10 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h11 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h12 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h13 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h14 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h15 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h16 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h17 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h18 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h19 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h20 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h21 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h22 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h23 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h24 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h25 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h26 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h27 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h28 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h29 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h30 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h31 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h32 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h33 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h34 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h35 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h36 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h37 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h38 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h39 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h40 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h41 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h42 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin, from h,\n  have h43 : \u2200 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 {\u03b1 : Type*} (S : set \u03b1) : \u2200 A B \u2208 \ud835\udcab S, (A \u2229 B) \u2208 \ud835\udcab S :=\nbegin\n  assume (A : set \u03b1) (hA : A \u2208 \ud835\udcab S) (B : set \u03b1) (hB : B \u2208 \ud835\udcab S),\n  have h1 : (A \u2286 S) \u2227 (B \u2286 S), from by {split,apply set.subset_of_mem_powerset,exact hA,apply set.subset_of_mem_powerset,exact hB},\n  have h2 : (A \u2229 B) \u2286 A, from by apply set.inter_subset_left,\n  have h3 : (A \u2229 B) \u2286 S, from by {apply set.subset.trans h2 h1.left},\n  show (A \u2229 B) \u2208  \ud835\udcab 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 : \u211d) : (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 \u2190 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] : \u2203! e : G, \u2200 a : G, e * a = a \u2227 a * e = a :=\nbegin\n  have h1 : \u2200 a b : G, \u2203! x : G, a * x = b, from by {\n    assume a b : G, use a\u207b\u00b9 * b, obviously, },\n  have h2 : \u2200 a b : G, \u2203! y : G, y * a = b, from by {\n    assume a b : G, use b * a\u207b\u00b9, obviously, }, \n\n  have h3 : \u2200 a : G, \u2203! x : G, a * x = a, from \n    assume a : G, h1 a a,\n  have h4 : \u2200 a : G, \u2203! y : G, y * a = a, from\n    assume a : G, h2 a a,\n\n  have h5 : \u2200 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 : \u2200 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 \u2203! e : G, \u2200 a : G, e * a = a \u2227 a * e = a, from by {\n    use (1 : G),\n    have h7 : \u2200 e : G, (\u2200 a : G, e * a = a \u2227 a * e = a) \u2192 e = 1, from by {\n      assume (e : G) (hident : \u2200 a : G, e * a = a \u2227 a * e = a),\n      have h8 : \u2200 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 : \u2200 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 \u27e8by obviously, h7\u27e9,\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 : \u2200 n : \u2115, \u2203 (m : F.Model) [mfin : fintype m], n \u2264 @fintype.card m mfin) : \u2203 (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": "\nimport tactic.monotonicity.basic\nimport category.basic\nimport category.traversable\nimport category.traversable.derive\n\nimport data.dlist\nimport logic.basic\nimport tactic.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 \u2192 list (expr elab) \u2192 list (expr elab) \u2192 mono_function\n | assoc : expr elab \u2192 option (expr elab) \u2192 option (expr elab) \u2192 mono_function\n | assoc_comm : expr elab \u2192 expr elab \u2192 mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function \u2192 tactic format\n | (mono_function.non_assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 mmap pp xs,\n  ys' \u2190 mmap pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 pp xs,\n  ys' \u2190 pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 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 \u2192 expr \u2192 expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr \u2192 expr \u2192 expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn  \u2190 pp ctx.function,\n   l   \u2190 pp ctx.left,\n   r   \u2190 pp ctx.right,\n   rel \u2190 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 \u2190 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 { assumptions := pure asms }\n<|>\nreflexivity\n<|>\napplyc ``id\n<|>\nreturn ()\n\nprivate meta def match_rule_head  (p : expr)\n: list expr \u2192 expr \u2192 expr \u2192 tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) \u2190 return t | failed,\n   v \u2190 mk_meta_var d,\n   match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr \u2192 tactic expr\n| (expr.pi n _ t b) :=\ndo v \u2190 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 \u2192 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 \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 list expr)\n | es (x :: xs) := do\n    es' \u2190 delete_expr x es,\n    match es' with\n     | (some es') := do\n       (c,l,r) \u2190 match_ac' es' xs, return (x::c,l,r)\n     | none := do\n       (c,l,r) \u2190 match_ac' es xs, return (c,l,x::r)\n    end\n | es [] := do\nreturn ([],es,[])\n\nmeta def match_ac (unif : bool) (l : list expr) (r : list expr)\n: tactic (list expr \u00d7 list expr \u00d7 list expr) :=\ndo (s',l',r') \u2190 match_ac' l r,\n   s' \u2190 mmap instantiate_mvars s',\n   l' \u2190 mmap instantiate_mvars l',\n   r' \u2190 mmap instantiate_mvars r',\n   return (s',l',r')\n\nmeta def match_prefix\n: list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 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) \u2190 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 \u00d7 list expr \u00d7 list expr \u00d7 list expr) :=\ndo (pre,l\u2081,r\u2081) \u2190 match_prefix l r,\n   (suf,l\u2082,r\u2082) \u2190 match_prefix (reverse l\u2081) (reverse r\u2081),\n   return (pre,reverse l\u2082,reverse r\u2082,reverse suf)\n\nmeta def check_ac : expr \u2192 tactic (bool \u00d7 bool \u00d7 option (expr \u00d7 expr \u00d7 expr) \u00d7 expr)\n | (expr.app (expr.app f x) y) :=\n   do t \u2190 infer_type x,\n      a \u2190 try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n      c \u2190 try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n      i \u2190 try_core (do\n          v \u2190 mk_meta_var t,\n          l_inst_p \u2190 to_expr ``(is_left_id %%t %%f %%v),\n          r_inst_p \u2190 to_expr ``(is_right_id %%t %%f %%v),\n          l_v \u2190 mk_meta_var l_inst_p,\n          r_v \u2190 mk_meta_var r_inst_p ,\n          l_id \u2190 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 \u2190 mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n          mk_instance r_inst_p >>= unify r_v,\n          v' \u2190 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 \u2192 tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) \u2190 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 \u2192 tactic (list expr) :=\nmap dlist.to_list \u2218 parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) : option (expr \u00d7 expr \u00d7 expr) \u2192 list expr \u2192 option (expr \u00d7 list expr)\n| _ (x::xs) := some (foldl (expr.app \u2218 expr.app op) x xs, [])\n| none []   := none\n| (some (l_id,r_id,x\u2080)) [] := some (x\u2080,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr \u2192 option expr\n| (x::xs) := some $ foldl (expr.app \u2218 expr.app op) x xs\n| []   := none\n\nmeta def same_function_aux\n: list expr \u2192 list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr)\n | xs\u2080 xs\u2081 (expr.app f\u2080 a\u2080) (expr.app f\u2081 a\u2081) :=\n   same_function_aux (a\u2080 :: xs\u2080) (a\u2081 :: xs\u2081) f\u2080 f\u2081\n | xs\u2080 xs\u2081 e\u2080 e\u2081 := is_def_eq e\u2080 e\u2081 >> return (e\u2080,xs\u2080,xs\u2081)\n\nmeta def same_function : expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr \u00d7 expr \u00d7 list expr \u00d7 mono_function) :=\ndo (full_f,ls,rs) \u2190 same_function l r,\n   (a,c,i,f) \u2190 check_ac l,\n   if a\n   then if c\n   then do\n     (s,ls,rs) \u2190 monad.join (match_ac tt\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 fold_assoc f i rs,\n     s' \u2190 fold_assoc1 f s,\n     return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n   else do -- a \u2227 \u00ac c\n     (pre,ls,rs,suff) \u2190 monad.join (match_assoc\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 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 -- \u00ac a\n     (xs\u2080,x\u2080,x\u2081,xs\u2081) \u2190 find_one_difference opt ls rs,\n     return (x\u2080,x\u2081,[],mono_function.non_assoc full_f xs\u2080 xs\u2081)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' \u2190 to_expr l,\n   r' \u2190 to_expr r,\n   parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr \u2192 tactic (expr \u00d7 expr \u00d7 list expr \u00d7 ac_mono_ctx)\n | `(%%e\u2080 \u2192 %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) \u2192 (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080 = %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) = (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080) e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     return (e\u2080, e\u2081, id_rs,\n            { function := f\n            , left := l, right := r\n            , to_rel := expr.app \u2218 expr.app rel\n            , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr)  : option expr \u2192 expr \u2192 expr\n| none e := e\n| (some e\u2080) e\u2081 := f.mk_app [e\u2080,e\u2081]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr \u2192 option expr \u2192 expr\n| e none := e\n| e\u2080 (some e\u2081) := f.mk_app [e\u2080,e\u2081]\n\nmeta def mk_fun_app : mono_function \u2192 expr \u2192 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\u2080,r\u2080) (r\u2081,l\u2081)` gives first how to find rules to prove\n      x+(y\u2080+z) R x+(y\u2081+z);\n      if that fails, helps prove (x+y\u2080)+z R (x+y\u2081)+z -/\n | assoc : expr \u00d7 expr \u2192 expr \u00d7 expr \u2192 mono_law\n   /- `congr r` gives the rule to prove `x = y \u2192 f x = f y` -/\n | congr : expr \u2192 mono_law\n | other : expr \u2192 mono_law\n\nmeta def mono_law.to_tactic_format : mono_law \u2192 tactic format\n | (mono_law.other e) := do e \u2190 pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e \u2190 pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\ndo x\u2080 \u2190 pp x\u2080,\n   x\u2081 \u2190 pp x\u2081,\n   y\u2080 \u2190 pp y\u2080,\n   y\u2081 \u2190 pp y\u2081,\n   return format!\"assoc {x\u2080}; {x\u2081} | {y\u2080}; {y\u2081}\"\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 \u2192 expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs\u2080 xs\u2081 : list expr) (l r : expr) : tactic expr :=\ndo p \u2190 mk_app `eq [fn.mk_app $ xs\u2080 ++ l :: xs\u2081,fn.mk_app $ xs\u2080 ++ r :: xs\u2081],\n   prod.snd <$> solve_aux p\n     (do iterate_exactly (xs\u2081.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\u2080 x\u2081) :=\n    if (x\u2080 <|> x\u2081).is_some\n       then mk_congr_args f x\u2080.to_monad x\u2081.to_monad ctx.left ctx.right\n       else failed\n | (mono_function.assoc_comm f x\u2080) := mk_congr_args f [x\u2080] [] ctx.left ctx.right\n | (mono_function.non_assoc f x\u2080 x\u2081) := mk_congr_args f x\u2080 x\u2081 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 (\u03bb i, bin_op f x (bin_op f i y))\n       , mk_rel ctx (\u03bb i, bin_op f i y))\n       ( mk_rel ctx (\u03bb i, bin_op f (bin_op f x i) y)\n       , mk_rel ctx (\u03bb i, bin_op f x i))\n    | (mono_function.assoc f (some x) none) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb e, mk_fun_app ctx.function e)\n    | (mono_function.assoc f none (some y)) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb 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 (\u03bb 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' \u2190 mk_const r,\n    t  \u2190 infer_type r',\n    match_rule_head pat [] r' t\n\nmeta def find_lemma (pat : expr) : list name \u2192 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\u2080 x\u2081 : expr) : tactic (list expr) :=\ndo x' \u2190 to_expr ``(%%x\u2081 \u2192 %%x\u2080),\n   r\u2080 \u2190 find_lemma x' ls,\n   r\u2081 \u2190 find_lemma x\u2081 ls,\n   return (expr.app <$> r\u2080 <*> r\u2081)\n\nmeta def find_rule (ls : list name) : mono_law \u2192 tactic (list expr)\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\n(match_chaining_rules ls x\u2080 x\u2081)\n<|> (match_chaining_rules ls y\u2080 y\u2081)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\nlemma apply_rel {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x y : \u03b1}\n  (x' y' : \u03b1)\n  (h : R x y)\n  (hx : x = x')\n  (hy : y = y')\n: R x' y' :=\nby { rw [\u2190 hx,\u2190 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 \u2190 pp e,\n   asm \u2190 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 \u2190 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 -/\nmeta def generalize' (h : name) (v : expr) (x : name) : tactic (expr \u00d7 expr) :=\ndo tgt \u2190 target,\n   t \u2190 infer_type v,\n   tgt' \u2190 do {\n     \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize v x >> target),\n     to_expr ``(\u03bb y : %%t, \u03a0 x, y = x \u2192 %%(tgt'.binding_body.lift_vars 0 1))\n     } <|> to_expr ``(\u03bb y : %%t, \u03a0 x, %%v = x \u2192 %%tgt),\n   t \u2190 head_beta (tgt' v) >>= assert h,\n   swap,\n   r \u2190 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 \u2192 tactic unit) : tactic unit :=\nfocus1 $\ndo tgt \u2190 target >>= instantiate_mvars,\n   tactic.change tgt,\n   ctx \u2190 local_context,\n   let vs := tgt.list_meta_vars,\n   vs' \u2190 mmap (\u03bb v,\n             do h \u2190 get_unused_name `h,\n                x \u2190 get_unused_name `x,\n                prod.snd <$> generalize' h v x) vs,\n     tac ctx;\n     vs'.mmap' (try \u2218 tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ \u03bb _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   set_goals [v],\n   target >>= instantiate_mvars >>= tactic.change,\n   tac, done,\n   set_goals $ gs\n\ndef list.minimum_on {\u03b1 \u03b2} [decidable_linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : list \u03b1 \u2192 list \u03b1\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (\u03bb \u27e8k,a\u27e9 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 {\u03b2} (xs : list expr) (tac : expr \u2192 tactic \u03b2) : tactic unit :=\ndo t \u2190 target,\n   xs \u2190 xs.mmap (\u03bb 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 \u2218 prod.fst \u2218 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 \u2190 r.mmap (\u03bb \u27e8l,gs,_\u27e9,\n          do ts \u2190 gs.mmap infer_type,\n             msg \u2190 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) (cfg : mono_cfg := { mono_cfg . }) :\n  tactic unit :=\ndo t \u2190 target >>= instantiate_mvars,\n   ns \u2190 get_monotonicity_lemmas t dir,\n   asms \u2190 local_context,\n   rs \u2190 find_lemma asms t ns,\n   focus1 $ () <$ best_match rs (\u03bb law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 z`\n-/\nmeta def mono (many : parse (tk \"*\")?) (dir : parse side)\n  (hyps : parse $ tk \"with\" *> pexpr_list_or_texpr <|> pure [])\n  (cfg : mono_cfg := { mono_cfg . }) :\n  tactic unit :=\ndo hyps \u2190 hyps.mmap (\u03bb p, to_expr p >>= mk_meta_var),\n   hyps.mmap' (\u03bb pr, do h \u2190 get_unused_name `h, note h none pr),\n   if many.is_some\n     then repeat $ mono_aux dir cfg\n     else mono_aux dir cfg,\n   gs \u2190 get_goals,\n   set_goals $ hyps ++ gs\n\n/--\ntransforms a goal of the form `f x \u227c f y` into `x \u2264 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 $ \u03bb asms,\ndo try `[dunfold has_sub.sub algebra.sub],\n   tgt \u2190 target >>= instantiate_mvars,\n   (l,r,id_rs,g) \u2190 ac_monotonicity_goal cfg tgt\n             <|> fail \"monotonic context not found\",\n   ns \u2190 get_monotonicity_lemmas tgt both,\n   p \u2190 mk_pattern g,\n   rules \u2190 find_rule asms ns p <|> fail \"no applicable rules found\",\n   when (rules = []) (fail \"no applicable rules found\"),\n   err \u2190 format.join <$> mmap side_conditions rules,\n   focus1 $ best_match rules (\u03bb rule, do\n     t\u2080 \u2190 mk_meta_var `(Prop),\n     v\u2080 \u2190 mk_meta_var t\u2080,\n     t\u2081 \u2190 mk_meta_var `(Prop),\n     v\u2081 \u2190 mk_meta_var t\u2081,\n     tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v\u2080 %%v\u2081),\n     solve_mvar v\u2080 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     solve_mvar v\u2081 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     n \u2190 num_goals,\n     iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>\n       tactic.solve_by_elim {assumptions := pure 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 \u2192 tactic unit \u2192 tactic unit \u2192 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 \u2192 tactic unit \u2192 tactic unit :=\nrepeat_until_or_at_most 100000\n\n@[derive _root_.has_reflect]\ninductive rep_arity : Type\n| one | exactly (n : \u2115) | many\n\nmeta def repeat_or_not : rep_arity \u2192 tactic unit \u2192 option (tactic unit) \u2192 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 \u2295 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`ac_mono` reduces the `f x \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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\nand uses `h` to solve the remaining goal. Can be combined with * or\n^k: `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\nand use the one the minimizes the difference between the left-hand\nside and the right-hand side.\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-/\nmeta def ac_mono (rep : parse arity) :\n         parse assert_or_rule? \u2192\n         opt_param mono_cfg { mono_cfg . } \u2192\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 \u2190 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\nattribute [mono] and.imp or.imp\n\nend tactic.interactive\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/monotonicity/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352605, "lm_q2_score": 0.038466196151892916, "lm_q1q2_score": 0.015668567018887018}}
{"text": "/-\nCopyright (c) 2019 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn\n-/\nimport data.option.defs\nimport data.string.defs\nimport tactic.derive_inhabited\n/-!\n# Additional operations on expr and related types\n\nThis file defines basic operations on the types expr, name, declaration, level, environment.\n\nThis file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.\n\n## Tags\n\nexpr, name, declaration, level, environment, meta, metaprogramming, tactic\n-/\n\nopen tactic\n\nattribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind\n\nnamespace binder_info\n\n/-! ### Declarations about `binder_info` -/\n\ninstance : inhabited binder_info := \u27e8 binder_info.default \u27e9\n\n/-- The brackets corresponding to a given binder_info. -/\ndef brackets : binder_info \u2192 string \u00d7 string\n| binder_info.implicit        := (\"{\", \"}\")\n| binder_info.strict_implicit := (\"{{\", \"}}\")\n| binder_info.inst_implicit   := (\"[\", \"]\")\n| _                           := (\"(\", \")\")\n\nend binder_info\n\nnamespace name\n\n/-! ### Declarations about `name` -/\n\n/-- Find the largest prefix `n` of a `name` such that `f n \u2260 none`, then replace this prefix\nwith the value of `f n`. -/\ndef map_prefix (f : name \u2192 option name) : name \u2192 name\n| anonymous := anonymous\n| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')\n| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')\n\n/-- If `nm` is a simple name (having only one string component) starting with `_`, then\n`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/\nmeta def deinternalize_field : name \u2192 name\n| (mk_string s name.anonymous) :=\n  let i := s.mk_iterator in\n  if i.curr = '_' then i.next.next_to_string else s\n| n := n\n\n/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/\nmeta def get_nth_prefix : name \u2192 \u2115 \u2192 name\n| nm 0 := nm\n| nm (n + 1) := get_nth_prefix nm.get_prefix n\n\n/-- Auxiliary definition for `pop_nth_prefix` -/\nprivate meta def pop_nth_prefix_aux : name \u2192 \u2115 \u2192 name \u00d7 \u2115\n| anonymous n := (anonymous, 1)\n| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in\n          if height \u2264 n then (anonymous, height + 1)\n          else (nm.update_prefix pfx, height + 1)\n\n/-- Pops the top `n` prefixes from the given name. -/\nmeta def pop_nth_prefix (nm : name) (n : \u2115) : name :=\nprod.fst $ pop_nth_prefix_aux nm n\n\n/-- Pop the prefix of a name -/\nmeta def pop_prefix (n : name) : name :=\npop_nth_prefix n 1\n\n/-- Auxiliary definition for `from_components` -/\nprivate def from_components_aux : name \u2192 list string \u2192 name\n| n [] := n\n| n (s :: rest) := from_components_aux (name.mk_string s n) rest\n\n/-- Build a name from components. For example `from_components [\"foo\",\"bar\"]` becomes\n  ``` `foo.bar``` -/\ndef from_components : list string \u2192 name :=\nfrom_components_aux name.anonymous\n\n/-- `name`s can contain numeral pieces, which are not legal names\n  when typed/passed directly to the parser. We turn an arbitrary\n  name into a legal identifier name by turning the numbers to strings. -/\nmeta def sanitize_name : name \u2192 name\n| name.anonymous := name.anonymous\n| (name.mk_string s p) := name.mk_string s $ sanitize_name p\n| (name.mk_numeral s p) := name.mk_string sformat!\"n{s}\" $ sanitize_name p\n\n/-- Append a string to the last component of a name. -/\ndef append_suffix : name \u2192 string \u2192 name\n| (mk_string s n) s' := mk_string (s ++ s') n\n| n _ := n\n\n/-- Update the last component of a name. -/\ndef update_last (f : string \u2192 string) : name \u2192 name\n| (mk_string s n) := mk_string (f s) n\n| n := n\n\n/-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`,\n  either as prefix or as suffix (specified by `is_prefix`), separated by `_`.\n  Used by `simps_add_projections`. -/\ndef append_to_last (nm : name) (s : string) (is_prefix : bool) : name :=\nnm.update_last $ \u03bb s', if is_prefix then s ++ \"_\" ++ s' else s' ++ \"_\" ++ s\n\n/-- The first component of a name, turning a number to a string -/\nmeta def head : name \u2192 string\n| (mk_string s anonymous) := s\n| (mk_string s p)         := head p\n| (mk_numeral n p)        := head p\n| anonymous               := \"[anonymous]\"\n\n/-- Tests whether the first component of a name is `\"_private\"` -/\nmeta def is_private (n : name) : bool :=\nn.head = \"_private\"\n\n/-- Returns the number of characters used to print all the string components of a name,\n  including periods between name segments. Ignores numerical parts of a name. -/\nmeta def length : name \u2192 \u2115\n| (mk_string s anonymous) := s.length\n| (mk_string s p)         := s.length + 1 + p.length\n| (mk_numeral n p)        := p.length\n| anonymous               := \"[anonymous]\".length\n\n/-- Checks whether `nm` has a prefix (including itself) such that P is true -/\ndef has_prefix (P : name \u2192 bool) : name \u2192 bool\n| anonymous := ff\n| (mk_string s nm)  := P (mk_string s nm) \u2228 has_prefix nm\n| (mk_numeral s nm) := P (mk_numeral s nm) \u2228 has_prefix nm\n\n/-- Appends `'` to the end of a name. -/\nmeta def add_prime : name \u2192 name\n| (name.mk_string s p) := name.mk_string (s ++ \"'\") p\n| n := (name.mk_string \"x'\" n)\n\n/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.\nFor example, ``last_string `a.b.c.33`` will return `` `c ``. -/\ndef last_string : name \u2192 string\n| anonymous        := \"[anonymous]\"\n| (mk_string s _)  := s\n| (mk_numeral _ n) := last_string n\n\n/-- Like `++`, except that if the right argument starts with `_root_` the namespace will be\nignored.\n```\nappend_namespace `a.b `c.d = `a.b.c.d\nappend_namespace `a.b `_root_.c.d = `c.d\n```\n-/\nmeta def append_namespace (ns : name) : name \u2192 name\n| (mk_string s anonymous) := if s = \"_root_\" then anonymous else mk_string s ns\n| (mk_string s p)         := mk_string s (append_namespace p)\n| (mk_numeral n p)        := mk_numeral n (append_namespace p)\n| anonymous               := ns\n\n/--\nConstructs a (non-simple) name from a string.\n\nExample: ``name.from_string \"foo.bar\" = `foo.bar``\n-/\nmeta def from_string (s : string) : name :=\nfrom_components $ s.split (= '.')\n\n\n/--\nIn surface Lean, we can write anonymous \u03a0 binders (i.e. binders where the\nargument is not named) using the function arrow notation:\n\n```lean\ninductive test : Type\n| intro : unit \u2192 test\n```\n\nAfter elaboration, however, every binder must have a name, so Lean generates\none. In the example, the binder in the type of `intro` is anonymous, so Lean\ngives it the name `\u1fb0`:\n\n```lean\ntest.intro : \u2200 (\u1fb0 : unit), test\n```\n\nWhen there are multiple anonymous binders, they are named `\u1fb0_1`, `\u1fb0_2` etc.\n\nThus, when we want to know whether the user named a binder, we can check whether\nthe name follows this scheme. Note, however, that this is not reliable. When the\nuser writes (for whatever reason)\n\n```lean\ninductive test : Type\n| intro : \u2200 (\u1fb0 : unit), test\n```\n\nwe cannot tell that the binder was, in fact, named.\n\nThe function `name.is_likely_generated_binder_name` checks if\na name is of the form `\u1fb0`, `\u1fb0_1`, etc.\n-/\nlibrary_note \"likely generated binder names\"\n\n/--\nCheck whether a simple name was likely generated by Lean to name an anonymous\nbinder. Such names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_simple_name : string \u2192 bool\n| \"\u1fb0\" := tt\n| n :=\n  match n.get_rest \"\u1fb0_\" with\n  | none := ff\n  | some suffix := suffix.is_nat\n  end\n\n/--\nCheck whether a name was likely generated by Lean to name an anonymous binder.\nSuch names are either `\u1fb0` or `\u1fb0_n` for some natural `n`. See\nnote [likely generated binder names].\n-/\nmeta def is_likely_generated_binder_name (n : name) : bool :=\nmatch n with\n| mk_string s anonymous := is_likely_generated_binder_simple_name s\n| _ := ff\nend\n\nend name\n\nnamespace level\n\n/-! ### Declarations about `level` -/\n\n/-- Tests whether a universe level is non-zero for all assignments of its variables -/\nmeta def nonzero : level \u2192 bool\n| (succ _) := tt\n| (max l\u2081 l\u2082) := l\u2081.nonzero || l\u2082.nonzero\n| (imax _ l\u2082) := l\u2082.nonzero\n| _ := ff\n\n/--\n`l.fold_mvar f` folds a function `f : name \u2192 \u03b1 \u2192 \u03b1`\nover each `n : name` appearing in a `level.mvar n` in `l`.\n-/\nmeta def fold_mvar {\u03b1} : level \u2192 (name \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1 \u2192 \u03b1\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 \u2218 fold_mvar b f\n| (imax a b) f := fold_mvar a f \u2218 fold_mvar b f\n\n/--\n`l.params` is the set of parameters occuring in `l`.\nFor example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`.\n-/\nprotected meta def params (u : level) : name_set :=\nu.fold mk_name_set $ \u03bb v l,\n  match v with\n  | (param nm) := l.insert nm\n  | _ := l\n  end\n\nend level\n\n/-! ### Declarations about `binder` -/\n\n/-- The type of binders containing a name, the binding info and the binding type -/\n@[derive decidable_eq, derive inhabited]\nmeta structure binder :=\n  (name : name)\n  (info : binder_info)\n  (type : expr)\n\nnamespace binder\n/-- Turn a binder into a string. Uses expr.to_string for the type. -/\nprotected meta def to_string (b : binder) : string :=\nlet (l, r) := b.info.brackets in\nl ++ b.name.to_string ++ \" : \" ++ b.type.to_string ++ r\n\nmeta instance : has_to_string binder := \u27e8 binder.to_string \u27e9\nmeta instance : has_to_format binder := \u27e8 \u03bb b, b.to_string \u27e9\nmeta instance : has_to_tactic_format binder :=\n\u27e8 \u03bb b, let (l, r) := b.info.brackets in\n  (\u03bb e, l ++ b.name.to_string ++ \" : \" ++ e ++ r) <$> pp b.type \u27e9\n\nend binder\n\n/-!\n### Converting between expressions and numerals\n\nThere are a number of ways to convert between expressions and numerals, depending on the input and\noutput types and whether you want to infer the necessary type classes.\n\nSee also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.\n-/\n\n\n/--\n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def nat.mk_numeral (type has_zero has_one has_add : expr) : \u2115 \u2192 expr :=\nlet z : expr := `(@has_zero.zero.{0} %%type %%has_zero),\n    o : expr := `(@has_one.one.{0} %%type %%has_one) in\nnat.binary_rec z\n  (\u03bb b n e, if n = 0 then o else\n    if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)\n    else `(@bit0.{0} %%type %%has_add %%e))\n\n/--\n`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.\n`type`: an expression representing the target type. This must live in Type 0.\n`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.\n -/\nmeta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : \u2124 \u2192 expr\n| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add\n| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in\n            `(@has_neg.neg.{0} %%type %%has_neg %%ne)\n\n/--\n`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(nat.to_pexpr 5) : \u2124))` will create a native integer numeral `(5 : \u2124)`.\n-/\nmeta def nat.to_pexpr : \u2115 \u2192 pexpr\n| 0 := ``(0)\n| 1 := ``(1)\n| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))\n\n/--\n`int.to_pexpr n` creates a `pexpr` that will evaluate to `n`.\nThe `pexpr` does not hold any typing information:\n`to_expr ``((%%(int.to_pexpr (-5)) : \u211a))` will create a native `\u211a` numeral `(-5 : \u211a)`.\n-/\nmeta def int.to_pexpr : \u2124 \u2192 pexpr\n| (int.of_nat k) := k.to_pexpr\n| (int.neg_succ_of_nat k) := ``(-%%((k+1).to_pexpr))\n\nnamespace expr\n\n/--\nTurns an expression into a natural number, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.\n-/\nprotected meta def to_nat : expr \u2192 option \u2115\n| `(has_zero.zero) := some 0\n| `(has_one.one) := some 1\n| `(bit0 %%e) := bit0 <$> e.to_nat\n| `(bit1 %%e) := bit1 <$> e.to_nat\n| `(nat.succ %%e) := (+1) <$> e.to_nat\n| `(nat.zero) := some 0\n| _ := none\n\n/--\nTurns an expression into a integer, assuming it is only built up from\n`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.\n-/\nprotected meta def to_int : expr \u2192 option \u2124\n| `(has_neg.neg %%e) := do n \u2190 e.to_nat, some (-n)\n| e                  := coe <$> e.to_nat\n\n/--\nTurns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`.\n-/\nprotected meta def to_list {\u03b1} (f : expr \u2192 option \u03b1) : expr \u2192 option (list \u03b1)\n| `(list.nil)          := some []\n| `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list\n| _                    := none\n\n/--\n`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,\nignoring differences in type and type class arguments.\n-/\nmeta def is_num_eq : expr \u2192 expr \u2192 bool\n| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt\n| `(@has_one.one _ _) `(@has_one.one _ _) := tt\n| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b\n| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b\n| `(-%%a) `(-%%b) := a.is_num_eq b\n| `(%%a/%%a') `(%%b/%%b') :=  a.is_num_eq b\n| _ _ := ff\n\nend expr\n\n/-! ### Declarations about `pexpr` -/\n\nnamespace pexpr\n\n/--\nIf `e` is an annotation of `frozen_name` to `expr.const n`,\n`e.get_frozen_name` returns `n`.\nOtherwise, returns `name.anonymous`.\n-/\nmeta def get_frozen_name (e : pexpr) : name :=\nmatch e.is_annotation with\n| some (`frozen_name, expr.const n _) := n\n| _ := name.anonymous\nend\n\n/--\nIf `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_fn_args` returns `(f, [e\u2081, ... e\u2099])`.\nSee also `expr.get_app_fn_args`.\n-/\nmeta def get_app_fn_args : pexpr \u2192 opt_param (list pexpr) [] \u2192 pexpr \u00d7 list pexpr\n| (expr.app e1 e2) r := get_app_fn_args e1 (e2::r)\n| e1 r := (e1, r)\n\n/--\nIf `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_fn` returns `f`.\nSee also `expr.get_app_fn`.\n-/\nmeta def get_app_fn : pexpr \u2192 list pexpr :=\nprod.snd \u2218 get_app_fn_args\n\n/--\nIf `e : pexpr` is a sequence of applications `f e\u2081 e\u2082 ... e\u2099`,\n`e.get_app_args` returns `[e\u2081, ... e\u2099]`.\nSee also `expr.get_app_args`.\n-/\nmeta def get_app_args : pexpr \u2192 list pexpr :=\nprod.snd \u2218 get_app_fn_args\n\nend pexpr\n\n/-! ### Declarations about `expr` -/\n\nnamespace expr\n\n/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/\nmeta def clean_ids : list name :=\n[``id, ``id_rhs, ``id_delta, ``hidden]\n\n/-- Clean an expression by removing `id`s listed in `clean_ids`. -/\nmeta def clean (e : expr) : expr :=\ne.replace (\u03bb e n,\n     match e with\n     | (app (app (const n _) _) e') :=\n       if n \u2208 clean_ids then some e' else none\n     | (app (lam _ _ _ (var 0)) e') := some e'\n     | _ := none\n     end)\n\n/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/\nmeta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=\ne.replace $ \u03bbc d, if c = s then some (s'.lift_vars 0 d) else none\n\n/-- Implementation of `expr.mreplace`. -/\nmeta def mreplace_aux {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) :\n  expr \u2192 \u2115 \u2192 m expr\n| (app f x) n := option.mget_or_else (R (app f x) n)\n  (do Rf \u2190 mreplace_aux f n, Rx \u2190 mreplace_aux x n, return $ app Rf Rx)\n| (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd)\n| (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n)\n  (do Rty \u2190 mreplace_aux ty n, Rbd \u2190 mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd)\n| (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n)\n  (do Rty \u2190 mreplace_aux ty n,\n    Ra \u2190 mreplace_aux a n,\n    Rb \u2190 mreplace_aux b n,\n    return $ elet nm Rty Ra Rb)\n| (macro c es) n := option.mget_or_else (R (macro c es) n) $\n    macro c <$> es.mmap (\u03bb e, mreplace_aux e n)\n| e n := option.mget_or_else (R e n) (return e)\n\n/--\nMonadic analogue of `expr.replace`.\n\nThe `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where\n`n` is the number of binders above `e`.\nIf `R s n` fails, the whole replacement fails.\nIf `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit\nits subexpressions).\nIf `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.\n\nWARNING: This function performs exponentially worse on large terms than `expr.replace`,\nif a subexpression occurs more than once in an expression, `expr.replace` visits them only once,\nbut this function will visit every occurence of it. Do not use this on large expressions.\n-/\nmeta def mreplace {m : Type* \u2192 Type*} [monad m] (R : expr \u2192 nat \u2192 m (option expr)) (e : expr) :\n  m expr :=\nmreplace_aux R e 0\n\n/-- Match a variable. -/\nmeta def match_var {elab} : expr elab \u2192 option \u2115\n| (var n) := some n\n| _ := none\n\n/-- Match a sort. -/\nmeta def match_sort {elab} : expr elab \u2192 option level\n| (sort u) := some u\n| _ := none\n\n/-- Match a constant. -/\nmeta def match_const {elab} : expr elab \u2192 option (name \u00d7 list level)\n| (const n lvls) := some (n, lvls)\n| _ := none\n\n/-- Match a metavariable. -/\nmeta def match_mvar {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 expr elab)\n| (mvar unique pretty type) := some (unique, pretty, type)\n| _ := none\n\n/-- Match a local constant. -/\nmeta def match_local_const {elab} : expr elab \u2192\n  option (name \u00d7 name \u00d7 binder_info \u00d7 expr elab)\n| (local_const unique pretty bi type) := some (unique, pretty, bi, type)\n| _ := none\n\n/-- Match an application. -/\nmeta def match_app {elab} : expr elab \u2192 option (expr elab \u00d7 expr elab)\n| (app t u) := some (t, u)\n| _ := none\n\n/-- Match an application of `coe_fn`. -/\nmeta def match_app_coe_fn : expr \u2192 option (expr \u00d7 expr \u00d7 expr \u00d7 expr \u00d7 expr)\n| (app `(@coe_fn %%\u03b1 %%\u03b2 %%inst %%fexpr) x) := some (\u03b1, \u03b2, inst, fexpr, x)\n| _ := none\n\n/-- Match an abstraction. -/\nmeta def match_lam {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (lam var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a \u03a0 type. -/\nmeta def match_pi {elab} : expr elab \u2192\n  option (name \u00d7 binder_info \u00d7 expr elab \u00d7 expr elab)\n| (pi var_name bi type body) := some (var_name, bi, type, body)\n| _ := none\n\n/-- Match a let. -/\nmeta def match_elet {elab} : expr elab \u2192\n  option (name \u00d7 expr elab \u00d7 expr elab \u00d7 expr elab)\n| (elet var_name type assignment body) := some (var_name, type, assignment, body)\n| _ := none\n\n/-- Match a macro. -/\nmeta def match_macro {elab} : expr elab \u2192\n  option (macro_def \u00d7 list (expr elab))\n| (macro df args) := some (df, args)\n| _ := none\n\n/-- Tests whether an expression is a meta-variable. -/\nmeta def is_mvar : expr \u2192 bool\n| (mvar _ _ _) := tt\n| _            := ff\n\n/-- Tests whether an expression is a sort. -/\nmeta def is_sort : expr \u2192 bool\n| (sort _) := tt\n| e         := ff\n\n/-- Get the universe levels of a `const` expression -/\nmeta def univ_levels : expr \u2192 list level\n| (const n ls) := ls\n| _            := []\n\n/--\nReplace any metavariables in the expression with underscores, in preparation for printing\n`refine ...` statements.\n-/\nmeta def replace_mvars (e : expr) : expr :=\ne.replace (\u03bb e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)\n\n/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to\n `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/\nmeta def to_implicit_local_const : expr \u2192 expr\n| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t\n| e := e\n\n/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder\ninfo of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.\n-/\nmeta def to_implicit_binder : expr \u2192 expr\n| (local_const n\u2081 n\u2082 _ d) := local_const n\u2081 n\u2082 binder_info.implicit d\n| (lam n _ d b) := lam n binder_info.implicit d b\n| (pi n _ d b) := pi n binder_info.implicit d b\n| e  := e\n\n/-- Returns a list of all local constants in an expression (without duplicates). -/\nmeta def list_local_consts (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_local_constant then insert e' es else es)\n\n/-- Returns the set of all local constants in an expression. -/\nmeta def list_local_consts' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_local_constant then es.insert e' else es)\n\n/-- Returns the unique names of all local constants in an expression. -/\nmeta def list_local_const_unique_names (e : expr) : name_set :=\ne.fold mk_name_set\n  (\u03bb e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es)\n\n/-- Returns a `name_set` of all constants in an expression. -/\nmeta def list_constant (e : expr) : name_set :=\ne.fold mk_name_set (\u03bb e' _ es, if e'.is_constant then es.insert e'.const_name else es)\n\n/-- Returns a `list name` containing the constant names of an `expr` in the same order\n  that `expr.fold` traverses it. -/\nmeta def list_constant' (e : expr) : list name :=\n(e.fold [] (\u03bb e' _ es, if e'.is_constant then es.insert e'.const_name else es)).reverse\n\n/-- Returns a list of all meta-variables in an expression (without duplicates). -/\nmeta def list_meta_vars (e : expr) : list expr :=\ne.fold [] (\u03bb e' _ es, if e'.is_mvar then insert e' es else es)\n\n/-- Returns the set of all meta-variables in an expression. -/\nmeta def list_meta_vars' (e : expr) : expr_set :=\ne.fold mk_expr_set (\u03bb e' _ es, if e'.is_mvar then es.insert e' else es)\n\n/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/\nmeta def list_univ_meta_vars (e : expr) : list name :=\nnative.rb_set.to_list $ e.fold native.mk_rb_set $ \u03bb e' i s,\nmatch e' with\n| (sort u) := u.fold_mvar (flip native.rb_set.insert) s\n| (const _ ls) := ls.foldl (\u03bb s' l, l.fold_mvar (flip native.rb_set.insert) s') s\n| _ := s\nend\n\n/--\nTest `t` contains the specified subexpression `e`, or a metavariable.\nThis represents the notion that `e` \"may occur\" in `t`,\npossibly after subsequent unification.\n-/\nmeta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=\n-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.\n\u00ac t.list_meta_vars.empty \u2228 e.occurs t\n\n/-- Returns a `name_set` of all constants in an expression starting with a certain prefix. -/\nmeta def list_names_with_prefix (pre : name) (e : expr) : name_set :=\ne.fold mk_name_set $ \u03bb e' _ l,\n  match e' with\n  | expr.const n _ := if n.get_prefix = pre then l.insert n else l\n  | _ := l\n  end\n\n/-- Returns true if `e` contains a name `n` where `p n` is true.\n  Returns `true` if `p name.anonymous` is true. -/\nmeta def contains_constant (e : expr) (p : name \u2192 Prop) [decidable_pred p] : bool :=\ne.fold ff (\u03bb e' _ b, if p (e'.const_name) then tt else b)\n\n/--\nReturns true if `e` contains a `sorry`.\nSee also `name.contains_sorry`.\n-/\nmeta def contains_sorry (e : expr) : bool :=\ne.fold ff (\u03bb e' _ b, if (is_sorry e').is_some then tt else b)\n\n/--\n`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.\n-/\nmeta def app_symbol_in (e : expr) (l : list name) : bool :=\nmatch e.get_app_fn with\n| (expr.const n _) := n \u2208 l\n| _ := ff\nend\n\n/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/\nmeta def get_simp_args (e : expr) : tactic (list expr) :=\n-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app\nif \u00ac e.is_app then pure [] else do\ncgr \u2190 mk_specialized_congr_lemma_simp e,\npure $ do\n  (arg_kind, arg) \u2190 cgr.arg_kinds.zip e.get_app_args,\n  guard $ arg_kind = congr_arg_kind.eq,\n  pure arg\n\n/-- Simplifies the expression `t` with the specified options.\n  The result is `(new_e, pr)` with the new expression `new_e` and a proof\n  `pr : e = new_e`. -/\nmeta def simp (t : expr)\n  (cfg : simp_config := {}) (discharger : tactic unit := failed)\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic (expr \u00d7 expr \u00d7 name_set) :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   simplify s to_unfold t cfg `eq discharger\n\n/-- Definitionally simplifies the expression `t` with the specified options.\n  The result is the simplified expression. -/\nmeta def dsimp (t : expr)\n  (cfg : dsimp_config := {})\n  (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :\n  tactic expr :=\ndo (s, to_unfold) \u2190 mk_simp_set no_defaults attr_names hs,\n   s.dsimplify to_unfold t cfg\n\n/-- Get the names of the bound variables by a sequence of pis or lambdas. -/\nmeta def binding_names : expr \u2192 list name\n| (pi n _ _ e)  := n :: e.binding_names\n| (lam n _ _ e) := n :: e.binding_names\n| e             := []\n\n/-- head-reduce a single let expression -/\nmeta def reduce_let : expr \u2192 expr\n| (elet _ _ v b) := b.instantiate_var v\n| e              := e\n\n/-- head-reduce all let expressions -/\nmeta def reduce_lets : expr \u2192 expr\n| (elet _ _ v b) := reduce_lets $ b.instantiate_var v\n| e              := e\n\n/-- Instantiate lambdas in the second argument by expressions from the first. -/\nmeta def instantiate_lambdas : list expr \u2192 expr \u2192 expr\n| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')\n| _        e              := e\n\n/-- Repeatedly apply `expr.subst`. -/\nmeta def substs : expr \u2192 list expr \u2192 expr | e es := es.foldl expr.subst e\n\n/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.\nIf the length of `es` is larger than the number of lambdas in `e`,\nthen the term is applied to the remaining terms.\nAlso reduces head let-expressions in `e`, including those after instantiating all lambdas.\n\nThis is very similar to `expr.substs`, but this also reduces head let-expressions. -/\nmeta def instantiate_lambdas_or_apps : list expr \u2192 expr \u2192 expr\n| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v\n| es      e              := mk_app e es\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/-- Get the codomain/target of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def pi_codomain : expr \u2192 expr\n| (pi n bi d b) := pi_codomain b\n| e             := e\n\n/-- Get the body/value of a lambda-expression.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  See note [open expressions]. -/\nmeta def lambda_body : expr \u2192 expr\n| (lam n bi d b) := lambda_body b\n| e             := e\n\n/-- Auxiliary defintion for `pi_binders`.\n  See note [open expressions]. -/\nmeta def pi_binders_aux : list binder \u2192 expr \u2192 list binder \u00d7 expr\n| es (pi n bi d b) := pi_binders_aux (\u27e8n, bi, d\u27e9::es) b\n| es e             := (es, e)\n\n/-- Get the binders and codomain of a pi-type.\n  This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n  The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the\n  free variables.\n  See note [open expressions]. -/\nmeta def pi_binders (e : expr) : list binder \u00d7 expr :=\nlet (es, e) := pi_binders_aux [] e in (es.reverse, e)\n\n/-- Auxiliary defintion for `get_app_fn_args`. -/\nmeta def get_app_fn_args_aux : list expr \u2192 expr \u2192 expr \u00d7 list expr\n| r (app f a) := get_app_fn_args_aux (a::r) f\n| r e         := (e, r)\n\n/-- A combination of `get_app_fn` and `get_app_args`: lists both the\n  function and its arguments of an application -/\nmeta def get_app_fn_args : expr \u2192 expr \u00d7 list expr :=\nget_app_fn_args_aux []\n\n/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/\nmeta def drop_pis : list expr \u2192 expr \u2192 tactic expr\n| (v :: vs) (pi n bi d b) := do\n  t \u2190 infer_type v,\n  guard (t =\u2090 d),\n  drop_pis vs (b.instantiate_var v)\n| [] e := return e\n| _  _ := failed\n\n/-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`.\n  Does not check whether the result remains type-correct. -/\nmeta def instantiate_pis : list expr \u2192 expr \u2192 expr\n| (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v)\n| _ e := e\n\n/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.\n  Returns `empty` if the list is empty. -/\nmeta def mk_op_lst (op : expr) (empty : expr) : list expr \u2192 expr\n| []        := empty\n| [e]       := e\n| (e :: es) := op e $ mk_op_lst es\n\n/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 \u2227 (x2 \u2227 ...)`, or `true` if the list is empty. -/\nmeta def mk_and_lst : list expr \u2192 expr := mk_op_lst `(and) `(true)\n\n/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 \u2228 (x2 \u2228 ...)`, or `false` if the list is empty. -/\nmeta def mk_or_lst : list expr \u2192 expr := mk_op_lst `(or) `(false)\n\n/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.\nOtherwise returns `binder_info.default`. -/\nmeta def local_binding_info : expr \u2192 binder_info\n| (expr.local_const _ _ bi _) := bi\n| _ := binder_info.default\n\n/-- `is_default_local e` tests whether `e` is a local constant with binder info\n`binder_info.default` -/\nmeta def is_default_local : expr \u2192 bool\n| (expr.local_const _ _ binder_info.default _) := tt\n| _ := ff\n\n/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/\nmeta def has_local_constant (e l : expr) : bool :=\ne.has_local_in $ mk_name_set.insert l.local_uniq_name\n\n/-- Turns a local constant into a binder -/\nmeta def to_binder : expr \u2192 binder\n| (local_const _ nm bi t) := \u27e8nm, bi, t\u27e9\n| _                       := default\n\n/-- Strip-away the context-dependent unique id for the given local const and return: its friendly\n`name`, its `binder_info`, and its `type : expr`. -/\nmeta def get_local_const_kind : expr \u2192 name \u00d7 binder_info \u00d7 expr\n| (expr.local_const _ n bi e) := (n, bi, e)\n| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])\n\n/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/\nmeta def local_const_set_type {elab : bool} : expr elab \u2192 expr elab \u2192 expr elab\n| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t\n| e                           new_t := e\n\n/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to\naccess core `expr` manipulation functions for `pexpr`-based use, but which are restricted to\n`expr tt` at the site of definition unnecessarily.\n\nDANGER: Unless you know exactly what you are doing, this is probably not the function you are\nlooking for. For `pexpr \u2192 expr` see `tactic.to_expr`. For `expr \u2192 pexpr` see `to_pexpr`. -/\nmeta def unsafe_cast {elab\u2081 elab\u2082 : bool} : expr elab\u2081 \u2192 expr elab\u2082 := unchecked_cast\n\n/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr \u00d7 expr)` as\na collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says \"whenever\n`f` is encountered in `e` verbatim, replace it with `t`\". -/\nmeta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr \u00d7 expr)) :\n  expr elab :=\nunsafe_cast $ e.unsafe_cast.replace $ \u03bb e n,\n  (mappings.filter $ \u03bb ent : expr \u00d7 expr, ent.1 = e).head'.map prod.snd\n\n/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of\n    other `expr.local_const`s. It determines whether `e` should be considered \"available in context\"\n    as a variable by virtue of the fact that the variables `vs` have been deemed such.\n\n    For example, given `variables (n : \u2115) [prime n] [ih : even n]`, a reference to `n` implies that\n    the typeclass instance `prime n` should be included, but `ih : even n` should not.\n\n    DANGER: It is possible that for `f : expr` another `expr.local_const`, we have\n    `is_implicitly_included_variable f vs = ff` but\n    `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to\n    iteratively add a list of local constants (usually, the `variables` declared in the local scope)\n    which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables\n    were added in a particular iteration. The function `all_implicitly_included_variables` below\n    implements this behaviour.\n\n    Note that if `e \u2208 vs` then `is_implicitly_included_variable e vs = tt`. -/\nmeta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=\nif \u00ac(e.local_pp_name.to_string.starts_with \"_\") then\n  e \u2208 vs\nelse e.local_type.fold tt $ \u03bb se _ b,\n  if \u00acb then ff\n  else if \u00acse.is_local_constant then tt\n  else se \u2208 vs\n\n/-- Private work function for `all_implicitly_included_variables`, performing the actual series of\n    iterations, tracking with a boolean whether any updates occured this iteration. -/\nprivate meta def all_implicitly_included_variables_aux\n  : list expr \u2192 list expr \u2192 list expr \u2192 bool \u2192 list expr\n| []          vs rs tt := all_implicitly_included_variables_aux rs vs [] ff\n| []          vs rs ff := vs\n| (e :: rest) vs rs b :=\n  let (vs, rs, b) :=\n    if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in\n  all_implicitly_included_variables_aux rest vs rs b\n\n/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,\n    another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion\n    of the variables in `vs` into the local context implies that `e` should also be included. See\n    `is_implicitly_included_variable e vs` for the details.\n\n    In particular, those elements of `vs` are included automatically. -/\nmeta def all_implicitly_included_variables (es vs : list expr) : list expr :=\nall_implicitly_included_variables_aux es vs [] ff\n\n/-- Get the list of explicit arguments of a function. -/\nmeta def list_explicit_args (f : expr) : tactic (list expr) :=\ntactic.fold_explicit_args f [] (\u03bb ll e, return $ ll ++ [e])\n\n/--  `replace_explicit_args f parg` assumes that `f` is an expression corresponding to a function\napplication.  It replaces the explicit arguments of `f`, in succession, by the elements of `parg`.\nThe implicit arguments of `f` remain unchanged. -/\nmeta def replace_explicit_args (f : expr) (parg : list expr) : tactic expr :=\ndo finf \u2190 (get_fun_info f.get_app_fn),\n  let is_ex_arg : list bool := finf.params.map (\u03bb e, \u00ac e.is_implicit \u2227 \u00ac e.is_inst_implicit),\n  let nargs := list.replace_if f.get_app_args is_ex_arg parg,\n  return $ expr.mk_app f.get_app_fn nargs\n\n/-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier.\nThis also works if `x1, ... xn` contain free variables. -/\nprotected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do\n(@const tt n ls, es) \u2190 return e.get_app_fn_args |\n  exceptional.fail \"expression is not a constant applied to arguments\",\nd \u2190 env.get n,\nreturn $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls\n\n/-- Auxilliary function for `head_eta_expand`. -/\nmeta def head_eta_expand_aux : \u2115 \u2192 expr \u2192 expr \u2192 expr\n| (n+1) e (pi x bi d b) :=\n  lam x bi d $ head_eta_expand_aux n e b\n| _ e _ := e\n\n/-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained\n  by its type `t`. -/\nmeta def head_eta_expand (n : \u2115) (e t : expr) : expr :=\n((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t\n\n/-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in\n`dict`. They are expanded until they are applied to one more argument than the maximum in\n`dict.find n`. -/\nprotected meta def eta_expand (env : environment) (dict : name_map $ list \u2115) : expr \u2192 expr\n| e := e.replace $ \u03bb e _, do\n  let (e0, es) := e.get_app_fn_args,\n  let ns := (dict.find e0.const_name).iget,\n  guard (bnot ns.empty),\n  let e' := e0.mk_app $ es.map eta_expand,\n  let needed_n := ns.foldr max 0 + 1,\n  if needed_n \u2264 es.length then some e'\n  else do\n    e'_type \u2190 (e'.simple_infer_type env).to_option,\n    some $ head_eta_expand (needed_n - es.length) e' e'_type\n\n/--\n`e.apply_replacement_fun f test` applies `f` to each identifier\n(inductive type, defined function etc) in an expression, unless\n* The identifier occurs in an application with first argument `arg`; and\n* `test arg` is false.\nHowever, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`\nis tested, instead of the first argument.\n\nReorder contains the information about what arguments to reorder:\ne.g. `g x\u2081 x\u2082 x\u2083 ... x\u2099` becomes `g x\u2082 x\u2081 x\u2083 ... x\u2099` if `reorder.find g = some [1]`.\nWe assume that all functions where we want to reorder arguments are fully applied.\nThis can be done by applying `expr.eta_expand` first.\n-/\nprotected meta def apply_replacement_fun (f : name \u2192 name) (test : expr \u2192 bool)\n  (relevant : name_map \u2115) (reorder : name_map $ list \u2115) : expr \u2192 expr\n| e := e.replace $ \u03bb e _,\n  match e with\n  | const n ls := some $ const (f n) $\n      -- if the first two arguments are reordered, we also reorder the first two universe parameters\n      if 1 \u2208 (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls\n  | app g x :=\n    let f := g.get_app_fn,\n        nm := f.const_name,\n        n_args := g.get_app_num_args in -- this might be inefficient\n    if n_args \u2208 (reorder.find nm).iget \u2227 test g.get_app_args.head then\n    -- interchange `x` and the last argument of `g`\n    some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $\n      apply_replacement_fun g.app_arg else\n    if n_args = (relevant.find nm).lhoare 0 \u2227 f.is_constant \u2227 \u00ac test x then\n      some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else\n      none\n  | _ := none\n  end\n\nend expr\n\n/-! ### Declarations about `environment` -/\n\nnamespace environment\n\n/-- Tests whether `n` is a structure. -/\nmeta def is_structure (env : environment) (n : name) : bool :=\n(env.structure_fields n).is_some\n\n/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a\n  structure. -/\nmeta def structure_fields_full (env : environment) (n : name) : option (list name) :=\n(env.structure_fields n).map (list.map $ \u03bb n', n ++ n')\n\n/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.\n  Note that `is_ginductive` returns `tt` even on regular inductive types.\n  This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive\n  type. -/\nmeta def is_ginductive' (e : environment) (nm : name) : bool :=\ne.is_ginductive nm \u2227 \u00ac e.is_inductive nm\n\n/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list.  -/\nmeta def decl_filter_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 option \u03b1) : list \u03b1 :=\n  e.fold [] $ \u03bb d l, match f d with\n                     | some r := r :: l\n                     | none := l\n                     end\n\n/-- Maps `f` to all declarations in the environment. -/\nmeta def decl_map {\u03b1 : Type} (e : environment) (f : declaration \u2192 \u03b1) : list \u03b1 :=\n  e.decl_filter_map $ \u03bb d, some (f d)\n\n/-- Lists all declarations in the environment -/\nmeta def get_decls (e : environment) : list declaration :=\n  e.decl_map id\n\n/-- Lists all trusted (non-meta) declarations in the environment -/\nmeta def get_trusted_decls (e : environment) : list declaration :=\n  e.decl_filter_map (\u03bb d, if d.is_trusted then some d else none)\n\n/-- Lists the name of all declarations in the environment -/\nmeta def get_decl_names (e : environment) : list name :=\n  e.decl_map declaration.to_name\n\n/-- Fold a monad over all declarations in the environment. -/\nmeta def mfold {\u03b1 : Type} {m : Type \u2192 Type} [monad m] (e : environment) (x : \u03b1)\n  (fn : declaration \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\ne.fold (return x) (\u03bb d t, t >>= fn d)\n\n/-- Filters all declarations in the environment. -/\nmeta def filter (e : environment) (test : declaration \u2192 bool) : list declaration :=\ne.fold [] $ \u03bb d ds, if test d then d::ds else ds\n\n/-- Filters all declarations in the environment. -/\nmeta def mfilter (e : environment) (test : declaration \u2192 tactic bool) : tactic (list declaration) :=\ne.mfold [] $ \u03bb d ds, do b \u2190 test d, return $ if b then d::ds else ds\n\n/-- Checks whether `s` is a prefix of the file where `n` is declared.\n  This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/\nmeta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=\ns.is_prefix_of $ (e.decl_olean n).get_or_else \"\"\n\nend environment\n\n/-!\n### `is_eta_expansion`\n\n In this section we define the tactic `is_eta_expansion` which checks whether an expression\n  is an eta-expansion of a structure. (not to be confused with eta-expanion for `\u03bb`).\n\n-/\n\nnamespace expr\n\n/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have\n  `pr = nm.{univs} args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name \u00d7 expr)) :\n  bool :=\nl.all $ \u03bb\u27e8proj, val\u27e9, val = (const proj univs).mk_app args\n\n/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all\n  elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.\n  Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we\n  want to eta-reduce. -/\nmeta def is_eta_expansion_test : list (name \u00d7 expr) \u2192 option expr\n| []              := none\n| (\u27e8proj, val\u27e9::l) :=\n  match val.get_app_fn with\n  | (const nm univs : expr) :=\n    if nm = proj then\n      let args := val.get_app_args in\n      let e := args.ilast in\n      if is_eta_expansion_of args univs l then some e else none\n    else\n      none\n  | _                       := none\n  end\n\n/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.\n  Here `l` is intended to consists of the projections and the fields of `val`.\n  This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and\n  afterward checks whether the resulting expression `e` unifies with `val`.\n  This last check is necessary, because `val` and `e` might have different types. -/\nmeta def is_eta_expansion_aux (val : expr) (l : list (name \u00d7 expr)) : tactic (option expr) :=\ndo l' \u2190 l.mfilter (\u03bb\u27e8proj, val\u27e9, bnot <$> is_proof val),\n  match is_eta_expansion_test l' with\n  | some e := option.map (\u03bb _, e) <$> try_core (unify e val)\n  | none   := return none\n  end\n\n/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the\n  eta-expansion of `e`.\n  With eta-expansion we here mean the eta-expansion of a structure, not of a function.\n  For example, the eta-expansion of `x : \u03b1 \u00d7 \u03b2` is `\u27e8x.1, x.2\u27e9`.\n  This assumes that `val` is a fully-applied application of the constructor of a structure.\n\n  This is useful to reduce expressions generated by the notation\n    `{ field_1 := _, ..other_structure }`\n  If `other_structure` is itself a field of the structure, then the elaborator will insert an\n  eta-expanded version of `other_structure`. -/\nmeta def is_eta_expansion (val : expr) : tactic (option expr) := do\n  e \u2190 get_env,\n  type \u2190 infer_type val,\n  projs \u2190 e.structure_fields_full type.get_app_fn.const_name,\n  let args := (val.get_app_args).drop type.get_app_args.length,\n  is_eta_expansion_aux val (projs.zip args)\n\nend expr\n\n/-! ### Declarations about `declaration` -/\n\nnamespace declaration\n\n/--\n`declaration.update_with_fun f test tgt decl`\nsets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and\n`expr.apply_replacement_fun` to the value and type of `decl`.\n-/\nprotected meta def update_with_fun (env : environment) (f : name \u2192 name) (test : expr \u2192 bool)\n  (relevant : name_map \u2115) (reorder : name_map $ list \u2115) (tgt : name) (decl : declaration) :\n  declaration :=\nlet decl := decl.update_name $ tgt in\nlet decl := decl.update_type $\n  (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in\ndecl.update_value $\n  (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder\n\n/-- Checks whether the declaration is declared in the current file.\n  This is a simple wrapper around `environment.in_current_file`\n  Use `environment.in_current_file` instead if performance matters. -/\nmeta def in_current_file (d : declaration) : tactic bool :=\ndo e \u2190 get_env, return $ e.in_current_file d.to_name\n\n/-- Checks whether a declaration is a theorem -/\nmeta def is_theorem : declaration \u2192 bool\n| (thm _ _ _ _) := tt\n| _             := ff\n\n/-- Checks whether a declaration is a constant -/\nmeta def is_constant : declaration \u2192 bool\n| (cnst _ _ _ _) := tt\n| _              := ff\n\n/-- Checks whether a declaration is a axiom -/\nmeta def is_axiom : declaration \u2192 bool\n| (ax _ _ _) := tt\n| _          := ff\n\n/-- Checks whether a declaration is automatically generated in the environment.\n  There is no cheap way to check whether a declaration in the namespace of a generalized\n  inductive type is automatically generated, so for now we say that all of them are automatically\n  generated. -/\nmeta def is_auto_generated (e : environment) (d : declaration) : bool :=\ne.is_constructor d.to_name \u2228\n(e.is_projection d.to_name).is_some \u2228\n(e.is_constructor d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"inj\", \"inj_eq\", \"sizeof_spec\", \"inj_arrow\"]) \u2228\n(e.is_inductive d.to_name.get_prefix \u2227\n  d.to_name.last \u2208 [\"below\", \"binduction_on\", \"brec_on\", \"cases_on\", \"dcases_on\", \"drec_on\", \"drec\",\n  \"rec\", \"rec_on\", \"no_confusion\", \"no_confusion_type\", \"sizeof\", \"ibelow\", \"has_sizeof_inst\"]) \u2228\nd.to_name.has_prefix (\u03bb nm, e.is_ginductive' nm)\n\n/--\nReturns true iff `d` is an automatically-generated or internal declaration.\n-/\nmeta def is_auto_or_internal (env : environment) (d : declaration) : bool :=\nd.to_name.is_internal || d.is_auto_generated env\n\n/-- Returns the list of universe levels of a declaration. -/\nmeta def univ_levels (d : declaration) : list level :=\nd.univ_params.map level.param\n\n/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/\nprotected meta def reducibility_hints : declaration \u2192 reducibility_hints\n| (declaration.defn _ _ _ _ red _) := red\n| _ := _root_.reducibility_hints.opaque\n\n/-- formats the arguments of a `declaration.thm` -/\nprivate meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body.get,\n   return $ \"<theorem \" ++ to_fmt nm ++ \" : \" ++ tp ++ \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.defn` -/\nprivate meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :\n  tactic format :=\ndo tp \u2190 pp tp, body \u2190 pp body,\n   return $ \"<\" ++ (if is_trusted then \"def \" else \"meta def \") ++ to_fmt nm ++ \" : \" ++ tp ++\n     \" := \" ++ body ++ \">\"\n\n/-- formats the arguments of a `declaration.cnst` -/\nprivate meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<\" ++ (if is_trusted then \"constant \" else \"meta constant \") ++ to_fmt nm ++ \" : \"\n     ++ tp ++ \">\"\n\n/-- formats the arguments of a `declaration.ax` -/\nprivate meta def print_ax (nm : name) (tp : expr) : tactic format :=\ndo tp \u2190 pp tp,\n   return $ \"<axiom \" ++ to_fmt nm ++ \" : \" ++ tp ++ \">\"\n\n/-- pretty-prints a `declaration` object. -/\nmeta def to_tactic_format : declaration \u2192 tactic format\n| (declaration.thm nm _ tp bd) := print_thm nm tp bd\n| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted\n| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted\n| (declaration.ax nm _ tp) := print_ax nm tp\n\nmeta instance : has_to_tactic_format declaration :=\n\u27e8to_tactic_format\u27e9\n\nend declaration\n\nmeta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=\nunchecked_cast\nexpr.has_decidable_eq\n\nsection\nlocal attribute [semireducible] reflected\nmeta instance {\u03b1} [has_reflect \u03b1] : has_reflect (thunk \u03b1) | a :=\nexpr.lam `x binder_info.default (reflect unit) (reflect $ a ())\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/meta/expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256832002764217, "lm_q2_score": 0.06097518641075782, "lm_q1q2_score": 0.0156603792447964}}
{"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 \u2964 C) :\n  \u2203 (X\u2081 X\u2082 : C), nonempty (F \u2245 pair X\u2081 X\u2082) :=\n\u27e8F.obj (discrete.mk walking_pair.left), F.obj (discrete.mk walking_pair.right),\n  \u27e8discrete.nat_iso_functor \u226a\u226b eq_to_iso (by { congr' 1, ext j, cases j, tidy, })\u27e9\u27e9\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 \u2964 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 := \u03bb X, 0, },\n  have hc : is_limit c :=\n  { lift := \u03bb s, 0,\n    fac' := by rintro s \u27e8\u27e8\u27e9\u27e9,\n    uniq' := \u03bb s m hm, subsingleton.elim _ _, },\n  refine preserves_limit_of_preserves_limit_cone hc\n  { lift := \u03bb s, 0,\n    fac' := by rintro s \u27e8\u27e8\u27e9\u27e9,\n    uniq' := \u03bb 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, \u2190 F.map_id,\n        subsingleton.elim (\ud835\udfd9 (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\u2081 : S.f = 0) (h\u2082 : S.g = 0) : is_zero S.X\u2082 :=\n(short_complex.homology_data.of_zeros S h\u2081 h\u2082).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 \u2194 S.g = 0 :=\nbegin\n  split,\n  { introI,\n    simp only [\u2190 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 [\u2190 S.p_desc_cycles_co _ eq, \u2190 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 \u2194 S.f = 0 :=\nbegin\n  split,\n  { introI,\n    simp only [\u2190 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 [\u2190 S.lift_cycles_i _ eq, \u2190 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 \u2124]\n  [preadditive C] [\u2200 (n : \u2124), (shift_functor C n).additive] [pretriangulated C]\n  [category D] [has_zero_object D] [has_shift D \u2124]\n  [preadditive D] [\u2200 (n : \u2124), (shift_functor D n).additive] [pretriangulated D]\n  [category A] [abelian A] (F : C \u2964 A) [functor.preserves_zero_morphisms F]\n\n@[simps]\ndef pretriangulated.triangle.short_complex (T : pretriangulated.triangle C)\n  (hT : T \u2208 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 [] : \u2200 (T : pretriangulated.triangle C) (hT : T \u2208 dist_triang C),\n  ((T.short_complex hT).map F).exact)\n\nnamespace is_homological\n\nlemma mk' (hF : \u2200 (T : pretriangulated.triangle C) (hT : T \u2208 dist_triang C),\n  \u2203 (T' : pretriangulated.triangle C) (hT' : T' \u2208 dist_triang C) (e : T \u2245 T'),\n    ((T'.short_complex hT').map F).exact) :\n  F.is_homological :=\n\u27e8\u03bb T hT, begin\n  obtain \u27e8T', hT', e, ex'\u27e9 := 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 \u2964 _) e,\nend\u27e9\n\nvariable {F}\n\nlemma of_iso {G : C \u2964 A} [G.preserves_zero_morphisms] (e : G \u2245 F) [F.is_homological] :\n  G.is_homological :=\nis_homological.mk (\u03bb 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\u03bb K, \u2200 (n : \u2124), limits.is_zero (F.obj (K\u27e6n\u27e7))\n\ninstance : is_triangulated_subcategory F.kernel_of_is_homological :=\n{ zero := \u03bb n, limits.is_zero.of_iso (is_zero_zero A)\n    (F.map_iso (shift_functor C n).map_zero_object \u226a\u226b F.map_zero_object),\n  shift := \u03bb 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\u2082 := \u03bb T hT h\u2081 h\u2083 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\u2081 _) _ _) (is_zero.eq_of_tgt (h\u2083 _) _ _), }\n\ninstance kernel_of_is_homological_saturated :\n  saturated F.kernel_of_is_homological :=\n\u27e8\u03bb 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 \u22a2 hL,\n  have eq : \ud835\udfd9 _ = i \u226b \ud835\udfd9 _ \u226b retraction i := by simp only [id_comp, is_split_mono.id],\n  replace eq := (shift_functor C n \u22d9 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\u27e9\n\ndef W_of_is_homological : morphism_property C :=\n\u03bb X Y f, \u2200 (n : \u2124), is_iso (F.map (f\u27e6n\u27e7'))\n\ninstance : preserves_limits_of_shape (discrete walking_pair) F :=\nbegin\n  suffices : \u2200 (X\u2081 X\u2082 : C), preserves_limit (pair X\u2081 X\u2082) F,\n  { haveI := this,\n    exact \u27e8\u03bb 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\u27e9, },\n  intros X\u2081 X\u2082,\n  haveI : mono (F.biprod_comparison X\u2081 X\u2082),\n  { rw preadditive.mono_iff_cancel_zero,\n    intros Z f hf,\n    have h\u2082 : f \u226b F.map biprod.snd = 0,\n    { simpa only [assoc, biprod_comparison_snd, zero_comp] using hf =\u226b biprod.snd, },\n    have ex := is_homological.map_distinguished F _\n      (binary_biproduct_triangle_distinguished X\u2081 X\u2082),\n    let S := short_complex.mk (F.map (biprod.inl : X\u2081 \u27f6 _)) (F.map (biprod.snd : _ \u27f6 X\u2082))\n      (by { rw \u2190 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\u2081 X\u2082)),\n    have hf' : \u2203 (f\u2081 : Z \u27f6 F.obj X\u2081), f\u2081 \u226b F.map biprod.inl = f := \u27e8_, ex.lift_f f h\u2082\u27e9,\n    obtain \u27e8f\u2081, rfl\u27e9 := hf',\n    replace hf := hf =\u226b biprod.fst,\n    simp only [assoc, biprod_comparison_fst, zero_comp, \u2190 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\u2081 X\u2082 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\u27e6n\u27e7',\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 \u27e8Z, g', h', dist, mem\u27e9 := 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 \u2124).symm.app _))) _ _), }, },\n  { intro hf,\n    obtain \u27e8Z, g, h, mem\u27e9 := pretriangulated.distinguished_cocone_triangle _ _ f,\n    have w : f \u226b g = 0 := pretriangulated.triangle.comp_zero\u2081\u2082 _ mem,\n    refine \u27e8Z, g, h, mem, \u03bb n, _\u27e9,\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 \u2190 cancel_epi (F.map (f\u27e6n\u27e7')),\n      simp only [F.map_zsmul, comp_zero, preadditive.comp_zsmul, \u2190 functor.map_comp, w,\n        functor.map_zero, zsmul_zero], },\n    { haveI : is_iso (F.map (f\u27e6n\u27e7'\u27e6(1 : \u2124)\u27e7')) :=\n        (nat_iso.is_iso_map_iff (iso_whisker_right (shift_functor_add _ n 1) F) f).1 (hf (n+1)),\n      rw \u2190 cancel_mono (F.map (f\u27e6n\u27e7'\u27e6(1 : \u2124)\u27e7')),\n      have w' := F.congr_map (pretriangulated.triangle.comp_zero\u2082\u2083 _\n        (rot_of_dist_triangle _ _ (triangle.shift_distinguished _ _ mem n))),\n      dsimp [pretriangulated.triangle.short_complex] at \u22a2 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, \u2190 units.coe_mul, \u2190 mul_zpow, mul_neg, neg_mul, neg_neg, one_mul, one_smul,\n        one_zpow, units.coe_one] at w',\n      simp only [\u2190 F.map_comp, zero_comp, assoc, preadditive.zsmul_comp, F.map_zsmul, w',\n        smul_zero], }, },\nend\n\ninstance shift_is_homological (n : \u2124) :\n  (shift_functor C n \u22d9 F).is_homological :=\n\u27e8\u03bb 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 \u2124)^n) (iso.refl _))\n    (iso.refl _) (preadditive.mul_iso ((-1 : units \u2124)^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      \u2190 units.coe_mul, \u2190 mul_zpow, mul_neg, neg_mul, neg_neg, one_mul, one_smul, one_zpow,\n      units.coe_one], },\nend\u27e9\n\nend\n\n@[priority 100]\ninstance triangulated_functor_preserves_zero_morphisms\n  (F : C \u2964 D) [F.has_comm_shift \u2124] [F.is_triangulated] :\n  F.preserves_zero_morphisms :=\n\u27e8\u03bb X\u2081 X\u2082, begin\n  have h := triangle.comp_zero\u2081\u2082 _ (F.map_distinguished _\n    (binary_product_triangle_distinguished X\u2081 X\u2082)),\n  dsimp at h,\n  simpa only [\u2190 F.map_comp, prod.lift_snd] using h,\nend\u27e9\n\ninstance triangulated_functor_preserves_binary_products\n  (F : C \u2964 D) [F.has_comm_shift \u2124] [F.is_triangulated] :\n  preserves_limits_of_shape (discrete walking_pair) F :=\nbegin\n  suffices : \u2200 (X\u2081 X\u2082 : C), preserves_limit (pair X\u2081 X\u2082) F,\n  { haveI := this,\n    exact \u27e8\u03bb 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\u27e9, },\n  intros X\u2081 X\u2082,\n  haveI : mono (F.biprod_comparison X\u2081 X\u2082),\n  { rw preadditive.mono_iff_cancel_zero,\n    intros Z f hf,\n    have h\u2082 : f \u226b F.map biprod.snd = 0,\n    { simpa only [assoc, biprod_comparison_snd, zero_comp] using hf =\u226b biprod.snd, },\n    obtain \u27e8f\u2081, rfl\u27e9 := covariant_yoneda_exact\u2082 _\n      (F.map_distinguished _ (binary_biproduct_triangle_distinguished X\u2081 X\u2082)) f h\u2082,\n    replace hf := hf =\u226b biprod.fst,\n    dsimp [triangulated_functor.map_triangle] at hf,\n    simp only [assoc, biprod_comparison_fst, zero_comp, \u2190 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\u2081 X\u2082 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 \u2964 D) [F.has_comm_shift \u2124] [F.is_triangulated ] :\n  F.additive :=\nfunctor.additive_of_preserves_binary_products _\n\n@[priority 100]\ninstance is_homological.of_comp (F : C \u2964 D) (G : D \u2964 A) [F.has_comm_shift \u2124]\n  [F.is_triangulated] [G.preserves_zero_morphisms]\n  [G.is_homological] : (F \u22d9 G).is_homological :=\n\u27e8\u03bb T hT, begin\n  have h := is_homological.map_distinguished G _ (F.map_distinguished _ hT),\n  exact h,\nend\u27e9\n\nnamespace is_homological\n\nvariables (F) (T : pretriangulated.triangle C) (hT : T \u2208 dist_triang C)\n  (n\u2080 n\u2081 : \u2124) (h : n\u2081 = n\u2080+1)\n\ninclude h\n\ndef \u03b4 : F.obj (T.obj\u2083\u27e6n\u2080\u27e7) \u27f6 F.obj (T.obj\u2081\u27e6n\u2081\u27e7) :=\nF.map (T.mor\u2083\u27e6n\u2080\u27e7' \u226b (shift_functor_add' C (1 : \u2124) n\u2080 n\u2081 (by rw [h, add_comm])).inv.app T.obj\u2081)\n\nomit h\n\ninclude hT\n\nlemma \u03b4_comp : \u03b4 F T n\u2080 n\u2081 h \u226b F.map (T.mor\u2081\u27e6n\u2081\u27e7') = 0 :=\nbegin\n  dsimp only [\u03b4],\n  rw [\u2190 F.map_comp, assoc, \u2190 nat_trans.naturality],\n  erw [\u2190 functor.map_comp_assoc, pretriangulated.triangle.comp_zero\u2083\u2081 _ hT],\n  simp only [functor.map_zero, zero_comp],\nend\n\nlemma comp_\u03b4 : F.map (T.mor\u2082\u27e6n\u2080\u27e7') \u226b \u03b4 F T n\u2080 n\u2081 h  = 0 :=\nbegin\n  dsimp only [\u03b4],\n  rw [\u2190 F.map_comp, \u2190 functor.map_comp_assoc, pretriangulated.triangle.comp_zero\u2082\u2083 _ hT],\n  simp only [functor.map_zero, zero_comp],\nend\n\nvariable [hF : F.is_homological]\n\ninclude hF\n\nlemma ex\u2082 (n : \u2124) :\n  (short_complex.mk (F.map (T.mor\u2081\u27e6n\u27e7')) (F.map (T.mor\u2082\u27e6n\u27e7'))\n    (by rw [\u2190 F.map_comp, \u2190 functor.map_comp, pretriangulated.triangle.comp_zero\u2081\u2082 _ 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 \u2124)^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\u2083 :\n  (short_complex.mk (F.map (T.mor\u2082\u27e6n\u2080\u27e7')) (\u03b4 F T n\u2080 n\u2081 h) (comp_\u03b4 F T hT n\u2080 n\u2081 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\u2080))),\n  refine short_complex.mk_iso (iso.refl _) (preadditive.mul_iso ((-1 : units \u2124)^n\u2080) (iso.refl _))\n    (F.map_iso ((shift_functor_add' C n\u2080 (1 : \u2124) n\u2081 h).symm.app T.obj\u2081)) _ _,\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 [\u03b4],\n    simp only [preadditive.zsmul_comp, id_comp, F.map_zsmul, \u2190 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\u2081 :\n  (short_complex.mk (\u03b4 F T n\u2080 n\u2081 h) (F.map (T.mor\u2081\u27e6n\u2081\u27e7')) (\u03b4_comp F T hT n\u2080 n\u2081 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\u2081))),\n  refine short_complex.mk_iso\n    (F.map_iso ((shift_functor_add' C n\u2081 (-1) n\u2080\n      (by rw [h, int.add_neg_one, add_tsub_cancel_right])).symm.app T.obj\u2083))\n    (preadditive.mul_iso ((-1 : units \u2124)^n\u2080) (iso.refl _))\n    (preadditive.mul_iso ((-1 : units \u2124)) (iso.refl _)) _ _,\n  { change F.map ((shift_functor_add' C n\u2081 (-1 : \u2124) n\u2080 _).inv.app T.obj\u2083) \u226b\n      F.map (T.mor\u2083\u27e6n\u2080\u27e7' \u226b (shift_functor_add' C 1 n\u2080 n\u2081 _).inv.app T.obj\u2081) =\n      F.map (-(shift_functor C (-1 : \u2124)).map (((-1 : units \u2124)^n\u2081 \u2022 T.mor\u2083\u27e6n\u2081\u27e7') \u226b (shift_functor_add_comm C 1 n\u2081).hom.app _) \u226b\n      (shift_shift_neg (T.obj\u2081\u27e6n\u2081\u27e7) (1 : \u2124)).hom) \u226b ((-1 : units \u2124)^n\u2080 \u2022 \ud835\udfd9 _),\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, \u2190 F.map_comp],\n    erw \u2190 nat_trans.naturality_assoc,\n    rw [(shift_functor C (-1 : \u2124)).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": "deriving instance TypeName for Nat\nderiving instance TypeName for String\n\nexample : (Dynamic.mk 42).get? String = none := by native_decide\nexample : (Dynamic.mk 42).get? Nat = some 42 := by native_decide\nexample : (Dynamic.mk 42).typeName = ``Nat := by native_decide\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/dynamic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37754066879814535, "lm_q2_score": 0.04146227256335484, "lm_q1q2_score": 0.01565369411345998}}
{"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 \u2192 name \u2192 name\n| mk_numeral : unsigned \u2192 name \u2192 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 (\u03b1 : Sort u) (tac_name : name) : Sort u :=\n\u03b1\n\n@[simp] lemma {u} auto_param_eq (\u03b1 : Sort u) (n : name) : auto_param \u03b1 n = \u03b1 :=\nrfl\n\ninstance : inhabited name :=\n\u27e8name.anonymous\u27e9\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\u27e8mk_simple_name\u27e9\n\ninfix ` <.> `:65 := mk_str_name\n\nopen name\n\ndef name.get_prefix : name \u2192 name\n| anonymous        := anonymous\n| (mk_string s p)  := p\n| (mk_numeral s p) := p\n\ndef name.update_prefix : name \u2192 name \u2192 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 \u2192 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 \u2192 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\u27e8name.to_string\u27e9\n\ninstance : has_repr name :=\n\u27e8name.repr\u27e9\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 \u2192 name \u2192 ordering\nmeta constant name.lex_cmp : name \u2192 name \u2192 ordering\nmeta constant name.append : name \u2192 name \u2192 name\nmeta constant name.is_internal : name \u2192 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\u03bb a b, ordering.decidable_eq _ _\n\nmeta instance : has_lt name :=\n\u27e8name.lt\u27e9\n\nattribute [instance] name.has_decidable_eq\n\nmeta instance : has_append name :=\n\u27e8name.append\u27e9\n\n/-- `name.append_after n i` return a name of the form n_i -/\nmeta constant name.append_after : name \u2192 nat \u2192 name\n\nmeta def name.is_prefix_of : name \u2192 name \u2192 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 \u2192 name \u2192 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 \u2192 name \u2192 name \u2192 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": "/-\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.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Meta.Basic\n\nnamespace Lean.Meta\n\nstructure CongrLemma where\n  theoremName   : Name\n  funName       : Name\n  hypothesesPos : Array Nat\n  priority      : Nat\nderiving Inhabited, Repr\n\nstructure CongrLemmas where\n  lemmas : SMap Name (List CongrLemma) := {}\n  deriving Inhabited, Repr\n\ndef CongrLemmas.get (d : CongrLemmas) (declName : Name) : List CongrLemma :=\n  match d.lemmas.find? declName with\n  | none    => []\n  | some cs => cs\n\ndef addCongrLemmaEntry (d : CongrLemmas) (e : CongrLemma) : CongrLemmas :=\n  { d with lemmas :=\n      match d.lemmas.find? e.funName with\n      | none    => d.lemmas.insert e.funName [e]\n      | some es => d.lemmas.insert e.funName <| insert es }\nwhere\n  insert : List CongrLemma \u2192 List CongrLemma\n    | []     => [e]\n    | e'::es => if e.priority \u2265 e'.priority then e::e'::es else e' :: insert es\n\nbuiltin_initialize congrExtension : SimpleScopedEnvExtension CongrLemma CongrLemmas \u2190\n  registerSimpleScopedEnvExtension {\n    name           := `congrExt\n    initial        := {}\n    addEntry       := addCongrLemmaEntry\n    finalizeImport := fun s => { s with lemmas := s.lemmas.switch }\n  }\n\ndef mkCongrLemma (declName : Name) (prio : Nat) : MetaM CongrLemma := withReducible do\n  let c \u2190 mkConstWithLevelParams declName\n  let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType c)\n  match type.eq? with\n  | none => throwError \"invalid 'congr' theorem, equality expected{indentExpr type}\"\n  | some (_, lhs, rhs) =>\n    lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do\n      unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do\n        throwError \"invalid 'congr' theorem, equality left/right-hand sides must be applications of the same function{indentExpr type}\"\n      let mut foundMVars : NameSet := {}\n      for lhsArg in lhsArgs do\n        unless lhsArg.isSort do\n          unless lhsArg.isMVar do\n            throwError \"invalid 'congr' theorem, arguments in the left-hand-side must be variables or sorts{indentExpr lhs}\"\n          foundMVars := foundMVars.insert lhsArg.mvarId!\n      let mut i := 0\n      let mut hypothesesPos := #[]\n      for x in xs, bi in bis do\n        if bi.isExplicit && !foundMVars.contains x.mvarId! then\n          let rhsFn? \u2190 forallTelescopeReducing (\u2190 inferType x) fun ys xType => do\n            match xType.eq? with\n            | none => pure none -- skip\n            | some (_, xLhs, xRhs) =>\n              let mut j := 0\n              for y in ys do\n                let yType \u2190 inferType y\n                unless onlyMVarsAt yType foundMVars do\n                  throwError \"invalid 'congr' theorem, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}\"\n                j := j + 1\n              unless onlyMVarsAt xLhs foundMVars do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}\"\n              let xRhsFn := xRhs.getAppFn\n              unless xRhsFn.isMVar do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}\"\n              unless !foundMVars.contains xRhsFn.mvarId! do\n                throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}\"\n              for arg in xRhs.getAppArgs do\n                unless arg.isFVar do\n                  throwError \"invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}\"\n              pure (some xRhsFn)\n          match rhsFn? with\n          | none       => pure ()\n          | some rhsFn =>\n            foundMVars    := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId!\n            hypothesesPos := hypothesesPos.push i\n        i := i + 1\n      trace[Meta.debug] \"c: {c} : {type}\"\n      return {\n        theoremName   := declName\n        funName       := lhsFn.constName!\n        hypothesesPos := hypothesesPos\n        priority      := prio\n      }\nwhere\n  /-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/\n  onlyMVarsAt (t : Expr) (mvarSet : NameSet) : Bool :=\n    Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId!\n\ndef addCongrLemma (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n  let lemma \u2190 mkCongrLemma declName prio\n  congrExtension.add lemma attrKind\n\nbuiltin_initialize\n  registerBuiltinAttribute {\n    name  := `congr\n    descr := \"congruence theorem\"\n    add   := fun declName stx attrKind => do\n      let prio \u2190 getAttrParamOptPrio stx[1]\n      discard <| addCongrLemma declName attrKind prio |>.run {} {}\n  }\n\ndef getCongrLemmas : MetaM CongrLemmas :=\n  return congrExtension.getState (\u2190 getEnv)\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/CongrLemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.035678554466513586, "lm_q1q2_score": 0.015620909559865616}}
{"text": "import Machine.Parser\nimport Machine.Options\nimport Lean.Elab\n\nopen Lean Machine.Types\n\nnamespace List\n  def forAll {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : List \u03b1 \u2192 Prop\n  | []      => True\n  | x :: xs => P x \u2227 forAll P xs\n\n  def successively {\u03b1 : Type u} (R : \u03b1 \u2192 \u03b1 \u2192 Prop) : List \u03b1 \u2192 Prop\n  | []           => True\n  | [x]          => True\n  | x :: y :: ys => R x y \u2227 successively R (y :: ys)\n\n  def forLast {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : List \u03b1 \u2192 Prop\n  | []      => True\n  | [x]     => P x\n  | x :: xs => forLast P xs\n\n  def forFirst {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : List \u03b1 \u2192 Prop\n  | []      => True\n  | x :: xs => P x\n\n  def nonempty {\u03b1 : Type u} : List \u03b1 \u2192 Prop\n  | []      => False\n  | x :: xs => True\nend List\n\nnamespace Machine.Types\n  def machine.next : machine \u2192 machine\n  | \u27e8stack, regs, flag, progc\u27e9 => \u27e8stack, regs, flag, progc + 1\u27e9\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  \u27e8M.stack, M.regs, M.flag, if M.flag == cond then ptr else M.progc + 1\u27e9\n\n  def instr.eval (M : machine) : instr \u2192 machine\n  | instr.push z => \u27e8M.stack.push z, M.regs, M.flag, M.progc + 1\u27e9\n  | instr.pushr r => \u27e8M.stack.push (M.get r), M.regs, M.flag, M.progc + 1\u27e9\n  | instr.popr r => \u27e8M.stack.pop, M.regs.replace r M.stack.back, M.flag, M.progc + 1\u27e9\n  | instr.dup => \u27e8M.stack.push M.stack.back, M.regs, M.flag, M.progc + 1\u27e9\n  | instr.add r\u2081 r\u2082 r\u2083 => \u27e8M.stack, M.regs.replace r\u2083 (M.get r\u2081 + M.get r\u2082), M.flag, M.progc + 1\u27e9\n  | instr.neg r\u2081 r\u2082 => \u27e8M.stack, M.regs.replace r\u2082 (-M.get r\u2081), M.flag, M.progc + 1\u27e9\n  | instr.mul r\u2081 r\u2082 r\u2083 => \u27e8M.stack, M.regs.replace r\u2083 (M.get r\u2081 * M.get r\u2082), M.flag, M.progc + 1\u27e9\n  | instr.cmp r\u2081 r\u2082 => \u27e8M.stack, M.regs, compare (M.get r\u2081) (M.get r\u2082), M.progc + 1\u27e9\n  | instr.jmp ptr => \u27e8M.stack, M.regs, M.flag, ptr\u27e9\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 \u2192 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) (\u03c1 : tape) : Option machine :=\n  match \u03c1.get? M.progc with\n  | none   => none\n  | some \u03b5 => some (instr.eval M \u03b5)\n\n  def effect (M : machine) (\u03c1 : tape) : IO Unit :=\n  match \u03c1.get? M.progc with\n  | none   => return ()\n  | some \u03b5 => instr.effect M \u03b5\n\n  private def await (M\u2080 : machine) (\u03c1 : tape) : Nat \u2192 IO Unit\n  |   0   => throw (IO.userError \"execution depth was reached\")\n  | n + 1 => do effect M\u2080 \u03c1; match tick M\u2080 \u03c1 with\n    | none   => return ()\n    | some M => await M \u03c1 n\n\n  private partial def unsafeAwait (M\u2080 : machine) (\u03c1 : tape) : IO Unit :=\n  do effect M\u2080 \u03c1; match tick M\u2080 \u03c1 with\n  | none   => return ()\n  | some M => unsafeAwait M \u03c1\n\n  def simulate :=\n  unsafeAwait machine.init\n\n  elab \"asm \" label:ident xs:mnemonic* \" end\" : command => do\n    let (\u03c1, M) \u2190 Machine.Parser.expand xs\n    let xs \u2190 Array.mapM instr.restore \u03c1\n    Elab.Command.elabDeclaration (\u2190 `(def $label : Array instr := #[$xs,*]))\n\n    let opts \u2190 getOptions\n\n    if Machine.Options.debugAsm.get opts then\n      do await M \u03c1 (Machine.Options.executionDepth.get opts)\n    else return ()\n\n  def computes (\u03c1 : tape) (M\u2081 M\u2082 : machine) :=\n  tick M\u2081 \u03c1 = some M\u2082\n\n  def completed (\u03c1 : tape) (M : machine) :=\n  tick M \u03c1 = none\n\n  def clean (M : machine) :=\n  M = machine.init\n\n  def allowed (\u03c1 : tape) (L : List machine) :=\n  L.successively (computes \u03c1) \u2227 L.forLast (completed \u03c1)\n\n  def terminator (\u03c1 : tape) (L : List machine) :=\n  L.nonempty \u2227 L.forFirst clean \u2227 allowed \u03c1 L\n\n  def terminating (\u03c1 : tape) :=\n  \u2203 L, terminator \u03c1 L\n\n  asm loop\n    M: jmp M\n  end\n\n  theorem some_inj {\u03b1 : Type u} {a b : \u03b1} (p : some a = some b) : a = b :=\n  by { apply Option.noConfusion p; apply id }\n\n  theorem loop.conservative : \u2200 (M\u2081 M\u2082 : machine), tick M\u2081 loop = M\u2082 \u2192 M\u2081 = M\u2082 :=\n  \u03bb \u27e8stack\u2081, regs\u2081, flags\u2081, progc\u2081\u27e9 \u27e8stack\u2082, regs\u2082, flags\u2082, progc\u2082\u27e9 H => by {\n    induction progc\u2081; apply some_inj H; cases H\n  }\n\n  theorem loopTerminator : \u2200 (L : List machine), terminator loop L \u2192 False\n  | [], \u27e8p, _\u27e9 => p\n  | [x], \u27e8_, \u27e8q, \u27e8_, h\u27e9\u27e9\u27e9 => by { rw [q] at h; cases h }\n  | x :: y :: ys, \u27e8p, \u27e8q, \u27e8r, h\u27e9\u27e9\u27e9 => by {\n    apply loopTerminator (y :: ys); apply And.intro;\n    apply True.intro; apply And.intro; rw [\u2190loop.conservative x y r.left];\n    apply q; apply And.intro; apply r.right; apply h\n  }\n\n  theorem nonterminating : \u00acterminating loop :=\n  \u03bb | Exists.intro L \u03b7 => loopTerminator L \u03b7\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 {\u03b1 \u03b2 \u03b3 : 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 : \u03a0 (i : spec.\u03b9), spec.domain i \u2192 oracle_comp spec' (spec.range i))\n(update_state : \u03a0 (s : S) (i : spec.\u03b9), spec.domain i \u2192 spec.range i \u2192 S)\n(o := \u03bb i x, (\u03bb 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 := \u03bb _ _ _ _, ())\n(o := \u03bb i x, (\u03bb u, (u, ())) <$> (answer_query i x.1))\n\ndef identi_o (spec : oracle_spec) : stateless_sim_oracle spec spec :=\n{ answer_query := \u03bb 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 : \u03a0 (i : spec.\u03b9), spec.domain i \u2192 oracle_comp spec' (spec.range i))\n  (update_state : \u03a0 (s : S) (i : spec.\u03b9), spec.domain i \u2192 spec.range i \u2192 S)\n  (default_state : S) : sim_oracle spec spec' S :=\n{ default_state := default_state,\n  o := \u03bb i \u27e8t, s\u27e9, (\u03bb u, (u, update_state s i t u)) <$> (o i t) }\n\nnotation `\u27ea` o `|` update_state `,` default_state `\u27eb` :=\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 : \u03a0 (i : spec.\u03b9), spec.domain i \u2192 oracle_comp spec' (spec.range i))\n  (o' : \u03a0 (i : spec.\u03b9), spec.domain i \u2192 oracle_comp spec'' (spec.range i))\n  (update_state : \u03a0 (s : S) (i : spec.\u03b9), spec.domain i \u2192 spec.range i \u2192 S)\n  (update_state' : \u03a0 (s : S') (i : spec.\u03b9), spec.domain i \u2192 spec.range i \u2192 S')\n  (default_state : S) (default_state' : S') (a : \u03b1) (i : spec.\u03b9) (t : spec.domain i)\n  (oa : oracle_comp spec \u03b1) (ob : \u03b1 \u2192 oracle_comp spec \u03b2) (s : S) (s' : S')\n  (x : spec.domain i \u00d7 S) (y : spec.range i \u00d7 S)\n\n@[simp] lemma apply_eq : \u27eao | update_state, default_state\u27eb i x =\n  (\u03bb u, (u, update_state x.2 i x.1 u)) <$> (o i x.1) := by {cases x, refl}\n\ninstance decidable [decidable_eq S] [\u2200 i x, (o i x).decidable] :\n  (\u27eao | update_state, default_state\u27eb i x).decidable :=\nby { rw [apply_eq], exact oracle_comp.decidable_map _ _ }\n\nsection support\n\n@[simp] lemma support_apply : (\u27eao | update_state, default_state\u27eb i x).support =\n  (\u03bb u, (u, update_state x.2 i x.1 u)) '' (o i x.1).support :=\nset.ext (\u03bb y, by rw [apply_eq, support_map])\n\nlemma fin_support_apply [\u2200 i t, (o i t).decidable] [decidable_eq S] :\n  (\u27eao | update_state, default_state\u27eb i x).fin_support =\n    (o i x.1).fin_support.image (\u03bb 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 \u00d7 S} :\n  y \u2208 (\u27eao | update_state, default_state\u27eb i x).support \u2194\n    y.1 \u2208 (o i x.1).support \u2227 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 : \u2200 i t, (o i t).support = \u22a4) :\n  (simulate' \u27eao | update_state, default_state\u27eb oa s).support = oa.support :=\nsupport_simulate'_eq_support _ oa s (\u03bb i t s, set.ext (\u03bb 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' \u27eaquery | update_state, default_state\u27eb oa s).support = oa.support :=\nsupport_simulate'_eq_support query update_state default_state oa s (\u03bb _ _, rfl)\n\ntheorem support_simulate'_eq_support_simulate' (h : \u2200 i t, (o i t).support = (o' i t).support) :\n  (simulate' \u27eao | update_state, default_state\u27eb oa s).support =\n    (simulate' \u27eao' | update_state', default_state'\u27eb oa s').support :=\nsupport_simulate'_eq_support_simulate' (\u03bb i t s s', set.ext $ \u03bb 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' \u27eao | update_state, default_state\u27eb oa s).support =\n    (simulate' \u27eao | update_state', default_state'\u27eb oa s').support :=\nsupport_simulate'_eq_support_simulate' o o _ _ _ _ oa s s' (\u03bb _ _, rfl)\n\nsection subsingleton\n\nvariables [subsingleton S]\n\n@[simp] lemma support_apply_of_subsingleton :\n  (\u27eao | update_state, default_state\u27eb i x).support = prod.fst \u207b\u00b9' (o i x.1).support :=\nset.ext (\u03bb 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 : \u2200 i t, (o i t).support = \u22a4) :\n  (simulate \u27eao | update_state, default_state\u27eb oa s).support = prod.fst \u207b\u00b9' 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 \u27eaquery | update_state, default_state\u27eb oa s).support = prod.fst \u207b\u00b9' oa.support :=\nsupport_simulate_eq_preimage_support_of_subsingleton query _ _ oa s (\u03bb _ _, rfl)\n\nend subsingleton\n\nend support\n\nsection eval_dist\n\n@[simp] lemma eval_dist_apply :\n  \u2045\u27eao | update_state, default_state\u27eb i (t, s)\u2046 = \u2045o i t\u2046.map (\u03bb 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 : \u2200 i t, \u2045o i t\u2046 = pmf.uniform_of_fintype (spec.range i)) :\n  \u2045simulate' \u27eao | update_state, default_state\u27eb oa s\u2046 = \u2045oa\u2046 :=\neval_dist_simulate'_eq_eval_dist _ oa s (\u03bb i t s, trans\n  (by simpa [eval_dist_apply, pmf.map_comp] using pmf.map_id \u2045o i t\u2046) (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  \u2045simulate' \u27eaquery | update_state, default_state\u27eb oa s\u2046 = \u2045oa\u2046 :=\neval_dist_simulate'_eq_eval_dist query update_state default_state oa s (\u03bb _ _, rfl)\n\nlemma eval_dist_simulate'_eq_eval_dist_simulate'\n  (h : \u2200 i t, o i t \u2243\u209a o' i t) : \u2045simulate' \u27eao | update_state, default_state\u27eb oa s\u2046 =\n    \u2045simulate' \u27eao' | update_state', default_state'\u27eb oa s'\u2046 :=\neval_dist_simulate'_eq_eval_dist_simulate' (\u03bb 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  \u2045simulate' \u27eao | update_state, default_state\u27eb oa s\u2046 =\n    \u2045simulate' \u27eao | update_state', default_state'\u27eb oa s'\u2046 :=\neval_dist_simulate'_eq_eval_dist_simulate' o o _ _ _ _ oa s s' (\u03bb _ _, rfl)\n\nend eval_dist\n\nsection prob_event\n\nvariable (e : set \u03b1)\n\n@[simp] lemma prob_event_apply (e : set (spec.range i \u00d7 S)) :\n  \u2045e | \u27eao | update_state, default_state\u27eb i (t, s)\u2046 =\n    \u2045\u03bb u, (u, update_state s i t u) \u2208 e | o i t\u2046 :=\nby simpa only [apply_eq, prob_event_map]\n\nlemma prob_event_simulate'_eq_prob_event\n  (h : \u2200 i t, \u2045o i t\u2046 = pmf.uniform_of_fintype (spec.range i)) :\n  \u2045e | simulate' \u27eao | update_state, default_state\u27eb oa s\u2046 = \u2045e | oa\u2046 :=\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  \u2045e | simulate' \u27eaquery | update_state, default_state\u27eb oa s\u2046 = \u2045e | oa\u2046 :=\nprob_event_simulate'_eq_prob_event _ _ _ oa s e (\u03bb _ _, rfl)\n\nlemma prob_event_simulate'_eq_prob_event_simulate'\n  (h : \u2200 i t, o i t \u2243\u209a o' i t) : \u2045e | simulate' \u27eao | update_state, default_state\u27eb oa s\u2046 =\n    \u2045e | simulate' \u27eao' | update_state', default_state'\u27eb oa s'\u2046 :=\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  \u2045e | simulate' \u27eao | update_state, default_state\u27eb oa s\u2046 =\n    \u2045e | simulate' \u27eao | update_state', default_state'\u27eb oa s'\u2046 :=\nprob_event_simulate'_eq_prob_event_simulate' o o _ _ _ _ oa s s' e (\u03bb _ _, 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 ` \u2218 `:80 g:80 := g \u226b 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 \u27f6 y) : Prop := is_weq f\n\nlemma homotopic_iff_equal_in_ho {x y : C} {f g : x \u27f6 y} : f \u2243 g \u2194 \u27e6f\u27e7 = \u27e6g\u27e7 :=\nby symmetry; apply quotient.eq\n\nlemma homotopy_equivalence_iff {x y : C} {f : x \u27f6 y} :\n  homotopy_equivalence f \u2194 \u2203 g, g \u2218 f \u2243 \ud835\udfd9 _ \u2227 f \u2218 g \u2243 \ud835\udfd9 _ :=\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, \u2190hg] at this, exact this },\n    { have := i.inv_hom_id',\n      rw [hi, \u2190hg] at this, exact this } },\n  { intro h, rcases h with \u27e8g, h\u2081, h\u2082\u27e9,\n    refine \u27e8iso.mk \u27e6f\u27e7 \u27e6g\u27e7 _ _, rfl\u27e9;\n    { dsimp [auto_param], change \u27e6_\u27e7 = \u27e6_\u27e7, rw \u2190homotopic_iff_equal_in_ho,\n      exact h\u2081 <|> exact h\u2082 } }\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 \"\u2665\" a:\"\u2665\"? b:\"\u2665\"? : term => do\n  let nExpr : Expr \u2190 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 \u2665 -- 8\n#eval 7 \u2665\u2665 -- 9\n#eval 7 \u2665\u2665\u2665 -- 10\n\n/- ### 2. -/\n\n-- a) using `syntax` + `@[command_elab alias] def elabOurAlias : CommandElab`\nsyntax (name := aliasA) (docComment)? \"aliasA \" ident \" \u2190 \" ident* : command\n\n@[command_elab \u00abaliasA\u00bb]\ndef elabOurAlias : CommandElab := \u03bb stx =>\n  match stx with\n  | `(aliasA $x:ident \u2190 $ys:ident*) =>\n    for y in ys do\n      Lean.logInfo y\n  | _ =>\n    throwUnsupportedSyntax\n\naliasA hi.hello \u2190 d.d w.w nnn\n\n-- b) using `syntax` + `elab_rules`.\nsyntax (name := aliasB) (docComment)? \"aliasB \" ident \" \u2190 \" ident* : command\n\nelab_rules : command\n  | `(command | aliasB $m:ident \u2190 $ys:ident*) =>\n    for y in ys do\n      Lean.logInfo y\n\naliasB hi.hello \u2190 d.d w.w nnn\n\n-- c) using `elab`\nelab \"aliasC \" x:ident \" \u2190 \" ys:ident* : command =>\n  for y in ys do\n    Lean.logInfo y\n\naliasC hi.hello \u2190 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 [\u2190 add_zero] at h\n  nth_rewriteC 2 [\u2190 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 \u03b1] [Hashable \u03b1] (s : Lean.PHashSet \u03b1) : List \u03b1 :=\n  s.1.toList.map (\u00b7.1)\n\nnamespace Lean\n\nnamespace Meta.DiscrTree\n\npartial def Trie.getElements : Trie \u03b1 s \u2192 Array \u03b1\n  | Trie.node vs children =>\n    vs ++ children.concatMap fun (_, child) \u21a6 child.getElements\n\ndef getElements (d : DiscrTree \u03b1 s) : Array \u03b1 :=\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 (\u00b7.key)}\ntoUnfold: {s.toUnfold.toList}\nerased: {s.erased.toList.map (\u00b7.key)}\ntoUnfoldThms: {s.toUnfoldThms.toList}\"\n\ndef mkEqSymm (e : Expr) (r : Simp.Result) : MetaM Simp.Result :=\n  ({ expr := e, proof? := \u00b7 }) <$>\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 #[\u2190 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 (\u2190 getLCtx) do\n    unless localDecl.isAuxDecl do\n      if (\u2190 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 \u2190 mkDischargeWrapper stx[2]\n  let simpOnly := !stx[3].isNone\n  let simpTheorems \u2190 if simpOnly then\n    simpOnlyBuiltins.foldlM (\u00b7.addConst \u00b7) {}\n  else\n    pure simpTheorems\n  let congrTheorems \u2190 Meta.getSimpCongrTheorems\n  let r \u2190 elabSimpArgs stx[4] (eraseLocal := eraseLocal) (kind := kind) {\n    config       := (\u2190 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 \u2190 getPropHyps\n    for h in hs do\n      unless simpTheorems.isErased (.fvar h) do\n        simpTheorems \u2190 simpTheorems.addTheorem (.fvar h) (\u2190 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 \u00d7 Array SimpTheorem) := do\n  let cinfo \u2190 getConstInfo declName\n  let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n  withReducible do\n    let type \u2190 inferType val\n    checkTypeIsProp type\n    if inv || (\u2190 shouldPreprocess type) then\n      let mut r := #[]\n      let mut auxNames := #[]\n      for (val, type) in (\u2190 preprocess val type inv (isGlobal := true)) do\n        let auxName \u2190 mkAuxLemma cinfo.levelParams type val\n        auxNames := auxNames.push auxName\n        r := r.push <| \u2190 mkSimpTheoremCore (.decl declName)\n          (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio\n      return (auxNames, r)\n    else\n      return (#[], #[\u2190 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) \u2190 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 \u2190 getConstInfo declName\n  if (\u2190 isProp info.type) then\n    addSimpTheorem' ext declName post (inv := false) attrKind prio\n  else if info.hasValue then\n    if let some eqns \u2190 getEqnsFor? declName then\n      let mut auxNames := #[]\n      for eqn in eqns do\n        -- Is this list is always empty?\n        let newAuxNames \u2190 addSimpTheorem' ext eqn post (inv := false) attrKind prio\n        auxNames := auxNames ++ newAuxNames\n      ext.add (SimpEntry.toUnfoldThms declName eqns) attrKind\n      if hasSmartUnfoldingDecl (\u2190 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 \u2190 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 (\u00b7.addConst \u00b7) (\u2190 simpOnlyBuiltins.foldlM (\u00b7.addConst \u00b7) {})\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  (\u00b7.1) <$> simp e\n    { simpTheorems := #[\u2190 simpTheoremsOfNames lemmas], congrTheorems := \u2190 getSimpCongrTheorems,\n      config := config }\n\n/--\nGiven a simplifier `S : Expr \u2192 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 \u2192 MetaM Simp.Result) (e : Expr) : MetaM Expr := do\n  match (\u2190 S (\u2190 inferType e)) with\n  | \u27e8ty', none, _\u27e9 => mkExpectedTypeHint e ty'\n  -- We use `mkExpectedTypeHint` in this branch as well, in order to preserve the binder types.\n  | \u27e8ty', some prf, _\u27e9 => mkExpectedTypeHint (\u2190 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 \u2192 MetaM Simp.Result) (type pf : Expr) : MetaM (Expr \u00d7 Expr) := do\n  forallTelescope type fun fvars type => do\n    let .app (.app (.app (.const `Eq [u]) \u03b1) lhs) rhs := type | throwError \"simpEq expecting Eq\"\n    let \u27e8lhs', lhspf?, _\u27e9 \u2190 S lhs\n    let \u27e8rhs', rhspf?, _\u27e9 \u2190 S rhs\n    let mut pf' := mkAppN pf fvars\n    if let some lhspf := lhspf? then\n      pf' \u2190 mkEqTrans (\u2190 mkEqSymm lhspf) pf'\n    if let some rhspf := rhspf? then\n      pf' \u2190 mkEqTrans pf' rhspf\n    let type' := mkApp3 (mkConst ``Eq [u]) \u03b1 lhs' rhs'\n    return (\u2190 mkForallFVars fvars type', \u2190 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 \u2190 getSimpExtension? simpAttr | return false\n  return (\u2190 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 \u2190 getSimpExtension? simpAttr | return []\n  let thms \u2190 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 (\u2190 simpExtensionMapRef.get).toList do\n    if (\u2190 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) 2020 Sebastian Ullrich. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\n\nimport Lean.PrettyPrinter.Delaborator.Basic\nimport Lean.PrettyPrinter.Delaborator.SubExpr\nimport Lean.PrettyPrinter.Delaborator.TopDownAnalyze\nimport Lean.Parser\n\nnamespace Lean.PrettyPrinter.Delaborator\nopen Lean.Meta\nopen Lean.Parser.Term\nopen SubExpr\nopen TSyntax.Compat\n\ndef maybeAddBlockImplicit (ident : Syntax) : DelabM Syntax := do\n  if \u2190 getPPOption getPPAnalysisBlockImplicit then `(@$ident:ident) else pure ident\n\ndef unfoldMDatas : Expr \u2192 Expr\n  | Expr.mdata _ e => unfoldMDatas e\n  | e              => e\n\n@[builtin_delab fvar]\ndef delabFVar : Delab := do\nlet Expr.fvar fvarId \u2190 getExpr | unreachable!\ntry\n  let l \u2190 fvarId.getDecl\n  maybeAddBlockImplicit (mkIdent l.userName)\ncatch _ =>\n  -- loose free variable, use internal name\n  maybeAddBlockImplicit <| mkIdent fvarId.name\n\n-- loose bound variable, use pseudo syntax\n@[builtin_delab bvar]\ndef delabBVar : Delab := do\n  let Expr.bvar idx \u2190 getExpr | unreachable!\n  pure $ mkIdent $ Name.mkSimple $ \"#\" ++ toString idx\n\n@[builtin_delab mvar]\ndef delabMVar : Delab := do\n  let Expr.mvar n \u2190 getExpr | unreachable!\n  let mvarDecl \u2190 n.getDecl\n  let n :=\n    match mvarDecl.userName with\n    | Name.anonymous => n.name.replacePrefix `_uniq `m\n    | n => n\n  `(?$(mkIdent n))\n\n@[builtin_delab sort]\ndef delabSort : Delab := do\n  let Expr.sort l \u2190 getExpr | unreachable!\n  match l with\n  | Level.zero => `(Prop)\n  | Level.succ .zero => `(Type)\n  | _ => match l.dec with\n    | some l' => `(Type $(Level.quote l' max_prec))\n    | none    => `(Sort $(Level.quote l max_prec))\n\n\n-- NOTE: not a registered delaborator, as `const` is never called (see [delab] description)\ndef delabConst : Delab := do\n  let Expr.const c\u2080 ls \u2190 getExpr | unreachable!\n  let c\u2080 := if (\u2190 getPPOption getPPPrivateNames) then c\u2080 else (privateToUserName? c\u2080).getD c\u2080\n\n  let mut c \u2190 unresolveNameGlobal c\u2080 (fullNames := \u2190 getPPOption getPPFullNames)\n  let stx \u2190 if ls.isEmpty || !(\u2190 getPPOption getPPUniverses) then\n    if (\u2190 getLCtx).usesUserName c then\n      -- `c` is also a local declaration\n      if c == c\u2080 && !(\u2190 read).inPattern then\n        -- `c` is the fully qualified named. So, we append the `_root_` prefix\n        c := `_root_ ++ c\n      else\n        c := c\u2080\n    pure <| mkIdent c\n  else\n    `($(mkIdent c).{$[$(ls.toArray.map quote)],*})\n\n  let mut stx \u2190 maybeAddBlockImplicit stx\n  if (\u2190 getPPOption getPPTagAppFns) then\n    stx \u2190 annotateCurPos stx\n    addTermInfo (\u2190 getPos) stx (\u2190 getExpr)\n  return stx\n\ndef withMDataOptions [Inhabited \u03b1] (x : DelabM \u03b1) : DelabM \u03b1 := do\n  match \u2190 getExpr with\n  | Expr.mdata m .. =>\n    let mut posOpts := (\u2190 read).optionsPerPos\n    let pos \u2190 getPos\n    for (k, v) in m do\n      if (`pp).isPrefixOf k then\n        let opts := posOpts.find? pos |>.getD {}\n        posOpts := posOpts.insert pos (opts.insert k v)\n    withReader ({ \u00b7 with optionsPerPos := posOpts }) $ withMDataExpr x\n  | _ => x\n\npartial def withMDatasOptions [Inhabited \u03b1] (x : DelabM \u03b1) : DelabM \u03b1 := do\n  if (\u2190 getExpr).isMData then withMDataOptions (withMDatasOptions x) else x\n\ndef delabAppFn : Delab := do\n  if (\u2190 getExpr).consumeMData.isConst then\n    withMDatasOptions delabConst\n  else\n    delab\n\nstructure ParamKind where\n  name        : Name\n  bInfo       : BinderInfo\n  defVal      : Option Expr := none\n  isAutoParam : Bool := false\n\ndef ParamKind.isRegularExplicit (param : ParamKind) : Bool :=\n  param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone\n\n/-- Return array with n-th element set to kind of n-th parameter of `e`. -/\npartial def getParamKinds : DelabM (Array ParamKind) := do\n  let e \u2190 getExpr\n  try\n    withTransparency TransparencyMode.all do\n      forallTelescopeArgs e.getAppFn e.getAppArgs fun params _ => do\n        params.mapM fun param => do\n          let l \u2190 param.fvarId!.getDecl\n          pure { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam }\n  catch _ => pure #[] -- recall that expr may be nonsensical\nwhere\n  forallTelescopeArgs f args k := do\n    forallBoundedTelescope (\u2190 inferType f) args.size fun xs b =>\n      if xs.isEmpty || xs.size == args.size then\n        -- we still want to consider optParams\n        forallTelescopeReducing b fun ys b => k (xs ++ ys) b\n      else\n        forallTelescopeArgs (mkAppN f $ args.shrink xs.size) (args.extract xs.size args.size) fun ys b =>\n          k (xs ++ ys) b\n\n@[builtin_delab app]\ndef delabAppExplicit : Delab := do\n  let paramKinds \u2190 getParamKinds\n  let tagAppFn \u2190 getPPOption getPPTagAppFns\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (do\n      let stx \u2190 withOptionAtCurrPos `pp.tagAppFns tagAppFn delabAppFn\n      let needsExplicit := stx.raw.getKind != ``Lean.Parser.Term.explicit\n      let stx \u2190 if needsExplicit then `(@$stx) else pure stx\n      pure (stx, paramKinds.toList, #[]))\n    (fun \u27e8fnStx, paramKinds, argStxs\u27e9 => do\n      let isInstImplicit := match paramKinds with\n                            | [] => false\n                            | param :: _ => param.bInfo == BinderInfo.instImplicit\n      let argStx \u2190 if \u2190 getPPOption getPPAnalysisHole then `(_)\n                   else if isInstImplicit == true then\n                     let stx \u2190 if \u2190 getPPOption getPPInstances then delab else `(_)\n                     if \u2190 getPPOption getPPInstanceTypes then\n                       let typeStx \u2190 withType delab\n                       `(($stx : $typeStx))\n                     else pure stx\n                   else delab\n      pure (fnStx, paramKinds.tailD [], argStxs.push argStx))\n  return Syntax.mkApp fnStx argStxs\n\ndef shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do\n  pure (getPPMotivesAll opts)\n  <||> (pure (getPPMotivesPi opts) <&&> returnsPi motive)\n  <||> (pure (getPPMotivesNonConst opts) <&&> isNonConstFun motive)\n\ndef isRegularApp : DelabM Bool := do\n  let e \u2190 getExpr\n  if not (unfoldMDatas e.getAppFn).isConst then return false\n  if \u2190 withNaryFn (withMDatasOptions (getPPOption getPPUniverses <||> getPPOption getPPAnalysisBlockImplicit)) then return false\n  for i in [:e.getAppNumArgs] do\n    if \u2190 withNaryArg i (getPPOption getPPAnalysisNamedArg) then return false\n  return true\n\ndef unexpandRegularApp (stx : Syntax) : Delab := do\n  let Expr.const c .. := (unfoldMDatas (\u2190 getExpr).getAppFn) | unreachable!\n  let fs := appUnexpanderAttribute.getValues (\u2190 getEnv) c\n  let ref \u2190 getRef\n  fs.firstM fun f =>\n    match f stx |>.run ref |>.run () with\n    | EStateM.Result.ok stx _ => pure stx\n    | _ => failure\n\ndef unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do\n  let env \u2190 getEnv\n  let e \u2190 getExpr\n  let some s \u2190 pure $ e.isConstructorApp? env | failure\n  guard $ isStructure env s.induct;\n  /- If implicit arguments should be shown, and the structure has parameters, we should not\n     pretty print using { ... }, because we will not be able to see the parameters. -/\n  let fieldNames := getStructureFields env s.induct\n  let mut fields := #[]\n  guard $ fieldNames.size == stx[1].getNumArgs\n  let args := e.getAppArgs\n  let fieldVals := args.extract s.numParams args.size\n  for idx in [:fieldNames.size] do\n    let fieldName := fieldNames[idx]!\n    let fieldId := mkIdent fieldName\n    let fieldPos \u2190 nextExtraPos\n    let fieldId := annotatePos fieldPos fieldId\n    addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx]!\n    let field \u2190 `(structInstField|$fieldId:ident := $(stx[1][idx]))\n    fields := fields.push field\n  let tyStx \u2190 withType do\n    if (\u2190 getPPOption getPPStructureInstanceType) then delab >>= pure \u2218 some else pure none\n  `({ $fields,* $[: $tyStx]? })\n\n@[builtin_delab app]\ndef delabAppImplicit : Delab := do\n  -- TODO: always call the unexpanders, make them guard on the right # args?\n  let paramKinds \u2190 getParamKinds\n  if \u2190 getPPOption getPPExplicit then\n    if paramKinds.any (fun param => !param.isRegularExplicit) then failure\n\n  -- If the application has an implicit function type, fall back to delabAppExplicit.\n  -- This is e.g. necessary for `@Eq`.\n  let isImplicitApp \u2190 try\n      let ty \u2190 whnf (\u2190 inferType (\u2190 getExpr))\n      pure <| ty.isForall && (ty.binderInfo == BinderInfo.implicit || ty.binderInfo == BinderInfo.instImplicit)\n    catch _ => pure false\n  if isImplicitApp then failure\n\n  let tagAppFn \u2190 getPPOption getPPTagAppFns\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (withOptionAtCurrPos `pp.tagAppFns tagAppFn <|\n      return (\u2190 delabAppFn, paramKinds.toList, #[]))\n    (fun (fnStx, paramKinds, argStxs) => do\n      let arg \u2190 getExpr\n      let opts \u2190 getOptions\n      let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do\n        `(Parser.Term.namedArgument| ($(mkIdent name) := $argStx))\n      let argStx? : Option Syntax \u2190\n        if \u2190 getPPOption getPPAnalysisSkip then pure none\n        else if \u2190 getPPOption getPPAnalysisHole then `(_)\n        else\n          match paramKinds with\n          | [] => delab\n          | param :: rest =>\n            if param.defVal.isSome && rest.isEmpty then\n              let v := param.defVal.get!\n              if !v.hasLooseBVars && v == arg then pure none else delab\n            else if !param.isRegularExplicit && param.defVal.isNone then\n              if \u2190 getPPOption getPPAnalysisNamedArg <||> (pure (param.name == `motive) <&&> shouldShowMotive arg opts) then some <$> mkNamedArg param.name (\u2190 delab) else pure none\n            else delab\n      let argStxs := match argStx? with\n        | none => argStxs\n        | some stx => argStxs.push stx\n      pure (fnStx, paramKinds.tailD [], argStxs))\n  let stx := Syntax.mkApp fnStx argStxs\n\n  if \u2190 isRegularApp then\n    (guard (\u2190 getPPOption getPPNotation) *> unexpandRegularApp stx)\n    <|> (guard (\u2190 getPPOption getPPStructureInstances) *> unexpandStructureInstance stx)\n    <|> pure stx\n  else pure stx\n\n/-- State for `delabAppMatch` and helpers. -/\nstructure AppMatchState where\n  info        : MatcherInfo\n  matcherTy   : Expr\n  params      : Array Expr := #[]\n  motive      : Option (Term \u00d7 Expr) := none\n  motiveNamed : Bool := false\n  discrs      : Array Term := #[]\n  varNames    : Array (Array Name) := #[]\n  rhss        : Array Term := #[]\n  -- additional arguments applied to the result of the `match` expression\n  moreArgs    : Array Term := #[]\n/--\n  Extract arguments of motive applications from the matcher type.\n  For the example below: `#[#[`([])], #[`(a::as)]]` -/\nprivate partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Term)) :=\n  withReader (fun ctx => { ctx with inPattern := true, optionsPerPos := {} }) do\n    let ty \u2190 instantiateForall st.matcherTy st.params\n    -- need to reduce `let`s that are lifted into the matcher type\n    forallTelescopeReducing ty fun params _ => do\n      -- skip motive and discriminators\n      let alts := Array.ofSubarray params[1 + st.discrs.size:]\n      alts.mapIdxM fun idx alt => do\n        let ty \u2190 inferType alt\n        -- TODO: this is a hack; we are accessing the expression out-of-sync with the position\n        -- Currently, we reset `optionsPerPos` at the beginning of `delabPatterns` to avoid\n        -- incorrectly considering annotations.\n        withTheReader SubExpr ({ \u00b7 with expr := ty }) $\n          usingNames st.varNames[idx]! do\n            withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (\u2190 delab))\nwhere\n  usingNames {\u03b1} (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    usingNamesAux 0 varNames x\n  usingNamesAux {\u03b1} (i : Nat) (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    if i < varNames.size then\n      withBindingBody varNames[i]! <| usingNamesAux (i+1) varNames x\n    else\n      x\n\n/-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/\nprivate partial def skippingBinders {\u03b1} (numParams : Nat) (x : Array Name \u2192 DelabM \u03b1) : DelabM \u03b1 :=\n  loop numParams #[]\nwhere\n  loop : Nat \u2192 Array Name \u2192 DelabM \u03b1\n    | 0,   varNames => x varNames\n    | n+1, varNames => do\n      let rec visitLambda : DelabM \u03b1 := do\n        let varName := (\u2190 getExpr).bindingName!.eraseMacroScopes\n        -- Pattern variables cannot shadow each other\n        if varNames.contains varName then\n          let varName := (\u2190 getLCtx).getUnusedName varName\n          withBindingBody varName do\n            loop n (varNames.push varName)\n        else\n          withBindingBodyUnusedName fun id => do\n            loop n (varNames.push id.getId)\n      let e \u2190 getExpr\n      if e.isLambda then\n        visitLambda\n      else\n        -- eta expand `e`\n        let e \u2190 forallTelescopeReducing (\u2190 inferType e) fun xs _ => do\n          if xs.size == 1 && (\u2190 inferType xs[0]!).isConstOf ``Unit then\n            -- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable.\n            -- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable.\n            -- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure\n            -- it adds an annotation to distinguish these two cases.\n            mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit))\n          else\n            mkLambdaFVars xs (mkAppN e xs)\n        withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda\n\n/--\n  Delaborate applications of \"matchers\" such as\n  ```\n  List.map.match_1 : {\u03b1 : Type _} \u2192\n    (motive : List \u03b1 \u2192 Sort _) \u2192\n      (x : List \u03b1) \u2192 (Unit \u2192 motive List.nil) \u2192 ((a : \u03b1) \u2192 (as : List \u03b1) \u2192 motive (a :: as)) \u2192 motive x\n  ```\n-/\n@[builtin_delab app]\ndef delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do\n  -- incrementally fill `AppMatchState` from arguments\n  let st \u2190 withAppFnArgs\n    (do\n      let (Expr.const c us) \u2190 getExpr | failure\n      let (some info) \u2190 getMatcherInfo? c | failure\n      let matcherTy \u2190 instantiateTypeLevelParams (\u2190 getConstInfo c) us\n      return { matcherTy, info : AppMatchState })\n    (fun st => do\n      if st.params.size < st.info.numParams then\n        return { st with params := st.params.push (\u2190 getExpr) }\n      else if st.motive.isNone then\n        -- store motive argument separately\n        let lamMotive \u2190 getExpr\n        let piMotive \u2190 lambdaTelescope lamMotive fun xs body => mkForallFVars xs body\n        -- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive`\n        -- Thus the binder types won't have any annotations\n        let piStx \u2190 withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab\n        let named \u2190 getPPOption getPPAnalysisNamedArg\n        return { st with motive := (piStx, lamMotive), motiveNamed := named }\n      else if st.discrs.size < st.info.numDiscrs then\n        let idx := st.discrs.size\n        let discr \u2190 delab\n        if let some hName := st.info.discrInfos[idx]!.hName? then\n          -- TODO: we should check whether the corresponding binder name, matches `hName`.\n          -- If it does not we should pretty print this `match` as a regular application.\n          return { st with discrs := st.discrs.push (\u2190 `(matchDiscr| $(mkIdent hName) : $discr)) }\n        else\n          return { st with discrs := st.discrs.push (\u2190 `(matchDiscr| $discr:term)) }\n      else if st.rhss.size < st.info.altNumParams.size then\n        /- We save the variables names here to be able to implement safe_shadowing.\n           The pattern delaboration must use the names saved here. -/\n        let (varNames, rhs) \u2190 skippingBinders st.info.altNumParams[st.rhss.size]! fun varNames => do\n          let rhs \u2190 delab\n          return (varNames, rhs)\n        return { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }\n      else\n        return { st with moreArgs := st.moreArgs.push (\u2190 delab) })\n\n  if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then\n    -- underapplied\n    failure\n\n  match st.discrs, st.rhss with\n  | #[discr], #[] =>\n    let stx \u2190 `(nomatch $discr)\n    return Syntax.mkApp stx st.moreArgs\n  | _,        #[] => failure\n  | _,        _   =>\n    let pats \u2190 delabPatterns st\n    let stx \u2190 do\n      let (piStx, lamMotive) := st.motive.get!\n      let opts \u2190 getOptions\n      -- TODO: disable the match if other implicits are needed?\n      if \u2190 pure st.motiveNamed <||> shouldShowMotive lamMotive opts then\n        `(match (motive := $piStx) $[$st.discrs:matchDiscr],* with $[| $pats,* => $st.rhss]*)\n      else\n        `(match $[$st.discrs:matchDiscr],* with $[| $pats,* => $st.rhss]*)\n    return Syntax.mkApp stx st.moreArgs\n\n/--\n  Delaborate applications of the form `(fun x => b) v` as `let_fun x := v; b`\n-/\ndef delabLetFun : Delab := do\n  let stxV \u2190 withAppArg delab\n  withAppFn do\n    let Expr.lam n _ b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxB \u2190 withBindingBody n delab\n    if \u2190 getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then\n      let stxT \u2190 withBindingDomain delab\n      `(let_fun $(mkIdent n) : $stxT := $stxV; $stxB)\n    else\n      `(let_fun $(mkIdent n) := $stxV; $stxB)\n\n@[builtin_delab mdata]\ndef delabMData : Delab := do\n  if let some _ := inaccessible? (\u2190 getExpr) then\n    let s \u2190 withMDataExpr delab\n    if (\u2190 read).inPattern then\n      `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns\n    else\n      return s\n  else if isLetFun (\u2190 getExpr) && getPPNotation (\u2190 getOptions) then\n    withMDataExpr <| delabLetFun\n  else if let some _ := isLHSGoal? (\u2190 getExpr) then\n    withMDataExpr <| withAppFn <| withAppArg <| delab\n  else\n    withMDataOptions delab\n\n/--\nCheck for a `Syntax.ident` of the given name anywhere in the tree.\nThis is usually a bad idea since it does not check for shadowing bindings,\nbut in the delaborator we assume that bindings are never shadowed.\n-/\npartial def hasIdent (id : Name) : Syntax \u2192 Bool\n  | Syntax.ident _ _ id' _ => id == id'\n  | Syntax.node _ _ args   => args.any (hasIdent id)\n  | _                      => false\n\n/--\nReturn `true` iff current binder should be merged with the nested\nbinder, if any, into a single binder group:\n* both binders must have same binder info and domain\n* they cannot be inst-implicit (`[a b : A]` is not valid syntax)\n* `pp.binderTypes` must be the same value for both terms\n* prefer `fun a b` over `fun (a b)`\n-/\nprivate def shouldGroupWithNext : DelabM Bool := do\n  let e \u2190 getExpr\n  let ppEType \u2190 getPPOption (getPPBinderTypes e)\n  let go (e' : Expr) := do\n    let ppE'Type \u2190 withBindingBody `_ $ getPPOption (getPPBinderTypes e)\n    pure $ e.binderInfo == e'.binderInfo &&\n      e.bindingDomain! == e'.bindingDomain! &&\n      e'.binderInfo != BinderInfo.instImplicit &&\n      ppEType == ppE'Type &&\n      (e'.binderInfo != BinderInfo.default || ppE'Type)\n  match e with\n  | Expr.lam _ _     e'@(Expr.lam _ _ _ _) _     => go e'\n  | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'\n  | _ => pure false\nwhere\n  getPPBinderTypes (e : Expr) :=\n    if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes\n\nprivate partial def delabBinders (delabGroup : Array Syntax \u2192 Syntax \u2192 Delab) : optParam (Array Syntax) #[] \u2192 Delab\n  -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished\n  -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping\n  -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.\n  | curNames => do\n    if \u2190 shouldGroupWithNext then\n      -- group with nested binder => recurse immediately\n      withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)\n    else\n      -- don't group => delab body and prepend current binder group\n      let (stx, stxN) \u2190 withBindingBodyUnusedName fun stxN => return (\u2190 delab, stxN)\n      delabGroup (curNames.push stxN) stx\n\n@[builtin_delab lam]\ndef delabLam : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let stxT \u2190 withBindingDomain delab\n    let ppTypes \u2190 getPPOption getPPFunBinderTypes\n    let usedDownstream := curNames.any (fun n => hasIdent n.getId stxBody)\n\n    -- leave lambda implicit if possible\n    -- TODO: for now we just always block implicit lambdas when delaborating. We can revisit.\n    -- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit,\n    -- it doesn't seem like we can leave a subsequent binder implicit.\n    let blockImplicitLambda := true\n    /-\n    let blockImplicitLambda := expl ||\n      e.binderInfo == BinderInfo.default ||\n      -- Note: the following restriction fixes many issues with roundtripping,\n      -- but this condition may still not be perfectly in sync with the elaborator.\n      e.binderInfo == BinderInfo.instImplicit ||\n      Elab.Term.blockImplicitLambda stxBody ||\n      usedDownstream\n    -/\n\n    if !blockImplicitLambda then\n      pure stxBody\n    else\n      let defaultCase (_ : Unit) : Delab := do\n        if ppTypes then\n          -- \"default\" binder group is the only one that expects binder names\n          -- as a term, i.e. a single `Syntax.ident` or an application thereof\n          let stxCurNames \u2190\n            if curNames.size > 1 then\n              `($(curNames.get! 0) $(curNames.eraseIdx 0)*)\n            else\n              pure $ curNames.get! 0;\n          `(funBinder| ($stxCurNames : $stxT))\n        else\n          pure curNames.back  -- here `curNames.size == 1`\n      let group \u2190 match e.binderInfo, ppTypes with\n        | BinderInfo.default,        _      => defaultCase ()\n        | BinderInfo.implicit,       true   => `(funBinder| {$curNames* : $stxT})\n        | BinderInfo.implicit,       false  => `(funBinder| {$curNames*})\n        | BinderInfo.strictImplicit, true   => `(funBinder| \u2983$curNames* : $stxT\u2984)\n        | BinderInfo.strictImplicit, false  => `(funBinder| \u2983$curNames*\u2984)\n        | BinderInfo.instImplicit,   _     =>\n          if usedDownstream then `(funBinder| [$curNames.back : $stxT])  -- here `curNames.size == 1`\n          else  `(funBinder| [$stxT])\n      let (binders, stxBody) :=\n        match stxBody with\n        | `(fun $binderGroups* => $stxBody) => (#[group] ++ binderGroups, stxBody)\n        | _                                 => (#[group], stxBody)\n      if \u2190 getPPOption getPPUnicodeFun then\n        `(fun $binders* \u21a6 $stxBody)\n      else\n        `(fun $binders* => $stxBody)\n\n/--\nSimilar to `delabBinders`, but tracking whether `forallE` is dependent or not.\n\nSee issue #1571\n-/\nprivate partial def delabForallBinders (delabGroup : Array Syntax \u2192 Bool \u2192 Syntax \u2192 Delab) (curNames : Array Syntax := #[]) (curDep := false) : Delab := do\n  let dep := !(\u2190 getExpr).isArrow\n  if !curNames.isEmpty && dep != curDep then\n    -- don't group\n    delabGroup curNames curDep (\u2190 delab)\n  else\n    let curDep := dep\n    if \u2190 shouldGroupWithNext then\n      -- group with nested binder => recurse immediately\n      withBindingBodyUnusedName fun stxN => delabForallBinders delabGroup (curNames.push stxN) curDep\n    else\n      -- don't group => delab body and prepend current binder group\n      let (stx, stxN) \u2190 withBindingBodyUnusedName fun stxN => return (\u2190 delab, stxN)\n      delabGroup (curNames.push stxN) curDep stx\n\n@[builtin_delab forallE]\ndef delabForall : Delab := do\n  delabForallBinders fun curNames dependent stxBody => do\n    let e \u2190 getExpr\n    let prop \u2190 try isProp e catch _ => pure false\n    let stxT \u2190 withBindingDomain delab\n    let group \u2190 match e.binderInfo with\n    | BinderInfo.implicit       => `(bracketedBinderF|{$curNames* : $stxT})\n    | BinderInfo.strictImplicit => `(bracketedBinderF|\u2983$curNames* : $stxT\u2984)\n    -- here `curNames.size == 1`\n    | BinderInfo.instImplicit   => `(bracketedBinderF|[$curNames.back : $stxT])\n    | _                         =>\n      -- NOTE: non-dependent arrows are available only for the default binder info\n      if dependent then\n        if prop && !(\u2190 getPPOption getPPPiBinderTypes) then\n          return \u2190 `(\u2200 $curNames:ident*, $stxBody)\n        else\n          `(bracketedBinderF|($curNames* : $stxT))\n      else\n        return \u2190 curNames.foldrM (fun _ stxBody => `($stxT \u2192 $stxBody)) stxBody\n    if prop then\n      match stxBody with\n      | `(\u2200 $groups*, $stxBody) => `(\u2200 $group $groups*, $stxBody)\n      | _                       => `(\u2200 $group, $stxBody)\n    else\n      `($group:bracketedBinder \u2192 $stxBody)\n\n@[builtin_delab letE]\ndef delabLetE : Delab := do\n  let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n  let n \u2190 getUnusedName n b\n  let stxV \u2190 descend v 1 delab\n  let stxB \u2190 withLetDecl n t v fun fvar =>\n    let b := b.instantiate1 fvar\n    descend b 2 delab\n  if \u2190 getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then\n    let stxT \u2190 descend t 0 delab\n    `(let $(mkIdent n) : $stxT := $stxV; $stxB)\n  else `(let $(mkIdent n) := $stxV; $stxB)\n\n@[builtin_delab lit]\ndef delabLit : Delab := do\n  let Expr.lit l \u2190 getExpr | unreachable!\n  match l with\n  | Literal.natVal n => pure $ quote n\n  | Literal.strVal s => pure $ quote s\n\n-- `@OfNat.ofNat _ n _` ~> `n`\n@[builtin_delab app.OfNat.ofNat]\ndef delabOfNat : Delab := whenPPOption getPPCoercions do\n  let .app (.app _ (.lit (.natVal n))) _ \u2190 getExpr | failure\n  return quote n\n\n-- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true`\n@[builtin_delab app.OfScientific.ofScientific]\ndef delabOfScientific : Delab := whenPPOption getPPCoercions do\n  let expr \u2190 getExpr\n  guard <| expr.getAppNumArgs == 5\n  let .lit (.natVal m) \u2190 pure (expr.getArg! 2) | failure\n  let .lit (.natVal e) \u2190 pure (expr.getArg! 4) | failure\n  let s \u2190 match expr.getArg! 3 with\n    | Expr.const ``Bool.true _  => pure true\n    | Expr.const ``Bool.false _ => pure false\n    | _ => failure\n  let str  := toString m\n  if s && e == str.length then\n    return Syntax.mkScientificLit (\"0.\" ++ str)\n  else if s && e < str.length then\n    let mStr := str.extract 0 \u27e8str.length - e\u27e9\n    let eStr := str.extract \u27e8str.length - e\u27e9 \u27e8str.length\u27e9\n    return Syntax.mkScientificLit (mStr ++ \".\" ++ eStr)\n  else\n    return Syntax.mkScientificLit (str ++ \"e\" ++ (if s then \"-\" else \"\") ++ toString e)\n\n/--\nDelaborate a projection primitive. These do not usually occur in\nuser code, but are pretty-printed when e.g. `#print`ing a projection\nfunction.\n-/\n@[builtin_delab proj]\ndef delabProj : Delab := do\n  let Expr.proj _ idx _ \u2190 getExpr | unreachable!\n  let e \u2190 withProj delab\n  -- not perfectly authentic: elaborates to the `idx`-th named projection\n  -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual\n  -- `proj`.\n  let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1));\n  `($(e).$idx:fieldIdx)\n\n/-- Delaborate a call to a projection function such as `Prod.fst`. -/\n@[builtin_delab app]\ndef delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do\n  let e@(Expr.app fn _) \u2190 getExpr | failure\n  let .const c@(.str _ f) _ \u2190 pure fn.getAppFn | failure\n  let env \u2190 getEnv\n  let some info \u2190 pure $ env.getProjectionFnInfo? c | failure\n  -- can't use with classes since the instance parameter is implicit\n  guard $ !info.fromClass\n  -- projection function should be fully applied (#struct params + 1 instance parameter)\n  -- TODO: support over-application\n  guard $ e.getAppNumArgs == info.numParams + 1\n  -- If pp.explicit is true, and the structure has parameters, we should not\n  -- use field notation because we will not be able to see the parameters.\n  let expl \u2190 getPPOption getPPExplicit\n  guard $ !expl || info.numParams == 0\n  let appStx \u2190 withAppArg delab\n  `($(appStx).$(mkIdent f):ident)\n\n@[builtin_delab app.dite]\ndef delabDIte : Delab := whenPPOption getPPNotation do\n  -- Note: we keep this as a delaborator for now because it actually accesses the expression.\n  guard $ (\u2190 getExpr).getAppNumArgs == 5\n  let c \u2190 withAppFn $ withAppFn $ withAppFn $ withAppArg delab\n  let (t, h) \u2190 withAppFn $ withAppArg $ delabBranch none\n  let (e, _) \u2190 withAppArg $ delabBranch h\n  `(if $(mkIdent h):ident : $c then $t else $e)\nwhere\n  delabBranch (h? : Option Name) : DelabM (Syntax \u00d7 Name) := do\n    let e \u2190 getExpr\n    guard e.isLambda\n    let h \u2190 match h? with\n      | some h => return (\u2190 withBindingBody h delab, h)\n      | none   => withBindingBodyUnusedName fun h => do\n        return (\u2190 delab, h.getId)\n\n@[builtin_delab app.cond]\ndef delabCond : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 4\n  let c \u2190 withAppFn $ withAppFn $ withAppArg delab\n  let t \u2190 withAppFn $ withAppArg delab\n  let e \u2190 withAppArg delab\n  `(bif $c then $t else $e)\n\n@[builtin_delab app.namedPattern]\ndef delabNamedPattern : Delab := do\n  -- Note: we keep this as a delaborator because it accesses the DelabM context\n  guard (\u2190 read).inPattern\n  guard $ (\u2190 getExpr).getAppNumArgs == 4\n  let x \u2190 withAppFn $ withAppFn $ withAppArg delab\n  let p \u2190 withAppFn $ withAppArg delab\n  -- TODO: we should hide `h` if it has an inaccessible name and is not used in the rhs\n  let h \u2190 withAppArg delab\n  guard x.raw.isIdent\n  `($x:ident@$h:ident:$p:term)\n\n-- Sigma and PSigma delaborators\ndef delabSigmaCore (sigma : Bool) : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 2\n  guard $ (\u2190 getExpr).appArg!.isLambda\n  withAppArg do\n    let \u03b1 \u2190 withBindingDomain delab\n    let bodyExpr := (\u2190 getExpr).bindingBody!\n    withBindingBodyUnusedName fun n => do\n      let b \u2190 delab\n      if bodyExpr.hasLooseBVars then\n        if sigma then `(($n:ident : $\u03b1) \u00d7 $b) else `(($n:ident : $\u03b1) \u00d7' $b)\n      else\n        if sigma then `((_ : $\u03b1) \u00d7 $b) else `((_ : $\u03b1) \u00d7' $b)\n\n@[builtin_delab app.Sigma]\ndef delabSigma : Delab := delabSigmaCore (sigma := true)\n\n@[builtin_delab app.PSigma]\ndef delabPSigma : Delab := delabSigmaCore (sigma := false)\n\npartial def delabDoElems : DelabM (List Syntax) := do\n  let e \u2190 getExpr\n  if e.isAppOfArity ``Bind.bind 6 then\n    -- Bind.bind.{u, v} : {m : Type u \u2192 Type v} \u2192 [self : Bind m] \u2192 {\u03b1 \u03b2 : Type u} \u2192 m \u03b1 \u2192 (\u03b1 \u2192 m \u03b2) \u2192 m \u03b2\n    let \u03b1 := e.getAppArgs[2]!\n    let ma \u2190 withAppFn $ withAppArg delab\n    withAppArg do\n      match (\u2190 getExpr) with\n      | Expr.lam _ _ body _ =>\n        withBindingBodyUnusedName fun n => do\n          if body.hasLooseBVars then\n            prependAndRec `(doElem|let $n:term \u2190 $ma:term)\n          else if \u03b1.isConstOf ``Unit || \u03b1.isConstOf ``PUnit then\n            prependAndRec `(doElem|$ma:term)\n          else\n            prependAndRec `(doElem|let _ \u2190 $ma:term)\n      | _ => failure\n  else if e.isLet then\n    let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxT \u2190 descend t 0 delab\n    let stxV \u2190 descend v 1 delab\n    withLetDecl n t v fun fvar =>\n      let b := b.instantiate1 fvar\n      descend b 2 $\n        prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV)\n  else\n    let stx \u2190 delab\n    return [\u2190 `(doElem|$stx:term)]\n  where\n    prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems\n\n@[builtin_delab app.Bind.bind]\ndef delabDo : Delab := whenPPOption getPPNotation do\n  guard <| (\u2190 getExpr).isAppOfArity ``Bind.bind 6\n  let elems \u2190 delabDoElems\n  let items \u2190 elems.toArray.mapM (`(doSeqItem|$(\u00b7):doElem))\n  `(do $items:doSeqItem*)\n\ndef reifyName : Expr \u2192 DelabM Name\n  | .const ``Lean.Name.anonymous .. => return Name.anonymous\n  | .app (.app (.const ``Lean.Name.str ..) n) (.lit (.strVal s)) => return (\u2190 reifyName n).mkStr s\n  | .app (.app (.const ``Lean.Name.num ..) n) (.lit (.natVal i)) => return (\u2190 reifyName n).mkNum i\n  | _ => failure\n\n@[builtin_delab app.Lean.Name.str]\ndef delabNameMkStr : Delab := whenPPOption getPPNotation do\n  let n \u2190 reifyName (\u2190 getExpr)\n  -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version\n  return mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{n}\"]\n\n@[builtin_delab app.Lean.Name.num]\ndef delabNameMkNum : Delab := delabNameMkStr\n\nopen Parser Command Term in\n@[run_builtin_parser_attribute_hooks]\n-- use `termParser` instead of `declId` so we can reuse `delabConst`\ndef declSigWithId := leading_parser termParser maxPrec >> declSig\n\nprivate unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax :=\n  env.evalConstCheck Syntax opts ``Syntax constName\n\n@[implemented_by evalSyntaxConstantUnsafe]\nprivate opaque evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw \"\"\n\n/-- Pretty-prints a constant `c` as `c.{<levels>} <params> : <type>`. -/\npartial def delabConstWithSignature : Delab := do\n  let e \u2190 getExpr\n  -- use virtual expression node of arity 2 to separate name and type info\n  let idStx \u2190 descend e 0 <|\n    withOptions (pp.universes.set \u00b7 true |> (pp.fullNames.set \u00b7 true)) <|\n      delabConst\n  descend (\u2190 inferType e) 1 <|\n    delabParams idStx #[] #[]\nwhere\n  -- follows `delabBinders`, but does not uniquify binder names and accumulates all binder groups\n  delabParams (idStx : Ident) (groups : TSyntaxArray ``bracketedBinder) (curIds : Array Ident) := do\n    if let .forallE n d _ i \u2190 getExpr then\n      let stxN \u2190 annotateCurPos (mkIdent n)\n      let curIds := curIds.push \u27e8stxN\u27e9\n      if \u2190 shouldGroupWithNext then\n        withBindingBody n <| delabParams idStx groups curIds\n      else\n        let delabTy := withOptions (pp.piBinderTypes.set \u00b7 true) delab\n        let group \u2190 withBindingDomain do\n          match i with\n          | .implicit       => `(bracketedBinderF|{$curIds* : $(\u2190 delabTy)})\n          | .strictImplicit => `(bracketedBinderF|\u2983$curIds* : $(\u2190 delabTy)\u2984)\n          | .instImplicit   => `(bracketedBinderF|[$curIds.back : $(\u2190 delabTy)])\n          | _ =>\n            if d.isOptParam then\n              `(bracketedBinderF|($curIds* : $(\u2190 withAppFn <| withAppArg delabTy) := $(\u2190 withAppArg delabTy)))\n            else if let some (.const tacticDecl _) := d.getAutoParamTactic? then\n              let tacticSyntax \u2190 ofExcept <| evalSyntaxConstant (\u2190 getEnv) (\u2190 getOptions) tacticDecl\n              `(bracketedBinderF|($curIds* : $(\u2190 withAppFn <| withAppArg delabTy) := by $tacticSyntax))\n            else\n              `(bracketedBinderF|($curIds* : $(\u2190 delabTy)))\n        withBindingBody n <| delabParams idStx (groups.push group) #[]\n    else\n      let type \u2190 delab\n      `(declSigWithId| $idStx:ident $groups* : $type)\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/Builtins.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.05261895223347499, "lm_q1q2_score": 0.01548128356661748}}
{"text": "/-\nCopyright (c) 2023 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport REPL.JSON\nimport REPL.Frontend\nimport REPL.InfoTree\n\n/-!\n# A REPL for Lean.\n\nCommunicates via JSON on stdin and stdout. Commands should be separated by blank lines.\n\nCommands may be of the form\n```\n{ \"cmd\" : \"import Mathlib.Data.List.Basic\\ndef f := 2\" }\n```\nor\n```\n{ \"cmd\" : \"example : f = 2 := rfl\", \"env\" : 3 }\n```\n\nThe `env` field, if present,\nmust contain a number received in the `env` field of a previous response,\nand causes the command to be run in the existing environment.\n\nIf there is no `env` field, a new environment is created.\n\nYou can only use `import` commands when you do not specify the `env` field.\n\nYou can backtrack simply by using earlier values for `env`.\n\nThe results are of the form\n```\n{\"sorries\":\n [{\"pos\": {\"line\": 1, \"column\": 18},\n   \"endPos\": {\"line\": 1, \"column\": 23},\n   \"goal\": \"\\n\u22a2 Nat\"}],\n \"messages\":\n [{\"severity\": \"error\",\n   \"pos\": {\"line\": 1, \"column\": 23},\n   \"endPos\": {\"line\": 1, \"column\": 26},\n   \"data\":\n   \"type mismatch\\n  rfl\\nhas type\\n  f = f : Prop\\nbut is expected to have type\\n  f = 2 : Prop\"}],\n \"env\": 6}\n ```\n showing any messages generated, or sorries with their goal states.\n Information is generated for tactic mode sorries, but not for term mode sorries.\n-/\n\nopen Lean Elab\n\nnamespace REPL\n\n/-- The monadic state for the Lean REPL. -/\nstructure State where\n  environments : Array Environment\n  lines : Array Nat\n\n/-- The Lean REPL monad. -/\nabbrev M (m : Type \u2192 Type) := StateT State m\n\nvariable [Monad m] [MonadLiftT IO m]\n\n/-- Get the next available id for a new environment. -/\ndef nextId : M m Nat := do pure (\u2190 get).environments.size\n\n/-- Run a command, returning the id of the new environment, and any messages and sorries. -/\nunsafe def run (s : Run) : M m Response := do\n  let env? := s.env.bind ((\u2190 get).environments[\u00b7]?)\n  let (env, messages, trees) \u2190 IO.processInput s.cmd env? {} \"\"\n  let messages \u2190 messages.mapM fun m => Message.of m\n  let sorries \u2190 trees.bind InfoTree.sorries |>.mapM\n    fun \u27e8ctx, g, pos, endPos\u27e9 => Sorry.of ctx g pos endPos\n  let lines := s.cmd.splitOn \"\\n\" |>.length\n  let id \u2190 nextId\n  modify fun s => { environments := s.environments.push env, lines := s.lines.push lines }\n  pure \u27e8id, messages, sorries\u27e9\n\nend REPL\n\nopen REPL\n\n/-- Get lines from stdin until a blank line is entered. -/\nunsafe def getLines : IO String := do\n  match (\u2190 (\u2190 IO.getStdin).getLine) with\n  | \"\" => pure \"\"\n  | \"\\n\" => pure \"\\n\"\n  | line => pure <| line ++ (\u2190 getLines)\n\n/-- Read-eval-print loop for Lean. -/\nunsafe def repl : IO Unit :=\n  StateT.run' loop \u27e8#[], #[]\u27e9\nwhere loop : M IO Unit := do\n  let query \u2190 getLines\n  if query = \"\" then\n    return ()\n  let json := Json.parse query\n  match json with\n  | .error e => IO.println <| toString <| toJson (\u27e8e\u27e9 : Error)\n  | .ok j => match fromJson? j with\n    | .error e => IO.println <| toString <| toJson (\u27e8e\u27e9 : Error)\n    | .ok (r : Run) => IO.println <| toString <| toJson (\u2190 run r)\n  loop\n\n/-- Main executable function, run as `lake env lean --run Mathlib/Util/REPL.lean`. -/\nunsafe def main (_ : List String) : IO Unit := do\n  repl\n", "meta": {"author": "leanprover-community", "repo": "repl", "sha": "b42f6399946459f96ac50bbfd6cf1fb9a1f807ae", "save_path": "github-repos/lean/leanprover-community-repl", "path": "github-repos/lean/leanprover-community-repl/repl-b42f6399946459f96ac50bbfd6cf1fb9a1f807ae/REPL/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814056194821861, "lm_q2_score": 0.055005289842570144, "lm_q1q2_score": 0.01547879766294565}}
{"text": "/- Author: E.W.Ayers \u00a9 2019 -/\n\nimport .table .rule .rule_table .tree\nnamespace robot\n\n@[derive decidable_eq]\nmeta inductive task : Type\n|CreateAll : expr \u2192 task\n|Create : \u2115 \u2192 expr \u2192 task\n/- Use a term annihilation move. For example `X * X\u207b\u00b9 = e` annihilates anything in X. -/\n|Annihilate : expr \u2192 task\n/- passes when we remove the given term from the CE.\nGenerally this is only used when a variable appears in the CE but not\nin the target and there are no rules explicitly removing the variable. -/\n|Destroy : expr.zipper \u2192 task\n|Merge : expr \u2192 task\nnamespace task\n    protected meta def code : task \u2192 \u2115\n    |(Create _ _) := 0\n    |(CreateAll _) := 1\n    |(Annihilate _) := 2\n    |(Merge _) := 3\n    |(Destroy _) := 4\n    protected meta def lt : task \u2192 task \u2192 bool\n    |(Create n\u2081 e\u2081) (Create n\u2082 e\u2082) := (n\u2081,e\u2081) < (n\u2082,e\u2082)\n    |(CreateAll e\u2081) (CreateAll e\u2082) := e\u2081 < e\u2082\n    |(Annihilate e\u2081) (Annihilate e\u2082) := e\u2081 < e\u2082\n    |(Merge e\u2081) (Merge e\u2082) := e\u2081 < e\u2082\n    |x y := task.code x < task.code y\n    meta instance has_lt : has_lt task := \u27e8\u03bb x y, task.lt x y\u27e9\n    meta instance decidable_lt : decidable_rel ((<) : task \u2192 task \u2192 Prop) := by apply_instance\n    meta instance : has_to_tactic_format task := \u27e8\u03bb t, match t with\n    |(Create n x) :=\n        if n = 0 then notimpl /- should not happen -/ else\n        if n = 1 then pure ((++) \"Create \") <*> tactic.pp x else\n        pure (\u03bb ppn ppx, \"Create(\u00d7\" ++ ppn ++ \") \" ++ ppx) <*> tactic.pp n <*> tactic.pp x\n    |(CreateAll x) := pure (\u03bb x, \"CreateAll \" ++ x) <*> tactic.pp x\n    |(Annihilate x) := pure ((++) \"Annihilate \") <*> tactic.pp x\n    |(Destroy x) := pure ((++) \"Destroy \") <*> tactic.pp x\n    |(Merge x) := pure ((++) \"Merge \") <*> tactic.pp x\n    end\u27e9\n    meta def is_def_eq : task \u2192 task \u2192 tactic bool\n    |(Create n\u2081 x) (Create n\u2082 y) := if n\u2081 \u2260 n\u2082 then pure ff else tactic.is_success $ tactic.is_def_eq x y\n    |(CreateAll x) (CreateAll y) := tactic.is_success $ tactic.is_def_eq x y\n    |(Annihilate x) (Annihilate y) := tactic.is_success $ tactic.is_def_eq x y\n    |(Merge x) (Merge y) := tactic.is_success $ tactic.is_def_eq x y\n    |_ _ := pure ff\nend task\nopen task\n\n@[derive decidable_eq]\nmeta inductive strategy : Type\n|Use : rule_app \u2192 strategy\n|ReduceDistance : expr \u2192 expr \u2192 strategy\nopen strategy\nnamespace strategy\n    meta def code : strategy \u2192 \u2115\n    |(Use _) := 0\n    |(ReduceDistance _ _) := 1\n    meta def lt : strategy \u2192 strategy \u2192 bool\n    |(Use r\u2081) (Use r\u2082) := r\u2081 < r\u2082\n    |(ReduceDistance a b) (ReduceDistance a' b') := (a,b) < (a',b')\n    |s\u2081 s\u2082 := s\u2081.code < s\u2082.code\n    meta instance has_lt : has_lt strategy := \u27e8\u03bb x y, lt x y\u27e9\n    meta instance decidable_lt : decidable_rel ((<) : strategy \u2192 strategy \u2192 Prop) := by apply_instance\n    meta instance : has_to_tactic_format robot.strategy :=\n    \u27e8\u03bb s, match s with\n        | (Use x) := do x \u2190 tactic.pp x, pure $ \"Use \" ++ x\n        | (ReduceDistance x y) := pure (\u03bb x y, \"ReduceDistance \" ++ x ++ \" \" ++ y) <*> tactic.pp x <*> tactic.pp y\n    end\u27e9\n    meta def is_def_eq : strategy \u2192 strategy \u2192 tactic bool\n    |(Use r\u2081) (Use r\u2082) := rule_app.is_def_eq r\u2081 r\u2082\n    |(ReduceDistance a b) (ReduceDistance c d) :=\n        tactic.is_success $ (do tactic.is_def_eq a c, tactic.is_def_eq b d)\n    |_ _ := pure ff\nend strategy\n\nmeta inductive tree_entry : Type\n|task (t : task) (achieved : list task)\n|strat (s : strategy) (achieved : list task)\nnamespace tree_entry\n    meta def code : tree_entry \u2192 \u2115\n    |(task _ _) := 0 | (strat _ _) := 1\n    meta def lt : tree_entry \u2192 tree_entry \u2192 bool\n    |(task t\u2081 a\u2081) (task t\u2082 a\u2082) := t\u2081 < t\u2082\n    |(strat s\u2081 _) (strat s\u2082 _) := s\u2081 < s\u2082\n    |x y := x.code < y.code\n    meta instance has_lt : has_lt tree_entry := \u27e8\u03bb x y, lt x y\u27e9\n    meta instance decidable_lt : decidable_rel ((<) : tree_entry \u2192 tree_entry \u2192 Prop) := by apply_instance\n    meta def of_task : robot.task \u2192 tree_entry := \u03bb t, tree_entry.task t []\n    meta def as_task : tree_entry \u2192 option robot.task |(tree_entry.task t _) := some t | _ := none\n    meta def of_strat : robot.strategy \u2192 tree_entry := \u03bb t, tree_entry.strat t []\n    meta def as_strat : tree_entry \u2192 option robot.strategy |(tree_entry.strat t _) := some t | _ := none\n    meta def is_strat : tree_entry \u2192 bool := option.is_some \u2218 as_strat\n    /-- Get the achieved child subtasks for this entry. -/\n    meta def achieved : tree_entry \u2192 list robot.task | (tree_entry.strat _ a) := a | (tree_entry.task _ a) := a\n    meta def map_achieved (f : list robot.task \u2192 list robot.task) : tree_entry \u2192 tree_entry\n    | (tree_entry.strat s a) := (tree_entry.strat s $ f a) | (tree_entry.task t a) := tree_entry.task t $ f a\n    meta def push_achieved (t : robot.task) : tree_entry \u2192 tree_entry := map_achieved ((::) t)\n    meta instance : has_to_tactic_format tree_entry := \u27e8\u03bb x, match x with |(task t _ ) := tactic.pp t | (strat s _ ) := tactic.pp s end\u27e9\n    meta def is_def_eq : tree_entry \u2192 tree_entry \u2192 tactic bool\n    |(task a _) (task b _) := task.is_def_eq a b\n    |(strat a _) (strat b _) := strategy.is_def_eq a b\n    |_ _ := pure ff\n    meta def is_eq : tree_entry \u2192 tree_entry \u2192 tactic bool\n    |(task a _) (task b _) := pure $ a = b\n    |(strat a _) (strat b _) := pure $ a = b\n    |_ _ := pure ff\nend tree_entry\n\nmeta def task_tree := tree tree_entry\nmeta def task_zipper := tree.zipper tree_entry\nnotation `Z` := task_zipper\n\nmeta structure state :=\n(lookahead : list rule_app)\n(path : list expr)\n(rt : rule_table)\n\nmeta def refinement := list task \u00d7 list strategy\nmeta instance : has_append refinement := \u27e8\u03bb \u27e8ts\u2081,ss\u2081\u27e9 \u27e8ts\u2082,ss\u2082\u27e9, \u27e8ts\u2081 ++ ts\u2082, ss\u2081 ++ ss\u2082\u27e9\u27e9\nmeta instance : has_emptyc refinement := \u27e8\u27e8[],[]\u27e9\u27e9\nmeta def action := (strategy \u00d7 Z)\nmeta instance : has_to_tactic_format action := \u27e8\u03bb \u27e8s,_\u27e9, tactic.pp s\u27e9\n\nmeta def as_action : Z \u2192 option action := \u03bb z, z.item.as_strat >>= \u03bb s, pure (s,z)\n\nend robot", "meta": {"author": "EdAyers", "repo": "lean-subtask", "sha": "04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b", "save_path": "github-repos/lean/EdAyers-lean-subtask", "path": "github-repos/lean/EdAyers-lean-subtask/lean-subtask-04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b/src/data.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.0390482952423748, "lm_q1q2_score": 0.015465786136050649}}
{"text": "/-\nCopyright (c) 2017 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes H\u00f6lzl\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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (x : Subtype p) : \u03b1 := \u2191x\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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (x : Subtype p) : p \u2191x := property x\n\n@[simp] theorem val_eq_coe {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {x : Subtype p} : val x = \u2191x := rfl\n\n@[simp] protected theorem forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop}\n    {q : (Subtype fun (a : \u03b1) => p a) \u2192 Prop} :\n    (\u2200 (x : Subtype fun (a : \u03b1) => p a), q x) \u2194\n        \u2200 (a : \u03b1) (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' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : (x : \u03b1) \u2192 p x \u2192 Prop} :\n    (\u2200 (x : \u03b1) (h : p x), q x h) \u2194 \u2200 (x : Subtype fun (a : \u03b1) => p a), q (\u2191x) (property x) :=\n  iff.symm subtype.forall\n\n@[simp] protected theorem exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop}\n    {q : (Subtype fun (a : \u03b1) => p a) \u2192 Prop} :\n    (\u2203 (x : Subtype fun (a : \u03b1) => p a), q x) \u2194\n        \u2203 (a : \u03b1), \u2203 (b : p a), q { val := a, property := b } :=\n  sorry\n\nprotected theorem ext {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x}\n    {a2 : Subtype fun (x : \u03b1) => p x} : \u2191a1 = \u2191a2 \u2192 a1 = a2 :=\n  sorry\n\ntheorem ext_iff {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x}\n    {a2 : Subtype fun (x : \u03b1) => p x} : a1 = a2 \u2194 \u2191a1 = \u2191a2 :=\n  { mp := congr_arg fun {a1 : Subtype fun (x : \u03b1) => p x} => \u2191a1, mpr := subtype.ext }\n\ntheorem heq_iff_coe_eq {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (h : \u2200 (x : \u03b1), p x \u2194 q x)\n    {a1 : Subtype fun (x : \u03b1) => p x} {a2 : Subtype fun (x : \u03b1) => q x} : a1 == a2 \u2194 \u2191a1 = \u2191a2 :=\n  Eq._oldrec (fun (a2' : Subtype fun (x : \u03b1) => p x) => iff.trans heq_iff_eq ext_iff)\n    (funext fun (x : \u03b1) => propext (h x)) a2\n\ntheorem ext_val {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x}\n    {a2 : Subtype fun (x : \u03b1) => p x} : val a1 = val a2 \u2192 a1 = a2 :=\n  subtype.ext\n\ntheorem ext_iff_val {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x}\n    {a2 : Subtype fun (x : \u03b1) => p x} : a1 = a2 \u2194 val a1 = val a2 :=\n  ext_iff\n\n@[simp] theorem coe_eta {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (a : Subtype fun (a : \u03b1) => p a) (h : p \u2191a) :\n    { val := \u2191a, property := h } = a :=\n  subtype.ext rfl\n\n@[simp] theorem coe_mk {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (a : \u03b1) (h : p a) :\n    \u2191{ val := a, property := h } = a :=\n  rfl\n\n@[simp] theorem mk_eq_mk {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a : \u03b1} {h : p a} {a' : \u03b1} {h' : p a'} :\n    { val := a, property := h } = { val := a', property := h' } \u2194 a = a' :=\n  ext_iff\n\ntheorem coe_eq_iff {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a : Subtype fun (a : \u03b1) => p a} {b : \u03b1} :\n    \u2191a = b \u2194 \u2203 (h : p b), a = { val := b, property := h } :=\n  sorry\n\ntheorem coe_injective {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : function.injective coe :=\n  fun (a b : Subtype p) => subtype.ext\n\ntheorem val_injective {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : function.injective val := coe_injective\n\n/-- Restrict a (dependent) function to a subtype -/\ndef restrict {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Type u_2} (f : (x : \u03b1) \u2192 \u03b2 x) (p : \u03b1 \u2192 Prop) (x : Subtype p) :\n    \u03b2 (val x) :=\n  f \u2191x\n\ntheorem restrict_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Type u_2} (f : (x : \u03b1) \u2192 \u03b2 x) (p : \u03b1 \u2192 Prop)\n    (x : Subtype p) : restrict f p x = f (val x) :=\n  Eq.refl (restrict f p x)\n\ntheorem restrict_def {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (p : \u03b1 \u2192 Prop) :\n    restrict f p = f \u2218 coe :=\n  Eq.refl (restrict f p)\n\ntheorem restrict_injective {\u03b1 : Sort u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} (p : \u03b1 \u2192 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) {p : \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1), p (f a)) :\n    \u03b1 \u2192 Subtype p :=\n  fun (a : \u03b1) => { val := f a, property := h a }\n\ntheorem coind_injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop}\n    (h : \u2200 (a : \u03b1), p (f a)) (hf : function.injective f) : function.injective (coind f h) :=\n  fun (x y : \u03b1) (hxy : coind f h x = coind f h y) => hf (congr_arg val hxy)\n\ntheorem coind_surjective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop}\n    (h : \u2200 (a : \u03b1), p (f a)) (hf : function.surjective f) : function.surjective (coind f h) :=\n  sorry\n\ntheorem coind_bijective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop}\n    (h : \u2200 (a : \u03b1), 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2)\n    (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) : \u2200 (\u1fb0 : Subtype p), \u2191(map f h \u1fb0) = f \u2191\u1fb0 :=\n  fun (\u1fb0 : Subtype p) => Eq.refl \u2191(map f h \u1fb0)\n\ntheorem map_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop}\n    {r : \u03b3 \u2192 Prop} {x : Subtype p} (f : \u03b1 \u2192 \u03b2) (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) (g : \u03b2 \u2192 \u03b3)\n    (l : \u2200 (a : \u03b2), q a \u2192 r (g a)) :\n    map g l (map f h x) = map (g \u2218 f) (fun (a : \u03b1) (ha : p a) => l (f a) (h a ha)) x :=\n  rfl\n\ntheorem map_id {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {h : \u2200 (a : \u03b1), p a \u2192 p (id a)} : map id h = id :=\n  sorry\n\ntheorem map_injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {f : \u03b1 \u2192 \u03b2}\n    (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) (hf : function.injective f) : function.injective (map f h) :=\n  coind_injective (fun (x : Subtype fun (a : \u03b1) => p a) => map._proof_1 f h x)\n    (function.injective.comp hf coe_injective)\n\ntheorem map_involutive {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {f : \u03b1 \u2192 \u03b1} (h : \u2200 (a : \u03b1), p a \u2192 p (f a))\n    (hf : function.involutive f) : function.involutive (map f h) :=\n  fun (x : Subtype fun (a : \u03b1) => p a) => subtype.ext (hf \u2191x)\n\nprotected instance has_equiv {\u03b1 : Sort u_1} [has_equiv \u03b1] (p : \u03b1 \u2192 Prop) : has_equiv (Subtype p) :=\n  has_equiv.mk fun (s t : Subtype p) => \u2191s \u2248 \u2191t\n\ntheorem equiv_iff {\u03b1 : Sort u_1} [has_equiv \u03b1] {p : \u03b1 \u2192 Prop} {s : Subtype p} {t : Subtype p} :\n    s \u2248 t \u2194 \u2191s \u2248 \u2191t :=\n  iff.rfl\n\nprotected theorem refl {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [setoid \u03b1] (s : Subtype p) : s \u2248 s :=\n  setoid.refl \u2191s\n\nprotected theorem symm {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [setoid \u03b1] {s : Subtype p} {t : Subtype p}\n    (h : s \u2248 t) : t \u2248 s :=\n  setoid.symm h\n\nprotected theorem trans {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [setoid \u03b1] {s : Subtype p} {t : Subtype p}\n    {u : Subtype p} (h\u2081 : s \u2248 t) (h\u2082 : t \u2248 u) : s \u2248 u :=\n  setoid.trans h\u2081 h\u2082\n\ntheorem equivalence {\u03b1 : Sort u_1} [setoid \u03b1] (p : \u03b1 \u2192 Prop) : equivalence has_equiv.equiv :=\n  mk_equivalence has_equiv.equiv subtype.refl subtype.symm subtype.trans\n\nprotected instance setoid {\u03b1 : Sort u_1} [setoid \u03b1] (p : \u03b1 \u2192 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 `\u03b1` is a type. -/\n\n@[simp] theorem coe_prop {\u03b1 : Type u_1} {S : set \u03b1} (a : Subtype fun (a : \u03b1) => a \u2208 S) : \u2191a \u2208 S :=\n  prop a\n\ntheorem val_prop {\u03b1 : Type u_1} {S : set \u03b1} (a : Subtype fun (a : \u03b1) => a \u2208 S) : val a \u2208 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) 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 Init.Prelude\nimport Init.SizeOf\n\nuniverse u v w\n\ndef inline {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := a\n\n@[inline] def flip {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) : \u03b2 \u2192 \u03b1 \u2192 \u03c6 :=\n  fun b a => f a b\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 (\u03b1 : Type u) : Type u where\n  private fn : Unit \u2192 \u03b1\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 : \u03b1) : Thunk \u03b1 :=\n  \u27e8fun _ => a\u27e9\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 \u03b1) : \u03b1 :=\n  x.fn ()\n@[inline] protected def Thunk.map (f : \u03b1 \u2192 \u03b2) (x : Thunk \u03b1) : Thunk \u03b2 :=\n  \u27e8fun _ => f x.get\u27e9\n@[inline] protected def Thunk.bind (x : Thunk \u03b1) (f : \u03b1 \u2192 Thunk \u03b2) : Thunk \u03b2 :=\n  \u27e8fun _ => (f x.get).get\u27e9\n\nabbrev Eq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} {b : \u03b1} (h : a = b) (m : motive a) : motive b :=\n  Eq.ndrec m h\n\nstructure Iff (a b : Prop) : Prop where\n  intro :: (mp : a \u2192 b) (mpr : b \u2192 a)\n\ninfix:20 \" <-> \" => Iff\ninfix:20 \" \u2194 \"   => Iff\n\ninductive Sum (\u03b1 : Type u) (\u03b2 : Type v) where\n  | inl (val : \u03b1) : Sum \u03b1 \u03b2\n  | inr (val : \u03b2) : Sum \u03b1 \u03b2\n\ninductive PSum (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  | inl (val : \u03b1) : PSum \u03b1 \u03b2\n  | inr (val : \u03b2) : PSum \u03b1 \u03b2\n\nstructure Sigma {\u03b1 : Type u} (\u03b2 : \u03b1 \u2192 Type v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\nattribute [unbox] Sigma\n\nstructure PSigma {\u03b1 : Sort u} (\u03b2 : \u03b1 \u2192 Sort v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\ninductive Exists {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) : Prop where\n  | intro (w : \u03b1) (h : p w) : Exists p\n\n/- Auxiliary type used to compile `for x in xs` notation. -/\ninductive ForInStep (\u03b1 : Type u) where\n  | done  : \u03b1 \u2192 ForInStep \u03b1\n  | yield : \u03b1 \u2192 ForInStep \u03b1\n\nclass ForIn (m : Type u\u2081 \u2192 Type u\u2082) (\u03c1 : Type u) (\u03b1 : outParam (Type v)) where\n  forIn {\u03b2} [Monad m] (x : \u03c1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2\n\nexport ForIn (forIn)\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPRBC (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPR (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultBC (\u03c3 : Type u) where\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultBC \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultBC \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultSBC (\u03b1 \u03c3 : Type u) where\n  | \u00abpureReturn\u00bb : \u03b1 \u2192 \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abbreak\u00bb      : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abcontinue\u00bb   : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n\nclass HasEquiv  (\u03b1 : Sort u) where\n  Equiv : \u03b1 \u2192 \u03b1 \u2192 Sort v\n\ninfix:50 \" \u2248 \"  => HasEquiv.Equiv\n\nclass EmptyCollection (\u03b1 : Type u) where\n  emptyCollection : \u03b1\n\nnotation \"{\" \"}\" => EmptyCollection.emptyCollection\nnotation \"\u2205\"     => EmptyCollection.emptyCollection\n\n/- Remark: tasks have an efficient implementation in the runtime. -/\nstructure Task (\u03b1 : Type u) : Type u where\n  pure :: (get : \u03b1)\n  deriving Inhabited\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\ndef Priority.default : Priority := 0\n-- see `LEAN_MAX_PRIO`\ndef Priority.max : Priority := 8\n/--\n  Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.\n  This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more\n  non-dedicated workers than the number of cores to reduce context switches. -/\ndef Priority.dedicated : Priority := 9\n\n@[noinline, extern \"lean_task_spawn\"]\nprotected def spawn {\u03b1 : Type u} (fn : Unit \u2192 \u03b1) (prio := Priority.default) : Task \u03b1 :=\n  \u27e8fn ()\u27e9\n\n@[noinline, extern \"lean_task_map\"]\nprotected def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (x : Task \u03b1) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8f x.get\u27e9\n\n@[noinline, extern \"lean_task_bind\"]\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} (x : Task \u03b1) (f : \u03b1 \u2192 Task \u03b2) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8(f x.get).get\u27e9\n\nend Task\n\n/- Some type that is not a scalar value in our runtime. -/\nstructure NonScalar where\n  val : Nat\n\n/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/\ninductive PNonScalar : Type u where\n  | mk (v : Nat) : PNonScalar\n\n@[simp] theorem Nat.add_zero (n : Nat) : n + 0 = n := rfl\n\ntheorem optParam_eq (\u03b1 : Sort u) (default : \u03b1) : optParam \u03b1 default = \u03b1 := rfl\n\n/- Boolean operators -/\n\n@[extern c inline \"#1 || #2\"] def strictOr  (b\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\n@[extern c inline \"#1 && #2\"] def strictAnd (b\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\n\n@[inline] def bne {\u03b1 : Type u} [BEq \u03b1] (a b : \u03b1) : Bool :=\n  !(a == b)\n\ninfix:50 \" != \" => bne\n\n/- Logical connectives an equality -/\n\ndef implies (a b : Prop) := a \u2192 b\n\ntheorem implies.trans {p q r : Prop} (h\u2081 : implies p q) (h\u2082 : implies q r) : implies p r :=\n  fun hp => h\u2082 (h\u2081 hp)\n\ndef trivial : True := \u27e8\u27e9\n\ntheorem mt {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : \u00acb) : \u00aca :=\n  fun ha => h\u2082 (h\u2081 ha)\n\ntheorem not_false : \u00acFalse := id\n\ntheorem not_not_intro {p : Prop} (h : p) : \u00ac \u00ac p :=\n  fun hn : \u00ac p => hn h\n\n-- proof irrelevance is built in\ntheorem proofIrrel {a : Prop} (h\u2081 h\u2082 : a) : h\u2081 = h\u2082 := rfl\n\ntheorem id.def {\u03b1 : Sort u} (a : \u03b1) : id a = a := rfl\n\n@[macroInline] def Eq.mp {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (a : \u03b1) : \u03b2 :=\n  h \u25b8 a\n\n@[macroInline] def Eq.mpr {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (b : \u03b2) : \u03b1 :=\n  h \u25b8 b\n\ntheorem Eq.substr {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : b = a) (h\u2082 : p a) : p b :=\n  h\u2081 \u25b8 h\u2082\n\ntheorem cast_eq {\u03b1 : Sort u} (h : \u03b1 = \u03b1) (a : \u03b1) : cast h a = a :=\n  rfl\n\n@[reducible] def Ne {\u03b1 : Sort u} (a b : \u03b1) :=\n  \u00ac(a = b)\n\ninfix:50 \" \u2260 \"  => Ne\n\nsection Ne\nvariable {\u03b1 : Sort u}\nvariable {a b : \u03b1} {p : Prop}\n\ntheorem Ne.intro (h : a = b \u2192 False) : a \u2260 b := h\n\ntheorem Ne.elim (h : a \u2260 b) : a = b \u2192 False := h\n\ntheorem Ne.irrefl (h : a \u2260 a) : False := h rfl\n\ntheorem Ne.symm (h : a \u2260 b) : b \u2260 a :=\n  fun h\u2081 => h (h\u2081.symm)\n\ntheorem false_of_ne : a \u2260 a \u2192 False := Ne.irrefl\n\ntheorem ne_false_of_self : p \u2192 p \u2260 False :=\n  fun (hp : p) (h : p = False) => h \u25b8 hp\n\ntheorem ne_true_of_not : \u00acp \u2192 p \u2260 True :=\n  fun (hnp : \u00acp) (h : p = True) =>\n    have : \u00acTrue := h \u25b8 hnp\n    this trivial\n\ntheorem true_ne_false : \u00acTrue = False :=\n  ne_false_of_self trivial\n\nend Ne\n\nsection\nvariable {\u03b1 \u03b2 \u03c6 : Sort u} {a a' : \u03b1} {b b' : \u03b2} {c : \u03c6}\n\ntheorem HEq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} (m : motive a) {\u03b2 : Sort u2} {b : \u03b2} (h : HEq a b) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} {\u03b2 : Sort u2} {b : \u03b2} (h : HEq a b) (m : motive a) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.elim {\u03b1 : Sort u} {a : \u03b1} {p : \u03b1 \u2192 Sort v} {b : \u03b1} (h\u2081 : HEq a b) (h\u2082 : p a) : p b :=\n  eq_of_heq h\u2081 \u25b8 h\u2082\n\ntheorem HEq.subst {p : (T : Sort u) \u2192 T \u2192 Prop} (h\u2081 : HEq a b) (h\u2082 : p \u03b1 a) : p \u03b2 b :=\n  HEq.ndrecOn h\u2081 h\u2082\n\ntheorem HEq.symm (h : HEq a b) : HEq b a :=\n  HEq.ndrecOn (motive := fun x => HEq x a) h (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\u2081 : HEq a b) (h\u2082 : HEq b c) : HEq a c :=\n  HEq.subst h\u2082 h\u2081\n\ntheorem heq_of_heq_of_eq (h\u2081 : HEq a b) (h\u2082 : b = b') : HEq a b' :=\n  HEq.trans h\u2081 (heq_of_eq h\u2082)\n\ntheorem heq_of_eq_of_heq (h\u2081 : a = a') (h\u2082 : HEq a' b) : HEq a b :=\n  HEq.trans (heq_of_eq h\u2081) h\u2082\n\ndef type_eq_of_heq (h : HEq a b) : \u03b1 = \u03b2 :=\n  HEq.ndrecOn (motive := @fun (x : Sort u) _ => \u03b1 = x) h (Eq.refl \u03b1)\n\nend\n\ntheorem eqRec_heq {\u03b1 : Sort u} {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} : (h : a = a') \u2192 (p : \u03c6 a) \u2192 HEq (Eq.recOn (motive := fun x _ => \u03c6 x) h p) p\n  | rfl, p => HEq.refl p\n\ntheorem heq_of_eqRec_eq {\u03b1 \u03b2 : Sort u} {a : \u03b1} {b : \u03b2} (h\u2081 : \u03b1 = \u03b2) (h\u2082 : Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\u2081 = b) : HEq a b := by\n  subst h\u2081\n  apply heq_of_eq\n  exact h\u2082\n\ntheorem cast_heq {\u03b1 \u03b2 : Sort u} : (h : \u03b1 = \u03b2) \u2192 (a : \u03b1) \u2192 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 \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 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 \u2194 a :=\n  Iff.intro (fun h => h) (fun h => h)\n\nprotected theorem Iff.rfl {a : Prop} : a \u2194 a :=\n  Iff.refl a\n\ntheorem Iff.trans (h\u2081 : a \u2194 b) (h\u2082 : b \u2194 c) : a \u2194 c :=\n  Iff.intro\n    (fun ha => Iff.mp h\u2082 (Iff.mp h\u2081 ha))\n    (fun hc => Iff.mpr h\u2081 (Iff.mpr h\u2082 hc))\n\ntheorem Iff.symm (h : a \u2194 b) : b \u2194 a :=\n  Iff.intro (Iff.mpr h) (Iff.mp h)\n\ntheorem Iff.comm : (a \u2194 b) \u2194 (b \u2194 a) :=\n  Iff.intro Iff.symm Iff.symm\n\n/- Exists -/\n\ntheorem Exists.elim {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {b : Prop}\n   (h\u2081 : Exists (fun x => p x)) (h\u2082 : \u2200 (a : \u03b1), p a \u2192 b) : b :=\n  h\u2082 h\u2081.1 h\u2081.2\n\n/- Decidable -/\n\ntheorem decide_true_eq_true (h : Decidable True) : @decide True h = true :=\n  match h with\n  | isTrue h  => rfl\n  | isFalse h => False.elim <| h \u27e8\u27e9\n\ntheorem decide_false_eq_false (h : Decidable False) : @decide False h = false :=\n  match h with\n  | isFalse h => 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 p (h := d)\n\ntheorem toBoolUsing_eq_true {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=\n  decide_eq_true (s := d) h\n\ntheorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=\n  of_decide_eq_true (s := d) h\n\ntheorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : \u00ac p :=\n  of_decide_eq_false (s := 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@[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p \u2192 q) (h2 : \u00acp \u2192 q) : q :=\n  match dec with\n  | isTrue h  => h1 h\n  | isFalse h => h2 h\n\ntheorem em (p : Prop) [Decidable p] : p \u2228 \u00acp :=\n  byCases Or.inl Or.inr\n\ntheorem byContradiction [dec : Decidable p] (h : \u00acp \u2192 False) : p :=\n  byCases id (fun np => False.elim (h np))\n\ntheorem of_not_not [Decidable p] : \u00ac \u00ac p \u2192 p :=\n  fun hnn => byContradiction (fun hn => absurd hn hnn)\n\ntheorem not_and_iff_or_not (p q : Prop) [d\u2081 : Decidable p] [d\u2082 : Decidable q] : \u00ac (p \u2227 q) \u2194 \u00ac p \u2228 \u00ac q :=\n  Iff.intro\n    (fun h => match d\u2081, d\u2082 with\n      | isTrue h\u2081,  isTrue h\u2082   => absurd (And.intro h\u2081 h\u2082) h\n      | _,           isFalse h\u2082 => Or.inr h\u2082\n      | isFalse h\u2081, _           => Or.inl h\u2081)\n    (fun (h) \u27e8hp, hq\u27e9 => 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@[inline] def  decidableOfDecidableOfIff (hp : Decidable p) (h : p \u2194 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@[inline] def  decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=\n  h \u25b8 hp\nend\n\n@[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p \u2192 q) :=\n  if hp : p then\n    if hq : q then isTrue (fun h => 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 \u2194 q) :=\n  if hp : p then\n    if hq : q then\n      isTrue \u27e8fun _ => hq, fun _ => hp\u27e9\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 \u27e8fun h => absurd h hp, fun h => absurd h hq\u27e9\n\n/- if-then-else expression theorems -/\n\ntheorem if_pos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = t :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem if_neg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = e :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\ntheorem dif_pos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = t hc :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem dif_neg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = e hnc :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\n-- Remark: dite and ite are \"defally equal\" when we ignore the proofs.\ntheorem dif_eq_if (c : Prop) [h : Decidable c] {\u03b1 : Sort u} (t : \u03b1) (e : \u03b1) : dite c (fun h => t) (fun h => e) = ite c t e :=\n  match h with\n  | isTrue hc   => rfl\n  | isFalse hnc => 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 hc  => dT\n  | isFalse hc => dE\n\ninstance {c : Prop} {t : c \u2192 Prop} {e : \u00acc \u2192 Prop} [dC : Decidable c] [dT : \u2200 h, Decidable (t h)] [dE : \u2200 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 definitions for generating compact `noConfusion` for enumeration types -/\nabbrev noConfusionTypeEnum {\u03b1 : Sort u} {\u03b2 : Sort v} [DecidableEq \u03b2] (f : \u03b1 \u2192 \u03b2) (P : Sort w) (x y : \u03b1) : Sort w :=\n  if f x = f y then P \u2192 P else P\n\nabbrev noConfusionEnum {\u03b1 : Sort u} {\u03b2 : Sort v} [DecidableEq \u03b2] (f : \u03b1 \u2192 \u03b2) {P : Sort w} {x y : \u03b1} (h : x = y) : noConfusionTypeEnum f P x y :=\n  if h' : f x = f y then\n    cast (@if_pos _ _ h' _ (P \u2192 P) (P)).symm (fun (h : P) => h)\n  else\n    False.elim (h' (congrArg f h))\n\n/- Inhabited -/\n\ninstance : Inhabited Prop where\n  default := True\n\nderiving instance Inhabited for NonScalar, PNonScalar, True, ForInStep\n\nclass inductive Nonempty (\u03b1 : Sort u) : Prop where\n  | intro (val : \u03b1) : Nonempty \u03b1\n\nprotected def Nonempty.elim {\u03b1 : Sort u} {p : Prop} (h\u2081 : Nonempty \u03b1) (h\u2082 : \u03b1 \u2192 p) : p :=\n  h\u2082 h\u2081.1\n\ninstance {\u03b1 : Sort u} [Inhabited \u03b1] : Nonempty \u03b1 :=\n  \u27e8arbitrary\u27e9\n\ntheorem nonempty_of_exists {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : Exists (fun x => p x) \u2192 Nonempty \u03b1\n  | \u27e8w, h\u27e9 => \u27e8w\u27e9\n\n/- Subsingleton -/\n\nclass Subsingleton (\u03b1 : Sort u) : Prop where\n  intro :: allEq : (a b : \u03b1) \u2192 a = b\n\nprotected def Subsingleton.elim {\u03b1 : Sort u} [h : Subsingleton \u03b1] : (a b : \u03b1) \u2192 a = b :=\n  h.allEq\n\nprotected def Subsingleton.helim {\u03b1 \u03b2 : Sort u} [h\u2081 : Subsingleton \u03b1] (h\u2082 : \u03b1 = \u03b2) (a : \u03b1) (b : \u03b2) : HEq a b := by\n  subst h\u2082\n  apply heq_of_eq\n  apply Subsingleton.elim\n\ninstance (p : Prop) : Subsingleton p :=\n  \u27e8fun a b => proofIrrel a b\u27e9\n\ninstance (p : Prop) : Subsingleton (Decidable p) :=\n  Subsingleton.intro fun\n    | isTrue t\u2081 => fun\n      | isTrue t\u2082  => rfl\n      | isFalse f\u2082 => absurd t\u2081 f\u2082\n    | isFalse f\u2081 => fun\n      | isTrue t\u2082  => absurd t\u2082 f\u2081\n      | isFalse f\u2082 => rfl\n\ntheorem recSubsingleton\n     {p : Prop} [h : Decidable p]\n     {h\u2081 : p \u2192 Sort u}\n     {h\u2082 : \u00acp \u2192 Sort u}\n     [h\u2083 : \u2200 (h : p), Subsingleton (h\u2081 h)]\n     [h\u2084 : \u2200 (h : \u00acp), Subsingleton (h\u2082 h)]\n     : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h\u2082 h\u2081) :=\n  match h with\n  | isTrue h  => h\u2083 h\n  | isFalse h => h\u2084 h\n\nstructure Equivalence {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Prop where\n  refl  : \u2200 x, r x x\n  symm  : \u2200 {x y}, r x y \u2192 r y x\n  trans : \u2200 {x y z}, r x y \u2192 r y z \u2192 r x z\n\ndef emptyRelation {\u03b1 : Sort u} (a\u2081 a\u2082 : \u03b1) : Prop :=\n  False\n\ndef Subrelation {\u03b1 : Sort u} (q r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  \u2200 {x y}, q x y \u2192 r x y\n\ndef InvImage {\u03b1 : Sort u} {\u03b2 : Sort v} (r : \u03b2 \u2192 \u03b2 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b1 \u2192 Prop :=\n  fun a\u2081 a\u2082 => r (f a\u2081) (f a\u2082)\n\ninductive TC {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : \u03b1 \u2192 \u03b1 \u2192 Prop where\n  | base  : \u2200 a b, r a b \u2192 TC r a b\n  | trans : \u2200 a b c, TC r a b \u2192 TC r b c \u2192 TC r a c\n\n/- Subtype -/\n\nnamespace Subtype\ndef existsOfSubtype {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : { x // p x } \u2192 Exists (fun x => p x)\n  | \u27e8a, h\u27e9 => \u27e8a, h\u27e9\n\nvariable {\u03b1 : Type u} {p : \u03b1 \u2192 Prop}\n\nprotected theorem eq : \u2200 {a1 a2 : {x // p x}}, val a1 = val a2 \u2192 a1 = a2\n  | \u27e8x, h1\u27e9, \u27e8_, _\u27e9, 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 {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} {a : \u03b1} (h : p a) : Inhabited {x // p x} where\n  default := \u27e8a, h\u27e9\n\ninstance {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [DecidableEq \u03b1] : DecidableEq {x : \u03b1 // p x} :=\n  fun \u27e8a, h\u2081\u27e9 \u27e8b, h\u2082\u27e9 =>\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 {\u03b1 : Type u} {\u03b2 : Type v}\n\ninstance Sum.inhabitedLeft [h : Inhabited \u03b1] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inl arbitrary\n\ninstance Sum.inhabitedRight [h : Inhabited \u03b2] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inr arbitrary\n\ninstance {\u03b1 : Type u} {\u03b2 : Type v} [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (Sum \u03b1 \u03b2) := fun a b =>\n  match a, b with\n  | Sum.inl a, Sum.inl b =>\n    if h : a = b then isTrue (h \u25b8 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 \u25b8 rfl)\n    else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h\n  | Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h\n  | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h\n\nend\n\n/- Product -/\n\ninstance [Inhabited \u03b1] [Inhabited \u03b2] : Inhabited (\u03b1 \u00d7 \u03b2) where\n  default := (arbitrary, arbitrary)\n\ninstance [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (\u03b1 \u00d7 \u03b2) :=\n  fun (a, b) (a', b') =>\n    match decEq a a' with\n    | isTrue e\u2081 =>\n      match decEq b b' with\n      | isTrue e\u2082  => isTrue (e\u2081 \u25b8 e\u2082 \u25b8 rfl)\n      | isFalse n\u2082 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2082' n\u2082\n    | isFalse n\u2081 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2081' n\u2081\n\ninstance [BEq \u03b1] [BEq \u03b2] : BEq (\u03b1 \u00d7 \u03b2) where\n  beq := fun (a\u2081, b\u2081) (a\u2082, b\u2082) => a\u2081 == a\u2082 && b\u2081 == b\u2082\n\ninstance [LT \u03b1] [LT \u03b2] : LT (\u03b1 \u00d7 \u03b2) where\n  lt s t := s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)\n\ninstance prodHasDecidableLt\n    [LT \u03b1] [LT \u03b2] [DecidableEq \u03b1] [DecidableEq \u03b2]\n    [(a b : \u03b1) \u2192 Decidable (a < b)] [(a b : \u03b2) \u2192 Decidable (a < b)]\n    : (s t : \u03b1 \u00d7 \u03b2) \u2192 Decidable (s < t) :=\n  fun t s => inferInstanceAs (Decidable (_ \u2228 _))\n\ntheorem Prod.lt_def [LT \u03b1] [LT \u03b2] (s t : \u03b1 \u00d7 \u03b2) : (s < t) = (s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)) :=\n  rfl\n\ntheorem Prod.ext (p : \u03b1 \u00d7 \u03b2) : (p.1, p.2) = p := by\n  cases p; rfl\n\ndef Prod.map {\u03b1\u2081 : Type u\u2081} {\u03b1\u2082 : Type u\u2082} {\u03b2\u2081 : Type v\u2081} {\u03b2\u2082 : Type v\u2082}\n    (f : \u03b1\u2081 \u2192 \u03b1\u2082) (g : \u03b2\u2081 \u2192 \u03b2\u2082) : \u03b1\u2081 \u00d7 \u03b2\u2081 \u2192 \u03b1\u2082 \u00d7 \u03b2\u2082\n  | (a, b) => (f a, g b)\n\n/- Dependent products -/\n\ntheorem ex_of_PSigma {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : (PSigma (fun x => p x)) \u2192 Exists (fun x => p x)\n  | \u27e8x, hx\u27e9 => \u27e8x, hx\u27e9\n\nprotected theorem PSigma.eta {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {a\u2081 a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081} {b\u2082 : \u03b2 a\u2082}\n    (h\u2081 : a\u2081 = a\u2082) (h\u2082 : Eq.ndrec b\u2081 h\u2081 = b\u2082) : PSigma.mk a\u2081 b\u2081 = PSigma.mk a\u2082 b\u2082 := by\n  subst h\u2081\n  subst h\u2082\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 = \u27e8\u27e9 :=\n  PUnit.subsingleton a \u27e8\u27e9\n\ninstance : Subsingleton PUnit :=\n  Subsingleton.intro PUnit.subsingleton\n\ninstance : Inhabited PUnit where\n  default := \u27e8\u27e9\n\ninstance : DecidableEq PUnit :=\n  fun a b => isTrue (PUnit.subsingleton a b)\n\n/- Setoid -/\n\nclass Setoid (\u03b1 : Sort u) where\n  r : \u03b1 \u2192 \u03b1 \u2192 Prop\n  iseqv {} : Equivalence r\n\ninstance {\u03b1 : Sort u} [Setoid \u03b1] : HasEquiv \u03b1 :=\n  \u27e8Setoid.r\u27e9\n\nnamespace Setoid\n\nvariable {\u03b1 : Sort u} [Setoid \u03b1]\n\ntheorem refl (a : \u03b1) : a \u2248 a :=\n  (Setoid.iseqv \u03b1).refl a\n\ntheorem symm {a b : \u03b1} (hab : a \u2248 b) : b \u2248 a :=\n  (Setoid.iseqv \u03b1).symm hab\n\ntheorem trans {a b c : \u03b1} (hab : a \u2248 b) (hbc : b \u2248 c) : a \u2248 c :=\n  (Setoid.iseqv \u03b1).trans hab hbc\n\nend Setoid\n\n\n/- Propositional extensionality -/\n\naxiom propext {a b : Prop} : (a \u2194 b) \u2192 a = b\n\ntheorem Eq.propIntro {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : b \u2192 a) : a = b :=\n  propext <| Iff.intro h\u2081 h\u2082\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/- Quotients -/\n\n-- Iff can now be used to do substitutions in a calculation\ntheorem Iff.subst {a b : Prop} {p : Prop \u2192 Prop} (h\u2081 : a \u2194 b) (h\u2082 : p a) : p b :=\n  Eq.subst (propext h\u2081) h\u2082\n\nnamespace Quot\naxiom sound : \u2200 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a b : \u03b1}, r a b \u2192 Quot.mk r a = Quot.mk r b\n\nprotected theorem liftBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v}\n    (f : \u03b1 \u2192 \u03b2)\n    (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b)\n    (a : \u03b1)\n    : lift f c (Quot.mk r a) = f a :=\n  rfl\n\nprotected theorem indBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (p : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (a : \u03b1)\n    : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=\n  rfl\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b) : \u03b2 :=\n  lift f c q\n\nprotected theorem inductionOn {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (q : Quot r)\n    (h : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q :=\n  ind h q\n\ntheorem exists_rep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=\n  Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => \u27e8a, rfl\u27e9)\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\nvariable {motive : Quot r \u2192 Sort v}\n\n@[reducible, macroInline]\nprotected def indep (f : (a : \u03b1) \u2192 motive (Quot.mk r a)) (a : \u03b1) : PSigma motive :=\n  \u27e8Quot.mk r a, f a\u27e9\n\nprotected theorem indepCoherent\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : (a b : \u03b1) \u2192 r a b \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : \u2200 (a b : \u03b1) (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\nprotected abbrev rec\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 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\nprotected abbrev recOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : motive q :=\n Quot.rec f h q\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quot.mk r a))]\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q := by\n  induction q using Quot.rec\n  apply f\n  apply Subsingleton.elim\n\nprotected abbrev hrecOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (c : (a b : \u03b1) \u2192 (p : r a b) \u2192 HEq (f a) (f b))\n    : motive q :=\n  Quot.recOn q f fun a b p => eq_of_heq <|\n    have p\u2081 : HEq (Eq.ndrec (f a) (sound p)) (f a) := eqRec_heq (sound p) (f a)\n    HEq.trans p\u2081 (c a b p)\n\nend\nend Quot\n\ndef Quotient {\u03b1 : Sort u} (s : Setoid \u03b1) :=\n  @Quot \u03b1 Setoid.r\n\nnamespace Quotient\n\n@[inline]\nprotected def mk {\u03b1 : Sort u} [s : Setoid \u03b1] (a : \u03b1) : Quotient s :=\n  Quot.mk Setoid.r a\n\ndef sound {\u03b1 : Sort u} [s : Setoid \u03b1] {a b : \u03b1} : a \u2248 b \u2192 Quotient.mk a = Quotient.mk b :=\n  Quot.sound\n\nprotected abbrev lift {\u03b1 : Sort u} {\u03b2 : Sort v} [s : Setoid \u03b1] (f : \u03b1 \u2192 \u03b2) : ((a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) \u2192 Quotient s \u2192 \u03b2 :=\n  Quot.lift f\n\nprotected theorem ind {\u03b1 : Sort u} [s : Setoid \u03b1] {motive : Quotient s \u2192 Prop} : ((a : \u03b1) \u2192 motive (Quotient.mk a)) \u2192 (q : Quot Setoid.r) \u2192 motive q :=\n  Quot.ind\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} [s : Setoid \u03b1] (q : Quotient s) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) : \u03b2 :=\n  Quot.liftOn q f c\n\nprotected theorem inductionOn {\u03b1 : Sort u} [s : Setoid \u03b1] {motive : Quotient s \u2192 Prop}\n    (q : Quotient s)\n    (h : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    : motive q :=\n  Quot.inductionOn q h\n\ntheorem exists_rep {\u03b1 : Sort u} [s : Setoid \u03b1] (q : Quotient s) : Exists (fun (a : \u03b1) => Quotient.mk a = q) :=\n  Quot.exists_rep q\n\nsection\nvariable {\u03b1 : Sort u}\nvariable [s : Setoid \u03b1]\nvariable {motive : Quotient s \u2192 Sort v}\n\n@[inline]\nprotected def rec\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    (q : Quotient s)\n    : motive q :=\n  Quot.rec f h q\n\nprotected abbrev recOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    : motive q :=\n  Quot.recOn q f h\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quotient.mk a))]\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    : motive q :=\n  Quot.recOnSubsingleton (h := h) q f\n\nprotected abbrev hrecOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (c : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 HEq (f a) (f b))\n    : motive q :=\n  Quot.hrecOn q f c\nend\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB} {\u03c6 : Sort uC}\nvariable [s\u2081 : Setoid \u03b1] [s\u2082 : Setoid \u03b2]\n\nprotected abbrev lift\u2082\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    (q\u2081 : Quotient s\u2081) (q\u2082 : Quotient s\u2082)\n    : \u03c6 := by\n  apply Quotient.lift (fun (a\u2081 : \u03b1) => Quotient.lift (f a\u2081) (fun (a b : \u03b2) => c a\u2081 a a\u2081 b (Setoid.refl a\u2081)) q\u2082) _ q\u2081\n  intros\n  induction q\u2082 using Quotient.ind\n  apply c; assumption; apply Setoid.refl\n\nprotected abbrev liftOn\u2082\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    : \u03c6 :=\n  Quotient.lift\u2082 f c q\u2081 q\u2082\n\nprotected theorem ind\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2083\n    [s\u2083 : Setoid \u03c6]\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Quotient s\u2083 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (q\u2083 : Quotient s\u2083)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 (c : \u03c6) \u2192 motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))\n    : motive q\u2081 q\u2082 q\u2083 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  induction q\u2083 using Quotient.ind\n  apply h\n\nend\n\nsection Exact\n\nvariable   {\u03b1 : Sort u}\n\nprivate def rel [s : Setoid \u03b1] (q\u2081 q\u2082 : Quotient s) : Prop :=\n  Quotient.liftOn\u2082 q\u2081 q\u2082\n    (fun a\u2081 a\u2082 => a\u2081 \u2248 a\u2082)\n    (fun a\u2081 a\u2082 b\u2081 b\u2082 a\u2081b\u2081 a\u2082b\u2082 =>\n      propext (Iff.intro\n        (fun a\u2081a\u2082 => Setoid.trans (Setoid.symm a\u2081b\u2081) (Setoid.trans a\u2081a\u2082 a\u2082b\u2082))\n        (fun b\u2081b\u2082 => Setoid.trans a\u2081b\u2081 (Setoid.trans b\u2081b\u2082 (Setoid.symm a\u2082b\u2082)))))\n\nprivate theorem rel.refl [s : Setoid \u03b1] (q : Quotient s) : rel q q :=\n  Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a)\n\nprivate theorem rel_of_eq [s : Setoid \u03b1] {q\u2081 q\u2082 : Quotient s} : q\u2081 = q\u2082 \u2192 rel q\u2081 q\u2082 :=\n  fun h => Eq.ndrecOn h (rel.refl q\u2081)\n\ntheorem exact [s : Setoid \u03b1] {a b : \u03b1} : Quotient.mk a = Quotient.mk b \u2192 a \u2248 b :=\n  fun h => rel_of_eq h\n\nend Exact\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB}\nvariable [s\u2081 : Setoid \u03b1] [s\u2082 : Setoid \u03b2]\n\nprotected abbrev recOnSubsingleton\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Sort uC}\n    [s : (a : \u03b1) \u2192 (b : \u03b2) \u2192 Subsingleton (motive (Quotient.mk a) (Quotient.mk b))]\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (g : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quot.recOnSubsingleton\n  induction q\u2082 using Quot.recOnSubsingleton\n  apply g\n  intro a; apply s\n  induction q\u2082 using Quot.recOnSubsingleton\n  intro a; apply s\n  infer_instance\n\nend\nend Quotient\n\nsection\nvariable {\u03b1 : Type u}\nvariable (r : \u03b1 \u2192 \u03b1 \u2192 Prop)\n\ninstance {\u03b1 : Sort u} {s : Setoid \u03b1} [d : \u2200 (a b : \u03b1), Decidable (a \u2248 b)] : DecidableEq (Quotient s) :=\n  fun (q\u2081 q\u2082 : Quotient s) =>\n    Quotient.recOnSubsingleton\u2082 (motive := fun a b => Decidable (a = b)) q\u2081 q\u2082\n      fun a\u2081 a\u2082 =>\n        match d a\u2081 a\u2082 with\n        | isTrue h\u2081  => isTrue (Quotient.sound h\u2081)\n        | isFalse h\u2082 => isFalse fun h => absurd (Quotient.exact h) h\u2082\n\n/- Function extensionality -/\n\nnamespace Function\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\nprotected def Equiv (f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x) : Prop := \u2200 x, f\u2081 x = f\u2082 x\n\nprotected theorem Equiv.refl (f : \u2200 (x : \u03b1), \u03b2 x) : Function.Equiv f f :=\n  fun x => rfl\n\nprotected theorem Equiv.symm {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} : Function.Equiv f\u2081 f\u2082 \u2192 Function.Equiv f\u2082 f\u2081 :=\n  fun h x => Eq.symm (h x)\n\nprotected theorem Equiv.trans {f\u2081 f\u2082 f\u2083 : \u2200 (x : \u03b1), \u03b2 x} : Function.Equiv f\u2081 f\u2082 \u2192 Function.Equiv f\u2082 f\u2083 \u2192 Function.Equiv f\u2081 f\u2083 :=\n  fun h\u2081 h\u2082 x => Eq.trans (h\u2081 x) (h\u2082 x)\n\nprotected theorem Equiv.isEquivalence (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Equivalence (@Function.Equiv \u03b1 \u03b2) := {\n  refl := Equiv.refl\n  symm := Equiv.symm\n  trans := Equiv.trans\n}\n\nend Function\n\nsection\nopen Quotient\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\n@[instance]\nprivate def funSetoid (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Setoid (\u2200 (x : \u03b1), \u03b2 x) :=\n  Setoid.mk (@Function.Equiv \u03b1 \u03b2) (Function.Equiv.isEquivalence \u03b1 \u03b2)\n\nprivate def extfunApp (f : Quotient <| funSetoid \u03b1 \u03b2) (x : \u03b1) : \u03b2 x :=\n  Quot.liftOn f\n    (fun (f : \u2200 (x : \u03b1), \u03b2 x) => f x)\n    (fun f\u2081 f\u2082 h => h x)\n\ntheorem funext {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} (h : \u2200 x, f\u2081 x = f\u2082 x) : f\u2081 = f\u2082 := by\n  show extfunApp (Quotient.mk f\u2081) = extfunApp (Quotient.mk f\u2082)\n  apply congrArg\n  apply Quotient.sound\n  exact h\n\nend\n\ninstance {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton (\u2200 a, \u03b2 a) where\n  allEq f\u2081 f\u2082 :=\n    funext (fun a => Subsingleton.elim (f\u2081 a) (f\u2082 a))\n\n/- Squash -/\n\ndef Squash (\u03b1 : Type u) := Quot (fun (a b : \u03b1) => True)\n\ndef Squash.mk {\u03b1 : Type u} (x : \u03b1) : Squash \u03b1 := Quot.mk _ x\n\ntheorem Squash.ind {\u03b1 : Type u} {motive : Squash \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), motive (Squash.mk a)) : \u2200 (q : Squash \u03b1), motive q :=\n  Quot.ind h\n\n@[inline] def Squash.lift {\u03b1 \u03b2} [Subsingleton \u03b2] (s : Squash \u03b1) (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  Quot.lift f (fun a b _ => Subsingleton.elim _ _) s\n\ninstance : Subsingleton (Squash \u03b1) 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\nnamespace Lean\n/- Kernel reduction hints -/\n\n/--\n  When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.\n  The kernel will not use the interpreter if `c` is not a constant.\n  This feature is useful for performing proofs by reflection.\n\n  Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing\n  free 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\n  Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\n  This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using\n  external type checkers (e.g., Trepplein) that do not implement this feature.\n  Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\n  So, you are mainly losing the capability of type checking your developement using external checkers.\n\n  Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.\n  If an extern function is executed, then the trusted code base will also include the implementation of the associated\n  foreign function.\n-/\nconstant reduceBool (b : Bool) : Bool := b\n\n/--\n  Similar to `Lean.reduceBool` for closed `Nat` terms.\n\n  Remark: we do not have plans for supporting a generic `reduceValue {\u03b1} (a : \u03b1) : \u03b1 := a`.\n  The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.\n  We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/\nconstant reduceNat (n : Nat) : Nat := n\n\naxiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b\naxiom ofReduceNat (a b : Nat) (h : reduceNat a = b)    : a = b\n\nend Lean\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/Core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.04742587385075148, "lm_q1q2_score": 0.015377147130018724}}
{"text": "import ..data_util.util\nimport all\n\nsection main\nopen tactic\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  let dest : string := ((args.nth 0).get_or_else \"./data/mathlib_decls.log\"),\n  let ignore_decls_fn : environment \u2192 declaration \u2192 bool :=\n    (\u03bb e d, declaration.is_auto_or_internal e d || bnot (declaration.is_theorem d) || d.to_name.is_aux),\n  f \u2190 io.mk_file_handle dest io.mode.append,\n  io.run_tactic' $ do {\n    env \u2190 get_env,\n    mathlib_dir \u2190 get_mathlib_dir,\n    decls \u2190 list.filter (\u03bb d, !(ignore_decls_fn env d)) <$> (lint_project_decls mathlib_dir),\n    for_ decls $ \u03bb decl, do {\n      let decl_name := decl.to_name.to_string,\n      tactic.unsafe_run_io $ io.fs.put_str_ln f decl_name,\n      tactic.trace format!\"DECL: {decl_name}\"\n    }\n  }\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/tools/all_decls.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3007455914759599, "lm_q2_score": 0.051082732984356866, "lm_q1q2_score": 0.015362906745588933}}
{"text": "example (foo bar : OptionM Nat) : False := by\n  have : do { let x \u2190 bar; foo } = bar >>= fun x => foo := rfl\n  admit\n  done\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/500_lean3.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.04023794420614677, "lm_q1q2_score": 0.015339491637306435}}
{"text": "import Lib.Data.Array.Basic\nimport Lib.Data.List.Instances\nimport Lib.Data.Traversable\n\nnamespace Array\n\ninstance : Foldable Array where\n  foldr := Array.foldr\n  foldl := Array.foldl\n  toArray := id\n  toList := Array.toList\n  length := Array.size\n\ninstance : Traversable Array where\n  map := Array.map\n  traverse := Array.mapA\n  mapM := Array.mapM\n\n@[simp]\ntheorem map_toList {\u03b1 \u03b2 : Type _} (f : \u03b1 \u2192 \u03b2) (ar : Array \u03b1) :\n  f <$> ar.toList = (f <$> ar).toList := by\n-- have : f <$> ar = Array.map f ar := rfl\n-- rw [this]; simp [map, mapM]\nsuffices f <$> toList ar =\n         toList (foldl (fun bs a => push bs (f a))\n                       (mkEmpty (size ar)) ar)\n  from this\nrw [\u2190 foldl_toList]\nhave : toList (Foldable.foldl (fun bs a => push bs (f a)) (mkEmpty (size ar)) (toList ar)) =\n       Foldable.foldl (fun bs a => bs ++ [f a]) [] (toList ar) := by\n     apply LawfulFoldable.foldl_hom (h := toList)\n     <;> simp\nsimp only [Foldable.foldl] at this\nrw [this]; clear this\ngeneralize toList ar = ys\ntrans ([] ++ f <$> ys)\n. simp\nsuffices \u2200 xs,\n  xs ++ f <$> ys = List.foldl (fun bs a => bs ++ [f a]) xs ys\n  by apply this\nintros xs\ninduction ys generalizing xs\n<;> simp [List.foldl]\nnext y ys ih =>\nsimp [\u2190 ih, List.append_assoc]\n\ninstance : LawfulFoldable Array where\n  foldl_sim :=  by\n    intros; apply Array.foldl_sim <;> auto\n  toArray_toList := sorry\n  length_toList :=\n    by intros; simp [toList]; sorry\n  foldl_toList := by\n    intros; simp [toList, foldl]; sorry\n  foldr_eq_foldMap := sorry\n\ninstance : LawfulFunctor Array := sorry\n\ninstance : LawfulTraversable Array := by\napply LawfulTraversable_of_hom (T\u2080 := List) (T\u2081 := Array)\n  (g := @List.toArray)\n  (f := @Array.toList)\nfocus\n  intros; ext;\n  simp\nfocus\n  intros; ext;\n  simp\nfocus\n  intros; ext;\n  simp\nall_goals admit\n\nend Array\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/Data/Array/Instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.03410042387178048, "lm_q1q2_score": 0.015324479823034764}}
{"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<http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html>\n-/\nimport control.monad.writer\n\nuniverses u v w u\u2080 u\u2081 v\u2080 v\u2081\n\nstructure monad_cont.label (\u03b1 : Type w) (m : Type u \u2192 Type v) (\u03b2 : Type u) :=\n(apply : \u03b1 \u2192 m \u03b2)\n\ndef monad_cont.goto {\u03b1 \u03b2} {m : Type u \u2192 Type v} (f : monad_cont.label \u03b1 m \u03b2) (x : \u03b1) := f.apply x\n\nclass monad_cont (m : Type u \u2192 Type v) :=\n(call_cc : \u03a0 {\u03b1 \u03b2}, ((monad_cont.label \u03b1 m \u03b2) \u2192 m \u03b1) \u2192 m \u03b1)\n\nopen monad_cont\n\nclass is_lawful_monad_cont (m : Type u \u2192 Type v) [monad m] [monad_cont m]\nextends is_lawful_monad m :=\n(call_cc_bind_right {\u03b1 \u03c9 \u03b3} (cmd : m \u03b1) (next : (label \u03c9 m \u03b3) \u2192 \u03b1 \u2192 m \u03c9) :\n  call_cc (\u03bb f, cmd >>= next f) = cmd >>= \u03bb x, call_cc (\u03bb f, next f x))\n(call_cc_bind_left {\u03b1} (\u03b2) (x : \u03b1) (dead : label \u03b1 m \u03b2 \u2192 \u03b2 \u2192 m \u03b1) :\n  call_cc (\u03bb f : label \u03b1 m \u03b2, goto f x >>= dead f) = pure x)\n(call_cc_dummy {\u03b1 \u03b2} (dummy : m \u03b1) :\n  call_cc (\u03bb f : label \u03b1 m \u03b2, dummy) = dummy)\n\nexport is_lawful_monad_cont\n\ndef cont_t (r : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type w) := (\u03b1 \u2192 m r) \u2192 m r\n\n@[reducible] def cont (r : Type u) (\u03b1 : Type w) := cont_t r id \u03b1\n\nnamespace cont_t\n\nexport monad_cont (label goto)\n\nvariables {r : Type u} {m : Type u \u2192 Type v} {\u03b1 \u03b2 \u03b3 \u03c9 : Type w}\n\ndef run : cont_t r m \u03b1 \u2192 (\u03b1 \u2192 m r) \u2192 m r := id\n\ndef map (f : m r \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b1 := f \u2218 x\n\nlemma run_cont_t_map_cont_t (f : m r \u2192 m r) (x : cont_t r m \u03b1) :\n  run (map f x) = f \u2218 run x := rfl\n\ndef with_cont_t (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b2 :=\n\u03bb g, x $ f g\n\nlemma run_with_cont_t (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) :\n  run (with_cont_t f x) = run x \u2218 f := rfl\n\n@[ext]\nprotected lemma ext {x y : cont_t r m \u03b1}\n  (h : \u2200 f, x.run f = y.run f) :\n  x = y := by { ext; apply h }\n\ninstance : monad (cont_t r m) :=\n{ pure := \u03bb \u03b1 x f, f x,\n  bind := \u03bb \u03b1 \u03b2 x f g, x $ \u03bb 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] {\u03b1} : m \u03b1 \u2192 cont_t r m \u03b1 :=\n\u03bb x f, x >>= f\n\ninstance [monad m] : has_monad_lift m (cont_t r m) :=\n{ monad_lift := \u03bb \u03b1, cont_t.monad_lift }\n\nlemma monad_lift_bind [monad m] [is_lawful_monad m] {\u03b1 \u03b2} (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) :\n  (monad_lift (x >>= f) : cont_t r m \u03b2) = monad_lift x >>= monad_lift \u2218 f :=\nbegin\n  ext,\n  simp only [monad_lift,has_monad_lift.monad_lift,(\u2218),(>>=),bind_assoc,id.def,run,cont_t.monad_lift]\nend\n\ninstance : monad_cont (cont_t r m) :=\n{ call_cc := \u03bb \u03b1 \u03b2 f g, f \u27e8\u03bb x h, g x\u27e9 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 (\u03b5) [monad_except \u03b5 m] : monad_except \u03b5 (cont_t r m) :=\n{ throw := \u03bb x e f, throw e,\n  catch := \u03bb \u03b1 act h f, catch (act f) (\u03bb e, h e f) }\n\ninstance : monad_run (\u03bb \u03b1, (\u03b1 \u2192 m r) \u2192 ulift.{u v} (m r)) (cont_t.{u v u} r m) :=\n{ run := \u03bb \u03b1 f x, \u27e8 f x \u27e9 }\n\nend cont_t\n\nvariables {m : Type u \u2192 Type v} [monad m]\n\ndef except_t.mk_label {\u03b1 \u03b2 \u03b5} : label (except.{u u} \u03b5 \u03b1) m \u03b2 \u2192 label \u03b1 (except_t \u03b5 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, monad_lift $ f (except.ok a) \u27e9\n\nlemma except_t.goto_mk_label {\u03b1 \u03b2 \u03b5 : Type*} (x : label (except.{u u} \u03b5 \u03b1) m \u03b2) (i : \u03b1) :\n  goto (except_t.mk_label x) i = \u27e8 except.ok <$> goto x (except.ok i) \u27e9 := by cases x; refl\n\ndef except_t.call_cc\n  {\u03b5} [monad_cont m] {\u03b1 \u03b2 : Type*} (f : label \u03b1 (except_t \u03b5 m) \u03b2 \u2192 except_t \u03b5 m \u03b1) :\n  except_t \u03b5 m \u03b1 :=\nexcept_t.mk (call_cc $ \u03bb x : label _ m \u03b2, except_t.run $ f (except_t.mk_label x) : m (except \u03b5 \u03b1))\n\ninstance {\u03b5} [monad_cont m] : monad_cont (except_t \u03b5 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, except_t.call_cc }\n\ninstance {\u03b5} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t \u03b5 m) :=\n{ call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp,\n    congr' with \u27e8 \u27e9; 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 {\u03b1 \u03b2} : label (option.{u} \u03b1) m \u03b2 \u2192 label \u03b1 (option_t m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, monad_lift $ f (some a) \u27e9\n\nlemma option_t.goto_mk_label {\u03b1 \u03b2 : Type*} (x : label (option.{u} \u03b1) m \u03b2) (i : \u03b1) :\n  goto (option_t.mk_label x) i = \u27e8 some <$> goto x (some i) \u27e9 := by cases x; refl\n\ndef option_t.call_cc [monad_cont m] {\u03b1 \u03b2 : Type*} (f : label \u03b1 (option_t m) \u03b2 \u2192 option_t m \u03b1) :\n  option_t m \u03b1 :=\noption_t.mk (call_cc $ \u03bb x : label _ m \u03b2, option_t.run $ f (option_t.mk_label x) : m (option \u03b1))\n\ninstance [monad_cont m] : monad_cont (option_t m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, 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 \u27e8 \u27e9; 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 {\u03b1 \u03b2 \u03c9} [has_one \u03c9] : label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 label \u03b1 (writer_t \u03c9 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, monad_lift $ f (a,1) \u27e9\n\nlemma writer_t.goto_mk_label {\u03b1 \u03b2 \u03c9 : Type*} [has_one \u03c9] (x : label (\u03b1 \u00d7 \u03c9) m \u03b2) (i : \u03b1) :\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] {\u03b1 \u03b2 \u03c9 : Type*} [has_one \u03c9]\n  (f : label \u03b1 (writer_t \u03c9 m) \u03b2 \u2192 writer_t \u03c9 m \u03b1) : writer_t \u03c9 m \u03b1 :=\n\u27e8 call_cc (writer_t.run \u2218 f \u2218 writer_t.mk_label : label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 m (\u03b1 \u00d7 \u03c9)) \u27e9\n\ninstance (\u03c9) [monad m] [has_one \u03c9] [monad_cont m] : monad_cont (writer_t \u03c9 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, writer_t.call_cc }\n\ndef state_t.mk_label {\u03b1 \u03b2 \u03c3 : Type u} : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3) \u2192 label \u03b1 (state_t \u03c3 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, \u27e8 \u03bb s, f (a,s) \u27e9 \u27e9\n\nlemma state_t.goto_mk_label {\u03b1 \u03b2 \u03c3 : Type u} (x : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) (i : \u03b1) :\n  goto (state_t.mk_label x) i = \u27e8 \u03bb s, (goto x (i,s)) \u27e9 := by cases x; refl\n\ndef state_t.call_cc {\u03c3}  [monad_cont m] {\u03b1 \u03b2 : Type*}\n  (f : label \u03b1 (state_t \u03c3 m) \u03b2 \u2192 state_t \u03c3 m \u03b1) : state_t \u03c3 m \u03b1 :=\n\u27e8 \u03bb r, call_cc (\u03bb f', (f $ state_t.mk_label f').run r) \u27e9\n\ninstance {\u03c3} [monad_cont m] : monad_cont (state_t \u03c3 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, state_t.call_cc }\n\ninstance {\u03c3} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t \u03c3 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 \u27e8x\u2080,x\u2081\u27e9, 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 {\u03b1 \u03b2} (\u03c1) : label \u03b1 m \u03b2 \u2192 label \u03b1 (reader_t \u03c1 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 monad_lift \u2218 f \u27e9\n\nlemma reader_t.goto_mk_label {\u03b1 \u03c1 \u03b2} (x : label \u03b1 m \u03b2) (i : \u03b1) :\n  goto (reader_t.mk_label \u03c1 x) i = monad_lift (goto x i) := by cases x; refl\n\ndef reader_t.call_cc {\u03b5}  [monad_cont m] {\u03b1 \u03b2 : Type*}\n  (f : label \u03b1 (reader_t \u03b5 m) \u03b2 \u2192 reader_t \u03b5 m \u03b1) : reader_t \u03b5 m \u03b1 :=\n\u27e8 \u03bb r, call_cc (\u03bb f', (f $ reader_t.mk_label _ f').run r) \u27e9\n\ninstance {\u03c1} [monad_cont m] : monad_cont (reader_t \u03c1 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, reader_t.call_cc }\n\ninstance {\u03c1} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t \u03c1 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081}\n  {\u03b1\u2081 r\u2081 : Type u\u2080} {\u03b1\u2082 r\u2082 : Type u\u2081} (F : m\u2081 r\u2081 \u2243 m\u2082 r\u2082) (G : \u03b1\u2081 \u2243 \u03b1\u2082) :\n  cont_t r\u2081 m\u2081 \u03b1\u2081 \u2243 cont_t r\u2082 m\u2082 \u03b1\u2082 :=\n{ to_fun := \u03bb f r, F $ f $ \u03bb x, F.symm $ r $ G x,\n  inv_fun := \u03bb f r, F.symm $ f $ \u03bb x, F $ r $ G.symm x,\n  left_inv := \u03bb f, by funext r; simp,\n  right_inv := \u03bb 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": "/-\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.Data.List.Basic\nimport Init.Data.Char.Basic\nimport Init.Data.Option.Basic\nuniverse u\n\ndef List.asString (s : List Char) : String :=\n  \u27e8s\u27e9\n\nnamespace String\n\ninstance : OfNat String.Pos (nat_lit 0) where\n  ofNat := {}\n\ninstance : LT String :=\n  \u27e8fun s\u2081 s\u2082 => s\u2081.data < s\u2082.data\u27e9\n\n@[extern \"lean_string_dec_lt\"]\ninstance decLt (s\u2081 s\u2082 : @& String) : Decidable (s\u2081 < s\u2082) :=\n  List.hasDecidableLt s\u2081.data s\u2082.data\n\n@[extern \"lean_string_length\"]\ndef length : (@& String) \u2192 Nat\n  | \u27e8s\u27e9 => s.length\n\n/-- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the String is not shared. -/\n@[extern \"lean_string_push\"]\ndef push : String \u2192 Char \u2192 String\n  | \u27e8s\u27e9, c => \u27e8s ++ [c]\u27e9\n\n/-- The internal implementation uses dynamic arrays and will perform destructive updates\n   if the String is not shared. -/\n@[extern \"lean_string_append\"]\ndef append : String \u2192 (@& String) \u2192 String\n  | \u27e8a\u27e9, \u27e8b\u27e9 => \u27e8a ++ b\u27e9\n\n/-- O(n) in the runtime, where n is the length of the String -/\ndef toList (s : String) : List Char :=\n  s.data\n\nprivate def utf8GetAux : List Char \u2192 Pos \u2192 Pos \u2192 Char\n  | [],    _, _ => default\n  | c::cs, i, p => if i = p then c else utf8GetAux cs (i + c) p\n\n/--\n  Return character at position `p`. If `p` is not a valid position\n  returns `(default : Char)`.\n  See `utf8GetAux` for the reference implementation.\n-/\n@[extern \"lean_string_utf8_get\"]\ndef get (s : @& String) (p : @& Pos) : Char :=\n  match s with\n  | \u27e8s\u27e9 => utf8GetAux s 0 p\n\nprivate def utf8GetAux? : List Char \u2192 Pos \u2192 Pos \u2192 Option Char\n  | [],    _, _ => none\n  | c::cs, i, p => if i = p then c else utf8GetAux cs (i + c) p\n\n@[extern \"lean_string_utf8_get_opt\"]\ndef get? : (@& String) \u2192 (@& Pos) \u2192 Option Char\n  | \u27e8s\u27e9, p => utf8GetAux? s 0 p\n\n/--\n  Similar to `get`, but produces a panic error message if `p` is not a valid `String.Pos`.\n-/\n@[extern \"lean_string_utf8_get_bang\"]\ndef get! (s : @& String) (p : @& Pos) : Char :=\n  match s with\n  | \u27e8s\u27e9 => utf8GetAux s 0 p\n\nprivate def utf8SetAux (c' : Char) : List Char \u2192 Pos \u2192 Pos \u2192 List Char\n  | [],    _, _ => []\n  | c::cs, i, p =>\n    if i = p then (c'::cs) else c::(utf8SetAux c' cs (i + c) p)\n\n@[extern \"lean_string_utf8_set\"]\ndef set : String \u2192 (@& Pos) \u2192 Char \u2192 String\n  | \u27e8s\u27e9, i, c => \u27e8utf8SetAux c s 0 i\u27e9\n\ndef modify (s : String) (i : Pos) (f : Char \u2192 Char) : String :=\n  s.set i <| f <| s.get i\n\n@[extern \"lean_string_utf8_next\"]\ndef next (s : @& String) (p : @& Pos) : Pos :=\n  let c := get s p\n  p + c\n\nprivate def utf8PrevAux : List Char \u2192 Pos \u2192 Pos \u2192 Pos\n  | [],    _, _ => 0\n  | c::cs, i, p =>\n    let i' := i + c\n    if i' = p then i else utf8PrevAux cs i' p\n\n@[extern \"lean_string_utf8_prev\"]\ndef prev : (@& String) \u2192 (@& Pos) \u2192 Pos\n  | \u27e8s\u27e9, p => if p = 0 then 0 else utf8PrevAux s 0 p\n\ndef front (s : String) : Char :=\n  get s 0\n\ndef back (s : String) : Char :=\n  get s (prev s s.endPos)\n\n@[extern \"lean_string_utf8_at_end\"]\ndef atEnd : (@& String) \u2192 (@& Pos) \u2192 Bool\n  | s, p => p.byteIdx \u2265 utf8ByteSize s\n\n/--\nSimilar to `get` but runtime does not perform bounds check.\n-/\n@[extern \"lean_string_utf8_get_fast\"]\ndef get' (s : @& String) (p : @& Pos) (h : \u00ac s.atEnd p) : Char :=\n  match s with\n  | \u27e8s\u27e9 => utf8GetAux s 0 p\n\n@[extern \"lean_string_utf8_next_fast\"]\ndef next' (s : @& String) (p : @& Pos) (h : \u00ac s.atEnd p) : Pos :=\n  let c := get s p\n  p + c\n\n/- TODO: remove `partial` keywords after we restore the tactic\n  framework and wellfounded recursion support -/\n\npartial def posOfAux (s : String) (c : Char) (stopPos : Pos) (pos : Pos) : Pos :=\n  if pos >= stopPos then pos\n  else if s.get pos == c then pos\n       else posOfAux s c stopPos (s.next pos)\n\n@[inline] def posOf (s : String) (c : Char) : Pos :=\n  posOfAux s c s.endPos 0\n\npartial def revPosOfAux (s : String) (c : Char) (pos : Pos) : Option Pos :=\n if s.get pos == c then some pos\n else if pos == 0 then none\n else revPosOfAux s c (s.prev pos)\n\ndef revPosOf (s : String) (c : Char) : Option Pos :=\n  if s.endPos == 0 then none\n  else revPosOfAux s c (s.prev s.endPos)\n\npartial def findAux (s : String) (p : Char \u2192 Bool) (stopPos : Pos) (pos : Pos) : Pos :=\n  if pos >= stopPos then pos\n  else if p (s.get pos) then pos\n       else findAux s p stopPos (s.next pos)\n\n@[inline] def find (s : String) (p : Char \u2192 Bool) : Pos :=\n  findAux s p s.endPos 0\n\npartial def revFindAux (s : String) (p : Char \u2192 Bool) (pos : Pos) : Option Pos :=\n if p (s.get pos) then some pos\n else if pos == 0 then none\n else revFindAux s p (s.prev pos)\n\ndef revFind (s : String) (p : Char \u2192 Bool) : Option Pos :=\n  if s.endPos == 0 then none\n  else revFindAux s p (s.prev s.endPos)\n\nabbrev Pos.min (p\u2081 p\u2082 : Pos) : Pos :=\n  { byteIdx := p\u2081.byteIdx.min p\u2082.byteIdx }\n\n/-- Returns the first position where the two strings differ. -/\npartial def firstDiffPos (a b : String) : Pos :=\n  let stopPos := a.endPos.min b.endPos\n  let rec loop (i : Pos) : Pos :=\n    if i >= stopPos || a.get i != b.get i then i\n    else loop (a.next i)\n  loop 0\n\n@[extern \"lean_string_utf8_extract\"]\ndef extract : (@& String) \u2192 (@& Pos) \u2192 (@& Pos) \u2192 String\n  | \u27e8s\u27e9, b, e => if b.byteIdx \u2265 e.byteIdx then \u27e8[]\u27e9 else \u27e8go\u2081 s 0 b e\u27e9\nwhere\n  go\u2081 : List Char \u2192 Pos \u2192 Pos \u2192 Pos \u2192 List Char\n    | [],        _, _, _ => []\n    | s@(c::cs), i, b, e => if i = b then go\u2082 s i e else go\u2081 cs (i + c) b e\n\n  go\u2082 : List Char \u2192 Pos \u2192 Pos \u2192 List Char\n    | [],    _, _ => []\n    | c::cs, i, e => if i = e then [] else c :: go\u2082 cs (i + c) e\n\n\n@[specialize] partial def splitAux (s : String) (p : Char \u2192 Bool) (b : Pos) (i : Pos) (r : List String) : List String :=\n  if s.atEnd i then\n    let r := (s.extract b i)::r\n    r.reverse\n  else if p (s.get i) then\n    let i := s.next i\n    splitAux s p i i (s.extract b { byteIdx := i.byteIdx - 1 } :: r)\n  else\n    splitAux s p b (s.next i) r\n\n@[specialize] def split (s : String) (p : Char \u2192 Bool) : List String :=\n  splitAux s p 0 0 []\n\npartial def splitOnAux (s sep : String) (b : Pos) (i : Pos) (j : Pos) (r : List String) : List String :=\n  if s.atEnd i then\n    let r := if sep.atEnd j then \"\"::(s.extract b (i - j))::r else (s.extract b i)::r\n    r.reverse\n  else if s.get i == sep.get j then\n    let i := s.next i\n    let j := sep.next j\n    if sep.atEnd j then\n      splitOnAux s sep i i 0 (s.extract b (i - j)::r)\n    else\n      splitOnAux s sep b i j r\n  else\n    splitOnAux s sep b (s.next i) 0 r\n\ndef splitOn (s : String) (sep : String := \" \") : List String :=\n  if sep == \"\" then [s] else splitOnAux s sep 0 0 0 []\n\ninstance : Inhabited String := \u27e8\"\"\u27e9\n\ninstance : Append String := \u27e8String.append\u27e9\n\ndef str : String \u2192 Char \u2192 String := push\n\ndef pushn (s : String) (c : Char) (n : Nat) : String :=\n  n.repeat (fun s => s.push c) s\n\ndef isEmpty (s : String) : Bool :=\n  s.endPos == 0\n\ndef join (l : List String) : String :=\n  l.foldl (fun r s => r ++ s) \"\"\n\ndef singleton (c : Char) : String :=\n  \"\".push c\n\ndef intercalate (s : String) : List String \u2192 String\n  | []      => \"\"\n  | a :: as => go a s as\nwhere go (acc : String) (s : String) : List String \u2192 String\n  | a :: as => go (acc ++ s ++ a) s as\n  | []      => acc\n\n/-- Iterator for `String`. That is, a `String` and a position in that string. -/\nstructure Iterator where\n  s : String\n  i : Pos\n  deriving DecidableEq\n\ndef mkIterator (s : String) : Iterator :=\n  \u27e8s, 0\u27e9\n\nabbrev iter := mkIterator\n\ninstance : SizeOf String.Iterator where\n  sizeOf i := i.1.utf8ByteSize - i.2.byteIdx\n\ntheorem Iterator.sizeOf_eq (i : String.Iterator) : sizeOf i = i.1.utf8ByteSize - i.2.byteIdx :=\n  rfl\n\nnamespace Iterator\ndef toString : Iterator \u2192 String\n  | \u27e8s, _\u27e9 => s\n\ndef remainingBytes : Iterator \u2192 Nat\n  | \u27e8s, i\u27e9 => s.endPos.byteIdx - i.byteIdx\n\ndef pos : Iterator \u2192 Pos\n  | \u27e8_, i\u27e9 => i\n\ndef curr : Iterator \u2192 Char\n  | \u27e8s, i\u27e9 => get s i\n\ndef next : Iterator \u2192 Iterator\n  | \u27e8s, i\u27e9 => \u27e8s, s.next i\u27e9\n\ndef prev : Iterator \u2192 Iterator\n  | \u27e8s, i\u27e9 => \u27e8s, s.prev i\u27e9\n\ndef atEnd : Iterator \u2192 Bool\n  | \u27e8s, i\u27e9 => i.byteIdx \u2265 s.endPos.byteIdx\n\ndef hasNext : Iterator \u2192 Bool\n  | \u27e8s, i\u27e9 => i.byteIdx < s.endPos.byteIdx\n\ndef hasPrev : Iterator \u2192 Bool\n  | \u27e8_, i\u27e9 => i.byteIdx > 0\n\ndef setCurr : Iterator \u2192 Char \u2192 Iterator\n  | \u27e8s, i\u27e9, c => \u27e8s.set i c, i\u27e9\n\ndef toEnd : Iterator \u2192 Iterator\n  | \u27e8s, _\u27e9 => \u27e8s, s.endPos\u27e9\n\ndef extract : Iterator \u2192 Iterator \u2192 String\n  | \u27e8s\u2081, b\u27e9, \u27e8s\u2082, e\u27e9 =>\n    if s\u2081 \u2260 s\u2082 || b > e then \"\"\n    else s\u2081.extract b e\n\ndef forward : Iterator \u2192 Nat \u2192 Iterator\n  | it, 0   => it\n  | it, n+1 => forward it.next n\n\ndef remainingToString : Iterator \u2192 String\n  | \u27e8s, i\u27e9 => s.extract i s.endPos\n\ndef nextn : Iterator \u2192 Nat \u2192 Iterator\n  | it, 0   => it\n  | it, i+1 => nextn it.next i\n\ndef prevn : Iterator \u2192 Nat \u2192 Iterator\n  | it, 0   => it\n  | it, i+1 => prevn it.prev i\nend Iterator\n\npartial def offsetOfPosAux (s : String) (pos : Pos) (i : Pos) (offset : Nat) : Nat :=\n  if i >= pos || s.atEnd i then\n    offset\n  else\n    offsetOfPosAux s pos (s.next i) (offset+1)\n\ndef offsetOfPos (s : String) (pos : Pos) : Nat :=\n  offsetOfPosAux s pos 0 0\n\n@[specialize] partial def foldlAux {\u03b1 : Type u} (f : \u03b1 \u2192 Char \u2192 \u03b1) (s : String) (stopPos : Pos) (i : Pos) (a : \u03b1) : \u03b1 :=\n  let rec loop (i : Pos) (a : \u03b1) :=\n    if i >= stopPos then a\n    else loop (s.next i) (f a (s.get i))\n  loop i a\n\n@[inline] def foldl {\u03b1 : Type u} (f : \u03b1 \u2192 Char \u2192 \u03b1) (init : \u03b1) (s : String) : \u03b1 :=\n  foldlAux f s s.endPos 0 init\n\n@[specialize] partial def foldrAux {\u03b1 : Type u} (f : Char \u2192 \u03b1 \u2192 \u03b1) (a : \u03b1) (s : String) (stopPos : Pos) (i : Pos) : \u03b1 :=\n  let rec loop (i : Pos) :=\n    if i >= stopPos then a\n    else f (s.get i) (loop (s.next i))\n  loop i\n\n@[inline] def foldr {\u03b1 : Type u} (f : Char \u2192 \u03b1 \u2192 \u03b1) (init : \u03b1) (s : String) : \u03b1 :=\n  foldrAux f init s s.endPos 0\n\n@[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char \u2192 Bool) (i : Pos) : Bool :=\n  let rec loop (i : Pos) :=\n    if i >= stopPos then false\n    else if p (s.get i) then true\n    else loop (s.next i)\n  loop i\n\n@[inline] def any (s : String) (p : Char \u2192 Bool) : Bool :=\nanyAux s s.endPos p 0\n\n@[inline] def all (s : String) (p : Char \u2192 Bool) : Bool :=\n!s.any (fun c => !p c)\n\ndef contains (s : String) (c : Char) : Bool :=\ns.any (fun a => a == c)\n\n@[specialize] partial def mapAux (f : Char \u2192 Char) (i : Pos) (s : String) : String :=\n  if s.atEnd i then s\n  else\n    let c := f (s.get i)\n    let s := s.set i c\n    mapAux f (s.next i) s\n\n@[inline] def map (f : Char \u2192 Char) (s : String) : String :=\n  mapAux f 0 s\n\ndef isNat (s : String) : Bool :=\n  !s.isEmpty && s.all (\u00b7.isDigit)\n\ndef toNat? (s : String) : Option Nat :=\n  if s.isNat then\n    some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0\n  else\n    none\n\n/--\nReturn `true` iff the substring of byte size `sz` starting at position `off1` in `s1` is equal to that starting at `off2` in `s2.`.\nFalse if either substring of that byte size does not exist. -/\npartial def substrEq (s1 : String) (off1 : String.Pos) (s2 : String) (off2 : String.Pos) (sz : Nat) : Bool :=\n  off1.byteIdx + sz \u2264 s1.endPos.byteIdx && off2.byteIdx + sz \u2264 s2.endPos.byteIdx && loop off1 off2 { byteIdx := off1.byteIdx + sz }\nwhere\n  loop (off1 off2 stop1 : Pos) :=\n    if off1.byteIdx >= stop1.byteIdx then\n      true\n    else\n      let c\u2081 := s1.get off1\n      let c\u2082 := s2.get off2\n      c\u2081 == c\u2082 && loop (off1 + c\u2081) (off2 + c\u2082) stop1\n\n/-- Return true iff `p` is a prefix of `s` -/\ndef isPrefixOf (p : String) (s : String) : Bool :=\n  substrEq p 0 s 0 p.endPos.byteIdx\n\n/-- Replace all occurrences of `pattern` in `s` with `replacment`. -/\npartial def replace (s pattern replacement : String) : String :=\n  loop \"\" 0 0\nwhere\n  loop (acc : String) (accStop pos : String.Pos) :=\n    if pos.byteIdx + pattern.endPos.byteIdx > s.endPos.byteIdx then\n      acc ++ s.extract accStop s.endPos\n    else if s.substrEq pos pattern 0 pattern.endPos.byteIdx then\n      loop (acc ++ s.extract accStop pos ++ replacement) (pos + pattern) (pos + pattern)\n    else\n      loop acc accStop (s.next pos)\n\nend String\n\nnamespace Substring\n\n@[inline] def isEmpty (ss : Substring) : Bool :=\n  ss.bsize == 0\n\n@[inline] def toString : Substring \u2192 String\n  | \u27e8s, b, e\u27e9 => s.extract b e\n\n@[inline] def toIterator : Substring \u2192 String.Iterator\n  | \u27e8s, b, _\u27e9 => \u27e8s, b\u27e9\n\n/-- Return the codepoint at the given offset into the substring. -/\n@[inline] def get : Substring \u2192 String.Pos \u2192 Char\n  | \u27e8s, b, _\u27e9, p => s.get (b+p)\n\n/-- Given an offset of a codepoint into the substring,\nreturn the offset there of the next codepoint. -/\n@[inline] def next : Substring \u2192 String.Pos \u2192 String.Pos\n  | \u27e8s, b, e\u27e9, p =>\n    let absP := b+p\n    if absP = e then p else { byteIdx := (s.next absP).byteIdx - b.byteIdx }\n\n/-- Given an offset of a codepoint into the substring,\nreturn the offset there of the previous codepoint. -/\n@[inline] def prev : Substring \u2192 String.Pos \u2192 String.Pos\n  | \u27e8s, b, _\u27e9, p =>\n    let absP := b+p\n    if absP = b then p else { byteIdx := (s.prev absP).byteIdx - b.byteIdx }\n\ndef nextn : Substring \u2192 Nat \u2192 String.Pos \u2192 String.Pos\n  | _,  0,   p => p\n  | ss, i+1, p => ss.nextn i (ss.next p)\n\ndef prevn : Substring \u2192 Nat \u2192 String.Pos \u2192 String.Pos\n  | _,  0,   p => p\n  | ss, i+1, p => ss.prevn i (ss.prev p)\n\n@[inline] def front (s : Substring) : Char :=\n  s.get 0\n\n/-- Return the offset into `s` of the first occurence of `c` in `s`,\nor `s.bsize` if `c` doesn't occur. -/\n@[inline] def posOf (s : Substring) (c : Char) : String.Pos :=\n  match s with\n  | \u27e8s, b, e\u27e9 => { byteIdx := (String.posOfAux s c e b).byteIdx - b.byteIdx }\n\n@[inline] def drop : Substring \u2192 Nat \u2192 Substring\n  | ss@\u27e8s, b, e\u27e9, n => \u27e8s, b + ss.nextn n 0, e\u27e9\n\n@[inline] def dropRight : Substring \u2192 Nat \u2192 Substring\n  | ss@\u27e8s, b, _\u27e9, n => \u27e8s, b, b + ss.prevn n \u27e8ss.bsize\u27e9\u27e9\n\n@[inline] def take : Substring \u2192 Nat \u2192 Substring\n  | ss@\u27e8s, b, _\u27e9, n => \u27e8s, b, b + ss.nextn n 0\u27e9\n\n@[inline] def takeRight : Substring \u2192 Nat \u2192 Substring\n  | ss@\u27e8s, b, e\u27e9, n => \u27e8s, b + ss.prevn n \u27e8ss.bsize\u27e9, e\u27e9\n\n@[inline] def atEnd : Substring \u2192 String.Pos \u2192 Bool\n  | \u27e8_, b, e\u27e9, p => b + p == e\n\n@[inline] def extract : Substring \u2192 String.Pos \u2192 String.Pos \u2192 Substring\n  | \u27e8s, b, e\u27e9, b', e' => if b' \u2265 e' then \u27e8\"\", 0, 0\u27e9 else \u27e8s, e.min (b+b'), e.min (b+e')\u27e9\n\npartial def splitOn (s : Substring) (sep : String := \" \") : List Substring :=\n  if sep == \"\" then\n    [s]\n  else\n    let rec loop (b i j : String.Pos) (r : List Substring) : List Substring :=\n      if i.byteIdx == s.bsize then\n        let r := if sep.atEnd j then\n          \"\".toSubstring :: s.extract b (i-j) :: r\n        else\n          s.extract b i :: r\n        r.reverse\n      else if s.get i == sep.get j then\n        let i := s.next i\n        let j := sep.next j\n        if sep.atEnd j then\n          loop i i 0 (s.extract b (i-j) :: r)\n        else\n          loop b i j r\n      else\n        loop b (s.next i) 0 r\n    loop 0 0 0 []\n\n@[inline] def foldl {\u03b1 : Type u} (f : \u03b1 \u2192 Char \u2192 \u03b1) (init : \u03b1) (s : Substring) : \u03b1 :=\n  match s with\n  | \u27e8s, b, e\u27e9 => String.foldlAux f s e b init\n\n@[inline] def foldr {\u03b1 : Type u} (f : Char \u2192 \u03b1 \u2192 \u03b1) (init : \u03b1) (s : Substring) : \u03b1 :=\n  match s with\n  | \u27e8s, b, e\u27e9 => String.foldrAux f init s e b\n\n@[inline] def any (s : Substring) (p : Char \u2192 Bool) : Bool :=\n  match s with\n  | \u27e8s, b, e\u27e9 => String.anyAux s e p b\n\n@[inline] def all (s : Substring) (p : Char \u2192 Bool) : Bool :=\n  !s.any (fun c => !p c)\n\ndef contains (s : Substring) (c : Char) : Bool :=\n  s.any (fun a => a == c)\n\n@[specialize] private partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char \u2192 Bool) (i : String.Pos) : String.Pos :=\n  if i >= stopPos then i\n  else if p (s.get i) then takeWhileAux s stopPos p (s.next i)\n  else i\n\n@[inline] def takeWhile : Substring \u2192 (Char \u2192 Bool) \u2192 Substring\n  | \u27e8s, b, e\u27e9, p =>\n    let e := takeWhileAux s e p b;\n    \u27e8s, b, e\u27e9\n\n@[inline] def dropWhile : Substring \u2192 (Char \u2192 Bool) \u2192 Substring\n  | \u27e8s, b, e\u27e9, p =>\n    let b := takeWhileAux s e p b;\n    \u27e8s, b, e\u27e9\n\n@[specialize] private partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char \u2192 Bool) (i : String.Pos) : String.Pos :=\n  if i == begPos then i\n  else\n    let i' := s.prev i\n    let c  := s.get i'\n    if !p c then i\n    else takeRightWhileAux s begPos p i'\n\n@[inline] def takeRightWhile : Substring \u2192 (Char \u2192 Bool) \u2192 Substring\n  | \u27e8s, b, e\u27e9, p =>\n    let b := takeRightWhileAux s b p e\n    \u27e8s, b, e\u27e9\n\n@[inline] def dropRightWhile : Substring \u2192 (Char \u2192 Bool) \u2192 Substring\n  | \u27e8s, b, e\u27e9, p =>\n    let e := takeRightWhileAux s b p e\n    \u27e8s, b, e\u27e9\n\n@[inline] def trimLeft (s : Substring) : Substring :=\n  s.dropWhile Char.isWhitespace\n\n@[inline] def trimRight (s : Substring) : Substring :=\n  s.dropRightWhile Char.isWhitespace\n\n@[inline] def trim : Substring \u2192 Substring\n  | \u27e8s, b, e\u27e9 =>\n    let b := takeWhileAux s e Char.isWhitespace b\n    let e := takeRightWhileAux s b Char.isWhitespace e\n    \u27e8s, b, e\u27e9\n\ndef isNat (s : Substring) : Bool :=\n  s.all fun c => c.isDigit\n\ndef toNat? (s : Substring) : Option Nat :=\n  if s.isNat then\n    some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0\n  else\n    none\n\ndef beq (ss1 ss2 : Substring) : Bool :=\n  ss1.bsize == ss2.bsize && ss1.str.substrEq ss1.startPos ss2.str ss2.startPos ss1.bsize\n\ninstance hasBeq : BEq Substring := \u27e8beq\u27e9\n\nend Substring\n\nnamespace String\n\ndef drop (s : String) (n : Nat) : String :=\n  (s.toSubstring.drop n).toString\n\ndef dropRight (s : String) (n : Nat) : String :=\n  (s.toSubstring.dropRight n).toString\n\ndef take (s : String) (n : Nat) : String :=\n  (s.toSubstring.take n).toString\n\ndef takeRight (s : String) (n : Nat) : String :=\n  (s.toSubstring.takeRight n).toString\n\ndef takeWhile (s : String) (p : Char \u2192 Bool) : String :=\n  (s.toSubstring.takeWhile p).toString\n\ndef dropWhile (s : String) (p : Char \u2192 Bool) : String :=\n  (s.toSubstring.dropWhile p).toString\n\ndef takeRightWhile (s : String) (p : Char \u2192 Bool) : String :=\n  (s.toSubstring.takeRightWhile p).toString\n\ndef dropRightWhile (s : String) (p : Char \u2192 Bool) : String :=\n  (s.toSubstring.dropRightWhile p).toString\n\ndef startsWith (s pre : String) : Bool :=\n  s.toSubstring.take pre.length == pre.toSubstring\n\ndef endsWith (s post : String) : Bool :=\n  s.toSubstring.takeRight post.length == post.toSubstring\n\ndef trimRight (s : String) : String :=\n  s.toSubstring.trimRight.toString\n\ndef trimLeft (s : String) : String :=\n  s.toSubstring.trimLeft.toString\n\ndef trim (s : String) : String :=\n  s.toSubstring.trim.toString\n\n@[inline] def nextWhile (s : String) (p : Char \u2192 Bool) (i : String.Pos) : String.Pos :=\n  Substring.takeWhileAux s s.endPos p i\n\n@[inline] def nextUntil (s : String) (p : Char \u2192 Bool) (i : String.Pos) : String.Pos :=\n  nextWhile s (fun c => !p c) i\n\ndef toUpper (s : String) : String :=\n  s.map Char.toUpper\n\ndef toLower (s : String) : String :=\n  s.map Char.toLower\n\ndef capitalize (s : String) :=\n  s.set 0 <| s.get 0 |>.toUpper\n\ndef decapitalize (s : String) :=\n  s.set 0 <| s.get 0 |>.toLower\n\nend String\n\nprotected def Char.toString (c : Char) : String :=\n  String.singleton c\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/String/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934935817440722, "lm_q2_score": 0.06371500136344282, "lm_q1q2_score": 0.01525014468242152}}
{"text": "import Lean\nimport PremiseSelection.StatementFeatures\n\nopen Lean System\n\nnamespace String\n\n/-- Check if a string is contained in another one. -/\npartial def isSubstrOf (target str : String) : Bool :=\n  loop \"\" 0\nwhere\n  loop (acc : String) (pos : String.Pos) : Bool :=\n    if pos.byteIdx + target.endPos.byteIdx > str.endPos.byteIdx then\n      false\n    else if str.substrEq pos target 0 target.endPos.byteIdx then\n      true\n    else\n      loop acc (str.next pos)\n\nend String\n\n/-- Find file path from module imported from Mathbin. -/\ndef pathFromMathbinImport (mod : Name) : MetaM (Option FilePath) := do\n  let mathbinPath : System.FilePath := \".\" / \"lake-packages\" / \"mathlib3port\"\n  SearchPath.findModuleWithExt [mathbinPath] \"lean\" mod\n\n/-- Find file path from module imported from Mathbin. -/\ndef pathFromMathlibImport (mod : Name) : MetaM (Option FilePath) := do\n  let mathbinPath : System.FilePath := \".\" / \"lake-packages\" / \"mathlib\"\n  SearchPath.findModuleWithExt [mathbinPath] \"lean\" mod\n\n/-- Find file path of JSON with proof sources. -/\ndef proofSourcePath (mod : Name) : MetaM (Option FilePath) := do\n  let mathbinPath : System.FilePath := \".\" / \"data\" / \"proof_sources\"\n  SearchPath.findModuleWithExt [mathbinPath] \"json\" mod\n\n/-- Given a theorem name and a file path, extract the proof text. -/\ndef proofSource (thm : Name) (json : Json) : MetaM (Option String) := do\n  if let Name.str _ thmStr := thm then\n    match json.getObjVal? thmStr  with\n    | Except.ok (Json.str s) =>\n        return some s\n    | _ => return none\n  return none\n\nnamespace PremiseSelection\n\n/-- Given a list of premises and proof text, get rid of the ones that do not\nappear. We take into account `ToAdditive` name translations. -/\ndef filterUserPremises (premises : Multiset Name) (proofSource : String)\n  : Multiset Name := Id.run <| do\n  let appearsInProof (s : String) : Bool := s.isSubstrOf proofSource\n  let mut result := Std.RBMap.empty\n  for (p, c) in premises do\n    let pLast := (Syntax.splitNameLit p.toString.toSubstring).reverse.head!.toString\n    if appearsInProof pLast then\n      result := result.insert p c\n  return result\n\n/-- Like `filterUserPremises` but simply checks that the premise appears\nsomewhere in the file, instead of looking for the proof source. -/\ndef filterUserPremisesFromFile\n  (premises : Multiset Name) (referencePath : FilePath)\n  : IO (Multiset Name) := do\n  let appearsInFile (s : String) : IO Bool := do\n    let args := #[s, referencePath.toString]\n    let output \u2190 IO.Process.output { cmd := \"grep\", args := args }\n    if output.exitCode != 0 then\n      return false\n    if output.stdout.isEmpty then\n      return false\n    return true\n  let mut result := Std.RBMap.empty\n  for (p, c) in premises do\n    if \u2190 appearsInFile p.toString then\n      result := result.insert p c\n  return result\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/ProofSource.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.04958902052601327, "lm_q1q2_score": 0.015241583007166304}}
{"text": "import complexity_class.lemmas\nimport data.multiset.functor\nimport data.finset.functor\n\nnamespace function\n/- Note that Lean fails to infer something like\n(infer_instance : \u2200 x : \u03b1, has_uncurry (list (\u03b2 x) \u2192 list (\u03b2 x) \u2192 list (\u03b2 x)) _ _)\nunless all the underscores are made explicit for some reason.\n(infer_instance : \u2200 x : \u03b1, has_uncurry (list (\u03b2 x) \u2192 list (\u03b2 x) \u2192 list (\u03b2 x)) (list (\u03b2 x) \u00d7 list (\u03b2 x)) (list $ \u03b2 x))\n\nThis is why we make the following instances\n-/\nvariables {\u03b1 : Type*} {\u03b2 \u03b2\u2081 \u03b2\u2082 \u03b3 \u03b4 : \u03b1 \u2192 Type*}\n\nclass has_uncurry_dep_aux {\u03b1 : Type*} (\u03b2 : \u03b1 \u2192 Type*) (\u03b2\u2081 \u03b2\u2082 : out_param (\u03b1 \u2192 Type*)) :=\n(uncurry : \u2200 {x}, (\u03b2 x) \u2192 ((\u03b2\u2081 x) \u2192 (\u03b2\u2082 x)))\n\ninstance has_uncurry_dep_aux_base : has_uncurry_dep_aux (\u03bb x, (\u03b2\u2081 x \u2192 \u03b2\u2082 x)) \u03b2\u2081 \u03b2\u2082 := \u27e8\u03bb x y, y\u27e9\n\ninstance has_uncurry_dep_aux_ind [has_uncurry_dep_aux \u03b3 \u03b2\u2081 \u03b2\u2082] : has_uncurry_dep_aux (\u03bb x, \u03b4 x \u2192 \u03b3 x) (\u03bb x, \u03b4 x \u00d7 \u03b2\u2081 x) \u03b2\u2082 :=\n\u27e8\u03bb x f p, has_uncurry_dep_aux.uncurry _ (f p.1) p.2\u27e9\n\nclass has_uncurry_dep {\u03b1 : Type*} (\u03b2 : \u03b1 \u2192 Type*) {\u03b1' : out_param Type*} (\u03b3 : out_param (\u03b1' \u2192 Type*)) :=\n(uncurry : (\u2200 x, (\u03b2 x)) \u2192 \u2200 x', (\u03b3 x'))\n\nnotation (name := uncurry_dep) `\u21bf\u209a`:max x:max := has_uncurry_dep.uncurry x\n\ninstance has_uncurry_dep_base : has_uncurry_dep (\u03bb x, \u03b2 x) \u03b2 := \u27e8\u03bb f x, f x\u27e9\n\ninstance has_uncurry_dep_base\u2082 [has_uncurry_dep_aux \u03b3 \u03b2\u2081 \u03b2\u2082] :\n  has_uncurry_dep (\u03bb x, \u03b3 x) (\u03bb z : (\u03a3 x, \u03b2\u2081 x), \u03b2\u2082 z.1) :=\n\u27e8\u03bb f x, (has_uncurry_dep_aux.uncurry _ (f x.1)) x.2\u27e9\n\nend function\n\nnamespace complexity_class\nopen_locale complexity_class\nopen tencodable function\n\nsection dep\nvariables (C : complexity_class)\n  {\u03b1 \u03b1' \u03b1\u2081 \u03b1\u2082 : Type} {\u03b2 \u03b2\u2081 \u03b2\u2082 \u03b3 \u03b4 : \u03b1 \u2192 Type} {\u03b3' : \u03b1' \u2192 Type}\n  [tencodable \u03b1] [tencodable \u03b1\u2081] [tencodable \u03b1\u2082] [\u2200 x, tencodable (\u03b2 x)] [\u2200 x, tencodable (\u03b2\u2081 x)]\n  [\u2200 x, tencodable (\u03b2\u2081 x)] [\u2200 x, tencodable (\u03b2\u2082 x)] [\u2200 x, tencodable (\u03b3 x)] [\u2200 x, tencodable (\u03b4 x)]\n\ndef mem1_dep (f : \u2200 x, \u03b2 x) : Prop :=\n\u2203 (f' : tree unit \u2192 tree unit), C.prop f' \u2227 \u2200 x : \u03b1, f' (encode x) = encode (f x)\n\ndef mem_dep [has_uncurry_dep \u03b3' \u03b3] (f : \u2200 x, \u03b3' x) (C : complexity_class) : Prop :=\nC.mem1_dep \u21bf\u209af\n\n@[simp] lemma mem_dep_iff\u2081 (f : \u03b1 \u2192 \u03b1\u2081) :\n  mem_dep f C \u2194 mem f C := iff.rfl\n\n@[simp] lemma mem_dep_iff\u2082 (f : \u03b1 \u2192 \u03b1\u2081 \u2192 \u03b1\u2082) :\n  mem_dep f C \u2194 mem f C :=\nby split; rintro \u27e8f, pf, hf\u27e9; refine \u27e8f, pf, _\u27e9; rintro \u27e8a, b\u27e9; exact hf \u27e8a, b\u27e9\n\nlocalized \"infix ` \u2208\u2090 `:50 := complexity_class.mem_dep\" in complexity_class\n\nlemma mem_iff_comp_encode_dep {f : \u2200 x, \u03b2 x} :\n  f \u2208\u2090 C \u2194 (\u03bb x, encode (f x)) \u2208\u2091 C := iff.rfl\n\nlemma mem_dep_iff_comp_eq_encode {f : \u2200 x, \u03b2 x} (g : \u2200 x, \u03b2 x \u2192 \u03b1\u2081)\n  (hg : \u2200 (x : \u03b1) (y : \u03b2 x), encode (g x y) = encode y) :\n  f \u2208\u2090 C \u2194 (\u03bb x, g x (f x)) \u2208\u2091 C :=\nby { rw [mem_iff_comp_encode, mem_iff_comp_encode_dep], simp only [hg], }\n\nsection functor\n\nclass is_encodable_functor (F : Type \u2192 Type) [functor F] :=\n(inst : \u2200 x, tencodable x \u2192 tencodable (F x))\n(map_encode : \u2200 {\u03b1} [I : tencodable \u03b1] (x : F \u03b1), (@encode _ (inst _ infer_instance) $ @encode _ I <$> x) = @encode _ (inst _ I) x)\n\ninstance : is_encodable_functor list :=\n\u27e8@list.tencodable, \u03bb \u03b1 _ x, by simp [encode]\u27e9\n\nlemma list_map_encode (x : list \u03b1) : encode (x.map encode) = encode x := is_encodable_functor.map_encode x\n\ninstance : is_encodable_functor option :=\n\u27e8@option.tencodable, \u03bb \u03b1 _ x, by cases x; simp [encode]\u27e9\n\nlemma option_map_encode (x : option \u03b1) : encode (x.map encode) = encode x := is_encodable_functor.map_encode x\n\nlemma _root_.list.sorted_map {\u03b1 \u03b2 : Type*} {r : \u03b2 \u2192 \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2) {l : list \u03b1} :\n  (l.map f).sorted r \u2194 l.sorted (\u03bb x y, r (f x) (f y)) := list.pairwise_map f\n\nlemma _root_.list.map_merge_sort {\u03b1 \u03b2 : Type*} (r : \u03b2 \u2192 \u03b2 \u2192 Prop) [decidable_rel r]\n  [is_total \u03b2 r] [is_trans \u03b2 r] [is_antisymm \u03b2 r] (f : \u03b1 \u2192 \u03b2) (l : list \u03b1)  :\n  (l.map f).merge_sort r = (l.merge_sort (\u03bb x y, r (f x) (f y))).map f :=\nbegin\n  refine list.eq_of_perm_of_sorted (trans ((l.map f).perm_merge_sort r) ((l.perm_merge_sort (\u03bb x y, r (f x) (f y))).map f).symm)\n    (list.sorted_merge_sort _ _) ((list.sorted_map f).mpr $ _),\n  refine @list.sorted_merge_sort _ _ _ \u27e8_\u27e9 \u27e8_\u27e9 _,\n  { intros a b, exact is_total.total (f a) (f b), },\n  { intros a b c, exact is_trans.trans (f a) (f b) (f c), }\nend\n\ninstance : is_encodable_functor multiset :=\n\u27e8@multiset.tencodable, \u03bb \u03b1 _ x, quotient.induction_on x $ \u03bb x, begin\n  dsimp [encode_multiset, lift_le],\n  rw [\u2190 @list_map_encode \u03b1, list.map_merge_sort],\nend\u27e9\n\nlemma multiset_map_encode (x : multiset \u03b1) : encode (x.map encode) = encode x := is_encodable_functor.map_encode x\n\nsection\nopen_locale classical\n\nlemma _root_.finset.fmap_def' {\u03b1 \u03b2 : Type*} [decidable_eq \u03b2] (f : \u03b1 \u2192 \u03b2) (x : finset \u03b1) :\n  f <$> x = x.image f := by { dsimp, congr, }\n\nnoncomputable instance : is_encodable_functor finset :=\n\u27e8\u03bb \u03b1 I, @finset.tencodable _ I _, \u03bb \u03b1 _ x, begin\n  resetI,\n  simp only [finset.fmap_def'],\n  rw (show x.image encode = _, from (finset.map_eq_image \u27e8encode, encode_injective\u27e9 x).symm),\n  cases x with v hv,\n  simp only [finset.map, encode_finset],\n  exact multiset_map_encode _,\nend\u27e9\n\nlemma finset_image_encode [decidable_eq \u03b1] (x : finset \u03b1) : encode (x.image encode) = encode x := by convert is_encodable_functor.map_encode x\n\nend\n\nlemma functor_map_dep (F : Type \u2192 Type) [functor F] [is_lawful_functor F] [is_encodable_functor F]\n  {l : \u2200 x, F (\u03b2 x)} {g : \u2200 x, \u03b2 x \u2192 \u03b3 x} (hl : by { haveI : \u2200 x, tencodable (F (\u03b2 x)) := \u03bb x, is_encodable_functor.inst _ infer_instance, exact l \u2208\u2090 C, })\n  (hg : g \u2208\u2090 C) (hm : by { haveI : tencodable (F (tree unit)) := is_encodable_functor.inst _ infer_instance,\n    exact \u2200 {l' : \u03b1 \u2192 F (tree unit)} {g' : \u03b1 \u2192 tree unit \u2192 tree unit}, l' \u2208\u2091 C \u2192 g' \u2208\u2091 C \u2192 (\u03bb z, (g' z) <$> (l' z)) \u2208\u2091 C, }) :\n  by { haveI : \u2200 x, tencodable (F (\u03b3 x)) := \u03bb x, is_encodable_functor.inst _ infer_instance, exact (\u03bb x, (g x) <$> (l x)) \u2208\u2090 C } :=\nbegin\n  letI : \u2200 x, tencodable (F (\u03b2 x)) := \u03bb x, is_encodable_functor.inst _ infer_instance,\n  letI : tencodable (F (tree unit)) := is_encodable_functor.inst _ infer_instance,\n  letI : \u2200 x, tencodable (F (\u03b3 x)) := \u03bb x, is_encodable_functor.inst _ infer_instance,\n  rcases hg with \u27e8g', pg, hg\u27e9,\n  simp only [sigma.forall] at hg,\n  dsimp [encode_sigma, has_uncurry_dep.uncurry, has_uncurry_dep_aux.uncurry] at hg,\n  rw C.mem_dep_iff_comp_eq_encode (\u03bb x (y : F (\u03b3 x)), encode <$> y) (\u03bb x y, is_encodable_functor.map_encode y),\n  rw C.mem_dep_iff_comp_eq_encode (\u03bb x (y : F (\u03b2 x)), encode <$> y) (\u03bb x y, is_encodable_functor.map_encode y) at hl,\n  have pg' : (\u03bb (x : \u03b1) (t : tree unit), g' (tree.node () (encode x) t)) \u2208\u2091 C := by complexity,\n  convert hm hl pg',\n  funext x,\n  simp [functor.map_map, function.comp, hg],\nend\n\nend functor\n\n-- lemma mem_iff_comp_list_map_dep {f : \u2200 x, list (\u03b2 x)} :\n--   f \u2208\u2090 C \u2194 (\u03bb x, (f x).map encode) \u2208\u2091 C :=\n-- C.mem_dep_iff_comp_eq_encode (\u03bb x (y : list (\u03b2 x)), y.map encode) (\u03bb (x : \u03b1) y, list_map_encode y)\n\nend dep\n\n/-- A function which is encoded as a table -/\nstructure table_fun (\u03b1 \u03b2 : Type*) :=\n(to_fun : \u03b1 \u2192 \u03b2)\n\nnamespace table_fun\nvariables {\u03b1 \u03b2 \u03b3 : Type*}\n\nlocalized \"infixr ` [\u2192] `:25 := complexity_class.table_fun\" in complexity_class\n\ninstance : has_coe_to_fun (\u03b1 [\u2192] \u03b2) (\u03bb _, \u03b1 \u2192 \u03b2) := \u27e8table_fun.to_fun\u27e9\n\n@[ext]\nprotected lemma ext : \u2200 (f g : \u03b1 [\u2192] \u03b2), \u21d1f = (by exact \u21d1g) \u2192 f = g\n| \u27e8f\u27e9 \u27e8g\u27e9 rfl := rfl\n\n@[simp] lemma to_fun_eq_coe (f : \u03b1 [\u2192] \u03b2) : f.to_fun = \u21d1f := rfl\n\n@[simps]\ndef equiv_fun : (\u03b1 [\u2192] \u03b2) \u2243 (\u03b1 \u2192 \u03b2) := \u27e8\u03bb f, \u21d1f, \u03bb f, \u27e8f\u27e9, \u03bb f, by ext; refl, \u03bb f, rfl\u27e9\n\n@[simps]\ndef sum (f : \u03b1 [\u2192] \u03b3) (g : \u03b2 [\u2192] \u03b3) : \u03b1 \u2295 \u03b2 [\u2192] \u03b3 := \u27e8sum.elim \u21d1f \u21d1g\u27e9\n\n@[simps]\ndef map (f : \u03b1 [\u2192] \u03b2) (g : \u03b2 \u2192 \u03b3) : \u03b1 [\u2192] \u03b3 := \u27e8\u03bb x, g (f x)\u27e9\n\n@[simps]\ndef comp (f : \u03b1 [\u2192] \u03b2) (g : \u03b3 [\u2192] \u03b1) : \u03b3 [\u2192] \u03b2 := \u27e8\u03bb x, f (g x)\u27e9\n\ndef to_finmap [fintype \u03b1] (f : \u03b1 [\u2192] \u03b2) : @finmap \u03b1 (\u03bb _, \u03b2) := finmap.of_fun f \n\ndef finmap_equiv_fun [fintype \u03b1] [decidable_eq \u03b1] :\n  {x : @finmap \u03b1 (\u03bb _, \u03b2) // \u2200 k : \u03b1, k \u2208 x} \u2243 (\u03b1 \u2192 \u03b2) :=\n{ to_fun := \u03bb f x, @option.get _ ((\u2191f : finmap _).lookup x) (finmap.lookup_is_some.mpr $ f.prop x),\n  inv_fun := \u03bb f, \u27e8finmap.of_fun f, \u03bb k, finmap.mem_iff.mpr \u27e8_, finmap.of_fun_lookup k\u27e9\u27e9,\n  left_inv := \u03bb f, by { ext : 1, apply finmap.ext_lookup, simp, },\n  right_inv := \u03bb f, by { ext, simp, } } \n\nvariables [tencodable \u03b1] [fintype \u03b1] [decidable_eq \u03b1] [tencodable \u03b2] [tencodable \u03b3]\n\ninstance : tencodable (\u03b1 [\u2192] \u03b2) :=\ntencodable.of_equiv _ (equiv_fun.trans finmap_equiv_fun.symm)\n\nlemma encode_table_fun (f : \u03b1 [\u2192] \u03b2) : encode f = encode f.to_finmap := rfl\n\nend table_fun\n\nopen_locale complexity_class\nvariables {C : complexity_class} {\u03b1 : Type} {\u03b2 \u03b3 : \u03b1 \u2192 Type} [tencodable \u03b1]\n  [\u2200 i, tencodable (\u03b2 i)] [\u2200 i, tencodable (\u03b3 i)] [\u2200 i, decidable_eq (\u03b2 i)] [\u2200 i, fintype (\u03b2 i)]\n\nlemma to_finmap_iff {f : \u2200 x, (\u03b2 x) [\u2192] (\u03b3 x)} : \n  f \u2208\u2090 C \u2194 (\u03bb x, (f x).to_finmap) \u2208\u2090 C := iff.rfl\n\n@[complexity] lemma to_finmap {f : \u2200 x, (\u03b2 x) [\u2192] (\u03b3 x)} (hf : f \u2208\u2090 C) : (\u03bb x, (f x).to_finmap) \u2208\u2090 C := hf\n\nend complexity_class\n", "meta": {"author": "prakol16", "repo": "circuits", "sha": "cdf4ce1e019d6817e4abe0d082d8d379539fddca", "save_path": "github-repos/lean/prakol16-circuits", "path": "github-repos/lean/prakol16-circuits/circuits-cdf4ce1e019d6817e4abe0d082d8d379539fddca/src/complexity_class/dependent.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.030675805033796792, "lm_q1q2_score": 0.01521807759131956}}
{"text": "-- This example used to produce\n-- `error: (kernel) declaration has metavariables`\n-- Because we were not registering postponed instance metavariables\ndef f {\u03b1 : Type u} (a : \u03b1) : \u03b1 :=\n  let g a b := a + b\n  g a 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/kernelMVarBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.04742587620689797, "lm_q1q2_score": 0.015215231913389906}}
{"text": "import ReactorModel.Determinism.State\n\nopen Classical ReactorType Indexable\n\nnamespace Execution\nnamespace Instantaneous\nnamespace Step\n\nvariable [Indexable \u03b1] {s\u2081 s\u2082 : State \u03b1}\n\ntheorem rcn_not_mem_progress (e : s\u2081 \u21d3\u1d62 s\u2082) : e.rcn \u2209 s\u2081.progress := \n  sorry -- e.allows.unprocessed\n\ntheorem preserves_tag (e : s\u2081 \u21d3\u1d62 s\u2082) : s\u2081.tag = s\u2082.tag := \n  sorry -- e.exec.preserves_tag\n  \ntheorem mem_progress_iff :\n  (e : s\u2081 \u21d3\u1d62 s\u2082) \u2192 (rcn' \u2208 s\u2082.progress \u2194 rcn' = e.rcn \u2228 rcn' \u2208 s\u2081.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, \u2190rcn] 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\u2081 \u21d3\u1d62 s\u2082) \u2192 (rcn' \u2260 e.rcn) \u2192 rcn' \u2209 s\u2081.progress \u2192 rcn' \u2209 s\u2082.progress := \n  sorry -- \u03bb h hn hm => (mt h.mem_progress.mp) $ not_or.mpr \u27e8hn, hm\u27e9\n\n-- Corollary of `InstStep.mem_progress`.\ntheorem monotonic_progress : (s\u2081 \u21d3\u1d62 s\u2082) \u2192 rcn' \u2208 s\u2081.progress \u2192 rcn' \u2208 s\u2082.progress := \n  sorry -- (\u00b7.mem_progress_iff.mpr $ .inr \u00b7)\n\n-- Corollary of `InstStep.mem_progress`.\ntheorem rcn_mem_progress : (e : s\u2081 \u21d3\u1d62 s\u2082) \u2192 e.rcn \u2208 s\u2082.progress := \n  (\u00b7.mem_progress_iff.mpr $ .inl rfl)\n\ntheorem Skip.equiv : (s\u2081 \u21d3\u209b s\u2082) \u2192 s\u2081.rtr \u2248 s\u2082.rtr\n  | mk .. => .refl\n\ntheorem Skip.progress_eq : (e : s\u2081 \u21d3\u209b s\u2082) \u2192 s\u2082.progress = s\u2081.progress.insert e.rcn\n  | mk .. => rfl\n\ntheorem Skip.progress_mono (e : s\u2081 \u21d3\u209b s\u2082) : s\u2081.progress \u2286 s\u2082.progress := by\n  simp [e.progress_eq]\n  apply Set.subset_insert\n\ntheorem Skip.triggers_iff (e : s\u2081 \u21d3\u209b s\u2082) : (s\u2081.Triggers i) \u2194 (s\u2082.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\u2081.record_preserves_rtr rcn) (s\u2081.record_preserves_tag rcn) |>.choose_spec\n\ntheorem Skip.mem_progress_iff (e : s\u2081 \u21d3\u209b s\u2082) : \n    (rcn' \u2208 s\u2082.progress) \u2194 (rcn' = e.rcn \u2228 rcn' \u2208 s\u2081.progress) := by\n  sorry\n\ntheorem Skip.preserves_allows_indep (e\u2081 : s\u2081 \u21d3\u209b s\u2082) (e\u2082 : s\u2082 \u21d3\u209b s\u2083) (h : e\u2081.rcn \u226e[s\u2081.rtr] e\u2082.rcn) : \n    s\u2081.Allows e\u2082.rcn where\n  mem := sorry\n  unprocessed := Set.not_mem_subset e\u2081.progress_mono $ e\u2082.allows_rcn.unprocessed\n  deps := by\n    intro i hi\n    have h' := equiv_eq_dependencies e\u2081.equiv |>.symm \u25b8 e\u2082.allows_rcn.deps\n    refine e\u2081.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\u2081 : s\u2081 \u21d3\u209b s\u2082) (e\u2082 : s\u2082 \u21d3\u209b s\u2083) (h : e\u2081.rcn \u226e[s\u2081.rtr] e\u2082.rcn) : \n    \u2203 (s\u2082' : _) (f\u2081 : s\u2081 \u21d3\u209b s\u2082') (f\u2082 : s\u2082' \u21d3\u209b s\u2083), (f\u2081.rcn = e\u2082.rcn) \u2227 (f\u2082.rcn = e\u2081.rcn) := by \n  have ha := e\u2081.preserves_allows_indep e\u2082 h\n  have ht := e\u2081.triggers_iff.not.mpr e\u2082.not_triggers\n  have e\u2081' := Skip.mk ha ht\n  simp at e\u2081'\n  exists _, e\u2081'\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\u2081 : s\u2081 \u21d3\u209b s\u2082) (e\u2082 : s\u2082 \u21d3\u2091 s\u2083) (h : e\u2081.rcn \u226e[s\u2081.rtr] e\u2082.rcn) : \n    \u2203 (s\u2082' : _) (f\u2081 : s\u2081 \u21d3\u2091 s\u2082') (f\u2082 : s\u2082' \u21d3\u209b s\u2083), (f\u2081.rcn = e\u2082.rcn) \u2227 (f\u2082.rcn = e\u2081.rcn) := by \n  sorry\n\ntheorem Skip.swap_indep (e\u2081 : s\u2081 \u21d3\u209b s\u2082) (e\u2082 : s\u2082 \u21d3\u1d62 s\u2083) (h : e\u2081.rcn \u226e[s\u2081.rtr] e\u2082.rcn) : \n    \u2203 (s\u2082' : _) (f\u2081 : s\u2081 \u21d3\u1d62 s\u2082') (f\u2082 : s\u2082' \u21d3\u209b s\u2083), (f\u2081.rcn = e\u2082.rcn) \u2227 (f\u2082.rcn = e\u2081.rcn) := by \n  cases e\u2082\n  case skip e\u2082 =>\n    have \u27e8_, e\u2081', e\u2082', _\u27e9 := e\u2081.swap_indep_skip e\u2082 h\n    exists _, skip e\u2081', e\u2082'\n  case exec e\u2082 =>\n    have \u27e8_, e\u2081', e\u2082', _\u27e9 := e\u2081.swap_indep_exec e\u2082 h\n    exists _, exec e\u2081', e\u2082'\n\ntheorem Exec.equiv : (s\u2081 \u21d3\u2091 s\u2082) \u2192 s\u2081.rtr \u2248 s\u2082.rtr\n  | mk .. => by simp [State.record_preserves_rtr, s\u2081.exec_equiv]\n\ntheorem Exec.progress_eq : (e : s\u2081 \u21d3\u2091 s\u2082) \u2192 s\u2082.progress = s\u2081.progress.insert e.rcn\n  | mk .. => rfl\n\ntheorem not_Closed (e : s\u2081 \u21d3\u1d62 s\u2082) : \u00acs\u2081.Closed := by\n  intro c\n  have h := c \u25b8 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\u2081 \u21d3\u1d62 s\u2082) \u2192 s\u2081.rtr \u2248 s\u2082.rtr\n  | skip e | exec e => e.equiv\n\ntheorem deterministic (e\u2081 : s \u21d3\u1d62 s\u2081) (e\u2082 : s \u21d3\u1d62 s\u2082) (h : e\u2081.rcn = e\u2082.rcn) : s\u2081 = s\u2082 := by\n  cases e\u2081 <;> cases e\u2082\n  all_goals \n    case _ e\u2081 e\u2082 => \n      cases e\u2081; cases e\u2082\n      simp [rcn] at h\n      subst h\n      first | rfl | contradiction\n\ntheorem acyclic (e : s\u2081 \u21d3\u1d62 s\u2082) : e.rcn \u226e[s\u2081.rtr] e.rcn :=\n  e.allows_rcn.acyclic\n\ntheorem progress_eq : (e : s\u2081 \u21d3\u1d62 s\u2082) \u2192 s\u2082.progress = s\u2081.progress.insert e.rcn\n  | skip e | exec e => e.progress_eq  \n\n/-\nBy cases on e\u2081 and e\u2082:\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\u2081 : s\u2081 \u21d3\u1d62 s\u2082) (e\u2082 : s\u2082 \u21d3\u1d62 s\u2083) (h : e\u2081.rcn \u226e[s\u2081.rtr] e\u2082.rcn) :\n    \u2203 (s\u2082' : _) (e\u2081' : s\u2081 \u21d3\u1d62 s\u2082') (e\u2082' : s\u2082' \u21d3\u1d62 s\u2083), e\u2081'.rcn = e\u2082.rcn \u2227 e\u2082'.rcn = e\u2081.rcn := by\n  cases e\u2081 \n  case skip e\u2081 => \n    have \u27e8_, e\u2081', e\u2082', _\u27e9 := e\u2081.swap_indep e\u2082 h\n    exists _, e\u2081', skip e\u2082'\n  case exec e\u2081 =>\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 Alloy.C\nopen scoped Alloy.C\n\n/-!\n# `S.lean`\n\nAn adaption of Lean 4's ['foreign'][1] example for Alloy.\n\n[1]: https://github.com/leanprover/lean4/tree/b278a20ac22adcbfde11db386f2dc874d4a215ad/tests/compiler/foreign\n-/\n\nalloy c include <stdint.h> <stdlib.h> <string.h> <lean/lean.h>\n\n--------------------------------------------------------------------------------\n/-! ## C Definition of S                                                      -/\n--------------------------------------------------------------------------------\n\nalloy c section\n\ntypedef struct {\n  uint32_t      m_x;\n  uint32_t      m_y;\n  lean_object * m_s;\n} S;\n\nstatic void S_finalize(void* ptr) {\n  lean_dec(((S*)ptr)->m_s);\n  free(ptr);\n}\n\nstatic void S_foreach(void* ptr, b_lean_obj_arg f) {\n  lean_apply_1(f, ((S*)ptr)->m_s);\n}\n\nstatic lean_external_class * g_S_class = NULL;\n\nstatic inline lean_object * S_to_lean(S* s) {\n  if (g_S_class == NULL) {\n    g_S_class = lean_register_external_class(S_finalize, S_foreach);\n  }\n  return lean_alloc_external(g_S_class, s);\n}\n\nstatic inline S const * to_S(b_lean_obj_arg s) {\n  return (S*)(lean_get_external_data(s));\n}\n\nstatic S g_s = {0, 0, NULL};\n\nend\n\n--------------------------------------------------------------------------------\n/-! ## Lean Interface                                                         -/\n--------------------------------------------------------------------------------\n\nopaque S.nonemptyType : NonemptyType\ndef S : Type := S.nonemptyType.type\ninstance : Nonempty S := S.nonemptyType.property\n\nalloy c extern \"lean_mk_S\"\ndef mkS (x y : UInt32) (string : String) : S := {\n  S* s = malloc(sizeof(S));\n  s->m_x = x;\n  s->m_y = y;\n  s->m_s = string;\n  return S_to_lean(s);\n}\n\nalloy c extern \"lean_S_add_x_y\"\ndef S.addXY (s : @& S) : UInt32 := {\n  return to_S(s)->m_x + to_S(s)->m_y;\n}\n\nalloy c extern \"lean_S_string\"\ndef S.string (s : @& S) : String := {\n  lean_inc(to_S(s)->m_s);\n  return to_S(s)->m_s;\n}\n\nalloy c extern \"lean_S_global_append\"\ndef appendToGlobalS (string : String) : BaseIO PUnit := {\n  if (g_s.m_s == NULL) {\n    g_s.m_s = string;\n  } else {\n    g_s.m_s = lean_string_append(g_s.m_s, string);\n  }\n  return lean_io_result_mk_ok(lean_box(0));\n}\n\nalloy c extern \"lean_S_global_string\"\ndef getGlobalString : BaseIO String := {\n  if (g_s.m_s == NULL) {\n    g_s.m_s = lean_mk_string(\"\");\n  }\n  lean_inc(g_s.m_s);\n  return lean_io_result_mk_ok(g_s.m_s);\n}\n\nalloy c extern \"lean_S_update_global\"\ndef updateGlobalS (s : @& S) : BaseIO Unit := {\n  if (g_s.m_s != NULL) {\n    lean_dec(g_s.m_s);\n  }\n  lean_inc(to_S(s)->m_s);\n  g_s.m_x = to_S(s)->m_x;\n  g_s.m_y = to_S(s)->m_y;\n  g_s.m_s = to_S(s)->m_s;\n  return lean_io_result_mk_ok(lean_box(0));\n}\n", "meta": {"author": "tydeu", "repo": "lean4-alloy", "sha": "334407dc09c10c84549242dc73f9d364886267d1", "save_path": "github-repos/lean/tydeu-lean4-alloy", "path": "github-repos/lean/tydeu-lean4-alloy/lean4-alloy-334407dc09c10c84549242dc73f9d364886267d1/examples/S/S.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.03732688868276006, "lm_q1q2_score": 0.015204488480284608}}
{"text": "-- Copyright (c) 2018 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Keeley Hoek, Scott Morrison\n\nimport .init\nimport .discovery\n\nimport tidy.lib.list\nimport tidy.lib.expr\n\nopen tactic\n\nvariables {\u03b1 \u03b2 \u03b3 \u03b4 : Type}\n\nnamespace tidy.rewrite_search\n\nmeta def try_search (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4) (prog : discovery.progress) (rs : list (expr \u00d7 bool)) (eqn : sided_pair expr) : tactic (option string) := do\n  i \u2190 try_mk_search_instance cfg prog rs eqn,\n  match i with\n  | none := return none\n  | some i := do\n    (i, result) \u2190 i.search_until_solved,\n    match result with\n    | search_result.failure reason := fail reason\n    | search_result.success proof steps := do\n      exact proof,\n      some <$> i.explain proof steps\n    end\n  end\n\nmeta def rewrite_search_pair (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4) (prog : discovery.progress) (rs : list (expr \u00d7 bool)) (eqn : sided_pair expr) := do\n  result \u2190 try_search cfg prog rs eqn,\n  match result with\n  | some str := return str\n  | none := do\n    trace \"\\nError initialising rewrite_search instance, falling back to emergency config!\",\n    result \u2190 try_search (mk_fallback_config cfg) prog rs eqn,\n    match result with\n    | some str := return str\n    | none := fail \"Could not initialise emergency rewrite_search instance!\"\n    end\n  end\n\n-- TODO If try_search fails due to a failure to init any of the tracer, metric, or strategy we try again\n-- using the \"fallback\" default versions of all three of these. Instead we could be more thoughtful,\n-- and try again only replacing the failing one of these with its respective fallback module version.\n\nmeta def collect_rw_lemmas (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr \u00d7 bool)) : tactic (discovery.progress \u00d7 list (expr \u00d7 bool)) := do\n  let per := if cfg.help_me then discovery.persistence.try_everything else per,\n  (prog, rws) \u2190 discovery.collect use_suggest_annotations per cfg.suggest extra_names,\n  hyp_rws \u2190 discovery.rewrite_list_from_hyps,\n  let rws := rws ++ extra_rws ++ hyp_rws,\n\n  locs \u2190 local_context,\n  rws \u2190 rws.mmap $ discovery.inflate_rw locs,\n  return (prog, rws.join)\n\nmeta def rewrite_search_target (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr \u00d7 bool)) : tactic string := do\n  t \u2190 target,\n  if t.has_meta_var then\n    fail \"rewrite_search is not suitable for goals containing metavariables\"\n  else skip,\n\n  (prog, rws) \u2190 collect_rw_lemmas cfg use_suggest_annotations per extra_names extra_rws,\n\n  if cfg.trace_rules then\n    do rs_strings \u2190 pp_rules rws,\n      trace (\"rewrite_search using:\\n---\\n\" ++ (string.intercalate \"\\n\" rs_strings) ++ \"\\n---\")\n  else skip,\n\n  match t with\n  | `(%%lhs = %%rhs) := rewrite_search_pair cfg prog rws \u27e8lhs, rhs\u27e9\n  | `(%%lhs \u2194 %%rhs) := rewrite_search_pair cfg prog rws \u27e8lhs, rhs\u27e9\n  | _                := fail \"target is not an equation or iff\"\n  end\n\nprivate meta def add_simps : simp_lemmas \u2192 list name \u2192 tactic simp_lemmas\n| s []      := return s\n| s (n::ns) := do s' \u2190 s.add_simp n, add_simps s' ns\n\nprivate meta def add_expr (s : simp_lemmas) (u : list name) (e : expr) : tactic (simp_lemmas \u00d7 list name) :=\ndo\n  let e := e.erase_annotations,\n  match e with\n  | expr.const n _           :=\n    (do b \u2190 is_valid_simp_lemma_cnst n, guard b, s \u2190 s.add_simp n, return (s, u))\n    <|>\n    (do eqns \u2190 get_eqn_lemmas_for tt n, guard (eqns.length > 0), s \u2190 add_simps s eqns, return (s, u))\n    <|>\n    (do env \u2190 get_env, guard (env.is_projection n).is_some, return (s, n::u))\n    <|>\n    fail n\n  | _ :=\n    (do b \u2190 is_valid_simp_lemma e, guard b, s \u2190 s.add e, return (s, u))\n    <|>\n    fail e\n  end\n\nmeta def simp_search_target (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr \u00d7 bool)) : tactic unit := do\n  t \u2190 target,\n\n  (prog, rws) \u2190 collect_rw_lemmas cfg use_suggest_annotations per extra_names extra_rws,\n\n  if cfg.trace_rules then\n    do rs_strings \u2190 pp_rules rws,\n      trace (\"simp_search using:\\n---\\n\" ++ (string.intercalate \"\\n\" rs_strings) ++ \"\\n---\")\n  else skip,\n\n  (s, to_unfold) \u2190 mk_simp_set ff [] [] >>= \u03bb sset, rws.mfoldl (\u03bb c e, add_expr c.1 c.2 e.1 <|> return c) sset,\n  (n, pf) \u2190 simplify s to_unfold t {contextual := tt} `eq failed,\n  replace_target n pf >> try tactic.triv >> try (tactic.reflexivity reducible)\n\nend tidy.rewrite_search\n\nnamespace tactic.interactive\n\nopen interactive\nopen tidy.rewrite_search tidy.rewrite_search.discovery.persistence\n\nmeta def rewrite_search (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4 . pick_default_config) : tactic string :=\n  rewrite_search_target cfg tt try_everything [] []\n\nmeta def rewrite_search_with (rs : parse rw_rules) (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4 . pick_default_config) : tactic string := do\n  extra_rws \u2190 discovery.rewrite_list_from_rw_rules rs.rules,\n  rewrite_search_target cfg tt try_everything [] extra_rws\n\nmeta def rewrite_search_using (as : list name) (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4 . pick_default_config) : tactic string := do\n  extra_names \u2190 discovery.load_attr_list as,\n  rewrite_search_target cfg ff try_bundles extra_names []\n\n-- @Scott should we still do this?\n--  exprs \u2190 close_under_apps exprs, -- TODO don't do this for everything, it's too expensive: only for specially marked lemmas\n\nmeta def simp_search (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4 . pick_default_config) : tactic unit := do\n  simp_search_target cfg tt try_everything [] []\n\nmeta def simp_search_with (rs : parse rw_rules) (cfg : rewrite_search_config \u03b1 \u03b2 \u03b3 \u03b4 . pick_default_config) : tactic unit := do\n  extra_rws \u2190 discovery.rewrite_list_from_rw_rules rs.rules,\n  simp_search_target cfg tt try_everything [] extra_rws\n\nend tactic.interactive\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/tidy/rewrite_search/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.04272219846061002, "lm_q1q2_score": 0.015199485607991711}}
{"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\nimport tidy.tidy\n\nopen tactic\nset_option trace.tidy true\n\n@[reducible] def {u} auto_cast {\u03b1 \u03b2 : Sort u} {h : \u03b1 = \u03b2} (a : \u03b1) := cast h a\n@[simp] lemma {u} auto_cast_identity {\u03b1 : Sort u} (p : \u03b1 = \u03b1) (a : \u03b1) : @auto_cast \u03b1 \u03b1 p a = a :=\nbegin unfold auto_cast, unfold cast, end\nnotation `\u27ec` p `\u27ed` := @auto_cast _ _ (by obviously) p\n", "meta": {"author": "semorrison", "repo": "lean-tidy", "sha": "6c1d46de6cff05e1c2c4c9692af812bca3e13b6c", "save_path": "github-repos/lean/semorrison-lean-tidy", "path": "github-repos/lean/semorrison-lean-tidy/lean-tidy-6c1d46de6cff05e1c2c4c9692af812bca3e13b6c/src/tidy/auto_cast.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.28457600421652673, "lm_q2_score": 0.05340333356619821, "lm_q1q2_score": 0.015197307278111005}}
{"text": "import polytime.lemmas\nimport complexity_class.dependent\n\nnamespace polytime\n\nopen_locale complexity_class\nopen tencodable function polysize\n\nvariables {\u03b1 \u03b2 \u03b3 \u03b4 \u03b5 \u03b7 : Type} [tencodable \u03b1] [tencodable \u03b2] [tencodable \u03b3]\n [tencodable \u03b4] [tencodable \u03b5] [tencodable \u03b7]\n\n@[complexity] lemma list_len : (@list.length \u03b1) \u2208\u2091 PTIME :=\nbegin\n  complexity using \u03bb x, (encode x).stack_rec (\u03bb _ : unit, 0) (\u03bb _ _ _, ()) (\u03bb _ _ _, ())\n    (\u03bb _ ih _ _ _, ih + 1) (),\n  induction x with hd tl ih, { refl, },\n  simpa [encode_cons],\nend\n\n@[simp] def scanl_step {\u03b1 \u03b2 : Type*} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) : list \u03b1 \u00d7 list \u03b2 \u2192 list \u03b1 \u00d7 list \u03b2\n| ((x :: xs), (y :: ys)) := (xs, f y x :: y :: ys)\n| x := x\n\n@[complexity] theorem scanl_step_polytime {f : \u03b3 \u2192 \u03b2 \u2192 \u03b1 \u2192 \u03b2} {st : \u03b3 \u2192 list \u03b1 \u00d7 list \u03b2} (hf : f \u2208\u2091 PTIME) (hst : st \u2208\u2091 PTIME) :\n  (\u03bb x, scanl_step (f x) (st x)) \u2208\u2091 PTIME :=\nby { delta scanl_step, clean_target, complexity, }\n\ntheorem scanl_step_iterate' {\u03b1 : Type*} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (l : list \u03b1) (x : \u03b2) (n : \u2115) :\n  (scanl_step f)^[n] (l, [x]) = (l.drop n, ((l.scanl f x).take (n + 1)).reverse) :=\nbegin\n  suffices : \u2200 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 {\u03b1 : Type*} (f : \u03b2 \u2192 \u03b1 \u2192 \u03b2) (l : list \u03b1) (x : \u03b2) :\n  (scanl_step f)^[l.length] (l, [x]) = ([], (l.scanl f x).reverse) :=\nby { rw [scanl_step_iterate', \u2190 @list.length_scanl _ _ f x l], simp, }\n\nlemma list_scanl_rev' [polysize \u03b1] [polysize \u03b2] [polysize \u03b3] {lst : \u03b3 \u2192 list \u03b1} {acc : \u03b3 \u2192 \u03b2} {f : \u03b3 \u2192 \u03b2 \u2192 \u03b1 \u2192 \u03b2}\n  (hlst : lst \u2208\u2091 PTIME) (hacc : acc \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME)\n  (hf' : polysize_fun (\u03bb (ls : list \u03b1) (x), ls.foldl (f x) (acc x))) :\n  polytime.mem (\u03bb x : \u03b3, ((lst x).scanl (f x) (acc x)).reverse) :=\nbegin\n  convert_to polytime.mem (\u03bb 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 \u27e8n, hn, rfl\u27e9,\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 \u03b1] [polysize \u03b2] [polysize \u03b3] {lst : \u03b3 \u2192 list \u03b1} {acc : \u03b3 \u2192 \u03b2} {f : \u03b3 \u2192 \u03b2 \u2192 \u03b1 \u2192 \u03b2}\n  (hlst : lst \u2208\u2091 PTIME) (hacc : acc \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME)\n  (hf' : polysize_safe (\u03bb (usf : \u03b3 \u00d7 \u03b1) (sf : \u03b2), f usf.1 sf usf.2)) :\n  polytime.mem (\u03bb x : \u03b3, ((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\u2083_1, complexity, }))\n\nlemma list_foldl' [polysize \u03b1] [polysize \u03b2] [polysize \u03b3] {lst : \u03b3 \u2192 list \u03b1} {acc : \u03b3 \u2192 \u03b2} {f : \u03b3 \u2192 \u03b2 \u2192 \u03b1 \u2192 \u03b2}\n  (hlst : lst \u2208\u2091 PTIME) (hacc : acc \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME)\n  (hf' : polysize_fun (\u03bb (ls : list \u03b1) (x), ls.foldl (f x) (acc x))) :\n  polytime.mem (\u03bb x : \u03b3, (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 \u03b1] [polysize \u03b2] [polysize \u03b3] {lst : \u03b3 \u2192 list \u03b1} {acc : \u03b3 \u2192 \u03b2} {f : \u03b3 \u2192 \u03b2 \u2192 \u03b1 \u2192 \u03b2}\n  (hlst : lst \u2208\u2091 PTIME) (hacc : acc \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME)\n  (hf' : polysize_safe (\u03bb (usf : \u03b3 \u00d7 \u03b1) (sf : \u03b2), f usf.1 sf usf.2)) :\n  polytime.mem (\u03bb x : \u03b3, (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 \u03b1) \u2208\u2091 PTIME :=\nbegin\n  complexity using (\u03bb l : list \u03b1, l.foldl (\u03bb (acc : list \u03b1) (hd : \u03b1), hd :: acc) []),\n  rw [\u2190 list.foldr_reverse, list.foldr_eta],\nend\n\n@[complexity] lemma list_scanl [polysize \u03b1] [polysize \u03b2] [polysize \u03b3] {lst : \u03b3 \u2192 list \u03b1} {acc : \u03b3 \u2192 \u03b2} {f : \u03b3 \u2192 \u03b2 \u2192 \u03b1 \u2192 \u03b2}\n  (hlst : lst \u2208\u2091 PTIME) (hacc : acc \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME)\n  (hf' : polysize_safe (\u03bb (usf : \u03b3 \u00d7 \u03b1) (sf : \u03b2), f usf.1 sf usf.2)) :\n  polytime.mem (\u03bb x : \u03b3, ((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 \u03b1] [polysize \u03b2] [polysize \u03b3] {lst : \u03b3 \u2192 list \u03b1} {acc : \u03b3 \u2192 \u03b2} {f : \u03b3 \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b2}\n  (hlst : lst \u2208\u2091 PTIME) (hacc : acc \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME)\n  (hf' : polysize_safe (\u03bb (usf : \u03b3 \u00d7 \u03b1) (sf : \u03b2), f usf.1 usf.2 sf)) :\n  polytime.mem (\u03bb x : \u03b3, (lst x).foldr (f x) (acc x)) :=\nby { simp_rw \u2190 list.foldl_reverse, complexity, }\n\n@[complexity] theorem list_map {lst : \u03b3 \u2192 list \u03b1} {f : \u03b3 \u2192 \u03b1 \u2192 \u03b2} (hlst : lst \u2208\u2091 PTIME) (hf : f \u2208\u2091 PTIME) :\n (\u03bb x, (lst x).map (f x)) \u2208\u2091 PTIME :=\nby { complexity using (\u03bb x, (lst x).foldr (\u03bb hd acc, (f x hd) :: acc) []), induction lst x; simp [*], }\n\n\n@[complexity] theorem list_all_some : (@list.all_some \u03b1) \u2208\u2091 PTIME :=\nbegin\n  complexity using \u03bb l, l.foldr (\u03bb hd' acc', hd'.bind (\u03bb hd, acc'.map (\u03bb acc, hd :: acc))) (some []),\n  induction l with hd, { simp, }, cases hd; simp [*],\nend\n\ninstance {\u03b1 : Type*} [polycodable \u03b1] : polycodable (list \u03b1) :=\n{ poly := by { dunfold decode, complexity, } }\n\n@[complexity] theorem list_tails : (@list.tails \u03b1) \u2208\u2091 PTIME :=\nby { complexity using \u03bb ls, ls.scanl (\u03bb l _, l.tail) ls, induction ls; simp [*], }\n\n@[complexity] theorem list_init : (@list.init \u03b1) \u2208\u2091 PTIME :=\nby { complexity using \u03bb ls, ls.reverse.tail.reverse, induction ls using list.reverse_rec_on; simp [list.init], }\n\ntheorem stack_rec_eq [inhabited \u03b2] [inhabited \u03b3] (ls : list \u03b3) (base : \u03b1 \u2192 \u03b2) (pre : \u03b3 \u2192 list \u03b3 \u2192 \u03b1 \u2192 \u03b1)\n  (post : \u03b2 \u2192 \u03b3 \u2192 list \u03b3 \u2192 \u03b1 \u2192 \u03b2) (arg : \u03b1) : ls.stack_rec base pre post arg =\n  (ls.tails.init.scanl (\u03bb (acc : list \u03b3 \u00d7 \u03b1) (x : list \u03b3), (x.tail, pre x.head x.tail acc.2)) (ls, arg))\n    .foldr (\u03bb 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 \u03b1] [polysize \u03b2] [polysize \u03b3] [polysize \u03b4] {ls : \u03b4 \u2192 list \u03b3} {base : \u03b4 \u2192 \u03b1 \u2192 \u03b2} {pre : \u03b4 \u2192 \u03b3 \u2192 list \u03b3 \u2192 \u03b1 \u2192 \u03b1}\n  {post : \u03b4 \u2192 \u03b2 \u2192 \u03b3 \u2192 list \u03b3 \u2192 \u03b1 \u2192 \u03b2} {arg : \u03b4 \u2192 \u03b1} (hls : ls \u2208\u2091 PTIME) (hb : base \u2208\u2091 PTIME)\n  (hpre : pre \u2208\u2091 PTIME) (hpost : post \u2208\u2091 PTIME) (harg : arg \u2208\u2091 PTIME)\n  (hpre' : polysize_safe (\u03bb (usf : \u03b4 \u00d7 \u03b3 \u00d7 list \u03b3) (sf : \u03b1), pre usf.1 usf.2.1 usf.2.2 sf))\n  (hpost' : polysize_safe (\u03bb (usf : \u03b4 \u00d7 \u03b3 \u00d7 list \u03b3 \u00d7 \u03b1) (sf : \u03b2), post usf.1 sf usf.2.1 usf.2.2.1 usf.2.2.2)) :\n  (\u03bb x, (ls x).stack_rec (base x) (pre x) (post x) (arg x)) \u2208\u2091 PTIME :=\nbegin\n  casesI is_empty_or_nonempty \u03b4, { exact complexity_class.of_from_fintype' _, },\n  casesI is_empty_or_nonempty \u03b3, { complexity using (\u03bb x, base x (arg x)), cases ls x with hd, { refl, }, exact is_empty.elim' infer_instance hd, },\n  inhabit \u03b4, inhabit \u03b3, haveI : inhabited \u03b1 := \u27e8arg default\u27e9, haveI : inhabited \u03b2 := \u27e8base default default\u27e9,\n  simp_rw stack_rec_eq,\n  complexity, { apply polysize_safe.comp\u2084_3, complexity, },\n  { apply polysize_safe.comp\u2085_1, complexity, },\nend\n\n@[complexity] lemma repeat : (@list.repeat \u03b1) \u2208\u2091 PTIME :=\nby { complexity using \u03bb x n, (list.cons x)^[n] [], induction n; simp [iterate_succ', *], }\n\n@[complexity] lemma nat_stack_rec {n : \u03b3 \u2192 \u2115} {base : \u03b3 \u2192 \u03b1 \u2192 \u03b2} {pre : \u03b3 \u2192 \u2115 \u2192 \u03b1 \u2192 \u03b1} {post : \u03b3 \u2192 \u03b2 \u2192 \u2115 \u2192 \u03b1 \u2192 \u03b2}\n  {arg : \u03b3 \u2192 \u03b1}  (hn : n \u2208\u2091 PTIME) (hb : base \u2208\u2091 PTIME) (hpr : pre \u2208\u2091 PTIME) (hpo : post \u2208\u2091 PTIME)\n  (harg : arg \u2208\u2091 PTIME) (hpr : polysize_safe (\u03bb (usf : \u03b3 \u00d7 \u2115) (sf : \u03b1), pre usf.1 usf.2 sf))\n  (hpo' : polysize_safe (\u03bb (usf : \u03b3 \u00d7 \u2115 \u00d7 \u03b1) (sf : \u03b2), post usf.1 sf usf.2.1 usf.2.2)) : (\u03bb x, (n x).stack_rec (base x) (pre x) (post x) (arg x)) \u2208\u2091 PTIME :=\nbegin\n  complexity using \u03bb x, (list.repeat () $ n x).stack_rec (base x) (\u03bb _ tl y, pre x tl.length y)\n    (\u03bb ih _ tl y, post x ih tl.length y) (arg x),\n  { apply polysize_safe.comp\u2083_2, complexity, },\n  { apply polysize_safe.comp\u2084_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 \u2115 _ _) \u2208\u2091 PTIME :=\nby { delta list.sum, complexity, }\n\n@[complexity] lemma list_ordered_insert {r : \u03b3 \u2192 \u03b1 \u2192 \u03b1 \u2192 Prop} [\u2200 x, decidable_rel (r x)] {a : \u03b3 \u2192 \u03b1} {ls : \u03b3 \u2192 list \u03b1} (hr : r \u2208\u209a PTIME)\n  (he : a \u2208\u2091 PTIME) (hls : ls \u2208\u2091 PTIME) : (\u03bb x, (ls x).ordered_insert (r x) (a x)) \u2208\u2091 PTIME :=\nbegin\n  complexity using \u03bb x, (ls x).stack_rec (\u03bb _ : unit, [a x]) (\u03bb _ _ _, ())\n    (\u03bb 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 : \u03b3 \u2192 \u03b1 \u2192 \u03b1 \u2192 Prop} [\u2200 x, decidable_rel (r x)] {ls : \u03b3 \u2192 list \u03b1} (hr : r \u2208\u209a PTIME)\n  (hls : ls \u2208\u2091 PTIME) : (\u03bb x, (ls x).insertion_sort (r x)) \u2208\u2091 PTIME :=\nby { complexity using \u03bb x, (ls x).foldr (\u03bb b ih, list.ordered_insert (r x) b ih) [], induction ls x; simp [*], }\n\n@[complexity] lemma list_append : ((++) : list \u03b1 \u2192 list \u03b1 \u2192 list \u03b1) \u2208\u2091 PTIME :=\nby { complexity using \u03bb l\u2081 l\u2082, l\u2081.foldr (\u03bb hd acc, hd :: acc) l\u2082, induction l\u2081; simp [*], }\n\n@[complexity] lemma list_drop : @list.drop \u03b1 \u2208\u2091 PTIME :=\nby { complexity using \u03bb n l, list.tail^[n] l, simp, }\n\n@[complexity] lemma list_any {l : \u03b1 \u2192 list \u03b2} {p : \u03b1 \u2192 \u03b2 \u2192 bool} (hl : l \u2208\u2091 PTIME) (hp : p \u2208\u2091 PTIME) :\n  (\u03bb x, (l x).any (p x)) \u2208\u2091 PTIME :=\nby { delta list.any, complexity, use 0, simp, }\n\n@[complexity] lemma list_all {l : \u03b1 \u2192 list \u03b2} {p : \u03b1 \u2192 \u03b2 \u2192 bool} (hl : l \u2208\u2091 PTIME) (hp : p \u2208\u2091 PTIME) :\n  (\u03bb x, (l x).all (p x)) \u2208\u2091 PTIME :=\nby { delta list.all, complexity, use 0, simp, }\n\n@[complexity] lemma list_bex {l : \u03b1 \u2192 list \u03b2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} [\u2200 x y, decidable (p x y)] (hl : l \u2208\u2091 PTIME) (hp : p \u2208\u209a PTIME) :\n  (\u03bb x, \u2203 e \u2208 l x, p x e) \u2208\u209a PTIME :=\nby { simp_rw [\u2190 list.any_iff_exists_prop], complexity, }\n\n@[complexity] lemma list_ball {l : \u03b1 \u2192 list \u03b2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} [\u2200 x y, decidable (p x y)] (hl : l \u2208\u2091 PTIME) (hp : p \u2208\u209a PTIME) :\n  (\u03bb x, \u2200 e \u2208 l x, p x e) \u2208\u209a PTIME :=\nby { simp_rw \u2190 list.all_iff_forall_prop, complexity, }\n\n@[complexity] lemma list_mem : ((\u2208) : \u03b1 \u2192 list \u03b1 \u2192 Prop) \u2208\u209a PTIME :=\nby { haveI : decidable_eq \u03b1 := decidable_eq_of_encodable _, complexity using \u03bb x l, \u2203 z \u2208 l, z = x, simp, }\n\n@[complexity] lemma pairwise {l : \u03b1 \u2192 list \u03b2} {r : \u03b1 \u2192 \u03b2 \u2192 \u03b2 \u2192 Prop} (hl : l \u2208\u2091 PTIME)\n  (hr : r \u2208\u209a PTIME) : (\u03bb x, (l x).pairwise (r x)) \u2208\u209a PTIME :=\nbegin\n  classical, rw \u2190 complexity_class.mem_iff_mem_pred,\n  complexity using \u03bb x, (l x).stack_rec (\u03bb _ : unit, tt) (\u03bb _ _ _, ())\n    (\u03bb ih hd tl _, (\u2200 a' \u2208 tl, r x hd a') && ih) (), { use 0, simp, },\n  induction l x; simp [*],\nend\n\n@[complexity] lemma list_nodup : (@list.nodup \u03b1) \u2208\u209a PTIME :=\nby { dunfold list.nodup, complexity, }\n\n@[complexity] lemma list_nth {\u03b1 : Type} [tencodable \u03b1] : @list.nth \u03b1 \u2208\u2091 PTIME :=\nby { complexity using \u03bb l n, (l.drop n).head', rw [\u2190 list.nth_zero, list.nth_drop], refl, }\n\nsection dep\nopen_locale tree\nvariables {\u03c3 \u03c4 : \u03b1 \u2192 Type} [\u2200 i, tencodable (\u03c3 i)] [\u2200 i, tencodable (\u03c4 i)]\n\nlemma list_map_dep {f : \u2200 x, list (\u03c3 x)} {g : \u2200 x, \u03c3 x \u2192 \u03c4 x} (hf : f \u2208\u2090 PTIME) (hg : g \u2208\u2090 PTIME) :\n  (\u03bb x, @list.map _ (\u03c4 x) (g x) (f x)) \u2208\u2090 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) (\u03c4: typ) (e: exp):\n  subst ex x fv_ex (exp.fn y \u03c4 e) =\n  exp.fn y \u03c4 (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 {\u03c4: typ} (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n  subst ex x fv_ex (exp.either_left \u03c4 e) = exp.either_left \u03c4 (subst ex x fv_ex e)\n  := by simp [subst]\n\ntheorem either_right_subst {\u03c4: typ} (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n  subst ex x fv_ex (exp.either_right \u03c4 e) = exp.either_right \u03c4 (subst ex x fv_ex e)\n  := by simp [subst]\n\ntheorem case_never_subst {\u03c4: typ} (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n  subst ex x fv_ex (exp.case_never \u03c4 e) = exp.case_never \u03c4 (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 {\u0393: env} {x x': var} {\u03c41 \u03c42 \u03c4: typ} {e: exp}:\n  has_typ (env.insert_exp \u0393 x' \u03c41) e \u03c42 ->\n  (x \u2209 fv e -> has_typ (env.insert_exp (env.insert_exp \u0393 x' \u03c41) x \u03c4) e \u03c42) ->\n  x \u2209 list.filter (ne x') (fv e) ->\n  has_typ (env.insert_exp (env.insert_exp \u0393 x \u03c4) x' \u03c41) e \u03c42 :=\nbegin\n  intros et ih fv_e,\n  by_cases x = x',\n  let a := useless_insert_twice \u0393.exps x \u03c41 \u03c4,\n  rw symm h at et \u22a2,\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 \u0393.exps x x' \u03c4 \u03c41 h at b,\n  exact b,\nend\n\ntheorem weakening {\u0393: env} {e: exp} {\u03c4: typ} (x: var) (\u03c4x: typ):\n  x \u2209 fv e ->\n  has_typ \u0393 e \u03c4 ->\n  has_typ (env.insert_exp \u0393 x \u03c4x) e \u03c4 :=\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  {\u0393 \u0393': env} {x x': var} {\u03c41 \u03c42 \u03c4x: typ}\n  {ex e: exp} (fv_ex: fv ex = []):\n  \u0393' = env.insert_exp \u0393 x \u03c4x ->\n  has_typ (env.insert_exp \u0393' x' \u03c41) e \u03c42 ->\n  has_typ \u0393 ex \u03c4x ->\n  (\u2200 {\u0393 : env},\n    env.insert_exp \u0393' x' \u03c41 = env.insert_exp \u0393 x \u03c4x \u2192\n    has_typ \u0393 ex \u03c4x \u2192 has_typ \u0393 (subst ex x fv_ex e) \u03c42) ->\n  has_typ (env.insert_exp \u0393 x' \u03c41) (ite (x = x') e (subst ex x fv_ex e)) \u03c42 :=\nbegin\n  intros \u0393'_is et ext ih,\n  by_cases x = x',\n  simp [h],\n  rw \u0393'_is at et,\n  rw h at et,\n  simp [env.insert_exp] at et,\n  rw useless_insert_twice \u0393.exps x' \u03c41 \u03c4x at et,\n  exact et,\n  simp [h],\n  rw \u0393'_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' \u03c41 notin_fv_ex ext,\n  simp [env.insert_exp] at ih,\n  let a := insert_comm \u0393.exps x' x \u03c41 \u03c4x (fun a, h (symm a)),\n  exact @ih (env.insert_exp \u0393 x' \u03c41) a ext',\nend\n\ntheorem subst_preservation\n  {\u0393 \u0393': env}\n  {e ex: exp}\n  {x: var}\n  {\u03c4 \u03c4x: typ}\n  (\u0393'_is: \u0393' = env.insert_exp \u0393 x \u03c4x)\n  (fv_ex: fv ex = [])\n  (et: has_typ \u0393' e \u03c4)\n  (ext: has_typ \u0393 ex \u03c4x)\n  : has_typ \u0393 (subst ex x fv_ex e) \u03c4 :=\nbegin\n  induction et generalizing \u0393,\n  exact has_typ.int,\n  exact has_typ.true,\n  exact has_typ.false,\n  let a := et_ih_a \u0393'_is ext,\n  let b := et_ih_a_1 \u0393'_is ext,\n  let c := et_ih_a_2 \u0393'_is ext,\n  exact has_typ.if_ a b c,\n  rw \u0393'_is at et_a,\n  by_cases x = et_x,\n  rw h at et_a \u22a2,\n  rw lookup_uniq (lookup_insert \u0393.exps et_x \u03c4x) 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 \u0393'_is et_a ext @et_ih,\n  exact has_typ.fn a,\n  let a := et_ih_a \u0393'_is ext,\n  let b := et_ih_a_1 \u0393'_is ext,\n  exact has_typ.app a b,\n  exact has_typ.unit,\n  let a := et_ih_a \u0393'_is ext,\n  let b := et_ih_a_1 \u0393'_is ext,\n  exact has_typ.pair a b,\n  exact has_typ.pair_left (et_ih \u0393'_is ext),\n  exact has_typ.pair_right (et_ih \u0393'_is ext),\n  exact has_typ.either_left (et_ih \u0393'_is ext),\n  exact has_typ.either_right (et_ih \u0393'_is ext),\n  exact has_typ.case_never (et_ih \u0393'_is ext),\n  rw case_subst,\n  let t_e1 := subst_preservation_var_helper fv_ex \u0393'_is et_a_1 ext @et_ih_a_1,\n  let t_e2 := subst_preservation_var_helper fv_ex \u0393'_is et_a_2 ext @et_ih_a_2,\n  exact has_typ.case (et_ih_a \u0393'_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 \u2964 FreeAb C :=\n{ obj := of,\n  map := \u03bb X Y f, free_abelian_group.of f,\n  map_id' := \u03bb X, rfl,\n  map_comp' := \u03bb 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' : \u211d\u22650)\nvariables (BD : breen_deligne.data)\nvariables (M : ProFiltPseuNormGrpWithTinv r')\nvariables (c c\u2081 c\u2082 c\u2083 c\u2084 : \u211d\u22650) (l m n : \u2115)\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' : \u211d\u22650) (c : \u211d\u22650) (n : \u2115) :\n  ProFiltPseuNormGrpWithTinv r' \u2964 FreeAb Profinite :=\nFiltrationPow r' c n \u22d9 FreeAb.of_functor _\n\ntheorem FP2_def (r' : \u211d\u22650) (c : \u211d\u22650) (n : \u2115) :\n  FP2 r' c n = FiltrationPow r' c n \u22d9 FreeAb.of_functor _ := rfl\n\nnamespace FP2\n\n@[simps {fully_applied := ff}]\ndef res (r' : \u211d\u22650) (c\u2081 c\u2082 : \u211d\u22650) [fact (c\u2081 \u2264 c\u2082)] (n : \u2115) : FP2 r' c\u2081 n \u27f6 FP2 r' c\u2082 n :=\nwhisker_right (FiltrationPow.cast_le r' c\u2081 c\u2082 n) _\n\n@[simp] lemma res_refl : res r' c c n = \ud835\udfd9 _ :=\nby { simp [res, FiltrationPow.cast_le_refl], refl }\n\nlemma res_comp_res [h\u2081 : fact (c\u2081 \u2264 c\u2082)] [h\u2082 : fact (c\u2082 \u2264 c\u2083)] :\n  res r' c\u2081 c\u2082 n \u226b res r' c\u2082 c\u2083 n = @res r' c\u2081 c\u2083 \u27e8le_trans h\u2081.1 h\u2082.1\u27e9 n :=\nby simp only [res, \u2190 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\u2081 \u2264 r' * c\u2082)] : FP2 r' c\u2081 n \u27f6 FP2 r' c\u2082 n :=\nwhisker_right (FiltrationPow.Tinv r' c\u2081 c\u2082 n) _\n\nlemma Tinv_def [fact (c\u2081 \u2264 r' * c\u2082)] :\n  Tinv r' c\u2081 c\u2082 n = whisker_right (FiltrationPow.Tinv r' c\u2081 c\u2082 n) _ := rfl\n\nlemma res_comp_Tinv\n  [fact (c\u2081 \u2264 c\u2082)] [fact (c\u2082 \u2264 c\u2083)] [fact (c\u2081 \u2264 r' * c\u2082)] [fact (c\u2082 \u2264 r' * c\u2083)] :\n  res r' c\u2081 c\u2082 n \u226b Tinv r' c\u2082 c\u2083 n = Tinv r' c\u2081 c\u2082 n \u226b res r' c\u2082 c\u2083 n :=\nby { simp only [Tinv, res, \u2190 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 (\u03d5 : basic_universal_map m n)\n\ndef eval_FP2 (c\u2081 c\u2082 : \u211d\u22650) [\u03d5.suitable c\u2081 c\u2082] : FP2 r' c\u2081 m \u27f6 FP2 r' c\u2082 n :=\nwhisker_right (\u03d5.eval_FP r' c\u2081 c\u2082) _\n\ndef eval_FP2' (c\u2081 c\u2082 : \u211d\u22650) : FP2 r' c\u2081 m \u27f6 FP2 r' c\u2082 n :=\nif H : \u03d5.suitable c\u2081 c\u2082\nthen by exactI whisker_right (\u03d5.eval_FP r' c\u2081 c\u2082) _\nelse 0\n\nlemma eval_FP2_eq_eval_FP2' (h : \u03d5.suitable c\u2081 c\u2082) :\n  eval_FP2 r' \u03d5 c\u2081 c\u2082 = eval_FP2' r' \u03d5 c\u2081 c\u2082 :=\nby { delta eval_FP2 eval_FP2', rw dif_pos h }\n\nlemma eval_FP2'_def [h : \u03d5.suitable c\u2081 c\u2082] :\n  eval_FP2' r' \u03d5 c\u2081 c\u2082 = whisker_right (\u03d5.eval_FP r' c\u2081 c\u2082) _ :=\ndif_pos h\n\nlemma eval_FP2'_not_suitable (h : \u00ac \u03d5.suitable c\u2081 c\u2082) :\n  eval_FP2' r' \u03d5 c\u2081 c\u2082 = 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\u2081 c\u2082] [hg : g.suitable c\u2082 c\u2083] :\n  eval_FP2' r' (comp g f) c\u2081 c\u2083 = eval_FP2' r' f c\u2081 c\u2082 \u226b eval_FP2' r' g c\u2082 c\u2083 :=\nbegin\n  haveI : (comp g f).suitable c\u2081 c\u2083 := suitable_comp c\u2082,\n  simp only [eval_FP2'_def, eval_FP_comp r' _ c\u2082, 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\u2081 c\u2082] [hg : g.suitable c\u2082 c\u2083] :\n  @eval_FP2 r' _ _ (comp g f) c\u2081 c\u2083 (suitable_comp c\u2082) =\n    eval_FP2 r' f c\u2081 c\u2082 \u226b eval_FP2 r' g c\u2082 c\u2083 :=\nby { simp only [eval_FP2_eq_eval_FP2'], apply eval_FP2'_comp }\n\nlemma res_comp_eval_FP2\n  [fact (c\u2081 \u2264 c\u2082)] [fact (c\u2083 \u2264 c\u2084)] [\u03d5.suitable c\u2082 c\u2084] [\u03d5.suitable c\u2081 c\u2083] :\n  res r' c\u2081 c\u2082 m \u226b eval_FP2 r' \u03d5 c\u2082 c\u2084 = eval_FP2 r' \u03d5 c\u2081 c\u2083 \u226b res r' c\u2083 c\u2084 n :=\nby simp only [res, eval_FP2, \u2190 whisker_right_comp,\n  cast_le_comp_eval_FP _ c\u2081 c\u2082 c\u2083 c\u2084]\n\nlemma Tinv_comp_eval_FP2 [fact (0 < r')] [fact (c\u2081 \u2264 r' * c\u2082)] [fact (c\u2083 \u2264 r' * c\u2084)]\n  [\u03d5.suitable c\u2081 c\u2083] [\u03d5.suitable c\u2082 c\u2084] :\n  Tinv r' c\u2081 c\u2082 m \u226b eval_FP2 r' \u03d5 c\u2082 c\u2084 = eval_FP2 r' \u03d5 c\u2081 c\u2083 \u226b Tinv r' c\u2083 c\u2084 n :=\nby simp only [Tinv, eval_FP2, \u2190 whisker_right_comp,\n  Tinv_comp_eval_FP _ _ c\u2081 c\u2082 c\u2083 c\u2084]\n\nend basic_universal_map\n\nnamespace universal_map\n\nopen free_abelian_group\n\nvariables (\u03d5 : universal_map m n)\n\ndef eval_FP2 [\u03d5.suitable c\u2081 c\u2082] : FP2 r' c\u2081 m \u27f6 FP2 r' c\u2082 n :=\n\u2211 g : {g : basic_universal_map m n // g \u2208 \u03d5.support},\n  begin\n    haveI := suitable_of_mem_support \u03d5 c\u2081 c\u2082 g g.2,\n    exact coeff (g : basic_universal_map m n) \u03d5 \u2022 (basic_universal_map.eval_FP2 r' g c\u2081 c\u2082)\n  end\n\ndef eval_FP2' : FP2 r' c\u2081 m \u27f6 FP2 r' c\u2082 n :=\n\u2211 g in \u03d5.support, coeff g \u03d5 \u2022 (g.eval_FP2' r' c\u2081 c\u2082)\n\nlemma eval_FP2_eq_eval_FP2' (h : \u03d5.suitable c\u2081 c\u2082) :\n  eval_FP2 r' c\u2081 c\u2082 \u03d5 = eval_FP2' r' c\u2081 c\u2082 \u03d5 :=\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 \u03d5.support (\u03bb _, iff.rfl),\nend\n\n@[simp] lemma eval_FP2'_of (f : basic_universal_map m n) :\n  eval_FP2' r' c\u2081 c\u2082 (of f) = f.eval_FP2' r' c\u2081 c\u2082 :=\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\u2081 c\u2082] :\n  eval_FP2 r' c\u2081 c\u2082 (of f) = f.eval_FP2 r' c\u2081 c\u2082 :=\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\u2081 c\u2082 (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\u2081 c\u2082 (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\u2081 c\u2082 (-f) = -eval_FP2' r' c\u2081 c\u2082 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\u2081 c\u2082] :\n  eval_FP2 r' c\u2081 c\u2082 (-f) = -eval_FP2 r' c\u2081 c\u2082 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\u2081 c\u2082 (f + g) = eval_FP2' r' c\u2081 c\u2082 f + eval_FP2' r' c\u2081 c\u2082 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\u2081 c\u2082] [g.suitable c\u2081 c\u2082] :\n  eval_FP2 r' c\u2081 c\u2082 (f + g) = eval_FP2 r' c\u2081 c\u2082 f + eval_FP2 r' c\u2081 c\u2082 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\u2081 c\u2082] [g.suitable c\u2081 c\u2082] :\n  eval_FP2 r' c\u2081 c\u2082 (f - g) = eval_FP2 r' c\u2081 c\u2082 f - eval_FP2 r' c\u2081 c\u2082 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\u2081 c\u2082] [hg : g.suitable c\u2082 c\u2083] :\n  eval_FP2' r' c\u2081 c\u2083 ((universal_map.comp (of g)) (of f)) =\n    eval_FP2' r' c\u2081 c\u2082 (of f) \u226b eval_FP2' r' c\u2082 c\u2083 (of g) :=\nbegin\n  simp only [universal_map.comp_of, eval_FP2'_of],\n  haveI hfg : (basic_universal_map.comp g f).suitable c\u2081 c\u2083 := basic_universal_map.suitable_comp c\u2082,\n  rw \u2190 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\u2081 c\u2082] [hg : g.suitable c\u2082 c\u2083] :\n  eval_FP2' r' c\u2081 c\u2083 (universal_map.comp g f) = eval_FP2' r' c\u2081 c\u2082 f \u226b eval_FP2' r' c\u2082 c\u2083 g :=\nbegin\n  unfreezingI { revert hg },\n  apply free_abelian_group.induction_on_free_predicate\n    (universal_map.suitable c\u2081 c\u2082) (universal_map.suitable_free_predicate c\u2081 c\u2082) f hf;\n      unfreezingI { clear_dependent f },\n  { intros h\u2082,\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\u2082 c\u2083) (universal_map.suitable_free_predicate c\u2082 c\u2083) 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\u2081 : universal_map m n) (g\u2082 : universal_map m n) hg\u2081 hg\u2082 IH\u2081 IH\u2082, resetI,\n      haveI Hg\u2081f : (universal_map.comp g\u2081 (of f)).suitable c\u2081 c\u2083 := suitable.comp c\u2082,\n      haveI Hg\u2082f : (universal_map.comp g\u2082 (of f)).suitable c\u2081 c\u2083 := suitable.comp c\u2082,\n      simp only [add_monoid_hom.map_add, eval_FP2'_add, IH\u2081, IH\u2082, 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\u2081 : universal_map l m) (f\u2082 : universal_map l m) hf\u2081 hf\u2082 IH\u2081 IH\u2082 hf, resetI,\n    haveI Hgf\u2081 : (universal_map.comp g f\u2081).suitable c\u2081 c\u2083 := suitable.comp c\u2082,\n    haveI Hgf\u2082 : (universal_map.comp g f\u2082).suitable c\u2081 c\u2083 := suitable.comp c\u2082,\n    simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, eval_FP2'_add, IH\u2081, IH\u2082, add_comp] }\nend\n\nlemma eval_FP2_comp (g : universal_map m n) (f : universal_map l m)\n  [hf : f.suitable c\u2081 c\u2082] [hg : g.suitable c\u2082 c\u2083] :\n  @eval_FP2 r' c\u2081 c\u2083 _ _ (universal_map.comp g f) (universal_map.suitable.comp c\u2082) =\n    eval_FP2 r' c\u2081 c\u2082 f \u226b eval_FP2 r' c\u2082 c\u2083 g :=\nby { simp only [eval_FP2_eq_eval_FP2'], apply eval_FP2'_comp }\n\nlemma res_comp_eval_FP2 [fact (c\u2081 \u2264 c\u2082)] [fact (c\u2083 \u2264 c\u2084)] [\u03d5.suitable c\u2081 c\u2083] [\u03d5.suitable c\u2082 c\u2084] :\n  res r' c\u2081 c\u2082 m \u226b eval_FP2 r' c\u2082 c\u2084 \u03d5 = eval_FP2 r' c\u2081 c\u2083 \u03d5 \u226b res r' c\u2083 c\u2084 n :=\nbegin\n  simp only [eval_FP2, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n  apply finset.sum_congr rfl,\n  rintros \u27e8g, hg\u27e9 -,\n  haveI : g.suitable c\u2081 c\u2083 := suitable_of_mem_support \u03d5 _ _ g hg,\n  haveI : g.suitable c\u2082 c\u2084 := suitable_of_mem_support \u03d5 _ _ g hg,\n  simp only [subtype.coe_mk, g.res_comp_eval_FP2 r' c\u2081 c\u2082 c\u2083 c\u2084],\nend\n\nlemma Tinv_comp_eval_FP2 [fact (0 < r')] [fact (c\u2081 \u2264 r' * c\u2082)] [fact (c\u2083 \u2264 r' * c\u2084)]\n  [\u03d5.suitable c\u2081 c\u2083] [\u03d5.suitable c\u2082 c\u2084] :\n  Tinv r' c\u2081 c\u2082 m \u226b eval_FP2 r' c\u2082 c\u2084 \u03d5 = eval_FP2 r' c\u2081 c\u2083 \u03d5 \u226b Tinv r' c\u2083 c\u2084 n :=\nbegin\n  simp only [eval_FP2, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n  apply finset.sum_congr rfl,\n  rintros \u27e8g, hg\u27e9 -,\n  haveI : g.suitable c\u2081 c\u2083 := suitable_of_mem_support \u03d5 _ _ g hg,\n  haveI : g.suitable c\u2082 c\u2084 := suitable_of_mem_support \u03d5 _ _ g hg,\n  congr' 1, apply basic_universal_map.Tinv_comp_eval_FP2 r',\nend\n\nend universal_map\n\n\nvariables (\u03ba : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650) [\u2200 c, BD.suitable (\u03ba c)]\n\ndef FPsystem.X (c : \u211d\u22650) (n : \u2115) : FreeAb Profinite :=\nFreeAb.of $ (FiltrationPow r' (\u03ba c n) $ BD.X n).obj M\n\ndef FPsystem.d (c : \u211d\u22650) (n : \u2115) :\n  FPsystem.X r' BD M \u03ba c (n + 1) \u27f6 FPsystem.X r' BD M \u03ba c n :=\n(universal_map.eval_FP2 r' (\u03ba c (n+1)) (\u03ba c n) (BD.d (n+1) n)).app M\n\nlemma FPsystem.d_comp_d (c : \u211d\u22650) (n : \u2115) :\n  FPsystem.d r' BD M \u03ba c (n + 1) \u226b FPsystem.d r' BD M \u03ba c n = 0 :=\nbegin\n  delta FPsystem.d,\n  rw [\u2190 nat_trans.comp_app, \u2190 universal_map.eval_FP2_comp],\n  convert nat_trans.app_zero _, refl, refl,\n  convert universal_map.eval_FP2_zero _ _ _,\n  show BD.d _ _ \u226b BD.d _ _ = 0,\n  rw homological_complex.d_comp_d,\nend\n\nopen opposite\n\ndef FPsystem [h\u03ba : \u2200 n, fact (monotone (function.swap \u03ba n))] :\n  \u211d\u22650 \u2964 chain_complex (FreeAb Profinite) \u2115 :=\n{ obj := \u03bb c, chain_complex.of (FPsystem.X r' BD M \u03ba c) (FPsystem.d r' BD M \u03ba _) (FPsystem.d_comp_d _ _ _ _ _),\n  map := \u03bb c\u2081 c\u2082 h,\n  { f := \u03bb n, by { refine (@FP2.res r' _ _ (id _) (BD.X n)).app M,\n      have := (h\u03ba n).out, refine \u27e8this h.le\u27e9, },\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 [\u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app],\n      congr' 1,\n      apply universal_map.res_comp_eval_FP2,\n    end },\n  map_id' := \u03bb c, begin\n    ext n, dsimp, rw [Filtration.cast_le_refl, (FreeAb.of_functor _).map_id], refl,\n  end,\n  map_comp' := \u03bb c\u2081 c\u2082 c\u2083 h\u2081\u2082 h\u2082\u2083, begin\n    ext n, dsimp, rw [\u2190 (FreeAb.of_functor _).map_comp, Filtration.cast_le_comp],\n  end }\n.\n\ndef FPsystem.Tinv [fact (0 < r')]\n  (\u03ba\u2081 \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\n  [\u2200 c, BD.suitable (\u03ba\u2081 c)] [\u2200 c, BD.suitable (\u03ba\u2082 c)]\n  [h\u03ba\u2081 : \u2200 n, fact (monotone (function.swap \u03ba\u2081 n))]\n  [h\u03ba\u2082 : \u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\n  [\u2200 c n, fact (\u03ba\u2081 c n \u2264 r' * \u03ba\u2082 c n)] :\n  FPsystem r' BD M \u03ba\u2081 \u27f6 FPsystem r' BD M \u03ba\u2082 :=\n{ app := \u03bb c,\n  { f := \u03bb 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 [\u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app],\n      congr' 1,\n      apply universal_map.Tinv_comp_eval_FP2\n    end },\n  naturality' := begin\n    intros c\u2081 c\u2082 h,\n    ext n,\n    dsimp only [FPsystem, Tinv_app, homological_complex.comp_f, functor.comp_map, res_app],\n    rw [\u2190 functor.map_comp, \u2190 functor.map_comp],\n    refl,\n  end }\n\ndef FPsystem.res [fact (r' \u2264 1)]\n  (\u03ba\u2081 \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\n  [\u2200 c, BD.suitable (\u03ba\u2081 c)] [\u2200 c, BD.suitable (\u03ba\u2082 c)]\n  [h\u03ba\u2081 : \u2200 n, fact (monotone (function.swap \u03ba\u2081 n))]\n  [h\u03ba\u2082 : \u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\n  [\u2200 c n, fact (\u03ba\u2081 c n \u2264 \u03ba\u2082 c n)] :\n  FPsystem r' BD M \u03ba\u2081 \u27f6 FPsystem r' BD M \u03ba\u2082 :=\n{ app := \u03bb c,\n  { f := \u03bb 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 [\u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app],\n      congr' 1,\n      apply universal_map.res_comp_eval_FP2\n    end },\n  naturality' := begin\n    intros c\u2081 c\u2082 h,\n    ext n,\n    dsimp only [FPsystem, res_app, homological_complex.comp_f, functor.comp_map],\n    rw [\u2190 functor.map_comp, \u2190 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 \u2227 b \u2227 c \u2228 d` or\n`h2 : \u2203 x y, trans_rel R x y`. Usual usage might be `rcases h1 with \u27e8ha, hb, hc\u27e9 | hd` or\n`rcases h2 with \u27e8x, y, _ | \u27e8z, hxz, hzy\u27e9\u27e9` 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 `\u27e8p1, p2, p3\u27e9`, which matches a constructor with many arguments, or a series\n  of nested conjunctions or existentials. For example if the active hypothesis is `a \u2227 b \u2227 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 \u2228 b \u2228 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 \u27e8y, z\u27e9` 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 \u27e8hx, hy\u27e9 | hz := foo` is equivalent to `rcases foo with \u27e8hx, hy\u27e9 | hz`. Unlike `rcases`,\n  `obtain` also allows one to omit `:= foo`, although a type must be provided in this case,\n  as in `obtain \u27e8hx, hy\u27e9 | hz : a \u2227 b \u2228 c`, in which case it produces a subgoal for proving\n  `a \u2227 b \u2228 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\u03a3` is used where a list represents a disjunction, such as the\n  list of possible constructors of an inductive type.\n\n- `list\u03a0` 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 `\u27e8p1, p2, p3\u27e9`\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 \u2228 a2 \u2228 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 `\u27e8p\u27e9`\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 `\u27e8p\u27e9`. -/\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, \u27e8c, d\u27e9]`\nbecomes `\u27e8a, b, c, d\u27e9` instead of `\u27e8a, b, \u27e8c, d\u27e9\u27e9`.\n\nWe must be careful to turn `[a, \u27e8\u27e9]` into `\u27e8a, \u27e8\u27e9\u27e9` instead of `\u27e8a\u27e9` (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\u2081_core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n`\ninstead of `\u27e8n\u27e9` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `\u27e8a, b, c\u27e9`. -/\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\u2081` 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\u2081_core`, but it produces a cases pattern directly instead of a list of alternatives. We\nspecially translate the empty alternation to `\u27e8\u27e9`, and translate `|(a | b)` to `\u27e8a | b\u27e9` (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 `\u03b1 \u00d7 \u03b2 \u00d7 \u03b3` against `\u27e8a, b, c\u27e9`.\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  `\u27e8a | b, \u27e8c, d\u27e9\u27e9` performs the `\u27e8c, d\u27e9` 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\u2081 pat\u2082 ... pat\u2099` introduces `n` arguments, then pattern matches on the `pat\u1d62` 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 {\u03b1 : Type u_1} (m : \u03b1 \u2192 \u03b1 \u2192 \u03b1) : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1 := 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 `\u27e8a, b\u27e9` 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 `\u03a3\u03a0`-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? \u27e8e1, e2, e3\u27e9` is like `rcases \u27e8e1, e2, e3\u27e9 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? \u27e8e1, e2, e3\u27e9 : 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\" | \"_\" | \"\u27e8\" (patt \",\")* patt \"\u27e9\" | \"(\" 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? \u27e8expr, ...\u27e9 (: n)?` calls `rcases_hint`\n* `rcases? \u27e8expr, ...\u27e9 (: n)?` calls `rcases_hint_many`\n* `rcases (h :)? expr (with patt)?` calls `rcases`\n* `rcases \u27e8expr, ...\u27e9 (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 \u2227 b \u2227 c \u2228 d` or\n`h2 : \u2203 x y, trans_rel R x y`. Usual usage might be `rcases h1 with \u27e8ha, hb, hc\u27e9 | hd` or\n`rcases h2 with \u27e8x, y, _ | \u27e8z, hxz, hzy\u27e9\u27e9` 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 `\u27e8p1, p2, p3\u27e9`, which matches a constructor with many arguments, or a series\n  of nested conjunctions or existentials. For example if the active hypothesis is `a \u2227 b \u2227 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 \u2228 b \u2228 c`.\n\nA pattern like `\u27e8a, b, c\u27e9 | \u27e8d, e\u27e9` 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 `\u27e8\u27e8a\u27e9, b | c\u27e9 | d` then these will cause more case splits as necessary.\nIf there are too many arguments, such as `\u27e8a, b, c\u27e9` for splitting on\n`\u2203 x, \u2203 y, p x`, then it will be treated as `\u27e8a, \u27e8b, c\u27e9\u27e9`, 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 | \u27e8b, c\u27e9) \u27e8d, e\u27e9`\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 \u27e8patt\u27e9 : type,\n{ ... }\n```\nis equivalent to\n```lean\nhave h : type,\n{ ... },\nrcases h with \u27e8patt\u27e9\n```\n\nThe syntax `obtain \u27e8patt\u27e9 : type := proof` is also supported.\n\nIf `\u27e8patt\u27e9` 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 \u03b1] : \u03b1 \u2192 \u03b1 \u2192 Prop\n  | intro\n    (mem_cpt?_iff : \u2200 cpt j, (j \u2208 cpt? cpt rtr\u2081) \u2194 (j \u2208 cpt? cpt rtr\u2082)) \n    (rcns_some_eq : \u2200 {i r\u2081 r\u2082}, (rcns rtr\u2081 i = some r\u2081) \u2192 (rcns rtr\u2082 i = some r\u2082) \u2192 r\u2081 = r\u2082) \n    (nest_equiv : \u2200 {i n\u2081 n\u2082}, (nest rtr\u2081 i = some n\u2081) \u2192 (nest rtr\u2082 i = some n\u2082) \u2192 Equivalent n\u2081 n\u2082) \n    : Equivalent rtr\u2081 rtr\u2082\n \nnamespace Equivalent\n\ninstance [ReactorType \u03b1] : HasEquiv \u03b1 where \n  Equiv := Equivalent\n\n@[refl]\nprotected theorem refl [ReactorType.WellFounded \u03b1] {rtr : \u03b1} : rtr \u2248 rtr := by\n  induction rtr using ReactorType.WellFounded.induction\n  case nest hi =>\n    constructor <;> (intros; simp_all)\n    exact hi _ _ \u2039_\u203a  \n\nvariable [ReactorType \u03b1] {rtr rtr\u2081 : \u03b1}\n\n@[symm]\nprotected theorem symm (e : rtr\u2081 \u2248 rtr\u2082) : rtr\u2082 \u2248 rtr\u2081 := by\n  induction e\n  case intro h\u2081 h\u2082 _ hi => \n    constructor <;> intros\n    \u00b7 exact h\u2081 \u2039_\u203a \u2039_\u203a |>.symm\n    \u00b7 exact h\u2082 \u2039_\u203a \u2039_\u203a |>.symm\n    \u00b7 exact hi \u2039_\u203a \u2039_\u203a\n \n@[trans]\nprotected theorem trans (e\u2081 : rtr\u2081 \u2248 rtr\u2082) (e\u2082 : rtr\u2082 \u2248 rtr\u2083) : rtr\u2081 \u2248 rtr\u2083 := by\n  induction e\u2081 generalizing rtr\u2083; cases e\u2082\n  case intro.intro h\u2081 h\u2082 _ hi h\u2081' h\u2082' h\u2083' => \n    constructor\n    \u00b7 intros; exact h\u2081 \u2039_\u203a \u2039_\u203a |>.trans (h\u2081' \u2039_\u203a \u2039_\u203a)\n    \u00b7 intro _ _ _ h _\n      have \u27e8_, h\u27e9 := Partial.mem_iff.mp <| h\u2081 .rcn \u2039_\u203a |>.mp $ Partial.mem_iff.mpr \u27e8_, h\u27e9\n      exact h\u2082 \u2039_\u203a h |>.trans (h\u2082' h \u2039_\u203a)\n    \u00b7 intro _ _ _ h _\n      have \u27e8_, h\u27e9 := Partial.mem_iff.mp <| h\u2081 .rtr \u2039_\u203a |>.mp $ Partial.mem_iff.mpr \u27e8_, h\u27e9 \n      exact hi \u2039_\u203a h (h\u2083' h \u2039_\u203a)\n\ntheorem mem_cpt?_iff : (rtr\u2081 \u2248 rtr\u2082) \u2192 (i \u2208 cpt? cpt rtr\u2081 \u2194 i \u2208 cpt? cpt rtr\u2082)\n  | intro h .. => h _ _\n\ntheorem rcns_some_eq : (rtr\u2081 \u2248 rtr\u2082) \u2192 (rcns rtr\u2081 i = some r\u2081) \u2192 (rcns rtr\u2082 i = some r\u2082) \u2192 r\u2081 = r\u2082\n  | intro _ h .. => h\n\ntheorem nest_equiv : (rtr\u2081 \u2248 rtr\u2082) \u2192 (nest rtr\u2081 i = some n\u2081) \u2192 (nest rtr\u2082 i = some n\u2082) \u2192 n\u2081 \u2248 n\u2082\n  | intro _ _ h => h\n\ntheorem rcns_eq (e : rtr\u2081 \u2248 rtr\u2082) : rcns rtr\u2082 = rcns rtr\u2081 := by\n  funext i\n  by_cases h\u2081 : i \u2208 rcns rtr\u2081 \n  case pos =>\n    have \u27e8_, h\u2082\u27e9 := Partial.mem_iff.mp $ mem_cpt?_iff e (cpt := .rcn) |>.mp h\u2081\n    have \u27e8_, h\u2081\u27e9 := Partial.mem_iff.mp h\u2081\n    exact rcns_some_eq e h\u2081 h\u2082 \u25b8 h\u2081 |>.symm \u25b8 h\u2082\n  case neg =>\n    have h\u2082 := Partial.mem_iff.not.mp $ mem_cpt?_iff e (cpt := .rcn) |>.not.mp h\u2081\n    have h\u2081 := Partial.mem_iff.not.mp h\u2081\n    simp [cpt?] at h\u2081 h\u2082 \n    simp [Option.eq_none_iff_forall_not_mem.mpr h\u2081, Option.eq_none_iff_forall_not_mem.mpr h\u2082]\n\ntheorem cpt?_some_iff (e : rtr\u2081 \u2248 rtr\u2082) :\n    (\u2203 o\u2081, cpt? cpt rtr\u2081 i = some o\u2081) \u2194 (\u2203 o\u2082, cpt? cpt rtr\u2082 i = some o\u2082) := by\n  simp [\u2190Partial.mem_iff, mem_cpt?_iff e]\n\nvariable [Indexable \u03b1] {rtr\u2081 : \u03b1}\n\ntheorem obj?_rcn_eq (e : rtr\u2081 \u2248 rtr\u2082) : rtr\u2081[.rcn] = rtr\u2082[.rcn] :=\n  sorry\n\ntheorem mem_iff {i} (e : rtr\u2081 \u2248 rtr\u2082) : (i \u2208 rtr\u2081[cpt]) \u2194 (i \u2208 rtr\u2082[cpt]) := by\n  sorry\n\ntheorem obj?_rtr_equiv (e : rtr\u2081 \u2248 rtr\u2082) (h\u2081 : rtr\u2081[.rtr][i] = some n\u2081) (h\u2082 : rtr\u2082[.rtr][i] = some n\u2082) : \n    n\u2081 \u2248 n\u2082 := by\n  sorry\n\ntheorem obj?_some_iff (e : rtr\u2081 \u2248 rtr\u2082) :\n    (\u2203 o\u2081, rtr\u2081[cpt][i] = some o\u2081) \u2194 (\u2203 o\u2082, rtr\u2082[cpt][i] = some o\u2082) := \n  sorry\n\nend Equivalent\n\ntheorem LawfulMemUpdate.equiv [ReactorType.WellFounded \u03b1] {rtr\u2081 : \u03b1}\n    (u : LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) : rtr\u2081 \u2248 rtr\u2082 := by\n  induction u <;> constructor\n  case final.mem_cpt?_iff e h\u2081 h\u2082 =>\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\u2081, h\u2082]\n  case final.rcns_some_eq e _ _ =>\n    intro j _ _ h\u2081 h\u2082\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\u2081 h\u2082\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\u2081 h\u2082 _ _ =>\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\u2081, h\u2082]\n  case nest.rcns_some_eq e h\u2081 h\u2082 _ _ =>\n    intro j _ _ h\u2081 h\u2082\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\u2081' n\u2082' h\u2081' h\u2082'\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 \u03b1] {rtr\u2081 : \u03b1} :\n    (LawfulUpdate cpt i f rtr\u2081 rtr\u2082) \u2192 rtr\u2081 \u2248 rtr\u2082\n  | notMem _ h => h \u25b8 .refl\n  | update u   => u.equiv\n\ntheorem LawfulUpdatable.equiv [LawfulUpdatable \u03b1] {rtr : \u03b1} : \n    (Updatable.update rtr cpt i f) \u2248 rtr := \n  Equivalent.symm (lawful rtr cpt i f).equiv\n\nnamespace Member\n\ninductive Equivalent [ReactorType \u03b1] [ReactorType \u03b2] : \n    {rtr\u2081 : \u03b1} \u2192 {rtr\u2082 : \u03b2} \u2192 (Member cpt i rtr\u2081) \u2192 (Member cpt i rtr\u2082) \u2192 Prop \n  | final : Equivalent (.final h\u2081) (.final h\u2082)\n  | nest {n\u2081 : \u03b1} {n\u2082 : \u03b2} {m\u2081 : Member cpt i n\u2081} {m\u2082 : Member cpt i n\u2082} :\n    (h\u2081 : ReactorType.nest rtr\u2081 j = some n\u2081) \u2192 (h\u2082 : ReactorType.nest rtr\u2082 j = some n\u2082) \u2192 \n    (Equivalent m\u2081 m\u2082) \u2192 Equivalent (.nest h\u2081 m\u2081) (.nest h\u2082 m\u2082)\n\nnamespace Equivalent\n\n@[refl]\ntheorem refl [ReactorType.WellFounded \u03b1] {rtr : \u03b1} {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 _ \u27e8_, h\u27e9)\n\nvariable [ReactorType \u03b1] [ReactorType \u03b2]\n\ntheorem symm {rtr\u2081 : \u03b1} {rtr\u2082 : \u03b2} {m\u2081 : Member cpt i rtr\u2081} {m\u2082 : Member cpt i rtr\u2082}\n    (e : Equivalent m\u2081 m\u2082) : (Equivalent m\u2082 m\u2081) := by\n  induction e <;> constructor; assumption\n\ntheorem trans \n    [ReactorType \u03b3] {rtr\u2081 : \u03b1} {rtr\u2082 : \u03b2} {rtr\u2083 : \u03b3}\n    {m\u2081 : Member cpt i rtr\u2081} {m\u2082 : Member cpt i rtr\u2082} {m\u2083 : Member cpt i rtr\u2083}\n    (e\u2081 : Equivalent m\u2081 m\u2082) (e\u2082 : Equivalent m\u2082 m\u2083) : (Equivalent m\u2081 m\u2083) := by\n  induction e\u2081 generalizing m\u2083 rtr\u2083 <;> cases e\u2082 <;> constructor\n  case nest.nest hi\u2081 _ _ _ _ hi\u2082 => exact hi\u2081 hi\u2082\n\n-- Lemma for `to_eq`.\nprivate theorem to_eq' {rtr\u2081 rtr\u2082 : \u03b1} {m\u2081 : Member cpt i rtr\u2081} {m\u2082 : Member cpt i rtr\u2082} \n    (h : rtr\u2081 = rtr\u2082) (e : Equivalent m\u2081 m\u2082) : m\u2081 = cast (by simp [h]) m\u2082 := by\n  induction e <;> subst h\n  case final => rfl\n  case nest m\u2081 _ h\u2081 _ hi h\u2082 => \n    injection h\u2081 \u25b8 h\u2082 with h\n    simp [hi h, h]\n\ntheorem to_eq {rtr : \u03b1} {m\u2081 m\u2082 : Member cpt i rtr} (e : Equivalent m\u2081 m\u2082) : m\u2081 = m\u2082 := \n  e.to_eq' rfl\n\ntheorem from_lawfulCoe [ReactorType \u03b1] [ReactorType \u03b2] [LawfulCoe \u03b1 \u03b2] {rtr : \u03b1} \n    (m : Member cpt i rtr) : Equivalent m (m : Member cpt i (rtr : \u03b2)) := by\n  induction m\n  case final => constructor\n  case nest e => simp [fromLawfulCoe, Equivalent.nest _ _ e]\n\nend Equivalent\n\nvariable [ReactorType.WellFounded \u03b1] {rtr\u2081 : \u03b1}\n\ndef fromLawfulMemUpdate {rtr\u2081 : \u03b1} : \n    (Member c j rtr\u2082) \u2192 (LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) \u2192 Member c j rtr\u2081\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 \u25b8 h\n  | nest h m (j := j\u2082), .nest e h\u2081 h\u2082 u (j := j\u2081) =>\n      if hj : j\u2082 = j\u2081 then\n        let m' := (hj \u25b8 h |>.symm.trans h\u2082 |> Option.some_inj.mp) \u25b8 m \n        nest h\u2081 $ 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 \u25b8 h\n\ndef fromLawfulUpdate (m : Member c j rtr\u2082) : (LawfulUpdate cpt i f rtr\u2081 rtr\u2082) \u2192 Member c j rtr\u2081\n  | .notMem _ h => h \u25b8 m\n  | .update u   => m.fromLawfulMemUpdate u\n\ntheorem Equivalent.from_lawfulMemUpdate (u : LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) \n    (m : Member c j rtr\u2082) : 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 \u25b8 hn) .refl\n  case nest.nest e h\u2081 h\u2082 _ hi _ _ m hn =>\n    split\n    case inl hj =>\n      subst hj\n      cases Option.some_inj.mp $ hn.symm.trans h\u2082\n      exact .nest hn h\u2081 (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 \u25b8 hn) .refl\n\ntheorem Equivalent.from_lawfulUpdate (u : LawfulUpdate cpt i f rtr\u2081 rtr\u2082) \n    (m : Member c j rtr\u2082) : 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 \u03b1] [ReactorType \u03b2] [LawfulCoe \u03b1 \u03b2] {rtr : \u03b1} \n    (h : UniqueIDs (rtr : \u03b2)) : UniqueIDs rtr where\n  allEq m\u2081 m\u2082 :=\n    h.allEq (.fromLawfulCoe m\u2081) (.fromLawfulCoe m\u2082) \u25b8 Member.Equivalent.from_lawfulCoe m\u2081 \n      |>.trans (Member.Equivalent.from_lawfulCoe m\u2082).symm \n      |>.to_eq\n\ninstance [LawfulUpdatable \u03b1] [ind : Indexable \u03b2] [LawfulCoe \u03b1 \u03b2] : Indexable \u03b1 where\n  unique_ids := UniqueIDs.lift ind.unique_ids \n\nopen Equivalent\nvariable [Indexable \u03b1] [Indexable \u03b2] {rtr rtr\u2081 : \u03b1}\n\nnamespace Dependency\n \ntheorem equiv (e : rtr\u2081 \u2248 rtr\u2082) (d : j\u2081 <[rtr\u2082] j\u2082) : j\u2081 <[rtr\u2081] j\u2082 := by\n  induction d with\n  | prio h\u2081 h\u2082 h\u2083 => \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 \u27e8_, h\u2081'\u27e9 := obj?_some_iff e |>.mpr \u27e8_, h\u2081\u27e9\n    have e := Equivalent.obj?_rtr_equiv e h\u2081' h\u2081\n    exact prio h\u2081' (rcns_eq e \u25b8 h\u2082) (rcns_eq e \u25b8 h\u2083) \u2039_\u203a \u2039_\u203a\n  | mutNorm h\u2081 h\u2082 h\u2083 => \n    have \u27e8_, h\u2081'\u27e9 := obj?_some_iff e |>.mpr \u27e8_, h\u2081\u27e9  \n    have e := Equivalent.obj?_rtr_equiv e h\u2081' h\u2081\n    exact mutNorm h\u2081' (rcns_eq e \u25b8 h\u2082) (rcns_eq e \u25b8 h\u2083) \u2039_\u203a \u2039_\u203a\n  | depOverlap h\u2081 h\u2082 => \n    exact depOverlap (e.obj?_rcn_eq.symm \u25b8 h\u2081) (e.obj?_rcn_eq.symm \u25b8 h\u2082) \u2039_\u203a \u2039_\u203a \u2039_\u203a\n  | mutNest h\u2081 h\u2082 h\u2083 _ h\u2084 => \n    have \u27e8_, h\u2081'\u27e9 := e.obj?_some_iff.mpr \u27e8_, h\u2081\u27e9  \n    have e := Equivalent.obj?_rtr_equiv e h\u2081' h\u2081\n    have \u27e8_, h\u2082'\u27e9 := cpt?_some_iff e (cpt := .rtr) |>.mpr \u27e8_, h\u2082\u27e9\n    have h\u2084' := mem_cpt?_iff (Equivalent.nest_equiv e h\u2082' h\u2082) (cpt := .rcn) |>.mpr h\u2084\n    exact mutNest h\u2081' h\u2082' (rcns_eq e \u25b8 h\u2083) \u2039_\u203a h\u2084'\n  | trans _ _ d\u2081 d\u2082 => \n    exact trans d\u2081 d\u2082\n\ntheorem Acyclic.equiv (e : rtr\u2081 \u2248 rtr\u2082) (a : Acyclic rtr\u2081) : Acyclic rtr\u2082 :=\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 \u2039_\u203a h\u2081 h\u2082\n    have \u27e8_, hc'\u27e9 := Equivalent.cpt?_some_iff e (cpt := .rtr) |>.mp \u27e8_, hc\u27e9 \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\u2081 \u2248 rtr\u2082) (h\u2081 : rtr\u2081[.rtr][j] = some con\u2081) (h\u2082 : rtr\u2082[.rtr][j] = some con\u2082) : \n    (ValidDependency con\u2081 rk dk d) \u2192 ValidDependency con\u2082 rk dk d\n  | stv h           => stv $ mem_cpt?_iff (obj?_rtr_equiv e h\u2081 h\u2082) (cpt := .stv) |>.mp h\n  | act h           => act $ mem_cpt?_iff (obj?_rtr_equiv e h\u2081 h\u2082) (cpt := .act) |>.mp h\n  | prt h           => prt $ mem_cpt?_iff (obj?_rtr_equiv e h\u2081 h\u2082) (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\u2081:ident rtr\u2082:ident : term => `(\n  fun h\u2081 h\u2082 h\u2083 => \n    have \u27e8_, h\u2081'\u27e9 := Equivalent.obj?_some_iff \u2039$rtr\u2081 \u2248 $rtr\u2082\u203a |>.mpr \u27e8_, h\u2081\u27e9 \n    have e := Equivalent.obj?_rtr_equiv \u2039_\u203a h\u2081' h\u2081\n    $(Lean.mkIdentFrom name $ `Wellformed ++ name.getId) \n      \u2039_\u203a h\u2081' (Equivalent.rcns_eq e \u25b8 h\u2082) (Equivalent.rcns_eq e \u25b8 h\u2083)\n)\n\ntheorem equiv (e : rtr\u2081 \u2248 rtr\u2082) (wf : Wellformed rtr\u2081) : Wellformed rtr\u2082 where\n  overlap_prio  := equiv_prio_proof overlap_prio rtr\u2081 rtr\u2082\n  hazards_prio  := equiv_prio_proof hazards_prio rtr\u2081 rtr\u2082\n  mutation_prio := equiv_prio_proof mutation_prio rtr\u2081 rtr\u2082\n  acyclic_deps  := wf.acyclic_deps.equiv e\n  valid_deps h\u2081 h\u2082 h\u2083 := \n    have \u27e8_, h\u2081'\u27e9 := Equivalent.obj?_some_iff e |>.mpr \u27e8_, h\u2081\u27e9 \n    have e := Equivalent.obj?_rtr_equiv e h\u2081' h\u2081\n    have h\u2082' := Equivalent.rcns_eq e \u25b8 h\u2082\n    wf.valid_deps h\u2081' h\u2082' h\u2083 |>.equiv \u2039_\u203a h\u2081' h\u2081\n  unique_inputs h\u2081 h\u2082 _ h\u2083 := \n    have h\u2083' := Equivalent.mem_iff e |>.mpr h\u2083\n    wf.unique_inputs (e.obj?_rcn_eq.symm \u25b8 h\u2081) (e.obj?_rcn_eq.symm \u25b8 h\u2082) \u2039_\u203a h\u2083'\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 lean_gym.server\n\n-- set up server\nmeta def  json_config : json_server lean_server_request lean_server_response := {\n  read_write := io_streams.stdin_stdout_streams,\n  get_json := json_server.get_custom_json,   -- use custom format since faster\n  put_json := json_server.put_standard_json, -- use standard format  \n}\n\ntheorem foo : 1=1 := begin\nlean_gym.run_server_from_tactic json_config,\nrefl\nend", "meta": {"author": "jasonrute", "repo": "lean_gym_prototype", "sha": "ab29624d14e4e069e15afe0b1d90248b5b394b86", "save_path": "github-repos/lean/jasonrute-lean_gym_prototype", "path": "github-repos/lean/jasonrute-lean_gym_prototype/lean_gym_prototype-ab29624d14e4e069e15afe0b1d90248b5b394b86/src/examples/interactive_tactic_entry.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.05419873249666699, "lm_q1q2_score": 0.015081165527256742}}
{"text": "example (a : \u03b1) (f : \u03b1 \u2192 Option \u03b1) : Bool := by\n  match h:f a with\n  | some _ => exact true\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/matchMissingCasesAsStuckError.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.06008665564415841, "lm_q1q2_score": 0.015076510222291473}}
{"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 (\ud835\udc9e : Type u) [category.{v} \ud835\udc9e]\n\n@[ext]\nstructure short_exact_sequence [has_images \ud835\udc9e] [has_zero_morphisms \ud835\udc9e] [has_kernels \ud835\udc9e] :=\n(fst snd trd : \ud835\udc9e)\n(f : fst \u27f6 snd)\n(g : snd \u27f6 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 {\ud835\udc9e} [has_images \ud835\udc9e] [has_zero_morphisms \ud835\udc9e] [has_kernels \ud835\udc9e]\n\n@[simp, reassoc] lemma f_comp_g (A : short_exact_sequence \ud835\udc9e) : A.f \u226b A.g = 0 := A.exact'.w\n\n@[ext]\nstructure hom (A B : short_exact_sequence \ud835\udc9e) :=\n(fst : A.1 \u27f6 B.1)\n(snd : A.2 \u27f6 B.2)\n(trd : A.3 \u27f6 B.3)\n(sq1' : fst \u226b B.f = A.f \u226b snd . obviously)\n(sq2' : snd \u226b B.g = A.g \u226b 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 \ud835\udc9e) := \u27e8hom\u27e9\n\ndef id (A : short_exact_sequence \ud835\udc9e) : A \u27f6 A :=\n{ fst := \ud835\udfd9 _,\n  snd := \ud835\udfd9 _,\n  trd := \ud835\udfd9 _,\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 \ud835\udc9e} (f : A \u27f6 B) (g : B \u27f6 C) : A \u27f6 C :=\n{ fst := f.1 \u226b g.1,\n  snd := f.2 \u226b g.2,\n  trd := f.3 \u226b 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 \ud835\udc9e) :=\n{ id := id,\n  comp := \u03bb 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 \ud835\udc9e)) }\n\n@[simp] lemma id_fst (A : short_exact_sequence \ud835\udc9e) : hom.fst (\ud835\udfd9 A) = \ud835\udfd9 A.1 := rfl\n@[simp] lemma id_snd (A : short_exact_sequence \ud835\udc9e) : hom.snd (\ud835\udfd9 A) = \ud835\udfd9 A.2 := rfl\n@[simp] lemma id_trd (A : short_exact_sequence \ud835\udc9e) : hom.trd (\ud835\udfd9 A) = \ud835\udfd9 A.3 := rfl\n\nvariables {A B C : short_exact_sequence \ud835\udc9e} (f : A \u27f6 B) (g : B \u27f6 C)\n\n@[simp, reassoc] lemma comp_fst : (f \u226b g).1 = f.1 \u226b g.1 := rfl\n@[simp, reassoc] lemma comp_snd : (f \u226b g).2 = f.2 \u226b g.2 := rfl\n@[simp, reassoc] lemma comp_trd : (f \u226b g).3 = f.3 \u226b g.3 := rfl\n\nvariables (\ud835\udc9e)\n\n@[simps] def Fst : short_exact_sequence \ud835\udc9e \u2964 \ud835\udc9e :=\n{ obj := fst, map := \u03bb A B f, f.1 }\n\n@[simps] def Snd : short_exact_sequence \ud835\udc9e \u2964 \ud835\udc9e :=\n{ obj := snd, map := \u03bb A B f, f.2 }\n\n@[simps] def Trd : short_exact_sequence \ud835\udc9e \u2964 \ud835\udc9e :=\n{ obj := trd, map := \u03bb A B f, f.3 }\n\n@[simps] def f_nat : Fst \ud835\udc9e \u27f6 Snd \ud835\udc9e :=\n{ app := \u03bb A, A.f,\n  naturality' := \u03bb A B f, f.sq1 }\n\n@[simps] def g_nat : Snd \ud835\udc9e \u27f6 Trd \ud835\udc9e :=\n{ app := \u03bb A, A.g,\n  naturality' := \u03bb A B f, f.sq2 }\n\ninstance : has_zero_morphisms (short_exact_sequence \ud835\udc9e) :=\n{ has_zero := \u03bb A B, \u27e8{ fst := 0, snd := 0, trd := 0 }\u27e9,\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 \u27f6 B).1 = 0 := rfl\n\n@[simp] lemma hom_zero_snd : (0 : A \u27f6 B).2 = 0 := rfl\n\n@[simp] lemma hom_zero_trd : (0 : A \u27f6 B).3 = 0 := rfl\n\nvariables {\ud835\udc9e}\n\nprotected def functor (A : short_exact_sequence \ud835\udc9e) : fin 3 \u2964 \ud835\udc9e :=\nfin3_functor_mk ![A.1, A.2, A.3] A.f A.g\n\ndef functor_map {A B : short_exact_sequence \ud835\udc9e} (f : A \u27f6 B) :\n  \u03a0 i, A.functor.obj i \u27f6 B.functor.obj i\n| \u27e80,h\u27e9 := f.1\n| \u27e81,h\u27e9 := f.2\n| \u27e82,h\u27e9 := f.3\n| \u27e8i+3,hi\u27e9 := 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 \ud835\udc9e} (f : A \u27f6 B) :\n  \u2200 (i j : fin 3) (hij : i \u2264 j),\n    functor_map f i \u226b B.functor.map hij.hom = A.functor.map hij.hom \u226b functor_map f j\n| \u27e80,hi\u27e9 \u27e80,hj\u27e9 hij := by aux_tac\n| \u27e81,hi\u27e9 \u27e81,hj\u27e9 hij := by aux_tac\n| \u27e82,hi\u27e9 \u27e82,hj\u27e9 hij := by aux_tac\n| \u27e80,hi\u27e9 \u27e81,hj\u27e9 hij := f.sq1\n| \u27e81,hi\u27e9 \u27e82,hj\u27e9 hij := f.sq2\n| \u27e8i+3,hi\u27e9 _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+3,hj\u27e9 _ := by { exfalso, revert hj, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e80,hi\u27e9 \u27e82,hj\u27e9 hij :=\nbegin\n  have h01 : (0 : fin 3) \u27f6 1 := hom_of_le dec_trivial,\n  have h12 : (1 : fin 3) \u27f6 2 := hom_of_le dec_trivial,\n  calc functor_map f \u27e80, hi\u27e9 \u226b B.functor.map hij.hom\n      = functor_map f \u27e80, hi\u27e9 \u226b B.functor.map h01 \u226b B.functor.map h12 : _\n  ... = (functor_map f \u27e80, hi\u27e9 \u226b B.functor.map h01) \u226b B.functor.map h12 : by rw category.assoc\n  ... = (A.functor.map h01 \u226b functor_map f _) \u226b B.functor.map h12 : _\n  ... = A.functor.map h01 \u226b functor_map f _ \u226b B.functor.map h12 : category.assoc _ _ _\n  ... = A.functor.map h01 \u226b A.functor.map h12 \u226b functor_map f _ : _\n  ... = A.functor.map hij.hom \u226b functor_map f \u27e82, hj\u27e9 : _,\n  { rw [\u2190 functor.map_comp], congr, },\n  { congr' 1, exact f.sq1 },\n  { congr' 1, exact f.sq2 },\n  { rw [\u2190 functor.map_comp_assoc], congr, },\nend\n\n@[simps] def Functor : short_exact_sequence \ud835\udc9e \u2964 fin 3 \u2964 \ud835\udc9e :=\n{ obj := short_exact_sequence.functor,\n  map := \u03bb A B f,\n  { app := functor_map f,\n    naturality' := \u03bb i j hij, (functor_map_naturality f i j hij.le).symm },\n  map_id' := \u03bb A, by { ext i, fin_cases i; refl },\n  map_comp' := \u03bb A B C f g, by { ext i, fin_cases i; refl } }\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nvariables {\ud835\udc9e} [abelian \ud835\udc9e]\nvariables {A B C : short_exact_sequence \ud835\udc9e} (f : A \u27f6 B) (g : B \u27f6 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 \ud835\udc9e _ _\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 \u27e8\u27e8inv f.1, inv f.2, inv f.3, _, _\u27e9, _, _\u27e9,\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\u2081 : A.1 \u2245 B.1) (f\u2082 : A.2 \u2245 B.2) (f\u2083 : A.3 \u2245 B.3)\n  (sq1 : f\u2081.hom \u226b B.f = A.f \u226b f\u2082.hom) (sq2 : f\u2082.hom \u226b B.g = A.g \u226b f\u2083.hom) :\n  A \u2245 B :=\n{ hom := \u27e8f\u2081.hom, f\u2082.hom, f\u2083.hom, sq1, sq2\u27e9,\n  inv :=\n  begin\n    refine \u27e8f\u2081.inv, f\u2082.inv, f\u2083.inv, _, _\u27e9; dsimp,\n    rw [iso.inv_comp_eq, \u2190 category.assoc, iso.eq_comp_inv, sq1],\n    rw [iso.inv_comp_eq, \u2190 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\u2081 : A.1 \u2245 B.1) (f\u2082 : A.2 \u27f6 B.2) (f\u2083 : A.3 \u2245 B.3)\n  (sq1 : f\u2081.hom \u226b B.f = A.f \u226b f\u2082) (sq2 : f\u2082 \u226b B.g = A.g \u226b f\u2083.hom) :\n  A \u2245 B :=\nlet F : A \u27f6 B := \u27e8f\u2081.hom, f\u2082, f\u2083.hom, sq1, sq2\u27e9 in\n{ hom := F,\n  inv :=\n  begin\n    haveI : is_iso F.2 := snd_is_iso _ infer_instance infer_instance,\n    refine \u27e8f\u2081.inv, inv F.2, f\u2083.inv, _, _\u27e9; dsimp,\n    rw [iso.inv_comp_eq, \u2190 category.assoc, is_iso.eq_comp_inv, sq1],\n    rw [is_iso.inv_comp_eq, \u2190 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 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is *left split*\nif there exists a morphism `\u03c6 : A\u2082 \u27f6 A\u2081` such that `f \u226b \u03c6 = \ud835\udfd9 A\u2081`. -/\ndef left_split (A : short_exact_sequence \ud835\udc9e) : Prop :=\n\u2203 \u03c6 : A.2 \u27f6 A.1, A.f \u226b \u03c6 = \ud835\udfd9 A.1\n\n/-- A short exact sequence `0 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is *right split*\nif there exists a morphism `\u03c6 : A\u2082 \u27f6 A\u2081` such that `f \u226b \u03c6 = \ud835\udfd9 A\u2081`. -/\ndef right_split (A : short_exact_sequence \ud835\udc9e) : Prop :=\n\u2203 \u03c7 : A.3 \u27f6 A.2, \u03c7 \u226b A.g = \ud835\udfd9 A.3\n\nvariables {\ud835\udc9c : Type*} [category \ud835\udc9c] [abelian \ud835\udc9c]\n\nlemma exact_of_split {A B C : \ud835\udc9c} (f : A \u27f6 B) (g : B \u27f6 C) (\u03c7 : C \u27f6 B) (\u03c6 : B \u27f6 A)\n  (hfg : f \u226b g = 0) (H : \u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 B) : exact f g :=\n{ w := hfg,\n  epi :=\n  begin\n    let \u03c8 : (kernel_subobject g : \ud835\udc9c) \u27f6 image_subobject f :=\n      subobject.arrow _ \u226b \u03c6 \u226b factor_thru_image_subobject f,\n    suffices : \u03c8 \u226b image_to_kernel f g hfg = \ud835\udfd9 _,\n    { convert epi_of_epi \u03c8 _, rw this, apply_instance },\n    rw \u2190 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 \u226b \u03c6 \u226b f\n        = (kernel_subobject g).arrow \u226b \ud835\udfd9 B : _\n    ... = (kernel_subobject g).arrow        : category.comp_id _,\n    rw [\u2190 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 : \ud835\udc9c) : exact (biprod.inl : A \u27f6 A \u229e B) biprod.snd :=\nexact_of_split _ _ biprod.inr biprod.fst biprod.inl_snd biprod.total\n\ndef mk_of_split {A B C : \ud835\udc9c} (f : A \u27f6 B) (g : B \u27f6 C) (\u03c6 : B \u27f6 A) (\u03c7 : C \u27f6 B)\n  (hfg : f \u226b g = 0) (h\u03c6 : f \u226b \u03c6 = \ud835\udfd9 A) (h\u03c7 : \u03c7 \u226b g = \ud835\udfd9 C) (H : \u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 B) :\n  short_exact_sequence \ud835\udc9c :=\n{ fst := A,\n  snd := B,\n  trd := C,\n  f := f,\n  g := g,\n  mono' := by { haveI : mono (f \u226b \u03c6), { rw h\u03c6, apply_instance }, exact mono_of_mono f \u03c6, },\n  epi' := by { haveI : epi (\u03c7 \u226b g), { rw h\u03c7, apply_instance }, exact epi_of_epi \u03c7 g, },\n  exact' := exact_of_split f g \u03c7 \u03c6 hfg H }\n\ndef mk_of_split' {A B C : \ud835\udc9c} (f : A \u27f6 B) (g : B \u27f6 C)\n  (H : \u2203 (\u03c6 : B \u27f6 A) (\u03c7 : C \u27f6 B), f \u226b g = 0 \u2227 f \u226b \u03c6 = \ud835\udfd9 A \u2227 \u03c7 \u226b g = \ud835\udfd9 C \u2227 \u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 B) :\n  short_exact_sequence \ud835\udc9c :=\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 : \ud835\udc9c) : short_exact_sequence \ud835\udc9c :=\n{ fst := A,\n  snd := A \u229e 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 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is\nan isomorphism to the short exact sequence `0 \u27f6 A\u2081 \u27f6 A\u2081 \u2295 A\u2083 \u27f6 A\u2083 \u27f6 0`,\nwhere the left and right components of the isomorphism are identity maps. -/\nstructure splitting (A : short_exact_sequence \ud835\udc9c) extends A \u2245 (mk_split A.1 A.3) :=\n(fst_eq_id : hom.1 = \ud835\udfd9 A.1)\n(trd_eq_id : hom.3 = \ud835\udfd9 A.3)\n\n/-- A short exact sequence `0 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is *split* if there exist\n`\u03c6 : A\u2082 \u27f6 A\u2081` and `\u03c7 : A\u2083 \u27f6 A\u2082` such that:\n* `f \u226b \u03c6 = \ud835\udfd9 A\u2081`\n* `\u03c7 \u226b g = \ud835\udfd9 A\u2083`\n* `\u03c7 \u226b \u03c6 = 0`\n* `\u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 A\u2082`\n-/\ndef split (A : short_exact_sequence \ud835\udc9c) : Prop :=\n\u2203 (\u03c6 : A.2 \u27f6 A.1) (\u03c7 : A.3 \u27f6 A.2),\n   A.f \u226b \u03c6 = \ud835\udfd9 A.1 \u2227 \u03c7 \u226b A.g = \ud835\udfd9 A.3 \u2227 \u03c7 \u226b \u03c6 = 0 \u2227 \u03c6 \u226b A.f + A.g \u226b \u03c7 = \ud835\udfd9 A.2\n\nlemma mk_split_split (A B : \ud835\udc9c) : (mk_split A B).split :=\n\u27e8biprod.fst, biprod.inr, biprod.inl_fst, biprod.inr_snd, biprod.inr_fst, biprod.total\u27e9\n\nlemma splitting.split {A : short_exact_sequence \ud835\udc9c} (i : splitting A) : A.split :=\nbegin\n  refine \u27e8i.hom.2 \u226b biprod.fst \u226b i.inv.1, i.hom.3 \u226b biprod.inr \u226b i.inv.2, _\u27e9,\n  simp only [category.assoc, \u2190 hom.sq1_assoc, hom.sq2], dsimp,\n  simp only [biprod.inl_fst_assoc, biprod.inr_snd_assoc, category.comp_id, category.assoc,\n    \u2190 comp_fst, \u2190 comp_snd_assoc, \u2190 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, \u2190 hom.sq2_assoc, \u2190 comp_add],\n  simp only [\u2190 category.assoc, \u2190 add_comp, biprod.total,\n    category.comp_id, \u2190 comp_snd, i.to_iso.hom_inv_id], refl,\nend\n\ndef left_split.splitting {A : short_exact_sequence \ud835\udc9c} (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 \ud835\udc9c} (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 \ud835\udc9c) :\n  tfae [A.left_split, A.right_split, A.split, nonempty A.splitting] :=\nbegin\n  tfae_have : 3 \u2192 1, { rintro \u27e8\u03c6, \u03c7, h\u03c6, h\u03c7, h\u03c7\u03c6, H\u27e9, exact \u27e8\u03c6, h\u03c6\u27e9 },\n  tfae_have : 3 \u2192 2, { rintro \u27e8\u03c6, \u03c7, h\u03c6, h\u03c7, h\u03c7\u03c6, H\u27e9, exact \u27e8\u03c7, h\u03c7\u27e9 },\n  tfae_have : 4 \u2192 3, { rintro \u27e8i\u27e9, exact i.split, },\n  tfae_have : 1 \u2192 4, { intro h, exact \u27e8h.splitting\u27e9 },\n  tfae_have : 2 \u2192 4, { intro h, exact \u27e8h.splitting\u27e9 },\n  tfae_finish\nend\n\nend split\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nopen category_theory.preadditive\n\nvariables {\ud835\udc9e} [preadditive \ud835\udc9e] [has_images \ud835\udc9e] [has_kernels \ud835\udc9e]\nvariables (A B : short_exact_sequence \ud835\udc9e)\n\nlocal notation `\u03c0\u2081` := congr_arg _root_.prod.fst\nlocal notation `\u03c0\u2082` := congr_arg _root_.prod.snd\n\nprotected def hom_inj (f : A \u27f6 B) : (A.1 \u27f6 B.1) \u00d7 (A.2 \u27f6 B.2) \u00d7 (A.3 \u27f6 B.3) := \u27e8f.1, f.2, f.3\u27e9\n\nprotected lemma hom_inj_injective : function.injective (short_exact_sequence.hom_inj A B) :=\n\u03bb f g h, let aux := \u03c0\u2082 h in\nby { ext; [have := \u03c0\u2081 h, have := \u03c0\u2081 aux, have := \u03c0\u2082 aux]; exact this, }\n\ninstance : has_add (A \u27f6 B) :=\n{ add := \u03bb 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 \u27f6 B) :=\n{ neg := \u03bb 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 \u27f6 B) :=\n{ sub := \u03bb 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 \u2115 (A \u27f6 B) :=\n{ smul := \u03bb n f,\n  { fst := n \u2022 f.1,\n    snd := n \u2022 f.2,\n    trd := n \u2022 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 \u2124 (A \u27f6 B) :=\n{ smul := \u03bb n f,\n  { fst := n \u2022 f.1,\n    snd := n \u2022 f.2,\n    trd := n \u2022 f.3,\n    sq1' := by rw [zsmul_comp, comp_zsmul, f.sq1],\n    sq2' := by rw [zsmul_comp, comp_zsmul, f.sq2] } }\n\nvariables (\ud835\udc9e)\n\ninstance : preadditive (short_exact_sequence \ud835\udc9e) :=\n{ hom_group := \u03bb A B, (short_exact_sequence.hom_inj_injective A B).add_comm_group _\n  rfl (\u03bb _ _, rfl) (\u03bb _, rfl) (\u03bb _ _, rfl) (\u03bb _ _, rfl) (\u03bb _ _, 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 \ud835\udc9e).additive := {}\ninstance Snd_additive : (Snd \ud835\udc9e).additive := {}\ninstance Trd_additive : (Trd \ud835\udc9e).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 \n    -- data.real.basic\n    -- topology.instances.real\n    -- measure_theory.borel_space\n    -- measure_theory.measure_space\n    substances\n\nuniverse u\nopen set topological_space classical\nlocal attribute [instance] prop_decidable\n\nnamespace ontology\n\n -- Substances have `states`, although the states of simple\n -- substances are trivial.\n \n variables {\u03c9 : ontology} (s : \u03c9.substance)\n include \u03c9\n \n -- The state of a substance at some \n -- possible world is the set of its subsistents existing at the world.\n  def substance.state (w : \u03c9.world) : set \u03c9.entity :=\n  s.up.subsistents \u2229 w.entities\n \n  lemma exists_iff_in_state : \u2200 {w : \u03c9.world} {s : \u03c9.substance}, w \u2208 s.exists \u2194 s.up \u2208 s.state w :=\n   begin\n       intros,\n       constructor; intro h;\n       simp[substance.state, h] at *,\n       exact h,\n   end\n\n  lemma exists_iff_nonempty_state : \u2200 {w : \u03c9.world} {s : \u03c9.substance}, w \u2208 s.exists \u2194 (s.state w).nonempty := \n    begin \n        intros,\n        convert exists_iff_in_state; try{assumption},\n        simp, constructor; intro h, swap,\n            exact nonempty_of_mem h,\n        simp [set.nonempty, substance.state] at h,\n        obtain \u27e8e, se, we\u27e9 := h,\n        have c := entails_of_subsist se we,\n        unfold_coes at c,\n        exact exists_iff_in_state.mp c,\n    end\n\n -- The state equivalence of possible worlds generated by a substance\n def substance.equiv (w\u2081 w\u2082 : \u03c9.world) :=\n    s.state w\u2081 = s.state w\u2082\n \n lemma substance.equiv_sound : equivalence s.equiv :=\n  begin\n    repeat{fsplit},\n        simp [reflexive, substance.equiv],\n        simp [symmetric, substance.equiv],\n            intros x y h,\n            rw h,\n        simp [transitive, substance.equiv],\n            intros x y z h\u2081 h\u2082,\n            rwa \u2190h\u2081 at h\u2082,\n  end\n \n def substance.State_setoid : setoid \u03c9.world :=\n \u27e8s.equiv, s.equiv_sound\u27e9\n\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/states.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.032100708105956687, "lm_q1q2_score": 0.015048511068137576}}
{"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 \u2192String\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 \u2192 Const\n| float: Float \u2192 Const\n| unit: Const\n| pair: Const \u2192 Const \u2192 Const\nderiving BEq\n\ninstance : ToString Const where\n  toString :=\n    let rec go : Const \u2192 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 => \"<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 \u2192 Op \u2192 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 \u2192 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 \u2192 Bool\n| .regionsnil => True\n| .regionscons _ _ => False\n\n\ndef Expr.format : Expr k \u2192 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 \u2983k: OR\u2984: ToFormat (Expr k) where\n  format := Expr.format\n\ninstance : ToString (Expr k) where\n   toString := Format.pretty \u2218 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 \u00d7 q.eval\n\ninstance Kind.bEqEval: (k : Kind) \u2192 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 := \u27e8a, a'\u27e9}, {kind := .pair r s, val := \u27e8b, b'\u27e9 } =>\n      go \u27e8p, a\u27e9 \u27e8r, b\u27e9 && go \u27e8q, a'\u27e9 \u27e8s, b'\u27e9\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 \u301akind\u27e7, 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 \u27e6var.kind\u27e7\nabbrev Env := (v: Var) \u2192 v.kind.eval\n\n\ninstance : Inhabited ((k: Kind) \u2192 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) \u2192 Kind.eval k := default\n  f v.kind\n\n-- truncation of a type that smashes everything into a single equivalence class.\ninductive trunc (\u03b1: Type): \u03b1 \u2192 \u03b1 \u2192 Prop\n| trunc: trunc \u03b1 a a' -- smash everthing.\n\ninstance EquivalenceTrunc : Equivalence (trunc \u03b1) where\n  refl _ := .trunc\n  symm _  := .trunc\n  trans _ _ := .trunc\n\ninstance SetoidTrunc (\u03b1 : Type) : Setoid \u03b1 where\n   r := trunc \u03b1\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 := \"<<error>>\"\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 \u2192 Except ErrorKind \u03b1\nabbrev TopM (\u03b1 : Type) : Type := ReaderT Env Id \u03b1\n\nabbrev Env.set (var: Var) (val: var.kind.eval): Env \u2192 Env\n| env => fun v => if H : v = var then H \u25b8 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 \u03c1 m \u03c1 := fun x => pure x\nabbrev ReaderT.withEnv [Monad m] (f: \u03c1 \u2192 \u03c1) (reader: ReaderT \u03c1 m \u03b1): ReaderT \u03c1 m \u03b1 :=\n  reader \u2218 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 \u27e8name, .unit\u27e9 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 \u2192 TopM \u03b2):\n  (TopM.get \u27e8name, kind\u27e9) >>= k =  fun env => (k (env \u27e8name, kind\u27e9)) env := rfl\n\ndef TopM.set (nv: NamedVal)  (k: TopM \u03b1): TopM \u03b1 :=\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 \u25b8 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 := \u27e8.unit, ()\u27e9\n  regions: List (Val \u2192 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') \u2192 TopM o.retkind.eval\n\n\n-- TODO: consider this design.\n-- partial finitely supported function.\n-- abbrev Semantics := (name: String) \u2192 Option (Semantic name)\n\nabbrev Semantics := OpName \u2192 (o: Op') \u2192 TopM o.retkind.eval\n\ninstance : ToString Op' where\n  toString x := \"(\" ++ toString x.argval ++ \")\" ++\n    \" [\" ++ \"#\" ++ toString x.regions.length ++ \"]\" ++\n    \" {\" ++ toString x.const ++ \"}\" ++ \" \u2192 \" ++ toString x.retkind\n\n@[reducible]\ndef AST.OR.denoteType: OR -> Type\n| .O => TopM NamedVal\n| .Os => TopM NamedVal\n| .R => Val \u2192 TopM Val\n| .Rs => List (Val \u2192 TopM Val) -- TODO: is 'List' here correct?\n\n\ndef AST.Expr.denote {kind: OR}\n (sem: Semantics): Expr kind \u2192 kind.denoteType\n| .opsone o => AST.Expr.denote (kind := .O) sem o\n| .opscons o os => do\n    let retv \u2190 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 \u2190TopM.get arg1\n   let val2 \u2190 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 \u2190 TopM.get arg\n    let op' : Op' :=\n      { argval := \u27e8arg.kind, val\u27e9\n      , regions := rs.denote sem\n      , const := const\n      , retkind := ret.kind }\n    let out \u2190 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 := \u27e8arg.kind, argval\u27e9\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: \u2200 (ma: TopM \u03b1) (k: \u03b1 \u2192 \u03b1 \u2192 TopM \u03b2),\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: \u2200 (ma: TopM \u03b1) (mb: TopM \u03b2) (k: \u03b1 \u2192 \u03b2 \u2192 TopM \u03b3),\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 \u2190TopM.get arg1\n   let val2 \u2190 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 := \u27e8arg.kind, val\u27e9\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    \u2203 argval1, env.get arg1 = argval1 \u2227\n    \u2203 argval2, env.get arg2 = argval2 \u2227\n    outval = { name := retname, kind := .pair arg1.kind arg2.kind, val := \u27e8argval1, argval2 \u27e9} := 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 \u22a2;\n      simp[pure, ReaderT.pure, Except.pure] at SUCCESS \u22a2  ;\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    \u2203 argval, env.get arg = argval \u2227\n    \u2203 (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 \u22a2;\n      simp[ReaderT.get, pure, Except.pure] at SUCCESS \u22a2;\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, \"\u00d7\") :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 \u2192 List Op \u2192 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 \u2192 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 ]\u00d7* ]) => do\n    if ks.isEmpty\n    then `(AST.Kind.unit)\n    else\n      let mut out \u2190 parseKind ks[ks.size - 1]!\n      for k in ks.pop.reverse do\n        let cur \u2190 parseKind k\n        out \u2190 `(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 \u2190 `([dsl_op| $op])\n   let ops_term \u2190 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 \u2190 `([dsl_ops| $op $ops*])\n   match arg with\n   | .none => `(Expr.region Var.unit $ops)\n   | .some arg => do\n      let arg_term \u2190 `([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 \u2190 `([dsl_var| $res])\n      let arg_term \u2190 match arg with\n          | .some arg => `([dsl_var| $arg])\n          | .none => `(AST.Var.unit)\n      let name_term := name\n      let rgns_term \u2190 match rgns with\n        | .none => `(.regionsnil)\n        | .some rgns =>\n           let rgns \u2190 rgns.getElems.mapM (fun stx => `([dsl_region| $stx]))\n           `(AST.Regions.fromList [ $rgns,* ])\n      let const_term \u2190\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 \u2190 `([dsl_var_name| $res])\n    let arg1_term \u2190 `([dsl_var| $arg1 ])\n    let arg2_term \u2190 `([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 \u00d7 nat]\n#reduce eg_kind_int_times_nat\n\ndef eg_kind_int_times_nat_times_nat := [dsl_kind| int \u00d7 nat \u00d7 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 \u00d7 $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 := \u27e8.pair .int .int, (x, y)\u27e9 } => 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 := \u27e8.pair .int .int, (x, y)\u27e9 } => 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 \u00d7 int);\n }]\n#reduce eg_region_sub\n\n\nend Arith\n\nnamespace Scf -- 'structured control flow'\n\ndef repeatM (n: Nat) (f: Val \u2192 TopM Val) : Val \u2192 TopM Val :=\n  n.repeat (f >=> .) pure\n\n\ntheorem repeatM.peel_left: \u2200 (n: Nat) (f: Val \u2192 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 \u2192 Type}\n  [M: Monad m] [LM: LawfulMonad m]\n  {\u03b1 \u03b2 \u03b3 \u03b4: Type}\n  (f: \u03b1 \u2192 m \u03b2) (g: \u03b2 \u2192 m \u03b3) (h: \u03b3 \u2192 m \u03b4) :\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 \u2192 Type}\n  [M: Monad m] [LM: LawfulMonad m]\n  {\u03b1 \u03b2: Type}\n  (f: \u03b1 \u2192 m \u03b2) :\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 \u2192 Type}\n  [M: Monad m] [LM: LawfulMonad m]\n  {\u03b1 \u03b2: Type}\n  (f: \u03b1 \u2192 m \u03b2) :\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 [\u2190peel_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 \u2192 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 [\u2190kleisliRight.assoc, COMMUTES]\n\ntheorem repeatM.commuting_pull_right\n  {f g: Val \u2192 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 \u2192 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 [\u2190kleisliRight.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: \u03b1 \u2192 m \u03b2) (k h : \u03b2 \u2192 m \u03b3) (H: k = h) :\n  f >=> k = f >=> h := by {\n    rw[H];\n}\n\ntheorem repeatM.commuting_compose\n  {f g: Val \u2192 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 [\u2190kleisliRight.assoc _ g _, kleisliRight.assoc _ _ g]\n    rw [commuting_pull_left COMMUTES]\n    rw [\u2190kleisliRight.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 := \u27e8.int, cond\u27e9,\n      regions := [rthen, relse],\n      retkind := .int -- hack: we assume that we always return ints.\n    } => do\n      let rrun := if cond \u2260 0 then rthen else relse\n      let v \u2190 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 \u2190 r Val.unit\n      let w \u2190 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 \u2190 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 := \u27e8.pair .nat .int, \u27e8niters, init\u27e9\u27e9\n    } =>\n      repeatM niters r \u27e8.int, init\u27e9 >=> 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 \u2192 a \u223c 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 \u00d7 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 \u00d7 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 \u00d7 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 \u00d7 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: \u2200 (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 \u2192 Prop\ndef assertion.implies (P Q: assertion T) : Prop := \u2200 (e: T), P e \u2192 Q e\n\n\nnotation P:80 \"->>\" Q:80 => assertion.implies P Q\n\nabbrev assertion.iff (P Q: assertion T) : Prop := P ->> Q \u2227 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 \u2227 Q v\nnotation P:80 \"h\u2227\" 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) => \u2203 (val: v.kind.eval), (e.get v) = val\n\nnotation \"h[\" v:80 \"\u21a6\" val:80 \"]\" => assertion.mapsto v val\nnotation \"hprop(\" p:80 \")\" => assertion.prop p\nnotation \"h[\" v:80 \"\u21a6\" \"?\" \"]\" => assertion.maps v\n-- def hoare_triple_region (P: assertion Env) (r: Expr .R) (Q: assertion (Except ErrorKind NamedVal)) : Prop :=\n--  \u2200 (e: Env) (sem : (o : Op') \u2192 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 \u00d7 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 \u03b1)\n  (maval: \u03b1)\n  (MAVAL: ma = pure maval)\n  (compute: \u03b1 -> m \u03b2) :\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 \u00d7 int) [$(r)];\n    % $(m_out1) = tuple( %$(m) : nat, %$(out1) : int);\n    % $(out2) : int = \"scf.for\" ( %$(m_out1) : nat \u00d7 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 \u00d7 nat);\n    % $(n_plus_m_init) = tuple( %$(n_plus_m) : nat, %$(init) : int);\n    % $(out2) : int = \"scf.for\" ( %$(n_plus_m_init) : nat \u00d7 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 \u2192 (o : Op') \u2192 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) \u2192\n--   (r: AST.Region) \u2192\n--   (arg: Val := Val.unit ) \u2192\n--   (env: Env := Env.empty) \u2192 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? \u2190 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 (\ud835\udc9e : Type u) [category.{v} \ud835\udc9e]\n\n@[ext]\nstructure short_exact_sequence [has_images \ud835\udc9e] [has_zero_morphisms \ud835\udc9e] [has_kernels \ud835\udc9e] :=\n(fst snd trd : \ud835\udc9e)\n(f : fst \u27f6 snd)\n(g : snd \u27f6 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 {\ud835\udc9e} [has_images \ud835\udc9e] [has_zero_morphisms \ud835\udc9e] [has_kernels \ud835\udc9e]\n\n@[simp, reassoc] lemma f_comp_g (A : short_exact_sequence \ud835\udc9e) : A.f \u226b A.g = 0 := A.exact'.w\n\n@[ext]\nstructure hom (A B : short_exact_sequence \ud835\udc9e) :=\n(fst : A.1 \u27f6 B.1)\n(snd : A.2 \u27f6 B.2)\n(trd : A.3 \u27f6 B.3)\n(sq1' : fst \u226b B.f = A.f \u226b snd . obviously)\n(sq2' : snd \u226b B.g = A.g \u226b 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 \ud835\udc9e) := \u27e8hom\u27e9\n\ndef id (A : short_exact_sequence \ud835\udc9e) : A \u27f6 A :=\n{ fst := \ud835\udfd9 _,\n  snd := \ud835\udfd9 _,\n  trd := \ud835\udfd9 _,\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 \ud835\udc9e} (f : A \u27f6 B) (g : B \u27f6 C) : A \u27f6 C :=\n{ fst := f.1 \u226b g.1,\n  snd := f.2 \u226b g.2,\n  trd := f.3 \u226b 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 \ud835\udc9e) :=\n{ id := id,\n  comp := \u03bb 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 \ud835\udc9e)) }\n\n@[simp] lemma id_fst (A : short_exact_sequence \ud835\udc9e) : hom.fst (\ud835\udfd9 A) = \ud835\udfd9 A.1 := rfl\n@[simp] lemma id_snd (A : short_exact_sequence \ud835\udc9e) : hom.snd (\ud835\udfd9 A) = \ud835\udfd9 A.2 := rfl\n@[simp] lemma id_trd (A : short_exact_sequence \ud835\udc9e) : hom.trd (\ud835\udfd9 A) = \ud835\udfd9 A.3 := rfl\n\nvariables {A B C : short_exact_sequence \ud835\udc9e} (f : A \u27f6 B) (g : B \u27f6 C)\n\n@[simp, reassoc] lemma comp_fst : (f \u226b g).1 = f.1 \u226b g.1 := rfl\n@[simp, reassoc] lemma comp_snd : (f \u226b g).2 = f.2 \u226b g.2 := rfl\n@[simp, reassoc] lemma comp_trd : (f \u226b g).3 = f.3 \u226b g.3 := rfl\n\nvariables (\ud835\udc9e)\n\n@[simps] def Fst : short_exact_sequence \ud835\udc9e \u2964 \ud835\udc9e :=\n{ obj := fst, map := \u03bb A B f, f.1 }\n\n@[simps] def Snd : short_exact_sequence \ud835\udc9e \u2964 \ud835\udc9e :=\n{ obj := snd, map := \u03bb A B f, f.2 }\n\n@[simps] def Trd : short_exact_sequence \ud835\udc9e \u2964 \ud835\udc9e :=\n{ obj := trd, map := \u03bb A B f, f.3 }\n\n@[simps] def f_nat : Fst \ud835\udc9e \u27f6 Snd \ud835\udc9e :=\n{ app := \u03bb A, A.f,\n  naturality' := \u03bb A B f, f.sq1 }\n\n@[simps] def g_nat : Snd \ud835\udc9e \u27f6 Trd \ud835\udc9e :=\n{ app := \u03bb A, A.g,\n  naturality' := \u03bb A B f, f.sq2 }\n\ninstance : has_zero_morphisms (short_exact_sequence \ud835\udc9e) :=\n{ has_zero := \u03bb A B, \u27e8{ fst := 0, snd := 0, trd := 0 }\u27e9,\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 \u27f6 B).1 = 0 := rfl\n\n@[simp] lemma hom_zero_snd : (0 : A \u27f6 B).2 = 0 := rfl\n\n@[simp] lemma hom_zero_trd : (0 : A \u27f6 B).3 = 0 := rfl\n\nvariables {\ud835\udc9e}\n\nprotected def functor (A : short_exact_sequence \ud835\udc9e) : fin 3 \u2964 \ud835\udc9e :=\nfin3_functor_mk ![A.1, A.2, A.3] A.f A.g\n\ndef functor_map {A B : short_exact_sequence \ud835\udc9e} (f : A \u27f6 B) :\n  \u03a0 i, A.functor.obj i \u27f6 B.functor.obj i\n| \u27e80,h\u27e9 := f.1\n| \u27e81,h\u27e9 := f.2\n| \u27e82,h\u27e9 := f.3\n| \u27e8i+3,hi\u27e9 := 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 \ud835\udc9e} (f : A \u27f6 B) :\n  \u2200 (i j : fin 3) (hij : i \u2264 j),\n    functor_map f i \u226b B.functor.map hij.hom = A.functor.map hij.hom \u226b functor_map f j\n| \u27e80,hi\u27e9 \u27e80,hj\u27e9 hij := by aux_tac\n| \u27e81,hi\u27e9 \u27e81,hj\u27e9 hij := by aux_tac\n| \u27e82,hi\u27e9 \u27e82,hj\u27e9 hij := by aux_tac\n| \u27e80,hi\u27e9 \u27e81,hj\u27e9 hij := f.sq1\n| \u27e81,hi\u27e9 \u27e82,hj\u27e9 hij := f.sq2\n| \u27e8i+3,hi\u27e9 _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+3,hj\u27e9 _ := by { exfalso, revert hj, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e80,hi\u27e9 \u27e82,hj\u27e9 hij :=\nbegin\n  have h01 : (0 : fin 3) \u27f6 1 := hom_of_le dec_trivial,\n  have h12 : (1 : fin 3) \u27f6 2 := hom_of_le dec_trivial,\n  calc functor_map f \u27e80, hi\u27e9 \u226b B.functor.map hij.hom\n      = functor_map f \u27e80, hi\u27e9 \u226b B.functor.map h01 \u226b B.functor.map h12 : _\n  ... = (functor_map f \u27e80, hi\u27e9 \u226b B.functor.map h01) \u226b B.functor.map h12 : by rw category.assoc\n  ... = (A.functor.map h01 \u226b functor_map f _) \u226b B.functor.map h12 : _\n  ... = A.functor.map h01 \u226b functor_map f _ \u226b B.functor.map h12 : category.assoc _ _ _\n  ... = A.functor.map h01 \u226b A.functor.map h12 \u226b functor_map f _ : _\n  ... = A.functor.map hij.hom \u226b functor_map f \u27e82, hj\u27e9 : _,\n  { rw [\u2190 functor.map_comp], congr, },\n  { congr' 1, exact f.sq1 },\n  { congr' 1, exact f.sq2 },\n  { rw [\u2190 functor.map_comp_assoc], congr, },\nend\n\n@[simps] def Functor : short_exact_sequence \ud835\udc9e \u2964 fin 3 \u2964 \ud835\udc9e :=\n{ obj := short_exact_sequence.functor,\n  map := \u03bb A B f,\n  { app := functor_map f,\n    naturality' := \u03bb i j hij, (functor_map_naturality f i j hij.le).symm },\n  map_id' := \u03bb A, by { ext i, fin_cases i; refl },\n  map_comp' := \u03bb A B C f g, by { ext i, fin_cases i; refl } }\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nvariables {\ud835\udc9e} [abelian \ud835\udc9e]\nvariables {A B C : short_exact_sequence \ud835\udc9e} (f : A \u27f6 B) (g : B \u27f6 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 \ud835\udc9e _ _\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 \u27e8\u27e8inv f.1, inv f.2, inv f.3, _, _\u27e9, _, _\u27e9,\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\u2081 : A.1 \u2245 B.1) (f\u2082 : A.2 \u2245 B.2) (f\u2083 : A.3 \u2245 B.3)\n  (sq1 : f\u2081.hom \u226b B.f = A.f \u226b f\u2082.hom) (sq2 : f\u2082.hom \u226b B.g = A.g \u226b f\u2083.hom) :\n  A \u2245 B :=\n{ hom := \u27e8f\u2081.hom, f\u2082.hom, f\u2083.hom, sq1, sq2\u27e9,\n  inv :=\n  begin\n    refine \u27e8f\u2081.inv, f\u2082.inv, f\u2083.inv, _, _\u27e9; dsimp,\n    rw [iso.inv_comp_eq, \u2190 category.assoc, iso.eq_comp_inv, sq1],\n    rw [iso.inv_comp_eq, \u2190 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\u2081 : A.1 \u2245 B.1) (f\u2082 : A.2 \u27f6 B.2) (f\u2083 : A.3 \u2245 B.3)\n  (sq1 : f\u2081.hom \u226b B.f = A.f \u226b f\u2082) (sq2 : f\u2082 \u226b B.g = A.g \u226b f\u2083.hom) :\n  A \u2245 B :=\nlet F : A \u27f6 B := \u27e8f\u2081.hom, f\u2082, f\u2083.hom, sq1, sq2\u27e9 in\n{ hom := F,\n  inv :=\n  begin\n    haveI : is_iso F.2 := snd_is_iso _ infer_instance infer_instance,\n    refine \u27e8f\u2081.inv, inv F.2, f\u2083.inv, _, _\u27e9; dsimp,\n    rw [iso.inv_comp_eq, \u2190 category.assoc, is_iso.eq_comp_inv, sq1],\n    rw [is_iso.inv_comp_eq, \u2190 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 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is *left split*\nif there exists a morphism `\u03c6 : A\u2082 \u27f6 A\u2081` such that `f \u226b \u03c6 = \ud835\udfd9 A\u2081`. -/\ndef left_split (A : short_exact_sequence \ud835\udc9e) : Prop :=\n\u2203 \u03c6 : A.2 \u27f6 A.1, A.f \u226b \u03c6 = \ud835\udfd9 A.1\n\n/-- A short exact sequence `0 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is *right split*\nif there exists a morphism `\u03c6 : A\u2082 \u27f6 A\u2081` such that `f \u226b \u03c6 = \ud835\udfd9 A\u2081`. -/\ndef right_split (A : short_exact_sequence \ud835\udc9e) : Prop :=\n\u2203 \u03c7 : A.3 \u27f6 A.2, \u03c7 \u226b A.g = \ud835\udfd9 A.3\n\nvariables {\ud835\udc9c : Type*} [category \ud835\udc9c] [abelian \ud835\udc9c]\n\nlemma exact_of_split {A B C : \ud835\udc9c} (f : A \u27f6 B) (g : B \u27f6 C) (\u03c7 : C \u27f6 B) (\u03c6 : B \u27f6 A)\n  (hfg : f \u226b g = 0) (H : \u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 B) : exact f g :=\n{ w := hfg,\n  epi :=\n  begin\n    let \u03c8 : (kernel_subobject g : \ud835\udc9c) \u27f6 image_subobject f :=\n      subobject.arrow _ \u226b \u03c6 \u226b factor_thru_image_subobject f,\n    suffices : \u03c8 \u226b image_to_kernel f g hfg = \ud835\udfd9 _,\n    { convert epi_of_epi \u03c8 _, rw this, apply_instance },\n    rw \u2190 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 \u226b \u03c6 \u226b f\n        = (kernel_subobject g).arrow \u226b \ud835\udfd9 B : _\n    ... = (kernel_subobject g).arrow        : category.comp_id _,\n    rw [\u2190 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 : \ud835\udc9c) : exact (biprod.inl : A \u27f6 A \u229e B) biprod.snd :=\nexact_of_split _ _ biprod.inr biprod.fst biprod.inl_snd biprod.total\n\ndef mk_of_split {A B C : \ud835\udc9c} (f : A \u27f6 B) (g : B \u27f6 C) (\u03c6 : B \u27f6 A) (\u03c7 : C \u27f6 B)\n  (hfg : f \u226b g = 0) (h\u03c6 : f \u226b \u03c6 = \ud835\udfd9 A) (h\u03c7 : \u03c7 \u226b g = \ud835\udfd9 C) (H : \u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 B) :\n  short_exact_sequence \ud835\udc9c :=\n{ fst := A,\n  snd := B,\n  trd := C,\n  f := f,\n  g := g,\n  mono' := by { haveI : mono (f \u226b \u03c6), { rw h\u03c6, apply_instance }, exact mono_of_mono f \u03c6, },\n  epi' := by { haveI : epi (\u03c7 \u226b g), { rw h\u03c7, apply_instance }, exact epi_of_epi \u03c7 g, },\n  exact' := exact_of_split f g \u03c7 \u03c6 hfg H }\n\ndef mk_of_split' {A B C : \ud835\udc9c} (f : A \u27f6 B) (g : B \u27f6 C)\n  (H : \u2203 (\u03c6 : B \u27f6 A) (\u03c7 : C \u27f6 B), f \u226b g = 0 \u2227 f \u226b \u03c6 = \ud835\udfd9 A \u2227 \u03c7 \u226b g = \ud835\udfd9 C \u2227 \u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 B) :\n  short_exact_sequence \ud835\udc9c :=\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 : \ud835\udc9c) : short_exact_sequence \ud835\udc9c :=\n{ fst := A,\n  snd := A \u229e 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 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is\nan isomorphism to the short exact sequence `0 \u27f6 A\u2081 \u27f6 A\u2081 \u2295 A\u2083 \u27f6 A\u2083 \u27f6 0`,\nwhere the left and right components of the isomorphism are identity maps. -/\nstructure splitting (A : short_exact_sequence \ud835\udc9c) extends A \u2245 (mk_split A.1 A.3) :=\n(fst_eq_id : hom.1 = \ud835\udfd9 A.1)\n(trd_eq_id : hom.3 = \ud835\udfd9 A.3)\n\n/-- A short exact sequence `0 \u27f6 A\u2081 -f\u27f6 A\u2082 -g\u27f6 A\u2083 \u27f6 0` is *split* if there exist\n`\u03c6 : A\u2082 \u27f6 A\u2081` and `\u03c7 : A\u2083 \u27f6 A\u2082` such that:\n* `f \u226b \u03c6 = \ud835\udfd9 A\u2081`\n* `\u03c7 \u226b g = \ud835\udfd9 A\u2083`\n* `\u03c7 \u226b \u03c6 = 0`\n* `\u03c6 \u226b f + g \u226b \u03c7 = \ud835\udfd9 A\u2082`\n-/\ndef split (A : short_exact_sequence \ud835\udc9c) : Prop :=\n\u2203 (\u03c6 : A.2 \u27f6 A.1) (\u03c7 : A.3 \u27f6 A.2),\n   A.f \u226b \u03c6 = \ud835\udfd9 A.1 \u2227 \u03c7 \u226b A.g = \ud835\udfd9 A.3 \u2227 \u03c7 \u226b \u03c6 = 0 \u2227 \u03c6 \u226b A.f + A.g \u226b \u03c7 = \ud835\udfd9 A.2\n\nlemma mk_split_split (A B : \ud835\udc9c) : (mk_split A B).split :=\n\u27e8biprod.fst, biprod.inr, biprod.inl_fst, biprod.inr_snd, biprod.inr_fst, biprod.total\u27e9\n\nlemma splitting.split {A : short_exact_sequence \ud835\udc9c} (i : splitting A) : A.split :=\nbegin\n  refine \u27e8i.hom.2 \u226b biprod.fst \u226b i.inv.1, i.hom.3 \u226b biprod.inr \u226b i.inv.2, _\u27e9,\n  simp only [category.assoc, \u2190 hom.sq1_assoc, hom.sq2], dsimp,\n  simp only [biprod.inl_fst_assoc, biprod.inr_snd_assoc, category.comp_id, category.assoc,\n    \u2190 comp_fst, \u2190 comp_snd_assoc, \u2190 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, \u2190 hom.sq2_assoc, \u2190 comp_add],\n  simp only [\u2190 category.assoc, \u2190 add_comp, biprod.total,\n    category.comp_id, \u2190 comp_snd, i.to_iso.hom_inv_id], refl,\nend\n\ndef left_split.splitting {A : short_exact_sequence \ud835\udc9c} (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 \ud835\udc9c} (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 \ud835\udc9c) :\n  tfae [A.left_split, A.right_split, A.split, nonempty A.splitting] :=\nbegin\n  tfae_have : 3 \u2192 1, { rintro \u27e8\u03c6, \u03c7, h\u03c6, h\u03c7, h\u03c7\u03c6, H\u27e9, exact \u27e8\u03c6, h\u03c6\u27e9 },\n  tfae_have : 3 \u2192 2, { rintro \u27e8\u03c6, \u03c7, h\u03c6, h\u03c7, h\u03c7\u03c6, H\u27e9, exact \u27e8\u03c7, h\u03c7\u27e9 },\n  tfae_have : 4 \u2192 3, { rintro \u27e8i\u27e9, exact i.split, },\n  tfae_have : 1 \u2192 4, { intro h, exact \u27e8h.splitting\u27e9 },\n  tfae_have : 2 \u2192 4, { intro h, exact \u27e8h.splitting\u27e9 },\n  tfae_finish\nend\n\nend split\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nopen category_theory.preadditive\n\nvariables {\ud835\udc9e} [preadditive \ud835\udc9e] [has_images \ud835\udc9e] [has_kernels \ud835\udc9e]\nvariables (A B : short_exact_sequence \ud835\udc9e)\n\nlocal notation `\u03c0\u2081` := congr_arg _root_.prod.fst\nlocal notation `\u03c0\u2082` := congr_arg _root_.prod.snd\n\nprotected def hom_inj (f : A \u27f6 B) : (A.1 \u27f6 B.1) \u00d7 (A.2 \u27f6 B.2) \u00d7 (A.3 \u27f6 B.3) := \u27e8f.1, f.2, f.3\u27e9\n\nprotected lemma hom_inj_injective : function.injective (short_exact_sequence.hom_inj A B) :=\n\u03bb f g h, let aux := \u03c0\u2082 h in\nby { ext; [have := \u03c0\u2081 h, have := \u03c0\u2081 aux, have := \u03c0\u2082 aux]; exact this, }\n\ninstance : has_add (A \u27f6 B) :=\n{ add := \u03bb 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 \u27f6 B) :=\n{ neg := \u03bb 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 \u27f6 B) :=\n{ sub := \u03bb 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 \u2115 (A \u27f6 B) :=\n{ smul := \u03bb n f,\n  { fst := n \u2022 f.1,\n    snd := n \u2022 f.2,\n    trd := n \u2022 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 \u2124 (A \u27f6 B) :=\n{ smul := \u03bb n f,\n  { fst := n \u2022 f.1,\n    snd := n \u2022 f.2,\n    trd := n \u2022 f.3,\n    sq1' := by rw [zsmul_comp, comp_zsmul, f.sq1],\n    sq2' := by rw [zsmul_comp, comp_zsmul, f.sq2] } }\n\nvariables (\ud835\udc9e)\n\ninstance : preadditive (short_exact_sequence \ud835\udc9e) :=\n{ hom_group := \u03bb A B, (short_exact_sequence.hom_inj_injective A B).add_comm_group _\n  rfl (\u03bb _ _, rfl) (\u03bb _, rfl) (\u03bb _ _, rfl) (\u03bb _ _, rfl) (\u03bb _ _, 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 \ud835\udc9e).additive := {}\ninstance Snd_additive : (Snd \ud835\udc9e).additive := {}\ninstance Trd_additive : (Trd \ud835\udc9e).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 ` \u2218 `:80 g:80 := g \u226b 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 \u27f6 X) : Prop := hep 0 j\n\n/-\n\n* A cofibration in Top is an embedding. [Str\u00f8m, Note on cofibrations,\n  Theorem 1.] Proof: Suppose j : A \u2192 X is a cofibration. Form the\n  mapping cylinder Z as the pushout shown below, with induced map\n  k : Z \u2192 IX.\n\n      j\n    A \u2192 X = X\n  i\u2080\u2193   \u2193   \u2193i\u2080\n   IA \u2192 Z \u2192 IX \u2192 Z\n  i\u2081\u2191   \u2191   \u2191i\u2081\n    A = A \u2192 X\n          j\n\n  By the homotopy extension property, we can find a map r from IX back\n  to Z. So Z \u2192 X is the inclusion of a retract, hence in particular an\n  embedding. The map i\u2080 : A \u2192 IA has closed image, so IA \u2192 Z is a\n  homeomorphism onto its image away from the image of i\u2080. Thus the\n  composition\n\n      i\u2081\n    A \u2192 IA \u2192 Z \u2192 IX\n\n  is an embedding; but it equals i\u2081 \u2218 j : A \u2192 IX, so j : A \u2192 X is an\n  embedding as well.\n\n-/\n\nvariables {A X : Top} {j : A \u27f6 X}\nlocal notation `i` := i.{0}\n\nlemma embedding_i {\u03b5} : embedding (i \u03b5 @> A) :=\nembedding_of_embedding_comp (p @> A) embedding_id\n\nlemma closed_i {\u03b5} : is_closed (set.range (i \u03b5 @> A)) :=\nhave is_closed {p : Top.prod A I01 | p.snd \u2208 ({I01_of_endpoint \u03b5} : 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 (\u2203 a', (a', _) = (a, t)) \u2194 _,\n  simpa using eq_comm\nend\n\nlemma disjoint_i\u2080_i\u2081 : set.range (i 0 @> A) \u2229 set.range (i 1 @> A) = \u2205 :=\nbegin\n  apply set.eq_empty_of_subset_empty, intros p hp,\n  cases p with a t, rcases hp with \u27e8\u27e8_, hp\u2080\u27e9, \u27e8_, hp\u2081\u27e9\u27e9,\n  have hp\u2080' : 0 = t := congr_arg prod.snd hp\u2080,\n  have hp\u2081' : 1 = t := congr_arg prod.snd hp\u2081,\n  have : (0 : I01) = 1 := hp\u2080'.trans hp\u2081'.symm,\n  exact absurd (congr_arg subtype.val this)\n    (show \u00ac(0 : \u211d) = 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 \u27f6 I.obj X :=\n      po.is_pushout.induced (I &> j) (i 0 @> X) ((i 0).naturality j).symm,\n    \u27e8r, hr\u2080, hr\u2081\u27e9 := h Z po.map\u2081 po.map\u2080 po.is_pushout.commutes.symm in\nhave _ := hr\u2080.symm,\nhave hr : r \u2218 k = \ud835\udfd9 _, by apply po.is_pushout.uniqueness; { rw \u2190assoc, 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\u2080 \u2218 i 1 @> A), from\n  comp_embedding_of_embedding_of_disjoint\n    po.is_pushout (or.inl closed_i) embedding_i disjoint_i\u2080_i\u2081,\nhave embedding (k \u2218 (po.map\u2080 \u2218 i 1 @> A)), from e_z_ix.comp e_a_z,\nhave embedding (i 1 @> X \u2218 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 \u2194 (pair.mk X (range j)).cofibered :=\nlet j' := Top.factor_through_incl j (range j) (subset.refl _) in\nshow hep 0 j \u2194 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 \u2194 embedding j \u2227 (pair.mk X (range j)).cofibered :=\niff.intro\n  (assume h,\n    have e : embedding j := embedding_of_cofibration h,\n    \u27e8e, (cofibration_iff_cofibered_of_embedding e).mp h\u27e9)\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' : \u2203 Po : pushout (\u2202I &> j) (ii @> A),\n  cofibration (Po.is_pushout.induced (ii @> X) (I &> j) (ii.naturality _)) \u2227\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 (\u2202I &> j) (ii @> A)\n  ((\u2202I.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\u27e8\u27e8(P \u2297 I_01).subspace, _, _, po'\u27e9,\n begin\n   change cofibration ind \u2227 is_closed (range ind), rw this,\n   refine \u27e8prod_I_01_cofibered P ha (cofibration_iff_cofibered.mp hj).2, _\u27e9,\n   convert @pair.prod.is_closed P I_01 ha I_01.is_closed using 1,\n   apply subtype.range_val\n end\u27e9\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": "/-\nCopyright (c) 2021 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport data.int.basic\nimport tactic.aesop.percent\nimport tactic.aesop.rule\nimport tactic.aesop.rule_builder\nimport tactic.aesop.util\n\nnamespace tactic\nnamespace aesop\n\nopen lean\nopen lean.parser\nopen interactive (with_desc)\nopen interactive.types (list_of brackets)\n\n@[derive has_reflect]\ninductive builder_clause\n| apply\n| simp_lemma\n| tactic\n\nnamespace builder_clause\n\nmeta def args_parser : lean.parser builder_clause :=\nwith_desc \"apply | simp_lemma | tactic\" $ do\n  i \u2190 ident,\n  match i with\n  | `apply := pure builder_clause.apply\n  | `simp_lemma := pure builder_clause.simp_lemma\n  | `tactic := pure builder_clause.tactic\n  | _ := fail $ format! \"Unknown builder: {i}\"\n  end\n\nmeta def to_rule_builder : builder_clause \u2192 rule_builder\n| apply := rule_builder.apply\n| simp_lemma := rule_builder.normalization_simp_lemma\n| tactic := rule_builder.tac\n\nend builder_clause\n\n@[derive has_reflect]\nstructure safety_clause :=\n(to_safety : safety)\n\nnamespace safety_clause\n\nprotected meta def safe_args_parser : lean.parser safety_clause :=\npure \u27e8safety.safe\u27e9\n\nprotected meta def almost_safe_args_parser : lean.parser safety_clause :=\npure \u27e8safety.almost_safe\u27e9\n\nend safety_clause\n\n@[derive has_reflect]\ninductive rule_clause\n| builder (c : builder_clause)\n| safety (c : safety_clause)\n\nmeta def clause_parser {\u03b1}\n  (simple_clauses : name_map \u03b1)\n  (clauses : name_map (lean.parser \u03b1)) :\n  lean.parser \u03b1 :=\nwith_desc \"clause\" $\n(do\n  i \u2190 ident,\n  match simple_clauses.find i with\n  | some v := pure v\n  | none := failed\n  end)\n<|>\n(brackets \"(\" \")\" $ do\n  i \u2190 ident,\n  match clauses.find i with\n  | some arg_parser := arg_parser\n  | none := fail $ format! \"Unknown clause: {i}\"\n  end)\n\nmeta def simple_rule_clauses : name_map rule_clause :=\nnative.rb_map.of_list\n  [ (`safe, rule_clause.safety \u27e8safety.safe\u27e9),\n    (`almost_safe, rule_clause.safety \u27e8safety.almost_safe\u27e9) ]\n\nmeta def rule_clauses : name_map (lean.parser rule_clause) :=\nnative.rb_map.of_list\n  [ (`builder, rule_clause.builder <$> builder_clause.args_parser),\n    (`safe, rule_clause.safety <$> safety_clause.safe_args_parser),\n    (`almost_safe, rule_clause.safety <$> safety_clause.almost_safe_args_parser) ]\n\nnamespace rule_clause\n\nmeta def parser : lean.parser rule_clause :=\nclause_parser simple_rule_clauses rule_clauses\n\nend rule_clause\n\n@[derive has_reflect]\nstructure normalization_rule_config :=\n(penalty : option \u2124 := none)\n(builder : option builder_clause := none)\n\nnamespace normalization_rule_config\n\nmeta def add_clause (conf : normalization_rule_config) :\n  rule_clause \u2192 exceptional normalization_rule_config\n| (rule_clause.builder c) :=\n  if conf.builder.is_some\n    then exceptional.fail \"Duplicate builder clause not allowed.\"\n    else pure { builder := some c, ..conf }\n| (rule_clause.safety c) := exceptional.fail\n  \"Safety clause not allowed for normalization rules.\"\n\nmeta def add_clauses (clauses : list rule_clause)\n  (conf : normalization_rule_config) : exceptional normalization_rule_config :=\nclauses.mfoldl add_clause conf\n\nmeta def parser : lean.parser normalization_rule_config :=\nwith_desc \"penalty (clause)...\" $ do\n  penalty \u2190 optional small_int,\n  clauses \u2190 many rule_clause.parser,\n  let init : normalization_rule_config := { penalty := penalty },\n  init.add_clauses clauses\n\nend normalization_rule_config\n\nmeta def normalization_declaration_to_rule (decl : name)\n  (conf : normalization_rule_config) : tactic rule_set_member := do\n  env \u2190 get_env,\n  d \u2190 env.get decl,\n  let builder :=\n    (builder_clause.to_rule_builder <$> conf.builder).get_or_else\n      rule_builder.normalization_default,\n  r \u2190 builder d,\n  match r with\n  | rule_builder_output.rule r imode :=\n    pure $ rule_set_member.normalization_rule\n      { penalty := conf.penalty.get_or_else 0, ..r }\n      imode\n  | rule_builder_output.simp_lemmas s := do\n    when conf.penalty.is_some $ fail!\n      \"Penalty annotation is not allowed for norm equations (only for norm tactics).\",\n    pure $ rule_set_member.normalization_simp_lemmas s\n  end\n\n@[derive has_reflect]\nstructure safe_rule_config :=\n(penalty : option \u2124 := none)\n(builder : option builder_clause := none)\n(safety : option safety_clause := none)\n\nnamespace safe_rule_config\n\nmeta def add_clause (conf : safe_rule_config) :\n  rule_clause \u2192 exceptional safe_rule_config\n| (rule_clause.builder c) :=\n  if conf.builder.is_some\n    then exceptional.fail \"Duplicate builder clause not allowed.\"\n    else pure { builder := c, ..conf }\n| (rule_clause.safety c) :=\n  if conf.safety.is_some\n    then exceptional.fail \"Duplicate safety clause not allowed.\"\n    else pure { safety := c, ..conf }\n\nmeta def add_clauses (clauses : list rule_clause)\n  (conf : safe_rule_config) : exceptional safe_rule_config :=\nclauses.mfoldl add_clause conf\n\nmeta def parser : lean.parser safe_rule_config :=\nwith_desc \"penalty (clause)...\" $ do\n  penalty \u2190 optional small_int,\n  clauses \u2190 many rule_clause.parser,\n  let init : safe_rule_config := { penalty := penalty },\n  init.add_clauses clauses\n\nend safe_rule_config\n\nmeta def safe_declaration_to_rule (decl : name) (conf : safe_rule_config) :\n  tactic rule_set_member := do\n  env \u2190 get_env,\n  d \u2190 env.get decl,\n  let penalty := conf.penalty.get_or_else 0,\n  let safety :=\n    (safety_clause.to_safety <$> conf.safety).get_or_else safety.safe,\n  let builder :=\n    (builder_clause.to_rule_builder <$> conf.builder).get_or_else\n      rule_builder.safe_default,\n  r \u2190 builder d,\n  match r with\n  | rule_builder_output.rule r imode :=\n    pure $ rule_set_member.safe_rule\n      { penalty := penalty,\n        safety := safety,\n        ..r }\n      imode\n  | rule_builder_output.simp_lemmas _ :=\n    fail! \"aesop/safe_declaration_to_rule: internal error: unexpected rule builder output\"\n  end\n\n@[derive has_reflect]\nstructure unsafe_rule_config :=\n(success_probability : percent)\n(builder : option builder_clause := none)\n\nnamespace unsafe_rule_config\n\nmeta def add_clause (conf : unsafe_rule_config) :\n  rule_clause \u2192 exceptional unsafe_rule_config\n| (rule_clause.builder c) :=\n  if conf.builder.is_some\n    then exceptional.fail \"Duplicate builder clause not allowed.\"\n    else pure { builder := some c, ..conf }\n| (rule_clause.safety c) := exceptional.fail\n  \"Safety clause not allowed for unsafe rules.\"\n\nmeta def add_clauses (clauses : list rule_clause)\n  (conf : unsafe_rule_config) : exceptional unsafe_rule_config :=\nclauses.mfoldl add_clause conf\n\nmeta def parser : lean.parser unsafe_rule_config :=\nwith_desc \"probability (clause)...\" $ do\n  success_probability \u2190 percent.parser,\n  clauses \u2190 many rule_clause.parser,\n  let init : unsafe_rule_config := { success_probability := success_probability },\n  init.add_clauses clauses\n\nend unsafe_rule_config\n\nmeta def unsafe_declaration_to_rule (decl : name) (conf : unsafe_rule_config) :\n  tactic rule_set_member := do\n  env \u2190 get_env,\n  d \u2190 env.get decl,\n  let builder :=\n    (builder_clause.to_rule_builder <$> conf.builder).get_or_else\n      rule_builder.unsafe_default,\n  r \u2190 builder d,\n  match r with\n  | rule_builder_output.rule r imode :=\n    pure $ rule_set_member.unsafe_rule\n      { success_probability := conf.success_probability, ..r }\n      imode\n  | rule_builder_output.simp_lemmas _ :=\n    fail! \"aesop/unsafe_declaration_to_rule: internal error: unexpected rule builder output\"\n  end\n\n/-! ## Attribute -/\n\n@[derive has_reflect]\ninductive rule_config : Type\n| normalization (c : normalization_rule_config)\n| unsafe (c : unsafe_rule_config)\n| safe (c : safe_rule_config)\n\nmeta def declaration_to_rule (decl : name) :\n  rule_config \u2192 tactic rule_set_member\n| (rule_config.normalization c) := normalization_declaration_to_rule decl c\n| (rule_config.unsafe c) := unsafe_declaration_to_rule decl c\n| (rule_config.safe c) := safe_declaration_to_rule decl c\n\nmeta def declarations_to_rule_set (decls : list (name \u00d7 rule_config)) :\n  tactic rule_set := do\n  rs \u2190 rule_set.from_list <$> decls.mmap (function.uncurry declaration_to_rule),\n  default_simp_lemmas \u2190 simp_lemmas.mk_default,\n  let rs :=\n    { normalization_simp_lemmas :=\n        rs.normalization_simp_lemmas.join default_simp_lemmas,\n      ..rs },\n  pure rs\n\nmeta def attr_config_parser : lean.parser rule_config :=\nwith_desc \"[norm | safe | unsafe] rule_config\" $ do\n  rule_type \u2190 optional ident,\n  match rule_type with\n  | some `norm   := rule_config.normalization <$> normalization_rule_config.parser\n  | some `safe   := rule_config.safe <$> safe_rule_config.parser\n  | some `unsafe := rule_config.unsafe <$> unsafe_rule_config.parser\n  | none         := rule_config.unsafe <$> unsafe_rule_config.parser\n  | some n       := fail $ format! \"Unknown aesop attribute type: {n}\"\n  end\n\n@[user_attribute]\nmeta def attr : user_attribute name_set rule_config :=\n{ name := `aesop,\n  descr := \"Registers a definition as a rule for the aesop tactic.\",\n  cache_cfg := {\n    mk_cache := pure \u2218 name_set.of_list,\n    dependencies := [] },\n  parser := attr_config_parser }\n\nmeta def attr_declarations_to_rule_set (decls : name_set) : tactic rule_set := do\n  rs \u2190 decls.to_list.mmap $ \u03bb decl, do {\n    config \u2190 attr.get_param decl,\n    pure (decl, config) },\n  declarations_to_rule_set rs\n\nmeta def registered_rule_set : tactic rule_set :=\nattr.get_cache >>= attr_declarations_to_rule_set\n\n/-! ## Tactic Configuration -/\n\n@[derive has_reflect]\ninductive config_clause\n| additional_rules (rs : list (name \u00d7 rule_config))\n\nmeta def rule_parser {\u03b1} (p : lean.parser \u03b1) : lean.parser (name \u00d7 \u03b1) :=\nprod.mk <$> ident <*> p\n\nmeta def rules_parser {\u03b1} (p : lean.parser \u03b1) : lean.parser (list (name \u00d7 \u03b1)) :=\nlist_of (rule_parser p)\n\nmeta def simple_config_clauses : name_map config_clause :=\nnative.rb_map.mk _ _\n\nmeta def config_clauses : name_map (lean.parser config_clause) :=\nnative.rb_map.of_list\n  [ (`unsafe,\n      config_clause.additional_rules <$>\n        rules_parser (rule_config.unsafe <$> unsafe_rule_config.parser)),\n    (`safe,\n      config_clause.additional_rules <$>\n        rules_parser (rule_config.safe <$> safe_rule_config.parser)),\n    (`norm,\n      config_clause.additional_rules <$>\n        rules_parser (rule_config.normalization <$> normalization_rule_config.parser)) ]\n\nnamespace config_clause\n\nmeta def parser : lean.parser config_clause :=\nwith_desc\n  \"((unsafe [id probability clause*, ...]) | (safe [id penalty clause*, ...]) | (norm [id penalty clause*, ...]))\" $\n  clause_parser simple_config_clauses config_clauses\n\nend config_clause\n\n@[derive has_reflect]\nmeta structure config :=\n(additional_rules : list (name \u00d7 rule_config) := [])\n\nnamespace config\n\nmeta def add_clause (conf : config) : config_clause \u2192 config\n| (config_clause.additional_rules rs) :=\n  { additional_rules := conf.additional_rules ++ rs ..conf }\n\nmeta def of_config_clauses (clauses : list config_clause) : config :=\nclauses.foldl add_clause {}\n\nmeta def parser : lean.parser config :=\nof_config_clauses <$> many config_clause.parser\n\nmeta def rule_set (conf : config) : tactic rule_set := do\n  default_rules \u2190 registered_rule_set,\n  additional_rules \u2190 declarations_to_rule_set conf.additional_rules,\n  pure $ default_rules.merge additional_rules\n\nend config\n\nend aesop\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/aesop/config.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.048857784161913866, "lm_q1q2_score": 0.015016831648436941}}
{"text": "import automation.model \nimport automation.rpo_fst_tactic\nimport Architectural.proofObligations\n\nopen LANG PORTS \nlocal infix ` OR `:50 := LANG.disj \nlocal infix ` & `:50 := LANG.conj \n\nmeta def delegation : list (expr \u00d7 expr) := [\n    (`(fault_armDeactivated_armController), `(fault_lockingSwitchPosition_LACU)),\n    (`(fault_operatorControlLever_LACU), `(fault_operatorControlLever_LAAP)),\n    (`(fault_operatorControlLever_LACU), `(fault_operatorControlLever_armController)),\n    (`(fault_groundSpeed_LACU), `(fault_groundSpeed_LAAP)),\n    (`(fault_LAAPFlow_LAAP), `(fault_LAAPFlow_armController)),\n    (`(fault_LAAPActive_LAAP),`(fault_LAAPActive_armController)),\n    (`(fault_armPositionAngle1_LACU), `(fault_input1_armPosition)),\n    (`(fault_output_armPosition), `(fault_angleSensor_armController)),\n    (`(fault_LAAPSetpoint_LACU), `(fault_LAAPSetpoint_LAAP)),\n    (`(fault_armFlow_armController), `(fault_PWMFlow_LACU)),\n    (`(fault_armPositionAngle2_LACU), `(fault_input2_armPosition)),\n    (`(fault_groundSpeed_LACU), `(fault_groundSpeed_armController)),\n    (`(fault_LAAPRequest_LACU), `(fault_LAAPRequest_LAAP)),\n    (`(fault_output_armPosition), `(fault_angleSensor_LAAP))\n  ]\n\n\nmeta def foo' : model_info := { del := delegation, comps := [`(armPosition), `(LAAP), `(armController)]}\n\n\n-- theorem rpo_snd_lacu : RPO_fst MODEL := \n-- by {solve_rpo_fst_new foo',}\n\n\ntheorem rpo_snd_lacu : RPO_snd MODEL := \nbegin\n\n\nsolve_rpo_snd_new foo',\n-- all_goals {rw fsadfdsa,\n-- split,\n-- assumption,\n-- rw \u2190 asdff,\n-- assumption,},\n-- {rw fsadfdsa,\n--     split,\n--       { -- copied from above\n--         apply H1_right_1,},\n--       {\n--         rw \u2190 asdff, \n--         apply H1_right_2,\n--       }},\n-- {},\n  -- {    -- copied from above,\n  --       rw [disj_comm_guarded],\n  --       apply H1,\n  -- },\n  -- { \n  --   rw fsadfdsa,\n  --   split,\n  --     { -- copied from above\n  --       apply H1_right_2,},\n  --     {\n  --       rw \u2190 asdff, \n  --       apply H1_right_1,\n  --     }\n  -- },\n  -- {\n  --   rw fsadfdsa,\n  --   split,\n  --     { -- copied from above\n  --       apply H1_right_2,},\n  --     {\n  --       rw \u2190 asdff, \n  --       apply H1_right_1,\n  --     },\n  -- },\nend ", "meta": {"author": "loganrjmurphy", "repo": "ForeMoSt", "sha": "c7affc7c8971562520d2775ac48fe4f188f84b02", "save_path": "github-repos/lean/loganrjmurphy-ForeMoSt", "path": "github-repos/lean/loganrjmurphy-ForeMoSt/ForeMoSt-c7affc7c8971562520d2775ac48fe4f188f84b02/src/test_rpo_fst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.03308598089141841, "lm_q1q2_score": 0.014996612842246062}}
{"text": "universe u \nvariables a b c : Type u \n\nmeta def trace_example : tactic unit := \ndo \n  goal \u2190 tactic.target,\n  tactic.trace goal\n\n\nmeta def let_example : tactic unit := \ndo \n  let message := \"Hello world!\",\n  tactic.trace message\n\n\n#check trace_example\n#eval let_example", "meta": {"author": "apurvanakade", "repo": "lean-playground", "sha": "2fe58797031ff8a6c29e1a442cbcc7a0ebc9c768", "save_path": "github-repos/lean/apurvanakade-lean-playground", "path": "github-repos/lean/apurvanakade-lean-playground/lean-playground-2fe58797031ff8a6c29e1a442cbcc7a0ebc9c768/src/metaprogramming/let.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.061875986588615615, "lm_q1q2_score": 0.014986712234697554}}
{"text": "inductive Foo where\n  | mk : Nat \u2192 Foo\n  | boo : String \u2192 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": "import Mathlib.Data.Real.Basic\n\n/-! # Test transparency level of `Div` field in `DivInvMonoid`\n\nIt is desirable that particular `DivInvMonoid`s have their `Div` instance not unfold at `.instance`\ntransparency level, in the same way that the `Div` field of a generic `DivInvMonoid` does not.\n\nTo ensure this, in examples where the `Div` field is defined as `fun a b \u21a6 a * b\u207b\u00b9`, we hide this\nunder one layer of other function (so for example the `Div` instance for `Rat` is defined to be\n`\u27e8Rat.div\u27e9`, where `Rat.div` is defined to be `fun a b \u21a6 a * b\u207b\u00b9`).\n\nThis file checks that this and similar tricks have had the desired effect:\n`with_reducible_and_instances apply mul_le_mul` fails although `apply mul_le_mul` succeeds.\n-/\n\nexample {a b : \u03b1} [LinearOrderedField \u03b1] : a / 2 \u2264 b / 2 := by\n  fail_if_success with_reducible_and_instances apply mul_le_mul -- fails, as desired\n  sorry\n\nexample {a b : \u211a} : a / 2 \u2264 b / 2 := by\n  fail_if_success with_reducible_and_instances apply mul_le_mul -- fails, as desired\n  apply mul_le_mul\n  repeat sorry\n\nexample {a b : \u211d} : a / 2 \u2264 b / 2 := by\n  fail_if_success with_reducible_and_instances apply mul_le_mul -- fails, as desired\n  apply mul_le_mul\n  repeat sorry\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/InstanceTransparency.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.035678547160776994, "lm_q1q2_score": 0.014938497426518437}}
{"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 \u2964 (C\u1d52\u1d56 \u2964 Type v\u2081)`,\n   along with an instance that it is `fully_faithful`.\n\n   Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) \u2245 (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\u2081 u\u2081 u\u2082 -- declare the `v`'s first; see `category_theory.category` for an explanation\n\nvariables {C : Type u\u2081} [\ud835\udc9e : category.{v\u2081} C]\ninclude \ud835\udc9e\n\ndef yoneda : C \u2964 (C\u1d52\u1d56 \u2964 Type v\u2081) :=\n{ obj := \u03bb X,\n  { obj := \u03bb Y, unop Y \u27f6 X,\n    map := \u03bb Y Y' f g, f.unop \u226b g,\n    map_comp' := \u03bb _ _ _ f g, begin ext1, dsimp at *, erw [category.assoc] end,\n    map_id' := \u03bb Y, begin ext1, dsimp at *, erw [category.id_comp] end },\n  map := \u03bb X X' f, { app := \u03bb Y g, g \u226b f } }\n\ndef coyoneda : C\u1d52\u1d56 \u2964 (C \u2964 Type v\u2081) :=\n{ obj := \u03bb X,\n  { obj := \u03bb Y, unop X \u27f6 Y,\n    map := \u03bb Y Y' f g, g \u226b f,\n    map_comp' := \u03bb _ _ _ f g, begin ext1, dsimp at *, erw [category.assoc] end,\n    map_id' := \u03bb Y, begin ext1, dsimp at *, erw [category.comp_id] end },\n  map := \u03bb X X' f, { app := \u03bb Y g, f.unop \u226b g },\n  map_comp' := \u03bb _ _ _ f g, begin ext1, ext1, dsimp at *, erw [category.assoc] end,\n  map_id' := \u03bb X, begin ext1, ext1, dsimp at *, erw [category.id_comp] end }\n\nnamespace yoneda\n@[simp] lemma obj_obj (X : C) (Y : C\u1d52\u1d56) : (yoneda.obj X).obj Y = (unop Y \u27f6 X) := rfl\n@[simp] lemma obj_map (X : C) {Y Y' : C\u1d52\u1d56} (f : Y \u27f6 Y') :\n  (yoneda.obj X).map f = \u03bb g, f.unop \u226b g := rfl\n@[simp] lemma map_app {X X' : C} (f : X \u27f6 X') (Y : C\u1d52\u1d56) :\n  (yoneda.map f).app Y = \u03bb g, g \u226b f := rfl\n\nlemma obj_map_id {X Y : C} (f : op X \u27f6 op Y) :\n  ((@yoneda C _).obj X).map f (\ud835\udfd9 X) = ((@yoneda C _).map f.unop).app (op Y) (\ud835\udfd9 Y) :=\nby obviously\n\n@[simp] lemma naturality {X Y : C} (\u03b1 : yoneda.obj X \u27f6 yoneda.obj Y)\n  {Z Z' : C} (f : Z \u27f6 Z') (h : Z' \u27f6 X) : f \u226b \u03b1.app (op Z') h = \u03b1.app (op Z) (f \u226b h) :=\nbegin erw [functor_to_types.naturality], refl end\n\ninstance yoneda_fully_faithful : fully_faithful (@yoneda C _) :=\n{ preimage := \u03bb X Y f, (f.app (op X)) (\ud835\udfd9 X),\n  injectivity' := \u03bb X Y f g p,\n  begin\n    injection p with h,\n    convert (congr_fun (congr_fun h (op X)) (\ud835\udfd9 X)); dsimp; simp,\n  end }\n\n/-- Extensionality via Yoneda. The typical usage would be\n```\n-- Goal is `X \u2245 Y`\napply yoneda.ext,\n-- Goals are now functions `(Z \u27f6 X) \u2192 (Z \u27f6 Y)`, `(Z \u27f6 Y) \u2192 (Z \u27f6 X)`, and the fact that these\nfunctions are inverses and natural in `Z`.\n```\n-/\ndef ext (X Y : C)\n  (p : \u03a0 {Z : C}, (Z \u27f6 X) \u2192 (Z \u27f6 Y)) (q : \u03a0 {Z : C}, (Z \u27f6 Y) \u2192 (Z \u27f6 X))\n  (h\u2081 : \u03a0 {Z : C} (f : Z \u27f6 X), q (p f) = f) (h\u2082 : \u03a0 {Z : C} (f : Z \u27f6 Y), p (q f) = f)\n  (n : \u03a0 {Z Z' : C} (f : Z' \u27f6 Z) (g : Z \u27f6 X), p (f \u226b g) = f \u226b p g) : X \u2245 Y :=\n@preimage_iso _ _ _ _ yoneda _ _ _ _\n  (nat_iso.of_components (\u03bb 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\u1d52\u1d56 \u2964 Type v\u2081) \u00d7 C\u1d52\u1d56) :=\ncategory_theory.prod.{(max u\u2081 v\u2081)  v\u2081} (C\u1d52\u1d56 \u2964 Type v\u2081) C\u1d52\u1d56\n\ninstance prod_category_instance_2 : category (C\u1d52\u1d56 \u00d7 (C\u1d52\u1d56 \u2964 Type v\u2081)) :=\ncategory_theory.prod.{v\u2081 (max u\u2081 v\u2081)} C\u1d52\u1d56 (C\u1d52\u1d56 \u2964 Type v\u2081)\n\nend yoneda\n\nnamespace coyoneda\n@[simp] lemma obj_obj (X : C\u1d52\u1d56) (Y : C) : (coyoneda.obj X).obj Y = (unop X \u27f6 Y) := rfl\n@[simp] lemma obj_map {X' X : C} (f : X' \u27f6 X) (Y : C\u1d52\u1d56) :\n  (coyoneda.obj Y).map f = \u03bb g, g \u226b f := rfl\n@[simp] lemma map_app (X : C) {Y Y' : C\u1d52\u1d56} (f : Y \u27f6 Y') :\n  (coyoneda.map f).app X = \u03bb g, f.unop \u226b g := rfl\nend coyoneda\n\nclass representable (F : C\u1d52\u1d56 \u2964 Type v\u2081) :=\n(X : C)\n(w : yoneda.obj X \u2245 F)\n\nvariables (C)\nopen yoneda\n\ndef yoneda_evaluation : C\u1d52\u1d56 \u00d7 (C\u1d52\u1d56 \u2964 Type v\u2081) \u2964 Type (max u\u2081 v\u2081) :=\nevaluation_uncurried C\u1d52\u1d56 (Type v\u2081) \u22d9 ulift_functor.{u\u2081}\n\n@[simp] lemma yoneda_evaluation_map_down\n  (P Q : C\u1d52\u1d56 \u00d7 (C\u1d52\u1d56 \u2964 Type v\u2081)) (\u03b1 : P \u27f6 Q) (x : (yoneda_evaluation C).obj P) :\n  ((yoneda_evaluation C).map \u03b1 x).down = \u03b1.2.app Q.1 (P.2.map \u03b1.1 x.down) := rfl\n\ndef yoneda_pairing : C\u1d52\u1d56 \u00d7 (C\u1d52\u1d56 \u2964 Type v\u2081) \u2964 Type (max u\u2081 v\u2081) :=\nfunctor.prod yoneda.op (functor.id (C\u1d52\u1d56 \u2964 Type v\u2081)) \u22d9 functor.hom (C\u1d52\u1d56 \u2964 Type v\u2081)\n\n@[simp] lemma yoneda_pairing_map\n  (P Q : C\u1d52\u1d56 \u00d7 (C\u1d52\u1d56 \u2964 Type v\u2081)) (\u03b1 : P \u27f6 Q) (\u03b2 : (yoneda_pairing C).obj P) :\n  (yoneda_pairing C).map \u03b1 \u03b2 = yoneda.map \u03b1.1.unop \u226b \u03b2 \u226b \u03b1.2 := rfl\n\ndef yoneda_lemma : yoneda_pairing C \u2245 yoneda_evaluation C :=\n{ hom :=\n  { app := \u03bb F x, ulift.up ((x.app F.1) (\ud835\udfd9 (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 [\u2190functor_to_types.naturality,\n           obj_map_id,\n           functor_to_types.naturality,\n           functor_to_types.map_id]\n    end },\n  inv :=\n  { app := \u03bb F x,\n    { app := \u03bb 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 [\u2190functor_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 [\u2190functor_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\u1d52\u1d56 \u2964 Type v\u2081) : (yoneda.obj X \u27f9 F) \u2245 ulift.{u\u2081} (F.obj (op X)) :=\nnat_iso.app (yoneda_lemma C) (op X, F)\n\nomit \ud835\udc9e\n@[simp] def yoneda_sections_small {C : Type u\u2081} [small_category C] (X : C) (F : C\u1d52\u1d56 \u2964 Type u\u2081) : (yoneda.obj X \u27f9 F) \u2245 F.obj (op X) :=\nyoneda_sections X F \u226a\u226b 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 $ \u03bb e i ms,\nmatch e with\n| expr.mvar _ _ _ := ms.insert e\n| _ := ms\nend\n\nmeta def list.dup_by_native {\u03b1 \u03b2} [has_lt \u03b2] [decidable_rel ((<) : \u03b2 \u2192 \u03b2 \u2192 Prop)]\n  (f : \u03b1 \u2192 \u03b2) (xs : list \u03b1) : list \u03b1 :=\nrb_map.values $ xs.foldl (\u03bb m x, m.insert (f x) x) mk_rb_map\n\nmeta def level.mvar_name : level \u2192 name\n| (level.mvar n) := n\n| _ := name.anonymous\n\nprivate meta def level.meta_vars_core : level \u2192 name_set \u2192 name_set\n| level.zero := id\n| (level.param _) := id\n| (level.succ l) := l.meta_vars_core\n| (level.mvar n) := \u03bb ms, ms.insert n\n| (level.max a b) := a.meta_vars_core \u2218 b.meta_vars_core\n| (level.imax a b) := a.meta_vars_core \u2218 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 $ \u03bb 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' {\u03b1} [decidable_eq \u03b1] (a : \u03b1) : \u2115 \u2192 list \u03b1 \u2192 option \u2115\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' {\u03b1} [decidable_eq \u03b1] (a : \u03b1) (xs : list \u03b1) : option \u2115 :=\nxs.index_of_core' a 0\n\nmeta def expr.abstract_mvars (e : expr) (mvars : list name) : expr :=\ne.replace $ \u03bb e i,\nmatch e with\n| e@(expr.mvar n _ _) :=\n  (mvars.index_of' n).map (\u03bb j, expr.var (i + j))\n| e := none\nend\n\nmeta def expr.meta_uniq_name : expr \u2192 name\n| (expr.mvar n _ _) := n\n| _ := name.anonymous\n\nmeta def expr.meta_type : expr \u2192 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 \u2192 list expr \u2192 tactic (list expr)\n| (e@(expr.mvar n pp_n _)::es) ctx :=\n  if \u2203 m \u2208 ctx, (m : expr).meta_uniq_name = e.meta_uniq_name then\n    sorted_mvars_core es ctx\n  else do\n    t \u2190 infer_type e >>= instantiate_mvars,\n    ctx \u2190 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 \u2192 tactic (list expr)\n| [] := pure []\n| (m :: ms) := do\n  t \u2190 infer_type m >>= instantiate_mvars,\n  ms' \u2190 abstract_mvar_telescope ms,\n  pure $ t.abstract_mvars' ms :: ms'\n\nmeta def level.instantiate_univ_mvars (subst : rb_map name level) : level \u2192 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 $ \u03bb 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 \u2192 expr \u2192 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 \u2192 p') (hq : q \u2192 q') : p \u2228 q \u2192 p' \u2228 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 \u2192 r) : q \u2228 p \u2192 r \u2228 p :=\nor_imp_congr h id\n\nlemma or_imp_congr_right {p q r} (h : q \u2192 r) : p \u2228 q \u2192 p \u2228 r :=\nor_imp_congr id h\n\nlemma or_imp_congr_right_strong {p q r} (h : \u00ac p \u2192 q \u2192 r) : p \u2228 q \u2192 p \u2228 r :=\nmatch classical.prop_decidable p with\n| decidable.is_true hp := \u03bb _, 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 \u2192 q) \u2194 (\u00ac p \u2228 q) :=\nby cases classical.prop_decidable p; simp *\n\nlemma not_imp_iff_or {p q : Prop} : (\u00ac p \u2192 q) \u2194 (p \u2228 q) :=\nby cases classical.prop_decidable p; simp *\n\ntheorem iff_imp {a b c} : ((a \u2194 b) \u2192 c) \u2194 ((a \u2192 b) \u2192 (b \u2192 a) \u2192 c) :=\niff.intro (\u03bb h ha hb, h \u27e8ha, hb\u27e9) (\u03bb h \u27e8ha, hb\u27e9, h ha hb)\n\nlemma classical.forall_imp_iff_exists_not_or {\u03b1} {p : \u03b1 \u2192 Prop} {q : Prop} :\n  ((\u2200 x, p x) \u2192 q) \u2194 ((\u2203 x, \u00ac p x) \u2228 q) :=\nby simp [imp_iff_or_not]\n\ndef list.has_dups_core {\u03b1} [decidable_eq \u03b1] : list \u03b1 \u2192 list \u03b1 \u2192 bool\n| (x::xs) ys := x \u2208 ys \u2228 xs.has_dups_core (x::ys)\n| [] _ := ff\n\ndef list.has_dups {\u03b1} [decidable_eq \u03b1] (xs : list \u03b1) : bool :=\nxs.has_dups_core []\n\ndef list.zip_with_index_core {\u03b1} : \u2115 \u2192 list \u03b1 \u2192 list (\u03b1 \u00d7 \u2115)\n| _ [] := []\n| i (x::xs) := (x,i) :: list.zip_with_index_core (i+1) xs\n\ndef list.zip_with_index {\u03b1} : list \u03b1 \u2192 list (\u03b1 \u00d7 \u2115) :=\nlist.zip_with_index_core 0\n\ndef list.filter_maximal {\u03b1} (gt : \u03b1 \u2192 \u03b1 \u2192 bool) (l : list \u03b1) : list \u03b1 :=\nl.filter $ \u03bb x, \u2200 y \u2208 l, \u00ac gt y x\n\ndef list.m_any {\u03b1 m} [monad m] (f : \u03b1 \u2192 m bool) : list \u03b1 \u2192 m bool\n| [] := pure ff\n| (x::xs) := do f_x \u2190 f x, if f_x then pure tt else xs.m_any\n\nmeta def mk_metas_core : list expr \u2192 tactic (list expr)\n| [] := pure []\n| (t::ts) := do\n  ms \u2190 mk_metas_core ts,\n  m \u2190 mk_meta_var (t.instantiate_vars ms),\n  pure (m::ms)\n\nmeta def expr.name_hint : expr \u2192 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 \u2192 tactic (list expr)\n| [] := pure []\n| (t::ts) := do\n  lcs \u2190 mk_locals_core ts,\n  lc \u2190 mk_local' t.hyp_name_hint binder_info.default (t.instantiate_vars lcs),\n  pure (lc :: lcs)\n\nmeta def expr.const_levels : expr \u2192 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 := \u27e8\u03bb _, id\u27e9\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 \u2190 infer_type a,\ntb \u2190 infer_type b,\nunify ta tb trnsp approx,\nunify a b trnsp approx\n\nmeta def minimal_tc_failure : expr \u2192 tactic expr | e := do\nff \u2190 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 \u2190 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 \u2190 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 {\u03b1} (p : \u03b1 \u2192 bool) : list \u03b1 \u2192 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 \u2190 infer_type type >>= whnf,\nmatch sort_of_type with\n| expr.sort lvl := pure lvl\n| not_sort := do\n  fmt \u2190 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": "macro \"A\" : term => `(id x)\ntheorem test : A = A := 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/autobound_and_macroscopes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807713748839185, "lm_q2_score": 0.04401864782501479, "lm_q1q2_score": 0.014881698452790625}}
{"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\u2080 | ind\u2081 | ind\u2082 | break | output | len | vals\n\nopen Vars\ninstance : has_to_string Vars :=\n\u27e8\u03bb 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\u2080 := \"ind\u2080\" | ind\u2081 := \"ind\u2081\" | ind\u2082 := \"ind\u2082\" | break := \"break\" | output := \"output\" | len := \"len\" | vals := \"vals\"\nend\u27e9\nend vars\n\nsection NameSpace\n@[derive decidable_eq, derive inhabited, derive has_to_string, reducible]\ndef NameSpace := \u2115\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 \u2209 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 \u2260 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\u27e8\u03bb i, \"n\" ++ (to_string i.ns) ++ \"_\" ++ (to_string i.name)\u27e9\n\nlemma Ident_ns_surjective {b : Types} : function.surjective (@Ident.ns b) :=\nby { intro x, use \u27e8x, default\u27e9, }\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 `\u2237`:9000 := Ident.mk\ninfix `\u2237\u2099`:9000 := @Ident.mk Types.nn\ninfix `\u2237\u1d63`:9000 := @Ident.mk Types.rr\n\nend Ident\n\nsection frames\n-- TODO Fix\nvariables {\u03b1 \u03b3 : Type*} {\u03b2 : \u03b1 \u2192 Type*} (f : (\u03a0 x, \u03b2 x) \u2192 \u03b3) (g : (\u03a0 x, \u03b2 x) \u2192 (\u03a0 x, \u03b2 x))\n\ndef function.has_dframe (S : set \u03b1) : Prop :=\n\u2200 \u2983c\u2081 c\u2082 : \u03a0 x, \u03b2 x\u2984, (\u2200 x \u2208 S, c\u2081 x = c\u2082 x) \u2192 f c\u2081 = f c\u2082\n\nstructure function.has_dheap (S : set \u03b1) : Prop :=\n(local_frame : \u2200 (c\u2081 c\u2082 : \u03a0 x, \u03b2 x), (\u2200 x \u2208 S, c\u2081 x = c\u2082 x) \u2192 \u2200 {y}, y \u2208 S \u2192 g c\u2081 y = g c\u2082 y)\n(global_id : \u2200 (c y), y \u2209 S \u2192 g c y = c y)\n\nvariables {f g}\ntheorem function.has_dframe.res {S} (h : function.has_dframe f S) (S') (hS' : S \u2286 S') :\n  function.has_dframe f S' :=\n\u03bb c\u2081 c\u2082 h', h (\u03bb x hx, h' _ (hS' hx))\n\ntheorem function.has_dheap.res {S} (h : function.has_dheap g S) (S') (hS' : S \u2286 S') :\n  function.has_dheap g S' :=\n{ local_frame := \u03bb c\u2081 c\u2082 c_eq y hy,\nbegin\n  by_cases H : y \u2208 S,\n  { exact h.local_frame c\u2081 c\u2082 (\u03bb x hx, c_eq _ (hS' hx)) H, },\n  { rw [h.global_id c\u2081 _ H, h.global_id c\u2082 _ H],  exact c_eq _ hy, },\nend,\n  global_id := \u03bb c y hy, h.global_id c y (\u03bb H, hy (hS' H)), }\n\ntheorem function.has_dframe.const (x : \u03b3) (S : set \u03b1) : function.has_dframe (\u03bb _ : \u03a0 x, \u03b2 x, x) S :=\n\u03bb _ _ _, rfl\n\ntheorem function.has_dheap.id (S : set \u03b1) : function.has_dheap (@id (\u03a0 x, \u03b2 x)) S :=\n{ local_frame := \u03bb c\u2081 c\u2082 h y hy, h y hy,\n  global_id := \u03bb _ _ _, rfl }\n\nexample {S : set \u03b1} {x\u2080 : \u03b1} {y\u2080 : \u03b2 x\u2080} [\u2200 x, decidable_eq (\u03b2 x)] (f : (\u03a0 x, \u03b2 x) \u2192 (\u03a0 x, \u03b2 x)) (g : (\u03a0 x, \u03b2 x) \u2192 \u03b3)\n  (hf : function.has_dframe g S) (hg : function.has_dheap f (insert x\u2080 S)) :\n  function.has_dframe (\u03bb ctx, if ctx x\u2080 = y\u2080 then g (f ctx) else g ctx) (insert x\u2080 S) :=\nbegin\n  intros c\u2081 c\u2082 c_eq, dsimp only,\n  have := (hf.res _ _) c_eq,\n  all_goals { sorry, },\nend\n\nend frames\n\ndef Context (val_type : Types \u2192 Type) : Type :=\n\u2200 \u2983b : Types\u2984, Ident b \u2192 val_type b\n\nstructure HeapContext (val_type : Types \u2192 Type) : Type :=\n(store : Context val_type)\n(heap : Context (list \u2218 val_type))\n\nnamespace Context\n\nvariable {val_type : Types \u2192 Type}\n\ninstance [\u2200 b, inhabited (val_type b)] : inhabited (Context val_type) :=\n\u27e8\u03bb _ _, default\u27e9\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 \u2260 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 \u2192 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 \u2192 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 : \u2115) (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 {\u03b1 : Type*} (f : \u03b1 \u2192 option \u03b1) (cond : \u03b1 \u2192 option bool) : \u2115 \u2192 \u03b1 \u2192 option \u03b1\n| 0 x := none\n| (n+1) x := (cond x).bind (\u03bb b, if b then (f x).bind (iterate_while n) else some x)\n\n-- theorem iterate_while_tr {\u03b1 \u03b2 : Type*} {f\u2081 : \u03b1 \u2192 option \u03b1} {cond\u2081 : \u03b1 \u2192 option bool} {n : \u2115} {x : \u03b1}\n--   (tr : \u03b1 \u2192 \u03b2) (f\u2082 : \u03b2 \u2192 option \u03b2) (cond\u2082 : \u03b2 \u2192 option bool) (y : \u03b2)\n--   (hf : \u2200 x, )\n\n-- theorem iterate_while_eq_of_invariant {\u03b1 : Type*} (inv : \u03b1 \u2192 \u2115 \u2192 Prop)\n--   (f : \u03b1 \u2192 option \u03b1) (cond : \u03b1 \u2192 option bool) (n : \u2115) (x : \u03b1)\n--   (hcond : \u2200 {x i}, inv x i \u2192 (cond x).is_some)\n--   (h\u2080 : inv x 0) (hind : \u2200 x i, cond x = some tt \u2192 inv x i \u2192 \u2203 x' \u2208 f x, inv x' (i + 1))\n--   (h\u209c : \u2200 {x}, inv x n \u2192 cond x = some ff) :\n--   \u2203 r \u2208 iterate_while f cond (n + 1) x, inv r n :=\n-- begin\n--   induction n with n ih generalizing x,\n--   { simpa [h\u209c h\u2080], },\n--   obtain \u27e8_|_, hc\u27e9 := option.is_some_iff_exists.mp (hcond h\u2080),\n--   { simp, }\n-- end\n\nend iterate\n\ntheorem imp_iff_distrib {a b c : Prop} : ((a \u2192 b) \u2194 (a \u2192 c)) \u2194 (a \u2192 (b \u2194 c)) :=\n\u27e8\u03bb h ha, \u27e8\u03bb hb, h.mp (\u03bb _, hb) ha, \u03bb hc, h.mpr (\u03bb _, hc) ha\u27e9, \u03bb h, \u27e8\u03bb hb ha, (h ha).mp (hb ha), \u03bb hc ha, (h ha).mpr (hc ha)\u27e9\u27e9\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": "import Duper.MClause\nimport Duper.RuleM\nimport Duper.Simp\nimport Duper.Util.ProofReconstruction\n\nnamespace Duper\nopen Lean\nopen Meta\nopen RuleM\nopen SimpResult\n\n\ninitialize Lean.registerTraceClass `Rule.eqHoist\n\ntheorem eq_hoist_proof (x y : \u03b1) (f : Prop \u2192 Prop) (h : f (x = y)) : f False \u2228 x = y := by\n  by_cases x_eq_y : x = y\n  . exact Or.inr x_eq_y\n  . rename \u00acx = y => x_ne_y\n    have x_eq_y_false := eq_false x_ne_y\n    exact Or.inl $ x_eq_y_false \u25b8 h\n\ndef mkEqHoistProof (pos : ClausePos) (freshVar1 freshVar2 : Expr) (premises : List Expr)\n  (parents : List ProofParent) (transferExprs : Array Expr) (c : Clause) : MetaM Expr :=\n  Meta.forallTelescope c.toForallExpr fun xs body => do\n    let cLits := c.lits.map (fun l => l.map (fun e => e.instantiateRev xs))\n    let (parentsLits, appliedPremises, transferExprs) \u2190 instantiatePremises parents premises xs transferExprs\n    let parentLits := parentsLits[0]!\n    let appliedPremise := appliedPremises[0]!\n\n    let mut caseProofs := Array.mkEmpty parentLits.size\n    for i in [:parentLits.size] do\n      let lit := parentLits[i]!\n      let pr : Expr \u2190 Meta.withLocalDeclD `h lit.toExpr fun h => do\n        if i == pos.lit then\n          let substLitPos : LitPos := \u27e8pos.side, pos.pos\u27e9\n          let abstrLit \u2190 (lit.abstractAtPos! substLitPos)\n          let abstrExp := abstrLit.toExpr\n          let abstrLam := mkLambda `x BinderInfo.default (mkSort levelZero) abstrExp\n          let lastTwoClausesProof \u2190 Meta.mkAppM ``eq_hoist_proof #[freshVar1, freshVar2, abstrLam, h]\n          Meta.mkLambdaFVars #[h] $ \u2190 orSubclause (cLits.map Lit.toExpr) 2 lastTwoClausesProof\n        else\n          let idx := if i \u2265 pos.lit then i - 1 else i\n          Meta.mkLambdaFVars #[h] $ \u2190 orIntro (cLits.map Lit.toExpr) idx h\n      caseProofs := caseProofs.push pr\n    let r \u2190 orCases (parentLits.map Lit.toExpr) caseProofs\n    Meta.mkLambdaFVars xs $ mkApp r appliedPremise\n\ndef eqHoistAtExpr (e : Expr) (pos : ClausePos) (given : Clause) (c : MClause) : RuleM (Array ClauseStream) :=\n  withoutModifyingMCtx do\n    let lit := c.lits[pos.lit]!\n    if e.getTopSymbol.isMVar then -- Check condition 4\n      -- If the head of e is a variable then it must be applied and the affected literal must be either\n      -- e = True, e = False, or e = e' where e' is another variable headed term\n      if not e.isApp then -- e is a non-applied variable and so we cannot apply eqHoist\n        return #[]\n      if pos.pos != #[] then\n        return #[] -- e is not at the top level so the affected literal cannot have the form e = ...\n      if not lit.sign then\n        return #[] -- The affected literal is not positive and so it cannot have the form e = ...\n      let otherSide := lit.getOtherSide pos.side\n      if otherSide != (mkConst ``True) && otherSide != (mkConst ``False) && not otherSide.getTopSymbol.isMVar then\n        return #[] -- The other side is not True, False, or variable headed, so the affected literal cannot have the required form\n    -- Check conditions 1 and 3 (condition 2 is guaranteed by construction)\n    let eligibility \u2190 eligibilityPreUnificationCheck c pos.lit\n    if eligibility == Eligibility.notEligible then\n      return #[]\n    -- Make freshVars and freshVarEquality\n    let freshVar1 \u2190 mkFreshExprMVar none\n    let freshVarTy \u2190 inferType freshVar1\n    let freshVar2 \u2190 mkFreshExprMVar freshVarTy\n    let freshVarEquality \u2190 mkAppM ``Eq #[freshVar1, freshVar2]\n    -- Perform unification\n    let ug \u2190 unifierGenerator #[(e, freshVarEquality)]\n    let loaded \u2190 getLoadedClauses\n    let yC := do\n      setLoadedClauses loaded\n      if not $ \u2190 eligibilityPostUnificationCheck c pos.lit eligibility (strict := lit.sign) then\n        return none\n      let eSide \u2190 instantiateMVars $ lit.getSide pos.side\n      let otherSide \u2190 instantiateMVars $ lit.getOtherSide pos.side\n      let cmp \u2190 compare eSide otherSide\n      if cmp == Comparison.LessThan || cmp == Comparison.Equal then -- If eSide \u2264 otherSide then e is not in an eligible position\n        return none\n      -- All side conditions have been met. Yield the appropriate clause\n      let cErased := c.eraseLit pos.lit\n      -- Need to instantiate mvars in freshVar1, freshVar2, and freshVarEquality because unification assigned to mvars in each of them\n      let freshVar1 \u2190 instantiateMVars freshVar1\n      let freshVar2 \u2190 instantiateMVars freshVar2\n      let freshVarEquality \u2190 instantiateMVars freshVarEquality\n      let newClause := cErased.appendLits #[\u2190 lit.replaceAtPos! \u27e8pos.side, pos.pos\u27e9 (mkConst ``False), Lit.fromExpr freshVarEquality]\n      trace[Rule.eqHoist] \"Created {newClause.lits} from {c.lits}\"\n      yieldClause newClause \"eqHoist\" $ some (mkEqHoistProof pos freshVar1 freshVar2)\n    return #[ClauseStream.mk ug given yC \"eqHoist\"]\n\ndef eqHoist (given : Clause) (c : MClause) (cNum : Nat) : RuleM (Array ClauseStream) := do\n  trace[Rule.eqHoist] \"Running EqHoist on {c.lits}\"\n  let fold_fn := fun streams e pos => do\n    let str \u2190 eqHoistAtExpr e.consumeMData pos given c\n    return streams.append str\n  c.foldGreenM fold_fn #[]", "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/Rules/EqHoist.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.033589503473407556, "lm_q1q2_score": 0.01483557646417088}}
{"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.Data.Options\n\n/-! # Basic support for auto bound implicit local names -/\n\nnamespace Lean.Elab\n\nregister_builtin_option autoImplicit : Bool := {\n    defValue := true\n    descr    := \"Unbound local variables in declaration headers become implicit arguments. In \\\"relaxed\\\" mode (default), any atomic identifier is eligible, otherwise only a lower case or greek letter followed by numeric digits are eligible. For example, `def f (x : Vector \u03b1 n) : Vector \u03b1 n :=` automatically introduces the implicit variables {\u03b1 n}.\"\n  }\n\nregister_builtin_option relaxedAutoImplicit : Bool := {\n    defValue := true\n    descr    := \"When \\\"relaxed\\\" mode is enabled, any atomic nonempty identifier is eligible for auto bound implicit locals (see optin `autoBoundImplicitLocal`.\"\n  }\n\n\nprivate def isValidAutoBoundSuffix (s : String) : Bool :=\n  s.toSubstring.drop 1 |>.all fun c => c.isDigit || isSubScriptAlnum c || c == '_' || c == '\\''\n\n/-!\nRemark: Issue #255 exposed a nasty interaction between macro scopes and auto-bound-implicit names.\n```\nlocal notation \"A\" => id x\ntheorem test : A = A := sorry\n```\nWe used to use `n.eraseMacroScopes` at `isValidAutoBoundImplicitName` and `isValidAutoBoundLevelName`.\nThus, in the example above, when `A` is expanded, a `x` with a fresh macro scope is created.\n`x`+macros-scope is not in scope and is a valid auto-bound implicit name after macro scopes are erased.\nSo, an auto-bound exception would be thrown, and `x`+macro-scope would be added as a new implicit.\nWhen, we try again, a `x` with a new macro scope is created and this process keeps repeating.\nTherefore, we do consider identifier with macro scopes anymore.\n-/\n\ndef isValidAutoBoundImplicitName (n : Name) (relaxed : Bool) : Bool :=\n  match n with\n  | .str .anonymous s => s.length > 0 && (relaxed || ((isGreek s.front || s.front.isLower) && isValidAutoBoundSuffix s))\n  | _ => false\n\ndef isValidAutoBoundLevelName (n : Name) (relaxed : Bool) : Bool :=\n  match n with\n  | .str .anonymous s => s.length > 0 && (relaxed || (s.front.isLower && isValidAutoBoundSuffix s))\n  | _ => false\n\nend Lean.Elab\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/AutoBound.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386099567919973, "lm_q2_score": 0.058345842249068455, "lm_q1q2_score": 0.014811733607090037}}
{"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 tactic.fix_reflect_string\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) : \u2115 :=\ns.fold 1 (\u03bb h c, (33*h + c.val) % unsigned_sz)\n\n/-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name\n`nspace._i` -/\nmeta def string.mk_hashed_name (nspace : name) (id : string) : name :=\nnspace <.> (\"_\" ++ to_string id.hash)\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 \u2190 doc_string fr,\n   to.mmap' $ \u03bb tgt, add_doc_string tgt fr_ds\n\nopen lean lean.parser interactive\n\n/--\n`copy_doc_string source \u2192 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 \u2190 parser.ident,\n   tk \"->\",\n   to \u2190 parser.many parser.ident,\n   expr.const fr _  \u2190 resolve_name fr,\n   to \u2190 parser.of_tactic (to.mmap $ \u03bb 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 \u00d7 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\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 : \u2115 := 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/-- If `note_name` and `note` are `pexpr`s representing strings,\n`add_library_note note_name note` adds a declaration of type `string \u00d7 string` and tags it with\nthe `library_note` attribute. -/\nmeta def tactic.add_library_note (note_name note : string) : tactic unit :=\ndo let decl_name := note_name.mk_hashed_name `library_note,\n   add_decl $ mk_reflected_definition decl_name (note_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 \u2190 parser.pexpr,\nnote_name \u2190 eval_pexpr string note_name,\nsome doc_string \u2190 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 \u00d7 string)) :=\nattribute.get_instances `library_note >>=\n  list.mmap (\u03bb dcl, mk_const dcl >>= eval_expr (string \u00d7 string))\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 \u2192 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 := \u27e8\u2191doc_category.to_string\u27e9\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(description : 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) : json :=\njson.object [\n  (\"name\", d.name),\n  (\"category\", d.category.to_string),\n  (\"decl_names\", d.decl_names.map (json.of_string \u2218 to_string)),\n  (\"tags\", d.tags.map json.of_string),\n  (\"description\", d.description)\n]\n\nmeta instance : has_to_string tactic_doc_entry :=\n\u27e8json.unparse \u2218 tactic_doc_entry.to_json\u27e9\n\n/-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the\n    doc string of the declaration named `inh_id`. -/\nmeta def tactic_doc_entry.update_description_from (tde : tactic_doc_entry) (inh_id : name) :\n  tactic tactic_doc_entry :=\ndo ds \u2190 doc_string inh_id <|> fail (to_string inh_id ++ \" has no doc string\"),\n   return { description := ds .. tde }\n\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`. -/\nmeta def tactic_doc_entry.update_description (tde : tactic_doc_entry) : tactic tactic_doc_entry :=\nmatch tde.inherit_description_from, tde.decl_names with\n| some inh_id, _ := tde.update_description_from inh_id\n| none, [inh_id] := tde.update_description_from inh_id\n| none, _ := return tde\nend\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\n/-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/\nmeta def tactic.get_tactic_doc_entries : tactic (list tactic_doc_entry) :=\nattribute.get_instances `tactic_doc >>=\n  list.mmap (\u03bb dcl, mk_const dcl >>= eval_expr tactic_doc_entry)\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) : tactic unit :=\ndo when (tde.description = \"\" \u2227 tde.inherit_description_from.is_none \u2227 tde.decl_names.length \u2260 1) $\n     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   tde \u2190 if tde.description = \"\" then tde.update_description else return tde,\n   let decl_name := (tde.name ++ tde.category.to_string).mk_hashed_name `tactic_doc,\n   add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde),\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```\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 \u2190 parser.pexpr,\ne \u2190 eval_pexpr tactic_doc_entry pe,\nlet e : tactic_doc_entry := match mi.doc_string with\n  | some desc := { description := desc, ..e }\n  | none := e\n  end,\ntactic.add_tactic_doc e .\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 : \u2115) (f : \u2115 \u2192 \u2115) (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 : \u2115 \u2192 \u2115) (x : \u2115)\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 <https://leanprover-community.github.io/extras/conv.html> 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 : \u2115) (h\u2081 : b = c) (h\u2082 : a + c = a + d) : a + b = a + d :=\nby conv {\n  to_lhs,\n  conv {\n    congr, skip,\n    rw h\u2081,\n  },\n  rw h\u2082,\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-/\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 {\u03c0 \u03b1 : Type} : component \u03c0 \u03b1 :=\ncomponent.ignore_props $ component.mk_simple int int 0 (\u03bb _ x y, (x + y, none)) (\u03bb _ 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 \u2190 parser.ident,\nn \u2190 resolve_constant n,\nsome doc \u2190 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": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/doc_commands.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18952109132967757, "lm_q2_score": 0.07807816299972123, "lm_q1q2_score": 0.01479745866072362}}
{"text": "partial def inf (u : Unit) : List Unit := u :: inf u\n\ntheorem aa : False :=\n  nomatch (\u27e8inf._unsafe_rec (), rfl\u27e9 : \u2203 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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_div_mod_n \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_3 : mem_at mem code_bigint_mul (\u03c3.pc  - 668))\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 654))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 9))\n    (hin_a : a = cast_BigInt3 mem (\u03c3.fp - 8))\n    (hin_b : b = cast_BigInt3 mem (\u03c3.fp - 5))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u03c4.ap = \u03c3.ap + 88 \u2227\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 9)) (mem $ \u03c4.ap - 4)\n        (spec_div_mod_n mem \u03ba range_check_ptr a b (mem (\u03c4.ap - 4)) (cast_BigInt3 mem (\u03c4.ap - 3)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  have h_mem_rec := h_mem,\n  unpack_memory code_div_mod_n at h_mem with \u27e8hpc0, 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\u27e9,\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 \u03ba_call3 ap3 h_call3,\n  rcases h_call3 with \u27e8h_call3_ap_offset, h_call3\u27e9,\n  rcases h_call3 with \u27e8rc_m3, rc_mle3, hl_range_check_ptr\u2081, h_call3\u27e9,\n  generalize' hr_rev_range_check_ptr\u2081: mem (ap3 - 4) = range_check_ptr\u2081,\n  have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\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\u2081 },\n  rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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\u2081 _ _),\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\u2081, 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 \u03ba_call6 ap6 h_call6,\n  rcases h_call6 with \u27e8h_call6_ap_offset, h_call6\u27e9,\n  rcases h_call6 with \u27e8rc_m6, rc_mle6, hl_range_check_ptr\u2082, h_call6\u27e9,\n  generalize' hr_rev_range_check_ptr\u2082: mem (ap6 - 4) = range_check_ptr\u2082,\n  have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\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\u2082 },\n  rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\n  try { simp only [arg0] at h_call6 },\n  rw [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2081, htv_res, htv_range_check_ptr\u2082, 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 \u03ba_call14 ap14 h_call14,\n  rcases h_call14 with \u27e8h_call14_ap_offset, h_call14\u27e9,\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\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2081, htv_res, htv_range_check_ptr\u2082, 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 \u03ba_call25 ap25 h_call25,\n  rcases h_call25 with \u27e8h_call25_ap_offset, h_call25\u27e9,\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 : \u2124) : F) = carry1,\n  have hl_carry1 := hl_rev_carry1.symm, clear hl_rev_carry1,\n  have htv_carry1: carry1 = _, {\n    have h_\u03b425_c0 : \u2200 x : F, x / (BASE : \u2124) = x * (-46768052394588894761721767695234645457402928824320 : \u2124),\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_\u03b425_c0] at hl_carry1 },\n      try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2082 + 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\u2081, htv_res, htv_range_check_ptr\u2082, 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 : \u2124) : F) = carry2,\n  have hl_carry2 := hl_rev_carry2.symm, clear hl_rev_carry2,\n  have htv_carry2: carry2 = _, {\n    have h_\u03b432_c0 : \u2200 x : F, x / (BASE : \u2124) = x * (-46768052394588894761721767695234645457402928824320 : \u2124),\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_\u03b432_c0] at hl_carry2 },\n      try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2082 + 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\u2081, htv_res, htv_range_check_ptr\u2082, 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 : \u2124) : F) = carry3,\n  have hl_carry3 := hl_rev_carry3.symm, clear hl_rev_carry3,\n  have htv_carry3: carry3 = _, {\n    have h_\u03b440_c0 : \u2200 x : F, x / (BASE : \u2124) = x * (-46768052394588894761721767695234645457402928824320 : \u2124),\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_\u03b440_c0] at hl_carry3 },\n      try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2082 + 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\u2081, htv_res, htv_range_check_ptr\u2082, 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 : \u2124) : F) = carry4,\n  have hl_carry4 := hl_rev_carry4.symm, clear hl_rev_carry4,\n  have htv_carry4: carry4 = _, {\n    have h_\u03b448_c0 : \u2200 x : F, x / (BASE : \u2124) = x * (-46768052394588894761721767695234645457402928824320 : \u2124),\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_\u03b448_c0] at hl_carry4 },\n      try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2082 + 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\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2083: (range_check_ptr\u2082 + 4 : F) = range_check_ptr\u2083,\n  have hl_range_check_ptr\u2083 := hl_rev_range_check_ptr\u2083.symm, clear hl_rev_range_check_ptr\u2083,\n  try { dsimp at hl_range_check_ptr\u2083 }, try { arith_simps at hl_range_check_ptr\u2083 },\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 [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03ba_call3],\n  use_only [range_check_ptr\u2081],\n  use_only [res],\n  have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n  have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n  have spec3 := h_call3 rc_h_range_check_ptr',\n  rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] at spec3,\n  try { dsimp at spec3, arith_simps at spec3 },\n  use_only [spec3],\n  use_only [\u03ba_call6],\n  use_only [range_check_ptr\u2082],\n  use_only [k],\n  have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n  have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n  have spec6 := h_call6 rc_h_range_check_ptr\u2081',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190htv_range_check_ptr\u2082] at spec6,\n  try { dsimp at spec6, arith_simps at spec6 },\n  use_only [spec6],\n  use_only [\u03ba_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 [\u03ba_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\u2082' (0) (by norm_num1) with n hn, arith_simps at hn,\n  use_only [n], { simp only [a29.symm, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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\u2082' (1) (by norm_num1) with n hn, arith_simps at hn,\n  use_only [n], { simp only [a37.symm, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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\u2082' (2) (by norm_num1) with n hn, arith_simps at hn,\n  use_only [n], { simp only [a45.symm, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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\u2082' (3) (by norm_num1) with n hn, arith_simps at hn,\n  use_only [n], { simp only [a52.symm, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, hin_range_check_ptr], arith_simps, exact hn },\n  use_only [a55],\n  have rc_h_range_check_ptr\u2083 := range_checked_offset' rc_h_range_check_ptr\u2082,\n  have rc_h_range_check_ptr\u2083' := range_checked_add_right rc_h_range_check_ptr\u2083,try { norm_cast at rc_h_range_check_ptr\u2083' },\n  use_only [range_check_ptr\u2083, hl_range_check_ptr\u2083],\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\u2081, htv_res, htv_range_check_ptr\u2082, 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\u2083] }, },\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 {\u03b1 : Type*} (f : \u03b1 \u2192 \u03b1)\n  : \u2200 (n : \u2115) (x0 : \u03b1), 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 \u2245 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 [\u2190 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 \u27f6 Y) [is_iso f]\n  {x : X} {y : Y} : f x = y \u2192 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 \u27f6 X) [is_iso f] : \u2200 (g g' : Y \u27f6 Z), inv f \u226b g = inv f \u226b g' \u2194 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 \u2964 D) {X Y : C} (f g : X \u27f6 Y)\n  : parallel_pair f g \u22d9 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 \u2964 D) {X Y : C} (f g : X \u27f6 Y)\n  (c : cocone (parallel_pair f g \u22d9 F)) : cocone (parallel_pair (F.map f) (F.map g)) := {\n    X := c.X,\n    \u03b9 := eq_to_hom (parallel_pair_comp F f g).symm \u226b c.\u03b9\n  }\n\ndef parallel_pair_comp.cocone_pair_to_cocone_comp\n  {C : Type*} {D : Type*} [category C] [category D] (F : C \u2964 D) {X Y : C} (f g : X \u27f6 Y)\n  (c : cocone (parallel_pair (F.map f) (F.map g))) : cocone (parallel_pair f g \u22d9 F) := {\n    X := c.X,\n    \u03b9 := eq_to_hom (parallel_pair_comp F f g) \u226b c.\u03b9\n  }\n\ndef parallel_pair_comp.is_colimit_comp_to_is_colimit_pair\n  {C : Type*} {D : Type*} [category C] [category D] (F : C \u2964 D) {X Y : C} (f g : X \u27f6 Y)\n  (c : cocone (parallel_pair f g \u22d9 F)) (hc : is_colimit c)\n  : is_colimit (parallel_pair_comp.cocone_comp_to_cocone_pair F f g c) := {\n    desc := \u03bb 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' := \u03bb s m h, hc.uniq' (parallel_pair_comp.cocone_pair_to_cocone_comp F f g s) m\n                               (\u03bb u, by { refine eq.trans _ (congr_arg (\u03bb w, nat_trans.app (eq_to_hom (parallel_pair_comp F f g)) u \u226b w) (h u)),\n                                          refine eq.trans _ (category.assoc _ _ _),\n                                          refine congr_arg (\u03bb w, w \u226b 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 \u2964 D) {X Y : C} (f g : X \u27f6 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 := \u03bb 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' := \u03bb s m h, hc.uniq' (parallel_pair_comp.cocone_comp_to_cocone_pair F f g s) m\n                               (\u03bb u, by { refine eq.trans _ (congr_arg (\u03bb w, nat_trans.app (eq_to_hom (parallel_pair_comp F f g).symm) u \u226b w) (h u)),\n                                          refine eq.trans _ (category.assoc _ _ _),\n                                          refine congr_arg (\u03bb w, w \u226b 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 \u27f6 X)\n  (k : \u2115) : @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 \u2190 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] {\u2130 : Type*} [category \u2130]\n  : (C \u2964 \u2130)\u1d52\u1d56 \u2964 \u2130 \u2964 C\u1d52\u1d56 \u2964 Type u := \n  category_theory.functor.op_hom _ _\n  \u22d9 whiskering_left C\u1d52\u1d56 \u2130\u1d52\u1d56 (Type u)\n  \u22d9 (whiskering_left _ _ _).obj yoneda\n\nlemma restricted_yoneda_functor_obj {C : Type u} [small_category C] {\u2130 : Type*} [category \u2130]\n  (A : C \u2964 \u2130) : 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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E)\n  : cones.functoriality K (F \u22d9 G)\n  \u2245 cones.functoriality K F\n    \u22d9 cones.functoriality (K \u22d9 F) G\n    \u22d9 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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E)\n  : cones.functoriality K (F \u22d9 G) \u22d9 cones.postcompose (functor.associator K F G).inv\n  \u2245 cones.functoriality K F \u22d9 cones.functoriality (K \u22d9 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  \u226a\u226b ((whiskering_right _ _ _).obj (cones.postcompose (functor.associator K F G).inv)).map_iso\n        (functor.associator (cones.functoriality K F) (cones.functoriality (K \u22d9 F) G)\n                            (cones.postcompose (K.associator F G).hom)).symm\n  \n  \u226a\u226b (functor.associator _ _ _)\n  \u226a\u226b ((whiskering_left _ _ _).obj _).map_iso\n        ((limits.cones.postcompose_comp _ _).symm \u226a\u226b\n          by { rw (K.associator F G).hom_inv_id, exact limits.cones.postcompose_id })\n  \u226a\u226b (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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E) (c : cone K)\n  : (F \u22d9 G).map_cone c\n  \u2245 (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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E) (c : cone K)\n  : (cones.postcompose (functor.associator K F G).inv).obj ((F \u22d9 G).map_cone c)\n  \u2245 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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E)\n  : cocones.functoriality K (F \u22d9 G)\n  \u2245 cocones.functoriality K F\n    \u22d9 cocones.functoriality (K \u22d9 F) G\n    \u22d9 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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E)\n  : cocones.functoriality K (F \u22d9 G) \u22d9 cocones.precompose (functor.associator K F G).inv\n  \u2245 cocones.functoriality K F \u22d9 cocones.functoriality (K \u22d9 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  \u226a\u226b ((whiskering_right _ _ _).obj (cocones.precompose (functor.associator K F G).inv)).map_iso\n        (functor.associator (cocones.functoriality K F) (cocones.functoriality (K \u22d9 F) G)\n                            (cocones.precompose (K.associator F G).hom)).symm\n  \n  \u226a\u226b (functor.associator _ _ _)\n  \u226a\u226b ((whiskering_left _ _ _).obj _).map_iso\n        ((limits.cocones.precompose_comp _ _).symm \u226a\u226b\n          by { rw (K.associator F G).inv_hom_id, exact limits.cocones.precompose_id })\n  \u226a\u226b (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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E) (c : cocone K)\n  : (F \u22d9 G).map_cocone c\n  \u2245 (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 \u2964 C) (F : C \u2964 D) (G : D \u2964 E) (c : cocone K)\n  : (cocones.precompose (functor.associator K F G).inv).obj ((F \u22d9 G).map_cocone c)\n  \u2245 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 \u2964 C}\n  {C' : Type*} [category C'] (F : C \u2964 D) (e : C \u224c C')\n  (h : preserves_limit (K \u22d9 e.functor) (e.inverse \u22d9 F))\n  : preserves_limit K F :=\nbegin\n  constructor, intros c hc,\n  let \u03b1 : K \u22d9 F \u2245 (K \u22d9 e.functor) \u22d9 (e.inverse \u22d9 F) :=\n  calc K \u22d9 F \u2245 K \u22d9 (\ud835\udfed C \u22d9 F) : ((whiskering_left _ _ _).obj K).map_iso F.left_unitor.symm\n          ... \u2245 K \u22d9 ((e.functor \u22d9 e.inverse) \u22d9 F) : ((whiskering_left _ _ _).obj K).map_iso\n                                                          (((whiskering_right _ _ _).obj F).map_iso\n                                                            e.unit_iso)\n          ... \u2245 K \u22d9 (e.functor \u22d9 (e.inverse \u22d9 F)) : ((whiskering_left _ _ _).obj K).map_iso \n                                                          (functor.associator _ _ _)\n          ... \u2245 (K \u22d9 e.functor) \u22d9 (e.inverse \u22d9 F) : functor.associator _ _ _,\n  refine is_limit.equiv_of_nat_iso_of_iso \u03b1.symm\n                                          ((e.inverse \u22d9 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 [\u2190 F.map_comp, \u2190 F.map_comp],\n      refine congr_arg _ _,\n      rw [\u2190 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 \u2964 C}\n  {C' : Type*} [category C'] (F : C \u2964 D) (e : C \u224c C')\n  (h : preserves_colimit (K \u22d9 e.functor) (e.inverse \u22d9 F))\n  : preserves_colimit K F :=\nbegin\n  constructor, intros c hc,\n  let \u03b1 : K \u22d9 F \u2245 (K \u22d9 e.functor) \u22d9 (e.inverse \u22d9 F) :=\n  calc K \u22d9 F \u2245 K \u22d9 (\ud835\udfed C \u22d9 F) : ((whiskering_left _ _ _).obj K).map_iso F.left_unitor.symm\n          ... \u2245 K \u22d9 ((e.functor \u22d9 e.inverse) \u22d9 F) : ((whiskering_left _ _ _).obj K).map_iso\n                                                          (((whiskering_right _ _ _).obj F).map_iso\n                                                            e.unit_iso)\n          ... \u2245 K \u22d9 (e.functor \u22d9 (e.inverse \u22d9 F)) : ((whiskering_left _ _ _).obj K).map_iso \n                                                          (functor.associator _ _ _)\n          ... \u2245 (K \u22d9 e.functor) \u22d9 (e.inverse \u22d9 F) : functor.associator _ _ _,\n  refine is_colimit.equiv_of_nat_iso_of_iso \u03b1.symm\n                                            ((e.inverse \u22d9 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 [\u2190 F.map_comp, \u2190 F.map_comp],\n      refine congr_arg _ _,\n      rw [\u2190 functor.comp_map],\n      rw \u2190 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 \u2964 C}\n  {D' : Type*} [category D'] (F : C \u2964 D) (e : D \u224c D')\n  (h : preserves_colimit K (F \u22d9 e.functor))\n  : preserves_colimit K F :=\n  @limits.preserves_colimit_of_nat_iso _ _ _ _ _ _ _ _ _\n    (functor.associator _ _ _ \u226a\u226b ((whiskering_left _ _ _).obj F).map_iso e.unit_iso.symm\n                              \u226a\u226b functor.right_unitor _)\n    (@limits.comp_preserves_colimit C _ D' _ J _ K D _ (F \u22d9 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 \u2245 Cat.of D) : C \u224c D :=\n  \u27e8F.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 }\u27e9.\n\nlemma colimit_iso_colimit_cocone_desc {J C : Type*} [category J] [category C]\n  (F : J \u2964 C) [has_colimit F] (c : colimit_cocone F) (c' : cocone F)\n  : (colimit.iso_colimit_cocone c).inv \u226b colimit.desc F c' = c.is_colimit.desc c' :=\n by { apply c.is_colimit.hom_ext, intro j, simp }\n\n-- universes v\u2081 v\u2082 v\u2083 v\u2084 u\u2081 u\u2082 u\u2083 u\u2084 \n-- I think the universe levels are borked :(\n-- def comma.cocone_of_preserves_is_colimit'\n--   {J : Type u\u2081} [small_category.{u\u2081} J] {A : Type u\u2082}\n--   [category.{(max u\u2081 u\u2082) u\u2082} A] {B : Type u\u2083}\n--   [category.{(max u\u2081 u\u2083) u\u2083} B] {T : Type u\u2084}\n--   [category.{(max u\u2081 u\u2084) u\u2084} T] {L : A \u2964 T} {R : B \u2964 T}\n--   (F : J \u2964 comma L R)\n--   [preserves_colimit (F \u22d9 comma.fst L R) L]\n--   {c\u2081 : cocone (F \u22d9 comma.fst L R)} (t\u2081 : is_colimit c\u2081)\n--   {c\u2082 : cocone (F \u22d9 comma.snd L R)} (t\u2082 : is_colimit c\u2082) :\n--   is_colimit (comma.cocone_of_preserves.{u\u2081} F t\u2081 c\u2082) :=\n-- { desc := \u03bb s,\n--   { left := t\u2081.desc ((fst L R).map_cocone s),\n--     right := t\u2082.desc ((snd L R).map_cocone s),\n--     w' := (is_colimit_of_preserves L t\u2081).hom_ext $ \u03bb j,\n--     begin\n--       rw [cocone_of_preserves_X_hom, (is_colimit_of_preserves L t\u2081).fac_assoc,\n--         colimit_auxiliary_cocone_\u03b9_app, assoc, \u2190R.map_comp, t\u2082.fac, L.map_cocone_\u03b9_app,\n--         \u2190L.map_comp_assoc, t\u2081.fac],\n--       exact (s.\u03b9.app j).w,\n--     end },\n--   uniq' := \u03bb s m w, comma_morphism.ext _ _\n--       (t\u2081.uniq ((fst L R).map_cocone s) _ (by simp [\u2190w]))\n--       (t\u2082.uniq ((snd L R).map_cocone s) _ (by simp [\u2190w])) }\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\u2081 u\u2082\n\nopen interactive interactive.types\nopen lean.parser nat tactic\n\nmeta def get_ext_subject : expr \u2192 tactic name\n| (expr.pi n bi d b) :=\n  do v  \u2190 mk_local' n bi d,\n     b' \u2190 whnf $ b.instantiate_var v,\n     get_ext_subject b'\n| (expr.app _ e) :=\n  do t \u2190 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 \u2190 pp t,\n       fail format!\"only constants and Pi types are supported: {t}\"\n| e := fail format!\"Only expressions of the form `_ \u2192 _ \u2192 ... \u2192 R ... e are supported: {e}\"\n\nopen native\n\n@[reducible] def ext_param_type := option name \u2295 option name\n\nmeta def opt_minus : lean.parser (option name \u2192 ext_param_type) :=\nsum.inl <$ tk \"-\" <|> pure sum.inr\n\nmeta def ext_param :=\nopt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets \"(\" \")\" (tk \"\u2192\" <|> tk \"->\") <|>\n                none <$  tk \"*\" <|>\n                some <$> ident )\n\nmeta def saturate_fun : name \u2192 tactic expr\n| (name.mk_numeral 0 name.anonymous) :=\ndo v\u2080 \u2190 mk_mvar,\n   v\u2081 \u2190 mk_mvar,\n   return $ v\u2080.imp v\u2081\n| (name.mk_numeral 1 name.anonymous) :=\ndo u \u2190 mk_meta_univ,\n   pure $ expr.sort u\n| n :=\ndo e \u2190 resolve_constant n >>= mk_const,\n   a \u2190 get_arity e,\n   e.mk_app <$> (list.iota a).mmap (\u03bb _, mk_mvar)\n\nmeta def equiv_type_constr (n n' : name) : tactic unit :=\ndo e  \u2190 saturate_fun n,\n   e' \u2190 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 : \u2200 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 [(\u2192),thunk,stream]] funext\n ```\n\n Those parameters are cumulative. The following are equivalent:\n\n ```\n attribute [extensionality [(\u2192),thunk]] funext\n attribute [extensionality [stream]] funext\n ```\n and\n ```\n attribute [extensionality [(\u2192),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 : \u2200 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 : \u2200 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 : \u2200 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 \u00d7 list ext_param_type \u00d7 list name \u00d7 list (name \u00d7 name)) :=\n{ name := `extensionality,\n  descr := \"lemmas usable by `ext` tactic\",\n  cache_cfg := { mk_cache := \u03bb ls,\n                          do { attrs \u2190 ls.mmap $ \u03bb l,\n                                     do { \u27e8_,_,ls,_\u27e9 \u2190 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 \u2190 pure <$> ext_param <|> list_of ext_param <|> pure [],\n         m \u2190 extensional_attribute.get_cache,\n         pure $ (ff,ls,[],m.to_list)  },\n  after_set := some $ \u03bb n _ b,\n    do (ff,ls,_,ls') \u2190 extensional_attribute.get_param n | pure (),\n       s \u2190 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'' \u222a (ls'.filter $ \u03bb 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 [(\u2192),thunk]] _root_.funext\n\nnamespace ulift\n@[extensionality] lemma ext {\u03b1 : Type u\u2081} (X Y : ulift.{u\u2082} \u03b1) (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 \u2192 tactic ext_patt\n| [] := try intros $> []\n| (x::xs) :=\ndo tgt \u2190 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 \u2190 target >>= get_ext_subject,\n   m \u2190 extensional_attribute.get_cache,\n   do { rule \u2190 m.find subject,\n        applyc rule } <|>\n     do { ls \u2190 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 \u2192 option \u2115 \u2192 tactic unit\n| _  (some 0) := skip\n| xs n        := focus1 $ do\n  ys \u2190 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  \u03b1 \u03b2 : Type,\n  f g : \u03b1 \u2192 set \u03b2\n  \u22a2 f = g\n  ```\n\n  applying `ext x y` yields:\n\n  ```\n  \u03b1 \u03b2 : Type,\n  f g : \u03b1 \u2192 set \u03b2,\n  x : \u03b1,\n  y : \u03b2\n  \u22a2 y \u2208 f x \u2194 y \u2208 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 \u2192 parse (tk \":\" *> small_nat)? \u2192 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": "/-\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\n! This file was ported from Lean 3 source module init.control.lift\n! leanprover-community/mathlib commit 9af482290ef68e8aaa5ead01aa7b09b7be7019fd\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.Function\nimport Leanbin.Init.Coe\nimport Leanbin.Init.Control.Monad\n\nuniverse 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 HasMonadLift (m : Type u \u2192 Type v) (n : Type u \u2192 Type w) where\n  monadLift : \u2200 {\u03b1}, m \u03b1 \u2192 n \u03b1\n#align has_monad_lift HasMonadLift\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 HasMonadLiftT (m : Type u \u2192 Type v) (n : Type u \u2192 Type w) where\n  monadLift : \u2200 {\u03b1}, m \u03b1 \u2192 n \u03b1\n#align has_monad_lift_t HasMonadLiftT\n\nexport HasMonadLiftT (monadLift)\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]\ndef hasMonadLiftToHasCoe {m n} [HasMonadLiftT m n] {\u03b1} : Coe (m \u03b1) (n \u03b1) :=\n  \u27e8monadLift\u27e9\n#align has_monad_lift_to_has_coe hasMonadLiftToHasCoe\n\ninstance (priority := 100) hasMonadLiftTTrans (m n o) [HasMonadLiftT m n] [HasMonadLift n o] :\n    HasMonadLiftT m o :=\n  \u27e8fun \u03b1 ma => HasMonadLift.monadLift (monadLift ma : n \u03b1)\u27e9\n#align has_monad_lift_t_trans hasMonadLiftTTrans\n\ninstance hasMonadLiftTRefl (m) : HasMonadLiftT m m :=\n  \u27e8fun \u03b1 => id\u27e9\n#align has_monad_lift_t_refl hasMonadLiftTRefl\n\n@[simp]\ntheorem monadLift_refl {m : Type u \u2192 Type v} {\u03b1} : (monadLift : m \u03b1 \u2192 m \u03b1) = id :=\n  rfl\n#align monad_lift_refl monadLift_refl\n\n/- warning: monad_functor -> MonadFunctor is a dubious translation:\nlean 3 declaration is\n  (Type.{u1} -> Type.{u2}) -> (Type.{u1} -> Type.{u2}) -> (Type.{u1} -> Type.{u3}) -> (Type.{u1} -> Type.{u3}) -> Sort.{max (succ (succ u1)) (succ u2) (succ u3)}\nbut is expected to have type\n  (Type.{u1} -> Type.{u2}) -> (Type.{u1} -> Type.{u3}) -> Sort.{max (max (succ (succ u1)) (succ u2)) (succ u3)}\nCase conversion may be inaccurate. Consider using '#align monad_functor MonadFunctor\u2093'. -/\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 MonadFunctor (m m' : Type u \u2192 Type v) (n n' : Type u \u2192 Type w) where\n  monadMap {\u03b1 : Type u} : (\u2200 {\u03b1}, m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1\n#align monad_functor MonadFunctor\n\n/- warning: monad_functor_t -> MonadFunctorT is a dubious translation:\nlean 3 declaration is\n  (Type.{u1} -> Type.{u2}) -> (Type.{u1} -> Type.{u2}) -> (Type.{u1} -> Type.{u3}) -> (Type.{u1} -> Type.{u3}) -> Sort.{max (succ (succ u1)) (succ u2) (succ u3)}\nbut is expected to have type\n  (Type.{u1} -> Type.{u2}) -> (Type.{u1} -> Type.{u3}) -> Sort.{max (max (succ (succ u1)) (succ u2)) (succ u3)}\nCase conversion may be inaccurate. Consider using '#align monad_functor_t MonadFunctorT\u2093'. -/\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 MonadFunctorT (m m' : Type u \u2192 Type v) (n n' : Type u \u2192 Type w) where\n  monadMap {\u03b1 : Type u} : (\u2200 {\u03b1}, m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1\n#align monad_functor_t MonadFunctorT\n\nexport MonadFunctorT (monadMap)\n\ninstance (priority := 100) monadFunctorTTrans (m m' n n' o o') [MonadFunctorT m m' n n']\n    [MonadFunctor n n' o o'] : MonadFunctorT m m' o o' :=\n  \u27e8fun \u03b1 f => MonadFunctor.monadMap fun \u03b1 => (monadMap @f : n \u03b1 \u2192 n' \u03b1)\u27e9\n#align monad_functor_t_trans monadFunctorTTrans\n\ninstance monadFunctorTRefl (m m') : MonadFunctorT m m' m m' :=\n  \u27e8fun \u03b1 f => f\u27e9\n#align monad_functor_t_refl monadFunctorTRefl\n\n@[simp]\ntheorem monadMap_refl {m m' : Type u \u2192 Type v} (f : \u2200 {\u03b1}, m \u03b1 \u2192 m' \u03b1) {\u03b1} :\n    (monadMap @f : m \u03b1 \u2192 m' \u03b1) = f :=\n  rfl\n#align monad_map_refl monadMap_refl\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 {\u03b1 : Type} (x : my_monad \u03b1) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n    def my_monad.run {\u03b1 : Type} (x : my_monad \u03b1) := monad_run.run x\n    ```\n    -/\nclass MonadRun (out : outParam <| Type u \u2192 Type v) (m : Type u \u2192 Type v) where\n  run {\u03b1 : Type u} : m \u03b1 \u2192 out \u03b1\n#align monad_run MonadRun\n\nexport MonadRun (run)\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/Control/Lift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.044680869000553285, "lm_q1q2_score": 0.014640504424604205}}
{"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 \u2192 X or B \u2192 X\n--  > project goes from X \u2192 Option A or X \u2192 Option B\nclass Prismatic (e : Type \u2192 Type) (u : Type \u2192 Type v) where\n    inject : e \u03b1 \u2192 u \u03b1\n    project : u \u03b1 \u2192 Option (e \u03b1)\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 \u2192 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 \u2192 Term \u2192 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 \u2192 CommandElabM CtorView := \n      fun subterm => do\n        let ty \u2190 `({x : Type} \u2192 $subterm x \u2192 $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 \u2190 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? := (\u2190 `(Type \u2192 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 \u2190\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 \u00d7 TSyntax `term) \u2192 TermElabM (TSyntax `Lean.Parser.Term.matchAlt) := fun \u27e8subval, collapser\u27e9 => 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 \u2190 Array.sequenceMap (Array.zip subidsArray collapsersArray) evalBranch\n    let collapserFunc \u2190 `(fun {\u03b1 : Type} (sumVal : $sumid \u03b1) => (match sumVal with $branches:matchAlt* : $collapsertarget \u03b1))\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 \u2192 OtherI y\n  | C : y \u2192 y \u2192 OtherI y\n    deriving Repr\n\ninductive EcksI (x : Type) (y : Type) where\n| X : x \u2192 y \u2192 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": "/-\nCopyright (c) E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: E.W.Ayers\n-/\nprelude\nimport init.function\nimport init.data.option.basic\nimport init.util\nimport init.meta.tactic\nimport init.meta.mk_dec_eq_instance\nimport init.meta.json\n\n/-! A component is a piece of UI which may contain internal state. Use component.mk to build new components.\n\n## Using widgets.\n\nTo make a widget, you need to make a custom executor object and then instead of calling `save_info_thunk` you call `save_widget`.\n\nAdditionally, you will need a compatible build of the vscode extension or web app to use widgets in vscode.\n\n## How it works:\n\nThe design is inspired by React.\nIf you are familiar with using React or Elm or a similar functional UI framework then that's helpful for this.\nThe [React article on reconciliation](https://reactjs.org/docs/reconciliation.html) might be helpful.\n\nOne can imagine making a UI for a particular object as just being a function `f : \u03b1 \u2192 UI` where `UI` is some inductive datatype for buttons, textboxes, lists and so on.\nThe process of evaluating `f` is called __rendering__.\nSo for example `\u03b1` could be `tactic_state` and the function renders a goal view.\n\n## HTML\n\nFor our purposes, `UI` is an HTML tree and is written `html \u03b1 : Type`. I'm going to assume some familiarity with HTML for the purposes of this document.\nAn HTML tree is composed of elements and strings.\nEach element has a tag such as \"div\", \"span\", \"article\" and so on and a set of attributes and child html.\nUse the helper function `h : string \u2192 list (attr \u03b1) \u2192 list (html \u03b1) \u2192 html \u03b1` to build new pieces of `html`. So for example:\n\n```lean\nh \"ul\" [] [\n     h \"li\" [] [\"this is list item 1\"],\n     h \"li\" [style [(\"color\", \"blue\")]] [\"this is list item 2\"],\n     h \"hr\" [] [],\n     h \"li\" [] [\n          h \"span\" [] [\"there is a button here\"],\n          h \"button\" [on_click (\u03bb _, 3)] [\"click me!\"]\n     ]\n]\n```\nHas the type `html nat`.\nThe `nat` type is called the __action__ and whenever the user interacts with the UI, the html will emit an object of type `nat`.\nSo for example if the user clicks the button above, the html will 'emit' `3`.\nThe above example is compiled to the following piece of html:\n\n```html\n<ul>\n  <li>this is list item 1</li>\n  <li style=\"{ color: blue; }\">this is list item 2</li>\n  <hr/>\n  <li>\n     <span>There is a button here</span>\n     <button onClick=\"[handler]\">click me!</button>\n  </li>\n</ul>\n```\n\n## Components\n\nIn order for the UI to react to events, you need to be able to take these actions \u03b1 and alter some state.\nTo do this we use __components__. `component` takes two type arguments: `\u03c0` and `\u03b1`. `\u03b1` is called the 'action' and `\u03c0` are the 'props'.\nThe props can be thought of as a kind of wrapped function domain for `component`. So given `C : component nat \u03b1`, one can turn this into html with\n`html.of_component 4 C : html \u03b1`.\n\nThe base constructor for a component is `pure`:\n```lean\nmeta def Hello : component string \u03b1 := component.pure (\u03bb s, [\"hello, \", s, \", good day!\"])\n\n#html Hello \"lean\" -- renders \"hello, lean, good day!\"\n```\nSo here a pure component is just a simple function `\u03c0 \u2192 list (html \u03b1)`.\nHowever, one can augment components with __hooks__.\nThe hooks available for compoenents are listed in the inductive definition for component.\n\nHere we will just look at the `with_state` hook, which can be used to build components with inner state.\n\n```\nmeta inductive my_action\n| increment\n| decrement\nopen my_action\n\nmeta def Counter : component unit \u03b1 :=\ncomponent.with_state\n     my_action          -- the action of the inner component\n     int                -- the state\n     (\u03bb _, 0)           -- initialise the state\n     (\u03bb _ _ s, s)       -- update the state if the props change\n     (\u03bb _ s a,          -- update the state if an action was received\n          match a with\n          | increment := (s + 1, none) -- replace `none` with `some _` to emit an action\n          | decrement := (s - 1, none)\n          end\n     )\n$ component.pure (\u03bb \u27e8state, \u27e8\u27e9\u27e9, [\n     button \"+\" (\u03bb _, increment),\n     to_string state,\n     button \"-\" (\u03bb _, decrement)\n  ])\n\n#html Counter ()\n```\n\nYou can add many hooks to a component.\n\n- `filter_map_action` lets you filter or map actions that are emmitted by the component\n- `map_props` lets you map the props.\n- `with_should_update` will not re-render the child component if the given test returns false. This can be useful for efficiency.\n- `with_state` discussed above.`\n- `with_mouse` subscribes the component to the mouse state, for example whether or not the mouse is over the component. See the `tests/lean/widget/widget_mouse.lean` test for an example.\n\nGiven an active document, Lean (in server mode) maintains a set of __widgets__ for the document.\nA widget is a component `c`, some `p : Props` and an internal state-manager which manages the states\nof the component and subcomponents and also handles the routing of events from the UI.\n\n## Reconciliation\n\nIf a parent component's state changes, this can cause child components to change position or to appear and dissappear.\nHowever we want to preserve the state of these child components where we can.\nThe UI system will try to match up these child components through a process called __reconciliation__.\n\nReconciliation will make sure that the states are carried over correctly and will also not rerender subcomponents if they haven't changed their props or state.\nTo compute whether two components are the same, the system will perform a hash on their VM objects.\nNot all VM objects can be hashed, so it's important to make sure that any items that you expect to change over the lifetime of the component are fed through the 'Props' argument.\nThis is why we need the props argument on `component`.\nThe reconciliation engine uses the `props_eq` predicate passed to the component constructor to determine whether the props have changed and hence whether the component should be re-rendered.\n\n## Keys\n\nIf you have some list of components and the list changes according to some state, it is important to add keys to the components so\nthat if two components change order in the list their states are preserved.\nIf you don't provide keys or there are duplicate keys then you may get some strange behaviour in both the Lean widget engine and react.\n\nIt is possible to use incorrect HTML tags and attributes, there is (currently) no type checking that the result is a valid piece of HTML.\nSo for example, the client widget system will error if you add a `text_change_event` attribute to anything other than an element tagged with `input`.\n\n## Styles with Tachyons\n\nThe widget system assumes that a stylesheet called 'tachyons' is present.\nYou can find documentation for this stylesheet at [Tachyons.io](http://tachyons.io/).\nTachyons was chosen because it is very terse and allows arbitrary styling without using inline styles and without needing to dynamically load a stylesheet.\n\n## Further work (up for grabs!)\n\n- Add type checking for html.\n- Better error handling when the html tree is malformed.\n- Better error handling when keys are malformed.\n- Add a 'with_task' which lets long-running operations (eg running `simp`) not block the UI update.\n- Timers, animation (ambitious).\n- More event handlers\n- Drag and drop support.\n- The current perf bottleneck is sending the full UI across to the server for every update.\n  Instead, it should be possible to send a smaller [JSON Patch](http://jsonpatch.com).\n  Which is already supported by `json.hpp` and javascript ecosystem.\n\n-/\n\nnamespace widget\n\ninductive mouse_event_kind\n| on_click\n| on_mouse_enter\n| on_mouse_leave\n\n/-- An effect is some change that the widget makes outside of its own state.\nUsually, giving instructions to the editor to perform some task.\n- `insert_text_relative` will insert at a line relative to the position of the widget.\n- `insert_text_absolute` will insert text at the precise position given.\n- `reveal_position` will move the editor to view the given position.\n- `highlight_position` will add a text highlight to the given position.\n- `clear_highlighting` will remove all highlights created with `highlight_position`.\n- `copy_text` will copy the given text to the clipboard.\n- `custom` can be used to pass custom effects to the client without having to recompile Lean.\n-/\nmeta inductive effect : Type\n| insert_text_absolute (file_name : option string) (p : pos) (text : string)\n| insert_text_relative (relative_line : int) (text : string)\n| reveal_position (file_name : option string) (p : pos)\n| highlight_position (file_name : option string) (p : pos)\n| clear_highlighting\n| copy_text (text : string)\n| custom (key : string) (value : string)\n\nmeta def effects := list effect\n\nmeta mutual inductive component, html, attr\n\nwith component : Type \u2192 Type \u2192 Type\n| pure\n     {Props Action : Type}\n     (view : Props \u2192 list (html Action))\n     : component Props Action\n| filter_map_action\n     {Props InnerAction OuterAction}\n     (action_map : Props \u2192 InnerAction \u2192 option OuterAction)\n     : component Props InnerAction \u2192 component Props OuterAction\n| map_props\n     {Props1 Props2 Action}\n     (map : Props2 \u2192 Props1)\n     : component Props1 Action \u2192 component Props2 Action\n| with_should_update\n     {Props Action : Type}\n     (should_update : \u03a0 (old new : Props), bool)\n     : component Props Action \u2192 component Props Action\n| with_state\n     {Props Action : Type}\n     (InnerAction State : Type)\n     (init : Props \u2192 State)\n     (props_changed : Props \u2192 Props \u2192 State \u2192 State)\n     (update : Props \u2192 State \u2192 InnerAction \u2192 State \u00d7 option Action)\n     : component (State \u00d7 Props) InnerAction \u2192 component Props Action\n| with_effects\n     {Props Action : Type}\n     (emit : Props \u2192 Action \u2192 effects)\n     : component Props Action \u2192 component Props Action\n\nwith html : Type \u2192 Type\n| element      {\u03b1 : Type} (tag : string) (attrs : list (attr \u03b1)) (children : list (html \u03b1)) : html \u03b1\n| of_string    {\u03b1 : Type} : string \u2192 html \u03b1\n| of_component {\u03b1 : Type} {Props : Type} : Props \u2192 component Props \u03b1 \u2192 html \u03b1\n\nwith attr : Type \u2192 Type\n| val               {\u03b1 : Type} (name : string) (value : json) : attr \u03b1\n| mouse_event       {\u03b1 : Type} (kind : mouse_event_kind) (handler : unit \u2192 \u03b1) : attr \u03b1\n| style             {\u03b1 : Type} : list (string \u00d7 string) \u2192 attr \u03b1\n| tooltip           {\u03b1 : Type} : html \u03b1 \u2192 attr \u03b1\n| text_change_event {\u03b1 : Type} (handler : string \u2192 \u03b1) : attr \u03b1\n\nvariables {\u03b1 \u03b2 : Type} {\u03c0 : Type}\n\nnamespace component\n\nmeta def map_action (f : \u03b1 \u2192 \u03b2) : component \u03c0 \u03b1 \u2192 component \u03c0 \u03b2\n| c := filter_map_action (\u03bb p a, some $ f a) c\n\n/-- Returns a component that will never trigger an action. -/\nmeta def ignore_action : component \u03c0 \u03b1 \u2192 component \u03c0 \u03b2\n| c := component.filter_map_action (\u03bb p a, none) c\n\nmeta def ignore_props : component unit \u03b1 \u2192 component \u03c0 \u03b1\n| c := with_should_update (\u03bb a b, ff) $ component.map_props (\u03bb p, ()) c\n\nmeta instance : has_coe (component \u03c0 empty) (component \u03c0 \u03b1) :=\n\u27e8component.filter_map_action (\u03bb p x, none)\u27e9\n\nmeta instance : has_coe_to_fun (component \u03c0 \u03b1) (\u03bb c, \u03c0 \u2192 html \u03b1) :=\n\u27e8\u03bb c p, html.of_component p c\u27e9\n\nmeta def stateful {\u03c0 \u03b1 : Type}\n     (\u03b2 \u03c3 : Type)\n     (init : \u03c0 \u2192 option \u03c3 \u2192 \u03c3)\n     (update : \u03c0 \u2192 \u03c3 \u2192 \u03b2 \u2192 \u03c3 \u00d7 option \u03b1)\n     (view : \u03c0 \u2192 \u03c3 \u2192 list (html \u03b2))\n     : component \u03c0 \u03b1 :=\nwith_state \u03b2 \u03c3 (\u03bb p, init p none) (\u03bb _ p s, init p $ some s) update (component.pure (\u03bb \u27e8s,p\u27e9, view p s))\n\nmeta def stateless {\u03c0 \u03b1 : Type} [decidable_eq \u03c0] (view : \u03c0 \u2192 list (html \u03b1)) : component \u03c0 \u03b1 :=\ncomponent.with_should_update (\u03bb p1 p2, p1 \u2260 p2)\n$ component.pure view\n\n/-- Causes the component to only update on a props change when `test old_props new_props` yields `ff`. -/\nmeta def with_props_eq (test : \u03c0 \u2192 \u03c0 \u2192 bool) : component \u03c0 \u03b1 \u2192 component \u03c0 \u03b1\n| c := component.with_should_update (\u03bb x y, bnot $ test x y) c\n\nend component\n\nmeta mutual def attr.map_action, html.map_action (f : \u03b1 \u2192 \u03b2)\nwith attr.map_action : attr \u03b1 \u2192 attr \u03b2\n| (attr.val k v) := attr.val k v\n| (attr.style s) := attr.style s\n| (attr.tooltip h) := attr.tooltip $ html.map_action h\n| (attr.mouse_event k a) := attr.mouse_event k (f \u2218 a)\n| (attr.text_change_event a) := attr.text_change_event (f \u2218 a)\nwith html.map_action : html \u03b1 \u2192 html \u03b2\n| (html.element t a c) := html.element t (list.map attr.map_action a) (list.map html.map_action c)\n| (html.of_string s) := html.of_string s\n| (html.of_component p c) := html.of_component p $ component.map_action f c\n\nmeta instance attr.is_functor : functor attr :=\n{ map := @attr.map_action }\n\nmeta instance html.is_functor : functor html :=\n{ map := \u03bb _ _, html.map_action }\n\nnamespace html\n\n/-- See Note [use has_coe_t]. -/\nmeta instance to_string_coe [has_to_string \u03b2] : has_coe_t \u03b2 (html \u03b1) :=\n\u27e8html.of_string \u2218 to_string\u27e9\n\nmeta instance : has_emptyc (html \u03b1) := \u27e8of_string \"\"\u27e9\n\nmeta instance list_coe : has_coe (html \u03b1) (list (html \u03b1)) := \u27e8\u03bb x, [x]\u27e9\n\nend html\n\nmeta def as_element : html \u03b1 \u2192 option (string \u00d7 list (attr \u03b1) \u00d7 list (html \u03b1))\n| (html.element t a c) := some \u27e8t,a,c\u27e9\n| _ := none\n\nmeta def key [has_to_string \u03b2] : \u03b2 \u2192 attr \u03b1\n| s := attr.val \"key\" $ to_string s\n\nmeta def className : string \u2192 attr \u03b1\n| s := attr.val \"className\" $ s\n\nmeta def on_click : (unit \u2192 \u03b1) \u2192 attr \u03b1\n| a := attr.mouse_event mouse_event_kind.on_click a\n\nmeta def on_mouse_enter : (unit \u2192 \u03b1) \u2192 attr \u03b1\n| a := attr.mouse_event mouse_event_kind.on_mouse_enter a\n\nmeta def on_mouse_leave : (unit \u2192 \u03b1) \u2192 attr \u03b1\n| a := attr.mouse_event mouse_event_kind.on_mouse_leave a\n\n/-- Alias for `html.element`. -/\nmeta def h : string \u2192 list (attr \u03b1) \u2192 list (html \u03b1) \u2192 html \u03b1 := html.element\n/-- Alias for className. -/\nmeta def cn : string \u2192 attr \u03b1 := className\n\nmeta def button : string \u2192 thunk \u03b1 \u2192 html \u03b1\n| s t := h \"button\" [on_click t] [s]\n\nmeta def textbox : string \u2192 (string \u2192 \u03b1) \u2192 html \u03b1\n| s t := h \"input\" [attr.val \"type\" \"text\", attr.val \"value\" s, attr.text_change_event t] []\n\nmeta structure select_item (\u03b1 : Type) :=\n(result : \u03b1)\n(key : string)\n(view : list (html \u03b1))\n\n/-- Choose from a dropdown selection list. -/\nmeta def select {\u03b1} [decidable_eq \u03b1] : list (select_item \u03b1) \u2192 \u03b1 \u2192 html \u03b1\n| items value :=\n     let k := match list.filter (\u03bb i, select_item.result i = value) items with\n              | [] := \"\" | (h::_) := select_item.key h\n              end in\n     h \"select\" [\n          attr.val \"value\" k,\n          attr.val \"key\" k,\n          attr.text_change_event (\u03bb k,\n               match items.filter (\u03bb i, select_item.key i = k) with\n               | [] := undefined\n               | (h::_) := h.result\n               end\n          )]\n     $ items.map (\u03bb i, h \"option\" [attr.val \"value\" i.key] $ select_item.view i)\n\n/-- If the html is not an of_element it will wrap it in a div. -/\nmeta def with_attrs : list (attr \u03b1) \u2192  html \u03b1 \u2192 html \u03b1\n| a x := match as_element x with\n         | (some \u27e8t,as,c\u27e9) := html.element t (a ++ as) c\n         | none := html.element \"div\" a [x]\n         end\n\n/-- If the html is not an of_element it will wrap it in a div. -/\nmeta def with_attr : attr \u03b1 \u2192  html \u03b1 \u2192 html \u03b1\n| a x := with_attrs [a] x\n\nmeta def with_style : string \u2192 string \u2192 html \u03b1 \u2192 html \u03b1\n| k v h := with_attr (attr.style [(k,v)]) h\n\nmeta def with_cn : string \u2192 html \u03b1 \u2192 html \u03b1\n| s h := with_attr (className s) h\n\nmeta def with_key {\u03b2} [has_to_string \u03b2] : \u03b2 \u2192 html \u03b1 \u2192 html \u03b1\n| s h := with_attr (key s) h\n\nmeta def effect.insert_text : string \u2192 effect :=\neffect.insert_text_relative 0\n\nend widget\n\nnamespace tactic\n\n/-- Same as `tactic.save_info_thunk` except saves a widget to be displayed by a compatible infoviewer. -/\nmeta constant save_widget : pos \u2192 widget.component tactic_state empty \u2192 tactic unit\n\n/-- Outputs a widget trace position at the given position. -/\nmeta constant trace_widget_at (p : pos) (w : widget.component tactic_state empty)\n     (text := \"(widget)\") : tactic unit\n\n/-- Outputs a widget trace position at the current default trace position. -/\nmeta def trace_widget (w : widget.component tactic_state empty) (text := \"(widget)\") : tactic unit :=\ndo p \u2190 get_trace_msg_pos, trace_widget_at p w text\n\nend tactic\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/widget/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2568319913875189, "lm_q2_score": 0.05665242132616554, "lm_q1q2_score": 0.01455015418612384}}
{"text": "import Lean.Elab.Tactic.ElabTerm\nimport Lean.Elab.Tactic.Conv.Basic\n\nnamespace Lean.Elab.Tactic.Conv \nopen Meta\n\n\n\nsyntax (name := print_lhs) \"print_lhs\" : conv\nsyntax (name := print_rhs) \"print_rhs\" : conv\nsyntax (name := add_id) \"add_id\" : conv\nsyntax (name := add_foo) \"add_foo\" : conv\n\n\n@[tactic print_lhs] def printLhs : Tactic := fun stx => do\n  match stx with\n  | `(conv| print_lhs) => do\n    let lhs \u2190 getLhs\n    IO.println lhs\n    -- dbg_trace lhs\n  | _ => throwUnsupportedSyntax\n\n@[tactic print_rhs] def printRhs : Tactic := fun stx => do\n  match stx with\n  | `(conv| print_rhs) => do\n    let rhs \u2190 getRhs\n    IO.println rhs\n    -- dbg_trace rhs\n  | _ => throwUnsupportedSyntax\n\ntheorem id_eq {\u03b1} (a : \u03b1) : a = id a := by rfl\n\n@[tactic add_id] def addId : Tactic := fun stx => do\n  match stx with\n  | `(conv| add_id) => do\n    let lhs \u2190 getLhs\n    let lhs' \u2190 mkAppM `id #[lhs]\n    let eq \u2190 mkAppM `Lean.Elab.Tactic.Conv.id_eq #[lhs]\n    updateLhs lhs' eq\n    -- dbg_trace rhs\n  | _ => throwUnsupportedSyntax\n\n-- @[irreducible]\ndef foo {\u03b1} (a : \u03b1) := a\n\n@[tactic add_foo] def addFoo : Tactic := fun stx => do\n  match stx with\n  | `(conv| add_foo) => do\n    let lhs \u2190 getLhs\n    let lhs' \u2190 mkAppM `Lean.Elab.Tactic.Conv.foo #[lhs]\n    let eqGoal \u2190 mkFreshExprSyntheticOpaqueMVar (\u2190 mkEq lhs' lhs)\n\n    updateLhs lhs' eqGoal\n\n    replaceMainGoal [eqGoal.mvarId!, (\u2190 getMainGoal)]\n  | _ => throwUnsupportedSyntax\n\n\nexample (x y z : Nat) : (x + y) + z = (x + (foo y + z)) := \nby\n  conv =>\n    enter [1,1,2]\n    add_foo; (tactic => unfold foo; rfl)\n    \n  .\n  apply Nat.add_assoc\n  done\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/MyConvTactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082128783705344, "lm_q2_score": 0.0453525845865351, "lm_q1q2_score": 0.01455007459379109}}
{"text": "/-\nCopyright (c) 2021 Floris van Doorn. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Floris van Doorn\n-/\n\n/-!\n\n# Project directory locator\n\nWe use the dummy declaration in this file to locate the project directory of mathlib.\n\n-/\n\n/-- This is a dummy declaration that is used to determine the project folder of mathlib, using the\n  tactic `tactic.decl_olean`. This is used in `tactic.get_mathlib_dir`. -/\nlemma mathlib_dir_locator : true := trivial\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/project_dir.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.06371500091897545, "lm_q1q2_score": 0.01453699174485358}}
{"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 \u2192 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) \u2228\n  (\u2203 v : list (symbol T g.nt), (grammar_transforms g u v) \u2227 (grammar_derives g v w)) :=\nrelation.refl_trans_gen.cases_head ass\n\n\nlemma grammar_deri_with_prefix {w\u2081 w\u2082 : list (symbol T g.nt)}\n    (p\u1d63 : list (symbol T g.nt))\n    (ass : grammar_derives g w\u2081 w\u2082) :\n  grammar_derives g (p\u1d63 ++ w\u2081) (p\u1d63 ++ w\u2082) :=\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 \u27e8r, rin, u, v, h_bef, h_aft\u27e9,\n  use r,\n  split,\n  {\n    exact rin,\n  },\n  use p\u1d63 ++ 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\u2081 w\u2082 : list (symbol T g.nt)}\n    (p\u2092 : list (symbol T g.nt))\n    (ass : grammar_derives g w\u2081 w\u2082) :\n  grammar_derives g (w\u2081 ++ p\u2092) (w\u2082 ++ p\u2092) :=\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 \u27e8r, rin, u, v, h_bef, h_aft\u27e9,\n  use r,\n  split,\n  {\n    exact rin,\n  },\n  use u,\n  use v ++ p\u2092,\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 \u2192 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": "import tactic.lint\nimport algebra.ring.basic\n\nopen tactic\n\ndef foo1 (n m : \u2115) : \u2115 := n + 1\ndef foo2 (n m : \u2115) : m = m := by refl\nlemma foo3 (n m : \u2115) : \u2115 := n - m\nlemma foo.foo (n m : \u2115) : n \u2265 n := le_refl n\ninstance bar.bar : has_add \u2115 := by apply_instance  -- we don't check the name of instances\nlemma foo.bar (\u03b5 > 0) : \u03b5 = \u03b5 := rfl -- >/\u2265 is allowed in binders (and in fact, in all hypotheses)\n/-- Test exception in `def_lemma` linter. -/\n@[pattern] def my_exists_intro := @Exists.intro\n\nmeta def fold_over_with_cond {\u03b1} (l : list declaration) (tac : declaration \u2192 tactic (option \u03b1)) :\n  tactic (list (declaration \u00d7 \u03b1)) :=\nl.mmap_filter $ \u03bb d, option.map (\u03bb x, (d, x)) <$> tac d\n\nrun_cmd do\n  let t := name \u00d7 list \u2115,\n  e \u2190 get_env,\n  let l := e.filter (\u03bb d, e.in_current_file d.to_name \u2227 \u00ac d.is_auto_or_internal e),\n  l2 \u2190 fold_over_with_cond l (return \u2218 check_unused_arguments),\n  guard (l2.length = 4) <|> fail \"wrong length\",\n  let l2 : list (name \u00d7 list \u2115) := l2.map (\u03bb x, \u27e8x.1.to_name, x.2\u27e9),\n  guard ((\u27e8`foo1, [2]\u27e9 : t) \u2208 l2) <|> fail \"foo1\",\n  guard ((\u27e8`foo2, [1]\u27e9 : t) \u2208 l2) <|> fail \"foo2\",\n  guard ((\u27e8`foo.foo, [2]\u27e9 : t) \u2208 l2) <|> fail \"foofoo\",\n  guard ((\u27e8`foo.bar, [2]\u27e9 : t) \u2208 l2) <|> fail \"foobar\",\n  l2 \u2190 fold_over_with_cond l linter.def_lemma.test,\n  guard $ l2.length = 2,\n  let l2 : list (name \u00d7 _) := l2.map $ \u03bb x, \u27e8x.1.to_name, x.2\u27e9,\n  guard $ \u2203(x \u2208 l2), (x : name \u00d7 _).1 = `foo2,\n  guard $ \u2203(x \u2208 l2), (x : name \u00d7 _).1 = `foo3,\n  l3 \u2190 fold_over_with_cond l linter.dup_namespace.test,\n  guard $ l3.length = 1,\n  guard $ \u2203(x \u2208 l3), (x : declaration \u00d7 _).1.to_name = `foo.foo,\n  l4 \u2190 fold_over_with_cond l linter.ge_or_gt.test,\n  guard $ l4.length = 1,\n  guard $ \u2203(x \u2208 l4), (x : declaration \u00d7 _).1.to_name = `foo.foo,\n  -- guard $ \u2203(x \u2208 l4), (x : declaration \u00d7 _).1.to_name = `foo4,\n  (_, s) \u2190 lint ff,\n  guard $ \"/- (slow tests skipped) -/\\n\".is_suffix_of s.to_string,\n  (_, s2) \u2190 lint tt,\n  guard $ s.to_string \u2260 s2.to_string,\n  skip\n\n/- check customizability and nolint -/\n\nmeta def dummy_check (d : declaration) : tactic (option string) :=\nreturn $ if d.to_name.last = \"foo\" then some \"gotcha!\" else none\n\nmeta def linter.dummy_linter : linter :=\n{ test := dummy_check,\n  auto_decls := ff,\n  no_errors_found := \"found nothing.\",\n  errors_found := \"found something:\" }\n\n@[nolint dummy_linter]\ndef bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)\n\nrun_cmd do\n  (_, s) \u2190 lint tt lint_verbosity.medium [`linter.dummy_linter] tt,\n  guard $ \"/- found something: -/\\n#check @foo.foo /- gotcha! -/\\n\".is_suffix_of s.to_string\n\ndef incorrect_type_class_argument_test {\u03b1 : Type} (x : \u03b1) [x = x] [decidable_eq \u03b1] [group \u03b1] :\n  unit := ()\n\nrun_cmd do\n  d \u2190 get_decl `incorrect_type_class_argument_test,\n  x \u2190 linter.incorrect_type_class_argument.test d,\n  guard $ x = some \"These are not classes. argument 3: [_inst_1 : x = x]\"\n\nsection\ndef impossible_instance_test {\u03b1 \u03b2 : Type} [add_group \u03b1] : has_add \u03b1 := infer_instance\nlocal attribute [instance] impossible_instance_test\nrun_cmd do\n  d \u2190 get_decl `impossible_instance_test,\n  x \u2190 linter.impossible_instance.test d,\n  guard $ x = some \"Impossible to infer argument 2: {\u03b2 : Type}\"\n\ndef dangerous_instance_test {\u03b1 \u03b2 \u03b3 : Type} [ring \u03b1] [add_comm_group \u03b2] [has_coe \u03b1 \u03b2]\n  [has_inv \u03b3] : has_add \u03b2 := infer_instance\nlocal attribute [instance] dangerous_instance_test\nrun_cmd do\n  d \u2190 get_decl `dangerous_instance_test,\n  x \u2190 linter.dangerous_instance.test d,\n  guard $ x = some\n    \"The following arguments become metavariables. argument 1: {\u03b1 : Type}, argument 3: {\u03b3 : Type}\"\nend\n\nsection\ndef foo_has_mul {\u03b1} [has_mul \u03b1] : has_mul \u03b1 := infer_instance\nlocal attribute [instance, priority 1] foo_has_mul\nrun_cmd do\n  d \u2190 get_decl `foo_has_mul,\n  some s \u2190 fails_quickly 20 d,\n  guard $ \"type-class inference timed out\".is_prefix_of s\nlocal attribute [instance, priority 10000] foo_has_mul\nrun_cmd do\n  d \u2190 get_decl `foo_has_mul,\n  some s \u2190 fails_quickly 3000 d,\n  guard $ \"maximum class-instance resolution depth has been reached\".is_prefix_of s\nend\n\ninstance beta_redex_test {\u03b1} [monoid \u03b1] : (\u03bb (X : Type), has_mul X) \u03b1 := \u27e8(*)\u27e9\nrun_cmd do\n  d \u2190 get_decl `beta_redex_test,\n  x \u2190 linter.instance_priority.test d,\n  guard $ x = some \"set priority below 1000\"\n\n/- Test exception in `def_lemma` linter. -/\nrun_cmd do\n  d \u2190 get_decl `my_exists_intro,\n  t \u2190 linter.def_lemma.test d,\n  guard $ t = none\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/lint.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.039638841086350206, "lm_q1q2_score": 0.014531192301961118}}
{"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.Compiler.LCNF.Simp.SimpM\n\nnamespace Lean.Compiler.LCNF\nnamespace Simp\n\n/--\nAuxiliary function for projecting \"type class dictionary access\".\nThat is, we are trying to extract one of the type class instance elements.\nRemark: We do not consider parent instances to be elements.\nFor example, suppose `e` is `_x_4.1`, and we have\n```\n_x_2 : Monad (ReaderT Bool (ExceptT String Id)) := @ReaderT.Monad Bool (ExceptT String Id) _x_1\n_x_3 : Applicative (ReaderT Bool (ExceptT String Id)) := _x_2.1\n_x_4 : Functor (ReaderT Bool (ExceptT String Id)) := _x_3.1\n```\nThen, we will expand `_x_4.1` since it corresponds to the `Functor` `map` element,\nand its type is not a type class, but is of the form\n```\n{\u03b1 \u03b2 : Type u} \u2192 (\u03b1 \u2192 \u03b2) \u2192 ...\n```\nIn the example above, the compiler should not expand `_x_3.1` or `_x_2.1` because they are\ntype class applications: `Functor` and `Applicative` respectively.\nBy eagerly expanding them, we may produce inefficient and bloated code.\nFor example, we may be using `_x_3.1` to invoke a function that expects a `Functor` instance.\nBy expanding `_x_3.1` we will be just expanding the code that creates this instance.\n\nThe result is representing a sequence of code containing let-declarations and local function declarations (`Array CodeDecl`)\nand the free variable containing the result (`FVarId`). The resulting `FVarId` often depends only on a small\nsubset of `Array CodeDecl`. However, this method does try to filter the relevant ones.\nWe rely on the `used` var set available in `SimpM` to filter them. See `attachCodeDecls`.\n-/\npartial def inlineProjInst? (e : LetValue) : SimpM (Option (Array CodeDecl \u00d7 FVarId)) := do\n  let .proj _ i s := e | return none\n  let sType \u2190 getType s\n  unless (\u2190 isClass? sType).isSome do return none\n  let eType \u2190 e.inferType\n  unless  (\u2190 isClass? eType).isNone do return none\n  let (fvarId?, decls) \u2190 visit s [i] |>.run |>.run #[]\n  if let some fvarId := fvarId? then\n    return some (decls, fvarId)\n  else\n    eraseCodeDecls decls\n    return none\nwhere\n  visit (fvarId : FVarId) (projs : List Nat) : OptionT (StateRefT (Array CodeDecl) SimpM) FVarId := do\n    let some letDecl \u2190 findLetDecl? fvarId | failure\n    match letDecl.value with\n    | .proj _ i s => visit s (i :: projs)\n    | .fvar .. | .value .. | .erased => failure\n    | .const declName us args =>\n      if let some (.ctorInfo ctorVal) := (\u2190 getEnv).find? declName then\n        let i :: projs := projs | unreachable!\n        let arg := args[ctorVal.numParams + i]!\n        let fvarId \u2190 match arg with\n          | .fvar fvarId => pure fvarId\n          | .erased | .type .. =>\n            let auxDecl \u2190 mkLetDeclErased\n            modify (\u00b7.push (.let auxDecl))\n            pure auxDecl.fvarId\n        if projs.isEmpty then\n          return fvarId\n        else\n          visit fvarId projs\n      else\n        let some decl \u2190 getDecl? declName | failure\n        guard (decl.getArity == args.size)\n        let params := decl.instantiateParamsLevelParams us\n        let code := decl.instantiateValueLevelParams us\n        let code \u2190 betaReduce params code args (mustInline := true)\n        visitCode code projs\n\n  visitCode (code : Code) (projs : List Nat) : OptionT (StateRefT (Array CodeDecl) SimpM) FVarId := do\n    match code with\n    | .let decl k => modify (\u00b7.push (.let decl)); visitCode k projs\n    | .fun decl k => modify (\u00b7.push (.fun decl)); visitCode k projs\n    | .return fvarId => visit fvarId projs\n    | _ => eraseCode code; failure\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/Simp/InlineProj.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.04208772551257712, "lm_q1q2_score": 0.014524695350050363}}
{"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Keeley Hoek, Scott Morrison\n\n! This file was ported from Lean 3 source module tactic.simp_command\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/-!\n## #simp\nA user command to run the simplifier.\n-/\n\n\nnamespace Tactic\n\n/-- Strip all annotations of non local constants in the passed `expr`. (This is required in an\nincantation later on in order to make the C++ simplifier happy.) -/\nprivate unsafe def strip_annotations_from_all_non_local_consts {elab : Bool} (e : expr elab) :\n    expr elab :=\n  expr.unsafe_cast <|\n    e.unsafe_cast.replace fun e n =>\n      match e.is_annotation with\n      | some (_, expr.local_const _ _ _ _) => none\n      | some (_, _) => e.erase_annotations\n      | _ => none\n#align tactic.strip_annotations_from_all_non_local_consts tactic.strip_annotations_from_all_non_local_consts\n\n/-- `simp_arg_type.to_pexpr` retrieves the `pexpr` underlying the given `simp_arg_type`, if there is\none. -/\nunsafe def simp_arg_type.to_pexpr : simp_arg_type \u2192 Option pexpr\n  | sat@(simp_arg_type.expr e) => e\n  | sat@(simp_arg_type.symm_expr e) => e\n  | sat => none\n#align tactic.simp_arg_type.to_pexpr tactic.simp_arg_type.to_pexpr\n\n/-- Incantation which prepares a `pexpr` in a `simp_arg_type` for use by the simplifier after\n`expr.replace_subexprs` as been called to replace some of its local variables. -/\nprivate unsafe def replace_subexprs_for_simp_arg (e : pexpr) (rules : List (expr \u00d7 expr)) : pexpr :=\n  strip_annotations_from_all_non_local_consts <|\n    pexpr.of_expr <| e.unsafe_cast.replace_subexprs rules\n#align tactic.replace_subexprs_for_simp_arg tactic.replace_subexprs_for_simp_arg\n\n/-- `simp_arg_type.replace_subexprs` calls `expr.replace_subexprs` on the underlying `pexpr`, if\nthere is one, and then prepares the result for use by the simplifier. -/\nunsafe def simp_arg_type.replace_subexprs : simp_arg_type \u2192 List (expr \u00d7 expr) \u2192 simp_arg_type\n  | simp_arg_type.expr e, rules => simp_arg_type.expr <| replace_subexprs_for_simp_arg e rules\n  | simp_arg_type.symm_expr e, rules =>\n    simp_arg_type.symm_expr <| replace_subexprs_for_simp_arg e rules\n  | sat, rules => sat\n#align tactic.simp_arg_type.replace_subexprs tactic.simp_arg_type.replace_subexprs\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\n-- Turn off the messages if the result is exactly `true` with this option.\ninitialize\n  registerTraceClass.1 `silence_simp_if_true\n\n/-- The basic usage is `#simp e`, where `e` is an expression,\nwhich will print the simplified form of `e`.\n\nYou can specify additional simp lemmas as usual for example using\n`#simp [f, g] : e`, or `#simp with attr : e`.\n(The colon is optional, but helpful for the parser.)\n\n`#simp` understands local variables, so you can use them to\nintroduce parameters.\n-/\n@[user_command]\nunsafe def simp_cmd (_ : parse <| tk \"#simp\") : lean.parser Unit := do\n  let no_dflt \u2190 only_flag\n  let hs \u2190 simp_arg_list\n  let attr_names \u2190 with_ident_list\n  let o \u2190 optional (tk \":\")\n  let e \u2190 types.texpr\n  let-- Retrieve the `pexpr`s parsed as part of the simp args, and collate them into a big list.\n  hs_es := List.join <| hs.map <| Option.toList \u2218 simp_arg_type.to_pexpr\n  let/- Synthesize a `tactic_state` including local variables as hypotheses under which `expr.simp`\n         may be safely called with expected behaviour given the `variables` in the environment. -/\n    (ts, mappings)\n    \u2190 synthesize_tactic_state_with_variables_as_hyps (e :: hs_es)\n  let simp_result\n    \u2190-- Enter the `tactic` monad, *critically* using the synthesized tactic state `ts`.\n        lean.parser.of_tactic\n        fun _ =>\n        (/- Resolve the local variables added by the parser to `e` (when it was parsed) against the local\n                 hypotheses added to the `ts : tactic_state` which we are using. -/\n          do\n            let e \u2190 to_expr e\n            let/- Replace the variables referenced in the passed `simp_arg_list` with the `expr`s corresponding\n                   to the local hypotheses we created.\n            \n                   We would prefer to just elaborate the `pexpr`s encoded in the `simp_arg_list` against the\n                   tactic state we have created (as we could with `e` above), but the simplifier expects\n                   `pexpr`s and not `expr`s. Thus, we just modify the `pexpr`s now and let `simp` do the\n                   elaboration when the time comes.\n            \n                   You might think that we could just examine each of these `pexpr`s, call `to_expr` on them,\n                   and then call `to_pexpr` afterward and save the results over the original `pexprs`. Due to\n                   how functions like `simp_lemmas.add_pexpr` are implemented in the core library, the `simp`\n                   framework is not robust enough to handle this method. When pieces of expressions like\n                   annotation macros are injected, the direct patten matches in the `simp_lemmas.*` codebase\n                   fail, and the lemmas we want don't get added.\n                   -/\n            hs := hs.map fun sat => sat.replace_subexprs mappings\n            -- Finally, call `expr.simp` with `e` and return the result.\n                Prod.fst <$>\n                e { } failed no_dflt attr_names hs)\n          ts\n  -- Trace the result.\n      when\n      (\u00acis_trace_enabled_for `silence_simp_if_true \u2228 simp_result \u2260 expr.const `true [])\n      (trace simp_result)\n#align tactic.simp_cmd tactic.simp_cmd\n\nadd_tactic_doc\n  { Name := \"#simp\"\n    category := DocCategory.cmd\n    declNames := [`tactic.simp_cmd]\n    tags := [\"simplification\"] }\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/SimpCommand.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406687981454, "lm_q2_score": 0.038466191053825004, "lm_q1q2_score": 0.01452255149657833}}
{"text": "/-\nCopyright (c) 2017 Johannes H\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes H\u00f6lzl\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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (x : Subtype p) : \u03b1 :=\n  \u2191x\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 {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (x : Subtype p) : p \u2191x :=\n  property x\n\n@[simp] theorem val_eq_coe {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {x : Subtype p} : val x = \u2191x :=\n  rfl\n\n@[simp] protected theorem forall {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : (Subtype fun (a : \u03b1) => p a) \u2192 Prop} : (\u2200 (x : Subtype fun (a : \u03b1) => p a), q x) \u2194 \u2200 (a : \u03b1) (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' {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : (x : \u03b1) \u2192 p x \u2192 Prop} : (\u2200 (x : \u03b1) (h : p x), q x h) \u2194 \u2200 (x : Subtype fun (a : \u03b1) => p a), q (\u2191x) (property x) :=\n  iff.symm subtype.forall\n\n@[simp] protected theorem exists {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : (Subtype fun (a : \u03b1) => p a) \u2192 Prop} : (\u2203 (x : Subtype fun (a : \u03b1) => p a), q x) \u2194 \u2203 (a : \u03b1), \u2203 (b : p a), q { val := a, property := b } := sorry\n\nprotected theorem ext {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x} {a2 : Subtype fun (x : \u03b1) => p x} : \u2191a1 = \u2191a2 \u2192 a1 = a2 := sorry\n\ntheorem ext_iff {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x} {a2 : Subtype fun (x : \u03b1) => p x} : a1 = a2 \u2194 \u2191a1 = \u2191a2 :=\n  { mp := congr_arg fun {a1 : Subtype fun (x : \u03b1) => p x} => \u2191a1, mpr := subtype.ext }\n\ntheorem heq_iff_coe_eq {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {q : \u03b1 \u2192 Prop} (h : \u2200 (x : \u03b1), p x \u2194 q x) {a1 : Subtype fun (x : \u03b1) => p x} {a2 : Subtype fun (x : \u03b1) => q x} : a1 == a2 \u2194 \u2191a1 = \u2191a2 :=\n  Eq._oldrec (fun (a2' : Subtype fun (x : \u03b1) => p x) => iff.trans heq_iff_eq ext_iff)\n    (funext fun (x : \u03b1) => propext (h x)) a2\n\ntheorem ext_val {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x} {a2 : Subtype fun (x : \u03b1) => p x} : val a1 = val a2 \u2192 a1 = a2 :=\n  subtype.ext\n\ntheorem ext_iff_val {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a1 : Subtype fun (x : \u03b1) => p x} {a2 : Subtype fun (x : \u03b1) => p x} : a1 = a2 \u2194 val a1 = val a2 :=\n  ext_iff\n\n@[simp] theorem coe_eta {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (a : Subtype fun (a : \u03b1) => p a) (h : p \u2191a) : { val := \u2191a, property := h } = a :=\n  subtype.ext rfl\n\n@[simp] theorem coe_mk {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} (a : \u03b1) (h : p a) : \u2191{ val := a, property := h } = a :=\n  rfl\n\n@[simp] theorem mk_eq_mk {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a : \u03b1} {h : p a} {a' : \u03b1} {h' : p a'} : { val := a, property := h } = { val := a', property := h' } \u2194 a = a' :=\n  ext_iff\n\ntheorem coe_eq_iff {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {a : Subtype fun (a : \u03b1) => p a} {b : \u03b1} : \u2191a = b \u2194 \u2203 (h : p b), a = { val := b, property := h } := sorry\n\ntheorem coe_injective {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : function.injective coe :=\n  fun (a b : Subtype p) => subtype.ext\n\ntheorem val_injective {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} : function.injective val :=\n  coe_injective\n\n/-- Restrict a (dependent) function to a subtype -/\ndef restrict {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Type u_2} (f : (x : \u03b1) \u2192 \u03b2 x) (p : \u03b1 \u2192 Prop) (x : Subtype p) : \u03b2 (val x) :=\n  f \u2191x\n\ntheorem restrict_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Type u_2} (f : (x : \u03b1) \u2192 \u03b2 x) (p : \u03b1 \u2192 Prop) (x : Subtype p) : restrict f p x = f (val x) :=\n  Eq.refl (restrict f p x)\n\ntheorem restrict_def {\u03b1 : Sort u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 \u03b2) (p : \u03b1 \u2192 Prop) : restrict f p = f \u2218 coe :=\n  Eq.refl (restrict f p)\n\ntheorem restrict_injective {\u03b1 : Sort u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} (p : \u03b1 \u2192 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) {p : \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1), p (f a)) : \u03b1 \u2192 Subtype p :=\n  fun (a : \u03b1) => { val := f a, property := h a }\n\ntheorem coind_injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1), p (f a)) (hf : function.injective f) : function.injective (coind f h) :=\n  fun (x y : \u03b1) (hxy : coind f h x = coind f h y) => hf (congr_arg val hxy)\n\ntheorem coind_surjective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1), p (f a)) (hf : function.surjective f) : function.surjective (coind f h) := sorry\n\ntheorem coind_bijective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} (h : \u2200 (a : \u03b1), 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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2) (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) : \u2200 (\u1fb0 : Subtype p), \u2191(map f h \u1fb0) = f \u2191\u1fb0 :=\n  fun (\u1fb0 : Subtype p) => Eq.refl \u2191(map f h \u1fb0)\n\ntheorem map_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {r : \u03b3 \u2192 Prop} {x : Subtype p} (f : \u03b1 \u2192 \u03b2) (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) (g : \u03b2 \u2192 \u03b3) (l : \u2200 (a : \u03b2), q a \u2192 r (g a)) : map g l (map f h x) = map (g \u2218 f) (fun (a : \u03b1) (ha : p a) => l (f a) (h a ha)) x :=\n  rfl\n\ntheorem map_id {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {h : \u2200 (a : \u03b1), p a \u2192 p (id a)} : map id h = id := sorry\n\ntheorem map_injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} {f : \u03b1 \u2192 \u03b2} (h : \u2200 (a : \u03b1), p a \u2192 q (f a)) (hf : function.injective f) : function.injective (map f h) :=\n  coind_injective (fun (x : Subtype fun (a : \u03b1) => p a) => map._proof_1 f h x) (function.injective.comp hf coe_injective)\n\ntheorem map_involutive {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} {f : \u03b1 \u2192 \u03b1} (h : \u2200 (a : \u03b1), p a \u2192 p (f a)) (hf : function.involutive f) : function.involutive (map f h) :=\n  fun (x : Subtype fun (a : \u03b1) => p a) => subtype.ext (hf \u2191x)\n\nprotected instance has_equiv {\u03b1 : Sort u_1} [has_equiv \u03b1] (p : \u03b1 \u2192 Prop) : has_equiv (Subtype p) :=\n  has_equiv.mk fun (s t : Subtype p) => \u2191s \u2248 \u2191t\n\ntheorem equiv_iff {\u03b1 : Sort u_1} [has_equiv \u03b1] {p : \u03b1 \u2192 Prop} {s : Subtype p} {t : Subtype p} : s \u2248 t \u2194 \u2191s \u2248 \u2191t :=\n  iff.rfl\n\nprotected theorem refl {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [setoid \u03b1] (s : Subtype p) : s \u2248 s :=\n  setoid.refl \u2191s\n\nprotected theorem symm {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [setoid \u03b1] {s : Subtype p} {t : Subtype p} (h : s \u2248 t) : t \u2248 s :=\n  setoid.symm h\n\nprotected theorem trans {\u03b1 : Sort u_1} {p : \u03b1 \u2192 Prop} [setoid \u03b1] {s : Subtype p} {t : Subtype p} {u : Subtype p} (h\u2081 : s \u2248 t) (h\u2082 : t \u2248 u) : s \u2248 u :=\n  setoid.trans h\u2081 h\u2082\n\ntheorem equivalence {\u03b1 : Sort u_1} [setoid \u03b1] (p : \u03b1 \u2192 Prop) : equivalence has_equiv.equiv :=\n  mk_equivalence has_equiv.equiv subtype.refl subtype.symm subtype.trans\n\nprotected instance setoid {\u03b1 : Sort u_1} [setoid \u03b1] (p : \u03b1 \u2192 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 `\u03b1` is a type. -/\n\n@[simp] theorem coe_prop {\u03b1 : Type u_1} {S : set \u03b1} (a : Subtype fun (a : \u03b1) => a \u2208 S) : \u2191a \u2208 S :=\n  prop a\n\ntheorem val_prop {\u03b1 : Type u_1} {S : set \u03b1} (a : Subtype fun (a : \u03b1) => a \u2208 S) : val a \u2208 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": "import Lib.Meta.Opaque\n-- import Lib.Meta.DeclGraph\nimport Lib.Meta.ImportPrivate\nimport Lib.Meta.Dump\n\n-- import Lean.Elab.BuiltinCommand\n\n-- import_private append._impl.append._eq_1\n\n\n\n--\n-- NOTE: transported theorem has same name as equation\n--\n--\n-- [opaque.decls] _ _private.0.append._impl.append._eq_1 : \u2200 {\u03b1 : Type u_1} (x : List \u03b1), append._impl.append [] x = x\n-- 11:0:\n-- [opaque.decls] theorem _private.0.append._impl.append._eq_1 : \u2200 {\u03b1 : Type u_1} (x : List \u03b1), append [] x = x\n\nnamespace Foo\n\nopaque def append : List \u03b1 \u2192 List \u03b1 \u2192 List \u03b1\n| [], ys => ys\n| x :: xs, ys => x :: append xs ys\n\nopen Lean.Parser\nopen Lean.Elab.Command\nopaque namespace append\n-- #check 3\n\ndef foo := 3\n\n-- set_option trace.opaque.proof.state true\ntheorem append_assoc (xs ys zs : List \u03b1) :\n  append xs (append ys zs) = (xs ++ ys) ++ zs := by\ninduction xs <;> simp [*, append]\ninduction ys <;> simp [*, append]\n\nend append\n\n\nend Foo\n\nset_option trace.opaque.decls true\n\n-- syntax (name := opaqueSection)\n--    \"opaque \" \"section \" ident : command\n\n-- syntax (name := opaqueSectionEnd)\n--   \"myend \" ident : command\n\nimport_private Lean.Elab.Command.addNamespace\n\n-- @[commandElab opaqueSection]\n-- def elabOpaqueSection : CommandElab := \u03bb stx => do\n-- match stx with\n-- | `(opaque section $id:ident) =>\n-- -- \u03bb stx =>\n--   -- println!\"foo\"\n--   addNamespace id.getId\n-- | _ => println!\"wtf\"\n\n#print Lean.Options\nopen Lean\n#check addDecl\n#pred MonadEnv\nderiving instance Repr for Lean.OpenDecl\nderiving instance Repr for Lean.DataValue\nderiving instance Repr for Lean.KVMap\n-- #check @StateRefT'.instMonadLiftStateRefT'\n#check Core.State\nset_option pp.explicit true in\n#check inferInstanceAs (MonadState _ CoreM)\n#check @instMonadEnv\n#check Core.instMonadEnvCoreM\n#check @ReaderT.instMonadLiftReaderT\nset_option pp.explicit true in\n#check inferInstanceAs (MonadEnv MetaM)\n-- #check instMonadEnv\ninstance : Repr Lean.Options :=\ninferInstanceAs (Repr Lean.KVMap)\n-- deriving instance Repr for NameGenerator\n-- deriving instance Repr for EnvironmentHeader\n-- deriving instance Repr for Environment\n-- deriving instance Repr for MessageLog\n-- deriving instance Repr for Elab.InfoState\n-- deriving instance Repr for TraceState\n\n-- -- #succ Nat\n-- #succ Lean.EnvExtensionState\n-- #succ Environment\n-- #check EnvExtensionState\n-- #fullname Extension\n-- deriving instance Repr for Scope\n-- -- deriving instance Repr for State\n\n-- @[commandElab opaqueSectionEnd]\n-- def elabOpaqueSectionEnd : CommandElab := \u03bb stx => do\n-- match stx with\n-- | `(myend $id:ident) =>\n--   let s \u2190 get\n--   -- println!\"id: {id}\"\n--   print_vars![id]\n-- | _ => println!\"wtf\"\n\n\n-- elab_rules\n-- | `(command| opaque section $id:ident) => `(command| namespace $id)\n\n-- syntax (name := opaqueSection)\n--    \"opaque \" \"section \" ident\n--    (ppLine (! \"end \") command)* \"end \" ident : command\n\n-- opaque section append\n\n-- def foo := 3\n\n-- myend append\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/test/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.03114383390697389, "lm_q1q2_score": 0.014478816860151487}}
{"text": "-- Check whether all intermediate steps during tactic execution\n-- can be successfully pretty-printed to trace output\n\nset_option trace.Elab.step true\n\nexample : True := by\n  skip\n  trivial\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/traceTacticSteps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.06656918572976649, "lm_q1q2_score": 0.014467982479564913}}
{"text": "inductive Val\n| mk : Nat -> Val\n\ninstance : Inhabited Val where\ndefault := Val.mk 0\n\n@[simp]\ntheorem true_iff_true : True <-> True := Iff.intro (fun _ => trivial) (fun _ => trivial)\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/753.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.05749327476308012, "lm_q1q2_score": 0.014425797797965136}}
{"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 Fixtures.Termination.Init.Prelude\nimport Fixtures.Termination.Init.Coe\nset_option linter.all false -- prevent error messages from runFrontend\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 \u2190 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 \u03b1] : HAdd \u03b1 \u03b1 \u03b1 where ...\n@[default_instance default] instance [Sub \u03b1] : HSub \u03b1 \u03b1 \u03b1 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\u2081 <|> $p\u2082) => `(stx| orelse($p\u2081, $p\u2082))\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 \" \u2218 \"  => Function.comp\n@[inherit_doc] infixr:35 \" \u00d7 \"  => 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 \" \u2264 \"  => LE.le\n@[inherit_doc] infix:50 \" < \"  => LT.lt\n@[inherit_doc] infix:50 \" >= \" => GE.ge\n@[inherit_doc] infix:50 \" \u2265 \"  => 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 \u2264 $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 \u2265 $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 \" \u2227 \"   => And\n@[inherit_doc] infixr:30 \" \\\\/ \" => Or\n@[inherit_doc] infixr:30 \" \u2228  \"  => Or\n@[inherit_doc] notation:max \"\u00ac\" 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 \" \u2208 \" => Membership.mem\n/-- `a \u2209 b` is negated elementhood. It is notation for `\u00ac (a \u2208 b)`. -/\nnotation:50 a:50 \" \u2209 \" b:50 => \u00ac (a \u2208 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\u2081 ... x\u2099`; it refers to tag `tag` and renames\nthe last `n` hypotheses to `x\u2081 ... x\u2099`.\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 \u2190 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 \u2190 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 \u2190 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 `\u27e8...\u27e9` 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  (\u2190 ``(List.cons $(\u27e8elems.elemsAndSeps.get! i\u27e9) $result))\n    if elems.elemsAndSeps.size < 64 then\n      expandListLit elems.elemsAndSeps.size false (\u2190 ``(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 (\u27e8(Syntax.ident tk.getHeadInfo \"this\".toSubstring `this [])\u27e9 : 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 := \u27e8stx\u27e9\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": "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/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189993684582, "lm_q2_score": 0.07055959569867688, "lm_q1q2_score": 0.014418281843843328}}
{"text": "/-\n## Dialect semantics\n\nThis file defines the interface that dialects provide to define their\nsemantics. This is built upon the `Dialect` interface from `MLIR.Dialects`\nwhich define the custom attributes and type required to model the programs.\n-/\n\nimport MLIR.Semantics.Fitree\nimport MLIR.Semantics.FitreeLaws\nimport MLIR.Semantics.SSAEnv\nimport MLIR.Semantics.UB\nimport MLIR.Semantics.Dominance\nimport MLIR.AST\nimport MLIR.Util.Monads\nopen MLIR.AST\n\n\nabbrev TypedArg (\u03b4: Dialect \u03b1 \u03c3 \u03b5) := (\u03c4: MLIRType \u03b4) \u00d7 MLIRType.eval \u03c4\n\n\n-- | Abbreviation with a typeclass context?\n@[simp]\nabbrev TypedArgs (\u03b4: Dialect \u03b1 \u03c3 \u03b5) := List (TypedArg \u03b4)\n\n\ninductive OpM (\u0394: Dialect \u03b1 \u03c3 \u03f5): Type -> Type _ where\n| Ret: R -> OpM \u0394 R\n| RunRegion: Nat -> TypedArgs \u0394 -> (TypedArgs \u0394 -> OpM \u0394 R) -> OpM \u0394 R\n| Unhandled: String \u2192 OpM \u0394 R\n| Error: String -> OpM \u0394 R\n\n\ndef OpM.map (f: A \u2192 B): OpM \u0394 A -> OpM \u0394 B\n| .Ret a => .Ret (f a)\n| .Unhandled s => .Unhandled s\n| .RunRegion ix args k =>\n    .RunRegion ix args (fun blockResult =>  (k blockResult).map f)\n| .Error s => .Error s\n\n\ndef OpM.bind (ma: OpM \u0394 A) (a2mb: A -> OpM \u0394 B): OpM \u0394 B :=\n  match ma with\n  | .Unhandled s => .Unhandled s\n  | .Ret a => a2mb a\n  | .Error s => .Error s\n  | .RunRegion ix args k =>\n      .RunRegion ix args (fun blockResult => (k blockResult).bind a2mb)\n\ninstance : Monad (OpM \u0394) where\n   pure := OpM.Ret\n   bind := OpM.bind\n\ninstance : LawfulMonad (OpM \u0394) := sorry\n\n-- Interpreted operation, like MLIR.AST.Op, but with less syntax\ninductive IOp (\u03b4: Dialect \u03b1 \u03c3 \u03b5) := | mk\n  (name:    String) -- TODO: name should come from an Enum in \u03b4.\n  (resTy:   List (MLIRType \u03b4))\n  (args:    TypedArgs \u03b4)\n  (regions: List (TypedArgs \u03b4 \u2192 OpM \u03b4 (TypedArgs \u03b4)))\n  (attrs:   AttrDict \u03b4)\n\n\n-- The monad in which these computations are run\nabbrev TopM (\u0394: Dialect \u03b1 \u03c3 \u03b5) (R: Type _) := StateT (SSAEnv \u0394) (Except (String \u00d7 (SSAEnv \u0394))) R\ndef TopM.run (t: TopM \u0394 R) (env: SSAEnv \u0394): Except (String \u00d7 (SSAEnv \u0394)) (R \u00d7 SSAEnv \u0394) :=\n  StateT.run t env\n\ndef TopM.scoped (t: TopM \u0394 R): TopM \u0394 R := do\n  -- TODO: convert this to using the `SSAEnv`'s ability to a stack of `SSAScope`,\n  -- instead of approximating it with overwriting the `SSAEnv` temporarily.\n  let state \u2190 get -- save scope\n  let res \u2190 t -- run computation\n  set state -- restore scope\n  return res -- return result\n\n\ndef TopM.raiseUB {\u0394: Dialect \u03b1 \u03c3 \u03b5} (message: String): TopM \u0394 R := do\n  let state \u2190 get\n  Except.error (message, state)\n\ndef TopM.get {\u0394: Dialect \u03b1 \u03c3 \u03b5} (\u03c4: MLIRType \u0394) (name: SSAVal): TopM \u0394 \u03c4.eval := do\n  let s \u2190 StateT.get\n  match SSAEnv.get name \u03c4 s  with\n  | .some v => return v\n  | .none => return default\n\ndef TopM.set {\u0394: Dialect \u03b1 \u03c3 \u03b5} (\u03c4: MLIRType \u0394) (name: SSAVal) (v: \u03c4.eval): TopM \u0394 Unit := do\n  let s \u2190 StateT.get\n  match SSAEnv.get name \u03c4 s with\n  | .some _ => TopM.raiseUB \"setting to SSA value twice!\"\n  | .none => StateT.set (SSAEnv.set name \u03c4 v s)\n\ntheorem TopM.get_unfold {\u0394: Dialect \u03b1 \u03c3 \u03b5} (\u03c4: MLIRType \u0394) (name: SSAVal) (env: SSAEnv \u0394) :\n    TopM.get \u03c4 name env =\n    Except.ok (\n      (match env.get name \u03c4 with\n      | some v => v\n      | none => default)\n      , env) := by\n  simp [TopM.get]\n  simp_monad\n  cases (env.get name \u03c4) <;> rfl\n\ntheorem TopM.set_unfold {\u0394: Dialect \u03b1 \u03c3 \u03b5} (\u03c4: MLIRType \u0394) (name: SSAVal)\n  (env: SSAEnv \u0394) (v: MLIRType.eval \u03c4):\n    TopM.set \u03c4 name v env =\n    match env.get name \u03c4 with\n    | some _ => Except.error (\"setting to SSA value twice!\", env)\n    | none => Except.ok ((), env.set name \u03c4 v) := by\n  simp [TopM.set]\n  simp_monad\n  cases (env.get name \u03c4) <;> rfl\n\ntheorem TopM.set_ok {\u0394: Dialect \u03b1 \u03c3 \u03b5} {\u03c4: MLIRType \u0394} {name: SSAVal}\n  {v: MLIRType.eval \u03c4} {env: SSAEnv \u0394} {r}:\n    TopM.set \u03c4 name v env = Except.ok r ->\n    r = ((), env.set name \u03c4 v) \u2227 env.get name \u03c4 = none := by\n  simp [set]; simp_monad\n  cases (env.get name \u03c4) <;> simp <;> intros H <;> try contradiction\n  rw [H]\n\ntheorem TopM.get_env_set_commutes {\u0394: Dialect \u03b1 \u03c3 \u03b5}:\n    \u2200 \u2983\u03c4: MLIRType \u0394\u2984 \u2983name env r env'\u2984, TopM.get \u03c4 name env = Except.ok (r, env') ->\n    \u2200 \u2983name'\u2984, name' \u2260 name ->\n    \u2200 \u2983\u03c4' v'\u2984, TopM.get \u03c4 name (env.set name' \u03c4' v') = Except.ok (r, env'.set name' \u03c4' v') := by\n  intros \u03c4 name env r env' H name' Hne \u03c4' v'\n  rw [TopM.get_unfold] at *\n  simp_monad at *\n  simp_ssaenv at *\n  revert H\n  cases (env.get name \u03c4) <;> simp at * <;> intros H1 H2 <;> subst r <;> subst env <;> simp\n\ntheorem TopM.set_env_set_commutes {\u0394: Dialect \u03b1 \u03c3 \u03b5}:\n    \u2200 \u2983\u03c4: MLIRType \u0394\u2984 \u2983name v env r env'\u2984, TopM.set \u03c4 name v env = Except.ok (r, env') ->\n    \u2200 \u2983name'\u2984, name' \u2260 name ->\n    \u2200 \u03c4' v', \u2203 env'', (env'.set name' \u03c4' v').equiv env'' \u2227\n      TopM.set \u03c4 name v (env.set name' \u03c4' v') = Except.ok (r, env'') := by\n  intros \u03c4 name v env r env' H name' Hname \u03c4' v'\n  simp [set] at *; simp_monad at *\n  revert H; cases Hget: (env.get name \u03c4) <;> simp <;> intros H <;> try contradiction\n  simp_ssaenv\n  -- rw [Hget]; simp\n  subst env'\n  exists (SSAEnv.set name \u03c4 v (SSAEnv.set name' \u03c4' v' env))\n  simp[Hget]\n  simp_ssaenv\n  apply SSAEnv.set_commutes; try assumption\n  simp [Ne.symm Hname]\n\n\ntheorem TopM.get_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5}:\n    \u2200 \u2983env\u2081 env\u2082: SSAEnv \u0394\u2984, env\u2081.equiv env\u2082 ->\n    \u2200 \u2983\u03c4 name r env\u2081'\u2984, TopM.get \u03c4 name env\u2081 = Except.ok (r, env\u2081') \u2192\n    TopM.get \u03c4 name env\u2082 = Except.ok (r, env\u2082):= by\n  intros env\u2081 env\u2082 Hequiv \u03c4 name r env\u2081'\n  repeat rw [TopM.get_unfold]\n  rw [Hequiv]\n  simp_monad\n  intros H _;\n  rw [H]\n\ntheorem TopM.set_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5}:\n    \u2200 \u2983env\u2081 env\u2082: SSAEnv \u0394\u2984, env\u2081.equiv env\u2082 ->\n    \u2200 \u2983\u03c4 name v r env\u2081'\u2984, TopM.set \u03c4 name v env\u2081 = Except.ok (r, env\u2081') \u2192\n    TopM.set \u03c4 name v env\u2082 = Except.ok (r, env\u2082.set name \u03c4 v):= by\n  intros env\u2081 env\u2082 Hequiv \u03c4 name v r env\u2081'\n  repeat rw [TopM.set_unfold]\n  rw [Hequiv]\n  simp_monad\n  cases (SSAEnv.get name \u03c4 env\u2082) <;> simp\n\n\nclass Semantics (\u0394: Dialect \u03b1 \u03c3 \u03b5)  where\n  -- Operation semantics function: maps an IOp (morally an Op but slightly less\n  -- rich to guarantee good properties) to an interaction tree. Usually exposes\n  -- any region calls then emits of event of E. This function runs on the\n  -- program's entire dialect \u0394 but returns none for any operation that is not\n  -- part of \u03b4.\n  -- TODO: make this such that it's a ddependent function, where we pass it the resTy and we expect\n  -- an answer that matches the types of the resTy of the IOp.\n  semantics_op: IOp \u0394 \u2192 OpM \u0394 (TypedArgs \u0394)\n\n-- This attribute allows matching explicit effect families like `ArithE`, which\n-- often appear from bottom-up inference like in `Fitree.trigger`, with their\n-- implicit form like `Semantics.E arith`, which often appears from top-down\n-- type inference due to the type signatures in this module. Without this\n-- attribute, instances of `Member` could not be derived, preventing most\n-- lemmas about `Fitree.trigger` from applying.\n-- attribute [reducible] Semantics.E\n\n-- | TODO: Make this dependently typed to never allow such an error\ndef denoteTypedArgs (args: TypedArgs \u0394) (names: List SSAVal): TopM \u0394 Unit :=\n match args with\n | [] => return ()\n | \u27e8\u03c4, val\u27e9::args =>\n    match names with\n    | [] => TopM.raiseUB \"not enough names in denoteTypedArgs\"\n    | name :: names => do\n        TopM.set \u03c4 name val\n        denoteTypedArgs args names\n\n-- Denote a region with an abstract `OpM.RunRegion`\ndef OpM.denoteRegion {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  (_r: Region \u0394)\n  (ix: Nat) (args: TypedArgs \u0394): OpM \u0394 (TypedArgs \u0394) :=\n    OpM.RunRegion ix args (fun retvals => OpM.Ret retvals)\n\n-- Denote the list of regions with an abstract `OpM.runRegion`\ndef OpM.denoteRegions {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  (regions: List (Region \u0394))\n  (ix: Nat): List (TypedArgs \u0394 \u2192 OpM \u0394 (TypedArgs \u0394)) :=\n match regions with\n | [] => []\n | r :: rs => (OpM.denoteRegion r ix) :: OpM.denoteRegions rs (ix + 1)\n\n-- Denote a region by using its denotation function from the list\n-- of regions. TODO: refactor to use Option\ndef TopM.denoteRegionsByIx\n  (rs0: List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394)))\n (ix: Nat) (args: TypedArgs \u0394): TopM \u0394 (TypedArgs \u0394) :=\n  match rs0 with\n  | [] => TopM.raiseUB s!\"unknown region of ix {ix}\"\n  | r:: rs' =>\n    match ix with\n    | 0 => r args\n    | ix' + 1 => TopM.denoteRegionsByIx rs' ix' args\n\n-- Morphism from OpM to topM\ndef OpM.toTopM (rs0: List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394))):\n  OpM \u0394 (TypedArgs \u0394) -> TopM \u0394 (TypedArgs \u0394)\n| OpM.Unhandled s => TopM.raiseUB s!\"OpM.toTopM unhandled '{\u0394.name}': {s}\"\n| OpM.Ret r => pure r\n| OpM.Error s => TopM.raiseUB s\n| OpM.RunRegion ix args k => do\n       let ret <- TopM.denoteRegionsByIx rs0 ix args\n       OpM.toTopM rs0 (k ret)\nmutual\nvariable (\u0394: Dialect \u03b1' \u03c3' \u03b5') [S: Semantics \u0394]\n\n-- unfolded version of List.map denoteRegion.\n-- This allows the termination checker to view the termination.\ndef TopM.mapDenoteRegion:\n  List (Region \u0394) \u2192\n  List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394))\n| [] => []\n| r :: rs =>\n  let f := denoteRegion r\n  (TopM.scoped \u2218 f) :: TopM.mapDenoteRegion rs\n\ndef denoteOpArgs (args: List (TypedSSAVal \u0394)) : TopM \u0394 (List (TypedArg \u0394)) := do\n  args.mapM (fun (name, \u03c4) => do\n        pure \u27e8\u03c4, \u2190 TopM.get \u03c4 name\u27e9)\n\n-- Convert a region to its denotation to establish finiteness.\n-- Then use this finiteness condition to evaluate region semantics.\n-- Use the morphism from OpM to TopM.\ndef denoteOp (op: Op \u0394):\n    TopM \u0394 (TypedArgs \u0394) :=\n  match op with\n  | .mk name res0 args0 regions0 attrs => do\n      let resTy := res0.map Prod.snd\n      let args \u2190 denoteOpArgs args0\n      -- Built the interpreted operation\n      let iop : IOp \u0394 := IOp.mk name resTy args (OpM.denoteRegions regions0 0) attrs\n      -- Use the dialect-provided semantics, and substitute regions\n      let ret \u2190 OpM.toTopM (TopM.mapDenoteRegion regions0) (S.semantics_op iop)\n      match res0 with\n      | [] => pure ()\n      | [res] => match ret with\n          | [\u27e8\u03c4, v\u27e9] => TopM.set \u03c4 res.fst v\n          | _ => TopM.raiseUB s!\"denoteOp: expected 1 return value, got '{ret}'\"\n      | _ => TopM.raiseUB s!\"denoteOp: expected 0 or 1 results, got '{res0}'\"\n      return ret\n  -- denote a sequence of ops\ndef denoteOps (stmts: List (Op \u0394)): TopM \u0394 (TypedArgs \u0394) :=\n   match stmts with\n   | [] => return  []\n   | [stmt] => denoteOp stmt\n   | (stmt :: stmts') => do\n        let _ \u2190 denoteOp stmt\n        denoteOps stmts'\n\ndef denoteRegion (rgn: Region \u0394) (args: TypedArgs \u0394):\n    TopM \u0394 (TypedArgs \u0394) := do\n  match rgn with\n  | Region.mk name formalArgsAndTypes ops =>\n     -- TODO: check that types in [TypedArgs] is equal to types at [bb.args]\n     -- TODO: Any checks on the BlockResults of intermediate ops?\n     let formalArgs : List SSAVal := formalArgsAndTypes.map Prod.fst\n     denoteTypedArgs args formalArgs\n     denoteOps ops\nend\ntermination_by\n  mapDenoteRegion _ _ _ _ _ rgns =>  by {\n   exact (sizeOf rgns)\n  }\n  denoteOp sem op  => sizeOf op\n  denoteOps stmts _ => sizeOf stmts\n  denoteRegion rgn _ => sizeOf rgn\n\n\n\n\nsection Retraction\n\nvariable {\u03b1\u2081 \u03c3\u2081 \u03b5\u2081} {\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081}\n variable   {\u03b1\u2082 \u03c3\u2082 \u03b5\u2082} {\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082}\n\n-- TODO: create holes for things that are unknown? eg. use `undefined?\ndef MLIRType.retractLeft: MLIRType (\u03b4\u2081 + \u03b4\u2082) \u2192 MLIRType \u03b4\u2081\n| .int sgn sz => .int sgn sz -- : Signedness -> Nat -> MLIRType \u03b4\n| .float sz => .float sz -- : Nat -> MLIRType \u03b4\n| .index => .index --:  MLIRType \u03b4\n| .tensor1d => .tensor1d\n| .tensor2d => .tensor2d\n| .tensor4d => .tensor4d\n| .erased => .erased\n| .undefined s => .undefined s-- : String \u2192 MLIRType \u03b4\n| .extended (Sum.inl \u03c3\u2081) => .extended \u03c3\u2081 -- : \u03c3 \u2192 MLIRType \u03b4\n| .extended (Sum.inr \u03c3\u2082) => .erased\n\ndef MLIRType.swapDialect: MLIRType (\u03b4\u2081 + \u03b4\u2082) -> MLIRType (\u03b4\u2082 + \u03b4\u2081)\n| .int sgn sz => (.int sgn sz) -- : Signedness -> Nat -> MLIRType \u03b4\n| .float sz => (.float sz) -- : Nat -> MLIRType \u03b4\n| .index => (.index) --:  MLIRType \u03b4\n| .erased => .erased\n| .tensor1d => .tensor1d\n| .tensor2d => .tensor2d\n| .tensor4d => .tensor4d\n| .undefined s => (.undefined s) -- : String \u2192 MLIRType \u03b4\n| .extended (Sum.inl \u03c3\u2081) => .extended (Sum.inr \u03c3\u2081)\n| .extended (Sum.inr \u03c3\u2082) => .extended (Sum.inl \u03c3\u2082)\n\n\ndef TypedArg.swapDialect: TypedArg (\u03b4\u2081 + \u03b4\u2082) -> TypedArg (\u03b4\u2082 + \u03b4\u2081)\n| \u27e8.int sgn sz, v \u27e9 =>  \u27e8 .int sgn sz, v \u27e9 -- : Signedness -> Nat -> MLIRType \u03b4\n| \u27e8 .float sz, v \u27e9 =>  \u27e8.float sz, v \u27e9 -- : Nat -> MLIRType \u03b4\n| \u27e8.index, v\u27e9 => \u27e8.index, v \u27e9 --:  MLIRType \u03b4\n| \u27e8.undefined s, v \u27e9 =>  \u27e8.undefined s, v\u27e9 -- : String \u2192 MLIRType \u03b4\n\n| \u27e8.tensor1d, v\u27e9 => \u27e8.tensor1d, v \u27e9\n| \u27e8.tensor2d, v\u27e9 => \u27e8.tensor2d, v \u27e9\n| \u27e8.tensor4d, v\u27e9 => \u27e8.tensor4d, v \u27e9\n| \u27e8.extended (Sum.inl \u03c3\u2081), v \u27e9 => \u27e8.extended (Sum.inr \u03c3\u2081), v\u27e9\n| \u27e8.extended (Sum.inr \u03c3\u2082), v \u27e9 => \u27e8.extended (Sum.inl \u03c3\u2082), v\u27e9\n| \u27e8.erased, ()\u27e9 => \u27e8.erased, ()\u27e9\n\n@[reducible, simp]\ndef TypedArgs.swapDialect (ts: TypedArgs (\u03b4\u2081 + \u03b4\u2082)): TypedArgs (\u03b4\u2082 + \u03b4\u2081) :=\n  ts.map TypedArg.swapDialect\n\n\n\ndef TypedArg.retractLeft (t: TypedArg (\u03b4\u2081 + \u03b4\u2082)):  TypedArg \u03b4\u2081 :=\nmatch t with\n| \u27e8.int sgn sz, v \u27e9 =>  \u27e8 .int sgn sz, v \u27e9 -- : Signedness -> Nat -> MLIRType \u03b4\n| \u27e8 .float sz, v \u27e9 => \u27e8.float sz, v \u27e9 -- : Nat -> MLIRType \u03b4\n| \u27e8.index, v\u27e9 => \u27e8.index, v \u27e9 --:  MLIRType \u03b4\n| \u27e8.tensor1d, v\u27e9 =>  \u27e8.tensor1d,v \u27e9\n| \u27e8.tensor2d, v\u27e9 =>  \u27e8.tensor2d,v \u27e9\n| \u27e8.tensor4d, v\u27e9 =>  \u27e8.tensor4d,v \u27e9\n| \u27e8.undefined s, v \u27e9 =>  \u27e8.undefined s, v\u27e9 -- : String \u2192 MLIRType \u03b4\n| \u27e8.extended (Sum.inl \u03c3\u2081), v \u27e9 =>  \u27e8.extended \u03c3\u2081, v\u27e9 -- : \u03c3 \u2192 MLIRType \u03b4\n| \u27e8.extended (Sum.inr \u03c3\u2082), v \u27e9 => \u27e8.erased, () \u27e9\n| \u27e8.erased, ()\u27e9 =>  \u27e8.erased, ()\u27e9\n\ndef TypedArg.retractRight (t: TypedArg (\u03b4\u2081 + \u03b4\u2082)):  TypedArg \u03b4\u2082 :=\nmatch t with\n| \u27e8.int sgn sz, v \u27e9 =>  \u27e8 .int sgn sz, v \u27e9 -- : Signedness -> Nat -> MLIRType \u03b4\n| \u27e8 .float sz, v \u27e9 => \u27e8.float sz, v \u27e9 -- : Nat -> MLIRType \u03b4\n| \u27e8.index, v\u27e9 => \u27e8.index, v \u27e9 --:  MLIRType \u03b4\n| \u27e8.tensor1d, v\u27e9 =>  \u27e8.tensor1d,v \u27e9\n| \u27e8.tensor2d, v\u27e9 =>  \u27e8.tensor2d,v \u27e9\n| \u27e8.tensor4d, v\u27e9 =>  \u27e8.tensor4d,v \u27e9\n| \u27e8.undefined s, v \u27e9 =>  \u27e8.undefined s, v\u27e9 -- : String \u2192 MLIRType \u03b4\n| \u27e8.extended (Sum.inl \u03c3\u2081), v \u27e9 =>  \u27e8.erased, ()\u27e9 -- : \u03c3 \u2192 MLIRType \u03b4\n| \u27e8.extended (Sum.inr \u03c3\u2082), v \u27e9 => \u27e8.extended \u03c3\u2082, v \u27e9\n| \u27e8.erased, ()\u27e9 =>  \u27e8.erased, ()\u27e9\n\n\n@[reducible, simp]\ndef TypedArgs.retractLeft (ts: TypedArgs (\u03b4\u2081 + \u03b4\u2082)): TypedArgs \u03b4\u2081 :=\n  ts.map TypedArg.retractLeft\n\n@[reducible, simp]\ndef TypedArgs.retractRight (ts: TypedArgs (\u03b4\u2081 + \u03b4\u2082)): TypedArgs \u03b4\u2082 :=\n  ts.map TypedArg.retractRight\n\n-- TODO: define the attribute dictionary retraction.\n-- Will need to rectact over entries, which will need a retraction over values.\nmutual\ndef AttrValues.retractLeft: List (AttrValue  (\u03b4\u2081 + \u03b4\u2082)) -> List (AttrValue \u03b4\u2081)\n| [] => []\n| a::as => a.retractLeft:: AttrValues.retractLeft as\n\ndef MLIR.AST.AttrValue.retractLeft: AttrValue (\u03b4\u2081 + \u03b4\u2082) -> AttrValue \u03b4\u2081\n| .symbol s => .symbol s\n| .permutation p => .permutation p\n| .nat n => .nat n\n| .str s => .str s\n| .int i t => .int i (MLIRType.retractLeft t)\n| .bool b => .bool b\n| .float f t => .float f (MLIRType.retractLeft t)\n| .type t => .type (MLIRType.retractLeft t)\n| .affine aff => .affine aff\n| .list as => .list <| AttrValues.retractLeft as\n| .extended (.inl x) => .extended x\n| .extended (.inr _) => .erased\n| .erased => .erased\n| .opaque_ dialect value => .opaque_ dialect value\n| .opaqueElements dialect value ty => .opaqueElements dialect value .erased\n| .unit => .unit\n| .dict d => .dict <| d.retractLeft\n| .alias x => .alias x\n| .nestedsymbol x y => .nestedsymbol x.retractLeft y.retractLeft\n\n\ndef MLIR.AST.AttrEntry.retractLeft: AttrEntry (\u03b4\u2081 + \u03b4\u2082) -> AttrEntry \u03b4\u2081\n| .mk k v => .mk k v.retractLeft\n\ndef AttrEntries.retractLeft: List (AttrEntry (\u03b4\u2081 + \u03b4\u2082)) -> List (AttrEntry \u03b4\u2081)\n| [] => []\n| e :: es => e.retractLeft :: AttrEntries.retractLeft es\n\ndef MLIR.AST.AttrDict.retractLeft: AttrDict (\u03b4\u2081 + \u03b4\u2082) -> AttrDict \u03b4\u2081\n| .mk es => AttrDict.mk (AttrEntries.retractLeft es)\nend\ntermination_by\n  AttrValues.retractLeft xs => sizeOf xs\n  MLIR.AST.AttrValue.retractLeft attrval => sizeOf attrval\n  MLIR.AST.AttrDict.retractLeft attrdict => sizeOf attrdict\n  AttrEntries.retractLeft attrentries => sizeOf attrentries\n  MLIR.AST.AttrEntry.retractLeft attrentry => sizeOf attrentry\n\n\n-- Retract right\nmutual\ndef AttrValues.swapDialect: List (AttrValue  (\u03b4\u2081 + \u03b4\u2082)) -> List (AttrValue (\u03b4\u2082  + \u03b4\u2081))\n| [] => []\n| a::as => a.swapDialect:: AttrValues.swapDialect as\n\ndef MLIR.AST.AttrValue.swapDialect: AttrValue (\u03b4\u2081 + \u03b4\u2082) -> AttrValue (\u03b4\u2082 + \u03b4\u2081)\n| .symbol s => .symbol s\n| .permutation p => .permutation p\n| .nat n => .nat n\n| .str s => .str s\n| .int i t => .int i (MLIRType.swapDialect t)\n| .bool b => .bool b\n| .float f t => .float f (MLIRType.swapDialect t)\n| .type t => .type (MLIRType.swapDialect t)\n| .affine aff => .affine aff\n| .list as => .list <| AttrValues.swapDialect as\n| .extended (.inl x) => .extended (.inr x)\n| .extended (.inr x) => .extended (.inl x)\n| .erased => .erased\n| .opaque_ dialect value => .opaque_ dialect value\n| .opaqueElements dialect value ty => .opaqueElements dialect value .erased\n| .unit => .unit\n| .dict d => .dict <| d.swapDialect\n| .alias x => .alias x\n| .nestedsymbol x y => .nestedsymbol x.swapDialect y.swapDialect\n\n\ndef MLIR.AST.AttrEntry.swapDialect: AttrEntry (\u03b4\u2081 + \u03b4\u2082) -> AttrEntry (\u03b4\u2082 + \u03b4\u2081)\n| .mk k v => .mk k v.swapDialect\n\ndef AttrEntries.swapDialect: List (AttrEntry (\u03b4\u2081 + \u03b4\u2082)) -> List (AttrEntry (\u03b4\u2082 + \u03b4\u2081))\n| [] => []\n| e :: es => e.swapDialect :: AttrEntries.swapDialect es\n\ndef MLIR.AST.AttrDict.swapDialect: AttrDict (\u03b4\u2081 + \u03b4\u2082) -> AttrDict (\u03b4\u2082 + \u03b4\u2081)\n| .mk es => AttrDict.mk (AttrEntries.swapDialect es)\n\n\nend -- ends the mutual block\ntermination_by\n  AttrValues.swapDialect _ x  => sizeOf x\n  MLIR.AST.AttrValue.swapDialect _ x  => sizeOf x\n  MLIR.AST.AttrDict.swapDialect _ x  => sizeOf x\n  AttrEntries.swapDialect _ x => sizeOf x\n  MLIR.AST.AttrEntry.swapDialect _ x => sizeOf x\n\n\ndef OpM.swapDialect: OpM (\u03b4\u2081 + \u03b4\u2082) (TypedArgs (\u03b4\u2081 + \u03b4\u2082)) -> OpM (\u03b4\u2082 + \u03b4\u2081) (TypedArgs (\u03b4\u2081 + \u03b4\u2082))\n| OpM.Ret r => OpM.Ret r\n| OpM.Unhandled s => OpM.Unhandled s\n| OpM.Error s => OpM.Error s\n| OpM.RunRegion ix args k =>\n  OpM.RunRegion ix (TypedArgs.swapDialect args) (fun retargs =>\n              OpM.swapDialect (k (TypedArgs.swapDialect retargs)))\n\ndef IOp.swapDialect: IOp (\u03b4\u2081 + \u03b4\u2082) -> IOp (\u03b4\u2082 + \u03b4\u2081)\n| IOp.mk  (name:    String) -- TODO: name should come from an Enum in \u03b4.\n  (resTy:   List (MLIRType (\u03b4\u2081 + \u03b4\u2082)))\n  (args:    TypedArgs (\u03b4\u2081 + \u03b4\u2082))\n  (regions: List (TypedArgs (\u03b4\u2081 + \u03b4\u2082) -> OpM (\u03b4\u2081 + \u03b4\u2082) (TypedArgs (\u03b4\u2081 + \u03b4\u2082))))\n  (attrs:   AttrDict (\u03b4\u2081 + \u03b4\u2082)) =>\n     IOp.mk name\n        (resTy.map MLIRType.swapDialect)\n        (args.map TypedArg.swapDialect)\n        (AttrDict.swapDialect attrs)\n        -- conjugate region by swapping dialect.\n        (regions := regions.map  (fun rgnEff => (fun args =>\n                 (rgnEff (TypedArgs.swapDialect args)).swapDialect.map TypedArgs.swapDialect)))\n\n-- a -> a + b\ndef TypedArg.injectLeft: TypedArg (\u03b4\u2081) -> TypedArg (\u03b4\u2081 +  \u03b4\u2082)\n| \u27e8.int sgn sz, v \u27e9 =>  \u27e8 .int sgn sz, v \u27e9 -- : Signedness -> Nat -> MLIRType \u03b4\n| \u27e8 .float sz, v \u27e9 =>  \u27e8.float sz, v \u27e9 -- : Nat -> MLIRType \u03b4\n| \u27e8.index, v\u27e9 => \u27e8.index, v \u27e9 --:  MLIRType \u03b4\n| \u27e8.undefined s, v \u27e9 =>  \u27e8.undefined s, v\u27e9 -- : String \u2192 MLIRType \u03b4\n| \u27e8.tensor1d, v\u27e9 => \u27e8.tensor1d, v \u27e9\n| \u27e8.tensor2d, v\u27e9 => \u27e8.tensor2d, v \u27e9\n| \u27e8.tensor4d, v\u27e9 => \u27e8.tensor4d, v \u27e9\n| \u27e8.extended \u03c3, v \u27e9 => \u27e8.extended (Sum.inl \u03c3), v\u27e9\n| \u27e8.erased, ()\u27e9 => \u27e8.erased, ()\u27e9\n\n\n@[reducible, simp]\ndef TypedArg.injectRight: TypedArg \u03b4\u2082 -> TypedArg (\u03b4\u2081 + \u03b4\u2082) :=\n  TypedArg.swapDialect \u2218 TypedArg.injectLeft\n\n@[reducible, simp]\ndef TypedArgs.injectLeft (ts: TypedArgs (\u03b4\u2081)): TypedArgs (\u03b4\u2081 + \u03b4\u2082) :=\n  ts.map TypedArg.injectLeft\n\n@[reducible, simp]\ndef TypedArgs.injectRight (ts: TypedArgs (\u03b4\u2082)): TypedArgs (\u03b4\u2081 + \u03b4\u2082) :=\n  ts.map TypedArg.injectRight\n\ndef OpM.retractLeft [Inhabited R]: OpM (\u03b4\u2081+ \u03b4\u2082) R -> OpM \u03b4\u2081  R\n| OpM.Error s => OpM.Error s\n| OpM.Unhandled s => OpM.Unhandled s\n| OpM.Ret r => OpM.Ret r\n| OpM.RunRegion ix args k =>\n  OpM.RunRegion ix args.retractLeft (fun results => (k results.injectLeft).retractLeft)\n\n-- Retract an IOp to the left component.\n-- TODO: IOp needs to be profunctorial, region can use more stuff than the operation\n-- strictly has?\ndef IOp.retractLeft: IOp (\u03b4\u2081 + \u03b4\u2082) -> IOp \u03b4\u2081\n| IOp.mk  (name:    String) -- TODO: name should come from an Enum in \u03b4.\n  (resTys:   List (MLIRType (\u03b4\u2081 + \u03b4\u2082)))\n  (args:    TypedArgs (\u03b4\u2081 + \u03b4\u2082))\n  (regions: List (TypedArgs (\u03b4\u2081 + \u03b4\u2082) -> OpM (\u03b4\u2081+\u03b4\u2082) (TypedArgs (\u03b4\u2081 + \u03b4\u2082))))\n  (attrs:   AttrDict (\u03b4\u2081 + \u03b4\u2082)) =>\n  let resTys' := resTys.map MLIRType.retractLeft\n  let args' := args.map TypedArg.retractLeft\n  let attrs' := AttrDict.retractLeft attrs\n  let regions' := regions.map (fun rgnEff =>\n    (fun args => (rgnEff args.injectLeft).retractLeft.map TypedArgs.retractLeft ))\n  (IOp.mk name resTys' args' regions' attrs')\n\ndef IOp.retractRight (op: IOp (\u03b4\u2081 + \u03b4\u2082)): IOp \u03b4\u2082 :=\n  IOp.retractLeft (IOp.swapDialect op)\n\ndef OpM.injectLeft: OpM \u03b4\u2081 (TypedArgs \u03b4\u2081) -> OpM (\u03b4\u2081 + \u03b4\u2082) (TypedArgs (\u03b4\u2081 + \u03b4\u2082))\n| OpM.Ret r => OpM.Ret r.injectLeft\n| OpM.Error s => OpM.Error s\n| OpM.Unhandled s => OpM.Unhandled s\n| OpM.RunRegion ix args k =>\n  OpM.RunRegion ix args.injectLeft (fun args => (k args.retractLeft).injectLeft)\n\n@[simp, reducible]\ndef OpM.injectRight: OpM \u03b4\u2082 (TypedArgs \u03b4\u2082) -> OpM (\u03b4\u2081 + \u03b4\u2082) (TypedArgs (\u03b4\u2081 + \u03b4\u2082))\n| OpM.Ret r => OpM.Ret r.injectRight\n| OpM.Error s => OpM.Error s\n| OpM.Unhandled s => OpM.Unhandled s\n| OpM.RunRegion ix args k =>\n  OpM.RunRegion ix args.injectRight (fun args => (k args.retractRight).injectRight)\n\n\n\n-- Or the two OpM, using unhandled as the unit for the or.\ndef OpM.orUnhandled: OpM \u03b4\u2081 (TypedArgs \u03b4\u2081)\n  -> OpM \u03b4\u2082 (TypedArgs \u03b4\u2082) -> OpM (\u03b4\u2081 + \u03b4\u2082) (TypedArgs (\u03b4\u2081 + \u03b4\u2082))\n| OpM.Error e, _ => OpM.Error e\n| _, OpM.Error e => OpM.Error e\n| OpM.Unhandled x, OpM.Unhandled y => OpM.Unhandled s!\"(({\u03b4\u2081.name}) ({x}) | ({\u03b4\u2082.name}) ({y}))\"\n| OpM.Unhandled _, x => x.injectRight\n| x, _ => x.injectLeft\n\n\n\n-- TODO: Allow the semantics to be defined in such a way that a dialect like `scf`\n-- can successfully 'forward' extended type arguments.\ninstance\n    {\u03b1\u2081 \u03c3\u2081 \u03b5\u2081} {\u03b4\u2081: Dialect \u03b1\u2081 \u03c3\u2081 \u03b5\u2081}\n    {\u03b1\u2082 \u03c3\u2082 \u03b5\u2082} {\u03b4\u2082: Dialect \u03b1\u2082 \u03c3\u2082 \u03b5\u2082}\n    [S\u2081: Semantics \u03b4\u2081]\n    [S\u2082: Semantics \u03b4\u2082]\n    : Semantics (\u03b4\u2081 + \u03b4\u2082) where\n  -- semantics_op: IOp \u0394 \u2192 Fitree (RegionE \u0394 +' UBE) (BlockResult \u0394)\n  semantics_op op :=\n    let op\u2081 := IOp.retractLeft op\n    let op\u2082 := IOp.retractRight op\n    let res1 :=  (S\u2081.semantics_op op\u2081)\n    let res2 :=  (S\u2082.semantics_op op\u2082)\n    OpM.orUnhandled res1 res2\n\n\n\ndef run! {\u0394: Dialect \u03b1' \u03c3' \u03b5'}  {R} [Inhabited R]\n    (t: TopM \u0394 R) (env: SSAEnv \u0394):\n    R \u00d7 SSAEnv \u0394 :=\n   match t.run env with\n   | .error err => panic! s!\"error when running progam: {err}\"\n   | .ok val => val\n\ndef run {\u0394: Dialect \u03b1' \u03c3' \u03b5'} {R}\n    (t: TopM  \u0394 R) (env: SSAEnv \u0394):\n    Except (String \u00d7 SSAEnv \u0394) (R \u00d7 SSAEnv \u0394) :=\n  StateT.run t env\n\n-- The property for two programs to execute with no error and satisfy a\n-- post-condition\ndef semanticPostCondition\u2082 {\u0394: Dialect \u03b1' \u03c3' \u03b5'}\n    (t\u2081 t\u2082: Except String (R \u00d7 SSAEnv \u0394))\n    (f: R \u2192 SSAEnv \u0394 \u2192 R \u2192 SSAEnv \u0394 \u2192 Prop) :=\n  match t\u2081, t\u2082 with\n  | .ok (r\u2081, env\u2081), .ok (r\u2082, env\u2082) => f r\u2081 env\u2081 r\u2082 env\u2082\n  | _, _ => False\n\n@[simp] theorem semanticPostCondition\u2082_ok_ok:\n  semanticPostCondition\u2082 (Except.ok (r\u2081, env\u2081)) (Except.ok (r\u2082, env\u2082)) f =\n  f r\u2081 env\u2081 r\u2082 env\u2082 := rfl\n\n/-\n### Denotation notation\n-/\n\nclass Denote (\u03b4: Dialect \u03b1 \u03c3 \u03b5) [S: Semantics \u03b4]\n    (T: {\u03b1 \u03c3: Type} \u2192 {\u03b5: \u03c3 \u2192 Type} \u2192 Dialect \u03b1 \u03c3 \u03b5 \u2192 Type) where\n  denote: T \u03b4 \u2192 TopM \u03b4 (TypedArgs \u03b4)\n\nnotation \"\u27e6 \" t \" \u27e7\" => Denote.denote t\n\ninstance DenoteOp (\u03b4: Dialect \u03b1 \u03c3 \u03b5) [Semantics \u03b4]: Denote \u03b4 Op where\n  denote op := denoteOp \u03b4 op\n-- This only works for single-BB regions with no arguments\ninstance DenoteRegion (\u03b4: Dialect \u03b1 \u03c3 \u03b5) [Semantics \u03b4]: Denote \u03b4 Region where\n  denote r := denoteRegion \u03b4 r []\n\n-- Not for regions because we need to specify the fuel\n\n@[simp] theorem Denote.denoteOp [Semantics \u03b4]:\n  Denote.denote (self := DenoteOp \u03b4) op = denoteOp \u03b4 op := rfl\n@[simp] theorem Denote.denoteRegion [Semantics \u03b4]:\n  Denote.denote (self := DenoteRegion \u03b4) r = denoteRegion \u03b4 r [] := rfl\n\n/-\n### Simplification tactics for semantics monad\n-/\n\nmacro \"simp_semantics_monad\" : tactic =>\n  `(tactic| simp_monad <;>\n            (repeat rw [TopM.get_unfold]) <;>\n            (repeat rw [TopM.get_unfold]) <;> simp)\n\nmacro \"simp_semantics_monad\" \"at\" Hname:ident : tactic =>\n  `(tactic| simp_monad at $Hname <;>\n            (repeat rw [TopM.get_unfold] at $Hname:ident) <;>\n            (repeat rw [TopM.set_unfold] at $Hname:ident) <;>\n            simp at $Hname:ident)\n\nmacro \"simp_semantics_monad\" \"at\" \"*\" : tactic =>\n  `(tactic| simp_monad at * <;>\n            (repeat rw [TopM.get_unfold] at *) <;>\n            (repeat rw [TopM.set_unfold] at *) <;>\n            simp at *)\n\n/-\n### General proofs on denotation of programs\n-/\n\ntheorem denoteOpArgs_res [S: Semantics \u0394] \u2983args: List (TypedSSAVal \u0394)\u2984:\n    \u2200 \u2983env r env'\u2984, denoteOpArgs \u0394 args env = Except.ok (r, env') \u2192\n    env' = env := by\n  induction args <;> intros env r env' H\n  case nil =>\n    simp [denoteOpArgs] at *\n    simp_monad at *\n    cases H; subst r env\n    simp\n  case cons head tail HInd =>\n    simp [denoteOpArgs]; simp [denoteOpArgs] at H\n    have \u27e8headName, head\u03c4\u27e9 := head\n    simp_monad at *\n    revert H\n    cases Hhead: TopM.get head\u03c4 headName env <;> simp <;> intros H <;> try contradiction\n    case ok r =>\n    rw [TopM.get_unfold] at Hhead\n    have \u27e8rRes, rEnv\u27e9 := r; simp at Hhead; cases Hhead; subst rEnv\n    simp [denoteOpArgs] at HInd\n    split at H <;> try contradiction\n    case h_2 tailR HTailR =>\n    have \u27e8tailRes, tailEnv\u27e9 := tailR\n    simp at *\n    specialize HInd HTailR\n    cases H; subst env'\n    assumption\n\ntheorem denoteTypedArgs_cons_args {\u03b4: Dialect \u03b1 \u03c3 \u03b5} {argsHead: TypedArg \u03b4}\n    {argsTail: TypedArgs \u03b4} {vals: List SSAVal} {env: SSAEnv \u03b4} {res} {env': SSAEnv \u03b4} :\n  denoteTypedArgs (argsHead::argsTail) vals env = Except.ok (res, env') \u2192\n  \u2203 valHead valTail,\n    vals = valHead::valTail \u2227\n    TopM.set argsHead.fst valHead argsHead.snd env =\n      Except.ok ((), env.set valHead argsHead.fst argsHead.snd) \u2227\n    denoteTypedArgs argsTail valTail (env.set valHead argsHead.fst argsHead.snd) =\n      Except.ok ((), env'):= by\n  intros H\n  simp [denoteTypedArgs] at H\n  cases vals <;> try contradiction\n  case cons headVal tailVal =>\n  exists headVal\n  exists tailVal\n  simp_monad at *\n  revert H\n  split <;> intros H <;> try contradiction\n  case h_2 v Hv =>\n  have \u27e8fst, snd\u27e9 := v; cases fst\n  case unit =>\n  simp_semantics_monad at *\n  revert Hv; split <;> intros Hv <;> try contradiction\n  simp at Hv; subst snd\n  simp [H]\n\n\ntheorem denoteTypedArgs_cons_unfold (headArgs: TypedArg \u0394) (tailArgs: List (TypedArg \u0394)) (env: SSAEnv \u0394):\n    denoteTypedArgs (headArgs::tailArgs) (headVal::tailVal) env =\n      (do\n         TopM.set headArgs.fst headVal headArgs.snd\n         denoteTypedArgs tailArgs tailVal) env := by\n  simp [denoteTypedArgs]\n\n\n/-\n### Congruence proofs for denotations\n\nCongruence proofs prove that if the execution of a denotation is succeeding\nand returns an environment, an equivalent input environment will yield the\nsame resulting environment, and the same result.\n-/\n\ntheorem denoteOpArgs_equiv [S: Semantics \u0394] \u2983args: List (TypedSSAVal \u0394)\u2984:\n    \u2200 \u2983env r env'\u2984, denoteOpArgs \u0394 args env = Except.ok (r, env') \u2192\n    \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n    denoteOpArgs \u0394 args env\u2082 = Except.ok (r, env\u2082) := by\n  induction args <;> intros env r env' H\n  case nil =>\n    simp [denoteOpArgs] at *\n    simp_monad at *\n    cases H; subst r env\n    simp\n  case cons head tail HInd =>\n    intros env\u2082 Henv\u2082\n    simp [denoteOpArgs]; simp [denoteOpArgs] at H\n    have \u27e8headName, head\u03c4\u27e9 := head\n    simp_monad at *\n    revert H\n    cases Hhead: TopM.get head\u03c4 headName env <;> simp <;> intros H <;> try contradiction\n    case ok headR =>\n    have \u27e8headR, headEnv\u27e9 := headR\n    simp [TopM.get_equiv Henv\u2082 Hhead]\n    split at H <;> try contradiction\n    case h_2 tailR HTailR =>\n    simp at H; cases H; subst env' r\n    have \u27e8tailR, tailEnv\u27e9 := tailR; simp at HTailR\n    have AOEU := HInd HTailR\n    rw [TopM.get_unfold] at Hhead; simp at Hhead; cases Hhead; subst env\n    specialize HInd HTailR Henv\u2082\n    simp [denoteOpArgs] at HInd\n    simp_monad at *\n    simp [HInd]\n\n\ntheorem denoteTypedArgs_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5} {args: TypedArgs \u0394} :\n    \u2200 \u2983vals env\u2081 r env\u2081'\u2984,\n    denoteTypedArgs args vals env\u2081 = Except.ok (r, env\u2081') \u2192\n    \u2200 \u2983env\u2082\u2984, env\u2081.equiv env\u2082 \u2192\n    \u2203 env\u2082', env\u2081'.equiv env\u2082' \u2227\n             denoteTypedArgs args vals env\u2082 = Except.ok (r, env\u2082') := by\n  induction args\n  case nil =>\n    intros val env\u2081 r env\u2081' H env\u2082 Henv\u2082\n    simp [denoteTypedArgs] at *\n    exists env\u2082\n    simp_monad at *; subst H; assumption\n  case cons argsHead argsTail HInd =>\n    intros vals env\u2081 r env\u2081' H env\u2082 Henv\u2082\n    have \u27e8valsHead, valsTail, HVals, HHead, HTail\u27e9 := denoteTypedArgs_cons_args H\n    subst vals\n    have HHead\u2082 := TopM.set_equiv Henv\u2082 HHead\n    specialize (HInd HTail (by apply SSAEnv.equiv_set Henv\u2082))\n    have \u27e8env\u2082', Hequiv\u2082', Henv\u2082'\u27e9 := HInd\n    exists env\u2082'\n    cases r\n    rw [denoteTypedArgs_cons_unfold]\n    simp_monad\n    rw [HHead\u2082]; simp; rw [Henv\u2082']\n    simp; assumption\n\n\ndef denoteRegionsEquivInvariant {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n    (regions: List (TypedArgs \u0394 -> TopM \u0394 (TypedArgs \u0394))) :=\n  \u2200 \u2983region\u2984, region \u2208 regions \u2192\n  \u2200 \u2983args env res env'\u2984, region args env = Except.ok (res, env') \u2192\n  \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n  \u2203 env\u2082', env'.equiv env\u2082' \u2227\n    region args env\u2082 = Except.ok (res, env\u2082')\n\n\ntheorem denoteRegionByIx_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  (regions: List (TypedArgs \u0394 -> TopM \u0394 (TypedArgs \u0394))) :\n    denoteRegionsEquivInvariant regions ->\n    \u2200 \u2983idx args env res env'\u2984,\n    TopM.denoteRegionsByIx regions idx args env = Except.ok (res, env') \u2192\n    \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n    \u2203 env\u2082', env'.equiv env\u2082' \u2227\n      TopM.denoteRegionsByIx regions idx args env\u2082 = Except.ok (res, env\u2082') := by\n  induction regions <;> intros H idx args env res env' Hrun env\u2082 Henv\u2082 <;> try contradiction\n  case cons head tail HInd =>\n    cases idx\n    case zero =>\n      simp at *\n      specialize (H (by constructor) (by assumption) (by assumption))\n      assumption\n    case succ idx' =>\n      specialize (HInd (by\n        intros region Hregions args env res env' Hrun env\u2082 Henv\u2082\n        specialize (H (.tail _ Hregions) (by assumption) (by assumption))\n        assumption\n      ))\n      simp at Hrun\n      specialize (HInd Hrun Henv\u2082)\n      assumption\n\ntheorem OpM.toTopM_regions_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  (regions: List (TypedArgs \u0394 -> TopM \u0394 (TypedArgs \u0394))) :\n    denoteRegionsEquivInvariant regions ->\n    \u2200 \u2983opM env res env'\u2984,\n    OpM.toTopM regions opM env = Except.ok (res, env') \u2192\n    \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n    \u2203 env\u2082', env'.equiv env\u2082' \u2227\n      OpM.toTopM regions opM env\u2082 = Except.ok (res, env\u2082') := by\n  intros Hregs opM\n  induction opM <;> intros env res env' H env\u2082 Henv\u2082 <;> try contradiction\n\n  -- Ret case, we return the same value in both cases, so this is trivial\n  case Ret ret =>\n    unfold OpM.toTopM; unfold OpM.toTopM at H\n    cases H <;> simp\n    exists env\u2082\n\n  -- Running a region. This is the inductive case over opM\n  case RunRegion idx args continuation HInd =>\n    unfold OpM.toTopM; unfold OpM.toTopM at H\n    have \u27e8\u27e8resReg, envReg\u27e9, HReg\u27e9 := ExceptMonad.split H\n    simp_monad at *\n    rw [HReg] at H; simp at H\n\n    have \u27e8env\u2082', Henv\u2082', HIx\u27e9 := denoteRegionByIx_equiv regions Hregs HReg Henv\u2082\n    specialize (HInd resReg (by assumption) (by assumption))\n    rw [HIx]; simp\n    assumption\n\n\ntheorem denoteOp_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394] : \u2200 \u2983op: Op \u0394\u2984,\n    \u2200 \u2983env r env'\u2984,\n    denoteOp \u0394 op env = Except.ok (r, env') \u2192\n    \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n    \u2203 env\u2082', env'.equiv env\u2082' \u2227\n      denoteOp \u0394 op env\u2082 = Except.ok (r, env\u2082')\n  | Op.mk op_name res args regions attrs => by\n    unfold denoteOp; simp_monad\n    intros env r env' H env\u2082 Henv\u2082\n\n    -- denoteOpArgs\n    split at H <;> try contradiction\n    case h_2 _ argsRes HargsRes =>\n    have \u27e8argRes, argResEnv\u27e9 := argsRes\n    have _ := denoteOpArgs_res HargsRes; subst argResEnv\n    simp [denoteOpArgs_equiv HargsRes Henv\u2082]\n\n    -- interpreting regions\n    split at H <;> try contradiction\n    case h_2 regR HregR =>\n    have \u27e8regR, regEnv\u27e9 := regR\n    have HRegInd := OpM.toTopM_regions_equiv (TopM.mapDenoteRegion \u0394 regions)\n    have \u27e8regEnv\u2082, HregEnv\u2082, HregR\u2082\u27e9 := HRegInd (by sorry) HregR Henv\u2082 -- mutual induction\n    simp [HregR\u2082]\n    -- interpreting the operation results\n    cases res\n    case nil =>\n      simp at *; cases H; exists regEnv\u2082\n      subst r env'; simp [HregEnv\u2082]\n      sorry -- unhandled case.\n    case cons headRes tailRes =>\n      cases tailRes\n      case cons _ _ => simp at *; cases H\n      case nil =>\n        simp\n        cases regR\n        case nil => simp at *; cases H\n        case cons opRHead opRTail =>\n          cases opRTail\n          case cons _ _ =>  simp at *; cases H\n          case nil =>\n              simp at *\n              split at H <;> try contradiction\n              case h_2 setRes HSetRes =>\n              sorry -- failed proof port\n              /-\n              rw [TopM.set_equiv HregEnv\u2082 HSetRes]; simp\n              cases H; have \u27e8setRes, setEnv\u27e9 := setRes\n              have Hset := TopM.set_ok HSetRes; cases Hset; simp at *\n              exists (regEnv\u2082.set headRes.fst opRHead.fst opRHead.snd)\n              subst setEnv\n              simp\n              apply SSAEnv.equiv_set\n              assumption\n              -/\n\ntheorem denoteOps_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]:\n  \u2200 \u2983ops: List (Op \u0394)\u2984 \u2983env res env'\u2984,\n  denoteOps \u0394 ops env = Except.ok (res, env') \u2192\n  \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n  \u2203 env\u2082', env'.equiv env\u2082' \u2227\n  denoteOps \u0394 ops env\u2082 = Except.ok (res, env\u2082')\n  | [] => by\n    intros env res env' H env\u2082 Henv\u2082\n    simp [denoteOps] at *; simp_monad at *\n    cases H; subst res env\n    constructor <;> simp; try assumption\n  | head::tail => by\n    intros env res env' H env\u2082 Henv\u2082\n    unfold denoteOps at H; simp_monad at H\n    match TAIL: tail with\n    | .nil =>\n      apply denoteOp_equiv <;> assumption\n    | .cons head2 tail2 =>\n      simp [denoteOps] at *; simp_monad at *\n      split at H <;> try contradiction\n      case h_2 headR HHeadR =>\n      have \u27e8headR, headEnv\u27e9 := headR; simp at *\n      have \u27e8envHead, HenvHead, HdenoteHead\u27e9 := denoteOp_equiv HHeadR Henv\u2082\n      simp [HdenoteHead]\n      rw [\u2190TAIL] at H; rw [\u2190TAIL]\n      apply denoteOps_equiv H HenvHead\n\ntheorem denoteRegion_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394] \u2983region\u2984:\n    \u2200 \u2983args env res env'\u2984,\n    denoteRegion \u0394 region args env = Except.ok (res, env') \u2192\n    \u2200 \u2983env\u2082\u2984, env.equiv env\u2082 \u2192\n    \u2203 env\u2082', env'.equiv env\u2082' \u2227\n    denoteRegion \u0394 region args env\u2082 = Except.ok (res, env\u2082') := by\n  cases region\n  case mk rName rArgs rOps =>\n  intros args env res env' H env\u2082 Henv\u2082\n  simp [denoteRegion] at *; simp_monad at *\n  (split at H <;> try contradiction); rename_i argsR HargsR\n  have \u27e8argsR, argsEnv\u27e9 := argsR; cases argsR\n  have \u27e8argsEnv\u2082, HargsEnv\u2082, HdenoteArgs\u27e9 := denoteTypedArgs_equiv HargsR Henv\u2082\n  rw [HdenoteArgs]; simp at *\n  apply denoteOps_equiv (by assumption) (by assumption)\n\ntheorem mapDenoteRegion_equiv {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394] \u2983regions\u2984:\n    denoteRegionsEquivInvariant (TopM.mapDenoteRegion \u0394 regions) := by\n  match REGIONS: regions with\n  | .nil =>\n    intros region HregIn args env res env' H env\u2082 Henv\u2082\n    contradiction\n  | .cons head tail =>\n    intros region HregIn args env res env' H env\u2082 Henv\u2082\n    simp [TopM.mapDenoteRegion] at HregIn\n    cases HregIn\n    case inl HXX =>\n      subst HXX;\n      sorry\n      -- simp [HXX] at *;\n      -- simp [TopM.scoped] at *; simp_monad at *\n      -- (split at H <;> try contradiction); rename_i regR HregR\n      -- have \u27e8regR, regEnv\u27e9 := regR; simp at *; cases H; subst regR env'\n      -- have \u27e8regEnv\u2082, _, Hregion\u27e9 := denoteRegion_equiv HregR Henv\u2082\n      -- exists env\u2082\n      -- simp [Hregion]\n      -- assumption\n    case inr HXX =>\n      apply mapDenoteRegion_equiv <;> assumption\n\n/-\n### Commutation proofs for denotations\n\nProve that adding a value to an disjoint name does not change the\nresult of running a denotation.\n-/\n\ntheorem denoteOpArgs_set_commutes [S: Semantics \u0394]\n    \u2983args: List (TypedSSAVal \u0394)\u2984:\n    \u2200 \u2983env r resEnv\u2984,\n    denoteOpArgs \u0394 args env = Except.ok (r, resEnv) ->\n    \u2200 \u2983name\u2984, args.all (fun arg => name \u2260 arg.fst) ->\n    \u2200 \u03c4 v, denoteOpArgs \u0394 args (env.set name \u03c4 v) = Except.ok (r, resEnv.set name \u03c4 v) := by\n  induction args\n  case nil =>\n    intros env r resEnv H\n    simp [denoteOpArgs] at *\n    simp_monad at *\n    cases H; subst r env; simp\n  case cons head tail HInd =>\n    intros env r resEnv H name Hname \u03c4 v\n    simp [denoteOpArgs]; simp [denoteOpArgs] at H\n    have \u27e8headName, head\u03c4\u27e9 := head\n    simp_monad at *\n    cases Hhead: (TopM.get head\u03c4 headName env)\n    case error _ =>\n      rw [Hhead] at H; contradiction\n    case ok headRes =>\n      rw [Hhead] at H\n      simp [List.all, List.foldr] at Hname\n      have \u27e8Hname_head, _\u27e9 := Hname\n      rw [TopM.get_env_set_commutes Hhead Hname_head]\n      simp at *\n      split at H <;> try contradiction\n      case h_2 rTail Htail =>\n      have \u27e8rTailRes, rTailEnv\u27e9 := rTail\n      simp at H; have \u27e8_, _\u27e9 := H; subst r resEnv\n      simp [denoteOpArgs] at *\n      simp [bind, StateT.bind, Except.bind, pure, StateT.pure, Except.pure] at HInd\n      rw [HInd] <;> assumption\n\ndef denoteTypedArgs_set_commutes (regArgs: TypedArgs \u0394):\n    \u2200 \u2983vals env res env'\u2984,\n    denoteTypedArgs regArgs vals env = Except.ok (res, env') \u2192\n    \u2200 \u2983name\u2984, name \u2209 vals \u2192\n    \u2200 \u03c4 v, \u2203 env'',\n    (SSAEnv.set name \u03c4 v env').equiv env'' \u2227\n    denoteTypedArgs regArgs vals (SSAEnv.set name \u03c4 v env) = Except.ok (res, env'') := by\n  induction regArgs\n  case nil =>\n    intros vals env res env' H name _ \u03c4 v\n    simp [denoteTypedArgs] at *; simp_monad at *; subst env\n    simp [SSAEnv.equiv_rfl]\n  case cons head tail HInd =>\n    intros vals env res env' H name Hname \u03c4 v\n    have \u27e8valHead, valTail, HVal, HHead, HTail\u27e9 := denoteTypedArgs_cons_args H\n    subst vals; have \u27e8HNameHead, HNameTail\u27e9 := List.ne_mem_cons Hname\n    rw [denoteTypedArgs_cons_unfold]; simp_monad\n    have \u27e8envHead, HEnvHeadEquiv, HEnvHead\u27e9 := TopM.set_env_set_commutes HHead HNameHead \u03c4 v\n    have \u27e8HEnvHead, _\u27e9 := TopM.set_ok HEnvHead\n    simp at HEnvHead; subst envHead\n    have \u27e8env'', HEquiv, HdenoteTail\u27e9 := HInd HTail HNameTail \u03c4 v\n    have \u27e8env\u2082'', Henv\u2082equiv'', Henv\u2082''\u27e9 := denoteTypedArgs_equiv HdenoteTail HEnvHeadEquiv\n    exists env\u2082''\n    simp [HEnvHead, Henv\u2082'']\n    apply SSAEnv.equiv_trans (by assumption) (by assumption)\n\n\ndef denoteRegionsSetCommutesInvariant {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]\n    name \u03c4 v (regions: List (TypedArgs \u0394 -> TopM \u0394 (TypedArgs \u0394))) :=\n    \u2200 \u2983region\u2984, region \u2208 regions \u2192\n      \u2200 \u2983args env res env'\u2984, region args env = Except.ok (res, env') \u2192\n      \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n      region args (env.set name \u03c4 v)  = Except.ok (res, env\u2082')\n\n\ntheorem denoteRegionByIx_set_commutes {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]\n  \u2983name \u03c4 v\u2984 \u2983regions: List (TypedArgs \u0394 -> TopM \u0394 (TypedArgs \u0394))\u2984 :\n    denoteRegionsSetCommutesInvariant name \u03c4 v regions ->\n    \u2200 \u2983idx args env res env'\u2984,\n    TopM.denoteRegionsByIx regions idx args env = Except.ok (res, env') ->\n    \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n    TopM.denoteRegionsByIx regions idx args (env.set name \u03c4 v) = Except.ok (res, env\u2082') := by\n  induction regions <;> intros H idx args env res env' Hrun <;> try contradiction\n  case cons head tail HInd =>\n    cases idx\n    case zero =>\n      simp at *\n      specialize (H (by constructor) (by assumption))\n      assumption\n    case succ idx' =>\n      specialize (HInd (by\n        intros region Hregions args env res env' Hrun\n        specialize (H (.tail _ Hregions) (by assumption))\n        assumption\n      ))\n      simp at Hrun\n      apply (HInd Hrun)\n\ndef OpM.toTopM_set_commutes {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]\n  (regions: List (TypedArgs \u0394 -> TopM \u0394 (TypedArgs \u0394))) :\n    denoteRegionsEquivInvariant regions \u2192\n    \u2200 \u2983name \u03c4 v\u2984, denoteRegionsSetCommutesInvariant name \u03c4 v regions \u2192\n    \u2200 \u2983opM env res env'\u2984, OpM.toTopM regions opM env = Except.ok (res, env') \u2192\n    \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n      OpM.toTopM regions opM (env.set name \u03c4 v) = Except.ok (res, env\u2082') := by\n  intros HRegsEquiv name \u03c4 v HRegs opM\n  induction opM <;> intros env res env' H <;> try contradiction\n\n  -- Ret case, we return the same value in both cases, so this is trivial\n  case Ret ret =>\n    unfold OpM.toTopM; unfold OpM.toTopM at H\n    cases H <;> simp\n    exists env.set name \u03c4 v\n    simp_monad; apply SSAEnv.equiv_rfl\n\n  -- Running a region. This is the inductive case over opM\n  case RunRegion idx args continuation HInd =>\n    unfold OpM.toTopM; unfold OpM.toTopM at H\n    have \u27e8\u27e8resReg, envReg\u27e9, HReg\u27e9 := ExceptMonad.split H\n    simp_monad at *\n    rw [HReg] at H; simp at H\n\n    have \u27e8env\u2082', Henv\u2082', HIx\u27e9 := denoteRegionByIx_set_commutes HRegs HReg\n    rw [HIx]; simp\n    have \u27e8env\u2083', Henv\u2083', HInd\u27e9 := HInd resReg H\n    have \u27e8env\u2084', Henv\u2084', HRegEquiv\u27e9 := toTopM_regions_equiv regions (by assumption) HInd  Henv\u2082'\n    exists env\u2084'; simp [HRegEquiv]\n    apply SSAEnv.equiv_trans (by assumption) (by assumption)\n\ndef run_denoteOp_env_set_preserves {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]:\n    \u2200 \u2983op env r env'\u2984, denoteOp \u0394 op env = Except.ok (r, env') \u2192\n    \u2200 \u03c4 v, \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n    denoteOp \u0394 op (SSAEnv.set name \u03c4 v env) = Except.ok (r, env\u2082') :=\n  by sorry\n\ndef run_denoteOps_env_set_preserves {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]:\n    \u2200 \u2983ops env res env'\u2984, denoteOps \u0394 ops env = Except.ok (res, env') \u2192\n    \u2200 \u03c4 v, \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n    denoteOps \u0394 ops (env.set name \u03c4 v) = Except.ok (res, env\u2082') :=\n  by sorry\n\n\ndef denoteRegion_env_set_preserves {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]:\n    \u2200 \u2983region args env res env'\u2984, denoteRegion \u0394 region args env = Except.ok (res, env') \u2192\n    \u2200 \u03c4 v, \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n    denoteRegion \u0394 region args (env.set name \u03c4 v) = Except.ok (res, env\u2082') :=\n  by sorry\n\n\ndef mapDenoteRegion_env_set_preserves {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]:\n    \u2200 \u2983region regions\u2984, region \u2208 (TopM.mapDenoteRegion \u0394 regions) \u2192\n    \u2200 \u2983args env res env'\u2984, region args env = Except.ok (res, env') \u2192\n    \u2200 \u03c4 v, \u2203 env\u2082', (env'.set name \u03c4 v).equiv env\u2082' \u2227\n    region args (env.set name \u03c4 v)  = Except.ok (res, env\u2082') :=\n  by sorry\n\n/-\n### PostSSAEnv\n\nA PostSSAEnv is a predicate on an environment, that check that it can be the\nresulting environment of the interpretation of a TopM monad.\n-/\n\ndef postSSAEnv (m: TopM \u03b4 R) (env: SSAEnv \u03b4) : Prop :=\n  \u2203 env' v, run m env' = .ok (v, env)\n\n/-\n### Running lemmas\n\nThese lemmas enable us to equationally reason with run (denoteFoo .. ) input\n-/\n\ntheorem run_seq {\u0394: Dialect \u03b1 \u03c3 \u03b5} {ma: TopM \u0394 Unit} {mb: TopM \u0394 \u03b2}\n  {env: SSAEnv \u0394}:\n  run (do ma; mb) env =\n    match run ma env with\n    | .ok ((), env') => run mb env'\n    | .error e => .error e := by {\n  simp[run];\n  cases H : StateT.run ma env;\n  case error err => {\n    simp[H];\n    simp[bind, Except.bind];\n  }\n  case ok out => {\n    simp[H, bind, Except.bind];\n  }\n}\n\n\n\nabbrev TopM.bind (ma: TopM \u0394 \u03b1) (a2mb: \u03b1 \u2192 TopM \u0394 \u03b2) : TopM \u0394 \u03b2 :=\n  StateT.bind ma a2mb\n\nabbrev TopM.map (f: a -> b) (ma: TopM \u0394 a): TopM \u0394 b := StateT.map f ma\n\n/-\nRun distributes over '>>='\n-/\ntheorem run_bind {\u0394: Dialect \u03b1 \u03c3 \u03b5} {ma: TopM \u0394 a} {k: a \u2192 TopM \u0394 b}\n  {env: SSAEnv \u0394}:\n  run (do let a \u2190 ma; k a) env =\n    match run ma env with\n    | .ok (a, env') => run (k a) env'\n    | .error e => .error e := by {\n  simp[run];\n  cases H : StateT.run ma env;\n  case error err => {\n    simp[H];\n    simp[bind, Except.bind];\n  }\n  case ok out => {\n    simp[H, bind, Except.bind];\n  }\n}\n\ntheorem run_bind2 {\u0394: Dialect \u03b1 \u03c3 \u03b5} {ma: TopM \u0394 a} {k: a \u2192 TopM \u0394 b}\n  {env: SSAEnv \u0394}:\n  run (StateT.bind ma k) env =\n    match run ma env with\n    | .ok (a, env') => run (k a) env'\n    | .error e => .error e := by {\n  simp[run, TopM.bind];\n  cases H : StateT.run ma env;\n  case error err => {\n    simp[bind, Except.bind, StateT.bind, StateT.run] at *;\n    simp[H];\n\n  }\n  case ok out => {\n    simp[bind, Except.bind, StateT.bind, StateT.run] at *;\n    simp[H];\n  }\n}\n\ntheorem run_bind3 {\u0394: Dialect \u03b1 \u03c3 \u03b5} {ma: TopM \u0394 a} {k: a \u2192 TopM \u0394 b}\n  {env: SSAEnv \u0394}:\n  run (StateT.bind ma (fun x => k x)) env =\n    match run ma env with\n    | .ok (a, env') => run (k a) env'\n    | .error e => .error e := by {\n  simp[run, TopM.bind];\n  cases H : StateT.run ma env;\n  case error err => {\n    simp[bind, Except.bind, StateT.bind, StateT.run] at *;\n    simp[H];\n\n  }\n  case ok out => {\n    simp[bind, Except.bind, StateT.bind, StateT.run] at *;\n    simp[H];\n  }\n}\n\n/-\nrunning where the output of the first command is ignored\n-/\ntheorem run_bind_ {\u0394: Dialect \u03b1 \u03c3 \u03b5} {ma: TopM \u0394 a} {mb: TopM \u0394 b}\n  {env: SSAEnv \u0394}:\n  run (do let _ \u2190 ma; mb) env =\n    match run ma env with\n    | .ok (a_, env') => run mb env'\n    | .error e => .error e := by {\n  simp[run];\n  cases H : StateT.run ma env;\n  case error err => {\n    simp[H];\n    simp[bind, Except.bind];\n  }\n  case ok out => {\n    simp[H, bind, Except.bind];\n  }\n}\n\n\ntheorem run_bind_success {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  {ma: TopM \u0394 a} {a2mb: a \u2192 TopM \u0394 b} {env: SSAEnv \u0394}\n  {va: a} {env': SSAEnv \u0394}\n  (MA: ma env = Except.ok (va, env')):\n  run (ma >>= a2mb) env = run (a2mb va) env' := by {\n    simp[bind, StateT.bind, Except.bind];\n    simp[run, StateT.run] at *;\n    simp[MA];\n}\n\n/-\ndenotation of a region is to run arguments, followed by ops.\n-/\ntheorem run_denoteRegion {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n (args: TypedArgs \u0394)\n (env: SSAEnv \u0394)\n (name: String)\n (formals: List (TypedSSAVal \u0394))\n (ops: List (Op \u0394)):\n     run (denoteRegion \u0394 (Region.mk name formals ops) args) env = run\n      (do\n        denoteTypedArgs args (List.map Prod.fst formals)\n        denoteOps \u0394 ops) env\n := by { simp[denoteRegion]; }\n\n/-\ndenotation of empty typed args is success\n-/\ntheorem run_denoteTypedArgs_nil {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n (env: SSAEnv \u0394):\n   run (denoteTypedArgs [] []) env = Except.ok ((), env) := by {\n    simp[denoteTypedArgs, pure, run, StateT.run, StateT.pure, Except.pure];\n}\n\ntheorem run_denoteOps_nil {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  (env: SSAEnv \u0394):\n  run (denoteOps \u0394 []) env = Except.ok ([], env) := by {\n  simp[denoteOps];\n  simp [pure, StateT.pure, run, StateT.run, Except.pure];\n}\n\ntheorem run_denoteOps_cons {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  (env: SSAEnv \u0394) (op op': Op \u0394) (ops: List (Op \u0394)):\n  run (denoteOps \u0394 (op :: op' :: ops)) env =\n  run (do let _ \u2190 denoteOp \u0394 op; denoteOps \u0394 (op' :: ops)) env := by {\n  simp[denoteOps];\n}\n\ntheorem run_denoteOps_singleton {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  (env: SSAEnv \u0394) (op: Op \u0394):\n  run (denoteOps \u0394 [op]) env = run (denoteOp \u0394 op) env := by {\n  simp[denoteOps];\n}\n\ntheorem run_denoteOp {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  (env: SSAEnv \u0394)\n  (name : String)\n  (res args : List (TypedSSAVal \u0394))\n  (regions : List (Region \u0394))\n  (attrs : AttrDict \u0394) :\n   run (denoteOp \u0394 (Op.mk name res args regions attrs)) env =\n   run (do\n        let args \u2190 denoteOpArgs \u0394 args\n        let ret \u2190\n          OpM.toTopM (TopM.mapDenoteRegion \u0394 regions)\n              (Semantics.semantics_op (IOp.mk name (List.map Prod.snd res) args (OpM.denoteRegions regions 0) attrs))\n        match res with\n          | [] => pure ret\n          | [res] =>\n            match ret with\n            | [{ fst := \u03c4, snd := v }] => do\n              TopM.set \u03c4 res.fst v\n              pure ret\n            | x => do\n              TopM.raiseUB (toString \"denoteOp: expected 1 return value, got '\" ++ toString ret ++ toString \"'\")\n              pure ret\n          | x => do\n            TopM.raiseUB (toString \"denoteOp: expected 0 or 1 results, got '\" ++ toString res ++ toString \"'\")\n            pure ret) env := by {\n   simp [denoteOp];\n}\n\n/-\ninternal use. For public facing uses, it is cleaner to use\nrun_denoteOpArgs_cons_{success,failure}\n-/\ntheorem run_denoteOpArgs_cons_ {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  {env: SSAEnv \u0394} {name: SSAVal}  {ty: MLIRType \u0394} {args: List (TypedSSAVal \u0394)}:\n  run (denoteOpArgs \u0394 (\u27e8name, ty\u27e9::args)) env = run (do\n     let x \u2190 TopM.get ty name\n     let xs \u2190 denoteOpArgs \u0394 args\n     return \u27e8ty, x\u27e9::xs\n  ) env := by {\n  simp[denoteOpArgs];\n}\n\n/-\ninternal use. For public facing uses, it is\ncleaner to use run_TopM_get_{success,failure}\n-/\ntheorem run_TopM_get_\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  {env: SSAEnv \u0394}\n  {ty: MLIRType \u0394}\n  {name: SSAVal}:\n  run (TopM.get ty name) env =\n  Except.ok (match SSAEnv.get name ty env  with\n  | .some v => v\n  | .none => default, env) := by {\n  simp[TopM.get, run, StateT.run, StateT.get, bind, StateT.bind, Except.bind, pure,\n  Except.pure, StateT.pure];\n  cases H:SSAEnv.get name ty env <;> simp;\n}\n\ntheorem run_TopM_get_success\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  {env: SSAEnv \u0394}\n  {ty: MLIRType \u0394}\n  {v: ty.eval}\n  {name: SSAVal}\n  {ENV: SSAEnv.get name ty env = .some v}:\n  run (TopM.get ty name) env =\n  Except.ok (v, env) := by {\n  simp[run_TopM_get_, ENV];\n}\n\n/-\nevaluate 'denoteOpArgs' when the head of the argument list succeeds in being\nevaluated.\n-/\ntheorem run_denoteOpArgs_cons_success\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  {env: SSAEnv \u0394}\n  {ty: MLIRType \u0394}\n  {v: ty.eval}\n  {name: SSAVal}\n  {ENV: SSAEnv.get name ty env = .some v}\n  {args: List (TypedSSAVal \u0394)}:\n  run (denoteOpArgs \u0394 (\u27e8name, ty\u27e9::args)) env =\n  match run (denoteOpArgs \u0394 args) env with\n    | Except.ok (xs, env') => Except.ok (\u27e8ty, v\u27e9::xs, env')\n    | Except.error e => Except.error e := by {\n  simp[run_denoteOpArgs_cons_];\n  simp [run_bind];\n  simp[run_TopM_get_success (ENV := ENV)];\n  simp[pure, StateT.pure, run, StateT.run, Except.pure];\n  cases denoteOpArgs \u0394 args env <;> simp\n}\n\n\n\ntheorem run_denoteOpArgs_nil {\u0394: Dialect \u03b1 \u03c3 \u03b5} {S: Semantics \u0394}\n  {env: SSAEnv \u0394}:\n  run (denoteOpArgs \u0394 []) env = Except.ok ([], env) := by {\n  simp[denoteOpArgs];\n  simp[run, pure, StateT.run, StateT.pure, Except.pure];\n}\n\ntheorem run_pure\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  {env: SSAEnv \u0394}\n  {v: a}:  run (pure v) env = .ok (v, env) := by {\n  simp[run, pure, StateT.run, StateT.pure, Except.pure];\n}\n\ntheorem OpM_toTopM_denoteRegion\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  {args: TypedArgs \u0394}\n  {r: Region \u0394}\n  {rs: List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394))}:\n    (OpM.toTopM rs (OpM.denoteRegion r ix args)) =\n      TopM.denoteRegionsByIx rs ix args := by {\n   simp[OpM.denoteRegion];\n   simp[OpM.toTopM];\n}\n\ntheorem run_OpM_toTopM_denoteRegion\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  {args: TypedArgs \u0394}\n  {r: Region \u0394}\n  {env: SSAEnv \u0394}\n  {rs: List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394))}:\n    run (OpM.toTopM rs (OpM.denoteRegion r ix args)) env =\n      run (TopM.denoteRegionsByIx rs ix args) env := by {\n   simp[OpM.denoteRegion];\n   simp[OpM.toTopM];\n}\n\ntheorem run_OpM_toTopM_Ret\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  {env: SSAEnv \u0394}\n  {v: TypedArgs \u0394}\n  {rs: List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394))}:\n    run (OpM.toTopM rs (OpM.Ret v)) env = .ok (v, env) := by {\n   simp[OpM.denoteRegion];\n   simp[OpM.toTopM];\n   simp[run_pure];\n }\n\ntheorem TopM_mapDenoteRegion_cons\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]\n  {r: Region \u0394}\n  {rs: List (Region \u0394)}:\n  TopM.mapDenoteRegion \u0394 (List.cons r rs) =\n  TopM.scoped \u2218 denoteRegion \u0394 r :: TopM.mapDenoteRegion \u0394 rs := by {\n  simp[TopM.mapDenoteRegion];\n}\ntheorem TopM_mapDenoteRegion_nil\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5} [S: Semantics \u0394]:\n  TopM.mapDenoteRegion \u0394 List.nil = [] := by {\n  simp[TopM.mapDenoteRegion];\n}\n\ntheorem OpM_denoteRegions_cons\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  {r: Region \u0394}\n  {rs: List (Region \u0394)}\n  {ix: Nat}:\n    OpM.denoteRegions (r::rs) ix =\n    OpM.denoteRegion r ix :: OpM.denoteRegions rs (ix + 1) := by {\n  simp[OpM.denoteRegions];\n\n}\ntheorem OpM_denoteRegions_nil\n  {\u0394: Dialect \u03b1 \u03c3 \u03b5} {ix: Nat}:\n    OpM.denoteRegions (\u0394 := \u0394) [] ix = [] := by {\n   simp[OpM.denoteRegions];\n}\n\ntheorem run_TopM_denoteRegionsByIx_cons\n {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n {ix: Nat}\n {r: TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394)}\n {rs: List (TypedArgs \u0394 \u2192 TopM \u0394 (TypedArgs \u0394))}\n {args: TypedArgs \u0394}\n {env: SSAEnv \u0394}:\n  run (TopM.denoteRegionsByIx (r::rs) ix args) env =\n   run (match ix with\n       | 0 => r args\n       | ix' + 1 => TopM.denoteRegionsByIx rs ix' args) env := by {\n  simp[TopM.denoteRegionsByIx];\n}\n\n/-\napply 'funext' on OpM.denoteRegion for unfolding.\n-/\ndef OpM_denoteRegion_unfold {\u0394: Dialect \u03b1 \u03c3 \u03b5}\n  (_r: Region \u0394)\n  (ix: Nat):\n   OpM.denoteRegion _r ix = fun args => OpM.RunRegion ix args (fun retvals => OpM.Ret retvals) := by {\n   funext args;\n   simp[OpM.denoteRegion];\n}\n\nabbrev OpM_denoteRegion {\u0394: Dialect \u03b1 \u03c3 \u03b5} (_r: Region \u0394) (ix: Nat)\n   := OpM_denoteRegion_unfold (\u0394 := \u0394) (_r := _r) (ix := ix)\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/Semantics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225123, "lm_q2_score": 0.03567855421017194, "lm_q1q2_score": 0.014398682380301907}}
{"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} [\ud835\udc9e : category.{v} C]\ninclude \ud835\udc9e\n\nvariables {F : J \u2964 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  : \u03a0 (s : cone F), s.X \u27f6 t.X)\n(fac'  : \u2200 (s : cone F) (j : J), lift s \u226b t.\u03c0.app j = s.\u03c0.app j . obviously)\n(uniq' : \u2200 (s : cone F) (m : s.X \u27f6 t.X) (w : \u2200 j : J, m \u226b t.\u03c0.app j = s.\u03c0.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\u27e8by intros P Q; cases P; cases Q; congr; ext; solve_by_elim\u27e9\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 \u27f6 t :=\n{ hom := h.lift s }\n\nlemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s \u27f6 t} :\n  f = f' :=\nhave \u2200 {g : s \u27f6 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 : \u03a0 (s : cone F), s \u27f6 t)\n  (uniq' : \u2200 (s : cone F) (m : s \u27f6 t), m = lift s) : is_limit t :=\n{ lift := \u03bb s, (lift s).hom,\n  uniq' := \u03bb 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 \u2245 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 \u2245 t) : is_limit t :=\nis_limit.mk_cone_morphism\n  (\u03bb s, P.lift_cone_morphism s \u226b i.hom)\n  (\u03bb s m, by rw \u2190i.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 \u27f6 t.X) :\n  m = h.lift { X := W, \u03c0 := { app := \u03bb b, m \u226b t.\u03c0.app b } } :=\nh.uniq { X := W, \u03c0 := { app := \u03bb b, m \u226b t.\u03c0.app b } } m (\u03bb 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 \u27f6 t.X}\n  (w : \u2200 j, f \u226b t.\u03c0.app j = f' \u226b t.\u03c0.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 \u27f6 X` is the same as\n  a cone on `F` with vertex `W`. -/\ndef hom_iso (h : is_limit t) (W : C) : (W \u27f6 t.X) \u2245 ((const J).obj W \u27f9 F) :=\n{ hom := \u03bb f, (t.extend f).\u03c0,\n  inv := \u03bb \u03c0, h.lift { X := W, \u03c0 := \u03c0 },\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 \u27f6 t.X) :\n  (is_limit.hom_iso h W).hom f = (t.extend f).\u03c0 := 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 \u2245 F.cones :=\nnat_iso.of_components (\u03bb W, is_limit.hom_iso h (unop W)) (by tidy)\n\ndef hom_iso' (h : is_limit t) (W : C) :\n  (W \u27f6 t.X) \u2245 { p : \u03a0 j, W \u27f6 F.obj j // \u2200 {j j'} (f : j \u27f6 j'), p j \u226b F.map f = p j' } :=\nh.hom_iso W \u226a\u226b\n{ hom := \u03bb \u03c0,\n  \u27e8\u03bb j, \u03c0.app j, \u03bb j j' f,\n   by convert \u2190(\u03c0.naturality f).symm; apply id_comp\u27e9,\n  inv := \u03bb p,\n  { app := \u03bb j, p.1 j,\n    naturality' := \u03bb j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } }\n\n/-- If G : C \u2192 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 \u2964 D) [faithful G]\n  (ht : is_limit (G.map_cone t)) (lift : \u03a0 (s : cone F), s.X \u27f6 t.X)\n  (h : \u2200 s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t :=\n{ lift := lift,\n  fac' := \u03bb s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac,\n  uniq' := \u03bb s m w, begin\n    apply G.injectivity, rw h,\n    refine ht.uniq (G.map_cone s) _ (\u03bb j, _),\n    convert \u2190congr_arg (\u03bb 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 \u2245 \u03a0 s, unique (s \u27f6 t) :=\n{ hom := \u03bb h s,\n  { default := h.lift_cone_morphism s,\n    uniq := \u03bb _, h.uniq_cone_morphism },\n  inv := \u03bb h,\n  { lift := \u03bb s, (h s).default.hom,\n    uniq' := \u03bb s f w, congr_arg cone_morphism.hom ((h s).uniq \u27e8f, w\u27e9) } }\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  : \u03a0 (s : cocone F), t.X \u27f6 s.X)\n(fac'  : \u2200 (s : cocone F) (j : J), t.\u03b9.app j \u226b desc s = s.\u03b9.app j . obviously)\n(uniq' : \u2200 (s : cocone F) (m : t.X \u27f6 s.X) (w : \u2200 j : J, t.\u03b9.app j \u226b m = s.\u03b9.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\u27e8by intros P Q; cases P; cases Q; congr; ext; solve_by_elim\u27e9\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 \u27f6 s :=\n{ hom := h.desc s }\n\nlemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t \u27f6 s} :\n  f = f' :=\nhave \u2200 {g : t \u27f6 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 : \u03a0 (s : cocone F), t \u27f6 s)\n  (uniq' : \u2200 (s : cocone F) (m : t \u27f6 s), m = desc s) : is_colimit t :=\n{ desc := \u03bb s, (desc s).hom,\n  uniq' := \u03bb 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 \u2245 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 \u2245 t) : is_colimit t :=\nis_colimit.mk_cocone_morphism\n  (\u03bb s, i.inv \u226b P.desc_cocone_morphism s)\n  (\u03bb 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 \u27f6 W) :\n  m = h.desc { X := W, \u03b9 := { app := \u03bb b, t.\u03b9.app b \u226b m,\n    naturality' := by intros; erw [\u2190assoc, t.\u03b9.naturality, comp_id, comp_id] } } :=\nh.uniq { X := W, \u03b9 := { app := \u03bb b, t.\u03b9.app b \u226b m, naturality' := _ } } m (\u03bb 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 \u27f6 W}\n  (w : \u2200 j, t.\u03b9.app j \u226b f = t.\u03b9.app j \u226b 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 \u27f6 W` is the same as\n  a cocone on `F` with vertex `W`. -/\ndef hom_iso (h : is_colimit t) (W : C) : (t.X \u27f6 W) \u2245 (F \u27f9 (const J).obj W) :=\n{ hom := \u03bb f, (t.extend f).\u03b9,\n  inv := \u03bb \u03b9, h.desc { X := W, \u03b9 := \u03b9 },\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 \u27f6 W) :\n  (is_colimit.hom_iso h W).hom f = (t.extend f).\u03b9 := 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) \u2245 F.cocones :=\nnat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw \u2190assoc; refl)\n\ndef hom_iso' (h : is_colimit t) (W : C) :\n  (t.X \u27f6 W) \u2245 { p : \u03a0 j, F.obj j \u27f6 W // \u2200 {j j' : J} (f : j \u27f6 j'), F.map f \u226b p j' = p j } :=\nh.hom_iso W \u226a\u226b\n{ hom := \u03bb \u03b9,\n  \u27e8\u03bb j, \u03b9.app j, \u03bb j j' f,\n   by convert \u2190(\u03b9.naturality f); apply comp_id\u27e9,\n  inv := \u03bb p,\n  { app := \u03bb j, p.1 j,\n    naturality' := \u03bb j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } }\n\n/-- If G : C \u2192 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 \u2964 D) [faithful G]\n  (ht : is_colimit (G.map_cocone t)) (desc : \u03a0 (s : cocone F), t.X \u27f6 s.X)\n  (h : \u2200 s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t :=\n{ desc := desc,\n  fac' := \u03bb s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac,\n  uniq' := \u03bb s m w, begin\n    apply G.injectivity, rw h,\n    refine ht.uniq (G.map_cocone s) _ (\u03bb j, _),\n    convert \u2190congr_arg (\u03bb 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 \u2245 \u03a0 s, unique (t \u27f6 s) :=\n{ hom := \u03bb h s,\n  { default := h.desc_cocone_morphism s,\n    uniq := \u03bb _, h.uniq_cocone_morphism },\n  inv := \u03bb h,\n  { desc := \u03bb s, (h s).default.hom,\n    uniq' := \u03bb s f w, congr_arg cocone_morphism.hom ((h s).uniq \u27e8f, w\u27e9) } }\n\nsection limit\n\n/-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/\nclass has_limit (F : J \u2964 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 \u2964 C`. -/\n@[class] def has_limits_of_shape := \u03a0 F : J \u2964 C, has_limit F\n\n/-- `C` has all (small) limits if it has limits of every shape. -/\n@[class] def has_limits :=\n\u03a0 {J : Type v} {\ud835\udca5 : 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 \u2964 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 \u2964 C) [has_limit F] : cone F := has_limit.cone F\n\ndef limit (F : J \u2964 C) [has_limit F] := (limit.cone F).X\n\ndef limit.\u03c0 (F : J \u2964 C) [has_limit F] (j : J) : limit F \u27f6 F.obj j :=\n(limit.cone F).\u03c0.app j\n\n@[simp] lemma limit.cone_\u03c0 {F : J \u2964 C} [has_limit F] (j : J) :\n  (limit.cone F).\u03c0.app j = limit.\u03c0 _ j := rfl\n\n@[simp] lemma limit.w (F : J \u2964 C) [has_limit F] {j j' : J} (f : j \u27f6 j') :\n  limit.\u03c0 F j \u226b F.map f = limit.\u03c0 F j' := (limit.cone F).w f\n\ndef limit.is_limit (F : J \u2964 C) [has_limit F] : is_limit (limit.cone F) :=\nhas_limit.is_limit.{v} F\n\ndef limit.lift (F : J \u2964 C) [has_limit F] (c : cone F) : c.X \u27f6 limit F :=\n(limit.is_limit F).lift c\n\n@[simp] lemma limit.is_limit_lift {F : J \u2964 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_\u03c0 {F : J \u2964 C} [has_limit F] (c : cone F) (j : J) :\n  limit.lift F c \u226b limit.\u03c0 F j = c.\u03c0.app j :=\nis_limit.fac _ c j\n\ndef limit.cone_morphism {F : J \u2964 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 \u2964 C} [has_limit F] (c : cone F) :\n  (limit.cone_morphism c).hom = limit.lift F c := rfl\n@[simp] lemma limit.cone_morphism_\u03c0 {F : J \u2964 C} [has_limit F] (c : cone F) (j : J) :\n  (limit.cone_morphism c).hom \u226b limit.\u03c0 F j = c.\u03c0.app j :=\nby erw is_limit.fac\n\n@[extensionality] lemma limit.hom_ext {F : J \u2964 C} [has_limit F] {X : C} {f f' : X \u27f6 limit F}\n  (w : \u2200 j, f \u226b limit.\u03c0 F j = f' \u226b limit.\u03c0 F j) : f = f' :=\n(limit.is_limit F).hom_ext w\n\ndef limit.hom_iso (F : J \u2964 C) [has_limit F] (W : C) : (W \u27f6 limit F) \u2245 (F.cones.obj (op W)) :=\n(limit.is_limit F).hom_iso W\n\n@[simp] lemma limit.hom_iso_hom (F : J \u2964 C) [has_limit F] {W : C} (f : W \u27f6 limit F):\n  (limit.hom_iso F W).hom f = (const J).map f \u226b (limit.cone F).\u03c0 :=\n(limit.is_limit F).hom_iso_hom f\n\ndef limit.hom_iso' (F : J \u2964 C) [has_limit F] (W : C) :\n  (W \u27f6 limit F) \u2245 { p : \u03a0 j, W \u27f6 F.obj j // \u2200 {j j' : J} (f : j \u27f6 j'), p j \u226b F.map f = p j' } :=\n(limit.is_limit F).hom_iso' W\n\nlemma limit.lift_extend {F : J \u2964 C} [has_limit F] (c : cone F) {X : C} (f : X \u27f6 c.X) :\n  limit.lift F (c.extend f) = f \u226b limit.lift F c :=\nby obviously\n\nsection pre\nvariables {K : Type v} [small_category K]\nvariables (F) [has_limit F] (E : K \u2964 J) [has_limit (E \u22d9 F)]\n\ndef limit.pre : limit F \u27f6 limit (E \u22d9 F) :=\nlimit.lift (E \u22d9 F)\n  { X := limit F,\n    \u03c0 := { app := \u03bb k, limit.\u03c0 F (E.obj k) } }\n\n@[simp] lemma limit.pre_\u03c0 (k : K) : limit.pre F E \u226b limit.\u03c0 (E \u22d9 F) k = limit.\u03c0 F (E.obj k) :=\nby erw is_limit.fac\n\n@[simp] lemma limit.lift_pre (c : cone F) :\n  limit.lift F c \u226b limit.pre F E = limit.lift (E \u22d9 F) (c.whisker E) :=\nby ext; simp\n\nvariables {L : Type v} [small_category L]\nvariables (D : L \u2964 K) [has_limit (D \u22d9 E \u22d9 F)]\n\n@[simp] lemma limit.pre_pre : limit.pre F E \u226b limit.pre (E \u22d9 F) D = limit.pre F (D \u22d9 E) :=\nby ext j; erw [assoc, limit.pre_\u03c0, limit.pre_\u03c0, limit.pre_\u03c0]; refl\n\nend pre\n\nsection post\nvariables {D : Type u'} [\ud835\udc9f : category.{v} D]\ninclude \ud835\udc9f\n\nvariables (F) [has_limit F] (G : C \u2964 D) [has_limit (F \u22d9 G)]\n\ndef limit.post : G.obj (limit F) \u27f6 limit (F \u22d9 G) :=\nlimit.lift (F \u22d9 G)\n{ X := G.obj (limit F),\n  \u03c0 :=\n  { app := \u03bb j, G.map (limit.\u03c0 F j),\n    naturality' :=\n      by intros j j' f; erw [\u2190G.map_comp, limits.cone.w, id_comp]; refl } }\n\n@[simp] lemma limit.post_\u03c0 (j : J) : limit.post F G \u226b limit.\u03c0 (F \u22d9 G) j = G.map (limit.\u03c0 F j) :=\nby erw is_limit.fac\n\n@[simp] lemma limit.lift_post (c : cone F) :\n  G.map (limit.lift F c) \u226b limit.post F G = limit.lift (F \u22d9 G) (G.map_cone c) :=\nby ext; rw [assoc, limit.post_\u03c0, \u2190G.map_comp, limit.lift_\u03c0, limit.lift_\u03c0]; refl\n\n@[simp] lemma limit.post_post\n  {E : Type u''} [category.{v} E] (H : D \u2964 E) [has_limit ((F \u22d9 G) \u22d9 H)] :\n/- H G (limit F) \u27f6 H (limit (F \u22d9 G)) \u27f6 limit ((F \u22d9 G) \u22d9 H) equals -/\n/- H G (limit F) \u27f6 limit (F \u22d9 (G \u22d9 H)) -/\n  H.map (limit.post F G) \u226b limit.post (F \u22d9 G) H = limit.post F (G \u22d9 H) :=\nby ext; erw [assoc, limit.post_\u03c0, \u2190H.map_comp, limit.post_\u03c0, limit.post_\u03c0]; refl\n\nend post\n\nlemma limit.pre_post {K : Type v} [small_category K] {D : Type u'} [category.{v} D]\n  (E : K \u2964 J) (F : J \u2964 C) (G : C \u2964 D)\n  [has_limit F] [has_limit (E \u22d9 F)] [has_limit (F \u22d9 G)] [has_limit ((E \u22d9 F) \u22d9 G)] :\n/- G (limit F) \u27f6 G (limit (E \u22d9 F)) \u27f6 limit ((E \u22d9 F) \u22d9 G) vs -/\n/- G (limit F) \u27f6 limit F \u22d9 G \u27f6 limit (E \u22d9 (F \u22d9 G)) or -/\n  G.map (limit.pre F E) \u226b limit.post (E \u22d9 F) G = limit.post F G \u226b limit.pre (F \u22d9 G) E :=\nby ext; erw [assoc, limit.post_\u03c0, \u2190G.map_comp, limit.pre_\u03c0, assoc, limit.pre_\u03c0, limit.post_\u03c0]; 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 \u2964 C) \u2964 C :=\n{ obj := \u03bb F, limit F,\n  map := \u03bb F G \u03b1, limit.lift G\n    { X := limit F,\n      \u03c0 :=\n      { app := \u03bb j, limit.\u03c0 F j \u226b \u03b1.app j,\n        naturality' := \u03bb j j' f,\n          by erw [id_comp, assoc, \u2190\u03b1.naturality, \u2190assoc, limit.w] } },\n  map_comp' := \u03bb F G H \u03b1 \u03b2,\n    by ext; erw [assoc, is_limit.fac, is_limit.fac, \u2190assoc, is_limit.fac, assoc]; refl }\n\nvariables {F} {G : J \u2964 C} (\u03b1 : F \u27f9 G)\n\n@[simp] lemma lim.map_\u03c0 (j : J) : lim.map \u03b1 \u226b limit.\u03c0 G j = limit.\u03c0 F j \u226b \u03b1.app j :=\nby apply is_limit.fac\n\n@[simp] lemma limit.lift_map (c : cone F) :\n  limit.lift F c \u226b lim.map \u03b1 = limit.lift G ((cones.postcompose \u03b1).obj c) :=\nby ext; rw [assoc, lim.map_\u03c0, \u2190assoc, limit.lift_\u03c0, limit.lift_\u03c0]; refl\n\nlemma limit.map_pre {K : Type v} [small_category K] [has_limits_of_shape K C] (E : K \u2964 J) :\n  lim.map \u03b1 \u226b limit.pre G E = limit.pre F E \u226b lim.map (whisker_left E \u03b1) :=\nby ext; rw [assoc, limit.pre_\u03c0, lim.map_\u03c0, assoc, lim.map_\u03c0, \u2190assoc, limit.pre_\u03c0]; refl\n\nlemma limit.map_pre' {K : Type v} [small_category K] [has_limits_of_shape.{v} K C]\n  (F : J \u2964 C) {E\u2081 E\u2082 : K \u2964 J} (\u03b1 : E\u2081 \u27f9 E\u2082) :\n  limit.pre F E\u2082 = limit.pre F E\u2081 \u226b lim.map (whisker_right \u03b1 F) :=\nby ext1; simp [(category.assoc _ _ _ _).symm]\n\nlemma limit.id_pre (F : J \u2964 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 \u2964 D) :\n/- H (limit F) \u27f6 H (limit G) \u27f6 limit (G \u22d9 H) vs\n   H (limit F) \u27f6 limit (F \u22d9 H) \u27f6 limit (G \u22d9 H) -/\n  H.map (lim.map \u03b1) \u226b limit.post G H = limit.post F H \u226b lim.map (whisker_right \u03b1 H) :=\nbegin\n  ext,\n  rw [assoc, limit.post_\u03c0, \u2190H.map_comp, lim.map_\u03c0, H.map_comp],\n  rw [assoc, lim.map_\u03c0, \u2190assoc, limit.post_\u03c0],\n  refl\nend\n\ndef lim_yoneda : lim \u22d9 yoneda \u2245 category_theory.cones J C :=\nnat_iso.of_components (\u03bb F, nat_iso.of_components (\u03bb 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 \u2964 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 \u2964 C`. -/\n@[class] def has_colimits_of_shape := \u03a0 F : J \u2964 C, has_colimit F\n\n/-- `C` has all (small) colimits if it has limits of every shape. -/\n@[class] def has_colimits :=\n\u03a0 {J : Type v} {\ud835\udca5 : 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 \u2964 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 \u2964 C) [has_colimit F] : cocone F := has_colimit.cocone F\n\ndef colimit (F : J \u2964 C) [has_colimit F] := (colimit.cocone F).X\n\ndef colimit.\u03b9 (F : J \u2964 C) [has_colimit F] (j : J) : F.obj j \u27f6 colimit F :=\n(colimit.cocone F).\u03b9.app j\n\n@[simp] lemma colimit.cocone_\u03b9 {F : J \u2964 C} [has_colimit F] (j : J) :\n  (colimit.cocone F).\u03b9.app j = colimit.\u03b9 _ j := rfl\n\n@[simp] lemma colimit.w (F : J \u2964 C) [has_colimit F] {j j' : J} (f : j \u27f6 j') :\n  F.map f \u226b colimit.\u03b9 F j' = colimit.\u03b9 F j := (colimit.cocone F).w f\n\ndef colimit.is_colimit (F : J \u2964 C) [has_colimit F] : is_colimit (colimit.cocone F) :=\nhas_colimit.is_colimit.{v} F\n\ndef colimit.desc (F : J \u2964 C) [has_colimit F] (c : cocone F) : colimit F \u27f6 c.X :=\n(colimit.is_colimit F).desc c\n\n@[simp] lemma colimit.is_colimit_desc {F : J \u2964 C} [has_colimit F] (c : cocone F) :\n  (colimit.is_colimit F).desc c = colimit.desc F c := rfl\n\n@[simp] lemma colimit.\u03b9_desc {F : J \u2964 C} [has_colimit F] (c : cocone F) (j : J) :\n  colimit.\u03b9 F j \u226b colimit.desc F c = c.\u03b9.app j :=\nis_colimit.fac _ c j\n\ndef colimit.cocone_morphism {F : J \u2964 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 \u2964 C} [has_colimit F] (c : cocone F) :\n  (colimit.cocone_morphism c).hom = colimit.desc F c := rfl\n@[simp] lemma colimit.\u03b9_cocone_morphism {F : J \u2964 C} [has_colimit F] (c : cocone F) (j : J) :\n  colimit.\u03b9 F j \u226b (colimit.cocone_morphism c).hom = c.\u03b9.app j :=\nby erw is_colimit.fac\n\n@[extensionality] lemma colimit.hom_ext {F : J \u2964 C} [has_colimit F] {X : C} {f f' : colimit F \u27f6 X}\n  (w : \u2200 j, colimit.\u03b9 F j \u226b f = colimit.\u03b9 F j \u226b f') : f = f' :=\n(colimit.is_colimit F).hom_ext w\n\ndef colimit.hom_iso (F : J \u2964 C) [has_colimit F] (W : C) : (colimit F \u27f6 W) \u2245 (F.cocones.obj W) :=\n(colimit.is_colimit F).hom_iso W\n\n@[simp] lemma colimit.hom_iso_hom (F : J \u2964 C) [has_colimit F] {W : C} (f : colimit F \u27f6 W):\n  (colimit.hom_iso F W).hom f = (colimit.cocone F).\u03b9 \u226b (const J).map f :=\n(colimit.is_colimit F).hom_iso_hom f\n\ndef colimit.hom_iso' (F : J \u2964 C) [has_colimit F] (W : C) :\n  (colimit F \u27f6 W) \u2245 { p : \u03a0 j, F.obj j \u27f6 W // \u2200 {j j'} (f : j \u27f6 j'), F.map f \u226b p j' = p j } :=\n(colimit.is_colimit F).hom_iso' W\n\nlemma colimit.desc_extend (F : J \u2964 C) [has_colimit F] (c : cocone F) {X : C} (f : c.X \u27f6 X) :\n  colimit.desc F (c.extend f) = colimit.desc F c \u226b 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 \u2964 J) [has_colimit (E \u22d9 F)]\n\ndef colimit.pre : colimit (E \u22d9 F) \u27f6 colimit F :=\ncolimit.desc (E \u22d9 F)\n  { X := colimit F,\n    \u03b9 := { app := \u03bb k, colimit.\u03b9 F (E.obj k) } }\n\n@[simp] lemma colimit.\u03b9_pre (k : K) : colimit.\u03b9 (E \u22d9 F) k \u226b colimit.pre F E = colimit.\u03b9 F (E.obj k) :=\nby erw is_colimit.fac\n\n@[simp] lemma colimit.pre_desc (c : cocone F) :\n  colimit.pre F E \u226b colimit.desc F c = colimit.desc (E \u22d9 F) (c.whisker E) :=\nby ext; rw [\u2190assoc, colimit.\u03b9_pre]; simp\n\nvariables {L : Type v} [small_category L]\nvariables (D : L \u2964 K) [has_colimit (D \u22d9 E \u22d9 F)]\n\n@[simp] lemma colimit.pre_pre : colimit.pre (E \u22d9 F) D \u226b colimit.pre F E = colimit.pre F (D \u22d9 E) :=\nbegin\n  ext j,\n  rw [\u2190assoc, colimit.\u03b9_pre, colimit.\u03b9_pre],\n  letI : has_colimit ((D \u22d9 E) \u22d9 F) := show has_colimit (D \u22d9 E \u22d9 F), by apply_instance,\n  exact (colimit.\u03b9_pre F (D \u22d9 E) j).symm\nend\n\nend pre\n\nsection post\nvariables {D : Type u'} [\ud835\udc9f : category.{v} D]\ninclude \ud835\udc9f\n\nvariables (F) [has_colimit F] (G : C \u2964 D) [has_colimit (F \u22d9 G)]\n\ndef colimit.post : colimit (F \u22d9 G) \u27f6 G.obj (colimit F) :=\ncolimit.desc (F \u22d9 G)\n{ X := G.obj (colimit F),\n  \u03b9 :=\n  { app := \u03bb j, G.map (colimit.\u03b9 F j),\n    naturality' :=\n      by intros j j' f; erw [\u2190G.map_comp, limits.cocone.w, comp_id]; refl } }\n\n@[simp] lemma colimit.\u03b9_post (j : J) : colimit.\u03b9 (F \u22d9 G) j \u226b colimit.post F G  = G.map (colimit.\u03b9 F j) :=\nby erw is_colimit.fac\n\n@[simp] lemma colimit.post_desc (c : cocone F) :\n  colimit.post F G \u226b G.map (colimit.desc F c) = colimit.desc (F \u22d9 G) (G.map_cocone c) :=\nby ext; rw [\u2190assoc, colimit.\u03b9_post, \u2190G.map_comp, colimit.\u03b9_desc, colimit.\u03b9_desc]; refl\n\n@[simp] lemma colimit.post_post\n  {E : Type u''} [category.{v} E] (H : D \u2964 E) [has_colimit ((F \u22d9 G) \u22d9 H)] :\n/- H G (colimit F) \u27f6 H (colimit (F \u22d9 G)) \u27f6 colimit ((F \u22d9 G) \u22d9 H) equals -/\n/- H G (colimit F) \u27f6 colimit (F \u22d9 (G \u22d9 H)) -/\n  colimit.post (F \u22d9 G) H \u226b H.map (colimit.post F G) = colimit.post F (G \u22d9 H) :=\nbegin\n  ext,\n  rw [\u2190assoc, colimit.\u03b9_post, \u2190H.map_comp, colimit.\u03b9_post],\n  exact (colimit.\u03b9_post F (G \u22d9 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 \u2964 J) (F : J \u2964 C) (G : C \u2964 D)\n  [has_colimit F] [has_colimit (E \u22d9 F)] [has_colimit (F \u22d9 G)] [has_colimit ((E \u22d9 F) \u22d9 G)] :\n/- G (colimit F) \u27f6 G (colimit (E \u22d9 F)) \u27f6 colimit ((E \u22d9 F) \u22d9 G) vs -/\n/- G (colimit F) \u27f6 colimit F \u22d9 G \u27f6 colimit (E \u22d9 (F \u22d9 G)) or -/\n  colimit.post (E \u22d9 F) G \u226b G.map (colimit.pre F E) = colimit.pre (F \u22d9 G) E \u226b colimit.post F G :=\nbegin\n  ext,\n  rw [\u2190assoc, colimit.\u03b9_post, \u2190G.map_comp, colimit.\u03b9_pre, \u2190assoc],\n  letI : has_colimit (E \u22d9 F \u22d9 G) := show has_colimit ((E \u22d9 F) \u22d9 G), by apply_instance,\n  erw [colimit.\u03b9_pre (F \u22d9 G) E j, colimit.\u03b9_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 \u2964 C) \u2964 C :=\n{ obj := \u03bb F, colimit F,\n  map := \u03bb F G \u03b1, colimit.desc F\n    { X := colimit G,\n      \u03b9 :=\n      { app := \u03bb j, \u03b1.app j \u226b colimit.\u03b9 G j,\n        naturality' := \u03bb j j' f,\n          by erw [comp_id, \u2190assoc, \u03b1.naturality, assoc, colimit.w] } },\n  map_comp' := \u03bb F G H \u03b1 \u03b2,\n    by ext; erw [\u2190assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, \u2190assoc]; refl }\n\nvariables {F} {G : J \u2964 C} (\u03b1 : F \u27f9 G)\n\n@[simp] lemma colim.\u03b9_map (j : J) : colimit.\u03b9 F j \u226b colim.map \u03b1 = \u03b1.app j \u226b colimit.\u03b9 G j :=\nby apply is_colimit.fac\n\n@[simp] lemma colimit.map_desc (c : cocone G) :\n  colim.map \u03b1 \u226b colimit.desc G c = colimit.desc F ((cocones.precompose \u03b1).obj c) :=\nby ext; rw [\u2190assoc, colim.\u03b9_map, assoc, colimit.\u03b9_desc, colimit.\u03b9_desc]; refl\n\nlemma colimit.pre_map {K : Type v} [small_category K] [has_colimits_of_shape K C] (E : K \u2964 J) :\n  colimit.pre F E \u226b colim.map \u03b1 = colim.map (whisker_left E \u03b1) \u226b colimit.pre G E :=\nby ext; rw [\u2190assoc, colimit.\u03b9_pre, colim.\u03b9_map, \u2190assoc, colim.\u03b9_map, assoc, colimit.\u03b9_pre]; refl\n\nlemma colimit.pre_map' {K : Type v} [small_category K] [has_colimits_of_shape.{v} K C]\n  (F : J \u2964 C) {E\u2081 E\u2082 : K \u2964 J} (\u03b1 : E\u2081 \u27f9 E\u2082) :\n  colimit.pre F E\u2081 = colim.map (whisker_right \u03b1 F) \u226b colimit.pre F E\u2082 :=\nby ext1; simp [(category.assoc _ _ _ _).symm]\n\nlemma colimit.pre_id (F : J \u2964 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 \u2964 D) :\n/- H (colimit F) \u27f6 H (colimit G) \u27f6 colimit (G \u22d9 H) vs\n   H (colimit F) \u27f6 colimit (F \u22d9 H) \u27f6 colimit (G \u22d9 H) -/\n  colimit.post F H \u226b H.map (colim.map \u03b1) = colim.map (whisker_right \u03b1 H) \u226b colimit.post G H:=\nbegin\n  ext,\n  rw [\u2190assoc, colimit.\u03b9_post, \u2190H.map_comp, colim.\u03b9_map, H.map_comp],\n  rw [\u2190assoc, colim.\u03b9_map, assoc, colimit.\u03b9_post],\n  refl\nend\n\ndef colim_coyoneda : colim.op \u22d9 coyoneda \u2245 category_theory.cocones J C :=\nnat_iso.of_components (\u03bb F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy))\n  (by {tidy, rw [\u2190 category.assoc,\u2190 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 Lean.Elab.Command\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.Tactic.Location\nimport Lean.Elab.Tactic.Match\nimport Lean.Meta.Tactic.Split\nimport Lean.PrettyPrinter\n\nimport Lib.Data.List.Control\nimport Lib.Data.Array.Control\nimport Lib.Logic.Relation\nimport Lib.Meta.Dump\n\nmacro \"rintro1 \" t:term : tactic =>\n  `(tactic| intro x; match x with | $t:term => ?_)\n\nsyntax \"rintro \" term,* : tactic\n\nmacro_rules\n| `(tactic| rintro $([]),*) => `(tactic| skip)\n| `(tactic| rintro $(t::ts),*) =>\n  `(tactic| rintro1 $t <;> rintro $ts )\n\nmacro \"obtain \" p:term \" from \" d:term : tactic =>\n  `(tactic| match $d:term with | $p:term => ?_)\n\nmacro \"obtain \" p:term \" : \" q:term \" from \" d:term : tactic =>\n  `(tactic|\n    have h : $q := $d;\n    match h with | $p:term => ?_)\n\nnamespace Lean.Elab.Tactic\nopen Lean.Meta\n\nelab \"obtain\" \"!\" p:term \" from \" d:term : tactic =>\n  withMainContext do\n    let (e, mvarIds') \u2190 elabTermWithHoles d none `specialize (allowNaturalHoles := true)\n    let h := e.getAppFn\n    if h.isFVar then\n      let localDecl \u2190 getLocalDecl h.fvarId!\n      let mvarId \u2190 assert (\u2190 getMainGoal) localDecl.userName (\u2190 inferType e).headBeta e\n      let (newHyp', mvarId) \u2190 intro1P mvarId\n      let mvarId \u2190 tryClear mvarId h.fvarId!\n      replaceMainGoal (mvarId :: mvarIds')\n      withMainContext do\n        let newHyp \u2190 mkIdentFromRef\n            <| (\u2190 getLCtx).get! newHyp' |>.userName\n        let myMatch \u2190\n          `(tactic| match $newHyp:term with | $p => ?_ )\n        let stx \u2190 getRef\n        withMacroExpansion stx myMatch\n          <| Lean.Elab.Tactic.evalMatch myMatch\n        liftMetaTactic1 <| (tryClear . newHyp')\n    else\n      throwError \"'specialize' requires a term of the form `h x_1 .. x_n` where `h` appears in the local context\"\n\nmacro \"obtain!\" p:term \" from \" d:term : tactic =>\n  `(tactic| obtain ! $p from $d)\n\nend Lean.Elab.Tactic\n\nmacro \"left\" : tactic =>\n  `(tactic| apply Or.inl)\n\nmacro \"right\" : tactic =>\n  `(tactic| apply Or.inr)\n\nsyntax \"refl\" : tactic\n\nmacro \"congr\" : tactic =>\n  `(tactic| repeat first | apply congrArg | apply congrFun | refl)\n\n-- TODO: import mathlib and get rid of this\nsyntax \"extOrSkip\" (ident)* : tactic\nsyntax \"ext\" (ident)* : tactic\n\nmacro_rules\n| `(tactic| extOrSkip) => `(tactic| skip)\n| `(tactic| extOrSkip $x $xs) =>\n  `(tactic| apply funext; intro $x; extOrSkip $xs)\n\nmacro_rules\n| `(tactic| ext) => `(tactic| repeat (apply funext; intro))\n| `(tactic| ext $xs) =>\n  `(tactic| extOrSkip $xs)\n\nsyntax \"change\" term \"with\" term : tactic\n\n\nmacro \"change\" t:term \"with\" t':term : tactic =>\n  `(tactic| have H : $t = $t' := rfl; rw [H]; clear H )\n\nnamespace Lean.Elab.Tactic\n\ninitialize registerTraceClass `refl\ninitialize registerTraceClass `substAll\n\nopen Expr Lean.Meta\n\ndef applyUnifyAll (g : MVarId) (lmm : Expr) (allowMVars := false) : MetaM (List MVarId) := do\n  trace[auto.lemmas]\"try {lmm}\"\n  trace[auto.lemmas]\"type: {(\u2190 inferType lmm)}\"\n  trace[auto.goal]\"goal {(\u2190 inferType (mkMVar g))}\"\n  let gs \u2190 try apply g lmm\n           catch e =>\n             trace[auto.apply.failure]\"error: {lmm}\"\n             trace[auto.apply.failure]\"error: {e.toMessageData}\"\n             throw e\n  trace[auto.lemmas]\"{gs.length} new goals\"\n  let ls \u2190 gs.mapM \u03bb v => inferType (mkMVar v)\n  trace[auto.lemmas]\"{ls} all new goals\"\n  let b \u2190 gs.allM \u03bb v => do\n    return (\u2190 inferType (\u2190 inferType (mkMVar v))).isProp\n  if \u00ac (allowMVars \u2228 b) then\n    trace[auto.lemmas]\"failed\"\n    failure\n  trace[auto.lemmas]\"success\"\n  return gs\n\ndef tacRefl : TacticM Unit := do\n  let g := (\u2190 instantiateMVars (\u2190 getMainTarget)).consumeMData\n  match g with\n  | (app (app R x _) y _) => liftMetaTactic \u03bb g => do\n    let cl \u2190 mkAppOptM ``Reflexive #[none, R]\n    let inst \u2190 synthInstance cl\n    let reflLmm \u2190 mkAppOptM ``Reflexive.refl #[none, R, inst]\n    apply g reflLmm\n  | _ =>\n    trace[refl]\"ctorName: {g.ctorName}\"\n    let reflLmm \u2190 mkConstWithFreshMVarLevels ``Reflexive.refl\n    liftMetaTactic (apply . reflLmm) <|>\n      throwError \"Expection a reflexive relation: R x y\"\n\ndef tacSymm : TacticM Unit := do\n  let g := (\u2190 instantiateMVars (\u2190 getMainTarget)).consumeMData\n  match g with\n  | (app (app R x _) y _) => liftMetaTactic \u03bb g => do\n    let cl \u2190 mkAppOptM ``Symmetric #[none, R]\n    let inst \u2190 synthInstance cl\n    let symmLmm \u2190 mkAppOptM ``Symmetric.symmetry #[none, R, inst]\n    apply g symmLmm\n  | _ =>\n    trace[refl]\"ctorName: {g.ctorName}\"\n    let symmLmm \u2190 mkConstWithFreshMVarLevels ``Symmetric.symmetry\n    liftMetaTactic (apply . symmLmm) <|>\n      throwError \"Expection a symmetric relation: R x y\"\n\ndef tacSubstAll : TacticM Unit := do\n  let lctx \u2190 getLCtx\n  trace[substAll] \"hyps: {lctx.getFVars}\"\n\n  for h in lctx do\n    let t := (\u2190 instantiateMVars h.type).consumeMData\n\n    if \u00ac h.isAuxDecl then\n      match t with\n      | app (app eq lhs _) rhs _ =>\n        let lc \u2190 getLCtx\n        trace[substAll] \"{h.userName} : {t}\"\n        if let Option.some _ := lc.find? h.fvarId then\n          trace[substAll] \"valid hyp\"\n          if eq.isAppOf `Eq \u2227 (lhs.isFVar \u2228 rhs.isFVar) then\n            trace[substAll] \"var eq\"\n            liftMetaTactic1 (subst .  h.fvarId)\n      | _ =>\n        trace[substAll] \"ignore {h.userName} :  {t.ctorName} {t}\"\n\ndef SearchT (\u03b4 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) := (\u03b1 \u2192 m \u03b4) \u2192 m \u03b4\n\nnamespace SearchT\n\nvariable {\u03c3 : Type} {m : Type \u2192 Type}\nvariable {\u03b1 \u03b2 : Type}\n\ndef pure (x : \u03b1) : SearchT \u03b4 m \u03b1 :=\n\u03bb f => f x\n\ndef bind (x : SearchT \u03b4 m \u03b1) (f : \u03b1 \u2192 SearchT \u03b4 m \u03b2) : SearchT \u03b4 m \u03b2 :=\n\u03bb g => x \u03bb a => f a g\n\ninstance : Monad (SearchT \u03b4 m) where\n  pure := pure\n  bind := bind\n\nsection Alternative\nvariable [Alternative m] [Monad m] [MonadBacktrack \u03c3 m]\n\ndef failure  : SearchT \u03b4 m \u03b1 :=\n\u03bb f => Alternative.failure\n\ndef orElse (x : SearchT \u03b4 m \u03b1) (y : Unit \u2192 SearchT \u03b4 m \u03b1) : SearchT \u03b4 m \u03b1 :=\n\u03bb f => do\n  let s \u2190 saveState\n  Alternative.orElse (x f) \u03bb _ => restoreState s >>= \u03bb _ => y () f\n\ninstance : Alternative (SearchT \u03b4 m) where\n  failure := failure\n  orElse := orElse\n\nend Alternative\n\ndef pick [Alternative m] [Monad m] [MonadBacktrack \u03c3 m] (l : List \u03b1) : SearchT \u03b4 m \u03b1 :=\n\u03bb g => do\n  let s \u2190 saveState\n  l.firstM \u03bb a => do\n    restoreState s\n    g a\n\ndef pick' [Alternative m] [Monad m] [MonadBacktrack \u03c3 m] (l : Array \u03b1) : SearchT \u03b4 m \u03b1 :=\n\u03bb g => do\n  let s \u2190 saveState\n  l.firstM \u03bb a => do\n    restoreState s\n    g a\n\ninstance [Bind m] : MonadLift m (SearchT \u03b4 m) where\n  monadLift x f := x >>= f\n\ninstance [Bind m] [MonadEnv m] : MonadEnv (SearchT \u03b4 m) where\n  getEnv f := getEnv >>= f\n  modifyEnv x f := modifyEnv x >>= f\n\n-- instance [Bind m] [MonadExceptOf \u03b5 m] : MonadExceptOf \u03b5 (SearchT \u03b4 m) where\n--   throw e f := throw e\n--   tryCatch x f g := _\n\ninstance [Monad m] [MonadRef m] : MonadRef (SearchT \u03b4 m) where\n  getRef f := getRef >>= f\n  withRef s x f := withRef s (x f)\n\ninstance [Bind m] [AddErrorMessageContext m] : AddErrorMessageContext (SearchT \u03b4 m) where\n  add s m f := AddErrorMessageContext.add s m >>= f\n\ndef run [Pure m] (x : SearchT \u03b1 m \u03b1) : m \u03b1 := x Pure.pure\n\nend SearchT\n\nabbrev SearchTacticM \u03b4 := SearchT \u03b4 TacticM\n\nnamespace SearchTacticM\n\n-- instance [Bind m] : MonadFunctor m (SearchT m) where\n--   monadMap f x \u03b4 g := f _\n\ndef focus {\u03b1 : Type} (x : SearchTacticM \u03b4 \u03b1) : SearchTacticM \u03b4 \u03b1 := do\n  let mvarId :: mvarIds \u2190 getUnsolvedGoals | throwNoGoalsToBeSolved\n  setGoals [mvarId]\n  let a \u2190 x\n  let mvarIds' \u2190 getUnsolvedGoals\n  setGoals (mvarIds' ++ mvarIds)\n  pure a\n\ndef focusAndDone {\u03b1} (tactic : SearchTacticM \u03b4 \u03b1) : SearchTacticM \u03b4 \u03b1 :=\n  focus do\n    let a \u2190 tactic\n    done\n    pure a\n\nend SearchTacticM\n\ndef isDone : TacticM Bool :=\nOption.isSome <$> optional done\n\ndef allGoals [Monad m] [MonadLiftT TacticM m] (tac : m PUnit) : m PUnit := do\nlet gs \u2190 getGoals\nlet gs' \u2190 gs.mapM \u03bb g => do setGoals [g]; tac; getGoals\nsetGoals gs'.join\n\ndef tryTac [Alternative m] [Pure m] (x: m Unit) : m Unit :=\nAlternative.orElse x (\u03bb _ => pure ())\n\ndef iterate [Monad m] [MonadLiftT TacticM m]: Nat \u2192 m PUnit \u2192 m PUnit\n| 0, _ => pure ()\n| Nat.succ n, tac => do\n  unless (\u2190 isDone) do\n    -- tryTac (do\n      ( traceM `auto.iterate <| return s!\"iterate n = {n}\" : TacticM Unit)\n      tac\n      allGoals $ iterate n tac\n\ndef tacMyApply (e : Expr) : TacticM Unit :=\n  liftMetaTactic (applyUnifyAll . e)\n\nend Lean.Elab.Tactic\n\nopen Lean.Elab.Tactic\n\nelab \"apply1\" t:term : tactic =>\n  withMainContext (do tacMyApply (\u2190 elabTerm t none))\nelab \"refl\" : tactic => withMainContext Lean.Elab.Tactic.tacRefl\nelab \"symmetry\" : tactic => withMainContext Lean.Elab.Tactic.tacSymm\nelab \"substAll\" : tactic => withMainContext Lean.Elab.Tactic.tacSubstAll\n\nmacro \"exfalso\" : tactic =>\n  `(tactic| apply False.elim)\n\nmacro \"byContradiction\" h: ident : tactic =>\n  `(tactic| apply Classical.byContradiction; intro h)\n\nsyntax \"trans\" (term)? : tactic\n\nmacro_rules\n| `(tactic| trans ) => `(tactic| trans ?middle)\n| `(tactic| trans $t:term) =>\n  `(tactic|\n    -- show (?rel : ?\u03b1 \u2192 ?\u03b1 \u2192 ?t) ?x ?y ;\n    focus\n      refine' Trans.trans (r := ?rel) (s := ?rel) (t := ?rel)\n                         (self := ?inst) (b := $t) ?first ?second;\n      case inst => infer_instance\n      rotate_right 2 )\n\nopen Lean.Elab.Tactic\nopen Lean\n\n-- syntax (name := auto) \"auto\" : attr\n-- syntax (name := eauto) \"eauto\" : attr\n\nabbrev AutoExtension := SimpleScopedEnvExtension Name NameSet\n\ndef mkAutoAttr (attrName : Name) (attrDescr : String) (ext : AutoExtension) : 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 \u2190 getConstInfo declName\n        match info with\n        | ConstantInfo.inductInfo i =>\n          for c in i.ctors do\n            ext.add c attrKind\n        | _ =>\n          ext.add declName attrKind\n      discard <| go.run {} {}\n    erase := fun declName => do\n      let s := ext.getState (\u2190 getEnv)\n      let s := s.erase declName\n      modifyEnv fun env => ext.modifyState env fun _ => s\n  }\n\ndef mkAutoExt (extName : Name) : IO AutoExtension :=\n  registerSimpleScopedEnvExtension {\n    name     := extName\n    initial  := {}\n    addEntry := fun d e => d.insert e\n  }\n\ndef registerAutoAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter \"Ext\") : IO AutoExtension := do\n  let ext \u2190 mkAutoExt extName\n  mkAutoAttr attrName attrDescr ext\n  return ext\n\ninitialize autoExtension : AutoExtension \u2190 registerAutoAttr `auto \"auto closing lemma\"\n\n-- initialize autoLemmasAttr : TagAttribute \u2190 registerTagAttribute `auto \"auto lemmas\"\n-- initialize autoLemmasAttr : ParametricAttribute Unit \u2190\n--   registerAutoAttribute {\n--     name := `auto,\n--     descr := \"auto lemmas\",\n--     getParam := \u03bb _ _ => () }\nopen Lean\n-- open Tactic\nopen Lean Meta\n\n-- initialize extLemmasCache : DeclCache (DiscrTree Name) \u2190\n--   DeclCache.mk \"ext: initialize cache\" {} fun decl ci lemmas => do\n--     if let some keys := extAttribute.getParam (\u2190 getEnv) decl then\n--       lemmas.insertCore keys decl\n--     else\n--       lemmas\n\ndef getAutoLemmas [Monad m] [MonadEnv m] : m NameSet := do\n  let ns := autoExtension.getState (\u2190 getEnv)\n  return ns\n    |>.insert ``True.intro\n    |>.insert ``Iff.intro\n    |>.insert ``And.intro\n\ndef getAutoList [Monad m] [MonadEnv m] (hyps : Array Name := #[]) : m (Array Name) := do\n  return hyps ++ (\u2190 getAutoLemmas).toArray\n\ninitialize registerTraceClass `auto\ninitialize registerTraceClass `auto.apply\ninitialize registerTraceClass `auto.apply.attempts\ninitialize registerTraceClass `auto.apply.failure\ninitialize registerTraceClass `auto.destruct_hyp\ninitialize registerTraceClass `auto.goal\ninitialize registerTraceClass `auto.iterate\ninitialize registerTraceClass `auto.lemmas\n\nopen Lean\n\ndef Meta.applyAuto (ns : Array Name) (allowMVars := false) : SearchTacticM \u03b4 Unit :=\nSearchTacticM.focus do\n  let n \u2190 SearchT.pick' ns\n  traceM `auto.lemmas <| return s!\"Lemma: {n}\"\n  let mut lmm \u2190 (mkConstWithFreshMVarLevels n : TacticM _)\n  Lean.Elab.Term.synthesizeSyntheticMVars true\n  lmm \u2190 instantiateMVars lmm\n  liftMetaTactic (applyUnifyAll . lmm allowMVars)\n\ndef Meta.applyAssumption (allowMVars := false) : SearchTacticM \u03b4 Unit := SearchTacticM.focus $ do\n  let x \u2190 SearchT.pick' (\u2190 getLCtx).getFVarIds\n  let lctx \u2190 getLCtx\n  guard (\u00ac (lctx.get! x).isAuxDecl)\n  traceM `auto.lemmas <| return s!\"Hyp: {lctx.get! x |>.userName}\"\n  liftMetaTactic (applyUnifyAll . (mkFVar x) allowMVars)\n\nelab \"#print\" \"auto_db\" : command => do\n  IO.println (\u2190 getAutoLemmas).toList\n\ninstance : ToMessageData LocalContext where\n  toMessageData lctx := toMessageData\n    <| lctx.fvarIdToDecl.toList.map\n    <| LocalDecl.userName \u2218 Prod.snd\n\ndef Meta.destructHyp : TacticM Unit := focus $ do\n  let lctx \u2190 getLCtx\n  let mut changed := false\n  trace[auto.destruct_hyp] \"local context: {lctx}\"\n  for x in lctx do\n    trace[auto.destruct_hyp]\"local: {x.userName}\"\n    trace[auto.destruct_hyp]\"is type: {x.type}\"\n    let type \u2190 instantiateMVars x.type\n    if \u00ac x.isAuxDecl \u2227 type.isAppOf ``And then\n      let g \u2190 getMainGoal\n      let gs \u2190 cases g x.fvarId\n      replaceMainGoal <|\n        gs.toList.map <|\n          InductionSubgoal.mvarId \u2218 CasesSubgoal.toInductionSubgoal\n      changed := true\n  guard changed\n\nsection HOrElse\nvariable  [Alternative m] [Monad m] [MonadBacktrack \u03c3 m]\ninstance : HOrElse (m \u03b1) (SearchT \u03b4 m \u03b1) (SearchT \u03b4 m \u03b1) where\n  hOrElse x y := (Alternative.orElse (liftM x) y)\n\ninstance : HOrElse (SearchT \u03b4 m \u03b1) (m \u03b1) (SearchT \u03b4 m \u03b1) where\n  hOrElse x y := (Alternative.orElse x (liftM \u2218 y))\n\nend HOrElse\n\ndef withMainContext' (x : SearchTacticM \u03b4 \u03b1) : SearchTacticM \u03b4 \u03b1 :=\n\u03bb f => withMainContext (x f)\n\ndef Meta.tacAutoStep (ns : Array Name) (allowMVars := false) : SearchTacticM \u03b4 Unit :=\nwithMainContext' $\n  Lean.Elab.Tactic.tacRefl <|>\n  liftMetaTactic (do Meta.contradiction .; return []) <|>\n  Meta.applyAssumption allowMVars <|>\n  Meta.destructHyp <|>\n  liftMetaTactic1 ((some \u2218 Prod.snd) <$> intro1 .) <|>\n  Meta.applyAuto (allowMVars := allowMVars) ns\n  -- Meta.applyAuto ns allowMVars <|>\n  -- liftMetaTactic1 ((some \u2218 Prod.snd) <$> intro1 .)\n\ndef Meta.tacAuto (ns : Array Name) (bound : Option Nat)\n  (allowMVars := false) : SearchTacticM \u03b4 Unit :=\nlet bound := bound.getD 5\nSearchTacticM.focusAndDone $\niterate bound <| Meta.tacAutoStep ns allowMVars\n\ndef autoTac : TacticM Unit  := do\nMeta.tacAuto (\u2190 getAutoList) none |>.run\n\ndef autoStepTac : TacticM Unit  := do\nMeta.tacAutoStep (\u2190 getAutoList) |>.run\n\nnamespace Parser\n\nelab \"destruct_hyp\" : tactic => withMainContext Meta.destructHyp\n\nsyntax \"eauto\" \"[\" ident,* \"]\" : tactic\nsyntax \"auto\" (\"[\" ident,* \"]\")? (\" with \" num)? : tactic\n\nelab \"auto\" : tactic => do\n  withMainContext (Meta.tacAuto (\u2190 getAutoList) none).run\n\nelab \"auto\" \" with \" n:num : tactic => do\n  withMainContext (Meta.tacAuto (\u2190 getAutoList) (Syntax.isNatLit? n)).run\n\nelab \"auto\" \"[\" ids:ident,* \"]\": tactic => do\n  let ids \u2190 getAutoList (\u2190 ids.getElems.mapM resolveGlobalConstNoOverload)\n  withMainContext (Meta.tacAuto ids none).run\n\nelab \"auto\" \"[\" ids:ident,* \"]\" \" with \" n:num : tactic => do\n  let ids \u2190 getAutoList (\u2190 ids.getElems.mapM resolveGlobalConstNoOverload)\n  withMainContext (Meta.tacAuto ids (Syntax.isNatLit? n)).run\n\nelab \"eauto\" : tactic => do\n  withMainContext (Meta.tacAuto (\u2190 getAutoList) none true).run\nelab \"auto_step\" : tactic => do\n  withMainContext (Meta.tacAutoStep (\u2190 getAutoList)).run\nelab \"eauto_step\" : tactic => do\n  withMainContext (Meta.tacAutoStep (allowMVars := true) (\u2190 getAutoList)).run\nelab \"apply_auto\" : tactic => do\n  withMainContext (Meta.applyAuto (\u2190 getAutoList)).run\n\nelab \"eauto\" \"[\" ids:ident,* \"]\" : tactic => do\n  let ids \u2190 getAutoList (\u2190 ids.getElems.mapM resolveGlobalConstNoOverload)\n  withMainContext (Meta.tacAuto ids none true).run\n\nelab \"eauto\" \"[\" ids:ident,* \"]\" \" with \" n:num : tactic => do\n  let ids \u2190 getAutoList (\u2190 ids.getElems.mapM resolveGlobalConstNoOverload)\n  withMainContext (Meta.tacAuto ids (Syntax.isNatLit? n) true).run\n\nsyntax \"change\" term \"at\" ident : tactic\n\nelab \"change\" t:term \"at\" h:ident : tactic =>\n  withMainContext do\n    let h \u2190 getFVarId h\n    liftMetaTactic1 (changeLocalDecl . h (\u2190 elabTerm t none))\n\nelab \"apply_assumption\" : tactic =>\n  withMainContext (Meta.applyAssumption true).run\n\nend Parser\n\n-- macro \"auto\" : tactic =>\n--   `(tactic|\n--     solve\n--     | repeat\n--         first\n--         | refl\n--         | apply True.intro\n--         | assumption\n--         | destruct_hyp\n--         | apply And.intro\n--         | apply Iff.intro\n--         | intros _\n--         | apply_auto_lemma )\n\n-- macro \"auto_step\" : tactic =>\n--   `(tactic|\n--         first\n--         | refl\n--         | apply True.intro\n--         | assumption\n--         | destruct_hyp\n--         | apply And.intro\n--         | apply Iff.intro\n--         | intros _\n--         | apply_auto_lemma )\n\n-- theorem swapHyp {p q : Prop} (h : p) (h' : \u00ac p) : q := by\n--   cases h' h\n\n-- macro \"swapHyp\" h:term \"as\" h':ident : tactic =>\n--   `(tactic| apply Classical.byContradiction; intro $h' <;>\n--             first\n--             | apply $h ; clear $h\n--             | apply swapHyp $h <;> clear $h\n--               )\n\nopen Lean.Elab.Tactic\n\nelab \"all_but_first \" tac:tacticSeq : tactic => do\n  let mvarId :: mvarIds \u2190 getUnsolvedGoals\n    | throwNoGoalsToBeSolved\n  let mut gs := #[mvarId]\n  for g in mvarIds do\n    if \u2190 not <$> isExprMVarAssigned g then\n      setGoals [g]\n      tryTac <| withMainContext <| evalTactic tac\n      gs := gs.appendList (\u2190 getGoals)\n  setGoals gs.toList\n\nmacro:1 x:tactic \" </> \" y:tactic:0 : tactic =>\n  `(tactic| focus ($x:tactic; all_but_first ($y:tactic; done)))\n\nsyntax \"split\" \"*\" : tactic\nmacro_rules\n  | `(tactic| split*) => `(tactic| first | split <;> split* | skip)\n\nmacro \"have \" \" \u2190 \" \" : \" p:term \" := \" proof:term : tactic =>\n  `(tactic|\n    have h : $p := $proof ;\n    rw [\u2190 h] <;> clear h )\n\nmacro \"have \" \" \u2192 \" \" : \" p:term \" := \" proof:term : tactic =>\n  `(tactic|\n    have h : $p := $proof ;\n    rw [h] <;> clear h )\n\nnamespace Classical\n\ntheorem contradiction {p q} (hp : p) (hnp : \u00ac p) : q :=\nby cases hnp hp\n\nend Classical\n\nsyntax \"apply' \" term,* : tactic\n\nmacro_rules\n| `(tactic| apply' $(xs):term,* ) => do\n    if xs.elemsAndSeps.size == 0 then\n      `(tactic| skip)\n    else if xs.elemsAndSeps.size == 0 then\n      `(tactic| apply $(xs.elemsAndSeps[0]):term)\n    else\n      let xs' := { xs with elemsAndSeps := xs.elemsAndSeps[2:] }\n      `(tactic| apply $(xs.elemsAndSeps[0]):term; apply' $(xs'):term,*)\n\nmacro \"falseHyp\" h:ident : tactic =>\n  `(first\n    | refine' Classical.contradiction _ $h; clear $h\n    | apply Classical.contradiction $h; clear $h )\n\nelab \"fold\" foo:ident : tactic => do\n  let mut eqns := #[]\n  if let some xs \u2190 Lean.Meta.getEqnsFor? foo.getId then\n    eqns := xs\n  else if let some x \u2190 Lean.Meta.getUnfoldEqnFor? foo.getId then\n    eqns := #[x]\n  else\n    throwError \"{foo.getId} has no equational lemmas\"\n  liftMetaTactic1 \u03bb mvar => do\n    let tgt \u2190 inferType (mkMVar mvar)\n    let mut simpLmms : SimpTheorems := {}\n    for x in eqns do\n      simpLmms \u2190 simpLmms.addConst (inv := true) x\n    let r \u2190 Lean.Meta.simp tgt { simpTheorems := #[simpLmms] }\n    let newGoal \u2190 mkFreshExprMVar (some r.expr)\n    if let some pr := r.proof? then\n      assignExprMVar mvar (\u2190 mkEqMP pr newGoal)\n    else assignExprMVar mvar newGoal\n    return some newGoal.mvarId!\n\nmacro \"assume \" h:ident \" : \" t:term : tactic =>\n  `(tactic|\n      refine' \u03bb $h:ident : $t => ?_  )\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/Tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386101825929835, "lm_q2_score": 0.05665242451161216, "lm_q1q2_score": 0.014381842173375898}}
{"text": "import Do.Basic\nimport Do.LazyList\n\n/-! # Local Mutation -/\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 \"let\" \"mut\" ident \":=\" term \";\" stmt : stmt\nsyntax ident \":=\" term : stmt\nsyntax \"if\" term \"then\" stmt \"else\" stmt:1 : stmt\n\ndeclare_syntax_cat expander\n-- generic syntax for traversal-like functions S_y/R/B/L\nsyntax \"expand!\" expander \"in\" stmt:1 : stmt\nsyntax \"mut\" ident : expander  -- corresponds to `S_y`\n\n-- generic traversal rules\nmacro_rules\n  | `(stmt| expand! $exp in let $x \u2190 $s; $s') => `(stmt| let $x \u2190 expand! $exp in $s; expand! $exp in $s')                -- subsumes (R3, B4, L4)\n  | `(stmt| expand! $exp in let mut $x := $e; $s') => `(stmt| let mut $x := $e; expand! $exp in $s')                      -- subsumes (R4, B5, L5)\n  | `(stmt| expand! $_ in $x:ident := $e) => `(stmt| $x:ident := $e)                                                      -- subsumes (R5, B6, L6)\n  | `(stmt| expand! $exp in if $e then $s\u2081 else $s\u2082) => `(stmt| if $e then expand! $exp in $s\u2081 else expand! $exp in $s\u2082)  -- subsumes (S6, R6, B7, L7)\n  | `(stmt| expand! $exp in $s) => do\n    let s' \u2190 expandStmt s\n    `(stmt| expand! $exp in $s')\n\n\nmacro_rules\n  | `(d! let mut $x := $e; $s) => `(let $x := $e; StateT.run' (d! expand! mut $x in $s) $x) -- (D3)\n  | `(d! $x:ident := $_:term) =>\n      -- `s!\"...\"` is an interpolated string. For more information, see https://leanprover.github.io/lean4/doc/stringinterp.html.\n      throw <| Macro.Exception.error x s!\"variable '{x.getId}' is not reassignable in this scope\"\n  | `(d! if $e then $s\u2081 else $s\u2082) => `(if $e then d! $s\u2081 else d! $s\u2082)                       -- (D4)\n\nmacro_rules\n  | `(stmt| expand! mut $_ in $e:term) => `(stmt| StateT.lift $e)  -- (S1)\n  | `(stmt| expand! mut $y in let $x \u2190 $s; $s') =>                -- (S2)\n    if x == y then\n      throw <| Macro.Exception.error x s!\"cannot shadow 'mut' variable '{x.getId}'\"\n    else\n      `(stmt| let $x \u2190 expand! mut $y in $s; let $y \u2190 get; expand! mut $y in $s')\n  | `(stmt| expand! mut $y in let mut $x := $e; $s') =>           -- (S3)\n    if x == y then\n      throw <| Macro.Exception.error x s!\"cannot shadow 'mut' variable '{x.getId}'\"\n    else\n      `(stmt| let mut $x := $e; expand! mut $y in $s')\n  | `(stmt| expand! mut $y in $x:ident := $e) =>\n    if x == y then\n      `(stmt| set $e)                                             -- (S5)\n    else\n      `(stmt| $x:ident := $e)                                     -- (S4)\n\nmacro:0 \"let\" \"mut\" x:ident \"\u2190\" s:stmt:1 \";\" s':stmt : stmt => `(let y \u2190 $s; let mut $x := y; $s') -- (A3)\nmacro:0 x:ident \"\u2190\" s:stmt:1 : stmt => `(let y \u2190 $s; $x:ident := y)                                -- (A4)\n-- a variant of (A4) since we technically cannot make the above macro a `stmt`\nmacro:0 x:ident \"\u2190\" s:stmt:1 \";\" s':stmt : stmt => `(let y \u2190 $s; $x:ident := y; $s')\nmacro \"if\" e:term \"then\" s\u2081:stmt:1 : stmt => `(if $e then $s\u2081 else pure ())                        -- (A5)\nmacro \"unless\" e:term \"do'\" s\u2082:stmt:1 : stmt => `(if $e then pure () else $s\u2082)                     -- (A6)\n\n/-\nThe `variable` command instructs Lean to insert the declared variables as bound variables\nin definitions that refer to them.\n-/\n\nvariable [Monad m]\nvariable (ma ma' : m \u03b1)\n\n/-\n  Mark `map_eq_pure_bind` as a simplification lemma.\n  It is a theorem for\n  `f <$> x = x >>= pure (f a)`\n-/\nattribute [local simp] map_eq_pure_bind\n\n/-\n  Remark: an `example` in Lean is like a \"nameless\" definition, and it does not update the environment.\n  It is useful for writing tests.\n-/\n\n/-\n  The instance `[LawfulMonad m]` contains the monadic laws.\n  For more information, see https://github.com/leanprover/lean4/blob/v4.0.0-m4/src/Init/Control/Lawful.lean\n-/\n\nexample [LawfulMonad m] :\n    (do' let mut x \u2190 ma;\n         pure x : m \u03b1)\n    =\n    ma\n:= by simp\n\nexample [LawfulMonad m] :\n    (do' let mut x \u2190 ma;\n         x \u2190 ma';\n         pure x)\n    =\n    (ma >>= fun _ => ma')\n:= by simp\n\n/- The command `#check_failure <term>` succeeds only if `<term>` fails to be elaborated. -/\n\n#check_failure do'\n  let mut x \u2190 ma;\n  let x \u2190 ma';  -- cannot shadow 'mut' variable 'x'\n  pure x\n\n#check_failure do'\n  x \u2190 ma;  -- variable 'x' is not reassignable in this scope\n  pure ()\n\nvariable (b : Bool)\n\n-- The following equivalence is true even if `m` does not satisfy the monadic laws.\nexample :\n    (do' if b then {\n           discard ma\n         })\n    =\n    (if b then discard ma else pure ())\n:= rfl\n\ntheorem simple [LawfulMonad m] :\n    (do' let mut x \u2190 ma;\n         if b then {\n           x \u2190 ma'\n         };\n         pure x)\n    =\n    (ma >>= fun x => if b then ma' else pure x)\n:= by cases b <;> simp\n\nexample [LawfulMonad m] (f : \u03b1 \u2192 \u03b1 \u2192 \u03b1) :\n    (do' let mut x \u2190 ma;\n         let y \u2190\n           if b then {\n             x \u2190 ma;\n             ma'\n           } else {\n             ma'\n           };\n         pure (f x y))\n    =\n    (ma >>= fun x => if b then ma >>= fun x => ma' >>= fun y => pure (f x y) else ma' >>= fun y => pure (f x y))\n:= by cases b <;> simp\n\n/-\nNondeterminism example from Section 2.\n-/\ndef choose := @List.toLazy\n\ndef ex : LazyList Nat := do'\n  let mut x := 0;\n  let y \u2190 choose [0, 1, 2, 3];\n  x := x + 1;\n  guard (x < 3);\n  pure (x + y)\n\n-- Generate all solutions\n#eval ex.toList\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/Mut.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.05261895111923625, "lm_q1q2_score": 0.014313646557248554}}
{"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\u2080, y\u2081, y\u2082, y\u2083)\n  (y\u2084, y\u2085, y\u2086, y\u2087)\n  (y\u2088, y\u2089, y\u2081\u2080, y\u2081\u2081)\n  (y\u2081\u2082, y\u2081\u2083, y\u2081\u2084, y\u2081\u2085)\n\n  But we need this to be converted to:\n\n  (y\u2080, y\u2081, y\u2082, y\u2083)\n  (y\u2085, y\u2086, y\u2087, y\u2084)\n  (y\u2081\u2080, y\u2081\u2081, y\u2088, y\u2089)\n  (y\u2081\u2085, y\u2081\u2082, y\u2081\u2083, y\u2081\u2084)  \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\u2080, z\u2081, z\u2082, z\u2083)\n  (z\u2085, z\u2086, z\u2087, z\u2084)\n  (z\u2081\u2080, z\u2081\u2081, z\u2088, z\u2089)\n  (z\u2081\u2085, z\u2081\u2082, z\u2081\u2083, z\u2081\u2084)  \n\n  But we need this to be converted to:\n\n  (z\u2080, z\u2081, z\u2082, z\u2083)\n  (z\u2084, z\u2085, z\u2086, z\u2087)\n  (z\u2088, z\u2089, z\u2081\u2080, z\u2081\u2081)\n  (z\u2081\u2082, z\u2081\u2083, z\u2081\u2084, z\u2081\u2085)\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\u2080, x\u2081, x\u2082, x\u2083)\n  (x\u2084, x\u2085, x\u2086, x\u2087)\n  (x\u2088, x\u2089, x\u2081\u2080, x\u2081\u2081)\n  (x\u2081\u2082, x\u2081\u2083, x\u2081\u2084, x\u2081\u2085)\n\n  But we need this to be converted to:\n\n  (x\u2080, x\u2084, x\u2088, x\u2081\u2082)\n  (x\u2085, x\u2089, x\u2081\u2083, x\u2081)\n  (x\u2081\u2080, x\u2081\u2084, x\u2082, x\u2086)\n  (x\u2081\u2085, x\u2083, x\u2087, x\u2081\u2081)\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\u2080, y\u2084, y\u2088, y\u2081\u2082)\n  (y\u2085, y\u2089, y\u2081\u2083, y\u2081)\n  (y\u2081\u2080, y\u2081\u2084, y\u2082, y\u2086)\n  (y\u2081\u2085, y\u2083, y\u2087, y\u2081\u2081)\n\n  But we need this to be converted to:\n\n  (y\u2080, y\u2081, y\u2082, y\u2083)\n  (y\u2084, y\u2085, y\u2086, y\u2087)\n  (y\u2088, y\u2089, y\u2081\u2080, y\u2081\u2081)\n  (y\u2081\u2082, y\u2081\u2083, y\u2081\u2084, y\u2081\u2085)  \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\u1d62\u2c7c + B\u1d62\u2c7c\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 : \u2203 (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\u2080 a\u2081 a\u2082 a\u2083 a\u2084 a\u2085 a\u2086 a\u2087 a\u2088 a\u2089 a\u2081\u2080 a\u2081\u2081 a\u2081\u2082 a\u2081\u2083 a\u2081\u2084 a\u2081\u2085 : bitvec word_len\n\n/-- Distribute 2 * Matrix. -/\n@[simp] lemma matrix_distribute_two :\n  2 * ((a\u2080, a\u2081, a\u2082, a\u2083), (a\u2084, a\u2085, a\u2086, a\u2087), (a\u2088, a\u2089, a\u2081\u2080, a\u2081\u2081), (a\u2081\u2082, a\u2081\u2083, a\u2081\u2084, a\u2081\u2085)) =\n  (\n    (2 * a\u2080, 2 * a\u2081, 2 * a\u2082, 2 * a\u2083),\n    (2 * a\u2084, 2 * a\u2085, 2 * a\u2086, 2 * a\u2087),\n    (2 * a\u2088, 2 * a\u2089, 2 * a\u2081\u2080, 2 * a\u2081\u2081),\n    (2 * a\u2081\u2082, 2 * a\u2081\u2083, 2 * a\u2081\u2084, 2 * a\u2081\u2085)\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 \u2190 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 \u2192 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) \u2192 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 {\u03b1 \u03b3 : Sort u} {\u03b2 \u03b4 : Sort v} {f\u2081 : \u03b1 \u2192 \u03b2} {f\u2082 : \u03b3 \u2192 \u03b4} {a\u2081 : \u03b1} {a\u2082 : \u03b3} (h\u2081 : f\u2081 == f\u2082) (h\u2082 : a\u2081 == a\u2082) : f\u2081 a\u2081 == f\u2082 a\u2082\n\naxiom heq.dcongr {\u03b1 \u03b2 : Sort u} {\u03b3 \u03b4 : Sort v} {\u03b5 \u03b6 : Sort w} {f\u2081 : \u03a0 \u03b1, \u03b3 \u2192 \u03b5} {f\u2082 : \u03a0 \u03b2, \u03b4 \u2192 \u03b6} {a\u2081\u2081 : \u03b1} {a\u2081\u2082 : \u03b3} {a\u2082\u2081 : \u03b2} {a\u2082\u2082 : \u03b4} (h\u2081 : f\u2081 == f\u2082) (h\u2082 : a\u2081\u2081 == a\u2082\u2081) (h\u2083 : a\u2081\u2082 == a\u2082\u2082) : f\u2081 a\u2081\u2081 a\u2081\u2082 == f\u2082 a\u2082\u2081 a\u2082\u2082\n\n/- The context except the hole consumes \u0393\u2091 resources, while the\n   hole can consume arbitrary resources \u0393. 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 {\u03b3} (\u0393\u2091: context \u03b3) (A' A: tp): Type :=\n  \u03a0 (\u0393: context \u03b3), term \u0393 A' \u2192 term (\u0393 + \u0393\u2091) A\n\nnamespace eval_ctx_fn\n\n@[reducible]\ndef apply {\u03b3} {\u0393\u2091 \u0393': context \u03b3} {A' A: tp}\n  (f: eval_ctx_fn \u0393\u2091 A' A)\n  (\u0393: context \u03b3)\n  (M: term \u0393' A')\n  (h: auto_param (\u0393 = \u0393'+\u0393\u2091) ``solve_context)\n  : term \u0393 A :=\ncast (by solve_context) $ f \u0393' 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  : \u03a0 {\u03b3} {A' A: tp} (\u0393\u2091: context \u03b3), eval_ctx_fn \u0393\u2091 A' A \u2192 Type\n| EHole:\n  \u03a0 (\u03b3: precontext) (A: tp),\n  eval_ctx 0 (\u03bb (\u0393: context \u03b3) (M: term \u0393 A), begin convert M, solve_context end)\n\n| EAppLeft:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B: tp}\n    {C'}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (N: term \u0393\u2082 A)\n  (E: eval_ctx_fn \u0393\u2081 C' $ A\u22b8B),\n  eval_ctx \u0393\u2081 E\n  -------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, App _ (E \u0393 M) N)\n\n| EAppRight:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B: tp}\n    {A'} {V: term \u0393\u2081 $ A\u22b8B}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (hV: value V)\n  (E: eval_ctx_fn \u0393\u2082 A' A),\n  eval_ctx \u0393\u2082 E\n  -------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, App _ V $ E \u0393 M)\n\n| ELetUnit:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A: tp}\n    {A'}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (N: term \u0393\u2082 A)\n  (E: eval_ctx_fn \u0393\u2081 A' tp.unit),\n  eval_ctx \u0393\u2081 E\n  ---------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, LetUnit _ (E \u0393 M) N)\n\n| EPairLeft:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B: tp}\n    {A'}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (N: term \u0393\u2082 B)\n  (E: eval_ctx_fn \u0393\u2081 A' A),\n  eval_ctx \u0393\u2081 E\n  ------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Pair _ (E \u0393 M) N)\n\n| EPairRight:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B: tp}\n    {B'} {V: term \u0393\u2081 A}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (hV: value V)\n  (E: eval_ctx_fn \u0393\u2082 B' B),\n  eval_ctx \u0393\u2082 E\n  ------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Pair _ V $ E \u0393 M)\n\n| ELetPair:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B C: tp}\n    {C'}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (N: term (\u27e61\u2b1dA\u27e7::\u27e61\u2b1dB\u27e7::\u0393\u2082) C)\n  (E: eval_ctx_fn \u0393\u2081 C' $ tp.prod A B),\n  eval_ctx \u0393\u2081 E\n  ----------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, LetPair _ (E \u0393 M) N)\n\n| EInl:\n  \u03a0 {\u03b3} {\u0393\u2091: context \u03b3} {A: tp}\n    {A'}\n  (B: tp)\n  (E: eval_ctx_fn \u0393\u2091 A' A),\n  eval_ctx \u0393\u2091 E\n  -----------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Inl B $ E \u0393 M)\n\n| EInr:\n  \u03a0 {\u03b3} {\u0393\u2091: context \u03b3} {B: tp}\n    {B'}\n  (A: tp)\n  (E: eval_ctx_fn \u0393\u2091 B' B),\n  eval_ctx \u0393\u2091 E\n  ---------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Inr A $ E \u0393 M)\n\n| ECase:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B C: tp}\n    {D'}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (M: term (\u27e61\u2b1dA\u27e7::\u0393\u2082) C)\n  (N: term (\u27e61\u2b1dB\u27e7::\u0393\u2082) C)\n  (E: eval_ctx_fn \u0393\u2081 D' $ tp.sum A B),\n  eval_ctx \u0393\u2081 E\n  --------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 L, Case _ (E \u0393 L) M N)\n\n| EFork:\n  \u03a0 {\u03b3} {\u0393\u2091: context \u03b3} {S: sesh_tp}\n    {T'}\n  (E: eval_ctx_fn \u0393\u2091 T' $ S\u22b8End!),\n  eval_ctx \u0393\u2091 E\n  --------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 x, Fork (E \u0393 x))\n\n| ESendLeft:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A: tp} {S: sesh_tp}\n    {A'}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (N: term \u0393\u2082 $ !A\u2b1dS)\n  (E: eval_ctx_fn \u0393\u2081 A' A),\n  eval_ctx \u0393\u2081 E\n  ------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Send _ (E \u0393 M) N)\n\n| ESendRight:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A: tp} {S: sesh_tp}\n    {T'} {V: term \u0393\u2081 A}\n  (\u0393\u2091: context \u03b3)\n  (h\u0393: \u0393\u2091 = \u0393\u2081 + \u0393\u2082)\n  (hV: value V)\n  (E: eval_ctx_fn \u0393\u2082 T' $ !A\u2b1dS),\n  eval_ctx \u0393\u2082 E\n  ------------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Send _ V $ E \u0393 M)\n\n| ERecv:\n  \u03a0 {\u03b3} {\u0393\u2091: context \u03b3} {A: tp} {S: sesh_tp}\n    {T'}\n  (E: eval_ctx_fn \u0393\u2091 T' ?A\u2b1dS),\n  eval_ctx \u0393\u2091 E\n  --------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Recv $ E \u0393 M)\n\n| EWait:\n  \u03a0 {\u03b3} {\u0393\u2091: context \u03b3}\n    {T'}\n  (E: eval_ctx_fn \u0393\u2091 T' End?),\n  eval_ctx \u0393\u2091 E\n  --------------------------\n\u2192 eval_ctx \u0393\u2091 (\u03bb \u0393 M, Wait $ E \u0393 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 \u03c1 \u0393) and returns the same expression,\n   but well-typed under the extended environment. -/\ndef ext:\n    \u03a0 {\u03b3 \u03b4: precontext}  {A' A: tp}{\u0393: context \u03b3}\n      {E: eval_ctx_fn \u0393 A' A}\n    (\u03c1: ren_fn \u03b3 \u03b4),\n    eval_ctx \u0393 E\n    -----------------------------------------------\n  \u2192 \u03a3 E': eval_ctx_fn (\u0393 \u229b (\u03bb B x, identity \u03b4 B $ \u03c1 B x)) A' A,\n      eval_ctx (\u0393 \u229b (\u03bb B x, identity \u03b4 B $ \u03c1 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 \u27e8_, EHole _ _\u27e9\nend\n| _ _ _ _ _ _ \u03c1 (EAppLeft _ h\u0393 N _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EAppLeft\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (rename \u03c1 _ N)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EAppRight _ h\u0393 hV _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EAppRight\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (hV.rename \u03c1)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (ELetUnit _ h\u0393 N _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, ELetUnit\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (rename \u03c1 _ N)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EPairLeft _ h\u0393 N _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EPairLeft\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (rename \u03c1 _ N)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EPairRight _ h\u0393 hV _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EPairRight\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (hV.rename \u03c1)\n    E'.fst\n    E'.snd\u27e9\n| \u03b3 _ _ _ _ _ \u03c1 (ELetPair _ h\u0393 N _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, ELetPair\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (rename ((\u03c1.ext _).ext _) _ N)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EInl C _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EInl\n    C\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EInr C _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EInr\n    C\n    E'.fst\n    E'.snd\u27e9\n| \u03b3 _ _ _ _ _ \u03c1 (ECase _ h\u0393 M N _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, ECase\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (rename (\u03c1.ext _) _ M)\n    (rename (\u03c1.ext _) _ N)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EFork _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EFork\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (ESendLeft _ h\u0393 N _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, ESendLeft\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (rename \u03c1 _ N)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (ESendRight _ h\u0393 hV _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, ESendRight\n    _\n    (begin rw [h\u0393, vmul_right_distrib] end)\n    (hV.rename \u03c1)\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (ERecv _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, ERecv\n    E'.fst\n    E'.snd\u27e9\n| _ _ _ _ _ _ \u03c1 (EWait _ E) :=\n  let E' := ext \u03c1 E in\n  \u27e8_, EWait\n    E'.fst\n    E'.snd\u27e9\n\ndef wrap: \u03a0 {\u03b3} {A'' A' A: tp} {\u0393\u2091 \u0393\u2091': context \u03b3}\n  (E: eval_ctx_fn \u0393\u2091 A'' A')\n  (hE: eval_ctx \u0393\u2091 E)\n  (E': eval_ctx_fn \u0393\u2091' A' A)\n  (hE': eval_ctx \u0393\u2091' E')\n  (\u0393: context \u03b3)\n  (h\u0393: \u0393 = \u0393\u2091+\u0393\u2091'),\n  \u03a3 E': eval_ctx_fn \u0393 A'' A,\n      eval_ctx \u0393 E'\n| _ _ _ _ _ _ E hE _ (EHole _ _) \u0393 h\u0393 :=\n  cast (begin congr; simp [*, h\u0393], congr' 1, simp [h\u0393] end)\n    (sigma.mk E hE)\n| _ _ _ _ _ _ E hE _ (EAppLeft _ _ N E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EAppLeft \u0393 (by solve_context) N EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EAppRight _ _ hV E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EAppRight \u0393 (by solve_context) hV EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (ELetUnit _ _ N E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, ELetUnit \u0393 (by solve_context) N EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EPairLeft _ _ N E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EPairLeft \u0393 (by solve_context) N EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EPairRight _ _ hV E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EPairRight \u0393 (by solve_context) hV EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (ELetPair _ _ N E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, ELetPair \u0393 (by solve_context) N EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EInl B E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EInl B (cast (by rw [h\u0393]) EE'.fst) $ cast (begin\n    congr' 1, exact h\u0393.symm,\n    h_generalize Hx: EE'.fst == x, exact Hx,\n  end) EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EInr A E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EInr A (cast (by rw [h\u0393]) EE'.fst) $ cast (begin\n    congr' 1, exact h\u0393.symm,\n    h_generalize Hx: EE'.fst == x, exact Hx,\n  end) EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (ECase _ _ M N E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, ECase \u0393 (by solve_context) M N EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EFork E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EFork (cast (by rw [h\u0393]) EE'.fst) $ cast (begin\n    congr' 1, exact h\u0393.symm,\n    h_generalize Hx: EE'.fst == x, exact Hx,\n  end) EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (ESendLeft _ _ M E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, ESendLeft \u0393 (by solve_context) M EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (ESendRight _ _ hV E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, ESendRight \u0393 (by solve_context) hV EE'.fst EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (ERecv E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, ERecv (cast (by rw [h\u0393]) EE'.fst) $ cast (begin\n    congr' 1, exact h\u0393.symm,\n    h_generalize Hx: EE'.fst == x, exact Hx,\n  end) EE'.snd\u27e9\n| _ _ _ _ _ _ E hE _ (EWait E' hE') \u0393 h\u0393 :=\n  let EE' := wrap E hE E' hE' _ rfl in\n  \u27e8_, EWait (cast (by rw [h\u0393]) EE'.fst) $ cast (begin\n    congr' 1, exact h\u0393.symm,\n    h_generalize Hx: EE'.fst == x, exact Hx,\n  end) EE'.snd\u27e9\n\nset_option pp.implicit true\n\nlemma wrap_composes {\u03b3} {\u0393 \u0393\u2091 \u0393\u2091': context \u03b3} {A'' A' A: tp}\n    {M: term \u0393 A''}\n    {E': eval_ctx_fn \u0393\u2091 A'' A'}\n    {hE': eval_ctx \u0393\u2091 E'}\n    {E: eval_ctx_fn \u0393\u2091' A' A}\n    {hE: eval_ctx \u0393\u2091' E}\n  (\u0393': context \u03b3)\n  (h\u0393': \u0393' = \u0393+\u0393\u2091)\n  (EM: term \u0393' A')\n  (\u0393'': context \u03b3)\n  (h\u0393'': \u0393'' = \u0393'+\u0393\u2091')\n  (EM': term \u0393'' A)\n  (hEM: EM = E'.apply \u0393' M)\n  (hEM': EM' = E.apply \u0393'' EM)\n  : EM' = (wrap E' hE' E hE _ rfl).fst.apply \u0393'' M :=\nbegin\n  induction hE; simp [*, wrap, eval_ctx_fn.apply],\n  case EHole {\n    h_generalize Hx: (E' \u0393 M) == x,\n    h_generalize Hy: x == y,\n    h_generalize Hx': (\u27e8E', hE'\u27e9: \u03a3 E': eval_ctx_fn \u0393\u2091 A'' hE_A, eval_ctx \u0393\u2091 E') == x',\n    congr' 1, simp [h\u0393'],\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' {\u03b3} (\u0393\u2091: context \u03b3) (A' A: tp) :=\n(f: eval_ctx_fn \u0393\u2091 A' A)\n(h: eval_ctx \u0393\u2091 f)\n\nnamespace eval_ctx'\n\ndef ext {\u03b3 \u03b4: precontext} {\u0393: context \u03b3} {A' A: tp} (\u03c1: ren_fn \u03b3 \u03b4) (E: eval_ctx' \u0393 A' A)\n  : eval_ctx' (\u0393 \u229b (\u03bb B x, identity \u03b4 B $ \u03c1 B x)) A' A :=\n  let E' := eval_ctx.ext \u03c1 E.h in\n  \u27e8E'.fst, E'.snd\u27e9\n\ndef wrap {\u03b3} {\u0393\u2091 \u0393\u2091': context \u03b3} {A'' A' A: tp}\n  (E: eval_ctx' \u0393\u2091 A'' A')\n  (E': eval_ctx' \u0393\u2091' A' A)\n  (\u0393: context \u03b3)\n  (h\u0393: \u0393 = \u0393\u2091+\u0393\u2091')\n  : eval_ctx' \u0393 A'' A :=\nlet EE' := eval_ctx.wrap E.f E.h E'.f E'.h \u0393 h\u0393 in\n\u27e8EE'.fst, EE'.snd\u27e9\n\nlemma wrap_composes {\u03b3} {\u0393 \u0393\u2091 \u0393\u2091': context \u03b3} {A'' A' A: tp}\n    {M: term \u0393 A''}\n    {E': eval_ctx' \u0393\u2091 A'' A'}\n    {E: eval_ctx' \u0393\u2091' A' A}\n  (\u0393': context \u03b3)\n  (h\u0393': \u0393' = \u0393+\u0393\u2091)\n  (EM: term \u0393' A')\n  (\u0393'': context \u03b3)\n  (h\u0393'': \u0393'' = \u0393'+\u0393\u2091')\n  (EM': term \u0393'' A)\n  (hE: EM = E'.f.apply \u0393' M)\n  (hE': EM' = E.f.apply \u0393'' EM)\n  : EM' = (E'.wrap E _ rfl).f.apply \u0393'' M :=\nsorry\n\nend eval_ctx'\n\ninductive term_reduces\n  : \u2200 {\u03b3} {\u0393: context \u03b3} {A: tp}, term \u0393 A \u2192 term \u0393 A \u2192 Prop\ninfix ` \u27f6M `:55 := term_reduces\n| EvalLift:\n  \u2200 {\u03b3} {\u0393 \u0393\u2091: context \u03b3} {A A': tp}\n    {M M': term \u0393 A}\n  (\u0393': context \u03b3)\n  (E: eval_ctx' \u0393\u2091 A A')\n  (EM EM': term \u0393' A')\n  (h\u0393': \u0393' = \u0393+\u0393\u2091)\n  (hStep: M \u27f6M M')\n  (hEM: EM = E.f.apply \u0393' M)\n  (hEM': EM' = E.f.apply \u0393' M'),\n  -----------------------\n  EM \u27f6M EM'\n\n| EvalLam:\n  \u2200 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B: tp}\n    {V: term \u0393\u2082 A}\n  (\u0393: context \u03b3)\n  (M: term (\u27e61\u2b1dA\u27e7::\u0393\u2081) B)\n  (hV: value V)\n  (_: auto_param (\u0393 = \u0393\u2081 + \u0393\u2082) ``solve_context),\n  ----------------------------------------------\n  (App \u0393 (Abs M) V) \u27f6M ssubst _ M V\n\n| EvalUnit:\n  \u2200 {\u03b3} {\u0393: context \u03b3} {A: tp}\n  (M: term \u0393 A),\n  ---------------------------------------\n  (LetUnit \u0393 (Unit 0) M $ by simp) \u27f6M M\n\n| EvalPair:\n  \u2200 {\u03b3} {\u0393\u2081\u2081 \u0393\u2081\u2082 \u0393\u2082: context \u03b3} {A B C: tp}\n    {V: term \u0393\u2081\u2081 A} {W: term \u0393\u2081\u2082 B}\n  (\u0393\u2081 \u0393: context \u03b3)\n  (hV: value V)\n  (hW: value W)\n  (M: term (\u27e61\u2b1dA\u27e7::\u27e61\u2b1dB\u27e7::\u0393\u2082) C)\n  (_: auto_param (\u0393 = \u0393\u2081 + \u0393\u2082) ``solve_context)\n  (_: auto_param (\u0393\u2081 = \u0393\u2081\u2081 + \u0393\u2081\u2082) ``solve_context),\n  -----------------------------------------------------------\n  (LetPair \u0393 (Pair \u0393\u2081 V W $ by assumption) M $ by assumption)\n  \u27f6M\n  dsubst _ M V W\n\n| EvalInl:\n  \u2200 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B C: tp}\n    {V: term \u0393\u2081 A}\n  (\u0393: context \u03b3)\n  (hV: value V)\n  (M: term (\u27e61\u2b1dA\u27e7::\u0393\u2082) C)\n  (N: term (\u27e61\u2b1dB\u27e7::\u0393\u2082) C)\n  (_: auto_param (\u0393 = \u0393\u2081 + \u0393\u2082) ``solve_context),\n  ----------------------------------------------\n  (Case \u0393 (Inl B V) M N) \u27f6M ssubst _ M V\n\n| EvalInr:\n  \u2200 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {A B C: tp}\n    {V: term \u0393\u2081 B}\n  (\u0393: context \u03b3)\n  (hV: value V)\n  (M: term (\u27e61\u2b1dA\u27e7::\u0393\u2082) C)\n  (N: term (\u27e61\u2b1dB\u27e7::\u0393\u2082) C)\n  (_: auto_param (\u0393 = \u0393\u2081 + \u0393\u2082) ``solve_context),\n  ----------------------------------------------\n  (Case \u0393 (Inr A V) M N) \u27f6M ssubst _ N V\n\ninfix ` \u27f6M `: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 {\u03b1 : Type u} (encode : \u03b1 \u2192 put_m) (decode : get_m \u03b1) : Prop :=\n\u2200 w, decode -<< encode w = pure w\n\nclass serial (\u03b1 : Type u) :=\n  (encode : \u03b1 \u2192 put_m.{u})\n  (decode : get_m \u03b1)\n  (correctness : \u2200 w, decode -<< encode w = pure w)\n\nclass serial1 (f : Type u \u2192 Type v) :=\n  (encode : \u03a0 {\u03b1} [serial \u03b1], f \u03b1 \u2192 put_m.{v})\n  (decode : \u03a0 {\u03b1} [serial \u03b1], get_m (f \u03b1))\n  (correctness : \u2200 {\u03b1} [serial \u03b1] (w : f \u03b1), decode -<< encode w = pure w)\n\ninstance serial.serial1 {f \u03b1} [serial1 f] [serial \u03b1] : serial (f \u03b1) :=\n{ encode := \u03bb x, serial1.encode x,\n  decode := serial1.decode f,\n  correctness := serial1.correctness }\n\nclass serial2 (f : Type u \u2192 Type v \u2192 Type w) :=\n  (encode : \u03a0 {\u03b1 \u03b2} [serial \u03b1] [serial \u03b2], f \u03b1 \u03b2 \u2192 put_m.{w})\n  (decode : \u03a0 {\u03b1 \u03b2} [serial \u03b1] [serial \u03b2], get_m (f \u03b1 \u03b2))\n  (correctness : \u2200 {\u03b1 \u03b2} [serial \u03b1] [serial \u03b2] (w : f \u03b1 \u03b2), decode -<< encode w = pure w)\n\ninstance serial.serial2 {f \u03b1 \u03b2} [serial2 f] [serial \u03b1] [serial \u03b2] : serial (f \u03b1 \u03b2) :=\n{ encode := \u03bb x, serial2.encode x,\n  decode := serial2.decode f,\n  correctness := serial2.correctness }\n\ninstance serial1.serial2 {f \u03b1} [serial2 f] [serial \u03b1] : serial1 (f \u03b1) :=\n{ encode := \u03bb \u03b2 inst x, @serial2.encode _ _ \u03b1 \u03b2 _ inst x,\n  decode := \u03bb \u03b2 inst, @serial2.decode f _ \u03b1 \u03b2 _ inst,\n  correctness := \u03bb \u03b2 inst, @serial2.correctness _ _ \u03b1 \u03b2 _ inst }\n\nexport serial (encode decode)\n\nnamespace serial\n\nopen function\n\nvariables {\u03b1 \u03b2 \u03c3 \u03b3 : Type u} {\u03c9 : Type}\n\ndef serialize [serial \u03b1] (x : \u03b1) : list unsigned := (encode x).eval\ndef deserialize (\u03b1 : Type u) [serial \u03b1] (bytes : list unsigned) : option \u03b1 := (decode \u03b1).eval bytes\n\nlemma encode_decode_bind [serial \u03b1]\n  (f : \u03b1 \u2192 get_m \u03b2) (f' : punit \u2192 put_m) (w : \u03b1) :\n  (decode \u03b1 >>= f) -<< (encode w >>= f') = f w -<< f' punit.star :=\nby { rw [read_write_mono]; rw serial.correctness; refl }\n\nlemma encode_decode_bind' [serial \u03b1]\n  (f : \u03b1 \u2192 get_m \u03b2) (w : \u03b1) :\n  (decode \u03b1 >>= 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' : \u03b1) (u : punit) :\n  (pure w) -<< (pure u) = pure w' \u2194 w = w' :=\nby split; intro h; cases h; refl\n\nopen ulift\n\nprotected def ulift.encode [serial \u03b1] (w : ulift.{v} \u03b1) : put_m :=\nliftable1.up equiv.punit_equiv_punit (encode (down w))\n\nprotected def ulift.decode [serial \u03b1] : get_m (ulift \u03b1) :=\nget_m.up ulift.up (decode \u03b1)\n\ninstance [serial \u03b1] : serial (ulift.{v u} \u03b1) :=\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 := \u03bb 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 {\u03b1 \u03b2 \u03b3 : Type u}\n  (w : unsigned) (x : \u03b1) (f : \u03b1 \u2192 unsigned \u2192 get_m (\u03b2 \u2295 \u03b1)) (g : \u03b2 \u2192 get_m \u03b3)\n  (rest : punit \u2192 put_m) :\n  get_m.loop f g x -<< (write_word w >>= rest) =\n  (f x w >>= @sum.rec _ _ (\u03bb _, get_m \u03b3) g (get_m.loop f g)) -<< rest punit.star := rfl\n\n@[simp] lemma loop_read_write_word' {\u03b1 \u03b2 \u03b3 : Type u}\n  (w : unsigned) (x : \u03b1) (f : \u03b1 \u2192 unsigned \u2192 get_m (\u03b2 \u2295 \u03b1)) (g : \u03b2 \u2192 get_m \u03b3)  :\n  get_m.loop f g x -<< (write_word w) =\n  (f x w >>= @sum.rec _ _ (\u03bb _, get_m \u03b3) 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 \u00d7 get_m \u03b1) \u2192 get_m \u03b1\n| [] := get_m.fail\n| ((w,x) :: xs) := if w = tag then x else select_tag' xs\n\ndef select_tag (xs : list (unsigned \u00d7 get_m \u03b1)) : get_m \u03b1 :=\ndo w \u2190 read_word,\n   select_tag' (down w) xs\n\n@[simp]\nlemma read_write_tag_hit {w w' : unsigned} {x : get_m \u03b1}\n  {xs : list (unsigned \u00d7 get_m \u03b1)} {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 \u03b1}\n  {xs : list (unsigned \u00d7 get_m \u03b1)}\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 \u03b1}\n  {xs : list (unsigned \u00d7 get_m \u03b1)} {y : put_m}\n  (h : w \u2260 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 {\u03b1} : \u2115 \u2192 (get_m \u03b1 \u2192 get_m \u03b1) \u2192 get_m \u03b1\n| 0 _ := get_m.fail\n| (nat.succ n) rec_fn := rec_fn $ recursive_parser n rec_fn\n\nlemma recursive_parser_unfold {\u03b1} (n : \u2115) (f : get_m \u03b1 \u2192 get_m \u03b1) (h : 1 \u2264 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 (\u03b1 : Type u) (\u03b2 : Type u) :=\n(encoder : \u03b1 \u2192 put_m.{u})\n(decoder : get_m \u03b2)\n\nnamespace serializer\n\ndef valid_serializer {\u03b1} (x : serializer \u03b1 \u03b1) :=\nserial_inverse\n      (serializer.encoder x)\n      (serializer.decoder x)\n\nlemma serializer.eq {\u03b1 \u03b2} (x y : serializer \u03b1 \u03b2)\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 {\u03b1 : Type u} {i j : Type u}\nvariables (x : serializer \u03b1 (i \u2192 j))\nvariables (y : serializer \u03b1 i)\n\ndef encoder := \u03bb (k : \u03b1), x.encoder k >> y.encoder k\ndef decoder := x.decoder <*> y.decoder\n\nend serializer.seq\n\ninstance {\u03b1 : Type u} : applicative (serializer.{u} \u03b1) :=\n{ pure := \u03bb i x, { encoder := \u03bb _, return punit.star, decoder := pure x }\n, seq := \u03bb i j x y,\n  { encoder := serializer.seq.encoder x y\n  , decoder := serializer.seq.decoder x y } }\n\nsection lawful_applicative\n\nvariables {\u03b1 \u03b2 : Type u} {\u03c3 : Type u}\n\n@[simp]\nlemma decoder_pure (x : \u03b2) :\n  (pure x : serializer \u03c3 \u03b2).decoder = pure x := rfl\n\n@[simp]\nlemma decoder_map (f : \u03b1 \u2192 \u03b2) (x : serializer \u03c3 \u03b1) :\n  (f <$> x).decoder = f <$> x.decoder := rfl\n\n@[simp]\nlemma decoder_seq (f : serializer \u03c3 (\u03b1 \u2192 \u03b2)) (x : serializer \u03c3 \u03b1) :\n  (f <*> x).decoder = f.decoder <*> x.decoder := rfl\n\n@[simp]\nlemma encoder_pure (x : \u03b2) (w : \u03c3) :\n  (pure x : serializer \u03c3 \u03b2).encoder w = pure punit.star := rfl\n\n@[simp]\nlemma encoder_map (f : \u03b1 \u2192 \u03b2) (w : \u03c3) (x : serializer \u03c3 \u03b1) :\n  (f <$> x : serializer \u03c3 \u03b2).encoder w = x.encoder w := rfl\n\n@[simp]\nlemma encoder_seq (f : serializer \u03c3 (\u03b1 \u2192 \u03b2)) (x : serializer \u03c3 \u03b1) (w : \u03c3) :\n  (f <*> x : serializer \u03c3 \u03b2).encoder w = f.encoder w >> x.encoder w := rfl\n\nend lawful_applicative\n\ninstance {\u03b1} : is_lawful_functor (serializer.{u} \u03b1) :=\nby refine { .. }; intros; apply serializer.eq; try { ext }; simp [map_map]\n\ninstance {\u03b1} : is_lawful_applicative (serializer.{u} \u03b1) :=\nby{  constructor; intros; apply serializer.eq; try { ext };\n     simp [(>>),pure_seq_eq_map,seq_assoc,bind_assoc],  }\n\ndef ser_field {\u03b1 \u03b2} [serial \u03b2] (f : \u03b1 \u2192 \u03b2) : serializer \u03b1 \u03b2 :=\n{ encoder := \u03bb x, encode (f x)\n, decoder := @decode _ _ }\n\nvariables {\u03b1 \u03b2 \u03c3 \u03b3 : Type u} {\u03c9 : Type}\n\ndef there_and_back_again\n  (y : serializer \u03b3 \u03b1) (w : \u03b3) : option \u03b1 :=\ny.decoder -<< y.encoder w\n\nlemma there_and_back_again_seq [serial \u03b1]\n  (x : serializer \u03b3 (\u03b1 \u2192 \u03b2)) (f : \u03b1 \u2192 \u03b2) (y : \u03b3 \u2192 \u03b1) (w : \u03b3) (w' : \u03b2)\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 \u03b1]\n  (f : \u03b1 \u2192 \u03b2) (y : \u03b3 \u2192 \u03b1) (w : \u03b3) :\n  there_and_back_again (f <$> ser_field y) w = pure (f $ y w) :=\nby rw [\u2190 pure_seq_eq_map,there_and_back_again_seq]; refl\n\n@[simp]\nlemma there_and_back_again_pure (x : \u03b2) (w : \u03b3) :\n  there_and_back_again (pure x) w =\n  pure x := rfl\n\nlemma valid_serializer_of_there_and_back_again\n      {\u03b1 : Type*} (y : serializer \u03b1 \u03b1) :\n  valid_serializer y \u2194\n  \u2200 (w : \u03b1), 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' {\u03b1 \u03b2} [serial \u03b2] (f : \u03b1 \u2192 \u03b2) : serializer.{max u v} \u03b1 (ulift.{v} \u03b2) :=\nser_field (up \u2218 f)\n\ndef of_serializer {\u03b1} (s : serializer \u03b1 \u03b1) (h : \u2200 w, there_and_back_again s w = pure w) : serial \u03b1 :=\n{ encode := s.encoder\n, decode := s.decoder\n, correctness := @h }\n\ndef of_serializer\u2081 {f : Type u \u2192 Type v}\n  (s : \u03a0 \u03b1 [serial \u03b1], serializer (f \u03b1) (f \u03b1))\n  (h : \u2200 \u03b1 [serial \u03b1] w, there_and_back_again (s \u03b1) w = pure w) : serial1 f :=\n{ encode := \u03bb \u03b1 inst, (@s \u03b1 inst).encoder\n, decode := \u03bb \u03b1 inst, (@s \u03b1 inst).decoder\n, correctness := @h }\n\ndef of_serializer\u2082 {f : Type u \u2192 Type v \u2192 Type w}\n  (s : \u03a0 \u03b1 \u03b2 [serial \u03b1] [serial \u03b2], serializer (f \u03b1 \u03b2) (f \u03b1 \u03b2))\n  (h : \u2200 \u03b1 \u03b2 [serial \u03b1] [serial \u03b2] w, there_and_back_again (s \u03b1 \u03b2) w = pure w) : serial2 f :=\n{ encode := \u03bb \u03b1 \u03b2 inst inst', (@s \u03b1 \u03b2 inst inst').encoder\n, decode := \u03bb \u03b1 \u03b2 inst inst', (@s \u03b1 \u03b2 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 : \u2200n m : \u2115, n < m \u2192 \u2203i j, m = n + i \u2228 m + j = n) : true :=\nbegin\n  choose i j h using h,\n  guard_hyp i : \u2200n m : \u2115, n < m \u2192 \u2115,\n  guard_hyp j : \u2200n m : \u2115, n < m \u2192 \u2115,\n  guard_hyp h : \u2200 (n m : \u2115) (h : n < m), m = n + i n m h \u2228 m + j n m h = n,\n  trivial\nend\n\nexample (h : \u2200n m : \u2115, n < m \u2192 \u2203i j, m = n + i \u2228 m + j = n) : true :=\nbegin\n  choose! i j h using h,\n  guard_hyp i : \u2115 \u2192 \u2115 \u2192 \u2115,\n  guard_hyp j : \u2115 \u2192 \u2115 \u2192 \u2115,\n  guard_hyp h : \u2200 (n m : \u2115), n < m \u2192 m = n + i n m \u2228 m + j n m = n,\n  trivial\nend\n\nexample (h : \u2200n m : \u2115, \u2203i, \u2200n:\u2115, \u2203j, m = n + i \u2228 m + j = n) : true :=\nbegin\n  choose i j h using h,\n  guard_hyp i : \u2115 \u2192 \u2115 \u2192 \u2115,\n  guard_hyp j : \u2115 \u2192 \u2115 \u2192 \u2115 \u2192 \u2115,\n  guard_hyp h : \u2200 (n m k : \u2115), m = k + i n m \u2228 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 : \u2200 n, \u2203 k \u2265 0, n = k) : \u2200 x : \u2115, 1 = 1 :=\nbegin\n  choose u hu using h,\n  guard_hyp hu : \u2200 n, u n \u2265 0 \u2227 n = u n,\n  intro, refl\nend\n\n-- test choose with conjunction\nexample (h : \u2200 i : \u2115, \u2203 j, i < j \u2227 j < i+i) : true :=\nbegin\n  choose f h h' using h,\n  guard_hyp f : \u2115 \u2192 \u2115,\n  guard_hyp h : \u2200 (i : \u2115), i < f i,\n  guard_hyp h' : \u2200 (i : \u2115), f i < i + i,\n  trivial,\nend\n\n-- test choose with nonempty instances\nuniverse u\nexample {\u03b1 : Type u} (p : \u03b1 \u2192 Prop) (h : \u2200 i : \u03b1, p i \u2192 \u2203 j : \u03b1 \u00d7 \u03b1, p j.1) : true :=\nbegin\n  choose! f h using h,\n  guard_hyp f : \u03b1 \u2192 \u03b1 \u00d7 \u03b1,\n  guard_hyp h : \u2200 (i : \u03b1), p i \u2192 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 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.Check\nimport Lean.Meta.Match.MatcherInfo\nimport Lean.Meta.Match.CaseArraySizes\n\nnamespace Lean.Meta.Match\n\n/--\n  Auxiliary annotation used to mark terms marked with the \"inaccessible\" annotation `.(t)` and\n  `_` in patterns. -/\ndef mkInaccessible (e : Expr) : Expr :=\n  mkAnnotation `_inaccessible e\n\ndef inaccessible? (e : Expr) : Option Expr :=\n  annotation? `_inaccessible e\n\ninductive Pattern : Type where\n  | inaccessible (e : Expr) : Pattern\n  | var          (fvarId : FVarId) : Pattern\n  | ctor         (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern\n  | val          (e : Expr) : Pattern\n  | arrayLit     (type : Expr) (xs : List Pattern) : Pattern\n  | as           (varId : FVarId) (p : Pattern) : Pattern\n  deriving Inhabited\n\nnamespace Pattern\n\npartial def toMessageData : Pattern \u2192 MessageData\n  | inaccessible e         => m!\".({e})\"\n  | var varId              => mkFVar varId\n  | ctor ctorName _ _ []   => ctorName\n  | ctor ctorName _ _ pats => m!\"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ \" \" ++ toMessageData pat) Format.nil})\"\n  | val e                  => e\n  | arrayLit _ pats        => m!\"#[{MessageData.joinSep (pats.map toMessageData) \", \"}]\"\n  | as varId p             => m!\"{mkFVar varId}@{toMessageData p}\"\n\npartial def toExpr (p : Pattern) (annotate := false) : MetaM Expr :=\n  visit p\nwhere\n  visit (p : Pattern) := do\n    match p with\n    | inaccessible e                 =>\n      if annotate then\n        pure (mkInaccessible e)\n      else\n        pure e\n    | var fvarId                     => pure $ mkFVar fvarId\n    | val e                          => pure e\n    | as fvarId p                    =>\n      if annotate then\n        mkAppM `namedPattern #[mkFVar fvarId, (\u2190 visit p)]\n      else\n        visit p\n    | arrayLit type xs               =>\n      let xs \u2190 xs.mapM visit\n      mkArrayLit type xs\n    | ctor ctorName us params fields =>\n      let fields \u2190 fields.mapM visit\n      pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray\n\n/- Apply the free variable substitution `s` to the given pattern -/\npartial def applyFVarSubst (s : FVarSubst) : Pattern \u2192 Pattern\n  | inaccessible e  => inaccessible $ s.apply e\n  | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s)\n  | val e           => val $ s.apply e\n  | arrayLit t xs   => arrayLit (s.apply t) $ xs.map (applyFVarSubst s)\n  | var fvarId      => match s.find? fvarId with\n    | some e => inaccessible e\n    | none   => var fvarId\n  | as fvarId p     => match s.find? fvarId with\n    | none   => as fvarId $ applyFVarSubst s p\n    | some _ => applyFVarSubst s p\n\ndef replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern :=\n  let s : FVarSubst := {}\n  p.applyFVarSubst (s.insert fvarId v)\n\npartial def hasExprMVar : Pattern \u2192 Bool\n  | inaccessible e => e.hasExprMVar\n  | ctor _ _ ps fs => ps.any (\u00b7.hasExprMVar) || fs.any hasExprMVar\n  | val e          => e.hasExprMVar\n  | as _ p         => hasExprMVar p\n  | arrayLit t xs  => t.hasExprMVar || xs.any hasExprMVar\n  | _              => false\n\nend Pattern\n\npartial def instantiatePatternMVars : Pattern \u2192 MetaM Pattern\n  | Pattern.inaccessible e      => return Pattern.inaccessible (\u2190 instantiateMVars e)\n  | Pattern.val e               => return Pattern.val (\u2190 instantiateMVars e)\n  | Pattern.ctor n us ps fields => return Pattern.ctor n us (\u2190 ps.mapM instantiateMVars) (\u2190 fields.mapM instantiatePatternMVars)\n  | Pattern.as x p              => return Pattern.as x (\u2190 instantiatePatternMVars p)\n  | Pattern.arrayLit t xs       => return Pattern.arrayLit (\u2190 instantiateMVars t) (\u2190 xs.mapM instantiatePatternMVars)\n  | p                   => return p\n\nstructure AltLHS where\n  ref        : Syntax\n  fvarDecls  : List LocalDecl -- Free variables used in the patterns.\n  patterns   : List Pattern   -- We use `List Pattern` since we have nary match-expressions.\n\ndef instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS :=\n  return { altLHS with\n    fvarDecls := (\u2190 altLHS.fvarDecls.mapM instantiateLocalDeclMVars),\n    patterns  := (\u2190 altLHS.patterns.mapM instantiatePatternMVars)\n  }\n\nstructure Alt where\n  ref       : Syntax\n  idx       : Nat -- for generating error messages\n  rhs       : Expr\n  fvarDecls : List LocalDecl\n  patterns  : List Pattern\n  deriving Inhabited\n\nnamespace Alt\n\npartial def toMessageData (alt : Alt) : MetaM MessageData := do\n  withExistingLocalDecls alt.fvarDecls do\n    let msg : List MessageData := alt.fvarDecls.map fun d => m!\"{d.toExpr}:({d.type})\"\n    let msg : MessageData := m!\"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}\"\n    addMessageContext msg\n\ndef applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt :=\n  { alt with\n    patterns  := alt.patterns.map fun p => p.applyFVarSubst s,\n    fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s,\n    rhs       := alt.rhs.applyFVarSubst s }\n\ndef replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt :=\n  { alt with\n    patterns  := alt.patterns.map fun p => p.replaceFVarId fvarId v,\n    fvarDecls :=\n      let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId\n      decls.map $ replaceFVarIdAtLocalDecl fvarId v,\n    rhs       := alt.rhs.replaceFVarId fvarId v }\n\n/-\n  Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`.\n  This extra check is necessary when performing dependent elimination and inaccessible terms have been used.\n  For example, consider the following code fragment:\n\n```\ninductive Vec (\u03b1 : Type u) : Nat \u2192 Type u where\n  | nil : Vec \u03b1 0\n  | cons {n} (head : \u03b1) (tail : Vec \u03b1 n) : Vec \u03b1 (n+1)\n\ninductive VecPred {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 Vec \u03b1 n \u2192 Prop where\n  | nil   : VecPred P Vec.nil\n  | cons  {n : Nat} {head : \u03b1} {tail : Vec \u03b1 n} : P head \u2192 VecPred P tail \u2192 VecPred P (Vec.cons head tail)\n\ntheorem ex {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 (v : Vec \u03b1 (n+1)) \u2192 VecPred P v \u2192 Exists P\n  | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => \u27e8head, h\u27e9\n```\nRecall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term.\nThe elaborator uses an inaccessible term when typing constraints restrict its value.\nThus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)`\nbecause the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`.\nAfter elaboration the alternative becomes:\n```\n  | .(0), @Vec.cons .(\u03b1) .(0) head .(Vec.nil), @VecPred.cons .(\u03b1) .(P) .(0) .(head) .(Vec.nil) h w => \u27e8head, h\u27e9\n```\nwhere\n```\n(head : \u03b1), (h: P head), (w : VecPred P Vec.nil)\n```\nThen, when we process this alternative in this module, the following check will detect that\n`w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`.\nNote that if we had written\n```\ntheorem ex {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 (v : Vec \u03b1 (n+1)) \u2192 VecPred P v \u2192 Exists P\n  | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => \u27e8head, h\u27e9\n```\nwe would get the easier to digest error message\n```\nmissing cases:\n_, (Vec.cons _ _ (Vec.cons _ _ _)), _\n```\n-/\ndef checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do\n  match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with\n  | none          => throwErrorAt alt.ref \"unknown free pattern variable\"\n  | some fvarDecl => do\n    let vType \u2190 inferType v\n    unless (\u2190 isDefEqGuarded fvarDecl.type vType) do\n      withExistingLocalDecls alt.fvarDecls do\n        let (expectedType, givenType) \u2190 addPPExplicitToExposeDiff vType fvarDecl.type\n        throwErrorAt alt.ref \"type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\\nexpected type{indentExpr expectedType}\"\n    pure $ replaceFVarId fvarId v alt\n\nend Alt\n\ninductive Example where\n  | var        : FVarId \u2192 Example\n  | underscore : Example\n  | ctor       : Name \u2192 List Example \u2192 Example\n  | val        : Expr \u2192 Example\n  | arrayLit   : List Example \u2192 Example\n\nnamespace Example\n\npartial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example \u2192 Example\n  | var x        => if x == fvarId then ex else var x\n  | ctor n exs   => ctor n $ exs.map (replaceFVarId fvarId ex)\n  | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex)\n  | ex           => ex\n\npartial def applyFVarSubst (s : FVarSubst) : Example \u2192 Example\n  | var fvarId =>\n    match s.get fvarId with\n    | Expr.fvar fvarId' _ => var fvarId'\n    | _                   => underscore\n  | ctor n exs   => ctor n $ exs.map (applyFVarSubst s)\n  | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s)\n  | ex           => ex\n\npartial def varsToUnderscore : Example \u2192 Example\n  | var x        => underscore\n  | ctor n exs   => ctor n $ exs.map varsToUnderscore\n  | arrayLit exs => arrayLit $ exs.map varsToUnderscore\n  | ex           => ex\n\npartial def toMessageData : Example \u2192 MessageData\n  | var fvarId        => mkFVar fvarId\n  | ctor ctorName []  => mkConst ctorName\n  | ctor ctorName exs => m!\"({mkConst ctorName}{exs.foldl (fun msg pat => m!\"{msg} {toMessageData pat}\") Format.nil})\"\n  | arrayLit exs      => \"#\" ++ MessageData.ofList (exs.map toMessageData)\n  | val e             => e\n  | underscore        => \"_\"\n\nend Example\n\ndef examplesToMessageData (cex : List Example) : MessageData :=\n  MessageData.joinSep (cex.map (Example.toMessageData \u2218 Example.varsToUnderscore)) \", \"\n\nstructure Problem where\n  mvarId        : MVarId\n  vars          : List Expr\n  alts          : List Alt\n  examples      : List Example\n  deriving Inhabited\n\ndef withGoalOf {\u03b1} (p : Problem) (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withMVarContext p.mvarId x\n\ndef Problem.toMessageData (p : Problem) : MetaM MessageData :=\n  withGoalOf p do\n    let alts \u2190 p.alts.mapM Alt.toMessageData\n    let vars \u2190 p.vars.mapM fun x => do let xType \u2190 inferType x; pure m!\"{x}:({xType})\"\n    return m!\"remaining variables: {vars}\\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\\nexamples:{examplesToMessageData p.examples}\\n\"\n\nabbrev CounterExample := List Example\n\ndef counterExampleToMessageData (cex : CounterExample) : MessageData :=\n  examplesToMessageData cex\n\ndef counterExamplesToMessageData (cexs : List CounterExample) : MessageData :=\n  MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line\n\nstructure MatcherResult where\n  matcher         : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables.\n  counterExamples : List CounterExample\n  unusedAltIdxs   : List Nat\n  addMatcher      : MetaM Unit\n\n/--\n  Convert a expression occurring as the argument of a `match` motive application back into a `Pattern`\n  For example, we can use this method to convert `x::y::xs` at\n  ```\n  ...\n  (motive : List Nat \u2192 Sort u_1) (xs : List Nat) (h_1 : (x y : Nat) \u2192 (xs : List Nat) \u2192 motive (x :: y :: xs))\n  ...\n  ```\n  into a pattern object\n-/\npartial def toPattern (e : Expr) : MetaM Pattern := do\n  match inaccessible? e with\n  | some t => return Pattern.inaccessible t\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) =>\n      return Pattern.arrayLit \u03b1 (\u2190 lits.mapM toPattern)\n    | none =>\n      if e.isAppOfArity `namedPattern 3 then\n        let p \u2190 toPattern <| e.getArg! 2\n        match e.getArg! 1 with\n        | Expr.fvar fvarId _ => return Pattern.as fvarId p\n        | _                  => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if e.isNatLit || e.isStringLit || e.isCharLit then\n        return Pattern.val e\n      else if e.isFVar then\n        return Pattern.var e.fvarId!\n      else\n        let newE \u2190 whnf e\n        if newE != e then\n          toPattern newE\n        else matchConstCtor e.getAppFn (fun _ => throwError \"unexpected pattern{indentExpr e}\") fun v us => do\n          let args := e.getAppArgs\n          unless args.size == v.numParams + v.numFields do\n            throwError \"unexpected pattern{indentExpr e}\"\n          let params := args.extract 0 v.numParams\n          let fields := args.extract v.numParams args.size\n          let fields \u2190 fields.mapM toPattern\n          return Pattern.ctor v.name us params.toList fields.toList\n\nend Lean.Meta.Match\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/Match/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.04468086804648062, "lm_q1q2_score": 0.014182881087210058}}
{"text": "import Lean\n\n-- The `cases` tactic does not use `Lean.Meta.cases` under the hood,\n-- so it is unaffected by this issue. We define a tactic\n-- `mcases` that delegates to `Lean.Meta.cases`.\nsyntax (name := mcases) \"mcases\" ident : tactic\n\nnamespace Lean.Elab.Tactic\n\n@[tactic mcases]\ndef evalMcases : Tactic\n| `(tactic| mcases $hyp) => do\n  let hyp \u2190 getFVarId hyp\n  liftMetaTactic fun goal => do\n    let goals \u2190 Lean.Meta.cases goal hyp\n    return goals.map (\u00b7.mvarId) |>.toList\n| _ => unreachable!\n\nend Lean.Elab.Tactic\n\nexample : True := by\n  let h : \u2203 n, n = 0 := \u27e80, rfl\u27e9\n  mcases h\n  sorry -- sorry\n\nexample : True := by\n  have h : \u2203 n, n = 0 := \u27e80, rfl\u27e9\n  mcases h\n  apply True.intro\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/983.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.23934933647101647, "lm_q2_score": 0.05921024534589488, "lm_q1q2_score": 0.01417193293582603}}
{"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 \u2192 regular_mono` and\n* `regular_mono \u2192 mono`\nas well as the dual constructions for regular epimorphisms. Additionally, we give the construction\n* `regular_epi \u27f6 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\u2081 u\u2081 u\u2082\n\nvariables {C : Type u\u2081} [category.{v\u2081} 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 \u27f6 Y) :=\n(Z : C)\n(left right : Y \u27f6 Z)\n(w : f \u226b left = f \u226b right)\n(is_limit : is_limit (fork.of_\u03b9 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 \u27f6 Y) [regular_mono f] : mono f :=\nmono_of_is_limit_fork regular_mono.is_limit\n\ninstance equalizer_regular (g h : X \u27f6 Y) [has_limit (parallel_pair g h)] :\n  regular_mono (equalizer.\u03b9 g h) :=\n{ Z := Y,\n  left := g,\n  right := h,\n  w := equalizer.condition g h,\n  is_limit := fork.is_limit.mk _ (\u03bb s, limit.lift _ s) (by simp) (\u03bb s m w, by { ext1, simp [\u2190w] }) }\n\n/-- Every split monomorphism is a regular monomorphism. -/\n@[priority 100]\ninstance regular_mono.of_split_mono (f : X \u27f6 Y) [split_mono f] : regular_mono f :=\n{ Z     := Y,\n  left  := \ud835\udfd9 Y,\n  right := retraction f \u226b 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 \u27f6 Y` equalizing `regular_mono.left` and\n    `regular_mono.right` induces a morphism `l : W \u27f6 X` such that `l \u226b f = k`. -/\ndef regular_mono.lift' {W : C} (f : X \u27f6 Y) [regular_mono f] (k : W \u27f6 Y)\n  (h : k \u226b (regular_mono.left : Y \u27f6 @regular_mono.Z _ _ _ _ f _) = k \u226b regular_mono.right) :\n  {l : W \u27f6 X // l \u226b 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S}\n  {k : R \u27f6 S} [hr : regular_mono h] (comm : f \u226b h = g \u226b k)\n  (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono g :=\n{ Z := hr.Z,\n  left := k \u226b hr.left,\n  right := k \u226b hr.right,\n  w := by rw [\u2190 reassoc_of comm, \u2190 reassoc_of comm, hr.w],\n  is_limit :=\n  begin\n    apply fork.is_limit.mk' _ _,\n    intro s,\n    have l\u2081 : (fork.\u03b9 s \u226b k) \u226b regular_mono.left = (fork.\u03b9 s \u226b k) \u226b regular_mono.right,\n      rw [category.assoc, s.condition, category.assoc],\n    obtain \u27e8l, hl\u27e9 := fork.is_limit.lift' hr.is_limit _ l\u2081,\n    obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := pullback_cone.is_limit.lift' t _ _ hl,\n    refine \u27e8p, hp\u2082, _\u27e9,\n    intros m w,\n    have z : m \u226b g = p \u226b g := w.trans hp\u2082.symm,\n    apply t.hom_ext,\n    apply (pullback_cone.mk f g comm).equalizer_ext,\n    { erw [\u2190 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S}\n  {k : R \u27f6 S} [hr : regular_mono k] (comm : f \u226b h = g \u226b 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 \u27f6 Y) [regular_mono f] : strong_mono f :=\n{ mono := by apply_instance,\n  has_lift :=\n  begin\n    introsI,\n    have : v \u226b (regular_mono.left : Y \u27f6 regular_mono.Z f) = v \u226b regular_mono.right,\n    { apply (cancel_epi z).1,\n      simp only [regular_mono.w, \u2190 reassoc_of h] },\n    obtain \u27e8t, ht\u27e9 := regular_mono.lift' _ _ this,\n    refine arrow.has_lift.mk \u27e8t, (cancel_mono f).1 _, ht\u27e9,\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 \u27f6 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 : \u2200 {X Y : C} (f : X \u27f6 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 \u27f6 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 := \u03bb _ _ 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 := \u03bb _ _ 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 \u27f6 Y) :=\n(W : C)\n(left right : W \u27f6 X)\n(w : left \u226b f = right \u226b f)\n(is_colimit : is_colimit (cofork.of_\u03c0 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 \u27f6 Y) [regular_epi f] : epi f :=\nepi_of_is_colimit_cofork regular_epi.is_colimit\n\ninstance coequalizer_regular (g h : X \u27f6 Y) [has_colimit (parallel_pair g h)] :\n  regular_epi (coequalizer.\u03c0 g h) :=\n{ W := X,\n  left := g,\n  right := h,\n  w := coequalizer.condition g h,\n  is_colimit := cofork.is_colimit.mk _ (\u03bb s, colimit.desc _ s) (by simp)\n    (\u03bb s m w, by { ext1, simp [\u2190w] }) }\n\n/-- Every split epimorphism is a regular epimorphism. -/\n@[priority 100]\ninstance regular_epi.of_split_epi (f : X \u27f6 Y) [split_epi f] : regular_epi f :=\n{ W     := X,\n  left  := \ud835\udfd9 X,\n  right := f \u226b 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 \u27f6 W` coequalizing `regular_epi.left` and\n    `regular_epi.right` induces `l : Y \u27f6 W` such that `f \u226b l = k`. -/\ndef regular_epi.desc' {W : C} (f : X \u27f6 Y) [regular_epi f] (k : X \u27f6 W)\n  (h : (regular_epi.left : regular_epi.W f \u27f6 X) \u226b k = regular_epi.right \u226b k) :\n  {l : Y \u27f6 W // f \u226b 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S} {k : R \u27f6 S}\n  [gr : regular_epi g] (comm : f \u226b h = g \u226b k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi h :=\n{ W := gr.W,\n  left := gr.left \u226b f,\n  right := gr.right \u226b 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\u2081 : gr.left \u226b f \u226b s.\u03c0 = gr.right \u226b f \u226b s.\u03c0,\n      rw [\u2190 category.assoc, \u2190 category.assoc, s.condition],\n    obtain \u27e8l, hl\u27e9 := cofork.is_colimit.desc' gr.is_colimit (f \u226b cofork.\u03c0 s) l\u2081,\n    obtain \u27e8p, hp\u2081, hp\u2082\u27e9 := pushout_cocone.is_colimit.desc' t _ _ hl.symm,\n    refine \u27e8p, hp\u2081, _\u27e9,\n    intros m w,\n    have z := w.trans hp\u2081.symm,\n    apply t.hom_ext,\n    apply (pushout_cocone.mk _ _ comm).coequalizer_ext,\n    { exact z },\n    { erw [\u2190 cancel_epi g, \u2190 reassoc_of comm, \u2190 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 \u27f6 Q} {g : P \u27f6 R} {h : Q \u27f6 S} {k : R \u27f6 S}\n  [fr : regular_epi f] (comm : f \u226b h = g \u226b 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 \u27f6 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 \u27f6 X) \u226b u = regular_epi.right \u226b u,\n    { apply (cancel_mono z).1,\n      simp only [category.assoc, h, regular_epi.w_assoc] },\n    obtain \u27e8t, ht\u27e9 := regular_epi.desc' f u this,\n    exact arrow.has_lift.mk \u27e8t, ht, (cancel_epi f).1\n      (by simp only [\u2190category.assoc, ht, \u2190h, arrow.mk_hom, arrow.hom_mk'_right])\u27e9,\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 \u27f6 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 : \u2200 {X Y : C} (f : X \u27f6 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 \u27f6 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 := \u03bb _ _ 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 := \u03bb _ _ 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 \u00d7 spec.State)\n  : TaskM spec T\n| s => match f s with\n  | \u27e8t, s'\u27e9 => 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 \u27e8\u27e9\n  else\n    IterationResult.Panic s \"Assertion failed\"\n\ndef atomic_blocking_rmr\n  (block_until : spec.State -> Bool)\n  (f : spec.State -> T \u00d7 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 \u2192 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  \u03bb s => IterationResult.Done s t\n\ndef bind {U V : Type} (mu : TaskM spec U) (f : U -> TaskM spec V) : TaskM spec V :=\n  \u03bb s => match h : mu s with\n    | IterationResult.Done s' u => IterationResult.Running s' (\u03bb _ => 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 :=\u27e8h\u27e9\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' (\u03bb _ => 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 Lean.Meta.Tactic.Rewrite\nimport Lean.Meta.Tactic.Replace\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.Tactic.ElabTerm\nimport Lean.Elab.Tactic.Location\nimport Lean.Elab.Tactic.Config\nopen Lean Meta Elab Tactic\nopen Lean.Elab.Term\n\n/- Shows how to get arguments to tactics\nelab \"myTactic\" argumentStx:term : tactic =>  do\n  let goals <- getGoals\n  let target <- getMainTarget\n  match target.eq? with \n  | none =>  throwError \"target {target} is not an equality\"\n  | some (equalityType, equalityLhs, equalityRhs) => \n    let maingoal <- getMainGoal\n    let argumentAsTy <- Lean.Elab.Term.elabType argumentStx \n\n    liftMetaTactic fun mvarId => do\n      -- let (h, mvarId) <- intro1P mvarId\n      -- let goals <- apply mvarId (mkApp (mkConst ``Or.elim) (mkFVar h))\n      let lctx <- getLCtx\n      let mctx <- getMCtx\n      let hypsOfType <- lctx.foldlM (init := []) (fun accum decl =>  do \n          if decl.type == equalityType \n          then return (decl.userName, decl.type) :: accum\n          else return accum)\n      let out := \"\\n====\\n\"\n      let out := out ++ m!\"-argumentStx: {argumentStx}\\n\"\n      let out := out ++ m!\"-argumentAsTy: {argumentAsTy}\\n\"\n      let out := out ++ m!\"-equalityType: {equalityType}\\n\"\n      let out := out ++ m!\"-equalityLhs: {equalityLhs}\\n\"\n      let out := out ++ m!\"-equalityRhs: {equalityRhs}\\n\"\n      let out := out ++ m!\"-hypsOfEqualityType: {hypsOfType}\\n\"\n      -- let out := out ++ m!\"-argumentStx: {argumentStx}\\n\"\n      -- let out := out ++ m!\"-mainGoal: {maingoal}\\n\"\n      -- let out := out ++ m!\"-goals: {goals}\\n\"\n      -- let out := out ++ m!\"-target: {target}\\n\"\n      let out := out ++ \"\\n====\\n\"\n      throwTacticEx `myTactic mvarId out\n      return goals\n-/\n\nelab \"myTactic\" : tactic =>  do\n  let goals <- getGoals\n  let target <- getMainTarget\n  match target.eq? with \n  | none =>  throwError \"target {target} is not an equality\"\n  | some (equalityType, equalityLhs, equalityRhs) => \n    let maingoal <- getMainGoal\n    liftMetaTactic fun mvarId => do\n      -- let (h, mvarId) <- intro1P mvarId\n      -- let goals <- apply mvarId (mkApp (mkConst ``Or.elim) (mkFVar h))\n      let lctx <- getLCtx\n      let mctx <- getMCtx\n      let hypsOfType <- lctx.foldlM (init := []) (fun accum decl =>  do \n          if decl.type == equalityType \n          then return (decl.userName, decl.type) :: accum\n          else return accum)\n      let out := \"\\n====\\n\"\n      let out := out ++ m!\"-equalityType: {equalityType}\\n\"\n      let out := out ++ m!\"-equalityLhs: {equalityLhs}\\n\"\n      let out := out ++ m!\"-equalityRhs: {equalityRhs}\\n\"\n      let out := out ++ m!\"-hypsOfEqualityType: {hypsOfType}\\n\"\n      -- let out := out ++ m!\"-argumentStx: {argumentStx}\\n\"\n      -- let out := out ++ m!\"-mainGoal: {maingoal}\\n\"\n      -- let out := out ++ m!\"-goals: {goals}\\n\"\n      -- let out := out ++ m!\"-target: {target}\\n\"\n      let out := out ++ \"\\n====\\n\"\n      throwTacticEx `myTactic mvarId out\n      return goals\n\n-- theorem test {p: Prop} : (p \u2228 p) -> p := by\n--   intro h\n--   apply Or.elim h\n--   trace_state\n\n-- TODO: Figure out how to extract hypotheses from goal.\ntheorem testSuccess : \u2200 (anat: Nat) (bint: Int) (cnat: Nat) (dint: Int) (eint: Int), bint = dint := by\n intros a b c d e\n myTactic\n sorry\n\ntheorem testGoalNotEqualityMustFail  : \u2200 (a: Nat) (b: Int) (c: Nat) , Nat := by\n intros a b c\n myTactic \n\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/playground/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.034100424362588755, "lm_q1q2_score": 0.014148226709218089}}
{"text": "import vc0.basic\n\nnamespace c0\nopen ast\n\nnamespace value\n\ndef ts_sized (\u0393 : ast) : type \u2295 sdef \u2192 Prop\n| (sum.inl \u03c4) := \u0393.sized \u03c4\n| (sum.inr sd) := \u2200 \u03c4 \u2208 sd.values, \u0393.sized \u03c4\n\ntheorem default_exists {\u0393 : ast} (ok : \u0393.okind) :\n  \u2200 ts, ts_sized \u0393 ts \u2192 \u2203 (v : value), default \u0393 ts v :=\nast.okind.induction' ok $ \u03bb \u0393 ok IH, begin\n  have : \u2200 {\u03c4}, \u0393.sized \u03c4 \u2192 \u2203 (v : value), default \u0393 (sum.inl \u03c4) v,\n  { intros \u03c4 sz, induction \u03c4,\n    { exact \u27e8_, default.int\u27e9 },\n    { exact \u27e8_, default.bool\u27e9 },\n    { exact \u27e8_, default.ref\u27e9 },\n    { exact \u27e8_, default.arr\u27e9 },\n    { cases sz with sd h,\n      cases (get_sdef_ex_iff ok).1 \u27e8_, h\u27e9 with x\u03c4s m,\n      cases IH with d \u0393 ok' IH'; rcases m with rfl | m,\n      { rcases sdecl_ok1 ok' with \u27e8nd, sd', al, sz\u27e9,\n        cases get_sdef_determ ok h \u27e8or.inl rfl, al.imp $ \u03bb _ _ _ h, h.weak\u27e9,\n        rcases IH' (sum.inr sd) sz with \u27e8v, h'\u27e9,\n        exact \u27e8_, default.struct h h'.weak\u27e9 },\n      { cases ok,\n        cases (get_sdef_ex_iff ok_a_1).2 \u27e8_, m\u27e9 with sd' h\u2081,\n        cases IH' (sum.inl (type.struct \u03c4)) \u27e8_, h\u2081\u27e9 with v h\u2082,\n        exact \u27e8v, h\u2082.weak\u27e9 } } },\n  rintro (\u03c4 | sd) sz,\n  { exact this sz },\n  { refine alist.rec' (\u03bb sz, \u27e8_, default.nil\u27e9) (\u03bb sd x \u03c4 h IH sz, _) sd sz,\n    cases list.forall_mem_cons.1 sz with sz\u2081 sz\u2082,\n    cases this sz\u2081 with v v0,\n    cases IH sz\u2082 with vs vs0,\n    exact \u27e8_, default.cons v0 vs0\u27e9 }\nend\n\nend value\n\nnamespace addr\n\ntheorem update_at.progress {\u03b1 \u03b2} (S : \u03b1 \u2192 \u03b2 \u2192 Prop) {b}\n  {R : \u03b1 \u2192 \u03b1 \u2192 Prop} (hR : \u2200 x, S x b \u2192 \u2203 y, R x y) :\n  \u2200 {l\u2081 l\u2082}, list.forall\u2082 S l\u2081 l\u2082 \u2192 \u2200 {n}, b \u2208 list.nth l\u2082 n \u2192 \u2203 l', list.update_at R n l\u2081 l'\n| _ _ (@list.forall\u2082.cons _ _ S a b' l\u2081 l\u2082 r h) 0 rfl :=\n  let \u27e8y, r\u27e9 := hR a r in \u27e8_, list.update_at.one r\u27e9\n| _ _ (@list.forall\u2082.cons _ _ S a b' l\u2081 l\u2082 r h) (n+1) h' :=\n  let \u27e8l\u2082, r\u27e9 := update_at.progress h h' in\n  \u27e8_, list.update_at.cons r\u27e9\n\ntheorem at_head.progress {\u0393 E \u03c4 \u03c4s}\n  {R : value \u2192 value \u2192 Prop} (hR : \u2200 x, value.ok \u0393 E x \u03c4 \u2192 \u2203 y, R x y)\n  (x) (xok : value.ok \u0393 E x (vtype.cons \u03c4 \u03c4s)) :\n  \u2203 y, value.at_head R x y :=\nby cases xok; cases hR _ xok_a with v' h'; exact \u27e8_, \u27e8h'\u27e9\u27e9\n\ntheorem at_tail.progress {\u0393 E \u03c4 \u03c4s}\n  {R : value \u2192 value \u2192 Prop} (hR : \u2200 x, value.ok \u0393 E x \u03c4s \u2192 \u2203 y, R x y)\n  (x) (xok : value.ok \u0393 E x (vtype.cons \u03c4 \u03c4s)) :\n  \u2203 y, value.at_tail R x y :=\nby cases xok; cases hR _ xok_a_1 with v' h'; exact \u27e8_, \u27e8h'\u27e9\u27e9\n\ntheorem at_nth'.progress {\u0393 E \u03c4}\n  {R : value \u2192 value \u2192 Prop} (hR : \u2200 x, value.ok \u0393 E x \u03c4 \u2192 \u2203 y, R x y) :\n  \u2200 {i n}, i < n \u2192 \u2200 x, value.ok \u0393 E x (vtype.arr' \u03c4 n) \u2192\n  \u2203 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 {\u0393 E \u03c4}\n  {R : value \u2192 value \u2192 Prop} (hR : \u2200 x, value.ok \u0393 E x \u03c4 \u2192 \u2203 y, R x y)\n  {i n} (lt : i < n) (x) (xok : value.ok \u0393 E x (vtype.arr \u03c4 n)) :\n  \u2203 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 \u27e8_, lt, h\u27e9\nend\n\ntheorem at_field.progress {\u0393 E \u03c4}\n  {R : value \u2192 value \u2192 Prop} (hR : \u2200 x, value.ok \u0393 E x \u03c4 \u2192 \u2203 y, R x y)\n  {s sd f} (hd : \u0393.get_sdef s sd)\n  {t} (ht : t \u2208 sd.lookup f) (t\u03c4 : vtype.of_ty (exp.type.reg t) \u03c4)\n  (x) (xok : value.ok \u0393 E x (vtype.struct s)) :\n  \u2203 y, value.at_field R f x y :=\nbegin\n  rcases xok with _|_|_|_|_|_|_|_|\u27e8_, vs, rfl, al\u27e9,\n  cases vtype.of_ty_alist sd with \u03c4s s\u03c4,\n  rcases value.of_map_ok.1 (al _ _ hd s\u03c4) with \u27e8vs', e, h\u27e9,\n  cases value.of_map_inj e,\n  rcases s\u03c4.rel_of_lookup_right ht with \u27e8\u03c4', h\u03c4, t\u03c4'\u27e9,\n  cases vtype.of_ty_determ t\u03c4 t\u03c4',\n  rcases h.flip.rel_of_lookup_right h\u03c4 with \u27e8v, m, vok\u27e9,\n  cases hR _ vok with y r,\n  exact \u27e8_, r, m, rfl, rfl\u27e9\nend\n\ntheorem update.progress {\u0393 E \u03c3 H \u03b7} (ok : ast.okind \u0393)\n  (Eok : heap.ok \u0393 H E) (\u03b7ok : vars.ok \u0393 E \u03b7 \u03c3)\n  {a \u03c4} (aok : addr.ok \u0393 E \u03c3 a \u03c4)\n  {R : value \u2192 value \u2192 Prop} (hR : \u2200 x, value.ok \u0393 E x \u03c4 \u2192 \u2203 y, R x y)\n  (Rok : \u2200 x, value.ok \u0393 E x \u03c4 \u2192 \u2200 y, R x y \u2192 value.ok \u0393 E y \u03c4) :\n  \u2203 H' \u03b7', update H \u03b7 R a H' \u03b7' :=\nbegin\n  induction a generalizing \u03c4 R; cases aok,\n  { cases update_at.progress _ hR Eok aok_a with H' h,\n    exact \u27e8_, _, update.ref h\u27e9 },\n  { rcases \u03b7ok _ _ aok_a with \u27e8v, h, vok\u27e9,\n    cases hR v vok with v' h',\n    exact \u27e8_, _, update.var h h' rfl\u27e9 },\n  { rcases a_ih aok_a_1 (at_head.progress hR) (at_head.ok Rok) with \u27e8H', \u03b7', h\u27e9,\n    exact \u27e8_, _, update.head h\u27e9 },\n  { rcases a_ih aok_a_1 (at_tail.progress hR) (at_tail.ok Rok) with \u27e8H', \u03b7', h\u27e9,\n    exact \u27e8_, _, update.tail h\u27e9 },\n  { rcases a_ih aok_a_2 (at_nth.progress hR aok_a_1) (at_nth.ok Rok aok_a_1) with \u27e8H', \u03b7', h\u27e9,\n    exact \u27e8_, _, update.nth h\u27e9 },\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 \u27e8H', \u03b7', h\u27e9,\n    exact \u27e8_, _, update.field h\u27e9 }\nend\n\ntheorem get.progress {\u0393 E \u03c3 \u0394 H \u03b7 a \u03c4}\n  (Eok : heap.ok \u0393 H E) (\u03c3ok : vars_ty.ok \u0394 \u03c3)\n  (\u03b7ok : vars.ok \u0393 E \u03b7 \u03c3) (aok : addr.ok \u0393 E \u03c3 a \u03c4) :\n  \u2203 v, get H \u03b7 a v :=\nbegin\n  induction aok,\n  { rcases Eok.flip.nth_right aok_a with \u27e8v, h, vok\u27e9,\n    exact \u27e8_, get.ref h\u27e9 },\n  { rcases \u03b7ok _ _ aok_a with \u27e8v, h, vok\u27e9,\n    exact \u27e8_, get.var h\u27e9 },\n  { rcases aok_ih with \u27e8v, h\u27e9,\n    cases get.ok \u03c3ok Eok \u03b7ok aok_a_1 h,\n    exact \u27e8_, get.head h\u27e9 },\n  { rcases aok_ih with \u27e8v, h\u27e9,\n    cases get.ok \u03c3ok Eok \u03b7ok aok_a_1 h,\n    exact \u27e8_, get.tail h\u27e9 },\n  case c0.addr.ok.nth : a i n \u03c4 lt aok IH {\n    rcases IH with \u27e8_, h\u27e9,\n    cases get.ok \u03c3ok Eok \u03b7ok aok h,\n    suffices : \u2203 v', value.is_nth i v v',\n    { cases this with v' h', exact \u27e8v', get.nth h h'\u27e9 },\n    clear h aok _x,\n    induction i with i IH generalizing n v,\n    { cases n, {cases lt},\n      cases a_1, exact \u27e8_, value.is_nth.zero\u27e9 },\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 \u27e8_, value.is_nth.succ h'\u27e9 } },\n  case c0.addr.ok.field : a s f t sd \u03c4 hd hf t\u03c4 aok IH {\n    rcases IH with \u27e8v, h\u27e9,\n    cases get.ok \u03c3ok Eok \u03b7ok aok h, subst v,\n    cases vtype.of_ty_alist sd with \u03c4s s\u03c4,\n    rcases value.of_map_ok.1 (a_1 _ _ hd s\u03c4) with \u27e8vs', e, al\u27e9,\n    cases value.of_map_inj e,\n    rcases s\u03c4.rel_of_lookup_right hf with \u27e8\u03c4', h\u03c4, t\u03c4'\u27e9,\n    cases vtype.of_ty_determ t\u03c4 t\u03c4',\n    rcases al.flip.rel_of_lookup_right h\u03c4 with \u27e8v', h', vok\u27e9,\n    exact \u27e8v', get.field h h'\u27e9 }\nend\n\ntheorem get_len.progress {\u0393 E \u03c3 \u0394 H \u03b7 a \u03c4 n}\n  (Eok : heap.ok \u0393 H E) (\u03c3ok : vars_ty.ok \u0394 \u03c3)\n  (\u03b7ok : vars.ok \u0393 E \u03b7 \u03c3) (aok : addr.ok \u0393 E \u03c3 a (vtype.arr \u03c4 n)) :\n  get_len H \u03b7 a n :=\nbegin\n  cases get.progress Eok \u03c3ok \u03b7ok aok with v h,\n  cases get.ok \u03c3ok Eok \u03b7ok aok h, exact \u27e8h\u27e9\nend\n\nend addr\n\ntheorem alloc_arr.progress (i:int32) :\n  (\u2203 (j:\u2115), (i:\u2124) = j) \u2228 i < 0 :=\nbegin\n  cases lt_or_le (i:\u2124) 0 with h\u2081,\n  { rw [\u2190 int32.coe_zero, int32.coe_lt] at h\u2081,\n    exact or.inr h\u2081 },\n  { cases e : (i:\u2124) with j,\n    { exact or.inl \u27e8_, rfl\u27e9 },\n    { rw e at h, cases h } },\nend\n\ntheorem bounds.progress (n : \u2115) (i:int32) :\n  (\u2203 (j:\u2115), (i:\u2124) = j \u2227 j < n) \u2228 i < 0 \u2228 (n:\u2124) \u2264 (i:\u2124) :=\nbegin\n  rcases alloc_arr.progress i with \u27e8j, e\u27e9 | h,\n  { cases lt_or_le (i:\u2124) (n:\u2124) with h\u2082,\n    { refine or.inl \u27e8j, e, int.coe_nat_lt.1 _\u27e9,\n      rw \u2190 e, exact h\u2082 },\n    { exact or.inr (or.inr h) } },\n  { exact or.inr (or.inl h) }\nend\n\ntheorem step_binop.progress {\u0393 E op v\u2081 v\u2082 t\u2081 t\u2082 \u03c4\u2081}\n  (opok : binop.ok op t\u2081 t\u2082)\n  (t\u03c4\u2081 : vtype.of_ty (exp.type.reg t\u2081) \u03c4\u2081)\n  (vok\u2081 : value.ok \u0393 E v\u2081 \u03c4\u2081)\n  (vok\u2082 : value.ok \u0393 E v\u2082 \u03c4\u2081) :\n  \u2203 v, value.step_binop op v\u2081 v\u2082 v :=\nbegin\n  cases opok,\n  case c0.binop.ok.comp {\n    cases t\u03c4\u2081, cases vok\u2081 with n\u2081, cases vok\u2082 with n\u2082,\n    have : \u2203 b, value.step_comp opok_1 (value.int n\u2081) (value.int n\u2082) b,\n    { cases opok_1; exact \u27e8_, by constructor\u27e9 },\n    cases this with b h,\n    exact \u27e8_, value.step_binop.comp h\u27e9 },\n  case c0.binop.ok.eq { exact \u27e8_, by constructor; constructor\u27e9 },\n  case c0.binop.ok.ne { exact \u27e8_, by constructor; constructor\u27e9 },\n  all_goals {\n    cases t\u03c4\u2081, cases vok\u2081, cases vok\u2082,\n    exact \u27e8_, by constructor\u27e9 }\nend\n\ntheorem step_unop.progress  {\u0393 E op v t\u2081 t\u2082 \u03c4\u2081}\n  (opok : unop.ok op t\u2081 t\u2082)\n  (t\u03c4 : vtype.of_ty (exp.type.reg t\u2081) \u03c4\u2081)\n  (vok : value.ok \u0393 E v \u03c4\u2081) :\n  \u2203 v', value.step_unop op v v' :=\nby cases opok; {\n  cases t\u03c4, cases vok,\n  exact \u27e8_, by constructor\u27e9 }\n\ntheorem step_call.progress {\u0393 E \u0394 f vs ts \u03c4s t \u03c4 s}\n  (ok : ast.ok \u0393)\n  (fd : get_fdef \u0393 f \u27e8ts, t\u27e9)\n  (hs : get_body \u0393 f \u03c4 \u0394 s)\n  (t\u03c4 : vtype.of_ty (exp.type.ls ts) \u03c4s)\n  (vsok : value.ok \u0393 E vs \u03c4s) :\n  \u2203 \u03b7, step_call \u0394 vs \u03b7 :=\nbegin\n  cases hs,\n  have : list.forall\u2082 (\u03bb (c : ident \u00d7 ast.type), eval_ty \u0393 c.2) hs_x\u03c4s \u0394.values,\n  { rw [alist.values, list.forall\u2082_map_right_iff],\n    unfold alist.forall\u2082 at hs_a_1,\n    rw [alist.mk'_entries, list.forall\u2082_map_left_iff] at hs_a_1,\n    refine hs_a_1.imp _, rintro _ _ \u27e8i, t, \u03c4, h\u27e9, 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 \u0394.entries.map sigma.snd with \u0394.values,\n  refine alist.rec' _ (\u03bb \u0394 x t h IH, _) \u0394 vs \u03c4s vsok t\u03c4; intros vs \u03c4s vsok t\u03c4,\n  { cases t\u03c4, cases vsok,\n    exact \u27e8_, by constructor\u27e9 },\n  { cases t\u03c4, cases vsok,\n    rcases IH _ _ vsok_a_1 t\u03c4_a_1 with \u27e8\u03b7, h\u27e9,\n    exact \u27e8_, step_call.cons _ h\u27e9 }\nend\n\ntheorem step_ret.progress {\u0393 E \u03c3s H S \u03b7 \u03c4 v}\n  (Sok : stack.ok \u0393 E \u03c3s S \u03c4) (vok : value.ok \u0393 E v \u03c4) :\n  \u2203 s', step_ret \u27e8H, S, \u03b7\u27e9 v s' :=\nbegin\n  cases Sok,\n  { cases vok, exact \u27e8_, step_ret.done\u27e9 },\n  { exact \u27e8_, step_ret.ret\u27e9 }\nend\n\ntheorem step_deref.progress {\u0393 E \u03c3 \u0394 H S \u03b7 a \u03c4 K}\n  (Eok : heap.ok \u0393 H E) (\u03c3ok : vars_ty.ok \u0394 \u03c3)\n  (\u03b7ok : vars.ok \u0393 E \u03b7 \u03c3) (aok : addr_opt.ok \u0393 E \u03c3 a \u03c4) :\n  \u2203 s', step_deref \u27e8H, S, \u03b7\u27e9 a K s' :=\nbegin\n  cases a,\n  { exact \u27e8_, step_deref.null\u27e9 },\n  { cases addr.get.progress Eok \u03c3ok \u03b7ok aok with v h,\n    exact \u27e8_, step_deref.deref h\u27e9 }\nend\n\ninductive progresses (\u0393 : ast) (s : state) : Prop\n| final {} : s.final \u2192 progresses\n| prog {s'} : step \u0393 s none s' \u2192 progresses\n| io {i} (f : heap \u00d7 value \u2192 state) :\n  (\u2200 o, step \u0393 s (some (i, o)) (f o)) \u2192 progresses\nopen progresses\n\ntheorem progress {\u0393 : ast} (ok : \u0393.ok)\n  {s} (stok : state.ok \u0393 s) : progresses \u0393 s :=\nbegin\n  cases stok,\n  case c0.state.ok.stmt : E \u03c3s \u03c3 \u0394 C \u03c4 \u03b4 s K t Cok t\u03c4 sok si Kok {\n    cases Cok with _ _ _ H \u03b7 S _ _ \u03c3ok Eok \u03b7ok Sok,\n    cases sok,\n    { exact prog (step.decl sok_a) },\n    { exact prog (step.decl_asgn sok_a) },\n    { exact prog step.If\u2081 },\n    { exact prog step.while },\n    { cases e : lval.is_var sok_lv,\n      { exact prog (step.asgn\u2081 e) },\n      { exact prog (step.asgn_var\u2081 e) } },\n    { exact prog step.asnop\u2081 },\n    { exact prog step.eval\u2081 },\n    { exact prog step.assert\u2081 },\n    { cases sok_e,\n      { cases sok_a, cases t\u03c4,\n        cases step_ret.progress Sok value.ok.nil with s' h,\n        exact prog (step.ret_none h) },\n      { exact prog step.ret\u2081 } },\n    { cases K,\n      { rcases Kok with \u27e8\u27e8\u27e9\u27e9 | Kok,\n        cases Kok.eq_none, cases t\u03c4,\n        cases step_ret.progress Sok value.ok.nil with s' h,\n        exact prog (step.nop\u2081 h) },\n      { exact prog step.nop\u2082 } },\n    { exact prog step.seq } },\n  case c0.state.ok.exp : E \u03c3s \u03c3 H \u03b7 S \u0394 ret \u03c4 e \u03b1 K Cok eu lok eok {\n    cases Cok with _ _ _ H \u03b7 S _ _ \u03c3ok Eok \u03b7ok Sok,\n    rcases eok with \u27e8t, eok, t\u03c4\u27e9,\n    cases \u03b1,\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 \u27e8\u03c4', i\u03c4'\u27e9,\n        rcases \u03b7ok _ _ i\u03c4' with \u27e8v, h, vok\u27e9,\n        exact prog (step.var h) },\n      { exact prog step.binop\u2081 },\n      { exact prog step.unop\u2081 },\n      { exact prog step.cond\u2081 },\n      { exact prog step.nil },\n      { exact prog step.cons\u2081 },\n      { exact prog step.call\u2081 },\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 \u27e8\u27e9) },\n      { exact prog (step.alloc_arr\u2081 eok_a) } },\n    { cases lok,\n      { exact prog step.addr_var },\n      { exact prog step.addr_deref\u2081 },\n      { exact prog step.addr_index\u2081 },\n      { exact prog step.addr_field\u2081 } } },\n  case c0.state.ok.ret : E \u03c3s \u03c3 H \u03b7 S \u0394 ret \u03c4 \u03b1 a K Cok aok Kok {\n    cases Cok with _ _ _ H \u03b7 S _ _ \u03c3ok Eok \u03b7ok Sok,\n    cases Kok,\n    { cases aok,\n      exact prog step.If\u2082 },\n    { exact prog step.asgn\u2082 },\n    { cases Kok_a,\n      { exact prog step.asgn_err },\n      { rcases addr.update.progress ok.ind Eok \u03b7ok\n          Kok_a_1 (by exact \u03bb _ _, \u27e8a, rfl\u27e9)\n          (addr.eq.ok aok) with \u27e8H', \u03b7', h\u27e9,\n        exact prog (step.asgn\u2083 h) } },\n    { exact prog step.asgn_var\u2082 },\n    { cases step_deref.progress Eok \u03c3ok \u03b7ok aok with s' h,\n      exact prog (step.asnop\u2082 h) },\n    { exact prog step.eval\u2082 },\n    { cases aok,\n      exact prog step.assert\u2082 },\n    { cases step_ret.progress Sok aok with s' h,\n      exact prog (step.ret\u2082 h) },\n    { cases aok;\n      exact prog step.addr_deref\u2082 },\n    { cases a,\n      { exact prog step.addr_field_err },\n      { exact prog step.addr_field\u2082 } },\n    { cases aok;\n      exact prog step.addr_index\u2082 },\n    { cases aok, cases Kok_o,\n      { exact prog step.addr_index_err\u2081 },\n      { cases Kok_a _ rfl with n aok,\n        have h := addr.get_len.progress Eok \u03c3ok \u03b7ok aok,\n        rcases bounds.progress n aok_1 with \u27e8j, h\u2081, h\u2082\u27e9 | h',\n        { exact prog (step.addr_index\u2083 h h\u2081 h\u2082) },\n        { exact prog (step.addr_index_err\u2082 h h') } } },\n    { exact prog step.binop\u2082 },\n    { rcases step_binop.progress Kok_a Kok_a_1 Kok_a_3 aok with \u27e8v|err, h\u27e9,\n      { exact prog (step.binop\u2083 h) },\n      { exact prog (step.binop_err h) } },\n    { rcases step_unop.progress Kok_a Kok_a_1 aok with \u27e8v, h\u27e9,\n      exact prog (step.unop\u2082 h) },\n    { cases aok,\n      exact prog step.cond\u2082 },\n    { exact prog step.cons\u2082 },\n    { exact prog step.cons\u2083 },\n    { cases Kok,\n      rcases Kok_a_6 with ext | \u27e8\u03c4, \u0394, s, h\u27e9,\n      { exact progresses.io\n          (\u03bb o, state.ret cont_ty.V \u27e8o.1, S, \u03b7\u27e9 o.2 Kok_K)\n          (\u03bb \u27e8H', v\u27e9, step.call_extern ext) },\n      { cases step_call.progress ok Kok_a_5 h Kok_a_8 aok with \u03b7 h',\n        exact prog (step.call\u2082 h h') } },\n    { cases step_deref.progress Eok \u03c3ok \u03b7ok aok with s' h,\n      exact prog (step.deref' h) },\n    { cases aok,\n      rcases alloc_arr.progress aok_1 with \u27e8j, h\u27e9 | h,\n      { cases value.default_exists ok.ind (sum.inl _) Kok_a_1 with v v0,\n        exact prog (step.alloc_arr\u2082 h v0 \u27e8\u27e9) },\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) 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.Tactic.Simp\nimport Lean.Meta.Tactic.Replace\nimport Lean.Elab.BuiltinNotation\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.Tactic.ElabTerm\nimport Lean.Elab.Tactic.Location\nimport Lean.Elab.Tactic.Config\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\ndeclare_config_elab elabSimpConfigCore    Meta.Simp.Config\ndeclare_config_elab elabSimpConfigCtxCore Meta.Simp.ConfigCtx\n\n/--\n  Implement a `simp` discharge function using the given tactic syntax code.\n  Recall that `simp` dischargers are in `SimpM` which does not have access to `Term.State`.\n  We need access to `Term.State` to store messages and update the info tree.\n  Thus, we create an `IO.ref` to track these changes at `Term.State` when we execute `tacticCode`.\n  We must set this reference with the current `Term.State` before we execute `simp` using the\n  generated `Simp.Discharge`. -/\ndef tacticToDischarge (tacticCode : Syntax) : TacticM (IO.Ref Term.State \u00d7 Simp.Discharge) := do\n  let tacticCode \u2190 `(tactic| try ($tacticCode:tacticSeq))\n  let ref \u2190 IO.mkRef (\u2190 getThe Term.State)\n  let ctx \u2190 readThe Term.Context\n  let disch : Simp.Discharge := fun e => do\n    let mvar \u2190 mkFreshExprSyntheticOpaqueMVar e `simp.discharger\n    let s \u2190 ref.get\n    let runTac? : TermElabM (Option Expr) :=\n      try\n        /- We must only save messages and info tree changes. Recall that `simp` uses temporary metavariables (`withNewMCtxDepth`).\n           So, we must not save references to them at `Term.State`. -/\n        withoutModifyingStateWithInfoAndMessages do\n          Term.withSynthesize (mayPostpone := false) <| Term.runTactic mvar.mvarId! tacticCode\n          let result \u2190 instantiateMVars mvar\n          if result.hasExprMVar then\n            return none\n          else\n            return some result\n      catch _ =>\n        return none\n    let (result?, s) \u2190 liftM (m := MetaM) <| Term.TermElabM.run runTac? ctx s\n    ref.set s\n    return result?\n  return (ref, disch)\n\ninductive Simp.DischargeWrapper where\n  | default\n  | custom (ref : IO.Ref Term.State) (discharge : Simp.Discharge)\n\ndef Simp.DischargeWrapper.with (w : Simp.DischargeWrapper) (x : Option Simp.Discharge \u2192 TacticM \u03b1) : TacticM \u03b1 := do\n  match w with\n  | default => x none\n  | custom ref d =>\n    ref.set (\u2190 getThe Term.State)\n    try\n      x d\n    finally\n      set (\u2190 ref.get)\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) \u2190 tacticToDischarge optDischargeSyntax[0][3]\n    return Simp.DischargeWrapper.custom ref d\n\n/-\n  `optConfig` is of the form `(\"(\" \"config\" \":=\" term \")\")?`\n  If `ctx == false`, the argument is assumed to have type `Meta.Simp.Config`, and `Meta.Simp.ConfigCtx` otherwise. -/\ndef elabSimpConfig (optConfig : Syntax) (ctx : Bool) : TermElabM Meta.Simp.Config := do\n  if ctx then\n    return (\u2190 elabSimpConfigCtxCore optConfig).toConfig\n  else\n    elabSimpConfigCore optConfig\n\nprivate def addDeclToUnfoldOrTheorem (thms : Meta.SimpTheorems) (e : Expr) (post : Bool) (inv : Bool) : MetaM Meta.SimpTheorems := do\n  if e.isConst then\n    let declName := e.constName!\n    let info \u2190 getConstInfo declName\n    if (\u2190 isProp info.type) then\n      thms.addConst declName (post := post) (inv := inv)\n    else\n      if inv then\n        throwError \"invalid '\u2190' modifier, '{declName}' is a declaration name to be unfolded\"\n      thms.addDeclToUnfold declName\n  else\n    thms.add #[] e (post := post) (inv := inv)\n\nprivate def addSimpTheorem (thms : Meta.SimpTheorems) (stx : Syntax) (post : Bool) (inv : Bool) : TermElabM Meta.SimpTheorems := do\n  let (levelParams, proof) \u2190 Term.withoutModifyingElabMetaStateWithInfo <| withRef stx <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx none\n    Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)\n    let e \u2190 instantiateMVars e\n    let e := e.eta\n    if e.hasMVar then\n      let r \u2190 abstractMVars e\n      return (r.paramNames, r.expr)\n    else\n      return (#[], e)\n  thms.add levelParams proof (post := post) (inv := inv)\n\nstructure ElabSimpArgsResult where\n  ctx     : Simp.Context\n  starArg : Bool := false\n\n/--\n  Elaborate extra simp theorems provided to `simp`. `stx` is of the `simpTheorem,*`\n  If `eraseLocal == true`, then we consider local declarations when resolving names for erased theorems (`- 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 := \"\u2193\"\n    syntax simpPost := \"\u2191\"\n    syntax simpLemma := (simpPre <|> simpPost)? term\n\n    syntax simpErase := \"-\" ident\n    -/\n    withMainContext do\n      let mut thms    := ctx.simpTheorems\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 && (\u2190 Term.isLocalIdent? arg[1]).isSome then\n            -- We use `eraseCore` because the simp theorem for the hypothesis was not added yet\n            thms := thms.eraseCore arg[1].getId\n          else\n            let declName \u2190 resolveGlobalConstNoOverloadWithInfo arg[1]\n            thms \u2190 thms.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 (\u2190 resolveSimpIdTheorem? term) with\n          | some e => thms \u2190 addDeclToUnfoldOrTheorem thms e post inv\n          | _      => thms \u2190 addSimpTheorem thms 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 simpTheorems := thms }, starArg }\nwhere\n  resolveSimpIdTheorem? (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\n-- TODO: move?\nprivate def getPropHyps : MetaM (Array FVarId) := do\n  let mut result := #[]\n  for localDecl in (\u2190 getLCtx) do\n    unless localDecl.isAuxDecl do\n      if (\u2190 isProp localDecl.type) then\n        result := result.push localDecl.fvarId\n  return result\n\nstructure MkSimpContextResult where\n  ctx              : Simp.Context\n  dischargeWrapper : Simp.DischargeWrapper\n  fvarIdToLemmaId  : FVarIdToLemmaId\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 \u2190 mkDischargeWrapper stx[2]\n  let simpOnly := !stx[3].isNone\n  let simpTheorems \u2190\n    if simpOnly then\n      ({} : SimpTheorems).addConst ``eq_self\n    else\n      getSimpTheorems\n  let congrTheorems \u2190 getSimpCongrTheorems\n  let r \u2190 elabSimpArgs stx[4] (eraseLocal := eraseLocal) {\n    config      := (\u2190 elabSimpConfig stx[1] (ctx := ctx))\n    simpTheorems, congrTheorems\n  }\n  if !r.starArg || ignoreStarArg then\n    return { r with fvarIdToLemmaId := {}, dischargeWrapper }\n  else\n    let ctx := r.ctx\n    let erased := ctx.simpTheorems.erased\n    let hs \u2190 getPropHyps\n    let mut ctx := ctx\n    let mut fvarIdToLemmaId := {}\n    for h in hs do\n      let localDecl \u2190 getLocalDecl h\n      unless erased.contains localDecl.userName do\n        let fvarId := localDecl.fvarId\n        let proof  := localDecl.toExpr\n        let id     \u2190 mkFreshUserName `h\n        fvarIdToLemmaId := fvarIdToLemmaId.insert fvarId id\n        let simpTheorems \u2190 ctx.simpTheorems.add #[] proof (name? := id)\n        ctx := { ctx with simpTheorems }\n    return { ctx, fvarIdToLemmaId, dischargeWrapper }\n\n/--\n`simpLocation ctx discharge? varIdToLemmaId loc`\nruns the simplifier at locations specified by `loc`,\nusing the simp theorems collected in `ctx`\noptionally running a discharger specified in `discharge?` on generated subgoals.\n(Local hypotheses which have been added to the simp theorems must be recorded in\n`fvarIdToLemmaId`.)\n\nIts primary use is as the implementation of the\n`simp [...] at ...` and `simp only [...] at ...` syntaxes,\nbut can also be used by other tactics when a `Syntax` is not available.\n\nFor many tactics other than the simplifier,\none should use the `withLocation` tactic combinator\nwhen working with a `location`.\n-/\ndef simpLocation (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (fvarIdToLemmaId : FVarIdToLemmaId := {}) (loc : Location) : TacticM Unit := do\n  match loc with\n  | Location.targets hyps simplifyTarget =>\n    withMainContext do\n      let fvarIds \u2190 getFVarIds hyps\n      go fvarIds simplifyTarget fvarIdToLemmaId\n  | Location.wildcard =>\n    withMainContext do\n      go (\u2190 getNondepPropHyps (\u2190 getMainGoal)) (simplifyTarget := true) fvarIdToLemmaId\nwhere\n  go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) (fvarIdToLemmaId : Lean.Meta.FVarIdToLemmaId) : TacticM Unit := do\n    let mvarId \u2190 getMainGoal\n    let result? \u2190 simpGoal mvarId ctx (simplifyTarget := simplifyTarget) (discharge? := discharge?) (fvarIdsToSimp := fvarIdsToSimp) (fvarIdToLemmaId := fvarIdToLemmaId)\n    match result? with\n    | none => replaceMainGoal []\n    | some (_, mvarId) => replaceMainGoal [mvarId]\n\n/-\n  \"simp \" (config)? (discharger)? (\"only \")? (\"[\" simpLemma,* \"]\")? (location)?\n-/\n@[builtinTactic Lean.Parser.Tactic.simp] def evalSimp : Tactic := fun stx => do\n  let { ctx, fvarIdToLemmaId, dischargeWrapper } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false)\n  dischargeWrapper.with fun discharge? =>\n    simpLocation ctx discharge? fvarIdToLemmaId (expandOptLocation stx[5])\n\n@[builtinTactic Lean.Parser.Tactic.simpAll] def evalSimpAll : Tactic := fun stx => do\n  let { ctx, .. } \u2190 mkSimpContext stx (eraseLocal := true) (ctx := true) (ignoreStarArg := true)\n  match (\u2190 simpAll (\u2190 getMainGoal) ctx) with\n  | none => replaceMainGoal []\n  | some mvarId => replaceMainGoal [mvarId]\n\nend Lean.Elab.Tactic\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/Elab/Tactic/Simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.03963883910097002, "lm_q1q2_score": 0.014102503760151536}}
{"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 \u2192 list (expr elab) \u2192 list (expr elab) \u2192 mono_function\n | assoc : expr elab \u2192 option (expr elab) \u2192 option (expr elab) \u2192 mono_function\n | assoc_comm : expr elab \u2192 expr elab \u2192 mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function \u2192 tactic format\n | (mono_function.non_assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 mmap pp xs,\n  ys' \u2190 mmap pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 pp xs,\n  ys' \u2190 pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 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 \u2192 expr \u2192 expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr \u2192 expr \u2192 expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn  \u2190 pp ctx.function,\n   l   \u2190 pp ctx.left,\n   r   \u2190 pp ctx.right,\n   rel \u2190 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 \u2190 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 \u2192 expr \u2192 expr \u2192 tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) \u2190 return t | failed,\n   v \u2190 mk_meta_var d,\n   match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr \u2192 tactic expr\n| (expr.pi n _ t b) :=\ndo v \u2190 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 \u2192 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 \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 list expr)\n | es (x :: xs) := do\n    es' \u2190 delete_expr x es,\n    match es' with\n     | (some es') := do\n       (c,l,r) \u2190 match_ac' es' xs, return (x::c,l,r)\n     | none := do\n       (c,l,r) \u2190 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 \u00d7 list expr \u00d7 list expr) :=\ndo (s',l',r') \u2190 match_ac' l r,\n   s' \u2190 mmap instantiate_mvars s',\n   l' \u2190 mmap instantiate_mvars l',\n   r' \u2190 mmap instantiate_mvars r',\n   return (s',l',r')\n\nmeta def match_prefix\n: list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 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) \u2190 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 \u00d7 list expr \u00d7 list expr \u00d7 list expr) :=\ndo (pre,l\u2081,r\u2081) \u2190 match_prefix l r,\n   (suf,l\u2082,r\u2082) \u2190 match_prefix (reverse l\u2081) (reverse r\u2081),\n   return (pre,reverse l\u2082,reverse r\u2082,reverse suf)\n\nmeta def check_ac : expr \u2192 tactic (bool \u00d7 bool \u00d7 option (expr \u00d7 expr \u00d7 expr) \u00d7 expr)\n | (expr.app (expr.app f x) y) :=\n   do t \u2190 infer_type x,\n      a \u2190 try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n      c \u2190 try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n      i \u2190 try_core (do\n          v \u2190 mk_meta_var t,\n          l_inst_p \u2190 to_expr ``(is_left_id %%t %%f %%v),\n          r_inst_p \u2190 to_expr ``(is_right_id %%t %%f %%v),\n          l_v \u2190 mk_meta_var l_inst_p,\n          r_v \u2190 mk_meta_var r_inst_p ,\n          l_id \u2190 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 \u2190 mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n          mk_instance r_inst_p >>= unify r_v,\n          v' \u2190 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 \u2192 tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) \u2190 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 \u2192 tactic (list expr) :=\nmap dlist.to_list \u2218 parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) : option (expr \u00d7 expr \u00d7 expr) \u2192 list expr \u2192 option (expr \u00d7 list expr)\n| _ (x::xs) := some (foldl (expr.app \u2218 expr.app op) x xs, [])\n| none []   := none\n| (some (l_id,r_id,x\u2080)) [] := some (x\u2080,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr \u2192 option expr\n| (x::xs) := some $ foldl (expr.app \u2218 expr.app op) x xs\n| []   := none\n\nmeta def same_function_aux\n: list expr \u2192 list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr)\n | xs\u2080 xs\u2081 (expr.app f\u2080 a\u2080) (expr.app f\u2081 a\u2081) :=\n   same_function_aux (a\u2080 :: xs\u2080) (a\u2081 :: xs\u2081) f\u2080 f\u2081\n | xs\u2080 xs\u2081 e\u2080 e\u2081 := is_def_eq e\u2080 e\u2081 >> return (e\u2080,xs\u2080,xs\u2081)\n\nmeta def same_function : expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr \u00d7 expr \u00d7 list expr \u00d7 mono_function) :=\ndo (full_f,ls,rs) \u2190 same_function l r,\n   (a,c,i,f) \u2190 check_ac l,\n   if a\n   then if c\n   then do\n     (s,ls,rs) \u2190 monad.join (match_ac\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 fold_assoc f i rs,\n     s' \u2190 fold_assoc1 f s,\n     return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n   else do -- a \u2227 \u00ac c\n     (pre,ls,rs,suff) \u2190 monad.join (match_assoc\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 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 -- \u00ac a\n     (xs\u2080,x\u2080,x\u2081,xs\u2081) \u2190 find_one_difference opt ls rs,\n     return (x\u2080,x\u2081,[],mono_function.non_assoc full_f xs\u2080 xs\u2081)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' \u2190 to_expr l,\n   r' \u2190 to_expr r,\n   parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr \u2192 tactic (expr \u00d7 expr \u00d7 list expr \u00d7 ac_mono_ctx)\n | `(%%e\u2080 \u2192 %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) \u2192 (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080 = %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) = (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080) e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     return (e\u2080, e\u2081, id_rs,\n            { function := f\n            , left := l, right := r\n            , to_rel := expr.app \u2218 expr.app rel\n            , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr)  : option expr \u2192 expr \u2192 expr\n| none e := e\n| (some e\u2080) e\u2081 := f.mk_app [e\u2080,e\u2081]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr \u2192 option expr \u2192 expr\n| e none := e\n| e\u2080 (some e\u2081) := f.mk_app [e\u2080,e\u2081]\n\nmeta def mk_fun_app : mono_function \u2192 expr \u2192 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\u2080,r\u2080) (r\u2081,l\u2081)` gives first how to find rules to prove\n      x+(y\u2080+z) R x+(y\u2081+z);\n      if that fails, helps prove (x+y\u2080)+z R (x+y\u2081)+z -/\n | assoc : expr \u00d7 expr \u2192 expr \u00d7 expr \u2192 mono_law\n   /- `congr r` gives the rule to prove `x = y \u2192 f x = f y` -/\n | congr : expr \u2192 mono_law\n | other : expr \u2192 mono_law\n\nmeta def mono_law.to_tactic_format : mono_law \u2192 tactic format\n | (mono_law.other e) := do e \u2190 pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e \u2190 pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\ndo x\u2080 \u2190 pp x\u2080,\n   x\u2081 \u2190 pp x\u2081,\n   y\u2080 \u2190 pp y\u2080,\n   y\u2081 \u2190 pp y\u2081,\n   return format!\"assoc {x\u2080}; {x\u2081} | {y\u2080}; {y\u2081}\"\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 \u2192 expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs\u2080 xs\u2081 : list expr) (l r : expr) : tactic expr :=\ndo p \u2190 mk_app `eq [fn.mk_app $ xs\u2080 ++ l :: xs\u2081,fn.mk_app $ xs\u2080 ++ r :: xs\u2081],\n   prod.snd <$> solve_aux p\n     (do iterate_exactly (xs\u2081.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\u2080 x\u2081) :=\n    if (x\u2080 <|> x\u2081).is_some\n       then mk_congr_args f x\u2080.to_monad x\u2081.to_monad ctx.left ctx.right\n       else failed\n | (mono_function.assoc_comm f x\u2080) := mk_congr_args f [x\u2080] [] ctx.left ctx.right\n | (mono_function.non_assoc f x\u2080 x\u2081) := mk_congr_args f x\u2080 x\u2081 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 (\u03bb i, bin_op f x (bin_op f i y))\n       , mk_rel ctx (\u03bb i, bin_op f i y))\n       ( mk_rel ctx (\u03bb i, bin_op f (bin_op f x i) y)\n       , mk_rel ctx (\u03bb i, bin_op f x i))\n    | (mono_function.assoc f (some x) none) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb e, mk_fun_app ctx.function e)\n    | (mono_function.assoc f none (some y)) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb 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 (\u03bb 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' \u2190 mk_const r,\n    t  \u2190 infer_type r',\n    t  \u2190 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 \u2192 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\u2080 x\u2081 : expr) : tactic (list expr) :=\ndo x' \u2190 to_expr ``(%%x\u2081 \u2192 %%x\u2080),\n   r\u2080 \u2190 find_lemma x' ls,\n   r\u2081 \u2190 find_lemma x\u2081 ls,\n   return (expr.app <$> r\u2080 <*> r\u2081)\n\nmeta def find_rule (ls : list name) : mono_law \u2192 tactic (list expr)\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\n(match_chaining_rules ls x\u2080 x\u2081)\n<|> (match_chaining_rules ls y\u2080 y\u2081)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x y : \u03b1}\n  (x' y' : \u03b1)\n  (h : R x y)\n  (hx : x = x')\n  (hy : y = y')\n: R x' y' :=\nby { rw [\u2190 hx,\u2190 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 \u2190 pp e,\n   asm \u2190 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 \u2190 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 \u00d7 expr) :=\ndo tgt \u2190 target,\n   t \u2190 infer_type v,\n   tgt' \u2190 do {\n     \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize v x >> target),\n     to_expr ``(\u03bb y : %%t, \u03a0 x, y = x \u2192 %%(tgt'.binding_body.lift_vars 0 1))\n     } <|> to_expr ``(\u03bb y : %%t, \u03a0 x, %%v = x \u2192 %%tgt),\n   t \u2190 head_beta (tgt' v) >>= assert h,\n   swap,\n   r \u2190 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 \u2192 tactic unit) : tactic unit :=\nfocus1 $\ndo tgt \u2190 target >>= instantiate_mvars,\n   tactic.change tgt,\n   ctx \u2190 local_context,\n   let vs := tgt.list_meta_vars,\n   vs' \u2190 mmap (\u03bb v,\n             do h \u2190 get_unused_name `h,\n                x \u2190 get_unused_name `x,\n                prod.snd <$> monotonicity.generalize' h v x) vs,\n     tac ctx;\n     vs'.mmap' (try \u2218 tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ \u03bb _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   set_goals [v],\n   target >>= instantiate_mvars >>= tactic.change,\n   tac, done,\n   set_goals $ gs\n\ndef list.minimum_on {\u03b1 \u03b2} [linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : list \u03b1 \u2192 list \u03b1\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (\u03bb \u27e8k,a\u27e9 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 {\u03b2} (xs : list expr) (tac : expr \u2192 tactic \u03b2) : tactic unit :=\ndo t \u2190 target,\n   xs \u2190 xs.mmap (\u03bb 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 \u2218 prod.fst \u2218 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 \u2190 r.mmap (\u03bb \u27e8l,gs,_\u27e9,\n          do ts \u2190 gs.mmap infer_type,\n             msg \u2190 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 \u2190 target >>= instantiate_mvars,\n   ns \u2190 get_monotonicity_lemmas t dir,\n   asms \u2190 local_context,\n   rs \u2190 find_lemma asms t ns,\n   focus1 $ () <$ best_match rs (\u03bb law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (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 \u2190 hyps.mmap (\u03bb p, to_expr p >>= mk_meta_var),\n   hyps.mmap' (\u03bb pr, do h \u2190 get_unused_name `h, note h none pr),\n   when (\u00ac 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 \u2190 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 \u227c f y` into `x \u2264 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 $ \u03bb asms,\ndo try `[simp only [sub_eq_add_neg]],\n   tgt \u2190 target >>= instantiate_mvars,\n   (l,r,id_rs,g) \u2190 ac_monotonicity_goal cfg tgt\n             <|> fail \"monotonic context not found\",\n   ns \u2190 get_monotonicity_lemmas tgt both,\n   p \u2190 mk_pattern g,\n   rules \u2190 find_rule asms ns p <|> fail \"no applicable rules found\",\n   when (rules = []) (fail \"no applicable rules found\"),\n   err \u2190 format.join <$> mmap side_conditions rules,\n   focus1 $ best_match rules (\u03bb rule, do\n     t\u2080 \u2190 mk_meta_var `(Prop),\n     v\u2080 \u2190 mk_meta_var t\u2080,\n     t\u2081 \u2190 mk_meta_var `(Prop),\n     v\u2081 \u2190 mk_meta_var t\u2081,\n     tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v\u2080 %%v\u2081),\n     solve_mvar v\u2080 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     solve_mvar v\u2081 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     n \u2190 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 \u2192 tactic unit \u2192 tactic unit \u2192 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 \u2192 tactic unit \u2192 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 : \u2115) | many\n\nmeta def repeat_or_not : rep_arity \u2192 tactic unit \u2192 option (tactic unit) \u2192 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 \u2295 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 \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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? \u2192\n         opt_param mono_cfg { mono_cfg . } \u2192\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 \u2190 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 (\u2115 \u00d7 \u2115)) (sk : \u2115 \u00d7 \u2115) : boxint\n:=\nlet boxes2d := (bset2d.from_indexes boxes) in\nlet blocks2d := (bset2d.from_indexes blocks) in\nlet subboxes := boxes2d \u2229 avail in\nlet supboxes := (avail \\ blocks2d) \u222a subboxes in\nboxint.generate avail subboxes supboxes sk\n\ndef list.pall {\u03b1 : Type} (P : \u03b1 \u2192 Prop) : list \u03b1 \u2192 Prop\n| [] := true\n| (h::t) := P h \u2227 list.pall t\ndef list.pall_iff {\u03b1 : Type} {P : \u03b1 \u2192 Prop} {l : list \u03b1}\n: list.pall P l \u2194 (\u2200 a : \u03b1, a \u2208 l \u2192 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 {\u03b1 : Type} (l : list \u03b1)\n: l.pall (\u03bb a, a \u2208 l) := list.pall_iff.mpr (\u03bb a H, H)\n\nnamespace deadlocks\n\ntheorem boxint.generate_from_list_valid {avail : bset2d} {boxes blocks : list (\u2115 \u00d7 \u2115)} {sk : \u2115 \u00d7 \u2115}\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:= \u2200 s1 s2 : sokostate, s1 \u2208 as \u2192 s2 \u2208 goal \u2192 s2.reachable avail s1 \u2192 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: (\u2200 as : boxint, as \u2208 new_dls \u2192\n  as.valid avail \u2227 as.disjoint goal \u2227\n  (\u2200 as2 : boxint, as2 \u2208 as.next_states avail \u2192\n  \u2203 dl : boxint, as2.subset_g dl goal \u2227 (dl \u2208 new_dls \u2228 deadlock avail goal dl))\n) \u2192 (\u2200 as : boxint, as \u2208 new_dls \u2192 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 \u27e8Hval, Hdisj, H\u27e9,\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 \u27e8as2, Has2_next, Hin_as2\u27e9,\n      rcases H as2 Has2_next with \u27e8dl, Hdl_sup, Hdl\u27e9,\n      let s2 := sokostate.move avail d s1,\n      have : s2 \u2208 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 \u2227 new_dl.disjoint goal \u2227\n  (\u2200 as2 : boxint, as2 \u2208 new_dl.next_states avail \u2192\n  \u2203 dl : boxint, as2.subset_g dl goal \u2227 deadlock avail goal dl)\n) \u2192 deadlock avail goal new_dl\n:=\nbegin\n  rintros \u27e8Hval, Hdisj, H\u27e9,\n  have : (\u2200 as, as \u2208 [new_dl] \u2192 deadlock avail goal as), {\n    apply new_deadlocks,\n    refine list.pall_iff.mp \u27e8_, trivial\u27e9,\n      refine \u27e8Hval, Hdisj, _\u27e9,\n      intros as2 Has2,\n      rcases H as2 Has2 with \u27e8dl, Hsub, Hdl\u27e9,\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 : \u2115 \u2192 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) \u2190 tactic.target,\n  num_steps \u2190 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 \u00d7 bool)\n:=\n(do\n  `(deadlocks.deadlock %%e0 %%e1 %%e) \u2190 tactic.whnf t reducible,\n  return (e, ff)\n) <|> \n(do\n  `(%%e \u2208 %%e0) \u2190 return t,\n  return (e, tt)\n)\n\nmeta def tactic.deadlocked_step (e : expr) : tactic unit :=\ndo\n  t \u2190 tactic.infer_type e,\n  (dl, is_rep) \u2190 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": "import ProofWidgets.Component.Basic\n\nopen ProofWidgets\nopen Lean Meta Server Elab Tactic\n\n/-- A `MetaM String` continuation, containing both the computation and all monad state. -/\nstructure MetaMStringCont where\n  ci : Elab.ContextInfo\n  lctx : LocalContext\n  -- We can only derive `TypeName` for type constants, so this must be monomorphic.\n  k : MetaM String\n  deriving TypeName\n\nstructure RunnerWidgetProps where\n  /-- A continuation to run and print the results of when the button is clicked. -/\n  k : WithRpcRef MetaMStringCont\n\n-- Make it possible for widgets to receive `RunnerWidgetProps`. Uses the `TypeName` instance.\n#mkrpcenc RunnerWidgetProps\n\n@[server_rpc_method]\ndef runMetaMStringCont : RunnerWidgetProps \u2192 RequestM (RequestTask String)\n  | {k := \u27e8{ci, lctx, k}\u27e9} => RequestM.asTask do\n    ci.runMetaM lctx k\n\n@[widget_module]\ndef runnerWidget : Component RunnerWidgetProps where\n  javascript := \"\n    import { RpcContext, mapRpcError } from '@leanprover/infoview'\n    import * as React from 'react';\n    const e = React.createElement;\n\n    export default function(props) {\n      const [contents, setContents] = React.useState('Run!')\n      const rs = React.useContext(RpcContext)\n      return e('button', { onClick: () => {\n        setContents('Running..')\n        rs.call('runMetaMStringCont', props)\n          .then(setContents)\n          .catch(e => { setContents(mapRpcError(e).message) })\n      }}, contents)\n    }\n  \"\n\nsyntax (name := makeRunnerTac) \"make_runner\" : tactic\n\n@[tactic makeRunnerTac] def makeRunner : Tactic\n  | `(tactic| make_runner%$tk) => do\n    let x : MetaM String := do\n      return \"Hello, world!\"\n    -- Store the continuation and monad context.\n    let props : RunnerWidgetProps := {\n      k := \u27e8{\n        ci := (\u2190 ContextInfo.save)\n        lctx := (\u2190 getLCtx)\n        k := x\n      }\u27e9}\n    -- Save a widget together with a pointer to `props`.\n    savePanelWidgetInfo tk ``runnerWidget (rpcEncode props)\n  | _ => throwUnsupportedSyntax\n\nexample : True := by\n  make_runner\n  trivial\n", "meta": {"author": "EdAyers", "repo": "ProofWidgets4", "sha": "c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e", "save_path": "github-repos/lean/EdAyers-ProofWidgets4", "path": "github-repos/lean/EdAyers-ProofWidgets4/ProofWidgets4-c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e/ProofWidgets/Demos/LazyComputation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3007455664065234, "lm_q2_score": 0.046724954145958314, "lm_q1q2_score": 0.014052322799945066}}
{"text": "import Runtime.Reaction.Monad\n\n/-\nThis file contains a variety of trivial lemmas about the monadic operations defined for `ReactionT`.\n-/\n\nnamespace ReactionT\n\n/--\nThis macro should be used by LF-users to prove theorems about reactions. It makes it possible to\nwrite `input -[ReactorName.ReactionN]\u2192 output` to express that running reaction number N of reactor\n(class) `ReactorName` on a given `input` produces `output`.\n-/\nmacro input:term:max \" -[\" rcn:ident \"]\u2192 \" output:term:max : term => `(\n  ($(Lean.mkIdentFrom rcn <| `LF ++ rcn.getId ++ `body) $input).fst = $output\n)\n\n-- TODO: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/Conditional.20Syntax/near/311857316\nopen Lean in\nmacro \"mk_get_lemmas\" op:ident field:ident var:\"_\"? : command => do\n  let var := if var.isSome then #[mkIdent `var] else #[]\n  let input := mkIdent `input\n  let opApp \u2190 `($op $[ $var ]* $input (m := Id)\n    (\u03c3PS := $(mkIdent `\u03c3PS)) (\u03c3PE := $(mkIdent `\u03c3PE))\n    (\u03c3AS := $(mkIdent `\u03c3AS)) (\u03c3AE := $(mkIdent `\u03c3AE))\n    (\u03c3S  := $(mkIdent  `\u03c3S)) (\u03c3P  := $(mkIdent  `\u03c3P))\n  )\n  let lemmas := #[\n    (\"value\",         \u2190 `(($opApp).snd = $input.$field $[ $var ]*)),\n    (\"state\",         \u2190 `(($opApp).fst.state = $(input).state)),\n    (\"ports\",         \u2190 `(($opApp).fst.ports.isEmpty)),\n    (\"events\",        \u2190 `(($opApp).fst.events.isEmpty)),\n    (\"stopRequested\", \u2190 `(($opApp).fst.stopRequested = false)),\n    (\"writtenPorts\",  \u2190 `(($opApp).fst.writtenPorts.isEmpty))\n  ]\n  let commands \u2190 lemmas.mapM fun \u27e8suffix, property\u27e9 => `(\n    @[simp] theorem $(mkIdentFrom op s!\"{op.getId}_{suffix}\") {$[ $var ]*} : $property := rfl\n  )\n  return \u27e8mkNullNode commands\u27e9\n\nopen Lean in\nmacro \"mk_set_lemma\" op:ident suffix:ident \" : \" prop:term : command => `(\n  @[simp] theorem $(mkIdentFrom op s!\"{op.getId}_{suffix.getId}\") : $prop := by\n    simp [$op:ident]; first | done | rfl | intro h; simp [h]\n)\n\nmk_get_lemmas getInput       ports   _\nmk_get_lemmas getState       state   _\nmk_get_lemmas getAction      actions _\nmk_get_lemmas getParam       params  _\nmk_get_lemmas getTag         tag\nmk_get_lemmas getLogicalTime time\n\nmk_set_lemma setOutput state : (setOutput (m := Id) (\u03c3AE := \u03c3AE) var val input).fst.state = input.state\nmk_set_lemma setOutput same_port : (setOutput (m := Id) (\u03c3AE := \u03c3AE) var val input).fst.ports var = val\n\n@[simp] theorem setOutput_other_port {var' var val} : (var' \u2260 var) \u2192\n  (setOutput (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.ports var' = none :=\n  by simp [setOutput]; first | done | rfl | intro h; simp [h]\n\nmk_set_lemma setOutput events : (setOutput (m := Id) (\u03c3AE := \u03c3AE) var val input).fst.events.isEmpty\nmk_set_lemma setOutput stopRequested : (setOutput (m := Id) (\u03c3AE := \u03c3AE) var val input).fst.stopRequested = false\nmk_set_lemma setOutput writtenPorts : (setOutput (m := Id) (\u03c3AE := \u03c3AE) var val input).fst.writtenPorts = #[var]\n\nmk_set_lemma setState same_state : (setState (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.state var = val\n\n@[simp] theorem setState_other_state {var' var val} : (var' \u2260 var) \u2192\n  (setState (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.state var' = input.state var' :=\n  by simp [setState]; first | done | rfl | intro h; simp [h]\n\nmk_set_lemma setState ports : (setState (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.ports.isEmpty\nmk_set_lemma setState events : (setState (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.events.isEmpty\nmk_set_lemma setState stopRequested : (setState (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.stopRequested = false\nmk_set_lemma setState writtenPorts : (setState (m := Id) (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) var val input).fst.writtenPorts.isEmpty\n\n-- TODO: Lemmas for `schedule` and `requestStop`.\n\nend ReactionT\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/Reaction/Lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.04146227019447842, "lm_q1q2_score": 0.014017445621119536}}
{"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\u2081 u\u2082\n\n/-!\nRemark: we can define `mapM`, `mapM\u2082` and `forM` using `Applicative` instead of `Monad`.\nExample:\n```\ndef mapM {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\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 \u2192 Type v} [Monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) (as : List \u03b1) : m (List \u03b2) :=\n  let rec @[specialize] loop\n    | [],      bs => pure bs.reverse\n    | a :: as, bs => do loop as ((\u2190 f a)::bs)\n  loop as []\n\n@[specialize]\ndef mapA {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\n  | []    => pure []\n  | a::as => List.cons <$> f a <*> mapA f as\n\n@[specialize]\nprotected def forM {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type w} (as : List \u03b1) (f : \u03b1 \u2192 m PUnit) : m PUnit :=\n  match as with\n  | []      => pure \u27e8\u27e9\n  | a :: as => do f a; List.forM as f\n\n@[specialize]\ndef forA {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} (as : List \u03b1) (f : \u03b1 \u2192 m PUnit) : m PUnit :=\n  match as with\n  | []      => pure \u27e8\u27e9\n  | a :: as => f a *> forA as f\n\n@[specialize]\ndef filterAuxM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 List \u03b1 \u2192 m (List \u03b1)\n  | [],     acc => pure acc\n  | h :: t, acc => do\n    let b \u2190 f h\n    filterAuxM f t (cond b (h :: acc) acc)\n\n@[inline]\ndef filterM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) (as : List \u03b1) : m (List \u03b1) := do\n  let as \u2190 filterAuxM f as []\n  pure as.reverse\n\n@[inline]\ndef filterRevM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) (as : List \u03b1) : m (List \u03b1) :=\n  filterAuxM f as.reverse []\n\n@[inline]\ndef filterMapM {m : Type u \u2192 Type v} [Monad m] {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 m (Option \u03b2)) (as : List \u03b1) : m (List \u03b2) :=\n  let rec @[specialize] loop\n    | [],     bs => pure bs\n    | a :: as, bs => do\n      match (\u2190 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 \u2192 Type v} [Monad m] {s : Type u} {\u03b1 : Type w} : (f : s \u2192 \u03b1 \u2192 m s) \u2192 (init : s) \u2192 List \u03b1 \u2192 m s\n  | _, s, []      => pure s\n  | f, s, a :: as => do\n    let s' \u2190 f s a\n    List.foldlM f s' as\n\n@[inline]\ndef foldrM {m : Type u \u2192 Type v} [Monad m] {s : Type u} {\u03b1 : Type w} (f : \u03b1 \u2192 s \u2192 m s) (init : s) (l : List \u03b1) : m s :=\n  l.reverse.foldlM (fun s a => f a s) init\n\n@[specialize]\ndef firstM {m : Type u \u2192 Type v} [Alternative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m \u03b2\n  | []    => failure\n  | a::as => f a <|> firstM f as\n\n@[specialize]\ndef anyM {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type v} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m Bool\n  | []    => pure false\n  | a::as => do\n    match (\u2190 f a) with\n    | true  => pure true\n    | false => anyM f as\n\n@[specialize]\ndef allM {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type v} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m Bool\n  | []    => pure true\n  | a::as => do\n    match (\u2190 f a) with\n    | true  => allM f as\n    | false => pure false\n\n@[specialize]\ndef findM? {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type} (p : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m (Option \u03b1)\n  | []    => pure none\n  | a::as => do\n    match (\u2190 p a) with\n    | true  => pure (some a)\n    | false => findM? p as\n\n@[specialize]\ndef findSomeM? {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m (Option \u03b2)) : List \u03b1 \u2192 m (Option \u03b2)\n  | []    => pure none\n  | a::as => do\n    match (\u2190 f a) with\n    | some b => pure (some b)\n    | none   => findSomeM? f as\n\n@[inline] protected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : List \u03b1) (init : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec @[specialize] loop\n    | [], b    => pure b\n    | a::as, b => do\n      match (\u2190 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 \u03b1) \u03b1 where\n  forIn := List.forIn\n\n@[simp] theorem forIn_nil [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) (b : \u03b2) : forIn [] b f = pure b :=\n  rfl\n\n@[simp] theorem forIn_cons [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) (a : \u03b1) (as : List \u03b1) (b : \u03b2)\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' {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : List \u03b1) (init : \u03b2) (f : (a : \u03b1) \u2192 a \u2208 as \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec @[specialize] loop : (as' : List \u03b1) \u2192 (b : \u03b2) \u2192 Exists (fun bs => bs ++ as' = as) \u2192 m \u03b2\n    | [], b, _    => pure b\n    | a::as', b, h => do\n      have : a \u2208 as := by\n        have \u27e8bs, h\u27e9 := h\n        subst h\n        exact mem_append_of_mem_right _ (Mem.head ..)\n      match (\u2190 f a this b) with\n      | ForInStep.done b  => pure b\n      | ForInStep.yield b =>\n        have : Exists (fun bs => bs ++ as' = as) := have \u27e8bs, h\u27e9 := h; \u27e8bs ++ [a], by rw [\u2190 h, append_cons bs a as']\u27e9\n        loop as' b this\n  loop as init \u27e8[], rfl\u27e9\n\ninstance : ForIn' m (List \u03b1) \u03b1 inferInstance where\n  forIn' := List.forIn'\n\n@[simp] theorem forIn'_eq_forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : List \u03b1) (init : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : forIn' as init (fun a _ b => f a b) = forIn as init f := by\n  simp [forIn', forIn, List.forIn, List.forIn']\n  have : \u2200 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 \u03b1) \u03b1 where\n  forM := List.forM\n\n@[simp] theorem forM_nil  [Monad m] (f : \u03b1 \u2192 m PUnit) : forM [] f = pure \u27e8\u27e9 :=\n  rfl\n@[simp] theorem forM_cons [Monad m] (f : \u03b1 \u2192 m PUnit) (a : \u03b1) (as : List \u03b1) : 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 \u2209 calls_p t :=\n  assume t_has_call: prop.has_call_p c t,\n  show \u00abfalse\u00bb, by cases t_has_call\n\nlemma prop.has_call_p.not.inv {c: calltrigger} {P: prop}: c \u2208 calls_p P.not \u2192 c \u2208 calls_n P :=\n  assume not_has_call: c \u2208 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\u2081 P\u2082: prop}: c \u2208 calls_p (P\u2081 \u22c0 P\u2082) \u2192 c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082 :=\n  assume and_has_call: c \u2208 calls_p (P\u2081 \u22c0 P\u2082),\n  begin\n    cases and_has_call,\n    show c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082, from or.inl a,\n    show c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082, from or.inr a\n  end\n\nlemma prop.has_call_p.or.inv {c: calltrigger} {P\u2081 P\u2082: prop}: c \u2208 calls_p (P\u2081 \u22c1 P\u2082) \u2192 c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082 :=\n  assume or_has_call: c \u2208 calls_p (P\u2081 \u22c1 P\u2082),\n  begin\n    cases or_has_call,\n    show c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082, from or.inl a,\n    show c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082, from or.inr a\n  end\n\nlemma prop.has_call_p.pre\u2081.inv {c: calltrigger} {op: unop} {t: term}: c \u2209 calls_p (prop.pre\u2081 op t) :=\n  assume pre_has_call: c \u2208 calls_p (prop.pre\u2081 op t),\n  show \u00abfalse\u00bb, by cases pre_has_call\n\nlemma prop.has_call_p.pre\u2082.inv {c: calltrigger} {op: binop} {t\u2081 t\u2082: term}: c \u2209 calls_p (prop.pre\u2082 op t\u2081 t\u2082) :=\n  assume pre_has_call: c \u2208 calls_p (prop.pre\u2082 op t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_call\n\nlemma prop.has_call_p.pre.inv {c: calltrigger} {t\u2081 t\u2082: term}: c \u2209 calls_p (prop.pre t\u2081 t\u2082) :=\n  assume pre_has_call: c \u2208 calls_p (prop.pre t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_call\n\nlemma prop.has_call_p.post.inv {c: calltrigger} {t\u2081 t\u2082: term}: c \u2209 calls_p (prop.post t\u2081 t\u2082) :=\n  assume post_has_call: c \u2208 calls_p (prop.post t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases post_has_call\n\nlemma prop.has_call_p.call.inv {c: calltrigger} {t: term}:\n      c \u2208 calls_p (prop.call t) \u2192 (c = calltrigger.mk t) :=\n  assume call_has_call: c \u2208 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 \u2209 calls_p (prop.forallc x P) :=\n  assume forall_has_call: c \u2208 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 \u2209 calls_p (prop.exis x P) :=\n  assume exis_has_call: c \u2208 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 \u2209 calls_n t :=\n  assume t_has_call_n: prop.has_call_n c t,\n  show \u00abfalse\u00bb, by cases t_has_call_n\n\nlemma prop.has_call_n.not.inv {c: calltrigger} {P: prop}: c \u2208 calls_n P.not \u2192 c \u2208 calls_p P :=\n  assume not_has_call_n: c \u2208 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\u2081 P\u2082: prop}: c \u2208 calls_n (P\u2081 \u22c0 P\u2082) \u2192 c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082 :=\n  assume and_has_call_n: c \u2208 calls_n (P\u2081 \u22c0 P\u2082),\n  begin\n    cases and_has_call_n,\n    show c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082, from or.inl a,\n    show c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082, from or.inr a\n  end\n\nlemma prop.has_call_n.or.inv {c: calltrigger} {P\u2081 P\u2082: prop}: c \u2208 calls_n (P\u2081 \u22c1 P\u2082) \u2192 c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082 :=\n  assume or_has_call_n: c \u2208 calls_n (P\u2081 \u22c1 P\u2082),\n  begin\n    cases or_has_call_n,\n    show c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082, from or.inl a,\n    show c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082, from or.inr a\n  end\n\nlemma prop.has_call_n.pre\u2081.inv {c: calltrigger} {op: unop} {t: term}: c \u2209 calls_n (prop.pre\u2081 op t) :=\n  assume pre_has_call_n: c \u2208 calls_n (prop.pre\u2081 op t),\n  show \u00abfalse\u00bb, by cases pre_has_call_n\n\nlemma prop.has_call_n.pre\u2082.inv {c: calltrigger} {op: binop} {t\u2081 t\u2082: term}: c \u2209 calls_n (prop.pre\u2082 op t\u2081 t\u2082) :=\n  assume pre_has_call_n: c \u2208 calls_n (prop.pre\u2082 op t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_call_n\n\nlemma prop.has_call_n.pre.inv {c: calltrigger} {t\u2081 t\u2082: term}: c \u2209 calls_n (prop.pre t\u2081 t\u2082) :=\n  assume pre_has_call_n: c \u2208 calls_n (prop.pre t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_call_n\n\nlemma prop.has_call_n.post.inv {c: calltrigger} {t\u2081 t\u2082: term}: c \u2209 calls_n (prop.post t\u2081 t\u2082) :=\n  assume post_has_call_n: c \u2208 calls_n (prop.post t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases post_has_call_n\n\nlemma prop.has_call_n.call.inv {c: calltrigger} {t\u2081 t\u2082: term}: c \u2209 calls_n (prop.call t\u2081 t\u2082) :=\n  assume call_has_call_n: c \u2208 calls_n (prop.call t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases call_has_call_n\n\nlemma prop.has_call_n.forallc.inv {c: calltrigger} {x: var} {t: term} {P: prop}:\n      c \u2209 calls_n (prop.forallc x P) :=\n  assume forall_has_call_n: c \u2208 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 \u2209 calls_n (prop.exis x P) :=\n  assume exis_has_call_n: c \u2208 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 \u2209 quantifiers_p t :=\n  assume t_has_quantifier_p: prop.has_quantifier_p q t,\n  show \u00abfalse\u00bb, by cases t_has_quantifier_p\n\nlemma prop.has_quantifier_p.not.inv {q: callquantifier} {P: prop}: q \u2208 quantifiers_p P.not \u2192 q \u2208 quantifiers_n P :=\n  assume not_has_quantifier_p: q \u2208 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\u2081 P\u2082: prop}:\n      q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082) \u2192 q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082 :=\n  assume and_has_quantifier_p: q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082),\n  begin\n    cases and_has_quantifier_p,\n    show q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082, from or.inl a,\n    show q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082, from or.inr a\n  end\n\nlemma prop.has_quantifier_p.or.inv {q: callquantifier} {P\u2081 P\u2082: prop}:\n      q \u2208 quantifiers_p (P\u2081 \u22c1 P\u2082) \u2192 q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082 :=\n  assume or_has_quantifier_p: q \u2208 quantifiers_p (P\u2081 \u22c1 P\u2082),\n  begin\n    cases or_has_quantifier_p,\n    show q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082, from or.inl a,\n    show q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082, from or.inr a\n  end\n\nlemma prop.has_quantifier_p.pre\u2081.inv {q: callquantifier} {op: unop} {t: term}: q \u2209 quantifiers_p (prop.pre\u2081 op t) :=\n  assume pre_has_quantifier_p: q \u2208 quantifiers_p (prop.pre\u2081 op t),\n  show \u00abfalse\u00bb, by cases pre_has_quantifier_p\n\nlemma prop.has_quantifier_p.pre\u2082.inv {q: callquantifier} {op: binop} {t\u2081 t\u2082: term}: q \u2209 quantifiers_p (prop.pre\u2082 op t\u2081 t\u2082) :=\n  assume pre_has_quantifier_p: q \u2208 quantifiers_p (prop.pre\u2082 op t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_quantifier_p\n\nlemma prop.has_quantifier_p.pre.inv {q: callquantifier} {t\u2081 t\u2082: term}: q \u2209 quantifiers_p (prop.pre t\u2081 t\u2082) :=\n  assume pre_has_quantifier_p: q \u2208 quantifiers_p (prop.pre t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_quantifier_p\n\nlemma prop.has_quantifier_p.post.inv {q: callquantifier} {t\u2081 t\u2082: term}: q \u2209 quantifiers_p (prop.post t\u2081 t\u2082) :=\n  assume post_has_quantifier_p: q \u2208 quantifiers_p (prop.post t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases post_has_quantifier_p\n\nlemma prop.has_quantifier_p.call.inv {q: callquantifier} {t\u2081 t\u2082: term}: q \u2209 quantifiers_p (prop.call t\u2081 t\u2082) :=\n  assume call_has_quantifier_p: q \u2208 quantifiers_p (prop.call t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases call_has_quantifier_p\n\nlemma prop.has_quantifier_p.forallc.inv {q: callquantifier} {x: var} {P: prop}:\n      q \u2208 quantifiers_p (prop.forallc x P) \u2192 (q = \u27e8x, P\u27e9) :=\n  assume forall_has_quantifier_p: q \u2208 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 \u2209 quantifiers_n t :=\n  assume t_has_quantifier_n: prop.has_quantifier_n q t,\n  show \u00abfalse\u00bb, by cases t_has_quantifier_n\n\nlemma prop.has_quantifier_n.not.inv {q: callquantifier} {P: prop}: q \u2208 quantifiers_n P.not \u2192 q \u2208 quantifiers_p P :=\n  assume not_has_quantifier_n: q \u2208 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\u2081 P\u2082: prop}:\n      q \u2208 quantifiers_n (P\u2081 \u22c0 P\u2082) \u2192 q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082 :=\n  assume and_has_quantifier_n: q \u2208 quantifiers_n (P\u2081 \u22c0 P\u2082),\n  begin\n    cases and_has_quantifier_n,\n    show q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082, from or.inl a,\n    show q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082, from or.inr a\n  end\n\nlemma prop.has_quantifier_n.or.inv {q: callquantifier} {P\u2081 P\u2082: prop}:\n      q \u2208 quantifiers_n (P\u2081 \u22c1 P\u2082) \u2192 q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082 :=\n  assume or_has_quantifier_n: q \u2208 quantifiers_n (P\u2081 \u22c1 P\u2082),\n  begin\n    cases or_has_quantifier_n,\n    show q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082, from or.inl a,\n    show q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082, from or.inr a\n  end\n\nlemma prop.has_quantifier_n.pre\u2081.inv {q: callquantifier} {op: unop} {t: term}: q \u2209 quantifiers_n (prop.pre\u2081 op t) :=\n  assume pre_has_quantifier_n: q \u2208 quantifiers_n (prop.pre\u2081 op t),\n  show \u00abfalse\u00bb, by cases pre_has_quantifier_n\n\nlemma prop.has_quantifier_n.pre\u2082.inv {q: callquantifier} {op: binop} {t\u2081 t\u2082: term}: q \u2209 quantifiers_n (prop.pre\u2082 op t\u2081 t\u2082) :=\n  assume pre_has_quantifier_n: q \u2208 quantifiers_n (prop.pre\u2082 op t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_quantifier_n\n\nlemma prop.has_quantifier_n.pre.inv {q: callquantifier} {t\u2081 t\u2082: term}: q \u2209 quantifiers_n (prop.pre t\u2081 t\u2082) :=\n  assume pre_has_quantifier_n: q \u2208 quantifiers_n (prop.pre t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases pre_has_quantifier_n\n\nlemma prop.has_quantifier_n.post.inv {q: callquantifier} {t\u2081 t\u2082: term}: q \u2209 quantifiers_n (prop.post t\u2081 t\u2082) :=\n  assume post_has_quantifier_n: q \u2208 quantifiers_n (prop.post t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases post_has_quantifier_n\n\nlemma prop.has_quantifier_n.call.inv {q: callquantifier} {t\u2081 t\u2082: term}: q \u2209 quantifiers_n (prop.call t\u2081 t\u2082) :=\n  assume call_has_quantifier_n: q \u2208 quantifiers_n (prop.call t\u2081 t\u2082),\n  show \u00abfalse\u00bb, by cases call_has_quantifier_n\n\nlemma prop.has_quantifier_n.forallc.inv {q: callquantifier} {x: var} {P: prop}:\n      q \u2209 quantifiers_n (prop.forallc x P) :=\n  assume forall_has_quantifier_n: q \u2208 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} {\u03c3: env}:\n      c \u2209 calls_p_subst \u03c3 t :=\n  assume : c \u2208 calls_p_subst \u03c3 t,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p t, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p t)\n      (\u03bba, \u00abfalse\u00bb) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p t,\n    show \u00abfalse\u00bb, from prop.has_call_p.term.inv this\n  )\n\nlemma prop.has_call_p_subst.and\u2081 {c: calltrigger} {P\u2081 P\u2082: prop} {\u03c3: env}:\n      c \u2208 calls_p_subst \u03c3 P\u2081 \u2192 c \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082) :=\n  assume : c \u2208 calls_p_subst \u03c3 P\u2081,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p P\u2081, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p P\u2081)\n      (\u03bba, a \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082)) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p P\u2081,\n    have c' \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2081 this,\n    show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082), from set.mem_image this rfl\n  )\n\nlemma prop.has_call_p_subst.and\u2082 {c: calltrigger} {P\u2081 P\u2082: prop} {\u03c3: env}:\n      c \u2208 calls_p_subst \u03c3 P\u2082 \u2192 c \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082) :=\n  assume : c \u2208 calls_p_subst \u03c3 P\u2082,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p P\u2082, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p P\u2082)\n      (\u03bba, a \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082)) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p P\u2082,\n    have c' \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2082 this,\n    show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082), from set.mem_image this rfl\n  )\n\nlemma prop.has_call_p_subst.not {c: calltrigger} {P: prop} {\u03c3: env}:\n      c \u2208 calls_p_subst \u03c3 P \u2192 c \u2208 calls_n_subst \u03c3 P.not :=\n  assume : c \u2208 calls_p_subst \u03c3 P,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p P, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p P)\n      (\u03bba, a \u2208 calls_n_subst \u03c3 P.not) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p P,\n    have c' \u2208 calls_n P.not, from prop.has_call_n.not this,\n    show calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P.not, from set.mem_image this rfl\n  )\n\nlemma prop.has_call_n_subst.term.inv {c: calltrigger} {t: term} {\u03c3: env}:\n      c \u2209 calls_n_subst \u03c3 t :=\n  assume : c \u2208 calls_n_subst \u03c3 t,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_n t, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_n t)\n      (\u03bba, \u00abfalse\u00bb) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_n t,\n    show \u00abfalse\u00bb, from prop.has_call_n.term.inv this\n  )\n\nlemma prop.has_call_n_subst.not {c: calltrigger} {P: prop} {\u03c3: env}:\n      c \u2208 calls_n_subst \u03c3 P \u2192 c \u2208 calls_p_subst \u03c3 P.not :=\n  assume : c \u2208 calls_n_subst \u03c3 P,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_n P, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_n P)\n      (\u03bba, a \u2208 calls_p_subst \u03c3 P.not) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_n P,\n    have c' \u2208 calls_p P.not, from prop.has_call_p.not this,\n    show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P.not, from set.mem_image this rfl\n  )\n\nlemma prop.has_call_p_subst.not.inv {c: calltrigger} {P: prop} {\u03c3: env}:\n      c \u2208 calls_p_subst \u03c3 P.not \u2192 c \u2208 calls_n_subst \u03c3 P :=\n  assume : c \u2208 calls_p_subst \u03c3 P.not,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p P.not, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p P.not)\n      (\u03bba, a \u2208 calls_n_subst \u03c3 P) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p P.not,\n    have c' \u2208 calls_n P, from prop.has_call_p.not.inv this,\n    show calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P, from set.mem_image this rfl\n  )\n\nlemma prop.has_call_n_subst.not.inv {c: calltrigger} {P: prop} {\u03c3: env}:\n      c \u2208 calls_n_subst \u03c3 P.not \u2192 c \u2208 calls_p_subst \u03c3 P :=\n  assume : c \u2208 calls_n_subst \u03c3 P.not,\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_n P.not, from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_n P.not)\n      (\u03bba, a \u2208 calls_p_subst \u03c3 P) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_n P.not,\n    have c' \u2208 calls_p P, from prop.has_call_n.not.inv this,\n    show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P, from set.mem_image this rfl\n  )\n\nlemma prop.has_call_p_subst.and.inv {c: calltrigger} {P\u2081 P\u2082: prop} {\u03c3: env}:\n      c \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082) \u2192 c \u2208 calls_p_subst \u03c3 P\u2081 \u2228 c \u2208 calls_p_subst \u03c3 P\u2082 :=\n  assume : c \u2208 calls_p_subst \u03c3 (P\u2081 \u22c0 P\u2082),\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p (P\u2081 \u22c0 P\u2082), from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p (P\u2081 \u22c0 P\u2082))\n      (\u03bba, a \u2208 calls_p_subst \u03c3 P\u2081 \u2228 a \u2208 calls_p_subst \u03c3 P\u2082) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p (P\u2081 \u22c0 P\u2082),\n    or.elim (prop.has_call_p.and.inv this) (\n      assume : c' \u2208 calls_p P\u2081,\n      have calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2081, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2082, from or.inl this\n    ) (\n      assume : c' \u2208 calls_p P\u2082,\n      have calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2082, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2082, from or.inr this\n    )\n  )\n\nlemma prop.has_call_p_subst.or.inv {c: calltrigger} {P\u2081 P\u2082: prop} {\u03c3: env}:\n      c \u2208 calls_p_subst \u03c3 (P\u2081 \u22c1 P\u2082) \u2192 c \u2208 calls_p_subst \u03c3 P\u2081 \u2228 c \u2208 calls_p_subst \u03c3 P\u2082 :=\n  assume : c \u2208 calls_p_subst \u03c3 (P\u2081 \u22c1 P\u2082),\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_p (P\u2081 \u22c1 P\u2082), from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_p (P\u2081 \u22c1 P\u2082))\n      (\u03bba, a \u2208 calls_p_subst \u03c3 P\u2081 \u2228 a \u2208 calls_p_subst \u03c3 P\u2082) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_p (P\u2081 \u22c1 P\u2082),\n    or.elim (prop.has_call_p.or.inv this) (\n      assume : c' \u2208 calls_p P\u2081,\n      have calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2081, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2082, from or.inl this\n    ) (\n      assume : c' \u2208 calls_p P\u2082,\n      have calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2082, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_p_subst \u03c3 P\u2082, from or.inr this\n    )\n  )\n\nlemma prop.has_call_n_subst.and.inv {c: calltrigger} {P\u2081 P\u2082: prop} {\u03c3: env}:\n      c \u2208 calls_n_subst \u03c3 (P\u2081 \u22c0 P\u2082) \u2192 c \u2208 calls_n_subst \u03c3 P\u2081 \u2228 c \u2208 calls_n_subst \u03c3 P\u2082 :=\n  assume : c \u2208 calls_n_subst \u03c3 (P\u2081 \u22c0 P\u2082),\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_n (P\u2081 \u22c0 P\u2082), from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_n (P\u2081 \u22c0 P\u2082))\n      (\u03bba, a \u2208 calls_n_subst \u03c3 P\u2081 \u2228 a \u2208 calls_n_subst \u03c3 P\u2082) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_n (P\u2081 \u22c0 P\u2082),\n    or.elim (prop.has_call_n.and.inv this) (\n      assume : c' \u2208 calls_n P\u2081,\n      have calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2081, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2082, from or.inl this\n    ) (\n      assume : c' \u2208 calls_n P\u2082,\n      have calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2082, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2082, from or.inr this\n    )\n  )\n\nlemma prop.has_call_n_subst.or.inv {c: calltrigger} {P\u2081 P\u2082: prop} {\u03c3: env}:\n      c \u2208 calls_n_subst \u03c3 (P\u2081 \u22c1 P\u2082) \u2192 c \u2208 calls_n_subst \u03c3 P\u2081 \u2228 c \u2208 calls_n_subst \u03c3 P\u2082 :=\n  assume : c \u2208 calls_n_subst \u03c3 (P\u2081 \u22c1 P\u2082),\n  have c \u2208 (calltrigger.subst \u03c3) '' calls_n (P\u2081 \u22c1 P\u2082), from this,\n  @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst \u03c3) (calls_n (P\u2081 \u22c1 P\u2082))\n      (\u03bba, a \u2208 calls_n_subst \u03c3 P\u2081 \u2228 a \u2208 calls_n_subst \u03c3 P\u2082) c this (\n    assume c': calltrigger,\n    assume : c' \u2208 calls_n (P\u2081 \u22c1 P\u2082),\n    or.elim (prop.has_call_n.or.inv this) (\n      assume : c' \u2208 calls_n P\u2081,\n      have calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2081, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2082, from or.inl this\n    ) (\n      assume : c' \u2208 calls_n P\u2082,\n      have calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2082, from set.mem_image this rfl,\n      show calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2081\n         \u2228 calltrigger.subst \u03c3 c' \u2208 calls_n_subst \u03c3 P\u2082, from or.inr this\n    )\n  )\n\nlemma no_instantiations.term {t: term}: no_instantiations t :=\n  have h1: calls_p t = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p t,\n    show \u00abfalse\u00bb, from prop.has_call_p.term.inv this\n  ),\n  have h2: calls_n t = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n t,\n    show \u00abfalse\u00bb, from prop.has_call_n.term.inv this\n  ),\n  have h3: quantifiers_p t = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p t,\n    show \u00abfalse\u00bb, from prop.has_quantifier_p.term.inv  this\n  ),\n  have h4: quantifiers_n t = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n t,\n    show \u00abfalse\u00bb, from prop.has_quantifier_n.term.inv  this\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.not {P: prop}: no_instantiations P \u2192 no_instantiations P.not :=\n  assume \u27e8no_calls_p_in_P, \u27e8no_calls_n_in_P, \u27e8no_quantifiers_p_in_P, no_quantifiers_n_in_P\u27e9\u27e9\u27e9,\n  have h1: calls_p P.not = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p P.not,\n    have c_in_calls_p_P: c \u2208 calls_n P, from prop.has_call_p.not.inv this,\n    have c_not_in_calls_p_P: c \u2209 calls_n P, from set.forall_not_mem_of_eq_empty no_calls_n_in_P c,\n    show \u00abfalse\u00bb, from c_not_in_calls_p_P c_in_calls_p_P\n  ),\n  have h2: calls_n P.not = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n P.not,\n    have c_in_calls_p_P: c \u2208 calls_p P, from prop.has_call_n.not.inv this,\n    have c_not_in_calls_p_P: c \u2209 calls_p P, from set.forall_not_mem_of_eq_empty no_calls_p_in_P c,\n    show \u00abfalse\u00bb, from c_not_in_calls_p_P c_in_calls_p_P\n  ),\n  have h3: quantifiers_p P.not = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p P.not,\n    have c_in_quantifiers_p_P: q \u2208 quantifiers_n P, from prop.has_quantifier_p.not.inv this,\n    have c_not_in_quantifiers_p_P: q \u2209 quantifiers_n P, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P q,\n    show \u00abfalse\u00bb, from c_not_in_quantifiers_p_P c_in_quantifiers_p_P\n  ),\n  have h4: quantifiers_n P.not = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n P.not,\n    have c_in_quantifiers_p_P: q \u2208 quantifiers_p P, from prop.has_quantifier_n.not.inv this,\n    have c_not_in_quantifiers_p_P: q \u2209 quantifiers_p P, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P q,\n    show \u00abfalse\u00bb, from c_not_in_quantifiers_p_P c_in_quantifiers_p_P\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.and {P\u2081 P\u2082: prop}:\n      no_instantiations P\u2081 \u2192 no_instantiations P\u2082 \u2192 no_instantiations (prop.and P\u2081 P\u2082) :=\n  assume \u27e8no_calls_p_in_P\u2081, \u27e8no_calls_n_in_P\u2081, \u27e8no_quantifiers_p_in_P\u2081, no_quantifiers_n_in_P\u2081\u27e9\u27e9\u27e9,\n  assume \u27e8no_calls_p_in_P\u2082, \u27e8no_calls_n_in_P\u2082, \u27e8no_quantifiers_p_in_P\u2082, no_quantifiers_n_in_P\u2082\u27e9\u27e9\u27e9,\n  have h1: calls_p (P\u2081 \u22c0 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (P\u2081 \u22c0 P\u2082),\n    have c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082, from prop.has_call_p.and.inv this,\n    or.elim this (\n      assume c_in_calls_p_P\u2081: c \u2208 calls_p P\u2081,\n      have c_not_in_calls_p_P\u2081: c \u2209 calls_p P\u2081, from set.forall_not_mem_of_eq_empty no_calls_p_in_P\u2081 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2081 c_in_calls_p_P\u2081\n    ) (\n      assume c_in_calls_p_P\u2082: c \u2208 calls_p P\u2082,\n      have c_not_in_calls_p_P\u2082: c \u2209 calls_p P\u2082, from set.forall_not_mem_of_eq_empty no_calls_p_in_P\u2082 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2082 c_in_calls_p_P\u2082\n    )\n  ),\n  have h2: calls_n (P\u2081 \u22c0 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n (P\u2081 \u22c0 P\u2082),\n    have c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082, from prop.has_call_n.and.inv this,\n    or.elim this (\n      assume c_in_calls_p_P\u2081: c \u2208 calls_n P\u2081,\n      have c_not_in_calls_p_P\u2081: c \u2209 calls_n P\u2081, from set.forall_not_mem_of_eq_empty no_calls_n_in_P\u2081 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2081 c_in_calls_p_P\u2081\n    ) (\n      assume c_in_calls_p_P\u2082: c \u2208 calls_n P\u2082,\n      have c_not_in_calls_p_P\u2082: c \u2209 calls_n P\u2082, from set.forall_not_mem_of_eq_empty no_calls_n_in_P\u2082 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2082 c_in_calls_p_P\u2082\n    )\n  ),\n  have h3: quantifiers_p (P\u2081 \u22c0 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082),\n    have q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082, from prop.has_quantifier_p.and.inv this,\n    or.elim this (\n      assume q_in_quantifiers_p_P\u2081: q \u2208 quantifiers_p P\u2081,\n      have q_not_in_quantifiers_p_P\u2081: q \u2209 quantifiers_p P\u2081, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P\u2081 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2081 q_in_quantifiers_p_P\u2081\n    ) (\n      assume q_in_quantifiers_p_P\u2082: q \u2208 quantifiers_p P\u2082,\n      have q_not_in_quantifiers_p_P\u2082: q \u2209 quantifiers_p P\u2082, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P\u2082 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2082 q_in_quantifiers_p_P\u2082\n    )\n  ),\n  have h4: quantifiers_n (P\u2081 \u22c0 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n (P\u2081 \u22c0 P\u2082),\n    have q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082, from prop.has_quantifier_n.and.inv this,\n    or.elim this (\n      assume q_in_quantifiers_p_P\u2081: q \u2208 quantifiers_n P\u2081,\n      have q_not_in_quantifiers_p_P\u2081: q \u2209 quantifiers_n P\u2081, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P\u2081 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2081 q_in_quantifiers_p_P\u2081\n    ) (\n      assume q_in_quantifiers_p_P\u2082: q \u2208 quantifiers_n P\u2082,\n      have q_not_in_quantifiers_p_P\u2082: q \u2209 quantifiers_n P\u2082, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P\u2082 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2082 q_in_quantifiers_p_P\u2082\n    )\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.or {P\u2081 P\u2082: prop}:\n      no_instantiations P\u2081 \u2192 no_instantiations P\u2082 \u2192 no_instantiations (prop.or P\u2081 P\u2082) :=\n  assume \u27e8no_calls_p_in_P\u2081, \u27e8no_calls_n_in_P\u2081, \u27e8no_quantifiers_p_in_P\u2081, no_quantifiers_n_in_P\u2081\u27e9\u27e9\u27e9,\n  assume \u27e8no_calls_p_in_P\u2082, \u27e8no_calls_n_in_P\u2082, \u27e8no_quantifiers_p_in_P\u2082, no_quantifiers_n_in_P\u2082\u27e9\u27e9\u27e9,\n  have h1: calls_p (P\u2081 \u22c1 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (P\u2081 \u22c1 P\u2082),\n    have c \u2208 calls_p P\u2081 \u2228 c \u2208 calls_p P\u2082, from prop.has_call_p.or.inv this,\n    or.elim this (\n      assume c_in_calls_p_P\u2081: c \u2208 calls_p P\u2081,\n      have c_not_in_calls_p_P\u2081: c \u2209 calls_p P\u2081, from set.forall_not_mem_of_eq_empty no_calls_p_in_P\u2081 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2081 c_in_calls_p_P\u2081\n    ) (\n      assume c_in_calls_p_P\u2082: c \u2208 calls_p P\u2082,\n      have c_not_in_calls_p_P\u2082: c \u2209 calls_p P\u2082, from set.forall_not_mem_of_eq_empty no_calls_p_in_P\u2082 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2082 c_in_calls_p_P\u2082\n    )\n  ),\n  have h2: calls_n (P\u2081 \u22c1 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n (P\u2081 \u22c1 P\u2082),\n    have c \u2208 calls_n P\u2081 \u2228 c \u2208 calls_n P\u2082, from prop.has_call_n.or.inv this,\n    or.elim this (\n      assume c_in_calls_p_P\u2081: c \u2208 calls_n P\u2081,\n      have c_not_in_calls_p_P\u2081: c \u2209 calls_n P\u2081, from set.forall_not_mem_of_eq_empty no_calls_n_in_P\u2081 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2081 c_in_calls_p_P\u2081\n    ) (\n      assume c_in_calls_p_P\u2082: c \u2208 calls_n P\u2082,\n      have c_not_in_calls_p_P\u2082: c \u2209 calls_n P\u2082, from set.forall_not_mem_of_eq_empty no_calls_n_in_P\u2082 c,\n      show \u00abfalse\u00bb, from c_not_in_calls_p_P\u2082 c_in_calls_p_P\u2082\n    )\n  ),\n  have h3: quantifiers_p (P\u2081 \u22c1 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (P\u2081 \u22c1 P\u2082),\n    have q \u2208 quantifiers_p P\u2081 \u2228 q \u2208 quantifiers_p P\u2082, from prop.has_quantifier_p.or.inv this,\n    or.elim this (\n      assume q_in_quantifiers_p_P\u2081: q \u2208 quantifiers_p P\u2081,\n      have q_not_in_quantifiers_p_P\u2081: q \u2209 quantifiers_p P\u2081, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P\u2081 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2081 q_in_quantifiers_p_P\u2081\n    ) (\n      assume q_in_quantifiers_p_P\u2082: q \u2208 quantifiers_p P\u2082,\n      have q_not_in_quantifiers_p_P\u2082: q \u2209 quantifiers_p P\u2082, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P\u2082 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2082 q_in_quantifiers_p_P\u2082\n    )\n  ),\n  have h4: quantifiers_n (P\u2081 \u22c1 P\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n (P\u2081 \u22c1 P\u2082),\n    have q \u2208 quantifiers_n P\u2081 \u2228 q \u2208 quantifiers_n P\u2082, from prop.has_quantifier_n.or.inv this,\n    or.elim this (\n      assume q_in_quantifiers_p_P\u2081: q \u2208 quantifiers_n P\u2081,\n      have q_not_in_quantifiers_p_P\u2081: q \u2209 quantifiers_n P\u2081, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P\u2081 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2081 q_in_quantifiers_p_P\u2081\n    ) (\n      assume q_in_quantifiers_p_P\u2082: q \u2208 quantifiers_n P\u2082,\n      have q_not_in_quantifiers_p_P\u2082: q \u2209 quantifiers_n P\u2082, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P\u2082 q,\n      show \u00abfalse\u00bb, from q_not_in_quantifiers_p_P\u2082 q_in_quantifiers_p_P\u2082\n    )\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.pre {t\u2081 t\u2082: term}: no_instantiations (prop.pre t\u2081 t\u2082) :=\n  have h1: calls_p (prop.pre t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (prop.pre t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_call_p.pre.inv this\n  ),\n  have h2: calls_n (prop.pre t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n (prop.pre t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_call_n.pre.inv this\n  ),\n  have h3: quantifiers_p (prop.pre t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (prop.pre t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_quantifier_p.pre.inv  this\n  ),\n  have h4: quantifiers_n (prop.pre t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n (prop.pre t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_quantifier_n.pre.inv  this\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.pre\u2081 {t: term} {op: unop}: no_instantiations (prop.pre\u2081 op t) :=\n  have h1: calls_p (prop.pre\u2081 op t) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (prop.pre\u2081 op t),\n    show \u00abfalse\u00bb, from prop.has_call_p.pre\u2081.inv this\n  ),\n  have h2: calls_n (prop.pre\u2081 op t) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n (prop.pre\u2081 op t),\n    show \u00abfalse\u00bb, from prop.has_call_n.pre\u2081.inv this\n  ),\n  have h3: quantifiers_p (prop.pre\u2081 op t) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (prop.pre\u2081 op t),\n    show \u00abfalse\u00bb, from prop.has_quantifier_p.pre\u2081.inv  this\n  ),\n  have h4: quantifiers_n (prop.pre\u2081 op t) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n (prop.pre\u2081 op t),\n    show \u00abfalse\u00bb, from prop.has_quantifier_n.pre\u2081.inv  this\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.pre\u2082 {t\u2081 t\u2082: term} {op: binop}: no_instantiations (prop.pre\u2082 op t\u2081 t\u2082) :=\n  have h1: calls_p (prop.pre\u2082 op t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (prop.pre\u2082 op t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_call_p.pre\u2082.inv this\n  ),\n  have h2: calls_n (prop.pre\u2082 op t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n (prop.pre\u2082 op t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_call_n.pre\u2082.inv this\n  ),\n  have h3: quantifiers_p (prop.pre\u2082 op t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (prop.pre\u2082 op t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_quantifier_p.pre\u2082.inv  this\n  ),\n  have h4: quantifiers_n (prop.pre\u2082 op t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n (prop.pre\u2082 op t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_quantifier_n.pre\u2082.inv  this\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\n\nlemma no_instantiations.post {t\u2081 t\u2082: term}: no_instantiations (prop.post t\u2081 t\u2082) :=\n  have h1: calls_p (prop.post t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (prop.post t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_call_p.post.inv this\n  ),\n  have h2: calls_n (prop.post t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume c: calltrigger,\n    assume : c \u2208 calls_n (prop.post t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_call_n.post.inv this\n  ),\n  have h3: quantifiers_p (prop.post t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (prop.post t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_quantifier_p.post.inv  this\n  ),\n  have h4: quantifiers_n (prop.post t\u2081 t\u2082) = \u2205, from set.eq_empty_of_forall_not_mem (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_n (prop.post t\u2081 t\u2082),\n    show \u00abfalse\u00bb, from prop.has_quantifier_n.post.inv  this\n  ),\n  \u27e8h1, \u27e8h2, \u27e8h3, h4\u27e9\u27e9\u27e9\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 \u22c1 Q.erased_n) : by unfold prop.erased_n\n                             ... = ((vc.not P.erased_p) \u22c1 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 \u22c1 Q.erased_p) : by unfold prop.erased_p\n                               ... = (vc.not P.erased_n \u22c1 Q.erased_p) : by unfold prop.erased_p\n\nlemma free_of_erased_n_free {x: var} {P: prop}: (x \u2208 FV P.erased_n \u2228 x \u2208 FV P.erased_p) \u2192 x \u2208 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 \u25b8 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 \u25b8 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\u2081 ih { from (\n      or.elim x_free_in_erased_n_or_erased_p\n      (\n        assume x_free: x \u2208 FV (prop.not P\u2081).erased_n,\n        have (prop.not P\u2081).erased_n = vc.not P\u2081.erased_p, by unfold prop.erased_n,\n        have x \u2208 FV (vc.not P\u2081.erased_p), from this \u25b8 x_free,\n        have x \u2208 FV P\u2081.erased_p, from free_in_vc.not.inv this,\n        have x \u2208 FV P\u2081, from ih (or.inr this),\n        show x \u2208 FV P\u2081.not, from free_in_prop.not this\n      ) (\n        assume x_free: x \u2208 FV (prop.not P\u2081).erased_p,\n        have (prop.not P\u2081).erased_p = vc.not P\u2081.erased_n, by unfold prop.erased_p,\n        have x \u2208 FV (vc.not P\u2081.erased_n), from this \u25b8 x_free,\n        have x \u2208 FV P\u2081.erased_n, from free_in_vc.not.inv this,\n        have x \u2208 FV P\u2081, from ih (or.inl this),\n        show x \u2208 FV P\u2081.not, from free_in_prop.not this\n      )\n    )},\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082).erased_n,\n        have (prop.and P\u2081 P\u2082).erased_n = (P\u2081.erased_n \u22c0 P\u2082.erased_n), by unfold prop.erased_n,\n        have x \u2208 FV (P\u2081.erased_n \u22c0 P\u2082.erased_n), from this \u25b8 x_free,\n        have x \u2208 FV P\u2081.erased_n \u2228 x \u2208 FV P\u2082.erased_n, from free_in_vc.and.inv this,\n        or.elim this (\n          assume : x \u2208 FV P\u2081.erased_n,\n          have x \u2208 FV P\u2081, from P\u2081_ih (or.inl this),\n          show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n        ) (\n          assume : x \u2208 FV P\u2082.erased_n,\n          have x \u2208 FV P\u2082, from P\u2082_ih (or.inl this),\n          show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this\n        )\n      ) (\n        assume x_free: x \u2208 FV (P\u2081 \u22c0 P\u2082).erased_p,\n        have (prop.and P\u2081 P\u2082).erased_p = (P\u2081.erased_p \u22c0 P\u2082.erased_p), by unfold prop.erased_p,\n        have x \u2208 FV (P\u2081.erased_p \u22c0 P\u2082.erased_p), from this \u25b8 x_free,\n        have x \u2208 FV P\u2081.erased_p \u2228 x \u2208 FV P\u2082.erased_p, from free_in_vc.and.inv this,\n        or.elim this (\n          assume : x \u2208 FV P\u2081.erased_p,\n          have x \u2208 FV P\u2081, from P\u2081_ih (or.inr this),\n          show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this\n        ) (\n          assume : x \u2208 FV P\u2082.erased_p,\n          have x \u2208 FV P\u2082, from P\u2082_ih (or.inr this),\n          show x \u2208 FV (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this\n        )\n      )\n    )},\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082).erased_n,\n        have (prop.or P\u2081 P\u2082).erased_n = (P\u2081.erased_n \u22c1 P\u2082.erased_n), by unfold prop.erased_n,\n        have x \u2208 FV (P\u2081.erased_n \u22c1 P\u2082.erased_n), from this \u25b8 x_free,\n        have x \u2208 FV P\u2081.erased_n \u2228 x \u2208 FV P\u2082.erased_n, from free_in_vc.or.inv this,\n        or.elim this (\n          assume : x \u2208 FV P\u2081.erased_n,\n          have x \u2208 FV P\u2081, from P\u2081_ih (or.inl this),\n          show x \u2208 FV (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2081 this\n        ) (\n          assume : x \u2208 FV P\u2082.erased_n,\n          have x \u2208 FV P\u2082, from P\u2082_ih (or.inl this),\n          show x \u2208 FV (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2082 this\n        )\n      ) (\n        assume x_free: x \u2208 FV (P\u2081 \u22c1 P\u2082).erased_p,\n        have (prop.or P\u2081 P\u2082).erased_p = (P\u2081.erased_p \u22c1 P\u2082.erased_p), by unfold prop.erased_p,\n        have x \u2208 FV (P\u2081.erased_p \u22c1 P\u2082.erased_p), from this \u25b8 x_free,\n        have x \u2208 FV P\u2081.erased_p \u2228 x \u2208 FV P\u2082.erased_p, from free_in_vc.or.inv this,\n        or.elim this (\n          assume : x \u2208 FV P\u2081.erased_p,\n          have x \u2208 FV P\u2081, from P\u2081_ih (or.inr this),\n          show x \u2208 FV (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2081 this\n        ) (\n          assume : x \u2208 FV P\u2082.erased_p,\n          have x \u2208 FV P\u2082, from P\u2082_ih (or.inr this),\n          show x \u2208 FV (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2082 this\n        )\n      )\n    )},\n    case prop.pre t\u2081 t\u2082 { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (prop.pre t\u2081 t\u2082).erased_n,\n        have (prop.pre t\u2081 t\u2082).erased_n = vc.pre t\u2081 t\u2082, by unfold prop.erased_n,\n        have x \u2208 FV (vc.pre t\u2081 t\u2082), from this \u25b8 x_free,\n        have x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.pre.inv this,\n        or.elim this (\n          assume : x \u2208 FV t\u2081,\n          show free_in_prop x (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2081 this\n        ) (\n          assume : x \u2208 FV t\u2082,\n          show free_in_prop x (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2082 this\n        )\n      ) (\n        assume x_free: x \u2208 FV (prop.pre t\u2081 t\u2082).erased_p,\n        have (prop.pre t\u2081 t\u2082).erased_p = vc.pre t\u2081 t\u2082, by unfold prop.erased_p,\n        have x \u2208 FV (vc.pre t\u2081 t\u2082), from this \u25b8 x_free,\n        have x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.pre.inv this,\n        or.elim this (\n          assume : x \u2208 FV t\u2081,\n          show free_in_prop x (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2081 this\n        ) (\n          assume : x \u2208 FV t\u2082,\n          show free_in_prop x (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2082 this\n        )\n      )\n    )},\n    case prop.pre\u2081 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\u2081 op t).erased_n,\n        have (prop.pre\u2081 op t).erased_n = vc.pre\u2081 op t, by unfold prop.erased_n,\n        have free_in_vc x (vc.pre\u2081 op t), from this \u25b8 x_free_in_t,\n        have free_in_term x t, from free_in_vc.pre\u2081.inv this,\n        show free_in_prop x (prop.pre\u2081 op t), from free_in_prop.preop this\n      ) (\n        assume x_free_in_t: free_in_vc x (prop.pre\u2081 op t).erased_p,\n        have (prop.pre\u2081 op t).erased_p = vc.pre\u2081 op t, by unfold prop.erased_p,\n        have free_in_vc x (vc.pre\u2081 op t), from this \u25b8 x_free_in_t,\n        have free_in_term x t, from free_in_vc.pre\u2081.inv this,\n        show free_in_prop x (prop.pre\u2081 op t), from free_in_prop.preop this\n      )\n    )},\n    case prop.pre\u2082 op t\u2081 t\u2082 { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (prop.pre\u2082 op t\u2081 t\u2082).erased_n,\n        have (prop.pre\u2082 op t\u2081 t\u2082).erased_n = vc.pre\u2082 op t\u2081 t\u2082, by unfold prop.erased_n,\n        have x \u2208 FV (vc.pre\u2082 op t\u2081 t\u2082), from this \u25b8 x_free,\n        have x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.pre\u2082.inv this,\n        or.elim this (\n          assume : x \u2208 FV t\u2081,\n          show free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2081 this\n        ) (\n          assume : x \u2208 FV t\u2082,\n          show free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2082 this\n        )\n      ) (\n        assume x_free: x \u2208 FV (prop.pre\u2082 op t\u2081 t\u2082).erased_p,\n        have (prop.pre\u2082 op t\u2081 t\u2082).erased_p = vc.pre\u2082 op t\u2081 t\u2082, by unfold prop.erased_p,\n        have x \u2208 FV (vc.pre\u2082 op t\u2081 t\u2082), from this \u25b8 x_free,\n        have x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.pre\u2082.inv this,\n        or.elim this (\n          assume : x \u2208 FV t\u2081,\n          show free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2081 this\n        ) (\n          assume : x \u2208 FV t\u2082,\n          show free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2082 this\n        )\n      )\n    )},\n    case prop.post t\u2081 t\u2082 { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (prop.post t\u2081 t\u2082).erased_n,\n        have (prop.post t\u2081 t\u2082).erased_n = vc.post t\u2081 t\u2082, by unfold prop.erased_n,\n        have x \u2208 FV (vc.post t\u2081 t\u2082), from this \u25b8 x_free,\n        have x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.post.inv this,\n        or.elim this (\n          assume : x \u2208 FV t\u2081,\n\n          show free_in_prop x (prop.post t\u2081 t\u2082), from free_in_prop.post\u2081 this\n        ) (\n          assume : x \u2208 FV t\u2082,\n\n          show free_in_prop x (prop.post t\u2081 t\u2082), from free_in_prop.post\u2082 this\n        )\n      ) (\n        assume x_free: x \u2208 FV (prop.post t\u2081 t\u2082).erased_p,\n        have (prop.post t\u2081 t\u2082).erased_p = vc.post t\u2081 t\u2082, by unfold prop.erased_p,\n        have x \u2208 FV (vc.post t\u2081 t\u2082), from this \u25b8 x_free,\n        have x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.post.inv this,\n        or.elim this (\n          assume : x \u2208 FV t\u2081,\n\n          show free_in_prop x (prop.post t\u2081 t\u2082), from free_in_prop.post\u2081 this\n        ) (\n          assume : x \u2208 FV t\u2082,\n\n          show free_in_prop x (prop.post t\u2081 t\u2082), from free_in_prop.post\u2082 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 \u2208 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 \u2208 FV (vc.term value.true), from this \u25b8 x_free,\n        have x \u2208 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 \u2208 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 \u2208 FV (vc.term value.true), from this \u25b8 x_free,\n        have x \u2208 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\u2081 ih { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (prop.forallc y P\u2081).erased_n,\n        have (prop.forallc y P\u2081).erased_n = vc.univ y P\u2081.erased_n, by unfold prop.erased_n,\n        have x \u2208 FV (vc.univ y P\u2081.erased_n), from this \u25b8 x_free,\n        have h2: (x \u2260 y) \u2227 free_in_vc x P\u2081.erased_n, from free_in_vc.univ.inv this,\n        have x \u2208 FV P\u2081, from ih (or.inl h2.right),\n        show x \u2208 FV (prop.forallc y P\u2081), from free_in_prop.forallc h2.left this\n      ) (\n        assume x_free: x \u2208 FV (prop.forallc y P\u2081).erased_p,\n        have (prop.forallc y P\u2081).erased_p = vc.term value.true, by unfold prop.erased_p,\n        have x \u2208 FV (vc.term value.true), from this \u25b8 x_free,\n        have x \u2208 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\u2081 ih { from (\n      or.elim x_free_in_erased_n_or_erased_p (\n        assume x_free: x \u2208 FV (prop.exis y P\u2081).erased_n,\n        have (prop.exis y P\u2081).erased_n = vc.not (vc.univ y (vc.not P\u2081.erased_n)), by unfold prop.erased_n,\n        have x \u2208 FV (vc.not (vc.univ y (vc.not P\u2081.erased_n))), from this \u25b8 x_free,\n        have x \u2208 FV (vc.univ y (vc.not P\u2081.erased_n)), from free_in_vc.not.inv this,\n        have h2: (x \u2260 y) \u2227 free_in_vc x (vc.not P\u2081.erased_n), from free_in_vc.univ.inv this,\n        have h3: x \u2208 FV P\u2081.erased_n, from free_in_vc.not.inv h2.right,\n        have x \u2208 FV P\u2081, from ih (or.inl h3),\n        show x \u2208 FV (prop.exis y P\u2081), from free_in_prop.exis h2.left this\n      )\n      (\n        assume x_free: x \u2208 FV (prop.exis y P\u2081).erased_p,\n        have (prop.exis y P\u2081).erased_p = vc.not (vc.univ y (vc.not P\u2081.erased_p)), by unfold prop.erased_p,\n        have x \u2208 FV (vc.not (vc.univ y (vc.not P\u2081.erased_p))), from this \u25b8 x_free,\n        have x \u2208 FV (vc.univ y (vc.not P\u2081.erased_p)), from free_in_vc.not.inv this,\n        have h2: (x \u2260 y) \u2227 free_in_vc x (vc.not P\u2081.erased_p), from free_in_vc.univ.inv this,\n        have h3: x \u2208 FV P\u2081.erased_p, from free_in_vc.not.inv h2.right,\n        have x \u2208 FV P\u2081, from ih (or.inr h3),\n        show x \u2208 FV (prop.exis y P\u2081), from free_in_prop.exis h2.left this\n      )\n    )}\n  end\n\nlemma free_of_erased_free {x: var} {P: prop}: (x \u2208 FV P.erased_p \u2228 x \u2208 FV P.erased_n) \u2192 x \u2208 FV P :=\n  assume : x \u2208 FV P.erased_p \u2228 x \u2208 FV P.erased_n,\n  have x \u2208 FV P.erased_n \u2228 x \u2208 FV P.erased_p, from this.symm,\n  show x \u2208 FV P, from free_of_erased_n_free this\n\nlemma prop.has_call_p.and_union {P\u2081 P\u2082: prop}:\n      calls_p (P\u2081 \u22c0 P\u2082) = calls_p P\u2081 \u222a calls_p P\u2082 :=\n  set.eq_of_subset_of_subset (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (P\u2081 \u22c0 P\u2082),\n    or.elim (prop.has_call_p.and.inv this) (\n      assume : c \u2208 calls_p P\u2081,\n      show c \u2208 calls_p P\u2081 \u222a calls_p P\u2082, from set.mem_union_left (calls_p P\u2082) this\n    ) (\n      assume : c \u2208 calls_p P\u2082,\n      show c \u2208 calls_p P\u2081 \u222a calls_p P\u2082, from set.mem_union_right (calls_p P\u2081) this\n    )\n  ) (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p P\u2081 \u222a calls_p P\u2082,\n    or.elim (set.mem_or_mem_of_mem_union this) (\n      assume : c \u2208 calls_p P\u2081,\n      show c \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2081 this\n    ) (\n      assume : c \u2208 calls_p P\u2082,\n      show c \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2082 this\n    )\n  )\n\nlemma prop.has_call_p.and.symm {P\u2081 P\u2082: prop}:\n      calls_p (P\u2081 \u22c0 P\u2082) = calls_p (P\u2082 \u22c0 P\u2081) :=\n  set.eq_of_subset_of_subset (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (P\u2081 \u22c0 P\u2082),\n    or.elim (prop.has_call_p.and.inv this) (\n      assume : c \u2208 calls_p P\u2081,\n      show c \u2208 calls_p (P\u2082 \u22c0 P\u2081), from prop.has_call_p.and\u2082 this\n    ) (\n      assume : c \u2208 calls_p P\u2082,\n      show c \u2208 calls_p (P\u2082 \u22c0 P\u2081), from prop.has_call_p.and\u2081 this\n    )\n  ) (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (P\u2082 \u22c0 P\u2081),\n    or.elim (prop.has_call_p.and.inv this) (\n      assume : c \u2208 calls_p P\u2082,\n      show c \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2082 this\n    ) (\n      assume : c \u2208 calls_p P\u2081,\n      show c \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2081 this\n    )\n  )\n\nlemma prop.has_quantifier_p.and.symm {P\u2081 P\u2082: prop}:\n      quantifiers_p (P\u2081 \u22c0 P\u2082) = quantifiers_p (P\u2082 \u22c0 P\u2081) :=\n  set.eq_of_subset_of_subset (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082),\n    or.elim (prop.has_quantifier_p.and.inv this) (\n      assume : q \u2208 quantifiers_p P\u2081,\n      show q \u2208 quantifiers_p (P\u2082 \u22c0 P\u2081), from prop.has_quantifier_p.and\u2082 this\n    ) (\n      assume : q \u2208 quantifiers_p P\u2082,\n      show q \u2208 quantifiers_p (P\u2082 \u22c0 P\u2081), from prop.has_quantifier_p.and\u2081 this\n    )\n  ) (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (P\u2082 \u22c0 P\u2081),\n    or.elim (prop.has_quantifier_p.and.inv this) (\n      assume : q \u2208 quantifiers_p P\u2082,\n      show q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082), from prop.has_quantifier_p.and\u2082 this\n    ) (\n      assume : q \u2208 quantifiers_p P\u2081,\n      show q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082), from prop.has_quantifier_p.and\u2081 this\n    )\n  )\n\nlemma prop.has_call_p.and.comm {P\u2081 P\u2082 P\u2083: prop}:\n      calls_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083) = calls_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083) :=\n  set.eq_of_subset_of_subset (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083),\n    or.elim (prop.has_call_p.and.inv this) (\n      assume : c \u2208 calls_p P\u2081,\n      have c \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2081 this,\n      show c \u2208 calls_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from prop.has_call_p.and\u2081 this\n    ) (\n      assume : c \u2208 calls_p (P\u2082 \u22c0 P\u2083),\n      or.elim (prop.has_call_p.and.inv this) (\n        assume : c \u2208 calls_p P\u2082,\n        have c \u2208 calls_p (P\u2081 \u22c0 P\u2082), from prop.has_call_p.and\u2082 this,\n        show c \u2208 calls_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from prop.has_call_p.and\u2081 this\n      ) (\n        assume : c \u2208 calls_p P\u2083,\n        show c \u2208 calls_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from prop.has_call_p.and\u2082 this\n      )\n    )\n  ) (\n    assume c: calltrigger,\n    assume : c \u2208 calls_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083),\n    or.elim (prop.has_call_p.and.inv this) (\n      assume : c \u2208 calls_p (P\u2081 \u22c0 P\u2082),\n      or.elim (prop.has_call_p.and.inv this) (\n        assume : c \u2208 calls_p P\u2081,\n        show c \u2208 calls_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from prop.has_call_p.and\u2081 this\n      ) (\n        assume : c \u2208 calls_p P\u2082,\n        have c \u2208 calls_p (P\u2082 \u22c0 P\u2083), from prop.has_call_p.and\u2081 this,\n        show c \u2208 calls_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from prop.has_call_p.and\u2082 this\n      )\n    ) (\n      assume : c \u2208 calls_p P\u2083,\n      have c \u2208 calls_p (P\u2082 \u22c0 P\u2083), from prop.has_call_p.and\u2082 this,\n      show c \u2208 calls_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from prop.has_call_p.and\u2082 this\n    )\n  )\n\nlemma prop.has_quantifier_p.and.comm {P\u2081 P\u2082 P\u2083: prop}:\n      quantifiers_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083) = quantifiers_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083) :=\n  set.eq_of_subset_of_subset (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083),\n    or.elim (prop.has_quantifier_p.and.inv this) (\n      assume : q \u2208 quantifiers_p P\u2081,\n      have q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082), from prop.has_quantifier_p.and\u2081 this,\n      show q \u2208 quantifiers_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from prop.has_quantifier_p.and\u2081 this\n    ) (\n      assume : q \u2208 quantifiers_p (P\u2082 \u22c0 P\u2083),\n      or.elim (prop.has_quantifier_p.and.inv this) (\n        assume : q \u2208 quantifiers_p P\u2082,\n        have q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082), from prop.has_quantifier_p.and\u2082 this,\n        show q \u2208 quantifiers_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from prop.has_quantifier_p.and\u2081 this\n      ) (\n        assume : q \u2208 quantifiers_p P\u2083,\n        show q \u2208 quantifiers_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083), from prop.has_quantifier_p.and\u2082 this\n      )\n    )\n  ) (\n    assume q: callquantifier,\n    assume : q \u2208 quantifiers_p ((P\u2081 \u22c0 P\u2082) \u22c0 P\u2083),\n    or.elim (prop.has_quantifier_p.and.inv this) (\n      assume : q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082),\n      or.elim (prop.has_quantifier_p.and.inv this) (\n        assume : q \u2208 quantifiers_p P\u2081,\n        show q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from prop.has_quantifier_p.and\u2081 this\n      ) (\n        assume : q \u2208 quantifiers_p P\u2082,\n        have q \u2208 quantifiers_p (P\u2082 \u22c0 P\u2083), from prop.has_quantifier_p.and\u2081 this,\n        show q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from prop.has_quantifier_p.and\u2082 this\n      )\n    ) (\n      assume : q \u2208 quantifiers_p P\u2083,\n      have q \u2208 quantifiers_p (P\u2082 \u22c0 P\u2083), from prop.has_quantifier_p.and\u2082 this,\n      show q \u2208 quantifiers_p (P\u2081 \u22c0 P\u2082 \u22c0 P\u2083), from prop.has_quantifier_p.and\u2082 this\n    )\n  )\n\nlemma same_calls_p_and_left {P P' Q: prop} {\u03c3: env}:\n      calls_p_subst \u03c3 P' \u2286 calls_p_subst \u03c3 P \u2192 (calls_p_subst \u03c3 (P' \u22c0 Q) \u2286 calls_p_subst \u03c3 (P \u22c0 Q)) :=\n  assume calls_P'_P: calls_p_subst \u03c3 P' \u2286 calls_p_subst \u03c3 P,\n  assume c: calltrigger,\n  assume : c \u2208 calls_p_subst \u03c3 (P' \u22c0 Q),\n  or.elim (prop.has_call_p_subst.and.inv this) (\n    assume : c \u2208 calls_p_subst \u03c3 P',\n    have c \u2208 calls_p_subst \u03c3 P, from set.mem_of_mem_of_subset this calls_P'_P,\n    show c \u2208 calls_p_subst \u03c3 (P \u22c0 Q), from prop.has_call_p_subst.and\u2081 this\n  )\n  (\n    assume : c \u2208 calls_p_subst \u03c3 Q,\n    show c \u2208 calls_p_subst \u03c3 (P \u22c0 Q), from prop.has_call_p_subst.and\u2082 this\n  )\n\nlemma prop.has_call_of_subst_has_call {P: prop} {c: calltrigger} {y: var} {v: value}:\n          (c \u2208 calls_p (prop.subst y v P) \u2192 \u2203c', c' \u2208 calls_p P) \u2227\n          (c \u2208 calls_n (prop.subst y v P) \u2192 \u2203c', c' \u2208 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\u2081 P\u2081_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\u2081_ih.right h2,\n      cases h3 with c' a,\n      from \u27e8c', prop.has_call_p.not a\u27e9,\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\u2081_ih.left h2,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_n.not h3\u27e9,\n    },\n    case prop.and P\u2082 P\u2083 P\u2082_ih P\u2083_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\u2082_ih.left a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_p.and\u2081 h3\u27e9,\n      have h3, from P\u2083_ih.left a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_p.and\u2082 h3\u27e9,\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\u2082_ih.right a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_n.and\u2081 h3\u27e9,\n      have h3, from P\u2083_ih.right a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_n.and\u2082 h3\u27e9,\n    },\n    case prop.or P\u2084 P\u2085 P\u2084_ih P\u2085_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\u2084_ih.left a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_p.or\u2081 h3\u27e9,\n      have h3, from P\u2085_ih.left a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_p.or\u2082 h3\u27e9,\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\u2084_ih.right a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_n.or\u2081 h3\u27e9,\n      have h3, from P\u2085_ih.right a,\n      cases h3 with c' h3,\n      from \u27e8c', prop.has_call_n.or\u2082 h3\u27e9,\n    },\n    case prop.pre t\u2081 t\u2082 {\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\u2081 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\u2082 op t\u2081 t\u2082 {\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\u2081 t\u2082 {\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} {\u03c3: env}:\n          (\u2200c, c \u2208 calls_p (prop.subst_env \u03c3 P) \u2192 \u2203c', c' \u2208 calls_p P) \u2227\n          (\u2200c, c \u2208 calls_n (prop.subst_env \u03c3 P) \u2192 \u2203c', c' \u2208 calls_n P) :=\n  begin\n    induction \u03c3 with \u03c3' 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 \u2208 calls_p P \u2194 c \u2208 P.find_calls_p) \u2227 (c \u2208 calls_n P \u2194 c \u2208 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\u2081 ih {\n      split,\n\n      split,\n\n      assume h1,\n      cases h1,\n      have h2: c \u2208 calls_n P\u2081, 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 \u2208 calls_p P\u2081, 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      split,\n\n      assume h1,\n      cases h1,\n\n      have h2: c \u2208 calls_p P\u2081, from a,\n      unfold prop.find_calls_p,\n      apply list.mem_append.mpr,\n      left,\n      from P\u2081_ih.left.mp h2,\n\n      have h2: c \u2208 calls_p P\u2082, from a,\n      unfold prop.find_calls_p,\n      apply list.mem_append.mpr,\n      right,\n      from P\u2082_ih.left.mp h2,\n\n      assume h1,\n      change prop.has_call_p c (prop.and P\u2081 P\u2082),\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\u2081_ih.left.mpr a,\n      have h4: prop.has_call_p c P\u2081, from h3,\n      from prop.has_call_p.and\u2081 h4,\n\n      have h3, from P\u2082_ih.left.mpr a,\n      have h4: prop.has_call_p c P\u2082, from h3,\n      from prop.has_call_p.and\u2082 h4,\n\n      split,\n\n      assume h1,\n      cases h1,\n\n      have h2: c \u2208 calls_n P\u2081, from a,\n      unfold prop.find_calls_n,\n      apply list.mem_append.mpr,\n      left,\n      from P\u2081_ih.right.mp h2,\n\n      have h2: c \u2208 calls_n P\u2082, from a,\n      unfold prop.find_calls_n,\n      apply list.mem_append.mpr,\n      right,\n      from P\u2082_ih.right.mp h2,\n\n      assume h1,\n      change prop.has_call_n c (prop.and P\u2081 P\u2082),\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\u2081_ih.right.mpr a,\n      have h4: prop.has_call_n c P\u2081, from h3,\n      from prop.has_call_n.and\u2081 h4,\n\n      have h3, from P\u2082_ih.right.mpr a,\n      have h4: prop.has_call_n c P\u2082, from h3,\n      from prop.has_call_n.and\u2082 h4\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      split,\n\n      assume h1,\n      cases h1,\n\n      have h2: c \u2208 calls_p P\u2081, from a,\n      unfold prop.find_calls_p,\n      apply list.mem_append.mpr,\n      left,\n      from P\u2081_ih.left.mp h2,\n\n      have h2: c \u2208 calls_p P\u2082, from a,\n      unfold prop.find_calls_p,\n      apply list.mem_append.mpr,\n      right,\n      from P\u2082_ih.left.mp h2,\n\n      assume h1,\n      change prop.has_call_p c (prop.or P\u2081 P\u2082),\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\u2081_ih.left.mpr a,\n      have h4: prop.has_call_p c P\u2081, from h3,\n      from prop.has_call_p.or\u2081 h4,\n\n      have h3, from P\u2082_ih.left.mpr a,\n      have h4: prop.has_call_p c P\u2082, from h3,\n      from prop.has_call_p.or\u2082 h4,\n\n      split,\n\n      assume h1,\n      cases h1,\n\n      have h2: c \u2208 calls_n P\u2081, from a,\n      unfold prop.find_calls_n,\n      apply list.mem_append.mpr,\n      left,\n      from P\u2081_ih.right.mp h2,\n\n      have h2: c \u2208 calls_n P\u2082, from a,\n      unfold prop.find_calls_n,\n      apply list.mem_append.mpr,\n      right,\n      from P\u2082_ih.right.mp h2,\n\n      assume h1,\n      change prop.has_call_n c (prop.or P\u2081 P\u2082),\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\u2081_ih.right.mpr a,\n      have h4: prop.has_call_n c P\u2081, from h3,\n      from prop.has_call_n.or\u2081 h4,\n\n      have h3, from P\u2082_ih.right.mpr a,\n      have h4: prop.has_call_n c P\u2082, from h3,\n      from prop.has_call_n.or\u2082 h4\n    },\n    case prop.pre t\u2081 t\u2082 {\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\u2081 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\u2082 op t\u2081 t\u2082 {\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\u2081 t\u2082 {\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\u2081 P\u2081_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\u2081 P\u2081_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      \u2200P: prop, ((\u22a8 P.erased_n) \u2192 \u22a8 P.to_vc) \u2227 ((\u22a8 P.to_vc) \u2192 \u22a8 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\u2081) :=\n  have rec_wf: P\u2081.simplesize < (prop.not P\u2081).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\u2081).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\u2081).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\u2081 P\u2082) :=\n  have rec_1: P\u2081.simplesize < (prop.and P\u2081 P\u2082).simplesize, from simplesize_prop_and\u2081,\n  have rec_2: P\u2082.simplesize < (prop.and P\u2081 P\u2082).simplesize, from simplesize_prop_and\u2082,\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 \u22a8 prop.to_vc P\u2081, by begin\n      have h2, from (valid.and.mpr h1).left,\n      from (to_vc_valid_of_erased_n_valid P\u2081).left h2\n    end,\n\n    show \u22a8 prop.to_vc P\u2082, by begin\n      have h2, from (valid.and.mpr h1).right,\n      from (to_vc_valid_of_erased_n_valid P\u2082).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 \u22a8prop.erased_p P\u2081, by begin\n      have h2, from (valid.and.mpr h1).left,\n      from (to_vc_valid_of_erased_n_valid P\u2081).right h2\n    end,\n\n    show \u22a8prop.erased_p P\u2082, by begin\n      have h2, from (valid.and.mpr h1).right,\n      from (to_vc_valid_of_erased_n_valid P\u2082).right h2\n    end\n  end\n| (prop.or P\u2081 P\u2082) :=\n  have rec_1: P\u2081.simplesize < (prop.or P\u2081 P\u2082).simplesize, from simplesize_prop_or\u2081,\n  have rec_2: P\u2082.simplesize < (prop.or P\u2081 P\u2082).simplesize, from simplesize_prop_or\u2082,\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\u2081).left a,\n\n    apply valid.or.right,\n    from (to_vc_valid_of_erased_n_valid P\u2082).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\u2081).right a,\n\n    apply valid.or.right,\n    from (to_vc_valid_of_erased_n_valid P\u2082).right a\n  end\n| (prop.pre t\u2081 t\u2082) := 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\u2081 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\u2082 op t\u2081 t\u2082) := 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\u2081 t\u2082) := 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\u2081) :=\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\u2081) = vc.subst y v (prop.erased_n P\u2081)),\n    from vc.substt_value_eq_subst,\n    have h3c: \u22a8vc.subst y v (prop.erased_n P\u2081), from h3b \u25b8 h3,\n    have h4: (vc.subst y v (prop.erased_n P\u2081) = prop.erased_n (prop.subst y v P\u2081)),\n    from subst_distrib_erased.right,\n    have h5: \u22a8 prop.erased_n (prop.subst y v P\u2081), from h4 \u25b8 h3c,\n    have h6: (vc.subst y v (prop.to_vc P\u2081) = prop.to_vc (prop.subst y v P\u2081)),\n    from subst_distrib_to_vc,\n    rw[h6],\n    show \u22a8prop.to_vc (prop.subst y v P\u2081), from (\n      have ht1: P\u2081.simplesize = (prop.subst y v P\u2081).simplesize, from same_simplesize_after_subst,\n      have ht2: P\u2081.simplesize < (prop.forallc y P\u2081).simplesize, from simplesize_prop_forall,\n      have rec_wf: (prop.subst y v P\u2081).simplesize < (prop.forallc y P\u2081).simplesize, from ht1 \u25b8 ht2,\n      (to_vc_valid_of_erased_n_valid (prop.subst y v P\u2081)).left h5\n    ),\n\n    assume h1,\n    unfold prop.erased_p,\n    from valid.tru\n  end\n| (prop.exis y P\u2081) := 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: \u22a8vc.univ y (vc.not (prop.erased_n P\u2081)), 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\u2081)) = vc.subst y v (vc.not (prop.to_vc P\u2081))),\n      from vc.substt_value_eq_subst,\n      have h6c: \u22a8vc.subst y v (vc.not (prop.to_vc P\u2081)), from h6b \u25b8 h6,\n      have h7: (vc.subst y v (vc.not (prop.to_vc P\u2081)) = vc.not (vc.subst y v (prop.to_vc P\u2081))),\n      by unfold vc.subst,\n      rw[h7] at h6c,\n      have h8: (vc.subst y v (vc.not (prop.erased_n P\u2081)) = vc.not (vc.subst y v (prop.erased_n P\u2081))),\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: \u22a8vc.subst y v (prop.to_vc P\u2081), by begin\n\n        have h12: (vc.subst y v (prop.erased_n P\u2081) = prop.erased_n (prop.subst y v P\u2081)),\n        from subst_distrib_erased.right,\n        have h13: \u22a8 prop.erased_n (prop.subst y v P\u2081), from h12 \u25b8 h10,\n        have h14: (vc.subst y v (prop.to_vc P\u2081) = prop.to_vc (prop.subst y v P\u2081)),\n        from subst_distrib_to_vc,\n        rw[h14],\n        show \u22a8prop.to_vc (prop.subst y v P\u2081), from (\n          have ht1: P\u2081.simplesize = (prop.subst y v P\u2081).simplesize, from same_simplesize_after_subst,\n          have ht2: P\u2081.simplesize < (prop.forallc y P\u2081).simplesize, from simplesize_prop_forall,\n          have rec_wf: (prop.subst y v P\u2081).simplesize < (prop.forallc y P\u2081).simplesize, from ht1 \u25b8 ht2,\n          (to_vc_valid_of_erased_n_valid (prop.subst y v P\u2081)).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: \u22a8vc.univ y (vc.not (prop.to_vc P\u2081)), 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\u2081)) = vc.not (vc.subst y v (prop.erased_p P\u2081))),\n      by unfold vc.subst,\n      have h8: (vc.subst y v (vc.not (prop.to_vc P\u2081)) = vc.not (vc.subst y v (prop.to_vc P\u2081))),\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: \u22a8vc.subst y v (prop.erased_p P\u2081), by begin\n\n        have h12: (vc.subst y v (prop.to_vc P\u2081) = prop.to_vc (prop.subst y v P\u2081)),\n        from subst_distrib_to_vc,\n        have h13: \u22a8 prop.to_vc (prop.subst y v P\u2081), from h12 \u25b8 h10,\n        have h14: (vc.subst y v (prop.erased_p P\u2081) = prop.erased_p (prop.subst y v P\u2081)),\n        from subst_distrib_erased.left,\n        rw[h14],\n        show \u22a8prop.erased_p (prop.subst y v P\u2081), from (\n          have ht1: P\u2081.simplesize = (prop.subst y v P\u2081).simplesize, from same_simplesize_after_subst,\n          have ht2: P\u2081.simplesize < (prop.forallc y P\u2081).simplesize, from simplesize_prop_forall,\n          have rec_wf: (prop.subst y v P\u2081).simplesize < (prop.forallc y P\u2081).simplesize, from ht1 \u25b8 ht2,\n          (to_vc_valid_of_erased_n_valid (prop.subst y v P\u2081)).right h13\n        )\n      end,\n      from h9 h11\n    end,\n    from h2 h4\n  end\nusing_well_founded {\n  rel_tac := \u03bb _ _, `[exact \u27e8_, measure_wf $ \u03bb s, s.simplesize\u27e9],\n  dec_tac := tactic.assumption\n}\n\nlemma and_lifted_p_is_some {P\u2081 P\u2082 Q: prop} {x: var}:\n      prop.lift_p (prop.and P\u2081 P\u2082) x = some Q \u2192\n      (\u2203Q\u2081: prop, P\u2081.lift_p x = some Q\u2081 \u2227 (Q = (Q\u2081 \u22c0 P\u2082))) \u2228 (\u2203Q\u2082: prop, P\u2082.lift_p x = some Q\u2082 \u2227 (Q = (P\u2081 \u22c0 Q\u2082))) :=\n  begin\n    assume h1,\n    unfold prop.lift_p at h1,\n    cases (prop.lift_p P\u2081 x) with Q\u2081 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\u2082 h4,\n    right,\n    existsi Q\u2082,\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\u2081,\n    split,\n    from rfl,\n    from h2.symm\n  end\n\nlemma and_lifted_n_is_some {P\u2081 P\u2082 Q: prop} {x: var}:\n      prop.lift_n (prop.and P\u2081 P\u2082) x = some Q \u2192\n      (\u2203Q\u2081: prop, P\u2081.lift_n x = some Q\u2081 \u2227 (Q = (Q\u2081 \u22c0 P\u2082))) \u2228 (\u2203Q\u2082: prop, P\u2082.lift_n x = some Q\u2082 \u2227 (Q = (P\u2081 \u22c0 Q\u2082))) :=\n  begin\n    assume h1,\n    unfold prop.lift_n at h1,\n    cases (prop.lift_n P\u2081 x) with Q\u2081 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\u2082 h4,\n    right,\n    existsi Q\u2082,\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\u2081,\n    split,\n    from rfl,\n    from h2.symm\n  end\n\nlemma or_lifted_p_is_some {P\u2081 P\u2082 Q: prop} {x: var}:\n      prop.lift_p (prop.or P\u2081 P\u2082) x = some Q \u2192\n      (\u2203Q\u2081: prop, P\u2081.lift_p x = some Q\u2081 \u2227 (Q = (Q\u2081 \u22c1 P\u2082))) \u2228 (\u2203Q\u2082: prop, P\u2082.lift_p x = some Q\u2082 \u2227 (Q = (P\u2081 \u22c1 Q\u2082))) :=\n  begin\n    assume h1,\n    unfold prop.lift_p at h1,\n    cases (prop.lift_p P\u2081 x) with Q\u2081 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\u2082 h4,\n    right,\n    existsi Q\u2082,\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\u2081,\n    split,\n    from rfl,\n    from h2.symm\n  end\n\nlemma or_lifted_n_is_some {P\u2081 P\u2082 Q: prop} {x: var}:\n      prop.lift_n (prop.or P\u2081 P\u2082) x = some Q \u2192\n      (\u2203Q\u2081: prop, P\u2081.lift_n x = some Q\u2081 \u2227 (Q = (Q\u2081 \u22c1 P\u2082))) \u2228 (\u2203Q\u2082: prop, P\u2082.lift_n x = some Q\u2082 \u2227 (Q = (P\u2081 \u22c1 Q\u2082))) :=\n  begin\n    assume h1,\n    unfold prop.lift_n at h1,\n    cases (prop.lift_n P\u2081 x) with Q\u2081 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\u2082 h4,\n    right,\n    existsi Q\u2082,\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\u2081,\n    split,\n    from rfl,\n    from h2.symm\n  end\n\nlemma to_vc_valid_of_lifted_to_vc_valid {x: var}:\n  \u2200P: prop, \u2200Q: prop, \u00ac prop.uses_var x P \u2192\n  (P.lift_p x = some Q \u2192 (\u22a8 Q.to_vc) \u2192 \u22a8 P.to_vc) \u2227\n  (P.lift_n x = some Q \u2192 (\u22a8 P.to_vc) \u2192 \u22a8 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\u2081) :=\n  have rec_wf: P\u2081.simplesize < (prop.not P\u2081).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\u2082 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: \u22a8prop.to_vc Q\u2082, by begin\n      have h8: \u00ac prop.uses_var x P\u2081, 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\u2081 Q\u2082 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\u2082 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: \u22a8prop.to_vc P\u2081, by begin\n      have h8: \u00ac prop.uses_var x P\u2081, 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\u2081 Q\u2082 h8).left h3.left h6\n    end,\n    from h5 h7\n  end\n| (prop.and P\u2081 P\u2082) :=\n  have rec_1: P\u2081.simplesize < (prop.and P\u2081 P\u2082).simplesize, from simplesize_prop_and\u2081,\n  have rec_2: P\u2082.simplesize < (prop.and P\u2081 P\u2082).simplesize, from simplesize_prop_and\u2082,\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\u2081 h4,\n    assume h5,\n    rw[h4.right] at h5,\n    have h6: \u22a8prop.to_vc (prop.and Q\u2081 P\u2082), 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: \u00ac prop.uses_var x P\u2081, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.and P\u2081 P\u2082), from prop.uses_var.and\u2081 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2081 Q\u2081 h8).left h4.left h7,\n    from (valid.and.mpr h6).right,\n\n    cases h4 with Q\u2082 h5,\n    assume h6,\n    rw[h5.right] at h6,\n    have h7: \u22a8prop.to_vc (prop.and P\u2081 Q\u2082), 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: \u00ac prop.uses_var x P\u2082, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.and P\u2081 P\u2082), from prop.uses_var.and\u2082 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2082 Q\u2082 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\u2081 h4,\n    assume h5,\n    rw[h4.right],\n    unfold prop.to_vc at h5,\n    change \u22a8prop.to_vc (prop.and Q\u2081 P\u2082),\n    unfold prop.to_vc,\n    apply valid.and.mp,\n    split,\n    have h7, from (valid.and.mpr h5).left,\n    have h8: \u00ac prop.uses_var x P\u2081, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.and P\u2081 P\u2082), from prop.uses_var.and\u2081 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2081 Q\u2081 h8).right h4.left h7,\n    from (valid.and.mpr h5).right,\n\n    cases h4 with Q\u2082 h5,\n    assume h6,\n    rw[h5.right],\n    change \u22a8prop.to_vc (prop.and P\u2081 Q\u2082),\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: \u00ac prop.uses_var x P\u2082, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.and P\u2081 P\u2082), from prop.uses_var.and\u2082 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2082 Q\u2082 h8).right h5.left h7.right\n  end\n| (prop.or P\u2081 P\u2082) :=\n  have rec_1: P\u2081.simplesize < (prop.or P\u2081 P\u2082).simplesize, from simplesize_prop_or\u2081,\n  have rec_2: P\u2082.simplesize < (prop.or P\u2081 P\u2082).simplesize, from simplesize_prop_or\u2082,\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\u2081 h4,\n    assume h5,\n    rw[h4.right] at h5,\n    have h6: \u22a8prop.to_vc (prop.or Q\u2081 P\u2082), 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: \u00ac prop.uses_var x P\u2081, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.or P\u2081 P\u2082), from prop.uses_var.or\u2081 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2081 Q\u2081 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\u2082 h6,\n    rw[h6.right] at h5,\n    have h7: \u22a8prop.to_vc (prop.or P\u2081 Q\u2082), 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: \u00ac prop.uses_var x P\u2082, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.or P\u2081 P\u2082), from prop.uses_var.or\u2082 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2082 Q\u2082 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\u2081 h4,\n    assume h5,\n    rw[h4.right],\n    change \u22a8prop.to_vc (prop.or Q\u2081 P\u2082),\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: \u00ac prop.uses_var x P\u2081, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.or P\u2081 P\u2082), from prop.uses_var.or\u2081 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2081 Q\u2081 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\u2082 h6,\n    rw[h6.right],\n    change \u22a8prop.to_vc (prop.or P\u2081 Q\u2082),\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: \u00ac prop.uses_var x P\u2082, by begin\n      assume h9,\n      have h10: prop.uses_var x (prop.or P\u2081 P\u2082), from prop.uses_var.or\u2082 h9,\n      from x_unused h10\n    end,\n    from (to_vc_valid_of_lifted_to_vc_valid P\u2082 Q\u2082 h10).right h6.left h9\n  end\n| (prop.pre t\u2081 t\u2082) := 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\u2081 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\u2082 op t\u2081 t\u2082) := 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\u2081 t\u2082) := 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\u2081) := 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: \u22a8vc.term \u2191value.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\u2081) = prop.to_vc (prop.substt y x P\u2081)),\n    from substt_distrib_to_vc,\n    rw[\u2190h6] at h5,\n\n    by_cases (free_in_vc y P\u2081.to_vc) with h7,\n\n    have h8: \u22a8 vc.substt x y (vc.substt y \u2191x (prop.to_vc P\u2081)), from valid.alpha_equiv h5,\n    have h9: \u00ac vc.uses_var x (prop.to_vc P\u2081), 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\u2081), 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\u2081)) = (prop.to_vc P\u2081)),\n    from vc.substt_var_cancel h9,\n    rw[h10] at h8,\n    have h11: \u22a8 vc.univ y P\u2081.to_vc, from valid.univ.free \u27e8h7, h8\u27e9,\n    have h12: \u22a8 vc.substt y v (prop.to_vc P\u2081),\n    from valid.univ.mpr h11 v,\n    have h13: (vc.substt y v (prop.to_vc P\u2081) = vc.subst y v (prop.to_vc P\u2081)),\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\u2081) = (prop.to_vc P\u2081)),\n    from unchanged_of_subst_nonfree_vc h7,\n    rw[h8],\n    have h9: (vc.substt y x (prop.to_vc P\u2081) = (prop.to_vc P\u2081)),\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\u2081) := 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 := \u03bb _ _, `[exact \u27e8_, measure_wf $ \u03bb s, s.simplesize\u27e9],\n  dec_tac := tactic.assumption\n}\n\nlemma to_vc_valid_of_lift_all_to_vc_valid: \u2200P:prop, (\u22a8 P.lift_all.to_vc) \u2192 \u22a8 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: \u2203Q, (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 \u22a8 prop.to_vc P, from (\n      have Q.num_quantifiers < P.num_quantifiers, from (lifted_prop_smaller Q).left h5,\n      have h6: \u22a8 Q.to_vc, from to_vc_valid_of_lift_all_to_vc_valid Q h1,\n      have P.fresh_var \u2264 P.fresh_var, from le_refl P.fresh_var,\n      have \u00ac 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 := \u03bb _ _, `[exact \u27e8_, measure_wf $ \u03bb s, s.num_quantifiers \u27e9],\n  dec_tac := tactic.assumption\n}\n\nlemma erased_valid_of_instantiated_with_erased_valid {P: prop} {t: calltrigger}:\n  ((\u22a8 (P.instantiate_with_n t).to_vc) \u2192 \u22a8 P.to_vc) \u2227\n  ((\u22a8 P.to_vc) \u2192 \u22a8 (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\u2081 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: \u22a8 prop.to_vc (prop.instantiate_with_p P\u2081 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: \u22a8 prop.to_vc P\u2081,\n      from ih.left a,\n      have h3, from valid.not.mpr h1,\n      from h3 h2\n    },\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      unfold prop.instantiate_with_n,\n      unfold prop.to_vc,\n      assume h1,\n      have h2: \u22a8 prop.to_vc (prop.and (prop.instantiate_with_n P\u2081 t) (prop.instantiate_with_n P\u2082 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 \u22a8 prop.to_vc P\u2081, from P\u2081_ih.left h3.left,\n      show \u22a8 prop.to_vc P\u2082, from P\u2082_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 \u22a8 prop.to_vc (prop.and (prop.instantiate_with_p P\u2081 t) (prop.instantiate_with_p P\u2082 t)),\n      unfold prop.to_vc,\n      apply valid.and.mp,\n      split,\n      show \u22a8 prop.to_vc (prop.instantiate_with_p P\u2081 t), from P\u2081_ih.right h2.left,\n      show \u22a8 prop.to_vc (prop.instantiate_with_p P\u2082 t), from P\u2082_ih.right h2.right\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      split,\n\n      unfold prop.instantiate_with_n,\n      unfold prop.to_vc,\n      assume h1,\n      have h2: \u22a8 prop.to_vc (prop.or (prop.instantiate_with_n P\u2081 t) (prop.instantiate_with_n P\u2082 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\u2081_ih.left h3,\n\n      apply valid.or.right,\n      from P\u2082_ih.left h4,\n\n      unfold prop.instantiate_with_p,\n      unfold prop.to_vc,\n      assume h1,\n      change \u22a8 prop.to_vc (prop.or (prop.instantiate_with_p P\u2081 t) (prop.instantiate_with_p P\u2082 t)),\n      unfold prop.to_vc,\n      cases valid.or.elim h1 with h3 h4,\n\n      apply valid.or.left,\n      from P\u2081_ih.right h3,\n\n      apply valid.or.right,\n      from P\u2082_ih.right h4\n    },\n    case prop.pre t\u2081 t\u2082 {\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\u2081 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\u2082 op t\u2081 t\u2082 {\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\u2081 t\u2082 {\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\u2081 P\u2081_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 \u22a8 prop.to_vc (prop.and (prop.forallc y P\u2081) (prop.substt y (t.x) P\u2081)),\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\u2081) = prop.to_vc (prop.substt y (t.x) P\u2081)),\n      from substt_distrib_to_vc,\n      rw[\u2190h2],\n      from valid.univ.mpr h1 t.x\n    },\n    case prop.exis y P\u2081 P\u2081_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  \u2200P: prop, (\u22a8 (P.instantiate_with_all T).lift_all.to_vc) \u2192 \u22a8 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: \u2115}:\n  \u2200P: prop, (\u22a8 P.instantiate_rep n) \u2192 \u22a8 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)   \u21d2   inst_p(P)\n--         \u21d8    \u21d7  \n--     \u21d1      P      \u21d3\n--         \u21d7    \u21d8 \n-- erased_n(P)  \u21d2  erased_p(P)\n\nlemma to_vc_valid_of_instantiated_n_valid {P: prop}:\n  (\u22a8 P.instantiated_n) \u2192 \u22a8 P.to_vc :=\n  assume : \u22a8 P.instantiated_n,\n  have \u22a8 P.instantiate_rep P.max_nesting_level, by { unfold prop.instantiated_n at this, from this },\n  have \u22a8 P.lift_all.to_vc, from lifted_all_to_vc_valid_of_instantiate_rep_valid P this,\n  show \u22a8 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  \u27ea P \u27eb \u2192 \u2983 P \u2984 :=\n  assume h1: \u27ea P \u27eb,\n  assume \u03c3: env,\n  assume h2: closed_subst \u03c3 P,\n  have h3: \u22a8 (prop.subst_env \u03c3 P).instantiated_n, from h1 \u03c3 h2,\n  have h4: \u22a8 (prop.subst_env \u03c3 P).to_vc, from to_vc_valid_of_instantiated_n_valid h3,\n  have h5: (vc.subst_env \u03c3 (prop.to_vc P) = prop.to_vc (prop.subst_env \u03c3 P)),\n  from subst_env_distrib_to_vc,\n  show \u22a8 vc.subst_env \u03c3 (prop.to_vc P), from h5.symm \u25b8 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": "import UserDeriving.Simple\n\ninductive Foo where\n  | mk\u2081\n  | mk\u2082\n  deriving Simple, Inhabited /- Creates `Foo.test`, and then runs builtin handler. -/\n\nexample : Foo.test = 0 := by 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/pkg/deriving/UserDeriving/Tst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.04742587738497126, "lm_q1q2_score": 0.01395340319462464}}
{"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.Check\nimport Lean.Meta.CollectFVars\nimport Lean.Meta.Match.MatcherInfo\nimport Lean.Meta.Match.CaseArraySizes\n\nnamespace Lean.Meta.Match\n\ndef mkNamedPattern (x h p : Expr) : MetaM Expr :=\n  mkAppM ``namedPattern #[x, p, h]\n\ndef isNamedPattern (e : Expr) : Bool :=\n  let e := e.consumeMData\n  e.getAppNumArgs == 4 && e.getAppFn.consumeMData.isConstOf ``namedPattern\n\ndef isNamedPattern? (e : Expr) : Option Expr :=\n  let e := e.consumeMData\n  if e.getAppNumArgs == 4 && e.getAppFn.consumeMData.isConstOf ``namedPattern then\n    some e\n  else\n    none\n\ninductive Pattern : Type where\n  | inaccessible (e : Expr) : Pattern\n  | var          (fvarId : FVarId) : Pattern\n  | ctor         (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern\n  | val          (e : Expr) : Pattern\n  | arrayLit     (type : Expr) (xs : List Pattern) : Pattern\n  | as           (varId : FVarId) (p : Pattern) (hId : FVarId) : Pattern\n  deriving Inhabited\n\nnamespace Pattern\n\npartial def toMessageData : Pattern \u2192 MessageData\n  | inaccessible e         => m!\".({e})\"\n  | var varId              => mkFVar varId\n  | ctor ctorName _ _ []   => ctorName\n  | ctor ctorName _ _ pats => m!\"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ \" \" ++ toMessageData pat) Format.nil})\"\n  | val e                  => e\n  | arrayLit _ pats        => m!\"#[{MessageData.joinSep (pats.map toMessageData) \", \"}]\"\n  | as varId p _           => m!\"{mkFVar varId}@{toMessageData p}\"\n\npartial def toExpr (p : Pattern) (annotate := false) : MetaM Expr :=\n  visit p\nwhere\n  visit (p : Pattern) := do\n    match p with\n    | inaccessible e                 =>\n      if annotate then\n        pure (mkInaccessible e)\n      else\n        pure e\n    | var fvarId                     => pure $ mkFVar fvarId\n    | val e                          => pure e\n    | as fvarId p hId                =>\n      -- TODO\n      if annotate then\n        mkNamedPattern (mkFVar fvarId) (mkFVar hId) (\u2190 visit p)\n      else\n        visit p\n    | arrayLit type xs               =>\n      let xs \u2190 xs.mapM visit\n      mkArrayLit type xs\n    | ctor ctorName us params fields =>\n      let fields \u2190 fields.mapM visit\n      pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray\n\n/-- Apply the free variable substitution `s` to the given pattern -/\npartial def applyFVarSubst (s : FVarSubst) : Pattern \u2192 Pattern\n  | inaccessible e  => inaccessible $ s.apply e\n  | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s)\n  | val e           => val $ s.apply e\n  | arrayLit t xs   => arrayLit (s.apply t) $ xs.map (applyFVarSubst s)\n  | var fvarId      => match s.find? fvarId with\n    | some e => inaccessible e\n    | none   => var fvarId\n  | as fvarId p hId => match s.find? fvarId with\n    | none   => as fvarId (applyFVarSubst s p) hId\n    | some _ => applyFVarSubst s p\n\ndef replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern :=\n  let s : FVarSubst := {}\n  p.applyFVarSubst (s.insert fvarId v)\n\npartial def hasExprMVar : Pattern \u2192 Bool\n  | inaccessible e => e.hasExprMVar\n  | ctor _ _ ps fs => ps.any (\u00b7.hasExprMVar) || fs.any hasExprMVar\n  | val e          => e.hasExprMVar\n  | as _ p _       => hasExprMVar p\n  | arrayLit t xs  => t.hasExprMVar || xs.any hasExprMVar\n  | _              => false\n\n\npartial def collectFVars (p : Pattern) : StateRefT CollectFVars.State MetaM Unit := do\n  match p with\n  | inaccessible e => e.collectFVars\n  | ctor _ _ ps fs =>\n    ps.forM fun p => p.collectFVars\n    fs.forM collectFVars\n  | val e => e.collectFVars\n  | arrayLit t xs => t.collectFVars; xs.forM collectFVars\n  | as fvarId\u2081 p fvarId\u2082 => modify (\u00b7.add fvarId\u2081 |>.add fvarId\u2082); p.collectFVars\n  | var fvarId => modify (\u00b7.add fvarId)\n\nend Pattern\n\npartial def instantiatePatternMVars : Pattern \u2192 MetaM Pattern\n  | Pattern.inaccessible e      => return Pattern.inaccessible (\u2190 instantiateMVars e)\n  | Pattern.val e               => return Pattern.val (\u2190 instantiateMVars e)\n  | Pattern.ctor n us ps fields => return Pattern.ctor n us (\u2190 ps.mapM instantiateMVars) (\u2190 fields.mapM instantiatePatternMVars)\n  | Pattern.as x p h            => return Pattern.as x (\u2190 instantiatePatternMVars p) h\n  | Pattern.arrayLit t xs       => return Pattern.arrayLit (\u2190 instantiateMVars t) (\u2190 xs.mapM instantiatePatternMVars)\n  | p                   => return p\n\nstructure AltLHS where\n  ref        : Syntax\n  fvarDecls  : List LocalDecl -- Free variables used in the patterns.\n  patterns   : List Pattern   -- We use `List Pattern` since we have nary match-expressions.\n\ndef AltLHS.collectFVars (altLHS: AltLHS) : StateRefT CollectFVars.State MetaM Unit := do\n  altLHS.fvarDecls.forM fun fvarDecl => fvarDecl.collectFVars\n  altLHS.patterns.forM fun p => p.collectFVars\n\ndef instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS :=\n  return { altLHS with\n    fvarDecls := (\u2190 altLHS.fvarDecls.mapM instantiateLocalDeclMVars),\n    patterns  := (\u2190 altLHS.patterns.mapM instantiatePatternMVars)\n  }\n\n/-- `Match` alternative -/\nstructure Alt where\n  /-- `Syntax` object for providing position information -/\n  ref       : Syntax\n  /--\n  Orginal alternative index. Alternatives can be split, this index is the original\n  position of the alternative that generated this one.\n  -/\n  idx       : Nat\n  /--\n  Right-hand-side of the alternative.\n  -/\n  rhs       : Expr\n  /--\n  Alternative pattern variables.\n  -/\n  fvarDecls : List LocalDecl\n  /--\n  Alternative patterns.\n  -/\n  patterns  : List Pattern\n  /--\n  Pending constraints `lhs \u224b rhs` that need to be solved before the alternative\n  is considered acceptable. We generate them when processing inaccessible patterns.\n  Note that `lhs` and `rhs` often have different types.\n  After we perform additional case analysis, their types become definitionally equal.\n  -/\n  cnstrs    : List (Expr \u00d7 Expr)\n  deriving Inhabited\n\nnamespace Alt\n\npartial def toMessageData (alt : Alt) : MetaM MessageData := do\n  withExistingLocalDecls alt.fvarDecls do\n    let msg := alt.fvarDecls.map fun d => m!\"{d.toExpr}:({d.type})\"\n    let mut msg := m!\"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}\"\n    for (lhs, rhs) in alt.cnstrs do\n      msg := m!\"{msg}\\n  | {lhs} \u224b {rhs}\"\n    addMessageContext msg\n\ndef applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt :=\n  { alt with\n    patterns  := alt.patterns.map fun p => p.applyFVarSubst s,\n    fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s,\n    rhs       := alt.rhs.applyFVarSubst s\n    cnstrs    := alt.cnstrs.map fun (lhs, rhs) => (lhs.applyFVarSubst s, rhs.applyFVarSubst s) }\n\ndef replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt :=\n  { alt with\n    patterns  := alt.patterns.map fun p => p.replaceFVarId fvarId v,\n    rhs       := alt.rhs.replaceFVarId fvarId v\n    fvarDecls :=\n      let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId\n      decls.map (\u00b7.replaceFVarId fvarId v)\n    cnstrs    := alt.cnstrs.map fun (lhs, rhs) => (lhs.replaceFVarId fvarId v, rhs.replaceFVarId fvarId v) }\n\n/-- Return `true` if `fvarId` is one of the alternative pattern variables -/\ndef isLocalDecl (fvarId : FVarId) (alt : Alt) : Bool :=\n   alt.fvarDecls.any fun d => d.fvarId == fvarId\n\n/--\n  Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`.\n  This extra check is necessary when performing dependent elimination and inaccessible terms have been used.\n  For example, consider the following code fragment:\n\n```\ninductive Vec (\u03b1 : Type u) : Nat \u2192 Type u where\n  | nil : Vec \u03b1 0\n  | cons {n} (head : \u03b1) (tail : Vec \u03b1 n) : Vec \u03b1 (n+1)\n\ninductive VecPred {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 Vec \u03b1 n \u2192 Prop where\n  | nil   : VecPred P Vec.nil\n  | cons  {n : Nat} {head : \u03b1} {tail : Vec \u03b1 n} : P head \u2192 VecPred P tail \u2192 VecPred P (Vec.cons head tail)\n\ntheorem ex {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 (v : Vec \u03b1 (n+1)) \u2192 VecPred P v \u2192 Exists P\n  | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => \u27e8head, h\u27e9\n```\nRecall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term.\nThe elaborator uses an inaccessible term when typing constraints restrict its value.\nThus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)`\nbecause the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`.\nAfter elaboration the alternative becomes:\n```\n  | .(0), @Vec.cons .(\u03b1) .(0) head .(Vec.nil), @VecPred.cons .(\u03b1) .(P) .(0) .(head) .(Vec.nil) h w => \u27e8head, h\u27e9\n```\nwhere\n```\n(head : \u03b1), (h: P head), (w : VecPred P Vec.nil)\n```\nThen, when we process this alternative in this module, the following check will detect that\n`w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`.\nNote that if we had written\n```\ntheorem ex {\u03b1 : Type u} (P : \u03b1 \u2192 Prop) : {n : Nat} \u2192 (v : Vec \u03b1 (n+1)) \u2192 VecPred P v \u2192 Exists P\n  | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => \u27e8head, h\u27e9\n```\nwe would get the easier to digest error message\n```\nmissing cases:\n_, (Vec.cons _ _ (Vec.cons _ _ _)), _\n```\n-/\ndef checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do\n  match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with\n  | none          => throwErrorAt alt.ref \"unknown free pattern variable\"\n  | some fvarDecl => do\n    let vType \u2190 inferType v\n    unless (\u2190 isDefEqGuarded fvarDecl.type vType) do\n      withExistingLocalDecls alt.fvarDecls do\n        let (expectedType, givenType) \u2190 addPPExplicitToExposeDiff vType fvarDecl.type\n        throwErrorAt alt.ref \"type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\\nexpected type{indentExpr expectedType}\"\n    return replaceFVarId fvarId v alt\n\nend Alt\n\ninductive Example where\n  | var        : FVarId \u2192 Example\n  | underscore : Example\n  | ctor       : Name \u2192 List Example \u2192 Example\n  | val        : Expr \u2192 Example\n  | arrayLit   : List Example \u2192 Example\n\nnamespace Example\n\npartial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example \u2192 Example\n  | var x        => if x == fvarId then ex else var x\n  | ctor n exs   => ctor n $ exs.map (replaceFVarId fvarId ex)\n  | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex)\n  | ex           => ex\n\npartial def applyFVarSubst (s : FVarSubst) : Example \u2192 Example\n  | var fvarId =>\n    match s.get fvarId with\n    | Expr.fvar fvarId' => var fvarId'\n    | _                 => underscore\n  | ctor n exs   => ctor n $ exs.map (applyFVarSubst s)\n  | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s)\n  | ex           => ex\n\npartial def varsToUnderscore : Example \u2192 Example\n  | var _        => underscore\n  | ctor n exs   => ctor n $ exs.map varsToUnderscore\n  | arrayLit exs => arrayLit $ exs.map varsToUnderscore\n  | ex           => ex\n\npartial def toMessageData : Example \u2192 MessageData\n  | var fvarId        => mkFVar fvarId\n  | ctor ctorName []  => mkConst ctorName\n  | ctor ctorName exs => m!\"({mkConst ctorName}{exs.foldl (fun msg pat => m!\"{msg} {toMessageData pat}\") Format.nil})\"\n  | arrayLit exs      => \"#\" ++ MessageData.ofList (exs.map toMessageData)\n  | val e             => e\n  | underscore        => \"_\"\n\nend Example\n\ndef examplesToMessageData (cex : List Example) : MessageData :=\n  MessageData.joinSep (cex.map (Example.toMessageData \u2218 Example.varsToUnderscore)) \", \"\n\nstructure Problem where\n  mvarId        : MVarId\n  vars          : List Expr\n  alts          : List Alt\n  examples      : List Example\n  deriving Inhabited\n\ndef withGoalOf {\u03b1} (p : Problem) (x : MetaM \u03b1) : MetaM \u03b1 :=\n  p.mvarId.withContext x\n\ndef Problem.toMessageData (p : Problem) : MetaM MessageData :=\n  withGoalOf p do\n    let alts \u2190 p.alts.mapM Alt.toMessageData\n    let vars \u2190 p.vars.mapM fun x => do let xType \u2190 inferType x; pure m!\"{x}:({xType})\"\n    return m!\"remaining variables: {vars}\\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\\nexamples:{examplesToMessageData p.examples}\\n\"\n\nabbrev CounterExample := List Example\n\ndef counterExampleToMessageData (cex : CounterExample) : MessageData :=\n  examplesToMessageData cex\n\ndef counterExamplesToMessageData (cexs : List CounterExample) : MessageData :=\n  MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line\n\nstructure MatcherResult where\n  matcher         : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables.\n  counterExamples : List CounterExample\n  unusedAltIdxs   : List Nat\n  addMatcher      : MetaM Unit\n\n/--\n  Convert a expression occurring as the argument of a `match` motive application back into a `Pattern`\n  For example, we can use this method to convert `x::y::xs` at\n  ```\n  ...\n  (motive : List Nat \u2192 Sort u_1) (xs : List Nat) (h_1 : (x y : Nat) \u2192 (xs : List Nat) \u2192 motive (x :: y :: xs))\n  ...\n  ```\n  into a pattern object\n-/\npartial def toPattern (e : Expr) : MetaM Pattern := do\n  match inaccessible? e with\n  | some t => return Pattern.inaccessible t\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) =>\n      return Pattern.arrayLit \u03b1 (\u2190 lits.mapM toPattern)\n    | none =>\n      if let some e := isNamedPattern? e then\n        let p \u2190 toPattern <| e.getArg! 2\n        match e.getArg! 1, e.getArg! 3 with\n        | Expr.fvar x, Expr.fvar h => return Pattern.as x p h\n        | _,           _   => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if isMatchValue e then\n        return Pattern.val e\n      else if e.isFVar then\n        return Pattern.var e.fvarId!\n      else\n        let newE \u2190 whnf e\n        if newE != e then\n          toPattern newE\n        else matchConstCtor e.getAppFn (fun _ => throwError \"unexpected pattern{indentExpr e}\") fun v us => do\n          let args := e.getAppArgs\n          unless args.size == v.numParams + v.numFields do\n            throwError \"unexpected pattern{indentExpr e}\"\n          let params := args.extract 0 v.numParams\n          let fields := args.extract v.numParams args.size\n          let fields \u2190 fields.mapM toPattern\n          return Pattern.ctor v.name us params.toList fields.toList\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/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.061875990480993785, "lm_q1q2_score": 0.01394787573171279}}
{"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.Basic\n\nnamespace Lean.Meta\n\nstructure AuxLemmas where\n  idx    : Nat := 1\n  lemmas : Std.PHashMap Expr (Name \u00d7 List Name) := {}\n  deriving Inhabited\n\nbuiltin_initialize auxLemmasExt : EnvExtension AuxLemmas \u2190 registerEnvExtension (pure {})\n\n/--\n  Helper method for creating auxiliary lemmas in the environment.\n\n  It uses a cache that maps `type` to declaration name. The cache is not stored in `.olean` files.\n  It is useful to make sure the same auxiliary lemma is not created over and over again in the same file.\n\n  This method is useful for tactics (e.g., `simp`) that may perform preprocessing steps to lemmas provided by\n  users. For example, `simp` preprocessor may convert a lemma into multiple ones.\n-/\ndef mkAuxLemma (levelParams : List Name) (type : Expr) (value : Expr) : MetaM Name := do\n  let env \u2190 getEnv\n  let s \u2190 auxLemmasExt.getState env\n  let mkNewAuxLemma := do\n    let auxName := Name.mkNum (env.mainModule ++ `_auxLemma) s.idx\n    addDecl <| Declaration.thmDecl {\n      name        := auxName\n      levelParams := levelParams\n      type        := type\n      value       := value\n    }\n    modifyEnv fun env => auxLemmasExt.modifyState env fun \u27e8idx, lemmas\u27e9 => \u27e8idx + 1, lemmas.insert type (auxName, levelParams)\u27e9\n    return auxName\n  match s.lemmas.find? type with\n  | some (name, levelParams') => if levelParams == levelParams' then return name else mkNewAuxLemma\n  | none => mkNewAuxLemma\n\nend Lean.Meta", "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/AuxLemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.051845463719763736, "lm_q1q2_score": 0.013943392704379772}}
{"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 {\u03b1 : Type u_1} : coe = some := rfl\n\ntheorem some_ne_none {\u03b1 : Type u_1} (x : \u03b1) : some x \u2260 none :=\n  fun (h : some x = none) => option.no_confusion h\n\n@[simp] theorem get_mem {\u03b1 : Type u_1} {o : Option \u03b1} (h : \u21a5(is_some o)) : get h \u2208 o :=\n  option.cases_on o\n    (fun (h : \u21a5(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 : \u03b1) (h : \u21a5(is_some (some o))) => idRhs (some o = some o) rfl) h\n\ntheorem get_of_mem {\u03b1 : Type u_1} {a : \u03b1} {o : Option \u03b1} (h : \u21a5(is_some o)) : a \u2208 o \u2192 get h = a :=\n  sorry\n\n@[simp] theorem not_mem_none {\u03b1 : Type u_1} (a : \u03b1) : \u00aca \u2208 none :=\n  fun (h : a \u2208 none) => option.no_confusion h\n\n@[simp] theorem some_get {\u03b1 : Type u_1} {x : Option \u03b1} (h : \u21a5(is_some x)) : some (get h) = x :=\n  option.cases_on x\n    (fun (h : \u21a5(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 : \u03b1) (h : \u21a5(is_some (some x))) => idRhs (some (get h) = some (get h)) rfl) h\n\n@[simp] theorem get_some {\u03b1 : Type u_1} (x : \u03b1) (h : \u21a5(is_some (some x))) : get h = x := rfl\n\n@[simp] theorem get_or_else_some {\u03b1 : Type u_1} (x : \u03b1) (y : \u03b1) : get_or_else (some x) y = x := rfl\n\n@[simp] theorem get_or_else_coe {\u03b1 : Type u_1} (x : \u03b1) (y : \u03b1) : get_or_else (\u2191x) y = x := rfl\n\ntheorem get_or_else_of_ne_none {\u03b1 : Type u_1} {x : Option \u03b1} (hx : x \u2260 none) (y : \u03b1) :\n    some (get_or_else x y) = x :=\n  sorry\n\ntheorem mem_unique {\u03b1 : Type u_1} {o : Option \u03b1} {a : \u03b1} {b : \u03b1} (ha : a \u2208 o) (hb : b \u2208 o) :\n    a = b :=\n  some.inj (Eq.trans (Eq.symm ha) hb)\n\ntheorem some_injective (\u03b1 : Type u_1) : function.injective some :=\n  fun (_x _x_1 : \u03b1) => iff.mp some_inj\n\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} (Hf : function.injective f) :\n    function.injective (option.map f) :=\n  sorry\n\ntheorem ext {\u03b1 : Type u_1} {o\u2081 : Option \u03b1} {o\u2082 : Option \u03b1} :\n    (\u2200 (a : \u03b1), a \u2208 o\u2081 \u2194 a \u2208 o\u2082) \u2192 o\u2081 = o\u2082 :=\n  sorry\n\ntheorem eq_none_iff_forall_not_mem {\u03b1 : Type u_1} {o : Option \u03b1} : o = none \u2194 \u2200 (a : \u03b1), \u00aca \u2208 o :=\n  sorry\n\n@[simp] theorem none_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 Option \u03b2) : none >>= f = none :=\n  rfl\n\n@[simp] theorem some_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} (a : \u03b1) (f : \u03b1 \u2192 Option \u03b2) :\n    some a >>= f = f a :=\n  rfl\n\n@[simp] theorem none_bind' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 Option \u03b2) :\n    option.bind none f = none :=\n  rfl\n\n@[simp] theorem some_bind' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (a : \u03b1) (f : \u03b1 \u2192 Option \u03b2) :\n    option.bind (some a) f = f a :=\n  rfl\n\n@[simp] theorem bind_some {\u03b1 : Type u_1} (x : Option \u03b1) : x >>= some = x := bind_pure\n\n@[simp] theorem bind_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2}\n    {b : \u03b2} : x >>= f = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = some b :=\n  sorry\n\n@[simp] theorem bind_eq_some' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2}\n    {b : \u03b2} : option.bind x f = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = some b :=\n  sorry\n\n@[simp] theorem bind_eq_none' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {o : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} :\n    option.bind o f = none \u2194 \u2200 (b : \u03b2) (a : \u03b1), a \u2208 o \u2192 \u00acb \u2208 f a :=\n  sorry\n\n@[simp] theorem bind_eq_none {\u03b1 : Type u_1} {\u03b2 : Type u_1} {o : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} :\n    o >>= f = none \u2194 \u2200 (b : \u03b2) (a : \u03b1), a \u2208 o \u2192 \u00acb \u2208 f a :=\n  bind_eq_none'\n\ntheorem bind_comm {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {f : \u03b1 \u2192 \u03b2 \u2192 Option \u03b3} (a : Option \u03b1)\n    (b : Option \u03b2) :\n    (option.bind a fun (x : \u03b1) => option.bind b (f x)) =\n        option.bind b fun (y : \u03b2) => option.bind a fun (x : \u03b1) => f x y :=\n  sorry\n\ntheorem bind_assoc {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (x : Option \u03b1) (f : \u03b1 \u2192 Option \u03b2)\n    (g : \u03b2 \u2192 Option \u03b3) :\n    option.bind (option.bind x f) g = option.bind x fun (y : \u03b1) => option.bind (f y) g :=\n  option.cases_on x (Eq.refl (option.bind (option.bind none f) g))\n    fun (x : \u03b1) => Eq.refl (option.bind (option.bind (some x) f) g)\n\ntheorem join_eq_some {\u03b1 : Type u_1} {x : Option (Option \u03b1)} {a : \u03b1} :\n    join x = some a \u2194 x = some (some a) :=\n  sorry\n\ntheorem join_ne_none {\u03b1 : Type u_1} {x : Option (Option \u03b1)} :\n    join x \u2260 none \u2194 \u2203 (z : \u03b1), x = some (some z) :=\n  sorry\n\ntheorem join_ne_none' {\u03b1 : Type u_1} {x : Option (Option \u03b1)} :\n    \u00acjoin x = none \u2194 \u2203 (z : \u03b1), x = some (some z) :=\n  sorry\n\ntheorem bind_id_eq_join {\u03b1 : Type u_1} {x : Option (Option \u03b1)} : x >>= id = join x := sorry\n\ntheorem join_eq_join {\u03b1 : Type u_1} : mjoin = join := sorry\n\ntheorem bind_eq_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} {f : \u03b1 \u2192 Option \u03b2} {x : Option \u03b1} :\n    x >>= f = option.bind x f :=\n  rfl\n\n@[simp] theorem map_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_1} {f : \u03b1 \u2192 \u03b2} :\n    Functor.map f = option.map f :=\n  rfl\n\ntheorem map_none {\u03b1 : Type u_1} {\u03b2 : Type u_1} {f : \u03b1 \u2192 \u03b2} : f <$> none = none := rfl\n\ntheorem map_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> some a = some (f a) :=\n  rfl\n\n@[simp] theorem map_none' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} : option.map f none = none :=\n  rfl\n\n@[simp] theorem map_some' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} :\n    option.map f (some a) = some (f a) :=\n  rfl\n\ntheorem map_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} :\n    f <$> x = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = b :=\n  sorry\n\n@[simp] theorem map_eq_some' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} :\n    option.map f x = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = b :=\n  sorry\n\ntheorem map_eq_none {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} :\n    f <$> x = none \u2194 x = none :=\n  sorry\n\n@[simp] theorem map_eq_none' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} :\n    option.map f x = none \u2194 x = none :=\n  sorry\n\ntheorem map_congr {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b1 \u2192 \u03b2} {x : Option \u03b1}\n    (h : \u2200 (a : \u03b1), a \u2208 x \u2192 f a = g a) : option.map f x = option.map g x :=\n  sorry\n\n@[simp] theorem map_id' {\u03b1 : Type u_1} : option.map id = id := map_id\n\n@[simp] theorem map_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2)\n    (x : Option \u03b1) : option.map h (option.map g x) = option.map (h \u2218 g) x :=\n  sorry\n\ntheorem comp_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2)\n    (x : Option \u03b1) : option.map (h \u2218 g) x = option.map h (option.map g x) :=\n  Eq.symm (map_map h g x)\n\n@[simp] theorem map_comp_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) :\n    option.map g \u2218 option.map f = option.map (g \u2218 f) :=\n  sorry\n\ntheorem mem_map_of_mem {\u03b1 : Type u_1} {\u03b2 : Type u_2} {a : \u03b1} {x : Option \u03b1} (g : \u03b1 \u2192 \u03b2)\n    (h : a \u2208 x) : g a \u2208 option.map g x :=\n  iff.mpr mem_def (Eq.symm (iff.mp mem_def h) \u25b8 map_some')\n\ntheorem bind_map_comm {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option (Option \u03b1)} {f : \u03b1 \u2192 \u03b2} :\n    x >>= option.map f = option.map (option.map f) x >>= id :=\n  sorry\n\ntheorem join_map_eq_map_join {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {x : Option (Option \u03b1)} :\n    join (option.map (option.map f) x) = option.map f (join x) :=\n  sorry\n\ntheorem join_join {\u03b1 : Type u_1} {x : Option (Option (Option \u03b1))} :\n    join (join x) = join (option.map join x) :=\n  sorry\n\ntheorem mem_of_mem_join {\u03b1 : Type u_1} {a : \u03b1} {x : Option (Option \u03b1)} (h : a \u2208 join x) :\n    some a \u2208 x :=\n  iff.mpr mem_def (Eq.symm (iff.mp mem_def h) \u25b8 iff.mp join_eq_some h)\n\n@[simp] theorem pbind_eq_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 Option \u03b2) (x : Option \u03b1) :\n    (pbind x fun (a : \u03b1) (_x : a \u2208 x) => f a) = option.bind x f :=\n  sorry\n\ntheorem map_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1)\n    (g : \u03b1 \u2192 Option \u03b2) :\n    option.map f (x >>= g) =\n        do \n          let a \u2190 x \n          option.map f (g a) :=\n  sorry\n\ntheorem map_bind' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1)\n    (g : \u03b1 \u2192 Option \u03b2) :\n    option.map f (option.bind x g) = option.bind x fun (a : \u03b1) => option.map f (g a) :=\n  sorry\n\ntheorem map_pbind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1)\n    (g : (a : \u03b1) \u2192 a \u2208 x \u2192 Option \u03b2) :\n    option.map f (pbind x g) = pbind x fun (a : \u03b1) (H : a \u2208 x) => option.map f (g a H) :=\n  sorry\n\ntheorem pbind_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (x : Option \u03b1)\n    (g : (b : \u03b2) \u2192 b \u2208 option.map f x \u2192 Option \u03b3) :\n    pbind (option.map f x) g = pbind x fun (a : \u03b1) (h : a \u2208 x) => g (f a) (mem_map_of_mem f h) :=\n  option.cases_on x\n    (fun (g : (b : \u03b2) \u2192 b \u2208 option.map f none \u2192 Option \u03b3) => Eq.refl (pbind (option.map f none) g))\n    (fun (x : \u03b1) (g : (b : \u03b2) \u2192 b \u2208 option.map f (some x) \u2192 Option \u03b3) =>\n      Eq.refl (pbind (option.map f (some x)) g))\n    g\n\n@[simp] theorem pmap_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2)\n    {H : \u2200 (a : \u03b1), a \u2208 none \u2192 p a} : pmap f none H = none :=\n  rfl\n\n@[simp] theorem pmap_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2)\n    {x : \u03b1} (h : p x) : pmap f (some x) = fun (_x : \u2200 (a : \u03b1), a \u2208 some x \u2192 p a) => some (f x h) :=\n  rfl\n\ntheorem mem_pmem {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (x : Option \u03b1)\n    {a : \u03b1} (h : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) (ha : a \u2208 x) : f a (h a ha) \u2208 pmap f x h :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (f a (h a ha) \u2208 pmap f x h)) (propext mem_def)))\n    (Eq._oldrec\n      (fun (h : \u2200 (a_1 : \u03b1), a_1 \u2208 some a \u2192 p a_1) (ha : a \u2208 some a) => Eq.refl (pmap f (some a) h))\n      (Eq.symm (eq.mp (Eq._oldrec (Eq.refl (a \u2208 x)) (propext mem_def)) ha)) h ha)\n\ntheorem pmap_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2)\n    (g : \u03b3 \u2192 \u03b1) (x : Option \u03b3) (H : \u2200 (a : \u03b1), a \u2208 option.map g x \u2192 p a) :\n    pmap f (option.map g x) H =\n        pmap (fun (a : \u03b3) (h : p (g a)) => f (g a) h) x\n          fun (a : \u03b3) (h : a \u2208 x) => H (g a) (mem_map_of_mem g h) :=\n  sorry\n\ntheorem map_pmap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {p : \u03b1 \u2192 Prop} (g : \u03b2 \u2192 \u03b3)\n    (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (x : Option \u03b1) (H : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) :\n    option.map g (pmap f x H) = pmap (fun (a : \u03b1) (h : p a) => g (f a h)) x H :=\n  sorry\n\n@[simp] theorem pmap_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (p : \u03b1 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) (x : Option \u03b1)\n    (H : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) : pmap (fun (a : \u03b1) (_x : p a) => f a) x H = option.map f x :=\n  sorry\n\ntheorem pmap_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} {x : Option \u03b1} {g : \u03b1 \u2192 Option \u03b2}\n    {p : \u03b2 \u2192 Prop} {f : (b : \u03b2) \u2192 p b \u2192 \u03b3} (H : \u2200 (a : \u03b2), a \u2208 x >>= g \u2192 p a)\n    (H' : \u2200 (a : \u03b1) (b : \u03b2), b \u2208 g a \u2192 b \u2208 x >>= g) :\n    pmap f (x >>= g) H =\n        do \n          let a \u2190 x \n          pmap f (g a) fun (b : \u03b2) (h : b \u2208 g a) => H b (H' a b h) :=\n  sorry\n\ntheorem bind_pmap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_2} {p : \u03b1 \u2192 Prop}\n    (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (x : Option \u03b1) (g : \u03b2 \u2192 Option \u03b3) (H : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) :\n    pmap f x H >>= g = pbind x fun (a : \u03b1) (h : a \u2208 x) => g (f a (H a h)) :=\n  sorry\n\ntheorem pbind_eq_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : (a : \u03b1) \u2192 a \u2208 x \u2192 Option \u03b2}\n    (h' : \u2200 (a : \u03b1) (H : a \u2208 x), f a H = none \u2192 x = none) : pbind x f = none \u2194 x = none :=\n  sorry\n\ntheorem pbind_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : (a : \u03b1) \u2192 a \u2208 x \u2192 Option \u03b2}\n    {y : \u03b2} : pbind x f = some y \u2194 \u2203 (z : \u03b1), \u2203 (H : z \u2208 x), f z H = some y :=\n  sorry\n\n@[simp] theorem pmap_eq_none_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop}\n    {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {x : Option \u03b1} {h : \u2200 (a : \u03b1), a \u2208 x \u2192 p a} :\n    pmap f x h = none \u2194 x = none :=\n  sorry\n\n@[simp] theorem pmap_eq_some_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop}\n    {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {x : Option \u03b1} {hf : \u2200 (a : \u03b1), a \u2208 x \u2192 p a} {y : \u03b2} :\n    pmap f x hf = some y \u2194 \u2203 (a : \u03b1), \u2203 (H : x = some a), f a (hf a H) = y :=\n  sorry\n\n@[simp] theorem join_pmap_eq_pmap_join {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop}\n    {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {x : Option (Option \u03b1)}\n    (H : \u2200 (a : Option \u03b1), a \u2208 x \u2192 \u2200 (a_1 : \u03b1), a_1 \u2208 a \u2192 p a_1) :\n    join (pmap (pmap f) x H) =\n        pmap f (join x) fun (a : \u03b1) (h : a \u2208 join x) => H (some a) (mem_of_mem_join h) a rfl :=\n  sorry\n\n@[simp] theorem seq_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} :\n    some f <*> some a = some (f a) :=\n  rfl\n\n@[simp] theorem some_orelse' {\u03b1 : Type u_1} (a : \u03b1) (x : Option \u03b1) :\n    option.orelse (some a) x = some a :=\n  rfl\n\n@[simp] theorem some_orelse {\u03b1 : Type u_1} (a : \u03b1) (x : Option \u03b1) : (some a <|> x) = some a := rfl\n\n@[simp] theorem none_orelse' {\u03b1 : Type u_1} (x : Option \u03b1) : option.orelse none x = x :=\n  option.cases_on x (Eq.refl (option.orelse none none))\n    fun (x : \u03b1) => Eq.refl (option.orelse none (some x))\n\n@[simp] theorem none_orelse {\u03b1 : Type u_1} (x : Option \u03b1) : (none <|> x) = x := none_orelse' x\n\n@[simp] theorem orelse_none' {\u03b1 : Type u_1} (x : Option \u03b1) : option.orelse x none = x :=\n  option.cases_on x (Eq.refl (option.orelse none none))\n    fun (x : \u03b1) => Eq.refl (option.orelse (some x) none)\n\n@[simp] theorem orelse_none {\u03b1 : Type u_1} (x : Option \u03b1) : (x <|> none) = x := orelse_none' x\n\n@[simp] theorem is_some_none {\u03b1 : Type u_1} : is_some none = false := rfl\n\n@[simp] theorem is_some_some {\u03b1 : Type u_1} {a : \u03b1} : is_some (some a) = tt := rfl\n\ntheorem is_some_iff_exists {\u03b1 : Type u_1} {x : Option \u03b1} : \u21a5(is_some x) \u2194 \u2203 (a : \u03b1), x = some a :=\n  sorry\n\n@[simp] theorem is_none_none {\u03b1 : Type u_1} : is_none none = tt := rfl\n\n@[simp] theorem is_none_some {\u03b1 : Type u_1} {a : \u03b1} : is_none (some a) = false := rfl\n\n@[simp] theorem not_is_some {\u03b1 : Type u_1} {a : Option \u03b1} : is_some a = false \u2194 is_none a = tt :=\n  sorry\n\ntheorem eq_some_iff_get_eq {\u03b1 : Type u_1} {o : Option \u03b1} {a : \u03b1} :\n    o = some a \u2194 \u2203 (h : \u21a5(is_some o)), get h = a :=\n  sorry\n\ntheorem not_is_some_iff_eq_none {\u03b1 : Type u_1} {o : Option \u03b1} : \u00ac\u21a5(is_some o) \u2194 o = none := sorry\n\ntheorem ne_none_iff_is_some {\u03b1 : Type u_1} {o : Option \u03b1} : o \u2260 none \u2194 \u21a5(is_some o) := sorry\n\ntheorem ne_none_iff_exists {\u03b1 : Type u_1} {o : Option \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), some x = o := sorry\n\ntheorem ne_none_iff_exists' {\u03b1 : Type u_1} {o : Option \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), o = some x :=\n  iff.trans ne_none_iff_exists (exists_congr fun (_x : \u03b1) => eq_comm)\n\ntheorem bex_ne_none {\u03b1 : Type u_1} {p : Option \u03b1 \u2192 Prop} :\n    (\u2203 (x : Option \u03b1), \u2203 (H : x \u2260 none), p x) \u2194 \u2203 (x : \u03b1), p (some x) :=\n  sorry\n\ntheorem ball_ne_none {\u03b1 : Type u_1} {p : Option \u03b1 \u2192 Prop} :\n    (\u2200 (x : Option \u03b1), x \u2260 none \u2192 p x) \u2194 \u2200 (x : \u03b1), p (some x) :=\n  sorry\n\ntheorem iget_mem {\u03b1 : Type u_1} [Inhabited \u03b1] {o : Option \u03b1} : \u21a5(is_some o) \u2192 iget o \u2208 o := sorry\n\ntheorem iget_of_mem {\u03b1 : Type u_1} [Inhabited \u03b1] {a : \u03b1} {o : Option \u03b1} : a \u2208 o \u2192 iget o = a :=\n  sorry\n\n@[simp] theorem guard_eq_some {\u03b1 : Type u_1} {p : \u03b1 \u2192 Prop} [decidable_pred p] {a : \u03b1} {b : \u03b1} :\n    guard p a = some b \u2194 a = b \u2227 p a :=\n  sorry\n\n@[simp] theorem guard_eq_some' {p : Prop} [Decidable p] (u : Unit) : guard p = some u \u2194 p := sorry\n\ntheorem lift_or_get_choice {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} (h : \u2200 (a b : \u03b1), f a b = a \u2228 f a b = b)\n    (o\u2081 : Option \u03b1) (o\u2082 : Option \u03b1) : lift_or_get f o\u2081 o\u2082 = o\u2081 \u2228 lift_or_get f o\u2081 o\u2082 = o\u2082 :=\n  sorry\n\n@[simp] theorem lift_or_get_none_left {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {b : Option \u03b1} :\n    lift_or_get f none b = b :=\n  option.cases_on b (Eq.refl (lift_or_get f none none))\n    fun (b : \u03b1) => Eq.refl (lift_or_get f none (some b))\n\n@[simp] theorem lift_or_get_none_right {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {a : Option \u03b1} :\n    lift_or_get f a none = a :=\n  option.cases_on a (Eq.refl (lift_or_get f none none))\n    fun (a : \u03b1) => Eq.refl (lift_or_get f (some a) none)\n\n@[simp] theorem lift_or_get_some_some {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {a : \u03b1} {b : \u03b1} :\n    lift_or_get f (some a) (some b) = \u2191(f a b) :=\n  rfl\n\n/-- given an element of `a : option \u03b1`, a default element `b : \u03b2` and a function `\u03b1 \u2192 \u03b2`, apply this\nfunction to `a` if it comes from `\u03b1`, and return `b` otherwise. -/\ndef cases_on' {\u03b1 : Type u_1} {\u03b2 : Type u_2} : Option \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2 := sorry\n\n@[simp] theorem cases_on'_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) :\n    cases_on' none x f = x :=\n  rfl\n\n@[simp] theorem cases_on'_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n    cases_on' (some a) x f = f a :=\n  rfl\n\n@[simp] theorem cases_on'_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n    cases_on' (\u2191a) x f = f a :=\n  rfl\n\n@[simp] theorem cases_on'_none_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : Option \u03b1 \u2192 \u03b2) (o : Option \u03b1) :\n    cases_on' o (f none) (f \u2218 coe) = f o :=\n  option.cases_on o (Eq.refl (cases_on' none (f none) (f \u2218 coe)))\n    fun (o : \u03b1) => Eq.refl (cases_on' (some o) (f none) (f \u2218 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 (\u03c3 : Type) (lbl : Type)\n\n@[reducible]\ndef pred := \u03c3 \u2192 Prop\n\nparameters {\u03c3}\n\ninductive code : pred \u2192 pred \u2192 Type\n  | skip {} : \u2200 p, code p p\n  | action : \u2200 p q, set lbl \u2192 lbl \u2192 code p q\n  | seq : \u2200 {p q r}, code p q \u2192 code q r \u2192 code p r\n  | if_then_else : \u2200 p {pa pb q}, set lbl \u2192 pred \u2192 code pa q \u2192 code pb q \u2192 code p q\n  | while : \u2200 {p inv} q, set lbl \u2192 pred \u2192 code p inv \u2192 code inv q\n\nparameters {\u03c3 lbl}\n\n@[pattern,reducible]\ndef if_then_else : \u2200 p {pa pb q}, set lbl \u2192 pred \u2192 code pa q \u2192 code pb q \u2192 code p q :=\ncode.if_then_else\n\n@[pattern,reducible]\ndef while : \u2200 {p inv} q, set lbl \u2192 pred \u2192 code p inv \u2192 code inv q :=\n@code.while\n\ninductive current : \u2200 {p q}, code p q \u2192 Type\n  | action : \u2200 p q s l, current (code.action p q s l)\n  | seq_left : \u2200 p q r (c\u2080 : code p q) (c\u2081 : code q r), current c\u2080 \u2192 current (code.seq c\u2080 c\u2081)\n  | seq_right : \u2200 p q r (c\u2080 : code p q) (c\u2081 : code q r), current c\u2081 \u2192 current (code.seq c\u2080 c\u2081)\n  | ite_cond  : \u2200 p t pa pb q s (c\u2080 : code pa q) (c\u2081 : code pb q),\n         current (code.if_then_else p s t c\u2080 c\u2081)\n  | ite_left  : \u2200 p t pa pb q s (c\u2080 : code pa q) (c\u2081 : code pb q),\n         current c\u2080 \u2192 current (code.if_then_else p s t c\u2080 c\u2081)\n  | ite_right : \u2200 p t pa pb q s (c\u2080 : code pa q) (c\u2081 : code pb q),\n         current c\u2081 \u2192 current (code.if_then_else p s t c\u2080 c\u2081)\n  | while_cond : \u2200 p inv q s w (c : code p inv),\n         current (code.while q s w c)\n  | while_body : \u2200 p inv q s w (c : code p inv),\n         current c \u2192 current (code.while q s w c)\n\n@[reducible]\ndef seq_left {p q r} {c\u2080 : code p q} (c\u2081 : code q r)\n  (cur : current c\u2080)\n: current (code.seq c\u2080 c\u2081) :=\ncurrent.seq_left _ _ _ c\u2080 _ cur\n\n@[reducible]\ndef seq_right {p q r} (c\u2080 : code p q) {c\u2081 : code q r}\n  (cur : current c\u2081)\n: current (code.seq c\u2080 c\u2081) :=\ncurrent.seq_right _ _ _ c\u2080 _ cur\n\n@[reducible]\ndef ite_cond (p t) {pa pb q} (s : set lbl) (c\u2080 : code pa q) (c\u2081 : code pb q)\n: current (if_then_else p s t c\u2080 c\u2081) :=\ncurrent.ite_cond p t _ _ _ s c\u2080 c\u2081\n\n@[reducible]\ndef ite_left (p t) {pa pb q} (s : set lbl) {c\u2080 : code pa q} (c\u2081 : code pb q) (cur\u2080 : current c\u2080)\n: current (if_then_else p s t c\u2080 c\u2081) :=\ncurrent.ite_left p t _ _ _ s c\u2080 c\u2081 cur\u2080\n\n@[reducible]\ndef ite_right (p t : pred) {pa pb q : pred} (s : set lbl)\n  (c\u2080 : code pa q) {c\u2081 : code pb q}\n  (cur\u2081 : current c\u2081)\n: current (if_then_else p s t c\u2080 c\u2081) :=\ncurrent.ite_right p t _ _ _ s c\u2080 c\u2081 cur\u2081\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' : \u03a0 {p q} {c : code p q}, current c \u2192 lbl \u2192 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) \u2192 lbl \u2192 Prop\n  | (some c) := selects' c\n  | none := False\n\ndef is_control' : \u03a0 {p q} {c : code p q}, current c \u2192 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) \u2192 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-- : \u2200 {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\u2080 c\u2081 cur) := is_control_decidable cur\n--   | ._ ._ ._ (current.seq_right p q r c\u2080 c\u2081 cur) := is_control_decidable cur\n--   | ._ ._ ._ (current.ite_cond  p t pa pb q c\u2080 c\u2081) := decidable.true\n--   | ._ ._ ._ (current.ite_left  p t pa pb q c\u2080 c\u2081 cur) := is_control_decidable cur\n--   | ._ ._ ._ (current.ite_right p t pa pb q c\u2080 c\u2081 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' : \u03a0 {p q} {c : code p q} (pc : current c), is_control' pc \u2192 \u03c3 \u2192 Prop\n  | ._ ._ ._ (current.action _ _ _ _) h := by cases h\n  | ._ ._ ._ (current.seq_left  p q r c\u2080 c\u2081 pc) h := condition' pc h\n  | ._ ._ ._ (current.seq_right p q r c\u2080 c\u2081 pc) h := condition' pc h\n  | .(p) .(q) ._ (current.ite_cond  p c pa pb q _ c\u2080 c\u2081) h := c\n  | .(p) .(q) ._ (current.ite_left  p c pa pb q _ c\u2080 c\u2081 pc) h := condition' pc h\n  | .(p) .(q) ._ (current.ite_right p c pa pb q _ c\u2080 c\u2081 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} : \u2200 pc : option $ current c, is_control pc \u2192 \u03c3 \u2192 Prop\n  | (some pc) := condition' pc\n  | none := assume h, by cases h\n\ndef action_of : \u03a0 {p q} {c : code p q} (cur : current c),\n{ p // \u2203 P, condition (some cur) P = p }  \u2295 subtype (selects (some cur))\n  | ._ ._ ._ (current.action _ _ _ l) := sum.inr \u27e8l,rfl\u27e9\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 \u27e8t,rfl,rfl\u27e9\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 \u27e8t,rfl,rfl\u27e9\n  | ._ ._ ._ (current.while_body _ _ _ _ _ _ pc) := action_of pc\n\ndef assert_of' : \u03a0 {p q} {c : code p q}, current c \u2192 \u03c3 \u2192 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) \u2192 \u03c3 \u2192 Prop\n  | none := q\n  | (some pc) := assert_of' pc\n\nlocal attribute [instance] classical.prop_decidable\n\nnoncomputable def next_assert' : \u03a0 {p q} {c : code p q}, current c \u2192 \u03c3 \u2192 \u03c3 \u2192 Prop\n  | ._ .(q) ._ (current.action _ q _ _) := \u03bb _, 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 _ _ _)  := \u03bb 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 _)  := \u03bb 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) \u2192 \u03c3 \u2192 \u03c3 \u2192 Prop\n  | none := \u03bb _, q\n  | (some pc) := next_assert' pc\n\ndef first : \u03a0 {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\u2080 c\u2081) :=\n        seq_left c\u2081 <$> first _\n    <|> seq_right _ <$> first _\n  | ._ ._ (@if_then_else ._ ._ p _ _ _ _ c b\u2080 b\u2081) :=\n    some $ ite_cond _ _ _ _ _\n  | ._ ._ (@code.while ._ ._ _ _ _ _ c b) :=\n    some $ while_cond _ _ _ _\n\nnoncomputable def next' (s : \u03c3) : \u2200 {p q} {c : code p q}, current c \u2192 option (current c)\n  | ._ ._ ._ (current.action p q _ l) := none\n  | ._ ._ ._ (current.seq_left _ _ _ c\u2080 c\u2081 cur\u2080) :=\n        seq_left c\u2081 <$> next' cur\u2080\n    <|> seq_right c\u2080 <$> first c\u2081\n  | ._ ._ ._ (current.seq_right _ _ _ c\u2080 c\u2081 cur\u2081) :=\n        seq_right _ <$> next' cur\u2081\n  | .(p) .(q) ._ (current.ite_cond p c pa pb q _ b\u2080 b\u2081) :=\n      if c s\n         then ite_left _ _ _ _ <$> first b\u2080\n         else ite_right _ _ _ _ <$> first b\u2081\n  | ._ ._ ._ (current.ite_left _ _ _ _ _ _ b\u2080 b\u2081 cur\u2080) :=\n      ite_left _ _ _ b\u2081 <$> next' cur\u2080\n  | ._ ._ ._ (current.ite_right _ _ _ _ _ _ b\u2080 b\u2081 cur\u2081) :=\n      ite_right _ _ _ _ <$> next' cur\u2081\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 : \u03c3) {p q : pred} {c : code p q}\n: option (current c) \u2192 option (current c)\n  | (some pc) := next' s pc\n  | none := none\n\ninductive subtree {p q : pred} (c : code p q) : \u2200 {p' q' : pred}, code p' q' \u2192 Type\n  | rfl {} : subtree c\n  | seq_left  : \u2200 (p' q' r) (c\u2080 : code p' q') (c\u2081 : code q' r),\n    subtree c\u2080 \u2192\n    subtree (code.seq c\u2080 c\u2081)\n  | seq_right : \u2200 (p' q' r) (c\u2080 : code p' q') (c\u2081 : code q' r),\n    subtree c\u2081 \u2192\n    subtree (code.seq c\u2080 c\u2081)\n  | ite_left  : \u2200 (ds t p' pa pb q') (c\u2080 : code pa q') (c\u2081 : code pb q'),\n    subtree c\u2080 \u2192\n    subtree (code.if_then_else p' ds t c\u2080 c\u2081)\n  | ite_right : \u2200 (ds t p' pa pb q') (c\u2080 : code pa q') (c\u2081 : code pb q'),\n    subtree c\u2081 \u2192\n    subtree (code.if_then_else p' ds t c\u2080 c\u2081)\n  | while : \u2200 (ds t p' q' inv) (c' : code q' inv),\n    subtree c' \u2192\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: \u2200 {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\u2080 c\u2081 P)\n             (current.seq_left ._ ._ ._ ._ ._ pc) := within' P pc\n  | ._ ._ ._ (subtree.seq_left p' q' r' c\u2080 c\u2081 P)\n             (current.seq_right ._ ._ ._ ._ ._ pc) := ff\n  | ._ ._ ._ (subtree.seq_right p' q' r' c\u2080 c\u2081 P)\n             (current.seq_left ._ ._ ._ ._ ._ pc) := ff\n  | ._ ._ ._ (subtree.seq_right p' q' r' c\u2080 c\u2081 P)\n             (current.seq_right ._ ._ ._ ._ ._ pc) := within' P pc\n  | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c\u2080 c\u2081 P)\n             (current.ite_left ._ ._ ._ ._ ._ ._ ._ ._ pc) := within' P pc\n  | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c\u2080 c\u2081 P)\n             (current.ite_right ._ ._ ._ ._ ._ ._ ._ ._ pc) := ff\n  | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c\u2080 c\u2081 P)\n             (current.ite_cond ._ ._ ._ ._ ._ ._ ._ ._) := ff\n  | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c\u2080 c\u2081 P)\n             (current.ite_left ._ ._ ._ ._ ._ ._ ._ ._ pc) := ff\n  | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c\u2080 c\u2081 P)\n             (current.ite_right ._ ._ ._ ._ ._ ._ ._ ._ pc) := within' P pc\n  | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c\u2080 c\u2081 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: \u2200 {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\u2080 c\u2081 P)  :=\n        (seq_left c\u2081 <$> exit' P)\n    <|> (seq_right c\u2080 <$> first c\u2081)\n  | ._ ._ ._ (subtree.seq_right p' q' r' c\u2080 c\u2081 P) :=\n        seq_right c\u2080 <$> exit' P\n  | ._ ._ ._ (subtree.ite_left  ds t p' pa pb q' c\u2080 c\u2081 P) :=\n        ite_left p' t ds c\u2081 <$> exit' P\n  | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c\u2080 c\u2081 P) :=\n        ite_right p' t ds c\u2080 <$> 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: \u2200 {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\u2080 : code p q} {c\u2081 : code q r}\n  {P : subtree c c\u2080 }\n: exit' (subtree.seq_left p q r c\u2080 c\u2081 P) =\n  (     (seq_left c\u2081 <$> exit' P)\n    <|> (seq_right c\u2080 <$> first c\u2081) ) :=\nby refl\n\n@[simp]\nlemma exit'_seq_right {p' q' p q r : pred}\n  {c : code p' q'} {c\u2080 : code p q} {c\u2081 : code q r}\n  {P : subtree c c\u2081 }\n: exit' (subtree.seq_right p q r c\u2080 c\u2081 P) =\n  (seq_right c\u2080 <$> 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\u2080 : code pa q} {c\u2081 : code pb q}\n  {P : subtree c c\u2080 }\n: exit' (subtree.ite_left ds t p pa pb q c\u2080 c\u2081 P) =\n  ite_left p t ds c\u2081 <$> 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\u2080 : code pa q} {c\u2081 : code pb q}\n  {P : subtree c c\u2081 }\n: exit' (subtree.ite_right ds t p pa pb q c\u2080 c\u2081 P) =\n  ite_right p t ds c\u2080 <$> 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  \u2194 true :=\nby { cases c ; change tt \u2194 true ; simp ; exact rfl, }\n\n@[simp]\nlemma within'_seq_left {p' q' p q r : pred}\n  {c : code p' q'} {c\u2080 : code p q} {c\u2081 : code q r}\n  {P : subtree c c\u2080 }\n  {pc : current (code.seq c\u2080 c\u2081)}\n:   within' (subtree.seq_left p q r c\u2080 c\u2081 P) pc\n  \u2194 (\u2203 pc\u2080, within' P pc\u2080 \u2227 pc = current.seq_left p q r c\u2080 c\u2081 pc\u2080) :=\nbegin\n  cases pc with pc,\n  { split ; intro h,\n    { existsi a,\n      split, apply h, refl },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      rw h\u2081, apply h\u2080 }, },\n  { split ; intro h,\n    { cases h },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      cases h\u2081, } }\nend\n\n@[simp]\nlemma within'_seq_right {p' q' p q r : pred}\n  {c : code p' q'} {c\u2080 : code p q} {c\u2081 : code q r}\n  {P : subtree c c\u2081 }\n  {pc : current (code.seq c\u2080 c\u2081)}\n:   within' (subtree.seq_right p q r c\u2080 c\u2081 P) pc\n  \u2194 (\u2203 pc\u2081, within' P pc\u2081 \u2227 pc = current.seq_right p q r c\u2080 c\u2081 pc\u2081) :=\nbegin\n  cases pc with pc,\n  { split ; intro h,\n    { cases h },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      cases h\u2081, } },\n  { split ; intro h,\n    { existsi a,\n      split, apply h, refl },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      rw h\u2081, apply h\u2080 }, },\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\u2080 : code pa q} {c\u2081 : code pb q}\n  {P : subtree c c\u2080 }\n  {pc : current _}\n:   within' (subtree.ite_left ds t p pa pb q c\u2080 c\u2081 P) pc\n  \u2194 \u2203 pc\u2080, within' P pc\u2080 \u2227 pc = current.ite_left _ _ _ _ _ _ c\u2080 c\u2081 pc\u2080 :=\nbegin\n  cases pc with pc,\n  { split ; intro h,\n    { cases h },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      cases h\u2081, } },\n  { split ; intro h,\n    { existsi a,\n      split, apply h, refl },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      rw h\u2081, apply h\u2080 }, },\n  { split ; intro h,\n    { cases h },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      cases h\u2081, } }\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\u2080 : code pa q} {c\u2081 : code pb q}\n  {P : subtree c c\u2081 }\n  {pc : current _}\n:   within' (subtree.ite_right ds t p pa pb q c\u2080 c\u2081 P) pc\n  \u2194 \u2203 pc\u2081, within' P pc\u2081 \u2227 pc = current.ite_right _ _ _ _ _ _ c\u2080 c\u2081 pc\u2081 :=\nbegin\n  cases pc with pc,\n  { split ; intro h,\n    { cases h },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      cases h\u2081, } },\n  { split ; intro h,\n    { cases h },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      cases h\u2081, } },\n  { split ; intro h,\n    { existsi a,\n      split, apply h, refl },\n    { cases h with pc\u2080 h, cases h with h\u2080 h\u2081,\n      rw h\u2081, apply h\u2080 }, },\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  \u2194 \u2203 pc', within' P pc' \u2227 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\u2080 h\u2081,\n    cases h\u2081, apply h\u2080 }\nend\n\ndef counter {p q ds l}\n: \u2200 {p' q'} {c' : code p' q'}, subtree (code.action p q ds l) c' \u2192 current c'\n  | ._ ._ ._ subtree.rfl := current.action _ _ _ _\n  | ._ ._ ._ (subtree.seq_left p q r c\u2080 c\u2081 P) :=\n    current.seq_left _ _ _ _ _ (counter P)\n  | ._ ._ ._ (subtree.seq_right p q r c\u2080 c\u2081 P) :=\n    current.seq_right _ _ _ _ _ (counter P)\n  | ._ ._ ._ (subtree.ite_left ds p t pa pb q c\u2080 c\u2081 P) :=\n    current.ite_left _ _ _ _ _ _ _ _ (counter P)\n  | ._ ._ ._ (subtree.ite_right ds p t pa pb q c\u2080 c\u2081 P) :=\n    current.ite_right _ _ _ _ _ _ _ _ (counter P)\n  | ._ ._ ._ (subtree.while p t inv q c\u2080 c\u2081 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') \u2192 Prop\n  | (some pc) := within' P pc \u2228 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\u2080 : code p q} {c\u2081 : code q r}\n  {P : subtree c c\u2080 }\n  {pc : option $ current (code.seq c\u2080 c\u2081)}\n:   within (subtree.seq_left p q r c\u2080 c\u2081 P) pc\n  \u2194 (\u2203 pc\u2080, within P pc\u2080 \u2227 pc = current.seq_left p q r c\u2080 c\u2081 <$> pc\u2080) :=\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\u2080 h, cases h with h\u2080 h\u2081,\n      rw [eq_comm,fmap_eq_none_iff] at h\u2081, subst pc\u2080,\n      dunfold within at h\u2080, simp [h\u2080], admit } },\n  { admit }\nend\n\nsection projections\n\nvariables {p q r : pred}\nvariables {c\u2080 : code p q}\nvariables {c\u2081 : code q r}\n\ndef subtree.left\n: \u2200 {p' q'} {c : code p' q'}, subtree (code.seq c\u2080 c\u2081) c \u2192 subtree c\u2080 c\n | ._ ._ ._ subtree.rfl := subtree.seq_left _ _ _ _ _ subtree.rfl\n | ._ ._ ._ (subtree.seq_left p q r c\u2082 c\u2083 S) := subtree.seq_left _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.seq_right p q r c\u2082 c\u2083 S) := subtree.seq_right _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.ite_left p ds t pa pb r c\u2082 c\u2083 S) :=\n   subtree.ite_left _ _ _ _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.ite_right p ds t pa pb r c\u2082 c\u2083 S) :=\n   subtree.ite_right _ _ _ _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.while ds t p q c\u2082 c\u2083 S) :=\n   subtree.while _ _ _ _ _ _ (subtree.left S)\n\ndef subtree.right\n: \u2200 {p' q'} {c : code p' q'}, subtree (code.seq c\u2080 c\u2081) c \u2192 subtree c\u2081 c\n | ._ ._ ._ subtree.rfl := subtree.seq_right _ _ _ _ _ subtree.rfl\n | ._ ._ ._ (subtree.seq_left p q r c\u2082 c\u2083 S) := subtree.seq_left _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.seq_right p q r c\u2082 c\u2083 S) := subtree.seq_right _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.ite_left p ds t pa pb r c\u2082 c\u2083 S) :=\n   subtree.ite_left _ _ _ _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.ite_right p ds t pa pb r c\u2082 c\u2083 S) :=\n   subtree.ite_right _ _ _ _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.while ds t p q c\u2082 c\u2083 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\u2080 c\u2081) c)\n: within H pc \u2194 within H.left pc \u2228 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 \u2194 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\u2080 c\u2081) c)\n: exits H pc \u2194 exits H.right pc := sorry\n\nlemma exits_left_imp_within_right\n  (H : subtree (code.seq c\u2080 c\u2081) c)\n: exits H.left pc \u2192 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 : \u03a0 (ports : list port) (sockets : list socket) (bound : time), \n     (poll_result ports sockets bound \u2192 (list (socket \u00d7 message_t) \u00d7 A)) \u2192 act\n\nnamespace act\ndef just_send_messages {A : Type u} (ms : list (socket \u00d7 message_t)) \n  (x : A) := act.poll [] [] 0 (\u03bb _, (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 \u2192 Prop\n| mk : \u2200 ports sockets bound cont, 0 < bound \u2192 s \u2208 sockets \n  \u2192 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 \u2227 s \u2208 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 \u2192 act state_type)\n\n\ninductive dlabel {A : Type u} : act A \u2192 Type u\n| poll : \u2200 (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} : \u2200 {next : act A} (la : dlabel next), \n   list (socket \u00d7 message_t) \u00d7 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 \u00d7 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  : \u2203 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": "axiom FalseIntro : False\ntheorem False.intro : False := FalseIntro\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/RejectAxiomFalse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.04813677453046283, "lm_q1q2_score": 0.01385221446441358}}
{"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 \u03c0_BigInt3 (F : Type) :=\n  ( \u03c3_ptr : F ) ( d0 : F ) ( d1 : F ) ( d2 : F )\n@[reducible] def \u03c6_BigInt3.d0 := 0\n@[reducible] def \u03c6_BigInt3.d1 := 1\n@[reducible] def \u03c6_BigInt3.d2 := 2\n@[reducible] def \u03c6_BigInt3.SIZE := 3\n@[reducible] def cast_BigInt3 (mem : F \u2192 F) (p : F) : BigInt3 F := {\n  d0 := mem (p + \u03c6_BigInt3.d0),\n  d1 := mem (p + \u03c6_BigInt3.d1),\n  d2 := mem (p + \u03c6_BigInt3.d2)\n}\n@[reducible] def cast_\u03c0_BigInt3 (mem : F \u2192 F) (p : F) : \u03c0_BigInt3 F := {\n  \u03c3_ptr := mem p,\n  d0 := mem ((mem p) + \u03c6_BigInt3.d0),\n  d1 := mem ((mem p) + \u03c6_BigInt3.d1),\n  d2 := mem ((mem p) + \u03c6_BigInt3.d2)\n}\ninstance \u03c0_BigInt3_to_F : has_coe (\u03c0_BigInt3 F) F := \u27e8\u03bb s, s.\u03c3_ptr\u27e9\n@[ext] structure UnreducedBigInt5 (F : Type) :=\n  ( d0 : F ) ( d1 : F ) ( d2 : F ) ( d3 : F ) ( d4 : F )\n@[ext] structure \u03c0_UnreducedBigInt5 (F : Type) :=\n  ( \u03c3_ptr : F ) ( d0 : F ) ( d1 : F ) ( d2 : F ) ( d3 : F ) ( d4 : F )\n@[reducible] def \u03c6_UnreducedBigInt5.d0 := 0\n@[reducible] def \u03c6_UnreducedBigInt5.d1 := 1\n@[reducible] def \u03c6_UnreducedBigInt5.d2 := 2\n@[reducible] def \u03c6_UnreducedBigInt5.d3 := 3\n@[reducible] def \u03c6_UnreducedBigInt5.d4 := 4\n@[reducible] def \u03c6_UnreducedBigInt5.SIZE := 5\n@[reducible] def cast_UnreducedBigInt5 (mem : F \u2192 F) (p : F) : UnreducedBigInt5 F := {\n  d0 := mem (p + \u03c6_UnreducedBigInt5.d0),\n  d1 := mem (p + \u03c6_UnreducedBigInt5.d1),\n  d2 := mem (p + \u03c6_UnreducedBigInt5.d2),\n  d3 := mem (p + \u03c6_UnreducedBigInt5.d3),\n  d4 := mem (p + \u03c6_UnreducedBigInt5.d4)\n}\n@[reducible] def cast_\u03c0_UnreducedBigInt5 (mem : F \u2192 F) (p : F) : \u03c0_UnreducedBigInt5 F := {\n  \u03c3_ptr := mem p,\n  d0 := mem ((mem p) + \u03c6_UnreducedBigInt5.d0),\n  d1 := mem ((mem p) + \u03c6_UnreducedBigInt5.d1),\n  d2 := mem ((mem p) + \u03c6_UnreducedBigInt5.d2),\n  d3 := mem ((mem p) + \u03c6_UnreducedBigInt5.d3),\n  d4 := mem ((mem p) + \u03c6_UnreducedBigInt5.d4)\n}\ninstance \u03c0_UnreducedBigInt5_to_F : has_coe (\u03c0_UnreducedBigInt5 F) F := \u27e8\u03bb s, s.\u03c3_ptr\u27e9\n@[ext] structure UnreducedBigInt3 (F : Type) :=\n  ( d0 : F ) ( d1 : F ) ( d2 : F )\n@[ext] structure \u03c0_UnreducedBigInt3 (F : Type) :=\n  ( \u03c3_ptr : F ) ( d0 : F ) ( d1 : F ) ( d2 : F )\n@[reducible] def \u03c6_UnreducedBigInt3.d0 := 0\n@[reducible] def \u03c6_UnreducedBigInt3.d1 := 1\n@[reducible] def \u03c6_UnreducedBigInt3.d2 := 2\n@[reducible] def \u03c6_UnreducedBigInt3.SIZE := 3\n@[reducible] def cast_UnreducedBigInt3 (mem : F \u2192 F) (p : F) : UnreducedBigInt3 F := {\n  d0 := mem (p + \u03c6_UnreducedBigInt3.d0),\n  d1 := mem (p + \u03c6_UnreducedBigInt3.d1),\n  d2 := mem (p + \u03c6_UnreducedBigInt3.d2)\n}\n@[reducible] def cast_\u03c0_UnreducedBigInt3 (mem : F \u2192 F) (p : F) : \u03c0_UnreducedBigInt3 F := {\n  \u03c3_ptr := mem p,\n  d0 := mem ((mem p) + \u03c6_UnreducedBigInt3.d0),\n  d1 := mem ((mem p) + \u03c6_UnreducedBigInt3.d1),\n  d2 := mem ((mem p) + \u03c6_UnreducedBigInt3.d2)\n}\ninstance \u03c0_UnreducedBigInt3_to_F : has_coe (\u03c0_UnreducedBigInt3 F) F := \u27e8\u03bb s, s.\u03c3_ptr\u27e9\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 : \u2124)\n\nnamespace bigint3\n\ndef val (x : bigint3) : int := x.i2 * \u2191BASE^2 + x.i1 * \u2191BASE + x.i0\n\ndef toBigInt3 (x : bigint3) : BigInt3 F := \u27e8x.i0, x.i1, x.i2\u27e9\n\ndef toUnreducedBigInt3 (x : bigint3) : UnreducedBigInt3 F := \u27e8x.i0, x.i1, x.i2\u27e9\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 : \u2124) (x : bigint3) : bigint3 :=\n{ i0 := c * x.i0, i1 := c * x.i1, i2 := c * x.i2}\n\ntheorem cmul_val (c : \u2124) (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 \u2261 x.val * y.val [ZMOD \u2191SECP_PRIME] :=\nbegin\n  have aux : (4 : \u2124) \u2223 \u2191BASE ^ 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 [\u2190mul_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 \u2261 x.val^2 [ZMOD \u2191SECP_PRIME] :=\nby { rw pow_two, exact mul_val x x }\n\ndef bounded (x : bigint3) (b : \u2124) := abs x.i0 \u2264 b \u2227 abs x.i1 \u2264 b \u2227 abs x.i2 \u2264 b\n\ntheorem bounded_of_bounded_of_le {x : bigint3} {b\u2081 b\u2082 : \u2124} (bddx : x.bounded b\u2081) (hle : b\u2081 \u2264 b\u2082) :\n  x.bounded b\u2082 :=\n\u27e8bddx.1.trans hle, bddx.2.1.trans hle, bddx.2.2.trans hle\u27e9\n\ntheorem bounded_add {x y : bigint3} {b\u2081 b\u2082 : int} (bddx : x.bounded b\u2081) (bddy : y.bounded b\u2082) :\n  (x.add y).bounded (b\u2081 + b\u2082) :=\n\u27e8(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)\u27e9\n\ntheorem bounded_sub {x y : bigint3} {b\u2081 b\u2082 : int} (bddx : x.bounded b\u2081) (bddy : y.bounded b\u2082) :\n  (x.sub y).bounded (b\u2081 + b\u2082) :=\n\u27e8(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)\u27e9\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 \u27e8mul_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 _)\u27e9\nend\n\ntheorem bounded_cmul' {x : bigint3} {c b : int} (h : 0 \u2264 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 : \u2124} (hx : x.bounded b) (hy : y.bounded b) :\n  (x.mul y).bounded (b^2 * (8 * SECP_REM + 1)) :=\nbegin\n  have bnonneg : 0 \u2264 b := le_trans (abs_nonneg _) hx.1,\n  have secp4nonneg : (0 : \u2124) \u2264 4 * \u2191SECP_REM,\n  { apply mul_nonneg, norm_num1, rw [SECP_REM], simp_int_casts, norm_num1 },\n  have secp4ge1 : (1 : \u2124) \u2264 4 * \u2191SECP_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 * \u2191SECP_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 * \u2191SECP_REM)) + (b * b) * (4 * \u2191SECP_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 [\u2190mul_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 : \u2124} (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 : \u2124} (h : x = (bigint3.mk i0 i1 i2).toBigInt3) :\n  x.d0 = i0 \u2227 x.d1 = i1 \u2227 x.d2 = i2 :=\nby { rwa BigInt3.ext_iff at h }\n\ntheorem unreduced_bigint3_eqs {x : UnreducedBigInt3 F} {i0 i1 i2 : \u2124} (h : x = (bigint3.mk i0 i1 i2).toUnreducedBigInt3) :\n  x.d0 = i0 \u2227 x.d1 = i1 \u2227 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 \u2264 3 * BASE - 1)\n    (jbdd : abs j \u2264 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) = \u27e80, 0, 0\u27e9)\n    (abdd : a.bounded (3 * BASE - 1)) :\n  a = \u27e80, 0, 0\u27e9 :=\nbegin\n  have : (a.toBigInt3 : BigInt3 F) = bigint3.toBigInt3 \u27e80, 0, 0\u27e9,\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 : \u2124)\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 := \u27e8x.i0, x.i1, x.i2, x.i3, x.i4\u27e9\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 := \u27e8ix.i0, ix.i1, ix.i2, 0, 0\u27e9\n\ndef BigInt3.toUnreducedBigInt5  {F : Type} [field F]\n    (x : BigInt3 F) : UnreducedBigInt5 F := \u27e8x.d0, x.d1, x.d2, 0, 0\u27e9\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 * \u2191BASE^4 + x.i3 * \u2191BASE^3 + x.i2 * \u2191BASE^2 +\n  x.i1 * \u2191BASE + 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 : \u2124) (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 : \u2124) := abs x.i0 \u2264 b \u2227 abs x.i1 \u2264 b \u2227 abs x.i2 \u2264 b \u2227\n  abs x.i3 \u2264 b \u2227 abs x.i4 \u2264 b\n\ntheorem bounded_of_bounded_of_le {x : bigint5} {b\u2081 b\u2082 : \u2124} (bddx : x.bounded b\u2081) (hle : b\u2081 \u2264 b\u2082) :\n  x.bounded b\u2082 :=\n\u27e8bddx.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\u27e9\n\ntheorem bounded_add {x y : bigint5} {b\u2081 b\u2082 : int} (bddx : x.bounded b\u2081) (bddy : y.bounded b\u2082) :\n  (x.add y).bounded (b\u2081 + b\u2082) :=\n\u27e8(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)\u27e9\n\ntheorem bounded_sub {x y : bigint5} {b\u2081 b\u2082 : int} (bddx : x.bounded b\u2081) (bddy : y.bounded b\u2082) :\n  (x.sub y).bounded (b\u2081 + b\u2082) :=\n\u27e8(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) \u27e9\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 \u27e8mul_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 _)\u27e9\nend\n\ntheorem bounded_cmul' {x : bigint5} {c b : int} (h : 0 \u2264 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 : \u2124) - 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 : \u2124}\n    (hx : x.bounded b) (hy : y.bounded b) :\n  (x.bigint5_mul y).bounded (3 * b^2) :=\nbegin\n  have bnn : 0 \u2264 b := le_trans (abs_nonneg _) hx.1,\n  have b2nn: 0 \u2264 b^2 := sq_nonneg b,\n  have b2le3b2   : b^2 \u2264 3 * b^2, by linarith,\n  have b2b2le3b2 : b^2 + b^2 \u2264 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 : \u2124} (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 \u2192 F) (\u03ba : \u2115) (x y : BigInt3 F) (\u03c1_res : UnreducedBigInt5 F) : Prop :=\n  14 \u2264 \u03ba \u2227\n  \u03c1_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 \u2192 F) (\u03ba : \u2115) (x y : BigInt3 F) (\u03c1_res : UnreducedBigInt5 F) : Prop :=\n  \u03c1_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 \u2192 F}\n    (\u03ba : \u2115)\n    (x y : BigInt3 F) (\u03c1_res : UnreducedBigInt5 F)\n    (h_auto : auto_spec_bigint_mul mem \u03ba x y \u03c1_res) :\n  spec_bigint_mul mem \u03ba x y \u03c1_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 \u2192 F) (\u03ba : \u2115) (range_check_ptr \u03c1_range_check_ptr : F) (\u03c1_res : BigInt3 F) : Prop :=\n  \u2203 res : BigInt3 F,\n  \u2203 MAX_SUM : F, MAX_SUM = 232113757366008801543585789 \u2227\n  mem (range_check_ptr) = MAX_SUM - (res.d0 + res.d1 + res.d2) \u2227\n  is_range_checked (rc_bound F) (MAX_SUM - (res.d0 + res.d1 + res.d2)) \u2227\n  \u2203 range_check_ptr\u2081 : F, range_check_ptr\u2081 = range_check_ptr + 4 \u2227\n  mem (range_check_ptr\u2081 - 3) = res.d0 \u2227\n  is_range_checked (rc_bound F) (res.d0) \u2227\n  mem (range_check_ptr\u2081 - 2) = res.d1 \u2227\n  is_range_checked (rc_bound F) (res.d1) \u2227\n  mem (range_check_ptr\u2081 - 1) = res.d2 \u2227\n  is_range_checked (rc_bound F) (res.d2) \u2227\n  10 \u2264 \u03ba \u2227\n  \u03c1_range_check_ptr = range_check_ptr\u2081 \u2227\n  \u03c1_res = res\n\n-- You may change anything in this definition except the name and arguments.\ndef spec_nondet_bigint3 (mem : F \u2192 F) (\u03ba : \u2115) (range_check_ptr \u03c1_range_check_ptr : F) (\u03c1_res : BigInt3 F) : Prop :=\n  \u2203 nd0 nd1 nd2 slack : \u2115,\n    nd0 < rc_bound F \u2227\n    nd1 < rc_bound F \u2227\n    nd2 < rc_bound F \u2227\n    slack < rc_bound F \u2227\n    \u03c1_res = bigint3.toBigInt3 { i0 := nd0, i1 := nd1, i2 := nd2 } \u2227\n    nd0 + nd1 + nd2 + slack = 3 * (BASE - 1)\n\ntheorem nondet_bigint3_corr {mem : F \u2192 F} {k : \u2115} {range_check_ptr : F} {ret0 : F} {x : BigInt3 F}\n    (h : spec_nondet_bigint3 mem k range_check_ptr ret0 x) :\n  \u2203 ix : bigint3, x = ix.toBigInt3 \u2227 ix.bounded (3 * (BASE - 1)) :=\nbegin\n  have BASEge1: 1 \u2264 BASE, by { unfold BASE, norm_num1 },\n  rcases h with \u27e8nd0, nd1, nd2, _, _, _, _, _, xeq, sumeq\u27e9,\n  refine \u27e8_, xeq, _\u27e9,\n  simp only [bigint3.bounded],\n  have : (3 : \u2124) * (\u2191BASE - 1) = \u2191(3 * (BASE - 1)),\n  { rw [int.coe_nat_mul, int.coe_nat_sub BASEge1], simp },\n  rw [this, \u2190sumeq], 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 \u2192 F}\n    (\u03ba : \u2115)\n    (range_check_ptr \u03c1_range_check_ptr : F) (\u03c1_res : BigInt3 F)\n    (h_auto : auto_spec_nondet_bigint3 mem \u03ba range_check_ptr \u03c1_range_check_ptr \u03c1_res) :\n  spec_nondet_bigint3 mem \u03ba range_check_ptr \u03c1_range_check_ptr \u03c1_res :=\nbegin\n  rcases h_auto with \u27e8res, MAX_SUM, MAX_SUM_eq,\n    _, \u27e8slack, slack_lt, slack_eq\u27e9,\n    rp1, rp1eq,\n    resd0eq,\n    \u27e8nd0, nd0_lt, nd0_eq\u27e9,\n    resd1eq,\n    \u27e8nd1, nd1_lt, nd1_eq\u27e9,\n    resd2eq,\n    \u27e8nd2, nd2_lt, nd2_eq\u27e9,\n    _,\n    rp1eq',\n    reseq\u27e9,\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, \u2190slack_eq, \u2190nd0_eq, \u2190nd1_eq, \u2190nd2_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 \u2192 Nat \u2192 Key\n  | fvar  : FVarId \u2192 Nat \u2192 Key\n  | lit   : Literal \u2192 Key\n  | star  : Key\n  | other : Key\n  | arrow : Key\n  | proj  : Name \u2192 Nat \u2192 Key\n  deriving Inhabited, BEq, Repr\n\nprotected def Key.hash : Key \u2192 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 := \u27e8Key.hash\u27e9\n\ninductive Trie (\u03b1 : Type) where\n  | node (vs : Array \u03b1) (children : Array (Key \u00d7 Trie \u03b1)) : Trie \u03b1\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 (\u03b1 : Type) where\n  root : PersistentHashMap Key (Trie \u03b1) := {}\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 \u2192 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 \u2192 Key \u2192 Bool\n  | Key.lit v\u2081,      Key.lit v\u2082      => v\u2081 < v\u2082\n  | Key.fvar n\u2081 a\u2081,  Key.fvar n\u2082 a\u2082  => a\u2081 < a\u2082 -- Name.quickLt n\u2081.name n\u2082.name || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | Key.const n\u2081 a\u2081, Key.const n\u2082 a\u2082 => Name.quickLt n\u2081 n\u2082 || (n\u2081 == n\u2082 && a\u2081 < a\u2082)\n  | Key.proj s\u2081 i\u2081,  Key.proj s\u2082 i\u2082  => Name.quickLt s\u2081 s\u2082 || (s\u2081 == s\u2082 && i\u2081 < i\u2082)\n  | k\u2081,              k\u2082              => k\u2081.ctorIdx < k\u2082.ctorIdx\n\ninstance : LT Key := \u27e8fun a b => Key.lt a b\u27e9\ninstance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key \u2192 Format\n  | Key.star                   => \"*\"\n  | Key.other                  => \"\u25fe\"\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                  => \"\u2192\"\n\ninstance : ToFormat Key := \u27e8Key.format\u27e9\n\ndef Key.arity : Key \u2192 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 \u03b1) := \u27e8Trie.node #[] #[]\u27e9\n\nnamespace DiscrTree\n\ndef empty : DiscrTree \u03b1 := { root := {} }\n\npartial def Trie.format [ToMessageData \u03b1] : Trie \u03b1 \u2192 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 \u27e8k, c\u27e9 => MessageData.paren (toMessageData k ++ \" => \" ++ format c)) \",\"\n\npartial def Trie.formatClause : Trie (Clause \u00d7 \u03b1) \u2192 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 \u27e8k, c\u27e9 => MessageData.paren (toMessageData k ++ \" => \" ++ formatClause c)) \",\"\n\ninstance [ToMessageData \u03b1] : ToMessageData (Trie \u03b1) := \u27e8Trie.format\u27e9\ninstance : ToMessageData (Trie (Clause \u00d7 \u03b1)) := \u27e8Trie.formatClause\u27e9\n\npartial def format [ToMessageData \u03b1] (d : DiscrTree \u03b1) : MessageData :=\n  let (_, r) := d.root.foldl\n    (fun (p : Bool \u00d7 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 \u00d7 \u03b1)) : MessageData :=\n  let (_, r) := d.root.foldl\n    (fun (p : Bool \u00d7 MessageData) k c =>\n      (false, p.2 ++ MessageData.paren (toMessageData k ++ \" => \" ++ toMessageData c)))\n    (true, Format.nil)\n  MessageData.group r\n\ninstance [ToMessageData \u03b1] : ToMessageData (DiscrTree \u03b1) := \u27e8fun dt => format dt\u27e9\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 \u03b1) 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 \u03b1]`) 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., `{\u03b1 : 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 \u27e8i, h\u27e9\n    if info.isInstImplicit then\n      return true\n    else if info.isImplicit || info.isStrictImplicit then\n      return not (\u2190 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 \u2192 Expr \u2192 Array Expr \u2192 RuleM (Array Expr)\n  | i, Expr.app f a, todo => do\n    if (\u2190 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 \u00d7 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 \u00d7 Array Expr) := do\n      let info \u2190 Meta.getFunInfoNArgs fn nargs\n      let todo \u2190 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) \u2190 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 : \u03b1) (i : Nat) : Trie \u03b1 :=\n  if h : i < keys.size then\n    let k := keys.get \u27e8i, h\u27e9\n    let c := createNodes keys v (i+1)\n    Trie.node #[] #[(k, c)]\n  else\n    Trie.node #[v] #[]\n\nprivate def insertVal [BEq \u03b1] (vs : Array \u03b1) (v : \u03b1) : Array \u03b1 :=\n  if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq \u03b1] (keys : Array Key) (v : \u03b1) : Nat \u2192 Trie \u03b1 \u2192 Trie \u03b1\n  | i, Trie.node vs cs =>\n    if h : i < keys.size then\n      let k := keys.get \u27e8i, h\u27e9\n      let c := Id.run $ cs.binInsertM\n          (fun a b => a.1 < b.1)\n          (fun \u27e8_, s\u27e9 => 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 \u03b1] (d : DiscrTree \u03b1) (keys : Array Key) (v : \u03b1) : DiscrTree \u03b1 :=\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 \u03b1] (d : DiscrTree \u03b1) (e : Expr) (v : \u03b1) : RuleM (DiscrTree \u03b1) := do\n  let keys \u2190 mkPath e\n  return d.insertCore keys v\n-/\n\ndef insert [BEq \u03b1] (d : DiscrTree (Clause \u00d7 \u03b1)) (e : Expr) (v : (Clause \u00d7 \u03b1)) : RuleM (DiscrTree (Clause \u00d7 \u03b1)) := do\n  let keys \u2190 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 \u00d7 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 \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : RuleM (Key \u00d7 Array Expr) :=\n  getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree \u03b1) : Array \u03b1 :=\n  let result : Array \u03b1 := 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 \u00d7 Trie \u03b1)) (k : Key) : Option (Key \u00d7 Trie \u03b1) :=\n  cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie \u03b1) (result : Array \u03b1) : RuleM (Array \u03b1) := 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) \u2190 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 \u03b1) : RuleM (Array \u03b1) :=\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 \u03b1) : RuleM (Array \u03b1) :=\n        match findKey cs k with\n        | none   => return result\n        | some c => getMatchLoop (todo ++ args) c.2 result\n      let result \u2190 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 #[] (\u2190 visitNonStar k args result)\n      | _         => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree \u03b1) (k : Key) (args : Array Expr) (result : Array \u03b1) : RuleM (Array \u03b1) :=\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 \u03b1) (e : Expr) : RuleM (Array \u03b1) := do\n  Core.checkMaxHeartbeats \"getMatch\"\n  let result := getStarResult d\n  let (k, args) \u2190 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 \u00d7 \u03b1)) (e : Expr) : RuleM (Array (Clause \u00d7 \u03b1)) := do\n  let unfiltered_result \u2190 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 \u03b1) (e : Expr) : RuleM (Array \u03b1) := do\n  Core.checkMaxHeartbeats \"getUnify\"\n  let (k, args) \u2190 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 \u03b1) (result : Array \u03b1) : RuleM (Array \u03b1) := 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 \u27e8k, c\u27e9 => 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) \u2190 getUnifyKeyArgs e (root := false)\n        let visitStar (result : Array \u03b1) : RuleM (Array \u03b1) :=\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 \u03b1) : RuleM (Array \u03b1) :=\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 \u27e8k, c\u27e9 => process k.arity todo c result\n        -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n        | Key.arrow => visitNonStar Key.other #[] (\u2190 visitNonStar k args (\u2190 visitStar result))\n        | _         => visitNonStar k args (\u2190 visitStar result)\n\npartial def getUnify (d : DiscrTree (Clause \u00d7 \u03b1)) (e : Expr) : RuleM (Array (Clause \u00d7 \u03b1)) := do\n  let unfiltered_result \u2190 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 \u03b1) (c : Clause) : RuleM (DiscrTree \u03b1) := 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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl, 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 : (\u03a0 x, \u03b2 x) \u2192 \u03b2 x`. -/\ndef eval {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (x : \u03b1) (f : (x : \u03b1) \u2192 \u03b2 x) : \u03b2 x :=\n  f x\n\n@[simp] theorem eval_apply {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} (x : \u03b1) (f : (x : \u03b1) \u2192 \u03b2 x) : eval x f = f x :=\n  rfl\n\ntheorem comp_apply {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b2 \u2192 \u03c6) (g : \u03b1 \u2192 \u03b2) (a : \u03b1) : comp f g a = f (g a) :=\n  rfl\n\ntheorem const_def {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {y : \u03b2} : (fun (x : \u03b1) => y) = const \u03b1 y :=\n  rfl\n\n@[simp] theorem const_apply {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {y : \u03b2} {x : \u03b1} : const \u03b1 y x = y :=\n  rfl\n\n@[simp] theorem const_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {c : \u03b3} : const \u03b2 c \u2218 f = const \u03b1 c :=\n  rfl\n\n@[simp] theorem comp_const {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b2 \u2192 \u03b3} {b : \u03b2} : f \u2218 const \u03b1 b = const \u03b1 (f b) :=\n  rfl\n\ntheorem id_def {\u03b1 : Sort u_1} : id = fun (x : \u03b1) => x :=\n  rfl\n\ntheorem hfunext {\u03b1 : Sort u} {\u03b1' : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {\u03b2' : \u03b1' \u2192 Sort v} {f : (a : \u03b1) \u2192 \u03b2 a} {f' : (a : \u03b1') \u2192 \u03b2' a} (h\u03b1 : \u03b1 = \u03b1') (h : \u2200 (a : \u03b1) (a' : \u03b1'), a == a' \u2192 f a == f' a') : f == f' := sorry\n\ntheorem funext_iff {\u03b1 : Sort u_1} {\u03b2 : \u03b1 \u2192 Sort u_2} {f\u2081 : (x : \u03b1) \u2192 \u03b2 x} {f\u2082 : (x : \u03b1) \u2192 \u03b2 x} : f\u2081 = f\u2082 \u2194 \u2200 (a : \u03b1), f\u2081 a = f\u2082 a :=\n  { mp := fun (h : f\u2081 = f\u2082) (a : \u03b1) => h \u25b8 rfl, mpr := funext }\n\n@[simp] theorem injective.eq_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) {a : \u03b1} {b : \u03b1} : f a = f b \u2194 a = b :=\n  { mp := I, mpr := congr_arg f }\n\ntheorem injective.eq_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) {a : \u03b1} {b : \u03b1} {c : \u03b2} (h : f b = c) : f a = c \u2194 a = b :=\n  h \u25b8 injective.eq_iff I\n\ntheorem injective.ne {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : injective f) {a\u2081 : \u03b1} {a\u2082 : \u03b1} : a\u2081 \u2260 a\u2082 \u2192 f a\u2081 \u2260 f a\u2082 :=\n  mt fun (h : f a\u2081 = f a\u2082) => hf h\n\ntheorem injective.ne_iff {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : injective f) {x : \u03b1} {y : \u03b1} : f x \u2260 f y \u2194 x \u2260 y :=\n  { mp := mt (congr_arg f), mpr := injective.ne hf }\n\ntheorem injective.ne_iff' {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : injective f) {x : \u03b1} {y : \u03b1} {z : \u03b2} (h : f y = z) : f x \u2260 z \u2194 x \u2260 y :=\n  h \u25b8 injective.ne_iff hf\n\n/-- If the co-domain `\u03b2` of an injective function `f : \u03b1 \u2192 \u03b2` has decidable equality, then\nthe domain `\u03b1` also has decidable equality. -/\ndef injective.decidable_eq {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} [DecidableEq \u03b2] (I : injective f) : DecidableEq \u03b1 :=\n  fun (a b : \u03b1) => decidable_of_iff (f a = f b) (injective.eq_iff I)\n\ntheorem injective.of_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b3 \u2192 \u03b1} (I : injective (f \u2218 g)) : injective g :=\n  fun (x y : \u03b3) (h : g x = g y) => I ((fun (this : f (g x) = f (g y)) => this) (congr_arg f h))\n\ntheorem surjective.of_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b3 \u2192 \u03b1} (S : surjective (f \u2218 g)) : surjective f := sorry\n\nprotected instance decidable_eq_pfun (p : Prop) [Decidable p] (\u03b1 : p \u2192 Type u_1) [(hp : p) \u2192 DecidableEq (\u03b1 hp)] : DecidableEq ((hp : p) \u2192 \u03b1 hp) :=\n  sorry\n\ntheorem surjective.forall {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) {p : \u03b2 \u2192 Prop} : (\u2200 (y : \u03b2), p y) \u2194 \u2200 (x : \u03b1), p (f x) := sorry\n\ntheorem surjective.forall\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) {p : \u03b2 \u2192 \u03b2 \u2192 Prop} : (\u2200 (y\u2081 y\u2082 : \u03b2), p y\u2081 y\u2082) \u2194 \u2200 (x\u2081 x\u2082 : \u03b1), p (f x\u2081) (f x\u2082) :=\n  iff.trans (surjective.forall hf) (forall_congr fun (x : \u03b1) => surjective.forall hf)\n\ntheorem surjective.forall\u2083 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) {p : \u03b2 \u2192 \u03b2 \u2192 \u03b2 \u2192 Prop} : (\u2200 (y\u2081 y\u2082 y\u2083 : \u03b2), p y\u2081 y\u2082 y\u2083) \u2194 \u2200 (x\u2081 x\u2082 x\u2083 : \u03b1), p (f x\u2081) (f x\u2082) (f x\u2083) :=\n  iff.trans (surjective.forall hf) (forall_congr fun (x : \u03b1) => surjective.forall\u2082 hf)\n\ntheorem surjective.exists {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) {p : \u03b2 \u2192 Prop} : (\u2203 (y : \u03b2), p y) \u2194 \u2203 (x : \u03b1), p (f x) := sorry\n\ntheorem surjective.exists\u2082 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) {p : \u03b2 \u2192 \u03b2 \u2192 Prop} : (\u2203 (y\u2081 : \u03b2), \u2203 (y\u2082 : \u03b2), p y\u2081 y\u2082) \u2194 \u2203 (x\u2081 : \u03b1), \u2203 (x\u2082 : \u03b1), p (f x\u2081) (f x\u2082) :=\n  iff.trans (surjective.exists hf) (exists_congr fun (x : \u03b1) => surjective.exists hf)\n\ntheorem surjective.exists\u2083 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) {p : \u03b2 \u2192 \u03b2 \u2192 \u03b2 \u2192 Prop} : (\u2203 (y\u2081 : \u03b2), \u2203 (y\u2082 : \u03b2), \u2203 (y\u2083 : \u03b2), p y\u2081 y\u2082 y\u2083) \u2194 \u2203 (x\u2081 : \u03b1), \u2203 (x\u2082 : \u03b1), \u2203 (x\u2083 : \u03b1), p (f x\u2081) (f x\u2082) (f x\u2083) :=\n  iff.trans (surjective.exists hf) (exists_congr fun (x : \u03b1) => surjective.exists\u2082 hf)\n\n/-- Cantor's diagonal argument implies that there are no surjective functions from `\u03b1`\nto `set \u03b1`. -/\ntheorem cantor_surjective {\u03b1 : Type u_1} (f : \u03b1 \u2192 set \u03b1) : \u00acsurjective f := sorry\n\n/-- Cantor's diagonal argument implies that there are no injective functions from `set \u03b1` to `\u03b1`. -/\ntheorem cantor_injective {\u03b1 : Type u_1} (f : set \u03b1 \u2192 \u03b1) : \u00acinjective 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 {\u03b1 : Type u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 Option \u03b1) :=\n  \u2200 (x : \u03b1) (y : \u03b2), g y = some x \u2194 f x = y\n\ntheorem is_partial_inv_left {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 Option \u03b1} (H : is_partial_inv f g) (x : \u03b1) : g (f x) = some x :=\n  iff.mpr (H x (f x)) rfl\n\ntheorem injective_of_partial_inv {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 Option \u03b1} (H : is_partial_inv f g) : injective f :=\n  fun (a b : \u03b1) (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 {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 Option \u03b1} (H : is_partial_inv f g) (x : \u03b2) (y : \u03b2) (b : \u03b1) (h\u2081 : b \u2208 g x) (h\u2082 : b \u2208 g y) : x = y :=\n  Eq.trans (Eq.symm (iff.mp (H b x) h\u2081)) (iff.mp (H b y) h\u2082)\n\ntheorem left_inverse.comp_eq_id {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (h : left_inverse f g) : f \u2218 g = id :=\n  funext h\n\ntheorem left_inverse_iff_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} : left_inverse f g \u2194 f \u2218 g = id :=\n  { mp := left_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem right_inverse.comp_eq_id {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (h : right_inverse f g) : g \u2218 f = id :=\n  funext h\n\ntheorem right_inverse_iff_comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} : right_inverse f g \u2194 g \u2218 f = id :=\n  { mp := right_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem left_inverse.comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} {h : \u03b2 \u2192 \u03b3} {i : \u03b3 \u2192 \u03b2} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h \u2218 f) (g \u2218 i) := sorry\n\ntheorem right_inverse.comp {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} {h : \u03b2 \u2192 \u03b3} {i : \u03b3 \u2192 \u03b2} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h \u2218 f) (g \u2218 i) :=\n  left_inverse.comp hh hf\n\ntheorem left_inverse.right_inverse {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (h : left_inverse g f) : right_inverse f g :=\n  h\n\ntheorem right_inverse.left_inverse {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (h : right_inverse g f) : left_inverse f g :=\n  h\n\ntheorem left_inverse.surjective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (h : left_inverse f g) : surjective f :=\n  right_inverse.surjective (left_inverse.right_inverse h)\n\ntheorem right_inverse.injective {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (h : right_inverse f g) : injective f :=\n  left_inverse.injective (right_inverse.left_inverse h)\n\ntheorem left_inverse.eq_right_inverse {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} {g\u2081 : \u03b2 \u2192 \u03b1} {g\u2082 : \u03b2 \u2192 \u03b1} (h\u2081 : left_inverse g\u2081 f) (h\u2082 : right_inverse g\u2082 f) : g\u2081 = g\u2082 := sorry\n\n/-- We can use choice to construct explicitly a partial inverse for\n  a given injective function `f`. -/\ndef partial_inv {\u03b1 : Type u_1} {\u03b2 : Sort u_2} (f : \u03b1 \u2192 \u03b2) (b : \u03b2) : Option \u03b1 :=\n  dite (\u2203 (a : \u03b1), f a = b) (fun (h : \u2203 (a : \u03b1), f a = b) => some (classical.some h))\n    fun (h : \u00ac\u2203 (a : \u03b1), f a = b) => none\n\ntheorem partial_inv_of_injective {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) : is_partial_inv f (partial_inv f) := sorry\n\ntheorem partial_inv_left {\u03b1 : Type u_1} {\u03b2 : Sort u_2} {f : \u03b1 \u2192 \u03b2} (I : injective f) (x : \u03b1) : 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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) (s : set \u03b1) (b : \u03b2) : \u03b1 :=\n  dite (\u2203 (a : \u03b1), a \u2208 s \u2227 f a = b) (fun (h : \u2203 (a : \u03b1), a \u2208 s \u2227 f a = b) => classical.some h)\n    fun (h : \u00ac\u2203 (a : \u03b1), a \u2208 s \u2227 f a = b) => Classical.choice n\n\ntheorem inv_fun_on_pos {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2} (h : \u2203 (a : \u03b1), \u2203 (H : a \u2208 s), f a = b) : inv_fun_on f s b \u2208 s \u2227 f (inv_fun_on f s b) = b := sorry\n\ntheorem inv_fun_on_mem {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2} (h : \u2203 (a : \u03b1), \u2203 (H : a \u2208 s), f a = b) : inv_fun_on f s b \u2208 s :=\n  and.left (inv_fun_on_pos h)\n\ntheorem inv_fun_on_eq {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2} (h : \u2203 (a : \u03b1), \u2203 (H : a \u2208 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' {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {a : \u03b1} (h : \u2200 (x : \u03b1), x \u2208 s \u2192 \u2200 (y : \u03b1), y \u2208 s \u2192 f x = f y \u2192 x = y) (ha : a \u2208 s) : inv_fun_on f s (f a) = a :=\n  (fun (this : \u2203 (a' : \u03b1), \u2203 (H : a' \u2208 s), f a' = f a) =>\n      h (inv_fun_on (fun (a' : \u03b1) => 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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {s : set \u03b1} {b : \u03b2} (h : \u00ac\u2203 (a : \u03b1), \u2203 (H : a \u2208 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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} (f : \u03b1 \u2192 \u03b2) : \u03b2 \u2192 \u03b1 :=\n  inv_fun_on f set.univ\n\ntheorem inv_fun_eq {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} (h : \u2203 (a : \u03b1), f a = b) : f (inv_fun f b) = b := sorry\n\ntheorem inv_fun_neg {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} (h : \u00ac\u2203 (a : \u03b1), f a = b) : inv_fun f b = Classical.choice n := sorry\n\ntheorem inv_fun_eq_of_injective_of_right_inverse {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b1} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=\n  funext\n    fun (b : \u03b2) =>\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 {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) : right_inverse (inv_fun f) f :=\n  fun (b : \u03b2) => inv_fun_eq (hf b)\n\ntheorem left_inverse_inv_fun {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : injective f) : left_inverse (inv_fun f) f :=\n  fun (b : \u03b1) => (fun (this : f (inv_fun f (f b)) = f b) => hf this) (inv_fun_eq (Exists.intro b rfl))\n\ntheorem inv_fun_surjective {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : injective f) : surjective (inv_fun f) :=\n  left_inverse.surjective (left_inverse_inv_fun hf)\n\ntheorem inv_fun_comp {\u03b1 : Type u} [n : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : injective f) : inv_fun f \u2218 f = id :=\n  funext (left_inverse_inv_fun hf)\n\ntheorem injective.has_left_inverse {\u03b1 : Type u} [i : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Type u} [i : Nonempty \u03b1] {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} : injective f \u2194 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  `\u03b1` to be inhabited.) -/\ndef surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (h : surjective f) (b : \u03b2) : \u03b1 :=\n  classical.some (h b)\n\ntheorem surj_inv_eq {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (h : surjective f) (b : \u03b2) : f (surj_inv h b) = b :=\n  classical.some_spec (h b)\n\ntheorem right_inverse_surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (hf : surjective f) : right_inverse (surj_inv hf) f :=\n  surj_inv_eq hf\n\ntheorem left_inverse_surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} : surjective f \u2194 has_right_inverse f :=\n  { mp := surjective.has_right_inverse, mpr := has_right_inverse.surjective }\n\ntheorem bijective_iff_has_inverse {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} : bijective f \u2194 \u2203 (g : \u03b2 \u2192 \u03b1), left_inverse g f \u2227 right_inverse g f := sorry\n\ntheorem injective_surj_inv {\u03b1 : Sort u} {\u03b2 : Sort v} {f : \u03b1 \u2192 \u03b2} (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 {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (f : (a : \u03b1) \u2192 \u03b2 a) (a' : \u03b1) (v : \u03b2 a') (a : \u03b1) : \u03b2 a :=\n  dite (a = a') (fun (h : a = a') => Eq._oldrec v (Eq.symm h)) fun (h : \u00aca = a') => f a\n\n/-- On non-dependent functions, `function.update` can be expressed as an `ite` -/\ntheorem update_apply {\u03b1 : Sort u} [DecidableEq \u03b1] {\u03b2 : Sort u_1} (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) (b : \u03b2) (a : \u03b1) : update f a' b a = ite (a = a') b (f a) := sorry\n\n@[simp] theorem update_same {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (a : \u03b1) (v : \u03b2 a) (f : (a : \u03b1) \u2192 \u03b2 a) : update f a v a = v :=\n  dif_pos rfl\n\ntheorem update_injective {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (f : (a : \u03b1) \u2192 \u03b2 a) (a' : \u03b1) : injective (update f a') := sorry\n\n@[simp] theorem update_noteq {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {a : \u03b1} {a' : \u03b1} (h : a \u2260 a') (v : \u03b2 a') (f : (a : \u03b1) \u2192 \u03b2 a) : update f a' v a = f a :=\n  dif_neg h\n\ntheorem forall_update_iff {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (f : (a : \u03b1) \u2192 \u03b2 a) {a : \u03b1} {b : \u03b2 a} (p : (a : \u03b1) \u2192 \u03b2 a \u2192 Prop) : (\u2200 (x : \u03b1), p x (update f a b x)) \u2194 p a b \u2227 \u2200 (x : \u03b1), x \u2260 a \u2192 p x (f x) := sorry\n\ntheorem update_eq_iff {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b2 a} {f : (a : \u03b1) \u2192 \u03b2 a} {g : (a : \u03b1) \u2192 \u03b2 a} : update f a b = g \u2194 b = g a \u2227 \u2200 (x : \u03b1), x \u2260 a \u2192 f x = g x :=\n  iff.trans funext_iff (forall_update_iff f fun (x : \u03b1) (y : \u03b2 x) => y = g x)\n\ntheorem eq_update_iff {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {a : \u03b1} {b : \u03b2 a} {f : (a : \u03b1) \u2192 \u03b2 a} {g : (a : \u03b1) \u2192 \u03b2 a} : g = update f a b \u2194 g a = b \u2227 \u2200 (x : \u03b1), x \u2260 a \u2192 g x = f x :=\n  iff.trans funext_iff (forall_update_iff f fun (x : \u03b1) (y : \u03b2 x) => g x = y)\n\n@[simp] theorem update_eq_self {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] (a : \u03b1) (f : (a : \u03b1) \u2192 \u03b2 a) : update f a (f a) = f :=\n  iff.mpr update_eq_iff { left := rfl, right := fun (_x : \u03b1) (_x_1 : _x \u2260 a) => rfl }\n\ntheorem update_comp_eq_of_forall_ne' {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [DecidableEq \u03b1] {\u03b1' : Sort u_1} (g : (a : \u03b1) \u2192 \u03b2 a) {f : \u03b1' \u2192 \u03b1} {i : \u03b1} (a : \u03b2 i) (h : \u2200 (x : \u03b1'), f x \u2260 i) : (fun (j : \u03b1') => update g i a (f j)) = fun (j : \u03b1') => g (f j) :=\n  funext fun (x : \u03b1') => 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 {\u03b1' : Sort w} [DecidableEq \u03b1'] {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} (g : \u03b1' \u2192 \u03b2) {f : \u03b1 \u2192 \u03b1'} {i : \u03b1'} (a : \u03b2) (h : \u2200 (x : \u03b1), f x \u2260 i) : update g i a \u2218 f = g \u2218 f :=\n  update_comp_eq_of_forall_ne' g a h\n\ntheorem update_comp_eq_of_injective' {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {\u03b1' : Sort w} [DecidableEq \u03b1] [DecidableEq \u03b1'] (g : (a : \u03b1) \u2192 \u03b2 a) {f : \u03b1' \u2192 \u03b1} (hf : injective f) (i : \u03b1') (a : \u03b2 (f i)) : (fun (j : \u03b1') => update g (f i) a (f j)) = update (fun (i : \u03b1') => g (f i)) i a :=\n  iff.mpr eq_update_iff\n    { left := update_same (f i) a g, right := fun (j : \u03b1') (hj : j \u2260 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 {\u03b1 : Sort u} {\u03b1' : Sort w} [DecidableEq \u03b1] [DecidableEq \u03b1'] {\u03b2 : Sort u_1} (g : \u03b1' \u2192 \u03b2) {f : \u03b1 \u2192 \u03b1'} (hf : injective f) (i : \u03b1) (a : \u03b2) : update g (f i) a \u2218 f = update (g \u2218 f) i a :=\n  update_comp_eq_of_injective' g hf i a\n\ntheorem apply_update {\u03b9 : Sort u_1} [DecidableEq \u03b9] {\u03b1 : \u03b9 \u2192 Sort u_2} {\u03b2 : \u03b9 \u2192 Sort u_3} (f : (i : \u03b9) \u2192 \u03b1 i \u2192 \u03b2 i) (g : (i : \u03b9) \u2192 \u03b1 i) (i : \u03b9) (v : \u03b1 i) (j : \u03b9) : f j (update g i v j) = update (fun (k : \u03b9) => f k (g k)) i (f i v) j := sorry\n\ntheorem comp_update {\u03b1 : Sort u} [DecidableEq \u03b1] {\u03b1' : Sort u_1} {\u03b2 : Sort u_2} (f : \u03b1' \u2192 \u03b2) (g : \u03b1 \u2192 \u03b1') (i : \u03b1) (v : \u03b1') : f \u2218 update g i v = update (f \u2218 g) i (f v) :=\n  funext (apply_update (fun (x : \u03b1) => f) g i v)\n\ntheorem update_comm {\u03b1 : Sort u_1} [DecidableEq \u03b1] {\u03b2 : \u03b1 \u2192 Sort u_2} {a : \u03b1} {b : \u03b1} (h : a \u2260 b) (v : \u03b2 a) (w : \u03b2 b) (f : (a : \u03b1) \u2192 \u03b2 a) : update (update f a v) b w = update (update f b w) a v := sorry\n\n@[simp] theorem update_idem {\u03b1 : Sort u_1} [DecidableEq \u03b1] {\u03b2 : \u03b1 \u2192 Sort u_2} {a : \u03b1} (v : \u03b2 a) (w : \u03b2 a) (f : (a : \u03b1) \u2192 \u03b2 a) : update (update f a v) a w = update f a w := sorry\n\n/-- `extend f g e'` extends a function `g : \u03b1 \u2192 \u03b3`\nalong a function `f : \u03b1 \u2192 \u03b2` to a function `\u03b2 \u2192 \u03b3`,\nby using the values of `g` on the range of `f`\nand the values of an auxiliary function `e' : \u03b2 \u2192 \u03b3` elsewhere.\n\nMostly useful when `f` is injective. -/\ndef extend {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) : \u03b2 \u2192 \u03b3 :=\n  fun (b : \u03b2) =>\n    dite (\u2203 (a : \u03b1), f a = b) (fun (h : \u2203 (a : \u03b1), f a = b) => g (classical.some h)) fun (h : \u00ac\u2203 (a : \u03b1), f a = b) => e' b\n\ntheorem extend_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) (b : \u03b2) : extend f g e' b =\n  dite (\u2203 (a : \u03b1), f a = b) (fun (h : \u2203 (a : \u03b1), f a = b) => g (classical.some h)) fun (h : \u00ac\u2203 (a : \u03b1), f a = b) => e' b :=\n  rfl\n\n@[simp] theorem extend_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {f : \u03b1 \u2192 \u03b2} (hf : injective f) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) (a : \u03b1) : extend f g e' (f a) = g a := sorry\n\n@[simp] theorem extend_comp {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {f : \u03b1 \u2192 \u03b2} (hf : injective f) (g : \u03b1 \u2192 \u03b3) (e' : \u03b2 \u2192 \u03b3) : extend f g e' \u2218 f = g :=\n  funext fun (a : \u03b1) => extend_apply hf g e' a\n\ntheorem uncurry_def {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) : uncurry f = fun (p : \u03b1 \u00d7 \u03b2) => f (prod.fst p) (prod.snd p) :=\n  rfl\n\n@[simp] theorem uncurry_apply_pair {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (x : \u03b1) (y : \u03b2) : uncurry f (x, y) = f x y :=\n  rfl\n\n@[simp] theorem curry_apply {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u00d7 \u03b2 \u2192 \u03b3) (x : \u03b1) (y : \u03b2) : 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 {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {\u03b5 : Type u_5} (f : \u03b3 \u2192 \u03b4 \u2192 \u03b5) (g : \u03b1 \u2192 \u03b3) (h : \u03b2 \u2192 \u03b4) (a : \u03b1) (b : \u03b2) : \u03b5 :=\n  f (g a) (h b)\n\n/-- Compose an unary function `f` with a binary function `g`. -/\ndef bicompr {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b3 \u2192 \u03b4) (g : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (a : \u03b1) (b : \u03b2) : \u03b4 :=\n  f (g a b)\n\n-- Suggested local notation:\n\ntheorem uncurry_bicompr {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (g : \u03b3 \u2192 \u03b4) : uncurry (bicompr g f) = g \u2218 uncurry f :=\n  rfl\n\ntheorem uncurry_bicompl {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} {\u03b5 : Type u_5} (f : \u03b3 \u2192 \u03b4 \u2192 \u03b5) (g : \u03b1 \u2192 \u03b3) (h : \u03b2 \u2192 \u03b4) : uncurry (bicompl f g h) = uncurry f \u2218 prod.map g h :=\n  rfl\n\n/-- Records a way to turn an element of `\u03b1` into a function from `\u03b2` to `\u03b3`. The most generic use\nis to recursively uncurry. For instance `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4` will be turned into\n`\u21bff : \u03b1 \u00d7 \u03b2 \u00d7 \u03b3 \u2192 \u03b4`. One can also add instances for bundled maps. -/\nclass has_uncurry (\u03b1 : Type u_5) (\u03b2 : outParam (Type u_6)) (\u03b3 : outParam (Type u_7)) \nwhere\n  uncurry : \u03b1 \u2192 \u03b2 \u2192 \u03b3\n\nprefix:1024 \"\u21bf\" => Mathlib.function.has_uncurry.uncurry\n\n/-- Uncurrying operator. The most generic use is to recursively uncurry. For instance\n`f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b4` will be turned into `\u21bff : \u03b1 \u00d7 \u03b2 \u00d7 \u03b3 \u2192 \u03b4`. One can also add instances\nfor bundled maps.-/\nprotected instance has_uncurry_base {\u03b1 : Type u_1} {\u03b2 : Type u_2} : has_uncurry (\u03b1 \u2192 \u03b2) \u03b1 \u03b2 :=\n  has_uncurry.mk id\n\nprotected instance has_uncurry_induction {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {\u03b4 : Type u_4} [has_uncurry \u03b2 \u03b3 \u03b4] : has_uncurry (\u03b1 \u2192 \u03b2) (\u03b1 \u00d7 \u03b3) \u03b4 :=\n  has_uncurry.mk fun (f : \u03b1 \u2192 \u03b2) (p : \u03b1 \u00d7 \u03b3) => has_uncurry.uncurry (f (prod.fst p)) (prod.snd p)\n\n/-- A function is involutive, if `f \u2218 f = id`. -/\ndef involutive {\u03b1 : Sort u_1} (f : \u03b1 \u2192 \u03b1) :=\n  \u2200 (x : \u03b1), f (f x) = x\n\ntheorem involutive_iff_iter_2_eq_id {\u03b1 : Sort u_1} {f : \u03b1 \u2192 \u03b1} : involutive f \u2194 nat.iterate f (bit0 1) = id :=\n  iff.symm funext_iff\n\nnamespace involutive\n\n\n@[simp] theorem comp_self {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : f \u2218 f = id :=\n  funext h\n\nprotected theorem left_inverse {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : left_inverse f f :=\n  h\n\nprotected theorem right_inverse {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : right_inverse f f :=\n  h\n\nprotected theorem injective {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : injective f :=\n  left_inverse.injective (involutive.left_inverse h)\n\nprotected theorem surjective {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : surjective f :=\n  fun (x : \u03b1) => Exists.intro (f x) (h x)\n\nprotected theorem bijective {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) : bijective f :=\n  { left := involutive.injective h, right := involutive.surjective h }\n\n/-- Involuting an `ite` of an involuted value `x : \u03b1` negates the `Prop` condition in the `ite`. -/\nprotected theorem ite_not {\u03b1 : Sort u} {f : \u03b1 \u2192 \u03b1} (h : involutive f) (P : Prop) [Decidable P] (x : \u03b1) : f (ite P x (f x)) = ite (\u00acP) x (f x) := sorry\n\nend involutive\n\n\n/-- The property of a binary function `f : \u03b1 \u2192 \u03b2 \u2192 \u03b3` being injective.\n  Mathematically this should be thought of as the corresponding function `\u03b1 \u00d7 \u03b2 \u2192 \u03b3` being injective.\n-/\ndef injective2 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {\u03b3 : Sort u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) :=\n  \u2200 {a\u2081 a\u2082 : \u03b1} {b\u2081 b\u2082 : \u03b2}, f a\u2081 b\u2081 = f a\u2082 b\u2082 \u2192 a\u2081 = a\u2082 \u2227 b\u2081 = b\u2082\n\nnamespace injective2\n\n\nprotected theorem left {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hf : injective2 f) {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} (h : f a\u2081 b\u2081 = f a\u2082 b\u2082) : a\u2081 = a\u2082 :=\n  and.left (hf h)\n\nprotected theorem right {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hf : injective2 f) {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} (h : f a\u2081 b\u2081 = f a\u2082 b\u2082) : b\u2081 = b\u2082 :=\n  and.right (hf h)\n\ntheorem eq_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (hf : injective2 f) {a\u2081 : \u03b1} {a\u2082 : \u03b1} {b\u2081 : \u03b2} {b\u2082 : \u03b2} : f a\u2081 b\u2081 = f a\u2082 b\u2082 \u2194 a\u2081 = a\u2082 \u2227 b\u2081 = b\u2082 := 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 `\u03b1` is a proposition, in which case `f` is necessarily a\nconstant function, so that `sometimes f = f a` for all `a`. -/\ndef sometimes {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} [Nonempty \u03b2] (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  dite (Nonempty \u03b1) (fun (h : Nonempty \u03b1) => f (Classical.choice h)) fun (h : \u00acNonempty \u03b1) => Classical.choice _inst_1\n\ntheorem sometimes_eq {p : Prop} {\u03b1 : Sort u_1} [Nonempty \u03b1] (f : p \u2192 \u03b1) (a : p) : sometimes f = f a :=\n  dif_pos (Nonempty.intro a)\n\ntheorem sometimes_spec {p : Prop} {\u03b1 : Sort u_1} [Nonempty \u03b1] (P : \u03b1 \u2192 Prop) (f : p \u2192 \u03b1) (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 {\u03b1 : Type u} {\u03b2 : \u03b1 \u2192 Sort v} (s : set \u03b1) (f : (i : \u03b1) \u2192 \u03b2 i) (g : (i : \u03b1) \u2192 \u03b2 i) [(j : \u03b1) \u2192 Decidable (j \u2208 s)] (i : \u03b1) : \u03b2 i :=\n  ite (i \u2208 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 \u27f6 X) (h' : g \u226b h = h \u226b g) :\n    f \u226b g \u226b h = f \u226b h \u226b g := by rw [h']\n\n-- If there is already a `ConcreteCategory` instance, do not add a new argument.\nexample : \u2200 C [Category C] [ConcreteCategory C] (X : C) (f g h : X \u27f6 X) (_ : g \u226b h = h \u226b 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 \u27f6 X) (h' : g \u226b h = h \u226b g) :\n    f \u226b g \u226b h = f \u226b h \u226b g := by rw [h']\n\n-- If there is not already a `ConcreteCategory` instance, insert a new argument.\nexample : \u2200 C [Category C] (X : C) (f g h : X \u27f6 X) (_ : g \u226b h = h \u226b 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 \u2245 Y) : f.hom \u226b f.inv = \ud835\udfd9 X :=\n  Iso.hom_inv_id _\n\nexample : \u2200 C [Category C] (X Y : C) (f : X \u2245 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 : \u2200 C [Category C] (X Y : C) (f : X \u2245 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 \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) : f \u226b \ud835\udfd9 N \u226b g = h := by\n  simp [w]\n\n@[elementwise]\nlemma foo' [Category C]\n    {M N K : C} {f : M \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) : f \u226b \ud835\udfd9 N \u226b g = h := by\n  simp [w]\n\nlemma bar [Category C] [ConcreteCategory C]\n    {M N K : C} {f : M \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) (x : M) : g (f x) = h x := by\n  apply foo_apply w\n\nexample {M N K : Type} {f : M \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) (x : M) :\n  g (f x) = h x := by\n  have := elementwise_of% w\n  guard_hyp this : \u2200 (x : M), g (f x) = h x\n  exact this x\n\nexample {M N K : Type} {f : M \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b 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 \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) (x : M) :\n    g (f x) = h x := by\n  have := elementwise_of% w\n  guard_hyp this : \u2200 (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 : \u2200 D [Category D] (X Y : D) (f : X \u27f6 Y) (g : Y \u27f6 X), f \u226b g = \ud835\udfd9 X)\n    {M N : C} {f : M \u27f6 N} {g : N \u27f6 M} (x : M) : g (f x) = x := by\n  have := elementwise_of% h\n  guard_hyp this : \u2200 D [Category D] (X Y : D) (f : X \u27f6 Y) (g : Y \u27f6 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 \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b 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 \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) (x : M) :\n    g (f x) = h x := by apply foo_apply w\n\nlemma bar''' {M N K : Mon} {f : M \u27f6 N} {g : N \u27f6 K} {h : M \u27f6 K} (w : f \u226b g = h) (x : M) :\n  g (f x) = h x := by apply foo_apply w\n\nexample (M N K : Mon) (f : M \u27f6 N) (g : N \u27f6 K) (h : M \u27f6 K) (w : f \u226b g = h) (m : M) :\n    g (f m) = h m := by rw [elementwise_of% w]\n\nexample (M N K : Mon) (f : M \u27f6 N) (g : N \u27f6 K) (h : M \u27f6 K) (w : f \u226b 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 {\u03b1 \u03b2 : Type} (f g : \u03b1 \u27f6 \u03b2) (w : f = g) (a : \u03b1) : f a = g a := by\n  -- porting note: did not port `elementwise!` tactic\n  replace w := elementwise_of% w\n  guard_hyp w : \u2200 (x : \u03b1), f x = g x\n  rw [w]\n\n\nexample {\u03b1 \u03b2 : Type} (f g : \u03b1 \u27f6 \u03b2) (w : f \u226b \ud835\udfd9 \u03b2 = g) (a : \u03b1) : f a = g a := by\n  -- porting note: did not port `elementwise!` tactic\n  replace w := elementwise_of% w\n  guard_hyp w : \u2200 (x : \u03b1), 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": "/-\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.Elab.Tactic.Simp\n\n/-!\n# `squeeze_scope` tactic\n\nThe `squeeze_scope` tactic allows aggregating multiple calls to `simp` coming from the same syntax\nbut in different branches of execution, such as in `cases x <;> simp`.\nThe reported `simp` call covers all simp lemmas used by this syntax.\n-/\nnamespace Std.Tactic\nopen Lean Elab Parser Tactic\n\n/--\n`squeeze_scope a => tacs` is part of the implementation of `squeeze_scope`.\nInside `tacs`, invocations of `simp` wrapped with `squeeze_wrap a _ => ...` will contribute\nto the accounting associated to scope `a`.\n-/\nlocal syntax (name := squeezeScopeIn) \"squeeze_scope \" ident \" => \" tacticSeq : tactic\n/--\n`squeeze_wrap a x => tac` is part of the implementation of `squeeze_scope`.\nHere `tac` will be a `simp` or `dsimp` syntax, and `squeeze_wrap` will run the tactic\nand contribute the generated `usedSimps` to the `squeezeScopes[a][x]` variable.\n-/\nlocal syntax (name := squeezeWrap) \"squeeze_wrap \" ident ident \" => \" tactic : tactic\n\nopen TSyntax.Compat in\n/--\nThe `squeeze_scope` tactic allows aggregating multiple calls to `simp` coming from the same syntax\nbut in different branches of execution, such as in `cases x <;> simp`.\nThe reported `simp` call covers all simp lemmas used by this syntax.\n```\n@[simp] def bar (z : Nat) := 1 + z\n@[simp] def baz (z : Nat) := 1 + z\n\n@[simp] def foo : Nat \u2192 Nat \u2192 Nat\n  | 0, z => bar z\n  | _+1, z => baz z\n\nexample : foo x y = 1 + y := by\n  cases x <;> simp? -- two printouts:\n  -- \"Try this: simp only [foo, bar]\"\n  -- \"Try this: simp only [foo, baz]\"\n\nexample : foo x y = 1 + y := by\n  squeeze_scope\n    cases x <;> simp -- only one printout: \"Try this: simp only [foo, baz, bar]\"\n```\n-/\nmacro (name := squeezeScope) \"squeeze_scope \" seq:tacticSeq : tactic => do\n  let a \u2190 withFreshMacroScope `(a)\n  let seq \u2190 seq.raw.rewriteBottomUpM fun stx =>\n    match stx.getKind with\n    | ``dsimp | ``simpAll | ``simp => do\n      withFreshMacroScope `(tactic| squeeze_wrap $a x => $stx)\n    | _ => pure stx\n  `(tactic| squeeze_scope $a => $seq)\n\nopen Meta\n\n/--\nWe implement `squeeze_scope` using a global variable that tracks all `squeeze_scope` invocations\nin flight. It is a map `a \u21a6 (x \u21a6 (stx, simps))` where `a` is a unique identifier for\nthe `squeeze_scope` invocation which is shared with all contained simps, and `x` is a unique\nidentifier for a particular piece of simp syntax (which can be called multiple times).\nWithin that, `stx` is the simp syntax itself, and `simps` is the aggregated list of simps used\nso far.\n-/\ninitialize squeezeScopes : IO.Ref (NameMap (NameMap (Syntax \u00d7 List Simp.UsedSimps))) \u2190 IO.mkRef {}\n\nelab_rules : tactic\n  | `(tactic| squeeze_scope $a => $tac) => do\n    let a := a.getId\n    let old \u2190 squeezeScopes.modifyGet fun map => (map.find? a, map.insert a {})\n    let reset map := match old with | some old => map.insert a old | none => map.erase a\n    let new \u2190 try\n      Elab.Tactic.evalTactic tac\n      squeezeScopes.modifyGet fun map => (map.find? a, reset map)\n    catch e =>\n      squeezeScopes.modify reset\n      throw e\n    if let some new := new then\n      for (_, stx, usedSimps) in new do\n        let usedSimps := usedSimps.foldl (fun s usedSimps => usedSimps.fold .insert s) {}\n        Elab.Tactic.traceSimpCall stx usedSimps\n\n-- TODO: move to core\n/-- Implementation of `dsimp`. -/\ndef dsimpLocation' (ctx : Simp.Context) (loc : Location) : TacticM Simp.UsedSimps := do\n  match loc with\n  | Location.targets hyps simplifyTarget =>\n    withMainContext do\n      let fvarIds \u2190 getFVarIds hyps\n      go fvarIds simplifyTarget\n  | Location.wildcard =>\n    withMainContext do\n      go (\u2190 (\u2190 getMainGoal).getNondepPropHyps) (simplifyTarget := true)\nwhere\n  /-- Implementation of `dsimp`. -/\n  go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM Simp.UsedSimps := do\n    let mvarId \u2190 getMainGoal\n    let (result?, usedSimps) \u2190\n      dsimpGoal mvarId ctx (simplifyTarget := simplifyTarget) (fvarIdsToSimp := fvarIdsToSimp)\n    match result? with\n    | none => replaceMainGoal []\n    | some mvarId => replaceMainGoal [mvarId]\n    pure usedSimps\n\nelab_rules : tactic\n  | `(tactic| squeeze_wrap $a $x => $tac) => do\n    let stx := tac.raw\n    let usedSimps \u2190 match stx.getKind with\n    | ``Parser.Tactic.simp => do\n      let { ctx, dischargeWrapper } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false)\n      dischargeWrapper.with fun discharge? =>\n        simpLocation ctx discharge? (expandOptLocation stx[5])\n    | ``Parser.Tactic.simpAll => do\n      let { ctx, .. } \u2190 mkSimpContext stx\n        (eraseLocal := true) (kind := .simpAll) (ignoreStarArg := true)\n      let (result?, usedSimps) \u2190 simpAll (\u2190 getMainGoal) ctx\n      match result? with\n      | none => replaceMainGoal []\n      | some mvarId => replaceMainGoal [mvarId]\n      pure usedSimps\n    | ``Parser.Tactic.dsimp => do\n      let { ctx, .. } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false) (kind := .dsimp)\n      dsimpLocation' ctx (expandOptLocation stx[5])\n    | _ => Elab.throwUnsupportedSyntax\n    let a := a.getId; let x := x.getId\n    squeezeScopes.modify fun map => Id.run do\n      let some map1 := map.find? a | return map\n      let newSimps := match map1.find? x with\n      | some (stx, oldSimps) => (stx, usedSimps :: oldSimps)\n      | none => (stx, [usedSimps])\n      map.insert a (map1.insert x newSimps)\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/SqueezeScope.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761019, "lm_q2_score": 0.04885777567918882, "lm_q1q2_score": 0.01374885145375416}}
{"text": "import tactic.rewrite_search\n\nopen tactic.rewrite_search.discovery\n\nnamespace tactic.rewrite_search.testing\n\n@[bundle] meta def algebraic_geometry : bundle := {}\n\nprivate axiom foo : [0] = [1]\nprivate axiom bar1 : [1] = [2]\nprivate axiom bar2 : [3] = [2]\nprivate axiom bar3 : [3] = [4]\n\nprivate def my_example (a : unit) : [[0],[0]] = [[4],[4]] :=\nbegin\n  -- These don't work (because they don't know about the lemmas):\n  success_if_fail { rewrite_search {} },\n  success_if_fail { rewrite_search_using [`search] {} },\n\n  -- But manually specifying them does:\n  rewrite_search_with [foo, bar1, \u2190 bar2, bar2, \u2190 bar3] {},\nend\n\n-- Let's add them to the `algebraic_geometry` bundle:\nattribute [search algebraic_geometry] foo bar1 bar2 bar3\n\n-- Now because they are under the `search xxx` namespace whatever,\n-- the following \"old\" thing will succeed\n\nprivate example : [[0],[0]] = [[4],[4]] :=\nbegin\n  rewrite_search_using [`search] {},\nend\n\n-- And manually suggesting the `algebraic_geometry` bundle\n-- will work too:\n\nprivate example : [[0],[0]] = [[4],[4]] :=\nbegin\n  rewrite_search {suggest := [`algebraic_geometry]}\nend\n\n-- Finally (and probably most commonly), you can suggest some number\n-- of bundles via:\n\n@[suggest] meta def my_suggestion := `algebraic_geometry\n\n-- or:\n\n@[suggest] meta def my_suggestion2 := [`algebraic_geometry, `default]\n\n-- The discovery code will accept both a name, or a list of names,\n-- as tagged with `[suggest]`.\n\n-- This is pretty cool, because any number of suggestions will be\n-- considered and are available to the `rewrite_search`er, not\n-- just the last one to be tagged `[suggest]` or something.\n--\n-- Also, you can use `local attribute xxx` and imports to constrain\n-- the scope of where your suggestions apply, just like you were\n-- doing before with [search] in the category theory library.\n\n\n\n-- In terms of using `[search xxx]`, the attribute will accept any\n-- `xxx` which is a bundle which has already been declared as\n-- `@[bundle]`. You can also leave the `xxx` off and just annotate\n-- as `@[search]`, which will add the lemma to all of the default\n-- bundles. At the moment, the list consists of only one bundle, and\n-- it is called `default`.\n--\n-- Lemmas can be part of multiple bundles too simultanously, either\n-- with annotations declared in separate places, or in the same place\n-- via the list syntax:\n\n@[search [algebraic_geometry, default]] private axiom bar4 : [3] = [4]\n\n-- (Here we add `bar4` to both `algebraic_geometry` and `default`\n-- at the same time.)\n\n\n\n\n\n-- When `rewrite_search` goes to run, it does not do several ugly\n-- attribute lookups over all bundles, and then all of their children.\n-- Instead, all of the membership is cached at *parse* time via\n-- some tricky (if I do say so myself ;)) hiding and updating of\n-- mutable state in annotations. In fact, we even cache the\n-- resolved names of which bundles you refer to when you annotate\n-- with `@[suggest]` (and then forget this state when you go out\n-- of scope).\n\n\n\n\n\n-- The idea is to have builtin bundles under\n--\n--    tactic.rewrite_search.discovery.bundles\n--\n-- which are imported everytime you include\n--\n--    tactic.rewrite_search\n--\n-- but as you can see, anyone can create one or modify an existing one\n-- on the fly.\n\n\n\n\n\n-- One more thing: the bundle names ARE NOT the names of objects\n-- declared of type bundle. They are anything you want, and can\n-- choosen as you like:\n\n@[bundle] meta def scotts_fave_bundle : bundle := {name := `the_real_name}\n\n-- And so this will work:\n\n@[search the_real_name] private axiom bar5 : [3] = [4]\n\n-- but this will not:\n\n-- UNCOMMENT ME\n-- @[search scotts_fave_bundle] private axiom bar4 : [3] = [4]\n\n-- This was intentional, because I didn't want the fully-scoped identifier\n-- to have to be available and `open`ed, or fully-qualified, when\n-- you go to write `@[search xxxx]`.\n--\n-- I used some autoparams tricks to default the name of a bundle\n-- to its \"lowest level\" identifier (i.e. after the last dot).\n-- So in practise this means it always gets the name you expect,\n-- and you don't have to write it.\n\n\n\n\n\n-- We also fail gracefully if you try to break the rules:\n\n-- UNCOMMENT ME:\n-- @[suggest] meta def my_suggestion_rebel : \u2115 := 0\n\n-- UNCOMMENT ME:\n-- @[suggest] meta def my_suggestion_rebel2 : name := `fake_name\n\n-- Everything else gracefully handles errors, too:\n\nprivate example : tt :=\nbegin\n-- UNCOMMENT ME:\n  -- rewrite_search {suggest := [`algssebraic_geometry]},\n\n  exact dec_trivial\nend\n\nend tactic.rewrite_search.testing\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/test/rewrite_search_discovery.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580041760868, "lm_q2_score": 0.044680875043013955, "lm_q1q2_score": 0.013733024578061895}}
{"text": "import data_util.lean_step\nimport data_util.basic\nimport system.io\nimport all\n\nmeta def dummy_dp_handler : \u2115 \u2192 \u2115 \u2192 tactic.ref \u2115 \u2192 \u2115 \u2192 LeanStepDatapoint \u2192 tactic unit := \u03bb _ _ _ _ dp, do {\n  dp_fmt \u2190 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 \u2192 tactic bool)\n  (decl_count : \u2115)\n  (decl_total : \u2115)\n  (dp_count : tactic.ref \u2115)\n  (total : \u2115)\n  : LeanStepDatapoint \u2192 tactic unit := \u03bb dp, do {\n  mcond (bnot <$> serialization_guard dp) (pure ()) $ do {\n    msg \u2190 (format.to_string \u2218 format.flatten \u2218 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 \u2190 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 \u2192 tactic bool := \u03bb dp, do {\n  let validate_expr : expr \u2192 bool := \u03bb e, (e.get_depth \u2264 SERIALIZATION_DEPTH_LIMIT) && (e.get_weight \u2264 SERIALIZATION_WEIGHT_LIMIT),\n  option.is_some <$> match dp with\n  | \u27e8_, decl_tp, hyps, _, decl_premises, _, goal, proof_term, result, next_lemma, _\u27e9 := optional $ do {\n    guard $ validate_expr decl_tp,\n    guard $ all $ hyps.map (\u03bb \u27e8x\u2081, x\u2082\u27e9, validate_expr x\u2081 && validate_expr x\u2082),\n    guard $ all $ decl_premises.map (\u03bb \u27e8x\u2081, x\u2082\u27e9, validate_expr x\u2081 && validate_expr x\u2082),\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 \u2192 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 : \u2115 \u2192 \u2115 \u2192 tactic.ref \u2115 \u2192 \u2115 \u2192 LeanStepDatapoint \u2192 tactic unit)\n  (opts : LeanStepOpts)\n  (decl_nm : name)\n  (decl_count : \u2115) (decl_total : \u2115)\n  : tactic unit := do {\n  env \u2190 tactic.get_env,\n  decl \u2190 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 \u2190 tactic.get_proof decl,\n  decl_premises \u2190 gather_used_premises pf >>= \u03bb xs, xs.mmap mk_type_annotation,\n  tactic.using_new_ref (0 : \u2115) $ \u03bb 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 : \u2200 {P Q : Prop}, ((P \u2192 Q) \u2192 P) \u2192 P :=\n\u03bb {P Q : Prop}, (em P).elim (\u03bb (_x : P) (_x_1 : (P \u2192 Q) \u2192 P), _x) $ \u03bb (_x : \u00acP) (H : (P \u2192 Q) \u2192 P), H (\u03bb (_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 : \u2115) (depth_limit : \u2115) (weight_limit : \u2115) : io unit := do {\n  nm_strs \u2190 io.mk_file_handle decls_file io.mode.read >>= readlines',\n  (nms : list (name \u00d7 list name)) \u2190 (nm_strs.filter $ \u03bb nm_str, string.length nm_str > 0).mmap $ \u03bb nm_str, do {\n    ((io.run_tactic' \u2218 parse_decl_nm_and_open_ns) $ nm_str)\n  },\n  let total := nms.length,\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n  io.run_tactic' $ tactic.using_new_ref (0 : \u2115) $ \u03bb ref,\n  for_ nms $ \u03bb \u27e8nm, _\u27e9, do {\n    count \u2190 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 \u2190 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 {\u03b1} [has_to_format \u03b1] (xs : list \u03b1) (pos : \u2115) (msg : string) (default : option \u03b1 := none) : io \u03b1 :=\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 : \u2115 \u2192 string := repr\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  decls_file \u2190 args.nth_except 0 \"decls_file\",\n  dest \u2190 args.nth_except 1 \"dest\",\n  rec_limit \u2190 string.to_nat <$> args.nth_except_with_default 2 \"rec_limit\" (5000 : \u2115).to_string,\n  serialization_depth_limit \u2190 string.to_nat <$> (args.nth_except_with_default 3 \"serialization_depth_limit\" (100 : \u2115).to_string),\n  serialization_weight_limit \u2190 string.to_nat <$> (args.nth_except_with_default 4 \"serialization_weight_limit\" (2000 : \u2115).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 {\u03b1 \u03c3} [encodable \u03b1] [inhabited \u03b1] [encodable \u03c3] (f : \u03b1 \u2192. \u03c3) :=\n(\u03bb n, (f $ (decode \u03b1 n).get_or_else (default \u03b1)).map encode)\n\ndef encode2_total {\u03b1 \u03c3}  [encodable \u03b1] [inhabited \u03b1] [encodable \u03c3] (f : \u03b1 \u2192 \u03c3) :=\n(\u03bb n, encode (f $ (decode \u03b1 n).get_or_else (default \u03b1)))\n\n@[simp] lemma encode2_total_eq {\u03b1 \u03c3} [encodable \u03b1] [inhabited \u03b1] [encodable \u03c3] (f : \u03b1 \u2192 \u03c3) : \n  encode2 (f : \u03b1 \u2192. \u03c3) = pfun.lift (encode2_total f) := funext (\u03bb x, by simp[encode2, encode2_total])\n\ntheorem rpartrec.encode2_rpartrec_in {\u03b1 \u03c3} [primcodable \u03b1] [primcodable \u03c3] [inhabited \u03b1] (f : \u03b1 \u2192. \u03c3) :\n  encode2 f partrec_in f :=\nbegin\n  simp only [encode2],\n  have c\u2080 : (\u03bb n, f ((decode \u03b1 n).get_or_else (default \u03b1))) partrec_in f :=\n  rpartrec.refl.comp ((computable.decode.option_get_or_else $ computable.const $ default \u03b1).to_rpart),\n  have c\u2081 : computable (\u03bb x, encode x.2 : \u2115 \u00d7 \u03c3 \u2192 \u2115) := computable.encode.comp computable.snd,\n  exact c\u2080.map c\u2081.to_rpart\nend\n\ntheorem rpartrec.rpartrec_in_encode2 {\u03b1 \u03c3} [primcodable \u03b1] [primcodable \u03c3]  [inhabited \u03b1] (f : \u03b1 \u2192. \u03c3) :\n  f partrec_in encode2 f :=\nbegin\n  let f' : \u03b1 \u2192. \u03c3 := (\u03bb a, (encode2 f (encode a)).bind (\u03bb x, decode \u03c3 x)),\n  have c\u2080 : (\u03bb a, encode2 f (encode a) : \u03b1 \u2192. \u2115) partrec_in encode2 f :=\n  rpartrec.refl.comp (partrec.to_rpart computable.encode),\n  have c\u2081 : partrec\u2082 (\u03bb x y, \u2191(decode \u03c3 y) : \u03b1 \u2192 \u2115 \u2192. \u03c3) := computable.decode.of_option.comp computable.snd,\n  exact ((c\u2080.bind c\u2081.to_rpart).of_eq $ \u03bb a, by simp[encode2])\nend\n\ndef graph {\u03b1 \u03b2} [decidable_eq \u03b2] (f : \u03b1 \u2192 \u03b2) : \u03b1 \u00d7 \u03b2 \u2192 bool :=\n\u03bb x, to_bool (f x.1 = x.2)\n\ndef epsilon_r {\u03b2} [primcodable \u03b2] [inhabited \u03b2] (p : \u03b2 \u2192. bool) : part \u03b2 := \n  ((nat.rfind $ \u03bb x, p ((decode \u03b2 x).get_or_else (default \u03b2))).map \n    (\u03bb x, (decode \u03b2 x).get_or_else (default \u03b2)))\n\ndef epsilon {\u03b2} [primcodable \u03b2] [inhabited \u03b2] (p : \u03b2 \u2192 bool) : part \u03b2 :=\nepsilon_r (p : \u03b2 \u2192. bool)\n\ntheorem epsilon_witness {\u03b2} [primcodable \u03b2] [inhabited \u03b2] {p : \u03b2 \u2192 bool} {b : \u03b2} :\n  b \u2208 epsilon p \u2192 p b = tt :=\nby { simp[epsilon,epsilon_r], intros x h hl he, rw he at h, simp[\u2190h] }\n\n@[simp] theorem exists_epsilon_iff {\u03b2} [primcodable \u03b2] [inhabited \u03b2] {p : \u03b2 \u2192 bool} :\n  (epsilon p).dom \u2194 (\u2203 b, p b = tt) := by { split,\n{ intros w, use (epsilon p).get w, exact epsilon_witness \u27e8w, rfl\u27e9 },\n{ rintros \u27e8b, hb\u27e9, simp[epsilon,epsilon_r, part.map, part.some],\n  use (encode b), simp[hb], use trivial} }\n\n@[simp] def initialpart {\u03b1 \u03c3} [denumerable \u03b1] (f : \u03b1 \u2192 option \u03c3) : \u2115 \u2192 list (\u03b1 \u00d7 \u03c3)\n| 0       := []\n| (n + 1) := option.cases_on (f (of_nat \u03b1 n)) (initialpart n) (\u03bb a, (of_nat \u03b1 n, a) :: initialpart n)\n\ninfix `\u21be`:70 := initialpart\n\n@[simp] theorem nat.initialpart_length {\u03b1 \u03c3} [denumerable \u03b1] (f : \u03b1 \u2192 option \u03c3) (s) : (f\u21bes).length \u2264 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 {\u03b1 \u03c3} [denumerable \u03b1] {f : \u03b1 \u2192 option \u03c3} {s n : \u2115} {a}\n  (h : n < s) (hn : f (of_nat \u03b1 n) = some a) :\n  \u2203 i, (f\u21bes).nth i = some (of_nat \u03b1 n, a) \u2227 \u2200 j b, j < i \u2192 (f\u21bes).nth j \u2260 some (of_nat \u03b1 n, b) :=\nbegin\n  induction s with s IH,\n  { simp at h, contradiction },\n  { simp[initialpart], cases C : f (of_nat \u03b1 s) with v; simp,\n    { have : n < s \u2228 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 \u2228 n = s, from nat.lt_succ_iff_lt_or_eq.mp h,\n      cases eqn_n,\n      { rcases IH eqn_n with \u27e8i, eqn_na, hi\u27e9, use i + 1, simp, refine \u27e8eqn_na, \u03bb j b eqn_j, _\u27e9,\n        cases j; simp, \n        { intros e, exfalso, \n          have : n = s, rw \u2190@denumerable.encode_of_nat \u03b1 _ s,\n            rw \u2190@denumerable.encode_of_nat \u03b1 _ 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 {\u03b1 \u03c3} [denumerable \u03b1] {f : \u03b1 \u2192 option \u03c3} (s) {n}\n  (hn : f (of_nat \u03b1 n) = none) : \u2200 i a, (f\u21bes).nth i \u2260 some (of_nat \u03b1 n, a) :=\nbegin\n  induction s with s IH generalizing n; simp[initialpart],\n  { cases C : f (of_nat \u03b1 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 {\u03b1 \u03c3} [decidable_eq \u03b1] [denumerable \u03b1] {f : \u03b1 \u2192 option \u03c3} {s a b}\n  (h : encode a < s) (hn : f a = some b) : (f\u21bes).to_fn a = some b :=\nby simp; rw (show a = of_nat \u03b1 (encode a), by simp) at hn \u22a2; exact nat.initialpart_nth h hn\n\nlemma nat.initialpart_to_fn_none {\u03b1 \u03c3} [decidable_eq \u03b1] [denumerable \u03b1] {f : \u03b1 \u2192 option \u03c3} {a}\n  (ha : f a = none) (s) : (f\u21bes).to_fn a = none :=\nby simp; rw (show a = of_nat \u03b1 (encode a), by simp) at ha \u22a2;\n   intros m y; exact nat.initialpart_nth_none s ha m y\n\ndef list.subseq {\u03b1} [decidable_eq \u03b1] (f : \u2115 \u2192 \u03b1) : list \u03b1 \u2192 bool\n| []      := tt\n| (x::xs) := to_bool (x = f xs.length) && list.subseq xs\n\nnotation l` \u2282\u2098 `f:80 := list.subseq f l\n\ndef list.subseq_t {\u03c3} [primcodable \u03c3] (f : \u2115 \u2192 \u03c3) :=\nlist.subseq (\u03bb x, encode $ f x)\n\nnotation l` \u2282\u2098* `f:80 := list.subseq_t f l\n\ntheorem subseq_iff (l : list \u2115) (f : \u2115 \u2192 \u2115) :\n  l \u2282\u2098 f \u2194 (\u2200 n, n < l.length \u2192 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 : \u2200 {n}, n < l0.length \u2192 l0.rnth n = option.some (f n), from ih.mp h.2,\n    have e : n < l0.length \u2228 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 \u2282\u2098 f) = tt,\n  { apply ih.mpr, intros n ne,\n    have h' := h n (nat.lt.step ne), rw \u2190 h',\n    simp[list.rnth], symmetry, exact list.nth_append (by simp[ne]) },\n  exact \u27e8lm0, lm1\u27e9\nend\n\ndef nat.rfind_fin0 (p : \u2115 \u2192 bool) (m : \u2115) : \u2115 \u2192 option \u2115\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 : \u2115 \u2192 bool) (m : \u2115) := nat.rfind_fin0 p m m\n\ntheorem rfind_fin0_iff (p : \u2115 \u2192 bool) : \u2200 (i m n : \u2115), i \u2264 m \u2192 \n  (nat.rfind_fin0 p m i = some n \u2194 (m - i \u2264 n \u2227 n < m \u2227 p n = tt \u2227 \u2200 l, m - i \u2264 l \u2192 l < n \u2192 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 \u2264 m, by omega), split, \n      { rintros \u27e8e0, e1, e2, h0\u27e9,\n        have l0 : \u2200 (l : \u2115), m \u2264 l + i0.succ \u2192 l < n \u2192 p l = ff,\n        { intros l el0 el1,\n          have le : m - i0.succ = l \u2228 m - i0 \u2264 l, omega,\n          cases le, simp[\u2190ep, le], simp at*,  exact h0 _ le el1 },\n        exact \u27e8show m \u2264 n + i0.succ, by omega, e1, e2, l0\u27e9 },\n      { rintros \u27e8e0, e1, e2, h0\u27e9, split,\n        { have l0 : m - i0.succ = n \u2228 m - i0 \u2264 n, omega, cases l0,\n          { exfalso, simp[l0, e2] at ep, exact ep },\n          { exact l0 } },\n        { have l0 : \u2200 (l : \u2115), m - i0 \u2264 l \u2192 l < n \u2192 p l = ff := \u03bb _ _ el1, h0 _ (by omega) el1,\n          exact \u27e8e1, e2, l0\u27e9 } } },\n    { simp, split,\n      { assume e, rcases e with rfl,\n        exact \u27e8by 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 }\u27e9 },\n      { rintros \u27e8e0, e1, e2, h0\u27e9,\n        have l0 : m - i0.succ < n \u2228 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 : \u2115 \u2192 bool} {m n : \u2115} :\n  nat.rfind_fin p m = some n \u2194 n < m \u2227 p n = tt \u2227 \u2200 {l : \u2115}, l < n \u2192 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 : \u2115 \u2192 bool} {m : \u2115} :\n  nat.rfind_fin p m = none \u2194 \u2200 {l : \u2115}, l < m \u2192 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 \u27e8m0, en, em0, hm0\u27e9,\n    have l0 : \u00acnat.rfind_fin p m = some m0, { rw e, intros c, exact option.not_mem_none _ c },\n    have nc := \u03bb n, not_congr (@rfind_fin_iff p m n), simp[-rfind_fin_iff] at nc, \n    have l1 : \u2203 (x : \u2115), x < m0 \u2227 p x = tt := (nc _).mp l0 (by omega) em0,\n    rcases l1 with \u27e8n, hn, en\u27e9,\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 \u27e8e.1, e.2.1\u27e9 }\nend\n\nnamespace primrec\n\nvariables {\u03b1 : Type*} {\u03b2 : Type*} {\u03b3 : Type*} {\u03b4 : Type*} {\u03c3 : Type*} {\u03c4 : Type*} {\u03bc : Type*}\n  [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] [primcodable \u03b4] [primcodable \u03c3] [primcodable \u03c4] [primcodable \u03bc]\n\ntheorem list_get_elem {f : \u03b1 \u2192 list \u03b2} {p : \u03b1 \u2192 \u03b2 \u2192 Prop}\n  [\u2200 a b, decidable (p a b)]\n  (hf : primrec f) (hp : primrec_rel p) :\n  primrec (\u03bb a, (f a).get_elem (p a)) :=\nlist_nth.comp hf (list_find_index hf hp)\n\ntheorem list_rnth : primrec\u2082 (@list.rnth \u03b1) := \nprimrec.list_nth.comp (primrec.list_reverse.comp primrec.fst) primrec.snd\n\ndef subseq {\u03b1} (A B : \u2115 \u2192 option \u03b1) := \u2200 n b, A n = some b \u2192 B n = some b\n\ninfix ` \u2286* `:50 := subseq\n\nend primrec\n\nnamespace rpartrec\n\nvariables {\u03b1 : Type*} {\u03b2 : Type*} {\u03b3 : Type*} {\u03b4 : Type*} {\u03c3 : Type*} {\u03c4 : Type*} {\u03bc : Type*}\n  [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] [primcodable \u03b4] [primcodable \u03c3] [primcodable \u03c4] [primcodable \u03bc]\n\ntheorem epsilon_r_rpartrec [inhabited \u03b2] (p : \u03b1 \u00d7 \u03b2 \u2192. bool) :\n  (\u03bb a, epsilon_r (\u03bb x, p (a, x))) partrec_in p :=\nbegin\n  have c\u2080 : (\u03bb x, p (x.1, (decode \u03b2 x.2).get_or_else (default \u03b2)) : \u03b1 \u00d7 \u2115 \u2192. 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 \u03b2))))\n    .to_rpart),\n  have c\u2081 : computable (\u03bb x, (decode \u03b2 x.2).get_or_else (default \u03b2) : \u03b1 \u00d7 \u2115 \u2192 \u03b2) :=\n  (computable.decode.comp computable.snd).option_get_or_else (computable.const (default \u03b2)),\n  have c\u2082 : (\u03bb a, nat.rfind $ \u03bb x, p (a, (decode \u03b2 x).get_or_else (default \u03b2))) partrec_in p, from rfind c\u2080,\n  exact c\u2082.map c\u2081.to_rpart\nend\n\ntheorem epsilon_r_rpartrec_refl [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192. bool} :\n  (\u03bb a, epsilon_r (p a)) partrec_in prod.unpaired p :=\nbegin\n  have c\u2080 : (\u03bb x, p x.1 ((decode \u03b2 x.2).get_or_else (default \u03b2)) : \u03b1 \u00d7 \u2115 \u2192. 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 \u03b2))))\n    .to_rpart),\n  have c\u2081 : computable (\u03bb x, (decode \u03b2 x.2).get_or_else (default \u03b2) : \u03b1 \u00d7 \u2115 \u2192 \u03b2) :=\n  (computable.decode.comp computable.snd).option_get_or_else (computable.const (default \u03b2)),\n  have c\u2082 : (\u03bb a, nat.rfind $ \u03bb x, p a ((decode \u03b2 x).get_or_else (default \u03b2))) partrec_in prod.unpaired p, from rfind c\u2080,\n  exact c\u2082.map c\u2081.to_rpart\nend\n\n@[rcomputability]\nprotected theorem epsilon_r [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192. bool} {g : \u03b3 \u2192. \u03c3}\n  (hp : p partrec\u2082_in g) : (\u03bb a, epsilon_r (p a)) partrec_in g :=\nepsilon_r_rpartrec_refl.trans hp\n\n@[rcomputability]\nprotected theorem epsilon [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192 bool} {g : \u03b3 \u2192. \u03c3}\n  (hp : p computable\u2082_in g) :\n  (\u03bb a, epsilon (p a)) partrec_in g :=\nepsilon_r_rpartrec_refl.trans hp\n\ntheorem epsilon_rpartrec [inhabited \u03b2] (p : \u03b1 \u00d7 \u03b2 \u2192 bool) :\n  (\u03bb a, epsilon (\u03bb x, p (a, x))) partrec_in (\u03bb x, some $ p x) :=\nepsilon_r_rpartrec _  \n\nend rpartrec\n\nnamespace rcomputable\n\nvariables {\u03b1 : Type*} {\u03b2 : Type*} {\u03b3 : Type*} {\u03b4 : Type*} {\u03c3 : Type*} {\u03c4 : Type*} {\u03bc : Type*}\n  [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] [primcodable \u03b4] [primcodable \u03c3] [primcodable \u03c4] [primcodable \u03bc]\n\n@[rcomputability]\nprotected theorem epsilon [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192 bool} {g : \u03b3 \u2192. \u03c3} (hp : p computable\u2082_in g) :\n  (\u03bb a, epsilon (p a)) partrec_in g :=\nrpartrec.epsilon_r hp\n\n@[rcomputability]\ntheorem initialpart {\u03b1} [denumerable \u03b1] {f : \u03b1 \u2192 option \u03c3} {g : \u03b2 \u2192. \u03c4}\n  (hf : f computable_in g) : (\u21be) f computable_in g :=\nbegin\n  let I : \u2115 \u2192 list (\u03b1 \u00d7 \u03c3) := (\u03bb n : \u2115, n.elim []\n    (\u03bb m IH, option.cases_on (f (of_nat \u03b1 m)) IH (\u03bb a, (of_nat \u03b1 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 $ \u03bb n, by induction n with n IH; simp[I]; simp[\u2190IH])\nend\n\ntheorem initialpart_s {\u03b1 \u03b2} [primcodable \u03b1] [denumerable \u03b2] {f : \u03b1 \u2192 \u03b2 \u2192 option \u03b3} {g : \u03b1 \u2192 \u2115} {o : \u03c3 \u2192. \u03c4}\n  (hf : f computable\u2082_in o) (hg : g computable_in o) : (\u03bb x, (f x)\u21be(g x)) computable_in o :=\nbegin\n  let I : \u03b1 \u2192 list (\u03b2 \u00d7 \u03b3) := (\u03bb a : \u03b1, (g a).elim []\n    (\u03bb m IH, option.cases_on (f a (of_nat \u03b2 m)) IH (\u03bb a, (of_nat \u03b2 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 \u03b2).comp fst.to_unary\u2082)) snd.to_unary\u2082\n    (rcomputable\u2082.list_cons.comp\u2082 (((rcomputable.of_nat \u03b2).comp fst.to_unary\u2082).to_unary\u2081.pair id'.to_unary\u2082)\n    (to_unary\u2081 snd.to_unary\u2082)) }) },\n  exact (this.of_eq $ \u03bb n, by { simp[I], induction (g n) with n IH; simp[I]; simp[\u2190IH]})\nend\n\nprivate lemma list.concat_induction {\u03b1} {C : list \u03b1 \u2192 Sort*} :\n  C [] \u2192 (\u03a0 l t, C l \u2192 C (l.concat t)) \u2192 \u03a0 l, C l :=\nbegin\n  assume h0 ih,\n  have l0 : \u03a0 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 \u03b1] (f : \u03b1 \u00d7 \u03b2 \u2192 \u03b2) :\n  (\u03bb x, list.foldr (\u03bb y z, f (y, z)) x.1 x.2 : \u03b2 \u00d7 list \u03b1 \u2192 \u03b2) computable_in (f : \u03b1 \u00d7 \u03b2 \u2192. \u03b2) :=\n  let foldr' := (\u03bb x, nat.elim x.1 \n    (\u03bb y IH, f ((x.2.reverse.nth y).get_or_else (default \u03b1), IH))\n    x.2.length : \u03b2 \u00d7 list \u03b1 \u2192 \u03b2) in\n  have c\u2080 : computable (\u03bb x, x.2.length : \u03b2 \u00d7 list \u03b1 \u2192 \u2115) :=\n  computable.list_length.comp computable.snd,\n  have c\u2081 : computable (\u03bb x, x.1 : \u03b2 \u00d7 list \u03b1 \u2192 \u03b2) := computable.fst,\n  have c\u2082 : computable (\u03bb x, (x.1.2.reverse.nth x.2.1).get_or_else (default \u03b1) :\n    (\u03b2 \u00d7 list \u03b1) \u00d7 \u2115 \u00d7 \u03b2 \u2192 \u03b1) :=\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 \u03b1),\n  have c\u2083 : (\u03bb x, f (((x.1.2.reverse.nth x.2.1).get_or_else (default \u03b1)), x.2.2) :\n    (\u03b2 \u00d7 list \u03b1) \u00d7 \u2115 \u00d7 \u03b2 \u2192 \u03b2) computable_in (f : \u03b1 \u00d7 \u03b2 \u2192. \u03b2) :=\n  refl.comp (pair c\u2082.to_rcomp (snd.comp snd)),\n  have c\u2084 : foldr' computable_in (f : \u03b1 \u00d7 \u03b2 \u2192. \u03b2) := nat_elim c\u2080.to_rcomp c\u2081.to_rcomp c\u2083,\n  have e : \u2200 a (l m : list \u03b1), nat.elim a\n    (\u03bb y IH, f (((l ++ m).nth y).get_or_else (default \u03b1), IH)) l.length =\n    nat.elim a (\u03bb y IH, f ((l.nth y).get_or_else (default \u03b1), IH)) l.length,\n  { intros a,\n    apply @list.concat_induction _ (\u03bb l, \u2200 m, nat.elim a \n      (\u03bb y IH, f (((l ++ m).nth y).get_or_else (default \u03b1), IH)) l.length = \n      nat.elim a (\u03bb y IH, f ((l.nth y).get_or_else (default \u03b1), 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\u2084.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 \u03b1] (f : \u03b1 \u00d7 \u03b2 \u2192 \u03b2) (b : \u03b2) :\n  (\u03bb x, list.foldr (\u03bb y z, f (y, z)) b x : list \u03b1 \u2192 \u03b2) computable_in (f : \u03b1 \u00d7 \u03b2 \u2192. \u03b2) := \n(foldr' f).comp (pair (const b) id)\n\n@[rcomputability]\ntheorem list_foldr' [inhabited \u03b1] {f : \u03b1 \u2192 \u03b2 \u2192 \u03b2} {o : \u03c3 \u2192. \u03c4} (hf : f computable\u2082_in o) :\n  list.foldr f computable\u2082_in o :=\nrcomputable\u2082.trans\u2082 (foldr' (prod.unpaired f)).to\u2082 hf\n\n@[rcomputability]\ntheorem list_foldr [inhabited \u03b2] {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u2192 \u03b3} {g : \u03b1 \u2192 \u03b3} {h : \u03b1 \u2192 list \u03b2} {o : \u03c3 \u2192. \u03c4}\n  (hf : (prod.unpaired3 f) computable_in o) (hg : g computable_in o) (hh : h computable_in o) :\n  (\u03bb x : \u03b1, list.foldr (f x) (g x) (h x)) computable_in o :=\nbegin\n  have eqn: \u2200 (a : \u03b1) (H\u2081 H\u2082 : list \u03b2),\n    nat.elim (g a) (\u03bb y IH, f a ((H\u2081.reverse ++ H\u2082).nth y).iget IH) H\u2081.length = \n    nat.elim (g a) (\u03bb y IH, f a (H\u2081.reverse.nth y).iget IH) H\u2081.length,\n  { intros a H\u2081 H\u2082,\n    induction H\u2081 with hd H\u2081 IH generalizing a H\u2082; simp,\n    { have eq_hd : (H\u2081.reverse ++ [hd]).nth H\u2081.length = hd,\n      { rw [show H\u2081.length = H\u2081.reverse.length, by simp, list.nth_concat_length H\u2081.reverse hd], refl },\n      have eq_hd' : (H\u2081.reverse ++ hd :: H\u2082).nth H\u2081.length = hd,\n      { rw [show H\u2081.reverse ++ hd :: H\u2082 = H\u2081.reverse ++ [hd] ++ H\u2082,by simp,\n            list.nth_append (show H\u2081.length < (H\u2081.reverse ++ [hd]).length, by simp)], simp[eq_hd] },\n      simp[eq_hd, eq_hd', IH] } },\n  have : (\u03bb a, nat.elim (g a) (\u03bb 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\u2082.list_rnth.comp (to_unary\u2081 hh) fst.to_unary\u2082)) snd.to_unary\u2082) },\n  exact this.of_eq (by { \n    intros a, induction (h a) with h H IH,\n    { simp }, simp[\u2190IH, 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 \u03b2] {g : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {f : \u03b1 \u2192 list \u03b2} {o : \u03c3 \u2192. \u03c4}\n  (hg : g computable\u2082_in o) (hf : f computable_in o) :\n(\u03bb a : \u03b1, list.map (g a) (f a)) computable_in o :=\nhave (\u03bb a, list.foldr (\u03bb b s, g a b :: s) [] (f a)) computable_in o,\n{ refine list_foldr\n  (rcomputable\u2082.list_cons.comp (rcomputable\u2082.comp hg fst fst.to_unary\u2082) snd.to_unary\u2082) (const list.nil) hf },\nthis.of_eq (\u03bb a, by simp[list.map_eq_foldr])  \n\n@[rcomputability]\nlemma list_filter [inhabited \u03b2] {p : \u03b1 \u2192 \u03b2 \u2192 Prop} [\u2200 x y, decidable (p x y)] {f : \u03b1 \u2192 list \u03b2} {o : \u03c3 \u2192. \u03c4}\n  (hp : (\u03bb a b, to_bool (p a b)) computable\u2082_in o) (hf : f computable_in o) :\n(\u03bb a : \u03b1, list.filter (p a) (f a)) computable_in o :=\nhave (\u03bb a, list.foldr (\u03bb 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\u2082))\n    (rcomputable\u2082.list_cons.comp fst.to_unary\u2082 snd.to_unary\u2082) snd.to_unary\u2082 } },\nthis.of_eq (\u03bb a, by simp[list.filter_eq_foldr])  \n\n@[rcomputability]\nlemma list_rec [inhabited \u03b2] {f : \u03b1 \u2192 list \u03b2} {g : \u03b1 \u2192 \u03b3} {h : \u03b1 \u2192 \u03b2 \u2192 list \u03b2 \u2192 \u03b3 \u2192 \u03b3} {o : \u03c3 \u2192. \u03c4}\n  (hf : f computable_in o) (hg : g computable_in o) (hh : prod.unpaired4 h computable_in o) :\n  @rcomputable _ _ \u03b3 _ _ _ _ _ (\u03bb a : \u03b1, list.rec_on (f a) (g a) (h a)) o :=\nlet F (a : \u03b1) := (f a).foldr\n  (\u03bb (b : \u03b2) (s : list \u03b2 \u00d7 \u03b3), (b :: s.1, h a b s.1 s.2)) ([], g a) in\nhave F computable_in o,\n  from list_foldr ((rcomputable\u2082.list_cons.comp fst.to_unary\u2082 (fst.comp snd.to_unary\u2082)).pair hh)\n    ((const list.nil).pair hg) hf,\n(snd.comp this).of_eq (\u03bb a, by { \n  suffices : F a = (f a, list.rec_on (f a) (g a) (\u03bb 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 \u03b1] (r : omega_ordering \u03b1) {o : \u03c3 \u2192. \u03c4}\n  (hr : r.ordering computable_in o) :\n  r.Min computable_in o :=\nbegin\n  let F : list \u03b1 \u2192 option \u03b1 := list.foldr\n    (\u03bb (a : \u03b1) (IH : option \u03b1), option.cases_on IH a\n    (\u03bb ih, if omega_ordering.ordering a \u2264 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\u2082 ((option_some.comp rpartrec.some).comp fst.to_unary\u2082) _) (const none) id',\n    { refine rcomputable.ite _ _ _,\n      { refine rcomputable\u2082.to_bool_nat_le.comp (comp hr (fst.comp snd.to_unary\u2081)) (to_unary\u2082 hr) },\n      { exact option_some.comp (fst.comp snd.to_unary\u2081) },\n      exact (option_some.comp rpartrec.some).to_unary\u2082 } },\n  exact this.of_eq (\u03bb l, by { induction l with x l IH, { simp[F, omega_ordering.Min] },\n    { simp[F, omega_ordering.Min] at IH \u22a2, rw[IH], cases C : r.Min l; simp,\n      { simp[omega_ordering.min_iff],\n        by_cases C : omega_ordering.ordering x \u2264 omega_ordering.ordering val; simp[C] } } })\nend\n\n@[rcomputability]\nlemma omega_ordering_Min_le [inhabited \u03b1] (r : omega_ordering \u03b1) (f : \u03b2 \u2192 list \u03b1) (h : \u2200 x, (f x).length > 0) {o : \u03c3 \u2192. \u03c4}\n  (hr : r.ordering computable_in o) (hf : f computable_in o) :\n  (\u03bb 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 \u03b1] {o : \u03c3 \u2192. \u03c4} : ((\u21be*) : list \u03b1 \u2192 \u2115 \u2192 list \u03b1) computable\u2082_in o :=\nbegin\n  let lindex : list \u03b1 \u2192 list (\u03b1 \u00d7 \u2115) := \u03bb l, list.rec_on l [] (\u03bb a l IH, (a, l.length) :: IH),\n  let F : list \u03b1 \u2192 \u2115 \u2192 list \u03b1 := \u03bb l n, ((lindex l).filter (\u03bb p : \u03b1 \u00d7 \u2115, p.2 < n)).map prod.fst,\n  have : F computable\u2082_in o,\n  { refine list_map (fst.to_unary\u2082)\n      (list_filter (rcomputable\u2082.to_bool_nat_lt.comp (snd.to_unary\u2082) (snd.to_unary\u2081))\n      (list_rec fst (const [])\n      (rcomputable\u2082.list_cons.comp (pair fst.to_unary\u2082 (list_length.comp (fst.comp snd.to_unary\u2082)))\n        (snd.comp snd.to_unary\u2082)))) },\n  exact this.of_eq (\u03bb l n, by { \n    induction l with x l IH; simp[F, lindex, list.filter],\n    { have : @list.rec \u03b1 (\u03bb _, list (\u03b1 \u00d7 \u2115)) [] (\u03bb (a : \u03b1) (l : list \u03b1), list.cons (a, l.length)) (x :: l) = \n        (x, l.length) :: lindex l, from rfl,\n      simp[show @list.rec \u03b1 (\u03bb _, list (\u03b1 \u00d7 \u2115)) [] (\u03bb (a : \u03b1) (l : list \u03b1), 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)\u21be*n = x :: l, from list.initial_elim (nat.succ_le_iff.mpr C),\n             show l\u21be*n = l, from list.initial_elim (le_of_lt C),\n             F, lindex] at IH \u22a2, exact IH },\n      { have : (x :: l)\u21be*n = l\u21be*n, from list.initial_cons (not_lt.mp C),\n        rw this, exact IH } } })\nend\n\n@[rcomputability]\nlemma list_weight_of [inhabited \u03b1] {wt : \u03b1 \u2192 \u2115} {o : \u03c3 \u2192. \u03c4}\n  (h : wt computable_in o) : list.weight_of wt computable_in o :=\nbegin\n  let F : list \u03b1 \u2192 \u2115 := \u03bb l, list.rec_on l 0 (\u03bb 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\u2082.nat_add.comp\n      (rcomputable\u2082.comp rpartrec.some (comp h fst.to_unary\u2082) (snd.comp snd.to_unary\u2082))\n      (const 1) },\n  exact this.of_eq (\u03bb 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 \u03b1] [inhabited \u03b1] {o : \u03c3 \u2192. \u03c4} :\n  (list.chr : list \u03b1 \u2192 \u03b1 \u2192 bool) computable\u2082_in o :=\nbegin\n  let F : list \u03b1 \u2192 \u03b1 \u2192 bool := \u03bb l a, l.filter (\u03bb x, x = a) \u2260 [],\n  have : F computable\u2082_in o,\n  { simp[F],\n    refine (dom_fintype bnot).comp\u2082\n      ((rcomputable\u2082.to_bool_eq _).comp\n        (rcomputable.list_filter ((rcomputable\u2082.to_bool_eq _).comp snd snd.to_unary\u2081) fst) (const [])) },\n  exact this.of_eq (\u03bb l a, by simp[F, list.filter_eq_nil, list.chr])\nend\n\n@[rcomputability]\ntheorem graph_rcomp [decidable_eq \u03b2] (f : \u03b1 \u2192 \u03b2) : graph f computable_in (f : \u03b1 \u2192. \u03b2) :=\n  have c\u2080 : (\u03bb x, to_bool (x.1 = x.2) : \u03b2 \u00d7 \u03b2 \u2192 bool) computable_in (f : \u03b1 \u2192. \u03b2) := primrec.eq.to_rcomp,\n  have c\u2082 : (\u03bb x, (f x.1, x.2) : \u03b1 \u00d7 \u03b2 \u2192 \u03b2 \u00d7 \u03b2) computable_in (f : \u03b1 \u2192. \u03b2) := rcomputable.pair \n  (rcomputable.refl.comp rcomputable.fst) rcomputable.snd,\nc\u2080.comp c\u2082\n\n@[rcomputability]\ntheorem subseq_rcomputable [decidable_eq \u03b1] [inhabited \u03b1] (f : \u2115 \u2192 \u03b1) :\n  list.subseq f computable_in! f :=\nbegin\n  let g := (\u03bb x, (x.2.1 + 1, x.2.2 && graph f (x.2.1, x.1)) : \u03b1 \u00d7 \u2115 \u00d7 bool \u2192 \u2115 \u00d7 bool),\n  let subseq0 := (\u03bb x, (list.foldr (\u03bb y z, g (y, z)) (0, tt) x) : list \u03b1 \u2192 \u2115 \u00d7 bool),\n  let subseq1 := (\u03bb x, (subseq0 x).2),\n  have cg : g computable_in (f : \u2115 \u2192. \u03b1) := ((computable.succ.to_rcomp).comp (fst.comp snd)).pair \n  ((primrec.to_rcomp (primrec.dom_bool\u2082 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 : \u2115 \u2192. \u03b1) := rcomputable.snd.comp (\n    list_foldr (cg.comp (pair fst.to_unary\u2082 snd.to_unary\u2082)) ((const 0).pair (const tt)) id),\n  have e : \u2200 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 $ \u03bb l, by simp[subseq1,e])\nend\n\nprivate lemma rfind_fin0 {p : \u03b1 \u2192 \u2115 \u2192 bool} {f : \u03b1 \u2192 \u2115} {g : \u03b1 \u2192 \u2115} {h : \u03b2 \u2192. \u03c4}\n  (hp : prod.unpaired p computable_in h) (hf : f computable_in h) (hg : g computable_in h) :\n  (\u03bb a, nat.rfind_fin0 (p a) (f a) (g a) : \u03b1 \u2192 option \u2115) computable_in h :=\nbegin\n  let f\u2081 : \u03b1 \u00d7 \u2115 \u00d7 option \u2115 \u2192 option \u2115 :=\n    (\u03bb 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\u2081 : f\u2081 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 : \u2200 a b n, nat.elim option.none (\u03bb 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\u2082 := nat_elim hg (const option.none) c\u2081,\n  exact (c\u2082.of_eq $ \u03bb n, by simp[f\u2081]; simp; rw e)\nend\n\n@[rcomputability]\ntheorem rfind_fin {p : \u03b1 \u2192 \u2115 \u2192 bool} {f : \u03b1 \u2192 \u2115} {g : \u03b2 \u2192. \u03c4}\n  (hp : p computable\u2082_in g) (hf : f computable_in g) :\n  (\u03bb 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 {\u03b1 : Type*} {\u03c3 : Type*} {\u03b2 : Type*} {\u03c4 : Type*} {\u03b3 : Type*} {\u03bc : Type*} {\u03bd : Type*} {o_dom : Type*} {o_cod : Type*}\n  [primcodable \u03b1] [primcodable \u03c3] [primcodable \u03b2] [primcodable \u03c4] [primcodable \u03b3] [primcodable \u03bc] [primcodable \u03bd] [primcodable o_dom] [primcodable o_cod]\n  {o : o_dom \u2192. o_cod}\n\naxiom rcomputable.code_rec {f : \u03b1 \u2192 code} {fo : \u03b1 \u2192 \u03c3} {fz : \u03b1 \u2192 \u03c3} {fs : \u03b1 \u2192 \u03c3} {fl : \u03b1 \u2192 \u03c3} {fr : \u03b1 \u2192 \u03c3}\n  {fp : \u03b1 \u2192 code \u2192 code \u2192 \u03c3 \u2192 \u03c3 \u2192 \u03c3} {fc : \u03b1 \u2192 code \u2192 code \u2192 \u03c3 \u2192 \u03c3 \u2192 \u03c3} {fpr : \u03b1 \u2192 code \u2192 code \u2192 \u03c3 \u2192 \u03c3 \u2192 \u03c3} {frf : \u03b1 \u2192 code \u2192 \u03c3 \u2192 \u03c3}\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 \u03b1 _ \u03c3 _ _ _ _ _ (\u03bb 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 (\u03bb x : \u2115 \u00d7 list (\u2115 \u00d7 \u2115) \u00d7 code \u00d7 \u2115, 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 : \u03b1 \u2192 \u2115} {l : \u03b1 \u2192 list (\u2115 \u00d7 \u2115)} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115}\n  (hs : computable s) (hl : computable l) (hc : computable c) (hn : computable n) :\n  computable (\u03bb 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 : \u2115 \u2192 option \u2115) (c n) :\n  code.eval f c n = nat.rfind_opt (\u03bb s, code.evaln s f c n) :=\npart.ext $ \u03bb 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 {\u03b1} [primcodable \u03b1]\n  {l : \u03b1 \u2192 list (\u2115 \u00d7 \u2115)} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115}\n  (hl : computable l) (hc : computable c) (hn : computable n) :\n  partrec (\u03bb x, code.eval (l x).to_fn (c x) (n x)) :=\nbegin\n  let f := (\u03bb x, nat.rfind_opt (\u03bb 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 \u03c3] [denumerable \u03c3]\n  (f : \u03c4 \u2192 option \u03bc) (c : list (\u03c3 \u00d7 \u03c4)) (n) :\n  (c.to_fn n).map f = (c.map (\u03bb x : \u03c3 \u00d7 \u03c4, (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 \u22a2, 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 \u22a2, rcases C with \u27e8m, eqn_nv, hyp\u27e9,\n    refine \u27e8m, \u27e8n, v, eqn_nv, rfl, rfl\u27e9, \u03bb k p eqn_k x y eqn_xy eqn_n eqn_p, _\u27e9,\n    have := hyp _ y eqn_k, rw [eqn_n] at eqn_xy, contradiction }\nend\n\ntheorem list.to_fn_encode_of_nat {\u03c3} [decidable_eq \u03c3] [denumerable \u03c3]\n  (c : list (\u03c3 \u00d7 \u03c4)) :\n  (\u03bb n, option.map encode (c.to_fn (of_nat \u03c3 n))) = \n  (c.map (\u03bb x : \u03c3 \u00d7 \u03c4, (encode x.1, encode x.2))).to_fn :=\nbegin\n  funext n,\n  cases C : c.to_fn (of_nat \u03c3 n) with v; simp; symmetry,\n  { simp [list.to_fn_iff_none] at C \u22a2, intros m k x y eqn_xy eqn_n eqn_k,\n    have := C m y, rw \u2190eqn_n at this, simp at this, contradiction },\n  { simp [list.to_fn_iff] at C \u22a2, rcases C with \u27e8m, eqn_nv, hyp\u27e9,\n    refine \u27e8m, \u27e8_, _, eqn_nv, (by simp), rfl\u27e9, \u03bb k z eqn_k x y eqn_xy eqn_n eqn_z, _\u27e9,\n    have := hyp _ y eqn_k, rw \u2190eqn_n at this, simp at this, contradiction }\nend\n\ntheorem computable.univn_to_fn (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3] {\u03b2} [decidable_eq \u03b2] [denumerable \u03b2]\n  {i : \u03b3 \u2192 \u2115} {l : \u03b3 \u2192 list (\u03b2 \u00d7 \u03c4)} {s : \u03b3 \u2192 \u2115} {n : \u03b3 \u2192 \u03b1}\n  (hi : computable i) (hl : computable l) (hs : computable s) (hn : computable n) :\n  computable (\u03bb x : \u03b3, (\u27e6i x\u27e7*(l x).to_fn [s x] (n x) : option \u03c3)) :=\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\u2082).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 (\u03b1 \u03c3) [primcodable \u03b1] [decidable_eq \u03c3] [denumerable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {l : \u03b3 \u2192 list (\u03c3 \u00d7 \u03c4)} {n : \u03b3 \u2192 \u03b1}\n  (hi : computable i) (hl : computable l) (hn : computable n) :\n  partrec (\u03bb x : \u03b3, (\u27e6i x\u27e7*(l x).to_fn (n x) : part \u03c3)) :=\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\u2082).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 : \u03b1 \u2192 \u2115} {f : \u2115 \u2192 option \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hs : s computable_in o) (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) : \n  (\u03bb x, code.evaln (s x) f (c x) (n x)) computable_in o :=\nbegin\n  let u := (\u03bb x, code.evaln (s x) (f\u21be(s x)).to_fn (c x) (n x)),\n  have eqn_u : (\u03bb x, code.evaln (s x) f (c x) (n x)) = u,\n  { suffices :\n      \u2200 t d, code.evaln t (f\u21bet).to_fn d = code.evaln t f d,\n    { funext, simp[u] at this \u22a2, 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 := (\u03bb x, (s x, f\u21bes 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 : \u03b1 \u2192 \u2115} {f : \u03b1 \u2192 \u2115 \u2192 option \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hs : s computable_in o) (hf : f computable\u2082_in o) (hc : c computable_in o) (hn : n computable_in o) : \n  (\u03bb x, code.evaln (s x) (f x) (c x) (n x)) computable_in o :=\nbegin\n  let u := (\u03bb x, code.evaln (s x) ((f x)\u21be(s x)).to_fn (c x) (n x)),\n  have eqn_u : (\u03bb x, code.evaln (s x) (f x) (c x) (n x)) = u,\n  { suffices :\n      \u2200 x t d, code.evaln t ((f x)\u21bet).to_fn d = code.evaln t (f x) d,\n    { funext, simp[u] at this \u22a2, 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 := (\u03bb x, (s x, (f x)\u21bes 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 : \u03b1 \u2192 \u2115} {f : \u2115 \u2192 \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hs : s computable_in o) (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) : \n  (\u03bb x, code.evaln (s x) \u2191\u2092f (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 : \u03b1 \u2192 \u2115} {f : \u03b1 \u2192 \u2115 \u2192 \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hs : s computable_in o) (hf : f computable\u2082_in o) (hc : c computable_in o) (hn : n computable_in o) : \n  (\u03bb x, code.evaln (s x) \u2191\u2092(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 : \u2115 \u2192 option \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) :\n  (\u03bb x, code.eval f (c x) (n x)) partrec_in o :=\nbegin\n  let p := (\u03bb x, nat.rfind_opt (\u03bb 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 $ \u03bb a, by simp [p, eval_eq_rfind])\nend\n\ntheorem rpartrec.eval_s {f : \u03b1 \u2192 \u2115 \u2192 option \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hf : f computable\u2082_in o) (hc : c computable_in o) (hn : n computable_in o) :\n  (\u03bb x, code.eval (f x) (c x) (n x)) partrec_in o :=\nbegin \n  let p := (\u03bb x, nat.rfind_opt (\u03bb 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\u2082.comp\u2082 hf rcomputable.fst.to_unary\u2081 rcomputable.id'.to_unary\u2082)\n      (hc.comp rcomputable.fst) (hn.comp rcomputable.fst)) },\n  exact (this.of_eq $ \u03bb a, by simp [p, eval_eq_rfind])\nend\n\ntheorem rpartrec.eval_tot {f : \u2115 \u2192 \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) :\n  (\u03bb x, code.eval (\u2191\u2092f) (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 : \u03b1 \u2192 \u2115 \u2192 \u2115} {c : \u03b1 \u2192 code} {n : \u03b1 \u2192 \u2115} {o : \u03b2 \u2192. \u03c3}\n  (hf : f computable\u2082_in o) (hc : c computable_in o) (hn : n computable_in o) :\n  (\u03bb x, code.eval (\u2191\u2092(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 (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {p : \u03b2 \u2192 option \u03c4} {s : \u03b3 \u2192 \u2115} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hp : p computable_in o) (hs : s computable_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7*p [s x] (n x) : \u03b3 \u2192 option \u03c3) 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 (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {p : \u03b2 \u2192 option \u03c4} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hp : p computable_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7*p (n x) : \u03b3 \u2192. \u03c3) 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 (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {f : \u03b2 \u2192 \u03c4} {s : \u03b3 \u2192 \u2115} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hf : f computable_in o) (hs : s computable_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7^f [s x] (n x) : \u03b3 \u2192 option \u03c3) computable_in o :=\nrcomputable.univn_w _ _ hi (rcomputable.option_some_iff.mpr hf) hs hn\n\n@[rcomputability]\ntheorem rpartrec.univ_tot (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {f : \u03b2 \u2192 \u03c4} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hf : f computable_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7^f (n x) : \u03b3 \u2192. \u03c3) partrec_in o :=\nrpartrec.univ_w _ _ hi (rcomputable.option_some_iff.mpr hf) hn\n\ntheorem rcomputable.univn_s (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {p : \u03b3 \u2192 \u03b2 \u2192 option \u03c4} {s : \u03b3 \u2192 \u2115} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hp : p computable\u2082_in o) (hs : s computable_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7*(p x) [s x] (n x) : \u03b3 \u2192 option \u03c3) computable_in o :=\nrcomputable.option_bind (rcomputable.evaln_s hs\n  (rcomputable.option_bind (rcomputable.decode.to_unary\u2082)\n    ((rcomputable.id'.option_map rcomputable.encode.to_unary\u2082).comp\u2082\n      (rcomputable\u2082.comp\u2082 hp rcomputable.fst.to_unary\u2081 rcomputable.id'.to_unary\u2082)))\n  ((primrec.of_nat _).to_rcomp.comp hi)\n  (primrec.encode.to_rcomp.comp hn)) (rcomputable.decode.to_unary\u2082)\n\ntheorem rpartrec.univ_s (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {p : \u03b3 \u2192 \u03b2 \u2192 option \u03c4} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hp : p computable\u2082_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7*(p x) (n x) : \u03b3 \u2192. \u03c3) partrec_in o :=\nrpartrec.bind (rpartrec.eval_s\n  (rcomputable.option_bind (rcomputable.decode.to_unary\u2082)\n    ((rcomputable.id'.option_map rcomputable.encode.to_unary\u2082).comp\u2082\n      (rcomputable\u2082.comp\u2082 hp rcomputable.fst.to_unary\u2081 rcomputable.id'.to_unary\u2082)))\n  ((primrec.of_nat _).to_rcomp.comp hi)\n    (primrec.encode.to_rcomp.comp hn)) ((rpartrec.coe.comp rcomputable.decode).to_unary\u2082)\n\n@[rcomputability]\ntheorem rcomputable.univn_tot_s (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {f : \u03b3 \u2192 \u03b2 \u2192 \u03c4} {s : \u03b3 \u2192 \u2115} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hf : f computable\u2082_in o) (hs : s computable_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7^(f x) [s x] (n x) : \u03b3 \u2192 option \u03c3) computable_in o :=\nrcomputable.univn_s _ _ hi (rcomputable.option_some_iff.mpr hf) hs hn\n\n@[rcomputability]\ntheorem rpartrec.univ_tot_s (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {i : \u03b3 \u2192 \u2115} {f : \u03b3 \u2192 \u03b2 \u2192 \u03c4} {n : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192. \u03bd}\n  (hi : i computable_in o) (hf : f computable\u2082_in o) (hn : n computable_in o) :\n  (\u03bb x, \u27e6i x\u27e7^(f x) (n x) : \u03b3 \u2192. \u03c3) partrec_in o :=\nrpartrec.univ_s _ _ hi (rcomputable.option_some_iff.mpr hf) hn\n\ntheorem rpartrec.exists_index {f : \u03b1 \u2192. \u03c3} {g : \u03b2 \u2192 \u03c4} :\n  f partrec_in! g \u2194 \u2203 e, \u27e6e\u27e7^g = f :=\nbegin\n  split,\n  { let g' := (\u03bb n, (decode \u03b2 n).bind (\u03bb a, some $ encode (g a))),\n    have : (\u03bb (n : \u2115), (of_option (decode \u03b2 n)).bind (\u03bb (a : \u03b2), some (encode (g a)))) = \u2191\u02b3g',\n    { funext n, simp [g'], cases decode \u03b2 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 \u27e8c, eqn_c\u27e9,\n      refine \u27e8encode c, funext $ \u03bb a, _\u27e9, simp [eqn_c, part.of_option] },\n  { rintros \u27e8e, rfl\u27e9, refine rpartrec.univ_tot _ _\n      (primrec.const e).to_rcomp rcomputable.refl rcomputable.id }\nend\n\n@[rcomputability]\ntheorem univ_partrec_in {f : \u03b1 \u2192 \u03c3} {e} :\n  (\u27e6e\u27e7^f : \u03b2 \u2192. \u03c4) 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 : \u03b1 \u2192. \u03b2) [\u2200 a, decidable (p a).dom] : p partrec_in! p.complement :=\n(rpartrec.coe.comp rpartrec.refl).of_eq (\u03bb a, by simp)\n\nend\n\n@[rcomputability]\nprotected theorem cond {c : \u03b1 \u2192 bool} {f : \u03b1 \u2192. \u03c3} {g : \u03b1 \u2192. \u03c3} {h : \u03b2 \u2192 \u03c4}\n  (hc : c computable_in! h) (hf : f partrec_in! h) (hg : g partrec_in! h) :\n  (\u03bb a, cond (c a) (f a) (g a)) partrec_in! h :=\nbegin\n  rcases exists_index.1 hf with \u27e8e, eqn_e\u27e9,\n  rcases exists_index.1 hg with \u27e8i, eqn_i\u27e9,\n  have := rpartrec.univ_tot \u03b1 \u03c3 (rcomputable.cond hc (rcomputable.const e) (rcomputable.const i))\n    rcomputable.refl rcomputable.id,\n  exact (this.of_eq $ \u03bb a, by cases eqn : c a; simp[eqn, eqn_e, eqn_i])\nend\n\ntheorem bool_to_part (c : \u03b1 \u2192 bool):\n  (\u03bb a, cond (c a) (some 0) part.none : \u03b1 \u2192. \u2115) partrec_in (c : \u03b1 \u2192. bool) :=\nrpartrec.cond rcomputable.refl (rcomputable.const 0) partrec.none.to_rpart\n\ntheorem universal_index {f : \u03b2 \u2192 \u03c4} : \u2203 u, \u2200 (x : \u2115) (y : \u03b1),\n  (\u27e6u\u27e7^f (x, y) : part \u03c3) = \u27e6x\u27e7^f y :=\nby rcases exists_index.mp \n   (rpartrec.univ_tot \u03b1 \u03c3 rcomputable.fst (rcomputable.refl_in f) rcomputable.snd) with \u27e8u, hu\u27e9;\n   exact \u27e8u, by simp[hu]\u27e9\n\ntheorem recursion (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3] (f : \u03b2 \u2192 \u03c4) :\n  \u2203 fixpoint : \u2115 \u2192 \u2115, primrec fixpoint \u2227\n  \u2200 {I : \u2115 \u2192 \u2115} {i}, \u27e6i\u27e7^f = \u2191\u1d63I \u2192\n    (\u27e6fixpoint i\u27e7^f : \u03b1 \u2192. \u03c3) = \u27e6I (fixpoint i)\u27e7^f :=\nbegin\n  have : \u2203 j, (\u27e6j\u27e7^f : \u2115 \u00d7 \u03b1 \u2192. \u03c3) = \u03bb a, (\u27e6a.1\u27e7^f a.1).bind (\u03bb n : \u2115, \u27e6n\u27e7^f a.2),\n  { have this := (rpartrec.univ_tot \u2115 \u2115 rcomputable.fst rcomputable.refl rcomputable.fst).bind\n      ((rpartrec.univ_tot \u03b1 \u03c3 rcomputable.snd rcomputable.refl (snd.comp fst).to_rcomp)).to\u2082,\n    exact exists_index.mp this },\n  rcases this with \u27e8j, lmm_j\u27e9,\n  have : \u2203 k, \u27e6k\u27e7^f = \u03bb (a : \u2115 \u00d7 \u2115), \u27e6a.1\u27e7^f (curry j a.2),\n  { have := rpartrec.curry_prim.to_comp.comp (computable.const j) computable.id,\n    have := (rpartrec.univ_tot \u2115 \u2115 rcomputable.fst rcomputable.refl \n      (this.to_rcomp.comp rcomputable.snd)),\n    exact exists_index.mp this },\n  rcases this with \u27e8k, lmm_k\u27e9,\n  let fixpoint : \u2115 \u2192 \u2115 := \u03bb 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 \u27e8fixpoint, this, _\u27e9,\n  assume I i h, funext x,\n  show \u27e6fixpoint i\u27e7^f x = \u27e6I (fixpoint i)\u27e7^f x,\n  simp[fixpoint, lmm_j, lmm_k, h],\nend\n\ntheorem recursion1 (\u03b1 \u03c3) [primcodable \u03b1] [primcodable \u03c3]\n  {f : \u03b2 \u2192 \u03c4} {I : \u2115 \u2192 \u2115} (h : I computable_in \u2191\u1d63f) :\n  \u2203 n, (\u27e6n\u27e7^f : \u03b1 \u2192. \u03c3) = \u27e6I n\u27e7^f :=\nby rcases recursion \u03b1 \u03c3 f with \u27e8fixpoint, cf, hfix\u27e9;\n   rcases exists_index.mp h with \u27e8i, hi\u27e9;\n   exact \u27e8fixpoint i, hfix hi\u27e9\n\nend rpartrec\n\nnoncomputable def bounded_computation (f : \u03b1 \u2192. \u03c3) (h : \u03b2 \u2192 \u03c4) (s : \u2115) : \u03b1 \u2192 option \u03c3 :=\n\u27e6classical.epsilon (\u03bb e : \u2115, \u27e6e\u27e7^h = f)\u27e7^h [s]\n\nnotation f`^`h` .[`s`]` := bounded_computation f h s\n  \ntheorem bounded_computation_spec {f : \u03b1 \u2192. \u03c3} {h : \u03b2 \u2192 \u03c4} (hf : f partrec_in! h)\n  {x y} : y \u2208 f x \u2194 \u2203 s, f^h.[s] x = some y :=\nbegin\n  have : y \u2208 \u27e6classical.epsilon (\u03bb (y : \u2115), \u27e6y\u27e7^h = f)\u27e7^h x \u2194\n    \u2203 (s : \u2115), \u27e6classical.epsilon (\u03bb e, \u27e6e\u27e7^h = f)\u27e7^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 (\u03c3) [primcodable \u03c3] (p : \u03b2 \u2192 option \u03c4) (e : \u2115) (s : \u2115) (x : \u03b1) : part (option \u2115) :=\ncond ((\u27e6e\u27e7*p [s] x : option \u03c3)).is_some\n  ((nat.rfind $ \u03bb u : \u2115, (\u27e6e\u27e7*p [u] x : option \u03c3).is_some).map option.some)\n  (some option.none)\n\nlemma usen_pfun_defined {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {s : \u2115} {x : \u03b1} :\n  (usen_pfun \u03c3 p e s x).dom :=\nbegin\n  simp [usen_pfun],\n  cases C : (\u27e6e\u27e7*p [s] x).is_some; simp [C, part.dom],\n  refine \u27e8s, _\u27e9, simp[C, part.some]\nend \n\ndef usen (\u03c3) [primcodable \u03c3] (f : \u03b2 \u2192 option \u03c4) (e : \u2115) (s : \u2115) (x : \u03b1) : option \u2115 :=\n(usen_pfun \u03c3 f e s x).get usen_pfun_defined\n\ndef usen0 (\u03c3) [primcodable \u03c3] (e : \u2115) (s : \u2115) (x : \u03b1) : option \u2115 := usen \u03c3 \u2191\u2092(\u03bb _, 0 : \u2115 \u2192 \u2115) e s x\n\nnotation `\u03a6\u27e6` e `\u27e7^`f ` [` s `]`  := usen _ \u2191\u2092f e s\n\nnotation `\u03a6\u27e6` e `\u27e7\u2070` ` [` s `]` := usen0 _ e s\n\n@[rcomputability]\ntheorem rcomputable.usen_tot (\u03c3) [primcodable \u03c3]\n  {f : \u03b2 \u2192 \u03c4} {i : \u03b3 \u2192 \u2115} {s : \u03b3 \u2192 \u2115} {a : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192 \u03bd}\n  (hf : f computable_in! o) (hi : i computable_in! o) (hs : s computable_in! o) (ha : a computable_in! o) :\n  (\u03bb x, usen \u03c3 \u2191\u2092f (i x) (s x) (a x)) computable_in! o :=\nbegin\n  suffices :\n    (\u03bb x, usen_pfun \u03c3 \u2191\u2092f (i x) (s x) (a x)) partrec_in! o,\n  from (this.of_eq $ \u03bb 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 (\u03c3) [primcodable \u03c3] {\u03b2} [decidable_eq \u03b2] [denumerable \u03b2]\n  {l : \u03b3 \u2192 list (\u03b2 \u00d7 \u03c4)} {i : \u03b3 \u2192 \u2115} {s : \u03b3 \u2192 \u2115} {a : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192 \u03bd}\n  (hl : computable l) (hi : computable i) (hs : computable s) (ha : computable a) :\n  computable (\u03bb x, usen \u03c3 (l x).to_fn (i x) (s x) (a x)) :=\nbegin\n  suffices :\n    partrec (\u03bb x, usen_pfun \u03c3 (l x).to_fn (i x) (s x) (a x)),\n  from (this.of_eq $ \u03bb n, by simp [usen] ),\n  refine partrec.cond _ _ _,\n  { refine (option_is_some.to_comp.comp (computable.univn_to_fn \u03b1 \u03c3 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 : \u03b2 \u2192 option \u03c4} {e : \u2115} {s : \u2115} {x : \u03b1}\n  (h : (\u27e6e\u27e7*p [s] x : option \u03c3).is_some = tt) :\n  usen \u03c3 p e s x = ((nat.rfind (\u03bb u, (\u27e6e\u27e7*p [u] x).is_some)).get (rfind_dom_total \u27e8s, h\u27e9)) :=\nby simp [usen, usen_pfun, h, map]\n\ntheorem usen_eq_ff {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {s : \u2115} {x : \u03b1}\n  (h : (\u27e6e\u27e7*p [s] x : option \u03c3).is_some = ff) :\n  usen \u03c3 p e s x = none :=\nby simp [usen, usen_pfun, h, map]\n\ntheorem usen_is_some_iff {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {s : \u2115} {x : \u03b1} :\n  (usen \u03c3 p e s x).is_some \u2194 (\u27e6e\u27e7*p [s] x : option \u03c3).is_some :=\nby { cases C : (\u27e6e\u27e7*p [s] x).is_some, { simp[usen_eq_ff C] }, { simp[usen_eq_tt C] } }\n\ntheorem usen_step_tt {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {s : \u2115}  {x : \u03b1}\n  {u : \u2115} (hu : usen \u03c3 p e s x = u) :\n  (\u27e6e\u27e7*p [u] x : option \u03c3).is_some = tt :=\nbegin\n  have : (\u27e6e\u27e7*p [s] x : option \u03c3).is_some, { simp[\u2190usen_is_some_iff, hu] },\n  simp [usen_eq_tt this] at hu,\n  have : u \u2208 nat.rfind (\u03bb u, (\u27e6e\u27e7*p [u] x).is_some), rw \u2190hu, from get_mem _,\n  simp at this, simp [this.1]\nend\n\ntheorem usen_consumption_step {p : \u2115 \u2192 option \u03c4} {e : \u2115} {s : \u2115} {x : \u03b1} {y : \u03c3}\n  {u : \u2115} (hu : usen \u03c3 p e s x = u) :\n  \u27e6e\u27e7*p [s] x = some y \u2192 \u2200 {q : \u2115 \u2192 option \u03c4}, (\u2200 n, n < u \u2192 q n = p n) \u2192\n  \u27e6e\u27e7*q [u] x = some y := \u03bb h q hq,\nbegin\n  suffices : (\u27e6e\u27e7*q [u] : \u03b1 \u2192 option \u03c3) = \u27e6e\u27e7*p [u],\n  { simp [this], have := usen_step_tt hu,\n    rcases option.is_some_iff_exists.mp this with \u27e8z, hz\u27e9,\n    simp [rpartrec.univn_mono_eq h hz, hz] },\n  apply rpartrec.univn_use, exact hq\nend\n\ntheorem usen_le {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {s : \u2115} {x : \u03b1}\n  (u : \u2115) (hu : usen \u03c3 p e s x = u) : u \u2264 s :=\nbegin\n  cases h : (\u27e6e\u27e7*p [s] x : option \u03c3).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 \u2191(\u03bb u, (\u27e6e\u27e7*p [u] x).is_some)).get (rfind_dom_total \u27e8_, h\u27e9),\n    suffices : u \u2264 s, from this,\n    have eqn : u \u2264 s \u2228 s < u, from le_or_lt u s, cases eqn, refine eqn,\n    exfalso,\n    have : u \u2208 nat.rfind (\u03bb u, (\u27e6e\u27e7*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 : \u03b2 \u2192 option \u03c4} {e : \u2115} {x : \u03b1}\n  {m n u : \u2115} (le : u \u2264 n) (hm : usen \u03c3 p e m x = u) : usen \u03c3 p e n x = u :=\nbegin\n  have mdom : (\u27e6e\u27e7*p [m] x : option \u03c3).is_some, from usen_is_some_iff.mp (by simp[hm]),\n  have udom : (\u27e6e\u27e7*p [u] x : option \u03c3).is_some, from usen_step_tt hm,\n  have ndom : (\u27e6e\u27e7*p [n] x : option \u03c3).is_some, from rpartrec.univn_dom_mono le udom, \n  have : usen \u03c3 p e m x = (nat.rfind (\u03bb u, (\u27e6e\u27e7*p [u] x).is_some)).get _, from usen_eq_tt mdom,\n  have : usen \u03c3 p e n x = usen \u03c3 p e m x, simp[this], from usen_eq_tt ndom,\n  simp[this, hm]\nend\n\ndef use (\u03c3) [primcodable \u03c3] (p : \u03b2 \u2192 option \u03c4) (e : \u2115) (x : \u03b1) : part \u2115 :=\nnat.rfind_opt (\u03bb s, usen \u03c3 p e s x)\n\n@[rcomputability]\ntheorem rcomputable.use_tot (\u03c3) [primcodable \u03c3]\n  {f : \u03b2 \u2192 \u03c4} {i : \u03b3 \u2192 \u2115} {s : \u03b3 \u2192 \u2115} {a : \u03b3 \u2192 \u03b1} {o : \u03bc \u2192 \u03c4}\n  (hf : f computable_in! o) (hi : i computable_in! o) (hs : s computable_in! o) (ha : a computable_in! o) :\n  (\u03bb x, use \u03c3 \u2191\u2092f (i x) (a x)) partrec_in! o :=\nrpartrec.rfind_opt\n  (rcomputable.usen_tot _ hf (rcomputable.to_unary\u2081 hi)\n    ((rpartrec.of_option' rcomputable.id').to_unary\u2082) (rcomputable.to_unary\u2081 ha))\n  \ndef use0 (\u03c3) [primcodable \u03c3] (e : \u2115) (x : \u03b1) : part \u2115 := use \u03c3 \u2191\u2092(\u03bb _, 0 : \u2115 \u2192 \u2115) e x\n\nnotation `\u03a6\u27e6` e `\u27e7^`f  := use _ \u2191\u2092f e\n\nnotation `\u03a6\u27e6` e `\u27e7\u2070 ` x := use0 _ e x\n\ntheorem use_dom_iff {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {x : \u03b1} :\n  (use \u03c3 p e x).dom \u2194 (\u27e6e\u27e7*p x : part \u03c3).dom :=\ncalc (use \u03c3 p e x).dom \u2194 \u2203 s, (usen \u03c3 p e s x).is_some         : by simp[use, nat.rfind_opt_dom, option.is_some_iff_exists]\n                   ... \u2194 \u2203 s, (\u27e6e\u27e7*p [s] x : option \u03c3).is_some : by simp[usen_is_some_iff]\n                   ... \u2194 (\u27e6e\u27e7*p x : part \u03c3).dom                : iff.symm rpartrec.univn_dom_complete\n\ntheorem use_eq_iff {p : \u03b2 \u2192 option \u03c4} {e : \u2115} {x : \u03b1} {u : \u2115} :\n  u \u2208 use \u03c3 p e x \u2194 usen \u03c3 p e u x = u :=\ncalc u \u2208 use \u03c3 p e x \u2194 \u2203 s, usen \u03c3 p e s x = u : nat.rfind_opt_mono (\u03bb u m n le h, usen_mono ((usen_le u h).trans le) h)\n                 ... \u2194 usen \u03c3 p e u x = u      : \u27e8\u03bb \u27e8s, eq_use\u27e9, usen_mono (by refl) eq_use, \u03bb h, \u27e8u, h\u27e9\u27e9\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 {\u03b1 : Sort u_1} {\u03b2 : Sort u_2} {p : PProd \u03b1 \u03b2} : { fst := pprod.fst p, snd := pprod.snd p } = p :=\n  pprod.cases_on p fun (a : \u03b1) (b : \u03b2) => 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": "example (a b : Nat) : False := by\n  fail -- Error\n\nexample (a b : Nat) : False := by\n  fail \"giving up\" -- Error\n\nexample (a b : Nat) : True := by\n  first\n   | fail \"giving up\"\n   | constructor\n\nexample (a b : Nat) : True \u2227 False := by\n  constructor\n  fail \"failing here\"\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/failTac.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.06097517958516649, "lm_q1q2_score": 0.013579180958514715}}
{"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 \u2964 D} {F : D \u2964 C}\n\n/-namespace comm_sq\n\nsection\nvariables {A B : C} {X Y : D} {i : A \u27f6 B} {p : X \u27f6 Y}\n  {u : G.obj A \u27f6 X} {v : G.obj B \u27f6 Y}\n  (sq : comm_sq u (G.map i) p v) (adj : G \u22a3 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\u27e8begin\n  simp only [adjunction.hom_equiv_unit, assoc, \u2190 F.map_comp, sq.w],\n  rw [F.map_comp, adjunction.unit_naturality_assoc],\nend\u27e9\n\ndef right_adjoint_lift_struct_equiv :\n  sq.lift_struct \u2243 (sq.right_adjoint adj).lift_struct :=\n{ to_fun := \u03bb l,\n  { l := adj.hom_equiv _ _ l.l,\n    fac_left' := by rw [\u2190 adj.hom_equiv_naturality_left, l.fac_left],\n    fac_right' := by rw [\u2190 adjunction.hom_equiv_naturality_right, l.fac_right], },\n  inv_fun := \u03bb l,\n  { l := (adj.hom_equiv _ _).symm l.l,\n    fac_left' := begin\n      rw [\u2190 adjunction.hom_equiv_naturality_left_symm, l.fac_left],\n      apply (adj.hom_equiv _ _).left_inv,\n    end,\n    fac_right' := begin\n      rw [\u2190 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) \u2194 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 \u27f6 B} {p : X \u27f6 Y}\n  {u : A \u27f6 F.obj X} {v : B \u27f6 F.obj Y}\n  (sq : comm_sq u i (F.map p) v) (adj : G \u22a3 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\u27e8begin\n  simp only [adjunction.hom_equiv_counit, assoc,\n    \u2190 G.map_comp_assoc, \u2190 sq.w],\n  rw [G.map_comp, assoc, adjunction.counit_naturality],\nend\u27e9\n\ndef left_adjoint_lift_struct_equiv :\n  sq.lift_struct \u2243 (sq.left_adjoint adj).lift_struct :=\n{ to_fun := \u03bb l,\n  { l := (adj.hom_equiv _ _).symm l.l,\n    fac_left' := by rw [\u2190 adj.hom_equiv_naturality_left_symm, l.fac_left],\n    fac_right' := by rw [\u2190 adj.hom_equiv_naturality_right_symm, l.fac_right], },\n  inv_fun := \u03bb l,\n  { l := (adj.hom_equiv _ _) l.l,\n    fac_left' := begin\n      rw [\u2190 adj.hom_equiv_naturality_left, l.fac_left],\n      apply (adj.hom_equiv _ _).right_inv,\n    end,\n    fac_right' := begin\n      rw [\u2190 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) \u2194 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 \u22a3 F) {A B : C} {X Y : D} (i : A \u27f6 B) (p : X \u27f6 Y) :\n  has_lifting_property (G.map i) p \u2194 has_lifting_property i (F.map p) :=\nbegin\n  split,\n  { introI,\n    constructor,\n    intros f g sq,\n    rw \u2190 sq.left_adjoint_has_lift_iff adj,\n    apply_instance, },\n  { introI,\n    constructor,\n    intros f g sq,\n    rw \u2190 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 \u27f6 B} {i' : A' \u27f6 B'}\n  (e : arrow.mk i \u2245 arrow.mk i') (p : X \u27f6 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 \u226b i \u226b (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' \u22a2,\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 \u27f6 B) {p : X \u27f6 Y} {p' : X' \u27f6 Y'}\n  (e : arrow.mk p \u2245 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 \u226b p \u226b (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' \u22a2,\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 \u27f6 B} {i' : A' \u27f6 B'}\n  (e : arrow.mk i \u2245 arrow.mk i') (p : X \u27f6 Y) :\n  has_lifting_property i p \u2194 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 \u27f6 B) {p : X \u27f6 Y} {p' : X' \u27f6 Y'}\n  (e : arrow.mk p \u2245 arrow.mk p') :\n  has_lifting_property i p \u2194 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 (\ud835\udc9e : Type u) [category.{v} \ud835\udc9e]\n\n@[protect_proj] structure struc : Type (max u v (w+1) (x+1)) :=\n( F : \ud835\udc9e \u2192 Type w )\n[ cat : category.{x} (sigma F) ]\n( fst_map : \u03a0 {A B : sigma F} (f : A \u27f6 B), A.1 \u27f6 B.1 )\n( fst_map_id : \u2200 (A : sigma F), fst_map (\ud835\udfd9 A) = \ud835\udfd9 A.1 )\n( fst_map_comp : \u2200 {A B C : sigma F} (f : A \u27f6 B) (g : B \u27f6 C),\n    fst_map (f \u226b g) = fst_map f \u226b fst_map g )\n\nnamespace struc\n\ninstance : has_coe_to_fun (struc \ud835\udc9e) (\u03bb _, \ud835\udc9e \u2192 Type w) :=\n{ coe := struc.F }\n\nvariables {\ud835\udc9e} {F : struc \ud835\udc9e}\n\ninstance : category (sigma F) := F.cat\n\ndef fst : sigma F \u2964 \ud835\udc9e :=\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 : \ud835\udc9e) : category_struct (F X) :=\n{ hom := \u03bb A B, { f : sigma.mk X A \u27f6 \u27e8X, B\u27e9 // fst.map f = \ud835\udfd9 X },\n  id := \u03bb A, \u27e8\ud835\udfd9 _, by simp; refl\u27e9,\n  comp := \u03bb A B C f g, \u27e8f.1 \u226b g.1, by erw [functor.map_comp, f.2, g.2, category.comp_id]\u27e9 }\n\ninstance (X : \ud835\udc9e) : category (F X) :=\n{ comp_id' := \u03bb _ _ _, subtype.ext (category.comp_id _),\n  id_comp' := \u03bb _ _ _, subtype.ext (category.id_comp _),\n  assoc' := \u03bb _ _ _ _ _ _ _, subtype.ext (category.assoc _ _ _) }\n\nopen opposite\n\ndef of_functor (F : \ud835\udc9e \u2964 Type w) : struc \ud835\udc9e :=\n{ F := F.obj,\n  cat := \n  { hom := \u03bb A B, {f : A.1 \u27f6 B.1 // F.map f A.2 = B.2 },\n    id := \u03bb A, \u27e8\ud835\udfd9 A.1, by simp\u27e9,\n    comp := \u03bb A B C f g, \u27e8f.1 \u226b g.1, by simp [f.prop, g.prop]\u27e9,\n    comp_id' := \u03bb _ _ _, subtype.ext (category.comp_id _),\n    id_comp' := \u03bb _ _ _, subtype.ext (category.id_comp _),\n    assoc' := \u03bb _ _ _ _ _ _ _, subtype.ext (category.assoc _ _ _) },\n  fst_map := \u03bb _ _, subtype.val,\n  fst_map_id := by intros; refl,\n  fst_map_comp := by intros; refl }\n\ndef Module\u2082 : struc Ring :=\n{ F := \u03bb R, Module R,\n  cat :=\n  { hom := \u03bb A B, \u03a3 f : A.1 \u27f6 B.1, A.2 \u2192\u209b\u2097[f] B.2,\n    id := \u03bb A, \u27e8\ud835\udfd9 A.1, linear_map.id\u27e9,\n    comp := \u03bb A B C f g, \u27e8f.1 \u226b g.1, \n      @linear_map.comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \u27e8rfl\u27e9 g.2 f.2\u27e9,\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 := \u03bb _ _ f, f.fst,\n  fst_map_id := by intros; refl,\n  fst_map_comp := by intros; refl }\n\n\ndef of_category (\ud835\udc9f : Type*) [category \ud835\udc9f] : struc \ud835\udc9e :=\n{ F := \u03bb _, \ud835\udc9f,\n  cat := \n  { hom := \u03bb A B, (A.1 \u27f6 B.1) \u00d7 (A.2 \u27f6 B.2),\n    id := \u03bb _, (\ud835\udfd9 _, \ud835\udfd9 _),\n    comp := \u03bb A B C f g, (f.1 \u226b g.1, f.2 \u226b g.2),\n    comp_id' := \u03bb A B f, prod.ext (category.comp_id _) (category.comp_id _),\n    id_comp' := \u03bb A B f, prod.ext (category.id_comp _) (category.id_comp _),\n    assoc' := \u03bb A B C D f g h, prod.ext (category.assoc _ _ _) (category.assoc _ _ _) },\n  fst_map := \u03bb _ _, prod.fst,\n  fst_map_id := \u03bb _, rfl,\n  fst_map_comp := by intros; refl }\n\nvariable (\ud835\udc9e)\n\ndef type : struc \ud835\udc9e := of_category (Type v)\n\ndef prop : struc \ud835\udc9e := of_category Prop\n\nlemma hcongr {\u03b1 \u03b1' : Sort*}\n  {\u03b2 : \u03b1 \u2192 Sort*} {\u03b2' : \u03b1' \u2192 Sort*} {f : \u03a0 a, \u03b2 a}\n  {g : \u03a0 a, \u03b2' a} (h\u03b2 : \u03b2 == \u03b2')\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\u03b2 ha,\n  simp at *,\n  subst h\nend\n\n\ndef sigma_pi (F : \ud835\udc9e \u2964 Type) (G : struc (sigma (of_functor F))) : struc \ud835\udc9e :=\n{ F := \u03bb X, \u03a0 a : F.obj X, G.F \u27e8X, a\u27e9,\n  cat := \n  { hom := \u03bb A B, \u03a3 (f : A.1 \u27f6 B.1), \n      \u03a0 (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) \u27f6 sigma.mk (sigma.mk B.1 b) (B.2 b),\n    id := \u03bb X, \u27e8\ud835\udfd9 X.1, \u03bb x y h, cast (by simp [F.map_id] at h; rw h) \n        (\ud835\udfd9 (sigma.mk (sigma.mk X.1 x) (X.2 x)))\u27e9,\n    comp := \u03bb X Y Z f g, \u27e8f.1 \u226b g.1, \n        \u03bb a b h, cast (by simp) (f.2 a _ rfl \u226b g.2 (F.map f.1 a) b (by simp [h]))\u27e9,\n    comp_id' := \u03bb X Y f, begin \n        cases f with f\u2081 f\u2082,\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' := \u03bb X Y f, begin \n        cases f with f\u2081 f\u2082,\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\u2082 a b a'),\n              { simp },\n              { rw [F.map_id],\n                refl },\n              { simp },\n              { simp } } } }\n      end,\n    assoc' := \u03bb 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 := \u03bb _ _ 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 : \ud835\udc9e \u2964 Type) (G : struc \ud835\udc9e) : struc \ud835\udc9e :=\n{ F := \u03bb X, F.obj X \u2192 G X,\n  cat := \n  { hom := \u03bb A B, \u03a3 (f : A.1 \u27f6 B.1), \n      \u03a0 (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) \u27f6 sigma.mk B.1 (B.2 b) // fst.map g = f } ,\n    id := \u03bb X, \u27e8\ud835\udfd9 X.1, \u03bb x y h, \u27e8cast (by simp [h]) (\ud835\udfd9 (sigma.mk X.1 (X.2 x))), \n      begin simp, end\u27e9\u27e9,\n    comp := \u03bb X Y Z f g, \u27e8f.1 \u226b g.1, \n        \u03bb x z h, cast (by simp [h]) (f.2 x (F.map f.1 x) rfl \u226b g.2 (F.map f.1 x) z (by simp [h]))\u27e9,\n    comp_id' := \u03bb X Y f,  \n      begin \n        cases f with f\u2081 f\u2082,\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' := \u03bb X Y f, begin \n        cases f with f\u2081 f\u2082,\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\u2082 a b a'),\n              { simp },\n              { simp },\n              { simp } } } }\n      end,\n    assoc' := \u03bb 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 := \u03bb _ _ f, f.fst,\n  fst_map_id := by intros; refl,\n  fst_map_comp := by intros; refl }\n\n-- def sigma_arrow (F : struc \ud835\udc9e) (G : struc \ud835\udc9e) : struc \ud835\udc9e :=\n-- { F := \u03bb X, \u03a3 (i : F X \u2192 G X), \n--     (\u03a0 (a b : F X), (sigma.mk X a \u27f6 \u27e8X, b\u27e9) \u2192 \n--       { f : sigma.mk X (i a) \u27f6 \u27e8X, i b\u27e9 // fst.map f = \ud835\udfd9 X}),\n--   cat := \n--   { hom := \u03bb A B, \u03a3 (f : A.1 \u27f6 B.1), \u03a0 (a : F A.1) (b : F B.1),\n--       (sigma.mk A.1 a \u27f6 sigma.mk B.1 b) \u2192\n--       { g : (sigma.mk A.1 (A.2.1 a)) \u27f6 (sigma.mk B.1 (B.2.1 b)) // fst.map g = f },\n--     id := \u03bb A, \u27e8\ud835\udfd9 _, \u03bb a b f, A.2.2 a b f\u27e9,\n--     comp := \u03bb A B C f g, \u27e8f.1 \u226b g.1, \u03bb a c h, \n--       begin\n--         have := sigma.snd f a,\n        \n--       end\u27e9,\n--     comp_id' := sorry,\n--     id_comp' := sorry,\n--     assoc' := sorry },\n\n--   fst_map := \u03bb _ _ f, f.fst,\n--   fst_map_id := by intros; refl,\n--   fst_map_comp := by intros; refl }\n\n\n-- def sigma_pi\u2082 (F : struc \ud835\udc9e) (G : struc (sigma F)) : struc \ud835\udc9e :=\n-- { F := \u03bb X, \u03a3 (i : \u03a0 a : F X, G.F \u27e8X, a\u27e9), \n--     (\u03a0 (a b : F X) (f : sigma.mk X a \u27f6 sigma.mk X b), \n--       { g : sigma.mk (sigma.mk X a) (i a) \u27f6 \u27e8\u27e8X, b\u27e9, i b\u27e9 // fst.map g = f }),\n--   cat := \n--   { hom := \u03bb A B, \u03a3 (f : A.1 \u27f6 B.1), (\u03a0 (a : F A.1) (b : F B.1), \n--       (sigma.mk A.1 a \u27f6 sigma.mk B.1 b) \u2192 \n--         (sigma.mk (sigma.mk A.1 a) (A.2.1 a) \u27f6 \u27e8\u27e8B.1, b\u27e9, B.2.1 b\u27e9)),\n--     id := \u03bb A, \u27e8\ud835\udfd9 _, \u03bb a b f, (A.2.2 a b f).1\u27e9,\n--     comp := \u03bb A B C f g, \u27e8f.1 \u226b g.1, \u03bb a c h, \n--       begin\n--         have := sigma.snd f a,\n        \n--       end\u27e9,\n--     comp_id' := sorry,\n--     id_comp' := sorry,\n--     assoc' := sorry },\n\n--   fst_map := \u03bb _ _ 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 tactic\n\nexample : false \u2192 0 = 1 :=\nbegin\n  sorry,\nend", "meta": {"author": "xhkittyyan", "repo": "Lean-Seminars-Series-Fall-2022", "sha": "6951cdf2cb4e001666d2a56170601325f69d52b5", "save_path": "github-repos/lean/xhkittyyan-Lean-Seminars-Series-Fall-2022", "path": "github-repos/lean/xhkittyyan-Lean-Seminars-Series-Fall-2022/Lean-Seminars-Series-Fall-2022-6951cdf2cb4e001666d2a56170601325f69d52b5/src/9_Tactics used for classical reasoning/9.2_exfalso/ex2_exfalso_false.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25386100696924885, "lm_q2_score": 0.05340332753999997, "lm_q1q2_score": 0.013557022504813011}}
{"text": "import super\n\nsection\nopen super tactic\nexample (i : Type) (a b : i) (p : i \u2192 Prop) (H : a = b) (Hpa : p a) : true := by do\nH \u2190 get_local `H >>= clause.of_classical_proof,\nHpa \u2190 get_local `Hpa >>= clause.of_classical_proof,\na \u2190 get_local `a,\ntry_sup (\u03bbx y, ff) H Hpa 0 0 [0] tt ff ``super.sup_ltr >>= clause.validate,\nto_expr ``(trivial) >>= apply\n\nexample (i : Type) (a b : i) (p : i \u2192 Prop) (H : a = b) (Hpa : p a \u2192 false) (Hpb : p b \u2192 false) : true := by do\nH \u2190 get_local `H >>= clause.of_classical_proof,\nHpa \u2190 get_local `Hpa >>= clause.of_classical_proof,\nHpb \u2190 get_local `Hpb >>= clause.of_classical_proof,\ntry_sup (\u03bbx y, ff) H Hpa 0 0 [0] tt ff ``super.sup_ltr >>= clause.validate,\ntry_sup (\u03bbx y, ff) H Hpb 0 0 [0] ff ff ``super.sup_rtl >>= clause.validate,\nto_expr ``(trivial) >>= apply\n\nexample (i : Type) (p q : i \u2192 Prop) (H : \u2200x y, p x \u2192 q y \u2192 false) : true := by do\nh \u2190 get_local `H >>= clause.of_classical_proof,\n(op, lcs) \u2190 h^.open_constn h^.num_binders,\nguard $ (get_components lcs)^.length = 2,\ntriv\n\nexample (i : Type) (p : i \u2192 i \u2192 Prop) (H : \u2200x y z, p x y \u2192 p y z \u2192 false) : true := by do\nh \u2190 get_local `H >>= clause.of_classical_proof,\n(op, lcs) \u2190 h^.open_constn h^.num_binders,\nguard $ (get_components lcs)^.length = 1,\ntriv\n\nexample (i : Type) (p : i \u2192 i \u2192 Type) (c : i) (h : \u2200 (x : i), p x c \u2192 p x c) : true := by do\nh \u2190 get_local `h, hcls \u2190 clause.of_classical_proof h,\ntaut \u2190 is_taut hcls,\nwhen (\u00actaut) failed,\nto_expr ``(trivial) >>= apply\n\nopen tactic\nexample (m n : \u2115) : true := by do\ne\u2081 \u2190 to_expr ```((0 + (m : \u2115)) + 0),\ne\u2082 \u2190 to_expr ```(0 + (0 + (m : \u2115))),\ne\u2083 \u2190 to_expr ```(0 + (m : \u2115)),\nprec \u2190 return (contained_funsyms e\u2081)^.keys,\nprec_gt \u2190 return $ prec_gt_of_name_list prec,\nguard $ lpo prec_gt e\u2081 e\u2083,\nguard $ lpo prec_gt e\u2082 e\u2083,\nto_expr ``(trivial) >>= apply\n\n/-\nopen tactic\nexample (i : Type) (f : i \u2192 i) (c d x : i) : true := by do\nef \u2190 get_local `f, ec \u2190 get_local `c, ed \u2190 get_local `d,\nsyms \u2190 return [ef,ec,ed],\nprec_gt \u2190 return $ prec_gt_of_name_list (list.map local_uniq_name [ef, ec, ed]),\nsequence' (do s1 \u2190 syms, s2 \u2190 syms, return (do\n  s1_fmt \u2190 pp s1, s2_fmt \u2190 pp s2,\n  trace (s1_fmt ++ to_fmt \" > \" ++ s2_fmt ++ to_fmt \": \" ++ to_fmt (prec_gt s1 s2))\n)),\n\nexprs \u2190 @mapM tactic _ _ _ to_expr [`(f c), `(f (f c)), `(f d), `(f x), `(f (f x))],\nsequence' (do e1 \u2190 exprs, e2 \u2190 exprs, return (do\n  e1_fmt \u2190 pp e1, e2_fmt \u2190 pp e2,\n  trace (e1_fmt ++ to_fmt\" > \" ++ e2_fmt ++ to_fmt\": \" ++ to_fmt (lpo prec_gt e1 e2))\n)),\n\nmk_const ``true.intro >>= apply\n-/\nopen monad\nexample (x y : \u2115) (h : nat.zero = nat.succ nat.zero) (h2 : nat.succ x = nat.succ y) : true := by do\nh \u2190 get_local `h >>= clause.of_classical_proof,\nh2 \u2190 get_local `h2 >>= clause.of_classical_proof,\ncs \u2190 try_no_confusion_eq_r h 0,\ncs.mmap' clause.validate,\ncs \u2190 try_no_confusion_eq_r h2 0,\ncs.mmap' clause.validate,\nto_expr ``(trivial) >>= exact\nend\n", "meta": {"author": "leanprover", "repo": "super", "sha": "47b107b4cec8f3b41d72daba9cbda2f9d54025de", "save_path": "github-repos/lean/leanprover-super", "path": "github-repos/lean/leanprover-super/super-47b107b4cec8f3b41d72daba9cbda2f9d54025de/test/super_tests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630095, "lm_q2_score": 0.030675800824508114, "lm_q1q2_score": 0.013548673602214595}}
{"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.backward\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.SetGetOptionTactics\n\nnamespace Tactic\n\nunsafe axiom back_lemmas : Type\n#align tactic.back_lemmas tactic.back_lemmas\n\n/-- Create a datastructure containing all lemmas tagged as [intro].\n   Lemmas are indexed using their head-symbol.\n   The head-symbol is computed with respect to the given transparency setting. -/\nunsafe axiom mk_back_lemmas_core : Transparency \u2192 tactic back_lemmas\n#align tactic.mk_back_lemmas_core tactic.mk_back_lemmas_core\n\n/-- (back_lemmas_insert_core m lemmas lemma) adds the given lemma to the set back_lemmas.\n   It infers the type of the lemma, and uses its head-symbol as an index.\n   The head-symbol is computed with respect to the given transparency setting. -/\nunsafe axiom back_lemmas_insert_core : Transparency \u2192 back_lemmas \u2192 expr \u2192 tactic back_lemmas\n#align tactic.back_lemmas_insert_core tactic.back_lemmas_insert_core\n\n/-- Return the lemmas that have the same head symbol of the given expression -/\nunsafe axiom back_lemmas_find : back_lemmas \u2192 expr \u2192 tactic (List expr)\n#align tactic.back_lemmas_find tactic.back_lemmas_find\n\nunsafe def mk_back_lemmas : tactic back_lemmas :=\n  mk_back_lemmas_core reducible\n#align tactic.mk_back_lemmas tactic.mk_back_lemmas\n\nunsafe def back_lemmas_insert : back_lemmas \u2192 expr \u2192 tactic back_lemmas :=\n  back_lemmas_insert_core reducible\n#align tactic.back_lemmas_insert tactic.back_lemmas_insert\n\n/--\n(backward_chaining_core t insts max_depth pre_tactic leaf_tactic lemmas): perform backward chaining using\n   the lemmas marked as [intro] and extra_lemmas.\n\n   The search maximum depth is \\c max_depth.\n\n   Before processing each goal, the tactic pre_tactic is invoked. The possible outcomes are:\n      1) it closes the goal\n      2) it does nothing, and backward_chaining_core tries applicable lemmas.\n      3) it fails, and backward_chaining_core backtracks.\n\n   Whenever no lemma is applicable, the leaf_tactic is invoked, to try to close the goal.\n   If insts is tt, then type class resolution is used to discharge goals.\n\n   Remark pre_tactic may also be used to trace the execution of backward_chaining_core -/\nunsafe axiom backward_chaining_core :\n    Transparency \u2192 Bool \u2192 Nat \u2192 tactic Unit \u2192 tactic Unit \u2192 back_lemmas \u2192 tactic Unit\n#align tactic.backward_chaining_core tactic.backward_chaining_core\n\nunsafe def back_lemmas_add_extra : Transparency \u2192 back_lemmas \u2192 List expr \u2192 tactic back_lemmas\n  | m, bls, [] => return bls\n  | m, bls, l :: ls => do\n    let new_bls \u2190 back_lemmas_insert_core m bls l\n    back_lemmas_add_extra m new_bls ls\n#align tactic.back_lemmas_add_extra tactic.back_lemmas_add_extra\n\nunsafe def back_chaining_core (pre_tactic : tactic Unit) (leaf_tactic : tactic Unit)\n    (extra_lemmas : List expr) : tactic Unit := do\n  let intro_lemmas \u2190 mk_back_lemmas_core reducible\n  let new_lemmas \u2190 back_lemmas_add_extra reducible intro_lemmas extra_lemmas\n  let max \u2190 get_nat_option `back_chaining.max_depth 8\n  backward_chaining_core reducible tt max pre_tactic leaf_tactic new_lemmas\n#align tactic.back_chaining_core tactic.back_chaining_core\n\nunsafe def back_chaining : tactic Unit :=\n  back_chaining_core skip assumption []\n#align tactic.back_chaining tactic.back_chaining\n\nunsafe def back_chaining_using : List expr \u2192 tactic Unit :=\n  back_chaining_core skip assumption\n#align tactic.back_chaining_using tactic.back_chaining_using\n\nunsafe def back_chaining_using_hs : tactic Unit :=\n  local_context >>= back_chaining_core skip failed\n#align tactic.back_chaining_using_hs tactic.back_chaining_using_hs\n\nend Tactic\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/Backward.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37387582277169656, "lm_q2_score": 0.03622005612506083, "lm_q1q2_score": 0.013541803284594145}}
{"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) \u2194 is_zero A \u2227 is_zero B :=\nbegin\n  split,\n  { intro h,\n    simp only [is_zero.iff_id_eq_zero],\n    split,\n    { rw \u2190 cancel_mono (biprod.inl : _ \u27f6 A \u229e B),\n      apply h.eq_of_tgt, },\n    { rw \u2190 cancel_mono (biprod.inr : _ \u27f6 A \u229e B),\n      apply h.eq_of_tgt, }, },\n  { rintro \u27e8h\u2081, h\u2082\u27e9,\n    rw is_zero.iff_id_eq_zero,\n    ext1,\n    { apply h\u2081.eq_of_src, },\n    { apply h\u2082.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 \u2124} [\u2200 p, has_binary_biproduct (F.X (p+1)) (G.X p)]\n  (\u03c6 : F \u27f6 G)\n\nopen hom_complex\n\ninclude \u03c6\n\ndef mapping_cone : cochain_complex C \u2124 :=\n{ X := \u03bb i, F.X (i+1) \u229e G.X i,\n  d := \u03bb i j, begin\n    by_cases i+1 = j,\n    { exact -biprod.fst \u226b F.d _ _ \u226b biprod.inl +\n        biprod.fst \u226b (cochain.of_hom \u03c6).v (i+1) j (by simpa only [add_zero, \u2190 h]) \u226b biprod.inr +\n        biprod.snd \u226b G.d _ _ \u226b biprod.inr,\n      },\n    { exact 0, },\n  end,\n  shape' := \u03bb i j (hij : i+1 \u2260 j), by rw dif_neg hij,\n  d_comp_d' := \u03bb 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, \u03c6.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 \u03c6\n\nnamespace mapping_cone\n\ninclude \u03c6\n\nlemma X_is_zero_iff (n : \u2124) :\n  is_zero ((mapping_cone \u03c6).X n) \u2194 is_zero (F.X (n+1)) \u2227 is_zero (G.X n) :=\nbiprod.is_zero_iff _ _\n\ndef inl : cochain F (mapping_cone \u03c6) (-1) :=\ncochain.mk (\u03bb p q hpq, (cochain.of_hom (\ud835\udfd9 F)).v p (q+1) (by linarith) \u226b biprod.inl)\n\ndef inr : G \u27f6 mapping_cone \u03c6 :=\ncocycle.hom_of\n  (cocycle.mk (cochain.mk (\u03bb p q hpq,\n    (cochain.of_hom (\ud835\udfd9 G)).v p q hpq \u226b biprod.inr)) 1 (zero_add 1)\n    begin\n      ext1 p _ rfl,\n      dsimp [mapping_cone],\n      simp only [cochain.zero_v,\n        \u03b4_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        \u03b5_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 \u03c6) F 1 :=\ncocycle.mk (cochain.mk (\u03bb p q hpq, biprod.fst \u226b\n  (cochain.of_hom (\ud835\udfd9 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 [\u03b4_v 1 2 (by linarith) _ p (p+1+1) (by linarith) (p+1) (p+1) (by linarith) rfl,\n      dif_pos rfl, \u03b5_succ, \u03b5_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 \u03c6) G 0 :=\ncochain.mk (\u03bb p q hpq, biprod.snd \u226b (cochain.of_hom (\ud835\udfd9 G)).v p q hpq)\n\n@[simp, reassoc]\nlemma inl_fst (p q : \u2124) (hpq : p = q+1) :\n  (inl \u03c6).v p q (by rw [hpq, int.add_neg_one, add_tsub_cancel_right]) \u226b\n     (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v q p hpq = \ud835\udfd9 _ :=\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 : \u2124) (hpq : q = p+(-1)) :\n  (inl \u03c6).v p q hpq \u226b (snd \u03c6).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 : \u2124) (hpq : q = p+1) :\n  (inr \u03c6).f p \u226b (fst \u03c6 : cochain (mapping_cone \u03c6) 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 : \u2124) :\n  (inr \u03c6).f p \u226b (snd \u03c6).v p p (add_zero p).symm = \ud835\udfd9 _ :=\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 : \u2124) (hpq : q = p+1) :\n  (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v p q hpq \u226b\n    (inl \u03c6).v q p (by rw [hpq, int.add_neg_one, add_tsub_cancel_right]) +\n  (snd \u03c6).v p p (add_zero p).symm \u226b (inr \u03c6).f p = \ud835\udfd9 _ :=\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\u2081 n\u2082 n\u2083 : \u2124) (h\u2081\u2082 : n\u2081 = n\u2082 + (-1)) (h\u2082\u2083 : n\u2082 = n\u2083 + (-1)) :\n  (inl \u03c6).v n\u2082 n\u2081 h\u2081\u2082 \u226b (mapping_cone \u03c6).d n\u2081 n\u2082 =\n    \u03c6.f n\u2082 \u226b (inr \u03c6).f n\u2082 - F.d n\u2082 n\u2083 \u226b (inl \u03c6).v _ _ h\u2082\u2083 :=\nbegin\n  have hn\u2082 : n\u2082 = n\u2081 + 1 := by linarith,\n  have hn\u2083 : n\u2083 = n\u2081 + 1 + 1 := by linarith,\n  substs hn\u2082 hn\u2083,\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' : \u2124) :\n  (inr \u03c6).f n \u226b (mapping_cone \u03c6).d n n' =\n    G.d n n' \u226b (inr \u03c6).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 \u00ac (complex_shape.up \u2124).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 : \u2124) (hi : i = n+1) [has_binary_biproduct (F.X i) (G.X n)] :\n  (mapping_cone \u03c6).X n \u2245 F.X i \u229e G.X n :=\n{ hom := (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n i hi \u226b biprod.inl +\n    (snd \u03c6).v n n (add_zero n).symm   \u226b biprod.inr,\n  inv := biprod.fst \u226b (inl \u03c6).v i n (by linarith) + biprod.snd \u226b (inr \u03c6).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 \u03c6).comp (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) (neg_add_self 1).symm =\n    cochain.of_hom (\ud835\udfd9 _) :=\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 \u03c6).comp (snd \u03c6) (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 \u03c6)).comp (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) (zero_add 1).symm = 0 :=\nby tidy\n\n@[simp]\nlemma inr_comp_snd :\n  (cochain.of_hom (inr \u03c6)).comp\n    (snd \u03c6 : cochain (mapping_cone \u03c6) G 0) (zero_add 0).symm = cochain.of_hom (\ud835\udfd9 _) :=\nby tidy\n\n@[simps]\ndef \u03b4_as_cocycle : cocycle (mapping_cone \u03c6) F 1 :=\n-fst \u03c6\n\ndef \u03b4 : mapping_cone \u03c6 \u27f6 F\u27e6(1 : \u2124)\u27e7 :=\ncocycle.hom_of (cocycle.right_shift (\u03b4_as_cocycle \u03c6) 1 0 (zero_add 1).symm)\n\n@[simp, priority 1100]\nlemma inr_\u03b4 : inr \u03c6 \u226b \u03b4 \u03c6 = 0 :=\nbegin\n  ext n,\n  dsimp only [\u03b4],\n  simp only [homological_complex.comp_f, cocycle.hom_of_f, cochain.neg_v,\n    cocycle.right_shift_coe, \u03b4_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_\u03b4 :\n  (inl \u03c6).comp (cochain.of_hom (\u03b4 \u03c6)) (add_zero _).symm =\n  -(cochain.of_hom (\ud835\udfd9 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, \u03b4,\n    cocycle.hom_of_f, cocycle.right_shift_coe, \u03b4_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 {\u03c6}\n\nlemma to_ext_iff {A : C} {n : \u2124} (f g : A \u27f6 (mapping_cone \u03c6).X n) (n' : \u2124) (hn' : n' = n+1) :\n  f = g \u2194 f \u226b (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n n' hn' =\n    g \u226b (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n n' hn' \u2227\n    f \u226b (snd \u03c6).v n n (add_zero n).symm = g \u226b (snd \u03c6).v n n (add_zero n).symm :=\nbegin\n  split,\n  { rintro rfl,\n    tauto, },\n  { intro hfg,\n    rw [\u2190 cancel_mono (\ud835\udfd9 ((mapping_cone \u03c6).X n))],\n    simp only [\u2190 id _ _ _ hn', preadditive.comp_add, reassoc_of hfg.1, reassoc_of hfg.2], },\nend\n\nlemma from_ext_iff {A : C} {n : \u2124} (f g : (mapping_cone \u03c6).X n \u27f6 A)\n  (n' : \u2124) (h : n' = n+1) :\n  f = g \u2194 (inl \u03c6).v n' n (by rw [h, int.add_neg_one, add_tsub_cancel_right]) \u226b f =\n    (inl \u03c6).v n' n (by rw [h, int.add_neg_one, add_tsub_cancel_right]) \u226b g \u2227\n    (inr \u03c6).f n \u226b f = (inr \u03c6).f n \u226b 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 [\u2190 cancel_epi (\ud835\udfd9 ((mapping_cone \u03c6).X n))],\n    simp only [\u2190 id _ _ _ h, preadditive.add_comp, assoc, hfg.1, hfg.2], },\nend\n\nvariable (\u03c6)\n\n@[reassoc]\nlemma d_fst (n\u2081 n\u2082 n\u2083 : \u2124) (h\u2081\u2082 : n\u2082 = n\u2081 + 1) (h\u2082\u2083 : n\u2083 = n\u2082 + 1) :\n  (mapping_cone \u03c6).d n\u2081 n\u2082 \u226b (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n\u2082 n\u2083 h\u2082\u2083 =\n  -(fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n\u2081 n\u2082 h\u2081\u2082 \u226b F.d n\u2082 n\u2083 :=\nby simp only [from_ext_iff _ _ _ h\u2081\u2082, inl_d_assoc _ n\u2081 n\u2082 n\u2083 (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\u2081 n\u2082 : \u2124) (h\u2081\u2082 : n\u2082 = n\u2081 + 1) :\n  (mapping_cone \u03c6).d n\u2081 n\u2082 \u226b (snd \u03c6).v n\u2082 n\u2082 (add_zero n\u2082).symm =\n    (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n\u2081 n\u2082 h\u2081\u2082 \u226b \u03c6.f n\u2082 +\n    (snd \u03c6).v n\u2081 n\u2081 (add_zero n\u2081).symm \u226b G.d n\u2081 n\u2082 :=\nby simp only [from_ext_iff _ _ _ h\u2081\u2082, assoc,\n  inl_d_assoc _ n\u2081 n\u2082 (n\u2082+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 \u03b4_inl :\n  hom_complex.\u03b4 (-1) 0 (inl \u03c6) = cochain.of_hom (\u03c6 \u226b inr \u03c6) :=\nbegin\n  ext p,\n  simp only [\u03b4_v (-1) 0 (neg_add_self 1) _ p p (add_zero p).symm _ _ rfl rfl,\n    inl_d \u03c6 (p-1) p (p+1) (by linarith)( by linarith),\n    add_left_neg, \u03b5_0, one_zsmul, sub_add_cancel, cochain.of_hom_comp,\n    cochain.comp_zero_cochain, cochain.of_hom_v],\nend\n\n@[simp]\nlemma \u03b4_snd :\n  hom_complex.\u03b4 0 1 (snd \u03c6) = -(fst \u03c6 : cochain (mapping_cone \u03c6) F 1).comp\n    (cochain.of_hom \u03c6) (add_zero 1).symm :=\nbegin\n  ext p q hpq,\n  simp only [\u03b4_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, \u03b5_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 \u03c6\nlemma _root_.int.two_eq_one_add_one : (2 : \u2124) = 1+1 := by linarith\nlemma _root_.int.one_eq_two_add_neg_one : (1 : \u2124) = 2+(-1) := by linarith\n\nlemma of_d_eq : cochain.of_d (mapping_cone \u03c6) =\n  -((fst \u03c6 : cochain (mapping_cone \u03c6) F 1).comp (cochain.of_d F)\n    int.two_eq_one_add_one).comp (inl \u03c6) int.one_eq_two_add_neg_one +\n  ((fst \u03c6 : cochain (mapping_cone \u03c6) F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm).comp\n      (cochain.of_hom (inr \u03c6)) (add_zero 1).symm +\n  ((snd \u03c6).comp (cochain.of_d G) (zero_add 1).symm).comp\n    (cochain.of_hom (inr \u03c6)) (add_zero 1).symm :=\nbegin\n  ext p q hpq,\n  simp only [from_ext_iff _ _ _ hpq,\n    cochain.of_d_v, inl_d \u03c6 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 {\u03c6}\n\nlemma to_decomposition {A : C} {n : \u2124} (f : A \u27f6 (mapping_cone \u03c6).X n)\n  (n' : \u2124) (h : n' = n+1) :\n  \u2203 (x : A \u27f6 F.X n') (y : A \u27f6 G.X n), f = x \u226b\n    (inl \u03c6 : cochain F (mapping_cone \u03c6) (-1)).v n' n (by rw [h, int.add_neg_one, add_tsub_cancel_right])\n      + y \u226b (inr \u03c6).f n :=\nbegin\n  refine \u27e8f \u226b (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v _ _ (by linarith), f \u226b (snd \u03c6).v n n (by linarith), _\u27e9,\n  have h := f \u226b= id \u03c6 n n' h,\n  rw comp_id at h,\n  nth_rewrite 0 \u2190 h,\n  simp only [preadditive.comp_add, assoc],\nend\n\nlemma cochain_ext {K : cochain_complex C \u2124} {m m' : \u2124}\n  (y\u2081 y\u2082 : cochain (mapping_cone \u03c6) K m) (hm' : m = m'+1) :\n  y\u2081 = y\u2082 \u2194 (inl \u03c6).comp y\u2081 (show m' = -1+m, by rw [hm', neg_add_cancel_comm_assoc]) =\n    (inl \u03c6).comp y\u2082 (show m' = -1+m, by rw [hm', neg_add_cancel_comm_assoc]) \u2227\n    (cochain.of_hom (inr \u03c6)).comp y\u2081 (zero_add m).symm =\n      (cochain.of_hom (inr \u03c6)).comp y\u2082 (zero_add m).symm :=\nbegin\n  split,\n  { rintro rfl,\n    tauto, },\n  { rintro \u27e8h\u2081, h\u2082\u27e9,\n    ext p q hpq,\n    replace h\u2081 := cochain.congr_v h\u2081 (p+1) q (by linarith),\n    replace h\u2082 := cochain.congr_v h\u2082 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\u2081,\n    simp only [cochain.zero_cochain_comp, cochain.of_hom_v] at h\u2082,\n    rw [from_ext_iff _ _ (p+1) rfl, h\u2081, h\u2082],\n    tauto, },\nend\n\nlemma cochain_ext' {K : cochain_complex C \u2124} {m m' : \u2124}\n  (y\u2081 y\u2082 : cochain K (mapping_cone \u03c6) m) (hm' : m' = m+1) :\n  y\u2081 = y\u2082 \u2194 y\u2081.comp (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) hm' =\n    y\u2082.comp (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) hm' \u2227\n    y\u2081.comp (snd \u03c6) (add_zero m).symm =\n      y\u2082.comp (snd \u03c6) (add_zero m).symm :=\nbegin\n  split,\n  { rintro rfl,\n    tauto, },\n  { rintro \u27e8h\u2081, h\u2082\u27e9,\n    ext p q hpq,\n    replace h\u2081 := cochain.congr_v h\u2081 p (q+1) (by linarith),\n    simp only [cochain.comp_v _ _ hm' p q (q+1) (by linarith) (by linarith)] at h\u2081,\n    replace h\u2082 := cochain.congr_v h\u2082 p q (by linarith),\n    simp only [cochain.comp_zero_cochain] at h\u2082,\n    rw [to_ext_iff _ _ (q+1) rfl, h\u2082, h\u2081],\n    tauto, },\nend\n\nvariable (\u03c6)\n\n@[simp]\ndef \u03b9' := (homotopy_category.quotient _ _).map (inr \u03c6)\n\ndef \u03b4' : (homotopy_category.quotient _ _).obj (mapping_cone \u03c6) \u27f6\n  ((homotopy_category.quotient _ _).obj F)\u27e6(1 : \u2124)\u27e7 :=\n(homotopy_category.quotient _ _).map (\u03b4 \u03c6)\n\ndef desc_cochain {K : cochain_complex C \u2124} {n m : \u2124} (\u03b1 : cochain F K m) (\u03b2 : cochain G K n)\n  (h : m+1=n) :\n  cochain (mapping_cone \u03c6) K n :=\n(fst \u03c6 : cochain (mapping_cone \u03c6) F 1).comp \u03b1 (show n = 1+m, by rw [\u2190 h, add_comm])\n  + (snd \u03c6).comp \u03b2 (zero_add n).symm\n\n@[simp, reassoc]\nlemma inl_desc_cochain_v {K : cochain_complex C \u2124} {n m : \u2124}\n  (\u03b1 : cochain F K m) (\u03b2 : cochain G K n) (h : m+1=n) (p\u2081 p\u2082 p\u2083 : \u2124)\n    (h\u2081\u2082 : p\u2082 = p\u2081 + (-1)) (h\u2082\u2083 : p\u2083 = p\u2082 + n) :\n  (inl \u03c6).v p\u2081 p\u2082 h\u2081\u2082 \u226b (desc_cochain \u03c6 \u03b1 \u03b2 h).v p\u2082 p\u2083 h\u2082\u2083 =\n      \u03b1.v p\u2081 p\u2083 (by rw [h\u2082\u2083, h\u2081\u2082, \u2190 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\u2082 p\u2081 p\u2083 (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 \u2124} {n m : \u2124}\n  (\u03b1 : cochain F K m) (\u03b2 : cochain G K n) (h : m+1=n) (p\u2081 p\u2082 : \u2124)\n    (h\u2081\u2082 : p\u2082 = p\u2081 + n) :\n  (inr \u03c6).f p\u2081 \u226b (desc_cochain \u03c6 \u03b1 \u03b2 h).v p\u2081 p\u2082 h\u2081\u2082 =\n      \u03b2.v p\u2081 p\u2082 h\u2081\u2082 :=\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\u2081 (p\u2081 + 1) p\u2082 rfl (by linarith),\n    inr_fst_assoc, zero_comp],\nend\n\n@[simp]\nlemma inl_desc_cochain {K : cochain_complex C \u2124} {n m : \u2124}\n  (\u03b1 : cochain F K m) (\u03b2 : cochain G K n) (h : m+1=n) :\n  (inl \u03c6).comp (desc_cochain \u03c6 \u03b1 \u03b2 h)\n    (show m = -1+n, by rw [\u2190 h, neg_add_cancel_comm_assoc]) = \u03b1 :=\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 \u2124} {n m : \u2124}\n  (\u03b1 : cochain F K m) (\u03b2 : cochain G K n) (h : m+1=n) :\n  (cochain.of_hom (inr \u03c6)).comp\n    (desc_cochain \u03c6 \u03b1 \u03b2 h) (zero_add n).symm = \u03b2  :=\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 \u03b4_desc_cochain {K : cochain_complex C \u2124} {n m n' : \u2124} (\u03b1 : cochain F K m) (\u03b2 : cochain G K n)\n  (h : m+1=n) (hn' : n+1 = n') : hom_complex.\u03b4 n n' (desc_cochain \u03c6 \u03b1 \u03b2 h) =\n  (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).comp (hom_complex.\u03b4 m n \u03b1 +\n    \u03b5 (n+1) \u2022 (cochain.of_hom \u03c6).comp \u03b2 (zero_add n).symm) (by rw [\u2190 hn', add_comm]) +\n    (snd \u03c6).comp (hom_complex.\u03b4 n n' \u03b2) (zero_add n').symm :=\nbegin\n  ext p q hpq,\n  simp only [from_ext_iff _ _ (p+1) rfl,\n    \u03b4_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, \u03b5_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 \u03c6 p (p+1) (p+2) (by linarith) (by linarith),\n    \u03b4_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, \u03b5_sub, \u03b5_1, mul_neg, mul_one, neg_neg],\n  exact \u27e8by abel, rfl\u27e9,\nend\n\ndef desc_cocycle {K : cochain_complex C \u2124} {n m : \u2124} (\u03b1 : cochain F K m) (\u03b2 : cocycle G K n)\n  (h : m+1=n) (eq : hom_complex.\u03b4 m n \u03b1 =\n    \u03b5 n \u2022 (cochain.of_hom \u03c6).comp (\u03b2 : cochain G K n) (zero_add n).symm) :\n  cocycle (mapping_cone \u03c6) K n :=\ncocycle.mk (desc_cochain \u03c6 \u03b1 (\u03b2 : cochain G K n) h) (n+1) rfl\n  (by simp only [\u03b4_desc_cochain \u03c6 \u03b1 (\u03b2 : cochain G K n) h rfl, \u03b5_add, \u03b5_1, mul_neg, mul_one, eq,\n    neg_smul, \u2190 sub_eq_add_neg, sub_self, cochain.comp_zero, zero_add,\n    cocycle.\u03b4_eq_zero, cochain.comp_zero])\n\n@[simp]\nlemma desc_cocycle_coe {K : cochain_complex C \u2124} {n m : \u2124} (\u03b1 : cochain F K m) (\u03b2 : cocycle G K n)\n  (h : m+1=n) (eq : hom_complex.\u03b4 m n \u03b1 = \u03b5 n \u2022 (cochain.of_hom \u03c6).comp \u03b2.1 (zero_add n).symm) :\n(desc_cocycle \u03c6 \u03b1 \u03b2 h eq : cochain (mapping_cone \u03c6) K n) =\n  desc_cochain \u03c6 \u03b1 \u03b2 h := rfl\n\ndef desc {K : cochain_complex C \u2124} (\u03b1 : cochain F K (-1)) (\u03b2 : G \u27f6 K)\n  (eq : hom_complex.\u03b4 (-1) 0 \u03b1 = cochain.of_hom (\u03c6 \u226b \u03b2)) :\n  mapping_cone \u03c6 \u27f6 K :=\ncocycle.hom_of (desc_cocycle \u03c6 \u03b1 (cocycle.of_hom \u03b2) (neg_add_self 1)\n  (by simp only [eq, \u03b5_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 \u2124} (\u03b1 : cochain F K (-1)) (\u03b2 : G \u27f6 K)\n  (eq : hom_complex.\u03b4 (-1) 0 \u03b1 = cochain.of_hom (\u03c6 \u226b \u03b2)) (p q : \u2124) (hpq : q = p + (-1)) :\n  (inl \u03c6).v p q hpq \u226b (desc \u03c6 \u03b1 \u03b2 eq).f q = \u03b1.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 \u2124} (\u03b1 : cochain F K (-1)) (\u03b2 : G \u27f6 K)\n  (eq : hom_complex.\u03b4 (-1) 0 \u03b1 = cochain.of_hom (\u03c6 \u226b \u03b2)) :\n  (inl \u03c6).comp (cochain.of_hom (desc \u03c6 \u03b1 \u03b2 eq)) (add_zero _).symm = \u03b1 :=\nby tidy\n\n@[simp, reassoc]\nlemma inr_desc_f {K : cochain_complex C \u2124} (\u03b1 : cochain F K (-1)) (\u03b2 : G \u27f6 K)\n  (eq : hom_complex.\u03b4 (-1) 0 \u03b1 = cochain.of_hom (\u03c6 \u226b \u03b2)) (n : \u2124):\n  (inr \u03c6).f n \u226b (desc \u03c6 \u03b1 \u03b2 eq).f n = \u03b2.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 \u2124} (\u03b1 : cochain F K (-1)) (\u03b2 : G \u27f6 K)\n  (eq : hom_complex.\u03b4 (-1) 0 \u03b1 = cochain.of_hom (\u03c6 \u226b \u03b2)) :\n  inr \u03c6 \u226b desc \u03c6 \u03b1 \u03b2 eq = \u03b2 :=\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 \u2124} (\u03b1 : cochain F K (-1)) (\u03b2 : G \u27f6 K)\n  (eq : hom_complex.\u03b4 (-1) 0 \u03b1 = cochain.of_hom (\u03c6 \u226b \u03b2)) (n n' : \u2124) (hn' : n' = n+1) :\n  (desc \u03c6 \u03b1 \u03b2 eq).f n =\n    (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n n' hn' \u226b\n      \u03b1.v n' n (by { rw [hn', int.add_neg_one, add_tsub_cancel_right]}) +\n      (snd \u03c6).v n n (add_zero n).symm \u226b \u03b2.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 \u2124} (f\u2081 f\u2082 : mapping_cone \u03c6 \u27f6 K)\n  (\u03b3\u2081 : cochain F K (-2)) (\u03b3\u2082 : cochain G K (-1))\n  (h\u2081 : (inl \u03c6).comp (cochain.of_hom f\u2081) (add_zero (-1)).symm =\n    hom_complex.\u03b4 (-2) (-1) \u03b3\u2081 + (cochain.of_hom \u03c6).comp \u03b3\u2082 (zero_add _).symm +\n    (inl \u03c6).comp (cochain.of_hom f\u2082) (add_zero (-1)).symm)\n  (h\u2082 : cochain.of_hom (inr \u03c6 \u226b f\u2081) =\n    hom_complex.\u03b4 (-1) 0 \u03b3\u2082 + cochain.of_hom (inr \u03c6 \u226b f\u2082)) :\n  homotopy f\u2081 f\u2082 :=\n(equiv_homotopy _ _).symm\nbegin\n  refine \u27e8desc_cochain _ \u03b3\u2081 \u03b3\u2082 (by linarith), _\u27e9,\n  rw [\u03b4_desc_cochain \u03c6 \u03b3\u2081 \u03b3\u2082 (by linarith) (neg_add_self 1),\n    cochain_ext _ _ (show (0 : \u2124) = -1 +1 , by linarith)],\n  split,\n  { rw [cochain.comp_add, h\u2081],\n    nth_rewrite 0 cochain.comp_add,\n    simp only [\u2190 cochain.comp_assoc _ _ _ (neg_add_self 1).symm (add_neg_self 1).symm\n        (show (-1 : \u2124) = (-1) +1 + (-1), by linarith), inl_comp_fst, cochain.id_comp,\n        neg_add_self, \u03b5_0, one_smul, \u2190 cochain.comp_assoc_of_second_is_zero_cochain,\n        inl_comp_snd, cochain.zero_comp, add_zero], },\n  { rw [cochain.comp_add, \u2190 cochain.of_hom_comp, \u2190 cochain.of_hom_comp, h\u2082],\n    nth_rewrite 0 cochain.comp_add,\n    simp only [\u2190 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 \u2124}\n  {n m : \u2124} (\u03b1 : cochain K F m) (\u03b2 : cochain K G n) (h : n+1=m) :\n  cochain K (mapping_cone \u03c6) n :=\n\u03b1.comp (inl \u03c6) (by linarith) + \u03b2.comp (cochain.of_hom (inr \u03c6)) (by linarith)\n\n@[simp, reassoc]\nlemma lift_cochain_fst_v {K : cochain_complex C \u2124}\n  {n m : \u2124} (\u03b1 : cochain K F m) (\u03b2 : cochain K G n) (h : n+1=m) (p\u2081 p\u2082 p\u2083 : \u2124)\n  (h\u2081\u2082 : p\u2082 = p\u2081 + n) (h\u2082\u2083 : p\u2083 = p\u2082 + 1) :\n  (lift_cochain \u03c6 \u03b1 \u03b2 h).v p\u2081 p\u2082 h\u2081\u2082 \u226b (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v p\u2082 p\u2083 h\u2082\u2083 =\n    \u03b1.v p\u2081 p\u2083 (by rw [h\u2082\u2083, h\u2081\u2082, \u2190 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\u2081 p\u2083 p\u2082 (by linarith) (by linarith),\n    inl_fst, comp_id],\nend\n\n@[simp, reassoc]\nlemma lift_cochain_snd_v {K : cochain_complex C \u2124}\n  {n m : \u2124} (\u03b1 : cochain K F m) (\u03b2 : cochain K G n) (h : n+1=m)\n    (p\u2081 p\u2082 : \u2124) (h\u2081\u2082 : p\u2082 = p\u2081 + n) :\n  (lift_cochain \u03c6 \u03b1 \u03b2 h).v p\u2081 p\u2082 h\u2081\u2082 \u226b (snd \u03c6).v p\u2082 p\u2082 (add_zero p\u2082).symm =\n    \u03b2.v p\u2081 p\u2082 h\u2081\u2082 :=\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\u2081 (p\u2081+m) p\u2082 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 \u2124}\n  {n m : \u2124} (\u03b1 : cochain K F m) (\u03b2 : cochain K G n) (h : n+1=m)  :\n  (lift_cochain \u03c6 \u03b1 \u03b2 h).comp (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) h.symm = \u03b1 :=\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 \u2124}\n  {n m : \u2124} (\u03b1 : cochain K F m) (\u03b2 : cochain K G n) (h : n+1=m)  :\n  (lift_cochain \u03c6 \u03b1 \u03b2 h).comp (snd \u03c6) (add_zero n).symm = \u03b2 :=\nbegin\n  ext p q hpq,\n  simp only [cochain.comp_zero_cochain, lift_cochain_snd_v],\nend\n\nlemma \u03b4_lift_cochain {K : cochain_complex C \u2124}\n  {n m : \u2124} (\u03b1 : cochain K F m) (\u03b2 : cochain K G n) (h : n+1=m) (m' : \u2124) (hm' : m = m'+(-1)) :\n  hom_complex.\u03b4 n m (lift_cochain \u03c6 \u03b1 \u03b2 h) =\n    -(hom_complex.\u03b4 m m' \u03b1).comp (inl \u03c6) hm' +\n    (hom_complex.\u03b4 n m \u03b2 + \u03b1.comp (cochain.of_hom \u03c6) (add_zero m).symm).comp\n      (cochain.of_hom (inr \u03c6)) (add_zero m).symm :=\nbegin\n  ext p q hpq,\n  simp only [to_ext_iff _ _ (q+1) rfl, \u03b4_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    \u03b4_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 \u03c6 (q-1) q (q+1) (by linarith) rfl, lift_cochain_fst_v_assoc, comp_id, neg_add, h,\n    \u03b5_succ, neg_smul, neg_neg, inl_snd, neg_zero, zero_add, d_snd \u03c6 (q-1) q (by linarith),\n    preadditive.comp_add, lift_cochain_snd_v_assoc, inr_snd, lift_cochain_snd_v],\n  refine \u27e8rfl, _\u27e9,\n  have : \u2200 (x y z : K.X p \u27f6 G.X q), x +y +z = y+z +x := \u03bb x y z, by abel,\n  apply this,\nend\n\ndef lift_cocycle {K : cochain_complex C \u2124}\n  {n m : \u2124} (\u03b1 : cocycle K F m) (\u03b2 : cochain K G n) (h : n+1=m)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 n m \u03b2 + (\u03b1 : cochain K F m).comp (cochain.of_hom \u03c6) (add_zero m).symm = 0) :\n  cocycle K (mapping_cone \u03c6) n :=\ncocycle.mk (lift_cochain \u03c6 (\u03b1 : cochain K F m) \u03b2 h) _ h\n  (by simp only [\u03b4_lift_cochain \u03c6 _ _ h (m+1) (by linarith), h\u03b1\u03b2, cochain.zero_comp, add_zero,\n    cocycle.\u03b4_eq_zero, neg_zero])\n\n@[simp]\ndef lift_cocycle_coe {K : cochain_complex C \u2124}\n  {n m : \u2124} (\u03b1 : cocycle K F m) (\u03b2 : cochain K G n) (h : n+1=m)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 n m \u03b2 + (\u03b1 : cochain K F m).comp (cochain.of_hom \u03c6) (add_zero m).symm = 0) :\n  (lift_cocycle \u03c6 \u03b1 \u03b2 h h\u03b1\u03b2 : cochain K (mapping_cone \u03c6) n) =\n    lift_cochain \u03c6 (\u03b1 : cochain K F m) \u03b2 h := rfl\n\ndef lift {K : cochain_complex C \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0) :\n   K \u27f6 mapping_cone \u03c6 :=\ncocycle.hom_of (lift_cocycle \u03c6 \u03b1 \u03b2 (zero_add 1) h\u03b1\u03b2)\n\n@[simp, reassoc]\nlemma lift_fst_f {K : cochain_complex C \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0)\n  (n n' : \u2124) (hnn' : n' = n+1) :\n    (lift \u03c6 \u03b1 \u03b2 h\u03b1\u03b2).f n \u226b\n      (fst \u03c6 : cochain (mapping_cone \u03c6) F 1).v n n' hnn' = (\u03b1 : 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 \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0) :\n  (cochain.of_hom (lift \u03c6 \u03b1 \u03b2 h\u03b1\u03b2)).comp\n    (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) (zero_add 1).symm =\n      (\u03b1 : 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 \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0) (n : \u2124) :\n  (lift \u03c6 \u03b1 \u03b2 h\u03b1\u03b2).f n \u226b (snd \u03c6).v n n (add_zero n).symm =\n    \u03b2.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 \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0) :\n  (cochain.of_hom (lift \u03c6 \u03b1 \u03b2 h\u03b1\u03b2)).comp\n    (snd \u03c6) (add_zero 0).symm = \u03b2 :=\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 \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0)\n  (\u03b1' : cochain F L (-1)) (\u03b2' : G \u27f6 L) (eq : hom_complex.\u03b4 (-1) 0 \u03b1' = cochain.of_hom (\u03c6 \u226b \u03b2'))\n  (n n' : \u2124) (hnn' : n' = n+1) :\n  (lift \u03c6 \u03b1 \u03b2 h\u03b1\u03b2).f n \u226b (desc \u03c6 \u03b1' \u03b2' eq).f n =\n    (\u03b1 : cochain K F 1).v n n' hnn' \u226b \u03b1'.v n' n (by { rw [hnn', int.add_neg_one, add_tsub_cancel_right], }) +\n      \u03b2.v n n (add_zero n).symm \u226b \u03b2'.f n :=\nbegin\n  rw [\u2190 id_comp ((desc \u03c6 \u03b1' \u03b2' eq).f n), \u2190 id \u03c6 _ _ 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 \u2124} (\u03b1 : cocycle K F 1) (\u03b2 : cochain K G 0)\n  (h\u03b1\u03b2 : hom_complex.\u03b4 0 1 \u03b2 + (\u03b1 : cochain K F 1).comp (cochain.of_hom \u03c6) (add_zero 1).symm = 0) (n n' : \u2124)\n    (hn' : n' = n+1) :\n    (lift \u03c6 \u03b1 \u03b2 h\u03b1\u03b2).f n = (\u03b1 : cochain K F 1).v n n' hn' \u226b\n      (inl \u03c6).v n' n (by rw [hn', int.add_neg_one, add_tsub_cancel_right]) +\n    \u03b2.v n n (add_zero n).symm \u226b (inr \u03c6).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 \u2124} (f\u2081 f\u2082 : K \u27f6 mapping_cone \u03c6)\n  (\u03b3\u2081 : cochain K F 0) (\u03b3\u2082 : cochain K G (-1))\n  (h\u2081 : (cochain.of_hom f\u2081).comp (fst \u03c6 :\n    cochain (mapping_cone \u03c6) F 1) (zero_add 1).symm = -hom_complex.\u03b4 0 1 \u03b3\u2081 +\n      (cochain.of_hom f\u2082).comp (fst \u03c6 : cochain (mapping_cone \u03c6) F 1) (zero_add 1).symm)\n  (h\u2082 : (cochain.of_hom f\u2081).comp (snd \u03c6) (add_zero 0).symm =\n    hom_complex.\u03b4 (-1) 0 \u03b3\u2082 + \u03b3\u2081.comp (cochain.of_hom \u03c6) (zero_add 0).symm +\n    (cochain.of_hom f\u2082).comp (snd \u03c6) (add_zero 0).symm) :\n  homotopy f\u2081 f\u2082 :=\n(equiv_homotopy _ _).symm\nbegin\n  refine \u27e8lift_cochain \u03c6 \u03b3\u2081 \u03b3\u2082 (neg_add_self 1), _\u27e9,\n  simp only [\u03b4_lift_cochain \u03c6 _ _ _ 1 (show (0 : \u2124) = 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 : \u2124) = 1+(-1)+1, by linarith),\n      inl_comp_fst, cochain.comp_id, h\u2081], },\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\u2082], },\nend\n\nsection\n\nvariables {K\u2081 K\u2082 L\u2081 L\u2082 : cochain_complex C \u2124}\n  [\u2200 p, has_binary_biproduct (K\u2081.X (p+1)) (L\u2081.X p)]\n  [\u2200 p, has_binary_biproduct (K\u2082.X (p+1)) (L\u2082.X p)]\n  (f\u2081 : K\u2081 \u27f6 L\u2081) (f\u2082 : K\u2082 \u27f6 L\u2082) (\u03c4\u2081 : K\u2081 \u27f6 K\u2082) (\u03c4\u2082 : L\u2081 \u27f6 L\u2082) (comm : f\u2081 \u226b \u03c4\u2082 = \u03c4\u2081 \u226b f\u2082)\n\ninclude comm\n\ndef map : mapping_cone f\u2081 \u27f6 mapping_cone f\u2082 :=\ndesc f\u2081 ((cochain.of_hom \u03c4\u2081).comp (inl f\u2082) (zero_add _).symm)\n  (\u03c4\u2082 \u226b inr f\u2082)\nbegin\n  rw [\u03b4_comp_of_first_is_zero_cochain _ _ _ (neg_add_self 1), \u03b4_inl,\n    cocycle.\u03b4_cochain_of_hom, cochain.zero_comp, smul_zero, add_zero, cochain.of_hom_comp f\u2082,\n    \u2190 assoc f\u2081, \u2190 cochain.of_hom_comp, \u2190 cochain.of_hom_comp, \u2190 assoc, comm],\nend\n\nlemma inr_comp_map :\n  inr f\u2081 \u226b map _ _ _ _ comm =\n    \u03c4\u2082 \u226b inr f\u2082 :=\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_\u03b4 :\n  map _ _ _ _ comm \u226b \u03b4 f\u2082 =\n  \u03b4 f\u2081 \u226b \u03c4\u2081\u27e61\u27e7' :=\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, \u2190 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_\u03b4, 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, \u2190 hom_complex.cochain.comp_assoc_of_first_is_zero_cochain,\n      \u2190 cochain.of_hom_comp, inr_desc, \u2190 cochain.of_hom_comp, assoc,\n      inr_\u03b4, comp_zero, cochain.of_hom_zero, \u2190 cochain.of_hom_comp, \u2190 assoc,\n      inr_\u03b4, zero_comp, cochain.of_hom_zero], },\nend\n\nend\n\nexample : \u2115 := 42\n\nsection\n\nvariables {K L : cochain_complex C \u2124} (f : K \u27f6 L) {D : Type*} [category D] [preadditive D]\n  [\u2200 p, has_binary_biproduct (K.X (p+1)) (L.X p)] (\u03a6 : C \u2964 D) [functor.additive \u03a6]\n  [\u2200 p, has_binary_biproduct (((\u03a6.map_homological_complex (complex_shape.up \u2124)).obj K).X (p + 1))\n    (((\u03a6.map_homological_complex (complex_shape.up \u2124)).obj  L).X p)]\n\n@[simps]\ndef map_iso : (\u03a6.map_homological_complex _).obj (mapping_cone f) \u2245\n  mapping_cone ((\u03a6.map_homological_complex _).map f) :=\n{ hom := mapping_cone.lift _ (cocycle.map (mapping_cone.fst f) \u03a6)\n    ((mapping_cone.snd f).map \u03a6) (by simp),\n  inv := mapping_cone.desc _ ((mapping_cone.inl f).map \u03a6)\n      ((\u03a6.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, \u2190 \u03a6.map_comp, \u2190 \u03a6.map_add,\n      mapping_cone.id, \u03a6.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, \u2190 \u03a6.map_comp, \u03a6.map_zero, \u03a6.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 \u2124)} (ex : S.short_exact)\n\ninclude ex\n\nlemma degreewise_exact (n : \u2124) :\n  (S.map (homological_complex.eval C (complex_shape.up \u2124) n)).short_exact :=\nex.map_of_exact (homological_complex.eval C (complex_shape.up \u2124) n)\n\ndef from_mapping_cone_of_ses : mapping_cone S.f \u27f6 S.X\u2083 :=\nmapping_cone.desc S.f 0 S.g (by simp)\n\n@[simp, reassoc]\nlemma inr_from_mapping_cone_of_ses (n : \u2124) :\n  (mapping_cone.inr S.f).f n \u226b (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 : \u2124) (hpq : q = p + (-1)) :\n  (mapping_cone.inl S.f).v p q hpq \u226b (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 \u226b 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\u27e8\u03bb 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 : \u2200 (n : \u2124), mono (S.f.f n) :=\n    \u03bb 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\u2082 hxy z hz,\n    obtain \u27e8x, y, rfl\u27e9 := mapping_cone.to_decomposition x\u2082 _ 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 \u27e8hx, hy\u27e9 := (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, \u2190 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 \u27e8A', \u03c0, h\u03c0, z', hz'\u27e9 := 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' \u27f6 S.X\u2081.X n := ex'.exact.lift (\u03c0 \u226b y - z' \u226b S.X\u2082.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 \u226b S.f.f n = _ := ex'.exact.lift_f _ _,\n    refine \u27e8A', \u03c0, h\u03c0, w \u226b (mapping_cone.inl S.f).v n (n-1) (show n-1 = n+(-1), by refl) + z' \u226b (mapping_cone.inr S.f).f (n-1),\n      (mapping_cone.to_ext_iff _ _ _ rfl).mpr \u27e8_, _\u27e9\u27e9,\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, \u2190 cancel_mono (S.f.f (n+1)), zero_comp],\n      simp only [\u2190 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 \u27e8A', \u03c0, h\u03c0, y, hy\u27e9 := 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' \u27f6 S.X\u2081.X (n+1) := ex'.exact.lift (y \u226b S.X\u2082.d _ _) begin\n      dsimp,\n      simp only [assoc, \u2190 S.g.comm, \u2190 reassoc_of hy, hz, comp_zero],\n    end,\n    have hx : x \u226b S.f.f (n+1) = _ := ex'.exact.lift_f _ _,\n    have hdx : x \u226b S.X\u2081.d (n+1) (n+1+1) = 0,\n    { simp only [\u2190 cancel_mono (S.f.f (n+1+1)), assoc, zero_comp, \u2190 S.f.comm, reassoc_of hx,\n        homological_complex.d_comp_d, comp_zero], },\n    refine \u27e8A', \u03c0, h\u03c0, y \u226b (mapping_cone.inr S.f).f n -\n      x \u226b (mapping_cone.inl S.f).v (n+1) n (show n = (n+1)+(-1), by linarith), _, _\u27e9,\n    { simp only [preadditive.sub_comp, assoc, mapping_cone.inr_d, \u2190 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 \u27e80, 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]\u27e9, }, },\nend\u27e9\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": "/-\nCopyright (c) 2017 Mario Carneiro All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Floris van Doorn\n-/\nimport tactic.core\n\nnamespace tactic\n\n/-- `copy_attribute' attr_name src tgt p d_name` copy (user) attribute `attr_name` from\n   `src` to `tgt` if it is defined for `src`; unlike `copy_attribute` the primed version also copies\n   the parameter of the user attribute, in the user attribute case. Make it persistent if `p` is\n   `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src`  -/\nmeta def copy_attribute' (attr_name : name) (src : name) (tgt : name) (p : option bool := none) :\ntactic unit := do\n  get_decl tgt <|> fail!\"unknown declaration {tgt}\",\n  -- if the source doesn't have the attribute we do not error and simply return\n  mwhen (succeeds (has_attribute attr_name src)) $\n    do (p', prio) \u2190 has_attribute attr_name src,\n      let p := p.get_or_else p',\n      s \u2190 try_or_report_error (set_basic_attribute attr_name tgt p prio),\n      sum.inr msg \u2190 return s | skip,\n      if msg =\n        (format!(\"set_basic_attribute tactic failed, '{attr_name}' \" ++\n          \"is not a basic attribute\")).to_string\n      then do\n        user_attr_const \u2190 (get_user_attribute_name attr_name >>= mk_const),\n        tac \u2190 eval_pexpr (tactic unit)\n        ``(user_attribute.get_param_untyped %%user_attr_const %%`(src) >>=\n          \u03bb x, user_attribute.set_untyped %%user_attr_const %%`(tgt) x %%`(p) %%`(prio)),\n        tac\n      else fail msg\n\nopen expr\n/-- Auxilliary function for `additive_test`. The bool argument *only* matters when applied\nto exactly a constant. -/\nmeta def additive_test_aux (f : name \u2192 option name) (ignore : name_map $ list \u2115) :\n  bool \u2192 expr \u2192 bool\n| b (var n)                := tt\n| b (sort l)               := tt\n| b (const n ls)           := b || (f n).is_some\n| b (mvar n m t)           := tt\n| b (local_const n m bi t) := tt\n| b (app e f)              := additive_test_aux tt e &&\n  -- this might be inefficient.\n  -- If it becomes a performance problem: we can give this info for the recursive call to `e`.\n    match ignore.find e.get_app_fn.const_name with\n    | some l := if e.get_app_num_args + 1 \u2208 l then tt else additive_test_aux ff f\n    | none   := additive_test_aux ff f\n    end\n| b (lam n bi e t)         := additive_test_aux ff t\n| b (pi n bi e t)          := additive_test_aux ff t\n| b (elet n g e f)         := additive_test_aux ff e && additive_test_aux ff f\n| b (macro d args)         := tt\n\n/--\n`additive_test f replace_all ignore e` tests whether the expression `e` contains no constant\n`nm` that is not applied to any arguments, and such that `f nm = none`.\nThis is used in `@[to_additive]` for deciding which subexpressions to transform: we only transform\nconstants if `additive_test` applied to their first argument returns `tt`.\nThis means we will replace expression applied to e.g. `\u03b1` or `\u03b1 \u00d7 \u03b2`, but not when applied to\ne.g. `\u2115` or `\u211d \u00d7 \u03b1`.\n`f` is the dictionary of declarations that are in the `to_additive` dictionary.\nWe ignore all arguments specified in the `name_map` `ignore`.\nIf `replace_all` is `tt` the test always return `tt`.\n-/\nmeta def additive_test (f : name \u2192 option name) (replace_all : bool) (ignore : name_map $ list \u2115)\n  (e : expr) : bool :=\nif replace_all then tt else additive_test_aux f ignore ff e\n\n/-- transform the declaration `src` and all declarations `pre._proof_i` occurring in `src`\nusing the dictionary `f`.\n`replace_all`, `trace`, `ignore` and `reorder` are configuration options.\n`pre` is the declaration that got the `@[to_additive]` attribute and `tgt_pre` is the target of this\ndeclaration. -/\nmeta def transform_decl_with_prefix_fun_aux (f : name \u2192 option name)\n  (replace_all trace : bool) (relevant : name_map \u2115) (ignore reorder : name_map $ list \u2115)\n  (pre tgt_pre : name) : name \u2192 command :=\n\u03bb src,\ndo\n  -- if this declaration is not `pre` or an internal declaration, we do nothing.\n  tt \u2190 return (src = pre \u2228 src.is_internal : bool) |\n    if (f src).is_some then skip else fail!(\"@[to_additive] failed.\nThe declaration {pre} depends on the declaration {src} which is in the namespace {pre}, but \" ++\n\"does not have the `@[to_additive]` attribute. This is not supported. Workaround: move {src} to \" ++\n\"a different namespace.\"),\n  env \u2190 get_env,\n  -- we find the additive name of `src`\n  let tgt := src.map_prefix (\u03bb n, if n = pre then some tgt_pre else none),\n  -- we skip if we already transformed this declaration before\n  ff \u2190 return $ env.contains tgt | skip,\n  decl \u2190 get_decl src,\n  -- we first transform all the declarations of the form `pre._proof_i`\n  (decl.type.list_names_with_prefix pre).mfold () (\u03bb n _, transform_decl_with_prefix_fun_aux n),\n  (decl.value.list_names_with_prefix pre).mfold () (\u03bb n _, transform_decl_with_prefix_fun_aux n),\n  -- we transform `decl` using `f` and the configuration options.\n  let decl :=\n    decl.update_with_fun env (name.map_prefix f) (additive_test f replace_all ignore)\n      relevant reorder tgt,\n  -- o \u2190 get_options, set_options $ o.set_bool `pp.all tt, -- print with pp.all (for debugging)\n  pp_decl \u2190 pp decl,\n  when trace $ trace!\"[to_additive] > generating\\n{pp_decl}\",\n  decorate_error (format!\"@[to_additive] failed. Type mismatch in additive declaration.\nFor help, see the docstring of `to_additive.attr`, section `Troubleshooting`.\nFailed to add declaration\\n{pp_decl}\n\nNested error message:\\n\").to_string $ do\n  { if env.is_protected src then add_protected_decl decl else add_decl decl,\n    -- we test that the declaration value type-checks, so that we get the decorated error message\n    -- without this line, the type-checking might fail outside the `decorate_error`.\n    decorate_error \"proof doesn't type-check. \" $ type_check decl.value }\n\n/--\nMake a new copy of a declaration,\nreplacing fragments of the names of identifiers in the type and the body using the function `f`.\nThis is used to implement `@[to_additive]`.\n-/\nmeta def transform_decl_with_prefix_fun (f : name \u2192 option name) (replace_all trace : bool)\n  (relevant : name_map \u2115) (ignore reorder : name_map $ list \u2115) (src tgt : name) (attrs : list name)\n  : command :=\ndo -- In order to ensure that attributes are copied correctly we must transform declarations and\n   -- attributes in the right order:\n   -- first generate the transformed main declaration\n   transform_decl_with_prefix_fun_aux f replace_all trace relevant ignore reorder src tgt src,\n   ls \u2190 get_eqn_lemmas_for tt src,\n   -- now transform all of the equational lemmas\n   ls.mmap' $\n    transform_decl_with_prefix_fun_aux f replace_all trace relevant ignore reorder src tgt,\n   -- copy attributes for the equational lemmas so that they know if they are refl lemmas\n   ls.mmap' (\u03bb src_eqn, do\n    let tgt_eqn := src_eqn.map_prefix (\u03bb n, if n = src then some tgt else none),\n    attrs.mmap' (\u03bb n, copy_attribute' n src_eqn tgt_eqn)),\n   -- set the transformed equation lemmas as equation lemmas for the new declaration\n   ls.mmap' (\u03bb src_eqn, do\n    e \u2190 get_env,\n    let tgt_eqn := src_eqn.map_prefix (\u03bb n, if n = src then some tgt else none),\n    set_env (e.add_eqn_lemma tgt_eqn)),\n   -- copy attributes for the main declaration, this needs the equational lemmas to exist already\n   attrs.mmap' (\u03bb n, copy_attribute' n src tgt)\n\n/--\nMake a new copy of a declaration, replacing fragments of the names of identifiers in the type and\nthe body using the dictionary `dict`.\nThis is used to implement `@[to_additive]`.\n-/\nmeta def transform_decl_with_prefix_dict (dict : name_map name) (replace_all trace : bool)\n  (relevant : name_map \u2115) (ignore reorder : name_map $ list \u2115) (src tgt : name) (attrs : list name)\n  : command :=\ntransform_decl_with_prefix_fun dict.find replace_all trace relevant ignore reorder src tgt attrs\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/transform_decl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.03514484614814642, "lm_q1q2_score": 0.013527677602487957}}
{"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.Data.LOption\nimport Lean.Environment\nimport Lean.Class\nimport Lean.ReducibilityAttrs\nimport Lean.Util.Trace\nimport Lean.Util.RecDepth\nimport Lean.Util.PPExt\nimport Lean.Util.OccursCheck\nimport Lean.Util.MonadBacktrack\nimport Lean.Compiler.InlineAttrs\nimport Lean.Meta.TransparencyMode\nimport Lean.Meta.DiscrTreeTypes\nimport Lean.Eval\nimport Lean.CoreM\n\n/-\nThis module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.\n1- Weak head normal form computation with support for metavariables and transparency modes.\n2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).\n3- Type inference.\n4- Type class resolution.\n\nThey are packed into the MetaM monad.\n-/\n\nnamespace Lean.Meta\n\nbuiltin_initialize isDefEqStuckExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `isDefEqStuck\n\nstructure Config where\n  foApprox           : Bool := false\n  ctxApprox          : Bool := false\n  quasiPatternApprox : Bool := false\n  /- When `constApprox` is set to true,\n     we solve `?m t =?= c` using\n     `?m := fun _ => c`\n     when `?m t` is not a higher-order pattern and `c` is not an application as -/\n  constApprox        : Bool := false\n  /-\n    When the following flag is set,\n    `isDefEq` throws the exeption `Exeption.isDefEqStuck`\n    whenever it encounters a constraint `?m ... =?= t` where\n    `?m` is read only.\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  isDefEqStuckEx     : Bool := false\n  transparency       : TransparencyMode := TransparencyMode.default\n  /- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/\n  zetaNonDep         : Bool := true\n  /- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/\n  trackZeta          : Bool := false\n  unificationHints   : Bool := true\n\nstructure ParamInfo where\n  implicit     : Bool      := false\n  instImplicit : Bool      := false\n  hasFwdDeps   : Bool      := false\n  backDeps     : Array Nat := #[]\n  deriving Inhabited\n\ndef ParamInfo.isExplicit (p : ParamInfo) : Bool :=\n  !p.implicit && !p.instImplicit\n\nstructure FunInfo where\n  paramInfo  : Array ParamInfo := #[]\n  resultDeps : Array Nat       := #[]\n\nstructure InfoCacheKey where\n  transparency : TransparencyMode\n  expr         : Expr\n  nargs?       : Option Nat\n  deriving Inhabited, BEq\n\nnamespace InfoCacheKey\ninstance : Hashable InfoCacheKey :=\n  \u27e8fun \u27e8transparency, expr, nargs\u27e9 => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)\u27e9\nend InfoCacheKey\n\nopen Std (PersistentArray PersistentHashMap)\n\nabbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)\n\nabbrev InferTypeCache := PersistentExprStructMap Expr\nabbrev FunInfoCache   := PersistentHashMap InfoCacheKey FunInfo\nabbrev WhnfCache      := PersistentExprStructMap Expr\nstructure Cache where\n  inferType     : InferTypeCache := {}\n  funInfo       : FunInfoCache   := {}\n  synthInstance : SynthInstanceCache := {}\n  whnfDefault   : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`\n  whnfAll       : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`\n  deriving Inhabited\n\n/--\n \"Context\" for a postponed universe constraint.\n `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.\n-/\nstructure DefEqContext where\n  lhs            : Expr\n  rhs            : Expr\n  lctx           : LocalContext\n  localInstances : LocalInstances\n\n/--\n  Auxiliary structure for representing postponed universe constraints.\n  Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.\n  Remark: we may consider improving the error message generation in the future.\n-/\nstructure PostponedEntry where\n  ref  : Syntax -- We save the `ref` at entry creation time\n  lhs  : Level\n  rhs  : Level\n  ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created\n  deriving Inhabited\n\nstructure State where\n  mctx        : MetavarContext := {}\n  cache       : Cache := {}\n  /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/\n  zetaFVarIds : NameSet := {}\n  postponed   : PersistentArray PostponedEntry := {}\n  deriving Inhabited\n\nstructure SavedState where\n  core        : Core.State\n  meta        : State\n  deriving Inhabited\n\nstructure Context where\n  config         : Config               := {}\n  lctx           : LocalContext         := {}\n  localInstances : LocalInstances       := #[]\n  /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/\n  defEqCtx?      : Option DefEqContext  := none\n\nabbrev MetaM  := ReaderT Context $ StateRefT State CoreM\n\ninstance : Inhabited (MetaM \u03b1) where\n  default := fun _ _ => arbitrary\n\ninstance : MonadLCtx MetaM where\n  getLCtx := return (\u2190 read).lctx\n\ninstance : MonadMCtx MetaM where\n  getMCtx    := return (\u2190 get).mctx\n  modifyMCtx f := modify fun s => { s with mctx := f s.mctx }\n\ninstance : AddMessageContext MetaM where\n  addMessageContext := addMessageContextFull\n\nprotected def saveState : MetaM SavedState :=\n  return { core := (\u2190 getThe Core.State), meta := (\u2190 get) }\n\n/-- Restore backtrackable parts of the state. -/\ndef SavedState.restore (b : SavedState) : MetaM Unit := do\n  Core.restore b.core\n  modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }\n\ninstance : MonadBacktrack SavedState MetaM where\n  saveState      := Meta.saveState\n  restoreState s := s.restore\n\n@[inline] def MetaM.run (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM (\u03b1 \u00d7 State) :=\n  x ctx |>.run s\n\n@[inline] def MetaM.run' (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM \u03b1 :=\n  Prod.fst <$> x.run ctx s\n\n@[inline] def MetaM.toIO (x : MetaM \u03b1) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (\u03b1 \u00d7 Core.State \u00d7 State) := do\n  let ((a, s), sCore) \u2190 (x.run ctx s).toIO ctxCore sCore\n  pure (a, sCore, s)\n\ninstance [MetaEval \u03b1] : MetaEval (MetaM \u03b1) :=\n  \u27e8fun env opts x _ => MetaEval.eval env opts x.run' true\u27e9\n\nprotected def throwIsDefEqStuck : MetaM \u03b1 :=\n  throw <| Exception.internal isDefEqStuckExceptionId\n\nbuiltin_initialize\n  registerTraceClass `Meta\n  registerTraceClass `Meta.debug\n\n@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM \u03b1) : m \u03b1 :=\n  liftM x\n\n@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, MetaM \u03b1 \u2192 MetaM \u03b1) {\u03b1} (x : m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f <| runInBase x\n\n@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b => runInBase <| k b\n\n@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 \u03b3 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 \u03b3 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c\n\nsection Methods\nvariable [MonadControlT MetaM n] [Monad n]\n\n@[inline] def modifyCache (f : Cache \u2192 Cache) : MetaM Unit :=\n  modify fun \u27e8mctx, cache, zetaFVarIds, postponed\u27e9 => \u27e8mctx, f cache, zetaFVarIds, postponed\u27e9\n\n@[inline] def modifyInferTypeCache (f : InferTypeCache \u2192 InferTypeCache) : MetaM Unit :=\n  modifyCache fun \u27e8ic, c1, c2, c3, c4\u27e9 => \u27e8f ic, c1, c2, c3, c4\u27e9\n\ndef getLocalInstances : MetaM LocalInstances :=\n  return (\u2190 read).localInstances\n\ndef getConfig : MetaM Config :=\n  return (\u2190 read).config\n\ndef setMCtx (mctx : MetavarContext) : MetaM Unit :=\n  modify fun s => { s with mctx := mctx }\n\ndef resetZetaFVarIds : MetaM Unit :=\n  modify fun s => { s with zetaFVarIds := {} }\n\ndef getZetaFVarIds : MetaM NameSet :=\n  return (\u2190 get).zetaFVarIds\n\ndef getPostponed : MetaM (PersistentArray PostponedEntry) :=\n  return (\u2190 get).postponed\n\ndef setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := postponed }\n\n@[inline] def modifyPostponed (f : PersistentArray PostponedEntry \u2192 PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := f s.postponed }\n\nbuiltin_initialize whnfRef : IO.Ref (Expr \u2192 MetaM Expr) \u2190 IO.mkRef fun _ => throwError \"whnf implementation was not set\"\nbuiltin_initialize inferTypeRef : IO.Ref (Expr \u2192 MetaM Expr) \u2190 IO.mkRef fun _ => throwError \"inferType implementation was not set\"\nbuiltin_initialize isExprDefEqAuxRef : IO.Ref (Expr \u2192 Expr \u2192 MetaM Bool) \u2190 IO.mkRef fun _ _ => throwError \"isDefEq implementation was not set\"\nbuiltin_initialize synthPendingRef : IO.Ref (MVarId \u2192 MetaM Bool) \u2190 IO.mkRef fun _ => pure false\n\ndef whnf (e : Expr) : MetaM Expr :=\n  withIncRecDepth do (\u2190 whnfRef.get) e\n\ndef whnfForall (e : Expr) : MetaM Expr := do\n  let e' \u2190 whnf e\n  if e'.isForall then pure e' else pure e\n\ndef inferType (e : Expr) : MetaM Expr :=\n  withIncRecDepth do (\u2190 inferTypeRef.get) e\n\nprotected def isExprDefEqAux (t s : Expr) : MetaM Bool :=\n  withIncRecDepth do (\u2190 isExprDefEqAuxRef.get) t s\n\nprotected def synthPending (mvarId : MVarId) : MetaM Bool :=\n  withIncRecDepth do (\u2190 synthPendingRef.get) mvarId\n\n-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`\nprotected def withIncRecDepth (x : n \u03b1) : n \u03b1 :=\n  mapMetaM (withIncRecDepth (m := MetaM)) x\n\nprivate def mkFreshExprMVarAtCore\n    (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do\n  modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;\n  return mkMVar mvarId\n\ndef mkFreshExprMVarAt\n    (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  let mvarId \u2190 mkFreshId\n  mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs\n\ndef mkFreshLevelMVar : MetaM Level := do\n  let mvarId \u2190 mkFreshId\n  modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;\n  return mkLevelMVar mvarId\n\nprivate def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do\n  let lctx \u2190 getLCtx\n  let localInsts \u2190 getLocalInstances\n  mkFreshExprMVarAt lctx localInsts type kind userName\n\nprivate def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarCore type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous\n    mkFreshExprMVarCore type kind userName\n\ndef mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  mkFreshExprMVarImpl type? kind userName\n\ndef mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  mkFreshExprMVar (mkSort u) kind userName\n\n/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create\n   the metavar using this method. -/\nprivate def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  let lctx \u2190 getLCtx\n  let localInsts \u2190 getLocalInstances\n  mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs\n\ndef mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarWithIdCore mvarId type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVar (mkSort u)\n    mkFreshExprMVarWithIdCore mvarId type kind userName\n\ndef mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=\n  num.foldM (init := []) fun _ us =>\n    return (\u2190 mkFreshLevelMVar)::us\n\ndef mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=\n  mkFreshLevelMVars info.numLevelParams\n\ndef mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do\n  let info \u2190 getConstInfo declName\n  return mkConst declName (\u2190 mkFreshLevelMVarsFor info)\n\ndef getTransparency : MetaM TransparencyMode :=\n  return (\u2190 getConfig).transparency\n\ndef shouldReduceAll : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.all\n\ndef shouldReduceReducibleOnly : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.reducible\n\ndef getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do\n  let mctx \u2190 getMCtx\n  match mctx.findDecl? mvarId with\n  | some d => pure d\n  | none   => throwError \"unknown metavariable '?{mvarId}'\"\n\ndef setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.setMVarKind mvarId kind\n\n/- Update the type of the given metavariable. This function assumes the new type is\n   definitionally equal to the current one -/\ndef setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.setMVarType mvarId type\n\ndef isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  let mctx     \u2190 getMCtx\n  return mvarDecl.depth != mctx.depth\n\ndef isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  match mvarDecl.kind with\n  | MetavarKind.syntheticOpaque => pure true\n  | _ =>\n    let mctx \u2190 getMCtx\n    return mvarDecl.depth != mctx.depth\n\ndef isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  match mctx.findLevelDepth? mvarId with\n  | some depth => return depth != mctx.depth\n  | _          => throwError \"unknown universe metavariable '?{mvarId}'\"\n\ndef renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName\n\ndef isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).isExprAssigned mvarId\n\ndef getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=\n  return (\u2190 getMCtx).getExprAssignment? mvarId\n\n/-- Return true if `e` contains `mvarId` directly or indirectly -/\ndef occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=\n  return (\u2190 getMCtx).occursCheck mvarId e\n\ndef assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.assignExpr mvarId val\n\ndef isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).isDelayedAssigned mvarId\n\ndef getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=\n  return (\u2190 getMCtx).getDelayedAssignment? mvarId\n\ndef hasAssignableMVar (e : Expr) : MetaM Bool :=\n  return (\u2190 getMCtx).hasAssignableMVar e\n\ndef throwUnknownFVar (fvarId : FVarId) : MetaM \u03b1 :=\n  throwError \"unknown free variable '{mkFVar fvarId}'\"\n\ndef findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=\n  return (\u2190 getLCtx).find? fvarId\n\ndef getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).find? fvarId with\n  | some d => pure d\n  | none   => throwUnknownFVar fvarId\n\ndef getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=\n  getLocalDecl fvar.fvarId!\n\ndef getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).findFromUserName? userName with\n  | some d => pure d\n  | none   => throwError \"unknown local declaration '{userName}'\"\n\ndef instantiateLevelMVars (u : Level) : MetaM Level :=\n  MetavarContext.instantiateLevelMVars u\n\ndef instantiateMVars (e : Expr) : MetaM Expr :=\n  (MetavarContext.instantiateExprMVars e).run\n\ndef instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := do\n  match localDecl with\n  | LocalDecl.cdecl idx id n type bi  =>\n    let type \u2190 instantiateMVars type\n    return LocalDecl.cdecl idx id n type bi\n  | LocalDecl.ldecl idx id n type val nonDep =>\n    let type \u2190 instantiateMVars type\n    let val \u2190 instantiateMVars val\n    return LocalDecl.ldecl idx id n type val nonDep\n\n@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM \u03b1) : MetaM \u03b1 := do\n  match x (\u2190 getLCtx) { mctx := (\u2190 getMCtx), ngen := (\u2190 getNGen) } with\n  | EStateM.Result.ok e newS => do\n    setNGen newS.ngen;\n    setMCtx newS.mctx;\n    pure e\n  | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do\n    setMCtx newS.mctx;\n    setNGen newS.ngen;\n    throwError \"failed to create binder due to failure when reverting variable dependencies\"\n\ndef mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly\n\ndef mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly\n\ndef mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr :=\n  mkLambdaFVars xs e (usedLetOnly := usedLetOnly)\n\ndef mkArrow (d b : Expr) : MetaM Expr := do\n  let n \u2190 mkFreshUserName `x\n  return Lean.mkForall n BinderInfo.default d b\n\ndef elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder\n\n@[inline] def withConfig (f : Config \u2192 Config) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })\n\n@[inline] def withTrackingZeta (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with trackZeta := true }) x\n\n@[inline] def withTransparency (mode : TransparencyMode) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withConfig (fun config => { config with transparency := mode })\n\n@[inline] def withDefault (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.default x\n\n@[inline] def withReducible (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.reducible x\n\n@[inline] def withReducibleAndInstances (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.instances x\n\n@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n \u03b1) : n \u03b1 :=\n  withConfig\n    (fun config =>\n      let oldMode := config.transparency\n      let mode    := if oldMode.lt mode then mode else oldMode\n      { config with transparency := mode })\n    x\n\n/-- Save cache, execute `x`, restore cache -/\n@[inline] private def savingCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let s \u2190 get\n  let savedCache := s.cache\n  try x finally modify fun s => { s with cache := savedCache }\n\n@[inline] def savingCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM savingCacheImpl\n\ndef getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  if (\u2190 shouldReduceAll) then\n    return some info\n  else\n    return none\n\nprivate def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getTransparency) with\n  | TransparencyMode.all => return some info\n  | TransparencyMode.default => return some info\n  | _ =>\n    if (\u2190 isReducible info.name) then\n      return some info\n    else\n      return none\n\n/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.\n   This method is only used to implement `isClassQuickConst?`.\n   It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and\n   `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/\nprivate def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do\n  let env \u2190 getEnv\n  match env.find? constName with\n  | some (info@(ConstantInfo.thmInfo _))  => getTheoremInfo info\n  | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info\n  | some info                             => pure (some info)\n  | none                                  => throwUnknownConstant constName\n\nprivate def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do\n  let env \u2190 getEnv\n  if isClass env constName then\n    pure (LOption.some constName)\n  else\n    match (\u2190 getConstTemp? constName) with\n    | some _ => pure LOption.undef\n    | none   => pure LOption.none\n\nprivate partial def isClassQuick? : Expr \u2192 MetaM (LOption Name)\n  | Expr.bvar ..         => pure LOption.none\n  | Expr.lit ..          => pure LOption.none\n  | Expr.fvar ..         => pure LOption.none\n  | Expr.sort ..         => pure LOption.none\n  | Expr.lam ..          => pure LOption.none\n  | Expr.letE ..         => pure LOption.undef\n  | Expr.proj ..         => pure LOption.undef\n  | Expr.forallE _ _ b _ => isClassQuick? b\n  | Expr.mdata _ e _     => isClassQuick? e\n  | Expr.const n _ _     => isClassQuickConst? n\n  | Expr.mvar mvarId _   => do\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => isClassQuick? val\n    | none     => pure LOption.none\n  | Expr.app f _ _       =>\n    match f.getAppFn with\n    | Expr.const n .. => isClassQuickConst? n\n    | Expr.lam ..     => pure LOption.undef\n    | _              => pure LOption.none\n\ndef saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do\n  let s \u2190 get\n  let savedSythInstance := s.cache.synthInstance\n  modifyCache fun c => { c with synthInstance := {} }\n  pure savedSythInstance\n\ndef restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=\n  modifyCache fun c => { c with synthInstance := cache }\n\n@[inline] private def resettingSynthInstanceCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let savedSythInstance \u2190 saveAndResetSynthInstanceCache\n  try x finally restoreSynthInstanceCache savedSythInstance\n\n/-- Reset `synthInstance` cache, execute `x`, and restore cache -/\n@[inline] def resettingSynthInstanceCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM resettingSynthInstanceCacheImpl\n\n@[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n \u03b1) : n \u03b1 :=\n  if b then resettingSynthInstanceCache x else x\n\nprivate def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let localDecl \u2190 getFVarLocalDecl fvar\n  /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/\n  match localDecl.binderInfo with\n  | BinderInfo.auxDecl => k\n  | _ =>\n    resettingSynthInstanceCache <|\n      withReader\n        (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })\n        k\n\n/-- Add entry `{ className := className, fvar := fvar }` to localInstances,\n    and then execute continuation `k`.\n    It resets the type class cache using `resettingSynthInstanceCache`. -/\ndef withNewLocalInstance (className : Name) (fvar : Expr) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstanceImp className fvar\n\nprivate def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=\n  match maxFVars? with\n  | some maxFVars => fvars.size < maxFVars\n  | none          => true\n\nmutual\n  /--\n    `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances\n    using free variables `fvars[j] ... fvars.back`, and execute `k`.\n\n    - `isClassExpensive` is defined later.\n    - The type class chache is reset whenever a new local instance is found.\n    - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.\n      Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/\n  private partial def withNewLocalInstancesImp\n      (fvars : Array Expr) (i : Nat) (k : MetaM \u03b1) : MetaM \u03b1 := do\n    if h : i < fvars.size then\n      let fvar := fvars.get \u27e8i, h\u27e9\n      let decl \u2190 getFVarLocalDecl fvar\n      match (\u2190 isClassQuick? decl.type) with\n      | LOption.none   => withNewLocalInstancesImp fvars (i+1) k\n      | LOption.undef  =>\n        match (\u2190 isClassExpensive? decl.type) with\n        | none   => withNewLocalInstancesImp fvars (i+1) k\n        | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n      | LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n    else\n      k\n\n  /--\n    `forallTelescopeAuxAux lctx fvars j type`\n    Remarks:\n    - `lctx` is the `MetaM` local context extended with declarations for `fvars`.\n    - `type` is the type we are computing the telescope for. It contains only\n      dangling bound variables in the range `[j, fvars.size)`\n    - if `reducing? == true` and `type` is not `forallE`, we use `whnf`.\n    - when `type` is not a `forallE` nor it can't be reduced to one, we\n      excute the continuation `k`.\n\n    Here is an example that demonstrates the `reducing?`.\n    Suppose we have\n    ```\n    abbrev StateM s a := s -> Prod a s\n    ```\n    Now, assume we are trying to build the telescope for\n    ```\n    forall (x : Nat), StateM Int Bool\n    ```\n    if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.\n    if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`\n\n    if `maxFVars?` is `some max`, then we interrupt the telescope construction\n    when `fvars.size == max`\n  -/\n  private partial def forallTelescopeReducingAuxAux\n      (reducing          : Bool) (maxFVars? : Option Nat)\n      (type              : Expr)\n      (k                 : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM \u03b1 := do\n      match type with\n      | Expr.forallE n d b c =>\n        if fvarsSizeLtMaxFVars fvars maxFVars? then\n          let d     := d.instantiateRevRange j fvars.size fvars\n          let fvarId \u2190 mkFreshId\n          let lctx  := lctx.mkLocalDecl fvarId n d c.binderInfo\n          let fvar  := mkFVar fvarId\n          let fvars := fvars.push fvar\n          process lctx fvars j b\n        else\n          let type := type.instantiateRevRange j fvars.size fvars;\n          withReader (fun ctx => { ctx with lctx := lctx }) do\n            withNewLocalInstancesImp fvars j do\n              k fvars type\n      | _ =>\n        let type := type.instantiateRevRange j fvars.size fvars;\n        withReader (fun ctx => { ctx with lctx := lctx }) do\n          withNewLocalInstancesImp fvars j do\n            if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then\n              let newType \u2190 whnf type\n              if newType.isForall then\n                process lctx fvars fvars.size newType\n              else\n                k fvars type\n            else\n              k fvars type\n    process (\u2190 getLCtx) #[] 0 type\n\n  private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    match maxFVars? with\n    | some 0 => k #[] type\n    | _ => do\n      let newType \u2190 whnf type\n      if newType.isForall then\n        forallTelescopeReducingAuxAux true maxFVars? newType k\n      else\n        k #[] type\n\n  private partial def isClassExpensive? : Expr \u2192 MetaM (Option Name)\n    | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.\n      forallTelescopeReducingAux type none fun xs type => do\n        let env \u2190 getEnv\n        match type.getAppFn with\n        | Expr.const c _ _ => do\n          if isClass env c then\n            return some c\n          else\n            -- make sure abbreviations are unfolded\n            match (\u2190 whnf type).getAppFn with\n            | Expr.const c _ _ => return if isClass env c then some c else none\n            | _ => return none\n        | _ => return none\n\n  private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do\n    match (\u2190 isClassQuick? type) with\n    | LOption.none   => pure none\n    | LOption.some c => pure (some c)\n    | LOption.undef  => isClassExpensive? type\n\nend\n\ndef isClass? (type : Expr) : MetaM (Option Name) :=\n  try isClassImp? type catch _ => pure none\n\nprivate def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImp fvars j\n\npartial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImpAux fvars j\n\n@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k\n\n/--\n  Given `type` of the form `forall xs, A`, execute `k xs A`.\n  This combinator will declare local declarations, create free variables for them,\n  execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/\ndef forallTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeImp type k) k\n\nprivate def forallTelescopeReducingImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type (maxFVars? := none) k\n\n/--\n  Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,\n  it reduces `A` and continues bulding the telescope if it is a `forall`. -/\ndef forallTelescopeReducing (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeReducingImp type k) k\n\nprivate def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type maxFVars? k\n\n/--\n  Similar to `forallTelescopeReducing`, stops constructing the telescope when\n  it reaches size `maxFVars`. -/\ndef forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k\n\n/-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/\nprivate partial def lambdaTelescopeAux\n    (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1)\n    : Bool \u2192 LocalContext \u2192 Array Expr \u2192 Nat \u2192 Expr \u2192 MetaM \u03b1\n  | consumeLet, lctx, fvars, j, Expr.lam n d b c => do\n    let d := d.instantiateRevRange j fvars.size fvars\n    let fvarId \u2190 mkFreshId\n    let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo\n    let fvar := mkFVar fvarId\n    lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b\n  | true, lctx, fvars, j, Expr.letE n t v b _ => do\n    let t := t.instantiateRevRange j fvars.size fvars\n    let v := v.instantiateRevRange j fvars.size fvars\n    let fvarId \u2190 mkFreshId\n    let lctx := lctx.mkLetDecl fvarId n t v\n    let fvar := mkFVar fvarId\n    lambdaTelescopeAux k true lctx (fvars.push fvar) j b\n  | _, lctx, fvars, j, e =>\n    let e := e.instantiateRevRange j fvars.size fvars;\n    withReader (fun ctx => { ctx with lctx := lctx }) do\n      withNewLocalInstancesImp fvars j do\n        k fvars e\n\nprivate partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM \u03b1 := do\n    match consumeLet, e with\n    | _, Expr.lam n d b c =>\n      let d := d.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshId\n      let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo\n      let fvar := mkFVar fvarId\n      process consumeLet lctx (fvars.push fvar) j b\n    | true, Expr.letE n t v b _ => do\n      let t := t.instantiateRevRange j fvars.size fvars\n      let v := v.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshId\n      let lctx := lctx.mkLetDecl fvarId n t v\n      let fvar := mkFVar fvarId\n      process true lctx (fvars.push fvar) j b\n    | _, e =>\n      let e := e.instantiateRevRange j fvars.size fvars\n      withReader (fun ctx => { ctx with lctx := lctx }) do\n        withNewLocalInstancesImp fvars j do\n          k fvars e\n  process consumeLet (\u2190 getLCtx) #[] 0 e\n\n/-- Similar to `forallTelescope` but for lambda and let expressions. -/\ndef lambdaLetTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp type true k) k\n\n/-- Similar to `forallTelescope` but for lambda expressions. -/\ndef lambdaTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp type false k) k\n\n/-- Return the parameter names for the givel global declaration. -/\ndef getParamNames (declName : Name) : MetaM (Array Name) := do\n  let cinfo \u2190 getConstInfo declName\n  forallTelescopeReducing cinfo.type fun xs _ => do\n    xs.mapM fun x => do\n      let localDecl \u2190 getLocalDecl x.fvarId!\n      pure localDecl.userName\n\n-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.\nprivate partial def forallMetaTelescopeReducingAux\n    (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    match type with\n    | Expr.forallE n d b c =>\n      let cont : Unit \u2192 MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := fun _ => do\n        let d  := d.instantiateRevRange j mvars.size mvars\n        let k  := if c.binderInfo.isInstImplicit then  MetavarKind.synthetic else kind\n        let mvar \u2190 mkFreshExprMVar d k n\n        let mvars := mvars.push mvar\n        let bis   := bis.push c.binderInfo\n        process mvars bis j b\n      match maxMVars? with\n      | none          => cont ()\n      | some maxMVars =>\n        if mvars.size < maxMVars then\n          cont ()\n        else\n          let type := type.instantiateRevRange j mvars.size mvars;\n          pure (mvars, bis, type)\n    | _ =>\n      let type := type.instantiateRevRange j mvars.size mvars;\n      if reducing then do\n        let newType \u2190 whnf type;\n        if newType.isForall then\n          process mvars bis mvars.size newType\n        else\n          pure (mvars, bis, type)\n      else\n        pure (mvars, bis, type)\n  process #[] #[] 0 e\n\n/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/\ndef forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind\n\n/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/\ndef forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind\n\n/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/\npartial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    let finalize : Unit \u2192 MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := fun _ => do\n      let type := type.instantiateRevRange j mvars.size mvars\n      pure (mvars, bis, type)\n    let cont : Unit \u2192 MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := fun _ => do\n      match type with\n      | Expr.lam n d b c =>\n        let d     := d.instantiateRevRange j mvars.size mvars\n        let mvar \u2190 mkFreshExprMVar d\n        let mvars := mvars.push mvar\n        let bis   := bis.push c.binderInfo\n        process mvars bis j b\n      | _ => finalize ()\n    match maxMVars? with\n    | none          => cont ()\n    | some maxMVars =>\n      if mvars.size < maxMVars then\n        cont ()\n      else\n        finalize ()\n  process #[] #[] 0 e\n\nprivate def withNewFVar (fvar fvarType : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  match (\u2190 isClass? fvarType) with\n  | none   => k fvar\n  | some c => withNewLocalInstance c fvar <| k fvar\n\nprivate def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLocalDecl fvarId n type bi\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar fvar type k\n\ndef withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  map1MetaM (fun k => withLocalDeclImp name bi type k) k\n\ndef withLocalDeclD (name : Name) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecl name BinderInfo.default type k\n\npartial def withLocalDecls\n    [Inhabited \u03b1]\n    (declInfos : Array (Name \u00d7 BinderInfo \u00d7 (Array Expr \u2192 n Expr)))\n    (k : (xs : Array Expr) \u2192 n \u03b1)\n    : n \u03b1 :=\n  let rec loop\n      [Inhabited \u03b1]\n      (acc : Array Expr) : n \u03b1 := do\n    if acc.size < declInfos.size then\n      let (name, bi, typeCtor) := declInfos[acc.size]\n      withLocalDecl name bi (\u2190typeCtor acc) fun x => loop (acc.push x)\n    else k acc\n\n  loop #[]\n\ndef withLocalDeclsD\n    [Inhabited \u03b1]\n    (declInfos : Array (Name \u00d7 (Array Expr \u2192 n Expr)))\n    (k : (xs : Array Expr) \u2192 n \u03b1)\n    : n \u03b1 :=\n  withLocalDecls\n    (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k\n\nprivate def withNewBinderInfosImp (bs : Array (FVarId \u00d7 BinderInfo)) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let lctx := bs.foldl (init := (\u2190 getLCtx)) fun lctx (fvarId, bi) =>\n      lctx.setBinderInfo fvarId bi\n  withReader (fun ctx => { ctx with lctx := lctx }) k\n\ndef withNewBinderInfos (bs : Array (FVarId \u00d7 BinderInfo)) (k : n \u03b1) : n \u03b1 :=\n  mapMetaM (fun k => withNewBinderInfosImp bs k) k\n\nprivate def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLetDecl fvarId n type val\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar fvar type k\n\ndef withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  map1MetaM (fun k => withLetDeclImp name type val k) k\n\nprivate def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let ctx \u2190 read\n  let numLocalInstances := ctx.localInstances.size\n  let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    let newLocalInsts \u2190 decls.foldlM\n      (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {\n        match (\u2190 isClass? decl.type) with\n        | none   => pure newlocalInsts\n        | some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))\n      ctx.localInstances;\n    if newLocalInsts.size == numLocalInstances then\n      k\n    else\n      resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k\n\ndef withExistingLocalDecls (decls : List LocalDecl) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withExistingLocalDeclsImp decls\n\nprivate def withNewMCtxDepthImp (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let saved \u2190 get\n  modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} }\n  try\n    x\n  finally\n    modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }\n\n/--\n  Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,\n  and restore saved data. -/\ndef withNewMCtxDepth : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM withNewMCtxDepthImp\n\nprivate def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let localInstsCurr \u2190 getLocalInstances\n  withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do\n    if localInsts == localInstsCurr then\n      x\n    else\n      resettingSynthInstanceCache x\n\ndef withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withLocalContextImp lctx localInsts\n\nprivate def withMVarContextImp (mvarId : MVarId) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x\n\n/--\n  Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.\n  The type class resolution cache is flushed when executing `x` if its `LocalInstances` are\n  different from the current ones. -/\ndef withMVarContext (mvarId : MVarId) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMVarContextImp mvarId\n\nprivate def withMCtxImp (mctx : MetavarContext) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mctx' \u2190 getMCtx\n  setMCtx mctx\n  try x finally setMCtx mctx'\n\ndef withMCtx (mctx : MetavarContext) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMCtxImp mctx\n\n@[inline] private def approxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x\n\n/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`.  -/\n@[inline] def approxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM approxDefEqImp\n\n@[inline] private def fullApproxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x\n\n/--\n  Similar to `approxDefEq`, but uses all available approximations.\n  We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.\n  For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.\n  Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved\n  as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to\n  solve `[Pure (fun _ => IO Bool)]` -/\n@[inline] def fullApproxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM fullApproxDefEqImp\n\ndef normalizeLevel (u : Level) : MetaM Level := do\n  let u \u2190 instantiateLevelMVars u\n  pure u.normalize\n\ndef assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.assignLevel mvarId u\n\ndef whnfR (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.reducible <| whnf e\n\ndef whnfD (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.default <| whnf e\n\ndef whnfI (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.instances <| whnf e\n\ndef setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do\n  let env \u2190 getEnv\n  match Compiler.setInlineAttribute env declName kind with\n  | Except.ok env    => setEnv env\n  | Except.error msg => throwError msg\n\nprivate partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    let e \u2190 whnf e\n    match e with\n    | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)\n    | _                    => throwError \"invalid instantiateForall, too many parameters\"\n  else\n    pure e\n\n/- Given `e` 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`, return `B[p_1, ..., p_n]`. -/\ndef instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateForallAux ps 0 e\n\nprivate partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    let e \u2190 whnf e\n    match e with\n    | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)\n    | _                => throwError \"invalid instantiateLambda, too many parameters\"\n  else\n    pure e\n\n/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.\n   It uses `whnf` to reduce `e` if it is not a lambda -/\ndef instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateLambdaAux ps 0 e\n\n/-- Return true iff `e` depends on the free variable `fvarId` -/\ndef dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).exprDependsOn e fvarId\n\ndef ppExpr (e : Expr) : MetaM Format := do\n  let env  \u2190 getEnv\n  let mctx \u2190 getMCtx\n  let lctx \u2190 getLCtx\n  let opts \u2190 getOptions\n  let ctxCore  \u2190 readThe Core.Context\n  Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls  } e\n\n@[inline] protected def orelse (x y : MetaM \u03b1) : MetaM \u03b1 := do\n  let env  \u2190 getEnv\n  let mctx \u2190 getMCtx\n  try x catch _ => setEnv env; setMCtx mctx; y\n\ninstance : OrElse (MetaM \u03b1) := \u27e8Meta.orelse\u27e9\n\n@[inline] private def orelseMergeErrorsImp (x y : MetaM \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 r\u2082 => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ m\u2082) : MetaM \u03b1 := do\n  let env  \u2190 getEnv\n  let mctx \u2190 getMCtx\n  try\n    x\n  catch ex =>\n    setEnv env\n    setMCtx mctx\n    match ex with\n    | Exception.error ref\u2081 m\u2081 =>\n      try\n        y\n      catch\n        | Exception.error ref\u2082 m\u2082 => throw <| Exception.error (mergeRef ref\u2081 ref\u2082) (mergeMsg m\u2081 m\u2082)\n        | ex => throw ex\n    | ex => throw ex\n\n/--\n  Similar to `orelse`, but merge errors. Note that internal errors are not caught.\n  The default `mergeRef` uses the `ref` (position information) for the first message.\n  The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/\n@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 r\u2082 => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ Format.line ++ m\u2082) : m \u03b1 := do\n  controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg\n\n/-- Execute `x`, and apply `f` to the produced error message -/\ndef mapErrorImp (x : MetaM \u03b1) (f : MessageData \u2192 MessageData) : MetaM \u03b1 := do\n  try\n    x\n  catch\n    | Exception.error ref msg => throw <| Exception.error ref <| f msg\n    | ex => throw ex\n\n@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m \u03b1) (f : MessageData \u2192 MessageData) : m \u03b1 :=\n  controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f\n\nend Methods\nend Meta\n\nexport Meta (MetaM)\n\nend Lean\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/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491213037224875, "lm_q2_score": 0.035144843621678024, "lm_q1q2_score": 0.013527676630019626}}
{"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 \u2208 (@AssertionLang.sem LANG PORTS _ _ _ A) \u2194 x \u2208 LANG.sem A := by {refl,}\n\ntheorem fsadfdsa (x : Trace PORTS) (A B : LANG) : x \u2208 LANG.sem (A & B).always \u2194 x \u2208 LANG.sem (A).always \u2227 x \u2208 LANG.sem (B).always := \nbegin\nsimp, rw forall_and_distrib, \nend \n\ntheorem disj_comm_guarded (x : Trace PORTS) (A B : LANG) : x \u2208 LANG.sem (A OR B).always \u2194 x \u2208 LANG.sem (B OR A).always := \nbegin\nsimp,\nend \ntheorem conj_comm_guarded (x : Trace PORTS) (A B : LANG) : x \u2208 LANG.sem (A & B).always \u2194 x \u2208 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 \u2208 LANG.sem (A & B) \u2194 x \u2208 LANG.sem A \u2227 x \u2208 LANG.sem B := \nbegin\nrw conj_def, simp, \nend \n\ntheorem foobars {x : Trace PORTS} (A B C D : LANG) : \n                            x \u2208 LANG.sem ((A & B & C).always & D.always) \n              \u2194  \n                            x \u2208 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 \u2208 @AssertionLang.sem LANG PORTS _ _ _ (A & B).always) \u2192 x \u2208 (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 \u2208 @AssertionLang.sem LANG PORTS _ _ _ (A & B).always) \u2192 x \u2208 (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 \u00d7 expr)) \n(comps : list expr)\n\n\nmeta def preprocess_rpo_fst : tactic (name \u00d7 name) := do \n  x \u2190 tactic.get_unused_name `x,\n  H \u2190 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 \u27e8x, H\u27e9\n\n\nmeta def decompose_conj : expr \u2192  expr \u2192 tactic (unit)\n| h `(and %%left %%right) := do \n    left_nm \u2190 get_unused_name,\n    right_nm \u2190 get_unused_name,\n    cases_core h [left_nm, right_nm] transparency.semireducible,\n    right_e \u2190 get_local right_nm,\n    decompose_conj right_e right\n| _ _ := do return ()\n\nmeta def decompose_conj_left : expr \u2192  expr \u2192 tactic (unit)\n| h `(and %%left %%right) := do \n    left_nm \u2190 get_unused_name,\n    right_nm \u2190 get_unused_name,\n    cases_core h [left_nm, right_nm] transparency.semireducible,\n    left_e \u2190 get_local left_nm,\n    decompose_conj left_e left\n| _ _ := do return ()\n\n\n\n\nmeta def collect_assertions : list expr \u2192 tactic (list expr) \n| (h::t ) := do \n  \u03c4 \u2190 infer_type h,\n  match \u03c4 with \n  | `(_ \u2208 _) := do \n                l \u2190 collect_assertions t,\n                return $ [h]++l\n  | `(_ \u2208 _ \u2192 _) := do \n                l \u2190 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) : \u2200 {\u03b1 : Type} {t e  :\u03b1}, c \u2192 ite c t e = t := by {intros a b c h, apply if_pos h,}\ntheorem  IFf_neg  : \u03a0 (c : Prop) [H : decidable c], \u2200 {\u03b1 : Type} {t e  :\u03b1}, \u00acc \u2192 (@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 \u2192 tactic (list expr)\n| `(@ite %%A %%B %%C %%D %%E) := do \n        let cond := [B],\n        r \u2190 get_conds_aux E,\n        return $ cond ++ r\n| _ := return []\n\n\n\nmeta def get_conds : expr \u2192 tactic (list expr)\n| `(%%x \u2208 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| `(_ \u2192 %%x \u2208 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 \u2192 tactic (list (list expr))\n| (h::t) := do \n    -- tactic.trace \"here\",\n    -- \u03c4 \u2190 infer_type h,\n    -- tactic.trace \u03c4,\n    l\u2190 get_conds h, t \u2190 GFSAUIHasd t, return (l::t)\n| _ := do return []\n\n\nmeta def aiuhsfd : list expr \u2192 list (expr \u00d7 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 \u00d7 bool) \u2192 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 \u00d7 list (expr \u00d7 bool)) \u2192 tactic unit\n| [] := return ()\n| ((e, l)::xs) := do a \u2190 sjdioaf e l,\n                  suihfa xs\n\nmeta def extract_contracts : expr \u2192  tactic unit := \u03bb h, do \n  infer_type h >>= decompose_conj h, dedup,\n  tactic.repeat `[rw Map.find_val at *],\n  xs \u2190 local_context >>= collect_assertions,\n  l \u2190 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 \u00d7 expr) \u2192 (list (expr \u00d7 expr)) \n| []   := []\n| ((h, \u03c4)::t) := match \u03c4 with \n                | `(%%P \u2192 %%Q) := (collect_consequents t).cons (h,Q) \n                | _ := collect_consequents t\n                end \n\nmeta def collect_vars_aux : expr \u2192 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 \u2192 list expr \n| `(_ \u2208 AssertionLang.sem %%P) := collect_vars_aux P \n| _ := []\n\nmeta def find_matches_aux : expr \u2192 list (expr \u00d7 expr) \u2192 list (expr \u00d7 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 \u00d7 expr))  : list expr \u2192 list (expr \u00d7 expr) \n| [] := []\n| (h::t) := find_matches_aux h del++(find_matches t )\n-- find_matches_aux es del \n\n\nopen tactic.interactive (\u00abhave\u00bb)\n\nmeta def mk_sync_apply (x : expr) : (expr \u00d7 expr) \u2192  tactic unit \n| (a,b) := do \n -- ((synchronize' x fault_PWMFlow_LACU fault_armFlow_armController) (atom fault_PWMFlow_LACU).neg.always).mpr\n `(_ \u2208 AssertionLang.sem %%FOO) \u2190 target,\n let e := expr.mk_app `(synchronize') [x, b, a, FOO],\n--  tactic.trace e,\n \u03c4 \u2190 infer_type e,\n match \u03c4 with \n | `(%%GOAL \u2192 %%FOO) := do \n   h \u2190 get_unused_name `h,\n   \u00abhave\u00bb h ``(%%GOAL) ``(by dec_trivial),\n   h_e \u2190 get_local h,\n   let e' := expr.mk_app e [h_e],\n    \u03c4 \u2190 infer_type e',\n   match \u03c4  with \n   | `(%%l \u2194 %%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 \u2192 tactic unit \n| [] := return ()\n| (h::t) :=  (do apply h, return ()) <|> try_application t\n\n\nmeta def synchronize_ports (x : name) (\u0393 : model_info): tactic unit := do \n  tgt \u2190 target, \n  let cs := collect_vars tgt,\n  let ls := find_matches \u0393.del cs, -- vars to sub will be on LEFT\n  x \u2190 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 \u2190 get_unused_name `A,\n  intro A,\n  A_e \u2190 get_local A, x \u2190 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 \u2190 get_local A,tactic.rewrite_hyp e' A_e, return ()),\n  A_e \u2190 get_local A,\n  tactic.repeat (do A_e \u2190 get_local A, cases_core A_e [A] transparency.semireducible, return ()),\n  return ()\n\nmeta def try_rewrites : expr \u2192 tactic unit  \n| `(_ \u2208 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 \u2192 tactic unit \n| (h::t) := match h with \n            | `(_ \u2192 (_ \u2208 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 \u2192 tactic unit \n| (h::t) := match h with \n            | `(_ \u2192 _ \u2192 (_ \u2208 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`(_ \u2208 LANG.sem (LANG.always %%FOO)) \u2190 target,\nlocal_context >>= (list.mmap infer_type) >>= check_for_portation_aux FOO\n\nmeta def check_for_portation' : tactic unit := do \n`(_ \u2208 LANG.sem (LANG.always %%FOO)) \u2190 target,\nlocal_context >>= (list.mmap infer_type) >>= check_for_portation_aux' FOO\n\nmeta def find_assumption : list expr \u2192 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) (\u0393 : model_info) : tactic unit := do \ncheck_for_portation,\nlocal_context >>= try_application,\nsynchronize_ports x \u0393, \ntarget >>= try_rewrites,\nb \u2190 local_context >>= find_assumption,\nif !b then try_terminal_rws else return ()\n\nmeta def solve_rpo_fst_new (\u0393 : model_info) : tactic unit := do \n  \u27e8x, H\u27e9 \u2190 preprocess_rpo_fst,\n  get_local H >>= extract_contracts,\n  decompose_env_assumptions x,\n  synchronize_ports x \u0393,\n  local_context >>= try_application,\n  synchronize_ports x \u0393,\n  target >>= try_rewrites,\n  repeat `[split],\n  all_goals $ core_rpo_loop x \u0393,\n  try (`[repeat {split}, repeat {assumption}]), -- can fix.\n  return ()\n\nmeta def make_cases (H : name) : tactic unit := do \n  H_e \u2190 get_local H,\n  \u03c4 \u2190 infer_type H_e,\n  match \u03c4 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 (\u0393 : model_info) : list expr \u2192 tactic expr \n| [] := return default \n| (h::t) := do \n            \u03c4 \u2190 infer_type h,\n            match \u03c4 with \n            | `(_ = %%FOO) := \n                  if FOO \u2208 \u0393.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 \u2190 get_unused_name,\n  let e : expr := (expr.mk_app H [comp]),\n  \u03c4 \u2190 infer_type e,\n  tactic.local_proof h (\u03c4) (tactic.exact e),\n  return ()\n\nmeta def get_other_comp_contracts (\u0393 : model_info) (H2 : expr) : tactic expr := do \n  e \u2190 local_context >>= find_this_component \u0393,\n  let l := \u0393.comps.erase e,\n  l.mmap (get_comp_contract H2),\n  return e\n\nmeta def rewrite_this_comp  (comp : expr ) : list expr \u2192 tactic unit \n| (h::t) := do \n          \u03c4 \u2190 infer_type h,\n          match \u03c4 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 (\u0393 : model_info) : tactic unit := do \n  Ha \u2190 tactic.get_unused_name `Ha,\n  `[rw AssertionLang.impl_def], \n  tactic.intro Ha, \n  `[rw AssertionLang.conj_def at *],\n  H_e \u2190 get_local Ha, \n  H1 \u2190 get_unused_name `H1,\n  H2 \u2190 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\u2082] at *],  \n   this_comp \u2190 get_local H2 >>= get_other_comp_contracts \u0393,\n   local_context >>= rewrite_this_comp this_comp,\n   H1_e \u2190 get_local H1,\n   tactic.rewrite_hyp `(asdff) H1_e,\n   repeat `[rw fsadfdsa at *],\n  tactic.iterate (do H1_e \u2190 get_local H1, cases_core H1_e [H1] transparency.semireducible),\n  return ()\n\nmeta def clear_goal_rewrites_aux : expr \u2192 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 \u2190 target,\n match tgt with \n | `(_ \u2208 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 \u2190 local_context >>= collect_assertions,\n  l \u2190 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 \u2190 asdff, repeat {split}]),\n  return ()\n\nmeta def check_for_semantic_unfolding : expr \u2192 tactic unit \n| `(_ \u2208 AssertionLang.sem _) := do return ()\n| _ := do try `[rw \u2190 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 \u2190 asdff], assumption,\n return ()\n\nmeta def new_tac_finisher (x : name) (\u0393 : model_info) : tactic unit := do \n  synchronize_ports x \u0393,\n  `[rw asdff],\n  try_terminal_rws,\n  -- finish_conjunctions,\n  -- `[rw fsadfdsa],\n    -- split, -- copied from above\n    -- assumption,rw \u2190 asdff,assumption],\n  return ()\n\nmeta def solve_rpo_snd_new (\u0393 : model_info) : tactic unit := do \n  S \u2190 tactic.get_unused_name `S,\n  H \u2190 tactic.get_unused_name `H,\n  x \u2190 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 \u0393,\n  all_goals $ rpo_snd_core, \n  all_goals $ try $ `[rw \u2190 asdff],\n  all_goals (do x_e \u2190 get_local x,synchronize_ports x \u0393),\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 \u0393,\n  all_goals $ (do `[rw fsadfdsa, split], assumption <|> `[rw \u2190 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 `{ <missing> }`,\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 `\u2200 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 [\u2190 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 `\u22a2 lhs` into a regular goal `\u22a2 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\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses\n  with inaccessible names to the given names.\n* `case tag\u2081 | tag\u2082 => tac` is equivalent to `(case tag\u2081 => tac); (case tag\u2082 => 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\u2081 ... x\u2099 => 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 `\u00b7 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/-- `\u00b7 conv` focuses on the main conv goal and tries to solve it using `s`. -/\nmacro dot:patternIgnore(\"\u00b7\" <|> \".\") 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 <https://leanprover.github.io/theorem_proving_in_lean4/conv.html> 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": "/-\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.Parser.Term\nimport Lean.Meta.Closure\nimport Lean.Meta.Check\nimport Lean.Elab.Command\nimport Lean.Elab.Match\nimport Lean.Elab.DefView\nimport Lean.Elab.PreDefinition\nimport Lean.Elab.DeclarationRange\n\nnamespace Lean.Elab\nopen Lean.Parser.Term\n\n/- DefView after elaborating the header. -/\nstructure DefViewElabHeader where\n  ref           : Syntax\n  modifiers     : Modifiers\n  kind          : DefKind\n  shortDeclName : Name\n  declName      : Name\n  levelNames    : List Name\n  binderIds     : Array Syntax\n  numParams     : Nat\n  type          : Expr -- including the parameters\n  valueStx      : Syntax\n  deriving Inhabited\n\nnamespace Term\nopen Meta\n\nprivate def checkModifiers (m\u2081 m\u2082 : Modifiers) : TermElabM Unit := do\n  unless m\u2081.isUnsafe == m\u2082.isUnsafe do\n    throwError \"cannot mix unsafe and safe definitions\"\n  unless m\u2081.isNoncomputable == m\u2082.isNoncomputable do\n    throwError \"cannot mix computable and non-computable definitions\"\n  unless m\u2081.isPartial == m\u2082.isPartial do\n    throwError \"cannot mix partial and non-partial definitions\"\n\nprivate def checkKinds (k\u2081 k\u2082 : DefKind) : TermElabM Unit := do\n  unless k\u2081.isExample == k\u2082.isExample do\n    throwError \"cannot mix examples and definitions\" -- Reason: we should discard examples\n  unless k\u2081.isTheorem == k\u2082.isTheorem do\n    throwError \"cannot mix theorems and definitions\" -- Reason: we will eventually elaborate theorems in `Task`s.\n\nprivate def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do\n  if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then\n    throwError \"'unsafe' theorems are not allowed\"\n  if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then\n    throwError \"'partial' theorems are not allowed, 'partial' is a code generation directive\"\n  if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then\n    throwError \"'theorem' subsumes 'noncomputable', code is not generated for theorems\"\n  if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then\n    throwError \"'noncomputable unsafe' is not allowed\"\n  if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then\n    throwError \"'noncomputable partial' is not allowed\"\n  if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then\n    throwError \"'unsafe' subsumes 'partial'\"\n  if h : 0 < prevHeaders.size then\n    let firstHeader := prevHeaders.get \u27e80, h\u27e9\n    try\n      unless newHeader.levelNames == firstHeader.levelNames do\n        throwError \"universe parameters mismatch\"\n      checkModifiers newHeader.modifiers firstHeader.modifiers\n      checkKinds newHeader.kind firstHeader.kind\n    catch\n       | Exception.error ref msg => throw (Exception.error ref m!\"invalid mutually recursive definitions, {msg}\")\n       | ex => throw ex\n  else\n    pure ()\n\nprivate def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit :=\n  registerCustomErrorIfMVar type ref \"failed to infer definition type\"\n\n/--\n  Return `some [b, c]` if the given `views` are representing a declaration of the form\n  ```\n  constant a b c : Nat\n  ```  -/\nprivate def isMultiConstant? (views : Array DefView) : Option (List Name) :=\n  if views.size == 1 &&\n     views[0].kind == DefKind.opaque &&\n     views[0].binders.getArgs.size > 0 &&\n     views[0].binders.getArgs.all (\u00b7.getKind == ``Parser.Term.simpleBinder) then\n    some <| (views[0].binders.getArgs.toList.map (fun stx => stx[0].getArgs.toList.map (\u00b7.getId))).join\n  else\n    none\n\nprivate def getPendindMVarErrorMessage (views : Array DefView) : String :=\n  match isMultiConstant? views with\n  | some ids =>\n    let idsStr := \", \".intercalate <| ids.map fun id => s!\"`{id}`\"\n    let paramsStr := \", \".intercalate <| ids.map fun id => s!\"`({id} : _)`\"\n    s!\"\\nrecall that you cannot declare multiple constants in a single declaration. The identifier(s) {idsStr} are being interpreted as parameters {paramsStr}\"\n  | none =>\n    \"\\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed\"\n\nprivate def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do\n  let mut headers := #[]\n  for view in views do\n    let newHeader \u2190 withRef view.ref do\n      let \u27e8shortDeclName, declName, levelNames\u27e9 \u2190 Term.expandDeclId (\u2190 getCurrNamespace) (\u2190 getLevelNames) view.declId view.modifiers\n      addDeclarationRanges declName view.ref\n      applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration\n      withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <|\n        elabBindersEx view.binders.getArgs fun xs => do\n          let refForElabFunType := view.value\n          let type \u2190 match view.type? with\n            | some typeStx =>\n              let type \u2190 elabType typeStx\n              registerFailedToInferDefTypeInfo type typeStx\n              pure type\n            | none =>\n              let hole := mkHole refForElabFunType\n              let type \u2190 elabType hole\n              registerFailedToInferDefTypeInfo type refForElabFunType\n              pure type\n          Term.synthesizeSyntheticMVarsNoPostponing\n          let (binderIds, xs) := xs.unzip\n          let type \u2190 mkForallFVars xs type\n          let type \u2190 mkForallFVars (\u2190 read).autoBoundImplicits.toArray type\n          let type \u2190 instantiateMVars type\n          let xs \u2190 addAutoBoundImplicits xs\n          let levelNames \u2190 getLevelNames\n          if view.type?.isSome then\n            let pendingMVarIds \u2190 getMVars type\n            discard <| logUnassignedUsingErrorInfos pendingMVarIds <|\n              getPendindMVarErrorMessage views\n          let newHeader := {\n            ref           := view.ref,\n            modifiers     := view.modifiers,\n            kind          := view.kind,\n            shortDeclName := shortDeclName,\n            declName      := declName,\n            levelNames    := levelNames,\n            binderIds     := binderIds,\n            numParams     := xs.size,\n            type          := type,\n            valueStx      := view.value : DefViewElabHeader }\n          check headers newHeader\n          pure newHeader\n    headers := headers.push newHeader\n  pure headers\n\nprivate partial def withFunLocalDecls {\u03b1} (headers : Array DefViewElabHeader) (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (fvars : Array Expr) := do\n    if h : i < headers.size then\n      let header := headers.get \u27e8i, h\u27e9\n      if header.modifiers.isNonrec then\n        loop (i+1) fvars\n      else\n        withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar)\n    else\n      k fvars\n  loop 0 #[]\n\nprivate def expandWhereStructInst : Macro\n  | `(Parser.Command.whereStructInst|where $[$decls:letDecl$[;]?]*) => do\n    let letIdDecls \u2190 decls.mapM fun stx => match stx with\n      | `(letDecl|$decl:letPatDecl)  => Macro.throwErrorAt stx \"patterns are not allowed here\"\n      | `(letDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl\n      | `(letDecl|$decl:letIdDecl)   => pure decl\n      | _                               => Macro.throwUnsupported\n    let structInstFields \u2190 letIdDecls.mapM fun\n      | stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do\n        let mut val := val\n        if let some ty := ty? then\n          val \u2190 `(($val : $ty))\n        val \u2190 if binders.size > 0 then `(fun $[$binders]* => $val:term) else pure val\n        `(structInstField|$id:ident := $val)\n      | _ => Macro.throwUnsupported\n    `({ $[$structInstFields,]* })\n  | _ => Macro.throwUnsupported\n\n/-\nRecall that\n```\ndef declValSimple    := leading_parser \" :=\\n\" >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef declVal          := declValSimple <|> declValEqns <|> Term.whereDecls\n```\n-/\nprivate def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do\n  if declVal.isOfKind ``Lean.Parser.Command.declValSimple then\n    expandWhereDeclsOpt declVal[2] declVal[1]\n  else if declVal.isOfKind ``Lean.Parser.Command.declValEqns then\n    expandMatchAltsWhereDecls declVal[0]\n  else if declVal.isOfKind ``Lean.Parser.Command.whereStructInst then\n    expandWhereStructInst declVal\n  else if declVal.isMissing then\n    Macro.throwErrorAt declVal \"declaration body is missing\"\n  else\n    Macro.throwErrorAt declVal \"unexpected declaration body\"\n\nprivate def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) :=\n  headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do\n    let valStx \u2190 liftMacroM $ declValToTerm header.valueStx\n    forallBoundedTelescope header.type header.numParams fun xs type => do\n      -- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location.\n      for i in [0:header.binderIds.size] do\n        -- skip auto-bound prefix in `xs`\n        addTermInfo (isBinder := true) header.binderIds[i] xs[header.numParams - header.binderIds.size + i]\n      let val \u2190 elabTermEnsuringType valStx type\n      mkLambdaFVars xs val\n\nprivate def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    : StateRefT CollectFVars.State MetaM Unit := do\n  headers.forM fun header => collectUsedFVars header.type\n  values.forM collectUsedFVars\n  toLift.forM fun letRecToLift => do\n    collectUsedFVars letRecToLift.type\n    collectUsedFVars letRecToLift.val\n\nprivate def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed headers values toLift).run {}\n  removeUnused vars used\n\nprivate def withUsed {\u03b1} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnusedVars vars headers values toLift\n  withLCtx lctx localInsts $ k vars\n\nprivate def isExample (views : Array DefView) : Bool :=\n  views.any (\u00b7.kind.isExample)\n\nprivate def isTheorem (views : Array DefView) : Bool :=\n  views.any (\u00b7.kind.isTheorem)\n\nprivate def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do\n  let type \u2190 instantiateMVars header.type\n  pure { header with type := type }\n\nprivate def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do\n  let type \u2190 instantiateMVars toLift.type\n  let val \u2190 instantiateMVars toLift.val\n  pure { toLift with type := type, val := val }\n\nprivate def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId :=\n  let occ? := type.find? fun e => match e with\n    | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId\n    | _ => false\n  match occ? with\n  | some (Expr.fvar fvarId _) => some fvarId\n  | _ => none\n\nprivate def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do\n  match (\u2190 findLocalDecl? fvarId) with\n  | some decl => pure decl.userName\n  | none =>\n    /- Recall that the FVarId of nested let-recs are not in the current local context. -/\n    match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with\n    | none   => throwError \"unknown function\"\n    | some n => pure n\n\n/-\nEnsures that the of let-rec definition types do not contain functions being defined.\nIn principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components.\nHowever, this extra complication doesn't seem worth it.\n-/\nprivate def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit :=\n  letRecsToLift.forM fun toLift =>\n    match typeHasRecFun toLift.type funVars letRecsToLift with\n    | none        => pure ()\n    | some fvarId => do\n      let fnName \u2190 getFunName fvarId letRecsToLift\n      throwErrorAt toLift.ref \"invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously\"\n\nnamespace MutualClosure\n\n/- A mapping from FVarId to Set of FVarIds. -/\nabbrev UsedFVarsMap := FVarIdMap FVarIdSet\n\n/-\nCreate the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of\nfree variables in its definition.\n\nFor `mainFVars`, this is just the set of section variables `sectionVars` used.\nFor nested let-rec functions, we collect their free variables.\n\nRecall that a `let rec` expressions are encoded as follows in the elaborator.\n```lean\nlet rec\n  f : A := t,\n  g : B := s;\nbody\n```\nis encoded as\n```lean\nlet f : A := ?m\u2081;\nlet g : B := ?m\u2082;\nbody\n```\nwhere `?m\u2081` and `?m\u2082` are synthetic opaque metavariables. That are assigned by this module.\nWe may have nested `let rec`s.\n```lean\nlet rec f : A :=\n    let rec g : B := t;\n    s;\nbody\n```\nis encoded as\n```lean\nlet f : A := ?m\u2081;\nbody\n```\nand the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above,\nwe would have a `LetRecToLift` containing:\n```\n{\n  mvarId := m\u2081,\n  val    := `(let g : B := ?m\u2082; body)\n  ...\n}\n```\nNote that `g` is not a free variable at `(let g : B := ?m\u2082; body)`. We recover the fact that\n`f` depends on `g` because it contains `m\u2082`\n-/\nprivate def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift)\n    : UsedFVarsMap := Id.run <| do\n  let mut sectionVarSet := {}\n  for var in sectionVars do\n    sectionVarSet := sectionVarSet.insert var.fvarId!\n  let mut usedFVarMap := {}\n  for mainFVarId in mainFVarIds do\n    usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet\n  for toLift in letRecsToLift do\n    let state := Lean.collectFVars {} toLift.val\n    let state := Lean.collectFVars state toLift.type\n    let mut set := state.fvarSet\n    /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId\n       for the associated let-rec because we need this information to compute the fixpoint later. -/\n    let mvarIds := (toLift.val.collectMVars {}).result\n    for mvarId in mvarIds do\n      match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with\n      | some fvarId => set := set.insert fvarId\n      | none        => pure ()\n    usedFVarMap := usedFVarMap.insert toLift.fvarId set\n  pure usedFVarMap\n\n/-\nThe let-recs may invoke each other. Example:\n```\nlet rec\n  f (x : Nat) := g x + y\n  g : Nat \u2192 Nat\n    | 0   => 1\n    | x+1 => f x + z\n```\n`y` is free variable in `f`, and `z` is a free variable in `g`.\nTo close `f` and `g`, `y` and `z` must be in the closure of both.\nThat is, we need to generate the top-level definitions.\n```\ndef f (y z x : Nat) := g y z x + y\ndef g (y z : Nat) : Nat \u2192 Nat\n  | 0 => 1\n  | x+1 => f y z x + z\n```\n-/\nnamespace FixPoint\n\nstructure State where\n  usedFVarsMap : UsedFVarsMap := {}\n  modified     : Bool         := false\n\nabbrev M := ReaderT (List FVarId) $ StateM State\n\nprivate def isModified : M Bool := do pure (\u2190 get).modified\nprivate def resetModified : M Unit := modify fun s => { s with modified := false }\nprivate def markModified : M Unit := modify fun s => { s with modified := true }\nprivate def getUsedFVarsMap : M UsedFVarsMap := do pure (\u2190 get).usedFVarsMap\nprivate def modifyUsedFVars (f : UsedFVarsMap \u2192 UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap }\n\n-- merge s\u2082 into s\u2081\nprivate def merge (s\u2081 s\u2082 : FVarIdSet) : M FVarIdSet :=\n  s\u2082.foldM (init := s\u2081) fun s\u2081 k => do\n    if s\u2081.contains k then\n      pure s\u2081\n    else\n      markModified\n      pure $ s\u2081.insert k\n\nprivate def updateUsedVarsOf (fvarId : FVarId) : M Unit := do\n  let usedFVarsMap \u2190 getUsedFVarsMap\n  match usedFVarsMap.find? fvarId with\n  | none         => pure ()\n  | some fvarIds =>\n    let fvarIdsNew \u2190 fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' =>\n      if fvarId == fvarId' then\n        pure fvarIdsNew\n      else\n        match usedFVarsMap.find? fvarId' with\n        | none => pure fvarIdsNew\n          /- We are being sloppy here `otherFVarIds` may contain free variables that are\n             not in the context of the let-rec associated with fvarId.\n             We filter these out-of-context free variables later. -/\n        | some otherFVarIds => merge fvarIdsNew otherFVarIds\n    modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew\n\nprivate partial def fixpoint : Unit \u2192 M Unit\n  | _ => do\n    resetModified\n    let letRecFVarIds \u2190 read\n    letRecFVarIds.forM updateUsedVarsOf\n    if (\u2190 isModified) then\n      fixpoint ()\n\ndef run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap :=\n  let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap }\n  s.usedFVarsMap\n\nend FixPoint\n\nabbrev FreeVarMap := FVarIdMap (Array FVarId)\n\nprivate def mkFreeVarMap\n    (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId)\n    (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := Id.run <| do\n  let usedFVarsMap  := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift\n  let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId\n  let usedFVarsMap  := FixPoint.run letRecFVarIds usedFVarsMap\n  let mut freeVarMap := {}\n  for toLift in letRecsToLift do\n    let lctx       := toLift.lctx\n    let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get!\n    let fvarIds    := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId =>\n      if lctx.contains fvarId && !recFVarIds.contains fvarId then\n        fvarIds.push fvarId\n      else\n        fvarIds\n    freeVarMap := freeVarMap.insert toLift.fvarId fvarIds\n  pure freeVarMap\n\nstructure ClosureState where\n  newLocalDecls : Array LocalDecl := #[]\n  localDecls    : Array LocalDecl := #[]\n  newLetDecls   : Array LocalDecl := #[]\n  exprArgs      : Array Expr      := #[]\n\nprivate def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId :=\n  fvarIds.getMax? fun fvarId\u2081 fvarId\u2082 => (lctx.get! fvarId\u2081).index < (lctx.get! fvarId\u2082).index\n\nprivate def preprocess (e : Expr) : TermElabM Expr := do\n  let e \u2190 instantiateMVars e\n  -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.\n  Meta.check e\n  pure e\n\n/- Push free variables in `s` to `toProcess` if they are not already there. -/\nprivate def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId :=\n  s.fvarSet.fold (init := toProcess) fun toProcess fvarId =>\n    if toProcess.contains fvarId then toProcess else toProcess.push fvarId\n\nprivate def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default)\n    : StateRefT ClosureState TermElabM (Array FVarId) := do\n  let type \u2190 preprocess type\n  modify fun s => { s with\n    newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl default fvarId userName type bi,\n    exprArgs      := s.exprArgs.push (mkFVar fvarId)\n  }\n  pure $ pushNewVars toProcess (collectFVars {} type)\n\nprivate partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do\n  let lctx \u2190 getLCtx\n  match pickMaxFVar? lctx toProcess with\n  | none        => pure ()\n  | some fvarId =>\n    trace[Elab.definition.mkClosure] \"toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}\"\n    let toProcess := toProcess.erase fvarId\n    let localDecl \u2190 getLocalDecl fvarId\n    match localDecl with\n    | LocalDecl.cdecl _ _ userName type bi =>\n      let toProcess \u2190 pushLocalDecl toProcess fvarId userName type bi\n      mkClosureForAux toProcess\n    | LocalDecl.ldecl _ _ userName type val _ =>\n      let zetaFVarIds \u2190 getZetaFVarIds\n      if !zetaFVarIds.contains fvarId then\n        /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/\n        let toProcess \u2190 pushLocalDecl toProcess fvarId userName type\n        mkClosureForAux toProcess\n      else\n        /- Dependent let-decl. -/\n        let type \u2190 preprocess type\n        let val  \u2190 preprocess val\n        modify fun s => { s with\n          newLetDecls   := s.newLetDecls.push $ LocalDecl.ldecl default fvarId userName type val false,\n          /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId\n             at `newLocalDecls` and `localDecls` -/\n          newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val),\n          localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val)\n        }\n        mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val))\n\nprivate partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do\n  let (_, s) \u2190 (mkClosureForAux freeVars).run { localDecls := localDecls }\n  pure { s with\n    newLocalDecls := s.newLocalDecls.reverse,\n    newLetDecls   := s.newLetDecls.reverse,\n    exprArgs      := s.exprArgs.reverse\n  }\n\nstructure LetRecClosure where\n  ref        : Syntax\n  localDecls : Array LocalDecl\n  closed     : Expr -- expression used to replace occurrences of the let-rec FVarId\n  toLift     : LetRecToLift\n\nprivate def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do\n  let lctx := toLift.lctx\n  withLCtx lctx toLift.localInstances do\n  lambdaTelescope toLift.val fun xs val => do\n    let type \u2190 instantiateForall toLift.type xs\n    let lctx \u2190 getLCtx\n    let s \u2190 mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId!\n    let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type\n    let val  := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val\n    let c    := mkAppN (Lean.mkConst toLift.declName) s.exprArgs\n    assignExprMVar toLift.mvarId c\n    return {\n      ref        := toLift.ref\n      localDecls := s.newLocalDecls\n      closed     := c\n      toLift     := { toLift with val := val, type := type }\n    }\n\nprivate def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) :=\n  letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get!\n\n/- Mapping from FVarId of mutually recursive functions being defined to \"closure\" expression. -/\nabbrev Replacement := FVarIdMap Expr\n\ndef insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement :=\n  mainFVars.size.fold (init := r) fun i r =>\n    r.insert mainFVars[i].fvarId! (mkAppN (Lean.mkConst mainHeaders[i].declName) sectionVars)\n\n\ndef insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement :=\n  letRecClosures.foldl (init := r) fun r c =>\n    r.insert c.toLift.fvarId c.closed\n\ndef Replacement.apply (r : Replacement) (e : Expr) : Expr :=\n  e.replace fun e => match e with\n    | Expr.fvar fvarId _ => match r.find? fvarId with\n      | some c => some c\n      | _      => none\n    | _ => none\n\ndef pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr)\n    : TermElabM (Array PreDefinition) :=\n  mainHeaders.size.foldM (init := preDefs) fun i preDefs => do\n    let header := mainHeaders[i]\n    let val  \u2190 mkLambdaFVars sectionVars mainVals[i]\n    let type \u2190 mkForallFVars sectionVars header.type\n    return preDefs.push {\n      ref         := getDeclarationSelectionRef header.ref\n      kind        := header.kind\n      declName    := header.declName\n      levelParams := [], -- we set it later\n      modifiers   := header.modifiers\n      type        := type\n      value       := val\n    }\n\ndef pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition :=\n  letRecClosures.foldl (init := preDefs) fun preDefs c =>\n    let type := Closure.mkForall c.localDecls c.toLift.type\n    let val  := Closure.mkLambda c.localDecls c.toLift.val\n    preDefs.push {\n      ref         := c.ref\n      kind        := kind\n      declName    := c.toLift.declName\n      levelParams := [] -- we set it later\n      modifiers   := { modifiers with attrs := c.toLift.attrs }\n      type        := type\n      value       := val\n    }\n\ndef getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind :=\n  if mainHeaders.any fun h => h.kind.isTheorem then DefKind.\u00abtheorem\u00bb\n  else DefKind.\u00abdef\u00bb\n\ndef getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := {\n  isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable\n  recKind         := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default\n  isUnsafe        := mainHeaders.any fun h => h.modifiers.isUnsafe\n}\n\n/-\n- `sectionVars`:   The section variables used in the `mutual` block.\n- `mainHeaders`:   The elaborated header of the top-level definitions being defined by the mutual block.\n- `mainFVars`:     The auxiliary variables used to represent the top-level definitions being defined by the mutual block.\n- `mainVals`:      The elaborated value for the top-level definitions\n- `letRecsToLift`: The let-rec's definitions that need to be lifted\n-/\ndef main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift)\n    : TermElabM (Array PreDefinition) := do\n  -- Store in recFVarIds the fvarId of every function being defined by the mutual block.\n  let mainFVarIds := mainFVars.map Expr.fvarId!\n  let recFVarIds  := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds\n  -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec.\n  let mctx \u2190 getMCtx\n  let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift\n  resetZetaFVarIds\n  withTrackingZeta do\n    -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`.\n    letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val\n    let letRecClosures \u2190 mkLetRecClosures letRecsToLift freeVarMap\n    -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations.\n    let mainVals    \u2190 mainVals.mapM (instantiateMVars \u00b7)\n    let mainHeaders \u2190 mainHeaders.mapM instantiateMVarsAtHeader\n    let letRecClosures \u2190 letRecClosures.mapM fun closure => do pure { closure with toLift := (\u2190 instantiateMVarsAtLetRecToLift closure.toLift) }\n    -- Replace fvarIds for functions being defined with closed terms\n    let r              := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars\n    let r              := insertReplacementForLetRecs r letRecClosures\n    let mainVals       := mainVals.map r.apply\n    let mainHeaders    := mainHeaders.map fun h => { h with type := r.apply h.type }\n    let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } }\n    let letRecKind     := getKindForLetRecs mainHeaders\n    let letRecMods     := getModifiersForLetRecs mainHeaders\n    pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals\n\nend MutualClosure\n\nprivate def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name :=\n  if h : 0 < headers.size then\n    -- Recall that all top-level functions must have the same levels. See `check` method above\n    (headers.get \u27e80, h\u27e9).levelNames\n  else\n    []\n\n/-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/\nprivate def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do\n  let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do\n    let mut newHeaders := #[]\n    for view in views, header in headers do\n      if view.kind.isTheorem then\n        newHeaders := newHeaders.push { header with type := (\u2190 levelMVarToParam' header.type) }\n      else\n        newHeaders := newHeaders.push header\n    return newHeaders\n  let newHeaders \u2190 (process).run' 1\n  newHeaders.mapM fun header => return { header with type := (\u2190 instantiateMVars header.type) }\n\n/-- Result for `mkInst?` -/\nstructure MkInstResult where\n  instVal   : Expr\n  instType  : Expr\n  outParams : Array Expr := #[]\n\n/--\n  Construct an instance for `className out\u2081 ... out\u2099 type`.\n  The method support classes with a prefix of `outParam`s (e.g. `MonadReader`). -/\nprivate partial def mkInst? (className : Name) (type : Expr) : MetaM (Option MkInstResult) := do\n  let rec go? (instType instTypeType : Expr) (outParams : Array Expr) : MetaM (Option MkInstResult) := do\n    let instTypeType \u2190 whnfD instTypeType\n    unless instTypeType.isForall do\n      return none\n    let d := instTypeType.bindingDomain!\n    if isOutParam d then\n      let mvar \u2190 mkFreshExprMVar d\n      go? (mkApp instType mvar) (instTypeType.bindingBody!.instantiate1 mvar) (outParams.push mvar)\n    else\n      unless (\u2190 isDefEqGuarded (\u2190 inferType type) d) do\n        return none\n      let instType \u2190 instantiateMVars (mkApp instType type)\n      let instVal \u2190 synthInstance instType\n      return some { instVal, instType, outParams }\n  let instType \u2190 mkConstWithFreshMVarLevels className\n  go? instType (\u2190 inferType instType) #[]\n\ndef processDefDeriving (className : Name) (declName : Name) : TermElabM Bool := do\n  try\n    let ConstantInfo.defnInfo info \u2190 getConstInfo declName | return false\n    let some result \u2190 mkInst? className info.value | return false\n    let instTypeNew := mkApp result.instType.appFn! (Lean.mkConst declName (info.levelParams.map mkLevelParam))\n    Meta.check instTypeNew\n    let instName \u2190 liftMacroM <| mkUnusedBaseName (declName.appendBefore \"inst\" |>.appendAfter className.getString!)\n    addAndCompile <| Declaration.defnDecl {\n      name        := instName\n      levelParams := info.levelParams\n      type        := (\u2190 instantiateMVars instTypeNew)\n      value       := (\u2190 instantiateMVars result.instVal)\n      hints       := info.hints\n      safety      := info.safety\n    }\n    addInstance instName AttributeKind.global (eval_prio default)\n    return true\n  catch ex =>\n    return false\n\n/-- Remove auxiliary match discriminant let-declarations. -/\ndef eraseAuxDiscr (e : Expr) : CoreM Expr := do\n  Core.transform e fun e => match e with\n    | Expr.letE n _ v b .. =>\n      if isAuxDiscrName n then\n        return TransformStep.visit (b.instantiate1 v)\n      else\n        return TransformStep.visit e\n    | e => return TransformStep.visit e\n\ndef elabMutualDef (vars : Array Expr) (views : Array DefView) (hints : TerminationHints) : TermElabM Unit :=\n  if isExample views then\n    withoutModifyingEnv go\n  else\n    go\nwhere\n  go := do\n    let scopeLevelNames \u2190 getLevelNames\n    let headers \u2190 elabHeaders views\n    let headers \u2190 levelMVarToParamHeaders views headers\n    let allUserLevelNames := getAllUserLevelNames headers\n    withFunLocalDecls headers fun funFVars => do\n      let values \u2190 elabFunValues headers\n      Term.synthesizeSyntheticMVarsNoPostponing\n      let values \u2190 values.mapM (instantiateMVars \u00b7)\n      let headers \u2190 headers.mapM instantiateMVarsAtHeader\n      let letRecsToLift \u2190 getLetRecsToLift\n      let letRecsToLift \u2190 letRecsToLift.mapM instantiateMVarsAtLetRecToLift\n      checkLetRecsToLiftTypes funFVars letRecsToLift\n      withUsed vars headers values letRecsToLift fun vars => do\n        let preDefs \u2190 MutualClosure.main vars headers funFVars values letRecsToLift\n        for preDef in preDefs do\n          trace[Elab.definition] \"{preDef.declName} : {preDef.type} :=\\n{preDef.value}\"\n        let preDefs \u2190 levelMVarToParamPreDecls preDefs\n        let preDefs \u2190 instantiateMVarsAtPreDecls preDefs\n        let preDefs \u2190 fixLevelParams preDefs scopeLevelNames allUserLevelNames\n        let preDefs \u2190 preDefs.mapM fun preDef =>\n          if preDef.kind.isTheorem || preDef.kind.isExample then\n            return preDef\n          else\n            return { preDef with value := (\u2190 eraseAuxDiscr preDef.value) }\n        addPreDefinitions preDefs hints\n        processDeriving headers\n\n  processDeriving (headers : Array DefViewElabHeader) := do\n    for header in headers, view in views do\n      if let some classNamesStx := view.deriving? then\n        for classNameStx in classNamesStx do\n          let className \u2190 resolveGlobalConstNoOverload classNameStx\n          withRef classNameStx do\n            unless (\u2190 processDefDeriving className header.declName) do\n              throwError \"failed to synthesize instance '{className}' for '{header.declName}'\"\n\nend Term\nnamespace Command\n\ndef elabMutualDef (ds : Array Syntax) (hints : TerminationHints) : CommandElabM Unit := do\n  let views \u2190 ds.mapM fun d => do\n    let modifiers \u2190 elabModifiers d[0]\n    if ds.size > 1 && modifiers.isNonrec then\n      throwErrorAt d \"invalid use of 'nonrec' modifier in 'mutual' block\"\n    mkDefView modifiers d[1]\n  runTermElabM none fun vars => Term.elabMutualDef vars views hints\n\nend Command\nend Lean.Elab\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/Elab/MutualDef.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746995506106744, "lm_q2_score": 0.04535257958657159, "lm_q1q2_score": 0.013491029811520934}}
{"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 \u2190 getLCtx\n    let env \u2190 getEnv\n    for (thm, _) in usedSimps.toArray.qsort (\u00b7.2 < \u00b7.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 (\u2190 `(Parser.Tactic.simpLemma| $(mkIdent (\u2190 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 \u27e8thmStx\u27e9 \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 ++ (\u2190 locals.mapM fun id => `(Parser.Tactic.simpLemma| $(mkIdent id):ident))\n    else\n      args := args.push \u27e8(\u2190 `(Parser.Tactic.simpStar| *))\u27e9 \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 \u2190 getFVarIds hyps\n        go fvarIds simplifyTarget\n    | Location.wildcard =>\n      withMainContext do\n        go (\u2190 (\u2190 getMainGoal).getNondepPropHyps) (simplifyTarget := true)\n  where\n    go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM Syntax := do\n      let mvarId \u2190 getMainGoal\n      let (result?, usedSimps) \u2190 dsimpGoal mvarId ctx (simplifyTarget := simplifyTarget) (fvarIdsToSimp := fvarIdsToSimp)\n      match result? with\n      | none => replaceMainGoal []\n      | some mvarId => replaceMainGoal [mvarId]\n      traceSimpCall' (\u2190 getRef) usedSimps\n\n  def getMainGoal' : TacticM (MVarId \u00d7 List MVarId) := do\n  loop (\u2190 getGoals)\n    where\n  loop : List MVarId \u2192 TacticM (MVarId \u00d7 List MVarId)\n    | [] => throwNoGoalsToBeSolved\n    | mvarId :: mvarIds => do\n      if (\u2190 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 (\u2190 mvarIds.findM? fun mvarId => return tag == (\u2190 mvarId.getDecl).userName) with\n  | some mvarId => return mvarId\n  | none =>\n  match (\u2190 mvarIds.findM? fun mvarId => return tag.isSuffixOf (\u2190 mvarId.getDecl).userName) with\n  | some mvarId => return mvarId\n  | none => mvarIds.findM? fun mvarId => return tag.isPrefixOf (\u2190 mvarId.getDecl).userName\n\ndef getCaseGoals (tag : TSyntax `Lean.binderIdent) : TacticM (MVarId \u00d7 List MVarId) := do\n  let gs \u2190 getUnsolvedGoals\n  let g \u2190 if let `(Lean.binderIdent| $tag:ident) := tag then\n    let tag := tag.getId\n    let some g \u2190 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 \u2190 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 \u2192 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| \u00b7 $[$tacs]*) => do\n    let (mainGoal, otherGoals) \u2190 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) \u2190 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 } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false)\n    let usedSimps \u2190 dischargeWrapper.with fun discharge? =>\n      simpLocation ctx discharge? (expandOptLocation stx.raw[5])\n    traceTacticCallAt stx \u27e8\u2190 traceSimpCall' stx usedSimps\u27e9\n    traceGoalsAt stx\n  | stx@`(tactic| simp_all%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]?) => do\n    traceGoalsAt stx\n    let { ctx, .. } \u2190 mkSimpContext stx (eraseLocal := true) (kind := .simpAll) (ignoreStarArg := true)\n    let (result?, usedSimps) \u2190 simpAll (\u2190 getMainGoal) ctx\n    match result? with\n    | none => replaceMainGoal []\n    | some mvarId => replaceMainGoal [mvarId]\n    traceTacticCallAt stx \u27e8\u2190 traceSimpCall' stx usedSimps\u27e9\n    traceGoalsAt stx\n  | stx@`(tactic| dsimp%$tk $(config)? $[only%$o]? $[[$args,*]]? $(loc)?) => do\n    traceGoalsAt stx\n    let { ctx, .. } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false) (kind := .dsimp)\n    traceTacticCallAt stx \u27e8\u2190 dsimpLocation' ctx (expandOptLocation stx.raw[5])\u27e9\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 \u27e8r.raw\u27e9\n      let rtac \u2190 `(tactic| rw $[$cfg]? [$r] $[$loc]?) \n      evalTactic rtac\n      traceTacticCallAt \u27e8r.raw\u27e9 rtac\n      traceGoalsAt \u27e8r.raw\u27e9\n  | `(tactic| erw [$rs,*] $[$loc]?) => do\n    for r in (rs : TSyntaxArray `Lean.Parser.Tactic.rwRule) do\n      traceGoalsAt \u27e8r.raw\u27e9\n      let rtac \u2190 `(tactic| erw [$r] $[$loc]?) \n      evalTactic rtac\n      traceTacticCallAt \u27e8r.raw\u27e9 rtac\n      traceGoalsAt \u27e8r.raw\u27e9\n  | `(tactic| rwa [$rs,*] $[$loc]?) => do\n    for r in (rs : TSyntaxArray `Lean.Parser.Tactic.rwRule) do\n      traceGoalsAt \u27e8r.raw\u27e9\n      let rtac \u2190 `(tactic| rw [$r] $[$loc]?) \n      evalTactic rtac\n      traceTacticCallAt \u27e8r.raw\u27e9 rtac\n      traceGoalsAt \u27e8r.raw\u27e9\n    `(tactic| assumption) >>= evalTactic \u2218 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 \u2190 Tactic.elabTerm v none\n    let typ \u2190 inferType trm\n    let (mainGoal, otherGoals) \u2190 getMainGoal'\n    let newGoals \u2190 mainGoal.apply trm\n    setGoals <| newGoals ++ otherGoals\n    let typ \u2190 instantiateMVars typ\n    let typStx \u2190 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 \u2190 Tactic.elabTerm v none\n    let typ \u2190 inferType trm\n    let typStx \u2190 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 \u27e8arr\u27e9\n      traceTacticCallAt \u27e8arr\u27e9 stx -- TODO (unimportant) remove the `tacticSeq` from `stx`\n      let (g, _) \u2190 getCaseGoals tag\n      withRef arr <| addRawTrace (goalsToMessageData [g])\n    let stx \u2190 `(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 \u27e8arr\u27e9\n      traceTacticCallAt \u27e8arr\u27e9 stx -- TODO (unimportant) remove the `tacticSeq` from `stx`\n      let (g, _) \u2190 getCaseGoals tag\n      withRef arr <| addRawTrace (goalsToMessageData [g])\n    let stx \u2190 `(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 \u2190\n      is.mapM <|\n        fun\n          | `(inductionAlt| $il* => $ts:tacticSeq) => `(inductionAlt| $il* => seq $ts)\n          | i => return \u27e8i\u27e9\n    let stx' \u2190 `(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 \u2190\n      is.mapM <|\n        fun\n          | `(inductionAlt| $il* => $ts:tacticSeq) => `(inductionAlt| $il* => seq $ts)\n          | i => return \u27e8i\u27e9\n    let stx' \u2190 `(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 \u2190\n      alts.mapM <|\n        fun\n          | `(matchAltTac| | $[$pats,*]|* => $rhs:tacticSeq) => do\n              let alt \u2190 `(matchAltTac| | $[$pats,*]|* => seq $rhs)\n              return \u27e8alt\u27e9\n          | alt =>  return \u27e8alt\u27e9\n      let stx' \u2190 `(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 \u2190 Tactic.elabTerm prf none\n    let typ \u2190 inferType trm\n    let typStx \u2190 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 \u2190 Tactic.elabTerm val none\n    let typ \u2190 inferType trm\n    let typStx \u2190 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 <| \u2190 `(tactic.sorry)\n\n-- an example of the `seq` tactic\nexample (h : x = y) : 0 + x = y \u2227 1 = 1 := by\n  seq \n    rw [Nat.zero_add, (h : x = y)]\n  refine' \u27e8_, _\u27e9\n  focus\n    rw [\u2190h, h]\n  \u00b7 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 \u2190 mkFreshExprMVar expectedType MetavarKind.syntheticOpaque\n    let mvarId := mvar.mvarId!\n    let ref \u2190 getRef\n    registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic stx (\u2190 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 \u2227 1 = 1 := by\n  have := (rfl : 1 = 1)\n  let a := 5\n  simp at this\n  refine' \u27e8_, _\u27e9\n  \u00b7 apply Eq.symm\n    apply Eq.symm\n    erw [h, \u2190 h, h, \u2190 h]\n    simp_all\n  \u00b7 apply Eq.symm\n    apply Eq.symm\n    subst h\n    rfl\n  done\n\nexample : \u2200 n : Nat, n = n := by\n  intro n\n  let x : \u2200 m : \u2115, m = m := by\n    intro a\n    rfl\n  match n with\n  | .zero => rfl\n  | .succ _ => rfl\n\nexample : P \u2227 Q \u2194 Q \u2227 P := by\n  constructor\n  \u00b7 intro \u27e8x, y\u27e9\n    constructor\n    \u00b7 assumption\n    \u00b7 assumption\n  \u00b7 intro \u27e8_, _\u27e9\n    constructor\n    \u00b7 assumption\n    \u00b7 assumption\n\nexample : \u2200 n : Nat, n = n := by\n  intro n\n  induction n\n  case zero => rfl\n  case succ _ ih => simp\n\nexample : \u2200 n : Nat, n + n = n + n := by\n  intro n\n  induction n with\n    | zero => rfl\n    | succ _ _ => rfl\n\nexample : \u2200 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 : \u2200 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": "/-\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\nNotation for operators defined at Prelude.lean\n-/\nprelude\nimport Init.Prelude\n\n-- DSL for specifying parser precedences and priorities\n\nnamespace Lean.Parser.Syntax\n\nsyntax:65 (name := addPrec) prec \" + \" prec:66 : prec\nsyntax:65 (name := subPrec) prec \" - \" prec:66 : prec\n\nsyntax:65 (name := addPrio) prio \" + \" prio:66 : prio\nsyntax:65 (name := subPrio) prio \" - \" prio:66 : prio\n\nend Lean.Parser.Syntax\n\nmacro \"max\"  : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...)\nmacro \"arg\"  : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...)\nmacro \"lead\" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...)\nmacro \"(\" p:prec \")\" : prec => p\nmacro \"min\"  : prec => `(10)   -- minimum precedence used in term parsers\nmacro \"min1\" : prec => `(11)   -- `(min+1) we can only `min+1` after `Meta.lean`\n/-\n  `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.\n  We use `max_prec` to workaround bootstrapping issues. -/\nmacro \"max_prec\" : term => `(1024)\n\nmacro \"default\" : prio => `(1000)\nmacro \"low\"     : prio => `(100)\nmacro \"mid\"     : prio => `(1000)\nmacro \"high\"    : prio => `(10000)\nmacro \"(\" p:prio \")\" : prio => p\n\n-- Basic notation for defining parsers\n-- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses\nsyntax:arg stx:max \"+\" : stx\nsyntax:arg stx:max \"*\" : stx\nsyntax:arg stx:max \"?\" : stx\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\u2081 <|> $p\u2082) => `(stx| orelse($p\u2081, $p\u2082))\n\n/- Comma-separated sequence. -/\nmacro:arg x:stx:max \",*\"   : stx => `(stx| sepBy($x, \",\", \", \"))\nmacro:arg x:stx:max \",+\"   : stx => `(stx| sepBy1($x, \",\", \", \"))\n/- Comma-separated sequence with optional trailing comma. -/\nmacro:arg x:stx:max \",*,?\" : stx => `(stx| sepBy($x, \",\", \", \", allowTrailingSep))\nmacro:arg x:stx:max \",+,?\" : stx => `(stx| sepBy1($x, \",\", \", \", allowTrailingSep))\n\nmacro:arg \"!\" x:stx:max : stx => `(stx| notFollowedBy($x))\n\nsyntax (name := rawNatLit) \"nat_lit \" num : term\n\ninfixr:90 \" \u2218 \"  => Function.comp\ninfixr:35 \" \u00d7 \"  => Prod\n\ninfixl:55 \" ||| \" => HOr.hOr\ninfixl:58 \" ^^^ \" => HXor.hXor\ninfixl:60 \" &&& \" => HAnd.hAnd\ninfixl:65 \" + \"   => HAdd.hAdd\ninfixl:65 \" - \"   => HSub.hSub\ninfixl:70 \" * \"   => HMul.hMul\ninfixl:70 \" / \"   => HDiv.hDiv\ninfixl:70 \" % \"   => HMod.hMod\ninfixl:75 \" <<< \" => HShiftLeft.hShiftLeft\ninfixl:75 \" >>> \" => HShiftRight.hShiftRight\ninfixr:80 \" ^ \"   => HPow.hPow\ninfixl:65 \" ++ \"  => HAppend.hAppend\nprefix:100 \"-\"    => Neg.neg\nprefix:100 \"~~~\"  => Complement.complement\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% HAppend.hAppend $x $y)\n\n-- declare ASCII alternatives first so that the latter Unicode unexpander wins\ninfix:50 \" <= \" => LE.le\ninfix:50 \" \u2264 \"  => LE.le\ninfix:50 \" < \"  => LT.lt\ninfix:50 \" >= \" => GE.ge\ninfix:50 \" \u2265 \"  => GE.ge\ninfix:50 \" > \"  => GT.gt\ninfix:50 \" = \"  => Eq\ninfix: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 \u2264 $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 \u2265 $y)  => `(binrel% GE.ge $x $y)\nmacro_rules | `($x = $y)  => `(binrel% Eq $x $y)\nmacro_rules | `($x == $y) => `(binrel% BEq.beq $x $y)\n\ninfixr:35 \" /\\\\ \" => And\ninfixr:35 \" \u2227 \"   => And\ninfixr:30 \" \\\\/ \" => Or\ninfixr:30 \" \u2228  \"  => Or\nnotation:max \"\u00ac\" p:40 => Not p\n\ninfixl:35 \" && \" => and\ninfixl:30 \" || \" => or\nnotation:max \"!\" b:40 => not b\n\ninfixr:67 \" :: \" => List.cons\nsyntax:20 term:21 \" <|> \" term:20 : term\nsyntax:60 term:61 \" >> \" term:60 : term\ninfixl:55  \" >>= \" => Bind.bind\nnotation:60 a:60 \" <*> \" b:61 => Seq.seq a fun _ : Unit => b\nnotation:60 a:60 \" <* \" b:61 => SeqLeft.seqLeft a fun _ : Unit => b\nnotation:60 a:60 \" *> \" b:61 => SeqRight.seqRight a fun _ : Unit => b\ninfixr: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\nsyntax (name := termDepIfThenElse) ppGroup(ppDedent(\"if \" ident \" : \" term \" then\" ppSpace term ppDedent(ppSpace \"else\") ppSpace term)) : term\n\nmacro_rules\n  | `(if $h:ident : $c then $t:term else $e:term) => ``(dite $c (fun $h:ident => $t) (fun $h:ident => $e))\n\nsyntax (name := termIfThenElse) ppGroup(ppDedent(\"if \" term \" then\" ppSpace term ppDedent(ppSpace \"else\") ppSpace term)) : term\n\nmacro_rules\n  | `(if $c then $t:term else $e:term) => ``(ite $c $t $e)\n\nmacro \"if \" \"let \" pat:term \" := \" d:term \" then \" t:term \" else \" e:term : term =>\n  `(match $d:term with | $pat:term => $t | _ => $e)\n\nsyntax:min term \"<|\" term:min : term\n\nmacro_rules\n  | `($f $args* <| $a) => let args := args.push a; `($f $args*)\n  | `($f <| $a) => `($f $a)\n\nsyntax:min term \"|>\" term:min1 : term\n\nmacro_rules\n  | `($a |> $f $args*) => let args := args.push a; `($f $args*)\n  | `($a |> $f)        => `($f $a)\n\n-- Haskell-like pipe <|\n-- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations.\nsyntax:min term atomic(\"$\" ws) term:min : term\n\nmacro_rules\n  | `($f $args* $ $a) => let args := args.push a; `($f $args*)\n  | `($f $ $a) => `($f $a)\n\nsyntax \"{ \" 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.\n  Recall that terms such as `match ... with ...` and `\u27e8...\u27e9` will postpone elaboration until\n  expected type is known. So, `without_expected_type` is not effective in this case. -/\nmacro \"without_expected_type \" x:term : term => `(let aux := $x; aux)\n\nsyntax \"[\" term,* \"]\"  : term\nsyntax \"%[\" term,* \"|\" term \"]\" : term -- auxiliary notation for creating big list literals\n\nnamespace Lean\n\nmacro_rules\n  | `([ $elems,* ]) => do\n    let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : 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  (\u2190 ``(List.cons $(elems.elemsAndSeps[i]) $result))\n    if elems.elemsAndSeps.size < 64 then\n      expandListLit elems.elemsAndSeps.size false (\u2190 ``(List.nil))\n    else\n      `(%[ $elems,* | List.nil ])\n\nnotation:50 e:51 \" matches \" p:51 => match e with | p => true | _ => false\n\nnamespace Parser.Tactic\n/--\nIntroduce one or more hypotheses, optionally naming and/or pattern-matching them.\nFor each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type.\n* `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`.\n* `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`,\n  or matched against a pattern:\n  ```lean\n  -- ... \u22a2 \u03b1 \u00d7 \u03b2 \u2192 ...\n  intro (a, b)\n  -- ..., a : \u03b1, b : \u03b2 \u22a2 ...\n  ```\n* Alternatively, `intro` can be combined with pattern matching much like `fun`:\n  ```lean\n  intro\n  | n + 1, 0 => tac\n  | ...\n  ```\n-/\nsyntax (name := intro) \"intro \" notFollowedBy(\"|\") (colGt term:max)* : tactic\n/-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/\nsyntax (name := intros) \"intros \" (colGt (ident <|> \"_\"))* : tactic\n/--\n`rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`,\nor fails if no such hypothesis could be found. -/\nsyntax (name := rename) \"rename \" term \" => \" ident : tactic\n/-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/\nsyntax (name := revert) \"revert \" (colGt ident)+ : tactic\n/-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/\nsyntax (name := clear) \"clear \" (colGt ident)+ : tactic\n/--\n`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`.\nIf `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/\nsyntax (name := subst) \"subst \" (colGt ident)+ : tactic\n/--\n`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.\nNote also the `\u2039t\u203a` term notation, which is a shorthand for `show t by assumption`. -/\nsyntax (name := assumption) \"assumption\" : tactic\n/--\n`contradiction` closes the main goal if its hypotheses are \"trivially contradictory\".\n```lean\nexample (h : False) : p := by contradiction  -- inductive type/family with no applicable constructors\nexample (h : none = some true) : p := by contradiction  -- injectivity of constructors\nexample (h : 2 + 2 = 3) : p := by contradiction  -- decidable false proposition\nexample (h : p) (h' : \u00ac p) : q := by contradiction\nexample (x : Nat) (h : x \u2260 x) : p := by contradiction\n```\n-/\nsyntax (name := contradiction) \"contradiction\" : tactic\n/--\n`apply e` tries to match the current goal against the conclusion of `e`'s type.\nIf it succeeds, then the tactic returns as many subgoals as the number of premises that\nhave not been fixed by type inference or type class resolution.\nNon-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\nsyntax (name := apply) \"apply \" term : tactic\n/--\n`exact e` closes the main goal if its target type matches that of `e`.\n-/\nsyntax (name := exact) \"exact \" term : tactic\n/--\n`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved\nby unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name.\n-/\nsyntax (name := refine) \"refine \" term : tactic\n/-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/\nsyntax (name := refine') \"refine' \" term : tactic\n/-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/\nsyntax (name := constructor) \"constructor\" : tactic\n/--\n`case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails.\n`case tag x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/\nsyntax (name := case) \"case \" (ident <|> \"_\") (ident <|> \"_\")* \" => \" tacticSeq : tactic\n/--\n`next => tac` focuses on the next goal solves it using `tac`, or else fails.\n`next x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/\nmacro \"next \" args:(ident <|> \"_\")* \" => \" tac:tacticSeq : tactic => `(tactic| case _ $(args.getArgs)* => $tac)\n\n/-- `allGoals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/\nsyntax (name := allGoals) \"all_goals \" tacticSeq : tactic\n/-- `anyGoals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds.  -/\nsyntax (name := anyGoals) \"any_goals \" tacticSeq : tactic\n/--\n`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.\nUsually `\u00b7 tac`, which enforces that the goal is closed by `tac`, should be preferred. -/\nsyntax (name := focus) \"focus \" tacticSeq : tactic\n/-- `skip` does nothing. -/\nsyntax (name := skip) \"skip\" : tactic\n/-- `done` succeeds iff there are no remaining goals. -/\nsyntax (name := done) \"done\" : tactic\nsyntax (name := traceState) \"trace_state\" : tactic\nsyntax (name := failIfSuccess) \"fail_if_success \" tacticSeq : tactic\nsyntax (name := paren) \"(\" tacticSeq \")\" : tactic\nsyntax (name := withReducible) \"with_reducible \" tacticSeq : tactic\nsyntax (name := withReducibleAndInstances) \"with_reducible_and_instances \" tacticSeq : tactic\n/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/\nsyntax (name := first) \"first \" withPosition((group(colGe \"|\" tacticSeq))+) : tactic\nsyntax (name := rotateLeft) \"rotate_left\" (num)? : tactic\nsyntax (name := rotateRight) \"rotate_right\" (num)? : tactic\n/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/\nmacro \"try \" t:tacticSeq : tactic => `(first | $t | skip)\n/-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/\nmacro:1 x:tactic \" <;> \" y:tactic:0 : tactic => `(tactic| focus ($x:tactic; all_goals $y:tactic))\n\n/-- `\u00b7 tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/\nmacro dot:(\"\u00b7\" <|> \".\") ts:tacticSeq : tactic => `(tactic| {%$dot ($ts:tacticSeq) })\n\n/-- `rfl` is a shorthand for `exact rfl`. -/\nmacro \"rfl\" : tactic => `(exact rfl)\n/-- `admit` is a shorthand for `exact sorry`. -/\nmacro \"admit\" : tactic => `(exact sorry)\n/-- The `sorry` tactic isnxo a shorthand for `exact sorry`. -/\nmacro \"sorry\" : tactic => `(exact sorry)\nmacro \"infer_instance\" : tactic => `(exact inferInstance)\n\n/-- Optional configuration option for tactics -/\nsyntax config := atomic(\"(\" &\"config\") \" := \" term \")\"\n\nsyntax locationWildcard := \"*\"\nsyntax locationHyp      := (colGt ident)+ (\"\u22a2\" <|> \"|-\")? -- TODO: delete\nsyntax locationTargets  := (colGt ident)+ (\"\u22a2\" <|> \"|-\")?\nsyntax location         := withPosition(\" at \" (locationWildcard <|> locationHyp))\n\nsyntax (name := change) \"change \" term (location)? : tactic\nsyntax (name := changeWith) \"change \" term \" with \" term (location)? : tactic\n\nsyntax rwRule    := (\"\u2190\" <|> \"<-\")? term\nsyntax rwRuleSeq := \"[\" rwRule,+,? \"]\"\n\nsyntax (name := rewriteSeq) \"rewrite \" (config)? rwRuleSeq (location)? : tactic\n\nsyntax (name := rwSeq) \"rw \" (config)? rwRuleSeq (location)? : tactic\n\ndef rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do\n  -- We show the `rfl` state on `]`\n  let seq   := stx[2]\n  let rbrak := seq[2]\n  -- Replace `]` token with one without position information in the expanded tactic\n  let seq   := seq.setArg 2 (mkAtom \"]\")\n  let tac   := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 2 seq\n  `(tactic| $tac; try (with_reducible rfl%$rbrak))\n\n@[macro rwSeq] def expandRwSeq : Macro :=\n  rwWithRfl ``Lean.Parser.Tactic.rewriteSeq \"rewrite\"\n\nsyntax (name := injection) \"injection \" term (\" with \" (colGt (ident <|> \"_\"))+)? : tactic\n\nsyntax (name := injections) \"injections\" : tactic\n\nsyntax discharger := atomic(\"(\" (&\"discharger\" <|> &\"disch\")) \" := \" tacticSeq \")\"\n\nsyntax simpPre   := \"\u2193\"\nsyntax simpPost  := \"\u2191\"\nsyntax simpLemma := (simpPre <|> simpPost)? (\"\u2190\" <|> \"<-\")? term\nsyntax simpErase := \"-\" ident\nsyntax simpStar  := \"*\"\nsyntax (name := simp) \"simp \" (config)? (discharger)? (&\"only \")? (\"[\" (simpStar <|> simpErase <|> simpLemma),* \"]\")? (location)? : tactic\nsyntax (name := simpAll) \"simp_all \" (config)? (discharger)? (&\"only \")? (\"[\" (simpErase <|> simpLemma),* \"]\")? : tactic\n\n/--\n  Delta expand the given definition.\n  This is a low-level tactic, it will expose how recursive definitions have been compiled by Lean. -/\nsyntax (name := delta) \"delta \" ident (location)? : tactic\n\n-- Auxiliary macro for lifting have/suffices/let/...\n-- It makes sure the \"continuation\" `?_` is the main goal after refining\nmacro \"refine_lift \" e:term : tactic => `(focus (refine noImplicitLambda% $e; rotate_right))\n\nmacro \"have \" d:haveDecl : tactic => `(refine_lift have $d:haveDecl; ?_)\n/- We use a priority > default, to avoid ambiguity with previous `have` notation -/\nmacro (priority := high) \"have\" x:ident \" := \" p:term : tactic => `(have $x:ident : _ := $p)\nmacro \"suffices \" d:sufficesDecl : tactic => `(refine_lift suffices $d:sufficesDecl; ?_)\nmacro \"let \" d:letDecl : tactic => `(refine_lift let $d:letDecl; ?_)\nmacro \"show \" e:term : tactic => `(refine_lift show $e:term from ?_)\nsyntax (name := letrec) withPosition(atomic(group(\"let \" &\"rec \")) letRecDecls) : tactic\nmacro_rules\n  | `(tactic| let rec $d:letRecDecls) => `(tactic| refine_lift let rec $d:letRecDecls; ?_)\n\n-- Similar to `refineLift`, but using `refine'`\nmacro \"refine_lift' \" e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotate_right))\nmacro \"have' \" d:haveDecl : tactic => `(refine_lift' have $d:haveDecl; ?_)\nmacro (priority := high) \"have'\" x:ident \" := \" p:term : tactic => `(have' $x:ident : _ := $p)\nmacro \"let' \" d:letDecl : tactic => `(refine_lift' let $d:letDecl; ?_)\n\nsyntax inductionAlt  := \"| \" (group(\"@\"? ident) <|> \"_\") (ident <|> \"_\")* \" => \" (hole <|> syntheticHole <|> tacticSeq)\nsyntax inductionAlts := \"with \" (tactic)? withPosition( (colGe inductionAlt)+)\nsyntax (name := induction) \"induction \" term,+ (\" using \" ident)?  (\"generalizing \" ident+)? (inductionAlts)? : tactic\n\nsyntax generalizeArg := atomic(ident \" : \")? term:51 \" = \" ident\n/--\n`generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal with a fresh hypothesis `x`s.\nIf `h` is given, `h : e = x` is introduced as well. -/\nsyntax (name := generalize) \"generalize \" generalizeArg,+ : tactic\n\nsyntax casesTarget := atomic(ident \" : \")? term\nsyntax (name := cases) \"cases \" casesTarget,+ (\" using \" ident)? (inductionAlts)? : tactic\n\nsyntax (name := existsIntro) \"exists \" term : tactic\n\n/-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/\nsyntax (name := renameI) \"rename_i \" (colGt (ident <|> \"_\"))+ : tactic\n\nsyntax \"repeat \" tacticSeq : tactic\nmacro_rules\n  | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)\n\nsyntax \"trivial\" : tactic\n\nsyntax (name := split) \"split \" (colGt term)? (location)? : tactic\n\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`.\nThe premises of this hypothesis, either universal quantifications or non-dependent implications,\nare instantiated by concrete terms coming either from arguments `a\u2081` ... `a\u2099`.\nThe tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099` and tries to clear the previous one.\n-/\nsyntax (name := specialize) \"specialize \" term : tactic\n\nmacro_rules | `(tactic| trivial) => `(tactic| assumption)\nmacro_rules | `(tactic| trivial) => `(tactic| rfl)\nmacro_rules | `(tactic| trivial) => `(tactic| contradiction)\nmacro_rules | `(tactic| trivial) => `(tactic| apply True.intro)\nmacro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)\n\nmacro \"unhygienic \" t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq)\n\nend Tactic\n\nnamespace Attr\n-- simp attribute syntax\nsyntax (name := simp) \"simp\" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr\nend Attr\n\nend Parser\nend Lean\n\nmacro \"\u2039\" type:term \"\u203a\" : term => `((by assumption : $type))\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/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.04023793830762335, "lm_q1q2_score": 0.013463189295527866}}
{"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 : \u03ba) (fn : Option \u03b1 \u2192 Option \u03b1) (r : RBMap \u03ba \u03b1 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 : \u03ba \u2192 \u03b1 \u2192 \u03b1 \u2192 \u03b1) (r1 r2 : RBMap \u03ba \u03b1 cmp) :  RBMap \u03ba \u03b1 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 (\u03b1 : Type) [Ord \u03b1] := Std.RBMap \u03b1 Nat compare\n\nvariable {\u03b1 : Type} [Ord \u03b1]\n\ndef Multiset.empty : Multiset \u03b1 := mkRBMap _ _ _\n\ninstance : EmptyCollection  (Multiset \u03b1) :=  \u27e8Multiset.empty\u27e9\n\ninstance : Append  (Multiset \u03b1) where\n  append x y := x.mergeBy (fun _ => (\u00b7+\u00b7)) y\n\ndef Multiset.add : Multiset \u03b1 \u2192 \u03b1 \u2192 Multiset \u03b1\n  | m, a => m.modify' a (fun | none => some 1 | some v => some (v + 1))\n\ndef Multiset.singleton : \u03b1 \u2192 Multiset \u03b1\n  | a => Multiset.empty |>.add a\n\ninstance : Ord Name := \u27e8Name.quickCmp\u27e9\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 := \u2205\n  bigramCounts : Multiset Bigram := \u2205\n  trigramCounts : Multiset Trigram := \u2205\n\ninstance : ForIn M (Multiset \u03b1) (\u03b1 \u00d7 Nat) :=\n  show ForIn _ (Std.RBMap _ _ _) _ by infer_instance\n\ndef Multiset.toList (m : Multiset \u03b1) : List \u03b1 :=\n  m.foldl (fun l x _ => x :: l) []\n\ndef Multiset.toHFeatures [ToString \u03b1] (m : Multiset \u03b1) : Array String :=\n  Array.mk <| m.toList.map (s!\"H:{\u00b7}\")\n\ndef Multiset.toTFeatures [ToString \u03b1] (m : Multiset \u03b1) : Array String :=\n  Array.mk <| m.toList.map (s!\"T:{\u00b7}\")\n\ninstance [ToJson \u03b1] : ToJson (Multiset \u03b1) where\n  toJson m := Json.arr (Array.mk (m.toList.map toJson))\n\ninstance : EmptyCollection StatementFeatures := \u27e8{}\u27e9\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 \u2192 StatementFeatures\n  | n => {nameCounts := Multiset.singleton n}\n\ndef StatementFeatures.mkBigram : Name \u2192 Name \u2192 StatementFeatures\n  | n1, n2 => {bigramCounts := Multiset.singleton \u27e8n1, n2\u27e9}\n\ndef StatementFeatures.mkTrigram : Name \u2192 Name \u2192 Name \u2192 StatementFeatures\n  | n1, n2, n3 => {trigramCounts := Multiset.singleton \u27e8n1, n2, n3\u27e9}\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 \u2190 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) \u2190 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 \u2190 inferType arg\n    if (\u2190 inferType argType).isProp then\n      let argFeats \u2190 getStatementFeatures argType\n      if ! argFeats.nameCounts.isEmpty then\n        argsFeats := argsFeats ++ #[argFeats]\n  return argsFeats\n\ndef getThmAndArgsFeatures (e : Expr) \n  : MetaM (StatementFeatures \u00d7 Array StatementFeatures) := do\n  forallTelescope e <| fun args thm => do\n      let thmFeats \u2190 getStatementFeatures thm\n      let argsFeats \u2190 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: Leonardo de Moura\n-/\nimport Lean.Structure\nimport Lean.Util.Recognizers\nimport Lean.Meta.GetConst\nimport Lean.Meta.FunInfo\nimport Lean.Meta.Match.MatcherInfo\nimport Lean.Meta.Match.MatchPatternAttr\n\nnamespace Lean.Meta\n\n-- ===========================\n/-! # Smart unfolding support -/\n-- ===========================\n\n/--\nForward declaration. It is defined in the module `src/Lean/Elab/PreDefinition/Structural/Eqns.lean`.\nIt is possible to avoid this hack if we move `Structural.EqnInfo` and `Structural.eqnInfoExt`\nto this module.\n-/\n@[extern \"lean_get_structural_rec_arg_pos\"]\nopaque getStructuralRecArgPos? (declName : Name) : CoreM (Option Nat)\n\ndef smartUnfoldingSuffix := \"_sunfold\"\n\n@[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name :=\n  Name.mkStr declName smartUnfoldingSuffix\n\ndef hasSmartUnfoldingDecl (env : Environment) (declName : Name) : Bool :=\n  env.contains (mkSmartUnfoldingNameFor declName)\n\nregister_builtin_option smartUnfolding : Bool := {\n  defValue := true\n  descr := \"when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion\"\n}\n\n/-- Add auxiliary annotation to indicate the `match`-expression `e` must be reduced when performing smart unfolding. -/\ndef markSmartUnfoldingMatch (e : Expr) : Expr :=\n  mkAnnotation `sunfoldMatch e\n\ndef smartUnfoldingMatch? (e : Expr) : Option Expr :=\n  annotation? `sunfoldMatch e\n\n/-- Add auxiliary annotation to indicate expression `e` (a `match` alternative rhs) was successfully reduced by smart unfolding. -/\ndef markSmartUnfoldingMatchAlt (e : Expr) : Expr :=\n  mkAnnotation `sunfoldMatchAlt e\n\ndef smartUnfoldingMatchAlt? (e : Expr) : Option Expr :=\n  annotation? `sunfoldMatchAlt e\n\n-- ===========================\n/-! # Helper methods -/\n-- ===========================\n\ndef isAuxDef (constName : Name) : MetaM Bool := do\n  let env \u2190 getEnv\n  return isAuxRecursor env constName || isNoConfusion env constName\n\n@[inline] private def matchConstAux {\u03b1} (e : Expr) (failK : Unit \u2192 MetaM \u03b1) (k : ConstantInfo \u2192 List Level \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  match e with\n  | Expr.const name lvls => do\n    let (some cinfo) \u2190 getConst? name | failK ()\n    k cinfo lvls\n  | _ => failK ()\n\n-- ===========================\n/-! # Helper functions for reducing recursors -/\n-- ===========================\n\nprivate def getFirstCtor (d : Name) : MetaM (Option Name) := do\n  let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) \u2190 getConstNoEx? d | pure none\n  return some ctor\n\nprivate def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do\n  match type.getAppFn with\n  | Expr.const d lvls =>\n    let (some ctor) \u2190 getFirstCtor d | pure none\n    return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams)\n  | _ =>\n    return none\n\nprivate def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule :=\n  match major.getAppFn with\n  | Expr.const fn _ => recVal.rules.find? fun r => r.ctor == fn\n  | _               => none\n\nprivate def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM Expr := do\n  let majorType \u2190 inferType major\n  let majorType \u2190 instantiateMVars (\u2190 whnf majorType)\n  let majorTypeI := majorType.getAppFn\n  if !majorTypeI.isConstOf recVal.getInduct then\n    return major\n  else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then\n    return major\n  else do\n    let (some newCtorApp) \u2190 mkNullaryCtor majorType recVal.numParams | pure major\n    let newType \u2190 inferType newCtorApp\n    /- TODO: check whether changing reducibility to default hurts performance here.\n       We do that to make sure auxiliary `Eq.rec` introduced by the `match`-compiler\n       are reduced even when `TransparencyMode.reducible` (like in `simp`).\n\n       We use `withNewMCtxDepth` to make sure metavariables at `majorType` are not assigned.\n       For example, given `major : Eq ?x y`, we don't want to apply K by assigning `?x := y`.\n    -/\n    if (\u2190 withAtLeastTransparency TransparencyMode.default <| withNewMCtxDepth <| isDefEq majorType newType) then\n      return newCtorApp\n    else\n      return major\n\n/--\n  Create the `i`th projection `major`. It tries to use the auto-generated projection functions if available. Otherwise falls back\n  to `Expr.proj`.\n-/\ndef mkProjFn (ctorVal : ConstructorVal) (us : List Level) (params : Array Expr) (i : Nat) (major : Expr) : CoreM Expr := do\n  match getStructureInfo? (\u2190 getEnv) ctorVal.induct with\n  | none => return mkProj ctorVal.induct i major\n  | some info => match info.getProjFn? i with\n    | none => return mkProj ctorVal.induct i major\n    | some projFn => return mkApp (mkAppN (mkConst projFn us) params) major\n\n/--\n  If `major` is not a constructor application, and its type is a structure `C ...`, then return `C.mk major.1 ... major.n`\n\n  \\pre `inductName` is `C`.\n\n  If `Meta.Config.etaStruct` is `false` or the condition above does not hold, this method just returns `major`. -/\nprivate def toCtorWhenStructure (inductName : Name) (major : Expr) : MetaM Expr := do\n  unless (\u2190 useEtaStruct inductName) do\n    return major\n  let env \u2190 getEnv\n  if !isStructureLike env inductName then\n    return major\n  else if let some _ := major.isConstructorApp? env then\n    return major\n  else\n    let majorType \u2190 inferType major\n    let majorType \u2190 instantiateMVars (\u2190 whnf majorType)\n    let majorTypeI := majorType.getAppFn\n    if !majorTypeI.isConstOf inductName then\n      return major\n    match majorType.getAppFn with\n    | Expr.const d us =>\n      if (\u2190 whnfD (\u2190 inferType majorType)) == mkSort levelZero then\n        return major -- We do not perform eta for propositions, see implementation in the kernel\n      else\n        let some ctorName \u2190 getFirstCtor d | pure major\n        let ctorInfo \u2190 getConstInfoCtor ctorName\n        let params := majorType.getAppArgs.shrink ctorInfo.numParams\n        let mut result := mkAppN (mkConst ctorName us) params\n        for i in [:ctorInfo.numFields] do\n          result := mkApp result (\u2190 mkProjFn ctorInfo us params i major)\n        return result\n    | _ => return major\n\n/-- Auxiliary function for reducing recursor applications. -/\nprivate def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit \u2192 MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  let majorIdx := recVal.getMajorIdx\n  if h : majorIdx < recArgs.size then do\n    let major := recArgs.get \u27e8majorIdx, h\u27e9\n    let mut major \u2190 whnf major\n    if recVal.k then\n      major \u2190 toCtorWhenK recVal major\n    major := major.toCtorIfLit\n    major \u2190 toCtorWhenStructure recVal.getInduct major\n    match getRecRuleFor recVal major with\n    | some rule =>\n      let majorArgs := major.getAppArgs\n      if recLvls.length != recVal.levelParams.length then\n        failK ()\n      else\n        let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls\n        -- Apply parameters, motives and minor premises from recursor application.\n        let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs\n        /- The number of parameters in the constructor is not necessarily\n           equal to the number of parameters in the recursor when we have\n           nested inductive types. -/\n        let nparams := majorArgs.size - rule.nfields\n        let rhs := mkAppRange rhs nparams majorArgs.size majorArgs\n        let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs\n        successK rhs\n    | none => failK ()\n  else\n    failK ()\n\n-- ===========================\n/-! # Helper functions for reducing Quot.lift and Quot.ind -/\n-- ===========================\n\n/-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/\nprivate def reduceQuotRec (recVal  : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit \u2192 MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  let process (majorPos argPos : Nat) : MetaM \u03b1 :=\n    if h : majorPos < recArgs.size then do\n      let major := recArgs.get \u27e8majorPos, h\u27e9\n      let major \u2190 whnf major\n      match major with\n      | Expr.app (Expr.app (Expr.app (Expr.const majorFn _) _) _) majorArg => do\n        let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) \u2190 getConstNoEx? majorFn | failK ()\n        let f := recArgs[argPos]!\n        let r := mkApp f majorArg\n        let recArity := majorPos + 1\n        successK <| mkAppRange r recArity recArgs.size recArgs\n      | _ => failK ()\n    else\n      failK ()\n  match recVal.kind with\n  | QuotKind.lift => process 5 3\n  | QuotKind.ind  => process 4 3\n  | _             => failK ()\n\n-- ===========================\n/-! # Helper function for extracting \"stuck term\" -/\n-- ===========================\n\nmutual\n  private partial def isRecStuck? (recVal : RecursorVal) (recArgs : Array Expr) : MetaM (Option MVarId) :=\n    if recVal.k then\n      -- TODO: improve this case\n      return none\n    else do\n      let majorIdx := recVal.getMajorIdx\n      if h : majorIdx < recArgs.size then do\n        let major := recArgs.get \u27e8majorIdx, h\u27e9\n        let major \u2190 whnf major\n        getStuckMVar? major\n      else\n        return none\n\n  private partial def isQuotRecStuck? (recVal : QuotVal) (recArgs : Array Expr) : MetaM (Option MVarId) :=\n    let process? (majorPos : Nat) : MetaM (Option MVarId) :=\n      if h : majorPos < recArgs.size then do\n        let major := recArgs.get \u27e8majorPos, h\u27e9\n        let major \u2190 whnf major\n        getStuckMVar? major\n      else\n        return none\n    match recVal.kind with\n    | QuotKind.lift => process? 5\n    | QuotKind.ind  => process? 4\n    | _             => return none\n\n  /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/\n  partial def getStuckMVar? (e : Expr) : MetaM (Option MVarId) := do\n    match e with\n    | .mdata _ e  => getStuckMVar? e\n    | .proj _ _ e => getStuckMVar? (\u2190 whnf e)\n    | .mvar .. =>\n      let e \u2190 instantiateMVars e\n      match e with\n      | .mvar mvarId => return some mvarId\n      | _ => getStuckMVar? e\n    | .app f .. =>\n      let f := f.getAppFn\n      match f with\n      | .mvar .. =>\n        let e \u2190 instantiateMVars e\n        match e.getAppFn with\n        | .mvar mvarId => return some mvarId\n        | _ => getStuckMVar? e\n      | .const fName _ =>\n        match (\u2190 getConstNoEx? fName) with\n        | some <| .recInfo recVal  => isRecStuck? recVal e.getAppArgs\n        | some <| .quotInfo recVal => isQuotRecStuck? recVal e.getAppArgs\n        | _  =>\n          unless e.hasExprMVar do return none\n          -- Projection function support\n          let some projInfo \u2190 getProjectionFnInfo? fName | return none\n          -- This branch is relevant if `e` is a type class projection that is stuck because the instance has not been synthesized yet.\n          unless projInfo.fromClass do return none\n          let args := e.getAppArgs\n          -- First check whether `e`s instance is stuck.\n          if let some major := args.get? projInfo.numParams then\n            if let some mvarId \u2190 getStuckMVar? major then\n              return mvarId\n          /-\n          Then, recurse on the explicit arguments\n          We want to detect the stuck instance in terms such as\n          `HAdd.hAdd Nat Nat Nat (instHAdd Nat instAddNat) n (OfNat.ofNat Nat 2 ?m)`\n          See issue https://github.com/leanprover/lean4/issues/1408 for an example where this is needed.\n          -/\n          let info \u2190 getFunInfo f\n          for pinfo in info.paramInfo, arg in args do\n            if pinfo.isExplicit then\n              if let some mvarId \u2190 getStuckMVar? arg then\n                return some mvarId\n          return none\n      | .proj _ _ e => getStuckMVar? (\u2190 whnf e)\n      | _ => return none\n    | _ => return none\nend\n\n-- ===========================\n/-! # Weak Head Normal Form auxiliary combinators -/\n-- ===========================\n\n/-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the \"hard\" cases as an argument -/\n@[specialize] partial def whnfEasyCases (e : Expr) (k : Expr \u2192 MetaM Expr) : MetaM Expr := do\n  match e with\n  | .forallE ..    => return e\n  | .lam ..        => return e\n  | .sort ..       => return e\n  | .lit ..        => return e\n  | .bvar ..       => unreachable!\n  | .letE ..       => k e\n  | .const ..      => k e\n  | .app ..        => k e\n  | .proj ..       => k e\n  | .mdata _ e     => whnfEasyCases e k\n  | .fvar fvarId   =>\n    let decl \u2190 fvarId.getDecl\n    match decl with\n    | .cdecl .. => return e\n    | .ldecl (value := v) (nonDep := nonDep) .. =>\n      let cfg \u2190 getConfig\n      if nonDep && !cfg.zetaNonDep then\n        return e\n      else\n        if cfg.trackZeta then\n          modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId }\n        whnfEasyCases v k\n  | .mvar mvarId   =>\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some v => whnfEasyCases v k\n    | none   => return e\n\n@[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level)\n    (failK : Unit \u2192 MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  if c.levelParams.length != lvls.length then\n    failK ()\n  else\n    successK (\u2190 instantiateValueLevelParams c lvls)\n\n@[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr)\n    (failK : Unit \u2192 MetaM \u03b1) (successK : Expr \u2192 MetaM \u03b1) (preserveMData := false) : MetaM \u03b1 := do\n  if c.levelParams.length != lvls.length then\n    failK ()\n  else\n    let val \u2190 instantiateValueLevelParams c lvls\n    let val := val.betaRev revArgs (preserveMData := preserveMData)\n    successK val\n\ninductive ReduceMatcherResult where\n  | reduced (val : Expr)\n  | stuck   (val : Expr)\n  | notMatcher\n  | partialApp\n\n/--\n  The \"match\" compiler uses `if-then-else` expressions and other auxiliary declarations to compile match-expressions such as\n  ```\n  match v with\n  | 'a' => 1\n  | 'b' => 2\n  | _   => 3\n  ```\n  because it is more efficient than using `casesOn` recursors.\n  The method `reduceMatcher?` fails if these auxiliary definitions (e.g., `ite`) cannot be unfolded in the current\n  transparency setting. This is problematic because tactics such as `simp` use `TransparencyMode.reducible`, and\n  most users assume that expressions such as\n  ```\n  match 0 with\n  | 0 => 1\n  | 100 => 2\n  | _ => 3\n  ```\n  should reduce in any transparency mode.\n  Thus, we define a custom `canUnfoldAtMatcher` predicate for `whnfMatcher`.\n\n  This solution is not very modular because modications at the `match` compiler require changes here.\n  We claim this is defensible because it is reducing the auxiliary declaration defined by the `match` compiler.\n\n  Alternative solution: tactics that use `TransparencyMode.reducible` should rely on the equations we generated for match-expressions.\n  This solution is also not perfect because the match-expression above will not reduce during type checking when we are not using\n  `TransparencyMode.default` or `TransparencyMode.all`.\n-/\ndef canUnfoldAtMatcher (cfg : Config) (info : ConstantInfo) : CoreM Bool := do\n  match cfg.transparency with\n  | TransparencyMode.all     => return true\n  | TransparencyMode.default => return true\n  | _ =>\n    if (\u2190 isReducible info.name) || isGlobalInstance (\u2190 getEnv) info.name then\n      return true\n    else if hasMatchPatternAttribute (\u2190 getEnv) info.name then\n      return true\n    else\n      return info.name == ``ite\n       || info.name == ``dite\n       || info.name == ``decEq\n       || info.name == ``Nat.decEq\n       || info.name == ``Char.ofNat   || info.name == ``Char.ofNatAux\n       || info.name == ``String.decEq || info.name == ``List.hasDecEq\n       || info.name == ``Fin.ofNat\n       || info.name == ``UInt8.ofNat  || info.name == ``UInt8.decEq\n       || info.name == ``UInt16.ofNat || info.name == ``UInt16.decEq\n       || info.name == ``UInt32.ofNat || info.name == ``UInt32.decEq\n       || info.name == ``UInt64.ofNat || info.name == ``UInt64.decEq\n       /- Remark: we need to unfold the following two definitions because they are used for `Fin`, and\n          lazy unfolding at `isDefEq` does not unfold projections.  -/\n       || info.name == ``HMod.hMod || info.name == ``Mod.mod\n\nprivate def whnfMatcher (e : Expr) : MetaM Expr := do\n  /- When reducing `match` expressions, if the reducibility setting is at `TransparencyMode.reducible`,\n     we increase it to `TransparencyMode.instance`. We use the `TransparencyMode.reducible` in many places (e.g., `simp`),\n     and this setting prevents us from reducing `match` expressions where the discriminants are terms such as `OfNat.ofNat \u03b1 n inst`.\n     For example, `simp [Int.div]` will not unfold the application `Int.div 2 1` occuring in the target.\n\n     TODO: consider other solutions; investigate whether the solution above produces counterintuitive behavior.  -/\n  let mut transparency \u2190 getTransparency\n  if transparency == TransparencyMode.reducible then\n    transparency := TransparencyMode.instances\n  withTransparency transparency <| withReader (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher }) do\n    whnf e\n\ndef reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do\n  match e.getAppFn with\n  | Expr.const declName declLevels =>\n    let some info \u2190 getMatcherInfo? declName\n      | return ReduceMatcherResult.notMatcher\n    let args := e.getAppArgs\n    let prefixSz := info.numParams + 1 + info.numDiscrs\n    if args.size < prefixSz + info.numAlts then\n      return ReduceMatcherResult.partialApp\n    else\n      let constInfo \u2190 getConstInfo declName\n      let f \u2190 instantiateValueLevelParams constInfo declLevels\n      let auxApp := mkAppN f args[0:prefixSz]\n      let auxAppType \u2190 inferType auxApp\n      forallBoundedTelescope auxAppType info.numAlts fun hs _ => do\n        let auxApp \u2190 whnfMatcher (mkAppN auxApp hs)\n        let auxAppFn := auxApp.getAppFn\n        let mut i := prefixSz\n        for h in hs do\n          if auxAppFn == h then\n            let result := mkAppN args[i]! auxApp.getAppArgs\n            let result := mkAppN result args[prefixSz + info.numAlts:args.size]\n            return ReduceMatcherResult.reduced result.headBeta\n          i := i + 1\n        return ReduceMatcherResult.stuck auxApp\n  | _ => pure ReduceMatcherResult.notMatcher\n\nprivate def projectCore? (e : Expr) (i : Nat) : MetaM (Option Expr) := do\n  let e := e.toCtorIfLit\n  matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ =>\n    let numArgs := e.getAppNumArgs\n    let idx := ctorVal.numParams + i\n    if idx < numArgs then\n      return some (e.getArg! idx)\n    else\n      return none\n\ndef project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do\n  projectCore? (\u2190 whnf e) i\n\n/-- Reduce kernel projection `Expr.proj ..` expression. -/\ndef reduceProj? (e : Expr) : MetaM (Option Expr) := do\n  match e with\n  | Expr.proj _ i c => project? c i\n  | _               => return none\n\n/--\n  Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned.\n  Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been \"filled\".\n-/\nprivate def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do\n  if f'.isMVar then\n    match (\u2190 getDelayedMVarAssignment? f'.mvarId!) with\n    | none => return none\n    | some { fvars, mvarIdPending } =>\n      let args := e.getAppArgs\n      if fvars.size > args.size then\n        -- Insufficient number of argument to expand delayed assignment\n        return none\n      else\n        let newVal \u2190 instantiateMVars (mkMVar mvarIdPending)\n        if newVal.hasExprMVar then\n           -- Delayed assignment still contains metavariables\n           return none\n        else\n           let newVal := newVal.abstract fvars\n           let result := newVal.instantiateRevRange 0 fvars.size args\n           return mkAppRange result fvars.size args.size args\n  else\n    return none\n\n/--\nApply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction,\nexpand let-expressions, expand assigned meta-variables.\n\nThe parameter `deltaAtProj` controls how to reduce projections `s.i`. If `deltaAtProj == true`,\nthen delta reduction is used to reduce `s` (i.e., `whnf` is used), otherwise `whnfCore`.\n\nIf `simpleReduceOnly`, then `iota` and projection reduction are not performed.\nNote that the value of `deltaAtProj` is irrelevant if `simpleReduceOnly = true`.\n-/\npartial def whnfCore (e : Expr) (deltaAtProj : Bool := true) (simpleReduceOnly := false) : MetaM Expr :=\n  go e\nwhere\n  go (e : Expr) : MetaM Expr :=\n    whnfEasyCases e fun e => do\n      trace[Meta.whnf] e\n      match e with\n      | Expr.const ..  => pure e\n      | Expr.letE _ _ v b _ => go <| b.instantiate1 v\n      | Expr.app f ..       =>\n        let f := f.getAppFn\n        let f' \u2190 go f\n        if f'.isLambda then\n          let revArgs := e.getAppRevArgs\n          go <| f'.betaRev revArgs\n        else if let some eNew \u2190 whnfDelayedAssigned? f' e then\n          go eNew\n        else\n          let e := if f == f' then e else e.updateFn f'\n          if simpleReduceOnly then\n            return e\n          else\n            match (\u2190 reduceMatcher? e) with\n            | ReduceMatcherResult.reduced eNew => go eNew\n            | ReduceMatcherResult.partialApp   => pure e\n            | ReduceMatcherResult.stuck _      => pure e\n            | ReduceMatcherResult.notMatcher   =>\n              matchConstAux f' (fun _ => return e) fun cinfo lvls =>\n                match cinfo with\n                | ConstantInfo.recInfo rec    => reduceRec rec lvls e.getAppArgs (fun _ => return e) go\n                | ConstantInfo.quotInfo rec   => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) go\n                | c@(ConstantInfo.defnInfo _) => do\n                  if (\u2190 isAuxDef c.name) then\n                    deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) go\n                  else\n                    return e\n                | _ => return e\n      | Expr.proj _ i c =>\n        if simpleReduceOnly then\n          return e\n        else\n          let c \u2190 if deltaAtProj then whnf c else whnfCore c\n          match (\u2190 projectCore? c i) with\n          | some e => go e\n          | none => return e\n      | _ => unreachable!\n\n/--\n  Recall that `_sunfold` auxiliary definitions contains the markers: `markSmartUnfoldingMatch` (*) and `markSmartUnfoldingMatchAlt` (**).\n  For example, consider the following definition\n  ```\n  def r (i j : Nat) : Nat :=\n    i +\n      match j with\n      | Nat.zero => 1\n      | Nat.succ j =>\n        i + match j with\n            | Nat.zero => 2\n            | Nat.succ j => r i j\n  ```\n  produces the following `_sunfold` auxiliary definition with the markers\n  ```\n  def r._sunfold (i j : Nat) : Nat :=\n    i +\n      (*) match j with\n      | Nat.zero => (**) 1\n      | Nat.succ j =>\n        i + (*) match j with\n            | Nat.zero => (**) 2\n            | Nat.succ j => (**) r i j\n  ```\n\n  `match` expressions marked with `markSmartUnfoldingMatch` (*) must be reduced, otherwise the resulting term is not definitionally\n   equal to the given expression. The recursion may be interrupted as soon as the annotation `markSmartUnfoldingAlt` (**) is reached.\n\n  For example, the term `r i j.succ.succ` reduces to the definitionally equal term `i + i * r i j`\n-/\npartial def smartUnfoldingReduce? (e : Expr) : MetaM (Option Expr) :=\n  go e |>.run\nwhere\n  go (e : Expr) : OptionT MetaM Expr := do\n    match e with\n    | Expr.letE n t v b _ => withLetDecl n t (\u2190 go v) fun x => do mkLetFVars #[x] (\u2190 go (b.instantiate1 x))\n    | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (\u2190 go b)\n    | Expr.app f a .. => return mkApp (\u2190 go f) (\u2190 go a)\n    | Expr.proj _ _ s => return e.updateProj! (\u2190 go s)\n    | Expr.mdata _ b  =>\n      if let some m := smartUnfoldingMatch? e then\n        goMatch m\n      else\n        return e.updateMData! (\u2190 go b)\n    | _ => return e\n\n  goMatch (e : Expr) : OptionT MetaM Expr := do\n    match (\u2190 reduceMatcher? e) with\n    | ReduceMatcherResult.reduced e =>\n      if let some alt := smartUnfoldingMatchAlt? e then\n        return alt\n      else\n        go e\n    | ReduceMatcherResult.stuck e' =>\n      let mvarId \u2190 getStuckMVar? e'\n      /- Try to \"unstuck\" by resolving pending TC problems -/\n      if (\u2190 Meta.synthPending mvarId) then\n        goMatch e\n      else\n        failure\n    | _ => failure\n\nmutual\n\n  /--\n    Auxiliary method for unfolding a class projection.\n  -/\n  partial def unfoldProjInst? (e : Expr) : MetaM (Option Expr) := do\n    match e.getAppFn with\n    | Expr.const declName .. =>\n      match (\u2190 getProjectionFnInfo? declName) with\n      | some { fromClass := true, .. } =>\n        match (\u2190 withDefault <| unfoldDefinition? e) with\n        | none   => return none\n        | some e =>\n          match (\u2190 withReducibleAndInstances <| reduceProj? e.getAppFn) with\n          | none   => return none\n          | some r => return mkAppN r e.getAppArgs |>.headBeta\n      | _ => return none\n    | _ => return none\n\n  /--\n    Auxiliary method for unfolding a class projection. when transparency is set to `TransparencyMode.instances`.\n    Recall that class instance projections are not marked with `[reducible]` because we want them to be\n    in \"reducible canonical form\".\n  -/\n  partial def unfoldProjInstWhenIntances? (e : Expr) : MetaM (Option Expr) := do\n    if (\u2190 getTransparency) != TransparencyMode.instances then\n      return none\n    else\n      unfoldProjInst? e\n\n  /-- Unfold definition using \"smart unfolding\" if possible. -/\n  partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) :=\n    match e with\n    | Expr.app f _ =>\n      matchConstAux f.getAppFn (fun _ => unfoldProjInstWhenIntances? e) fun fInfo fLvls => do\n        if fInfo.levelParams.length != fLvls.length then\n          return none\n        else\n          let unfoldDefault (_ : Unit) : MetaM (Option Expr) :=\n            if fInfo.hasValue then\n              deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))\n            else\n              return none\n          if smartUnfolding.get (\u2190 getOptions) then\n            match ((\u2190 getEnv).find? (mkSmartUnfoldingNameFor fInfo.name)) with\n            | some fAuxInfo@(ConstantInfo.defnInfo _) =>\n              -- We use `preserveMData := true` to make sure the smart unfolding annotation are not erased in an over-application.\n              deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (preserveMData := true) (fun _ => pure none) fun e\u2081 => do\n                let some r \u2190 smartUnfoldingReduce? e\u2081 | return none\n                /-\n                  If `smartUnfoldingReduce?` succeeds, we should still check whether the argument the\n                  structural recursion is recursing on reduces to a constructor.\n                  This extra check is necessary in definitions (see issue #1081) such as\n                  ```\n                  inductive Vector (\u03b1 : Type u) : Nat \u2192 Type u where\n                    | nil  : Vector \u03b1 0\n                    | cons : \u03b1 \u2192 Vector \u03b1 n \u2192 Vector \u03b1 (n+1)\n\n                  def Vector.insert (a: \u03b1) (i : Fin (n+1)) (xs : Vector \u03b1 n) : Vector \u03b1 (n+1) :=\n                    match i, xs with\n                    | \u27e80,   _\u27e9,        xs => cons a xs\n                    | \u27e8i+1, h\u27e9, cons x xs => cons x (xs.insert a \u27e8i, Nat.lt_of_succ_lt_succ h\u27e9)\n                  ```\n                  The structural recursion is being performed using the vector `xs`. That is, we used `Vector.brecOn` to define\n                  `Vector.insert`. Thus, an application `xs.insert a \u27e80, h\u27e9` is **not** definitionally equal to\n                  `Vector.cons a xs` because `xs` is not a constructor application (the `Vector.brecOn` application is blocked).\n\n                  Remark 1: performing structural recursion on `Fin (n+1)` is not an option here because it is a `Subtype` and\n                  and the repacking in recursive applications confuses the structural recursion module.\n\n                  Remark 2: the match expression reduces reduces to `cons a xs` when the discriminants are `\u27e80, h\u27e9` and `xs`.\n\n                  Remark 3: this check is unnecessary in most cases, but we don't need dependent elimination to trigger the issue                        fixed by this extra check. Here is another example that triggers the issue fixed by this check.\n                  ```\n                  def f : Nat \u2192 Nat \u2192 Nat\n                    | 0,   y   => y\n                    | x+1, y+1 => f (x-2) y\n                    | x+1, 0   => 0\n\n                  theorem ex : f 0 y = y := rfl\n                  ```\n\n                  Remark 4: the `return some r` in the following `let` is not a typo. Binport generated .olean files do not\n                  store the position of recursive arguments for definitions using structural recursion.\n                  Thus, we should keep `return some r` until Mathlib has been ported to Lean 3.\n                  Note that the `Vector` example above does not even work in Lean 3.\n                -/\n                let some recArgPos \u2190 getStructuralRecArgPos? fInfo.name | return some r\n                let numArgs := e.getAppNumArgs\n                if recArgPos >= numArgs then return none\n                let recArg := e.getArg! recArgPos numArgs\n                if !(\u2190 whnfMatcher recArg).isConstructorApp (\u2190 getEnv) then return none\n                return some r\n            | _ =>\n              if (\u2190 getMatcherInfo? fInfo.name).isSome then\n                -- Recall that `whnfCore` tries to reduce \"matcher\" applications.\n                return none\n              else\n                unfoldDefault ()\n          else\n            unfoldDefault ()\n    | Expr.const declName lvls => do\n      if smartUnfolding.get (\u2190 getOptions) && (\u2190 getEnv).contains (mkSmartUnfoldingNameFor declName) then\n        return none\n      else\n        let (some (cinfo@(ConstantInfo.defnInfo _))) \u2190 getConstNoEx? declName | pure none\n        deltaDefinition cinfo lvls\n          (fun _ => pure none)\n          (fun e => pure (some e))\n    | _ => return none\nend\n\ndef unfoldDefinition (e : Expr) : MetaM Expr := do\n  let some e \u2190 unfoldDefinition? e | throwError \"failed to unfold definition{indentExpr e}\"\n  return e\n\n@[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr \u2192 MetaM Bool) : MetaM Expr :=\n  whnfEasyCases e fun e => do\n    let e \u2190 whnfCore e\n    if (\u2190 pred e) then\n        match (\u2190 unfoldDefinition? e) with\n        | some e => whnfHeadPred e pred\n        | none   => return e\n    else\n      return e\n\ndef whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do\n  let e \u2190 whnfHeadPred e (fun e => return !e.isAppOf declName)\n  if e.isAppOf declName then\n    return e\n  else\n    return none\n\n/-- Try to reduce matcher/recursor/quot applications. We say they are all \"morally\" recursor applications. -/\ndef reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do\n  if !e.isApp then\n    return none\n  else match (\u2190 reduceMatcher? e) with\n    | ReduceMatcherResult.reduced e => return e\n    | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do\n      match cinfo with\n      | ConstantInfo.recInfo \u00abrec\u00bb  => reduceRec \u00abrec\u00bb lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e))\n      | ConstantInfo.quotInfo \u00abrec\u00bb => reduceQuotRec \u00abrec\u00bb lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e))\n      | c@(ConstantInfo.defnInfo _) =>\n        if (\u2190 isAuxDef c.name) then\n          deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e))\n        else\n          return none\n      | _ => return none\n\nunsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName\nunsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName\n@[implemented_by reduceBoolNativeUnsafe] opaque reduceBoolNative (constName : Name) : MetaM Bool\n@[implemented_by reduceNatNativeUnsafe] opaque reduceNatNative (constName : Name) : MetaM Nat\n\ndef reduceNative? (e : Expr) : MetaM (Option Expr) :=\n  match e with\n  | Expr.app (Expr.const fName _) (Expr.const argName _) =>\n    if fName == ``Lean.reduceBool then do\n      return toExpr (\u2190 reduceBoolNative argName)\n    else if fName == ``Lean.reduceNat then do\n      return toExpr (\u2190 reduceNatNative argName)\n    else\n      return none\n  | _ =>\n    return none\n\n@[inline] def withNatValue {\u03b1} (a : Expr) (k : Nat \u2192 MetaM (Option \u03b1)) : MetaM (Option \u03b1) := do\n  let a \u2190 whnf a\n  match a with\n  | Expr.const `Nat.zero _      => k 0\n  | Expr.lit (Literal.natVal v) => k v\n  | _                           => return none\n\ndef reduceUnaryNatOp (f : Nat \u2192 Nat) (a : Expr) : MetaM (Option Expr) :=\n  withNatValue a fun a =>\n  return mkRawNatLit <| f a\n\ndef reduceBinNatOp (f : Nat \u2192 Nat \u2192 Nat) (a b : Expr) : MetaM (Option Expr) :=\n  withNatValue a fun a =>\n  withNatValue b fun b => do\n  trace[Meta.isDefEq.whnf.reduceBinOp] \"{a} op {b}\"\n  return mkRawNatLit <| f a b\n\ndef reduceBinNatPred (f : Nat \u2192 Nat \u2192 Bool) (a b : Expr) : MetaM (Option Expr) := do\n  withNatValue a fun a =>\n  withNatValue b fun b =>\n  return toExpr <| f a b\n\ndef reduceNat? (e : Expr) : MetaM (Option Expr) :=\n  if e.hasFVar || e.hasMVar then\n    return none\n  else match e with\n    | Expr.app (Expr.const fn _) a                =>\n      if fn == ``Nat.succ then\n        reduceUnaryNatOp Nat.succ a\n      else\n        return none\n    | Expr.app (Expr.app (Expr.const fn _) a1) a2 =>\n      if fn == ``Nat.add then reduceBinNatOp Nat.add a1 a2\n      else if fn == ``Nat.sub then reduceBinNatOp Nat.sub a1 a2\n      else if fn == ``Nat.mul then reduceBinNatOp Nat.mul a1 a2\n      else if fn == ``Nat.div then reduceBinNatOp Nat.div a1 a2\n      else if fn == ``Nat.mod then reduceBinNatOp Nat.mod a1 a2\n      else if fn == ``Nat.beq then reduceBinNatPred Nat.beq a1 a2\n      else if fn == ``Nat.ble then reduceBinNatPred Nat.ble a1 a2\n      else return none\n    | _ =>\n      return none\n\n\n@[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do\n  -- We cache only closed terms without expr metavars.\n  -- Potential refinement: cache if `e` is not stuck at a metavariable\n  if e.hasFVar || e.hasExprMVar || (\u2190 read).canUnfold?.isSome then\n    return false\n  else\n    match (\u2190 getConfig).transparency with\n    | TransparencyMode.default => return true\n    | TransparencyMode.all     => return true\n    | _                        => return false\n\n@[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do\n  if useCache then\n    match (\u2190 getConfig).transparency with\n    | TransparencyMode.default => return (\u2190 get).cache.whnfDefault.find? e\n    | TransparencyMode.all     => return (\u2190 get).cache.whnfAll.find? e\n    | _                        => unreachable!\n  else\n    return none\n\nprivate def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do\n  if useCache then\n    match (\u2190 getConfig).transparency with\n    | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r }\n    | TransparencyMode.all     => modify fun s => { s with cache.whnfAll     := s.cache.whnfAll.insert e r }\n    | _                        => unreachable!\n  return r\n\n@[export lean_whnf]\npartial def whnfImp (e : Expr) : MetaM Expr :=\n  withIncRecDepth <| whnfEasyCases e fun e => do\n    checkMaxHeartbeats \"whnf\"\n    let useCache \u2190 useWHNFCache e\n    match (\u2190 cached? useCache e) with\n    | some e' => pure e'\n    | none    =>\n      let e' \u2190 whnfCore e\n      match (\u2190 reduceNat? e') with\n      | some v => cache useCache e v\n      | none   =>\n        match (\u2190 reduceNative? e') with\n        | some v => cache useCache e v\n        | none   =>\n          match (\u2190 unfoldDefinition? e') with\n          | some e => whnfImp e\n          | none   => cache useCache e e'\n\n/-- If `e` is a projection function that satisfies `p`, then reduce it -/\ndef reduceProjOf? (e : Expr) (p : Name \u2192 Bool) : MetaM (Option Expr) := do\n  if !e.isApp then\n    pure none\n  else match e.getAppFn with\n    | Expr.const name .. => do\n      let env \u2190 getEnv\n      match env.getProjectionStructureName? name with\n      | some structName =>\n        if p structName then\n          Meta.unfoldDefinition? e\n        else\n          pure none\n      | none => pure none\n    | _ => pure none\n\nbuiltin_initialize\n  registerTraceClass `Meta.whnf\n  registerTraceClass `Meta.isDefEq.whnf.reduceBinOp\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/WHNF.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.03846618981375453, "lm_q1q2_score": 0.013411049432730108}}
{"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.Data.Options\n\n/- Basic support for auto bound implicit local names -/\n\nnamespace Lean.Elab\n\nregister_builtin_option autoImplicit : Bool := {\n    defValue := true\n    descr    := \"Unbound local variables in declaration headers become implicit arguments. In \\\"relaxed\\\" mode (default), any atomic identifier is eligible, otherwise only a lower case or greek letter followed by numeric digits are eligible. For example, `def f (x : Vector \u03b1 n) : Vector \u03b1 n :=` automatically introduces the implicit variables {\u03b1 n}.\"\n  }\n\nregister_builtin_option relaxedAutoImplicit : Bool := {\n    defValue := true\n    descr    := \"When \\\"relaxed\\\" mode is enabled, any atomic nonempty identifier is eligible for auto bound implicit locals (see optin `autoBoundImplicitLocal`.\"\n  }\n\n\nprivate def isValidAutoBoundSuffix (s : String) : Bool :=\n  s.toSubstring.drop 1 |>.all fun c => c.isDigit || isSubScriptAlnum c || c == '_' || c == '\\''\n\n/-\nRemark: Issue #255 exposed a nasty interaction between macro scopes and auto-bound-implicit names.\n```\nlocal notation \"A\" => id x\ntheorem test : A = A := sorry\n```\nWe used to use `n.eraseMacroScopes` at `isValidAutoBoundImplicitName` and `isValidAutoBoundLevelName`.\nThus, in the example above, when `A` is expanded, a `x` with a fresh macro scope is created.\n`x`+macros-scope is not in scope and is a valid auto-bound implicit name after macro scopes are erased.\nSo, an auto-bound exception would be thrown, and `x`+macro-scope would be added as a new implicit.\nWhen, we try again, a `x` with a new macro scope is created and this process keeps repeating.\nTherefore, we do consider identifier with macro scopes anymore.\n-/\n\ndef isValidAutoBoundImplicitName (n : Name) (relaxed : Bool) : Bool :=\n  match n with\n  | Name.str Name.anonymous s _ => s.length > 0 && (relaxed || ((isGreek s[0] || s[0].isLower) && isValidAutoBoundSuffix s))\n  | _ => false\n\ndef isValidAutoBoundLevelName (n : Name) (relaxed : Bool) : Bool :=\n  match n with\n  | Name.str Name.anonymous s _ => s.length > 0 && (relaxed || (s[0].isLower && isValidAutoBoundSuffix s))\n  | _ => false\n\nend Lean.Elab\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/src/Lean/Elab/AutoBound.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.05340333356619821, "lm_q1q2_score": 0.013399579852337466}}
{"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\u2080 u\u2081 v\u2080 v\u2081 \n\nnamespace Mathlib\n\nstructure writer_t (\u03c9 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) \nwhere\n  run : m (\u03b1 \u00d7 \u03c9)\n\ndef writer (\u03c9 : Type u) (\u03b1 : Type u) :=\n  writer_t \u03c9 id\n\nnamespace writer_t\n\n\nprotected theorem ext {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} (x : writer_t \u03c9 m \u03b1) (x' : writer_t \u03c9 m \u03b1) (h : run x = run x') : x = x' := sorry\n\nprotected def tell {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] (w : \u03c9) : writer_t \u03c9 m PUnit :=\n  mk (pure (PUnit.unit, w))\n\nprotected def listen {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m (\u03b1 \u00d7 \u03c9) :=\n  sorry\n\nprotected def pass {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} : writer_t \u03c9 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 writer_t \u03c9 m \u03b1 :=\n  sorry\n\nprotected def pure {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} [HasOne \u03c9] (a : \u03b1) : writer_t \u03c9 m \u03b1 :=\n  mk (pure (a, 1))\n\nprotected def bind {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} [Mul \u03c9] (x : writer_t \u03c9 m \u03b1) (f : \u03b1 \u2192 writer_t \u03c9 m \u03b2) : writer_t \u03c9 m \u03b2 :=\n  mk\n    (do \n      let x \u2190 run x \n      let x' \u2190 run (f (prod.fst x))\n      pure (prod.fst x', prod.snd x * prod.snd x'))\n\nprotected instance monad {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] [HasOne \u03c9] [Mul \u03c9] : Monad (writer_t \u03c9 m) := sorry\n\nprotected instance is_lawful_monad {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] [monoid \u03c9] [is_lawful_monad m] : is_lawful_monad (writer_t \u03c9 m) := sorry\n\nprotected def lift {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} [HasOne \u03c9] (a : m \u03b1) : writer_t \u03c9 m \u03b1 :=\n  mk (flip Prod.mk 1 <$> a)\n\nprotected instance has_monad_lift {\u03c9 : Type u} (m : Type u \u2192 Type u_1) [Monad m] [HasOne \u03c9] : has_monad_lift m (writer_t \u03c9 m) :=\n  has_monad_lift.mk fun (\u03b1 : Type u) => writer_t.lift\n\nprotected def monad_map {\u03c9 : Type u} {m : Type u \u2192 Type u_1} {m' : Type u \u2192 Type u_2} [Monad m] [Monad m'] {\u03b1 : Type u} (f : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m' \u03b1 :=\n  fun (x : writer_t \u03c9 m \u03b1) => mk (f (run x))\n\nprotected instance monad_functor {\u03c9 : Type u} (m : Type u \u2192 Type u_1) (m' : Type u \u2192 Type u_1) [Monad m] [Monad m'] : monad_functor m m' (writer_t \u03c9 m) (writer_t \u03c9 m') :=\n  monad_functor.mk writer_t.monad_map\n\nprotected def adapt {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03c9' : Type u} {\u03b1 : Type u} (f : \u03c9 \u2192 \u03c9') : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9' m \u03b1 :=\n  fun (x : writer_t \u03c9 m \u03b1) => mk (prod.map id f <$> run x)\n\nprotected instance monad_except {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] (\u03b5 : outParam (Type u_1)) [HasOne \u03c9] [Monad m] [monad_except \u03b5 m] : monad_except \u03b5 (writer_t \u03c9 m) :=\n  monad_except.mk (fun (\u03b1 : Type u) => writer_t.lift \u2218 throw)\n    fun (\u03b1 : Type u) (x : writer_t \u03c9 m \u03b1) (c : \u03b5 \u2192 writer_t \u03c9 m \u03b1) => mk (catch (run x) fun (e : \u03b5) => 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 (\u03c1 : out_param (Type u)) (n : Type u \u2192 Type u) :=\n(lift {\u03b1 : Type u} : (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1) \u2192 n \u03b1)\n```\n-/\nclass monad_writer (\u03c9 : outParam (Type u)) (m : Type u \u2192 Type v) \nwhere\n  tell : \u03c9 \u2192 m PUnit\n  listen : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 m (\u03b1 \u00d7 \u03c9)\n  pass : {\u03b1 : Type u} \u2192 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 m \u03b1\n\nprotected instance writer_t.monad_writer {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] : monad_writer \u03c9 (writer_t \u03c9 m) :=\n  monad_writer.mk writer_t.tell (fun (\u03b1 : Type u) => writer_t.listen) fun (\u03b1 : Type u) => writer_t.pass\n\nprotected instance reader_t.monad_writer {\u03c9 : Type u} {\u03c1 : Type u} {m : Type u \u2192 Type v} [Monad m] [monad_writer \u03c9 m] : monad_writer \u03c9 (reader_t \u03c1 m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x)) (fun (\u03b1 : Type u) (_x : reader_t \u03c1 m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : reader_t \u03c1 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => sorry\n\ndef swap_right {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} : (\u03b1 \u00d7 \u03b2) \u00d7 \u03b3 \u2192 (\u03b1 \u00d7 \u03b3) \u00d7 \u03b2 :=\n  sorry\n\nprotected instance state_t.monad_writer {\u03c9 : Type u} {\u03c3 : Type u} {m : Type u \u2192 Type v} [Monad m] [monad_writer \u03c9 m] : monad_writer \u03c9 (state_t \u03c3 m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x)) (fun (\u03b1 : Type u) (_x : state_t \u03c3 m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : state_t \u03c3 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => sorry\n\ndef except_t.pass_aux {\u03b5 : Type u_1} {\u03b1 : Type u_2} {\u03c9 : Type u_3} : except \u03b5 (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 except \u03b5 \u03b1 \u00d7 (\u03c9 \u2192 \u03c9) :=\n  sorry\n\nprotected instance except_t.monad_writer {\u03c9 : Type u} {\u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m] [monad_writer \u03c9 m] : monad_writer \u03c9 (except_t \u03b5 m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x)) (fun (\u03b1 : Type u) (_x : except_t \u03b5 m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : except_t \u03b5 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => sorry\n\ndef option_t.pass_aux {\u03b1 : Type u_1} {\u03c9 : Type u_2} : Option (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 Option \u03b1 \u00d7 (\u03c9 \u2192 \u03c9) :=\n  sorry\n\nprotected instance option_t.monad_writer {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] [monad_writer \u03c9 m] : monad_writer \u03c9 (option_t m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x)) (fun (\u03b1 : Type u) (_x : option_t m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : option_t m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => 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 (\u03c1 \u03c1' : out_param (Type u)) (n n' : Type u \u2192 Type u) :=\n(map {\u03b1 : Type u} : (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1 \u2192 reader_t \u03c1' m \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1)\n```\n-/\nclass monad_writer_adapter (\u03c9 : outParam (Type u)) (\u03c9' : outParam (Type u)) (m : Type u \u2192 Type v) (m' : Type u \u2192 Type v) \nwhere\n  adapt_writer : {\u03b1 : Type u} \u2192 (\u03c9 \u2192 \u03c9') \u2192 m \u03b1 \u2192 m' \u03b1\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 {\u03c9 : Type u} {\u03c9' : Type u} {m : Type u \u2192 Type v} {m' : Type u \u2192 Type v} {n : Type u \u2192 Type v} {n' : Type u \u2192 Type v} [monad_writer_adapter \u03c9 \u03c9' m m'] [monad_functor m m' n n'] : monad_writer_adapter \u03c9 \u03c9' n n' :=\n  monad_writer_adapter.mk fun (\u03b1 : Type u) (f : \u03c9 \u2192 \u03c9') => monad_map fun (\u03b1 : Type u) => adapt_writer f\n\nprotected instance writer_t.monad_writer_adapter {\u03c9 : Type u} {\u03c9' : Type u} {m : Type u \u2192 Type v} [Monad m] : monad_writer_adapter \u03c9 \u03c9' (writer_t \u03c9 m) (writer_t \u03c9' m) :=\n  monad_writer_adapter.mk fun (\u03b1 : Type u) => writer_t.adapt\n\nprotected instance writer_t.monad_run (\u03c9 : Type u) (m : Type u \u2192 Type (max u u_1)) (out : outParam (Type u \u2192 Type (max u u_1))) [monad_run out m] : monad_run (fun (\u03b1 : Type u) => out (\u03b1 \u00d7 \u03c9)) (writer_t \u03c9 m) :=\n  monad_run.mk fun (\u03b1 : Type u) (x : writer_t \u03c9 m \u03b1) => 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081} {\u03b1\u2081 : Type u\u2080} {\u03c9\u2081 : Type u\u2080} {\u03b1\u2082 : Type u\u2081} {\u03c9\u2082 : Type u\u2081} (F : m\u2081 (\u03b1\u2081 \u00d7 \u03c9\u2081) \u2243 m\u2082 (\u03b1\u2082 \u00d7 \u03c9\u2082)) : writer_t \u03c9\u2081 m\u2081 \u03b1\u2081 \u2243 writer_t \u03c9\u2082 m\u2082 \u03b1\u2082 :=\n  equiv.mk (fun (_x : writer_t \u03c9\u2081 m\u2081 \u03b1\u2081) => sorry) (fun (_x : writer_t \u03c9\u2082 m\u2082 \u03b1\u2082) => 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\u2081 u\u2082\n\n/-\nRemark: we can define `mapM`, `mapM\u2082` and `forM` using `Applicative` instead of `Monad`.\nExample:\n```\ndef mapM {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\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 \u2192 Type v} [Monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\n  | []    => pure []\n  | a::as => return (\u2190 f a) :: (\u2190 mapM f as)\n\n@[specialize]\ndef mapA {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\n  | []    => pure []\n  | a::as => List.cons <$> f a <*> mapA f as\n\n@[specialize]\nprotected def forM {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type w} (as : List \u03b1) (f : \u03b1 \u2192 m PUnit) : m PUnit :=\n  match as with\n  | []      => pure \u27e8\u27e9\n  | a :: as => do f a; List.forM as f\n\n@[specialize]\ndef forA {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} (as : List \u03b1) (f : \u03b1 \u2192 m PUnit) : m PUnit :=\n  match as with\n  | []      => pure \u27e8\u27e9\n  | a :: as => f a *> forA as f\n\n@[specialize]\ndef filterAuxM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 List \u03b1 \u2192 m (List \u03b1)\n  | [],     acc => pure acc\n  | h :: t, acc => do\n    let b \u2190 f h\n    filterAuxM f t (cond b (h :: acc) acc)\n\n@[inline]\ndef filterM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) (as : List \u03b1) : m (List \u03b1) := do\n  let as \u2190 filterAuxM f as []\n  pure as.reverse\n\n@[inline]\ndef filterRevM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) (as : List \u03b1) : m (List \u03b1) :=\n  filterAuxM f as.reverse []\n\n@[inline]\ndef filterMapM {m : Type u \u2192 Type v} [Monad m] {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 m (Option \u03b2)) (as : List \u03b1) : m (List \u03b2) :=\n  let rec @[specialize] loop\n    | [],     bs => pure bs\n    | a :: as, bs => do\n      match (\u2190 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 \u2192 Type v} [Monad m] {s : Type u} {\u03b1 : Type w} : (f : s \u2192 \u03b1 \u2192 m s) \u2192 (init : s) \u2192 List \u03b1 \u2192 m s\n  | f, s, []      => pure s\n  | f, s, a :: as => do\n    let s' \u2190 f s a\n    List.foldlM f s' as\n\n@[specialize]\ndef foldrM {m : Type u \u2192 Type v} [Monad m] {s : Type u} {\u03b1 : Type w} : (f : \u03b1 \u2192 s \u2192 m s) \u2192 (init : s) \u2192 List \u03b1 \u2192 m s\n  | f, s, []      => pure s\n  | f, s, a :: as => do\n    let s' \u2190 foldrM f s as\n    f a s'\n\n@[specialize]\ndef firstM {m : Type u \u2192 Type v} [Monad m] [Alternative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m \u03b2\n  | []    => failure\n  | a::as => f a <|> firstM f as\n\n@[specialize]\ndef anyM {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type v} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m Bool\n  | []    => pure false\n  | a::as => do\n    match (\u2190 f a) with\n    | true  => pure true\n    | false => anyM f as\n\n@[specialize]\ndef allM {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type v} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m Bool\n  | []    => pure true\n  | a::as => do\n    match (\u2190 f a) with\n    | true  => allM f as\n    | false => pure false\n\n@[specialize]\ndef findM? {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type} (p : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m (Option \u03b1)\n  | []    => pure none\n  | a::as => do\n    match (\u2190 p a) with\n    | true  => pure (some a)\n    | false => findM? p as\n\n@[specialize]\ndef findSomeM? {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m (Option \u03b2)) : List \u03b1 \u2192 m (Option \u03b2)\n  | []    => pure none\n  | a::as => do\n    match (\u2190 f a) with\n    | some b => pure (some b)\n    | none   => findSomeM? f as\n\n@[inline] protected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : List \u03b1) (init : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec @[specialize] loop\n    | [], b    => pure b\n    | a::as, b => do\n      match (\u2190 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 \u03b1) \u03b1 where\n  forIn := List.forIn\n\n@[simp] theorem forIn_nil [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) (b : \u03b2) : forIn [] b f = pure b :=\n  rfl\n\n@[simp] theorem forIn_cons [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) (a : \u03b1) (as : List \u03b1) (b : \u03b2)\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 \u03b1) \u03b1 where\n  forM := List.forM\n\n@[simp] theorem forM_nil  [Monad m] (f : \u03b1 \u2192 m PUnit) : forM [] f = pure \u27e8\u27e9 :=\n  rfl\n@[simp] theorem forM_cons [Monad m] (f : \u03b1 \u2192 m PUnit) (a : \u03b1) (as : List \u03b1) : 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 dag\nimport tactic\nimport crawler\nimport data.list.defs\n-- import data.int.basic\n-- import number_theory.quadratic_reciprocity\n-- import topology.algebra.module\n-- import topology.algebra.ordered.basic\n-- import ring_theory.discrete_valuation_ring\n-- import algebra.lie.classical\n-- import system.io\n-- import init.meta.widget.tactic_component\n-- import data.list.lex\n\n-- TODO replace igets with get or else for surity\n/-!\nNotes:\n\n* Sometimes files need changing beyond their imports, this can either be a insufficiency of this\n  code or a weirdness in the file being modified, here are some ways this can happen:\n  - The file being modified opens a namespace but never uses it, this will fail when the import is\n    removed, but it wasn't doing anything in the first place, solution: delete the `open blah`\n  - The file being modified applies simp with some attribute but then so simp lemmas with that\n    attribute are applied so the dependency is missed, solution change to another or no simp set.\n  - The file being modified uses notation but only notation from another file, solution, ignore it\n    or move the notation next to the defs it refers to.\n  - If a file contains an `example` which introduces extra dependencies this won't be visible in the\n    environment after, so will be missed.\n\n-/\n\nsection generic_io_stuff\n\n/-- Remove a trailing newline character from a `list char` (if there is one) -/\nmeta def remove_trail : list char \u2192 list char\n| ['\\n'] := []\n| (a :: b) := a :: remove_trail b\n| [] := []\n\nopen io\n/-- read one line of the file `f` as a string -/\nmeta def io.handle.get_line_as_string (f : handle) : io string :=\ndo g \u2190 fs.get_line f, return $ (remove_trail g.to_list).as_string\n\nend generic_io_stuff\n\nlocal attribute [-instance] string_to_name -- this tends to cause confusion\nopen tactic declaration environment io io.fs (put_str_ln close)\n\n/-- These decls are special as they are magically defined in cpp and don't have a genuine lean file\n    source to point to, also they can never not be imported. -/\ndef magic_homeless_decls := [`quot, `quot.mk, `quot.lift, `quot.ind]\n\n/-- These are user attributes that we can use to check for imports not obvious from the final\n    proof term, i.e.\n    ```\n    @[ext]\n    structure blah := (n : \u2115)\n    ```\n    will produce a lemma `blah.ext` that doesn't contain any references to the file where the `ext`\n    attribute is defined, nevertheless by looking up the place where the user attribute is defined\n    we can track the dependency on that file.\n\n    Putting every possible attribute in this list would be too slow so we restrict to a hand-crafted\n    list we found useful.\n    -/\ndef evidence_attrs : list name :=\n-- [`_can_lift, `_ext_core, `_ext_lemma_core, `_localized, `_refl_lemma, `_simp.sizeof, `_simp_cache, `_simps_str, `_squeeze_loc, `algebra, `alias, `ancestor, `breakpoint, `class, `congr, `continuity, `derive, `derive_handle, `elab_as_eliminator, `elab_simple, `elab_strategy, `elab_with_expected_type, `elementwise, `ematch, `ematch_lhs, `equiv_rw_simp, `ext, `field_simps, `functor_norm, `ghost_simps, `higher_order, `hint_tactic, `hole_command, `inline, `instance, `integral_simps, `interactive, `intro, `inverse, `irreducible, `is_poly, `library_note, `linter, `main_declaration, `measurability, `mfld_simps, `mk_iff, `monad_norm, `mono, `monotonicity, `no_inst_pattern, `no_rsimp, `nolint, `nontriviality, `norm, `norm_cast, `norm_num, `notation_class, `obviously, `parity_simps, `parsing_only, `pattern, `pp_nodot, `pp_using_anonymous_constructor, `pre_smt, `protect_proj, `protected, `push_cast, `reassoc, `recursor, `reducibility, `reducible, `refl, `replaceable, `rewrite, `rsimp, `semireducible, `simp, `simps, `split_if_reduction, `subst, `sugar, `sugar_nat, `symm, `tactic_doc, `tidy, `to_additive, `to_additive_aux, `to_additive_ignore_args, `to_additive_relevant_arg, `to_additive_reorder, `trans, `transport_simps, `typevec, `unify, `user_attribute, `user_command, `user_notation, `vm_monitor, `vm_override, `wrapper_eq, `zify]\n-- [`_ext_core, `_ext_lemma_core, `alias, `ancestor, `congr, `continuity, `elementwise, `ematch, `equiv_rw_simp, `ext, `field_simps, `functor_norm, `ghost_simps, `higher_order, `integral_simps, `interactive, `intro, `inverse, `irreducible, `is_poly, `library_note, `linter, `main_declaration, `measurability, `mfld_simps, `mk_iff, `monad_norm, `mono, `monotonicity, `no_inst_pattern, `no_rsimp, `nolint, `nontriviality, `norm, `norm_cast, `norm_num, `notation_class, `obviously, `parity_simps, `pattern, `pp_nodot, `protect_proj, `protected, `push_cast, `reassoc, `recursor, `reducibility, `reducible, `refl, `replaceable, `rewrite, `rsimp, `semireducible, `simp, `simps, `split_if_reduction, `subst, `symm, `tactic_doc, `tidy, `to_additive, `trans, `transport_simps, `unify, `user_attribute, `user_command, `zify]\n[`ext,\n `simps,\n `continuity,\n `mono,\n `_localized, -- sadly this only makes files that depend on localized not remove, TODO localized still\n `nolint,\n `to_additive,\n `protect_proj,\n `linter,\n `higher_order, -- TODO double check\n `derive_handler, -- TODO double check\n `deriver, -- TODO double check\n `hint_tactic,\n `obviously,\n `ancestor,\n `norm_cast,\n `nontriviality,\n `measurability,\n `mk_iff,\n `tidy\n ]\n-- TODO map to get prios also\n/-- get the attributes on a decl that tell us about necessary imports. -/\nmeta def get_decl_evidence_attrs (decna : name) : tactic $ list name :=\nevidence_attrs.mfilter (\u03bb ana, do (tactic.has_attribute ana decna >> return tt) <|> return ff)\n\n/-- Convert an import name like `data.list.defs` to a filename by appending a prefix `pre`.\n    `pre` should have a slash at the end, this does not check that a real file exists, so\n    if `foo.blah` refers to `/files/mathlib/src/foo/bar/default.lean` this will not be the right\n    filename. -/\ndef import_to_file (pre : string) (im : name) : string :=\npre ++ im.to_string_with_sep \"/\" ++ \".lean\"-- TODO windows lol\n\nsection\nopen name\n/-- Remove default from the end of an (import) `name`. -/\ndef name.remove_default : name \u2192 name\n| (mk_string \"default\" p) := p\n| p := p\nend\n\n/-- A hackish way to get the `src` directory of any project.\n  Requires as argument any declaration name `n` in that project, and `k`, the number of characters\n  in the path of the file where `n` is declared not part of the `src` directory.\n  Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`.\n  Note: does not work in the file where `n` is declared.\n  This is copied from mathlib but abstracts over the environment instead.\n   -/\nmeta def environment.get_project_dir (e : environment) (n : name) (k : \u2115) : string :=\n(do\n  s \u2190 e.decl_olean n,\n  return $ s.popn_back k).get_or_else sformat!\"Hello! I'm {n} trapped in an error string, please let me out\"\n\n/-- A hackish way to get the `src` directory of mathlib.\n    This is copied from mathlib but abstracts over the environment instead.  -/\nmeta def environment.get_mathlib_dir (e : environment) : string :=\ne.get_project_dir `mathlib_dir_locator 23\n\n/-- A hackish way to get the `src` directory of core.\n    This is copied from mathlib but abstracts over the environment instead.  -/\nmeta def environment.get_core_dir (e : environment) : string :=\ne.get_project_dir `nat 14\n\n/-- Checks whether a declaration with the given name is declared in mathlib.\nIf you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,\nsince it is expensive to execute `get_mathlib_dir` many times. -/\nmeta def environment.is_in_mathlib (e : environment) (n : name) : bool :=\ne.is_prefix_of_file e.get_mathlib_dir n\n\n@[derive inhabited]\nstructure import_data : Type :=\n(decl_name : name)\n(file_name : name)\n(file_pos : option pos)\n(deps : list name)\n\nlemma import_data.ext (d e : import_data) :\n  d = e \u2194 d.decl_name = e.decl_name \u2227 d.file_name = e.file_name \u2227 d.file_pos = e.file_pos \u2227 d.deps = e.deps :=\nbegin\n  split, { intro h, cases h, repeat { split, refl }, refl },\n  cases d, cases e, dsimp, intro h,\n  repeat { cases h with h' h, cases h' },\n  cases h', congr,\nend\n\n-- attribute [derive inhabited] pos\nmeta instance : has_lt import_data := \u27e8\u03bb n m, n.decl_name < m.decl_name\u27e9\nmeta instance : decidable_eq import_data :=\nbegin\n  intros d e, cases d, cases e,\n  rw import_data.ext,\n  dsimp,\n  apply_instance,\nend\n\nmeta instance : has_to_format import_data :=\n  \u27e8\u03bb i, to_fmt i.decl_name\n        ++ \" : \" ++ to_fmt i.file_name\n        ++ \" : \" ++ to_fmt (i.file_pos.iget)\n        ++ \" : \" ++ to_fmt (i.deps)\n        \u27e9\n\nmeta instance : has_to_string import_data :=\n\u27e8\u03bb b, to_string $ to_fmt b\u27e9\n\nmeta instance : has_to_tactic_format import_data :=\n\u27e8\u03bb b, return $ to_fmt b\u27e9\n\nmeta def get_attr_deps (n : name) : tactic (list name) :=\ndo\n  ll \u2190 get_decl_evidence_attrs n,\n  ll.mmap_filter (\u03bb n, do (option.some <$> get_user_attribute_name n) <|> return none)\n  -- o \u2190  ll.mmap_filter (\u03bb ana, pure $ get_user_attribute_name ana),\n  -- return o\n\n/-- Given a declaration `decl` return a structure of its name, position, list of dependent decl\n    names and filename.\n    Note that the dependent decl names includes the names of decls needed to declare the attributes\n    on `decl`, that means that `decl` may originally have been defined without all of the\n    dependent declarations returned by this function imported, and it may be necessary to prune this\n    list.  -/\nmeta def mk_data (env : environment) (fname : name)\n  (decl : declaration) : tactic import_data :=\nlet na := decl.to_name,\n    po := env.decl_pos na\n    --fname := file_to_import $ file_name $ env.decl_olean na\n    in\n  (\u03bb attrd,\n    { decl_name := na,\n      file_name := fname,\n      file_pos := po,\n      deps := -- dont even consider quot and friends\n        (list_items decl.type ++ list_items decl.value ++ attrd).dedup.diff magic_homeless_decls, }) <$>\n  get_attr_deps na\n\n-- #eval (\u03bb inp : list nat, do l \u2190 inp, guardb (l = 1), pure l) [1,2]\n-- meta def aa (env : environment) (fname : name) (file_to_import : string \u2192 name) : list declaration \u2192 tactic (list import_data)\n-- | (d :: l) :=\n-- let fn_string := import_to_file env.get_mathlib_dir fname in\n-- aa l >>= (\n--   if (env.decl_olean d.to_name = fn_string) then\n--  (do\n--   of \u2190 mk_data env file_to_import fname d,\n--     ((::) of ))\n--     else\n--  id)\n-- | [] := pure []\n/-- Creates an import data tuple for every declaration in file `fname`. -/\nmeta def get_file_data (env : environment) (fname : name) (proj_dir : string := env.get_mathlib_dir) :\n  tactic $ list import_data :=\nlet fn_string := import_to_file proj_dir fname in\n-- aa env fname file_to_import env.get_decls\n-- (\u03bb decls : list declaration, do d \u2190 decls,\n--   guardb (env.decl_olean d.to_name = fn_string) >>\n--   mk_data env file_to_import fname d,\n--   skip\n-- ) env.get_decls\n  -- (\u03bb d : declaration, env.decl_olean d.to_name = fn_string)).mmap\n    -- (mk_data env file_to_import fname)\n(env.get_decls.filter\n  (\u03bb d : declaration, env.decl_olean d.to_name = fn_string)).mmap\n    (mk_data env fname)\n\n-- /-- Given a declaration return a structure of its name, position, list of dependent decl names and\n--     filename. -/\n-- meta def mk_data (env : environment) (file_to_import : string \u2192 name)\n--   (decl : declaration) (na : name) : tactic import_data :=\n-- let po := env.decl_pos na,\n--     fname := file_to_import $ file_name $ env.decl_olean na in\n--   (\u03bb attrd,\n--     { decl_name := na,\n--       file_name := fname,\n--       file_pos := po,\n--       deps := (list_items decl.type ++ list_items decl.value ++ attrd).dedup, }) <$>\n--   get_attr_deps env na\n\n-- /-- Creates an import data tuple for every declaration in file `fname`. -/\n-- meta def get_file_data (env : environment) (fname : name) (file_to_import : string \u2192 name) :\n--   tactic $ list import_data :=\n-- let fn_string := import_to_file env.get_mathlib_dir fname in\n-- env.get_decls.mmap_filter (\u03bb d, let na := d.to_name in if\n--   env.decl_olean na = fn_string then\n--     option.some <$> mk_data env d na else none)\n\nopen native\n/-- Creates a dag of input data. -/\nmeta def mk_file_dag_of_file_data (fdata : rb_map name import_data) :\n  dag import_data :=\n-- let fdata := mk_file_data env fname file_to_import,\n  -- let decl_names := fdata.map import_data.decl_name in\nfdata.fold\n  (dag.mk _)\n  (\u03bb _ id G,\n    id.deps.foldl\n      (\u03bb G2 dep,\n        ((fdata.find dep).map -- todo maybe replace with an rb_map\n          (\u03bb a, G2.insert_edge a id)).get_or_else G2)\n      (G.insert_vertex id))\n\nsection rb_counter\nopen native\nvariables (T : Type)\nmeta def rb_counter := rb_map T \u2115\nnamespace rb_counter\nvariable {T}\nmeta def incr_by (t : T) (n : \u2115) (A : rb_counter T) : rb_counter T :=\nrb_map.insert A t ((rb_map.zfind A t) + n)\nmeta def incr (t : T) (A : rb_counter T) : rb_counter T := A.incr_by t 1\nmeta def mk (key : Type) [has_lt key] [decidable_rel ((<) : key \u2192 key \u2192 Prop)] : rb_counter key :=\nrb_map.mk _ _\n\nmeta instance [has_to_format T] : has_to_format (rb_counter T) := rb_map.has_to_format\nmeta instance [has_to_string T] : has_to_string (rb_counter T) := rb_map.has_to_string\nmeta instance {R : Type*} [has_to_string T] [has_to_string R]: has_to_string (rb_lmap T R) := rb_map.has_to_string\nend rb_counter\nend rb_counter\n\nopen native\n\n-- meta def dfs_all_paths' {T : Type*} [has_lt T] [decidable_rel ((<) : T \u2192 T \u2192 Prop)] [decidable_eq T] (d : dag T)\n--   : T \u2192 (list (list T) \u00d7 rb_set T) \u2192 (list (list T) \u00d7 rb_set T)\n-- -- vertex and stack, visited pair\n-- | v stavis :=\n--   (\u03bb a : list (list T) \u00d7 rb_set T, (a.fst.map ((::) v), a.snd))\n--     ((d.find v).foldl\n--       (\u03bb stavis' w,\n--         if stavis'.snd.contains w then\n--           stavis'\n--         else\n--           dfs_all_paths' w stavis')\n--       (stavis.fst, stavis.snd.insert v))\n\n-- TODO convert this to use the `dfs` function\n/-- Depth first search all paths. -/\nmeta def dfs_all_paths {T : Type*} [has_lt T] [decidable_rel ((<) : T \u2192 T \u2192 Prop)]\n  (d : dag T) : T \u2192 rb_lmap T (list T) \u2192 rb_lmap T (list T)\n| v paths :=\n  if paths.contains v then paths else\n    let npaths := (d.find v).foldl (\u03bb opaths de, dfs_all_paths de opaths) paths in\n    rb_map.insert npaths v $ (d.find v).foldl (\u03bb acc de,\n      let dep_paths := (npaths.find de) in\n      acc ++ dep_paths.map ((::) v)) []\n    -- (d.find v).foldl (\u03bb opaths de, rb_map.insert opaths v _) npaths\n    -- rb_map.insert npaths v $ (npaths.find de).map ((::) v) _\n    -- (d.find v).foldl (\u03bb opa de,\n    -- let npa :=\n    --   if paths.contains de then opa else dfs_all_paths de opa in\n    --     rb_map.insert npa v $ (npa.find de).map ((::) v)) paths\n      -- else\n      --   (dfs_all_paths de opa).map (\u03bb p, v :: p)) paths\n  -- let a := ((d.find v).foldl\n      -- (\u03bb (rea' : rb_map T (list T)) w, let n :=\n      --   if rea'.contains w then\n      --     rea'\n      -- ()  else\n      --     dfs_reach_table w rea' in\n      --   n.insert v $ (((n.find v).get_or_else mk_rb_set).union $ (n.find w).get_or_else mk_rb_set))\n      -- rea) in a.insert v $ ((a.find v).get_or_else mk_rb_set).insert v\n\n-- TODO convert this to use the `dfs` function\n/-- Find all paths from `src` to `target` in the dag, not used currently but helpful for debugging-/\nmeta def dag.all_paths {T : Type*} [has_lt T] [decidable_rel ((<) : T \u2192 T \u2192 Prop)]\n  (d : dag T) (src tgt : T) : list (list T) :=\n(dfs_all_paths d src $ (mk_rb_map).insert tgt [[tgt]]).find src\n\n-- run_cmd (do\n--   e \u2190 get_env,\n--   G \u2190 unsafe_run_io $ get_import_dag e `algebra.group_power.lemmas,\n--   trace (all_paths G `data.int.cast `data.equiv.basic),\n  -- skip)\n\n-- #eval all_paths ((dag.mk \u2115).insert_edges [(1, 5), (3, 2), (4,5), (2,5), (5,6),(5,8),(8,7),(8,6), (5,19),(19,7), (6,7)]) 1 7\n\nmeta def dag.count_descendents {T : Type*} [has_lt T] [decidable_rel ((<) : T \u2192 T \u2192 Prop)]\n  [decidable_eq T] (d : dag T) (start : list T) : \u2115 :=\nd.dfs (\u03bb _, nat.succ) 0 start\n\nmeta def dag.count_all_descendents {T : Type*} [has_lt T] [decidable_rel ((<) : T \u2192 T \u2192 Prop)]\n  [decidable_eq T] (d : dag T) (start : list T := d.vertices) : rb_counter T :=\nd.dfs (\u03bb v acc, acc.insert v $ 1 + ((d.find v).map $ \u03bb de, acc.zfind de).sum) mk_rb_map start\n-- #eval count_descendents (((dag.mk \u2115).insert_vertex 3).insert_edges [(1, 5), (4,5), (2,5)]) ([1,4,3])\n\nopen tactic native\n\n/-- -/\nmeta def mk_file_dep_counts_basic (env : environment) (fname : name) (file_to_import : string \u2192 name)\n  (fdata : rb_map name import_data) :\n  rb_counter name :=\nlet G := mk_file_dag_of_file_data fdata,\n    Gr := G.count_all_descendents in\n(Gr.fold (rb_counter.mk _) (\u03bb k d o, k.deps.foldl\n  (\u03bb o2 dep,\n    let imp := file_to_import $ file_name $ env.decl_olean dep in\n    if \u00ac (`init).is_prefix_of imp then\n      o2.incr_by imp d\n    else\n      o2) o)).erase fname -- erase the file itself as most likely it will depend on itself\n\n/-- parse a files imports by reading the first few lines of the file.\n  Note this function is quite brittle, some examples of things that probably break it but are valid\n  lean. Most of these are banned / not done in mathlib though\n\n  TODO handle relative imports, e.g. `import .blah` this is done once in mathlib (in tests), or\n    remove from mathlib\n```\n  /-hi-/ import tactic\n  import algebra.add_torsor\n-- asddd\nimport data.list.basic\n```\n  -/\nmeta def get_imports_aux : handle \u2192 bool \u2192 io (list name)\n| f b :=\ndo\n  eo \u2190 io.fs.is_eof f,\n  if eo then return []\n  else do\n    l \u2190 f.get_line_as_string,\n    let ls := l.split_on ' ',\n    -- if ls.tail.head = \"graph.\" hen return [] else --stupid hack around the file reserved notation\n    (if ls.head = \"import\" then\n      do a \u2190 get_imports_aux f tt,\n        return ((((ls.tail.split_on_p (\u03bb s, \"--\".is_prefix_of s)).head.filter (\u2260 \"\")).map\n          name.from_string).map name.remove_default ++ a) -- space separated lists on imports (in core)\n    else\n      -- stop parsing imports if we see a non-newline line after seeing an import already\n      -- or if we see a module docstring header\n      if (b \u2227 l \u2260 \"\\n\") \u2228 \"/-!\".is_prefix_of l then\n        return []\n      else\n        get_imports_aux f b)\n\nmeta def get_imports (e : environment) (file : name) (project_dir : string := e.get_mathlib_dir) :\n  io (list name) :=\ndo\n  -- get the file handle by trying a bunch of possibilities in order\n  f \u2190 mk_file_handle (import_to_file e.get_mathlib_dir file) io.mode.read <|>\n      mk_file_handle (import_to_file e.get_mathlib_dir $ file.append `default) io.mode.read <|>\n      mk_file_handle (import_to_file project_dir file) io.mode.read <|>\n      mk_file_handle (import_to_file project_dir $ file.append `default) io.mode.read <|>\n      mk_file_handle (import_to_file e.get_core_dir file) io.mode.read <|>\n      mk_file_handle (import_to_file e.get_core_dir $ file.append `default) io.mode.read,\n  l \u2190 get_imports_aux f ff,\n  fs.close f,\n  return l\n\nopen io io.fs\n/-- Checks whether the import given by name `file` refers to a default file, this simply checks if\n    the corresponding filename with default appended appears in either mathlib or core.\n    Note that if default is already a prefix of the file this does the wrong thing.\n    We assume all default suffixes are stripped. TODO maybe change this\n     -/\nmeta def is_default (e : environment) (file : name) : io bool :=\ndo\n  bm \u2190 file_exists $ import_to_file e.get_mathlib_dir $ file.append `default,\n  bc \u2190 file_exists $ import_to_file e.get_core_dir $ file.append `default,\n  return $ bm \u2228 bc\n\n/-- Checks whether the file whose import name is `file` is in the mathlib directory.\n    Compare `environment.is_in_mathlib` which checks if a declaration is in mathlib. -/\nmeta def file_is_in_mathlib (e : environment) (file : name) : io bool :=\ndo\n  b \u2190 file_exists $ import_to_file e.get_mathlib_dir $ file,\n  if b then return tt else do\n    bd \u2190 file_exists $ import_to_file e.get_mathlib_dir $ file.append `default,\n    return $ bd\n\n/-- Checks whether the file whose import name is `file` is in the project directory.\n    Compare `environment.is_in_mathlib` which checks if a declaration is in mathlib. -/\nmeta def file_is_in_project (file : name) (project_dir : string) : io bool :=\ndo\n  b \u2190 file_exists $ import_to_file project_dir $ file,\n  if b then return tt else do\n  bd \u2190 file_exists $ import_to_file project_dir $ file.append `default,\n  return $ bd\n\n/-- Auxiliary function to make the import dag. -/\nmeta def get_dag_aux (e : environment) (project_dir : string) :\n  name \u2192 dag name \u2192 io (dag name)\n| n d := do\nif d.contains n then return d else do\n  l \u2190 get_imports e n project_dir,\n  l.mfoldl (\u03bb od im, do\n    G \u2190 get_dag_aux im od,\n    return $ G.insert_edge n im) d\n\n/-- get a dag of all imports between files with edges from later dependencies to earlier.\n   the environment is used to find the location of files, to parse their imports -/\nmeta def get_import_dag (e : environment) (files : list name) (project_dir : string := e.get_mathlib_dir) :\n  io (dag name) :=\nfiles.mfoldl (\u03bb ol file, get_dag_aux e project_dir file ol) (dag.mk _)\n\nopen native\n-- TODO we should probably not pass this function around anymore\n/-- Given an environment creates a function `file_to_import` that translates a filename into an\n    import `name`.\n    We remove `default` by default.\n    E.g. this will send\n    `/users/alex/mathlib/src/group_theory/subgroup/default.lean` to `group_theory.subgroup`. -/\nmeta def mk_file_to_import (e : environment) (proj_pre : string := \"this will never be a prefix\") :\n  string \u2192 name :=\nlet mathlib_pre := e.get_mathlib_dir,\n    core_pre := e.get_core_dir in\n\u03bb file,\n  let rest := (file.get_rest mathlib_pre).get_or_else $ -- take off the mathlib or core prefix\n              (file.get_rest proj_pre).get_or_else $\n              (file.get_rest core_pre).get_or_else $\n              sformat!\"Hello, I'm {file} trapped in an error string, please let me out\" in\n  (name.from_components -- create the name from the suffix\n    ((rest.popn_back 5 -- remove the `.lean` suffix\n      ).split_on '/')).remove_default\n\nmeta def mk_file_dep_counts (env : environment) (fname : name) (Gr : rb_map name (rb_set name))\n  (fdata : rb_map name import_data) (proj_pre : string := \"this will never be a prefix\") :\n  rb_counter name :=\nlet file_to_import := mk_file_to_import env proj_pre,\n    dcb := mk_file_dep_counts_basic env fname file_to_import fdata,\n    -- now we copy accross only those deps which were transitive imports of the original, to prevent\n    -- spurious deps being added\n    dc : rb_counter name := (Gr.ifind fname).fold mk_rb_map (\u03bb dn acc, acc.insert dn $ dcb.zfind dn)\n     in\n  (dc.fold dc\n    (\u03bb nam co acc, (Gr.ifind nam).fold acc (\u03bb de acc', acc'.incr_by de $ dc.zfind nam))).erase fname\n  -- return $ (Gr.fold dc (\u03bb na ln odc, ln.fold odc (\u03bb de odc', odc'.incr_by de ((dc.find na).get_or_else 0)))).erase fname\n\nmeta def get_minimal_imports (e : environment) (n : name) (G : dag name) (Gr : rb_map name (rb_set name))\n  (fdata : rb_map name import_data) (proj_pre : string := \"this will never be a prefix\") (robust : bool := tt) :\n  rb_set name :=\n  let b := mk_file_dep_counts e n Gr fdata proj_pre in\n  G.minimal_vertices $\n    (b.keys.filter (\u03bb k, b.find k \u2260 some 0)).union $ -- the needed imports\n      ((Gr.find n).iget).to_list.filter\n        -- if \"robust\" add some extra original imports back so we never remove imports from tactics\n        -- this is a heuristic but quite effective\n        (\u03bb dn, robust \u2227 dn \u2260 n \u2227 ((`tactic).is_prefix_of dn \u2228 dn = `data.rbtree.default_lt))\n\nmeta def optimize_imports (e : environment) (nam : name) (G : dag name) (Gr := G.reachable_table)\n  (fdata : rb_map name import_data) (proj_pre : string := \"this will never be a prefix\") :\n  name \u00d7 list name \u00d7 \u2115 :=\n  let new_imp := get_minimal_imports e nam G Gr fdata proj_pre in\n  (nam,\n  --  old_imp.qsort (\u03bb a b, a.to_string < b.to_string : name \u2192 name \u2192 bool),\n   new_imp.to_list,\n  --  G.count_descendents (old_imp : list name),\n   G.count_descendents (new_imp.keys : list name))\n\n/-- Convert the output of `optimize_imports` into a sed script for removing these imports. Note:\n  * This clobbers import comments\n  * Mac users should replace `sed` with `gsed` (via homebrew) in the script to ensure it works\n  * This pipes to stdout by default, append `-i` after every `sed` to replace in-place\n\n  We add the decidable_eq name argument so this function stays non-meta, this is probably pointless\n  but it just feels weird to have this function meta.\n-/\nmeta def output_to_sed [decidable_eq name] -- TODO remove numbers\n (o : name \u00d7 rb_set name \u00d7 rb_set name \u00d7 rb_set name \u00d7 \u2115 \u00d7 \u2115) : string :=\nlet \u27e8na, ol, ne, dif, oli, nei\u27e9 := o,\n    fn := na.to_string_with_sep \"/\",\n    -- https://unix.stackexchange.com/questions/342516/sed-remove-all-matches-in-the-file-and-insert-some-lines-where-the-first-match\n    ne2 := ne.to_list,\n    ol2 := ol.to_list,\n    imps := \"\\\\\\n\".intercalate $ (ne2.map (\u03bb i, sformat!\"import {i}\")).qsort (\u03bb a b, a <  b) in\nif ne2 \u2260 ol2 then\nsformat!\"# {oli} \u2192 {nei} {ol2}, removed {dif.to_list}\\n\" ++\n-- (if oli = nei then \"# only transitive imports removed\\n\" else \"\") ++\n\"sed '/^import /{x;//!c\\\\\n\" ++ sformat!\"{imps}\n\" ++ \"d}' \" ++ sformat!\"src/{fn}.lean\\n\"\nelse \"\"\n\n-- set_option profiler true\n-- run_cmd unsafe_run_io (do\n--   e \u2190 run_tactic get_env,\n--   -- let L := [`all],\n-- --   -- let L := [`data.list.defs],\n-- --   let L := [`tactic.basic],\n-- --   -- let L := [`linear_algebra.affine_space.basic],\n-- --   -- let L := [`linear_algebra.matrix.determinant],\n--   let L := [`algebra.char_p.invertible],\n--   fdata \u2190 run_tactic $ get_file_data e L.head,\n--   print_ln fdata,\n--   G \u2190 get_import_dag e L,\n--   -- print_ln $ to_string G.size,\n--   -- print_ln $ to_fmt $ G.find `algebra.char_p.invertible,\n--   let Gr := G.reachable_table,\n--   let T := L.map (\u03bb nam, optimize_imports e nam G Gr fdata),\n--   -- print_ln $ to_fmt $ (G.reverse.reachable_table.find `linear_algebra.tensor_product).map (rb_set.size)\n--   -- print_ln $ to_fmt $ G.reverse.reachable_table.fold (mk_rb_map : rb_counter name) (\u03bb v es acc, acc.insert v es.size),\n--   print_ln $ to_string T\n--   )\n--   -- print_ln (to_fmt G),\n--   -- let file_to_import := mk_file_to_import e,\n--   -- let G' := mk_file_dag e `algebra.group_with_zero.basic file_to_import,\n--   -- print_ln G'.keys,\n--   -- print_ln $to_fmt G,\n--   let Gr := G.reachable_table,\n--   let T := L.map (\u03bb nam, optimize_imports e nam G Gr fdata),\n--   -- print_ln T,\n--   ((T.filter (\u03bb R : name \u00d7 list string \u00d7 list string \u00d7 \u2115 \u00d7 \u2115, R.2.2.1 \u2260 R.2.1 \u2227 R.2.2.2.2 \u2260 0)).map\n--     output_to_sed).mmap print_ln)\n\n-- run_cmd silly `group_theory.free_abelian_group\n-- run_cmd silly `algebra.module.linear_map -- quite successful\n-- run_cmd silly `data.fin.basic\n-- run_cmd silly `data.matrix.basic\n-- run_cmd silly `data.polynomial.field_division\n-- run_cmd silly `group_theory.perm.basic\n-- run_cmd silly `group_theory.perm.sign\n-- run_cmd silly `linear_algebra.coevaluation\n-- run_cmd silly `linear_algebra.dimension\n-- run_cmd silly `linear_algebra.eigenspace\n-- run_cmd silly `linear_algebra.matrix.determinant\n-- run_cmd silly `linear_algebra.matrix.transvection\n-- run_cmd silly `algebra.group_power.identities\n-- run_cmd silly `number_theory.number_field\n\n-- (\u03bb ana, do\n--   \u27e8b, prio\u27e9 \u2190 tactic.has_attribute ana decna,\n--   guardb b,\n--   return (ana, prio))\n", "meta": {"author": "alexjbest", "repo": "dag-tools", "sha": "3f38feb2d50ba191af6dd6977c6413e432688996", "save_path": "github-repos/lean/alexjbest-dag-tools", "path": "github-repos/lean/alexjbest-dag-tools/dag-tools-3f38feb2d50ba191af6dd6977c6413e432688996/src/import_optimizer.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199138751883, "lm_q2_score": 0.05184546371976374, "lm_q1q2_score": 0.013315573691556282}}
{"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 \u2190 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 \u2190 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) \u00d7 (Array String)) := do \n  let deps \u2190 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 \u2190  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 \u2190 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 \u2190 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 \u2190 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 \"{\u03b1 : Type u} [group \u03b1] [has_lt \u03b1] [covariant_class \u03b1 \u03b1 (function.swap has_mul.mul) has_lt.lt] {a : \u03b1} : 1 < a\u207b\u00b9 \u2194 a < 1\"\n\n\n/-- split prompts into those that parse -/\ndef promptsThmSplit : MetaM ((Array String) \u00d7 (Array String)) := do \n  let deps \u2190 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 \u2190  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) \u00d7 (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\u2081, `u\u2082, `W\u2081, `W\u2082, `w\u2081, `w\u2082, `u', `v', `uu, `w, `wE]\n\npartial def idents : Syntax \u2192 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 \u2190 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 (\u2190 getEnv) `term funStx with\n        | Except.ok termStx => Term.withLevelNames levelNames <|\n          try \n            let expr \u2190 Term.withoutErrToSorry <| \n                Term.elabTerm termStx none\n            return Except.ok expr\n          catch e => \n            return Except.error s!\"{\u2190 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 \u2194 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 \u2194 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\u2081 e\u2082 : Expr) : TermElabM Bool := do\n  let type \u2190 mkEq e\u2081 e\u2082\n  let mvar \u2190 mkFreshExprMVar <| some type\n  let mvarId := mvar.mvarId!\n  let stx \u2190 `(tactic| lynx;  try (rfl))\n  let res \u2190  runTactic mvarId stx\n  let (remaining, _) := res\n  return remaining.isEmpty\n\ndef provedEquiv (e\u2081 e\u2082 : Expr) : TermElabM Bool := do\n  try\n  let type \u2190 mkAppM ``Iff #[e\u2081, e\u2082]\n  let mvar \u2190 mkFreshExprMVar <| some type\n  let mvarId := mvar.mvarId!\n  let stx \u2190 `(tactic| intros; lynx at *<;> apply Iff.intro <;> intro hyp  <;> (lynx at *) <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp))\n  let res \u2190  runTactic mvarId stx\n  let (remaining, _) := res\n  return remaining.isEmpty\n  catch _ => pure false\n\n\ndef compareThms(s\u2081 s\u2082 : String)(opens: List String := []) \n  (levelNames : List Lean.Name := levelNames)\n  : TermElabM <| Except String Bool := do\n  let e\u2081 \u2190 elabThm s\u2081 opens levelNames\n  let e\u2082 \u2190 elabThm s\u2082 opens levelNames\n  match e\u2081 with\n  | Except.ok e\u2081 => match e\u2082 with\n    | Except.ok e\u2082 => \n        let p := (\u2190 provedEqual e\u2081 e\u2082) || \n          (\u2190 provedEquiv e\u2081 e\u2082)\n        return Except.ok p\n    | Except.error e\u2082 => return Except.error e\u2082\n  | Except.error e\u2081 => return Except.error e\u2081\n\ndef compareThmsCore(s\u2081 s\u2082 : String)(opens: List String := []) \n  (levelNames : List Lean.Name := levelNames)\n  : CoreM <| Except String Bool := \n    (compareThms s\u2081 s\u2082 opens levelNames).run'.run'\n\ndef compareThmExps(e\u2081 e\u2082: Expr)\n  : TermElabM <| Except String Bool := do\n      let p := (\u2190 provedEqual e\u2081 e\u2082) || \n        (\u2190 provedEquiv e\u2081 e\u2082)\n      return Except.ok p\n\ndef compareThmExpsCore(e\u2081 e\u2082: Expr)\n  : CoreM <| Except String Bool := do\n      (compareThmExps e\u2081 e\u2082).run'.run'\n\ndef equalThms(s\u2081 s\u2082 : String)(opens: List String := []) \n  (levelNames : List Lean.Name := levelNames)\n  : TermElabM Bool := do\n  match \u2190 compareThms s\u2081 s\u2082 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 \u2190 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 \u2190 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 \u2022 s\"\n\n-- #eval checkTerm \"\u03bb x : Nat, x + 1\"\n\n-- #eval checkTerm \"a - t = 0\"\n\n\ndef checkStatements : MetaM (List (String \u00d7 Bool)) := do\n  let prompts \u2190 depsPrompt\n  (prompts.toList.take 50).mapM fun s => \n    do return (s, \u2190 checkTerm s)\n\ndef tryParseThm (s : String) : MetaM String := do\n  let env \u2190 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 (\u03b1 : 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} : (\u2200 (x : K), x \u2208 l \u2192 x \u2208 s) \u2192 l.sum \u2208 s\"\n\ndef checkElabThm (s : String) : TermElabM String := do\n  let env \u2190 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 \u2190 Term.withoutErrToSorry <| \n                Term.elabTerm termStx none\n            pure s!\"elaborated: {\u2190 expr.view} from {funStx}\"\n          catch e => \n            pure s!\"{\u2190 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 \u2190 Term.withoutErrToSorry <| \n                Term.elabTerm termStx none\n            pure s!\"elaborated: {\u2190 expr.view} from {funStx}\"\n          catch e => \n            pure s!\"{\u2190 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 \u2190 Term.withoutErrToSorry <| \n                Term.elabTerm termStx none\n            pure s!\"elaborated: {\u2190 expr.view} from {funStx}\"\n          catch e => \n            pure s!\"{\u2190 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} : (\u2200 (x : K), x \u2208 l \u2192 x \u2208 s) \u2192 l.sum \u2208 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} : (\u2200 (x : K), x \u2208 l \u2192 x \u2208 s) \u2192 l.sum \u2208 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 \u2192  True\" \"{A: Type}: A \u2192  true\"\n\n-- #eval compareThms \": False\" \": false = true\"\n\n-- #eval compareThms \"{A: Sort} : False \u2192  A\" \"{A: Sort} : false = true \u2192  A\"\n\nexample : (\u2200 {A: Sort}, False \u2192 A) \u2194 (\u2200 {A: Sort}, false = true \u2192 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 : (\u2200 (a b c: Nat), \n  a + (b + c) = (a + b) + c) \u2194 (\u2200 (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 \u2192 list (expr elab) \u2192 list (expr elab) \u2192 mono_function\n | assoc : expr elab \u2192 option (expr elab) \u2192 option (expr elab) \u2192 mono_function\n | assoc_comm : expr elab \u2192 expr elab \u2192 mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function \u2192 tactic format\n | (mono_function.non_assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 mmap pp xs,\n  ys' \u2190 mmap pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 pp xs,\n  ys' \u2190 pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 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 \u2192 expr \u2192 expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr \u2192 expr \u2192 expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn  \u2190 pp ctx.function,\n   l   \u2190 pp ctx.left,\n   r   \u2190 pp ctx.right,\n   rel \u2190 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 \u2190 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 \u2192 expr \u2192 expr \u2192 tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) \u2190 return t | failed,\n   v \u2190 mk_meta_var d,\n   match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr \u2192 tactic expr\n| (expr.pi n _ t b) :=\ndo v \u2190 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 \u2192 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 \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 list expr)\n | es (x :: xs) := do\n    es' \u2190 delete_expr x es,\n    match es' with\n     | (some es') := do\n       (c,l,r) \u2190 match_ac' es' xs, return (x::c,l,r)\n     | none := do\n       (c,l,r) \u2190 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 \u00d7 list expr \u00d7 list expr) :=\ndo (s',l',r') \u2190 match_ac' l r,\n   s' \u2190 mmap instantiate_mvars s',\n   l' \u2190 mmap instantiate_mvars l',\n   r' \u2190 mmap instantiate_mvars r',\n   return (s',l',r')\n\nmeta def match_prefix\n: list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 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) \u2190 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 \u00d7 list expr \u00d7 list expr \u00d7 list expr) :=\ndo (pre,l\u2081,r\u2081) \u2190 match_prefix l r,\n   (suf,l\u2082,r\u2082) \u2190 match_prefix (reverse l\u2081) (reverse r\u2081),\n   return (pre,reverse l\u2082,reverse r\u2082,reverse suf)\n\nmeta def check_ac : expr \u2192 tactic (bool \u00d7 bool \u00d7 option (expr \u00d7 expr \u00d7 expr) \u00d7 expr)\n | (expr.app (expr.app f x) y) :=\n   do t \u2190 infer_type x,\n      a \u2190 try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n      c \u2190 try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n      i \u2190 try_core (do\n          v \u2190 mk_meta_var t,\n          l_inst_p \u2190 to_expr ``(is_left_id %%t %%f %%v),\n          r_inst_p \u2190 to_expr ``(is_right_id %%t %%f %%v),\n          l_v \u2190 mk_meta_var l_inst_p,\n          r_v \u2190 mk_meta_var r_inst_p ,\n          l_id \u2190 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 \u2190 mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n          mk_instance r_inst_p >>= unify r_v,\n          v' \u2190 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 \u2192 tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) \u2190 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 \u2192 tactic (list expr) :=\nmap dlist.to_list \u2218 parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) :\n  option (expr \u00d7 expr \u00d7 expr) \u2192 list expr \u2192 option (expr \u00d7 list expr)\n| _ (x::xs) := some (foldl (expr.app \u2218 expr.app op) x xs, [])\n| none []   := none\n| (some (l_id,r_id,x\u2080)) [] := some (x\u2080,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr \u2192 option expr\n| (x::xs) := some $ foldl (expr.app \u2218 expr.app op) x xs\n| []   := none\n\nmeta def same_function_aux\n: list expr \u2192 list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr)\n | xs\u2080 xs\u2081 (expr.app f\u2080 a\u2080) (expr.app f\u2081 a\u2081) :=\n   same_function_aux (a\u2080 :: xs\u2080) (a\u2081 :: xs\u2081) f\u2080 f\u2081\n | xs\u2080 xs\u2081 e\u2080 e\u2081 := is_def_eq e\u2080 e\u2081 >> return (e\u2080,xs\u2080,xs\u2081)\n\nmeta def same_function : expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr \u00d7 expr \u00d7 list expr \u00d7 mono_function) :=\ndo (full_f,ls,rs) \u2190 same_function l r,\n   (a,c,i,f) \u2190 check_ac l,\n   if a\n   then if c\n   then do\n     (s,ls,rs) \u2190 monad.join (match_ac\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 fold_assoc f i rs,\n     s' \u2190 fold_assoc1 f s,\n     return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n   else do -- a \u2227 \u00ac c\n     (pre,ls,rs,suff) \u2190 monad.join (match_assoc\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 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 -- \u00ac a\n     (xs\u2080,x\u2080,x\u2081,xs\u2081) \u2190 find_one_difference opt ls rs,\n     return (x\u2080,x\u2081,[],mono_function.non_assoc full_f xs\u2080 xs\u2081)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' \u2190 to_expr l,\n   r' \u2190 to_expr r,\n   parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr \u2192 tactic (expr \u00d7 expr \u00d7 list expr \u00d7 ac_mono_ctx)\n | `(%%e\u2080 \u2192 %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) \u2192 (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080 = %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) = (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080) e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     return (e\u2080, e\u2081, id_rs,\n            { function := f\n            , left := l, right := r\n            , to_rel := expr.app \u2218 expr.app rel\n            , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr)  : option expr \u2192 expr \u2192 expr\n| none e := e\n| (some e\u2080) e\u2081 := f.mk_app [e\u2080,e\u2081]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr \u2192 option expr \u2192 expr\n| e none := e\n| e\u2080 (some e\u2081) := f.mk_app [e\u2080,e\u2081]\n\nmeta def mk_fun_app : mono_function \u2192 expr \u2192 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\u2080,r\u2080) (r\u2081,l\u2081)` gives first how to find rules to prove\n      x+(y\u2080+z) R x+(y\u2081+z);\n      if that fails, helps prove (x+y\u2080)+z R (x+y\u2081)+z -/\n | assoc : expr \u00d7 expr \u2192 expr \u00d7 expr \u2192 mono_law\n   /- `congr r` gives the rule to prove `x = y \u2192 f x = f y` -/\n | congr : expr \u2192 mono_law\n | other : expr \u2192 mono_law\n\nmeta def mono_law.to_tactic_format : mono_law \u2192 tactic format\n | (mono_law.other e) := do e \u2190 pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e \u2190 pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\ndo x\u2080 \u2190 pp x\u2080,\n   x\u2081 \u2190 pp x\u2081,\n   y\u2080 \u2190 pp y\u2080,\n   y\u2081 \u2190 pp y\u2081,\n   return format!\"assoc {x\u2080}; {x\u2081} | {y\u2080}; {y\u2081}\"\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 \u2192 expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs\u2080 xs\u2081 : list expr) (l r : expr) : tactic expr :=\ndo p \u2190 mk_app `eq [fn.mk_app $ xs\u2080 ++ l :: xs\u2081,fn.mk_app $ xs\u2080 ++ r :: xs\u2081],\n   prod.snd <$> solve_aux p\n     (do iterate_exactly (xs\u2081.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\u2080 x\u2081) :=\n    if (x\u2080 <|> x\u2081).is_some\n       then mk_congr_args f x\u2080.to_monad x\u2081.to_monad ctx.left ctx.right\n       else failed\n | (mono_function.assoc_comm f x\u2080) := mk_congr_args f [x\u2080] [] ctx.left ctx.right\n | (mono_function.non_assoc f x\u2080 x\u2081) := mk_congr_args f x\u2080 x\u2081 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 (\u03bb i, bin_op f x (bin_op f i y))\n       , mk_rel ctx (\u03bb i, bin_op f i y))\n       ( mk_rel ctx (\u03bb i, bin_op f (bin_op f x i) y)\n       , mk_rel ctx (\u03bb i, bin_op f x i))\n    | (mono_function.assoc f (some x) none) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb e, mk_fun_app ctx.function e)\n    | (mono_function.assoc f none (some y)) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb 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 (\u03bb 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' \u2190 mk_const r,\n    t  \u2190 infer_type r',\n    t  \u2190 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 \u2192 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\u2080 x\u2081 : expr) : tactic (list expr) :=\ndo x' \u2190 to_expr ``(%%x\u2081 \u2192 %%x\u2080),\n   r\u2080 \u2190 find_lemma x' ls,\n   r\u2081 \u2190 find_lemma x\u2081 ls,\n   return (expr.app <$> r\u2080 <*> r\u2081)\n\nmeta def find_rule (ls : list name) : mono_law \u2192 tactic (list expr)\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\n(match_chaining_rules ls x\u2080 x\u2081)\n<|> (match_chaining_rules ls y\u2080 y\u2081)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x y : \u03b1}\n  (x' y' : \u03b1)\n  (h : R x y)\n  (hx : x = x')\n  (hy : y = y')\n: R x' y' :=\nby { rw [\u2190 hx,\u2190 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 \u2190 pp e,\n   asm \u2190 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 \u2190 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 \u00d7 expr) :=\ndo tgt \u2190 target,\n   t \u2190 infer_type v,\n   tgt' \u2190 do\n   { \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize v x >> target),\n     to_expr ``(\u03bb y : %%t, \u03a0 x, y = x \u2192 %%(tgt'.binding_body.lift_vars 0 1)) }\n   <|> to_expr ``(\u03bb y : %%t, \u03a0 x, %%v = x \u2192 %%tgt),\n   t \u2190 head_beta (tgt' v) >>= assert h,\n   swap,\n   r \u2190 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 \u2192 tactic unit) : tactic unit :=\nfocus1 $\ndo tgt \u2190 target >>= instantiate_mvars,\n   tactic.change tgt,\n   ctx \u2190 local_context,\n   let vs := tgt.list_meta_vars,\n   vs' \u2190 mmap (\u03bb v,\n             do h \u2190 get_unused_name `h,\n                x \u2190 get_unused_name `x,\n                prod.snd <$> monotonicity.generalize' h v x) vs,\n     tac ctx;\n     vs'.mmap' (try \u2218 tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ \u03bb _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   set_goals [v],\n   target >>= instantiate_mvars >>= tactic.change,\n   tac, done,\n   set_goals $ gs\n\ndef list.minimum_on {\u03b1 \u03b2} [linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : list \u03b1 \u2192 list \u03b1\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (\u03bb \u27e8k,a\u27e9 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 {\u03b2} (xs : list expr) (tac : expr \u2192 tactic \u03b2) : tactic unit :=\ndo t \u2190 target,\n   xs \u2190 xs.mmap (\u03bb 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 \u2218 prod.fst \u2218 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 \u2190 r.mmap (\u03bb \u27e8l,gs,_\u27e9,\n          do ts \u2190 gs.mmap infer_type,\n             msg \u2190 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 \u2190 target >>= instantiate_mvars,\n   ns \u2190 get_monotonicity_lemmas t dir,\n   asms \u2190 local_context,\n   rs \u2190 find_lemma asms t ns,\n   focus1 $ () <$ best_match rs (\u03bb law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (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 \u2190 hyps.mmap (\u03bb p, to_expr p >>= mk_meta_var),\n   hyps.mmap' (\u03bb pr, do h \u2190 get_unused_name `h, note h none pr),\n   when (\u00ac 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 \u2190 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 \u227c f y` into `x \u2264 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 $ \u03bb asms,\ndo try `[simp only [sub_eq_add_neg]],\n   tgt \u2190 target >>= instantiate_mvars,\n   (l,r,id_rs,g) \u2190 ac_monotonicity_goal cfg tgt\n             <|> fail \"monotonic context not found\",\n   ns \u2190 get_monotonicity_lemmas tgt both,\n   p \u2190 mk_pattern g,\n   rules \u2190 find_rule asms ns p <|> fail \"no applicable rules found\",\n   when (rules = []) (fail \"no applicable rules found\"),\n   err \u2190 format.join <$> mmap side_conditions rules,\n   focus1 $ best_match rules (\u03bb rule, do\n     t\u2080 \u2190 mk_meta_var `(Prop),\n     v\u2080 \u2190 mk_meta_var t\u2080,\n     t\u2081 \u2190 mk_meta_var `(Prop),\n     v\u2081 \u2190 mk_meta_var t\u2081,\n     tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v\u2080 %%v\u2081),\n     solve_mvar v\u2080 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     solve_mvar v\u2081 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     n \u2190 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 \u2192 tactic unit \u2192 tactic unit \u2192 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 \u2192 tactic unit \u2192 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 : \u2115) | many\n\nmeta def repeat_or_not : rep_arity \u2192 tactic unit \u2192 option (tactic unit) \u2192 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 \u2295 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 \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* := h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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? \u2192\n         opt_param mono_cfg { mono_cfg . } \u2192\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 \u2190 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": "/-\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 Init.Prelude\nimport Init.SizeOf\n\nuniverse u v w\n\ndef inline {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := a\n\n@[inline] def flip {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) : \u03b2 \u2192 \u03b1 \u2192 \u03c6 :=\n  fun b a => f a b\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 (\u03b1 : Type u) : Type u where\n  -- TODO: make private\n  fn : Unit \u2192 \u03b1\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 : \u03b1) : Thunk \u03b1 :=\n  \u27e8fun _ => a\u27e9\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 \u03b1) : \u03b1 :=\n  x.fn ()\n@[inline] protected def Thunk.map (f : \u03b1 \u2192 \u03b2) (x : Thunk \u03b1) : Thunk \u03b2 :=\n  \u27e8fun _ => f x.get\u27e9\n@[inline] protected def Thunk.bind (x : Thunk \u03b1) (f : \u03b1 \u2192 Thunk \u03b2) : Thunk \u03b2 :=\n  \u27e8fun _ => (f x.get).get\u27e9\n\nabbrev Eq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} {b : \u03b1} (h : a = b) (m : motive a) : motive b :=\n  Eq.ndrec m h\n\nstructure Iff (a b : Prop) : Prop where\n  intro :: (mp : a \u2192 b) (mpr : b \u2192 a)\n\ninfix:20 \" <-> \" => Iff\ninfix:20 \" \u2194 \"   => Iff\n\ninductive Sum (\u03b1 : Type u) (\u03b2 : Type v) where\n  | inl (val : \u03b1) : Sum \u03b1 \u03b2\n  | inr (val : \u03b2) : Sum \u03b1 \u03b2\n\ninductive PSum (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  | inl (val : \u03b1) : PSum \u03b1 \u03b2\n  | inr (val : \u03b2) : PSum \u03b1 \u03b2\n\nstructure Sigma {\u03b1 : Type u} (\u03b2 : \u03b1 \u2192 Type v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\nattribute [unbox] Sigma\n\nstructure PSigma {\u03b1 : Sort u} (\u03b2 : \u03b1 \u2192 Sort v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\ninductive Exists {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) : Prop where\n  | intro (w : \u03b1) (h : p w) : Exists p\n\n/- Auxiliary type used to compile `for x in xs` notation. -/\ninductive ForInStep (\u03b1 : Type u) where\n  | done  : \u03b1 \u2192 ForInStep \u03b1\n  | yield : \u03b1 \u2192 ForInStep \u03b1\n\nclass ForIn (m : Type u\u2081 \u2192 Type u\u2082) (\u03c1 : Type u) (\u03b1 : outParam (Type v)) where\n  forIn {\u03b2} [Monad m] (x : \u03c1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2\n\nexport ForIn (forIn)\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPRBC (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPR (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultBC (\u03c3 : Type u) where\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultBC \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultBC \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultSBC (\u03b1 \u03c3 : Type u) where\n  | \u00abpureReturn\u00bb : \u03b1 \u2192 \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abbreak\u00bb      : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abcontinue\u00bb   : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n\nclass HasEquiv  (\u03b1 : Sort u) where\n  Equiv : \u03b1 \u2192 \u03b1 \u2192 Sort v\n\ninfix:50 \" \u2248 \"  => HasEquiv.Equiv\n\nclass EmptyCollection (\u03b1 : Type u) where\n  emptyCollection : \u03b1\n\nnotation \"{\" \"}\" => EmptyCollection.emptyCollection\nnotation \"\u2205\"     => EmptyCollection.emptyCollection\n\n/- Remark: tasks have an efficient implementation in the runtime. -/\nstructure Task (\u03b1 : Type u) : Type u where\n  pure :: (get : \u03b1)\n  deriving Inhabited\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\ndef Priority.default : Priority := 0\n-- see `LEAN_MAX_PRIO`\ndef Priority.max : Priority := 8\n/--\n  Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.\n  This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more\n  non-dedicated workers than the number of cores to reduce context switches. -/\ndef Priority.dedicated : Priority := 9\n\n@[noinline, extern \"lean_task_spawn\"]\nprotected def spawn {\u03b1 : Type u} (fn : Unit \u2192 \u03b1) (prio := Priority.default) : Task \u03b1 :=\n  \u27e8fn ()\u27e9\n\n@[noinline, extern \"lean_task_map\"]\nprotected def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (x : Task \u03b1) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8f x.get\u27e9\n\n@[noinline, extern \"lean_task_bind\"]\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} (x : Task \u03b1) (f : \u03b1 \u2192 Task \u03b2) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8(f x.get).get\u27e9\n\nend Task\n\n/- Some type that is not a scalar value in our runtime. -/\nstructure NonScalar where\n  val : Nat\n\n/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/\ninductive PNonScalar : Type u where\n  | mk (v : Nat) : PNonScalar\n\ntheorem natAddZero (n : Nat) : n + 0 = n := rfl\n\ntheorem optParamEq (\u03b1 : Sort u) (default : \u03b1) : optParam \u03b1 default = \u03b1 := rfl\n\n/- Boolean operators -/\n\n@[extern c inline \"#1 || #2\"] def strictOr  (b\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\n@[extern c inline \"#1 && #2\"] def strictAnd (b\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\n\n@[inline] def bne {\u03b1 : Type u} [BEq \u03b1] (a b : \u03b1) : Bool :=\n  !(a == b)\n\ninfix:50 \" != \" => bne\n\n/- Logical connectives an equality -/\n\ndef implies (a b : Prop) := a \u2192 b\n\ntheorem implies.trans {p q r : Prop} (h\u2081 : implies p q) (h\u2082 : implies q r) : implies p r :=\n  fun hp => h\u2082 (h\u2081 hp)\n\ndef trivial : True := \u27e8\u27e9\n\ntheorem mt {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : \u00acb) : \u00aca :=\n  fun ha => h\u2082 (h\u2081 ha)\n\ntheorem notFalse : \u00acFalse := id\n\n-- proof irrelevance is built in\ntheorem proofIrrel {a : Prop} (h\u2081 h\u2082 : a) : h\u2081 = h\u2082 := rfl\n\ntheorem id.def {\u03b1 : Sort u} (a : \u03b1) : id a = a := rfl\n\n@[macroInline] def Eq.mp {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (a : \u03b1) : \u03b2 :=\n  h \u25b8 a\n\n@[macroInline] def Eq.mpr {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (b : \u03b2) : \u03b1 :=\n  h \u25b8 b\n\ntheorem Eq.substr {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : b = a) (h\u2082 : p a) : p b :=\n  h\u2081 \u25b8 h\u2082\n\ntheorem castEq {\u03b1 : Sort u} (h : \u03b1 = \u03b1) (a : \u03b1) : cast h a = a :=\n  rfl\n\n@[reducible] def Ne {\u03b1 : Sort u} (a b : \u03b1) :=\n  \u00ac(a = b)\n\ninfix:50 \" \u2260 \"  => Ne\n\nsection Ne\nvariable {\u03b1 : Sort u}\nvariable {a b : \u03b1} {p : Prop}\n\ntheorem Ne.intro (h : a = b \u2192 False) : a \u2260 b := h\n\ntheorem Ne.elim (h : a \u2260 b) : a = b \u2192 False := h\n\ntheorem Ne.irrefl (h : a \u2260 a) : False := h rfl\n\ntheorem Ne.symm (h : a \u2260 b) : b \u2260 a :=\n  fun h\u2081 => h (h\u2081.symm)\n\ntheorem falseOfNe : a \u2260 a \u2192 False := Ne.irrefl\n\ntheorem neFalseOfSelf : p \u2192 p \u2260 False :=\n  fun (hp : p) (h : p = False) => h \u25b8 hp\n\ntheorem neTrueOfNot : \u00acp \u2192 p \u2260 True :=\n  fun (hnp : \u00acp) (h : p = True) =>\n    have : \u00acTrue := h \u25b8 hnp\n    this trivial\n\ntheorem trueNeFalse : \u00acTrue = False :=\n  neFalseOfSelf trivial\n\nend Ne\n\nsection\nvariable {\u03b1 \u03b2 \u03c6 : Sort u} {a a' : \u03b1} {b b' : \u03b2} {c : \u03c6}\n\ntheorem HEq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} (m : motive a) {\u03b2 : Sort u2} {b : \u03b2} (h : a \u2245 b) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} {\u03b2 : Sort u2} {b : \u03b2} (h : a \u2245 b) (m : motive a) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.elim {\u03b1 : Sort u} {a : \u03b1} {p : \u03b1 \u2192 Sort v} {b : \u03b1} (h\u2081 : a \u2245 b) (h\u2082 : p a) : p b :=\n  eqOfHEq h\u2081 \u25b8 h\u2082\n\ntheorem HEq.subst {p : (T : Sort u) \u2192 T \u2192 Prop} (h\u2081 : a \u2245 b) (h\u2082 : p \u03b1 a) : p \u03b2 b :=\n  HEq.ndrecOn h\u2081 h\u2082\n\ntheorem HEq.symm (h : a \u2245 b) : b \u2245 a :=\n  HEq.ndrecOn (motive := fun x => x \u2245 a) h (HEq.refl a)\n\ntheorem heqOfEq (h : a = a') : a \u2245 a' :=\n  Eq.subst h (HEq.refl a)\n\ntheorem HEq.trans (h\u2081 : a \u2245 b) (h\u2082 : b \u2245 c) : a \u2245 c :=\n  HEq.subst h\u2082 h\u2081\n\ntheorem heqOfHEqOfEq (h\u2081 : a \u2245 b) (h\u2082 : b = b') : a \u2245 b' :=\n  HEq.trans h\u2081 (heqOfEq h\u2082)\n\ntheorem heqOfEqOfHEq (h\u2081 : a = a') (h\u2082 : a' \u2245 b) : a \u2245 b :=\n  HEq.trans (heqOfEq h\u2081) h\u2082\n\ndef typeEqOfHEq (h : a \u2245 b) : \u03b1 = \u03b2 :=\n  HEq.ndrecOn (motive := @fun (x : Sort u) _ => \u03b1 = x) h (Eq.refl \u03b1)\n\nend\n\ntheorem eqRecHEq {\u03b1 : Sort u} {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} : (h : a = a') \u2192 (p : \u03c6 a) \u2192 (Eq.recOn (motive := fun x _ => \u03c6 x) h p) \u2245 p\n  | rfl, p => HEq.refl p\n\ntheorem heqOfEqRecEq {\u03b1 \u03b2 : Sort u} {a : \u03b1} {b : \u03b2} (h\u2081 : \u03b1 = \u03b2) (h\u2082 : Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\u2081 = b) : a \u2245 b := by\n  subst h\u2081\n  apply heqOfEq\n  exact h\u2082\n\ntheorem castHEq {\u03b1 \u03b2 : Sort u} : (h : \u03b1 = \u03b2) \u2192 (a : \u03b1) \u2192 cast h a \u2245 a\n  | rfl, a => HEq.refl a\n\nvariable {a b c d : Prop}\n\ntheorem iffIffImpliesAndImplies (a b : Prop) : (a \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 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 \u2194 a :=\n  Iff.intro (fun h => h) (fun h => h)\n\ntheorem Iff.rfl {a : Prop} : a \u2194 a :=\n  Iff.refl a\n\ntheorem Iff.trans (h\u2081 : a \u2194 b) (h\u2082 : b \u2194 c) : a \u2194 c :=\n  Iff.intro\n    (fun ha => Iff.mp h\u2082 (Iff.mp h\u2081 ha))\n    (fun hc => Iff.mpr h\u2081 (Iff.mpr h\u2082 hc))\n\ntheorem Iff.symm (h : a \u2194 b) : b \u2194 a :=\n  Iff.intro (Iff.mpr h) (Iff.mp h)\n\ntheorem Iff.comm : (a \u2194 b) \u2194 (b \u2194 a) :=\n  Iff.intro Iff.symm Iff.symm\n\n/- Exists -/\n\ntheorem Exists.elim {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {b : Prop}\n   (h\u2081 : Exists (fun x => p x)) (h\u2082 : \u2200 (a : \u03b1), p a \u2192 b) : b :=\n  h\u2082 h\u2081.1 h\u2081.2\n\n/- Decidable -/\n\ntheorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=\n  match h with\n  | isTrue h  => rfl\n  | isFalse h => False.elim <| h \u27e8\u27e9\n\ntheorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=\n  match h with\n  | isFalse h => 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 p (h := d)\n\ntheorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=\n  decideEqTrue (s := d) h\n\ntheorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=\n  ofDecideEqTrue (s := d) h\n\ntheorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : \u00ac p :=\n  ofDecideEqFalse (s := d) h\n\ninstance : Decidable True :=\n  isTrue trivial\n\ninstance : Decidable False :=\n  isFalse notFalse\n\nnamespace Decidable\nvariable {p q : Prop}\n\n@[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p \u2192 q) (h2 : \u00acp \u2192 q) : q :=\n  match dec with\n  | isTrue h  => h1 h\n  | isFalse h => h2 h\n\ntheorem em (p : Prop) [Decidable p] : p \u2228 \u00acp :=\n  byCases Or.inl Or.inr\n\ntheorem byContradiction [dec : Decidable p] (h : \u00acp \u2192 False) : p :=\n  byCases id (fun np => False.elim (h np))\n\ntheorem ofNotNot [Decidable p] : \u00ac \u00ac p \u2192 p :=\n  fun hnn => byContradiction (fun hn => absurd hn hnn)\n\ntheorem notAndIffOrNot (p q : Prop) [d\u2081 : Decidable p] [d\u2082 : Decidable q] : \u00ac (p \u2227 q) \u2194 \u00ac p \u2228 \u00ac q :=\n  Iff.intro\n    (fun h => match d\u2081, d\u2082 with\n      | isTrue h\u2081,  isTrue h\u2082   => absurd (And.intro h\u2081 h\u2082) h\n      | _,           isFalse h\u2082 => Or.inr h\u2082\n      | isFalse h\u2081, _           => Or.inl h\u2081)\n    (fun (h) \u27e8hp, hq\u27e9 => 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@[inline] def  decidableOfDecidableOfIff (hp : Decidable p) (h : p \u2194 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@[inline] def  decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=\n  h \u25b8 hp\nend\n\n@[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p \u2192 q) :=\n  if hp : p then\n    if hq : q then isTrue (fun h => 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 \u2194 q) :=\n  if hp : p then\n    if hq : q then\n      isTrue \u27e8fun _ => hq, fun _ => hp\u27e9\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 \u27e8fun h => absurd h hp, fun h => absurd h hq\u27e9\n\n/- if-then-else expression theorems -/\n\ntheorem ifPos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = t :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem ifNeg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = e :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\ntheorem difPos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = t hc :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem difNeg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = e hnc :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\n-- Remark: dite and ite are \"defally equal\" when we ignore the proofs.\ntheorem difEqIf (c : Prop) [h : Decidable c] {\u03b1 : Sort u} (t : \u03b1) (e : \u03b1) : dite c (fun h => t) (fun h => e) = ite c t e :=\n  match h with\n  | isTrue hc   => rfl\n  | isFalse hnc => 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 hc  => dT\n  | isFalse hc => dE\n\ninstance {c : Prop} {t : c \u2192 Prop} {e : \u00acc \u2192 Prop} [dC : Decidable c] [dT : \u2200 h, Decidable (t h)] [dE : \u2200 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/- Inhabited -/\n\ninstance : Inhabited Prop where\n  default := True\n\nderiving instance Inhabited for NonScalar, PNonScalar, True, ForInStep\n\nclass inductive Nonempty (\u03b1 : Sort u) : Prop where\n  | intro (val : \u03b1) : Nonempty \u03b1\n\nprotected def Nonempty.elim {\u03b1 : Sort u} {p : Prop} (h\u2081 : Nonempty \u03b1) (h\u2082 : \u03b1 \u2192 p) : p :=\n  h\u2082 h\u2081.1\n\ninstance {\u03b1 : Sort u} [Inhabited \u03b1] : Nonempty \u03b1 where\n  val := arbitrary\n\ntheorem nonemptyOfExists {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : Exists (fun x => p x) \u2192 Nonempty \u03b1\n  | \u27e8w, h\u27e9 => \u27e8w\u27e9\n\n/- Subsingleton -/\n\nclass Subsingleton (\u03b1 : Sort u) : Prop where\n  intro :: allEq : (a b : \u03b1) \u2192 a = b\n\nprotected def Subsingleton.elim {\u03b1 : Sort u} [h : Subsingleton \u03b1] : (a b : \u03b1) \u2192 a = b :=\n  h.allEq\n\nprotected def Subsingleton.helim {\u03b1 \u03b2 : Sort u} [h\u2081 : Subsingleton \u03b1] (h\u2082 : \u03b1 = \u03b2) (a : \u03b1) (b : \u03b2) : a \u2245 b := by\n  subst h\u2082\n  apply heqOfEq\n  apply Subsingleton.elim\n\ninstance (p : Prop) : Subsingleton p :=\n  \u27e8fun a b => proofIrrel a b\u27e9\n\ninstance (p : Prop) : Subsingleton (Decidable p) :=\n  Subsingleton.intro fun\n    | isTrue t\u2081 => fun\n      | isTrue t\u2082  => rfl\n      | isFalse f\u2082 => absurd t\u2081 f\u2082\n    | isFalse f\u2081 => fun\n      | isTrue t\u2082  => absurd t\u2082 f\u2081\n      | isFalse f\u2082 => rfl\n\ntheorem recSubsingleton\n     {p : Prop} [h : Decidable p]\n     {h\u2081 : p \u2192 Sort u}\n     {h\u2082 : \u00acp \u2192 Sort u}\n     [h\u2083 : \u2200 (h : p), Subsingleton (h\u2081 h)]\n     [h\u2084 : \u2200 (h : \u00acp), Subsingleton (h\u2082 h)]\n     : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h\u2082 h\u2081) :=\n  match h with\n  | isTrue h  => h\u2083 h\n  | isFalse h => h\u2084 h\n\nstructure Equivalence {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Prop where\n  refl  : \u2200 x, r x x\n  symm  : \u2200 {x y}, r x y \u2192 r y x\n  trans : \u2200 {x y z}, r x y \u2192 r y z \u2192 r x z\n\ndef emptyRelation {\u03b1 : Sort u} (a\u2081 a\u2082 : \u03b1) : Prop :=\n  False\n\ndef Subrelation {\u03b1 : Sort u} (q r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  \u2200 {x y}, q x y \u2192 r x y\n\ndef InvImage {\u03b1 : Sort u} {\u03b2 : Sort v} (r : \u03b2 \u2192 \u03b2 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b1 \u2192 Prop :=\n  fun a\u2081 a\u2082 => r (f a\u2081) (f a\u2082)\n\ninductive TC {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : \u03b1 \u2192 \u03b1 \u2192 Prop where\n  | base  : \u2200 a b, r a b \u2192 TC r a b\n  | trans : \u2200 a b c, TC r a b \u2192 TC r b c \u2192 TC r a c\n\n/- Subtype -/\n\nnamespace Subtype\ndef existsOfSubtype {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : { x // p x } \u2192 Exists (fun x => p x)\n  | \u27e8a, h\u27e9 => \u27e8a, h\u27e9\n\nvariable {\u03b1 : Type u} {p : \u03b1 \u2192 Prop}\n\nprotected theorem eq : \u2200 {a1 a2 : {x // p x}}, val a1 = val a2 \u2192 a1 = a2\n  | \u27e8x, h1\u27e9, \u27e8_, _\u27e9, 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 {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} {a : \u03b1} (h : p a) : Inhabited {x // p x} where\n  default := \u27e8a, h\u27e9\n\ninstance {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [DecidableEq \u03b1] : DecidableEq {x : \u03b1 // p x} :=\n  fun \u27e8a, h\u2081\u27e9 \u27e8b, h\u2082\u27e9 =>\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 {\u03b1 : Type u} {\u03b2 : Type v}\n\ninstance Sum.inhabitedLeft [h : Inhabited \u03b1] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inl arbitrary\n\ninstance Sum.inhabitedRight [h : Inhabited \u03b2] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inr arbitrary\n\ninstance {\u03b1 : Type u} {\u03b2 : Type v} [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (Sum \u03b1 \u03b2) := fun a b =>\n  match a, b with\n  | Sum.inl a, Sum.inl b =>\n    if h : a = b then isTrue (h \u25b8 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 \u25b8 rfl)\n    else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h\n  | Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h\n  | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h\n\nend\n\n/- Product -/\n\ninstance [Inhabited \u03b1] [Inhabited \u03b2] : Inhabited (\u03b1 \u00d7 \u03b2) where\n  default := (arbitrary, arbitrary)\n\ninstance [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (\u03b1 \u00d7 \u03b2) :=\n  fun (a, b) (a', b') =>\n    match decEq a a' with\n    | isTrue e\u2081 =>\n      match decEq b b' with\n      | isTrue e\u2082  => isTrue (e\u2081 \u25b8 e\u2082 \u25b8 rfl)\n      | isFalse n\u2082 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2082' n\u2082\n    | isFalse n\u2081 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2081' n\u2081\n\ninstance [BEq \u03b1] [BEq \u03b2] : BEq (\u03b1 \u00d7 \u03b2) where\n  beq := fun (a\u2081, b\u2081) (a\u2082, b\u2082) => a\u2081 == a\u2082 && b\u2081 == b\u2082\n\ninstance [LT \u03b1] [LT \u03b2] : LT (\u03b1 \u00d7 \u03b2) where\n  lt s t := s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)\n\ninstance prodHasDecidableLt\n    [LT \u03b1] [LT \u03b2] [DecidableEq \u03b1] [DecidableEq \u03b2]\n    [(a b : \u03b1) \u2192 Decidable (a < b)] [(a b : \u03b2) \u2192 Decidable (a < b)]\n    : (s t : \u03b1 \u00d7 \u03b2) \u2192 Decidable (s < t) :=\n  fun t s => inferInstanceAs (Decidable (_ \u2228 _))\n\ntheorem Prod.ltDef [LT \u03b1] [LT \u03b2] (s t : \u03b1 \u00d7 \u03b2) : (s < t) = (s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)) :=\n  rfl\n\ntheorem Prod.ext (p : \u03b1 \u00d7 \u03b2) : (p.1, p.2) = p := by\n  cases p; rfl\n\ndef Prod.map {\u03b1\u2081 : Type u\u2081} {\u03b1\u2082 : Type u\u2082} {\u03b2\u2081 : Type v\u2081} {\u03b2\u2082 : Type v\u2082}\n    (f : \u03b1\u2081 \u2192 \u03b1\u2082) (g : \u03b2\u2081 \u2192 \u03b2\u2082) : \u03b1\u2081 \u00d7 \u03b2\u2081 \u2192 \u03b1\u2082 \u00d7 \u03b2\u2082\n  | (a, b) => (f a, g b)\n\n/- Dependent products -/\n\ntheorem exOfPsig {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : (PSigma (fun x => p x)) \u2192 Exists (fun x => p x)\n  | \u27e8x, hx\u27e9 => \u27e8x, hx\u27e9\n\nprotected theorem PSigma.eta {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {a\u2081 a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081} {b\u2082 : \u03b2 a\u2082}\n    (h\u2081 : a\u2081 = a\u2082) (h\u2082 : Eq.ndrec b\u2081 h\u2081 = b\u2082) : PSigma.mk a\u2081 b\u2081 = PSigma.mk a\u2082 b\u2082 := by\n  subst h\u2081\n  subst h\u2082\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\n@[simp] theorem PUnit.eq_punit (a : PUnit) : a = \u27e8\u27e9 :=\n  PUnit.subsingleton a \u27e8\u27e9\n\ninstance : Subsingleton PUnit :=\n  Subsingleton.intro PUnit.subsingleton\n\ninstance : Inhabited PUnit where\n  default := \u27e8\u27e9\n\ninstance : DecidableEq PUnit :=\n  fun a b => isTrue (PUnit.subsingleton a b)\n\n/- Setoid -/\n\nclass Setoid (\u03b1 : Sort u) where\n  r : \u03b1 \u2192 \u03b1 \u2192 Prop\n  iseqv {} : Equivalence r\n\ninstance {\u03b1 : Sort u} [Setoid \u03b1] : HasEquiv \u03b1 :=\n  \u27e8Setoid.r\u27e9\n\nnamespace Setoid\n\nvariable {\u03b1 : Sort u} [Setoid \u03b1]\n\ntheorem refl (a : \u03b1) : a \u2248 a :=\n  (Setoid.iseqv \u03b1).refl a\n\ntheorem symm {a b : \u03b1} (hab : a \u2248 b) : b \u2248 a :=\n  (Setoid.iseqv \u03b1).symm hab\n\ntheorem trans {a b c : \u03b1} (hab : a \u2248 b) (hbc : b \u2248 c) : a \u2248 c :=\n  (Setoid.iseqv \u03b1).trans hab hbc\n\nend Setoid\n\n\n/- Propositional extensionality -/\n\naxiom propext {a b : Prop} : (a \u2194 b) \u2192 a = b\n\ntheorem Eq.propIntro {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : b \u2192 a) : a = b :=\n  propext <| Iff.intro h\u2081 h\u2082\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/- Quotients -/\n\n-- Iff can now be used to do substitutions in a calculation\ntheorem iffSubst {a b : Prop} {p : Prop \u2192 Prop} (h\u2081 : a \u2194 b) (h\u2082 : p a) : p b :=\n  Eq.subst (propext h\u2081) h\u2082\n\nnamespace Quot\naxiom sound : \u2200 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a b : \u03b1}, r a b \u2192 Quot.mk r a = Quot.mk r b\n\nprotected theorem liftBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v}\n    (f : \u03b1 \u2192 \u03b2)\n    (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b)\n    (a : \u03b1)\n    : lift f c (Quot.mk r a) = f a :=\n  rfl\n\nprotected theorem indBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (p : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (a : \u03b1)\n    : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=\n  rfl\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b) : \u03b2 :=\n  lift f c q\n\nprotected theorem inductionOn {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (q : Quot r)\n    (h : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q :=\n  ind h q\n\ntheorem existsRep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=\n  Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => \u27e8a, rfl\u27e9)\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\nvariable {motive : Quot r \u2192 Sort v}\n\n@[reducible, macroInline]\nprotected def indep (f : (a : \u03b1) \u2192 motive (Quot.mk r a)) (a : \u03b1) : PSigma motive :=\n  \u27e8Quot.mk r a, f a\u27e9\n\nprotected theorem indepCoherent\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : (a b : \u03b1) \u2192 r a b \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : \u2200 (a b : \u03b1) (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\nprotected abbrev rec\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 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\nprotected abbrev recOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : motive q :=\n Quot.rec f h q\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quot.mk r a))]\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q := by\n  induction q using Quot.rec\n  apply f\n  apply Subsingleton.elim\n\nprotected abbrev hrecOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (c : (a b : \u03b1) \u2192 (p : r a b) \u2192 f a \u2245 f b)\n    : motive q :=\n  Quot.recOn q f fun a b p => eqOfHEq <|\n    have p\u2081 : Eq.ndrec (f a) (sound p) \u2245 f a := eqRecHEq (sound p) (f a)\n    HEq.trans p\u2081 (c a b p)\n\nend\nend Quot\n\ndef Quotient {\u03b1 : Sort u} (s : Setoid \u03b1) :=\n  @Quot \u03b1 Setoid.r\n\nnamespace Quotient\n\n@[inline]\nprotected def mk {\u03b1 : Sort u} [s : Setoid \u03b1] (a : \u03b1) : Quotient s :=\n  Quot.mk Setoid.r a\n\ndef sound {\u03b1 : Sort u} [s : Setoid \u03b1] {a b : \u03b1} : a \u2248 b \u2192 Quotient.mk a = Quotient.mk b :=\n  Quot.sound\n\nprotected abbrev lift {\u03b1 : Sort u} {\u03b2 : Sort v} [s : Setoid \u03b1] (f : \u03b1 \u2192 \u03b2) : ((a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) \u2192 Quotient s \u2192 \u03b2 :=\n  Quot.lift f\n\nprotected theorem ind {\u03b1 : Sort u} [s : Setoid \u03b1] {motive : Quotient s \u2192 Prop} : ((a : \u03b1) \u2192 motive (Quotient.mk a)) \u2192 (q : Quot Setoid.r) \u2192 motive q :=\n  Quot.ind\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} [s : Setoid \u03b1] (q : Quotient s) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) : \u03b2 :=\n  Quot.liftOn q f c\n\nprotected theorem inductionOn {\u03b1 : Sort u} [s : Setoid \u03b1] {motive : Quotient s \u2192 Prop}\n    (q : Quotient s)\n    (h : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    : motive q :=\n  Quot.inductionOn q h\n\ntheorem existsRep {\u03b1 : Sort u} [s : Setoid \u03b1] (q : Quotient s) : Exists (fun (a : \u03b1) => Quotient.mk a = q) :=\n  Quot.existsRep q\n\nsection\nvariable {\u03b1 : Sort u}\nvariable [s : Setoid \u03b1]\nvariable {motive : Quotient s \u2192 Sort v}\n\n@[inline]\nprotected def rec\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    (q : Quotient s)\n    : motive q :=\n  Quot.rec f h q\n\nprotected abbrev recOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    : motive q :=\n  Quot.recOn q f h\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quotient.mk a))]\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    : motive q :=\n  Quot.recOnSubsingleton (h := h) q f\n\nprotected abbrev hrecOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (c : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 f a \u2245 f b)\n    : motive q :=\n  Quot.hrecOn q f c\nend\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB} {\u03c6 : Sort uC}\nvariable [s\u2081 : Setoid \u03b1] [s\u2082 : Setoid \u03b2]\n\nprotected abbrev lift\u2082\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    (q\u2081 : Quotient s\u2081) (q\u2082 : Quotient s\u2082)\n    : \u03c6 := by\n  apply Quotient.lift (fun (a\u2081 : \u03b1) => Quotient.lift (f a\u2081) (fun (a b : \u03b2) => c a\u2081 a a\u2081 b (Setoid.refl a\u2081)) q\u2082) _ q\u2081\n  intros\n  induction q\u2082 using Quotient.ind\n  apply c; assumption; apply Setoid.refl\n\nprotected abbrev liftOn\u2082\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    : \u03c6 :=\n  Quotient.lift\u2082 f c q\u2081 q\u2082\n\nprotected theorem ind\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2083\n    [s\u2083 : Setoid \u03c6]\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Quotient s\u2083 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (q\u2083 : Quotient s\u2083)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 (c : \u03c6) \u2192 motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))\n    : motive q\u2081 q\u2082 q\u2083 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  induction q\u2083 using Quotient.ind\n  apply h\n\nend\n\nsection Exact\n\nvariable   {\u03b1 : Sort u}\n\nprivate def rel [s : Setoid \u03b1] (q\u2081 q\u2082 : Quotient s) : Prop :=\n  Quotient.liftOn\u2082 q\u2081 q\u2082\n    (fun a\u2081 a\u2082 => a\u2081 \u2248 a\u2082)\n    (fun a\u2081 a\u2082 b\u2081 b\u2082 a\u2081b\u2081 a\u2082b\u2082 =>\n      propext (Iff.intro\n        (fun a\u2081a\u2082 => Setoid.trans (Setoid.symm a\u2081b\u2081) (Setoid.trans a\u2081a\u2082 a\u2082b\u2082))\n        (fun b\u2081b\u2082 => Setoid.trans a\u2081b\u2081 (Setoid.trans b\u2081b\u2082 (Setoid.symm a\u2082b\u2082)))))\n\nprivate theorem rel.refl [s : Setoid \u03b1] (q : Quotient s) : rel q q :=\n  Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a)\n\nprivate theorem eqImpRel [s : Setoid \u03b1] {q\u2081 q\u2082 : Quotient s} : q\u2081 = q\u2082 \u2192 rel q\u2081 q\u2082 :=\n  fun h => Eq.ndrecOn h (rel.refl q\u2081)\n\ntheorem exact [s : Setoid \u03b1] {a b : \u03b1} : Quotient.mk a = Quotient.mk b \u2192 a \u2248 b :=\n  fun h => eqImpRel h\n\nend Exact\n\nsection\nuniverse uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB}\nvariable [s\u2081 : Setoid \u03b1] [s\u2082 : Setoid \u03b2]\n\nprotected abbrev recOnSubsingleton\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Sort uC}\n    [s : (a : \u03b1) \u2192 (b : \u03b2) \u2192 Subsingleton (motive (Quotient.mk a) (Quotient.mk b))]\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (g : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quot.recOnSubsingleton\n  induction q\u2082 using Quot.recOnSubsingleton\n  apply g\n  intro a; apply s\n  induction q\u2082 using Quot.recOnSubsingleton\n  intro a; apply s\n  inferInstance\n\nend\nend Quotient\n\nsection\nvariable {\u03b1 : Type u}\nvariable (r : \u03b1 \u2192 \u03b1 \u2192 Prop)\n\ninstance {\u03b1 : Sort u} {s : Setoid \u03b1} [d : \u2200 (a b : \u03b1), Decidable (a \u2248 b)] : DecidableEq (Quotient s) :=\n  fun (q\u2081 q\u2082 : Quotient s) =>\n    Quotient.recOnSubsingleton\u2082 (motive := fun a b => Decidable (a = b)) q\u2081 q\u2082\n      fun a\u2081 a\u2082 =>\n        match d a\u2081 a\u2082 with\n        | isTrue h\u2081  => isTrue (Quotient.sound h\u2081)\n        | isFalse h\u2082 => isFalse fun h => absurd (Quotient.exact h) h\u2082\n\n/- Function extensionality -/\n\nnamespace Function\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\nprotected def Equiv (f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x) : Prop := \u2200 x, f\u2081 x = f\u2082 x\n\nprotected theorem Equiv.refl (f : \u2200 (x : \u03b1), \u03b2 x) : Function.Equiv f f :=\n  fun x => rfl\n\nprotected theorem Equiv.symm {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} : Function.Equiv f\u2081 f\u2082 \u2192 Function.Equiv f\u2082 f\u2081 :=\n  fun h x => Eq.symm (h x)\n\nprotected theorem Equiv.trans {f\u2081 f\u2082 f\u2083 : \u2200 (x : \u03b1), \u03b2 x} : Function.Equiv f\u2081 f\u2082 \u2192 Function.Equiv f\u2082 f\u2083 \u2192 Function.Equiv f\u2081 f\u2083 :=\n  fun h\u2081 h\u2082 x => Eq.trans (h\u2081 x) (h\u2082 x)\n\nprotected theorem Equiv.isEquivalence (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Equivalence (@Function.Equiv \u03b1 \u03b2) := {\n  refl := Equiv.refl\n  symm := Equiv.symm\n  trans := Equiv.trans\n}\n\nend Function\n\nsection\nopen Quotient\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\n@[instance]\nprivate def funSetoid (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Setoid (\u2200 (x : \u03b1), \u03b2 x) :=\n  Setoid.mk (@Function.Equiv \u03b1 \u03b2) (Function.Equiv.isEquivalence \u03b1 \u03b2)\n\nprivate def extfunApp (f : Quotient <| funSetoid \u03b1 \u03b2) (x : \u03b1) : \u03b2 x :=\n  Quot.liftOn f\n    (fun (f : \u2200 (x : \u03b1), \u03b2 x) => f x)\n    (fun f\u2081 f\u2082 h => h x)\n\ntheorem funext {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} (h : \u2200 x, f\u2081 x = f\u2082 x) : f\u2081 = f\u2082 := by\n  show extfunApp (Quotient.mk f\u2081) = extfunApp (Quotient.mk f\u2082)\n  apply congrArg\n  apply Quotient.sound\n  exact h\n\nend\n\ninstance {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton (\u2200 a, \u03b2 a) where\n  allEq f\u2081 f\u2082 :=\n    funext (fun a => Subsingleton.elim (f\u2081 a) (f\u2082 a))\n\n/- Squash -/\n\ndef Squash (\u03b1 : Type u) := Quot (fun (a b : \u03b1) => True)\n\ndef Squash.mk {\u03b1 : Type u} (x : \u03b1) : Squash \u03b1 := Quot.mk _ x\n\ntheorem Squash.ind {\u03b1 : Type u} {motive : Squash \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), motive (Squash.mk a)) : \u2200 (q : Squash \u03b1), motive q :=\n  Quot.ind h\n\n@[inline] def Squash.lift {\u03b1 \u03b2} [Subsingleton \u03b2] (s : Squash \u03b1) (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  Quot.lift f (fun a b _ => Subsingleton.elim _ _) s\n\ninstance : Subsingleton (Squash \u03b1) 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\nnamespace Lean\n/- Kernel reduction hints -/\n\n/--\n  When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.\n  The kernel will not use the interpreter if `c` is not a constant.\n  This feature is useful for performing proofs by reflection.\n\n  Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing\n  free 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\n  Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\n  This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using\n  external type checkers (e.g., Trepplein) that do not implement this feature.\n  Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\n  So, you are mainly losing the capability of type checking your developement using external checkers.\n\n  Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.\n  If an extern function is executed, then the trusted code base will also include the implementation of the associated\n  foreign function.\n-/\nconstant reduceBool (b : Bool) : Bool := b\n\n/--\n  Similar to `Lean.reduceBool` for closed `Nat` terms.\n\n  Remark: we do not have plans for supporting a generic `reduceValue {\u03b1} (a : \u03b1) : \u03b1 := a`.\n  The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.\n  We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/\nconstant reduceNat (n : Nat) : Nat := n\n\naxiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b\naxiom ofReduceNat (a b : Nat) (h : reduceNat a = b)    : a = b\n\nend Lean\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Init/Core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.04813677487184563, "lm_q1q2_score": 0.013243857576229248}}
{"text": "import tactic\nimport tactic.induction\n\nimport .base .lemma_2_4\n\nnoncomputable theory\nopen_locale classical\n\nlemma A_pw_2_hws : A_hws 2 :=\nbegin\n  sorry\nend", "meta": {"author": "user7230724", "repo": "lean-projects", "sha": "ab9a83874775efd18f8c5b867e480bae4d596b31", "save_path": "github-repos/lean/user7230724-lean-projects", "path": "github-repos/lean/user7230724-lean-projects/lean-projects-ab9a83874775efd18f8c5b867e480bae4d596b31/src/ap/pw_2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.24798741512455283, "lm_q2_score": 0.05340333017646162, "lm_q1q2_score": 0.013243353809503748}}
{"text": "import its reducibility\n\nopen encodable denumerable\n\nattribute [simp] set.set_of_app_iff\n\nvariables {\u03b1 : Type*} {\u03b2 : Type*} {\u03b3 : Type*} {\u03c3 : Type*} {\u03c4 : Type*} {\u03bc : Type*}\n  [primcodable \u03b1] [primcodable \u03b2] [primcodable \u03b3] [primcodable \u03c3] [primcodable \u03c4] [primcodable \u03bc]\n  {o : \u03c3 \u2192. \u03c4}\nvariables {n : \u2115} (S : strategy n) {k : \u2115}\n\nopen strategy encodable\n\ndef ancestor.equiv_fin {k : \u2115} (\u03b7 : Tree k) :\nancestor \u03b7 \u2243 fin \u03b7.length :=\n{ to_fun := (\u03bb \u03bc, \u27e8\u03bc.val.length, list.is_initial_length \u03bc.property\u27e9),\n  inv_fun := (\u03bb n, \u27e8\u03b7\u21be*n.val, list.is_initial_initial \u03b7 n.val n.property\u27e9),\n  left_inv := (\u03bb \u27e8\u03bc, \u27e8l, x, p\u27e9\u27e9,\n    by { simp[\u2190p],  simp only [show l ++ x :: \u03bc = (l ++ [x]) ++ \u03bc, by simp, list.initial_append] }),\n  right_inv := (\u03bb \u27e8n, lt\u27e9, by { simp, exact list.initial_length lt }) }\n\ninstance primcodable.ancestor_arrow {\u03b1 : Type*} [primcodable \u03b1] {k} (\u03b7 : Tree k) : primcodable (ancestor \u03b7 \u2192 \u03b1) :=\nprimcodable.of_equiv (fin \u03b7.length \u2192 \u03b1) (equiv.arrow_congr (ancestor.equiv_fin \u03b7) (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 (\u03bb b, by cases b; simp) },\n  { let F : Tree' (k + 1) \u2192 bool := \u03bb \u03bc, list.cases_on \u03bc ff (\u03bb \u03b7 _, !@Tree'.is_pi k \u03b7),\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 (\u03bb \u03bc, by { induction \u03bc with \u03bd \u03bc 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 (\u03b1 : Type*) [inhabited \u03b1] [primcodable \u03b1] (\u03b7 : Tree k) (x : Tree' k) (n : \u2115) : \u2115 := \n  let f := (decode (ancestor (x :: \u03b7) \u2192 \u03b1) n).iget in\nencode (ancestor.extend_fn f \u03b7 (list.suffix_cons x \u03b7))\n\nnamespace strategy\n\nnamespace approx_enc\n\ndef derivative (\u03b7 : Tree (k + 1)) (\u03bc : Tree k) (\u03c5 : list (Tree (k + 1))) : list \u2115 :=\n(list.range_r \u03bc.length).filter (\u03bb i, \u03c5.nth i = \u03b7)\n\ndef pi_derivative\n  (\u03b7 : Tree (k + 1)) (\u03bc : Tree k) (\u03c5 : list (Tree (k + 1))) : list \u2115 :=\n(derivative \u03b7 \u03bc \u03c5).filter (\u03bb i, @Tree'.is_sigma (k + 1) (\u03bc\u21be*(i + 1)))\n\ndef lambda : \u03a0 (\u03bc : Tree k) (\u03c5 : list (Tree (k + 1))), Tree (k + 1)\n| []       _ := []\n| (x :: \u03bc) \u03c5 := let ih := lambda \u03bc \u03c5 in\n    option.cases_on (\u03c5.nth \u03bc.length) []\n    (\u03bb u\u03bc, if u\u03bc = ih \u2228 (x.is_pi \u2227 pi_derivative u\u03bc \u03bc \u03c5 = [])\n    then (x :: \u03bc) :: u\u03bc else ih)\n\ndef assignment (\u03bc : Tree k) (\u03c5 : list (Tree (k + 1))) : Tree (k + 1) \u00d7 \u2115 :=\n(S.priority (k + 1)).Min_le\n  ((lambda \u03bc \u03c5, 0) :: ((list.range_r (lambda \u03bc \u03c5).length).filter\n    (\u03bb i, @Tree'.is_sigma (k + 2) (lambda \u03bc \u03c5\u21be*(i + 1)))).map\n  (\u03bb i, ((lambda \u03bc \u03c5)\u21be*i, (derivative (lambda \u03bc \u03c5\u21be*i) \u03bc \u03c5).length))) (by simp)\n\ndef up (\u03bc : Tree k) (\u03c5 : list (Tree (k + 1))) : Tree (k + 1) :=\n(assignment S \u03bc \u03c5).1\n\nlemma ancestors_eq_range (\u03bc : Tree k) : \u03bc.ancestors.map ancestor.index = list.range_r \u03bc.length :=\nby { induction \u03bc with \u03bd \u03bc IH; simp[ancestor.index, (\u2218)], exact IH }\n\nlemma derivative_eq {\u03bc : Tree k} {\u03c5 : ancestor \u03bc \u2192 Tree (k + 1)} {\u03c5' : list (Tree (k + 1))}\n  (h : \u2200 \u03bd : ancestor \u03bc, \u03c5'.nth \u03bd.index = some (\u03c5 \u03bd)) (\u03b7 : Tree (k + 1)) : \n  derivative \u03b7 \u03bc \u03c5' = (approx.derivative \u03b7 \u03c5).map ancestor.index :=\nby { simp[derivative, approx.derivative, \u2190ancestors_eq_range, list.map_filter, (\u2218)],\n     congr, funext \u03bd, simp [h] }\n\nlemma pi_derivative_eq {\u03bc : Tree k} {\u03c5 : ancestor \u03bc \u2192 Tree (k + 1)} {\u03c5' : list (Tree (k + 1))}\n  (h : \u2200 \u03bd : ancestor \u03bc, \u03c5'.nth \u03bd.index = some (\u03c5 \u03bd)) (\u03b7 : Tree (k + 1)) : \n  pi_derivative \u03b7 \u03bc \u03c5' = (approx.pi_derivative \u03b7 \u03c5).map ancestor.index :=\nby { simp[pi_derivative, approx.pi_derivative, derivative_eq h, list.map_filter, (\u2218)],\n     congr, funext \u03bd, simp[ancestor_initial_index_succ] }\n\nlemma lambda_eq {\u03bc : Tree k} {\u03c5 : ancestor \u03bc \u2192 Tree (k + 1)} {\u03c5' : list (Tree (k + 1))}\n  (h : \u2200 \u03bd : ancestor \u03bc, \u03c5'.nth \u03bd.index = some (\u03c5 \u03bd)) : \n  lambda \u03bc \u03c5' = approx.lambda \u03c5 :=\nbegin\n  induction \u03bc with \u03bd \u03bc IH; simp[lambda, approx.lambda],\n  rw [show \u03c5'.nth \u03bc.length = some (\u03c5 \u27e8\u03bc, by simp\u27e9), from h \u27e8\u03bc, by simp\u27e9], simp,\n  have la_eq : lambda \u03bc \u03c5' = approx.lambda (ancestor.extend_fn \u03c5 \u03bc _),\n    from @IH (ancestor.extend_fn \u03c5 \u03bc (by simp)) (\u03bb \u03c3, h (\u03c3.extend (by simp))),\n  have pider_eq : \u2200 \u03b7,\n    pi_derivative \u03b7 \u03bc \u03c5' = list.map ancestor.index (approx.pi_derivative \u03b7 (ancestor.extend_fn \u03c5 \u03bc _)),\n    from @pi_derivative_eq _ _ (ancestor.extend_fn \u03c5 \u03bc (by simp)) \u03c5'\n    (\u03bb \u03c3, h (\u03c3.extend (by simp))),\n  simp[la_eq, pider_eq]\nend\n\nlemma assignment_eq {\u03bc : Tree k} {\u03c5 : ancestor \u03bc \u2192 Tree (k + 1)} {\u03c5' : list (Tree (k + 1))}\n  (h : \u2200 \u03bd : ancestor \u03bc, \u03c5'.nth \u03bd.index = some (\u03c5 \u03bd)) : \n  assignment S \u03bc \u03c5' = approx.assignment S \u03c5 :=\nbegin\n  simp[assignment, approx.assignment, lambda_eq h],\n  refine omega_ordering.Min_le_eq _ _ _ _,\n  simp,\n  rw [\u2190ancestors_eq_range],\n  simp[list.map_filter, (\u2218)],\n  congr,\n  { funext \u03bd, simp[ancestor_initial_index, derivative_eq h] },\n  { ext \u03bd, simp[ancestor_initial_index_succ] }\nend\n\nlemma up_eq {\u03bc : Tree k} {\u03c5 : ancestor \u03bc \u2192 Tree (k + 1)} {\u03c5' : list (Tree (k + 1))}\n  (h : \u2200 \u03bd : ancestor \u03bc, \u03c5'.nth \u03bd.index = some (\u03c5 \u03bd)) : \n  up S \u03bc \u03c5' = approx.up S \u03c5 :=\ncongr_arg prod.fst (assignment_eq S h)\n\nvariables {S}\nopen rcomputable computable\u2082\n\nlemma rcomputable.derivative :\n  (prod.unpaired3 (derivative : Tree (k + 1) \u2192 Tree k \u2192 list (Tree (k + 1)) \u2192 list \u2115)) computable_in o :=\nbegin\n  refine rcomputable.list_filter _ _,\n  { refine (rcomputable\u2082.to_bool_eq (option (Tree (k + 1)))).comp\u2082 _ _,\n    { exact rcomputable\u2082.list_nth.comp\u2082 (rcomputable.to_unary\u2081 rcomputable.snd.to_unary\u2082) rcomputable.id'.to_unary\u2082 },\n    { exact rcomputable.to_unary\u2081 rcomputable.option_some.to_unary\u2081 } },\n  { exact rcomputable.list_range_r.comp (rcomputable.list_length.comp rcomputable.fst.to_unary\u2082) }\nend\n\nlemma rcomputable.pi_derivative : \n  (prod.unpaired3 (pi_derivative : Tree (k + 1) \u2192 Tree k \u2192 list (Tree (k + 1)) \u2192 list \u2115)) computable_in o :=\nbegin\n  refine rcomputable.list_filter _ rcomputable.derivative,\n  { simp, exact rcomputable.is_sigma.comp\u2082\n    (rcomputable.rcomputable.list_initial.comp\u2082 (rcomputable.to_unary\u2081 rcomputable.fst.to_unary\u2082)\n    rcomputable.succ.to_unary\u2082) }\nend\n\nlemma rcomputable.lambda : \n  (lambda : Tree k \u2192 list (Tree (k + 1)) \u2192 Tree (k + 1)) computable\u2082_in o :=\nbegin\n  let F : Tree k \u2192 list (Tree (k + 1)) \u2192 Tree (k + 1) :=\n    \u03bb \u03bc \u03c5, list.rec_on \u03bc []\n      (\u03bb x \u03bc ih, option.cases_on (\u03c5.nth \u03bc.length) []\n        (\u03bb u\u03bc, if u\u03bc = ih \u2228 (x.is_pi \u2227 pi_derivative u\u03bc \u03bc \u03c5 = []) then (x :: \u03bc) :: u\u03bc else ih)),\n  have : F computable\u2082_in o,\n  { simp[F],\n    refine rcomputable.list_rec (rpartrec.some.to_unary\u2081) (rcomputable.const list.nil)\n      (rcomputable.option_rec\n        (rcomputable\u2082.list_nth.comp snd.to_unary\u2081\n          (rcomputable.list_length.comp (fst.comp snd.to_unary\u2082)))\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\u2081)) _),\n      { refine (rcomputable\u2082.to_bool_eq _).comp snd\n        (snd.comp (snd.comp snd.to_unary\u2081)) },\n      { refine (rcomputable\u2082.to_bool_eq _).comp\n          (rcomputable.pi_derivative.unpaired3 snd\n            (fst.comp (snd.comp snd.to_unary\u2081))\n            (snd.comp fst.to_unary\u2081)) (rcomputable.const []) } },\n    { exact rcomputable\u2082.list_cons.comp\n        (rcomputable\u2082.list_cons.comp (fst.comp snd.to_unary\u2081)\n        (fst.comp (snd.comp snd.to_unary\u2081)))\n        snd },\n    { exact snd.comp (snd.comp snd.to_unary\u2081) } },\n  exact this.of_eq (\u03bb \u03bc \u03c5, by {\n    induction \u03bc with x \u03bc IH; simp[F, lambda],\n    { cases C : \u03c5.nth \u03bc.length with \u03bd; simp[C],\n      { simp[F, lambda] at IH, simp[IH] } } })\nend\n\nlemma rcomputable.assignment_enc : \n  (assignment S : Tree k \u2192 list (Tree (k + 1)) \u2192 Tree (k + 1) \u00d7 \u2115) computable\u2082_in o :=\n(omega_ordering_Min_le (S.priority (k + 1)) _ _ (S.effective _).to_rcomp\n  (rcomputable\u2082.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\u2081 snd.to_unary\u2081) snd)\n        (list_length.comp (rcomputable.derivative.unpaired3\n          (rcomputable.list_initial.comp (rcomputable.lambda.comp fst.to_unary\u2081 snd.to_unary\u2081) snd)\n          (fst.to_unary\u2081) (snd.to_unary\u2081))))\n      (list_filter\n        (by {simp, exact is_sigma.comp\u2082 \n          (rcomputable.list_initial.comp\u2082 (rcomputable.lambda.comp fst snd).to_unary\u2081 succ.to_unary\u2082) })\n        (list_range_r.comp (list_length.comp (rcomputable.lambda.comp fst snd)))))))\n\nlemma rcomputable.up_enc : \n  (up S : Tree k \u2192 list (Tree (k + 1)) \u2192 Tree (k + 1)) computable\u2082_in o :=\nfst.comp rcomputable.assignment_enc\n\nend approx_enc\n\ndef up'_enc : Tree k \u2192 list (Tree (k + 1))\n| []       := []\n| (_ :: \u03b7) := up'_enc \u03b7 ++ [approx_enc.up S \u03b7 (up'_enc \u03b7)]\n\n@[simp] lemma up'_enc_length (\u03bc : Tree k) : (up'_enc S \u03bc).length = \u03bc.length :=\nby induction \u03bc with \u03bd \u03bc IH; simp[up'_enc]; exact IH\n\nvariables {S}\nopen rcomputable rcomputable\u2082\n\nlemma rcomputable.up'_enc : (up'_enc S : Tree k \u2192 list (Tree (k + 1))) computable_in o :=\nbegin\n  let F : Tree k \u2192 list (Tree (k + 1)) := \u03bb \u03bc, list.rec_on \u03bc [] (\u03bb _ \u03b7 IH, IH ++ [approx_enc.up S \u03b7 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\u2082)\n      (list_cons.comp (approx_enc.rcomputable.up_enc.comp (fst.comp snd.to_unary\u2082) (snd.comp snd.to_unary\u2082))\n      (const [])) },\n  exact this.of_eq (\u03bb \u03bc, by { \n    induction \u03bc with \u03bd \u03bc IH; simp[F, up'_enc],\n    { simp[F] at IH, simp[IH] }  })\nend\n\nlemma up_enc_eq_up {\u03bc : Tree k} : \u2200 \u03bd : ancestor \u03bc, (S.up'_enc \u03bc).nth \u03bd.index = some (S.up' \u03bc \u03bd) :=\nbegin\n  induction \u03bc with \u03bd \u03bc IH; simp[up'_enc, up' S, -up'_up_consistent],\n    {  rintros \u27e8\u03c3, lt\u27e9,simp at lt, contradiction },\n    { rintros \u27e8\u03c3, lt\u27e9, simp[up', -up'_up_consistent],\n      have : \u03c3 = \u03bc \u2228 \u03c3 \u2282\u1d62 \u03bc, from list.is_initial_cons_iff.mp lt,\n      rcases this with (rfl | lt),\n      { simp[ancestor.index],\n        rw [show \u03c3.length = (S.up'_enc \u03c3).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 \u03c3 < (S.up'_enc \u03bc).length, by simp[list.is_initial_length lt])],\n        have := IH \u27e8\u03c3, lt\u27e9, simp[ancestor.index] at this, exact this } }\nend\n\n@[rcomputability]\ntheorem rcomputable.up : (up[S] : Tree k \u2192 Tree (k + 1)) computable_in o :=\n(approx_enc.rcomputable.up_enc.comp id' rcomputable.up'_enc).of_eq\n(\u03bb \u03bc, approx_enc.up_eq S up_enc_eq_up)\n\n\n@[rcomputability]\ntheorem rcomputable.lambda : (\u03bb[S] : Tree k \u2192 Tree (k + 1)) computable_in o :=\nby { have : (\u03bb \u03bc : Tree k, approx_enc.lambda \u03bc (S.up'_enc \u03bc)) computable_in o,\n       from approx_enc.rcomputable.lambda.comp id' rcomputable.up'_enc,\n     exact this.of_eq (\u03bb \u03bc, approx_enc.lambda_eq up_enc_eq_up) }\n\nlemma rcomputable.Tree'_weight_aux {k : \u2115} :\n  (Tree'.weight_aux : Tree' k \u2192 \u2115) computable_in o :=\nbegin\n  induction k with k IH,\n  { exact (id'.cond (const 1) (const 0)).of_eq (\u03bb \u03bc, by cases \u03bc; simp[Tree'.weight_aux]) },\n  { exact list_weight_of IH }\nend\n\n@[rcomputability]\nlemma rcomputable.Tree_weight {k : \u2115} :\n  (Tree.weight : Tree k \u2192 \u2115) computable_in o :=\nbegin\n  induction k with k IH,\n  { exact rcomputable.Tree'_weight_aux },\n  { let F : Tree (k + 1) \u2192 \u2115 := \u03bb \u03bc, list.rec_on \u03bc 0 (\u03bb \u03bd _ _, \u03bd.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\u2082) (const 1)) },\n    exact this.of_eq (\u03bb \u03bc, by cases \u03bc; 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": "example : Id Nat := do\n  let x \u2190 if true then\n    pure 1\n  else\n    pure 2\n  pure x\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/1120.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.05033063117300158, "lm_q1q2_score": 0.013228995573569801}}
{"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 \u03bb 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\u27e8\u03bb x => format x.toList\u27e9\n\ninstance : ToFormat FieldData :=\n\u27e8\u03bb \u27e8a, b, c, d, e\u27e9 => group (nest 1 (format \"\u27e8\"  ++ format a ++ format \",\" ++ line ++ format b ++\nformat \",\" ++ line ++ format c ++ format \",\" ++ line ++ format d ++ format \",\" ++ line ++ format e\n++ format \"\u27e9\"))\u27e9\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 \u2190 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 \"\u27e8\"  ++\nformat x.name ++ format \",\" ++ line ++\nformat (\u2190 Meta.ppExpr x.fvar) ++ format \",\" ++ line ++\nformat (\u2190 Meta.ppExpr x.type) ++ format \",\" ++ line ++\nformat (\u2190 x.depends.toList.mapM \u03bb e => Meta.ppExpr (mkFVar \u27e8e\u27e9)) ++ format \",\" ++ line ++\nformat x.isProp ++ format \"\u27e9\"))\n\n/-- make a field mapping with no connections. -/\ndef mkState (fields1 : Array FieldData) : State :=\n{ mapping := fields1.map (\u00b7.toFieldMapping) }\n\nnamespace State\n\ndef done (st : State) : Bool :=\nst.mapping.all (\u00b7.tgt.isSome)\n\ndef update (st : State) (f : FieldData \u2192 Option Expr) : State :=\n{ mapping := st.mapping.map \u03bb info => info.update (f info.toFieldData) }\n\ndef updateM (st : State) (f : FieldData \u2192 MetaM (Option Expr)) : MetaM State := do\n  let fieldMapping \u2190 st.mapping.mapM \u03bb info => info.updateM (f info.toFieldData)\n  return { mapping := fieldMapping }\n\ndef getDataMapping (st : State) : Array (Expr \u00d7 Expr) :=\nst.mapping.filterMap \u03bb 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 \u00d7 Expr) :=\nst.mapping.filterMap \u03bb 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 \u03bb info => if info.tgt.isNone then some info.toFieldData else none\n\ndef missingData (st : State) : Array FieldData :=\nst.mapping.filterMap \u03bb 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 \u03bb 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 \u00d7 Array FieldData) := do\n  let casegoal := l.get! 0\n  let mvarId := casegoal.mvarId\n  withMVarContext mvarId do\n  let lctx \u2190 getLCtx\n  let fieldExprs := casegoal.fields\n  let fields := fieldExprs.map Expr.fvarId!\n  let ldecls := fields.map \u03bb e => lctx.fvarIdToDecl.find! e\n  let axiom_fields \u2190 fieldExprs.mapM isProof\n  let types \u2190 fieldExprs.mapM inferType\n  let depends := types.map \u03bb 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 \u2190 withMVarContext mvarId $ fields.mapM \u03bb info =>\n    match casegoal.subst.find? info.fvar.fvarId! with\n    | (some e) => do\n      let lctx \u2190 getLCtx\n      let id := e.fvarId!\n      let ldecl := lctx.fvarIdToDecl.find! id\n      let t \u2190 inferType e\n      let depends := NameSet.empty -- todo\n      return \u27e8ldecl, e, t, depends, info.isProp\u27e9\n    | none => return info\n  return fieldData\n\ndef AddFieldsToContext (mvarId : MVarId) (nm : Name) (us : List Level) (args : Array Expr) :\n  MetaM (MVarId \u00d7 MVarId \u00d7 Array FieldData) := do\n  let env \u2190 getEnv\n  let d \u2190 env.find? nm\n  let true \u2190 isStructureLike env nm\n  let eStr \u2190 mkAppN (mkConst nm us) args\n  let (h, mvarId, m2) \u2190 assertm mvarId `h eStr\n  let l \u2190 cases mvarId h\n  let (mvarId, fieldData) \u2190 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 $ \u03bb info =>\n  if info.isProp then none else\n    ctx.target.findSome? \u03bb 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 $ \u03bb info => if info.isProp then return none else do\n  let sources \u2190 st.mapping.filterM \u03bb info' => isDefEq info.type info'.type\n  let targets \u2190 ctx.target.filterM \u03bb info' => isDefEq info.type info'.type\n  return (if sources.size = 1 \u2227 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 \u00d7 Array FieldData) := do\n  let env \u2190 getEnv\n  let info? := st.find? \u03bb info =>\n    info.type.getAppFn.constName?.any (isVeryStructureLike env \u00b7 includeProp)\n  match info? with\n  | some info => do\n    let rest := st.filter \u03bb 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 \u2190 cases mvarId info.fvar.fvarId! #[\u27e8false, (giveNames env str info.name).toList\u27e9]\n    let (mvarId, fieldData) \u2190 fieldDataofCaseGoals l\n    let rest \u2190 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 \u00d7 Expr) := ctx.target.filterMap \u03bb info =>\n    if info.isProp then (info.fvar, info.type) else none\n  st.updateM \u03bb info => do\n    let e := info.type.instantiateFVars st.getDataMapping\n    match (\u2190 targetTypes.findM? \u03bb (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 (\u2190 getLCtx) do\n    unless localDecl.isAuxDecl do\n      if (\u2190 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 (\u2190 getSimpLemmas)\n    congrLemmas := (\u2190 getCongrLemmas) }\n  if !starArg then\n    return ctx\n  else\n    let hs \u2190 getPropHyps\n    let mut ctx := ctx\n    for h in hs do\n      let localDecl \u2190 getLocalDecl h\n      let fvarId := localDecl.fvarId\n      let proof  := localDecl.toExpr\n      let id     \u2190 mkFreshUserName `h\n      let simpLemmas \u2190 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 \u2190 simpTarget mvarId (\u2190 mkSimpContext false)\n\n-- match (\u2190 simpTarget mvarId (\u2190 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 \u2192 MetaM Unit) (e : Expr) : MetaM (Option Expr) :=\nwithoutModifyingState do\n  let (fvar, mvarId, m2) \u2190 assertm mvarId `h e\n  try\n    tac m2\n    -- IO.println s!\"is assigned: {\u2190 isExprMVarAssigned m2}\"\n    let some e \u2190 getExprMVarAssignment? m2 | return none\n    let e \u2190 instantiateMVars e\n    if (\u2190 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 \u00d7 MVarId \u00d7 MVarId \u00d7 State) := do\n  let u := mkLevelParam `u\n  let (M, mvarId) \u2190 asserti mvarId `M (mkSort (mkLevelSucc u)) (mkConst `PUnit [mkLevelSucc u])\n  let (mvarId, m2, fields2) \u2190 AddFieldsToContext mvarId nm2 [u] #[mkFVar M]\n  let (mvarId, fields2) \u2190 caseOnStructures mvarId fields2 \u27e8#[]\u27e9 false\n  let ctx : Context := \u27e8fields2\u27e9\n  if trace then IO.println s!\"cases on fields class 2: {\u2190 ctx.target.map (\u00b7.name)}\"\n  let (mvarId, m1, fields1) \u2190 AddFieldsToContext mvarId nm1 [u] #[mkFVar M]\n  let (mvarId, fields1) \u2190 caseOnStructures mvarId fields1 ctx\n  let st := mkState fields1\n  withMVarContext mvarId do\n  let st \u2190 uniqueMapping st ctx\n  let st := trivialMapping st ctx\n  if trace then IO.println s!\"map of data: {\u2190 st.traceMapping}\"\n  let (mvarId, fields2) \u2190 caseOnStructures mvarId fields2 \u27e8#[]\u27e9 -- is this dangerous?\n  let ctx : Context := \u27e8fields2\u27e9\n  withMVarContext mvarId do\n  let ctx : Context := \u27e8fields2\u27e9\n  let st \u2190 matchingAxioms st ctx\n  let st \u2190 st.updateM \u03bb 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: {\u2190 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 \u2190 getMainGoal\nlet (mvarId, m1, m2, st) \u2190 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 (\u00b7.name)}.\"\nlet l \u2190 getUnsolvedGoals\nsetGoals (mvarId::m1::m2::l)\n\ndef cryptomorphicTac (nm1 nm2 : Name) (trace := false) : TacticM Unit := withMainContext do\nlet mvarId \u2190 getMainGoal\nlet (mvarId, m1, m2, st1) \u2190 Meta.isSubclass mvarId nm1 nm2 trace\nlet (mvarId, m3, m4, st2) \u2190 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} \u2192 {nm1}: cannot construct {st1.missing.map (\u00b7.name)}\"\n  if !st2.done then\n    IO.println s!\"{nm1} \u2192 {nm2}: Cannot construct {st2.missing.map (\u00b7.name)}\"\nlet l \u2190 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 \u00abisSubclass\u00bb] def evalIsSubclass : Tactic := fun stx =>\n  match stx with\n  | `(tactic| isSubclass $nm1 $nm2) => withoutModifyingState $ isSubclassTac nm1.getId nm2.getId\n  | _ => throwUnsupportedSyntax\n@[tactic \u00abisSubclassE\u00bb] 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 \u00abcryptomorphic\u00bb] 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 (`\u2203 one, ...`)\n(6) by extending a `Monoid` structure.\n-/\n\nclass Zero (\u03b1 : Type u) where\n  zero : \u03b1\n\ninstance [Zero \u03b1] : OfNat \u03b1 (nat_lit 0) where\n  ofNat := Zero.zero\n\nclass One (\u03b1 : Type u) where\n  one : \u03b1\n\ninstance [One \u03b1] : OfNat \u03b1 (nat_lit 1) where\n  ofNat := One.one\n\nclass CommMonoid1 (M : Type _) extends Mul M, One M :=\n(mul_assoc : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : \u2200 x y : M, x * y = y * x)\n(mul_one : \u2200 x : M, x * 1 = x)\n\nclass CommMonoid2 (M : Type _) extends Mul M, One M :=\n(mul_one : \u2200 x : M, x * 1 = x)\n(one_mul_one : 1 * 1 = 1)\n(mul_assoc : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : \u2200 x y : M, x * y = y * x)\n\nclass CommMonoid3 (M : Type _) extends Mul M, One M :=\n(one_mul : \u2200 x : M, 1 * x = x)\n(mul_assoc : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : \u2200 x y : M, x * y = y * x)\n\nclass CommMonoid4 (M : Type _) extends Add M, Zero M :=\n(add_assoc : \u2200 x y z : M, (x + y) + z = x + (y + z))\n(add_comm : \u2200 x y : M, x + y = y + x)\n(add_zero : \u2200 x : M, x + 0 = x)\n\nclass CommMonoid5 (M : Type _) extends Mul M :=\n(mul_axioms : (\u2200 x y z : M, (x * y) * z = x * (y * z)) \u2227 (\u2200 x y : M, x * y = y * x))\n(exists_one : \u2203 one : M, \u2200 x : M, x * one = x)\n\nclass Monoid (M : Type _) extends Mul M, One M :=\n(mul_assoc : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(mul_one : \u2200 x : M, x * 1 = x)\n\nclass CommMonoid6 (M : Type _) extends Monoid M :=\n(mul_comm : \u2200 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 : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(one : M)\n(mul_one : \u2200 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 \u2192 M \u2192 M)\n(mul_assoc : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : \u2200 x y : M, x * y = y * x)\n(one : M)\n(mul_one : \u2200 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 : \u2200 x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : \u2200 x y : M, x * y = y * x)\n(one_axioms : \u2203 one : M, (\u2200 x : M, x * one = x) \u2227 (\u2200 x : M, x * x = one))\n\nclass CommMonoidBundled2 (M : Type _) :=\n(data : (M \u2192 M \u2192 M) \u00d7 M)\n(mul_assoc : \u2200 x y z : M, data.1 (data.1 x y) z = data.1 x (data.1 y z))\n(mul_comm : \u2200 x y : M, data.1 x y = data.1 y x)\n(mul_one : \u2200 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 Mathlib.Tactic.Spread\n\nclass Foo (\u03b1 : Type) where\n  bar : True\n\nclass Something where\n  bar : True\n\ninstance : Something where\n  bar := by trivial\n\ninstance : Foo \u03b1 where\n  __ := instSomething -- include fields from `instSomething`\n\nexample : Foo \u03b1 := {\n  __ := instSomething -- include fields from `instSomething`\n}\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/spread.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3486451488696663, "lm_q2_score": 0.03789242567892773, "lm_q1q2_score": 0.013211010391862524}}
{"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 \u2192 Type v} [monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : option \u03b1 \u2192 m (option \u03b2)\n-- | none       := return none\n-- | (some x) := do x' \u2190 f x, return (some x')\n\ndef list.last_option {\u03b1 : Type u}: list \u03b1 \u2192 option \u03b1\n| []        := none\n| [a]       := some a\n| (a::b::l) := list.last_option (b::l)\n\nmeta def expr.local_uniq_name_option : expr \u2192 option name\n| (expr.local_const n m bi t) := some n\n| e                      := none\n\nmeta def expr.mvar_uniq_name_option : expr \u2192 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  \u03bb _, 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 \u00d7 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 \u00d7 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-- \u27e8\u03bb \u27e8decls, goals\u27e9, pure $ format!\"tactic_state_data.mk \\n\\t decls := {decls} \\n\\t goals := {goals}\"\u27e9\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\u27e8by mk_to_tactic_json name.anonymous\u27e9\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\u27e8\u03bb msg, match msg with\n  | (json.array $ [c, json.array [un, pp, ety, cxt, ty, assn]]) := do\n    (c_nm : name) \u2190 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\u27e9\n\nmeta instance : has_from_json univ_mvar_decl :=\n\u27e8\u03bb msg, match msg with\n  | (json.array $ [c, json.array [un, pp]]) := do\n    (c_nm : name) \u2190 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\u27e9\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 \u2192 tactic bool))\n\nmeta instance : has_from_json local_decl := \n\u27e8\u03bb msg, match msg with\n  | (json.array $ [c, json.array [un, pp, ty, val, bi, idx]]) := do\n    (c_nm : name) \u2190 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\u27e9\n\nmeta instance : has_from_json local_decl2 :=\n\u27e8\u03bb msg, match msg with\n  | (json.array $ [c, json.array [un, pp, ety, bi, ty, prev, frozen, ld]]) := do\n    (c_nm : name) \u2190 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\u27e9\n\nmeta instance : has_from_json context.decl :=\nlet \u27e8fn\u2081\u27e9 := (by apply_instance : has_from_json mvar_decl) in\nlet \u27e8fn\u2082\u27e9 := (by apply_instance : has_from_json univ_mvar_decl) in\nlet \u27e8fn\u2083\u27e9 := (by apply_instance : has_from_json local_decl2) in\n\u27e8\u03bb msg, match msg with\n  | (json.array $ [c, json.array args]) := do\n    (c_nm : name) \u2190 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\u2081 args.head else\n    if c_nm = `context.decl.univ_mvar_decl then context.decl.univ_mvar_decl <$> fn\u2082 args.head else\n    if c_nm = `context.decl.local_decl then context.decl.local_decl <$> fn\u2083 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\u27e9\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 \u00d7 tactic.tag)) := has_from_json_list\n\nmeta instance : has_from_json tactic_state_data :=\nlet \u27e8fn\u2081\u27e9 := (by apply_instance : has_from_json (list context.decl)) in\nlet \u27e8fn\u2082\u27e9 := (by apply_instance : has_from_json (list (name \u00d7 tactic.tag))) in\n\u27e8\u03bb msg, match msg with\n  | (json.array $ [c, json.array [decls_msg, goals_msg]]) := do\n    (c_nm : name) \u2190 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\u2081 decls_msg <*> fn\u2082 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\u27e9\n\n\nend instances\n\n-- convience functions and instances\n\nmeta instance mvar_decl_has_to_string : has_to_format mvar_decl := \n\u27e8 \u03bb 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}\" \u27e9 \n\nmeta instance univ_mvar_decl_has_to_string : has_to_format univ_mvar_decl := \n\u27e8 \u03bb d, format! \"{{univ_mvar_decl .\\nunique_name := {d.unique_name},\\nassignment := {d.assignment},\\n}\" \u27e9 \n\nmeta instance local_decl_has_to_string : has_to_format local_decl := \n\u27e8 \u03bb 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}\" \u27e9 \n\nmeta instance local_decl2_has_to_string : has_to_format local_decl2 := \n\u27e8 \u03bb 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}\" \u27e9 \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\u27e8 \u03bb 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 \u27e9\n\nmeta instance context_has_to_string : has_to_format context := \n\u27e8 \u03bb cxt, format! \"{cxt.decls}\" \u27e9\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 (\u03bb d, \u00ac (cxt1.names.contains d.unique_name))),\n  names := cxt1.names.fold cxt2.names $ \u03bb n ns, ns.insert n\n}\n\nmeta instance context.has_append : has_append context := \u27e8 context.append \u27e9\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 {\u03b1 : Type} [decidable_eq \u03b1] (a : \u03b1) : list \u03b1 -> option \u03b1\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 (\u03bb 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 (\u03bb 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 (\u03bb 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 $ \u03bb 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 \u2190 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 \u2192 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 \u00d7 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) \u00d7 (name_map local_context) \u00d7 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) \u2218 expr.unfold_string_macros \u2218 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 (\u03bb 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) \u2218 expr.unfold_string_macros \u2218 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) \u00d7 (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 $ \u03bb \u27e8nm, tag\u27e9, 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 $ \u03bb 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 $ \u03bb \u27e8g, tag\u27e9, 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 $ \u03bb 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 $ \u03bb 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 (\u03b1 : 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 {\u03b1 \u03b2 \u03b3 : Type} --(f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3)\n--   : \u03b1 :=\n-- begin\n--   trace_context,\n--   refresh_tactic_state,\n--   trace_context,\n-- end\n\n-- -- Frozen local instances\n-- def fish {\u03b1 \u03b2 \u03b3} {m : Type \u2192 Type} [monad m] (f : m \u03b1 \u2192 m \u03b2) (g : m \u03b2 \u2192 m \u03b3)\n--   : m \u03b1 \u2192 m \u03b3 :=\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 \u03b1  -- 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": "import Smt\n\ntheorem contains : \"a\".contains 'a' := by\n  smt\n  sorry\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/Test/String/Contains.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.04023794521321183, "lm_q1q2_score": 0.0131846991365301}}
{"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.dlist.basic\nimport Mathlib.logic.function.basic\nimport Mathlib.control.basic\nimport Mathlib.meta.expr\nimport Mathlib.meta.rb_map\nimport Mathlib.data.bool\nimport Mathlib.tactic.binder_matching\nimport Mathlib.tactic.lean_core_docs\nimport Mathlib.tactic.interactive_expr\nimport Mathlib.Lean3Lib.system.io\nimport Mathlib.PostPort\n\nuniverses u_1 l_2 l_1 \n\nnamespace Mathlib\n\nprotected instance pos.has_lt : HasLess pos :=\n  { Less := fun (x y : pos) => (pos.line x, pos.column x) < (pos.line y, pos.column y) }\n\nnamespace expr\n\n\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_nat \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`. -/\n/-- Given an expr `\u03b1` representing a type with numeral structure,\n`of_int \u03b1 n` creates the `\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\n/-- Generates an expression of the form `\u2203(args), inner`. `args` is assumed to be a list of local\nconstants. When possible, `p \u2227 q` is used instead of `\u2203(_ : p), q`. -/\n/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/\n/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,\nwith initial value `a`. -/\n/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`\nwith `new`. The occurrences of `old` in `e` are determined using keyed matching\nwith transparency `md`; see `kabstract` for details. If `unify` is true,\nwe may assign metavariables in `e` as we match subterms of `e` against `old`. -/\nend expr\n\n\nnamespace interaction_monad\n\n\n/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/\n-- Note that this is a generalization of `tactic.read` in core.\n\n/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/\n-- Note that this is a generalization of `tactic.write` in core.\n\n/--\n`run_with_state state tac` applies `tac` to the given state `state` and returns the result,\nsubsequently restoring the original state.\nIf `tac` fails, then `run_with_state` does too.\n-/\nend interaction_monad\n\n\nnamespace format\n\n\n/-- `join' [a,b,c]` produces the format object `abc`.\nIt differs from `format.join` by using `format.nil` instead of `\"\"` for the empty list. -/\n/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,\nwhere `.` represents `format.join`. -/\n/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`\nthe result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`\neach line break is decided independently -/\n/-- Format a list as a comma separated list, without any brackets. -/\nend format\n\n\n/-- format a `list` by separating elements with `soft_break` instead of `line` -/\nnamespace tactic\n\n\n/-- Private work function for `add_local_consts_as_local_hyps`: given\n    `mappings : list (expr \u00d7 expr)` corresponding to pairs `(var, hyp)` of variables and the local\n    hypothesis created as a result and `(var :: rest) : list expr` of more local variables we\n    examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the\n    back of the queue and recurse. If it does not, then we perform replacements inside the type of\n    `var` using the `mappings`, create a new associate local hypothesis, add this to the list of\n    mappings, and recurse. We are done once all local hypotheses have been processed.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\n/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the\n    tactic state. This is harder than it sounds, since the list of local constants which we have\n    been passed can have dependencies between their types.\n\n    For example, suppose we have two local constants `n : \u2115` and `h : n = 3`. Then we cannot blindly\n    add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as\n    a new local hypothesis, not the old local constant `n` with the same name. Of course, these\n    dependencies can be nested arbitrarily deep.\n\n    If the list of passed local constants have types which depend on one another (which can only\n    happen by hand-crafting the `expr`s manually), this function will loop forever. -/\n/- The `list.reverse` below is a performance optimisation since the list of available variables\n   reported by the system is often mostly the reverse of the order in which they are dependent. -/\n\n/-- Compute the arity of explicit arguments of `type`. -/\n/-- Compute the arity of explicit arguments of `fn`'s type. -/\n/--\nFor `e = f x\u2081 ... x\u2099`, `get_app_fn_args_whnf e` returns `(f, [x\u2081, ..., x\u2099])`. `e`\nis normalised as necessary; for example:\n\n```\nget_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])\n```\n\nThe returned expression is in whnf, but the arguments are generally not.\n-/\n/--\n`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is\nnormalised as necessary (with transparency `md`). `unfold_ginductive` controls\nwhether constructors of generalised inductive types are unfolded. The returned\nexpression is in whnf.\n-/\n/--\n`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x\u2081 ... x\u2099`,\nwhere `C` is a constant, after normalisation with transparency `md`. If so, the\nname of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded.\n-/\n/--\n`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`\nis normalised as necessary (with transparency `md`). `unfold_ginductive`\ncontrols whether constructors of generalised inductive types are unfolded. The\nreturned expressions are not necessarily in whnf.\n-/\n/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with pi binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``pis [a, b] `(f a b)`` will return the expression\n`\u03a0 (a : Ta) (b : Tb), f a b`. -/\n/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.\n`loc_consts` should be a list of local constants. The function will abstract these local\nconstants from `f` and bind them with lambda binders.\n\nFor example, if `a, b` are local constants with types `Ta, Tb`,\n``lambdas [a, b] `(f a b)`` will return the expression\n`\u03bb (a : Ta) (b : Tb), f a b`. -/\n-- TODO: move to `declaration` namespace in `meta/expr.lean`\n\n/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named\n`ls`, type `t`, and body `e`. -/\n/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this\nto the environment as a theorem with name `n` and universe parameters `ls`. -/\n/-- `eval_expr' \u03b1 e` attempts to evaluate the expression `e` in the type `\u03b1`.\nThis is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare\nsituations the latter will fail but the former will succeed. -/\n/-- `mk_fresh_name` returns identifiers starting with underscores,\nwhich are not legal when emitted by tactic programs. `mk_user_fresh_name`\nturns the useful source of random names provided by `mk_fresh_name` into\nnames which are usable by tactic programs.\n\nThe returned name has four components which are all strings. -/\n/-- `has_attribute' attr_name decl_name` checks\nwhether `decl_name` exists and has attribute `attr_name`. -/\n/-- Checks whether the name is a simp lemma -/\n/-- Checks whether the name is an instance. -/\n/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.\nCovers all declarations from the current file. -/\n/-- `get_decls_from` returns a dictionary mapping names to their\ncorresponding declarations.  Covers all declarations the files listed\nin `fs`, with the current file listed as `none`.\n\nThe path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present); e.g. `\"src/tactic/core.lean\"`\n\nPossible issue: `get_decls_from` uses `get_cwd`, the current working\ndirectory, which may not always point at the root of the project.\nIt would work better if it searched for the root directory or,\nbetter yet, if Lean exposed its path information.\n-/\n/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/\n/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it\nreturns that, otherwise it tries `nm_2`, `nm_3`, ... -/\n/--\nReturns a pair `(e, t)`, where `e \u2190 mk_const d.to_name`, and `t = d.type`\nbut with universe params updated to match the fresh universe metavariables in `e`.\n\nThis should have the same effect as just\n```lean\ndo e \u2190 mk_const d.to_name,\n   t \u2190 infer_type e,\n   return (e, t)\n```\nbut is hopefully faster.\n-/\n/--\nReplace every universe metavariable in an expression with a universe parameter.\n\n(This is useful when making new declarations.)\n-/\n/-- `mk_local n` creates a dummy local variable with name `n`.\nThe type of this local constant is a constant with name `n`, so it is very unlikely to be\na meaningful expression. -/\n/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,\n`y : ty x` and `z : tz x y`, creates an expression of sigma type:\n`\u27e8x,y,z\u27e9 : \u03a3' (x : tx) (y : ty x), tz x y`.\n-/\n/--\nUpdate the type of a local constant or metavariable. For local constants and\nmetavariables obtained via, for example, `tactic.get_local`, the type stored in\nthe expression is not necessarily the same as the type returned by `infer_type`.\nThis tactic, given a local constant or metavariable, updates the stored type to\nmatch the output of `infer_type`. If the input is not a local constant or\nmetavariable, `update_type` does nothing.\n-/\n/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`\ntimes and uses `ns` to name the resulting variables. Returns a triple: list of new variables,\nremaining term and unused variable names.\n-/\n/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose\ntype is a (nested) sum `\u2295`. Returns the list of local constants representing the components of `e`.\n-/\n/-- Given `elab_def`, a tactic to solve the current goal,\n`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it\nto close the goal. If `trusted` is false, it will be a meta definition. -/\n/-- Attempts to close the goal with `dec_trivial`. -/\n/-- Runs a tactic for a result, reverting the state after completion. -/\n/-- Runs a tactic for a result, reverting the state after completion or error. -/\n/-- Repeat a tactic at least once, calling it recursively on all subgoals,\nuntil it fails. This tactic fails if the first invocation fails. -/\n/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and\nat most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/\n/--\nGiven a tactic `tac` that takes an expression\nand returns a new expression and a proof of equality,\nuse that tactic to change the type of the hypotheses listed in `hs`,\nas well as the goal if `tgt = tt`.\n\nReturns `tt` if any types were successfully changed.\n-/\n/-- `revert_after e` reverts all local constants after local constant `e`. -/\n/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).\n  Returns the number of local constants that have been reverted. -/\n/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant\nwith name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.\n\n`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the\ngoal, in which case it just calls `assert`.\nIn contrast to `generalize` it already introduces the generalized variable. -/\n/--\n`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name\nprovided by the binder to name the new local constant.\nUnlike `intron`, it does not rename introduced constants if the names shadow existing constants.\n-/\n/-!\n### Various tactics related to local definitions (local constants of the form `x : \u03b1 := t`)\n\nWe call `t` the value of `x`.\n-/\n\n/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined\n  locally using a `let` expression. Otherwise it fails. -/\n/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form\n`e : \u03b1 := t`) and otherwise fails. -/\n/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`\n(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.\nwhereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes\nthem in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition\nrunning up to the first match. -/\n/-- `partition_local_deps vs`, with `vs` a list of local constants,\nreorders `vs` in the order they appear in the local context together\nwith the variables that follow them. If local context is `[a,b,c,d,e,f]`,\nand that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.\nThe head of each list is one of the variables given as a parameter. -/\n/-- `clear_value [e\u2080, e\u2081, e\u2082, ...]` clears the body of the local definitions `e\u2080`, `e\u2081`, `e\u2082`, ...\nchanging them into regular hypotheses. A hypothesis `e : \u03b1 := t` is changed to `e : \u03b1`. The order of\nlocals `e\u2080`, `e\u2081`, `e\u2082` does not matter as a permutation will be chosen so as to preserve type\ncorrectness. This tactic is called `clearbody` in Coq. -/\n/--\n`context_has_local_def` is true iff there is at least one local definition in\nthe context.\n-/\n/--\n`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the\ncontext up to and including `h` is a local definition.\n-/\n/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,\n`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting\nexpression and a proof of equality. -/\n/-- Caches unary type classes on a type `\u03b1 : Type.{univ}`. -/\n/-- Creates an `instance_cache` for the type `\u03b1`. -/\nnamespace instance_cache\n\n\n/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of\n`n c.\u03b1` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance\nvia type class resolution, and updates the cache. -/\n/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,\n`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/\n/-- Creates the application `n c.\u03b1 p l`, where `p` is a type class instance found in the cache `c`.\n-/\n/-- `c.of_nat n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`. -/\n/-- `c.of_int n` creates the `c.\u03b1`-valued numeral expression corresponding to `n`.\nThe output is either a numeral or the negation of a numeral. -/\nend instance_cache\n\n\n/-- A variation on `assert` where a (possibly incomplete)\nproof of the assertion is provided as a parameter.\n\n``(h,gs) \u2190 local_proof `h p tac`` creates a local `h : p` and\nuse `tac` to (partially) construct a proof for it. `gs` is the\nlist of remaining goals in the proof of `h`.\n\nThe benefits over assert are:\n- unlike with ``h \u2190 assert `h p, tac`` , `h` cannot be used by `tac`;\n- when `tac` does not complete the proof of `h`, returning the list\n  of goals allows one to write a tactic using `h` and with the confidence\n  that a proof will not boil over to goals left over from the proof of `h`,\n  unlike what would be the case when using `tactic.swap`.\n-/\n/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/\n/-- When `struct_n` is the name of a structure type,\n`subobject_names struct_n` returns two lists of names `(instances, fields)`.\nThe names in `instances` are the projections from `struct_n` to the structures that it extends\n(assuming it was defined with `old_structure_cmd false`).\nThe names in `fields` are the standard fields of `struct_n`. -/\n/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure\nnamed `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name\nof the projection is `prefix.name`.\n\n`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/\n/--\nReturn a list of all type classes which can be instantiated\nfor the given expression.\n-/\n/--\nFinds an instance of an implication `cond \u2192 tgt`.\nReturns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention\n`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,\nsince it has been \"proven\" by a metavariable.\n-/\n/-- Create a list of `n` fresh metavariables. -/\n/-- Returns the only goal, or fails if there isn't just one goal. -/\n/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,\nor until it fails. Always succeeds. -/\n/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first\ngoal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on\ncurrent goal. -/\n/-- This makes sure that the execution of the tactic does not change the tactic state.\nThis can be helpful while using rewrite, apply, or expr munging.\nRemember to instantiate your metavariables before you're done! -/\n/--\n`apply_list l`, for `l : list (tactic expr)`,\ntries to apply the lemmas generated by the tactics in `l` on the first goal, and\nfail if none succeeds.\n-/\n/--\nConstructs a list of `tactic expr` given a list of p-expressions, as follows:\n- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it\n- if the p-expression is a user attribute, add all the theorems with this attribute\n  to the list.\n\nWe need to return a list of `tactic expr`, rather than just `expr`, because these expressions\nwill be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.\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\nUnlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies\na lemma from the list until it can't.\n -/\n/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local\ncontext, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.\nFails if there is nothing named `h` in the local context. -/\n/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``\nor `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an\n`iff`, returns an expression with the `iff` converted to either the forwards or backwards\nimplication, as requested. -/\n/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., A \u2192 B`. -/\n/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.\nIf `ty` has the shape `\u03a0 ..., A \u2194 B`, returns an expression whose type is `\u03a0 ..., B \u2192 A`. -/\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the forward implication. -/\n/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,\ncreate the expression which is the reverse implication. -/\n/--\nAttempts to apply `e`, and if that fails, if `e` is an `iff`,\ntry applying both directions separately.\n-/\n/--\nConfiguration options for `apply_any`:\n* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.\n* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.\n* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.\n-/\n/--\nThis is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,\nand evaluates these as thunks before trying to apply them.\n\nWe need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.\n-/\n/--\n`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.\n\n`apply_any lemmas opt` allows control over how lemmas are applied.\n`opt` has fields:\n* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)\n* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)\n* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).\n\n`apply_any lemmas tac` calls the tactic `tac` after a successful application.\nDefaults to `skip`. This is used, for example, by `solve_by_elim` to arrange\nrecursive invocations of `apply_any`.\n-/\n/-- Try to apply a hypothesis from the local context to the goal. -/\n/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails\nif this is not a definitional equality.\n\n`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`\nby reverting `h`, changing the goal, and reintroducing hypotheses. -/\n/--\n`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,\nassuming `olde` and `newe` are defeq when elaborated.\n-/\n/-- Returns a list of all metavariables in the current partial proof. This can differ from\nthe list of goals, since the goals can be manually edited. -/\n/--\n`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,\nand fail otherwise.\n-/\n/-- Fail if the target contains a metavariable. -/\n/-- Succeeds only if the current goal is a proposition. -/\n/-- Succeeds only if we can construct an instance showing the\n  current goal is a subsingleton type. -/\n/--\nSucceeds only if the current goal is \"terminal\",\nin the sense that no other goals depend on it\n(except possibly through shared metavariables; see `independent_goal`).\n-/\n/--\nSucceeds only if the current goal is \"independent\", in the sense\nthat no other goals depend on it, even through shared meta-variables.\n-/\n/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,\nit only unfolds reducible definitions, so it sometimes fails faster. -/\n/-- Apply a tactic as many times as possible, collecting the results in a list.\nFail if the tactic does not succeed at least once. -/\n/-- Introduces one or more variables and returns the new local constants.\nFails if `intro` cannot be applied. -/\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nnamespace interactive\n\n\n/-- Run a tactic \"under binders\", by running `intros` before, and `revert` afterwards. -/\nend interactive\n\n\n/-- `successes` invokes each tactic in turn, returning the list of successful results. -/\n/--\nTry all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results,\nand reverting to the original `tactic_state`.\n-/\n-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.\n\n/--\nTry all the tactics in a list, each time starting at the original `tactic_state`,\nreturning the list of successful results sorted by\nthe value produced by a subsequent execution of the `sort_by` tactic,\nand reverting to the original `tactic_state`.\n-/\n/-- Return target after instantiating metavars and whnf. -/\n/--\nJust like `split`, `fsplit` applies the constructor when the type of the target is\nan inductive data type with one constructor.\nHowever it does not reorder goals or invoke `auto_param` tactics.\n-/\n-- FIXME check if we can remove `auto_param := ff`\n\n/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`\nsucceeds, clears the old hypothesis. -/\n/-- Calls `cases` on every local hypothesis, succeeding if\nit succeeds on at least one hypothesis. -/\n/--\n`note_anon t v`, given a proof `v : t`,\nadds `h : t` to the current context, where the name `h` is fresh.\n\n`note_anon none v` will infer the type `t` from `v`.\n-/\n-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.\n\n/-- `find_local t` returns a local constant with type t, or fails if none exists. -/\n/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values\nof the previous local constants. `l` is a list of local constants and their values. -/\n/--\nInstantiates metavariables that appear in the current goal.\n-/\n/--\nInstantiates metavariables in all goals.\n-/\n/-- Protect the declaration `n` -/\nend tactic\n\n\nnamespace lean.parser\n\n\n/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the\ncurrent line. -/\n/-- Inner recursion for `emit_code_here`. -/\n/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in\nsource code. -/\n/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the\ntop level, giving access to operations like `emit_code_here`. -/\n/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).\n\nThis function deserves a C++ implementation in core lean, and will fail if it is not called from\nthe body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/\n/-- `get_variables` returns a list of existing variable names, along with their types and binder\ninfo. -/\n/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been\n\"included\" by an `include v` statement and are not (yet) `omit`ed. -/\n/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local\nvariables referenced in `es : list pexpr`, and those variables which have been `include`ed in the\nlocal context---precisely those variables which would be ambiently accessible if we were in a\ntactic-mode block where the goals had types `es.mmap to_expr`, for example.\n\nReturns a new `ts : tactic_state` with these local variables added, and\n`mappings : list (expr \u00d7 expr)`, for which pairs `(var, hyp)` correspond to an existing variable\n`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/\nend lean.parser\n\n\nnamespace tactic\n\n\n/--\nHole command used to fill in a structure's field when specifying an instance.\n\nIn the following:\n\n```lean\ninstance : monad id :=\n{! !}\n```\n\ninvoking the hole command \"Instance Stub\" (\"Generate a skeleton for the structure under\nconstruction.\") produces:\n\n```lean\ninstance : monad id :=\n{ map := _,\n  map_const := _,\n  pure := _,\n  seq := _,\n  seq_left := _,\n  seq_right := _,\n  bind := _ }\n```\n-/\n/-- Like `resolve_name` except when the list of goals is\nempty. In that situation `resolve_name` fails whereas\n`resolve_name'` simply proceeds on a dummy goal -/\n/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/\n/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/\n/--\nHole command used to generate a `match` expression.\n\nIn the following:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\n{! e !}\n```\n\ninvoking hole command \"Match Stub\" (\"Generate a list of equations for a `match` expression\")\nproduces:\n\n```lean\nmeta def foo (e : expr) : tactic unit :=\nmatch e with\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\nend\n```\n-/\n/--\nInvoking hole command \"Equations Stub\" (\"Generate a list of equations for a recursive definition\")\nin the following:\n\n```lean\nmeta def foo : {! expr \u2192 tactic unit !} -- `:=` is omitted\n```\n\nproduces:\n\n```lean\nmeta def foo : expr \u2192 tactic unit\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\nA similar result can be obtained by invoking \"Equations Stub\" on the following:\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- do not forget to write `:=`!!\n{! !}\n```\n\n```lean\nmeta def foo : expr \u2192 tactic unit := -- don't forget to erase `:=`!!\n| (expr.var a) := _\n| (expr.sort a) := _\n| (expr.const a a_1) := _\n| (expr.mvar a a_1 a_2) := _\n| (expr.local_const a a_1 a_2 a_3) := _\n| (expr.app a a_1) := _\n| (expr.lam a a_1 a_2 a_3) := _\n| (expr.pi a a_1 a_2 a_3) := _\n| (expr.elet a a_1 a_2 a_3) := _\n| (expr.macro a a_1) := _\n```\n\n-/\n/--\nThis command lists the constructors that can be used to satisfy the expected type.\n\nInvoking \"List Constructors\" (\"Show the list of constructors of the expected type\")\nin the following hole:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! !}\n```\n\nproduces:\n\n```lean\ndef foo : \u2124 \u2295 \u2115 :=\n{! sum.inl, sum.inr !}\n```\n\nand will display:\n\n```lean\nsum.inl : \u2124 \u2192 \u2124 \u2295 \u2115\n\nsum.inr : \u2115 \u2192 \u2124 \u2295 \u2115\n```\n\n-/\n/-- Makes the declaration `classical.prop_decidable` available to type class inference.\nThis asserts that all propositions are decidable, but does not have computational content. -/\n/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,\nreturns the expression `f \u2218 g \u2218 h`. -/\n/-- Given two expressions `e\u2080` and `e\u2081`, return the expression `` `(%%e\u2080 \u2194 %%e\u2081)``. -/\n/--\nFrom a lemma of the shape `\u2200 x, f (g x) = h x`\nderive an auxiliary lemma of the form `f \u2218 g = h`\nfor reasoning about higher-order functions.\n-/\n/-- A user attribute that applies to lemmas of the shape `\u2200 x, f (g x) = h x`.\nIt derives an auxiliary lemma of the form `f \u2218 g = h` for reasoning about higher-order functions.\n-/\n@[simp] theorem Mathlib.is_lawful_applicative.map_comp_pure {f : Type l_2 \u2192 Type l_1} [Applicative f] [c : is_lawful_applicative f] {\u03b1 : Type l_2} {\u03b2 : Type l_2} (g : \u03b1 \u2192 \u03b2) : Functor.map g \u2218 pure = pure \u2218 g :=\n  funext fun (x : \u03b1) => map_pure g x\n\n/--\nCopies a definition into the `tactic.interactive` namespace to make it usable\nin proof scripts. It allows one to write\n\n```lean\n@[interactive]\nmeta def my_tactic := ...\n```\n\ninstead of\n\n```lean\nmeta def my_tactic := ...\n\nrun_cmd add_interactive [``my_tactic]\n```\n-/\n/--\nUse `refine` to partially discharge the goal,\nor call `fconstructor` and try again.\n-/\n/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations\nat the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to\nthe expected type.\n\n```lean\nexample : \u2203 x : \u2124, x = x :=\nby tactic.use ``(42)\n```\n\nSee the doc string for `tactic.interactive.use` for more information.\n -/\n/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the\nlocal context. -/\n/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/\n/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)\nfinds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/\n/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/\n/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/\n/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing\ninteractive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.\nIt does *not* use the `namespace` command, so it will typically be used after\n`namespace tactic.interactive`.\n-/\n/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if\n`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/\n/--\n`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.\n-/\n/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/\n/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,\n  returns the error message. -/\n/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/\n/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.\n-/\n/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message\nof `t`. -/\n/--\n``trace_if_enabled `n msg`` traces the message `msg`\nonly if tracing is enabled for the name `n`.\n\nCreate new names registered for tracing with `declare_trace n`.\nThen use `set_option trace.n true/false` to enable or disable tracing for `n`.\n-/\n/--\n``trace_state_if_enabled `n msg`` prints the tactic state,\npreceded by the optional string `msg`,\nonly if tracing is enabled for the name `n`.\n-/\n/--\nThis combinator is for testing purposes. It succeeds if `t` fails with message `msg`,\nand fails otherwise.\n-/\n/--\nConstruct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.\n-/\n/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the\ninitial goals and returns the goals `tac` ended on. -/\n/-- like `with_local_goals` but discards the resulting goals -/\n/-- Representation of a proof goal that lends itself to comparison. The\nfollowing goal:\n\n```lean\nl\u2080 : T,\nl\u2081 : T\n\u22a2 \u2200 v : T, foo\n```\n\nis represented as\n\n```\n(2, \u2200 l\u2080 l\u2081 v : T, foo)\n```\n\nThe number 2 indicates that first the two bound variables of the\n`\u2200` are actually local constant. Comparing two such goals with `=`\nrather than `=\u2090` or `is_def_eq` tells us that proof script should\nnot see the difference between the two.\n -/\n/-- proof state made of multiple `goal` meant for comparing\nthe result of running different tactics -/\n/-- create a `packaged_goal` corresponding to the current goal -/\n/-- `goal_of_mvar g`, with `g` a meta variable, creates a\n`packaged_goal` corresponding to `g` interpretted as a proof goal -/\n/-- `get_proof_state` lists the user visible goal for each goal\nof the current state and for each goal, abstracts all of the\nmeta variables of the other gaols.\n\nThis produces a list of goals in the form of `\u2115 \u00d7 expr` where\nthe `expr` encodes the following proof state:\n\n```lean\n2 goals\nl\u2081 : t\u2081,\nl\u2082 : t\u2082,\nl\u2083 : t\u2083\n\u22a2 tgt\u2081\n\n\u22a2 tgt\u2082\n```\n\nas\n\n```lean\n[ (3, \u2200 (mv : tgt\u2081) (mv : tgt\u2082) (l\u2081 : t\u2081) (l\u2082 : t\u2082) (l\u2083 : t\u2083), tgt\u2081),\n  (0, \u2200 (mv : tgt\u2081) (mv : tgt\u2082), tgt\u2082) ]\n```\n\nwith 2 goals, the first 2 bound variables encode the meta variable\nof all the goals, the next 3 (in the first goal) and 0 (in the second goal)\nare the local constants.\n\nThis representation allows us to compare goals and proof states while\nignoring information like the unique name of local constants and\nthe equality or difference of meta variables that encode the same goal.\n-/\n/--\nRun `tac` in a disposable proof state and return the state.\nSee `proof_state`, `goal` and `get_proof_state`.\n-/\n/-- A type alias for `tactic format`, standing for \"pretty print format\". -/\n/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/\n/-- an alias for `pp`. -/\n/-- See `format!` in `init/meta/interactive_base.lean`.\n\nThe main differences are that `pp` is called instead of `to_fmt` and that we can use\narguments of type `tactic \u03b1` in the quotations.\n\nNow, consider the following:\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace format!\"{e}\"  -- outputs `has_add.add.{0} nat nat.has_add\n                    -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`\ntrace pformat!\"{e}\" -- outputs `3 + 7`\n```\n\nThe difference is significant. And now, the following is expressible:\n\n```lean\ne \u2190 to_expr ``(3 + 7),\ntrace pformat!\"{e} : {infer_type e}\" -- outputs `3 + 7 : \u2115`\n```\n\nSee also: `trace!` and `fail!`\n-/\n/--\nThe combination of `pformat` and `fail`.\n-/\n/--\nThe combination of `pformat` and `trace`.\n-/\n/-- A hackish way to get the `src` directory of mathlib. -/\n/-- Checks whether a declaration with the given name is declared in mathlib.\nIf you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,\nsince it is expensive to execute `get_mathlib_dir` many times. -/\n/--\nRuns a tactic by name.\nIf it is a `tactic string`, return whatever string it returns.\nIf it is a `tactic unit`, return the name.\n(This is mostly used in invoking \"self-reporting tactics\", e.g. by `tidy` and `hint`.)\n-/\n/-- auxiliary function for `apply_under_n_pis` -/\n/--\nAssumes `pi_expr` is of the form `\u03a0 x1 ... xn xn+1..., _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\n/--\nAssumes `pi_expr` is of the form `\u03a0 x1 ... xn, _`.\nCreates a pexpr of the form `\u03a0 x1 ... xn, func (arg x1 ... xn)`.\nAll arguments (implicit and explicit) to `arg` should be supplied. -/\n/--\nIf `func` is a `pexpr` representing a function that takes an argument `a`,\n`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.\nWhen `tgt` is a `pi` expr, `func` is elaborated in a context\nwith the domain of `tgt`.\n\nExamples:\n* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function\n  argument.\n* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument\n  of type `\u03b1 \u2192 \u03b1`.\n* ```get_pexpr_arg_arity_with_tgt ``(module R) `(\u03a0 (R : Type), comm_ring R \u2192 true)``` returns 0\n-/\n/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.\n\n`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a\ndeclaration named `m` can be found. -/\n/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`\nand creates a local notation to refer to it.\n\n`import_private foo` looks for `foo` in all imported files.\n\nWhen possible, make `foo` non-private rather than using this feature.\n -/\n/--\nThe command `mk_simp_attribute simp_name \"description\"` creates a simp set with name `simp_name`.\nLemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.\n`mk_simp_attribute simp_name none` will use a default description.\n\nAppending the command with `with attr1 attr2 ...` will include all declarations tagged with\n`attr1`, `attr2`, ... in the new simp set.\n\nThis command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string\nto the attribute that is defined. If you need to create a simp set in a file where this command is\nnot available, you should use\n```lean\nrun_cmd mk_simp_attr `simp_name\nrun_cmd add_doc_string `simp_attr.simp_name \"Description of the simp set here\"\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/core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.03358950456175575, "lm_q1q2_score": 0.013178399746642878}}
{"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 {\u03b1 : Type u} {\u03b2 : Type v}\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ndef Parallel.aux2 : List (Computation \u03b1) \u2192 Sum \u03b1 (List (Computation \u03b1)) :=\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 \u03b1) \u00d7 Wseq (Computation \u03b1) \u2192\n      Sum \u03b1 (List (Computation \u03b1) \u00d7 Wseq (Computation \u03b1))\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 \u03b1)) : Computation \u03b1 :=\n  corec Parallel.aux1 ([], S)\n#align computation.parallel Computation.parallel\n\ntheorem TerminatesParallel.aux :\n    \u2200 {l : List (Computation \u03b1)} {S c},\n      c \u2208 l \u2192 Terminates c \u2192 Terminates (corec Parallel.aux1 (l, S)) :=\n  by\n  have lem1 :\n    \u2200 l S, (\u2203 a : \u03b1, parallel.aux2 l = Sum.inl a) \u2192 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  \u00b7 intro a l S m\n    apply lem1\n    induction' l with c l IH generalizing m <;> simp at m\n    \u00b7 contradiction\n    cases' m with e m\n    \u00b7 rw [\u2190 e]\n      simp [parallel.aux2]\n      cases' List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l with a' ls\n      exacts[\u27e8a', rfl\u27e9, \u27e8a, rfl\u27e9]\n    \u00b7 cases' IH m with a' e\n      simp [parallel.aux2]\n      simp [parallel.aux2] at e\n      rw [e]\n      exact \u27e8a', rfl\u27e9\n  \u00b7 intro s IH l S m\n    have H1 : \u2200 l', parallel.aux2 l = Sum.inr l' \u2192 s \u2208 l' :=\n      by\n      induction' l with c l IH' generalizing m <;> intro l' e' <;> simp at m\n      \u00b7 contradiction\n      cases' m with e m <;> simp [parallel.aux2] at e'\n      \u00b7 rw [\u2190 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 [\u2190 e']\n        simp\n      \u00b7 induction' e : List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l with a' ls <;>\n          rw [e] at e'\n        \u00b7 contradiction\n        have := IH' m _ e\n        simp [parallel.aux2] at e'\n        cases destruct c <;> injection e' with h'\n        rw [\u2190 h']\n        simp [this]\n    induction' h : parallel.aux2 l with a l'\n    \u00b7 exact lem1 _ _ \u27e8a, h\u27e9\n    \u00b7 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 (_ | \u27e8_ | c, S'\u27e9) <;> simp [parallel.aux1] <;> apply IH <;>\n        simp [this]\n#align computation.terminates_parallel.aux Computation.TerminatesParallel.aux\n\ntheorem terminates_parallel {S : Wseq (Computation \u03b1)} {c} (h : c \u2208 S) [T : Terminates c] :\n    Terminates (parallel S) :=\n  by\n  suffices\n    \u2200 (n) (l : List (Computation \u03b1)) (S c),\n      c \u2208 l \u2228 some (some c) = Seq.nth S n \u2192 Terminates c \u2192 Terminates (corec Parallel.aux1 (l, S))\n    from\n    let \u27e8n, h\u27e9 := 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  \u00b7 cases' o with a a\n    \u00b7 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 [\u2190 a]\n      simp\n    induction' h : parallel.aux2 l with a l' <;> have C : corec parallel.aux1 (l, S) = _\n    \u00b7 apply destruct_eq_ret\n      simp [parallel.aux1]\n      rw [h]\n      simp [rmap]\n    \u00b7 rw [C]\n      skip\n      infer_instance\n    \u00b7 apply destruct_eq_think\n      simp [parallel.aux1]\n      rw [h, H]\n      simp [rmap]\n    \u00b7 rw [C]\n      apply @Computation.think_terminates _ _ _\n      apply terminates_parallel.aux _ T\n      simp\n  \u00b7 cases' o with a a\n    \u00b7 exact terminates_parallel.aux a T\n    induction' h : parallel.aux2 l with a l' <;> have C : corec parallel.aux1 (l, S) = _\n    \u00b7 apply destruct_eq_ret\n      simp [parallel.aux1]\n      rw [h]\n      simp [rmap]\n    \u00b7 rw [C]\n      skip\n      infer_instance\n    \u00b7 apply destruct_eq_think\n      simp [parallel.aux1]\n      rw [h]\n      simp [rmap]\n    \u00b7 rw [C]\n      apply @Computation.think_terminates _ _ _\n      have TT : \u2200 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      \u00b7 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      \u00b7 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 \u03b1)} {a} (h : a \u2208 parallel S) :\n    \u2203 c \u2208 S, a \u2208 c :=\n  by\n  suffices\n    \u2200 C,\n      a \u2208 C \u2192\n        \u2200 (l : List (Computation \u03b1)) (S),\n          corec Parallel.aux1 (l, S) = C \u2192 \u2203 c, (c \u2208 l \u2228 c \u2208 S) \u2227 a \u2208 c\n    from\n    let \u27e8c, h1, h2\u27e9 := this _ h [] S rfl\n    \u27e8c, h1.resolve_left id, h2\u27e9\n  let F : List (Computation \u03b1) \u2192 Sum \u03b1 (List (Computation \u03b1)) \u2192 Prop :=\n    by\n    intro l a\n    cases' a with a l'\n    exact \u2203 c \u2208 l, a \u2208 c\n    exact \u2200 a', (\u2203 c \u2208 l', a' \u2208 c) \u2192 \u2203 c \u2208 l, a' \u2208 c\n  have lem1 : \u2200 l : List (Computation \u03b1), F l (parallel.aux2 l) :=\n    by\n    intro l\n    induction' l with c l IH <;> simp [parallel.aux2]\n    \u00b7 intro a h\n      rcases h with \u27e8c, hn, _\u27e9\n      exact False.elim hn\n    \u00b7 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      \u00b7 rcases IH with \u27e8c', cl, ac\u27e9\n        refine' \u27e8c', Or.inr cl, ac\u27e9\n      \u00b7 induction' h : destruct c with a c' <;> simp [rmap]\n        \u00b7 refine' \u27e8c, List.mem_cons_self _ _, _\u27e9\n          rw [destruct_eq_ret h]\n          apply ret_mem\n        \u00b7 intro a' h\n          rcases h with \u27e8d, dm, ad\u27e9\n          simp at dm\n          cases' dm with e dl\n          \u00b7 rw [e] at ad\n            refine' \u27e8c, List.mem_cons_self _ _, _\u27e9\n            rw [destruct_eq_think h]\n            exact think_mem ad\n          \u00b7 cases' IH a' \u27e8d, dl, ad\u27e9 with d dm\n            cases' dm with dm ad\n            exact \u27e8d, Or.inr dm, ad\u27e9\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  \u00b7 rw [h'] at this\n    rcases this with \u27e8c, cl, ac\u27e9\n    exact \u27e8c, Or.inl cl, ac\u27e9\n  \u00b7 induction' e : seq.destruct S with a <;> rw [e] at h'\n    \u00b7\n      exact\n        let \u27e8d, o, ad\u27e9 := IH _ _ h'\n        let \u27e8c, cl, ac\u27e9 := this a \u27e8d, o.resolve_right (wseq.not_mem_nil _), ad\u27e9\n        \u27e8c, Or.inl cl, ac\u27e9\n    \u00b7 cases' a with o S'\n      cases' o with c <;> simp [parallel.aux1] at h' <;> rcases IH _ _ h' with \u27e8d, dl | dS', ad\u27e9\n      \u00b7\n        exact\n          let \u27e8c, cl, ac\u27e9 := this a \u27e8d, dl, ad\u27e9\n          \u27e8c, Or.inl cl, ac\u27e9\n      \u00b7 refine' \u27e8d, Or.inr _, ad\u27e9\n        rw [seq.destruct_eq_cons e]\n        exact seq.mem_cons_of_mem _ dS'\n      \u00b7 simp at dl\n        cases' dl with dc dl\n        \u00b7 rw [dc] at ad\n          refine' \u27e8c, Or.inr _, ad\u27e9\n          rw [seq.destruct_eq_cons e]\n          apply seq.mem_cons\n        \u00b7\n          exact\n            let \u27e8c, cl, ac\u27e9 := this a \u27e8d, dl, ad\u27e9\n            \u27e8c, Or.inl cl, ac\u27e9\n      \u00b7 refine' \u27e8d, Or.inr _, ad\u27e9\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 : \u03b1 \u2192 \u03b2) (S) : map f (parallel S) = parallel (S.map (map f)) :=\n  by\n  refine'\n    eq_of_bisim\n      (fun c1 c2 =>\n        \u2203 l S,\n          c1 = map f (corec parallel.aux1 (l, S)) \u2227\n            c2 = corec parallel.aux1 (l.map (map f), S.map (map f)))\n      _ \u27e8[], S, rfl, rfl\u27e9\n  intro c1 c2 h;\n  exact\n    match c1, c2, h with\n    | _, _, \u27e8l, S, rfl, rfl\u27e9 => 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 \u27e8_, _, rfl, rfl\u27e9\n#align computation.map_parallel Computation.map_parallel\n\ntheorem parallel_empty (S : Wseq (Computation \u03b1)) (h : S.headI ~> none) : parallel S = empty _ :=\n  eq_empty_of_not_terminates fun \u27e8\u27e8a, m\u27e9\u27e9 =>\n    by\n    let \u27e8c, cs, ac\u27e9 := exists_of_mem_parallel m\n    let \u27e8n, nm\u27e9 := Wseq.exists_nth_of_mem cs\n    let \u27e8c', h'\u27e9 := 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 \u03b1)} (C : \u03b1 \u2192 Sort v) (H : \u2200 s \u2208 S, \u2200 a \u2208 s, C a) {a}\n    (h : a \u2208 parallel S) : C a :=\n  by\n  let T : wseq (Computation (\u03b1 \u00d7 Computation \u03b1)) := S.map fun c => c.map fun a => (a, c)\n  have : S = T.map (map fun c => c.1) :=\n    by\n    rw [\u2190 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 [\u2190 map_comp]\n    exact (map_id _).symm\n  have pe := congr_arg parallel this\n  rw [\u2190 map_parallel] at pe\n  have h' := h\n  rw [pe] at h'\n  haveI : terminates (parallel T) := (terminates_map_iff _ _).1 \u27e8\u27e8_, h'\u27e9\u27e9\n  induction' e : get (parallel T) with a' c\n  have : a \u2208 c \u2227 c \u2208 S := by\n    rcases exists_of_mem_map h' with \u27e8d, dT, cd\u27e9\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 \u27e8d', dT', ad'\u27e9\n    rcases wseq.exists_of_mem_map dT' with \u27e8c', cs', e'\u27e9\n    rw [\u2190 e'] at ad'\n    rcases exists_of_mem_map ad' with \u27e8a', ac', e'\u27e9\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 \u03b1)} {a} (H : \u2200 s \u2208 S, s ~> a) : parallel S ~> a :=\n  fun a' ma' =>\n  let \u27e8c, cs, ac\u27e9 := exists_of_mem_parallel ma'\n  H _ cs ac\n#align computation.parallel_promises Computation.parallel_promises\n\ntheorem mem_parallel {S : Wseq (Computation \u03b1)} {a} (H : \u2200 s \u2208 S, s ~> a) {c} (cs : c \u2208 S)\n    (ac : a \u2208 c) : a \u2208 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 \u03b1)} {a} (H : S.LiftRel Equiv T) :\n    (\u2200 s \u2208 S, s ~> a) \u2194 \u2200 t \u2208 T, t ~> a :=\n  \u27e8fun h1 t tT =>\n    let \u27e8s, sS, se\u27e9 := Wseq.exists_of_liftRel_right H tT\n    (promises_congr se _).1 (h1 _ sS),\n    fun h2 s sS =>\n    let \u27e8t, tT, se\u27e9 := Wseq.exists_of_liftRel_left H sS\n    (promises_congr se _).2 (h2 _ tT)\u27e9\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 \u03b1)} {a} (h1 : \u2200 s \u2208 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  \u27e8fun h => by\n    have aa := parallel_promises h1 h <;> rw [\u2190 aa] <;> rw [\u2190 aa] at h <;>\n      exact\n        let \u27e8s, sS, as\u27e9 := exists_of_mem_parallel h\n        let \u27e8t, tT, st\u27e9 := 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 [\u2190 aa] <;> rw [\u2190 aa] at h <;>\n      exact\n        let \u27e8s, sS, as\u27e9 := exists_of_mem_parallel h\n        let \u27e8t, tT, st\u27e9 := wseq.exists_of_lift_rel_right H sS\n        let aT := (st _).2 as\n        mem_parallel h1 tT aT\u27e9\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 \u03b1)} {a} (h2 : \u2200 t \u2208 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\u00f6lzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes H\u00f6lzl\n\nMonotone version of 1-point elimination for \u2203 (and \u2200).\n\n  `\u2203x, t[x, R x a] ~> t[a, rfl]`\n\nwith the (reflexive) relation `R`, and `t` is monotone in `R`:\n  `\u2200x y, R x y \u2192 t x \u2192 t y`.\n\nThen\n  (\u2203x, R x a \u2227 p x) \u2194 p a\nthen\n  assume h : p a, \u27e8a, h, R.refl a\u27e9\nand\n  assume \u27e8x, hx, hxa\u27e9, mono x a hxa hx\n\nOr with the following dependent monotonicity:\n  `\u2200x y (h : R x y), t x h \u2192 t y R.refl`.\n\nThen\n  (\u2203x, \u2203h:R x a, p x h) \u2194 p a R.refl\nthen\n  assume h : p a R.refl, \u27e8a, h, R.refl a\u27e9\nand\n  assume \u27e8x, hx, hxa\u27e9, mono x a hxa hx\n\n-/\nimport simp_loop.conv\n\ninductive bintree (\u03b1 : Type*)\n| leaf (a : \u03b1) : bintree\n| node (l r : bintree) : bintree\n\ndef list.dedup {\u03b1 : Type*} [decidable_eq \u03b1] : list \u03b1 \u2192 list \u03b1\n| []        := []\n| (x :: xs) := (if x \u2208 xs then xs.dedup else x :: xs.dedup)\n\nnamespace bintree\nvariables {\u03b1 : Type*} {\u03b2 : Type*}\n\ndef pos := list bool\n\ndef left : bintree \u03b1 \u2192 bintree \u03b1\n| (leaf a)   := leaf a\n| (node l r) := l\n\ndef right : bintree \u03b1 \u2192 bintree \u03b1\n| (leaf a)   := leaf a\n| (node l r) := r\n\ndef at_pos : pos \u2192 bintree \u03b1 \u2192 bintree \u03b1\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 : \u03b1 \u2192 \u03b2) : bintree \u03b1 \u2192 bintree \u03b2\n| (leaf a) := leaf (f a)\n| (node l r) := node (map l) (map r)\n\ndef mmap {m : Type* \u2192 Type*} [monad m] (f : \u03b1 \u2192 m \u03b2) : bintree \u03b1 \u2192 m (bintree \u03b2)\n| (leaf a)   := leaf <$> f a\n| (node l r) := node <$> mmap l <*> mmap r\n\nend bintree\n\n\ndef monotone {\u03b1 : Sort*} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (p : \u03b1 \u2192 Prop) : Prop :=\n\u2200x y, r x y \u2192 p x \u2192 p y\n\nlemma monotone_eq {\u03b1 : Type*} (p : \u03b1 \u2192 Prop) : monotone (=) p :=\nassume x y h, h \u25b8 id\n\n-- do we/want need a dependent version?\nlemma exists_elim_rel {\u03b1 : Sort*} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {p : \u03b1 \u2192 Prop} {a : \u03b1} [is_refl \u03b1 r]\n  (h : monotone r p) :\n  (\u2203x, r x a \u2227 p x) \u2194 p a :=\n\u27e8assume \u27e8x, hxa, hx\u27e9, h x a hxa hx, assume ha, \u27e8a, is_refl.refl r a, ha\u27e9\u27e9\n\nlemma ex_extend {\u03b1 : Type*} {p : \u03b1 \u2192 Prop} : (\u2203a, p a) \u2194 (\u2203a, p a \u2227 true) :=\n\u27e8assume \u27e8a, ha\u27e9, \u27e8a, ha, \u27e8\u27e9\u27e9, assume \u27e8a, ha, \u27e8\u27e9\u27e9, \u27e8a, ha\u27e9\u27e9\n\nlemma l_eq {p E : Prop} : (p \u2227 E) \u2194 (E \u2227 p) :=\nand_comm _ _\nlemma l_ex {p E : Prop} {r : E \u2192 Prop} : (p \u2227 (\u2203h:E, r h)) \u2194 (\u2203h:E, p \u2227 r h) :=\n\u27e8\u03bb\u27e8h, e, r\u27e9, \u27e8e, h, r\u27e9, \u03bb\u27e8e, h, r\u27e9, \u27e8h, e, r\u27e9\u27e9\nlemma l_cn {p q E : Prop} : (p \u2227 (E \u2227 q)) \u2194 (E \u2227 (p \u2227 q)) :=\n\u27e8\u03bb\u27e8h, e, r\u27e9, \u27e8e, h, r\u27e9, \u03bb\u27e8e, h, r\u27e9, \u27e8h, e, r\u27e9\u27e9\nlemma r_eq {p E : Prop} : (E \u2227 p) \u2194 (E \u2227 p) :=\niff.refl _\nlemma r_ex {p E : Prop} {r : E \u2192 Prop} : ((\u2203h:E, r h) \u2227 p) \u2194 (\u2203h:E, r h \u2227 p) :=\n\u27e8\u03bb\u27e8\u27e8e, r\u27e9, h\u27e9, \u27e8e, r, h\u27e9, \u03bb\u27e8e, r, h\u27e9, \u27e8\u27e8e, r\u27e9, h\u27e9\u27e9\nlemma r_cn {p q E : Prop} : ((E \u2227 q) \u2227 p) \u2194 (E \u2227 (q \u2227 p)) :=\n\u27e8\u03bb\u27e8\u27e8e, r\u27e9, h\u27e9, \u27e8e, r, h\u27e9, \u03bb\u27e8e, r, h\u27e9, \u27e8\u27e8e, r\u27e9, h\u27e9\u27e9\nlemma e_eq_Prop {p E : Prop} : (\u2203a:p, E) \u2194 (E \u2227 p) :=\n\u27e8\u03bb\u27e8a, h\u27e9, \u27e8h, a\u27e9, \u03bb\u27e8h, a\u27e9, \u27e8a, h\u27e9\u27e9\nlemma e_eq {\u03b1 : Sort*} {E : Prop} : (\u2203a:\u03b1, E) \u2194 (E \u2227 \u2203a:\u03b1, true) :=\n\u27e8\u03bb\u27e8a, h\u27e9, \u27e8h, \u27e8a, \u27e8\u27e9\u27e9\u27e9, \u03bb\u27e8h, \u27e8a, _\u27e9\u27e9, \u27e8a, h\u27e9\u27e9\nlemma e_ex {\u03b1 : Sort*} {E : Prop} {s : E \u2192 \u03b1 \u2192 Prop} : (\u2203a:\u03b1, \u2203h:E, s h a) \u2194 (\u2203h:E, \u2203a:\u03b1, s h a) :=\n\u27e8\u03bb\u27e8a, h, t\u27e9, \u27e8h, a, t\u27e9, \u03bb\u27e8a, h, t\u27e9, \u27e8h, a, t\u27e9\u27e9\nlemma e_cn {\u03b1 : Sort*} {E : Prop} {t : \u03b1 \u2192 Prop} : (\u2203a:\u03b1, E \u2227 t a) \u2194 (E \u2227 (\u2203a:\u03b1, t a)) :=\n\u27e8\u03bb\u27e8a, e, t\u27e9, \u27e8e, \u27e8a, t\u27e9\u27e9, \u03bb\u27e8e, \u27e8a, t\u27e9\u27e9, \u27e8a, e, t\u27e9\u27e9\n\nlemma l_congr {p q r : Prop} (h : q \u2194 r) : p \u2227 q \u2194 p \u2227 r :=\nand_congr (iff.refl p) h\nlemma r_congr {p q r : Prop} (h : q \u2194 r) : q \u2227 p \u2194 r \u2227 p :=\nand_congr h (iff.refl p)\nlemma ex_congr {\u03b1 : Sort*} {p q : \u03b1 \u2192 Prop} (h : \u2200a, p a \u2194 q a) : (\u2203a, p a) \u2194 (\u2203a, q a) :=\nexists_congr h\n\nlemma comm_l {\u03b1 : Sort*} {p : Prop} {q : \u03b1 \u2192 Prop} : p \u2227 (\u2203a, q a) \u2194 \u2203a, p \u2227 q a :=\n\u27e8\u03bb\u27e8a, hq, hp\u27e9, \u27e8hq, \u27e8a, hp\u27e9\u27e9, \u03bb \u27e8hq, \u27e8a, hp\u27e9\u27e9, \u27e8a, hq, hp\u27e9\u27e9\nlemma comm_r {\u03b1 : Sort*} {p : Prop} {q : \u03b1 \u2192 Prop} : (\u2203a, q a) \u2227 p \u2194 \u2203a, q a \u2227 p :=\n\u27e8\u03bb \u27e8\u27e8a, hp\u27e9, hq\u27e9, \u27e8a, hp, hq\u27e9, \u03bb\u27e8a, hp, hq\u27e9, \u27e8\u27e8a, hp\u27e9, hq\u27e9\u27e9\nlemma comm_ex {\u03b1 : Sort*} {\u03b2 : Sort*} {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203a b, p a b) \u2194 (\u2203b a, p a b) :=\n\u27e8\u03bb\u27e8a, \u27e8b, h\u27e9\u27e9, \u27e8b, \u27e8a, h\u27e9\u27e9, \u03bb\u27e8a, \u27e8b, h\u27e9\u27e9, \u27e8b, \u27e8a, h\u27e9\u27e9\u27e9\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\u27e8\u03bbi, 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\u27e9\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\u27e8\u03bbi, 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\u27e9\nend norm_form\n\nmeta def congr_ex {\u03b1} (c : conv \u03b1) : conv \u03b1 := congr_binder ``ex_congr (\u03bb_, c)\n\nmeta def congr {\u03b1} (c : conv \u03b1) : info \u2192 conv \u03b1\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 \u2192 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 \u2192 list expr \u2192 expr \u2192 bool)\n  (v : expr) (deps : list expr) : expr \u2192 tactic (option $ list $ info \u00d7 expr)\n| `(@Exists %%\u03b1 %%p) := if chk v deps \u03b1 then\n    return none\n  else do\n    (lam pp_n bi domain body) \u2190 return p | return (some []),\n    x \u2190 mk_local' pp_n bi domain,\n    return [(info.binder x (deps.any $ \u03bbv, v.occurs \u03b1), body.instantiate_var x)]\n| `(%%p \u2227 %%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 \u2192 list expr \u2192 expr \u2192 bool)\n  (v : expr) : list expr \u2192 expr \u2192 tactic (list $ list info) | deps e := do\nsome is \u2190 analyse chk v deps e | return [[]],\niss \u2190 is.mmap (\u03bb\u27e8i, t\u27e9, do\n  deps \u2190 return $ match i with (info.binder v tt) := v :: deps | _ := deps end,\n  iss \u2190 find deps t,\n  return $ iss.map $ \u03bbis, i :: is),\nreturn iss.join\n\nsection reorder\n\nprivate meta def reorder_dependent : list info \u2192 conv norm_form\n| [] := (do -- trace \"reorder_equality []\", trace_lhs,\n  `(_ = _) \u2190 lhs, return norm_form.eq) <|> return norm_form.ex\n| (i::xs)  := do\n  n \u2190 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 \u2192 conv (option (list info))\n| []      := return none\n| (i::is) := (do info.binder _ ff \u2190 return i, return is) <|> (do\n  some is' \u2190 congr (reorder_non_dependent is) i | return none,\n  r \u2190 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 {\u03b1} (elim : norm_form \u2192 conv \u03b1) : list info \u2192 conv \u03b1 | l := do\n-- trace (to_fmt \"reorder_and_elim \" ++ to_fmt l),\nsome l' \u2190 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 \u2194 x Q g z\n\n    \u27f9 f x R t \u2194 x Q t'\n    \u27f9 t Q g x \u2194 t' R x\n\nInjectivity rules:\n  f x R g y \u2194 x Q y\n\n    \u27f9 f x R t \u2194 x Q t'\n    \u27f9 t R g x \u2194 t' Q x\n\nSplitting rules:\n  f x R t \u2194 (C\u2081 \u2227 x Q\u2081 t\u2081) \u2228 (C\u2082 \u2227 x Q\u2082 t\u2082)\n\nSetup:\n\n* allow symmetric relations\n* apply the rules symmetrically\n* should we add dischargers for conditional rules, ala:\n    0 < R \u2192 x / R \u2264 S \u2194 x \u2264 S * R\n  or:\n    x / R \u2264 S \u2194 (0 < R \u2227 x \u2264 S * R) \u2228 (R < 0 \u2227 S * R \u2264 x) \u2228 (R = 0 \u2227 0 \u2264 S)\n    This one doesn't work for monotone elimination as we have x \u2264 S * R and S * R \u2264 x case.\n* conditionals:\n    \u2200x n i : \u2115, x + n = i \u2194 (n \u2264 i \u2227 x = i - n)\n    \u2200x n i : \u2115, x - n = i \u2194 ((i = 0 \u2227 x \u2264 n) \u2228 x = i + n)\n    \u2200x n i : \u2115, n - x = i \u2194 ((i = 0 \u2227 n \u2264 x) \u2228 (i \u2264 n \u2227 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 \u2194 x Q g z, used for term focusing\" }\n\nsection analyse\n\nmeta def conjs : expr \u2192 tactic (list expr)\n| `(%%a \u2227 %%b) := do\n  as \u2190 conjs a,\n  bs \u2190 conjs b,\n  return (as ++ bs)\n| e := return [e]\n\nmeta def disjs_of_conjs : expr \u2192 tactic (list $ list expr)\n| `(%%a \u2228 %%b) := do\n  as \u2190 disjs_of_conjs a,\n  bs \u2190 disjs_of_conjs b,\n  return (as ++ bs)\n| e := do\n  d \u2190 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 \u2192 tactic (expr \u00d7 expr \u00d7 expr)\n| (expr.app (expr.app f a) b) := return (f, a, b)\n| _ := fail \"term is not a relation application\"\n\ndef peep {\u03b1} : list \u03b1 \u2192 list (list \u03b1 \u00d7 \u03b1 \u00d7 list \u03b1)\n| []        := []\n| (a :: xs) := ([], a, xs) :: (peep xs).map (\u03bb\u27e8p, a', s\u27e9, (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 \u2190 disjs_of_conjs rhs,\ncandidates \u2190 disjs.mmap (\u03bbconjs, do\n  candidates \u2190 (peep conjs).mmap (\u03bbxs, (do\n    (ps, e, ss) \u2190 return xs,\n    (rel, l, r) \u2190 parse_rel e,\n    return $\n      (if l \u2208 vs \u2227 (r :: rel :: ps ++ ss).all (\u03bbe, \u00ac l.occurs e) then [l] else []) ++\n      (if r \u2208 vs \u2227 (l :: rel :: ps ++ ss).all (\u03bbe, \u00ac r.occurs e) then [r] else []))\n      <|> return []),\n  return candidates.join),\nlet candidates := vs.filter $ \u03bbv, candidates.all $ \u03bbcs, v \u2208 cs,\n\n(rel, l, r) \u2190 parse_rel lhs,\nlet candidates := candidates.filter $ \u03bbc,\n  \u00ac c.occurs rel \u2227 ((c.occurs l \u2227 \u00ac c.occurs r) \u2228 c.occurs r \u2227 \u00ac c.occurs l),\nlet candidates := candidates.dedup,\nlet vs' := vs.filter (\u03bbv, v.occurs lhs),\ncandidates.mmap (\u03bbc, 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 \u00d7 pattern := do\ne \u2190 get_env,\nd \u2190 e.get n,\nlet ls := d.univ_params.map level.param,\n(vs, `(%%lhs \u2194 %%rhs)) \u2190 mk_local_pis d.type,\nl \u2190 analyse_connection_aux ls vs lhs rhs,\nr \u2190 analyse_connection_aux ls vs rhs lhs,\nreturn (l.map (\u03bbp, (ff, p)) ++ r.map (\u03bbp, (tt, p)))\n\nmeta def ors (c : conv unit) : conv unit := do\n`(_ \u2228 _) \u2190 lhs | c,\ncongr_core (congr_core skip ors) ors,\nskip\n\nmeta def ands (c : conv unit) : conv unit := do\n`(_ \u2227 _) \u2190 lhs | c,\ncongr_core (congr_core skip ands) ands,\nskip\n\nmeta def local_eq (v\u2080 v\u2081 : expr) : bool :=\nv\u2080.is_local_constant \u2227 v\u2081.is_local_constant \u2227 v\u2080.local_uniq_name = v\u2081.local_uniq_name\n\nmeta def term_focus (l : list (name \u00d7 bool \u00d7 pattern)) (v : expr) : conv unit :=\nl.mfirst $ assume \u27e8n, symm, pat\u27e9, do\n  ([], [t]) \u2190 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 \u2190 lhs,\n    (_, l, r) \u2190 lift_tactic $ parse_rel l,\n    guard ((v.occurs l \u2227 \u00ac local_eq l v) \u2228 (v.occurs r \u2227 \u00ac local_eq r v)),\n    term_focus) <|> skip)\n\nend analyse\n\n/-\n\nLattices\n\n  x \u2264 y \u2293 z \u2194 x \u2264 y \u2227 x \u2264 z\n\n  y \u2293 z \u2264 x \u2194 y \\ z \u2264 x (Heyting algebra)\n\n  a \u2294 b \u2264 c \u2194 a \u2264 c \u2227 b \u2264 c\n\nCase: Focus on a\n  (\u2203 x, x \u2294 b \u2264 c \u2227 p x) \u2194 (\u2203x, x \u2264 c \u2227 b \u2264 c \u2227 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 \u2192 bool\n| `(%%l = %%r) := (l = x \u2227 deps.all (\u03bbx, \u00ac x.occurs r)) \u2228 (r = x \u2227 deps.all (\u03bbx, \u00ac 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 \u2190 congr_binder ``ex_congr (\u03bbv, do t \u2190 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": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Std.ShareCommon\nimport Lean.Parser.Command\nimport Lean.Util.CollectLevelParams\nimport Lean.Util.FoldConsts\nimport Lean.Meta.CollectFVars\nimport Lean.Elab.Command\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.Binders\nimport Lean.Elab.DeclUtil\nnamespace Lean.Elab\n\ninductive DefKind where\n  | \u00abdef\u00bb | \u00abtheorem\u00bb | \u00abexample\u00bb | \u00abopaque\u00bb | \u00ababbrev\u00bb\n  deriving Inhabited, BEq\n\ndef DefKind.isTheorem : DefKind \u2192 Bool\n  | \u00abtheorem\u00bb => true\n  | _         => false\n\ndef DefKind.isDefOrAbbrevOrOpaque : DefKind \u2192 Bool\n  | \u00abdef\u00bb    => true\n  | \u00abopaque\u00bb => true\n  | \u00ababbrev\u00bb => true\n  | _        => false\n\ndef DefKind.isExample : DefKind \u2192 Bool\n  | \u00abexample\u00bb => true\n  | _         => false\n\nstructure DefView where\n  kind          : DefKind\n  ref           : Syntax\n  modifiers     : Modifiers\n  declId        : Syntax\n  binders       : Syntax\n  type?         : Option Syntax\n  value         : Syntax\n  deriving?     : Option (Array Syntax) := none\n  deriving Inhabited\n\nnamespace Command\n\nopen Meta\n\ndef mkDefViewOfAbbrev (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\n  let (binders, type) := expandOptDeclSig stx[2]\n  let modifiers       := modifiers.addAttribute { name := `inline }\n  let modifiers       := modifiers.addAttribute { name := `reducible }\n  { ref := stx, kind := DefKind.abbrev, modifiers,\n    declId := stx[1], binders, type? := type, value := stx[3] }\n\ndef mkDefViewOfDef (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"def \" >> declId >> optDeclSig >> declVal >> optDefDeriving\n  let (binders, type) := expandOptDeclSig stx[2]\n  let deriving? := if stx[4].isNone then none else some stx[4][1].getSepArgs\n  { ref := stx, kind := DefKind.def, modifiers,\n    declId := stx[1], binders, type? := type, value := stx[3], deriving? }\n\ndef mkDefViewOfTheorem (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"theorem \" >> declId >> declSig >> declVal\n  let (binders, type) := expandDeclSig stx[2]\n  { ref := stx, kind := DefKind.theorem, modifiers,\n    declId := stx[1], binders, type? := some type, value := stx[3] }\n\nnamespace MkInstanceName\n\n-- Table for `mkInstanceName`\nprivate def kindReplacements : NameMap String :=\n  Std.RBMap.ofList [\n    (``Parser.Term.depArrow, \"DepArrow\"),\n    (``Parser.Term.\u00abforall\u00bb, \"Forall\"),\n    (``Parser.Term.arrow, \"Arrow\"),\n    (``Parser.Term.prop,  \"Prop\"),\n    (``Parser.Term.sort,  \"Sort\"),\n    (``Parser.Term.type,  \"Type\")\n  ]\n\nabbrev M := StateRefT String CommandElabM\n\ndef isFirst : M Bool :=\n  return (\u2190 get) == \"\"\n\ndef append (str : String) : M Unit :=\n  modify fun s => s ++ str\n\npartial def collect (stx : Syntax) : M Unit := do\n  match stx with\n  | Syntax.node k args =>\n    unless (\u2190 isFirst) do\n      match kindReplacements.find? k with\n      | some r => append r\n      | none   => pure ()\n    for arg in args do\n      collect arg\n  | Syntax.ident (preresolved := preresolved) .. =>\n    unless preresolved.isEmpty && (\u2190 resolveGlobalName stx.getId).isEmpty do\n      match stx.getId.eraseMacroScopes with\n      | Name.str _ str _ =>\n          if str[0].isLower then\n            append str.capitalize\n          else\n            append str\n      | _ => pure ()\n  | _ => pure ()\n\ndef mkFreshInstanceName : CommandElabM Name := do\n  let s \u2190 get\n  let idx := s.nextInstIdx\n  modify fun s => { s with nextInstIdx := s.nextInstIdx + 1 }\n  return Lean.Elab.mkFreshInstanceName s.env idx\n\npartial def main (type : Syntax) : CommandElabM Name := do\n  /- We use `expandMacros` to expand notation such as `x < y` into `LT.lt x y` -/\n  let type \u2190 liftMacroM <| expandMacros type\n  let (_, str) \u2190 collect type |>.run \"\"\n  if str.isEmpty then\n    mkFreshInstanceName\n  else\n    liftMacroM <| mkUnusedBaseName <| Name.mkSimple (\"inst\" ++ str)\n\nend MkInstanceName\n\ndef mkDefViewOfConstant (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser \"constant \" >> declId >> declSig >> optional declValSimple\n  let (binders, type) := expandDeclSig stx[2]\n  let val \u2190 match stx[3].getOptional? with\n    | some val => pure val\n    | none     =>\n      let val \u2190 `(arbitrary)\n      pure $ Syntax.node ``Parser.Command.declValSimple #[ mkAtomFrom stx \":=\", val ]\n  return {\n    ref := stx, kind := DefKind.opaque, modifiers := modifiers,\n    declId := stx[1], binders := binders, type? := some type, value := val\n  }\n\ndef mkDefViewOfInstance (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal\n  let attrKind        \u2190 liftMacroM <| toAttributeKind stx[0]\n  let prio            \u2190 liftMacroM <| expandOptNamedPrio stx[2]\n  let attrStx         \u2190 `(attr| instance $(quote prio):numLit)\n  let (binders, type) := expandDeclSig stx[4]\n  let modifiers       := modifiers.addAttribute { kind := attrKind, name := `instance, stx := attrStx }\n  let declId \u2190 match stx[3].getOptional? with\n    | some declId => pure declId\n    | none        =>\n      let id \u2190 MkInstanceName.main type\n      pure <| Syntax.node ``Parser.Command.declId #[mkIdentFrom stx id, mkNullNode]\n  return {\n    ref := stx, kind := DefKind.def, modifiers := modifiers,\n    declId := declId, binders := binders, type? := type, value := stx[5]\n  }\n\ndef mkDefViewOfExample (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"example \" >> declSig >> declVal\n  let (binders, type) := expandDeclSig stx[1]\n  let id              := mkIdentFrom stx `_example\n  let declId          := Syntax.node ``Parser.Command.declId #[id, mkNullNode]\n  { ref := stx, kind := DefKind.example, modifiers := modifiers,\n    declId := declId, binders := binders, type? := some type, value := stx[2] }\n\ndef isDefLike (stx : Syntax) : Bool :=\n  let declKind := stx.getKind\n  declKind == ``Parser.Command.\u00ababbrev\u00bb ||\n  declKind == ``Parser.Command.\u00abdef\u00bb ||\n  declKind == ``Parser.Command.\u00abtheorem\u00bb ||\n  declKind == ``Parser.Command.\u00abconstant\u00bb ||\n  declKind == ``Parser.Command.\u00abinstance\u00bb ||\n  declKind == ``Parser.Command.\u00abexample\u00bb\n\ndef mkDefView (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView :=\n  let declKind := stx.getKind\n  if declKind == ``Parser.Command.\u00ababbrev\u00bb then\n    pure $ mkDefViewOfAbbrev modifiers stx\n  else if declKind == ``Parser.Command.\u00abdef\u00bb then\n    pure $ mkDefViewOfDef modifiers stx\n  else if declKind == ``Parser.Command.\u00abtheorem\u00bb then\n    pure $ mkDefViewOfTheorem modifiers stx\n  else if declKind == ``Parser.Command.\u00abconstant\u00bb then\n    mkDefViewOfConstant modifiers stx\n  else if declKind == ``Parser.Command.\u00abinstance\u00bb then\n    mkDefViewOfInstance modifiers stx\n  else if declKind == ``Parser.Command.\u00abexample\u00bb then\n    pure $ mkDefViewOfExample modifiers stx\n  else\n    throwError \"unexpected kind of definition\"\n\nbuiltin_initialize registerTraceClass `Elab.definition\n\nend Command\nend Lean.Elab\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/Elab/DefView.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649166448126, "lm_q2_score": 0.057493279204116406, "lm_q1q2_score": 0.01311746487749768}}
{"text": "import ReactorModel.Determinism.InstantaneousExecution\n\nnamespace Execution\n\nopen ReactorType\nopen State (Closed)\n\nvariable [Indexable \u03b1] {s s\u2081 s\u2082 : State \u03b1} [State.Nontrivial s] [State.Nontrivial s\u2081]\n\nnamespace AdvanceTag\n\ntheorem not_Closed (a : s\u2081 \u21d3- s\u2082) : \u00ac(Closed s\u2082) :=\n  have := a.advance.preserves_Nontrivial -- TODO: Make this work via type class inference.\n  (absurd a.advance.progress_empty \u00b7.progress_Nonempty.ne_empty)\n\ntheorem nonrepeatable (a\u2081 : s\u2081 \u21d3- s\u2082) (a\u2082 : s\u2082 \u21d3- s\u2083) : False :=\n  absurd a\u2082.closed a\u2081.not_Closed\n\ntheorem tag_lt (a : s\u2081 \u21d3- s\u2082) : s\u2081.tag < s\u2082.tag :=\n  a.advance.tag_lt\n\ntheorem tag_ne (a : s\u2081 \u21d3- s\u2082) : s\u2081.tag \u2260 s\u2082.tag :=\n  ne_of_lt a.tag_lt\n\ntheorem determinisic (a\u2081 : s \u21d3- s\u2081) (a\u2082 : s \u21d3- s\u2082) : s\u2081 = s\u2082 :=\n  a\u2081.advance.determinisic a\u2082.advance\n\ninstance preserves_Nontrivial [State.Nontrivial s\u2081] {e : s\u2081 \u21d3- s\u2082} : State.Nontrivial s\u2082 :=\n  e.advance.preserves_Nontrivial\n\nend AdvanceTag\n\nnamespace Instantaneous\nnamespace ClosedExecution\n\ntheorem not_Closed (e : s\u2081 \u21d3| s\u2082) : \u00ac(Closed s\u2081) := by\n  simp [Closed]\n  have h := Partial.Nonempty.iff_ids_nonempty.mp $ State.Nontrivial.nontrivial (s := s\u2081)\n  exact e.fresh \u25b8 h.ne_empty.symm \n\ntheorem preserves_tag (e : s\u2081 \u21d3| s\u2082) : s\u2081.tag = s\u2082.tag :=\n  e.exec.preserves_tag\n\ntheorem equiv (e : s\u2081 \u21d3| s\u2082) : s\u2081.rtr \u2248 s\u2082.rtr :=\n  e.exec.equiv\n  \ntheorem rcns_Nodup (e : s\u2081 \u21d3| s\u2082) : e.rcns.Nodup := \n  e.exec.rcns_nodup\n\ntheorem progress_def (e : s\u2081 \u21d3| s\u2082) : s\u2082.progress = s\u2081.rtr[.rcn].ids :=\n  Equivalent.obj?_rcn_eq e.equiv \u25b8 e.closed\n\ntheorem mem_rcns_iff (e : s\u2081 \u21d3| s\u2082) : rcn \u2208 e.rcns \u2194 (rcn \u2208 s\u2081.rtr[.rcn] \u2227 rcn \u2209 s\u2081.progress) := by\n  simp [Partial.mem_def, e.progress_def \u25b8 e.exec.mem_rcns_iff (rcn := rcn)]\n\ntheorem rcns_perm (e\u2081 : s \u21d3| s\u2081) (e\u2082 : s \u21d3| s\u2082) : e\u2081.rcns ~ e\u2082.rcns := by\n  simp [List.perm_ext e\u2081.rcns_Nodup e\u2082.rcns_Nodup, e\u2081.mem_rcns_iff, e\u2082.mem_rcns_iff]\n\ntheorem tag_eq (e\u2081 : s \u21d3| s\u2081) (e\u2082 : s \u21d3| s\u2082) : s\u2081.tag = s\u2082.tag :=\n  e\u2081.exec.preserves_tag \u25b8 e\u2082.exec.preserves_tag\n\ntheorem progress_eq (e\u2081 : s \u21d3| s\u2081) (e\u2082 : s \u21d3| s\u2082) : s\u2081.progress = s\u2082.progress := by\n  simp [e\u2081.progress_def, e\u2082.progress_def]\n\ntheorem deterministic (e\u2081 : s \u21d3| s\u2081) (e\u2082 : s \u21d3| s\u2082) : s\u2081 = s\u2082 :=\n  e\u2081.exec.deterministic e\u2082.exec (e\u2081.tag_eq e\u2082) (e\u2081.progress_eq e\u2082)\n\ntheorem step_determined (e : s \u21d3| s\u2081) (a : s \u21d3- s\u2082) : False :=\n  absurd a.closed e.not_Closed\n\ninstance preserves_Nontrivial [h : State.Nontrivial s\u2081] {e : s\u2081 \u21d3| s\u2082} : State.Nontrivial s\u2082 where\n  nontrivial := Equivalent.obj?_rcn_eq e.equiv \u25b8 h.nontrivial\n\ntheorem nonrepeatable (e\u2081 : s\u2081 \u21d3| s\u2082) (e\u2082 : s\u2082 \u21d3| s\u2083) : False :=\n  have := e\u2081.preserves_Nontrivial -- TODO: Make this work via type class inference.\n  absurd e\u2081.closed $ e\u2082.not_Closed\n\ntheorem progress_ssubset (e : s\u2081 \u21d3| s\u2082) : s\u2081.progress \u2282 s\u2082.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\u2081 \u21d3 s\u2082) \u2192 s\u2081.tag \u2264 s\u2082.tag\n  | close e   => le_of_eq e.preserves_tag\n  | advance a => le_of_lt a.tag_lt\n\ntheorem deterministic : (s \u21d3 s\u2081) \u2192 (s \u21d3 s\u2082) \u2192 s\u2081 = s\u2082\n  | close e\u2081, close e\u2082                      => e\u2081.deterministic e\u2082\n  | advance a\u2081, advance a\u2082                  => a\u2081.determinisic a\u2082\n  | close e, advance a | advance a, close e => e.step_determined a |>.elim\n\ntheorem seq_tag_lt : (s\u2081 \u21d3 s\u2082) \u2192 (s\u2082 \u21d3 s\u2083) \u2192 s\u2081.tag < s\u2083.tag\n  | close e\u2081,   close e\u2082   => e\u2081.nonrepeatable e\u2082 |>.elim\n  | advance a\u2081, advance a\u2082 => a\u2081.nonrepeatable a\u2082 |>.elim\n  | close e,    advance a  => e.preserves_tag \u25b8 a.tag_lt\n  | advance a,  close e    => e.preserves_tag \u25b8 a.tag_lt\n\ninstance preserves_Nontrivial [State.Nontrivial s\u2081] : (s\u2081 \u21d3 s\u2082) \u2192 State.Nontrivial s\u2082\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": "/-\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.tactic init.meta.attribute init.meta.constructor_tactic\nimport init.meta.relation_tactics init.meta.occurrences\nimport init.data.option.basic\n\nopen tactic\n\ndef tactic.id_tag.simp : unit := ()\n\ndef simp.default_max_steps := 10000000\n\n/-- Prefix the given `attr_name` with `\"simp_attr\"`. -/\nmeta constant mk_simp_attr_decl_name (attr_name : name) : 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 \u00d7 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 \u2194 r`.\n- A list of the metavariables that must be filled before the proof can be applied.\n- A priority number\n-/\nmeta constant simp_lemmas : Type\n/-- Make a new table of simp lemmas -/\nmeta constant simp_lemmas.mk : simp_lemmas\n/-- Merge the simp_lemma tables. -/\nmeta constant simp_lemmas.join : simp_lemmas \u2192 simp_lemmas \u2192 simp_lemmas\n/-- Remove the given lemmas from the table. Use the names of the lemmas. -/\nmeta constant simp_lemmas.erase : simp_lemmas \u2192 list name \u2192 simp_lemmas\n/-- Remove all simp lemmas from the table. -/\nmeta constant simp_lemmas.erase_simp_lemmas : simp_lemmas \u2192 simp_lemmas\n/-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/\nmeta constant simp_lemmas.mk_default : tactic simp_lemmas\n/-- Add 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 `\u03a0 (h\u2081 : _) ... (h\u2099 : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`).\n- Any of the hypotheses `h\u1d62` 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\u1d62`.\n\n -/\nmeta constant simp_lemmas.add (s : simp_lemmas) (e : expr) (symm : bool := false) : tactic simp_lemmas\n/-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/\nmeta constant simp_lemmas.add_simp (s : simp_lemmas) (id : name) (symm : bool := false) : tactic simp_lemmas\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 \u2227 b` to `c \u2227 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 \u2194 c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ...\nlemma imp_congr_right (h : a \u2192 (b \u2194 c)) : (a \u2192 b) \u2194 (a \u2192 c) := ...\nlemma and_congr (h\u2081 : a \u2194 c) (h\u2082 : b \u2194 d) : (a \u2227 b) \u2194 (c \u2227 d) := ...\n```\n-/\nmeta constant simp_lemmas.add_congr : simp_lemmas \u2192 name \u2192 tactic simp_lemmas\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-/\nmeta def simp_lemmas.append_with_symm (s : simp_lemmas) (hs : list (expr \u00d7 bool)) :\n  tactic simp_lemmas :=\nhs.mfoldl (\u03bb s h, simp_lemmas.add s h.fst h.snd) s\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-/\nmeta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas :=\nhs.mfoldl (\u03bb s h, simp_lemmas.add s h ff) s\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) -/\nmeta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr)\n                                  (prove : tactic unit := failed) (r : name := `eq) (md := reducible)\n                                  : tactic (expr \u00d7 expr)\nmeta constant simp_lemmas.rewrites (s : simp_lemmas) (e : expr)\n                                  (prove : tactic unit := failed) (r : name := `eq) (md := reducible)\n                                  : tactic $ list (expr \u00d7 expr)\n/-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/\nmeta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr\n\nmeta constant is_valid_simp_lemma_cnst : name \u2192 tactic bool\nmeta constant is_valid_simp_lemma : expr \u2192 tactic bool\n\nmeta constant simp_lemmas.pp : simp_lemmas \u2192 tactic format\n\nmeta instance : has_to_tactic_format simp_lemmas :=\n\u27e8simp_lemmas.pp\u27e9\n\nnamespace tactic\n/- Remark: `transform` should not change the target. -/\n/-- Revert a local constant, change its type using `transform`.  -/\nmeta def revert_and_transform (transform : expr \u2192 tactic expr) (h : expr) : tactic unit :=\ndo num_reverted : \u2115 \u2190 revert h,\n   t \u2190 target,\n   match t with\n   | expr.pi n bi d b  :=\n        do h_simp \u2190 transform d,\n           unsafe_change $ expr.pi n bi h_simp b\n   | expr.elet n g e f :=\n        do h_simp \u2190 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   end,\n   intron num_reverted\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. -/\nmeta def get_eqn_lemmas_for (deps : bool) (d : name) : tactic (list name) := do\nenv \u2190 get_env,\npure $ if deps then env.get_ext_eqn_lemmas_for d else env.get_eqn_lemmas_for d\n\nstructure dsimp_config :=\n(md                        := reducible) -- reduction mode: how aggressively constants are replaced with their definitions.\n(max_steps : nat           := simp.default_max_steps) -- The maximum number of steps allowed before failing.\n(canonize_instances : bool := tt) -- See the documentation in `src/library/defeq_canonizer.h`\n(single_pass : bool        := ff) -- Visit each subterm no more than once.\n(fail_if_unchanged         := tt) -- Don't throw if dsimp didn't do anything.\n(eta                       := tt) -- allow eta-equivalence: `(\u03bb x, F $ x) \u219d F`\n(zeta : bool               := tt) -- do zeta-reductions: `let x : a := b in c \u219d c[x/b]`.\n(beta : bool               := tt) -- do beta-reductions: `(\u03bb x, E) $ (y) \u219d E[x/y]`.\n(proj : bool               := tt) -- reduce projections: `\u27e8a,b\u27e9.1 \u219d a`.\n(iota : bool               := tt) -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R \u219d R n $ nat.rec_on n Z R`\n(unfold_reducible          := ff) -- if tt, definitions with `reducible` transparency will be unfolded (delta-reduced)\n(memoize                   := tt) -- Perform caching of dsimps of subterms.\nend tactic\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.-/\nmeta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr\n\nnamespace tactic\n/- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/\nmeta constant dsimplify_core\n  /- The user state type. -/\n  {\u03b1 : Type}\n  /- Initial user data -/\n  (a : \u03b1)\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             : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 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            : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 bool))\n  (e               : expr)\n  (cfg             : dsimp_config := {})\n  : tactic (\u03b1 \u00d7 expr)\n\nmeta def dsimplify\n  (pre             : expr \u2192 tactic (expr \u00d7 bool))\n  (post            : expr \u2192 tactic (expr \u00d7 bool))\n  : expr \u2192 tactic expr :=\n\u03bb e, do (a, new_e) \u2190 dsimplify_core ()\n                       (\u03bb u e, do r \u2190 pre e, return (u, r))\n                       (\u03bb u e, do r \u2190 post e, return (u, r)) e,\n        return new_e\n\nmeta def get_simp_lemmas_or_default : option simp_lemmas \u2192 tactic simp_lemmas\n| none     := simp_lemmas.mk_default\n| (some s) := return s\n\nmeta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit :=\ndo\n  s \u2190 get_simp_lemmas_or_default s,\n  t \u2190 target >>= instantiate_mvars,\n  s.dsimplify u t cfg >>= unsafe_change\n\nmeta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit :=\ndo s \u2190 get_simp_lemmas_or_default s, revert_and_transform (\u03bb e, s.dsimplify u e cfg) h\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\n/-- Tries to unfold `e` if it is a constant or a constant application.\n    Remark: this is not a recursive procedure. -/\nmeta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr\n\nstructure dunfold_config extends dsimp_config :=\n(md := transparency.instances)\n\n/- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for\n   performance reasons. -/\n\nmeta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr\n\nmeta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit :=\ndo t \u2190 target, dunfold cs t cfg >>= unsafe_change\n\nmeta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit :=\nrevert_and_transform (\u03bb e, dunfold cs e cfg) h\n\nstructure delta_config :=\n(max_steps       := simp.default_max_steps)\n(visit_instances := tt)\n\nprivate meta def is_delta_target (e : expr) (cs : list name) : bool :=\ncs.any (\u03bb c,\n  if e.is_app_of c then tt   /- Exact match -/\n  else let f := e.get_app_fn in\n       /- f is an auxiliary constant generated when compiling c -/\n       f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c))\n\n/-- Delta reduce the given constant names -/\nmeta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr :=\nlet unfold (u : unit) (e : expr) : tactic (unit \u00d7 expr \u00d7 bool) := do\n  guard (is_delta_target e cs),\n  (expr.const f_name f_lvls) \u2190 return e.get_app_fn,\n  env   \u2190 get_env,\n  decl  \u2190 env.get f_name,\n  new_f \u2190 decl.instantiate_value_univ_params f_lvls,\n  new_e \u2190 head_beta (expr.mk_app new_f e.get_app_args),\n  return (u, new_e, tt)\nin do (c, new_e) \u2190 dsimplify_core () (\u03bb c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances},\n      return new_e\n\nmeta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit :=\ndo t \u2190 target, delta cs t cfg >>= unsafe_change\n\nmeta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit :=\nrevert_and_transform (\u03bb e, delta cs e cfg) h\n\nstructure unfold_proj_config extends dsimp_config :=\n(md := transparency.instances)\n\n/-- If `e` is a projection application, try to unfold it, otherwise fail. -/\nmeta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr\n\nmeta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr :=\nlet unfold (changed : bool) (e : expr) : tactic (bool \u00d7 expr \u00d7 bool) := do\n  new_e \u2190 unfold_proj e cfg.md,\n  return (tt, new_e, tt)\nin do (tt, new_e) \u2190 dsimplify_core ff (\u03bb c e, failed) unfold e cfg.to_dsimp_config | fail \"no projections to unfold\",\n      return new_e\n\nmeta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit :=\ndo t \u2190 target, unfold_projs t cfg >>= unsafe_change\n\nmeta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit :=\nrevert_and_transform (\u03bb e, unfold_projs e cfg) h\n\nstructure simp_config :=\n(max_steps : nat           := simp.default_max_steps)\n(contextual : bool         := ff)\n(lift_eq : bool            := tt)\n(canonize_instances : bool := tt)\n(canonize_proofs : bool    := ff)\n(use_axioms : bool         := tt)\n(zeta : bool               := tt)\n(beta : bool               := tt)\n(eta  : bool               := tt)\n(proj : bool               := tt) -- reduce projections\n(iota : bool               := tt)\n(iota_eqn : bool           := ff) -- reduce using all equation lemmas generated by equation/pattern-matching compiler\n(constructor_eq : bool     := tt)\n(single_pass : bool        := ff)\n(fail_if_unchanged         := tt)\n(memoize                   := tt)\n(trace_lemmas              := ff)\n\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-/\nmeta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq)\n                       (discharger : tactic unit := failed) : tactic (expr \u00d7 expr \u00d7 name_set)\n\nmeta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic name_set :=\ndo t \u2190 target >>= instantiate_mvars,\n   (new_t, pr, lms) \u2190 simplify s to_unfold t cfg `eq discharger,\n   replace_target new_t pr ``id_tag.simp,\n   return lms\n\nmeta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic (expr \u00d7 name_set) :=\ndo when (expr.is_local_constant h = ff) (fail \"tactic simp_at failed, the given expression is not a hypothesis\"),\n   htype \u2190 infer_type h,\n   (h_new_type, pr, lms) \u2190 simplify s to_unfold htype cfg `eq discharger,\n   new_hyp \u2190 replace_hyp h h_new_type pr ``id_tag.simp,\n   return (new_hyp, lms)\n\n/--\n`ext_simplify_core a c s discharger pre post r e`:\n\n- `a : \u03b1` - 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 : \u03b1 \u2192 tactic \u03b1` - tactic for dischaging hypothesis in conditional rewriting rules. The argument '\u03b1' 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 `\u2194`.\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-/\nmeta constant ext_simplify_core\n  {\u03b1 : Type}\n  (a : \u03b1)\n  (c : simp_config)\n  (s : simp_lemmas)\n  (discharger : \u03b1 \u2192 tactic \u03b1)\n  (pre : \u03b1 \u2192 simp_lemmas \u2192 name \u2192 option expr \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 option expr \u00d7 bool))\n  (post : \u03b1 \u2192 simp_lemmas  \u2192 name \u2192 option expr \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 option expr \u00d7 bool))\n  (r : name) :\n  expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr)\n\nprivate meta def is_equation : expr \u2192 bool\n| (expr.pi n bi d b) := is_equation b\n| e                  := match (expr.is_eq e) with (some a) := tt | none := ff end\n\nmeta def collect_ctx_simps : tactic (list expr) :=\nlocal_context\n\nsection simp_intros\n\nmeta def intro1_aux : bool \u2192 list name \u2192 tactic expr\n| ff _       := intro1\n| tt (n::ns) := intro n\n| _  _       := failed\n\nstructure simp_intros_config extends simp_config :=\n(use_hyps := ff)\n\nmeta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas \u2192 bool \u2192 list name \u2192 tactic simp_lemmas\n| S tt     [] := try (simp_target S to_unfold cfg) >> return S\n| S use_ns ns := do\n  t \u2190 target,\n  if t.is_napp_of `not 1 then\n    intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail\n  else if t.is_arrow then\n    do {\n      d \u2190 return t.binding_domain,\n      (new_d, h_d_eq_new_d, lms) \u2190 simplify S to_unfold d cfg,\n      h_d \u2190 intro1_aux use_ns ns,\n      h_new_d \u2190 mk_eq_mp h_d_eq_new_d h_d,\n      assertv_core h_d.local_pp_name new_d h_new_d,\n      clear h_d,\n      h_new   \u2190 intro1,\n      new_S \u2190 if use_hyps then mcond (is_prop new_d) (S.add h_new ff) (return S)\n              else return S,\n      simp_intros_aux new_S use_ns ns.tail\n    }\n    <|>\n    -- failed to simplify... we just introduce and continue\n    (intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail)\n  else if t.is_pi || t.is_let then\n    intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail\n  else do\n    new_t \u2190 whnf t reducible,\n    if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns\n    else\n      try (simp_target S to_unfold cfg) >>\n      mcond (expr.is_pi <$> target)\n        (simp_intros_aux S use_ns ns)\n        (if use_ns \u2227 \u00acns.empty then failed else return S)\n\nmeta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit :=\nstep $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids\n\nend simp_intros\n\nmeta def mk_eq_simp_ext (simp_ext : expr \u2192 tactic (expr \u00d7 expr)) : tactic unit :=\ndo (lhs, rhs)     \u2190 target >>= match_eq,\n   (new_rhs, heq) \u2190 simp_ext lhs,\n   unify rhs new_rhs,\n   exact heq\n\n/- Simp attribute support -/\n\nmeta def to_simp_lemmas : simp_lemmas \u2192 list name \u2192 tactic simp_lemmas\n| S []      := return S\n| S (n::ns) := do S' \u2190 (has_attribute `congr n >> S.add_congr n) <|> S.add_simp n ff, to_simp_lemmas S' ns\n\nmeta def mk_simp_attr (attr_name : name) (attr_deps : list name := []) : command :=\ndo let t := `(user_attribute simp_lemmas),\n   let v := `({name     := attr_name,\n               descr    := \"simplifier attribute\",\n               cache_cfg := {\n                 mk_cache := \u03bb ns, do {\n                          s \u2190 tactic.to_simp_lemmas simp_lemmas.mk ns,\n                          s \u2190 attr_deps.mfoldl\n                                (\u03bb s attr_name, do\n                                   ns \u2190 attribute.get_instances attr_name,\n                                   to_simp_lemmas s ns)\n                                s,\n                          return s },\n                 dependencies := `reducibility :: attr_deps}} : user_attribute simp_lemmas),\n   let n := mk_simp_attr_decl_name attr_name,\n   add_decl (declaration.defn n [] t v reducibility_hints.abbrev ff),\n   attribute.register n\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 -/\nmeta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas :=\nif attr_name = `default then simp_lemmas.mk_default\nelse get_attribute_cache_dyn (mk_simp_attr_decl_name attr_name)\n\nmeta def join_user_simp_lemmas_core : simp_lemmas \u2192 list name \u2192 tactic simp_lemmas\n| S []             := return S\n| S (attr_name::R) := do S' \u2190 get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R\n\nmeta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas :=\ndo s \u2190 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\nmeta def simplify_top_down {\u03b1} (a : \u03b1) (pre : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr)) (e : expr) (cfg : simp_config := {}) : tactic (\u03b1 \u00d7 expr \u00d7 expr) :=\next_simplify_core a cfg simp_lemmas.mk (\u03bb _, failed)\n  (\u03bb a _ _ _ e, do (new_a, new_e, pr) \u2190 pre a e, guard (\u00ac new_e =\u2090 e), return (new_a, new_e, some pr, tt))\n  (\u03bb _ _ _ _ _, failed)\n  `eq e\n\nmeta def simp_top_down (pre : expr \u2192 tactic (expr \u00d7 expr)) (cfg : simp_config := {}) : tactic unit :=\ndo t                   \u2190 target,\n   (_, new_target, pr) \u2190 simplify_top_down () (\u03bb _ e, do (new_e, pr) \u2190 pre e, return ((), new_e, pr)) t cfg,\n   replace_target new_target pr ``id_tag.simp\n\nmeta def simplify_bottom_up {\u03b1} (a : \u03b1) (post : \u03b1 \u2192 expr \u2192 tactic (\u03b1 \u00d7 expr \u00d7 expr)) (e : expr) (cfg : simp_config := {}) : tactic (\u03b1 \u00d7 expr \u00d7 expr) :=\next_simplify_core a cfg simp_lemmas.mk (\u03bb _, failed)\n  (\u03bb _ _ _ _ _, failed)\n  (\u03bb a _ _ _ e, do (new_a, new_e, pr) \u2190 post a e, guard (\u00ac new_e =\u2090 e), return (new_a, new_e, some pr, tt))\n  `eq e\n\nmeta def simp_bottom_up (post : expr \u2192 tactic (expr \u00d7 expr)) (cfg : simp_config := {}) : tactic unit :=\ndo t                   \u2190 target,\n   (_, new_target, pr) \u2190 simplify_bottom_up () (\u03bb _ e, do (new_e, pr) \u2190 post e, return ((), new_e, pr)) t cfg,\n   replace_target new_target pr ``id_tag.simp\n\nprivate meta def remove_deps (s : name_set) (h : expr) : name_set :=\nif s.empty then s\nelse h.fold s (\u03bb e o s, if e.is_local_constant then s.erase e.local_uniq_name else s)\n\n/- Return the list of hypothesis that are propositions and do not have\n   forward dependencies. -/\nmeta def non_dep_prop_hyps : tactic (list expr) :=\ndo\n  ctx \u2190 local_context,\n  s   \u2190 ctx.mfoldl (\u03bb s h, do\n           h_type \u2190 infer_type h,\n           let s := remove_deps s h_type,\n           h_val  \u2190 head_zeta h,\n           let s := if h_val =\u2090 h then s else remove_deps s h_val,\n           mcond (is_prop h_type)\n             (return $ s.insert h.local_uniq_name)\n             (return s)) mk_name_set,\n  t   \u2190 target,\n  let s := remove_deps s t,\n  return $ ctx.filter (\u03bb h, s.contains h.local_uniq_name)\n\nsection simp_all\n\nmeta structure simp_all_entry :=\n(h        : expr) -- hypothesis\n(new_type : expr) -- new type\n(pr       : option expr) -- proof that type of h is equal to new_type\n(s        : simp_lemmas) -- simplification lemmas for simplifying new_type\n\nprivate meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) :=\nes.mmap $ \u03bb e, do new_s \u2190 e.s.add h ff, return {s := new_s, ..e}\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 meta def init_aux : list expr \u2192 simp_lemmas \u2192 list simp_all_entry \u2192 tactic (simp_lemmas \u00d7 list simp_all_entry)\n| []      s r := return (s, r)\n| (h::hs) s r := do\n  new_r  \u2190 update_simp_lemmas r h,\n  new_s  \u2190 s.add h ff,\n  h_type \u2190 infer_type h,\n  init_aux hs new_s (\u27e8h, h_type, none, s\u27e9::new_r)\n\nprivate meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas \u00d7 list simp_all_entry) :=\ninit_aux hs s []\n\nprivate meta def add_new_hyps (es : list simp_all_entry) : tactic unit :=\nes.mmap' $ \u03bb e,\n   match e.pr with\n   | none    := return ()\n   | some pr :=\n      assert e.h.local_pp_name e.new_type >>\n      mk_eq_mp pr e.h >>= exact\n   end\n\nprivate meta def clear_old_hyps (es : list simp_all_entry) : tactic unit :=\nes.mmap' $ \u03bb e, when (e.pr \u2260 none) (try (clear e.h))\n\nprivate meta def join_pr : option expr \u2192 expr \u2192 tactic expr\n| none       pr\u2082 := return pr\u2082\n| (some pr\u2081) pr\u2082 := mk_eq_trans pr\u2081 pr\u2082\n\nprivate meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name)\n                      : list simp_all_entry \u2192 list simp_all_entry \u2192 simp_lemmas \u2192 bool \u2192 tactic name_set\n| []      r  s m :=\n  if m then loop r [] s ff\n  else do\n    add_new_hyps r,\n    (lms, target_changed) \u2190 (simp_target s to_unfold cfg discharger >>= \u03bb ns, return (ns, tt)) <|>\n                            (return (mk_name_set, ff)),\n    guard (cfg.fail_if_unchanged = ff \u2228 target_changed \u2228 r.any (\u03bb e, e.pr \u2260 none)) <|> fail \"simp_all tactic failed to simplify\",\n    clear_old_hyps r,\n    return lms\n| (e::es) r  s m := do\n   let \u27e8h, h_type, h_pr, s'\u27e9 := e,\n   (new_h_type, new_pr, lms) \u2190 simplify s' to_unfold h_type {fail_if_unchanged := ff, ..cfg} `eq discharger,\n   if h_type =\u2090 new_h_type then do\n     new_lms \u2190 loop es (e::r) s m,\n     return (new_lms.fold lms (\u03bb n ns, name_set.insert ns n))\n   else do\n     new_pr      \u2190 join_pr h_pr new_pr,\n     new_fact_pr \u2190 mk_eq_mp new_pr h,\n     if new_h_type = `(false) then do\n       tgt         \u2190 target,\n       to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact,\n       return (mk_name_set)\n     else do\n       h0_type     \u2190 infer_type h,\n       let new_fact_pr := mk_tagged_proof new_h_type new_fact_pr ``id_tag.simp,\n       new_es      \u2190 update_simp_lemmas es new_fact_pr,\n       new_r       \u2190 update_simp_lemmas r new_fact_pr,\n       let new_r := {new_type := new_h_type, pr := new_pr, ..e} :: new_r,\n       new_s       \u2190 s.add new_fact_pr ff,\n       new_lms \u2190 loop new_es new_r new_s tt,\n       return (new_lms.fold lms (\u03bb n ns, name_set.insert ns n))\n\nmeta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic name_set :=\ndo hs      \u2190 non_dep_prop_hyps,\n   (s, es) \u2190 init s hs,\n   loop cfg discharger to_unfold es [] s ff\n\nend simp_all\n\n/- debugging support for algebraic normalizer -/\n\nmeta constant trace_algebra_info : expr \u2192 tactic unit\n\nend tactic\n\nexport tactic (mk_simp_attr)\n\nrun_cmd mk_simp_attr `norm [`simp]\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/simp_tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242354120407358, "lm_q2_score": 0.04023794622027691, "lm_q1q2_score": 0.013046567072404452}}
{"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.meta.smt.smt_tactic init.meta.fun_info init.meta.rb_map\n\ndef tactic.id_tag.rsimp : unit := ()\n\nopen tactic\n\nprivate meta def add_lemma (m : transparency) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas :=\n(do h \u2190 hinst_lemma.mk_from_decl_core m h tt, return $ hs.add h) <|> return hs\n\nprivate meta def to_hinst_lemmas (m : transparency) (ex : name_set) : list name \u2192 hinst_lemmas \u2192 tactic hinst_lemmas\n| []      hs := return hs\n| (n::ns) hs :=\n  if ex.contains n then to_hinst_lemmas ns hs else\n  let add n := add_lemma m n hs >>= to_hinst_lemmas ns\n  in do eqns   \u2190 tactic.get_eqn_lemmas_for tt n,\n  match eqns with\n  | []  := add n\n  | _   := mcond (is_prop_decl n) (add n) (to_hinst_lemmas eqns hs >>= to_hinst_lemmas ns)\n  end\n\n/-- Create a rsimp attribute named `attr_name`, the attribute declaration is named `attr_decl_name`.\n    The cached hinst_lemmas structure is built using the lemmas marked with simp attribute `simp_attr_name`,\n    but *not* marked with `ex_attr_name`.\n\n    We say `ex_attr_name` is the \"exception set\". It is useful for excluding lemmas in `simp_attr_name`\n    which are not good or redundant for ematching. -/\nmeta def mk_hinst_lemma_attr_from_simp_attr (attr_decl_name attr_name : name) (simp_attr_name : name) (ex_attr_name : name) : command :=\ndo let t := `(user_attribute hinst_lemmas),\n   let v := `({name     := attr_name,\n               descr    := sformat!\"hinst_lemma attribute derived from '{simp_attr_name}'\",\n               cache_cfg := {\n                 mk_cache := \u03bb ns,\n                 let aux := simp_attr_name in\n                 let ex_attr := ex_attr_name in\n                 do {\n                   hs   \u2190 to_hinst_lemmas reducible mk_name_set ns hinst_lemmas.mk,\n                   ss   \u2190 attribute.get_instances aux,\n                   ex   \u2190 get_name_set_for_attr ex_attr,\n                   to_hinst_lemmas reducible ex ss hs\n                 },\n                 dependencies := [`reducibility, simp_attr_name]}} : user_attribute hinst_lemmas),\n   add_decl (declaration.defn attr_decl_name [] t v reducibility_hints.abbrev ff),\n   attribute.register attr_decl_name\n\nrun_cmd mk_name_set_attr `no_rsimp\nrun_cmd mk_hinst_lemma_attr_from_simp_attr `rsimp_attr `rsimp `simp `no_rsimp\n\n/- The following lemmas are not needed by rsimp, and they actually hurt performance since they generate a lot of\n   instances. -/\nattribute [no_rsimp]\n  id.def ne.def not_true not_false_iff ne_self_iff_false eq_self_iff_true heq_self_iff_true iff_not_self not_iff_self\n  true_iff_false false_iff_true and.comm and.assoc and.left_comm and_true true_and and_false false_and not_and_self and_not_self\n  and_self or.comm or.assoc or.left_comm or_true true_or or_false false_or or_self iff_true true_iff iff_false false_iff\n  iff_self implies_true_iff false_implies_iff if_t_t if_true if_false\n\nnamespace rsimp\n\nmeta def is_value_like : expr \u2192 bool\n| e :=\n  if \u00ac e.is_app then ff\n  else let fn    := e.get_app_fn in\n   if \u00ac fn.is_constant then ff\n   else let nargs := e.get_app_num_args,\n            fname := fn.const_name in\n     if      fname = ``has_zero.zero \u2227 nargs = 2 then tt\n     else if fname = ``has_one.one \u2227 nargs = 2 then tt\n     else if fname = ``bit0 \u2227 nargs = 3 then is_value_like e.app_arg\n     else if fname = ``bit1 \u2227 nargs = 4 then is_value_like e.app_arg\n     else if fname = ``char.of_nat \u2227 nargs = 1 then is_value_like e.app_arg\n     else ff\n\n/-- Return the size of term by considering only explicit arguments. -/\nmeta def explicit_size : expr \u2192 tactic nat\n| e :=\n  if \u00ac e.is_app then return 1\n  else if is_value_like e then return 1\n  else fold_explicit_args e 1\n    (\u03bb n arg, do r \u2190 explicit_size arg, return $ r + n)\n\n/-- Choose smallest element (with respect to explicit_size) in `e`s equivalence class. -/\nmeta def choose (ccs : cc_state) (e : expr) : tactic expr :=\ndo sz \u2190 explicit_size e,\n   p  \u2190 ccs.mfold_eqc e (e, sz) $ \u03bb p e',\n     if p.2 = 1 then return p\n     else do {\n       sz' \u2190 explicit_size e',\n       if sz' < p.2 then return (e', sz')\n       else return p\n     },\n   return p.1\n\nmeta def repr_map := expr_map expr\nmeta def mk_repr_map := expr_map.mk expr\n\nmeta def to_repr_map (ccs : cc_state) : tactic repr_map :=\nccs.roots.mfoldl (\u03bb S e, do r \u2190 choose ccs e, return $ S.insert e r) mk_repr_map\n\nmeta def rsimplify (ccs : cc_state) (e : expr) (m : option repr_map := none) : tactic (expr \u00d7 expr) :=\ndo m \u2190 match m with\n       | none   := to_repr_map ccs\n       | some m := return m\n       end,\n   r \u2190 simplify_top_down () (\u03bb _ t,\n         do root  \u2190 return $ ccs.root t,\n            new_t \u2190 m.find root,\n            guard (\u00ac new_t =\u2090 t),\n            prf   \u2190 ccs.eqv_proof t new_t,\n            return ((), new_t, prf))\n         e,\n   return r.2\n\nstructure config :=\n(attr_name   := `rsimp_attr)\n(max_rounds  := 8)\n\nopen smt_tactic\n\nprivate def tagged_proof.rsimp : unit := ()\n\nmeta def collect_implied_eqs (cfg : config := {}) (extra := hinst_lemmas.mk) : tactic cc_state :=\ndo focus1 $ using_smt_with {em_attr := cfg.attr_name} $\n   do\n     add_lemmas_from_facts,\n     add_lemmas extra,\n     iterate_at_most cfg.max_rounds (ematch >> try smt_tactic.close),\n     (done >> return cc_state.mk)\n     <|>\n     to_cc_state\n\nmeta def rsimplify_goal (ccs : cc_state) (m : option repr_map := none) : tactic unit :=\ndo t           \u2190 target,\n   (new_t, pr) \u2190 rsimplify ccs t m,\n   try (replace_target new_t pr ``id_tag.rsimp)\n\nmeta def rsimplify_at (ccs : cc_state) (h : expr) (m : option repr_map := none) : tactic unit :=\ndo when (expr.is_local_constant h = ff) (tactic.fail \"tactic rsimplify_at failed, the given expression is not a hypothesis\"),\n   htype            \u2190 infer_type h,\n   (new_htype, heq) \u2190 rsimplify ccs htype m,\n   try $ do assert (expr.local_pp_name h) new_htype,\n            mk_eq_mp heq h >>= exact,\n            try $ clear h\nend rsimp\n\nopen rsimp\n\nnamespace tactic\n\nmeta def rsimp (cfg : config := {}) (extra := hinst_lemmas.mk) : tactic unit :=\ndo ccs \u2190 collect_implied_eqs cfg extra,\n   try $ rsimplify_goal ccs\n\nmeta def rsimp_at (h : expr) (cfg : config := {}) (extra := hinst_lemmas.mk) : tactic unit :=\ndo ccs \u2190 collect_implied_eqs cfg extra,\n   try $ rsimplify_at ccs h\n\nnamespace interactive\n\n/- TODO(Leo): allow user to provide extra lemmas manually -/\nmeta def rsimp : tactic unit :=\ntactic.rsimp\n\nend interactive\nend tactic\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/rsimp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081161995, "lm_q2_score": 0.038466189262612104, "lm_q1q2_score": 0.013004538129836858}}
{"text": "import ..utils.util\nimport all\n\nsection main\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  names_file \u2190 args.nth_except 0 \"names_file\",\n  dest \u2190 args.nth_except 1 \"dest\",\n  nm_strs \u2190 (io.mk_file_handle names_file io.mode.read >>= \u03bb f,\n    (string.split (\u03bb c, c = '\\n') <$> buffer.to_string <$> io.fs.read_to_end f)),\n\n  (nms : list (name \u00d7 list name)) \u2190 (nm_strs.filter $ \u03bb nm_str, string.length nm_str > 0).mmap $ \u03bb nm_str, do {\n    ((io.run_tactic' \u2218 parse_decl_nm_and_open_ns) $ nm_str)\n  },\n\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n \n  io.run_tactic' $ do {\n    env \u2190 tactic.get_env,\n    for_ nms $ \u03bb \u27e8nm, open_ns\u27e9, tactic.try $ do {\n      decl \u2190 env.get nm,\n      if decl.is_theorem then do {\n        tactic.trace format! \"[filter_defs] KEEPING {nm.to_string}\",\n        tactic.unsafe_run_io $\n          io.fs.put_str_ln_flush\n            dest_handle\n              (nm.to_string ++ \" \" ++ (\" \".intercalate $ name.to_string <$> open_ns))\n      } else do {\n        tactic.trace format! \"[filter_defs] DISCARDING {nm.to_string}\",\n        pure ()\n      }\n    }\n  }\n}\n\nend main\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/tools/filter_defs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3812195662561499, "lm_q2_score": 0.03410042411718461, "lm_q1q2_score": 0.012999748891103871}}
{"text": "/-\nCopyright (c) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\nPorted by: E.W.Ayers\n-/\nimport Lean\nimport Lean.Data\n\nopen Lean\nopen Lean.Elab\nopen Lean.Elab.Command\n\n/--\n__DEPRECATED__: `restate_axiom` was necessary in Lean 3 but is no longer needed for Lean 4.\nIt is still present for backwards compatibility but will probably be removed in the future.\n\n# Original Docstring\n\n`restate_axiom` makes a new copy of a structure field, first definitionally simplifying the type.\nThis is useful to remove `auto_param` or `opt_param` from the statement.\n\nAs an example, we have:\n```lean\nstructure A :=\n(x : \u2115)\n(a' : x = 1 . skip)\n\nexample (z : A) : z.x = 1 := by rw A.a' -- rewrite tactic failed, lemma is not an equality nor a iff\n\nrestate_axiom A.a'\nexample (z : A) : z.x = 1 := by rw A.a\n```\n\nBy default, `restate_axiom` names the new lemma by removing a trailing `'`, or otherwise appending\n`_lemma` if there is no trailing `'`. You can also give `restate_axiom` a second argument to\nspecify the new name, as in\n```lean\nrestate_axiom A.a f\nexample (z : A) : z.x = 1 := by rw A.f\n```\n-/\nelab \"restate_axiom \" oldName:ident newName:optional(ident) : command => do\n  let oldName \u2190 resolveGlobalConstNoOverloadWithInfo oldName\n  let newName : Name :=\n    match newName with\n      | none =>\n        match oldName with\n        | Name.str n s =>\n          if s.back = '\\'' then\n            Name.mkStr n $ s.extract 0 (s.endPos - \u27e81\u27e9)\n          else\n            Name.mkStr n $ s ++ \"_lemma\"\n        | x => x\n      | some n => Name.getPrefix oldName ++ n.getId\n  liftCoreM do\n    match \u2190 getConstInfo oldName with\n    | ConstantInfo.defnInfo info =>\n      addAndCompile <| .defnDecl { info with name := newName }\n    | ConstantInfo.thmInfo info =>\n      addAndCompile <| .thmDecl { info with name := newName }\n    | _ => throwError \"Constant {oldName} is not a definition or theorem.\"\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/RestateAxiom.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22270013882530887, "lm_q2_score": 0.05834584634253715, "lm_q1q2_score": 0.012993628080363162}}
{"text": "import Lean\nimport Lean.Meta\n-- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/benchmarking.20commands/near/249677507\n\n\nsection\nopen Lean Elab Command\n\nsyntax (name := timeCmd)  \"#time \" command : command\n\n@[commandElab timeCmd] def elabTimeCmd : CommandElab\n  | `(#time%$tk $stx:command) => do\n    let start \u2190 IO.monoMsNow\n    elabCommand stx\n    logInfoAt tk m!\"time: {(\u2190 IO.monoMsNow) - start}ms\"\n  | _ => throwUnsupportedSyntax\n\nend\n/-\nset_option maxRecDepth 200000 in\n#time example : (List.range 5100).length = 5100 := rfl\n-/\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/Benchmark.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.05834583569951912, "lm_q1q2_score": 0.012993625710161568}}
{"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 data.bool.basic\nimport meta.rb_map\nimport tactic.core\n\n/-!\n# list_unused_decls\n\n`#list_unused_decls` is a command used for theory development.\nWhen writing a new theory one often tries\nmultiple variations of the same definitions: `foo`, `foo'`, `foo\u2082`,\n`foo\u2083`, etc. Once the main definition or theorem has been written,\nit's time to clean up and the file can contain a lot of dead code.\nMark the main declarations with `@[main_declaration]` and\n`#list_unused_decls` will show the declarations in the file\nthat are not needed to define the main declarations.\n\nSome of the so-called \"unused\" declarations may turn out to be useful\nafter all. The oversight can be corrected by marking those as\n`@[main_declaration]`. `#list_unused_decls` will revise the list of\nunused declarations. By default, the list of unused declarations will\nnot include any dependency of the main declarations.\n\nThe `@[main_declaration]` attribute should be removed before submitting\ncode to mathlib as it is merely a tool for cleaning up a module.\n-/\n\nnamespace tactic\n\n/-- Attribute `main_declaration` is used to mark declarations that are featured\nin the current file.  Then, the `#list_unused_decls` command can be used to\nlist the declaration present in the file that are not used by the main\ndeclarations of the file. -/\n@[user_attribute]\nmeta def main_declaration_attr : user_attribute :=\n{ name := `main_declaration,\n  descr := \"tag essential declarations to help identify unused definitions\" }\n\n/-- `update_unsed_decls_list n m` removes from the map of unneeded declarations those\nreferenced by declaration named `n` which is considerred to be a\nmain declaration -/\nprivate meta def update_unsed_decls_list :\n  name \u2192 name_map declaration \u2192 tactic (name_map declaration)\n| n m :=\n  do d \u2190 get_decl n,\n     if m.contains n then do\n       let m := m.erase n,\n       let ns := d.value.list_constant.union d.type.list_constant,\n       ns.mfold m update_unsed_decls_list\n     else pure m\n\n/-- In the current file, list all the declaration that are not marked as `@[main_declaration]` and\nthat are not referenced by such declarations -/\nmeta def all_unused (fs : list (option string)) : tactic (name_map declaration) :=\ndo ds \u2190 get_decls_from fs,\n   ls \u2190 ds.keys.mfilter (succeeds \u2218 user_attribute.get_param_untyped main_declaration_attr),\n   ds \u2190 ls.mfoldl (flip update_unsed_decls_list) ds,\n   ds.mfilter $ \u03bb n d, do\n     e \u2190 get_env,\n     return $ !d.is_auto_or_internal e\n\n/-- expecting a string literal (e.g. `\"src/tactic/find_unused.lean\"`)\n-/\nmeta def parse_file_name (fn : pexpr) : tactic (option string) :=\nsome <$> (to_expr fn >>= eval_expr string) <|> fail \"expecting: \\\"src/dir/file-name\\\"\"\n\nsetup_tactic_parser\n\n/-- The command `#list_unused_decls` lists the declarations that that\nare not used the main features of the present file. The main features\nof a file are taken as the declaration tagged with\n`@[main_declaration]`.\n\nA list of files can be given to `#list_unused_decls` as follows:\n\n```lean\n#list_unused_decls [\"src/tactic/core.lean\",\"src/tactic/interactive.lean\"]\n```\n\nThey are given in a list that contains file names written as Lean\nstrings. With a list of files, the declarations from all those files\nin addition to the declarations above `#list_unused_decls` in the\ncurrent file will be considered and their interdependencies will be\nanalyzed to see which declarations are unused by declarations marked\nas `@[main_declaration]`. The files listed must be imported by the\ncurrent file. The path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present).\n\nNeither `#list_unused_decls` nor `@[main_declaration]` should appear\nin a finished mathlib development. -/\n@[user_command]\nmeta def unused_decls_cmd (_ : parse $ tk \"#list_unused_decls\") : lean.parser unit :=\ndo fs \u2190 pexpr_list,\n   show tactic unit, from\n   do fs \u2190 fs.mmap parse_file_name,\n      ds \u2190 all_unused $ none :: fs,\n      ds.to_list.mmap' $ \u03bb \u27e8n,_\u27e9, trace!\"#print {n}\"\n\nadd_tactic_doc\n{ name                     := \"#list_unused_decls\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.unused_decls_cmd],\n  tags                     := [\"debugging\"] }\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/find_unused.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14414885670945202, "lm_q2_score": 0.09009299762657567, "lm_q1q2_score": 0.012986802605398258}}
{"text": "theorem ex1 : True := sorry\n", "meta": {"author": "gebner", "repo": "autograder", "sha": "9d23bfc346c672e93d0b4ee11453925ed15cd091", "save_path": "github-repos/lean/gebner-autograder", "path": "github-repos/lean/gebner-autograder/autograder-9d23bfc346c672e93d0b4ee11453925ed15cd091/AutograderTests/Fail/Unsolved.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.0481367670200415, "lm_q1q2_score": 0.012945971106640296}}
{"text": "/-\nCopyright 2022 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    https://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\nAuthors: Moritz Firsching\n-/\nimport tactic\n/-!\n# On a lemma of Littlewook and Offord\n\n## TODO\n  - statement\n    - proof\n      - Claim\n-/\n", "meta": {"author": "mo271", "repo": "formal_book", "sha": "34cbc0b9e9d361b74adbe0fd06192a72e684b992", "save_path": "github-repos/lean/mo271-formal_book", "path": "github-repos/lean/mo271-formal_book/formal_book-34cbc0b9e9d361b74adbe0fd06192a72e684b992/src/chapters/25_On_a_lemma_of_Littlewook_and_Offord.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25683200276421697, "lm_q2_score": 0.05033063010464514, "lm_q1q2_score": 0.012926516530161003}}
{"text": "\nimport data.fix.inductive_decl\nimport mvqpf\nimport data.fix.equations\nimport category.bitraversable.instances\n\nuniverses u\n\nlemma foo {n} {p : mvpfunctor n} {v} (C : p.apply v \u2192 Sort*) {a : p.A} {f g : p.B a \u27f9 v} (h : f = g) (x : C \u27e8a,f\u27e9) : C \u27e8a,g\u27e9 :=\nby cases h; apply x\n\nnamespace tactic\n\nopen native\n\nmeta def map_arg' (m : rb_map expr expr) : expr \u2192 expr \u2192 tactic expr\n| e (expr.pi n bi d b) :=\ndo v \u2190 mk_local' n bi d,\n   e' \u2190 head_beta (e v) >>= whnf,\n   map_arg' e' (b.instantiate_var v) >>= lambdas [v]\n| e v@(expr.local_const _ _ _ _) :=\ndo some f \u2190 pure $ m.find v | pure e,\n   pure $ f e\n| e _ := pure e\n\nmeta def map_arg (m : rb_map expr expr) (e : expr) : tactic expr :=\ninfer_type e >>= whnf >>= map_arg' m e\n\nmeta def find_dead_occ (n : name) (ps : list expr) : rb_map expr \u2115 \u2192 expr \u2192 rb_map expr \u2115\n| m `(%%a \u2192 %%b) := find_dead_occ (a.list_local_consts.foldl rb_map.erase m) b\n| m (expr.local_const _ _ _ _) := m\n| m e :=\nif e.get_app_fn.const_name = n\n  then m\n  else e.list_local_consts.foldl rb_map.erase m\n\nmeta def live_vars (induct : inductive_type) : tactic $ rb_map expr \u2115 \u00d7 rb_map expr \u2115 :=\ndo let n := induct.name,\n   let params : list expr := induct.params,\n   let e := (@expr.const tt n induct.u_params).mk_app params,\n   let vs := rb_map.of_list $ params.enum.map prod.swap,\n   let ls := induct.ctors,\n   ls \u2190 ls.mmap $ \u03bb c,\n     do { ts \u2190 c.args.mmap infer_type,\n          pure $ ts.foldl (find_dead_occ n params) vs },\n   let m := ls.foldl rb_map.intersect vs,\n   m.mfilter $ \u03bb e _, expr.is_sort <$> infer_type e,\n   let m' := vs.difference m,\n   pure (m,m')\n\nmeta instance : has_repr expr := \u27e8 to_string \u27e9\nmeta instance task.has_repr {\u03b1} [has_repr \u03b1] : has_repr (task \u03b1) := \u27e8 repr \u2218 task.get \u27e9\n\nopen level\nmeta def level.repr : level \u2192 \u2115 \u2192 string\n| zero n := repr n\n| (succ a) n := level.repr a n.succ\n| (max x y) n := sformat!\"(max {level.repr x n} {level.repr y n})\"\n| (imax x y) n := sformat!\"(imax {level.repr x n} {level.repr y n})\"\n| (param a) n := if n = 0 then repr a\n                          else sformat!\"({n} + {repr a})\"\n| (mvar a) n := if n = 0 then repr a\n                         else sformat!\"({n} + {repr a})\"\n\nmeta instance level.has_repr : has_repr level := \u27e8 \u03bb l, level.repr l 0 \u27e9\n\nattribute [derive has_repr] reducibility_hints declaration type_cnstr inductive_type\n\n@[derive has_repr]\nmeta structure internal_mvfunctor :=\n(decl : declaration)\n(induct : inductive_type)\n(def_name eqn_name map_name abs_name repr_name pfunctor_name : name)\n(univ_params : list level)\n(vec_lvl : level)\n(live_params : list $ expr \u00d7 \u2115)\n(dead_params : list $ expr \u00d7 \u2115)\n(params : list expr)\n(type : expr)\n\nmeta def mk_inductive' : inductive_type \u2192 lean.parser unit\n| decl :=\ndo let n\u2080 := name.anonymous,\n   t \u2190 pis decl.idx decl.type,\n   cn \u2190 mk_local_def (decl.name.replace_prefix decl.pre n\u2080) t,\n   brs \u2190 decl.ctors.mmap $ \u03bb c,\n       do { let rt := cn.mk_app c.result,\n            t \u2190 pis c.args rt,\n            pure format!\"| {(c.name.update_prefix n\u2080).to_string} : {expr.parsable_printer t}\" },\n   args \u2190 decl.params.mmap $ \u03bb p,\n     do { t \u2190 infer_type p,\n          pure $ expr.fmt_binder p.local_pp_name p.binding_info (expr.parsable_printer t) },\n   let xs := format!\"\ninductive {cn} {format.intercalate \\\" \\\" args} : {expr.parsable_printer t}\n{format.intercalate \\\"\\n\\\" brs}\",\n   lean.parser.with_input lean.parser.command_like xs.to_string,\n   pure ()\n\nmeta def internalize_mvfunctor (ind : inductive_type) : tactic internal_mvfunctor :=\ndo let decl := declaration.cnst ind.name ind.u_names ind.type tt,\n   let n := decl.to_name,\n   let df_name := n <.> \"internal\",\n   let lm_name := n <.> \"internal_eq\",\n   -- decl \u2190 get_decl n,\n   (params,t) \u2190 mk_local_pis decl.type,\n   let params := ind.params ++ params,\n   (m,m') \u2190 live_vars ind,\n   let m := rb_map.sort prod.snd m.to_list,\n   let m' := rb_map.sort prod.snd m'.to_list,\n   u \u2190 mk_meta_univ,\n   let vars := string.intercalate \",\" (m.map to_string),\n   (params.mmap' (\u03bb e, infer_type e >>= unify (expr.sort u))\n     <|> fail format!\"live type parameters ({params}) are not in the same universe\" : tactic _),\n   (level.succ u) \u2190 get_univ_assignment u <|> pure level.zero.succ,\n   ts \u2190 (params.mmap infer_type : tactic _),\n   pure { decl := decl,\n          induct := ind,\n          def_name := df_name,\n          eqn_name := lm_name,\n          map_name := (df_name <.> \"map\"),\n          abs_name := (df_name <.> \"abs\"),\n          repr_name := (df_name <.> \"repr\"),\n          pfunctor_name := n <.> \"pfunctor\",\n          vec_lvl := u,\n          univ_params := decl.univ_params.map level.param,\n          live_params := m,\n          dead_params := m',\n          params := params,\n          type := t }\n\nnotation `\u2983 ` r:( foldr `, ` (h t, typevec.append1 t h) fin'.elim0 ) ` \u2984` := r\nnotation `\u2983`  `\u2984` := fin'.elim0\n\nlocal prefix `\u266f`:0 := cast (by try { simp only with typevec }; congr' 1; try { simp only with typevec })\n\nmeta def mk_internal_functor_def (func : internal_mvfunctor) : tactic unit :=\ndo let trusted := func.decl.is_trusted,\n   let arity := func.live_params.length,\n   let vec := @expr.const tt ``_root_.typevec [func.vec_lvl] `(arity),\n   v_arg \u2190 mk_local_def `v_arg vec,\n   t \u2190 pis (func.dead_params.map prod.fst ++ [v_arg]) func.type,\n   (_,df) \u2190 @solve_aux unit t $ do\n     { m' \u2190 func.dead_params.mmap $ \u03bb v, prod.mk v.2 <$> intro v.1.local_pp_name,\n       vs \u2190 func.live_params.reverse.mmap $ \u03bb x, do\n         { refine ``(typevec.typevec_cases_cons _ _),\n           x' \u2190 intro x.1.local_pp_name,\n           pure (x.2,x') },\n       refine ``(typevec.typevec_cases_nil _),\n       let args := (rb_map.sort prod.fst (m' ++ vs)).map prod.snd,\n       let e := (@expr.const tt func.decl.to_name (func.decl.univ_params.map level.param)).mk_app args,\n       exact e },\n   df \u2190 instantiate_mvars df,\n   add_decl $ declaration.defn func.def_name func.decl.univ_params t df (reducibility_hints.regular 1 tt) trusted\n\nmeta def mk_live_vec (u : level) (vs : list expr) : tactic expr :=\ndo nil \u2190 mk_mapp ``fin'.elim0 [@expr.sort tt $ level.succ u],\n   vs.reverse.mfoldr (\u03bb e s, mk_mapp ``typevec.append1 [none,s,e]) nil\n\nmeta def mk_map_vec (u : level) (vs : list expr) : tactic expr :=\ndo let nil := @expr.const tt ``typevec.nil_fun [u,u],\n   vs.reverse.mfoldr (\u03bb e s,\n     mk_mapp ``typevec.append_fun [none,none,none,none,none,s,e]) nil\n\nmeta def mk_internal_functor_app (func : internal_mvfunctor) : tactic expr :=\ndo let decl := func.decl,\n   vec \u2190 mk_live_vec func.vec_lvl $ func.live_params.map prod.fst,\n   pure $ (@expr.const tt func.def_name decl.univ_levels).mk_app (func.dead_params.map prod.fst ++ [vec])\n\nmeta def mk_internal_functor_eqn (func : internal_mvfunctor) : tactic unit :=\ndo let decl := func.decl,\n   lhs \u2190 mk_internal_functor_app func,\n   let rhs := (@expr.const tt decl.to_name decl.univ_levels).mk_app func.params,\n   p \u2190 mk_app `eq [lhs,rhs] >>= pis func.params,\n   (_,pr) \u2190 solve_aux p $ intros >> reflexivity,\n   pr \u2190 instantiate_mvars pr,\n   add_decl $ declaration.thm func.eqn_name decl.univ_params p (pure pr)\n\n-- meta def mk_internal_functor (n : name) : tactic internal_mvfunctor :=\n-- do decl \u2190 get_decl n,\n--    func \u2190 internalize_mvfunctor decl,\n--    mk_internal_functor_def func,\n--    mk_internal_functor_eqn func,\n--    pure func\n\nmeta def mk_internal_functor' (d : interactive.inductive_decl) : lean.parser internal_mvfunctor :=\ndo d \u2190 inductive_type.of_decl d,\n   mk_inductive' d,\n   func \u2190 internalize_mvfunctor d,\n   mk_internal_functor_def func,\n   mk_internal_functor_eqn func,\n   pure func\n\nopen typevec\n\nmeta def destruct_typevec\u2083 (func : internal_mvfunctor) (v : name) : tactic (list $ expr \u00d7 expr \u00d7 expr \u00d7 \u2115) :=\ndo vs \u2190 func.live_params.reverse.mmap $ \u03bb x : expr \u00d7 \u2115, do\n     { refine ``(typevec_cases_cons\u2083 _ _),\n       \u03b1 \u2190 get_unused_name `\u03b1 >>= intro,\n       \u03b2 \u2190 get_unused_name `\u03b2 >>= intro,\n       f \u2190 get_unused_name `f >>= intro,\n       pure (\u03b1,\u03b2,f,x.2) },\n   refine ``(typevec_cases_nil\u2083 _),\n   pure vs\n\nmeta def destruct_typevec' (func : internal_mvfunctor) (v : name) : tactic (list $ expr \u00d7 \u2115) :=\ndo vs \u2190 func.live_params.reverse.mmap $ \u03bb x : expr \u00d7 \u2115, do\n     { refine ``(typevec_cases_cons _ _),\n       \u03b1 \u2190 get_unused_name `\u03b1 >>= intro,\n       pure (\u03b1,x.2) },\n   refine ``(typevec_cases_nil _),\n   pure vs\n\ndef mk_arg_list {\u03b1} (xs : list (\u03b1 \u00d7 \u2115)) : list \u03b1 :=\n(rb_map.sort prod.snd xs).map prod.fst\n\nmeta def internal_expr (func : internal_mvfunctor) :=\n(@expr.const tt func.def_name func.decl.univ_levels).mk_app (func.dead_params.map prod.fst)\n\nmeta def functor_expr (func : internal_mvfunctor) :=\n(@expr.const tt func.pfunctor_name func.decl.univ_levels).mk_app (func.dead_params.map prod.fst)\n\nmeta def mk_mvfunctor_map (func : internal_mvfunctor) : tactic expr :=\ndo let decl := func.decl,\n   let intl := internal_expr func,\n   let arity := func.live_params.length,\n   \u03b1 \u2190 mk_local_def `\u03b1 $ @expr.const tt ``typevec [func.vec_lvl] `(arity),\n   \u03b2 \u2190 mk_local_def `\u03b2 $ @expr.const tt ``typevec [func.vec_lvl] `(arity),\n   f \u2190 mk_app ``typevec.arrow [\u03b1,\u03b2] >>= mk_local_def `f,\n   let r := expr.imp (intl \u03b1) (intl \u03b2),\n\n   map_t \u2190 pis (func.dead_params.map prod.fst ++ [\u03b1,\u03b2,f]) r,\n   (_,df) \u2190 @solve_aux unit map_t $ do\n     { vs \u2190 intron' func.dead_params.length,\n       let vs := vs.zip $ func.dead_params.map prod.snd,\n       m\u03b1\u03b2f \u2190 destruct_typevec\u2083 func `\u03b1,\n       let m := rb_map.of_list $ m\u03b1\u03b2f.map $ \u03bb \u27e8\u03b1,\u03b2,f,i\u27e9, (\u03b1,f),\n       let \u03b2 := m\u03b1\u03b2f.map $ \u03bb \u27e8\u03b1,\u03b2,f,i\u27e9, (\u03b2,i),\n       target >>= instantiate_mvars >>= unsafe_change,\n       let e := (@expr.const tt func.eqn_name func.decl.univ_levels),\n       g \u2190 target,\n       (g',_) \u2190 solve_aux g $\n         repeat (rewrite_target e) >> target,\n       unsafe_change g',\n       x \u2190 intro1,\n       xs \u2190 cases_core x,\n       xs.mmap' $ \u03bb \u27e8c, args, _\u27e9, do\n         { let e := (@expr.const tt c decl.univ_levels).mk_app $ mk_arg_list (vs ++ \u03b2),\n           args' \u2190 args.mmap (map_arg m),\n           exact $ e.mk_app args' } },\n   df \u2190 instantiate_mvars df,\n   add_decl' $ declaration.defn func.map_name decl.univ_params map_t df (reducibility_hints.regular 1 tt) decl.is_trusted\n\nmeta def mk_mvfunctor_map_eqn (func : internal_mvfunctor) : tactic unit :=\ndo env \u2190 get_env,\n   let decl := func.decl,\n   let cs := env.constructors_of func.decl.to_name,\n   live_params' \u2190 func.live_params.mmap $ \u03bb \u27e8v,i\u27e9, flip prod.mk i <$> (infer_type v >>= mk_local_def (add_prime v.local_pp_name)),\n   let arity := live_params'.length,\n   fs \u2190 mzip_with (\u03bb v v' : expr \u00d7 \u2115, prod.mk v.1 <$> mk_local_def (\"f\" ++ to_string v.2 : string) (v.1.imp v'.1)) func.live_params live_params',\n   let m := rb_map.of_list fs,\n   cs.enum.mmap' $ \u03bb \u27e8i,c\u27e9, do\n     { let c := @expr.const tt c func.decl.univ_levels,\n       let e := c.mk_app func.params,\n       let e' := c.mk_app $ mk_arg_list $ func.dead_params ++ live_params',\n       t  \u2190 infer_type e,\n       (vs,_) \u2190 mk_local_pis t,\n       t' \u2190 infer_type e',\n       vs' \u2190 vs.mmap (map_arg m),\n       \u03b1 \u2190 mk_live_vec func.vec_lvl (mk_arg_list func.live_params),\n       \u03b2 \u2190 mk_live_vec func.vec_lvl (mk_arg_list live_params'),\n       f \u2190 mk_map_vec func.vec_lvl $ fs.map prod.snd,\n       let x := e.mk_app vs,\n       let map_e := (@expr.const tt func.map_name func.decl.univ_levels).mk_app (mk_arg_list func.dead_params ++ [\u03b1,\u03b2,f,x]),\n       eqn \u2190 mk_app `eq [map_e,(e'.mk_app vs')] >>= pis (func.params ++ live_params'.map prod.fst ++ fs.map prod.snd ++ vs),\n       (_,pr) \u2190 solve_aux eqn $ do\n         { intros >> reflexivity },\n       pr \u2190 instantiate_mvars pr,\n       add_decl $ declaration.thm (func.map_name <.> (\"_equation_\" ++ to_string i)) decl.univ_params eqn (pure pr),\n       pure () }\n\nmeta def mk_mvfunctor_instance (func : internal_mvfunctor) : tactic unit :=\ndo map_d \u2190 mk_mvfunctor_map func,\n   mk_mvfunctor_map_eqn func,\n   vec \u2190 mk_live_vec func.vec_lvl $ func.live_params.map prod.fst,\n   let decl := func.decl,\n   let intl := (@expr.const tt func.def_name decl.univ_levels).mk_app (func.dead_params.map prod.fst),\n   let vs := (func.dead_params.map prod.fst),\n\n   t \u2190 mk_app ``mvfunctor [intl] >>= pis vs,\n   (_,df) \u2190 @solve_aux unit t $ do\n     { vs \u2190 intro_lst $ vs.map expr.local_pp_name,\n       to_expr ``( { mvfunctor . map := %%(map_d.mk_app vs) } ) >>= exact },\n   df \u2190 instantiate_mvars df,\n   let inst_n := func.def_name <.> \"mvfunctor\",\n   add_decl $ declaration.defn inst_n func.decl.univ_params t df (reducibility_hints.regular 1 tt) func.decl.is_trusted,\n   set_basic_attribute `instance inst_n,\n   pure ()\n\nopen expr (const)\n\nmeta def mk_head_t (decl : inductive_type) (func : internal_mvfunctor) : lean.parser inductive_type :=\ndo let n := decl.name,\n   let head_n := (n <.> \"head_t\"),\n   let sig_c  : expr := const n decl.u_params,\n   cs \u2190 decl.ctors.mmap $ \u03bb d : type_cnstr,\n   do { vs' \u2190 d.args.mfilter $ \u03bb v,\n          do { t \u2190 infer_type v,\n               pure $ \u00ac \u2203 v \u2208 func.live_params, expr.occurs (prod.fst v) t },\n        pure { name := d.name.update_prefix head_n, args := vs', .. d } },\n   let decl' := { name := head_n, ctors := cs, params := func.dead_params.map prod.fst, .. decl },\n   decl' <$ mk_inductive' decl'\n\nmeta def mk_child_t (decl : inductive_type) (func : internal_mvfunctor) : lean.parser (list inductive_type) :=\ndo let n := decl.name,\n   let mk_constr : name \u2192 expr := \u03bb n', (const (n'.update_prefix $ n <.> \"head_t\") decl.u_params).mk_app $ func.dead_params.map prod.fst,\n   let head_t : expr := const (n <.> \"head_t\") decl.u_params,\n   func.live_params.mmap $ \u03bb l,\n     do let child_n := (n <.> \"child_t\" ++ l.1.local_pp_name),\n        let sig_c  : expr := const n decl.u_params,\n        cs \u2190 (decl.ctors.mmap $ \u03bb d : type_cnstr,\n          do { (rec,vs') \u2190 d.args.mpartition $ \u03bb v,\n                 do { t \u2190 infer_type v,\n                      pure $ expr.occurs l.1 t },\n               vs' \u2190 vs'.mfilter $ \u03bb v,\n                 do { t \u2190 infer_type v,\n                      pure $ \u00ac \u2203 v \u2208 func.live_params, expr.occurs (prod.fst v) t },\n               rec.enum.mmap $ \u03bb \u27e8i,r\u27e9, do\n                 (args',r') \u2190 infer_type r >>= unpi,\n                 pure { name := (d.name.append_after i).update_prefix $ n <.> \"child_t\"  ++ l.1.local_pp_name,\n                        args := vs' ++ args', result := [(mk_constr d.name).mk_app vs'], .. d } } : tactic _),\n        idx \u2190 (mk_local_def `i $ head_t.mk_app $ func.dead_params.map prod.fst : tactic _),\n        let decl' := { name := child_n, params := func.dead_params.map prod.fst, idx := decl.idx ++ [idx], ctors := cs.join, .. decl },\n        decl' <$ mk_inductive' decl'\n\nmeta def inductive_type.of_pfunctor (func : internal_mvfunctor) : lean.parser inductive_type :=\ndo -- mk_inductive' func.induct,\n   let d := func.decl,\n   let params := func.params,\n   (idx,t) \u2190 unpi (d.type.instantiate_pi params),\n   env \u2190 get_env,\n   -- let (params,idx) := idx.split_at $ env.inductive_num_params d.to_name,\n   cs \u2190 (env.constructors_of d.to_name).mmap $ \u03bb c : name,\n   do { let e := @const tt c d.univ_levels,\n        t \u2190 infer_type $ e.mk_app params,\n        (vs,t) \u2190 unpi t,\n        pure (t.get_app_fn.const_name,{ type_cnstr .\n               name := c,\n               args := vs,\n               result := t.get_app_args.drop $ env.inductive_num_params d.to_name }) },\n   pure { pre     := func.induct.pre,\n          name    := d.to_name,\n          u_names := d.univ_params,\n          params  := params,\n          idx     := idx, type := t,\n          ctors   := cs.map prod.snd }\n\nmeta def mk_child_t_vec (decl : inductive_type) (func : internal_mvfunctor) (vs : list inductive_type) : lean.parser expr :=\ndo let n := decl.name,\n   let head_t := (@const tt (n <.> \"head_t\") func.decl.univ_levels).mk_app $ func.dead_params.map prod.fst,\n   let child_n := (n <.> \"child_t\"),\n   let arity := func.live_params.length,\n   punit.star \u2190 coe $\n     do { hd_v \u2190 mk_local_def `hd head_t,\n          (expr.sort u') \u2190 pure decl.type,\n          let u := u'.pred,\n          let vec_t := @const tt ``typevec [u] (reflect arity),\n          t \u2190 pis (func.dead_params.map prod.fst ++ [hd_v]) vec_t,\n          nil \u2190 mk_mapp ``fin'.elim0 [some $ expr.sort u.succ],\n          vec \u2190 func.live_params.reverse.mfoldr (\u03bb e v,\n            do c \u2190 mk_const $ child_n ++ e.1.local_pp_name,\n               let c := (@const tt (n <.> \"child_t\" ++ e.1.local_pp_name) func.decl.univ_levels).mk_app $ func.dead_params.map prod.fst ++ [hd_v],\n               mv \u2190 mk_mvar,\n               unify_app (const ``append1 [u]) [mv,v,c]) nil,\n          -- vec \u2190 mk_mapp ``_root_.id [vec_t,vec],\n          df \u2190 (instantiate_mvars vec >>= lambdas (func.dead_params.map prod.fst ++ [hd_v]) : tactic _),\n          -- df \u2190 instantiate_mvars vec,\n          let r := reducibility_hints.regular 1 tt,\n          add_decl' $ declaration.defn child_n func.decl.univ_params t df r tt,\n          -- pure { eqn_compiler.fun_def .\n          --        univs := func.induct.u_names,\n          --        name := child_n,\n          --        params := func.dead_params.map prod.fst ++ [hd_v],\n          --        type := vec_t,\n          --        body := eqn_compiler.def_body.term df }\n          pure () },\n   -- eqn_compiler.add_fn func.decl.to_name eqns,\n   pure $ expr.const child_n $ func.induct.u_params\n\nmeta def mk_pfunctor (func : internal_mvfunctor) : lean.parser unit :=\ndo d \u2190 inductive_type.of_pfunctor func,\n   hd \u2190 mk_head_t d func,\n   ch \u2190 mk_child_t d func,\n   mk_child_t_vec d func ch,\n   let arity := func.live_params.length,\n   (expr.sort u') \u2190 pure d.type,\n   let u := u'.pred,\n   let vec_t := @const tt ``mvpfunctor [u] $ reflect arity,\n   t \u2190 pis (func.dead_params.map prod.fst) vec_t,\n   let n := d.name,\n   let head_t := (@const tt (n <.> \"head_t\") func.decl.univ_levels).mk_app $ func.dead_params.map prod.fst,\n   let child_t := (@const tt (n <.> \"child_t\") func.decl.univ_levels).mk_app $ func.dead_params.map prod.fst,\n   df \u2190 (mk_mapp ``mvpfunctor.mk [some $ reflect arity, head_t,child_t] >>= lambdas (func.dead_params.map prod.fst) : tactic _),\n   add_decl $ mk_definition func.pfunctor_name func.decl.univ_params t df,\n   pure ()\n\nmeta def mk_pfunc_constr (func : internal_mvfunctor) : tactic unit :=\ndo env \u2190 get_env,\n   let cs := env.constructors_of func.decl.to_name,\n   let u := func.type.sort_univ.pred,\n   let u' := func.univ_params.foldl level.max u,\n   let out_t :=  (@const tt func.pfunctor_name func.univ_params).mk_app $ func.dead_params.map prod.fst,\n   vec_t \u2190 mk_live_vec func.vec_lvl $ func.live_params.map prod.fst,\n   let arity := func.live_params.length,\n   let fn := @const tt ``mvpfunctor.apply [u],\n   r \u2190 unify_app fn [reflect arity,out_t,vec_t],\n   cs.mmap $ \u03bb c,\n     do { let p := c.update_prefix (c.get_prefix <.> \"pfunctor\"),\n          let hd_c := c.update_prefix (func.decl.to_name <.> \"head_t\"),\n          let e := (@const tt c func.univ_params).mk_app func.params,\n          (args,_) \u2190 infer_type e >>= mk_local_pis,\n          sig \u2190 pis (func.params ++ args) r,\n          (rec,vs') \u2190 args.mpartition $ \u03bb v,\n                 do { t \u2190 infer_type v,\n                      pure $ \u00ac \u2203 v \u2208 func.live_params, expr.occurs (prod.fst v) t },\n\n          let e := (@const tt hd_c func.univ_params).mk_app (func.dead_params.map prod.fst ++ rec),\n          ms \u2190 func.live_params.mmap $ \u03bb l,\n                do { let l_name := l.1.local_pp_name,\n                     vs' \u2190 vs'.mfilter $ \u03bb v,\n                       do { t \u2190 infer_type v,\n                            pure $ expr.occurs l.1 t },\n                     y \u2190 infer_type e >>= mk_local_def `y,\n                     hy \u2190 mk_app `eq [y,e] >>= mk_local_def `hy,\n                     let ch_t := (@const tt (func.decl.to_name <.> \"child_t\" ++ l_name) func.univ_params).mk_app (func.dead_params.map prod.fst ++ [y]),\n                     let ch_c := c.update_prefix (func.decl.to_name <.> \"child_t\" ++ l_name),\n                     t \u2190 pis (vs' ++ rec ++ [y,hy]) $ ch_t.imp l.1,\n                     (_,f) \u2190 @solve_aux unit t $ do\n                       { (vs',\u03c3\u2080) \u2190 mk_substitution vs' ,\n                         (rec,\u03c3\u2081) \u2190 mk_substitution rec ,\n                         y \u2190 intro1, hy \u2190 intro1,\n                         x \u2190 intro `x,\n                         interactive.generalize `hx () (to_pexpr x,`x'),\n                         solve1 $ do\n                         { a \u2190 better_induction x,\n                           gs \u2190 get_goals,\n                           rs \u2190 mzip_with (\u03bb (x : name \u00d7 list (expr \u00d7 option expr) \u00d7 list (name \u00d7 expr)) g,\n                             do let \u27e8ctor,a,b\u27e9 := x,\n                                set_goals [g],\n                                cases $ hy.instantiate_locals b,\n                                gs \u2190 get_goals,\n                                pure $ gs.map $ \u03bb g, (a,b,g)) a gs,\n                           mzip_with' (\u03bb (v : expr) (r : list (expr \u00d7 option expr) \u00d7 list (name \u00d7 expr) \u00d7 expr),\n                             do let (a,b,g) := r,\n                                set_goals [g],\n                                x' \u2190 get_local `x',\n                                expr.app _ t \u2190 infer_type x',\n                                let ts := t.get_app_args.length - func.dead_params.length,\n                                let a' := (a.drop ts).map prod.fst, exact $ v.mk_app a' ) vs' rs.join,\n                           skip } },\n                     pr \u2190 mk_eq_refl e,\n                     pure $ f.mk_app $ vs' ++ rec ++ [e,pr] },\n          (_,df) \u2190 solve_aux r $ do\n            { m \u2190 mk_map_vec func.vec_lvl ms,\n              refine ``( \u27e8 %%e, _ \u27e9 ),\n              exact m,\n              pure () },\n          let c' := c.update_prefix $ c.get_prefix <.> \"pfunctor\",\n          let vs := func.params ++ args,\n          r  \u2190 pis vs r >>= instantiate_mvars,\n          df \u2190 instantiate_mvars df >>= lambdas vs,\n          add_decl $ mk_definition c' func.decl.univ_params r df,\n          pure () },\n   pure ()\n\n-- meta def saturate' : expr \u2192 expr \u2192 tactic expr\n-- | (expr.pi n bi t b) e :=\n-- do v \u2190 mk_meta_var t,\n--    t \u2190 whnf $ b.instantiate_var v,\n--    saturate' t (e v)\n-- | t e := pure e\n\n-- meta def saturate (e : expr) : tactic expr :=\n-- do t \u2190 infer_type e >>= whnf,\n--    saturate' t e\n\nopen nat expr\n\nmeta def mk_motive : tactic expr :=\ndo (pi en bi d b) \u2190 target,\n   pure $ lam en bi d b\n\nmeta def destruct_multimap' : \u2115 \u2192 expr \u2192 expr \u2192 list expr \u2192 tactic (list expr)\n| 0 v\u2080 v\u2081 xs :=\ndo C \u2190 mk_motive,\n   refine ``(@typevec_cases_nil\u2082 %%C _),\n   pure xs\n| (succ n) v\u2080 v\u2081 xs :=\ndo C \u2190 mk_motive,\n   a \u2190 mk_mvar, b \u2190 mk_mvar,\n   to_expr ``(append1 %%a %%b) tt ff >>= unify v\u2080,\n   `(append1 %%a' %%b') \u2190 pure v\u2081,\n   refine ``(@typevec_cases_cons\u2082 _ %%b %%b' %%a %%a' %%C _),\n   f \u2190 intro `f,\n   destruct_multimap' n a a' (f :: xs)\n\nmeta def destruct_multimap (e : expr) : tactic (list expr) :=\ndo `(%%v\u2080 \u27f9 %%v\u2081) \u2190 infer_type e,\n   `(typevec %%n) \u2190 infer_type v\u2080,\n   n \u2190 eval_expr \u2115 n,\n   n_h \u2190 revert e,\n   destruct_multimap' n v\u2080 v\u2081 [] <*\n     intron (n_h-1)\n\ndef santas_helper {n} {P : mvpfunctor n} {\u03b1} (C : P.apply \u03b1 \u2192 Sort*) {a : P.A} {b} (b')\n  (x : C \u27e8a,b\u27e9) (h : b = b') : C \u27e8a,b'\u27e9 :=\nby cases h; exact x\n\nopen list\n\nsection zip_vars\nvariables (n : name) (univs : list level)\n  (args : list expr) (shape_args : list expr)\n\nmeta def mk_child_arg (e : expr \u00d7 list expr) : list (expr \u00d7 expr \u00d7 \u2115) \u2192 list (expr \u00d7 expr \u00d7 \u2115) \u00d7 list expr \u00d7 expr\n| [] := ([],shape_args.tail,shape_args.head)\n| (\u27e8v,e',i\u27e9::vs) :=\nif v.occurs e.1\n  then let c : expr := const ( (n.update_prefix $ n.get_prefix ++ v.local_pp_name).append_after i ) univs\n       in ( \u27e8v,e',i+1\u27e9::vs, shape_args, expr.lambdas e.2 $ e' $ c.mk_app $ args ++ e.2)\n  else prod.map (cons \u27e8v,e',i\u27e9) id $ mk_child_arg vs\n\nmeta def zip_vars' : list expr \u2192 list (expr \u00d7 expr \u00d7 \u2115) \u2192 list (expr \u00d7 list expr) \u2192 list expr\n| _ xs [] := []\n| shape_args xs (v :: vs) :=\nlet (xs',shape_args',v') := mk_child_arg n univs args shape_args v xs in\nv' :: zip_vars' shape_args' xs' vs\n\nmeta def zip_vars (ls : list (expr \u00d7 expr)) (vs : list expr) : tactic $ list expr :=\ndo vs' \u2190 vs.mmap $ \u03bb v, do { (vs,_) \u2190 infer_type v >>= mk_local_pis, pure (v,vs) },\n   pure $ zip_vars' n univs args shape_args (ls.map $ \u03bb x, (x.1,x.2,0)) vs'\n\nend zip_vars\n\nmeta def mk_pfunc_recursor (func : internal_mvfunctor) : tactic unit :=\ndo let u := fresh_univ func.induct.u_names,\n   v \u2190 mk_live_vec func.vec_lvl $ func.live_params.map prod.fst,\n   fn \u2190 mk_app `mvpfunctor.apply [functor_expr func,v],\n   C \u2190 mk_local' `C binder_info.implicit (expr.imp fn $ expr.sort $ level.param u),\n   let dead_params := func.dead_params.map prod.fst,\n   cases_t \u2190 func.induct.ctors.mmap $ \u03bb c,\n   do { let n := c.name.update_prefix (func.decl.to_name <.> \"pfunctor\"),\n        let e := (@expr.const tt n func.induct.u_params).mk_app (func.params ++ c.args),\n        prod.mk c <$> (pis c.args (C e) >>= mk_local_def `v) },\n   n \u2190 mk_local_def `n fn,\n   (_,df) \u2190 solve_aux (expr.pis [n] $ C n) $ do\n     { n \u2190 intro1, [(_, [n_fst,n_snd], _)] \u2190 cases_core n,\n       hs \u2190 cases_core n_fst,\n       gs \u2190 get_goals,\n       gs \u2190 list.mzip_with\u2083 (\u03bb h g v,\n         do { let \u27e8c,h\u27e9 := (h : type_cnstr \u00d7 expr),\n              set_goals [g],\n              \u27e8n,xs,[(_,n_snd)]\u27e9 \u2190 pure (v : name \u00d7 list expr \u00d7 list (name \u00d7 expr)),\n              fs \u2190 destruct_multimap n_snd,\n              n_snd \u2190 mk_map_vec func.vec_lvl fs,\n              let child_n := c.name.update_prefix $ func.induct.name <.> \"child_t\",\n              let subst := (func.live_params.map prod.fst).zip fs,\n              h_args \u2190 zip_vars child_n func.induct.u_params (dead_params ++ xs) xs subst c.args,\n              let h := h.mk_app h_args,\n              let n_fst := (@const tt n func.induct.u_params).mk_app $ func.dead_params.map prod.fst ++ xs,\n              vec \u2190 mk_live_vec func.vec_lvl $ func.live_params.map prod.fst,\n              fn \u2190 mk_const ``santas_helper,\n              unify_mapp fn [none,none,vec,C,none,none,n_snd,h,none] >>= refine \u2218 to_pexpr,\n              reflexivity <|> (congr; ext [rcases_patt.many [[rcases_patt.one `_]]] none; reflexivity),\n              done }) cases_t gs hs,\n       pure () },\n   let vs := func.params.map expr.to_implicit_binder ++ C :: cases_t.map prod.snd,\n   df \u2190 instantiate_mvars df >>= lambdas vs,\n   t \u2190 pis (vs ++ [n]) (C n),\n   add_decl $ mk_definition (func.pfunctor_name <.> \"rec\") (u :: func.induct.u_names) t df,\n   pure ()\n\nmeta def mk_pfunc_rec_eqns (func : internal_mvfunctor) : tactic unit :=\ndo let u := fresh_univ func.induct.u_names,\n   let rec := (@const tt (func.pfunctor_name <.> \"rec\") (level.param u :: func.induct.u_params)).mk_app func.params,\n   let eqn := (@const tt func.eqn_name func.induct.u_params).mk_app func.params,\n   (C::fs,_) \u2190 infer_type rec >>= mk_local_pis,\n   let rec := rec C,\n   let fs := fs.init,\n   mzip_with' (\u03bb (c : type_cnstr) (f : expr), do\n   { let cn := c.name.update_prefix $ c.name.get_prefix <.> \"pfunctor\",\n     let c := (@const tt cn func.induct.u_params).mk_app func.params,\n     (args,_) \u2190 infer_type c >>= mk_local_pis,\n     let x := c.mk_app args,\n     t \u2190 mk_app `eq [rec.mk_app (fs ++ [x]),f.mk_app args] >>= pis (func.params ++ C :: fs ++ args),\n     (_,df) \u2190 solve_aux t $ do\n     { intros, reflexivity },\n     df \u2190 instantiate_mvars df,\n     let n := cn.append_suffix \"_rec\",\n     add_decl $ declaration.thm n (u :: func.induct.u_names) t (pure df),\n     simp_attr.typevec.set n () tt }) func.induct.ctors fs,\n   skip\n\nmeta def mk_qpf_abs (func : internal_mvfunctor) : tactic unit :=\ndo let n := func.live_params.length,\n   let dead_params := func.dead_params.map prod.fst,\n   let e := (@const tt func.def_name func.induct.u_params).mk_app dead_params,\n   let e' := (@const tt func.pfunctor_name func.induct.u_params).mk_app dead_params,\n   t \u2190 to_expr ``(\u2200 v, mvpfunctor.apply %%e' v \u2192 %%e v),\n   (_,df) \u2190 @solve_aux unit t $ do\n   { vs \u2190 destruct_typevec' func `v,\n     C \u2190 mk_motive,\n     let params := (rb_map.sort prod.snd $ func.dead_params ++ vs).map prod.fst,\n     let rec := @const tt (func.pfunctor_name <.> \"rec\") $ level.succ func.vec_lvl :: func.induct.u_params,\n     let branches := list.repeat (@none expr) func.induct.ctors.length,\n     rec \u2190 unify_mapp rec (params.map some ++ C :: branches),\n     refine \u2218 to_pexpr $ rec,\n     let cs := func.induct.ctors,\n     let c' := cs.map $ \u03bb c : type_cnstr, c.name.update_prefix $ c.name.get_prefix <.> \"pfunctor\",\n     let eqn := (@const tt func.eqn_name func.induct.u_params).mk_app params,\n     cs.mmap $ \u03bb c, solve1 $ do\n       { xs \u2190 intros,\n         let n := c.name.update_prefix func.induct.name,\n         let e := (@const tt n func.induct.u_params).mk_app $ params ++ xs,\n         mk_eq_mpr eqn e >>= exact },\n     done },\n   t \u2190 pis dead_params t,\n   df \u2190 instantiate_mvars df >>= lambdas dead_params,\n   add_decl $ mk_definition func.abs_name func.induct.u_names t df\n\nmeta def mk_qpf_repr (func : internal_mvfunctor) : tactic unit :=\ndo let n := func.live_params.length,\n   let dead_params := func.dead_params.map prod.fst,\n   let e := (@const tt func.def_name func.induct.u_params).mk_app dead_params,\n   let e' := (@const tt func.pfunctor_name func.induct.u_params).mk_app dead_params,\n   t \u2190 to_expr ``(\u2200 v, %%e v \u2192 mvpfunctor.apply %%e' v),\n   (_,df) \u2190 @solve_aux unit t $ do\n   { vs \u2190 destruct_typevec' func `v,\n     C \u2190 mk_motive,\n     let params := (rb_map.sort prod.snd $ func.dead_params ++ vs).map prod.fst,\n     let rec := @const tt (func.induct.name <.> \"rec\") $ level.succ func.vec_lvl :: func.induct.u_params,\n     let branches := list.repeat (@none expr) func.induct.ctors.length,\n     rec \u2190 unify_mapp rec (params.map some ++ C :: branches),\n     refine \u2218 to_pexpr $ rec,\n     let cs := func.induct.ctors,\n     let c' := cs.map $ \u03bb c : type_cnstr, c.name.update_prefix $ c.name.get_prefix <.> \"pfunctor\",\n     let eqn := (@const tt func.eqn_name func.induct.u_params).mk_app params,\n     cs.mmap $ \u03bb c, solve1 $ do\n       { xs \u2190 intros,\n         let n := c.name.update_prefix func.pfunctor_name,\n         let e := (@const tt n func.induct.u_params).mk_app $ params ++ xs,\n         exact e },\n     done },\n   t \u2190 pis dead_params t,\n   df \u2190 instantiate_mvars df >>= lambdas dead_params,\n   add_decl $ mk_definition func.repr_name func.induct.u_names t df\n\nopen bitraversable\n\nmeta def mk_pfunctor_map_eqn (func : internal_mvfunctor) : tactic unit :=\ndo \u03b2 \u2190 func.live_params.mmap $ tfst renew,\n   fs \u2190 mzip_with (\u03bb x y : expr \u00d7 _, mk_local_def `f $ x.1.imp y.1) func.live_params \u03b2,\n   vf \u2190 mk_map_vec func.vec_lvl fs,\n   let cs := func.induct.ctors.map $ \u03bb c : type_cnstr, c.name.update_prefix func.pfunctor_name,\n   let params' := (rb_map.sort prod.snd $ func.dead_params ++ \u03b2).map prod.fst,\n   cs.mmap' $ \u03bb cn,\n     do { let c := (@const tt cn func.induct.u_params).mk_app func.params,\n          let c' := (@const tt cn func.induct.u_params).mk_app params',\n          (vs,_) \u2190 infer_type c >>= mk_local_pis,\n          lhs \u2190 mk_app ``mvfunctor.map [vf,c.mk_app vs],\n          vs' \u2190 vs.mmap $ \u03bb v,\n            do { some (_,f) \u2190 pure $ ((func.live_params.map prod.fst).zip fs).find $ \u03bb x : expr \u00d7 expr, x.1.occurs v | pure v,\n                 (ws,_) \u2190 infer_type v >>= mk_local_pis,\n                 lambdas ws (f $ v.mk_app ws) },\n          let rhs := c'.mk_app vs',\n          t \u2190 mk_app `eq [lhs,rhs] >>= pis (func.params ++ \u03b2.map prod.fst ++ fs ++ vs),\n          (_,df) \u2190 solve_aux t $ do\n          { intros,\n            dunfold_target cs,\n            map_eq \u2190 mk_const ``mvpfunctor.map_eq, rewrite_target map_eq { md := semireducible },\n            simp_only [``(append_fun_comp'),``(nil_fun_comp)],\n            done <|> reflexivity <|> (congr; ext [rcases_patt.many [[rcases_patt.one `_]]] none; reflexivity),\n            done },\n          df \u2190 instantiate_mvars df,\n          let n := cn.append_suffix \"_map\",\n          add_decl $ declaration.thm n func.induct.u_names t (pure df),\n          let n' := mk_simp_attr_decl_name `typevec,\n          simp_attr.typevec.set n () tt },\n   skip\n\nmeta def prove_abs_repr (func : internal_mvfunctor) : tactic unit :=\ndo vs \u2190 destruct_typevec' func `\u03b1,\n   let cs := func.induct.ctors.map $ \u03bb c : type_cnstr, c.name.update_prefix func.pfunctor_name,\n   x \u2190 intro1, cases x,\n   repeat $ do\n   { dunfold_target [func.repr_name,func.abs_name],\n     simp_only [``(typevec.typevec_cases_nil_append1),``(typevec.typevec_cases_cons_append1)],\n     dunfold_target $ [func.pfunctor_name <.> \"rec\"] ++ cs,\n     `[dsimp],\n     reflexivity }\n\nmeta def prove_abs_map (func : internal_mvfunctor) : tactic unit :=\ndo vs \u2190 destruct_typevec\u2083 func `\u03b1,\n   C \u2190 mk_motive,\n   let vs := vs.map $ \u03bb \u27e8\u03b1,\u03b2,f,i\u27e9, (\u03b1,i),\n   let params := (rb_map.sort prod.snd $ func.dead_params ++ vs).map prod.fst,\n   let rec_n := func.pfunctor_name <.> \"rec\",\n   let rec := (@const tt rec_n $ level.zero :: func.induct.u_params).mk_app (params ++ [C]),\n   let cs := func.induct.ctors.map $ \u03bb c : type_cnstr, c.name.update_prefix func.pfunctor_name,\n   apply rec,\n   all_goals $ do\n   { intros,\n     dunfold_target [func.repr_name,func.abs_name],\n     simp_only [``(typevec.typevec_cases_nil_append1),``(typevec.typevec_cases_cons_append1)] [`typevec],\n     reflexivity }\n\nmeta def mk_mvqpf_instance (func : internal_mvfunctor) : tactic unit :=\ndo let n := func.live_params.length,\n   let dead_params := func.dead_params.map prod.fst,\n   let e := (@const tt func.def_name func.induct.u_params).mk_app dead_params,\n   let abs_fn := (@const tt func.abs_name func.induct.u_params).mk_app dead_params,\n   let repr_fn := (@const tt func.repr_name func.induct.u_params).mk_app dead_params,\n   mk_qpf_abs func,\n   mk_qpf_repr func,\n   mk_pfunctor_map_eqn func,\n   pfunctor_i \u2190 mk_mapp ``mvfunctor [some (reflect n),e] >>= mk_instance,\n   mvqpf_t \u2190 mk_mapp ``mvqpf [some (reflect n),e,pfunctor_i] >>= instantiate_mvars,\n   (_,df) \u2190 solve_aux mvqpf_t $ do\n     { let p := (@const tt func.pfunctor_name func.induct.u_params).mk_app dead_params,\n       refine ``( { P := %%p, abs := %%abs_fn, repr' := %%repr_fn, .. } ),\n       solve1 $ prove_abs_repr func,\n       solve1 $ prove_abs_map func },\n   df \u2190 instantiate_mvars df >>= lambdas dead_params,\n   mvqpf_t \u2190 pis dead_params mvqpf_t,\n   let inst_n := func.def_name <.> \"mvqpf\",\n   add_decl $ mk_definition inst_n func.induct.u_names mvqpf_t df,\n   set_basic_attribute `instance inst_n\n\nopen interactive lean.parser lean\n\n@[user_command]\nmeta def qpf_decl (meta_info : decl_meta_info) (_ : parse (tk \"qpf\")) : lean.parser unit :=\ndo d \u2190 inductive_decl.parse meta_info,\n   func \u2190 mk_internal_functor' d,\n   trace_error \"mk_mvfunctor_instance\" $ mk_mvfunctor_instance func,\n   mk_pfunctor func,\n   trace_error \"mk_pfunc_constr\" $ mk_pfunc_constr func,\n   trace_error \"mk_pfunc_recursor\" $ mk_pfunc_recursor func,\n   -- trace_error $ mk_pfunc_rec_eqns func,\n   -- mk_pfunc_map func,\n   -- mk_pfunc_mvfunctor_instance func,\n   trace_error \"mk_mvqpf_instance\" $ mk_mvqpf_instance func,\n   pure ()\n\n-- local attribute [user_command]  qpf_decl\n\nend tactic\n", "meta": {"author": "avigad", "repo": "qpf", "sha": "debe2eacb8cf46b21aba2eaf3f2e20940da0263b", "save_path": "github-repos/lean/avigad-qpf", "path": "github-repos/lean/avigad-qpf/qpf-debe2eacb8cf46b21aba2eaf3f2e20940da0263b/src/data/fix/parser/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681805313639, "lm_q2_score": 0.03258974253448186, "lm_q1q2_score": 0.01290776002961783}}
{"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.Tactic.Simp\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.Tactic.ElabTerm\nimport Lean.Elab.Tactic.Location\nimport Lean.Meta.Tactic.Replace\nimport Lean.Elab.BuiltinNotation\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\nunsafe def evalSimpConfigUnsafe (e : Expr) : TermElabM Meta.Simp.Config :=\n  Term.evalExpr Meta.Simp.Config ``Meta.Simp.Config e\n@[implementedBy evalSimpConfigUnsafe] constant evalSimpConfig (e : Expr) : TermElabM Meta.Simp.Config\n\nunsafe def evalSimpConfigCtxUnsafe (e : Expr) : TermElabM Meta.Simp.ConfigCtx :=\n  Term.evalExpr Meta.Simp.ConfigCtx ``Meta.Simp.ConfigCtx e\n@[implementedBy evalSimpConfigCtxUnsafe] constant evalSimpConfigCtx (e : Expr) : TermElabM Meta.Simp.ConfigCtx\n\n/-\n  `optConfig` is of the form `(\"(\" \"config\" \":=\" term \")\")?`\n  If `ctx == false`, the argument is assumed to have type `Meta.Simp.Config`, and `Meta.Simp.ConfigCtx` otherwise. -/\ndef elabSimpConfig (optConfig : Syntax) (ctx : Bool) : TermElabM Meta.Simp.Config := do\n  if optConfig.isNone then\n    if ctx then\n      return { : Meta.Simp.ConfigCtx }.toConfig\n    else\n      return {}\n  else\n    withoutModifyingState <| withLCtx {} {} <| Term.withSynthesize do\n      let c \u2190 Term.elabTermEnsuringType optConfig[3] (Lean.mkConst (if ctx then ``Meta.Simp.ConfigCtx else ``Meta.Simp.Config))\n      if ctx then\n        return (\u2190 evalSimpConfigCtx (\u2190 instantiateMVars c)).toConfig\n      else\n        evalSimpConfig (\u2190 instantiateMVars c)\n\nprivate def addDeclToUnfoldOrLemma (lemmas : Meta.SimpLemmas) (e : Expr) (post : Bool) : MetaM Meta.SimpLemmas := do\n  if e.isConst then\n    let declName := e.constName!\n    let info \u2190 getConstInfo declName\n    if (\u2190 isProp info.type) then\n      lemmas.addConst declName post\n    else\n      lemmas.addDeclToUnfold declName\n  else\n    lemmas.add #[] e post\n\nprivate def addSimpLemma (lemmas : Meta.SimpLemmas) (stx : Syntax) (post : Bool) : TermElabM Meta.SimpLemmas := do\n  let (levelParams, proof) \u2190 Term.withoutModifyingElabMetaState <| withRef stx <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx none\n    Term.synthesizeSyntheticMVarsUsingDefault\n    let e \u2190 instantiateMVars e\n    let e := e.eta\n    if e.hasMVar then\n      let r \u2190 abstractMVars e\n      return (r.paramNames, r.expr)\n    else\n      return (#[], e)\n  lemmas.add levelParams proof\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 elabSimpLemmas (stx : Syntax) (ctx : Simp.Context) (eraseLocal : Bool) : TacticM Simp.Context := do\n  if stx.isNone then\n    return ctx\n  else\n    /-\n    syntax simpPre := \"\u2193\"\n    syntax simpPost := \"\u2191\"\n    syntax simpLemma := (simpPre <|> simpPost)? term\n\n    syntax simpErase := \"-\" ident\n    -/\n    withMainContext do\n      let mut lemmas := ctx.simpLemmas\n      for arg in stx[1].getSepArgs do\n        if arg.getKind == ``Lean.Parser.Tactic.simpErase then\n          if eraseLocal && (\u2190 Term.isLocalIdent? arg[1]).isSome then\n            -- We use `eraseCore` because the simp lemma for the hypothesis was not added yet\n            lemmas \u2190 lemmas.eraseCore arg[1].getId\n          else\n            let declName \u2190 resolveGlobalConstNoOverloadWithInfo arg[1]\n            lemmas \u2190 lemmas.erase declName\n        else\n          let post :=\n            if arg[0].isNone then\n              true\n            else\n              arg[0][0].getKind == ``Parser.Tactic.simpPost\n          match (\u2190 resolveSimpIdLemma? arg[1]) with\n          | some e => lemmas \u2190 addDeclToUnfoldOrLemma lemmas e post\n          | _      => lemmas \u2190 addSimpLemma lemmas arg[1] post\n      return { ctx with simpLemmas := lemmas }\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\n--  If `ctx == false`, the argument is assumed to have type `Meta.Simp.Config`, and `Meta.Simp.ConfigCtx` otherwise. -/\nprivate def mkSimpContext (stx : Syntax) (eraseLocal : Bool) (ctx := false) : TacticM Simp.Context := do\n  let simpOnly := !stx[2].isNone\n  elabSimpLemmas stx[3] (eraseLocal := eraseLocal) {\n    config      := (\u2190 elabSimpConfig stx[1] (ctx := ctx))\n    simpLemmas  := if simpOnly then {} else (\u2190 getSimpLemmas)\n    congrLemmas := (\u2190 getCongrLemmas)\n  }\n\n/-\n  \"simp \" (\"(\" \"config\" \":=\" term \")\")? (\"only \")? (\"[\" simpLemma,* \"]\")? (location)?\n-/\n@[builtinTactic Lean.Parser.Tactic.simp] def evalSimp : Tactic := fun stx => do\n  let ctx  \u2190 mkSimpContext stx (eraseLocal := false)\n  -- trace[Meta.debug] \"Lemmas {\u2190 toMessageData ctx.simpLemmas.post}\"\n  let loc := expandOptLocation stx[4]\n  match loc with\n  | Location.targets hUserNames simpTarget =>\n    withMainContext do\n      let fvarIds \u2190 hUserNames.mapM fun hUserName => return (\u2190 getLocalDeclFromUserName hUserName).fvarId\n      go ctx fvarIds simpTarget\n  | Location.wildcard =>\n    withMainContext do\n      go ctx (\u2190 getNondepPropHyps (\u2190 getMainGoal)) true\nwhere\n  go (ctx : Simp.Context) (fvarIdsToSimp : Array FVarId) (simpType : Bool) : TacticM Unit := do\n    let mut mvarId \u2190 getMainGoal\n    let mut toAssert : Array Hypothesis := #[]\n    for fvarId in fvarIdsToSimp do\n      let localDecl \u2190 getLocalDecl fvarId\n      let type \u2190 instantiateMVars localDecl.type\n      match (\u2190 simpStep mvarId (mkFVar fvarId) type ctx) with\n      | none => replaceMainGoal []; return ()\n      | some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value }\n    if simpType then\n      match (\u2190 simpTarget mvarId ctx) with\n      | none => replaceMainGoal []; return ()\n      | some mvarIdNew => mvarId := mvarIdNew\n    let (_, mvarIdNew) \u2190 assertHypotheses mvarId toAssert\n    let mvarIdNew \u2190 tryClearMany mvarIdNew fvarIdsToSimp\n    replaceMainGoal [mvarIdNew]\n\n@[builtinTactic Lean.Parser.Tactic.simpAll] def evalSimpAll : Tactic := fun stx => do\n  let ctx  \u2190 mkSimpContext stx (eraseLocal := true) (ctx := true)\n  match (\u2190 simpAll (\u2190 getMainGoal) ctx) with\n  | none => replaceMainGoal []\n  | some mvarId => replaceMainGoal [mvarId]\n\nend Lean.Elab.Tactic\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/Elab/Tactic/Simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.041462276856943696, "lm_q1q2_score": 0.012882097064010656}}
{"text": "import Qq\nopen Qq\n\nset_option linter.unusedVariables false in\ndef typeClassArgument (\u03b1 : Q(Sort u)) (inst : Q(Inhabited $\u03b1)) : Q($\u03b1) :=\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 _ \u2190 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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (a : \u03b1)\n    (b : \u03b2) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) :\n    zip_with f (a :: l\u2081) (b :: l\u2082) = f a b :: zip_with f l\u2081 l\u2082 :=\n  rfl\n\n@[simp] theorem zip_cons_cons {\u03b1 : Type u} {\u03b2 : Type v} (a : \u03b1) (b : \u03b2) (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b2) : zip (a :: l\u2081) (b :: l\u2082) = (a, b) :: zip l\u2081 l\u2082 :=\n  rfl\n\n@[simp] theorem zip_with_nil_left {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (l : List \u03b2) : zip_with f [] l = [] :=\n  rfl\n\n@[simp] theorem zip_with_nil_right {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (l : List \u03b1) : zip_with f l [] = [] :=\n  list.cases_on l (Eq.refl (zip_with f [] []))\n    fun (l_hd : \u03b1) (l_tl : List \u03b1) => Eq.refl (zip_with f (l_hd :: l_tl) [])\n\n@[simp] theorem zip_nil_left {\u03b1 : Type u} {\u03b2 : Type v} (l : List \u03b1) : zip [] l = [] := rfl\n\n@[simp] theorem zip_nil_right {\u03b1 : Type u} {\u03b2 : Type v} (l : List \u03b1) : zip l [] = [] :=\n  zip_with_nil_right Prod.mk l\n\n@[simp] theorem zip_swap {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) :\n    map prod.swap (zip l\u2081 l\u2082) = zip l\u2082 l\u2081 :=\n  sorry\n\n@[simp] theorem length_zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b2) : length (zip_with f l\u2081 l\u2082) = min (length l\u2081) (length l\u2082) :=\n  sorry\n\n@[simp] theorem length_zip {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) :\n    length (zip l\u2081 l\u2082) = min (length l\u2081) (length l\u2082) :=\n  length_zip_with Prod.mk\n\ntheorem lt_length_left_of_zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {i : \u2115}\n    {l : List \u03b1} {l' : List \u03b2} (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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {i : \u2115}\n    {l : List \u03b1} {l' : List \u03b2} (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 {\u03b1 : Type u} {\u03b2 : Type v} {i : \u2115} {l : List \u03b1} {l' : List \u03b2}\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 {\u03b1 : Type u} {\u03b2 : Type v} {i : \u2115} {l : List \u03b1} {l' : List \u03b2}\n    (h : i < length (zip l l')) : i < length l' :=\n  lt_length_right_of_zip_with h\n\ntheorem zip_append {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {r\u2081 : List \u03b1} {l\u2082 : List \u03b2} {r\u2082 : List \u03b2}\n    (h : length l\u2081 = length l\u2082) : zip (l\u2081 ++ r\u2081) (l\u2082 ++ r\u2082) = zip l\u2081 l\u2082 ++ zip r\u2081 r\u2082 :=\n  sorry\n\ntheorem zip_map {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {\u03b4 : Type z} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4)\n    (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : zip (map f l\u2081) (map g l\u2082) = map (prod.map f g) (zip l\u2081 l\u2082) :=\n  sorry\n\ntheorem zip_map_left {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b3) (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b2) : zip (map f l\u2081) l\u2082 = map (prod.map f id) (zip l\u2081 l\u2082) :=\n  eq.mpr\n    (id\n      (Eq._oldrec (Eq.refl (zip (map f l\u2081) l\u2082 = map (prod.map f id) (zip l\u2081 l\u2082)))\n        (Eq.symm (zip_map f id l\u2081 l\u2082))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (zip (map f l\u2081) l\u2082 = zip (map f l\u2081) (map id l\u2082))) (map_id l\u2082)))\n      (Eq.refl (zip (map f l\u2081) l\u2082)))\n\ntheorem zip_map_right {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b2) : zip l\u2081 (map f l\u2082) = map (prod.map id f) (zip l\u2081 l\u2082) :=\n  eq.mpr\n    (id\n      (Eq._oldrec (Eq.refl (zip l\u2081 (map f l\u2082) = map (prod.map id f) (zip l\u2081 l\u2082)))\n        (Eq.symm (zip_map id f l\u2081 l\u2082))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (zip l\u2081 (map f l\u2082) = zip (map id l\u2081) (map f l\u2082))) (map_id l\u2081)))\n      (Eq.refl (zip l\u2081 (map f l\u2082))))\n\ntheorem zip_map' {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (l : List \u03b1) :\n    zip (map f l) (map g l) = map (fun (a : \u03b1) => (f a, g a)) l :=\n  sorry\n\ntheorem mem_zip {\u03b1 : Type u} {\u03b2 : Type v} {a : \u03b1} {b : \u03b2} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2} :\n    (a, b) \u2208 zip l\u2081 l\u2082 \u2192 a \u2208 l\u2081 \u2227 b \u2208 l\u2082 :=\n  sorry\n\ntheorem map_fst_zip {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) :\n    length l\u2081 \u2264 length l\u2082 \u2192 map prod.fst (zip l\u2081 l\u2082) = l\u2081 :=\n  sorry\n\ntheorem map_snd_zip {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) :\n    length l\u2082 \u2264 length l\u2081 \u2192 map prod.snd (zip l\u2081 l\u2082) = l\u2082 :=\n  sorry\n\n@[simp] theorem unzip_nil {\u03b1 : Type u} {\u03b2 : Type v} : unzip [] = ([], []) := rfl\n\n@[simp] theorem unzip_cons {\u03b1 : Type u} {\u03b2 : Type v} (a : \u03b1) (b : \u03b2) (l : List (\u03b1 \u00d7 \u03b2)) :\n    unzip ((a, b) :: l) = (a :: prod.fst (unzip l), b :: prod.snd (unzip l)) :=\n  sorry\n\ntheorem unzip_eq_map {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) :\n    unzip l = (map prod.fst l, map prod.snd l) :=\n  sorry\n\ntheorem unzip_left {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) :\n    prod.fst (unzip l) = map prod.fst l :=\n  sorry\n\ntheorem unzip_right {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) :\n    prod.snd (unzip l) = map prod.snd l :=\n  sorry\n\ntheorem unzip_swap {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) :\n    unzip (map prod.swap l) = prod.swap (unzip l) :=\n  sorry\n\ntheorem zip_unzip {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) :\n    zip (prod.fst (unzip l)) (prod.snd (unzip l)) = l :=\n  sorry\n\ntheorem unzip_zip_left {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2} :\n    length l\u2081 \u2264 length l\u2082 \u2192 prod.fst (unzip (zip l\u2081 l\u2082)) = l\u2081 :=\n  sorry\n\ntheorem unzip_zip_right {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2}\n    (h : length l\u2082 \u2264 length l\u2081) : prod.snd (unzip (zip l\u2081 l\u2082)) = l\u2082 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (zip l\u2081 l\u2082)) = l\u2082)) (Eq.symm (zip_swap l\u2082 l\u2081))))\n    (eq.mpr\n      (id\n        (Eq._oldrec (Eq.refl (prod.snd (unzip (map prod.swap (zip l\u2082 l\u2081))) = l\u2082))\n          (unzip_swap (zip l\u2082 l\u2081))))\n      (unzip_zip_left h))\n\ntheorem unzip_zip {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2}\n    (h : length l\u2081 = length l\u2082) : unzip (zip l\u2081 l\u2082) = (l\u2081, l\u2082) :=\n  sorry\n\ntheorem zip_of_prod {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} {l' : List \u03b2} {lp : List (\u03b1 \u00d7 \u03b2)}\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 {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} (f : \u03b1 \u2192 \u03b2) :\n    map (fun (x : \u03b1) => (x, f x)) l = zip l (map f l) :=\n  sorry\n\ntheorem map_prod_right_eq_zip {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} (f : \u03b1 \u2192 \u03b2) :\n    map (fun (x : \u03b1) => (f x, x)) l = zip (map f l) l :=\n  sorry\n\n@[simp] theorem length_revzip {\u03b1 : Type u} (l : List \u03b1) : length (revzip l) = length l := sorry\n\n@[simp] theorem unzip_revzip {\u03b1 : Type u} (l : List \u03b1) : unzip (revzip l) = (l, reverse l) :=\n  unzip_zip (Eq.symm (length_reverse l))\n\n@[simp] theorem revzip_map_fst {\u03b1 : Type u} (l : List \u03b1) : 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 {\u03b1 : Type u} (l : List \u03b1) : 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 {\u03b1 : Type u} (l : List \u03b1) : reverse (revzip l) = revzip (reverse l) := sorry\n\ntheorem revzip_swap {\u03b1 : Type u} (l : List \u03b1) : map prod.swap (revzip l) = revzip (reverse l) :=\n  sorry\n\ntheorem nth_zip_with {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1)\n    (l\u2082 : List \u03b2) (i : \u2115) : nth (zip_with f l\u2081 l\u2082) i = f <$> nth l\u2081 i <*> nth l\u2082 i :=\n  sorry\n\ntheorem nth_zip_with_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3)\n    (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) (z : \u03b3) (i : \u2115) :\n    nth (zip_with f l\u2081 l\u2082) i = some z \u2194\n        \u2203 (x : \u03b1), \u2203 (y : \u03b2), nth l\u2081 i = some x \u2227 nth l\u2082 i = some y \u2227 f x y = z :=\n  sorry\n\ntheorem nth_zip_eq_some {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) (z : \u03b1 \u00d7 \u03b2) (i : \u2115) :\n    nth (zip l\u2081 l\u2082) i = some z \u2194 nth l\u2081 i = some (prod.fst z) \u2227 nth l\u2082 i = some (prod.snd z) :=\n  sorry\n\n@[simp] theorem nth_le_zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {l : List \u03b1}\n    {l' : List \u03b2} {i : \u2115} {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 {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} {l' : List \u03b2} {i : \u2115}\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 {\u03b1 : Type u} {l : List \u03b1} {init : List \u03b1} {tail : List \u03b1} :\n    (init, tail) \u2208 zip (inits l) (tails l) \u2194 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 data.rat.basic\nimport data.list.defs\n\nimport tactic.rewrite_search.core.common\n\nimport ..types\nimport .common\n\nopen tactic\n\nnamespace tactic.rewrite_search.discovery\n\nopen tactic.rewrite_search\n\ndef BUNDLE_CHUNK_SIZE := 1\n\n-- TODO Be smarter about calculating this.\nmeta def score_bundle (b : bundle_ref) (sample : list expr) : tactic \u2115 := do\n  mems \u2190 b.get_members,\n  mems.mfoldl (\u03bb sum n, do\n    e \u2190 mk_const n,\n    ret \u2190 are_promising_rewrites (rewrite_list_from_lemma e) sample,\n    return $ if ret then sum + 1 else sum\n  ) 0\n\n-- TODO report the lemma(s) which caused a selected bundle to be chosen,\n-- so that that lemma could just be tagged individually.\n\n-- TODO at the end of the search report which \"desperations\" things happened\n-- (bundles added, random lemmas found and used) so that they can be addressed\n-- more easily/conveniently.\n\ndef min_rel {\u03b1 : Type} (l : list \u03b1) (r : \u03b1 \u2192 \u03b1 \u2192 Prop) [decidable_rel r] : option \u03b1 :=\nl.foldl (\u03bb o a, match o with | none := some a | some b := if r b a then b else a end) none\n\nmeta def try_bundles (conf : config) (rs : list (expr \u00d7 bool)) (p : progress) (sample : list expr) : tactic (progress \u00d7 list (expr \u00d7 bool)) :=\n  if p.persistence < persistence.try_bundles then\n    return (p, [])\n  else do\n    bs \u2190 list.filter (\u03bb b, b \u2209 p.seen_bundles) <$> get_bundles,\n    bs \u2190 bs.mmap $ \u03bb b, (do s \u2190 score_bundle b sample, return (b, s)),\n    (awful_bs, interesting_bs) \u2190 pure $ bs.partition $ \u03bb b, b.2 = 0,\n    let p := {p with seen_bundles := p.seen_bundles.append (awful_bs.map prod.fst)},\n    match min_rel interesting_bs (\u03bb a b, a.2 > b.2) with\n    | none := do\n      if conf.trace_discovery then\n      discovery_trace format!\"Could not find any promising bundles of the {bs.length} non-suggested bundles considered: {bs.map $ \u03bb b, b.1.bundle.name}\"\n      else skip,\n      return (p, [])\n    | some (b, score) := do\n      if conf.trace_discovery then\n      discovery_trace format!\"Found a promising bundle (of {bs.length} considered) \\\"{b.bundle.name}\\\"! If we succeed, please suggest this bundle for consideration.\"\n      else skip,\n      ms \u2190 b.get_members >>= load_names,\n      return (p, rewrite_list_from_lemmas ms)\n    end\n\nend tactic.rewrite_search.discovery\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/src/tactic/rewrite_search/discovery/collector/bundle.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861801254413975, "lm_q2_score": 0.033085981844833426, "lm_q1q2_score": 0.012857808507610657}}
{"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.Tactic.Injection\nimport Lean.Meta.Tactic.Apply\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 := 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\nprivate partial def mkInjectiveTheoremTypeCore? (ctorVal : ConstructorVal) (useEq : Bool) : MetaM (Option Expr) := do\n  let us := ctorVal.levelParams.map mkLevelParam\n  forallBoundedTelescope ctorVal.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 \u2190 mkEq lhs rhs\n      let mut eqs := #[]\n      for arg1 in args1, arg2 in args2 do\n        let arg1Type \u2190 inferType arg1\n        if !(\u2190 isProp arg1Type) && arg1 != arg2 then\n          if (\u2190 isDefEq arg1Type (\u2190 inferType arg2)) then\n            eqs := eqs.push (\u2190 mkEq arg1 arg2)\n          else\n            eqs := eqs.push (\u2190 mkHEq arg1 arg2)\n      if let some andEqs \u2190 mkAnd? eqs then\n        let result \u2190\n          if useEq then\n            mkEq eq andEqs\n          else\n            mkArrow eq andEqs\n        mkForallFVars params (\u2190 mkForallFVars args1 (\u2190 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 (\u2190 whnf type) with\n        | Expr.forallE n d b _ =>\n          let arg1 := args1.get \u27e8i, h\u27e9\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 {\u03b1} (ctorName : Name) (mvarId : MVarId) : MetaM \u03b1 :=\n  throwError \"{injTheoremFailureHeader ctorName}{indentD <| MessageData.ofGoal mvarId}\"\n\nprivate def solveEqOfCtorEq (ctorName : Name) (mvarId : MVarId) (h : FVarId) : MetaM Unit := do\n  match (\u2190 injection mvarId h) with\n  | InjectionResult.solved => unreachable!\n  | InjectionResult.subgoal mvarId .. =>\n    (\u2190 splitAnd mvarId).forM fun mvarId =>\n      unless (\u2190 assumptionCore mvarId) 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 \u2190 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 \u2190 mkInjectiveTheoremType? ctorVal\n    | return ()\n  let value \u2190 mkInjectiveTheoremValue ctorVal.name type\n  addDecl <| Declaration.thmDecl {\n    name        := mkInjectiveTheoremNameFor ctorVal.name\n    levelParams := ctorVal.levelParams\n    type        := (\u2190 instantiateMVars type)\n    value       := (\u2190 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 \u2190 mkFreshExprSyntheticOpaqueMVar type\n    let [mvarId\u2081, mvarId\u2082] \u2190 apply mvar.mvarId! (mkConst ``Eq.propIntro)\n      | throwError \"unexpected number of subgoals when proving injective theorem for constructor '{ctorName}'\"\n    let (h, mvarId\u2081) \u2190 intro1 mvarId\u2081\n    let (_, mvarId\u2082) \u2190 intro1 mvarId\u2082\n    solveEqOfCtorEq ctorName mvarId\u2081 h\n    let mvarId\u2082 \u2190 casesAnd mvarId\u2082\n    let mvarId\u2082 \u2190 substEqs mvarId\u2082\n    applyRefl mvarId\u2082 (injTheoremFailureHeader ctorName)\n    mkLambdaFVars xs mvar\n\nprivate def mkInjectiveEqTheorem (ctorVal : ConstructorVal) : MetaM Unit := do\n  let some type \u2190 mkInjectiveEqTheoremType? ctorVal\n    | return ()\n  let value \u2190 mkInjectiveEqTheoremValue ctorVal.name type\n  let name := mkInjectiveEqTheoremNameFor ctorVal.name\n  addDecl <| Declaration.thmDecl {\n    name\n    levelParams := ctorVal.levelParams\n    type        := (\u2190 instantiateMVars type)\n    value       := (\u2190 instantiateMVars value)\n  }\n  addSimpLemma name (post := true) 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 (\u2190 getEnv).contains ``Eq.propIntro && genInjectivity.get (\u2190 getOptions) &&  !(\u2190 isInductivePredicate declName) then\n    let info \u2190 getConstInfoInduct declName\n    unless info.isUnsafe do\n      for ctor in info.ctors do\n        let ctorVal \u2190 getConstInfoCtor ctor\n        if ctorVal.numFields > 0 then\n          mkInjectiveTheorem ctorVal\n          mkInjectiveEqTheorem ctorVal\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/Injective.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.026759283379480286, "lm_q1q2_score": 0.012857265103682017}}
{"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 \u00d7 String)) := do\n  let json \u2190 readJson s\n  return do\n    (\u2190 json.getArr?).mapM <| fun j => do\n      let docstring \u2190 j.getObjValAs? String \"doc_string\" \n      let typeField := \n        if fileName \u2208 [\"data/mathlib4-prompts.json\"] then \"type\"\n        else theoremField\n      let thm \u2190 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 \u00d7 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 \u00d7 String)) : Json:= prompt sysPrompt pairs.toList query \n\ndef makeFlipPrompt(query : String)(pairs: Array (String \u00d7 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 \u2190 \n    match json.getArr? with\n    | Except.ok arr => \n        let parsedArr : Array String \u2190 \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 \u00d7 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 \u00d7 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 \u00d7 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 := \u27e82, 1\u27e9)(stopTokens: Array String :=  #[\":=\", \"-/\"]) : MetaM Json := do\n  let key? \u2190 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 \u2190  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 := \u27e82, 1\u27e9)(stopTokens: Array String :=  #[\":=\", \"-/\"]) : MetaM Json := do\n  let key? \u2190 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 \u2190  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 := \u27e82, 1\u27e9)(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) \u2190 IO.mkRef (HashMap.empty)\n\ninitialize pendingJsonQueries : IO.Ref (HashSet String) \n    \u2190 IO.mkRef (HashSet.empty)\n\ninitialize logCache : IO.Ref (Array String) \u2190 IO.mkRef (#[])\n\ndef mkLog{\u03b1 : Type _}[ToString \u03b1](msg: \u03b1) : IO Unit := do\n  let cache \u2190 logCache.get\n  logCache.set (cache.push (toString msg))\n\ndef logs (num: Nat) : IO (List String) := do\n  let cache \u2190 logCache.get\n  return cache.reverse.toList.take num\n\ndef showLogs (num: Nat) : IO Unit := do\n  let cache \u2190 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 \u2190 webCacheJson.get\n  return cache.find? s\n\ndef cacheJson (s: String)(js: Json)  : IO Unit := do\n  let cache \u2190 webCacheJson.get\n  webCacheJson.set (cache.insert s js)\n  return ()\n\npartial def pollCacheJson (s : String) : IO Json := do\n  let cache \u2190 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? \u2190 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 \u2190 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 : \u2115) (f : \u2115 \u2192 \u2102) :\\n abs (\u2211 i in finset.range n, f i) \u2264 \u2211 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 : \u2115) (x y : euclidean_space \u211d (fin n)) :\\n \u2225x + y\u2225^2 + \u2225x - y\u2225^2 = 2*\u2225x\u2225^2 + 2*\u2225y\u2225^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 \u2260 1) (hx_inf : \u2200 n : \u2115, x ^ n \u2260 1) : \u2200 m n : \u2124, m \u2260 n \u2192 x ^ m \u2260 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 : \u2200 x \u2208 A, \u2203 U : set X, is_open U \u2227 x \u2208 U \u2227 U \u2286 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 \u00d7 String) \u00d7 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 \u2190  \n        IO.Process.output {cmd:= \"curl\", args:= \n          #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{\u2190 leanAideIP}/nearest_prompts\"]}\n      let pairs? \u2190 sentenceSimPairs simJsonOut.stdout \"theorem\"\n      -- IO.println s!\"obtained sentence similarity; time : {\u2190 IO.monoMsNow}\"\n      let allPairs : Array (String \u00d7 String) \u2190 \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 \u2190  keywordBasedPrompts docPair s numKW scoreBound matchBound\n        else #[]\n      -- IO.println s!\"obtained keyword pairs; time : {\u2190 IO.monoMsNow}\"\n      let allPairs := (allPairs ++ kwPairs).toList.eraseDups.toArray\n      let pairs -- := allPairs -- \n        \u2190  allPairs.filterM (fun (_, s) => do\n            isElabPrompt s )\n      let kwPairs \u2190  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 \u00d7 String) \u00d7 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 \u2190  \n        IO.Process.output {cmd:= \"curl\", args:= \n          #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{\u2190 leanAideIP}/nearest_prompts\"]}\n      let pairs? \u2190 sentenceSimPairs simJsonOut.stdout theoremField\n      -- IO.println s!\"obtained sentence similarity; time : {\u2190 IO.monoMsNow}\"\n      let allPairs : Array (String \u00d7 String) \u2190 \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 := \u27e82, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : TermElabM Json := do\n  match \u2190 getCachedJson? s with\n  | some js => return js\n  | none =>    \n    let pending \u2190  pendingJsonQueries.get\n    if pending.contains s then pollCacheJson s \n    else \n      let pending \u2190  pendingJsonQueries.get\n      pendingJsonQueries.set (pending.insert s)\n      -- work starts here; before this was caching, polling etc\n      let (pairs, IOOut) \u2190  \n        if numSim > 0 then  \n          getPromptPairs s numSim numKW scoreBound matchBound \n        else pure (#[], \u27e80, \"\", \"\"\u27e9)\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 \u2190 \n        gptQuery prompt queryNum temp \n      let outJson := \n        (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n      let pending \u2190  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? \u2190 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 \u2190  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 \u2190 groupFuncStrs elaborated\n    let topStr := groupSorted[0]![0]!\n    let thmExc \u2190 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? \u2190 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 \u2190  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 \u2190 groupFuncStrs elaborated\n    let topStr := groupSorted[0]![0]!\n    let thmExc \u2190 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\u00d7 (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? \u2190 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 \u2190  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 \u2190 groupFuncStrs priority\n    let topStr := groupSorted[0]![0]!\n    let thmExc \u2190 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? \u2190 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, _) \u2190 getPromptPairs thm numSim numKW scoreBound matchBound\n    let prompt := GPT.makeFlipPrompt thm pairs\n    -- elabLog prompt\n    let fullJson \u2190 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, _) \u2190 getPromptPairsGeneral thm numSim \"statement\"\n    let prompt := makeFlipStatementsPrompt thm pairs\n    -- elabLog prompt\n    let fullJson \u2190 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 : \u2200 n: Nat, \u2203 m : Nat, m > n \u2227 m % 2 = 0\"\n\ndef egPairs := getPromptPairsGeneral egThm 5 \"statement\" \"statement\"\n\ndef egPrompt := do\n  let (pairs, _) \u2190 egPairs\n  return makeFlipStatementsPrompt egThm pairs\n\n-- #eval egPrompt\n\n-- #eval statementToDoc egThm 5 0\n\n-- #eval leanToPrompt \"\u2200 {p : \u2115} [inst : Fact (Nat.Prime p)], p = 2 \u2228 p % 2 = 1\"\n\n-- #eval leanToPrompt \"\u2200 {\u03b1 : Type u} {x : FreeGroup \u03b1}, x \u2260 1 \u2192 \u00acIsOfFinOrder x\"\n\n-- #eval leanToPrompt \"{  n :  \u2115 } ->  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 \u2190 \n    match json.getArr? with\n    | Except.ok arr => \n        let parsedArr : Array String \u2190 \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 \u2190 readJson jsString\n  let outArr : Array String \u2190 \n    match json.getArr? with\n    | Except.ok arr => \n        let parsedArr : Array String \u2190 \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 \u2190 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 \u2190 getCodeJson  s\n  -- filtering, autocorrection and selection\n  let e \u2190 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 \" : \" ++ (\u2190 e.view)\n  | k +1 => \n    match e with\n    | Expr.forallE n t _ bi => do\n      let core := s!\"{n.eraseMacroScopes} : {\u2190 t.view}\"\n      let typeString :=s!\"{\u2190 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 \u2190 \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 \u2190 inferType fx\n            uncurriedView k newType\n      return \" \" ++ argString ++ tail\n    | _ => do return \" : \" ++ (\u2190 e.view)\n\nelab \"uncurry2\" e:term : term => do\n  let e \u2190 Term.elabTerm e none\n  let e \u2190 uncurriedView 2 e\n  return mkStrLit e\n\nuniverse u\n\n\ndef translateViewM (s: String) : TermElabM String := do\n  let js \u2190 getCodeJson  s\n  let output \u2190 GPT.jsonToExprStrArray js\n  trace[Translate.info] m!\"{output}\"\n  let e? \u2190 arrayToExpr? output\n  match e? with\n  | some (e, _) => do\n    e.view\n  | none => do\n    let stx \u2190 output.findSomeM? <| fun s => do\n      let exp \u2190  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": "import Do.Mut\n\n/-! # Early Return -/\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\ndef runCatch [Monad m] (x : ExceptT \u03b1 m \u03b1) : m \u03b1 :=\n  ExceptT.run x >>= fun\n    | Except.ok x => pure x\n    | Except.error e => pure e\n\n/-- Count syntax nodes satisfying `p`. -/\npartial def Lean.Syntax.count (stx : Syntax) (p : Syntax \u2192 Bool) : Nat :=\n  stx.getArgs.foldl (fun n arg => n + arg.count p) (if p stx then 1 else 0)\n\nsyntax \"return\" term : stmt\n\nsyntax \"return\" : expander\n\nmacro_rules\n  | `(do' $s) => do  -- (1')\n    -- optimization: fall back to original rule (1) if now `return` statement was expanded\n    let s' \u2190 expandStmt (\u2190 `(stmt| expand! return in $s))\n    if s'.raw.count (\u00b7 matches `(stmt| return $_)) == s.raw.count (\u00b7 matches `(stmt| return $_)) then\n      `(d! $s)\n    else\n      `(ExceptCpsT.runCatch (d! $s'))\n\nmacro_rules\n  | `(stmt| expand! return in return $e) => `(stmt| throw $e)          -- (R1)\n  | `(stmt| expand! return in $e:term) => `(stmt| ExceptCpsT.lift $e)  -- (R2)\n\nvariable [Monad m]\nvariable (ma ma' : m \u03b1)\nvariable (b : Bool)\n\nexample [LawfulMonad m] :\n    (do' let x \u2190 ma;\n         return x)\n    = ma\n:= by simp\n\nexample : Id.run\n    (do' let x := 1; return x)\n    = 1\n:= rfl\n\nexample [LawfulMonad m] :\n     (do' if b then {\n            let x \u2190 ma;\n            return x\n          };\n          ma')\n     =\n     (if b then ma else ma')\n:= by cases b <;> simp\n\nexample [LawfulMonad m] :\n    (do' let y \u2190\n           if b then {\n             let x \u2190 ma;\n             return x\n           } else {\n             ma'\n           };\n         pure y)\n    =\n    (if b then ma else ma')\n:= by cases b <;> simp\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/Return.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.04084571985051788, "lm_q1q2_score": 0.012827620579637829}}
{"text": "import LeanCodePrompts.Translate\nimport Lean\nimport Lean.Meta\nopen Lean Meta Elab\n\n/-- extract prompt pairs from JSON response to local server -/\ndef sentenceSimTriples(s: String) : MetaM  <| Except String (Array (String \u00d7 String \u00d7 String)) := do\n  let json \u2190 readJson (s) \n  -- logInfo \"obtained json\"\n  match json.getArr? with\n  | Except.ok jsonArr => do\n    let pairs \u2190  jsonArr.mapM fun json => do\n      let docstring : String \u2190  \n        match (json.getObjVal? \"doc_string\") with\n        | Except.error e => throwError s!\"Error {e} while getting doc_string\"\n        | Except.ok js => \n          match js.getStr? with\n          | Except.error e => throwError s!\"Error {e} while processing {js} as string\"  \n          | Except.ok s => pure s\n      let args \u2190  match (json.getObjVal? \"args\") with\n        | Except.error e => throwError s!\"Error {e} while getting theorem\"\n        | Except.ok js => \n          match js.getStr? with\n          | Except.error e => throwError s!\"Error {e} while processing {js} as string\"  \n          | Except.ok s => pure s\n      let type \u2190  match (json.getObjVal? \"type\") with\n        | Except.error e => throwError s!\"Error {e} while getting theorem\"\n        | Except.ok js => \n          match js.getStr? with\n          | Except.error e => throwError s!\"Error {e} while processing {js} as string\"  \n          | Except.ok s => pure s\n      return (docstring, args, type)\n    return Except.ok pairs\n  | Except.error e => return Except.error e\n\n/-- choosing pairs to build a prompt -/\ndef getPromptTriples(s: String)(numSim : Nat)\n   : TermElabM (Array (String \u00d7 String \u00d7 String) \u00d7 IO.Process.Output) := do\n      let jsData := Json.mkObj [\n        (\"filename\", \"data/safe_prompts.json\"),\n        (\"field\", \"doc_string\"),\n        (\"doc_string\", s),\n        (\"n\", numSim),\n        (\"model_name\", \"all-mpnet-base-v2\")\n      ]\n      let simJsonOut \u2190  \n        IO.Process.output {cmd:= \"curl\", args:= \n          #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{\u2190 leanAideIP}/nearest_prompts\"]}\n      let triples? \u2190 sentenceSimTriples simJsonOut.stdout\n      let allTriples := triples?.toOption.getD #[]        \n        -- \u2190  allPairs.filterM (fun (_, s) => do\n        --     isElabPrompt s )\n      return (\n          allTriples.toList.eraseDups.toArray, simJsonOut)\n\n\ndef sysContinuationPrompt := \"You are a coding assistant who translates from natural language to Lean Theorem Prover code following examples. Follow EXACTLY the syntax in the examples given. You will continue the sequence of examples\"\n\ndef continuationPrompt (egs: String) : Json := \n  Json.arr <| #[GPT.message \"system\" sysContinuationPrompt, GPT.message \"user\" egs]\n    \n\n/-- make prompt for continuing statements-/\ndef makeThmsPrompt(pairs: Array (String \u00d7 String))(context: String := \"\") : String := \npairs.foldr (fun  (_, thm) acc => \n        -- acc ++ \"/-- \" ++ ds ++\" -/\\ntheorem\" ++ thm ++ \"\\n\" ++ \"\\n\"\ns!\"theorem {thm} :=\n\n{acc}\"\n          ) s!\"\"\n\n\n/-- make prompt for continuing statements with docs-/\ndef makeDocsThmsPrompt(pairs: Array (String \u00d7 String)) : String := \npairs.foldr (fun  (ds, thm) acc => \ns!\"/-- {ds} -/\ntheorem {thm} := sorry\n\n{acc}\") s!\"\n/--\"\n\n/-- make prompt for continuing statements with docs-/\ndef makeSectionPrompt(triples: Array (String \u00d7 String \u00d7 String))\n    (context: String) : String := \ntriples.foldr (fun  (ds, args, type) acc => \ns!\"section\nvariable {args} \n/-- {ds} -/\ntheorem : {type} := sorry\nend\n\n{acc}\") s!\"section\nvariable {context}\n/-- \"\n\n\n\ndef getContinuationExprs (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 20)(temp : JsonNumber := \u27e88, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : TermElabM <| Array String := do\n      -- work starts here; before this was caching, polling etc\n    let (pairs, IOOut) \u2190  \n      if numSim > 0 then  \n        getPromptPairs s numSim numKW scoreBound matchBound \n      else pure (#[], \u27e80, \"\", \"\"\u27e9)\n    let pairs := if includeFixed then pairs ++ fixedPrompts else pairs \n    let prompt := continuationPrompt (makeThmsPrompt pairs)\n    trace[Translate.info] m!\"prompt: \\n{prompt}\"\n    mkLog prompt\n    let fullJson \u2190 gptQuery prompt queryNum temp\n    let outJson := \n      (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n    let pending \u2190  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    GPT.jsonToExprStrArray outJson\n\ndef getDocContinuationExprs (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 8)(temp : JsonNumber := \u27e88, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : TermElabM <| Array String := do\n      -- work starts here; before this was caching, polling etc\n    let (pairs, IOOut) \u2190  \n      if numSim > 0 then  \n        getPromptPairs s numSim numKW scoreBound matchBound \n      else pure (#[], \u27e80, \"\", \"\"\u27e9)\n    let pairs := if includeFixed then pairs ++ fixedPrompts else pairs \n    let promptPairs := pairs.map (fun (doc, thm) => (\"State a theorem with docstring\", s!\"/-- {doc} -/\\ntheorem {thm}\"))\n    let prompt := GPT.makePrompt \"State a theorem\" promptPairs\n    trace[Translate.info] m!\"prompt: \\n{prompt}\"\n    mkLog prompt\n    let fullJson \u2190 gptQuery prompt queryNum temp #[\":=\"]\n    let outJson := \n      (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n    let pending \u2190  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    let completions \u2190 GPT.jsonToExprStrArray outJson\n    let padded := completions.map (fun c => \"/-- \" ++ c)\n    return padded\n\ndef getSectionContinuationExprs (s: String)(context: String)(numSim : Nat:= 10)(queryNum: Nat := 8)(temp : JsonNumber := \u27e88, 1\u27e9) : TermElabM <| Array String := do\n      -- work starts here; before this was caching, polling etc\n    let (triples, IOOut) \u2190  \n        getPromptTriples s numSim  \n    let promptPairs := triples.map (fun (doc, args, thm) => (\"State a theorem with docstring in context\", s!\"variable {args}\\n/-- {doc} -/\\ntheorem {thm}\"))\n    let prompt := GPT.makePrompt \"State a theorem\" promptPairs\n    trace[Translate.info] m!\"prompt: \\n{prompt}\"\n    mkLog prompt\n    let fullJson \u2190 gptQuery prompt queryNum temp #[\":=\"]\n    let outJson := \n      (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n    let pending \u2190  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    let completions \u2190 GPT.jsonToExprStrArray outJson\n    let padded := completions.map (fun c => \n    s!\"{context}\n/-- \" ++ c)\n    return padded\n\n\ndef showContinuationExprs (s: String)(context: String := \"\")(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 8)(temp : JsonNumber := \u27e88, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : TermElabM <| Array (String \u00d7 (List String)) := do\n  let exprs \u2190 \n    getContinuationExprs s numSim numKW includeFixed queryNum temp scoreBound matchBound\n  exprs.mapM (fun s => do\n    let exps? \u2190 polyElabThmTrans (context ++ \" \" ++ s)\n    let exps := exps?.toOption.getD []\n    return (s!\"{s} := sorry\",exps.map (fun (_, s) => s.2))\n  )\n\ndef showDocContinuationExprs (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 20)(temp : JsonNumber := \u27e88, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : TermElabM <| Array (String \u00d7 (List String)) := do\n  let exprs \u2190 \n    getDocContinuationExprs s numSim numKW includeFixed queryNum temp scoreBound matchBound\n  exprs.mapM (fun s => do\n    let exps? \u2190 polyElabThmTrans (s)\n    let exps := exps?.toOption.getD []\n    return (s, exps.map (fun (_, s) => s.2))\n  )\n\ndef showSectionContinuationExprs (s: String)(context: String := \"\")(numSim : Nat:= 10)(queryNum: Nat := 16)(temp : JsonNumber := \u27e88, 1\u27e9) : TermElabM <| Array (String \u00d7 (List String)) := do\n  let exprs \u2190 \n    getSectionContinuationExprs s context numSim  queryNum temp \n  exprs.mapM (fun s => do\n    let exps? \u2190 polyElabThmTrans (s)\n    let exps := exps?.toOption.getD []\n    return (s, exps.map (fun (_, s) => s.2))\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/StatementGen.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.04084571868294197, "lm_q1q2_score": 0.012827619688492806}}
{"text": "def f : IO Nat := do\n  IO.println \"hello\"\n  IO.getStdin\n  return 10\n\ndef f1 : ExceptT String (StateT Nat Id) Nat := do\n  modify (\u00b7 + 1)\n  get\n\ndef f2 (x : Nat) : ExceptT String (StateT Nat Id) Nat := do\n  modify (\u00b7 + x)\n  get\n\ndef g1 : ExceptT String (StateT Nat Id) Unit := do\n  let x : String \u2190 f1\n  return ()\n\ndef g2 : ExceptT String (StateT Nat Id) Unit := do\n  let x : String \u2190 f2 10\n  return ()\n\ndef g3 : ExceptT String (StateT Nat Id) String := do\n  let x \u2190 f2\n  f1\n\nexample : Nat := Id.run do\n  let mut n : Nat := 0\n  (n, _) := (false, false)\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/tests/lean/doErrorMsg.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.04084571445047957, "lm_q1q2_score": 0.012827618359285737}}
{"text": "/-\nCopyright (c) 2022 Alex J. Best. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Alex J. Best\n-/\nimport Lean.Parser.Term\nimport Lean.Parser.Do\nimport Lean.Elab.Command\nimport Mathlib.Data.KVMap\n\n/-!\n# The `unset_option` command\n\nThis file defines an `unset_option` user command, which unsets user configurable\noptions.\nFor example inputing `set_option blah 7` and then `unset_option blah`\nreturns the user to the default state before any `set_option` command is called.\nThis is helpful when the user does not know the default value of the option or it\nis cleaner not to write it explicitly, or for some options where the default\nbehaviour is different from any user set value.\n-/\n\nnamespace Lean.Elab\n\nvariable [Monad m] [MonadOptions m] [MonadExceptOf Exception m] [MonadRef m]\nvariable [AddErrorMessageContext m] [MonadLiftT (EIO Exception) m] [MonadInfoTree m]\n\n/-- unset the option specified by id -/\ndef elabUnsetOption (id : Syntax) : m Options := do\n  -- We include the first argument (the keyword) for position information in case `id` is `missing`.\n  addCompletionInfo <| CompletionInfo.option (\u2190 getRef)\n  unsetOption id.getId.eraseMacroScopes\nwhere\n  /-- unset the given option name -/\n  unsetOption (optionName : Name) : m Options := return (\u2190 getOptions).erase optionName\n\nnamespace Command\n\n/-- Unset a user option -/\nelab (name := unsetOption) \"unset_option \" opt:ident : command => do\n  let options \u2190 Elab.elabUnsetOption opt\n  modify fun s \u21a6 { s with maxRecDepth := maxRecDepth.get options }\n  modifyScope fun scope \u21a6 { scope with opts := options }\n\nend Command\nend Lean.Elab\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/UnsetOption.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106120858237414, "lm_q2_score": 0.07477003517655195, "lm_q1q2_score": 0.012790252583047605}}
{"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 {\u03b1 : Type u_1} [preorder \u03b1] (f : \u2115 \u2192 \u03b1) {m : \u2115} (h : \u2200 (n : \u2115), n \u2265 m \u2192 f (Nat.succ n) \u2264 f n) {l : \u2115} (k : \u2115) (H : k \u2265 m) : k \u2264 l \u2192 f l \u2264 f k := sorry\n\ntheorem is_cau_of_decreasing_bounded {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] (f : \u2115 \u2192 \u03b1) {a : \u03b1} {m : \u2115} (ham : \u2200 (n : \u2115), n \u2265 m \u2192 abs (f n) \u2264 a) (hnm : \u2200 (n : \u2115), n \u2265 m \u2192 f (Nat.succ n) \u2264 f n) : is_cau_seq abs f := sorry\n\ntheorem is_cau_of_mono_bounded {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] (f : \u2115 \u2192 \u03b1) {a : \u03b1} {m : \u2115} (ham : \u2200 (n : \u2115), n \u2265 m \u2192 abs (f n) \u2264 a) (hnm : \u2200 (n : \u2115), n \u2265 m \u2192 f n \u2264 f (Nat.succ n)) : is_cau_seq abs f := sorry\n\ntheorem is_cau_series_of_abv_le_cau {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {f : \u2115 \u2192 \u03b2} {g : \u2115 \u2192 \u03b1} (n : \u2115) : (\u2200 (m : \u2115), n \u2264 m \u2192 abv (f m) \u2264 g m) \u2192\n  (is_cau_seq abs fun (n : \u2115) => finset.sum (finset.range n) fun (i : \u2115) => g i) \u2192\n    is_cau_seq abv fun (n : \u2115) => finset.sum (finset.range n) fun (i : \u2115) => f i := sorry\n\ntheorem is_cau_series_of_abv_cau {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {f : \u2115 \u2192 \u03b2} : (is_cau_seq abs fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => abv (f n)) \u2192\n  is_cau_seq abv fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => f n :=\n  is_cau_series_of_abv_le_cau 0 fun (n : \u2115) (h : 0 \u2264 n) => le_refl (abv (f n))\n\ntheorem is_cau_geo_series {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] {\u03b2 : Type u_2} [field \u03b2] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] (x : \u03b2) (hx1 : abv x < 1) : is_cau_seq abv fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => x ^ m := sorry\n\ntheorem is_cau_geo_series_const {\u03b1 : Type u_1} [linear_ordered_field \u03b1] [archimedean \u03b1] (a : \u03b1) {x : \u03b1} (hx1 : abs x < 1) : is_cau_seq abs fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => a * x ^ n := sorry\n\ntheorem series_ratio_test {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1] [archimedean \u03b1] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {f : \u2115 \u2192 \u03b2} (n : \u2115) (r : \u03b1) (hr0 : 0 \u2264 r) (hr1 : r < 1) (h : \u2200 (m : \u2115), n \u2264 m \u2192 abv (f (Nat.succ m)) \u2264 r * abv (f m)) : is_cau_seq abv fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => f n := sorry\n\ntheorem sum_range_diag_flip {\u03b1 : Type u_1} [add_comm_monoid \u03b1] (n : \u2115) (f : \u2115 \u2192 \u2115 \u2192 \u03b1) : (finset.sum (finset.range n) fun (m : \u2115) => finset.sum (finset.range (m + 1)) fun (k : \u2115) => f k (m - k)) =\n  finset.sum (finset.range n) fun (m : \u2115) => finset.sum (finset.range (n - m)) fun (k : \u2115) => f m k := sorry\n\ntheorem sum_range_sub_sum_range {\u03b1 : Type u_1} [add_comm_group \u03b1] {f : \u2115 \u2192 \u03b1} {n : \u2115} {m : \u2115} (hnm : n \u2264 m) : ((finset.sum (finset.range m) fun (k : \u2115) => f k) - finset.sum (finset.range n) fun (k : \u2115) => f k) =\n  finset.sum (finset.filter (fun (k : \u2115) => n \u2264 k) (finset.range m)) fun (k : \u2115) => f k := sorry\n\ntheorem abv_sum_le_sum_abv {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {\u03b3 : Type u_3} (f : \u03b3 \u2192 \u03b2) (s : finset \u03b3) : abv (finset.sum s fun (k : \u03b3) => f k) \u2264 finset.sum s fun (k : \u03b3) => abv (f k) := sorry\n\ntheorem cauchy_product {\u03b1 : Type u_1} {\u03b2 : Type u_2} [ring \u03b2] [linear_ordered_field \u03b1] {abv : \u03b2 \u2192 \u03b1} [is_absolute_value abv] {a : \u2115 \u2192 \u03b2} {b : \u2115 \u2192 \u03b2} (ha : is_cau_seq abs fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => abv (a n)) (hb : is_cau_seq abv fun (m : \u2115) => finset.sum (finset.range m) fun (n : \u2115) => b n) (\u03b5 : \u03b1) (\u03b50 : 0 < \u03b5) : \u2203 (i : \u2115),\n  \u2200 (j : \u2115),\n    j \u2265 i \u2192\n      abv\n          (((finset.sum (finset.range j) fun (k : \u2115) => a k) * finset.sum (finset.range j) fun (n : \u2115) => b n) -\n            finset.sum (finset.range j)\n              fun (n : \u2115) => finset.sum (finset.range (n + 1)) fun (m : \u2115) => a m * b (n - m)) <\n        \u03b5 := sorry\n\nnamespace complex\n\n\ntheorem is_cau_abs_exp (z : \u2102) : is_cau_seq abs fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => abs (z ^ m / \u2191(nat.factorial m)) := sorry\n\ntheorem is_cau_exp (z : \u2102) : is_cau_seq abs fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => z ^ m / \u2191(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 : \u2102) : cau_seq \u2102 abs :=\n  { val := fun (n : \u2115) => finset.sum (finset.range n) fun (m : \u2115) => z ^ m / \u2191(nat.factorial m),\n    property := is_cau_exp z }\n\n/-- The complex exponential function, defined via its Taylor series -/\ndef exp (z : \u2102) : \u2102 :=\n  cau_seq.lim (exp' z)\n\n/-- The complex sine function, defined via `exp` -/\ndef sin (z : \u2102) : \u2102 :=\n  (exp (-z * I) - exp (z * I)) * I / bit0 1\n\n/-- The complex cosine function, defined via `exp` -/\ndef cos (z : \u2102) : \u2102 :=\n  (exp (z * I) + exp (-z * I)) / bit0 1\n\n/-- The complex tangent function, defined as `sin z / cos z` -/\ndef tan (z : \u2102) : \u2102 :=\n  sin z / cos z\n\n/-- The complex hyperbolic sine function, defined via `exp` -/\ndef sinh (z : \u2102) : \u2102 :=\n  (exp z - exp (-z)) / bit0 1\n\n/-- The complex hyperbolic cosine function, defined via `exp` -/\ndef cosh (z : \u2102) : \u2102 :=\n  (exp z + exp (-z)) / bit0 1\n\n/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/\ndef tanh (z : \u2102) : \u2102 :=\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 : \u211d) : \u211d :=\n  complex.re (complex.exp \u2191x)\n\n/-- The real sine function, defined as the real part of the complex sine -/\ndef sin (x : \u211d) : \u211d :=\n  complex.re (complex.sin \u2191x)\n\n/-- The real cosine function, defined as the real part of the complex cosine -/\ndef cos (x : \u211d) : \u211d :=\n  complex.re (complex.cos \u2191x)\n\n/-- The real tangent function, defined as the real part of the complex tangent -/\ndef tan (x : \u211d) : \u211d :=\n  complex.re (complex.tan \u2191x)\n\n/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/\ndef sinh (x : \u211d) : \u211d :=\n  complex.re (complex.sinh \u2191x)\n\n/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/\ndef cosh (x : \u211d) : \u211d :=\n  complex.re (complex.cosh \u2191x)\n\n/-- The real hypebolic tangent function, defined as the real part of\nthe complex hyperbolic tangent -/\ndef tanh (x : \u211d) : \u211d :=\n  complex.re (complex.tanh \u2191x)\n\nend real\n\n\nnamespace complex\n\n\n@[simp] theorem exp_zero : exp 0 = 1 := sorry\n\ntheorem exp_add (x : \u2102) (y : \u2102) : exp (x + y) = exp x * exp y := sorry\n\ntheorem exp_list_sum (l : List \u2102) : 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 \u2102) : 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 {\u03b1 : Type u_1} (s : finset \u03b1) (f : \u03b1 \u2192 \u2102) : exp (finset.sum s fun (x : \u03b1) => f x) = finset.prod s fun (x : \u03b1) => exp (f x) :=\n  monoid_hom.map_prod (monoid_hom.mk exp exp_zero exp_add) f s\n\ntheorem exp_nat_mul (x : \u2102) (n : \u2115) : exp (\u2191n * x) = exp x ^ n := sorry\n\ntheorem exp_ne_zero (x : \u2102) : exp x \u2260 0 := sorry\n\ntheorem exp_neg (x : \u2102) : exp (-x) = (exp x\u207b\u00b9) := sorry\n\ntheorem exp_sub (x : \u2102) (y : \u2102) : exp (x - y) = exp x / exp y := sorry\n\n@[simp] theorem exp_conj (x : \u2102) : exp (coe_fn conj x) = coe_fn conj (exp x) := sorry\n\n@[simp] theorem of_real_exp_of_real_re (x : \u211d) : \u2191(re (exp \u2191x)) = exp \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (exp \u2191x) = exp \u2191x)) (Eq.symm (exp_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (exp (coe_fn conj \u2191x) = exp \u2191x)) (conj_of_real x))) (Eq.refl (exp \u2191x))))\n\n@[simp] theorem of_real_exp (x : \u211d) : \u2191(real.exp x) = exp \u2191x :=\n  of_real_exp_of_real_re x\n\n@[simp] theorem exp_of_real_im (x : \u211d) : im (exp \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (exp \u2191x) = 0)) (Eq.symm (of_real_exp_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (exp \u2191x)) = 0)) (of_real_im (re (exp \u2191x))))) (Eq.refl 0))\n\ntheorem exp_of_real_re (x : \u211d) : re (exp \u2191x) = real.exp x :=\n  rfl\n\ntheorem two_sinh (x : \u2102) : bit0 1 * sinh x = exp x - exp (-x) :=\n  mul_div_cancel' (exp x - exp (-x)) two_ne_zero'\n\ntheorem two_cosh (x : \u2102) : 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 : \u2102) : sinh (-x) = -sinh x := sorry\n\ntheorem sinh_add (x : \u2102) (y : \u2102) : 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 : \u2102) : cosh (-x) = cosh x := sorry\n\ntheorem cosh_add (x : \u2102) (y : \u2102) : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := sorry\n\ntheorem sinh_sub (x : \u2102) (y : \u2102) : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := sorry\n\ntheorem cosh_sub (x : \u2102) (y : \u2102) : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := sorry\n\ntheorem sinh_conj (x : \u2102) : sinh (coe_fn conj x) = coe_fn conj (sinh x) := sorry\n\n@[simp] theorem of_real_sinh_of_real_re (x : \u211d) : \u2191(re (sinh \u2191x)) = sinh \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (sinh \u2191x) = sinh \u2191x)) (Eq.symm (sinh_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (sinh (coe_fn conj \u2191x) = sinh \u2191x)) (conj_of_real x))) (Eq.refl (sinh \u2191x))))\n\n@[simp] theorem of_real_sinh (x : \u211d) : \u2191(real.sinh x) = sinh \u2191x :=\n  of_real_sinh_of_real_re x\n\n@[simp] theorem sinh_of_real_im (x : \u211d) : im (sinh \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (sinh \u2191x) = 0)) (Eq.symm (of_real_sinh_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (sinh \u2191x)) = 0)) (of_real_im (re (sinh \u2191x))))) (Eq.refl 0))\n\ntheorem sinh_of_real_re (x : \u211d) : re (sinh \u2191x) = real.sinh x :=\n  rfl\n\ntheorem cosh_conj (x : \u2102) : cosh (coe_fn conj x) = coe_fn conj (cosh x) := sorry\n\n@[simp] theorem of_real_cosh_of_real_re (x : \u211d) : \u2191(re (cosh \u2191x)) = cosh \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (cosh \u2191x) = cosh \u2191x)) (Eq.symm (cosh_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (cosh (coe_fn conj \u2191x) = cosh \u2191x)) (conj_of_real x))) (Eq.refl (cosh \u2191x))))\n\n@[simp] theorem of_real_cosh (x : \u211d) : \u2191(real.cosh x) = cosh \u2191x :=\n  of_real_cosh_of_real_re x\n\n@[simp] theorem cosh_of_real_im (x : \u211d) : im (cosh \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (cosh \u2191x) = 0)) (Eq.symm (of_real_cosh_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (cosh \u2191x)) = 0)) (of_real_im (re (cosh \u2191x))))) (Eq.refl 0))\n\ntheorem cosh_of_real_re (x : \u211d) : re (cosh \u2191x) = real.cosh x :=\n  rfl\n\ntheorem tanh_eq_sinh_div_cosh (x : \u2102) : 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 : \u2102) : tanh (-x) = -tanh x := sorry\n\ntheorem tanh_conj (x : \u2102) : tanh (coe_fn conj x) = coe_fn conj (tanh x) := sorry\n\n@[simp] theorem of_real_tanh_of_real_re (x : \u211d) : \u2191(re (tanh \u2191x)) = tanh \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (tanh \u2191x) = tanh \u2191x)) (Eq.symm (tanh_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (tanh (coe_fn conj \u2191x) = tanh \u2191x)) (conj_of_real x))) (Eq.refl (tanh \u2191x))))\n\n@[simp] theorem of_real_tanh (x : \u211d) : \u2191(real.tanh x) = tanh \u2191x :=\n  of_real_tanh_of_real_re x\n\n@[simp] theorem tanh_of_real_im (x : \u211d) : im (tanh \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (tanh \u2191x) = 0)) (Eq.symm (of_real_tanh_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (tanh \u2191x)) = 0)) (of_real_im (re (tanh \u2191x))))) (Eq.refl 0))\n\ntheorem tanh_of_real_re (x : \u211d) : re (tanh \u2191x) = real.tanh x :=\n  rfl\n\ntheorem cosh_add_sinh (x : \u2102) : cosh x + sinh x = exp x := sorry\n\ntheorem sinh_add_cosh (x : \u2102) : 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 : \u2102) : cosh x - sinh x = exp (-x) := sorry\n\ntheorem cosh_sq_sub_sinh_sq (x : \u2102) : cosh x ^ bit0 1 - sinh x ^ bit0 1 = 1 := sorry\n\ntheorem cosh_square (x : \u2102) : cosh x ^ bit0 1 = sinh x ^ bit0 1 + 1 := sorry\n\ntheorem sinh_square (x : \u2102) : sinh x ^ bit0 1 = cosh x ^ bit0 1 - 1 := sorry\n\ntheorem cosh_two_mul (x : \u2102) : cosh (bit0 1 * x) = cosh x ^ bit0 1 + sinh x ^ bit0 1 := sorry\n\ntheorem sinh_two_mul (x : \u2102) : sinh (bit0 1 * x) = bit0 1 * sinh x * cosh x := sorry\n\ntheorem cosh_three_mul (x : \u2102) : cosh (bit1 1 * x) = bit0 (bit0 1) * cosh x ^ bit1 1 - bit1 1 * cosh x := sorry\n\ntheorem sinh_three_mul (x : \u2102) : 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 : \u2102) : sin (-x) = -sin x := sorry\n\ntheorem two_sin (x : \u2102) : 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 : \u2102) : 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 : \u2102) : sinh (x * I) = sin x * I := sorry\n\ntheorem cosh_mul_I (x : \u2102) : cosh (x * I) = cos x := sorry\n\ntheorem tanh_mul_I (x : \u2102) : tanh (x * I) = tan x * I := sorry\n\ntheorem cos_mul_I (x : \u2102) : cos (x * I) = cosh x := sorry\n\ntheorem sin_mul_I (x : \u2102) : sin (x * I) = sinh x * I := sorry\n\ntheorem tan_mul_I (x : \u2102) : tan (x * I) = tanh x * I := sorry\n\ntheorem sin_add (x : \u2102) (y : \u2102) : 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 : \u2102) : cos (-x) = cos x := sorry\n\ntheorem cos_add (x : \u2102) (y : \u2102) : cos (x + y) = cos x * cos y - sin x * sin y := sorry\n\ntheorem sin_sub (x : \u2102) (y : \u2102) : sin (x - y) = sin x * cos y - cos x * sin y := sorry\n\ntheorem cos_sub (x : \u2102) (y : \u2102) : cos (x - y) = cos x * cos y + sin x * sin y := sorry\n\ntheorem sin_add_mul_I (x : \u2102) (y : \u2102) : sin (x + y * I) = sin x * cosh y + cos x * sinh y * I := sorry\n\ntheorem sin_eq (z : \u2102) : sin z = sin \u2191(re z) * cosh \u2191(im z) + cos \u2191(re z) * sinh \u2191(im z) * I := sorry\n\ntheorem cos_add_mul_I (x : \u2102) (y : \u2102) : cos (x + y * I) = cos x * cosh y - sin x * sinh y * I := sorry\n\ntheorem cos_eq (z : \u2102) : cos z = cos \u2191(re z) * cosh \u2191(im z) - sin \u2191(re z) * sinh \u2191(im z) * I := sorry\n\ntheorem sin_sub_sin (x : \u2102) (y : \u2102) : sin x - sin y = bit0 1 * sin ((x - y) / bit0 1) * cos ((x + y) / bit0 1) := sorry\n\ntheorem cos_sub_cos (x : \u2102) (y : \u2102) : cos x - cos y = -bit0 1 * sin ((x + y) / bit0 1) * sin ((x - y) / bit0 1) := sorry\n\ntheorem cos_add_cos (x : \u2102) (y : \u2102) : cos x + cos y = bit0 1 * cos ((x + y) / bit0 1) * cos ((x - y) / bit0 1) := sorry\n\ntheorem sin_conj (x : \u2102) : sin (coe_fn conj x) = coe_fn conj (sin x) := sorry\n\n@[simp] theorem of_real_sin_of_real_re (x : \u211d) : \u2191(re (sin \u2191x)) = sin \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (sin \u2191x) = sin \u2191x)) (Eq.symm (sin_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (sin (coe_fn conj \u2191x) = sin \u2191x)) (conj_of_real x))) (Eq.refl (sin \u2191x))))\n\n@[simp] theorem of_real_sin (x : \u211d) : \u2191(real.sin x) = sin \u2191x :=\n  of_real_sin_of_real_re x\n\n@[simp] theorem sin_of_real_im (x : \u211d) : im (sin \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (sin \u2191x) = 0)) (Eq.symm (of_real_sin_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (sin \u2191x)) = 0)) (of_real_im (re (sin \u2191x))))) (Eq.refl 0))\n\ntheorem sin_of_real_re (x : \u211d) : re (sin \u2191x) = real.sin x :=\n  rfl\n\ntheorem cos_conj (x : \u2102) : cos (coe_fn conj x) = coe_fn conj (cos x) := sorry\n\n@[simp] theorem of_real_cos_of_real_re (x : \u211d) : \u2191(re (cos \u2191x)) = cos \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (cos \u2191x) = cos \u2191x)) (Eq.symm (cos_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (cos (coe_fn conj \u2191x) = cos \u2191x)) (conj_of_real x))) (Eq.refl (cos \u2191x))))\n\n@[simp] theorem of_real_cos (x : \u211d) : \u2191(real.cos x) = cos \u2191x :=\n  of_real_cos_of_real_re x\n\n@[simp] theorem cos_of_real_im (x : \u211d) : im (cos \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (cos \u2191x) = 0)) (Eq.symm (of_real_cos_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (cos \u2191x)) = 0)) (of_real_im (re (cos \u2191x))))) (Eq.refl 0))\n\ntheorem cos_of_real_re (x : \u211d) : re (cos \u2191x) = real.cos x :=\n  rfl\n\n@[simp] theorem tan_zero : tan 0 = 0 := sorry\n\ntheorem tan_eq_sin_div_cos (x : \u2102) : tan x = sin x / cos x :=\n  rfl\n\ntheorem tan_mul_cos {x : \u2102} (hx : cos x \u2260 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 : \u2102) : tan (-x) = -tan x := sorry\n\ntheorem tan_conj (x : \u2102) : tan (coe_fn conj x) = coe_fn conj (tan x) := sorry\n\n@[simp] theorem of_real_tan_of_real_re (x : \u211d) : \u2191(re (tan \u2191x)) = tan \u2191x :=\n  iff.mp eq_conj_iff_re\n    (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (tan \u2191x) = tan \u2191x)) (Eq.symm (tan_conj \u2191x))))\n      (eq.mpr (id (Eq._oldrec (Eq.refl (tan (coe_fn conj \u2191x) = tan \u2191x)) (conj_of_real x))) (Eq.refl (tan \u2191x))))\n\n@[simp] theorem of_real_tan (x : \u211d) : \u2191(real.tan x) = tan \u2191x :=\n  of_real_tan_of_real_re x\n\n@[simp] theorem tan_of_real_im (x : \u211d) : im (tan \u2191x) = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (im (tan \u2191x) = 0)) (Eq.symm (of_real_tan_of_real_re x))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (im \u2191(re (tan \u2191x)) = 0)) (of_real_im (re (tan \u2191x))))) (Eq.refl 0))\n\ntheorem tan_of_real_re (x : \u211d) : re (tan \u2191x) = real.tan x :=\n  rfl\n\ntheorem cos_add_sin_I (x : \u2102) : cos x + sin x * I = exp (x * I) := sorry\n\ntheorem cos_sub_sin_I (x : \u2102) : cos x - sin x * I = exp (-x * I) := sorry\n\n@[simp] theorem sin_sq_add_cos_sq (x : \u2102) : sin x ^ bit0 1 + cos x ^ bit0 1 = 1 := sorry\n\n@[simp] theorem cos_sq_add_sin_sq (x : \u2102) : 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 : \u2102) : cos (bit0 1 * x) = cos x ^ bit0 1 - sin x ^ bit0 1 := sorry\n\ntheorem cos_two_mul (x : \u2102) : cos (bit0 1 * x) = bit0 1 * cos x ^ bit0 1 - 1 := sorry\n\ntheorem sin_two_mul (x : \u2102) : sin (bit0 1 * x) = bit0 1 * sin x * cos x := sorry\n\ntheorem cos_square (x : \u2102) : cos x ^ bit0 1 = 1 / bit0 1 + cos (bit0 1 * x) / bit0 1 := sorry\n\ntheorem cos_square' (x : \u2102) : cos x ^ bit0 1 = 1 - sin x ^ bit0 1 := sorry\n\ntheorem sin_square (x : \u2102) : sin x ^ bit0 1 = 1 - cos x ^ bit0 1 := sorry\n\ntheorem inv_one_add_tan_sq {x : \u2102} (hx : cos x \u2260 0) : 1 + tan x ^ bit0 1\u207b\u00b9 = cos x ^ bit0 1 := sorry\n\ntheorem tan_sq_div_one_add_tan_sq {x : \u2102} (hx : cos x \u2260 0) : tan x ^ bit0 1 / (1 + tan x ^ bit0 1) = sin x ^ bit0 1 := sorry\n\ntheorem cos_three_mul (x : \u2102) : cos (bit1 1 * x) = bit0 (bit0 1) * cos x ^ bit1 1 - bit1 1 * cos x := sorry\n\ntheorem sin_three_mul (x : \u2102) : sin (bit1 1 * x) = bit1 1 * sin x - bit0 (bit0 1) * sin x ^ bit1 1 := sorry\n\ntheorem exp_mul_I (x : \u2102) : exp (x * I) = cos x + sin x * I :=\n  Eq.symm (cos_add_sin_I x)\n\ntheorem exp_add_mul_I (x : \u2102) (y : \u2102) : 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 : \u2102) : exp x = exp \u2191(re x) * (cos \u2191(im x) + sin \u2191(im x) * I) := sorry\n\n/-- De Moivre's formula -/\ntheorem cos_add_sin_mul_I_pow (n : \u2115) (z : \u2102) : (cos z + sin z * I) ^ n = cos (\u2191n * z) + sin (\u2191n * 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 : \u211d) (y : \u211d) : exp (x + y) = exp x * exp y := sorry\n\ntheorem exp_list_sum (l : List \u211d) : 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 \u211d) : 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 {\u03b1 : Type u_1} (s : finset \u03b1) (f : \u03b1 \u2192 \u211d) : exp (finset.sum s fun (x : \u03b1) => f x) = finset.prod s fun (x : \u03b1) => exp (f x) :=\n  monoid_hom.map_prod (monoid_hom.mk exp exp_zero exp_add) f s\n\ntheorem exp_nat_mul (x : \u211d) (n : \u2115) : exp (\u2191n * x) = exp x ^ n := sorry\n\ntheorem exp_ne_zero (x : \u211d) : exp x \u2260 0 := sorry\n\ntheorem exp_neg (x : \u211d) : exp (-x) = (exp x\u207b\u00b9) := sorry\n\ntheorem exp_sub (x : \u211d) (y : \u211d) : 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 : \u211d) : sin (-x) = -sin x := sorry\n\ntheorem sin_add (x : \u211d) (y : \u211d) : 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 : \u211d) : cos (-x) = cos x := sorry\n\ntheorem cos_add (x : \u211d) (y : \u211d) : cos (x + y) = cos x * cos y - sin x * sin y := sorry\n\ntheorem sin_sub (x : \u211d) (y : \u211d) : sin (x - y) = sin x * cos y - cos x * sin y := sorry\n\ntheorem cos_sub (x : \u211d) (y : \u211d) : cos (x - y) = cos x * cos y + sin x * sin y := sorry\n\ntheorem sin_sub_sin (x : \u211d) (y : \u211d) : sin x - sin y = bit0 1 * sin ((x - y) / bit0 1) * cos ((x + y) / bit0 1) := sorry\n\ntheorem cos_sub_cos (x : \u211d) (y : \u211d) : cos x - cos y = -bit0 1 * sin ((x + y) / bit0 1) * sin ((x - y) / bit0 1) := sorry\n\ntheorem cos_add_cos (x : \u211d) (y : \u211d) : 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 : \u211d) : tan x = sin x / cos x := sorry\n\ntheorem tan_mul_cos {x : \u211d} (hx : cos x \u2260 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 : \u211d) : tan (-x) = -tan x := sorry\n\n@[simp] theorem sin_sq_add_cos_sq (x : \u211d) : sin x ^ bit0 1 + cos x ^ bit0 1 = 1 := sorry\n\n@[simp] theorem cos_sq_add_sin_sq (x : \u211d) : 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 : \u211d) : sin x ^ bit0 1 \u2264 1 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (sin x ^ bit0 1 \u2264 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 : \u211d) : cos x ^ bit0 1 \u2264 1 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (cos x ^ bit0 1 \u2264 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 : \u211d) : abs (sin x) \u2264 1 := sorry\n\ntheorem abs_cos_le_one (x : \u211d) : abs (cos x) \u2264 1 := sorry\n\ntheorem sin_le_one (x : \u211d) : sin x \u2264 1 :=\n  and.right (iff.mp abs_le (abs_sin_le_one x))\n\ntheorem cos_le_one (x : \u211d) : cos x \u2264 1 :=\n  and.right (iff.mp abs_le (abs_cos_le_one x))\n\ntheorem neg_one_le_sin (x : \u211d) : -1 \u2264 sin x :=\n  and.left (iff.mp abs_le (abs_sin_le_one x))\n\ntheorem neg_one_le_cos (x : \u211d) : -1 \u2264 cos x :=\n  and.left (iff.mp abs_le (abs_cos_le_one x))\n\ntheorem cos_two_mul (x : \u211d) : cos (bit0 1 * x) = bit0 1 * cos x ^ bit0 1 - 1 := sorry\n\ntheorem cos_two_mul' (x : \u211d) : cos (bit0 1 * x) = cos x ^ bit0 1 - sin x ^ bit0 1 := sorry\n\ntheorem sin_two_mul (x : \u211d) : sin (bit0 1 * x) = bit0 1 * sin x * cos x := sorry\n\ntheorem cos_square (x : \u211d) : cos x ^ bit0 1 = 1 / bit0 1 + cos (bit0 1 * x) / bit0 1 := sorry\n\ntheorem cos_square' (x : \u211d) : cos x ^ bit0 1 = 1 - sin x ^ bit0 1 := sorry\n\ntheorem sin_square (x : \u211d) : 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 : \u211d} (hx : cos x \u2260 0) : 1 + tan x ^ bit0 1\u207b\u00b9 = cos x ^ bit0 1 := sorry\n\ntheorem tan_sq_div_one_add_tan_sq {x : \u211d} (hx : cos x \u2260 0) : tan x ^ bit0 1 / (1 + tan x ^ bit0 1) = sin x ^ bit0 1 := sorry\n\ntheorem inv_sqrt_one_add_tan_sq {x : \u211d} (hx : 0 < cos x) : sqrt (1 + tan x ^ bit0 1)\u207b\u00b9 = cos x := sorry\n\ntheorem tan_div_sqrt_one_add_tan_sq {x : \u211d} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ bit0 1) = sin x := sorry\n\ntheorem cos_three_mul (x : \u211d) : cos (bit1 1 * x) = bit0 (bit0 1) * cos x ^ bit1 1 - bit1 1 * cos x := sorry\n\ntheorem sin_three_mul (x : \u211d) : 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 : \u211d) : 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 : \u211d) : sinh (-x) = -sinh x := sorry\n\ntheorem sinh_add (x : \u211d) (y : \u211d) : 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 : \u211d) : 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 : \u211d) : cosh (-x) = cosh x := sorry\n\ntheorem cosh_add (x : \u211d) (y : \u211d) : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := sorry\n\ntheorem sinh_sub (x : \u211d) (y : \u211d) : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := sorry\n\ntheorem cosh_sub (x : \u211d) (y : \u211d) : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := sorry\n\ntheorem tanh_eq_sinh_div_cosh (x : \u211d) : tanh x = sinh x / cosh x := sorry\n\n@[simp] theorem tanh_zero : tanh 0 = 0 := sorry\n\n@[simp] theorem tanh_neg (x : \u211d) : tanh (-x) = -tanh x := sorry\n\ntheorem cosh_add_sinh (x : \u211d) : cosh x + sinh x = exp x := sorry\n\ntheorem sinh_add_cosh (x : \u211d) : sinh x + cosh x = exp x := sorry\n\ntheorem cosh_sq_sub_sinh_sq (x : \u211d) : cosh x ^ bit0 1 - sinh x ^ bit0 1 = 1 := sorry\n\ntheorem cosh_square (x : \u211d) : cosh x ^ bit0 1 = sinh x ^ bit0 1 + 1 := sorry\n\ntheorem sinh_square (x : \u211d) : sinh x ^ bit0 1 = cosh x ^ bit0 1 - 1 := sorry\n\ntheorem cosh_two_mul (x : \u211d) : cosh (bit0 1 * x) = cosh x ^ bit0 1 + sinh x ^ bit0 1 := sorry\n\ntheorem sinh_two_mul (x : \u211d) : sinh (bit0 1 * x) = bit0 1 * sinh x * cosh x := sorry\n\ntheorem cosh_three_mul (x : \u211d) : cosh (bit1 1 * x) = bit0 (bit0 1) * cosh x ^ bit1 1 - bit1 1 * cosh x := sorry\n\ntheorem sinh_three_mul (x : \u211d) : sinh (bit1 1 * x) = bit0 (bit0 1) * sinh x ^ bit1 1 + bit1 1 * sinh x := sorry\n\n/- TODO make this private and prove \u2200 x -/\n\ntheorem add_one_le_exp_of_nonneg {x : \u211d} (hx : 0 \u2264 x) : x + 1 \u2264 exp x := sorry\n\ntheorem one_le_exp {x : \u211d} (hx : 0 \u2264 x) : 1 \u2264 exp x := sorry\n\ntheorem exp_pos (x : \u211d) : 0 < exp x := sorry\n\n@[simp] theorem abs_exp (x : \u211d) : 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 : \u211d} {y : \u211d} : x \u2264 y \u2192 exp x \u2264 exp y :=\n  strict_mono.monotone exp_strict_mono\n\n@[simp] theorem exp_lt_exp {x : \u211d} {y : \u211d} : exp x < exp y \u2194 x < y :=\n  strict_mono.lt_iff_lt exp_strict_mono\n\n@[simp] theorem exp_le_exp {x : \u211d} {y : \u211d} : exp x \u2264 exp y \u2194 x \u2264 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 : \u211d} {y : \u211d} : exp x = exp y \u2194 x = y :=\n  function.injective.eq_iff exp_injective\n\n@[simp] theorem exp_eq_one_iff (x : \u211d) : exp x = 1 \u2194 x = 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (exp x = 1 \u2194 x = 0)) (Eq.symm exp_zero)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (exp x = exp 0 \u2194 x = 0)) (propext (function.injective.eq_iff exp_injective))))\n      (iff.refl (x = 0)))\n\n@[simp] theorem one_lt_exp_iff {x : \u211d} : 1 < exp x \u2194 0 < x :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (1 < exp x \u2194 0 < x)) (Eq.symm exp_zero)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (exp 0 < exp x \u2194 0 < x)) (propext exp_lt_exp))) (iff.refl (0 < x)))\n\n@[simp] theorem exp_lt_one_iff {x : \u211d} : exp x < 1 \u2194 x < 0 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (exp x < 1 \u2194 x < 0)) (Eq.symm exp_zero)))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (exp x < exp 0 \u2194 x < 0)) (propext exp_lt_exp))) (iff.refl (x < 0)))\n\n@[simp] theorem exp_le_one_iff {x : \u211d} : exp x \u2264 1 \u2194 x \u2264 0 :=\n  exp_zero \u25b8 exp_le_exp\n\n@[simp] theorem one_le_exp_iff {x : \u211d} : 1 \u2264 exp x \u2194 0 \u2264 x :=\n  exp_zero \u25b8 exp_le_exp\n\n/-- `real.cosh` is always positive -/\ntheorem cosh_pos (x : \u211d) : 0 < cosh x :=\n  Eq.symm (cosh_eq x) \u25b8 half_pos (add_pos (exp_pos x) (exp_pos (-x)))\n\nend real\n\n\nnamespace complex\n\n\ntheorem sum_div_factorial_le {\u03b1 : Type u_1} [linear_ordered_field \u03b1] (n : \u2115) (j : \u2115) (hn : 0 < n) : (finset.sum (finset.filter (fun (k : \u2115) => n \u2264 k) (finset.range j)) fun (m : \u2115) => 1 / \u2191(nat.factorial m)) \u2264\n  \u2191(Nat.succ n) * (\u2191(nat.factorial n) * \u2191n\u207b\u00b9) := sorry\n\ntheorem exp_bound {x : \u2102} (hx : abs x \u2264 1) {n : \u2115} (hn : 0 < n) : abs (exp x - finset.sum (finset.range n) fun (m : \u2115) => x ^ m / \u2191(nat.factorial m)) \u2264\n  abs x ^ n * (\u2191(Nat.succ n) * (\u2191(nat.factorial n) * \u2191n\u207b\u00b9)) := sorry\n\ntheorem abs_exp_sub_one_le {x : \u2102} (hx : abs x \u2264 1) : abs (exp x - 1) \u2264 bit0 1 * abs x := sorry\n\ntheorem abs_exp_sub_one_sub_id_le {x : \u2102} (hx : abs x \u2264 1) : abs (exp x - 1 - x) \u2264 abs x ^ bit0 1 := sorry\n\nend complex\n\n\nnamespace real\n\n\ntheorem exp_bound {x : \u211d} (hx : abs x \u2264 1) {n : \u2115} (hn : 0 < n) : abs (exp x - finset.sum (finset.range n) fun (m : \u2115) => x ^ m / \u2191(nat.factorial m)) \u2264\n  abs x ^ n * (\u2191(Nat.succ n) / (\u2191(nat.factorial n) * \u2191n)) := 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 \u27f6 exp x` as `n \u27f6 \u221e`,\nfor any `r`. -/\ndef exp_near (n : \u2115) (x : \u211d) (r : \u211d) : \u211d :=\n  (finset.sum (finset.range n) fun (m : \u2115) => x ^ m / \u2191(nat.factorial m)) + x ^ n / \u2191(nat.factorial n) * r\n\n@[simp] theorem exp_near_zero (x : \u211d) (r : \u211d) : exp_near 0 x r = r := sorry\n\n@[simp] theorem exp_near_succ (n : \u2115) (x : \u211d) (r : \u211d) : exp_near (n + 1) x r = exp_near n x (1 + x / (\u2191n + 1) * r) := sorry\n\ntheorem exp_near_sub (n : \u2115) (x : \u211d) (r\u2081 : \u211d) (r\u2082 : \u211d) : exp_near n x r\u2081 - exp_near n x r\u2082 = x ^ n / \u2191(nat.factorial n) * (r\u2081 - r\u2082) := sorry\n\ntheorem exp_approx_end (n : \u2115) (m : \u2115) (x : \u211d) (e\u2081 : n + 1 = m) (h : abs x \u2264 1) : abs (exp x - exp_near m x 0) \u2264 abs x ^ m / \u2191(nat.factorial m) * ((\u2191m + 1) / \u2191m) := sorry\n\ntheorem exp_approx_succ {n : \u2115} {x : \u211d} {a\u2081 : \u211d} {b\u2081 : \u211d} (m : \u2115) (e\u2081 : n + 1 = m) (a\u2082 : \u211d) (b\u2082 : \u211d) (e : abs (1 + x / \u2191m * a\u2082 - a\u2081) \u2264 b\u2081 - abs x / \u2191m * b\u2082) (h : abs (exp x - exp_near m x a\u2082) \u2264 abs x ^ m / \u2191(nat.factorial m) * b\u2082) : abs (exp x - exp_near n x a\u2081) \u2264 abs x ^ n / \u2191(nat.factorial n) * b\u2081 := sorry\n\ntheorem exp_approx_end' {n : \u2115} {x : \u211d} {a : \u211d} {b : \u211d} (m : \u2115) (e\u2081 : n + 1 = m) (rm : \u211d) (er : \u2191m = rm) (h : abs x \u2264 1) (e : abs (1 - a) \u2264 b - abs x / rm * ((rm + 1) / rm)) : abs (exp x - exp_near n x a) \u2264 abs x ^ n / \u2191(nat.factorial n) * b := sorry\n\ntheorem exp_1_approx_succ_eq {n : \u2115} {a\u2081 : \u211d} {b\u2081 : \u211d} {m : \u2115} (en : n + 1 = m) {rm : \u211d} (er : \u2191m = rm) (h : abs (exp 1 - exp_near m 1 ((a\u2081 - 1) * rm)) \u2264 abs 1 ^ m / \u2191(nat.factorial m) * (b\u2081 * rm)) : abs (exp 1 - exp_near n 1 a\u2081) \u2264 abs 1 ^ n / \u2191(nat.factorial n) * b\u2081 := sorry\n\ntheorem exp_approx_start (x : \u211d) (a : \u211d) (b : \u211d) (h : abs (exp x - exp_near 0 x a) \u2264 abs x ^ 0 / \u2191(nat.factorial 0) * b) : abs (exp x - a) \u2264 b := sorry\n\ntheorem cos_bound {x : \u211d} (hx : abs x \u2264 1) : abs (cos x - (1 - x ^ bit0 1 / bit0 1)) \u2264\n  abs x ^ bit0 (bit0 1) * (bit1 (bit0 1) / bit0 (bit0 (bit0 (bit0 (bit0 (bit1 1)))))) := sorry\n\ntheorem sin_bound {x : \u211d} (hx : abs x \u2264 1) : abs (sin x - (x - x ^ bit1 1 / bit0 (bit1 1))) \u2264\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 : \u211d} (hx : abs x \u2264 1) : 0 < cos x := sorry\n\ntheorem sin_pos_of_pos_of_le_one {x : \u211d} (hx0 : 0 < x) (hx : x \u2264 1) : 0 < sin x := sorry\n\ntheorem sin_pos_of_pos_of_le_two {x : \u211d} (hx0 : 0 < x) (hx : x \u2264 bit0 1) : 0 < sin x := sorry\n\ntheorem cos_one_le : cos 1 \u2264 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 : \u211d) : abs (cos \u2191x + sin \u2191x * I) = 1 := sorry\n\ntheorem abs_exp_eq_iff_re_eq {x : \u2102} {y : \u2102} : abs (exp x) = abs (exp y) \u2194 re x = re y := sorry\n\n@[simp] theorem abs_exp_of_real (x : \u211d) : abs (exp \u2191x) = real.exp x :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (abs (exp \u2191x) = 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\u2081 :=\n(carrier : Type u)\n[str : pseudo_normed_group carrier]\n(exhaustive' : \u2200 x : carrier, \u2203 c : nnreal,\n  x \u2208 pseudo_normed_group.filtration carrier c)\n\nnamespace PseuNormGrp\u2081\n\ninstance : has_coe_to_sort PseuNormGrp\u2081.{u} (Type u) := \u27e8carrier\u27e9\ninstance (M : PseuNormGrp\u2081.{u}) : pseudo_normed_group M := M.str\n\nlemma exhaustive (M : PseuNormGrp\u2081) (x : M) :\n  \u2203 c, x \u2208 pseudo_normed_group.filtration M c := M.exhaustive' x\n\ninstance : category PseuNormGrp\u2081.{u} :=\n{ hom := \u03bb A B, strict_pseudo_normed_group_hom A B,\n  id := \u03bb A, strict_pseudo_normed_group_hom.id A,\n  comp := \u03bb A B C f g, f.comp g }\n\n@[simp]\nlemma id_apply (M : PseuNormGrp\u2081) (x : M) : (\ud835\udfd9 M : M \u27f6 M) x = x := rfl\n\n@[simp]\nlemma comp_apply {A B C : PseuNormGrp\u2081} (f : A \u27f6 B) (g : B \u27f6 C) (a : A) :\n  (f \u226b g) a = g (f a) := rfl\n\ndef to_Ab : PseuNormGrp\u2081.{u} \u2964 Ab.{u} :=\n{ obj := \u03bb M, AddCommGroup.of M,\n  map := \u03bb M N f, f.to_add_monoid_hom }\n\nvariable {K : J \u2964 PseuNormGrp\u2081.{u}}\nvariable (C : limits.limit_cone (K \u22d9 to_Ab))\n\ndef bounded_elements : add_subgroup C.cone.X :=\n{ carrier := { x | \u2203 c, \u2200 j, C.cone.\u03c0.app j x \u2208 pseudo_normed_group.filtration (K.obj j) c },\n  zero_mem' := \u27e80, \u03bb j, by { simp, apply pseudo_normed_group.zero_mem_filtration } \u27e9,\n  add_mem' := \u03bb a b ha hb, begin\n    obtain \u27e8c,hc\u27e9 := ha,\n    obtain \u27e8d,hd\u27e9 := 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' := \u03bb a ha, begin\n    obtain \u27e8c,hc\u27e9 := 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 | \u2200 j, C.cone.\u03c0.app j x \u2208 pseudo_normed_group.filtration (K.obj j) c }\n\ndef bounded_elements.filt_incl (c : nnreal) :\n  bounded_elements.filt C c \u2192 bounded_elements C :=\n\u03bb x, \u27e8x, c, x.2\u27e9\n\ndef bounded_elements.filtration (c : nnreal) : set (bounded_elements C) :=\nset.range (bounded_elements.filt_incl _ c)\n\ndef bounded_cone_point : PseuNormGrp\u2081 :=\n{ carrier := bounded_elements C,\n  str :=\n  { filtration := bounded_elements.filtration _,\n    filtration_mono := begin\n      intros c\u2081 c\u2082 h x hx,\n      obtain \u27e8t,rfl\u27e9 := hx, refine \u27e8\u27e8t,_\u27e9,rfl\u27e9, intros i,\n      apply pseudo_normed_group.filtration_mono h, apply t.2,\n    end,\n    zero_mem_filtration := begin\n      intros c, refine \u27e8\u27e80,\u03bb i, _\u27e9,rfl\u27e9, simp,\n        apply pseudo_normed_group.zero_mem_filtration\n    end,\n    neg_mem_filtration := begin\n      intros c x hx,\n      obtain \u27e8t,rfl\u27e9 := hx, refine \u27e8\u27e8-t, \u03bb i, _\u27e9, rfl\u27e9, simp,\n      apply pseudo_normed_group.neg_mem_filtration, apply t.2\n    end,\n    add_mem_filtration := begin\n      intros c\u2081 c\u2082 x\u2081 x\u2082 h\u2081 h\u2082,\n      obtain \u27e8t\u2081,rfl\u27e9 := h\u2081, obtain \u27e8t\u2082,rfl\u27e9 := h\u2082,\n      refine \u27e8\u27e8t\u2081 + t\u2082, \u03bb i, _\u27e9, rfl\u27e9, simp,\n      apply pseudo_normed_group.add_mem_filtration, apply t\u2081.2, apply t\u2082.2,\n    end },\n    exhaustive' := begin\n      intros m,\n      obtain \u27e8c,hc\u27e9 := m.2,\n      refine \u27e8c,\u27e8m.1, hc\u27e9, by { ext, refl }\u27e9,\n    end }\n\ndef bounded_cone : cone K :=\n{ X := bounded_cone_point C,\n  \u03c0 :=\n  { app := \u03bb j,\n    { to_fun := \u03bb x, C.cone.\u03c0.app _ x.1,\n      map_zero' := by simp,\n      map_add' := \u03bb x y, by simp,\n      strict' := begin\n        rintros c x \u27e8x,rfl\u27e9,\n        apply x.2,\n      end },\n    naturality' := begin\n      intros i j f,\n      ext,\n      dsimp,\n      rw \u2190 C.cone.w f,\n      refl,\n    end } }\n\ndef bounded_cone_lift (S : cone K) : S.X \u27f6 bounded_cone_point C :=\n{ to_fun := \u03bb x, \u27e8C.2.lift (to_Ab.map_cone S) x, begin\n    obtain \u27e8c,hc\u27e9 := S.X.exhaustive x,\n    use c,\n    intros j,\n    rw [\u2190 Ab.comp_apply, C.2.fac],\n    apply (S.\u03c0.app j).strict,\n    exact hc,\n  end\u27e9,\n  map_zero' := by { ext, simp },\n  map_add' := \u03bb x y, by { ext, simp },\n  strict' := begin\n    intros c x hx,\n    refine \u27e8\u27e8_, \u03bb j, _\u27e9,rfl\u27e9,\n    erw [\u2190 Ab.comp_apply, C.2.fac],\n    apply (S.\u03c0.app j).strict,\n    exact hx,\n  end }\n\ndef bounded_cone_is_limit : is_limit (bounded_cone C) :=\n{ lift := \u03bb S, bounded_cone_lift C S,\n  fac' := begin\n    intros S j,\n    ext,\n    dsimp [bounded_cone_lift, bounded_cone],\n    rw [\u2190 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 [\u2190 Ab.comp_apply, C.2.fac],\n    dsimp,\n    rw \u2190 hm,\n    refl,\n  end }\n\ninstance : has_limits PseuNormGrp\u2081 :=\nbegin\n  constructor, introsI J hJ, constructor, intros K,\n  exact has_limit.mk \u27e8_, bounded_cone_is_limit \u27e8_,limit.is_limit _\u27e9\u27e9,\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 \u2208 pseudo_normed_group.filtration C.X c \u2194\n  (\u2200 j : J, C.\u03c0.app j x \u2208 pseudo_normed_group.filtration (K.obj j) c) :=\nbegin\n  split,\n  { intros h j,\n    exact (C.\u03c0.app j).strict h },\n  { intros h,\n    let E := bounded_cone \u27e8_, Ab.explicit_limit_cone_is_limit.{u u} _\u27e9,\n    let e : C \u2245 E := hC.unique_up_to_iso (bounded_cone_is_limit _),\n    let eX : C.X \u2245 E.X := (cones.forget _).map_iso e,\n    let w := eX.hom x,\n    have hw : \u2200 j, E.\u03c0.app j w \u2208 filtration (K.obj j) c,\n    { intros j,\n      dsimp only [w],\n      change (eX.hom \u226b E.\u03c0.app _) _ \u2208 _,\n      dsimp only [eX, functor.map_iso, cones.forget],\n      convert h j,\n      simp },\n    suffices : w \u2208 filtration E.X c,\n    { convert eX.inv.strict this,\n      change _ = (eX.hom \u226b eX.inv) x,\n      rw iso.hom_inv_id,\n      refl },\n    refine \u27e8\u27e8_,hw\u27e9,rfl\u27e9 }\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 \u2192 filtration N c :=\n\u03bb x, \u27e8f x, f.strict x.2\u27e9\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 \u2218 f.level c := by { ext, refl }\n\n@[simps]\ndef level : nnreal \u2964 PseuNormGrp\u2081.{u} \u2964 Type u :=\n{ obj := \u03bb c,\n  { obj := \u03bb M, filtration M c,\n    map := \u03bb X Y f, f.level _,\n    map_id' := \u03bb M, strict_pseudo_normed_group_hom.level_id M _,\n    map_comp' := \u03bb M N L f g, f.level_comp g c },\n  map := \u03bb c\u2081 c\u2082 h,\n  { app := \u03bb M, pseudo_normed_group.cast_le' h.le } } .\n\nlemma level_map {X Y : PseuNormGrp\u2081} (f : X \u27f6 Y) (c) : (level.obj c).map f = f.level _ := rfl\n\nlemma level_map' {X Y : PseuNormGrp\u2081} (f : X \u27f6 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 \u22d9 level.obj c).sections :=\n{ val := \u03bb j,\n  { val := C.cone.\u03c0.app j t.1.1,\n    property := begin\n      obtain \u27e8w,hw\u27e9 := t.2,\n      apply_fun (\u03bb e, e.val) at hw,\n      rw \u2190 hw,\n      apply w.2\n    end },\n  property := begin\n    intros i j f,\n    ext,\n    dsimp,\n    rw \u2190 C.cone.w f,\n    refl,\n  end }\n\ndef level_cone_iso_inv (c) (t : (K \u22d9 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} _) \u27e8\u03bb j, (t.1 j).1, begin\n      intros i j f,\n      dsimp,\n      change _ = (t.val _).val,\n      rw \u2190 t.2 f,\n      refl,\n    end\u27e9,\n    property := begin\n      use c,\n      intros j,\n      rw [\u2190 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 \u27e8\u27e8_,_\u27e9,rfl\u27e9,\n    intros j,\n    dsimp,\n    rw [\u2190 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) \u2245 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 [\u2190 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 [\u2190 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 \u27e8_, Ab.explicit_limit_cone_is_limit _\u27e9),\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 \u27f6 level.obj.{u} c :=\n{ app := \u03bb 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\u2081\n\nnamespace CompHausFiltPseuNormGrp\u2081\n\n@[simp]\nlemma id_apply {A : CompHausFiltPseuNormGrp\u2081} (a : A) : (\ud835\udfd9 A : A \u27f6 A) a = a := rfl\n\n@[simp]\nlemma comp_apply {A B C : CompHausFiltPseuNormGrp\u2081} (f : A \u27f6 B) (g : B \u27f6 C) (a : A) :\n  (f \u226b g) a = g (f a) := rfl\n\ndef to_PNG\u2081 :\n  CompHausFiltPseuNormGrp\u2081.{u} \u2964 PseuNormGrp\u2081.{u} :=\n{ obj := \u03bb M,\n  { carrier := M,\n    exhaustive' := M.exhaustive },\n  map := \u03bb X Y f, { strict' := \u03bb c x h, f.strict h .. f.to_add_monoid_hom } }\n\ninstance : faithful to_PNG\u2081.{u} := faithful.mk $\nbegin\n  intros X Y f g h,\n  ext,\n  apply_fun (\u03bb e, e x) at h,\n  exact h\nend\n\nvariable {K : J \u2964 CompHausFiltPseuNormGrp\u2081.{u}}\nvariable (C : limits.limit_cone ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab))\n\ndef filtration_equiv (c : nnreal) :\n  pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\n  \u2243 (CompHaus.limit_cone.{u u} (K \u22d9 level.obj c)).X :=\n((cones.forget _).map_iso (PseuNormGrp\u2081.level_cone_iso C c)).to_equiv\n\ninstance (c) :\n  topological_space (pseudo_normed_group.filtration (PseuNormGrp\u2081.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\u2081.bounded_cone_point C) c\n  \u2243\u209c (CompHaus.limit_cone.{u u} (K \u22d9 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) := \u27e8rfl\u27e9,\n  rw this.is_open_iff at hU,\n  obtain \u27e8U,hU,rfl\u27e9 := hU,\n  simpa,\nend\n\ninstance (c) : t2_space\n  (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.t2_space\n\ninstance (c) : compact_space\n  (pseudo_normed_group.filtration (PseuNormGrp\u2081.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\u2081.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.totally_disconnected_space\n-/\n\ndef level_\u03c0 (j c) : pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c \u2192\n  pseudo_normed_group.filtration (K.obj j) c :=\n(PseuNormGrp\u2081.level.obj c).map ((PseuNormGrp\u2081.bounded_cone C).\u03c0.app j)\n\nlemma level_\u03c0_continuous (j c) : continuous (level_\u03c0 C j c) :=\nbegin\n  have : level_\u03c0 C j c \u2218 (filtration_homeo C c).symm =\n    (CompHaus.limit_cone.{u u} _).\u03c0.app j,\n  { ext,\n    change (C.is_limit.lift _ \u226b C.cone.\u03c0.app j) _ = _,\n    rw C.is_limit.fac,\n    refl },\n  suffices : continuous (level_\u03c0 C j c \u2218 (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 \u2964 CompHausFiltPseuNormGrp\u2081}\n  (C : category_theory.limits.limit_cone\n         ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab)) :\n  \u2200 (c\u2081 c\u2082 : nnreal), continuous\n  (pseudo_normed_group.add' :\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u00d7\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) (c\u2081 + c\u2082))) :=\nbegin\n  intros c\u2081 c\u2082,\n  let g : (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u00d7\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) (c\u2081 + c\u2082)) :=\n    pseudo_normed_group.add',\n  change continuous g,\n  suffices : continuous ((filtration_homeo C _) \u2218 g), by simpa using this,\n  apply continuous.subtype_mk,\n  apply continuous_pi,\n  intros j,\n  let e := pseudo_normed_group.add' \u2218 (prod.map (level_\u03c0 C j c\u2081) (level_\u03c0 C j c\u2082)),\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_\u03c0_continuous,\n    apply level_\u03c0_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 \u2964 CompHausFiltPseuNormGrp\u2081}\n  (C : category_theory.limits.limit_cone\n         ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab)) :\n  \u2200 (c : nnreal), continuous\n  (pseudo_normed_group.neg' :\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c)) :=\nbegin\n  intros c,\n  let g : (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) :=\n    pseudo_normed_group.neg',\n  change continuous g,\n  suffices : continuous ((filtration_homeo C c) \u2218 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' \u2218 level_\u03c0 C j c,\n  have he : continuous e,\n  { apply continuous.comp,\n    apply comphaus_filtered_pseudo_normed_group.continuous_neg',\n    apply level_\u03c0_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 \u2964 CompHausFiltPseuNormGrp\u2081}\n  (C : category_theory.limits.limit_cone\n         ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab)) :\n  \u2200 (c\u2081 c\u2082 : nnreal) (h : c\u2081 \u2264 c\u2082), continuous\n  (pseudo_normed_group.cast_le' h :\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082)) :=\nbegin\n  intros c\u2081 c\u2082 h,\n  let g : (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082) :=\n    pseudo_normed_group.cast_le' h,\n  change continuous g,\n  suffices : continuous ((filtration_homeo C _) \u2218 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 \u2218 level_\u03c0 C j c\u2081,\n  have he : continuous e,\n  { apply continuous.comp,\n    haveI : fact (c\u2081 \u2264 c\u2082) := \u27e8h\u27e9,\n    apply comphaus_filtered_pseudo_normed_group.continuous_cast_le,\n    apply level_\u03c0_continuous },\n  exact he,\nend\n\ndef bounded_cone_point : CompHausFiltPseuNormGrp\u2081 :=\n{ M := PseuNormGrp\u2081.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 := \u03bb _ _ h, bounded_cone_point_continuous_cast_le_aux _ _ _ h.out,\n    ..(infer_instance : pseudo_normed_group (PseuNormGrp\u2081.bounded_cone_point C)) },\n  exhaustive' := (PseuNormGrp\u2081.bounded_cone_point C).exhaustive }\n\ndef bounded_cone : cone K :=\n{ X := bounded_cone_point C,\n  \u03c0 :=\n  { app := \u03bb j,\n    { continuous' := \u03bb c, level_\u03c0_continuous _ _ _,\n      ..((PseuNormGrp\u2081.bounded_cone C).\u03c0.app j) },\n    naturality' := begin\n      intros i j f,\n      ext,\n      dsimp,\n      rw \u2190 (PseuNormGrp\u2081.bounded_cone C).w f,\n      refl,\n    end } }\n\ndef bounded_cone_is_limit : is_limit (bounded_cone C) :=\n{ lift := \u03bb S,\n  { continuous' := begin\n      intros c,\n      let t : pseudo_normed_group.filtration S.X c \u2192\n        pseudo_normed_group.filtration (bounded_cone C).X c :=\n        (((PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S)).level _),\n      change continuous t,\n      suffices : continuous ((filtration_homeo C c) \u2218 t), by simpa using this,\n      have : \u21d1(filtration_homeo C c) \u2218 t =\n        (CompHaus.limit_cone_is_limit.{u u} _).lift ((level.obj c).map_cone S),\n      { ext,\n        change (C.is_limit.lift _ \u226b C.cone.\u03c0.app _) _ = _,\n        rw C.is_limit.fac, refl },\n      rw this,\n      continuity,\n    end,\n    ..((PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S)) },\n  fac' := begin\n    intros S j,\n    ext,\n    dsimp [bounded_cone],\n    change ((PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S) \u226b\n      (PseuNormGrp\u2081.bounded_cone C).\u03c0.app j) _ = _,\n    rw (PseuNormGrp\u2081.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\u2081.map m =\n      (PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S),\n    { apply (PseuNormGrp\u2081.bounded_cone_is_limit C).uniq (to_PNG\u2081.map_cone S),\n      intros j,\n      ext t,\n      specialize hm j,\n      apply_fun (\u03bb e, e t) at hm,\n      exact hm },\n    rw \u2190 this,\n    refl,\n  end }\n\ninstance : preserves_limit K to_PNG\u2081 :=\n\nbegin\n  apply preserves_limit_of_preserves_limit_cone,\n  rotate 2,\n  exact bounded_cone \u27e8_,Ab.explicit_limit_cone_is_limit.{u u} _\u27e9,\n  exact bounded_cone_is_limit _,\n  exact PseuNormGrp\u2081.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\u2081 :=\nbegin\n  constructor, introsI J hJ, constructor\nend\n\nend CompHausFiltPseuNormGrp\u2081\n\nnamespace ProFiltPseuNormGrp\u2081\n\n@[simp]\nlemma id_apply {A : ProFiltPseuNormGrp\u2081} (a : A) : (\ud835\udfd9 A : A \u27f6 A) a = a := rfl\n\n@[simp]\nlemma comp_apply {A B C : ProFiltPseuNormGrp\u2081} (f : A \u27f6 B) (g : B \u27f6 C) (a : A) :\n  (f \u226b g) a = g (f a) := rfl\n\ndef to_PNG\u2081 :\n  ProFiltPseuNormGrp\u2081.{u} \u2964 PseuNormGrp\u2081.{u} :=\n{ obj := \u03bb M,\n  { carrier := M,\n    exhaustive' := M.exhaustive },\n  map := \u03bb X Y f, { strict' := \u03bb c x h, f.strict h .. f.to_add_monoid_hom } }\n\ninstance : faithful to_PNG\u2081.{u} := faithful.mk $\nbegin\n  intros X Y f g h,\n  ext,\n  apply_fun (\u03bb e, e x) at h,\n  exact h\nend\n\nvariable {K : J \u2964 ProFiltPseuNormGrp\u2081.{u}}\nvariable (C : limits.limit_cone ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab))\n\ndef filtration_equiv (c : nnreal) :\n  pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\n  \u2243 (Profinite.limit_cone (K \u22d9 level.obj c)).X :=\n((cones.forget _).map_iso (PseuNormGrp\u2081.level_cone_iso C c)).to_equiv\n\ninstance (c) :\n  topological_space (pseudo_normed_group.filtration (PseuNormGrp\u2081.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\u2081.bounded_cone_point C) c\n  \u2243\u209c (Profinite.limit_cone (K \u22d9 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) := \u27e8rfl\u27e9,\n  rw this.is_open_iff at hU,\n  obtain \u27e8U,hU,rfl\u27e9 := hU,\n  simpa,\nend\n\ninstance (c) : t2_space\n  (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.t2_space\n\ninstance (c) : compact_space\n  (pseudo_normed_group.filtration (PseuNormGrp\u2081.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\u2081.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.totally_disconnected_space\n\ndef level_\u03c0 (j c) : pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c \u2192\n  pseudo_normed_group.filtration (K.obj j) c :=\n(PseuNormGrp\u2081.level.obj c).map ((PseuNormGrp\u2081.bounded_cone C).\u03c0.app j)\n\nlemma level_\u03c0_continuous (j c) : continuous (level_\u03c0 C j c) :=\nbegin\n  have : level_\u03c0 C j c \u2218 (filtration_homeo C c).symm =\n    (Profinite.limit_cone _).\u03c0.app j,\n  { ext,\n    change (C.is_limit.lift _ \u226b C.cone.\u03c0.app j) _ = _,\n    rw C.is_limit.fac,\n    refl },\n  suffices : continuous (level_\u03c0 C j c \u2218 (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 \u2964 ProFiltPseuNormGrp\u2081}\n  (C : category_theory.limits.limit_cone\n         ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab)) :\n  \u2200 (c\u2081 c\u2082 : nnreal), continuous\n  (pseudo_normed_group.add' :\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u00d7\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) (c\u2081 + c\u2082))) :=\nbegin\n  intros c\u2081 c\u2082,\n  let g : (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u00d7\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) (c\u2081 + c\u2082)) :=\n    pseudo_normed_group.add',\n  change continuous g,\n  suffices : continuous ((filtration_homeo C _) \u2218 g), by simpa using this,\n  apply continuous.subtype_mk,\n  apply continuous_pi,\n  intros j,\n  let e := pseudo_normed_group.add' \u2218 (prod.map (level_\u03c0 C j c\u2081) (level_\u03c0 C j c\u2082)),\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_\u03c0_continuous,\n    apply level_\u03c0_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 \u2964 ProFiltPseuNormGrp\u2081}\n  (C : category_theory.limits.limit_cone\n         ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab)) :\n  \u2200 (c : nnreal), continuous\n  (pseudo_normed_group.neg' :\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c)) :=\nbegin\n  intros c,\n  let g : (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c) :=\n    pseudo_normed_group.neg',\n  change continuous g,\n  suffices : continuous ((filtration_homeo C c) \u2218 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' \u2218 level_\u03c0 C j c,\n  have he : continuous e,\n  { apply continuous.comp,\n    apply comphaus_filtered_pseudo_normed_group.continuous_neg',\n    apply level_\u03c0_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 \u2964 ProFiltPseuNormGrp\u2081}\n  (C : category_theory.limits.limit_cone\n         ((K \u22d9 to_PNG\u2081) \u22d9 PseuNormGrp\u2081.to_Ab)) :\n  \u2200 (c\u2081 c\u2082 : nnreal) (h : c\u2081 \u2264 c\u2082), continuous\n  (pseudo_normed_group.cast_le' h :\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082)) :=\nbegin\n  intros c\u2081 c\u2082 h,\n  let g : (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2081) \u2192\n    (pseudo_normed_group.filtration (PseuNormGrp\u2081.bounded_cone_point C) c\u2082) :=\n    pseudo_normed_group.cast_le' h,\n  change continuous g,\n  suffices : continuous ((filtration_homeo C _) \u2218 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 \u2218 level_\u03c0 C j c\u2081,\n  have he : continuous e,\n  { apply continuous.comp,\n    haveI : fact (c\u2081 \u2264 c\u2082) := \u27e8h\u27e9,\n    apply comphaus_filtered_pseudo_normed_group.continuous_cast_le,\n    apply level_\u03c0_continuous },\n  exact he,\nend\n\ndef bounded_cone_point : ProFiltPseuNormGrp\u2081 :=\n{ M := PseuNormGrp\u2081.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 := \u03bb _ _ h, bounded_cone_point_continuous_cast_le_aux _ _ _ h.out,\n    ..(infer_instance : pseudo_normed_group (PseuNormGrp\u2081.bounded_cone_point C)) },\n  exhaustive' := (PseuNormGrp\u2081.bounded_cone_point C).exhaustive }\n\ndef bounded_cone : cone K :=\n{ X := bounded_cone_point C,\n  \u03c0 :=\n  { app := \u03bb j,\n    { continuous' := \u03bb c, level_\u03c0_continuous _ _ _,\n      ..((PseuNormGrp\u2081.bounded_cone C).\u03c0.app j) },\n    naturality' := begin\n      intros i j f,\n      ext,\n      dsimp,\n      rw \u2190 (PseuNormGrp\u2081.bounded_cone C).w f,\n      refl,\n    end } }\n\ndef bounded_cone_is_limit : is_limit (bounded_cone C) :=\n{ lift := \u03bb S,\n  { continuous' := begin\n      intros c,\n      let t : pseudo_normed_group.filtration S.X c \u2192\n        pseudo_normed_group.filtration (bounded_cone C).X c :=\n        (((PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S)).level _),\n      change continuous t,\n      suffices : continuous ((filtration_homeo C c) \u2218 t), by simpa using this,\n      have : \u21d1(filtration_homeo C c) \u2218 t =\n        (Profinite.limit_cone_is_limit _).lift ((level.obj c).map_cone S),\n      { ext,\n        change (C.is_limit.lift _ \u226b C.cone.\u03c0.app _) _ = _,\n        rw C.is_limit.fac, refl },\n      rw this,\n      continuity,\n    end,\n    ..((PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S)) },\n  fac' := begin\n    intros S j,\n    ext,\n    dsimp [bounded_cone],\n    change ((PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S) \u226b\n      (PseuNormGrp\u2081.bounded_cone C).\u03c0.app j) _ = _,\n    rw (PseuNormGrp\u2081.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\u2081.map m =\n      (PseuNormGrp\u2081.bounded_cone_is_limit C).lift (to_PNG\u2081.map_cone S),\n    { apply (PseuNormGrp\u2081.bounded_cone_is_limit C).uniq (to_PNG\u2081.map_cone S),\n      intros j,\n      ext t,\n      specialize hm j,\n      apply_fun (\u03bb e, e t) at hm,\n      exact hm },\n    rw \u2190 this,\n    refl,\n  end }\n\ninstance : preserves_limit K to_PNG\u2081 :=\n\nbegin\n  apply preserves_limit_of_preserves_limit_cone,\n  rotate 2,\n  exact bounded_cone \u27e8_,Ab.explicit_limit_cone_is_limit.{u u} _\u27e9,\n  exact bounded_cone_is_limit _,\n  exact PseuNormGrp\u2081.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\u2081 :=\nbegin\n  constructor, introsI J hJ, constructor\nend\n\nend ProFiltPseuNormGrp\u2081\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": "import smt.basic\nimport smt.veriT\n\nnamespace smt.parser\nopen smt (atom sexpr)\nopen smt.atom\n\n-- #eval nat.of_char ['1','2','3','0']\n\n\nend smt.parser\n\nnamespace smt\n\nopen parser tactic ( unsafe_run_io )\n\n-- def foo_bar :=\n-- do h \u2190 io.proc.spawn\n--         { cmd := \"veriT\",\n--           args := [\n--                    -- \"--proof-prune\",\"--proof-merge\",\"--proof-with-sharing\",\n--                            -- \"--cnf-definitional\",\"--disable-ackermann\",\n--                            -- \"--disable-e\",\n--                            -- \"--max-time=3\",\n--                            -- \"--input=smtlib2\",\n--                            -- \"--print-flat\",\n--                            -- \"--disable-banner\",\n--                            -- \"--print-simp-and-exit\",\n--                            \"--proof=file.log\"\n--                              -- \"--input=test.smt\",\n--                              -- \"test.smt\"\n--                            ],\n--           stdin := stdio.piped,\n--           stdout := stdio.piped,\n--           stderr := stdio.piped,\n--           -- cwd := _,\n--           -- env := _\n--           },\n--    -- xs \u2190 buffer.to_string <$> io.fs.read_file \"test.smt\",\n--    -- io.fs.put_str_ln h.stdin xs,\n--    let xs := [ \"; Integer arithmetic\",\n--                \"(set-option :print-success false)\",\n--                \"(set-option :produce-proofs true)\",\n--                \"(set-logic QF_LIA)\",\n--                \";; (echo \\\"foo\\\")\",\n--                \"(declare-fun x ( ) Int)\",\n--                \"(declare-fun y ( ) Int)\",\n--                \"(assert (! (= (- x y) (+ x (- y) 1)) :named h0))\",\n--                \"(assert (= x y))\",\n--                \"(check-sat)\",\n--                \";; (get-value ((x 0) (y 0) (x 1) (y 1)))\",\n--                \";; (get-model)\",\n--                \"(get-proof)\",\n--                \"; unsat\",\n--                \";; (exit)\" ],\n--    xs.mmap' (io.fs.put_str_ln h.stdin),\n--    io.fs.close h.stdin,\n--    -- dir \u2190 io.env.get_cwd,\n--    -- io.print $ dir.to_list,\n--    -- io.put_str_ln h,\n--    -- h' \u2190 io.cmd { cmd := \"pwd\" },\n--    -- io.put_str_ln h',\n--    io.put_str_ln \"stderr\",\n--    xs \u2190 read_to_end h.stderr,\n--    io.put_str_ln xs.to_string,\n--    io.put_str_ln \"stdout\",\n--    xs \u2190 read_to_end h.stdout,\n--    io.put_str_ln xs.to_string,\n--    io.proc.wait h,\n--    parse_log,\n--    pure ()\n\n-- run_cmd unsafe_run_io parse_log -- unsafe_run_io foo_bar\n\nend smt\n\n-- meta instance name.reflect : has_reflect name\n-- | name.anonymous        := `(name.anonymous)\n-- | (name.mk_string  s n) := `(\u03bb n, name.mk_string  s n).subst (name.reflect n)\n-- | (name.mk_numeral i n) := `(\u03bb n, name.mk_numeral i n).subst (name.reflect n)\n\nnamespace tactic.interactive\n\nopen smt (hiding expr) tactic smt.parser\nopen smt.sexpr smt.atom\n\n-- | _ := fail \"run_step\"\n\nopen smt.logic_fragment (hiding hashable) tactic\n\n-- -- Currently, QF_UF/QF_IDL/QF_RDL/QF_UFIDL are covered by proof production.\n-- meta def insert_with {k \u03b1} (m : rb_map k \u03b1) (f : \u03b1 \u2192 \u03b1 \u2192 \u03b1) (x : k) (y : \u03b1) : rb_map k \u03b1 :=\n-- match m.find x with\n-- | some y\u2080 := m.insert x (f y y\u2080)\n-- | none := m.insert x y\n-- end\n\n-- meta def of_list_with {key data} [has_lt key] [decidable_rel $ @has_lt.lt key _] (f : data \u2192 data \u2192 data) :\n--   list (key \u00d7 data) \u2192 rb_map key data\n-- | []           := native.rb_map.mk key data\n-- | ((k, v)::ls) := insert_with (of_list_with ls) f k v\n\nmeta def hash_context : tactic word64 :=\ndo t \u2190 target,\n   (h,_) \u2190 solve_aux t $ do {\n     ls \u2190 local_context,\n     revert_lst ls,\n     hash <$> target\n     },\n   pure h\nopen smt io io.process io.fs\nmeta def parse_log (fn : string) (prover : solver) : tactic prover.proof_type :=\ndo p \u2190 tactic.unsafe_run_io $ io.fs.read_file fn,\n   parser.run prover.read p\n\n-- def cache {\u03b1} (f : unit \u2192 \u03b1) := trunc { x : option \u03b1 // x.get_or_else (f ()) = f () }\n\n-- def cache.mk {\u03b1} (f : unit \u2192 \u03b1) : cache f :=\n-- trunc.mk \u27e8 none,rfl \u27e9\n\n-- def cache.read {\u03b1} {f : unit \u2192 \u03b1} : cache f \u2192 \u03b1 :=\n-- trunc.lift (\u03bb y : { s : option \u03b1 // _ }, y.val.get_or_else (f ())) $\n-- by { intros, casesm* [subtype _], simp *, }\n\n-- lemma cache.read_eq  {\u03b1} {f : unit \u2192 \u03b1} (x : cache f) :\n--   x.read = f () :=\n-- trunc.induction_on x $\n-- by { rintros \u27e8 a, h \u27e9, simp [cache.read,trunc.lift_beta,*], }\n\nmeta def unique_file_name (logic : logic_fragment) (prover : solver) (ext : string) : tactic string :=\ndo h \u2190 hash_context,\n   let h' := @hash_with_salt _ (prod.hashable _ _) (prover,logic) h,\n   pure $ \"proof_witness_\" ++ to_string (h') ++ \".\" ++ ext\n\nmeta def write_formulas (logic : logic_fragment) (prover : solver) (xs : list string) (h : handle) : io unit :=\ndo let opts := prover.options ++ [\n               \"(set-option :produce-proofs true)\",\n               \"(set-logic \" ++ repr logic ++ \")\"  ],\n   opts.mmap' $ io.fs.put_str_ln h,\n   xs.mmap' io.put_str,\n   xs.mmap' $ io.fs.put_str h,\n   io.fs.put_str_ln h \"(check-sat)\",\n   io.fs.put_str_ln h \"(get-proof)\"\n\nmeta def mk_args (prover : solver) (fn : string) : list string :=\nmatch prover.output_to_file with\n| (some opt) := prover.args ++ [opt ++ fn]\n| none := prover.args\nend\n\nmeta def call_solver (logic : logic_fragment) (prover : solver) (fn : string) (xs : list string) : tactic string :=\nunsafe_run_io $\ndo let args := mk_args prover fn,\n   h \u2190 io.proc.spawn\n     { cmd := prover.cmd,\n       args := args,\n       stdin := stdio.piped,\n       stdout := stdio.piped,\n       stderr := stdio.piped },\n   write_formulas logic prover xs h.stdin,\n   close h.stdin,\n   when (prover.output_to_file.is_none) $\n     do { ln \u2190 buffer.to_string <$> get_line h.stdout,\n          io.put_str ln,\n          file \u2190 mk_file_handle fn mode.write,\n          if ln = \"unsat\\n\" then\n          do proof \u2190 read_to_end h.stdout,\n             write file proof,\n             io.put_str_ln proof.to_string\n          else pure (),\n          close file },\n   -- xs \u2190 buffer.to_string <$> read_to_end h.stdout,\n   -- io.put_str_ln xs,\n   xs \u2190 buffer.to_string <$> read_to_end h.stderr,\n   io.put_str_ln xs,\n   proc.wait h,\n   pure fn\n\nopen smt.logic_fragment\nmeta def veriT (logic : logic_fragment := QF_LIA) : tactic unit :=\ndo by_contradiction none,\n   dedup,\n   -- try $ `[norm_num at *],\n   let prover := smt.veriT,\n   -- `[dsimp only [has_pow.pow,pnat.pow,nat.pow,monoid.has_pow,gpow] { fail_if_unchanged := ff } ],\n   fn \u2190 unique_file_name logic prover \"log\",\n   trace $ repr logic,\n   trace fn,\n   ls \u2190 local_context,\n   ps \u2190 ls.mmap encode_local,\n   unsafe_run_io $ do {\n     h \u2190 io.mk_file_handle fn mode.write,\n     io.fs.write h \"\".to_char_buffer },\n   fn \u2190 call_solver logic prover fn ps,\n   p \u2190 parse_log fn prover,\n   prover.execute p,\n   done,\n   pure ()\n\nend tactic.interactive\n\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-lean.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376782, "lm_q2_score": 0.03514484842196812, "lm_q1q2_score": 0.012756497225464984}}
{"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 \u2192 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 \u2192 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 \u2192 expr \u2192 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 \u2192 bool \u2192 list expr\n/-- Get the root representative of the given expression. -/\nmeta constant cc_state.root             : cc_state \u2192 expr \u2192 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 \u2192 expr \u2192 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 \u2192 nat\n/-- Increment the Global Modification time. -/\nmeta constant cc_state.inc_gmt          : cc_state \u2192 cc_state\n/-- Check if `e` is the root of the congruence class. -/\nmeta constant cc_state.is_cg_root       : cc_state \u2192 expr \u2192 bool\n/-- Pretty print the entry associated with the given expression. -/\nmeta constant cc_state.pp_eqc           : cc_state \u2192 expr \u2192 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 \u2192 bool \u2192 tactic format\n/-- Add the given expression to the graph. -/\nmeta constant cc_state.internalize      : cc_state \u2192 expr \u2192 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 \u2192 expr \u2192 tactic cc_state\n/-- Check whether two expressions are in the same equivalence class. -/\nmeta constant cc_state.is_eqv           : cc_state \u2192 expr \u2192 expr \u2192 tactic bool\n/-- Check whether two expressions are not in the same equivalence class. -/\nmeta constant cc_state.is_not_eqv       : cc_state \u2192 expr \u2192 expr \u2192 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 \u2192 expr \u2192 expr \u2192 tactic expr\n/-- Returns true if the cc_state is inconsistent. For example if it had both `a = b` and `a \u2260 b` in it.-/\nmeta constant cc_state.inconsistent     : cc_state \u2192 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 \u2192 expr \u2192 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 \u2192 expr \u2192 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 \u2192 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\u27e8\u03bb s, cc_state.pp_core s tt\u27e9\n\nmeta def eqc_of_core (s : cc_state) : expr \u2192 expr \u2192 list expr \u2192 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 {\u03b1} (s : cc_state) (f : \u03b1 \u2192 expr \u2192 \u03b1) (first : expr) : expr \u2192 \u03b1 \u2192 \u03b1\n| c a :=\n  let new_a := f a c,\n      next  := s.next c in\n  if next =\u2090 first then new_a\n  else fold_eqc_core next new_a\n\nmeta def fold_eqc {\u03b1} (s : cc_state) (e : expr) (a : \u03b1) (f : \u03b1 \u2192 expr \u2192 \u03b1) : \u03b1 :=\nfold_eqc_core s f e e a\n\nmeta def mfold_eqc {\u03b1} {m : Type \u2192 Type} [monad m] (s : cc_state) (e : expr) (a : \u03b1) (f : \u03b1 \u2192 expr \u2192 m \u03b1) : m \u03b1 :=\nfold_eqc s e (return a) (\u03bb act e, do a \u2190 act, f a e)\nend cc_state\n\nopen tactic\nmeta def tactic.cc_core (cfg : cc_config) : tactic unit :=\ndo intros, s \u2190 cc_state.mk_using_hs_core cfg, t \u2190 target, s \u2190 s.internalize t,\n   if s.inconsistent then do {\n     pr \u2190 s.proof_for_false,\n     mk_app `false.elim [t, pr] >>= exact}\n   else do {\n     tr \u2190 return $ expr.const `true [],\n     b \u2190 s.is_eqv t tr,\n     if b then do {\n       pr \u2190 s.eqv_proof t tr,\n       mk_app `of_eq_true [pr] >>= exact\n     } else do {\n       dbg \u2190 get_bool_option `trace.cc.failure ff,\n       if dbg then do {\n         ccf \u2190 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) \u2190 target >>= match_eq,\n   s \u2190 return $ cc_state.mk,\n   s \u2190 s.internalize lhs,\n   s \u2190 s.internalize rhs,\n   b \u2190 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 {\u03c9 : ontology} (s : \u03c9.substance)\n include \u03c9\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 \u03c9.world s.State_setoid\n \n @[reducible]\n def substance.State_at (w : \u03c9.world) := @quotient.mk \u03c9.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 \u2260 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 : \u2200 (a: \u03c9.accident), a.inheres s \u2192 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 \u03b1 := {x : \u03c9.world | \u2203 (x_1 : \u03c9.world), x_1 \u2208 (a.val).exists \u2227 substance.equiv s x_1 x},\n--     suffices c : is_open \u03b1,\n--         exact c,\n--     suffices c : \u03b1  = a.val.exists,\n--         rw c,\n--         exact a.val.existential,\n--     ext, constructor; intro h; simp at *,\n--         obtain \u27e8y, h\u2081, h\u2082\u27e9 := h,\n--         simp [substance.equiv, substance.state] at h\u2082,\n--         simp [ontology.world.entities, entity.subsistents] at h\u2082,\n        \n--         -- have c : {a : \u03c9.accident | a.inheres s} \u2229 {a : \u03c9.accident | y \u2208 (a.val).exist} \u2286\n--         --          {a : \u03c9.accident | a.inheres s} \u2229 {a : \u03c9.accident | x \u2208 (a.val).exist},\n--         -- rw h\u2082,\n--         -- exact and.right (@c a \u27e8H, h\u2081\u27e9),\n--     existsi x,\n--     constructor,\n--         assumption,\n--     obtain \u27e8res, _, _\u27e9 := 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 : \u2200 (a: \u03c9.accident), a.inheres s \u2192 (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 : \u2200 (a: \u03c9.accident), a.inheres s \u2192 (s.State_at '' a.exists) \u2260 univ := sorry\n--  begin\n--     intros a H,\n--     simp [preimage, image, quotient.mk],\n--     intro h,\n--     -- This is a trick\n--     -- let \u03c8 := (@quotient.mk world ontology.substance.State_setoid),\n--     replace h : univ \u2286 {b : quotient s.State_setoid | \u2203 (a_1 : \u03c9.world), a_1 \u2208 (a.val).exists \u2227 s.State_at a_1 = b},\n--         rw \u2190h,\n--         -- refl,\n--     have c : s.val.exists = a.val.exists,\n--     ext, constructor; intro h\u2081,--; simp at *,\n--         have c := @h (s.State_at x) _,\n--         simp at c,\n--         obtain \u27e8y, c\u2081, c\u2082\u27e9 := c,\n--         replace c\u2082 : s.equiv y x := c\u2082,\n--         simp [substance.equiv, substance.state] at c\u2082,\n--         simp [ontology.world.entities, entity.subsistents] at c\u2082,\n--         have c : {a : \u03c9.accident | a.inheres s} \u2229 {a : \u03c9.accident | y \u2208 (a.val).exist} \u2286\n--                  {a : \u03c9.accident | a.inheres s} \u2229 {a : \u03c9.accident | x \u2208 (a.val).exist},\n--         rw c\u2082,\n--         exact and.right (@c a \u27e8H, c\u2081\u27e9),\n--             trivial,\n--         revert x,\n--         apply sub_of_inheres,\n--         exact H,\n--     have c\u2081 : s.val.exists.dense := s.property,\n--     have c\u2082 : \u00ac a.val.exists.dense := a.property,\n--     rw c at c\u2081,\n--     contradiction,\n--  end\n \n -- Finally we can construct the perfection.\n def substance.Perfection_of (a \u2208 s.accidents) : s.Perfection :=\n    \u27e8 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    \u27e9\n \n -- perfections which come from accidents\n @[reducible]\n def substance.aperfections := {p : s.Perfection | \u2203 a \u2208 s.accidents, (s.Perfection_of a H) = p}\n \n -- events which come from accidents\n @[reducible]\n def substance.aevents := {p : s.Event | \u2203 a \u2208 s.accidents, (s.Perfection_of a H).exist = p}\n \n instance state_has_mem : has_mem s.Perfection s.State :=\n \u27e8\u03bb p s, s \u2208 p.exist\u27e9\n @[reducible]\n def perfections (x : s.State) := {p : s.Perfection | p \u2208 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 : \u03c9.substance} (x : s.State) :=\n    (U : s.Event)\n    (is_open : is_open U)\n    (elem : x \u2208 U)\n \n noncomputable def state.nhd_default {s : \u03c9.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 : \u2203w, \u27e6w\u27e7 = x \u2227 (\u2203a : \u03c9.accident, a.inheres s \u2227 a.up \u2208 w),\n        swap,\n            exact \u27e8univ, is_open_univ, by simp\u27e9,\n        replace w := nonempty_subtype.2 w,\n        replace w := classical.choice w,\n        obtain \u27e8w, hw, a\u27e9 := w,\n        replace a := nonempty_subtype.2 a,\n        replace a := classical.choice a,\n        obtain \u27e8a, ha\u2081, ha\u2082\u27e9 := a,\n        -- a is now our wanted accident.\n        let p := s.Perfection_of a ha\u2081,\n        -- it is now easier to build the neighborhood.\n        fconstructor,\n            exact p.exist,\n            exact p.is_open,\n        rw \u2190hw,\n        simp [p,substance.Perfection_of],\n        existsi w,\n        exact \u27e8ha\u2082, rfl\u27e9,\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 \u2192 \u2200 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 : \u00ac \u2200 x, x \u2208 s.val.exists,\n --         by {obtain \u27e8\u27e8exist, is_open, nes\u27e9, perfect\u27e9 := 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 --     --  \u03c6 $\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 \u27e8x, hx\u27e9 := c,\n --     --         constructor,\n --     --         exact \u27e8x, hx\u27e9,\n --     --     end,\n --     \u03c6 $\n --     subtype.val $\n --     choice $\n --     aux h\n        \n \n \n \n --   begin\n --     classical,\n --     obtain \u27e8\u27e8exist, is_open, nes\u27e9, perfect\u27e9 := s,\n --     simp [contingent, nb, nbe] at h,\n --     set s : \u03c9.substance := \u27e8\u27e8exist, is_open, nes\u27e9, perfect\u27e9,\n --     have c : \u00ac \u2200 x, x \u2208 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 \u03c6 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))) = \u2205 :=\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.\u03c6],\n --         intros h\u2082 h\u2083,\n --         -- simp at h\u2083,\n --         have d := sub_of_inheres x s h\u2082,\n --         replace h\u2083 := d h\u2083,\n --         -- simp [(choice (aux s h)).property] at h\u2083,\n --         -- set c := subtype.val (choice (aux s h),\n --         -- let c := quotient.mk_out \u27e6(choice (aux s h)).val\u27e7,\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 \u22a5 = \u2205 :=\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\u207b\u00b9' p.exists,\n --      let state := p.ne.some,\n --      have c : is_open e \u2227 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\u2082 : entity := \u27e8e, c.1, c.2\u27e9, \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 \u27e8\u27e8exist, is_open, nes\u27e9, perfect\u27e9 := s,\n --             simp [contingent, nb, nbe] at h,\n --             set s : \u03c9.substance := \u27e8\u27e8exist, is_open, nes\u27e9, perfect\u27e9,\n --             have c : \u00ac \u2200 x, x \u2208 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 \u03c6 s c,\n --         exact \u03c6 s (default world),\n --     intros x\u2081 x\u2082,\n --     exact \u2200 p : s.Perfection, p \u2208 x\u2081 \u2192 p \u2208 x\u2082,\n --         intros x p h,\n --         exact h,\n --     intros x y z h\u2081 h\u2082 p hp,\n --     exact h\u2082 p (h\u2081 p hp),\n --         intros x y h\u2081 h\u2082,\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 : \u2200 (w : s.State) (U : set s.State), w \u2208 U \u2192 is_open U \u2192 \u2203 V \u2208 s.aevents, w \u2208 V \u2227 V \u2286 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 \u2190 mkFreshExprMVar (some (mkConst ``Nat))\n  let mvarId := mvar.mvarId!\n  let mvar2 \u2190 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 \u2190 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 \u2190 mvarMeta4\n      return  e\n\ndef chkMinAss4  := minass!\n\n#check chkMinAss4\n#eval chkMinAss4 2\n\ntheorem zero_add : (n : Nat) \u2192  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 \u2192 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) \u2192 Nat.below n \u2192 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 \u00d7 Nat) :=\n  do\n    let t \u2190 inferType e\n    let rwr \u2190 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 \u2190 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 \u2190 getMainGoal\n      let e \u2190 Elab.Tactic.elabTerm s none\n      let heq \u2190 Elab.Tactic.elabTerm t none\n      let (rw, l) \u2190 rwPush mvarId e heq\n      Elab.logInfo m!\"obtained {rw}\"\n      if \u2190 isDefEq (\u2190 inferType rw) (\u2190 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 {\u03b1 : Type}{P: \u03b1 \u2192 Type}{a b : \u03b1}(heq : a = b)(x : P a) : P b := by\n    rwPushTac heq on x\n\n#check @pushEg\n#reduce @pushEg\n\ndef transPf {\u03b1 : Type}{a b c : \u03b1}(f: \u03b1 \u2192 Nat) :\n          a = b \u2192 b = c \u2192 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": "/-\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 {\u03b5 : Type u}\n\n@[inline] protected def pure (a : \u03b1) : Except \u03b5 \u03b1 :=\n  Except.ok a\n\n@[inline] protected def map (f : \u03b1 \u2192 \u03b2) : Except \u03b5 \u03b1 \u2192 Except \u03b5 \u03b2\n  | Except.error err => Except.error err\n  | Except.ok v => Except.ok <| f v\n\n@[simp] theorem map_id : Except.map (\u03b5 := \u03b5) (\u03b1 := \u03b1) (\u03b2 := \u03b1) id = id := by\n  apply funext\n  intro e\n  simp [Except.map]; cases e <;> rfl\n\n@[inline] protected def mapError (f : \u03b5 \u2192 \u03b5') : Except \u03b5 \u03b1 \u2192 Except \u03b5' \u03b1\n  | Except.error err => Except.error <| f err\n  | Except.ok v      => Except.ok v\n\n@[inline] protected def bind (ma : Except \u03b5 \u03b1) (f : \u03b1 \u2192 Except \u03b5 \u03b2) : Except \u03b5 \u03b2 :=\n  match ma with\n  | Except.error err => Except.error err\n  | Except.ok v      => f v\n\n@[inline] protected def toBool : Except \u03b5 \u03b1 \u2192 Bool\n  | Except.ok _    => true\n  | Except.error _ => false\n\n@[inline] protected def toOption : Except \u03b5 \u03b1 \u2192 Option \u03b1\n  | Except.ok a    => some a\n  | Except.error _ => none\n\n@[inline] protected def tryCatch (ma : Except \u03b5 \u03b1) (handle : \u03b5 \u2192 Except \u03b5 \u03b1) : Except \u03b5 \u03b1 :=\n  match ma with\n  | Except.ok a    => Except.ok a\n  | Except.error e => handle e\n\ndef orElseLazy (x : Except \u03b5 \u03b1) (y : Unit \u2192 Except \u03b5 \u03b1) : Except \u03b5 \u03b1 :=\n  match x with\n  | Except.ok a    => Except.ok a\n  | Except.error e => y ()\n\ninstance : Monad (Except \u03b5) where\n  pure := Except.pure\n  bind := Except.bind\n  map  := Except.map\n\nend Except\n\ndef ExceptT (\u03b5 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) : Type v :=\n  m (Except \u03b5 \u03b1)\n\n@[inline] def ExceptT.mk {\u03b5 : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type u} (x : m (Except \u03b5 \u03b1)) : ExceptT \u03b5 m \u03b1 := x\n@[inline] def ExceptT.run {\u03b5 : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type u} (x : ExceptT \u03b5 m \u03b1) : m (Except \u03b5 \u03b1) := x\n\nnamespace ExceptT\n\nvariable {\u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m]\n\n@[inline] protected def pure {\u03b1 : Type u} (a : \u03b1) : ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk <| pure (Except.ok a)\n\n@[inline] protected def bindCont {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : Except \u03b5 \u03b1 \u2192 m (Except \u03b5 \u03b2)\n  | Except.ok a    => f a\n  | Except.error e => pure (Except.error e)\n\n@[inline] protected def bind {\u03b1 \u03b2 : Type u} (ma : ExceptT \u03b5 m \u03b1) (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : ExceptT \u03b5 m \u03b2 :=\n  ExceptT.mk <| ma >>= ExceptT.bindCont f\n\n@[inline] protected def map {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1) : ExceptT \u03b5 m \u03b2 :=\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@[inline] protected def lift {\u03b1 : Type u} (t : m \u03b1) : ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk <| Except.ok <$> t\n\ninstance : MonadLift (Except \u03b5) (ExceptT \u03b5 m) := \u27e8fun e => ExceptT.mk <| pure e\u27e9\ninstance : MonadLift m (ExceptT \u03b5 m) := \u27e8ExceptT.lift\u27e9\n\n@[inline] protected def tryCatch {\u03b1 : Type u} (ma : ExceptT \u03b5 m \u03b1) (handle : \u03b5 \u2192 ExceptT \u03b5 m \u03b1) : ExceptT \u03b5 m \u03b1 :=\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 \u03b5 m) := \u27e8fun f x => f x\u27e9\n\ninstance : Monad (ExceptT \u03b5 m) where\n  pure := ExceptT.pure\n  bind := ExceptT.bind\n  map  := ExceptT.map\n\n@[inline] protected def adapt {\u03b5' \u03b1 : Type u} (f : \u03b5 \u2192 \u03b5') : ExceptT \u03b5 m \u03b1 \u2192 ExceptT \u03b5' m \u03b1 := fun x =>\n  ExceptT.mk <| Except.mapError f <$> x\n\nend ExceptT\n\ninstance (m : Type u \u2192 Type v) (\u03b5\u2081 : Type u) (\u03b5\u2082 : Type u) [Monad m] [MonadExceptOf \u03b5\u2081 m] : MonadExceptOf \u03b5\u2081 (ExceptT \u03b5\u2082 m) where\n  throw e := ExceptT.mk <| throwThe \u03b5\u2081 e\n  tryCatch x handle := ExceptT.mk <| tryCatchThe \u03b5\u2081 x handle\n\ninstance (m : Type u \u2192 Type v) (\u03b5 : Type u) [Monad m] : MonadExceptOf \u03b5 (ExceptT \u03b5 m) where\n  throw e := ExceptT.mk <| pure (Except.error e)\n  tryCatch := ExceptT.tryCatch\n\ninstance [Monad m] [Inhabited \u03b5] : Inhabited (ExceptT \u03b5 m \u03b1) where\n  default := throw default\n\ninstance (\u03b5) : MonadExceptOf \u03b5 (Except \u03b5) where\n  throw    := Except.error\n  tryCatch := Except.tryCatch\n\nnamespace MonadExcept\nvariable {\u03b5 : Type u} {m : Type v \u2192 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@[inline] def orelse' [MonadExcept \u03b5 m] {\u03b1 : Type v} (t\u2081 t\u2082 : m \u03b1) (useFirstEx := true) : m \u03b1 :=\n  tryCatch t\u2081 fun e\u2081 => tryCatch t\u2082 fun e\u2082 => throw (if useFirstEx then e\u2081 else e\u2082)\n\nend MonadExcept\n\n@[inline] def observing {\u03b5 \u03b1 : Type u} {m : Type u \u2192 Type v} [Monad m] [MonadExcept \u03b5 m] (x : m \u03b1) : m (Except \u03b5 \u03b1) :=\n  tryCatch (do let a \u2190 x; pure (Except.ok a)) (fun ex => pure (Except.error ex))\n\ndef liftExcept [MonadExceptOf \u03b5 m] [Pure m] : Except \u03b5 \u03b1 \u2192 m \u03b1\n  | Except.ok a    => pure a\n  | Except.error e => throw e\n\ninstance (\u03b5 : Type u) (m : Type u \u2192 Type v) [Monad m] : MonadControl m (ExceptT \u03b5 m) where\n  stM        := Except \u03b5\n  liftWith f := liftM <| f fun x => x.run\n  restoreM x := x\n\nclass MonadFinally (m : Type u \u2192 Type v) where\n  tryFinally' {\u03b1 \u03b2} : m \u03b1 \u2192 (Option \u03b1 \u2192 m \u03b2) \u2192 m (\u03b1 \u00d7 \u03b2)\n\nexport MonadFinally (tryFinally')\n\n/-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/\n@[inline] def tryFinally {m : Type u \u2192 Type v} {\u03b1 \u03b2 : Type u} [MonadFinally m] [Functor m] (x : m \u03b1) (finalizer : m \u03b2) : m \u03b1 :=\n  let y := tryFinally' x (fun _ => finalizer)\n  (\u00b7.1) <$> y\n\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\ninstance ExceptT.finally {m : Type u \u2192 Type v} {\u03b5 : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT \u03b5 m) where\n  tryFinally' := fun x h => ExceptT.mk do\n    let r \u2190 tryFinally' x fun e? => match e? with\n        | some (Except.ok a) => h (some a)\n        | _                  => h none\n    match r with\n    | (Except.ok a,    Except.ok b)    => pure (Except.ok (a, b))\n    | (_,              Except.error e) => pure (Except.error e)  -- second error has precedence\n    | (Except.error e, _)              => pure (Except.error e)\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/Control/Except.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16667539640920676, "lm_q2_score": 0.07585818263281055, "lm_q1q2_score": 0.012643692661205701}}
{"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.function init.data.option.basic init.util\nimport init.control.combinators init.control.monad init.control.alternative init.control.monad_fail\nimport init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment\nimport init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad\nimport init.classical\n\nopen native\n\nmeta constant tactic_state : Type\n\nuniverses u v\n\nnamespace tactic_state\nmeta constant env         : tactic_state \u2192 environment\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. -/\nmeta constant to_format   (s : tactic_state) (target_lhs_only : bool := ff) : format\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. -/\nmeta constant format_expr : tactic_state \u2192 expr \u2192 format\nmeta constant get_options : tactic_state \u2192 options\nmeta constant set_options : tactic_state \u2192 options \u2192 tactic_state\nend tactic_state\n\nmeta instance : has_to_format tactic_state :=\n\u27e8tactic_state.to_format\u27e9\n\nmeta instance : has_to_string tactic_state :=\n\u27e8\u03bb s, (to_fmt s).to_string s.get_options\u27e9\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-/\n@[reducible] meta def tactic := interaction_monad tactic_state\n@[reducible] meta def tactic_result := interaction_monad.result tactic_state\n\nnamespace tactic\n  export interaction_monad (result result.success result.exception result.cases_on\n    result_to_string mk_exception silent_fail orelse' bracket)\n  /-- Cause the tactic to fail with no error message. -/\n  meta def failed {\u03b1 : Type} : tactic \u03b1 := interaction_monad.failed\n  meta def fail {\u03b1 : Type u} {\u03b2 : Type v} [has_to_format \u03b2] (msg : \u03b2) : tactic \u03b1 :=\n  interaction_monad.fail msg\nend tactic\n\nnamespace tactic_result\n  export interaction_monad.result\nend tactic_result\n\nopen tactic\nopen tactic_result\n\ninfixl ` >>=[tactic] `:2 := interaction_monad_bind\ninfixl ` >>[tactic] `:2  := interaction_monad_seq\n\nmeta instance : alternative tactic :=\n{ failure := @interaction_monad.failed _,\n  orelse  := @interaction_monad_orelse _,\n  ..interaction_monad.monad }\n\nmeta def {u\u2081 u\u2082} tactic.up {\u03b1 : Type u\u2082} (t : tactic \u03b1) : tactic (ulift.{u\u2081} \u03b1) :=\n\u03bb s, match t s with\n| success a s'      := success (ulift.up a) s'\n| exception t ref s := exception t ref s\nend\n\nmeta def {u\u2081 u\u2082} tactic.down {\u03b1 : Type u\u2082} (t : tactic (ulift.{u\u2081} \u03b1)) : tactic \u03b1 :=\n\u03bb s, match t s with\n| success (ulift.up a) s' := success a s'\n| exception t ref s       := exception t ref s\nend\n\nnamespace interactive\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 \u03b1` 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-/\nmeta class executor (m : Type \u2192 Type u) [monad m] :=\n(config_type : Type)\n[inhabited : inhabited config_type]\n(execute_with : config_type \u2192 m unit \u2192 tactic unit)\n\nattribute [inline] executor.execute_with\n\n@[inline]\nmeta def executor.execute_explicit (m : Type \u2192 Type u)\n   [monad m] [e : executor m] : m unit \u2192 tactic unit :=\nexecutor.execute_with e.inhabited.default\n\n@[inline]\nmeta def executor.execute_with_explicit (m : Type \u2192 Type u)\n   [monad m] [executor m] : executor.config_type m \u2192 m unit \u2192 tactic unit :=\nexecutor.execute_with\n\n/-- Default `executor` instance for `tactic`s themselves -/\nmeta instance executor_tactic : executor tactic :=\n{ config_type := unit,\n  inhabited := \u27e8()\u27e9,\n  execute_with := \u03bb _, id }\n\nend interactive\n\nnamespace tactic\n\nopen interaction_monad.result\n\nvariables {\u03b1 : Type u}\n\n/-- Does nothing. -/\nmeta def skip : tactic unit :=\nsuccess ()\n\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-/\nmeta def try_core (t : tactic \u03b1) : tactic (option \u03b1) := \u03bb s,\nmatch t s with\n| (exception _ _ _) := success none s\n| (success a s') := success (some a) s'\nend\n\n/--\n`try t` acts like `t`, but succeeds even if `t` fails.\n-/\nmeta def try (t : tactic \u03b1) : tactic unit := \u03bb s,\nmatch t s with\n| (exception _ _ _) := success () s\n| (success _ s') := success () s'\nend\n\nmeta def try_lst : list (tactic unit) \u2192 tactic unit\n| []            := failed\n| (tac :: tacs) := \u03bb s,\n  match tac s with\n  | success _ s' := try (try_lst tacs) s'\n  | exception e p s' :=\n    match try_lst tacs s' with\n    | exception _ _ _ := exception e p s'\n    | r := r\n    end\n  end\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-/\nmeta def fail_if_success {\u03b1 : Type u} (t : tactic \u03b1) : tactic unit := \u03bb s,\nmatch (t s) with\n| (success a s) := mk_exception \"fail_if_success combinator failed, given tactic succeeded\" none s\n| (exception _ _ _) := success () s\nend\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-/\nmeta def success_if_fail {\u03b1 : Type u} (t : tactic \u03b1) : tactic unit := \u03bb s,\nmatch t s with\n| (success a s) :=\n   mk_exception \"success_if_fail combinator failed, given tactic succeeded\" none s\n| (exception _ _ _) := success () s\nend\n\nopen nat\n\n/--\n`iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the\nresult of each successful iteration.\n-/\nmeta def iterate_at_most : nat \u2192 tactic \u03b1 \u2192 tactic (list \u03b1)\n| 0       t := pure []\n| (n + 1) t := do\n  (some a) \u2190 try_core t | pure [],\n  as \u2190 iterate_at_most n t,\n  pure $ a :: as\n\n/--\n`iterate_at_most' n t` repeats `t` `n` times or until `t` fails.\n-/\nmeta def iterate_at_most' : nat \u2192 tactic unit \u2192 tactic unit\n| 0        t := skip\n| (succ n) t := do\n  (some _) \u2190 try_core t | skip,\n  iterate_at_most' n t\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-/\nmeta def iterate_exactly : nat \u2192 tactic \u03b1 \u2192 tactic (list \u03b1)\n| 0       t := pure []\n| (n + 1) t := do\n  a \u2190 t,\n  as \u2190 iterate_exactly n t,\n  pure $ a ::as\n\n/--\n`iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole\ntactic fails.\n-/\nmeta def iterate_exactly' : nat \u2192 tactic unit \u2192 tactic unit\n| 0       t := skip\n| (n + 1) t := t *> iterate_exactly' n t\n\n/--\n`iterate t` repeats `t` 100.000 times or until `t` fails, returning the\nresult of each iteration.\n-/\nmeta def iterate : tactic \u03b1 \u2192 tactic (list \u03b1) :=\niterate_at_most 100000\n\n/--\n`iterate' t` repeats `t` 100.000 times or until `t` fails.\n-/\nmeta def iterate' : tactic unit \u2192 tactic unit :=\niterate_at_most' 100000\n\nmeta def returnopt (e : option \u03b1) : tactic \u03b1 :=\n\u03bb s, match e with\n| (some a) := success a s\n| none     := mk_exception \"failed\" none s\nend\n\nmeta instance opt_to_tac : has_coe (option \u03b1) (tactic \u03b1) :=\n\u27e8returnopt\u27e9\n\n/-- Decorate t's exceptions with msg. -/\nmeta def decorate_ex (msg : format) (t : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s, result.cases_on (t s)\n  success\n  (\u03bb opt_thunk,\n     match opt_thunk with\n     | some e := exception (some (\u03bb u, msg ++ format.nest 2 (format.line ++ e u)))\n     | none   := exception none\n     end)\n\n/-- Set the tactic_state. -/\n@[inline] meta def write (s' : tactic_state) : tactic unit :=\n\u03bb s, success () s'\n\n/-- Get the tactic_state. -/\n@[inline] meta def read : tactic tactic_state :=\n\u03bb s, success s s\n\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-/\nmeta def capture (t : tactic \u03b1) : tactic (tactic_result \u03b1) :=\n\u03bb s, match t s with\n| (success r s') := success (success r s') s'\n| (exception f p s') := success (exception f p s') s'\nend\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 \u2190 capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted.\n-/\nmeta def unwrap {\u03b1 : Type*} (t : tactic_result \u03b1) : tactic \u03b1 :=\nmatch t with\n| (success r s') := return r\n| e := \u03bb s, e\nend\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-/\nmeta def resume {\u03b1 : Type*} (t : tactic_result \u03b1) : tactic \u03b1 :=\n\u03bb s, t\n\nmeta def get_options : tactic options :=\ndo s \u2190 read, return s.get_options\n\nmeta def set_options (o : options) : tactic unit :=\ndo s \u2190 read, write (s.set_options o)\n\nmeta def save_options {\u03b1 : Type} (t : tactic \u03b1) : tactic \u03b1 :=\ndo o \u2190 get_options,\n   a \u2190 t,\n   set_options o,\n   return a\n\nmeta def returnex {\u03b1 : Type} (e : exceptional \u03b1) : tactic \u03b1 :=\n\u03bb s, match e with\n| exceptional.success a      := success a s\n| exceptional.exception f :=\n  match get_options s with\n  | success opt _   := exception (some (\u03bb u, f opt)) none s\n  | exception _ _ _ := exception (some (\u03bb u, f options.mk)) none s\n  end\nend\n\nmeta instance ex_to_tac {\u03b1 : Type} : has_coe (exceptional \u03b1) (tactic \u03b1) :=\n\u27e8returnex\u27e9\n\nend tactic\n\nmeta def tactic_format_expr (e : expr) : tactic format :=\ndo s \u2190 tactic.read, return (tactic_state.format_expr s e)\n\nmeta class has_to_tactic_format (\u03b1 : Type u) :=\n(to_tactic_format : \u03b1 \u2192 tactic format)\n\nmeta instance : has_to_tactic_format expr :=\n\u27e8tactic_format_expr\u27e9\n\nmeta def tactic.pp {\u03b1 : Type u} [has_to_tactic_format \u03b1] : \u03b1 \u2192 tactic format :=\nhas_to_tactic_format.to_tactic_format\n\nopen tactic format\n\nmeta instance {\u03b1 : Type u} [has_to_tactic_format \u03b1] : has_to_tactic_format (list \u03b1) :=\n\u27e8\u03bb l, to_fmt <$> l.mmap pp\u27e9\n\nmeta instance (\u03b1 : Type u) (\u03b2 : Type v) [has_to_tactic_format \u03b1] [has_to_tactic_format \u03b2] :\n has_to_tactic_format (\u03b1 \u00d7 \u03b2) :=\n\u27e8\u03bb \u27e8a, b\u27e9, to_fmt <$> (prod.mk <$> pp a <*> pp b)\u27e9\n\nmeta def option_to_tactic_format {\u03b1 : Type u} [has_to_tactic_format \u03b1] : option \u03b1 \u2192 tactic format\n| (some a) := do fa \u2190 pp a, return (to_fmt \"(some \" ++ fa ++ \")\")\n| none     := return \"none\"\n\nmeta instance {\u03b1 : Type u} [has_to_tactic_format \u03b1] : has_to_tactic_format (option \u03b1) :=\n\u27e8option_to_tactic_format\u27e9\n\nmeta instance {\u03b1} (a : \u03b1) : has_to_tactic_format (reflected a) :=\n\u27e8\u03bb h, pp h.to_expr\u27e9\n\n@[priority 10] meta instance has_to_format_to_has_to_tactic_format (\u03b1 : Type) [has_to_format \u03b1] : has_to_tactic_format \u03b1 :=\n\u27e8(\u03bb x, return x) \u2218 to_fmt\u27e9\n\nnamespace tactic\nopen tactic_state\n\nmeta def get_env : tactic environment :=\ndo s \u2190 read,\n   return $ env s\n\nmeta def get_decl (n : name) : tactic declaration :=\ndo s \u2190 read,\n   (env s).get n\n\nmeta constant get_trace_msg_pos : tactic pos\n\nmeta def trace {\u03b1 : Type u} [has_to_tactic_format \u03b1] (a : \u03b1) : tactic unit :=\ndo fmt \u2190 pp a,\n   return $ _root_.trace_fmt fmt (\u03bb u, ())\n\nmeta def trace_call_stack : tactic unit :=\nassume state, _root_.trace_call_stack (success () state)\n\nmeta def timetac {\u03b1 : Type u} (desc : string) (t : thunk (tactic \u03b1)) : tactic \u03b1 :=\n\u03bb s, timeit desc (t () s)\n\nmeta def trace_state : tactic unit :=\ndo s \u2190 read,\n   trace $ to_fmt s\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\n| all | semireducible | instances | reducible | none\n\nexport transparency (reducible semireducible)\n\n/-- (eval_expr \u03b1 e) evaluates 'e' IF 'e' has type '\u03b1'. -/\nmeta constant eval_expr (\u03b1 : Type u) [reflected \u03b1] : expr \u2192 tactic \u03b1\n\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. -/\nmeta constant result        : tactic expr\n/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to\n   `do { r \u2190 result, s \u2190 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. -/\nmeta constant format_result : tactic format\n/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/\nmeta constant target        : tactic expr\nmeta constant intro_core    : name \u2192 tactic expr\nmeta constant intron        : nat \u2192 tactic unit\n/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/\nmeta constant clear         : expr \u2192 tactic unit\n/-- `revert_lst : list expr \u2192 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 : \u2115, h : P(x) \u22a2 T(x)`, `revert_lst [x]` returns `2` and produces the state ` \u22a2 \u03a0 x, P(x) \u2192 T(x)`.\n -/\nmeta constant revert_lst    : list expr \u2192 tactic nat\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. -/\nmeta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr\n/-- (head) eta expand the given expression. `f : \u03b1 \u2192 \u03b2` head-eta-expands to `\u03bb a, f a`. If `f` isn't a function then it just returns `f`.  -/\nmeta constant head_eta_expand : expr \u2192 tactic expr\n/-- (head) beta reduction. `(\u03bb x, B) c` reduces to `B[x/c]`. -/\nmeta constant head_beta       : expr \u2192 tactic expr\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]`. -/\nmeta constant head_zeta       : expr \u2192 tactic expr\n/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/\nmeta constant zeta            : expr \u2192 tactic expr\n/-- (head) eta reduction. `(\u03bb x, f x)` reduces to `f`. -/\nmeta constant head_eta        : expr \u2192 tactic expr\n/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/\nmeta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit\n/-- Similar to `unify`, but it treats metavariables as constants. -/\nmeta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit\n/-- Infer the type of the given expression.\n   Remark: transparency does not affect type inference -/\nmeta constant infer_type    : expr \u2192 tactic expr\n\n/-- Get the `local_const` expr for the given `name`. -/\nmeta constant get_local     : name \u2192 tactic expr\n/-- Resolve a name using the current local context, environment, aliases, etc. -/\nmeta constant resolve_name  : name \u2192 tactic pexpr\n/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/\nmeta constant local_context : tactic (list expr)\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-/\nmeta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name\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 (\u03b1 : Type.{l_1}) (\u03b2 : \u03b1 -> Type.{l_2}), (Pi x : \u03b1, \u03b2 x) -> (Pi x : \u03b1, \u03b2 x) -> , Prop\n        nat     : Type\n        real    : Type\n        vec.{l} : Pi (\u03b1 : 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-/\nmeta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr\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} nat (a > b) (nat.decidable_gt a b) a b\n   ```\n-/\nmeta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr\n/-- (mk_congr_arg h\u2081 h\u2082) is a more efficient version of (mk_app `congr_arg [h\u2081, h\u2082]) -/\nmeta constant mk_congr_arg  : expr \u2192 expr \u2192 tactic expr\n/-- (mk_congr_fun h\u2081 h\u2082) is a more efficient version of (mk_app `congr_fun [h\u2081, h\u2082]) -/\nmeta constant mk_congr_fun  : expr \u2192 expr \u2192 tactic expr\n/-- (mk_congr h\u2081 h\u2082) is a more efficient version of (mk_app `congr [h\u2081, h\u2082]) -/\nmeta constant mk_congr      : expr \u2192 expr \u2192 tactic expr\n/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/\nmeta constant mk_eq_refl    : expr \u2192 tactic expr\n/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/\nmeta constant mk_eq_symm    : expr \u2192 tactic expr\n/-- (mk_eq_trans h\u2081 h\u2082) is a more efficient version of (mk_app `eq.trans [h\u2081, h\u2082]) -/\nmeta constant mk_eq_trans   : expr \u2192 expr \u2192 tactic expr\n/-- (mk_eq_mp h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mp [h\u2081, h\u2082]) -/\nmeta constant mk_eq_mp      : expr \u2192 expr \u2192 tactic expr\n/-- (mk_eq_mpr h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mpr [h\u2081, h\u2082]) -/\nmeta constant mk_eq_mpr      : expr \u2192 expr \u2192 tactic expr\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. -/\nmeta constant subst_core     : expr \u2192 tactic unit\n/-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to\n    the target type. -/\nmeta constant exact (e : expr) (md := semireducible) : tactic unit\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. -/\nmeta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr\n/-- Return true if the given expression is a type class. -/\nmeta constant is_class      : expr \u2192 tactic bool\n/-- Try to create an instance of the given type class. -/\nmeta constant mk_instance   : expr \u2192 tactic expr\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. -/\nmeta constant change (e : expr) (check : bool := tt): tactic unit\n/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/\nmeta constant assert_core   : name \u2192 expr \u2192 tactic unit\n/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/\nmeta constant assertv_core  : name \u2192 expr \u2192 expr \u2192 tactic unit\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. -/\nmeta constant define_core   : name \u2192 expr \u2192 tactic unit\n/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/\nmeta constant definev_core  : name \u2192 expr \u2192 expr \u2192 tactic unit\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. -/\nmeta constant rotate_left   : nat \u2192 tactic unit\n/-- Gets a list of metavariables, one for each goal. -/\nmeta constant get_goals     : tactic (list expr)\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.-/\nmeta constant set_goals     : list expr \u2192 tactic unit\n/-- Convenience function for creating ` for proofs. -/\nmeta def mk_tagged_proof (prop : expr) (pr : expr) (tag : name) : expr :=\nexpr.mk_app (expr.const ``id_tag []) [expr.const tag [], prop, pr]\n\n/-- How to order the new goals made from an `apply` tactic.\nSupposing we were applying `e : \u2200 (a:\u03b1) (p : P(a)), Q`\n- `non_dep_first` would produce goals `\u22a2 P(?m)`, `\u22a2 \u03b1`. 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 `\u22a2 P(?m)`.\n- `all` would produce goals `\u22a2 \u03b1`, `\u22a2 P(?m)`.\n-/\ninductive new_goals\n| non_dep_first | non_dep_only | all\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 :=\n(md            := semireducible)\n(approx        := tt)\n(new_goals     := new_goals.non_dep_first)\n(instances     := tt)\n(auto_param    := tt)\n(opt_param     := tt)\n(unify         := tt)\n/-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.\n    Supposing `e : \u03a0 (a\u2081:\u03b1\u2081) ... (a\u2099:\u03b1\u2099), P(a\u2081,...,a\u2099)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a\u2081,...?a\u2099)`.\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. -/\nmeta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name \u00d7 expr))\n/- Create a fresh meta universe variable. -/\nmeta constant mk_meta_univ  : tactic level\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. -/\nmeta constant mk_meta_var   : expr \u2192 tactic expr\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. -/\nmeta constant get_univ_assignment : level \u2192 tactic level\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. -/\nmeta constant get_assignment : expr \u2192 tactic expr\n/-- Return true if the given meta-variable is assigned.\n    Fail if argument is not a meta-variable. -/\nmeta constant is_assigned : expr \u2192 tactic bool\n/-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic.  -/\nmeta constant mk_fresh_name : tactic name\n\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` -/\nmeta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name \u00d7 list expr \u00d7 list (name \u00d7 expr)))\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. -/\nmeta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name \u00d7 list expr \u00d7 list (name \u00d7 expr)))\n/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/\nmeta constant destruct (e : expr) (md := semireducible) : tactic unit\n/-- Generalizes the target with respect to `e`.  -/\nmeta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit\n/-- instantiate assigned metavariables in the given expression -/\nmeta constant instantiate_mvars : expr \u2192 tactic expr\n/-- Add the given declaration to the environment -/\nmeta constant add_decl : declaration \u2192 tactic unit\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-/\nmeta constant set_env_core : environment \u2192 tactic unit\n/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/\nmeta constant set_env : environment \u2192 tactic unit\n/-- `doc_string env d k` returns the doc string for `d` (if available) -/\nmeta constant doc_string : name \u2192 tactic string\n/-- Set the docstring for the given declaration. -/\nmeta constant add_doc_string : name \u2192 string \u2192 tactic unit\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-/\nmeta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr\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. -/\nmeta constant olean_doc_strings : tactic (list (option string \u00d7 (list (pos \u00d7 string))))\n\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)` -/\nmeta def module_doc_strings : tactic (list (option name \u00d7 string)) :=\n  do\n    /- Obtain a list of top-level docs in current module. -/\n    mod_docs \u2190 olean_doc_strings,\n    let mod_docs: list (list (option name \u00d7 string)) :=\n      mod_docs.filter_map (\u03bb d,\n        if d.1.is_none\n          then some (d.2.map\n            (\u03bb pos_doc, \u27e8none, pos_doc.2\u27e9))\n          else none),\n    let mod_docs := mod_docs.join,\n    /- Obtain list of declarations in current module. -/\n    e \u2190 get_env,\n    let decls := environment.fold e ([]: list name)\n      (\u03bb d acc, let n := d.to_name in\n      if (environment.decl_olean e n).is_none\n        then n::acc else acc),\n    /- Map declarations to those which have docstrings. -/\n    decls \u2190 decls.mfoldl (\u03bba n,\n      (doc_string n >>=\n        \u03bb doc, pure $ (some n, doc) :: a)\n      <|> pure a) [],\n    pure (mod_docs ++ decls)\n\n/-- Set attribute `attr_name` for constant `c_name` with the given priority.\n   If the priority is none, then use default -/\nmeta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit\n/-- `unset_attribute attr_name c_name` -/\nmeta constant unset_attribute : name \u2192 name \u2192 tactic unit\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. -/\nmeta constant has_attribute : name \u2192 name \u2192 tactic (bool \u00d7 nat)\n\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`  -/\nmeta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit :=\ntry $ do\n  (p', prio) \u2190 has_attribute attr_name src,\n  let p := p.get_or_else p',\n  set_basic_attribute attr_name tgt p (some prio)\n\n/-- Name of the declaration currently being elaborated. -/\nmeta constant decl_name : tactic name\n\n/-- `save_type_info e ref` save (typeof e) at position associated with ref -/\nmeta constant save_type_info {elab : bool} : expr \u2192 expr elab \u2192 tactic unit\nmeta constant save_info_thunk : pos \u2192 (unit \u2192 format) \u2192 tactic unit\n/-- Return list of currently open namespaces -/\nmeta constant open_namespaces : tactic (list name)\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. -/\nmeta constant kdepends_on (e t : expr) (md := reducible) : tactic bool\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. -/\nmeta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr\n\n/-- Blocks the execution of the current thread for at least `msecs` milliseconds.\n    This tactic is used mainly for debugging purposes. -/\nmeta constant sleep (msecs : nat) : tactic unit\n\n/-- Type check `e` with respect to the current goal.\n    Fails if `e` is not type correct. -/\nmeta constant type_check (e : expr) (md := semireducible) : tactic unit\nopen list nat\n\n/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/\ndef tag : Type := list name\n\n/-- Enable/disable goal tagging.  -/\nmeta constant enable_tags (b : bool) : tactic unit\n/-- Return tt iff goal tagging is enabled. -/\nmeta constant tags_enabled : tactic bool\n/-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled.\n    Remark: `set_goal g []` removes the tag -/\nmeta constant set_tag (g : expr) (t : tag) : tactic unit\n/-- Return tag associated with `g`. Return `[]` if there is no tag. -/\nmeta constant get_tag (g : expr) : tactic tag\n\n/-! By default, Lean only considers local instances in the header of declarations.\n    This has two main benefits.\n    1- Results produced by the type class resolution procedure can be easily cached.\n    2- The set of local instances does not have to be recomputed.\n\n    This approach has the following disadvantages:\n    1- Frozen local instances cannot be reverted.\n    2- Local instances defined inside of a declaration are not considered during type\n       class resolution.\n-/\n\n/--\nAvoid this function!  Use `unfreezingI`/`resetI`/etc. instead!\n\nUnfreezes the current set of local instances.\nAfter this tactic, the instance cache is disabled.\n-/\nmeta constant unfreeze_local_instances : tactic unit\n/--\nFreeze the current set of local instances.\n-/\nmeta constant freeze_local_instances : tactic unit\n/- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/\nmeta constant frozen_local_instances : tactic (option (list expr))\n\n/-- Run the provided tactic, associating it to the given AST node. -/\nmeta constant with_ast {\u03b1 : Type u} (ast : \u2115) (t : tactic \u03b1) : tactic \u03b1\n\nmeta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=\ninduction h ns rec md >> return ()\n\n/-- Remark: set_goals will erase any solved goal -/\nmeta def cleanup : tactic unit :=\nget_goals >>= set_goals\n\n/-- Auxiliary definition used to implement begin ... end blocks -/\nmeta def step {\u03b1 : Type u} (t : tactic \u03b1) : tactic unit :=\nt >>[tactic] cleanup\n\nmeta def istep {\u03b1 : Type u} (line0 col0 line col ast : \u2115) (t : tactic \u03b1) : tactic unit :=\n\u03bb s, (@scope_trace _ line col (\u03bb _, with_ast ast (step t) s)).clamp_pos line0 line col\n\nmeta def is_prop (e : expr) : tactic bool :=\ndo t \u2190 infer_type e,\n   return (t = `(Prop))\n\n/-- Return true iff n is the name of declaration that is a proposition. -/\nmeta def is_prop_decl (n : name) : tactic bool :=\ndo env \u2190 get_env,\n   d   \u2190 env.get n,\n   t   \u2190 return $ d.type,\n   is_prop t\n\nmeta def is_proof (e : expr) : tactic bool :=\ninfer_type e >>= is_prop\n\nmeta def whnf_no_delta (e : expr) : tactic expr :=\nwhnf e transparency.none\n\n/-- Return `e` in weak head normal form with respect to the given transparency setting,\n    or `e` head is a generalized constructor or inductive datatype. -/\nmeta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr :=\nwhnf e md ff\n\nmeta def whnf_target : tactic unit :=\ntarget >>= whnf >>= change\n/-- Change the target of the main goal.\n   The input expression must be definitionally equal to the current target.\n   The tactic does not check whether `e`\n   is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/\nmeta def unsafe_change (e : expr) : tactic unit :=\nchange e ff\n\n/-- Pi or elet introduction.\nGiven the tactic state `\u22a2 \u03a0 x : \u03b1, Y`, ``intro `hello`` will produce the state `hello : \u03b1 \u22a2 Y[x/hello]`.\nReturns the new local constant. Similarly for `elet` expressions.\nIf the target is not a Pi or elet it will try to put it in WHNF.\n -/\nmeta def intro (n : name) : tactic expr :=\ndo t \u2190 target,\n   if expr.is_pi t \u2228 expr.is_let t then intro_core n\n   else whnf_target >> intro_core n\n\n/--\nA variant of `intro` which makes sure that the introduced hypothesis's name is\nunique in the context. If there is no hypothesis named `n` in the context yet,\n`intro_fresh n` is the same as `intro n`. If there is already a hypothesis named\n`n`, the new hypothesis is named `n_1` (or `n_2` if `n_1` already exists, etc.).\nIf `offset` is given, the new names are `n_offset`, `n_offset+1` etc.\n\nIf `n` is `_`, `intro_fresh n` is the same as `intro1`. The `offset` is ignored\nin this case.\n-/\nmeta def intro_fresh (n : name) (offset : option nat := none) : tactic expr :=\n  if n = `_\n    then intro `_\n    else do\n      n \u2190 get_unused_name n offset,\n      intro n\n\n/-- Like `intro` except the name is derived from the bound name in the \u03a0. -/\nmeta def intro1 : tactic expr :=\nintro `_\n\n/-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction. -/\nmeta def intros : tactic (list expr) :=\ndo t \u2190 target,\nmatch t with\n| expr.pi   _ _ _ _ := do H \u2190 intro1, Hs \u2190 intros, return (H :: Hs)\n| expr.elet _ _ _ _ := do H \u2190 intro1, Hs \u2190 intros, return (H :: Hs)\n| _                 := return []\nend\n\n/-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/\nmeta def intro_lst (ns : list name) : tactic (list expr) :=\nns.mmap intro\n\n/--\nA variant of `intro_lst` which makes sure that the introduced hypotheses' names\nare unique in the context. See `intro_fresh`.\n-/\nmeta def intro_lst_fresh (ns : list name) : tactic (list expr) :=\nns.mmap intro_fresh\n\n/-- Introduces new hypotheses with forward dependencies.  -/\nmeta def intros_dep : tactic (list expr) :=\ndo t \u2190 target,\n   let proc (b : expr) :=\n      if b.has_var_idx 0 then\n        do h \u2190 intro1, hs \u2190 intros_dep, return (h::hs)\n      else\n        -- body doesn't depend on new hypothesis\n        return [],\n   match t with\n   | expr.pi _ _ _ b   := proc b\n   | expr.elet _ _ _ b := proc b\n   | _                 := return []\n   end\n\nmeta def introv : list name \u2192 tactic (list expr)\n| []      := intros_dep\n| (n::ns) := do hs \u2190 intros_dep, h \u2190 intro n, hs' \u2190 introv ns, return (hs ++ h :: hs')\n\n/--\n`intron' n` introduces `n` hypotheses and returns the resulting local\nconstants. Fails if there are not at least `n` arguments to introduce. If you do\nnot need the return value, use `intron`.\n-/\nmeta def intron' (n : \u2115) : tactic (list expr)\n:= iterate_exactly n intro1\n\n/--\nLike `intron'` but the introduced hypotheses' names are derived from `base`,\ni.e. `base`, `base_1` etc. The new names are unique in the context. If `offset`\nis given, the new names will be `base_offset`, `base_offset+1` etc.\n-/\nmeta def intron_base (n : \u2115) (base : name) (offset : option nat := none)\n  : tactic (list expr)\n:= iterate_exactly n (intro_fresh base offset)\n\n/--\n`intron_with i ns base offset` introduces `i` hypotheses using the names from\n`ns`. If `ns` contains less than `i` names, the remaining hypotheses' names are\nderived from `base` and `offset` (as with `intron_base`). If `base` is `_`, the\nnames are derived from the \u03a0 binder names.\n\nReturns the introduced local constants and the remaining names from `ns` (if\n`ns` contains more than `i` names).\n-/\nmeta def intron_with\n  : \u2115 \u2192 list name \u2192 opt_param name `_ \u2192 opt_param (option \u2115) none\n  \u2192 tactic (list expr \u00d7 list name)\n| 0 ns _ _ := pure ([], ns)\n| (i + 1) [] base offset := do\n  hs \u2190 intron_base (i + 1) base offset,\n  pure (hs, [])\n| (i + 1) (n :: ns) base offset := do\n  h \u2190 intro n,\n  \u27e8hs, rest\u27e9 \u2190 intron_with i ns base offset,\n  pure (h :: hs, rest)\n\n/-- Returns n fully qualified if it refers to a constant, or else fails. -/\nmeta def resolve_constant (n : name) : tactic name :=\ndo e \u2190 resolve_name n,\n   match e with\n   | expr.const n _ := pure n\n   | _ := do\n     e \u2190 to_expr e tt ff,\n     expr.const n _ \u2190 pure $ e.get_app_fn,\n     pure n\n   end\n\nmeta def to_expr_strict (q : pexpr) : tactic expr :=\nto_expr q\n\n/--\nExample: with `x : \u2115, h : P(x) \u22a2 T(x)`, `revert x` returns `2` and produces the state ` \u22a2 \u03a0 x, P(x) \u2192 T(x)`.\n -/\nmeta def revert (l : expr) : tactic nat :=\nrevert_lst [l]\n\n/- Revert \"all\" hypotheses. Actually, the tactic only reverts\n   hypotheses occurring after the last frozen local instance.\n   Recall that frozen local instances cannot be reverted,\n   use `unfreezing revert_all` instead. -/\nmeta def revert_all : tactic nat :=\ndo lctx \u2190 local_context,\n   lis  \u2190 frozen_local_instances,\n   match lis with\n   | none           := revert_lst lctx\n   | some []        := revert_lst lctx\n                       /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/\n   | some (hi::his) := revert_lst $ lctx.foldl (\u03bb r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) []\n   end\n\nmeta def clear_lst : list name \u2192 tactic unit\n| []      := skip\n| (n::ns) := do H \u2190 get_local n, clear H, clear_lst ns\n\nmeta def match_not (e : expr) : tactic expr :=\nmatch (expr.is_not e) with\n| (some a) := return a\n| none     := fail \"expression is not a negation\"\nend\n\nmeta def match_and (e : expr) : tactic (expr \u00d7 expr) :=\nmatch (expr.is_and e) with\n| (some (\u03b1, \u03b2)) := return (\u03b1, \u03b2)\n| none     := fail \"expression is not a conjunction\"\nend\n\nmeta def match_or (e : expr) : tactic (expr \u00d7 expr) :=\nmatch (expr.is_or e) with\n| (some (\u03b1, \u03b2)) := return (\u03b1, \u03b2)\n| none     := fail \"expression is not a disjunction\"\nend\n\nmeta def match_iff (e : expr) : tactic (expr \u00d7 expr) :=\nmatch (expr.is_iff e) with\n| (some (lhs, rhs)) := return (lhs, rhs)\n| none              := fail \"expression is not an iff\"\nend\n\nmeta def match_eq (e : expr) : tactic (expr \u00d7 expr) :=\nmatch (expr.is_eq e) with\n| (some (lhs, rhs)) := return (lhs, rhs)\n| none              := fail \"expression is not an equality\"\nend\n\nmeta def match_ne (e : expr) : tactic (expr \u00d7 expr) :=\nmatch (expr.is_ne e) with\n| (some (lhs, rhs)) := return (lhs, rhs)\n| none              := fail \"expression is not a disequality\"\nend\n\nmeta def match_heq (e : expr) : tactic (expr \u00d7 expr \u00d7 expr \u00d7 expr) :=\ndo match (expr.is_heq e) with\n| (some (\u03b1, lhs, \u03b2, rhs)) := return (\u03b1, lhs, \u03b2, rhs)\n| none                    := fail \"expression is not a heterogeneous equality\"\nend\n\nmeta def match_refl_app (e : expr) : tactic (name \u00d7 expr \u00d7 expr) :=\ndo env \u2190 get_env,\nmatch (environment.is_refl_app env e) with\n| (some (R, lhs, rhs)) := return (R, lhs, rhs)\n| none                 := fail \"expression is not an application of a reflexive relation\"\nend\n\nmeta def match_app_of (e : expr) (n : name) : tactic (list expr) :=\nguard (expr.is_app_of e n) >> return e.get_app_args\n\nmeta def get_local_type (n : name) : tactic expr :=\nget_local n >>= infer_type\n\nmeta def trace_result : tactic unit :=\nformat_result >>= trace\n\nmeta def rexact (e : expr) : tactic unit :=\nexact e reducible\n\nmeta def any_hyp_aux {\u03b1 : Type} (f : expr \u2192 tactic \u03b1) : list expr \u2192 tactic \u03b1\n| []        := failed\n| (h :: hs) := f h <|> any_hyp_aux hs\n\nmeta def any_hyp {\u03b1 : Type} (f : expr \u2192 tactic \u03b1) : tactic \u03b1 :=\nlocal_context >>= any_hyp_aux f\n\n/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/\nmeta def find_same_type : expr \u2192 list expr \u2192 tactic expr\n| e []         := failed\n| e (H :: Hs) :=\n  do t \u2190 infer_type H,\n     (unify e t >> return H) <|> find_same_type e Hs\n\nmeta def find_assumption (e : expr) : tactic expr :=\ndo ctx \u2190 local_context, find_same_type e ctx\n\nmeta def assumption : tactic unit :=\ndo { ctx \u2190 local_context,\n     t   \u2190 target,\n     H   \u2190 find_same_type t ctx,\n     exact H }\n<|> fail \"assumption tactic failed\"\n\nmeta def save_info (p : pos) : tactic unit :=\ndo s \u2190 read,\n   tactic.save_info_thunk p (\u03bb _, tactic_state.to_format s)\n\nnotation `\u2039` p `\u203a` := (by assumption : p)\n\n/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/\nmeta def swap : tactic unit :=\ndo gs \u2190 get_goals,\n   match gs with\n   | (g\u2081 :: g\u2082 :: rs) := set_goals (g\u2082 :: g\u2081 :: rs)\n   | e                := skip\n   end\n\n/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/\nmeta def assert (h : name) (t : expr) : tactic expr :=\ndo assert_core h t, swap, e \u2190 intro h, swap, return e\n\n/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/\nmeta def assertv (h : name) (t : expr) (v : expr) : tactic expr :=\nassertv_core h t v >> intro h\n\n/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/\nmeta def define  (h : name) (t : expr) : tactic expr :=\ndo define_core h t, swap, e \u2190 intro h, swap, return e\n\n/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/\nmeta def definev (h : name) (t : expr) (v : expr) : tactic expr :=\ndefinev_core h t v >> intro h\n\n/-- Add `h : t := pr` to the current goal -/\nmeta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr :=\nlet dv := \u03bbt, definev h t pr in\noption.cases_on t (infer_type pr >>= dv) dv\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) : tactic expr :=\nlet dv := \u03bbt, assertv h t pr in\noption.cases_on t (infer_type pr >>= dv) dv\n\n/-- Return the number of goals that need to be solved -/\nmeta def num_goals     : tactic nat :=\ndo gs \u2190 get_goals,\n   return (length gs)\n\n/-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times.\n[NOTE] We have to provide the instance argument `[has_mod nat]` because\n   mod for nat was not defined yet -/\nmeta def rotate_right (n : nat) [has_mod nat] : tactic unit :=\ndo ng \u2190 num_goals,\n   if ng = 0 then skip\n   else rotate_left (ng - n % ng)\n\n/-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/\nmeta def rotate : nat \u2192 tactic unit :=\nrotate_left\n\nprivate meta def repeat_aux (t : tactic unit) : list expr \u2192 list expr \u2192 tactic unit\n| []      r := set_goals r.reverse\n| (g::gs) r := do\n  ok \u2190 try_core (set_goals [g] >> t),\n  match ok with\n  | none := repeat_aux gs (g::r)\n  | _    := do\n    gs' \u2190 get_goals,\n    repeat_aux (gs' ++ gs) r\n  end\n\n/-- This tactic is applied to each goal. If the application succeeds,\n    the tactic is applied recursively to all the generated subgoals until it eventually fails.\n    The recursion stops in a subgoal when the tactic has failed to make progress.\n    The tactic `repeat` never fails. -/\nmeta def repeat (t : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals, repeat_aux t gs []\n\n/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.\n   The tactic fails if all t_i's fail. -/\nmeta def first {\u03b1 : Type u} : list (tactic \u03b1) \u2192 tactic \u03b1\n| []      := fail \"first tactic failed, no more alternatives\"\n| (t::ts) := t <|> first ts\n\n/-- Applies the given tactic to the main goal and fails if it is not solved. -/\nmeta def solve1 {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\ndo gs \u2190 get_goals,\n   match gs with\n   | []      := fail \"solve1 tactic failed, there isn't any goal left to focus\"\n   | (g::rs) :=\n     do set_goals [g],\n        a \u2190 tac,\n        gs' \u2190 get_goals,\n        match gs' with\n        | [] := set_goals rs >> pure a\n        | gs := fail \"solve1 tactic failed, focused goal has not been solved\"\n        end\n   end\n\n/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/\nmeta def solve {\u03b1} (ts : list (tactic \u03b1)) : tactic \u03b1 :=\nfirst $ map solve1 ts\n\nprivate meta def focus_aux {\u03b1} : list (tactic \u03b1) \u2192 list expr \u2192 list expr \u2192 tactic (list \u03b1)\n| []       []      rs := set_goals rs *> pure []\n| (t::ts)  []      rs := fail \"focus tactic failed, insufficient number of goals\"\n| tts      (g::gs) rs :=\n  mcond (is_assigned g) (focus_aux tts gs rs) $\n    do set_goals [g],\n       t::ts \u2190 pure tts | fail \"focus tactic failed, insufficient number of tactics\",\n       a \u2190 t,\n       rs' \u2190 get_goals,\n       as \u2190 focus_aux ts gs (rs ++ rs'),\n       pure $ a :: as\n\n/--\n`focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of\ngoals is not n. Returns the results of t_i (one per goal).\n-/\nmeta def focus {\u03b1} (ts : list (tactic \u03b1)) : tactic (list \u03b1) :=\ndo gs \u2190 get_goals, focus_aux ts gs []\n\nprivate meta def focus'_aux : list (tactic unit) \u2192 list expr \u2192 list expr \u2192 tactic unit\n| []       []      rs := set_goals rs\n| (t::ts)  []      rs := fail \"focus' tactic failed, insufficient number of goals\"\n| tts      (g::gs) rs :=\n  mcond (is_assigned g) (focus'_aux tts gs rs) $\n    do set_goals [g],\n       t::ts \u2190 pure tts | fail \"focus' tactic failed, insufficient number of tactics\",\n       t,\n       rs' \u2190 get_goals,\n       focus'_aux ts gs (rs ++ rs')\n\n/-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/\nmeta def focus' (ts : list (tactic unit)) : tactic unit :=\ndo gs \u2190 get_goals, focus'_aux ts gs []\n\nmeta def focus1 {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\ndo g::gs \u2190 get_goals,\n   match gs with\n   | [] := tac\n   | _  := do\n      set_goals [g],\n      a \u2190 tac,\n      gs' \u2190 get_goals,\n      set_goals (gs' ++ gs),\n      return a\n   end\n\nprivate meta def all_goals_core {\u03b1} (tac : tactic \u03b1)\n  : list expr \u2192 list expr \u2192 tactic (list \u03b1)\n| []        ac := set_goals ac *> pure []\n| (g :: gs) ac :=\n  mcond (is_assigned g) (all_goals_core gs ac) $\n    do set_goals [g],\n       a \u2190 tac,\n       new_gs \u2190 get_goals,\n       as \u2190 all_goals_core gs (ac ++ new_gs),\n       pure $ a :: as\n\n/--\nApply the given tactic to all goals. Return one result per goal.\n-/\nmeta def all_goals {\u03b1} (tac : tactic \u03b1) : tactic (list \u03b1) :=\ndo gs \u2190 get_goals,\n   all_goals_core tac gs []\n\nprivate meta def all_goals'_core (tac : tactic unit) : list expr \u2192 list expr \u2192 tactic unit\n| []        ac := set_goals ac\n| (g :: gs) ac :=\n  mcond (is_assigned g) (all_goals'_core gs ac) $\n    do set_goals [g],\n       tac,\n       new_gs \u2190 get_goals,\n       all_goals'_core gs (ac ++ new_gs)\n\n/-- Apply the given tactic to all goals. -/\nmeta def all_goals' (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   all_goals'_core tac gs []\n\nprivate meta def any_goals_core {\u03b1} (tac : tactic \u03b1) : list expr \u2192 list expr \u2192 bool \u2192 tactic (list (option \u03b1))\n| []        ac progress := guard progress *> set_goals ac *> pure []\n| (g :: gs) ac progress :=\n  mcond (is_assigned g) (any_goals_core gs ac progress) $\n    do set_goals [g],\n       res \u2190 try_core tac,\n       new_gs \u2190 get_goals,\n       ress \u2190 any_goals_core gs (ac ++ new_gs) (res.is_some || progress),\n       pure $ res :: ress\n\n/--\nApply `tac` to any goal where it succeeds. The tactic succeeds if `tac`\nsucceeds for at least one goal. The returned list contains the result of `tac`\nfor each goal: `some a` if tac succeeded, or `none` if it did not.\n-/\nmeta def any_goals {\u03b1} (tac : tactic \u03b1) : tactic (list (option \u03b1)) :=\ndo gs \u2190 get_goals,\n   any_goals_core tac gs [] ff\n\nprivate meta def any_goals'_core (tac : tactic unit) : list expr \u2192 list expr \u2192 bool \u2192 tactic unit\n| []        ac progress := guard progress >> set_goals ac\n| (g :: gs) ac progress :=\n  mcond (is_assigned g) (any_goals'_core gs ac progress) $\n    do set_goals [g],\n       succeeded \u2190 try_core tac,\n       new_gs    \u2190 get_goals,\n       any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress)\n\n/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if\n   tac succeeds for at least one goal. -/\nmeta def any_goals' (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   any_goals'_core tac gs [] ff\n\n/--\nLCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies\n`tac2` to each goal produced by `tac1`.\n-/\nmeta def seq {\u03b1 \u03b2} (tac1 : tactic \u03b1) (tac2 : \u03b1 \u2192 tactic \u03b2) : tactic (list \u03b2) :=\ndo g::gs \u2190 get_goals,\n   set_goals [g],\n   a \u2190 tac1,\n   bs \u2190 all_goals $ tac2 a,\n   gs' \u2190 get_goals,\n   set_goals (gs' ++ gs),\n   pure bs\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 : tactic unit) (tac2 : tactic unit) : tactic unit :=\ndo g::gs \u2190 get_goals,\n   set_goals [g],\n   tac1, all_goals' tac2,\n   gs' \u2190 get_goals,\n   set_goals (gs' ++ gs)\n\n/--\nApplies `tac1` to the main goal, then applies each of the tactics in `tacs2` to\none of the produced subgoals (like `focus'`).\n-/\nmeta def seq_focus {\u03b1 \u03b2} (tac1 : tactic \u03b1) (tacs2 : \u03b1 \u2192 list (tactic \u03b2)) : tactic (list \u03b2) :=\ndo g::gs \u2190 get_goals,\n   set_goals [g],\n   a \u2190 tac1,\n   bs \u2190 focus $ tacs2 a,\n   gs' \u2190 get_goals,\n   set_goals (gs' ++ gs),\n   pure bs\n\n/--\nApplies `tac1` to the main goal, then applies each of the tactics in `tacs2` to\none of the produced subgoals (like `focus`).\n-/\nmeta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit :=\ndo g::gs \u2190 get_goals,\n   set_goals [g],\n   tac1, focus tacs2,\n   gs' \u2190 get_goals,\n   set_goals (gs' ++ gs)\n\nmeta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) :=\n\u27e8seq'\u27e9\n\nmeta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) :=\n\u27e8seq_focus'\u27e9\n\nmeta constant is_trace_enabled_for : name \u2192 bool\n\n/-- Execute tac only if option trace.n is set to true. -/\nmeta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=\nwhen (is_trace_enabled_for n = tt) tac\n\n/-- Fail if there are no remaining goals. -/\nmeta def fail_if_no_goals : tactic unit :=\ndo n \u2190 num_goals,\n   when (n = 0) (fail \"tactic failed, there are no goals to be solved\")\n\n/-- Fail if there are unsolved goals. -/\nmeta def done : tactic unit :=\ndo n \u2190 num_goals,\n   when (n \u2260 0) (fail \"done tactic failed, there are unsolved goals\")\n\nmeta def apply_opt_param : tactic unit :=\ndo `(opt_param %%t %%v) \u2190 target,\n   exact v\n\nmeta def apply_auto_param : tactic unit :=\ndo `(auto_param %%type %%tac_name_expr) \u2190 target,\n   change type,\n   tac_name \u2190 eval_expr name tac_name_expr,\n   tac \u2190 eval_expr (tactic unit) (expr.const tac_name []),\n   tac\n\nmeta def has_opt_auto_param (ms : list expr) : tactic bool :=\nms.mfoldl\n (\u03bb r m, do type \u2190 infer_type m,\n            return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)\n ff\n\nmeta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit :=\nwhen (cfg.auto_param || cfg.opt_param) $\nmwhen (has_opt_auto_param ms) $ do\n  gs \u2190 get_goals,\n  ms.mmap' (\u03bb m, mwhen (bnot <$> is_assigned m) $\n                   set_goals [m] >>\n                   when cfg.opt_param (try apply_opt_param) >>\n                   when cfg.auto_param (try apply_auto_param)),\n  set_goals gs\n\nmeta def has_opt_auto_param_for_apply (ms : list (name \u00d7 expr)) : tactic bool :=\nms.mfoldl\n (\u03bb r m, do type \u2190 infer_type m.2,\n            return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)\n ff\n\nmeta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name \u00d7 expr)) : tactic unit :=\nmwhen (has_opt_auto_param_for_apply ms) $ do\n  gs \u2190 get_goals,\n  ms.mmap' (\u03bb m, mwhen (bnot <$> (is_assigned m.2)) $\n                   set_goals [m.2] >>\n                   when cfg.opt_param (try apply_opt_param) >>\n                   when cfg.auto_param (try apply_auto_param)),\n  set_goals gs\n\nmeta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name \u00d7 expr)) :=\ndo r \u2190 apply_core e cfg,\n   try_apply_opt_auto_param_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 \u00d7 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 \u00d7 expr)) :=\napply e {new_goals := new_goals.non_dep_only}\n\n/-- Try to solve the main goal using type class resolution. -/\nmeta def apply_instance : tactic unit :=\ndo tgt \u2190 target >>= instantiate_mvars,\n   b   \u2190 is_class tgt,\n   if b then mk_instance tgt >>= exact\n   else fail \"apply_instance tactic fail, target is not a type class\"\n\n/-- Create a list of universe meta-variables of the given size. -/\nmeta def mk_num_meta_univs : nat \u2192 tactic (list level)\n| 0        := return []\n| (succ n) := do\n  l  \u2190 mk_meta_univ,\n  ls \u2190 mk_num_meta_univs n,\n  return (l::ls)\n\n/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/\nmeta def mk_const (c : name) : tactic expr :=\ndo env  \u2190 get_env,\n   decl \u2190 env.get c,\n   let num := decl.univ_params.length,\n   ls   \u2190 mk_num_meta_univs num,\n   return (expr.const c ls)\n\n/-- Apply the constant `c` -/\nmeta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit :=\ndo c \u2190 mk_const c, apply c cfg, skip\n\nmeta def eapplyc (c : name) : tactic unit :=\ndo c \u2190 mk_const c, eapply c, skip\n\nmeta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit :=\ntry (do c \u2190 mk_const n, save_type_info c ref)\n\n/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,\n   and return metavariable `?M : ?T`.\n   This action can be used to create a meta-variable when\n   we don't know its type at creation time -/\nmeta def mk_mvar : tactic expr :=\ndo u \u2190 mk_meta_univ,\n   t \u2190 mk_meta_var (expr.sort u),\n   mk_meta_var t\n\n/-- Makes a sorry macro with a meta-variable as its type. -/\nmeta def mk_sorry : tactic expr := do\nu \u2190 mk_meta_univ,\nt \u2190 mk_meta_var (expr.sort u),\nreturn $ expr.mk_sorry t\n\n/-- Closes the main goal using sorry. -/\nmeta def admit : tactic unit :=\ntarget >>= exact \u2218 expr.mk_sorry\n\nmeta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do\nuniq_name \u2190 mk_fresh_name,\nreturn $ expr.local_const uniq_name pp_name bi type\n\nmeta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=\nmk_local' pp_name binder_info.default type\n\nmeta def mk_local_pis : expr \u2192 tactic (list expr \u00d7 expr)\n| (expr.pi n bi d b) := do\n  p \u2190 mk_local' n bi d,\n  (ps, r) \u2190 mk_local_pis (expr.instantiate_var b p),\n  return ((p :: ps), r)\n| e := return ([], e)\n\nprivate meta def get_pi_arity_aux : expr \u2192 tactic nat\n| (expr.pi n bi d b) :=\n  do m     \u2190 mk_fresh_name,\n     let l := expr.local_const m n bi d,\n     new_b \u2190 whnf (expr.instantiate_var b l),\n     r     \u2190 get_pi_arity_aux new_b,\n     return (r + 1)\n| e                  := return 0\n\n/-- Compute the arity of the given (Pi-)type -/\nmeta def get_pi_arity (type : expr) : tactic nat :=\nwhnf type >>= get_pi_arity_aux\n\n/-- Compute the arity of the given function -/\nmeta def get_arity (fn : expr) : tactic nat :=\ninfer_type fn >>= get_pi_arity\n\nmeta def triv : tactic unit := mk_const `trivial >>= exact\n\nnotation `dec_trivial` := of_as_true (by tactic.triv)\n\nmeta def by_contradiction (H : name) : tactic expr :=\ndo tgt \u2190 target,\n  tgt_wh \u2190 whnf tgt reducible, -- to ensure that `not` in `ne` is found\n  (match_not tgt_wh $> ()) <|>\n  (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|>\n  (mk_mapp `classical.by_contradiction [some tgt] >>= eapply >> skip) <|>\n  fail \"tactic by_contradiction failed, target is not a proposition\",\n  intro H\n\nprivate meta def generalizes_aux (md : transparency) : list expr \u2192 tactic unit\n| []      := skip\n| (e::es) := generalize e `x md >> generalizes_aux es\n\nmeta def generalizes (es : list expr) (md := semireducible) : tactic unit :=\ngeneralizes_aux md es\n\nprivate meta def kdependencies_core (e : expr) (md : transparency) : list expr \u2192 list expr \u2192 tactic (list expr)\n| []      r := return r\n| (h::hs) r :=\n  do type \u2190 infer_type h,\n     d \u2190 kdepends_on type e md,\n     if d then kdependencies_core hs (h::r)\n     else kdependencies_core hs r\n\n/-- Return all hypotheses that depends on `e`\n    The dependency test is performed using `kdepends_on` with the given transparency setting. -/\nmeta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=\ndo ctx \u2190 local_context, kdependencies_core e md ctx []\n\n/-- Revert all hypotheses that depend on `e` -/\nmeta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=\nkdependencies e md >>= revert_lst\n\nmeta def revert_kdeps (e : expr) (md := reducible) :=\nrevert_kdependencies e md\n\n/-- Postprocess the output of `cases_core`:\n\n- The third component of each tuple in the input list (the list of\n  substitutions) is dropped since we don't use it anywhere.\n- The second component (the list of new hypotheses) is filtered: any expression\n  that is not a local constant is dropped. We only use the new hypotheses for\n  the renaming functionality of `case`, so we want to keep only those\n  \"new hypotheses\" that are, in fact, local constants. -/\nprivate meta def cases_postprocess (hs : list (name \u00d7 list expr \u00d7 list (name \u00d7 expr)))\n  : list (name \u00d7 list expr) :=\nhs.map $ \u03bb \u27e8n, hs, _\u27e9, (n, hs.filter (\u03bb h, h.is_local_constant))\n\n/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.\n    Remark, it reverts dependencies using `revert_kdeps`.\n\n    Two different transparency modes are used `md` and `dmd`.\n    The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`.\n\n    It returns the constructor names associated with each new goal and the newly\n    introduced hypotheses. Note that while `cases_core` may return \"new\n    hypotheses\" that are not local constants, this tactic only returns local\n    constants.\n-/\nmeta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name \u00d7 list expr)) :=\nif e.is_local_constant then\n  do r \u2190 cases_core e ids md, return $ cases_postprocess r\nelse do\n  n \u2190 revert_kdependencies e dmd,\n  x \u2190 get_unused_name,\n  (tactic.generalize e x dmd)\n  <|>\n  (do t \u2190 infer_type e,\n      tactic.assertv x t e,\n      get_local x >>= tactic.revert,\n      return ()),\n  h \u2190 tactic.intro1,\n  focus1 $ do\n    r \u2190 cases_core h ids md,\n    hs' \u2190 all_goals (intron' n),\n    return $ cases_postprocess $ r.map\u2082 (\u03bb \u27e8n, hs, x\u27e9 hs', (n, hs ++ hs', x)) hs'\n\n/-- The same as `exact` except you can add proof holes. -/\nmeta def refine (e : pexpr) : tactic unit :=\ndo tgt : expr \u2190 target,\n   to_expr ``(%%e : %%tgt) tt >>= exact\n\n/--\n`by_cases p h` splits the main goal into two cases, assuming `h : p` in the\nfirst branch, and `h : \u00ac p` in the second branch. The expression `p` needs to\nbe a proposition.\n\nThe produced proof term is `dite p ?m_1 ?m_2`.\n-/\nmeta def by_cases (e : expr) (h : name) : tactic unit := do\ndec_e \u2190 mk_app ``decidable [e] <|> fail \"by_cases tactic failed, type is not a proposition\",\ninst \u2190 mk_instance dec_e <|> pure `(classical.prop_decidable %%e),\ntgt \u2190 target,\nexpr.sort tgt_u \u2190 infer_type tgt >>= whnf,\ng1 \u2190 mk_meta_var (e.imp tgt),\ng2 \u2190 mk_meta_var (`(\u00ac %%e).imp tgt),\nfocus1 $ do\n  exact $ expr.const ``dite [tgt_u] tgt e inst g1 g2,\n  set_goals [g1, g2],\n  all_goals' $ intro h >> skip\n\nmeta def funext_core : list name \u2192 bool \u2192 tactic unit\n| []  tt       := return ()\n| ids only_ids := try $\n   do some (lhs, rhs) \u2190 expr.is_eq <$> (target >>= whnf),\n      applyc `funext,\n      id \u2190 if ids.empty \u2228 ids.head = `_ then do\n             (expr.lam n _ _ _) \u2190 whnf lhs\n               | pure `_,\n             return n\n           else return ids.head,\n      intro id,\n      funext_core ids.tail only_ids\n\nmeta def funext : tactic unit :=\nfunext_core [] ff\n\nmeta def funext_lst (ids : list name) : tactic unit :=\nfunext_core ids tt\n\nprivate meta def get_undeclared_const (env : environment) (base : name) : \u2115 \u2192 name | i :=\nlet n := base <.> (\"_aux_\" ++ repr i) in\nif \u00acenv.contains n then n\nelse get_undeclared_const (i+1)\n\nmeta def new_aux_decl_name : tactic name := do\nenv \u2190 get_env, n \u2190 decl_name,\nreturn $ get_undeclared_const env n 1\n\nprivate meta def mk_aux_decl_name : option name \u2192 tactic name\n| none          := new_aux_decl_name\n| (some suffix) := do p \u2190 decl_name, return $ p ++ suffix\n\nmeta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=\ndo fail_if_no_goals,\n   gs \u2190 get_goals,\n   type \u2190 if zeta_reduce then target >>= zeta else target,\n   is_lemma \u2190 is_prop type,\n   m \u2190 mk_meta_var type,\n   set_goals [m],\n   tac,\n   n \u2190 num_goals,\n   when (n \u2260 0) (fail \"abstract tactic failed, there are unsolved goals\"),\n   set_goals gs,\n   val \u2190 instantiate_mvars m,\n   val \u2190 if zeta_reduce then zeta val else return val,\n   c   \u2190 mk_aux_decl_name suffix,\n   e   \u2190 add_aux_decl c type val is_lemma,\n   exact e\n\n/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/\nmeta def solve_aux {\u03b1 : Type} (type : expr) (tac : tactic \u03b1) : tactic (\u03b1 \u00d7 expr) :=\ndo m \u2190 mk_meta_var type,\n   gs \u2190 get_goals,\n   set_goals [m],\n   a \u2190 tac,\n   set_goals gs,\n   return (a, m)\n\n/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/\nmeta def in_open_namespaces (d : name) : tactic bool :=\ndo ns  \u2190 open_namespaces,\n   env \u2190 get_env,\n   return $ ns.any (\u03bb n, n.is_prefix_of d) && env.contains d\n\n/-- Execute tac for 'max' \"heartbeats\". The heartbeat is approx. the maximum number of\n    memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting\n    long running tactics. -/\nmeta def try_for {\u03b1} (max : nat) (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s,\nmatch _root_.try_for max (tac s) with\n| some r := r\n| none   := mk_exception \"try_for tactic failed, timeout\" none s\nend\n\n/-- Execute `tac` for `max` milliseconds. Useful due to variance\n    in the number of heartbeats taken by various tactics. -/\nmeta def try_for_time {\u03b1} (max : nat) (tac : tactic \u03b1) : tactic \u03b1 :=\n\u03bb s,\nmatch _root_.try_for_time max (tac s) with\n| some r := r\n| none   := mk_exception \"try_for_time tactic failed, timeout\" none s\nend\n\n\nmeta def updateex_env (f : environment \u2192 exceptional environment) : tactic unit :=\ndo env \u2190 get_env,\n   env \u2190 returnex $ f env,\n   set_env env\n\n/- Add a new inductive datatype to the environment\n   name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/\nmeta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name \u00d7 expr))\n  (is_meta : bool := ff) : tactic unit :=\nupdateex_env $ \u03bbe, e.add_inductive n ls p ty is is_meta\n\nmeta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=\nadd_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)\n\n/-- add declaration `d` as a protected declaration -/\nmeta def add_protected_decl (d : declaration) : tactic unit :=\nupdateex_env $ \u03bb e, e.add_protected d\n\n/-- check if `n` is the name of a protected declaration -/\nmeta def is_protected_decl (n : name) : tactic bool :=\ndo env \u2190 get_env,\n   return $ env.is_protected n\n\n/-- `add_defn_equations` adds a definition specified by a list of equations.\n\n  The arguments:\n    * `lp`: list of universe parameters\n    * `params`: list of parameters (binders before the colon);\n    * `fn`: a local constant giving the name and type of the declaration\n      (with `params` in the local context);\n    * `eqns`: a list of equations, each of which is a list of patterns\n      (constructors applied to new local constants) and the branch\n      expression;\n    * `is_meta`: is the definition meta?\n\n\n  `add_defn_equations` can be used as:\n\n      do my_add \u2190 mk_local_def `my_add `(\u2115 \u2192 \u2115),\n          a \u2190 mk_local_def `a \u2115,\n          b \u2190 mk_local_def `b \u2115,\n          add_defn_equations [a] my_add\n              [ ([``(nat.zero)], a),\n                ([``(nat.succ %%b)], my_add b) ])\n              ff -- non-meta\n\n  to create the following definition:\n\n      def my_add (a : \u2115) : \u2115 \u2192 \u2115\n      | nat.zero := a\n      | (nat.succ b) := my_add b\n-/\nmeta def add_defn_equations (lp : list name) (params : list expr) (fn : expr)\n                            (eqns : list (list pexpr \u00d7 expr)) (is_meta : bool) : tactic unit :=\ndo opt \u2190 get_options,\n   updateex_env $ \u03bb e, e.add_defn_eqns opt lp params fn eqns is_meta\n\n/-- Get the revertible part of the local context. These are the hypotheses that\nappear after the last frozen local instance in the local context. We call them\nrevertible because `revert` can revert them, unlike those hypotheses which occur\nbefore a frozen instance. -/\nmeta def revertible_local_context : tactic (list expr) :=\ndo ctx \u2190 local_context,\n   frozen \u2190 frozen_local_instances,\n   pure $\n     match frozen with\n     | none := ctx\n     | some [] := ctx\n     | some (h :: _) := ctx.after (eq h)\n     end\n\n/--\nRename local hypotheses according to the given `name_map`. The `name_map`\ncontains as keys those hypotheses that should be renamed; the associated values\nare the new names.\n\nThis tactic can only rename hypotheses which occur after the last frozen local\ninstance. If you need to rename earlier hypotheses, try\n`unfreezing (rename_many ...)`.\n\nIf `strict` is true, we fail if `name_map` refers to hypotheses that do not\nappear in the local context or that appear before a frozen local instance.\nConversely, if `strict` is false, some entries of `name_map` may be silently\nignored.\n\nIf `use_unique_names` is true, the keys of `name_map` should be the unique names\nof hypotheses to be renamed. Otherwise, the keys should be display names.\n\nNote that we allow shadowing, so renamed hypotheses may have the same name\nas other hypotheses in the context. If `use_unique_names` is false and there are\nmultiple hypotheses with the same display name in the context, they are all\nrenamed.\n-/\nmeta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff)\n: tactic unit :=\ndo let hyp_name : expr \u2192 name :=\n     if use_unique_names then expr.local_uniq_name else expr.local_pp_name,\n   ctx \u2190 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 (\u03bb 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 (\u03bb h, \u00ac ctx_names.contains h),\n     when \u00ac 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 `unfreezingI { ... }`.\"\n       ]\n   },\n   -- The new names for all hypotheses in ctx_suffix.\n   let new_names :=\n     ctx_suffix.map $ \u03bb h,\n       (renames.find $ hyp_name h).get_or_else h.local_pp_name,\n   revert_lst ctx_suffix,\n   intro_lst new_names,\n   pure ()\n\n/--\nRename a local hypothesis. This is a special case of `rename_many`;\nsee there for caveats.\n-/\nmeta def rename (curr : name) (new : name) : tactic unit :=\nrename_many (rb_map.of_list [\u27e8curr, new\u27e9])\n\n/--\nRename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does\nnot preserve the order of hypotheses. Its implementation is simpler (and\ntherefore probably faster) than that of `rename`.\n-/\nmeta def rename_unstable (curr : name) (new : name) : tactic unit :=\ndo h \u2190 get_local curr,\n   n \u2190 revert h,\n   intro new,\n   intron (n - 1)\n\n/--\n\"Replace\" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof\nthat (type = new_type). The tactic actually creates a new hypothesis\nwith the same user facing name, and (tries to) clear `h`.\nThe `clear` step fails if `h` has forward dependencies. In this case, the old `h`\nwill remain in the local context. The tactic returns the new hypothesis. -/\nmeta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) (tag : name := `unit.star) : tactic expr :=\ndo h_type \u2190 infer_type h,\n   new_h \u2190 assert h.local_pp_name new_type,\n   eq_pr_type \u2190 mk_app `eq [h_type, new_type],\n   let eq_pr := mk_tagged_proof eq_pr_type eq_pr tag,\n   mk_eq_mp eq_pr h >>= exact,\n   try $ clear h,\n   return new_h\n\nmeta def main_goal : tactic expr :=\ndo g::gs \u2190 get_goals, return g\n\n/- Goal tagging support -/\nmeta def with_enable_tags {\u03b1 : Type} (t : tactic \u03b1) (b := tt) : tactic \u03b1 :=\ndo old \u2190 tags_enabled,\n   enable_tags b,\n   r \u2190 t,\n   enable_tags old,\n   return r\n\nmeta def get_main_tag : tactic tag :=\nmain_goal >>= get_tag\n\nmeta def set_main_tag (t : tag) : tactic unit :=\ndo g \u2190 main_goal, set_tag g t\n\nmeta def subst (h : expr) : tactic unit :=\n(do guard h.is_local_constant,\n    some (\u03b1, lhs, \u03b2, rhs) \u2190 expr.is_heq <$> infer_type h,\n    is_def_eq \u03b1 \u03b2,\n    new_h_type \u2190 mk_app `eq [lhs, rhs],\n    new_h_pr   \u2190 mk_app `eq_of_heq [h],\n    new_h \u2190 assertv h.local_pp_name new_h_type new_h_pr,\n    try (clear h),\n    subst_core new_h)\n<|> subst_core h\nend tactic\n\nnotation [parsing_only] `command`:max := tactic unit\n\nopen tactic\n\nnamespace list\n\nmeta def for_each {\u03b1} : list \u03b1 \u2192 (\u03b1 \u2192 tactic unit) \u2192 tactic unit\n| []      fn := skip\n| (e::es) fn := do fn e, for_each es fn\n\nmeta def any_of {\u03b1 \u03b2} : list \u03b1 \u2192 (\u03b1 \u2192 tactic \u03b2) \u2192 tactic \u03b2\n| []      fn := failed\n| (e::es) fn := do opt_b \u2190 try_core (fn e),\n                   match opt_b with\n                   | some b := return b\n                   | none   := any_of es fn\n                   end\nend list\n\n/- Install monad laws tactic and use it to prove some instances. -/\n\n/-- Try to prove with `iff.refl`.-/\nmeta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact\n\nmeta def monad_from_pure_bind {m : Type u \u2192 Type v}\n  (pure : \u03a0 {\u03b1 : Type u}, \u03b1 \u2192 m \u03b1)\n  (bind : \u03a0 {\u03b1 \u03b2 : Type u}, m \u03b1 \u2192 (\u03b1 \u2192 m \u03b2) \u2192 m \u03b2) : monad m :=\n{pure := @pure, bind := @bind}\n\nmeta instance : monad task :=\n{map := @task.map, bind := @task.bind, pure := @task.pure}\n\nnamespace tactic\n\nmeta def replace_target (new_target : expr) (pr : expr) (tag : name := `unit.star) : tactic unit :=\ndo t \u2190 target,\n   assert `htarget new_target, swap,\n   ht        \u2190 get_local `htarget,\n   pr_type   \u2190 mk_app `eq [t, new_target],\n   let locked_pr := mk_tagged_proof pr_type pr tag,\n   mk_eq_mpr locked_pr ht >>= exact\n\nmeta def eval_pexpr (\u03b1) [reflected \u03b1] (e : pexpr) : tactic \u03b1 :=\nto_expr ``(%%e : %%(reflect \u03b1)) ff ff >>= eval_expr \u03b1\n\nmeta def run_simple {\u03b1} : tactic_state \u2192 tactic \u03b1 \u2192 option \u03b1\n| ts t := match t ts with\n          | (interaction_monad.result.success a ts') := some a\n          | (interaction_monad.result.exception _ _ _) := none\n          end\n\nend tactic\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/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.050330633843892796, "lm_q1q2_score": 0.012628600167328682}}
{"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 => pure 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 \u00b7 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\n\nconstant foo : Nat\n\n#check _root_.foo\n       --^ textDocument/hover\n\nnamespace Bar\n\nconstant 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 := \u27e8toString\u27e9\n--^ textDocument/hover\ninstance f : ToString Nat := \u27e8toString\u27e9\n       --^ textDocument/hover\n\nexample : Type 0 := Nat\n        --^ textDocument/hover\n\ndef foo.bar : Nat := 1\n  --^ textDocument/hover\n      --^ textDocument/hover\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/interactive/hover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.03410042669392811, "lm_q1q2_score": 0.012624843860436557}}
{"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 \u2964 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\u2124 : has_shift C \u2124] [hD\u2124 : has_shift D \u2124]\n\nvariables (F A)\n\nnamespace comm_shift\n\ndef unit : shift_functor C (0 : A) \u22d9 F \u2245 F \u22d9 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) \u226b\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) \u226b\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 \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (h : a = b) :\n  shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b :=\nshift.compatibility.comm_shift.change e (eq_to_iso (by subst h))\n\ndef add {a b : A} (e\u2081 : shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (e\u2082 : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) :\n  shift_functor C (a + b) \u22d9 F \u2245 F \u22d9 shift_functor D (a + b) :=\nshift.compatibility.comm_shift.comp e\u2081 e\u2082\n\n@[simp]\nlemma add_hom_app {a b : A} (e\u2081 : shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (e\u2082 : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) (X : C) :\n  (add e\u2081 e\u2082).hom.app X = F.map ((shift_functor_add C a b).hom.app X) \u226b\n    e\u2082.hom.app (X\u27e6a\u27e7) \u226b (e\u2081.hom.app X)\u27e6b\u27e7' \u226b (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\u2081 : shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (e\u2082 : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) (X : C) :\n  (add e\u2081 e\u2082).inv.app X = (shift_functor_add D a b).hom.app (F.obj X) \u226b\n    (e\u2081.inv.app X)\u27e6b\u27e7' \u226b e\u2082.inv.app (X\u27e6a\u27e7) \u226b 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\u2081 : shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (e\u2082 : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) :\n  shift_functor C c \u22d9 F \u2245 F \u22d9 shift_functor D c :=\n(shift.compatibility.comm_shift.comp e\u2081 e\u2082).change (eq_to_iso (by simpa only [\u2190 h]))\n\nlemma add'_eq_add {a b : A} (e\u2081 : shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (e\u2082 : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) :\n  add' rfl e\u2081 e\u2082 = add e\u2081 e\u2082 :=\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) \u22d9 F \u2245 F \u22d9 shift_functor D (a + b))\n  (f : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) [is_equivalence (shift_functor D b)] :\n  shift_functor C a \u22d9 F \u2245 F \u22d9 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 \u22d9 F \u2245 F \u22d9 shift_functor D b)\n  [is_equivalence (shift_functor D b)] (a : A) :\n  (shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a) \u2243\n    (shift_functor C (a + b) \u22d9 F \u2245 F \u22d9 shift_functor D (a + b)) :=\n{ to_fun := \u03bb e, add e f,\n  inv_fun := \u03bb 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 \u22d9 F \u2245 F \u22d9 shift_functor D c)\n  (f : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b) [is_equivalence (shift_functor D b)] :\n  shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a :=\nsub (change e h.symm) f\n\nlemma sub'_eq_sub {a b : A} (e : shift_functor C (a + b) \u22d9 F \u2245 F \u22d9 shift_functor D (a + b))\n  (f : shift_functor C b \u22d9 F \u2245 F \u22d9 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 \u22d9 F \u2245 F \u22d9 shift_functor D b)\n  [is_equivalence (shift_functor D b)] :\n  (shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a) \u2243\n    (shift_functor C c \u22d9 F \u2245 F \u22d9 shift_functor D c) :=\n{ to_fun := \u03bb e, add' h e f,\n  inv_fun := \u03bb 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 \u22d9 F \u2245 F \u22d9 shift_functor D b)\n  [is_equivalence (shift_functor D b)] (a : A) :\n  function.bijective (\u03bb (e : shift_functor C a \u22d9 F \u2245 F \u22d9 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 \u22d9 F \u2245 F \u22d9 shift_functor D b)\n  [is_equivalence (shift_functor D b)] :\n  function.bijective (\u03bb (e : shift_functor C a \u22d9 F \u2245 F \u22d9 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 \u22d9 F \u2245 F \u22d9 shift_functor D c)\n  (f : shift_functor C b \u22d9 F \u2245 F \u22d9 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\u2081 : shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (e\u2082 : shift_functor C b \u22d9 F \u2245 F \u22d9 shift_functor D b)\n  (e\u2083 : shift_functor C c \u22d9 F \u2245 F \u22d9 shift_functor D c) :\n  add' (show ab + c = abc, by rw [\u2190 hab, habc]) (add' hab e\u2081 e\u2082) e\u2083 =\n    add' (show a + bc = abc, by rw [\u2190 hbc, \u2190 add_assoc, habc]) e\u2081 (add' hbc e\u2082 e\u2083) :=\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 \u22d9 F \u2245 F \u22d9 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 \u22d9 F \u2245 F \u22d9 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 \u22d9 F \u2245 F \u22d9 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 : \u03a0 (a : A), shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n(iso_zero : iso 0 = comm_shift.unit F A)\n(iso_add : \u2200 (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 \u22d9 F \u2245 F \u22d9 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) \u226b\n    (F.comm_shift_iso b).hom.app X \u226b 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\u2081 e\u2082 : F.has_comm_shift A) (a b : A)\n  (ha : e\u2081.iso a = e\u2082.iso a) (hb : e\u2081.iso b = e\u2082.iso b) :\n  e\u2081.iso (a + b) = e\u2082.iso (a + b) :=\nby rw [e\u2081.iso_add, e\u2082.iso_add, ha, hb]\n\nlemma iso_eq_of_iso_add_eq (e\u2081 e\u2082 : F.has_comm_shift A) (a b : A)\n  (hb : e\u2081.iso b = e\u2082.iso b) (hab : e\u2081.iso (a + b) = e\u2082.iso (a+b))\n  [is_equivalence (shift_functor D b)] : e\u2081.iso a = e\u2082.iso a :=\n(comm_shift.add_bijective (e\u2081.iso b) a).1\n  (by { dsimp only, rw [\u2190 e\u2081.iso_add, hb, \u2190 e\u2082.iso_add, hab], })\n\ninclude hC\u2124 hD\u2124\n\n@[ext]\nlemma eq_of_iso_one_eq (e\u2081 e\u2082 : F.has_comm_shift \u2124)\n  (h : e\u2081.iso (1 : \u2124) = e\u2082.iso (1 : \u2124)) : e\u2081 = e\u2082 :=\nbegin\n  suffices : \u2200 (n : \u2115), e\u2081.iso (n : \u2124) = e\u2082.iso (n : \u2124),\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\u2081 e\u2082 (-[1+n]) (1+n) (this _) _,\n      rw [eq, e\u2081.iso_zero, e\u2082.iso_zero], }, },\n  intro n,\n  induction n with n hn,\n  { exact e\u2081.iso_zero.trans (e\u2082.iso_zero.symm), },\n  { rw [nat.cast_succ, e\u2081.iso_add, e\u2082.iso_add, hn, h], },\nend\n\nvariable (e : shift_functor C (1 : \u2124) \u22d9 F \u2245 F \u22d9 shift_functor D (1 : \u2124))\n\nnamespace mk_\u2124\n\nnoncomputable\ndef iso_\u2115 : \u03a0 (n : \u2115), shift_functor C (int.of_nat n) \u22d9 F \u2245 F \u22d9 shift_functor D (int.of_nat n)\n| 0 := unit _ _\n| 1 := e\n| (n+2) := add (iso_\u2115 (n+1)) e\n\n@[simp]\nlemma iso_\u2115_zero : iso_\u2115 e 0 = unit _ _ := rfl\n\n@[simp]\nlemma iso_\u2115_one : iso_\u2115 e 1 = e := rfl\n\nlemma iso_\u2115_add_one (n : \u2115) : add (iso_\u2115 e n) e = iso_\u2115 e (n+1) :=\nbegin\n  cases n,\n  { unfold iso_\u2115,\n    simp only [comm_shift.zero_add, change, eq_to_iso_refl, shift.compatibility.comm_shift.change_refl], },\n  { unfold iso_\u2115, },\nend\n\nlemma iso_\u2115_add'_one (n\u2080 n\u2081 : \u2115) (h : n\u2080 + 1 = n\u2081) :\n  add' (by { simp only [\u2190 h, int.of_nat_eq_coe], push_cast, })\n    (iso_\u2115 e n\u2080) e = iso_\u2115 e n\u2081 :=\nbegin\n  subst h,\n  erw add'_eq_add,\n  apply iso_\u2115_add_one,\nend\n\ndef iso_\u2124 : \u03a0 (n : \u2124), shift_functor C (n : \u2124) \u22d9 F \u2245 F \u22d9 shift_functor D (n : \u2124)\n| (int.of_nat n) := iso_\u2115 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 \u2124) (iso_\u2115 e (1+n))\n\n@[simp]\nlemma iso_\u2124_zero : iso_\u2124 e 0 = unit _ _ := rfl\n\n@[simp]\nlemma iso_\u2124_one : iso_\u2124 e 1 = e := rfl\n\nlemma iso_\u2115_add' (n\u2081 n\u2082 n\u2083 : \u2115) (h : n\u2081 + n\u2082 = n\u2083) :\n  add' (by simp only [\u2190 h, int.of_nat_eq_coe, nat.cast_add]) (iso_\u2115 e n\u2081) (iso_\u2115 e n\u2082) =\n    iso_\u2115 e n\u2083 :=\nbegin\n  revert h n\u2083 n\u2081,\n  induction n\u2082 with n\u2082 hn\u2082,\n  { intros n\u2081 n\u2083 h,\n    have h' : n\u2081 = n\u2083 := by simpa only [add_zero] using h,\n    subst h',\n    exact add'_zero (iso_\u2115 e n\u2081), },\n  { intros n\u2081 n\u2083 h,\n    rw \u2190 iso_\u2115_add_one,\n    rw \u2190 add'_eq_add,\n    conv_lhs { congr, skip, congr, skip, rw \u2190 iso_\u2115_one e, },\n    erw \u2190 add'_assoc (int.of_nat n\u2081) (int.of_nat n\u2082) 1 (int.of_nat (n\u2081 + n\u2082))\n      (int.of_nat n\u2082 + 1) n\u2083 (by simp) (by simp) (by { rw \u2190 h, push_cast, simp, rw add_assoc,}),\n    rw hn\u2082 _ _ rfl,\n    erw iso_\u2115_add'_one,\n    rw [\u2190 h, nat.succ_eq_add_one, add_assoc], },\nend\n\nlemma iso_\u2124_add'_nonneg (n\u2081 n\u2082 n\u2083 : \u2124) (h : n\u2081 + n\u2082 = n\u2083) (hn\u2081 : 0 \u2264 n\u2081) (hn\u2082 : 0 \u2264 n\u2082) :\n  add' h (iso_\u2124 e n\u2081) (iso_\u2124 e n\u2082) = iso_\u2124 e n\u2083 :=\nbegin\n  have h\u2081 : \u2203 (m\u2081 : \u2115), n\u2081 = int.of_nat m\u2081 := int.eq_coe_of_zero_le hn\u2081,\n  have h\u2082 : \u2203 (m\u2082 : \u2115), n\u2082 = int.of_nat m\u2082 := int.eq_coe_of_zero_le hn\u2082,\n  rcases h\u2081 with \u27e8m\u2081, hm\u2081\u27e9,\n  rcases h\u2082 with \u27e8m\u2082, hm\u2082\u27e9,\n  have h\u2083 : n\u2083 = int.of_nat (m\u2081 + m\u2082),\n  { simp only [\u2190 h, hm\u2081, hm\u2082, int.of_nat_eq_coe, nat.cast_add], },\n  substs hm\u2081 hm\u2082 h\u2083,\n  unfold iso_\u2124,\n  exact iso_\u2115_add' e _ _ _ rfl,\nend\n\nlemma iso_\u2124_add'_neg (n\u2081 n\u2082 : \u2124) (h : n\u2081 + n\u2082 = 0) (hn\u2082 : 0 \u2264 n\u2082):\n  add' h (iso_\u2124 e n\u2081) (iso_\u2124 e n\u2082) = unit F \u2124 :=\nbegin\n  cases n\u2081,\n  { have hn\u2081 : 0 \u2264 int.of_nat n\u2081 := int.of_nat_nonneg n\u2081,\n    have h\u2082 : n\u2082 = 0 := by linarith,\n    subst h\u2082,\n    have h\u2081 : n\u2081 = 0 := by simpa only [int.of_nat_eq_coe, add_zero, nat.cast_eq_zero] using h,\n    subst h\u2081,\n    erw [iso_\u2124_zero, add'_zero], },\n  { have h\u2082 : n\u2082 = int.of_nat (1 + n\u2081),\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\u2082,\n    unfold iso_\u2124,\n    apply add'_sub', },\nend\n\nlemma iso_\u2124_add'_one (n\u2080 n\u2081 : \u2124) (h : n\u2080 + 1 = n\u2081) : add' h (iso_\u2124 e n\u2080) e = iso_\u2124 e n\u2081 :=\nbegin\n  cases n\u2080,\n  { have h\u2081 : n\u2081 = int.of_nat (n\u2080 + 1),\n    { rw \u2190 h, simp, },\n    subst h\u2081,\n    unfold iso_\u2124,\n    rw \u2190 iso_\u2115_add_one e n\u2080,\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\u2081 + int.of_nat n\u2080 = 0, by { rw int.of_nat_eq_coe, linarith, })\n      (iso_\u2124 e (int.of_nat n\u2080))).1 _,\n    simp only,\n    rw iso_\u2124_add'_neg e, swap, { apply int.of_nat_nonneg, },\n    rw add'_assoc (-[1+n\u2080]) 1 (int.of_nat n\u2080) n\u2081 (int.of_nat (1+n\u2080)) 0 h\n      (by simp) (by { rw int.neg_succ_of_nat_coe', simp,}),\n    conv_lhs { congr, skip, congr, rw \u2190 iso_\u2124_one e, },\n    rw iso_\u2124_add'_nonneg e 1 (int.of_nat n\u2080) (int.of_nat (1+n\u2080)) (by simp) zero_le_one (int.of_nat_nonneg n\u2080),\n    apply iso_\u2124_add'_neg,\n    apply int.of_nat_nonneg, },\nend\n\nlemma iso_\u2124_add_one (n : \u2124) : add (iso_\u2124 e n) (iso_\u2124 e 1) = iso_\u2124 e (n + 1) :=\nbegin\n  rw \u2190 add'_eq_add,\n  apply iso_\u2124_add'_one,\nend\n\nend mk_\u2124\n\n@[simps]\ndef mk'_\u2124 (iso : \u03a0 (a : \u2124), shift_functor C a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n  (iso_zero : iso 0 = comm_shift.unit F \u2124)\n  (iso_add_one : \u2200 (a : \u2124), iso (a + 1) = comm_shift.add (iso a) (iso 1)) :\n  has_comm_shift F \u2124 :=\n{ iso := iso,\n  iso_zero := iso_zero,\n  iso_add := begin\n    have iso_add_one' : \u2200 (a b : \u2124) (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 : \u2200 (a b c : \u2124) (h : a + b = c) (hb : 0 \u2264 b),\n      iso c = add' h (iso a) (iso b),\n    { intros a b,\n      by_cases hb : 0 \u2264 b,\n      { rw [this a b _ rfl hb, add'_eq_add], },\n      { rw \u2190 add'_eq_add,\n        apply (add'_bijective (show (a+b)+(-b) = a, by linarith) (iso (-b))).1,\n        simp only [\u2190 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          \u2190 this b (-b) 0 (by linarith) (by linarith), iso_zero, add'_zero], }, },\n    intros a b c h hb,\n    obtain \u27e8b', hb'\u27e9 := 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 [\u2190h, 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 \u2190 add'_assoc a b 1 _ b.succ c rfl (by push_cast)\n        (by { rw \u2190 h, push_cast, rw add_assoc, }),\n      rw \u2190 hb a _ rfl,\n      apply iso_add_one', },\n  end}\n\n@[simps]\ndef mk_\u2124 (e : shift_functor C (1 : \u2124) \u22d9 F \u2245 F \u22d9 shift_functor D (1 : \u2124)) :\n  has_comm_shift F \u2124 :=\nmk'_\u2124 (mk_\u2124.iso_\u2124 e) rfl (\u03bb a, (mk_\u2124.iso_\u2124_add_one e a).symm)\n\nvariable (F)\n\n@[simps]\ndef equiv_\u2124 : has_comm_shift F \u2124 \u2243\n  (shift_functor C (1 : \u2124) \u22d9 F \u2245 F \u22d9 shift_functor D (1 : \u2124)) :=\n{ to_fun := \u03bb c, c.iso 1,\n  inv_fun := \u03bb e, mk_\u2124 e,\n  left_inv := \u03bb c, by { ext, refl, },\n  right_inv := \u03bb e, rfl, }\n\nend comm_shift\n\nvariable {A}\n\nlemma iso_add_hom_app (F : C \u2964 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) \u226b\n    (F.comm_shift_iso q).hom.app (X\u27e6p\u27e7) \u226b ((F.comm_shift_iso p).hom.app X)\u27e6q\u27e7' \u226b\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.\u03bc_iso_hom],\nend\n\nlemma map_shift_functor_add_comm {A : Type*} [add_comm_monoid A] (F : C \u2964 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) \u226b\n      (F.comm_shift_iso p).hom.app (X\u27e6q\u27e7) \u226b ((F.comm_shift_iso q).hom.app X)\u27e6p\u27e7' =\n    (F.comm_shift_iso q).hom.app (X\u27e6p\u27e7) \u226b ((F.comm_shift_iso p).hom.app X)\u27e6q\u27e7' \u226b\n      (shift_functor_add_comm D p q).hom.app (F.obj X) :=\nbegin\n  have eq\u2081 := F.iso_add_hom_app p q X,\n  simp only [\u2190 cancel_mono ((shift_functor_add D p q).hom.app (F.obj X)),\n    assoc, iso.inv_hom_id_app] at eq\u2081,\n  erw comp_id at eq\u2081,\n  have eq\u2082 := F.iso_add_hom_app q p X,\n  simp only [\u2190 cancel_epi (F.map ((shift_functor_add C q p).inv.app X)),\n    \u2190 F.map_comp_assoc, iso.inv_hom_id_app, F.map_id, id_comp] at eq\u2082,\n  simp only [\u2190 cancel_epi (F.map ((shift_functor_add C p q).hom.app X)),\n    \u2190 cancel_mono ((shift_functor_add D q p).inv.app (F.obj X)), assoc],\n  slice_rhs 1 3 { rw \u2190 eq\u2081, },\n  simp only [assoc, \u2190 eq\u2082], clear eq\u2081 eq\u2082,\n  dsimp only [shift_functor_add_comm, iso.symm, iso.trans, nat_trans.comp_app],\n  simpa only [F.map_comp, \u2190 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\u2081 : C \u2964 D) (F\u2082 : D \u2964 E)\n  [F\u2081.has_comm_shift A] [F\u2082.has_comm_shift A] (a b : A) (X : C) :\n  F\u2082.map ((shift_functor D b).map ((F\u2081.comm_shift_iso a).hom.app X)) \u226b\n  (F\u2082.comm_shift_iso b).hom.app ((shift_functor D a).obj (F\u2081.obj X)) =\n  (F\u2082.comm_shift_iso b).hom.app (F\u2081.obj ((shift_functor C a).obj X)) \u226b\n    (shift_functor E b).map (F\u2082.map ((F\u2081.comm_shift_iso a).hom.app X)) :=\nbegin\n  let \u03b1 := (F\u2081.comm_shift_iso a).hom,\n  let \u03b2 := (F\u2082.comm_shift_iso b).hom,\n  have eq := nat_trans.exchange (F\u2081.comm_shift_iso a).hom (\ud835\udfd9 _) (\ud835\udfd9 _) (F\u2082.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\u2081 : C \u2964 D) (F\u2082 : D \u2964 E)\n  [F\u2081.has_comm_shift A] [F\u2082.has_comm_shift A] : (F\u2081 \u22d9 F\u2082).has_comm_shift A :=\n{ iso := \u03bb a, comm_shift_comp (F\u2081.comm_shift_iso a) (F\u2082.comm_shift_iso a),\n  iso_zero := begin\n    ext X,\n    simp only [comm_shift_comp_hom_app, F\u2081.comm_shift_iso_zero A,\n      F\u2082.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.\u03b5_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.\u03b5_iso],\n    nth_rewrite 1 \u2190 F\u2082.map_comp_assoc,\n    rw [\u2190 nat_trans.comp_app, is_iso.hom_inv_id],\n    erw [F\u2082.map_id, id_comp],\n  end,\n  iso_add := \u03bb 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 [\u2190 F\u2082.map_comp, iso.inv_hom_id_app, F\u2082.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 \u226b\n      F.map (((shift_functor_add' _ a b c) h).hom.app K) \u226b\n      (F.comm_shift_iso b).hom.app (K\u27e6a\u27e7) \u226b\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    \u2190 F.map_comp_assoc, \u03bc_hom_inv_app],\n  erw [F.map_id, id_comp, iso.inv_hom_id_app_assoc, \u2190 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 \u226b 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, \u2190 F.map_comp],\n  simp only [\u03b5_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  (\ud835\udfed C).has_comm_shift A :=\n{ iso := \u03bb a, by refl,\n  iso_add := \u03bb 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 (\ud835\udfed C) a).hom.app X = \ud835\udfd9 _ := 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 (\ud835\udfed C) a).inv.app X = \ud835\udfd9 _ := rfl\n\n@[simp]\nlemma has_comm_shift.comp_hom_app (F\u2081 : C \u2964 D) (F\u2082 : D \u2964 E)\n  [F\u2081.has_comm_shift A] [F\u2082.has_comm_shift A] (X : C) (a : A) :\n  (comm_shift_iso (F\u2081 \u22d9 F\u2082) a).hom.app X =\n    F\u2082.map ((comm_shift_iso F\u2081 a).hom.app X) \u226b\n      (comm_shift_iso F\u2082 a).hom.app (F\u2081.obj X) :=\ncomm_shift_comp_hom_app _ _ _\n\n@[simp]\nlemma has_comm_shift.comp_inv_app (F\u2081 : C \u2964 D) (F\u2082 : D \u2964 E)\n  [F\u2081.has_comm_shift A] [F\u2082.has_comm_shift A] (X : C) (a : A) :\n  (comm_shift_iso (F\u2081 \u22d9 F\u2082) a).inv.app X =\n    (comm_shift_iso F\u2082 a).inv.app (F\u2081.obj X) \u226b\n      F\u2082.map ((comm_shift_iso F\u2081 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 \u2964 D)\n  {A : Type*} [add_monoid A] [has_shift D A] [full F] [faithful F]\n  (s : A \u2192 C \u2964 C) (hs : \u03a0 (a : A), s a \u22d9 F \u2245 F \u22d9 shift_functor D a)\n\nlocal attribute [instance] endofunctor_monoidal_category\n\nlemma has_shift_of_fully_faithful_map_\u03b5_iso_hom_app (X : C) :\n  F.map ((@shift_monoidal_functor C A _ _\n    (has_shift_of_fully_faithful F s hs)).\u03b5_iso.hom.app X) =\n  (shift_zero A (F.obj X)).inv \u226b (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_\u03b5_iso_inv_app (X : C) :\n  F.map ((@shift_monoidal_functor C A _ _\n    (has_shift_of_fully_faithful F s hs)).\u03b5_iso.inv.app X) =\n  (hs 0).hom.app X \u226b (shift_zero A (F.obj X)).hom :=\nbegin\n  rw [\u2190 cancel_mono (F.map ((@shift_monoidal_functor C A _ _\n    (has_shift_of_fully_faithful F s hs)).\u03b5_iso.hom.app X)), \u2190 F.map_comp,\n    iso.inv_hom_id_app, F.map_id, has_shift_of_fully_faithful_map_\u03b5_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_\u03bc_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)).\u03bc_iso (discrete.mk a) (discrete.mk b)).hom.app X) =\n    (hs b).hom.app ((s a).obj X) \u226b (shift_functor D b).map ((hs a).hom.app X) \u226b\n      (shift_functor_add D a b).inv.app (F.obj X) \u226b (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_\u03bc_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)).\u03bc_iso (discrete.mk a) (discrete.mk b)).inv.app X) =\n      (hs (a + b)).hom.app X \u226b\n      (shift_functor_add D a b).hom.app (F.obj X) \u226b\n    (shift_functor D b).map ((hs a).inv.app X) \u226b\n    (hs b).inv.app ((s a).obj X) :=\nbegin\n  erw [\u2190 cancel_mono (F.map (((@shift_monoidal_functor C A _ _\n    (has_shift_of_fully_faithful F s hs)).\u03bc_iso (discrete.mk a) (discrete.mk b)).hom.app X)),\n    \u2190 F.map_comp, iso.inv_hom_id_app, F.map_id, assoc, assoc, assoc,\n    has_shift_of_fully_faithful_map_\u03bc_iso_hom_app, iso.inv_hom_id_app_assoc,\n    \u2190 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 := \u03bb 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_\u03bc_iso_inv_app,\n      assoc, assoc, assoc, iso.inv_hom_id_app_assoc, \u2190 functor.map_comp_assoc,\n      iso.inv_hom_id_app, functor.map_id, id_comp,\n      iso.symm_hom, monoidal_functor.\u03bc_iso_hom, \u03bc_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_\u03b5_iso_inv_app],\n    simp only [iso.app_hom, iso.symm_hom, monoidal_functor.\u03b5_iso_hom, assoc, \u03b5_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 [] : \u2200 (a : A) (X : C) (hX : X \u2208 S), X\u27e6a\u27e7 \u2208 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  (\u03bb a, full_subcategory.lift _ (full_subcategory_inclusion S \u22d9 shift_functor C a)\n  (\u03bb X, set.is_stable_by_shift.condition a X.1 X.2))\n  (\u03bb 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 \u2964 D} (e : F \u2245 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 := \u03bb a, iso_whisker_left _ e.symm \u226a\u226b comm_shift_iso F a \u226a\u226b\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.\u03b5_iso_hom, comm_shift_iso_zero, assoc,\n      \u2190 nat_trans.naturality_assoc, \u2190 nat_trans.naturality],\n    dsimp,\n    simp only [iso.inv_hom_id_app_assoc],\n  end,\n  iso_add := \u03bb 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.\u03bc_iso_hom, assoc, \u03bc_naturality,\n      comm_shift_iso_add],\n    erw nat_trans.naturality_assoc,\n    rw [\u2190 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 \u2964 D} (\u03c4 : F \u27f6 G) (e : F \u2245 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 [] : \u2200 (a : A), (F.comm_shift_iso a).hom \u226b whisker_right \u03c4 _ =\n  whisker_left _ \u03c4 \u226b (G.comm_shift_iso a).hom)\n\nvariable {A}\n\nnamespace respects_comm_shift\n\n@[reassoc]\nlemma comm_app (a : A) (X : C) [\u03c4.respects_comm_shift A] :\n  (F.comm_shift_iso a).hom.app X \u226b (\u03c4.app X)\u27e6a\u27e7' =\n  \u03c4.app (X\u27e6a\u27e7) \u226b (G.comm_shift_iso a).hom.app X :=\ncongr_app (respects_comm_shift.comm \u03c4 a) X\n\nlemma app_shift (a : A) (X : C) [\u03c4.respects_comm_shift A] :\n  \u03c4.app (X\u27e6a\u27e7) = (F.comm_shift_iso a).hom.app X \u226b\n    (\u03c4.app X)\u27e6a\u27e7' \u226b (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 \u2964 D} (e : F \u2245 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 \u27e8\u03bb a, _\u27e9,\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\u27e8\u03bb a, begin\n  ext X,\n  simp only [comp_app, whisker_right_app, whisker_left_app,\n    \u2190 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    \u2190 functor.map_comp, e.inv_hom_id_app, functor.map_id],\n  apply comp_id,\nend\u27e9\n\nlemma of_iso_hom : e.hom.respects_comm_shift A \u2194 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 \u2964 D} (\u03c4' : G \u27f6 H) [H.has_comm_shift A] [\u03c4.respects_comm_shift A]\n  [\u03c4'.respects_comm_shift A] : (\u03c4 \u226b \u03c4').respects_comm_shift A :=\n\u27e8\u03bb 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\u27e9\n\ninstance associator {C\u2081 C\u2082 C\u2083 C\u2084 : Type*} [category C\u2081] [category C\u2082] [category C\u2083] [category C\u2084]\n  [has_shift C\u2081 A] [has_shift C\u2082 A] [has_shift C\u2083 A] [has_shift C\u2084 A]\n  (F\u2081 : C\u2081 \u2964 C\u2082) (F\u2082 : C\u2082 \u2964 C\u2083) (F\u2083 : C\u2083 \u2964 C\u2084)\n  [F\u2081.has_comm_shift A] [F\u2082.has_comm_shift A][F\u2083.has_comm_shift A] :\n  (functor.associator F\u2081 F\u2082 F\u2083).hom.respects_comm_shift A :=\n\u27e8\u03bb 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\u27e9\n\ninstance whisker_left {C\u2081 C\u2082 C\u2083 : Type*} [category C\u2081] [category C\u2082] [category C\u2083]\n  [has_shift C\u2081 A] [has_shift C\u2082 A] [has_shift C\u2083 A]\n  (F : C\u2081 \u2964 C\u2082) {G G' : C\u2082 \u2964 C\u2083} [F.has_comm_shift A] [G.has_comm_shift A]\n  [G'.has_comm_shift A] (\u03c4 : G \u27f6 G') [\u03c4.respects_comm_shift A] :\n  (whisker_left F \u03c4).respects_comm_shift A :=\n\u27e8\u03bb 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\u27e9\n\ninstance whisker_right {C\u2081 C\u2082 C\u2083 : Type*} [category C\u2081] [category C\u2082] [category C\u2083]\n  [has_shift C\u2081 A] [has_shift C\u2082 A] [has_shift C\u2083 A]\n  {F F' : C\u2081 \u2964 C\u2082} [F.has_comm_shift A] [F'.has_comm_shift A]\n  (G : C\u2082 \u2964 C\u2083) [G.has_comm_shift A]\n  (\u03c4 : F \u27f6 F') [\u03c4.respects_comm_shift A] :\n  (whisker_right \u03c4 G).respects_comm_shift A :=\n\u27e8\u03bb 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, \u2190 G.map_comp_assoc,\n    \u2190 comm_app \u03c4 a X],\n  erw [G.map_comp, assoc, \u2190 nat_trans.naturality],\n  refl,\nend\u27e9\n\ninstance id : respects_comm_shift (\ud835\udfd9 F) A :=\n\u27e8\u03bb a, by simp only [whisker_right_id', comp_id, whisker_left_id', id_comp]\u27e9\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 \u2964 D} {G : D \u2964 E} {H : C \u2964 E} (e : F \u22d9 G \u2245 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 \u22d9 F \u2245 F \u22d9 shift_functor D a :=\nnat_iso_of_comp_fully_faithful G\n  (functor.associator _ _ _ \u226a\u226b iso_whisker_left _ e \u226a\u226b\n  H.comm_shift_iso a \u226a\u226b iso_whisker_right e.symm _ \u226a\u226b\n  functor.associator _ _ _ \u226a\u226b iso_whisker_left _ (G.comm_shift_iso a).symm \u226a\u226b\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) \u226b (H.comm_shift_iso a).hom.app X \u226b\n      (shift_functor E a).map (e.inv.app X) \u226b (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) \u226b (shift_functor E a).map (e.hom.app X) \u226b\n      (H.comm_shift_iso a).inv.app X \u226b 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.\u03b5_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, \u03b5_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 := \u03bb 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.\u03bc_iso_hom, map_comp, assoc, comm_shift_iso_add,\n      comm_shift.add_inv_app],\n    erw [\u2190 nat_trans.naturality_assoc, \u2190 nat_trans.naturality_assoc, \u2190 nat_trans.naturality_assoc],\n    dsimp,\n    simp only [\u03bc_hom_inv_app_assoc, of_fully_faithful.map_iso_hom_app, map_comp, assoc],\n    nth_rewrite 2 \u2190 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, \u2190 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 \u2964 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 : \u2200 (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 \u2964 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 : \u2200 (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": "/-\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.Util.FindMVar\nimport Lean.Parser.Term\nimport Lean.Meta.KAbstract\nimport Lean.Meta.Tactic.ElimInfo\nimport Lean.Elab.Term\nimport Lean.Elab.Binders\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.Arg\nimport Lean.Elab.RecAppSyntax\n\nnamespace Lean.Elab.Term\nopen Meta\n\nbuiltin_initialize elabWithoutExpectedTypeAttr : TagAttribute \u2190\n  registerTagAttribute `elab_without_expected_type \"mark that applications of the given declaration should be elaborated without the expected type\"\n\ndef hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool :=\n  elabWithoutExpectedTypeAttr.hasTag env declName\n\ninstance : ToString Arg where\n  toString\n    | .stx  val => toString val\n    | .expr val => toString val\n\ninstance : ToString NamedArg where\n  toString s := \"(\" ++ toString s.name ++ \" := \" ++ toString s.val ++ \")\"\n\ndef throwInvalidNamedArg (namedArg : NamedArg) (fn? : Option Name) : TermElabM \u03b1 :=\n  withRef namedArg.ref <| match fn? with\n    | some fn => throwError \"invalid argument name '{namedArg.name}' for function '{fn}'\"\n    | none    => throwError \"invalid argument name '{namedArg.name}' for function\"\n\nprivate def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do\n  try\n    ensureHasType expectedType arg none f\n  catch\n    | ex@(.error ..) =>\n      if (\u2190 read).errToSorry then\n        exceptionToSorry ex expectedType\n      else\n        throw ex\n    | ex => throw ex\n\nprivate def mkProjAndCheck (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do\n  let r := mkProj structName idx e\n  let eType \u2190 inferType e\n  if (\u2190 isProp eType) then\n    let rType \u2190 inferType r\n    if !(\u2190 isProp rType) then\n      throwError \"invalid projection, the expression{indentExpr e}\\nis a proposition and has type{indentExpr eType}\\nbut the projected value is not, it has type{indentExpr rType}\"\n  return r\n\ndef synthesizeAppInstMVars (instMVars : Array MVarId) (app : Expr) : TermElabM Unit :=\n  for mvarId in instMVars do\n    unless (\u2190 synthesizeInstMVarCore mvarId) do\n      registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass\n      registerMVarErrorImplicitArgInfo mvarId (\u2190 getRef) app\n\n/-- Return `some namedArg` if `namedArgs` contains an entry for `binderName`. -/\nprivate def findBinderName? (namedArgs : List NamedArg) (binderName : Name) : Option NamedArg :=\n  namedArgs.find? fun namedArg => namedArg.name == binderName\n\n/-- Erase entry for `binderName` from `namedArgs`. -/\ndef eraseNamedArg (namedArgs : List NamedArg) (binderName : Name) : List NamedArg :=\n  namedArgs.filter (\u00b7.name != binderName)\n\n/-- Return true if the given type contains `OptParam` or `AutoParams` -/\nprivate def hasOptAutoParams (type : Expr) : MetaM Bool := do\n  forallTelescopeReducing type fun xs _ =>\n    xs.anyM fun x => do\n      let xType \u2190 inferType x\n      return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome\n\n\n/-! # Default application elaborator -/\nnamespace ElabAppArgs\n\nstructure Context where\n  /--\n   `true` if `..` was used\n  -/\n  ellipsis      : Bool  --\n  /--\n   `true` if `@` modifier was used\n  -/\n  explicit      : Bool\n  /--\n    If the result type of an application is the `outParam` of some local instance, then special support may be needed\n    because type class resolution interacts poorly with coercions in this kind of situation.\n    This flag enables the special support.\n\n    The idea is quite simple, if the result type is the `outParam` of some local instance, we simply\n    execute `synthesizeSyntheticMVarsUsingDefault`. We added this feature to make sure examples as follows\n    are correctly elaborated.\n    ```lean\n    class GetElem (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where\n      getElem (xs : Cont) (i : Idx) : Elem\n\n    export GetElem (getElem)\n\n    instance : GetElem (Array \u03b1) Nat \u03b1 where\n      getElem xs i := xs.get \u27e8i, sorry\u27e9\n\n    opaque f : Option Bool \u2192 Bool\n    opaque g : Bool \u2192 Bool\n\n    def bad (xs : Array Bool) : Bool :=\n      let x := getElem xs 0\n      f x && g x\n    ```\n    Without the special support, Lean fails at `g x` saying `x` has type `Option Bool` but is expected to have type `Bool`.\n    From the user's point of view this is a bug, since `let x := getElem xs 0` clearly constrains `x` to be `Bool`, but\n    we only obtain this information after we apply the `OfNat` default instance for `0`.\n\n    Before converging to this solution, we have tried to create a \"coercion placeholder\" when `resultIsOutParamSupport = true`,\n    but it did not work well in practice. For example, it failed in the example above.\n  -/\n  resultIsOutParamSupport : Bool\n\n/-- Auxiliary structure for elaborating the application `f args namedArgs`. -/\nstructure State where\n  f                    : Expr\n  fType                : Expr\n  /-- Remaining regular arguments. -/\n  args                 : List Arg\n  /-- remaining named arguments to be processed. -/\n  namedArgs            : List NamedArg\n  expectedType?        : Option Expr\n  /--\n    When named arguments are provided and explicit arguments occurring before them are missing,\n    the elaborator eta-expands the declaration. For example,\n    ```\n    def f (x y : Nat) := x + y\n    #check f (y := 5)\n    -- fun x => f x 5\n    ```\n    `etaArgs` stores the fresh free variables for implementing the eta-expansion.\n    When `..` is used, eta-expansion is disabled, and missing arguments are treated as `_`.\n  -/\n  etaArgs              : Array Expr   := #[]\n  /-- Metavariables that we need to set the error context using the application being built. -/\n  toSetErrorCtx        : Array MVarId := #[]\n  /-- Metavariables for the instance implicit arguments that have already been processed. -/\n  instMVars            : Array MVarId := #[]\n  /--\n    The following field is used to implement the `propagateExpectedType` heuristic.\n    It is set to `true` true when `expectedType` still has to be propagated.\n  -/\n  propagateExpected    : Bool\n  /--\n    If the result type may be the `outParam` of some local instance.\n    See comment at `Context.resultIsOutParamSupport`\n   -/\n  resultTypeOutParam?  : Option MVarId := none\n\nabbrev M := ReaderT Context (StateRefT State TermElabM)\n\n/-- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/\nprivate def addInstMVar (mvarId : MVarId) : M Unit :=\n  modify fun s => { s with instMVars := s.instMVars.push mvarId }\n\n/--\n  Try to synthesize metavariables are `instMVars` using type class resolution.\n  The ones that cannot be synthesized yet stay in the `instMVars` list.\n  Remark: we use this method\n    - before trying to apply coercions to function,\n    - before unifying the expected type.\n-/\ndef trySynthesizeAppInstMVars : M Unit := do\n  let instMVars \u2190 (\u2190 get).instMVars.filterM fun instMVar => do\n    unless (\u2190 instantiateMVars (\u2190 inferType (.mvar instMVar))).isMVar do try\n      if (\u2190 synthesizeInstMVarCore instMVar) then\n        return false\n      catch _ => pure ()\n    return true\n  modify ({ \u00b7 with instMVars })\n\n/--\n  Try to synthesize metavariables are `instMVars` using type class resolution.\n  The ones that cannot be synthesized yet are registered.\n-/\ndef synthesizeAppInstMVars : M Unit := do\n  Term.synthesizeAppInstMVars (\u2190 get).instMVars (\u2190 get).f\n  modify ({ \u00b7 with instMVars := #[] })\n\n/-- fType may become a forallE after we synthesize pending metavariables. -/\nprivate def synthesizePendingAndNormalizeFunType : M Unit := do\n  trySynthesizeAppInstMVars\n  synthesizeSyntheticMVars\n  let s \u2190 get\n  let fType \u2190 whnfForall s.fType\n  if fType.isForall then\n    modify fun s => { s with fType }\n  else\n    if let some f \u2190 coerceToFunction? s.f then\n      let fType \u2190 inferType f\n      modify fun s => { s with f, fType }\n    else\n      for namedArg in s.namedArgs do\n        let f := s.f.getAppFn\n        if f.isConst then\n          throwInvalidNamedArg namedArg f.constName!\n        else\n          throwInvalidNamedArg namedArg none\n      throwError \"function expected at{indentExpr s.f}\\nterm has type{indentExpr fType}\"\n\n/-- Normalize and return the function type. -/\nprivate def normalizeFunType : M Expr := do\n  let s \u2190 get\n  let fType \u2190 whnfForall s.fType\n  modify fun s => { s with fType }\n  return fType\n\n/-- Return the binder name at `fType`. This method assumes `fType` is a function type. -/\nprivate def getBindingName : M Name := return (\u2190 get).fType.bindingName!\n\n/-- Return the next argument expected type. This method assumes `fType` is a function type. -/\nprivate def getArgExpectedType : M Expr := return (\u2190 get).fType.bindingDomain!\n\n/-- Remove named argument with name `binderName` from `namedArgs`. -/\ndef eraseNamedArg (binderName : Name) : M Unit :=\n  modify fun s => { s with namedArgs := Term.eraseNamedArg s.namedArgs binderName }\n\n/--\n  Add a new argument to the result. That is, `f := f arg`, update `fType`.\n  This method assumes `fType` is a function type. -/\nprivate def addNewArg (argName : Name) (arg : Expr) : M Unit := do\n  modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }\n  if arg.isMVar then\n    let mvarId := arg.mvarId!\n    if let some mvarErrorInfo \u2190 getMVarErrorInfo? mvarId then\n      registerMVarErrorInfo { mvarErrorInfo with argName? := argName }\n\n/--\n  Elaborate the given `Arg` and add it to the result. See `addNewArg`.\n  Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/\nprivate def elabAndAddNewArg (argName : Name) (arg : Arg) : M Unit := do\n  let s \u2190 get\n  let expectedType := (\u2190 getArgExpectedType).consumeTypeAnnotations\n  match arg with\n  | Arg.expr val =>\n    let arg \u2190 ensureArgType s.f val expectedType\n    addNewArg argName arg\n  | Arg.stx stx  =>\n    let val \u2190 elabTerm stx expectedType\n    let arg \u2190 withRef stx <| ensureArgType s.f val expectedType\n    addNewArg argName arg\n\n/-- Return true if `fType` contains `OptParam` or `AutoParams` -/\nprivate def fTypeHasOptAutoParams : M Bool := do\n  hasOptAutoParams (\u2190 get).fType\n\n/--\n   Auxiliary function for retrieving the resulting type of a function application.\n   See `propagateExpectedType`.\n   Remark: `(explicit : Bool) == true` when `@` modifier is used. -/\nprivate partial def getForallBody (explicit : Bool) : Nat \u2192 List NamedArg \u2192 Expr \u2192 Option Expr\n  | i, namedArgs, type@(.forallE n d b bi) =>\n    match findBinderName? namedArgs n with\n    | some _ => getForallBody explicit i (Term.eraseNamedArg namedArgs n) b\n    | none =>\n      if !explicit && !bi.isExplicit then\n        getForallBody explicit i namedArgs b\n      else if i > 0 then\n        getForallBody explicit (i-1) namedArgs b\n      else if d.isAutoParam || d.isOptParam then\n        getForallBody explicit i namedArgs b\n      else\n        some type\n  | 0, [], type => some type\n  | _, _,  _    => none\n\nprivate def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool :=\n  match nextArg with\n  | .expr _  => false -- it has already been elaborated\n  | .stx stx =>\n    -- TODO: make this configurable?\n    stx.getKind != ``Lean.Parser.Term.hole &&\n    stx.getKind != ``Lean.Parser.Term.syntheticHole &&\n    stx.getKind != ``Lean.Parser.Term.byTactic\n\n/--\n  Auxiliary method for propagating the expected type. We call it as soon as we find the first explicit\n  argument. The goal is to propagate the expected type in applications of functions such as\n  ```lean\n  Add.add {\u03b1 : Type u} : \u03b1 \u2192 \u03b1 \u2192 \u03b1\n  List.cons {\u03b1 : Type u} : \u03b1 \u2192 List \u03b1 \u2192 List \u03b1\n  ```\n  This is particularly useful when there applicable coercions. For example,\n  assume we have a coercion from `Nat` to `Int`, and we have\n  `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function,\n  the elaborator will fail to elaborate\n  ```\n  List.cons x []\n  ```\n  First, the elaborator creates a new metavariable `?\u03b1` for the implicit argument `{\u03b1 : Type u}`.\n  Then, when it processes `x`, it assigns `?\u03b1 := Nat`, and then obtains the\n  resultant type `List Nat` which is **not** definitionally equal to `List Int`.\n  We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example).\n  This method infers that the resultant type is `List ?\u03b1` and unifies it with `List Int`.\n  Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the\n  term\n  ```\n  @List.cons Int (coe x) (@List.nil Int)\n  ```\n  is produced.\n\n  The method will do nothing if\n  1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`).\n  2- The resultant type contains optional/auto params.\n\n  We have considered adding the following extra conditions\n    a) The resultant type does not contain any type metavariable.\n    b) The resultant type contains a nontype metavariable.\n\n  These two conditions would restrict the method to simple functions that are \"morally\" in\n  the Hindley&Milner fragment.\n  If users need to disable expected type propagation, we can add an attribute `[elab_without_expected_type]`.\n-/\nprivate def propagateExpectedType (arg : Arg) : M Unit := do\n  if shouldPropagateExpectedTypeFor arg then\n    let s \u2190 get\n    -- TODO: handle s.etaArgs.size > 0\n    unless !s.etaArgs.isEmpty || !s.propagateExpected do\n      match s.expectedType? with\n      | none              => pure ()\n      | some expectedType =>\n        /- We don't propagate `Prop` because we often use `Prop` as a more general \"Bool\" (e.g., `if-then-else`).\n           If we propagate `expectedType == Prop` in the following examples, the elaborator would fail\n           ```\n           def f1 (s : Nat \u00d7 Bool) : Bool := if s.2 then false else true\n\n           def f2 (s : List Bool) : Bool := if s.head! then false else true\n\n           def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true\n           ```\n           They would all fail for the same reason. So, let's focus on the first one.\n           We would elaborate `s.2` with `expectedType == Prop`.\n           Before we elaborate `s`, this method would be invoked, and `s.fType` is `?\u03b1 \u00d7 ?\u03b2 \u2192 ?\u03b2` and after\n           propagation we would have `?\u03b1 \u00d7 Prop \u2192 Prop`. Then, when we would try to elaborate `s`, and\n           get a type error because `?\u03b1 \u00d7 Prop` cannot be unified with `Nat \u00d7 Bool`.\n           Most users would have a hard time trying to understand why these examples failed.\n\n           Here is a possible alternative workaround. We give up the idea of using `Prop` at `if-then-else`.\n           Drawback: users use `if-then-else` with conditions that are not Decidable.\n           So, users would have to embrace `propDecidable` and `choice`.\n           This may not be that bad since the developers and users don't seem to care about constructivism.\n\n           We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/\n        if expectedType.isProp then\n          modify fun s => { s with propagateExpected := false }\n        else\n          let numRemainingArgs := s.args.length\n          trace[Elab.app.propagateExpectedType] \"etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}\"\n          match getForallBody (\u2190 read).explicit numRemainingArgs s.namedArgs s.fType with\n          | none           => pure ()\n          | some fTypeBody =>\n            unless fTypeBody.hasLooseBVars do\n              unless (\u2190 hasOptAutoParams fTypeBody) do\n                trySynthesizeAppInstMVars\n                trace[Elab.app.propagateExpectedType] \"{expectedType} =?= {fTypeBody}\"\n                if (\u2190 isDefEq expectedType fTypeBody) then\n                  /- Note that we only set `propagateExpected := false` when propagation has succeeded. -/\n                  modify fun s => { s with propagateExpected := false }\n\n/-- This method executes after all application arguments have been processed. -/\nprivate def finalize : M Expr := do\n  let s \u2190 get\n  let mut e := s.f\n  -- all user explicit arguments have been consumed\n  trace[Elab.app.finalize] e\n  let ref \u2190 getRef\n  -- Register the error context of implicits\n  for mvarId in s.toSetErrorCtx do\n    registerMVarErrorImplicitArgInfo mvarId ref e\n  if !s.etaArgs.isEmpty then\n    e \u2190 mkLambdaFVars s.etaArgs e\n  /-\n    Remark: we should not use `s.fType` as `eType` even when\n    `s.etaArgs.isEmpty`. Reason: it may have been unfolded.\n  -/\n  let eType \u2190 inferType e\n  trace[Elab.app.finalize] \"after etaArgs, {e} : {eType}\"\n  /- Recall that `resultTypeOutParam? = some mvarId` if the function result type is the output parameter\n     of a local instance. The value of this parameter may be inferable using other arguments. For example,\n     suppose we have\n     ```lean\n     def add_one {X} [Trait X] [One (Trait.R X)] [HAdd X (Trait.R X) X] (x : X) : X := x + (One.one : (Trait.R X))\n     ```\n     from test `948.lean`. There are multiple ways to infer `X`, and we don't want to mark it as `syntheticOpaque`.\n  -/\n  if let some outParamMVarId := s.resultTypeOutParam? then\n    synthesizeAppInstMVars\n    /- If `eType != mkMVar outParamMVarId`, then the\n       function is partially applied, and we do not apply default instances. -/\n    if !(\u2190 outParamMVarId.isAssigned) && eType.isMVar && eType.mvarId! == outParamMVarId then\n      synthesizeSyntheticMVarsUsingDefault\n      return e\n    else\n      return e\n  if let some expectedType := s.expectedType? then\n    trySynthesizeAppInstMVars\n    -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it.\n    trace[Elab.app.finalize] \"expected type: {expectedType}\"\n    discard <| isDefEq expectedType eType\n  synthesizeAppInstMVars\n  return e\n\n/-- Return `true` if there is a named argument that depends on the next argument. -/\nprivate def anyNamedArgDependsOnCurrent : M Bool := do\n  let s \u2190 get\n  if s.namedArgs.isEmpty then\n    return false\n  else\n    forallTelescopeReducing s.fType fun xs _ => do\n      let curr := xs[0]!\n      for i in [1:xs.size] do\n        let xDecl \u2190 xs[i]!.fvarId!.getDecl\n        if s.namedArgs.any fun arg => arg.name == xDecl.userName then\n          /- Remark: a default value at `optParam` does not count as a dependency -/\n          if (\u2190 exprDependsOn xDecl.type.cleanupAnnotations curr.fvarId!) then\n            return true\n      return false\n\n\n/-- Return `true` if there are regular or named arguments to be processed. -/\nprivate def hasArgsToProcess : M Bool := do\n  let s \u2190 get\n  return !s.args.isEmpty || !s.namedArgs.isEmpty\n\n/-- Return `true` if the next argument at `args` is of the form `_` -/\nprivate def isNextArgHole : M Bool := do\n  match (\u2190 get).args with\n  | Arg.stx (Syntax.node _ ``Lean.Parser.Term.hole _) :: _ => pure true\n  | _ => pure false\n\n/--\n  Return `true` if the next argument to be processed is the outparam of a local instance, and it the result type\n  of the function.\n\n  For example, suppose we have the class\n  ```lean\n  class Get (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where\n    get (xs : Cont) (i : Idx) : Elem\n  ```\n  And the current value of `fType` is\n  ```\n  {Cont : Type u_1} \u2192 {Idx : Type u_2} \u2192 {Elem : Type u_3} \u2192 [self : Get Cont Idx Elem] \u2192 Cont \u2192 Idx \u2192 Elem\n  ```\n  then the result returned by this method is `false` since `Cont` is not the output param of any local instance.\n  Now assume `fType` is\n  ```\n  {Elem : Type u_3} \u2192 [self : Get Cont Idx Elem] \u2192 Cont \u2192 Idx \u2192 Elem\n  ```\n  then, the method returns `true` because `Elem` is an output parameter for the local instance `[self : Get Cont Idx Elem]`.\n\n  Remark: if `resultIsOutParamSupport` is `false`, this method returns `false`.\n-/\nprivate partial def isNextOutParamOfLocalInstanceAndResult : M Bool := do\n  if !(\u2190 read).resultIsOutParamSupport then\n    return false\n  let type := (\u2190 get).fType.bindingBody!\n  unless isResultType type 0 do\n    return false\n  if (\u2190 hasLocalInstaceWithOutParams type) then\n    let x := mkFVar (\u2190 mkFreshFVarId)\n    isOutParamOfLocalInstance x (type.instantiate1 x)\n  else\n    return false\nwhere\n  isResultType (type : Expr) (i : Nat) : Bool :=\n    match type with\n    | .forallE _ _ b _ => isResultType b (i + 1)\n    | .bvar idx        => idx == i\n    | _                => false\n\n  /-- (quick filter) Return true if `type` contains a binder `[C ...]` where `C` is a class containing outparams. -/\n  hasLocalInstaceWithOutParams (type : Expr) : CoreM Bool := do\n    let .forallE _ d b bi := type | return false\n    if bi.isInstImplicit then\n      if let .const declName .. := d.getAppFn then\n        if hasOutParams (\u2190 getEnv) declName then\n          return true\n    hasLocalInstaceWithOutParams b\n\n  isOutParamOfLocalInstance (x : Expr) (type : Expr) : MetaM Bool := do\n    let .forallE _ d b bi := type | return false\n    if bi.isInstImplicit then\n      if let .const declName .. := d.getAppFn then\n        if hasOutParams (\u2190 getEnv) declName then\n          let cType \u2190 inferType d.getAppFn\n          if (\u2190 isOutParamOf x 0 d.getAppArgs cType) then\n            return true\n    isOutParamOfLocalInstance x b\n\n  isOutParamOf (x : Expr) (i : Nat) (args : Array Expr) (cType : Expr) : MetaM Bool := do\n    if h : i < args.size then\n      match (\u2190 whnf cType) with\n      | .forallE _ d b _ =>\n        let arg := args.get \u27e8i, h\u27e9\n        if arg == x && d.isOutParam then\n          return true\n        isOutParamOf x (i+1) args b\n      | _ => return false\n    else\n      return false\n\nmutual\n  /--\n    Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`,\n    and then execute the main loop.-/\n  private partial def addEtaArg (argName : Name) : M Expr := do\n    let n    \u2190 getBindingName\n    let type \u2190 getArgExpectedType\n    withLocalDeclD n type fun x => do\n      modify fun s => { s with etaArgs := s.etaArgs.push x }\n      addNewArg argName x\n      main\n\n  private partial def addImplicitArg (argName : Name) : M Expr := do\n    let argType \u2190 getArgExpectedType\n    let arg \u2190 if (\u2190 isNextOutParamOfLocalInstanceAndResult) then\n      let arg \u2190 mkFreshExprMVar argType\n      /- When the result type is an output parameter, we don't want to propagate the expected type.\n         So, we just mark `propagateExpected := false` to disable it.\n         At `finalize`, we check whether `arg` is still unassigned, if it is, we apply default instances,\n         and try to synthesize pending mvars. -/\n      modify fun s => { s with resultTypeOutParam? := some arg.mvarId!, propagateExpected := false }\n      pure arg\n    else\n      mkFreshExprMVar argType\n    modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! }\n    addNewArg argName arg\n    main\n\n  /--\n    Process a `fType` of the form `(x : A) \u2192 B x`.\n    This method assume `fType` is a function type -/\n  private partial def processExplictArg (argName : Name) : M Expr := do\n    match (\u2190 get).args with\n    | arg::args =>\n      if (\u2190 anyNamedArgDependsOnCurrent) then\n        /-\n        We treat the explicit argument `argName` as implicit if we have named arguments that depend on it.\n        The idea is that this explicit argument can be inferred using the type of the named argument one.\n        Note that we also use this approach in the branch where there are no explicit arguments left.\n        This is important to make sure the system behaves in a uniform way.\n        Moreover, users rely on this behavior. For example, consider the example on issue #1851\n        ```\n        class Approx {\u03b1 : Type} (a : \u03b1) (X : Type) : Type where\n          val : X\n\n        variable {\u03b1 \u03b2 X Y : Type} {f' : \u03b1 \u2192 \u03b2} {x' : \u03b1} [f : Approx f' (X \u2192 Y)] [x : Approx x' X]\n\n        #check f.val\n        #check f.val x.val\n        ```\n        The type of `Approx.val` is `{\u03b1 : Type} \u2192 (a : \u03b1) \u2192 {X : Type} \u2192 [self : Approx a X] \u2192 X`\n        Note that the argument `a` is explicit since there is no way to infer it from the expected\n        type or the type of other explicit arguments.\n        Recall that `f.val` is sugar for `Approx.val (self := f)`. In both `#check` commands above\n        the user assumed that `a` does not need to be provided since it can be inferred from the type\n        of `self`.\n        We used to that only in the branch where `(\u2190 get).args` was empty, but it created an asymmetry\n        because `#check f.val` worked as expected, but one would have to write `#check f.val _ x.val`\n        -/\n        return (\u2190 addImplicitArg argName)\n      propagateExpectedType arg\n      modify fun s => { s with args }\n      elabAndAddNewArg argName arg\n      main\n    | _ =>\n      let argType \u2190 getArgExpectedType\n      match (\u2190 read).explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with\n      | false, some defVal, _  => addNewArg argName defVal; main\n      | false, _, some (.const tacticDecl _) =>\n        let env \u2190 getEnv\n        let opts \u2190 getOptions\n        match evalSyntaxConstant env opts tacticDecl with\n        | Except.error err       => throwError err\n        | Except.ok tacticSyntax =>\n          -- TODO(Leo): does this work correctly for tactic sequences?\n          let tacticBlock \u2190 `(by $(\u27e8tacticSyntax\u27e9))\n          let argNew := Arg.stx tacticBlock\n          propagateExpectedType argNew\n          elabAndAddNewArg argName argNew\n          main\n      | false, _, some _ =>\n        throwError \"invalid autoParam, argument must be a constant\"\n      | _, _, _ =>\n        if !(\u2190 get).namedArgs.isEmpty then\n          if (\u2190 anyNamedArgDependsOnCurrent) then\n            addImplicitArg argName\n          else if (\u2190 read).ellipsis then\n            addImplicitArg argName\n          else\n            addEtaArg argName\n        else if !(\u2190 read).explicit then\n          if (\u2190 read).ellipsis then\n            addImplicitArg argName\n          else if (\u2190 fTypeHasOptAutoParams) then\n            addEtaArg argName\n          else\n            finalize\n        else\n          finalize\n\n  /--\n    Process a `fType` of the form `{x : A} \u2192 B x`.\n    This method assume `fType` is a function type -/\n  private partial def processImplicitArg (argName : Name) : M Expr := do\n    if (\u2190 read).explicit then\n      processExplictArg argName\n    else\n      addImplicitArg argName\n\n  /--\n    Process a `fType` of the form `{{x : A}} \u2192 B x`.\n    This method assume `fType` is a function type -/\n  private partial def processStrictImplicitArg (argName : Name) : M Expr := do\n    if (\u2190 read).explicit then\n      processExplictArg argName\n    else if (\u2190 hasArgsToProcess) then\n      addImplicitArg argName\n    else\n      finalize\n\n  /--\n    Process a `fType` of the form `[x : A] \u2192 B x`.\n    This method assume `fType` is a function type -/\n  private partial def processInstImplicitArg (argName : Name) : M Expr := do\n    if (\u2190 read).explicit then\n      if (\u2190 isNextArgHole) then\n        /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/\n        let arg \u2190 mkFreshExprMVar (\u2190 getArgExpectedType) MetavarKind.synthetic\n        modify fun s => { s with args := s.args.tail! }\n        addInstMVar arg.mvarId!\n        addNewArg argName arg\n        main\n      else\n        processExplictArg argName\n    else\n      let arg \u2190 mkFreshExprMVar (\u2190 getArgExpectedType) MetavarKind.synthetic\n      addInstMVar arg.mvarId!\n      addNewArg argName arg\n      main\n\n  /-- Elaborate function application arguments. -/\n  partial def main : M Expr := do\n    let fType \u2190 normalizeFunType\n    if fType.isForall then\n      let binderName := fType.bindingName!\n      let binfo := fType.bindingInfo!\n      let s \u2190 get\n      match findBinderName? s.namedArgs binderName with\n      | some namedArg =>\n        propagateExpectedType namedArg.val\n        eraseNamedArg binderName\n        elabAndAddNewArg binderName namedArg.val\n        main\n      | none          =>\n        match binfo with\n        | .implicit       => processImplicitArg binderName\n        | .instImplicit   => processInstImplicitArg binderName\n        | .strictImplicit => processStrictImplicitArg binderName\n        | _               => processExplictArg binderName\n    else if (\u2190 hasArgsToProcess) then\n      synthesizePendingAndNormalizeFunType\n      main\n    else\n      finalize\n\nend\n\nend ElabAppArgs\n\nbuiltin_initialize elabAsElim : TagAttribute \u2190\n  registerTagAttribute `elab_as_elim\n    \"instructs elaborator that the arguments of the function application should be elaborated as were an eliminator\"\n    /-\n    We apply `elab_as_elim` after compilation because this kind of attribute is not applied to auxiliary declarations\n    created by the `WF` and `Structural` modules. This is an \"indirect\" fix for issue #1900. We should consider\n    having an explicit flag in attributes to indicate whether they should be copied to auxiliary declarations or not.\n    -/\n    (applicationTime := .afterCompilation)\n    fun declName => do\n      let go : MetaM Unit := do\n        discard <| getElimInfo declName\n        let info \u2190 getConstInfo declName\n        if (\u2190 hasOptAutoParams info.type) then\n          throwError \"[elab_as_elim] attribute cannot be used in declarations containing optional and auto parameters\"\n      go.run' {} {}\n\n/-! # Eliminator-like function application elaborator -/\nnamespace ElabElim\n\n/-- Context of the `elab_as_elim` elaboration procedure. -/\nstructure Context where\n  elimInfo : ElimInfo\n  expectedType : Expr\n  /--\n  Position of additional arguments that should be elaborated eagerly\n  because they can contribute to the motive inference procedure.\n  For example, in the following theorem the argument `h : a = b`\n  should be elaborated eagerly because it contains `b` which occurs\n  in `motive b`.\n  ```\n  theorem Eq.subst' {\u03b1} {motive : \u03b1 \u2192 Prop} {a b : \u03b1} (h : a = b) : motive a \u2192 motive b\n  ```\n  -/\n  extraArgsPos : Array Nat\n\n/-- State of the `elab_as_elim` elaboration procedure. -/\nstructure State where\n  /-- The resultant expression being built. -/\n  f            : Expr\n  /-- `f : fType -/\n  fType        : Expr\n  /-- User-provided named arguments that still have to be processed. -/\n  namedArgs    : List NamedArg\n  /-- User-provided arguments that still have to be processed. -/\n  args         : List Arg\n  /-- Discriminants processed so far. -/\n  discrs       : Array Expr := #[]\n  /-- Instance implicit arguments collected so far. -/\n  instMVars    : Array MVarId := #[]\n  /-- Position of the next argument to be processed. We use it to decide whether the argument is the motive or a discriminant. -/\n  idx          : Nat := 0\n  /-- Store the metavariable used to represent the motive that will be computed at `finalize`. -/\n  motive?      : Option Expr := none\n\nabbrev M := ReaderT Context $ StateRefT State TermElabM\n\n/-- Infer the `motive` using the expected type by `kabstract`ing the discriminants. -/\ndef mkMotive (discrs : Array Expr) (expectedType : Expr): MetaM Expr := do\n  discrs.foldrM (init := expectedType) fun discr motive => do\n    let discr \u2190 instantiateMVars discr\n    let motiveBody \u2190 kabstract motive discr\n    /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/\n    let discrType \u2190 transform (usedLetOnly := true) (\u2190 instantiateMVars (\u2190 inferType discr))\n    return Lean.mkLambda (\u2190 mkFreshBinderName) BinderInfo.default discrType motiveBody\n\n/-- If the eliminator is over-applied, we \"revert\" the extra arguments. -/\ndef revertArgs (args : List Arg) (f : Expr) (expectedType : Expr) : TermElabM (Expr \u00d7 Expr) :=\n  args.foldrM (init := (f, expectedType)) fun arg (f, expectedType) => do\n    let val \u2190\n      match arg with\n      | .expr val => pure val\n      | .stx stx => elabTerm stx none\n    let val \u2190 instantiateMVars val\n    let expectedTypeBody \u2190 kabstract expectedType val\n    /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/\n    let valType \u2190 transform (usedLetOnly := true) (\u2190 instantiateMVars (\u2190 inferType val))\n    return (mkApp f val, mkForall (\u2190 mkFreshBinderName) BinderInfo.default valType expectedTypeBody)\n\n/--\nConstruct the resulting application after all discriminants have bee elaborated, and we have\nconsumed as many given arguments as possible.\n-/\ndef finalize : M Expr := do\n  unless (\u2190 get).namedArgs.isEmpty do\n    throwError \"failed to elaborate eliminator, unused named arguments: {(\u2190 get).namedArgs.map (\u00b7.name)}\"\n  let some motive := (\u2190 get).motive?\n    | throwError \"failed to elaborate eliminator, insufficient number of arguments\"\n  forallTelescope (\u2190 get).fType fun xs _ => do\n    let mut expectedType := (\u2190 read).expectedType\n    let mut f := (\u2190 get).f\n    if xs.size > 0 then\n      assert! (\u2190 get).args.isEmpty\n      try\n        expectedType \u2190 instantiateForall expectedType xs\n      catch _ =>\n        throwError \"failed to elaborate eliminator, insufficient number of arguments, expected type:{indentExpr expectedType}\"\n    else\n      -- over-application, simulate `revert`\n      (f, expectedType) \u2190 revertArgs (\u2190 get).args f expectedType\n    let result := mkAppN f xs\n    let mut discrs := (\u2190 get).discrs\n    let idx := (\u2190 get).idx\n    if (\u2190 get).discrs.size < (\u2190 read).elimInfo.targetsPos.size then\n      for i in [idx:idx + xs.size], x in xs do\n        if (\u2190 read).elimInfo.targetsPos.contains i then\n          discrs := discrs.push x\n    let motiveVal \u2190 mkMotive discrs expectedType\n    unless (\u2190 isDefEq motive motiveVal) do\n      throwError \"failed to elaborate eliminator, invalid motive{indentExpr motiveVal}\"\n    synthesizeAppInstMVars (\u2190 get).instMVars result\n    let result \u2190 mkLambdaFVars xs (\u2190 instantiateMVars result)\n    return result\n\n/--\nReturn the next argument to be processed.\nThe result is `.none` if it is an implicit argument which was not provided using a named argument.\nThe result is `.undef` if `args` is empty and `namedArgs` does contain an entry for `binderName`.\n-/\ndef getNextArg? (binderName : Name) (binderInfo : BinderInfo) : M (LOption Arg) := do\n  match findBinderName? (\u2190 get).namedArgs binderName with\n  | some namedArg =>\n    modify fun s => { s with namedArgs := eraseNamedArg s.namedArgs binderName }\n    return .some namedArg.val\n  | none =>\n    if binderInfo.isExplicit then\n      match (\u2190 get).args with\n      | [] => return .undef\n      | arg :: args =>\n        modify fun s => { s with args }\n        return .some arg\n    else\n      return .none\n\n/-- Set the `motive` field in the state. -/\ndef setMotive (motive : Expr) : M Unit :=\n  modify fun s => { s with motive? := motive }\n\n/-- Push the given expression into the `discrs` field in the state. -/\ndef addDiscr (discr : Expr) : M Unit :=\n  modify fun s => { s with discrs := s.discrs.push discr }\n\n/-- Elaborate the given argument with the given expected type. -/\nprivate def elabArg (arg : Arg) (argExpectedType : Expr) : M Expr := do\n  match arg with\n  | Arg.expr val => ensureArgType (\u2190 get).f val argExpectedType\n  | Arg.stx stx  =>\n    let val \u2190 elabTerm stx argExpectedType\n    withRef stx <| ensureArgType (\u2190 get).f val argExpectedType\n\n/-- Save information for producing error messages. -/\ndef saveArgInfo (arg : Expr) (binderName : Name) : M Unit := do\n  if arg.isMVar then\n    let mvarId := arg.mvarId!\n    if let some mvarErrorInfo \u2190 getMVarErrorInfo? mvarId then\n      registerMVarErrorInfo { mvarErrorInfo with argName? := binderName }\n\n/-- Create an implicit argument using the given `BinderInfo`. -/\ndef mkImplicitArg (argExpectedType : Expr) (bi : BinderInfo) : M Expr := do\n  let arg \u2190 mkFreshExprMVar argExpectedType (if bi.isInstImplicit then .synthetic else .natural)\n  if bi.isInstImplicit then\n    modify fun s => { s with instMVars := s.instMVars.push arg.mvarId! }\n  return arg\n\n/-- Main loop of the `elimAsElab` procedure. -/\npartial def main : M Expr := do\n  let .forallE binderName binderType body binderInfo \u2190 whnfForall (\u2190 get).fType |\n    finalize\n  let addArgAndContinue (arg : Expr) : M Expr := do\n    modify fun s => { s with idx := s.idx + 1, f := mkApp s.f arg, fType := body.instantiate1 arg }\n    saveArgInfo arg binderName\n    main\n  let idx := (\u2190 get).idx\n  if (\u2190 read).elimInfo.motivePos == idx then\n    let motive \u2190 mkImplicitArg binderType binderInfo\n    setMotive motive\n    addArgAndContinue motive\n  else if (\u2190 read).elimInfo.targetsPos.contains idx then\n    match (\u2190 getNextArg? binderName binderInfo) with\n    | .some arg => let discr \u2190 elabArg arg binderType; addDiscr discr; addArgAndContinue discr\n    | .undef => finalize\n    | .none => let discr \u2190 mkImplicitArg binderType binderInfo; addDiscr discr; addArgAndContinue discr\n  else match (\u2190 getNextArg? binderName binderInfo) with\n    | .some (.stx stx) =>\n      if (\u2190 read).extraArgsPos.contains idx then\n        let arg \u2190 elabArg (.stx stx) binderType\n        addArgAndContinue arg\n      else\n        addArgAndContinue (\u2190 postponeElabTerm stx binderType)\n    | .some (.expr val) => addArgAndContinue (\u2190 ensureArgType (\u2190 get).f val binderType)\n    | .undef => finalize\n    | .none => addArgAndContinue (\u2190 mkImplicitArg binderType binderInfo)\n\nend ElabElim\n\n/-- Return `true` if `declName` is a candidate for `ElabElim.main` elaboration. -/\nprivate def shouldElabAsElim (declName : Name) : CoreM Bool := do\n  if (\u2190 isRec declName) then return true\n  let env \u2190 getEnv\n  if isCasesOnRecursor env declName then return true\n  if isBRecOnRecursor env declName then return true\n  if isRecOnRecursor env declName then return true\n  return elabAsElim.hasTag env declName\n\nprivate def propagateExpectedTypeFor (f : Expr) : TermElabM Bool :=\n  match f.getAppFn.constName? with\n  | some declName => return !hasElabWithoutExpectedType (\u2190 getEnv) declName\n  | _ => return true\n\n/-! # Function application elaboration -/\n\n/--\nElaborate a `f`-application using `namedArgs` and `args` as the arguments.\n- `expectedType?` the expected type if available. It is used to propagate typing information only. This method does **not** ensure the result has this type.\n- `explicit = true` when notation `@` is used, and implicit arguments are assumed to be provided at `namedArgs` and `args`.\n- `ellipsis = true` when notation `..` is used. That is, we add `_` for missing arguments.\n- `resultIsOutParamSupport` is used to control whether special support is used when processing applications of functions that return\n   output parameter of some local instance. Example:\n   ```\n   GetElem.getElem : {Cont : Type u_1} \u2192 {Idx : Type u_2} \u2192 {elem : Type u_3} \u2192 {dom : cont \u2192 idx \u2192 Prop} \u2192 [self : GetElem cont idx elem dom] \u2192 (xs : cont) \u2192 (i : idx) \u2192 dom xs i \u2192 elem\n   ```\n   The result type `elem` is the output parameter of the local instance `self`.\n   When this parameter is set to `true`, we execute `synthesizeSyntheticMVarsUsingDefault`. For additional details, see comment at\n   `ElabAppArgs.resultIsOutParam`.\n-/\ndef elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg)\n    (expectedType? : Option Expr) (explicit ellipsis : Bool) (resultIsOutParamSupport := true) : TermElabM Expr := do\n  -- Coercions must be available to use this flag.\n  -- If `@` is used (i.e., `explicit = true`), we disable `resultIsOutParamSupport`.\n  let resultIsOutParamSupport := ((\u2190 getEnv).contains ``Lean.Internal.coeM) && resultIsOutParamSupport && !explicit\n  let fType \u2190 inferType f\n  let fType \u2190 instantiateMVars fType\n  unless namedArgs.isEmpty && args.isEmpty do\n    tryPostponeIfMVar fType\n  trace[Elab.app.args] \"explicit: {explicit}, ellipsis: {ellipsis}, {f} : {fType}\"\n  trace[Elab.app.args] \"namedArgs: {namedArgs}\"\n  trace[Elab.app.args] \"args: {args}\"\n  if let some elimInfo \u2190 elabAsElim? then\n    tryPostponeIfNoneOrMVar expectedType?\n    let some expectedType := expectedType? | throwError \"failed to elaborate eliminator, expected type is not available\"\n    let expectedType \u2190 instantiateMVars expectedType\n    if expectedType.getAppFn.isMVar then throwError \"failed to elaborate eliminator, expected type is not available\"\n    let extraArgsPos \u2190 getElabAsElimExtraArgsPos elimInfo\n    ElabElim.main.run { elimInfo, expectedType, extraArgsPos } |>.run' {\n      f, fType\n      args := args.toList\n      namedArgs := namedArgs.toList\n    }\n  else\n    ElabAppArgs.main.run { explicit, ellipsis, resultIsOutParamSupport } |>.run' {\n      args := args.toList\n      expectedType?, f, fType\n      namedArgs := namedArgs.toList\n      propagateExpected := (\u2190 propagateExpectedTypeFor f)\n    }\nwhere\n  /-- Return `some info` if we should elaborate as an eliminator. -/\n  elabAsElim? : TermElabM (Option ElimInfo) := do\n    if explicit || ellipsis then return none\n    let .const declName _ := f | return none\n    unless (\u2190 shouldElabAsElim declName) do return none\n    let elimInfo \u2190 getElimInfo declName\n    forallTelescopeReducing (\u2190 inferType f) fun xs _ => do\n      if h : elimInfo.motivePos < xs.size then\n        let x := xs[elimInfo.motivePos]\n        let localDecl \u2190 x.fvarId!.getDecl\n        if findBinderName? namedArgs.toList localDecl.userName matches some _ then\n          -- motive has been explicitly provided, so we should use standard app elaborator\n          return none\n        return some elimInfo\n      else\n        return none\n\n  /--\n  Collect extra argument positions that must be elaborated eagerly when using `elab_as_elim`.\n  The idea is that the contribute to motive inference. See comment at `ElamElim.Context.extraArgsPos`.\n  -/\n  getElabAsElimExtraArgsPos (elimInfo : ElimInfo) : MetaM (Array Nat) := do\n    let cinfo \u2190 getConstInfo elimInfo.name\n    forallTelescope cinfo.type fun xs type => do\n      let resultArgs := type.getAppArgs\n      let mut extraArgsPos := #[]\n      for i in [:xs.size] do\n        let x := xs[i]!\n        unless elimInfo.targetsPos.contains i do\n          let xType \u2190 inferType x\n          /- We only consider \"first-order\" types because we can reliably \"extract\" information from them. -/\n          if isFirstOrder xType\n             && Option.isSome (xType.find? fun e => e.isFVar && resultArgs.contains e) then\n            extraArgsPos := extraArgsPos.push i\n      return extraArgsPos\n\n  /-\n  Helper function for implementing `elab_as_elim`.\n  We say a term is \"first-order\" if all applications are of the form `f ...` where `f` is a constant.\n  -/\n  isFirstOrder (e : Expr) : Bool :=\n    Option.isNone <| e.find? fun e =>\n      e.isApp && !e.getAppFn.isConst\n\n/-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/\ninductive LValResolution where\n  | projFn   (baseStructName : Name) (structName : Name) (fieldName : Name)\n  | projIdx  (structName : Name) (idx : Nat)\n  | const    (baseStructName : Name) (structName : Name) (constName : Name)\n  | localRec (baseName : Name) (fullName : Name) (fvar : Expr)\n\nprivate def throwLValError (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM \u03b1 :=\n  throwError \"{msg}{indentExpr e}\\nhas type{indentExpr eType}\"\n\n/--\n`findMethod? env S fName`.\n- If `env` contains `S ++ fName`, return `(S, S++fName)`\n- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o\n- Otherwise for each parent structure `S'` of  `S`, we try `findMethod? env S' fname`\n-/\nprivate partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name \u00d7 Name) :=\n  let fullName := structName ++ fieldName\n  match env.find? fullName with\n  | some _ => some (structName, fullName)\n  | none   =>\n    let fullNamePrv := mkPrivateName env fullName\n    match env.find? fullNamePrv with\n    | some _ => some (structName, fullNamePrv)\n    | none   =>\n      if isStructure env structName then\n        (getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName\n      else\n        none\n\n/--\n  Return `some (structName', fullName)` if `structName ++ fieldName` is an alias for `fullName`, and\n  `fullName` is of the form `structName' ++ fieldName`.\n\n  TODO: if there is more than one applicable alias, it returns `none`. We should consider throwing an error or\n  warning.\n-/\nprivate def findMethodAlias? (env : Environment) (structName fieldName : Name) : Option (Name \u00d7 Name) :=\n  let fullName := structName ++ fieldName\n  -- We never skip `protected` aliases when resolving dot-notation.\n  let aliasesCandidates := getAliases env fullName (skipProtected := false) |>.filterMap fun alias =>\n    match alias.eraseSuffix? fieldName with\n    | none => none\n    | some structName' => some (structName', alias)\n  match aliasesCandidates with\n  | [r] => some r\n  | _   => none\n\nprivate def throwInvalidFieldNotation (e eType : Expr) : TermElabM \u03b1 :=\n  throwLValError e eType \"invalid field notation, type is not of the form (C ...) where C is a constant\"\n\nprivate def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do\n  if eType.isForall then\n    match lval with\n    | LVal.fieldName _ fieldName _ _ =>\n      let fullName := `Function ++ fieldName\n      if (\u2190 getEnv).contains fullName then\n        return LValResolution.const `Function `Function fullName\n    | _ => pure ()\n  match eType.getAppFn.constName?, lval with\n  | some structName, LVal.fieldIdx _ idx =>\n    if idx == 0 then\n      throwError \"invalid projection, index must be greater than 0\"\n    let env \u2190 getEnv\n    unless isStructureLike env structName do\n      throwLValError e eType \"invalid projection, structure expected\"\n    let numFields := getStructureLikeNumFields env structName\n    if idx - 1 < numFields then\n      if isStructure env structName then\n        let fieldNames := getStructureFields env structName\n        return LValResolution.projFn structName structName fieldNames[idx - 1]!\n      else\n        /- `structName` was declared using `inductive` command.\n           So, we don't projection functions for it. Thus, we use `Expr.proj` -/\n        return LValResolution.projIdx structName (idx - 1)\n    else\n      throwLValError e eType m!\"invalid projection, structure has only {numFields} field(s)\"\n  | some structName, LVal.fieldName _ fieldName _ _ =>\n    let env \u2190 getEnv\n    let searchEnv : Unit \u2192 TermElabM LValResolution := fun _ => do\n      if let some (baseStructName, fullName) := findMethod? env structName fieldName then\n        return LValResolution.const baseStructName structName fullName\n      else if let some (structName', fullName) := findMethodAlias? env structName fieldName then\n        return LValResolution.const structName' structName' fullName\n      else\n        throwLValError e eType\n          m!\"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'\"\n    -- search local context first, then environment\n    let searchCtx : Unit \u2192 TermElabM LValResolution := fun _ => do\n      let fullName := Name.mkStr structName fieldName\n      for localDecl in (\u2190 getLCtx) do\n        if localDecl.isAuxDecl then\n          if let some localDeclFullName := (\u2190 read).auxDeclToFullName.find? localDecl.fvarId then\n            if fullName == (privateToUserName? localDeclFullName).getD localDeclFullName then\n              /- LVal notation is being used to make a \"local\" recursive call. -/\n              return LValResolution.localRec structName fullName localDecl.toExpr\n      searchEnv ()\n    if isStructure env structName then\n      match findField? env structName (Name.mkSimple fieldName) with\n      | some baseStructName => return LValResolution.projFn baseStructName structName (Name.mkSimple fieldName)\n      | none                => searchCtx ()\n    else\n      searchCtx ()\n  | none, LVal.fieldName _ _ (some suffix) _ =>\n    if e.isConst then\n      throwUnknownConstant (e.constName! ++ suffix)\n    else\n      throwInvalidFieldNotation e eType\n  | _, _ => throwInvalidFieldNotation e eType\n\n/-- whnfCore + implicit consumption.\n   Example: given `e` with `eType := {\u03b1 : Type} \u2192 (fun \u03b2 => List \u03b2) \u03b1 `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/\nprivate partial def consumeImplicits (stx : Syntax) (e eType : Expr) (hasArgs : Bool) : TermElabM (Expr \u00d7 Expr) := do\n  let eType \u2190 whnfCore eType\n  match eType with\n  | .forallE _ d b bi =>\n    if bi.isImplicit || (hasArgs && bi.isStrictImplicit) then\n      let mvar \u2190 mkFreshExprMVar d\n      registerMVarErrorHoleInfo mvar.mvarId! stx\n      consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) hasArgs\n    else if bi.isInstImplicit then\n      let mvar \u2190 mkInstMVar d\n      let r := mkApp e mvar\n      registerMVarErrorImplicitArgInfo mvar.mvarId! stx r\n      consumeImplicits stx r (b.instantiate1 mvar) hasArgs\n    else match d.getOptParamDefault? with\n      | some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal) hasArgs\n      -- TODO: we do not handle autoParams here.\n      | _ => return (e, eType)\n  | _ => return (e, eType)\n\nprivate partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) (hasArgs : Bool) : TermElabM (Expr \u00d7 LValResolution) := do\n  let (e, eType) \u2190 consumeImplicits lval.getRef e eType hasArgs\n  tryPostponeIfMVar eType\n  /- If `eType` is still a metavariable application, we try to apply default instances to \"unblock\" it. -/\n  if (\u2190 isMVarApp eType) then\n    synthesizeSyntheticMVarsUsingDefault\n  let eType \u2190 instantiateMVars eType\n  try\n    let lvalRes \u2190 resolveLValAux e eType lval\n    return (e, lvalRes)\n  catch\n    | ex@(Exception.error _ _) =>\n      let eType? \u2190 unfoldDefinition? eType\n      match eType? with\n      | some eType => resolveLValLoop lval e eType (previousExceptions.push ex) hasArgs\n      | none       =>\n        previousExceptions.forM fun ex => logException ex\n        throw ex\n    | ex@(Exception.internal _ _) => throw ex\n\nprivate def resolveLVal (e : Expr) (lval : LVal) (hasArgs : Bool) : TermElabM (Expr \u00d7 LValResolution) := do\n  let eType \u2190 inferType e\n  resolveLValLoop lval e eType #[] hasArgs\n\nprivate partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do\n  let env \u2190 getEnv\n  match getPathToBaseStructure? env baseStructName structName with\n  | none => throwError \"failed to access field in parent structure\"\n  | some path =>\n    let mut e := e\n    for projFunName in path do\n      let projFn \u2190 mkConst projFunName\n      e \u2190 elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false)\n    return e\n\nprivate def typeMatchesBaseName (type : Expr) (baseName : Name) : MetaM Bool := do\n  if baseName == `Function then\n    return (\u2190 whnfR type).isForall\n  else if type.consumeMData.isAppOf baseName then\n    return true\n  else\n    return (\u2190 whnfR type).isAppOf baseName\n\n/-- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`.\n   This method first finds the parameter with a type of the form `(baseName ...)`.\n   When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`.\n   Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`.\n\n   Remark: `fullName` is the name of the resolved \"field\" access function. It is used for reporting errors -/\nprivate def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr)\n    : TermElabM (Array Arg \u00d7 Array NamedArg) :=\n  forallTelescopeReducing fType fun xs _ => do\n    let mut argIdx := 0 -- position of the next explicit argument\n    let mut remainingNamedArgs := namedArgs\n    for i in [:xs.size] do\n      let x := xs[i]!\n      let xDecl \u2190 x.fvarId!.getDecl\n      /- If there is named argument with name `xDecl.userName`, then we skip it. -/\n      match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with\n      | some idx =>\n        remainingNamedArgs := remainingNamedArgs.eraseIdx idx\n      | none =>\n        let type := xDecl.type\n        if (\u2190 typeMatchesBaseName type baseName) then\n          /- We found a type of the form (baseName ...).\n             First, we check if the current argument is an explicit one,\n             and the current explicit position \"fits\" at `args` (i.e., it must be \u2264 arg.size) -/\n          if argIdx \u2264 args.size && xDecl.binderInfo.isExplicit then\n            /- We insert `e` as an explicit argument -/\n            return (args.insertAt! argIdx (Arg.expr e), namedArgs)\n          /- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible\n             if there isn't an argument with the same name occurring before it. -/\n          for j in [:i] do\n            let prev := xs[j]!\n            let prevDecl \u2190 prev.fvarId!.getDecl\n            if prevDecl.userName == xDecl.userName then\n              throwError \"invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\\nbut it cannot be used\"\n          return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e })\n        if xDecl.binderInfo.isExplicit then\n          -- advance explicit argument position\n          argIdx := argIdx + 1\n    throwError \"invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with a unique name\"\n\nprivate def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool)\n    (f : Expr) (lvals : List LVal) : TermElabM Expr :=\n  let rec loop : Expr \u2192 List LVal \u2192 TermElabM Expr\n  | f, []          => elabAppArgs f namedArgs args expectedType? explicit ellipsis\n  | f, lval::lvals => do\n    if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then\n      addDotCompletionInfo targetStx f expectedType? fieldStx\n    let hasArgs := !namedArgs.isEmpty || !args.isEmpty\n    let (f, lvalRes) \u2190 resolveLVal f lval hasArgs\n    match lvalRes with\n    | LValResolution.projIdx structName idx =>\n      let f \u2190 mkProjAndCheck structName idx f\n      let f \u2190 addTermInfo lval.getRef f\n      loop f lvals\n    | LValResolution.projFn baseStructName structName fieldName =>\n      let f \u2190 mkBaseProjections baseStructName structName f\n      if let some info := getFieldInfo? (\u2190 getEnv) baseStructName fieldName then\n        if isPrivateNameFromImportedModule (\u2190 getEnv) info.projFn then\n          throwError \"field '{fieldName}' from structure '{structName}' is private\"\n        let projFn \u2190 mkConst info.projFn\n        let projFn \u2190 addTermInfo lval.getRef projFn\n        if lvals.isEmpty then\n          let namedArgs \u2190 addNamedArg namedArgs { name := `self, val := Arg.expr f }\n          elabAppArgs projFn namedArgs args expectedType? explicit ellipsis\n        else\n          let f \u2190 elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false)\n          loop f lvals\n      else\n        unreachable!\n    | LValResolution.const baseStructName structName constName =>\n      let f \u2190 if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f\n      let projFn \u2190 mkConst constName\n      let projFn \u2190 addTermInfo lval.getRef projFn\n      if lvals.isEmpty then\n        let projFnType \u2190 inferType projFn\n        let (args, namedArgs) \u2190 addLValArg baseStructName constName f args namedArgs projFnType\n        elabAppArgs projFn namedArgs args expectedType? explicit ellipsis\n      else\n        let f \u2190 elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false)\n        loop f lvals\n    | LValResolution.localRec baseName fullName fvar =>\n      let fvar \u2190 addTermInfo lval.getRef fvar\n      if lvals.isEmpty then\n        let fvarType \u2190 inferType fvar\n        let (args, namedArgs) \u2190 addLValArg baseName fullName f args namedArgs fvarType\n        elabAppArgs fvar namedArgs args expectedType? explicit ellipsis\n      else\n        let f \u2190 elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false)\n        loop f lvals\n  loop f lvals\n\nprivate def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)\n    (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do\n  if !lvals.isEmpty && explicit then\n    throwError \"invalid use of field notation with `@` modifier\"\n  elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals\n\ndef elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do\n  lvls.foldrM (init := []) fun stx lvls => return (\u2190 elabLevel stx)::lvls\n\n/-!\n# Interaction between `errToSorry` and `observing`.\n\n- The method `elabTerm` catches exceptions, logs them, and returns a synthetic sorry (IF `ctx.errToSorry` == true).\n\n- When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator.\n  The `observing x` executes `x` and returns a `TermElabResult`.\n\n`observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't\nif a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution\nbecause it would not be clear to decide what the \"main\" error message for the alternative is. When the result contains\na synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many\nerror messages may have been logged. Recall that we need an error per alternative at `mergeFailures`.\n\nThus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols.\n\nImportant: we rely on the property that after `errToSorry` is set to\nfalse, no elaboration function executed by `x` will reset it to\n`true`.\n-/\n\nprivate partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal)\n    (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr))\n    : TermElabM (Array (TermElabResult Expr)) := do\n  let funLVals \u2190 withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType?\n  let overloaded := overloaded || funLVals.length > 1\n  -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`.\n  withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do\n    funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do\n      let lvals' := toLVals fields (first := true)\n      let s \u2190 observing do\n        let f \u2190 addTermInfo fIdent f expectedType?\n        let e \u2190 elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis\n        if overloaded then ensureHasType expectedType? e else return e\n      return acc.push s\nwhere\n  toName (fields : List Syntax) : Name :=\n    let rec go\n      | []              => .anonymous\n      | field :: fields => .mkStr (go fields) field.getId.toString\n    go fields.reverse\n\n  toLVals : List Syntax \u2192 (first : Bool) \u2192 List LVal\n    | [],            _     => []\n    | field::fields, true  => .fieldName field field.getId.getString! (toName (field::fields)) fIdent :: toLVals fields false\n    | field::fields, false => .fieldName field field.getId.getString! none fIdent :: toLVals fields false\n\n/-- Resolve `(.$id:ident)` using the expected type to infer namespace. -/\nprivate partial def resolveDotName (id : Syntax) (expectedType? : Option Expr) : TermElabM Name := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let some expectedType := expectedType?\n    | throwError \"invalid dotted identifier notation, expected type must be known\"\n  forallTelescopeReducing expectedType fun _ resultType => do\n    go resultType expectedType #[]\nwhere\n  go (resultType : Expr) (expectedType : Expr) (previousExceptions : Array Exception) : TermElabM Name := do\n    let resultType \u2190 instantiateMVars resultType\n    let resultTypeFn := resultType.cleanupAnnotations.getAppFn\n    try\n      tryPostponeIfMVar resultTypeFn\n      let .const declName .. := resultTypeFn.cleanupAnnotations\n        | throwError \"invalid dotted identifier notation, expected type is not of the form (... \u2192 C ...) where C is a constant{indentExpr expectedType}\"\n      let idNew := declName ++ id.getId.eraseMacroScopes\n      unless (\u2190 getEnv).contains idNew do\n        throwError \"invalid dotted identifier notation, unknown identifier `{idNew}` from expected type{indentExpr expectedType}\"\n      return idNew\n    catch\n      | ex@(.error ..) =>\n        match (\u2190 unfoldDefinition? resultType) with\n        | some resultType =>\n          go (\u2190 whnfCore resultType) expectedType (previousExceptions.push ex)\n        | none =>\n          previousExceptions.forM fun ex => logException ex\n          throw ex\n      | ex@(.internal _ _) => throw ex\n\nprivate partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)\n    (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do\n  if f.getKind == choiceKind then\n    -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`.\n    withReader (fun ctx => { ctx with errToSorry := false }) do\n      f.getArgs.foldlM (init := acc) fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc\n  else\n    let elabFieldName (e field : Syntax) := do\n      let newLVals := field.identComponents.map fun comp =>\n        -- We use `none` in `suffix?` since `field` can't be part of a composite name\n        LVal.fieldName comp comp.getId.getString! none e\n      elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc\n    let elabFieldIdx (e idxStx : Syntax) := do\n      let some idx := idxStx.isFieldIdx? | throwError \"invalid field index\"\n      elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc\n    match f with\n    | `($(e).$idx:fieldIdx) => elabFieldIdx e idx\n    | `($e |>.$idx:fieldIdx) => elabFieldIdx e idx\n    | `($(e).$field:ident) => elabFieldName e field\n    | `($e |>.$field:ident) => elabFieldName e field\n    | `($_:ident@$_:term) =>\n      throwError \"unexpected occurrence of named pattern\"\n    | `($id:ident) => do\n      elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc\n    | `($id:ident.{$us,*}) => do\n      let us \u2190 elabExplicitUnivs us\n      elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc\n    | `(@$id:ident) =>\n      elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc\n    | `(@$_:ident.{$_us,*}) =>\n      elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc\n    | `(@$_)     => throwUnsupportedSyntax -- invalid occurrence of `@`\n    | `(_)       => throwError \"placeholders '_' cannot be used where a function is expected\"\n    | `(.$id:ident) =>\n        addCompletionInfo <| CompletionInfo.dotId f id.getId (\u2190 getLCtx) expectedType?\n        let fConst \u2190 mkConst (\u2190 resolveDotName id expectedType?)\n        let s \u2190 observing do\n          -- Use (force := true) because we want to record the result of .ident resolution even in patterns\n          let fConst \u2190 addTermInfo f fConst expectedType? (force := true)\n          let e \u2190 elabAppLVals fConst lvals namedArgs args expectedType? explicit ellipsis\n          if overloaded then ensureHasType expectedType? e else return e\n        return acc.push s\n    | _ => do\n      let catchPostpone := !overloaded\n      /- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms.\n        Recall that `observing` does not catch `postponeExceptionId`. -/\n      if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then\n        /- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain\n          arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/\n        let s \u2190 observing do\n          if overloaded then\n            elabTermEnsuringType f expectedType? catchPostpone\n          else\n            elabTerm f expectedType?\n        return acc.push s\n      else\n        let s \u2190 observing do\n          let f \u2190 elabTerm f none catchPostpone\n          let e \u2190 elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis\n          if overloaded then ensureHasType expectedType? e else return e\n        return acc.push s\n\n/-- Return the successful candidates. Recall we have Syntax `choice` nodes and overloaded symbols when we open multiple namespaces. -/\nprivate def getSuccesses (candidates : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do\n  let r\u2081 := candidates.filter fun | EStateM.Result.ok .. => true | _ => false\n  if r\u2081.size \u2264 1 then return r\u2081\n  let r\u2082 \u2190 candidates.filterM fun\n    | .ok e s => do\n      if e.isMVar then\n        /- Make sure `e` is not a delayed coercion.\n           Recall that coercion insertion may be delayed when the type and expected type contains\n           metavariables that block TC resolution.\n           When processing overloaded notation, we disallow delayed coercions at `e`. -/\n        try\n          s.restore\n          synthesizeSyntheticMVars -- Tries to process pending coercions (and elaboration tasks)\n          let e \u2190 instantiateMVars e\n          if e.isMVar then\n          /- If `e` is still a metavariable, and its `SyntheticMVarDecl` is a coercion, we discard this solution -/\n            if let some synDecl \u2190 getSyntheticMVarDecl? e.mvarId! then\n              if synDecl.kind matches SyntheticMVarKind.coe .. then\n                return false\n        catch _ =>\n          -- If `synthesizeSyntheticMVars` failed, we just eliminate the candidate.\n          return false\n      return true\n    | _ => return false\n  if r\u2082.size == 0 then return r\u2081 else return r\u2082\n\n/--\n  Throw an error message that describes why each possible interpretation for the overloaded notation and symbols did not work.\n  We use a nested error message to aggregate the exceptions produced by each failure.\n-/\nprivate def mergeFailures (failures : Array (TermElabResult Expr)) : TermElabM \u03b1 := do\n  let exs := failures.map fun | .error ex _ => ex | _ => unreachable!\n  throwErrorWithNestedErrors \"overloaded\" exs\n\nprivate def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do\n  let candidates \u2190 elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[]\n  if h : candidates.size = 1 then\n    have : 0 < candidates.size := by rw [h]; decide\n    applyResult candidates[0]\n  else\n    let successes \u2190 getSuccesses candidates\n    if h : successes.size = 1 then\n      have : 0 < successes.size := by rw [h]; decide\n      applyResult successes[0]\n    else if successes.size > 1 then\n      let msgs : Array MessageData \u2190 successes.mapM fun success => do\n        match success with\n        | .ok e s => withMCtx s.meta.meta.mctx <| withEnv s.meta.core.env do addMessageContext m!\"{e} : {\u2190 inferType e}\"\n        | _       => unreachable!\n      throwErrorAt f \"ambiguous, possible interpretations {toMessageList msgs}\"\n    else\n      withRef f <| mergeFailures candidates\n\n/--\n  We annotate recursive applications with their `Syntax` node to make sure we can produce error messages with\n  correct position information at `WF` and `Structural`.\n-/\n-- TODO: It is overkill to store the whole `Syntax` object, and we have to make sure we erase it later.\n-- We should store only the position information in the future.\n-- Recall that we will need to have a compact way of storing position information in the future anyway, if we\n-- want to support debugging information\nprivate def annotateIfRec (stx : Syntax) (e : Expr) : TermElabM Expr := do\n  if (\u2190 read).saveRecAppSyntax then\n    let resultFn := e.getAppFn\n    if resultFn.isFVar then\n      let localDecl \u2190 resultFn.fvarId!.getDecl\n      if localDecl.isAuxDecl then\n        return mkRecAppWithSyntax e stx\n  return e\n\n@[builtin_term_elab app] def elabApp : TermElab := fun stx expectedType? =>\n  universeConstraintsCheckpoint do\n    let (f, namedArgs, args, ellipsis) \u2190 expandApp stx\n    annotateIfRec stx (\u2190 elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType?)\n\nprivate def elabAtom : TermElab := fun stx expectedType? => do\n  annotateIfRec stx (\u2190 elabAppAux stx #[] #[] (ellipsis := false) expectedType?)\n\n@[builtin_term_elab ident] def elabIdent : TermElab := elabAtom\n@[builtin_term_elab namedPattern] def elabNamedPattern : TermElab := elabAtom\n@[builtin_term_elab dotIdent] def elabDotIdent : TermElab := elabAtom\n@[builtin_term_elab explicitUniv] def elabExplicitUniv : TermElab := elabAtom\n@[builtin_term_elab pipeProj] def elabPipeProj : TermElab\n  | `($e |>.$f $args*), expectedType? =>\n    universeConstraintsCheckpoint do\n      let (namedArgs, args, ellipsis) \u2190 expandArgs args\n      elabAppAux (\u2190 `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType?\n  | _, _ => throwUnsupportedSyntax\n\n@[builtin_term_elab explicit] def elabExplicit : TermElab := fun stx expectedType? =>\n  match stx with\n  | `(@$_:ident)         => elabAtom stx expectedType?  -- Recall that `elabApp` also has support for `@`\n  | `(@$_:ident.{$_us,*}) => elabAtom stx expectedType?\n  | `(@($t))             => elabTerm t expectedType? (implicitLambda := false)    -- `@` is being used just to disable implicit lambdas\n  | `(@$t)               => elabTerm t expectedType? (implicitLambda := false)   -- `@` is being used just to disable implicit lambdas\n  | _                    => throwUnsupportedSyntax\n\n@[builtin_term_elab choice] def elabChoice : TermElab := elabAtom\n@[builtin_term_elab proj] def elabProj : TermElab := elabAtom\n\nbuiltin_initialize\n  registerTraceClass `Elab.app\n  registerTraceClass `Elab.app.args (inherited := true)\n  registerTraceClass `Elab.app.propagateExpectedType (inherited := true)\n  registerTraceClass `Elab.app.finalize (inherited := true)\n\nend Lean.Elab.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/Lean/Elab/App.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.042087729717900216, "lm_q1q2_score": 0.012519834019293661}}
{"text": "import pseudo_normed_group.CLC\n/-!\n\n# V-hat((M_c)^n)^{T\u207b\u00b9}\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\u207b\u00b9 coincide.\n\n## Main definition\n\nHere `M` is a profinitely filtered pseudo-normed group with `T\u207b\u00b9` scaling things by `r'`,\n`V` is a seminormed group with `T\u207b\u00b9` 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\u207b\u00b9` (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\u2082 {C} [category C] {A\u2081 A\u2082 A\u2083 B\u2081 B\u2082 B\u2083 : C}\n  {f\u2081 : A\u2081 \u27f6 B\u2081} {f\u2082 : A\u2082 \u27f6 B\u2082} {f\u2083 : A\u2083 \u27f6 B\u2083}\n  {a : A\u2081 \u27f6 A\u2082} {a' : A\u2082 \u27f6 A\u2083} {b : B\u2081 \u27f6 B\u2082} {b' : B\u2082 \u27f6 B\u2083}\n  (h\u2081 : a \u226b f\u2082 = f\u2081 \u226b b) (h\u2082 : a' \u226b f\u2083 = f\u2082 \u226b b') : (a \u226b a') \u226b f\u2083 = f\u2081 \u226b b \u226b b' :=\nby rw [category.assoc, h\u2082, \u2190 category.assoc, h\u2081, \u2190 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 \u27f6 W) := of (f.equalizer g)\n\nnamespace equalizer\n\ndef \u03b9 {V W : SemiNormedGroup} (f g : V \u27f6 W) :\n  equalizer f g \u27f6 V :=\nnormed_add_group_hom.equalizer.\u03b9 _ _\n\n@[reassoc] lemma condition {V W : SemiNormedGroup} (f g : V \u27f6 W) :\n  \u03b9 f g \u226b f = \u03b9 f g \u226b g :=\nnormed_add_group_hom.equalizer.comp_\u03b9_eq _ _\n\nlemma \u03b9_range {V W : SemiNormedGroup} (f g : V \u27f6 W) :\n  (\u03b9 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 \u27e8x, rfl\u27e9, rw [normed_add_group_hom.sub_apply], exact x.2 },\n  { intro h, refine \u27e8\u27e8x, h\u27e9, rfl\u27e9, }\nend\n\nlemma \u03b9_range' {V W : SemiNormedGroup} (f g : V \u27f6 W) :\n  (\u03b9 f g).range = (g - f).ker :=\nbegin\n  rw \u03b9_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\u2081 V\u2082 W\u2081 W\u2082 : SemiNormedGroup} {f\u2081 f\u2082 g\u2081 g\u2082} (\u03c6 : V\u2081 \u27f6 V\u2082) (\u03c8 : W\u2081 \u27f6 W\u2082)\n  (hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8) (hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  equalizer f\u2081 g\u2081 \u27f6 equalizer f\u2082 g\u2082 :=\nnormed_add_group_hom.equalizer.map _ _ hf.symm hg.symm\n\nlemma map_comp_\u03b9 {V\u2081 V\u2082 W\u2081 W\u2082 : SemiNormedGroup} {f\u2081 f\u2082 g\u2081 g\u2082} (\u03c6 : V\u2081 \u27f6 V\u2082) (\u03c8 : W\u2081 \u27f6 W\u2082)\n  (hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8) (hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  map \u03c6 \u03c8 hf hg \u226b \u03b9 _ _ = \u03b9 _ _ \u226b \u03c6 :=\nrfl\n\ntheorem map_congr\n  {V\u2081 V\u2082 W\u2081 W\u2082 : SemiNormedGroup} {f\u2081 f\u2082 g\u2081 g\u2082} {\u03c6 : V\u2081 \u27f6 V\u2082} {\u03c8 : W\u2081 \u27f6 W\u2082}\n  {V\u2081' V\u2082' W\u2081' W\u2082' : SemiNormedGroup} {f\u2081' f\u2082' g\u2081' g\u2082'} {\u03c6' : V\u2081' \u27f6 V\u2082'} {\u03c8' : W\u2081' \u27f6 W\u2082'}\n  {hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8} {hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8}\n  {hf' : \u03c6' \u226b f\u2082' = f\u2081' \u226b \u03c8'} {hg' : \u03c6' \u226b g\u2082' = g\u2081' \u226b \u03c8'}\n  (H\u03c6 : arrow.mk \u03c6 = arrow.mk \u03c6') (H\u03c8 : arrow.mk \u03c8 = arrow.mk \u03c8')\n  (Hf\u2081 : arrow.mk f\u2081 = arrow.mk f\u2081') (Hf\u2082 : arrow.mk f\u2082 = arrow.mk f\u2082')\n  (Hg\u2081 : arrow.mk g\u2081 = arrow.mk g\u2081') (Hg\u2082 : arrow.mk g\u2082 = arrow.mk g\u2082') :\n  arrow.mk (map \u03c6 \u03c8 hf hg) = arrow.mk (map \u03c6' \u03c8' hf' hg') :=\nby { cases H\u03c6, cases H\u03c8, cases Hf\u2081, cases Hf\u2082, cases Hg\u2081, cases Hg\u2082, refl }\n\nlemma map_comp_map {V\u2081 V\u2082 V\u2083 W\u2081 W\u2082 W\u2083 : SemiNormedGroup} {f\u2081 f\u2082 f\u2083 g\u2081 g\u2082 g\u2083}\n  {\u03c6 : V\u2081 \u27f6 V\u2082} {\u03c8 : W\u2081 \u27f6 W\u2082} {\u03c6' : V\u2082 \u27f6 V\u2083} {\u03c8' : W\u2082 \u27f6 W\u2083}\n  (hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8) (hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8)\n  (hf' : \u03c6' \u226b f\u2083 = f\u2082 \u226b \u03c8') (hg' : \u03c6' \u226b g\u2083 = g\u2082 \u226b \u03c8') :\n  map \u03c6 \u03c8 hf hg \u226b map \u03c6' \u03c8' hf' hg' =\n  map (\u03c6 \u226b \u03c6') (\u03c8 \u226b \u03c8') (comm_sq\u2082 hf hf') (comm_sq\u2082 hg hg') :=\nby { ext, refl }\n\nlemma map_id {J} [category J] {V W : SemiNormedGroup} (f g : V \u27f6 W) :\n  map (\ud835\udfd9 V) (\ud835\udfd9 W) (show \ud835\udfd9 V \u226b f = f \u226b \ud835\udfd9 W, by simp) (show \ud835\udfd9 V \u226b g = g \u226b \ud835\udfd9 W, by simp) = \ud835\udfd9 _ :=\nby { ext, refl }\n\nlemma norm_map_le {V\u2081 V\u2082 W\u2081 W\u2082 : SemiNormedGroup} {f\u2081 f\u2082 g\u2081 g\u2082} {\u03c6 : V\u2081 \u27f6 V\u2082} {\u03c8 : W\u2081 \u27f6 W\u2082}\n  (hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8) (hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8) (C : \u211d) (h\u03c6 : \u2225\u03b9 f\u2081 g\u2081 \u226b \u03c6\u2225 \u2264 C) :\n  \u2225map \u03c6 \u03c8 hf hg\u2225 \u2264 C :=\nnormed_add_group_hom.equalizer.norm_map_le _ _ C h\u03c6\n\n@[simps obj map]\nprotected def F {J} [category J] {V W : J \u2964 SemiNormedGroup} (f g : V \u27f6 W) : J \u2964 SemiNormedGroup :=\n{ obj := \u03bb X, of ((f.app X).equalizer (g.app X)),\n  map := \u03bb X Y \u03c6, equalizer.map (V.map \u03c6) (W.map \u03c6) (f.naturality _) (g.naturality _),\n  map_id' := \u03bb X, by simp only [category_theory.functor.map_id]; exact normed_add_group_hom.equalizer.map_id,\n  map_comp' := \u03bb X Y Z \u03c6 \u03c8, 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\u2081 V\u2082 W\u2081 W\u2082 : J \u2964 SemiNormedGroup}\n  {f\u2081 f\u2082 g\u2081 g\u2082} (\u03c6 : V\u2081 \u27f6 V\u2082) (\u03c8 : W\u2081 \u27f6 W\u2082)\n  (hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8) (hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  equalizer.F f\u2081 g\u2081 \u27f6 equalizer.F f\u2082 g\u2082 :=\n{ app := \u03bb X, equalizer.map (\u03c6.app X) (\u03c8.app X)\n    (by rw [\u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app, hf])\n    (by rw [\u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app, hg]),\n  naturality' := \u03bb X Y \u03b1, by simp only [equalizer.F_map, map_comp_map, nat_trans.naturality] }\n\nlemma map_nat_comp_map_nat {J} [category J] {V\u2081 V\u2082 V\u2083 W\u2081 W\u2082 W\u2083 : J \u2964 SemiNormedGroup}\n  {f\u2081 f\u2082 f\u2083 g\u2081 g\u2082 g\u2083} {\u03c6 : V\u2081 \u27f6 V\u2082} {\u03c8 : W\u2081 \u27f6 W\u2082} {\u03c6' : V\u2082 \u27f6 V\u2083} {\u03c8' : W\u2082 \u27f6 W\u2083}\n  (hf : \u03c6 \u226b f\u2082 = f\u2081 \u226b \u03c8) (hg : \u03c6 \u226b g\u2082 = g\u2081 \u226b \u03c8)\n  (hf' : \u03c6' \u226b f\u2083 = f\u2082 \u226b \u03c8') (hg' : \u03c6' \u226b g\u2083 = g\u2082 \u226b \u03c8') :\n  map_nat \u03c6 \u03c8 hf hg \u226b map_nat \u03c6' \u03c8' hf' hg' =\n  map_nat (\u03c6 \u226b \u03c6') (\u03c8 \u226b \u03c8') (comm_sq\u2082 hf hf') (comm_sq\u2082 hg hg') :=\nby { ext, refl }\n\nlemma map_nat_id {J} [category J] {V W : J \u2964 SemiNormedGroup} (f g : V \u27f6 W) :\n  map_nat (\ud835\udfd9 V) (\ud835\udfd9 W) (show \ud835\udfd9 V \u226b f = f \u226b \ud835\udfd9 W, by simp) (show \ud835\udfd9 V \u226b g = g \u226b \ud835\udfd9 W, by simp) = \ud835\udfd9 _ :=\nby { ext, refl }\n\nend equalizer\nend SemiNormedGroup\n\nuniverse variable u\nvariables (r : \u211d\u22650) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)]\nvariables (r' : \u211d\u22650) [fact (0 < r')] [fact (r' \u2264 1)]\nvariables (M M\u2081 M\u2082 M\u2083 : ProFiltPseuNormGrpWithTinv.{u} r')\nvariables (c c\u2081 c\u2082 c\u2083 c\u2084 c\u2085 c\u2086 c\u2087 c\u2088 : \u211d\u22650) (l m n : \u2115)\nvariables (f : M\u2081 \u27f6 M\u2082) (g : M\u2082 \u27f6 M\u2083)\n\ndef CLCTinv (r : \u211d\u22650) (V : SemiNormedGroup)\n  [normed_with_aut r V] [fact (0 < r)] {A B : Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  SemiNormedGroup :=\nSemiNormedGroup.of $ normed_add_group_hom.equalizer\n  ((CLC V).map f)\n  ((CLC V).map g \u226b (CLC.T_inv r V).app B)\n\nnamespace CLCTinv\n\ndef \u03b9 (r : \u211d\u22650) (V : SemiNormedGroup)\n  [normed_with_aut r V] [fact (0 < r)] {A B : Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  CLCTinv r V f g \u27f6 (CLC V).obj A :=\nSemiNormedGroup.equalizer.\u03b9 _ _\n\nlemma \u03b9_range (r : \u211d\u22650) (V : SemiNormedGroup)\n  [normed_with_aut r V] [fact (0 < r)] {A B : Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  (\u03b9 r V f g).range =\n    normed_add_group_hom.ker ((CLC V).map f - ((CLC V).map g \u226b (CLC.T_inv r V).app B)) :=\nSemiNormedGroup.equalizer.\u03b9_range _ _\n\nlemma \u03b9_range' (r : \u211d\u22650) (V : SemiNormedGroup)\n  [normed_with_aut r V] [fact (0 < r)] {A B : Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  (\u03b9 r V f g).range =\n    normed_add_group_hom.ker (((CLC V).map g \u226b (CLC.T_inv r V).app B) - (CLC V).map f) :=\nSemiNormedGroup.equalizer.\u03b9_range' _ _\n\ndef map {A\u2081 B\u2081 A\u2082 B\u2082 : Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u27f6 A\u2082) (\u03c8 : B\u2081 \u27f6 B\u2082) (h\u2081 : \u03d5 \u226b f\u2082 = f\u2081 \u226b \u03c8) (h\u2082 : \u03d5 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  CLCTinv r V f\u2081 g\u2081 \u27f6 CLCTinv r V f\u2082 g\u2082 :=\nSemiNormedGroup.equalizer.map ((CLC V).map \u03d5) ((CLC V).map \u03c8)\n  (by rw [\u2190 functor.map_comp, \u2190 functor.map_comp, h\u2081]) $\nby rw [\u2190 category.assoc, \u2190 functor.map_comp, h\u2082, functor.map_comp,\n  category.assoc, (CLC.T_inv _ _).naturality, category.assoc]\n\nlemma map_comp_\u03b9 {A\u2081 B\u2081 A\u2082 B\u2082 : Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u27f6 A\u2082) (\u03c8 : B\u2081 \u27f6 B\u2082) (h\u2081 : \u03d5 \u226b f\u2082 = f\u2081 \u226b \u03c8) (h\u2082 : \u03d5 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  map r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5 \u03c8 h\u2081 h\u2082 \u226b \u03b9 r V _ _ = \u03b9 _ _ _ _ \u226b (CLC V).map \u03d5 :=\nnormed_add_group_hom.equalizer.\u03b9_comp_map _ _\n\nlemma map_norm_noninc {A\u2081 B\u2081 A\u2082 B\u2082 : Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u27f6 A\u2082) (\u03c8 : B\u2081 \u27f6 B\u2082) (h\u2081 h\u2082) :\n  (CLCTinv.map r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5 \u03c8 h\u2081 h\u2082).norm_noninc :=\nequalizer.map_norm_noninc _ _ $ CLC.map_norm_noninc _ _\n\nlemma norm_map_le {A\u2081 B\u2081 A\u2082 B\u2082 : Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u27f6 A\u2082) (\u03c8 : B\u2081 \u27f6 B\u2082) (h\u2081 h\u2082) (C : \u211d\u22650)\n  (H : \u2225SemiNormedGroup.equalizer.\u03b9\n         ((CLC V).map f\u2081)\n         ((CLC V).map g\u2081 \u226b (CLC.T_inv r V).app B\u2081) \u226b\n       (CLC V).map \u03d5\u2225 \u2264 C) :\n  \u2225CLCTinv.map r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5 \u03c8 h\u2081 h\u2082\u2225 \u2264 C :=\nSemiNormedGroup.equalizer.norm_map_le _ _ C H\n\n@[simp] lemma map_id {A B : Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  map r V f g f g (\ud835\udfd9 A) (\ud835\udfd9 B) rfl rfl = \ud835\udfd9 _ :=\nbegin\n  simp only [map, SemiNormedGroup.equalizer.map, category_theory.functor.map_id],\n  exact equalizer.map_id,\nend\n\nlemma map_comp {A\u2081 A\u2082 A\u2083 B\u2081 B\u2082 B\u2083 : Profinite\u1d52\u1d56}\n  {f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081} {f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082} {f\u2083 g\u2083 : A\u2083 \u27f6 B\u2083}\n  (\u03d5\u2081 : A\u2081 \u27f6 A\u2082) (\u03d5\u2082 : A\u2082 \u27f6 A\u2083) (\u03c8\u2081 : B\u2081 \u27f6 B\u2082) (\u03c8\u2082 : B\u2082 \u27f6 B\u2083)\n  (h1 h2 h3 h4 h5 h6) :\n  CLCTinv.map r V f\u2081 g\u2081 f\u2083 g\u2083 (\u03d5\u2081 \u226b \u03d5\u2082) (\u03c8\u2081 \u226b \u03c8\u2082) h1 h2 =\n  CLCTinv.map r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5\u2081 \u03c8\u2081 h3 h4 \u226b\n  CLCTinv.map r V f\u2082 g\u2082 f\u2083 g\u2083 \u03d5\u2082 \u03c8\u2082 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\u2081 A\u2082 A\u2083 B\u2081 B\u2082 B\u2083 : Profinite\u1d52\u1d56}\n  {f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081} {f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082} {f\u2083 g\u2083 : A\u2083 \u27f6 B\u2083}\n  (\u03d5\u2081 : A\u2081 \u27f6 A\u2082) (\u03d5\u2082 : A\u2082 \u27f6 A\u2083) (\u03c8\u2081 : B\u2081 \u27f6 B\u2082) (\u03c8\u2082 : B\u2082 \u27f6 B\u2083)\n  (h\u2081 h\u2082 h\u2083 h\u2084) :\n  CLCTinv.map r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5\u2081 \u03c8\u2081 h\u2081 h\u2082 \u226b\n  CLCTinv.map r V f\u2082 g\u2082 f\u2083 g\u2083 \u03d5\u2082 \u03c8\u2082 h\u2083 h\u2084 =\n  CLCTinv.map r V f\u2081 g\u2081 f\u2083 g\u2083 (\u03d5\u2081 \u226b \u03d5\u2082) (\u03c8\u2081 \u226b \u03c8\u2082) (comm_sq\u2082 h\u2081 h\u2083) (comm_sq\u2082 h\u2082 h\u2084) :=\n(map_comp _ _ _ _ _ _ _ _ _ _ _ _).symm\n\n@[simps]\ndef map_iso {A\u2081 B\u2081 A\u2082 B\u2082 : Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u2245 A\u2082) (\u03c8 : B\u2081 \u2245 B\u2082) (h\u2081 : \u03d5.hom \u226b f\u2082 = f\u2081 \u226b \u03c8.hom) (h\u2082 : \u03d5.hom \u226b g\u2082 = g\u2081 \u226b \u03c8.hom) :\n  CLCTinv r V f\u2081 g\u2081 \u2245 CLCTinv r V f\u2082 g\u2082 :=\n{ hom := map r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5.hom \u03c8.hom h\u2081 h\u2082,\n  inv := map r V f\u2082 g\u2082 f\u2081 g\u2081 \u03d5.inv \u03c8.inv\n    (by rw [iso.inv_comp_eq, \u2190 category.assoc, iso.eq_comp_inv, h\u2081])\n    (by rw [iso.inv_comp_eq, \u2190 category.assoc, iso.eq_comp_inv, h\u2082]),\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\u2081 B\u2081 A\u2082 B\u2082 : Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u2245 A\u2082) (\u03c8 : B\u2081 \u2245 B\u2082) (h\u2081 : \u03d5.hom \u226b f\u2082 = f\u2081 \u226b \u03c8.hom) (h\u2082 : \u03d5.hom \u226b g\u2082 = g\u2081 \u226b \u03c8.hom) :\n  isometry (map_iso r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5 \u03c8 h\u2081 h\u2082).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 : \u211d\u22650) (V : SemiNormedGroup)\n  [normed_with_aut r V] [fact (0 < r)] {A B : J \u2964 Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  J \u2964 SemiNormedGroup :=\n{ obj := \u03bb X, CLCTinv r V (f.app X) (g.app X),\n  map := \u03bb X Y \u03c6, map _ _ _ _ _ _ (A.map \u03c6) (B.map \u03c6) (f.naturality _) (g.naturality _),\n  map_id' := \u03bb X, by simp only [category_theory.functor.map_id]; apply map_id,\n  map_comp' := \u03bb X Y Z \u03c6 \u03c8, by simp only [functor.map_comp]; apply map_comp }\n\ntheorem F_def {J} [category J] (r : \u211d\u22650) (V : SemiNormedGroup)\n  [normed_with_aut r V] [fact (0 < r)] {A B : J \u2964 Profinite\u1d52\u1d56} (f g : A \u27f6 B) :\n  CLCTinv.F r V f g = SemiNormedGroup.equalizer.F\n    (whisker_right f (CLC V))\n    (whisker_right g (CLC V) \u226b whisker_left B (CLC.T_inv r V)) := rfl\n\n@[simps]\ndef map_nat {J} [category J] {A\u2081 B\u2081 A\u2082 B\u2082 : J \u2964 Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u27f6 A\u2082) (\u03c8 : B\u2081 \u27f6 B\u2082) (h\u2081 : \u03d5 \u226b f\u2082 = f\u2081 \u226b \u03c8) (h\u2082 : \u03d5 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  CLCTinv.F r V f\u2081 g\u2081 \u27f6 CLCTinv.F r V f\u2082 g\u2082 :=\n{ app := \u03bb X, map _ _ _ _ _ _ (\u03d5.app X) (\u03c8.app X)\n    (by rw [\u2190 nat_trans.comp_app, h\u2081, nat_trans.comp_app])\n    (by rw [\u2190 nat_trans.comp_app, h\u2082, nat_trans.comp_app]),\n  naturality' := \u03bb X Y \u03b1, by simp only [CLCTinv.F_map, map_comp_map, \u03d5.naturality, \u03c8.naturality] }\n\ntheorem map_nat_def {J} [category J] {A\u2081 B\u2081 A\u2082 B\u2082 : J \u2964 Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u27f6 A\u2082) (\u03c8 : B\u2081 \u27f6 B\u2082) (h\u2081 : \u03d5 \u226b f\u2082 = f\u2081 \u226b \u03c8) (h\u2082 : \u03d5 \u226b g\u2082 = g\u2081 \u226b \u03c8) :\n  map_nat r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5 \u03c8 h\u2081 h\u2082 = begin\n    dsimp only [F_def],\n    refine SemiNormedGroup.equalizer.map_nat\n      (whisker_right \u03d5 (CLC V))\n      (whisker_right \u03c8 (CLC V))\n      (by rw [\u2190 whisker_right_comp, \u2190 whisker_right_comp, h\u2081])\n      (comm_sq\u2082 _ _).symm,\n    { exact whisker_right \u03c8 _ },\n    { rw [\u2190 whisker_right_comp, \u2190 whisker_right_comp, h\u2082] },\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\u2081 B\u2081 A\u2082 B\u2082 : J \u2964 Profinite\u1d52\u1d56} (f\u2081 g\u2081 : A\u2081 \u27f6 B\u2081) (f\u2082 g\u2082 : A\u2082 \u27f6 B\u2082)\n  (\u03d5 : A\u2081 \u2245 A\u2082) (\u03c8 : B\u2081 \u2245 B\u2082) (h\u2081 : \u03d5.hom \u226b f\u2082 = f\u2081 \u226b \u03c8.hom) (h\u2082 : \u03d5.hom \u226b g\u2082 = g\u2081 \u226b \u03c8.hom) :\n  CLCTinv.F r V f\u2081 g\u2081 \u2245 CLCTinv.F r V f\u2082 g\u2082 :=\n{ hom := map_nat r V f\u2081 g\u2081 f\u2082 g\u2082 \u03d5.hom \u03c8.hom h\u2081 h\u2082,\n  inv := map_nat r V f\u2082 g\u2082 f\u2081 g\u2081 \u03d5.inv \u03c8.inv\n    (by rw [iso.inv_comp_eq, \u2190 category.assoc, iso.eq_comp_inv, h\u2081])\n    (by rw [iso.inv_comp_eq, \u2190 category.assoc, iso.eq_comp_inv, h\u2082]),\n  hom_inv_id' :=\n  begin\n    simp only [map_nat_def, _root_.id, SemiNormedGroup.equalizer.map_nat_comp_map_nat,\n      \u2190 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      \u2190 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\u2082 : \u211d\u22650) [r1 : fact (r' \u2264 1)] [h : fact (c\u2082 \u2264 r' * c)] : fact (c\u2082 \u2264 c) :=\n\u27e8h.1.trans $ (mul_le_mul' r1.1 le_rfl).trans (by simp)\u27e9\n\n@[simps obj]\ndef CLCFPTinv\u2082 (r : \u211d\u22650) (V : SemiNormedGroup)\n  (r' : \u211d\u22650) [fact (0 < r)] [fact (0 < r')] [r1 : fact (r' \u2264 1)] [normed_with_aut r V]\n  (c c\u2082 : \u211d\u22650) [fact (c\u2082 \u2264 r' * c)] (n : \u2115) : (ProFiltPseuNormGrpWithTinv r')\u1d52\u1d56 \u2964 SemiNormedGroup :=\nby haveI : fact (c\u2082 \u2264 c) := aux r' c c\u2082; exact\nCLCTinv.F r V\n  (nat_trans.op (FiltrationPow.Tinv r' c\u2082 c n))\n  (nat_trans.op (FiltrationPow.cast_le r' c\u2082 c n))\n\ntheorem CLCFPTinv\u2082_def (r : \u211d\u22650) (V : SemiNormedGroup)\n  (r' : \u211d\u22650) [fact (0 < r)] [fact (0 < r')] [r1 : fact (r' \u2264 1)] [normed_with_aut r V]\n  (c c\u2082 : \u211d\u22650) [fact (c\u2082 \u2264 r' * c)] (n : \u2115) :\n  CLCFPTinv\u2082 r V r' c c\u2082 n = SemiNormedGroup.equalizer.F\n    (CLCFP.Tinv V r' c c\u2082 n)\n    (@CLCFP.res V r' c c\u2082 n (aux r' c c\u2082) \u226b CLCFP.T_inv r V r' c\u2082 n) := rfl\n\ninstance CLCFPTinv\u2082.separated_space [fact (c\u2082 \u2264 r' * c\u2081)] (M) :\n  separated_space ((CLCFPTinv\u2082 r V r' c\u2081 c\u2082 n).obj M) :=\nbegin\n  rw separated_iff_t2,\n  refine @subtype.t2_space _ _ (id _) (id _),\n  rw \u2190 separated_iff_t2,\n  apply uniform_space.completion.separated_space\nend\n\ninstance CLCFPTinv\u2082.complete_space [fact (c\u2082 \u2264 r' * c\u2081)] (M) :\n  complete_space ((CLCFPTinv\u2082 r V r' c\u2081 c\u2082 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\u207b\u00b9}`,\ndefined by taking `T\u207b\u00b9`-invariants for two different actions by `T\u207b\u00b9`:\n\n* The first comes from the action of `T\u207b\u00b9` on `M`.\n* The second comes from the action of `T\u207b\u00b9` 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 : \u211d\u22650) (V : SemiNormedGroup) (r' : \u211d\u22650)\n  (c : \u211d\u22650) (n : \u2115) [normed_with_aut r V] [fact (0 < r)] [fact (0 < r')] [fact (r' \u2264 1)] :\n  (ProFiltPseuNormGrpWithTinv r')\u1d52\u1d56 \u2964 SemiNormedGroup :=\nCLCFPTinv\u2082 r V r' c (r' * c) n\n\nnamespace CLCFPTinv\u2082\n\nlemma map_norm_noninc [fact (c\u2082 \u2264 r' * c)] [fact (c\u2082 \u2264 c)]\n  {M\u2081 M\u2082} (f : M\u2081 \u27f6 M\u2082) : ((CLCFPTinv\u2082 r V r' c c\u2082 n).map f).norm_noninc :=\nCLCTinv.map_norm_noninc _ _ _ _ _ _ _ _ _ _\n\ndef res [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)] [fact (c\u2084 \u2264 c\u2083)]\n  [fact (c\u2083 \u2264 c\u2081)] [fact (c\u2084 \u2264 c\u2082)] : CLCFPTinv\u2082 r V r' c\u2081 c\u2082 n \u27f6 CLCFPTinv\u2082 r V r' c\u2083 c\u2084 n :=\nCLCTinv.map_nat r V _ _ _ _\n  (nat_trans.op (FiltrationPow.cast_le _ c\u2083 c\u2081 n))\n  (nat_trans.op (FiltrationPow.cast_le _ c\u2084 c\u2082 n)) rfl rfl\n\n@[simp] lemma res_refl [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2082 \u2264 c\u2081)] : res r V r' c\u2081 c\u2082 c\u2081 c\u2082 n = \ud835\udfd9 _ :=\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\u2082 \u2264 r' * c\u2081)] [fact (c\u2082 \u2264 c\u2081)]\n  [fact (c\u2084 \u2264 r' * c\u2083)] [fact (c\u2084 \u2264 c\u2083)]\n  [fact (c\u2086 \u2264 r' * c\u2085)] [fact (c\u2086 \u2264 c\u2085)]\n  [fact (c\u2083 \u2264 c\u2081)] [fact (c\u2084 \u2264 c\u2082)]\n  [fact (c\u2085 \u2264 c\u2083)] [fact (c\u2086 \u2264 c\u2084)]\n  [fact (c\u2085 \u2264 c\u2081)] [fact (c\u2086 \u2264 c\u2082)] :\n  res r V r' c\u2081 c\u2082 c\u2083 c\u2084 n \u226b res r V r' c\u2083 c\u2084 c\u2085 c\u2086 n = res r V r' c\u2081 c\u2082 c\u2085 c\u2086 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\u2082 \u2264 r' * c\u2081)} {_ : fact (c\u2082 \u2264 c\u2081)}\n  {_ : fact (c\u2084 \u2264 r' * c\u2083)} {_ : fact (c\u2084 \u2264 c\u2083)} {_ : fact (c\u2083 \u2264 c\u2081)} {_ : fact (c\u2084 \u2264 c\u2082)} (M) :\n  ((res r V r' c\u2081 c\u2082 c\u2083 c\u2084 n).app M).norm_noninc :=\nCLCTinv.map_norm_noninc _ _ _ _ _ _ _ _ _ _\n\nlemma norm_res_le [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)] [fact (c\u2084 \u2264 c\u2083)]\n  [fact (c\u2083 \u2264 c\u2081)] [fact (c\u2084 \u2264 c\u2082)] (h\u2082\u2083 : c\u2082 = c\u2083) (M) :\n  \u2225(res r V r' c\u2081 c\u2082 c\u2083 c\u2084 n).app M\u2225 \u2264 r :=\nbegin\n  apply CLCTinv.norm_map_le,\n  rw [\u2190 category.comp_id ((CLC V).map ((nat_trans.op (FiltrationPow.cast_le r' c\u2083 c\u2081 n)).app M))],\n  have := nat_trans.congr_app (CLC.T r V).inv_hom_id ((FiltrationPow r' c\u2083 n).op.obj M),\n  dsimp only [nat_trans.id_app] at this,\n  rw [\u2190 this, CLC.T_inv_eq, nat_trans.comp_app, \u2190 category.assoc ((CLC V).map _)],\n  unfreezingI { subst c\u2083 },\n  rw [\u2190 SemiNormedGroup.equalizer.condition_assoc, \u2190 category.assoc],\n  refine normed_add_group_hom.norm_comp_le_of_le' 1 r r (mul_one \u2191r).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.\u03b9_norm_noninc }\nend\n\nend CLCFPTinv\u2082\n\nnamespace CLCFPTinv\n\nlemma map_norm_noninc {M\u2081 M\u2082} (f : M\u2081 \u27f6 M\u2082) : ((CLCFPTinv r V r' c n).map f).norm_noninc :=\nCLCFPTinv\u2082.map_norm_noninc _ _ _ _ _ _ _\n\ndef res [fact (c\u2082 \u2264 c\u2081)] : CLCFPTinv r V r' c\u2081 n \u27f6 CLCFPTinv r V r' c\u2082 n :=\nCLCFPTinv\u2082.res r V r' c\u2081 _ c\u2082 _ n\n\n@[simp] lemma res_refl : res r V r' c\u2081 c\u2081 n = \ud835\udfd9 _ :=\nCLCFPTinv\u2082.res_refl _ _ _ _ _ _\n\nlemma res_comp_res [fact (c\u2083 \u2264 c\u2081)] [fact (c\u2085 \u2264 c\u2083)] [fact (c\u2085 \u2264 c\u2081)] :\n  res r V r' c\u2081 c\u2083 n \u226b res r V r' c\u2083 c\u2085 n = res r V r' c\u2081 c\u2085 n :=\nCLCFPTinv\u2082.res_comp_res _ _ _ _ _ _ _ _ _ _\n\nlemma res_norm_noninc {_ : fact (c\u2082 \u2264 c\u2081)} (M) :\n  ((res r V r' c\u2081 c\u2082 n).app M).norm_noninc :=\nCLCFPTinv\u2082.res_norm_noninc r V r' _ _ _ _ _ _\n\nlemma norm_res_le [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2082 \u2264 r' * c\u2081)] (M) :\n  \u2225(res r V r' c\u2081 c\u2082 n).app M\u2225 \u2264 r :=\nbegin\n  rw \u2190 res_comp_res r V r' c\u2081 (r' * c\u2081) c\u2082,\n  refine norm_comp_le_of_le' _ _ _ (one_mul \u2191r).symm _ (CLCFPTinv\u2082.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 : \u2115) [fact (c\u2082 \u2264 c\u2081)] [h : fact (c\u2082 \u2264 r' ^ N * c\u2081)] (M) :\n  \u2225(res r V r' c\u2081 c\u2082 n).app M\u2225 \u2264 (r ^ N) :=\nbegin\n  unfreezingI { induction N with N ih generalizing c\u2081 c\u2082 },\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\u2082 \u2264 r' ^ N * c\u2081) := nnreal.fact_le_pow_mul_of_le_pow_succ_mul _ _ _,\n  rw [pow_succ, mul_assoc] at h, resetI,\n  rw [\u2190 res_comp_res r V r' c\u2081 (r' ^ N * c\u2081) c\u2082],\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 (\u03d5 \u03c8 : universal_map m n)\n\ndef eval_CLCFPTinv\u2082\n  [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [\u03d5.suitable c\u2083 c\u2081] [\u03d5.suitable c\u2084 c\u2082] :\n  CLCFPTinv\u2082 r V r' c\u2081 c\u2082 n \u27f6 CLCFPTinv\u2082 r V r' c\u2083 c\u2084 m :=\nbegin\n  dsimp only [CLCFPTinv\u2082_def],\n  refine SemiNormedGroup.equalizer.map_nat (\u03d5.eval_CLCFP _ _ _ _) (\u03d5.eval_CLCFP _ _ _ _)\n    (Tinv_comp_eval_CLCFP V r' c\u2081 c\u2082 c\u2083 c\u2084 \u03d5).symm _,\n  haveI : fact (c\u2082 \u2264 c\u2081) := aux r' _ _, haveI : fact (c\u2084 \u2264 c\u2083) := aux r' _ _,\n  have h\u2081 := res_comp_eval_CLCFP V r' c\u2081 c\u2082 c\u2083 c\u2084 \u03d5,\n  have h\u2082 := T_inv_comp_eval_CLCFP r V r' c\u2082 c\u2084 \u03d5,\n  have := comm_sq\u2082 h\u2081 h\u2082,\n  exact this.symm\nend\n\n@[simp] lemma eval_CLCFPTinv\u2082_zero\n  [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)] :\n  (0 : universal_map m n).eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 = 0 :=\nby { simp only [eval_CLCFPTinv\u2082, eval_CLCFP_zero], ext, refl }\n\n@[simp] lemma eval_CLCFPTinv\u2082_add\n  [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [\u03d5.suitable c\u2083 c\u2081] [\u03d5.suitable c\u2084 c\u2082]\n  [\u03c8.suitable c\u2083 c\u2081] [\u03c8.suitable c\u2084 c\u2082] :\n  (\u03d5 + \u03c8 : universal_map m n).eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 =\n  \u03d5.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 + \u03c8.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 :=\nby { simp only [eval_CLCFPTinv\u2082, eval_CLCFP_add], ext, refl }\n\n@[simp] lemma eval_CLCFPTinv\u2082_sub\n  [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [\u03d5.suitable c\u2083 c\u2081] [\u03d5.suitable c\u2084 c\u2082]\n  [\u03c8.suitable c\u2083 c\u2081] [\u03c8.suitable c\u2084 c\u2082] :\n  (\u03d5 - \u03c8 : universal_map m n).eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 =\n  \u03d5.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 - \u03c8.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 :=\nby { simp only [eval_CLCFPTinv\u2082, eval_CLCFP_sub], ext, refl }\n\nlemma eval_CLCFPTinv\u2082_comp {l m n : FreeMat} (f : l \u27f6 m) (g : m \u27f6 n)\n  [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)] [fact (c\u2086 \u2264 r' * c\u2085)]\n  [f.suitable c\u2085 c\u2083] [f.suitable c\u2086 c\u2084] [g.suitable c\u2083 c\u2081] [g.suitable c\u2084 c\u2082] :\n  @eval_CLCFPTinv\u2082 r V _ _ r' _ _ c\u2081 c\u2082 c\u2085 c\u2086 _ _ (f \u226b g)\n    _ _ (suitable.comp c\u2083) (suitable.comp c\u2084) =\n  g.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084 \u226b f.eval_CLCFPTinv\u2082 r V r' c\u2083 c\u2084 c\u2085 c\u2086 :=\nbegin\n  dsimp only [eval_CLCFPTinv\u2082, CLCFPTinv\u2082_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\u2081 c\u2085 (f \u226b g) = eval_CLCFP V r' c\u2081 c\u2083 g \u226b eval_CLCFP V r' c\u2083 c\u2085 f :=\n    eval_CLCFP_comp V r' c\u2081 c\u2083 c\u2085 g f,\n  have H2 : eval_CLCFP V r' c\u2082 c\u2086 (f \u226b g) = eval_CLCFP V r' c\u2082 c\u2084 g \u226b eval_CLCFP V r' c\u2084 c\u2086 f :=\n    eval_CLCFP_comp V r' c\u2082 c\u2084 c\u2086 g f,\n  rw [H1, H2],\n  intros, refl,\nend\n\nlemma res_comp_eval_CLCFPTinv\u2082\n  [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [fact (c\u2086 \u2264 r' * c\u2085)] [fact (c\u2088 \u2264 r' * c\u2087)]\n  [fact (c\u2082 \u2264 c\u2081)] [fact (c\u2083 \u2264 c\u2081)] [fact (c\u2084 \u2264 c\u2082)] [fact (c\u2084 \u2264 c\u2083)]\n  [fact (c\u2086 \u2264 c\u2085)] [fact (c\u2087 \u2264 c\u2085)] [fact (c\u2088 \u2264 c\u2086)] [fact (c\u2088 \u2264 c\u2087)]\n  [\u03d5.suitable c\u2085 c\u2081] [\u03d5.suitable c\u2086 c\u2082]\n  [\u03d5.suitable c\u2087 c\u2083] [\u03d5.suitable c\u2088 c\u2084] :\n  CLCFPTinv\u2082.res r V r' c\u2081 c\u2082 c\u2083 c\u2084 n \u226b \u03d5.eval_CLCFPTinv\u2082 r V r' c\u2083 c\u2084 c\u2087 c\u2088 =\n    \u03d5.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2085 c\u2086 \u226b CLCFPTinv\u2082.res r V r' c\u2085 c\u2086 c\u2087 c\u2088 m :=\nbegin\n  dsimp only [CLCFPTinv\u2082.res, eval_CLCFPTinv\u2082, CLCFPTinv\u2082_def, CLCTinv.map_nat_def], delta id,\n  simp only [SemiNormedGroup.equalizer.map_nat_comp_map_nat],\n  congr' 1; { simp only [\u2190 CLCFP.res_def], apply res_comp_eval_CLCFP },\nend\n\nlemma norm_eval_CLCFPTinv\u2082_le [fact (c\u2082 \u2264 r' * c\u2081)] [fact (c\u2084 \u2264 r' * c\u2083)]\n  [\u03d5.suitable c\u2083 c\u2081] [\u03d5.suitable c\u2084 c\u2082] (N : \u2115) (h : \u03d5.bound_by N) (M) :\n  \u2225(\u03d5.eval_CLCFPTinv\u2082 r V r' c\u2081 c\u2082 c\u2083 c\u2084).app M\u2225 \u2264 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.\u03b9_norm_noninc }\nend\n\ndef eval_CLCFPTinv [\u03d5.suitable c\u2082 c\u2081] :\n  CLCFPTinv r V r' c\u2081 n \u27f6 CLCFPTinv r V r' c\u2082 m :=\n\u03d5.eval_CLCFPTinv\u2082 r V r' c\u2081 _ c\u2082 _\n\nlemma eval_CLCFPTinv_def [\u03d5.suitable c\u2082 c\u2081] :\n  \u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2082 = \u03d5.eval_CLCFPTinv\u2082 r V r' c\u2081 _ c\u2082 _ := rfl\n\n@[simp] lemma eval_CLCFPTinv_zero :\n  (0 : universal_map m n).eval_CLCFPTinv r V r' c\u2081 c\u2082 = 0 :=\nby apply eval_CLCFPTinv\u2082_zero\n\n@[simp] lemma eval_CLCFPTinv_add [\u03d5.suitable c\u2082 c\u2081] [\u03c8.suitable c\u2082 c\u2081] :\n  (\u03d5 + \u03c8 : universal_map m n).eval_CLCFPTinv r V r' c\u2081 c\u2082 =\n  \u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2082 + \u03c8.eval_CLCFPTinv r V r' c\u2081 c\u2082 :=\neval_CLCFPTinv\u2082_add _ _ _ _ _ _ _ _ _\n\n@[simp] lemma eval_CLCFPTinv_sub [\u03d5.suitable c\u2082 c\u2081] [\u03c8.suitable c\u2082 c\u2081] :\n  (\u03d5 - \u03c8 : universal_map m n).eval_CLCFPTinv r V r' c\u2081 c\u2082 =\n  \u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2082 - \u03c8.eval_CLCFPTinv r V r' c\u2081 c\u2082 :=\neval_CLCFPTinv\u2082_sub _ _ _ _ _ _ _ _ _\n\nlemma eval_CLCFPTinv_comp {l m n : FreeMat} (f : l \u27f6 m) (g : m \u27f6 n)\n  [hg : g.suitable c\u2082 c\u2081] [hf : f.suitable c\u2083 c\u2082] :\n  @eval_CLCFPTinv r V _ _ r' _ _ c\u2081 c\u2083 _ _ (f \u226b g) (suitable.comp c\u2082) =\n    g.eval_CLCFPTinv r V r' c\u2081 c\u2082 \u226b f.eval_CLCFPTinv r V r' c\u2082 c\u2083 :=\nby apply eval_CLCFPTinv\u2082_comp\n\nlemma res_comp_eval_CLCFPTinv\n  [fact (c\u2082 \u2264 c\u2081)] [\u03d5.suitable c\u2084 c\u2082] [\u03d5.suitable c\u2083 c\u2081] [fact (c\u2084 \u2264 c\u2083)] :\n  res r V r' c\u2081 c\u2082 n \u226b \u03d5.eval_CLCFPTinv r V r' c\u2082 c\u2084 =\n    \u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2083 \u226b res r V r' c\u2083 c\u2084 m :=\nby apply res_comp_eval_CLCFPTinv\u2082\n\nlemma res_comp_eval_CLCFPTinv_absorb\n  [fact (c\u2082 \u2264 c\u2081)] [h\u03d5 : \u03d5.suitable c\u2083 c\u2082] :\n  res r V r' c\u2081 c\u2082 n \u226b \u03d5.eval_CLCFPTinv r V r' c\u2082 c\u2083 =\n    @eval_CLCFPTinv r V _ _ r' _ _ c\u2081 c\u2083 _ _ \u03d5 (h\u03d5.le _ _ _ _ le_rfl (fact.out _)) :=\nby rw [@res_comp_eval_CLCFPTinv r V _ _ r' _ _ c\u2081 c\u2082 c\u2083 c\u2083 _ _ \u03d5\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\u2083 \u2264 c\u2082)} [h\u03d5 : \u03d5.suitable c\u2082 c\u2081] :\n  \u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2082 \u226b res r V r' c\u2082 c\u2083 m =\n    @eval_CLCFPTinv r V _ _ r' _ _ c\u2081 c\u2083 _ _ \u03d5 (h\u03d5.le _ _ _ _ (fact.out _) le_rfl) :=\nby rw [\u2190 @res_comp_eval_CLCFPTinv r V _ _ r' _ _ c\u2081 c\u2081 c\u2082 c\u2083 _ _ \u03d5\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)] [\u03d5.suitable c\u2082 c\u2081]\n  (N : \u2115) (h : \u03d5.bound_by N) (M) :\n  \u2225(\u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2082).app M\u2225 \u2264 N :=\nnorm_eval_CLCFPTinv\u2082_le r V r' _ _ _ _ _ N h M\n\nlemma eval_CLCFPTinv_norm_noninc [normed_with_aut r V] [fact (0 < r)]\n  [h : \u03d5.very_suitable r r' c\u2082 c\u2081] (M) :\n  ((\u03d5.eval_CLCFPTinv r V r' c\u2081 c\u2082).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 \u27e8N, k, c', hN, h\u03d5, hr, H\u27e9 },\n  haveI : fact (c' \u2264 c\u2081) := \u27e8H.trans $ fact.out _\u27e9,\n  have aux := res_comp_eval_CLCFPTinv r V r' c\u2081 c' c\u2082 c\u2082 \u03d5,\n  rw [res_refl, category.comp_id] at aux,\n  rw \u2190 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' \u2264 r' ^ k * c\u2081) := \u27e8H\u27e9,\n    rw nnreal.coe_pow,\n    apply norm_res_le_pow },\nend\n\nend universal_map\n\nend breen_deligne\n\nattribute [irreducible] CLCFPTinv\u2082 CLCFPTinv\u2082.res\n  breen_deligne.universal_map.eval_CLCFPTinv\u2082\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": "example (h : P) : P \u2228 Q := by\n  apply .inl\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/1719.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2337063569140403, "lm_q2_score": 0.053403331683011195, "lm_q1q2_score": 0.01248069809470869}}
{"text": "import Cdclt.Euf\n\nopen proof\nopen proof.sort proof.term\nopen rules eufRules\n\ndef U := atom 50\ndef a\u2081 := const 100 U\ndef a\u2082 := const 101 U\ndef a\u2083 := const 102 U\ndef a\u2084 := const 103 U\ndef b\u2081 := const 104 U\ndef b\u2082 := const 105 U\ndef f\u2081 := const 106 (mkArrowN [U, U, U])\ndef f\u2082 := const 107 (mkArrowN [U, U, U])\ndef f\u2083 := const 108 (mkArrowN [U, U])\n\ntheorem binCong :\n  thHolds (mkEq a\u2081 a\u2082) \u2192 thHolds (mkEq b\u2081 b\u2082) \u2192 (thHolds (mkEq (mkApp (mkApp f\u2081 a\u2081) b\u2081) (mkApp (mkApp f\u2081 a\u2082) b\u2082))) :=\n\u03bb s0 : thHolds (mkEq a\u2081 a\u2082) =>\n\u03bb s1 : thHolds (mkEq b\u2081 b\u2082) =>\nhave s2 : thHolds (mkEq f\u2081 f\u2081) from refl\nshow (thHolds (mkEq (mkApp (mkApp f\u2081 a\u2081) b\u2081) (mkApp (mkApp f\u2081 a\u2082) b\u2082))) 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\u2081 := const 1002 boolSort\ndef p\u2082 := const 1003 boolSort\ndef p\u2083 := 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\u2081 := mkNot p\u2081\ndef np\u2083 := mkNot p\u2083\ndef andp\u2082p\u2083 := mkAnd p\u2082 p\u2083\ndef ornp\u2081andp\u2082p\u2083 := mkOr np\u2081 andp\u2082p\u2083\ndef ornp\u2083neqfafb := mkOr np\u2083 neqfafb\n\ntheorem simpleCongRw :\n  thHolds eqab \u2192 thHolds ornp\u2083neqfafb \u2192 thHolds p\u2081 \u2192 thHolds ornp\u2081andp\u2082p\u2083 \u2192 thHolds bot :=\n\u03bb s0 : thHolds eqab =>\n\u03bb s1 : thHolds ornp\u2083neqfafb =>\n\u03bb s2 : thHolds p\u2081 =>\n\u03bb s3 : thHolds ornp\u2081andp\u2082p\u2083 =>\n\nhave s4 : thHolds andp\u2082p\u2083 from thAssume (R1 (clOr s3) (clAssume s2) p\u2081)\nhave s5 : thHolds p\u2083 from andElim s4 1\nhave s6 : thHolds neqfafb from thAssume (R1 (clOr s1) (clAssume s5) p\u2083)\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\u2081t := mkAnd p\u2081 (val (value.bool true) boolSort)\n\ntheorem simpleCong :\n  thHolds eqab \u2192 thHolds andp\u2081t \u2192 thHolds ornp\u2083neqfafb \u2192 thHolds p\u2081 \u2192 thHolds ornp\u2081andp\u2082p\u2083 \u2192 holds [] :=\n  -- thHolds eqab \u2192 thHolds andp\u2081t \u2192 thHolds ornp\u2083neqfafb \u2192 thHolds p\u2081 \u2192 thHolds ornp\u2081andp\u2082p\u2083 \u2192 thHolds (mkOr (mkNot eqab) eqfafb) :=\nfun a0 : thHolds eqab =>\nfun a1 : thHolds andp\u2081t =>\nfun a2 : thHolds ornp\u2083neqfafb =>\nfun a3 : thHolds p\u2081 =>\nfun a4 : thHolds ornp\u2081andp\u2082p\u2083 =>\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\u2082p\u2083] from R1 (clOr a4) (clAssume a3) p\u2081\nhave s3 : holds ([(mkNot (mkAndN [p\u2082, p\u2083])), p\u2083]) from @cnfAndPos ([p\u2082, p\u2083]) 1\nhave s4 : holds [p\u2083, mkNot andp\u2082p\u2083] from reorder s3 [1,0]\n\nhave s5 : thHolds (mkEq andp\u2081t p\u2081) from thTrustValid\nhave s6 : thHolds p\u2081 from eqResolve a1 s5\nhave s7 : holds [andp\u2082p\u2083] from R1 (clOr a4) (clAssume s6) p\u2081\nhave s8 : holds [p\u2083] from R1 s4 s7 andp\u2082p\u2083\n\nhave s9 : holds [neqfafb] from R1 (clOr a2) s8 p\u2083\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 \u2192 list (expr elab) \u2192 list (expr elab) \u2192 mono_function\n | assoc : expr elab \u2192 option (expr elab) \u2192 option (expr elab) \u2192 mono_function\n | assoc_comm : expr elab \u2192 expr elab \u2192 mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function \u2192 tactic format\n | (mono_function.non_assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 mmap pp xs,\n  ys' \u2190 mmap pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 pp xs,\n  ys' \u2190 pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 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 \u2192 expr \u2192 expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr \u2192 expr \u2192 expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn  \u2190 pp ctx.function,\n   l   \u2190 pp ctx.left,\n   r   \u2190 pp ctx.right,\n   rel \u2190 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 \u2190 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 \u2192 expr \u2192 expr \u2192 tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) \u2190 return t | failed,\n   v \u2190 mk_meta_var d,\n   match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr \u2192 tactic expr\n| (expr.pi n _ t b) :=\ndo v \u2190 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 \u2192 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 \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 list expr)\n | es (x :: xs) := do\n    es' \u2190 delete_expr x es,\n    match es' with\n     | (some es') := do\n       (c,l,r) \u2190 match_ac' es' xs, return (x::c,l,r)\n     | none := do\n       (c,l,r) \u2190 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 \u00d7 list expr \u00d7 list expr) :=\ndo (s',l',r') \u2190 match_ac' l r,\n   s' \u2190 mmap instantiate_mvars s',\n   l' \u2190 mmap instantiate_mvars l',\n   r' \u2190 mmap instantiate_mvars r',\n   return (s',l',r')\n\nmeta def match_prefix\n: list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 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) \u2190 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 \u00d7 list expr \u00d7 list expr \u00d7 list expr) :=\ndo (pre,l\u2081,r\u2081) \u2190 match_prefix l r,\n   (suf,l\u2082,r\u2082) \u2190 match_prefix (reverse l\u2081) (reverse r\u2081),\n   return (pre,reverse l\u2082,reverse r\u2082,reverse suf)\n\nmeta def check_ac : expr \u2192 tactic (bool \u00d7 bool \u00d7 option (expr \u00d7 expr \u00d7 expr) \u00d7 expr)\n | (expr.app (expr.app f x) y) :=\n   do t \u2190 infer_type x,\n      a \u2190 try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n      c \u2190 try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n      i \u2190 try_core (do\n          v \u2190 mk_meta_var t,\n          l_inst_p \u2190 to_expr ``(is_left_id %%t %%f %%v),\n          r_inst_p \u2190 to_expr ``(is_right_id %%t %%f %%v),\n          l_v \u2190 mk_meta_var l_inst_p,\n          r_v \u2190 mk_meta_var r_inst_p ,\n          l_id \u2190 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 \u2190 mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n          mk_instance r_inst_p >>= unify r_v,\n          v' \u2190 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 \u2192 tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) \u2190 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 \u2192 tactic (list expr) :=\nmap dlist.to_list \u2218 parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) :\n  option (expr \u00d7 expr \u00d7 expr) \u2192 list expr \u2192 option (expr \u00d7 list expr)\n| _ (x::xs) := some (foldl (expr.app \u2218 expr.app op) x xs, [])\n| none []   := none\n| (some (l_id,r_id,x\u2080)) [] := some (x\u2080,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr \u2192 option expr\n| (x::xs) := some $ foldl (expr.app \u2218 expr.app op) x xs\n| []   := none\n\nmeta def same_function_aux\n: list expr \u2192 list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr)\n | xs\u2080 xs\u2081 (expr.app f\u2080 a\u2080) (expr.app f\u2081 a\u2081) :=\n   same_function_aux (a\u2080 :: xs\u2080) (a\u2081 :: xs\u2081) f\u2080 f\u2081\n | xs\u2080 xs\u2081 e\u2080 e\u2081 := is_def_eq e\u2080 e\u2081 >> return (e\u2080,xs\u2080,xs\u2081)\n\nmeta def same_function : expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr \u00d7 expr \u00d7 list expr \u00d7 mono_function) :=\ndo (full_f,ls,rs) \u2190 same_function l r,\n   (a,c,i,f) \u2190 check_ac l,\n   if a\n   then if c\n   then do\n     (s,ls,rs) \u2190 monad.join (match_ac\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 fold_assoc f i rs,\n     s' \u2190 fold_assoc1 f s,\n     return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n   else do -- a \u2227 \u00ac c\n     (pre,ls,rs,suff) \u2190 monad.join (match_assoc\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 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 -- \u00ac a\n     (xs\u2080,x\u2080,x\u2081,xs\u2081) \u2190 find_one_difference opt ls rs,\n     return (x\u2080,x\u2081,[],mono_function.non_assoc full_f xs\u2080 xs\u2081)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' \u2190 to_expr l,\n   r' \u2190 to_expr r,\n   parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr \u2192 tactic (expr \u00d7 expr \u00d7 list expr \u00d7 ac_mono_ctx)\n | `(%%e\u2080 \u2192 %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) \u2192 (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080 = %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) = (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080) e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     return (e\u2080, e\u2081, id_rs,\n            { function := f\n            , left := l, right := r\n            , to_rel := expr.app \u2218 expr.app rel\n            , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr)  : option expr \u2192 expr \u2192 expr\n| none e := e\n| (some e\u2080) e\u2081 := f.mk_app [e\u2080,e\u2081]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr \u2192 option expr \u2192 expr\n| e none := e\n| e\u2080 (some e\u2081) := f.mk_app [e\u2080,e\u2081]\n\nmeta def mk_fun_app : mono_function \u2192 expr \u2192 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\u2080,r\u2080) (r\u2081,l\u2081)` gives first how to find rules to prove\n      x+(y\u2080+z) R x+(y\u2081+z);\n      if that fails, helps prove (x+y\u2080)+z R (x+y\u2081)+z -/\n | assoc : expr \u00d7 expr \u2192 expr \u00d7 expr \u2192 mono_law\n   /- `congr r` gives the rule to prove `x = y \u2192 f x = f y` -/\n | congr : expr \u2192 mono_law\n | other : expr \u2192 mono_law\n\nmeta def mono_law.to_tactic_format : mono_law \u2192 tactic format\n | (mono_law.other e) := do e \u2190 pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e \u2190 pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\ndo x\u2080 \u2190 pp x\u2080,\n   x\u2081 \u2190 pp x\u2081,\n   y\u2080 \u2190 pp y\u2080,\n   y\u2081 \u2190 pp y\u2081,\n   return format!\"assoc {x\u2080}; {x\u2081} | {y\u2080}; {y\u2081}\"\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 \u2192 expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs\u2080 xs\u2081 : list expr) (l r : expr) : tactic expr :=\ndo p \u2190 mk_app `eq [fn.mk_app $ xs\u2080 ++ l :: xs\u2081,fn.mk_app $ xs\u2080 ++ r :: xs\u2081],\n   prod.snd <$> solve_aux p\n     (do iterate_exactly (xs\u2081.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\u2080 x\u2081) :=\n    if (x\u2080 <|> x\u2081).is_some\n       then mk_congr_args f x\u2080.to_monad x\u2081.to_monad ctx.left ctx.right\n       else failed\n | (mono_function.assoc_comm f x\u2080) := mk_congr_args f [x\u2080] [] ctx.left ctx.right\n | (mono_function.non_assoc f x\u2080 x\u2081) := mk_congr_args f x\u2080 x\u2081 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 (\u03bb i, bin_op f x (bin_op f i y))\n       , mk_rel ctx (\u03bb i, bin_op f i y))\n       ( mk_rel ctx (\u03bb i, bin_op f (bin_op f x i) y)\n       , mk_rel ctx (\u03bb i, bin_op f x i))\n    | (mono_function.assoc f (some x) none) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb e, mk_fun_app ctx.function e)\n    | (mono_function.assoc f none (some y)) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb 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 (\u03bb 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' \u2190 mk_const r,\n    t  \u2190 infer_type r',\n    t  \u2190 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 \u2192 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\u2080 x\u2081 : expr) : tactic (list expr) :=\ndo x' \u2190 to_expr ``(%%x\u2081 \u2192 %%x\u2080),\n   r\u2080 \u2190 find_lemma x' ls,\n   r\u2081 \u2190 find_lemma x\u2081 ls,\n   return (expr.app <$> r\u2080 <*> r\u2081)\n\nmeta def find_rule (ls : list name) : mono_law \u2192 tactic (list expr)\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\n(match_chaining_rules ls x\u2080 x\u2081)\n<|> (match_chaining_rules ls y\u2080 y\u2081)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x y : \u03b1}\n  (x' y' : \u03b1)\n  (h : R x y)\n  (hx : x = x')\n  (hy : y = y')\n: R x' y' :=\nby { rw [\u2190 hx,\u2190 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 \u2190 pp e,\n   asm \u2190 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 \u2190 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 \u00d7 expr) :=\ndo tgt \u2190 target,\n   t \u2190 infer_type v,\n   tgt' \u2190 do\n   { \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize v x >> target),\n     to_expr ``(\u03bb y : %%t, \u03a0 x, y = x \u2192 %%(tgt'.binding_body.lift_vars 0 1)) }\n   <|> to_expr ``(\u03bb y : %%t, \u03a0 x, %%v = x \u2192 %%tgt),\n   t \u2190 head_beta (tgt' v) >>= assert h,\n   swap,\n   r \u2190 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 \u2192 tactic unit) : tactic unit :=\nfocus1 $\ndo tgt \u2190 target >>= instantiate_mvars,\n   tactic.change tgt,\n   ctx \u2190 local_context,\n   let vs := tgt.list_meta_vars,\n   vs' \u2190 mmap (\u03bb v,\n             do h \u2190 get_unused_name `h,\n                x \u2190 get_unused_name `x,\n                prod.snd <$> monotonicity.generalize' h v x) vs,\n     tac ctx;\n     vs'.mmap' (try \u2218 tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ \u03bb _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   set_goals [v],\n   target >>= instantiate_mvars >>= tactic.change,\n   tac, done,\n   set_goals $ gs\n\ndef list.minimum_on {\u03b1 \u03b2} [linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : list \u03b1 \u2192 list \u03b1\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (\u03bb \u27e8k,a\u27e9 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 {\u03b2} (xs : list expr) (tac : expr \u2192 tactic \u03b2) : tactic unit :=\ndo t \u2190 target,\n   xs \u2190 xs.mmap (\u03bb 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 \u2218 prod.fst \u2218 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 \u2190 r.mmap (\u03bb \u27e8l,gs,_\u27e9,\n          do ts \u2190 gs.mmap infer_type,\n             msg \u2190 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 \u2190 target >>= instantiate_mvars,\n   ns \u2190 get_monotonicity_lemmas t dir,\n   asms \u2190 local_context,\n   rs \u2190 find_lemma asms t ns,\n   focus1 $ () <$ best_match rs (\u03bb law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (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 \u2190 hyps.mmap (\u03bb p, to_expr p >>= mk_meta_var),\n   hyps.mmap' (\u03bb pr, do h \u2190 get_unused_name `h, note h none pr),\n   when (\u00ac 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 \u2190 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 \u227c f y` into `x \u2264 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 $ \u03bb asms,\ndo try `[simp only [sub_eq_add_neg]],\n   tgt \u2190 target >>= instantiate_mvars,\n   (l,r,id_rs,g) \u2190 ac_monotonicity_goal cfg tgt\n             <|> fail \"monotonic context not found\",\n   ns \u2190 get_monotonicity_lemmas tgt both,\n   p \u2190 mk_pattern g,\n   rules \u2190 find_rule asms ns p <|> fail \"no applicable rules found\",\n   when (rules = []) (fail \"no applicable rules found\"),\n   err \u2190 format.join <$> mmap side_conditions rules,\n   focus1 $ best_match rules (\u03bb rule, do\n     t\u2080 \u2190 mk_meta_var `(Prop),\n     v\u2080 \u2190 mk_meta_var t\u2080,\n     t\u2081 \u2190 mk_meta_var `(Prop),\n     v\u2081 \u2190 mk_meta_var t\u2081,\n     tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v\u2080 %%v\u2081),\n     solve_mvar v\u2080 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     solve_mvar v\u2081 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     n \u2190 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 \u2192 tactic unit \u2192 tactic unit \u2192 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 \u2192 tactic unit \u2192 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 : \u2115) | many\n\nmeta def repeat_or_not : rep_arity \u2192 tactic unit \u2192 option (tactic unit) \u2192 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 \u2295 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 \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* := h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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? \u2192\n         opt_param mono_cfg { mono_cfg . } \u2192\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 \u2190 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": "/-\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.FindExpr\nimport Lean.Parser.Term\nimport Lean.Meta.Structure\nimport Lean.Elab.App\nimport Lean.Elab.Binders\n\nnamespace Lean.Elab.Term.StructInst\n\nopen Meta\nopen TSyntax.Compat\n\n/-\n  Structure instances are of the form:\n\n      \"{\" >> optional (atomic (sepBy1 termParser \", \" >> \" with \"))\n          >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))\n          >> optEllipsis\n          >> optional (\" : \" >> termParser)\n          >> \" }\"\n-/\n\n@[builtin_macro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx =>\n  let expectedArg := stx[4]\n  if expectedArg.isNone then\n    Macro.throwUnsupported\n  else\n    let expected := expectedArg[1]\n    let stxNew   := stx.setArg 4 mkNullNode\n    `(($stxNew : $expected))\n\n/-- Expand field abbreviations. Example: `{ x, y := 0 }` expands to `{ x := x, y := 0 }` -/\n@[builtin_macro Lean.Parser.Term.structInst] def expandStructInstFieldAbbrev : Macro\n  | `({ $[$srcs,* with]? $fields,* $[..%$ell]? $[: $ty]? }) =>\n    if fields.getElems.raw.any (\u00b7.getKind == ``Lean.Parser.Term.structInstFieldAbbrev) then do\n      let fieldsNew \u2190 fields.getElems.mapM fun\n        | `(Parser.Term.structInstFieldAbbrev| $id:ident) =>\n          `(Parser.Term.structInstField| $id:ident := $id:ident)\n        | field => return field\n      `({ $[$srcs,* with]? $fieldsNew,* $[..%$ell]? $[: $ty]? })\n    else\n      Macro.throwUnsupported\n  | _ => Macro.throwUnsupported\n\n/--\n  If `stx` is of the form `{ s\u2081, ..., s\u2099 with ... }` and `s\u1d62` is not a local variable, expand into `let src := s\u1d62; { ..., src, ... with ... }`.\n\n  Note that this one is not a `Macro` because we need to access the local context.\n-/\nprivate def expandNonAtomicExplicitSources (stx : Syntax) : TermElabM (Option Syntax) := do\n  let sourcesOpt := stx[1]\n  if sourcesOpt.isNone then\n    return none\n  else\n    let sources := sourcesOpt[0]\n    if sources.isMissing then\n      throwAbortTerm\n    let sources := sources.getSepArgs\n    if (\u2190 sources.allM fun source => return (\u2190 isLocalIdent? source).isSome) then\n      return none\n    if sources.any (\u00b7.isMissing) then\n      throwAbortTerm\n    return some (\u2190 go sources.toList #[])\nwhere\n  go (sources : List Syntax) (sourcesNew : Array Syntax) : TermElabM Syntax := do\n    match sources with\n    | [] =>\n      let sources := Syntax.mkSep sourcesNew (mkAtomFrom stx \", \")\n      return stx.setArg 1 (stx[1].setArg 0 sources)\n    | source :: sources =>\n      if (\u2190 isLocalIdent? source).isSome then\n        go sources (sourcesNew.push source)\n      else\n        withFreshMacroScope do\n          let sourceNew \u2190 `(src)\n          let r \u2190 go sources (sourcesNew.push sourceNew)\n          `(let src := $source; $r)\n\nstructure ExplicitSourceInfo where\n  stx        : Syntax\n  structName : Name\n  deriving Inhabited\n\nstructure Source where\n  explicit : Array ExplicitSourceInfo -- `s\u2081 ... s\u2099 with`\n  implicit : Option Syntax -- `..`\n  deriving Inhabited\n\ndef Source.isNone : Source \u2192 Bool\n  | { explicit := #[], implicit := none } => true\n  | _ => false\n\n/-- `optional (atomic (sepBy1 termParser \", \" >> \" with \")` -/\nprivate def mkSourcesWithSyntax (sources : Array Syntax) : Syntax :=\n  let ref := sources[0]!\n  let stx := Syntax.mkSep sources (mkAtomFrom ref \", \")\n  mkNullNode #[stx, mkAtomFrom ref \"with \"]\n\nprivate def getStructSource (structStx : Syntax) : TermElabM Source :=\n  withRef structStx do\n    let explicitSource := structStx[1]\n    let implicitSource := structStx[3]\n    let explicit \u2190 if explicitSource.isNone then\n      pure #[]\n    else\n      explicitSource[0].getSepArgs.mapM fun stx => do\n        let some src \u2190 isLocalIdent? stx | unreachable!\n        addTermInfo' stx src\n        let srcType \u2190 whnf (\u2190 inferType src)\n        tryPostponeIfMVar srcType\n        let structName \u2190 getStructureName srcType\n        return { stx, structName }\n    let implicit := if implicitSource[0].isNone then none else implicitSource\n    return { explicit, implicit }\n\n/--\n  We say a `{ ... }` notation is a `modifyOp` if it contains only one\n  ```\n  def structInstArrayRef := leading_parser \"[\" >> termParser >>\"]\"\n  ```\n-/\nprivate def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do\n  let s? \u2190 stx[2].getSepArgs.foldlM (init := none) fun s? arg => do\n    /- arg is of the form `structInstFieldAbbrev <|> structInstField` -/\n    if arg.getKind == ``Lean.Parser.Term.structInstField then\n      /- Remark: the syntax for `structInstField` is\n         ```\n         def structInstLVal   := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (group (\".\" >> (ident <|> numLit)) <|> structInstArrayRef)\n         def structInstField  := leading_parser structInstLVal >> \" := \" >> termParser\n         ```\n      -/\n      let lval := arg[0]\n      let k    := lval[0].getKind\n      if k == ``Lean.Parser.Term.structInstArrayRef then\n        match s? with\n        | none   => return some arg\n        | some s =>\n          if s.getKind == ``Lean.Parser.Term.structInstArrayRef then\n            throwErrorAt arg \"invalid \\{...} notation, at most one `[..]` at a given level\"\n          else\n            throwErrorAt arg \"invalid \\{...} notation, can't mix field and `[..]` at a given level\"\n      else\n        match s? with\n        | none   => return some arg\n        | some s =>\n          if s.getKind == ``Lean.Parser.Term.structInstArrayRef then\n            throwErrorAt arg \"invalid \\{...} notation, can't mix field and `[..]` at a given level\"\n          else\n            return s?\n    else\n      return s?\n  match s? with\n  | none   => return none\n  | some s => if s[0][0].getKind == ``Lean.Parser.Term.structInstArrayRef then return s? else return none\n\nprivate def elabModifyOp (stx modifyOp : Syntax) (sources : Array ExplicitSourceInfo) (expectedType? : Option Expr) : TermElabM Expr := do\n  if sources.size > 1 then\n    throwError \"invalid \\{...} notation, multiple sources and array update is not supported.\"\n  let cont (val : Syntax) : TermElabM Expr := do\n    let lval := modifyOp[0][0]\n    let idx  := lval[1]\n    let self := sources[0]!.stx\n    let stxNew \u2190 `($(self).modifyOp (idx := $idx) (fun s => $val))\n    trace[Elab.struct.modifyOp] \"{stx}\\n===>\\n{stxNew}\"\n    withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  let rest := modifyOp[0][1]\n  if rest.isNone then\n    cont modifyOp[2]\n  else\n    let s \u2190 `(s)\n    let valFirst  := rest[0]\n    let valFirst  := if valFirst.getKind == ``Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1]\n    let restArgs  := rest.getArgs\n    let valRest   := mkNullNode restArgs[1:restArgs.size]\n    let valField  := modifyOp.setArg 0 <| mkNode ``Parser.Term.structInstLVal #[valFirst, valRest]\n    let valSource := mkSourcesWithSyntax #[s]\n    let val       := stx.setArg 1 valSource\n    let val       := val.setArg 2 <| mkNullNode #[valField]\n    trace[Elab.struct.modifyOp] \"{stx}\\nval: {val}\"\n    cont val\n\n/--\n  Get structure name.\n  This method triest to postpone execution if the expected type is not available.\n\n  If the expected type is available and it is a structure, then we use it.\n  Otherwise, we use the type of the first source. -/\nprivate def getStructName (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let useSource : Unit \u2192 TermElabM Name := fun _ => do\n    unless sourceView.explicit.isEmpty do\n      return sourceView.explicit[0]!.structName\n    match expectedType? with\n    | some expectedType => throwUnexpectedExpectedType expectedType\n    | none => throwUnknownExpectedType\n  match expectedType? with\n  | none => useSource ()\n  | some expectedType =>\n    let expectedType \u2190 whnf expectedType\n    match expectedType.getAppFn with\n    | Expr.const constName _ =>\n      unless isStructure (\u2190 getEnv) constName do\n        throwError \"invalid \\{...} notation, structure type expected{indentExpr expectedType}\"\n      return constName\n    | _                        => useSource ()\nwhere\n  throwUnknownExpectedType :=\n    throwError \"invalid \\{...} notation, expected type is not known\"\n  throwUnexpectedExpectedType type (kind := \"expected\") := do\n    let type \u2190 instantiateMVars type\n    if type.getAppFn.isMVar then\n      throwUnknownExpectedType\n    else\n      throwError \"invalid \\{...} notation, {kind} type is not of the form (C ...){indentExpr type}\"\n\ninductive FieldLHS where\n  | fieldName  (ref : Syntax) (name : Name)\n  | fieldIndex (ref : Syntax) (idx : Nat)\n  | modifyOp   (ref : Syntax) (index : Syntax)\n  deriving Inhabited\n\ninstance : ToFormat FieldLHS := \u27e8fun lhs =>\n  match lhs with\n  | .fieldName _ n  => format n\n  | .fieldIndex _ i => format i\n  | .modifyOp _ i   => \"[\" ++ i.prettyPrint ++ \"]\"\u27e9\n\ninductive FieldVal (\u03c3 : Type) where\n  | term  (stx : Syntax) : FieldVal \u03c3\n  | nested (s : \u03c3)       : FieldVal \u03c3\n  | default              : FieldVal \u03c3 -- mark that field must be synthesized using default value\n  deriving Inhabited\n\nstructure Field (\u03c3 : Type) where\n  ref   : Syntax\n  lhs   : List FieldLHS\n  val   : FieldVal \u03c3\n  expr? : Option Expr := none\n  deriving Inhabited\n\ndef Field.isSimple {\u03c3} : Field \u03c3 \u2192 Bool\n  | { lhs := [_], .. } => true\n  | _                  => false\n\ninductive Struct where\n  /-- Remark: the field `params` is use for default value propagation. It is initially empty, and then set at `elabStruct`. -/\n  | mk (ref : Syntax) (structName : Name) (params : Array (Name \u00d7 Expr)) (fields : List (Field Struct)) (source : Source)\n  deriving Inhabited\n\nabbrev Fields := List (Field Struct)\n\ndef Struct.ref : Struct \u2192 Syntax\n  | \u27e8ref, _, _, _, _\u27e9 => ref\n\ndef Struct.structName : Struct \u2192 Name\n  | \u27e8_, structName, _, _, _\u27e9 => structName\n\ndef Struct.params : Struct \u2192 Array (Name \u00d7 Expr)\n  | \u27e8_, _, params, _, _\u27e9 => params\n\ndef Struct.fields : Struct \u2192 Fields\n  | \u27e8_, _, _, fields, _\u27e9 => fields\n\ndef Struct.source : Struct \u2192 Source\n  | \u27e8_, _, _, _, s\u27e9 => s\n\n/-- `true` iff all fields of the given structure are marked as `default` -/\npartial def Struct.allDefault (s : Struct) : Bool :=\n  s.fields.all fun { val := val,  .. } => match val with\n    | .term _   => false\n    | .default  => true\n    | .nested s => allDefault s\n\ndef formatField (formatStruct : Struct \u2192 Format) (field : Field Struct) : Format :=\n  Format.joinSep field.lhs \" . \" ++ \" := \" ++\n    match field.val with\n    | .term v   => v.prettyPrint\n    | .nested s => formatStruct s\n    | .default  => \"<default>\"\n\npartial def formatStruct : Struct \u2192 Format\n  | \u27e8_, _,          _, fields, source\u27e9 =>\n    let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) \", \"\n    let implicitFmt := if source.implicit.isSome then \" .. \" else \"\"\n    if source.explicit.isEmpty then\n      \"{\" ++ fieldsFmt ++ implicitFmt ++ \"}\"\n    else\n      \"{\" ++ format (source.explicit.map (\u00b7.stx)) ++ \" with \" ++ fieldsFmt ++ implicitFmt ++ \"}\"\n\ninstance : ToFormat Struct     := \u27e8formatStruct\u27e9\ninstance : ToString Struct := \u27e8toString \u2218 format\u27e9\n\ninstance : ToFormat (Field Struct) := \u27e8formatField formatStruct\u27e9\ninstance : ToString (Field Struct) := \u27e8toString \u2218 format\u27e9\n\n/-\nRecall that `structInstField` elements have the form\n```\n   def structInstField  := leading_parser structInstLVal >> \" := \" >> termParser\n   def structInstLVal   := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many ((\".\" >> (ident <|> numLit)) <|> structInstArrayRef)\n   def structInstArrayRef := leading_parser \"[\" >> termParser >>\"]\"\n```\n-/\n-- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName`\ndef FieldLHS.toSyntax (first : Bool) : FieldLHS \u2192 Syntax\n  | .modifyOp   stx _    => stx\n  | .fieldName  stx name => if first then mkIdentFrom stx name else mkGroupNode #[mkAtomFrom stx \".\", mkIdentFrom stx name]\n  | .fieldIndex stx _    => if first then stx else mkGroupNode #[mkAtomFrom stx \".\", stx]\n\ndef FieldVal.toSyntax : FieldVal Struct \u2192 Syntax\n  | .term stx => stx\n  | _                 => unreachable!\n\ndef Field.toSyntax : Field Struct \u2192 Syntax\n  | field =>\n    let stx := field.ref\n    let stx := stx.setArg 2 field.val.toSyntax\n    match field.lhs with\n    | first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ]\n    | _ => unreachable!\n\nprivate def toFieldLHS (stx : Syntax) : MacroM FieldLHS :=\n  if stx.getKind == ``Lean.Parser.Term.structInstArrayRef then\n    return FieldLHS.modifyOp stx stx[1]\n  else\n    -- Note that the representation of the first field is different.\n    let stx := if stx.getKind == groupKind then stx[1] else stx\n    if stx.isIdent then\n      return FieldLHS.fieldName stx stx.getId.eraseMacroScopes\n    else match stx.isFieldIdx? with\n      | some idx => return FieldLHS.fieldIndex stx idx\n      | none     => Macro.throwError \"unexpected structure syntax\"\n\nprivate def mkStructView (stx : Syntax) (structName : Name) (source : Source) : MacroM Struct := do\n  /- Recall that `stx` is of the form\n     ```\n     leading_parser \"{\" >> optional (atomic (sepBy1 termParser \", \" >> \" with \"))\n                 >> sepByIndent (structInstFieldAbbrev <|> structInstField) ...\n                 >> optional \"..\"\n                 >> optional (\" : \" >> termParser)\n                 >> \" }\"\n     ```\n\n     This method assumes that `structInstFieldAbbrev` had already been expanded.\n  -/\n  let fields \u2190 stx[2].getSepArgs.toList.mapM fun fieldStx => do\n    let val      := fieldStx[2]\n    let first    \u2190 toFieldLHS fieldStx[0][0]\n    let rest     \u2190 fieldStx[0][1].getArgs.toList.mapM toFieldLHS\n    return { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct }\n  return \u27e8stx, structName, #[], fields, source\u27e9\n\ndef Struct.modifyFieldsM {m : Type \u2192 Type} [Monad m] (s : Struct) (f : Fields \u2192 m Fields) : m Struct :=\n  match s with\n  | \u27e8ref, structName, params, fields, source\u27e9 => return \u27e8ref, structName, params, (\u2190 f fields), source\u27e9\n\ndef Struct.modifyFields (s : Struct) (f : Fields \u2192 Fields) : Struct :=\n  Id.run <| s.modifyFieldsM f\n\ndef Struct.setFields (s : Struct) (fields : Fields) : Struct :=\n  s.modifyFields fun _ => fields\n\ndef Struct.setParams (s : Struct) (ps : Array (Name \u00d7 Expr)) : Struct :=\n  match s with\n  | \u27e8ref, structName, _, fields, source\u27e9 => \u27e8ref, structName, ps, fields, source\u27e9\n\nprivate def expandCompositeFields (s : Struct) : Struct :=\n  s.modifyFields fun fields => fields.map fun field => match field with\n    | { lhs := .fieldName _ (.str Name.anonymous ..) :: _, .. } => field\n    | { lhs := .fieldName ref n@(.str ..) :: rest, .. } =>\n      let newEntries := n.components.map <| FieldLHS.fieldName ref\n      { field with lhs := newEntries ++ rest }\n    | _ => field\n\nprivate def expandNumLitFields (s : Struct) : TermElabM Struct :=\n  s.modifyFieldsM fun fields => do\n    let env \u2190 getEnv\n    let fieldNames := getStructureFields env s.structName\n    fields.mapM fun field => match field with\n      | { lhs := .fieldIndex ref idx :: rest, .. } =>\n        if idx == 0 then throwErrorAt ref \"invalid field index, index must be greater than 0\"\n        else if idx > fieldNames.size then throwErrorAt ref \"invalid field index, structure has only #{fieldNames.size} fields\"\n        else return { field with lhs := .fieldName ref fieldNames[idx - 1]! :: rest }\n      | _ => return field\n\n/-- For example, consider the following structures:\n   ```\n   structure A where\n     x : Nat\n\n   structure B extends A where\n     y : Nat\n\n   structure C extends B where\n     z : Bool\n   ```\n   This method expands parent structure fields using the path to the parent structure.\n   For example,\n   ```\n   { x := 0, y := 0, z := true : C }\n   ```\n   is expanded into\n   ```\n   { toB.toA.x := 0, toB.y := 0, z := true : C }\n   ```\n-/\nprivate def expandParentFields (s : Struct) : TermElabM Struct := do\n  let env \u2190 getEnv\n  s.modifyFieldsM fun fields => fields.mapM fun field => do match field with\n    | { lhs := .fieldName ref fieldName :: _,    .. } =>\n      addCompletionInfo <| CompletionInfo.fieldId ref fieldName (\u2190 getLCtx) s.structName\n      match findField? env s.structName fieldName with\n      | none => throwErrorAt ref \"'{fieldName}' is not a field of structure '{s.structName}'\"\n      | some baseStructName =>\n        if baseStructName == s.structName then pure field\n        else match getPathToBaseStructure? env baseStructName s.structName with\n          | some path =>\n            let path := path.map fun funName => match funName with\n              | .str _ s => .fieldName ref (Name.mkSimple s)\n              | _        => unreachable!\n            return { field with lhs := path ++ field.lhs }\n          | _ => throwErrorAt ref \"failed to access field '{fieldName}' in parent structure\"\n    | _ => return field\n\nprivate abbrev FieldMap := HashMap Name Fields\n\nprivate def mkFieldMap (fields : Fields) : TermElabM FieldMap :=\n  fields.foldlM (init := {}) fun fieldMap field =>\n    match field.lhs with\n    | .fieldName _ fieldName :: _    =>\n      match fieldMap.find? fieldName with\n      | some (prevField::restFields) =>\n        if field.isSimple || prevField.isSimple then\n          throwErrorAt field.ref \"field '{fieldName}' has already been specified\"\n        else\n          return fieldMap.insert fieldName (field::prevField::restFields)\n      | _ => return fieldMap.insert fieldName [field]\n    | _ => unreachable!\n\nprivate def isSimpleField? : Fields \u2192 Option (Field Struct)\n  | [field] => if field.isSimple then some field else none\n  | _       => none\n\nprivate def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do\n  match fieldNames.findIdx? fun n => n == fieldName with\n  | some idx => return idx\n  | none     => throwError \"field '{fieldName}' is not a valid field of '{structName}'\"\n\ndef mkProjStx? (s : Syntax) (structName : Name) (fieldName : Name) : TermElabM (Option Syntax) := do\n  if (findField? (\u2190 getEnv) structName fieldName).isNone then\n    return none\n  return some <| mkNode ``Parser.Term.proj #[s, mkAtomFrom s \".\", mkIdentFrom s fieldName]\n\ndef findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) :=\n  fields.find? fun field =>\n    match field.lhs with\n    | [.fieldName _ n] => n == fieldName\n    | _                => false\n\nmutual\n\n  private partial def groupFields (s : Struct) : TermElabM Struct := do\n    let env \u2190 getEnv\n    withRef s.ref do\n    s.modifyFieldsM fun fields => do\n      let fieldMap \u2190 mkFieldMap fields\n      fieldMap.toList.mapM fun \u27e8fieldName, fields\u27e9 => do\n        match isSimpleField? fields with\n        | some field => pure field\n        | none =>\n          let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! }\n          let field := fields.head!\n          match Lean.isSubobjectField? env s.structName fieldName with\n          | some substructName =>\n            let substruct := Struct.mk s.ref substructName #[] substructFields s.source\n            let substruct \u2190 expandStruct substruct\n            pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct }\n          | none =>\n            let updateSource (structStx : Syntax) : TermElabM Syntax := do\n              let sourcesNew \u2190 s.source.explicit.filterMapM fun source => mkProjStx? source.stx source.structName fieldName\n              let explicitSourceStx := if sourcesNew.isEmpty then mkNullNode else mkSourcesWithSyntax sourcesNew\n              let implicitSourceStx := s.source.implicit.getD mkNullNode\n              return (structStx.setArg 1 explicitSourceStx).setArg 3 implicitSourceStx\n            let valStx := s.ref -- construct substructure syntax using s.ref as template\n            let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type\n            let args   := substructFields.toArray.map (\u00b7.toSyntax)\n            let valStx := valStx.setArg 2 (mkNullNode <| mkSepArray args (mkAtom \",\"))\n            let valStx \u2190 updateSource valStx\n            return { field with lhs := [field.lhs.head!], val := FieldVal.term valStx }\n\n  private partial def addMissingFields (s : Struct) : TermElabM Struct := do\n    let env \u2190 getEnv\n    let fieldNames := getStructureFields env s.structName\n    let ref := s.ref.mkSynthetic\n    withRef ref do\n      let fields \u2190 fieldNames.foldlM (init := []) fun fields fieldName => do\n        match findField? s.fields fieldName with\n        | some field => return field::fields\n        | none       =>\n          let addField (val : FieldVal Struct) : TermElabM Fields := do\n            return { ref, lhs := [FieldLHS.fieldName ref fieldName], val := val } :: fields\n          match Lean.isSubobjectField? env s.structName fieldName with\n          | some substructName =>\n            -- If one of the sources has the subobject field, use it\n            if let some val \u2190 s.source.explicit.findSomeM? fun source => mkProjStx? source.stx source.structName fieldName then\n              addField (FieldVal.term val)\n            else\n              let substruct := Struct.mk ref substructName #[] [] s.source\n              let substruct \u2190 expandStruct substruct\n              addField (FieldVal.nested substruct)\n          | none =>\n            if let some val \u2190 s.source.explicit.findSomeM? fun source => mkProjStx? source.stx source.structName fieldName then\n              addField (FieldVal.term val)\n            else if s.source.implicit.isSome then\n              addField (FieldVal.term (mkHole ref))\n            else\n              addField FieldVal.default\n      return s.setFields fields.reverse\n\n  private partial def expandStruct (s : Struct) : TermElabM Struct := do\n    let s := expandCompositeFields s\n    let s \u2190 expandNumLitFields s\n    let s \u2190 expandParentFields s\n    let s \u2190 groupFields s\n    addMissingFields s\n\nend\n\nstructure CtorHeaderResult where\n  ctorFn     : Expr\n  ctorFnType : Expr\n  instMVars  : Array MVarId\n  params     : Array (Name \u00d7 Expr)\n\nprivate def mkCtorHeaderAux : Nat \u2192 Expr \u2192 Expr \u2192 Array MVarId \u2192 Array (Name \u00d7 Expr) \u2192 TermElabM CtorHeaderResult\n  | 0,   type, ctorFn, instMVars, params => return { ctorFn , ctorFnType := type, instMVars, params }\n  | n+1, type, ctorFn, instMVars, params => do\n    match (\u2190 whnfForall type) with\n    | .forallE paramName d b c =>\n      match c with\n      | .instImplicit =>\n        let a \u2190 mkFreshExprMVar d .synthetic\n        mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!) (params.push (paramName, a))\n      | _ =>\n        let a \u2190 mkFreshExprMVar d\n        mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars (params.push (paramName, a))\n    | _ => throwError \"unexpected constructor type\"\n\nprivate partial def getForallBody : Nat \u2192 Expr \u2192 Option Expr\n  | i+1, .forallE _ _ b _ => getForallBody i b\n  | _+1, _                => none\n  | 0,   type             => type\n\nprivate def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit := do\n  match expectedType? with\n  | none              => return ()\n  | some expectedType =>\n    match getForallBody numFields type with\n      | none           => pure ()\n      | some typeBody =>\n        unless typeBody.hasLooseBVars do\n          discard <| isDefEq expectedType typeBody\n\nprivate def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do\n  let us \u2190 mkFreshLevelMVars ctorVal.levelParams.length\n  let val  := Lean.mkConst ctorVal.name us\n  let type \u2190 instantiateTypeLevelParams (ConstantInfo.ctorInfo ctorVal) us\n  let r \u2190 mkCtorHeaderAux ctorVal.numParams type val #[] #[]\n  propagateExpectedType r.ctorFnType ctorVal.numFields expectedType?\n  synthesizeAppInstMVars r.instMVars r.ctorFn\n  return r\n\ndef markDefaultMissing (e : Expr) : Expr :=\n  mkAnnotation `structInstDefault e\n\ndef defaultMissing? (e : Expr) : Option Expr :=\n  annotation? `structInstDefault e\n\ndef throwFailedToElabField {\u03b1} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM \u03b1 :=\n  throwError \"failed to elaborate field '{fieldName}' of '{structName}, {msgData}\"\n\ndef trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do\n  if !s.allDefault then\n    return none\n  else\n    try synthInstance? expectedType catch _ => return none\n\nstructure ElabStructResult where\n  val       : Expr\n  struct    : Struct\n  instMVars : Array MVarId\n\nprivate partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM ElabStructResult := withRef s.ref do\n  let env \u2190 getEnv\n  let ctorVal := getStructureCtor env s.structName\n  if isPrivateNameFromImportedModule env ctorVal.name then\n    throwError \"invalid \\{...} notation, constructor for `{s.structName}` is marked as private\"\n  -- We store the parameters at the resulting `Struct`. We use this information during default value propagation.\n  let { ctorFn, ctorFnType, params, .. } \u2190 mkCtorHeader ctorVal expectedType?\n  let (e, _, fields, instMVars) \u2190 s.fields.foldlM (init := (ctorFn, ctorFnType, [], #[])) fun (e, type, fields, instMVars) field => do\n    match field.lhs with\n    | [.fieldName ref fieldName] =>\n      let type \u2190 whnfForall type\n      trace[Elab.struct] \"elabStruct {field}, {type}\"\n      match type with\n      | .forallE _ d b bi =>\n        let cont (val : Expr) (field : Field Struct) (instMVars := instMVars) : TermElabM (Expr \u00d7 Expr \u00d7 Fields \u00d7 Array MVarId) := do\n          pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo {\n            projName := s.structName.append fieldName, fieldName, lctx := (\u2190 getLCtx), val, stx := ref }\n          let e     := mkApp e val\n          let type  := b.instantiate1 val\n          let field := { field with expr? := some val }\n          return (e, type, field::fields, instMVars)\n        match field.val with\n        | .term stx => cont (\u2190 elabTermEnsuringType stx d.consumeTypeAnnotations) field\n        | .nested s =>\n          -- if all fields of `s` are marked as `default`, then try to synthesize instance\n          match (\u2190 trySynthStructInstance? s d) with\n          | some val => cont val { field with val := FieldVal.term (mkHole field.ref) }\n          | none     =>\n            let { val, struct := sNew, instMVars := instMVarsNew } \u2190 elabStruct s (some d)\n            let val \u2190 ensureHasType d val\n            cont val { field with val := FieldVal.nested sNew } (instMVars ++ instMVarsNew)\n        | .default  =>\n          match d.getAutoParamTactic? with\n          | some (.const tacticDecl ..) =>\n            match evalSyntaxConstant env (\u2190 getOptions) tacticDecl with\n            | .error err       => throwError err\n            | .ok tacticSyntax =>\n              let stx \u2190 `(by $tacticSyntax)\n              cont (\u2190 elabTermEnsuringType stx (d.getArg! 0).consumeTypeAnnotations) field\n          | _ =>\n            if bi == .instImplicit then\n              let val \u2190 withRef field.ref <| mkFreshExprMVar d .synthetic\n              cont val field (instMVars.push val.mvarId!)\n            else\n              let val \u2190 withRef field.ref <| mkFreshExprMVar (some d)\n              cont (markDefaultMissing val) field\n      | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!\"unexpected constructor type{indentExpr type}\"\n    | _ => throwErrorAt field.ref \"unexpected unexpanded structure field\"\n  return { val := e, struct := s.setFields fields.reverse |>.setParams params, instMVars }\n\nnamespace DefaultFields\n\nstructure Context where\n  -- We must search for default values overriden in derived structures\n  structs : Array Struct := #[]\n  allStructNames : Array Name := #[]\n  /--\n  Consider the following example:\n  ```\n  structure A where\n    x : Nat := 1\n\n  structure B extends A where\n    y : Nat := x + 1\n    x := y + 1\n\n  structure C extends B where\n    z : Nat := 2*y\n    x := z + 3\n  ```\n  And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`.\n  We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2.\n  The field `maxDistance` specifies the maximum distance considered in a round of Default field computation.\n  Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0.\n\n  The fixpoint for setting default values works in the following way.\n  - Keep computing default values using `maxDistance == 0`.\n  - We increase `maxDistance` whenever we failed to compute a new default value in a round.\n  - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value.\n    We use depth-first search.\n  - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above).\n  -/\n  maxDistance : Nat := 0\n\nstructure State where\n  progress : Bool := false\n\npartial def collectStructNames (struct : Struct) (names : Array Name) : Array Name :=\n  let names := names.push struct.structName\n  struct.fields.foldl (init := names) fun names field =>\n    match field.val with\n    | .nested struct => collectStructNames struct names\n    | _ => names\n\npartial def getHierarchyDepth (struct : Struct) : Nat :=\n  struct.fields.foldl (init := 0) fun max field =>\n    match field.val with\n    | .nested struct => Nat.max max (getHierarchyDepth struct + 1)\n    | _ => max\n\ndef isDefaultMissing? [Monad m] [MonadMCtx m] (field : Field Struct) : m Bool := do\n  if let some expr := field.expr? then\n    if let some (.mvar mvarId) := defaultMissing? expr then\n      unless (\u2190 mvarId.isAssigned) do\n        return true\n  return false\n\npartial def findDefaultMissing? [Monad m] [MonadMCtx m] (struct : Struct) : m (Option (Field Struct)) :=\n  struct.fields.findSomeM? fun field => do\n   match field.val with\n   | .nested struct => findDefaultMissing? struct\n   | _ => return if (\u2190 isDefaultMissing? field) then field else none\n\npartial def allDefaultMissing [Monad m] [MonadMCtx m] (struct : Struct) : m (Array (Field Struct)) :=\n  go struct *> get |>.run' #[]\nwhere\n  go (struct : Struct) : StateT (Array (Field Struct)) m Unit :=\n    for field in struct.fields do\n      if let .nested struct := field.val then\n        go struct\n      else if (\u2190 isDefaultMissing? field) then\n        modify (\u00b7.push field)\n\ndef getFieldName (field : Field Struct) : Name :=\n  match field.lhs with\n  | [.fieldName _ fieldName] => fieldName\n  | _ => unreachable!\n\nabbrev M := ReaderT Context (StateRefT State TermElabM)\n\ndef isRoundDone : M Bool := do\n  return (\u2190 get).progress && (\u2190 read).maxDistance > 0\n\ndef getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr :=\n  struct.fields.findSome? fun field =>\n    if getFieldName field == fieldName then\n      field.expr?\n    else\n      none\n\npartial def mkDefaultValueAux? (struct : Struct) : Expr \u2192 TermElabM (Option Expr)\n  | .lam n d b c => withRef struct.ref do\n    if c.isExplicit then\n      let fieldName := n\n      match getFieldValue? struct fieldName with\n      | none     => return none\n      | some val =>\n        let valType \u2190 inferType val\n        if (\u2190 isDefEq valType d) then\n          mkDefaultValueAux? struct (b.instantiate1 val)\n        else\n          return none\n    else\n      if let some (_, param) := struct.params.find? fun (paramName, _) => paramName == n then\n        -- Recall that we did not use to have support for parameter propagation here.\n        if (\u2190 isDefEq (\u2190 inferType param) d) then\n          mkDefaultValueAux? struct (b.instantiate1 param)\n        else\n          return none\n      else\n        let arg \u2190 mkFreshExprMVar d\n        mkDefaultValueAux? struct (b.instantiate1 arg)\n  | e =>\n    if e.isAppOfArity ``id 2 then\n      return some e.appArg!\n    else\n      return some e\n\ndef mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) :=\n  withRef struct.ref do\n  let us \u2190 mkFreshLevelMVarsFor cinfo\n  mkDefaultValueAux? struct (\u2190 instantiateValueLevelParams cinfo us)\n\n/-- Reduce default value. It performs beta reduction and projections of the given structures. -/\npartial def reduce (structNames : Array Name) (e : Expr) : MetaM Expr := do\n  match e with\n  | .lam ..       => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (\u2190 reduce structNames b)\n  | .forallE ..   => forallTelescope e fun xs b => do mkForallFVars xs (\u2190 reduce structNames b)\n  | .letE ..      => lambdaLetTelescope e fun xs b => do mkLetFVars xs (\u2190 reduce structNames b)\n  | .proj _ i b   =>\n    match (\u2190 Meta.project? b i) with\n    | some r => reduce structNames r\n    | none   => return e.updateProj! (\u2190 reduce structNames b)\n  | .app f .. =>\n    match (\u2190 reduceProjOf? e structNames.contains) with\n    | some r => reduce structNames r\n    | none   =>\n      let f := f.getAppFn\n      let f' \u2190 reduce structNames f\n      if f'.isLambda then\n        let revArgs := e.getAppRevArgs\n        reduce structNames (f'.betaRev revArgs)\n      else\n        let args \u2190 e.getAppArgs.mapM (reduce structNames)\n        return mkAppN f' args\n  | .mdata _ b =>\n    let b \u2190 reduce structNames b\n    if (defaultMissing? e).isSome && !b.isMVar then\n      return b\n    else\n      return e.updateMData! b\n  | .mvar mvarId =>\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => if val.isMVar then pure val else reduce structNames val\n    | none     => return e\n  | e => return e\n\npartial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool :=\n  let rec loop (i : Nat) (dist : Nat) := do\n    if dist > maxDistance then\n      return false\n    else if h : i < structs.size then\n      let struct := structs.get \u27e8i, h\u27e9\n      match getDefaultFnForField? (\u2190 getEnv) struct.structName fieldName with\n      | some defFn =>\n        let cinfo \u2190 getConstInfo defFn\n        let mctx \u2190 getMCtx\n        match (\u2190 mkDefaultValue? struct cinfo) with\n        | none     => setMCtx mctx; loop (i+1) (dist+1)\n        | some val =>\n          let val \u2190 reduce allStructNames val\n          match val.find? fun e => (defaultMissing? e).isSome with\n          | some _ => setMCtx mctx; loop (i+1) (dist+1)\n          | none   =>\n            let mvarDecl \u2190 getMVarDecl mvarId\n            let val \u2190 ensureHasType mvarDecl.type val\n            mvarId.assign val\n            return true\n      | _ => loop (i+1) dist\n    else\n      return false\n  loop 0 0\n\npartial def step (struct : Struct) : M Unit :=\n  unless (\u2190 isRoundDone) do\n    withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do\n      for field in struct.fields do\n        match field.val with\n        | .nested struct => step struct\n        | _ => match field.expr? with\n          | none      => unreachable!\n          | some expr =>\n            match defaultMissing? expr with\n            | some (.mvar mvarId) =>\n              unless (\u2190 mvarId.isAssigned) do\n                let ctx \u2190 read\n                if (\u2190 withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then\n                  modify fun _ => { progress := true }\n            | _ => pure ()\n\npartial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do\n  match (\u2190 findDefaultMissing? struct) with\n  | none       => return () -- Done\n  | some field =>\n    trace[Elab.struct] \"propagate [{d}] [field := {field}]: {struct}\"\n    if d > hierarchyDepth then\n      let missingFields := (\u2190 allDefaultMissing struct).map getFieldName\n      let missingFieldsWithoutDefault :=\n        let env := (\u2190 getEnv)\n        let structs := (\u2190 read).allStructNames\n        missingFields.filter fun fieldName => structs.all fun struct =>\n          (getDefaultFnForField? env struct fieldName).isNone\n      let fieldsToReport :=\n        if missingFieldsWithoutDefault.isEmpty then missingFields else missingFieldsWithoutDefault\n      throwErrorAt field.ref \"fields missing: {fieldsToReport.toList.map (s!\"'{\u00b7}'\") |> \", \".intercalate}\"\n    else withReader (fun ctx => { ctx with maxDistance := d }) do\n      modify fun _ => { progress := false }\n      step struct\n      if (\u2190 get).progress then\n        propagateLoop hierarchyDepth 0 struct\n      else\n        propagateLoop hierarchyDepth (d+1) struct\n\ndef propagate (struct : Struct) : TermElabM Unit :=\n  let hierarchyDepth := getHierarchyDepth struct\n  let structNames := collectStructNames struct #[]\n  propagateLoop hierarchyDepth 0 struct { allStructNames := structNames } |>.run' {}\n\nend DefaultFields\n\nprivate def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do\n  let structName \u2190 getStructName expectedType? source\n  let struct \u2190 liftMacroM <| mkStructView stx structName source\n  let struct \u2190 expandStruct struct\n  trace[Elab.struct] \"{struct}\"\n  /- We try to synthesize pending problems with `withSynthesize` combinator before trying to use default values.\n     This is important in examples such as\n      ```\n      structure MyStruct where\n          {\u03b1 : Type u}\n          {\u03b2 : Type v}\n          a : \u03b1\n          b : \u03b2\n\n      #check { a := 10, b := true : MyStruct }\n      ```\n     were the `\u03b1` will remain \"unknown\" until the default instance for `OfNat` is used to ensure that `10` is a `Nat`.\n\n     TODO: investigate whether this design decision may have unintended side effects or produce confusing behavior.\n  -/\n  let { val := r, struct, instMVars } \u2190 withSynthesize (mayPostpone := true) <| elabStruct struct expectedType?\n  trace[Elab.struct] \"before propagate {r}\"\n  DefaultFields.propagate struct\n  synthesizeAppInstMVars instMVars r\n  return r\n\n@[builtin_term_elab structInst] def elabStructInst : TermElab := fun stx expectedType? => do\n  match (\u2190 expandNonAtomicExplicitSources stx) with\n  | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | none =>\n    let sourceView \u2190 getStructSource stx\n    if let some modifyOp \u2190 isModifyOp? stx then\n      if sourceView.explicit.isEmpty then\n        throwError \"invalid \\{...} notation, explicit source is required when using '[<index>] := <value>'\"\n      elabModifyOp stx modifyOp sourceView.explicit expectedType?\n    else\n      elabStructInstAux stx expectedType? sourceView\n\nbuiltin_initialize registerTraceClass `Elab.struct\n\nend Lean.Elab.Term.StructInst\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/StructInst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271168, "lm_q2_score": 0.05184546463539375, "lm_q1q2_score": 0.012409178122124226}}
{"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, David Renshaw\n-/\nimport Lean\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 \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\ntheorem alias1 : <type of my_theorem> := my_theorem\n\n/-- doc string -/\ntheorem alias2 : <type of my_theorem> := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B \u2194 B_of_A A_of_B\nalias A_iff_B \u2194 ..\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\nnamespace Tactic\nnamespace Alias\n\nopen Lean Elab Parser.Command\n\n/-- Adds some copies of a theorem or definition. -/\nsyntax (name := alias) (docComment)? \"alias \" ident \" \u2190 \" ident* : command\n\n/-- Adds one-way implication declarations. -/\nsyntax (name := aliasLR) (docComment)? \"alias \" ident \" \u2194 \" binderIdent binderIdent : command\n\n/-- Adds one-way implication declarations, inferring names for them. -/\nsyntax (name := aliasLRDots) (docComment)? \"alias \" ident \" \u2194 \" \"..\" : command\n\n/-- Like `++`, except that if the right argument starts with `_root_` the namespace will be\nignored.\n```\nappendNamespace `a.b `c.d = `a.b.c.d\nappendNamespace `a.b `_root_.c.d = `c.d\n```\n\nTODO: Move this declaration to a more central location.\n-/\ndef appendNamespace (ns : Name) : Name \u2192 Name\n| .str .anonymous s => if s = \"_root_\" then Name.anonymous else Name.mkStr ns s\n| .str p s          => Name.mkStr (appendNamespace ns p) s\n| .num p n          => Name.mkNum (appendNamespace ns p) n\n| .anonymous        => ns\n\n/-- An alias can be in one of three forms -/\ninductive Target\n| plain : Name \u2192 Target\n| forward : Name \u2192 Target\n| backwards : Name \u2192 Target\n\n/-- The name underlying an alias target -/\ndef Target.toName : Target \u2192 Name\n| Target.plain n => n\n| Target.forward n => n\n| Target.backwards n => n\n\n/-- The docstring for an alias. -/\ndef Target.toString : Target \u2192 String\n| Target.plain n => s!\"**Alias** of `{n}`.\"\n| Target.forward n => s!\"**Alias** of the forward direction of `{n}`.\"\n| Target.backwards n => s!\"**Alias** of the reverse direction of `{n}`.\"\n\n/-- Elaborates an `alias \u2190` command. -/\n@[command_elab \u00abalias\u00bb] def elabAlias : Command.CommandElab\n| `($[$doc]? alias $name:ident \u2190 $aliases:ident*) => do\n  let resolved \u2190 resolveGlobalConstNoOverloadWithInfo name\n  let constant \u2190 getConstInfo resolved\n  let ns \u2190 getCurrNamespace\n  for a in aliases do withRef a do\n    let declName := appendNamespace ns a.getId\n    let decl \u2190 match constant with\n    | Lean.ConstantInfo.defnInfo d =>\n      pure $ .defnDecl {\n        d with name := declName\n               value := mkConst resolved (d.levelParams.map mkLevelParam)\n      }\n    | Lean.ConstantInfo.thmInfo t =>\n      pure $ .thmDecl {\n        t with name := declName\n               value := mkConst resolved (t.levelParams.map mkLevelParam)\n      }\n    | _ => throwError \"alias only works with def or theorem\"\n    checkNotAlreadyDeclared declName\n    addDeclarationRanges declName {\n      range := \u2190 getDeclarationRange (\u2190 getRef)\n      selectionRange := \u2190 getDeclarationRange a\n    }\n    -- TODO add @alias attribute\n    Command.liftTermElabM do\n      Lean.addDecl decl\n      Term.addTermInfo' a (\u2190 mkConstWithLevelParams declName) (isBinder := true)\n      let target := Target.plain resolved\n      let docString := match doc with | none => target.toString\n                                      | some d => d.getDocString\n      addDocString declName docString\n| _ => throwUnsupportedSyntax\n\n/--\n  Given a possibly forall-quantified iff expression `prf`, produce a value for one\n  of the implication directions (determined by `mp`).\n-/\ndef mkIffMpApp (mp : Bool) (ty prf : Expr) : MetaM Expr := do\n  Meta.forallTelescope ty fun xs ty \u21a6 do\n    let some (lhs, rhs) := ty.iff?\n      | throwError \"Target theorem must have the form `\u2200 x y z, a \u2194 b`\"\n    Meta.mkLambdaFVars xs <|\n      mkApp3 (mkConst (if mp then ``Iff.mp else ``Iff.mpr)) lhs rhs (mkAppN prf xs)\n\n/--\n  Given a constant representing an iff decl, adds a decl for one of the implication\n  directions.\n-/\ndef aliasIff (doc : Option (TSyntax `Lean.Parser.Command.docComment)) (ci : ConstantInfo)\n  (ref : Syntax) (al : Name) (isForward : Bool) :\n  TermElabM Unit := do\n  let ls := ci.levelParams\n  let v \u2190 mkIffMpApp isForward ci.type ci.value!\n  let t' \u2190 Meta.inferType v\n  -- TODO add @alias attribute\n  addDeclarationRanges al {\n    range := \u2190 getDeclarationRange (\u2190 getRef)\n    selectionRange := \u2190 getDeclarationRange ref\n  }\n  addDecl $ .thmDecl {\n    name := al\n    value := v\n    type := t'\n    levelParams := ls\n  }\n  Term.addTermInfo' ref (\u2190 mkConstWithLevelParams al) (isBinder := true)\n  let target := if isForward then Target.forward ci.name else Target.backwards ci.name\n  let docString := match doc with | none => target.toString\n                                  | some d => d.getDocString\n  addDocString al docString\n\n/-- Elaborates an `alias \u2194` command. -/\n@[command_elab aliasLR] def elabAliasLR : Command.CommandElab\n| `($[$doc]? alias $name:ident \u2194 $left:binderIdent $right:binderIdent) => do\n  let resolved \u2190 resolveGlobalConstNoOverloadWithInfo name\n  let constant \u2190 getConstInfo resolved\n  let ns \u2190 getCurrNamespace\n  Command.liftTermElabM do\n    if let `(binderIdent| $x:ident) := left then\n      aliasIff doc constant x (appendNamespace ns x.getId) true\n    if let `(binderIdent| $x:ident) := right then\n      aliasIff doc constant x (appendNamespace ns x.getId) false\n| _ => throwUnsupportedSyntax\n\n/-- Elaborates an `alias \u2194 ..` command. -/\n@[command_elab aliasLRDots] def elabAliasLRDots : Command.CommandElab\n| `($[$doc]? alias $name:ident \u2194 ..%$tk) => do\n  let resolved \u2190 resolveGlobalConstNoOverloadWithInfo name\n  let constant \u2190 getConstInfo resolved\n  let (parent, base) \u2190 match resolved with\n    | .str n s => pure (n, s)\n    | _ => throwError \"alias only works for string names\"\n  let components := base.splitOn \"_iff_\"\n  if components.length != 2 then throwError \"LHS must be of the form *_iff_*\"\n  let forward := String.intercalate \"_of_\" components.reverse\n  let backward := String.intercalate \"_of_\" components\n  let forwardName := Name.mkStr parent forward\n  let backwardName := Name.mkStr parent backward\n  Command.liftTermElabM do\n    aliasIff doc constant tk forwardName true\n    aliasIff doc constant tk backwardName false\n| _ => throwUnsupportedSyntax\n\nend Alias\nend Tactic\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/Alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946968133032526, "lm_q2_score": 0.05921025406152681, "lm_q1q2_score": 0.012402753049755617}}
{"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 {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0]\n\nvariables {A\u2081\u2081 A\u2081\u2082 A\u2081\u2083 A\u2081\u2084 A\u2081\u2085 : \ud835\udcd0}\nvariables {A\u2082\u2081 A\u2082\u2082 A\u2082\u2083 A\u2082\u2084 A\u2082\u2085 : \ud835\udcd0}\nvariables {A\u2083\u2081 A\u2083\u2082 A\u2083\u2083 A\u2083\u2084 A\u2083\u2085 : \ud835\udcd0}\nvariables {A\u2084\u2081 A\u2084\u2082 A\u2084\u2083 A\u2084\u2084 A\u2084\u2085 : \ud835\udcd0}\nvariables {A\u2085\u2081 A\u2085\u2082 A\u2085\u2083 A\u2085\u2084 A\u2085\u2085 : \ud835\udcd0}\n\nvariables {f\u2081\u2081 : A\u2081\u2081 \u27f6 A\u2081\u2082} {f\u2081\u2082 : A\u2081\u2082 \u27f6 A\u2081\u2083} {f\u2081\u2083 : A\u2081\u2083 \u27f6 A\u2081\u2084} {f\u2081\u2084 : A\u2081\u2084 \u27f6 A\u2081\u2085}\nvariables {g\u2081\u2081 : A\u2081\u2081 \u27f6 A\u2082\u2081} {g\u2081\u2082 : A\u2081\u2082 \u27f6 A\u2082\u2082} {g\u2081\u2083 : A\u2081\u2083 \u27f6 A\u2082\u2083} {g\u2081\u2084 : A\u2081\u2084 \u27f6 A\u2082\u2084} {g\u2081\u2085 : A\u2081\u2085 \u27f6 A\u2082\u2085}\nvariables {f\u2082\u2081 : A\u2082\u2081 \u27f6 A\u2082\u2082} {f\u2082\u2082 : A\u2082\u2082 \u27f6 A\u2082\u2083} {f\u2082\u2083 : A\u2082\u2083 \u27f6 A\u2082\u2084} {f\u2082\u2084 : A\u2082\u2084 \u27f6 A\u2082\u2085}\nvariables {g\u2082\u2081 : A\u2082\u2081 \u27f6 A\u2083\u2081} {g\u2082\u2082 : A\u2082\u2082 \u27f6 A\u2083\u2082} {g\u2082\u2083 : A\u2082\u2083 \u27f6 A\u2083\u2083} {g\u2082\u2084 : A\u2082\u2084 \u27f6 A\u2083\u2084} {g\u2082\u2085 : A\u2082\u2085 \u27f6 A\u2083\u2085}\nvariables {f\u2083\u2081 : A\u2083\u2081 \u27f6 A\u2083\u2082} {f\u2083\u2082 : A\u2083\u2082 \u27f6 A\u2083\u2083} {f\u2083\u2083 : A\u2083\u2083 \u27f6 A\u2083\u2084} {f\u2083\u2084 : A\u2083\u2084 \u27f6 A\u2083\u2085}\nvariables {g\u2083\u2081 : A\u2083\u2081 \u27f6 A\u2084\u2081} {g\u2083\u2082 : A\u2083\u2082 \u27f6 A\u2084\u2082} {g\u2083\u2083 : A\u2083\u2083 \u27f6 A\u2084\u2083} {g\u2083\u2084 : A\u2083\u2084 \u27f6 A\u2084\u2084} {g\u2083\u2085 : A\u2083\u2085 \u27f6 A\u2084\u2085}\nvariables {f\u2084\u2081 : A\u2084\u2081 \u27f6 A\u2084\u2082} {f\u2084\u2082 : A\u2084\u2082 \u27f6 A\u2084\u2083} {f\u2084\u2083 : A\u2084\u2083 \u27f6 A\u2084\u2084} {f\u2084\u2084 : A\u2084\u2084 \u27f6 A\u2084\u2085}\nvariables {g\u2084\u2081 : A\u2084\u2081 \u27f6 A\u2085\u2081} {g\u2084\u2082 : A\u2084\u2082 \u27f6 A\u2085\u2082} {g\u2084\u2083 : A\u2084\u2083 \u27f6 A\u2085\u2083} {g\u2084\u2084 : A\u2084\u2084 \u27f6 A\u2085\u2084} {g\u2084\u2085 : A\u2084\u2085 \u27f6 A\u2085\u2085}\nvariables {f\u2085\u2081 : A\u2085\u2081 \u27f6 A\u2085\u2082} {f\u2085\u2082 : A\u2085\u2082 \u27f6 A\u2085\u2083} {f\u2085\u2083 : A\u2085\u2083 \u27f6 A\u2085\u2084} {f\u2085\u2084 : A\u2085\u2084 \u27f6 A\u2085\u2085}\n\nsection\n\nvariables (f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081)\n\n/-- A *commutative square* is a commutative diagram of the following shape:\n```\nA\u2081\u2081 --- f\u2081\u2081 --> A\u2081\u2082\n |               |\ng\u2081\u2081             g\u2081\u2082\n |               |\n v               v\nA\u2082\u2081 --- f\u2082\u2081 --> A\u2082\u2082\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 : \ud835\udcd0)\n(\u03b9 : A\u2081\u2081 \u27f6 S)\n(\u03c0 : S \u27f6 A\u2082\u2082)\n(diag : A\u2081\u2081 \u27f6 A\u2082\u2082)\n(sum : sum_str A\u2081\u2082 A\u2082\u2081 S)\n(\u03b9_fst : \u03b9 \u226b sum.fst = f\u2081\u2081)\n(\u03b9_snd : \u03b9 \u226b sum.snd = g\u2081\u2081)\n(inl_\u03c0 : sum.inl \u226b \u03c0 = g\u2081\u2082)\n(inr_\u03c0 : sum.inr \u226b \u03c0 = f\u2082\u2081)\n(tr\u2081 : g\u2081\u2081 \u226b f\u2082\u2081 = diag)\n(tr\u2082 : f\u2081\u2081 \u226b g\u2081\u2082 = diag)\n\nend\n\nnamespace commsq\n\nattribute [simp, reassoc] \u03b9_fst \u03b9_snd inl_\u03c0 inr_\u03c0\n\n@[reassoc] lemma w (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) : f\u2081\u2081 \u226b g\u2081\u2082 = g\u2081\u2081 \u226b f\u2082\u2081 :=\nby rw [sq.tr\u2081, sq.tr\u2082]\n\n@[reassoc] lemma w_inv [is_iso g\u2081\u2081] [is_iso g\u2081\u2082] (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  inv g\u2081\u2081 \u226b f\u2081\u2081 = f\u2082\u2081 \u226b inv g\u2081\u2082 :=\nby rw [is_iso.eq_comp_inv, category.assoc, sq.w, is_iso.inv_hom_id_assoc]\n\ndef of_eq (w : f\u2081\u2081 \u226b g\u2081\u2082 = g\u2081\u2081 \u226b f\u2082\u2081) : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081 :=\n{ S := A\u2081\u2082 \u229e A\u2082\u2081,\n  \u03b9 := biprod.lift f\u2081\u2081 g\u2081\u2081,\n  \u03c0 := biprod.desc g\u2081\u2082 f\u2082\u2081,\n  diag := g\u2081\u2081 \u226b f\u2082\u2081,\n  sum := sum_str.biprod _ _,\n  \u03b9_fst := biprod.lift_fst _ _,\n  \u03b9_snd := biprod.lift_snd _ _,\n  inl_\u03c0 := biprod.inl_desc _ _,\n  inr_\u03c0 := biprod.inr_desc _ _,\n  tr\u2081 := rfl,\n  tr\u2082 := w }\n\ndef symm (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) : commsq g\u2081\u2081 f\u2081\u2081 f\u2082\u2081 g\u2081\u2082 :=\n{ sum := sq.sum.symm,\n  \u03b9_fst := sq.\u03b9_snd,\n  \u03b9_snd := sq.\u03b9_fst,\n  inl_\u03c0 := sq.inr_\u03c0,\n  inr_\u03c0 := sq.inl_\u03c0,\n  tr\u2081 := sq.tr\u2082,\n  tr\u2082 := sq.tr\u2081,\n  .. sq }\n\nlemma \u03b9_eq (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq.\u03b9 = f\u2081\u2081 \u226b sq.sum.inl + g\u2081\u2081 \u226b sq.sum.inr :=\nbegin\n  rw [\u2190 cancel_mono (\ud835\udfd9 sq.S), \u2190 sq.sum.total],\n  simp only [preadditive.add_comp, category.assoc, \u03b9_fst_assoc, \u03b9_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 \u03c0_eq (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq.\u03c0 = sq.sum.fst \u226b g\u2081\u2082 + sq.sum.snd \u226b f\u2082\u2081 :=\nbegin\n  rw [\u2190 cancel_epi (\ud835\udfd9 sq.S), \u2190 sq.sum.total],\n  simp only [preadditive.add_comp, category.assoc, inl_\u03c0, inr_\u03c0, 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 \u03b9_iso_hom (sq\u2081 sq\u2082 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq\u2081.\u03b9 \u226b (sq\u2081.sum.iso sq\u2082.sum).hom = sq\u2082.\u03b9 :=\nbegin\n  simp only [sum_str.iso_hom, comp_add, \u03b9_fst_assoc, \u03b9_snd_assoc],\n  simp only [\u2190 sq\u2082.\u03b9_fst_assoc, \u2190 sq\u2082.\u03b9_snd_assoc, \u2190 comp_add, sum_str.total, category.comp_id],\nend\n\nlemma iso_hom_\u03c0 (sq\u2081 sq\u2082 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  (sq\u2081.sum.iso sq\u2082.sum).hom \u226b sq\u2082.\u03c0 = sq\u2081.\u03c0 :=\nbegin\n  simp only [sum_str.iso_hom, add_comp, category.assoc, inl_\u03c0, inr_\u03c0],\n  simp only [\u2190 sq\u2081.inl_\u03c0, \u2190 sq\u2081.inr_\u03c0],\n  simp only [\u2190 category.assoc, \u2190 add_comp, sum_str.total, category.id_comp],\nend\n\nlemma \u03b9_iso_inv (sq\u2081 sq\u2082 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq\u2082.\u03b9 \u226b (sq\u2081.sum.iso sq\u2082.sum).inv = sq\u2081.\u03b9 :=\n\u03b9_iso_hom _ _\n\nlemma iso_inv_\u03c0 (sq\u2081 sq\u2082 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  (sq\u2081.sum.iso sq\u2082.sum).inv \u226b sq\u2081.\u03c0 = sq\u2082.\u03c0 :=\niso_hom_\u03c0 _ _\n\nend iso\n\nlemma of_iso (e\u2081\u2081 : A\u2081\u2081 \u2245 A\u2083\u2083) (e\u2081\u2082 : A\u2081\u2082 \u2245 A\u2083\u2084) (e\u2082\u2081 : A\u2082\u2081 \u2245 A\u2084\u2083) (e\u2082\u2082 : A\u2082\u2082 \u2245 A\u2084\u2084)\n  (sqa : commsq f\u2081\u2081 e\u2081\u2081.hom e\u2081\u2082.hom f\u2083\u2083) (sqb : commsq g\u2081\u2081 e\u2081\u2081.hom e\u2082\u2081.hom g\u2083\u2083)\n  (sqc : commsq g\u2081\u2082 e\u2081\u2082.hom e\u2082\u2082.hom g\u2083\u2084) (sqd : commsq f\u2082\u2081 e\u2082\u2081.hom e\u2082\u2082.hom f\u2084\u2083)\n  (sq1 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  commsq f\u2083\u2083 g\u2083\u2083 g\u2083\u2084 f\u2084\u2083 :=\nof_eq $ by rw [\u2190 cancel_epi e\u2081\u2081.hom, \u2190 sqa.w_assoc, \u2190 sqc.w, \u2190 sqb.w_assoc, \u2190 sqd.w, sq1.w_assoc]\n\ndef kernel (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  commsq (kernel.\u03b9 f\u2081\u2081) (kernel.map _ _ _ _ sq.w) g\u2081\u2081 (kernel.\u03b9 f\u2082\u2081) :=\ncommsq.of_eq $ by simp only [kernel.lift_\u03b9]\n\ndef cokernel (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  commsq (cokernel.\u03c0 f\u2081\u2081) g\u2081\u2082 (cokernel.map _ _ _ _ sq.w) (cokernel.\u03c0 f\u2082\u2081) :=\ncommsq.of_eq $ by simp only [cokernel.\u03c0_desc]\n\ndef bicartesian (sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) : Prop :=\nshort_exact (-f\u2081\u2081 \u226b sq.sum.inl + g\u2081\u2081 \u226b sq.sum.inr) sq.\u03c0\n\ndef bicartesian.is_limit {sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081} (h : sq.bicartesian) :\n  is_limit (pullback_cone.mk f\u2081\u2081 g\u2081\u2081 sq.w) :=\npullback_cone.is_limit.mk sq.w\n  (\u03bb s, (@abelian.is_limit_of_exact_of_mono _ _ _ _ _ _ _ _ h.mono h.exact).lift\n      (fork.of_\u03b9 (-s.fst \u226b sq.sum.inl + s.snd \u226b sq.sum.inr)\n        (by simp only [s.condition, preadditive.add_comp, preadditive.neg_comp, category.assoc,\n          inl_\u03c0, inr_\u03c0, add_left_neg, comp_zero])))\n  (\u03bb s,\n  begin\n    have : f\u2081\u2081 = -((-f\u2081\u2081 \u226b sq.sum.inl + g\u2081\u2081 \u226b sq.sum.inr) \u226b 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, \u2190 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_\u03b9_\u03c0_app, sum_str.inl_fst, category.comp_id, sum_str.inr_fst, add_zero, neg_neg],\n  end)\n  (\u03bb s,\n  begin\n    have : g\u2081\u2081 = (-f\u2081\u2081 \u226b sq.sum.inl + g\u2081\u2081 \u226b sq.sum.inr) \u226b 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 \u2190 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_\u03b9_\u03c0_app, sum_str.inl_snd, neg_zero, sum_str.inr_snd, category.comp_id, zero_add],\n  end)\n  (\u03bb s m h\u2081 h\u2082,\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\u2081, reassoc_of h\u2082, kernel_fork.\u03b9_of_\u03b9, preadditive.comp_add,\n      preadditive.comp_neg, fork.of_\u03b9_\u03c0_app],\n  end)\n\ndef bicartesian.is_colimit {sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081} (h : sq.bicartesian) :\n  is_colimit (pushout_cocone.mk g\u2081\u2082 f\u2082\u2081 sq.w) :=\npushout_cocone.is_colimit.mk sq.w\n  (\u03bb s, (@abelian.is_colimit_of_exact_of_epi _ _ _ _ _ _ _ _ h.epi h.exact).desc\n    (cofork.of_\u03c0 (sq.sum.fst \u226b s.inl + sq.sum.snd \u226b 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  (\u03bb s,\n  begin\n    conv_lhs { congr, rw [\u2190 sq.inl_\u03c0] },\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_\u03c0_\u03b9_app, sum_str.inl_fst_assoc,\n      sum_str.inl_snd_assoc],\n  end)\n  (\u03bb s,\n  begin\n    conv_lhs { congr, rw [\u2190 sq.inr_\u03c0] },\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_\u03c0_\u03b9_app, sum_str.inr_fst_assoc,\n      sum_str.inr_snd_assoc]\n  end)\n  (\u03bb s m h\u2081 h\u2082,\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.\u03c0_of_\u03c0, cofork.of_\u03c0_\u03b9_app],\n    conv_lhs { congr, rw [\u2190 category.id_comp sq.\u03c0] },\n    rw [\u2190 sq.sum.total],\n    simp only [h\u2081, h\u2082, preadditive.add_comp, category.assoc, inl_\u03c0, inr_\u03c0]\n  end)\n\nlemma bicartesian.of_is_limit_of_is_colimt {sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081}\n  (hl : is_limit (pullback_cone.mk f\u2081\u2081 g\u2081\u2081 sq.w)) (hc : is_colimit (pushout_cocone.mk g\u2081\u2082 f\u2082\u2081 sq.w)) :\n  sq.bicartesian :=\nbegin\n  have h : (-f\u2081\u2081 \u226b sq.sum.inl + g\u2081\u2081 \u226b sq.sum.inr) \u226b sq.\u03c0 = 0,\n  { simp only [sq.w, preadditive.add_comp, preadditive.neg_comp, category.assoc, inl_\u03c0, inr_\u03c0,\n      add_left_neg] },\n  let hker : is_limit (kernel_fork.of_\u03b9 _ h),\n  { fapply kernel_fork.is_limit.of_\u03b9,\n    { refine \u03bb T g hg, hl.lift (pullback_cone.mk (-g \u226b sq.sum.fst) (g \u226b sq.sum.snd) _),\n      rw [sq.\u03c0_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, \u2190 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_\u03c0_app_left,\n        pullback_cone.mk_\u03c0_app_right, \u2190 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 [\u2190 hm, preadditive.neg_comp, category.assoc, neg_neg, pullback_cone.mk_\u03c0_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 [\u2190 hm, preadditive.neg_comp, category.assoc, pullback_cone.mk_\u03c0_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_\u03c0 _ h),\n  { fapply cokernel_cofork.is_colimit.of_\u03c0,\n    { refine \u03bb T g hg, hc.desc (pushout_cocone.mk (sq.sum.inl \u226b g) (sq.sum.inr \u226b 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.\u03c0_eq, preadditive.add_comp, category.assoc],\n      erw [hc.fac _ walking_cospan.left, hc.fac _ walking_cospan.right],\n      simp only [pushout_cocone.mk_\u03b9_app_left, pushout_cocone.mk_\u03b9_app_right, \u2190 category.assoc,\n        \u2190 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 [\u2190 hm, pushout_cocone.mk_\u03b9_app_left, inl_\u03c0_assoc] },\n      { erw [pushout_cocone.mk_inr, hc.fac _ walking_cospan.right],\n        simp only [\u2190hm, pushout_cocone.mk_\u03b9_app_right, inr_\u03c0_assoc] } } },\n  haveI : mono (-f\u2081\u2081 \u226b sq.sum.inl + g\u2081\u2081 \u226b sq.sum.inr) := mono_of_is_limit_fork hker,\n  haveI : epi sq.\u03c0 := epi_of_is_colimit_cofork hcoker,\n  exact \u27e8abelian.exact_of_is_kernel _ _ h hker\u27e9\nend\n\nopen category_theory.preadditive\n\nlemma bicartesian.congr {sq\u2081 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081}\n  (h : sq\u2081.bicartesian) (sq\u2082 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq\u2082.bicartesian :=\nbegin\n  have := h.mono, have := h.epi, resetI,\n  have hm : mono (-f\u2081\u2081 \u226b sq\u2082.sum.inl + g\u2081\u2081 \u226b sq\u2082.sum.inr),\n  { suffices : -f\u2081\u2081 \u226b sq\u2082.sum.inl + g\u2081\u2081 \u226b sq\u2082.sum.inr =\n      (-f\u2081\u2081 \u226b sq\u2081.sum.inl + g\u2081\u2081 \u226b sq\u2081.sum.inr) \u226b (sq\u2081.sum.iso sq\u2082.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\u2082.\u03c0, { rw [\u2190 sq\u2081.iso_inv_\u03c0 sq\u2082], apply epi_comp },\n  have H : exact (-f\u2081\u2081 \u226b sq\u2082.sum.inl + g\u2081\u2081 \u226b sq\u2082.sum.inr) sq\u2082.\u03c0,\n  { apply exact_of_iso_of_exact' _ _ _ _\n      (iso.refl _) (sq\u2081.sum.iso sq\u2082.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_\u03c0], }, },\n  exactI \u27e8H\u27e9\nend\n\nlemma bicartesian_iff (sq\u2081 sq\u2082 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq\u2081.bicartesian \u2194 sq\u2082.bicartesian :=\n\u27e8\u03bb h, h.congr _, \u03bb h, h.congr _\u27e9\n\n--move this (do we want this?)\ninstance {C : Type*} [category C] [preadditive C] {X Y : C} : has_neg (X \u2245 Y) :=\n\u27e8\u03bb e, \u27e8-e.hom, -e.inv, by simp, by simp\u27e9\u27e9\n\n@[simp] lemma neg_iso_hom {C : Type*} [category C] [preadditive C] {X Y : C} {e : X \u2245 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 \u2245 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\u2081\u2081 f\u2081\u2082) :\n  short_exact (-f\u2081\u2081) f\u2081\u2082 :=\nbegin\n  haveI := h.mono, haveI := h.epi,\n  refine \u27e8_\u27e9,\n  have : -f\u2081\u2081 = (-iso.refl _).hom \u226b f\u2081\u2081,\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\u2081\u2081) f\u2081\u2082 \u2194 short_exact f\u2081\u2081 f\u2081\u2082 :=\nbegin\n  refine \u27e8_, \u03bb h, h.neg_left\u27e9,\n  intro h, simpa only [neg_neg] using h.neg_left\nend\n\nlemma bicartesian.symm {sq : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081} (h : sq.bicartesian) :\n  sq.symm.bicartesian :=\nbegin\n  rw bicartesian at h \u22a2,\n  rw \u2190 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\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) :\n  sq.symm.bicartesian \u2194 sq.bicartesian :=\n\u27e8\u03bb h, h.symm, \u03bb h, h.symm\u27e9\n\nsection\nvariables (g\u2081\u2081 g\u2081\u2082 g\u2081\u2083)\n\n-- move me\nlemma short_exact.of_iso (h : short_exact f\u2081\u2081 f\u2081\u2082)\n  (sq1 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081) (sq2 : commsq f\u2081\u2082 g\u2081\u2082 g\u2081\u2083 f\u2082\u2082)\n  [is_iso g\u2081\u2081] [is_iso g\u2081\u2082] [is_iso g\u2081\u2083] :\n  short_exact f\u2082\u2081 f\u2082\u2082 :=\nbegin\n  have := h.mono, have := h.epi, resetI,\n  have : mono f\u2082\u2081,\n  { suffices : mono (f\u2082\u2081 \u226b inv g\u2081\u2082), { resetI, apply mono_of_mono f\u2082\u2081 (inv g\u2081\u2082), },\n    rw \u2190 sq1.w_inv, apply_instance },\n  have : epi f\u2082\u2082,\n  { suffices : epi (g\u2081\u2082 \u226b f\u2082\u2082), { resetI, apply epi_of_epi g\u2081\u2082 f\u2082\u2082 },\n    { rw \u2190 sq2.w, apply epi_comp } },\n  resetI, refine \u27e8_\u27e9,\n  apply exact_of_iso_of_exact' _ _ _ _ (as_iso g\u2081\u2081) (as_iso g\u2081\u2082) (as_iso g\u2081\u2083)\n    sq1.symm.w sq2.symm.w h.exact,\nend\n\nend\n\nlemma bicartesian.of_iso (e\u2081\u2081 : A\u2081\u2081 \u2245 A\u2083\u2083) (e\u2081\u2082 : A\u2081\u2082 \u2245 A\u2083\u2084) (e\u2082\u2081 : A\u2082\u2081 \u2245 A\u2084\u2083) (e\u2082\u2082 : A\u2082\u2082 \u2245 A\u2084\u2084)\n  {sq1 : commsq f\u2081\u2081 g\u2081\u2081 g\u2081\u2082 f\u2082\u2081} {sq2 : commsq f\u2083\u2083 g\u2083\u2083 g\u2083\u2084 f\u2084\u2083}\n  (sqa : commsq f\u2081\u2081 e\u2081\u2081.hom e\u2081\u2082.hom f\u2083\u2083) (sqb : commsq g\u2081\u2081 e\u2081\u2081.hom e\u2082\u2081.hom g\u2083\u2083)\n  (sqc : commsq g\u2081\u2082 e\u2081\u2082.hom e\u2082\u2082.hom g\u2083\u2084) (sqd : commsq f\u2082\u2081 e\u2082\u2081.hom e\u2082\u2082.hom f\u2084\u2083)\n  (h : sq1.bicartesian) :\n  sq2.bicartesian :=\nbegin\n  let e : sq1.S \u2245 sq2.S := _,\n  apply short_exact.of_iso e\u2081\u2081.hom e.hom e\u2082\u2082.hom h,\n  swap 3,\n  { refine \u27e8sq1.sum.fst \u226b e\u2081\u2082.hom \u226b sq2.sum.inl + sq1.sum.snd \u226b e\u2082\u2081.hom \u226b sq2.sum.inr,\n            sq2.sum.fst \u226b e\u2081\u2082.inv \u226b sq1.sum.inl + sq2.sum.snd \u226b e\u2082\u2081.inv \u226b sq1.sum.inr,\n            _, _\u27e9;\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_\u03c0, inr_\u03c0, \u2190 sqc.w, \u2190 sqd.w, sq1.\u03c0_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 : \u2115} {\u03c3 : Type} {\u03b9 : Type} {\u03c4 : \u03b9 \u2192 Type} [decidable_eq \u03b9]\n\n@[simp]\nlemma exec_skip {n} {ac : vector bool n} {s} : exec_state (kernel.compute id : kernel \u03c3 \u03c4) 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 \u03c3 \u03c4} {ac : vector bool n} {k} (h\u2081 : exec_state k ac s u) (h\u2082 : exec_state k ac s t) : t = u := begin\n  induction h\u2081 generalizing t,\n  case exec_state.load {\n    cases h\u2082, refl,\n  },\n  case exec_state.store {\n    cases h\u2082, refl,\n  },\n  case exec_state.compute {\n    cases h\u2082, refl,\n  },\n  case exec_state.sync_all {\n    cases h\u2082,\n    case parlang.exec_state.sync_all {\n      by_cases hl : 0 < n,\n      {\n        have : h\u2081_m = h\u2082_m := by apply state.syncable_unique h\u2081_hs h\u2082_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\u2081_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\u2082_h h\u2081_ha),\n      have : n = 0 := by simpa using hl,\n      subst this,\n      rw [state.map_threads, vector.vector_0_eq h\u2081_s.threads, vector.map_nil],\n      sorry,\n    },\n  },\n  case exec_state.sync_none {\n    cases h\u2082,\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\u2081_h h\u2082_ha),},\n      {\n        by_cases h' : n = 0,\n        swap,\n        {\n          sorry,\n        }, {\n          subst h',\n          cases h\u2081_s,\n          cases h\u2081_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\u2082,\n    specialize h\u2081_ih_a h\u2082_a,\n    subst h\u2081_ih_a,\n    specialize h\u2081_ih_a_1 h\u2082_a_1,\n    assumption,\n  },\n  case parlang.exec_state.ite {\n    cases h\u2082,\n    specialize h\u2081_ih_a h\u2082_a,\n    subst h\u2081_ih_a,\n    specialize h\u2081_ih_a_1 h\u2082_a_1,\n    assumption,\n  },\n  case parlang.exec_state.loop_stop {\n    cases h\u2082,\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\u2081_a h\u2082_a),\n    }\n  },\n  case parlang.exec_state.loop_step {\n    cases h\u2082,\n    case parlang.exec_state.loop_stop {\n      apply false.elim (no_threads_active_no_active_thread h\u2082_a h\u2081_a),\n    },\n    case parlang.exec_state.loop_step {\n      specialize h\u2081_ih_a h\u2082_a_1,\n      subst h\u2081_ih_a,\n      specialize h\u2081_ih_a_1 h\u2082_a_2,\n      assumption,\n    }\n  }\nend\n\nlemma exec_state_precedes {s u : state n \u03c3 \u03c4} {ac : vector bool n} {k} : exec_state (k) ac s u \u2192 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      | \u27e8[], h\u27e9 := begin\n          sorry,\n          -- rw vector.map\u2082_nil',\n          -- rw vector.map\u2082_nil,\n          -- intro,\n          -- have : (a, b) \u2209 (@vector.nil (thread_state \u03c3 \u03c4 \u00d7 thread_state \u03c3 \u03c4)) := by apply vector.mem_nil,\n          -- contradiction,\n        end\n      end,\n    },\n    case nat.succ {\n      exact match ac, s.threads with\n      | \u27e8list.cons a ac_tl, h \u27e9 := begin\n          sorry\n        end\n      end,\n    },\n  },\n  repeat { admit }\nend\n\nlemma exec_state_seq_left {s u : state n \u03c3 \u03c4} {ac : vector bool n} {k\u2081 k\u2082} : exec_state (k\u2081 ;; k\u2082) ac s u \u2192 \u2203t, exec_state k\u2081 ac s t \u2227 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 \u03c3 \u03c4} {ac : vector bool n} {k} : exec_state k ac s u \u2192 \u2200 i, \u00ac ac.nth i \u2192 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 : \u21a5(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 \u2190 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 \u2190 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 \u03c3 \u03c4) ac s t \u2192 t = s := exec_state_unique exec_skip\n\nlemma kernel_transform_inhab {k : kernel \u03c3 \u03c4} {n} {ac} {s u} : exec_state k ac s u \u2192 \u00accontains_sync k \u2192 \u2203 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 : \u00accontains_sync k_a := sorry,\n    have h2 : \u00accontains_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 \u2218 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 \u2190 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 \u03c3 \u03c4} {ac\u2081 ac\u2082 : vector bool n} {k\u2081 k\u2082} :\n  ac_distinct ac\u2081 ac\u2082 \u2192\n  exec_state k\u2081 ac\u2081 s t \u2192\n  exec_state k\u2082 ac\u2082 t u \u2192\n  \u2203 t', exec_state k\u2082 ac\u2082 s t' \u2227 exec_state k\u2081 ac\u2081 t' u :=\nbegin\n  intros hd hk\u2081 hk\u2082,\n  have hf\u2081 : _ := kernel_transform_inhab hk\u2081 sorry,\n  have hf\u2082 : _ := kernel_transform_inhab hk\u2082 sorry,\n  cases hf\u2081 with f\u2081 hf\u2081,\n  cases hf\u2082 with f\u2082 hf\u2082,\n  have h : u = state.map_active_threads ac\u2082 f\u2082 (state.map_active_threads ac\u2081 f\u2081 s) := begin\n    have hkst : t = state.map_active_threads ac\u2081 f\u2081 s := ((hf\u2081 s t).mp hk\u2081), -- an underscore as a type would break the rw below\n    have hktu : _ := (hf\u2082 t u).mp hk\u2082,\n    rw \u2190 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\u2082 f\u2082 s),\n  apply and.intro, \n  {\n    apply (hf\u2082 _ _).mpr,\n    refl,\n  }, {\n    apply (hf\u2081 _ _).mpr,\n    exact h,\n  }\nend\n\n@[simp]\nlemma init_state_syncable {init : \u2115 \u2192 \u03c3} {f : memory \u03c4 \u2192 \u2115} {m : memory \u03c4} : (init_state init f m).syncable m := begin\n  unfold state.syncable init_state,\n  simp,\nend\n\nlemma kernel_foldr_skip {k : kernel \u03c3 \u03c4} {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 \u03c3 \u03c4} {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 [\u2190 state.map_active_threads_no_thread_active s ac _ h] { occs := occurrences.pos [2] },\n    apply exec_state.load,\n  }, {\n    rw [\u2190 state.map_active_threads_no_thread_active s ac _ h] { occs := occurrences.pos [2] },\n    apply exec_state.store,\n  }, {\n    rw [\u2190 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  | \u27e8l\u2081, c\u2081\u27e9, \u27e8l\u2082, c\u2082\u27e9 =>\n    if h\u2081 : l\u2081 = l\u2082 then\n      if h\u2082 : c\u2081 = c\u2082 then isTrue (Eq.recOn h\u2081 (Eq.recOn h\u2082 rfl))\n      else isFalse fun contra => Pos.noConfusion contra fun e\u2081 e\u2082 => absurd e\u2082 h\u2082\n    else isFalse fun contra => Pos.noConfusion contra fun e\u2081 e\u2082 => absurd e\u2081 h\u2081\n\nunsafe instance : has_to_format Pos :=\n  \u27e8fun \u27e8l, c\u27e9 => \"\u27e8\" ++ l ++ \", \" ++ c ++ \"\u27e9\"\u27e9\n\n/-- Auxiliary annotation for binders (Lambda and Pi).\n    This information is only used for elaboration.\n      The difference between `{}` and `\u2983\u2984` is how implicit arguments are treated that are *not* followed by explicit arguments.\n  `{}` arguments are applied eagerly, while `\u2983\u2984` arguments are left partially applied:\n```lean\ndef foo {x : \u2115} : \u2115 := x\ndef bar \u2983x : \u2115\u2984 : \u2115 := x\n#check foo -- foo : \u2115\n#check bar -- bar : \u03a0 \u2983x : \u2115\u2984, \u2115\n```\n    -/\ninductive BinderInfo-- `(x : \u03b1)`\n\n  | default-- `{x : \u03b1}`\n\n  | implicit-- `\u2983x:\u03b1\u2984`\n\n  | strict_implicit-- `[x : \u03b1]`. 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  \u27e8fun 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\"\u27e9\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 : (\u03b1 \u2192 \u03b1) \u2192 \u03b1 | 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 : \u2115)\n     #print foo.mynat\n     -- @[reducible]\n     -- def foo.mynat : foo \u2192 \u2115 :=\n     -- \u03bb (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 \u22a2 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 ```(\u03bb a : \u03b1, x)``\n\n  |\n  lam (var_name : Name) (bi : BinderInfo) (var_type : expr) (body : expr) :\n    expr-- Pi type constructor. eg ```(\u03a0 a : \u03b1, x)`` and ```(\u03b1 \u2192 \u03b2)``\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  \u27e8expr.sort level.zero\u27e9\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 `(\u03bb 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 \u2192 Option (Name \u00d7 expr elab)\n#align expr.is_annotation expr.is_annotation\n\nunsafe axiom expr.is_string_macro : expr elab \u2192 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 \u2192 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 \u2192 expr \u2192 Bool\n#align expr.alpha_eqv expr.alpha_eqv\n\nprotected unsafe axiom expr.to_string : expr elab \u2192 String\n#align expr.to_string expr.to_string\n\nunsafe instance : ToString (expr elab) :=\n  \u27e8expr.to_string\u27e9\n\nunsafe instance : has_to_format (expr elab) :=\n  \u27e8fun e => e.toString\u27e9\n\n/-- Coercion for letting users write (f a) instead of (expr.app f a) -/\nunsafe instance : CoeFun (expr elab) fun e => expr elab \u2192 expr elab :=\n  \u27e8fun e => expr.app e\u27e9\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 \u2192 Nat\n#align expr.hash expr.hash\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nunsafe axiom expr.lt : expr \u2192 expr \u2192 Bool\n#align expr.lt expr.lt\n\n/-- Compares expressions, ignoring binder names. -/\nunsafe axiom expr.lex_lt : expr \u2192 expr \u2192 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 {\u03b1 : Type} : expr \u2192 \u03b1 \u2192 (expr \u2192 Nat \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1\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 \u2192 (expr \u2192 Nat \u2192 Option expr) \u2192 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 \u2192 Name \u2192 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 \u2192 List Name \u2192 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 \u2192 expr \u2192 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\u2081,l\u2081), ...]` will traverse `e` and replace any universe parameters with name `n\u1d62` with the corresponding level `l\u1d62`.  -/\nunsafe axiom expr.instantiate_univ_params : expr \u2192 List (Name \u00d7 level) \u2192 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 \u2192 expr \u2192 expr \u2192 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 \u2192 expr \u2192 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 \u2192 List expr \u2192 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 \u2192 Nat \u2192 List expr \u2192 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 `(\u03bb x, %%Y) Z = Y[x/Z]``, and\n``expr.subst X Z = X.app Z`` otherwise -/\nprotected unsafe axiom expr.subst : expr elab \u2192 expr elab \u2192 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 \u2192 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 \u2192 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 \u2192 Nat \u2192 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 \u2192 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 \u2192 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 `(\u03bb x, #2 #1 #0) 1 1 = `(\u03bb x, #1 #1 #0 )``\n    -/\nunsafe axiom expr.lower_vars : expr \u2192 Nat \u2192 Nat \u2192 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 `\u2265 s` in `e` by `d`. -/\nunsafe axiom expr.lift_vars : expr \u2192 Nat \u2192 Nat \u2192 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 \u2192 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 \u2192 expr \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u03b1-equivalence. Purely structural: no unification or definitional equality. -/\nunsafe axiom expr.occurs : expr \u2192 expr \u2192 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 \u2192 name_set \u2192 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 \u2192 \u2115\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 \u2192 \u2115\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 \u2192 List Name \u2192 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 \u2192 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 `\u03b1` 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 (\u03b1 : Sort u) : \u03b1 \u2192 Type := fun _ => expr\n#align reflected reflected\n\n@[inline]\nunsafe def reflected.to_expr {\u03b1 : Sort u} {a : \u03b1} : reflected _ a \u2192 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 `` (`(\u03bb 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 {\u03b1 : Sort v} {\u03b2 : \u03b1 \u2192 Sort u} {f : \u2200 a : \u03b1, \u03b2 a} {a : \u03b1} :\n    reflected _ f \u2192 reflected _ a \u2192 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 {\u03b1 : Sort u} (a : \u03b1) : Coe (reflected _ a) expr :=\n  \u27e8reflected.to_expr\u27e9\n\nprotected unsafe def reflect {\u03b1 : Sort u} (a : \u03b1) [h : reflected _ a] : reflected _ a :=\n  h\n#align reflect reflect\n\nunsafe instance {\u03b1} (a : \u03b1) : has_to_format (reflected _ a) :=\n  \u27e8fun h => to_fmt h.to_expr\u27e9\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  \u27e8expr.lt_prop\u27e9\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 \u00d7 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 \u2192 Bool\n  | var _ => true\n  | _ => false\n#align expr.is_var expr.is_var\n\nunsafe def app_of_list : expr \u2192 List expr \u2192 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 \u2192 Bool\n  | app f a => true\n  | e => false\n#align expr.is_app expr.is_app\n\nunsafe def app_fn : expr \u2192 expr\n  | app f a => f\n  | a => a\n#align expr.app_fn expr.app_fn\n\nunsafe def app_arg : expr \u2192 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 \u2192 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 \u2192 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 \u2192 expr \u2192 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 \u2192 List expr :=\n  get_app_args_aux []\n#align expr.get_app_args expr.get_app_args\n\nunsafe def mk_app : expr \u2192 List expr \u2192 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 \u2192 BinderInfo \u2192 expr \u2192 expr \u2192 expr) (e : expr) : \u2200 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 \u2192 Nat \u2192 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 \u2192 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 \u2192 Bool\n  | const n ls => true\n  | e => false\n#align expr.is_constant expr.is_constant\n\nunsafe def is_local_constant : expr \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 Name \u2192 Bool\n  | const n\u2081 ls, n\u2082 => n\u2081 = n\u2082\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 \u2227 get_app_num_args e = n\n#align expr.is_napp_of expr.is_napp_of\n\nunsafe def is_false : expr \u2192 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 \u2192 Option expr\n    | q( Not $ ( a ) ) => some a | q( $ ( a ) \u2192 False ) => some a | e => none\n#align expr.is_not expr.is_not\n\nunsafe def is_and : expr \u2192 Option (expr \u00d7 expr)\n  | q(And $(\u03b1) $(\u03b2)) => some (\u03b1, \u03b2)\n  | _ => none\n#align expr.is_and expr.is_and\n\nunsafe def is_or : expr \u2192 Option (expr \u00d7 expr)\n  | q(Or $(\u03b1) $(\u03b2)) => some (\u03b1, \u03b2)\n  | _ => none\n#align expr.is_or expr.is_or\n\nunsafe def is_iff : expr \u2192 Option (expr \u00d7 expr)\n  | q(($(a) : Prop) \u2194 $(b)) => some (a, b)\n  | _ => none\n#align expr.is_iff expr.is_iff\n\nunsafe def is_eq : expr \u2192 Option (expr \u00d7 expr)\n  | q(($(a) : $(_)) = $(b)) => some (a, b)\n  | _ => none\n#align expr.is_eq expr.is_eq\n\nunsafe def is_ne : expr \u2192 Option (expr \u00d7 expr)\n  | q(($(a) : $(_)) \u2260 $(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 \u00d7 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 \u00d7 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 \u00d7 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 \u00d7 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 \u00d7 expr) :=\n  is_bin_arith_app e `` GE.ge\n#align expr.is_ge expr.is_ge\n\nunsafe def is_heq : expr \u2192 Option (expr \u00d7 expr \u00d7 expr \u00d7 expr)\n  | q(@HEq $(\u03b1) $(a) $(\u03b2) $(b)) => some (\u03b1, a, \u03b2, b)\n  | _ => none\n#align expr.is_heq expr.is_heq\n\nunsafe def is_lambda : expr \u2192 Bool\n  | lam _ _ _ _ => true\n  | e => false\n#align expr.is_lambda expr.is_lambda\n\nunsafe def is_pi : expr \u2192 Bool\n  | pi _ _ _ _ => true\n  | e => false\n#align expr.is_pi expr.is_pi\n\nunsafe def is_arrow : expr \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 : \u2115 \u2192 expr \u2192 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 \u2192 Bool\n  | macro d a => true\n  | e => false\n#align expr.is_macro expr.is_macro\n\nunsafe def is_numeral : expr \u2192 Bool\n  | q(@Zero.zero $(\u03b1) $(s)) => true\n  | q(@One.one $(\u03b1) $(s)) => true\n  | q(@bit0 $(\u03b1) $(s) $(v)) => is_numeral v\n  | q(@bit1 $(\u03b1) $(s\u2081) $(s\u2082) $(v)) => is_numeral v\n  | _ => false\n#align expr.is_numeral expr.is_numeral\n\nunsafe def pi_arity : expr \u2192 \u2115\n  | pi _ _ _ b => pi_arity b + 1\n  | _ => 0\n#align expr.pi_arity expr.pi_arity\n\nunsafe def lam_arity : expr \u2192 \u2115\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 \u2192 expr \u2192 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 \u2192 expr \u2192 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 \u2192 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 \u2192 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 \u2192 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 {\u03b1 : Type} {m : Type \u2192 Type} [Monad m] (e : expr) (a : \u03b1)\n    (fn : expr \u2192 Nat \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\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\u2093 contains find min max fold keys values toList mfold of_list set_of_list map for filter\u2093)\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": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Meta.ForEachExpr\nimport Lean.Elab.Command\nimport Lean.Elab.DeclUtil\n\nnamespace Lean.Elab\n\ninductive DefKind where\n  | def | theorem | example | opaque | abbrev\n  deriving Inhabited, BEq\n\ndef DefKind.isTheorem : DefKind \u2192 Bool\n  | .theorem => true\n  | _        => false\n\ndef DefKind.isDefOrAbbrevOrOpaque : DefKind \u2192 Bool\n  | .def    => true\n  | .opaque => true\n  | .abbrev => true\n  | _       => false\n\ndef DefKind.isExample : DefKind \u2192 Bool\n  | .example => true\n  | _        => false\n\nstructure DefView where\n  kind          : DefKind\n  ref           : Syntax\n  modifiers     : Modifiers\n  declId        : Syntax\n  binders       : Syntax\n  type?         : Option Syntax\n  value         : Syntax\n  deriving?     : Option (Array Syntax) := none\n  deriving Inhabited\n\ndef DefView.isInstance (view : DefView) : Bool :=\n  view.modifiers.attrs.any fun attr => attr.name == `instance\n\nnamespace Command\nopen Meta\n\ndef mkDefViewOfAbbrev (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\n  let (binders, type) := expandOptDeclSig stx[2]\n  let modifiers       := modifiers.addAttribute { name := `inline }\n  let modifiers       := modifiers.addAttribute { name := `reducible }\n  { ref := stx, kind := DefKind.abbrev, modifiers,\n    declId := stx[1], binders, type? := type, value := stx[3] }\n\ndef mkDefViewOfDef (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"def \" >> declId >> optDeclSig >> declVal >> optDefDeriving\n  let (binders, type) := expandOptDeclSig stx[2]\n  let deriving? := if stx[4].isNone then none else some stx[4][1].getSepArgs\n  { ref := stx, kind := DefKind.def, modifiers,\n    declId := stx[1], binders, type? := type, value := stx[3], deriving? }\n\ndef mkDefViewOfTheorem (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"theorem \" >> declId >> declSig >> declVal\n  let (binders, type) := expandDeclSig stx[2]\n  { ref := stx, kind := DefKind.theorem, modifiers,\n    declId := stx[1], binders, type? := some type, value := stx[3] }\n\ndef mkFreshInstanceName : CommandElabM Name := do\n  let s \u2190 get\n  let idx := s.nextInstIdx\n  modify fun s => { s with nextInstIdx := s.nextInstIdx + 1 }\n  return Lean.Elab.mkFreshInstanceName s.env idx\n\n/--\n  Generate a name for an instance with the given type.\n  Note that we elaborate the type twice. Once for producing the name, and another when elaborating the declaration. -/\ndef mkInstanceName (binders : Array Syntax) (type : Syntax) : CommandElabM Name := do\n  let savedState \u2190 get\n  try\n    let result \u2190 runTermElabM fun _ => Term.withAutoBoundImplicit <| Term.elabBinders binders fun _ => Term.withoutErrToSorry do\n      let type \u2190 instantiateMVars (\u2190 Term.elabType type)\n      let ref \u2190 IO.mkRef \"\"\n      Meta.forEachExpr type fun e => do\n        if e.isForall then ref.modify (\u00b7 ++ \"ForAll\")\n        else if e.isProp then ref.modify (\u00b7 ++ \"Prop\")\n        else if e.isType then ref.modify (\u00b7 ++ \"Type\")\n        else if e.isSort then ref.modify (\u00b7 ++ \"Sort\")\n        else if e.isConst then\n          match e.constName!.eraseMacroScopes with\n          | .str _ str =>\n              if str.front.isLower then\n                ref.modify (\u00b7 ++ str.capitalize)\n              else\n                ref.modify (\u00b7 ++ str)\n          | _ => pure ()\n      ref.get\n    set savedState\n    liftMacroM <| mkUnusedBaseName <| Name.mkSimple (\"inst\" ++ result)\n  catch _ =>\n    set savedState\n    mkFreshInstanceName\n\ndef mkDefViewOfInstance (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal\n  let attrKind        \u2190 liftMacroM <| toAttributeKind stx[0]\n  let prio            \u2190 liftMacroM <| expandOptNamedPrio stx[2]\n  let attrStx         \u2190 `(attr| instance $(quote prio):num)\n  let (binders, type) := expandDeclSig stx[4]\n  let modifiers       := modifiers.addAttribute { kind := attrKind, name := `instance, stx := attrStx }\n  let declId \u2190 match stx[3].getOptional? with\n    | some declId => pure declId\n    | none        =>\n      let id \u2190 mkInstanceName binders.getArgs type\n      pure <| mkNode ``Parser.Command.declId #[mkIdentFrom stx id, mkNullNode]\n  return {\n    ref := stx, kind := DefKind.def, modifiers := modifiers,\n    declId := declId, binders := binders, type? := type, value := stx[5]\n  }\n\ndef mkDefViewOfOpaque (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser \"opaque \" >> declId >> declSig >> optional declValSimple\n  let (binders, type) := expandDeclSig stx[2]\n  let val \u2190 match stx[3].getOptional? with\n    | some val => pure val\n    | none     =>\n      let val \u2190 if modifiers.isUnsafe then `(default_or_ofNonempty% unsafe) else `(default_or_ofNonempty%)\n      pure <| mkNode ``Parser.Command.declValSimple #[ mkAtomFrom stx \":=\", val ]\n  return {\n    ref := stx, kind := DefKind.opaque, modifiers := modifiers,\n    declId := stx[1], binders := binders, type? := some type, value := val\n  }\n\ndef mkDefViewOfExample (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"example \" >> declSig >> declVal\n  let (binders, type) := expandOptDeclSig stx[1]\n  let id              := mkIdentFrom stx `_example\n  let declId          := mkNode ``Parser.Command.declId #[id, mkNullNode]\n  { ref := stx, kind := DefKind.example, modifiers := modifiers,\n    declId := declId, binders := binders, type? := type, value := stx[2] }\n\ndef isDefLike (stx : Syntax) : Bool :=\n  let declKind := stx.getKind\n  declKind == ``Parser.Command.abbrev ||\n  declKind == ``Parser.Command.def ||\n  declKind == ``Parser.Command.theorem ||\n  declKind == ``Parser.Command.opaque ||\n  declKind == ``Parser.Command.instance ||\n  declKind == ``Parser.Command.example\n\ndef mkDefView (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView :=\n  let declKind := stx.getKind\n  if declKind == ``Parser.Command.\u00ababbrev\u00bb then\n    return mkDefViewOfAbbrev modifiers stx\n  else if declKind == ``Parser.Command.def then\n    return mkDefViewOfDef modifiers stx\n  else if declKind == ``Parser.Command.theorem then\n    return mkDefViewOfTheorem modifiers stx\n  else if declKind == ``Parser.Command.opaque then\n    mkDefViewOfOpaque modifiers stx\n  else if declKind == ``Parser.Command.instance then\n    mkDefViewOfInstance modifiers stx\n  else if declKind == ``Parser.Command.example then\n    return mkDefViewOfExample modifiers stx\n  else\n    throwError \"unexpected kind of definition\"\n\nbuiltin_initialize registerTraceClass `Elab.definition\n\nend Command\nend Lean.Elab\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/DefView.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.05108274255494228, "lm_q1q2_score": 0.01237252777753547}}
{"text": "import ReactorModel.Objects.Reactor.Indexable\n\nnamespace ReactorType\nnamespace Indexable\n\nvariable [a : Indexable \u03b1]\n\nvariable {rtr rtr\u2081 rtr\u2082 : \u03b1}\n\ntheorem con?_eq_some (h : rtr[cpt][i]& = some con) : \n    \u2203 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) \u2227 \u2203 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    \u2203 c, (rtr[cpt][i]& = some c) \u2227 (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    \u2203 c con, (rtr[.rtr][c] = some con) \u2227 (cpt? cpt con i = some o) := by\n  have \u27e8\u27e8c, con\u27e9, ho, _\u27e9 := obj?_to_con?_and_cpt? h \n  have \u27e8_, _, _\u27e9 := 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 \u27e8\u22a4, rtr\u27e9 := by\n  let m := Member.final (Partial.mem_iff.mpr \u27e8_, h\u27e9)\n  simp [con?, Nonempty.intro m, \u2190a.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 \u27e8\u27e8\u22a4, rtr\u27e9, cpt?_to_con? h, h\u27e9 \n\ntheorem con?_nested {c : ID} (h : nest rtr\u2081 i = some rtr\u2082) (ho : rtr\u2082[cpt][j]& = some \u27e8c, con\u27e9) : \n    rtr\u2081[cpt][j]& = some \u27e8c, con\u27e9 := by\n  simp [con?] at ho \u22a2 \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\u2082 h\u2082 =>\n      let l\u2081 := Member.nest h (.nest h\u2082 l\u2082)\n      simp [hm, Member.container] at ho\n      simp [Nonempty.intro l\u2081, \u2190a.unique_ids.allEq l\u2081, Member.container, ho]\n\ntheorem con?_eq_root (h : rtr[cpt][i]& = some \u27e8\u22a4, con\u27e9) : rtr = con :=\n  Member.container_eq_root (con?_eq_some h).choose_spec\n\ntheorem obj?_nested {o} {j : ID} (h : nest rtr\u2081 i = some rtr\u2082) (ho : rtr\u2082[cpt][j] = some o) : \n    rtr\u2081[cpt][j] = some o := by\n  cases cpt <;> try cases j\n  all_goals\n    simp [obj?, bind]\n    have \u27e8\u27e8c, con\u27e9, hc, ho\u27e9 := obj?_to_con?_and_cpt? ho \n    cases c\n    case some c => \n      have := con?_nested h hc\n      exists \u27e8c, con\u27e9\n    case none => \n      replace hc := con?_eq_root hc\n      simp at ho\n      subst hc\n      exists \u27e8i, rtr\u2082\u27e9\n      let m := Member.nest h (.final $ Partial.mem_iff.mpr \u27e8_, ho\u27e9)\n      simp [ho, con?, Nonempty.intro m, \u2190a.unique_ids.allEq m, Member.container]\n\n-- Note: By `ho` we get `rtr\u2082 = rtr\u2083`.\ntheorem obj?_nested_root (h : nest rtr\u2081 i = some rtr\u2082) (ho : rtr\u2082[.rtr][\u22a4] = some rtr\u2083) : \n    \u2203 j, rtr\u2081[.rtr][j] = some rtr\u2083 := by\n  simp [obj?] at ho\n  exact \u27e8i, ho \u25b8 cpt?_to_obj? h\u27e9\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 = \u22a4`, then `j' = .nest i`.\ntheorem obj?_nested' {o j} (h : nest rtr\u2081 i = some rtr\u2082) (ho : rtr\u2082[cpt][j] = some o) : \n    \u2203 j', rtr\u2081[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 \u27e8_, obj?_nested h ho\u27e9\n\ntheorem obj?_mem_nested {j : ID} (h : nest rtr\u2081 i = some rtr\u2082) (hm : \u2191j \u2208 rtr\u2082[cpt]) : \n    \u2191j \u2208 rtr\u2081[cpt] :=\n  Partial.mem_iff.mpr \u27e8_, obj?_nested h (Partial.mem_iff.mp hm).choose_spec\u27e9  \n\ntheorem mem_cpt?_rtr_eq (ho\u2081 : rtr[.rtr][c\u2081] = some con\u2081) (ho\u2082 : rtr[.rtr][c\u2082] = some con\u2082) \n    (hc\u2081 : j \u2208 cpt? cpt con\u2081) (hc\u2082 : j \u2208 cpt? cpt con\u2082) : c\u2081 = c\u2082 := by\n  cases c\u2081 <;> cases c\u2082\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\u2081 and hc\u2081 and one from ho\u2082 and hc\u2082.\n    --       By `unique_ids` they are equal, from which we can extract that `c\u2081 = c\u2082`.\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 \u03b1] {rtr\u2081 : \u03b1}\n\ntheorem obj?_preserved (u : LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) (h : c \u2260 cpt \u2228 j \u2260 i) : \n    rtr\u2082[c][j] = rtr\u2081[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\u2081 (u : LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) : \u2203 o, rtr\u2081[cpt][i] = some o := by\n  induction u \n  case final         => exact \u27e8_, cpt?_to_obj? \u2039_\u203a\u27e9\n  case nest h _ _ hi => exact \u27e8_, obj?_nested h hi.choose_spec\u27e9\n\ntheorem obj?_some\u2082 (u : LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) : \u2203 o, rtr\u2082[cpt][i] = some o := by\n  induction u \n  case final       => exact \u27e8_, cpt?_to_obj? \u2039_\u203a\u27e9\n  case nest h _ hi => exact \u27e8_, obj?_nested h hi.choose_spec\u27e9\n\ntheorem obj?_updated (u : LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082) : \n    rtr\u2082[cpt][i] = f <$> rtr\u2081[cpt][i] := by\n  induction u\n  case final h\u2081 h\u2082 => \n    rw [cpt?_to_obj? h\u2081, cpt?_to_obj? h\u2082, Option.map_some]\n  case nest h\u2081 h\u2082 u hi =>\n    have \u27e8_, h\u2081'\u27e9 := u.obj?_some\u2081\n    have \u27e8_, h\u2082'\u27e9 := u.obj?_some\u2082\n    rw [obj?_nested h\u2081 h\u2081', obj?_nested h\u2082 h\u2082']\n    exact h\u2081' \u25b8 h\u2082' \u25b8 hi\n\nend LawfulMemUpdate\n\nnamespace LawfulUpdate\n\nvariable [Indexable \u03b1] {rtr\u2081 : \u03b1}\n\ntheorem obj?_preserved (h : c \u2260 cpt \u2228 j \u2260 i) : \n    (LawfulUpdate cpt i f rtr\u2081 rtr\u2082) \u2192 rtr\u2082[c][j] = rtr\u2081[c][j]\n  | update u   => u.obj?_preserved h\n  | notMem _ h => h \u25b8 rfl\n\ntheorem obj?_updated : (LawfulUpdate cpt i f rtr\u2081 rtr\u2082) \u2192 rtr\u2082[cpt][i] = f <$> rtr\u2081[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 \u03b1] {rtr : \u03b1}\n\ntheorem obj?_preserved (h : c \u2260 cpt \u2228 j \u2260 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 \u2260 cpt := by exact (nomatch \u00b7)) : \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 \u2260 i) : \n    (update rtr cpt i f)[c][j] = rtr[c][j] :=\n  obj?_preserved $ .inr h\n\ntheorem obj?_updated {rtr : \u03b1} : (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 ` \u2b1d ` := has_mul.mul\nnotation x`\u00b2`:99 := x\u2b1dx\nnotation `\u00a0` binders ` \u21a6 ` f:(scoped f, f) := f\nnotation `\u27ee` binders ` \u21a6 ` f:(scoped f, f) `\u27ef`:= f\n\ndef flip_over_2{A B C D}(f: A\u2192B\u2192C\u2192D) :=\u00a0z x y \u21a6 f x y z\ninfixl ` @\u2081`:99 := flip\ninfixl ` @\u2082`:99 := flip_over_2\ninfixr ` \u2218\u2082 `:80 := (\u2218)\u2218(\u2218)\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 \u2192 t) := {\n\tone := id,\n\tmul := (\u2218),\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\u2192B): option A \u2192 B\n| none := no\n| (some a) := yes a\n\ndef ifoldl_help{S T}(f: \u2115\u2192S\u2192T\u2192T): \u2115 \u2192 list S \u2192 T \u2192 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: \u2115\u2192S\u2192T\u2192T) := ifoldl_help f 0\n\ndef list.imap{S T}(f: \u2115\u2192S\u2192T)(s: list S) := (s.ifoldl(list.cons \u2218\u2082 f) []).reverse\n\nuniverse U\ndef list.mfilter_map{A B : Type U}{M}[monad M](f: A \u2192 M(option B)): list A \u2192 M(list B)\n| [] := pure[]\n| (a::s) := do\n\tfa \u2190 f a,\n\ts' \u2190 s.mfilter_map,\n\tpure(fa.maybe s' \u27eeb \u21a6 b::s'\u27ef)\n\n@[simp] def map\u2082_default{X Z}(d)(f: X \u2192 X \u2192 Z): list X \u2192 list X \u2192 list Z\n| [] [] := []\n--| s l := f ((s.nth 0).get_or_else d) ((l.nth 0).get_or_else d) :: map\u2082_default s.tail l.tail\n| [] (y::ys) := f d y :: map\u2082_default [] ys\n| (x::xs) [] := f x d :: map\u2082_default xs []\n| (x::xs) (y::ys) := f x y :: map\u2082_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\u2c7c | j] = [(x\u1d62,x\u2c7c) | i<j]\ndef list.unique_pairs{T}: list T \u2192 list(T\u00d7T)\n| [] := []\n| (x::xs) := xs.map\u27eey\u21a6 (x,y)\u27ef ++ xs.unique_pairs\n\n@[priority 0]instance to_string_of_repr{X}[has_repr X]: has_to_string X := \u27e8repr\u27e9\n@[priority 0]meta instance format_of_repr{X}[has_repr X]: has_to_tactic_format X := \u27e8has_to_tactic_format.to_tactic_format \u2218 repr\u27e9\n\n/-- \n`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.\n`type`: an expression representing the target type\n`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. \n -/\nmeta def nat.mk_numeral (type has_zero has_one has_add : expr) : \u2115 \u2192 expr :=\nlet z : expr := `(@has_zero.zero.{0} %%type %%has_zero),\n    o : expr := `(@has_one.one.{0} %%type %%has_one) in\nnat.binary_rec z\n  (\u03bb b n e, if n = 0 then o else\n    if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) \n    else `(@bit0.{0} %%type %%has_add %%e))\n\nmeta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : \u2124 \u2192 expr\n| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add \n| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in \n            `(@has_neg.neg.{0} %%type %%has_neg %%ne)\n\nmeta def rat.mk_numeral (type has_zero has_one has_add has_neg has_div : expr) : \u211a \u2192 expr\n| \u27e8num, denom, _, _\u27e9 := \n  let nume := num.mk_numeral type has_zero has_one has_add has_neg in\n  if denom = 1 then nume else\n    let dene := denom.mk_numeral type has_zero has_one has_add in \n    `(@has_div.div.{0} %%type %%has_div %%nume %%dene)\n\nmeta def rat.reflect : \u211a \u2192 expr :=\nrat.mk_numeral `(\u211a) `((infer_instance : has_zero \u211a))\n         `((infer_instance : has_one \u211a))`((infer_instance : has_add \u211a))\n         `((infer_instance : has_neg \u211a)) `(infer_instance : has_div \u211a)\n\nsection \nlocal attribute [semireducible] reflected\nmeta instance \u211a_has_reflect: has_reflect \u211a := rat.reflect\nend \n\n-- infixr ` \u2237 `:67 := (++)\u2218repr\n-- --set_option pp.all true\n-- def replace_1_: list char \u2192 string\n-- --| ('+'::' '::'-'::s) := \"- \"++ replace_minus s\n-- | [] := \"\"\n-- | (a::s) := match if a\u2260' ' then none else match s with\n-- \t| [] := none\n-- \t| (b::s) := if b\u2260'1' then none else match s with\n-- \t\t| [] := none\n-- \t\t| (c::s) := if c\u2260' ' then none else \n-- \t\t\thave hint: s.sizeof < a.val+(1+s.sizeof), from by{simp[has_lt.lt,nat.lt], rw(_:nat.succ _=0+_), rw(_:1+_=nat.succ _), apply nat.add_le_add_right, tidy, rw nat.add_comm},\n-- \t\t\tsome(' '\u2237 replace_1_ s)\n-- end end with\n-- | none := a \u2237 replace_1_ s\n-- | some s := s\n\n\n--\u2013Monomials are now represented by lists, which are thought to be zero extended. Trailing zeros are normalized away. \ndef monomial := list \u2115\nnamespace monomial\n\ndef deg(m: monomial) := list.sum m\n\ndef variable_name: \u2115 \u2192 string\n| 0 := \"x\" | 1 := \"y\" | 2 := \"z\"\n| n := (char.of_nat(121-n)).to_string\n\ndef rise_digit(n: char) := (\"\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\".to_list.nth n.to_string.to_nat).get_or_else '?'\ndef rise_number(n: string) := (n.to_list.map rise_digit).as_string\n\ninstance monomial.has_repr: has_repr monomial := \u27e8\u00a0m \u21a6 m.ifoldl\u27eej e \u21a6 ite(e=0) id (++ variable_name j ++ ite(e=1) \"\" (rise_number(repr e)))\u27ef \"\" \u27e9\ninstance: has_one monomial := \u27e8[]\u27e9\ninstance: has_mul monomial := \u27e8map\u2082_default 0 (+)\u27e9 --no need to trim\ninstance: has_div monomial := \u27e8trim_tail 0 \u2218\u2082 map\u2082_default 0 \u27eex y \u21a6 x-y\u27ef\u27e9\n\ndef gcd(n m : monomial): monomial := trim_tail 0 (list.map\u2082 min n m) --no need to extend\ndef lcm(n m : monomial): monomial := map\u2082_default 0 max n m --no need to trim\n\ndef dvd': monomial \u2192 monomial \u2192 bool\n| [] _ := tt\n| (n::ns) m := n \u2264 (m.nth 0).get_or_else 0 \u2227 dvd' ns m.tail\ndef dvd :=\u00a0n m \u21a6 (dvd' n m : Prop)\ninstance: has_dvd monomial := \u27e8dvd\u27e9\ninstance: decidable_rel dvd := by unfold dvd; apply_instance\n\n\n--\u2013Orders should be admissible (unit least and multiplication monotonous). \nclass order := \n(lt: monomial \u2192 monomial \u2192 Prop)\n(decidable: decidable_rel lt)\n\ndef lex: order := {\n\tlt := list.lex(<),\n\tdecidable := infer_instance,\n}\ndef deg_lex: order := {\n\tlt :=\u00a0n m \u21a6 deg n < deg m \u2228 (deg n = deg m \u2227 list.lex(<) n m),\n\tdecidable :=\u00a0_ _\u21a6 by apply or.decidable,\n}\nend monomial\n\n@[reducible] private def mo := monomial.order\n\n\n--\u2013Polynomials (this ended up essentially reimplementing very basics of rbmap equivalently, because I didn't find rbmap early enough)\n--Reverse order to have the leading term first. \ndef poly.less[mo]{K}(x y : K\u00d7monomial) := monomial.order.lt y.snd x.snd\ndef poly[mo](K)[ring K] := rbtree (K\u00d7monomial) poly.less\n\nnamespace poly\n--K \u2208 Type 0 because otherwise combination with tactics gets problematic.\nvariables{K: Type}[ring K][decidable_eq K][o:mo](P R : poly K)\n\ninstance[mo]: has_lt monomial := \u27e8monomial.order.lt\u27e9\ninstance[mo]: has_le monomial := \u27e8\u00a0n m \u21a6 \u00acn>m \u27e9\ninstance decidable_lt[mo]: @decidable_rel monomial (<) := monomial.order.decidable\ninstance decidable_le[mo]: @decidable_rel monomial (\u2264) := by apply_instance\ninstance decidable_less: decidable_rel(@less o K) :=\u00a0_ _\u21a6 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\u2192K): 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) := \u27e8\u00a0m\u21a6 monom(1,m) \u27e9\n\n--Let f' = (f; 0\u21a6id). Then combine@\u2082f maps \u03a3 p\u2c7c\u2b1dm\u2c7c and \u03a3 r\u2c7c\u2b1dm\u2c7c to \u03a3 f' p\u2c7c r\u2c7c \u2b1d m\u2c7c (...assuming unsoundly that there's no explicit 0 coefficients...exact behavior depends on what the representation happens to be). \ndef combine(f: K\u2192K\u2192K): poly K := P.fold\u27eep R' \u21a6 update R' p.snd (f p.fst)\u27ef R\ndef map_poly(f: K\u2192K): poly K := combine P P\u00a0_\u21a6f\n\ninstance[mo]: has_zero(poly K) := \u27e8rbtree_of[]less\u27e9\ninstance[mo]: has_one(poly K) := \u27e8monom(1,1)\u27e9\ninstance[mo]: has_add(poly K) := \u27e8combine @\u2082(+)\u27e9\ninstance[mo]: has_neg(poly K) := \u27e8map_poly @\u2081\u00a0k\u21a6-k\u27e9\ninstance[mo]: has_sub(poly K) := \u27e8\u00a0P R \u21a6 P + -R \u27e9\ninstance[mo]: has_mul(poly K) := \u27e8\u00a0P\u21a6 fold\u27eem\u21a6 P.fold\u27een\u21a6 (+monom(m\u2b1dn))\u27ef\u27ef @\u20810 \u27e9\ninstance[mo]: has_scalar K (poly K) := \u27e8\u00a0k\u21a6 map_poly @\u2081(\u2b1dk) \u27e9\ninstance[mo]: has_pow(poly K) \u2115 := \u27e8\u00a0P n \u21a6 (list.repeat P n).foldl(\u2b1d)1 \u27e9\n\ninstance[mo][has_repr K]: has_repr(poly K) := \u27e8\u00a0P\u21a6 match P.to_list.filter\u27eep:K\u00d7_ \u21a6 p.fst \u2260 0\u27ef with\n\t| [] := \"0\"\n\t| (m::ms) := ms.foldl\u27ees p \u21a6 s ++\" + \"++ repr p.fst ++\" \"++ repr p.snd\u27ef (repr m.fst ++\" \"++ repr m.snd)\nend\u27e9\n\ndef lead_term := (P.fold\u27eep:K\u00d7_ \u21a6 option.maybe (if p.fst = 0 then none else some p) some\u27ef 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) := \u27e80\u27e9\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 \u00d7 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) := \u27e8(0,[])\u27e9\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\u27ee_\u21a60\u27ef\ndef is_triv[mo]: proof K \u2192 bool\n| [] := tt\n| (p::ps) := is0 p \u2227 is_triv ps\ndef proof_add[mo](p\u2081 p\u2082 : proof K)(f: poly K \u2192 poly K) := p\u2081.map\u2082(+) (p\u2082.map f)\n\n--Compute the S-polynomial of monic polynomials with membership proof. \ndef monicS[mo]: poly_mem K \u2192 poly_mem K \u2192 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\u2b1dmp - R\u2b1dmr, proof_add (pP.map(\u2b1dmp)) pR(\u2b1d(-mr)))\n\n\n--Accumulates proof to show that if P\u2192R then R - P \u2208 \u27e8B\u27e9. \nmeta def simplify_leading_loop[mo](B: polys K): poly_mem K \u2192 poly_mem K |(P, proof) :=\n\tlet p := P.lead_mono in match B.filter((\u2223p)\u2218lead_mono\u2218fst) 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\u2b1dc, proof_add proof prf(\u2b1dc))\nend\n--B must be a non-empty list of monic (and \u22600) polynomials.\nmeta def simplify_leading[mo](B: polys K)(P: poly_mem K): poly_mem K := \n\tmatch B.filter(is_const \u2218 fst) with\n\t| (_,prf)::_ := (0, proof_add P.snd prf(\u2b1d(-P.fst)))\n\t| _ := simplify_leading_loop B P\nend\n\nmeta def simplify_loop[mo](B): poly K \u2192 poly_mem K \u2192 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\u2190P and proof that R - P \u2208 \u27e8B\u27e9. 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 \u2192 poly_mem K | (P,prf) := let c := P.lead_coef \u207b\u00b9 in (c\u2022P, prf.map((\u2022)c))\n\n\nmeta def simplify_basis_loop[mo](simp: polys K \u2192 poly_mem K \u2192 poly_mem K): \u2115 \u2192 polys K \u2192 polys K\n| 0 B := B\n| l [] := sorry -- l \u2264 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\u2082\u27eex y \u21a6 x-y\u27ef 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\u27eeB P \u21a6 let P' := simplify_leading [S] P in if is_triv P'.snd then P else simplify_leading B P'\u27ef B.length B\n\n--Interreduce B. \nmeta def simplify_basis[mo](B: polys K) := simplify_basis_loop(simplify_loop @\u20810) B.length B\n\n\n--main loop\nprivate meta def go[mo]: polys K \u2192 list(poly_mem K \u00d7 poly_mem K) \u2192 polys K\n| G [] := G\n| G ((p\u2081,p\u2082)::ps) := let S := scale_monic(simplify_leading G (monicS p\u2081 p\u2082))\n\tin if S.is0 then go G ps else let G := simplify_basis_by S G in go (S::G) (ps ++ G.map\u27eeP\u21a6 (P,S)\u27ef)\n\nmeta def \u00abGr\u00f6bner basis of\u00bb[mo](B: list(poly K)) := let B := B.filter(not\u2218is0), B1 := B.imap\u27eei b \u21a6 scale_monic(b, (B.map\u27ee_\u21a6(0: poly K)\u27ef).update_nth i 1)\u27ef in simplify_basis(go B1 B1.unique_pairs)\nnotation `Gr\u00f6bner_basis_of` := \u00abGr\u00f6bner basis of\u00bb\n--Lean's letter recognition is broken! It is not just an implementation mistake, but it is even specified in an adhoc way \u2013 see https://leanprover.github.io/reference/lexical_structure.html#identifiers \u2013 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 \u2121\u214b\u2100 := \"Telephone sign \u01dd\u0287 \u201caccount\u201d 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\u00e4st\u00e4 voisi johtaa tyyliin ringa-taktiikan. Sievennet\u00e4\u00e4n kaikkia ... hmm, miten sievennyskelpoiset lausekkeet m\u00e4\u00e4r\u00e4t\u00e4\u00e4n? Kertoimien tulee olla kunnasta, mutta muuttujia saa k\u00e4sitell\u00e4 vain rengasoperaatioilla. Teoreettisesti n\u00e4tti\u00e4 olisi yleist\u00e4\u00e4 hieman ja ratkaista renkaiden ehdolliset sanaongelmat, mutta seh\u00e4n edellytt\u00e4isi paljon lis\u00e4\u00e4 koodausta! \n--Sitten pit\u00e4\u00e4 ratkaista, miten termien triviaali sievennys kuten x+y-x=y hoidetaan. Koska tulos tiedet\u00e4\u00e4n aina, voidaan turvallisesti turvautua ring-taktiikkaan. \n--Luetaan tavoitetta kunnes vastaan tulee +,\u2b1d,- (t\u00e4rke\u00e4\u00e4 on, ett\u00e4 l\u00f6ydet\u00e4\u00e4n maksimaalinen termi sievennett\u00e4v\u00e4ksi\u2014t\u00e4m\u00e4n pit\u00e4isi riitt\u00e4\u00e4 siihen, koska tietenk\u00e4\u00e4n p\u00e4\u00e4lioperaatio ei t\u00e4ll\u00f6in voi olla jokin sellainen, jota ei osata k\u00e4sitell\u00e4). Huom. - voi esiinty\u00e4 sek\u00e4 unaarisena ett\u00e4 bin\u00e4\u00e4risen\u00e4. Seuraavaksi tarkistetaan, ett\u00e4 alitermi on kuntatyyppi\u00e4...mutta t\u00e4m\u00e4 rajoittaa k\u00e4ytett\u00e4vyytt\u00e4 melko merkitt\u00e4v\u00e4sti. Teoriassa voisi vaatia, ett\u00e4 tyyppi on vaihdannainen rengas ja K-moduli jonkin kunnan K suhteen, ja K:lta vaaditaan lis\u00e4ksi p\u00e4\u00e4tett\u00e4v\u00e4 yhtyvyys. Jotta t\u00e4st\u00e4 teoriasta tulee k\u00e4yt\u00e4nt\u00f6\u00e4, lienee vaadittava, ett\u00e4 k\u00e4ytt\u00e4j\u00e4 sy\u00f6tt\u00e4\u00e4 kunnan (\u211a voi olla oletusarvo).\n\nmeta def \ud835\udd3c(pre) := to_expr pre tt ff\n--meta def childs(e: expr) := (e.mfoldl\u27eec s \u21a6 [list.cons s c]\u27ef []).head\nmeta def childs: expr \u2192 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 `\u1d58\u1d56 ` 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 \u2190 state_t.get, when(s=[]) reaction\n\nmeta def fbs_loop{T}(t)(test: (expr \u2192 ST T) \u2192 expr \u2192 ST T)(atoms: rb_set expr): bool \u2192 expr \u2192 ST unit | layer's_top e :=\nwhen(\u00ac atoms.contains e) (test\u27eex \u21a6 t<$\n\tif x\u2260e then fbs_loop ff x\n\telse (childs x).mmap'(if_not_found \u2218 fbs_loop tt)\n\u27ef e >> if_not_found(when layer's_top (test\u27eee' \u21a6 when(e\u2260e') (state_t.put[e]) $>t\u27ef 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 \u2192 tactic(option expr) \n| e := prod.fst <$> (do\n\tfbs_loop t test atoms tt e,\n\tg \u2190 state_t.get,\n\t~ g.nth 0\n).run[]\n\n\nmeta def prepare_loop{T}(var: \u2115\u2192T)(test: (expr \u2192 ST T) \u2192 expr \u2192 ST T): expr \u2192 ST T | e :=\ntest\u27eex \u21a6 if x\u2260e then prepare_loop x else do\n\tvs \u2190 state_t.get,\n\tlet i := vs.index_of x,\n\twhen(i = vs.length) (state_t.put(vs++[x])) $> var i\n\u27efe\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: \u2115\u2192T)(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: \u2115 \u2192 T)(test)(es: list expr) := (es.mmap(prepare_loop var test)).run[]\n\n\nmeta def simplify_by_loop{T}(var: \u2115\u2192T)(test: (expr \u2192 ST T) \u2192 expr \u2192 ST T)(simp: expr \u2192 T \u2192 tactic expr): rb_set expr \u2192 tactic unit | simplified := do\n\te \u2190 target,\n\tx \u2190 find_bottom_simplifiable (var 0) test simplified e,\n\tx.maybe(~())\u27eex \u21a6 do\n\t\t(x',g) \u2190 prepare var test x,\n\t\tproof \u2190 simp x x',\n\t\trewrite_target proof,\n\t\t`(%%_ = %%s) \u2190 infer_type proof,\n\t\tsimplify_by_loop(simplified.insert s)\u27ef\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\u00f6bner 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 \u2208 expr \u2192 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 \u2200x\u2080...\u2200x\u2099 ???).\nmeta def simplify_by{T}(var: \u2115\u2192T)(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\u00f6bner 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) := (\ud835\udd3c i >>= mk_instance) $> tt <|> ~ff\n\n\nmeta def test_poly[mo][reflected K](r: expr \u2192 ST(poly K))(e: expr): ST(poly K) := match e with\n| `(%%x \u2b1d %%y) := (\u2b1d) <$> r x <*> r y\n| `(%%x + %%y) := (+) <$> r x <*> r y\n| `(%%x - %%y) := \u27eex y \u21a6 x-y\u27ef <$> r x <*> r y\n| `(- %%x) := \u27eex \u21a6 -x\u27ef <$> r x\n| `(%%x ^ %%n) := do\n\tN \u2190\u1d58\u1d56 infer_type n,\n\tif N \u2260 `(\u2115) \u2228 n.has_var \u2228 n.has_local then r e\n\telse do n \u2190\u1d58\u1d56 eval_expr \u2115 n, (^n) <$> r x\n| e := do\n\tE \u2190\u1d58\u1d56 infer_type e,\n\tif E \u2260 reflect K \u2228 e.has_var \u2228 e.has_local then r e\n\telse do k \u2190\u1d58\u1d56 eval_expr K e, ~monom(k,[])\nend\n\nmeta def test_poly_typed[mo][reflected K](M: option expr)(r: expr \u2192 ST(poly K))(e): ST(poly K) := do\n\tE \u2190\u1d58\u1d56 infer_type e,\n\tok \u2190 match M with some M := ~(E=M : bool)\n\t\t| _ :=\u1d58\u1d56 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\u1d57\u02b0 variable \"X\u1d62\".\ndef X'[mo](i:\u2115): 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 \u27eex p e \u21a6 if p=0 then e else do e\u2190e, \ud835\udd3c``(%%e \u2b1d %%(vs.nth x).iget ^ %%(reflect p))\u27ef (\ud835\udd3c``(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 \u27eem e \u21a6 let c:= m.fst in if c=0 then e else do e\u2190e, mono \u2190 represent_mono r M vs m.snd, \ud835\udd3c``(%%e + %%(reflect c)\u2b1d%%mono)\u27ef (\ud835\udd3c``(0:%%M))\n--TODO Use module product \u2022 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 \u2190 local_context,\n\tls.mfilter\u27eea \u21a6 do b \u2190 infer_type a, match b with `(%%x = %%y) := do Y \u2190 infer_type y, ~Y=M | _:=~ff end\u27ef\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 \u2190 get_unused_name,\n\tgoal >>= assert n,\n\tsolve,\n\tproof \u2190 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\u2b1d(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\u00f6bner 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 \u2192 poly K \u2192 tactic expr) := do\n\tlet test: (expr \u2192 ST(poly K)) \u2192 _ := test_poly_typed(option.some M),\n\tbe \u2190 E.mmap\u27eep \u21a6 do e \u2190 infer_type p, match e with `(%%x = %%y) := \ud835\udd3c``(%%x - %%y) | _:=sorry end\u27ef,\n\t((B: list(poly K)), vs) \u2190 prepares X' test be,\n\tlet G := Gr\u00f6bner_basis_of B,\n~\u00a0pe _ \u21a6 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) \u2190 (prepare_loop X' test pe).run vs,\n\tlet (R, coef) := simplify G P,\n\t--R = P + coef\u2022(f\u2c7c - g\u2c7c)\u2c7c\n\t--P - R  =\u02b3\u2071\u207f\u1d4d=  -coef\u2022(f\u2c7c - g\u2c7c)\u2c7c  = \u201ccoef\u20220\u201d = 0  \u27f9 P=R\n\tre \u2190 represent_poly M vs R,\n\tce \u2190 coef.mmap(represent_poly M vs),\n\tK0is0 \u2190 \ud835\udd3c``(rfl : (0:%%(reflect K)) = 0),\n\tstep2 \u2190 (ce.zip E).mfoldl \u27eeprf cb \u21a6 \ud835\udd3c``(@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)\u27ef K0is0,\n\t`(%%ce_be = %%_) \u2190 infer_type step2,\n\tring_step \u2190 prove_by`[{ring}] (\ud835\udd3c``(%%pe - %%re = %%ce_be)),\n\t\ud835\udd3c``(@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\u211a := `[exact \u211a]\n\nmeta def ringa(K:Type. exact\u211a)[reflected K][has_reflect K][field K][decidable_eq K][has_repr K/-debug-/][mo]: tactic unit := do\n\tt \u2190 target,\n\t--\"find_top_simplifiable\" would be more expected behavior...if it existed\n\te \u2190 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 \u2190 infer_type e.iget,\n\tB \u2190 local_equations_of_type M,\n\tif B=[] then `[ring] else do --Do not fail to preserve composability.\n\treducer \u2190 verifying_reducer M B,\n\tsimplify_by (X': \u2115 \u2192 poly K) (test_poly_typed(some M)) reducer,\n\t`[try{ring}]\n\n\n#check Gr\u00f6bner_basis_of\n--Test cases\ninstance use_this_order := monomial.deg_lex\nvariables{v x y z : \u211a}{f: \u211a\u2192\u211a}\n\n--These delegate to ring tactic\nexample: (x+y)\u2b1d(x-y) = x\u00b2 - y\u00b2 := by ringa\nexample: f(2\u2b1dx) = f(x+x) := by ringa\n--These don't\nexample(_:v=z): (x+y)\u2b1d(x-y) = x\u00b2 - y\u00b2 := by ringa\nexample(_:v=z): f(2\u2b1dx) = f(x+x) := by ringa\n\n--Core functionality tests\nexample(_: x+y = z)(_: x\u00b2 + y\u00b2 = z\u00b2): x\u2b1dy = 0 := by ringa\nexample(_: x\u2b1dy\u00b2 = x+y)(_: x\u00b2\u2b1dy = x\u00b2 + y\u00b2): y^5 = (2\u2b1dx-1)\u2b1d(2\u2b1dy-1)/2 - 1/2 := by ringa\nexample(_: x\u2b1dy\u00b2 = x+y)(_: x\u00b2\u2b1dy = x+1): y = x\u00b2 := by ringa\nexample(_: z\u2b1dx=y)(_: y=x\u00b2)(_: v\u00b2=2): x\u2b1d(2\u2b1dz-x-x) = 0 := by ringa\nexample(_: x\u00b2\u2b1dy = x\u00b2)(_: x\u2b1dy\u00b2 = y\u00b2): (x+y)\u2b1d(x-y) + x\u00b2 = x^3 := by ringa\n\n--Iteration tests\nexample(_: x=y): x\u2b1df(2\u2b1dx\u00b2 - y\u00b2) - y\u2b1df(x\u2b1dy) = 0 := by ringa\nexample(_: x=y): x\u2b1df(x-y) - y\u2b1df(x-x) = 0 := by ringa\nexample(_: x=y+1): (x-1)\u2b1df(2\u2b1dx-1) - y\u2b1df(x\u00b2 - y\u00b2) = 0 := by ringa\nexample(_: x\u00b2+y\u00b2 = z\u00b2)(_: x^3 + y^3 = z^3)(_: x\u2b1dy = 1): f(x + y + f(2/3)) = f(f(z\u00b2) - 2\u2b1dz) := by ringa\n\n--In algebras over \u211a\nopen polynomial\nexample{P: polynomial \u211a}(_: X\u00b2 - X - 1 = (0: polynomial \u211a))(_: P = 1-X): P\u00b2 = P+1 := by ringa\n\n\n--Is it worth to handle the situation of inconsistent axioms?\nexample(_: x\u00b2+3\u2b1dx+1 = 0)(_: y\u00b2+3\u2b1dy+1 = 0)(_: x^5 + y^5 = 0): x-y = 1 := by ringa\n#check ringa\n--\u221b2\u0305+\u0305\u221a\u03055\u0305 + \u221b2\u0305-\u0305\u221a\u03055\u0305 = 1\n--example(_: x\u00b2=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\u27e8\u00a0x \u21a6 repr x.fst \u27e9\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 \u2115): poly \u211a := monom(1,m)\n\ndef a := lm[2] +3\u2b1dlm[1]+lm[]\ndef b := lm[0,2] +3\u2b1dlm[0,1]+lm[]\ndef c := lm[5] + lm[0,5]\n#eval simplify(Gr\u00f6bner_basis_of[a,b]) c\n--#eval Gr\u00f6bner_basis_of[a,b,c] --Time out just because the algorithm is so slow!\n\ndef \u03b1 := lm[0,0,2] + lm[0,2] - lm[2]\ndef \u03b2 := lm[0,0,3] + lm[0,3] - lm[3]\ndef \u03b3 := lm[0,1,1] - 1\n#eval (Gr\u00f6bner_basis_of[\u03b1,\u03b2,\u03b3])\n#eval simplify(Gr\u00f6bner_basis_of[\u03b1,\u03b2,\u03b3]) (lm[2])\n\ndef P := lm[2,1] + ((1:\u211a)/2)\u2022lm[2]\ndef R := lm[1,2] + lm[0,2]\ndef S := -lm[2,2] + lm[1,1] + lm[2]\n#eval (Gr\u00f6bner_basis_of[P,R])\n#eval simplify (Gr\u00f6bner_basis_of[P,R]) (S\u00b2)\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\u00f6bner_basis_of B\n#eval P\u00b2\u2b1dR\n#eval Gr\u00f6bner_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(\u2b1d1)\n#eval Gr\u00f6bner_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\u00f6bner_basis_of(B++[P\u00b2\u2b1dR])\n--#eval Gr\u00f6bner_basis_of(P\u00b2\u2b1dR::B)\n\n#eval (lm[] + 0).lead_coef\n#eval (2\u2b1dlm[4,2] + lm[3,4])\u00b2.fold((++)\u2218repr) \"\"\n#eval (2\u2b1dlm[4,2] + lm[3,4])\u00b2.lead_mono\n#eval (P + 3\u2b1dP\u00b2 + P\u00b2)\u00b2\n", "meta": {"author": "0function", "repo": "storage", "sha": "1a28fa3019003170c509b0c2badb85bd25319cd5", "save_path": "github-repos/lean/0function-storage", "path": "github-repos/lean/0function-storage/storage-1a28fa3019003170c509b0c2badb85bd25319cd5/Gr\u00f6bner.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 \u2192 type \u2192 expr       /- integer literal -/\n| Econst_float : float \u2192 type \u2192 expr   /- double float literal -/\n| Econst_single : float32 \u2192 type \u2192 expr /- single float literal -/\n| Econst_long : int64 \u2192 type \u2192 expr    /- long integer literal -/\n| Evar : ident \u2192 type \u2192 expr           /- variable -/\n| Etempvar : ident \u2192 type \u2192 expr       /- temporary variable -/\n| Ederef : expr \u2192 type \u2192 expr          /- pointer dereference (unary [*]) -/\n| Eaddrof : expr \u2192 type \u2192 expr         /- address-of operator ([&]) -/\n| Eunop : unary_operation \u2192 expr \u2192 type \u2192 expr  /- unary operation -/\n| Ebinop : binary_operation \u2192 expr \u2192 expr \u2192 type \u2192 expr /- binary operation -/\n| Ecast : expr \u2192 type \u2192 expr   /- type cast ([(ty) e]) -/\n| Efield : expr \u2192 ident \u2192 type \u2192 expr /- access to a member of a struct or union -/\n| Esizeof : type \u2192 type \u2192 expr         /- size of a type -/\n| Ealignof : type \u2192 type \u2192 expr        /- alignment of a type -/\nopen clight.expr\n\n/- Extract the type part of a type-annotated Clight expression. -/\n\ndef typeof : expr \u2192 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 \u2192 expr \u2192 statement      /- assignment [lvalue = rvalue] -/\n| Sset        : ident \u2192 expr \u2192 statement     /- assignment [tempvar = rvalue] -/\n| Scall       : option ident \u2192 expr \u2192 list expr \u2192 statement\n                                             /- function call -/\n| Sbuiltin    : option ident \u2192 external_function \u2192 list type \u2192 list expr \u2192 statement\n                                             /- builtin invocation -/\n| Ssequence   : statement \u2192 statement \u2192 statement\n                                             /- sequence -/\n| Sifthenelse : expr \u2192 statement \u2192 statement \u2192 statement\n                                             /- conditional -/\n| Sloop       : statement \u2192 statement \u2192 statement\n                                             /- infinite loop -/\n| Sbreak      : statement                    /- [break] statement -/\n| Scontinue   : statement                    /- [continue] statement -/\n| Sreturn     : option expr \u2192 statement      /- [return] statement -/\n| Sswitch     : expr \u2192 list (option \u2124 \u00d7 statement) \u2192 statement\n                                             /- [switch] statement -/\n                                             /- [None] is [default], [Some x] is [case x] -/\n| Slabel      : label \u2192 statement \u2192 statement\n| Sgoto       : label \u2192 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 \u00d7 type))\n(vars : list (ident \u00d7 type))\n(temps : list (ident \u00d7 type))\n(body : statement)\n\n\ndef var_names (vars : list (ident \u00d7 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 \u2192 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) := \u27e8genv.genv\u27e9\ninstance coe_genv_cenv : has_coe genv composite_env := \u27e8genv.cenv\u27e9\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 \u00d7 type). /- map variable -> location & type -/\n\ndef empty_env : env := (\u2205 : PTree (block \u00d7 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 \u2192 Prop\n| deref_loc_value (chunk v) :\n      access_mode ty = By_value chunk \u2192\n      loadv chunk m (Vptr b ofs) = some v \u2192\n      deref_loc v\n| deref_loc_reference :\n      access_mode ty = By_reference \u2192\n      deref_loc (Vptr b ofs)\n| deref_loc_copy :\n      access_mode ty = By_copy \u2192\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 \u2192 mem \u2192 Prop\n| assign_loc_value (v chunk m') :\n      access_mode ty = By_value chunk \u2192\n      storev chunk m (Vptr b ofs) v = some m' \u2192\n      assign_loc v m'\n| assign_loc_copy (b' ofs' bytes m') :\n      access_mode ty = By_copy \u2192\n      (sizeof ce ty > 0 \u2192\n        alignof_blockcopy ce ty \u2223 unsigned ofs' \u2227 \n        alignof_blockcopy ce ty \u2223 unsigned ofs) \u2192\n      b' \u2260 b \u2228 unsigned ofs' = unsigned ofs\n              \u2228 unsigned ofs' + sizeof ce ty \u2264 unsigned ofs\n              \u2228 unsigned ofs + sizeof ce ty \u2264 unsigned ofs' \u2192\n      load_bytes m b' (unsigned ofs') (sizeof ce ty) = some bytes \u2192\n      store_bytes m b (unsigned ofs) bytes = some m' \u2192\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 \u2192 mem \u2192 list (ident \u00d7 type) \u2192 env \u2192 mem \u2192 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 \u2192\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 \u2192 list (ident \u00d7 type) \u2192 list val \u2192 mem \u2192 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) \u2192\n      assign_loc ge ty m b 0 v1 m1 \u2192\n      bind_parameters m1 params vl m2 \u2192\n      bind_parameters m ((id, ty) :: params) (v1 :: vl) m2\n\n/- Initialization of temporary variables -/\n\ndef create_undef_temps : list (ident \u00d7 type) \u2192 temp_env\n| [] := (\u2205 : 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 \u00d7 type) \u2192 list val \u2192 temp_env \u2192 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 \u00d7 block \u00d7 type \u2192 block \u00d7 \u2115 \u00d7 \u2115\n| (id, b, ty) := (b, 0, sizeof ge ty)\n\ndef blocks_of_env (e : env) : list (block \u00d7 \u2115 \u00d7 \u2115) :=\n(PTree.elements e).map block_of_binding\n\n/- Optional assignment to a temporary -/\n\ndef set_opttemp : option ident \u2192 val \u2192 temp_env \u2192 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 \u2124 \u00d7 statement)\n\ndef select_switch_default : labeled_statements \u2192 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 : \u2124) : labeled_statements \u2192 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 : \u2124) (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 \u2192 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 \u2192 val \u2192 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 \u2192\n      eval_expr (Etempvar id ty) v\n| eval_Eaddrof (a ty loc ofs) :\n      eval_lvalue a loc ofs \u2192\n      eval_expr (Eaddrof a ty) (Vptr loc ofs)\n| eval_Eunop (op a ty v1 v) :\n      eval_expr a v1 \u2192\n      sem_unary_operation op m v1 (typeof a) = some v \u2192\n      eval_expr (Eunop op a ty) v\n| eval_Ebinop (op a1 a2 ty v1 v2 v) :\n      eval_expr a1 v1 \u2192\n      eval_expr a2 v2 \u2192\n      sem_binary_operation ge op m v1 (typeof a1) v2 (typeof a2) = some v \u2192\n      eval_expr (Ebinop op a1 a2 ty) v\n| eval_Ecast (a ty v1 v) :\n      eval_expr a v1 \u2192\n      sem_cast m v1 (typeof a) ty = some v \u2192\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 \u2192\n      deref_loc (typeof a) m loc ofs v \u2192\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 \u2192 block \u2192 ptrofs \u2192 Prop\n| eval_Evar_local (id l ty) :\n      (e^!id) = some (l, ty) \u2192\n      eval_lvalue (Evar id ty) l 0\n| eval_Evar_global (id l ty) :\n      (e^!id) = none \u2192\n      Genv.find_symbol ge.genv id = some l \u2192\n      eval_lvalue (Evar id ty) l 0\n| eval_Ederef (a ty l ofs) :\n      eval_expr a (Vptr l ofs) \u2192\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) \u2192\n      typeof a = Tstruct id att \u2192\n      (ge.cenv^!id) = some co \u2192\n      field_offset ge i co.co_members = OK delta \u2192\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) \u2192\n      typeof a = Tunion id att \u2192\n      (ge.cenv^!id) = some co \u2192\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 \u2192 list type \u2192 list val \u2192 Prop\n| nil : eval_exprlist [] [] []\n| cons (a bl ty tyl v1 v2 vl) :\n      eval_expr a v1 \u2192\n      sem_cast m v1 (typeof a) ty = some v2 \u2192\n      eval_exprlist bl tyl vl \u2192\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 \u2192 cont \u2192 cont       /- [Kseq s2 k] = after [s1] in [s1;s2] -/\n| Kloop1 : statement \u2192 statement \u2192 cont \u2192 cont /- [Kloop1 s1 s2 k] = after [s1] in [Sloop s1 s2] -/\n| Kloop2 : statement \u2192 statement \u2192 cont \u2192 cont /- [Kloop1 s1 s2 k] = after [s2] in [Sloop s1 s2] -/\n| Kswitch : cont \u2192 cont       /- catches [break] statements arising out of [switch] -/\n| Kcall : option ident \u2192                  /- where to store result -/\n          function \u2192                      /- calling function -/\n          env \u2192                           /- local env of calling function -/\n          temp_env \u2192                      /- temporary env of calling function -/\n          cont \u2192 cont\nopen cont\n\n/- Pop continuation until a call or stop -/\n\ndef call_cont : cont \u2192 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 \u2192 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 \u2192 cont \u2192 option (statement \u00d7 cont)\n| (Ssequence s1 s2)     := \u03bbk, find_label s1 (Kseq s2 k) <|> find_label s2 k\n| (Sifthenelse a s1 s2) := \u03bbk, find_label s1 k <|> find_label s2 k\n| (Sloop s1 s2)         := \u03bbk, find_label s1 (Kloop1 s1 s2 k) <|> find_label s2 (Kloop2 s1 s2 k)\n| (Sswitch e sl)        := \u03bbk, find_label_ls sl (Kswitch k)\n| (Slabel lbl' s')      := \u03bbk, if lbl = lbl' then some (s', k) else find_label s' k\n| _                     := \u03bbk, none\nwith find_label_ls : list (option \u2124 \u00d7 statement) \u2192 cont \u2192 option (statement \u00d7 cont)\n| []                    := \u03bbk, none\n| ((_, s) :: sl')       := \u03bbk, 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 \u2192 list val \u2192 mem \u2192 env \u2192 temp_env \u2192 mem \u2192 Prop\n\n/- Transition relation -/\n\ninductive step : state \u2192 trace \u2192 state \u2192 Prop :=\n\n| step_assign :   \u2200 f a1 a2 k e le m loc ofs v2 v m',\n      eval_lvalue e le m a1 loc ofs \u2192\n      eval_expr e le m a2 v2 \u2192\n      sem_cast v2 (typeof a2) (typeof a1) m = some v \u2192\n      assign_loc ge (typeof a1) m loc ofs v m' \u2192\n      step (State f (Sassign a1 a2) k e le m)\n        E0 (State f Sskip k e le m')\n\n| step_set :   \u2200 f id a k e le m v,\n      eval_expr e le m a v \u2192\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 :   \u2200 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 \u2192\n      eval_expr e le m a vf \u2192\n      eval_exprlist e le m al tyargs vargs \u2192\n      Genv.find_funct ge vf = some fd \u2192\n      type_of_fundef fd = Tfunction tyargs tyres cconv \u2192\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 :   \u2200 f optid ef tyargs al k e le m vargs t vres m',\n      eval_exprlist e le m al tyargs vargs \u2192\n      external_call ef ge vargs m t vres m' \u2192\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 :  \u2200 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 : \u2200 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 : \u2200 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 : \u2200 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 :  \u2200 f a s1 s2 k e le m v1 b,\n      eval_expr e le m a v1 \u2192\n      bool_val v1 (typeof a) m = some b \u2192\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 : \u2200 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 :  \u2200 f s1 s2 k e le m x,\n      x = Sskip \u2228 x = Scontinue \u2192\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 :  \u2200 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 : \u2200 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 : \u2200 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 : \u2200 f k e le m m',\n      Mem.free_list m (blocks_of_env e) = some m' \u2192\n      step (State f (Sreturn none) k e le m)\n        E0 (Returnstate Vundef (call_cont k) m')\n| step_return_1 : \u2200 f a k e le m v v' m',\n      eval_expr e le m a v \u2192\n      sem_cast v (typeof a) f.(fn_return) m = some v' \u2192\n      Mem.free_list m (blocks_of_env e) = some m' \u2192\n      step (State f (Sreturn (some a)) k e le m)\n        E0 (Returnstate v' (call_cont k) m')\n| step_skip_call : \u2200 f k e le m m',\n      is_call_cont k \u2192\n      Mem.free_list m (blocks_of_env e) = some m' \u2192\n      step (State f Sskip k e le m)\n        E0 (Returnstate Vundef k m')\n\n| step_switch : \u2200 f a sl k e le m v n,\n      eval_expr e le m a v \u2192\n      sem_switch_arg v (typeof a) = some n \u2192\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 : \u2200 f x k e le m,\n      x = Sskip \u2228 x = Sbreak \u2192\n      step (State f x (Kswitch k) e le m)\n        E0 (State f Sskip k e le m)\n| step_continue_switch : \u2200 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 : \u2200 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 : \u2200 f lbl k e le m s' k',\n      find_label lbl f.(fn_body) (call_cont k) = some (s', k') \u2192\n      step (State f (Sgoto lbl) k e le m)\n        E0 (State f s' k' e le m)\n\n| step_internal_function : \u2200 f vargs k m e le m1,\n      function_entry f vargs m e le m1 \u2192\n      step (Callstate (Internal f) vargs k m)\n        E0 (State f f.(fn_body) k e le m1)\n\n| step_external_function : \u2200 ef targs tres cconv vargs k m vres t m',\n      external_call ef ge vargs m t vres m' \u2192\n      step (Callstate (External ef targs tres cconv) vargs k m)\n         t (Returnstate vres k m')\n\n| step_returnstate : \u2200 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 \u2192 Prop :=\n| initial_state_intro : \u2200 b f m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = some m0 \u2192\n      Genv.find_symbol ge p.(prog_main) = some b \u2192\n      Genv.find_funct_ptr ge b = some f \u2192\n      type_of_fundef f = Tfunction Tnil type_int32s cc_default \u2192\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 \u2192 int32 \u2192 Prop :=\n| final_state_intro : \u2200 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 : \u2200 m1,\n      list_norepet (var_names f.(fn_params) ++ var_names f.(fn_vars)) \u2192\n      alloc_variables ge empty_env m (f.(fn_params) ++ f.(fn_vars)) e m1 \u2192\n      bind_parameters ge e m1 f.(fn_params) vargs m' \u2192\n      le = create_undef_temps f.(fn_temps) \u2192\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)) \u2192\n      list_norepet (var_names f.(fn_params)) \u2192\n      list_disjoint (var_names f.(fn_params)) (var_names f.(fn_temps)) \u2192\n      alloc_variables ge empty_env m f.(fn_vars) e m' \u2192\n      bind_parameter_temps f.(fn_params) vargs (create_undef_temps f.(fn_temps)) = some le \u2192\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  \u2200 (p : program), receptive (semantics1 p)\nProof\n  intros. unfold semantics1\n  set (ge := globalenv p). constructor; simpl; intros\n/- receptiveness -/\n  assert (t1 = E0 \u2192 \u2203 s2, step1 ge s t2 s2)\n    intros. subst. inv H0. \u2203 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  \u2203 (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": "import .util\n\nsection tactic\nopen tactic\nopen interaction_monad.result\nmeta def tactic.try_verbose {\u03b1} (tac : tactic \u03b1) : tactic unit := \u03bb s, match tac s with\n| (exception msg pos state) := match msg with\n  | (some thunk) := (tactic.trace format! \"[try_verbose] FAILURE: {thunk ()}\") s\n  | none := success () s\n  end\n| (success _ s') := success () s'\nend\n\nend tactic\n\nsection mfold_with_binders\n\nnamespace expr\n\n-- this should satisfy the following invariants:\n-- the variable binding list should only inherit from higher binders, so there is a tree of local bindings\n-- the accumulator \u03b1, however, should be folded across the entire tree\nmeta def expr.mfold_with_binders_aux {\u03b1 : Type} : expr \u2192 \u03b1 \u2192 (list expr) \u2192 (expr \u2192 \u03b1 \u2192 (list expr) \u2192 tactic \u03b1) \u2192 (tactic \u03b1)\n| e@(var k) acc bs f := f e acc bs\n| e@(sort l) acc bs f := f e acc bs\n| e@(const nm ls) acc bs f := f e acc bs\n| e@(mvar _ _ _) acc bs f := f e acc bs\n| e@(local_const _ _ _ _) acc bs f := f e acc bs\n| e@(app e\u2081 e\u2082) acc bs f := do {\n    r\u2080 \u2190 f e acc bs,\n    r\u2081 \u2190 expr.mfold_with_binders_aux e\u2081 r\u2080 bs f,\n    r\u2082 \u2190 expr.mfold_with_binders_aux e\u2082 r\u2081 bs f,\n    pure r\u2082\n  }\n| e@(lam var_name b_info var_type body) acc bs f := do {\n    \u27e8[b], e'\u27e9 \u2190 tactic.open_n_lambdas e 1,\n    r \u2190 expr.mfold_with_binders_aux e' acc (b::bs) f,\n    pure r\n  }\n| e@(pi var_name b_info var_type body) acc bs f := do {\n    \u27e8[b], e'\u27e9 \u2190 tactic.open_n_pis e 1,\n    r \u2190 expr.mfold_with_binders_aux e' acc (b::bs) f,\n    pure r\n  }\n| e@(elet var_name var_type var_assignment body) acc bs f := do {\n    expr.mfold_with_binders_aux e.reduce_let acc bs f\n  }\n| e@(macro _ _) acc bs f := do {\n  (e.unfold_macros) >>= (\u03bb x, f x acc bs)\n}\n\nmeta def mfold_with_binders {\u03b1 : Type} : expr \u2192 \u03b1 \u2192 (expr \u2192 \u03b1 \u2192 (list expr) \u2192 tactic \u03b1) \u2192 tactic \u03b1 :=\n\u03bb e acc f, expr.mfold_with_binders_aux e acc [] f\n\nend expr\n\nend mfold_with_binders\n\nsection generic\n\n-- TODO(): probably buggy! don't trust io.fs.get_line\nmeta def readlines (f : io.handle) : io (list string) := do {\n  ls \u2190 io.iterate [] (\u03bb acc, do {\n     do {\n      r \u2190 buffer.to_string <$> io.fs.get_line f,\n      mcond (io.fs.is_eof f) (pure none) $ do\n      -- io.put_str_ln $ \"GOT STRING: \" ++ r,\n      pure \u2218 pure $ acc ++ [r]\n    }\n  }),\n  pure ls\n}\n\n-- note(): use this instead\nmeta def readlines' (f : io.handle) : io (list string) := do {\n  list.filter (\u03bb x, !(x = \"\")) <$> (string.split (= '\\n') <$> buffer.to_string <$> io.fs.read_to_end f)\n}\n\nmeta def dump_step\n  {datapoint_type : Type}\n  {worker_fn_options_type : Type}\n  (r : tactic.ref \u2115)\n  (decl : declaration)\n  (dest_handle : io.handle)\n  (serialization_guard : datapoint_type \u2192 tactic bool)\n  (worker_fn : expr \u2192 worker_fn_options_type \u2192 tactic (list datapoint_type))\n  (serialization_fn : datapoint_type \u2192 tactic string)\n  (worker_fn_options : worker_fn_options_type)\n  (desc : string)\n: tactic unit :=\ndo {\n  tactic.trace format!\"[dump_{desc}_step] PROCESSING DECL {decl.to_name}\",\n  pf \u2190 tactic.get_proof decl,\n  dps \u2190 worker_fn pf worker_fn_options,\n  for_ dps $ \u03bb dp, do {\n    mcond (bnot <$> serialization_guard dp) (pure ()) $ do\n    msg \u2190 serialization_fn dp,\n    tactic.unsafe_run_io $ io.fs.put_str_ln dest_handle msg\n  },\n  tactic.modify_ref r nat.succ\n}\n\n/- TODO(): it is inefficient to eagerly produce an entire list of datapoints first before serialization.\n  In practice, this seems to work OK, but we might hit performance problems when we try to do everything at once\n  might be better to make `serialization_fn` an argument to `worker_fn` and have it write datapoints to the file\n  in a loop. -/\nmeta def dump_from_decls_file\n  /- `datapoint_type` and `worker_fn_options_type` should be inferred automatically from `worker_fn` -/\n  {datapoint_type : Type}\n  {worker_fn_options_type : Type}\n\n  /- used to populate stdout trace message -/\n  (desc : string)\n  /- file containing a list of Lean declarations -/\n  (decls_file : string)\n  /- destination filepath for the serialized datapoints -/\n  (dest : string)\n  /- returns tt if OK to serialize-/\n  (serialization_guard : datapoint_type \u2192 tactic bool)\n  /- responsible for extracting a list of datapoints from the declaration -/\n  (worker_fn : expr \u2192 worker_fn_options_type \u2192 tactic (list datapoint_type))\n  /- responsible for writing the datapoint_type to a string, which is then written to the file -/\n  (serialization_fn : datapoint_type \u2192 tactic string)\n  /- configuration (e.g. recursion limits) for the worker_fn, which is responsible for extracting datapoints -/\n  (worker_fn_options : worker_fn_options_type)\n\n: io unit := do {\n  nm_strs \u2190 io.mk_file_handle decls_file io.mode.read >>= readlines',\n  (nms : list (name \u00d7 list name)) \u2190 (nm_strs.filter $ \u03bb nm_str, string.length nm_str > 0).mmap $ \u03bb nm_str, do {\n    ((io.run_tactic' \u2218 parse_decl_nm_and_open_ns) $ nm_str)\n  },\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n  io.run_tactic $ do {\n    env \u2190 tactic.get_env,\n    let total := nms.length,\n    tactic.trace format!\"TOTAL: {total}\",\n    tactic.using_new_ref (0 : \u2115) $ \u03bb r,\n    for_ nms $ \u03bb \u27e8nm, _\u27e9, do {\n      decl \u2190 optional (env.get nm),\n      match decl with\n      | (some decl) := do {\n          dump_step r decl dest_handle serialization_guard worker_fn serialization_fn worker_fn_options desc\n        }\n      | none := do {\n        tactic.trace format!\"[WARNING] COULDN'T RESOLVE {nm}\",\n        tactic.modify_ref r nat.succ\n      }\n      end,\n      count \u2190 tactic.read_ref r,\n      tactic.trace format!\"PROGRESS: {count}/{total}\"\n    }\n  }\n}\n\nend generic\n\nsection premise_selection\n\nmeta def gather_used_premises : expr \u2192 tactic (list expr) := \u03bb e,\n  let fn : expr \u2192 list expr \u2192 list expr \u2192 tactic (list expr) := \u03bb e acc bs, do {\n    match e with\n      | ex@(expr.const nm levels) := mcond (tactic.is_proof ex) (pure $ ex::acc) (pure acc)\n      | _ := pure acc\n    end\n  } in\n  e.mfold_with_binders [] fn\n\nmeta def mk_type_annotation : expr \u2192 tactic (expr \u00d7 expr) :=\n\u03bb h, prod.mk h <$> tactic.infer_type h\n\nend premise_selection\n\nsection pp\n\nmeta def enable_verbose : tactic unit := do {\n-- tactic.set_bool_option `pp.implicit true\n  tactic.set_bool_option `pp.all true,\n  tactic.set_bool_option `pp.implicit true, -- TODO(): can we get away with setting this `false`? this blows up the proof terms by a LOT\n  tactic.set_bool_option `pp.universes false,\n  tactic.set_bool_option `pp.notation true,\n  tactic.set_bool_option `pp.generalized_field_notation true,\n  tactic.set_bool_option `pp.structure_projections true,\n  tactic.set_bool_option `pp.beta true,\n  tactic.set_bool_option `pp.binder_types true,\n  tactic.set_nat_option `pp.max_depth 128,\n  tactic.set_nat_option `pp.max_steps 10000\n}\n\nmeta def with_verbose {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\ntactic.save_options $ enable_verbose *> tac\n\nend pp\n\nsection test_lemmas\n  -- GOAL P Q : Prop \u22a2 ((P \u2192 Q) \u2192 P) \u2192 P PROOFSTEP apply or.elim (em P)\n  -- GOAL P Q : Prop \u22a2 P \u2192 ((P \u2192 Q) \u2192 P) \u2192 P  P Q : Prop \u22a2 \u00acP \u2192 ((P \u2192 Q) \u2192 P) \u2192 P PROOFSTEP intros h _\n  -- GOAL P Q : Prop, h : P, \u1fb0 : (P \u2192 Q) \u2192 P \u22a2 P  P Q : Prop \u22a2 \u00acP \u2192 ((P \u2192 Q) \u2192 P) \u2192 P PROOFSTEP exact h\n  -- GOAL P Q : Prop \u22a2 \u00acP \u2192 ((P \u2192 Q) \u2192 P) \u2192 P PROOFSTEP tauto!\nlemma peirce_identity {P Q :Prop} : ((P \u2192 Q) \u2192 P) \u2192 P :=\nbegin\n  apply or.elim (em P),\n  intros h _,\n  exact h,\n  tauto!\nend\n\nend test_lemmas\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/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606815201671963, "lm_q2_score": 0.031143832895315228, "lm_q1q2_score": 0.012335080341565025}}
{"text": "theorem unsound : False := -- Error\n  unsound\n\npartial theorem unsound2 : False := -- Error\n  unsound2\n\nunsafe theorem unsound3 : False := -- Error\n  unsound3\n\nopaque unsound4 : False  -- Error\n\naxiom magic : False -- OK\nnamespace Foo\npartial def foo (x : Nat) : Nat := foo x  -- OK\n\nunsafe def unsound2 : False := unsound  -- OK\n\npartial def unsound3 : False := unsound3  -- Error\n\npartial def unsound4 (x : Unit) : False := unsound4 ()  -- Error\n\npartial def badcast1 (x : Nat) : Bool :=\n  unsafeCast x -- Error: partial cannot use unsafe constant\n\npartial def badcast2 (x : Nat) : Bool :=\n  if x == 0 then unsafeCast x -- Error: partial cannot use unsafe constant\n  else badcast2 (x + 1)\n\nunsafe def badcast3 (x : Nat) : Bool := -- OK\n  if x == 0 then unsafeCast x\n  else badcast3 (x + 1)\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/sanitychecks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.04146226871393072, "lm_q1q2_score": 0.01233377817813223}}
{"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-- \u03b1 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 {\u03b1 : Type}\n\ninductive TacticScript (\u03b1 : Type) : Type\n  | base : \u03b1 \u2192 tactic_script\n  | work (index : \u2115) (first : \u03b1) (later : List tactic_script) (closed : Bool) : tactic_script\n#align tactic.tactic_script Tactic.TacticScript\n\nunsafe def tactic_script.to_string : TacticScript String \u2192 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 \u2192 tactic \u03b1) (g : expr) : tactic \u03b1 := do\n  let type \u2190 infer_type g\n  let is_lemma \u2190 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 \u2190 mk_meta_var type\n      let a \u2190 tac m\n      (do\n            let val \u2190 instantiate_mvars m\n            guard (val = [])\n            let c \u2190 new_aux_decl_name\n            let gs \u2190 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 {\u03b1} (tac : tactic \u03b1) : expr \u2192 tactic (\u03b1 \u00d7 List (TacticScript \u03b1))\n    | g => do\n      set_goals [g]\n      let a \u2190 tac\n      let l \u2190 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 {\u03b1} (tac : tactic \u03b1) : List expr \u2192 tactic (List (TacticScript \u03b1))\n    | [] => return []\n    | [g] =>\n      (do\n          let (a, l) \u2190 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 {\u03b1} (tac : tactic \u03b1) :\n      List expr \u2192 List expr \u2192 tactic (List (TacticScript \u03b1))\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) \u2190 abstract_if_success chain_single g\n          let new_goals \u2190 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' \u2190 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 {\u03b1 : Type} [ToString (TacticScript \u03b1)] (tactics : List (tactic \u03b1)) :\n    tactic (List String) := do\n  let results \u2190 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 \u03b1)] [has_to_format \u03b1]\n\ninitialize\n  registerTraceClass.1 `chain\n\nunsafe def trace_output (t : tactic \u03b1) : tactic \u03b1 := do\n  let tgt \u2190 target\n  let r \u2190 t\n  let name \u2190 decl_name\n  trace f! \"`chain` successfully applied a tactic during elaboration of {Name}:\"\n  let tgt \u2190 pp tgt\n  trace f! \"previous target: {tgt}\"\n  trace f! \"tactic result: {r}\"\n  let tgt \u2190 try_core target\n  let tgt \u2190\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 \u03b1)) : 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": "/-\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 Init.Prelude\nimport Init.SizeOf\n\nuniverses u v w\n\ndef inline {\u03b1 : Sort u} (a : \u03b1) : \u03b1 := a\n\n@[inline] def flip {\u03b1 : Sort u} {\u03b2 : Sort v} {\u03c6 : Sort w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6) : \u03b2 \u2192 \u03b1 \u2192 \u03c6 :=\n  fun b a => f a b\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 (\u03b1 : Type u) : Type u where\n  -- TODO: make private\n  fn : Unit \u2192 \u03b1\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 : \u03b1) : Thunk \u03b1 :=\n  \u27e8fun _ => a\u27e9\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 \u03b1) : \u03b1 :=\n  x.fn ()\n@[inline] protected def Thunk.map (f : \u03b1 \u2192 \u03b2) (x : Thunk \u03b1) : Thunk \u03b2 :=\n  \u27e8fun _ => f x.get\u27e9\n@[inline] protected def Thunk.bind (x : Thunk \u03b1) (f : \u03b1 \u2192 Thunk \u03b2) : Thunk \u03b2 :=\n  \u27e8fun _ => (f x.get).get\u27e9\n\nabbrev Eq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : \u03b1 \u2192 Sort u1} {b : \u03b1} (h : a = b) (m : motive a) : motive b :=\n  Eq.ndrec m h\n\nstructure Iff (a b : Prop) : Prop where\n  intro :: (mp : a \u2192 b) (mpr : b \u2192 a)\n\ninfix:20 \" <-> \" => Iff\ninfix:20 \" \u2194 \"   => Iff\n\ninductive Sum (\u03b1 : Type u) (\u03b2 : Type v) where\n  | inl (val : \u03b1) : Sum \u03b1 \u03b2\n  | inr (val : \u03b2) : Sum \u03b1 \u03b2\n\ninductive PSum (\u03b1 : Sort u) (\u03b2 : Sort v) where\n  | inl (val : \u03b1) : PSum \u03b1 \u03b2\n  | inr (val : \u03b2) : PSum \u03b1 \u03b2\n\nstructure Sigma {\u03b1 : Type u} (\u03b2 : \u03b1 \u2192 Type v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\nattribute [unbox] Sigma\n\nstructure PSigma {\u03b1 : Sort u} (\u03b2 : \u03b1 \u2192 Sort v) where\n  fst : \u03b1\n  snd : \u03b2 fst\n\ninductive Exists {\u03b1 : Sort u} (p : \u03b1 \u2192 Prop) : Prop where\n  | intro (w : \u03b1) (h : p w) : Exists p\n\n/- Auxiliary type used to compile `for x in xs` notation. -/\ninductive ForInStep (\u03b1 : Type u) where\n  | done  : \u03b1 \u2192 ForInStep \u03b1\n  | yield : \u03b1 \u2192 ForInStep \u03b1\n\nclass ForIn (m : Type u\u2081 \u2192 Type u\u2082) (\u03c1 : Type u) (\u03b1 : outParam (Type v)) where\n  forIn {\u03b2} [Monad m] (x : \u03c1) (b : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2\n\nexport ForIn (forIn)\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPRBC (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultPRBC \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultPR (\u03b1 \u03b2 \u03c3 : Type u) where\n  | \u00abpure\u00bb     : \u03b1 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n  | \u00abreturn\u00bb   : \u03b2 \u2192 \u03c3 \u2192 DoResultPR \u03b1 \u03b2 \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultBC (\u03c3 : Type u) where\n  | \u00abbreak\u00bb    : \u03c3 \u2192 DoResultBC \u03c3\n  | \u00abcontinue\u00bb : \u03c3 \u2192 DoResultBC \u03c3\n\n/- Auxiliary type used to compile `do` notation. -/\ninductive DoResultSBC (\u03b1 \u03c3 : Type u) where\n  | \u00abpureReturn\u00bb : \u03b1 \u2192 \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abbreak\u00bb      : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n  | \u00abcontinue\u00bb   : \u03c3 \u2192 DoResultSBC \u03b1 \u03c3\n\nclass HasEquiv  (\u03b1 : Sort u) where\n  Equiv : \u03b1 \u2192 \u03b1 \u2192 Sort v\n\ninfix:50 \" \u2248 \"  => HasEquiv.Equiv\n\nclass EmptyCollection (\u03b1 : Type u) where\n  emptyCollection : \u03b1\n\nnotation \"{\" \"}\" => EmptyCollection.emptyCollection\nnotation \"\u2205\"     => EmptyCollection.emptyCollection\n\n/- Remark: tasks have an efficient implementation in the runtime. -/\nstructure Task (\u03b1 : Type u) : Type u where\n  pure :: (get : \u03b1)\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\ndef Priority.default : Priority := 0\n-- see `LEAN_MAX_PRIO`\ndef Priority.max : Priority := 8\n/--\n  Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.\n  This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more\n  non-dedicated workers than the number of cores to reduce context switches. -/\ndef Priority.dedicated : Priority := 9\n\n@[noinline, extern \"lean_task_spawn\"]\nprotected def spawn {\u03b1 : Type u} (fn : Unit \u2192 \u03b1) (prio := Priority.default) : Task \u03b1 :=\n  \u27e8fn ()\u27e9\n\n@[noinline, extern \"lean_task_map\"]\nprotected def map {\u03b1 : Type u} {\u03b2 : Type v} (f : \u03b1 \u2192 \u03b2) (x : Task \u03b1) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8f x.get\u27e9\n\n@[noinline, extern \"lean_task_bind\"]\nprotected def bind {\u03b1 : Type u} {\u03b2 : Type v} (x : Task \u03b1) (f : \u03b1 \u2192 Task \u03b2) (prio := Priority.default) : Task \u03b2 :=\n  \u27e8(f x.get).get\u27e9\n\nend Task\n\n/- Some type that is not a scalar value in our runtime. -/\nstructure NonScalar where\n  val : Nat\n\n/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/\ninductive PNonScalar : Type u where\n  | mk (v : Nat) : PNonScalar\n\ntheorem natAddZero (n : Nat) : n + 0 = n := rfl\n\ntheorem optParamEq (\u03b1 : Sort u) (default : \u03b1) : optParam \u03b1 default = \u03b1 := rfl\n\n/- Boolean operators -/\n\n@[extern c inline \"#1 || #2\"] def strictOr  (b\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\n@[extern c inline \"#1 && #2\"] def strictAnd (b\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\n\n@[inline] def bne {\u03b1 : Type u} [BEq \u03b1] (a b : \u03b1) : Bool :=\n  !(a == b)\n\ninfix:50 \" != \" => bne\n\n/- Logical connectives an equality -/\n\ndef implies (a b : Prop) := a \u2192 b\n\ntheorem implies.trans {p q r : Prop} (h\u2081 : implies p q) (h\u2082 : implies q r) : implies p r :=\n  fun hp => h\u2082 (h\u2081 hp)\n\ndef trivial : True := \u27e8\u27e9\n\ntheorem mt {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : \u00acb) : \u00aca :=\n  fun ha => h\u2082 (h\u2081 ha)\n\ntheorem notFalse : \u00acFalse := id\n\n-- proof irrelevance is built in\ntheorem proofIrrel {a : Prop} (h\u2081 h\u2082 : a) : h\u2081 = h\u2082 := rfl\n\ntheorem id.def {\u03b1 : Sort u} (a : \u03b1) : id a = a := rfl\n\n@[macroInline] def Eq.mp {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (a : \u03b1) : \u03b2 :=\n  h \u25b8 a\n\n@[macroInline] def Eq.mpr {\u03b1 \u03b2 : Sort u} (h : \u03b1 = \u03b2) (b : \u03b2) : \u03b1 :=\n  h \u25b8 b\n\ntheorem Eq.substr {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {a b : \u03b1} (h\u2081 : b = a) (h\u2082 : p a) : p b :=\n  h\u2081 \u25b8 h\u2082\n\ntheorem castEq {\u03b1 : Sort u} (h : \u03b1 = \u03b1) (a : \u03b1) : cast h a = a :=\n  rfl\n\n@[reducible] def Ne {\u03b1 : Sort u} (a b : \u03b1) :=\n  \u00ac(a = b)\n\ninfix:50 \" \u2260 \"  => Ne\n\nsection Ne\nvariable {\u03b1 : Sort u}\nvariable {a b : \u03b1} {p : Prop}\n\ntheorem Ne.intro (h : a = b \u2192 False) : a \u2260 b := h\n\ntheorem Ne.elim (h : a \u2260 b) : a = b \u2192 False := h\n\ntheorem Ne.irrefl (h : a \u2260 a) : False := h rfl\n\ntheorem Ne.symm (h : a \u2260 b) : b \u2260 a :=\n  fun h\u2081 => h (h\u2081.symm)\n\ntheorem falseOfNe : a \u2260 a \u2192 False := Ne.irrefl\n\ntheorem neFalseOfSelf : p \u2192 p \u2260 False :=\n  fun (hp : p) (h : p = False) => h \u25b8 hp\n\ntheorem neTrueOfNot : \u00acp \u2192 p \u2260 True :=\n  fun (hnp : \u00acp) (h : p = True) =>\n    have : \u00acTrue := h \u25b8 hnp\n    this trivial\n\ntheorem trueNeFalse : \u00acTrue = False :=\n  neFalseOfSelf trivial\n\nend Ne\n\nsection\nvariable {\u03b1 \u03b2 \u03c6 : Sort u} {a a' : \u03b1} {b b' : \u03b2} {c : \u03c6}\n\ntheorem HEq.ndrec.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} (m : motive a) {\u03b2 : Sort u2} {b : \u03b2} (h : a \u2245 b) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.ndrecOn.{u1, u2} {\u03b1 : Sort u2} {a : \u03b1} {motive : {\u03b2 : Sort u2} \u2192 \u03b2 \u2192 Sort u1} {\u03b2 : Sort u2} {b : \u03b2} (h : a \u2245 b) (m : motive a) : motive b :=\n  @HEq.rec \u03b1 a (fun b _ => motive b) m \u03b2 b h\n\ntheorem HEq.elim {\u03b1 : Sort u} {a : \u03b1} {p : \u03b1 \u2192 Sort v} {b : \u03b1} (h\u2081 : a \u2245 b) (h\u2082 : p a) : p b :=\n  eqOfHEq h\u2081 \u25b8 h\u2082\n\ntheorem HEq.subst {p : (T : Sort u) \u2192 T \u2192 Prop} (h\u2081 : a \u2245 b) (h\u2082 : p \u03b1 a) : p \u03b2 b :=\n  HEq.ndrecOn h\u2081 h\u2082\n\ntheorem HEq.symm (h : a \u2245 b) : b \u2245 a :=\n  HEq.ndrecOn (motive := fun x => x \u2245 a) h (HEq.refl a)\n\ntheorem heqOfEq (h : a = a') : a \u2245 a' :=\n  Eq.subst h (HEq.refl a)\n\ntheorem HEq.trans (h\u2081 : a \u2245 b) (h\u2082 : b \u2245 c) : a \u2245 c :=\n  HEq.subst h\u2082 h\u2081\n\ntheorem heqOfHEqOfEq (h\u2081 : a \u2245 b) (h\u2082 : b = b') : a \u2245 b' :=\n  HEq.trans h\u2081 (heqOfEq h\u2082)\n\ntheorem heqOfEqOfHEq (h\u2081 : a = a') (h\u2082 : a' \u2245 b) : a \u2245 b :=\n  HEq.trans (heqOfEq h\u2081) h\u2082\n\ndef typeEqOfHEq (h : a \u2245 b) : \u03b1 = \u03b2 :=\n  HEq.ndrecOn (motive := @fun (x : Sort u) _ => \u03b1 = x) h (Eq.refl \u03b1)\n\nend\n\ntheorem eqRecHEq {\u03b1 : Sort u} {\u03c6 : \u03b1 \u2192 Sort v} {a a' : \u03b1} : (h : a = a') \u2192 (p : \u03c6 a) \u2192 (Eq.recOn (motive := fun x _ => \u03c6 x) h p) \u2245 p\n  | rfl, p => HEq.refl p\n\ntheorem heqOfEqRecEq {\u03b1 \u03b2 : Sort u} {a : \u03b1} {b : \u03b2} (h\u2081 : \u03b1 = \u03b2) (h\u2082 : Eq.rec (motive := fun \u03b1 _ => \u03b1) a h\u2081 = b) : a \u2245 b := by\n  subst h\u2081\n  apply heqOfEq\n  exact h\u2082\n\ntheorem castHEq {\u03b1 \u03b2 : Sort u} : (h : \u03b1 = \u03b2) \u2192 (a : \u03b1) \u2192 cast h a \u2245 a\n  | rfl, a => HEq.refl a\n\nvariable {a b c d : Prop}\n\ntheorem iffIffImpliesAndImplies (a b : Prop) : (a \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 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 \u2194 a :=\n  Iff.intro (fun h => h) (fun h => h)\n\ntheorem Iff.rfl {a : Prop} : a \u2194 a :=\n  Iff.refl a\n\ntheorem Iff.trans (h\u2081 : a \u2194 b) (h\u2082 : b \u2194 c) : a \u2194 c :=\n  Iff.intro\n    (fun ha => Iff.mp h\u2082 (Iff.mp h\u2081 ha))\n    (fun hc => Iff.mpr h\u2081 (Iff.mpr h\u2082 hc))\n\ntheorem Iff.symm (h : a \u2194 b) : b \u2194 a :=\n  Iff.intro (Iff.mpr h) (Iff.mp h)\n\ntheorem Iff.comm : (a \u2194 b) \u2194 (b \u2194 a) :=\n  Iff.intro Iff.symm Iff.symm\n\n/- Exists -/\n\ntheorem Exists.elim {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} {b : Prop}\n   (h\u2081 : Exists (fun x => p x)) (h\u2082 : \u2200 (a : \u03b1), p a \u2192 b) : b :=\n  h\u2082 h\u2081.1 h\u2081.2\n\n/- Decidable -/\n\ntheorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=\n  match h with\n  | isTrue h  => rfl\n  | isFalse h => False.elim <| h \u27e8\u27e9\n\ntheorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=\n  match h with\n  | isFalse h => 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 p (h := d)\n\ntheorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=\n  decideEqTrue (s := d) h\n\ntheorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=\n  ofDecideEqTrue (s := d) h\n\ntheorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : \u00ac p :=\n  ofDecideEqFalse (s := d) h\n\ninstance : Decidable True :=\n  isTrue trivial\n\ninstance : Decidable False :=\n  isFalse notFalse\n\nnamespace Decidable\nvariable {p q : Prop}\n\n@[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p \u2192 q) (h2 : \u00acp \u2192 q) : q :=\n  match dec with\n  | isTrue h  => h1 h\n  | isFalse h => h2 h\n\ntheorem em (p : Prop) [Decidable p] : p \u2228 \u00acp :=\n  byCases Or.inl Or.inr\n\ntheorem byContradiction [dec : Decidable p] (h : \u00acp \u2192 False) : p :=\n  byCases id (fun np => False.elim (h np))\n\ntheorem ofNotNot [Decidable p] : \u00ac \u00ac p \u2192 p :=\n  fun hnn => byContradiction (fun hn => absurd hn hnn)\n\ntheorem notAndIffOrNot (p q : Prop) [d\u2081 : Decidable p] [d\u2082 : Decidable q] : \u00ac (p \u2227 q) \u2194 \u00ac p \u2228 \u00ac q :=\n  Iff.intro\n    (fun h => match d\u2081, d\u2082 with\n      | isTrue h\u2081,  isTrue h\u2082   => absurd (And.intro h\u2081 h\u2082) h\n      | _,           isFalse h\u2082 => Or.inr h\u2082\n      | isFalse h\u2081, _           => Or.inl h\u2081)\n    (fun (h) \u27e8hp, hq\u27e9 => 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@[inline] def  decidableOfDecidableOfIff (hp : Decidable p) (h : p \u2194 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@[inline] def  decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=\n  h \u25b8 hp\nend\n\n@[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p \u2192 q) :=\n  if hp : p then\n    if hq : q then isTrue (fun h => 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 \u2194 q) :=\n  if hp : p then\n    if hq : q then\n      isTrue \u27e8fun _ => hq, fun _ => hp\u27e9\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 \u27e8fun h => absurd h hp, fun h => absurd h hq\u27e9\n\n/- if-then-else expression theorems -/\n\ntheorem ifPos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = t :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem ifNeg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t e : \u03b1} : (ite c t e) = e :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\ntheorem difPos {c : Prop} [h : Decidable c] (hc : c) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = t hc :=\n  match h with\n  | isTrue  hc  => rfl\n  | isFalse hnc => absurd hc hnc\n\ntheorem difNeg {c : Prop} [h : Decidable c] (hnc : \u00acc) {\u03b1 : Sort u} {t : c \u2192 \u03b1} {e : \u00ac c \u2192 \u03b1} : (dite c t e) = e hnc :=\n  match h with\n  | isTrue hc   => absurd hc hnc\n  | isFalse hnc => rfl\n\n-- Remark: dite and ite are \"defally equal\" when we ignore the proofs.\ntheorem difEqIf (c : Prop) [h : Decidable c] {\u03b1 : Sort u} (t : \u03b1) (e : \u03b1) : dite c (fun h => t) (fun h => e) = ite c t e :=\n  match h with\n  | isTrue hc   => rfl\n  | isFalse hnc => 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 hc  => dT\n  | isFalse hc => dE\n\ninstance {c : Prop} {t : c \u2192 Prop} {e : \u00acc \u2192 Prop} [dC : Decidable c] [dT : \u2200 h, Decidable (t h)] [dE : \u2200 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/- Inhabited -/\n\ninstance : Inhabited Prop where\n  default := True\n\nderiving instance Inhabited for NonScalar, PNonScalar, True, ForInStep\n\nclass inductive Nonempty (\u03b1 : Sort u) : Prop where\n  | intro (val : \u03b1) : Nonempty \u03b1\n\nprotected def Nonempty.elim {\u03b1 : Sort u} {p : Prop} (h\u2081 : Nonempty \u03b1) (h\u2082 : \u03b1 \u2192 p) : p :=\n  h\u2082 h\u2081.1\n\ninstance {\u03b1 : Sort u} [Inhabited \u03b1] : Nonempty \u03b1 where\n  val := arbitrary\n\ntheorem nonemptyOfExists {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} : Exists (fun x => p x) \u2192 Nonempty \u03b1\n  | \u27e8w, h\u27e9 => \u27e8w\u27e9\n\n/- Subsingleton -/\n\nclass Subsingleton (\u03b1 : Sort u) : Prop where\n  intro :: allEq : (a b : \u03b1) \u2192 a = b\n\nprotected def Subsingleton.elim {\u03b1 : Sort u} [h : Subsingleton \u03b1] : (a b : \u03b1) \u2192 a = b :=\n  h.allEq\n\nprotected def Subsingleton.helim {\u03b1 \u03b2 : Sort u} [h\u2081 : Subsingleton \u03b1] (h\u2082 : \u03b1 = \u03b2) (a : \u03b1) (b : \u03b2) : a \u2245 b := by\n  subst h\u2082\n  apply heqOfEq\n  apply Subsingleton.elim\n\ninstance (p : Prop) : Subsingleton p :=\n  \u27e8fun a b => proofIrrel a b\u27e9\n\ninstance (p : Prop) : Subsingleton (Decidable p) :=\n  Subsingleton.intro fun\n    | isTrue t\u2081 => fun\n      | isTrue t\u2082  => rfl\n      | isFalse f\u2082 => absurd t\u2081 f\u2082\n    | isFalse f\u2081 => fun\n      | isTrue t\u2082  => absurd t\u2082 f\u2081\n      | isFalse f\u2082 => rfl\n\ntheorem recSubsingleton\n     {p : Prop} [h : Decidable p]\n     {h\u2081 : p \u2192 Sort u}\n     {h\u2082 : \u00acp \u2192 Sort u}\n     [h\u2083 : \u2200 (h : p), Subsingleton (h\u2081 h)]\n     [h\u2084 : \u2200 (h : \u00acp), Subsingleton (h\u2082 h)]\n     : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h\u2082 h\u2081) :=\n  match h with\n  | isTrue h  => h\u2083 h\n  | isFalse h => h\u2084 h\n\nstructure Equivalence {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : Prop where\n  refl  : \u2200 x, r x x\n  symm  : \u2200 {x y}, r x y \u2192 r y x\n  trans : \u2200 {x y z}, r x y \u2192 r y z \u2192 r x z\n\ndef emptyRelation {\u03b1 : Sort u} (a\u2081 a\u2082 : \u03b1) : Prop :=\n  False\n\ndef Subrelation {\u03b1 : Sort u} (q r : \u03b1 \u2192 \u03b1 \u2192 Prop) :=\n  \u2200 {x y}, q x y \u2192 r x y\n\ndef InvImage {\u03b1 : Sort u} {\u03b2 : Sort v} (r : \u03b2 \u2192 \u03b2 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) : \u03b1 \u2192 \u03b1 \u2192 Prop :=\n  fun a\u2081 a\u2082 => r (f a\u2081) (f a\u2082)\n\ninductive TC {\u03b1 : Sort u} (r : \u03b1 \u2192 \u03b1 \u2192 Prop) : \u03b1 \u2192 \u03b1 \u2192 Prop where\n  | base  : \u2200 a b, r a b \u2192 TC r a b\n  | trans : \u2200 a b c, TC r a b \u2192 TC r b c \u2192 TC r a c\n\n/- Subtype -/\n\nnamespace Subtype\ndef existsOfSubtype {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : { x // p x } \u2192 Exists (fun x => p x)\n  | \u27e8a, h\u27e9 => \u27e8a, h\u27e9\n\nvariable {\u03b1 : Type u} {p : \u03b1 \u2192 Prop}\n\nprotected theorem eq : \u2200 {a1 a2 : {x // p x}}, val a1 = val a2 \u2192 a1 = a2\n  | \u27e8x, h1\u27e9, \u27e8_, _\u27e9, 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 {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} {a : \u03b1} (h : p a) : Inhabited {x // p x} where\n  default := \u27e8a, h\u27e9\n\ninstance {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} [DecidableEq \u03b1] : DecidableEq {x : \u03b1 // p x} :=\n  fun \u27e8a, h\u2081\u27e9 \u27e8b, h\u2082\u27e9 =>\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 {\u03b1 : Type u} {\u03b2 : Type v}\n\ninstance Sum.inhabitedLeft [h : Inhabited \u03b1] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inl arbitrary\n\ninstance Sum.inhabitedRight [h : Inhabited \u03b2] : Inhabited (Sum \u03b1 \u03b2) where\n  default := Sum.inr arbitrary\n\ninstance {\u03b1 : Type u} {\u03b2 : Type v} [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (Sum \u03b1 \u03b2) := fun a b =>\n  match a, b with\n  | Sum.inl a, Sum.inl b =>\n    if h : a = b then isTrue (h \u25b8 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 \u25b8 rfl)\n    else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h\n  | Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h\n  | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h\n\nend\n\n/- Product -/\n\ninstance [Inhabited \u03b1] [Inhabited \u03b2] : Inhabited (\u03b1 \u00d7 \u03b2) where\n  default := (arbitrary, arbitrary)\n\ninstance [DecidableEq \u03b1] [DecidableEq \u03b2] : DecidableEq (\u03b1 \u00d7 \u03b2) :=\n  fun (a, b) (a', b') =>\n    match decEq a a' with\n    | isTrue e\u2081 =>\n      match decEq b b' with\n      | isTrue e\u2082  => isTrue (e\u2081 \u25b8 e\u2082 \u25b8 rfl)\n      | isFalse n\u2082 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2082' n\u2082\n    | isFalse n\u2081 => isFalse fun h => Prod.noConfusion h fun e\u2081' e\u2082' => absurd e\u2081' n\u2081\n\ninstance [BEq \u03b1] [BEq \u03b2] : BEq (\u03b1 \u00d7 \u03b2) where\n  beq := fun (a\u2081, b\u2081) (a\u2082, b\u2082) => a\u2081 == a\u2082 && b\u2081 == b\u2082\n\ninstance [LT \u03b1] [LT \u03b2] : LT (\u03b1 \u00d7 \u03b2) where\n  lt s t := s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)\n\ninstance prodHasDecidableLt\n    [LT \u03b1] [LT \u03b2] [DecidableEq \u03b1] [DecidableEq \u03b2]\n    [(a b : \u03b1) \u2192 Decidable (a < b)] [(a b : \u03b2) \u2192 Decidable (a < b)]\n    : (s t : \u03b1 \u00d7 \u03b2) \u2192 Decidable (s < t) :=\n  fun t s => inferInstanceAs (Decidable (_ \u2228 _))\n\ntheorem Prod.ltDef [LT \u03b1] [LT \u03b2] (s t : \u03b1 \u00d7 \u03b2) : (s < t) = (s.1 < t.1 \u2228 (s.1 = t.1 \u2227 s.2 < t.2)) :=\n  rfl\n\ntheorem Prod.ext (p : \u03b1 \u00d7 \u03b2) : (p.1, p.2) = p := by\n  cases p; rfl\n\ndef Prod.map {\u03b1\u2081 : Type u\u2081} {\u03b1\u2082 : Type u\u2082} {\u03b2\u2081 : Type v\u2081} {\u03b2\u2082 : Type v\u2082}\n    (f : \u03b1\u2081 \u2192 \u03b1\u2082) (g : \u03b2\u2081 \u2192 \u03b2\u2082) : \u03b1\u2081 \u00d7 \u03b2\u2081 \u2192 \u03b1\u2082 \u00d7 \u03b2\u2082\n  | (a, b) => (f a, g b)\n\n/- Dependent products -/\n\ntheorem exOfPsig {\u03b1 : Type u} {p : \u03b1 \u2192 Prop} : (PSigma (fun x => p x)) \u2192 Exists (fun x => p x)\n  | \u27e8x, hx\u27e9 => \u27e8x, hx\u27e9\n\nprotected theorem PSigma.eta {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} {a\u2081 a\u2082 : \u03b1} {b\u2081 : \u03b2 a\u2081} {b\u2082 : \u03b2 a\u2082}\n    (h\u2081 : a\u2081 = a\u2082) (h\u2082 : Eq.ndrec b\u2081 h\u2081 = b\u2082) : PSigma.mk a\u2081 b\u2081 = PSigma.mk a\u2082 b\u2082 := by\n  subst h\u2081\n  subst h\u2082\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\n@[simp] theorem PUnit.eq_punit (a : PUnit) : a = \u27e8\u27e9 :=\n  PUnit.subsingleton a \u27e8\u27e9\n\ninstance : Subsingleton PUnit :=\n  Subsingleton.intro PUnit.subsingleton\n\ninstance : Inhabited PUnit where\n  default := \u27e8\u27e9\n\ninstance : DecidableEq PUnit :=\n  fun a b => isTrue (PUnit.subsingleton a b)\n\n/- Setoid -/\n\nclass Setoid (\u03b1 : Sort u) where\n  r : \u03b1 \u2192 \u03b1 \u2192 Prop\n  iseqv {} : Equivalence r\n\ninstance {\u03b1 : Sort u} [Setoid \u03b1] : HasEquiv \u03b1 :=\n  \u27e8Setoid.r\u27e9\n\nnamespace Setoid\n\nvariable {\u03b1 : Sort u} [Setoid \u03b1]\n\ntheorem refl (a : \u03b1) : a \u2248 a :=\n  (Setoid.iseqv \u03b1).refl a\n\ntheorem symm {a b : \u03b1} (hab : a \u2248 b) : b \u2248 a :=\n  (Setoid.iseqv \u03b1).symm hab\n\ntheorem trans {a b c : \u03b1} (hab : a \u2248 b) (hbc : b \u2248 c) : a \u2248 c :=\n  (Setoid.iseqv \u03b1).trans hab hbc\n\nend Setoid\n\n\n/- Propositional extensionality -/\n\naxiom propext {a b : Prop} : (a \u2194 b) \u2192 a = b\n\ntheorem Eq.propIntro {a b : Prop} (h\u2081 : a \u2192 b) (h\u2082 : b \u2192 a) : a = b :=\n  propext <| Iff.intro h\u2081 h\u2082\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/- Quotients -/\n\n-- Iff can now be used to do substitutions in a calculation\ntheorem iffSubst {a b : Prop} {p : Prop \u2192 Prop} (h\u2081 : a \u2194 b) (h\u2082 : p a) : p b :=\n  Eq.subst (propext h\u2081) h\u2082\n\nnamespace Quot\naxiom sound : \u2200 {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {a b : \u03b1}, r a b \u2192 Quot.mk r a = Quot.mk r b\n\nprotected theorem liftBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {\u03b2 : Sort v}\n    (f : \u03b1 \u2192 \u03b2)\n    (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b)\n    (a : \u03b1)\n    : lift f c (Quot.mk r a) = f a :=\n  rfl\n\nprotected theorem indBeta {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (p : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (a : \u03b1)\n    : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=\n  rfl\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 r a b \u2192 f a = f b) : \u03b2 :=\n  lift f c q\n\nprotected theorem inductionOn {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} {motive : Quot r \u2192 Prop}\n    (q : Quot r)\n    (h : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q :=\n  ind h q\n\ntheorem existsRep {\u03b1 : Sort u} {r : \u03b1 \u2192 \u03b1 \u2192 Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=\n  Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => \u27e8a, rfl\u27e9)\n\nsection\nvariable {\u03b1 : Sort u}\nvariable {r : \u03b1 \u2192 \u03b1 \u2192 Prop}\nvariable {motive : Quot r \u2192 Sort v}\n\n@[reducible, macroInline]\nprotected def indep (f : (a : \u03b1) \u2192 motive (Quot.mk r a)) (a : \u03b1) : PSigma motive :=\n  \u27e8Quot.mk r a, f a\u27e9\n\nprotected theorem indepCoherent\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : (a b : \u03b1) \u2192 r a b \u2192 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 : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : \u2200 (a b : \u03b1) (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\nprotected abbrev rec\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 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\nprotected abbrev recOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (h : (a b : \u03b1) \u2192 (p : r a b) \u2192 Eq.ndrec (f a) (sound p) = f b)\n    : motive q :=\n Quot.rec f h q\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quot.mk r a))]\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    : motive q := by\n  induction q using Quot.rec\n  apply f\n  apply Subsingleton.elim\n\nprotected abbrev hrecOn\n    (q : Quot r)\n    (f : (a : \u03b1) \u2192 motive (Quot.mk r a))\n    (c : (a b : \u03b1) \u2192 (p : r a b) \u2192 f a \u2245 f b)\n    : motive q :=\n  Quot.recOn q f fun a b p => eqOfHEq <|\n    have p\u2081 : Eq.ndrec (f a) (sound p) \u2245 f a := eqRecHEq (sound p) (f a)\n    HEq.trans p\u2081 (c a b p)\n\nend\nend Quot\n\ndef Quotient {\u03b1 : Sort u} (s : Setoid \u03b1) :=\n  @Quot \u03b1 Setoid.r\n\nnamespace Quotient\n\n@[inline]\nprotected def mk {\u03b1 : Sort u} [s : Setoid \u03b1] (a : \u03b1) : Quotient s :=\n  Quot.mk Setoid.r a\n\ndef sound {\u03b1 : Sort u} [s : Setoid \u03b1] {a b : \u03b1} : a \u2248 b \u2192 Quotient.mk a = Quotient.mk b :=\n  Quot.sound\n\nprotected abbrev lift {\u03b1 : Sort u} {\u03b2 : Sort v} [s : Setoid \u03b1] (f : \u03b1 \u2192 \u03b2) : ((a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) \u2192 Quotient s \u2192 \u03b2 :=\n  Quot.lift f\n\nprotected theorem ind {\u03b1 : Sort u} [s : Setoid \u03b1] {motive : Quotient s \u2192 Prop} : ((a : \u03b1) \u2192 motive (Quotient.mk a)) \u2192 (q : Quot Setoid.r) \u2192 motive q :=\n  Quot.ind\n\nprotected abbrev liftOn {\u03b1 : Sort u} {\u03b2 : Sort v} [s : Setoid \u03b1] (q : Quotient s) (f : \u03b1 \u2192 \u03b2) (c : (a b : \u03b1) \u2192 a \u2248 b \u2192 f a = f b) : \u03b2 :=\n  Quot.liftOn q f c\n\nprotected theorem inductionOn {\u03b1 : Sort u} [s : Setoid \u03b1] {motive : Quotient s \u2192 Prop}\n    (q : Quotient s)\n    (h : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    : motive q :=\n  Quot.inductionOn q h\n\ntheorem existsRep {\u03b1 : Sort u} [s : Setoid \u03b1] (q : Quotient s) : Exists (fun (a : \u03b1) => Quotient.mk a = q) :=\n  Quot.existsRep q\n\nsection\nvariable {\u03b1 : Sort u}\nvariable [s : Setoid \u03b1]\nvariable {motive : Quotient s \u2192 Sort v}\n\n@[inline]\nprotected def rec\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    (q : Quotient s)\n    : motive q :=\n  Quot.rec f h q\n\nprotected abbrev recOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (h : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 Eq.ndrec (f a) (Quotient.sound p) = f b)\n    : motive q :=\n  Quot.recOn q f h\n\nprotected abbrev recOnSubsingleton\n    [h : (a : \u03b1) \u2192 Subsingleton (motive (Quotient.mk a))]\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    : motive q :=\n  Quot.recOnSubsingleton (h := h) q f\n\nprotected abbrev hrecOn\n    (q : Quotient s)\n    (f : (a : \u03b1) \u2192 motive (Quotient.mk a))\n    (c : (a b : \u03b1) \u2192 (p : a \u2248 b) \u2192 f a \u2245 f b)\n    : motive q :=\n  Quot.hrecOn q f c\nend\n\nsection\nuniverses uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB} {\u03c6 : Sort uC}\nvariable [s\u2081 : Setoid \u03b1] [s\u2082 : Setoid \u03b2]\n\nprotected abbrev lift\u2082\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    (q\u2081 : Quotient s\u2081) (q\u2082 : Quotient s\u2082)\n    : \u03c6 := by\n  apply Quotient.lift (fun (a\u2081 : \u03b1) => Quotient.lift (f a\u2081) (fun (a b : \u03b2) => c a\u2081 a a\u2081 b (Setoid.refl a\u2081)) q\u2082) _ q\u2081\n  intros\n  induction q\u2082 using Quotient.ind\n  apply c; assumption; apply Setoid.refl\n\nprotected abbrev liftOn\u2082\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (f : \u03b1 \u2192 \u03b2 \u2192 \u03c6)\n    (c : (a\u2081 : \u03b1) \u2192 (b\u2081 : \u03b2) \u2192 (a\u2082 : \u03b1) \u2192 (b\u2082 : \u03b2) \u2192 a\u2081 \u2248 a\u2082 \u2192 b\u2081 \u2248 b\u2082 \u2192 f a\u2081 b\u2081 = f a\u2082 b\u2082)\n    : \u03c6 :=\n  Quotient.lift\u2082 f c q\u2081 q\u2082\n\nprotected theorem ind\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  apply h\n\nprotected theorem inductionOn\u2083\n    [s\u2083 : Setoid \u03c6]\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Quotient s\u2083 \u2192 Prop}\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (q\u2083 : Quotient s\u2083)\n    (h : (a : \u03b1) \u2192 (b : \u03b2) \u2192 (c : \u03c6) \u2192 motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))\n    : motive q\u2081 q\u2082 q\u2083 := by\n  induction q\u2081 using Quotient.ind\n  induction q\u2082 using Quotient.ind\n  induction q\u2083 using Quotient.ind\n  apply h\n\nend\n\nsection Exact\n\nvariable   {\u03b1 : Sort u}\n\nprivate def rel [s : Setoid \u03b1] (q\u2081 q\u2082 : Quotient s) : Prop :=\n  Quotient.liftOn\u2082 q\u2081 q\u2082\n    (fun a\u2081 a\u2082 => a\u2081 \u2248 a\u2082)\n    (fun a\u2081 a\u2082 b\u2081 b\u2082 a\u2081b\u2081 a\u2082b\u2082 =>\n      propext (Iff.intro\n        (fun a\u2081a\u2082 => Setoid.trans (Setoid.symm a\u2081b\u2081) (Setoid.trans a\u2081a\u2082 a\u2082b\u2082))\n        (fun b\u2081b\u2082 => Setoid.trans a\u2081b\u2081 (Setoid.trans b\u2081b\u2082 (Setoid.symm a\u2082b\u2082)))))\n\nprivate theorem rel.refl [s : Setoid \u03b1] (q : Quotient s) : rel q q :=\n  Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a)\n\nprivate theorem eqImpRel [s : Setoid \u03b1] {q\u2081 q\u2082 : Quotient s} : q\u2081 = q\u2082 \u2192 rel q\u2081 q\u2082 :=\n  fun h => Eq.ndrecOn h (rel.refl q\u2081)\n\ntheorem exact [s : Setoid \u03b1] {a b : \u03b1} : Quotient.mk a = Quotient.mk b \u2192 a \u2248 b :=\n  fun h => eqImpRel h\n\nend Exact\n\nsection\nuniverses uA uB uC\nvariable {\u03b1 : Sort uA} {\u03b2 : Sort uB}\nvariable [s\u2081 : Setoid \u03b1] [s\u2082 : Setoid \u03b2]\n\nprotected abbrev recOnSubsingleton\u2082\n    {motive : Quotient s\u2081 \u2192 Quotient s\u2082 \u2192 Sort uC}\n    [s : (a : \u03b1) \u2192 (b : \u03b2) \u2192 Subsingleton (motive (Quotient.mk a) (Quotient.mk b))]\n    (q\u2081 : Quotient s\u2081)\n    (q\u2082 : Quotient s\u2082)\n    (g : (a : \u03b1) \u2192 (b : \u03b2) \u2192 motive (Quotient.mk a) (Quotient.mk b))\n    : motive q\u2081 q\u2082 := by\n  induction q\u2081 using Quot.recOnSubsingleton\n  induction q\u2082 using Quot.recOnSubsingleton\n  apply g\n  intro a; apply s\n  induction q\u2082 using Quot.recOnSubsingleton\n  intro a; apply s\n  inferInstance\n\nend\nend Quotient\n\nsection\nvariable {\u03b1 : Type u}\nvariable (r : \u03b1 \u2192 \u03b1 \u2192 Prop)\n\ninstance {\u03b1 : Sort u} {s : Setoid \u03b1} [d : \u2200 (a b : \u03b1), Decidable (a \u2248 b)] : DecidableEq (Quotient s) :=\n  fun (q\u2081 q\u2082 : Quotient s) =>\n    Quotient.recOnSubsingleton\u2082 (motive := fun a b => Decidable (a = b)) q\u2081 q\u2082\n      fun a\u2081 a\u2082 =>\n        match d a\u2081 a\u2082 with\n        | isTrue h\u2081  => isTrue (Quotient.sound h\u2081)\n        | isFalse h\u2082 => isFalse fun h => absurd (Quotient.exact h) h\u2082\n\n/- Function extensionality -/\n\nnamespace Function\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\ndef Equiv (f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x) : Prop := \u2200 x, f\u2081 x = f\u2082 x\n\nprotected theorem Equiv.refl (f : \u2200 (x : \u03b1), \u03b2 x) : Equiv f f :=\n  fun x => rfl\n\nprotected theorem Equiv.symm {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} : Equiv f\u2081 f\u2082 \u2192 Equiv f\u2082 f\u2081 :=\n  fun h x => Eq.symm (h x)\n\nprotected theorem Equiv.trans {f\u2081 f\u2082 f\u2083 : \u2200 (x : \u03b1), \u03b2 x} : Equiv f\u2081 f\u2082 \u2192 Equiv f\u2082 f\u2083 \u2192 Equiv f\u2081 f\u2083 :=\n  fun h\u2081 h\u2082 x => Eq.trans (h\u2081 x) (h\u2082 x)\n\nprotected theorem Equiv.isEquivalence (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Equivalence (@Function.Equiv \u03b1 \u03b2) := {\n  refl := Equiv.refl\n  symm := Equiv.symm\n  trans := Equiv.trans\n}\n\nend Function\n\nsection\nopen Quotient\nvariable {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v}\n\n@[instance]\nprivate def funSetoid (\u03b1 : Sort u) (\u03b2 : \u03b1 \u2192 Sort v) : Setoid (\u2200 (x : \u03b1), \u03b2 x) :=\n  Setoid.mk (@Function.Equiv \u03b1 \u03b2) (Function.Equiv.isEquivalence \u03b1 \u03b2)\n\nprivate def extfunApp (f : Quotient <| funSetoid \u03b1 \u03b2) (x : \u03b1) : \u03b2 x :=\n  Quot.liftOn f\n    (fun (f : \u2200 (x : \u03b1), \u03b2 x) => f x)\n    (fun f\u2081 f\u2082 h => h x)\n\ntheorem funext {f\u2081 f\u2082 : \u2200 (x : \u03b1), \u03b2 x} (h : \u2200 x, f\u2081 x = f\u2082 x) : f\u2081 = f\u2082 := by\n  show extfunApp (Quotient.mk f\u2081) = extfunApp (Quotient.mk f\u2082)\n  apply congrArg\n  apply Quotient.sound\n  exact h\n\nend\n\ninstance {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} [\u2200 a, Subsingleton (\u03b2 a)] : Subsingleton (\u2200 a, \u03b2 a) where\n  allEq f\u2081 f\u2082 :=\n    funext (fun a => Subsingleton.elim (f\u2081 a) (f\u2082 a))\n\n/- Squash -/\n\ndef Squash (\u03b1 : Type u) := Quot (fun (a b : \u03b1) => True)\n\ndef Squash.mk {\u03b1 : Type u} (x : \u03b1) : Squash \u03b1 := Quot.mk _ x\n\ntheorem Squash.ind {\u03b1 : Type u} {motive : Squash \u03b1 \u2192 Prop} (h : \u2200 (a : \u03b1), motive (Squash.mk a)) : \u2200 (q : Squash \u03b1), motive q :=\n  Quot.ind h\n\n@[inline] def Squash.lift {\u03b1 \u03b2} [Subsingleton \u03b2] (s : Squash \u03b1) (f : \u03b1 \u2192 \u03b2) : \u03b2 :=\n  Quot.lift f (fun a b _ => Subsingleton.elim _ _) s\n\ninstance : Subsingleton (Squash \u03b1) 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\nnamespace Lean\n/- Kernel reduction hints -/\n\n/--\n  When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.\n  The kernel will not use the interpreter if `c` is not a constant.\n  This feature is useful for performing proofs by reflection.\n\n  Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing\n  free 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\n  Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\n  This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using\n  external type checkers (e.g., Trepplein) that do not implement this feature.\n  Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\n  So, you are mainly losing the capability of type checking your developement using external checkers.\n\n  Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.\n  If an extern function is executed, then the trusted code base will also include the implementation of the associated\n  foreign function.\n-/\nconstant reduceBool (b : Bool) : Bool := b\n\n/--\n  Similar to `Lean.reduceBool` for closed `Nat` terms.\n\n  Remark: we do not have plans for supporting a generic `reduceValue {\u03b1} (a : \u03b1) : \u03b1 := a`.\n  The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.\n  We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/\nconstant reduceNat (n : Nat) : Nat := n\n\naxiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b\naxiom ofReduceNat (a b : Nat) (h : reduceNat a = b)    : a = b\n\nend Lean\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/Core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798743735585307, "lm_q2_score": 0.04958902702220519, "lm_q1q2_score": 0.012297455732206815}}
{"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 \u03a3(C) consisting of a this identity and an assignment of fields to values. -/\n@[derive decidable_eq]\nstructure state_space {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (self : class_name \u03b1) :=\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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    {self : class_name \u03b1} (\u03c3 : state_space self) : \u03b2 :=\n  value.the_object \u03c3.N\nlemma state_space.class_of_id {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n  {self : class_name \u03b1} (\u03c3 : state_space self) :\n  class_of \u03b1 \u03c3.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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    {C : class_name \u03b1} (f : field_name C)\n    (v : value (field_type f)) : state_space C \u2192 state_space C\n| \u27e8map, this, N\u27e9 := \u27e8\u03bbg, if H : f = g\n    then cast begin rewrite H end v else map g,this,N\u27e9\n/- A state space can be updated, given a field variable in a typing environment related to the same class. -/\ndef state_space.updatev {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    {C : class_name \u03b1} {e : tenv C} {ty : type \u03b1}\n    (fvar : fvar e ty) (v : value ty)\n    (\u03c3 : state_space C) : state_space C :=\n  \u03c3.update fvar.idx (cast begin rewrite fvar.H end v)\nnotation \u03a3(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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (C : class_name \u03b1) :=\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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    {C : class_name \u03b1}\n    (\u03c3 : \u03a3(C)) (\u03c0 : active_process C)\n    {tx : type \u03b1} : rvar \u03c0.e tx \u2192 value tx\n| (rvar.tvar t) := cast begin rewrite t.H end \u03c3.this\n| (rvar.fvar f) := cast begin rewrite f.H end $ \u03c3.map f.idx\n| (rvar.pvar p) := \u03c0.args.lookup p.idx\n| (rvar.lvar l) := \u03c0.store.lookup l.idx\n\n/- A process is either nil or an active process. -/\n@[derive decidable_eq]\ninductive process {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (C : class_name \u03b1)\n| nil : process\n| active (a : active_process C) : process\n\n/- Evaluating a pure expression to a list of values. -/\ndef eval {\u03b1 \u03b2 : Type} [interpret \u03b1 \u03b2]\n    {C : class_name \u03b1}\n    (\u03c3 : \u03a3(C)) (\u03c0 : active_process C) :\n    \u03a0 {l : list (type \u03b1)}, pexp \u03c0.e l \u2192 vallist l\n| _ (pexp.const .(\u03c0.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 (\u03c0.lookup \u03c3 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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (p : program \u03b1) (c : class_name \u03b1) (m : method_name c)\n    (\u03c4 : vallist (param_types m)) : process c :=\n  process.active \u27e8(p.body m).tenv,\u03c4,default _,(p.body m).S\u27e9\n\ndef process.schedule {\u03b1 \u03b2 : Type} [interpret \u03b1 \u03b2]\n    (pr : program \u03b1) {\u03b8 : global_history \u03b1 \u03b2}\n    {C : class_name \u03b1} (\u03c3 : \u03a3(C)) (d : callsite \u03b1 \u03b2)\n    (H : global_history.sched \u03b8 (state_space.id \u03c3) = some d)\n    : process C :=\n  callsite.elim d (\u03bbc o m \u03c4 g,\n    let p := process.activate pr c m \u03c4,\n      G : process c = process C := begin\n        have F : state_space.id \u03c3 = o.val,\n          apply eq.symm,\n          apply global_history.sched_object \u03b8 (\u03c3.id) \u27e8o,m,\u03c4\u27e9,\n          rw \u2190 g, apply H,\n        rewrite o.property,\n        rewrite \u2190 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 {\u03b1 : Type u_1} : coe = some :=\n  rfl\n\ntheorem some_ne_none {\u03b1 : Type u_1} (x : \u03b1) : some x \u2260 none :=\n  fun (h : some x = none) => option.no_confusion h\n\n@[simp] theorem get_mem {\u03b1 : Type u_1} {o : Option \u03b1} (h : \u21a5(is_some o)) : get h \u2208 o :=\n  option.cases_on o\n    (fun (h : \u21a5(is_some none)) => eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h))\n    (fun (o : \u03b1) (h : \u21a5(is_some (some o))) => idRhs (some o = some o) rfl) h\n\ntheorem get_of_mem {\u03b1 : Type u_1} {a : \u03b1} {o : Option \u03b1} (h : \u21a5(is_some o)) : a \u2208 o \u2192 get h = a := sorry\n\n@[simp] theorem not_mem_none {\u03b1 : Type u_1} (a : \u03b1) : \u00aca \u2208 none :=\n  fun (h : a \u2208 none) => option.no_confusion h\n\n@[simp] theorem some_get {\u03b1 : Type u_1} {x : Option \u03b1} (h : \u21a5(is_some x)) : some (get h) = x :=\n  option.cases_on x\n    (fun (h : \u21a5(is_some none)) => eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h))\n    (fun (x : \u03b1) (h : \u21a5(is_some (some x))) => idRhs (some (get h) = some (get h)) rfl) h\n\n@[simp] theorem get_some {\u03b1 : Type u_1} (x : \u03b1) (h : \u21a5(is_some (some x))) : get h = x :=\n  rfl\n\n@[simp] theorem get_or_else_some {\u03b1 : Type u_1} (x : \u03b1) (y : \u03b1) : get_or_else (some x) y = x :=\n  rfl\n\n@[simp] theorem get_or_else_coe {\u03b1 : Type u_1} (x : \u03b1) (y : \u03b1) : get_or_else (\u2191x) y = x :=\n  rfl\n\ntheorem get_or_else_of_ne_none {\u03b1 : Type u_1} {x : Option \u03b1} (hx : x \u2260 none) (y : \u03b1) : some (get_or_else x y) = x := sorry\n\ntheorem mem_unique {\u03b1 : Type u_1} {o : Option \u03b1} {a : \u03b1} {b : \u03b1} (ha : a \u2208 o) (hb : b \u2208 o) : a = b :=\n  some.inj (Eq.trans (Eq.symm ha) hb)\n\ntheorem some_injective (\u03b1 : Type u_1) : function.injective some :=\n  fun (_x _x_1 : \u03b1) => iff.mp some_inj\n\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} (Hf : function.injective f) : function.injective (option.map f) := sorry\n\ntheorem ext {\u03b1 : Type u_1} {o\u2081 : Option \u03b1} {o\u2082 : Option \u03b1} : (\u2200 (a : \u03b1), a \u2208 o\u2081 \u2194 a \u2208 o\u2082) \u2192 o\u2081 = o\u2082 := sorry\n\ntheorem eq_none_iff_forall_not_mem {\u03b1 : Type u_1} {o : Option \u03b1} : o = none \u2194 \u2200 (a : \u03b1), \u00aca \u2208 o := sorry\n\n@[simp] theorem none_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} (f : \u03b1 \u2192 Option \u03b2) : none >>= f = none :=\n  rfl\n\n@[simp] theorem some_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} (a : \u03b1) (f : \u03b1 \u2192 Option \u03b2) : some a >>= f = f a :=\n  rfl\n\n@[simp] theorem none_bind' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 Option \u03b2) : option.bind none f = none :=\n  rfl\n\n@[simp] theorem some_bind' {\u03b1 : Type u_1} {\u03b2 : Type u_2} (a : \u03b1) (f : \u03b1 \u2192 Option \u03b2) : option.bind (some a) f = f a :=\n  rfl\n\n@[simp] theorem bind_some {\u03b1 : Type u_1} (x : Option \u03b1) : x >>= some = x :=\n  bind_pure\n\n@[simp] theorem bind_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} {b : \u03b2} : x >>= f = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = some b := sorry\n\n@[simp] theorem bind_eq_some' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} {b : \u03b2} : option.bind x f = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = some b := sorry\n\n@[simp] theorem bind_eq_none' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {o : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} : option.bind o f = none \u2194 \u2200 (b : \u03b2) (a : \u03b1), a \u2208 o \u2192 \u00acb \u2208 f a := sorry\n\n@[simp] theorem bind_eq_none {\u03b1 : Type u_1} {\u03b2 : Type u_1} {o : Option \u03b1} {f : \u03b1 \u2192 Option \u03b2} : o >>= f = none \u2194 \u2200 (b : \u03b2) (a : \u03b1), a \u2208 o \u2192 \u00acb \u2208 f a :=\n  bind_eq_none'\n\ntheorem bind_comm {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {f : \u03b1 \u2192 \u03b2 \u2192 Option \u03b3} (a : Option \u03b1) (b : Option \u03b2) : (option.bind a fun (x : \u03b1) => option.bind b (f x)) = option.bind b fun (y : \u03b2) => option.bind a fun (x : \u03b1) => f x y := sorry\n\ntheorem bind_assoc {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (x : Option \u03b1) (f : \u03b1 \u2192 Option \u03b2) (g : \u03b2 \u2192 Option \u03b3) : option.bind (option.bind x f) g = option.bind x fun (y : \u03b1) => option.bind (f y) g :=\n  option.cases_on x (Eq.refl (option.bind (option.bind none f) g))\n    fun (x : \u03b1) => Eq.refl (option.bind (option.bind (some x) f) g)\n\ntheorem join_eq_some {\u03b1 : Type u_1} {x : Option (Option \u03b1)} {a : \u03b1} : join x = some a \u2194 x = some (some a) := sorry\n\ntheorem join_ne_none {\u03b1 : Type u_1} {x : Option (Option \u03b1)} : join x \u2260 none \u2194 \u2203 (z : \u03b1), x = some (some z) := sorry\n\ntheorem join_ne_none' {\u03b1 : Type u_1} {x : Option (Option \u03b1)} : \u00acjoin x = none \u2194 \u2203 (z : \u03b1), x = some (some z) := sorry\n\ntheorem bind_id_eq_join {\u03b1 : Type u_1} {x : Option (Option \u03b1)} : x >>= id = join x := sorry\n\ntheorem join_eq_join {\u03b1 : Type u_1} : mjoin = join := sorry\n\ntheorem bind_eq_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} {f : \u03b1 \u2192 Option \u03b2} {x : Option \u03b1} : x >>= f = option.bind x f :=\n  rfl\n\n@[simp] theorem map_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_1} {f : \u03b1 \u2192 \u03b2} : Functor.map f = option.map f :=\n  rfl\n\ntheorem map_none {\u03b1 : Type u_1} {\u03b2 : Type u_1} {f : \u03b1 \u2192 \u03b2} : f <$> none = none :=\n  rfl\n\ntheorem map_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> some a = some (f a) :=\n  rfl\n\n@[simp] theorem map_none' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} : option.map f none = none :=\n  rfl\n\n@[simp] theorem map_some' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : option.map f (some a) = some (f a) :=\n  rfl\n\ntheorem map_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} : f <$> x = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = b := sorry\n\n@[simp] theorem map_eq_some' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} {b : \u03b2} : option.map f x = some b \u2194 \u2203 (a : \u03b1), x = some a \u2227 f a = b := sorry\n\ntheorem map_eq_none {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} : f <$> x = none \u2194 x = none := sorry\n\n@[simp] theorem map_eq_none' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : \u03b1 \u2192 \u03b2} : option.map f x = none \u2194 x = none := sorry\n\ntheorem map_congr {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {g : \u03b1 \u2192 \u03b2} {x : Option \u03b1} (h : \u2200 (a : \u03b1), a \u2208 x \u2192 f a = g a) : option.map f x = option.map g x := sorry\n\n@[simp] theorem map_id' {\u03b1 : Type u_1} : option.map id = id :=\n  map_id\n\n@[simp] theorem map_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2) (x : Option \u03b1) : option.map h (option.map g x) = option.map (h \u2218 g) x := sorry\n\ntheorem comp_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (h : \u03b2 \u2192 \u03b3) (g : \u03b1 \u2192 \u03b2) (x : Option \u03b1) : option.map (h \u2218 g) x = option.map h (option.map g x) :=\n  Eq.symm (map_map h g x)\n\n@[simp] theorem map_comp_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (g : \u03b2 \u2192 \u03b3) : option.map g \u2218 option.map f = option.map (g \u2218 f) := sorry\n\ntheorem mem_map_of_mem {\u03b1 : Type u_1} {\u03b2 : Type u_2} {a : \u03b1} {x : Option \u03b1} (g : \u03b1 \u2192 \u03b2) (h : a \u2208 x) : g a \u2208 option.map g x :=\n  iff.mpr mem_def (Eq.symm (iff.mp mem_def h) \u25b8 map_some')\n\ntheorem bind_map_comm {\u03b1 : Type u_1} {\u03b2 : Type u_1} {x : Option (Option \u03b1)} {f : \u03b1 \u2192 \u03b2} : x >>= option.map f = option.map (option.map f) x >>= id := sorry\n\ntheorem join_map_eq_map_join {\u03b1 : Type u_1} {\u03b2 : Type u_2} {f : \u03b1 \u2192 \u03b2} {x : Option (Option \u03b1)} : join (option.map (option.map f) x) = option.map f (join x) := sorry\n\ntheorem join_join {\u03b1 : Type u_1} {x : Option (Option (Option \u03b1))} : join (join x) = join (option.map join x) := sorry\n\ntheorem mem_of_mem_join {\u03b1 : Type u_1} {a : \u03b1} {x : Option (Option \u03b1)} (h : a \u2208 join x) : some a \u2208 x :=\n  iff.mpr mem_def (Eq.symm (iff.mp mem_def h) \u25b8 iff.mp join_eq_some h)\n\n@[simp] theorem pbind_eq_bind {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : \u03b1 \u2192 Option \u03b2) (x : Option \u03b1) : (pbind x fun (a : \u03b1) (_x : a \u2208 x) => f a) = option.bind x f := sorry\n\ntheorem map_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1) (g : \u03b1 \u2192 Option \u03b2) : option.map f (x >>= g) =\n  do \n    let a \u2190 x \n    option.map f (g a) := sorry\n\ntheorem map_bind' {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1) (g : \u03b1 \u2192 Option \u03b2) : option.map f (option.bind x g) = option.bind x fun (a : \u03b1) => option.map f (g a) := sorry\n\ntheorem map_pbind {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b2 \u2192 \u03b3) (x : Option \u03b1) (g : (a : \u03b1) \u2192 a \u2208 x \u2192 Option \u03b2) : option.map f (pbind x g) = pbind x fun (a : \u03b1) (H : a \u2208 x) => option.map f (g a H) := sorry\n\ntheorem pbind_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2) (x : Option \u03b1) (g : (b : \u03b2) \u2192 b \u2208 option.map f x \u2192 Option \u03b3) : pbind (option.map f x) g = pbind x fun (a : \u03b1) (h : a \u2208 x) => g (f a) (mem_map_of_mem f h) :=\n  option.cases_on x (fun (g : (b : \u03b2) \u2192 b \u2208 option.map f none \u2192 Option \u03b3) => Eq.refl (pbind (option.map f none) g))\n    (fun (x : \u03b1) (g : (b : \u03b2) \u2192 b \u2208 option.map f (some x) \u2192 Option \u03b3) => Eq.refl (pbind (option.map f (some x)) g)) g\n\n@[simp] theorem pmap_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) {H : \u2200 (a : \u03b1), a \u2208 none \u2192 p a} : pmap f none H = none :=\n  rfl\n\n@[simp] theorem pmap_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) {x : \u03b1} (h : p x) : pmap f (some x) = fun (_x : \u2200 (a : \u03b1), a \u2208 some x \u2192 p a) => some (f x h) :=\n  rfl\n\ntheorem mem_pmem {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (x : Option \u03b1) {a : \u03b1} (h : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) (ha : a \u2208 x) : f a (h a ha) \u2208 pmap f x h :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (f a (h a ha) \u2208 pmap f x h)) (propext mem_def)))\n    (Eq._oldrec (fun (h : \u2200 (a_1 : \u03b1), a_1 \u2208 some a \u2192 p a_1) (ha : a \u2208 some a) => Eq.refl (pmap f (some a) h))\n      (Eq.symm (eq.mp (Eq._oldrec (Eq.refl (a \u2208 x)) (propext mem_def)) ha)) h ha)\n\ntheorem pmap_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (g : \u03b3 \u2192 \u03b1) (x : Option \u03b3) (H : \u2200 (a : \u03b1), a \u2208 option.map g x \u2192 p a) : pmap f (option.map g x) H =\n  pmap (fun (a : \u03b3) (h : p (g a)) => f (g a) h) x fun (a : \u03b3) (h : a \u2208 x) => H (g a) (mem_map_of_mem g h) := sorry\n\ntheorem map_pmap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} {p : \u03b1 \u2192 Prop} (g : \u03b2 \u2192 \u03b3) (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (x : Option \u03b1) (H : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) : option.map g (pmap f x H) = pmap (fun (a : \u03b1) (h : p a) => g (f a h)) x H := sorry\n\n@[simp] theorem pmap_eq_map {\u03b1 : Type u_1} {\u03b2 : Type u_2} (p : \u03b1 \u2192 Prop) (f : \u03b1 \u2192 \u03b2) (x : Option \u03b1) (H : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) : pmap (fun (a : \u03b1) (_x : p a) => f a) x H = option.map f x := sorry\n\ntheorem pmap_bind {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} {x : Option \u03b1} {g : \u03b1 \u2192 Option \u03b2} {p : \u03b2 \u2192 Prop} {f : (b : \u03b2) \u2192 p b \u2192 \u03b3} (H : \u2200 (a : \u03b2), a \u2208 x >>= g \u2192 p a) (H' : \u2200 (a : \u03b1) (b : \u03b2), b \u2208 g a \u2192 b \u2208 x >>= g) : pmap f (x >>= g) H =\n  do \n    let a \u2190 x \n    pmap f (g a) fun (b : \u03b2) (h : b \u2208 g a) => H b (H' a b h) := sorry\n\ntheorem bind_pmap {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_2} {p : \u03b1 \u2192 Prop} (f : (a : \u03b1) \u2192 p a \u2192 \u03b2) (x : Option \u03b1) (g : \u03b2 \u2192 Option \u03b3) (H : \u2200 (a : \u03b1), a \u2208 x \u2192 p a) : pmap f x H >>= g = pbind x fun (a : \u03b1) (h : a \u2208 x) => g (f a (H a h)) := sorry\n\ntheorem pbind_eq_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : (a : \u03b1) \u2192 a \u2208 x \u2192 Option \u03b2} (h' : \u2200 (a : \u03b1) (H : a \u2208 x), f a H = none \u2192 x = none) : pbind x f = none \u2194 x = none := sorry\n\ntheorem pbind_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} {x : Option \u03b1} {f : (a : \u03b1) \u2192 a \u2208 x \u2192 Option \u03b2} {y : \u03b2} : pbind x f = some y \u2194 \u2203 (z : \u03b1), \u2203 (H : z \u2208 x), f z H = some y := sorry\n\n@[simp] theorem pmap_eq_none_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {x : Option \u03b1} {h : \u2200 (a : \u03b1), a \u2208 x \u2192 p a} : pmap f x h = none \u2194 x = none := sorry\n\n@[simp] theorem pmap_eq_some_iff {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {x : Option \u03b1} {hf : \u2200 (a : \u03b1), a \u2208 x \u2192 p a} {y : \u03b2} : pmap f x hf = some y \u2194 \u2203 (a : \u03b1), \u2203 (H : x = some a), f a (hf a H) = y := sorry\n\n@[simp] theorem join_pmap_eq_pmap_join {\u03b1 : Type u_1} {\u03b2 : Type u_2} {p : \u03b1 \u2192 Prop} {f : (a : \u03b1) \u2192 p a \u2192 \u03b2} {x : Option (Option \u03b1)} (H : \u2200 (a : Option \u03b1), a \u2208 x \u2192 \u2200 (a_1 : \u03b1), a_1 \u2208 a \u2192 p a_1) : join (pmap (pmap f) x H) = pmap f (join x) fun (a : \u03b1) (h : a \u2208 join x) => H (some a) (mem_of_mem_join h) a rfl := sorry\n\n@[simp] theorem seq_some {\u03b1 : Type u_1} {\u03b2 : Type u_1} {a : \u03b1} {f : \u03b1 \u2192 \u03b2} : some f <*> some a = some (f a) :=\n  rfl\n\n@[simp] theorem some_orelse' {\u03b1 : Type u_1} (a : \u03b1) (x : Option \u03b1) : option.orelse (some a) x = some a :=\n  rfl\n\n@[simp] theorem some_orelse {\u03b1 : Type u_1} (a : \u03b1) (x : Option \u03b1) : (some a <|> x) = some a :=\n  rfl\n\n@[simp] theorem none_orelse' {\u03b1 : Type u_1} (x : Option \u03b1) : option.orelse none x = x :=\n  option.cases_on x (Eq.refl (option.orelse none none)) fun (x : \u03b1) => Eq.refl (option.orelse none (some x))\n\n@[simp] theorem none_orelse {\u03b1 : Type u_1} (x : Option \u03b1) : (none <|> x) = x :=\n  none_orelse' x\n\n@[simp] theorem orelse_none' {\u03b1 : Type u_1} (x : Option \u03b1) : option.orelse x none = x :=\n  option.cases_on x (Eq.refl (option.orelse none none)) fun (x : \u03b1) => Eq.refl (option.orelse (some x) none)\n\n@[simp] theorem orelse_none {\u03b1 : Type u_1} (x : Option \u03b1) : (x <|> none) = x :=\n  orelse_none' x\n\n@[simp] theorem is_some_none {\u03b1 : Type u_1} : is_some none = false :=\n  rfl\n\n@[simp] theorem is_some_some {\u03b1 : Type u_1} {a : \u03b1} : is_some (some a) = tt :=\n  rfl\n\ntheorem is_some_iff_exists {\u03b1 : Type u_1} {x : Option \u03b1} : \u21a5(is_some x) \u2194 \u2203 (a : \u03b1), x = some a := sorry\n\n@[simp] theorem is_none_none {\u03b1 : Type u_1} : is_none none = tt :=\n  rfl\n\n@[simp] theorem is_none_some {\u03b1 : Type u_1} {a : \u03b1} : is_none (some a) = false :=\n  rfl\n\n@[simp] theorem not_is_some {\u03b1 : Type u_1} {a : Option \u03b1} : is_some a = false \u2194 is_none a = tt := sorry\n\ntheorem eq_some_iff_get_eq {\u03b1 : Type u_1} {o : Option \u03b1} {a : \u03b1} : o = some a \u2194 \u2203 (h : \u21a5(is_some o)), get h = a := sorry\n\ntheorem not_is_some_iff_eq_none {\u03b1 : Type u_1} {o : Option \u03b1} : \u00ac\u21a5(is_some o) \u2194 o = none := sorry\n\ntheorem ne_none_iff_is_some {\u03b1 : Type u_1} {o : Option \u03b1} : o \u2260 none \u2194 \u21a5(is_some o) := sorry\n\ntheorem ne_none_iff_exists {\u03b1 : Type u_1} {o : Option \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), some x = o := sorry\n\ntheorem ne_none_iff_exists' {\u03b1 : Type u_1} {o : Option \u03b1} : o \u2260 none \u2194 \u2203 (x : \u03b1), o = some x :=\n  iff.trans ne_none_iff_exists (exists_congr fun (_x : \u03b1) => eq_comm)\n\ntheorem bex_ne_none {\u03b1 : Type u_1} {p : Option \u03b1 \u2192 Prop} : (\u2203 (x : Option \u03b1), \u2203 (H : x \u2260 none), p x) \u2194 \u2203 (x : \u03b1), p (some x) := sorry\n\ntheorem ball_ne_none {\u03b1 : Type u_1} {p : Option \u03b1 \u2192 Prop} : (\u2200 (x : Option \u03b1), x \u2260 none \u2192 p x) \u2194 \u2200 (x : \u03b1), p (some x) := sorry\n\ntheorem iget_mem {\u03b1 : Type u_1} [Inhabited \u03b1] {o : Option \u03b1} : \u21a5(is_some o) \u2192 iget o \u2208 o := sorry\n\ntheorem iget_of_mem {\u03b1 : Type u_1} [Inhabited \u03b1] {a : \u03b1} {o : Option \u03b1} : a \u2208 o \u2192 iget o = a := sorry\n\n@[simp] theorem guard_eq_some {\u03b1 : Type u_1} {p : \u03b1 \u2192 Prop} [decidable_pred p] {a : \u03b1} {b : \u03b1} : guard p a = some b \u2194 a = b \u2227 p a := sorry\n\n@[simp] theorem guard_eq_some' {p : Prop} [Decidable p] (u : Unit) : guard p = some u \u2194 p := sorry\n\ntheorem lift_or_get_choice {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} (h : \u2200 (a b : \u03b1), f a b = a \u2228 f a b = b) (o\u2081 : Option \u03b1) (o\u2082 : Option \u03b1) : lift_or_get f o\u2081 o\u2082 = o\u2081 \u2228 lift_or_get f o\u2081 o\u2082 = o\u2082 := sorry\n\n@[simp] theorem lift_or_get_none_left {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {b : Option \u03b1} : lift_or_get f none b = b :=\n  option.cases_on b (Eq.refl (lift_or_get f none none)) fun (b : \u03b1) => Eq.refl (lift_or_get f none (some b))\n\n@[simp] theorem lift_or_get_none_right {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {a : Option \u03b1} : lift_or_get f a none = a :=\n  option.cases_on a (Eq.refl (lift_or_get f none none)) fun (a : \u03b1) => Eq.refl (lift_or_get f (some a) none)\n\n@[simp] theorem lift_or_get_some_some {\u03b1 : Type u_1} {f : \u03b1 \u2192 \u03b1 \u2192 \u03b1} {a : \u03b1} {b : \u03b1} : lift_or_get f (some a) (some b) = \u2191(f a b) :=\n  rfl\n\n/-- given an element of `a : option \u03b1`, a default element `b : \u03b2` and a function `\u03b1 \u2192 \u03b2`, apply this\nfunction to `a` if it comes from `\u03b1`, and return `b` otherwise. -/\ndef cases_on' {\u03b1 : Type u_1} {\u03b2 : Type u_2} : Option \u03b1 \u2192 \u03b2 \u2192 (\u03b1 \u2192 \u03b2) \u2192 \u03b2 :=\n  sorry\n\n@[simp] theorem cases_on'_none {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) : cases_on' none x f = x :=\n  rfl\n\n@[simp] theorem cases_on'_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : cases_on' (some a) x f = f a :=\n  rfl\n\n@[simp] theorem cases_on'_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} (x : \u03b2) (f : \u03b1 \u2192 \u03b2) (a : \u03b1) : cases_on' (\u2191a) x f = f a :=\n  rfl\n\n@[simp] theorem cases_on'_none_coe {\u03b1 : Type u_1} {\u03b2 : Type u_2} (f : Option \u03b1 \u2192 \u03b2) (o : Option \u03b1) : cases_on' o (f none) (f \u2218 coe) = f o :=\n  option.cases_on o (Eq.refl (cases_on' none (f none) (f \u2218 coe)))\n    fun (o : \u03b1) => Eq.refl (cases_on' (some o) (f none) (f \u2218 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 - \u27e83\u27e9)\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 \u2190 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": "example : False := _\n\nexample : True := trivial\n\nexample : True := trivial\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/309.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.20181324146316568, "lm_q2_score": 0.060086644283076515, "lm_q1q2_score": 0.012126280451411864}}
{"text": "import data.pfun\nimport o_minimal.sheaf.covers\n\nsection orelse_pure\n\nopen_locale classical\n\nnoncomputable def roption.orelse_pure {\u03b1 : Type*} (x : roption \u03b1) (y : \u03b1) :=\nif h : x.dom then x.get h else y\n\n-- TODO: Is this actually useful?\nlemma roption.orelse_pure_eq_iff {\u03b1 : Type*} {x : roption \u03b1} {y : \u03b1} (z : \u03b1) :\n  x.orelse_pure y = z \u2194 (z \u2208 x \u2228 \u00ac x.dom \u2227 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 := \u03bb K f,\n    \u2203 H : def_set S (pfun.dom f),\n    definable S (pfun.as_subtype f),\n  definable_precomp := \u03bb L K \u03c6 f \u27e8H, h\u27e9,\n    \u27e8\u03c6.is_definable.preimage H,\n     h.comp (definable_subtype.map (Def.definable_iff_def_fun.mpr \u03c6.is_definable) (\u03bb _, id))\u27e9,\n  definable_cover := \u03bb K f \ud835\udcdb hf, begin\n    have : def_set S (pfun.dom f) := Def.set_subcanonical \ud835\udcdb _ (\u03bb i, (hf i).fst),\n    refine \u27e8this, _\u27e9,\n    letI : definable_rep S (pfun.dom f) :=\n      subtype.definable_rep (definable_iff_def_set.mpr this),\n    let \ud835\udcdb' : cover S (pfun.dom f) :=\n      (cover_of_Def \ud835\udcdb).pullback subtype.val definable.subtype.val,\n    refine definable_cover (pfun.as_subtype f) \ud835\udcdb' _,\n    -- TODO: messy proof\n    intro i,\n    let \u03c8 : (\ud835\udcdb'.map i).obj \u2192 {l | (\ud835\udcdb.map i).to_fun l \u2208 pfun.dom f} :=\n      \u03bb l', \u27e8l'.1.2, begin\n        rcases l' with \u27e8\u27e8\u27e8a, b\u27e9, c\u27e9, rfl : a = map_to.to_fun _ c\u27e9,\n        exact b\n      end\u27e9,\n    have : (\ud835\udcdb'.map i).to_fun = subtype.map (\ud835\udcdb.map i) (\u03bb _, id) \u2218 \u03c8,\n    { ext1 \u27e8\u27e8\u27e8a, b\u27e9, c\u27e9, rfl : a = map_to.to_fun _ c\u27e9, 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 \u2192 Z \u2192 Prop) :=\nbegin\n  rw definable_iff_uncurry,\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  rw definable_rep.eq at h\u03c6,\n  exact def_set_eq (def_fun.fst.comp h\u03c6) (def_fun.snd.comp h\u03c6)\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 ((\u2208) : Z \u2192 roption Z \u2192 Prop) :=\nbegin\n  rw definable_iff_uncurry,\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  let K' := {k | (\u03c6 k).2.dom},\n  have dK' : def_set S {k : \u21a5K | (\u03c6 k).snd.dom} := h\u03c6.2.fst,\n  letI : definable_rep S K' :=\n    subtype.definable_rep (definable_iff_def_set.mpr dK'),\n  have : definable S (\u03bb (k' : {k | (\u03c6 k).2.dom}), (\u03c6 k'.val).1 = (\u03c6 k'.val).2.get k'.property),\n  { let \u03c8\u2081 : K' \u2192 Z := \u03bb k', (\u03c6 k'.val).1,\n    have d\u03c8\u2081 : definable S \u03c8\u2081 :=\n      (definable_yoneda.mpr h\u03c6.1).comp definable.subtype.val,\n    let \u03c8\u2082 : K' \u2192 Z := \u03bb k', (\u03c6 k'.val).2.get k'.property,\n    have d\u03c8\u2082 : definable S \u03c8\u2082 := h\u03c6.2.snd,\n    let \u03c8 : K' \u2192 Z \u00d7 Z := \u03bb k', (\u03c8\u2081 k', \u03c8\u2082 k'),\n    suffices d\u03c8 : definable S \u03c8,\n    { have : definable S (\u03bb (p : Z \u00d7 Z), p.1 = p.2) :=\n        definable_iff_uncurry.mp definable_eq,\n      exact this.comp d\u03c8 },\n    -- TODO: lemma\n    begin [defin]\n      intro k,\n      app, app, exact definable.prod_mk.definable _,\n      app, exact d\u03c8\u2081.definable _, var,\n      app, exact d\u03c8\u2082.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 \u2192 Prop) :=\nbegin\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  exact h\u03c6.fst\nend\n\nlemma definable_orelse_pure :\n  definable S (roption.orelse_pure : roption X \u2192 X \u2192 X) :=\nbegin\n  rw definable_iff_uncurry,\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  rw \u2190definable_yoneda at \u22a2 h\u03c6,\n  let s := {k | (\u03c6 k).1.dom},\n  apply definable_if _ s,\n  { exact definable_roption.dom.comp (definable.fst.comp h\u03c6) },\n  { suffices : definable S (\u03bb (p : s), (\u03c6 p.val).1.get p.property),\n    { convert this,\n      ext \u27e8k, hk\u27e9,\n      change dite _ _ _ = (\u03c6 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\u03c6,\n    exact h\u03c6.1.snd },\n  { suffices : definable S (\u03bb (p : s\u1d9c), (\u03c6 p.val).2),\n    { convert this,\n      ext \u27e8k, hk\u27e9,\n      change dite _ _ _ = (\u03c6 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\u03c6.comp definable.subtype.val) }\nend\n\nlemma definable_roption_map :\n  definable S (roption.map : (X \u2192 Y) \u2192 roption X \u2192 roption Y) :=\nbegin\n  rw definable_iff_uncurry,\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  refine \u27e8h\u03c6.2.fst, _\u27e9,\n  change definable S (\u03bb (p : {k | (\u03c6 k).2.dom}), (\u03c6 p.1).1 (pfun.as_subtype (prod.snd \u2218 \u03c6) p)),\n  begin [defin]\n    intro p,\n    app,\n    app, exact definable.fst.definable _,\n    app, exact (definable_yoneda.mpr h\u03c6).definable _,\n    app, exact definable.subtype.val.definable _,\n    var,\n    app, exact h\u03c6.2.snd.definable _, var\n  end\nend\n\ninstance pfun.definable_sheaf : definable_sheaf S (X \u2192. Y) :=\nshow definable_sheaf S (X \u2192 roption Y), by apply_instance\n\nlemma definable_pfun_of_graph {Z : Type*} [has_coordinates R Z] [definable_rep S Z]\n  {f : X \u2192. Z} (df : definable S {p : X \u00d7 Z | p.2 \u2208 f p.1}) : definable S f :=\nbegin\n  rw definable_fun,\n  intros K \u03c6 h\u03c6,\n  rw \u2190definable_yoneda at h\u03c6,\n  have d : def_set S (pfun.dom (f \u2218 \u03c6)),\n  { suffices : def_set S {k : K | \u2203 z : Z, z \u2208 f (\u03c6 k)},\n    { convert this,\n      ext k,\n      simp [pfun.mem_dom] },\n    apply def_set.exists,\n    let \u03c8 : K \u00d7 Z \u2192 X \u00d7 Z := \u03bb p, (\u03c6 p.1, p.2),\n    have d\u03c8 : definable S \u03c8,\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\u03c6.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\u03c8) },\n  refine \u27e8d, _\u27e9,\n  apply definable_of_graph,\n  let \u03c8 : pfun.dom (f \u2218 \u03c6) \u00d7 Z \u2192 X \u00d7 Z := \u03bb p, (\u03c6 p.1.val, p.2),\n  have d\u03c8 : definable S \u03c8,\n  begin [defin]                 -- TODO: ... and this\n    intro p,\n    app, app, exact definable.prod_mk.definable _,\n    app, exact h\u03c6.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\u03c8,\n  ext \u27e8\u27e8k, h\u27e9, z\u27e9,\n  change (f (\u03c6 k)).get _ = z \u2194 z \u2208 f (\u03c6 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( \u03b1 : Type )\n( \u03b2 : \u03b1 \u2192 Type )\n\nvariable (P : PFunctor)\n\nnamespace PFunctor\n\ndef obj (X : Type) : Type :=\n\u03a3 (a : P.\u03b1), P.\u03b2 a \u2192 X\n\ndef map {X Y : Type} (f : X \u2192 Y) (x : P.obj X) : P.obj Y :=\n\u27e8x.1, \u03bb a => f (x.2 a)\u27e9\n\ninductive Z (P : PFunctor) : Type\n| bud : Z P\n| some (a : P.\u03b1) (f : P.\u03b2 a \u2192 Z P) : Z P\n\nvariable {P}\n\ndef of_\u03b1 (a : P.\u03b1) : Z P :=\nZ.some a (\u03bb _ => Z.bud)\n\ndef bud : (z : Z P) \u2192 Type\n| Z.bud => Unit\n| Z.some a f => \u03a3 (a : P.\u03b2 a), bud (f a)\n\ndef extend : (z : Z P) \u2192 (b : bud z \u2192 P.\u03b1) \u2192 Z P\n| Z.bud, b => Z.some (b ()) (\u03bb _ => Z.bud)\n| Z.some a f, b => Z.some a (\u03bb bpa => extend (f bpa) (\u03bb bf => b \u27e8bpa, bf\u27e9))\n\ntheorem extend_injective_right : {z : Z P} \u2192 {b\u2081 b\u2082 : bud z \u2192 P.\u03b1} \u2192 \n  extend z b\u2081 = extend z b\u2082 \u2192 b\u2081 = b\u2082\n| Z.bud, b\u2081, b\u2082, h => funext (\u03bb x => by\ncases x; simp [extend] at h; exact h.1)\n| Z.some a f, b\u2081, b\u2082, h => by\n  apply funext\n  intro x\n  simp [extend] at h\n  dsimp [bud] at x\n  match x with \n  | \u27e8x\u2081, x\u2082\u27e9 => exact congrFun (extend_injective_right (congrFun h x\u2081)) x\u2082\n\n@[simp] def bud_of_bud_extend : {z : Z P} \u2192 {bz : bud z \u2192 P.\u03b1} \u2192 (b : bud (extend z bz)) \u2192 bud z\n| Z.bud, _, _ => ()\n| Z.some _ _, _, \u27e8pba, b\u27e9 => \u27e8pba, bud_of_bud_extend b\u27e9\n\n@[simp] def \u03b2_of_bud_extend : {z : Z P} \u2192 {bz : bud z \u2192 P.\u03b1} \u2192 (b : bud (extend z bz)) \u2192 \n  P.\u03b2 (bz (bud_of_bud_extend b))\n| Z.bud, _, b => b.1\n| Z.some _ _, _, \u27e8_, b\u27e9 => \u03b2_of_bud_extend b\n\ndef mk_bud_extend : (z : Z P) \u2192 (bz : bud z \u2192 P.\u03b1) \u2192 (b : bud z) \u2192 \n  (bp : P.\u03b2 (bz b)) \u2192 bud (extend z bz) \n| Z.bud, _, _, bp => \u27e8bp, ()\u27e9\n| Z.some _ _, _, b, bp => \u27e8b.1, mk_bud_extend _ _ b.2 bp\u27e9\n\n@[simp] theorem bud_of_bud_extend_mk_bud_extend : {z : Z P} \u2192 {bz : bud z \u2192 P.\u03b1} \n  \u2192 (b : bud z) \u2192 (bp : P.\u03b2 (bz b)) \u2192 bud_of_bud_extend (mk_bud_extend z bz b bp) = b\n| Z.bud, _, _, _ => rfl\n| Z.some a f, bz, \u27e8_, _\u27e9, bp => by \nsimp [bud_of_bud_extend, mk_bud_extend]\nsimp [bud_of_bud_extend_mk_bud_extend]\n\n@[simp] theorem \u03b2_of_bud_extend_mk_bud_extend : {z : Z P} \u2192 {bz : bud z \u2192 P.\u03b1} \n  \u2192 (b : bud z) \u2192 (bp : P.\u03b2 (bz b)) \u2192 \u03b2_of_bud_extend (mk_bud_extend z bz b bp) = \n    cast (by simp) bp \n| Z.bud, _, _, _ => rfl\n| Z.some _ _, _, _, _ => by\nsimp [\u03b2_of_bud_extend, mk_bud_extend]\nsimp [\u03b2_of_bud_extend_mk_bud_extend]\n\nstructure M (P : PFunctor) : Type :=\n( seq : Nat \u2192 Z P )\n( leaf : (n : Nat) \u2192 bud (seq n) \u2192 P.\u03b1 )\n( zero_eq : seq 0 = Z.bud )\n( succ_eq : (n : Nat) \u2192 seq (n+1) = extend (seq n) (leaf n) )\n\ntheorem M_ext : {m\u2081 m\u2082 : M P} \u2192 (h : \u2200 n, m\u2081.seq n = m\u2082.seq n) \u2192 m\u2081 = m\u2082 \n| \u27e8seq\u2081, leaf\u2081, zero_eq\u2081, succ_eq\u2081\u27e9, \n  \u27e8seq\u2082, leaf\u2082, zero_eq\u2082, succ_eq\u2082\u27e9, h => by\nsimp only [M.mk.injEq]\nhave hseq : seq\u2081 = seq\u2082 := funext h\nsubst hseq\nsimp\napply funext\nintro n\napply funext\nintro b\nhave := (succ_eq\u2081 n).symm.trans (succ_eq\u2082 n)\nrw [extend_injective_right this]\n\ntheorem M_ext2 {m\u2081 m\u2082 : M P} (h : \u2200 (n : Nat) (h : m\u2081.seq n = m\u2082.seq n),\n  m\u2081.leaf n = (\u03bb b => m\u2082.leaf n (by rw [\u2190 h]; exact b))) : m\u2081 = m\u2082 := 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.\u03b2 (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.\u03b2 (m.leaf 0 bud_zero)) : \n  (n : Nat) \u2192 (z : Z P) \u00d7 (bud z \u2192 bud (m.seq (n+1)))\n| 0 => \u27e8Z.bud, \u03bb _ => bud_succ bud_zero p\u27e9\n| n+1 => \nlet sn := M_coalg_seq_aux m p n\n\u27e8extend sn.1 (\u03bb b =>  m.leaf _ (sn.2 b)), \n  \u03bb b => bud_succ (sn.2 (bud_of_bud_extend b)) (\u03b2_of_bud_extend b) \u27e9 \n\ndef M_coalg (m : M P) : P.obj (M P) :=\n\u27e8m.leaf 0 bud_zero, \n  \u03bb b => \n    { seq := \u03bb n => (M_coalg_seq_aux m b n).1,\n      leaf := \u03bb 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 := \u03bb n => by rfl }\u27e9\n\ntheorem M_coalg_snd (m : M P) : (M_coalg m).2 = \n   \u03bb b => \n    { seq := \u03bb n => (M_coalg_seq_aux m b n).1,\n      leaf := \u03bb n => _,\n      zero_eq := rfl,\n      succ_eq := \u03bb n => by rfl } := rfl\n\ntheorem M_coalg_snd_app_seq (m : M P) \n  (b : P.\u03b2 (M_coalg m).1) : ((M_coalg m).2 b).seq = \n    \u03bb n => (M_coalg_seq_aux m b n).1 := rfl\n\ndef to_M_seq_aux {A : Type} (coalg : A \u2192 P.obj A) (a : A) : \n  Nat \u2192 (z : Z P) \u00d7 (bud z \u2192 A)\n| 0 => \u27e8Z.bud, \u03bb _ => a\u27e9\n| n+1 => let \u27e8z, bz\u27e9 := to_M_seq_aux coalg a n\n  \u27e8extend z\n    (\u03bb b => (coalg (bz b)).1),\n     \u03bb b => bz (bud_of_bud_extend b) \u27e9\n\ndef to_M {A : Type} (coalg : A \u2192 P.obj A) (a : A) : M P :=\n{ seq := \u03bb n => (to_M_seq_aux coalg a n).1,\n  leaf := \u03bb n b => (coalg ((to_M_seq_aux coalg a n).2 b)).1,\n  zero_eq := rfl,\n  succ_eq := \u03bb _ => rfl }\n\ntheorem obj_ext {A : Type} {a b : P.obj A} \n  (h\u2081 : a.1 = b.1) (h\u2082 : \u2200 (x : P.\u03b2 a.1), a.2 x = b.2 (cast (by rw [h\u2081]) x)) :\n  a = b := \nmatch a, b with\n| \u27e8a\u2081, a\u2082\u27e9, \u27e8b\u2081, b\u2082\u27e9 => by\ndsimp at h\u2081\nsubst h\u2081\ndsimp [cast] at h\u2082\nsimp [funext h\u2082]\n\ntheorem coalg_to_M {A : Type} (coalg : A \u2192 P.obj A) (a : A) \n  (x : P.\u03b2 (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 \u2192 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 \u2192 P.obj A) (a : A) \n  (f : A \u2192 M P) (f_hom : \u2200 (a : A), M_coalg (f a) = P.map f (coalg a)) :\n  (n : Nat) \u2192 (show \u03a3 (z : Z P), bud z \u2192 P.\u03b1 from \u27e8(f a).seq n, (f a).leaf n\u27e9) =\n  \u27e8(to_M_seq_aux coalg a n).1, \n    \u03bb b => (coalg ((to_M_seq_aux coalg a n).2 b)).1\u27e9\n| 0 => by\n  specialize f_hom a\n  have := congrArg Sigma.fst f_hom\n  dsimp [M_coalg] at this \u22a2\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 \u2192 P.obj A) (a : A) \n  (f : A \u2192 M P) (f_hom : \u2200 (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 \u22a2\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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_nondet_bigint3 \u03c3.pc)\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 3))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u03c4.ap = \u03c3.ap + 8 \u2227\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 3)) (mem $ \u03c4.ap - 4)\n        (spec_nondet_bigint3 mem \u03ba range_check_ptr (mem (\u03c4.ap - 4)) (cast_BigInt3 mem (\u03c4.ap - 3)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  have h_mem_rec := h_mem,\n  unpack_memory code_nondet_bigint3 at h_mem with \u27e8hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11\u27e9,\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\u2081: (range_check_ptr + 4 : F) = range_check_ptr\u2081,\n  have hl_range_check_ptr\u2081 := hl_rev_range_check_ptr\u2081.symm, clear hl_rev_range_check_ptr\u2081,\n  have htv_range_check_ptr\u2081: range_check_ptr\u2081 = _, {\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\u2081] },\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\u2081 }, try { arith_simps at hl_range_check_ptr\u2081 },\n  -- assert eq\n  step_assert_eq hpc8 with temp0,\n  have a8: mem (range_check_ptr\u2081 - 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\u2081, htv_range_check_ptr\u2081] },\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\u2081 - 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\u2081, htv_range_check_ptr\u2081] },\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\u2081 - 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\u2081, htv_range_check_ptr\u2081] },\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 [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n  have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081,try { norm_cast at rc_h_range_check_ptr\u2081' },\n  use_only [range_check_ptr\u2081, hl_range_check_ptr\u2081],\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\u2081, 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\u2081, 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\u2081, 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\u2081, htv_range_check_ptr\u2081] }, },\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 \u00ab\u3053\u3093\u306b\u3061\u306f\u00bb := \"hello\"\n#eval \u00ab\u3053\u3093\u306b\u3061\u306f\u00bb++\u00ab\u3053\u3093\u306b\u3061\u306f\u00bb\n\ndef say (a : String) := a.capitalize\n#eval say \u00ab\u3053\u3093\u306b\u3061\u306f\u00bb\n\n-- WRAP Sbar[decl] (e0:evt)\u00d7 (\u8a89\u3081\u308b/\u307b\u3081\u308b/\u30ac\u30f2(e0,\u592a\u90ce/\u305f\u308d\u3046;\u592a\u90ce/\u305f\u308d\u3046,\u6b21\u90ce/\u3058\u308d\u3046)) [0.85]\n--   > S[v:1<1>][term|attr<4>][] \u03bbx0.(e0:evt)\u00d7 (u0:\u8a89\u3081\u308b/\u307b\u3081\u308b/\u30ac\u30f2(e0,\u592a\u90ce/\u305f\u308d\u3046;\u592a\u90ce/\u305f\u308d\u3046,\u6b21\u90ce/\u3058\u308d\u3046))\u00d7 x0(e0) [0.95]\n--     > T1/(T1\\NP[ga]) \u03bbx0.x0(\u592a\u90ce/\u305f\u308d\u3046;\u592a\u90ce/\u305f\u308d\u3046) [0.99]\n--       LEX \u592a\u90ce T1/(T1\\NP[nc]) \u03bbx0.x0(\u592a\u90ce/\u305f\u308d\u3046;\u592a\u90ce/\u305f\u308d\u3046) (PN) [0.99]\n--       LEX \u304c T1/(T1\\NP[ga])\\NP[nc] \u03bbx0.\u03bbx1.x1(x0) (524) [1.00]\n--     > S[v:1<1>][term|attr<4>][]\\NP[ga] \u03bbx0.\u03bbx1.(e0:evt)\u00d7 (u0:\u8a89\u3081\u308b/\u307b\u3081\u308b/\u30ac\u30f2(e0,x0,\u6b21\u90ce/\u3058\u308d\u3046))\u00d7 x1(e0) [0.96]\n--       > T1/(T1\\NP[o]) \u03bbx0.x0(\u6b21\u90ce/\u3058\u308d\u3046) [0.99]\n--         LEX \u6b21\u90ce T1/(T1\\NP[nc]) \u03bbx0.x0(\u6b21\u90ce/\u3058\u308d\u3046) (PN) [0.99]\n--         LEX \u3092 T1/(T1\\NP[o])\\NP[nc] \u03bbx0.\u03bbx1.x1(x0) (524) [1.00]\n--       <B2 S[v:1<1>][term|attr][]\\NP[ga]\\NP[o] \u03bbx0.\u03bbx1.\u03bbx2.(e0:evt)\u00d7 (u0:\u8a89\u3081\u308b/\u307b\u3081\u308b/\u30ac\u30f2(e0,x1,x0))\u00d7 x2(e0) [0.97]\n--         LEX \u307b\u3081 S[v:1][stem|neg|cont|+][]\\NP[ga]\\NP[o] \u03bbx0.\u03bbx1.\u03bbx2.(e0:evt)\u00d7 (u0:\u8a89\u3081\u308b/\u307b\u3081\u308b/\u30ac\u30f2(e0,x1,x0))\u00d7 x2(e0) (JCon) [0.97]\n--         LEX \u308b S[v:5:r|v:1|v:5:ARU|+<1>][term|attr][]\\S[v:5:r|v:1|v:5:ARU|+<1>][stem][] \u03bbx0.x0 (125) [1.00]\n-- Sig. [\u592a\u90ce/\u305f\u308d\u3046;\u592a\u90ce/\u305f\u308d\u3046:entity, \u6b21\u90ce/\u3058\u308d\u3046:entity, \u8a89\u3081\u308b/\u307b\u3081\u308b/\u30ac\u30f2:(x0:entity)\u2192 (x1:entity)\u2192 (e0:evt)\u2192 type]\n\nstructure Entity where\n  entity : Name\nopen Entity\n\ndef taro : Entity := \u27e8`a\u27e9\ndef jiro : Entity := \u27e8`b\u27e9\nexample : taro \u2260 jiro := by \n  admit\n\ndef \u00ab\u592a\u90ce\u304c\u00bb :Entity := \u27e8`\u00ab\u592a\u90ce\u304c\u00bb\u27e9\ndef \u00ab\u6b21\u90ce\u3092\u00bb :Entity := \u27e8`\u00ab\u6b21\u90ce\u3092\u00bb\u27e9\n\n-- i==2 -> S\\NP\\NP:       \\y.\\x.\\c.(e:event)X(op(e,x,y)X(ce)\ninductive \u00ab\u307b\u3081\u308bsr\u00bb (ga wo : Entity) : Prop where\n  | rel : Entity -> Entity -> \u00ab\u307b\u3081\u308bsr\u00bb ga wo\n\n#check \u00ab\u307b\u3081\u308bsr\u00bb ({entity := `aa} : Entity) ({entity := `aa} : Entity)\ndef \u00ab\u307b\u3081\u308b\u00bb (ga wo : Entity) : Prop := \u00ab\u307b\u3081\u308bsr\u00bb ga wo\n\n#check \u00ab\u307b\u3081\u308b\u00bb \u00ab\u592a\u90ce\u304c\u00bb \u00ab\u6b21\u90ce\u3092\u00bb \ndef A := \u00ab\u307b\u3081\u308b\u00bb \u00ab\u592a\u90ce\u304c\u00bb \u00ab\u6b21\u90ce\u3092\u00bb \ndef B := \u00ab\u307b\u3081\u308b\u00bb \u00ab\u6b21\u90ce\u3092\u00bb \u00ab\u592a\u90ce\u304c\u00bb\n\n\ndef getCtors (typ : Name) : MetaM (List Name) := do\n  let env \u2190 getEnv\n  match env.find? typ with\n  | some (ConstantInfo.inductInfo val) =>\n    pure val.ctors\n  | _ => pure []\n\nsyntax (name := myanon) \"\u27e8\u27e8\" term+ \"\u27e9\u27e9\" : 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] \u2190 getCtors base | throwError \"type doesn't have exactly one constructor\"\n  logInfo s!\"stx:{stx}\"\n  let stx \u2190 `($(mkIdent ctor) $args*) -- syntax quotations\n  logInfo s!\"stx2:{stx}\"\n  elabTerm stx typ -- call term elaboration recursively\n\n-- #check (\u27e8\u27e81 sorry\u27e9\u27e9 : Fin 12)\n-- def oo: List Char := \u27e8\u27e8 hello \u27e9\u27e9\ndeclare_syntax_cat hoge\nsyntax term : hoge\ndeclare_syntax_cat ja_expr\nsyntax \"\u3053\u3093\u306b\u3061\u306f\" : ja_expr\nsyntax \"\u8a00\u3046\" : ja_expr\n-- \u304a\u305d\u3089\u304f{\u4efb\u610f\u306e\u6587\u6cd5}+\u3092\u4f7f\u3063\u3066\u3044\u308b\u5834\u5408\u3001\u7a7a\u767d\u304c\u5b58\u5728\u3059\u308b\u3060\u3051\u3067Term.app\u306e\u30d1\u30fc\u30b5\u30fc\u304c\u5f53\u305f\u3063\u3066\u3057\u307e\u3046\u3088\u3046\u3067\u3042\u308b\n-- \u7a7a\u767d\u306f\u8996\u8a8d\u6027\u304c\u60aa\u304f\u3001\u7a7a\u767d\u304c\u5b58\u5728\u3059\u308b\u304b\u3069\u3046\u304b\u3067\u632f\u308b\u821e\u3044\u5909\u308f\u308b\u306e\u306f\u671b\u307e\u3057\u304f\u306a\u3044\u306e\u3067\n-- Term.app \u306e\u30d1\u30fc\u30b5\u30fc\u304c\u5f53\u305f\u3089\u306a\u3044\u3088\u3046\u306b\u56de\u907f\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\n-- \u8abf\u67fb\u306e\u7d50\u679c{\u4efb\u610f\u306e\u6587\u6cd5}+\u3067\u5f53\u305f\u3063\u3066\u3057\u307e\u3046\u3088\u3046\u306a\u306e\u3067\u3001\u6ce5\u81ed\u304fTerm.app\u304b\u3069\u3046\u304b\u3067\u5834\u5408\u5206\u3051\u3057\u305f\u307b\u3046\u304c\u3044\u3044\u304b\u3082\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(\u3053\u3093\u306b\u3061\u306f)\n#eval ja(\u3053\u3093\u306b\u3061\u306f\u8a00\u3046)\n#eval ja(\u00ab\u307b\u3081\u308b\u00bb \u00ab\u592a\u90ce\u304c\u00bb \u00ab\u6b21\u90ce\u3092\u00bb)\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 Yatima.Typechecker.TypecheckM\nimport Lean.PrettyPrinter\n\n/-!\n# Typechecker printing\n\nThis module provides rudimentary printing for universes, expressions, and values used for debugging\nthe typechecker.\n-/\n\nopen Lean\n\nopen Yatima.Typechecker in\ndef Yatima.Typechecker.ConstNames.getF\n    (constNames : ConstNames) (f : Lurk.F) : Format :=\n  match constNames.find? f with\n  | some name => toString name\n  | none => toString f\n\nnamespace Yatima.IR\nopen Yatima.Typechecker\n\nprivate abbrev indentD := Std.Format.indentD\n\nprivate def join (as : Array \u03b1) (f : \u03b1 \u2192 Format) : Format := Id.run do\n  if h : 0 < as.size then\n    let mut result \u2190 f as[0]\n    for a in as[1:] do\n      result := f!\"{result} {\u2190 f a}\"\n    return result\n  else\n    return .nil\n\nprivate def prefixJoin (pre : Format) (as : Array \u03b1) (f : \u03b1 \u2192 TypecheckM Format) : TypecheckM Format := do\n  let mut result := .nil\n  for a in as do\n    result := f!\"{result}{pre}{\u2190 f a}\"\n  return result\n\ndef Expr.isProp : Expr \u2192 Bool\n  | .sort .zero => true\n  | _ => false\n\ndef Expr.isAtom : Expr \u2192 Bool\n  | .const .. | .var .. | .lit .. => true\n  | .proj _ e => isAtom e\n  | e => isProp e\n\ndef Expr.isBinder : Expr \u2192 Bool\n  | .lam .. | .pi .. => true\n  | _ => false\n\ndef Expr.isArrow : Expr \u2192 Bool\n  -- | .pi dom img => !(body.isVarFree name) && bInfo == .default\n  | _ => false\n\nnamespace PP\n\ninstance : ToFormat BinderInfo where format\n  | .default        => \"default\"\n  | .implicit       => \"implicit\"\n  | .strictImplicit => \"strict\"\n  | .instImplicit   => \"inst\"\n\ninstance : ToFormat QuotKind where format\n  | .type => \"Quot\"\n  | .ctor => \"Quot.mk\"\n  | .lift => \"Quot.lift\"\n  | .ind  => \"Quot.ind\"\n\nopen Std.Format in\nmutual\n  partial def paren (e : Expr) : TypecheckM Format :=\n    if e.isAtom then ppExpr e\n    else return f!\"({\u2190 ppExpr e})\"\n\n  partial def ppUniv (u : Univ) : Format :=\n    match u with\n    | .succ a   => s!\"{ppSuccUniv 1 a}\"\n    | .zero     => \"0\"\n    | .imax a b => s!\"(imax {ppUniv a} {ppUniv b})\"\n    | .max  a b => s!\"(max {ppUniv a} {ppUniv b})\"\n    | .var  i => s!\"_#{i}\"\n\n  partial def ppSuccUniv (acc : Nat) : Univ \u2192 Format\n    | .zero => s!\"{acc}\"\n    | .succ u => ppSuccUniv (acc + 1) u\n    | u => s!\"{acc}+{ppUniv u}\"\n\n  partial def ppUnivs (us : List Univ) : Format :=\n    bracket \"{\" (joinSep (us.map ppUniv) \", \") \"}\"\n\n  partial def ppExpr (e : Expr) : TypecheckM Format := do\n    let constNames := (\u2190 read).constNames\n    match e with\n    | .var name us => return f!\"v_{name}@{ppUnivs us}\"\n    | .sort u => return f!\"Sort {ppUniv u}\"\n    | .const name us =>\n      return f!\"{constNames.getF name}@{ppUnivs us}\"\n    | .app func body => match func with\n      | .app .. => return f!\"{\u2190 ppExpr func} {\u2190 paren body}\"\n      | _ => return f!\"{\u2190 paren func} {\u2190 paren body}\"\n    | .lam type body =>\n      return f!\"fun (_ : {\u2190 ppExpr type}) =>{indentD (\u2190 ppExpr body)}\"\n    | .pi dom img =>\n      return f!\"(_ : {\u2190 ppExpr dom}) \u2192 {\u2190 ppExpr img}\"\n    | .letE type value body =>\n      return f!\"let _ : {\u2190 ppExpr type} := {\u2190 ppExpr value}\"\n        ++ \";\" ++ .line ++ f!\"{\u2190 ppExpr body}\"\n    | .lit lit => match lit with\n      | .natVal num => return f!\"{num}\"\n      | .strVal str => return f!\"\\\"{str}\\\"\"\n    | .proj idx expr => return f!\"{\u2190 paren expr}.{idx})\"\nend\n\npartial def ppDefinition (defn : Definition) : TypecheckM Format :=\n  let part := if defn.part then \"partial \" else \"\"\n  return f!\"{part}def _ {defn.lvls} : {\u2190 ppExpr defn.type} :={indentD (\u2190 ppExpr defn.value)}\"\n\npartial def ppRecursorRule (rule : RecursorRule) : TypecheckM Format :=\n  return f!\"fields := {rule.fields}\" ++ .line ++ f!\"{\u2190 ppExpr rule.rhs}\"\n\npartial def ppRecursor (recr : Recursor) : TypecheckM Format :=\n  let rules := Array.mk recr.rules\n  let internal := if recr.internal then \"internal\" else \"external\"\n  return f!\"{internal} recursor _ (lvls := {recr.lvls}) : {\u2190 ppExpr recr.type}{indentD (\u2190 prefixJoin .line rules ppRecursorRule)}\"\n\npartial def ppConstructor (ctor : Constructor) : TypecheckM Format :=\n  let fields := f!\"idx := {ctor.idx}\" ++ .line ++\n                f!\"params := {ctor.params}\" ++ .line ++\n                f!\"fields := {ctor.fields}\"\n  return f!\"| _ {ctor.lvls} : {\u2190 ppExpr ctor.type}{indentD fields}\"\n\npartial def ppConstructors (ctors : List Constructor) : TypecheckM Format :=\n  return f!\"{\u2190 prefixJoin .line (Array.mk ctors) ppConstructor}\"\n\npartial def ppInductive (ind : Inductive) : TypecheckM Format := do\n  let indHeader := f!\"inductive _ {ind.lvls} : {\u2190 ppExpr ind.type}\"\n  let fields := f!\"recr := {ind.recr}\" ++ .line ++\n                f!\"refl := {ind.refl}\" ++ .line ++\n                f!\"unit := {ind.unit}\" ++ .line ++\n                f!\"params := {ind.params}\" ++ .line ++\n                f!\"indices := {ind.indices}\" ++ .line ++\n                f!\"struct := {ind.struct}\"\n  return f!\"{indHeader} with{indentD fields}\"\n\npartial def ppConst (const : Const) : TypecheckM Format :=\n  match const with\n  | .axiom ax => return f!\"axiom _ {ax.lvls} : {\u2190 ppExpr ax.type}\"\n  | .theorem thm =>\n    return f!\"theorem _ {thm.lvls} : {\u2190 ppExpr thm.type} :={indentD (\u2190 ppExpr thm.value)}\"\n  | .opaque opaq =>\n    return f!\"opaque _ {opaq.lvls} {\u2190 ppExpr opaq.type} :={indentD (\u2190 ppExpr opaq.value)}\"\n  | .quotient quot =>\n    return f!\"quot _ {quot.lvls} : {\u2190 ppExpr quot.type} :={indentD (format quot.kind)}\"\n  | .definition defn =>\n    ppDefinition defn\n  | .inductiveProj ind => return f!\"{reprStr ind}\"\n  | .constructorProj ctor => return f!\"{reprStr ctor}\"\n  | .recursorProj recr => return f!\"{reprStr recr}\"\n  | .definitionProj defn => return f!\"{reprStr defn}\"\n  | .mutDefBlock block =>\n    return f!\"{\u2190 prefixJoin (\"\\n\" ++ .line) (Array.mk block) ppDefinition}\"\n  | .mutIndBlock block =>\n    return f!\"{\u2190 prefixJoin (\"\\n\" ++ .line) (Array.mk block) ppInductive}\"\n\nend Yatima.IR.PP\n\nnamespace Yatima.Typechecker\n\nopen IR PP Lean Std.Format\n\nprivate abbrev indentD := Std.Format.indentD\n\ndef TypedExpr.isProp (t : TypedExpr) : Bool := match t.expr with\n  | .sort .zero => true\n  | _ => false\n\ndef TypedExpr.isAtom (t : TypedExpr) : Bool :=\n  -- For some reason, Lean can't prove termination when you use projections\n  let .mk _ expr := t\n  match expr with\n  | .const .. | .var .. | .lit .. => true\n  | .proj _ _ e => isAtom e\n  | _ => isProp t\n\nnamespace PP\n\nmutual\n  partial def paren (e : TypedExpr) : TypecheckM Format :=\n    if e.isAtom then ppTypedExpr e\n    else return f!\"({\u2190 ppTypedExpr e})\"\n\n  /-- Printer of expressions -/\n  partial def ppTypedExpr (t : TypedExpr) : TypecheckM Format := match t.expr with\n    | .var idx => return f!\"v_{idx}\"\n    | .sort u => return f!\"Sort {ppUniv u}\"\n    | .const k univs =>\n      return f!\"{(\u2190 read).constNames.getF k}@{ppUnivs univs}\"\n    | .app fnc arg => match fnc.expr with\n      | .app .. => return f!\"{\u2190 ppTypedExpr fnc} {\u2190 paren arg}\"\n      | _ => return f!\"{\u2190 paren fnc} {\u2190 paren arg}\"\n    | .lam dom bod =>\n      return f!\"fun (_ : {\u2190 ppTypedExpr dom}) =>{indentD (\u2190 ppTypedExpr bod)}\"\n    | .pi dom cod =>\n      return f!\"(_: {\u2190 ppTypedExpr dom}) \u2192 {\u2190 ppTypedExpr cod}\"\n    | .letE typ val bod => return f!\"let _ : {\u2190 ppTypedExpr typ} := {\u2190 ppTypedExpr val} in {\u2190 ppTypedExpr bod}\"\n    | .lit (.natVal x) => return f!\"{x}\"\n    | .lit (.strVal x) => return f!\"\\\"{x}\\\"\"\n    | .proj _ idx val => return f!\"{\u2190 ppTypedExpr val}.{idx}\"\n\nend\n\nmutual\n  partial def parenWith (e : TypedExpr) (env : Env) : TypecheckM Format :=\n    if e.isAtom then ppTypedExprWith e env\n    else return f!\"({\u2190 ppTypedExprWith e env})\"\n\n  /-- Auxiliary function to print the body of a lambda expression given `env : Env` -/\n  private partial def ppTypedExprWith (t : TypedExpr) (env : Env) : TypecheckM Format :=\n    match t.expr with\n    | .var 0 => return f!\"v_0\"\n    | .var (idx + 1) =>\n      match env.exprs.get? idx with\n     | some val => ppValue val.get\n     | none => return f!\"!_@{idx}!\"\n    | .sort u => return f!\"Sort {ppUniv u}\"\n    | .const k univs => return f!\"{(\u2190 read).constNames.getF k}@{ppUnivs univs}\"\n    | .app fnc arg => match fnc.expr with\n      | .app .. => return f!\"{\u2190 ppTypedExprWith fnc env} {\u2190 parenWith arg env}\"\n      | _ => return f!\"{\u2190 parenWith fnc env} {\u2190 parenWith arg env}\"\n    -- | .app _ fnc arg => f!\"({\u2190 ppTypedExprWith fnc env} {\u2190 ppTypedExprWith arg env})\"\n    | .lam dom bod =>\n      return f!\"fun (_ : {\u2190 ppTypedExprWith dom env}) =>{indentD (\u2190 ppTypedExprWith bod env)}\"\n    | .pi dom cod =>\n      return f!\"(_ : {\u2190 ppTypedExprWith dom env}) \u2192 {\u2190 ppTypedExprWith cod env}\"\n    | .letE typ val bod => return f!\"let _ : {\u2190 ppTypedExprWith typ env} := {\u2190 ppTypedExprWith val env} in {\u2190 ppTypedExprWith bod env}\"\n    | .lit (.natVal x) => return f!\"{x}\"\n    | .lit (.strVal x) => return f!\"\\\"{x}\\\"\"\n    | .proj _ idx val => return f!\"{\u2190 ppTypedExprWith val env}.{idx}\"\n\n  private partial def ppNeutral (neu : Neutral) : TypecheckM Format := match neu with\n    | .fvar idx .. => return f!\"fv_{idx}\"\n    | .const k univs => return f!\"{(\u2190 read).constNames.getF k}@{ppUnivs univs}\"\n    | .proj _ idx val => return f!\"{\u2190 ppValue val.value}.{idx}\"\n\n  /-- Auxiliary function to print a chain of unevaluated applications as a single application -/\n  private partial def ppSpine (neu : Neutral) (args : Args) : TypecheckM Format := do\n    List.foldrM (fun arg str => return f!\"{str} {\u2190 ppValue arg.get}\") (\u2190 ppNeutral neu) args\n\n  /-- Printer of typechecker values -/\n  partial def ppValue (val : Value) : TypecheckM Format :=\n    match val with\n    | .sort u => return f!\"Sort {ppUniv u}\"\n    | .app neu args _ => ppSpine neu args\n    | .lam dom bod ctx =>\n      return f!\"fun (_ : {\u2190 ppValue dom.get}) =>{indentD (\u2190 ppTypedExprWith bod ctx)}\"\n    | .pi dom cod ctx =>\n      return f!\"(_ : {\u2190 ppValue dom.get}) \u2192 {\u2190 ppTypedExprWith cod ctx}\"\n    | .lit (.natVal x) => return f!\"{x}\"\n    | .lit (.strVal x) => return f!\"\\\"{x}\\\"\"\n    | .exception e => return f!\"exception {e}\"\nend\n\n-- instance : ToFormat TypedExpr where format := ppTypedExpr\n-- instance : ToString TypedExpr where toString := pretty \u2218 ppTypedExpr\n-- instance : ToFormat Value where format := ppValue\n-- instance : ToString Value where toString := pretty \u2218 ppValue\n\ndef ppTypecheckCtx : TypecheckM Format := do\n  let \u27e8lvl, env, types, _, _, _, _, _, _, _\u27e9 \u2190 read\n  let env := \u2190 match env with\n    | .mk vals us => do\n      let vals : List Value := vals.map (\u00b7.get)\n      let fields := f!\"vals := {\u2190 vals.mapM ppValue}\" ++ line ++ f!\"us := {us.map ppUniv}\"\n      return f!\"env with{indentD fields}\"\n  let types \u2190 types.mapM fun t => ppValue t.get\n  let fields := f!\"lvl := {lvl}\" ++ line ++ f!\"env := {env}\" ++ line ++ f!\"types := {types}\"\n  return f!\"typecheckCtx with{indentD fields}\"\n\nend Yatima.Typechecker.PP\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/Yatima/Typechecker/Printing.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082128783705344, "lm_q2_score": 0.03732688854889699, "lm_q1q2_score": 0.011975260455207295}}
{"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.basic\nimport tactic.simpa\n\nsetup_tactic_parser\n\nprivate meta def loc.to_string_aux : option name \u2192 string\n| none := \"\u22a2\"\n| (some x) := to_string x\n\n/-- pretty print a `loc` -/\nmeta def loc.to_string : loc \u2192 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\n/-- shift `pos` `n` columns to the left -/\nmeta def pos.move_left (p : pos) (n : \u2115) : pos :=\n{ line := p.line, column := p.column - n }\n\nnamespace tactic\n\nattribute [derive decidable_eq] simp_arg_type\n\n/-- Turn a `simp_arg_type` into a string. -/\nmeta instance simp_arg_type.has_to_string : has_to_string simp_arg_type :=\n\u27e8\u03bb a, match a with\n| simp_arg_type.all_hyps := \"*\"\n| (simp_arg_type.except n) := \"-\" ++ to_string n\n| (simp_arg_type.expr e) := to_string e\n| (simp_arg_type.symm_expr e) := \"\u2190\" ++ to_string e\nend\u27e9\n\nopen list\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\nmeta def struct_inst : lean.parser pexpr :=\ndo tk \"{\",\n   ls \u2190 sep_by (skip_info (tk \",\"))\n     ( sum.inl <$> (tk \"..\" *> texpr) <|>\n       sum.inr <$> (prod.mk <$> ident <* tk \":=\" <*> texpr)),\n   tk \"}\",\n   let (srcs,fields) := partition_map id ls,\n   let (names,values) := unzip fields,\n   pure $ pexpr.mk_structure_instance\n     { field_names := names,\n       field_values := values,\n       sources := srcs }\n\n/-- pretty print structure instance -/\nmeta def struct.to_tactic_format (e : pexpr) : tactic format :=\ndo r \u2190 e.get_structure_instance_info,\n   fs \u2190 mzip_with (\u03bb n v,\n     do v \u2190 to_expr v >>= pp,\n        pure $ format!\"{n} := {v}\" )\n     r.field_names r.field_values,\n   let ss := r.sources.map (\u03bb s, format!\" .. {s}\"),\n   let x : format := format.join $ list.intersperse \", \" (fs ++ ss),\n   pure format!\" {{{x}}}\"\n\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n@[user_attribute]\nprivate meta def squeeze_loc_attr :\n  user_attribute unit (option (list (pos \u00d7 string \u00d7 list simp_arg_type \u00d7 string))) :=\n{ name := `_squeeze_loc,\n  parser := fail \"this attribute should not be used\",\n  descr := \"table to accumulate multiple `squeeze_simp` suggestions\" }\n\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeeze_loc_attr_carrier := ()\n\nrun_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt\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. -/\nmeta def render_simp_arg_list : list simp_arg_type \u2192 format\n| [] := \"\"\n| args := (++) \" \" $ to_line_wrap_format $ args.map to_string\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. -/\nmeta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type)\n  (at_pos := ff) : tactic unit :=\ndo xs \u2190 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       @scope_trace _ p.line p.column $\n         \u03bb _, _root_.trace sformat!\"{pre}{args}{post}\" (pure () : tactic unit)\n     else\n       trace sformat!\"{pre}{args}{post}\"\n   | some xs := do\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff\n   end\n\n/-- translate a `pexpr` into a `simp` configuration -/\nmeta def parse_config : option pexpr \u2192 tactic (simp_config_ext \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr simp_config_ext e\n             <*> struct.to_tactic_format cfg\n\n/-- translate a `pexpr` into a `dsimp` configuration -/\nmeta def parse_dsimp_config : option pexpr \u2192 tactic (dsimp_config \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr dsimp_config e\n             <*> struct.to_tactic_format cfg\n\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\nmeta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool :=\ndo s \u2190 get_proof_state_after tac,\n   pure $ some pr = s\n\n/--\nConsumes the first list of `simp` arguments, accumulating required arguments\non the second one and unnecessary arguments on the third one.\n-/\nprivate meta def filter_simp_set_aux\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (args : list simp_arg_type) (pr : proof_state) :\n  list simp_arg_type \u2192 list simp_arg_type \u2192\n  list simp_arg_type \u2192 tactic (list simp_arg_type \u00d7 list simp_arg_type)\n| [] ys ds := pure (ys, ds)\n| (x :: xs) ys ds :=\n  do b \u2190 same_result pr (tac tt (args ++ xs ++ ys)),\n     if b\n       then filter_simp_set_aux xs ys (ds.concat x)\n       else filter_simp_set_aux xs (ys.concat x) ds\n\ndeclare_trace squeeze.deleted\n\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-/\nmeta def filter_simp_set\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) :=\ndo some s \u2190 get_proof_state_after (tac ff (user_args ++ simp_args)),\n   (simp_args', _)  \u2190 filter_simp_set_aux tac user_args s simp_args [] [],\n   (user_args', ds) \u2190 filter_simp_set_aux tac simp_args' s user_args [] [],\n   when (is_trace_enabled_for `squeeze.deleted = tt \u2227 \u00ac ds.empty)\n     trace!\"deleting provided arguments {ds}\",\n   pure (user_args' ++ simp_args')\n\n/-- make a `simp_arg_type` that references the name given as an argument -/\nmeta def name.to_simp_args (n : name) : simp_arg_type :=\nsimp_arg_type.expr $ @expr.local_const ff n n (default) pexpr.mk_placeholder\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. -/\nmeta def prepend_root_if_needed (n : name) : tactic name :=\ndo x \u2190 resolve_name' n,\nreturn $ match x with\n| expr.macro _ _ := `_root_ ++ n\n| _ := n\nend\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-/\nmeta def squeeze_simp_core\n  (slow no_dflt : bool) (args : list simp_arg_type)\n  (tac : \u03a0 (no_dflt : bool) (args : list simp_arg_type), tactic unit)\n  (mk_suggestion : list simp_arg_type \u2192 tactic unit) : tactic unit :=\ndo v \u2190 target >>= mk_meta_var,\n   args \u2190 if slow then do\n     simp_set \u2190 attribute.get_instances `simp,\n     simp_set \u2190 simp_set.mfilter $ has_attribute' `_refl_lemma,\n     simp_set \u2190 simp_set.mmap $ resolve_name' >=> pure \u2218 simp_arg_type.expr,\n     pure $ args ++ simp_set\n   else pure args,\n   g \u2190 retrieve $ do\n   { g \u2190 main_goal,\n     tac no_dflt args,\n     instantiate_mvars g },\n   let vs := g.list_constant',\n   vs \u2190 vs.mfilter is_simp_lemma,\n   vs \u2190 vs.mmap strip_prefix,\n   vs \u2190 vs.mmap prepend_root_if_needed,\n   with_local_goals' [v] (filter_simp_set tac args $ vs.map name.to_simp_args)\n     >>= mk_suggestion,\n   tac no_dflt args\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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (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-/\nmeta def squeeze_scope (tac : itactic) : tactic unit :=\ndo none \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (),\n   squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff,\n   finally tac $ do\n     some xs \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail \"invalid state\",\n     let m := native.rb_lmap.of_list xs,\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff,\n     m.to_list.reverse.mmap' $ \u03bb \u27e8p,suggs\u27e9, do\n       { let \u27e8pre,_,post\u27e9 := suggs.head,\n         let suggs : list (list simp_arg_type) := suggs.map $ prod.fst \u2218 prod.snd,\n         mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () }\n\n/--\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-/\nmeta def squeeze_simp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\n/-- see `squeeze_simp` -/\nmeta def squeeze_simpa\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (tgt : parse (tk \"using\" *> texpr)?)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   tgt' \u2190 traverse (\u03bb t, do t \u2190 to_expr t >>= pp,\n                            pure format!\" using {t}\") tgt,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            tgt' := tgt'.get_or_else \"\" in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simpa{use_iota_eqn} only\"\n          sformat!\"{attrs}{tgt'}{c}\" args)\n\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 -/\nmeta def squeeze_dsimp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?)\n  (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_dsimp_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: dsimp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\nend interactive\nend tactic\n\nopen tactic.interactive\nadd_tactic_doc\n{ name       := \"squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope\",\n  category   := doc_category.tactic,\n  decl_names :=\n   [``squeeze_simp,\n    ``squeeze_dsimp,\n    ``squeeze_simpa,\n    ``squeeze_scope],\n  tags       := [\"simplification\", \"Try this\"],\n  inherit_description_from := ``squeeze_simp }\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/squeeze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508500761839522, "lm_q2_score": 0.04885778000710959, "lm_q1q2_score": 0.011974309385260331}}
{"text": "syntax \"have\" \":\" term : tactic\nexample : False := by\n  have : True := by simp [  -- should *not* parse the shorter `have` syntax and then fail on `:=`\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/longestParsePrio.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2598256264980406, "lm_q2_score": 0.04603389798216715, "lm_q1q2_score": 0.011960786383363467}}
{"text": "import AwesomeDashboards.Prometheus\n\ndef node_boot_time_seconds : Metric := {\n  name := \"node_boot_time_seconds\"\n  type := MetricType.gauge\n  labels := []\n  unit := MetricUnit.seconds\n}\n\ndef node_filesystem_avail_bytes : Metric := {\n  name := \"node_filesystem_avail_bytes\"\n  type := MetricType.gauge\n  labels := [\"device\", \"fstype\", \"mountpoint\"]\n  unit := MetricUnit.bytes\n}\n\ndef process_cpu_seconds_total : Metric := {\n  name := \"process_cpu_seconds_total\"\n  type := MetricType.counter\n  labels := []\n  unit := MetricUnit.seconds\n}\n\ndef node_network_receive_bytes_total : Metric := {\n  name := \"node_network_receive_bytes_total\"\n  type := MetricType.counter\n  labels := [\"device\"]\n  unit := MetricUnit.bytes\n}\n\ndef node_exporter : Exporter := {\n  metrics := [node_boot_time_seconds, node_filesystem_avail_bytes, process_cpu_seconds_total, node_network_receive_bytes_total]\n}\n\ndef lm : List KeyValuePair := [{key := \"__name__\", value := \"node_filesystem_avail_bytes\"}]\ndef v := InstantVector.selector {equal := lm} 0\n\n#eval InstantVector.typesafe v node_exporter\n#eval List.map (\u03bb l => l.key) (lm.filter $ is_name)\n#eval List.all (lm.filter $ is_name) (\u03bb l => \"node_filesystem_avail_bytes\" = l.key )\n\nexample : InstantVector.typesafe (InstantVector.selector {equal := lm} 0) node_exporter := by simp\n\ndef avail_bytes : InstantVector InstantVectorType.vector := [pql| node_filesystem_avail_bytes-node_filesystem_avail_bytes]\n#eval unitOf node_exporter avail_bytes\n#eval RangeVector.unitOf node_exporter $ RangeVector.selector (LabelMatchers.empty.withName \"node_network_receive_bytes_total\") 5\n#eval unitOf node_exporter [pql| rate(node_network_receive_bytes_total{}[5])]\n#eval [pql| rate(node_network_receive_bytes_total{device=\"vda\"}[120])]", "meta": {"author": "fischerman", "repo": "awesome-dashboards", "sha": "8be794e4edbf36c17ede4426b9980cb489e2af55", "save_path": "github-repos/lean/fischerman-awesome-dashboards", "path": "github-repos/lean/fischerman-awesome-dashboards/awesome-dashboards-8be794e4edbf36c17ede4426b9980cb489e2af55/AwesomeDashboards/NodeExporter.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.02800752334416486, "lm_q1q2_score": 0.011940211955395375}}
{"text": "import .definitions3 .qi\n\nlemma exp.vcgen.extension {P: prop} {e: exp} {Q: propctx}: (P \u22a2 e : Q) \u2192 (P \u22a9 e : Q) :=\n  begin\n\n    assume e_verified: P \u22a2 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\u2081 e\u2082 Q\u2081 Q\u2082 f_not_in_P fx_not_in_P f_neq_fx fx_in_R fv_R fv_S\n                        e\u2081_verified e\u2082_verified func_vc ih\u2081 ih\u2082 {\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\u2081,\n      from ih\u2082,\n      from vc_valid_from_inst_valid func_vc\n    },\n\n    case exp.vcgen.unop op P e' x\u2081 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\u2081 x\u2082 y Q x\u2081_free_in_P x\u2082_free_in_P y_not_in_P e'_verified vc_valid ih {\n      apply exp.dvcgen.binop,\n      from x\u2081_free_in_P,\n      from x\u2082_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\u2081 Q f_free_in_P x\u2081_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\u2081_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\u2081 e\u2082 y Q\u2081 Q\u2082 y_free_in_P e\u2081_verified e\u2082_verified vc_valid ih\u2081 ih\u2082 {\n      apply exp.dvcgen.ite,\n      from y_free_in_P,\n      from ih\u2081,\n      from ih\u2082,\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 \u22a9 exp.return x : Q) \u2192 x \u2208 FV P :=\n  assume return_verified: P \u22a9 exp.return x : Q,\n  begin\n    cases return_verified,\n    case exp.dvcgen.return x_free {\n      show x \u2208 FV P, from x_free\n    }\n  end\n\nlemma stack.dvcgen.top.inv {R: spec} {\u03c3: env} {e: exp} {Q: propctx}:\n  (\u22a9\u209b (R, \u03c3, e) : Q) \u2192\n  \u2203P Q\u2082, (\u22a9 \u03c3: P) \u2227 (FV R.to_prop \u2286 FV P) \u2227 (\u03c3 \u22a8 R.to_prop.to_vc) \u2227 (R \u22c0 P \u22a9 e: Q\u2082) :=\n  assume top_verified: \u22a9\u209b (R, \u03c3, 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 \u2203P Q\u2082, (\u22a9 \u03c3: P) \u2227 (FV R.to_prop \u2286 FV P) \u2227 (\u03c3 \u22a8 R.to_prop.to_vc) \u2227 (R \u22c0 P \u22a9 e: Q\u2082),\n      from exists.intro P (exists.intro Q \u27e8env_verified, \u27e8fv_R, \u27e8R_valid, e_verified\u27e9\u27e9\u27e9) \n    }\n  end\n\nlemma env.dvcgen.inv {\u03c3: env} {P: prop} {x: var} {v: value}:\n      (\u22a9 \u03c3 : P) \u2192 (\u03c3 x = v) \u2192 \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q' :=\n  assume env_verified: \u22a9 \u03c3 : P,\n  assume \u03c3_x_is_v: \u03c3 x = v,\n  show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : 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 \u03c3_x_is_v.symm this,\n      show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q', from false.elim (option.no_confusion this)\n    },\n    case env.dvcgen.tru \u03c3' y Q y_not_in_\u03c3' \u03c3'_verified ih { from\n      have env.apply (\u03c3'[y\u21a6value.true]) x = v, from \u03c3_x_is_v,\n      have h1: (if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191value.true else \u03c3'.apply x) = v,\n      by { unfold env.apply at this, from this },\n      if h2: y = x \u2227 option.is_none (\u03c3'.apply x) then (\n        have (\u2191value.true) = \u2191v, 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_\u03c3': x \u2209 \u03c3', from h2.left \u25b8 y_not_in_\u03c3',\n        have \u22a9 (\u03c3'[x\u21a6value.true]) : Q \u22c0 x \u2261 value.true, from env.dvcgen.tru x_not_in_\u03c3' \u03c3'_verified,\n        have \u22a9 (\u03c3'[x\u21a6v]) : Q \u22c0 x \u2261 value.true, from v_is_true.symm \u25b8 this,\n        show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q',\n        from exists.intro \u03c3' (exists.intro (Q \u22c0 x \u2261 value.true) this)\n      ) else (\n        have (\u03c3'.apply x) = v, by { simp[h2] at h1, from h1 },\n        show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q', from ih this\n      )\n    },\n    case env.dvcgen.fls \u03c3' y Q y_not_in_\u03c3' \u03c3'_verified ih { from\n      have env.apply (\u03c3'[y\u21a6value.false]) x = v, from \u03c3_x_is_v,\n      have h1: (if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191value.false else \u03c3'.apply x) = v,\n      by { unfold env.apply at this, from this },\n      if h2: y = x \u2227 option.is_none (\u03c3'.apply x) then (\n        have (\u2191value.false) = \u2191v, 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_\u03c3': x \u2209 \u03c3', from h2.left \u25b8 y_not_in_\u03c3',\n        have \u22a9 (\u03c3'[x\u21a6value.false]) : Q \u22c0 x \u2261 value.false, from env.dvcgen.fls x_not_in_\u03c3' \u03c3'_verified,\n        have \u22a9 (\u03c3'[x\u21a6v]) : Q \u22c0 x \u2261 value.false, from v_is_false.symm \u25b8 this,\n        show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q',\n        from exists.intro \u03c3' (exists.intro (Q \u22c0 x \u2261 value.false) this)\n      ) else (\n        have (\u03c3'.apply x) = v, by { simp[h2] at h1, from h1 },\n        show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q', from ih this\n      )\n    },\n    case env.dvcgen.num n \u03c3' y Q y_not_in_\u03c3' \u03c3'_verified ih { from\n      have env.apply (\u03c3'[y\u21a6value.num n]) x = v, from \u03c3_x_is_v,\n      have h1: (if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191(value.num n) else \u03c3'.apply x) = v,\n      by { unfold env.apply at this, from this },\n      if h2: y = x \u2227 option.is_none (\u03c3'.apply x) then (\n        have \u2191(value.num n) = \u2191v, 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_\u03c3': x \u2209 \u03c3', from h2.left \u25b8 y_not_in_\u03c3',\n        have \u22a9 (\u03c3'[x\u21a6value.num n]) : Q \u22c0 x \u2261 value.num n, from env.dvcgen.num x_not_in_\u03c3' \u03c3'_verified,\n        have \u22a9 (\u03c3'[x\u21a6v]) : Q \u22c0 x \u2261 value.num n, from v_is_num.symm \u25b8 this,\n        show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q',\n        from exists.intro \u03c3' (exists.intro (Q \u22c0 x \u2261 value.num n) this)\n      ) else (\n        have (\u03c3'.apply x) = v, by { simp[h2] at h1, from h1 },\n        show \u2203\u03c3' Q', \u22a9 (\u03c3'[x\u21a6v]) : Q', from ih this\n      )\n    },\n    case env.dvcgen.func f \u03c3\u2082 \u03c3\u2081 g gx R S e Q\u2081 Q\u2082 Q\u2083 f_not_in_\u03c3\u2081 g_not_in_\u03c3\u2082 gx_not_in_\u03c3\u2082 g_neq_gx\n                        \u03c3\u2081_verified \u03c3\u2082_verified x_free_in_R fv_R fv_S e_verified func_vc ih\u2081 ih\u2082 { from\n      have env.apply (\u03c3\u2081[f\u21a6value.func g gx R S e \u03c3\u2082]) x = v, from \u03c3_x_is_v,\n      have h1: (if f = x \u2227 option.is_none (\u03c3\u2081.apply x) then \u2191(value.func g gx R S e \u03c3\u2082) else \u03c3\u2081.apply x) = v,\n      by { unfold env.apply at this, from this },\n      if h2: f = x \u2227 option.is_none (\u03c3\u2081.apply x) then (\n        have \u2191(value.func g gx R S e \u03c3\u2082) = \u2191v, by { simp[h2] at h1, from h1 },\n        have v_is_num: v = value.func g gx R S e \u03c3\u2082, from (option.some.inj this).symm,\n        have x_not_in_\u03c3\u2081: x \u2209 \u03c3\u2081, from h2.left \u25b8 f_not_in_\u03c3\u2081,\n        have \u22a9 (\u03c3\u2081[x\u21a6value.func g gx R S e \u03c3\u2082]) :\n                  (Q\u2081\n                  \u22c0 x \u2261 value.func g gx R S e \u03c3\u2082\n                  \u22c0 prop.subst_env (\u03c3\u2082[g\u21a6value.func g gx R S e \u03c3\u2082]) (prop.func g gx R (Q\u2083 (term.app g gx) \u22c0 S))),\n        from env.dvcgen.func x_not_in_\u03c3\u2081 g_not_in_\u03c3\u2082 gx_not_in_\u03c3\u2082 g_neq_gx\n                             \u03c3\u2081_verified \u03c3\u2082_verified x_free_in_R fv_R fv_S e_verified func_vc,\n        have \u22a9 (\u03c3\u2081[x\u21a6v]) :\n                  (Q\u2081\n                  \u22c0 x \u2261 value.func g gx R S e \u03c3\u2082\n                  \u22c0 prop.subst_env (\u03c3\u2082[g\u21a6value.func g gx R S e \u03c3\u2082]) (prop.func g gx R (Q\u2083 (term.app g gx) \u22c0 S))),\n        from v_is_num.symm \u25b8 this,\n        show \u2203\u03c3\u2081 Q', \u22a9 (\u03c3\u2081[x\u21a6v]) : Q',\n        from exists.intro \u03c3\u2081 (exists.intro (Q\u2081\n                  \u22c0 x \u2261 value.func g gx R S e \u03c3\u2082\n                  \u22c0 prop.subst_env (\u03c3\u2082[g\u21a6value.func g gx R S e \u03c3\u2082]) (prop.func g gx R (Q\u2083 (term.app g gx) \u22c0 S))) this)\n      ) else (\n        have (\u03c3\u2081.apply x) = v, by { simp[h2] at h1, from h1 },\n        show \u2203\u03c3\u2081 Q\u2081, \u22a9 (\u03c3\u2081[x\u21a6v]) : Q\u2081, from ih\u2081 this\n      )\n    }\n  end\n\nlemma env.dvcgen.tru.inv {\u03c3: env} {x: var} {Q: prop}:\n    (\u22a9 (\u03c3[x \u21a6 value.true]) : Q \u22c0 x \u2261 value.true) \u2192 x \u2209 \u03c3 \u2227 (\u22a9 \u03c3 : Q) :=\n  assume h: \u22a9 (\u03c3[x \u21a6 value.true]) : Q \u22c0 x \u2261 value.true,\n  begin\n    cases h,\n    case env.dvcgen.tru h1 h2 { from \u27e8h1, h2\u27e9 }\n  end\n\nlemma env.dvcgen.fls.inv {\u03c3: env} {x: var} {Q: prop}:\n    (\u22a9 (\u03c3[x \u21a6 value.false]) : Q \u22c0 x \u2261 value.false) \u2192 x \u2209 \u03c3 \u2227 (\u22a9 \u03c3 : Q) :=\n  assume h: \u22a9 (\u03c3[x \u21a6 value.false]) : Q \u22c0 x \u2261 value.false,\n  begin\n    cases h,\n    case env.dvcgen.fls h1 h2 { from \u27e8h1, h2\u27e9 }\n  end\n\nlemma env.dvcgen.num.inv {\u03c3: env} {x: var} {n: \u2115} {Q: prop}:\n    (\u22a9 (\u03c3[x \u21a6 value.num n]) : Q \u22c0 x \u2261 value.num n) \u2192 x \u2209 \u03c3 \u2227 (\u22a9 \u03c3 : Q) :=\n  assume h: \u22a9 (\u03c3[x \u21a6 value.num n]) : Q \u22c0 x \u2261 value.num n,\n  begin\n    cases h,\n    case env.dvcgen.num h1 h2 { from \u27e8h1, h2\u27e9 }\n  end\n\nlemma env.dvcgen.func.inv {\u03c3\u2081 \u03c3\u2082: env} {f g x: var} {R S: spec} {e: exp} {Q: prop}:\n      (\u22a9 (\u03c3\u2081[f \u21a6 value.func g x R S e \u03c3\u2082]) : Q) \u2192\n      \u2203Q\u2081 Q\u2082 Q\u2083,\n      f \u2209 \u03c3\u2081 \u2227\n      g \u2209 \u03c3\u2082 \u2227\n      x \u2209 \u03c3\u2082 \u2227\n      g \u2260 x \u2227\n      (\u22a9 \u03c3\u2081 : Q\u2081) \u2227\n      (\u22a9 \u03c3\u2082 : Q\u2082) \u2227\n      x \u2208 FV R.to_prop.to_vc \u2227\n      FV R.to_prop \u2286 FV Q\u2082 \u222a { g, x } \u2227\n      FV S.to_prop \u2286 FV Q\u2082 \u222a { g, x } \u2227\n      (Q\u2082 \u22c0 spec.func g x R S \u22c0 R \u22a9 e : Q\u2083) \u2227\n      \u2983 prop.implies (Q\u2082 \u22c0 spec.func g x R S \u22c0 R \u22c0 Q\u2083 (term.app g x)) S \u2984 \u2227\n      (Q = (Q\u2081 \u22c0\n           ((f \u2261 (value.func g x R S e \u03c3\u2082)) \u22c0\n           prop.subst_env (\u03c3\u2082[g\u21a6value.func g x R S e \u03c3\u2082])\n           (prop.func g x R (Q\u2083 (term.app g \u2191x) \u22c0 S))))) :=\n  assume h : \u22a9 (\u03c3\u2081[f \u21a6 value.func g x R S e \u03c3\u2082]) : Q,\n  begin\n    cases h,\n    case env.dvcgen.func Q\u2081 Q\u2082 Q\u2083 f_not_in_\u03c3\u2081 g_not_in_\u03c3\u2082 x_not_in_\u03c3\u2082 g_neq_x\n                        \u03c3\u2081_verified \u03c3\u2082_verified x_free_in_R fv_R fv_S e_verified func_vc {\n      from \u27e8Q\u2081, \u27e8Q\u2082, \u27e8Q\u2083,\n           \u27e8f_not_in_\u03c3\u2081, \u27e8g_not_in_\u03c3\u2082, \u27e8x_not_in_\u03c3\u2082, \u27e8g_neq_x, \u27e8\u03c3\u2081_verified,\n           \u27e8\u03c3\u2082_verified, \u27e8x_free_in_R, \u27e8fv_R, \u27e8fv_S, \u27e8e_verified, \u27e8func_vc, rfl\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\u27e9\n    }\n  end\n\nlemma env.dvcgen.copy {\u03c3\u2081 \u03c3\u2082: env} {P\u2081 P\u2082} {x y: var} {v: value}:\n      (\u22a9 \u03c3\u2081 : P\u2081) \u2192 (y \u2209 \u03c3\u2081) \u2192 (\u22a9 (\u03c3\u2082[x\u21a6v]) : P\u2082) \u2192 \u2203P\u2083, (\u22a9 (\u03c3\u2081[y\u21a6v]) : P\u2081 \u22c0 P\u2083) :=\n  assume \u03c3\u2081_verified: \u22a9 \u03c3\u2081 : P\u2081,\n  assume y_not_in_\u03c3\u2081: y \u2209 \u03c3\u2081,\n  assume \u03c3\u2082_xv_verified: \u22a9 (\u03c3\u2082[x\u21a6v]) : P\u2082,\n  show \u2203P\u2083, (\u22a9 (\u03c3\u2081[y\u21a6v]) : P\u2081 \u22c0 P\u2083), by begin\n    cases \u03c3\u2082_xv_verified,\n    case env.dvcgen.tru { from\n      have \u22a9 (\u03c3\u2081[y\u21a6value.true]) : P\u2081 \u22c0 y \u2261 value.true,\n      from env.dvcgen.tru y_not_in_\u03c3\u2081 \u03c3\u2081_verified,\n      show \u2203P\u2083, \u22a9 (\u03c3\u2081[y\u21a6value.true]) : P\u2081 \u22c0 P\u2083, from exists.intro (y \u2261 value.true) this\n    },\n    case env.dvcgen.fls { from\n      have \u22a9 (\u03c3\u2081[y\u21a6value.false]) : P\u2081 \u22c0 y \u2261 value.false,\n      from env.dvcgen.fls y_not_in_\u03c3\u2081 \u03c3\u2081_verified,\n      show \u2203P\u2083, \u22a9 (\u03c3\u2081[y\u21a6value.false]) : P\u2081 \u22c0 P\u2083, from exists.intro (y \u2261 value.false) this\n    },\n    case env.dvcgen.num n { from\n      have \u22a9 (\u03c3\u2081[y\u21a6value.num n]) : P\u2081 \u22c0 y \u2261 value.num n,\n      from env.dvcgen.num y_not_in_\u03c3\u2081 \u03c3\u2081_verified,\n      show \u2203P\u2083, \u22a9 (\u03c3\u2081[y\u21a6value.num n]) : P\u2081 \u22c0 P\u2083, from exists.intro (y \u2261 value.num n) this\n    },\n    case env.dvcgen.func \u03c3\u2083 f fx R S e Q\u2083 Q\u2084 Q\u2082 x_not_in_\u03c3\u2082 f_not_in_\u03c3\u2083 fx_not_in_\u03c3\u2083\n                        f_neq_fx \u03c3\u2082_verified \u03c3\u2083_verified x_free_in_R fv_R fv_S e_verified func_vc { from\n      have \u22a9 (\u03c3\u2081[y\u21a6value.func f fx R S e \u03c3\u2083]) : (P\u2081\n        \u22c0 y \u2261 value.func f fx R S e \u03c3\u2083\n        \u22c0 prop.subst_env (\u03c3\u2083[f\u21a6value.func f fx R S e \u03c3\u2083]) (prop.func f fx R (Q\u2083 (term.app f fx) \u22c0 S))),\n      from env.dvcgen.func y_not_in_\u03c3\u2081 f_not_in_\u03c3\u2083 fx_not_in_\u03c3\u2083\n                        f_neq_fx \u03c3\u2081_verified \u03c3\u2083_verified x_free_in_R fv_R fv_S e_verified func_vc,\n      show \u2203P\u2083, \u22a9 (\u03c3\u2081[y\u21a6value.func f fx R S e \u03c3\u2083]) : P\u2081 \u22c0 P\u2083,\n      from exists.intro (\n        y \u2261 value.func f fx R S e \u03c3\u2083\n       \u22c0 prop.subst_env (\u03c3\u2083[f\u21a6value.func f fx R S e \u03c3\u2083]) (prop.func f fx R (Q\u2083 (term.app f fx) \u22c0 S)))\n      this\n    }\n  end\n\nlemma exp.dvcgen.inj {P: prop} {Q: propctx} {e: exp}: (P \u22a9 e : Q) \u2192 \u2200Q', (P \u22a9 e : Q') \u2192 (Q = Q') :=\n  assume h1: P \u22a9 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\u2081 = Q\u2081_1), from ih_1 Q\u2081_1 a_15,\n    rw[\u2190h3] at a_16,\n    have : (Q\u2082 = Q\u2082_1), from ih_2 Q\u2082_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\u2081 = Q\u2081_1), from ih_1 Q\u2081_1 a_5,\n    rw[this],\n    have : (Q\u2082 = Q\u2082_1), from ih_2 Q\u2082_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} {\u03c3: env}: (\u22a9 \u03c3 : P) \u2192 \u2200Q, (\u22a9 \u03c3 : Q) \u2192 (P = Q) :=\n  assume h1: \u22a9 \u03c3 : 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\u2081 = Q\u2081_1), from ih_1 Q\u2081_1 a_15,\n    rw[h3],\n    have h4: (Q\u2082 = Q\u2082_1), from ih_2 Q\u2082_1 a_16,\n    rw[\u2190h4] at a_20,\n    have : (Q\u2083 = Q\u2083_1), from exp.dvcgen.inj a_9 Q\u2083_1 a_20,\n    rw[this],\n    refl\n  end\n\nlemma stack.dvcgen.inj {s: dstack} {Q\u2081: propctx}: (\u22a9\u209b s : Q\u2081) \u2192 \u2200Q\u2082, (\u22a9\u209b s : Q\u2082) \u2192 (Q\u2081 = Q\u2082) :=\n  assume h1: \u22a9\u209b s : Q\u2081,\n  have \u2200s' Q\u2082, (s = s') \u2192 (\u22a9\u209b s' : Q\u2082) \u2192 (Q\u2081 = Q\u2082), by begin\n    cases h1,\n\n    intros s' Q\u2082 h2 h3,\n    cases h3,\n\n    injection h2,\n    have h4: (R = R_1), from h_1,\n    have h6: (\u03c3 = \u03c3_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 \u25b8 a_4),\n    have : \u2191R \u22c0 P \u22a9 e : Q_1, from h4.symm \u25b8 h7.symm \u25b8 h8.symm \u25b8 a_7,\n    have h9: (Q = Q_1), from exp.dvcgen.inj a_3 Q_1 this,\n    rw[\u2190h8],\n    rw[\u2190h9],\n\n    contradiction,\n\n    intros s' Q\u2082 h2 h3,\n    cases h3,\n\n    contradiction,\n\n    injection h2,\n\n    have h4: (P\u2081 = P\u2081_1), from env.dvcgen.inj a_2 P\u2081_1 (h_3.symm \u25b8 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\u2081_1 = Q\u2081), from exp.dvcgen.inj a_9 Q\u2081 a_24,\n    rw[\u2190h4],\n    rw[\u2190h_5],\n    rw[\u2190h_6],\n    rw[\u2190h_4],\n    rw[h5]\n  end,\n  show \u2200Q\u2082, (\u22a9\u209b s : Q\u2082) \u2192 (Q\u2081 = Q\u2082),\n  from \u03bbQ\u2082 h1, (this s Q\u2082) 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 \u2192 Sexp\n  | expr : List Sexp \u2192 Sexp\n  deriving Repr, BEq, Inhabited\n\nclass ToSexp (\u03b1 : Type u) where\n  toSexp : \u03b1 \u2192 Sexp\n\nnamespace Sexp\n\npartial def serialize : Sexp \u2192 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  \u27e8serialize\u27e9\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 (\u00b7 \u2260 c)\n      if s1.stopPos = s.stopPos then\n        throw <| .incomplete s!\"ending {c} missing after {s1}\"\n      else\n        let s1 := \u27e8s.str, s.startPos, s.next s1.stopPos\u27e9\n        let s2 := \u27e8s.str, s1.stopPos, s.stopPos\u27e9\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 \u27e8tk.bsize\u27e9 \u27e8s.bsize\u27e9)\n\nmutual\npartial def parseOneAux : List Substring \u2192 Except ParseError (Sexp \u00d7 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) \u2190 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 \u2192 Except ParseError (Array Sexp \u00d7 List Substring)\n  | tk :: tks => do\n    if tk.front == ')' then .ok (stk, tk :: tks)\n    else\n      let (e, tks) \u2190 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 \u2190 tokenize s.toSubstring\n  let (sexps, tks) \u2190 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 \u2190 tokenize s.toSubstring\n  let (sexp, _) \u2190 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\u22a2 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\u22a2 n = ?x\n\nn m : Nat\n\u22a2 ?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 {\u03b1} (a : \u03b1) (f : \u03b1 \u2192 \u03b1) (h : \u2200 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 `\u03b1`, `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\u22a2 f (f a) = ?b\n\n...\n\u22a2 ?b = a\n\n...\n\u22a2 \u03b1\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 \u03b1 (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 \u03b1 (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 \u03b1 (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 \u2192 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 \u2190 mkFreshExprMVar (Expr.const ``Nat []) (userName := `mvar1)\n  let mvar2 \u2190 mkFreshExprMVar (Expr.const ``Nat []) (userName := `mvar2)\n  -- Create a fresh metavariable of type `Nat \u2192 Nat`. The `mkArrow` function\n  -- creates a function type.\n  let mvar3 \u2190 mkFreshExprMVar (\u2190 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: {\u2190 instantiateMVars mvar1}\"\n    IO.println s!\"  meta2: {\u2190 instantiateMVars mvar2}\"\n    IO.println s!\"  meta3: {\u2190 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 \u2192 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 \u03b1) : MetaM \u03b1\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 \u2192 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 \u2192 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 \u2190 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 \u2190 mvarId.getType\n    -- For each hypothesis in the local context:\n    for ldecl in \u2190 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 \u2190 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 := (\u00b7 + 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 (\u2190 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 \u2227 Q`. We might want this tactic\nto recognise a hypothesis `h : X` if `X` reduces to `P \u2227 Q`. But if `P`\nadditionally reduces to `Y \u2228 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\u2081 ... x\u2099   (n \u2265 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 \u2190 elabTermAndSynthesize (\u2190 e) none\n  ppExpr (\u2190 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' `(\u03bb x : Nat => x)\n-- fun x => x\n\n/-!\nForalls are in WHNF:\n-/\n\n#eval whnf' `(\u2200 x, x > 0)\n-- \u2200 (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' `((\u03bb 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 \u2227 Q`, avoiding extra computation. WHNF\nmakes it easy:\n-/\n\ndef matchAndReducing (e : Expr) : MetaM (Option (Expr \u00d7 Expr)) := do\n  match \u2190 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\u2227 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 \u2227 Q \u2227 R`. The correct way to do\nthis uses `whnf` twice:\n-/\n\ndef matchAndReducing\u2082 (e : Expr) : MetaM (Option (Expr \u00d7 Expr \u00d7 Expr)) := do\n  match \u2190 whnf e with\n  | (.app (.app (.const ``And _) P) e') =>\n    match \u2190 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 \u2192 Expr \u2192 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\u2081 + ?m\u2082 + ?m\u2083 =?= 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 \u03b1) := (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} : {\u03b1 : Type u_1} \u2192 List.{u_1} \u03b1 \u2192 List.{u_1} \u03b1 \u2192 List.{u_1} \u03b1 :=\n-- fun {\u03b1 : Type u_1} (xs ys : List.{u_1} \u03b1) => @List.append.{u_1} \u03b1 (@List.append.{u_1} \u03b1 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 `\u03b1` 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\u2081 (u : Level) (\u03b1 xs ys : Expr) : Expr :=\n  mkAppN (.const ``List.append [u])\n    #[\u03b1, mkAppN (.const ``List.append [u]) #[\u03b1, 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 \u2192 Array Expr \u2192 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\u2082 (xs ys : Expr) : MetaM Expr := do\n  mkAppM ``List.append #[\u2190 mkAppM ``List.append #[xs, ys], xs]\n\n/-!\nNote the absence of any `\u03b1`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 `\u03b1` is, but with no arguments given to `append`, `\u03b1` could be anything,\nso `mkAppM` fails.\n\nAnother occasionally useful variant of `mkAppM` is `Lean.Meta.mkAppOptM` of type\n\n```lean\nmkAppOptM : Name \u2192 Array (Option Expr) \u2192 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 `\u03bb` or `\u2200` binders.\nSuppose we want to create the expression `\u03bb (x : Nat), Nat.add x x`. One way is\nto write out the lambda directly:\n-/\n\ndef doubleExpr\u2081 : Expr :=\n  .lam `x (.const ``Nat []) (mkAppN (.const ``Nat.add []) #[.bvar 0, .bvar 0])\n    BinderInfo.default\n\n#eval ppExpr doubleExpr\u2081\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\u2082 : MetaM Expr :=\n  withLocalDecl `x BinderInfo.default (.const ``Nat []) \u03bb x => do\n    let body \u2190 mkAppM ``Nat.add #[x, x]\n    mkLambdaFVars #[x] body\n\n#eval show MetaM _ from do\n  ppExpr (\u2190 doubleExpr\u2082)\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 \u2192 MetaM \u03b1) : MetaM \u03b1\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 \u2192 Expr \u2192 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 `\u2200` binders instead of `\u03bb` binders. `mkLetFVars`\n  creates `let` binders.\n- `mkArrow` is the non-dependent version of `mkForallFVars` which construcs\n  a function type `X \u2192 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\u03bb (f : Nat \u2192 Nat), \u2200 (n : Nat), f n = f (n + 1)\n```\n-/\n\ndef somePropExpr : MetaM Expr := do\n  let funcType \u2190 mkArrow (.const ``Nat []) (.const ``Nat [])\n  withLocalDecl `f BinderInfo.default funcType fun f => do\n    let feqn \u2190 withLocalDecl `n BinderInfo.default (.const ``Nat []) fun n => do\n      let lhs := .app f n\n      let rhs := .app f (\u2190 mkAppM ``Nat.succ #[n])\n      let eqn \u2190 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 => \u2200 (n : Nat), f n = f (Nat.succ n) : (Nat \u2192 Nat) \u2192 Prop\n#reduce someProp Nat.succ\n-- \u2200 (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 `\u03bb` and `\u2200` binders.\n\nWhen we are given a type of the form `\u2200 (x\u2081 : T\u2081) ... (x\u2099 : T\u2099), U`, we are\noften interested in doing something with the conclusion `U`. For instance, the\n`apply` tactic, when given an expression `e : \u2200 ..., 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 `\u2200`\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 \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1\n```\n\nGiven `type = \u2200 (x\u2081 : T\u2081) ... (x\u2099 : T\u2099), U x\u2081 ... x\u2099`, this function creates one\nfvar `f\u1d62` for each `\u2200`-bound variable `x\u1d62` and replaces each `x\u1d62` with `f\u1d62` in\nthe conclusion `U`. It then calls the computation `k`, passing it the `f\u1d62` and\nthe conclusion `U f\u2081 ... f\u2099`. Within this computation, the `f\u1d62` 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 `\u2200 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 `\u2200` 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  `\u03bb` binders instead of `\u2200`.\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 \u2190 goal.getType\n    -- Get the type of the given expression.\n    let type \u2190 inferType e\n    -- If `type` has the form `\u2200 (x\u2081 : T\u2081) ... (x\u2099 : T\u2099), U`, introduce new\n    -- metavariables for the `x\u1d62` and obtain the conclusion `U`. (If `type` does\n    -- not have this form, `args` is empty and `conclusion = type`.)\n    let (args, _, conclusion) \u2190 forallMetaTelescopeReducing type\n    -- If the conclusion unifies with the target:\n    if \u2190 isDefEq target conclusion then\n      -- Assign the goal to `e x\u2081 ... x\u2099`, where the `x\u1d62` 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 \u2190 args.filterMapM \u03bb mvar => do\n        let mvarId := mvar.mvarId!\n        if ! (\u2190 mvarId.isAssigned) && ! (\u2190 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 \u2190 Elab.Term.elabTerm e none\n  Elab.Tactic.liftMetaTactic (myApply \u00b7 e)\n\nexample (h : \u03b1 \u2192 \u03b2) (a : \u03b1) : \u03b2 := 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 \u2192 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 \u2190 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 \u03b1) : m \u03b1` 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 \u03b1) : m (Option \u03b1)` 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 : \u03b1) : m \u03b1` 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 \u2190 ...\n    -- Create `mvar2` with type `Nat`\n    -- let mvar2 \u2190 ...\n    -- Create `mvar3` with type `Nat`\n    -- let mvar3 \u2190 ...\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 \u2190 Lean.Elab.Tactic.getMainGoal\n    let metavarDecl : MetavarDecl \u2190 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 \u2192 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 \u2192 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 \u2190 Meta.reduce constantExpr\n    dbg_trace (\u2190 ppExpr reducedExpr) -- ...\n\n  Meta.withTransparency Meta.TransparencyMode.instances do\n    let reducedExpr \u2190 Meta.reduce constantExpr\n    dbg_trace (\u2190 ppExpr reducedExpr) -- ...\n\n  Meta.withTransparency Meta.TransparencyMode.default do\n    let reducedExpr \u2190 Meta.reduce constantExpr\n    dbg_trace (\u2190 ppExpr reducedExpr) -- ...\n\n  Meta.withTransparency Meta.TransparencyMode.all do\n    let reducedExpr \u2190 Meta.reduce constantExpr\n    dbg_trace (\u2190 ppExpr reducedExpr) -- ...\n\n  let reducedExpr \u2190 Meta.reduce constantExpr\n  dbg_trace (\u2190 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 `\u2200 (yellow: Nat), yellow`.\n12. [**Constructing Expressions**] Create expression `\u2200 (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 \u2192 Nat), \u2200 (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 \u2190 `(\u2200 (a : Prop) (b : Prop), a \u2228 b \u2192 b \u2192 a \u2227 a)\n  let expr \u2190 Elab.Term.elabTermAndSynthesize stx none\n\n  let (_, _, conclusion) \u2190 forallMetaTelescope expr\n  dbg_trace conclusion -- ...\n\n  let (_, _, conclusion) \u2190 forallMetaBoundedTelescope expr 2\n  dbg_trace conclusion -- ...\n\n  let (_, _, conclusion) \u2190 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 Scratch.ExprAppl\nimport Lean.Meta\nimport Lean.Elab\nimport Std.Data.HashMap\nopen Std\nopen Lean\nopen Meta\nopen Elab\n\n-- this is the wrong approach, so moved here\n\n\npartial def rewriteAllAux(type lhs rhs : Expr): Expr \u2192 MetaM (Array Expr) := fun e =>\n  match e with\n | Expr.app f a _ =>\n    do\n    let fs \u2190 recRewrite f\n    let as \u2190 recRewrite a\n    let mut es : Array Expr := #[]\n    for f in fs do\n      for a in as do\n        try \n          es \u2190 es.push (mkApp f a)\n        catch _ =>\n          ()\n    es\n | Expr.lam name x y data => \n    do\n      let xs \u2190 recRewrite x\n      let ys \u2190 recRewrite y\n      let mut es : Array Expr := #[]\n      for x in xs do\n        for y in ys do\n          try \n            es \u2190 es.push ((mkLambda name data.binderInfo x y))\n          catch _ =>\n            ()\n      es\n | Expr.forallE name x y data => \n    do\n      let xs \u2190 recRewrite x\n      let ys \u2190 recRewrite y\n      let mut es : Array Expr := #[]\n      for x in xs do\n        for y in ys do\n          try \n            es \u2190 es.push (mkForall name data.binderInfo x y)\n          catch _ =>\n            ()\n      es  \n | Expr.letE _ x y z _ => #[e]\n | _ => #[e]\n where recRewrite : Expr \u2192 MetaM (Array Expr) := \n  fun e => do\n    let mut es : Array Expr \u2190  rewriteAllAux type lhs rhs e\n    if \u2190 isDefEq e lhs then es := es.push rhs \n    if \u2190 isDefEq e rhs then es := es.push lhs\n    es\n\ndef rewriteAll (eq : Expr) : Expr \u2192 MetaM (Array Expr) :=\n  match eq.eq? with\n  | none => fun _ => #[]\n  | some (type, lhs, rhs) => \n    fun e => \n    do\n      let base \u2190 rewriteAllAux type lhs rhs (\u2190 whnf e)\n      let filtered \u2190 base.filterM $ fun x => do !(\u2190 isDefEq e x)\n      return filtered\n\nopen Term\n\nsyntax (name:= rwall) \"rewriteAll%\" term \"at\" term : term\n@[termElab rwall] def rewriteAllImp : TermElab :=\n  fun stx expectedType? =>\n  match stx with\n  | `(rewriteAll% $eq at $t) =>\n    do\n      let eqn \u2190 Term.elabTerm eq none\n      let x \u2190 Term.elabTerm t none\n      let rewritten \u2190 rewriteAll (\u2190 inferType eqn) x\n      logInfo m!\"rewritten: {rewritten}\" \n      return mkConst ``Unit.unit\n  | _ => throwIllFormedSyntax\n\nexample (a b : Nat)(f: Nat \u2192 Nat  \u2192 Bool)(eq: a = b) : Unit :=\n    let g := fun x : Nat => f a b\n    rewriteAll% eq at g\n\ninductive Letter where\n  | \u03b1 : Letter\n  | \u03b1! : Letter\n\ninitialize exprCache : IO.Ref (HashMap Name Expr) \u2190 IO.mkRef (HashMap.empty)\n\ndef getCached? (name : Name) : IO (Option (Expr)) := do\n  let cache \u2190 exprCache.get\n  return (cache.find? name)\n\ndef cache (name: Name)(e: Expr)  : IO Unit := do\n  let cache \u2190 exprCache.get\n  exprCache.set (cache.insert name e)\n  return ()\n\ndef saveExpr (name: Name)(e: Expr) : TermElabM Expr := do\n  let e \u2190 whnf e\n  Term.synthesizeSyntheticMVarsNoPostponing \n  let (e, _) \u2190 Term.levelMVarToParam (\u2190 instantiateMVars e)\n  cache name e\n  return e\n\nsyntax (name:= saveexpr) \"cache!\" term \"at\" ident : term\n@[termElab saveexpr] def cacheImp : TermElab :=\n  fun stx expectedType? =>\n  match stx with\n  | `(cache! $t at $name) =>\n    do\n      let t \u2190 Term.elabTerm t none false\n      let name \u2190 name.getId\n      saveExpr name t\n  | _ => throwIllFormedSyntax\n\n#check @id\n\nsyntax (name:= loadexpr) \"load!\" ident :term\n@[termElab loadexpr] def loadImp : TermElab :=\n  fun stx expectedType? =>\n  match stx with\n  | `(load! $name) =>\n    do\n      let name \u2190 name.getId\n      let cache \u2190 exprCache.get\n      logInfo m!\"loading: {name}\"\n      let e \u2190 cache.find? name\n      logInfo m!\"loading {name} : {e}\"\n      match e with\n      | some e =>\n        logInfo m!\"level mvar? {e.hasLevelMVar}\"\n        logInfo m!\"level param? {e.hasLevelParam}\" \n        return e\n      | none => throwError \"no such expression\"\n  | _ => throwIllFormedSyntax\n\n-- L\u2203\u2200N \n\n#eval (#[1, 3, 5]).back", "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/Eg10.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3812195521959384, "lm_q2_score": 0.03114383075959148, "lm_q1q2_score": 0.011872637215837556}}
{"text": "import for_mathlib.category_theory.localization.equivalence\n\nnoncomputable theory\n\nnamespace category_theory\n\nvariables {C\u2081 C\u2082 C\u2083 E : Type*} [category C\u2081] [category C\u2082] [category C\u2083]\n\nopen localization\n\nnamespace morphism_property\n\n@[refl]\nlemma subset.refl (W : morphism_property C\u2081) : W \u2286 W := \u03bb X Y f hf, hf\n\n@[simp]\ndef map (W : morphism_property C\u2081) (F : C\u2081 \u2964 C\u2082) : morphism_property C\u2082 :=\n\u03bb X\u2082 Y\u2082 f\u2082, \u2203 (X\u2081 Y\u2081 : C\u2081) (f\u2081 : X\u2081 \u27f6 Y\u2081) (hf\u2081 : W f\u2081),\n  nonempty (arrow.mk (F.map f\u2081) \u2245 arrow.mk f\u2082)\n\nlemma map_mem_map (W : morphism_property C\u2081) (F : C\u2081 \u2964 C\u2082) {X\u2081 Y\u2081 : C\u2081} (f\u2081 : X\u2081 \u27f6 Y\u2081)\n  (hf\u2081 : W f\u2081) : W.map F (F.map f\u2081) :=\n\u27e8_, _, f\u2081, hf\u2081, nonempty.intro (iso.refl _)\u27e9\n\nlemma map_is_inverted_by_iff (W : morphism_property C\u2081) (F : C\u2081 \u2964 C\u2082) (G : C\u2082 \u2964 C\u2083) :\n  (W.map F).is_inverted_by G \u2194 W.is_inverted_by (F \u22d9 G) :=\nbegin\n  split,\n  { intros h X\u2081 Y\u2081 f\u2081 hf\u2081,\n    exact h _ (W.map_mem_map F f\u2081 hf\u2081), },\n  { rintros h X\u2082 Y\u2082 f\u2082 \u27e8X\u2081, Y\u2081, f\u2081, hf\u2081, \u27e8e\u27e9\u27e9,\n    exact ((respects_iso.isomorphisms C\u2083).arrow_mk_iso_iff (G.map_arrow.map_iso e)).1 (h _ hf\u2081), },\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\u2081 : C\u2081 \u2964 C\u2082} {L\u2082 : C\u2082 \u2964 C\u2083} {W\u2081 : morphism_property C\u2081} {W\u2082 : morphism_property C\u2082}\n  (h\u2081 : strict_universal_property_fixed_target L\u2081 W\u2081 E)\n  (h\u2082 : strict_universal_property_fixed_target L\u2082 W\u2082 E)\n  (W\u2083 : morphism_property C\u2081) (hW\u2083 : W\u2083.is_inverted_by (L\u2081 \u22d9 L\u2082))\n  (hW\u2081\u2083 : W\u2081 \u2286 W\u2083) (hW\u2082\u2083 : W\u2082 \u2286 W\u2083.map L\u2081) :\n  strict_universal_property_fixed_target (L\u2081 \u22d9 L\u2082) W\u2083 E :=\n{ inverts := hW\u2083,\n  lift := \u03bb F hF, begin\n    have h : W\u2081.is_inverted_by F := \u03bb X\u2081 Y\u2081 f\u2081 hf\u2081, hF f\u2081 (hW\u2081\u2083 _ hf\u2081),\n    exact h\u2082.lift (h\u2081.lift F h) (\u03bb X\u2082 Y\u2082 f\u2082 hf\u2082, begin\n      obtain \u27e8X\u2081, Y\u2081, f\u2081, hf\u2081, \u27e8e\u27e9\u27e9 := hW\u2082\u2083 _ hf\u2082,\n      refine ((morphism_property.respects_iso.isomorphisms E).arrow_mk_iso_iff\n        ((h\u2081.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\u2081.fac F h)) (arrow.mk f\u2081))).2 (hF _ hf\u2081),\n    end),\n  end,\n  fac := \u03bb F hF, by rw [functor.assoc, h\u2082.fac, h\u2081.fac],\n  uniq := \u03bb F\u2081 F\u2082 h, begin\n    simp only [functor.assoc] at h,\n    exact h\u2082.uniq _ _ (h\u2081.uniq _ _ h),\n  end, }\n\nend\n\n@[protected]\nlemma comp (L\u2081 : C\u2081 \u2964 C\u2082) (L\u2082 : C\u2082 \u2964 C\u2083) (W\u2081 : morphism_property C\u2081)\n  (W\u2082 : morphism_property C\u2082) (W\u2083 : morphism_property C\u2081)\n  [L\u2081.is_localization W\u2081] [L\u2082.is_localization W\u2082] (hW\u2083 : W\u2083.is_inverted_by (L\u2081 \u22d9 L\u2082))\n  (hW\u2081\u2083 : W\u2081 \u2286 W\u2083) (hW\u2083' : W\u2082 \u2286 W\u2083.map L\u2081) :\n  (L\u2081 \u22d9 L\u2082).is_localization W\u2083 :=\nbegin\n  let L\u2081' := W\u2081.Q,\n  let eq\u2082 := equivalence_from_model L\u2081 W\u2081,\n  let W\u2082' : morphism_property (W\u2081.localization) := W\u2082.map eq\u2082.inverse,\n  let L\u2082' := W\u2082'.Q,\n  have h\u2082 : W\u2082'.is_inverted_by (eq\u2082.functor \u22d9 L\u2082),\n  { dsimp only [W\u2082'],\n    rw morphism_property.map_is_inverted_by_iff,\n    refine (morphism_property.is_inverted_by.iff_of_iso W\u2082 _).1 (localization.inverts L\u2082 W\u2082),\n    exact L\u2082.left_unitor.symm \u226a\u226b iso_whisker_right eq\u2082.counit_iso.symm _ \u226a\u226b functor.associator _ _ _, },\n  let F\u2083 : W\u2082'.localization \u2964 C\u2083 := localization.lift (eq\u2082.functor \u22d9 L\u2082) h\u2082 L\u2082',\n  let H : Comm_sq eq\u2082.functor L\u2082' L\u2082 F\u2083 := \u27e8localization.fac _ _ _\u27e9,\n  have h\u2081' : W\u2081.is_inverted_by L\u2081' := localization.inverts _ _,\n  have h\u2081\u2082' : W\u2081.is_inverted_by (L\u2081' \u22d9 L\u2082') :=\n    morphism_property.is_inverted_by.of_comp W\u2081 _ h\u2081' L\u2082',\n  letI : lifting L\u2081 W\u2081 L\u2081' eq\u2082.inverse := \u27e8comp_equivalence_from_model_inverse_iso _ _\u27e9,\n  let F\u2081\u2082' := localization.lift (L\u2081' \u22d9 L\u2082') h\u2081\u2082' L\u2081,\n  let e\u2081\u2082 : F\u2081\u2082' \u2245 eq\u2082.inverse \u22d9 L\u2082' := lift_nat_iso L\u2081 W\u2081 (L\u2081' \u22d9 L\u2082') (L\u2081' \u22d9 L\u2082') _ _ (iso.refl _),\n  have hF\u2081\u2082' : W\u2082.is_inverted_by F\u2081\u2082',\n  { have h := localization.inverts W\u2082'.Q W\u2082',\n    rw morphism_property.map_is_inverted_by_iff at h,\n    exact (morphism_property.is_inverted_by.iff_of_iso _ e\u2081\u2082.symm).1 h, },\n  let G\u2083 : C\u2083 \u2964 W\u2082'.localization := localization.lift F\u2081\u2082' hF\u2081\u2082' L\u2082,\n  letI : lifting L\u2082 W\u2082 (eq\u2082.inverse \u22d9 W\u2082'.Q) G\u2083 :=\n    \u27e8localization.fac F\u2081\u2082' hF\u2081\u2082' L\u2082 \u226a\u226b lift_nat_iso L\u2081 W\u2081\n      (L\u2081' \u22d9 L\u2082') (L\u2081' \u22d9 L\u2082') _ _ (iso.refl _)\u27e9,\n  let e\u2082 : (eq\u2082.inverse \u22d9 L\u2082') \u22d9 F\u2083 \u2245 L\u2082 := functor.associator _ _ _ \u226a\u226b\n      iso_whisker_left _ (localization.fac (eq\u2082.functor \u22d9 L\u2082) h\u2082 L\u2082') \u226a\u226b\n      (functor.associator _ _ _).symm \u226a\u226b iso_whisker_right eq\u2082.counit_iso _ \u226a\u226b L\u2082.left_unitor,\n  let e\u2083 : eq\u2082.functor \u22d9 eq\u2082.inverse \u22d9 L\u2082' \u2245 L\u2082' :=\n    (functor.associator _ _ _).symm \u226a\u226b iso_whisker_right eq\u2082.unit_iso.symm _ \u226a\u226b L\u2082'.left_unitor,\n  letI := lifting_is_equivalence H W\u2082' W\u2082 (eq\u2082.inverse \u22d9 L\u2082') G\u2083 e\u2082 e\u2083,\n  haveI : (L\u2081' \u22d9 L\u2082').is_localization W\u2083,\n  { have h\u2081 : W\u2083.is_inverted_by (W\u2081.Q \u22d9 W\u2082'.Q),\n    { suffices : W\u2083.is_inverted_by (W\u2081.Q \u22d9 W\u2082'.Q \u22d9 F\u2083),\n      { intros X\u2081 Y\u2081 f\u2081 hf\u2081,\n        haveI : is_iso (F\u2083.map ((W\u2081.Q \u22d9 W\u2082'.Q).map f\u2081)) := this f\u2081 hf\u2081,\n        exact is_iso_of_reflects_iso _ F\u2083, },\n      refine (morphism_property.is_inverted_by.iff_of_iso W\u2083 _).1 hW\u2083,\n      exact iso_whisker_right ((Q_comp_equivalence_from_model_functor_iso L\u2081 W\u2081).symm) _ \u226a\u226b\n         functor.associator _ _ _ \u226a\u226b iso_whisker_left _ (localization.fac _ _ _).symm, },\n    have h\u2082 : W\u2082' \u2286 W\u2083.map W\u2081.Q,\n    { dsimp only [W\u2082'],\n      rintros X Y f \u27e8X\u2082, Y\u2082, f\u2082, hf\u2082, \u27e8e\u2082\u27e9\u27e9,\n      rcases  hW\u2083' _ hf\u2082 with \u27e8X\u2081, Y\u2081, f\u2081, hf\u2081, \u27e8e\u2081\u27e9\u27e9,\n      refine \u27e8X\u2081, Y\u2081, f\u2081, hf\u2081, \u27e8_\u27e9\u27e9,\n      refine arrow.iso_of_nat_iso (comp_equivalence_from_model_inverse_iso L\u2081 W\u2081).symm (arrow.mk f\u2081)\n        \u226a\u226b eq\u2082.inverse.map_arrow.map_iso e\u2081 \u226a\u226b e\u2082, },\n    refine functor.is_localization.mk' _ _ _ _,\n    all_goals { exact (strict_universal_property_fixed_target_Q W\u2081 _).comp\n      (strict_universal_property_fixed_target_Q W\u2082' _) W\u2083 h\u2081 hW\u2081\u2083 h\u2082, }, },\n  apply functor.is_localization.of_equivalence (L\u2081' \u22d9 L\u2082') W\u2083 (L\u2081 \u22d9 L\u2082) F\u2083.as_equivalence,\n  exact functor.associator _ _ _ \u226a\u226b iso_whisker_left _ (localization.fac _ _ _) \u226a\u226b\n    (functor.associator _ _ _).symm \u226a\u226b iso_whisker_right (Q_comp_equivalence_from_model_functor_iso L\u2081 W\u2081) _,\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 \u2192 list (string \u00d7 value) \u2192 value\n| number : \u2124 \u2192 value\n| array : unit \u2192 list value \u2192 value\n| bool : bool \u2192 value\n| string : string \u2192 value\n| nil : value\n-- with object : Type\n-- | fields : list (string \u00d7 value) \u2192 object\n\nopen value (hiding object bool string)\n\n@[reducible] def object := list (string \u00d7 value)\n\ndef is_atom : value \u2192 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 \u2192 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 _ _) := \"<object>\"\n| (value.array _ _) := \"<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 : \u2124) | 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 \u2192 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 \u2192 list (string \u00d7 value) \u2192 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 \u2192 put_m\n| [] := pure ()\n| (v :: vs) :=\ndo encode_val v,\n   when (\u00ac vs = []) $ do\n     write_word comma,\n     encode_array vs\n\ninductive partial_val\n| array (ar : list value)\n| object (obj : list (string \u00d7 value)) (field : string)\n\ndef parser_state := list partial_val\n\nopen ulift\n\ndef push : list partial_val \u2192 value \u2192 get_m ( value \u2295 parser_state )\n| [] v := pure (sum.inl v)\n| (partial_val.array ar :: vs) v :=\n  do t \u2190 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 \u2190 read_word,\n     if down t = comma then do\n       \u27e8token.string fn'\u27e9 \u2190 read_word | failure,\n       \u27e8colon\u27e9 \u2190 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 \u2192 token \u2192 get_m ( value \u2295 parser_state )\n| vs nil := push vs value.nil\n| vs open_curly :=\n  do t \u2190 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 : \u2115) :=\n(\u2200 (v : value) (vs : list partial_val) (x : punit \u2192 put_m), sizeof v \u2264 m \u2192\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 : \u2115) :=\n(\u2200 (fn : string) (v : value) (obj obj' : object)\n   (vs : list partial_val) (x : punit \u2192 put_m),\n   sizeof obj' \u2264 m \u2192 sizeof v < m \u2192\nget_m.loop parser_step pure (partial_val.object obj fn :: vs) -<<\n  (encode_obj v obj' >>= \u03bb _, 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 : \u2115) :=\n(\u2200 (v v' : list value)\n   (vs : list partial_val) (x : punit \u2192 put_m), sizeof v' \u2264 m \u2192\nget_m.loop parser_step pure (partial_val.array v :: vs) -<<\n      (encode_array v' >>= \u03bb (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 : \u2115\nvariables ih_val : \u2200 (x : \u2115), x < n \u2192 encoding_correctness_val x\nvariables ih_obj : \u2200 (x : \u2115), x < n \u2192 encoding_correctness_obj x\nvariables ih_ar : \u2200 (x : \u2115), x < n \u2192 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 _ | \u27e8 \u27e8 fn,v \u27e9, vs \u27e9,\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 _ | \u27e8 \u27e8 fn', v' \u27e9, obj' \u27e9,\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 : \u2115) :\n    encoding_correctness_val m \u2227\n    encoding_correctness_obj m \u2227\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 \u27e8 ih_val, ih_obj, ih_ar \u27e9,\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 \u2192 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 := \u27e8 value.repr \u27e9\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 \u2115 put_m'\n\n-- def newline : writer unit :=\n-- \u27e8 \u03bb n, emit $ \"\\n\" ++ (list.repeat ' ' n).as_string \u27e9\n\n-- def bump {\u03b1} (tac : writer \u03b1) : writer \u03b1 :=\n-- \u27e8 \u03bb n, tac.run (n+2) \u27e9\n\n-- mutual def encode_aux, encode_obj, encode_array\n-- with encode_aux : value \u2192 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 \u00d7 value) \u2192 writer unit\n-- | [] := monad_lift $ emit \"[]\"\n-- | ((f,v) :: vs) :=\n--   do monad_lift $ emit (f ++ \": \"),\n--      bump $ do {\n--        when (\u00ac is_atom v) newline,\n--        encode_aux v },\n--      when (\u00ac vs.empty) $ do\n--        newline,\n--        encode_obj vs\n-- with encode_array : list value \u2192 writer unit\n-- | [] := monad_lift $ emit \"[]\"\n-- | (v :: vs) :=\n--   do monad_lift $ emit \"- \",\n--      bump $ encode_aux v,\n--      when (\u00ac 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 {\u03b1} (f : char \u2192 list (bool \u00d7 reader \u03b1)) (c : char) : reader \u03b1 :=\n-- (prod.snd <$> list.find (\u03bb x, prod.fst x = tt) (f c)).get_or_else failure\n\n-- def select {\u03b1} (f : char \u2192 list (bool \u00d7 reader \u03b1)) : reader \u03b1 :=\n-- peek >>= select_aux f\n\n-- def try_char (p : char \u2192 Prop) [decidable_pred p] : reader (option char) :=\n-- do c \u2190 read_char,\n--    if p c then pure c\n--           else unread c >> pure none\n\n-- def many_loop (p : char \u2192 Prop) [decidable_pred p] : list char \u2192 char \u2192 get_m ((list char \u00d7 option char) \u2295 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 \u2192 Prop) [decidable_pred p] : reader (list char) :=\n-- \u27e8 \u03bb n, \u27e8 \u03bb s : option char,\n-- do s' \u2190 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 \u27e9 \u27e9\n\n-- def parse_nat : reader \u2115 :=\n-- do c \u2190 read_char,\n--    guard c.is_digit,\n--    cs \u2190 many char.is_digit,\n--    pure $ list.foldl (\u03bb x (c : char), 10 * x + c.val - '0'.val) 0 (c :: cs)\n\n-- def parse_int : reader \u2124 :=\n-- do x \u2190 try_char (= '-'),\n--    n \u2190 parse_nat,\n--    pure $ if x.is_some then - \u2191n\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 : \u2115) :\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 \u2191n)) 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) : \u2115 :=\ns.fold 1 (\u03bb 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 \u2192 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 \u2190 doc_string fr,\n   to.mmap' $ \u03bb tgt, add_doc_string tgt fr_ds\n\nopen lean lean.parser interactive\n\n/--\n`copy_doc_string source \u2192 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 \u2190 parser.ident,\n   tk \"->\",\n   to \u2190 parser.many parser.ident,\n   expr.const fr _  \u2190 resolve_name fr,\n   to \u2190 parser.of_tactic (to.mmap $ \u03bb 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 \u00d7 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 : \u2115 := 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.<note_name>` 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 \u2190 parser.pexpr,\nnote_name \u2190 eval_pexpr string note_name,\nsome doc_string \u2190 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 \u00d7 string)) :=\nattribute.get_instances `library_note >>=\n  list.mmap (\u03bb 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 \u2192 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 := \u27e8\u2191doc_category.to_string\u27e9\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 \u2218 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 \u00d7 string) :=\n\u27e8\u03bb \u27e8doc, desc\u27e9, json.unparse (doc.to_json desc)\u27e9\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 \u00d7 string)) :=\nattribute.get_instances `tactic_doc >>=\n  list.mmap (\u03bb 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 \u2190 doc <|> (do\n    inh_id \u2190 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 \u2190 parser.pexpr,\ne \u2190 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 : \u2115) (f : \u2115 \u2192 \u2115) (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 : \u2115 \u2192 \u2115) (x : \u2115)\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 <https://leanprover-community.github.io/extras/conv.html> 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 : \u2115) (h\u2081 : b = c) (h\u2082 : a + c = a + d) : a + b = a + d :=\nby conv\n{ to_lhs,\n  conv\n  { congr, skip,\n    rw h\u2081 },\n  rw h\u2082, }\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 {\u03c0 \u03b1 : Type} : component \u03c0 \u03b1 :=\ncomponent.ignore_props $ component.mk_simple int int 0 (\u03bb _ x y, (x + y, none)) (\u03bb _ 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 \u2190 parser.ident,\nn \u2190 resolve_constant n,\nsome doc \u2190 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": "/-\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.attribute\nimport Mathlib.Lean3Lib.init.meta.constructor_tactic\nimport Mathlib.Lean3Lib.init.meta.relation_tactics\nimport Mathlib.Lean3Lib.init.meta.occurrences\nimport Mathlib.Lean3Lib.init.data.option.basic\n \n\nuniverses l \n\nnamespace Mathlib\n\ndef simp.default_max_steps : \u2115 :=\n  bit0\n    (bit0\n      (bit0\n        (bit0\n          (bit0\n            (bit0\n              (bit0\n                (bit1\n                  (bit0\n                    (bit1\n                      (bit1\n                        (bit0 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 1))))))))))))))))))))))\n\n/-- Prefix the given `attr_name` with `\"simp_attr\"`. -/\n/-- Simp lemmas are used by the \"simplifier\" family of tactics.\n`simp_lemmas` is essentially a pair of tables `rb_map (expr_type \u00d7 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 \u2194 r`.\n- A list of the metavariables that must be filled before the proof can be applied.\n- A priority number\n-/\n/-- Make a new table of simp lemmas -/\n/-- Merge the simp_lemma tables. -/\n/-- Remove the given lemmas from the table. Use the names of the lemmas. -/\n/-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/\n/-- Add 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 `\u03a0 (h\u2081 : _) ... (h\u2099 : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`).\n- Any of the hypotheses `h\u1d62` 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\u1d62`.\n\n -/\n/-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/\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 \u2227 b` to `c \u2227 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 \u2194 c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ...\nlemma imp_congr_right (h : a \u2192 (b \u2194 c)) : (a \u2192 b) \u2194 (a \u2192 c) := ...\nlemma and_congr (h\u2081 : a \u2194 c) (h\u2082 : b \u2194 d) : (a \u2227 b) \u2194 (c \u2227 d) := ...\n```\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-/\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-/\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) -/\n/-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/\nnamespace tactic\n\n\n/- Remark: `transform` should not change the target. -/\n\n/-- Revert a local constant, change its type using `transform`.  -/\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. -/\nstructure dsimp_config \nwhere\n  md : transparency\n  max_steps : \u2115\n  canonize_instances : Bool\n  single_pass : Bool\n  fail_if_unchanged : Bool\n  eta : Bool\n  zeta : Bool\n  beta : Bool\n  proj : Bool\n  iota : Bool\n  unfold_reducible : Bool\n  memoize : Bool\n\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.-/\nnamespace tactic\n\n\n/- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/\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\n/-- Tries to unfold `e` if it is a constant or a constant application.\n    Remark: this is not a recursive procedure. -/\nstructure dunfold_config \nextends dsimp_config\nwhere\n\n/- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for\n   performance reasons. -/\n\nstructure delta_config \nwhere\n  max_steps : \u2115\n  visit_instances : Bool\n\n/-- Delta reduce the given constant names -/\nstructure unfold_proj_config \nextends dsimp_config\nwhere\n\n/-- If `e` is a projection application, try to unfold it, otherwise fail. -/\nstructure simp_config \nwhere\n  max_steps : \u2115\n  contextual : Bool\n  lift_eq : Bool\n  canonize_instances : Bool\n  canonize_proofs : Bool\n  use_axioms : Bool\n  zeta : Bool\n  beta : Bool\n  eta : Bool\n  proj : Bool\n  iota : Bool\n  iota_eqn : Bool\n  constructor_eq : Bool\n  single_pass : Bool\n  fail_if_unchanged : Bool\n  memoize : Bool\n  trace_lemmas : Bool\n\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-/\n/--\n`ext_simplify_core a c s discharger pre post r e`:\n\n- `a : \u03b1` - 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 : \u03b1 \u2192 tactic \u03b1` - tactic for dischaging hypothesis in conditional rewriting rules. The argument '\u03b1' 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 `\u2194`.\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-/\nstructure simp_intros_config \nextends simp_config\nwhere\n  use_hyps : Bool\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/simp_tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.03410042730743849, "lm_q1q2_score": 0.011768237665083201}}
{"text": "import .gluing\n\nuniverses v u\n\nopen category_theory\nlocal notation f ` \u2218 `:80 g:80 := g \u226b 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 \u27f6 b} {f : a \u27f6 a'} {i' : a' \u27f6 b'} {f' : b \u27f6 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 \u2190this,\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 := \u03bb 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": "/-\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.CollectMVars\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Constructor\nimport Lean.Meta.Tactic.Assert\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.SyntheticMVars\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\n/- `elabTerm` for Tactics and basic tactics that use it. -/\n\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  /- We have disabled `Term.withoutErrToSorry` to improve error recovery.\n     When we were using it, any tactic using `elabTerm` would be interrupted at elaboration errors.\n     Tactics that do not want to proceed should check whether the result contains sythetic sorrys or\n     disable `errToSorry` before invoking `elabTerm` -/\n  withRef stx do -- <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx expectedType?\n    Term.synthesizeSyntheticMVars mayPostpone\n    instantiateMVars e\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  let e \u2190 elabTerm stx expectedType? mayPostpone\n  -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here.\n  match expectedType? with\n  | none => return e\n  | some expectedType =>\n    let eType \u2190 inferType e\n    unless (\u2190 isDefEq eType expectedType) do\n      Term.throwTypeMismatchError none expectedType eType e\n    return e\n\n/- Try to close main goal using `x target`, where `target` is the type of the main goal.  -/\ndef closeMainGoalUsing (x : Expr \u2192 TacticM Expr) (checkUnassigned := true) : TacticM Unit :=\n  withMainContext do\n    closeMainGoal (checkUnassigned := checkUnassigned) (\u2190 x (\u2190 getMainTarget))\n\nprivate def logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do\n   if (\u2190 Term.logUnassignedUsingErrorInfos mvarIds) then\n     throwAbortTactic\n\n@[builtinTactic \u00abexact\u00bb] def evalExact : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do\n    let r \u2190 elabTermEnsuringType e type\n    logUnassignedAndAbort (\u2190 getMVars r)\n    return r\n  | _ => throwUnsupportedSyntax\n\ndef elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr \u00d7 List MVarId) := do\n  let val \u2190 elabTermEnsuringType stx expectedType?\n  let newMVarIds \u2190 getMVarsNoDelayed val\n  /- ignore let-rec auxiliary variables, they are synthesized automatically later -/\n  let newMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 Term.isLetRecAuxMVar mvarId)\n  let newMVarIds \u2190\n    if allowNaturalHoles then\n      pure newMVarIds.toList\n    else\n      let naturalMVarIds \u2190 newMVarIds.filterM fun mvarId => return (\u2190 getMVarDecl mvarId).kind.isNatural\n      let syntheticMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 getMVarDecl mvarId).kind.isNatural\n      logUnassignedAndAbort naturalMVarIds\n      pure syntheticMVarIds.toList\n  tagUntaggedGoals (\u2190 getMainTag) tagSuffix newMVarIds\n  pure (val, newMVarIds)\n\n/- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned \"natural\" metavariables.\n   Recall that \"natutal\" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be\n   filled by typing constraints.\n   \"Synthetic\" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/\ndef refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do\n  withMainContext do\n    let (val, mvarIds') \u2190 elabTermWithHoles stx (\u2190 getMainTarget) tagSuffix allowNaturalHoles\n    assignExprMVar (\u2190 getMainGoal) val\n    replaceMainGoal mvarIds'\n\n@[builtinTactic \u00abrefine\u00bb] def evalRefine : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false)\n  | _                    => throwUnsupportedSyntax\n\n@[builtinTactic \u00abrefine'\u00bb] def evalRefine' : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true)\n  | _                     => throwUnsupportedSyntax\n\n/--\n   Given a tactic\n   ```\n   apply f\n   ```\n   we want the `apply` tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n   A similar method is also used in Lean 3.\n   This method is useful when applying lemmas such as:\n   ```\n   theorem infLeRight {s t : Set \u03b1} : s \u2293 t \u2264 t\n   ```\n   where `s \u2264 t` here is defined as\n   ```\n   \u2200 {x : \u03b1}, x \u2208 s \u2192 x \u2208 t\n   ```\n-/\ndef elabTermForApply (stx : Syntax) : TacticM Expr := do\n  if stx.isIdent then\n    match (\u2190 Term.resolveId? stx (withInfo := true)) with\n    | some e => return e\n    | _      => pure ()\n  elabTerm stx none (mayPostpone := true)\n\ndef evalApplyLikeTactic (tac : MVarId \u2192 Expr \u2192 MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do\n  withMainContext do\n    let val  \u2190 elabTermForApply e\n    let mvarIds'  \u2190 tac (\u2190 getMainGoal) val\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx =>\n  match stx with\n  | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e\n  | _ => throwUnsupportedSyntax\n\n@[builtinTactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun stx =>\n  withMainContext do\n    let mvarIds'  \u2190 Meta.constructor (\u2190 getMainGoal)\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(\u2190 Meta.existsIntro mvarId e)]) e\n  | _ => throwUnsupportedSyntax\n\n@[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx =>\n  withReducible <| evalTactic stx[1]\n\n@[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx =>\n  withReducibleAndInstances <| evalTactic stx[1]\n\n/--\n  Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable.\n  Note that, the main goal is updated when `Meta.assert` is used in the second case. -/\ndef elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId :=\n  withMainContext do\n    let e \u2190 elabTerm stx none\n    match e with\n    | Expr.fvar fvarId _ => pure fvarId\n    | _ =>\n      let type \u2190 inferType e\n      let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do\n        let mvarId \u2190 getMainGoal\n        let (fvarId, mvarId) \u2190 liftMetaM do\n          let mvarId \u2190 Meta.assert mvarId userName type e\n          Meta.intro1Core mvarId preserveBinderNames\n        replaceMainGoal [mvarId]\n        return fvarId\n      match userName? with\n      | none          => intro `h false\n      | some userName => intro userName true\n\n@[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx =>\n  match stx with\n  | `(tactic| rename $typeStx:term => $h:ident) => do\n    withMainContext do\n      let fvarId \u2190 withoutModifyingState <| withNewMCtxDepth do\n        let type \u2190 elabTerm typeStx none (mayPostpone := true)\n        let fvarId? \u2190 (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n          if (\u2190 isDefEq type localDecl.type) then return localDecl.fvarId else return none\n        match fvarId? with\n        | none => throwError \"failed to find a hypothesis with type{indentExpr type}\"\n        | some fvarId => return fvarId\n      let lctxNew := (\u2190 getLCtx).setUserName fvarId h.getId\n      let mvarNew \u2190 mkFreshExprMVarAt lctxNew (\u2190 getLocalInstances) (\u2190 getMainTarget) MetavarKind.syntheticOpaque (\u2190 getMainTag)\n      assignExprMVar (\u2190 getMainGoal) mvarNew\n      replaceMainGoal [mvarNew.mvarId!]\n  | _ => throwUnsupportedSyntax\n\n/--\n   Make sure `expectedType` does not contain free and metavariables.\n   It applies zeta-reduction to eliminate let-free-vars.\n-/\nprivate def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do\n  let mut expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasFVar then\n    expectedType \u2190 zetaReduce expectedType\n  if expectedType.hasFVar || expectedType.hasMVar then\n    throwError \"expected type must not contain free or meta variables{indentExpr expectedType}\"\n  return expectedType\n\n@[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun stx =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let d \u2190 instantiateMVars d\n    let r \u2190 withDefault <| whnf d\n    unless r.isConstOf ``true do\n      throwError \"failed to reduce to 'true'{indentExpr r}\"\n    let s := d.appArg! -- get instance from `d`\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    return mkApp3 (Lean.mkConst `ofDecideEqTrue) expectedType s rflPrf\n\nprivate def mkNativeAuxDecl (baseName : Name) (type val : Expr) : TermElabM Name := do\n  let auxName \u2190 Term.mkAuxName baseName\n  let decl := Declaration.defnDecl {\n    name := auxName, levelParams := [], type := type, value := val,\n    hints := ReducibilityHints.abbrev,\n    safety := DefinitionSafety.safe\n  }\n  addDecl decl\n  compileDecl decl\n  pure auxName\n\n@[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun stx =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let auxDeclName \u2190 mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    let s := d.appArg! -- get instance from `d`\n    return mkApp3 (Lean.mkConst `ofDecideEqTrue) expectedType s <| mkApp3 (Lean.mkConst `Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf\n\nend Lean.Elab.Tactic\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/Elab/Tactic/ElabTerm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940390354276, "lm_q2_score": 0.05665242411343132, "lm_q1q2_score": 0.01172104884597586}}
{"text": "/-\nCopyright (c) 2021 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg, Asta Halkj\u00e6r From\n-/\n\nimport Lean.Elab.Syntax\nimport Lean.Elab.Tactic.Basic\nimport Lean.Message\nimport Lean.Meta.DiscrTree\nimport Lean.Meta.Tactic.Simp.SimpLemmas\nimport Lean.Syntax\nimport Std.Data.BinomialHeap\n\nnamespace String\n\ndef joinSep (sep : String)  : List String \u2192 String\n  | [] => \"\"\n  | \"\" :: ss => joinSep sep ss\n  | s :: ss =>\n    let tail := joinSep sep ss\n    match tail with\n    | \"\" => s\n    | _ => s ++ sep ++ tail\n\nend String\n\n\nnamespace Std.Format\n\n@[inlineIfReduce]\ndef isEmptyShallow : Format \u2192 Bool\n  | nil => true\n  | text \"\" => true\n  | _ => false\n\n@[inline]\ndef indentDSkipEmpty [ToFormat \u03b1] (f : \u03b1) : Format :=\n  let f := format f\n  if f.isEmptyShallow then nil else indentD f\n\n@[inline]\ndef unlines [ToFormat \u03b1] (fs : List \u03b1) : Format :=\n  Format.joinSep fs line\n\n@[inline]\ndef indentDUnlines [ToFormat \u03b1] : List \u03b1 \u2192 Format :=\n  indentDSkipEmpty \u2218 unlines\n\n@[inline]\ndef indentDUnlinesSkipEmpty [ToFormat \u03b1] (fs : List \u03b1) : Format :=\n  indentDSkipEmpty $ unlines (fs.map format |>.filter (\u00ac \u00b7.isEmptyShallow))\n\ndef formatIf (b : Bool) (f : Thunk Format) : Format :=\n  if b then f.get else nil\n\nend Std.Format\n\n\nnamespace Lean.MessageData\n\n@[inline]\ndef join (ms : List MessageData) : MessageData :=\nms.foldl (\u00b7 ++ \u00b7) nil\n\n@[inlineIfReduce]\ndef isEmptyShallow : MessageData \u2192 Bool\n  | ofFormat f => f.isEmptyShallow\n  | _ => false\n\n@[inline]\ndef indentDSkipEmpty (m : MessageData) : MessageData :=\n  if m.isEmptyShallow then nil else indentD m\n\n@[inline]\ndef unlines (ms : List MessageData) : MessageData :=\n  joinSep ms Format.line\n\n@[inline]\ndef indentDUnlines : List MessageData \u2192 MessageData :=\n  indentDSkipEmpty \u2218 unlines\n\n@[inline]\ndef indentDUnlinesSkipEmpty (fs : List MessageData) : MessageData :=\n  indentDSkipEmpty $ unlines $ fs.filter (\u00ac \u00b7.isEmptyShallow)\n\ndef toMessageDataIf (b : Bool) (f : Thunk MessageData) : MessageData :=\n  if b then f.get else nil\n\ndef nodeFiltering (fs : Array (Option MessageData)) : MessageData :=\n  node $ fs.filterMap id\n\nend Lean.MessageData\n\n\nnamespace Std.PersistentHashSet\n\n@[inline]\ndef merge [BEq \u03b1] [Hashable \u03b1] (s t : PersistentHashSet \u03b1) : PersistentHashSet \u03b1 :=\n  if s.size < t.size then loop s t else loop t s\n  where\n    @[inline]\n    loop s t := s.fold (init := t) \u03bb s a => s.insert a\n\n-- Elements are returned in unspecified order.\ndef toList [BEq \u03b1] [Hashable \u03b1] (s : PersistentHashSet \u03b1) : List \u03b1 :=\n  s.fold (init := []) \u03bb as a => a :: as\n\n-- Elements are returned in unspecified order. (In fact, they are currently\n-- returned in reverse order of `toList`.)\ndef toArray [BEq \u03b1] [Hashable \u03b1] (s : PersistentHashSet \u03b1) : Array \u03b1 :=\n  s.fold (init := #[]) \u03bb as a => as.push a\n\nend Std.PersistentHashSet\n\n\nnamespace Std.PersistentHashMap\n\n@[inline]\ndef merge [BEq \u03b1] [Hashable \u03b1] (m n : PersistentHashMap \u03b1 \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 \u03b2 \u2192 \u03b2) :\n    PersistentHashMap \u03b1 \u03b2 :=\n  if m.size < n.size then loop m n f else loop n m (\u03bb a b b' => f a b' b)\n  where\n    @[inline]\n    loop m n f := m.foldl (init := n) \u03bb map k v =>\n      match map.find? k with\n      | some v' => map.insert k (f k v v')\n      | none => map.insert k v\n\nend Std.PersistentHashMap\n\n\nnamespace Lean.Meta.DiscrTree.Trie\n\nunsafe def foldMUnsafe [Monad m] (initialKeys : Array Key)\n    (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 m \u03c3) (init : \u03c3) : Trie \u03b1 \u2192 m \u03c3\n  | Trie.node vs children => do\n    let s \u2190 vs.foldlM (init := init) \u03bb s v => f s initialKeys v\n    children.foldlM (init := s) \u03bb s (k, t) =>\n      t.foldMUnsafe (initialKeys.push k) f s\n\n@[implementedBy foldMUnsafe]\nconstant foldM [Monad m] (initalKeys : Array Key)\n    (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 m \u03c3) (init : \u03c3) (t : Trie \u03b1) : m \u03c3 :=\n  pure init\n\n@[inline]\ndef fold (initialKeys : Array Key) (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 \u03c3) (init : \u03c3)\n    (t : Trie \u03b1) : \u03c3 :=\n  Id.run $ t.foldM initialKeys (init := init) \u03bb s k a => return f s k a\n\nend Trie\n\n@[inline]\ndef foldM [Monad m] (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 m \u03c3) (init : \u03c3) (t : DiscrTree \u03b1) :\n    m \u03c3 :=\n  t.root.foldlM (init := init) \u03bb s k t => t.foldM #[k] (init := s) f\n\n@[inline]\ndef fold (f : \u03c3 \u2192 Array Key \u2192 \u03b1 \u2192 \u03c3) (init : \u03c3) (t : DiscrTree \u03b1) : \u03c3 :=\n  Id.run $ t.foldM (init := init) \u03bb 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 \u03b1] (t u : DiscrTree \u03b1) : DiscrTree \u03b1 :=\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 \u03b1) : Array \u03b1 :=\n  t.fold (init := #[]) \u03bb as _ a => as.push a\n\ndef toArray (t : DiscrTree \u03b1) : Array (Array Key \u00d7 \u03b1) :=\n  t.fold (init := #[]) \u03bb as keys a => as.push (keys, a)\n\nend DiscrTree\n\n\nnamespace SimpLemmas\n\ndef merge (s t : SimpLemmas) : SimpLemmas where\n  pre := s.pre.merge t.pre\n  post := s.post.merge t.post\n  lemmaNames := s.lemmaNames.merge t.lemmaNames\n  toUnfold := s.toUnfold.merge t.toUnfold\n  erased := s.erased.merge t.erased\n\ndef addSimpEntry (s : SimpLemmas) : SimpEntry \u2192 SimpLemmas\n  | SimpEntry.lemma l => addSimpLemmaEntry s l\n  | SimpEntry.toUnfold d => s.addDeclToUnfold d\n\nopen MessageData in\nprotected def toMessageData (s : SimpLemmas) : MessageData :=\n  node #[\n    \"pre lemmas:\" ++ node (s.pre.values.map toMessageData),\n    \"post lemmas:\" ++ node (s.post.values.map toMessageData),\n    \"definitions to unfold:\" ++ node\n      (s.toUnfold.toArray.qsort Name.lt |>.map toMessageData),\n    \"erased entries:\" ++ node\n      (s.erased.toArray.qsort Name.lt |>.map toMessageData)\n  ]\n\nend SimpLemmas\n\ndef copyMVar (mvarId : MVarId) : MetaM MVarId := do\n  let decl \u2190 getMVarDecl mvarId\n  let mv \u2190 mkFreshExprMVarAt decl.lctx decl.localInstances decl.type decl.kind\n    decl.userName decl.numScopeArgs\n  return mv.mvarId!\n\nend Lean.Meta\n\n\nnamespace Std.BinomialHeap\n\n@[inline]\ndef removeMin {lt : \u03b1 \u2192 \u03b1 \u2192 Bool} (h : BinomialHeap \u03b1 lt) :\n    Option (\u03b1 \u00d7 BinomialHeap \u03b1 lt) :=\n  match h.head? with\n  | some hd => some (hd, h.tail)\n  | none => none\n\nend Std.BinomialHeap\n\n\nnamespace MonadStateOf\n\n@[inline]\ndef ofLens [Monad m] [MonadStateOf \u03b1 m] (project : \u03b1 \u2192 \u03b2) (inject : \u03b2 \u2192 \u03b1 \u2192 \u03b1) :\n    MonadStateOf \u03b2 m where\n  get := return project (\u2190 get)\n  set b := modify \u03bb a => inject b a\n  modifyGet f := modifyGet \u03bb a =>\n    let (r, b) := f (project a)\n    (r, inject b a)\n\nend MonadStateOf\n\n@[inline]\nabbrev setThe (\u03c3) {m} [MonadStateOf \u03c3 m] (s : \u03c3) : m PUnit :=\n  MonadStateOf.set s\n\n\nnamespace ST.Ref\n\nvariable {m} [Monad m] [MonadLiftT (ST \u03c3) m]\n\n@[inline]\nunsafe def modifyMUnsafe (r : Ref \u03c3 \u03b1) (f : \u03b1 \u2192 m \u03b1) : m Unit := do\n  let v \u2190 r.take\n  r.set (\u2190 f v)\n\n@[implementedBy modifyMUnsafe]\ndef modifyM (r : Ref \u03c3 \u03b1) (f : \u03b1 \u2192 m \u03b1) : m Unit := do\n  let v \u2190 r.get\n  r.set (\u2190 f v)\n\n@[inline]\nunsafe def modifyGetMUnsafe (r : Ref \u03c3 \u03b1) (f : \u03b1 \u2192 m (\u03b2 \u00d7 \u03b1)) : m \u03b2 := do\n  let v \u2190 r.take\n  let (b, a) \u2190 f v\n  r.set a\n  return b\n\n@[implementedBy modifyGetMUnsafe]\ndef modifyGetM (r : Ref \u03c3 \u03b1) (f : \u03b1 \u2192 m (\u03b2 \u00d7 \u03b1)) : m \u03b2 := do\n  let v \u2190 r.get\n  let (b, a) \u2190 f v\n  r.set a\n  return b\n\nend ST.Ref\n\n\nnamespace Lean.Meta\n\ndef instantiateMVarsMVarType (mvarId : MVarId) : MetaM Expr := do\n  let type \u2190 instantiateMVars (\u2190 getMVarDecl mvarId).type\n  setMVarType mvarId type\n  return type\n\nend Lean.Meta\n\n\nnamespace Lean.Syntax\n\n-- TODO for debugging, maybe remove\npartial def formatRaw : Syntax \u2192 String\n  | missing => \"missing\"\n  | node kind args =>\n    let args := \", \".joinSep $ args.map formatRaw |>.toList\n    s!\"(node {kind} [{args}])\"\n  | atom _ val => s!\"(atom {val})\"\n  | ident _ _ val _ => s!\"(ident {val})\"\n\nend Lean.Syntax\n\n\nnamespace Lean\n\nopen Lean.Elab.Tactic\n\ndef runTacticMAsMetaM (tac : TacticM Unit) (goal : MVarId) :\n    MetaM (List MVarId) :=\n  run goal tac |>.run'\n\ndef runMetaMAsImportM (x : MetaM \u03b1) : ImportM \u03b1 := do\n  let ctx : Core.Context := { options := (\u2190 read).opts }\n  let state : Core.State := { env := (\u2190 read).env }\n  let r \u2190 x |>.run {} {} |>.run ctx state |>.toIO'\n  match r with\n  | Except.ok ((a, _), _) => pure a\n  | Except.error e => throw $ IO.userError (\u2190 e.toMessageData.toString)\n\ndef runMetaMAsCoreM (x : MetaM \u03b1) : CoreM \u03b1 :=\n  Prod.fst <$> x.run {} {}\n\nend Lean\n\n\nnamespace Lean.Elab.Command\n\nsyntax (name := syntaxCatWithUnreservedTokens)\n  \"declare_syntax_cat' \" ident\n    (&\"allow_leading_unreserved_tokens\" <|> &\"force_leading_unreserved_tokens\")? : command\n\n-- Copied from Lean/Elab/Syntax.lean\nprivate def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do\n  if let Name.str _ suffix _ := catName then\n    let quotSymbol := \"`(\" ++ suffix ++ \"|\"\n    let name := catName ++ `quot\n    -- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator\n    let kind := ``Lean.Parser.Term.quot\n    let cmd \u2190 `(\n      @[termParser] def $(mkIdent name) : Lean.ParserDescr :=\n        Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec)\n          (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol))\n            (Lean.ParserDescr.binary `andthen\n              (Lean.ParserDescr.unary `incQuotDepth (Lean.ParserDescr.cat $(quote catName) 0))\n              (Lean.ParserDescr.symbol \")\"))))\n    elabCommand cmd\n\nopen Lean.Parser (LeadingIdentBehavior) in\n@[builtinCommandElab syntaxCatWithUnreservedTokens]\ndef elabDeclareSyntaxCatWithUnreservedTokens : CommandElab := fun stx => do\n  let catName  := stx[1].getId\n  let leadingIdentBehavior :=\n    match stx[2].getOptional? with\n    | none => LeadingIdentBehavior.default\n    | some b =>\n      match b.getAtomVal! with\n      | \"allow_leading_unreserved_tokens\" => LeadingIdentBehavior.both\n      | \"force_leading_unreserved_tokens\" => LeadingIdentBehavior.symbol\n      | _ => unreachable!\n  let attrName := catName.appendAfter \"Parser\"\n  let env \u2190 getEnv\n  let env \u2190\n    liftIO $ Parser.registerParserCategory env attrName catName\n      leadingIdentBehavior\n  setEnv env\n  declareSyntaxCatQuotParser catName\n\nend Lean.Elab.Command\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Aesop/Util.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.056652419335261495, "lm_q1q2_score": 0.011721048411487755}}
{"text": "inductive Wrapper where\n  | wrap: Wrapper\n\ndef Wrapper.extend: Wrapper \u2192 (Unit \u00d7 Unit)\n  | .wrap => ((), ())\n\nmutual\ninductive Op where\n  | mk: String \u2192 Block \u2192 Op\n\ninductive Assign where\n  | mk : String \u2192 Op \u2192 Assign\n\ninductive Block where\n  | mk: Assign \u2192 Block\n  | empty: Block\nend\n\nmutual\ndef runOp: Op \u2192 Wrapper\n  | .mk _ r => let r' := runBlock r; .wrap\n\ndef runAssign: Assign \u2192 Wrapper\n  | .mk _ op => runOp op\n\ndef runBlock: Block \u2192 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", "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/isDefEqProjPerfIssue.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.033589505771031564, "lm_q1q2_score": 0.011710817330683498}}
{"text": "import GMLInit.Meta.Prelude\nimport GMLInit.Logic.Cast\nimport GMLInit.Logic.Congr\nimport GMLInit.Logic.HEq\nimport Lean\n\nopen Lean\nopen Lean.Meta\nopen Lean.Parser.Tactic (location)\nopen Lean.Elab\nopen Lean.Elab.Tactic (Location expandLocation joinLocation)\n\nnamespace Meta\n\nsyntax termOrHole := term <|> hole <|> syntheticHole\n\nsyntax termList := \"[\" (term <|> hole <|> syntheticHole),* (\"|\" (term <|> hole <|> syntheticHole))? \"]\"\n\nmacro mods:declModifiers \"lemma\" n:declId sig:declSig val:declVal : command =>\n  `($mods:declModifiers theorem $n $sig $val)\n\nsyntax (name := clean) \"clean \" (colGt tactic)? (colGe location)? : tactic\nmacro_rules\n| `(tactic| clean $[$loc:location]?) =>\n  `(tactic| simp only [clean] $[$loc]?)\n| `(tactic| clean $tac $[$loc:location]?) => do\n  let mut loc : Location := match loc with\n  | some loc => expandLocation loc\n  | none => .targets #[] false\n  for stx in Lean.Syntax.filter tac fun stx => stx.getKind == ``location do\n    loc := joinLocation loc (expandLocation stx)\n  match loc with\n  | .wildcard =>\n    `(tactic| $tac; simp only [clean] at *)\n  | .targets hs true =>\n    let locs := hs.map Lean.TSyntax.mk\n    `(tactic| $tac; simp only [clean] at $[$locs]* \u22a2)\n  | .targets hs false =>\n    let locs := hs.map Lean.TSyntax.mk\n    `(tactic| $tac; simp only [clean] at $[$locs]*)\n\nsyntax \"elim_casts\" (location)? : tactic\nset_option hygiene false in macro_rules\n| `(tactic| elim_casts $[$loc]?) =>\n  `(tactic| first | rw [\u2190heq_iff_eq] $[$loc]?; simp only [elim_casts] $[$loc]?; rw [heq_iff_eq] $[$loc]? | simp only [elim_casts] $[$loc]?)\n\nmacro \"exfalso\" : tactic => `(tactic| apply False.elim)\n\nmacro \"absurd \" h:term : tactic => `(tactic| first | apply absurd _ $h | apply absurd $h)\n\ndef Tactic.constr (mvarId : MVarId) : MetaM (List MVarId) := do\n  mvarId.withContext do\n    mvarId.checkNotAssigned `constr\n    let target \u2190 mvarId.getType'\n    matchConstStruct target.getAppFn\n      (fun _ => throwTacticEx `constr mvarId \"target is not an inductive datatype with one constructor\")\n      fun _ us cval => do\n        let ctor := mkAppN (Lean.mkConst cval.name us) target.getAppArgs[:cval.numParams]\n        let ctorType \u2190 inferType ctor\n        let (mvars, _, _) \u2190 forallMetaTelescopeReducing ctorType (some cval.numFields)\n        mvarId.apply <| mkAppN ctor mvars\n\nelab \"constr\" : tactic => Tactic.withMainContext do\n  let gs \u2190 Tactic.constr (\u2190 Tactic.getMainGoal)\n  Term.synthesizeSyntheticMVarsNoPostponing\n  Tactic.replaceMainGoal gs\n\ndef Tactic.left (mvarId : MVarId) : MetaM (List MVarId) := do\n  mvarId.withContext do\n    mvarId.checkNotAssigned `left\n    let target \u2190 mvarId.getType'\n    matchConstInduct target.getAppFn\n      (fun _ => throwTacticEx `left mvarId \"target is not an inductive datatype\")\n      fun ival us => do\n        match ival.ctors with\n        | [ctor,_] => mvarId.apply (mkConst ctor us)\n        | _ => throwTacticEx `left mvarId \"target is not an inductive datatype with two constructors\"\n\nelab \"left\" : tactic => Tactic.withMainContext do\n  let gs \u2190 Tactic.left (\u2190 Tactic.getMainGoal)\n  Term.synthesizeSyntheticMVarsNoPostponing\n  Tactic.replaceMainGoal gs\n\ndef Tactic.right (mvarId : MVarId) : MetaM (List MVarId) := do\n  mvarId.withContext do\n    mvarId.checkNotAssigned `right\n    let target \u2190 mvarId.getType'\n    matchConstInduct target.getAppFn\n      (fun _ => throwTacticEx `right mvarId \"target is not an inductive datatype\")\n      fun ival us => do\n        match ival.ctors with\n        | [_,ctor] => mvarId.apply (mkConst ctor us)\n        | _ => throwTacticEx `right mvarId \"target is not an inductive datatype with two constructors\"\n\nelab \"right\" : tactic => Tactic.withMainContext do\n  let gs \u2190 Tactic.right (\u2190 Tactic.getMainGoal)\n  Term.synthesizeSyntheticMVarsNoPostponing\n  Tactic.replaceMainGoal gs\n\nend Meta\n", "meta": {"author": "fgdorais", "repo": "GMLInit", "sha": "a295111627ac907ebc6a86f906dd9b4d69b338d8", "save_path": "github-repos/lean/fgdorais-GMLInit", "path": "github-repos/lean/fgdorais-GMLInit/GMLInit-a295111627ac907ebc6a86f906dd9b4d69b338d8/GMLInit/Meta/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3486451217982255, "lm_q2_score": 0.033589501780421555, "lm_q1q2_score": 0.011710815939376784}}
{"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 \u27f6 Y \u27f6 Z` -/\n@[derive category]\ndef short_complex [has_zero_morphisms C] := full_subcategory $ \u03bb 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 (\ud835\udfd9 X) i = \ud835\udfd9 (X.X_prev i) := rfl\n\nlemma next_id (X : homological_complex C c) (i : M) : hom.next (\ud835\udfd9 X) i = \ud835\udfd9 (X.X_next i) := rfl\n\nlemma prev_comp {X Y Z : homological_complex C c} (f : X \u27f6 Y) (g : Y \u27f6 Z)\n  (i : M) : hom.prev (f \u226b g) i = hom.prev f i \u226b hom.prev g i := rfl\n\nlemma next_comp {X Y Z : homological_complex C c} (f : X \u27f6 Y) (g : Y \u27f6 Z)\n  (i : M) : hom.next (f \u226b g) i = hom.next f i \u226b 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 \u226b S.1.g = 0 := S.2\n\n@[simps]\ndef mk [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\n  short_complex C := \u27e8composable_morphisms.mk f g, zero\u27e9\n\n@[simp]\nlemma mk_id_\u03c4\u2081 [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\ncomposable_morphisms.hom.\u03c4\u2081 (\ud835\udfd9 (mk f g zero)) = \ud835\udfd9 X := rfl\n@[simp]\nlemma mk_id_\u03c4\u2082 [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\ncomposable_morphisms.hom.\u03c4\u2082 (\ud835\udfd9 (mk f g zero)) = \ud835\udfd9 Y := rfl\n@[simp]\nlemma mk_id_\u03c4\u2083 [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\ncomposable_morphisms.hom.\u03c4\u2083 (\ud835\udfd9 (mk f g zero)) = \ud835\udfd9 Z := rfl\n\n@[simp]\nlemma comp_\u03c4\u2081 [has_zero_morphisms C] {S\u2081 S\u2082 S\u2083 : short_complex C} (f : S\u2081 \u27f6 S\u2082) (g : S\u2082 \u27f6 S\u2083) :\n  (f \u226b g).\u03c4\u2081 = f.\u03c4\u2081 \u226b g.\u03c4\u2081 := rfl\n@[simp]\nlemma comp_\u03c4\u2082 [has_zero_morphisms C] {S\u2081 S\u2082 S\u2083 : short_complex C} (f : S\u2081 \u27f6 S\u2082) (g : S\u2082 \u27f6 S\u2083) :\n  (f \u226b g).\u03c4\u2082 = f.\u03c4\u2082 \u226b g.\u03c4\u2082 := rfl\n@[simp]\nlemma comp_\u03c4\u2083 [has_zero_morphisms C] {S\u2081 S\u2082 S\u2083 : short_complex C} (f : S\u2081 \u27f6 S\u2082) (g : S\u2082 \u27f6 S\u2083) :\n  (f \u226b g).\u03c4\u2083 = f.\u03c4\u2083 \u226b g.\u03c4\u2083 := rfl\n\n@[simps]\ndef hom_mk [has_zero_morphisms C] {X\u2081 Y\u2081 Z\u2081 X\u2082 Y\u2082 Z\u2082 : C} {f\u2081 : X\u2081 \u27f6 Y\u2081} {g\u2081 : Y\u2081 \u27f6 Z\u2081}\n  {f\u2082 : X\u2082 \u27f6 Y\u2082} {g\u2082 : Y\u2082 \u27f6 Z\u2082} {zero\u2081 : f\u2081 \u226b g\u2081 = 0} {zero\u2082 : f\u2082 \u226b g\u2082 = 0}\n  (\u03c4\u2081 : X\u2081 \u27f6 X\u2082) (\u03c4\u2082 : Y\u2081 \u27f6 Y\u2082) (\u03c4\u2083 : Z\u2081 \u27f6 Z\u2082) (comm\u2081\u2082 : f\u2081 \u226b \u03c4\u2082 = \u03c4\u2081 \u226b f\u2082)\n  (comm\u2082\u2083 : g\u2081 \u226b \u03c4\u2083 = \u03c4\u2082 \u226b g\u2082) :\n  mk f\u2081 g\u2081 zero\u2081 \u27f6 mk f\u2082 g\u2082 zero\u2082 := \u27e8\u03c4\u2081, \u03c4\u2082, \u03c4\u2083, comm\u2081\u2082, comm\u2082\u2083\u27e9\n\n@[simps]\ndef iso_mk [has_zero_morphisms C] {S\u2081 S\u2082 : short_complex C}\n  (\u03c4\u2081 : S\u2081.1.X \u2245 S\u2082.1.X) (\u03c4\u2082 : S\u2081.1.Y \u2245 S\u2082.1.Y) (\u03c4\u2083 : S\u2081.1.Z \u2245 S\u2082.1.Z)\n  (comm\u2081\u2082 : S\u2081.1.f \u226b \u03c4\u2082.hom = \u03c4\u2081.hom \u226b S\u2082.1.f)\n  (comm\u2082\u2083 : S\u2081.1.g \u226b \u03c4\u2083.hom = \u03c4\u2082.hom \u226b S\u2082.1.g) :\n  S\u2081 \u2245 S\u2082 :=\n{ hom := \u27e8\u03c4\u2081.hom, \u03c4\u2082.hom, \u03c4\u2083.hom, comm\u2081\u2082, comm\u2082\u2083\u27e9,\n  inv := begin\n    refine \u27e8\u03c4\u2081.inv, \u03c4\u2082.inv, \u03c4\u2083.inv, _, _\u27e9,\n    { simp only [\u2190 cancel_mono \u03c4\u2082.hom, \u2190 cancel_epi \u03c4\u2081.hom,\n        assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm\u2081\u2082], },\n    { simp only [\u2190 cancel_mono \u03c4\u2083.hom, \u2190 cancel_epi \u03c4\u2082.hom,\n        assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm\u2082\u2083], },\n  end,\n  hom_inv_id' := begin\n    ext,\n    { simpa only [comp_\u03c4\u2081, hom_mk_\u03c4\u2081, iso.hom_inv_id], },\n    { simpa only [comp_\u03c4\u2082, hom_mk_\u03c4\u2082, iso.hom_inv_id], },\n    { simpa only [comp_\u03c4\u2083, hom_mk_\u03c4\u2083, iso.hom_inv_id], },\n  end,\n  inv_hom_id' := begin\n    ext,\n    { simpa only [iso.inv_hom_id, comp_\u03c4\u2081, hom_mk_\u03c4\u2081], },\n    { simpa only [iso.inv_hom_id, comp_\u03c4\u2082, hom_mk_\u03c4\u2082], },\n    { simpa only [iso.inv_hom_id, comp_\u03c4\u2083, hom_mk_\u03c4\u2083], },\n  end, }\n\nlemma is_iso_of_is_isos [has_zero_morphisms C] {S\u2081 S\u2082 : short_complex C}\n  (\u03c6 : S\u2081 \u27f6 S\u2082) (h\u2081 : is_iso \u03c6.\u03c4\u2081) (h\u2082 : is_iso \u03c6.\u03c4\u2082) (h\u2083 : is_iso \u03c6.\u03c4\u2083) : is_iso \u03c6 :=\nbegin\n  let e : S\u2081 \u2245 S\u2082 := iso_mk (as_iso \u03c6.\u03c4\u2081) (as_iso \u03c6.\u03c4\u2082) (as_iso \u03c6.\u03c4\u2083) \u03c6.comm\u2081\u2082 \u03c6.comm\u2082\u2083,\n  unfreezingI { rcases \u03c6 with \u27e8\u03c4\u2081, \u03c4\u2082, \u03c4\u2083, comm\u2081\u2082, comm\u2082\u2082\u27e9, },\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 \u2964 C :=\n{ obj := \u03bb X, X.homology,\n  map := \u03bb X Y \u03c6, homology.map X.2 Y.2 \u27e8\u03c6.\u03c4\u2081, \u03c6.\u03c4\u2082, \u03c6.comm\u2081\u2082.symm\u27e9\n    \u27e8\u03c6.\u03c4\u2082, \u03c6.\u03c4\u2083, \u03c6.comm\u2082\u2083.symm\u27e9 rfl,\n  map_id' := \u03bb X, by apply homology.map_id,\n  map_comp' := \u03bb X Y Z \u03c6 \u03c8, 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 \u2964 short_complex C :=\n{ obj := \u03bb X, mk (X.d_to i) (X.d_from i) (X.d_to_comp_d_from i),\n  map := \u03bb 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' := \u03bb X, begin\n    ext,\n    { exact X.prev_id i, },\n    { refl, },\n    { exact X.next_id i, },\n  end,\n  map_comp' := \u03bb 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 \u2245\n  functor_homological_complex C c i \u22d9 short_complex.homology_functor :=\nnat_iso.of_components (\u03bb X, iso.refl _)\n  (\u03bb 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 \u2964 D)\n  [F.preserves_zero_morphisms] :\n  short_complex C \u2964 short_complex D :=\nfull_subcategory.lift _ (induced_functor _ \u22d9 F.map_composable_morphisms)\n(\u03bb X, begin\n  have h := X.2,\n  dsimp [composable_morphisms.zero] at h \u22a2,\n  rw [\u2190 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 \u2964 D}\n  [F.preserves_zero_morphisms] [G.preserves_zero_morphisms] (\u03c6 : F \u27f6 G) :\n  F.map_short_complex \u27f6 G.map_short_complex :=\n{ app := \u03bb X, \u27e8\u03c6.app _, \u03c6.app _, \u03c6.app _, \u03c6.naturality _, \u03c6.naturality _\u27e9, }\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 \u2964 D) [F.additive]\n  {M : Type*} (c : complex_shape M) (i : M) :\nshort_complex.functor_homological_complex C c i \u22d9 F.map_short_complex \u2245\nF.map_homological_complex c \u22d9 short_complex.functor_homological_complex D c i :=\niso.refl _\n\nvariables [preadditive C] [preadditive D] {F G : C \u2964 D} [functor.additive F] [functor.additive G]\n  {M : Type*} (c : complex_shape M) (i : M) (\u03c6 : F \u27f6 G) (X : homological_complex C c)\n\nlemma nat_trans.map_short_complex_app :\n  (nat_trans.map_short_complex \u03c6).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 \u03c6 c).app X) := rfl\n\nlemma naturality_functor_homological_complex_map :\n  (nat_trans.map_short_complex \u03c6).app\n    ((short_complex.functor_homological_complex C c i).obj X) \u226b\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 \u226b\n    (short_complex.functor_homological_complex D c i).map\n      ((nat_trans.map_homological_complex \u03c6 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 LeanCodePrompts.CheckParse\nimport Lean\nopen Lean Meta Parser Elab Tactic\n\ndef contractInductionStx (tac : Syntax) : MetaM Syntax := do\nmatch tac with\n| `(tactic| induction $name $_:inductionAlts) => \n  `(tactic| induction $name)\n| `(tactic| cases $name $_:inductionAlts) => \n  `(tactic| cases $name)\n| _ => return tac\n\ndef contractPolyTactic (tac: String): String := \n  if tac.contains ',' then\n    let head := tac.splitOn \",\" |>.head!\n    if head.contains '[' \n      then head ++ \"]\"\n      else tac\n  else tac\n\n\ndef partialParser  (parser : Parser) (input : String) (fileName := \"<input>\") : MetaM <| Option (Syntax \u00d7 String \u00d7 String) := do\n  let env \u2190 getEnv\n  -- let c := mkParserContext (mkInputContext input fileName) { env := env, options := {} }\n  let p := andthenFn whitespace parser.fn\n  let ictx := mkInputContext input fileName\n  let s := p.run ictx { env, options := {} } (getTokenTable env) (mkParserState input)\n  let stack := s.stxStack.toSubarray.as.filter fun s => !s.hasMissing\n  if stack.isEmpty &&  s.hasError then\n    return    none\n  else \n    -- IO.println s!\"errors: {s.errorMsg}\"\n    let head := input.extract 0 s.pos\n    let stx := stack.back\n    return some (stx, head, input.drop head.length)\n\n\ndeclare_syntax_cat defHead\nsyntax \"theorem\" : defHead\nsyntax \"def\" : defHead\nsyntax \"lemma\" : defHead\nsyntax \"instance\" : defHead\nsyntax \"example\" : defHead\n\ndeclare_syntax_cat theoremAndTactic\n\nsyntax \n  defHead (ident)? (argument)* \":\" term \":=\" \"by\" tacticSeq : theoremAndTactic\n\n\n\ndeclare_syntax_cat variableStatement\nsyntax \"variable\" (argument)* : variableStatement\n\ndeclare_syntax_cat sectionHead\nsyntax \"section\" (colGt ident)? : sectionHead\n\ndeclare_syntax_cat sectionEnd\nsyntax \"end\" (ident)? : sectionEnd\n\n-- code from Leo de Moura\ndef getTactics (s : TSyntax ``tacticSeq) : Array (TSyntax `tactic) :=\n  match s with\n  | `(tacticSeq| { $[$t]* }) => t\n  | `(tacticSeq| $[$t]*) => t\n  | _ => #[]\n\n\ndef parseTactics (s: String) : MetaM <| Array Syntax := do\n  match \u2190 partialParser tacticSeq s with\n  | some (stx, _, _) => \n    let seq := getTactics stx\n    IO.println seq[0]!.raw.reprint.get!\n    return seq\n  | none => return #[]\n\ndef parseTactics? (s: String) : MetaM <| Option <| Array Syntax := do\n  let parsed? \u2190 partialParser tacticSeq s\n  let seq := parsed?.map fun (stx, _, _) => getTactics stx\n  return seq\n\ndef parseTacticBlocks(s: String) : MetaM <| List <| Array String := do\n  let blocks := s.splitOn \"by\" |>.tailD []\n  let stxs \u2190  blocks.filterMapM fun b => parseTactics? b\n  return stxs.map (fun arr => \n    arr.map (fun stx => stx.reprint.getD \"\" |>.trim))\n\nstructure TheoremAndTactic where\n  kind: String\n  name: String\n  args: String \n  type: String\n  firstTactic : String\nderiving Repr\n\nnamespace TheoremAndTactic \n\ndef corePrompt (x: TheoremAndTactic) : String := \n  s!\"{x.args} : {x.type}\"\n\ndef tacticPrompt (x: TheoremAndTactic) : String := \n  s!\"{x.kind} {x.corePrompt} := by {x.firstTactic}; sorry\"\n \ndef toJson (x: TheoremAndTactic) : Json := \n  Json.mkObj [\n    (\"kind\", x.kind),\n    (\"name\", x.name),\n    (\"args\", x.args),\n    (\"type\", x.type),\n    (\"first-tactic\", x.firstTactic),\n    (\"core-prompt\", x.corePrompt),\n    (\"tactic-prompt\", x.tacticPrompt)\n  ]\n\nend TheoremAndTactic\n\ndef getTheoremAndTactic? (input : Syntax)(vars : String) : \n      MetaM <| Option TheoremAndTactic := do\n    match input with\n    | `(theoremAndTactic|$kind:defHead $name:ident $args:argument* : $type := by $tac:tacticSeq) =>\n        let seq := getTactics tac\n        let tac \u2190 contractInductionStx (seq[0]!)\n        let tac := tac.reprint.get!.splitOn \"--\" |>.head! |>.trim\n        let tac := tac.splitOn \"<;>\" |>.head! |>.trim\n        let tac := contractPolyTactic tac\n        let argString := \n          (args.map fun a => a.raw.reprint.get!).foldl (fun a b => a ++ \" \" ++ b) (vars)\n        let argString := argString.replace \"\\n\" \" \" |>.trim\n        return some \u27e8kind.raw.reprint.get!.trim, name.raw.reprint.get!.trim,\n        argString, type.raw.reprint.get!.trim, tac\u27e9\n    | `(theoremAndTactic|$kind:defHead  $args:argument* : $type := by $tac:tacticSeq) =>\n        let seq := getTactics tac\n        let tac \u2190 contractInductionStx (seq[0]!)\n        let tac := tac.reprint.get!.splitOn \"--\" |>.head! |>.trim\n        let tac := tac.splitOn \"<;>\" |>.head! |>.trim\n        let tac := contractPolyTactic tac\n        let argString := \n          (args.map fun a => a.raw.reprint.get!).foldl (fun a b => a ++ \" \" ++ b) (vars)\n        let argString := argString.replace \"\\n\" \" \" |>.trim\n        return some \u27e8kind.raw.reprint.get!.trim,\"\",\n        argString, type.raw.reprint.get!.trim, \n        tac\u27e9 \n    | _ =>\n      IO.println s!\"could not parse theorem {input.reprint.get!} to get tactic\"\n      return none\n\ndef parseTheoremAndTactic? (input: String) : MetaM <| Option TheoremAndTactic := do\n  match \u2190 partialParser (categoryParser `theoremAndTactic 0) input with\n  | some (stx, _, _) => \n      getTheoremAndTactic? stx \"\"\n  | none => \n    IO.println s!\"could not parse theorem {input}\"\n    throwUnsupportedSyntax\n\ndef getVariables! (input : Syntax) : \n      MetaM String := do\n    match input with\n    | `(variableStatement|variable $args:argument*) =>\n        let argString := \n          (args.map fun a => a.raw.reprint.get!).foldl (fun a b => a ++ \" \" ++ b) \"\"\n        return argString.replace \"\\n\" \" \" |>.trim \n    | _ =>\n      IO.println s!\"could not parse theorem {input.reprint.get!}\"\n      throwUnsupportedSyntax\n\n\npartial def getTheoremsTacticsAux (text: String) (vars : Array String)\n                        (sections : Array String)\n                        (accum : Array TheoremAndTactic) : MetaM (Array TheoremAndTactic) := do\n  if text.isEmpty then \n      return accum\n  else\n      match (\u2190 partialParser (categoryParser `theoremAndTactic 0) text) with\n      | some (stx, _, tail) => \n          let entry? \u2190 getTheoremAndTactic? stx (vars.foldl (fun a b => a ++ \" \" ++ b) \"\")\n          let accum := match entry? with\n            | some entry => accum.push entry\n            | none => accum \n          getTheoremsTacticsAux tail vars sections (accum)\n      | none => \n        match \n          (\u2190 partialParser (categoryParser `variableStatement 0) text) with\n        | some (stx, _, tail) =>\n          let newVars \u2190 getVariables! stx\n          let innerVars := vars.back\n          getTheoremsTacticsAux tail (vars.pop.push (innerVars ++ \" \" ++ newVars)) sections accum\n        | none =>\n          match \n            (\u2190 partialParser (categoryParser `sectionHead 0) text) with\n          | some (stx, _, tail) =>\n            -- IO.println s!\"\\nsection head found {stx.reprint.get!} followed by {tail.take 30}\"\n            match stx with\n            | `(sectionHead|section $name) =>\n            getTheoremsTacticsAux tail (vars.push \"\") \n              (sections.push name.raw.reprint.get!.trim) accum\n            | `(sectionHead|section) => \n              getTheoremsTacticsAux tail (vars.push \"\") (sections.push \"\") accum\n            | _ => \n              getTheoremsTacticsAux tail vars sections accum\n          | none =>\n            match \n              (\u2190 partialParser (categoryParser `sectionEnd 0) text) with\n            | some (stx, _, tail) =>\n              -- IO.println s!\"\\nend found {stx.reprint.get!} with sections {sections} and vars {vars} followed by {tail.take 30}\"\n              match stx with\n              | `(sectionEnd|end $name) =>\n                if sections.back? == some name.raw.reprint.get!.trim then\n                  getTheoremsTacticsAux tail (vars.pop) (sections.pop) accum\n                else\n                  getTheoremsTacticsAux tail vars sections accum\n              | `(sectionEnd|end) =>\n                getTheoremsTacticsAux tail (vars.pop) sections accum\n              | _ => \n                getTheoremsTacticsAux tail (vars) sections accum\n            | none =>        \n              match \u2190 partialParser Command.docComment text with\n              | some (_, _, tail) =>\n                getTheoremsTacticsAux tail vars sections accum\n              | none =>      \n                match \u2190 partialParser Command.moduleDoc text with\n              | some (_, _, tail) =>\n                getTheoremsTacticsAux tail vars sections accum\n              | none =>\n                let head := text.get 0\n                if ('a' \u2264 head && head \u2264 'z') || \n                  ('A' \u2264 head && head \u2264 'Z') then\n                  let tail := text.dropWhile fun c => \n                    ('a' \u2264 c && c \u2264 'z') || \n                  ('A' \u2264 c && c \u2264 'Z')\n                  getTheoremsTacticsAux tail vars sections accum\n                else\n                  getTheoremsTacticsAux (text.drop 1) vars sections accum\n\ndef getTheoremsTactics (text: String) : MetaM (Array TheoremAndTactic) := do\n  getTheoremsTacticsAux text #[\"\"] #[] #[]\n\ndef leanFiles (paths: List String) : IO (Array System.FilePath) := do \n  Lean.SearchPath.findAllWithExt [System.mkFilePath paths] \"lean\"\n \ndef polyLeanFiles := leanFiles ([\"/home/gadgil/code/polylean/Polylean\"])\n\ndef getTheoremsTacticsFromFiles (files: Array System.FilePath) : MetaM (Array TheoremAndTactic) := do\n  let mut accum := #[]\n  IO.println s!\"parsing {files.size} lean files\"\n  let mut parsedCount := 0\n  for file in files do\n    IO.println s!\"parsing {file}\"\n    let text \u2190 IO.FS.readFile file\n    let theorems \u2190 getTheoremsTactics text\n    IO.println s!\"parsed {theorems.size} theorems with tactics\"\n    parsedCount := parsedCount + 1\n    IO.println s!\"parsed {parsedCount} files out of {files.size}\"\n    accum := accum ++ theorems\n  return accum\n\ndef readAndSaveTheoremTacticsM (inps: List String ) : MetaM String := do\n  let mut files := #[]\n  for inp in inps do\n    let fs \u2190  leanFiles [inp]\n    files := files ++ fs\n  IO.println s!\"found {files.size} files\"\n  let all \u2190 getTheoremsTacticsFromFiles files\n  let js := Json.arr <| all.map fun a => a.toJson\n  return js.pretty\n\ndef readAndSaveTheoremTacticsCore \n  (inps: List String ) : CoreM String :=\n  readAndSaveTheoremTacticsM inps |>.run'\n\n-- example\ndef getTheoremsTacticsFromPolyLean : MetaM (Array TheoremAndTactic) := do\n  let files \u2190 polyLeanFiles\n  logInfo m!\"found {files.size} files\"\n  let files := files.toList.take 12 |>.toArray\n  getTheoremsTacticsFromFiles files\n\n#eval \"rw [Subsingleton.elim hd] -- align the Decidable instances implicitly used by `dite`\" |>.splitOn \"--\" |>.head!\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/FirstTacticData.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.05184546225475575, "lm_q1q2_score": 0.011686828647872249}}
{"text": "variable (x : Id Nat) (h : x = x)\n\ntheorem Id_def : Id \u03b1 = \u03b1 := rfl\n\ntheorem bar : x = x.succ := by\n  rw [Id_def] at x\n  -- rw should not expose the auxdecl `bar`:\n  fail_if_success assumption\n  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/1963.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.036769464096493294, "lm_q1q2_score": 0.011671593675809994}}
{"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\nNotation for operators defined at Prelude.lean\n-/\nprelude\nimport Init.Prelude\n\n-- DSL for specifying parser precedences and priorities\n\nnamespace Lean.Parser.Syntax\n\nsyntax:65 (name := addPrec) prec \" + \" prec:66 : prec\nsyntax:65 (name := subPrec) prec \" - \" prec:66 : prec\n\nsyntax:65 (name := addPrio) prio \" + \" prio:66 : prio\nsyntax:65 (name := subPrio) prio \" - \" prio:66 : prio\n\nend Lean.Parser.Syntax\n\nmacro \"max\"  : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...)\nmacro \"arg\"  : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...)\nmacro \"lead\" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...)\nmacro \"(\" p:prec \")\" : prec => return p\nmacro \"min\"  : prec => `(10)   -- minimum precedence used in term parsers\nmacro \"min1\" : prec => `(11)   -- `(min+1) we can only `min+1` after `Meta.lean`\n/-\n  `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.\n  We use `max_prec` to workaround bootstrapping issues. -/\nmacro \"max_prec\" : term => `(1024)\n\nmacro \"default\" : prio => `(1000)\nmacro \"low\"     : prio => `(100)\nmacro \"mid\"     : prio => `(1000)\nmacro \"high\"    : prio => `(10000)\nmacro \"(\" p:prio \")\" : prio => return p\n\n-- Basic notation for defining parsers\n-- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses\nsyntax:arg stx:max \"+\" : stx\nsyntax:arg stx:max \"*\" : stx\nsyntax:arg stx:max \"?\" : stx\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\u2081 <|> $p\u2082) => `(stx| orelse($p\u2081, $p\u2082))\n\n/- Comma-separated sequence. -/\nmacro:arg x:stx:max \",*\"   : stx => `(stx| sepBy($x, \",\", \", \"))\nmacro:arg x:stx:max \",+\"   : stx => `(stx| sepBy1($x, \",\", \", \"))\n/- Comma-separated sequence with optional trailing comma. -/\nmacro:arg x:stx:max \",*,?\" : stx => `(stx| sepBy($x, \",\", \", \", allowTrailingSep))\nmacro:arg x:stx:max \",+,?\" : stx => `(stx| sepBy1($x, \",\", \", \", allowTrailingSep))\n\nmacro:arg \"!\" x:stx:max : stx => `(stx| notFollowedBy($x))\n\nsyntax (name := rawNatLit) \"nat_lit \" num : term\n\ninfixr:90 \" \u2218 \"  => Function.comp\ninfixr:35 \" \u00d7 \"  => Prod\n\ninfixl:55 \" ||| \" => HOr.hOr\ninfixl:58 \" ^^^ \" => HXor.hXor\ninfixl:60 \" &&& \" => HAnd.hAnd\ninfixl:65 \" + \"   => HAdd.hAdd\ninfixl:65 \" - \"   => HSub.hSub\ninfixl:70 \" * \"   => HMul.hMul\ninfixl:70 \" / \"   => HDiv.hDiv\ninfixl:70 \" % \"   => HMod.hMod\ninfixl:75 \" <<< \" => HShiftLeft.hShiftLeft\ninfixl:75 \" >>> \" => HShiftRight.hShiftRight\ninfixr:80 \" ^ \"   => HPow.hPow\ninfixl:65 \" ++ \"  => HAppend.hAppend\nprefix:100 \"-\"    => Neg.neg\nprefix:100 \"~~~\"  => Complement.complement\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% HAppend.hAppend $x $y)\n\n-- declare ASCII alternatives first so that the latter Unicode unexpander wins\ninfix:50 \" <= \" => LE.le\ninfix:50 \" \u2264 \"  => LE.le\ninfix:50 \" < \"  => LT.lt\ninfix:50 \" >= \" => GE.ge\ninfix:50 \" \u2265 \"  => GE.ge\ninfix:50 \" > \"  => GT.gt\ninfix:50 \" = \"  => Eq\ninfix: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 \u2264 $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 \u2265 $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\ninfixr:35 \" /\\\\ \" => And\ninfixr:35 \" \u2227 \"   => And\ninfixr:30 \" \\\\/ \" => Or\ninfixr:30 \" \u2228  \"  => Or\nnotation:max \"\u00ac\" p:40 => Not p\n\ninfixl:35 \" && \" => and\ninfixl:30 \" || \" => or\nnotation:max \"!\" b:40 => not b\n\ninfixr:67 \" :: \" => List.cons\nsyntax:20 term:21 \" <|> \" term:20 : term\nsyntax:60 term:61 \" >> \" term:60 : term\ninfixl:55  \" >>= \" => Bind.bind\nnotation:60 a:60 \" <*> \" b:61 => Seq.seq a fun _ : Unit => b\nnotation:60 a:60 \" <* \" b:61 => SeqLeft.seqLeft a fun _ : Unit => b\nnotation:60 a:60 \" *> \" b:61 => SeqRight.seqRight a fun _ : Unit => b\ninfixr: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\nsyntax (name := termDepIfThenElse)\n  ppRealGroup(ppRealFill(ppIndent(\"if \" ident \" : \" term \" then\") ppSpace term)\n    ppDedent(ppSpace) ppRealFill(\"else \" term)) : term\n\nmacro_rules\n  | `(if $h:ident : $c then $t:term else $e:term) => `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite ?m (fun $h:ident => $t) (fun $h:ident => $e))\n\nsyntax (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:term else $e:term) => `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite ?m $t $e)\n\nmacro \"if \" \"let \" pat:term \" := \" d:term \" then \" t:term \" else \" e:term : term =>\n  `(match $d:term with | $pat:term => $t | _ => $e)\n\nsyntax:min term \" <| \" term:min : term\n\nmacro_rules\n  | `($f $args* <| $a) => let args := args.push a; `($f $args*)\n  | `($f <| $a) => `($f $a)\n\nsyntax:min term \" |> \" term:min1 : term\n\nmacro_rules\n  | `($a |> $f $args*) => let args := args.push a; `($f $args*)\n  | `($a |> $f)        => `($f $a)\n\n-- Haskell-like pipe <|\n-- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations.\nsyntax:min term atomic(\" $\" ws) term:min : term\n\nmacro_rules\n  | `($f $args* $ $a) => let args := args.push a; `($f $args*)\n  | `($f $ $a) => `($f $a)\n\nsyntax \"{ \" 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.\n  Recall that terms such as `match ... with ...` and `\u27e8...\u27e9` will postpone elaboration until\n  expected type is known. So, `without_expected_type` is not effective in this case. -/\nmacro \"without_expected_type \" x:term : term => `(let aux := $x; aux)\n\nsyntax \"[\" term,* \"]\"  : term\nsyntax \"%[\" term,* \"|\" term \"]\" : term -- auxiliary notation for creating big list literals\n\nnamespace Lean\n\nmacro_rules\n  | `([ $elems,* ]) => do\n    let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : 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  (\u2190 ``(List.cons $(elems.elemsAndSeps[i]) $result))\n    if elems.elemsAndSeps.size < 64 then\n      expandListLit elems.elemsAndSeps.size false (\u2190 ``(List.nil))\n    else\n      `(%[ $elems,* | List.nil ])\n\nnotation:50 e:51 \" matches \" p:51 => ((match e with | p => true | _ => false) : Bool)\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 metapgrogramming, as is done by `have`/`show`.\n/-- Special identifier introduced by \"anonymous\" `have : ...`, `suffices p ...` etc. -/\nmacro tk:\"this\" : term => return Syntax.ident tk.getHeadInfo \"this\".toSubstring `this []\n\nnamespace Parser.Tactic\n/--\nIntroduce one or more hypotheses, optionally naming and/or pattern-matching them.\nFor each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type.\n* `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`.\n* `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`,\n  or matched against a pattern:\n  ```lean\n  -- ... \u22a2 \u03b1 \u00d7 \u03b2 \u2192 ...\n  intro (a, b)\n  -- ..., a : \u03b1, b : \u03b2 \u22a2 ...\n  ```\n* Alternatively, `intro` can be combined with pattern matching much like `fun`:\n  ```lean\n  intro\n  | n + 1, 0 => tac\n  | ...\n  ```\n-/\nsyntax (name := intro) \"intro \" notFollowedBy(\"|\") (colGt term:max)* : tactic\n/-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/\nsyntax (name := intros) \"intros \" (colGt (ident <|> \"_\"))* : tactic\n/--\n`rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`,\nor fails if no such hypothesis could be found. -/\nsyntax (name := rename) \"rename \" term \" => \" ident : tactic\n/-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/\nsyntax (name := revert) \"revert \" (colGt term:max)+ : tactic\n/-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/\nsyntax (name := clear) \"clear \" (colGt term:max)+ : tactic\n/--\n`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`.\nIf `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/\nsyntax (name := subst) \"subst \" (colGt term:max)+ : tactic\n/--\n`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.\nNote also the `\u2039t\u203a` term notation, which is a shorthand for `show t by assumption`. -/\nsyntax (name := assumption) \"assumption\" : tactic\n/--\n`contradiction` closes the main goal if its hypotheses are \"trivially contradictory\".\n```lean\nexample (h : False) : p := by contradiction  -- inductive type/family with no applicable constructors\nexample (h : none = some true) : p := by contradiction  -- injectivity of constructors\nexample (h : 2 + 2 = 3) : p := by contradiction  -- decidable false proposition\nexample (h : p) (h' : \u00ac p) : q := by contradiction\nexample (x : Nat) (h : x \u2260 x) : p := by contradiction\n```\n-/\nsyntax (name := contradiction) \"contradiction\" : tactic\n/--\n`apply e` tries to match the current goal against the conclusion of `e`'s type.\nIf it succeeds, then the tactic returns as many subgoals as the number of premises that\nhave not been fixed by type inference or type class resolution.\nNon-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\nsyntax (name := apply) \"apply \" term : tactic\n/--\n`exact e` closes the main goal if its target type matches that of `e`.\n-/\nsyntax (name := exact) \"exact \" term : tactic\n/--\n`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved\nby unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name.\n-/\nsyntax (name := refine) \"refine \" term : tactic\n/-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/\nsyntax (name := refine') \"refine' \" term : tactic\n/-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/\nsyntax (name := constructor) \"constructor\" : tactic\n/--\n`case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails.\n`case tag x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/\nsyntax (name := case) \"case \" (ident <|> \"_\") (ident <|> \"_\")* \" => \" tacticSeq : tactic\n/--\n`next => tac` focuses on the next goal solves it using `tac`, or else fails.\n`next x\u2081 ... x\u2099 => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/\nmacro \"next \" args:(ident <|> \"_\")* \" => \" tac:tacticSeq : tactic => `(tactic| case _ $(args.getArgs)* => $tac)\n\n/-- `allGoals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/\nsyntax (name := allGoals) \"all_goals \" tacticSeq : tactic\n/-- `anyGoals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds.  -/\nsyntax (name := anyGoals) \"any_goals \" tacticSeq : tactic\n/--\n`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.\nUsually `\u00b7 tac`, which enforces that the goal is closed by `tac`, should be preferred. -/\nsyntax (name := focus) \"focus \" tacticSeq : tactic\n/-- `skip` does nothing. -/\nsyntax (name := skip) \"skip\" : tactic\n/-- `done` succeeds iff there are no remaining goals. -/\nsyntax (name := done) \"done\" : tactic\nsyntax (name := traceState) \"trace_state\" : tactic\nsyntax (name := failIfSuccess) \"fail_if_success \" tacticSeq : tactic\nsyntax (name := paren) \"(\" tacticSeq \")\" : tactic\nsyntax (name := withReducible) \"with_reducible \" tacticSeq : tactic\nsyntax (name := withReducibleAndInstances) \"with_reducible_and_instances \" tacticSeq : tactic\n/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/\nsyntax (name := first) \"first \" withPosition((group(colGe \"|\" tacticSeq))+) : tactic\nsyntax (name := rotateLeft) \"rotate_left\" (num)? : tactic\nsyntax (name := rotateRight) \"rotate_right\" (num)? : tactic\n/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/\nmacro \"try \" t:tacticSeq : tactic => `(first | $t | skip)\n/-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/\nmacro:1 x:tactic \" <;> \" y:tactic:0 : tactic => `(tactic| focus ($x:tactic; all_goals $y:tactic))\n\n/-- `rfl` is a shorthand for `exact rfl`. -/\nmacro \"rfl\" : tactic => `(exact rfl)\n/-- `admit` is a shorthand for `exact sorry`. -/\nmacro \"admit\" : tactic => `(exact sorry)\n/-- The `sorry` tactic is a shorthand for `exact sorry`. -/\nmacro \"sorry\" : tactic => `(exact sorry)\nmacro \"infer_instance\" : tactic => `(exact inferInstance)\n\n/-- Optional configuration option for tactics -/\nsyntax config := atomic(\"(\" &\"config\") \" := \" term \")\"\n\nsyntax locationWildcard := \"*\"\nsyntax locationHyp      := (colGt term:max)+ (\"\u22a2\" <|> \"|-\")?\nsyntax location         := withPosition(\" at \" (locationWildcard <|> locationHyp))\n\nsyntax (name := change) \"change \" term (location)? : tactic\nsyntax (name := changeWith) \"change \" term \" with \" term (location)? : tactic\n\nsyntax rwRule    := (\"\u2190 \" <|> \"<- \")? term\nsyntax rwRuleSeq := \"[\" rwRule,*,? \"]\"\n\nsyntax (name := rewriteSeq) \"rewrite \" (config)? rwRuleSeq (location)? : tactic\n\nsyntax (name := rwSeq) \"rw \" (config)? rwRuleSeq (location)? : tactic\n\ndef rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do\n  -- We show the `rfl` state on `]`\n  let seq   := stx[2]\n  let rbrak := seq[2]\n  -- Replace `]` token with one without position information in the expanded tactic\n  let seq   := seq.setArg 2 (mkAtom \"]\")\n  let tac   := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 2 seq\n  `(tactic| $tac; try (with_reducible rfl%$rbrak))\n\n@[macro rwSeq] def expandRwSeq : Macro :=\n  rwWithRfl ``Lean.Parser.Tactic.rewriteSeq \"rewrite\"\n\nsyntax (name := injection) \"injection \" term (\" with \" (colGt (ident <|> \"_\"))+)? : tactic\n\nsyntax (name := injections) \"injections\" : tactic\n\nsyntax discharger := atomic(\"(\" (&\"discharger\" <|> &\"disch\")) \" := \" tacticSeq \")\"\n\nsyntax simpPre   := \"\u2193\"\nsyntax simpPost  := \"\u2191\"\nsyntax simpLemma := (simpPre <|> simpPost)? (\"\u2190 \" <|> \"<- \")? term\nsyntax simpErase := \"-\" term:max\nsyntax simpStar  := \"*\"\nsyntax (name := simp) \"simp \" (config)? (discharger)? (&\"only \")? (\"[\" (simpStar <|> simpErase <|> simpLemma),* \"]\")? (location)? : tactic\nsyntax (name := simpAll) \"simp_all \" (config)? (discharger)? (&\"only \")? (\"[\" (simpErase <|> simpLemma),* \"]\")? : tactic\n\n/--\n  Delta expand the given definition.\n  This is a low-level tactic, it will expose how recursive definitions have been compiled by Lean. -/\nsyntax (name := delta) \"delta \" ident (location)? : tactic\n/--\n  Unfold definition. For non-recursive definitions, this tactic is identical to `delta`.\n  For recursive definitions, it hides the encoding tricks used by the Lean frontend to convince the\n  kernel that the definition terminates. -/\nsyntax (name := unfold) \"unfold \" ident (location)? : tactic\n\n-- Auxiliary macro for lifting have/suffices/let/...\n-- It makes sure the \"continuation\" `?_` is the main goal after refining\nmacro \"refine_lift \" e:term : tactic => `(focus (refine no_implicit_lambda% $e; rotate_right))\n\nmacro \"have \" d:haveDecl : tactic => `(refine_lift have $d:haveDecl; ?_)\n/- We use a priority > default, to avoid ambiguity with previous `have` notation -/\nmacro (priority := high) \"have\" x:ident \" := \" p:term : tactic => `(have $x:ident : _ := $p)\nmacro \"suffices \" d:sufficesDecl : tactic => `(refine_lift suffices $d:sufficesDecl; ?_)\nmacro \"let \" d:letDecl : tactic => `(refine_lift let $d:letDecl; ?_)\nmacro \"show \" e:term : tactic => `(refine_lift show $e:term from ?_)\nsyntax (name := letrec) withPosition(atomic(group(\"let \" &\"rec \")) letRecDecls) : tactic\nmacro_rules\n  | `(tactic| let rec $d:letRecDecls) => `(tactic| refine_lift let rec $d:letRecDecls; ?_)\n\n-- Similar to `refineLift`, but using `refine'`\nmacro \"refine_lift' \" e:term : tactic => `(focus (refine' no_implicit_lambda% $e; rotate_right))\nmacro \"have' \" d:haveDecl : tactic => `(refine_lift' have $d:haveDecl; ?_)\nmacro (priority := high) \"have'\" x:ident \" := \" p:term : tactic => `(have' $x:ident : _ := $p)\nmacro \"let' \" d:letDecl : tactic => `(refine_lift' let $d:letDecl; ?_)\n\nsyntax inductionAlt  := ppDedent(ppLine) \"| \" (group(\"@\"? ident) <|> \"_\") (ident <|> \"_\")* \" => \" (hole <|> syntheticHole <|> tacticSeq)\nsyntax inductionAlts := \"with \" (tactic)? withPosition( (colGe inductionAlt)+)\nsyntax (name := induction) \"induction \" term,+ (\" using \" ident)?  (\"generalizing \" (colGt term:max)+)? (inductionAlts)? : tactic\n\nsyntax generalizeArg := atomic(ident \" : \")? term:51 \" = \" ident\n/--\n`generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal with a fresh hypothesis `x`s.\nIf `h` is given, `h : e = x` is introduced as well. -/\nsyntax (name := generalize) \"generalize \" generalizeArg,+ : tactic\n\nsyntax casesTarget := atomic(ident \" : \")? term\nsyntax (name := cases) \"cases \" casesTarget,+ (\" using \" ident)? (inductionAlts)? : tactic\n\nsyntax (name := existsIntro) \"exists \" term : tactic\n\n/-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/\nsyntax (name := renameI) \"rename_i \" (colGt (ident <|> \"_\"))+ : tactic\n\nsyntax \"repeat \" tacticSeq : tactic\nmacro_rules\n  | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)\n\nsyntax \"trivial\" : tactic\n\nsyntax (name := split) \"split \" (colGt term)? (location)? : tactic\n\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`.\nThe premises of this hypothesis, either universal quantifications or non-dependent implications,\nare instantiated by concrete terms coming either from arguments `a\u2081` ... `a\u2099`.\nThe tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099` and tries to clear the previous one.\n-/\nsyntax (name := specialize) \"specialize \" term : tactic\n\nmacro_rules | `(tactic| trivial) => `(tactic| assumption)\nmacro_rules | `(tactic| trivial) => `(tactic| rfl)\nmacro_rules | `(tactic| trivial) => `(tactic| contradiction)\nmacro_rules | `(tactic| trivial) => `(tactic| apply True.intro)\nmacro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)\n\nmacro \"unhygienic \" t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq)\n\nend Tactic\n\nnamespace Attr\n-- simp attribute syntax\nsyntax (name := simp) \"simp\" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr\nend Attr\n\nend Parser\nend Lean\n\nmacro \"\u2039\" type:term \"\u203a\" : term => `((by assumption : $type))\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/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.03963883966822149, "lm_q1q2_score": 0.011662340109558961}}
{"text": "import data.multiset.basic\nimport tactic.where\n\n-- First set up the testing framework...\n\nsection framework\n\n-- Note that we cannot have any explicit `open`s, we are currently working around this bug:\n-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/What's.20the.20deal.20with.20.60open.60\n\n@[user_command]\nmeta def run_parser_from_command_cmd\n  (_ : interactive.parse $ lean.parser.tk \"run_parser_from_command\")\n  : lean.parser unit :=\ndo ns \u2190 lean.parser.ident,\n   let ns := if ns = `NONE then name.anonymous else ns,\n   n \u2190 lean.parser.ident,\n   prog \u2190 lean.parser.of_tactic $ tactic.mk_const (ns ++ n) >>= tactic.eval_expr (lean.parser unit),\n   if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $\n     \"namespace \" ++ ns.to_string,\n   prog,\n   if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $\n     \"end \" ++ ns.to_string\n\nmeta def remove_dot_aux : list char \u2192 list char\n| [] := []\n| (c :: rest) := (if c = '.' then '_' else c) :: remove_dot_aux rest\n\nmeta def remove_dot (s : string) : string :=\n(remove_dot_aux s.data).as_string\n\n-- NOTE We must emit fully qualified names below in order to not influence the real tests!\n@[user_command]\nmeta def run_parser_from_tactic_cmd\n  (_ : interactive.parse $ lean.parser.tk \"run_parser_from_tactic\")\n  : lean.parser unit :=\ndo ns \u2190 lean.parser.ident,\n   let ns := if ns = `NONE then name.anonymous else ns,\n   n \u2190 lean.parser.ident,\n   let tac_name := \"try_test_\" ++ (remove_dot (ns ++ n).to_string),\n   lean.parser.emit_code_here $\n     \"meta def tactic.interactive.\" ++ tac_name ++\n       \" (_ : interactive.parse \" ++ (ns ++ n).to_string ++ \")\" ++ \": tactic unit := tactic.triv\",\n   if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $\n     \"namespace \" ++ ns.to_string,\n   lean.parser.emit_code_here $\n      \"example : true := by \" ++ (name.mk_string tac_name name.anonymous).to_string,\n   if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $\n     \"end \" ++ ns.to_string\n\nmeta def assert_name_eq (n\u2081 n\u2082 : name) : lean.parser unit :=\nif n\u2081 = n\u2082 then return () else tactic.fail sformat!\"violation: '{n\u2081}' \u2260 '{n\u2082}'!\"\n\nmeta def assert_list_noorder_eq {\u03b1 : Type} [decidable_eq \u03b1] [has_to_string \u03b1]\n  (l\u2081 l\u2082 : list \u03b1) : lean.parser unit :=\nif (l\u2081 : multiset \u03b1) = (l\u2082 : multiset \u03b1) then return ()\nelse tactic.fail sformat!\"violation: '{l\u2081}' \u2260 '{l\u2082}'!\"\n\nmeta def assert_where_msg_eq (s : string) : lean.parser unit :=\ndo tw \u2190 where.build_msg,\n   if s = tw then return ()\n   else tactic.fail sformat!\"violation:\\n'\\n{tw}\\n'\\n\\n          \u2260\\n\\n'\\n{s}\\n'!\"\n\n-- Test the test framework...\n\nmeta def dummy : lean.parser unit := return ()\n\nrun_parser_from_command NONE dummy\nrun_parser_from_tactic  NONE dummy\n\nend framework\n\n-- TESTS START\n\n\n\n-- TEST: `#where` output\n-- NOTE: This section must come first because of the `open_namespaces` bug referenced above.\n-- NOTE: All other sections have correct answers, but the order of variables (say) may be safely\n--       reordered here: changes to `#where` which break this set of tests are possible, without an\n--       error.\n\nmeta def test_output_1 : lean.parser unit :=\nassert_where_msg_eq \"namespace [root namespace]\\n\\n\\n\\n\\nend [root namespace]\\n\"\nmeta def test_output_2 : lean.parser unit :=\nassert_where_msg_eq \"namespace [root namespace]\\n\\nopen list nat\\n\\n\\n\\nend [root namespace]\\n\"\nmeta def test_output_3 : lean.parser unit :=\nassert_where_msg_eq \"namespace [root namespace]\\n\\nopen list nat\\nvariables {c : \u2115 \u2192 list \u2115} (b a : \u2115) [decidable_eq : \u2115]\\n\\n\\n\\nend [root namespace]\\n\"\nmeta def test_output_4 : lean.parser unit :=\nassert_where_msg_eq \"namespace [root namespace]\\n\\nopen list nat\\nvariables {c : \u2115 \u2192 list \u2115} (b a : \u2115) [decidable_eq : \u2115]\\ninclude c a\\n\\n\\n\\nend [root namespace]\\n\"\nmeta def test_output_5 : lean.parser unit :=\nassert_where_msg_eq \"namespace a\\n\\nopen list nat\\nvariables {c : \u2115 \u2192 list \u2115} (b a : \u2115) [decidable_eq : \u2115]\\ninclude c a\\n\\n\\n\\nend a\\n\"\nmeta def test_output_6 : lean.parser unit :=\nassert_where_msg_eq \"namespace a.b\\n\\nopen a list nat\\nvariables {c : \u2115 \u2192 list \u2115} (b a : \u2115) [decidable_eq : \u2115]\\ninclude c a\\n\\n\\n\\nend a.b\\n\"\n\nsection b1\n\n-- #where\nrun_parser_from_command NONE test_output_1\n\nopen nat list\n\n-- #where\nrun_parser_from_command NONE test_output_2\n\nvariables (a b : \u2115) [decidable_eq : \u2115] {c : \u2115 \u2192 list \u2115}\n\n-- #where\nrun_parser_from_command NONE test_output_3\n\ninclude a c\n\n-- #where\nrun_parser_from_command NONE test_output_4\n\nend b1\n\nnamespace a\n\nvariables (a b : \u2115) [decidable_eq : \u2115] {c : \u2115 \u2192 list \u2115}\ninclude a c\nopen nat list\n\n-- #where\nrun_parser_from_command NONE test_output_5\n\nnamespace b\n\n-- #where\nrun_parser_from_command NONE test_output_6\n\nend b\n\nend a\n\n\n\n\n\n-- TEST: `lean.parser.get_current_namespace`\n\n-- Check no namespace\nmeta def test_no_namespace : lean.parser unit :=\ndo ns \u2190 lean.parser.get_current_namespace,\n   assert_name_eq ns name.anonymous,\n   return ()\n\nrun_parser_from_command NONE test_no_namespace\nrun_parser_from_tactic  NONE test_no_namespace\n\nsection a1\n\nopen nat list\n\n-- Check no namespace with opens\nmeta def test_no_namespace_w_opens : lean.parser unit :=\ndo ns \u2190 lean.parser.get_current_namespace,\n   assert_name_eq ns name.anonymous,\n   return ()\n\nrun_parser_from_command NONE test_no_namespace_w_opens\nrun_parser_from_tactic  NONE test_no_namespace_w_opens\n\nend a1\n\nnamespace test1\n\n-- Check a namespace\nmeta def test_1 : lean.parser unit :=\ndo ns \u2190 lean.parser.get_current_namespace,\n   assert_name_eq ns `test1,\n   return ()\n\nopen nat list\n\n-- Check a 2 namespaces with opens\nmeta def test_2 : lean.parser unit :=\ndo ns \u2190 lean.parser.get_current_namespace,\n   assert_name_eq ns `test1,\n   return ()\n\nend test1\n\nrun_parser_from_command test1 test_1\nrun_parser_from_command test1 test_2\nrun_parser_from_tactic  test1 test_1\nrun_parser_from_tactic  test1 test_2\n\nnamespace test1.test2\n\n-- Check a 2 namespaces\nmeta def test_1 : lean.parser unit :=\ndo ns \u2190 lean.parser.get_current_namespace,\n   assert_name_eq ns `test1.test2,\n   return ()\n\nopen nat list\n\n-- Check a 2 namespaces with opens\nmeta def test_2 : lean.parser unit :=\ndo ns \u2190 lean.parser.get_current_namespace,\n   assert_name_eq ns `test1.test2,\n   return ()\n\nend test1.test2\n\nrun_parser_from_command test1.test2 test_1\nrun_parser_from_command test1.test2 test_2\nrun_parser_from_tactic  test1.test2 test_1\nrun_parser_from_tactic  test1.test2 test_2\n\n\n\n\n\n\n-- TEST: `lean.parser.get_variables` and `lean.parser.get_included_variables`\n\n-- Check no variables\nmeta def test_no_variables : lean.parser unit :=\ndo ns \u2190 lean.parser.get_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [],\n   return ()\n\nrun_parser_from_command NONE test_no_variables\nrun_parser_from_tactic  NONE test_no_variables\n\nsection a1\n\nvariables (a : \u2115)\n\n-- Check 1 variable from command\nmeta def test_1_variable_from_command : lean.parser unit :=\ndo ns \u2190 lean.parser.get_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [`a],\n   return ()\n\nrun_parser_from_command NONE test_1_variable_from_command\n\n-- Check 1 variable from tactic\nmeta def test_1_variable_from_tactic : lean.parser unit :=\ndo ns \u2190 lean.parser.get_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [],\n   return ()\n\nrun_parser_from_tactic  NONE test_1_variable_from_tactic\n\nend a1\n\nnamespace a2\n\nvariables (a : \u2115)\n\n-- Check 1 variable from command inside namespace\nmeta def test_1_variable_from_command : lean.parser unit :=\ndo ns \u2190 lean.parser.get_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [`a],\n   return ()\n\nrun_parser_from_command NONE test_1_variable_from_command\n\n-- Check 1 variable from tactic inside namespace\nmeta def test_1_variable_from_tactic : lean.parser unit :=\ndo ns \u2190 lean.parser.get_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [],\n   return ()\n\nrun_parser_from_tactic NONE test_1_variable_from_tactic\n\nend a2\n\nsection a3\n\n-- Check 3 variables with 1 include\nmeta def test_2_variable_from_command : lean.parser unit :=\ndo ns \u2190 lean.parser.get_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [`a, `b, `c],\n   ns \u2190 lean.parser.get_included_variables,\n   assert_list_noorder_eq (ns.map prod.fst) [`b],\n   return ()\n\nvariables (a b c : \u2115)\ninclude b\n\nrun_parser_from_command NONE test_2_variable_from_command\n\nend a3\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/where.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.180106646483037, "lm_q2_score": 0.06465348970791009, "lm_q1q2_score": 0.011644523214717234}}
{"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 \u2192 Trigger net\n  | .action a => .action \u27e8reactor, reaction.subAS.coe a\u27e9\n  | .timer t  => .timer \u27e8reactor, reaction.eqTimers \u25b8 t\u27e9\n  | .startup  => .startup\n  | .shutdown => .shutdown\n  | .port p =>\n    match reaction.subPS.coe p with\n    | .inl input =>\n      (.port (kind := .input) \u27e8reactor, input\u27e9)\n    | .inr \u27e8c, output\u27e9 =>\n      (.port (kind := .output) \u27e8reactor.extend c, cast (by rw [Path.extend_class]) output\u27e9)\n\ninductive Trigger.Equiv {reactor : ReactorId net} {reaction : Reaction reactor.class} :\n  (Trigger net) \u2192 reaction.val.triggerType \u2192 Prop\n  | action :   Equiv (.action \u27e8reactor, reaction.subAS.coe a\u27e9) (.action a)\n  | timer :    Equiv (.timer \u27e8reactor, reaction.eqTimers \u25b8 t\u27e9) (.timer t)\n  | startup :  Equiv .startup .startup\n  | shutdown : Equiv .shutdown .shutdown\n  | input :\n    (reaction.subPS.coe p = .inl input) \u2192\n    Equiv (.port (kind := .input) \u27e8reactor, input\u27e9) (.port p)\n  | output :\n    (reaction.subPS.coe p = .inr \u27e8c, output\u27e9) \u2192\n    Equiv (.port (kind := .output) \u27e8reactor.extend c, cast (by rw [Path.extend_class]) output\u27e9) (.port p)\n\ninfix:50 \" \u2261 \" => Trigger.Equiv\n\ntheorem Trigger.Equiv.lift\n  {reactor : ReactorId net} {reaction : Reaction reactor.class} (t : reaction.val.triggerType) :\n  Trigger.lift t \u2261 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) \u2192 Prop\n  | port     : (exec.portIsPresent p)       \u2192 Activates _ (.port p)\n  | action   : (exec.actionIsPresent a)     \u2192 Activates _ (.action a)\n  | timer    : (exec.timer t |>.isFiring)   \u2192 Activates _ (.timer t)\n  | startup  : (exec.isStartingUp)          \u2192 Activates _ .startup\n  | shutdown : (exec.state = .shuttingDown) \u2192 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 \u2261 t') (mem : t' \u2208 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 \u00b7)\nwhere\n  activated : reaction.val.triggerType \u2192 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 \u25b8 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 \u2261 .port p') \u2192\n  ((Activates exec <| .port p) \u2194 (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 \u27e8c, output\u27e9 := sub\n      simp at output \u22a2\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 \u27e8v, hv\u27e9 := 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 \u2261 t') \u2192 (Activates exec t \u2194 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) \u2194 (exec.triggers reaction) := by\n  unfold triggers\n  constructor\n  case mp =>\n    intro \u27e8equiv, mem, active\u27e9\n    rw [Array.any_iff_mem_where]\n    refine \u27e8_, mem, ?_\u27e9\n    exact Activates.iff_equiv_trigger_activated equiv |>.mp active\n  case mpr =>\n    intro h\n    have \u27e8t', mem, active\u27e9 := Array.any_iff_mem_where.mp h\n    have \u27e8_, equiv\u27e9 : \u2203 t, t \u2261 t' := \u27e8_, Reaction.Trigger.Equiv.lift t'\u27e9\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 \u2192 q) \u2227 r := by\n  refine \u27e8?a, ?b\u27e9\n\nexample : (p \u2192 q) \u2227 r := by\n  refine \u27e8fun h => ?a, ?b\u27e9\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": "import Std.Data.AssocList\n\nimport LeanSat.Data.Sexp\nimport LeanSat.Dsl.Sexp\n\ndef argsCvc4 : IO.Process.SpawnArgs := {\n  cmd := \"cvc4\"\n  args := #[\"--lang\", \"smt\", \"/tmp/temp.smt\"] }\n\ndef argsCvc5 : IO.Process.SpawnArgs := {\n  cmd := \"cvc5\"\n  args := #[\"--lang\", \"smt\", \"/tmp/temp.smt\"] }\n\ndef argsZ3 : IO.Process.SpawnArgs := {\n  cmd := \"z3/bin/z3\"\n  args := #[\"-smt2\", \"/tmp/temp.smt\"] }\n\ndef argsBoolector : IO.Process.SpawnArgs := {\n  cmd := \"boolector\"\n  args := #[\"--smt2\", \"/tmp/temp.smt\"] }\n\n-- Same as IO.Process.run, but does not require exitcode = 0\ndef run' (args : IO.Process.SpawnArgs) : IO String := do\n  let out \u2190 IO.Process.output args\n  pure out.stdout\n\n/-- Executes the solver with the provided list of commands in SMT-LIB s-expression format.\nReturns the solver output as s-expressions. -/\ndef callSolver (args : IO.Process.SpawnArgs) (commands : List Sexp) (verbose : Bool := false)\n    : IO (List Sexp) := do\n  let cmdStr := Sexp.serializeMany commands\n  if verbose then\n    IO.println \"Sending SMT-LIB problem:\"\n    IO.println cmdStr\n  IO.FS.writeFile \"/tmp/temp.smt\" cmdStr\n  let out \u2190 run' args\n  if verbose then\n    IO.println \"\\nSolver replied:\"\n    IO.println out\n  let out \u2190 IO.ofExcept (Sexp.parse out)\n  return out\n\ndef callCvc4 := @callSolver argsCvc4\ndef callCvc5 := @callSolver argsCvc5\ndef callZ3 := @callSolver argsZ3\ndef callBoolector := @callSolver argsBoolector\n\nprivate def hexdigits : Array Char :=\n  #[ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ]\n\ndef enhexByte (x : UInt8) : String :=\n  \u27e8[hexdigits.get! $ UInt8.toNat $ (x.land 0xf0).shiftRight 4,\n    hexdigits.get! $ UInt8.toNat $ x.land 0xf ]\u27e9\n\n/-- Convert a little-endian (LSB first) list of bytes to hexadecimal. -/\ndef enhexLE : List UInt8 \u2192 String\n  | [] => \"\"\n  | b::bs => enhexLE bs ++ enhexByte b\n\n/-- Converts a number `n` to its hexadecimal SMT-LIB representation as a `nBits`-bit vector.\nFor example `toBVConst 32 0xf == \"#x0000000f\"`. -/\ndef toBVConst (nBits : Nat) (n : Nat) : String :=\n  assert! nBits % 8 == 0\n  let nBytes := nBits/8\n  let bytes := List.range nBytes |>.map fun i => UInt8.ofNat ((n >>> (i*8)) &&& 0xff)\n  \"#x\" ++ enhexLE bytes\n\nopen Std (AssocList)\n\n/-- Extracts constants assigned in a model returned from an SMT solver.\nThe model is expected to be a single s-expression representing a list,\nwith constant expressions represented by `(define-fun <name> () <type> <body>)`. -/\ndef decodeModelConsts : Sexp \u2192 AssocList String Sexp\n  | Sexp.expr ss =>\n    ss.foldl (init := AssocList.empty) fun\n      | acc, sexp!{(define-fun {Sexp.atom x} () {_} {body})} =>\n        acc.insert x body\n      | acc, _ => acc\n  | _ => AssocList.empty\n\n/-- Evaluates an SMT-LIB constant numeral such as `0` or `#b01` or `#x02`. -/\ndef evalNumConst : Sexp \u2192 Option Nat\n  | Sexp.atom s =>\n    let s' :=\n      if s.startsWith \"#b\" then \"0\" ++ s.drop 1\n      else if s.startsWith \"#x\" then \"0\" ++ s.drop 1\n      else s\n    Lean.Syntax.decodeNatLitVal? s'\n  | Sexp.expr _ => none", "meta": {"author": "Vtec234", "repo": "lean-sat", "sha": "b4f72c4a34726f8eb445edcdd1716aa47955da10", "save_path": "github-repos/lean/Vtec234-lean-sat", "path": "github-repos/lean/Vtec234-lean-sat/lean-sat-b4f72c4a34726f8eb445edcdd1716aa47955da10/LeanSat/Playground/SmtSolvers.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.310694383214554, "lm_q2_score": 0.037326887879581695, "lm_q1q2_score": 0.011597254407065447}}
{"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) \u2192 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 := \u27e8(\u00b7.toString)\u27e9\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 \u2192 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\u2081 A\u2082 A\u2083 : Type*} [category A\u2081] [preadditive A\u2081] [has_finite_biproducts A\u2081]\n  [category A\u2082] [preadditive A\u2082] --[has_finite_biproducts A\u2082]\n  [category A\u2083] [preadditive A\u2083] --[has_finite_biproducts A\u2083]\n\nnamespace universal_map\n\nvariables {m n : \u2115} (f : universal_map m n)\n\ndef eval_Pow' (F : A\u2081 \u2964 A\u2082) : universal_map m n \u2192+ (Pow m \u22d9 F \u27f6 Pow n \u22d9 F) :=\nfree_abelian_group.lift $ \u03bb g : basic_universal_map m n, whisker_right g.eval_Pow F\n\n@[simp]\nlemma eval_Pow'_of (F : A\u2081 \u2964 A\u2082) (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\u2081 \u2964 A\u2082) (H : A\u2082 \u2964 A\u2083) [H.additive] :\n  eval_Pow' F f \u25eb \ud835\udfd9 H = eval_Pow' (F \u22d9 H) f :=\nbegin\n  revert f,\n  let \u03c6 : universal_map m n \u2192+ ((Pow m \u22d9 F) \u22d9 H \u27f6 (Pow n \u22d9 F) \u22d9 H) :=\n  { to_fun := \u03bb 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' := \u03bb f\u2081 f\u2082, by { ext, dsimp, simp only [map_add, nat_trans.app_add,\n      functor.map_add], }, },\n  suffices : \u03c6 = eval_Pow' (F \u22d9 H),\n  { intro f,\n    change \ud835\udfd9 _ \u226b \u03c6 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\u2081 \u2964 A\u2082) (H : A\u2082 \u2964 A\u2083) [H.additive] (M\u2081 : A\u2081) :\n  H.map ((eval_Pow' F f).app M\u2081) = (eval_Pow' (F \u22d9 H) f).app M\u2081 :=\nby simpa only [nat_trans.hcomp_id_app] using nat_trans.congr_app (f.eval_Pow'_hcomp F H) M\u2081\n\nlemma map_eval_Pow (F : A\u2081 \u2964 A\u2081) (H : A\u2081 \u2964 A\u2082) [H.additive] (M\u2081 : A\u2081) :\n  H.map ((eval_Pow F f).app M\u2081) = (eval_Pow' (F \u22d9 H) f).app M\u2081 :=\nmap_eval_Pow' f F H M\u2081\n\n@[reassoc]\nlemma congr_eval_Pow' {F F' : A\u2081 \u2964 A\u2082} (\u03c6 : F \u27f6 F') (M\u2081 : A\u2081) :\n  (eval_Pow' F f).app M\u2081 \u226b \u03c6.app ((Pow n).obj M\u2081) =\n  \u03c6.app ((Pow m).obj M\u2081) \u226b (eval_Pow' F' f).app M\u2081 :=\nbegin\n  revert f,\n  let \u03c6\u2081 : universal_map m n \u2192+ ((Pow m \u22d9 F).obj M\u2081 \u27f6 (Pow n \u22d9 F').obj M\u2081) :=\n  { to_fun := \u03bb f, (eval_Pow' F f).app M\u2081 \u226b \u03c6.app ((Pow n).obj M\u2081),\n    map_zero' := by simp only [map_zero, nat_trans.app_zero, zero_comp],\n    map_add' := \u03bb f\u2081 f\u2082, by simp only [map_add, nat_trans.app_add, add_comp], },\n  let \u03c6\u2082 : universal_map m n \u2192+ ((Pow m \u22d9 F).obj M\u2081 \u27f6 (Pow n \u22d9 F').obj M\u2081) :=\n  { to_fun := \u03bb f, \u03c6.app ((Pow m).obj M\u2081) \u226b (eval_Pow' F' f).app M\u2081,\n    map_zero' := by simp only [map_zero, nat_trans.app_zero, comp_zero],\n    map_add' := \u03bb f\u2081 f\u2082, by simp only [map_add, nat_trans.app_add, comp_add], },\n  suffices : \u03c6\u2081 = \u03c6\u2082,\n  { intro f,\n    change \u03c6\u2081 f = \u03c6\u2082 f,\n    rw this, },\n  ext,\n  dsimp only [\u03c6\u2081, \u03c6\u2082],\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": "import Lean.Data.Json\nopen Lean\n\nderiving instance BEq for Except\n\nexample : Json.parse \"\\\"\\\\u7406\\\\u79d1\\\"\" == .ok \"\u7406\u79d1\" := by native_decide\nexample : Json.parse \"\\\"\\\\u7406\\\\u79D1\\\"\" == .ok \"\u7406\u79d1\" := by native_decide\n\nexample : Json.pretty \"\\x0b\" == \"\\\"\\\\u000b\\\"\" := by native_decide\nexample : Json.pretty \"\\x1b\" == \"\\\"\\\\u001b\\\"\" := by native_decide\nexample : Json.parse \"\\\"\\\\u000b\\\"\" == .ok \"\\x0b\" := by native_decide\nexample : Json.parse \"\\\"\\\\u001b\\\"\" == .ok \"\\x1b\" := by native_decide\nexample : Json.parse \"\\\"\\\\u000B\\\"\" == .ok \"\\x0b\" := by native_decide\nexample : Json.parse \"\\\"\\\\u001B\\\"\" == .ok \"\\x1b\" := by native_decide\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/1985.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284182582255894, "lm_q2_score": 0.044018648608834615, "lm_q1q2_score": 0.011569941970587734}}
{"text": "import Qpf.Qpf\n\nnamespace Macro\n  open Lean Meta Elab Term\n  open Elab.Command (CommandElabM)\n\n  open Lean.Parser.Term (binderIdent bracketedBinder)\n\n  initialize\n    registerTraceClass `QPF\n\n\n  def elabCommand' (stx : TSyntax `command) : CommandElabM Unit := do\n    trace[QPF] \"CUSTOM ELABCOMMAND\"\n    try\n      Elab.Command.elabCommand stx\n    catch e =>\n      throwError \"{e.toMessageData}\\n\\n Error thrown while elaborating:\\n\\n {stx}\"\n\n\n  variable [MonadControlT MetaM n] [Monad n] [MonadLiftT MetaM n] \n            [MonadError n] [MonadLog n] [AddMessageContext n]\n            [MonadQuotation n] [MonadTrace n] [MonadOptions n]\n            [MonadLiftT IO n]\n\n\n\n  /--\n    Takes an expression `e` of type `CurriedTypeFun n` and returns an expression of type `TypeFun n`\n    representing the uncurried version of `e`.\n    Tries to prevent unneccesary `ofCurried / curried` roundtrips\n  -/\n  def uncurry (F : Expr) (arity : Option Expr := none) : n Expr := do\n    mkAppOptM ``TypeFun.ofCurried #[arity, some F]\n\n    --\n    -- Although preventing unneccesary `ofCurried / curried` roundtrips seems like a good idea,\n    -- leaving them in actually causes more definitional equality (e.g., in the `_02_Tree` example)\n    --\n\n    -- let n       \u2190 mkFreshExprMVar (mkConst ``Nat)\n    -- let F_inner \u2190 mkFreshExprMVar (kind:=MetavarKind.synthetic) none\n    -- let us      \u2190 mkFreshLevelMVars 2\n    -- let app     := mkApp2 (mkConst ``TypeFun.curried us) n F_inner\n    \n    -- trace[QPF] \"\\nChecking defEq of {F} and {app}\"\n    -- if (\u2190isDefEq F app) then\n    --   if let some F' :=  (\u2190 getExprMVarAssignment? F_inner.mvarId!) then\n    --     trace[QPF] \"yes: {F'}\"\n    --     return F'\n    \n    -- trace[QPF] \"no\"\n    -- mkAppM ``TypeFun.ofCurried #[F]\n\n  \n\n  def withLiveBinders [Inhabited \u03b1]\n                  (binders : Array Syntax) \n                  (f : Array Expr \u2192 n \u03b1) : n \u03b1\n  := do\n    let u := mkLevelSucc <|\u2190 mkFreshLevelMVar;\n    let decls := binders.map fun \u03b1 => (\n      \u03b1.getId, \n      fun _ => pure (mkSort u)\n    )\n\n    withLocalDeclsD decls f\n\n\n  \n  /--\n    Takes an array of bracketed binders, and allocate a fresh identifier for each hole in the binders.\n    Returns a pair of the binder syntax with all holes replaced, and an array of all bound identifiers,\n    both pre-existing and newly created\n  -/\n  def mkFreshNamesForBinderHoles (binders : Array Syntax) : \n      n ((TSyntaxArray ``bracketedBinder) \u00d7 (Array Ident)) \n  := do\n    let mut bindersNoHoles := #[]\n    let mut binderNames := #[]\n  \n    for stx in binders do\n      let mut newArgStx := Syntax.missing\n      let kind := stx.getKind\n\n      if kind == ``Lean.Parser.Term.instBinder then\n        if stx[1].isNone then\n          throwErrorAt stx \"Instances without names are not supported yet\"\n          -- let id := mkIdentFrom stx (\u2190 mkFreshBinderName)\n          -- binderNames := binderNames.push id\n          -- newArgStx := stx[1].setArgs #[id, Syntax.atom SourceInfo.none \":\"]\n        else    \n          trace[QPF] stx[1]\n          let id := stx[1][0]\n          binderNames := binderNames.push \u27e8id\u27e9\n          newArgStx := stx[1]\n\n      else\n        -- replace each hole with a fresh id\n        let ids \u2190 stx[1].getArgs.mapM fun (id : Syntax) => do\n          trace[QPF] \"{id}\"\n          let kind := id.getKind\n          if kind == identKind then\n            return id\n          else if kind == ``Lean.Parser.Term.hole then\n            return mkIdentFrom id (\u2190 mkFreshBinderName)\n          else \n            throwErrorAt id \"identifier or `_` expected, found {kind}\"\n            \n        for id in ids do\n          binderNames := binderNames.push \u27e8id\u27e9 \n        newArgStx := stx[1].setArgs ids\n\n      let newStx := stx.setArg 1 newArgStx\n      bindersNoHoles := bindersNoHoles.push \u27e8newStx\u27e9\n\n    return (bindersNoHoles, binderNames)\n\n\n  inductive BinderKind\n    | explicit\n    | implicit\n    | ident\n    deriving DecidableEq, BEq, Inhabited\n\n\n  open Lean.Parser.Term (explicitBinder implicitBinder) in\n  /-- Parse a `BinderKind` from a `SyntaxNodeKind` -/\n  def BinderKind.ofSyntaxKind (kind : SyntaxNodeKind) : BinderKind :=\n    if kind == ``implicitBinder then\n          .implicit\n        else if kind == ``Lean.binderIdent \n                || kind == ``Lean.Parser.Term.binderIdent \n                || kind == ``Lean.Parser.Term.ident\n                || kind == ``Lean.Parser.ident\n                -- HACK: this one should be just a single backquote  \n                || kind == `ident \n                then\n          .ident\n        else if kind == ``explicitBinder then\n          .explicit\n        else\n          panic s!\"Bug: unexpected binder kind `{kind}\"\n\n\n  open Lean.Parser.Term in\n  /--\n    Takes a list of binders, and split it into live and dead binders, respectively.\n    For the live binders, return an array of with syntax of kind `binderIdent`, unwrapping \n    `simpleBinder` nodes if needed (while asserting that there were no type annotations)\n  -/\n  def splitLiveAndDeadBinders (binders : Array Syntax) \n      : n (TSyntaxArray ``Lean.Parser.Term.binderIdent \u00d7 TSyntaxArray ``bracketedBinder) := do\n    let mut liveVars := #[]\n    let mut deadBinders := #[]\n\n    let mut isLive := false\n    for binder in binders do\n      let kind := BinderKind.ofSyntaxKind binder.getKind\n\n      if kind == .ident then\n        isLive := true\n        liveVars := liveVars.push \u27e8binder\u27e9 \n\n      -- else if kind == .explicit then\n      --   isLive := true\n      --   for id in binder[0].getArgs do\n      --     liveVars := liveVars.push id\n\n      --   if !binder[1].isNone then\n      --     trace[QPF] binder[1]\n      --     throwErrorAt binder \"live variable may not have a type annotation.\\nEither add brackets to mark the variable as dead, or remove the type\"\n\n      else if isLive then\n        throwErrorAt binder f!\"Unexpected bracketed binder, dead arguments must precede all live arguments.\\nPlease reorder your arguments or mark this binder as live by removing brackets and/or type ascriptions\"\n\n      else \n        deadBinders := deadBinders.push \u27e8binder\u27e9\n\n    return (liveVars, deadBinders)\n\n\n\n  \n\n  \n  /--\n    Takes a list of binders, and returns an array of just the bound identifiers, \n    for use in applications\n  -/\n  def getBinderIdents (binders : Array Syntax) (includeImplicits := true) \n    : Array Term := \n  Id.run do\n    let mut idents : Array Term := #[]\n\n    for binder in binders do\n      let kind := BinderKind.ofSyntaxKind binder.getKind\n        \n      if kind == .implicit && !includeImplicits then\n        continue\n\n      else if kind == .ident then\n        idents := idents.push \u27e8binder\u27e9 \n\n      else \n        for id in binder[1].getArgs do\n          idents := idents.push \u27e8id\u27e9 \n        \n\n    -- dbg_trace \"idents = {idents}\"\n    pure idents\n\n\n\n\nopen Parser.Command in\ninstance : Quote Modifiers (k := ``declModifiers) where\n  quote mod :=\n    let isNoncomputable : Syntax := \n      if mod.isNoncomputable then \n        mkNode ``\u00abnoncomputable\u00bb #[mkAtom \"noncomputable \"]\n      else \n        mkNullNode\n\n    let visibility := match mod.visibility with\n      | .regular     => mkNullNode\n      | .\u00abprotected\u00bb => mkNode ``\u00abprotected\u00bb #[mkAtom \"protected \"]\n      | .\u00abprivate\u00bb   => mkNode ``\u00abprivate\u00bb #[mkAtom \"private \"]\n\n    mkNode ``declModifiers #[\n      mkNullNode, -- docComment\n      mkNullNode, -- Term.attributes\n      visibility, -- visibility\n      isNoncomputable, -- isNoncomputable\n      mkNullNode, -- unsafe\n      mkNullNode  -- partial / nonrec\n    ]\n\n  \n  -- open Lean.Parser.Term in\n  -- elab \"#dbg_syntax \" t:term : command => do\n  --   dbg_trace t\n\n    \n  -- open Lean.Parser.Term Elab.Command in\n  -- elab \"#dbg_expr \" t:term : command => do\n  --   let expr \u2190 liftTermElabM none $ elabTerm t none\n  --   dbg_trace expr\n  --   dbg_trace expr.isForall\n\n  -- #dbg_expr (Nat \u2192 Int)\n\nend Macro\n\n\n-- set_option pp.raw true\n\n-- open Lean in \n-- elab \"#dbg_ident\" id:binderIdent : command => do\n--   dbg_trace \"{id}\"\n--   let id := id.raw\n--   dbg_trace \"kind: {id.getKind}\"\n--   dbg_trace \"args: {id.getArgs}\"\n--   dbg_trace \"args[0].getKind: {id.getArgs[0]!.getKind}\"\n\n-- #dbg_ident x \n-- #dbg_ident _ \n\n-- example : ``Lean.binderIdent = ``Lean.Parser.Term.binderIdent := \n--   by rfl", "meta": {"author": "alexkeizer", "repo": "qpf4", "sha": "980f97425b9d5a5e3897073df33794192b3b3124", "save_path": "github-repos/lean/alexkeizer-qpf4", "path": "github-repos/lean/alexkeizer-qpf4/qpf4-980f97425b9d5a5e3897073df33794192b3b3124/Qpf/Macro/Common.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30074557894124154, "lm_q2_score": 0.03846619091603939, "lm_q1q2_score": 0.011568536856708592}}
{"text": "import Architectural.ArchWithContracts\nimport Architectural.proofObligations\n\n@[derive [fintype, decidable_eq]]\ninductive PORTS\n| fault_LAAPRequest_LACU\n| fault_armPositionAngle1_LACU\n| fault_LAAPSetpoint_LAAP\n| fault_lockingSwitchPosition_LACU\n| fault_LAAPRequest_LAAP\n| fault_operatorControlLever_LAAP\n| fault_operatorControlLever_LACU\n| fault_LAAPFlow_armController\n| fault_groundSpeed_LACU\n| fault_armDeactivated_armController\n| fault_input1_armPosition\n| fault_output_armPosition\n| fault_LAAPFlow_LAAP\n| fault_armPositionAngle2_LACU\n| fault_armFlow_armController\n| fault_LAAPActive_LAAP\n| fault_groundSpeed_armController\n| fault_operatorConstrolLever_armController\n| fault_LAAPSetpoint_LACU\n| fault_PWMFlow_LACU\n| fault_angleSensor_armController\n| fault_input2_armPosition\n| fault_LAAPActive_armController\n| fault_angleSensor_LAAP\n| fault_groundSpeed_LAAP\nopen PORTS\n\ndef LAAP : Component PORTS := {\n  ports := \n    \u27e8\n      [fault_angleSensor_LAAP,\n        fault_LAAPRequest_LAAP,\n        fault_LAAPSetpoint_LAAP,\n        fault_operatorControlLever_LAAP,\n        fault_groundSpeed_LAAP,\n        fault_LAAPFlow_LAAP,\n      fault_LAAPActive_LAAP]\n    ,\n    by {dec_trivial}\u27e9\n  }\n\n@[reducible]\ndef LACU : Component PORTS := {\n  ports := {\n    val := [\n      fault_armPositionAngle1_LACU,\n      fault_armPositionAngle2_LACU,\n      fault_LAAPRequest_LACU,\n      fault_LAAPSetpoint_LACU,\n      fault_operatorControlLever_LACU,\n      fault_groundSpeed_LACU,\n      fault_lockingSwitchPosition_LACU,\n      fault_PWMFlow_LACU\n    ],\n    nodup := by {dec_trivial}\n  }\n}\n\n@[reducible]\ndef armPosition : Component PORTS := {\n  ports := {\n    val := [\n      fault_input1_armPosition,\n      fault_input2_armPosition,\n      fault_output_armPosition\n    ],\n    nodup := by {dec_trivial}\n  }\n}\n\n@[reducible]\ndef armController : Component PORTS := {\n  ports := {\n    val := [\n      fault_angleSensor_armController,\n      fault_LAAPFlow_armController,\n      fault_LAAPActive_armController,\n      fault_operatorConstrolLever_armController,\n      fault_groundSpeed_armController,\n      fault_armDeactivated_armController,\n      fault_armFlow_armController\n    ],\n    nodup := by {dec_trivial}\n  }\n}\n\n@[reducible]\ndef LACU_ARCH_MODEL : Architecture LACU := \n{\n  subs := [\n    armPosition,\n    LAAP,\n    armController\n  ],\n  delegation := \n  [\n  (fault_armPositionAngle1_LACU, fault_input1_armPosition), \n  (fault_armPositionAngle2_LACU, fault_input2_armPosition),\n  (fault_PWMFlow_LACU, fault_armFlow_armController),\n  (fault_output_armPosition, fault_angleSensor_LAAP),\n  (fault_output_armPosition, fault_angleSensor_armController),\n  (fault_LAAPRequest_LACU, fault_LAAPRequest_LAAP),\n  (fault_operatorControlLever_LAAP, fault_operatorControlLever_LACU),\n  (fault_LAAPActive_armController, fault_LAAPActive_LAAP),\n  (fault_LAAPFlow_armController, fault_LAAPFlow_LAAP),\n  (fault_operatorConstrolLever_armController, fault_operatorControlLever_LACU)\n  ]\n}\n\ntheorem distinct_1 : armPosition \u2260 armController := by {exact of_to_bool_ff rfl,}\ntheorem distinct_2 : armPosition \u2260 LAAP := by {exact of_to_bool_ff rfl,}\ntheorem distinct_3 : armController \u2260 LAAP := by {exact of_to_bool_ff rfl,}", "meta": {"author": "loganrjmurphy", "repo": "ForeMoSt", "sha": "c7affc7c8971562520d2775ac48fe4f188f84b02", "save_path": "github-repos/lean/loganrjmurphy-ForeMoSt", "path": "github-repos/lean/loganrjmurphy-ForeMoSt/ForeMoSt-c7affc7c8971562520d2775ac48fe4f188f84b02/src/Architectural/LACU.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.029760092332479712, "lm_q1q2_score": 0.011565307935378357}}
{"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.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.Function\nimport Leanbin.Init.Data.Option.Basic\nimport Leanbin.Init.Util\nimport Leanbin.Init.Control.Combinators\nimport Leanbin.Init.Control.Monad\nimport Leanbin.Init.Control.Alternative\nimport Leanbin.Init.Control.MonadFail\nimport Leanbin.Init.Data.Nat.Div\nimport Leanbin.Init.Meta.Exceptional\nimport Leanbin.Init.Meta.Format\nimport Leanbin.Init.Meta.Environment\nimport Leanbin.Init.Meta.Pexpr\nimport Leanbin.Init.Data.Repr\nimport Leanbin.Init.Data.String.Basic\nimport Leanbin.Init.Meta.InteractionMonad\nimport Leanbin.Init.Classical\n\nopen Native\n\nunsafe axiom tactic_state : Type\n#align tactic_state tactic_state\n\nuniverse u v\n\nnamespace TacticState\n\nunsafe axiom env : tactic_state \u2192 environment\n#align tactic_state.env tactic_state.env\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. -/\nunsafe axiom to_format (s : tactic_state) (target_lhs_only : Bool := false) : format\n#align tactic_state.to_format tactic_state.to_format\n\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. -/\nunsafe axiom format_expr : tactic_state \u2192 expr \u2192 format\n#align tactic_state.format_expr tactic_state.format_expr\n\nunsafe axiom get_options : tactic_state \u2192 options\n#align tactic_state.get_options tactic_state.get_options\n\nunsafe axiom set_options : tactic_state \u2192 options \u2192 tactic_state\n#align tactic_state.set_options tactic_state.set_options\n\nend TacticState\n\nunsafe instance : has_to_format tactic_state :=\n  \u27e8tactic_state.to_format\u27e9\n\nunsafe instance : ToString tactic_state :=\n  \u27e8fun s => (to_fmt s).toString s.get_options\u27e9\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-/\n@[reducible]\nunsafe def tactic :=\n  interaction_monad tactic_state\n#align tactic tactic\n\n@[reducible]\nunsafe def tactic_result :=\n  interaction_monad.result tactic_state\n#align tactic_result tactic_result\n\nnamespace Tactic\n\nexport\n  InteractionMonad (result result.success result.exception result.cases_on result_to_string mk_exception silent_fail orelse' bracket)\n\n/-- Cause the tactic to fail with no error message. -/\nunsafe def failed {\u03b1 : Type} : tactic \u03b1 :=\n  interaction_monad.failed\n#align tactic.failed tactic.failed\n\nunsafe def fail {\u03b1 : Type u} {\u03b2 : Type v} [has_to_format \u03b2] (msg : \u03b2) : tactic \u03b1 :=\n  interaction_monad.fail msg\n#align tactic.fail tactic.fail\n\nend Tactic\n\nnamespace TacticResult\n\nexport InteractionMonad.Result ()\n\nend TacticResult\n\nopen Tactic\n\nopen TacticResult\n\n-- mathport name: \u00abexpr >>=[tactic] \u00bb\ninfixl:2 \" >>=[tactic] \" => interaction_monad_bind\n\n-- mathport name: \u00abexpr >>[tactic] \u00bb\ninfixl:2 \" >>[tactic] \" => interaction_monad_seq\n\nunsafe instance : Alternative tactic :=\n  { interaction_monad.monad with\n    failure := @interaction_monad.failed _\n    orelse := @interaction_monad_orelse _ }\n\nunsafe def tactic.up.{u\u2081, u\u2082} {\u03b1 : Type u\u2082} (t : tactic \u03b1) : tactic (ULift.{u\u2081} \u03b1) := fun s =>\n  match t s with\n  | success a s' => success (ULift.up a) s'\n  | exception t ref s => exception t ref s\n#align tactic.up tactic.up\n\nunsafe def tactic.down.{u\u2081, u\u2082} {\u03b1 : Type u\u2082} (t : tactic (ULift.{u\u2081} \u03b1)) : tactic \u03b1 := fun s =>\n  match t s with\n  | success (ULift.up a) s' => success a s'\n  | exception t ref s => exception t ref s\n#align tactic.down tactic.down\n\nnamespace Interactive\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 \u03b1` 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-/\nunsafe class executor (m : Type \u2192 Type u) [Monad m] where\n  config_type : Type\n  [Inhabited : Inhabited config_type]\n  execute_with : config_type \u2192 m Unit \u2192 tactic Unit\n#align interactive.executor interactive.executor\n\nattribute [inline] executor.execute_with\n\n@[inline]\nunsafe def executor.execute_explicit (m : Type \u2192 Type u) [Monad m] [e : executor m] :\n    m Unit \u2192 tactic Unit :=\n  executor.execute_with e.Inhabited.default\n#align interactive.executor.execute_explicit interactive.executor.execute_explicit\n\n@[inline]\nunsafe def executor.execute_with_explicit (m : Type \u2192 Type u) [Monad m] [executor m] :\n    executor.config_type m \u2192 m Unit \u2192 tactic Unit :=\n  executor.execute_with\n#align interactive.executor.execute_with_explicit interactive.executor.execute_with_explicit\n\n/-- Default `executor` instance for `tactic`s themselves -/\nunsafe instance executor_tactic : executor tactic\n    where\n  config_type := Unit\n  Inhabited := \u27e8()\u27e9\n  execute_with _ := id\n#align interactive.executor_tactic interactive.executor_tactic\n\nend Interactive\n\nnamespace Tactic\n\nopen InteractionMonad.Result\n\nvariable {\u03b1 : Type u}\n\n/-- Does nothing. -/\nunsafe def skip : tactic Unit :=\n  success ()\n#align tactic.skip tactic.skip\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-/\nunsafe def try_core (t : tactic \u03b1) : tactic (Option \u03b1) := fun s =>\n  match t s with\n  | exception _ _ _ => success none s\n  | success a s' => success (some a) s'\n#align tactic.try_core tactic.try_core\n\n/-- `try t` acts like `t`, but succeeds even if `t` fails.\n-/\nunsafe def try (t : tactic \u03b1) : tactic Unit := fun s =>\n  match t s with\n  | exception _ _ _ => success () s\n  | success _ s' => success () s'\n#align tactic.try tactic.try\n\nunsafe def try_lst : List (tactic Unit) \u2192 tactic Unit\n  | [] => failed\n  | tac :: tacs => fun s =>\n    match tac s with\n    | success _ s' => try (try_lst tacs) s'\n    | exception e p s' =>\n      match try_lst tacs s' with\n      | exception _ _ _ => exception e p s'\n      | r => r\n#align tactic.try_lst tactic.try_lst\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-/\nunsafe def fail_if_success {\u03b1 : Type u} (t : tactic \u03b1) : tactic Unit := fun s =>\n  match t s with\n  | success a s => mk_exception \"fail_if_success combinator failed, given tactic succeeded\" none s\n  | exception _ _ _ => success () s\n#align tactic.fail_if_success tactic.fail_if_success\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-/\nunsafe def success_if_fail {\u03b1 : Type u} (t : tactic \u03b1) : tactic Unit := fun s =>\n  match t s with\n  | success a s => mk_exception \"success_if_fail combinator failed, given tactic succeeded\" none s\n  | exception _ _ _ => success () s\n#align tactic.success_if_fail tactic.success_if_fail\n\nopen Nat\n\n/-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the\nresult of each successful iteration.\n-/\nunsafe def iterate_at_most : Nat \u2192 tactic \u03b1 \u2192 tactic (List \u03b1)\n  | 0, t => pure []\n  | n + 1, t => do\n    let some a \u2190 try_core t |\n      pure []\n    let as \u2190 iterate_at_most n t\n    pure <| a :: as\n#align tactic.iterate_at_most tactic.iterate_at_most\n\n/-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails.\n-/\nunsafe def iterate_at_most' : Nat \u2192 tactic Unit \u2192 tactic Unit\n  | 0, t => skip\n  | succ n, t => do\n    let some _ \u2190 try_core t |\n      skip\n    iterate_at_most' n t\n#align tactic.iterate_at_most' tactic.iterate_at_most'\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-/\nunsafe def iterate_exactly : Nat \u2192 tactic \u03b1 \u2192 tactic (List \u03b1)\n  | 0, t => pure []\n  | n + 1, t => do\n    let a \u2190 t\n    let as \u2190 iterate_exactly n t\n    pure <| a :: as\n#align tactic.iterate_exactly tactic.iterate_exactly\n\n/-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole\ntactic fails.\n-/\nunsafe def iterate_exactly' : Nat \u2192 tactic Unit \u2192 tactic Unit\n  | 0, t => skip\n  | n + 1, t => t *> iterate_exactly' n t\n#align tactic.iterate_exactly' tactic.iterate_exactly'\n\n/-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the\nresult of each iteration.\n-/\nunsafe def iterate : tactic \u03b1 \u2192 tactic (List \u03b1) :=\n  iterate_at_most 100000\n#align tactic.iterate tactic.iterate\n\n/-- `iterate' t` repeats `t` 100.000 times or until `t` fails.\n-/\nunsafe def iterate' : tactic Unit \u2192 tactic Unit :=\n  iterate_at_most' 100000\n#align tactic.iterate' tactic.iterate'\n\nunsafe def returnopt (e : Option \u03b1) : tactic \u03b1 := fun s =>\n  match e with\n  | some a => success a s\n  | none => mk_exception \"failed\" none s\n#align tactic.returnopt tactic.returnopt\n\nunsafe instance opt_to_tac : Coe (Option \u03b1) (tactic \u03b1) :=\n  \u27e8returnopt\u27e9\n#align tactic.opt_to_tac tactic.opt_to_tac\n\n/-- Decorate t's exceptions with msg. -/\nunsafe def decorate_ex (msg : format) (t : tactic \u03b1) : tactic \u03b1 := fun s =>\n  result.cases_on (t s) success fun opt_thunk =>\n    match opt_thunk with\n    | some e => exception (some fun u => msg ++ format.nest 2 (format.line ++ e u))\n    | none => exception none\n#align tactic.decorate_ex tactic.decorate_ex\n\n/-- Set the tactic_state. -/\n@[inline]\nunsafe def write (s' : tactic_state) : tactic Unit := fun s => success () s'\n#align tactic.write tactic.write\n\n/-- Get the tactic_state. -/\n@[inline]\nunsafe def read : tactic tactic_state := fun s => success s s\n#align tactic.read tactic.read\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-/\nunsafe def capture (t : tactic \u03b1) : tactic (tactic_result \u03b1) := fun s =>\n  match t s with\n  | success r s' => success (success r s') s'\n  | exception f p s' => success (exception f p s') s'\n#align tactic.capture tactic.capture\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 \u2190 capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted.\n-/\nunsafe def unwrap {\u03b1 : Type _} (t : tactic_result \u03b1) : tactic \u03b1 :=\n  match t with\n  | success r s' => return r\n  | e => fun s => e\n#align tactic.unwrap tactic.unwrap\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-/\nunsafe def resume {\u03b1 : Type _} (t : tactic_result \u03b1) : tactic \u03b1 := fun s => t\n#align tactic.resume tactic.resume\n\nunsafe def get_options : tactic options := do\n  let s \u2190 read\n  return s\n#align tactic.get_options tactic.get_options\n\nunsafe def set_options (o : options) : tactic Unit := do\n  let s \u2190 read\n  write (s o)\n#align tactic.set_options tactic.set_options\n\nunsafe def save_options {\u03b1 : Type} (t : tactic \u03b1) : tactic \u03b1 := do\n  let o \u2190 get_options\n  let a \u2190 t\n  set_options o\n  return a\n#align tactic.save_options tactic.save_options\n\nunsafe def returnex {\u03b1 : Type} (e : exceptional \u03b1) : tactic \u03b1 := fun s =>\n  match e with\n  | exceptional.success a => success a s\n  | exceptional.exception f =>\n    match get_options s with\n    | success opt _ => exception (some fun u => f opt) none s\n    | exception _ _ _ => exception (some fun u => f options.mk) none s\n#align tactic.returnex tactic.returnex\n\nunsafe instance ex_to_tac {\u03b1 : Type} : Coe (exceptional \u03b1) (tactic \u03b1) :=\n  \u27e8returnex\u27e9\n#align tactic.ex_to_tac tactic.ex_to_tac\n\nend Tactic\n\nunsafe def tactic_format_expr (e : expr) : tactic format := do\n  let s \u2190 tactic.read\n  return (tactic_state.format_expr s e)\n#align tactic_format_expr tactic_format_expr\n\nunsafe class has_to_tactic_format (\u03b1 : Type u) where\n  to_tactic_format : \u03b1 \u2192 tactic format\n#align has_to_tactic_format has_to_tactic_format\n\nunsafe instance : has_to_tactic_format expr :=\n  \u27e8tactic_format_expr\u27e9\n\nunsafe def tactic.pp {\u03b1 : Type u} [has_to_tactic_format \u03b1] : \u03b1 \u2192 tactic format :=\n  has_to_tactic_format.to_tactic_format\n#align tactic.pp tactic.pp\n\nopen Tactic Format\n\nunsafe instance {\u03b1 : Type u} [has_to_tactic_format \u03b1] : has_to_tactic_format (List \u03b1) :=\n  \u27e8fun l => to_fmt <$> l.mapM pp\u27e9\n\nunsafe instance (\u03b1 : Type u) (\u03b2 : Type v) [has_to_tactic_format \u03b1] [has_to_tactic_format \u03b2] :\n    has_to_tactic_format (\u03b1 \u00d7 \u03b2) :=\n  \u27e8fun \u27e8a, b\u27e9 => to_fmt <$> (Prod.mk <$> pp a <*> pp b)\u27e9\n\nunsafe def option_to_tactic_format {\u03b1 : Type u} [has_to_tactic_format \u03b1] : Option \u03b1 \u2192 tactic format\n  | some a => do\n    let fa \u2190 pp a\n    return (to_fmt \"(some \" ++ fa ++ \")\")\n  | none => return \"none\"\n#align option_to_tactic_format option_to_tactic_format\n\nunsafe instance {\u03b1 : Type u} [has_to_tactic_format \u03b1] : has_to_tactic_format (Option \u03b1) :=\n  \u27e8option_to_tactic_format\u27e9\n\nunsafe instance {\u03b1} (a : \u03b1) : has_to_tactic_format (reflected _ a) :=\n  \u27e8fun h => pp h.to_expr\u27e9\n\nunsafe instance (priority := 10) has_to_format_to_has_to_tactic_format (\u03b1 : Type)\n    [has_to_format \u03b1] : has_to_tactic_format \u03b1 :=\n  \u27e8(fun x => return x) \u2218 to_fmt\u27e9\n#align has_to_format_to_has_to_tactic_format has_to_format_to_has_to_tactic_format\n\nnamespace Tactic\n\nopen TacticState\n\nunsafe def get_env : tactic environment := do\n  let s \u2190 read\n  return <| env s\n#align tactic.get_env tactic.get_env\n\nunsafe def get_decl (n : Name) : tactic declaration := do\n  let s \u2190 read\n  (env s).get n\n#align tactic.get_decl tactic.get_decl\n\nunsafe axiom get_trace_msg_pos : tactic Pos\n#align tactic.get_trace_msg_pos tactic.get_trace_msg_pos\n\nunsafe def trace {\u03b1 : Type u} [has_to_tactic_format \u03b1] (a : \u03b1) : tactic Unit := do\n  let fmt \u2190 pp a\n  return <| _root_.trace_fmt fmt fun u => ()\n#align tactic.trace tactic.trace\n\nunsafe def trace_call_stack : tactic Unit := fun state => traceCallStack (success () StateM)\n#align tactic.trace_call_stack tactic.trace_call_stack\n\nunsafe def timetac {\u03b1 : Type u} (desc : String) (t : Thunk (tactic \u03b1)) : tactic \u03b1 := fun s =>\n  timeit desc (t () s)\n#align tactic.timetac tactic.timetac\n\nunsafe def trace_state : tactic Unit := do\n  let s \u2190 read\n  trace <| to_fmt s\n#align tactic.trace_state tactic.trace_state\n\n/--\nA 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\n  | all\n  | semireducible\n  | instances\n  | reducible\n  | none\n#align tactic.transparency Tactic.Transparency\n\nexport Transparency (reducible semireducible)\n\n/-- (eval_expr \u03b1 e) evaluates 'e' IF 'e' has type '\u03b1'. -/\nunsafe axiom eval_expr (\u03b1 : Type u) [reflected _ \u03b1] : expr \u2192 tactic \u03b1\n#align tactic.eval_expr tactic.eval_expr\n\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. -/\nunsafe axiom result : tactic expr\n#align tactic.result tactic.result\n\n/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to\n   `do { r \u2190 result, s \u2190 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. -/\nunsafe axiom format_result : tactic format\n#align tactic.format_result tactic.format_result\n\n/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/\nunsafe axiom target : tactic expr\n#align tactic.target tactic.target\n\nunsafe axiom intro_core : Name \u2192 tactic expr\n#align tactic.intro_core tactic.intro_core\n\nunsafe axiom intron : Nat \u2192 tactic Unit\n#align tactic.intron tactic.intron\n\n/--\nClear the given local constant. The tactic fails if the given expression is not a local constant. -/\nunsafe axiom clear : expr \u2192 tactic Unit\n#align tactic.clear tactic.clear\n\n/--\n`revert_lst : list expr \u2192 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 : \u2115, h : P(x) \u22a2 T(x)`, `revert_lst [x]` returns `2` and produces the state ` \u22a2 \u03a0 x, P(x) \u2192 T(x)`.\n -/\nunsafe axiom revert_lst : List expr \u2192 tactic Nat\n#align tactic.revert_lst tactic.revert_lst\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. -/\nunsafe axiom whnf (e : expr) (md := semireducible) (unfold_ginductive := true) : tactic expr\n#align tactic.whnf tactic.whnf\n\n/--\n(head) eta expand the given expression. `f : \u03b1 \u2192 \u03b2` head-eta-expands to `\u03bb a, f a`. If `f` isn't a function then it just returns `f`.  -/\nunsafe axiom head_eta_expand : expr \u2192 tactic expr\n#align tactic.head_eta_expand tactic.head_eta_expand\n\n/-- (head) beta reduction. `(\u03bb x, B) c` reduces to `B[x/c]`. -/\nunsafe axiom head_beta : expr \u2192 tactic expr\n#align tactic.head_beta tactic.head_beta\n\n/--\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]`. -/\nunsafe axiom head_zeta : expr \u2192 tactic expr\n#align tactic.head_zeta tactic.head_zeta\n\n/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/\nunsafe axiom zeta : expr \u2192 tactic expr\n#align tactic.zeta tactic.zeta\n\n/-- (head) eta reduction. `(\u03bb x, f x)` reduces to `f`. -/\nunsafe axiom head_eta : expr \u2192 tactic expr\n#align tactic.head_eta tactic.head_eta\n\n/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/\nunsafe axiom unify (t s : expr) (md := semireducible) (approx := false) : tactic Unit\n#align tactic.unify tactic.unify\n\n/-- Similar to `unify`, but it treats metavariables as constants. -/\nunsafe axiom is_def_eq (t s : expr) (md := semireducible) (approx := false) : tactic Unit\n#align tactic.is_def_eq tactic.is_def_eq\n\n/-- Infer the type of the given expression.\n   Remark: transparency does not affect type inference -/\nunsafe axiom infer_type : expr \u2192 tactic expr\n#align tactic.infer_type tactic.infer_type\n\n/-- Get the `local_const` expr for the given `name`. -/\nunsafe axiom get_local : Name \u2192 tactic expr\n#align tactic.get_local tactic.get_local\n\n/-- Resolve a name using the current local context, environment, aliases, etc. -/\nunsafe axiom resolve_name : Name \u2192 tactic pexpr\n#align tactic.resolve_name tactic.resolve_name\n\n/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/\nunsafe axiom local_context : tactic (List expr)\n#align tactic.local_context tactic.local_context\n\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-/\nunsafe axiom get_unused_name (n : Name := `_x) (i : Option Nat := none) : tactic Name\n#align tactic.get_unused_name tactic.get_unused_name\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 (\u03b1 : Type.{l_1}) (\u03b2 : \u03b1 -> Type.{l_2}), (Pi x : \u03b1, \u03b2 x) -> (Pi x : \u03b1, \u03b2 x) -> , Prop\n        nat     : Type\n        real    : Type\n        vec.{l} : Pi (\u03b1 : 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-/\nunsafe axiom mk_app (fn : Name) (args : List expr) (md := semireducible) : tactic expr\n#align tactic.mk_app tactic.mk_app\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} nat (a > b) (nat.decidable_gt a b) a b\n   ```\n-/\nunsafe axiom mk_mapp (fn : Name) (args : List (Option expr)) (md := semireducible) : tactic expr\n#align tactic.mk_mapp tactic.mk_mapp\n\n/-- (mk_congr_arg h\u2081 h\u2082) is a more efficient version of (mk_app `congr_arg [h\u2081, h\u2082]) -/\nunsafe axiom mk_congr_arg : expr \u2192 expr \u2192 tactic expr\n#align tactic.mk_congr_arg tactic.mk_congr_arg\n\n/-- (mk_congr_fun h\u2081 h\u2082) is a more efficient version of (mk_app `congr_fun [h\u2081, h\u2082]) -/\nunsafe axiom mk_congr_fun : expr \u2192 expr \u2192 tactic expr\n#align tactic.mk_congr_fun tactic.mk_congr_fun\n\n/-- (mk_congr h\u2081 h\u2082) is a more efficient version of (mk_app `congr [h\u2081, h\u2082]) -/\nunsafe axiom mk_congr : expr \u2192 expr \u2192 tactic expr\n#align tactic.mk_congr tactic.mk_congr\n\n/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/\nunsafe axiom mk_eq_refl : expr \u2192 tactic expr\n#align tactic.mk_eq_refl tactic.mk_eq_refl\n\n/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/\nunsafe axiom mk_eq_symm : expr \u2192 tactic expr\n#align tactic.mk_eq_symm tactic.mk_eq_symm\n\n/-- (mk_eq_trans h\u2081 h\u2082) is a more efficient version of (mk_app `eq.trans [h\u2081, h\u2082]) -/\nunsafe axiom mk_eq_trans : expr \u2192 expr \u2192 tactic expr\n#align tactic.mk_eq_trans tactic.mk_eq_trans\n\n/-- (mk_eq_mp h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mp [h\u2081, h\u2082]) -/\nunsafe axiom mk_eq_mp : expr \u2192 expr \u2192 tactic expr\n#align tactic.mk_eq_mp tactic.mk_eq_mp\n\n/-- (mk_eq_mpr h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mpr [h\u2081, h\u2082]) -/\nunsafe axiom mk_eq_mpr : expr \u2192 expr \u2192 tactic expr\n#align tactic.mk_eq_mpr tactic.mk_eq_mpr\n\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. -/\nunsafe axiom subst_core : expr \u2192 tactic Unit\n#align tactic.subst_core tactic.subst_core\n\n/-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to\n    the target type. -/\nunsafe axiom exact (e : expr) (md := semireducible) : tactic Unit\n#align tactic.exact tactic.exact\n\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. -/\nunsafe axiom to_expr (q : pexpr) (allow_mvars := true) (subgoals := true) : tactic expr\n#align tactic.to_expr tactic.to_expr\n\n/-- Return true if the given expression is a type class. -/\nunsafe axiom is_class : expr \u2192 tactic Bool\n#align tactic.is_class tactic.is_class\n\n/-- Try to create an instance of the given type class. -/\nunsafe axiom mk_instance : expr \u2192 tactic expr\n#align tactic.mk_instance tactic.mk_instance\n\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. -/\nunsafe axiom change (e : expr) (check : Bool := true) : tactic Unit\n#align tactic.change tactic.change\n\n/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/\nunsafe axiom assert_core : Name \u2192 expr \u2192 tactic Unit\n#align tactic.assert_core tactic.assert_core\n\n/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/\nunsafe axiom assertv_core : Name \u2192 expr \u2192 expr \u2192 tactic Unit\n#align tactic.assertv_core tactic.assertv_core\n\n/--\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. -/\nunsafe axiom define_core : Name \u2192 expr \u2192 tactic Unit\n#align tactic.define_core tactic.define_core\n\n/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/\nunsafe axiom definev_core : Name \u2192 expr \u2192 expr \u2192 tactic Unit\n#align tactic.definev_core tactic.definev_core\n\n/--\nRotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/\nunsafe axiom rotate_left : Nat \u2192 tactic Unit\n#align tactic.rotate_left tactic.rotate_left\n\n/-- Gets a list of metavariables, one for each goal. -/\nunsafe axiom get_goals : tactic (List expr)\n#align tactic.get_goals tactic.get_goals\n\n/--\nReplace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/\nunsafe axiom set_goals : List expr \u2192 tactic Unit\n#align tactic.set_goals tactic.set_goals\n\n/-- Convenience function for creating ` for proofs. -/\nunsafe def mk_tagged_proof (prop : expr) (pr : expr) (tag : Name) : expr :=\n  expr.mk_app (expr.const `` id_tag []) [expr.const tag [], prop, pr]\n#align tactic.mk_tagged_proof tactic.mk_tagged_proof\n\n/-- How to order the new goals made from an `apply` tactic.\nSupposing we were applying `e : \u2200 (a:\u03b1) (p : P(a)), Q`\n- `non_dep_first` would produce goals `\u22a2 P(?m)`, `\u22a2 \u03b1`. 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 `\u22a2 P(?m)`.\n- `all` would produce goals `\u22a2 \u03b1`, `\u22a2 P(?m)`.\n-/\ninductive NewGoals\n  | non_dep_first\n  | non_dep_only\n  | all\n#align tactic.new_goals Tactic.NewGoals\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 ApplyCfg where\n  md := semireducible\n  approx := true\n  NewGoals := NewGoals.non_dep_first\n  instances := true\n  autoParam\u2093 := true\n  optParam := true\n  unify := true\n#align tactic.apply_cfg Tactic.ApplyCfg\n\n/--\nApply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.\n    Supposing `e : \u03a0 (a\u2081:\u03b1\u2081) ... (a\u2099:\u03b1\u2099), P(a\u2081,...,a\u2099)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a\u2081,...?a\u2099)`.\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. -/\nunsafe axiom apply_core (e : expr) (cfg : ApplyCfg := { }) : tactic (List (Name \u00d7 expr))\n#align tactic.apply_core tactic.apply_core\n\n/-- Create a fresh meta universe variable. -/\nunsafe axiom mk_meta_univ : tactic level\n#align tactic.mk_meta_univ tactic.mk_meta_univ\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. -/\nunsafe axiom mk_meta_var : expr \u2192 tactic expr\n#align tactic.mk_meta_var tactic.mk_meta_var\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. -/\nunsafe axiom get_univ_assignment : level \u2192 tactic level\n#align tactic.get_univ_assignment tactic.get_univ_assignment\n\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. -/\nunsafe axiom get_assignment : expr \u2192 tactic expr\n#align tactic.get_assignment tactic.get_assignment\n\n/-- Return true if the given meta-variable is assigned.\n    Fail if argument is not a meta-variable. -/\nunsafe axiom is_assigned : expr \u2192 tactic Bool\n#align tactic.is_assigned tactic.is_assigned\n\n/--\nMake a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic.  -/\nunsafe axiom mk_fresh_name : tactic Name\n#align tactic.mk_fresh_name tactic.mk_fresh_name\n\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` -/\nunsafe axiom induction (h : expr) (ns : List Name := []) (rec : Option Name := none)\n    (md := semireducible) : tactic (List (Name \u00d7 List expr \u00d7 List (Name \u00d7 expr)))\n#align tactic.induction tactic.induction\n\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. -/\nunsafe axiom cases_core (h : expr) (ns : List Name := []) (md := semireducible) :\n    tactic (List (Name \u00d7 List expr \u00d7 List (Name \u00d7 expr)))\n#align tactic.cases_core tactic.cases_core\n\n/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/\nunsafe axiom destruct (e : expr) (md := semireducible) : tactic Unit\n#align tactic.destruct tactic.destruct\n\n/-- Generalizes the target with respect to `e`.  -/\nunsafe axiom generalize (e : expr) (n : Name := `_x) (md := semireducible) : tactic Unit\n#align tactic.generalize tactic.generalize\n\n/-- instantiate assigned metavariables in the given expression -/\nunsafe axiom instantiate_mvars : expr \u2192 tactic expr\n#align tactic.instantiate_mvars tactic.instantiate_mvars\n\n/-- Add the given declaration to the environment -/\nunsafe axiom add_decl : declaration \u2192 tactic Unit\n#align tactic.add_decl tactic.add_decl\n\n/-- Changes the environment to the `new_env`.\nThe new environment does not need to be a descendant of the old one.\nUse with care.\n-/\nunsafe axiom set_env_core : environment \u2192 tactic Unit\n#align tactic.set_env_core tactic.set_env_core\n\n/--\nChanges the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/\nunsafe axiom set_env : environment \u2192 tactic Unit\n#align tactic.set_env tactic.set_env\n\n/-- `doc_string env d k` returns the doc string for `d` (if available) -/\nunsafe axiom doc_string : Name \u2192 tactic String\n#align tactic.doc_string tactic.doc_string\n\n/-- Set the docstring for the given declaration. -/\nunsafe axiom add_doc_string : Name \u2192 String \u2192 tactic Unit\n#align tactic.add_doc_string tactic.add_doc_string\n\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-/\nunsafe axiom add_aux_decl (c : Name) (type : expr) (val : expr) (is_lemma : Bool) : tactic expr\n#align tactic.add_aux_decl tactic.add_aux_decl\n\n/--\nReturns 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. -/\nunsafe axiom olean_doc_strings : tactic (List (Option String \u00d7 List (Pos \u00d7 String)))\n#align tactic.olean_doc_strings tactic.olean_doc_strings\n\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)` -/\nunsafe def module_doc_strings : tactic (List (Option Name \u00d7 String)) := do\n  let mod_docs\n    \u2190-- Obtain a list of top-level docs in current module.\n      olean_doc_strings\n  let mod_docs : List (List (Option Name \u00d7 String)) :=\n    mod_docs.filterMap fun d =>\n      if d.1.isNone then some (d.2.map fun pos_doc => \u27e8none, pos_doc.2\u27e9) else none\n  let mod_docs := mod_docs.join\n  let e\n    \u2190-- Obtain list of declarations in current module.\n      get_env\n  let decls :=\n    environment.fold e ([] : List Name) fun d acc =>\n      let n := d.to_name\n      if (environment.decl_olean e n).isNone then n :: Acc else Acc\n  let decls\n    \u2190-- Map declarations to those which have docstrings.\n          decls.foldlM\n        (fun a n => (doc_string n >>= fun doc => pure <| (some n, doc) :: a) <|> pure a) []\n  pure (mod_docs ++ decls)\n#align tactic.module_doc_strings tactic.module_doc_strings\n\n/-- Set attribute `attr_name` for constant `c_name` with the given priority.\n   If the priority is none, then use default -/\nunsafe axiom set_basic_attribute (attr_name : Name) (c_name : Name) (persistent := false)\n    (prio : Option Nat := none) : tactic Unit\n#align tactic.set_basic_attribute tactic.set_basic_attribute\n\n/-- `unset_attribute attr_name c_name` -/\nunsafe axiom unset_attribute : Name \u2192 Name \u2192 tactic Unit\n#align tactic.unset_attribute tactic.unset_attribute\n\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. -/\nunsafe axiom has_attribute : Name \u2192 Name \u2192 tactic (Bool \u00d7 Nat)\n#align tactic.has_attribute tactic.has_attribute\n\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`  -/\nunsafe def copy_attribute (attr_name : Name) (src : Name) (tgt : Name) (p : Option Bool := none) :\n    tactic Unit :=\n  try do\n    let (p', prio) \u2190 has_attribute attr_name src\n    let p := p.getD p'\n    set_basic_attribute attr_name tgt p (some prio)\n#align tactic.copy_attribute tactic.copy_attribute\n\n/-- Name of the declaration currently being elaborated. -/\nunsafe axiom decl_name : tactic Name\n#align tactic.decl_name tactic.decl_name\n\n/-- `save_type_info e ref` save (typeof e) at position associated with ref -/\nunsafe axiom save_type_info {elab : Bool} : expr \u2192 expr elab \u2192 tactic Unit\n#align tactic.save_type_info tactic.save_type_info\n\nunsafe axiom save_info_thunk : Pos \u2192 (Unit \u2192 format) \u2192 tactic Unit\n#align tactic.save_info_thunk tactic.save_info_thunk\n\n/-- Return list of currently open namespaces -/\nunsafe axiom open_namespaces : tactic (List Name)\n#align tactic.open_namespaces tactic.open_namespaces\n\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. -/\nunsafe axiom kdepends_on (e t : expr) (md := reducible) : tactic Bool\n#align tactic.kdepends_on tactic.kdepends_on\n\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. -/\nunsafe axiom kabstract (e t : expr) (md := reducible) (unify := true) : tactic expr\n#align tactic.kabstract tactic.kabstract\n\n/-- Blocks the execution of the current thread for at least `msecs` milliseconds.\n    This tactic is used mainly for debugging purposes. -/\nunsafe axiom sleep (msecs : Nat) : tactic Unit\n#align tactic.sleep tactic.sleep\n\n/-- Type check `e` with respect to the current goal.\n    Fails if `e` is not type correct. -/\nunsafe axiom type_check (e : expr) (md := semireducible) : tactic Unit\n#align tactic.type_check tactic.type_check\n\nopen List Nat\n\n/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/\ndef Tag : Type :=\n  List Name\n#align tactic.tag Tactic.Tag\n\n/-- Enable/disable goal tagging.  -/\nunsafe axiom enable_tags (b : Bool) : tactic Unit\n#align tactic.enable_tags tactic.enable_tags\n\n/-- Return tt iff goal tagging is enabled. -/\nunsafe axiom tags_enabled : tactic Bool\n#align tactic.tags_enabled tactic.tags_enabled\n\n/-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled.\n    Remark: `set_goal g []` removes the tag -/\nunsafe axiom set_tag (g : expr) (t : Tag) : tactic Unit\n#align tactic.set_tag tactic.set_tag\n\n/-- Return tag associated with `g`. Return `[]` if there is no tag. -/\nunsafe axiom get_tag (g : expr) : tactic Tag\n#align tactic.get_tag tactic.get_tag\n\n/-! By default, Lean only considers local instances in the header of declarations.\n    This has two main benefits.\n    1- Results produced by the type class resolution procedure can be easily cached.\n    2- The set of local instances does not have to be recomputed.\n\n    This approach has the following disadvantages:\n    1- Frozen local instances cannot be reverted.\n    2- Local instances defined inside of a declaration are not considered during type\n       class resolution.\n-/\n\n\n/-- Avoid this function!  Use `unfreezingI`/`resetI`/etc. instead!\n\nUnfreezes the current set of local instances.\nAfter this tactic, the instance cache is disabled.\n-/\nunsafe axiom unfreeze_local_instances : tactic Unit\n#align tactic.unfreeze_local_instances tactic.unfreeze_local_instances\n\n/-- Freeze the current set of local instances.\n-/\nunsafe axiom freeze_local_instances : tactic Unit\n#align tactic.freeze_local_instances tactic.freeze_local_instances\n\n/-- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/\nunsafe axiom frozen_local_instances : tactic (Option (List expr))\n#align tactic.frozen_local_instances tactic.frozen_local_instances\n\n/-- Run the provided tactic, associating it to the given AST node. -/\nunsafe axiom with_ast {\u03b1 : Type u} (ast : \u2115) (t : tactic \u03b1) : tactic \u03b1\n#align tactic.with_ast tactic.with_ast\n\nunsafe def induction' (h : expr) (ns : List Name := []) (rec : Option Name := none)\n    (md := semireducible) : tactic Unit :=\n  induction h ns rec md >> return ()\n#align tactic.induction' tactic.induction'\n\n/-- Remark: set_goals will erase any solved goal -/\nunsafe def cleanup : tactic Unit :=\n  get_goals >>= set_goals\n#align tactic.cleanup tactic.cleanup\n\n/-- Auxiliary definition used to implement begin ... end blocks -/\nunsafe def step {\u03b1 : Type u} (t : tactic \u03b1) : tactic Unit :=\n  t >>[tactic] cleanup\n#align tactic.step tactic.step\n\nunsafe def istep {\u03b1 : Type u} (line0 col0 line col ast : \u2115) (t : tactic \u03b1) : tactic Unit := fun s =>\n  (@scopeTrace _ line col fun _ => with_ast ast (step t) s).clamp_pos line0 line col\n#align tactic.istep tactic.istep\n\nunsafe def is_prop (e : expr) : tactic Bool := do\n  let t \u2190 infer_type e\n  return (t = q(Prop))\n#align tactic.is_prop tactic.is_prop\n\n/-- Return true iff n is the name of declaration that is a proposition. -/\nunsafe def is_prop_decl (n : Name) : tactic Bool := do\n  let env \u2190 get_env\n  let d \u2190 env.get n\n  let t \u2190 return <| d.type\n  is_prop t\n#align tactic.is_prop_decl tactic.is_prop_decl\n\nunsafe def is_proof (e : expr) : tactic Bool :=\n  infer_type e >>= is_prop\n#align tactic.is_proof tactic.is_proof\n\nunsafe def whnf_no_delta (e : expr) : tactic expr :=\n  whnf e Transparency.none\n#align tactic.whnf_no_delta tactic.whnf_no_delta\n\n/-- Return `e` in weak head normal form with respect to the given transparency setting,\n    or `e` head is a generalized constructor or inductive datatype. -/\nunsafe def whnf_ginductive (e : expr) (md := semireducible) : tactic expr :=\n  whnf e md false\n#align tactic.whnf_ginductive tactic.whnf_ginductive\n\nunsafe def whnf_target : tactic Unit :=\n  target >>= whnf >>= change\n#align tactic.whnf_target tactic.whnf_target\n\n/-- Change the target of the main goal.\n   The input expression must be definitionally equal to the current target.\n   The tactic does not check whether `e`\n   is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/\nunsafe def unsafe_change (e : expr) : tactic Unit :=\n  change e false\n#align tactic.unsafe_change tactic.unsafe_change\n\n/-- Pi or elet introduction.\nGiven the tactic state `\u22a2 \u03a0 x : \u03b1, Y`, ``intro `hello`` will produce the state `hello : \u03b1 \u22a2 Y[x/hello]`.\nReturns the new local constant. Similarly for `elet` expressions.\nIf the target is not a Pi or elet it will try to put it in WHNF.\n -/\nunsafe def intro (n : Name) : tactic expr := do\n  let t \u2190 target\n  if expr.is_pi t \u2228 expr.is_let t then intro_core n else whnf_target >> intro_core n\n#align tactic.intro tactic.intro\n\n/-- A variant of `intro` which makes sure that the introduced hypothesis's name is\nunique in the context. If there is no hypothesis named `n` in the context yet,\n`intro_fresh n` is the same as `intro n`. If there is already a hypothesis named\n`n`, the new hypothesis is named `n_1` (or `n_2` if `n_1` already exists, etc.).\nIf `offset` is given, the new names are `n_offset`, `n_offset+1` etc.\n\nIf `n` is `_`, `intro_fresh n` is the same as `intro1`. The `offset` is ignored\nin this case.\n-/\nunsafe def intro_fresh (n : Name) (offset : Option Nat := none) : tactic expr :=\n  if n = `_ then intro `_\n  else do\n    let n \u2190 get_unused_name n offset\n    intro n\n#align tactic.intro_fresh tactic.intro_fresh\n\n/-- Like `intro` except the name is derived from the bound name in the \u03a0. -/\nunsafe def intro1 : tactic expr :=\n  intro `_\n#align tactic.intro1 tactic.intro1\n\n/--\nRepeatedly apply `intro1` and return the list of new local constants in order of introduction. -/\nunsafe def intros : tactic (List expr) := do\n  let t \u2190 target\n  match t with\n    | expr.pi _ _ _ _ => do\n      let H \u2190 intro1\n      let Hs \u2190 intros\n      return (H :: Hs)\n    | expr.elet _ _ _ _ => do\n      let H \u2190 intro1\n      let Hs \u2190 intros\n      return (H :: Hs)\n    | _ => return []\n#align tactic.intros tactic.intros\n\n/--\nSame as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/\nunsafe def intro_lst (ns : List Name) : tactic (List expr) :=\n  ns.mapM intro\n#align tactic.intro_lst tactic.intro_lst\n\n/-- A variant of `intro_lst` which makes sure that the introduced hypotheses' names\nare unique in the context. See `intro_fresh`.\n-/\nunsafe def intro_lst_fresh (ns : List Name) : tactic (List expr) :=\n  ns.mapM intro_fresh\n#align tactic.intro_lst_fresh tactic.intro_lst_fresh\n\n/-- Introduces new hypotheses with forward dependencies.  -/\nunsafe def intros_dep : tactic (List expr) := do\n  let t \u2190 target\n  let proc (b : expr) :=\n    if b.has_var_idx 0 then do\n      let h \u2190 intro1\n      let hs \u2190 intros_dep\n      return (h :: hs)\n    else-- body doesn't depend on new hypothesis\n        return\n        []\n  match t with\n    | expr.pi _ _ _ b => proc b\n    | expr.elet _ _ _ b => proc b\n    | _ => return []\n#align tactic.intros_dep tactic.intros_dep\n\nunsafe def introv : List Name \u2192 tactic (List expr)\n  | [] => intros_dep\n  | n :: ns => do\n    let hs \u2190 intros_dep\n    let h \u2190 intro n\n    let hs' \u2190 introv ns\n    return (hs ++ h :: hs')\n#align tactic.introv tactic.introv\n\n/-- `intron' n` introduces `n` hypotheses and returns the resulting local\nconstants. Fails if there are not at least `n` arguments to introduce. If you do\nnot need the return value, use `intron`.\n-/\nunsafe def intron' (n : \u2115) : tactic (List expr) :=\n  iterate_exactly n intro1\n#align tactic.intron' tactic.intron'\n\n/-- Like `intron'` but the introduced hypotheses' names are derived from `base`,\ni.e. `base`, `base_1` etc. The new names are unique in the context. If `offset`\nis given, the new names will be `base_offset`, `base_offset+1` etc.\n-/\nunsafe def intron_base (n : \u2115) (base : Name) (offset : Option Nat := none) : tactic (List expr) :=\n  iterate_exactly n (intro_fresh base offset)\n#align tactic.intron_base tactic.intron_base\n\n/-- `intron_with i ns base offset` introduces `i` hypotheses using the names from\n`ns`. If `ns` contains less than `i` names, the remaining hypotheses' names are\nderived from `base` and `offset` (as with `intron_base`). If `base` is `_`, the\nnames are derived from the \u03a0 binder names.\n\nReturns the introduced local constants and the remaining names from `ns` (if\n`ns` contains more than `i` names).\n-/\nunsafe def intron_with :\n    \u2115 \u2192 List Name \u2192 optParam Name `_ \u2192 optParam (Option \u2115) none \u2192 tactic (List expr \u00d7 List Name)\n  | 0, ns, _, _ => pure ([], ns)\n  | i + 1, [], base, offset => do\n    let hs \u2190 intron_base (i + 1) base offset\n    pure (hs, [])\n  | i + 1, n :: ns, base, offset => do\n    let h \u2190 intro n\n    let \u27e8hs, rest\u27e9 \u2190 intron_with i ns base offset\n    pure (h :: hs, rest)\n#align tactic.intron_with tactic.intron_with\n\n/-- Returns n fully qualified if it refers to a constant, or else fails. -/\nunsafe def resolve_constant (n : Name) : tactic Name := do\n  let e \u2190 resolve_name n\n  match e with\n    | expr.const n _ => pure n\n    | _ => do\n      let e \u2190 to_expr e tt ff\n      let expr.const n _ \u2190 pure <| e\n      pure n\n#align tactic.resolve_constant tactic.resolve_constant\n\nunsafe def to_expr_strict (q : pexpr) : tactic expr :=\n  to_expr q\n#align tactic.to_expr_strict tactic.to_expr_strict\n\n/--\nExample: with `x : \u2115, h : P(x) \u22a2 T(x)`, `revert x` returns `2` and produces the state ` \u22a2 \u03a0 x, P(x) \u2192 T(x)`.\n -/\nunsafe def revert (l : expr) : tactic Nat :=\n  revert_lst [l]\n#align tactic.revert tactic.revert\n\n/-- Revert \"all\" hypotheses. Actually, the tactic only reverts\n   hypotheses occurring after the last frozen local instance.\n   Recall that frozen local instances cannot be reverted,\n   use `unfreezing revert_all` instead. -/\nunsafe def revert_all : tactic Nat := do\n  let lctx \u2190 local_context\n  let lis \u2190 frozen_local_instances\n  match lis with\n    | none => revert_lst lctx\n    | some [] => revert_lst lctx\n    |-- `hi` is the last local instance. We shoul truncate `lctx` at `hi`.\n        some\n        (hi :: his) =>\n      revert_lst <| lctx (fun r h => if h = hi then [] else h :: r) []\n#align tactic.revert_all tactic.revert_all\n\nunsafe def clear_lst : List Name \u2192 tactic Unit\n  | [] => skip\n  | n :: ns => do\n    let H \u2190 get_local n\n    clear H\n    clear_lst ns\n#align tactic.clear_lst tactic.clear_lst\n\nunsafe def match_not (e : expr) : tactic expr :=\n  match expr.is_not e with\n  | some a => return a\n  | none => fail \"expression is not a negation\"\n#align tactic.match_not tactic.match_not\n\nunsafe def match_and (e : expr) : tactic (expr \u00d7 expr) :=\n  match expr.is_and e with\n  | some (\u03b1, \u03b2) => return (\u03b1, \u03b2)\n  | none => fail \"expression is not a conjunction\"\n#align tactic.match_and tactic.match_and\n\nunsafe def match_or (e : expr) : tactic (expr \u00d7 expr) :=\n  match expr.is_or e with\n  | some (\u03b1, \u03b2) => return (\u03b1, \u03b2)\n  | none => fail \"expression is not a disjunction\"\n#align tactic.match_or tactic.match_or\n\nunsafe def match_iff (e : expr) : tactic (expr \u00d7 expr) :=\n  match expr.is_iff e with\n  | some (lhs, rhs) => return (lhs, rhs)\n  | none => fail \"expression is not an iff\"\n#align tactic.match_iff tactic.match_iff\n\nunsafe def match_eq (e : expr) : tactic (expr \u00d7 expr) :=\n  match expr.is_eq e with\n  | some (lhs, rhs) => return (lhs, rhs)\n  | none => fail \"expression is not an equality\"\n#align tactic.match_eq tactic.match_eq\n\nunsafe def match_ne (e : expr) : tactic (expr \u00d7 expr) :=\n  match expr.is_ne e with\n  | some (lhs, rhs) => return (lhs, rhs)\n  | none => fail \"expression is not a disequality\"\n#align tactic.match_ne tactic.match_ne\n\nunsafe def match_heq (e : expr) : tactic (expr \u00d7 expr \u00d7 expr \u00d7 expr) := do\n  match expr.is_heq e with\n    | some (\u03b1, lhs, \u03b2, rhs) => return (\u03b1, lhs, \u03b2, rhs)\n    | none => fail \"expression is not a heterogeneous equality\"\n#align tactic.match_heq tactic.match_heq\n\nunsafe def match_refl_app (e : expr) : tactic (Name \u00d7 expr \u00d7 expr) := do\n  let env \u2190 get_env\n  match environment.is_refl_app env e with\n    | some (R, lhs, rhs) => return (R, lhs, rhs)\n    | none => fail \"expression is not an application of a reflexive relation\"\n#align tactic.match_refl_app tactic.match_refl_app\n\nunsafe def match_app_of (e : expr) (n : Name) : tactic (List expr) :=\n  guard (expr.is_app_of e n) >> return e.get_app_args\n#align tactic.match_app_of tactic.match_app_of\n\nunsafe def get_local_type (n : Name) : tactic expr :=\n  get_local n >>= infer_type\n#align tactic.get_local_type tactic.get_local_type\n\nunsafe def trace_result : tactic Unit :=\n  format_result >>= trace\n#align tactic.trace_result tactic.trace_result\n\nunsafe def rexact (e : expr) : tactic Unit :=\n  exact e reducible\n#align tactic.rexact tactic.rexact\n\nunsafe def any_hyp_aux {\u03b1 : Type} (f : expr \u2192 tactic \u03b1) : List expr \u2192 tactic \u03b1\n  | [] => failed\n  | h :: hs => f h <|> any_hyp_aux hs\n#align tactic.any_hyp_aux tactic.any_hyp_aux\n\nunsafe def any_hyp {\u03b1 : Type} (f : expr \u2192 tactic \u03b1) : tactic \u03b1 :=\n  local_context >>= any_hyp_aux f\n#align tactic.any_hyp tactic.any_hyp\n\n/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/\nunsafe def find_same_type : expr \u2192 List expr \u2192 tactic expr\n  | e, [] => failed\n  | e, H :: Hs => do\n    let t \u2190 infer_type H\n    unify e t >> return H <|> find_same_type e Hs\n#align tactic.find_same_type tactic.find_same_type\n\nunsafe def find_assumption (e : expr) : tactic expr := do\n  let ctx \u2190 local_context\n  find_same_type e ctx\n#align tactic.find_assumption tactic.find_assumption\n\nunsafe def assumption : tactic Unit :=\n  (do\n      let ctx \u2190 local_context\n      let t \u2190 target\n      let H \u2190 find_same_type t ctx\n      exact H) <|>\n    fail \"assumption tactic failed\"\n#align tactic.assumption tactic.assumption\n\nunsafe def save_info (p : Pos) : tactic Unit := do\n  let s \u2190 read\n  tactic.save_info_thunk p fun _ => tactic_state.to_format s\n#align tactic.save_info tactic.save_info\n\n/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/\nunsafe def swap : tactic Unit := do\n  let gs \u2190 get_goals\n  match gs with\n    | g\u2081 :: g\u2082 :: rs => set_goals (g\u2082 :: g\u2081 :: rs)\n    | e => skip\n#align tactic.swap tactic.swap\n\n/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/\nunsafe def assert (h : Name) (t : expr) : tactic expr := do\n  assert_core h t\n  swap\n  let e \u2190 intro h\n  swap\n  return e\n#align tactic.assert tactic.assert\n\n/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/\nunsafe def assertv (h : Name) (t : expr) (v : expr) : tactic expr :=\n  assertv_core h t v >> intro h\n#align tactic.assertv tactic.assertv\n\n/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/\nunsafe def define (h : Name) (t : expr) : tactic expr := do\n  define_core h t\n  swap\n  let e \u2190 intro h\n  swap\n  return e\n#align tactic.define tactic.define\n\n/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/\nunsafe def definev (h : Name) (t : expr) (v : expr) : tactic expr :=\n  definev_core h t v >> intro h\n#align tactic.definev tactic.definev\n\n/-- Add `h : t := pr` to the current goal -/\nunsafe def pose (h : Name) (t : Option expr := none) (pr : expr) : tactic expr :=\n  let dv t := definev h t pr\n  Option.casesOn t (infer_type pr >>= dv) dv\n#align tactic.pose 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) : tactic expr :=\n  let dv t := assertv h t pr\n  Option.casesOn t (infer_type pr >>= dv) dv\n#align tactic.note tactic.note\n\n/-- Return the number of goals that need to be solved -/\nunsafe def num_goals : tactic Nat := do\n  let gs \u2190 get_goals\n  return (length gs)\n#align tactic.num_goals tactic.num_goals\n\n/--\nRotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times.\n[NOTE] We have to provide the instance argument `[has_mod nat]` because\n   mod for nat was not defined yet -/\nunsafe def rotate_right (n : Nat) [Mod Nat] : tactic Unit := do\n  let ng \u2190 num_goals\n  if ng = 0 then skip else rotate_left (ng - n % ng)\n#align tactic.rotate_right tactic.rotate_right\n\n/-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/\nunsafe def rotate : Nat \u2192 tactic Unit :=\n  rotate_left\n#align tactic.rotate tactic.rotate\n\nprivate unsafe def repeat_aux (t : tactic Unit) : List expr \u2192 List expr \u2192 tactic Unit\n  | [], r => set_goals r.reverse\n  | g :: gs, r => do\n    let ok \u2190 try_core (set_goals [g] >> t)\n    match ok with\n      | none => repeat_aux gs (g :: r)\n      | _ => do\n        let gs' \u2190 get_goals\n        repeat_aux (gs' ++ gs) r\n#align tactic.repeat_aux tactic.repeat_aux\n\n/-- This tactic is applied to each goal. If the application succeeds,\n    the tactic is applied recursively to all the generated subgoals until it eventually fails.\n    The recursion stops in a subgoal when the tactic has failed to make progress.\n    The tactic `repeat` never fails. -/\nunsafe def repeat (t : tactic Unit) : tactic Unit := do\n  let gs \u2190 get_goals\n  repeat_aux t gs []\n#align tactic.repeat tactic.repeat\n\n/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.\n   The tactic fails if all t_i's fail. -/\nunsafe def first {\u03b1 : Type u} : List (tactic \u03b1) \u2192 tactic \u03b1\n  | [] => fail \"first tactic failed, no more alternatives\"\n  | t :: ts => t <|> first ts\n#align tactic.first tactic.first\n\n/-- Applies the given tactic to the main goal and fails if it is not solved. -/\nunsafe def solve1 {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 := do\n  let gs \u2190 get_goals\n  match gs with\n    | [] => fail \"solve1 tactic failed, there isn't any goal left to focus\"\n    | g :: rs => do\n      set_goals [g]\n      let a \u2190 tac\n      let gs' \u2190 get_goals\n      match gs' with\n        | [] => set_goals rs >> pure a\n        | gs => fail \"solve1 tactic failed, focused goal has not been solved\"\n#align tactic.solve1 tactic.solve1\n\n/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/\nunsafe def solve {\u03b1} (ts : List (tactic \u03b1)) : tactic \u03b1 :=\n  first <| map solve1 ts\n#align tactic.solve tactic.solve\n\nprivate unsafe def focus_aux {\u03b1} : List (tactic \u03b1) \u2192 List expr \u2192 List expr \u2192 tactic (List \u03b1)\n  | [], [], rs => set_goals rs *> pure []\n  | t :: ts, [], rs => fail \"focus tactic failed, insufficient number of goals\"\n  | tts, g :: gs, rs =>\n    condM (is_assigned g) (focus_aux tts gs rs) do\n      set_goals [g]\n      let t :: ts \u2190 pure tts |\n        fail \"focus tactic failed, insufficient number of tactics\"\n      let a \u2190 t\n      let rs' \u2190 get_goals\n      let as \u2190 focus_aux ts gs (rs ++ rs')\n      pure <| a :: as\n#align tactic.focus_aux tactic.focus_aux\n\n/-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of\ngoals is not n. Returns the results of t_i (one per goal).\n-/\nunsafe def focus {\u03b1} (ts : List (tactic \u03b1)) : tactic (List \u03b1) := do\n  let gs \u2190 get_goals\n  focus_aux ts gs []\n#align tactic.focus tactic.focus\n\nprivate unsafe def focus'_aux : List (tactic Unit) \u2192 List expr \u2192 List expr \u2192 tactic Unit\n  | [], [], rs => set_goals rs\n  | t :: ts, [], rs => fail \"focus' tactic failed, insufficient number of goals\"\n  | tts, g :: gs, rs =>\n    condM (is_assigned g) (focus'_aux tts gs rs) do\n      set_goals [g]\n      let t :: ts \u2190 pure tts |\n        fail \"focus' tactic failed, insufficient number of tactics\"\n      t\n      let rs' \u2190 get_goals\n      focus'_aux ts gs (rs ++ rs')\n#align tactic.focus'_aux tactic.focus'_aux\n\n/-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/\nunsafe def focus' (ts : List (tactic Unit)) : tactic Unit := do\n  let gs \u2190 get_goals\n  focus'_aux ts gs []\n#align tactic.focus' tactic.focus'\n\nunsafe def focus1 {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 := do\n  let g :: gs \u2190 get_goals\n  match gs with\n    | [] => tac\n    | _ => do\n      set_goals [g]\n      let a \u2190 tac\n      let gs' \u2190 get_goals\n      set_goals (gs' ++ gs)\n      return a\n#align tactic.focus1 tactic.focus1\n\nprivate unsafe def all_goals_core {\u03b1} (tac : tactic \u03b1) : List expr \u2192 List expr \u2192 tactic (List \u03b1)\n  | [], ac => set_goals ac *> pure []\n  | g :: gs, ac =>\n    condM (is_assigned g) (all_goals_core gs ac) do\n      set_goals [g]\n      let a \u2190 tac\n      let new_gs \u2190 get_goals\n      let as \u2190 all_goals_core gs (ac ++ new_gs)\n      pure <| a :: as\n#align tactic.all_goals_core tactic.all_goals_core\n\n/-- Apply the given tactic to all goals. Return one result per goal.\n-/\nunsafe def all_goals {\u03b1} (tac : tactic \u03b1) : tactic (List \u03b1) := do\n  let gs \u2190 get_goals\n  all_goals_core tac gs []\n#align tactic.all_goals tactic.all_goals\n\nprivate unsafe def all_goals'_core (tac : tactic Unit) : List expr \u2192 List expr \u2192 tactic Unit\n  | [], ac => set_goals ac\n  | g :: gs, ac =>\n    condM (is_assigned g) (all_goals'_core gs ac) do\n      set_goals [g]\n      tac\n      let new_gs \u2190 get_goals\n      all_goals'_core gs (ac ++ new_gs)\n#align tactic.all_goals'_core tactic.all_goals'_core\n\n/-- Apply the given tactic to all goals. -/\nunsafe def all_goals' (tac : tactic Unit) : tactic Unit := do\n  let gs \u2190 get_goals\n  all_goals'_core tac gs []\n#align tactic.all_goals' tactic.all_goals'\n\nprivate unsafe def any_goals_core {\u03b1} (tac : tactic \u03b1) :\n    List expr \u2192 List expr \u2192 Bool \u2192 tactic (List (Option \u03b1))\n  | [], ac, progress => guard progress *> set_goals ac *> pure []\n  | g :: gs, ac, progress =>\n    condM (is_assigned g) (any_goals_core gs ac progress) do\n      set_goals [g]\n      let res \u2190 try_core tac\n      let new_gs \u2190 get_goals\n      let ress \u2190 any_goals_core gs (ac ++ new_gs) (res.isSome || progress)\n      pure <| res :: ress\n#align tactic.any_goals_core tactic.any_goals_core\n\n/-- Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac`\nsucceeds for at least one goal. The returned list contains the result of `tac`\nfor each goal: `some a` if tac succeeded, or `none` if it did not.\n-/\nunsafe def any_goals {\u03b1} (tac : tactic \u03b1) : tactic (List (Option \u03b1)) := do\n  let gs \u2190 get_goals\n  any_goals_core tac gs [] ff\n#align tactic.any_goals tactic.any_goals\n\nprivate unsafe def any_goals'_core (tac : tactic Unit) : List expr \u2192 List expr \u2192 Bool \u2192 tactic Unit\n  | [], ac, progress => guard progress >> set_goals ac\n  | g :: gs, ac, progress =>\n    condM (is_assigned g) (any_goals'_core gs ac progress) do\n      set_goals [g]\n      let succeeded \u2190 try_core tac\n      let new_gs \u2190 get_goals\n      any_goals'_core gs (ac ++ new_gs) (succeeded || progress)\n#align tactic.any_goals'_core tactic.any_goals'_core\n\n/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if\n   tac succeeds for at least one goal. -/\nunsafe def any_goals' (tac : tactic Unit) : tactic Unit := do\n  let gs \u2190 get_goals\n  any_goals'_core tac gs [] ff\n#align tactic.any_goals' tactic.any_goals'\n\n/-- LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies\n`tac2` to each goal produced by `tac1`.\n-/\nunsafe def seq {\u03b1 \u03b2} (tac1 : tactic \u03b1) (tac2 : \u03b1 \u2192 tactic \u03b2) : tactic (List \u03b2) := do\n  let g :: gs \u2190 get_goals\n  set_goals [g]\n  let a \u2190 tac1\n  let bs \u2190 all_goals <| tac2 a\n  let gs' \u2190 get_goals\n  set_goals (gs' ++ gs)\n  pure bs\n#align tactic.seq tactic.seq\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 : tactic Unit) (tac2 : tactic Unit) : tactic Unit := do\n  let g :: gs \u2190 get_goals\n  set_goals [g]\n  tac1\n  all_goals' tac2\n  let gs' \u2190 get_goals\n  set_goals (gs' ++ gs)\n#align tactic.seq' tactic.seq'\n\n/-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to\none of the produced subgoals (like `focus'`).\n-/\nunsafe def seq_focus {\u03b1 \u03b2} (tac1 : tactic \u03b1) (tacs2 : \u03b1 \u2192 List (tactic \u03b2)) : tactic (List \u03b2) := do\n  let g :: gs \u2190 get_goals\n  set_goals [g]\n  let a \u2190 tac1\n  let bs \u2190 focus <| tacs2 a\n  let gs' \u2190 get_goals\n  set_goals (gs' ++ gs)\n  pure bs\n#align tactic.seq_focus tactic.seq_focus\n\n/-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to\none of the produced subgoals (like `focus`).\n-/\nunsafe def seq_focus' (tac1 : tactic Unit) (tacs2 : List (tactic Unit)) : tactic Unit := do\n  let g :: gs \u2190 get_goals\n  set_goals [g]\n  tac1\n  focus tacs2\n  let gs' \u2190 get_goals\n  set_goals (gs' ++ gs)\n#align tactic.seq_focus' tactic.seq_focus'\n\nunsafe instance andthen_seq : AndThen' (tactic Unit) (tactic Unit) (tactic Unit) :=\n  \u27e8seq'\u27e9\n#align tactic.andthen_seq tactic.andthen_seq\n\nunsafe instance andthen_seq_focus : AndThen' (tactic Unit) (List (tactic Unit)) (tactic Unit) :=\n  \u27e8seq_focus'\u27e9\n#align tactic.andthen_seq_focus tactic.andthen_seq_focus\n\nunsafe axiom is_trace_enabled_for : Name \u2192 Bool\n#align tactic.is_trace_enabled_for tactic.is_trace_enabled_for\n\n/-- Execute tac only if option trace.n is set to true. -/\nunsafe def when_tracing (n : Name) (tac : tactic Unit) : tactic Unit :=\n  when (is_trace_enabled_for n = true) tac\n#align tactic.when_tracing tactic.when_tracing\n\n/-- Fail if there are no remaining goals. -/\nunsafe def fail_if_no_goals : tactic Unit := do\n  let n \u2190 num_goals\n  when (n = 0) (fail \"tactic failed, there are no goals to be solved\")\n#align tactic.fail_if_no_goals tactic.fail_if_no_goals\n\n/-- Fail if there are unsolved goals. -/\nunsafe def done : tactic Unit := do\n  let n \u2190 num_goals\n  when (n \u2260 0) (fail \"done tactic failed, there are unsolved goals\")\n#align tactic.done tactic.done\n\nunsafe def apply_opt_param : tactic Unit := do\n  let q(optParam $(t) $(v)) \u2190 target\n  exact v\n#align tactic.apply_opt_param tactic.apply_opt_param\n\nunsafe def apply_auto_param : tactic Unit := do\n  let q(autoParam $(type) $(tac_name_expr)) \u2190 target\n  change type\n  let tac_name \u2190 eval_expr Name tac_name_expr\n  let tac \u2190 eval_expr (tactic Unit) (expr.const tac_name [])\n  tac\n#align tactic.apply_auto_param tactic.apply_auto_param\n\nunsafe def has_opt_auto_param (ms : List expr) : tactic Bool :=\n  ms.foldlM\n    (fun r m => do\n      let type \u2190 infer_type m\n      return <| r || type `opt_param 2 || type `auto_param 2)\n    false\n#align tactic.has_opt_auto_param tactic.has_opt_auto_param\n\nunsafe def try_apply_opt_auto_param (cfg : ApplyCfg) (ms : List expr) : tactic Unit :=\n  when (cfg.autoParam\u2093 || cfg.optParam) <|\n    whenM (has_opt_auto_param ms) do\n      let gs \u2190 get_goals\n      ms fun m =>\n          whenM (not <$> is_assigned m) <|\n            (set_goals [m] >> when cfg (try apply_opt_param)) >> when cfg (try apply_auto_param)\n      set_goals gs\n#align tactic.try_apply_opt_auto_param tactic.try_apply_opt_auto_param\n\nunsafe def has_opt_auto_param_for_apply (ms : List (Name \u00d7 expr)) : tactic Bool :=\n  ms.foldlM\n    (fun r m => do\n      let type \u2190 infer_type m.2\n      return <| r || type `opt_param 2 || type `auto_param 2)\n    false\n#align tactic.has_opt_auto_param_for_apply tactic.has_opt_auto_param_for_apply\n\nunsafe def try_apply_opt_auto_param_for_apply (cfg : ApplyCfg) (ms : List (Name \u00d7 expr)) :\n    tactic Unit :=\n  whenM (has_opt_auto_param_for_apply ms) do\n    let gs \u2190 get_goals\n    ms fun m =>\n        whenM (not <$> is_assigned m.2) <|\n          (set_goals [m.2] >> when cfg (try apply_opt_param)) >> when cfg (try apply_auto_param)\n    set_goals gs\n#align tactic.try_apply_opt_auto_param_for_apply tactic.try_apply_opt_auto_param_for_apply\n\nunsafe def apply (e : expr) (cfg : ApplyCfg := { }) : tactic (List (Name \u00d7 expr)) := do\n  let r \u2190 apply_core e cfg\n  try_apply_opt_auto_param_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 \u00d7 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 \u00d7 expr)) :=\n  apply e { NewGoals := NewGoals.non_dep_only }\n#align tactic.eapply tactic.eapply\n\n/-- Try to solve the main goal using type class resolution. -/\nunsafe def apply_instance : tactic Unit := do\n  let tgt \u2190 target >>= instantiate_mvars\n  let b \u2190 is_class tgt\n  if b then mk_instance tgt >>= exact\n    else fail \"apply_instance tactic fail, target is not a type class\"\n#align tactic.apply_instance tactic.apply_instance\n\n/-- Create a list of universe meta-variables of the given size. -/\nunsafe def mk_num_meta_univs : Nat \u2192 tactic (List level)\n  | 0 => return []\n  | succ n => do\n    let l \u2190 mk_meta_univ\n    let ls \u2190 mk_num_meta_univs n\n    return (l :: ls)\n#align tactic.mk_num_meta_univs tactic.mk_num_meta_univs\n\n/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/\nunsafe def mk_const (c : Name) : tactic expr := do\n  let env \u2190 get_env\n  let decl \u2190 env.get c\n  let num := decl.univ_params.length\n  let ls \u2190 mk_num_meta_univs Num\n  return (expr.const c ls)\n#align tactic.mk_const tactic.mk_const\n\n/-- Apply the constant `c` -/\nunsafe def applyc (c : Name) (cfg : ApplyCfg := { }) : tactic Unit := do\n  let c \u2190 mk_const c\n  apply c cfg\n  skip\n#align tactic.applyc tactic.applyc\n\nunsafe def eapplyc (c : Name) : tactic Unit := do\n  let c \u2190 mk_const c\n  eapply c\n  skip\n#align tactic.eapplyc tactic.eapplyc\n\nunsafe def save_const_type_info (n : Name) {elab : Bool} (ref : expr elab) : tactic Unit :=\n  try do\n    let c \u2190 mk_const n\n    save_type_info c ref\n#align tactic.save_const_type_info tactic.save_const_type_info\n\n/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,\n   and return metavariable `?M : ?T`.\n   This action can be used to create a meta-variable when\n   we don't know its type at creation time -/\nunsafe def mk_mvar : tactic expr := do\n  let u \u2190 mk_meta_univ\n  let t \u2190 mk_meta_var (expr.sort u)\n  mk_meta_var t\n#align tactic.mk_mvar tactic.mk_mvar\n\n/-- Makes a sorry macro with a meta-variable as its type. -/\nunsafe def mk_sorry : tactic expr := do\n  let u \u2190 mk_meta_univ\n  let t \u2190 mk_meta_var (expr.sort u)\n  return <| expr.mk_sorry t\n#align tactic.mk_sorry tactic.mk_sorry\n\n/-- Closes the main goal using sorry. -/\nunsafe def admit : tactic Unit :=\n  target >>= exact \u2218 expr.mk_sorry\n#align tactic.admit tactic.admit\n\nunsafe def mk_local' (pp_name : Name) (bi : BinderInfo) (type : expr) : tactic expr := do\n  let uniq_name \u2190 mk_fresh_name\n  return <| expr.local_const uniq_name pp_name bi type\n#align tactic.mk_local' tactic.mk_local'\n\nunsafe def mk_local_def (pp_name : Name) (type : expr) : tactic expr :=\n  mk_local' pp_name BinderInfo.default type\n#align tactic.mk_local_def tactic.mk_local_def\n\nunsafe def mk_local_pis : expr \u2192 tactic (List expr \u00d7 expr)\n  | expr.pi n bi d b => do\n    let p \u2190 mk_local' n bi d\n    let (ps, r) \u2190 mk_local_pis (expr.instantiate_var b p)\n    return (p :: ps, r)\n  | e => return ([], e)\n#align tactic.mk_local_pis tactic.mk_local_pis\n\nprivate unsafe def get_pi_arity_aux : expr \u2192 tactic Nat\n  | expr.pi n bi d b => do\n    let m \u2190 mk_fresh_name\n    let l := expr.local_const m n bi d\n    let new_b \u2190 whnf (expr.instantiate_var b l)\n    let r \u2190 get_pi_arity_aux new_b\n    return (r + 1)\n  | e => return 0\n#align tactic.get_pi_arity_aux tactic.get_pi_arity_aux\n\n/-- Compute the arity of the given (Pi-)type -/\nunsafe def get_pi_arity (type : expr) : tactic Nat :=\n  whnf type >>= get_pi_arity_aux\n#align tactic.get_pi_arity tactic.get_pi_arity\n\n/-- Compute the arity of the given function -/\nunsafe def get_arity (fn : expr) : tactic Nat :=\n  infer_type fn >>= get_pi_arity\n#align tactic.get_arity tactic.get_arity\n\nunsafe def triv : tactic Unit :=\n  mk_const `trivial >>= exact\n#align tactic.triv tactic.triv\n\nunsafe def by_contradiction (H : Name) : tactic expr := do\n  let tgt \u2190 target\n  let tgt_wh \u2190 whnf tgt reducible\n  -- to ensure that `not` in `ne` is found\n          match_not\n          tgt_wh $>\n        () <|>\n      (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply) >> skip <|>\n        (mk_mapp `classical.by_contradiction [some tgt] >>= eapply) >> skip <|>\n          fail \"tactic by_contradiction failed, target is not a proposition\"\n  intro H\n#align tactic.by_contradiction tactic.by_contradiction\n\nprivate unsafe def generalizes_aux (md : Transparency) : List expr \u2192 tactic Unit\n  | [] => skip\n  | e :: es => generalize e `x md >> generalizes_aux es\n#align tactic.generalizes_aux tactic.generalizes_aux\n\nunsafe def generalizes (es : List expr) (md := semireducible) : tactic Unit :=\n  generalizes_aux md es\n#align tactic.generalizes tactic.generalizes\n\nprivate unsafe def kdependencies_core (e : expr) (md : Transparency) :\n    List expr \u2192 List expr \u2192 tactic (List expr)\n  | [], r => return r\n  | h :: hs, r => do\n    let type \u2190 infer_type h\n    let d \u2190 kdepends_on type e md\n    if d then kdependencies_core hs (h :: r) else kdependencies_core hs r\n#align tactic.kdependencies_core tactic.kdependencies_core\n\n/-- Return all hypotheses that depends on `e`\n    The dependency test is performed using `kdepends_on` with the given transparency setting. -/\nunsafe def kdependencies (e : expr) (md := reducible) : tactic (List expr) := do\n  let ctx \u2190 local_context\n  kdependencies_core e md ctx []\n#align tactic.kdependencies tactic.kdependencies\n\n/-- Revert all hypotheses that depend on `e` -/\nunsafe def revert_kdependencies (e : expr) (md := reducible) : tactic Nat :=\n  kdependencies e md >>= revert_lst\n#align tactic.revert_kdependencies tactic.revert_kdependencies\n\nunsafe def revert_kdeps (e : expr) (md := reducible) :=\n  revert_kdependencies e md\n#align tactic.revert_kdeps tactic.revert_kdeps\n\n/-- Postprocess the output of `cases_core`:\n\n- The third component of each tuple in the input list (the list of\n  substitutions) is dropped since we don't use it anywhere.\n- The second component (the list of new hypotheses) is filtered: any expression\n  that is not a local constant is dropped. We only use the new hypotheses for\n  the renaming functionality of `case`, so we want to keep only those\n  \"new hypotheses\" that are, in fact, local constants. -/\nprivate unsafe def cases_postprocess (hs : List (Name \u00d7 List expr \u00d7 List (Name \u00d7 expr))) :\n    List (Name \u00d7 List expr) :=\n  hs.map fun \u27e8n, hs, _\u27e9 => (n, hs.filter\u2093 fun h => h.is_local_constant)\n#align tactic.cases_postprocess tactic.cases_postprocess\n\n/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.\n    Remark, it reverts dependencies using `revert_kdeps`.\n\n    Two different transparency modes are used `md` and `dmd`.\n    The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`.\n\n    It returns the constructor names associated with each new goal and the newly\n    introduced hypotheses. Note that while `cases_core` may return \"new\n    hypotheses\" that are not local constants, this tactic only returns local\n    constants.\n-/\nunsafe def cases (e : expr) (ids : List Name := []) (md := semireducible) (dmd := semireducible) :\n    tactic (List (Name \u00d7 List expr)) :=\n  if e.is_local_constant then do\n    let r \u2190 cases_core e ids md\n    return <| cases_postprocess r\n  else do\n    let n \u2190 revert_kdependencies e dmd\n    let x \u2190 get_unused_name\n    tactic.generalize e x dmd <|> do\n        let t \u2190 infer_type e\n        tactic.assertv x t e\n        get_local x >>= tactic.revert\n        return ()\n    let h \u2190 tactic.intro1\n    focus1 do\n        let r \u2190 cases_core h ids md\n        let hs' \u2190 all_goals (intron' n)\n        return <| cases_postprocess <| r (fun \u27e8n, hs, x\u27e9 hs' => (n, hs ++ hs', x)) hs'\n#align tactic.cases tactic.cases\n\n/-- The same as `exact` except you can add proof holes. -/\nunsafe def refine (e : pexpr) : tactic Unit := do\n  let tgt : expr \u2190 target\n  to_expr ``(($(e) : $(tgt))) tt >>= exact\n#align tactic.refine tactic.refine\n\n/-- `by_cases p h` splits the main goal into two cases, assuming `h : p` in the\nfirst branch, and `h : \u00ac p` in the second branch. The expression `p` needs to\nbe a proposition.\n\nThe produced proof term is `dite p ?m_1 ?m_2`.\n-/\nunsafe def by_cases (e : expr) (h : Name) : tactic Unit := do\n  let dec_e \u2190 mk_app `` Decidable [e] <|> fail \"by_cases tactic failed, type is not a proposition\"\n  let inst \u2190 mk_instance dec_e <|> pure q(Classical.propDecidable $(e))\n  let tgt \u2190 target\n  let expr.sort tgt_u \u2190 infer_type tgt >>= whnf\n  let g1 \u2190 mk_meta_var (e.imp tgt)\n  let g2 \u2190 mk_meta_var (q(\u00ac$(e)).imp tgt)\n  focus1 do\n      exact <| expr.const `` dite [tgt_u] tgt e inst g1 g2\n      set_goals [g1, g2]\n      all_goals' <| intro h >> skip\n#align tactic.by_cases tactic.by_cases\n\nunsafe def funext_core : List Name \u2192 Bool \u2192 tactic Unit\n  | [], tt => return ()\n  | ids, only_ids =>\n    try do\n      let some (lhs, rhs) \u2190 expr.is_eq <$> (target >>= whnf)\n      applyc `funext\n      let id \u2190\n        if ids.Empty \u2228 ids.headI = `_ then do\n            let expr.lam n _ _ _ \u2190 whnf lhs |\n              pure `_\n            return n\n          else return ids.headI\n      intro id\n      funext_core ids only_ids\n#align tactic.funext_core tactic.funext_core\n\nunsafe def funext : tactic Unit :=\n  funext_core [] false\n#align tactic.funext tactic.funext\n\nunsafe def funext_lst (ids : List Name) : tactic Unit :=\n  funext_core ids true\n#align tactic.funext_lst tactic.funext_lst\n\nprivate unsafe def get_undeclared_const (env : environment) (base : Name) : \u2115 \u2192 Name\n  | i =>\n    let n := .str base (\"_aux_\" ++ repr i)\n    if \u00acenv.contains n then n else get_undeclared_const (i + 1)\n#align tactic.get_undeclared_const tactic.get_undeclared_const\n\nunsafe def new_aux_decl_name : tactic Name := do\n  let env \u2190 get_env\n  let n \u2190 decl_name\n  return <| get_undeclared_const env n 1\n#align tactic.new_aux_decl_name tactic.new_aux_decl_name\n\nprivate unsafe def mk_aux_decl_name : Option Name \u2192 tactic Name\n  | none => new_aux_decl_name\n  | some suffix => do\n    let p \u2190 decl_name\n    return <| p ++ suffix\n#align tactic.mk_aux_decl_name tactic.mk_aux_decl_name\n\nunsafe def abstract (tac : tactic Unit) (suffix : Option Name := none) (zeta_reduce := true) :\n    tactic Unit := do\n  fail_if_no_goals\n  let gs \u2190 get_goals\n  let type \u2190 if zeta_reduce then target >>= zeta else target\n  let is_lemma \u2190 is_prop type\n  let m \u2190 mk_meta_var type\n  set_goals [m]\n  tac\n  let n \u2190 num_goals\n  when (n \u2260 0) (fail \"abstract tactic failed, there are unsolved goals\")\n  set_goals gs\n  let val \u2190 instantiate_mvars m\n  let val \u2190 if zeta_reduce then zeta val else return val\n  let c \u2190 mk_aux_decl_name suffix\n  let e \u2190 add_aux_decl c type val is_lemma\n  exact e\n#align tactic.abstract tactic.abstract\n\n/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/\nunsafe def solve_aux {\u03b1 : Type} (type : expr) (tac : tactic \u03b1) : tactic (\u03b1 \u00d7 expr) := do\n  let m \u2190 mk_meta_var type\n  let gs \u2190 get_goals\n  set_goals [m]\n  let a \u2190 tac\n  set_goals gs\n  return (a, m)\n#align tactic.solve_aux tactic.solve_aux\n\n/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/\nunsafe def in_open_namespaces (d : Name) : tactic Bool := do\n  let ns \u2190 open_namespaces\n  let env \u2190 get_env\n  return <| (ns fun n => n d) && env d\n#align tactic.in_open_namespaces tactic.in_open_namespaces\n\n/-- Execute tac for 'max' \"heartbeats\". The heartbeat is approx. the maximum number of\n    memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting\n    long running tactics. -/\nunsafe def try_for {\u03b1} (max : Nat) (tac : tactic \u03b1) : tactic \u03b1 := fun s =>\n  match _root_.try_for max (tac s) with\n  | some r => r\n  | none => mk_exception \"try_for tactic failed, timeout\" none s\n#align tactic.try_for tactic.try_for\n\n/-- Execute `tac` for `max` milliseconds. Useful due to variance\n    in the number of heartbeats taken by various tactics. -/\nunsafe def try_for_time {\u03b1} (max : Nat) (tac : tactic \u03b1) : tactic \u03b1 := fun s =>\n  match _root_.try_for_time max (tac s) with\n  | some r => r\n  | none => mk_exception \"try_for_time tactic failed, timeout\" none s\n#align tactic.try_for_time tactic.try_for_time\n\nunsafe def updateex_env (f : environment \u2192 exceptional environment) : tactic Unit := do\n  let env \u2190 get_env\n  let env \u2190 returnex <| f env\n  set_env env\n#align tactic.updateex_env tactic.updateex_env\n\n/-- Add a new inductive datatype to the environment\n   name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/\nunsafe def add_inductive (n : Name) (ls : List Name) (p : Nat) (ty : expr) (is : List (Name \u00d7 expr))\n    (is_meta : Bool := false) : tactic Unit :=\n  updateex_env fun e => e.add_inductive n ls p ty is is_meta\n#align tactic.add_inductive tactic.add_inductive\n\nunsafe def add_meta_definition (n : Name) (lvls : List Name) (type value : expr) : tactic Unit :=\n  add_decl (declaration.defn n lvls type value ReducibilityHints.abbrev false)\n#align tactic.add_meta_definition tactic.add_meta_definition\n\n/-- add declaration `d` as a protected declaration -/\nunsafe def add_protected_decl (d : declaration) : tactic Unit :=\n  updateex_env fun e => e.add_protected d\n#align tactic.add_protected_decl tactic.add_protected_decl\n\n/-- check if `n` is the name of a protected declaration -/\nunsafe def is_protected_decl (n : Name) : tactic Bool := do\n  let env \u2190 get_env\n  return <| env n\n#align tactic.is_protected_decl tactic.is_protected_decl\n\n/-- `add_defn_equations` adds a definition specified by a list of equations.\n\n  The arguments:\n    * `lp`: list of universe parameters\n    * `params`: list of parameters (binders before the colon);\n    * `fn`: a local constant giving the name and type of the declaration\n      (with `params` in the local context);\n    * `eqns`: a list of equations, each of which is a list of patterns\n      (constructors applied to new local constants) and the branch\n      expression;\n    * `is_meta`: is the definition meta?\n\n\n  `add_defn_equations` can be used as:\n\n      do my_add \u2190 mk_local_def `my_add `(\u2115 \u2192 \u2115),\n          a \u2190 mk_local_def `a \u2115,\n          b \u2190 mk_local_def `b \u2115,\n          add_defn_equations [a] my_add\n              [ ([``(nat.zero)], a),\n                ([``(nat.succ %%b)], my_add b) ])\n              ff -- non-meta\n\n  to create the following definition:\n\n      def my_add (a : \u2115) : \u2115 \u2192 \u2115\n      | nat.zero := a\n      | (nat.succ b) := my_add b\n-/\nunsafe def add_defn_equations (lp : List Name) (params : List expr) (fn : expr)\n    (eqns : List (List pexpr \u00d7 expr)) (is_meta : Bool) : tactic Unit := do\n  let opt \u2190 get_options\n  updateex_env fun e => e opt lp params fn eqns is_meta\n#align tactic.add_defn_equations tactic.add_defn_equations\n\n/-- Get the revertible part of the local context. These are the hypotheses that\nappear after the last frozen local instance in the local context. We call them\nrevertible because `revert` can revert them, unlike those hypotheses which occur\nbefore a frozen instance. -/\nunsafe def revertible_local_context : tactic (List expr) := do\n  let ctx \u2190 local_context\n  let frozen \u2190 frozen_local_instances\n  pure <|\n      match frozen with\n      | none => ctx\n      | some [] => ctx\n      | some (h :: _) => ctx (Eq h)\n#align tactic.revertible_local_context tactic.revertible_local_context\n\n/-- Rename local hypotheses according to the given `name_map`. The `name_map`\ncontains as keys those hypotheses that should be renamed; the associated values\nare the new names.\n\nThis tactic can only rename hypotheses which occur after the last frozen local\ninstance. If you need to rename earlier hypotheses, try\n`unfreezing (rename_many ...)`.\n\nIf `strict` is true, we fail if `name_map` refers to hypotheses that do not\nappear in the local context or that appear before a frozen local instance.\nConversely, if `strict` is false, some entries of `name_map` may be silently\nignored.\n\nIf `use_unique_names` is true, the keys of `name_map` should be the unique names\nof hypotheses to be renamed. Otherwise, the keys should be display names.\n\nNote that we allow shadowing, so renamed hypotheses may have the same name\nas other hypotheses in the context. If `use_unique_names` is false and there are\nmultiple hypotheses with the same display name in the context, they are all\nrenamed.\n-/\nunsafe def rename_many (renames : name_map Name) (strict := true) (use_unique_names := false) :\n    tactic Unit := do\n  let hyp_name : expr \u2192 Name :=\n    if use_unique_names then expr.local_uniq_name else expr.local_pp_name\n  let ctx \u2190 revertible_local_context\n  let-- The part of the context after (but including) the first hypthesis that\n  -- must be renamed.\n  ctx_suffix := ctx.dropWhile\u2093 fun h => (renames.find <| hyp_name h).isNone\n  when strict do\n      let ctx_names := rb_map.set_of_list (ctx_suffix hyp_name)\n      let invalid_renames := (renames Prod.fst).filter\u2093 fun h => \u00acctx_names h\n      when \u00acinvalid_renames <|\n          fail <|\n            format.join\n              [\"Cannot rename these hypotheses:\\n\",\n                format.join <| (invalid_renames to_fmt).intersperse \", \", 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 `unfreezingI { ... }`.\"]\n  let-- The new names for all hypotheses in ctx_suffix.\n  new_names := ctx_suffix.map fun h => (renames.find <| hyp_name h).getD h.local_pp_name\n  revert_lst ctx_suffix\n  intro_lst new_names\n  pure ()\n#align tactic.rename_many tactic.rename_many\n\n/-- Rename a local hypothesis. This is a special case of `rename_many`;\nsee there for caveats.\n-/\nunsafe def rename (curr : Name) (new : Name) : tactic Unit :=\n  rename_many (rb_map.of_list [\u27e8curr, new\u27e9])\n#align tactic.rename tactic.rename\n\n/-- Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does\nnot preserve the order of hypotheses. Its implementation is simpler (and\ntherefore probably faster) than that of `rename`.\n-/\nunsafe def rename_unstable (curr : Name) (new : Name) : tactic Unit := do\n  let h \u2190 get_local curr\n  let n \u2190 revert h\n  intro new\n  intron (n - 1)\n#align tactic.rename_unstable tactic.rename_unstable\n\n/-- \"Replace\" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof\nthat (type = new_type). The tactic actually creates a new hypothesis\nwith the same user facing name, and (tries to) clear `h`.\nThe `clear` step fails if `h` has forward dependencies. In this case, the old `h`\nwill remain in the local context. The tactic returns the new hypothesis. -/\nunsafe def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) (tag : Name := `unit.star) :\n    tactic expr := do\n  let h_type \u2190 infer_type h\n  let new_h \u2190 assert h.local_pp_name new_type\n  let eq_pr_type \u2190 mk_app `eq [h_type, new_type]\n  let eq_pr := mk_tagged_proof eq_pr_type eq_pr tag\n  mk_eq_mp eq_pr h >>= exact\n  try <| clear h\n  return new_h\n#align tactic.replace_hyp tactic.replace_hyp\n\nunsafe def main_goal : tactic expr := do\n  let g :: gs \u2190 get_goals\n  return g\n#align tactic.main_goal tactic.main_goal\n\n/-! Goal tagging support -/\n\n\nunsafe def with_enable_tags {\u03b1 : Type} (t : tactic \u03b1) (b := true) : tactic \u03b1 := do\n  let old \u2190 tags_enabled\n  enable_tags b\n  let r \u2190 t\n  enable_tags old\n  return r\n#align tactic.with_enable_tags tactic.with_enable_tags\n\nunsafe def get_main_tag : tactic Tag :=\n  main_goal >>= get_tag\n#align tactic.get_main_tag tactic.get_main_tag\n\nunsafe def set_main_tag (t : Tag) : tactic Unit := do\n  let g \u2190 main_goal\n  set_tag g t\n#align tactic.set_main_tag tactic.set_main_tag\n\nunsafe def subst (h : expr) : tactic Unit :=\n  (do\n      guard h\n      let some (\u03b1, lhs, \u03b2, rhs) \u2190 expr.is_heq <$> infer_type h\n      is_def_eq \u03b1 \u03b2\n      let new_h_type \u2190 mk_app `eq [lhs, rhs]\n      let new_h_pr \u2190 mk_app `eq_of_heq [h]\n      let new_h \u2190 assertv h.local_pp_name new_h_type new_h_pr\n      try (clear h)\n      subst_core new_h) <|>\n    subst_core h\n#align tactic.subst tactic.subst\n\nend Tactic\n\nopen Tactic\n\nnamespace List\n\nunsafe def for_each {\u03b1} : List \u03b1 \u2192 (\u03b1 \u2192 tactic Unit) \u2192 tactic Unit\n  | [], fn => skip\n  | e :: es, fn => do\n    fn e\n    for_each es fn\n#align list.for_each list.for_each\n\nunsafe def any_of {\u03b1 \u03b2} : List \u03b1 \u2192 (\u03b1 \u2192 tactic \u03b2) \u2192 tactic \u03b2\n  | [], fn => failed\n  | e :: es, fn => do\n    let opt_b \u2190 try_core (fn e)\n    match opt_b with\n      | some b => return b\n      | none => any_of es fn\n#align list.any_of list.any_of\n\nend List\n\n/-! Install monad laws tactic and use it to prove some instances. -/\n\n\n/-- Try to prove with `iff.refl`.-/\nunsafe def order_laws_tac :=\n  (whnf_target >> intros) >> to_expr ``(Iff.refl _) >>= exact\n#align order_laws_tac order_laws_tac\n\nunsafe def monad_from_pure_bind {m : Type u \u2192 Type v} (pure : \u2200 {\u03b1 : Type u}, \u03b1 \u2192 m \u03b1)\n    (bind : \u2200 {\u03b1 \u03b2 : Type u}, m \u03b1 \u2192 (\u03b1 \u2192 m \u03b2) \u2192 m \u03b2) : Monad m\n    where\n  pure := @pure\n  bind := @bind\n#align monad_from_pure_bind monad_from_pure_bind\n\nunsafe instance : Monad task where\n  map := @task.map\n  bind := @task.bind\n  pure := @task.pure\n\nnamespace Tactic\n\nunsafe def replace_target (new_target : expr) (pr : expr) (tag : Name := `unit.star) :\n    tactic Unit := do\n  let t \u2190 target\n  assert `htarget new_target\n  swap\n  let ht \u2190 get_local `htarget\n  let pr_type \u2190 mk_app `eq [t, new_target]\n  let locked_pr := mk_tagged_proof pr_type pr tag\n  mk_eq_mpr locked_pr ht >>= exact\n#align tactic.replace_target tactic.replace_target\n\nunsafe def eval_pexpr (\u03b1) [reflected _ \u03b1] (e : pexpr) : tactic \u03b1 :=\n  to_expr ``(($(e) : $(reflect \u03b1))) false false >>= eval_expr \u03b1\n#align tactic.eval_pexpr tactic.eval_pexpr\n\nunsafe def run_simple {\u03b1} : tactic_state \u2192 tactic \u03b1 \u2192 Option \u03b1\n  | ts, t =>\n    match t ts with\n    | interaction_monad.result.success a ts' => some a\n    | interaction_monad.result.exception _ _ _ => none\n#align tactic.run_simple tactic.run_simple\n\nend Tactic\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/Tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2068940488158881, "lm_q2_score": 0.055823141920008715, "lm_q1q2_score": 0.011549475849454533}}
{"text": "import Duper.MClause\nimport Duper.RuleM\nimport Duper.Simp\nimport Duper.Util.ProofReconstruction\n\nnamespace Duper\nopen Lean\nopen Meta\nopen RuleM\nopen SimpResult\n\ninitialize Lean.registerTraceClass `Rule.neHoist\n\ntheorem ne_hoist_proof (x y : \u03b1) (f : Prop \u2192 Prop) (h : f (x \u2260 y)) : f True \u2228 x = y := by\n  by_cases x_eq_y : x = y\n  . exact Or.inr x_eq_y\n  . rename \u00acx = y => x_ne_y\n    have x_ne_y_true := eq_true x_ne_y\n    exact Or.inl $ x_ne_y_true \u25b8 h\n\ndef mkNeHoistProof (pos : ClausePos) (freshVar1 freshVar2 : Expr) (premises : List Expr)\n  (parents : List ProofParent) (transferExprs : Array Expr) (c : Clause) : MetaM Expr :=\n  Meta.forallTelescope c.toForallExpr fun xs body => do\n    let cLits := c.lits.map (fun l => l.map (fun e => e.instantiateRev xs))\n    let (parentsLits, appliedPremises, transferExprs) \u2190 instantiatePremises parents premises xs transferExprs\n    let parentLits := parentsLits[0]!\n    let appliedPremise := appliedPremises[0]!\n\n    let mut caseProofs := Array.mkEmpty parentLits.size\n    for i in [:parentLits.size] do\n      let lit := parentLits[i]!\n      let pr : Expr \u2190 Meta.withLocalDeclD `h lit.toExpr fun h => do\n        if i == pos.lit then\n          let substLitPos : LitPos := \u27e8pos.side, pos.pos\u27e9\n          let abstrLit \u2190 (lit.abstractAtPos! substLitPos)\n          let abstrExp := abstrLit.toExpr\n          let abstrLam := mkLambda `x BinderInfo.default (mkSort levelZero) abstrExp\n          let lastTwoClausesProof \u2190 Meta.mkAppM ``ne_hoist_proof #[freshVar1, freshVar2, abstrLam, h]\n          Meta.mkLambdaFVars #[h] $ \u2190 orSubclause (cLits.map Lit.toExpr) 2 lastTwoClausesProof\n        else\n          let idx := if i \u2265 pos.lit then i - 1 else i\n          Meta.mkLambdaFVars #[h] $ \u2190 orIntro (cLits.map Lit.toExpr) idx h\n      caseProofs := caseProofs.push pr\n    let r \u2190 orCases (parentLits.map Lit.toExpr) caseProofs\n    Meta.mkLambdaFVars xs $ mkApp r appliedPremise\n\ndef neHoistAtExpr (e : Expr) (pos : ClausePos) (given : Clause) (c : MClause) : RuleM (Array ClauseStream) :=\n  withoutModifyingMCtx do\n    let lit := c.lits[pos.lit]!\n    if e.getTopSymbol.isMVar then -- Check condition 4\n      -- If the head of e is a variable then it must be applied and the affected literal must be either\n      -- e = True, e = False, or e = e' where e' is another variable headed term\n      if not e.isApp then -- e is a non-applied variable and so we cannot apply neHoist\n        return #[]\n      if pos.pos != #[] then\n        return #[] -- e is not at the top level so the affected literal cannot have the form e = ...\n      if not lit.sign then\n        return #[] -- The affected literal is not positive and so it cannot have the form e = ...\n      let otherSide := lit.getOtherSide pos.side\n      if otherSide != (mkConst ``True) && otherSide != (mkConst ``False) && not otherSide.getTopSymbol.isMVar then\n        return #[] -- The other side is not True, False, or variable headed, so the affected literal cannot have the required form\n    -- Check conditions 1 and 3 (condition 2 is guaranteed by construction)\n    let eligibility \u2190 eligibilityPreUnificationCheck c pos.lit\n    if eligibility == Eligibility.notEligible then\n      return #[]\n    -- Make freshVars, freshVarInequality, and freshVarEquality\n    let freshVar1 \u2190 mkFreshExprMVar none\n    let freshVarTy \u2190 inferType freshVar1\n    let freshVar2 \u2190 mkFreshExprMVar freshVarTy\n    let freshVarInequality \u2190 mkAppM ``Ne #[freshVar1, freshVar2]\n    let freshVarEquality \u2190 mkAppM ``Eq #[freshVar1, freshVar2]\n    -- Perform unification\n    let ug \u2190 unifierGenerator #[(e, freshVarInequality)]\n    let loaded \u2190 getLoadedClauses\n    let yC := do\n      setLoadedClauses loaded\n      if not $ \u2190 eligibilityPostUnificationCheck c pos.lit eligibility (strict := lit.sign) then\n        return none\n      let eSide \u2190 instantiateMVars $ lit.getSide pos.side\n      let otherSide \u2190 instantiateMVars $ lit.getOtherSide pos.side\n      let cmp \u2190 compare eSide otherSide\n      if cmp == Comparison.LessThan || cmp == Comparison.Equal then -- If eSide \u2264 otherSide then e is not in an eligible position\n        return none\n      -- All side conditions have been met. Yield the appropriate clause\n      let cErased := c.eraseLit pos.lit\n      -- Need to instantiate mvars in freshVar1, freshVar2, and freshVarEquality because unification assigned to mvars in each of them\n      let freshVar1 \u2190 instantiateMVars freshVar1\n      let freshVar2 \u2190 instantiateMVars freshVar2\n      let freshVarEquality \u2190 instantiateMVars freshVarEquality \n      let newClause := cErased.appendLits #[\u2190 lit.replaceAtPos! \u27e8pos.side, pos.pos\u27e9 (mkConst ``True), Lit.fromExpr freshVarEquality]\n      trace[Rule.neHoist] \"Created {newClause.lits} from {c.lits}\"\n      yieldClause newClause \"neHoist\" $ some (mkNeHoistProof pos freshVar1 freshVar2)\n    return #[ClauseStream.mk ug given yC \"neHoist\"]\n\ndef neHoist (given : Clause) (c : MClause) (cNum : Nat) : RuleM (Array ClauseStream) := do\n  trace[Rule.neHoist] \"Running NeHoist on {c.lits}\"\n  let fold_fn := fun streams e pos => do\n    let str \u2190 neHoistAtExpr e.consumeMData pos given c\n    return streams.append str\n  c.foldGreenM fold_fn #[]", "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/Rules/NeHoist.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.02635535208136987, "lm_q1q2_score": 0.01153899246865212}}
{"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.Tactic.Apply\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 \u2190 getMVarType mvarId\n  if let some (_, lhs, rhs) \u2190 matchEq? target then\n    if let some fvarId \u2190 findFVar? lhs then\n      return (\u2190 cases mvarId 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 (\u2190 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\nstructure MatchEqns where\n  eqnNames             : Array Name\n  splitterName         : Name\n  splitterAltNumParams : Array Nat\n  deriving Inhabited, Repr\n\nstructure MatchEqnsExtState where\n  map : Std.PHashMap Name MatchEqns := {}\n  deriving Inhabited\n\n/- We generate the equations and splitter on demand, and do not save them on .olean files. -/\nbuiltin_initialize matchEqnsExt : EnvExtension MatchEqnsExtState \u2190\n  registerEnvExtension (pure {})\n\nprivate def registerMatchEqns (matchDeclName : Name) (matchEqns : MatchEqns) : CoreM Unit :=\n  modifyEnv fun env => matchEqnsExt.modifyState env fun s => { s with map := s.map.insert matchDeclName matchEqns }\n\ndef unfoldNamedPattern (e : Expr) : MetaM Expr := do\n  let visit (e : Expr) : MetaM TransformStep := do\n    if e.isAppOfArity ``namedPattern 4 then\n      if let some eNew \u2190 unfoldDefinition? e then\n        return TransformStep.visit eNew\n    return TransformStep.visit e\n  Meta.transform e (pre := visit)\n\n/--\n  Similar to `forallTelescopeReducing`, but eliminates arguments for named parameters and the associated\n  equation proofs. The continuation `k` takes four arguments `ys args mask type`.\n  - `ys` are variables for the hypotheses that have not been eliminated.\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) (k : Array Expr \u2192 Array Expr \u2192 Array Bool \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  go #[] #[] #[] altType\nwhere\n  go (ys : Array Expr) (args : Array Expr) (mask : Array Bool) (type : Expr) : MetaM \u03b1 := do\n    let type \u2190 whnfForall type\n    match type with\n    | Expr.forallE n d b .. =>\n      let d \u2190 unfoldNamedPattern d\n      withLocalDeclD n d fun y => do\n        let typeNew := b.instantiate1 y\n        if let some (_, lhs, rhs) \u2190 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 mask    := mask.set! i false\n             let args    := args.map fun arg => if arg == lhs then rhs else arg\n             let args    := args.push (\u2190 mkEqRefl rhs)\n             let typeNew := typeNew.replaceFVar lhs rhs\n             return (\u2190 go ys args (mask.push false) typeNew)\n        go (ys.push y) (args.push y) (mask.push true) typeNew\n    | _ =>\n      let type \u2190 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 (\u2190 inferType ys[0]).isConstOf ``Unit && !(\u2190 dependsOn type ys[0].fvarId!) then\n          return (\u2190 k #[] #[mkConst ``Unit.unit] #[false] type)\n      k ys args mask type\n\n  isNamedPatternProof (type : Expr) (h : Expr) : Bool :=\n    Option.isSome <| type.find? fun e =>\n      e.isAppOfArity ``namedPattern 4 && e.appArg! == h\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 \u2192 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! (\u2190 get).xs.contains rhs\n  let (subst, mvarId) \u2190 substCore (\u2190 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 (\u2190 get).eqs.isEmpty\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-/\nprivate def trySubstVarsAndContradiction (mvarId : MVarId) : MetaM Bool :=\n  commitWhen do\n    let mvarId \u2190 substVars mvarId\n    contradictionCore mvarId {}\n\nprivate def processNextEq : M Bool := do\n  let s \u2190 get\n  withMVarContext s.mvarId do\n    -- If the goal is contradictory, the hypothesis is redundant.\n    if (\u2190 contradictionCore s.mvarId {}) then\n      return false\n    if let eq :: eqs := s.eqs then\n      modify fun s => { s with eqs }\n      let eqType \u2190 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) \u2190 matchEq? eqType then\n        if rhs.isFVar then\n          substRHS eq rhs.fvarId!\n          return true\n      if let some (\u03b1, lhs, \u03b2, rhs) \u2190 matchHEq? eqType then\n        -- Try to convert `HEq` into `Eq`\n        if (\u2190 isDefEq \u03b1 \u03b2) then\n          let (eqNew, mvarId) \u2190 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 if (\u2190 trySubstVarsAndContradiction s.mvarId) then\n          return false\n      try\n        -- Try to simplify equation using `injection` tactic.\n        match (\u2190 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 (\u2190 isDone) then\n    return true\n  else if (\u2190 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 does 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 \u2190 forallTelescope h fun ys _ => pure (ys.size - numEqs)\n  let mvarId := (\u2190 mkFreshExprSyntheticOpaqueMVar h).mvarId!\n  let (xs, mvarId) \u2190 introN mvarId numVars\n  let (eqs, mvarId) \u2190 introN mvarId numEqs\n  let (r, s) \u2190 SimpH.go |>.run { mvarId, xs := xs.toList, eqs := eqs.toList }\n  if r then\n    withMVarContext s.mvarId do\n      let vars := (s.xs ++ s.eqsNew.reverse).toArray.map mkFVar\n      let r \u2190 mkForallFVars vars (mkConst ``False)\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) := withMVarContext mvarId do\n  for localDecl in (\u2190 getLCtx) do\n    if let some (_, lhs, rhs) \u2190 matchEq? localDecl.type then\n      if lhs.isFVar then\n        if !(\u2190 dependsOn rhs lhs.fvarId!) then\n          match (\u2190 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 := do\n  let type \u2190 instantiateMVars type\n  withLCtx {} {} <| forallTelescope type fun ys target => do\n    let mvar0  \u2190 mkFreshExprSyntheticOpaqueMVar target\n    let mvarId \u2190 deltaTarget mvar0.mvarId! (. == matchDeclName)\n    trace[Meta.Match.matchEqs] \"{MessageData.ofGoal mvarId}\"\n    withDefault <| go mvarId 0\n    mkLambdaFVars ys (\u2190 instantiateMVars mvar0)\nwhere\n  go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do\n    let mvarId' \u2190 modifyTargetEqLHS mvarId whnfCore\n    let mvarId := mvarId'\n    let subgoals \u2190\n      (do applyRefl mvarId; return #[])\n      <|>\n      (do contradiction mvarId { genDiseq := true }; return #[])\n      <|>\n      (casesOnStuckLHS mvarId)\n      <|>\n      (do let mvarId' \u2190 simpIfTarget mvarId (useDecide := true)\n          if mvarId' == mvarId then throwError \"simpIf failed\"\n          return #[mvarId'])\n      <|>\n      (do if let some (s\u2081, s\u2082) \u2190 splitIfTarget? mvarId then\n            let mvarId\u2081 \u2190 trySubst s\u2081.mvarId s\u2081.fvarId\n            return #[mvarId\u2081, s\u2082.mvarId]\n          else\n            throwError \"spliIf failed\")\n      <|>\n      (substSomeVar mvarId)\n      <|>\n      (throwError \"failed to generate equality theorems for `match` expression\\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 \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let rec go (i : Nat) (xs : Array Expr) : MetaM \u03b1 := do\n    if h : i < altTypes.size then\n      let hName := (`h).appendIndexAfter (i+1)\n      withLocalDeclD hName (altTypes.get \u27e8i, h\u27e9) 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 injenctionAny (mvarId : MVarId) : MetaM InjectionAnyResult :=\n  withMVarContext mvarId do\n    for localDecl in (\u2190 getLCtx) do\n      if let some (_, lhs, rhs) \u2190 matchEq? localDecl.type then\n        unless (\u2190 isDefEq lhs rhs) do\n          let lhs \u2190 whnf lhs\n          let rhs \u2190 whnf rhs\n          unless lhs.isNatLit && rhs.isNatLit do\n            try\n              match (\u2190 injection mvarId localDecl.fvarId) with\n              | InjectionResult.solved  => return InjectionAnyResult.solved\n              | InjectionResult.subgoal mvarId .. => return InjectionAnyResult.subgoal mvarId\n            catch _ =>\n              pure ()\n    return InjectionAnyResult.failed\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    (altArgMasks : Array (Array Bool)) : MetaM Expr := do\n  trace[Meta.Match.matchEqs] \"proof template: {template}\"\n  let map := mkMap\n  let (proof, mvarIds) \u2190 convertTemplate 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 \u00d7 Array Bool) := Id.run <| do\n    let mut m := {}\n    for alt in alts, altNew in altsNew, argMask in altArgMasks do\n      m := m.insert alt.fvarId! (altNew, argMask)\n    return m\n\n  convertTemplate (m : FVarIdMap (Expr \u00d7 Array Bool)) : StateRefT (Array MVarId) MetaM Expr :=\n    transform template fun e => do\n      match e.getAppFn with\n      | Expr.fvar fvarId .. =>\n        match m.find? fvarId with\n        | some (altNew, argMask) =>\n          trace[Meta.Match.matchEqs] \">> {e}, {altNew}\"\n          let mut newArgs := #[]\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          let (mvars, _, _) \u2190 forallMetaTelescopeReducing (\u2190 inferType eNew) (kind := MetavarKind.syntheticOpaque)\n          modify fun s => s ++ (mvars.map (\u00b7.mvarId!))\n          let eNew := mkAppN eNew mvars\n          return TransformStep.done eNew\n        | none => return TransformStep.visit e\n      | _ => return TransformStep.visit e\n\n  proveSubgoalLoop (mvarId : MVarId) : MetaM Unit := do\n    if (\u2190 contradictionCore mvarId {}) then\n      return ()\n    match (\u2190 injenctionAny mvarId) with\n    | InjectionAnyResult.solved => return ()\n    | InjectionAnyResult.failed => throwError \"failed to generate splitter for match auxiliary declaration '{matchDeclName}', unsolved subgoal:\\n{MessageData.ofGoal mvarId}\"\n    | InjectionAnyResult.subgoal mvarId => proveSubgoalLoop mvarId\n\n  proveSubgoal (mvarId : MVarId) : MetaM Unit := do\n    trace[Meta.Match.matchEqs] \"subgoal {mkMVar mvarId}, {repr (\u2190 getMVarDecl mvarId).kind}, {\u2190 isExprMVarAssigned mvarId}\\n{MessageData.ofGoal mvarId}\"\n    let (_, mvarId) \u2190 intros mvarId\n    let mvarId \u2190 tryClearMany mvarId (alts.map (\u00b7.fvarId!))\n    proveSubgoalLoop mvarId\n\n/--\n  Create conditional equations and splitter for the given match auxiliary declaration. -/\nprivate partial def mkEquationsFor (matchDeclName : Name) :  MetaM MatchEqns :=\n  withConfig (fun c => { c with etaStruct := false }) do\n  let baseName := mkPrivateName (\u2190 getEnv) matchDeclName\n  let constInfo \u2190 getConstInfo matchDeclName\n  let us := constInfo.levelParams.map mkLevelParam\n  let some matchInfo \u2190 getMatcherInfo? matchDeclName | throwError \"'{matchDeclName}' is not a matcher function\"\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 alt in alts do\n      let thmName := baseName ++ ((`eq).appendIndexAfter idx)\n      eqnNames := eqnNames.push thmName\n      let (notAlt, splitterAltType, splitterAltNumParam, argMask) \u2190 forallAltTelescope (\u2190 inferType alt) fun ys rhsArgs argMask altResultType => do\n        let patterns := altResultType.getAppArgs\n        let mut hs := #[]\n        for notAlt in notAlts do\n          let h \u2190 instantiateForall notAlt patterns\n          if let some h \u2190 simpH? h patterns.size then\n            hs := hs.push h\n        trace[Meta.Match.matchEqs] \"hs: {hs}\"\n        let splitterAltType \u2190 mkForallFVars ys (\u2190 hs.foldrM (init := 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          if (\u2190 isDefEq (\u2190 inferType discr) (\u2190 inferType pattern)) then\n            notAlt \u2190 mkArrow (\u2190 mkEq discr pattern) notAlt\n          else\n            notAlt \u2190 mkArrow (\u2190 mkHEq discr pattern) notAlt\n        notAlt \u2190 mkForallFVars (discrs ++ ys) notAlt\n        let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts)\n        let rhs := mkAppN alt rhsArgs\n        let thmType \u2190 mkEq lhs rhs\n        let thmType \u2190 hs.foldrM (init := thmType) mkArrow\n        let thmType \u2190 mkForallFVars (params ++ #[motive] ++ alts ++ ys) thmType\n        let thmType \u2190 unfoldNamedPattern thmType\n        let thmVal \u2190 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 \u2190 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 \u2190 deltaExpand template (. == constInfo.name)\n      let splitterVal \u2190 mkLambdaFVars splitterParams (\u2190 mkSplitterProof matchDeclName template alts altsNew altArgMasks)\n      let splitterName := baseName ++ `splitter\n      addDecl <| Declaration.thmDecl {\n        name        := splitterName\n        levelParams := constInfo.levelParams\n        type        := splitterType\n        value       := splitterVal\n      }\n      let result := { eqnNames, splitterName, splitterAltNumParams }\n      registerMatchEqns matchDeclName result\n      return result\n\ndef getEquationsFor (matchDeclName : Name) : MetaM MatchEqns := do\n  match matchEqnsExt.getState (\u2190 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": "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/Match/MatchEqs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.035144844884912194, "lm_q1q2_score": 0.011515851606046738}}
{"text": "/-\nCopyright (c) 2022 Jo\u00ebl Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jo\u00ebl 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\u2080 d\u2081: A \u27f6 I) (\u03c3 : I \u27f6 A) [weq_\u03c3 : weak_eq \u03c3]\n(\u03c3d\u2080' : d\u2080 \u226b \u03c3 = \ud835\udfd9 A . obviously) (\u03c3d\u2081' : d\u2081 \u226b \u03c3 = \ud835\udfd9 A . obviously)\n\nnamespace precylinder\n\nvariables {A} (P : precylinder A)\n\nrestate_axiom \u03c3d\u2080'\nrestate_axiom \u03c3d\u2081'\nattribute [simp, reassoc] \u03c3d\u2080 \u03c3d\u2081\n\ninstance weq_\u03c3' : weak_eq P.\u03c3 := P.weq_\u03c3\ninstance weq_d\u2080 : weak_eq P.d\u2080 := weak_eq.of_comp_right P.d\u2080 P.\u03c3 infer_instance\n  (by { rw \u03c3d\u2080, apply_instance, })\ninstance weq_d\u2081 : weak_eq P.d\u2081 := weak_eq.of_comp_right P.d\u2081 P.\u03c3 infer_instance\n  (by { rw \u03c3d\u2081, apply_instance, })\n\n@[simps]\ndef change_I {I' : C} {f : P.I \u27f6 I'} {g : I' \u27f6 A} (fac : f \u226b g = P.\u03c3) [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\u2080 := P.d\u2080 \u226b f,\n    d\u2081 := P.d\u2081 \u226b f,\n    \u03c3 := g,\n    \u03c3d\u2080' := by { simp only [assoc, fac, \u03c3d\u2080], },\n    \u03c3d\u2081' := by { simp only [assoc, fac, \u03c3d\u2081], }, },\nend\n\n@[simp]\ndef \u03b9 := coprod.desc P.d\u2080 P.d\u2081\n\n@[simps]\ndef symm : precylinder A :=\n{ I := P.I,\n  d\u2080 := P.d\u2081,\n  d\u2081 := P.d\u2080,\n  \u03c3 := P.\u03c3, }\n\nend precylinder\n\nstructure cylinder extends precylinder A :=\n[cof_\u03b9 : cofibration to_precylinder.\u03b9]\n\nnamespace cylinder\n\nvariable {A}\n\ndef mk' (P : precylinder A) (h : cofibration P.\u03b9) : cylinder A :=\nby { haveI := h, exact mk P, }\n\nabbreviation pre (Q : cylinder A) := Q.to_precylinder\n\ninstance cof_\u03b9' (Q : cylinder A) : cofibration Q.pre.\u03b9 := Q.cof_\u03b9\n\nvariable (A)\n\ndef some : cylinder A :=\nbegin\n  let \u03c6 := coprod.desc (\ud835\udfd9 A) (\ud835\udfd9 A),\n  let P : precylinder A :=\n  { I := CM5b.obj \u03c6,\n    \u03c3 := CM5b.p \u03c6,\n    d\u2080 := coprod.inl \u226b CM5b.i \u03c6,\n    d\u2081 := coprod.inr \u226b CM5b.i \u03c6, },\n  apply mk' P,\n  rw [show P.\u03b9 = CM5b.i \u03c6, by tidy],\n  apply_instance,\nend\n\ninstance : fibration (some A).\u03c3 := 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) := \u27e8some A\u27e9\ninstance : inhabited (precylinder A) := \u27e8(some A).pre\u27e9\n\nvariables {A} (Q : cylinder A)\n\ninstance cof_d\u2080 [is_cofibrant A] : cofibration (Q.d\u2080) :=\nbegin\n  rw [show Q.d\u2080 = coprod.inl \u226b Q.pre.\u03b9, by simp only [precylinder.\u03b9, coprod.inl_desc]],\n  apply_instance,\nend\n\ninstance cof_d\u2081 [is_cofibrant A] : cofibration (Q.d\u2081) :=\nbegin\n  rw [show Q.d\u2081 = coprod.inr \u226b Q.pre.\u03b9, by simp only [precylinder.\u03b9, 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 \u226b Q.d\u2080),\n  apply_instance,\nend\n\n@[simps]\ndef symm : cylinder A := mk' Q.pre.symm\nbegin\n  have eq : Q.pre.symm.\u03b9 = (coprod.braiding A A).hom \u226b Q.pre.\u03b9,\n  { simp only [precylinder.\u03b9, precylinder.symm_d\u2080, precylinder.symm_d\u2081, 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 \u03c6 := pushout.desc Q.\u03c3 Q'.\u03c3 (by rw [Q.pre.\u03c3d\u2081, Q'.pre.\u03c3d\u2080]),\n  haveI : weak_eq \u03c6,\n  { apply weak_eq.of_comp_left (Q.d\u2080 \u226b pushout.inl),\n    { apply_instance, },\n    { simp only [assoc, pushout.inl_desc, precylinder.\u03c3d\u2080],\n      apply_instance, }, },\n  let P : precylinder A :=\n  { I := pushout Q.d\u2081 Q'.d\u2080,\n    d\u2080 := Q.d\u2080 \u226b pushout.inl,\n    d\u2081 := Q'.d\u2081 \u226b pushout.inr,\n    \u03c3 := \u03c6, },\n  apply mk' P,\n  let \u03c8 : Q.pre.I \u2a3f A \u27f6 P.I := coprod.desc pushout.inl (Q'.d\u2081 \u226b pushout.inr),\n  have eq : P.\u03b9 = (coprod.map Q.d\u2080 (\ud835\udfd9 A)) \u226b \u03c8,\n  { by simp only [precylinder.\u03b9, coprod.map_desc, id_comp], },\n  rw eq,\n  have fac : coprod.map Q.d\u2081 (\ud835\udfd9 A) \u226b \u03c8 = Q'.pre.\u03b9 \u226b pushout.inr,\n  { dsimp [\u03c8],\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\u2081 (coprod.inl \u226b Q'.pre.\u03b9)\n    (coprod.inl \u226b \u03c8) pushout.inr := by simpa only [precylinder.\u03b9, coprod.inl_desc]\n    using is_pushout.of_has_pushout Q.pre.d\u2081 Q'.pre.d\u2080,\n  haveI : cofibration \u03c8 := cofibration.direct_image\n    (is_pushout.of_bot sq fac (is_pushout.of_coprod_inl_with_id Q.d\u2081 A).flip),\n  apply_instance,\nend\n\nend cylinder\n\nstructure pre_path_object :=\n(I : C) (d\u2080 d\u2081: I \u27f6 B) (\u03c3 : B \u27f6 I) [weq_\u03c3 : weak_eq \u03c3]\n(d\u2080\u03c3' : \u03c3 \u226b d\u2080 = \ud835\udfd9 B . obviously) (d\u2081\u03c3' : \u03c3 \u226b d\u2081 = \ud835\udfd9 B . obviously)\n\nnamespace pre_path_object\n\nrestate_axiom d\u2080\u03c3'\nrestate_axiom d\u2081\u03c3'\nattribute [simp, reassoc] d\u2080\u03c3 d\u2081\u03c3\n\nvariables {B} (P : pre_path_object B)\n\ninstance : weak_eq P.\u03c3 := P.weq_\u03c3\n\n@[simps]\ndef op (P : pre_path_object B) : precylinder (op B) :=\nbegin\n  haveI : weak_eq P.\u03c3.op := weak_eq.op infer_instance,\n  exact\n  { I := op P.I,\n    d\u2080 := P.d\u2080.op,\n    d\u2081 := P.d\u2081.op,\n    \u03c3 := P.\u03c3.op,\n    \u03c3d\u2080' := by simp only [\u2190 op_comp, d\u2080\u03c3, op_id],\n    \u03c3d\u2081' := by simp only [\u2190 op_comp, d\u2081\u03c3, op_id], }\nend\n\n@[simps]\ndef unop {B : C\u1d52\u1d56} (P : pre_path_object B) : precylinder B.unop :=\nbegin\n  haveI : weak_eq P.\u03c3.unop := weak_eq.unop infer_instance,\n  exact\n  { I := unop P.I,\n    d\u2080 := P.d\u2080.unop,\n    d\u2081 := P.d\u2081.unop,\n    \u03c3 := P.\u03c3.unop,\n    \u03c3d\u2080' := by simp only [\u2190 unop_comp, d\u2080\u03c3, unop_id],\n    \u03c3d\u2081' := by simp only [\u2190 unop_comp, d\u2081\u03c3, 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.\u03c3.op := weak_eq.op infer_instance,\n  exact\n  { I := op P.I,\n    d\u2080 := P.d\u2080.op,\n    d\u2081 := P.d\u2081.op,\n    \u03c3 := P.\u03c3.op,\n    d\u2080\u03c3' := by simp only [\u2190 op_comp, \u03c3d\u2080, op_id],\n    d\u2081\u03c3' := by simp only [\u2190 op_comp, \u03c3d\u2081, op_id], }\nend\n\n@[simps]\ndef unop {A : C\u1d52\u1d56} (P : precylinder A) : pre_path_object (unop A) :=\nbegin\n  haveI : weak_eq P.\u03c3.unop := weak_eq.unop infer_instance,\n  exact\n  { I := unop P.I,\n    d\u2080 := P.d\u2080.unop,\n    d\u2081 := P.d\u2081.unop,\n    \u03c3 := P.\u03c3.unop,\n    d\u2080\u03c3' := by simp only [\u2190 unop_comp, \u03c3d\u2080, unop_id],\n    d\u2081\u03c3' := by simp only [\u2190 unop_comp, \u03c3d\u2081, unop_id], }\nend\n\nlemma unop_op (P : precylinder A) : P.op.unop = P := by { cases P, refl, }\nlemma op_unop {A : C\u1d52\u1d56} (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\u1d52\u1d56} (P : precylinder B) : P.unop.op = P := by { cases P, refl, }\n\ninstance weq_d\u2080 : weak_eq P.d\u2080 := weak_eq.unop (infer_instance : weak_eq P.op.d\u2080)\ninstance weq_d\u2081 : weak_eq P.d\u2081 := weak_eq.unop (infer_instance : weak_eq P.op.d\u2081)\n\n@[simps]\ndef change_I {I' : C} {f : I' \u27f6 P.I} {g : B \u27f6 I'} (fac : g \u226b f = P.\u03c3) [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 \u226b g.op = P.\u03c3.op := by rw [\u2190 op_comp, fac],\n  exact (P.op.change_I eq).unop,\nend\n\n@[simp]\ndef \u03c0 := prod.lift P.d\u2080 P.d\u2081\n\nlemma fibration_\u03c0_iff_cofibration_op_\u03b9 (P : pre_path_object B) :\n  fibration P.\u03c0 \u2194 cofibration P.op.\u03b9 :=\nby simpa only [fibration.iff_op]\n  using cofibration.respects_iso _ _ (arrow.iso_op_prod_lift P.d\u2080 P.d\u2081)\n\nlemma fibration_\u03c0_iff_cofibration_unop_\u03b9 {B : C\u1d52\u1d56} (P : pre_path_object B) :\n  fibration P.\u03c0 \u2194 cofibration P.unop.\u03b9 :=\nby simpa only [fibration.iff_unop]\n  using cofibration.respects_iso _ _ (arrow.iso_unop_prod_lift P.d\u2080 P.d\u2081)\n\n@[simps]\ndef symm : pre_path_object B :=\n{ I := P.I,\n  d\u2080 := P.d\u2081,\n  d\u2081 := P.d\u2080,\n  \u03c3 := P.\u03c3, }\n\nend pre_path_object\n\nstructure path_object extends pre_path_object B :=\n[fib_\u03c0 : fibration to_pre_path_object.\u03c0]\n\nnamespace path_object\n\nvariable {B}\n\ndef mk' (P : pre_path_object B) (h : fibration P.\u03c0) : 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.\u03c0 := Q.fib_\u03c0\n\n@[simps]\ndef change_I {B : C} (P : path_object B) {Z : C} {f : B \u27f6 Z} {g : Z \u27f6 P.I}\n  (fac : f \u226b g = P.\u03c3) [fibration g] [weak_eq g] : path_object B :=\nbegin\n  haveI : fibration (P.pre.change_I fac).\u03c0,\n  { convert (infer_instance : fibration (g \u226b P.\u03c0)),\n    simp only [pre_path_object.\u03c0, pre_path_object.change_I_d\u2080,\n      pre_path_object.change_I_d\u2081, 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\u1d52\u1d56} (Q : cylinder A) : path_object A.unop :=\nbegin\n  apply path_object.mk' Q.pre.unop,\n  rw [pre_path_object.fibration_\u03c0_iff_cofibration_op_\u03b9, 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_\u03c0_iff_cofibration_unop_\u03b9, 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 \u2190 Q.pre.fibration_\u03c0_iff_cofibration_op_\u03b9,\n  apply_instance,\nend\n\n@[simps]\ndef unop {B : C\u1d52\u1d56} (Q : path_object B) : cylinder B.unop :=\nbegin\n  apply cylinder.mk' Q.pre.unop,\n  rw \u2190 Q.pre.fibration_\u03c0_iff_cofibration_unop_\u03b9,\n  apply_instance,\nend\n\nvariable (B)\n\ndef some : path_object B := (cylinder.some (opposite.op B)).unop\n\ninstance : cofibration (some B).\u03c3 := 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 _ \u226b (some B).\u03c3),\n  apply_instance,\nend\n\ninstance : inhabited (path_object B) := \u27e8some B\u27e9\ninstance : inhabited (pre_path_object B) := \u27e8(some B).pre\u27e9\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": "import LightData\nimport Yatima.Datatypes.Const\nimport Yatima.Datatypes.Env\n\nnamespace Yatima.ContAddr\n\nopen IR\n\nscoped notation \"dec\" x => Encodable.decode x\n\ndef partitionName (name : Name) : List (Either String Nat) :=\n  let rec aux (acc : List (Either String Nat)) : Name \u2192 List (Either String Nat)\n    | .str name s => aux ((.left s) :: acc) name\n    | .num name n => aux ((.right n) :: acc) name\n    | .anonymous  => acc\n  aux [] name\n\ninstance : Encodable Name LightData where\n  encode n := partitionName n\n  decode x := do\n    let parts : List (Either String Nat) \u2190 dec x\n    parts.foldlM (init := .anonymous) fun acc x => match x with\n      | .left  s => pure $ acc.mkStr s\n      | .right n => pure $ acc.mkNum n\n\ninstance : Encodable Literal LightData where\n  encode\n    | .strVal s => .cell #[false, s]\n    | .natVal n => .cell #[true,  n]\n  decode\n    | .cell #[false, s] => return .strVal (\u2190 dec s)\n    | .cell #[true,  n] => return .natVal (\u2190 dec n)\n    | x => throw s!\"expected either but got {x}\"\n\ninstance : Encodable BinderInfo LightData where\n  encode | .default => 0 | .implicit => 1 | .strictImplicit => 2 | .instImplicit => 3\n  decode\n    | 0 => pure .default\n    | 1 => pure .implicit\n    | 2 => pure .strictImplicit\n    | 3 => pure .instImplicit\n    | x => throw s!\"Invalid encoding for BinderInfo: {x}\"\n\ninstance : Encodable QuotKind LightData where\n  encode | .type => 0 | .ctor => 1 | .lift => 2 | .ind => 3\n  decode\n    | 0 => pure .type\n    | 1 => pure .ctor\n    | 2 => pure .lift\n    | 3 => pure .ind\n    | x => throw s!\"Invalid encoding for QuotKind: {x}\"\n\ndef univToLightData : Univ \u2192 LightData\n  | .zero     => 0\n  | .succ x   => .cell #[false, univToLightData x]\n  | .var  x   => .cell #[true,  x]\n  | .max  x y => .cell #[false, univToLightData x, univToLightData y]\n  | .imax x y => .cell #[true,  univToLightData x, univToLightData y]\n\npartial def lightDataToUniv : LightData \u2192 Except String Univ\n  | 0 => pure .zero\n  | .cell #[false, x] => return .succ (\u2190 lightDataToUniv x)\n  | .cell #[true,  x] => return .var (\u2190 dec x)\n  | .cell #[false, x, y] => return .max  (\u2190 lightDataToUniv x) (\u2190 lightDataToUniv y)\n  | .cell #[true,  x, y] => return .imax (\u2190 lightDataToUniv x) (\u2190 lightDataToUniv y)\n  | x => throw s!\"Invalid encoding for Univ: {x}\"\n\ninstance : Encodable Univ LightData where\n  encode := univToLightData\n  decode := lightDataToUniv\n\ninstance : Encodable Lurk.F LightData where\n  encode x := x.val\n  decode x := return (.ofNat $ \u2190 dec x)\n\ndef exprToLightData : Expr \u2192 LightData\n  | .sort x => .cell #[false, x]\n  | .lit  x => .cell #[true,  x]\n  | .var   x y => .cell #[0, x, y]\n  | .const x y => .cell #[1, x, y]\n  | .app   x y => .cell #[2, exprToLightData x, exprToLightData y]\n  | .lam   x y => .cell #[3, exprToLightData x, exprToLightData y]\n  | .pi    x y => .cell #[4, exprToLightData x, exprToLightData y]\n  | .proj  x y => .cell #[5, x, exprToLightData y]\n  | .letE x y z => .cell #[false, exprToLightData x, exprToLightData y, exprToLightData z]\n\npartial def lightDataToExpr : LightData \u2192 Except String Expr\n  | .cell #[false, x] => return .sort (\u2190 lightDataToUniv x)\n  | .cell #[true,  x] => return .lit (\u2190 dec x)\n  | .cell #[0, x, y] => return .var (\u2190 dec x) (\u2190 dec y)\n  | .cell #[1, x, y] => return .const (\u2190 dec x) (\u2190 dec y)\n  | .cell #[2, x, y] => return .app (\u2190 lightDataToExpr x) (\u2190 lightDataToExpr y)\n  | .cell #[3, x, y] => return .lam (\u2190 lightDataToExpr x) (\u2190 lightDataToExpr y)\n  | .cell #[4, x, y] => return .pi  (\u2190 lightDataToExpr x) (\u2190 lightDataToExpr y)\n  | .cell #[5, x, y] => return .proj (\u2190 dec x) (\u2190 lightDataToExpr y)\n  | .cell #[false, x, y, z] =>\n    return .letE (\u2190 lightDataToExpr x) (\u2190 lightDataToExpr y) (\u2190 lightDataToExpr z)\n  | x => throw s!\"Invalid encoding for IR.Expr: {x}\"\n\ninstance : Encodable Expr LightData where\n  encode := exprToLightData\n  decode := lightDataToExpr\n\ninstance : Encodable Constructor LightData where\n  encode | \u27e8a, b, c, d, e\u27e9 => .cell #[a, b, c, d, e]\n  decode\n    | .cell #[a, b, c, d, e] => return \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c, \u2190 dec d, \u2190 dec e\u27e9\n    | x => throw s!\"Invalid encoding for IR.Constructor: {x}\"\n\ninstance : Encodable RecursorRule LightData where\n  encode | \u27e8a, b\u27e9 => .cell #[a, b]\n  decode\n    | .cell #[a, b] => return \u27e8\u2190 dec a, \u2190 dec b\u27e9\n    | x => throw s!\"Invalid encoding for IR.RecursorRule: {x}\"\n\ninstance : Encodable Definition LightData where\n  encode | \u27e8a, b, c, d\u27e9 => .cell #[a, b, c, d]\n  decode\n    | .cell #[a, b, c, d] => return \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c, \u2190 dec d\u27e9\n    | x => throw s!\"Invalid encoding for IR.Definition: {x}\"\n\ninstance : Encodable Recursor LightData where\n  encode | \u27e8a, b, c, d, e, f, g, h, i\u27e9 => .cell #[a, b, c, d, e, f, g, h, i]\n  decode\n    | .cell #[a, b, c, d, e, f, g, h, i] =>\n      return \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c, \u2190 dec d, \u2190 dec e, \u2190 dec f, \u2190 dec g, \u2190 dec h, \u2190 dec i\u27e9\n    | x => throw s!\"Invalid encoding for IR.Recursor: {x}\"\n\ninstance : Encodable Inductive LightData where\n  encode | \u27e8a, b, c, d, e, f, g, h, i, j\u27e9 => .cell #[a, b, c, d, e, f, g, h, i, j]\n  decode\n    | .cell #[a, b, c, d, e, f, g, h, i, j] =>\n      return \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c, \u2190 dec d, \u2190 dec e, \u2190 dec f, \u2190 dec g,\n        \u2190 dec h, \u2190 dec i, \u2190 dec j\u27e9\n    | x => throw s!\"Invalid encoding for IR.Inductive: {x}\"\n\ninstance : Encodable Const LightData where\n  encode\n    | .mutIndBlock x => .cell #[false, x]\n    | .mutDefBlock x => .cell #[true,  x]\n    | .axiom          \u27e8a, b\u27e9 => .cell #[0, a, b]\n    | .inductiveProj  \u27e8a, b\u27e9 => .cell #[1, a, b]\n    | .definitionProj \u27e8a, b\u27e9 => .cell #[2, a, b]\n    | .theorem         \u27e8a, b, c\u27e9 => .cell #[0, a, b, c]\n    | .opaque          \u27e8a, b, c\u27e9 => .cell #[1, a, b, c]\n    | .quotient        \u27e8a, b, c\u27e9 => .cell #[2, a, b, c]\n    | .constructorProj \u27e8a, b, c\u27e9 => .cell #[3, a, b, c]\n    | .recursorProj    \u27e8a, b, c\u27e9 => .cell #[4, a, b, c]\n    | .definition \u27e8a, b, c, d\u27e9 => .cell #[false, a, b, c, d]\n  decode\n    | .cell #[false, x] => return .mutIndBlock (\u2190 dec x)\n    | .cell #[true,  x] => return .mutDefBlock (\u2190 dec x)\n    | .cell #[0, a, b] => return .axiom          \u27e8\u2190 dec a, \u2190 dec b\u27e9\n    | .cell #[1, a, b] => return .inductiveProj  \u27e8\u2190 dec a, \u2190 dec b\u27e9\n    | .cell #[2, a, b] => return .definitionProj \u27e8\u2190 dec a, \u2190 dec b\u27e9\n    | .cell #[0, a, b, c] => return .theorem         \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c\u27e9\n    | .cell #[1, a, b, c] => return .opaque          \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c\u27e9\n    | .cell #[2, a, b, c] => return .quotient        \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c\u27e9\n    | .cell #[3, a, b, c] => return .constructorProj \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c\u27e9\n    | .cell #[4, a, b, c] => return .recursorProj    \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c\u27e9\n    | .cell #[false, a, b, c, d] => return .definition \u27e8\u2190 dec a, \u2190 dec b, \u2190 dec c, \u2190 dec d\u27e9\n    | x => throw s!\"Invalid encoding for IR.Const: {x}\"\n\ninstance [Encodable (Array (\u03b1 \u00d7 \u03b2)) LightData] [Ord \u03b1] :\n    Encodable (Std.RBMap \u03b1 \u03b2 compare) LightData where\n  encode x := (x.foldl (\u00b7.push (\u00b7, \u00b7)) #[] : Array (\u03b1 \u00d7 \u03b2))\n  decode x := return .ofArray (\u2190 dec x) _\n\ninstance [Encodable (Array \u03b1) LightData] [Ord \u03b1] :\n    Encodable (Std.RBSet \u03b1 compare) LightData where\n  encode x := (x.foldl (\u00b7.push \u00b7) #[] : Array \u03b1)\n  decode x := return .ofArray (\u2190 dec x) _\n\ninstance : Encodable IR.Env LightData where\n  encode | \u27e8x, y\u27e9 => .cell #[x, y]\n  decode\n    | .cell #[x, y] => return \u27e8\u2190 dec x, \u2190 dec y\u27e9\n    | x => throw s!\"Invalid encoding for IR.Definition: {x}\"\n\nend Yatima.ContAddr\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/Yatima/Common/LightData.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.027585280927720394, "lm_q1q2_score": 0.01144510121789081}}
{"text": "-- lemmas about substitution\n\nimport .definitions3 .freevars .others\n\nlemma env.contains.inv {\u03c3: env} {x y: var} {v: value}: x \u2208 (\u03c3[y\u21a6v]) \u2192 (x = y \u2228 x \u2208 \u03c3) :=\n  assume x_in: x \u2208 (\u03c3[y\u21a6v]),\n  show x = y \u2228 x \u2208 \u03c3, by { cases x_in, left, refl, right, from a }\n\nlemma env.contains.same.inv {\u03c3: env} {x y: var} {v: value}: x \u2209 (\u03c3[y\u21a6v]) \u2192 \u00ac (x = y \u2228 x \u2208 \u03c3) :=\n  assume x_not_in: x \u2209 (\u03c3[y\u21a6v]),\n  assume : (x = y \u2228 x \u2208 \u03c3),\n  this.elim (\n    assume x_is_y: x = y,\n    have x \u2208 (\u03c3[x\u21a6v]), from env.contains.same,\n    have x \u2208 (\u03c3[y\u21a6v]), from @eq.subst var (\u03bba, x \u2208 (\u03c3[a\u21a6v])) x y x_is_y this,\n    show \u00abfalse\u00bb, from x_not_in this\n  ) (\n    assume : x \u2208 \u03c3,\n    have x \u2208 (\u03c3[y\u21a6v]), from env.contains.rest this,\n    show \u00abfalse\u00bb, from x_not_in this\n  )\n\nlemma env.contains_apply_equiv {\u03c3: env} {x: var}:\n  ((\u03c3 x = none) \u2194 (x \u2209 \u03c3)) \u2227 ((\u2203v, \u03c3 x = some v) \u2194 (x \u2208 \u03c3)) :=\nbegin\n  induction \u03c3 with \u03c3' y v' ih,\n  show ((env.empty x = none) \u2194 (x \u2209 env.empty)) \u2227 ((\u2203v, env.empty x = some v) \u2194 (x \u2208 env.empty)), by begin\n    split,\n    show (env.empty x = none) \u2194 (x \u2209 env.empty), by begin\n      split,\n      show (env.empty x = none) \u2192 (x \u2209 env.empty), by begin\n        assume : (env.empty x = none),\n        by_contradiction h,\n        cases h\n      end,\n      show (x \u2209 env.empty) \u2192 (env.empty x = none), by begin\n        assume : (x \u2209 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 (\u2203v, env.empty x = some v) \u2194 (x \u2208 env.empty), by begin\n      split,\n      show (\u2203v, env.empty x = some v) \u2192 (x \u2208 env.empty), from (\n        assume : (\u2203v, env.empty x = some v),\n        let (\u27e8v, h0\u27e9) := 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 \u2208 env.empty), by contradiction\n      ),\n      show (x \u2208 env.empty) \u2192 (\u2203v,env.empty x = some v), by begin\n        assume h: x \u2208 env.empty,\n        cases h\n      end\n    end\n  end,\n  show (((\u03c3'[y\u21a6v']) x = none) \u2194 (x \u2209 (\u03c3'[y\u21a6v']))) \u2227 ((\u2203v, (\u03c3'[y\u21a6v']) x = some v) \u2194 (x \u2208 (\u03c3'[y\u21a6v']))), by begin\n    split,\n    show (((\u03c3'[y\u21a6v']) x = none) \u2194 (x \u2209 (\u03c3'[y\u21a6v']))), by begin\n      split,\n      show (((\u03c3'[y\u21a6v']) x = none) \u2192 (x \u2209 (\u03c3'[y\u21a6v']))), by begin\n        assume h: ((\u03c3'[y\u21a6v']) x = none),\n        have h2: (env.apply (\u03c3'[y\u21a6v']) x = (if y = x \u2227 option.is_none (\u03c3'.apply x) then v' else \u03c3'.apply x)),\n        by unfold env.apply,\n        have h3: ((if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = none),\n        from eq.trans h2.symm h,\n        have h4: (\u03c3'.apply x = none), by begin\n          by_cases (y = x \u2227 option.is_none (\u03c3'.apply x)),\n          show (\u03c3'.apply x = none), by begin\n            have : ((if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u2191v'),\n            by simp[h],\n            have : (none = \u2191v'), from eq.trans h3.symm this,\n            contradiction\n          end,\n          show (\u03c3'.apply x = none), by begin\n            have : ((if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u03c3'.apply x),\n            by simp[h],\n            show (\u03c3'.apply x = none), from eq.trans this.symm h3\n          end\n        end,\n        have : x \u2209 \u03c3', from ih.left.mp h4,\n        have h5: \u00ac (x = y), by begin\n          by_contradiction,\n          have h6: (option.is_none (\u03c3'.apply x) = tt), from option.is_none.inv.mp h4,\n          have : (y = x \u2227 option.is_none (\u03c3'.apply x)), from \u27e8a.symm, h6\u27e9,\n          have : ((if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u2191v'),\n          by simp[this],\n          have : (none = \u2191v'), 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 \u2209 (\u03c3'[y\u21a6v'])) \u2192 (((\u03c3'[y\u21a6v']) x = none)), by begin\n        assume : (x \u2209 (\u03c3'[y\u21a6v'])),\n        have h7: \u00ac (x = y \u2228 x \u2208 \u03c3'), from env.contains.same.inv this,\n        have : x \u2260 y, from (not_or_distrib.mp h7).left,\n        have h8: y \u2260 x, from ne.symm this,\n        have h9: x \u2209 \u03c3', from (not_or_distrib.mp h7).right,\n        have h10: (\u03c3'.apply x = none), from ih.left.mpr h9,\n        have h11: (env.apply (\u03c3'[y\u21a6v']) x = (if y = x \u2227 option.is_none (\u03c3'.apply x) then v' else \u03c3'.apply x)),\n        by unfold env.apply,\n        have h12: ((if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u03c3'.apply x),\n        by simp[h8],\n        show ((\u03c3'[y\u21a6v']) x = none), from eq.trans (eq.trans h11 h12) h10\n      end\n    end,\n    show ((\u2203v, (\u03c3'[y\u21a6v']) x = some v) \u2194 (x \u2208 (\u03c3'[y\u21a6v']))), by begin\n      split,\n      show ((\u2203v, (\u03c3'[y\u21a6v']) x = some v) \u2192 (x \u2208 (\u03c3'[y\u21a6v']))), from (\n        assume : (\u2203v, (\u03c3'[y\u21a6v']) x = some v),\n        let \u27e8v, h13\u27e9 := this in begin\n        have h14: (env.apply (\u03c3'[y\u21a6v']) x = (if y = x \u2227 option.is_none (\u03c3'.apply x) then v' else \u03c3'.apply x)),\n        by unfold env.apply,\n        by_cases (y = x \u2227 option.is_none (\u03c3'.apply x)) with h15,\n        show (x \u2208 (\u03c3'[y\u21a6v'])), by begin\n          have x_is_y: (y = x), from h15.left,\n          have : (x \u2208 (\u03c3'[x\u21a6v'])), from env.contains.same,\n          show x \u2208 (\u03c3'[y\u21a6v']), from @eq.subst var (\u03bba, x \u2208 (\u03c3'[a\u21a6v'])) x y x_is_y.symm this\n        end,\n        show (x \u2208 (\u03c3'[y\u21a6v'])), by begin\n          have : ((if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u03c3'.apply x),\n          by simp[h15],\n          have : (\u03c3'.apply x = v), from eq.trans (eq.trans this.symm h14.symm) h13,\n          have : x \u2208 \u03c3', from ih.right.mp (exists.intro v this),\n          show x \u2208 (\u03c3'[y\u21a6v']), from env.contains.rest this\n        end\n      end),\n      show (x \u2208 (\u03c3'[y\u21a6v'])) \u2192 (\u2203v, (\u03c3'[y\u21a6v']) x = some v), by begin\n        assume h16: (x \u2208 (\u03c3'[y\u21a6v'])),\n        have h17: (env.apply (\u03c3'[y\u21a6v']) x = (if y = x \u2227 option.is_none (\u03c3'.apply x) then v' else \u03c3'.apply x)),\n        by unfold env.apply,\n        cases h16,\n        case env.contains.same {\n          by_cases (x = x \u2227 option.is_none (\u03c3'.apply x)),\n          show (\u2203v, (\u03c3'[x\u21a6v']) x = some v), by begin\n            have : ((if x = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = v'),\n            by { simp[h] },\n            show (\u2203v, (\u03c3'[x\u21a6v']) x = some v), from exists.intro v' (eq.trans h17 this)\n          end,\n          show (\u2203v, (\u03c3'[x\u21a6v']) x = some v), by begin\n            have h19: \u00acoption.is_none (\u03c3'.apply x), by begin\n              by_contradiction h18,\n              have : (x = x \u2227 option.is_none (\u03c3'.apply x)), from \u27e8rfl, h18\u27e9,\n              exact h this\n            end,\n            have : ((option.is_some (\u03c3'.apply x)):Prop), from option.some_iff_not_none.mpr h19,\n            have : \u2203v, (\u03c3'.apply x) = some v, from option.is_some_iff_exists.mp this,\n            cases this with v h20,\n            have : ((if x = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u03c3'.apply x),\n            by { simp[h], simp[h19] },\n            show (\u2203v, (\u03c3'[x\u21a6v']) 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 : (\u2203v, \u03c3'.apply x = some v), from ih.right.mpr h27,\n          cases this with v h28,\n          have : \u00ac (option.is_none (\u03c3'.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 \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u03c3'.apply x),\n          by simp[this],\n          show (\u2203v, (\u03c3'[y\u21a6v']) x = some v), from exists.intro v (eq.trans (eq.trans h17 this) h28)\n        }\n      end\n    end\n  end\nend\n\ninstance {\u03c3: env} {x: var} : decidable (env.contains \u03c3 x) :=\n  let r := env.apply \u03c3 x in\n  have h: r = env.apply \u03c3 x, from rfl,\n  @option.rec_on value (\u03bba, (r = a) \u2192 decidable (env.contains \u03c3 x)) r\n  (\n    assume : r = none,\n    have env.apply \u03c3 x = none, from eq.trans h this,\n    have \u00ac (x \u2208 \u03c3), 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 \u03c3 x = some v, from eq.trans h this,\n    have \u2203v, env.apply \u03c3 x = some v, from exists.intro v this,\n    have x \u2208 \u03c3, from env.contains_apply_equiv.right.mp this,\n    is_true this\n  ) rfl\n\nlemma term.subst.congr {x: var} {v: value} {t\u2081 t\u2082: term}: (t\u2081 = t\u2082) \u2192 (term.subst x v t\u2081 = term.subst x v t\u2082) :=\n  begin\n    assume h1,\n    congr,\n    from h1\n  end\n\nlemma env.contains_without.inv {\u03c3: env} {x y: var}:\n      (x \u2208 \u03c3.without y) \u2192 (x \u2260 y) \u2227 x \u2208 \u03c3 :=\n  begin\n    assume h1,\n\n    induction \u03c3 with \u03c3' 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 {\u03c3: env} {x y: var}:\n      x \u2208 \u03c3 \u2227 (x \u2260 y) \u2192 x \u2208 \u03c3.without y :=\n  begin\n    assume h1,\n\n    induction \u03c3 with \u03c3' 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 \u2260 y), from @eq.subst var (\u03bba, a \u2260 y) x y this h1.right,\n    contradiction,\n\n    from ih \u27e8h5, h1.right\u27e9,\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 \u27e8h5, h1.right\u27e9,\n  end\n\nlemma env.without_equiv {\u03c3: env} {x y: var} {v: value}:\n      (x \u2209 \u03c3) \u2228 (\u03c3 x = v) \u2192 (x \u2209 \u03c3.without y \u2228 (\u03c3.without y x = v)) :=\n  begin\n    assume h1,\n\n    induction \u03c3 with \u03c3' 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 \u2208 (\u03c3'[z\u21a6v']), 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 \u2208 (\u03c3'[z\u21a6v']), from env.contains.same,\n    contradiction,\n\n    have h9, from env.contains_without.inv h8,\n    have : x \u2208 (\u03c3'[z\u21a6v']), 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 : \u00ac (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 : \u00ac (z = z), from @eq.subst var (\u03bba, \u00ac (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 : \u00ac (y = y), from h10.left,\n    contradiction,\n\n    right,\n    have h5: (env.apply (\u03c3'[z\u21a6v']) x = some v), from h3,\n    unfold env.apply at h5,\n    by_cases (z = x \u2227 (option.is_none (env.apply \u03c3' 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 \u03c3' y)[z\u21a6v']),\n    have h12: (env.without (\u03c3'[z\u21a6v']) y = (if z = y then (env.without \u03c3' y) else a')),\n    by unfold env.without,\n    rw[h12],\n    change ((ite (z = y) (env.without \u03c3' y) a') x = \u2191v),\n    have : \u00ac (z = y), from @eq.subst var (\u03bba, \u00ac (a = y)) x z h6.left.symm h4,\n    have : (ite (z = y) (env.without \u03c3' y) a'\n             = ((env.without \u03c3' y)[z\u21a6v'])), by simp[this],\n    have h13: (\n      ((ite (z = y) (env.without \u03c3' y) a') x = \u2191v)\n    = (((env.without \u03c3' y)[z\u21a6v']) x = \u2191v)\n    ), by rw[this],\n    rw[h13],\n    change (env.apply (env.without \u03c3' y[z\u21a6v']) x = \u2191v),\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 \u2227 (option.is_none (env.apply (env.without \u03c3' 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: \u00ac (z = x \u2227 option.is_none (env.apply (env.without \u03c3' 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 \u03c3' y)[z\u21a6v']),\n    have h7: (env.without (\u03c3'[z\u21a6v']) y = (if z = y then (env.without \u03c3' 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 \u03c3' y) ((env.without \u03c3' y)[z\u21a6v'])\n             = (env.without \u03c3' 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 \u2208 \u03c3', from env.contains_apply_equiv.right.mp (exists.intro v h5),\n    have h9: x \u2208 env.without \u03c3' y,\n    from env.contains_without.rinv \u27e8this, h4\u27e9,\n    contradiction,\n\n    from h10,\n\n    have : (ite (z = y) (env.without \u03c3' y) ((env.without \u03c3' y)[z\u21a6v'])\n             = ((env.without \u03c3' y)[z\u21a6v'])), by simp[h8],\n    rw[this],\n    change (env.apply ((env.without \u03c3' y)[z\u21a6v']) x = \u2191v),\n    unfold env.apply,\n\n    have h10b: x \u2208 \u03c3', from env.contains_apply_equiv.right.mp (exists.intro v h5),\n    have h11: x \u2208 env.without \u03c3' y,\n    from env.contains_without.rinv \u27e8h10b, h4\u27e9,\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: \u00ac (z = x \u2227 option.is_none (env.apply (env.without \u03c3' 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 {\u03c3: env} {x y: var}: x \u2209 \u03c3 \u2192 x \u2209 \u03c3.without y :=\n  begin\n    assume h1,\n\n    induction \u03c3 with \u03c3' 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 \u2208 (\u03c3'[z\u21a6v']), 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 \u2208 (\u03c3'[z\u21a6v']), from env.contains.same,\n    contradiction,\n\n    have h9, from env.contains_without.inv h8,\n    have : x \u2208 (\u03c3'[z\u21a6v']), from env.contains.rest h9.right,\n    contradiction\n  end\n\nlemma env.not_contains_without {\u03c3: env} {x: var}: x \u2209 \u03c3.without x :=\n  assume : x \u2208 \u03c3.without x,\n  have (x \u2260 x) \u2227 x \u2208 \u03c3, from env.contains_without.inv this,\n  show \u00abfalse\u00bb, from this.left (eq.refl x)\n\nlemma env.without_equiv_with {\u03c3: env} {x: var}: \u2200y, y \u2208 \u03c3.without x \u2192 (\u03c3.without x y = \u03c3 y) :=\n  assume y: var,\n  assume h1: y \u2208 \u03c3.without x,\n  have y \u2260 x \u2227 y \u2208 \u03c3, from env.contains_without.inv h1,\n  have \u2203v: value, \u03c3 y = v, from env.contains_apply_equiv.right.mpr this.right,\n  let \u27e8v, \u03c3_y_is_v\u27e9 := this in\n  have y \u2209 \u03c3.without x \u2228 (\u03c3.without x y = v), from env.without_equiv (or.inr \u03c3_y_is_v),\n  or.elim this (\n    assume : y \u2209 \u03c3.without x,\n    show \u03c3.without x y = \u03c3 y, from absurd h1 this\n  ) (\n    assume : \u03c3.without x y = v,\n    show \u03c3.without x y = \u03c3 y, from eq.trans this \u03c3_y_is_v.symm\n  )\n\nlemma env.without_nonexisting {\u03c3: env} {x: var}: x \u2209 \u03c3 \u2192 (\u03c3.without x = \u03c3) :=\n  begin\n    assume h1,\n\n    induction \u03c3 with \u03c3' z v' ih,\n\n    unfold env.without,\n\n    unfold env.without,\n    have h2: (z \u2260 x), by begin\n      assume h3,\n      rw[h3] at h1,\n      have h4: x \u2208 (\u03c3'[x\u21a6v']), from env.contains.same,\n      contradiction\n    end,\n    simp[h2],\n    congr,\n    apply ih,\n    by_contradiction h3,\n    have h4: x \u2208 (\u03c3'[z\u21a6v']), from env.contains.rest h3,\n    contradiction\n  end\n\nlemma unchanged_of_subst_nonfree_term {t: term} {x: var} {v: value}:\n    x \u2209 FV t \u2192 (term.subst x v t = t) :=\n  assume x_not_free: \u00ac free_in_term x t,\n  begin\n    induction t with v' y unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n    show (term.subst x v (term.value v') = \u2191v'), 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 \u25b8 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\u2081) = term.unop unop t\u2081), from (\n      have h: term.subst x v (term.unop unop t\u2081) = term.unop unop (term.subst x v t\u2081), by unfold term.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_term x (term.unop unop t\u2081), from free_in_term.unop this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have term.subst x v t\u2081 = t\u2081, from t\u2081_ih this,\n      show term.subst x v (term.unop unop t\u2081) = term.unop unop t\u2081,\n      from @eq.subst term (\u03bba, term.subst x v (term.unop unop t\u2081) = term.unop unop a) (term.subst x v t\u2081) t\u2081 this h\n    ),\n    show (term.subst x v (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 t\u2083), from (\n      have h: term.subst x v (term.binop binop t\u2082 t\u2083)\n            = term.binop binop (term.subst x v t\u2082) (term.subst x v t\u2083), by unfold term.subst,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_term x (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t2_subst: term.subst x v t\u2082 = t\u2082, from t\u2082_ih this,\n      have \u00ac free_in_term x t\u2083, from (\n        assume : free_in_term x t\u2083,\n        have free_in_term x (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t3_subst: term.subst x v t\u2083 = t\u2083, from t\u2083_ih this,\n      have term.subst x v (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 (term.subst x v t\u2083),\n      from @eq.subst term (\u03bba, term.subst x v (term.binop binop t\u2082 t\u2083) = term.binop binop a (term.subst x v t\u2083))\n      (term.subst x v t\u2082) t\u2082 t2_subst h,\n      show term.subst x v (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 t\u2083,\n      from @eq.subst term (\u03bba, term.subst x v (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 a)\n      (term.subst x v t\u2083) t\u2083 t3_subst this\n    ),\n    show (term.subst x v (term.app t\u2084 t\u2085) = term.app t\u2084 t\u2085), from (\n      have h: term.subst x v (term.app t\u2084 t\u2085)\n            = term.app (term.subst x v t\u2084) (term.subst x v t\u2085), by unfold term.subst,\n      have \u00ac free_in_term x t\u2084, from (\n        assume : free_in_term x t\u2084,\n        have free_in_term x (term.app t\u2084 t\u2085), from free_in_term.app\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t4_subst: term.subst x v t\u2084 = t\u2084, from t\u2084_ih this,\n      have \u00ac free_in_term x t\u2085, from (\n        assume : free_in_term x t\u2085,\n        have free_in_term x (term.app t\u2084 t\u2085), from free_in_term.app\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t5_subst: term.subst x v t\u2085 = t\u2085, from t\u2085_ih this,\n      have term.subst x v (term.app t\u2084 t\u2085) = term.app t\u2084 (term.subst x v t\u2085),\n      from @eq.subst term (\u03bba, term.subst x v (term.app t\u2084 t\u2085) = term.app a (term.subst x v t\u2085))\n      (term.subst x v t\u2084) t\u2084 t4_subst h,\n      show term.subst x v (term.app t\u2084 t\u2085) = term.app t\u2084 t\u2085,\n      from @eq.subst term (\u03bba, term.subst x v (term.app t\u2084 t\u2085) = term.app t\u2084 a)\n      (term.subst x v t\u2085) t\u2085 t5_subst this\n    )\n  end\n\nlemma unchanged_of_substt_nonfree_term {t: term} {x: var} {t': term}:\n    x \u2209 FV t \u2192 (term.substt x t' t = t) :=\n  assume x_not_free: \u00ac free_in_term x t,\n  begin\n    induction t with v y unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n    show (term.substt x t' (term.value v) = \u2191v), 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 \u25b8 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\u2081) = term.unop unop t\u2081), from (\n      have h: term.substt x t' (term.unop unop t\u2081) = term.unop unop (term.substt x t' t\u2081), by unfold term.substt,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_term x (term.unop unop t\u2081), from free_in_term.unop this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have term.substt x t' t\u2081 = t\u2081, from t\u2081_ih this,\n      show term.substt x t' (term.unop unop t\u2081) = term.unop unop t\u2081,\n      from @eq.subst term (\u03bba, term.substt x t' (term.unop unop t\u2081) = term.unop unop a) (term.substt x t' t\u2081) t\u2081 this h\n    ),\n    show (term.substt x t' (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 t\u2083), from (\n      have h: term.substt x t' (term.binop binop t\u2082 t\u2083)\n            = term.binop binop (term.substt x t' t\u2082) (term.substt x t' t\u2083), by unfold term.substt,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_term x (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t2_substt: term.substt x t' t\u2082 = t\u2082, from t\u2082_ih this,\n      have \u00ac free_in_term x t\u2083, from (\n        assume : free_in_term x t\u2083,\n        have free_in_term x (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t3_substt: term.substt x t' t\u2083 = t\u2083, from t\u2083_ih this,\n      have term.substt x t' (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 (term.substt x t' t\u2083),\n      from @eq.subst term (\u03bba, term.substt x t' (term.binop binop t\u2082 t\u2083) = term.binop binop a (term.substt x t' t\u2083))\n      (term.substt x t' t\u2082) t\u2082 t2_substt h,\n      show term.substt x t' (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 t\u2083,\n      from @eq.subst term (\u03bba, term.substt x t' (term.binop binop t\u2082 t\u2083) = term.binop binop t\u2082 a)\n      (term.substt x t' t\u2083) t\u2083 t3_substt this\n    ),\n    show (term.substt x t' (term.app t\u2084 t\u2085) = term.app t\u2084 t\u2085), from (\n      have h: term.substt x t' (term.app t\u2084 t\u2085)\n            = term.app (term.substt x t' t\u2084) (term.substt x t' t\u2085), by unfold term.substt,\n      have \u00ac free_in_term x t\u2084, from (\n        assume : free_in_term x t\u2084,\n        have free_in_term x (term.app t\u2084 t\u2085), from free_in_term.app\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t4_substt: term.substt x t' t\u2084 = t\u2084, from t\u2084_ih this,\n      have \u00ac free_in_term x t\u2085, from (\n        assume : free_in_term x t\u2085,\n        have free_in_term x (term.app t\u2084 t\u2085), from free_in_term.app\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have t5_substt: term.substt x t' t\u2085 = t\u2085, from t\u2085_ih this,\n      have term.substt x t' (term.app t\u2084 t\u2085) = term.app t\u2084 (term.substt x t' t\u2085),\n      from @eq.subst term (\u03bba, term.substt x t' (term.app t\u2084 t\u2085) = term.app a (term.substt x t' t\u2085))\n      (term.substt x t' t\u2084) t\u2084 t4_substt h,\n      show term.substt x t' (term.app t\u2084 t\u2085) = term.app t\u2084 t\u2085,\n      from @eq.subst term (\u03bba, term.substt x t' (term.app t\u2084 t\u2085) = term.app t\u2084 a)\n      (term.substt x t' t\u2085) t\u2085 t5_substt this\n    )\n  end\n\nlemma unchanged_of_subst_env_nonfree_term {t: term}:\n    closed t \u2192 (\u2200\u03c3, term.subst_env \u03c3 t = t) :=\n  assume x_not_free: (\u2200x, x \u2209 FV t),\n  assume \u03c3: env,\n  begin\n    induction \u03c3 with \u03c3' x v ih,\n\n    show (term.subst_env env.empty t = t), by unfold term.subst_env,\n\n    show (term.subst_env (\u03c3'[x\u21a6v]) t = t), by calc\n        term.subst_env (\u03c3'[x\u21a6v]) t = term.subst x v (term.subst_env \u03c3' 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 \u2260 y) \u2192 (term.subst x v y = y) :=\n  assume x_neq_y: x \u2260 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 \u2260 y) \u2192 (term.substt x t y = y) :=\n  assume x_neq_y: x \u2260 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 \u2209 FV P \u2192 (prop.subst x v P = P) :=\n  assume x_not_free: \u00ac 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, prop.subst x v (prop.term t) = prop.term a) (term.subst x v t) t this h\n    )},\n    case prop.not P\u2081 ih { from (\n      have h: prop.subst x v P\u2081.not = (prop.subst x v P\u2081).not, by unfold prop.subst,\n      have \u00ac free_in_prop x P\u2081, from (\n        assume : free_in_prop x P\u2081,\n        have free_in_prop x P\u2081.not, from free_in_prop.not this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have prop.subst x v P\u2081 = P\u2081, from ih this,\n      show prop.subst x v P\u2081.not = P\u2081.not,\n      from @eq.subst prop (\u03bba, prop.subst x v P\u2081.not = prop.not a) (prop.subst x v P\u2081) P\u2081 this h\n    )},\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have h: prop.subst x v (prop.and P\u2081 P\u2082) = (prop.subst x v P\u2081 \u22c0 prop.subst x v P\u2082), by unfold prop.subst,\n      have \u00ac free_in_prop x P\u2081, from (\n        assume : free_in_prop x P\u2081,\n        have free_in_prop x (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: prop.subst x v P\u2081 = P\u2081, from P\u2081_ih this,\n      have \u00ac free_in_prop x P\u2082, from (\n        assume : free_in_prop x P\u2082,\n        have free_in_prop x (P\u2081 \u22c0 P\u2082), from free_in_prop.and\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: prop.subst x v P\u2082 = P\u2082, from P\u2082_ih this,\n      have prop.subst x v (P\u2081 \u22c0 P\u2082) = (P\u2081 \u22c0 prop.subst x v P\u2082),\n      from @eq.subst prop (\u03bba, prop.subst x v (prop.and P\u2081 P\u2082) = (a \u22c0 prop.subst x v P\u2082)) (prop.subst x v P\u2081) P\u2081 h1 h,\n      show prop.subst x v (P\u2081 \u22c0 P\u2082) = (P\u2081 \u22c0 P\u2082),\n      from @eq.subst prop (\u03bba, prop.subst x v (prop.and P\u2081 P\u2082) = (P\u2081 \u22c0 a)) (prop.subst x v P\u2082) P\u2082 h2 this\n    )},\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have h: prop.subst x v (prop.or P\u2081 P\u2082) = (prop.subst x v P\u2081 \u22c1 prop.subst x v P\u2082), by unfold prop.subst,\n      have \u00ac free_in_prop x P\u2081, from (\n        assume : free_in_prop x P\u2081,\n        have free_in_prop x (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: prop.subst x v P\u2081 = P\u2081, from P\u2081_ih this,\n      have \u00ac free_in_prop x P\u2082, from (\n        assume : free_in_prop x P\u2082,\n        have free_in_prop x (P\u2081 \u22c1 P\u2082), from free_in_prop.or\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: prop.subst x v P\u2082 = P\u2082, from P\u2082_ih this,\n      have prop.subst x v (P\u2081 \u22c1 P\u2082) = (P\u2081 \u22c1 prop.subst x v P\u2082),\n      from @eq.subst prop (\u03bba, prop.subst x v (prop.or P\u2081 P\u2082) = (a \u22c1 prop.subst x v P\u2082)) (prop.subst x v P\u2081) P\u2081 h1 h,\n      show prop.subst x v (P\u2081 \u22c1 P\u2082) = (P\u2081 \u22c1 P\u2082),\n      from @eq.subst prop (\u03bba, prop.subst x v (prop.or P\u2081 P\u2082) = (P\u2081 \u22c1 a)) (prop.subst x v P\u2082) P\u2082 h2 this\n    )},\n    case prop.pre t\u2081 t\u2082 { from (\n      have h: prop.subst x v (prop.pre t\u2081 t\u2082) = prop.pre (term.subst x v t\u2081) (term.subst x v t\u2082), by unfold prop.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_prop x (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.subst x v t\u2081 = t\u2081, from unchanged_of_subst_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_prop x (prop.pre t\u2081 t\u2082), from free_in_prop.pre\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.subst x v t\u2082 = t\u2082, from unchanged_of_subst_nonfree_term this,\n      have prop.subst x v (prop.pre t\u2081 t\u2082) = prop.pre t\u2081 (term.subst x v t\u2082),\n      from @eq.subst term (\u03bba, prop.subst x v (prop.pre t\u2081 t\u2082) = prop.pre a (term.subst x v t\u2082)) (term.subst x v t\u2081) t\u2081 h1 h,\n      show prop.subst x v (prop.pre t\u2081 t\u2082) = prop.pre t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, prop.subst x v (prop.pre t\u2081 t\u2082) = prop.pre t\u2081 a) (term.subst x v t\u2082) t\u2082 h2 this\n    )},\n    case prop.pre\u2081 op t { from (\n      have h: prop.subst x v (prop.pre\u2081 op t) = prop.pre\u2081 op (term.subst x v t), by unfold prop.subst,\n      have \u00ac free_in_term x t, from (\n        assume : free_in_term x t,\n        have free_in_prop x (prop.pre\u2081 op t), from free_in_prop.preop this,\n        show \u00abfalse\u00bb, 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\u2081 op t) = prop.pre\u2081 op t,\n      from @eq.subst term (\u03bba, prop.subst x v (prop.pre\u2081 op t) = prop.pre\u2081 op a) (term.subst x v t) t this h\n    )},\n    case prop.pre\u2082 op t\u2081 t\u2082 { from (\n      have h: prop.subst x v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op (term.subst x v t\u2081) (term.subst x v t\u2082),\n      by unfold prop.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.subst x v t\u2081 = t\u2081, from unchanged_of_subst_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from free_in_prop.preop\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.subst x v t\u2082 = t\u2082, from unchanged_of_subst_nonfree_term this,\n      have prop.subst x v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op t\u2081 (term.subst x v t\u2082),\n      from @eq.subst term (\u03bba, prop.subst x v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op a (term.subst x v t\u2082)) (term.subst x v t\u2081) t\u2081 h1 h,\n      show prop.subst x v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, prop.subst x v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op t\u2081 a) (term.subst x v t\u2082) t\u2082 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, prop.subst x v (prop.call t) = prop.call a) (term.subst x v t) t h1 h\n    )},\n    case prop.post t\u2081 t\u2082 { from (\n      have h: prop.subst x v (prop.post t\u2081 t\u2082) = prop.post (term.subst x v t\u2081) (term.subst x v t\u2082), by unfold prop.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_prop x (prop.post t\u2081 t\u2082), from free_in_prop.post\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.subst x v t\u2081 = t\u2081, from unchanged_of_subst_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_prop x (prop.post t\u2081 t\u2082), from free_in_prop.post\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.subst x v t\u2082 = t\u2082, from unchanged_of_subst_nonfree_term this,\n      have prop.subst x v (prop.post t\u2081 t\u2082) = prop.post t\u2081 (term.subst x v t\u2082),\n      from @eq.subst term (\u03bba, prop.subst x v (prop.post t\u2081 t\u2082) = prop.post a (term.subst x v t\u2082)) (term.subst x v t\u2081) t\u2081 h1 h,\n      show prop.subst x v (prop.post t\u2081 t\u2082) = prop.post t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, prop.subst x v (prop.post t\u2081 t\u2082) = prop.post t\u2081 a) (term.subst x v t\u2082) t\u2082 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 (\u03bba, 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 (\u03bba, 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, 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 (\u03bba, 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 (\u03bba, 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, 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 \u2209 FV P \u2192 (vc.subst x v P = P) :=\n  assume x_not_free: \u00ac 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, vc.subst x v (vc.term t) = vc.term a) (term.subst x v t) t this h\n    )},\n    case vc.not P\u2081 ih { from (\n      have h: vc.subst x v P\u2081.not = (vc.subst x v P\u2081).not, by unfold vc.subst,\n      have \u00ac free_in_vc x P\u2081, from (\n        assume : free_in_vc x P\u2081,\n        have free_in_vc x P\u2081.not, from free_in_vc.not this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have vc.subst x v P\u2081 = P\u2081, from ih this,\n      show vc.subst x v P\u2081.not = P\u2081.not,\n      from @eq.subst vc (\u03bba, vc.subst x v P\u2081.not = vc.not a) (vc.subst x v P\u2081) P\u2081 this h\n    )},\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have h: vc.subst x v (vc.and P\u2081 P\u2082) = (vc.subst x v P\u2081 \u22c0 vc.subst x v P\u2082), by unfold vc.subst,\n      have \u00ac free_in_vc x P\u2081, from (\n        assume : free_in_vc x P\u2081,\n        have free_in_vc x (P\u2081 \u22c0 P\u2082), from free_in_vc.and\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: vc.subst x v P\u2081 = P\u2081, from P\u2081_ih this,\n      have \u00ac free_in_vc x P\u2082, from (\n        assume : free_in_vc x P\u2082,\n        have free_in_vc x (P\u2081 \u22c0 P\u2082), from free_in_vc.and\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: vc.subst x v P\u2082 = P\u2082, from P\u2082_ih this,\n      have vc.subst x v (P\u2081 \u22c0 P\u2082) = (P\u2081 \u22c0 vc.subst x v P\u2082),\n      from @eq.subst vc (\u03bba, vc.subst x v (vc.and P\u2081 P\u2082) = (a \u22c0 vc.subst x v P\u2082)) (vc.subst x v P\u2081) P\u2081 h1 h,\n      show vc.subst x v (P\u2081 \u22c0 P\u2082) = (P\u2081 \u22c0 P\u2082),\n      from @eq.subst vc (\u03bba, vc.subst x v (vc.and P\u2081 P\u2082) = (P\u2081 \u22c0 a)) (vc.subst x v P\u2082) P\u2082 h2 this\n    )},\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have h: vc.subst x v (vc.or P\u2081 P\u2082) = (vc.subst x v P\u2081 \u22c1 vc.subst x v P\u2082), by unfold vc.subst,\n      have \u00ac free_in_vc x P\u2081, from (\n        assume : free_in_vc x P\u2081,\n        have free_in_vc x (P\u2081 \u22c1 P\u2082), from free_in_vc.or\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: vc.subst x v P\u2081 = P\u2081, from P\u2081_ih this,\n      have \u00ac free_in_vc x P\u2082, from (\n        assume : free_in_vc x P\u2082,\n        have free_in_vc x (P\u2081 \u22c1 P\u2082), from free_in_vc.or\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: vc.subst x v P\u2082 = P\u2082, from P\u2082_ih this,\n      have vc.subst x v (P\u2081 \u22c1 P\u2082) = (P\u2081 \u22c1 vc.subst x v P\u2082),\n      from @eq.subst vc (\u03bba, vc.subst x v (vc.or P\u2081 P\u2082) = (a \u22c1 vc.subst x v P\u2082)) (vc.subst x v P\u2081) P\u2081 h1 h,\n      show vc.subst x v (P\u2081 \u22c1 P\u2082) = (P\u2081 \u22c1 P\u2082),\n      from @eq.subst vc (\u03bba, vc.subst x v (vc.or P\u2081 P\u2082) = (P\u2081 \u22c1 a)) (vc.subst x v P\u2082) P\u2082 h2 this\n    )},\n    case vc.pre t\u2081 t\u2082 { from (\n      have h: vc.subst x v (vc.pre t\u2081 t\u2082) = vc.pre (term.subst x v t\u2081) (term.subst x v t\u2082), by unfold vc.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.pre t\u2081 t\u2082), from free_in_vc.pre\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.subst x v t\u2081 = t\u2081, from unchanged_of_subst_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_vc x (vc.pre t\u2081 t\u2082), from free_in_vc.pre\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.subst x v t\u2082 = t\u2082, from unchanged_of_subst_nonfree_term this,\n      have vc.subst x v (vc.pre t\u2081 t\u2082) = vc.pre t\u2081 (term.subst x v t\u2082),\n      from @eq.subst term (\u03bba, vc.subst x v (vc.pre t\u2081 t\u2082) = vc.pre a (term.subst x v t\u2082)) (term.subst x v t\u2081) t\u2081 h1 h,\n      show vc.subst x v (vc.pre t\u2081 t\u2082) = vc.pre t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, vc.subst x v (vc.pre t\u2081 t\u2082) = vc.pre t\u2081 a) (term.subst x v t\u2082) t\u2082 h2 this\n    )},\n    case vc.pre\u2081 op t { from (\n      have h: vc.subst x v (vc.pre\u2081 op t) = vc.pre\u2081 op (term.subst x v t), by unfold vc.subst,\n      have \u00ac free_in_term x t, from (\n        assume : free_in_term x t,\n        have free_in_vc x (vc.pre\u2081 op t), from free_in_vc.preop this,\n        show \u00abfalse\u00bb, 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\u2081 op t) = vc.pre\u2081 op t,\n      from @eq.subst term (\u03bba, vc.subst x v (vc.pre\u2081 op t) = vc.pre\u2081 op a) (term.subst x v t) t this h\n    )},\n    case vc.pre\u2082 op t\u2081 t\u2082 { from (\n      have h: vc.subst x v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op (term.subst x v t\u2081) (term.subst x v t\u2082),\n      by unfold vc.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082), from free_in_vc.preop\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.subst x v t\u2081 = t\u2081, from unchanged_of_subst_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082), from free_in_vc.preop\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.subst x v t\u2082 = t\u2082, from unchanged_of_subst_nonfree_term this,\n      have vc.subst x v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op t\u2081 (term.subst x v t\u2082),\n      from @eq.subst term (\u03bba, vc.subst x v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op a (term.subst x v t\u2082)) (term.subst x v t\u2081) t\u2081 h1 h,\n      show vc.subst x v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, vc.subst x v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op t\u2081 a) (term.subst x v t\u2082) t\u2082 h2 this\n    )},\n    case vc.post t\u2081 t\u2082 { from (\n      have h: vc.subst x v (vc.post t\u2081 t\u2082) = vc.post (term.subst x v t\u2081) (term.subst x v t\u2082), by unfold vc.subst,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.post t\u2081 t\u2082), from free_in_vc.post\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.subst x v t\u2081 = t\u2081, from unchanged_of_subst_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_vc x (vc.post t\u2081 t\u2082), from free_in_vc.post\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.subst x v t\u2082 = t\u2082, from unchanged_of_subst_nonfree_term this,\n      have vc.subst x v (vc.post t\u2081 t\u2082) = vc.post t\u2081 (term.subst x v t\u2082),\n      from @eq.subst term (\u03bba, vc.subst x v (vc.post t\u2081 t\u2082) = vc.post a (term.subst x v t\u2082)) (term.subst x v t\u2081) t\u2081 h1 h,\n      show vc.subst x v (vc.post t\u2081 t\u2082) = vc.post t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, vc.subst x v (vc.post t\u2081 t\u2082) = vc.post t\u2081 a) (term.subst x v t\u2082) t\u2082 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 (\u03bba, 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 (\u03bba, 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, 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 \u2209 FV P \u2192 (vc.substt x t P = P) :=\n  assume x_not_free: \u00ac free_in_vc x P,\n  begin\n    induction P,\n    case vc.term t\u2081 { from (\n      have h: vc.substt x t (vc.term t\u2081) = term.substt x t t\u2081, by unfold vc.substt,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.term t\u2081), from free_in_vc.term this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have term.substt x t t\u2081 = t\u2081, from unchanged_of_substt_nonfree_term this,\n      show vc.substt x t t\u2081 = vc.term t\u2081,\n      from @eq.subst term (\u03bba, vc.substt x t (vc.term t\u2081) = vc.term a) (term.substt x t t\u2081) t\u2081 this h\n    )},\n    case vc.not P\u2081 ih { from (\n      have h: vc.substt x t P\u2081.not = (vc.substt x t P\u2081).not, by unfold vc.substt,\n      have \u00ac free_in_vc x P\u2081, from (\n        assume : free_in_vc x P\u2081,\n        have free_in_vc x P\u2081.not, from free_in_vc.not this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have vc.substt x t P\u2081 = P\u2081, from ih this,\n      show vc.substt x t P\u2081.not = P\u2081.not,\n      from @eq.subst vc (\u03bba, vc.substt x t P\u2081.not = vc.not a) (vc.substt x t P\u2081) P\u2081 this h\n    )},\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have h: vc.substt x t (vc.and P\u2081 P\u2082) = (vc.substt x t P\u2081 \u22c0 vc.substt x t P\u2082), by unfold vc.substt,\n      have \u00ac free_in_vc x P\u2081, from (\n        assume : free_in_vc x P\u2081,\n        have free_in_vc x (P\u2081 \u22c0 P\u2082), from free_in_vc.and\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: vc.substt x t P\u2081 = P\u2081, from P\u2081_ih this,\n      have \u00ac free_in_vc x P\u2082, from (\n        assume : free_in_vc x P\u2082,\n        have free_in_vc x (P\u2081 \u22c0 P\u2082), from free_in_vc.and\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: vc.substt x t P\u2082 = P\u2082, from P\u2082_ih this,\n      have vc.substt x t (P\u2081 \u22c0 P\u2082) = (P\u2081 \u22c0 vc.substt x t P\u2082),\n      from @eq.subst vc (\u03bba, vc.substt x t (vc.and P\u2081 P\u2082) = (a \u22c0 vc.substt x t P\u2082)) (vc.substt x t P\u2081) P\u2081 h1 h,\n      show vc.substt x t (P\u2081 \u22c0 P\u2082) = (P\u2081 \u22c0 P\u2082),\n      from @eq.subst vc (\u03bba, vc.substt x t (vc.and P\u2081 P\u2082) = (P\u2081 \u22c0 a)) (vc.substt x t P\u2082) P\u2082 h2 this\n    )},\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have h: vc.substt x t (vc.or P\u2081 P\u2082) = (vc.substt x t P\u2081 \u22c1 vc.substt x t P\u2082), by unfold vc.substt,\n      have \u00ac free_in_vc x P\u2081, from (\n        assume : free_in_vc x P\u2081,\n        have free_in_vc x (P\u2081 \u22c1 P\u2082), from free_in_vc.or\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: vc.substt x t P\u2081 = P\u2081, from P\u2081_ih this,\n      have \u00ac free_in_vc x P\u2082, from (\n        assume : free_in_vc x P\u2082,\n        have free_in_vc x (P\u2081 \u22c1 P\u2082), from free_in_vc.or\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: vc.substt x t P\u2082 = P\u2082, from P\u2082_ih this,\n      have vc.substt x t (P\u2081 \u22c1 P\u2082) = (P\u2081 \u22c1 vc.substt x t P\u2082),\n      from @eq.subst vc (\u03bba, vc.substt x t (vc.or P\u2081 P\u2082) = (a \u22c1 vc.substt x t P\u2082)) (vc.substt x t P\u2081) P\u2081 h1 h,\n      show vc.substt x t (P\u2081 \u22c1 P\u2082) = (P\u2081 \u22c1 P\u2082),\n      from @eq.subst vc (\u03bba, vc.substt x t (vc.or P\u2081 P\u2082) = (P\u2081 \u22c1 a)) (vc.substt x t P\u2082) P\u2082 h2 this\n    )},\n    case vc.pre t\u2081 t\u2082 { from (\n      have h: vc.substt x t (vc.pre t\u2081 t\u2082) = vc.pre (term.substt x t t\u2081) (term.substt x t t\u2082), by unfold vc.substt,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.pre t\u2081 t\u2082), from free_in_vc.pre\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.substt x t t\u2081 = t\u2081, from unchanged_of_substt_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_vc x (vc.pre t\u2081 t\u2082), from free_in_vc.pre\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.substt x t t\u2082 = t\u2082, from unchanged_of_substt_nonfree_term this,\n      have vc.substt x t (vc.pre t\u2081 t\u2082) = vc.pre t\u2081 (term.substt x t t\u2082),\n      from @eq.subst term (\u03bba, vc.substt x t (vc.pre t\u2081 t\u2082) = vc.pre a (term.substt x t t\u2082)) (term.substt x t t\u2081) t\u2081 h1 h,\n      show vc.substt x t (vc.pre t\u2081 t\u2082) = vc.pre t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, vc.substt x t (vc.pre t\u2081 t\u2082) = vc.pre t\u2081 a) (term.substt x t t\u2082) t\u2082 h2 this\n    )},\n    case vc.pre\u2081 op t\u2081 { from (\n      have h: vc.substt x t (vc.pre\u2081 op t\u2081) = vc.pre\u2081 op (term.substt x t t\u2081), by unfold vc.substt,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.pre\u2081 op t\u2081), from free_in_vc.preop this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have term.substt x t t\u2081 = t\u2081, from unchanged_of_substt_nonfree_term this,\n      show vc.substt x t (vc.pre\u2081 op t\u2081 ) = vc.pre\u2081 op t\u2081,\n      from @eq.subst term (\u03bba, vc.substt x t (vc.pre\u2081 op t\u2081) = vc.pre\u2081 op a) (term.substt x t t\u2081) t\u2081 this h\n    )},\n    case vc.pre\u2082 op t\u2081 t\u2082 { from (\n      have h: vc.substt x t (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op (term.substt x t t\u2081) (term.substt x t t\u2082),\n      by unfold vc.substt,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082), from free_in_vc.preop\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.substt x t t\u2081 = t\u2081, from unchanged_of_substt_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082), from free_in_vc.preop\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.substt x t t\u2082 = t\u2082, from unchanged_of_substt_nonfree_term this,\n      have vc.substt x t (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op t\u2081 (term.substt x t t\u2082),\n      from @eq.subst term (\u03bba, vc.substt x t (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op a (term.substt x t t\u2082)) (term.substt x t t\u2081) t\u2081 h1 h,\n      show vc.substt x t (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, vc.substt x t (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op t\u2081 a) (term.substt x t t\u2082) t\u2082 h2 this\n    )},\n    case vc.post t\u2081 t\u2082 { from (\n      have h: vc.substt x t (vc.post t\u2081 t\u2082) = vc.post (term.substt x t t\u2081) (term.substt x t t\u2082), by unfold vc.substt,\n      have \u00ac free_in_term x t\u2081, from (\n        assume : free_in_term x t\u2081,\n        have free_in_vc x (vc.post t\u2081 t\u2082), from free_in_vc.post\u2081 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h1: term.substt x t t\u2081 = t\u2081, from unchanged_of_substt_nonfree_term this,\n      have \u00ac free_in_term x t\u2082, from (\n        assume : free_in_term x t\u2082,\n        have free_in_vc x (vc.post t\u2081 t\u2082), from free_in_vc.post\u2082 this,\n        show \u00abfalse\u00bb, from x_not_free this\n      ),\n      have h2: term.substt x t t\u2082 = t\u2082, from unchanged_of_substt_nonfree_term this,\n      have vc.substt x t (vc.post t\u2081 t\u2082) = vc.post t\u2081 (term.substt x t t\u2082),\n      from @eq.subst term (\u03bba, vc.substt x t (vc.post t\u2081 t\u2082) = vc.post a (term.substt x t t\u2082)) (term.substt x t t\u2081) t\u2081 h1 h,\n      show vc.substt x t (vc.post t\u2081 t\u2082) = vc.post t\u2081 t\u2082,\n      from @eq.subst term (\u03bba, vc.substt x t (vc.post t\u2081 t\u2082) = vc.post t\u2081 a) (term.substt x t t\u2082) t\u2082 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 (\u03bba, 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 (\u03bba, 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 \u00ac 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 \u00abfalse\u00bb, 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 (\u03bba, 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 \u2192 (\u2200\u03c3, vc.subst_env \u03c3 P = P) :=\n  assume x_not_free: (\u2200x, x \u2209 FV P),\n  assume \u03c3: env,\n  begin\n    induction \u03c3 with \u03c3' x v ih,\n\n    show (vc.subst_env env.empty P = P), by unfold vc.subst_env,\n\n    show (vc.subst_env (\u03c3'[x\u21a6v]) P = P), by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) P = vc.subst x v (vc.subst_env \u03c3' 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) \u2192 x \u2260 y \u2227 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\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n    show x \u2260 y \u2227 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 \u25b8 x_free_in_subst,\n      show x \u2260 y \u2227 free_in_term x (term.value v'), from absurd this free_in_term.value.inv\n    ),\n    show x \u2260 y \u2227 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 \u25b8 x_free_in_subst,\n        show x \u2260 y \u2227 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 \u25b8 x_free_in_subst,\n        have x_is_z: x = z, from free_in_term.var.inv this,\n        have x \u2260 y, from x_is_z.symm \u25b8 (ne.symm y_is_z),\n        show x \u2260 y \u2227 free_in_term x (term.var z), from \u27e8this, x_is_z \u25b8 free_in_term.var x\u27e9\n    ),\n    show x \u2260 y \u2227 free_in_term x (term.unop unop t\u2081), from (\n      have term.subst y v (term.unop unop t\u2081) = term.unop unop (term.subst y v t\u2081), by unfold term.subst,\n      have free_in_term x (term.unop unop (term.subst y v t\u2081)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081), from free_in_term.unop.inv this,\n      have x \u2260 y \u2227 free_in_term x t\u2081, from t\u2081_ih this,\n      show x \u2260 y \u2227 free_in_term x (term.unop unop t\u2081), from \u27e8this.left, free_in_term.unop this.right\u27e9\n    ),\n    show x \u2260 y \u2227 free_in_term x (term.binop binop t\u2082 t\u2083), from (\n      have term.subst y v (term.binop binop t\u2082 t\u2083) = term.binop binop (term.subst y v t\u2082) (term.subst y v t\u2083),\n      by unfold term.subst,\n      have free_in_term x (term.binop binop (term.subst y v t\u2082) (term.subst y v t\u2083)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2082) \u2228 free_in_term x (term.subst y v t\u2083), from free_in_term.binop.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from t\u2082_ih this,\n        show x \u2260 y \u2227 free_in_term x (term.binop binop t\u2082 t\u2083), from \u27e8this.left, free_in_term.binop\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2083),\n        have x \u2260 y \u2227 free_in_term x t\u2083, from t\u2083_ih this,\n        show x \u2260 y \u2227 free_in_term x (term.binop binop t\u2082 t\u2083), from \u27e8this.left, free_in_term.binop\u2082 this.right\u27e9\n      )\n    ),\n    show x \u2260 y \u2227 free_in_term x (term.app t\u2084 t\u2085), from (\n      have term.subst y v (term.app t\u2084 t\u2085) = term.app (term.subst y v t\u2084) (term.subst y v t\u2085),\n      by unfold term.subst,\n      have free_in_term x (term.app (term.subst y v t\u2084) (term.subst y v t\u2085)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2084) \u2228 free_in_term x (term.subst y v t\u2085), from free_in_term.app.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2084),\n        have x \u2260 y \u2227 free_in_term x t\u2084, from t\u2084_ih this,\n        show x \u2260 y \u2227 free_in_term x (term.app t\u2084 t\u2085), from \u27e8this.left, free_in_term.app\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2085),\n        have x \u2260 y \u2227 free_in_term x t\u2085, from t\u2085_ih this,\n        show x \u2260 y \u2227 free_in_term x (term.app t\u2084 t\u2085), from \u27e8this.left, free_in_term.app\u2082 this.right\u27e9\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) \u2192 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\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_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 \u25b8 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 \u25b8 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 \u25b8 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\u2081) = term.unop unop (term.substt x t' t\u2081), by unfold term.substt,\n      have free_in_term x (term.unop unop (term.substt x t' t\u2081)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.substt x t' t\u2081), from free_in_term.unop.inv this,\n      show free_in_term x t', from t\u2081_ih this\n    ),\n    show free_in_term x t', from (\n      have term.substt x t' (term.binop binop t\u2082 t\u2083) = term.binop binop (term.substt x t' t\u2082) (term.substt x t' t\u2083),\n      by unfold term.substt,\n      have free_in_term x (term.binop binop (term.substt x t' t\u2082) (term.substt x t' t\u2083)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.substt x t' t\u2082) \u2228 free_in_term x (term.substt x t' t\u2083),\n      from free_in_term.binop.inv this,\n      or.elim this (\n        assume : free_in_term x (term.substt x t' t\u2082),\n        show free_in_term x t', from t\u2082_ih this\n      ) (\n        assume : free_in_term x (term.substt x t' t\u2083),\n        show free_in_term x t', from t\u2083_ih this\n      )\n    ),\n    show free_in_term x t', from (\n      have term.substt x t' (term.app t\u2084 t\u2085) = term.app (term.substt x t' t\u2084) (term.substt x t' t\u2085),\n      by unfold term.substt,\n      have free_in_term x (term.app (term.substt x t' t\u2084) (term.substt x t' t\u2085)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.substt x t' t\u2084) \u2228 free_in_term x (term.substt x t' t\u2085), from free_in_term.app.inv this,\n      or.elim this (\n        assume : free_in_term x (term.substt x t' t\u2084),\n        show free_in_term x t', from t\u2084_ih this\n      ) (\n        assume : free_in_term x (term.substt x t' t\u2085),\n        show free_in_term x t', from t\u2085_ih this\n      )\n    )\n  end\n\nlemma free_of_subst_env_term_step {t: term} {\u03c3: env} {x y: var} {v: value}:\n        free_in_term x (term.subst_env (\u03c3[y\u21a6v]) t) \u2192 x \u2260 y \u2227 free_in_term x (term.subst_env \u03c3 t) :=\n  assume x_free: free_in_term x (term.subst_env (\u03c3[y\u21a6v]) t),\n  have term.subst_env (\u03c3[y\u21a6v]) t = term.subst y v (term.subst_env \u03c3 t), by unfold term.subst_env,\n  have free_in_term x (term.subst y v (term.subst_env \u03c3 t)), from this \u25b8 x_free,\n  show x \u2260 y \u2227 free_in_term x (term.subst_env \u03c3 t), from free_of_subst_term this\n\nlemma free_of_subst_env_term {t: term} {\u03c3: env} {x: var}:\n        free_in_term x (term.subst_env \u03c3 t) \u2192 free_in_term x t \u2227 x \u2209 \u03c3 :=\n  assume x_free_in_subst: free_in_term x (term.subst_env \u03c3 t),\n  begin\n    induction \u03c3 with \u03c3' y v ih,\n    show free_in_term x t \u2227 x \u2209 env.empty, from (\n      have h2: x \u2209 env.empty, by begin\n        assume : x \u2208 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 \u2227 x \u2209 env.empty, from \u27e8this \u25b8 x_free_in_subst, h2\u27e9\n    ),\n    show free_in_term x t \u2227 x \u2209 (\u03c3'[y\u21a6v]), from (\n      have h1: x \u2260 y \u2227 free_in_term x (term.subst_env \u03c3' t),\n      from free_of_subst_env_term_step x_free_in_subst,\n      have h2: free_in_term x t \u2227 x \u2209 \u03c3', from ih h1.right,\n      have h3: x \u2209 (\u03c3'[y\u21a6v]), by begin\n        assume : x \u2208 (\u03c3'[y\u21a6v]),\n        have h3: env.contains (\u03c3'[y\u21a6v]) x, from this,\n        cases h3,\n        have h4: x \u2260 x, from h1.left,\n        contradiction,\n        have h5: \u00ac env.contains \u03c3' x, from h2.right,\n        contradiction\n      end,\n      show free_in_term x t \u2227 x \u2209 (\u03c3'[y\u21a6v]), from \u27e8h2.left, h3\u27e9\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) \u2192 x \u2260 y \u2227 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 \u25b8 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 \u2260 y \u2227 free_in_term x t, from free_of_subst_term this,\n      show x \u2260 y \u2227 free_in_prop x (prop.term t), from \u27e8this.left, free_in_prop.term this.right\u27e9\n    )},\n    case prop.not P\u2081 P\u2081_ih { from (\n      have (prop.subst y v P\u2081.not = (prop.subst y v P\u2081).not), by unfold prop.subst,\n      have free_in_prop x (prop.subst y v P\u2081).not, from this \u25b8 x_free_in_subst,\n      have free_in_prop x (prop.subst y v P\u2081), from free_in_prop.not.inv this,\n      have x \u2260 y \u2227 free_in_prop x P\u2081, from P\u2081_ih this,\n      show x \u2260 y \u2227 free_in_prop x P\u2081.not, from \u27e8this.left, free_in_prop.not this.right\u27e9\n    )},\n    case prop.and P\u2082 P\u2083 P\u2082_ih P\u2083_ih { from (\n      have prop.subst y v (prop.and P\u2082 P\u2083) = (prop.subst y v P\u2082 \u22c0 prop.subst y v P\u2083), by unfold prop.subst,\n      have free_in_prop x ((prop.subst y v P\u2082) \u22c0 (prop.subst y v P\u2083)), from this \u25b8 x_free_in_subst,\n      have free_in_prop x (prop.subst y v P\u2082) \u2228 free_in_prop x (prop.subst y v P\u2083),\n      from free_in_prop.and.inv this,\n      or.elim this (\n        assume : free_in_prop x (prop.subst y v P\u2082),\n        have x \u2260 y \u2227 free_in_prop x P\u2082, from P\u2082_ih this,\n        show x \u2260 y \u2227 free_in_prop x (P\u2082 \u22c0 P\u2083), from \u27e8this.left, free_in_prop.and\u2081 this.right\u27e9\n      ) (\n        assume : free_in_prop x (prop.subst y v P\u2083),\n        have x \u2260 y \u2227 free_in_prop x P\u2083, from P\u2083_ih this,\n        show x \u2260 y \u2227 free_in_prop x (P\u2082 \u22c0 P\u2083), from \u27e8this.left, free_in_prop.and\u2082 this.right\u27e9\n      )\n    )},\n    case prop.or P\u2084 P\u2085 P\u2084_ih P\u2085_ih { from (\n      have prop.subst y v (prop.or P\u2084 P\u2085) = (prop.subst y v P\u2084 \u22c1 prop.subst y v P\u2085), by unfold prop.subst,\n      have free_in_prop x (prop.or (prop.subst y v P\u2084) (prop.subst y v P\u2085)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_prop x (prop.subst y v P\u2084) \u2228 free_in_prop x (prop.subst y v P\u2085),\n      from free_in_prop.or.inv this,\n      or.elim this (\n        assume : free_in_prop x (prop.subst y v P\u2084),\n        have x \u2260 y \u2227 free_in_prop x P\u2084, from P\u2084_ih this,\n        show x \u2260 y \u2227 free_in_prop x (prop.or P\u2084 P\u2085), from \u27e8this.left, free_in_prop.or\u2081 this.right\u27e9\n      ) (\n        assume : free_in_prop x (prop.subst y v P\u2085),\n        have x \u2260 y \u2227 free_in_prop x P\u2085, from P\u2085_ih this,\n        show x \u2260 y \u2227 free_in_prop x (prop.or P\u2084 P\u2085), from \u27e8this.left, free_in_prop.or\u2082 this.right\u27e9\n      )\n    )},\n    case prop.pre t\u2081 t\u2082 { from (\n      have prop.subst y v (prop.pre t\u2081 t\u2082) = prop.pre (term.subst y v t\u2081) (term.subst y v t\u2082), by unfold prop.subst,\n      have free_in_prop x (prop.pre (term.subst y v t\u2081) (term.subst y v t\u2082)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081) \u2228 free_in_term x (term.subst y v t\u2082), from free_in_prop.pre.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2081),\n        have x \u2260 y \u2227 free_in_term x t\u2081, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_prop x (prop.pre t\u2081 t\u2082), from \u27e8this.left, free_in_prop.pre\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_prop x (prop.pre t\u2081 t\u2082), from \u27e8this.left, free_in_prop.pre\u2082 this.right\u27e9\n      )\n    )},\n    case prop.pre\u2081 op t { from (\n      have prop.subst y v (prop.pre\u2081 op t) = prop.pre\u2081 op (term.subst y v t), by unfold prop.subst,\n      have free_in_prop x (prop.pre\u2081 op (term.subst y v t)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t), from free_in_prop.pre\u2081.inv this,\n      have x \u2260 y \u2227 free_in_term x t, from free_of_subst_term this,\n      show x \u2260 y \u2227 free_in_prop x (prop.pre\u2081 op t), from \u27e8this.left, free_in_prop.preop this.right\u27e9\n    )},\n    case prop.pre\u2082 op t\u2081 t\u2082 { from (\n      have prop.subst y v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op (term.subst y v t\u2081) (term.subst y v t\u2082),\n      by unfold prop.subst,\n      have free_in_prop x (prop.pre\u2082 op (term.subst y v t\u2081) (term.subst y v t\u2082)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081) \u2228 free_in_term x (term.subst y v t\u2082), from free_in_prop.pre\u2082.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2081),\n        have x \u2260 y \u2227 free_in_term x t\u2081, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from \u27e8this.left, free_in_prop.preop\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_prop x (prop.pre\u2082 op t\u2081 t\u2082), from \u27e8this.left, free_in_prop.preop\u2082 this.right\u27e9\n      )\n    )},\n    case prop.post t\u2081 t\u2082 { from (\n      have prop.subst y v (prop.post t\u2081 t\u2082) = prop.post (term.subst y v t\u2081) (term.subst y v t\u2082), by unfold prop.subst,\n      have free_in_prop x (prop.post (term.subst y v t\u2081) (term.subst y v t\u2082)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081) \u2228 free_in_term x (term.subst y v t\u2082), from free_in_prop.post.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2081),\n        have x \u2260 y \u2227 free_in_term x t\u2081, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_prop x (prop.post t\u2081 t\u2082), from \u27e8this.left, free_in_prop.post\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_prop x (prop.post t\u2081 t\u2082), from \u27e8this.left, free_in_prop.post\u2082 this.right\u27e9\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 \u25b8 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 \u2260 y \u2227 free_in_term x t, from free_of_subst_term this,\n      show x \u2260 y \u2227 free_in_prop x (prop.call t), from \u27e8this.left, free_in_prop.call this.right\u27e9\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 \u25b8 x_free_in_subst,\n      have x_neq_z: x \u2260 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 \u2260 y, from y_eq_z.symm \u25b8 x_neq_z,\n        have free_in_prop x P, by { simp[y_eq_z] at fre_ite, from fre_ite },\n        show x \u2260 y \u2227 free_in_prop x (prop.forallc z P), from \u27e8x_neq_y, free_in_prop.forallc x_neq_z this\u27e9\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 \u2260 y \u2227 free_in_prop x P, from ih this,\n        show x \u2260 y \u2227 free_in_prop x (prop.forallc z P), from \u27e8this.left, free_in_prop.forallc x_neq_z this.right\u27e9\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 \u25b8 x_free_in_subst,\n      have x_neq_z: x \u2260 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 \u2260 y, from y_eq_z.symm \u25b8 x_neq_z,\n        have free_in_prop x P, by { simp[y_eq_z] at fre_ite, from fre_ite },\n        show x \u2260 y \u2227 free_in_prop x (prop.exis z P), from \u27e8x_neq_y, free_in_prop.exis x_neq_z this\u27e9\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 \u2260 y \u2227 free_in_prop x P, from ih this,\n        show x \u2260 y \u2227 free_in_prop x (prop.exis z P), from \u27e8this.left, free_in_prop.exis x_neq_z this.right\u27e9\n      )\n    )}\n  end\n\nlemma free_of_subst_env_prop {P: prop} {\u03c3: env} {x y: var} {v: value}:\n        free_in_prop x (prop.subst_env (\u03c3[y\u21a6v]) P) \u2192 x \u2260 y \u2227 free_in_prop x (prop.subst_env \u03c3 P) :=\n  assume x_free: free_in_prop x (prop.subst_env (\u03c3[y\u21a6v]) P),\n  have prop.subst_env (\u03c3[y\u21a6v]) P = prop.subst y v (prop.subst_env \u03c3 P), by unfold prop.subst_env,\n  have free_in_prop x (prop.subst y v (prop.subst_env \u03c3 P)), from this \u25b8 x_free,\n  show x \u2260 y \u2227 free_in_prop x (prop.subst_env \u03c3 P), from free_of_subst_prop this\n\nlemma free_of_subst_env {P: prop} {\u03c3: env} {x: var}:\n        free_in_prop x (prop.subst_env \u03c3 P) \u2192 free_in_prop x P :=\n  assume x_free_in_subst: free_in_prop x (prop.subst_env \u03c3 P),\n  begin\n    induction \u03c3 with \u03c3' 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 \u25b8 x_free_in_subst\n    ),\n    show free_in_prop x P, from (\n      have free_in_prop x (prop.subst_env \u03c3' 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) \u2192 x \u2260 y \u2227 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 \u25b8 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 \u2260 y \u2227 free_in_term x t, from free_of_subst_term this,\n      show x \u2260 y \u2227 free_in_vc x (vc.term t), from \u27e8this.left, free_in_vc.term this.right\u27e9\n    )},\n    case vc.not P\u2081 ih { from (\n      have (vc.subst y v P\u2081.not = (vc.subst y v P\u2081).not), by unfold vc.subst,\n      have free_in_vc x (vc.subst y v P\u2081).not, from this \u25b8 x_free_in_subst,\n      have free_in_vc x (vc.subst y v P\u2081), from free_in_vc.not.inv this,\n      have x \u2260 y \u2227 free_in_vc x P\u2081, from ih this,\n      show x \u2260 y \u2227 free_in_vc x P\u2081.not, from \u27e8this.left, free_in_vc.not this.right\u27e9\n    )},\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have vc.subst y v (vc.and P\u2081 P\u2082) = (vc.subst y v P\u2081 \u22c0 vc.subst y v P\u2082), by unfold vc.subst,\n      have free_in_vc x (vc.subst y v P\u2081 \u22c0 vc.subst y v P\u2082), from this \u25b8 x_free_in_subst,\n      have free_in_vc x (vc.subst y v P\u2081) \u2228 free_in_vc x (vc.subst y v P\u2082),\n      from free_in_vc.and.inv this,\n      or.elim this (\n        assume : free_in_vc x (vc.subst y v P\u2081),\n        have x \u2260 y \u2227 free_in_vc x P\u2081, from P\u2081_ih this,\n        show x \u2260 y \u2227 free_in_vc x (P\u2081 \u22c0 P\u2082), from \u27e8this.left, free_in_vc.and\u2081 this.right\u27e9\n      ) (\n        assume : free_in_vc x (vc.subst y v P\u2082),\n        have x \u2260 y \u2227 free_in_vc x P\u2082, from P\u2082_ih this,\n        show x \u2260 y \u2227 free_in_vc x (P\u2081 \u22c0 P\u2082), from \u27e8this.left, free_in_vc.and\u2082 this.right\u27e9\n      )\n    )},\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have vc.subst y v (vc.or P\u2081 P\u2082) = (vc.subst y v P\u2081 \u22c1 vc.subst y v P\u2082), by unfold vc.subst,\n      have free_in_vc x (vc.or (vc.subst y v P\u2081) (vc.subst y v P\u2082)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_vc x (vc.subst y v P\u2081) \u2228 free_in_vc x (vc.subst y v P\u2082),\n      from free_in_vc.or.inv this,\n      or.elim this (\n        assume : free_in_vc x (vc.subst y v P\u2081),\n        have x \u2260 y \u2227 free_in_vc x P\u2081, from P\u2081_ih this,\n        show x \u2260 y \u2227 free_in_vc x (vc.or P\u2081 P\u2082), from \u27e8this.left, free_in_vc.or\u2081 this.right\u27e9\n      ) (\n        assume : free_in_vc x (vc.subst y v P\u2082),\n        have x \u2260 y \u2227 free_in_vc x P\u2082, from P\u2082_ih this,\n        show x \u2260 y \u2227 free_in_vc x (vc.or P\u2081 P\u2082), from \u27e8this.left, free_in_vc.or\u2082 this.right\u27e9\n      )\n    )},\n    case vc.pre t\u2081 t\u2082 { from (\n      have vc.subst y v (vc.pre t\u2081 t\u2082) = vc.pre (term.subst y v t\u2081) (term.subst y v t\u2082), by unfold vc.subst,\n      have free_in_vc x (vc.pre (term.subst y v t\u2081) (term.subst y v t\u2082)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081) \u2228 free_in_term x (term.subst y v t\u2082),\n      from free_in_vc.pre.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2081),\n        have x \u2260 y \u2227 free_in_term x t\u2081, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_vc x (vc.pre t\u2081 t\u2082), from \u27e8this.left, free_in_vc.pre\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_vc x (vc.pre t\u2081 t\u2082), from \u27e8this.left, free_in_vc.pre\u2082 this.right\u27e9\n      )\n    )},\n    case vc.pre\u2081 op t { from (\n      have vc.subst y v (vc.pre\u2081 op t) = vc.pre\u2081 op (term.subst y v t), by unfold vc.subst,\n      have free_in_vc x (vc.pre\u2081 op (term.subst y v t)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t), from free_in_vc.pre\u2081.inv this,\n      have x \u2260 y \u2227 free_in_term x t, from free_of_subst_term this,\n      show x \u2260 y \u2227 free_in_vc x (vc.pre\u2081 op t), from \u27e8this.left, free_in_vc.preop this.right\u27e9\n    )},\n    case vc.pre\u2082 op t\u2081 t\u2082 { from (\n      have vc.subst y v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op (term.subst y v t\u2081) (term.subst y v t\u2082),\n      by unfold vc.subst,\n      have free_in_vc x (vc.pre\u2082 op (term.subst y v t\u2081) (term.subst y v t\u2082)), from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081) \u2228 free_in_term x (term.subst y v t\u2082),\n      from free_in_vc.pre\u2082.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2081),\n        have x \u2260 y \u2227 free_in_term x t\u2081, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082), from \u27e8this.left, free_in_vc.preop\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_vc x (vc.pre\u2082 op t\u2081 t\u2082), from \u27e8this.left, free_in_vc.preop\u2082 this.right\u27e9\n      )\n    )},\n    case vc.post t\u2081 t\u2082 { from (\n      have vc.subst y v (vc.post t\u2081 t\u2082) = vc.post (term.subst y v t\u2081) (term.subst y v t\u2082), by unfold vc.subst,\n      have free_in_vc x (vc.post (term.subst y v t\u2081) (term.subst y v t\u2082)),\n      from this \u25b8 x_free_in_subst,\n      have free_in_term x (term.subst y v t\u2081) \u2228 free_in_term x (term.subst y v t\u2082),\n      from free_in_vc.post.inv this,\n      or.elim this (\n        assume : free_in_term x (term.subst y v t\u2081),\n        have x \u2260 y \u2227 free_in_term x t\u2081, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_vc x (vc.post t\u2081 t\u2082), from \u27e8this.left, free_in_vc.post\u2081 this.right\u27e9\n      ) (\n        assume : free_in_term x (term.subst y v t\u2082),\n        have x \u2260 y \u2227 free_in_term x t\u2082, from free_of_subst_term this,\n        show x \u2260 y \u2227 free_in_vc x (vc.post t\u2081 t\u2082), from \u27e8this.left, free_in_vc.post\u2082 this.right\u27e9\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 (\u03bba, 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 (\u03bba, 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 \u2260 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 (\u03bba, free_in_vc x (vc.univ a P')) z x this.symm h2,\n          show \u00abfalse\u00bb, from (free_in_vc.univ.same.inv) this\n        ),\n        show x \u2260 y \u2227 free_in_vc x (vc.univ z P'), from \u27e8this, h2\u27e9\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 (\u03bba, 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 \u25b8 x_free_in_subst,\n        have h2: x \u2260 z \u2227 free_in_vc x (vc.subst y v P'), from free_in_vc.univ.inv this,\n        have x \u2260 y \u2227 free_in_vc x P', from P'_ih h2.right,\n        show x \u2260 y \u2227 free_in_vc x (vc.univ z P'), from \u27e8this.left, free_in_vc.univ h2.left this.right\u27e9\n      )\n    )}\n  end\n\nlemma free_in_vc.subst2 {P: vc} {\u03c3: env} {x y: var} {v: value}:\n        free_in_vc x (vc.subst_env (\u03c3[y\u21a6v]) P) \u2192 x \u2260 y \u2227 free_in_vc x (vc.subst_env \u03c3 P) :=\n  assume x_free: free_in_vc x (vc.subst_env (\u03c3[y\u21a6v]) P),\n  have vc.subst_env (\u03c3[y\u21a6v]) P = vc.subst y v (vc.subst_env \u03c3 P), by unfold vc.subst_env,\n  have free_in_vc x (vc.subst y v (vc.subst_env \u03c3 P)), from this \u25b8 x_free,\n  show x \u2260 y \u2227 free_in_vc x (vc.subst_env \u03c3 P), from free_in_vc.subst this\n\nlemma free_in_vc.subst_env {P: vc} {\u03c3: env} {x: var}:\n        free_in_vc x (vc.subst_env \u03c3 P) \u2192 free_in_vc x P :=\n  assume x_free_in_subst: free_in_vc x (vc.subst_env \u03c3 P),\n  begin\n    induction \u03c3 with \u03c3' 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 \u25b8 x_free_in_subst\n    ),\n    show free_in_vc x P, from (\n      have free_in_vc x (vc.subst_env \u03c3' 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} {\u03c3: env}:\n  (term.subst_env \u03c3 x = x) \u2228 (\u2203v:value, term.subst_env \u03c3 x = v) :=\n  begin\n    induction \u03c3 with \u03c3' y v' ih,\n    show (term.subst_env env.empty x = x) \u2228 (\u2203v: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) \u2228 (\u2203v:value, term.subst_env env.empty x = v), from or.inl this\n    ),\n    show (term.subst_env (\u03c3'[y\u21a6v']) x = x) \u2228 (\u2203v:value, term.subst_env (\u03c3'[y\u21a6v']) x = v), from (\n      have tsubst: (term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' (term.subst_env \u03c3' x)),\n      by unfold term.subst_env,\n      have (term.subst_env \u03c3' \u2191x = \u2191x \u2228 \u2203 (v : value), term.subst_env \u03c3' \u2191x = \u2191v), from ih,\n      or.elim this (\n        assume \u03c3'_x_is_x: term.subst_env \u03c3' \u2191x = \u2191x,\n        have h: (term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' \u2191x),\n        from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' x) x \u03c3'_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 (\u03c3'[y\u21a6v']) x = v', from eq.trans h this,\n          have (\u2203v:value, term.subst_env (\u03c3'[y\u21a6v']) x = v), from exists.intro v' this,\n          show (term.subst_env (\u03c3'[y\u21a6v']) x = x) \u2228 (\u2203v:value, term.subst_env (\u03c3'[y\u21a6v']) x = v), from or.inr this\n        ) (\n          assume : \u00ac(x = y),\n          have \u00ac(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 (\u03c3'[y\u21a6v']) x = x, from eq.trans h this,\n          show (term.subst_env (\u03c3'[y\u21a6v']) x = x) \u2228 (\u2203v:value, term.subst_env (\u03c3'[y\u21a6v']) x = v), from or.inl this\n        )\n      ) (\n        assume : \u2203 (v : value), term.subst_env \u03c3' \u2191x = \u2191v,\n        let \u27e8v, \u03c3'_x_is_v\u27e9 := this in\n        have h: (term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' \u2191v),\n        from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' x) v \u03c3'_x_is_v tsubst,\n        have term.subst y v' (term.value v) = \u2191v, by unfold term.subst,\n        have term.subst_env (\u03c3'[y\u21a6v']) x = v, from eq.trans h this,\n        have (\u2203v:value, term.subst_env (\u03c3'[y\u21a6v']) x = v), from exists.intro v this,\n        show (term.subst_env (\u03c3'[y\u21a6v']) x = x) \u2228 (\u2203v:value, term.subst_env (\u03c3'[y\u21a6v']) x = v), from or.inr this\n      )\n    )\n  end\n\nlemma term.subst_env.value {\u03c3: env} {v: value}: term.subst_env \u03c3 v = v :=\nbegin\n  induction \u03c3 with \u03c3' x v' ih,\n  show (term.subst_env env.empty v = v), by unfold term.subst_env,\n  show (term.subst_env (\u03c3'[x\u21a6v']) v = v), from (\n    have h: term.subst_env \u03c3' v = v, from ih,\n    have term.subst_env (\u03c3'[x\u21a6v']) v = term.subst x v' (term.subst_env \u03c3' v), by unfold term.subst_env,\n    have h2: term.subst_env (\u03c3'[x\u21a6v']) v = term.subst x v' v,\n    from @eq.subst term (\u03bba, term.subst_env (\u03c3'[x\u21a6v']) v = term.subst x v' a) (term.subst_env \u03c3' v) v h this,\n    have term.subst x v' (term.value v) = \u2191v, by unfold term.subst,\n    show term.subst_env (\u03c3'[x\u21a6v']) v = v, from eq.trans h2 this\n  )\nend\n\nlemma term.subst_env.closed {\u03c3: env} {t: term}: closed t \u2192 (term.subst_env \u03c3 t = t) :=\nbegin\n  assume t_closed: closed t,\n  induction \u03c3 with \u03c3' x v' ih,\n  show (term.subst_env env.empty t = t), by unfold term.subst_env,\n  show (term.subst_env (\u03c3'[x\u21a6v']) t = t), from (\n    have h: term.subst_env \u03c3' t = t, from ih,\n    have term.subst_env (\u03c3'[x\u21a6v']) t = term.subst x v' (term.subst_env \u03c3' t), by unfold term.subst_env,\n    have h2: term.subst_env (\u03c3'[x\u21a6v']) t = term.subst x v' t,\n    from @eq.subst term (\u03bba, term.subst_env (\u03c3'[x\u21a6v']) t = term.subst x v' a) (term.subst_env \u03c3' 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 (\u03c3'[x\u21a6v']) t = t, from eq.trans h2 this\n  )\nend\n\nlemma term.subst_env.var {\u03c3: env} {x: var}:\n      ((\u03c3 x = none) \u2194 (term.subst_env \u03c3 x = x)) \u2227 (\u2200v, (\u03c3 x = some v) \u2194 (term.subst_env \u03c3 x = v)) :=\nbegin\n  induction \u03c3 with \u03c3' y v' ih,\n  show (((env.empty x = none) \u2194 (term.subst_env env.empty x = x))\n     \u2227 (\u2200v, (env.empty x = some v) \u2194 (term.subst_env env.empty x = v))), by begin\n    split,\n    show ((env.empty x = none) \u2194 (term.subst_env env.empty x = x)), by begin\n      split,\n      show ((env.empty x = none) \u2192 (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) \u2192 (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 \u2200v, ((env.empty x = some v) \u2194 (term.subst_env env.empty x = v)), by begin\n      assume v,\n      split,\n      show ((env.empty x = some v) \u2192 (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 \u25b8 env_has_none,\n        contradiction \n      end,\n      show ((term.subst_env env.empty x = v) \u2192 (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 : (\u2191v = \u2191x), from eq.trans subst_is_v.symm this,\n        contradiction \n      end\n    end\n  end,\n  show ((((\u03c3'[y\u21a6v']) x = none) \u2194 (term.subst_env (\u03c3'[y\u21a6v']) x = x))\n     \u2227 (\u2200v, ((\u03c3'[y\u21a6v']) x = some v) \u2194 (term.subst_env (\u03c3'[y\u21a6v']) x = v))), by begin\n    have tsubst: (term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' (term.subst_env \u03c3' x)),\n    by unfold term.subst_env,\n    have app: ((\u03c3'[y\u21a6v']).apply x = (if y = x \u2227 option.is_none (\u03c3'.apply x) then v' else \u03c3'.apply x)),\n    by unfold env.apply,\n    split,\n    show (((\u03c3'[y\u21a6v']) x = none) \u2194 (term.subst_env (\u03c3'[y\u21a6v']) x = x)), by begin\n      split,\n      show (((\u03c3'[y\u21a6v']) x = none) \u2192 (term.subst_env (\u03c3'[y\u21a6v']) x = x)), by begin\n        assume \u03c3'_does_not_have_x: ((\u03c3'[y\u21a6v']) x = none),\n        by_cases (y = x \u2227 option.is_none (\u03c3'.apply x)) with h,\n        show (term.subst_env (\u03c3'[y\u21a6v']) x = x), from\n          have ((\u03c3'[y\u21a6v']).apply x) = v', by { simp[h] at app, rw[h.left], from app },\n          have some v' = none, from eq.trans this.symm \u03c3'_does_not_have_x,\n          by contradiction,\n        show (term.subst_env (\u03c3'[y\u21a6v']) x = x), from\n          have ((\u03c3'[y\u21a6v']).apply x) = \u03c3'.apply x, by { simp[h] at app, from app },\n          have \u03c3'_x_is_none: \u03c3'.apply x = none, from eq.trans this.symm \u03c3'_does_not_have_x,\n          have term.subst_env \u03c3' x = x, from ih.left.mp \u03c3'_x_is_none,\n          have h2: term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' x,\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' 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 \u00ac(y = x) \u2228 \u00ac(option.is_none (env.apply \u03c3' x)) , from not_and_distrib.mp h,\n          have \u00ac(y = x), from this.elim id ( \n            assume : \u00ac(option.is_none (env.apply \u03c3' x)),\n            have (env.apply \u03c3' x) \u2260 none, from option.is_none.ninv.mpr this,\n            show \u00ac(y = x), from absurd \u03c3'_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 (\u03c3'[y\u21a6v']) x = x), from eq.trans h2 this\n      end,\n      show ((term.subst_env (\u03c3'[y\u21a6v']) x = x) \u2192 ((\u03c3'[y\u21a6v']) x = none)), from (\n        assume h: term.subst_env (\u03c3'[y\u21a6v']) x = x,\n        have h2: term.subst y v' (term.subst_env \u03c3' x) = x, from eq.trans tsubst.symm h,\n        have (term.subst_env \u03c3' x = x) \u2228 (\u2203v:value, term.subst_env \u03c3' x = v), from term.subst_env.var.inv,\n        or.elim this (\n          assume : term.subst_env \u03c3' x = x,\n          have \u03c3'_x_is_none: \u03c3' x = none, from ih.left.mpr this,\n          have h3: term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' x,\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' 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 (\u03c3'[y\u21a6v']) x = v', from eq.trans h3 this,\n            have \u2191x = \u2191v', from eq.trans h.symm this,\n            show (\u03c3'[y\u21a6v']) x = none, by contradiction\n          ) (\n            assume : \u00ac(x = y),\n            have y_neq_x: \u00ac(y = x), from ne.symm this,\n            have (\u03c3'[y\u21a6v']).apply x = \u03c3'.apply x, by { simp[y_neq_x] at app, from app },\n            show (\u03c3'[y\u21a6v']).apply x = none, from eq.trans this \u03c3'_x_is_none\n          )\n        ) (\n          assume : (\u2203v'':value, term.subst_env \u03c3' x = v''),\n          let \u27e8v'', \u03c3'_x_is_v''\u27e9 := this in\n          have h3: (term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' \u2191v''),\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' x) v'' \u03c3'_x_is_v'' tsubst,\n          have term.subst y v' (term.value v'') = \u2191v'', by unfold term.subst,\n          have term.subst_env (\u03c3'[y\u21a6v']) x = \u2191v'', from eq.trans h3 this,\n          have \u2191x = \u2191v'', from eq.trans h.symm this,\n          show (\u03c3'[y\u21a6v']) x = none, by contradiction\n        )\n      )\n    end,\n    show (\u2200v, ((\u03c3'[y\u21a6v']) x = some v) \u2194 (term.subst_env (\u03c3'[y\u21a6v']) x = v)), by begin\n      assume v,\n      split,\n      show (((\u03c3'[y\u21a6v']) x = some v) \u2192 (term.subst_env (\u03c3'[y\u21a6v']) x = v)), by begin\n        assume env_has_x: ((\u03c3'[y\u21a6v']) x = some v),\n        have app: ((\u03c3'[y\u21a6v']).apply x = (if y = x \u2227 option.is_none (\u03c3'.apply x) then v' else \u03c3'.apply x)),\n        by unfold env.apply,\n        by_cases (y = x \u2227 option.is_none (\u03c3'.apply x)) with h,\n        show (term.subst_env (\u03c3'[y\u21a6v']) \u2191x = \u2191v), from (\n          have ((\u03c3'[y\u21a6v']).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 (\u03c3'.apply x), from h.right,\n          have \u03c3'.apply x = none, from option.is_none.inv.mpr this,\n          have \u03c3'_x_is_x: term.subst_env \u03c3' x = x, from ih.left.mp this,\n          have term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' (term.subst_env \u03c3' x),\n          by unfold term.subst_env,\n          have h2: term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' (term.var x),\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' x) x \u03c3'_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 (\u03c3'[y\u21a6v']) x = v, from v'_is_v \u25b8 eq.trans h2 this\n        ),\n        show (term.subst_env (\u03c3'[y\u21a6v']) \u2191x = \u2191v), from (\n          have (\u03c3'[y\u21a6v']).apply x = \u03c3'.apply x, by { simp [h] at app, from app },\n          have \u03c3'.apply x = v, from eq.trans this.symm env_has_x,\n          have \u03c3'_x_is_v: term.subst_env \u03c3' \u2191x = \u2191v, from (ih.right v).mp this,\n          have term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' (term.subst_env \u03c3' x),\n          by unfold term.subst_env,\n          have h2: term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' v,\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' x) v \u03c3'_x_is_v tsubst,\n          have term.subst y v' (term.value v) = \u2191v, by unfold term.subst,\n          show term.subst_env (\u03c3'[y\u21a6v']) x = v, from eq.trans h2 this\n        )\n      end,\n      show ((term.subst_env (\u03c3'[y\u21a6v']) x = v) \u2192 ((\u03c3'[y\u21a6v']) x = some v)), from (\n        assume h: term.subst_env (\u03c3'[y\u21a6v']) x = v,\n        have h2: term.subst y v' (term.subst_env \u03c3' x) = v, from eq.trans tsubst.symm h,\n        have (term.subst_env \u03c3' x = x) \u2228 (\u2203v:value, term.subst_env \u03c3' x = v), from term.subst_env.var.inv,\n        or.elim this (\n          assume : term.subst_env \u03c3' x = x,\n          have \u03c3'_x_is_none: \u03c3' x = none, from ih.left.mpr this,\n          have h3: term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' x,\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' 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 (\u03bba, 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 (\u03c3'[y\u21a6v']) x = v', from eq.trans h3 this,\n            have \u2191v = \u2191v', 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 \u03c3' x), from option.is_none.inv.mp \u03c3'_x_is_none,\n            have (if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = v',\n            by { simp[x_is_y.symm], simp[opt_is_none] },\n            have (\u03c3'[y\u21a6v']).apply x = v', from eq.trans app this,\n            have (\u03c3'[y\u21a6v']) x = some v', from this,\n            show (\u03c3'[y\u21a6v']) x = some v, from @eq.subst value (\u03bba, (\u03c3'[y\u21a6v']) x = some a) v' v v_is_v'.symm this\n          ) (\n            assume : \u00ac(x = y),\n            have \u00ac(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 \u2191v = \u2191x, from eq.trans (eq.trans h.symm h3) this,\n            show ((\u03c3'[y\u21a6v']) x = some v), by contradiction\n          )\n        ) (\n          assume : (\u2203v'':value, term.subst_env \u03c3' x = v''),\n          let \u27e8v'', \u03c3'_x_is_v''\u27e9 := this in\n          have h3: (term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' \u2191v''),\n          from @eq.subst term (\u03bba, term.subst_env (\u03c3'[y\u21a6v']) x = term.subst y v' a) (term.subst_env \u03c3' x) v'' \u03c3'_x_is_v'' tsubst,\n          have term.subst y v' (term.value v'') = \u2191v'', by unfold term.subst,\n          have term.subst_env (\u03c3'[y\u21a6v']) x = \u2191v'', from eq.trans h3 this,\n          have v_is_v'': \u2191v = \u2191v'', from eq.trans h.symm this,\n          have term.subst_env \u03c3' x = v,\n          from @eq.subst term (\u03bba, term.subst_env \u03c3' x = a) v'' v v_is_v''.symm \u03c3'_x_is_v'',\n          have \u03c3'_x_app_is_v: env.apply \u03c3' x = some v, from (ih.right v).mpr this,\n          have opt_is_not_none: \u00ac option.is_none (env.apply \u03c3' x),\n          from option.some_iff_not_none.mp (option.is_some_iff_exists.mpr (exists.intro v \u03c3'_x_app_is_v)),\n          have (if y = x \u2227 option.is_none (\u03c3'.apply x) then \u2191v' else \u03c3'.apply x) = \u03c3'.apply x,\n          by { simp[opt_is_not_none] },\n          have (\u03c3'[y\u21a6v']) x = \u03c3'.apply x, from eq.trans app this,\n          show (\u03c3'[y\u21a6v']) x = some v, from eq.trans this \u03c3'_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 \u2209 FV (term.subst x v t) :=\n  assume x_free: x \u2208 FV (term.subst x v t),\n  begin\n    induction t with a,\n\n    show \u00abfalse\u00bb, by begin -- term.value\n      unfold term.subst at x_free,\n      cases x_free\n    end,\n\n    show \u00abfalse\u00bb, 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 \u00abfalse\u00bb, 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 \u00abfalse\u00bb, 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 \u00abfalse\u00bb, 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\u2081 t\u2082: term}: closed t\u2081 \u2192 x \u2209 FV (term.substt x t\u2081 t\u2082) :=\n  assume t_closed: closed t\u2081,\n  assume x_free: x \u2208 FV (term.substt x t\u2081 t\u2082),\n  begin\n    induction t\u2082 with a,\n\n    show \u00abfalse\u00bb, by begin -- term.value\n      unfold term.substt at x_free,\n      cases x_free\n    end,\n\n    show \u00abfalse\u00bb, 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 \u2209 FV t\u2081, from t_closed a,\n      contradiction,\n      simp[h] at x_free,\n      cases x_free,\n      contradiction\n    end,\n\n    show \u00abfalse\u00bb, 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 \u00abfalse\u00bb, 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 \u00abfalse\u00bb, 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} {\u03c3: env} {t: term}: x \u2208 \u03c3 \u2192 x \u2209 FV (term.subst_env \u03c3 t) :=\n  assume x_in_\u03c3: x \u2208 \u03c3,\n  assume x_free: x \u2208 FV (term.subst_env \u03c3 t),\n  begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show \u00abfalse\u00bb, by cases x_in_\u03c3,\n\n    -- \u03c3'[x\u21a6v]\n    show \u00abfalse\u00bb, from (\n      have term.subst_env (\u03c3'[y\u21a6v]) t = term.subst y v (term.subst_env \u03c3' t), by unfold term.subst_env,\n      have x \u2208 FV (term.subst y v (term.subst_env \u03c3' t)), from this \u25b8 x_free,\n      have x_neq_y: x \u2260 y, from (free_of_subst_term this).left,\n      have h: x \u2208 FV (term.subst_env \u03c3' t), from (free_of_subst_term this).right,\n      have x = y \u2228 x \u2208 \u03c3', from env.contains.inv x_in_\u03c3,\n      or.elim this (\n        assume : x = y,\n        show \u00abfalse\u00bb, from x_neq_y this\n      ) (\n        assume : x \u2208 \u03c3',\n        have x \u2209 FV (term.subst_env \u03c3' t), from ih this,\n        show \u00abfalse\u00bb, from this h\n      )\n    )\n  end\n\nlemma prop.not_free_of_subst {x: var} {v: value} {P: prop}: x \u2209 FV (prop.subst x v P) :=\n  assume x_free: x \u2208 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 \u25b8 x_free,\n      have x \u2208 FV (term.subst x v t), from free_in_prop.term.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_subst this\n    )},\n    case prop.not P\u2081 P\u2081_ih { from (\n      have prop.subst x v (prop.not P\u2081) = (P\u2081.subst x v).not, by unfold prop.subst,\n      have x \u2208 FV (P\u2081.subst x v).not, from this \u25b8 x_free,\n      have x \u2208 FV (P\u2081.subst x v), from free_in_prop.not.inv this,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )},\n    case prop.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have prop.subst x v (prop.and P\u2081 P\u2082) = (P\u2081.subst x v \u22c0 P\u2082.subst x v), by unfold prop.subst,\n      have x \u2208 FV (P\u2081.subst x v \u22c0 P\u2082.subst x v), from this \u25b8 x_free,\n      or.elim (free_in_prop.and.inv this) (\n        assume : x \u2208 FV (P\u2081.subst x v),\n        show \u00abfalse\u00bb, from P\u2081_ih this\n      ) (\n        assume : x \u2208 FV (P\u2082.subst x v),\n        show \u00abfalse\u00bb, from P\u2082_ih this\n      )\n    )},\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have prop.subst x v (prop.or P\u2081 P\u2082) = (P\u2081.subst x v \u22c1 P\u2082.subst x v), by unfold prop.subst,\n      have x \u2208 FV (P\u2081.subst x v \u22c1 P\u2082.subst x v), from this \u25b8 x_free,\n      or.elim (free_in_prop.or.inv this) (\n        assume : x \u2208 FV (P\u2081.subst x v),\n        show \u00abfalse\u00bb, from P\u2081_ih this\n      ) (\n        assume : x \u2208 FV (P\u2082.subst x v),\n        show \u00abfalse\u00bb, from P\u2082_ih this\n      )\n    )},\n    case prop.pre t\u2081 t\u2082 { from (\n      have prop.subst x v (prop.pre t\u2081 t\u2082) = prop.pre (t\u2081.subst x v) (t\u2082.subst x v), by unfold prop.subst,\n      have x \u2208 FV (prop.pre (t\u2081.subst x v) (t\u2082.subst x v)), from this \u25b8 x_free,\n      or.elim (free_in_prop.pre.inv this) (\n        assume : x \u2208 FV (t\u2081.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      ) (\n        assume : x \u2208 FV (t\u2082.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      )\n    )},\n    case prop.pre\u2081 op t { from (\n      have prop.subst x v (prop.pre\u2081 op t) = prop.pre\u2081 op (t.subst x v), by unfold prop.subst,\n      have x \u2208 FV (prop.pre\u2081 op (t.subst x v)), from this \u25b8 x_free,\n      have x \u2208 FV (t.subst x v), from free_in_prop.pre\u2081.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_subst this\n    )},\n    case prop.pre\u2082 op t\u2081 t\u2082 { from (\n      have prop.subst x v (prop.pre\u2082 op t\u2081 t\u2082) = prop.pre\u2082 op (t\u2081.subst x v) (t\u2082.subst x v),\n      by unfold prop.subst,\n      have x \u2208 FV (prop.pre\u2082 op (t\u2081.subst x v) (t\u2082.subst x v)), from this \u25b8 x_free,\n      or.elim (free_in_prop.pre\u2082.inv this) (\n        assume : x \u2208 FV (t\u2081.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      ) (\n        assume : x \u2208 FV (t\u2082.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      )\n    )},\n    case prop.post t\u2081 t\u2082 { from (\n      have prop.subst x v (prop.post t\u2081 t\u2082) = prop.post (t\u2081.subst x v) (t\u2082.subst x v), by unfold prop.subst,\n      have x \u2208 FV (prop.post (t\u2081.subst x v) (t\u2082.subst x v)), from this \u25b8 x_free,\n      or.elim (free_in_prop.post.inv this) (\n        assume : x \u2208 FV (t\u2081.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      ) (\n        assume : x \u2208 FV (t\u2082.subst x v),\n        show \u00abfalse\u00bb, 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 \u2208 FV (prop.call (t.subst x v)), from this \u25b8 x_free,\n      have x \u2208 FV (t.subst x v), from free_in_prop.call.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_subst this\n    )},\n    case prop.forallc y P\u2081 P\u2081_ih { from (\n      have prop.subst x v (prop.forallc y P\u2081) = prop.forallc y (if x = y then P\u2081 else P\u2081.subst x v),\n      by unfold prop.subst,\n      have x \u2208 FV (prop.forallc y (if x = y then P\u2081 else P\u2081.subst x v)),\n      from this \u25b8 x_free,\n      have y_neq_x: x \u2260 y, from (free_in_prop.forallc.inv this).left,\n      have x \u2208 FV (prop.forallc y (P\u2081.subst x v)), by { simp[y_neq_x] at this, from this },\n      have x \u2208 FV (P\u2081.subst x v), from (free_in_prop.forallc.inv this).right,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )},\n    case prop.exis y P\u2081 P\u2081_ih { from (\n      have prop.subst x v (prop.exis y P\u2081)\n         = prop.exis y (if x = y then P\u2081 else P\u2081.subst x v), by unfold prop.subst,\n      have x \u2208 FV (prop.exis y (if x = y then P\u2081 else P\u2081.subst x v)), from this \u25b8 x_free,\n      have y_neq_x: x \u2260 y, from (free_in_prop.exis.inv this).left,\n      have x \u2208 FV (prop.exis y (P\u2081.subst x v)), by { simp[y_neq_x] at this, from this },\n      have x \u2208 FV (P\u2081.subst x v), from (free_in_prop.exis.inv this).right,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )}\n  end\n\nlemma prop.not_free_of_subst_env {x: var} {\u03c3: env} {P: prop}: x \u2208 \u03c3 \u2192 x \u2209 FV (prop.subst_env \u03c3 P) :=\n  assume x_in_\u03c3: x \u2208 \u03c3,\n  assume x_free: x \u2208 FV (prop.subst_env \u03c3 P),\n  begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show \u00abfalse\u00bb, by cases x_in_\u03c3,\n\n    -- \u03c3'[x\u21a6v]\n    show \u00abfalse\u00bb, from (\n      have prop.subst_env (\u03c3'[y\u21a6v]) P = prop.subst y v (prop.subst_env \u03c3' P), by unfold prop.subst_env,\n      have x \u2208 FV (prop.subst y v (prop.subst_env \u03c3' P)), from this \u25b8 x_free,\n      have x_neq_y: x \u2260 y, from (free_of_subst_prop this).left,\n      have h: x \u2208 FV (prop.subst_env \u03c3' P), from (free_of_subst_prop this).right,\n      have x = y \u2228 x \u2208 \u03c3', from env.contains.inv x_in_\u03c3,\n      or.elim this (\n        assume : x = y,\n        show \u00abfalse\u00bb, from x_neq_y this\n      ) (\n        assume : x \u2208 \u03c3',\n        have x \u2209 FV (prop.subst_env \u03c3' P), from ih this,\n        show \u00abfalse\u00bb, from this h\n      )\n    )\n  end\n\nlemma term.closed_of_closed_subst {\u03c3: env} {t: term}: closed_subst \u03c3 t \u2192 closed (term.subst_env \u03c3 t) :=\n  assume t_closed_subst: closed_subst \u03c3 t,\n  show closed (term.subst_env \u03c3 t), from (\n    assume x: var,\n    assume h1: x \u2208 FV (term.subst_env \u03c3 t),\n    have x \u2208 FV t, from (free_of_subst_env_term h1).left,\n    have x \u2208 \u03c3.dom, from t_closed_subst this,\n    have x \u2208 \u03c3, from this,\n    have h2: x \u2209 FV (term.subst_env \u03c3 t), from term.not_free_of_subst_env this,\n    show \u00abfalse\u00bb, from h2 h1\n  )\n\nlemma prop.closed_of_closed_subst {\u03c3: env} {P: prop}: closed_subst \u03c3 P \u2192 closed (prop.subst_env \u03c3 P) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  show closed (prop.subst_env \u03c3 P), from (\n    assume x: var,\n    assume h1: x \u2208 FV (prop.subst_env \u03c3 P),\n    have x \u2208 FV P, from free_of_subst_env h1,\n    have x \u2208 \u03c3.dom, from P_closed_subst this,\n    have x \u2208 \u03c3, from this,\n    have h2: x \u2209 FV (prop.subst_env \u03c3 P), from prop.not_free_of_subst_env this,\n    show \u00abfalse\u00bb, from h2 h1\n  )\n\nlemma vc.not_free_of_subst {x: var} {v: value} {P: vc}: x \u2209 FV (vc.subst x v P) :=\n  assume x_free: x \u2208 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 \u25b8 x_free,\n      have x \u2208 FV (term.subst x v t), from free_in_vc.term.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_subst this\n    )},\n    case vc.not P\u2081 P\u2081_ih { from (\n      have vc.subst x v (vc.not P\u2081) = (P\u2081.subst x v).not, by unfold vc.subst,\n      have x \u2208 FV (P\u2081.subst x v).not, from this \u25b8 x_free,\n      have x \u2208 FV (P\u2081.subst x v), from free_in_vc.not.inv this,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )},\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have vc.subst x v (vc.and P\u2081 P\u2082) = (P\u2081.subst x v \u22c0 P\u2082.subst x v), by unfold vc.subst,\n      have x \u2208 FV (P\u2081.subst x v \u22c0 P\u2082.subst x v), from this \u25b8 x_free,\n      or.elim (free_in_vc.and.inv this) (\n        assume : x \u2208 FV (P\u2081.subst x v),\n        show \u00abfalse\u00bb, from P\u2081_ih this\n      ) (\n        assume : x \u2208 FV (P\u2082.subst x v),\n        show \u00abfalse\u00bb, from P\u2082_ih this\n      )\n    )},\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have vc.subst x v (vc.or P\u2081 P\u2082) = (P\u2081.subst x v \u22c1 P\u2082.subst x v), by unfold vc.subst,\n      have x \u2208 FV (P\u2081.subst x v \u22c1 P\u2082.subst x v), from this \u25b8 x_free,\n      or.elim (free_in_vc.or.inv this) (\n        assume : x \u2208 FV (P\u2081.subst x v),\n        show \u00abfalse\u00bb, from P\u2081_ih this\n      ) (\n        assume : x \u2208 FV (P\u2082.subst x v),\n        show \u00abfalse\u00bb, from P\u2082_ih this\n      )\n    )},\n    case vc.pre t\u2081 t\u2082 { from (\n      have vc.subst x v (vc.pre t\u2081 t\u2082) = vc.pre (t\u2081.subst x v) (t\u2082.subst x v), by unfold vc.subst,\n      have x \u2208 FV (vc.pre (t\u2081.subst x v) (t\u2082.subst x v)), from this \u25b8 x_free,\n      or.elim (free_in_vc.pre.inv this) (\n        assume : x \u2208 FV (t\u2081.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      ) (\n        assume : x \u2208 FV (t\u2082.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      )\n    )},\n    case vc.pre\u2081 op t { from (\n      have vc.subst x v (vc.pre\u2081 op t) = vc.pre\u2081 op (t.subst x v), by unfold vc.subst,\n      have x \u2208 FV (vc.pre\u2081 op (t.subst x v)), from this \u25b8 x_free,\n      have x \u2208 FV (t.subst x v), from free_in_vc.pre\u2081.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_subst this\n    )},\n    case vc.pre\u2082 op t\u2081 t\u2082 { from (\n      have vc.subst x v (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op (t\u2081.subst x v) (t\u2082.subst x v),\n      by unfold vc.subst,\n      have x \u2208 FV (vc.pre\u2082 op (t\u2081.subst x v) (t\u2082.subst x v)), from this \u25b8 x_free,\n      or.elim (free_in_vc.pre\u2082.inv this) (\n        assume : x \u2208 FV (t\u2081.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      ) (\n        assume : x \u2208 FV (t\u2082.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      )\n    )},\n    case vc.post t\u2081 t\u2082 { from (\n      have vc.subst x v (vc.post t\u2081 t\u2082) = vc.post (t\u2081.subst x v) (t\u2082.subst x v), by unfold vc.subst,\n      have x \u2208 FV (vc.post (t\u2081.subst x v) (t\u2082.subst x v)), from this \u25b8 x_free,\n      or.elim (free_in_vc.post.inv this) (\n        assume : x \u2208 FV (t\u2081.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      ) (\n        assume : x \u2208 FV (t\u2082.subst x v),\n        show \u00abfalse\u00bb, from term.not_free_of_subst this\n      )\n    )},\n    case vc.univ y P\u2081 P\u2081_ih { from (\n      have vc.subst x v (vc.univ y P\u2081)\n         = vc.univ y (if x = y then P\u2081 else P\u2081.subst x v), by unfold vc.subst,\n      have x \u2208 FV (vc.univ y (if x = y then P\u2081 else P\u2081.subst x v)), from this \u25b8 x_free,\n      have y_neq_x: x \u2260 y, from (free_in_vc.univ.inv this).left,\n      have x \u2208 FV (vc.univ y (P\u2081.subst x v)), by { simp[y_neq_x] at this, from this },\n      have x \u2208 FV (P\u2081.subst x v), from (free_in_vc.univ.inv this).right,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )}\n  end\n\nlemma vc.not_free_of_substt {x: var} {t: term} {P: vc}: closed t \u2192 x \u2209 FV (vc.substt x t P) :=\n  assume t_closed: closed t,\n  assume x_free: x \u2208 FV (vc.substt x t P),\n  begin\n    induction P,\n    case vc.term t\u2082 { from (\n      have vc.substt x t (vc.term t\u2082) = (term.substt x t t\u2082), by unfold vc.substt,\n      have free_in_vc x (vc.term (term.substt x t t\u2082)), from this \u25b8 x_free,\n      have x \u2208 FV (term.substt x t t\u2082), from free_in_vc.term.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n    )},\n    case vc.not P\u2081 P\u2081_ih { from (\n      have vc.substt x t (vc.not P\u2081) = (P\u2081.substt x t).not, by unfold vc.substt,\n      have x \u2208 FV (P\u2081.substt x t).not, from this \u25b8 x_free,\n      have x \u2208 FV (P\u2081.substt x t), from free_in_vc.not.inv this,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )},\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have vc.substt x t (vc.and P\u2081 P\u2082) = (P\u2081.substt x t \u22c0 P\u2082.substt x t), by unfold vc.substt,\n      have x \u2208 FV (P\u2081.substt x t \u22c0 P\u2082.substt x t), from this \u25b8 x_free,\n      or.elim (free_in_vc.and.inv this) (\n        assume : x \u2208 FV (P\u2081.substt x t),\n        show \u00abfalse\u00bb, from P\u2081_ih this\n      ) (\n        assume : x \u2208 FV (P\u2082.substt x t),\n        show \u00abfalse\u00bb, from P\u2082_ih this\n      )\n    )},\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih { from (\n      have vc.substt x t (vc.or P\u2081 P\u2082) = (P\u2081.substt x t \u22c1 P\u2082.substt x t), by unfold vc.substt,\n      have x \u2208 FV (P\u2081.substt x t \u22c1 P\u2082.substt x t), from this \u25b8 x_free,\n      or.elim (free_in_vc.or.inv this) (\n        assume : x \u2208 FV (P\u2081.substt x t),\n        show \u00abfalse\u00bb, from P\u2081_ih this\n      ) (\n        assume : x \u2208 FV (P\u2082.substt x t),\n        show \u00abfalse\u00bb, from P\u2082_ih this\n      )\n    )},\n    case vc.pre t\u2081 t\u2082 { from (\n      have vc.substt x t (vc.pre t\u2081 t\u2082) = vc.pre (term.substt x t t\u2081) (term.substt x t t\u2082), by unfold vc.substt,\n      have x \u2208 FV (vc.pre (term.substt x t t\u2081) (term.substt x t t\u2082)), from this \u25b8 x_free,\n      or.elim (free_in_vc.pre.inv this) (\n        assume : x \u2208 FV (term.substt x t t\u2081),\n        show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n      ) (\n        assume : x \u2208 FV (term.substt x t t\u2082),\n        show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n      )\n    )},\n    case vc.pre\u2081 op t\u2081 { from (\n      have vc.substt x t (vc.pre\u2081 op t\u2081) = vc.pre\u2081 op (term.substt x t t\u2081), by unfold vc.substt,\n      have x \u2208 FV (vc.pre\u2081 op (term.substt x t t\u2081)), from this \u25b8 x_free,\n      have x \u2208 FV (term.substt x t t\u2081), from free_in_vc.pre\u2081.inv this,\n      show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n    )},\n    case vc.pre\u2082 op t\u2081 t\u2082 { from (\n      have vc.substt x t (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op (term.substt x t t\u2081) (term.substt x t t\u2082),\n      by unfold vc.substt,\n      have x \u2208 FV (vc.pre\u2082 op (term.substt x t t\u2081) (term.substt x t t\u2082)), from this \u25b8 x_free,\n      or.elim (free_in_vc.pre\u2082.inv this) (\n        assume : x \u2208 FV (term.substt x t t\u2081),\n        show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n      ) (\n        assume : x \u2208 FV (term.substt x t t\u2082),\n        show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n      )\n    )},\n    case vc.post t\u2081 t\u2082 { from (\n      have vc.substt x t (vc.post t\u2081 t\u2082) = vc.post (term.substt x t t\u2081) (term.substt x t t\u2082),\n      by unfold vc.substt,\n      have x \u2208 FV (vc.post (term.substt x t t\u2081) (term.substt x t t\u2082)), from this \u25b8 x_free,\n      or.elim (free_in_vc.post.inv this) (\n        assume : x \u2208 FV (term.substt x t t\u2081),\n        show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n      ) (\n        assume : x \u2208 FV (term.substt x t t\u2082),\n        show \u00abfalse\u00bb, from term.not_free_of_substt t_closed this\n      )\n    )},\n    case vc.univ y P\u2081 P\u2081_ih { from (\n      have vc.substt x t (vc.univ y P\u2081)\n         = vc.univ y (if x = y then P\u2081 else P\u2081.substt x t), by unfold vc.substt,\n      have x \u2208 FV (vc.univ y (if x = y then P\u2081 else P\u2081.substt x t)), from this \u25b8 x_free,\n      have y_neq_x: x \u2260 y, from (free_in_vc.univ.inv this).left,\n      have x \u2208 FV (vc.univ y (P\u2081.substt x t)), by { simp[y_neq_x] at this, from this },\n      have x \u2208 FV (P\u2081.substt x t), from (free_in_vc.univ.inv this).right,\n      show \u00abfalse\u00bb, from P\u2081_ih this\n    )}\n  end\n\nlemma vc.not_free_of_subst_env {x: var} {\u03c3: env} {P: vc}: x \u2208 \u03c3 \u2192 x \u2209 FV (vc.subst_env \u03c3 P) :=\n  assume x_in_\u03c3: x \u2208 \u03c3,\n  assume x_free: x \u2208 FV (vc.subst_env \u03c3 P),\n  begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show \u00abfalse\u00bb, by cases x_in_\u03c3,\n\n    -- \u03c3'[x\u21a6v]\n    show \u00abfalse\u00bb, from (\n      have vc.subst_env (\u03c3'[y\u21a6v]) P = vc.subst y v (vc.subst_env \u03c3' P), by unfold vc.subst_env,\n      have x \u2208 FV (vc.subst y v (vc.subst_env \u03c3' P)), from this \u25b8 x_free,\n      have x_neq_y: x \u2260 y, from (free_in_vc.subst this).left,\n      have h: x \u2208 FV (vc.subst_env \u03c3' P), from (free_in_vc.subst this).right,\n      have x = y \u2228 x \u2208 \u03c3', from env.contains.inv x_in_\u03c3,\n      or.elim this (\n        assume : x = y,\n        show \u00abfalse\u00bb, from x_neq_y this\n      ) (\n        assume : x \u2208 \u03c3',\n        have x \u2209 FV (vc.subst_env \u03c3' P), from ih this,\n        show \u00abfalse\u00bb, from this h\n      )\n    )\n  end\n\nlemma vc.closed_of_closed_subst {\u03c3: env} {P: vc}: closed_subst \u03c3 P \u2192 closed (vc.subst_env \u03c3 P) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  show closed (vc.subst_env \u03c3 P), from (\n    assume x: var,\n    assume h1: x \u2208 FV (vc.subst_env \u03c3 P),\n    have x \u2208 FV P, from free_in_vc.subst_env h1,\n    have x \u2208 \u03c3.dom, from P_closed_subst this,\n    have x \u2208 \u03c3, from this,\n    have h2: x \u2209 FV (vc.subst_env \u03c3 P), from vc.not_free_of_subst_env this,\n    show \u00abfalse\u00bb, from h2 h1\n  )\n\nlemma term.free_of_diff_subst {x y: var} {v: value} {t: term}: x \u2208 FV t \u2192 x \u2260 y \u2192 x \u2208 FV (term.subst y v t) :=\n  assume x_free: x \u2208 FV t,\n  assume x_neq_y: x \u2260 y,\n  show x \u2208 FV (term.subst y v t), from begin\n    induction t with v' z unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n\n    show x \u2208 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 \u2208 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 \u2208 FV (term.subst y v \u2191z),\n      rw[this],\n      from x_free\n    end,\n\n    show x \u2208 FV (term.subst y v (term.unop unop t\u2081)), by begin -- term.unop\n      unfold term.subst,\n      apply free_in_term.unop,\n      have : x \u2208 FV t\u2081, from free_in_term.unop.inv x_free,\n      from t\u2081_ih this\n    end,\n\n    show x \u2208 FV (term.subst y v (term.binop binop t\u2082 t\u2083)), by begin -- term.binop\n      unfold term.subst,\n      have : x \u2208 FV t\u2082 \u2228 x \u2208 FV t\u2083, from free_in_term.binop.inv x_free,\n      cases this with h,\n      apply free_in_term.binop\u2081,\n      from t\u2082_ih h,\n      apply free_in_term.binop\u2082,\n      from t\u2083_ih a\n    end,\n\n    show x \u2208 FV (term.subst y v (term.app t\u2084 t\u2085)), by begin -- term.binop\n      unfold term.subst,\n      have : x \u2208 FV t\u2084 \u2228 x \u2208 FV t\u2085, from free_in_term.app.inv x_free,\n      cases this with h,\n      apply free_in_term.app\u2081,\n      from t\u2084_ih h,\n      apply free_in_term.app\u2082,\n      from t\u2085_ih a\n    end,\n  end\n\nlemma vc.free_of_diff_subst {x y: var} {v: value} {P: vc}: x \u2208 FV P \u2192 x \u2260 y \u2192 x \u2208 FV (vc.subst y v P) :=\n  assume x_free: x \u2208 FV P,\n  assume x_neq_y: x \u2260 y,\n  show x \u2208 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\u2081 P\u2081_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\u2081_ih h2\n    },\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      unfold vc.subst,\n      have : x \u2208 FV P\u2081 \u2228 x \u2208 FV P\u2082, from free_in_vc.and.inv x_free,\n      cases this with h,\n      apply free_in_vc.and\u2081,\n      from P\u2081_ih h,\n      apply free_in_vc.and\u2082,\n      from P\u2082_ih a\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      unfold vc.subst,\n      have : x \u2208 FV P\u2081 \u2228 x \u2208 FV P\u2082, from free_in_vc.or.inv x_free,\n      cases this with h,\n      apply free_in_vc.or\u2081,\n      from P\u2081_ih h,\n      apply free_in_vc.or\u2082,\n      from P\u2082_ih a\n    },\n    case vc.pre t\u2081 t\u2082 {\n      unfold vc.subst,\n      have : x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.pre.inv x_free,\n      cases this with h,\n      apply free_in_vc.pre\u2081,\n      from term.free_of_diff_subst h x_neq_y,\n      apply free_in_vc.pre\u2082,\n      from term.free_of_diff_subst a x_neq_y\n    },\n    case vc.pre\u2081 op t {\n      unfold vc.subst,\n      apply free_in_vc.preop,\n      have h2, from free_in_vc.pre\u2081.inv x_free,\n      from term.free_of_diff_subst h2 x_neq_y\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      unfold vc.subst,\n      have : x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.pre\u2082.inv x_free,\n      cases this with h,\n      apply free_in_vc.preop\u2081,\n      from term.free_of_diff_subst h x_neq_y,\n      apply free_in_vc.preop\u2082,\n      from term.free_of_diff_subst a x_neq_y\n    },\n    case vc.post t\u2081 t\u2082 {\n      unfold vc.subst,\n      have : x \u2208 FV t\u2081 \u2228 x \u2208 FV t\u2082, from free_in_vc.post.inv x_free,\n      cases this with h,\n      apply free_in_vc.post\u2081,\n      from term.free_of_diff_subst h x_neq_y,\n      apply free_in_vc.post\u2082,\n      from term.free_of_diff_subst a x_neq_y\n    },\n    case vc.univ z P\u2081 P\u2081_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\u2081_ih h2.right\n    }\n  end\n\nlemma term.free_of_subst_env {x: var} {\u03c3: env} {t: term}: x \u2208 FV t \u2192 x \u2209 \u03c3 \u2192 x \u2208 FV (term.subst_env \u03c3 t) :=\n  assume x_free: x \u2208 FV t,\n  assume x_not_in_\u03c3: x \u2209 \u03c3,\n  show x \u2208 FV (term.subst_env \u03c3 t), begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show x \u2208 FV (term.subst_env env.empty t), begin\n      unfold term.subst_env,\n      from x_free\n    end,\n\n    -- \u03c3'[x\u21a6v]\n    show x \u2208 FV (term.subst_env (\u03c3'[y\u21a6v]) t), begin\n      unfold term.subst_env,\n      by_cases (x = y),\n      begin -- x = y\n        rw[h] at x_not_in_\u03c3,\n        have : y \u2208 (\u03c3'[y\u21a6v]), from env.contains.same,\n        contradiction\n      end,\n      begin -- x \u2260 y\n        by_cases (x \u2208 \u03c3') with h2,\n        begin -- x \u2208 \u03c3'\n          have : x \u2208 (\u03c3'[y\u21a6v]), from env.contains.rest h2,\n          contradiction\n        end,\n        begin -- x \u2209 \u03c3'\n          have : x \u2208 FV (term.subst_env \u03c3' 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} {\u03c3: env} {P: vc}: x \u2208 FV P \u2192 x \u2209 \u03c3 \u2192 x \u2208 FV (vc.subst_env \u03c3 P) :=\n  assume x_free: x \u2208 FV P,\n  assume x_not_in_\u03c3: x \u2209 \u03c3,\n  show x \u2208 FV (vc.subst_env \u03c3 P), begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show x \u2208 FV (vc.subst_env env.empty P), begin\n      unfold vc.subst_env,\n      from x_free\n    end,\n\n    -- \u03c3'[x\u21a6v]\n    show x \u2208 FV (vc.subst_env (\u03c3'[y\u21a6v]) P), begin\n      unfold vc.subst_env,\n      by_cases (x = y),\n      begin -- x = y\n        rw[h] at x_not_in_\u03c3,\n        have : y \u2208 (\u03c3'[y\u21a6v]), from env.contains.same,\n        contradiction\n      end,\n      begin -- x \u2260 y\n        by_cases (x \u2208 \u03c3') with h2,\n        begin -- x \u2208 \u03c3'\n          have : x \u2208 (\u03c3'[y\u21a6v]), from env.contains.rest h2,\n          contradiction\n        end,\n        begin -- x \u2209 \u03c3'\n          have : x \u2208 FV (vc.subst_env \u03c3' 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 \u2208 FV (term.subst y v t) \u2192 x \u2208 FV t :=\n  begin\n    assume h1,\n    induction t with v' z unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n\n    show x \u2208 FV (term.value v'), by begin\n      unfold term.subst at h1,\n      cases h1\n    end,\n\n    show x \u2208 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 \u2208 FV (term.unop unop t\u2081), 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\u2081_ih h2\n    end,\n\n    show x \u2208 FV (term.binop binop t\u2082 t\u2083), 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\u2081,\n      from t\u2082_ih a,\n      apply free_in_term.binop\u2082,\n      from t\u2083_ih a\n    end,\n\n    show x \u2208 FV (term.app t\u2084 t\u2085), 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\u2081,\n      from t\u2084_ih a,\n      apply free_in_term.app\u2082,\n      from t\u2085_ih a\n    end\n  end\n\nlemma term.closed_subst_of_closed {\u03c3: env} {t: term}: closed (term.subst_env \u03c3 t) \u2192 closed_subst \u03c3 t :=\n  assume t_closed_subst: closed (term.subst_env \u03c3 t),\n  show closed_subst \u03c3 t, from (\n    assume x: var,\n    assume h1: x \u2208 FV t,\n    have \u00ac x \u2209 \u03c3, from mt (term.free_of_subst_env h1) (t_closed_subst x),\n    have x \u2208 \u03c3, from of_not_not this,\n    show x \u2208 \u03c3.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\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_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 \u2191v (term.unop unop t\u2081) = term.subst x v (term.unop unop t\u2081)), 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\u2082 t\u2083) = term.subst x v (term.binop binop t\u2082 t\u2083)), by begin\n      unfold term.substt,\n      unfold term.subst,\n      congr\n    end,\n\n    show (term.substt x \u2191v (term.app t\u2084 t\u2085) = term.subst x v (term.app t\u2084 t\u2085)), 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\u2081 ih {\n      unfold vc.substt,\n      unfold vc.subst,\n      congr,\n      from ih\n    },\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      unfold vc.substt,\n      unfold vc.subst,\n      congr,\n      from P\u2081_ih,\n      from P\u2082_ih\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      unfold vc.substt,\n      unfold vc.subst,\n      congr,\n      from P\u2081_ih,\n      from P\u2082_ih\n    },\n    case vc.pre t\u2081 t\u2082 {\n      unfold vc.substt,\n      unfold vc.subst,\n      congr\n    },\n    case vc.pre\u2081 op t {\n      unfold vc.substt,\n      unfold vc.subst,\n      congr\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      unfold vc.substt,\n      unfold vc.subst,\n      congr\n    },\n    case vc.post t\u2081 t\u2082 {\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 \u2208 FV (prop.subst y v P) \u2192 x \u2208 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\u2081 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\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih a,\n      apply free_in_prop.and\u2082,\n      from P\u2082_ih a\n    },\n    case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih a,\n      apply free_in_prop.or\u2082,\n      from P\u2082_ih a\n    },\n    case prop.pre t\u2081 t\u2082 {\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\u2081,\n      from term.free_of_free_in_subst a,\n      apply free_in_prop.pre\u2082,\n      from term.free_of_free_in_subst  a\n    },\n    case prop.pre\u2081 op t {\n      unfold prop.subst at h1,\n      have h2, from free_in_prop.pre\u2081.inv h1,\n      apply free_in_prop.preop,\n      from term.free_of_free_in_subst h2\n    },\n    case prop.pre\u2082 op t\u2081 t\u2082 {\n      unfold prop.subst at h1,\n      have h2, from free_in_prop.pre\u2082.inv h1,\n      cases h2,\n      apply free_in_prop.preop\u2081,\n      from term.free_of_free_in_subst a,\n      apply free_in_prop.preop\u2082,\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\u2081 t\u2082 {\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\u2081,\n      from term.free_of_free_in_subst a,\n      apply free_in_prop.post\u2082,\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} {\u03c3: env} {P: prop}: x \u2208 FV (prop.subst_env \u03c3 P) \u2192 x \u2208 FV P :=\n  assume x_free: x \u2208 FV (prop.subst_env \u03c3 P),\n  show x \u2208 FV P, begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show x \u2208 FV P, begin\n      unfold prop.subst_env at x_free,\n      from x_free\n    end,\n\n    -- \u03c3'[x\u21a6v]\n    show x \u2208 FV P, begin\n      unfold prop.subst_env at x_free,\n      have h1: x \u2208 FV (prop.subst_env \u03c3' 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 \u2208 FV (vc.subst y v P) \u2192 x \u2208 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\u2081 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\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih a,\n      apply free_in_vc.and\u2082,\n      from P\u2082_ih a\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081,\n      from P\u2081_ih a,\n      apply free_in_vc.or\u2082,\n      from P\u2082_ih a\n    },\n    case vc.pre t\u2081 t\u2082 {\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\u2081,\n      from term.free_of_free_in_subst a,\n      apply free_in_vc.pre\u2082,\n      from term.free_of_free_in_subst  a\n    },\n    case vc.pre\u2081 op t {\n      unfold vc.subst at h1,\n      have h2, from free_in_vc.pre\u2081.inv h1,\n      apply free_in_vc.preop,\n      from term.free_of_free_in_subst h2\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      unfold vc.subst at h1,\n      have h2, from free_in_vc.pre\u2082.inv h1,\n      cases h2,\n      apply free_in_vc.preop\u2081,\n      from term.free_of_free_in_subst a,\n      apply free_in_vc.preop\u2082,\n      from term.free_of_free_in_subst  a\n    },\n    case vc.post t\u2081 t\u2082 {\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\u2081,\n      from term.free_of_free_in_subst a,\n      apply free_in_vc.post\u2082,\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} {\u03c3: env} {P: vc}: x \u2208 FV (vc.subst_env \u03c3 P) \u2192 x \u2208 FV P :=\n  assume x_free: x \u2208 FV (vc.subst_env \u03c3 P),\n  show x \u2208 FV P, begin\n    induction \u03c3 with \u03c3' y v ih,\n\n    -- env.empty\n    show x \u2208 FV P, begin\n      unfold vc.subst_env at x_free,\n      from x_free\n    end,\n\n    -- \u03c3'[x\u21a6v]\n    show x \u2208 FV P, begin\n      unfold vc.subst_env at x_free,\n      have h1: x \u2208 FV (vc.subst_env \u03c3' 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 {\u03c3: env} {P: vc}: closed (vc.subst_env \u03c3 P) \u2192 closed_subst \u03c3 P :=\n  assume P_closed_subst: closed (vc.subst_env \u03c3 P),\n  show closed_subst \u03c3 P, from (\n    assume x: var,\n    assume h1: x \u2208 FV P,\n    have \u00ac x \u2209 \u03c3, from mt (vc.free_of_subst_env h1) (P_closed_subst x),\n    have x \u2208 \u03c3, from of_not_not this,\n    show x \u2208 \u03c3.dom, from this\n  )\n\nlemma prop.closed_any_subst_of_closed {\u03c3: env} {P: prop}: closed P \u2192 closed_subst \u03c3 P :=\n  assume P_closed: closed P,\n  show closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    show x \u2208 \u03c3.dom, from absurd this (P_closed x)\n  )\n\nlemma term.subst_env.unop {\u03c3: env} {op: unop} {t: term}:\n      term.subst_env \u03c3 (term.unop op t) = term.unop op (term.subst_env \u03c3 t) :=\nbegin\n  induction \u03c3 with \u03c3' 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 (\u03c3'[x\u21a6v]) (term.unop op t) = (term.unop op (term.subst_env (\u03c3'[x\u21a6v]) t))),\n  by calc\n        term.subst_env (\u03c3'[x\u21a6v]) (term.unop op t)\n      = term.subst x v (term.subst_env \u03c3' (term.unop op t)) : by unfold term.subst_env\n  ... = term.subst x v (term.unop op (term.subst_env \u03c3' t)) : by rw[ih]\n  ... = term.unop op (term.subst x v (term.subst_env \u03c3' t)) : by unfold term.subst\n  ... = term.unop op (term.subst_env (\u03c3'[x\u21a6v]) t) : by unfold term.subst_env\nend\n\nlemma term.subst_env.binop {\u03c3: env} {op: binop} {t\u2081 t\u2082: term}:\n      term.subst_env \u03c3 (term.binop op t\u2081 t\u2082) = term.binop op (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (term.subst_env env.empty (term.binop op t\u2081 t\u2082)\n      = term.binop op (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        term.subst_env env.empty (term.binop op t\u2081 t\u2082)\n      = (term.binop op t\u2081 t\u2082) : by unfold term.subst_env\n  ... = (term.binop op (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (term.binop op (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (term.subst_env (\u03c3'[x\u21a6v]) (term.binop op t\u2081 t\u2082)\n      = (term.binop op (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082))),\n  by calc\n        term.subst_env (\u03c3'[x\u21a6v]) (term.binop op t\u2081 t\u2082)\n      = term.subst x v (term.subst_env \u03c3' (term.binop op t\u2081 t\u2082)) : by unfold term.subst_env\n  ... = term.subst x v (term.binop op (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = term.binop op (term.subst x v (term.subst_env \u03c3' t\u2081))\n                      (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst\n  ... = term.binop op (term.subst_env (\u03c3'[x\u21a6v]) t\u2081)\n                      (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = term.binop op (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma term.subst_env.app {\u03c3: env} {t\u2081 t\u2082: term}:\n      term.subst_env \u03c3 (term.app t\u2081 t\u2082) = term.app (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (term.subst_env env.empty (term.app t\u2081 t\u2082)\n      = term.app (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        term.subst_env env.empty (term.app t\u2081 t\u2082)\n      = (term.app t\u2081 t\u2082) : by unfold term.subst_env\n  ... = (term.app (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (term.app (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (term.subst_env (\u03c3'[x\u21a6v]) (term.app t\u2081 t\u2082)\n      = (term.app (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082))),\n  by calc\n        term.subst_env (\u03c3'[x\u21a6v]) (term.app t\u2081 t\u2082)\n      = term.subst x v (term.subst_env \u03c3' (term.app t\u2081 t\u2082)) : by unfold term.subst_env\n  ... = term.subst x v (term.app (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = term.app (term.subst x v (term.subst_env \u03c3' t\u2081))\n                      (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst\n  ... = term.app (term.subst_env (\u03c3'[x\u21a6v]) t\u2081)\n                      (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = term.app (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma prop.subst_env.term {\u03c3: env} {t: term}:\n  prop.subst_env \u03c3 t = prop.term (term.subst_env \u03c3 t) :=\nbegin\n  induction \u03c3 with \u03c3' 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[\u2190h2]\n  end,\n\n  show (prop.subst_env (\u03c3'[x\u21a6v]) t = prop.term (term.subst_env (\u03c3'[x\u21a6v]) t)),\n  by calc\n        prop.subst_env (\u03c3'[x\u21a6v]) t = prop.subst x v (prop.subst_env \u03c3' t) : by unfold prop.subst_env\n                               ... = prop.subst x v (prop.term (term.subst_env \u03c3' t)) : by rw[ih]\n                               ... = term.subst x v (term.subst_env \u03c3' t) : by unfold prop.subst\n                               ... = term.subst_env (\u03c3'[x\u21a6v]) t : by unfold term.subst_env\nend\n\nlemma prop.subst_env.not {\u03c3: env} {P: prop}:\n      prop.subst_env \u03c3 P.not = (prop.subst_env \u03c3 P).not :=\nbegin\n  induction \u03c3 with \u03c3' 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 (\u03c3'[x\u21a6v]) P.not = (prop.subst_env (\u03c3'[x\u21a6v]) P).not),\n  by calc\n        prop.subst_env (\u03c3'[x\u21a6v]) P.not = prop.subst x v (prop.subst_env \u03c3' P.not) : by unfold prop.subst_env\n                                   ... = prop.subst x v (prop.subst_env \u03c3' P).not : by rw[ih]\n                                   ... = (prop.subst x v (prop.subst_env \u03c3' P)).not : by unfold prop.subst\n                                   ... = (prop.subst_env (\u03c3'[x\u21a6v]) P).not : by unfold prop.subst_env\nend\n\nlemma prop.subst_env.and {\u03c3: env} {P Q: prop}:\n      prop.subst_env \u03c3 (P \u22c0 Q) = (prop.subst_env \u03c3 P \u22c0 prop.subst_env \u03c3 Q) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (prop.subst_env env.empty (P \u22c0 Q) = (prop.subst_env env.empty P \u22c0 prop.subst_env env.empty Q)),\n  by calc\n        prop.subst_env env.empty (P \u22c0 Q) = (P \u22c0 Q) : by unfold prop.subst_env\n                                      ... = (prop.subst_env env.empty P \u22c0 Q) : by unfold prop.subst_env\n                                      ... = (prop.subst_env env.empty P \u22c0 prop.subst_env env.empty Q)\n                                                     : by unfold prop.subst_env,\n\n  show (prop.subst_env (\u03c3'[x\u21a6v]) (P \u22c0 Q) = (prop.subst_env (\u03c3'[x\u21a6v]) P \u22c0 prop.subst_env (\u03c3'[x\u21a6v]) Q)),\n  by calc\n        prop.subst_env (\u03c3'[x\u21a6v]) (P \u22c0 Q) = prop.subst x v (prop.subst_env \u03c3' (P \u22c0 Q)) : by unfold prop.subst_env\n                                      ... = prop.subst x v (prop.subst_env \u03c3' P \u22c0 prop.subst_env \u03c3' Q) : by rw[ih]\n                                      ... = (prop.subst x v (prop.subst_env \u03c3' P) \u22c0\n                                             prop.subst x v (prop.subst_env \u03c3' Q)) : by refl\n                                      ... = (prop.subst_env (\u03c3'[x\u21a6v]) P \u22c0\n                                             prop.subst x v (prop.subst_env \u03c3' Q)) : by unfold prop.subst_env\n                                      ... = (prop.subst_env (\u03c3'[x\u21a6v]) P \u22c0 prop.subst_env (\u03c3'[x\u21a6v]) Q)\n                                                                               : by unfold prop.subst_env\nend\n\nlemma prop.subst_env.or {\u03c3: env} {P Q: prop}:\n      prop.subst_env \u03c3 (P \u22c1 Q) = (prop.subst_env \u03c3 P \u22c1 prop.subst_env \u03c3 Q) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (prop.subst_env env.empty (P \u22c1 Q) = (prop.subst_env env.empty P \u22c1 prop.subst_env env.empty Q)),\n  by calc\n        prop.subst_env env.empty (P \u22c1 Q) = (P \u22c1 Q) : by unfold prop.subst_env\n                                      ... = (prop.subst_env env.empty P \u22c1 Q) : by by unfold prop.subst_env\n                                      ... = (prop.subst_env env.empty P \u22c1 prop.subst_env env.empty Q)\n                                                     : by unfold prop.subst_env,\n\n  show (prop.subst_env (\u03c3'[x\u21a6v]) (P \u22c1 Q) = (prop.subst_env (\u03c3'[x\u21a6v]) P \u22c1 prop.subst_env (\u03c3'[x\u21a6v]) Q)),\n  by calc\n        prop.subst_env (\u03c3'[x\u21a6v]) (P \u22c1 Q) = prop.subst x v (prop.subst_env \u03c3' (P \u22c1 Q)) : by unfold prop.subst_env\n                                      ... = prop.subst x v (prop.subst_env \u03c3' P \u22c1 prop.subst_env \u03c3' Q) : by rw[ih]\n                                      ... = (prop.subst x v (prop.subst_env \u03c3' P) \u22c1\n                                             prop.subst x v (prop.subst_env \u03c3' Q)) : by refl\n                                      ... = (prop.subst_env (\u03c3'[x\u21a6v]) P \u22c1\n                                             prop.subst x v (prop.subst_env \u03c3' Q)) : by unfold prop.subst_env\n                                      ... = (prop.subst_env (\u03c3'[x\u21a6v]) P \u22c1 prop.subst_env (\u03c3'[x\u21a6v]) Q)\n                                               : by unfold prop.subst_env\nend\n\nlemma prop.subst_env.implies {\u03c3: env} {P Q: prop}:\n      prop.subst_env \u03c3 (prop.implies P Q) = prop.implies (prop.subst_env \u03c3 P) (prop.subst_env \u03c3 Q) :=\n  have h1: prop.subst_env \u03c3 (prop.implies P Q) = prop.subst_env \u03c3 (P.not \u22c1 Q), by refl,\n  have prop.subst_env \u03c3 (P.not \u22c1 Q) = (prop.subst_env \u03c3 P.not \u22c1 prop.subst_env \u03c3 Q), from prop.subst_env.or,\n  have h2: prop.subst_env \u03c3 (prop.implies P Q) = (prop.subst_env \u03c3 P.not \u22c1 prop.subst_env \u03c3 Q), from this \u25b8 h1,\n  have prop.subst_env \u03c3 P.not = prop.not (prop.subst_env \u03c3 P), from prop.subst_env.not,\n  have prop.subst_env \u03c3 (prop.implies P Q) = (prop.not (prop.subst_env \u03c3 P) \u22c1 prop.subst_env \u03c3 Q), from this \u25b8 h2,\n  show prop.subst_env \u03c3 (prop.implies P Q) = prop.implies (prop.subst_env \u03c3 P) (prop.subst_env \u03c3 Q), from this\n\nlemma prop.subst_env.pre {\u03c3: env} {t\u2081 t\u2082: term}:\n      prop.subst_env \u03c3 (prop.pre t\u2081 t\u2082) = prop.pre (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (prop.subst_env env.empty (prop.pre t\u2081 t\u2082)\n      = prop.pre (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        prop.subst_env env.empty (prop.pre t\u2081 t\u2082)\n      = (prop.pre t\u2081 t\u2082) : by unfold prop.subst_env\n  ... = (prop.pre (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (prop.pre (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (prop.subst_env (\u03c3'[x\u21a6v]) (prop.pre t\u2081 t\u2082)\n      = prop.pre (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082)),\n  by calc\n        prop.subst_env (\u03c3'[x\u21a6v]) (prop.pre t\u2081 t\u2082)\n      = prop.subst x v (prop.subst_env \u03c3' (prop.pre t\u2081 t\u2082)) : by unfold prop.subst_env\n  ... = prop.subst x v (prop.pre (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = prop.pre (term.subst x v (term.subst_env \u03c3' t\u2081)) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold prop.subst\n  ... = prop.pre (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = prop.pre (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma prop.subst_env.post {\u03c3: env} {t\u2081 t\u2082: term}:\n      prop.subst_env \u03c3 (prop.post t\u2081 t\u2082) = prop.post (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (prop.subst_env env.empty (prop.post t\u2081 t\u2082)\n      = prop.post (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        prop.subst_env env.empty (prop.post t\u2081 t\u2082)\n      = (prop.post t\u2081 t\u2082) : by unfold prop.subst_env\n  ... = (prop.post (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (prop.post (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (prop.subst_env (\u03c3'[x\u21a6v]) (prop.post t\u2081 t\u2082)\n      = prop.post (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082)),\n  by calc\n        prop.subst_env (\u03c3'[x\u21a6v]) (prop.post t\u2081 t\u2082)\n      = prop.subst x v (prop.subst_env \u03c3' (prop.post t\u2081 t\u2082)) : by unfold prop.subst_env\n  ... = prop.subst x v (prop.post (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = prop.post (term.subst x v (term.subst_env \u03c3' t\u2081)) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold prop.subst\n  ... = prop.post (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = prop.post (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma prop.subst_env.forallc_not_in {\u03c3: env} {x: var} {P: prop}:\n      (x \u2209 \u03c3) \u2192 (prop.subst_env \u03c3 (prop.forallc x P) = prop.forallc x (prop.subst_env \u03c3 P)) :=\nbegin\n  assume x_not_in_\u03c3,\n  induction \u03c3 with \u03c3' 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 (\u03c3'[y\u21a6v]) (prop.forallc x P)\n      = prop.forallc x (prop.subst_env (\u03c3'[y\u21a6v]) P)), from (\n    have \u00ac (x = y \u2228 x \u2208 \u03c3'), from env.contains.same.inv x_not_in_\u03c3,\n    have x_neq_y: x \u2260 y, from (not_or_distrib.mp this).left,\n    have x \u2209 \u03c3', from (not_or_distrib.mp this).right,\n    have h: prop.subst_env \u03c3' (prop.forallc x P) = prop.forallc x (prop.subst_env \u03c3' P),\n    from ih this,\n\n    calc\n        prop.subst_env (\u03c3'[y\u21a6v]) (prop.forallc x P)\n      = prop.subst y v (prop.subst_env \u03c3' (prop.forallc x P)) : by unfold prop.subst_env\n  ... = prop.subst y v (prop.forallc x (prop.subst_env \u03c3' P)) : by rw[h]\n  ... = prop.forallc x (if y = x then prop.subst_env \u03c3' P else (prop.subst_env \u03c3' P).subst y v)\n     : by unfold prop.subst\n  ... = prop.forallc x ((prop.subst_env \u03c3' P).subst y v) : by simp[x_neq_y.symm]\n  ... = prop.forallc x (prop.subst_env (\u03c3'[y\u21a6v]) P) : by unfold prop.subst_env\n  )\nend\n\nlemma prop.subst_env.forallc {\u03c3: env} {x: var} {P: prop}:\n      (prop.subst_env \u03c3 (prop.forallc x P) = prop.forallc x (prop.subst_env (\u03c3.without x) P)) :=\nbegin\n  induction \u03c3 with \u03c3' 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 (\u03c3'[y\u21a6v]) (prop.forallc x P) = prop.forallc x (prop.subst_env ((\u03c3'[y\u21a6v]).without x) P)),\n  by begin\n    unfold prop.subst_env,\n    by_cases (y = x) with h1,\n    rw[\u2190h1],\n    rw[\u2190h1] at ih,\n    unfold env.without,\n    simp,\n    have : y \u2209 FV (prop.subst_env \u03c3' (prop.forallc y P)), from (\n      assume : y \u2208 FV (prop.subst_env \u03c3' (prop.forallc y P)),\n      have y \u2208 FV (prop.forallc y P), from prop.free_of_free_subst_env this,\n      show \u00abfalse\u00bb, from free_in_prop.forallc.same.inv this\n    ),\n    have h2: (prop.subst y v (prop.subst_env \u03c3' (prop.forallc y P)) = prop.subst_env \u03c3' (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 \u03c3' x) P))\n          = prop.forallc x (prop.subst y v (prop.subst_env (env.without \u03c3' x) P))),\n    by { unfold prop.subst, simp[h1] },\n    rw[\u2190this],\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) \u22c1 vc.subst x v Q) : by unfold vc.subst\n                                 ... = ((vc.subst x v P).not \u22c1 vc.subst x v Q) : by unfold vc.subst\n\nlemma vc.subst_env.term {\u03c3: env} {t: term}:\n  vc.subst_env \u03c3 t = vc.term (term.subst_env \u03c3 t) :=\nbegin\n  induction \u03c3 with \u03c3' 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[\u2190h2]\n  end,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) t = vc.term (term.subst_env (\u03c3'[x\u21a6v]) t)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) t = vc.subst x v (vc.subst_env \u03c3' t) : by unfold vc.subst_env\n                             ... = vc.subst x v (vc.term (term.subst_env \u03c3' t)) : by rw[ih]\n                             ... = term.subst x v (term.subst_env \u03c3' t) : by unfold vc.subst\n                             ... = term.subst_env (\u03c3'[x\u21a6v]) t : by unfold term.subst_env\nend\n\nlemma vc.subst_env.not {\u03c3: env} {P: vc}:\n      vc.subst_env \u03c3 P.not = (vc.subst_env \u03c3 P).not :=\nbegin\n  induction \u03c3 with \u03c3' 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 (\u03c3'[x\u21a6v]) P.not = (vc.subst_env (\u03c3'[x\u21a6v]) P).not),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) P.not = vc.subst x v (vc.subst_env \u03c3' P.not) : by unfold vc.subst_env\n                                 ... = vc.subst x v (vc.subst_env \u03c3' P).not : by rw[ih]\n                                 ... = (vc.subst x v (vc.subst_env \u03c3' P)).not : by unfold vc.subst\n                                 ... = (vc.subst_env (\u03c3'[x\u21a6v]) P).not : by unfold vc.subst_env\nend\n\nlemma vc.subst_env.and {\u03c3: env} {P Q: vc}:\n      vc.subst_env \u03c3 (P \u22c0 Q) = (vc.subst_env \u03c3 P \u22c0 vc.subst_env \u03c3 Q) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (vc.subst_env env.empty (P \u22c0 Q) = (vc.subst_env env.empty P \u22c0 vc.subst_env env.empty Q)),\n  by calc\n        vc.subst_env env.empty (P \u22c0 Q) = (P \u22c0 Q) : by unfold vc.subst_env\n                                    ... = (vc.subst_env env.empty P \u22c0 Q) : by unfold vc.subst_env\n                                    ... = (vc.subst_env env.empty P \u22c0 vc.subst_env env.empty Q)\n                                                   : by unfold vc.subst_env,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) (P \u22c0 Q) = (vc.subst_env (\u03c3'[x\u21a6v]) P \u22c0 vc.subst_env (\u03c3'[x\u21a6v]) Q)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) (P \u22c0 Q) = vc.subst x v (vc.subst_env \u03c3' (P \u22c0 Q)) : by unfold vc.subst_env\n                                    ... = vc.subst x v (vc.subst_env \u03c3' P \u22c0 vc.subst_env \u03c3' Q) : by rw[ih]\n                                    ... = (vc.subst x v (vc.subst_env \u03c3' P) \u22c0\n                                           vc.subst x v (vc.subst_env \u03c3' Q)) : by refl\n                                    ... = (vc.subst_env (\u03c3'[x\u21a6v]) P \u22c0\n                                           vc.subst x v (vc.subst_env \u03c3' Q)) : by unfold vc.subst_env\n                                    ... = (vc.subst_env (\u03c3'[x\u21a6v]) P \u22c0 vc.subst_env (\u03c3'[x\u21a6v]) Q)\n                                                                             : by unfold vc.subst_env\nend\n\nlemma vc.subst_env.or {\u03c3: env} {P Q: vc}:\n      vc.subst_env \u03c3 (P \u22c1 Q) = (vc.subst_env \u03c3 P \u22c1 vc.subst_env \u03c3 Q) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (vc.subst_env env.empty (P \u22c1 Q) = (vc.subst_env env.empty P \u22c1 vc.subst_env env.empty Q)),\n  by calc\n        vc.subst_env env.empty (P \u22c1 Q) = (P \u22c1 Q) : by unfold vc.subst_env\n                                    ... = (vc.subst_env env.empty P \u22c1 Q) : by by unfold vc.subst_env\n                                    ... = (vc.subst_env env.empty P \u22c1 vc.subst_env env.empty Q)\n                                                   : by unfold vc.subst_env,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) (P \u22c1 Q) = (vc.subst_env (\u03c3'[x\u21a6v]) P \u22c1 vc.subst_env (\u03c3'[x\u21a6v]) Q)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) (P \u22c1 Q) = vc.subst x v (vc.subst_env \u03c3' (P \u22c1 Q)) : by unfold vc.subst_env\n                                    ... = vc.subst x v (vc.subst_env \u03c3' P \u22c1 vc.subst_env \u03c3' Q) : by rw[ih]\n                                    ... = (vc.subst x v (vc.subst_env \u03c3' P) \u22c1\n                                           vc.subst x v (vc.subst_env \u03c3' Q)) : by refl\n                                    ... = (vc.subst_env (\u03c3'[x\u21a6v]) P \u22c1\n                                           vc.subst x v (vc.subst_env \u03c3' Q)) : by unfold vc.subst_env\n                                    ... = (vc.subst_env (\u03c3'[x\u21a6v]) P \u22c1 vc.subst_env (\u03c3'[x\u21a6v]) Q)\n                                             : by unfold vc.subst_env\nend\n\nlemma vc.subst_env.implies {\u03c3: env} {P Q: vc}:\n      vc.subst_env \u03c3 (vc.implies P Q) = vc.implies (vc.subst_env \u03c3 P) (vc.subst_env \u03c3 Q) :=\n  have h1: vc.subst_env \u03c3 (vc.implies P Q) = vc.subst_env \u03c3 (vc.or P.not Q), from rfl,\n  have vc.subst_env \u03c3 (vc.or P.not Q) = vc.or (vc.subst_env \u03c3 P.not) (vc.subst_env \u03c3 Q), from vc.subst_env.or,\n  have h2: vc.subst_env \u03c3 (vc.implies P Q) = vc.or (vc.subst_env \u03c3 P.not) (vc.subst_env \u03c3 Q), from eq.trans h1 this,\n  have vc.subst_env \u03c3 (vc.not P) = vc.not (vc.subst_env \u03c3 P), from vc.subst_env.not,\n  show vc.subst_env \u03c3 (vc.implies P Q) = vc.or (vc.subst_env \u03c3 P).not (vc.subst_env \u03c3 Q), from this \u25b8 h2\n\nlemma vc.subst_env.pre\u2081 {\u03c3: env} {op: unop} {t: term}:\n      vc.subst_env \u03c3 (vc.pre\u2081 op t) = vc.pre\u2081 op (term.subst_env \u03c3 t) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (vc.subst_env env.empty (vc.pre\u2081 op t) = vc.pre\u2081 op (term.subst_env env.empty t)),\n  by calc\n        vc.subst_env env.empty (vc.pre\u2081 op t) = (vc.pre\u2081 op t) : by unfold vc.subst_env\n                                          ... = (vc.pre\u2081 op (term.subst_env env.empty t)) : by unfold term.subst_env,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) (vc.pre\u2081 op t) = vc.pre\u2081 op (term.subst_env (\u03c3'[x\u21a6v]) t)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) (vc.pre\u2081 op t) = vc.subst x v (vc.subst_env \u03c3' (vc.pre\u2081 op t)) : by unfold vc.subst_env\n                                          ... = vc.subst x v (vc.pre\u2081 op (term.subst_env \u03c3' t)) : by rw[ih]\n                                          ... = vc.pre\u2081 op (term.subst x v (term.subst_env \u03c3' t)) : by unfold vc.subst\n                                          ... = vc.pre\u2081 op (term.subst_env (\u03c3'[x\u21a6v]) t) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.pre\u2082 {\u03c3: env} {op: binop} {t\u2081 t\u2082: term}:\n      vc.subst_env \u03c3 (vc.pre\u2082 op t\u2081 t\u2082) = vc.pre\u2082 op (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (vc.subst_env env.empty (vc.pre\u2082 op t\u2081 t\u2082)\n      = vc.pre\u2082 op (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        vc.subst_env env.empty (vc.pre\u2082 op t\u2081 t\u2082)\n      = (vc.pre\u2082 op t\u2081 t\u2082) : by unfold vc.subst_env\n  ... = (vc.pre\u2082 op (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (vc.pre\u2082 op (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) (vc.pre\u2082 op t\u2081 t\u2082)\n      = vc.pre\u2082 op (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) (vc.pre\u2082 op t\u2081 t\u2082)\n      = vc.subst x v (vc.subst_env \u03c3' (vc.pre\u2082 op t\u2081 t\u2082)) : by unfold vc.subst_env\n  ... = vc.subst x v (vc.pre\u2082 op (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = vc.pre\u2082 op (term.subst x v (term.subst_env \u03c3' t\u2081)) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold vc.subst\n  ... = vc.pre\u2082 op (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = vc.pre\u2082 op (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.pre {\u03c3: env} {t\u2081 t\u2082: term}:\n      vc.subst_env \u03c3 (vc.pre t\u2081 t\u2082) = vc.pre (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (vc.subst_env env.empty (vc.pre t\u2081 t\u2082)\n      = vc.pre (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        vc.subst_env env.empty (vc.pre t\u2081 t\u2082)\n      = (vc.pre t\u2081 t\u2082) : by unfold vc.subst_env\n  ... = (vc.pre (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (vc.pre (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) (vc.pre t\u2081 t\u2082)\n      = vc.pre (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) (vc.pre t\u2081 t\u2082)\n      = vc.subst x v (vc.subst_env \u03c3' (vc.pre t\u2081 t\u2082)) : by unfold vc.subst_env\n  ... = vc.subst x v (vc.pre (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = vc.pre (term.subst x v (term.subst_env \u03c3' t\u2081)) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold vc.subst\n  ... = vc.pre (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = vc.pre (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.post {\u03c3: env} {t\u2081 t\u2082: term}:\n      vc.subst_env \u03c3 (vc.post t\u2081 t\u2082) = vc.post (term.subst_env \u03c3 t\u2081) (term.subst_env \u03c3 t\u2082) :=\nbegin\n  induction \u03c3 with \u03c3' x v ih,\n\n  show (vc.subst_env env.empty (vc.post t\u2081 t\u2082)\n      = vc.post (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)),\n  by calc\n        vc.subst_env env.empty (vc.post t\u2081 t\u2082)\n      = (vc.post t\u2081 t\u2082) : by unfold vc.subst_env\n  ... = (vc.post (term.subst_env env.empty t\u2081) t\u2082) : by unfold term.subst_env\n  ... = (vc.post (term.subst_env env.empty t\u2081) (term.subst_env env.empty t\u2082)) : by unfold term.subst_env,\n\n  show (vc.subst_env (\u03c3'[x\u21a6v]) (vc.post t\u2081 t\u2082)\n      = vc.post (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082)),\n  by calc\n        vc.subst_env (\u03c3'[x\u21a6v]) (vc.post t\u2081 t\u2082)\n      = vc.subst x v (vc.subst_env \u03c3' (vc.post t\u2081 t\u2082)) : by unfold vc.subst_env\n  ... = vc.subst x v (vc.post (term.subst_env \u03c3' t\u2081) (term.subst_env \u03c3' t\u2082)) : by rw[ih]\n  ... = vc.post (term.subst x v (term.subst_env \u03c3' t\u2081)) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold vc.subst\n  ... = vc.post (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst x v (term.subst_env \u03c3' t\u2082)) : by unfold term.subst_env\n  ... = vc.post (term.subst_env (\u03c3'[x\u21a6v]) t\u2081) (term.subst_env (\u03c3'[x\u21a6v]) t\u2082) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.univ_not_in {\u03c3: env} {x: var} {P: vc}:\n      (x \u2209 \u03c3) \u2192 (vc.subst_env \u03c3 (vc.univ x P) = vc.univ x (vc.subst_env \u03c3 P)) :=\nbegin\n  assume x_not_in_\u03c3,\n  induction \u03c3 with \u03c3' 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 (\u03c3'[y\u21a6v]) (vc.univ x P) = vc.univ x (vc.subst_env (\u03c3'[y\u21a6v]) P)), from (\n    have \u00ac (x = y \u2228 x \u2208 \u03c3'), from env.contains.same.inv x_not_in_\u03c3,\n    have x_neq_y: x \u2260 y, from (not_or_distrib.mp this).left,\n    have x \u2209 \u03c3', from (not_or_distrib.mp this).right,\n    have h: vc.subst_env \u03c3' (vc.univ x P) = vc.univ x (vc.subst_env \u03c3' P), from ih this,\n\n    calc\n        vc.subst_env (\u03c3'[y\u21a6v]) (vc.univ x P)\n           = vc.subst y v (vc.subst_env \u03c3' (vc.univ x P)) : by unfold vc.subst_env\n       ... = vc.subst y v (vc.univ x (vc.subst_env \u03c3' P)) : by rw[h]\n       ... = vc.univ x (if y = x then vc.subst_env \u03c3' P else (vc.subst_env \u03c3' P).subst y v) : by unfold vc.subst\n       ... = vc.univ x ((vc.subst_env \u03c3' P).subst y v) : by simp[x_neq_y.symm]\n       ... = vc.univ x (vc.subst_env (\u03c3'[y\u21a6v]) P) : by unfold vc.subst_env\n  )\nend\n\nlemma vc.subst_env.univ {\u03c3: env} {x: var} {P: vc}:\n      (vc.subst_env \u03c3 (vc.univ x P) = vc.univ x (vc.subst_env (\u03c3.without x) P)) :=\nbegin\n  induction \u03c3 with \u03c3' 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 (\u03c3'[y\u21a6v]) (vc.univ x P) = vc.univ x (vc.subst_env ((\u03c3'[y\u21a6v]).without x) P)), by begin\n    unfold vc.subst_env,\n    by_cases (y = x) with h1,\n    rw[\u2190h1],\n    rw[\u2190h1] at ih,\n    unfold env.without,\n    simp,\n    have : y \u2209 FV (vc.subst_env \u03c3' (vc.univ y P)), from (\n      assume : y \u2208 FV (vc.subst_env \u03c3' (vc.univ y P)),\n      have y \u2208 FV (vc.univ y P), from vc.free_of_free_subst_env this,\n      show \u00abfalse\u00bb, from free_in_vc.univ.same.inv this\n    ),\n    have h2: (vc.subst y v (vc.subst_env \u03c3' (vc.univ y P)) = vc.subst_env \u03c3' (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 \u03c3' x) P))\n         = vc.univ x (vc.subst y v (vc.subst_env (env.without \u03c3' x) P))),\n    by { unfold vc.subst, simp[h1] },\n    rw[\u2190this],\n    congr,\n    from ih  \n  end\nend\n\nlemma term.closed_subst.value {v: value} {\u03c3: env}: closed_subst \u03c3 (term.value v) :=\n  assume x: var,\n  assume : x \u2208 FV (term.value v),\n  show x \u2208 \u03c3.dom, from absurd this free_in_term.value.inv\n\nlemma prop.closed_subst.term {t: term} {\u03c3: env}: closed_subst \u03c3 t \u2192 closed_subst \u03c3 (prop.term t) :=\n  assume t_closed: closed_subst \u03c3 t,\n  show closed_subst \u03c3 (prop.term t), from (\n    assume x: var,\n    assume : x \u2208 FV (prop.term t),\n    have free_in_term x t, from free_in_prop.term.inv this,\n    show x \u2208 \u03c3.dom, from t_closed this\n  )\n\nlemma prop.closed_subst.and {P Q: prop} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 Q \u2192 closed_subst \u03c3 (P \u22c0 Q) :=\n  assume P_closed: closed_subst \u03c3 P,\n  assume Q_closed: closed_subst \u03c3 Q,\n  show closed_subst \u03c3 (P \u22c0 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c0 Q),\n    or.elim (free_in_prop.and.inv this) (\n      assume : x \u2208 FV P,\n      show x \u2208 \u03c3.dom, from P_closed this\n    ) (\n      assume : x \u2208 FV Q,\n      show x \u2208 \u03c3.dom, from Q_closed this\n    )\n  )\n\nlemma prop.closed_subst.or {P Q: prop} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 Q \u2192 closed_subst \u03c3 (P \u22c1 Q) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  assume Q_closed_subst: closed_subst \u03c3 Q,\n  show closed_subst \u03c3 (P \u22c1 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c1 Q),\n    or.elim (free_in_prop.or.inv this) (\n      assume : x \u2208 FV P,\n      show x \u2208 \u03c3.dom, from P_closed_subst this\n    ) (\n      assume : x \u2208 FV Q,\n      show x \u2208 \u03c3.dom, from Q_closed_subst this\n    )\n  )\n\nlemma prop.closed_subst.not {P: prop} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 P.not :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  show closed_subst \u03c3 P.not, from (\n    assume x: var,\n    assume : x \u2208 FV P.not,\n    have x \u2208 FV P, from free_in_prop.not.inv this,\n    show x \u2208 \u03c3.dom, from P_closed_subst this\n  )\n\nlemma prop.closed_subst.implies {P Q: prop} {\u03c3: env}:\n      closed_subst \u03c3 P \u2192 closed_subst \u03c3 Q \u2192 closed_subst \u03c3 (prop.implies P Q) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  have P_not_closed_subst: closed_subst \u03c3 P.not, from prop.closed_subst.not P_closed_subst,\n  assume Q_closed_subst: closed_subst \u03c3 Q,\n  show closed_subst \u03c3 (P.not \u22c1 Q), from prop.closed_subst.or P_not_closed_subst Q_closed_subst\n\nlemma prop.closed_subst.and.inv {P Q: prop} {\u03c3: env}: closed_subst \u03c3 (P \u22c0 Q) \u2192 (closed_subst \u03c3 P \u2227 closed_subst \u03c3 Q) :=\n  assume P_and_Q_closed_subst: closed_subst \u03c3 (P \u22c0 Q),\n  have P_closed_subst: closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c0 Q), from free_in_prop.and\u2081 this,\n    show x \u2208 \u03c3.dom, from P_and_Q_closed_subst this\n  ),\n  have Q_closed_subst: closed_subst \u03c3 Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c0 Q), from free_in_prop.and\u2082 this,\n    show x \u2208 \u03c3.dom, from P_and_Q_closed_subst this\n  ),\n  \u27e8P_closed_subst, Q_closed_subst\u27e9\n\nlemma prop.closed_subst.or.inv {P Q: prop} {\u03c3: env}: closed_subst \u03c3 (P \u22c1 Q) \u2192 (closed_subst \u03c3 P \u2227 closed_subst \u03c3 Q) :=\n  assume P_or_Q_closed_subst: closed_subst \u03c3 (P \u22c1 Q),\n  have P_closed_subst: closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c1 Q), from free_in_prop.or\u2081 this,\n    show x \u2208 \u03c3.dom, from P_or_Q_closed_subst this\n  ),\n  have Q_closed_subst: closed_subst \u03c3 Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c1 Q), from free_in_prop.or\u2082 this,\n    show x \u2208 \u03c3.dom, from P_or_Q_closed_subst this\n  ),\n  \u27e8P_closed_subst, Q_closed_subst\u27e9\n\nlemma prop.closed_subst.not.inv {P: prop} {\u03c3: env}: closed_subst \u03c3 P.not \u2192 closed_subst \u03c3 P :=\n  assume P_not_closed_subst: closed_subst \u03c3 P.not,\n  show closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV P.not, from free_in_prop.not this,\n    show x \u2208 \u03c3.dom, from P_not_closed_subst this\n  )\n\nlemma prop.closed_subst.implies.inv {P Q: prop} {\u03c3: env}:\n      closed_subst \u03c3 (prop.implies P Q) \u2192 closed_subst \u03c3 P \u2227 closed_subst \u03c3 Q :=\n  assume P_not_or_Q_closed_subst: closed_subst \u03c3 (P.not \u22c1 Q),\n  have P_not_closed_subst: closed_subst \u03c3 P.not, from (prop.closed_subst.or.inv P_not_or_Q_closed_subst).left,\n  have P_closed_subst: closed_subst \u03c3 P, from prop.closed_subst.not.inv P_not_closed_subst,\n  have Q_closed_subst: closed_subst \u03c3 Q, from (prop.closed_subst.or.inv P_not_or_Q_closed_subst).right,\n  \u27e8P_closed_subst, Q_closed_subst\u27e9\n\nlemma prop.closed_subst.subst {P: prop} {\u03c3: env} {x: var} {v: value}:\n      closed_subst \u03c3 P \u2192 closed_subst \u03c3 (prop.subst x v P) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  show closed_subst \u03c3 (prop.subst x v P), from (\n    assume y: var,\n    assume : y \u2208 FV (prop.subst x v P),\n    have y \u2208 FV P, from (free_of_subst_prop this).right,\n    show y \u2208 \u03c3.dom, from P_closed_subst this\n  )\n\nlemma vc.closed_subst.term {t: term} {\u03c3: env}: closed_subst \u03c3 t \u2192 closed_subst \u03c3 (vc.term t) :=\n  assume t_closed: closed_subst \u03c3 t,\n  show closed_subst \u03c3 (vc.term t), from (\n    assume x: var,\n    assume : x \u2208 FV (vc.term t),\n    have free_in_term x t, from free_in_vc.term.inv this,\n    show x \u2208 \u03c3.dom, from t_closed this\n  )\n\nlemma vc.closed_subst.and {P Q: vc} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 Q \u2192 closed_subst \u03c3 (P \u22c0 Q) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  assume Q_closed_subst: closed_subst \u03c3 Q,\n  show closed_subst \u03c3 (P \u22c0 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c0 Q),\n    or.elim (free_in_vc.and.inv this) (\n      assume : x \u2208 FV P,\n      show x \u2208 \u03c3.dom, from P_closed_subst this\n    ) (\n      assume : x \u2208 FV Q,\n      show x \u2208 \u03c3.dom, from Q_closed_subst this\n    )\n  )\n\nlemma vc.closed_subst.or {P Q: vc} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 Q \u2192 closed_subst \u03c3 (P \u22c1 Q) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  assume Q_closed_subst: closed_subst \u03c3 Q,\n  show closed_subst \u03c3 (P \u22c1 Q), from (\n    assume x: var,\n    assume : x \u2208 FV (P \u22c1 Q),\n    or.elim (free_in_vc.or.inv this) (\n      assume : x \u2208 FV P,\n      show x \u2208 \u03c3.dom, from P_closed_subst this\n    ) (\n      assume : x \u2208 FV Q,\n      show x \u2208 \u03c3.dom, from Q_closed_subst this\n    )\n  )\n\nlemma vc.closed_subst.not {P: vc} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 P.not :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  show closed_subst \u03c3 P.not, from (\n    assume x: var,\n    assume : x \u2208 FV P.not,\n    have x \u2208 FV P, from free_in_vc.not.inv this,\n    show x \u2208 \u03c3.dom, from P_closed_subst this\n  )\n\nlemma vc.closed_subst.implies {P Q: vc} {\u03c3: env}:\n      closed_subst \u03c3 P \u2192 closed_subst \u03c3 Q \u2192 closed_subst \u03c3 (vc.implies P Q) :=\n  assume P_closed_subst: closed_subst \u03c3 P,\n  have P_not_closed_subst: closed_subst \u03c3 P.not, from vc.closed_subst.not P_closed_subst,\n  assume Q_closed_subst: closed_subst \u03c3 Q,\n  show closed_subst \u03c3 (P.not \u22c1 Q), from vc.closed_subst.or P_not_closed_subst Q_closed_subst\n\nlemma vc.closed_subst.term.inv {t: term} {\u03c3: env}: closed_subst \u03c3 (vc.term t) \u2192 closed_subst \u03c3 t :=\n  assume t_closed: closed_subst \u03c3 (vc.term t),\n  show closed_subst \u03c3 t, from (\n    assume x: var,\n    assume : x \u2208 FV t,\n    have free_in_vc x (vc.term t), from free_in_vc.term this,\n    show x \u2208 \u03c3.dom, from t_closed this\n  )\n\nlemma vc.closed_subst.and.inv {P Q: vc} {\u03c3: env}: closed_subst \u03c3 (P \u22c0 Q) \u2192 (closed_subst \u03c3 P \u2227 closed_subst \u03c3 Q) :=\n  assume P_and_Q_closed_subst: closed_subst \u03c3 (P \u22c0 Q),\n  have P_closed_subst: closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c0 Q), from free_in_vc.and\u2081 this,\n    show x \u2208 \u03c3.dom, from P_and_Q_closed_subst this\n  ),\n  have Q_closed_subst: closed_subst \u03c3 Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c0 Q), from free_in_vc.and\u2082 this,\n    show x \u2208 \u03c3.dom, from P_and_Q_closed_subst this\n  ),\n  \u27e8P_closed_subst, Q_closed_subst\u27e9\n\nlemma vc.closed_subst.or.inv {P Q: vc} {\u03c3: env}: closed_subst \u03c3 (P \u22c1 Q) \u2192 (closed_subst \u03c3 P \u2227 closed_subst \u03c3 Q) :=\n  assume P_or_Q_closed_subst: closed_subst \u03c3 (P \u22c1 Q),\n  have P_closed_subst: closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV (P \u22c1 Q), from free_in_vc.or\u2081 this,\n    show x \u2208 \u03c3.dom, from P_or_Q_closed_subst this\n  ),\n  have Q_closed_subst: closed_subst \u03c3 Q, from (\n    assume x: var,\n    assume : x \u2208 FV Q,\n    have x \u2208 FV (P \u22c1 Q), from free_in_vc.or\u2082 this,\n    show x \u2208 \u03c3.dom, from P_or_Q_closed_subst this\n  ),\n  \u27e8P_closed_subst, Q_closed_subst\u27e9\n\nlemma vc.closed_subst.not.inv {P: vc} {\u03c3: env}: closed_subst \u03c3 P.not \u2192 closed_subst \u03c3 P :=\n  assume P_not_closed_subst: closed_subst \u03c3 P.not,\n  show closed_subst \u03c3 P, from (\n    assume x: var,\n    assume : x \u2208 FV P,\n    have x \u2208 FV P.not, from free_in_vc.not this,\n    show x \u2208 \u03c3.dom, from P_not_closed_subst this\n  )\n\nlemma vc.closed_subst.implies.inv {P Q: vc} {\u03c3: env}:\n      closed_subst \u03c3 (vc.implies P Q) \u2192 closed_subst \u03c3 P \u2227 closed_subst \u03c3 Q :=\n  assume P_not_or_Q_closed_subst: closed_subst \u03c3 (P.not \u22c1 Q),\n  have P_not_closed_subst: closed_subst \u03c3 P.not, from (vc.closed_subst.or.inv P_not_or_Q_closed_subst).left,\n  have P_closed_subst: closed_subst \u03c3 P, from vc.closed_subst.not.inv P_not_closed_subst,\n  have Q_closed_subst: closed_subst \u03c3 Q, from (vc.closed_subst.or.inv P_not_or_Q_closed_subst).right,\n  \u27e8P_closed_subst, Q_closed_subst\u27e9\n\nlemma to_vc_closed_from_prop_closed {P: prop} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 P.to_vc :=\n  assume h1: closed_subst \u03c3 P,\n  show closed_subst \u03c3 P.to_vc, from (\n    assume x: var,\n    assume : x \u2208 FV P.to_vc,\n    have x \u2208 FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_to_vc,\n    show x \u2208 \u03c3.dom, from h1 this\n  )\n\nlemma erased_p_closed_from_prop_closed {P: prop} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 P.erased_p :=\n  assume h1: closed_subst \u03c3 P,\n  show closed_subst \u03c3 P.erased_p, from (\n    assume x: var,\n    assume : x \u2208 FV P.erased_p,\n    have x \u2208 FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_erased.left,\n    show x \u2208 \u03c3.dom, from h1 this\n  )\n\nlemma erased_n_closed_from_prop_closed {P: prop} {\u03c3: env}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 P.erased_n :=\n  assume h1: closed_subst \u03c3 P,\n  show closed_subst \u03c3 P.erased_n, from (\n    assume x: var,\n    assume : x \u2208 FV P.erased_n,\n    have x \u2208 FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_erased.right,\n    show x \u2208 \u03c3.dom, from h1 this\n  )\n\nlemma subst_closed_of_forall_closed {P: prop} {\u03c3: env} {x: var} {v: value}:\n      closed_subst \u03c3 (prop.forallc x P) \u2192 closed_subst \u03c3 (prop.subst x v P) :=\n  assume h1: closed_subst \u03c3 (prop.forallc x P),\n  show closed_subst \u03c3 (prop.subst x v P), from (\n    assume y: var,\n    assume : y \u2208 FV (prop.subst x v P),\n    have y \u2260 x \u2227 y \u2208 FV P, from free_of_subst_prop this,\n    have y \u2208 FV (prop.forallc x P), from free_in_prop.forallc this.left this.right,\n    show y \u2208 \u03c3, from h1 this\n  )\n\nlemma contains_of_free_in_nonempty_env {\u03c3: env} {x y: var} {v: value}: (x \u2260 y \u2192 y \u2208 \u03c3) \u2192 y \u2208 (\u03c3[x\u21a6v]) :=\n  assume ih: x \u2260 y \u2192 y \u2208 \u03c3,\n  if x_eq_y: x = y \u2227 option.is_none (\u03c3.apply y) then (\n    have h: \u03c3[x\u21a6v].apply x = (if x = x \u2227 option.is_none (\u03c3.apply x) then \u2191v else \u03c3.apply x), by unfold env.apply,\n    have (if x = x \u2227 option.is_none (\u03c3.apply x) then \u2191v else \u03c3.apply x) = \u2191v, by simp [x_eq_y],\n    have \u03c3[x\u21a6v].apply x = \u2191v, from eq.trans h this,\n    have \u03c3[x\u21a6v].apply y = some v, from x_eq_y.left \u25b8 this,\n    have \u2203v', \u03c3[x\u21a6v] y = some v', from exists.intro v this,\n    show y \u2208 (\u03c3[x\u21a6v]), from env.contains_apply_equiv.right.mp this\n  ) else (\n    have y \u2208 \u03c3, from (\n      have \u00ac(x = y) \u2228 \u00ac(option.is_none (\u03c3.apply y)), from not_and_distrib.mp x_eq_y,\n      this.elim (\n        assume : x \u2260 y,\n        show y \u2208 \u03c3, from ih this        \n      ) ( \n        assume : \u00ac(option.is_none (env.apply \u03c3 y)),\n        have \u00ac(option.is_none (\u03c3 y)), from this,\n        have option.is_some (\u03c3 y), from option.some_iff_not_none.mpr this,\n        have \u2203v', \u03c3 y = some v', from option.is_some_iff_exists.mp this,\n        show y \u2208 \u03c3, from env.contains_apply_equiv.right.mp this\n      )\n    ),\n    let \u27e8v', \u03c3_has_y\u27e9 := (env.contains_apply_equiv.right.mpr this) in\n    have h: \u03c3[x\u21a6v].apply y = (if x = y \u2227 option.is_none (\u03c3.apply y) then \u2191v else \u03c3.apply y), by unfold env.apply,\n    have (if x = y \u2227 option.is_none (\u03c3.apply y) then \u2191v else \u03c3.apply y) = \u03c3.apply y, by simp *,\n    have \u03c3[x\u21a6v].apply y = \u03c3.apply y, from this \u25b8 h,\n    have \u03c3[x\u21a6v].apply y = some v', from eq.trans this \u03c3_has_y,\n    have \u2203v', \u03c3[x\u21a6v] y = some v', from exists.intro v' this,\n    show y \u2208 (\u03c3[x\u21a6v]), from env.contains_apply_equiv.right.mp this\n  )\n\nlemma contains_of_free_eq_value {P: prop} {\u03c3: env} {x y: var} {v: value}:\n  x \u2208 FV (P \u22c0 (y \u2261 v)) \u2192 (x \u2208 FV P \u2192 x \u2208 \u03c3) \u2192 x \u2208 (\u03c3[y\u21a6v]) :=\n  assume x_free_in_P: x \u2208 FV (P \u22c0 (y \u2261 v)),\n  assume ih : x \u2208 FV P \u2192 x \u2208 \u03c3,\n  contains_of_free_in_nonempty_env (\n    assume x'_is_not_x: y \u2260 x,\n    have free_in_prop x P \u2228 free_in_prop x (y \u2261 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 \u2208 \u03c3, from ih x_free_in_P\n    ) (\n      assume x_free_in_eq_v: free_in_prop x (y \u2261 v),\n      show x \u2208 \u03c3, 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\u2081 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\u2082 free_in_v {\n            cases free_in_v\n          }\n        }\n      end\n    )\n  )\n\nlemma env.dom.inv {\u03c3: env} {x: var} {v: value}: (\u03c3[x\u21a6v]).dom = (\u03c3.dom \u222a set.insert x \u2205) :=\n  set.eq_of_subset_of_subset (\n    assume y: var,\n    assume : y \u2208 (\u03c3[x\u21a6v]).dom,\n    have y \u2208 (\u03c3[x\u21a6v]), from this,\n    or.elim (env.contains.inv this) (\n      assume : y = x,\n      have y \u2208 set.insert x \u2205, from set.mem_singleton_of_eq this,\n      show y \u2208 (\u03c3.dom \u222a set.insert x \u2205), from set.mem_union_right \u03c3.dom this\n    ) (\n      assume : y \u2208 \u03c3,\n      have y \u2208 \u03c3.dom, from this,\n      show y \u2208 (\u03c3.dom \u222a set.insert x \u2205), from set.mem_union_left (set.insert x \u2205) this\n    )\n  ) (\n    assume y: var,\n    assume : y \u2208 (\u03c3.dom \u222a set.insert x \u2205),\n    or.elim (set.mem_or_mem_of_mem_union this) (\n      assume : y \u2208 \u03c3.dom,\n      have y \u2208 \u03c3, from this,\n      have y \u2208 (\u03c3[x\u21a6v]), from env.contains.rest this,\n      show y \u2208 (\u03c3[x\u21a6v]).dom, from this\n    ) (\n      assume : y \u2208 set.insert x \u2205,\n      have y = x, from (set.mem_singleton_iff y x).mp this,\n      have y \u2208 (\u03c3[x\u21a6v]), from this \u25b8 env.contains.same,\n      show y \u2208 (\u03c3[x\u21a6v]).dom, from this\n    )\n  )\n\nlemma env.dom.two_elems {\u03c3: env} {x y: var} {v\u2081 v\u2082: value}: (\u03c3[x\u21a6v\u2081][y\u21a6v\u2082]).dom = \u03c3.dom \u222a {x, y} :=\n  by calc (\u03c3[x\u21a6v\u2081][y\u21a6v\u2082]).dom = (\u03c3[x\u21a6v\u2081]).dom \u222a set.insert y \u2205 : env.dom.inv\n                           ... = \u03c3.dom \u222a set.insert x \u2205 \u222a set.insert y \u2205 : by rw[env.dom.inv]\n                           ... = \u03c3.dom \u222a (set.insert x \u2205 \u222a set.insert y \u2205) : by rw[set.union_assoc]\n                           ... = \u03c3.dom \u222a {x, y} : by rw[set.two_elems_of_insert]\n\nlemma env.apply_of_contains {\u03c3: env} {x: var} {v: value}: x \u2209 \u03c3 \u2192 ((\u03c3[x\u21a6v]) x = v) :=\n  begin\n    intro h,\n    change (env.apply (\u03c3[x\u21a6v]) x = some v),\n    unfold env.apply,\n    by_cases (x = x \u2227 (option.is_none (env.apply \u03c3 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 \u03c3 x = none), from h3,\n    rw[h4] at h2,\n    unfold option.is_none at h2,\n    have h5: (\u2191tt = \u00abfalse\u00bb), from eq_false_intro h2,\n    have h6: (\u2191tt = \u00abtrue\u00bb), by simp,\n    have h7: (\u00abfalse\u00bb = \u00abtrue\u00bb), from eq.trans h5.symm h6,\n    have h8: \u00abtrue\u00bb, from trivial,\n    have r9: \u00abfalse\u00bb, from h7.symm \u25b8 h8,\n    contradiction\n  end\n\nlemma env.equiv_of_rest_and_same {\u03c3 \u03c3': env} {x: var} {v: value}:\n      (\u2200y, y \u2208 \u03c3 \u2192 (\u03c3 y = \u03c3' y)) \u2192 x \u2209 \u03c3 \u2192 (\u03c3' x = v) \u2192 (\u2200y, y \u2208 (\u03c3[x\u21a6v]) \u2192 ((\u03c3[x\u21a6v]) y = \u03c3' y)) :=\n  assume h1: (\u2200y, y \u2208 \u03c3 \u2192 (\u03c3 y = \u03c3' y)),\n  assume h2: x \u2209 \u03c3,\n  assume h3: \u03c3' x = v,\n  assume y: var,\n  assume h4: y \u2208 (\u03c3[x\u21a6v]),\n  if h: x = y then (\n    have h5: (\u03c3[x\u21a6v]) y = v, from h \u25b8 env.apply_of_contains h2,\n    show ((\u03c3[x\u21a6v]) y = \u03c3' y), from eq.trans h5 (h \u25b8 h3.symm)\n  ) else (\n    have y \u2208 \u03c3, from (\n      have y = x \u2228 y \u2208 \u03c3, from env.contains.inv h4,\n      or.elim this.symm id (\n        assume : y = x,\n        show y \u2208 \u03c3, from absurd this.symm h\n      )\n    ),\n    have h6: \u03c3 y = \u03c3' y, from h1 y this,\n    have env.apply (\u03c3[x\u21a6v]) y = \u03c3.apply y, by { unfold env.apply, simp[h] },\n    have (\u03c3[x\u21a6v]) y = \u03c3 y, from this,\n    show ((\u03c3[x\u21a6v]) y = \u03c3' y), from this.symm \u25b8 h6\n  )\n\nlemma env.equiv_of_not_contains {\u03c3 \u03c3': env} {x: var} {v: value}:\n      (\u2200y, y \u2208 \u03c3 \u2192 (\u03c3 y = \u03c3' y)) \u2192 x \u2209 \u03c3 \u2192 (\u2200y, y \u2208 \u03c3 \u2192 (\u03c3 y = (\u03c3'[x\u21a6v]) y)) :=\n  assume h1: (\u2200y, y \u2208 \u03c3 \u2192 (\u03c3 y = \u03c3' y)),\n  assume h2: x \u2209 \u03c3,\n  assume y: var,\n  assume h4: y \u2208 \u03c3,\n  if h: x = y then (\n    have x \u2208 \u03c3, from h.symm \u25b8 h4,\n    show \u03c3 y = (\u03c3'[x\u21a6v]) y, from absurd this h2\n  ) else (\n    have h2: \u03c3 y = \u03c3' y, from h1 y h4,\n    have (\u2203v, \u03c3 y = some v), from env.contains_apply_equiv.right.mpr h4,\n    have option.is_some (\u03c3 y), from option.is_some_iff_exists.mpr this,\n    have \u00ac option.is_none (\u03c3 y), from option.some_iff_not_none.mp this,\n    have h5: \u00ac (x = y \u2227 option.is_none (env.apply \u03c3' y)), from not_and_distrib.mpr (or.inl h),\n    have env.apply (\u03c3'[x\u21a6v]) y = \u03c3' y, by { unfold env.apply, simp[h5], refl },\n    show \u03c3 y = (\u03c3'[x\u21a6v]) y, from eq.trans h2 this.symm\n  )\n\nlemma env.apply_of_rest_apply {\u03c3: env} {x y: var} {vx vy: value}:\n      (\u03c3 x = vx) \u2192 ((\u03c3[y\u21a6vy]) x = vx) :=\n  begin\n    assume h1: (env.apply \u03c3 x = some vx),\n    change (env.apply (\u03c3[y\u21a6vy]) x = \u2191vx),\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: \u00ac (y = x \u2227 (option.is_none (env.apply \u03c3 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} {\u03c3: env} {x: var} {v: value}:\n      (x \u2209 \u03c3) \u2228 (\u03c3 x = v) \u2192 (term.subst_env \u03c3 (term.subst x v t) = term.subst x v (term.subst_env \u03c3 t)) :=\n  begin\n    assume h1,\n    induction t with v' y unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n    \n    show (term.subst_env \u03c3 (term.subst x v (term.value v')) = term.subst x v (term.subst_env \u03c3 (term.value v'))),\n    by begin\n      change (term.subst_env \u03c3 (term.subst x v (term.value v')) = term.subst x v (term.subst_env \u03c3 v')),\n      rw[term.subst_env.value],\n      unfold term.subst,\n      rw[term.subst_env.value],\n      change (\u2191v' = term.subst x v (term.value v')),\n      unfold term.subst\n    end,\n\n    show (term.subst_env \u03c3 (term.subst x v (term.var y)) = term.subst x v (term.subst_env \u03c3 (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 : (\u03c3 y = none), from env.contains_apply_equiv.left.mpr a,\n      have h2: (term.subst_env \u03c3 (term.var y) = y), from term.subst_env.var.left.mp this,\n      simp[h2],\n      rw[term.subst_env.value],\n      change (\u2191v = term.subst y v (term.var y)),\n      unfold term.subst,\n      simp,\n\n      have h2: (term.subst_env \u03c3 (term.var y) = v), from (term.subst_env.var.right v).mp a,\n      rw[h2],\n      change (term.subst_env \u03c3 \u2191v = 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 \u2208 \u03c3) 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 \u03c3 y = v'), from (term.subst_env.var.right v').mp h5,\n      rw[h6],\n      change (\u2191v' = term.subst x v (term.subst_env \u03c3 \u2191y)),\n      rw[h6],\n      change (\u2191v' = term.subst x v (term.value v')),\n      unfold term.subst,\n\n      have : (\u03c3 y = none), from env.contains_apply_equiv.left.mpr h3,\n      have h4: (term.subst_env \u03c3 (term.var y) = y), from term.subst_env.var.left.mp this,\n      simp[h4],\n      change (term.subst_env \u03c3 (term.var y) = term.subst x v (term.var y)),\n      rw[h2],\n      rw[h4]\n    end,\n\n    show (term.subst_env \u03c3 (term.subst x v (term.unop unop t\u2081))\n        = term.subst x v (term.subst_env \u03c3 (term.unop unop t\u2081))), by begin\n      rw[term.subst_env.unop],\n      unfold term.subst,\n      rw[term.subst_env.unop],\n      congr,\n      from t\u2081_ih\n    end,\n\n    show (term.subst_env \u03c3 (term.subst x v (term.binop binop t\u2082 t\u2083))\n        = term.subst x v (term.subst_env \u03c3 (term.binop binop t\u2082 t\u2083))), by begin\n      rw[term.subst_env.binop],\n      unfold term.subst,\n      rw[term.subst_env.binop],\n      congr,\n      rw[t\u2082_ih],\n      rw[t\u2083_ih]\n    end,\n\n    show (term.subst_env \u03c3 (term.subst x v (term.app t\u2084 t\u2085))\n        = term.subst x v (term.subst_env \u03c3 (term.app t\u2084 t\u2085))), by begin\n      rw[term.subst_env.app],\n      unfold term.subst,\n      rw[term.subst_env.app],\n      congr,\n      rw[t\u2084_ih],\n      rw[t\u2085_ih]\n    end\n  end\n\nlemma term.substt_env.order {t' t: term} {\u03c3: env} {x: var}:\n      closed t' \u2192 (x \u2209 \u03c3) \u2192 (term.subst_env \u03c3 (term.substt x t' t) = term.substt x t' (term.subst_env \u03c3 t)) :=\n  begin\n    assume t'_closed,\n    assume h1,\n    induction t with v y unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n    \n    show (term.subst_env \u03c3 (term.substt x t' (term.value v)) = term.substt x t' (term.subst_env \u03c3 (term.value v))),\n    by begin\n      change (term.subst_env \u03c3 (term.substt x t' (term.value v)) = term.substt x t' (term.subst_env \u03c3 v)),\n      rw[term.subst_env.value],\n      unfold term.substt,\n      rw[term.subst_env.value],\n      change (\u2191v = term.substt x t' (term.value v)),\n      unfold term.substt\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x t' (term.var y)) = term.substt x t' (term.subst_env \u03c3 (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 : (\u03c3 y = none), from env.contains_apply_equiv.left.mpr h1,\n      have h2: (term.subst_env \u03c3 (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 \u2208 \u03c3) 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 \u03c3 y = v'), from (term.subst_env.var.right v').mp h5,\n      rw[h6],\n      change (\u2191v' = term.substt x t' (term.subst_env \u03c3 \u2191y)),\n      rw[h6],\n      change (\u2191v' = term.substt x t' (term.value v')),\n      unfold term.substt,\n\n      have : (\u03c3 y = none), from env.contains_apply_equiv.left.mpr h3,\n      have h4: (term.subst_env \u03c3 (term.var y) = y), from term.subst_env.var.left.mp this,\n      simp[h4],\n      change (term.subst_env \u03c3 (term.var y) = term.substt x t' (term.var y)),\n      rw[h2],\n      rw[h4]\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x t' (term.unop unop t\u2081))\n        = term.substt x t' (term.subst_env \u03c3 (term.unop unop t\u2081))), by begin\n      rw[term.subst_env.unop],\n      unfold term.substt,\n      rw[term.subst_env.unop],\n      congr,\n      from t\u2081_ih\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x t' (term.binop binop t\u2082 t\u2083))\n        = term.substt x t' (term.subst_env \u03c3 (term.binop binop t\u2082 t\u2083))), by begin\n      rw[term.subst_env.binop],\n      unfold term.substt,\n      rw[term.subst_env.binop],\n      congr,\n      rw[t\u2082_ih],\n      rw[t\u2083_ih]\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x t' (term.app t\u2084 t\u2085))\n        = term.substt x t' (term.subst_env \u03c3 (term.app t\u2084 t\u2085))), by begin\n      rw[term.subst_env.app],\n      unfold term.substt,\n      rw[term.subst_env.app],\n      congr,\n      rw[t\u2084_ih],\n      rw[t\u2085_ih]\n    end\n  end\n\nlemma term.subst_env_inner {t: term} {\u03c3: env} {x: var} {v: value}:\n      (\u03c3 x = some v) \u2192 (term.subst_env \u03c3 (term.subst x v t) = term.subst_env \u03c3 t) :=\n  begin\n    assume x_is_v,\n\n    induction \u03c3 with \u03c3\u2081 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 (\u03c3\u2081[y\u21a6v']) (term.subst x v t) = term.subst_env (\u03c3\u2081[y\u21a6v']) t), by begin\n      unfold term.subst_env,\n      have h2: (env.apply (\u03c3\u2081[y\u21a6v']) x = some v), from x_is_v,\n      unfold env.apply at h2,\n      by_cases (y = x \u2227 (option.is_none (env.apply \u03c3\u2081 x))) with h3,\n      simp[h3] at h2,\n      have h4: (v' = v), from option.some.inj h2,\n      simp[h3],\n      have h5: (\u03c3\u2081 x = none), from option.is_none.inv.mpr h3.right,\n      have h6: x \u2209 \u03c3\u2081, from env.contains_apply_equiv.left.mp h5,\n      rw[h4],\n      have h7: x \u2209 FV (term.subst x v t), from term.not_free_of_subst,\n      have h8: x \u2209 FV (term.subst_env \u03c3\u2081 (term.subst x v t)),\n      have : \u00ac(free_in_term x (term.subst x v t) \u2227 x \u2209 \u03c3\u2081), by begin\n        assume : free_in_term x (term.subst x v t) \u2227 x \u2209 \u03c3\u2081,\n        show \u00abfalse\u00bb, 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 \u03c3\u2081 (term.subst x v t)) = (term.subst_env \u03c3\u2081 (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} {\u03c3: env}:\n  term.subst_env \u03c3 (term.subst_env \u03c3 t) = term.subst_env \u03c3 t :=\n  begin\n    induction \u03c3 with \u03c3' 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 (\u03c3'[x\u21a6v]) (term.subst_env (\u03c3'[x\u21a6v]) t) = term.subst_env (\u03c3'[x\u21a6v]) t), by begin\n\n      by_cases (x \u2208 \u03c3') with h1,\n      unfold term.subst_env,\n\n      have h2: x \u2209 FV (term.subst_env \u03c3' t), from term.not_free_of_subst_env h1,\n      have h3: (term.subst x v (term.subst_env \u03c3' t) = (term.subst_env \u03c3' t)),\n      from unchanged_of_subst_nonfree_term h2,\n      rw[h3],\n      have h4: x \u2209 FV (term.subst_env \u03c3' (term.subst_env \u03c3' t)), from term.not_free_of_subst_env h1,\n      have h5: (term.subst x v (term.subst_env \u03c3' (term.subst_env \u03c3' t)) = (term.subst_env \u03c3' (term.subst_env \u03c3' t))),\n      from unchanged_of_subst_nonfree_term h4,\n      rw[h5],\n      from ih,\n\n      have h6: (term.subst_env (\u03c3'[x\u21a6v]) t = term.subst x v (term.subst_env \u03c3' t)),\n      by unfold term.subst_env,\n      rw[h6],\n\n      have h7: (env.apply (\u03c3'[x\u21a6v]) x = v), from env.apply_of_contains h1,\n      have h8: (term.subst_env (\u03c3'[x\u21a6v]) (term.subst x v (term.subst_env \u03c3' t))\n              = term.subst_env (\u03c3'[x\u21a6v]) (term.subst_env \u03c3' 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 {\u03c3\u2081 \u03c3\u2082: env}:\n  (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)) \u2192 (\u03c3\u2081.dom \u2286 \u03c3\u2082.dom) :=\n  assume env_equiv: (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)),\n  assume x: var,\n  assume : x \u2208 \u03c3\u2081.dom,\n  have h1: x \u2208 \u03c3\u2081, from this,\n  have \u2203v, \u03c3\u2081 x = some v, from env.contains_apply_equiv.right.mpr h1,\n  let \u27e8v, h2\u27e9 := this in\n  have \u03c3\u2081 x = \u03c3\u2082 x, from env_equiv x h1,\n  have \u03c3\u2082 x = some v, from eq.trans this.symm h2,\n  show x \u2208 \u03c3\u2082, from env.contains_apply_equiv.right.mp (exists.intro v this)\n\nlemma env.empty_of_dom_empty {\u03c3: env}: (\u03c3.dom = \u2205) \u2192 (\u03c3 = env.empty) :=\n  begin\n    assume h1: (\u03c3.dom = \u2205),\n    cases \u03c3 with \u03c3' x v,\n    refl,\n    have h2, from set.subset_of_eq h1,\n    have h3: x \u2208 (\u03c3'[x\u21a6v]), from env.contains.same,\n    have h4: x \u2208 (\u03c3'[x\u21a6v]).dom, from h3,\n    have h5, from set.mem_of_subset_of_mem h2 h4,\n    have : x \u2209 \u2205, from set.not_mem_empty x,\n    contradiction\n  end\n\nlemma env.empty_dom_is_empty: (env.empty.dom = \u2205) :=\n  begin\n    apply set.eq_of_subset_of_subset,\n    assume x: var,\n    assume : x \u2208 env.dom env.empty,\n    have h2: x \u2208 env.empty, from this,\n    cases h2,\n\n    assume x: var,\n    assume : x \u2208 \u2205,\n    have : x \u2209 \u2205, from set.not_mem_empty x,\n    contradiction\n  end\n\nlemma term.subst_env_twice_equiv {t: term} {\u03c3\u2081 \u03c3\u2082: env}:\n  (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)) \u2192 (term.subst_env \u03c3\u2081 (term.subst_env \u03c3\u2082 t) = term.subst_env \u03c3\u2082 t) :=\n  begin\n    assume env_equiv: \u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z),\n    -- have env_subst: \u03c3\u2081.dom \u2286 \u03c3\u2082.dom, from env.dom_subset_of_equivalent_env env_equiv,\n\n    induction \u03c3\u2081 with \u03c3' x v ih,\n    \n    show (term.subst_env env.empty (term.subst_env \u03c3\u2082 t) = term.subst_env \u03c3\u2082 t),\n    by unfold term.subst_env,\n\n    show (term.subst_env (\u03c3'[x\u21a6v]) (term.subst_env \u03c3\u2082 t) = term.subst_env \u03c3\u2082 t), by begin\n      unfold term.subst_env,\n      have h1: (\u2200 (z : var), z \u2208 \u03c3' \u2192 (\u03c3' z = \u03c3\u2082 z)), by begin\n        assume z: var,\n        assume h2: z \u2208 \u03c3',\n        have h3: (env.apply (\u03c3'[x\u21a6v]) z = \u03c3\u2082 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 \u2227 (option.is_none (env.apply \u03c3' z))) \u2191v (env.apply \u03c3' z) = (env.apply \u03c3' z)),\n        from ite.if_false h7,\n        rw[h8] at h3,\n        from h3\n      end,\n\n      have h2: (term.subst_env \u03c3' (term.subst_env \u03c3\u2082 t) = term.subst_env \u03c3\u2082 t), from ih h1,\n      rw[h2],\n      have h3: x \u2208 \u03c3\u2082, by begin\n        have h3: (env.apply (\u03c3'[x\u21a6v]) x = \u03c3\u2082 x), from env_equiv x env.contains.same,\n        unfold env.apply at h3,\n        by_cases (x \u2208 \u03c3') 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 \u2227 (option.is_none (env.apply \u03c3' x))) \u2191v (env.apply \u03c3' x) = (env.apply \u03c3' x)),\n        from ite.if_false h8,\n        rw[h9] at h3,\n        have h10: (\u03c3' x = \u03c3\u2082 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 \u2227 (option.is_none (env.apply \u03c3' x))) \u2191v (env.apply \u03c3' x) = v),\n        from ite.if_true \u27e8rfl, h6\u27e9,\n        rw[h7] at h3,\n        from env.contains_apply_equiv.right.mp (exists.intro v h3.symm)\n      end,\n\n      have : x \u2209 FV (term.subst_env \u03c3\u2082 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} {\u03c3\u2081 \u03c3\u2082: env} {x: var}:\n      (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)) \u2192 (x \u2209 \u03c3\u2081) \u2192\n      (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') t)\n     = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 t)) :=\n  begin\n    assume env_equiv,\n    assume h1,\n    induction t with v y unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n    \n    show (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') (term.value v))\n        = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 (term.value v))),\n    by begin\n      change (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') (term.value v)) =\n              term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 v)),\n      rw[term.subst_env.value],\n      unfold term.substt,\n      rw[term.subst_env.value],\n      change (\u2191v = term.substt x (term.subst_env \u03c3\u2082 t') (term.value v)),\n      unfold term.substt\n    end,\n\n    show (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') (term.var y))\n        = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 (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 : (\u03c3\u2081 y = none), from env.contains_apply_equiv.left.mpr h1,\n      have h2: (term.subst_env \u03c3\u2081 (term.var y) = y), from term.subst_env.var.left.mp this,\n      simp[h2],\n      have h3: (term.subst_env \u03c3\u2081 (term.subst_env \u03c3\u2082 t') = (term.subst_env \u03c3\u2082 t')),\n      from term.subst_env_twice_equiv env_equiv,\n      rw[h3],\n      change (term.subst_env \u03c3\u2082 t' = term.substt y (term.subst_env \u03c3\u2082 t') (term.var y)),\n      unfold term.substt,\n      simp,\n\n      unfold term.substt,\n      simp[h],\n      have h3: (term.subst_env \u03c3\u2081 y = y \u2228 \u2203v: value, term.subst_env \u03c3\u2081 y = v),\n      from term.subst_env.var.inv,\n      cases h3 with h4 h5,\n\n      change (term.subst_env \u03c3\u2081 y = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 y)),\n      rw[h4],\n      change (\u2191y = term.substt x (term.subst_env \u03c3\u2082 t') (term.var y)),\n      unfold term.substt,\n      simp[h],\n\n      cases h5 with v' h6,\n      change (term.subst_env \u03c3\u2081 y = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 y)),\n      rw[h6],\n      change (\u2191v' = term.substt x (term.subst_env \u03c3\u2082 t') (term.value v')),\n      unfold term.substt\n    end,\n\n    show (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') (term.unop unop t\u2081))\n        = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 (term.unop unop t\u2081))), by begin\n      rw[term.subst_env.unop],\n      unfold term.substt,\n      rw[term.subst_env.unop],\n      congr,\n      from t\u2081_ih\n    end,\n\n    show (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') (term.binop binop t\u2082 t\u2083))\n        = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 (term.binop binop t\u2082 t\u2083))), by begin\n      rw[term.subst_env.binop],\n      unfold term.substt,\n      rw[term.subst_env.binop],\n      congr,\n      rw[t\u2082_ih],\n      rw[t\u2083_ih]\n    end,\n\n    show (term.subst_env \u03c3\u2081 (term.substt x (term.subst_env \u03c3\u2082 t') (term.app t\u2084 t\u2085))\n        = term.substt x (term.subst_env \u03c3\u2082 t') (term.subst_env \u03c3\u2081 (term.app t\u2084 t\u2085))), by begin\n      rw[term.subst_env.app],\n      unfold term.substt,\n      rw[term.subst_env.app],\n      congr,\n      rw[t\u2084_ih],\n      rw[t\u2085_ih]\n    end\n  end\n\nlemma vc.subst_env.order {P: vc}:\n    \u2200 {\u03c3: env} {x: var} {v: value},\n      (x \u2209 \u03c3) \u2228 (\u03c3 x = v) \u2192 (vc.subst_env \u03c3 (vc.subst x v P) = vc.subst x v (vc.subst_env \u03c3 P)) :=\n  begin\n    induction P,\n    case vc.term t {\n      assume \u03c3 x v,\n      assume h1,\n      change (vc.subst_env \u03c3 (vc.subst x v (vc.term t)) = vc.subst x v (vc.subst_env \u03c3 \u2191t)),\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\u2081 ih {\n      assume \u03c3 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      assume \u03c3 x v,\n      assume h1,\n      change (vc.subst_env \u03c3 (vc.subst x v (vc.and P\u2081 P\u2082)) = vc.subst x v (vc.subst_env \u03c3 (P\u2081 \u22c0 P\u2082))),\n      rw[vc.subst_env.and],\n      unfold vc.subst,\n      rw[vc.subst_env.and],\n      congr,\n      from P\u2081_ih h1,\n      from P\u2082_ih h1\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      assume \u03c3 x v,\n      assume h1,\n      change (vc.subst_env \u03c3 (vc.subst x v (vc.or P\u2081 P\u2082)) = vc.subst x v (vc.subst_env \u03c3 (P\u2081 \u22c1 P\u2082))),\n      rw[vc.subst_env.or],\n      unfold vc.subst,\n      rw[vc.subst_env.or],\n      congr,\n      from P\u2081_ih h1,\n      from P\u2082_ih h1\n    },\n    case vc.pre t\u2081 t\u2082 {\n      assume \u03c3 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\u2081 op t {\n      assume \u03c3 x v,\n      assume h1,\n      rw[vc.subst_env.pre\u2081],\n      unfold vc.subst,\n      rw[vc.subst_env.pre\u2081],\n      congr,\n      from term.subst_env.order h1\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      assume \u03c3 x v,\n      assume h1,\n      rw[vc.subst_env.pre\u2082],\n      unfold vc.subst,\n      rw[vc.subst_env.pre\u2082],\n      congr,\n      from term.subst_env.order h1,\n      from term.subst_env.order h1\n    },\n    case vc.post t\u2081 t\u2082 {\n      assume \u03c3 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 \u03c3 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 \u2209 \u03c3.without z \u2228 (\u03c3.without z x = v)),\n      from env.without_equiv h1,\n      have h3: (vc.subst_env (\u03c3.without z) (vc.subst x v P') = vc.subst x v (vc.subst_env (\u03c3.without z) P')),\n      from P'_ih h2,\n      rw[h3]\n    }\n  end\n\nlemma vc.substt_env.order {P: vc}:\n    \u2200 {\u03c3: env} {x: var} {t: term},\n      closed t \u2192 (x \u2209 \u03c3) \u2192 (vc.subst_env \u03c3 (vc.substt x t P) = vc.substt x t (vc.subst_env \u03c3 P)) :=\n  begin\n    induction P,\n    case vc.term t' {\n      assume \u03c3 x t,\n      assume t_closed,\n      assume h1,\n      change (vc.subst_env \u03c3 (vc.substt x t (vc.term t')) = vc.substt x t (vc.subst_env \u03c3 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\u2081 ih {\n      assume \u03c3 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      assume \u03c3 x t,\n      assume t_closed,\n      assume h1,\n      change (vc.subst_env \u03c3 (vc.substt x t (vc.and P\u2081 P\u2082)) = vc.substt x t (vc.subst_env \u03c3 (P\u2081 \u22c0 P\u2082))),\n      rw[vc.subst_env.and],\n      unfold vc.substt,\n      rw[vc.subst_env.and],\n      congr,\n      from P\u2081_ih t_closed h1,\n      from P\u2082_ih t_closed h1\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      assume \u03c3 x t,\n      assume t_closed,\n      assume h1,\n      change (vc.subst_env \u03c3 (vc.substt x t (vc.or P\u2081 P\u2082)) = vc.substt x t (vc.subst_env \u03c3 (P\u2081 \u22c1 P\u2082))),\n      rw[vc.subst_env.or],\n      unfold vc.substt,\n      rw[vc.subst_env.or],\n      congr,\n      from P\u2081_ih t_closed h1,\n      from P\u2082_ih t_closed h1\n    },\n    case vc.pre t\u2081 t\u2082 {\n      assume \u03c3 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\u2081 op t {\n      assume \u03c3 x t,\n      assume t_closed,\n      assume h1,\n      rw[vc.subst_env.pre\u2081],\n      unfold vc.substt,\n      rw[vc.subst_env.pre\u2081],\n      congr,\n      from term.substt_env.order t_closed h1\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      assume \u03c3 x t,\n      assume t_closed,\n      assume h1,\n      rw[vc.subst_env.pre\u2082],\n      unfold vc.substt,\n      rw[vc.subst_env.pre\u2082],\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\u2081 t\u2082 {\n      assume \u03c3 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 \u03c3 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 \u2209 \u03c3.without z),\n      from env.not_in_without h1,\n      have h3: (vc.subst_env (\u03c3.without z) (vc.substt x t P') = vc.substt x t (vc.subst_env (\u03c3.without z) P')),\n      from P'_ih t_closed h2,\n      rw[h3]\n    }\n  end\n\nlemma vc.subst_env_inner {P: vc} {\u03c3: env} {x: var} {v: value}:\n      (\u03c3 x = some v) \u2192 (vc.subst_env \u03c3 (vc.subst x v P) = vc.subst_env \u03c3 P) :=\n  begin\n    assume x_is_v,\n\n    induction \u03c3 with \u03c3\u2081 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 (\u03c3\u2081[y\u21a6v']) (vc.subst x v P) = vc.subst_env (\u03c3\u2081[y\u21a6v']) P), by begin\n      unfold vc.subst_env,\n      have h2: (env.apply (\u03c3\u2081[y\u21a6v']) x = some v), from x_is_v,\n      unfold env.apply at h2,\n      by_cases (y = x \u2227 (option.is_none (env.apply \u03c3\u2081 x))) with h3,\n      simp[h3] at h2,\n      have h4: (v' = v), from option.some.inj h2,\n      simp[h3],\n      have h5: (\u03c3\u2081 x = none), from option.is_none.inv.mpr h3.right,\n      have h6: x \u2209 \u03c3\u2081, from env.contains_apply_equiv.left.mp h5,\n      rw[h4],\n      have h7: x \u2209 FV (vc.subst x v P), from vc.not_free_of_subst,\n      have h8: x \u2209 FV (vc.subst_env \u03c3\u2081 (vc.subst x v P)),\n      from mt free_in_vc.subst_env h7,\n      have h9: (vc.subst x v (vc.subst_env \u03c3\u2081 (vc.subst x v P)) = (vc.subst_env \u03c3\u2081 (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} {\u03c3\u2081 \u03c3\u2082: env}:\n  (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)) \u2192 (vc.subst_env \u03c3\u2082 (vc.subst_env \u03c3\u2081 P) = vc.subst_env \u03c3\u2082 P) :=\n  begin\n    assume env_equiv,\n    induction \u03c3\u2081 with \u03c3\u2081' x v ih,\n    \n    show (vc.subst_env \u03c3\u2082 (vc.subst_env env.empty P) = vc.subst_env \u03c3\u2082 P), from (\n      have vc.subst_env env.empty P = P, by unfold vc.subst_env,\n      show vc.subst_env \u03c3\u2082 (vc.subst_env env.empty P) = vc.subst_env \u03c3\u2082 P, from this.symm \u25b8 rfl\n    ),\n\n    show (vc.subst_env \u03c3\u2082 (vc.subst_env (\u03c3\u2081'[x\u21a6v]) P) = vc.subst_env \u03c3\u2082 P), by begin\n      unfold vc.subst_env,\n\n      have h0: (\u2200 (z : var), z \u2208 \u03c3\u2081' \u2192 (\u03c3\u2081' z = \u03c3\u2082 z)), from (\n        assume z: var,\n        assume h1: z \u2208 \u03c3\u2081',\n        have \u2203v, \u03c3\u2081' z = some v, from env.contains_apply_equiv.right.mpr h1,\n        let \u27e8v', h2\u27e9 := this in\n        have option.is_some (\u03c3\u2081' z), from option.is_some_iff_exists.mpr this,\n        have \u00ac option.is_none (\u03c3\u2081' z), from option.some_iff_not_none.mp this,\n        have \u00ac (x = z \u2227 option.is_none (env.apply \u03c3\u2081' z)), from not_and_distrib.mpr (or.inr this),\n        have h3: env.apply (\u03c3\u2081'[x\u21a6v]) z = \u03c3\u2081' z, by { unfold env.apply, simp[this], refl },\n        have z \u2208 (\u03c3\u2081'[x\u21a6v]), from env.contains.rest h1,\n        show \u03c3\u2081' z = \u03c3\u2082 z, from h3 \u25b8 (env_equiv z this)\n      ),\n      by_cases (x \u2208 \u03c3\u2081') with h1,\n\n      have h2: x \u2209 FV (vc.subst_env \u03c3\u2081' P), from vc.not_free_of_subst_env h1,\n      have h3: (vc.subst x v (vc.subst_env \u03c3\u2081' P) = (vc.subst_env \u03c3\u2081' P)),\n      from unchanged_of_subst_nonfree_vc h2,\n      rw[h3],\n      from ih h0,\n\n      have h2: x \u2208 (\u03c3\u2081'[x\u21a6v]), from env.contains.same,\n      have h3: ((\u03c3\u2081'[x\u21a6v]) x = \u03c3\u2082 x), from env_equiv x h2,\n      have h4: (env.apply (\u03c3\u2081'[x\u21a6v]) x = v), from env.apply_of_contains h1,\n      have h5: (\u03c3\u2082 x = some v), from eq.trans h3.symm h4,\n      have h6: (vc.subst_env \u03c3\u2082 (vc.subst x v (vc.subst_env \u03c3\u2081' P)) = vc.subst_env \u03c3\u2082 (vc.subst_env \u03c3\u2081' 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} {\u03c3\u2081 \u03c3\u2082: env}:\n  (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)) \u2192 closed_subst \u03c3\u2081 P \u2192 (vc.subst_env \u03c3\u2081 P = vc.subst_env \u03c3\u2082 P) :=\n  assume h1: (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)),\n  assume P_closed: closed_subst \u03c3\u2081 P,\n  have closed (vc.subst_env \u03c3\u2081 P), from vc.closed_of_closed_subst P_closed,\n  have h2: vc.subst_env \u03c3\u2082 (vc.subst_env \u03c3\u2081 P) = (vc.subst_env \u03c3\u2081 P),\n  from unchanged_of_subst_env_nonfree_vc this \u03c3\u2082,\n  have vc.subst_env \u03c3\u2082 (vc.subst_env \u03c3\u2081 P) = vc.subst_env \u03c3\u2082 P,\n  from vc.subst_env_with_equivalent_env h1,\n  show vc.subst_env \u03c3\u2081 P = vc.subst_env \u03c3\u2082 P, from h2 \u25b8 this\n\nlemma env.remove_unimportant_equivalence {\u03c3\u2081 \u03c3\u2082: env} {x: var}:\n  (\u2200y, y \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 y = \u03c3\u2082 y)) \u2192 x \u2209 \u03c3\u2081 \u2192 (\u2200y, y \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 y = \u03c3\u2082.without x y)) :=\n  assume h1: (\u2200y, y \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 y = \u03c3\u2082 y)),\n  assume h2: x \u2209 \u03c3\u2081,\n  assume y: var,\n  assume h3: y \u2208 \u03c3\u2081,\n  have \u2203v, \u03c3\u2081 y = some v, from env.contains_apply_equiv.right.mpr h3,\n  let \u27e8v, h4\u27e9 := this in\n  have \u03c3\u2081 y = \u03c3\u2082 y, from h1 y h3,\n  have h5: \u03c3\u2082 y = v, from eq.trans this.symm h4,\n  have h6: x \u2260 y, from (\n    assume : x = y,\n    have x \u2208 \u03c3\u2081, from this.symm \u25b8 h3,\n    show \u00abfalse\u00bb, from h2 this\n  ),\n  have y \u2208 \u03c3\u2081.dom, from h3,\n  have y \u2208 \u03c3\u2082.dom, from set.mem_of_subset_of_mem (env.dom_subset_of_equivalent_env h1) this,\n  have y \u2208 \u03c3\u2082, from this,\n  have h7: y \u2208 \u03c3\u2082.without x, from env.contains_without.rinv \u27e8this, h6.symm\u27e9,\n  -- have \u2203v', \u03c3\u2082.without x y = some v', from env.contains_apply_equiv.right.mpr this,\n  have y \u2209 \u03c3\u2082.without x \u2228 (\u03c3\u2082.without x y = v), from env.without_equiv (or.inr h5),\n  or.elim this (\n    assume : y \u2209 \u03c3\u2082.without x,\n    show \u03c3\u2081 y = \u03c3\u2082.without x y, from absurd h7 this\n  ) (\n    assume : \u03c3\u2082.without x y = v,\n    show \u03c3\u2081 y = \u03c3\u2082.without x y, from eq.trans h4 this.symm\n  )\n\nlemma vc.subst_env_without_nonfree {\u03c3: env} {P: vc} {x: var}:\n  x \u2209 FV P \u2192 (vc.subst_env \u03c3 P = vc.subst_env (\u03c3.without x) P) :=\n  begin\n    assume h1: x \u2209 FV P,\n\n    induction \u03c3 with \u03c3' 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 (\u03c3'[y\u21a6v]) P = vc.subst_env (env.without (\u03c3'[y\u21a6v]) 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 \u2209 FV (vc.subst_env \u03c3' P), by begin\n        assume : x \u2208 FV (vc.subst_env \u03c3' P),\n        have : x \u2208 FV P, from free_in_vc.subst_env this,\n        show \u00abfalse\u00bb, from h1 this\n      end,\n      have h4: (vc.subst x v (vc.subst_env \u03c3' P) = (vc.subst_env \u03c3' 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 {\u03c3: env} {x: var} {v: value} {P: vc}:\n  (vc.subst_env \u03c3 (vc.subst x v P) = vc.subst x v (vc.subst_env (\u03c3.without x) P)) :=\n  have x \u2209 FV (vc.subst x v P), from vc.not_free_of_subst,\n  have h1: vc.subst_env \u03c3 (vc.subst x v P) = vc.subst_env (\u03c3.without x) (vc.subst x v P),\n  from vc.subst_env_without_nonfree this,\n  have x \u2209 \u03c3.without x, from env.not_contains_without,\n  have h2: (vc.subst_env (\u03c3.without x) (vc.subst x v P) = vc.subst x v (vc.subst_env (\u03c3.without x) P)),\n  from vc.subst_env.order (or.inl this),\n  show vc.subst_env \u03c3 (vc.subst x v P) = vc.subst x v (vc.subst_env (\u03c3.without x) P),\n  from eq.trans h1 h2\n\nlemma vc.substt_env.reorder {\u03c3: env} {x: var} {t: term} {P: vc}:\n  closed t \u2192 (vc.subst_env \u03c3 (vc.substt x t P) = vc.substt x t (vc.subst_env (\u03c3.without x) P)) :=\n  assume t_closed: closed t,\n  have x \u2209 FV (vc.substt x t P), from vc.not_free_of_substt t_closed,\n  have h1: vc.subst_env \u03c3 (vc.substt x t P) = vc.subst_env (\u03c3.without x) (vc.substt x t P),\n  from vc.subst_env_without_nonfree this,\n  have x \u2209 \u03c3.without x, from env.not_contains_without,\n  have h2: (vc.subst_env (\u03c3.without x) (vc.substt x t P) = vc.substt x t (vc.subst_env (\u03c3.without x) P)),\n  from vc.substt_env.order t_closed this,\n  show vc.subst_env \u03c3 (vc.substt x t P) = vc.substt x t (vc.subst_env (\u03c3.without x) P),\n  from eq.trans h1 h2\n\nlemma term.substt_env.redundant {\u03c3: env} {x: var} {t t': term}:\n  (term.subst_env \u03c3 (term.substt x (term.subst_env \u03c3 t) t') = term.subst_env \u03c3 (term.substt x t t')) :=\n  begin\n    induction t' with v y unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_ih,\n\n    show (term.subst_env \u03c3 (term.substt x (term.subst_env \u03c3 t) (term.value v)) =\n          term.subst_env \u03c3 (term.substt x t (term.value v))), by begin\n      unfold term.substt\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x (term.subst_env \u03c3 t) (term.var y)) =\n          term.subst_env \u03c3 (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 \u03c3 (term.substt x (term.subst_env \u03c3 t) (term.unop unop t\u2081)) =\n          term.subst_env \u03c3 (term.substt x t (term.unop unop t\u2081))), by begin\n      unfold term.substt,\n      rw[term.subst_env.unop],\n      rw[term.subst_env.unop],\n      congr,\n      from t\u2081_ih\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x (term.subst_env \u03c3 t) (term.binop binop t\u2082 t\u2083)) =\n          term.subst_env \u03c3 (term.substt x t (term.binop binop t\u2082 t\u2083))), by begin\n      unfold term.substt,\n      rw[term.subst_env.binop],\n      rw[term.subst_env.binop],\n      congr,\n      from t\u2082_ih,\n      from t\u2083_ih\n    end,\n\n    show (term.subst_env \u03c3 (term.substt x (term.subst_env \u03c3 t) (term.app t\u2084 t\u2085)) =\n          term.subst_env \u03c3 (term.substt x t (term.app t\u2084 t\u2085))), by begin\n      unfold term.substt,\n      rw[term.subst_env.app],\n      rw[term.subst_env.app],\n      congr,\n      from t\u2084_ih,\n      from t\u2085_ih\n    end\n  end\n\nlemma term.substt_var_cancel {x y: var} {t: term}: x \u2209 FV t \u2192 (term.substt x y (term.substt y x t) = t) :=\n  begin\n    assume h1,\n\n    induction t with v z unop t\u2081 t\u2081_ih binop t\u2082 t\u2083 t\u2082_ih t\u2083_ih t\u2084 t\u2085 t\u2084_ih t\u2085_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 \u2191y (term.value v) = term.value v),\n      unfold term.substt,\n      refl\n    end,\n\n    show (term.substt x \u2191y (term.substt y \u2191x (term.var z)) = term.var z), by begin\n      have h2: (x \u2260 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 \u2191z (term.var x) = term.var z),\n      unfold term.substt,\n      simp,\n      refl,\n\n      simp[h3],\n      change (term.substt x \u2191y (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\u2081)) = term.unop unop t\u2081), by begin\n      unfold term.substt,\n      congr,\n      apply t\u2081_ih,\n      assume h1,\n      have h2: x \u2208 FV (term.unop unop t\u2081), 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\u2082 t\u2083)) = term.binop binop t\u2082 t\u2083), by begin\n      unfold term.substt,\n      congr,\n      apply t\u2082_ih,\n      assume h1,\n      have h2: x \u2208 FV (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2081 h1,\n      contradiction,\n      apply t\u2083_ih,\n      assume h1,\n      have h2: x \u2208 FV (term.binop binop t\u2082 t\u2083), from free_in_term.binop\u2082 h1,\n      contradiction\n    end,\n    \n    show (term.substt x y (term.substt y x (term.app t\u2084 t\u2085)) = term.app t\u2084 t\u2085), by begin\n      unfold term.substt,\n      congr,\n      apply t\u2084_ih,\n      assume h1,\n      have h2: x \u2208 FV (term.app t\u2084 t\u2085), from free_in_term.app\u2081 h1,\n      contradiction,\n      apply t\u2085_ih,\n      assume h1,\n      have h2: x \u2208 FV (term.app t\u2084 t\u2085), from free_in_term.app\u2082 h1,\n      contradiction\n    end\n  end\n\nlemma vc.substt_var_cancel {x y: var} {P: vc}: \u00ac vc.uses_var x P \u2192 (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 \u2191y (vc.term (term.substt y \u2191x 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\u2081 P\u2081_ih {\n      unfold vc.substt,\n      congr,\n      apply P\u2081_ih,\n      assume h1,\n      have h2: vc.uses_var x (vc.not P\u2081), from vc.uses_var.not h1,\n      contradiction\n    },\n    case vc.and P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      unfold vc.substt,\n      change (vc.substt x \u2191y (vc.and (vc.substt y \u2191x P\u2081) (vc.substt y \u2191x P\u2082)) = vc.and P\u2081 P\u2082),\n      unfold vc.substt,\n      congr,\n      apply P\u2081_ih,\n      assume h1,\n      have h2: vc.uses_var x (vc.and P\u2081 P\u2082), from vc.uses_var.and\u2081 h1,\n      contradiction,\n      apply P\u2082_ih,\n      assume h1,\n      have h2: vc.uses_var x (vc.and P\u2081 P\u2082), from vc.uses_var.and\u2082 h1,\n      contradiction\n    },\n    case vc.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n      unfold vc.substt,\n      change (vc.substt x \u2191y (vc.or (vc.substt y \u2191x P\u2081) (vc.substt y \u2191x P\u2082)) = vc.or P\u2081 P\u2082),\n      unfold vc.substt,\n      congr,\n      apply P\u2081_ih,\n      assume h1,\n      have h2: vc.uses_var x (vc.or P\u2081 P\u2082), from vc.uses_var.or\u2081 h1,\n      contradiction,\n      apply P\u2082_ih,\n      assume h1,\n      have h2: vc.uses_var x (vc.or P\u2081 P\u2082), from vc.uses_var.or\u2082 h1,\n      contradiction\n    },\n    case vc.pre t\u2081 t\u2082 {\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\u2081 t\u2082), from vc.uses_var.pre\u2081 h1,\n      contradiction,\n      apply term.substt_var_cancel,\n      assume h1,\n      have h2: vc.uses_var x (vc.pre t\u2081 t\u2082), from vc.uses_var.pre\u2082 h1,\n      contradiction\n    },\n    case vc.pre\u2081 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\u2081 op t), from vc.uses_var.preop h1,\n      contradiction\n    },\n    case vc.pre\u2082 op t\u2081 t\u2082 {\n      unfold vc.substt,\n      congr,\n      apply term.substt_var_cancel,\n      assume h1,\n      have h2: vc.uses_var x (vc.pre\u2082 op t\u2081 t\u2082), from vc.uses_var.preop\u2081 h1,\n      contradiction,\n      apply term.substt_var_cancel,\n      assume h1,\n      have h2: vc.uses_var x (vc.pre\u2082 op t\u2081 t\u2082), from vc.uses_var.preop\u2082 h1,\n      contradiction\n    },\n    case vc.post t\u2081 t\u2082 {\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\u2081 t\u2082), from vc.uses_var.post\u2081 h1,\n      contradiction,\n      apply term.substt_var_cancel,\n      assume h1,\n      have h2: vc.uses_var x (vc.post t\u2081 t\u2082), from vc.uses_var.post\u2082 h1,\n      contradiction\n    },\n    case vc.univ z P\u2081 P\u2081_ih {\n      unfold vc.substt,\n      congr,\n\n      have h1: (x \u2260 z), by begin\n        assume h2,\n        rw[h2] at h1,\n        have h3: vc.uses_var z (vc.univ z P\u2081), 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 \u2209 FV P\u2081, 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\u2081), 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: \u00acvc.uses_var x P\u2081, by begin\n        assume h4,\n        have h5: vc.uses_var x (vc.univ z P\u2081), from vc.uses_var.univ h4,\n        contradiction\n      end,\n      from P\u2081_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\u2081 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n    unfold prop.subst,\n    unfold prop.to_vc,\n    change (vc.subst x v (vc.and (prop.to_vc P\u2081) (prop.to_vc P\u2082))\n           = prop.to_vc (prop.and (prop.subst x v P\u2081) (prop.subst x v P\u2082))),\n    unfold vc.subst,\n    unfold prop.to_vc,\n    congr,\n    from P\u2081_ih,\n    from P\u2082_ih\n  },\n  case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n    unfold prop.subst,\n    unfold prop.to_vc,\n    change (vc.subst x v (vc.or (prop.to_vc P\u2081) (prop.to_vc P\u2082))\n           = prop.to_vc (prop.or (prop.subst x v P\u2081) (prop.subst x v P\u2082))),\n    unfold vc.subst,\n    unfold prop.to_vc,\n    congr,\n    from P\u2081_ih,\n    from P\u2082_ih\n  },\n  case prop.pre t\u2081 t\u2082 {\n    unfold prop.subst,\n    unfold prop.to_vc,\n    unfold vc.subst\n  },\n  case prop.pre\u2081 op t {\n    unfold prop.subst,\n    unfold prop.to_vc,\n    unfold vc.subst\n  },\n  case prop.pre\u2082 op t\u2081 t\u2082 {\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\u2081 t\u2082 {\n    unfold prop.subst,\n    unfold prop.to_vc,\n    unfold vc.subst\n  },\n  case prop.forallc y P\u2081 P\u2081_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\u2081_ih\n  },\n  case prop.exis y P\u2081 P\u2081_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\u2081_ih\n  }\nend\n\nlemma subst_env_distrib_to_vc {P: prop} {\u03c3: env}:\n      (vc.subst_env \u03c3 (prop.to_vc P) = prop.to_vc (prop.subst_env \u03c3 P)) :=\n  begin\n    induction \u03c3 with \u03c3\u2081 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 (\u03c3\u2081[y\u21a6v']) (prop.to_vc P) = prop.to_vc (prop.subst_env (\u03c3\u2081[y\u21a6v']) 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\u2082 {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    unfold vc.substt,\n    change (vc.term (term.substt x t t\u2082) = prop.to_vc (prop.term (term.substt x t t\u2082))),\n    unfold prop.to_vc\n  },\n  case prop.not P\u2081 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\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    change (vc.substt x t (vc.and (prop.to_vc P\u2081) (prop.to_vc P\u2082))\n           = prop.to_vc (prop.and (prop.substt x t P\u2081) (prop.substt x t P\u2082))),\n    unfold vc.substt,\n    unfold prop.to_vc,\n    congr,\n    from P\u2081_ih,\n    from P\u2082_ih\n  },\n  case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_ih {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    change (vc.substt x t (vc.or (prop.to_vc P\u2081) (prop.to_vc P\u2082))\n           = prop.to_vc (prop.or (prop.substt x t P\u2081) (prop.substt x t P\u2082))),\n    unfold vc.substt,\n    unfold prop.to_vc,\n    congr,\n    from P\u2081_ih,\n    from P\u2082_ih\n  },\n  case prop.pre t\u2081 t\u2082 {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    unfold vc.substt\n  },\n  case prop.pre\u2081 op t\u2081 {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    unfold vc.substt\n  },\n  case prop.pre\u2082 op t\u2081 t\u2082 {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    unfold vc.substt\n  },\n  case prop.call t\u2081 {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    unfold vc.substt,\n    congr\n  },\n  case prop.post t\u2081 t\u2082 {\n    unfold prop.substt,\n    unfold prop.to_vc,\n    unfold vc.substt\n  },\n  case prop.forallc y P\u2081 P\u2081_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\u2081_ih\n  },\n  case prop.exis y P\u2081 P\u2081_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\u2081_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)) \u2227\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\u2081 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\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081) (prop.erased_p P\u2082))\n           = prop.erased_p (prop.and (prop.subst x v P\u2081) (prop.subst x v P\u2082))),\n    unfold vc.subst,\n    unfold prop.erased_p,\n    congr,\n    from P\u2081_ih.left,\n    from P\u2082_ih.left,\n    \n    unfold prop.subst,\n    unfold prop.erased_n,\n    change (vc.subst x v (vc.and (prop.erased_n P\u2081) (prop.erased_n P\u2082))\n           = prop.erased_n (prop.and (prop.subst x v P\u2081) (prop.subst x v P\u2082))),\n    unfold vc.subst,\n    unfold prop.erased_n,\n    congr,\n    from P\u2081_ih.right,\n    from P\u2082_ih.right\n  },\n  case prop.or P\u2081 P\u2082 P\u2081_ih P\u2082_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\u2081) (prop.erased_p P\u2082))\n           = prop.erased_p (prop.or (prop.subst x v P\u2081) (prop.subst x v P\u2082))),\n    unfold vc.subst,\n    unfold prop.erased_p,\n    congr,\n    from P\u2081_ih.left,\n    from P\u2082_ih.left,\n    \n    unfold prop.subst,\n    unfold prop.erased_n,\n    change (vc.subst x v (vc.or (prop.erased_n P\u2081) (prop.erased_n P\u2082))\n           = prop.erased_n (prop.or (prop.subst x v P\u2081) (prop.subst x v P\u2082))),\n    unfold vc.subst,\n    unfold prop.erased_n,\n    congr,\n    from P\u2081_ih.right,\n    from P\u2082_ih.right\n  },\n  case prop.pre t\u2081 t\u2082 {\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\u2081 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\u2082 op t\u2081 t\u2082 {\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\u2081 t\u2082 {\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\u2081 P\u2081_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\u2081_ih.right\n  },\n  case prop.exis y P\u2081 P\u2081_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\u2081_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\u2081_ih.right\n  }\nend\n\nlemma dom_eq_of_equiv {\u03c3\u2081 \u03c3\u2082: env}: (\u2200x: var, \u03c3\u2081 x = \u03c3\u2082 x) \u2192 (\u03c3\u2081.dom = \u03c3\u2082.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} {\u03c3\u2081 \u03c3\u2082: env}:\n      \u03c3\u2081.dom \u2286 \u03c3\u2082.dom \u2192 (vc.subst_env \u03c3\u2081 (vc.subst_env \u03c3\u2082 P) = vc.subst_env \u03c3\u2082 P) :=\n  begin\n    assume h1,\n    induction \u03c3\u2081 with \u03c3\u2081' x v ih,\n\n    show (vc.subst_env env.empty (vc.subst_env \u03c3\u2082 P) = vc.subst_env \u03c3\u2082 P), by begin\n      unfold vc.subst_env\n    end,\n\n    show (vc.subst_env (\u03c3\u2081'[x\u21a6v]) (vc.subst_env \u03c3\u2082 P) = vc.subst_env \u03c3\u2082 P), by begin\n      have h2: x \u2208 (\u03c3\u2081'[x\u21a6v]).dom, from env.contains.same,\n      have h3: x \u2208 \u03c3\u2082.dom, from set.mem_of_mem_of_subset h2 h1,\n      unfold vc.subst_env,\n      have h4: x \u2209 FV (vc.subst_env \u03c3\u2082 P), from vc.not_free_of_subst_env h3,\n      have h5: x \u2209 FV (vc.subst_env \u03c3\u2081' (vc.subst_env \u03c3\u2082 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 \u03c3\u2081' (vc.subst_env \u03c3\u2082 P)) = (vc.subst_env \u03c3\u2081' (vc.subst_env \u03c3\u2082 P))),\n      from unchanged_of_subst_nonfree_vc h5,\n      rw[h6],\n      have h7: env.dom \u03c3\u2081' \u2286 env.dom \u03c3\u2082, by begin\n        assume z,\n        assume h8,\n        have h9: z \u2208 \u03c3\u2081', from h8,\n        have h10: z \u2208 (\u03c3\u2081'[x\u21a6v]), 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} {\u03c3\u2081 \u03c3\u2082: env}:\n  (\u2200z, \u03c3\u2081 z = \u03c3\u2082 z) \u2192 (vc.subst_env \u03c3\u2081 P = vc.subst_env \u03c3\u2082 P) :=\n  assume h1: (\u2200z, \u03c3\u2081 z = \u03c3\u2082 z),\n  have h2: vc.subst_env \u03c3\u2081 (vc.subst_env \u03c3\u2082 P) = (vc.subst_env \u03c3\u2082 P),\n  from vc.subst_env_unchanged (set.subset_of_eq (dom_eq_of_equiv h1)),\n  have vc.subst_env \u03c3\u2081 (vc.subst_env \u03c3\u2082 P) = vc.subst_env \u03c3\u2081 P,\n  from vc.subst_env_with_equivalent_env (\u03bbz _, (h1 z).symm),\n  show vc.subst_env \u03c3\u2081 P = vc.subst_env \u03c3\u2082 P, from eq.trans this.symm h2\n\nlemma vc.subst_env_with_without_equivalent {P: vc} {\u03c3: env} {x: var} {v: value}:\n  (\u03c3 x = v) \u2192 (vc.subst_env ((\u03c3.without x)[x\u21a6v]) P = vc.subst_env \u03c3 P) :=\n  assume h1: \u03c3 x = v,\n  have (\u2200z, ((\u03c3.without x)[x\u21a6v]) z = \u03c3 z), by begin\n    assume z,\n    change (env.apply (env.without \u03c3 x[x\u21a6v]) z = \u03c3 z),\n    unfold env.apply,\n    by_cases (x = z) with h2,\n    rw[h2],\n    simp,\n    have h3: z \u2209 \u03c3.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 \u2208 \u03c3 with h6,\n\n    have h7: x \u2260 z, from h2,\n    have h8, from env.contains_without.rinv \u27e8h6, h7.symm\u27e9,\n    have h9: (env.apply (env.without \u03c3 x) z = \u03c3 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 \u2209 (env.without \u03c3 x), from env.not_in_without h6,\n    have h9: (env.apply (env.without \u03c3 x) z = none), from env.contains_apply_equiv.left.mpr h8,\n    have h10: (env.apply (env.without \u03c3 x) z = \u03c3 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 {\u03c3\u2081 \u03c3\u2082: env} {x: var} {v: value}:\n      (\u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z)) \u2192 (\u03c3\u2081 x = v) \u2192 (\u03c3\u2082 x = v) :=\n  assume env_equiv: \u2200z, z \u2208 \u03c3\u2081 \u2192 (\u03c3\u2081 z = \u03c3\u2082 z),\n  assume x_is_v: \u03c3\u2081 x = v,\n  have x \u2208 \u03c3\u2081, from env.contains_apply_equiv.right.mp (exists.intro v x_is_v),\n  have \u03c3\u2081 x = \u03c3\u2082 x, from env_equiv x this,\n  show \u03c3\u2082 x = v, from this \u25b8 x_is_v\n\nlemma to_vc_closed_subst_of_closed {\u03c3: env} {P: prop}: closed_subst \u03c3 P \u2192 closed_subst \u03c3 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": "/-\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.buffer.parser\nimport Mathlib.tactic.core\nimport Mathlib.PostPort\n\nnamespace Mathlib\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 -/\n\nalias my_theorem \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n/-- doc string -/\nnamespace tactic.alias\n\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 -/\n/-- doc string -/\n/-- 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/tactic/alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2877678157610531, "lm_q2_score": 0.039638837966467104, "lm_q1q2_score": 0.011406781820916543}}
{"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.Elab.Command\nimport Lean.Linter.Util\nimport Std.Lean.AttributeExtra\n\nnamespace Std.Linter\nopen Lean Elab Command Linter\n\n/--\nEnables the 'unnecessary `<;>`' linter. This will warn whenever the `<;>` tactic combinator\nis used when `;` would work.\n\n```\nexample : True := by apply id <;> trivial\n```\nThe `<;>` is unnecessary here because `apply id` only makes one subgoal.\nPrefer `apply id; trivial` instead.\n\nIn some cases, the `<;>` is syntactically necessary because a single tactic is expected:\n```\nexample : True := by\n  cases () with apply id <;> apply id\n  | unit => trivial\n```\nIn this case, you should use parentheses, as in `(apply id; apply id)`:\n```\nexample : True := by\n  cases () with (apply id; apply id)\n  | unit => trivial\n```\n-/\nregister_option linter.unnecessarySeqFocus : Bool := {\n  defValue := true\n  descr := \"enable the 'unnecessary <;>' linter\"\n}\nexample : True := by\n  cases () with apply id <;> apply id\n  | unit => trivial\n\nnamespace UnnecessarySeqFocus\n\n/-- Gets the value of the `linter.unnecessarySeqFocus` option. -/\ndef getLinterUnnecessarySeqFocus (o : Options) : Bool :=\n  getLinterValue linter.unnecessarySeqFocus o\n\n/--\nThe `multigoal` attribute keeps track of tactics that operate on multiple goals,\nmeaning that `tac` acts differently from `focus tac`. This is used by the\n'unnecessary `<;>`' linter to prevent false positives where `tac <;> tac'` cannot\nbe replaced by `(tac; tac')` because the latter would expose `tac` to a different set of goals.\n-/\ninitialize multigoalAttr : TagAttributeExtra \u2190\n  registerTagAttributeExtra `multigoal \"this tactic acts on multiple goals\" [\n    ``Parser.Tactic.\u00abtacticNext_=>_\u00bb,\n    ``Parser.Tactic.allGoals,\n    ``Parser.Tactic.anyGoals,\n    ``Parser.Tactic.case,\n    ``Parser.Tactic.case',\n    ``Parser.Tactic.Conv.\u00abconvNext_=>_\u00bb,\n    ``Parser.Tactic.Conv.allGoals,\n    ``Parser.Tactic.Conv.anyGoals,\n    ``Parser.Tactic.Conv.case,\n    ``Parser.Tactic.Conv.case',\n    ``Parser.Tactic.rotateLeft,\n    ``Parser.Tactic.rotateRight,\n    ``Parser.Tactic.tacticShow_,\n    ``Parser.Tactic.tacticStop_\n  ]\n\n/-- The information we record for each `<;>` node appearing in the syntax. -/\nstructure Entry where\n  /-- The `<;>` node itself. -/\n  stx : Syntax\n  /--\n  * `true`: this `<;>` has been used unnecessarily at least once\n  * `false`: it has never been executed\n  * If it has been used properly at least once, the entry is removed from the table.\n  -/\n  used : Bool\n\n/-- The monad for collecting used tactic syntaxes. -/\nabbrev M (\u03c9) := StateRefT (HashMap String.Range Entry) (ST \u03c9)\n\n/-- True if this is a `<;>` node in either `tactic` or `conv` classes. -/\n@[inline] def isSeqFocus (k : SyntaxNodeKind) : Bool :=\n  k == ``Parser.Tactic.\u00abtactic_<;>_\u00bb || k == ``Parser.Tactic.Conv.\u00abconv_<;>_\u00bb\n\n/-- Accumulates the set of tactic syntaxes that should be evaluated at least once. -/\n@[specialize] partial def getTactics {\u03c9} (stx : Syntax) : M \u03c9 Unit := do\n  if let .node _ k args := stx then\n    if isSeqFocus k then\n      let r := stx.getRange? true\n      if let some r := r then\n        modify fun m => m.insert r { stx, used := false }\n    args.forM getTactics\n\n/--\nTraverse the info tree down a given path.\nEach `(n, i)` means that the array must have length `n` and we will descend into the `i`'th child.\n-/\ndef getPath : Info \u2192 PersistentArray InfoTree \u2192 List ((n : Nat) \u00d7 Fin n) \u2192 Option Info\n  | i, _, [] => some i\n  | _, c, \u27e8n, i, h\u27e9::ns =>\n    if e : c.size = n then\n      if let .node i c' := c[i]'(e \u25b8 h) then getPath i c' ns else none\n    else none\n\nmutual\nvariable (env : Environment)\n/-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/\npartial def markUsedTacticsList (trees : PersistentArray InfoTree) : M \u03c9 Unit :=\n  trees.forM markUsedTactics\n\n/-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/\npartial def markUsedTactics : InfoTree \u2192 M \u03c9 Unit\n  | .node i c => do\n    if let .ofTacticInfo i := i then\n      if let some r := i.stx.getRange? true then\n      if let some entry := (\u2190 get).find? r then\n      if i.stx.getKind == ``Parser.Tactic.\u00abtactic_<;>_\u00bb then\n        let isBad := do\n          unless i.goalsBefore.length == 1 || !multigoalAttr.hasTag env i.stx[0].getKind do\n            none\n          -- Note: this uses the exact sequence of tactic applications\n          -- in the macro expansion of `<;> : tactic`\n          let .ofTacticInfo i \u2190 getPath (.ofTacticInfo i) c\n            [\u27e81, 0\u27e9, \u27e82, 1\u27e9, \u27e81, 0\u27e9, \u27e85, 0\u27e9] | none\n          guard <| i.goalsAfter.length == 1\n        modify fun s => if isBad.isSome then s.insert r { entry with used := true } else s.erase r\n      else if i.stx.getKind == ``Parser.Tactic.Conv.\u00abconv_<;>_\u00bb then\n        let isBad := do\n          unless i.goalsBefore.length == 1 || !multigoalAttr.hasTag env i.stx[0].getKind do\n            none\n          -- Note: this uses the exact sequence of tactic applications\n          -- in the macro expansion of `<;> : conv`\n          let .ofTacticInfo i \u2190 getPath (.ofTacticInfo i) c\n            [\u27e81, 0\u27e9, \u27e81, 0\u27e9, \u27e81, 0\u27e9, \u27e81, 0\u27e9, \u27e81, 0\u27e9, \u27e82, 1\u27e9, \u27e81, 0\u27e9, \u27e85, 0\u27e9] | none\n          guard <| i.goalsAfter.length == 1\n        modify fun s => if isBad.isSome then s.insert r { entry with used := true } else s.erase r\n    markUsedTacticsList c\n  | .context _ t => markUsedTactics t\n  | .hole _ => pure ()\n\nend\n\n/-- The main entry point to the unused tactic linter. -/\npartial def unnecessarySeqFocusLinter : Linter := fun stx => do\n  unless getLinterUnnecessarySeqFocus (\u2190 getOptions) && (\u2190 getInfoState).enabled do\n    return\n  if (\u2190 get).messages.hasErrors then\n    return\n  let trees \u2190 getInfoTrees\n  let env \u2190 getEnv\n  let go {\u03c9} : M \u03c9 Unit := do\n    getTactics stx\n    markUsedTacticsList env trees\n  let (_, map) := runST fun _ => go.run {}\n  let unused := map.fold (init := #[]) fun acc r { stx, used } =>\n    if used then acc.push (stx[1].getRange?.getD r, stx[1]) else acc\n  let key (r : String.Range) := (r.start.byteIdx, (-r.stop.byteIdx : Int))\n  let mut last : String.Range := \u27e80, 0\u27e9\n  for (r, stx) in let _ := @lexOrd; let _ := @ltOfOrd.{0}; unused.qsort (key \u00b7.1 < key \u00b7.1) do\n    if last.start \u2264 r.start && r.stop \u2264 last.stop then continue\n    logLint linter.unnecessarySeqFocus stx\n      \"Used `tac1 <;> tac2` where `(tac1; tac2)` would suffice\"\n    last := r\n\ninitialize addLinter unnecessarySeqFocusLinter\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Linter/UnnecessarySeqFocus.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885695214168317, "lm_q2_score": 0.06754669864792355, "lm_q1q2_score": 0.011405729660921122}}
{"text": "theorem unsound : False := -- Error\n  unsound\n\npartial theorem unsound : False := -- Error\n  unsound\n\nunsafe theorem unsound : False := -- Error\n  unsound\n\nconstant unsound : False  -- Error\n\naxiom magic : False -- OK\n\npartial def foo (x : Nat) : Nat := foo x  -- OK\n\nunsafe def unsound2 : False := unsound  -- OK\n\npartial def unsound3 : False := unsound3  -- Error\n\npartial def badcast1 (x : Nat) : Bool :=\n  unsafeCast x -- Error: partial cannot use unsafe constant\n\npartial def badcast2 (x : Nat) : Bool :=\n  if x == 0 then unsafeCast x -- Error: partial cannot use unsafe constant\n  else badcast2 (x + 1)\n\nunsafe def badcast3 (x : Nat) : Bool := -- OK\n  if x == 0 then unsafeCast x\n  else badcast3 (x + 1)\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/sanitychecks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.0453525760382107, "lm_q1q2_score": 0.011379541754259698}}
{"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 \u2218 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 \u2218 StatementFeatures.nameCounts)\n    if format.b then\n      result := result ++ statementF.bigramCounts.toTFeatures ++\n        argsF.concatMap (Multiset.toHFeatures \u2218 StatementFeatures.bigramCounts)\n    if format.t then\n      result := result ++ statementF.trigramCounts.toTFeatures ++\n        argsF.concatMap (Multiset.toHFeatures \u2218 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 := (\u2190 getEnv).find? n then\n    if (\u2190 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) \u2190 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 \u2192 MetaM (Option TheoremPremises)\n  | ConstantInfo.thmInfo { name := n, type := ty, value := v, .. } => do\n      let (thmFeats, argsFeats) \u2190 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 (\u2190 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 := (\u2190 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 \u2190 resolveGlobalConst stx do\n    if let some data \u2190 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 (\u2190 getEnv).constants.toList do\n    let data? \u2190 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 \u2192 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 \u2192 Multiset Name \u2192 MetaM (Multiset Name \u00d7 Bool) :=\n    fun _ ns => pure (ns, false)\n  -- Source filter.\n  if source then\n    if let some modulePath \u2190 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 \u2190 pathFromImport moduleName then\n        let mdata \u2190 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 \u2190 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 \u2190 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 := \u2205\n      for (premise, count) in premises do\n        let output \u2190 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? \u2190 extractPremisesFromConstantInfo minDepth maxDepth cinfo\n    if let some data := data? then\n      countTotal := countTotal + 1\n      let mut filteredPremises : Multiset Name := \u2205\n      let (filterResult, found) \u2190 filter data.name data.premises\n      filteredPremises := filterResult\n      if noAux || source || math then\n        filteredPremises \u2190 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 := \u2205\n      for (p, c) in premises do\n        if !(blackList.any (\u00b7.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 \u2190 Handle.mk labelsPath Mode.append false\n  let featuresHandle \u2190 Handle.mk featuresPath Mode.append false\n\n  let insert : TheoremPremises \u2192 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 \u2190 Handle.mk outputPath Mode.append false\n  for cinfo in moduleData.constants do\n    if let some modulePath \u2190 pathFromMathbinImport moduleName then\n      let args := #[cinfo.name.toString, modulePath.toString]\n      let output \u2190 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 \u2190 getEnv\n  let imports := env.imports.map (\u00b7.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 \u03b1] (f : MetaM \u03b1) : CommandElabM Unit :=\n  liftTermElabM <| do dbg_trace s!\"{Json.pretty <| toJson <| \u2190 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 \u00abextract_premises_to_files\u00bb]\nunsafe def elabExtractPremisesToFiles : CommandElab\n| `(extract_premises_to_files l:$lp f:$fp) => liftTermElabM <| do\n  let labelsPath \u2190 evalTerm String (mkConst `String) lp.raw\n  let featuresPath \u2190 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": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Std.ShareCommon\nimport Lean.Parser.Command\nimport Lean.Util.CollectLevelParams\nimport Lean.Util.FoldConsts\nimport Lean.Meta.CollectFVars\nimport Lean.Elab.Command\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.Binders\nimport Lean.Elab.DeclUtil\nnamespace Lean.Elab\n\ninductive DefKind where\n  | \u00abdef\u00bb | \u00abtheorem\u00bb | \u00abexample\u00bb | \u00abopaque\u00bb | \u00ababbrev\u00bb\n  deriving Inhabited\n\ndef DefKind.isTheorem : DefKind \u2192 Bool\n  | \u00abtheorem\u00bb => true\n  | _         => false\n\ndef DefKind.isDefOrAbbrevOrOpaque : DefKind \u2192 Bool\n  | \u00abdef\u00bb    => true\n  | \u00abopaque\u00bb => true\n  | \u00ababbrev\u00bb => true\n  | _        => false\n\ndef DefKind.isExample : DefKind \u2192 Bool\n  | \u00abexample\u00bb => true\n  | _         => false\n\nstructure DefView where\n  kind          : DefKind\n  ref           : Syntax\n  modifiers     : Modifiers\n  declId        : Syntax\n  binders       : Syntax\n  type?         : Option Syntax\n  value         : Syntax\n  deriving Inhabited\n\nnamespace Command\n\nopen Meta\n\ndef mkDefViewOfAbbrev (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\n  let (binders, type) := expandOptDeclSig (stx.getArg 2)\n  let modifiers       := modifiers.addAttribute { name := `inline }\n  let modifiers       := modifiers.addAttribute { name := `reducible }\n  { ref := stx, kind := DefKind.abbrev, modifiers := modifiers,\n    declId := stx.getArg 1, binders := binders, type? := type, value := stx.getArg 3 }\n\ndef mkDefViewOfDef (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"def \" >> declId >> optDeclSig >> declVal\n  let (binders, type) := expandOptDeclSig (stx.getArg 2)\n  { ref := stx, kind := DefKind.def, modifiers := modifiers,\n    declId := stx.getArg 1, binders := binders, type? := type, value := stx.getArg 3 }\n\ndef mkDefViewOfTheorem (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"theorem \" >> declId >> declSig >> declVal\n  let (binders, type) := expandDeclSig (stx.getArg 2)\n  { ref := stx, kind := DefKind.theorem, modifiers := modifiers,\n    declId := stx.getArg 1, binders := binders, type? := some type, value := stx.getArg 3 }\n\nnamespace MkInstanceName\n\n-- Table for `mkInstanceName`\nprivate def kindReplacements : NameMap String :=\n  Std.RBMap.ofList [\n    (``Parser.Term.depArrow, \"DepArrow\"),\n    (``Parser.Term.\u00abforall\u00bb, \"Forall\"),\n    (``Parser.Term.arrow, \"Arrow\"),\n    (``Parser.Term.prop,  \"Prop\"),\n    (``Parser.Term.sort,  \"Sort\"),\n    (``Parser.Term.type,  \"Type\")\n  ]\n\nabbrev M := StateRefT String CommandElabM\n\ndef isFirst : M Bool :=\n  return (\u2190 get) == \"\"\n\ndef append (str : String) : M Unit :=\n  modify fun s => s ++ str\n\npartial def collect (stx : Syntax) : M Unit := do\n  match stx with\n  | Syntax.node k args =>\n    unless (\u2190 isFirst) do\n      match kindReplacements.find? k with\n      | some r => append r\n      | none   => pure ()\n    for arg in args do\n      collect arg\n  | Syntax.ident (preresolved := preresolved) .. =>\n    unless preresolved.isEmpty && (\u2190 resolveGlobalName stx.getId).isEmpty do\n      match stx.getId.eraseMacroScopes with\n      | Name.str _ str _ =>\n          if str[0].isLower then\n            append str.capitalize\n          else\n            append str\n      | _ => pure ()\n  | _ => pure ()\n\ndef mkFreshInstanceName : CommandElabM Name := do\n  let s \u2190 get\n  let idx := s.nextInstIdx\n  modify fun s => { s with nextInstIdx := s.nextInstIdx + 1 }\n  return Lean.Elab.mkFreshInstanceName s.env idx\n\npartial def main (type : Syntax) : CommandElabM Name := do\n  /- We use `expandMacros` to expand notation such as `x < y` into `LT.lt x y` -/\n  let type \u2190 liftMacroM <| expandMacros type\n  let (_, str) \u2190 collect type |>.run \"\"\n  if str.isEmpty then\n    mkFreshInstanceName\n  else\n    liftMacroM <| mkUnusedBaseName <| Name.mkSimple (\"inst\" ++ str)\n\nend MkInstanceName\n\ndef mkDefViewOfConstant (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser \"constant \" >> declId >> declSig >> optional declValSimple\n  let (binders, type) := expandDeclSig (stx.getArg 2)\n  let val \u2190 match (stx.getArg 3).getOptional? with\n    | some val => pure val\n    | none     =>\n      let val \u2190 `(arbitrary)\n      pure $ Syntax.node ``Parser.Command.declValSimple #[ mkAtomFrom stx \":=\", val ]\n  return {\n    ref := stx, kind := DefKind.opaque, modifiers := modifiers,\n    declId := stx.getArg 1, binders := binders, type? := some type, value := val\n  }\n\ndef mkDefViewOfInstance (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal\n  let attrKind        \u2190 liftMacroM <| toAttributeKind stx[0]\n  let prio            \u2190 liftMacroM <| expandOptNamedPrio stx[2]\n  let attrStx         \u2190 `(attr| instance $(quote prio):numLit)\n  let (binders, type) := expandDeclSig stx[4]\n  let modifiers       := modifiers.addAttribute { kind := attrKind, name := `instance, stx := attrStx }\n  let declId \u2190 match stx[3].getOptional? with\n    | some declId => pure declId\n    | none        =>\n      let id \u2190 MkInstanceName.main type\n      pure <| Syntax.node ``Parser.Command.declId #[mkIdentFrom stx id, mkNullNode]\n  return {\n    ref := stx, kind := DefKind.def, modifiers := modifiers,\n    declId := declId, binders := binders, type? := type, value := stx[5]\n  }\n\ndef mkDefViewOfExample (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"example \" >> declSig >> declVal\n  let (binders, type) := expandDeclSig (stx.getArg 1)\n  let id              := mkIdentFrom stx `_example\n  let declId          := Syntax.node ``Parser.Command.declId #[id, mkNullNode]\n  { ref := stx, kind := DefKind.example, modifiers := modifiers,\n    declId := declId, binders := binders, type? := some type, value := stx.getArg 2 }\n\ndef isDefLike (stx : Syntax) : Bool :=\n  let declKind := stx.getKind\n  declKind == ``Parser.Command.\u00ababbrev\u00bb ||\n  declKind == ``Parser.Command.\u00abdef\u00bb ||\n  declKind == ``Parser.Command.\u00abtheorem\u00bb ||\n  declKind == ``Parser.Command.\u00abconstant\u00bb ||\n  declKind == ``Parser.Command.\u00abinstance\u00bb ||\n  declKind == ``Parser.Command.\u00abexample\u00bb\n\ndef mkDefView (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView :=\n  let declKind := stx.getKind\n  if declKind == ``Parser.Command.\u00ababbrev\u00bb then\n    pure $ mkDefViewOfAbbrev modifiers stx\n  else if declKind == ``Parser.Command.\u00abdef\u00bb then\n    pure $ mkDefViewOfDef modifiers stx\n  else if declKind == ``Parser.Command.\u00abtheorem\u00bb then\n    pure $ mkDefViewOfTheorem modifiers stx\n  else if declKind == ``Parser.Command.\u00abconstant\u00bb then\n    mkDefViewOfConstant modifiers stx\n  else if declKind == ``Parser.Command.\u00abinstance\u00bb then\n    mkDefViewOfInstance modifiers stx\n  else if declKind == ``Parser.Command.\u00abexample\u00bb then\n    pure $ mkDefViewOfExample modifiers stx\n  else\n    throwError \"unexpected kind of definition\"\n\nbuiltin_initialize registerTraceClass `Elab.definition\n\nend Command\nend Lean.Elab\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/Elab/DefView.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220561778540017, "lm_q2_score": 0.04672496061726326, "lm_q1q2_score": 0.01131704795230274}}
{"text": "example : True := by\n  fail_if_success (have : False := by assumption)\n  trivial\n\nexample : True := by\n  have : False := by\n    fail_if_success assumption\n    sorry\n  trivial\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/1375.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010667288817792, "lm_q2_score": 0.06278920991237814, "lm_q1q2_score": 0.011308755690595829}}
{"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 \u03b1) : Array (Nat \u00d7 \u03b1) :=\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 \u2192 Term\n  | 0   => mkIdent ``PFin2.fz\n  | n+1 => Syntax.mkApp (mkIdent ``PFin2.fs) #[(quoteOfNat n)]\n\nprivate def Fin2.quoteOfNat : Nat \u2192 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 \u2192 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 \u2190 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 \u2190 `(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 \u2192 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 \u2190 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 \u2190 `(\n    def $declId : $headT \u2192 $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 => \u27e8MyList.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    \u27e9\n    | MyList.Shape.cons a as => \u27e8MyList.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 \u2190 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* => \u27e8$headAlt:ident, fun i => match i with\n        $(\n          \u2190args.per_type.enum.mapM fun (i, args) => do\n            let i := arity - 1 - i\n            let body \u2190 if args.size == 0 then\n                          -- `(fun j => Fin2.elim0 (C:=fun _ => _) j)\n                          `(PFin2.elim0)\n                        else\n                          let alts \u2190 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    \u27e9)\n  let box \u2190 `(\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 \u27e8head, child\u27e9 => 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 \u2190 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 \u2190 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 \u27e8j, _\u27e9 => (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 \u2190 `(\n    fun \u27e8head, $unbox_child\u27e9 => match head with\n        $unboxBody:matchAlt*\n  )\n\n  let cmd \u2190 `(\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 \u27e8head, child\u27e9;\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) \u2190 Replace.shapeOfCtors view shapeIdent\n  let ctors := ctors.map (CtorView.declReplacePrefix view.declName declName)\n\n  trace[QPF] \"mkShape :: r.getBinders = {\u2190r.getBinders}\"\n  trace[QPF] \"mkShape :: r.expr = {r.expr}\"\n\n  -- Assemble it back together, into the shape inductive type\n  let binders \u2190 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 \u2190 mkHeadT view\n  let childTName \u2190 mkChildT view r headTName\n\n  let PName := Name.mkStr declName \"P\"\n  let PId := mkIdent PName\n  -- let u \u2190 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 \u27e8r, declName, PName\u27e9  \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 \u2190 elabTerm (\u2190 `(MvQPF.IsPolynomial $F:term)) none\n    try\n      let inst \u2190 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 \u2192 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 \u2192 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 \u2190 view.deadBinderNames.mapM fun n => \n        `(namedArgument| ($n:ident := $n:term))\n  let uncurriedApplied \u2190 `($uncurriedIdent $deadBinderNamedArgs:namedArgument*)\n\n  let arity := view.liveBinders.size\n\n  let poly \u2190 isPolynomial base\n  trace[QPF] \"poly: {poly}\"\n\n  let cmd \u2190 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 \u2192 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 \u2190 (List.range n_args).mapM fun _ => \n      do pure <| mkIdent <|\u2190 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 \u2190 body\n    \n    let explicit \u2190 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 \u2190 `(\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 \u2190 elabModifiers stx[0]\n  let decl := stx[1]\n  let view \u2190 dataSyntaxToView modifiers decl\n\n  let (nonRecView, _rho) \u2190 makeNonRecursive view;\n  trace[QPF] \"nonRecView: {nonRecView}\"\n\n  let \u27e8r, shape, _P\u27e9 \u2190 mkShape nonRecView\n\n  /- Composition pipeline -/\n  let base \u2190 elabQpfCompositionBody {\n    liveBinders := nonRecView.liveBinders, \n    deadBinders := nonRecView.deadBinders,     \n    type?   := none,\n    target  := \u2190`(\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 \u03b1 \n    | mk : \u03b1 \u2192 Wrap \u03b1\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) E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: E.W.Ayers\n-/\nprelude\nimport init.meta.tactic\nimport init.meta.expr_address\nimport init.control\n\nuniverse u\n\n/-- An alternative to format that keeps structural information stored as a tag. -/\nmeta inductive tagged_format (\u03b1 : Type u)\n| tag       : \u03b1 \u2192 tagged_format \u2192 tagged_format\n| compose   : tagged_format \u2192 tagged_format \u2192 tagged_format\n| group     : tagged_format \u2192 tagged_format\n| nest      : nat \u2192 tagged_format \u2192 tagged_format\n| highlight : format.color \u2192 tagged_format \u2192 tagged_format\n| of_format : format \u2192 tagged_format\n\nnamespace tagged_format\n\nvariables {\u03b1 \u03b2 : Type u}\n\nprotected meta def map (f : \u03b1 \u2192 \u03b2) : tagged_format \u03b1 \u2192 tagged_format \u03b2\n| (compose x y)   := compose (map x) (map y)\n| (group x)       := group $ map x\n| (nest i x)      := nest i $ map x\n| (highlight c x) := highlight c $ map x\n| (of_format x)   := of_format x\n| (tag a x)       := tag (f a) (map x)\n\nmeta instance is_functor: functor tagged_format :=\n{ map := @tagged_format.map }\n\nmeta def m_untag {t : Type \u2192 Type} [monad t] (f : \u03b1 \u2192 format \u2192 t format) : tagged_format \u03b1 \u2192 t format\n| (compose x y)   := pure format.compose <*> m_untag x <*> m_untag y\n| (group x)       := pure format.group <*> m_untag x\n| (nest i x)      := pure (format.nest i) <*> m_untag x\n| (highlight c x) := pure format.highlight <*> m_untag x <*> pure c\n| (of_format x)   := pure $ x\n| (tag a x)       := m_untag x >>= f a\n\nmeta def untag (f : \u03b1 \u2192 format \u2192 format) : tagged_format \u03b1 \u2192 format :=\n@m_untag _ id _ f\n\nmeta instance has_to_fmt : has_to_format (tagged_format \u03b1) :=\n\u27e8tagged_format.untag (\u03bb a f, f)\u27e9\n\nend tagged_format\n\n/-- tagged_format with information about subexpressions. -/\nmeta def eformat := tagged_format (expr.address \u00d7 expr)\n\n/-- A special version of pp which also preserves expression boundary information.\n\nOn a tag \u27e8e,a\u27e9, note that the given expr `e` is _not_ necessarily the subexpression of the root\nexpression that `tactic_state.pp_tagged` was called with. For example if the subexpression is\nunder a binder then all of the `expr.var 0`s will be replaced with a local constant not in\nthe local context with the name and type set to that of the binder.-/\nmeta constant tactic_state.pp_tagged : tactic_state \u2192 expr \u2192 eformat\n\nmeta def tactic.pp_tagged : expr \u2192 tactic eformat\n| e := tactic.read >>= \u03bb ts, pure $ tactic_state.pp_tagged ts e\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/tagged_format.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111975283019596, "lm_q2_score": 0.034100427798246805, "lm_q1q2_score": 0.011291325223959425}}
{"text": "import Lean\n\nopen Lean Server Lsp\n\n@[codeActionProvider]\ndef helloProvider : CodeActionProvider := fun params _snap => do\n  let td := params.textDocument\n  let edit : TextEdit := {\n      range := params.range,\n      newText := \"hello!!!\"\n    }\n  let ca : CodeAction := {\n    title := \"hello world\",\n    kind? := \"quickfix\",\n    edit? := WorkspaceEdit.ofTextEdit td.uri edit\n  }\n  let longRunner : CodeAction := {\n    title := \"a long-running action\",\n    kind? := \"refactor\",\n  }\n  let lazyResult : IO CodeAction := do\n    let v? \u2190 IO.getEnv \"PWD\"\n    let v := v?.getD \"none\"\n    return { longRunner with\n      edit? := WorkspaceEdit.ofTextEdit td.uri { range := params.range, newText := v}\n    }\n  return #[ca, {eager := longRunner, lazy? := lazyResult}]\n\ntheorem asdf : (x : Nat) \u2192 x = x := by\n  intro x\n  --^ codeAction\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/interactive/codeaction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651624720889436, "lm_q2_score": 0.04742587620689798, "lm_q1q2_score": 0.011216990261049104}}
{"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 \u2192 Type v) (n : Type u \u2192 Type w) \nwhere\n  monad_lift : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 n \u03b1\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 \u2192 Type v) (n : Type u \u2192 Type w) \nwhere\n  monad_lift : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 n \u03b1\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 \u2192 Type u_2} {n : Type u_1 \u2192 Type u_3} [has_monad_lift_t m n] {\u03b1 : Type u_1} : has_coe (m \u03b1) (n \u03b1) :=\n  has_coe.mk monad_lift\n\nprotected instance has_monad_lift_t_trans (m : Type u_1 \u2192 Type u_2) (n : Type u_1 \u2192 Type u_3) (o : Type u_1 \u2192 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 (\u03b1 : Type u_1) (ma : m \u03b1) => has_monad_lift.monad_lift (monad_lift ma)\n\nprotected instance has_monad_lift_t_refl (m : Type u_1 \u2192 Type u_2) : has_monad_lift_t m m :=\n  has_monad_lift_t.mk fun (\u03b1 : Type u_1) => id\n\n@[simp] theorem monad_lift_refl {m : Type u \u2192 Type v} {\u03b1 : 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 \u2192 Type v) (m' : Type u \u2192 Type v) (n : Type u \u2192 Type w) (n' : Type u \u2192 Type w) \nwhere\n  monad_map : {\u03b1 : Type u} \u2192 ({\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1\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 \u2192 Type v) (m' : Type u \u2192 Type v) (n : Type u \u2192 Type w) (n' : Type u \u2192 Type w) \nwhere\n  monad_map : {\u03b1 : Type u} \u2192 ({\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1\n\nprotected instance monad_functor_t_trans (m : Type u_1 \u2192 Type u_2) (m' : Type u_1 \u2192 Type u_2) (n : Type u_1 \u2192 Type u_3) (n' : Type u_1 \u2192 Type u_3) (o : Type u_1 \u2192 Type u_4) (o' : Type u_1 \u2192 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 (\u03b1 : Type u_1) (f : {\u03b1 : Type u_1} \u2192 m \u03b1 \u2192 m' \u03b1) => monad_functor.monad_map fun (\u03b1 : Type u_1) => monad_map f\n\nprotected instance monad_functor_t_refl (m : Type u_1 \u2192 Type u_2) (m' : Type u_1 \u2192 Type u_2) : monad_functor_t m m' m m' :=\n  monad_functor_t.mk fun (\u03b1 : Type u_1) (f : {\u03b1 : Type u_1} \u2192 m \u03b1 \u2192 m' \u03b1) => f\n\n@[simp] theorem monad_map_refl {m : Type u \u2192 Type v} {m' : Type u \u2192 Type v} (f : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) {\u03b1 : 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 {\u03b1 : Type} (x : my_monad \u03b1) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n    def my_monad.run {\u03b1 : Type} (x : my_monad \u03b1) := monad_run.run x\n    ```\n    -/\nclass monad_run (out : outParam (Type u \u2192 Type v)) (m : Type u \u2192 Type v) \nwhere\n  run : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 out \u03b1\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": "import Lean.Data.Json\nimport Std.Data.Option.Basic\nimport Init.System.FilePath\nimport Mathlib.Data.Option.Basic\n\nopen Lean System\n\nnamespace V2ray\n\nclass FromJsonURI (\u03b1 : Type u) where\n  fromJsonURI? : String \u2192 Json \u2192 Except String \u03b1\n\nexport FromJsonURI (fromJsonURI?)\n\ninstance : ToJson UInt8 where\n  toJson := toJson \u2218 UInt8.toNat\n\ninstance : ToJson UInt16 where\n  toJson := toJson \u2218 UInt16.toNat\n\ninstance : ToJson UInt32 where\n  toJson := toJson \u2218 UInt32.toNat\n\ninstance : ToJson UInt64 where\n  toJson := toJson \u2218 UInt64.toNat\n\ninstance : FromJson UInt8 where\n  fromJson? n := do\n    let m \u2190 fromJson? n\n    if m >= UInt8.size\n      then throw s!\"{n} is too large for UInt8\"\n      else pure m.toUInt8\n\ninstance : FromJson UInt16 where\n  fromJson? n := do\n    let m \u2190 fromJson? n\n    if m >= UInt16.size\n      then throw s!\"{n} is too large for UInt16\"\n      else pure m.toUInt16\n\ninstance : FromJson UInt32 where\n  fromJson? n := do\n    let m \u2190 fromJson? n\n    if m >= UInt32.size\n      then throw s!\"{n} is too large for UInt32\"\n      else pure m.toUInt32\n\ninstance : FromJson UInt64 where\n  fromJson? n := do\n    let m \u2190 fromJson? n\n    if m >= UInt64.size\n      then throw s!\"{n} is too large for UInt64\"\n      else pure m.toUInt64\n\ndef StringNat := Nat\n\ninstance : FromJson StringNat where\n  fromJson? o := try fromJson? (\u03b1 := Nat) o\n    catch _ => do\n      let s \u2190 fromJson? (\u03b1 := String) o\n      s.toNat?.elim (throw s!\"Can't parse {s} as a number.\") pure\n\nend V2ray\n\nnamespace Except\n\ninstance [BEq a] [BEq b] : BEq (Except a b) where\n  beq\n    | ok a, ok b => a == b\n    | error a, error b => a == b\n    | _, _ => false\n\nend Except\n\nunsafe def IO.lazy' (m : IO a) : IO (Thunk a) := pure $ Thunk.mk fun _ => \n  match unsafeIO m with\n    | Except.ok x => x\n    | Except.error e => unsafeCast (panic $ \"Uncaught exception: \" ++ e.toString : Nat)\n\n@[implemented_by IO.lazy']\ndef IO.lazy (m : IO a) : IO (Thunk a) := m.map (Thunk.mk \u2218 (fun _ => \u00b7))\n\ndef compareFilePath (p q : FilePath) : Ordering :=\n  compare p.normalize.toString q.normalize.toString\n\nunsafe def fileReadRecord : IO.Ref (RBMap FilePath String compareFilePath) :=\n  unsafeBaseIO (IO.mkRef RBMap.empty)\n\nnamespace IO.FS\n\nunsafe def trackRead' (p : FilePath) : IO String := do\n  match (\u2190 fileReadRecord.get).find? p with\n    | some s => pure s\n    | none   => do\n        let s \u2190 readFile p\n        fileReadRecord.modify (fun m => m.insert p s)\n        pure s\n\n@[implemented_by trackRead']\ndef trackRead (p : FilePath) : IO String := readFile p\n\ndef createAndWrite (path : FilePath) (s : String) : IO Unit := do\n  if let some p := path.parent\n    then createDirAll p\n  writeFile path s\n\nunsafe def writeBack' (p : FilePath) (t : Thunk (Option String)) : IO Unit := do\n  if (\u2190 fileReadRecord.get).contains p then\n    if let some s := t.get then\n      createAndWrite p s\n      fileReadRecord.modify (fun m => m.insert p s)\n\n@[implemented_by writeBack']\ndef writeBack (p : FilePath) (t : Thunk (Option String)) : IO Unit := do\n  if let some s := t.get then\n      createAndWrite p s\n\nunsafe def forceWriteBack' (p : FilePath) : IO Unit := do\n  fileReadRecord.modify (fun m => m.insert p \"\")\n\n@[implemented_by forceWriteBack']\ndef forceWriteBack (_ : FilePath) : IO Unit := pure ()\n\nend IO.FS\n\ntheorem Array.findIdx?_res_lt_size (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : \n    as.findIdx? p = some n \u2192 n < as.size := by\n  let rec prf (i : Nat) (j : Nat) (inv : i + j = as.size) : \n      Array.findIdx?.loop as p i j inv = some n \u2192 n < as.size := by\n    intro h\n    rw [Array.findIdx?.loop] at h\n    split at h\n    case inl hlt =>\n      split at h\n      case h_1 inv =>\n        rw [Nat.zero_add] at inv\n        rw [inv] at hlt\n        exact absurd hlt (Nat.lt_irrefl _)\n      case h_2 i inv =>\n        split at h\n        case inl =>\n          rw [\u2190 Option.some_injective Nat h]\n          exact hlt\n        case inr =>\n          have : i + (j + 1) = as.size := by\n            rw [\u2190 inv, Nat.add_comm j 1, Nat.add_assoc]\n          exact prf i (j + 1) this h\n    case inr => contradiction\n  rw [Array.findIdx?]\n  exact prf as.size 0 rfl\n\ndef Array.findFinIdx? (as : Array \u03b1) (p : \u03b1 \u2192 Bool) : Option (Fin as.size) := \n  match h : as.findIdx? p with\n    | none => none\n    | some i => some \u27e8i, Array.findIdx?_res_lt_size as p h\u27e9\n\n", "meta": {"author": "AliasQli", "repo": "waveforce", "sha": "4aab32a2d6693e7c2248fb43614d428b7876300a", "save_path": "github-repos/lean/AliasQli-waveforce", "path": "github-repos/lean/AliasQli-waveforce/waveforce-4aab32a2d6693e7c2248fb43614d428b7876300a/Waveforce/Util.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.03210070486507694, "lm_q1q2_score": 0.011191754591999802}}
{"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 \u03b1` 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 \u2190 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 \u03b1 e) evaluates 'e' IF 'e' has type '\u03b1'. -/\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 \u2190 result, s \u2190 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 \u2192 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 : \u2115, h : P(x) \u22a2 T(x)`, `revert_lst [x]` returns `2` and produces the state ` \u22a2 \u03a0 x, P(x) \u2192 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 : \u03b1 \u2192 \u03b2` head-eta-expands to `\u03bb a, f a`. If `f` isn't a function then it just returns `f`.  -/\n/-- (head) beta reduction. `(\u03bb 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. `(\u03bb 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 (\u03b1 : Type.{l_1}) (\u03b2 : \u03b1 -> Type.{l_2}), (Pi x : \u03b1, \u03b2 x) -> (Pi x : \u03b1, \u03b2 x) -> , Prop\n        nat     : Type\n        real    : Type\n        vec.{l} : Pi (\u03b1 : 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\u2081 h\u2082) is a more efficient version of (mk_app `congr_arg [h\u2081, h\u2082]) -/\n/-- (mk_congr_fun h\u2081 h\u2082) is a more efficient version of (mk_app `congr_fun [h\u2081, h\u2082]) -/\n/-- (mk_congr h\u2081 h\u2082) is a more efficient version of (mk_app `congr [h\u2081, h\u2082]) -/\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\u2081 h\u2082) is a more efficient version of (mk_app `eq.trans [h\u2081, h\u2082]) -/\n/-- (mk_eq_mp h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mp [h\u2081, h\u2082]) -/\n/-- (mk_eq_mpr h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mpr [h\u2081, h\u2082]) -/\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 : \u2200 (a:\u03b1) (p : P(a)), Q`\n- `non_dep_first` would produce goals `\u22a2 P(?m)`, `\u22a2 \u03b1`. 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 `\u22a2 P(?m)`.\n- `all` would produce goals `\u22a2 \u03b1`, `\u22a2 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 : \u03a0 (a\u2081:\u03b1\u2081) ... (a\u2099:\u03b1\u2099), P(a\u2081,...,a\u2099)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a\u2081,...?a\u2099)`.\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 (\u03b1 \u03b2 : Type) [objects \u03b1 \u03b2] :=\n  {c : class_name \u03b1}\n  (o : {o : \u03b2 // c = class_of \u03b1 o})\n  (m : method_name c)\n  (\u03c4 : vallist (param_types m))\ndef callsite.elim {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] {\u03b3 : Sort u}\n    (cs : callsite \u03b1 \u03b2) (f : \u03a0{c : class_name \u03b1}\n      (o : {o : \u03b2 // c = class_of \u03b1 o})\n      (m : method_name c) (\u03c4 : vallist (param_types m)),\n      cs = \u27e8o,m,\u03c4\u27e9 \u2192 \u03b3) : \u03b3 :=\n  match cs, rfl : (\u2200 b, cs = b \u2192 \u03b3) with\n  | \u27e8o,m,\u03c4\u27e9, h := f o m \u03c4 h\n  end\n\n@[derive decidable_eq]\ninductive event (\u03b1 \u03b2 : Type) [objects \u03b1 \u03b2]\n| call: \u03b2 \u2192 callsite \u03b1 \u03b2 \u2192 event\n| selection: callsite \u03b1 \u03b2 \u2192 event\ndef event.to_callsite {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] :\n    event \u03b1 \u03b2 \u2192 callsite \u03b1 \u03b2\n| (event.call _ c) := c\n| (event.selection c) := c\ndef event.o {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (e : event \u03b1 \u03b2) :\n  \u03b2 := e.to_callsite.o\ndef event.c {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (e : event \u03b1 \u03b2) :\n  class_name \u03b1 := e.to_callsite.c\ndef event.m {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (e : event \u03b1 \u03b2) :\n  method_name e.c := e.to_callsite.m\ndef event.\u03c4 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (e : event \u03b1 \u03b2) :\n  vallist (param_types e.m) := e.to_callsite.\u03c4\ninstance event.event_to_callsite {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] :\n  has_coe (event \u03b1 \u03b2) (callsite \u03b1 \u03b2) := \u27e8event.to_callsite\u27e9\n\n/- A global history is a sequence of events. -/\n@[reducible]\ndef global_history (\u03b1 \u03b2 : Type) [objects \u03b1 \u03b2] :=\n  list (event \u03b1 \u03b2)\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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (x : \u03b2) :\n    event \u03b1 \u03b2 \u2192 option (callsite \u03b1 \u03b2)\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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n  {x : \u03b2} {e : event \u03b1 \u03b2} {c : callsite \u03b1 \u03b2} :\n  event.is_call_to x e = some c \u2192 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 \u2190 a, exfalso, assumption },\n  { exfalso, assumption }\nend\ndef event.is_selection_of {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (x : \u03b2) :\n    event \u03b1 \u03b2 \u2192 option (callsite \u03b1 \u03b2)\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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n  {x : \u03b2} {e : event \u03b1 \u03b2} {c : callsite \u03b1 \u03b2} :\n  event.is_selection_of x e = some c \u2192 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 \u2190 a, exfalso, assumption }\nend\n/- The subsequences are obtained by filtering out events. -/\ndef global_history.calls_to {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (\u03b8 : global_history \u03b1 \u03b2) (x : \u03b2) : list (callsite \u03b1 \u03b2) :=\n  \u03b8.filter_map (event.is_call_to x)\ndef global_history.selections_of {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (\u03b8 : global_history \u03b1 \u03b2) (x : \u03b2) : list (callsite \u03b1 \u03b2) :=\n  \u03b8.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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (\u03b8 : global_history \u03b1 \u03b2) (o : \u03b2) : list (callsite \u03b1 \u03b2) := \n  (\u03b8!o).remove_all (\u03b8?o)\n/- Pending calls have the same object as requested. -/\nlemma global_history.pending_calls_to_object\n  {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2] (\u03b8 : global_history \u03b1 \u03b2) (o : \u03b2) :\n  \u2200 c : callsite \u03b1 \u03b2,\n    c \u2208 (global_history.pending_calls_to \u03b8 o) \u2192 c.o.val = o :=\nbegin\n  unfold global_history.pending_calls_to, intro,\n  suffices : c \u2208 \u03b8!o \u2192 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 {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (\u03b8 : global_history \u03b1 \u03b2) (o : \u03b2) : option (callsite \u03b1 \u03b2) :=\n  head (lift (\u03b8.pending_calls_to o))\n/- Scheduled calls have the same object as requested. -/\nlemma global_history.sched_object {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n  (\u03b8 : global_history \u03b1 \u03b2) (o : \u03b2) (c : callsite \u03b1 \u03b2) :\n  (global_history.sched \u03b8 o) = some c \u2192 c.o.val = o :=\nbegin\n  unfold global_history.sched,\n  cases H : (global_history.pending_calls_to \u03b8 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 \u03b8,\n    rewrite H, rewrite this, simp }\nend\ndef global_history.collect {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (\u03b8 : global_history \u03b1 \u03b2) : finset \u03b2 :=\n  to_finset (foldr (\u03bb(e : event \u03b1 \u03b2) l, e.o :: l) [] \u03b8)\n@[reducible]\ndef global_history.fresh {\u03b1 \u03b2 : Type} [objects \u03b1 \u03b2]\n    (o : \u03b2) (\u03b8 : global_history \u03b1 \u03b2) : Prop :=\n  o \u2209 \u03b8.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 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2)\n\ndef map' : \u03a0 (i j : fin 3) (hij : i \u2264 j), F i \u27f6 F j\n| \u27e80,hi\u27e9 \u27e80,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e81,hi\u27e9 \u27e81,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e82,hi\u27e9 \u27e82,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e80,hi\u27e9 \u27e81,hj\u27e9 _ := a\n| \u27e81,hi\u27e9 \u27e82,hj\u27e9 _ := b\n| \u27e80,hi\u27e9 \u27e82,hj\u27e9 _ := a \u226b b\n| \u27e8i+3,hi\u27e9 _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+3,hj\u27e9 _ := by { exfalso, revert hj, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : \u2200 (i : fin 3), map' F a b i i le_rfl = \ud835\udfd9 _\n| \u27e80,hi\u27e9 := rfl\n| \u27e81,hi\u27e9 := rfl\n| \u27e82,hi\u27e9 := rfl\n| \u27e8i+3,hi\u27e9 := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : \u03a0 (i j k : fin 3) (hij : i \u2264 j) (hjk : j \u2264 k),\n  map' F a b i j hij \u226b map' F a b j k hjk = map' F a b i k (hij.trans hjk)\n| \u27e80, _\u27e9 \u27e80, _\u27e9 k _ _ := category.id_comp _\n| \u27e81, _\u27e9 \u27e81, _\u27e9 k _ _ := category.id_comp _\n| i \u27e81, _\u27e9 \u27e81, _\u27e9 _ _ := category.comp_id _\n| i \u27e82, _\u27e9 \u27e82, _\u27e9 _ _ := category.comp_id _\n| \u27e80, _\u27e9 \u27e81, _\u27e9 \u27e82, _\u27e9 _ _ := rfl\n| \u27e8i+3,hi\u27e9 _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+3,hj\u27e9 _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ \u27e8k+3,hk\u27e9 _ _ := by { exfalso, revert hk, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin3_functor_mk\n\ndef fin3_functor_mk (F : fin 3 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2) : fin 3 \u2964 C :=\n{ obj := F,\n  map := \u03bb i j hij, fin3_functor_mk.map' F a b i j hij.le,\n  map_id' := \u03bb i, fin3_functor_mk.map'_id F a b i,\n  map_comp' := \u03bb 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 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2) (c : F 2 \u27f6 F 3)\n\ndef map' : \u03a0 (i j : fin 4) (hij : i \u2264 j), F i \u27f6 F j\n| \u27e80,hi\u27e9 \u27e80,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e81,hi\u27e9 \u27e81,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e82,hi\u27e9 \u27e82,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e83,hi\u27e9 \u27e83,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e80,hi\u27e9 \u27e81,hj\u27e9 _ := a\n| \u27e81,hi\u27e9 \u27e82,hj\u27e9 _ := b\n| \u27e82,hi\u27e9 \u27e83,hj\u27e9 _ := c\n| \u27e80,hi\u27e9 \u27e82,hj\u27e9 _ := a \u226b b\n| \u27e81,hi\u27e9 \u27e83,hj\u27e9 _ := b \u226b c\n| \u27e80,hi\u27e9 \u27e83,hj\u27e9 _ := a \u226b b \u226b c\n| \u27e8i+4,hi\u27e9 _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+4,hj\u27e9 _ := by { exfalso, revert hj, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e83,hi\u27e9 \u27e82,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : \u2200 (i : fin 4), map' F a b c i i le_rfl = \ud835\udfd9 _\n| \u27e80,hi\u27e9 := rfl\n| \u27e81,hi\u27e9 := rfl\n| \u27e82,hi\u27e9 := rfl\n| \u27e83,hi\u27e9 := rfl\n| \u27e8i+4,hi\u27e9 := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : \u03a0 (i j k : fin 4) (hij : i \u2264 j) (hjk : j \u2264 k),\n  map' F a b c i j hij \u226b map' F a b c j k hjk = map' F a b c i k (hij.trans hjk)\n| \u27e80, _\u27e9 \u27e80, _\u27e9 k _ _ := category.id_comp _\n| \u27e81, _\u27e9 \u27e81, _\u27e9 k _ _ := category.id_comp _\n| \u27e82, _\u27e9 \u27e82, _\u27e9 k _ _ := category.id_comp _\n| i \u27e81, _\u27e9 \u27e81, _\u27e9 _ _ := category.comp_id _\n| i \u27e82, _\u27e9 \u27e82, _\u27e9 _ _ := category.comp_id _\n| i \u27e83, _\u27e9 \u27e83, _\u27e9 _ _ := category.comp_id _\n| \u27e80, _\u27e9 \u27e81, _\u27e9 \u27e82, _\u27e9 _ _ := rfl\n| \u27e80, _\u27e9 \u27e81, _\u27e9 \u27e83, _\u27e9 _ _ := rfl\n| \u27e80, _\u27e9 \u27e82, _\u27e9 \u27e83, _\u27e9 _ _ := category.assoc a b c\n| \u27e81, _\u27e9 \u27e82, _\u27e9 \u27e83, _\u27e9 _ _ := rfl\n| \u27e8i+4,hi\u27e9 _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+4,hj\u27e9 _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ \u27e8k+4,hk\u27e9 _ _ := by { exfalso, revert hk, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| \u27e83,hi\u27e9 \u27e82,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n| _ \u27e83,hi\u27e9 \u27e82,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin4_functor_mk\n\ndef fin4_functor_mk (F : fin 4 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2) (c : F 2 \u27f6 F 3) : fin 4 \u2964 C :=\n{ obj := F,\n  map := \u03bb i j hij, fin4_functor_mk.map' F a b c i j hij.le,\n  map_id' := \u03bb i, fin4_functor_mk.map'_id F a b c i,\n  map_comp' := \u03bb 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": "open tactic\n\nvariables A B : Prop\n\nexample : A \u2192 B \u2192 A \u2227 B :=\nby do trace \"Hi, Mom!\",\n      trace_state\n", "meta": {"author": "semorrison", "repo": "proof", "sha": "5ee398aa239a379a431190edbb6022b1a0aa2c70", "save_path": "github-repos/lean/semorrison-proof", "path": "github-repos/lean/semorrison-proof/proof-5ee398aa239a379a431190edbb6022b1a0aa2c70/lean/tactics-monad.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.19436781101874467, "lm_q2_score": 0.05749327758919408, "lm_q1q2_score": 0.011174842513304703}}
{"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 (\u03c3 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) := (\u03b4 : Type u) \u2192 \u03c3 \u2192 (\u03b1 \u2192 \u03c3 \u2192 m \u03b4) \u2192 m \u03b4\n\nnamespace StateCpsT\n\n@[inline] def runK {\u03b1 \u03c3 : Type u} {m : Type u \u2192 Type v}  (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2) : m \u03b2 :=\n  x _ s k\n\n@[inline] def run {\u03b1 \u03c3 : Type u} {m : Type u \u2192 Type v} [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : m (\u03b1 \u00d7 \u03c3) :=\n  runK x s (fun a s => pure (a, s))\n\n@[inline] def run' {\u03b1 \u03c3 : Type u} {m : Type u \u2192 Type v}  [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : m \u03b1 :=\n  runK x s (fun a s => pure a)\n\ninstance : Monad (StateCpsT \u03c3 m) where\n  map  f x := fun \u03b4 s k => x \u03b4 s fun a s => k (f a) s\n  pure a   := fun \u03b4 s k => k a s\n  bind x f := fun \u03b4 s k => x \u03b4 s fun a s => f a \u03b4 s k\n\ninstance : LawfulMonad (StateCpsT \u03c3 m) := by\n  refine' { .. } <;> intros <;> rfl\n\ninstance : MonadStateOf \u03c3 (StateCpsT \u03c3 m) where\n  get   := fun \u03b4 s k => k s s\n  set s := fun \u03b4 _ k => k \u27e8\u27e9 s\n  modifyGet f := fun _ s k => let (a, s) := f s; k a s\n\n@[inline] protected def lift [Monad m] (x : m \u03b1) : StateCpsT \u03c3 m \u03b1 :=\n  fun _ s k => x >>= (k . s)\n\ninstance [Monad m] : MonadLift m (StateCpsT \u03c3 m) where\n  monadLift := StateCpsT.lift\n\n@[simp] theorem runK_pure {m : Type u \u2192 Type v} (a : \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2) : (pure a : StateCpsT \u03c3 m \u03b1).runK s k = k a s := rfl\n\n@[simp] theorem runK_get {m : Type u \u2192 Type v} (s : \u03c3) (k : \u03c3 \u2192 \u03c3 \u2192 m \u03b2) : (get : StateCpsT \u03c3 m \u03c3).runK s k = k s s := rfl\n\n@[simp] theorem runK_set {m : Type u \u2192 Type v} (s s' : \u03c3) (k : PUnit \u2192 \u03c3 \u2192 m \u03b2) : (set s' : StateCpsT \u03c3 m PUnit).runK s k = k \u27e8\u27e9 s' := rfl\n\n@[simp] theorem runK_modify {m : Type u \u2192 Type v} (f : \u03c3 \u2192 \u03c3) (s : \u03c3) (k : PUnit \u2192 \u03c3 \u2192 m \u03b2) : (modify f : StateCpsT \u03c3 m PUnit).runK s k = k \u27e8\u27e9 (f s) := rfl\n\n@[simp] theorem runK_lift {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2) : (StateCpsT.lift x : StateCpsT \u03c3 m \u03b1).runK s k = x >>= (k . s) := rfl\n\n@[simp] theorem runK_monadLift {\u03c3 : Type u} [Monad m] [MonadLiftT n m] (x : n \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2)\n    : (monadLift x : StateCpsT \u03c3 m \u03b1).runK s k = (monadLift x : m \u03b1) >>= (k . s) := rfl\n\n@[simp] theorem runK_bind_pure {\u03b1 \u03c3 : Type u} [Monad m] (a : \u03b1) (f : \u03b1 \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (pure a >>= f).runK s k = (f a).runK s k := rfl\n\n@[simp] theorem runK_bind_lift {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3)\n    : (StateCpsT.lift x >>= f).runK s k = x >>= fun a => (f a).runK s k := rfl\n\n@[simp] theorem runK_bind_get {\u03c3 : Type u} [Monad m] (f : \u03c3 \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (get >>= f).runK s k = (f s).runK s k := rfl\n\n@[simp] theorem runK_bind_set {\u03c3 : Type u} [Monad m] (f : PUnit \u2192 StateCpsT \u03c3 m \u03b2) (s s' : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (set s' >>= f).runK s k = (f \u27e8\u27e9).runK s' k := rfl\n\n@[simp] theorem runK_bind_modify {\u03c3 : Type u} [Monad m] (f : \u03c3 \u2192 \u03c3) (g : PUnit \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (modify f >>= g).runK s k = (g \u27e8\u27e9).runK (f s) k := rfl\n\n@[simp] theorem run_eq [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : x.run s = x.runK s (fun a s => pure (a, s)) := rfl\n\n@[simp] theorem run'_eq [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : x.run' s = x.runK s (fun a s => pure a) := rfl\n\nend StateCpsT\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/StateCps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25386101825929835, "lm_q2_score": 0.04401864719795893, "lm_q1q2_score": 0.011174618600070664}}
{"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 \u2192 thread_flag \u2192 thread_flag \u2192 Prop\n| CC: add Child Child Child\n| CM: add Child Main Main\n| MC: add Main Child Main\n\nlemma child_add: \u2200 {\u03a6}, add Child \u03a6 \u03a6\n| Child := add.CC\n| Main := add.CM\n\nlemma add_child: \u2200 {\u03a6}, add \u03a6 Child \u03a6\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: \u03a0 {\u03b3}, context \u03b3 \u2192 thread_flag \u2192 Type\n| CNu:\n  \u03a0 {\u03b3} {\u0393: context \u03b3} {\u03a6: 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 (\u27e61\u2b1dS\u266f\u27e7::\u0393) \u03a6\n  --------------------\n\u2192 config \u0393 \u03a6\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\u266f) = S\u266f -/\n| CComp:\n  \u03a0 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {\u03a6\u2081 \u03a6\u2082: thread_flag} {S: sesh_tp}\n  (\u0393: context (S\u266f::\u03b3))\n  (\u03a6: thread_flag)\n  (C: config (\u27e61\u2b1dS\u27e7::\u0393\u2081) \u03a6\u2081)\n  (D: config (\u27e61\u2b1d(sesh_tp.dual S)\u27e7::\u0393\u2082) \u03a6\u2082)\n  /- The same auto_param technique is used for the resulting\n     context and thread flag. -/\n  (_: auto_param (\u0393 = (\u27e61\u2b1dS\u266f\u27e7::(\u0393\u2081 + \u0393\u2082))) ``solve_context)\n  (_: auto_param (add \u03a6\u2081 \u03a6\u2082 \u03a6) ``solve_flag),\n  ----------\n  config \u0393 \u03a6\n\n| CMain:\n  \u03a0 {\u03b3} {\u0393: context \u03b3} {A: tp},\n  term \u0393 A\n  -------------\n\u2192 config \u0393 Main\n\n| CChild:\n  \u03a0 {\u03b3} {\u0393: context \u03b3},\n  term \u0393 End!\n  --------------\n\u2192 config \u0393 Child\nopen config\n\nnotation `\u25cf`C:90 := CMain C\nnotation `\u25cb`C:90 := CChild C\n\n/- thread evaluation contexts -/\n@[reducible]\ndef thread_ctx_fn {\u03b3} (\u0393\u2091: context \u03b3) (A': tp) (\u03a6: thread_flag) :=\n  \u03a0 (\u0393: context \u03b3), term \u0393 A' \u2192 config (\u0393 + \u0393\u2091) \u03a6\n\nnamespace thread_ctx_fn\n\n@[reducible]\ndef apply {\u03b3} {\u0393\u2091 \u0393': context \u03b3} {A': tp} {\u03a6: thread_flag}\n  (f: thread_ctx_fn \u0393\u2091 A' \u03a6)\n  (\u0393: context \u03b3)\n  (M: term \u0393' A')\n  (h: auto_param (\u0393 = \u0393'+\u0393\u2091) ``solve_context)\n  : config \u0393 \u03a6 :=\ncast (by solve_context) $ f \u0393' M\n\nend thread_ctx_fn\n\ninductive thread_ctx\n  : \u03a0 {\u03b3} {A': tp} {\u03a6: thread_flag} (\u0393\u2091: context \u03b3),\n    thread_ctx_fn \u0393\u2091 A' \u03a6 \u2192 Type\n| FMain:\n  \u2200 {\u03b3} {\u0393\u2091: context \u03b3} {A' A: tp}\n  (E: eval_ctx' \u0393\u2091 A' A),\n  --------------------------------------\n  thread_ctx \u0393\u2091 (\u03bb \u0393 M, \u25cf(E.f \u0393 M))\n\n| FChild:\n  \u2200 {\u03b3} {\u0393\u2091: context \u03b3} {A': tp}\n  (E: eval_ctx' \u0393\u2091 A' End!),\n  --------------------------------------\n  thread_ctx \u0393\u2091 (\u03bb \u0393 M, \u25cb(E.f \u0393 M))\n\nnamespace thread_ctx\n\ndef ext:\n  \u03a0 {\u03b3 \u03b4: precontext} {\u0393: context \u03b3} {A': tp} {\u03a6: thread_flag}\n    {F: thread_ctx_fn \u0393 A' \u03a6}\n  (\u03c1: ren_fn \u03b3 \u03b4),\n  thread_ctx \u0393 F\n\u2192 let \u0393' := (\u0393 \u229b (\u03bb B x, identity \u03b4 B $ \u03c1 B x)) in\n  \u03a3 F': thread_ctx_fn \u0393' A' \u03a6,\n    thread_ctx \u0393' F'\n| _ _ _ _ _ _ \u03c1 (FMain E) := \u27e8_, FMain $ eval_ctx'.ext \u03c1 E\u27e9\n| _ _ _ _ _ _ \u03c1 (FChild E) := \u27e8_, FChild $ eval_ctx'.ext \u03c1 E\u27e9\n\nend thread_ctx\n\nstructure thread_ctx' {\u03b3} (\u0393\u2091: context \u03b3) (A': tp) (\u03a6: thread_flag) :=\n(f: thread_ctx_fn \u0393\u2091 A' \u03a6)\n(h: thread_ctx \u0393\u2091 f)\n\nnamespace thread_ctx'\n\ndef ext {\u03b3 \u03b4: precontext} {\u0393: context \u03b3} {A': tp} {\u03a6: thread_flag}\n  (\u03c1: ren_fn \u03b3 \u03b4)\n  (F: thread_ctx' \u0393 A' \u03a6)\n  : thread_ctx' (\u0393 \u229b (\u03bb B x, identity \u03b4 B $ \u03c1 B x)) A' \u03a6\n:= \u27e8_, (thread_ctx.ext \u03c1 F.h).snd\u27e9\n\nend thread_ctx'\n\ninductive context_reduces: \u2200 {\u03b3 \u03b3'}, context \u03b3 \u2192 context \u03b3' \u2192 Prop\n| \u0393Id:\n  \u2200 {\u03b3} {\u0393: context \u03b3},\n  context_reduces \u0393 \u0393\n\n| \u0393Send:\n    \u2200 {\u03b3} {\u0393: context \u03b3} {\u03c0: mult}\n      {A: tp} {S: sesh_tp},\n    context_reduces (\u27e6\u03c0\u2b1d(!A\u2b1dS)\u266f\u27e7::\u0393) (\u27e6\u03c0\u2b1dS\u266f\u27e7::\u0393)\n\n| \u0393Recv:\n    \u2200 {\u03b3} {\u0393: context \u03b3} {\u03c0: mult}\n      {A: tp} {S: sesh_tp},\n    context_reduces (\u27e6\u03c0\u2b1d(?A\u2b1dS)\u266f\u27e7::\u0393) (\u27e6\u03c0\u2b1dS\u266f\u27e7::\u0393)\n\n/- An experimental rule to allow self-duality of channel types.\n   Never actually used. -/\n| \u0393Hash:\n    \u2200 {\u03b3} {\u0393: context \u03b3} {\u03c0: mult} {S: sesh_tp},\n    context_reduces (\u27e6\u03c0\u2b1dS\u266f\u27e7::\u0393) (\u27e6\u03c0\u2b1d(sesh_tp.dual S)\u266f\u27e7::\u0393)\nopen context_reduces\n\ninductive config_reduces\n  : \u2200 {\u03b3 \u03b3'} {\u0393: context \u03b3} {\u0393': context \u03b3'} {\u03a6},\n  context_reduces \u0393 \u0393' \u2192 config \u0393 \u03a6 \u2192 config \u0393' \u03a6 \u2192 Prop\nnotation C` -`h`\u27f6C `C':55 := config_reduces h C C'\n| CEvalNu:\n  \u2200 {\u03b3} {\u0393: context \u03b3} {S: sesh_tp} {\u03a6: thread_flag}\n    {C C': config (\u27e61\u2b1dS\u266f\u27e7::\u0393) \u03a6},\n  C -\u0393Id\u27f6C C'\n  ---------------------\n\u2192 ((CNu C) -\u0393Id\u27f6C (CNu C'))\n\n/- TODO the right version results from commutativity.. somehow -/\n| CEvalComp:\n  \u2200 {\u03b3} {\u0393\u2081 \u0393\u2082: context \u03b3} {S: sesh_tp} {\u03a6\u2081 \u03a6\u2082: thread_flag}\n    {C C': config (\u27e61\u2b1dS\u27e7::\u0393\u2081) \u03a6\u2081}\n  (\u0393: context $ S\u266f::\u03b3)\n  (h\u0393: \u0393 = \u27e61\u2b1dS\u266f\u27e7::(\u0393\u2081 + \u0393\u2082))\n  (\u03a6: thread_flag)\n  (h\u03a6: add \u03a6\u2081 \u03a6\u2082 \u03a6)\n  (D: config (\u27e61\u2b1dsesh_tp.dual S\u27e7::\u0393\u2082) \u03a6\u2082),\n  C -\u0393Id\u27f6C C'\n  ----------------------------------------------------------\n\u2192 ((CComp \u0393 \u03a6 C D) -\u0393Id\u27f6C (CComp \u0393 \u03a6 C' D))\n\n| CEvalChild:\n  \u2200 {\u03b3} {\u0393: context \u03b3}\n    {M M': term \u0393 End!},\n  M \u27f6M M'\n  -------------------------------\n\u2192 (\u25cbM -\u0393Id\u27f6C \u25cbM)\n\n| CEvalMain:\n  \u2200 {\u03b3} {\u0393: context \u03b3} {A: tp}\n    {M M': term \u0393 A},\n  M \u27f6M M'\n  --------------------------------\n\u2192 (\u25cfM -\u0393Id\u27f6C \u25cfM')\n\n| CEvalFork:\n  \u2200 {\u03b3} {\u0393\u2091: context \u03b3} {S: sesh_tp} {\u03a6}\n  (F: thread_ctx' \u0393\u2091 (sesh_tp.dual S) \u03a6)\n  (M: term (\u27e61\u2b1dS\u27e7::(0: context \u03b3)) End!),\n  ---------------------------------------\n  ((F.f.apply \u0393\u2091 $ Fork $ Abs M)\n  -\u0393Id\u27f6C\n  (CNu\n    $ CComp (\u27e61\u2b1dS\u266f\u27e7::\u0393\u2091) \u03a6\n      (CChild M)\n      $ (F.ext $ ren_fn.lift_once $ sesh_tp.dual S).f.apply\n        (\u27e61\u2b1dsesh_tp.dual S\u27e7::\u0393\u2091)\n        (Var\n          (\u27e61\u2b1dsesh_tp.dual S\u27e7::0)\n          $ ZVar _ $ sesh_tp.dual S)\n        $ by solve_context))\n\n| CEvalComm:\n  \u2200 {\u03b3} {\u0393v: context \u03b3} {A: tp} {S: sesh_tp}\n    {\u03a6\u2081 \u03a6\u2082: thread_flag}\n  (V: term \u0393v A)\n  (hV: value V)\n  (\u03a6: thread_flag)\n  (h\u03a6: add \u03a6\u2081 \u03a6\u2082 \u03a6)\n  (F: thread_ctx' (0: context \u03b3) S \u03a6\u2081)\n  (F': thread_ctx' (0: context \u03b3) (tp.prod A $ sesh_tp.dual S) \u03a6\u2082),\n  -----------------------------------------------------------------\n  ((CComp (\u27e61\u2b1d(!A\u2b1dS)\u266f\u27e7::\u0393v) \u03a6\n    ((F.ext $ ren_fn.lift_once $ !A\u2b1dS).f.apply\n      (\u27e61\u2b1d!A\u2b1dS\u27e7::\u0393v)\n      (Send\n        (\u27e61\u2b1d(!A\u2b1dS)\u27e7::\u0393v)\n        (term.rename (ren_fn.lift_once $ !A\u2b1dS) _ V)\n        (Var\n          (\u27e61\u2b1d(!A\u2b1dS)\u27e7::0)\n          $ ZVar \u03b3 $ !A\u2b1dS)\n        $ by solve_context)\n      $ by solve_context)\n    $ (F'.ext $ ren_fn.lift_once $ sesh_tp.dual $ !A\u2b1dS).f.apply\n      (\u27e61\u2b1dsesh_tp.dual (!A\u2b1dS)\u27e7::0)\n      (Recv $\n        Var\n          (\u27e61\u2b1dsesh_tp.dual (!A\u2b1dS)\u27e7::0)\n          (begin convert\n            (ZVar \u03b3 $ sesh_tp.dual $ !A\u2b1dS),\n            rw [sesh_tp.dual],\n          end)\n        $ begin\n          have h: ?A\u2b1dsesh_tp.dual S = sesh_tp.dual (!A\u2b1dS),\n          unfold sesh_tp.dual,\n          sorry\n        end))\n  -\u0393Send\u27f6C\n  (CComp (\u27e61\u2b1dS\u266f\u27e7::\u0393v) \u03a6\n    ((F.ext $ ren_fn.lift_once S).f.apply\n      (\u27e61\u2b1dS\u27e7::0)\n      (Var\n        (\u27e61\u2b1dS\u27e7::0)\n        (ZVar \u03b3 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      (\u27e61\u2b1dsesh_tp.dual S\u27e7::\u0393v)\n      $ Pair\n        (\u27e61\u2b1dsesh_tp.dual S\u27e7::\u0393v)\n        (term.rename (ren_fn.lift_once $ sesh_tp.dual S) _ V)\n        (Var\n          (\u27e61\u2b1dsesh_tp.dual S\u27e7::0)\n          $ ZVar \u03b3 $ sesh_tp.dual S)\n        $ by solve_context))\n\n| CEvalWait:\n  \u2200 {\u03b3} {\u03a6}\n  (F: thread_ctx' (0: context \u03b3) tp.unit \u03a6),\n  ------------------------------------------\n  ((CNu\n    $ CComp (\u27e61\u2b1dEnd?\u266f\u27e7::0) \u03a6\n      ((F.ext $ ren_fn.lift_once $ End?).f.apply\n        (\u27e61\u2b1dEnd?\u27e7::0)\n        (Wait\n          $ Var\n            (\u27e61\u2b1dEnd?\u27e7::0)\n            $ ZVar \u03b3 End?)\n        $ by solve_context)\n      $ CChild\n        $ Var (\u27e61\u2b1dEnd!\u27e7::0)\n          (ZVar \u03b3 $ sesh_tp.dual End?)\n          $ begin\n            show \u27e61\u2b1dEnd!\u27e7::0 = identity (End!::\u03b3) End! (ZVar \u03b3 End!),\n            simp with unfold_,\n          end)\n  -\u0393Id\u27f6C\n  (F.f.apply (0: context \u03b3) $ 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 \u2190 get_env\n  let decl \u2190 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 \u2190 get_env\n  let decl \u2190 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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_fast_ec_add \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 317))\n    (h_mem_5 : mem_at mem code_unreduced_mul (\u03c3.pc  - 305))\n    (h_mem_6 : mem_at mem code_unreduced_sqr (\u03c3.pc  - 285))\n    (h_mem_7 : mem_at mem code_verify_zero (\u03c3.pc  - 269))\n    (h_mem_13 : mem_at mem code_compute_slope (\u03c3.pc  - 97))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 15))\n    (hin_point0 : point0 = cast_EcPoint mem (\u03c3.fp - 14))\n    (hin_point1 : point1 = cast_EcPoint mem (\u03c3.fp - 8))\n    (\u03bdbound : \u2115)\n    -- conclusion\n  : ensuresb_ret \u03bdbound mem\n    {pc := \u03c3.pc + 28, ap := ap, fp := \u03c3.fp}\n    (\u03bb \u03ba \u03c4,\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 15)) (mem $ \u03c4.ap - 7)\n        (auto_spec_fast_ec_add_block9 mem \u03ba range_check_ptr point0 point1 (mem (\u03c4.ap - 7)) (cast_EcPoint mem (\u03c4.ap - 6)))) :=\nbegin\n  have h_mem_rec := h_mem,\n  unpack_memory code_fast_ec_add at h_mem with \u27e8hpc0, 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\u27e9,\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 \u03ba_call43 ap43 h_call43,\n  rcases h_call43 with \u27e8h_call43_ap_offset, h_call43\u27e9,\n  rcases h_call43 with \u27e8rc_m43, rc_mle43, hl_range_check_ptr\u2081, h_call43\u27e9,\n  generalize' hr_rev_range_check_ptr\u2081: mem (ap43 - 4) = range_check_ptr\u2081,\n  have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\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\u2081 },\n  rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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\u2081, 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 \u03ba_call45 ap45 h_call45,\n  rcases h_call45 with \u27e8h_call45_ap_offset, h_call45\u27e9,\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\u2081 _ _),\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\u2081, 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 \u03ba_call48 ap48 h_call48,\n  rcases h_call48 with \u27e8h_call48_ap_offset, h_call48\u27e9,\n  rcases h_call48 with \u27e8rc_m48, rc_mle48, hl_range_check_ptr\u2082, h_call48\u27e9,\n  generalize' hr_rev_range_check_ptr\u2082: mem (ap48 - 4) = range_check_ptr\u2082,\n  have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\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\u2082 },\n  try { rw [h_call45_ap_offset] at hl_range_check_ptr\u2082 }, try { arith_simps at hl_range_check_ptr\u2082 },\n  rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\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 [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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\u2082 _ _),\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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, 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 \u03ba_call51 ap51 h_call51,\n  rcases h_call51 with \u27e8h_call51_ap_offset, h_call51\u27e9,\n  rcases h_call51 with \u27e8rc_m51, rc_mle51, hl_range_check_ptr\u2083, h_call51\u27e9,\n  generalize' hr_rev_range_check_ptr\u2083: mem (ap51 - 4) = range_check_ptr\u2083,\n  have htv_range_check_ptr\u2083 := hr_rev_range_check_ptr\u2083.symm, clear hr_rev_range_check_ptr\u2083,\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\u2083 },\n  rw [\u2190htv_range_check_ptr\u2083, \u2190htv_range_check_ptr\u2082] at hl_range_check_ptr\u2083,\n  try { simp only [arg0] at h_call51 },\n  rw [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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\u2083 {\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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, 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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, 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 \u03ba_call63 ap63 h_call63,\n  rcases h_call63 with \u27e8h_call63_ap_offset, h_call63\u27e9,\n  rcases h_call63 with \u27e8rc_m63, rc_mle63, hl_range_check_ptr\u2084, h_call63\u27e9,\n  generalize' hr_rev_range_check_ptr\u2084: mem (ap63 - 1) = range_check_ptr\u2084,\n  have htv_range_check_ptr\u2084 := hr_rev_range_check_ptr\u2084.symm, clear hr_rev_range_check_ptr\u2084,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at hl_range_check_ptr\u2084 },\n  rw [\u2190htv_range_check_ptr\u2084, \u2190htv_range_check_ptr\u2083] at hl_range_check_ptr\u2084,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at h_call63 },\n  rw [\u2190htv_range_check_ptr\u2083, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, htv_new_y, htv_range_check_ptr\u2084] },\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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, htv_new_y, htv_range_check_ptr\u2084] },\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 \u03ba_call71 ap71 h_call71,\n  rcases h_call71 with \u27e8h_call71_ap_offset, h_call71\u27e9,\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\u2084 {\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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, htv_new_y, htv_range_check_ptr\u2084, 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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, htv_new_y, htv_range_check_ptr\u2084, 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 \u03ba_call80 ap80 h_call80,\n  rcases h_call80 with \u27e8h_call80_ap_offset, h_call80\u27e9,\n  rcases h_call80 with \u27e8rc_m80, rc_mle80, hl_range_check_ptr\u2085, h_call80\u27e9,\n  generalize' hr_rev_range_check_ptr\u2085: mem (ap80 - 1) = range_check_ptr\u2085,\n  have htv_range_check_ptr\u2085 := hr_rev_range_check_ptr\u2085.symm, clear hr_rev_range_check_ptr\u2085,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr\u2085 },\n  try { rw [h_call71_ap_offset] at hl_range_check_ptr\u2085 }, try { arith_simps at hl_range_check_ptr\u2085 },\n  rw [\u2190htv_range_check_ptr\u2085, \u2190htv_range_check_ptr\u2084] at hl_range_check_ptr\u2085,\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 [\u2190htv_range_check_ptr\u2084, hl_range_check_ptr\u2084, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u2190htv_range_check_ptr\u2085, hl_range_check_ptr\u2085, hl_range_check_ptr\u2084, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03ba_call43],\n  use_only [range_check_ptr\u2081],\n  use_only [slope],\n  have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n  have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n  have spec43 := h_call43 rc_h_range_check_ptr',\n  rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] at spec43,\n  try { dsimp at spec43, arith_simps at spec43 },\n  use_only [spec43],\n  use_only [\u03ba_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 [\u03ba_call48],\n  use_only [range_check_ptr\u2082],\n  use_only [new_x],\n  have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n  have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n  have spec48 := h_call48 rc_h_range_check_ptr\u2081',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190htv_range_check_ptr\u2082] at spec48,\n  try { dsimp at spec48, arith_simps at spec48 },\n  use_only [spec48],\n  use_only [\u03ba_call51],\n  use_only [range_check_ptr\u2083],\n  use_only [new_y],\n  have rc_h_range_check_ptr\u2083 := range_checked_offset' rc_h_range_check_ptr\u2082,\n  have rc_h_range_check_ptr\u2083' := range_checked_add_right rc_h_range_check_ptr\u2083, try { norm_cast at rc_h_range_check_ptr\u2083' },\n  have spec51 := h_call51 rc_h_range_check_ptr\u2082',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2083] at spec51,\n  try { dsimp at spec51, arith_simps at spec51 },\n  use_only [spec51],\n  use_only [\u03ba_call63],\n  use_only [range_check_ptr\u2084],\n  have rc_h_range_check_ptr\u2084 := range_checked_offset' rc_h_range_check_ptr\u2083,\n  have rc_h_range_check_ptr\u2084' := range_checked_add_right rc_h_range_check_ptr\u2084, try { norm_cast at rc_h_range_check_ptr\u2084' },\n  have spec63 := h_call63 rc_h_range_check_ptr\u2083',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190hl_range_check_ptr\u2083, \u2190htv_range_check_ptr\u2084] at spec63,\n  try { dsimp at spec63, arith_simps at spec63 },\n  use_only [spec63],\n  use_only [\u03ba_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 [\u03ba_call80],\n  use_only [range_check_ptr\u2085],\n  have rc_h_range_check_ptr\u2085 := range_checked_offset' rc_h_range_check_ptr\u2084,\n  have rc_h_range_check_ptr\u2085' := range_checked_add_right rc_h_range_check_ptr\u2085, try { norm_cast at rc_h_range_check_ptr\u2085' },\n  have spec80 := h_call80 rc_h_range_check_ptr\u2084',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190hl_range_check_ptr\u2083, \u2190hl_range_check_ptr\u2084, \u2190htv_range_check_ptr\u2085] 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\u2081, htv_slope, htv_slope_sqr, htv_range_check_ptr\u2082, htv_new_x, htv_range_check_ptr\u2083, htv_new_y, htv_range_check_ptr\u2084, htv_x_diff_slope, htv_range_check_ptr\u2085] }, },\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 \u03c3.pc\n    (h_mem : mem_at mem code_fast_ec_add \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 317))\n    (h_mem_5 : mem_at mem code_unreduced_mul (\u03c3.pc  - 305))\n    (h_mem_6 : mem_at mem code_unreduced_sqr (\u03c3.pc  - 285))\n    (h_mem_7 : mem_at mem code_verify_zero (\u03c3.pc  - 269))\n    (h_mem_13 : mem_at mem code_compute_slope (\u03c3.pc  - 97))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 15))\n    (hin_point0 : point0 = cast_EcPoint mem (\u03c3.fp - 14))\n    (hin_point1 : point1 = cast_EcPoint mem (\u03c3.fp - 8))\n    (\u03bdbound : \u2115)\n    -- conclusion\n  : ensuresb_ret \u03bdbound mem\n    {pc := \u03c3.pc + 14, ap := ap, fp := \u03c3.fp}\n    (\u03bb \u03ba \u03c4,\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 15)) (mem $ \u03c4.ap - 7)\n        (auto_spec_fast_ec_add_block5 mem \u03ba range_check_ptr point0 point1 (mem (\u03c4.ap - 7)) (cast_EcPoint mem (\u03c4.ap - 6)))) :=\nbegin\n  have h_mem_rec := h_mem,\n  unpack_memory code_fast_ec_add at h_mem with \u27e8hpc0, 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\u27e9,\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 \u2260 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 \u03c3 _ 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 \u03bdbound),\n        intros \u03ba_block9 \u03c4, try { arith_simps },\n        intro h_block9,\n        rcases h_block9 with \u27e8rc_m_block9, rc_m_le_block9, hblk_range_check_ptr\u2081, h_block9\u27e9,\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\u2081] },\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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n        have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n        have h_block9' := h_block9 rc_h_range_check_ptr',\n        try { rw [\u2190hin_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[\u03ba_block9],\n        use [h_block9],\n        try { linarith }\n      }\n    },\n    {\n      -- if: negative branch\n      have a16 : point1.x.d1 \u2260 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 \u03c3 _ 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 \u03bdbound),\n      intros \u03ba_block9 \u03c4, try { arith_simps },\n      intro h_block9,\n      rcases h_block9 with \u27e8rc_m_block9, rc_m_le_block9, hblk_range_check_ptr\u2081, h_block9\u27e9,\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\u2081] },\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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n      have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n      have h_block9' := h_block9 rc_h_range_check_ptr',\n      try { rw [\u2190hin_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[\u03ba_block9],\n      use [h_block9],\n      try { linarith }\n    }\n  },\n  {\n    -- if: negative branch\n    have a14 : point1.x.d0 \u2260 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 \u03c3 _ 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 \u03bdbound),\n    intros \u03ba_block9 \u03c4, try { arith_simps },\n    intro h_block9,\n    rcases h_block9 with \u27e8rc_m_block9, rc_m_le_block9, hblk_range_check_ptr\u2081, h_block9\u27e9,\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\u2081] },\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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n    have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n    have h_block9' := h_block9 rc_h_range_check_ptr',\n    try { rw [\u2190hin_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[\u03ba_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 \u03c3.pc\n    (h_mem : mem_at mem code_fast_ec_add \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 317))\n    (h_mem_5 : mem_at mem code_unreduced_mul (\u03c3.pc  - 305))\n    (h_mem_6 : mem_at mem code_unreduced_sqr (\u03c3.pc  - 285))\n    (h_mem_7 : mem_at mem code_verify_zero (\u03c3.pc  - 269))\n    (h_mem_13 : mem_at mem code_compute_slope (\u03c3.pc  - 97))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 15))\n    (hin_point0 : point0 = cast_EcPoint mem (\u03c3.fp - 14))\n    (hin_point1 : point1 = cast_EcPoint mem (\u03c3.fp - 8))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 15)) (mem $ \u03c4.ap - 7)\n        (spec_fast_ec_add mem \u03ba range_check_ptr point0 point1 (mem (\u03c4.ap - 7)) (cast_EcPoint mem (\u03c4.ap - 6)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  have h_mem_rec := h_mem,\n  unpack_memory code_fast_ec_add at h_mem with \u27e8hpc0, 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\u27e9,\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 \u2260 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 \u03c3 _ 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 \u03bdbound),\n        intros \u03ba_block5 \u03c4, try { arith_simps },\n        intro h_block5,\n        rcases h_block5 with \u27e8rc_m_block5, rc_m_le_block5, hblk_range_check_ptr\u2081, h_block5\u27e9,\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\u2081] },\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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n        have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n        have h_block5' := h_block5 rc_h_range_check_ptr',\n        try { rw [\u2190hin_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[\u03ba_block5],\n        use [h_block5],\n        try { linarith }\n      }\n    },\n    {\n      -- if: negative branch\n      have a2 : point0.x.d1 \u2260 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 \u03c3 _ 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 \u03bdbound),\n      intros \u03ba_block5 \u03c4, try { arith_simps },\n      intro h_block5,\n      rcases h_block5 with \u27e8rc_m_block5, rc_m_le_block5, hblk_range_check_ptr\u2081, h_block5\u27e9,\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\u2081] },\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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n      have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n      have h_block5' := h_block5 rc_h_range_check_ptr',\n      try { rw [\u2190hin_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[\u03ba_block5],\n      use [h_block5],\n      try { linarith }\n    }\n  },\n  {\n    -- if: negative branch\n    have a0 : point0.x.d0 \u2260 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 \u03c3 _ 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 \u03bdbound),\n    intros \u03ba_block5 \u03c4, try { arith_simps },\n    intro h_block5,\n    rcases h_block5 with \u27e8rc_m_block5, rc_m_le_block5, hblk_range_check_ptr\u2081, h_block5\u27e9,\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\u2081] },\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\u2081 := range_checked_offset' rc_h_range_check_ptr,\n    have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n    have h_block5' := h_block5 rc_h_range_check_ptr',\n    try { rw [\u2190hin_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[\u03ba_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": "import Lean\n\nimport Smt.Reconstruction.Certifying.Boolean\nimport Smt.Reconstruction.Certifying.Pull\n\nnamespace Smt.Reconstruction.Certifying\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\u2082 $nm)\n    else `(dupOr $nm)\n  | (i' + 1) => do\n    let nm' := mkIdent (Name.mkSimple \"w\")\n    let r \u2190 congDupOr i' nm' last\n    let r: Term := \u27e8r\u27e9\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\u2081: move expr that is equal to the pivot to position i + 1\n      let step\u2081 \u2190\n        if j > i + 1 then\n          let fname \u2190 mkIdent <$> mkFreshId\n          let e \u2190 getTypeFromName nm.getId\n          let t \u2190 instantiateMVars e\n          pullToMiddleCore (i + 1) j nm t fname\n          pure fname\n        else pure nm\n\n      -- step\u2082: apply congOrLeft i times with dupOr\n      let step\u2082: Ident \u2190 do\n        let last := i + 1 == n - 1\n        let tactic \u2190 congDupOr i step\u2081 last \n        let tactic := \u27e8tactic\u27e9\n        let fname \u2190 mkIdent <$> mkFreshId\n        evalTactic (\u2190 `(tactic| have $fname := $tactic))\n        pure fname\n\n      loop i j (n - 1) pivot es step\u2082\n    else loop i (j + 1) n pivot es nm\n\ndef factorCore (type : Expr) (source : Ident) (suffixIdx : Nat) : TacticM Unit :=\n  withMainContext do\n    let initialLength := getLength type\n    let mut li := collectPropsInOrChain' suffixIdx 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 \u2190 loop i (i + 1) (li.length + i) e es answer\n        let e \u2190 getTypeFromName answer.getId\n        let t \u2190 instantiateMVars e\n        let newLength := getLength t\n        let propsDropped := initialLength - newLength\n        li := collectPropsInOrChain' (suffixIdx - propsDropped) t\n    evalTactic (\u2190 `(tactic| exact $answer))\n\nsyntax (name := factor) \"factor\" term (\",\")? (term)? : tactic\n\ndef parseFactor : Syntax \u2192 TacticM (Option Nat)\n  | `(tactic| factor $_)     => pure none\n  | `(tactic| factor $_, $i) => elabTerm i none >>= pure \u2218 getNatLit?\n  | _                        => throwError \"[factor]: wrong usage\"\n\n@[tactic factor] def evalFactor : Tactic := fun stx => do\n  /- let startTime \u2190 IO.monoMsNow -/\n  withMainContext do\n    let e \u2190 elabTerm stx[1] none\n    let type \u2190 inferType e\n    let lastSuffix := getLength type - 1\n    let source := \u27e8stx[1]\u27e9\n    let sufIdx :=\n      match (\u2190 parseFactor stx) with\n      | none => lastSuffix\n      | some i => i\n    factorCore type source sufIdx\n  /- let endTime \u2190 IO.monoMsNow -/\n  /- logInfo m!\"[factor] Time taken: {endTime - startTime}ms\" -/\n\nexample : A \u2228 A \u2228 A \u2228 A \u2228 B \u2228 A \u2228 B \u2228 A \u2228 C \u2228 B \u2228 C \u2228 B \u2228 A \u2192 A \u2228 B \u2228 C :=\n  by intro h\n     factor h\n\nexample : (A \u2228 B \u2228 C) \u2228 (A \u2228 B \u2228 C) \u2192 A \u2228 B \u2228 C := by\n  intro h\n  factor h, 1\n\nexample : (A \u2228 B \u2228 C) \u2228 (E \u2228 F) \u2228 (A \u2228 B \u2228 C) \u2228 (E \u2228 F) \u2192 (A \u2228 B \u2228 C) \u2228 (E \u2228 F) := by\n  intro h\n  factor h, 3\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/Factor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.036220053524200053, "lm_q1q2_score": 0.011132523362349168}}
{"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.smt.congruence_closure\nimport Mathlib.Lean3Lib.init.meta.attribute\nimport Mathlib.Lean3Lib.init.meta.simp_tactic\nimport Mathlib.Lean3Lib.init.meta.interactive_base\nimport Mathlib.Lean3Lib.init.meta.derive\n\nuniverses l \n\nnamespace Mathlib\n\n/-- Heuristic instantiation lemma -/\n/-- `mk_core m e as_simp`, m is used to decide which definitions will be unfolded in patterns.\n   If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion\n   as a pattern. -/\n/--\nCreate a new \"cached\" attribute (attr_name : user_attribute hinst_lemmas).\nIt also creates \"cached\" attributes for each attr_names and simp_attr_names if they have not been defined\nyet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with\n    attr_name, attrs_name, and simp_attr_names.\nFor the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern.\n-/\nstructure ematch_config where\n  max_instances : \u2115\n  max_generation : \u2115\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/smt/ematch_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.033589507584945354, "lm_q1q2_score": 0.011122149005793138}}
{"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 \u27f6 Y \u27f6 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} {\u03c6\u2081 \u03c6\u2082 : f \u27f6 g} (h : \u03c6\u2081 = \u03c6\u2082) : \u03c6\u2081.left = \u03c6\u2082.left := by rw h\nlemma congr_right {f g : arrow C} {\u03c6\u2081 \u03c6\u2082 : f \u27f6 g} (h : \u03c6\u2081 = \u03c6\u2082) : \u03c6\u2081.right = \u03c6\u2082.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 (\ud835\udfd9 X) i = \ud835\udfd9 (X.X_prev i) :=\nbegin\n  rcases h : c.prev i with _ | \u27e8j,w\u27e9,\n  { rw homological_complex.prev_eq_zero' _ i h,\n    symmetry,\n    rw \u2190 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 (\ud835\udfd9 X) i = \ud835\udfd9 (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 \u27f6 Y) (g : Y \u27f6 Z)\n  (i : M) : hom.prev (f \u226b g) i = hom.prev f i \u226b hom.prev g i :=\nbegin\n  rcases h : c.prev i with _ | \u27e8j,w\u27e9,\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 \u27f6 Y) (g : Y \u27f6 Z)\n  (i : M) : hom.next (f \u226b g) i = hom.next f i \u226b 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 \u226b S.1.g = 0 := S.2\n\n@[simps]\ndef mk [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\n  short_complex C := \u27e8composable_morphisms.mk f g, zero\u27e9\n\n@[simp]\nlemma mk_id_\u03c4\u2081 [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\ncomposable_morphisms.hom.\u03c4\u2081 (\ud835\udfd9 (mk f g zero)) = \ud835\udfd9 X := rfl\n@[simp]\nlemma mk_id_\u03c4\u2082 [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\ncomposable_morphisms.hom.\u03c4\u2082 (\ud835\udfd9 (mk f g zero)) = \ud835\udfd9 Y := rfl\n@[simp]\nlemma mk_id_\u03c4\u2083 [has_zero_morphisms C] {X Y Z : C} (f : X \u27f6 Y) (g : Y \u27f6 Z) (zero : f \u226b g = 0) :\ncomposable_morphisms.hom.\u03c4\u2083 (\ud835\udfd9 (mk f g zero)) = \ud835\udfd9 Z := rfl\n\n@[simp]\nlemma comp_\u03c4\u2081 [has_zero_morphisms C] {S\u2081 S\u2082 S\u2083 : short_complex C} (f : S\u2081 \u27f6 S\u2082) (g : S\u2082 \u27f6 S\u2083) :\n  (f \u226b g).\u03c4\u2081 = f.\u03c4\u2081 \u226b g.\u03c4\u2081 := rfl\n@[simp]\nlemma comp_\u03c4\u2082 [has_zero_morphisms C] {S\u2081 S\u2082 S\u2083 : short_complex C} (f : S\u2081 \u27f6 S\u2082) (g : S\u2082 \u27f6 S\u2083) :\n  (f \u226b g).\u03c4\u2082 = f.\u03c4\u2082 \u226b g.\u03c4\u2082 := rfl\n@[simp]\nlemma comp_\u03c4\u2083 [has_zero_morphisms C] {S\u2081 S\u2082 S\u2083 : short_complex C} (f : S\u2081 \u27f6 S\u2082) (g : S\u2082 \u27f6 S\u2083) :\n  (f \u226b g).\u03c4\u2083 = f.\u03c4\u2083 \u226b g.\u03c4\u2083 := rfl\n\n@[simps]\ndef hom_mk [has_zero_morphisms C] {X\u2081 Y\u2081 Z\u2081 X\u2082 Y\u2082 Z\u2082 : C} {f\u2081 : X\u2081 \u27f6 Y\u2081} {g\u2081 : Y\u2081 \u27f6 Z\u2081}\n  {f\u2082 : X\u2082 \u27f6 Y\u2082} {g\u2082 : Y\u2082 \u27f6 Z\u2082} {zero\u2081 : f\u2081 \u226b g\u2081 = 0} {zero\u2082 : f\u2082 \u226b g\u2082 = 0}\n  (\u03c4\u2081 : X\u2081 \u27f6 X\u2082) (\u03c4\u2082 : Y\u2081 \u27f6 Y\u2082) (\u03c4\u2083 : Z\u2081 \u27f6 Z\u2082) (comm\u2081\u2082 : f\u2081 \u226b \u03c4\u2082 = \u03c4\u2081 \u226b f\u2082)\n  (comm\u2082\u2083 : g\u2081 \u226b \u03c4\u2083 = \u03c4\u2082 \u226b g\u2082) :\n  mk f\u2081 g\u2081 zero\u2081 \u27f6 mk f\u2082 g\u2082 zero\u2082 := \u27e8\u03c4\u2081, \u03c4\u2082, \u03c4\u2083, comm\u2081\u2082, comm\u2082\u2083\u27e9\n\n@[simps]\ndef iso_mk [has_zero_morphisms C] {S\u2081 S\u2082 : short_complex C}\n  (\u03c4\u2081 : S\u2081.1.X \u2245 S\u2082.1.X) (\u03c4\u2082 : S\u2081.1.Y \u2245 S\u2082.1.Y) (\u03c4\u2083 : S\u2081.1.Z \u2245 S\u2082.1.Z)\n  (comm\u2081\u2082 : S\u2081.1.f \u226b \u03c4\u2082.hom = \u03c4\u2081.hom \u226b S\u2082.1.f)\n  (comm\u2082\u2083 : S\u2081.1.g \u226b \u03c4\u2083.hom = \u03c4\u2082.hom \u226b S\u2082.1.g) :\n  S\u2081 \u2245 S\u2082 :=\n{ hom := \u27e8\u03c4\u2081.hom, \u03c4\u2082.hom, \u03c4\u2083.hom, comm\u2081\u2082, comm\u2082\u2083\u27e9,\n  inv := begin\n    refine \u27e8\u03c4\u2081.inv, \u03c4\u2082.inv, \u03c4\u2083.inv, _, _\u27e9,\n    { simp only [\u2190 cancel_mono \u03c4\u2082.hom, \u2190 cancel_epi \u03c4\u2081.hom,\n        assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm\u2081\u2082], },\n    { simp only [\u2190 cancel_mono \u03c4\u2083.hom, \u2190 cancel_epi \u03c4\u2082.hom,\n        assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm\u2082\u2083], },\n  end,\n  hom_inv_id' := begin\n    ext,\n    { simpa only [comp_\u03c4\u2081, hom_mk_\u03c4\u2081, iso.hom_inv_id], },\n    { simpa only [comp_\u03c4\u2082, hom_mk_\u03c4\u2082, iso.hom_inv_id], },\n    { simpa only [comp_\u03c4\u2083, hom_mk_\u03c4\u2083, iso.hom_inv_id], },\n  end,\n  inv_hom_id' := begin\n    ext,\n    { simpa only [iso.inv_hom_id, comp_\u03c4\u2081, hom_mk_\u03c4\u2081], },\n    { simpa only [iso.inv_hom_id, comp_\u03c4\u2082, hom_mk_\u03c4\u2082], },\n    { simpa only [iso.inv_hom_id, comp_\u03c4\u2083, hom_mk_\u03c4\u2083], },\n  end, }\n\nlemma is_iso_of_is_isos [has_zero_morphisms C] {S\u2081 S\u2082 : short_complex C}\n  (\u03c6 : S\u2081 \u27f6 S\u2082) (h\u2081 : is_iso \u03c6.\u03c4\u2081) (h\u2082 : is_iso \u03c6.\u03c4\u2082) (h\u2083 : is_iso \u03c6.\u03c4\u2083) : is_iso \u03c6 :=\nbegin\n  let e : S\u2081 \u2245 S\u2082 := iso_mk (as_iso \u03c6.\u03c4\u2081) (as_iso \u03c6.\u03c4\u2082) (as_iso \u03c6.\u03c4\u2083) \u03c6.comm\u2081\u2082 \u03c6.comm\u2082\u2083,\n  unfreezingI { rcases \u03c6 with \u27e8\u03c4\u2081, \u03c4\u2082, \u03c4\u2083, comm\u2081\u2082, comm\u2082\u2082\u27e9, },\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 \u2964 C :=\n{ obj := \u03bb X, X.homology,\n  map := \u03bb X Y \u03c6, homology.map X.2 Y.2 \u27e8\u03c6.\u03c4\u2081, \u03c6.\u03c4\u2082, \u03c6.comm\u2081\u2082.symm\u27e9\n    \u27e8\u03c6.\u03c4\u2082, \u03c6.\u03c4\u2083, \u03c6.comm\u2082\u2083.symm\u27e9 rfl,\n  map_id' := \u03bb X, by apply homology.map_id,\n  map_comp' := \u03bb X Y Z \u03c6 \u03c8, 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 \u2964 short_complex C :=\n{ obj := \u03bb X, mk (X.d_to i) (X.d_from i) (X.d_to_comp_d_from i),\n  map := \u03bb 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' := \u03bb X, begin\n    ext,\n    { exact X.prev_id i, },\n    { refl, },\n    { exact X.next_id i, },\n  end,\n  map_comp' := \u03bb 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 \u2245\n  functor_homological_complex C c i \u22d9 short_complex.homology_functor :=\nnat_iso.of_components (\u03bb X, iso.refl _)\n  (\u03bb 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 \u2964 D)\n  [F.preserves_zero_morphisms] :\n  short_complex C \u2964 short_complex D :=\nfull_subcategory.lift _ (induced_functor _ \u22d9 F.map_composable_morphisms)\n(\u03bb X, begin\n  have h := X.2,\n  dsimp [composable_morphisms.zero] at h \u22a2,\n  rw [\u2190 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 \u2964 D}\n  [F.preserves_zero_morphisms] [G.preserves_zero_morphisms] (\u03c6 : F \u27f6 G) :\n  F.map_short_complex \u27f6 G.map_short_complex :=\n{ app := \u03bb X, \u27e8\u03c6.app _, \u03c6.app _, \u03c6.app _, \u03c6.naturality _, \u03c6.naturality _\u27e9, }\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 \u2964 D) [F.additive]\n  {M : Type*} (c : complex_shape M) (i : M) :\nshort_complex.functor_homological_complex C c i \u22d9 F.map_short_complex \u2245\nF.map_homological_complex c \u22d9 short_complex.functor_homological_complex D c i :=\nnat_iso.of_components\n  (\u03bb 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  (\u03bb X Y f, begin\n    ext,\n    { simp only [functor.comp_map, comp_\u03c4\u2081, functor.map_short_complex_map_\u03c4\u2081,\n        functor_homological_complex_map_\u03c4\u2081, iso_mk_hom_\u03c4\u2081, F.map_prev], },\n    { dsimp, simp only [comp_id, id_comp], },\n    { simp only [functor.comp_map, comp_\u03c4\u2083, functor.map_short_complex_map_\u03c4\u2083,\n        functor_homological_complex_map_\u03c4\u2083, iso_mk_hom_\u03c4\u2083, 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 \u2964 D} [F.additive] [G.additive]\n  {M : Type*} (c : complex_shape M) (i : M) (\u03c6 : F \u27f6 G) (X : homological_complex C c) :\n  (nat_trans.map_short_complex \u03c6).app\n    ((short_complex.functor_homological_complex C c i).obj X) \u226b\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 \u226b\n    (short_complex.functor_homological_complex D c i).map\n      ((nat_trans.map_homological_complex \u03c6 c).app X) :=\nbegin\n  ext; dsimp [functor_homological_complex_map],\n  { apply \u03c6.map_prev, },\n  { simp only [comp_id, id_comp], },\n  { apply \u03c6.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, \u2026).\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 \u03bb-calculus or typed functional programming languages\n(ML, OCaml, Haskell).\n\nTypes `\u03c3`, `\u03c4`, `\u03c5`:\n\n* type variables `\u03b1`;\n* basic types `T`;\n* complex types `T \u03c31 \u2026 \u03c3N`.\n\nSome type constructors `T` are written infix, e.g., `\u2192` (function type).\n\nThe function arrow is right-associative:\n`\u03c3\u2081 \u2192 \u03c3\u2082 \u2192 \u03c3\u2083 \u2192 \u03c4` = `\u03c3\u2081 \u2192 (\u03c3\u2082 \u2192 (\u03c3\u2083 \u2192 \u03c4))`.\n\nPolymorphic types are also possible. In Lean, the type variables must be bound\nusing `\u2200`, e.g., `\u2200\u03b1, \u03b1 \u2192 \u03b1`.\n\nTerms `t`, `u`:\n\n* constants `c`;\n* variables `x`;\n* applications `t u`;\n* \u03bb-expressions `\u03bbx, 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 \u2115\n#check \u2124\n\n#check empty\n#check unit\n#check bool\n\n#check \u2115 \u2192 \u2124\n#check \u2124 \u2192 \u2115\n#check bool \u2192 \u2115 \u2192 \u2124\n#check (bool \u2192 \u2115) \u2192 \u2124\n#check \u2115 \u2192 (bool \u2192 \u2115) \u2192 \u2124\n\n#check \u03bbx : \u2115, x\n#check \u03bbf : \u2115 \u2192 \u2115, \u03bbg : \u2115 \u2192 \u2115, \u03bbh : \u2115 \u2192 \u2115, \u03bbx : \u2115, h (g (f x))\n#check \u03bb(f g h : \u2115 \u2192 \u2115) (x : \u2115), h (g (f x))\n\nconstants a b : \u2124\nconstant f : \u2124 \u2192 \u2124\nconstant g : \u2124 \u2192 \u2124 \u2192 \u2124\n\n#check \u03bbx : \u2124, g (f (g a x)) (g x b)\n#check \u03bbx, g (f (g a x)) (g x b)\n\n#check \u03bbx, 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 \u22a2 t : \u03c3`, meaning `t` has type `\u03c3` in local context `C`.\n\nTyping rules:\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Cst   if c is declared with type \u03c3\n    C \u22a2 c : \u03c3\n\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Var   if x : \u03c3 is the last occurrence of x in C\n    C \u22a2 x : \u03c3\n\n    C \u22a2 t : \u03c3 \u2192 \u03c4    C \u22a2 u : \u03c3\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 App\n    C \u22a2 t u : \u03c4\n\n    C, x : \u03c3 \u22a2 t : \u03c4\n    \u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014 Lam\n    C \u22a2 (\u03bbx : \u03c3, t) : \u03c3 \u2192 \u03c4\n\n\n### Type Inhabitation\n\nGiven a type `\u03c3`, the __type inhabitation__ problem consists of finding a term\nof that type. Type inhabitation is undecidable.\n\nRecursive procedure:\n\n1. If `\u03c3` is of the form `\u03c4 \u2192 \u03c5`, a candidate inhabitant is an anonymous\n   function of the form `\u03bbx, _`.\n\n2. Alternatively, you can use any constant or variable `x : \u03c4\u2081 \u2192 \u22ef \u2192 \u03c4N \u2192 \u03c3` to\n   build the term `x _ \u2026 _`. -/\n\nconstants \u03b1 \u03b2 \u03b3 : Type\n\ndef some_fun_of_type : (\u03b1 \u2192 \u03b2 \u2192 \u03b3) \u2192 ((\u03b2 \u2192 \u03b1) \u2192 \u03b2) \u2192 \u03b1 \u2192 \u03b3 :=\n\u03bbf g a, f a (g (\u03bbb, 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` (= `\u2115`) of natural numbers, using Peano-style unary\nnotation: -/\n\ninductive nat : Type\n| zero : nat\n| succ : nat \u2192 nat\n\n#check nat\n#check nat.zero\n#check nat.succ\n\nend my_nat\n\n#print nat\n#print \u2115\n\n\n/-! ### Arithmetic Expressions -/\n\ninductive aexp : Type\n| num : \u2124 \u2192 aexp\n| var : string \u2192 aexp\n| add : aexp \u2192 aexp \u2192 aexp\n| sub : aexp \u2192 aexp \u2192 aexp\n| mul : aexp \u2192 aexp \u2192 aexp\n| div : aexp \u2192 aexp \u2192 aexp\n\n\n/-! ### Lists -/\n\nnamespace my_list\n\ninductive list (\u03b1 : Type) : Type\n| nil  : list\n| cons : \u03b1 \u2192 list \u2192 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 : \u2115 \u2192 \u2115 \u2192 \u2115\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 : \u2115 \u2192 \u2115 \u2192 \u2115\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 : \u2115 \u2192 \u2115 \u2192 \u2115\n| _ nat.zero     := 1\n| m (nat.succ n) := mul m (power m n)\n\n#eval power 2 5\n\ndef power\u2082 (m : \u2115) : \u2115 \u2192 \u2115\n| nat.zero     := 1\n| (nat.succ n) := mul m (power\u2082 n)\n\n#eval power\u2082 2 5\n\ndef iter (\u03b1 : Type) (z : \u03b1) (f : \u03b1 \u2192 \u03b1) : \u2115 \u2192 \u03b1\n| nat.zero     := z\n| (nat.succ n) := f (iter n)\n\n#check iter\n\ndef power\u2083 (m n : \u2115) : \u2115 :=\niter \u2115 1 (\u03bbl, mul m l) n\n\n#eval power\u2083 2 5\n\ndef append (\u03b1 : Type) : list \u03b1 \u2192 list \u03b1 \u2192 list \u03b1\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\u2082 {\u03b1 : Type} : list \u03b1 \u2192 list \u03b1 \u2192 list \u03b1\n| list.nil         ys := ys\n| (list.cons x xs) ys := list.cons x (append\u2082 xs ys)\n\n#check append\u2082\n#eval append\u2082 [3, 1] [4, 1, 5]\n\n#check @append\u2082\n#eval @append\u2082 _ [3, 1] [4, 1, 5]\n\n/-! Aliases:\n\n    `[]`          := `nil`\n    `x :: xs`     := `cons x xs`\n    `[x\u2081, \u2026, xN]` := `x\u2081 :: \u2026 :: xN :: []` -/\n\ndef append\u2083 {\u03b1 : Type} : list \u03b1 \u2192 list \u03b1 \u2192 list \u03b1\n| []        ys := ys\n| (x :: xs) ys := x :: append\u2083 xs ys\n\ndef reverse {\u03b1 : Type} : list \u03b1 \u2192 list \u03b1\n| []        := []\n| (x :: xs) := reverse xs ++ [x]\n\ndef eval (env : string \u2192 \u2124) : aexp \u2192 \u2124\n| (aexp.num i)     := i\n| (aexp.var x)     := env x\n| (aexp.add e\u2081 e\u2082) := eval e\u2081 + eval e\u2082\n| (aexp.sub e\u2081 e\u2082) := eval e\u2081 - eval e\u2082\n| (aexp.mul e\u2081 e\u2082) := eval e\u2081 * eval e\u2082\n| (aexp.div e\u2081 e\u2082) := eval e\u2081 / eval e\u2082\n\n#eval eval (\u03bbs, 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 : \u2115) :\n  add m n = add n m :=\nsorry\n\nlemma add_assoc (l m n : \u2115) :\n  add (add l m) n = add l (add m n) :=\nsorry\n\nlemma mul_comm (m n : \u2115) :\n  mul m n = mul n m :=\nsorry\n\nlemma mul_assoc (l m n : \u2115) :\n  mul (mul l m) n = mul l (mul m n) :=\nsorry\n\nlemma mul_add (l m n : \u2115) :\n  mul l (add m n) = add (mul l m) (mul l n) :=\nsorry\n\nlemma reverse_reverse {\u03b1 : Type} (xs : list \u03b1) :\n  reverse (reverse xs) = xs :=\nsorry\n\n/-! Axioms are like lemmas but without proofs (`:= \u2026`). Constant declarations\nare like definitions but without bodies (`:= \u2026`). -/\n\nconstants a b : \u2124\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": "import Lean\nimport LeanCodePrompts.Translate\n\nopen Lean Server Lsp RequestM\n\npartial def String.Iterator.findFirst? : String.Iterator \u2192 String \u2192 Option String.Pos\n  | i, pre => if i.hasNext then\n    if i.remainingToString.startsWith pre then \n      some i.pos \n    else \n      i.next.findFirst? pre\n  else none\n\ndef String.Range.expand : String.Range \u2192 Nat \u2192 String.Range\n  | \u27e8start, stop\u27e9, i => \u27e8start - \u27e8i\u27e9, stop + \u27e8i\u27e9\u27e9\n\n/-- Finds the comment or doc-string in the source nearest to the given position. -/\npartial def nearestComment? (source : String) \n  (pos : String.Pos) (start : String.Pos := \u27e80\u27e9) : Option String.Range := do\n    guard $ start \u2264 pos\n    let firstCommentRange \u2190 findFirstComment? source start\n    if (firstCommentRange.expand 2).contains pos then\n      some firstCommentRange\n    else\n      nearestComment? source pos (source.next firstCommentRange.stop)\n  where findFirstComment? (source : String) (init : String.Pos) : Option String.Range := do\n    let start \u2190 (String.Iterator.mk source init).findFirst? \"/-\"\n    let stop \u2190 (String.Iterator.mk source start).findFirst? \"-/\"\n    return \u27e8start, stop + \u27e82\u27e9\u27e9\n\n/-- Extracts the text contained in a comment. -/\ndef extractCommentText (comment : String) : Option String := do\n  guard $ comment.startsWith \"/-\"\n  guard $ comment.endsWith \"-/\"\n  let text := comment |>.drop 2 |>.dropRight 2\n  let c := text.front\n  if c.isAlphanum || c.isWhitespace then\n    return text\n  else\n    return text.drop 1\n\n/-\nopen Parser.Command in\ndef Syntax.extractComment : Syntax \u2192 Option String\n  | `($doc:docComment ) => getDocStringText doc\n  | _ => none\n\n#check getDocStringText\n-/\n\n/-- A code action for translating doc-strings to Lean code using OpenAI Codex -/\n@[codeActionProvider] def formaliseDocStr : CodeActionProvider := fun params snap => do\n  let doc \u2190 readDoc\n  let text := doc.meta.text\n  let source := text.source\n\n  -- the current position in the text document\n  let lspPos : Lsp.Position := params.range.end\n  -- The position from which to start searching for a comment (by default, five lines above the given position)\n  let lspBeginPos : Lsp.Position := \u27e8lspPos.line - 5, 0\u27e9\n  let pos : String.Pos := text.lspPosToUtf8Pos lspPos\n  let beginPos : String.Pos := text.lspPosToUtf8Pos lspBeginPos\n  let comment? := nearestComment? source pos beginPos\n\n  let edit : IO TextEdit := do\n    let some \u27e8start, stop\u27e9 := comment? | throw $ IO.userError \"No input found.\"\n    return {\n    range := \u27e8text.leanPosToLspPos <| text.toPosition start, text.leanPosToLspPos <| text.toPosition stop\u27e9\n    newText := \u2190 do\n      -- the smallest node of the `InfoTree` containing the current position\n      let info? := snap.infoTree.findInfo? (\u00b7.contains pos)\n      -- the `Syntax` corresponding to the `Info` node\n      let stx? := (\u00b7.stx) <$> info?\n\n      -- the statement to be translated to Lean code\n      let stmt? : Option String := \n        (none /- TODO: First attempt to parse using `Syntax` -/)  <|>\n        ( /- Parse as a string -/\n          let comment := source.extract start stop\n          extractCommentText comment\n        )\n\n      let translation' := snap.runTermElabM doc.meta <| translateViewM stmt?.get!\n      let translation \u2190 EIO.toIO (\u03bb _ => IO.userError \"Translation failed.\") translation'\n      return formatAsTheorem stmt? translation\n  }\n\n  let ca : CodeAction := { \n    title := \"Translate theorem docstring to Lean code\", \n    kind? := \"quickfix\", \n    disabled? := \n      match comment? with\n        | .some _ => none\n        | .none => some \u27e8\"No nearby comments available.\"\u27e9 }\n  return #[{ eager := ca, lazy? := some $ return {ca with edit? := WorkspaceEdit.ofTextEdit params.textDocument.uri $ \u2190 edit} }]\nwhere\n  formatAsTheorem : Option String \u2192 String \u2192 String\n    | some comment, type => s!\"/-{comment}-/\\nexample : {type.trim} := by sorry\"\n    |     none    , type => s!\"\\nexample : {type.trim} := by sorry\"\n\n-- @[codeActionProvider] def informaliseThm : CodeActionProvider := fun params snap => do\n--   let doc \u2190 readDoc\n--   let text := doc.meta.text\n--   let source := text.source\n\n--   let edit : IO TextEdit := do\n--     -- the current position in the text document\n--     let pos : String.Pos := text.lspPosToUtf8Pos params.range.end\n--     return {\n--     range := params.range\n--     newText := \u2190 do\n--       -- the smallest node of the `InfoTree` containing the current position\n--       let info? := snap.infoTree.findInfo? (\u00b7.contains pos)\n--       -- the `Syntax` corresponding to the `Info` node\n--       let stx? := (\u00b7.stx) <$> info?\n\n--       -- the statement to be translated to Lean code\n--       let thm? : Option String := stx? >>= Syntax.reprint\n\n--       let translation' := snap.runTermElabM doc.meta <| statementToDoc thm?.get!\n--       let translation \u2190 EIO.toIO (\u03bb _ => IO.userError \"Translation failed.\") translation'\n--       return \"/--\" ++ translation ++ \"-/\\n\"\n--   }\n\n--   let ca : CodeAction := { title := \"Add a docstring to a Lean theorem\", kind? := \"quickfix\" }\n--   return #[{ eager := ca, lazy? := some $ return {ca with edit? := WorkspaceEdit.ofTextEdit params.textDocument.uri $ \u2190 edit} }]\n\n-- open RequestM in\n-- @[codeActionProvider]\n-- def readFile : CodeActionProvider := fun params _snap => do\n--   let doc \u2190 readDoc\n--   let text := doc.meta.text\n--   let source := text.source\n--   let pos := text.lspPosToUtf8Pos params.range.end\n--   let edit : TextEdit := {\n--     range := params.range\n--     newText :=\n--       let tail := Substring.mk source pos source.endPos\n--       let tail := tail.toString.splitOn \"/-\" |>.head!\n--       \"/- \" ++ tail ++ \"-/\"\n--   }\n--   let ca : CodeAction := {title := \"tail of source\", kind? := \"quickfix\"}\n--   return #[{eager := ca, lazy? := some $ return { ca with edit? := WorkspaceEdit.ofTextEdit params.textDocument.uri edit}}]\n  \n/- \n\nexample : 1 = 1 := by\n  simp\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/CodeAction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.02931223234129297, "lm_q1q2_score": 0.011066559802098377}}
{"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 \u2192 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 \u2192 assert_with_vars \u2192 assert_with_vars\n | s_exists : expr \u2192 assert_with_vars \u2192 assert_with_vars\n | leaf : expr \u2192 assert_with_vars\n | prop : expr \u2192 assert_with_vars\nopen predicate\nmeta def parse_assert_with_vars : expr \u2192 tactic assert_with_vars\n | `(s_and %%e\u2080 %%e\u2081) := assert_with_vars.s_and <$> parse_assert_with_vars e\u2080\n                                                <*> parse_assert_with_vars e\u2081\n | `(p_exists %%e) :=\n   do `(\u03bb _ : %%t, %%e') \u2190 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 \u2192 pexpr\n | (assert_with_vars.leaf e) := to_pexpr e\n | (assert_with_vars.prop e) :=  ``([| %%e |])\n | (assert_with_vars.s_and e\u2080 e\u2081) := ``(%%(e\u2080.to_expr) :*: %%(e\u2081.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 \u2192 assert_with_vars \u2192 tactic (assert_with_vars \u00d7 expr)\n | vs (assert_with_vars.s_and e\u2080 e\u2081) :=\n   do (x\u2080,p\u2080) \u2190 hexists_to_meta_var vs e\u2080,\n      (x\u2081,p\u2081) \u2190 hexists_to_meta_var vs e\u2081,\n      let x := assert_with_vars.s_and x\u2080 x\u2081,\n      prod.mk x <$> to_expr ``(s_and_s_imp_s_and %%p\u2080 %%p\u2081)\n | vs (assert_with_vars.s_exists t e) :=\n   do v \u2190 mk_meta_var t,\n      (x,p) \u2190 hexists_to_meta_var (v :: vs) e,\n      let x := assert_with_vars.s_exists t x,\n      q \u2190 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 \u2190 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) \u2190 mk_simp_set tt [] rules,\n      (e'',p) \u2190 conv.convert (conv.interactive.simp tt rules []\n        { fail_if_unchanged := ff }) e',\n      ast \u2190 parse_assert_with_vars e'' ,\n      (assert_with_vars.leaf _) \u2190 pure ast | (do\n        (x,p') \u2190 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 \u2192 tactic (dlist expr)\n | `(%%e\u2080 :*: %%e\u2081) := (++) <$> parse_sep_assert' e\u2080 <*> parse_sep_assert' e\u2081\n | e := return $ dlist.singleton e\n\nmeta def parse_sep_assert : expr \u2192 tactic (list expr) :=\nmap dlist.to_list \u2218 parse_sep_assert'\n\nmeta def match_sep' (unif : bool)\n: list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 list expr)\n | es (x :: xs) := do\n    es' \u2190 delete_expr { unify := unif } x es,\n    match es' with\n     | (some es') := do\n       (c,l,r) \u2190 match_sep' es' xs, return (x::c,l,r)\n     | none := do\n       (c,l,r) \u2190 match_sep' es xs, return (c,l,x::r)\n    end\n | es [] := do\nreturn ([],es,[])\n\n/--\n`(common,left,right) \u2190 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 \u00d7 list expr \u00d7 list expr) :=\ndo (s',l',r') \u2190 match_sep' unif l r,\n   s' \u2190 mmap instantiate_mvars s',\n   l' \u2190 mmap instantiate_mvars l',\n   r' \u2190 mmap instantiate_mvars r',\n   return (s',l',r')\n\ndef expr_pat (t\u2080 t\u2081 : Type) : \u2115 \u2192 Type\n | 0 := t\u2081\n | (succ n) := t\u2080 \u2192 expr_pat n\n\ndef tuple : \u2115 \u2192 Type \u2192 Type\n | 0 _ := unit\n | 1 t := t\n | (succ n) t := t \u00d7 tuple n t\n\nmeta def match_expr : \u2200 (n : \u2115) (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 \u2190 mk_mvar, match_expr 0 (p v) e, instantiate_mvars v\n  | (succ (succ n)) p e := do\nv \u2190 mk_mvar,\nr \u2190 match_expr (succ n) (p v) e,\ne \u2190 instantiate_mvars v,\nreturn (e,r)\n\nmeta def reshuffle (e\u2080 e\u2081 : expr) : tactic unit := do\nt \u2190 target,\n(t\u2080,t\u2081) \u2190 match_eq t,\nh\u2080 \u2190 to_expr ``(%%t\u2080 = %%e\u2080) >>= assert `h\u2080,\nsolve1 ac_refl,\nh\u2081 \u2190 to_expr ``(%%t\u2081 = %%e\u2081) >>= assert `h\u2081,\nsolve1 admit,\n`[rw h\u2080],\n`[rw h\u2081],\ntactic.clear h\u2080, tactic.clear h\u2081\n\nmeta def find_match (pat : expr) : expr \u2192 list expr \u2192 tactic expr\n | e rest := do\n(unify e pat >> return (mk_sep_assert rest))\n<|>\n(do hprop \u2190 to_expr ``(hprop),\n    lv \u2190 mk_meta_var hprop,\n    rv \u2190 mk_meta_var hprop,\n    to_expr ``(%%lv :*: %%rv) >>= unify e,\n      -- this unification could be generalized to:\n      -- (le,re) \u2190 match_pat (\u03bb p\u2080 p\u2081, ``(%%p\u2080 :*: %%p\u2081))\n    le \u2190 instantiate_mvars lv,\n    re \u2190 instantiate_mvars rv,\n    (find_match le (re :: rest) <|> find_match re (le :: rest)))\n<|>\ndo p \u2190 pp pat,\n   e \u2190 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 \u00d7 expr \u00d7 expr) := do\ng \u2190 target,\nt  \u2190 to_expr ``(hprop),\ne\u2080 \u2190 mk_meta_var t,\ne\u2082 \u2190 mk_meta_var t,\ne\u2083 \u2190 mk_meta_var t,\npat \u2190 to_expr ``(%%e\u2080 = %%e\u2082 :*: %%e\u2083) >>= unify g,\nprod.mk <$> instantiate_mvars e\u2080\n        <*> (prod.mk <$> instantiate_mvars e\u2082\n                     <*> instantiate_mvars e\u2083)\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) \u2190 sep_goal,\ne \u2190 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 \u2190 mk_meta_var `(Prop),\n     (hp,pat,var) \u2190 sep_goal,\n     to_expr ``( [| _ |] ) >>= unify pat,\n     e \u2190 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 \u2190 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* \u2192 \u2200 (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 \u2192 tactic (expr \u00d7 expr)\n | `(%%e\u2080 =*> %%e\u2081) := return (e\u2080, e\u2081)\n | _ := fail \"expression is not an sep implication\"\n\nmeta def intro_unit (v : parse ident_?) : tactic unit :=\ndo e \u2190 match v with\n       | none := intro1\n       | (some v) := tactic.intro v\n       end,\n   t \u2190 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 \u2190 attribute.get_instances `ptr_abstraction,\n   abs' \u2190 mmap (map simp_arg_type.expr \u2218 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 \u2190 attribute.get_instances `ptr_abstraction\n           >>= mmap (map simp_arg_type.expr \u2218 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 \u2190 target,\n       (e\u2080,e\u2081) \u2190 match_eq t,\n       e\u2080 \u2190 parse_sep_assert e\u2080,\n       e\u2081 \u2190 parse_sep_assert e\u2081,\n       (c,l,r) \u2190 match_sep ff e\u2080 e\u2081,\n       (c',l',r') \u2190 match_sep tt l r,\n       (c'',l',r') \u2190 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 \u2190 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\u2081 e\u2082 e\u2083 : hprop)\n: e\u2081 :*: e\u2082 :*: e\u2083 = e\u2082 :*: e\u2083 :*: e\u2081 :=\nbegin\n  ac_mono1,\n  exact @rfl _ emp\nend\n\ndef replicate {m : Type u \u2192 Type v} [monad m] {\u03b1} : \u2115 \u2192 m \u03b1 \u2192 m (list \u03b1)\n | 0 _ := return []\n | (succ n) m := lift\u2082 cons m (replicate n m)\n\nprivate meta def get_pi_expl_arity_aux (t : expr) : expr \u2192 expr \u2192 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 \u2190 mk_fresh_name,\n--     let l := expr.local_const m n bi d,\n     l \u2190 mk_meta_var d,\n     new_b \u2190 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 \u2190 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* \u2192 parse subst_flag \u2192 tactic unit\n | [] _ := return ()\n | (x :: xs) sbst := do\nv \u2190 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 \u2190 target,\n   (hd,tl,spec) \u2190 (match_expr 3 (\u03bb e\u2080 e\u2081 s, ``(sat (%%e\u2080 >>= %%e\u2081) %%s)) g\n                : tactic (expr \u00d7 expr \u00d7 expr)),\n   let (cmd,args) := hd.get_app_fn_args,\n   let s : option _ := spec_thm,\n   e \u2190 (resolve_name (cmd.const_name <.> \"spec\") >>= to_expr) <| (to_expr <$> s),\n   r \u2190 to_expr ``(sat _ _),\n   e' \u2190 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) \u2190 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) \u2190 target,\n   r \u2190 parse_assert_with_vars q,\n   abs \u2190 attribute.get_instances `ptr_abstraction,\n   abs' \u2190 mmap (map (simp_arg_type.expr \u2218 to_pexpr) \u2218 resolve_name) abs,\n   (_,p) \u2190 hexists_to_meta_var abs' [] r,\n   h \u2190 mk_meta_var `(hprop),\n   g \u2190 mk_mvar,\n   p' \u2190 to_expr ``(s_imp_trans %%h %%g %%p),\n   t \u2190 target,\n   infer_type p' >>= unify t,\n   gs \u2190 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) \u2190 target,\n   let (cmd,args) := hd.get_app_fn_args,\n   e \u2190 (resolve_name (cmd.const_name <.> \"spec\") >>= to_expr) <| (to_expr <$> s),\n   r \u2190 to_expr ``(sat _ _),\n   e' \u2190 get_pi_expl_arity r e,\n   p\u2080 \u2190 mk_mvar,\n   p\u2081 \u2190 mk_mvar,\n   r \u2190 to_expr ``(framing_spec' _ %%e' %%p\u2080 %%p\u2081),\n   t \u2190 target,\n   infer_type r >>= unify t,\n   gs \u2190 get_goals,\n   set_goals [p\u2080],\n   simp_h_entails,\n   all_goals (try $ `[apply of_as_true, apply trivial] <|> solve_by_elim),\n   done,\n   set_goals [p\u2081],\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) \u2190 target | failed,\n--    ls \u2190 parse_sep_assert lhs,\n--    rs \u2190 parse_sep_assert rhs,\n--    (s,l,r) \u2190 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   \u2190 to_expr ``(%%(mk_sep_assert l) =*> %%(mk_sep_assert r))\n--       >>= assert `h,\n--    tactic.swap,\n--    prf \u2190 to_expr ``(s_and_s_imp_s_and_right %%(mk_sep_assert s) %%h),\n--    note `h none prf,\n--    return ()\n\nexample (e\u2081 e\u2082 e\u2083 e\u2084 e\u2085 e\u2086 : hprop)\n  (h : e\u2083 :*: e\u2081 :*: e\u2085 :*: e\u2084 =*> e\u2086)\n: e\u2083 :*: e\u2081 :*: e\u2085 :*: e\u2082 :*: e\u2084 =*> e\u2082 :*: e\u2086 :=\nbegin\n  ac_mono1,\n  solve_by_elim\nend\n\nexample (e\u2081 e\u2082 e\u2083 e\u2084 e\u2085 e\u2086 : hprop)\n  (h : e\u2081 :*: e\u2085 :*: e\u2084 =*> emp)\n: e\u2083 :*: e\u2081 :*: e\u2085 :*: e\u2082 :*: e\u2084 =*> e\u2082 :*: e\u2083 :=\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\u2080 u\u2081 v\u2080 v\u2081 \n\nnamespace Mathlib\n\nstructure writer_t (\u03c9 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) where\n  run : m (\u03b1 \u00d7 \u03c9)\n\ndef writer (\u03c9 : Type u) (\u03b1 : Type u) := writer_t \u03c9 id\n\nnamespace writer_t\n\n\nprotected theorem ext {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} (x : writer_t \u03c9 m \u03b1)\n    (x' : writer_t \u03c9 m \u03b1) (h : run x = run x') : x = x' :=\n  sorry\n\nprotected def tell {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] (w : \u03c9) : writer_t \u03c9 m PUnit :=\n  mk (pure (PUnit.unit, w))\n\nprotected def listen {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} :\n    writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m (\u03b1 \u00d7 \u03c9) :=\n  sorry\n\nprotected def pass {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} :\n    writer_t \u03c9 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 writer_t \u03c9 m \u03b1 :=\n  sorry\n\nprotected def pure {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} [HasOne \u03c9] (a : \u03b1) :\n    writer_t \u03c9 m \u03b1 :=\n  mk (pure (a, 1))\n\nprotected def bind {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} {\u03b2 : Type u} [Mul \u03c9]\n    (x : writer_t \u03c9 m \u03b1) (f : \u03b1 \u2192 writer_t \u03c9 m \u03b2) : writer_t \u03c9 m \u03b2 :=\n  mk\n    (do \n      let x \u2190 run x \n      let x' \u2190 run (f (prod.fst x))\n      pure (prod.fst x', prod.snd x * prod.snd x'))\n\nprotected instance monad {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] [HasOne \u03c9] [Mul \u03c9] :\n    Monad (writer_t \u03c9 m) :=\n  sorry\n\nprotected instance is_lawful_monad {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] [monoid \u03c9]\n    [is_lawful_monad m] : is_lawful_monad (writer_t \u03c9 m) :=\n  sorry\n\nprotected def lift {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type u} [HasOne \u03c9] (a : m \u03b1) :\n    writer_t \u03c9 m \u03b1 :=\n  mk (flip Prod.mk 1 <$> a)\n\nprotected instance has_monad_lift {\u03c9 : Type u} (m : Type u \u2192 Type u_1) [Monad m] [HasOne \u03c9] :\n    has_monad_lift m (writer_t \u03c9 m) :=\n  has_monad_lift.mk fun (\u03b1 : Type u) => writer_t.lift\n\nprotected def monad_map {\u03c9 : Type u} {m : Type u \u2192 Type u_1} {m' : Type u \u2192 Type u_2} [Monad m]\n    [Monad m'] {\u03b1 : Type u} (f : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9 m' \u03b1 :=\n  fun (x : writer_t \u03c9 m \u03b1) => mk (f (run x))\n\nprotected instance monad_functor {\u03c9 : Type u} (m : Type u \u2192 Type u_1) (m' : Type u \u2192 Type u_1)\n    [Monad m] [Monad m'] : monad_functor m m' (writer_t \u03c9 m) (writer_t \u03c9 m') :=\n  monad_functor.mk writer_t.monad_map\n\nprotected def adapt {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] {\u03c9' : Type u} {\u03b1 : Type u}\n    (f : \u03c9 \u2192 \u03c9') : writer_t \u03c9 m \u03b1 \u2192 writer_t \u03c9' m \u03b1 :=\n  fun (x : writer_t \u03c9 m \u03b1) => mk (prod.map id f <$> run x)\n\nprotected instance monad_except {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m]\n    (\u03b5 : outParam (Type u_1)) [HasOne \u03c9] [Monad m] [monad_except \u03b5 m] :\n    monad_except \u03b5 (writer_t \u03c9 m) :=\n  monad_except.mk (fun (\u03b1 : Type u) => writer_t.lift \u2218 throw)\n    fun (\u03b1 : Type u) (x : writer_t \u03c9 m \u03b1) (c : \u03b5 \u2192 writer_t \u03c9 m \u03b1) =>\n      mk (catch (run x) fun (e : \u03b5) => 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 (\u03c1 : out_param (Type u)) (n : Type u \u2192 Type u) :=\n(lift {\u03b1 : Type u} : (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1) \u2192 n \u03b1)\n```\n-/\nclass monad_writer (\u03c9 : outParam (Type u)) (m : Type u \u2192 Type v) where\n  tell : \u03c9 \u2192 m PUnit\n  listen : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 m (\u03b1 \u00d7 \u03c9)\n  pass : {\u03b1 : Type u} \u2192 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 m \u03b1\n\nprotected instance writer_t.monad_writer {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m] :\n    monad_writer \u03c9 (writer_t \u03c9 m) :=\n  monad_writer.mk writer_t.tell (fun (\u03b1 : Type u) => writer_t.listen)\n    fun (\u03b1 : Type u) => writer_t.pass\n\nprotected instance reader_t.monad_writer {\u03c9 : Type u} {\u03c1 : Type u} {m : Type u \u2192 Type v} [Monad m]\n    [monad_writer \u03c9 m] : monad_writer \u03c9 (reader_t \u03c1 m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x))\n    (fun (\u03b1 : Type u) (_x : reader_t \u03c1 m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : reader_t \u03c1 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => sorry\n\ndef swap_right {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} : (\u03b1 \u00d7 \u03b2) \u00d7 \u03b3 \u2192 (\u03b1 \u00d7 \u03b3) \u00d7 \u03b2 := sorry\n\nprotected instance state_t.monad_writer {\u03c9 : Type u} {\u03c3 : Type u} {m : Type u \u2192 Type v} [Monad m]\n    [monad_writer \u03c9 m] : monad_writer \u03c9 (state_t \u03c3 m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x))\n    (fun (\u03b1 : Type u) (_x : state_t \u03c3 m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : state_t \u03c3 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => sorry\n\ndef except_t.pass_aux {\u03b5 : Type u_1} {\u03b1 : Type u_2} {\u03c9 : Type u_3} :\n    except \u03b5 (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 except \u03b5 \u03b1 \u00d7 (\u03c9 \u2192 \u03c9) :=\n  sorry\n\nprotected instance except_t.monad_writer {\u03c9 : Type u} {\u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m]\n    [monad_writer \u03c9 m] : monad_writer \u03c9 (except_t \u03b5 m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x))\n    (fun (\u03b1 : Type u) (_x : except_t \u03b5 m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : except_t \u03b5 m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => sorry\n\ndef option_t.pass_aux {\u03b1 : Type u_1} {\u03c9 : Type u_2} : Option (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9)) \u2192 Option \u03b1 \u00d7 (\u03c9 \u2192 \u03c9) :=\n  sorry\n\nprotected instance option_t.monad_writer {\u03c9 : Type u} {m : Type u \u2192 Type v} [Monad m]\n    [monad_writer \u03c9 m] : monad_writer \u03c9 (option_t m) :=\n  monad_writer.mk (fun (x : \u03c9) => monad_lift (monad_writer.tell x))\n    (fun (\u03b1 : Type u) (_x : option_t m \u03b1) => sorry)\n    fun (\u03b1 : Type u) (_x : option_t m (\u03b1 \u00d7 (\u03c9 \u2192 \u03c9))) => 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 (\u03c1 \u03c1' : out_param (Type u)) (n n' : Type u \u2192 Type u) :=\n(map {\u03b1 : Type u} : (\u2200 {m : Type u \u2192 Type u} [monad m], reader_t \u03c1 m \u03b1 \u2192 reader_t \u03c1' m \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1)\n```\n-/\nclass monad_writer_adapter (\u03c9 : outParam (Type u)) (\u03c9' : outParam (Type u)) (m : Type u \u2192 Type v)\n    (m' : Type u \u2192 Type v)\n    where\n  adapt_writer : {\u03b1 : Type u} \u2192 (\u03c9 \u2192 \u03c9') \u2192 m \u03b1 \u2192 m' \u03b1\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 {\u03c9 : Type u} {\u03c9' : Type u} {m : Type u \u2192 Type v}\n    {m' : Type u \u2192 Type v} {n : Type u \u2192 Type v} {n' : Type u \u2192 Type v}\n    [monad_writer_adapter \u03c9 \u03c9' m m'] [monad_functor m m' n n'] : monad_writer_adapter \u03c9 \u03c9' n n' :=\n  monad_writer_adapter.mk\n    fun (\u03b1 : Type u) (f : \u03c9 \u2192 \u03c9') => monad_map fun (\u03b1 : Type u) => adapt_writer f\n\nprotected instance writer_t.monad_writer_adapter {\u03c9 : Type u} {\u03c9' : Type u} {m : Type u \u2192 Type v}\n    [Monad m] : monad_writer_adapter \u03c9 \u03c9' (writer_t \u03c9 m) (writer_t \u03c9' m) :=\n  monad_writer_adapter.mk fun (\u03b1 : Type u) => writer_t.adapt\n\nprotected instance writer_t.monad_run (\u03c9 : Type u) (m : Type u \u2192 Type (max u u_1))\n    (out : outParam (Type u \u2192 Type (max u u_1))) [monad_run out m] :\n    monad_run (fun (\u03b1 : Type u) => out (\u03b1 \u00d7 \u03c9)) (writer_t \u03c9 m) :=\n  monad_run.mk fun (\u03b1 : Type u) (x : writer_t \u03c9 m \u03b1) => 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081} {\u03b1\u2081 : Type u\u2080} {\u03c9\u2081 : Type u\u2080}\n    {\u03b1\u2082 : Type u\u2081} {\u03c9\u2082 : Type u\u2081} (F : m\u2081 (\u03b1\u2081 \u00d7 \u03c9\u2081) \u2243 m\u2082 (\u03b1\u2082 \u00d7 \u03c9\u2082)) :\n    writer_t \u03c9\u2081 m\u2081 \u03b1\u2081 \u2243 writer_t \u03c9\u2082 m\u2082 \u03b1\u2082 :=\n  equiv.mk (fun (_x : writer_t \u03c9\u2081 m\u2081 \u03b1\u2081) => sorry) (fun (_x : writer_t \u03c9\u2082 m\u2082 \u03b1\u2082) => 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   => \"<unknown>\"\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\u2081 e\u2082 := e\u2081.proof == e\u2082.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 \u2192 Expr \u2192 MetaM Bool\n  | Expr.app f\u2081 a\u2081 _, Expr.app f\u2082 a\u2082 _ => isPerm f\u2081 f\u2082 <&&> isPerm a\u2081 a\u2082\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\u2081 d\u2081 b\u2081 _, Expr.forallE n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.lam n\u2081 d\u2081 b\u2081 _, Expr.lam n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.letE n\u2081 t\u2081 v\u2081 b\u2081 _, Expr.letE n\u2082 t\u2082 v\u2082 b\u2082 _ =>\n    isPerm t\u2081 t\u2082 <&&> isPerm v\u2081 v\u2082 <&&> withLetDecl n\u2081 t\u2081 v\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.proj _ i\u2081 b\u2081 _, Expr.proj _ i\u2082 b\u2082 _ => pure (i\u2081 == i\u2082) <&&> isPerm b\u2081 b\u2082\n  | s, t => return s == t\n\nprivate def checkBadRewrite (lhs rhs : Expr) : MetaM Unit := do\n  let lhs \u2190 DiscrTree.whnfDT lhs (root := true)\n  if lhs == rhs && lhs.isFVar then\n    throwError \"invalid `simp` theorem, equation is equivalent to{indentExpr (\u2190 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 \u00d7 Expr)) :=\n  go e type\nwhere\n  go (e type : Expr) : MetaM (List (Expr \u00d7 Expr)) := do\n  let type \u2190 whnf type\n  if type.isForall then\n    forallTelescopeReducing type fun xs type => do\n      let e := mkAppN e xs\n      let ps \u2190 go e type\n      ps.mapM fun (e, type) =>\n        return (\u2190 mkLambdaFVars xs e, \u2190 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 \u2190 mkEq rhs lhs\n      let e    \u2190 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 \u2190 mkEq rhs lhs\n      let e    \u2190 mkEqSymm (\u2190 mkPropExt e)\n      return [(e, type)]\n    else\n      let type \u2190 mkEq lhs rhs\n      let e    \u2190 mkPropExt e\n      return [(e, type)]\n  else if let some (_, lhs, rhs) := type.ne? then\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'False'\"\n    let type \u2190 mkEq (\u2190 mkEq lhs rhs) (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some p := type.not? then\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'False'\"\n    let type \u2190 mkEq p (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some (type\u2081, type\u2082) := type.and? then\n    let e\u2081 := mkProj ``And 0 e\n    let e\u2082 := mkProj ``And 1 e\n    return (\u2190 go e\u2081 type\u2081) ++ (\u2190 go e\u2082 type\u2082)\n  else\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'True'\"\n    let type \u2190 mkEq type (mkConst ``True)\n    let e    \u2190 mkEqTrue e\n    return [(e, type)]\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n  unless (\u2190 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 \u2190 instantiateMVars (\u2190 inferType e)\n  withNewMCtxDepth do\n    let (xs, _, type) \u2190 withReducible <| forallMetaTelescopeReducing type\n    let type \u2190 whnfR type\n    let (keys, perm) \u2190\n      match type.eq? with\n      | some (_, lhs, rhs) => pure (\u2190 DiscrTree.mkPath lhs, \u2190 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 \u2190 getConstInfo declName\n  let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n  withReducible do\n    let type \u2190 inferType val\n    checkTypeIsProp type\n    if inv || (\u2190 shouldPreprocess type) then\n      let mut r := #[]\n      for (val, type) in (\u2190 preprocess val type inv (isGlobal := true)) do\n        let auxName \u2190 mkAuxLemma cinfo.levelParams type val\n        r := r.push <| (\u2190 mkSimpTheoremCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n      return r\n    else\n      return #[\u2190 mkSimpTheoremCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName]\n\ninductive SimpEntry where\n  | thm      : SimpTheorem \u2192 SimpEntry\n  | toUnfold : Name \u2192 SimpEntry\n  | toUnfoldThms : Name \u2192 Array Name \u2192 SimpEntry\n  deriving Inhabited\n\nabbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpTheorems\n\ndef SimpExtension.getTheorems (ext : SimpExtension) : CoreM SimpTheorems :=\n  return ext.getState (\u2190 getEnv)\n\ndef addSimpTheorem (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n  let simpThms \u2190 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 \u2190 getConstInfo declName\n        let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost\n        let prio \u2190 getAttrParamOptPrio stx[2]\n        if (\u2190 isProp info.type) then\n          addSimpTheorem ext declName post (inv := false) attrKind prio\n        else if info.hasValue then\n          if let some eqns \u2190 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 (\u2190 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 (\u2190 getEnv)\n      let s \u2190 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 \u2190 mkSimpExt extName\n  mkSimpAttr attrName attrDescr ext\n  return ext\n\nbuiltin_initialize simpExtension : SimpExtension \u2190 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 \u2190 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 \u2190 getConstInfo simpThm.proof.constName!\n    if info.levelParams.isEmpty then\n      return simpThm.proof\n    else\n      return simpThm.proof.updateConst! (\u2190 info.levelParams.mapM (fun _ => mkFreshLevelMVar))\n  else\n    let us \u2190 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 \u2190 inferType val\n  checkTypeIsProp type\n  let ps \u2190 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    (\u2190 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 \u2190 mkSimpTheorems levelParams proof post inv prio (\u2190 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 \u2190 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 \u2190 getEqnsFor? declName then\n      let mut d := d\n      for eqn in eqns do\n        d \u2190 SimpTheorems.addConst d eqn\n      if hasSmartUnfoldingDecl (\u2190 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 data.buffer.parser\nimport ircbot ircbot.base64\nimport ircbot.modules\n\nopen types effects support parsing login\nopen parser\n\n-- constants\ndef server : string := \"chat.freenode.net\"\ndef port : string := \"6667\"\n\ndef ident : string := \"lean\"\ndef bot_nickname : string := \"leanbot-test\"\n-- end\n\ntheorem bot_nickname_is_correct : bot_nickname.front \u2260 '#' :=\nbegin intros contra, cases contra end\n\ndef messages : list irc_text :=\n  [ join \"#chlor\",\n    privmsg \"#chlor\" \"\u041f\u0440\u0443\u0432\u0435\u0440\u044b \u043f\u0440\u0430\u0432\u044f\u0442 \u043c\u0438\u0440\u043e\u043c.\",\n    mode bot_nickname \"+B\" ]\n\ndef my_bot_info : bot_info :=\nbot_info.mk bot_nickname bot_nickname_is_correct ident server port []\n\ndef my_funcs (acc : account) : list bot_function :=\n  [ modules.ping_pong.ping_pong,\n    sasl my_bot_info messages acc,\n    modules.print_date.print_date,\n    modules.admin.join_channel,\n    relogin ]\n\ndef my_bot (acc : account) : bot :=\nlet funcs := my_funcs acc in\n{ info := my_bot_info,\n  funcs := modules.help.help funcs :: funcs,\n  fix := \u27e8tt, ff\u27e9 }\n\ndef main := do\n  args \u2190 io.cmdline_args,\n  match args with\n  | (login :: password :: []) :=\n    mk_bot (my_bot $ account.mk login password) netcat\n  | _ := io.fail \"syntax: lean --run file.lean [login] [password]\"\n  end\n", "meta": {"author": "forked-from-1kasper", "repo": "leanbot", "sha": "c61c8c7fdad7b05877e0d232719ce23d2999557f", "save_path": "github-repos/lean/forked-from-1kasper-leanbot", "path": "github-repos/lean/forked-from-1kasper-leanbot/leanbot-c61c8c7fdad7b05877e0d232719ce23d2999557f/sample-bot.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.031143831996063107, "lm_q1q2_score": 0.01096891312881351}}
{"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 \u2192 type gnd}\n\nvariables {\ud835\udcd2 : Type} [category \ud835\udcd2] \n          [limits.has_finite_products \ud835\udcd2] [cartesian_closed \ud835\udcd2]\n\ninductive beta_eta_eq (con_type : con \u2192 type gnd)\n: env gnd fv \u2192 term gnd con fv \u2192 term gnd con fv \u2192 type gnd \u2192 Type\n| Refl : \u2200 {\u0393 t A},\n(\u0393 \u22a9 t \u2237 A)\n-----------------------\n\u2192 beta_eta_eq \u0393 t t A \n\n| Symm : \u2200 {\u0393 t1 t2 A},\nbeta_eta_eq \u0393 t1 t2 A\n------------------------\n\u2192 beta_eta_eq \u0393 t2 t1 A \n\n| Trans : \u2200 {\u0393 t1 t2 t3 A},\nbeta_eta_eq \u0393 t1 t2 A \u2192 beta_eta_eq \u0393 t2 t3 A\n---------------------------------------------\n\u2192 beta_eta_eq \u0393 t1 t3 A\n\n| Beta_fun : \u2200 {\u0393 : env gnd fv} {t1 t2 : term gnd con fv} {A B},\n(\u0393 \u22a9 (\u039b A. t1) \u2237 (A \u2283 B))\n\u2192 (\u0393 \u22a9 t2 \u2237 A)\n----------------------------------------------------------\n\u2192 beta_eta_eq \u0393 ((\u039b A. t1) \u2b1d t2) (open_term t2 0 t1) B\n\n| Beta_prod_fst : \u2200 {\u0393 t1 t2 A B},\n(\u0393 \u22a9 t1 \u2237 A) \u2192 (\u0393 \u22a9 t2 \u2237 B)\n---------------------------------------------------\n\u2192 beta_eta_eq \u0393 (fst \u27eat1, t2\u27eb) t1 A\n\n| Beta_prod_snd : \u2200 {\u0393 t1 t2 A B},\n(\u0393 \u22a9 t1 \u2237 A) \u2192 (\u0393 \u22a9 t2 \u2237 B)\n---------------------------------------------------\n\u2192 beta_eta_eq \u0393 (snd \u27eat1, t2\u27eb) t2 B\n\n| Eta_fun : \u2200 {\u0393 t A B},\n(\u0393 \u22a9 t \u2237 (A \u2283 B))\n-----------------------------------------\n\u2192 beta_eta_eq \u0393 t (\u039b A. (t \u2b1d \u23080\u2309)) (A \u2283 B) \n\n| Eta_prod : \u2200 {\u0393 t A B},\n(\u0393 \u22a9 t \u2237 (A \u220f B))\n----------------------------------------\n\u2192 beta_eta_eq \u0393 t \u27eafst t, snd t\u27eb (A \u220f B)  \n\n| Eta_unit : \u2200 {\u0393 t},\n(\u0393 \u22a9 t \u2237 unit)\n--------------------------\n\u2192 beta_eta_eq \u0393 t \u27ea\u27eb unit\n\n| Cong_lam : \u2200 {\u0393 : env gnd fv} {t t' A B},\n(\u2200 x \u2209 free_vars t \u222a \u0393.keys.to_finset, \n  beta_eta_eq (\u27e8x, A\u27e9 :: \u0393) (open_var x 0 t) (open_var x 0 t') B)\n----------------------------------------------------------------\n\u2192 beta_eta_eq \u0393 (\u039b A. t) (\u039b A. t') (A \u2283 B)\n\n| Cong_app : \u2200 {\u0393 t1 t2 t1' t2' A B},\nbeta_eta_eq \u0393 t1 t1' (A \u2283 B) \u2192 beta_eta_eq \u0393 t2 t2' A\n-----------------------------------------------------\n\u2192 beta_eta_eq \u0393 (t1 \u2b1d t2) (t1' \u2b1d t2') B\n\n| Cong_fst : \u2200 {\u0393 t t' A B},\nbeta_eta_eq \u0393 t t' (A \u220f B)\n----------------------------------\n\u2192 beta_eta_eq \u0393 (fst t) (fst t') A\n\n| Cong_snd : \u2200 {\u0393 t t' A B},\nbeta_eta_eq \u0393 t t' (A \u220f B)\n----------------------------------\n\u2192 beta_eta_eq \u0393 (snd t) (snd t') B\n\n| Cong_pair : \u2200 {\u0393 t1 t2 t1' t2' A B},\nbeta_eta_eq \u0393 t1 t1' A \u2192 beta_eta_eq \u0393 t2 t2' B\n-----------------------------------------------\n\u2192 beta_eta_eq \u0393 \u27eat1, t2\u27eb \u27eat1', t2'\u27eb (A \u220f B)\n\nlemma has_type_of_beta_eta_eq {\u0393 : env gnd fv} \n{t1 t2 : term gnd con fv} {A : type gnd} \n(heq : beta_eta_eq con_type \u0393 t1 t2 A)\n: (\u0393 \u22a9 t1 \u2237 A) \u00d7 (\u0393 \u22a9 t2 \u2237 A) :=\nbegin\n  induction' heq generalizing \u0393 t1 t2 A,\n  case term_equality.beta_eta_eq.Refl : \u0393 t A h\n  { exact \u27e8h, h\u27e9 },\n  case term_equality.beta_eta_eq.Symm : \u0393 t1 t2 A rec ih\n  { exact prod.swap ih },\n  case term_equality.beta_eta_eq.Trans : \u0393 t1 t2 t3 A rec1 rec2 ih1 ih2\n  { exact \u27e8ih1.fst, ih2.snd\u27e9 },\n  case term_equality.beta_eta_eq.Beta_fun : \u0393 t1 t2 A B h1 h2\n  { refine \u27e8h1.App h2, _\u27e9,\n    cases' h1,\n    have hfresh := fvar.hfresh (free_vars t \u222a (list.keys \u0393).to_finset),\n    set x := fvar.fresh (free_vars t \u222a (list.keys \u0393).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 : \u0393 t1 t2 A B h1 h2\n  { exact \u27e8(h1.Pair h2).Fst, h1\u27e9 },\n  case term_equality.beta_eta_eq.Beta_prod_snd : \u0393 t1 t2 A B h1 h2\n  { exact \u27e8(h1.Pair h2).Snd, h2\u27e9 },\n  case term_equality.beta_eta_eq.Eta_fun : \u0393 t A B h\n  { refine \u27e8h, _\u27e9,\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 : \u0393 t A1 A2 h\n  { exact \u27e8h, h.Fst.Pair h.Snd\u27e9 },\n  case term_equality.beta_eta_eq.Eta_unit : \u0393 t1 h\n  { exact \u27e8h, has_type.Unit (ok_of_has_type h)\u27e9 },\n  case term_equality.beta_eta_eq.Cong_lam : \u0393 t1 t2 A1 A2 heq ih\n  { let ih1 := \u03bb x hx, (ih x hx).fst,\n    -- to make this useable, we need hx to be x \u2209 t2, not x \u2209 t1\n    -- but we need x \u2209 t1 to use ih.\n    -- I thought I could use free_vars_subset_env, but I realize there's no\n    -- proof of \u0393 \u22a9 open_var x 0 t \u2237 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 : \u03a0 (x : fv), x \u2209 free_vars t2 \u222a (list.keys \u0393).to_finset \u2192\n              (\u27e8x, A1\u27e9 :: \u0393 \u22a9 open_var x 0 t2 \u2237 A2) := \u03bb x hx, by {\n      rw finset.not_mem_union at hx,\n      sorry\n    },\n    exact \u27e8has_type.Abs ih1, has_type.Abs ih2\u27e9\n  },\n  case term_equality.beta_eta_eq.Cong_app : \u0393 t1 t2 t1' t2' A1 A2 heq heq_1 ih1 ih2\n  { exact \u27e8ih1.fst.App ih2.fst, ih1.snd.App ih2.snd\u27e9 },\n  case term_equality.beta_eta_eq.Cong_fst : \u0393 t1 t2 A B heq ih\n  { exact \u27e8ih.fst.Fst, ih.snd.Fst\u27e9 },\n  case term_equality.beta_eta_eq.Cong_snd : \u0393 t1 t2 A A_1 heq ih\n  { exact \u27e8ih.fst.Snd, ih.snd.Snd\u27e9 },\n  case term_equality.beta_eta_eq.Cong_pair : \u0393 t1 t2 t1' t2' A1 A2 heq heq_1 ih1 ih2\n  { exact \u27e8ih1.fst.Pair ih2.fst, ih1.snd.Pair ih2.snd\u27e9 }\nend\n\nuniverses u v\nvariables {C : Type u} [category.{v} C]\nlemma comp_cong {X Y Z : C} {f1 f2 : X \u27f6 Y} {g : Y \u27f6 Z} (h : f1 = f2)\n: f1 \u226b g = f2 \u226b g :=\nbegin\n  rw h\nend\n\ntheorem soundness {M : model gnd con \ud835\udcd2} \n{\u0393 : env gnd fv} {t1 t2 : term gnd con fv} {A : type gnd}\n(h1 : \u0393 \u22a9 t1 \u2237 A) (h2 : \u0393 \u22a9 t2 \u2237 A)\n(heq : beta_eta_eq con_type \u0393 t1 t2 A)\n: (M\u27e6h1\u27e7) = (M\u27e6h2\u27e7) :=\nbegin\n  induction' heq generalizing \u0393 t1 t2 A,\n  case beta_eta_eq.Refl : \u0393 t A { rw deriv_unicity h1 h2 },\n  case term_equality.beta_eta_eq.Symm : \u0393 t2 t1 A rec ih {\n    symmetry, exact ih h2 h1,\n  },\n  case term_equality.beta_eta_eq.Trans : \u0393 t1 t2 t3 A rec1 rec2 ih1 ih2 {\n    rename [h2 \u2192 h3],\n    obtain \u27e8_, h2\u27e9 := 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 : \u0393 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 : \u0393 t1 t1_1 A B x x_1\n  { cases' h1, cases h1, rw deriv_unicity h2 h1_\u1fb0, simp [eval_has_type] },\n  case term_equality.beta_eta_eq.Beta_prod_snd : \u0393 t1 t2 A1 A2 x x_1\n  { cases' h1, cases h1, rw deriv_unicity h2 h1_\u1fb0_1, simp [eval_has_type] },\n  case term_equality.beta_eta_eq.Eta_fun : \u0393 t A A_1 x\n  { -- need semantics of weakening...\n    admit },\n  case term_equality.beta_eta_eq.Eta_prod : \u0393 t A1 A2 x\n  { -- Idea: Due to deriv unicity, we can say that\n    -- M\u27e6h2_left : \u0393 \u22a9 fst t \u2237 A1\u27e7 = \u03c0\u2081 \u2218 M\u27e6h1 : \u0393 \u22a9 t \u2237 A1 \u220f A2\u27e7 \n    -- M\u27e6h2_right : \u0393 \u22a9 snd t \u2237 A1\u27e7 = \u03c0\u2082 \u2218 M\u27e6h1 : \u0393 \u22a9 t \u2237 A1 \u220f A2\u27e7\n    -- so M\u27e6h2\u27e7 = \u27e8\u03c0\u2081 \u2218 M\u27e6h1\u27e7, \u03c0\u2082 \u2218 M\u27e6h1\u27e7\u27e9 = M\u27e6h1\u27e7 by the universal \n    -- property of products.\n    cases' h2, cases h2, cases h2_1,\n    have := type_unicity h1 h2_\u1fb0, simp at this, subst this,\n    have := type_unicity h1 h2_1_\u1fb0, simp at this, subst this,\n    rw deriv_unicity h2_\u1fb0 h1,\n    rw deriv_unicity h2_1_\u1fb0 h1,\n    ext; simp [eval_has_type]\n  },\n  case term_equality.beta_eta_eq.Eta_unit : \u0393 t1 x\n  { -- M\u27e6h1\u27e7 and M\u27e6h2\u27e7 are both arrows from M\u27e6\u0393\u27e7 to the terminal object,\n    -- so they must be equal by the uniqueness condition. \n    have := category_theory.limits.unique_to_terminal (M.G\u27e6\u0393\u27e7),\n    exact trans (this.uniq (M\u27e6h1\u27e7)) (symm (this.uniq (M\u27e6h2\u27e7))),\n  },\n  case term_equality.beta_eta_eq.Cong_lam : \u0393 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 : \u0393 t1 t2 t1' t2' A1 A2 heq heq' ih ih'\n  { -- Idea: \n    -- the goal is essentially to show \n    -- eval \u2218 \u27e8M\u27e6h1.left\u27e7, M\u27e6h1.right\u27e7\u27e9 = eval \u2218 \u27e8M\u27e6h2.left\u27e7, M\u27e6h2.right\u27e7\u27e9\n    -- By congruence, and by the universal property of products,\n    -- This is the same as showing M\u27e6h1.left\u27e7 = M\u27e6h2.left\u27e7 and M\u27e6h1.right\u27e7 = M\u27e6h2.right\u27e7\n    -- But that's exactly what we have with the inductive hypotheses.\n    cases' h2, cases' h1,\n    obtain \u27e8h1_1', h2_1'\u27e9 := 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 : \u0393 t1 t2 A B heq ih\n  { -- showing \u03c0\u2081 \u2218 M\u27e6h1\u27e7 = \u03c0\u2082 \u2218 M\u27e6h2\u27e7 is the same as showing M\u27e6h1\u27e7 = M\u27e6h2\u27e7\n    -- by congruence\n    cases' h1, cases' h2,\n    obtain \u27e8h1', h2'\u27e9 := 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 : \u0393 t1 t2 A A_1 heq ih\n  { -- similar to Cong_fst\n    cases' h1, cases' h2,\n    obtain \u27e8h1', h2'\u27e9 := 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 : \u0393 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_\u1fb0,\n    exact ih' h1_1 h2_\u1fb0_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": "/-\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.Basic\n\nnamespace Lean.Meta\n\nstructure AuxLemmas where\n  idx    : Nat := 1\n  lemmas : PHashMap Expr (Name \u00d7 List Name) := {}\n  deriving Inhabited\n\nbuiltin_initialize auxLemmasExt : EnvExtension AuxLemmas \u2190 registerEnvExtension (pure {})\n\n/--\n  Helper method for creating auxiliary lemmas in the environment.\n\n  It uses a cache that maps `type` to declaration name. The cache is not stored in `.olean` files.\n  It is useful to make sure the same auxiliary lemma is not created over and over again in the same file.\n\n  This method is useful for tactics (e.g., `simp`) that may perform preprocessing steps to lemmas provided by\n  users. For example, `simp` preprocessor may convert a lemma into multiple ones.\n-/\ndef mkAuxLemma (levelParams : List Name) (type : Expr) (value : Expr) : MetaM Name := do\n  let env \u2190 getEnv\n  let s := auxLemmasExt.getState env\n  let mkNewAuxLemma := do\n    let auxName := Name.mkNum (env.mainModule ++ `_auxLemma) s.idx\n    addDecl <| Declaration.thmDecl {\n      name := auxName\n      levelParams, type, value\n    }\n    modifyEnv fun env => auxLemmasExt.modifyState env fun \u27e8idx, lemmas\u27e9 => \u27e8idx + 1, lemmas.insert type (auxName, levelParams)\u27e9\n    return auxName\n  match s.lemmas.find? type with\n  | some (name, levelParams') => if levelParams == levelParams' then return name else mkNewAuxLemma\n  | none => mkNewAuxLemma\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/AuxLemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27202456289736326, "lm_q2_score": 0.04023794506934539, "lm_q1q2_score": 0.010945709419376792}}
{"text": "import ..data_util.util\nimport all\n\nsection main\nopen tactic\n\nmeta def main : io unit := do {\n  args \u2190 io.cmdline_args,\n  -- let dest : string := ((args.nth 0).get_or_else \"./data/mathlib_decls.log\"),\n  dest \u2190 args.nth_except 0 \"dest\",\n  let ignore_decls_fn : environment \u2192 declaration \u2192 bool :=\n    (\u03bb e d, declaration.is_auto_or_internal e d || bnot (declaration.is_theorem d) || d.to_name.is_aux),\n  f \u2190 io.mk_file_handle dest io.mode.append,\n\n  let mk_decl_msg (d : declaration) : tactic string := do {\n    decl_type \u2190 do {\n      (format.to_string \u2218 format.flatten) <$> tactic.pp d.type\n    },\n    let msg : json := json.object $ [\n      (\"decl_name\", d.to_name.to_string),\n      (\"decl_type\", (decl_type : string))\n    ],\n    pure $ json.unparse msg\n  },\n\n  io.run_tactic' $ do {\n    env \u2190 get_env,\n    mathlib_dir \u2190 get_mathlib_dir,\n    decls \u2190 list.filter (\u03bb d, !(ignore_decls_fn env d)) <$> (lint_project_decls mathlib_dir),\n    for_ decls $ \u03bb decl, do {\n      msg \u2190 mk_decl_msg decl,\n      tactic.unsafe_run_io $ io.fs.put_str_ln f msg,\n      tactic.trace format!\"DECL: {decl.to_name}\"\n    }\n  }\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/tools/all_decls_jsonline.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.03963884207904032, "lm_q1q2_score": 0.010905824145069867}}
{"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* := \u2115\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\u27e8\u03bb _ _, by { unfold foo, exact 37 }\u27e9\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 \u27e8\u03bb _ _, 37\u27e9\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 \u27e8\u03bb _ _, 37\u27e9\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) 2021 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg, Asta Halkj\u00e6r From\n-/\n\nimport Aesop.Nanos\nimport Aesop.Util.UnionFind\nimport Std.Lean.Expr\nimport Std.Lean.Meta.DiscrTree\nimport Std.Lean.PersistentHashSet\n\n\nnamespace Subarray\n\ndef popFront? (as : Subarray \u03b1) : Option (\u03b1 \u00d7 Subarray \u03b1) :=\n  if h : as.start < as.stop\n    then\n      let head := as.as.get \u27e8as.start, Nat.lt_of_lt_of_le h as.h\u2082\u27e9\n      let tail :=\n        { as with\n          start := as.start + 1\n          h\u2081 := Nat.le_of_lt_succ $ Nat.succ_lt_succ h  }\n      some (head, tail)\n    else\n      none\n\nend Subarray\n\n\nnamespace IO\n\n@[inline]\ndef time [Monad m] [MonadLiftT BaseIO m] (x : m \u03b1) : m (\u03b1 \u00d7 Aesop.Nanos) := do\n  let start \u2190 monoNanosNow\n  let a \u2190 x\n  let stop \u2190 monoNanosNow\n  return (a, \u27e8stop - start\u27e9)\n\n@[inline]\ndef time' [Monad m] [MonadLiftT BaseIO m] (x : m Unit) : m Aesop.Nanos := do\n  let start \u2190 monoNanosNow\n  x\n  let stop \u2190 monoNanosNow\n  return \u27e8stop - start\u27e9\n\nend IO\n\n\nnamespace Lean.PersistentHashSet\n\n-- Elements are returned in unspecified order.\n@[inline]\ndef toList [BEq \u03b1] [Hashable \u03b1] (s : PersistentHashSet \u03b1) : List \u03b1 :=\n  s.fold (init := []) \u03bb as a => a :: as\n\n-- Elements are returned in unspecified order. (In fact, they are currently\n-- returned in reverse order of `toList`.)\n@[inline]\ndef toArray [BEq \u03b1] [Hashable \u03b1] (s : PersistentHashSet \u03b1) : Array \u03b1 :=\n  s.fold (init := Array.mkEmpty s.size) \u03bb as a => as.push a\n\nend Lean.PersistentHashSet\n\n\nnamespace Lean.Meta.DiscrTree\n\n-- For `type = \u2200 (x\u2081, ..., x\u2099), T`, returns keys that match `T * ... *` (with\n-- `n` stars).\ndef getConclusionKeys (type : Expr) :\n    MetaM (Array (Key s)) :=\n  withoutModifyingState do\n    let (_, _, conclusion) \u2190 forallMetaTelescope type\n    mkPath conclusion\n    -- We use a meta telescope because `DiscrTree.mkPath` ignores metas (they\n    -- turn into `Key.star`) but not fvars.\n\n-- For a constant `d` with type `\u2200 (x\u2081, ..., x\u2099), T`, returns keys that\n-- match `d * ... *` (with `n` stars).\ndef getConstKeys (decl : Name) : MetaM (Array (Key s)) := do\n  let (some info) \u2190 getConst? decl\n    | throwUnknownConstant decl\n  let arity := info.type.forallArity\n  let mut keys := Array.mkEmpty (arity + 1)\n  keys := keys.push $ .const decl arity\n  for _ in [0:arity] do\n    keys := keys.push $ .star\n  return keys\n\nend Lean.Meta.DiscrTree\n\n\nnamespace Lean.Meta.SimpTheorems\n\ndef addSimpEntry (s : SimpTheorems) : SimpEntry \u2192 SimpTheorems\n  | SimpEntry.thm l =>\n    { addSimpTheoremEntry s l with erased := s.erased.erase l.origin }\n  | SimpEntry.toUnfold d =>\n    { s with toUnfold := s.toUnfold.insert d }\n  | SimpEntry.toUnfoldThms n thms => s.registerDeclToUnfoldThms n thms\n\ndef eraseSimpEntry (s : SimpTheorems) : SimpEntry \u2192 SimpTheorems\n  | SimpEntry.thm l =>\n    let o := l.origin\n    { s with erased := s.erased.insert o, lemmaNames := s.lemmaNames.erase o }\n  | SimpEntry.toUnfold d =>\n    { s with toUnfold := s.toUnfold.erase d }\n  | SimpEntry.toUnfoldThms n _ =>\n    { s with toUnfoldThms := s.toUnfoldThms.erase n }\n\ndef foldSimpEntriesM [Monad m] (f : \u03c3 \u2192 SimpEntry \u2192 m \u03c3) (init : \u03c3)\n    (thms : SimpTheorems) : m \u03c3 := do\n  let s \u2190 thms.pre.foldValuesM  (init := init) processTheorem\n  let s \u2190 thms.post.foldValuesM (init := s)    processTheorem\n  let s \u2190 thms.toUnfold.foldM (init := s) \u03bb s n => f s (SimpEntry.toUnfold n)\n  thms.toUnfoldThms.foldlM (init := s) \u03bb s n thms =>\n    f s (SimpEntry.toUnfoldThms n thms)\n  where\n    @[inline]\n    processTheorem (s : \u03c3) (thm : SimpTheorem) : m \u03c3 :=\n      if thms.erased.contains thm.origin then\n        return s\n      else\n        f s (SimpEntry.thm thm)\n\ndef foldSimpEntries (f : \u03c3 \u2192 SimpEntry \u2192 \u03c3) (init : \u03c3) (thms : SimpTheorems) :\n    \u03c3 :=\n  Id.run $ foldSimpEntriesM f init thms\n\ndef simpEntries (thms : SimpTheorems) : Array SimpEntry :=\n  thms.foldSimpEntries (init := #[]) \u03bb s thm => s.push thm\n\ndef merge (s t : SimpTheorems) : SimpTheorems := {\n    pre := s.pre.mergePreservingDuplicates t.pre\n    post := s.post.mergePreservingDuplicates t.post\n    lemmaNames := s.lemmaNames.merge t.lemmaNames\n    toUnfold := s.toUnfold.merge t.toUnfold\n    toUnfoldThms := s.toUnfoldThms.mergeWith t.toUnfoldThms\n      (\u03bb _ thms\u2081 _ => thms\u2081)\n      -- We can ignore collisions here because the theorems should always be the\n      -- same.\n    erased := mkErased t s $ mkErased s t {}\n  }\n  where\n    -- Adds the erased lemmas from `s` to `init`, excluding those lemmas which\n    -- occur in `t`.\n    mkErased (s t : SimpTheorems) (init : PHashSet Origin) : PHashSet Origin :=\n      s.erased.fold (init := init) \u03bb x origin =>\n        -- I think the following check suffices to ensure that `decl` does not\n        -- occur in `t`. If `decl` is an unfold theorem (in the sense of\n        -- `toUnfoldThms`), then it occurs also in `t.lemmaNames`.\n        if t.lemmaNames.contains origin || t.toUnfold.contains origin.key then\n          x\n        else\n          x.insert origin\n\nend Lean.Meta.SimpTheorems\n\n\nnamespace Lean.Meta\n\ndef matchAppOf (f : Expr) (e : Expr) : MetaM (Option (Array Expr)) := do\n  let type \u2190 inferType f\n  let (mvars, _, _) \u2190 forallMetaTelescope type\n  let app := mkAppN f mvars\n  if \u2190 isDefEq app e then\n    some <$> mvars.mapM instantiateMVars\n  else\n    return none\n\nend Lean.Meta\n\n\n@[inline]\ndef setThe (\u03c3) {m} [MonadStateOf \u03c3 m] (s : \u03c3) : m PUnit :=\n  MonadStateOf.set s\n\n\nnamespace Lean\n\n@[inline]\ndef runMetaMAsCoreM (x : MetaM \u03b1) : CoreM \u03b1 :=\n  Prod.fst <$> x.run {} {}\n\n@[inline]\ndef runTermElabMAsCoreM (x : Elab.TermElabM \u03b1) : CoreM \u03b1 :=\n  runMetaMAsCoreM x.run'\n\nend Lean\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/Aesop/Util/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3007455789412415, "lm_q2_score": 0.036220054564544336, "lm_q1q2_score": 0.010893021279297243}}
{"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\u2081 u\u2082\n\n/-\nRemark: we can define `mapM`, `mapM\u2082` and `forM` using `Applicative` instead of `Monad`.\nExample:\n```\ndef mapM {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\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 \u2192 Type v} [Monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\n  | []    => pure []\n  | a::as => return (\u2190 f a) :: (\u2190 mapM f as)\n\n@[specialize]\ndef mapA {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m (List \u03b2)\n  | []    => pure []\n  | a::as => List.cons <$> f a <*> mapA f as\n\n@[specialize]\nprotected def forM {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type w} (as : List \u03b1) (f : \u03b1 \u2192 m PUnit) : m PUnit :=\n  match as with\n  | []      => pure \u27e8\u27e9\n  | a :: as => do f a; List.forM as f\n\n@[specialize]\ndef forA {m : Type u \u2192 Type v} [Applicative m] {\u03b1 : Type w} (as : List \u03b1) (f : \u03b1 \u2192 m PUnit) : m PUnit :=\n  match as with\n  | []      => pure \u27e8\u27e9\n  | a :: as => f a *> forA as f\n\n@[specialize]\ndef filterAuxM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 List \u03b1 \u2192 m (List \u03b1)\n  | [],     acc => pure acc\n  | h :: t, acc => do\n    let b \u2190 f h\n    filterAuxM f t (cond b (h :: acc) acc)\n\n@[inline]\ndef filterM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) (as : List \u03b1) : m (List \u03b1) := do\n  let as \u2190 filterAuxM f as []\n  pure as.reverse\n\n@[inline]\ndef filterRevM {m : Type \u2192 Type v} [Monad m] {\u03b1 : Type} (f : \u03b1 \u2192 m Bool) (as : List \u03b1) : m (List \u03b1) :=\n  filterAuxM f as.reverse []\n\n@[inline]\ndef filterMapM {m : Type u \u2192 Type v} [Monad m] {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 m (Option \u03b2)) (as : List \u03b1) : m (List \u03b2) :=\n  let rec @[specialize] loop\n    | [],     bs => pure bs\n    | a :: as, bs => do\n      match (\u2190 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 \u2192 Type v} [Monad m] {s : Type u} {\u03b1 : Type w} : (f : s \u2192 \u03b1 \u2192 m s) \u2192 (init : s) \u2192 List \u03b1 \u2192 m s\n  | f, s, []      => pure s\n  | f, s, a :: as => do\n    let s' \u2190 f s a\n    List.foldlM f s' as\n\n@[specialize]\ndef foldrM {m : Type u \u2192 Type v} [Monad m] {s : Type u} {\u03b1 : Type w} : (f : \u03b1 \u2192 s \u2192 m s) \u2192 (init : s) \u2192 List \u03b1 \u2192 m s\n  | f, s, []      => pure s\n  | f, s, a :: as => do\n    let s' \u2190 foldrM f s as\n    f a s'\n\n@[specialize]\ndef firstM {m : Type u \u2192 Type v} [Monad m] [Alternative m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m \u03b2) : List \u03b1 \u2192 m \u03b2\n  | []    => failure\n  | a::as => f a <|> firstM f as\n\n@[specialize]\ndef anyM {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type v} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m Bool\n  | []    => pure false\n  | a::as => do\n    match (\u2190 f a) with\n    | true  => pure true\n    | false => anyM f as\n\n@[specialize]\ndef allM {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type v} (f : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m Bool\n  | []    => pure true\n  | a::as => do\n    match (\u2190 f a) with\n    | true  => allM f as\n    | false => pure false\n\n@[specialize]\ndef findM? {m : Type \u2192 Type u} [Monad m] {\u03b1 : Type} (p : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 m (Option \u03b1)\n  | []    => pure none\n  | a::as => do\n    match (\u2190 p a) with\n    | true  => pure (some a)\n    | false => findM? p as\n\n@[specialize]\ndef findSomeM? {m : Type u \u2192 Type v} [Monad m] {\u03b1 : Type w} {\u03b2 : Type u} (f : \u03b1 \u2192 m (Option \u03b2)) : List \u03b1 \u2192 m (Option \u03b2)\n  | []    => pure none\n  | a::as => do\n    match (\u2190 f a) with\n    | some b => pure (some b)\n    | none   => findSomeM? f as\n\n@[inline] protected def forIn {\u03b1 : Type u} {\u03b2 : Type v} {m : Type v \u2192 Type w} [Monad m] (as : List \u03b1) (init : \u03b2) (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) : m \u03b2 :=\n  let rec @[specialize] loop\n    | [], b    => pure b\n    | a::as, b => do\n      match (\u2190 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 \u03b1) \u03b1 where\n  forIn := List.forIn\n\n@[simp] theorem forIn_nil [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) (b : \u03b2) : forIn [] b f = pure b :=\n  rfl\n\n@[simp] theorem forIn_cons [Monad m] (f : \u03b1 \u2192 \u03b2 \u2192 m (ForInStep \u03b2)) (a : \u03b1) (as : List \u03b1) (b : \u03b2)\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 \u03b1) \u03b1 where\n  forM := List.forM\n\n@[simp] theorem forM_nil  [Monad m] (f : \u03b1 \u2192 m PUnit) : forM [] f = pure \u27e8\u27e9 :=\n  rfl\n@[simp] theorem forM_cons [Monad m] (f : \u03b1 \u2192 m PUnit) (a : \u03b1) (as : List \u03b1) : 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": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Parser.Term\nimport Lean.Parser.Do\n\nnamespace Lean\nnamespace Parser\n\n/--\n  Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like\n  `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead.\n  Multiple command will be put in a `` `null `` node, but a single command will not (so that you can directly\n  match against a quotation in a command kind's elaborator). -/\n-- TODO: use two separate quotation parsers with parser priorities instead\n@[builtinTermParser] def Term.quot := leading_parser \"`(\" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> \")\"\n@[builtinTermParser] def Term.precheckedQuot := leading_parser \"`\" >> Term.quot\n\nnamespace Command\n\n-- A mutual block may be broken in different cliques, we identify them using an `ident` (an element of the clique)\ndef terminationByMany   := leading_parser atomic (lookahead (ident >> \" => \")) >> many1Indent (group (ppLine >> ident >> \" => \" >> termParser >> optional \";\"))\n-- Simpler syntax for mutual blocks containing single clique that requires well-founded recursion.\ndef terminationBy1 := leading_parser termParser\n\ndef terminationBy := leading_parser \"termination_by \" >> (terminationByMany <|> terminationBy1)\n\n@[builtinCommandParser]\ndef moduleDoc := leading_parser ppDedent $ \"/-!\" >> commentBody >> ppLine\n\ndef namedPrio := leading_parser (atomic (\"(\" >> nonReservedSymbol \"priority\") >> \" := \" >> priorityParser >> \")\")\ndef optNamedPrio := optional namedPrio\n\ndef \u00abprivate\u00bb        := leading_parser \"private \"\ndef \u00abprotected\u00bb      := leading_parser \"protected \"\ndef visibility       := \u00abprivate\u00bb <|> \u00abprotected\u00bb\ndef \u00abnoncomputable\u00bb  := leading_parser \"noncomputable \"\ndef \u00abunsafe\u00bb         := leading_parser \"unsafe \"\ndef \u00abpartial\u00bb        := leading_parser \"partial \"\ndef \u00abnonrec\u00bb         := leading_parser \"nonrec \"\ndef declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.\u00abattributes\u00bb >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional \u00abnoncomputable\u00bb >> optional \u00abunsafe\u00bb >> optional (\u00abpartial\u00bb <|> \u00abnonrec\u00bb)\ndef declId           := leading_parser ident >> optional (\".{\" >> sepBy1 ident \", \" >> \"}\")\ndef declSig          := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec\ndef optDeclSig       := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType\ndef declValSimple    := leading_parser \" :=\\n\" >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef declVal          := declValSimple <|> declValEqns <|> Term.whereDecls\ndef \u00ababbrev\u00bb         := leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\ndef optDefDeriving   := optional (atomic (\"deriving \" >> notSymbol \"instance\") >> sepBy1 ident \", \")\ndef \u00abdef\u00bb            := leading_parser \"def \" >> declId >> optDeclSig >> declVal >> optDefDeriving >> optional terminationBy\ndef \u00abtheorem\u00bb        := leading_parser \"theorem \" >> declId >> declSig >> declVal >> optional terminationBy\ndef \u00abconstant\u00bb       := leading_parser \"constant \" >> declId >> declSig >> optional declValSimple\ndef \u00abinstance\u00bb       := leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal >> optional terminationBy\ndef \u00abaxiom\u00bb          := leading_parser \"axiom \" >> declId >> declSig\ndef \u00abexample\u00bb        := leading_parser \"example \" >> declSig >> declVal\ndef inferMod         := leading_parser atomic (symbol \"{\" >> \"}\")\ndef ctor             := leading_parser \"\\n| \" >> declModifiers true >> ident >> optional inferMod >> optDeclSig\ndef derivingClasses  := sepBy1 (group (ident >> optional (\" with \" >> Term.structInst))) \", \"\ndef optDeriving      := leading_parser optional (atomic (\"deriving \" >> notSymbol \"instance\") >> derivingClasses)\ndef \u00abinductive\u00bb      := leading_parser \"inductive \" >> declId >> optDeclSig >> optional (symbol \":=\" <|> \"where\") >> many ctor >> optDeriving\ndef classInductive   := leading_parser atomic (group (symbol \"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional (symbol \":=\" <|> \"where\") >> many ctor >> optDeriving\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> optional inferMod >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> optional inferMod >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder))\ndef structCtor           := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> \" :: \")\ndef structureTk          := leading_parser \"structure \"\ndef classTk              := leading_parser \"class \"\ndef \u00abextends\u00bb            := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef \u00abstructure\u00bb          := leading_parser\n    (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType\n    >> optional ((symbol \" := \" <|> \" where \") >> optional structCtor >> structFields)\n    >> optDeriving\n@[builtinCommandParser] def declaration := leading_parser\ndeclModifiers false >> (\u00ababbrev\u00bb <|> \u00abdef\u00bb <|> \u00abtheorem\u00bb <|> \u00abconstant\u00bb <|> \u00abinstance\u00bb <|> \u00abaxiom\u00bb <|> \u00abexample\u00bb <|> \u00abinductive\u00bb <|> classInductive <|> \u00abstructure\u00bb)\n@[builtinCommandParser] def \u00abderiving\u00bb     := leading_parser \"deriving \" >> \"instance \" >> derivingClasses >> \" for \" >> sepBy1 ident \", \"\n@[builtinCommandParser] def \u00absection\u00bb      := leading_parser \"section \" >> optional ident\n@[builtinCommandParser] def \u00abnamespace\u00bb    := leading_parser \"namespace \" >> ident\n@[builtinCommandParser] def \u00abend\u00bb          := leading_parser \"end \" >> optional ident\n@[builtinCommandParser] def \u00abvariable\u00bb     := leading_parser \"variable\" >> many1 Term.bracketedBinder\n@[builtinCommandParser] def \u00abuniverse\u00bb     := leading_parser \"universe \" >> many1 ident\n@[builtinCommandParser] def check          := leading_parser \"#check \" >> termParser\n@[builtinCommandParser] def check_failure  := leading_parser \"#check_failure \" >> termParser -- Like `#check`, but succeeds only if term does not type check\n@[builtinCommandParser] def reduce         := leading_parser \"#reduce \" >> termParser\n@[builtinCommandParser] def eval           := leading_parser \"#eval \" >> termParser\n@[builtinCommandParser] def synth          := leading_parser \"#synth \" >> termParser\n@[builtinCommandParser] def exit           := leading_parser \"#exit\"\n@[builtinCommandParser] def print          := leading_parser \"#print \" >> (ident <|> strLit)\n@[builtinCommandParser] def printAxioms    := leading_parser \"#print \" >> nonReservedSymbol \"axioms \" >> ident\n@[builtinCommandParser] def \u00abresolve_name\u00bb := leading_parser \"#resolve_name \" >> ident\n@[builtinCommandParser] def \u00abinit_quot\u00bb    := leading_parser \"init_quot\"\ndef optionValue := nonReservedSymbol \"true\" <|> nonReservedSymbol \"false\" <|> strLit <|> numLit\n@[builtinCommandParser] def \u00abset_option\u00bb   := leading_parser \"set_option \" >> ident >> ppSpace >> optionValue\ndef eraseAttr := leading_parser \"-\" >> rawIdent\n@[builtinCommandParser] def \u00abattribute\u00bb    := leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"] \" >> many1 ident\n@[builtinCommandParser] def \u00abexport\u00bb       := leading_parser \"export \" >> ident >> \"(\" >> many1 ident >> \")\"\ndef openHiding       := leading_parser atomic (ident >> \"hiding\") >> many1 (checkColGt >> ident)\ndef openRenamingItem := leading_parser ident >> unicodeSymbol \"\u2192\" \"->\" >> checkColGt >> ident\ndef openRenaming     := leading_parser atomic (ident >> \"renaming\") >> sepBy1 openRenamingItem \", \"\ndef openOnly         := leading_parser atomic (ident >> \"(\") >> many1 ident >> \")\"\ndef openSimple       := leading_parser many1 (checkColGt >> ident)\ndef openScoped       := leading_parser \"scoped \" >> many1 (checkColGt >> ident)\ndef openDecl         := openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped\n@[builtinCommandParser] def \u00abopen\u00bb    := leading_parser withPosition (\"open \" >> openDecl)\n\n@[builtinCommandParser] def \u00abmutual\u00bb := leading_parser \"mutual \" >> many1 (ppLine >> notSymbol \"end\" >> commandParser) >> ppDedent (ppLine >> \"end\") >> optional terminationBy\n@[builtinCommandParser] def \u00abinitialize\u00bb := leading_parser optional visibility >> \"initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n@[builtinCommandParser] def \u00abbuiltin_initialize\u00bb := leading_parser optional visibility >> \"builtin_initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n\n@[builtinCommandParser] def \u00abin\u00bb  := trailing_parser withOpen (\" in \" >> commandParser)\n\n/-\n  This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`.\n  It is meant for bootstrapping purposes only. -/\n@[builtinCommandParser] def genInjectiveTheorems := leading_parser \"gen_injective_theorems% \" >> ident\n\n@[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false\n@[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true\n\nbuiltin_initialize\n  register_parser_alias \"declModifiers\"       declModifiersF\n  register_parser_alias \"nestedDeclModifiers\" declModifiersT\n  register_parser_alias                       declId\n  register_parser_alias                       declSig\n  register_parser_alias                       declVal\n  register_parser_alias                       optDeclSig\n  register_parser_alias                       openDecl\n\nend Command\n\nnamespace Term\n@[builtinTermParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> termParser)\n@[builtinTermParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> termParser\nend Term\n\nnamespace Tactic\n@[builtinTacticParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> tacticSeq)\n@[builtinTacticParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> tacticSeq\nend Tactic\n\nend Parser\nend Lean\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/src/Lean/Parser/Command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804847339313, "lm_q2_score": 0.040845712261275036, "lm_q1q2_score": 0.010860077775330487}}
{"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\u2081 ih\u2081 binop t\u2082 t\u2083 ih\u2082 ih\u2083 t\u2084 t\u2085 ih\u2084 ih\u2085,\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\u2081)) tt = term.unop unop t\u2081), by begin\n      unfold term.to_termctx,\n      unfold termctx.apply,\n      congr,\n      from ih\u2081\n    end,\n\n    show (termctx.apply (term.to_termctx (term.binop binop t\u2082 t\u2083)) tt = term.binop binop t\u2082 t\u2083), by begin\n      unfold term.to_termctx,\n      unfold termctx.apply,\n      congr,\n      from ih\u2082,\n      from ih\u2083\n    end,\n\n    show (termctx.apply (term.to_termctx (term.app t\u2084 t\u2085)) tt = term.app t\u2084 t\u2085), by begin\n      unfold term.to_termctx,\n      unfold termctx.apply,\n      congr,\n      from ih\u2084,\n      from ih\u2085\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\u2081 {\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\u2081 ih {\n      unfold prop.to_propctx,\n      unfold propctx.apply,\n      congr,\n      from ih\n    },\n\n    case prop.and P\u2081 P\u2082 ih\u2081 ih\u2082 {\n      unfold prop.to_propctx,\n      change (propctx.apply (propctx.and (prop.to_propctx P\u2081) (prop.to_propctx P\u2082)) t = prop.and P\u2081 P\u2082),\n      unfold propctx.apply,\n      congr,\n      from ih\u2081,\n      from ih\u2082\n    },\n\n    case prop.or P\u2081 P\u2082 ih\u2081 ih\u2082 {\n      unfold prop.to_propctx,\n      change (propctx.apply (propctx.or (prop.to_propctx P\u2081) (prop.to_propctx P\u2082)) t = prop.or P\u2081 P\u2082),\n      unfold propctx.apply,\n      congr,\n      from ih\u2081,\n      from ih\u2082\n    },\n\n    case prop.pre t\u2081 t\u2082 {\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\u2081 op t\u2081 {\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\u2082 op t\u2081 t\u2082 {\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\u2081 t\u2082 {\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\u2081 t\u2082 {\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\u2081 ih {\n      unfold prop.to_propctx,\n      unfold propctx.apply,\n      congr,\n      from ih\n    },\n\n    case prop.exis y P\u2081 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\u2081 t\u2082: term}: (t\u2081 = t\u2082) \u2192 (vc.term t\u2081 = vc.term t\u2082) :=\n  begin\n    assume h1,\n    congr,\n    from h1\n  end\n\nlemma vc.not.inj.inv {P Q: vc}: (P = Q) \u2192 (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\u2081 P\u2082 P\u2083 P\u2084: vc}: (P\u2081 = P\u2082) \u2192 (P\u2083 = P\u2084) \u2192 (vc.and P\u2081 P\u2083 = vc.and P\u2082 P\u2084) :=\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\u2081 P\u2082 P\u2083 P\u2084: vc}: (P\u2081 = P\u2082) \u2192 (P\u2083 = P\u2084) \u2192 (vc.or P\u2081 P\u2083 = vc.or P\u2082 P\u2084) :=\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\u2081 t\u2082 t\u2083 t\u2084: term}: (t\u2081 = t\u2082) \u2192 (t\u2083 = t\u2084) \u2192 (vc.pre t\u2081 t\u2083 = vc.pre t\u2082 t\u2084) :=\n  begin\n    assume h1,\n    assume h2,\n    congr,\n    from h1,\n    from h2\n  end\n\nlemma vc.pre\u2081.inj.inv {t\u2081 t\u2082: term} {op: unop}: (t\u2081 = t\u2082) \u2192 (vc.pre\u2081 op t\u2081 = vc.pre\u2081 op t\u2082) :=\n  begin\n    assume h1,\n    congr,\n    from h1\n  end\n\nlemma vc.pre\u2082.inj.inv {t\u2081 t\u2082 t\u2083 t\u2084: term} {op: binop}: (t\u2081 = t\u2082) \u2192 (t\u2083 = t\u2084) \u2192 (vc.pre\u2082 op t\u2081 t\u2083 = vc.pre\u2082 op t\u2082 t\u2084) :=\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\u2081 t\u2082 t\u2083 t\u2084: term}: (t\u2081 = t\u2082) \u2192 (t\u2083 = t\u2084) \u2192 (vc.post t\u2081 t\u2083 = vc.post t\u2082 t\u2084) :=\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) \u2192 (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": "import Lean\n\n\nopen Lean\nopen Lean.Elab\nopen Lean.Elab.Term\n\ndef getCtors (c : Name) : TermElabM (List Name) := do\nlet env \u2190 getEnv;\n(match env.find? c with\n| some (ConstantInfo.inductInfo val) =>\n  pure val.ctors\n| _ => pure [])\n\ndef elabAnonCtor (args : Array (TSyntax `term)) (\u03c4 : Expr) : TermElabM Expr :=\n  match \u03c4.getAppFn with\n  | Expr.const C _ => do\n    let ctors \u2190 getCtors C;\n    (match ctors with\n    | [c] => do\n      let stx \u2190 `($(Lean.mkIdent c) $args*);\n      elabTerm stx \u03c4\n-- error handling\n    | _ => unreachable!)\n  | _ => unreachable!\n\nelab \"foo\u27e8\" args:term,* \"\u27e9\" : term <= \u03c4 => do\n  elabAnonCtor args \u03c4\n\nexample : Nat \u00d7 Nat := foo\u27e81, 2\u27e9\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/elabCmd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.03210070486507694, "lm_q1q2_score": 0.010852513983973314}}
{"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 \u2192 list (expr elab) \u2192 list (expr elab) \u2192 mono_function\n | assoc : expr elab \u2192 option (expr elab) \u2192 option (expr elab) \u2192 mono_function\n | assoc_comm : expr elab \u2192 expr elab \u2192 mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function \u2192 tactic format\n | (mono_function.non_assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 mmap pp xs,\n  ys' \u2190 mmap pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 pp xs,\n  ys' \u2190 pp ys,\n  return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n  fn' \u2190 pp fn,\n  xs' \u2190 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 \u2192 expr \u2192 expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr \u2192 expr \u2192 expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn  \u2190 pp ctx.function,\n   l   \u2190 pp ctx.left,\n   r   \u2190 pp ctx.right,\n   rel \u2190 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 \u2190 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 \u2192 expr \u2192 expr \u2192 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) \u2190 return t | failed,\n   v \u2190 mk_meta_var d,\n   match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr \u2192 tactic expr\n| (expr.pi n _ t b) :=\ndo v \u2190 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 \u2192 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 \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 list expr)\n | es (x :: xs) := do\n    es' \u2190 delete_expr x es,\n    match es' with\n     | (some es') := do\n       (c,l,r) \u2190 match_ac' es' xs, return (x::c,l,r)\n     | none := do\n       (c,l,r) \u2190 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 \u00d7 list expr \u00d7 list expr) :=\ndo (s',l',r') \u2190 match_ac' l r,\n   s' \u2190 mmap instantiate_mvars s',\n   l' \u2190 mmap instantiate_mvars l',\n   r' \u2190 mmap instantiate_mvars r',\n   return (s',l',r')\n\nmeta def match_prefix\n: list expr \u2192 list expr \u2192 tactic (list expr \u00d7 list expr \u00d7 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) \u2190 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 \u00d7 list expr \u00d7 list expr \u00d7 list expr) :=\ndo (pre,l\u2081,r\u2081) \u2190 match_prefix l r,\n   (suf,l\u2082,r\u2082) \u2190 match_prefix (reverse l\u2081) (reverse r\u2081),\n   return (pre,reverse l\u2082,reverse r\u2082,reverse suf)\n\nmeta def check_ac : expr \u2192 tactic (bool \u00d7 bool \u00d7 option (expr \u00d7 expr \u00d7 expr) \u00d7 expr)\n | (expr.app (expr.app f x) y) :=\n   do t \u2190 infer_type x,\n      a \u2190 try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n      c \u2190 try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n      i \u2190 try_core (do\n          v \u2190 mk_meta_var t,\n          l_inst_p \u2190 to_expr ``(is_left_id %%t %%f %%v),\n          r_inst_p \u2190 to_expr ``(is_right_id %%t %%f %%v),\n          l_v \u2190 mk_meta_var l_inst_p,\n          r_v \u2190 mk_meta_var r_inst_p ,\n          l_id \u2190 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 \u2190 mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n          mk_instance r_inst_p >>= unify r_v,\n          v' \u2190 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 \u2192 tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) \u2190 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 \u2192 tactic (list expr) :=\nmap dlist.to_list \u2218 parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) :\n  option (expr \u00d7 expr \u00d7 expr) \u2192 list expr \u2192 option (expr \u00d7 list expr)\n| _ (x::xs) := some (foldl (expr.app \u2218 expr.app op) x xs, [])\n| none []   := none\n| (some (l_id,r_id,x\u2080)) [] := some (x\u2080,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr \u2192 option expr\n| (x::xs) := some $ foldl (expr.app \u2218 expr.app op) x xs\n| []   := none\n\nmeta def same_function_aux\n: list expr \u2192 list expr \u2192 expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr)\n | xs\u2080 xs\u2081 (expr.app f\u2080 a\u2080) (expr.app f\u2081 a\u2081) :=\n   same_function_aux (a\u2080 :: xs\u2080) (a\u2081 :: xs\u2081) f\u2080 f\u2081\n | xs\u2080 xs\u2081 e\u2080 e\u2081 := is_def_eq e\u2080 e\u2081 >> return (e\u2080,xs\u2080,xs\u2081)\n\nmeta def same_function : expr \u2192 expr \u2192 tactic (expr \u00d7 list expr \u00d7 list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr \u00d7 expr \u00d7 list expr \u00d7 mono_function) :=\ndo (full_f,ls,rs) \u2190 same_function l r,\n   (a,c,i,f) \u2190 check_ac l,\n   if a\n   then if c\n   then do\n     (s,ls,rs) \u2190 monad.join (match_ac\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 fold_assoc f i rs,\n     s' \u2190 fold_assoc1 f s,\n     return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n   else do -- a \u2227 \u00ac c\n     (pre,ls,rs,suff) \u2190 monad.join (match_assoc\n                   <$> parse_assoc_chain f l\n                   <*> parse_assoc_chain f r),\n     (l',l_id) \u2190 fold_assoc f i ls,\n     (r',r_id) \u2190 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 -- \u00ac a\n     (xs\u2080,x\u2080,x\u2081,xs\u2081) \u2190 find_one_difference opt ls rs,\n     return (x\u2080,x\u2081,[],mono_function.non_assoc full_f xs\u2080 xs\u2081)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' \u2190 to_expr l,\n   r' \u2190 to_expr r,\n   parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr \u2192 tactic (expr \u00d7 expr \u00d7 list expr \u00d7 ac_mono_ctx)\n | `(%%e\u2080 \u2192 %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) \u2192 (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080 = %%e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     t\u2080 \u2190 infer_type e\u2080,\n     t\u2081 \u2190 infer_type e\u2081,\n     rel_def \u2190 to_expr ``(\u03bb x\u2080 x\u2081, (x\u2080 : %%t\u2080) = (x\u2081 : %%t\u2081)),\n     return (e\u2080, e\u2081, 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\u2080) e\u2081) :=\n  do (l,r,id_rs,f) \u2190 parse_ac_mono_function e\u2080 e\u2081,\n     return (e\u2080, e\u2081, id_rs,\n            { function := f\n            , left := l, right := r\n            , to_rel := expr.app \u2218 expr.app rel\n            , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr)  : option expr \u2192 expr \u2192 expr\n| none e := e\n| (some e\u2080) e\u2081 := f.mk_app [e\u2080,e\u2081]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr \u2192 option expr \u2192 expr\n| e none := e\n| e\u2080 (some e\u2081) := f.mk_app [e\u2080,e\u2081]\n\nmeta def mk_fun_app : mono_function \u2192 expr \u2192 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\u2080,r\u2080) (r\u2081,l\u2081)` gives first how to find rules to prove\n      x+(y\u2080+z) R x+(y\u2081+z);\n      if that fails, helps prove (x+y\u2080)+z R (x+y\u2081)+z -/\n | assoc : expr \u00d7 expr \u2192 expr \u00d7 expr \u2192 mono_law\n   /- `congr r` gives the rule to prove `x = y \u2192 f x = f y` -/\n | congr : expr \u2192 mono_law\n | other : expr \u2192 mono_law\n\nmeta def mono_law.to_tactic_format : mono_law \u2192 tactic format\n | (mono_law.other e) := do e \u2190 pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e \u2190 pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\ndo x\u2080 \u2190 pp x\u2080,\n   x\u2081 \u2190 pp x\u2081,\n   y\u2080 \u2190 pp y\u2080,\n   y\u2081 \u2190 pp y\u2081,\n   return format!\"assoc {x\u2080}; {x\u2081} | {y\u2080}; {y\u2081}\"\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 \u2192 expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs\u2080 xs\u2081 : list expr) (l r : expr) : tactic expr :=\ndo p \u2190 mk_app `eq [fn.mk_app $ xs\u2080 ++ l :: xs\u2081,fn.mk_app $ xs\u2080 ++ r :: xs\u2081],\n   prod.snd <$> solve_aux p\n     (do iterate_exactly (xs\u2081.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\u2080 x\u2081) :=\n    if (x\u2080 <|> x\u2081).is_some\n       then mk_congr_args f x\u2080.to_monad x\u2081.to_monad ctx.left ctx.right\n       else failed\n | (mono_function.assoc_comm f x\u2080) := mk_congr_args f [x\u2080] [] ctx.left ctx.right\n | (mono_function.non_assoc f x\u2080 x\u2081) := mk_congr_args f x\u2080 x\u2081 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 (\u03bb i, bin_op f x (bin_op f i y))\n       , mk_rel ctx (\u03bb i, bin_op f i y))\n       ( mk_rel ctx (\u03bb i, bin_op f (bin_op f x i) y)\n       , mk_rel ctx (\u03bb i, bin_op f x i))\n    | (mono_function.assoc f (some x) none) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb e, mk_fun_app ctx.function e)\n    | (mono_function.assoc f none (some y)) :=\n      return $ mono_law.other $\n        mk_rel ctx (\u03bb 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 (\u03bb 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' \u2190 mk_const r,\n    t  \u2190 infer_type r',\n    t  \u2190 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 \u2192 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\u2080 x\u2081 : expr) : tactic (list expr) :=\ndo x' \u2190 to_expr ``(%%x\u2081 \u2192 %%x\u2080),\n   r\u2080 \u2190 find_lemma x' ls,\n   r\u2081 \u2190 find_lemma x\u2081 ls,\n   return (expr.app <$> r\u2080 <*> r\u2081)\n\nmeta def find_rule (ls : list name) : mono_law \u2192 tactic (list expr)\n | (mono_law.assoc (x\u2080,x\u2081) (y\u2080,y\u2081)) :=\n(match_chaining_rules ls x\u2080 x\u2081)\n<|> (match_chaining_rules ls y\u2080 y\u2081)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {\u03b1 : Sort u} (R : \u03b1 \u2192 \u03b1 \u2192 Sort v) {x y : \u03b1}\n  (x' y' : \u03b1)\n  (h : R x y)\n  (hx : x = x')\n  (hy : y = y')\n: R x' y' :=\nby { rw [\u2190 hx,\u2190 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 \u2190 pp e,\n   asm \u2190 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 \u2190 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 \u00d7 expr) :=\ndo tgt \u2190 target,\n   t \u2190 infer_type v,\n   tgt' \u2190 do\n   { \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize v x >> target),\n     to_expr ``(\u03bb y : %%t, \u03a0 x, y = x \u2192 %%(tgt'.binding_body.lift_vars 0 1)) }\n   <|> to_expr ``(\u03bb y : %%t, \u03a0 x, %%v = x \u2192 %%tgt),\n   t \u2190 head_beta (tgt' v) >>= assert h,\n   swap,\n   r \u2190 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 \u2192 tactic unit) : tactic unit :=\nfocus1 $\ndo tgt \u2190 target >>= instantiate_mvars,\n   tactic.change tgt,\n   ctx \u2190 local_context,\n   let vs := tgt.list_meta_vars,\n   vs' \u2190 mmap (\u03bb v,\n             do h \u2190 get_unused_name `h,\n                x \u2190 get_unused_name `x,\n                prod.snd <$> monotonicity.generalize' h v x) vs,\n     tac ctx;\n     vs'.mmap' (try \u2218 tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ \u03bb _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs \u2190 get_goals,\n   set_goals [v],\n   target >>= instantiate_mvars >>= tactic.change,\n   tac, done,\n   set_goals $ gs\n\ndef list.minimum_on {\u03b1 \u03b2} [linear_order \u03b2] (f : \u03b1 \u2192 \u03b2) : list \u03b1 \u2192 list \u03b1\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (\u03bb \u27e8k,a\u27e9 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 {\u03b2} (xs : list expr) (tac : expr \u2192 tactic \u03b2) : tactic unit :=\ndo t \u2190 target,\n   xs \u2190 xs.mmap (\u03bb 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 \u2218 prod.fst \u2218 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 \u2190 r.mmap (\u03bb \u27e8l,gs,_\u27e9,\n          do ts \u2190 gs.mmap infer_type,\n             msg \u2190 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 \u2190 target >>= instantiate_mvars,\n   ns \u2190 get_monotonicity_lemmas t dir,\n   asms \u2190 local_context,\n   rs \u2190 find_lemma asms t ns,\n   focus1 $ () <$ best_match rs (\u03bb law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x \u2264 y` or `mono with [0 \u2264 x,0 \u2264 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 \u2264 w` and `y < z` or\n    - right: `x < w` and `y \u2264 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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (k + 4 + x) - z :=\nbegin\n  mono, -- unfold `(-)`, apply add_le_add\n  { -- \u22a2 k + 3 + x \u2264 k + 4 + x\n    mono, -- apply add_le_add, refl\n    -- \u22a2 k + 3 \u2264 k + 4\n    mono },\n  { -- \u22a2 -y \u2264 -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 : \u2124)\n  (h : 3 \u2264 (4 : \u2124))\n  (h' : z \u2264 y) :\n  (k + 3 + x) - y \u2264 (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 \u2190 hyps.mmap (\u03bb p, to_expr p >>= mk_meta_var),\n   hyps.mmap' (\u03bb pr, do h \u2190 get_unused_name `h, note h none pr),\n   when (\u00ac 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 \u2190 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 \u227c f y` into `x \u2264 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 $ \u03bb asms,\ndo try `[simp only [sub_eq_add_neg]],\n   tgt \u2190 target >>= instantiate_mvars,\n   (l,r,id_rs,g) \u2190 ac_monotonicity_goal cfg tgt\n             <|> fail \"monotonic context not found\",\n   ns \u2190 get_monotonicity_lemmas tgt both,\n   p \u2190 mk_pattern g,\n   rules \u2190 find_rule asms ns p <|> fail \"no applicable rules found\",\n   when (rules = []) (fail \"no applicable rules found\"),\n   err \u2190 format.join <$> mmap side_conditions rules,\n   focus1 $ best_match rules (\u03bb rule, do\n     t\u2080 \u2190 mk_meta_var `(Prop),\n     v\u2080 \u2190 mk_meta_var t\u2080,\n     t\u2081 \u2190 mk_meta_var `(Prop),\n     v\u2081 \u2190 mk_meta_var t\u2081,\n     tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v\u2080 %%v\u2081),\n     solve_mvar v\u2080 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     solve_mvar v\u2081 (try (any_of id_rs rewrite_target) >>\n             ( done <|>\n               refl <|>\n               ac_refl <|>\n               `[simp only [is_associative.assoc]]) ),\n     n \u2190 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 \u2192 tactic unit \u2192 tactic unit \u2192 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 \u2192 tactic unit \u2192 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 : \u2115) | many\n\nmeta def repeat_or_not : rep_arity \u2192 tactic unit \u2192 option (tactic unit) \u2192 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 \u2295 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 \u2291 f y`, for some relation `\u2291` and a\nmonotonic function `f` to `x \u227a 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 : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : x \u2264 y) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nbegin\n  ac_mono,\n  -- \u22a2 (m + x + n) * z \u2264 z * (y + n + m)\n  ac_mono,\n  -- \u22a2 m + x + n \u2264 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\u2081`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : \u2115)\n  (h\u2080 : z \u2265 0)\n  (h\u2081 : m + x + n \u2264 y + n + m) :\n  (m + x + n) * z + k \u2264 z * (y + n + m) + k :=\nby ac_mono* := h\u2081.\n```\n\nBy giving `ac_mono` the assumption `h\u2081`, 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? \u2192\n         opt_param mono_cfg { mono_cfg . } \u2192\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 \u2190 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 (\u03c3 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) := (\u03b4 : Type u) \u2192 \u03c3 \u2192 (\u03b1 \u2192 \u03c3 \u2192 m \u03b4) \u2192 m \u03b4\n\nnamespace StateCpsT\n\n@[always_inline, inline]\ndef runK {\u03b1 \u03c3 : Type u} {m : Type u \u2192 Type v}  (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2) : m \u03b2 :=\n  x _ s k\n\n@[always_inline, inline]\ndef run {\u03b1 \u03c3 : Type u} {m : Type u \u2192 Type v} [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : m (\u03b1 \u00d7 \u03c3) :=\n  runK x s (fun a s => pure (a, s))\n\n@[always_inline, inline]\ndef run' {\u03b1 \u03c3 : Type u} {m : Type u \u2192 Type v}  [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : m \u03b1 :=\n  runK x s (fun a _ => pure a)\n\n@[always_inline]\ninstance : Monad (StateCpsT \u03c3 m) where\n  map  f x := fun \u03b4 s k => x \u03b4 s fun a s => k (f a) s\n  pure a   := fun _ s k => k a s\n  bind x f := fun \u03b4 s k => x \u03b4 s fun a s => f a \u03b4 s k\n\ninstance : LawfulMonad (StateCpsT \u03c3 m) := by\n  refine' { .. } <;> intros <;> rfl\n\n@[always_inline]\ninstance : MonadStateOf \u03c3 (StateCpsT \u03c3 m) where\n  get   := fun _ s k => k s s\n  set s := fun _ _ k => k \u27e8\u27e9 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 \u03b1) : StateCpsT \u03c3 m \u03b1 :=\n  fun _ s k => x >>= (k . s)\n\ninstance [Monad m] : MonadLift m (StateCpsT \u03c3 m) where\n  monadLift := StateCpsT.lift\n\n@[simp] theorem runK_pure {m : Type u \u2192 Type v} (a : \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2) : (pure a : StateCpsT \u03c3 m \u03b1).runK s k = k a s := rfl\n\n@[simp] theorem runK_get {m : Type u \u2192 Type v} (s : \u03c3) (k : \u03c3 \u2192 \u03c3 \u2192 m \u03b2) : (get : StateCpsT \u03c3 m \u03c3).runK s k = k s s := rfl\n\n@[simp] theorem runK_set {m : Type u \u2192 Type v} (s s' : \u03c3) (k : PUnit \u2192 \u03c3 \u2192 m \u03b2) : (set s' : StateCpsT \u03c3 m PUnit).runK s k = k \u27e8\u27e9 s' := rfl\n\n@[simp] theorem runK_modify {m : Type u \u2192 Type v} (f : \u03c3 \u2192 \u03c3) (s : \u03c3) (k : PUnit \u2192 \u03c3 \u2192 m \u03b2) : (modify f : StateCpsT \u03c3 m PUnit).runK s k = k \u27e8\u27e9 (f s) := rfl\n\n@[simp] theorem runK_lift {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2) : (StateCpsT.lift x : StateCpsT \u03c3 m \u03b1).runK s k = x >>= (k . s) := rfl\n\n@[simp] theorem runK_monadLift {\u03c3 : Type u} [Monad m] [MonadLiftT n m] (x : n \u03b1) (s : \u03c3) (k : \u03b1 \u2192 \u03c3 \u2192 m \u03b2)\n    : (monadLift x : StateCpsT \u03c3 m \u03b1).runK s k = (monadLift x : m \u03b1) >>= (k . s) := rfl\n\n@[simp] theorem runK_bind_pure {\u03b1 \u03c3 : Type u} [Monad m] (a : \u03b1) (f : \u03b1 \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (pure a >>= f).runK s k = (f a).runK s k := rfl\n\n@[simp] theorem runK_bind_lift {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3)\n    : (StateCpsT.lift x >>= f).runK s k = x >>= fun a => (f a).runK s k := rfl\n\n@[simp] theorem runK_bind_get {\u03c3 : Type u} [Monad m] (f : \u03c3 \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (get >>= f).runK s k = (f s).runK s k := rfl\n\n@[simp] theorem runK_bind_set {\u03c3 : Type u} [Monad m] (f : PUnit \u2192 StateCpsT \u03c3 m \u03b2) (s s' : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (set s' >>= f).runK s k = (f \u27e8\u27e9).runK s' k := rfl\n\n@[simp] theorem runK_bind_modify {\u03c3 : Type u} [Monad m] (f : \u03c3 \u2192 \u03c3) (g : PUnit \u2192 StateCpsT \u03c3 m \u03b2) (s : \u03c3) (k : \u03b2 \u2192 \u03c3 \u2192 m \u03b3) : (modify f >>= g).runK s k = (g \u27e8\u27e9).runK (f s) k := rfl\n\n@[simp] theorem run_eq [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : x.run s = x.runK s (fun a s => pure (a, s)) := rfl\n\n@[simp] theorem run'_eq [Monad m] (x : StateCpsT \u03c3 m \u03b1) (s : \u03c3) : 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) 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.Basic\n\nnamespace Lean.Meta\n\nstructure AuxLemmas where\n  idx    : Nat := 1\n  lemmas : Std.PHashMap Expr (Name \u00d7 List Name) := {}\n  deriving Inhabited\n\nbuiltin_initialize auxLemmasExt : EnvExtension AuxLemmas \u2190 registerEnvExtension (pure {})\n\n/--\n  Helper method for creating auxiliary lemmas in the environment.\n\n  It uses a cache that maps `type` to declaration name. The cache is not stored in `.olean` files.\n  It is useful to make sure the same auxiliary lemma is not created over and over again in the same file.\n\n  This method is useful for tactics (e.g., `simp`) that may perform preprocessing steps to lemmas provided by\n  users. For example, `simp` preprocessor may convert a lemma into multiple ones.\n-/\ndef mkAuxLemma (levelParams : List Name) (type : Expr) (value : Expr) : MetaM Name := do\n  let env \u2190 getEnv\n  let s := auxLemmasExt.getState env\n  let mkNewAuxLemma := do\n    let auxName := Name.mkNum (env.mainModule ++ `_auxLemma) s.idx\n    addDecl <| Declaration.thmDecl {\n      name        := auxName\n      levelParams := levelParams\n      type        := type\n      value       := value\n    }\n    modifyEnv fun env => auxLemmasExt.modifyState env fun \u27e8idx, lemmas\u27e9 => \u27e8idx + 1, lemmas.insert type (auxName, levelParams)\u27e9\n    return auxName\n  match s.lemmas.find? type with\n  | some (name, levelParams') => if levelParams == levelParams' then return name else mkNewAuxLemma\n  | none => mkNewAuxLemma\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/AuxLemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850021044189, "lm_q2_score": 0.044018654722629766, "lm_q1q2_score": 0.010788312085329405}}
{"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 \u2192 Type v) (n : Type u \u2192 Type w) :=\n(monad_lift : \u2200 {\u03b1}, m \u03b1 \u2192 n \u03b1)\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 \u2192 Type v) (n : Type u \u2192 Type w) :=\n(monad_lift : \u2200 {\u03b1}, m \u03b1 \u2192 n \u03b1)\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] {\u03b1} : has_coe (m \u03b1) (n \u03b1) :=\n\u27e8monad_lift\u27e9\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\u27e8\u03bb \u03b1 ma, has_monad_lift.monad_lift (monad_lift ma : n \u03b1)\u27e9\n\ninstance has_monad_lift_t_refl (m) : has_monad_lift_t m m :=\n\u27e8\u03bb \u03b1, id\u27e9\n\n@[simp] lemma monad_lift_refl {m : Type u \u2192 Type v} {\u03b1} : (monad_lift : m \u03b1 \u2192 m \u03b1) = 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 \u2192 Type v) (n n' : Type u \u2192 Type w) :=\n(monad_map {\u03b1 : Type u} : (\u2200 {\u03b1}, m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1)\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 \u2192 Type v) (n n' : Type u \u2192 Type w) :=\n(monad_map {\u03b1 : Type u} : (\u2200 {\u03b1}, m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1)\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\u27e8\u03bb \u03b1 f, monad_functor.monad_map (\u03bb \u03b1, (monad_map @f : n \u03b1 \u2192 n' \u03b1))\u27e9\n\ninstance monad_functor_t_refl (m m') : monad_functor_t m m' m m' :=\n\u27e8\u03bb \u03b1 f, f\u27e9\n\n@[simp] lemma monad_map_refl {m m' : Type u \u2192 Type v} (f : \u2200 {\u03b1}, m \u03b1 \u2192 m' \u03b1) {\u03b1} : (monad_map @f : m \u03b1 \u2192 m' \u03b1) = 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 {\u03b1 : Type} (x : my_monad \u03b1) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n    def my_monad.run {\u03b1 : Type} (x : my_monad \u03b1) := monad_run.run x\n    ```\n    -/\nclass monad_run (out : out_param $ Type u \u2192 Type v) (m : Type u \u2192 Type v) :=\n(run {\u03b1 : Type u} : m \u03b1 \u2192 out \u03b1)\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| \u27e8l\u2081, c\u2081\u27e9 \u27e8l\u2082, c\u2082\u27e9 := if h\u2081 : l\u2081 = l\u2082 then\n  if h\u2082 : c\u2081 = c\u2082 then is_true (eq.rec_on h\u2081 (eq.rec_on h\u2082 rfl))\n  else is_false (\u03bb contra, pos.no_confusion contra (\u03bb e\u2081 e\u2082, absurd e\u2082 h\u2082))\nelse is_false (\u03bb contra, pos.no_confusion contra (\u03bb e\u2081 e\u2082, absurd e\u2081 h\u2081))\n\nmeta instance : has_to_format pos :=\n\u27e8\u03bb \u27e8l, c\u27e9, \"\u27e8\" ++ l ++ \", \" ++ c ++ \"\u27e9\"\u27e9\n\n/-- Auxiliary annotation for binders (Lambda and Pi).\n    This information is only used for elaboration.\n      The difference between `{}` and `\u2983\u2984` is how implicit arguments are treated that are *not* followed by explicit arguments.\n  `{}` arguments are applied eagerly, while `\u2983\u2984` arguments are left partially applied:\n```lean\ndef foo {x : \u2115} : \u2115 := x\ndef bar \u2983x : \u2115\u2984 : \u2115 := x\n#check foo -- foo : \u2115\n#check bar -- bar : \u03a0 \u2983x : \u2115\u2984, \u2115\n```\n    -/\ninductive binder_info\n/- `(x : \u03b1)` -/\n| default\n/- `{x : \u03b1}` -/\n| implicit\n/- `\u2983x:\u03b1\u2984` -/\n| strict_implicit\n/- `[x : \u03b1]`. 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\u27e8\u03bb 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\u27e9\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 : (\u03b1 \u2192 \u03b1) \u2192 \u03b1 | 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 : \u2115)\n     #print foo.mynat\n     -- @[reducible]\n     -- def foo.mynat : foo \u2192 \u2115 :=\n     -- \u03bb (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 \u2192 expr\n/- A type universe: `Sort u` -/\n| sort        : level \u2192 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 \u2192 list level \u2192 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 \u22a2 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 \u2192 expr \u2192 expr\n/- Lambda abstraction. eg ```(\u03bb a : \u03b1, x)`` -/\n| lam        (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr\n/- Pi type constructor. eg ```(\u03a0 a : \u03b1, x)`` and ```(\u03b1 \u2192 \u03b2)`` -/\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 \u2192 list expr \u2192 expr\n\nvariable {elab : bool}\n\nmeta instance : inhabited (expr elab) := \u27e8expr.sort level.zero\u27e9\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 `(\u03bb 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 \u2192 option (name \u00d7 expr elab)\n\nmeta constant expr.is_string_macro : expr elab \u2192 option (expr elab)\n\n/-- Remove all macro annotations from the given `expr`. -/\nmeta def expr.erase_annotations : expr elab \u2192 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 \u2192 expr \u2192 bool\nnotation a ` =\u2090 `:50 b:50 := expr.alpha_eqv a b = bool.tt\n\nprotected meta constant expr.to_string : expr elab \u2192 string\n\nmeta instance : has_to_string (expr elab) := \u27e8expr.to_string\u27e9\nmeta instance : has_to_format (expr elab) := \u27e8\u03bb e, e.to_string\u27e9\n\n/-- Coercion for letting users write (f a) instead of (expr.app f a) -/\nmeta instance : has_coe_to_fun (expr elab) (\u03bb e, expr elab \u2192 expr elab) :=\n\u27e8\u03bb e, expr.app e\u27e9\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 \u2192 nat\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nmeta constant expr.lt : expr \u2192 expr \u2192 bool\n/-- Compares expressions, ignoring binder names. -/\nmeta constant expr.lex_lt : expr \u2192 expr \u2192 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 {\u03b1 : Type} : expr \u2192 \u03b1 \u2192 (expr \u2192 nat \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1\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 \u2192 (expr \u2192 nat \u2192 option expr) \u2192 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 \u2192 name \u2192 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 \u2192 list name \u2192 expr\n/-- `abstract e x` Abstracts the expression `e` over the local constant `x`.  -/\nmeta def expr.abstract : expr \u2192 expr \u2192 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\u2081,l\u2081), ...]` will traverse `e` and replace any universe parameters with name `n\u1d62` with the corresponding level `l\u1d62`.  -/\nmeta constant expr.instantiate_univ_params : expr \u2192 list (name \u00d7 level) \u2192 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 \u2192 expr \u2192 expr \u2192 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 \u2192 expr \u2192 expr\n/-- ``instantiate_vars `(#0 #1 #2) [x,y,z] = `(%%x %%y %%z)`` -/\nmeta constant expr.instantiate_vars        : expr \u2192 list expr \u2192 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 \u2192 nat \u2192 list expr \u2192 expr\n/-- Perform beta-reduction if the left expression is a lambda, or construct an application otherwise.\nThat is: ``expr.subst `(\u03bb x, %%Y) Z = Y[x/Z]``, and\n``expr.subst X Z = X.app Z`` otherwise -/\nprotected meta constant expr.subst : expr elab \u2192 expr elab \u2192 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 \u2192 nat\n/-- `has_var e` returns true iff e has free variables. -/\nmeta constant expr.has_var       : expr \u2192 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 \u2192 nat \u2192 bool\n/-- `has_local e` returns true if `e` contains a local constant. -/\nmeta constant expr.has_local     : expr \u2192 bool\n/-- `has_meta_var e` returns true iff `e` contains a metavariable. -/\nmeta constant expr.has_meta_var  : expr \u2192 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 `(\u03bb x, #2 #1 #0) 1 1 = `(\u03bb x, #1 #1 #0 )``\n    -/\nmeta constant expr.lower_vars    : expr \u2192 nat \u2192 nat \u2192 expr\n/-- Lifts free variables. `lift_vars e s d` will lift all free variables with index `\u2265 s` in `e` by `d`. -/\nmeta constant expr.lift_vars     : expr \u2192 nat \u2192 nat \u2192 expr\n/-- Get the position of the given expression in the Lean source file, if anywhere. -/\nprotected meta constant expr.pos : expr elab \u2192 option pos\n/-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/\nmeta constant expr.copy_pos_info : expr \u2192 expr \u2192 expr\n/-- Returns `some n` when the given expression is a constant with the name `..._cnstr.n`\n```\nis_internal_cnstr : expr \u2192 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 \u2192 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 \u2192 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 \u2192 list name\n/-- `occurs e t` returns `tt` iff `e` occurs in `t` up to \u03b1-equivalence. Purely structural: no unification or definitional equality. -/\nmeta constant expr.occurs        : expr \u2192 expr \u2192 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 \u2192 name_set \u2192 bool\n\n/-- Computes the number of sub-expressions (constant time). -/\nmeta constant expr.get_weight : expr \u2192 \u2115\n/-- Computes the maximum depth of the expression (constant time). -/\nmeta constant expr.get_depth : expr \u2192 \u2115\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 \u2192 list name \u2192 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 \u2192 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 {\u03b1 : Sort u} : \u03b1 \u2192 Type :=\n\u03bb _, expr\n\n@[inline] meta def reflected.to_expr {\u03b1 : Sort u} {a : \u03b1} : reflected a \u2192 expr :=\nid\n\n@[inline] meta def reflected.subst {\u03b1 : Sort v} {\u03b2 : \u03b1 \u2192 Sort u} {f : \u03a0 a : \u03b1, \u03b2 a} {a : \u03b1} :\n  reflected f \u2192 reflected a \u2192 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 {\u03b1 : Sort u} (a : \u03b1) : has_coe (reflected a) expr :=\n\u27e8reflected.to_expr\u27e9\n\nprotected meta def reflect {\u03b1 : Sort u} (a : \u03b1) [h : reflected a] : reflected a := h\n\nmeta instance {\u03b1} (a : \u03b1) : has_to_format (reflected a) :=\n\u27e8\u03bb h, to_fmt h.to_expr\u27e9\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\u03bb a b, bool.decidable_eq _ _\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nmeta instance : has_lt expr :=\n\u27e8 expr.lt_prop \u27e9\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 \u00d7 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 \u2192 bool\n| (var _) := tt\n| _       := ff\n\nmeta def app_of_list : expr \u2192 list expr \u2192 expr\n| f []      := f\n| f (p::ps) := app_of_list (f p) ps\n\nmeta def is_app : expr \u2192 bool\n| (app f a) := tt\n| e         := ff\n\nmeta def app_fn : expr \u2192 expr\n| (app f a) := f\n| a         := a\n\nmeta def app_arg : expr \u2192 expr\n| (app f a) := a\n| a         := a\n\nmeta def get_app_fn : expr elab \u2192 expr elab\n| (app f a) := get_app_fn f\n| a         := a\n\nmeta def get_app_num_args : expr \u2192 nat\n| (app f a) := get_app_num_args f + 1\n| e         := 0\n\nmeta def get_app_args_aux : list expr \u2192 expr \u2192 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 \u2192 list expr :=\nget_app_args_aux []\n\nmeta def mk_app : expr \u2192 list expr \u2192 expr\n| e []      := e\n| e (x::xs) := mk_app (e x) xs\n\nmeta def mk_binding (ctor : name \u2192 binder_info \u2192 expr \u2192 expr \u2192 expr) (e : expr) : \u03a0 (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 \u2192 nat \u2192 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 \u2192 name\n| (const n ls) := n\n| e            := name.anonymous\n\nmeta def is_constant : expr elab \u2192 bool\n| (const n ls) := tt\n| e            := ff\n\nmeta def is_local_constant : expr \u2192 bool\n| (local_const n m bi t) := tt\n| e                      := ff\n\nmeta def local_uniq_name : expr \u2192 name\n| (local_const n m bi t) := n\n| e                      := name.anonymous\n\nmeta def local_pp_name : expr elab \u2192 name\n| (local_const x n bi t) := n\n| e                      := name.anonymous\n\nmeta def local_type : expr elab \u2192 expr elab\n| (local_const _ _ _ t) := t\n| e := e\n\nmeta def is_aux_decl : expr \u2192 bool\n| (local_const _ _ binder_info.aux_decl _) := tt\n| _                                        := ff\n\nmeta def is_constant_of : expr elab \u2192 name \u2192 bool\n| (const n\u2081 ls) n\u2082 := n\u2081 = n\u2082\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 \u2227 get_app_num_args e = n\n\nmeta def is_false : expr \u2192 bool\n| `(false) := tt\n| _         := ff\n\nmeta def is_not : expr \u2192 option expr\n| `(not %%a)     := some a\n| `(%%a \u2192 false) := some a\n| e              := none\n\nmeta def is_and : expr \u2192 option (expr \u00d7 expr)\n| `(and %%\u03b1 %%\u03b2) := some (\u03b1, \u03b2)\n| _              := none\n\nmeta def is_or : expr \u2192 option (expr \u00d7 expr)\n| `(or %%\u03b1 %%\u03b2) := some (\u03b1, \u03b2)\n| _             := none\n\nmeta def is_iff : expr \u2192 option (expr \u00d7 expr)\n| `((%%a : Prop) \u2194 %%b) := some (a, b)\n| _                     := none\n\nmeta def is_eq : expr \u2192 option (expr \u00d7 expr)\n| `((%%a : %%_) = %%b) := some (a, b)\n| _                    := none\n\nmeta def is_ne : expr \u2192 option (expr \u00d7 expr)\n| `((%%a : %%_) \u2260 %%b) := some (a, b)\n| _                    := none\n\nmeta def is_bin_arith_app (e : expr) (op : name) : option (expr \u00d7 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 \u00d7 expr) :=\nis_bin_arith_app e ``has_lt.lt\n\nmeta def is_gt (e : expr) : option (expr \u00d7 expr) :=\nis_bin_arith_app e ``gt\n\nmeta def is_le (e : expr) : option (expr \u00d7 expr) :=\nis_bin_arith_app e ``has_le.le\n\nmeta def is_ge (e : expr) : option (expr \u00d7 expr) :=\nis_bin_arith_app e ``ge\n\nmeta def is_heq : expr \u2192 option (expr \u00d7 expr \u00d7 expr \u00d7 expr)\n| `(@heq %%\u03b1 %%a %%\u03b2 %%b) := some (\u03b1, a, \u03b2, b)\n| _                       := none\n\nmeta def is_lambda : expr \u2192 bool\n| (lam _ _ _ _) := tt\n| e             := ff\n\nmeta def is_pi : expr \u2192 bool\n| (pi _ _ _ _) := tt\n| e            := ff\n\nmeta def is_arrow : expr \u2192 bool\n| (pi _ _ _ b) := bnot (has_var b)\n| e            := ff\n\nmeta def is_let : expr \u2192 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 \u2192 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 \u2192 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 \u2192 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 \u2192 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 : \u2115 \u2192 expr \u2192 expr\n| (n + 1) (pi _ _ _ b) := nth_binding_body n b\n| _       e            := e\n\nmeta def is_macro : expr \u2192 bool\n| (macro d a) := tt\n| e           := ff\n\nmeta def is_numeral : expr \u2192 bool\n| `(@has_zero.zero %%\u03b1 %%s)  := tt\n| `(@has_one.one %%\u03b1 %%s)    := tt\n| `(@bit0 %%\u03b1 %%s %%v)       := is_numeral v\n| `(@bit1 %%\u03b1 %%s\u2081 %%s\u2082 %%v) := is_numeral v\n| _                          := ff\n\nmeta def pi_arity : expr \u2192 \u2115\n| (pi _ _ _ b) := pi_arity b + 1\n| _            := 0\n\nmeta def lam_arity : expr \u2192 \u2115\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 \u2192 expr \u2192 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 \u2192 expr \u2192 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 \u2192 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 \u2192 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 \u2192 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 {\u03b1 : Type} {m : Type \u2192 Type} [monad m] (e : expr) (a : \u03b1) (fn : expr \u2192 nat \u2192 \u03b1 \u2192 m \u03b1) : m \u03b1 :=\nfold e (return a) (\u03bb 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": "import system.io\nimport data.list\nimport ..utils.util\n\n-- file system utils\n\nmeta def write_line_to_file (dest : string) (msg : string) : io unit := do\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n  io.fs.put_str_ln_flush dest_handle msg\n\nmeta def write_to_file (dest : string) (msg : string) : io unit := do\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n  io.fs.put_str_flush dest_handle msg\n\nmeta def append_line_to_file (dest : string) (msg : string) : io unit := do\n  dest_handle \u2190 io.mk_file_handle dest io.mode.append,\n  io.fs.put_str_ln_flush dest_handle msg\n\nmeta def append_to_file (dest : string) (msg : string) : io unit := do\n  dest_handle \u2190 io.mk_file_handle dest io.mode.append,\n  io.fs.put_str_flush dest_handle msg\n\n-- printing utils\n\nsection pp\n\nmeta def enable_verbose : tactic unit := do {\n  -- jesse's pp settings\n  tactic.set_bool_option `pp.all true,\n  tactic.set_bool_option `pp.implicit true, -- TODO(): can we get away with setting this `false`? this blows up the proof terms by a LOT\n  tactic.set_bool_option `pp.universes false,\n  tactic.set_bool_option `pp.notation true,\n  tactic.set_bool_option `pp.generalized_field_notation true,\n  tactic.set_bool_option `pp.structure_projections true,\n  tactic.set_bool_option `pp.beta true,\n  tactic.set_bool_option `pp.binder_types true,\n  tactic.set_nat_option `pp.max_depth 128,\n  tactic.set_nat_option `pp.max_steps 10000\n}\n\nmeta def with_verbose {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 :=\ntactic.save_options $ enable_verbose *> tac\n\nend pp\n\nmeta def pp_expr (e : expr): tactic string := do\n  fmt <- tactic.pp e,\n  return (to_string fmt)\n\nmeta def print_decl_info (d : declaration) : tactic unit := do\n  let tp := d.type,\n  let v := d.value,\n  let univ_params := v.collect_univ_params,\n  tactic.trace v.to_raw_fmt\n\n-- extracting library theorems\n\nmeta def process_thm (d : declaration) : option declaration :=\nlet n := d.to_name in\n  if \u00ac d.is_trusted \u2228 n.is_internal then none\n  else match d with\n       | declaration.defn _ _ _ _ _ _ := none\n       | t@(declaration.thm n ns e te) := some t\n       | declaration.cnst _ _ _ _ := none\n       | declaration.ax _ _ _ := none\n       end\n\nmeta def library_thms : tactic $ list declaration :=\n  environment.decl_filter_map <$> tactic.get_env <*> return process_thm\n\nmeta def filter_non_theorems (d : declaration) : option declaration :=\n  if d.is_theorem then some d else none\n\nmeta def decl_to_proof (d : declaration) : tactic expr := return d.value\n\nmeta def decl_to_name (d : declaration) : tactic string := return d.to_name.to_string\n\nmeta def decl_to_theorem (d : declaration) : tactic expr := return d.type\n\nmeta def decl_to_inferred_theorem (d : declaration) : tactic expr := tactic.infer_type d.value\n\nmeta def cache_subproof_if_prop : expr -> string -> tactic unit := \u03bb e decl_name, do\n  is_proof <- tactic.is_proof e <|> return ff,\n  proof <- pp_expr e,\n  if is_proof && (proof.length < 2048)\n  then tactic.unsafe_run_io (append_line_to_file (\"output/proofs/\" ++ decl_name ++ \".txt\") (proof ++ \";\\n\"))\n    >> tactic.unsafe_run_io (append_line_to_file (\"output/type_universe_variables/\" ++ decl_name ++ \".txt\") e.collect_univ_params.to_string)\n  else return unit.star\n\nnamespace expr\nopen tactic\n\nmeta def replace_body : expr -> expr -> expr := \u03bb bindings new_body,\n  -- bindings, body => new expr where body is attached to bindings\n  match bindings with\n    -- CASE: lam ... (lam ...)\n    | lam var_name b_info var_type (lam var_name' b_info' var_type' body') := \n        lam var_name b_info var_type (replace_body (lam var_name' b_info' var_type' body') new_body)\n    -- CASE: lam ... (pi ...)\n    | lam var_name b_info var_type (pi var_name' b_info' var_type' body') := \n        lam var_name b_info var_type (replace_body (pi var_name' b_info' var_type' body') new_body)\n    -- CASE: pi ... (lam ...)\n    | pi var_name b_info var_type (lam var_name' b_info' var_type' body') := \n        pi var_name b_info var_type (replace_body (lam var_name' b_info' var_type' body') new_body)\n    -- CASE: pi ... (pi ...)\n    | pi var_name b_info var_type (pi var_name' b_info' var_type' body') := \n        pi var_name b_info var_type (replace_body (pi var_name' b_info' var_type' body') new_body)\n    -- BASE CASE: lam ... (not lam/pi ...)\n    | lam var_name b_info var_type _ := \n        lam var_name b_info var_type new_body\n    -- BASE CASE: pi ... (not lam/pi ...)\n    | pi var_name b_info var_type _ := \n        pi var_name b_info var_type new_body\n    -- dummy case (this should never happen)\n    -- TODO: throw exception\n    | _ := new_body\n  end\n\nmeta def traverse_subexpressions_aux : expr -> expr -> string -> tactic unit :=  \u03bb bindings tree decl_name,\n\n  match tree with\n\n    -- CASE: lam \n    | e@(lam var_name b_info var_type body) := do\n      let this_lam := (lam var_name b_info var_type (var 0)),\n      let new_bindings := replace_body bindings this_lam,\n      cache_subproof_if_prop (replace_body bindings e) decl_name,\n      traverse_subexpressions_aux new_bindings var_type decl_name,\n      traverse_subexpressions_aux new_bindings body decl_name\n\n    -- CASE: pi \n    | e@(pi var_name b_info var_type body) := do\n      let this_pi := (lam var_name b_info var_type (var 0)),\n      let new_bindings := replace_body bindings this_pi,\n      cache_subproof_if_prop (replace_body bindings e) decl_name,\n      traverse_subexpressions_aux new_bindings var_type decl_name,\n      traverse_subexpressions_aux new_bindings body decl_name\n\n    -- CASE : app\n    | e@(app func arg) := do\n      cache_subproof_if_prop (replace_body bindings e) decl_name,\n      traverse_subexpressions_aux bindings func decl_name,\n      traverse_subexpressions_aux bindings arg decl_name\n\n    -- CASE : elet\n    | e@(elet var_name type assignment body) := do\n      cache_subproof_if_prop (replace_body bindings e) decl_name,\n      traverse_subexpressions_aux bindings type decl_name,\n      traverse_subexpressions_aux bindings assignment decl_name,\n      traverse_subexpressions_aux bindings body decl_name\n\n    | _ := do\n      return unit.star\n  end\n\nmeta def traverse_subexpressions : nat -> (expr \u00d7 string) -> tactic unit := \n  \u03bb max_proof_len proof_and_name, do\n    let proof := proof_and_name.1,\n    let name := proof_and_name.2,\n    proof_string <- pp_expr proof,\n    if proof_string.length < 4096\n      then \n        traverse_subexpressions_aux (var 0) proof name\n      else \n        return unit.star\n\nend expr\n\nmeta def main : tactic unit := do\n\n  -- get cmdline args\n  args <- tactic.unsafe_run_io (io.cmdline_args),\n  num_proofs \u2190 tactic.unsafe_run_io (args.nth_partial 0 \"num_proofs\"),\n  max_proof_len \u2190 tactic.unsafe_run_io (args.nth_partial 1 \"max_proof_len\"),\n  let num_proofs := string.to_nat num_proofs, \n  let max_proof_len := string.to_nat max_proof_len, \n\n  -- set pp options\n  os <- tactic.get_options,\n  let os := os.set_bool `pp.all true,\n  let os := os.set_bool `pp.implicit true, -- TODO(): can we get away with setting this `false`? this blows up the proof terms by a LOT\n  let os := os.set_bool `pp.universes false,\n  let os := os.set_bool `pp.notation true,\n  let os := os.set_bool `pp.generalized_field_notation true,\n  let os := os.set_bool `pp.structure_projections true,\n  let os := os.set_bool `pp.beta true,\n  let os := os.set_bool `pp.binder_types true,\n  let os := os.set_nat `pp.max_depth 128,\n  let os := os.set_nat `pp.max_steps 10000,\n  tactic.set_options os,\n  \n  -- get proof terms\n  env <- tactic.get_env,\n  let ds := env.decl_filter_map filter_non_theorems,\n  proofs <- ds.traverse decl_to_proof,\n  names <- ds.traverse decl_to_name,\n  let proofs_and_names := list.zip proofs names,\n  -- traverse subexpressions in each proof term\n  (list.take num_proofs proofs_and_names).traverse (expr.traverse_subexpressions max_proof_len),\n  tactic.trace \"\"\n\n\n-- TESTS ----------------------------------------------------------------------------------------\n\n-- #eval do\n--   let e := (expr.lam (mk_simple_name \"b\") binder_info.implicit (expr.const `bool [])\n--             (expr.app\n--               (expr.app\n--               (expr.app (expr.const `eq.mp [level.zero])\n--                 (expr.app (expr.const `not []) (expr.app (expr.app (expr.app (expr.const `eq [level.succ level.zero]) (expr.const `bool [])) (@expr.var tt 0)) (expr.const `bool.tt []))))\n--               (expr.app (expr.app (expr.app (expr.const `eq [level.succ level.zero]) (expr.const `bool [])) (@expr.var tt 0)) (expr.const `bool.ff [])))\n--               (expr.app (expr.const `eq_ff_eq_not_eq_tt []) (@expr.var tt 0)))),\n--   traverse_subexpressions_aux (var 0) e \n\n-- run_cmd trace $\n--     replace_body (\n--       extract_bindings $\n--       lam `\u03b1 binder_info.default (expr.sort level.zero) $\n--       lam `\u03b2 binder_info.default (expr.sort level.zero) $\n--       var 0) $ (const `eq.mp [])\n", "meta": {"author": "joepalermo", "repo": "synthetic-proof-term-data-augmentation", "sha": "c82d77478d26d196e561c7df6ee08bd31ef813a3", "save_path": "github-repos/lean/joepalermo-synthetic-proof-term-data-augmentation", "path": "github-repos/lean/joepalermo-synthetic-proof-term-data-augmentation/synthetic-proof-term-data-augmentation-c82d77478d26d196e561c7df6ee08bd31ef813a3/src/data_bootstrap_pipeline/extract_subproofs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26284183737131667, "lm_q2_score": 0.04084571955862391, "lm_q1q2_score": 0.010735963977542234}}
{"text": "-- Many many thanks to Rob Lewis for supplying 99.9% of this file.\n\nimport tactic.modded tactic.apply\n\nopen tactic\n\nmeta def copy_decl (d : declaration) : tactic unit :=\nadd_decl $ d.update_name $ d.to_name.update_prefix `nat_num_game.interactive\n\n@[reducible] meta def filter (d : declaration) : bool :=\nd.to_name \u2209 [`tactic.interactive.induction, \n             `tactic.interactive.cases, \n             `tactic.interactive.rw, \n             `tactic.interactive.symmetry,\n             `tactic.interactive.use]\n\nmeta def copy_decls : tactic unit :=\ndo env \u2190 get_env,\n  let ls := env.fold [] list.cons,\n  ls.mmap' $ \u03bb dec, when (dec.to_name.get_prefix = `tactic.interactive \u2227 filter dec) (copy_decl dec)\n\n@[reducible] meta def nat_num_game := tactic\n\nnamespace nat_num_game\n\n--meta instance : monad nat_num_game := by delta nat_num_game; apply_instance\n\n--meta instance : alternative nat_num_game := by delta nat_num_game; apply_instance\n\nmeta def step {\u03b1} (c : nat_num_game \u03b1) : nat_num_game unit := \nc >> return ()\n\nmeta def istep := @tactic.istep\n\nmeta def save_info := tactic.save_info\n\nmeta def execute (c : nat_num_game unit) : nat_num_game unit := \nc\n\nmeta def execute_with := @smt_tactic.execute_with\n--meta def trace_state {\u03b1 : Type}\n\nmeta def solve1 := @tactic.solve1\n\nend nat_num_game\n\n--#check tactic.interactive.induction\n\nnamespace nat_num_game.interactive\n\nmeta def induction\n:= tactic.interactive.induction'\n\nmeta def cases\n:= tactic.interactive.cases'\n\nmeta def rw\n:= tactic.interactive.rw'\n\nmeta def symmetry\n:= tactic.interactive.symmetry'\n\nmeta def use\n:= tactic.interactive.use'\n\nend nat_num_game.interactive\n\nrun_cmd copy_decls\n\n--TODO : why is this broken?\n--#print tactic.interactive.rintro\n\n--#exit\n\n-- example just to check it's running\n-- example (n : \u2115) : true :=\n-- begin [nat_num_game]\n--   induction n,\n--     sorry, sorry  \n-- end\n", "meta": {"author": "ImperialCollegeLondon", "repo": "natural_number_game", "sha": "f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd", "save_path": "github-repos/lean/ImperialCollegeLondon-natural_number_game", "path": "github-repos/lean/ImperialCollegeLondon-natural_number_game/natural_number_game-f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd/src/tactic/nat_num_game.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.212068814316781, "lm_q2_score": 0.050330631707179815, "lm_q1q2_score": 0.010673557389956206}}
{"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.Data.LOption\nimport Lean.Environment\nimport Lean.Class\nimport Lean.ReducibilityAttrs\nimport Lean.Util.Trace\nimport Lean.Util.RecDepth\nimport Lean.Util.PPExt\nimport Lean.Util.OccursCheck\nimport Lean.Util.MonadBacktrack\nimport Lean.Compiler.InlineAttrs\nimport Lean.Meta.TransparencyMode\nimport Lean.Meta.DiscrTreeTypes\nimport Lean.Eval\nimport Lean.CoreM\n\n/-\nThis module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.\n1- Weak head normal form computation with support for metavariables and transparency modes.\n2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).\n3- Type inference.\n4- Type class resolution.\n\nThey are packed into the MetaM monad.\n-/\n\nnamespace Lean.Meta\n\nbuiltin_initialize isDefEqStuckExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `isDefEqStuck\n\nstructure Config where\n  foApprox           : Bool := false\n  ctxApprox          : Bool := false\n  quasiPatternApprox : Bool := false\n  /-- When `constApprox` is set to true,\n     we solve `?m t =?= c` using\n     `?m := fun _ => c`\n     when `?m t` is not a higher-order pattern and `c` is not an application as -/\n  constApprox        : Bool := false\n  /--\n    When the following flag is set,\n    `isDefEq` throws the exeption `Exeption.isDefEqStuck`\n    whenever it encounters a constraint `?m ... =?= t` where\n    `?m` is read only.\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  isDefEqStuckEx     : Bool := false\n  transparency       : TransparencyMode := TransparencyMode.default\n  /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/\n  zetaNonDep         : Bool := true\n  /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/\n  trackZeta          : Bool := false\n  unificationHints   : Bool := true\n  /-- Enables proof irrelevance at `isDefEq` -/\n  proofIrrelevance   : Bool := true\n  /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make\n      sure typing constraints resolved during elaboration should not \"fill\" holes that are supposed to be filled using tactics.\n      However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill\n      named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify\n      the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because\n      this last unification step is not really part of the term elaboration. -/\n  assignSyntheticOpaque : Bool := false\n  /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth\n      can be assigned.\n      We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few\n      cases. Recall that universe levels are often ignored by users, they may not even be aware they exist.\n      We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`.\n      We claim it is reasonable to ignore this restriction for universe metavariables because their values are often\n      contrained by the terms is instances and simp theorems.\n      TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests.\n  -/\n  ignoreLevelMVarDepth  : Bool := true\n  /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/\n  offsetCnstrs          : Bool := true\n\nstructure ParamInfo where\n  binderInfo     : BinderInfo := BinderInfo.default\n  hasFwdDeps     : Bool       := false\n  backDeps       : Array Nat  := #[]\n  deriving Inhabited\n\ndef ParamInfo.isImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.implicit\n\ndef ParamInfo.isInstImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.instImplicit\n\ndef ParamInfo.isStrictImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.strictImplicit\n\ndef ParamInfo.isExplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl\n\nstructure FunInfo where\n  paramInfo  : Array ParamInfo := #[]\n  resultDeps : Array Nat       := #[]\n\nstructure InfoCacheKey where\n  transparency : TransparencyMode\n  expr         : Expr\n  nargs?       : Option Nat\n  deriving Inhabited, BEq\n\nnamespace InfoCacheKey\ninstance : Hashable InfoCacheKey :=\n  \u27e8fun \u27e8transparency, expr, nargs\u27e9 => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)\u27e9\nend InfoCacheKey\n\nopen Std (PersistentArray PersistentHashMap)\n\nabbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)\n\nabbrev InferTypeCache := PersistentExprStructMap Expr\nabbrev FunInfoCache   := PersistentHashMap InfoCacheKey FunInfo\nabbrev WhnfCache      := PersistentExprStructMap Expr\n\n/- A set of pairs. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache).\n   We should also investigate the impact on memory consumption. -/\nabbrev DefEqCache := PersistentHashMap (Expr \u00d7 Expr) Unit\n\nstructure Cache where\n  inferType     : InferTypeCache := {}\n  funInfo       : FunInfoCache   := {}\n  synthInstance : SynthInstanceCache := {}\n  whnfDefault   : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`\n  whnfAll       : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`\n  defEqDefault  : DefEqCache := {}\n  defEqAll      : DefEqCache := {}\n  deriving Inhabited\n\n/--\n \"Context\" for a postponed universe constraint.\n `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.\n-/\nstructure DefEqContext where\n  lhs            : Expr\n  rhs            : Expr\n  lctx           : LocalContext\n  localInstances : LocalInstances\n\n/--\n  Auxiliary structure for representing postponed universe constraints.\n  Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.\n  Remark: we may consider improving the error message generation in the future.\n-/\nstructure PostponedEntry where\n  ref  : Syntax -- We save the `ref` at entry creation time\n  lhs  : Level\n  rhs  : Level\n  ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created\n  deriving Inhabited\n\nstructure State where\n  mctx        : MetavarContext := {}\n  cache       : Cache := {}\n  /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/\n  zetaFVarIds : FVarIdSet := {}\n  postponed   : PersistentArray PostponedEntry := {}\n  deriving Inhabited\n\nstructure SavedState where\n  core        : Core.State\n  meta        : State\n  deriving Inhabited\n\nstructure Context where\n  config            : Config               := {}\n  lctx              : LocalContext         := {}\n  localInstances    : LocalInstances       := #[]\n  /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/\n  defEqCtx?         : Option DefEqContext  := none\n  /--\n    Track the number of nested `synthPending` invocations. Nested invocations can happen\n    when the type class resolution invokes `synthPending`.\n\n    Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`.\n    We will add a configuration option if necessary. -/\n  synthPendingDepth : Nat                  := 0\n\nabbrev MetaM  := ReaderT Context $ StateRefT State CoreM\n\n-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the\n-- whole monad stack at every use site. May eventually be covered by `deriving`.\ninstance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind }\n\ninstance : Inhabited (MetaM \u03b1) where\n  default := fun _ _ => arbitrary\n\ninstance : MonadLCtx MetaM where\n  getLCtx := return (\u2190 read).lctx\n\ninstance : MonadMCtx MetaM where\n  getMCtx    := return (\u2190 get).mctx\n  modifyMCtx f := modify fun s => { s with mctx := f s.mctx }\n\ninstance : AddMessageContext MetaM where\n  addMessageContext := addMessageContextFull\n\nprotected def saveState : MetaM SavedState :=\n  return { core := (\u2190 getThe Core.State), meta := (\u2190 get) }\n\n/-- Restore backtrackable parts of the state. -/\ndef SavedState.restore (b : SavedState) : MetaM Unit := do\n  Core.restore b.core\n  modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }\n\ninstance : MonadBacktrack SavedState MetaM where\n  saveState      := Meta.saveState\n  restoreState s := s.restore\n\n@[inline] def MetaM.run (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM (\u03b1 \u00d7 State) :=\n  x ctx |>.run s\n\n@[inline] def MetaM.run' (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM \u03b1 :=\n  Prod.fst <$> x.run ctx s\n\n@[inline] def MetaM.toIO (x : MetaM \u03b1) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (\u03b1 \u00d7 Core.State \u00d7 State) := do\n  let ((a, s), sCore) \u2190 (x.run ctx s).toIO ctxCore sCore\n  pure (a, sCore, s)\n\ninstance [MetaEval \u03b1] : MetaEval (MetaM \u03b1) :=\n  \u27e8fun env opts x _ => MetaEval.eval env opts x.run' true\u27e9\n\nprotected def throwIsDefEqStuck : MetaM \u03b1 :=\n  throw <| Exception.internal isDefEqStuckExceptionId\n\nbuiltin_initialize\n  registerTraceClass `Meta\n  registerTraceClass `Meta.debug\n\n@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM \u03b1) : m \u03b1 :=\n  liftM x\n\n@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, MetaM \u03b1 \u2192 MetaM \u03b1) {\u03b1} (x : m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f <| runInBase x\n\n@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b => runInBase <| k b\n\n@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 \u03b3 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 \u03b3 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c\n\nsection Methods\nvariable [MonadControlT MetaM n] [Monad n]\n\n@[inline] def modifyCache (f : Cache \u2192 Cache) : MetaM Unit :=\n  modify fun \u27e8mctx, cache, zetaFVarIds, postponed\u27e9 => \u27e8mctx, f cache, zetaFVarIds, postponed\u27e9\n\n@[inline] def modifyInferTypeCache (f : InferTypeCache \u2192 InferTypeCache) : MetaM Unit :=\n  modifyCache fun \u27e8ic, c1, c2, c3, c4, c5, c6\u27e9 => \u27e8f ic, c1, c2, c3, c4, c5, c6\u27e9\n\ndef getLocalInstances : MetaM LocalInstances :=\n  return (\u2190 read).localInstances\n\ndef getConfig : MetaM Config :=\n  return (\u2190 read).config\n\ndef setMCtx (mctx : MetavarContext) : MetaM Unit :=\n  modify fun s => { s with mctx := mctx }\n\ndef resetZetaFVarIds : MetaM Unit :=\n  modify fun s => { s with zetaFVarIds := {} }\n\ndef getZetaFVarIds : MetaM FVarIdSet :=\n  return (\u2190 get).zetaFVarIds\n\ndef getPostponed : MetaM (PersistentArray PostponedEntry) :=\n  return (\u2190 get).postponed\n\ndef setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := postponed }\n\n@[inline] def modifyPostponed (f : PersistentArray PostponedEntry \u2192 PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := f s.postponed }\n\n/- WARNING: The following 4 constants are a hack for simulating forward declarations.\n   They are defined later using the `export` attribute. This is hackish because we\n   have to hard-code the true arity of these definitions here, and make sure the C names match.\n   We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/\n@[extern 6 \"lean_whnf\"] constant whnf : Expr \u2192 MetaM Expr\n@[extern 6 \"lean_infer_type\"] constant inferType : Expr \u2192 MetaM Expr\n@[extern 7 \"lean_is_expr_def_eq\"] constant isExprDefEqAux : Expr \u2192 Expr \u2192 MetaM Bool\n@[extern 6 \"lean_synth_pending\"] protected constant synthPending : MVarId \u2192 MetaM Bool\n\ndef whnfForall (e : Expr) : MetaM Expr := do\n  let e' \u2190 whnf e\n  if e'.isForall then pure e' else pure e\n\n-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`\nprotected def withIncRecDepth (x : n \u03b1) : n \u03b1 :=\n  mapMetaM (withIncRecDepth (m := MetaM)) x\n\nprivate def mkFreshExprMVarAtCore\n    (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do\n  modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;\n  return mkMVar mvarId\n\ndef mkFreshExprMVarAt\n    (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  mkFreshExprMVarAtCore (\u2190 mkFreshMVarId) lctx localInsts type kind userName numScopeArgs\n\ndef mkFreshLevelMVar : MetaM Level := do\n  let mvarId \u2190 mkFreshMVarId\n  modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;\n  return mkLevelMVar mvarId\n\nprivate def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do\n  mkFreshExprMVarAt (\u2190 getLCtx) (\u2190 getLocalInstances) type kind userName\n\nprivate def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarCore type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous\n    mkFreshExprMVarCore type kind userName\n\ndef mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  mkFreshExprMVarImpl type? kind userName\n\ndef mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  mkFreshExprMVar (mkSort u) kind userName\n\n/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create\n   the metavar using this method. -/\nprivate def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  mkFreshExprMVarAtCore mvarId (\u2190 getLCtx) (\u2190 getLocalInstances) type kind userName numScopeArgs\n\ndef mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarWithIdCore mvarId type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVar (mkSort u)\n    mkFreshExprMVarWithIdCore mvarId type kind userName\n\ndef mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=\n  num.foldM (init := []) fun _ us =>\n    return (\u2190 mkFreshLevelMVar)::us\n\ndef mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=\n  mkFreshLevelMVars info.numLevelParams\n\ndef mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do\n  let info \u2190 getConstInfo declName\n  return mkConst declName (\u2190 mkFreshLevelMVarsFor info)\n\ndef getTransparency : MetaM TransparencyMode :=\n  return (\u2190 getConfig).transparency\n\ndef shouldReduceAll : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.all\n\ndef shouldReduceReducibleOnly : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.reducible\n\ndef getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do\n  match (\u2190 getMCtx).findDecl? mvarId with\n  | some d => pure d\n  | none   => throwError \"unknown metavariable '?{mvarId.name}'\"\n\ndef setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.setMVarKind mvarId kind\n\n/- Update the type of the given metavariable. This function assumes the new type is\n   definitionally equal to the current one -/\ndef setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.setMVarType mvarId type\n\ndef isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do\n  return (\u2190 getMVarDecl mvarId).depth != (\u2190 getMCtx).depth\n\ndef isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  match mvarDecl.kind with\n  | MetavarKind.syntheticOpaque => return !(\u2190 getConfig).assignSyntheticOpaque\n  | _ => return mvarDecl.depth != (\u2190 getMCtx).depth\n\ndef getLevelMVarDepth (mvarId : MVarId) : MetaM Nat := do\n  match (\u2190 getMCtx).findLevelDepth? mvarId with\n  | some depth => return depth\n  | _          => throwError \"unknown universe metavariable '?{mvarId.name}'\"\n\ndef isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do\n  if (\u2190 getConfig).ignoreLevelMVarDepth then\n    return false\n  else\n    return (\u2190 getLevelMVarDepth mvarId) != (\u2190 getMCtx).depth\n\ndef renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName\n\ndef isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).isExprAssigned mvarId\n\ndef getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=\n  return (\u2190 getMCtx).getExprAssignment? mvarId\n\n/-- Return true if `e` contains `mvarId` directly or indirectly -/\ndef occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=\n  return (\u2190 getMCtx).occursCheck mvarId e\n\ndef assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.assignExpr mvarId val\n\ndef isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).isDelayedAssigned mvarId\n\ndef getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=\n  return (\u2190 getMCtx).getDelayedAssignment? mvarId\n\ndef hasAssignableMVar (e : Expr) : MetaM Bool :=\n  return (\u2190 getMCtx).hasAssignableMVar e\n\ndef throwUnknownFVar (fvarId : FVarId) : MetaM \u03b1 :=\n  throwError \"unknown free variable '{mkFVar fvarId}'\"\n\ndef findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=\n  return (\u2190 getLCtx).find? fvarId\n\ndef getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).find? fvarId with\n  | some d => pure d\n  | none   => throwUnknownFVar fvarId\n\ndef getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=\n  getLocalDecl fvar.fvarId!\n\ndef getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).findFromUserName? userName with\n  | some d => pure d\n  | none   => throwError \"unknown local declaration '{userName}'\"\n\ndef instantiateLevelMVars (u : Level) : MetaM Level :=\n  MetavarContext.instantiateLevelMVars u\n\ndef instantiateMVars (e : Expr) : MetaM Expr :=\n  (MetavarContext.instantiateExprMVars e).run\n\ndef instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl :=\n  match localDecl with\n  | LocalDecl.cdecl idx id n type bi  =>\n    return LocalDecl.cdecl idx id n (\u2190 instantiateMVars type) bi\n  | LocalDecl.ldecl idx id n type val nonDep =>\n    return LocalDecl.ldecl idx id n (\u2190 instantiateMVars type) (\u2190 instantiateMVars val) nonDep\n\n@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM \u03b1) : MetaM \u03b1 := do\n  match x (\u2190 getLCtx) { mctx := (\u2190 getMCtx), ngen := (\u2190 getNGen) } with\n  | EStateM.Result.ok e newS => do\n    setNGen newS.ngen;\n    setMCtx newS.mctx;\n    pure e\n  | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do\n    setMCtx newS.mctx;\n    setNGen newS.ngen;\n    throwError \"failed to create binder due to failure when reverting variable dependencies\"\n\ndef abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr :=\n  liftMkBindingM <| MetavarContext.abstractRange e n xs\n\ndef abstract (e : Expr) (xs : Array Expr) : MetaM Expr :=\n  abstractRange e xs.size xs\n\ndef mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly\n\ndef mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly\n\ndef mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr :=\n  mkLambdaFVars xs e (usedLetOnly := usedLetOnly)\n\ndef mkArrow (d b : Expr) : MetaM Expr :=\n  return Lean.mkForall (\u2190 mkFreshUserName `x) BinderInfo.default d b\n\n/-- `fun _ : Unit => a` -/\ndef mkFunUnit (a : Expr) : MetaM Expr :=\n  return Lean.mkLambda (\u2190 mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a\n\ndef elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder\n\n@[inline] def withConfig (f : Config \u2192 Config) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })\n\n@[inline] def withTrackingZeta (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with trackZeta := true }) x\n\n@[inline] def withoutProofIrrelevance (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with proofIrrelevance := false }) x\n\n@[inline] def withTransparency (mode : TransparencyMode) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withConfig (fun config => { config with transparency := mode })\n\n@[inline] def withDefault (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.default x\n\n@[inline] def withReducible (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.reducible x\n\n@[inline] def withReducibleAndInstances (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.instances x\n\n@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n \u03b1) : n \u03b1 :=\n  withConfig\n    (fun config =>\n      let oldMode := config.transparency\n      let mode    := if oldMode.lt mode then mode else oldMode\n      { config with transparency := mode })\n    x\n\n/-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/\n@[inline] def withAssignableSyntheticOpaque (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun config => { config with assignSyntheticOpaque := true }) x\n\n/-- Save cache, execute `x`, restore cache -/\n@[inline] private def savingCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let savedCache := (\u2190 get).cache\n  try x finally modify fun s => { s with cache := savedCache }\n\n@[inline] def savingCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM savingCacheImpl\n\ndef getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  if (\u2190 shouldReduceAll) then\n    return some info\n  else\n    return none\n\nprivate def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getTransparency) with\n  | TransparencyMode.all => return some info\n  | TransparencyMode.default => return some info\n  | _ =>\n    if (\u2190 isReducible info.name) then\n      return some info\n    else\n      return none\n\n/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.\n   This method is only used to implement `isClassQuickConst?`.\n   It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and\n   `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/\nprivate def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getEnv).find? constName with\n  | some (info@(ConstantInfo.thmInfo _))  => getTheoremInfo info\n  | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info\n  | some info                             => pure (some info)\n  | none                                  => throwUnknownConstant constName\n\nprivate def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do\n  if isClass (\u2190 getEnv) constName then\n    pure (LOption.some constName)\n  else\n    match (\u2190 getConstTemp? constName) with\n    | some _ => pure LOption.undef\n    | none   => pure LOption.none\n\nprivate partial def isClassQuick? : Expr \u2192 MetaM (LOption Name)\n  | Expr.bvar ..         => pure LOption.none\n  | Expr.lit ..          => pure LOption.none\n  | Expr.fvar ..         => pure LOption.none\n  | Expr.sort ..         => pure LOption.none\n  | Expr.lam ..          => pure LOption.none\n  | Expr.letE ..         => pure LOption.undef\n  | Expr.proj ..         => pure LOption.undef\n  | Expr.forallE _ _ b _ => isClassQuick? b\n  | Expr.mdata _ e _     => isClassQuick? e\n  | Expr.const n _ _     => isClassQuickConst? n\n  | Expr.mvar mvarId _   => do\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => isClassQuick? val\n    | none     => pure LOption.none\n  | Expr.app f _ _       =>\n    match f.getAppFn with\n    | Expr.const n .. => isClassQuickConst? n\n    | Expr.lam ..     => pure LOption.undef\n    | _              => pure LOption.none\n\ndef saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do\n  let savedSythInstance := (\u2190 get).cache.synthInstance\n  modifyCache fun c => { c with synthInstance := {} }\n  pure savedSythInstance\n\ndef restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=\n  modifyCache fun c => { c with synthInstance := cache }\n\n@[inline] private def resettingSynthInstanceCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let savedSythInstance \u2190 saveAndResetSynthInstanceCache\n  try x finally restoreSynthInstanceCache savedSythInstance\n\n/-- Reset `synthInstance` cache, execute `x`, and restore cache -/\n@[inline] def resettingSynthInstanceCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM resettingSynthInstanceCacheImpl\n\n@[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n \u03b1) : n \u03b1 :=\n  if b then resettingSynthInstanceCache x else x\n\nprivate def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let localDecl \u2190 getFVarLocalDecl fvar\n  /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/\n  match localDecl.binderInfo with\n  | BinderInfo.auxDecl => k\n  | _ =>\n    resettingSynthInstanceCache <|\n      withReader\n        (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })\n        k\n\n/-- Add entry `{ className := className, fvar := fvar }` to localInstances,\n    and then execute continuation `k`.\n    It resets the type class cache using `resettingSynthInstanceCache`. -/\ndef withNewLocalInstance (className : Name) (fvar : Expr) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstanceImp className fvar\n\nprivate def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=\n  match maxFVars? with\n  | some maxFVars => fvars.size < maxFVars\n  | none          => true\n\nmutual\n  /--\n    `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances\n    using free variables `fvars[j] ... fvars.back`, and execute `k`.\n\n    - `isClassExpensive` is defined later.\n    - The type class chache is reset whenever a new local instance is found.\n    - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.\n      Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/\n  private partial def withNewLocalInstancesImp\n      (fvars : Array Expr) (i : Nat) (k : MetaM \u03b1) : MetaM \u03b1 := do\n    if h : i < fvars.size then\n      let fvar := fvars.get \u27e8i, h\u27e9\n      let decl \u2190 getFVarLocalDecl fvar\n      match (\u2190 isClassQuick? decl.type) with\n      | LOption.none   => withNewLocalInstancesImp fvars (i+1) k\n      | LOption.undef  =>\n        match (\u2190 isClassExpensive? decl.type) with\n        | none   => withNewLocalInstancesImp fvars (i+1) k\n        | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n      | LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n    else\n      k\n\n  /--\n    `forallTelescopeAuxAux lctx fvars j type`\n    Remarks:\n    - `lctx` is the `MetaM` local context extended with declarations for `fvars`.\n    - `type` is the type we are computing the telescope for. It contains only\n      dangling bound variables in the range `[j, fvars.size)`\n    - if `reducing? == true` and `type` is not `forallE`, we use `whnf`.\n    - when `type` is not a `forallE` nor it can't be reduced to one, we\n      excute the continuation `k`.\n\n    Here is an example that demonstrates the `reducing?`.\n    Suppose we have\n    ```\n    abbrev StateM s a := s -> Prod a s\n    ```\n    Now, assume we are trying to build the telescope for\n    ```\n    forall (x : Nat), StateM Int Bool\n    ```\n    if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.\n    if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`\n\n    if `maxFVars?` is `some max`, then we interrupt the telescope construction\n    when `fvars.size == max`\n  -/\n  private partial def forallTelescopeReducingAuxAux\n      (reducing          : Bool) (maxFVars? : Option Nat)\n      (type              : Expr)\n      (k                 : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM \u03b1 := do\n      match type with\n      | Expr.forallE n d b c =>\n        if fvarsSizeLtMaxFVars fvars maxFVars? then\n          let d     := d.instantiateRevRange j fvars.size fvars\n          let fvarId \u2190 mkFreshFVarId\n          let lctx  := lctx.mkLocalDecl fvarId n d c.binderInfo\n          let fvar  := mkFVar fvarId\n          let fvars := fvars.push fvar\n          process lctx fvars j b\n        else\n          let type := type.instantiateRevRange j fvars.size fvars;\n          withReader (fun ctx => { ctx with lctx := lctx }) do\n            withNewLocalInstancesImp fvars j do\n              k fvars type\n      | _ =>\n        let type := type.instantiateRevRange j fvars.size fvars;\n        withReader (fun ctx => { ctx with lctx := lctx }) do\n          withNewLocalInstancesImp fvars j do\n            if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then\n              let newType \u2190 whnf type\n              if newType.isForall then\n                process lctx fvars fvars.size newType\n              else\n                k fvars type\n            else\n              k fvars type\n    process (\u2190 getLCtx) #[] 0 type\n\n  private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    match maxFVars? with\n    | some 0 => k #[] type\n    | _ => do\n      let newType \u2190 whnf type\n      if newType.isForall then\n        forallTelescopeReducingAuxAux true maxFVars? newType k\n      else\n        k #[] type\n\n  private partial def isClassExpensive? : Expr \u2192 MetaM (Option Name)\n    | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.\n      forallTelescopeReducingAux type none fun xs type => do\n        let env \u2190 getEnv\n        match type.getAppFn with\n        | Expr.const c _ _ => do\n          if isClass env c then\n            return some c\n          else\n            -- make sure abbreviations are unfolded\n            match (\u2190 whnf type).getAppFn with\n            | Expr.const c _ _ => return if isClass env c then some c else none\n            | _ => return none\n        | _ => return none\n\n  private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do\n    match (\u2190 isClassQuick? type) with\n    | LOption.none   => pure none\n    | LOption.some c => pure (some c)\n    | LOption.undef  => isClassExpensive? type\n\nend\n\ndef isClass? (type : Expr) : MetaM (Option Name) :=\n  try isClassImp? type catch _ => pure none\n\nprivate def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImp fvars j\n\npartial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImpAux fvars j\n\n@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k\n\n/--\n  Given `type` of the form `forall xs, A`, execute `k xs A`.\n  This combinator will declare local declarations, create free variables for them,\n  execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/\ndef forallTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeImp type k) k\n\nprivate def forallTelescopeReducingImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type (maxFVars? := none) k\n\n/--\n  Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,\n  it reduces `A` and continues bulding the telescope if it is a `forall`. -/\ndef forallTelescopeReducing (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeReducingImp type k) k\n\nprivate def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type maxFVars? k\n\n/--\n  Similar to `forallTelescopeReducing`, stops constructing the telescope when\n  it reaches size `maxFVars`. -/\ndef forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k\n\nprivate partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  process consumeLet (\u2190 getLCtx) #[] 0 e\nwhere\n  process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM \u03b1 := do\n    match consumeLet, e with\n    | _, Expr.lam n d b c =>\n      let d := d.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshFVarId\n      let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo\n      let fvar := mkFVar fvarId\n      process consumeLet lctx (fvars.push fvar) j b\n    | true, Expr.letE n t v b _ => do\n      let t := t.instantiateRevRange j fvars.size fvars\n      let v := v.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshFVarId\n      let lctx := lctx.mkLetDecl fvarId n t v\n      let fvar := mkFVar fvarId\n      process true lctx (fvars.push fvar) j b\n    | _, e =>\n      let e := e.instantiateRevRange j fvars.size fvars\n      withReader (fun ctx => { ctx with lctx := lctx }) do\n        withNewLocalInstancesImp fvars j do\n          k fvars e\n\n/-- Similar to `forallTelescope` but for lambda and let expressions. -/\ndef lambdaLetTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp type true k) k\n\n/-- Similar to `forallTelescope` but for lambda expressions. -/\ndef lambdaTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp type false k) k\n\n/-- Return the parameter names for the givel global declaration. -/\ndef getParamNames (declName : Name) : MetaM (Array Name) := do\n  forallTelescopeReducing (\u2190 getConstInfo declName).type fun xs _ => do\n    xs.mapM fun x => do\n      let localDecl \u2190 getLocalDecl x.fvarId!\n      pure localDecl.userName\n\n-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.\nprivate partial def forallMetaTelescopeReducingAux\n    (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  process #[] #[] 0 e\nwhere\n  process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    if maxMVars?.isEqSome mvars.size then\n      let type := type.instantiateRevRange j mvars.size mvars;\n      return (mvars, bis, type)\n    else\n      match type with\n      | Expr.forallE n d b c =>\n        let d  := d.instantiateRevRange j mvars.size mvars\n        let k  := if c.binderInfo.isInstImplicit then  MetavarKind.synthetic else kind\n        let mvar \u2190 mkFreshExprMVar d k n\n        let mvars := mvars.push mvar\n        let bis   := bis.push c.binderInfo\n        process mvars bis j b\n      | _ =>\n        let type := type.instantiateRevRange j mvars.size mvars;\n        if reducing then do\n          let newType \u2190 whnf type;\n          if newType.isForall then\n            process mvars bis mvars.size newType\n          else\n            return (mvars, bis, type)\n        else\n          return (mvars, bis, type)\n\n/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/\ndef forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind\n\n/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/\ndef forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind\n\n/-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/\ndef forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind)\n\n/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/\npartial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  process #[] #[] 0 e\nwhere\n  process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    let finalize : Unit \u2192 MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := fun _ => do\n      let type := type.instantiateRevRange j mvars.size mvars\n      pure (mvars, bis, type)\n    if maxMVars?.isEqSome mvars.size then\n      finalize ()\n    else\n      match type with\n      | Expr.lam n d b c =>\n        let d     := d.instantiateRevRange j mvars.size mvars\n        let mvar \u2190 mkFreshExprMVar d\n        let mvars := mvars.push mvar\n        let bis   := bis.push c.binderInfo\n        process mvars bis j b\n      | _ => finalize ()\n\nprivate def withNewFVar (fvar fvarType : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  match (\u2190 isClass? fvarType) with\n  | none   => k fvar\n  | some c => withNewLocalInstance c fvar <| k fvar\n\nprivate def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshFVarId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLocalDecl fvarId n type bi\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar fvar type k\n\ndef withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  map1MetaM (fun k => withLocalDeclImp name bi type k) k\n\ndef withLocalDeclD (name : Name) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecl name BinderInfo.default type k\n\npartial def withLocalDecls\n    [Inhabited \u03b1]\n    (declInfos : Array (Name \u00d7 BinderInfo \u00d7 (Array Expr \u2192 n Expr)))\n    (k : (xs : Array Expr) \u2192 n \u03b1)\n    : n \u03b1 :=\n  loop #[]\nwhere\n  loop [Inhabited \u03b1] (acc : Array Expr) : n \u03b1 := do\n    if acc.size < declInfos.size then\n      let (name, bi, typeCtor) := declInfos[acc.size]\n      withLocalDecl name bi (\u2190typeCtor acc) fun x => loop (acc.push x)\n    else\n      k acc\n\ndef withLocalDeclsD [Inhabited \u03b1] (declInfos : Array (Name \u00d7 (Array Expr \u2192 n Expr))) (k : (xs : Array Expr) \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecls\n    (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k\n\nprivate def withNewBinderInfosImp (bs : Array (FVarId \u00d7 BinderInfo)) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let lctx := bs.foldl (init := (\u2190 getLCtx)) fun lctx (fvarId, bi) =>\n      lctx.setBinderInfo fvarId bi\n  withReader (fun ctx => { ctx with lctx := lctx }) k\n\ndef withNewBinderInfos (bs : Array (FVarId \u00d7 BinderInfo)) (k : n \u03b1) : n \u03b1 :=\n  mapMetaM (fun k => withNewBinderInfosImp bs k) k\n\nprivate def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshFVarId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLetDecl fvarId n type val\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar fvar type k\n\ndef withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  map1MetaM (fun k => withLetDeclImp name type val k) k\n\nprivate def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let ctx \u2190 read\n  let numLocalInstances := ctx.localInstances.size\n  let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    let newLocalInsts \u2190 decls.foldlM\n      (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {\n        match (\u2190 isClass? decl.type) with\n        | none   => pure newlocalInsts\n        | some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))\n      ctx.localInstances;\n    if newLocalInsts.size == numLocalInstances then\n      k\n    else\n      resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k\n\ndef withExistingLocalDecls (decls : List LocalDecl) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withExistingLocalDeclsImp decls\n\nprivate def withNewMCtxDepthImp (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let saved \u2190 get\n  modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} }\n  try\n    x\n  finally\n    modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }\n\n/--\n  Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,\n  and restore saved data. -/\ndef withNewMCtxDepth : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM withNewMCtxDepthImp\n\nprivate def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let localInstsCurr \u2190 getLocalInstances\n  withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do\n    if localInsts == localInstsCurr then\n      x\n    else\n      resettingSynthInstanceCache x\n\ndef withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withLocalContextImp lctx localInsts\n\nprivate def withMVarContextImp (mvarId : MVarId) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x\n\n/--\n  Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.\n  The type class resolution cache is flushed when executing `x` if its `LocalInstances` are\n  different from the current ones. -/\ndef withMVarContext (mvarId : MVarId) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMVarContextImp mvarId\n\nprivate def withMCtxImp (mctx : MetavarContext) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mctx' \u2190 getMCtx\n  setMCtx mctx\n  try x finally setMCtx mctx'\n\ndef withMCtx (mctx : MetavarContext) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMCtxImp mctx\n\n@[inline] private def approxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x\n\n/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`.  -/\n@[inline] def approxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM approxDefEqImp\n\n@[inline] private def fullApproxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x\n\n/--\n  Similar to `approxDefEq`, but uses all available approximations.\n  We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.\n  For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.\n  Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved\n  as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to\n  solve `[Pure (fun _ => IO Bool)]` -/\n@[inline] def fullApproxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM fullApproxDefEqImp\n\ndef normalizeLevel (u : Level) : MetaM Level := do\n  let u \u2190 instantiateLevelMVars u\n  pure u.normalize\n\ndef assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.assignLevel mvarId u\n\ndef whnfR (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.reducible <| whnf e\n\ndef whnfD (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.default <| whnf e\n\ndef whnfI (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.instances <| whnf e\n\ndef setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do\n  let env \u2190 getEnv\n  match Compiler.setInlineAttribute env declName kind with\n  | Except.ok env    => setEnv env\n  | Except.error msg => throwError msg\n\nprivate partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    match (\u2190 whnf e) with\n    | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)\n    | _                    => throwError \"invalid instantiateForall, too many parameters\"\n  else\n    pure e\n\n/- Given `e` 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`, return `B[p_1, ..., p_n]`. -/\ndef instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateForallAux ps 0 e\n\nprivate partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    match (\u2190 whnf e) with\n    | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)\n    | _                => throwError \"invalid instantiateLambda, too many parameters\"\n  else\n    pure e\n\n/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.\n   It uses `whnf` to reduce `e` if it is not a lambda -/\ndef instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateLambdaAux ps 0 e\n\n/-- Return true iff `e` depends on the free variable `fvarId` -/\ndef dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).exprDependsOn e fvarId\n\ndef ppExpr (e : Expr) : MetaM Format := do\n  let ctxCore  \u2190 readThe Core.Context\n  Lean.ppExpr { env := (\u2190 getEnv), mctx := (\u2190 getMCtx), lctx := (\u2190 getLCtx), opts := (\u2190 getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls  } e\n\n@[inline] protected def orElse (x : MetaM \u03b1) (y : Unit \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let s \u2190 saveState\n  try x catch _ => s.restore; y ()\n\ninstance : OrElse (MetaM \u03b1) := \u27e8Meta.orElse\u27e9\n\ninstance : Alternative MetaM where\n  failure := fun {\u03b1} => throwError \"failed\"\n  orElse  := Meta.orElse\n\n@[inline] private def orelseMergeErrorsImp (x y : MetaM \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 r\u2082 => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ m\u2082) : MetaM \u03b1 := do\n  let env  \u2190 getEnv\n  let mctx \u2190 getMCtx\n  try\n    x\n  catch ex =>\n    setEnv env\n    setMCtx mctx\n    match ex with\n    | Exception.error ref\u2081 m\u2081 =>\n      try\n        y\n      catch\n        | Exception.error ref\u2082 m\u2082 => throw <| Exception.error (mergeRef ref\u2081 ref\u2082) (mergeMsg m\u2081 m\u2082)\n        | ex => throw ex\n    | ex => throw ex\n\n/--\n  Similar to `orelse`, but merge errors. Note that internal errors are not caught.\n  The default `mergeRef` uses the `ref` (position information) for the first message.\n  The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/\n@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 r\u2082 => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ Format.line ++ m\u2082) : m \u03b1 := do\n  controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg\n\n/-- Execute `x`, and apply `f` to the produced error message -/\ndef mapErrorImp (x : MetaM \u03b1) (f : MessageData \u2192 MessageData) : MetaM \u03b1 := do\n  try\n    x\n  catch\n    | Exception.error ref msg => throw <| Exception.error ref <| f msg\n    | ex => throw ex\n\n@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m \u03b1) (f : MessageData \u2192 MessageData) : m \u03b1 :=\n  controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f\n\n/--\n  Sort free variables using an order `x < y` iff `x` was defined before `y`.\n  If a free variable is not in the local context, we use their id. -/\ndef sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do\n  let lctx \u2190 getLCtx\n  return fvarIds.qsort fun fvarId\u2081 fvarId\u2082 =>\n    match lctx.find? fvarId\u2081, lctx.find? fvarId\u2082 with\n    | some d\u2081, some d\u2082 => d\u2081.index < d\u2082.index\n    | some _,  none    => false\n    | none,    some _  => true\n    | none,    none    => Name.quickLt fvarId\u2081.name fvarId\u2082.name\n\nend Methods\nend Meta\n\nexport Meta (MetaM)\n\nend Lean\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/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220179564702836, "lm_q2_score": 0.030214587831494465, "lm_q1q2_score": 0.010641632088987203}}
{"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.Tactic.Apply\nimport Lean.Meta.Tactic.Delta\nimport Lean.Meta.Tactic.SplitIf\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 \u2190 getMVarType mvarId\n  if let some (_, lhs, rhs) \u2190 matchEq? target then\n    if let some fvarId \u2190 findFVar? lhs then\n      return (\u2190 cases mvarId fvarId).map fun s => s.mvarId\n  throwError \"'casesOnStuckLHS' failed\"\nwhere\n  findFVar? (e : Expr) : MetaM (Option FVarId) := do\n    match e with\n    | Expr.proj _ _ e _ => findFVar? e\n    | Expr.app .. =>\n      let f := e.getAppFn\n      if !f.isConst then\n        return none\n      else\n        let declName := f.constName!\n        let args := e.getAppArgs\n        match (\u2190 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 e.getAppFn (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    | _ => return none\n\ndef casesOnStuckLHS? (mvarId : MVarId) : MetaM (Option (Array MVarId)) := do\n  try casesOnStuckLHS mvarId catch _ => return none\n\nnamespace Match\n\nstructure MatchEqns where\n  eqnNames             : Array Name\n  splitterName         : Name\n  splitterAltNumParams : Array Nat\n  deriving Inhabited, Repr\n\nstructure MatchEqnsExtState where\n  map : Std.PHashMap Name MatchEqns := {}\n  deriving Inhabited\n\n/- We generate the equations and splitter on demand, and do not save them on .olean files. -/\nbuiltin_initialize matchEqnsExt : EnvExtension MatchEqnsExtState \u2190\n  registerEnvExtension (pure {})\n\nprivate def registerMatchEqns (matchDeclName : Name) (matchEqns : MatchEqns) : CoreM Unit :=\n  modifyEnv fun env => matchEqnsExt.modifyState env fun s => { s with map := s.map.insert matchDeclName matchEqns }\n\n/-- Create a \"unique\" base name for conditional equations and splitter -/\nprivate def mkBaseNameFor (env : Environment) (matchDeclName : Name) : Name :=\n  Lean.mkBaseNameFor env matchDeclName `splitter `_matchEqns\n\n/--\n  Helper method. Recall that alternatives that do not have variables have a `Unit` parameter to ensure\n  they are not eagerly evaluated. -/\nprivate def toFVarsRHSArgs (ys : Array Expr) (resultType : Expr) : MetaM (Array Expr \u00d7 Array Expr) := do\n  if ys.size == 1 then\n    if (\u2190 inferType ys[0]).isConstOf ``Unit && !(\u2190 dependsOn resultType ys[0].fvarId!) then\n      return (#[], #[mkConst ``Unit.unit])\n  return (ys, ys)\n\n/--\n  Simplify/filter hypotheses that ensure that a match alternative does not match the previous ones.\n  Remark: if there is no overlaping between the alternatives, the empty array is returned. -/\nprivate partial def simpHs (hs : Array Expr) (numPatterns : Nat) : MetaM (Array Expr) := do\n  hs.filterMapM fun h => forallTelescope h fun ys _ => do\n    let xs  := ys[:ys.size - numPatterns].toArray\n    let eqs \u2190 ys[ys.size - numPatterns : ys.size].toArray.mapM inferType\n    if let some eqsNew \u2190 simpEqs eqs *> get |>.run |>.run' #[] then\n      let newH \u2190 eqsNew.foldrM (init := mkConst ``False) mkArrow\n      let xs \u2190 xs.filterM fun x => dependsOn newH x.fvarId!\n      return some (\u2190 mkForallFVars xs newH)\n    else\n      none\nwhere\n  simpEq (lhs : Expr) (rhs : Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do\n    if isMatchValue lhs && isMatchValue rhs then\n      unless (\u2190 isDefEq lhs rhs) do\n        failure\n    else if rhs.isFVar then\n      -- Ignore case since it matches anything\n      pure ()\n    else match lhs.arrayLit?, rhs.arrayLit? with\n      | some (_, lhsArgs), some (_, rhsArgs) =>\n        if lhsArgs.length != rhsArgs.length then\n          failure\n        else\n          for lhsArg in lhsArgs, rhsArg in rhsArgs do\n            simpEq lhsArg rhsArg\n      | _, _ =>\n        match toCtorIfLit lhs |>.constructorApp? (\u2190 getEnv), toCtorIfLit rhs |>.constructorApp? (\u2190 getEnv) with\n        | some (lhsCtor, lhsArgs), some (rhsCtor, rhsArgs) =>\n          if lhsCtor.name == rhsCtor.name then\n            for lhsArg in lhsArgs[lhsCtor.numParams:], rhsArg in rhsArgs[lhsCtor.numParams:] do\n              simpEq lhsArg rhsArg\n          else\n            failure\n        | _, _ =>\n          let newEq \u2190 mkEq lhs rhs\n          modify fun eqs => eqs.push newEq\n\n  simpEqs (eqs : Array Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do\n    eqs.forM fun eq =>\n      match eq.eq? with\n      | some (_, lhs, rhs) => simpEq lhs rhs\n      | _ => throwError \"failed to generate equality theorems for 'match', equality expected{indentExpr eq}\"\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 := do\n  let type \u2190 instantiateMVars type\n  withLCtx {} {} <| forallTelescope type fun ys target => do\n    let mvar0  \u2190 mkFreshExprSyntheticOpaqueMVar target\n    let mvarId \u2190 deltaTarget mvar0.mvarId! (. == matchDeclName)\n    trace[Meta.Match.matchEqs] \"{MessageData.ofGoal mvarId}\"\n    go mvarId 0\n    mkLambdaFVars ys (\u2190 instantiateMVars mvar0)\nwhere\n  go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do\n    let mvarId' \u2190 modifyTargetEqLHS mvarId whnfCore\n    let mvarId := mvarId'\n    let subgoals \u2190\n      (do applyRefl mvarId; return #[])\n      <|>\n      (do contradiction mvarId { genDiseq := true }; return #[])\n      <|>\n      (casesOnStuckLHS mvarId)\n      <|>\n      (do let mvarId' \u2190 simpIfTarget mvarId (useDecide := true)\n          if mvarId' == mvarId then throwError \"simpIf failed\"\n          return #[mvarId'])\n      <|>\n      (do if let some (s\u2081, s\u2082) \u2190 splitIfTarget? mvarId then\n            let mvarId\u2081 \u2190 trySubst s\u2081.mvarId s\u2081.fvarId\n            return #[mvarId\u2081, s\u2082.mvarId]\n          else\n            throwError \"spliIf failed\")\n      <|>\n      (throwError \"failed to generate equality theorems for `match` expression, support for array literals has not been implemented yet\\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 \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let rec go (i : Nat) (xs : Array Expr) : MetaM \u03b1 := do\n    if h : i < altTypes.size then\n      let hName := (`h).appendIndexAfter (i+1)\n      withLocalDeclD hName (altTypes.get \u27e8i, h\u27e9) 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 injenctionAny (mvarId : MVarId) : MetaM InjectionAnyResult :=\n  withMVarContext mvarId do\n    for localDecl in (\u2190 getLCtx) do\n      if let some (_, lhs, rhs) \u2190 matchEq? localDecl.type then\n        unless (\u2190 isDefEq lhs rhs) do\n          let lhs \u2190 whnf lhs\n          let rhs \u2190 whnf rhs\n          unless lhs.isNatLit && rhs.isNatLit do\n            try\n              match (\u2190 injection mvarId localDecl.fvarId) with\n              | InjectionResult.solved  => return InjectionAnyResult.solved\n              | InjectionResult.subgoal mvarId .. => return InjectionAnyResult.subgoal mvarId\n            catch _ =>\n              pure ()\n    return InjectionAnyResult.failed\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) : MetaM Expr := do\n  trace[Meta.Match.matchEqs] \"proof template: {template}\"\n  let map := mkMap\n  let (proof, mvarIds) \u2190 convertTemplate 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 := do\n    let mut m := {}\n    for alt in alts, altNew in altsNew do\n      m := m.insert alt.fvarId! altNew\n    return m\n\n  convertTemplate (m : FVarIdMap Expr) : StateRefT (Array MVarId) MetaM Expr :=\n    transform template fun e => do\n      match e.getAppFn with\n      | Expr.fvar fvarId .. =>\n        match m.find? fvarId with\n        | some altNew =>\n          trace[Meta.Match.matchEqs] \">> {e}, {altNew}\"\n          let eNew \u2190\n            if (\u2190 shouldCopyArgs e) then\n              addExtraParams (mkAppN altNew e.getAppArgs)\n            else\n              addExtraParams altNew\n          return TransformStep.done eNew\n        | none => return TransformStep.visit e\n      | _ => return TransformStep.visit e\n\n  shouldCopyArgs (e : Expr) : MetaM Bool := do\n    if e.getAppNumArgs == 1 then\n      match (\u2190 whnfD (\u2190 inferType e.appFn!)) with\n      | Expr.forallE _ d b _ =>\n        /- If result type does not depend on the argument, then\n           argument is an auxiliary unit used because Lean is an eager language, we should not copy it. -/\n        return b.hasLooseBVar 0\n      | _ => unreachable!\n    return true\n\n  addExtraParams (e : Expr) : StateRefT (Array MVarId) MetaM Expr := do\n    trace[Meta.Match.matchEqs] \"addExtraParams {e}\"\n    let (mvars, _, _) \u2190 forallMetaTelescopeReducing (\u2190 inferType e) (kind := MetavarKind.syntheticOpaque)\n    modify fun s => s ++ (mvars.map (\u00b7.mvarId!))\n    return mkAppN e mvars\n\n  proveSubgoalLoop (mvarId : MVarId) : MetaM Unit := do\n    if (\u2190 contradictionCore mvarId {}) then\n      return ()\n    match (\u2190 injenctionAny mvarId) with\n    | InjectionAnyResult.solved => return ()\n    | InjectionAnyResult.failed => throwError \"failed to generate splitter for match auxiliary declaration '{matchDeclName}', unsolved subgoal:\\n{MessageData.ofGoal mvarId}\"\n    | InjectionAnyResult.subgoal mvarId => proveSubgoalLoop mvarId\n\n  proveSubgoal (mvarId : MVarId) : MetaM Unit := do\n    trace[Meta.Match.matchEqs] \"subgoal {mkMVar mvarId}, {repr (\u2190 getMVarDecl mvarId).kind}, {\u2190 isExprMVarAssigned mvarId}\\n{MessageData.ofGoal mvarId}\"\n    let (_, mvarId) \u2190 intros mvarId\n    let mvarId \u2190 tryClearMany mvarId (alts.map (\u00b7.fvarId!))\n    proveSubgoalLoop mvarId\n\n/--\n  Create conditional equations and splitter for the given match auxiliary declaration. -/\nprivate partial def mkEquationsFor (matchDeclName : Name) :  MetaM MatchEqns := do\n  let baseName := mkBaseNameFor (\u2190 getEnv) matchDeclName\n  let constInfo \u2190 getConstInfo matchDeclName\n  let us := constInfo.levelParams.map mkLevelParam\n  let some matchInfo \u2190 getMatcherInfo? matchDeclName | throwError \"'{matchDeclName}' is not a matcher function\"\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    for alt in alts do\n      let thmName := baseName ++ ((`eq).appendIndexAfter idx)\n      eqnNames := eqnNames.push thmName\n      let altType \u2190 inferType alt\n      let (notAlt, splitterAltType, splitterAltNumParam) \u2190 forallTelescopeReducing altType fun ys altResultType => do\n        let (ys, rhsArgs) \u2190 toFVarsRHSArgs ys altResultType\n        let patterns := altResultType.getAppArgs\n        let mut hs := #[]\n        for notAlt in notAlts do\n          hs := hs.push (\u2190 instantiateForall notAlt patterns)\n        hs \u2190 simpHs hs patterns.size\n        trace[Meta.Match.matchEqs] \"hs: {hs}\"\n        let splitterAltType \u2190 mkForallFVars ys (\u2190 hs.foldrM (init := 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 \u2190 mkArrow (\u2190 mkEq discr pattern) notAlt\n        notAlt \u2190 mkForallFVars (discrs ++ ys) notAlt\n        let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts)\n        let rhs := mkAppN alt rhsArgs\n        let thmType \u2190 mkEq lhs rhs\n        let thmType \u2190 hs.foldrM (init := thmType) mkArrow\n        let thmType \u2190 mkForallFVars (params ++ #[motive] ++ alts ++ ys) thmType\n        let thmVal \u2190 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)\n      notAlts := notAlts.push notAlt\n      splitterAltTypes := splitterAltTypes.push splitterAltType\n      splitterAltNumParams := splitterAltNumParams.push splitterAltNumParam\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 \u2190 mkForallFVars splitterParams matchResultType\n      trace[Meta.Match.matchEqs] \"splitterType: {splitterType}\"\n      let template \u2190 mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ discrs ++ alts)\n      let template \u2190 deltaExpand template (. == constInfo.name)\n      let splitterVal \u2190 mkLambdaFVars splitterParams (\u2190 mkSplitterProof matchDeclName template alts altsNew)\n      let splitterName := baseName ++ `splitter\n      addDecl <| Declaration.thmDecl {\n        name        := splitterName\n        levelParams := constInfo.levelParams\n        type        := splitterType\n        value       := splitterVal\n      }\n      let result := { eqnNames, splitterName, splitterAltNumParams }\n      registerMatchEqns matchDeclName result\n      return result\n\ndef getEquationsFor (matchDeclName : Name) : MetaM MatchEqns := do\n  match matchEqnsExt.getState (\u2190 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": "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/Match/MatchEqs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082128783705344, "lm_q2_score": 0.03308597648187433, "lm_q1q2_score": 0.010614685584261385}}
{"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 data.bool\nimport meta.rb_map\nimport tactic.core\n\n/-!\n# list_unused_decls\n\n`#list_unused_decls` is a command used for theory development.\nWhen writing a new theory one often tries\nmultiple variations of the same definitions: `foo`, `foo'`, `foo\u2082`,\n`foo\u2083`, etc. Once the main definition or theorem has been written,\nit's time to clean up and the file can contain a lot of dead code.\nMark the main declarations with `@[main_declaration]` and\n`#list_unused_decls` will show the declarations in the file\nthat are not needed to define the main declarations.\n\nSome of the so-called \"unused\" declarations may turn out to be useful\nafter all. The oversight can be corrected by marking those as\n`@[main_declaration]`. `#list_unused_decls` will revise the list of\nunused declarations. By default, the list of unused declarations will\nnot include any dependency of the main declarations.\n\nThe `@[main_declaration]` attribute should be removed before submitting\ncode to mathlib as it is merely a tool for cleaning up a module.\n-/\n\nnamespace tactic\n\n/-- Attribute `main_declaration` is used to mark declarations that are featured\nin the current file.  Then, the `#list_unused_decls` command can be used to\nlist the declaration present in the file that are not used by the main\ndeclarations of the file. -/\n@[user_attribute]\nmeta def main_declaration_attr : user_attribute :=\n{ name := `main_declaration,\n  descr := \"tag essential declarations to help identify unused definitions\" }\n\n/-- `update_unsed_decls_list n m` removes from the map of unneeded declarations those\nreferenced by declaration named `n` which is considerred to be a\nmain declaration -/\nprivate meta def update_unsed_decls_list :\n  name \u2192 name_map declaration \u2192 tactic (name_map declaration)\n| n m :=\n  do d \u2190 get_decl n,\n     if m.contains n then do\n       let m := m.erase n,\n       let ns := d.value.list_constant.union d.type.list_constant,\n       ns.mfold m update_unsed_decls_list\n     else pure m\n\n/-- In the current file, list all the declaration that are not marked as `@[main_declaration]` and\nthat are not referenced by such declarations -/\nmeta def all_unused (fs : list (option string)) : tactic (name_map declaration) :=\ndo ds \u2190 get_decls_from fs,\n   ls \u2190 ds.keys.mfilter (succeeds \u2218 user_attribute.get_param_untyped main_declaration_attr),\n   ds \u2190 ls.mfoldl (flip update_unsed_decls_list) ds,\n   ds.mfilter $ \u03bb n d, do\n     e \u2190 get_env,\n     return $ !d.is_auto_or_internal e\n\n/-- expecting a string literal (e.g. `\"src/tactic/find_unused.lean\"`)\n-/\nmeta def parse_file_name (fn : pexpr) : tactic (option string) :=\nsome <$> (to_expr fn >>= eval_expr string) <|> fail \"expecting: \\\"src/dir/file-name\\\"\"\n\nsetup_tactic_parser\n\n/-- The command `#list_unused_decls` lists the declarations that that\nare not used the main features of the present file. The main features\nof a file are taken as the declaration tagged with\n`@[main_declaration]`.\n\nA list of files can be given to `#list_unused_decls` as follows:\n\n```lean\n#list_unused_decls [\"src/tactic/core.lean\",\"src/tactic/interactive.lean\"]\n```\n\nThey are given in a list that contains file names written as Lean\nstrings. With a list of files, the declarations from all those files\nin addition to the declarations above `#list_unused_decls` in the\ncurrent file will be considered and their interdependencies will be\nanalyzed to see which declarations are unused by declarations marked\nas `@[main_declaration]`. The files listed must be imported by the\ncurrent file. The path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present).\n\nNeither `#list_unused_decls` nor `@[main_declaration]` should appear\nin a finished mathlib development. -/\n@[user_command]\nmeta def unused_decls_cmd (_ : parse $ tk \"#list_unused_decls\") : lean.parser unit :=\ndo fs \u2190 pexpr_list,\n   show tactic unit, from\n   do fs \u2190 fs.mmap parse_file_name,\n      ds \u2190 all_unused $ none :: fs,\n      ds.to_list.mmap' $ \u03bb \u27e8n,_\u27e9, trace!\"#print {n}\"\n\nadd_tactic_doc\n{ name                     := \"#list_unused_decls\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.unused_decls_cmd],\n  tags                     := [\"debugging\"] }\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/find_unused.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.127652631959211, "lm_q2_score": 0.0826973375883307, "lm_q1q2_score": 0.010556532799169805}}
{"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.Elab.ElabRules\nimport Std.Lean.Parser\n\n/-!\n# `simp?` tactic\n\nThe `simp?` tactic is a simple wrapper around the simp with trace behavior implemented in core.\n-/\nnamespace Std.Tactic\nopen Lean Elab Parser Tactic\n\n/-- The common arguments of `simp?` and `simp?!`. -/\nsyntax simpTraceArgsRest := (config)? (discharger)? (&\" only\")? (simpArgs)? (ppSpace location)?\n\n/--\n`simp?` takes the same arguments as `simp`, but reports an equivalent call to `simp only`\nthat would be sufficient to close the goal. This is useful for reducing the size of the simp\nset in a local invocation to speed up processing.\n```\nexample (x : Nat) : (if True then x + 2 else 3) = x + 2 := by\n  simp? -- prints \"Try this: simp only [ite_true]\"\n```\n\nThis command can also be used in `simp_all` and `dsimp`.\n-/\nsyntax (name := simpTrace) \"simp?\" \"!\"? simpTraceArgsRest : tactic\n\n@[inherit_doc simpTrace]\nmacro tk:\"simp?!\" rest:simpTraceArgsRest : tactic => `(tactic| simp?%$tk ! $rest)\n\nmacro_rules\n  | `(tactic| simp?%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]? $(loc)?) =>\n    `(tactic| set_option tactic.simp.trace true in\n      simp%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]? $(loc)?)\n  | `(tactic| simp?%$tk ! $(config)? $(discharger)? $[only%$o]? $[[$args,*]]? $(loc)?) =>\n    `(tactic| set_option tactic.simp.trace true in\n      simp!%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]? $(loc)?)\n\n/-- The common arguments of `simp_all?` and `simp_all?!`. -/\nsyntax simpAllTraceArgsRest := (config)? (discharger)? (&\" only\")? (dsimpArgs)?\n\n@[inherit_doc simpTrace]\nsyntax (name := simpAllTrace) \"simp_all?\" \"!\"? simpAllTraceArgsRest : tactic\n\n@[inherit_doc simpTrace]\nmacro tk:\"simp_all?!\" rest:simpAllTraceArgsRest : tactic => `(tactic| simp_all?%$tk ! $rest)\n\nmacro_rules\n  | `(tactic| simp_all?%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]?) =>\n    `(tactic| set_option tactic.simp.trace true in\n      simp_all%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]?)\n  | `(tactic| simp_all?%$tk ! $(config)? $(discharger)? $[only%$o]? $[[$args,*]]?) =>\n    `(tactic| set_option tactic.simp.trace true in\n      simp_all!%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]?)\n\n/-- The common arguments of `dsimp?` and `dsimp?!`. -/\nsyntax dsimpTraceArgsRest := (config)? (&\" only\")? (dsimpArgs)? (ppSpace location)?\n\n@[inherit_doc simpTrace]\nsyntax (name := dsimpTrace) \"dsimp?\" \"!\"? dsimpTraceArgsRest : tactic\n\n@[inherit_doc simpTrace]\nmacro tk:\"dsimp?!\" rest:dsimpTraceArgsRest : tactic => `(tactic| dsimp?%$tk ! $rest)\n\nmacro_rules\n  | `(tactic| dsimp?%$tk $(config)? $[only%$o]? $[[$args,*]]? $(loc)?) =>\n    `(tactic| set_option tactic.simp.trace true in\n      dsimp%$tk $(config)? $[only%$o]? $[[$args,*]]? $(loc)?)\n  | `(tactic| dsimp?%$tk ! $(config)? $[only%$o]? $[[$args,*]]? $(loc)?) =>\n    `(tactic| set_option tactic.simp.trace true in\n      dsimp!%$tk $(config)? $[only%$o]? $[[$args,*]]? $(loc)?)\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/SimpTrace.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17553805637093017, "lm_q2_score": 0.06008665017400762, "lm_q1q2_score": 0.01054749378538531}}
{"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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_ec_mul_inner \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 460))\n    (h_mem_5 : mem_at mem code_unreduced_mul (\u03c3.pc  - 448))\n    (h_mem_6 : mem_at mem code_unreduced_sqr (\u03c3.pc  - 428))\n    (h_mem_7 : mem_at mem code_verify_zero (\u03c3.pc  - 412))\n    (h_mem_12 : mem_at mem code_compute_doubling_slope (\u03c3.pc  - 284))\n    (h_mem_13 : mem_at mem code_compute_slope (\u03c3.pc  - 240))\n    (h_mem_14 : mem_at mem code_ec_double (\u03c3.pc  - 216))\n    (h_mem_15 : mem_at mem code_fast_ec_add (\u03c3.pc  - 143))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 11))\n    (hin_point : point = cast_EcPoint mem (\u03c3.fp - 10))\n    (hin_scalar : scalar = mem (\u03c3.fp - 4))\n    (hin_m : m = mem (\u03c3.fp - 3))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 11)) (mem $ \u03c4.ap - 13)\n        (spec_ec_mul_inner mem \u03ba range_check_ptr point scalar m (mem (\u03c4.ap - 13)) (cast_EcPoint mem (\u03c4.ap - 12)) (cast_EcPoint mem (\u03c4.ap - 6)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  revert \u03c3 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 \u03bdbound with \u03bdbound \u03bdih,\n  { intros, intros n nlt, apply absurd nlt (nat.not_lt_zero _) },\n  intros \u03c3 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 \u03bdih,\n  have h_mem_rec := h_mem,\n  unpack_memory code_ec_mul_inner at h_mem with \u27e8hpc0, 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\u27e9,\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 \u2260 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 \u03ba_call35 ap35 h_call35,\n    rcases h_call35 with \u27e8rc_m35, rc_mle35, hl_range_check_ptr\u2081, h_call35\u27e9,\n    generalize' hr_rev_range_check_ptr\u2081: mem (ap35 - 7) = range_check_ptr\u2081,\n    have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\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\u2081 },\n    rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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 \u2190regstateapeq_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_\u03b437_c0 : \u2200 x : F, x / (2 : \u2124) = x * (-1809251394333065606848661391547535052811553607665798349986546028067936010240 : \u2124),\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_\u03b437_c0_fz : \u2200 x : F, x / 2 = x / (2 : \u2124), { intro x, norm_cast }, \n      step_rec_sub hpc48 (\u03bdih _ range_check_ptr\u2081 double_point (scalar / (2 : \u2124)) (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_\u03b437_c0_fz, h_\u03b437_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr\u2081, 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_\u03b437_c0_fz, h_\u03b437_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\u2081, 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_\u03b437_c0_fz, h_\u03b437_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr\u2081, 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_\u03b437_c0_fz, h_\u03b437_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr\u2081, 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 \u03ba_call50 ap50 h_call50,\n      rcases h_call50 with \u27e8rc_m50, rc_mle50, hl_range_check_ptr\u2082, h_call50\u27e9,\n      step_ret hpc50,\n      generalize' hr_rev_range_check_ptr\u2082: mem (ap50 - 13) = range_check_ptr\u2082,\n      have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\n      try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at hl_range_check_ptr\u2082 },\n      rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\n      try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call50 },\n      rw [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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 [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03ba_call35],\n      use_only [range_check_ptr\u2081],\n      use_only [double_point],\n      have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n      have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n      have spec35 := h_call35 rc_h_range_check_ptr',\n      rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] 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 [\u03ba_call50],\n      have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n      have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n      have spec50 := h_call50 rc_h_range_check_ptr\u2081',\n      rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081] 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 \u2190regstateapeq_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_\u03b451_c0 : \u2200 x : F, x / (2 : \u2124) = x * (-1809251394333065606848661391547535052811553607665798349986546028067936010240 : \u2124),\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_\u03b451_c0_fz : \u2200 x : F, x / 2 = x / (2 : \u2124), { intro x, norm_cast }, \n      step_rec_sub hpc64 (\u03bdih _ range_check_ptr\u2081 double_point ((scalar - 1) / (2 : \u2124)) (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_\u03b451_c0_fz, h_\u03b451_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr\u2081, 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_\u03b451_c0_fz, h_\u03b451_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\u2081, 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_\u03b451_c0_fz, h_\u03b451_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr\u2081, 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_\u03b451_c0_fz, h_\u03b451_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr\u2081, 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 \u03ba_call66 ap66 h_call66,\n      rcases h_call66 with \u27e8rc_m66, rc_mle66, hl_range_check_ptr\u2082, h_call66\u27e9,\n      generalize' hr_rev_range_check_ptr\u2082: mem (ap66 - 13) = range_check_ptr\u2082,\n      have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\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\u2082 },\n      rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\n      try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at h_call66 },\n      rw [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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 \u03c3.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\u2082 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\u2081, htv_double_point, htv_range_check_ptr\u2082, 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\u2081, htv_double_point, htv_range_check_ptr\u2082, 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\u2081, htv_double_point, htv_range_check_ptr\u2082, 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 \u03ba_call87 ap87 h_call87,\n      rcases h_call87 with \u27e8rc_m87, rc_mle87, hl_range_check_ptr\u2083, h_call87\u27e9,\n      generalize' hr_rev_range_check_ptr\u2083: mem (ap87 - 7) = range_check_ptr\u2083,\n      have htv_range_check_ptr\u2083 := hr_rev_range_check_ptr\u2083.symm, clear hr_rev_range_check_ptr\u2083,\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\u2083 },\n      rw [\u2190htv_range_check_ptr\u2083, \u2190htv_range_check_ptr\u2082] at hl_range_check_ptr\u2083,\n      try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call87 },\n      rw [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u2190htv_range_check_ptr\u2083, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03ba_call35],\n      use_only [range_check_ptr\u2081],\n      use_only [double_point],\n      have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n      have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n      have spec35 := h_call35 rc_h_range_check_ptr',\n      rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] 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 [\u03ba_call66],\n      use_only [range_check_ptr\u2082],\n      use_only [inner_pow2],\n      use_only [inner_res],\n      have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n      have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n      have spec66 := h_call66 rc_h_range_check_ptr\u2081',\n      rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190htv_range_check_ptr\u2082] at spec66,\n      try { dsimp at spec66, arith_simps at spec66 },\n      use_only [spec66],\n      use_only [\u03ba_call87],\n      use_only [range_check_ptr\u2083],\n      use_only [res],\n      have rc_h_range_check_ptr\u2083 := range_checked_offset' rc_h_range_check_ptr\u2082,\n      have rc_h_range_check_ptr\u2083' := range_checked_add_right rc_h_range_check_ptr\u2083, try { norm_cast at rc_h_range_check_ptr\u2083' },\n      have spec87 := h_call87 rc_h_range_check_ptr\u2082',\n      rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2083] 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\u2081, htv_double_point, htv_range_check_ptr\u2082, htv_inner_pow2, htv_inner_res, lc_inner_pow2, htv_range_check_ptr\u2083, 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": "import LeanCodePrompts.Translate\nimport LeanCodePrompts.Utils\n\nopen Lean Meta Elab\n\n\ndef translateWithDataM (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := \u27e82, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : \n  TermElabM ((Option (Expr \u00d7 (Array String) )) \u00d7 Array String) := do\n  let js \u2190 \n    getCodeJson s numSim numKW includeFixed queryNum temp scoreBound matchBound\n  let output \u2190 GPT.jsonToExprStrArray js\n  let output := output.toList.eraseDups.toArray\n  let res \u2190 arrayToExpr? output\n  return (res, output)\n  \ndef translateWithDataCore (s: String)(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := \u27e82, 1\u27e9)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : \n  CoreM ((Option (Expr \u00d7 (Array String) )) \u00d7 Array String) := \n    (translateWithDataM s \n      numSim numKW includeFixed \n        queryNum temp scoreBound matchBound).run'.run'\n\ndef checkTranslatedThmsM(type: String := \"thm\")(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := \u27e82, 1\u27e9) : TermElabM Json := do\n  elabLog s!\"Writing to file: {type}-elab-{numSim}-{numKW}-{includeFixed}-{queryNum}-{temp.mantissa}.json\"\n  let promptsFile \u2190 reroutePath <| System.mkFilePath [\"data\",\n    s!\"prompts-{type}-{numSim}-{numKW}-{includeFixed}-{queryNum}-{temp.mantissa}.jsonl\"]\n  let h \u2190 IO.FS.Handle.mk promptsFile IO.FS.Mode.append Bool.false\n  let file \u2190 reroutePath <| System.mkFilePath [s!\"data/{type}-prompts.txt\"]\n  let prompts \u2190  IO.FS.lines file\n  let prompts := \n      prompts.map <| fun s => s.replace \"<br>\" \"\\n\"\n  let mut count := 0\n  let mut elaborated := 0\n  let mut elabPairs: Array (String \u00d7 String \u00d7 (Array String)) := #[]\n  let mut failed : Array String := #[]\n  for prompt in prompts do \n    trace[Translate.info] m!\"{prompt}\"\n    IO.println \"\"\n    IO.println prompt\n    let (res?, outputs) \u2190 \n        translateWithDataM prompt\n          numSim numKW includeFixed queryNum temp\n    let fullPrompt := (\u2190 logs 1).head! \n    let js := Json.mkObj [(\"text\", Json.str prompt), (\"fullPrompt\", Json.str fullPrompt)]\n    h.putStrLn <| js.pretty 10000\n    count := count + 1\n    match res? with\n    | some (e, thms) =>\n      elabLog \"success\"\n      let v \u2190 e.view\n      elabLog s!\"theorem {v}\"\n      IO.println s!\"theorem {v}\"\n      elaborated := elaborated + 1\n      elabPairs := elabPairs.push (prompt, v, thms) \n    | none =>\n      elabLog \"failed to elaborate\"\n      IO.println \"failed to elaborate\"\n      failed := failed.push prompt\n      elabLog s!\"outputs: {outputs}\"\n    elabLog s!\"total : {count}\"\n    elabLog s!\"elaborated: {elaborated}\"\n    IO.println s!\"total : {count}\"\n    IO.println s!\"elaborated: {elaborated}\"\n    IO.sleep 20000\n\n  let js := \n    Json.mkObj \n      [(\"total-prompts\", count),\n        (\"elaborated\", elaborated),\n        (\"number-similar-sentences\", numSim),\n       (\"number-keyword-sentences\", numKW),\n       (\"include-fixed\", includeFixed),\n       (\"query-number\", queryNum),\n       (\"temperature\", Json.num temp),\n       (\"elaborated-prompts\", \n        Json.arr <| \u2190  elabPairs.mapM <| \n          fun (p, s, thms) => do \n            return Json.mkObj [\n            (\"prompt\", p), (\"theorem\", s),\n            (\"all-elabs\", Json.arr <| thms.map (Json.str)),\n            (\"comments\", \"\"), (\"correct\", Json.null), \n            (\"some-correct\", Json.null)   \n            ]),\n        (\"failures\", Json.arr <| failed.map (Json.str))\n            ]\n  return js\n\ndef checkTranslatedThmsCore(type: String := \"thm\")(numSim : Nat:= 10)(numKW: Nat := 1)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := \u27e82, 1\u27e9) : CoreM Json :=\n    (checkTranslatedThmsM type\n      numSim numKW includeFixed queryNum temp).run'.run'\n\ndef parsedThmsPrompt : IO (Array String) := do\n  let file \u2190 reroutePath <| System.mkFilePath [\"data/parsed_thms.txt\"]\n  IO.FS.lines file\n\n\ndef elabThmSplit(start? size?: Option Nat := none) : TermElabM ((Array String) \u00d7 (Array String)) := do \n  let deps \u2190 parsedThmsPrompt\n  let deps := deps.toList.drop (start?.getD 0)\n  let deps := deps.take (size?.getD (deps.length))\n  let deps := deps.toArray\n  let mut succ: Array String := Array.empty\n  let mut fail: Array String := Array.empty\n  let mut count := start?.getD 0\n  let succFile \u2190 reroutePath <| System.mkFilePath [\"data/elab_thms.txt\"]\n  let h \u2190 IO.FS.Handle.mk succFile IO.FS.Mode.append Bool.false\n  IO.println s!\"total: {deps.size}\"\n  for thm in deps do\n    IO.println s!\"parsing theorem {thm}\"\n    let chk \u2190  hasElab thm (some 25)\n    count := count + 1\n    if chk then\n      succ := succ.push thm\n      h.putStrLn thm\n    else\n      fail := fail.push thm\n    IO.println s!\"parsed: {count}\"\n    IO.println s!\"elaborated: {succ.size}\"\n  return (succ, fail)\n\ndef elabThmSplitCore(start? size?: Option Nat := none) : CoreM ((Array String) \u00d7 (Array String)) := \n  (elabThmSplit start? size?).run'.run'\n\ndef outputFromCompletionsM (s: String) : \n  TermElabM (String) := do\n  let output \u2190 jsonStringToExprStrArray s\n  let output := output ++ (output.map (fun s => \": \" ++ s))\n  let output := output.toList.eraseDups.toArray\n  -- IO.println s!\"output: {output}\"\n  let res? \u2190 arrayToExpr? output\n  let js : Json \u2190  match res? with\n  | some (thm, elabs) => do\n    let thm \u2190  thm.view\n    pure <| Json.mkObj [(\"success\", Bool.true), (\"theorem\", thm),\n            (\"all-elabs\", Json.arr <| elabs.map (Json.str))] \n  | none => pure <| Json.mkObj [(\"success\", Bool.false)]\n  return js.pretty 10000\n\ndef outputFromCompletionsCore (s: String) : CoreM String := \n  (outputFromCompletionsM s).run'.run'\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/BatchTranslate.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.02976009405352986, "lm_q1q2_score": 0.01048155815956602}}
{"text": "import Lean\n\n\nopen Lean\nopen Lean.Elab\nopen Lean.Elab.Term\n\ndef getCtors (c : Name) : TermElabM (List Name) := do\nlet env \u2190 getEnv;\n(match env.find? c with\n| some (ConstantInfo.inductInfo val) =>\n  pure val.ctors\n| _ => pure [])\n\ndef elabAnonCtor (args : Array Syntax) (\u03c4 : Expr) : TermElabM Expr :=\n  match \u03c4.getAppFn with\n  | Expr.const C _ _ => do\n    let ctors \u2190 getCtors C;\n    (match ctors with\n    | [c] => do\n      let stx \u2190 `($(Lean.mkIdent c) $args*);\n      elabTerm stx \u03c4\n-- error handling\n    | _ => unreachable!)\n  | _ => unreachable!\n\nelab \"foo\u27e8\" args:term,* \"\u27e9\" : term <= \u03c4 => do\n  elabAnonCtor args \u03c4\n\nexample : Nat \u00d7 Nat := foo\u27e81, 2\u27e9\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/elabCmd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.34158249943831703, "lm_q2_score": 0.030675800159883637, "lm_q1q2_score": 0.010478316490883379}}
{"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 \u2192 Type :=\n  | UB {\u03b1: Type} [Inhabited \u03b1]: Option String \u2192 UBE \u03b1\n  | Unhandled {\u03b1: Type} [Inhabited \u03b1]: UBE \u03b1\n\n@[simp_itree]\ndef UBE.handle {E}: UBE ~> UBT (Fitree E) := fun _ e =>\n  match e with\n  | Unhandled => throw \"<unhandled>\"\n  | UB none => throw \"<UB>\"\n  | UB (some msg) => throw s!\"<UB: {msg}>\"\n\n@[simp_itree]\ndef UBE.handle! {E}: UBE ~> Fitree E := fun _ e =>\n  match e with\n  | Unhandled => panic! \"<unhandled>\"\n  | UB none => panic! \"<UB>\"\n  | UB (some msg) => panic! s!\"<UB: {msg}>\"\n\ndef raiseUB (msg: String) {E \u03b1} [Member UBE E] [Inhabited \u03b1]: Fitree E \u03b1 :=\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 \u2192 Fitree UBE R):\n  interpUB (Fitree.bind t k) =\n  Fitree.bind (interpUB t) (fun x =>\n    match x with\n    | .error \u03b5 => Fitree.ret (.error \u03b5)\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 \u03b1 \u03b2 (f g: \u03b1 \u2192 \u03b2) x y: f = g \u2192 x = y \u2192 f x = g y :=\n        fun h\u2081 h\u2082 => by simp [h\u2081, h\u2082]\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 \u2192 Fitree (UBE +' E) R):\n  interpUB' (Fitree.bind t k) =\n  Fitree.bind (interpUB' t) (fun x =>\n    match x with\n    | .error \u03b5 => Fitree.ret (.error \u03b5)\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 \u03b1 \u03b2 (f g: \u03b1 \u2192 \u03b2) x y: f = g \u2192 x = y \u2192 f x = g y :=\n        fun h\u2081 h\u2082 => by simp [h\u2081, h\u2082]\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 `\u2200 x, ...`,\n`\u2203 x, ...` and `\u03bb 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 `\u2200 x, ...`, `\u2203 x, ...` and `\u03bb 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 `\u2190` is applied in the reverse direction.\n  - `simp_rw [lemma_1, ..., lemma_n] at h\u2081 ... h\u2099` will rewrite the given hypotheses.\n  - `simp_rw [...] at \u22a2 h\u2081 ... h\u2099` 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 {\u03b1 \u03b2 : Type} {f : \u03b1 \u2192 \u03b2} {t : set \u03b2} :\n  (\u2200 s, f '' s \u2286 t) = \u2200 s : set \u03b1, \u2200 x \u2208 s, x \u2208 f \u207b\u00b9' 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' (\u03bb 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 \u03b1` 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 \u2190 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 \u03b1 e) evaluates 'e' IF 'e' has type '\u03b1'. -/\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 \u2190 result, s \u2190 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 \u2192 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 : \u2115, h : P(x) \u22a2 T(x)`, `revert_lst [x]` returns `2` and produces the state ` \u22a2 \u03a0 x, P(x) \u2192 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 : \u03b1 \u2192 \u03b2` head-eta-expands to `\u03bb a, f a`. If `f` isn't a function then it just returns `f`.  -/\n/-- (head) beta reduction. `(\u03bb 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. `(\u03bb 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 (\u03b1 : Type.{l_1}) (\u03b2 : \u03b1 -> Type.{l_2}), (Pi x : \u03b1, \u03b2 x) -> (Pi x : \u03b1, \u03b2 x) -> , Prop\n        nat     : Type\n        real    : Type\n        vec.{l} : Pi (\u03b1 : 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\u2081 h\u2082) is a more efficient version of (mk_app `congr_arg [h\u2081, h\u2082]) -/\n/-- (mk_congr_fun h\u2081 h\u2082) is a more efficient version of (mk_app `congr_fun [h\u2081, h\u2082]) -/\n/-- (mk_congr h\u2081 h\u2082) is a more efficient version of (mk_app `congr [h\u2081, h\u2082]) -/\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\u2081 h\u2082) is a more efficient version of (mk_app `eq.trans [h\u2081, h\u2082]) -/\n/-- (mk_eq_mp h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mp [h\u2081, h\u2082]) -/\n/-- (mk_eq_mpr h\u2081 h\u2082) is a more efficient version of (mk_app `eq.mpr [h\u2081, h\u2082]) -/\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 : \u2200 (a:\u03b1) (p : P(a)), Q`\n- `non_dep_first` would produce goals `\u22a2 P(?m)`, `\u22a2 \u03b1`. 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 `\u22a2 P(?m)`.\n- `all` would produce goals `\u22a2 \u03b1`, `\u22a2 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 : \u03a0 (a\u2081:\u03b1\u2081) ... (a\u2099:\u03b1\u2099), P(a\u2081,...,a\u2099)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a\u2081,...?a\u2099)`.\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 : \u2115)\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 : \u2115) : message := sorry -- encodes a nat as a message\ndef decode (m : message) : \u2115 := 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 : \u2115)\n  (initial_state : ensemble ste) -- An ensemble of initial states (representing randomness in the machine execution)\n  (callers : finset (\u2115)) -- Ids of machines that input to this machine\n  (subroutines : finset (\u2115)) -- Ids of machines that give subroutine output to this machine\n  (backdoor : finset (\u2115)) -- 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 \u2192 \u2115 \u2192 message \u2192 option (ste \u00d7 \u2115 \u00d7 message))\n    -- TODO add condition for polytime halting\n  (environment_output : option (ste \u2192 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 \u2115)\n--   (\u03bc : \u2115 \u2192 machine)\n--   -- ids correspond to ids\n--   (ids_match : \u2200 i \u2208 ids, (\u03bc i).id = i)\n--   -- Callers match up with subroutines\n--   (callers_have_subroutines : \u2200 i j \u2208 ids, i \u2208 (\u03bc j).callers \u2194 j \u2208 (\u03bc 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    \u2200 (i j : machine), i \u2208 machines \u2192 i.ident \u2208 j.callers \u2194 j.ident \u2208 i.subroutines)\n\n\ndef protocol.ids (\u03c0 : protocol) : finset \u2115 :=\n  \u03c0.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 (\u03c0 : protocol) (\u03bc : machine) : Prop :=\n  \u03bc.ident \u2208 \u03c0.ids \u2227 \u2203 m \u2208 \u03bc.callers, m \u2209 \u03c0.ids\n\n-- TODO seems like a bug in the typeclass inference system tha tthis needs to be defined\ninstance (\u03c0 : protocol) : decidable_pred (is_main_machine \u03c0) := 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 (\u03c0 : protocol) : finset machine :=\n  \u03c0.machines.filter (is_main_machine \u03c0)\n\n/-- ... and the ids of these machines not in the protocol are \"external\" -/\ndef external_ids (\u03c0 : protocol) : finset \u2115 := \n  (finset.bUnion (\u03c0.machines) (\u03bb \u03bc, \u03bc.callers)) \\ \u03c0.ids\n\n/-- As defined in 2.2.1 -/\ndef execution (\u03c0 : protocol) (\ud835\udcd0 : machine) (\ud835\udcd4 : machine) :\n  -- (initial_states : \u2115 \u2192 ste) -- randomness initialization for the machines in the protocol (including input for environment)\n  -- (environment_id_zero : \ud835\udcd4.id = 0) -- environment machine has id 0\n  -- (adversary_id_one : \ud835\udcd0.id = 1) -- adversaty machine has id 1\n  -- (h0 : 0 \u2209 \ud835\udcdf.ids) (h1 : 1 \u2209 \ud835\udcdf.ids) -- \ud835\udcdf does not have 0 or 1 in its id list\n  -- (h0' : 0 \u2209 external_ids \ud835\udcdf) (h1' : 1 \u2209 external_ids \ud835\udcdf) -- 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 (\ud835\udcd4 : machine) : Prop :=\nsorry\n\n/-- As defined in 2.2.1 Definition 1 -/\ndef emulates (\u03c0 \u03d5 : protocol) : Prop :=\n  \u2200 (\ud835\udcd0 : machine), \u2203 (\ud835\udce2 : machine), \u2200 (\ud835\udcd4 : machine),\n    balanced \ud835\udcd4 \u2192 (execution \u03c0 \ud835\udcd0 \ud835\udcd4 \u2248\u209b execution \u03c0 \ud835\udce2 \ud835\udcd4)\n\ndef dummy_machine (ident : \u2115) (forwards_to : \u2115) (callers : finset \u2115) : machine := \n{ ident := ident,\n  initial_state := \u03bb n, \n  { val := \u03bb 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 := \u2205,\n  program := \u03bb st idx msg, \n    if idx = forwards_to \n      then some \u27e8st, decode (unpair_left msg), unpair_right msg\u27e9\n      else some \u27e8st, forwards_to, pair msg (encode idx)\u27e9,\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 (\u03bb 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 (\ud835\udcdf : protocol) (s : finset \u2115) : protocol :=\n-- { ids := \ud835\udcdf.ids \\ s,\n--   \u03bc := \ud835\udcdf.\u03bc,\n--   ids_match := begin\n--     intros i hi,\n--     rw finset.mem_sdiff at hi,\n--     exact \ud835\udcdf.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 \ud835\udcdf.callers_have_subroutines,\n--     exact hi.left,\n--     exact hj.left,\n--   end }\n\n/-- Per section 2.3 -/\ndef subroutine (\u03d5 \u03c0 : protocol) : Prop := \u03d5.machines \u2286 \u03c0.machines\n\ninstance : has_subset (protocol) := \u27e8\u03bb \u03d5 \u03c0, subroutine \u03d5 \u03c0\u27e9\n\n\n/-- Per section 2.3 -/\ndef compatible (\u03c0 \u03d5 : protocol) : Prop :=\n\u2200 \u03bc \u2208 \u03c0.machines, \u2203! \u03bc' \u2208 \u03d5.machines, ((\u03bc : machine).ident) = (\u03bc'.ident) \u2227 \u03bc.callers = \u03bc'.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 \u03bc is a machine\n\ndef identity_compatible (\u03c0 \u03c1 \u03d5 : protocol) :=\ndisjoint (\u03c0.ids) (\u03c1.ids \\ \u03d5.ids)\n\n/-- Per section 2.3 -/\ndef composed (\u03c1 \u03d5 \u03c0 : protocol) (h\u03d5\u03c1 : \u03d5 \u2286 \u03c1) (h\u03c0\u03d5 : compatible \u03c0 \u03d5)\n  (h : identity_compatible \u03c0 \u03c1 \u03d5) : protocol :=\n{ machines := (\u03c1.machines \\ \u03d5.machines) \u222a \u03c0.machines,\n  callers_have_subroutines := begin\n    sorry,\n    --follows from compatibility\n  end }\n\n/-- Section 2.3 theorem 3 -/\ntheorem composition_theorem (\u03c1 \u03d5 \u03c0 : protocol) (h\u03d5\u03c1 : \u03d5 \u2286 \u03c1) (h\u03c0\u03d5 : compatible \u03c0 \u03d5)\n  (h : identity_compatible \u03c0 \u03c1 \u03d5) (h_emulate : emulates \u03c0 \u03d5) :\n  emulates (composed \u03c1 \u03d5 \u03c0 h\u03d5\u03c1 h\u03c0\u03d5 h) \u03c1 :=\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) 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.buffer.parser\nimport Mathlib.tactic.core\nimport Mathlib.PostPort\n\nnamespace Mathlib\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 -/\n\nalias my_theorem \u2190 alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n/-- doc string -/\nnamespace tactic.alias\n\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 -/\n/-- doc string -/\n/-- 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/tactic/alias_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.23370634623958197, "lm_q2_score": 0.04401865268469796, "lm_q1q2_score": 0.010287438485329927}}
{"text": "/-\nCopyright (c) 2020 Sebastian Ullrich. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\n\nimport Lean.PrettyPrinter.Delaborator.Basic\nimport Lean.PrettyPrinter.Delaborator.SubExpr\nimport Lean.PrettyPrinter.Delaborator.TopDownAnalyze\nimport Lean.Parser\n\nnamespace Lean.PrettyPrinter.Delaborator\nopen Lean.Meta\nopen Lean.Parser.Term\nopen SubExpr\n\ndef maybeAddBlockImplicit (ident : Syntax) : DelabM Syntax := do\n  if \u2190 getPPOption getPPAnalysisBlockImplicit then `(@$ident:ident) else pure ident\n\ndef unfoldMDatas : Expr \u2192 Expr\n  | Expr.mdata _ e _ => unfoldMDatas e\n  | e                => e\n\n@[builtinDelab fvar]\ndef delabFVar : Delab := do\nlet Expr.fvar id _ \u2190 getExpr | unreachable!\ntry\n  let l \u2190 getLocalDecl id\n  maybeAddBlockImplicit (mkIdent l.userName)\ncatch _ =>\n  -- loose free variable, use internal name\n  maybeAddBlockImplicit $ mkIdent id.name\n\n-- loose bound variable, use pseudo syntax\n@[builtinDelab bvar]\ndef delabBVar : Delab := do\n  let Expr.bvar idx _ \u2190 getExpr | unreachable!\n  pure $ mkIdent $ Name.mkSimple $ \"#\" ++ toString idx\n\n@[builtinDelab mvar]\ndef delabMVar : Delab := do\n  let Expr.mvar n _ \u2190 getExpr | unreachable!\n  let mvarDecl \u2190 getMVarDecl n\n  let n :=\n    match mvarDecl.userName with\n    | Name.anonymous => n.name.replacePrefix `_uniq `m\n    | n => n\n  `(?$(mkIdent n))\n\n@[builtinDelab sort]\ndef delabSort : Delab := do\n  let Expr.sort l _ \u2190 getExpr | unreachable!\n  match l with\n  | Level.zero _ => `(Prop)\n  | Level.succ (Level.zero _) _ => `(Type)\n  | _ => match l.dec with\n    | some l' => `(Type $(Level.quote l' max_prec))\n    | none    => `(Sort $(Level.quote l max_prec))\n\n\ndef unresolveNameGlobal (n\u2080 : Name) : DelabM Name := do\n  if n\u2080.hasMacroScopes then return n\u2080\n  if (\u2190 getPPOption getPPFullNames) then\n    match (\u2190 resolveGlobalName n\u2080) with\n      | [(potentialMatch, _)] => if potentialMatch == n\u2080 then return n\u2080 else return rootNamespace ++ n\u2080\n      | _ => return n\u2080 -- if can't resolve, return the original\n  let mut initialNames := (getRevAliases (\u2190 getEnv) n\u2080).toArray\n  initialNames := initialNames.push (rootNamespace ++ n\u2080)\n  for initialName in initialNames do\n    match (\u2190 unresolveNameCore initialName) with\n    | none => continue\n    | some n => return n\n  return n\u2080 -- if can't resolve, return the original\nwhere\n  unresolveNameCore (n : Name) : DelabM (Option Name) := do\n    let mut revComponents := n.components'\n    let mut candidate := Name.anonymous\n    for i in [:revComponents.length] do\n      match revComponents with\n      | [] => return none\n      | cmpt::rest => candidate := cmpt ++ candidate; revComponents := rest\n      match (\u2190 resolveGlobalName candidate) with\n      | [(potentialMatch, _)] => if potentialMatch == n\u2080 then return some candidate else continue\n      | _ => continue\n    return none\n\n-- NOTE: not a registered delaborator, as `const` is never called (see [delab] description)\ndef delabConst : Delab := do\n  let Expr.const c\u2080 ls _ \u2190 getExpr | unreachable!\n  let ctx \u2190 read\n  let c\u2080 := if (\u2190 getPPOption getPPPrivateNames) then c\u2080 else (privateToUserName? c\u2080).getD c\u2080\n\n  let mut c \u2190 unresolveNameGlobal c\u2080\n  let stx \u2190\n    if ls.isEmpty || !(\u2190 getPPOption getPPUniverses) then\n      if (\u2190 getLCtx).usesUserName c then\n        -- `c` is also a local declaration\n        if c == c\u2080 && !(\u2190 read).inPattern then\n          -- `c` is the fully qualified named. So, we append the `_root_` prefix\n          c := `_root_ ++ c\n        else\n          c := c\u2080\n      pure <| mkIdent c\n    else\n      `($(mkIdent c).{$[$(ls.toArray.map quote)],*})\n\n  let mut stx \u2190 maybeAddBlockImplicit stx\n  if (\u2190 getPPOption getPPTagAppFns) then\n    stx \u2190 annotateCurPos stx\n    addTermInfo (\u2190 getPos) stx (\u2190 getExpr)\n  return stx\n\ndef withMDataOptions [Inhabited \u03b1] (x : DelabM \u03b1) : DelabM \u03b1 := do\n  match \u2190 getExpr with\n  | Expr.mdata m .. =>\n    let mut posOpts := (\u2190 read).optionsPerPos\n    let pos \u2190 getPos\n    for (k, v) in m do\n      if (`pp).isPrefixOf k then\n        let opts := posOpts.find? pos |>.getD {}\n        posOpts := posOpts.insert pos (opts.insert k v)\n    withReader ({ \u00b7 with optionsPerPos := posOpts }) $ withMDataExpr x\n  | _ => x\n\npartial def withMDatasOptions [Inhabited \u03b1] (x : DelabM \u03b1) : DelabM \u03b1 := do\n  if (\u2190 getExpr).isMData then withMDataOptions (withMDatasOptions x) else x\n\ndef delabAppFn : Delab := do\n  if (\u2190 getExpr).consumeMData.isConst then\n    withMDatasOptions delabConst\n  else\n    delab\n\nstructure ParamKind where\n  name        : Name\n  bInfo       : BinderInfo\n  defVal      : Option Expr := none\n  isAutoParam : Bool := false\n\ndef ParamKind.isRegularExplicit (param : ParamKind) : Bool :=\n  param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone\n\n/-- Return array with n-th element set to kind of n-th parameter of `e`. -/\npartial def getParamKinds : DelabM (Array ParamKind) := do\n  let e \u2190 getExpr\n  try\n    withTransparency TransparencyMode.all do\n      forallTelescopeArgs e.getAppFn e.getAppArgs fun params _ => do\n        params.mapM fun param => do\n          let l \u2190 getLocalDecl param.fvarId!\n          pure { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam }\n  catch _ => pure #[] -- recall that expr may be nonsensical\nwhere\n  forallTelescopeArgs f args k := do\n    forallBoundedTelescope (\u2190 inferType f) args.size fun xs b =>\n      if xs.isEmpty || xs.size == args.size then\n        -- we still want to consider optParams\n        forallTelescopeReducing b fun ys b => k (xs ++ ys) b\n      else\n        forallTelescopeArgs (mkAppN f $ args.shrink xs.size) (args.extract xs.size args.size) fun ys b =>\n          k (xs ++ ys) b\n\n@[builtinDelab app]\ndef delabAppExplicit : Delab := do\n  let paramKinds \u2190 getParamKinds\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (do\n      let stx \u2190 delabAppFn\n      let needsExplicit := stx.getKind != ``Lean.Parser.Term.explicit\n      let stx \u2190 if needsExplicit then `(@$stx) else pure stx\n      pure (stx, paramKinds.toList, #[]))\n    (fun \u27e8fnStx, paramKinds, argStxs\u27e9 => do\n      let isInstImplicit := match paramKinds with\n                            | [] => false\n                            | param :: _ => param.bInfo == BinderInfo.instImplicit\n      let argStx \u2190 if \u2190 getPPOption getPPAnalysisHole then `(_)\n                   else if isInstImplicit == true then\n                     let stx \u2190 if \u2190 getPPOption getPPInstances then delab else `(_)\n                     if \u2190 getPPOption getPPInstanceTypes then\n                       let typeStx \u2190 withType delab\n                       `(($stx : $typeStx))\n                     else pure stx\n                   else delab\n      pure (fnStx, paramKinds.tailD [], argStxs.push argStx))\n  return Syntax.mkApp fnStx argStxs\n\ndef shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do\n  pure (getPPMotivesAll opts)\n  <||> (pure (getPPMotivesPi opts) <&&> returnsPi motive)\n  <||> (pure (getPPMotivesNonConst opts) <&&> isNonConstFun motive)\n\ndef isRegularApp : DelabM Bool := do\n  let e \u2190 getExpr\n  if not (unfoldMDatas e.getAppFn).isConst then return false\n  if \u2190 withNaryFn (withMDatasOptions (getPPOption getPPUniverses <||> getPPOption getPPAnalysisBlockImplicit)) then return false\n  for i in [:e.getAppNumArgs] do\n    if \u2190 withNaryArg i (getPPOption getPPAnalysisNamedArg) then return false\n  return true\n\ndef unexpandRegularApp (stx : Syntax) : Delab := do\n  let Expr.const c .. := (unfoldMDatas (\u2190 getExpr).getAppFn) | unreachable!\n  let fs := appUnexpanderAttribute.getValues (\u2190 getEnv) c\n  let ref \u2190 getRef\n  fs.firstM fun f =>\n    match f stx |>.run ref |>.run () with\n    | EStateM.Result.ok stx _ => pure stx\n    | _ => failure\n\n-- abbrev coe {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeT \u03b1 a \u03b2] : \u03b2\n-- abbrev coeFun {\u03b1 : Sort u} {\u03b3 : \u03b1 \u2192 Sort v} (a : \u03b1) [CoeFun \u03b1 \u03b3] : \u03b3 a\ndef unexpandCoe (stx : Syntax) : Delab := whenPPOption getPPCoercions do\n  if not (isCoe (\u2190 getExpr)) then failure\n  let e \u2190 getExpr\n  match stx with\n  | `($fn $arg)   => return arg\n  | `($fn $args*) => `($(args.get! 0) $(args.eraseIdx 0)*)\n  | _             => failure\n\ndef unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do\n  let env \u2190 getEnv\n  let e \u2190 getExpr\n  let some s \u2190 pure $ e.isConstructorApp? env | failure\n  guard $ isStructure env s.induct;\n  /- If implicit arguments should be shown, and the structure has parameters, we should not\n     pretty print using { ... }, because we will not be able to see the parameters. -/\n  let fieldNames := getStructureFields env s.induct\n  let mut fields := #[]\n  guard $ fieldNames.size == stx[1].getNumArgs\n  let args := e.getAppArgs\n  let fieldVals := args.extract s.numParams args.size\n  for idx in [:fieldNames.size] do\n    let fieldName := fieldNames[idx]\n    let fieldId := mkIdent fieldName\n    let fieldPos \u2190 nextExtraPos\n    let fieldId := annotatePos fieldPos fieldId\n    addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx]\n    let field \u2190 `(structInstField|$fieldId:ident := $(stx[1][idx]):term)\n    fields := fields.push field\n  let tyStx \u2190 withType do\n    if (\u2190 getPPOption getPPStructureInstanceType) then delab >>= pure \u2218 some else pure none\n  if fields.isEmpty then\n    `({ $[: $tyStx]? })\n  else\n    let lastField := fields.back\n    fields := fields.pop\n    `({ $[$fields, ]* $lastField $[: $tyStx]? })\n\n@[builtinDelab app]\ndef delabAppImplicit : Delab := do\n  -- TODO: always call the unexpanders, make them guard on the right # args?\n  let paramKinds \u2190 getParamKinds\n  if \u2190 getPPOption getPPExplicit then\n    if paramKinds.any (fun param => !param.isRegularExplicit) then failure\n\n  -- If the application has an implicit function type, fall back to delabAppExplicit.\n  -- This is e.g. necessary for `@Eq`.\n  let isImplicitApp \u2190 try\n      let ty \u2190 whnf (\u2190 inferType (\u2190 getExpr))\n      pure <| ty.isForall && (ty.binderInfo == BinderInfo.implicit || ty.binderInfo == BinderInfo.instImplicit)\n    catch _ => pure false\n  if isImplicitApp then failure\n\n  let (fnStx, _, argStxs) \u2190 withAppFnArgs\n    (return (\u2190 delabAppFn, paramKinds.toList, #[]))\n    (fun (fnStx, paramKinds, argStxs) => do\n      let arg \u2190 getExpr\n      let opts \u2190 getOptions\n      let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do\n        `(Parser.Term.namedArgument| ($(mkIdent name):ident := $argStx:term))\n      let argStx? : Option Syntax \u2190\n        if \u2190 getPPOption getPPAnalysisSkip then pure none\n        else if \u2190 getPPOption getPPAnalysisHole then `(_)\n        else\n          match paramKinds with\n          | [] => delab\n          | param :: rest =>\n            if param.defVal.isSome && rest.isEmpty then\n              let v := param.defVal.get!\n              if !v.hasLooseBVars && v == arg then pure none else delab\n            else if !param.isRegularExplicit && param.defVal.isNone then\n              if \u2190 getPPOption getPPAnalysisNamedArg <||> (pure (param.name == `motive) <&&> shouldShowMotive arg opts) then mkNamedArg param.name (\u2190 delab) else pure none\n            else delab\n      let argStxs := match argStx? with\n        | none => argStxs\n        | some stx => argStxs.push stx\n      pure (fnStx, paramKinds.tailD [], argStxs))\n  let stx := Syntax.mkApp fnStx argStxs\n\n  if \u2190 isRegularApp then\n    (guard (\u2190 getPPOption getPPNotation) *> unexpandRegularApp stx)\n    <|> (guard (\u2190 getPPOption getPPStructureInstances) *> unexpandStructureInstance stx)\n    <|> (guard (\u2190 getPPOption getPPNotation) *> unexpandCoe stx)\n    <|> pure stx\n  else pure stx\n\n/-- State for `delabAppMatch` and helpers. -/\nstructure AppMatchState where\n  info        : MatcherInfo\n  matcherTy   : Expr\n  params      : Array Expr := #[]\n  motive      : Option (Syntax \u00d7 Expr) := none\n  motiveNamed : Bool := false\n  discrs      : Array Syntax := #[]\n  varNames    : Array (Array Name) := #[]\n  rhss        : Array Syntax := #[]\n  -- additional arguments applied to the result of the `match` expression\n  moreArgs    : Array Syntax := #[]\n/--\n  Extract arguments of motive applications from the matcher type.\n  For the example below: `#[#[`([])], #[`(a::as)]]` -/\nprivate partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Syntax)) :=\n  withReader (fun ctx => { ctx with inPattern := true, optionsPerPos := {} }) do\n    let ty \u2190 instantiateForall st.matcherTy st.params\n    forallTelescope ty fun params _ => do\n      -- skip motive and discriminators\n      let alts := Array.ofSubarray params[1 + st.discrs.size:]\n      alts.mapIdxM fun idx alt => do\n        let ty \u2190 inferType alt\n        -- TODO: this is a hack; we are accessing the expression out-of-sync with the position\n        -- Currently, we reset `optionsPerPos` at the beginning of `delabPatterns` to avoid\n        -- incorrectly considering annotations.\n        withTheReader SubExpr ({ \u00b7 with expr := ty }) $\n          usingNames st.varNames[idx] do\n            withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (\u2190 delab))\nwhere\n  usingNames {\u03b1} (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    usingNamesAux 0 varNames x\n  usingNamesAux {\u03b1} (i : Nat) (varNames : Array Name) (x : DelabM \u03b1) : DelabM \u03b1 :=\n    if i < varNames.size then\n      withBindingBody varNames[i] <| usingNamesAux (i+1) varNames x\n    else\n      x\n\n/-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/\nprivate partial def skippingBinders {\u03b1} (numParams : Nat) (x : Array Name \u2192 DelabM \u03b1) : DelabM \u03b1 :=\n  loop numParams #[]\nwhere\n  loop : Nat \u2192 Array Name \u2192 DelabM \u03b1\n    | 0,   varNames => x varNames\n    | n+1, varNames => do\n      let rec visitLambda : DelabM \u03b1 := do\n        let varName := (\u2190 getExpr).bindingName!.eraseMacroScopes\n        -- Pattern variables cannot shadow each other\n        if varNames.contains varName then\n          let varName := (\u2190 getLCtx).getUnusedName varName\n          withBindingBody varName do\n            loop n (varNames.push varName)\n        else\n          withBindingBodyUnusedName fun id => do\n            loop n (varNames.push id.getId)\n      let e \u2190 getExpr\n      if e.isLambda then\n        visitLambda\n      else\n        -- eta expand `e`\n        let e \u2190 forallTelescopeReducing (\u2190 inferType e) fun xs _ => do\n          if xs.size == 1 && (\u2190 inferType xs[0]).isConstOf ``Unit then\n            -- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable.\n            -- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable.\n            -- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure\n            -- it adds an annotation to distinguish these two cases.\n            mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit))\n          else\n            mkLambdaFVars xs (mkAppN e xs)\n        withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda\n\n/--\n  Delaborate applications of \"matchers\" such as\n  ```\n  List.map.match_1 : {\u03b1 : Type _} \u2192\n    (motive : List \u03b1 \u2192 Sort _) \u2192\n      (x : List \u03b1) \u2192 (Unit \u2192 motive List.nil) \u2192 ((a : \u03b1) \u2192 (as : List \u03b1) \u2192 motive (a :: as)) \u2192 motive x\n  ```\n-/\n@[builtinDelab app]\ndef delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do\n  -- incrementally fill `AppMatchState` from arguments\n  let st \u2190 withAppFnArgs\n    (do\n      let (Expr.const c us _) \u2190 getExpr | failure\n      let (some info) \u2190 getMatcherInfo? c | failure\n      return { matcherTy := (\u2190 getConstInfo c).instantiateTypeLevelParams us, info := info : AppMatchState })\n    (fun st => do\n      if st.params.size < st.info.numParams then\n        pure { st with params := st.params.push (\u2190 getExpr) }\n      else if st.motive.isNone then\n         -- store motive argument separately\n         let lamMotive \u2190 getExpr\n         let piMotive \u2190 lambdaTelescope lamMotive fun xs body => mkForallFVars xs body\n         -- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive`\n         -- Thus the binder types won't have any annotations\n         let piStx \u2190 withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab\n         let named \u2190 getPPOption getPPAnalysisNamedArg\n         pure { st with motive := (piStx, lamMotive), motiveNamed := named }\n      else if st.discrs.size < st.info.numDiscrs then\n        pure { st with discrs := st.discrs.push (\u2190 delab) }\n      else if st.rhss.size < st.info.altNumParams.size then\n        /- We save the variables names here to be able to implement safe_shadowing.\n           The pattern delaboration must use the names saved here. -/\n        let (varNames, rhs) \u2190 skippingBinders st.info.altNumParams[st.rhss.size] fun varNames => do\n          let rhs \u2190 delab\n          return (varNames, rhs)\n        pure { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }\n      else\n        pure { st with moreArgs := st.moreArgs.push (\u2190 delab) })\n\n  if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then\n    -- underapplied\n    failure\n\n  match st.discrs, st.rhss with\n  | #[discr], #[] =>\n    let stx \u2190 `(nomatch $discr)\n    return Syntax.mkApp stx st.moreArgs\n  | _,        #[] => failure\n  | _,        _   =>\n    let pats \u2190 delabPatterns st\n    let stx \u2190 do\n      let (piStx, lamMotive) := st.motive.get!\n      let opts \u2190 getOptions\n      -- TODO: disable the match if other implicits are needed?\n      if \u2190 pure st.motiveNamed <||> shouldShowMotive lamMotive opts then\n        `(match $[$st.discrs:term],* : $piStx with $[| $pats,* => $st.rhss]*)\n      else\n        `(match $[$st.discrs:term],* with $[| $pats,* => $st.rhss]*)\n    return Syntax.mkApp stx st.moreArgs\n\n/--\n  Delaborate applications of the form `(fun x => b) v` as `let_fun x := v; b`\n-/\ndef delabLetFun : Delab := do\n  let stxV \u2190 withAppArg delab\n  withAppFn do\n    let Expr.lam n t b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxB \u2190 withBindingBody n delab\n    if \u2190 getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then\n      let stxT \u2190 withBindingDomain delab\n      `(let_fun $(mkIdent n) : $stxT := $stxV; $stxB)\n    else\n      `(let_fun $(mkIdent n) := $stxV; $stxB)\n\n@[builtinDelab mdata]\ndef delabMData : Delab := do\n  if let some _ := inaccessible? (\u2190 getExpr) then\n    let s \u2190 withMDataExpr delab\n    if (\u2190 read).inPattern then\n      `(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns\n    else\n      return s\n  else if isLetFun (\u2190 getExpr) && getPPNotation (\u2190 getOptions) then\n    withMDataExpr <| delabLetFun\n  else if let some _ := isLHSGoal? (\u2190 getExpr) then\n    withMDataExpr <| withAppFn <| withAppArg <| delab\n  else\n    withMDataOptions delab\n\n/--\nCheck for a `Syntax.ident` of the given name anywhere in the tree.\nThis is usually a bad idea since it does not check for shadowing bindings,\nbut in the delaborator we assume that bindings are never shadowed.\n-/\npartial def hasIdent (id : Name) : Syntax \u2192 Bool\n  | Syntax.ident _ _ id' _ => id == id'\n  | Syntax.node _ _ args   => args.any (hasIdent id)\n  | _                      => false\n\n/--\nReturn `true` iff current binder should be merged with the nested\nbinder, if any, into a single binder group:\n* both binders must have same binder info and domain\n* they cannot be inst-implicit (`[a b : A]` is not valid syntax)\n* `pp.binderTypes` must be the same value for both terms\n* prefer `fun a b` over `fun (a b)`\n-/\nprivate def shouldGroupWithNext : DelabM Bool := do\n  let e \u2190 getExpr\n  let ppEType \u2190 getPPOption (getPPBinderTypes e)\n  let go (e' : Expr) := do\n    let ppE'Type \u2190 withBindingBody `_ $ getPPOption (getPPBinderTypes e)\n    pure $ e.binderInfo == e'.binderInfo &&\n      e.bindingDomain! == e'.bindingDomain! &&\n      e'.binderInfo != BinderInfo.instImplicit &&\n      ppEType == ppE'Type &&\n      (e'.binderInfo != BinderInfo.default || ppE'Type)\n  match e with\n  | Expr.lam _ _     e'@(Expr.lam _ _ _ _) _     => go e'\n  | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'\n  | _ => pure false\nwhere\n  getPPBinderTypes (e : Expr) :=\n    if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes\n\nprivate partial def delabBinders (delabGroup : Array Syntax \u2192 Syntax \u2192 Delab) : optParam (Array Syntax) #[] \u2192 Delab\n  -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished\n  -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping\n  -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.\n  | curNames => do\n    if \u2190 shouldGroupWithNext then\n      -- group with nested binder => recurse immediately\n      withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)\n    else\n      -- don't group => delab body and prepend current binder group\n      let (stx, stxN) \u2190 withBindingBodyUnusedName fun stxN => return (\u2190 delab, stxN)\n      delabGroup (curNames.push stxN) stx\n\n@[builtinDelab lam]\ndef delabLam : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let stxT \u2190 withBindingDomain delab\n    let ppTypes \u2190 getPPOption getPPFunBinderTypes\n    let expl \u2190 getPPOption getPPExplicit\n    let usedDownstream := curNames.any (fun n => hasIdent n.getId stxBody)\n\n    -- leave lambda implicit if possible\n    -- TODO: for now we just always block implicit lambdas when delaborating. We can revisit.\n    -- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit,\n    -- it doesn't seem like we can leave a subsequent binder implicit.\n    let blockImplicitLambda := true\n    /-\n    let blockImplicitLambda := expl ||\n      e.binderInfo == BinderInfo.default ||\n      -- Note: the following restriction fixes many issues with roundtripping,\n      -- but this condition may still not be perfectly in sync with the elaborator.\n      e.binderInfo == BinderInfo.instImplicit ||\n      Elab.Term.blockImplicitLambda stxBody ||\n      usedDownstream\n    -/\n\n    if !blockImplicitLambda then\n      pure stxBody\n    else\n      let defaultCase (_ : Unit) : Delab := do\n        if ppTypes then\n          -- \"default\" binder group is the only one that expects binder names\n          -- as a term, i.e. a single `Syntax.ident` or an application thereof\n          let stxCurNames \u2190\n            if curNames.size > 1 then\n              `($(curNames.get! 0) $(curNames.eraseIdx 0)*)\n            else\n              pure $ curNames.get! 0;\n          `(funBinder| ($stxCurNames : $stxT))\n        else\n          pure curNames.back  -- here `curNames.size == 1`\n      let group \u2190 match e.binderInfo, ppTypes with\n        | BinderInfo.default,        _      => defaultCase ()\n        | BinderInfo.auxDecl,        _      => defaultCase ()\n        | BinderInfo.implicit,       true   => `(funBinder| {$curNames* : $stxT})\n        | BinderInfo.implicit,       false  => `(funBinder| {$curNames*})\n        | BinderInfo.strictImplicit, true   => `(funBinder| \u2983$curNames* : $stxT\u2984)\n        | BinderInfo.strictImplicit, false  => `(funBinder| \u2983$curNames*\u2984)\n        | BinderInfo.instImplicit,   _     =>\n          if usedDownstream then `(funBinder| [$curNames.back : $stxT])  -- here `curNames.size == 1`\n          else  `(funBinder| [$stxT])\n      match stxBody with\n      | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody)\n      | _                                 => `(fun $group => $stxBody)\n\n@[builtinDelab forallE]\ndef delabForall : Delab :=\n  delabBinders fun curNames stxBody => do\n    let e \u2190 getExpr\n    let prop \u2190 try isProp e catch _ => pure false\n    let stxT \u2190 withBindingDomain delab\n    let group \u2190 match e.binderInfo with\n    | BinderInfo.implicit       => `(bracketedBinderF|{$curNames* : $stxT})\n    | BinderInfo.strictImplicit => `(bracketedBinderF|\u2983$curNames* : $stxT\u2984)\n    -- here `curNames.size == 1`\n    | BinderInfo.instImplicit   => `(bracketedBinderF|[$curNames.back : $stxT])\n    | _                         =>\n      -- heuristic: use non-dependent arrows only if possible for whole group to avoid\n      -- noisy mix like `(\u03b1 : Type) \u2192 Type \u2192 (\u03b3 : Type) \u2192 ...`.\n      let dependent := curNames.any fun n => hasIdent n.getId stxBody\n      -- NOTE: non-dependent arrows are available only for the default binder info\n      if dependent then\n        if prop && !(\u2190 getPPOption getPPPiBinderTypes) then\n          return \u2190 `(\u2200 $curNames:ident*, $stxBody)\n        else\n          `(bracketedBinderF|($curNames* : $stxT))\n      else\n        return \u2190 curNames.foldrM (fun _ stxBody => `($stxT \u2192 $stxBody)) stxBody\n    if prop then\n      match stxBody with\n      | `(\u2200 $groups*, $stxBody) => `(\u2200 $group $groups*, $stxBody)\n      | _                       => `(\u2200 $group, $stxBody)\n    else\n      `($group:bracketedBinder \u2192 $stxBody)\n\n@[builtinDelab letE]\ndef delabLetE : Delab := do\n  let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n  let n \u2190 getUnusedName n b\n  let stxV \u2190 descend v 1 delab\n  let stxB \u2190 withLetDecl n t v fun fvar =>\n    let b := b.instantiate1 fvar\n    descend b 2 delab\n  if \u2190 getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then\n    let stxT \u2190 descend t 0 delab\n    `(let $(mkIdent n) : $stxT := $stxV; $stxB)\n  else `(let $(mkIdent n) := $stxV; $stxB)\n\n@[builtinDelab lit]\ndef delabLit : Delab := do\n  let Expr.lit l _ \u2190 getExpr | unreachable!\n  match l with\n  | Literal.natVal n => pure $ quote n\n  | Literal.strVal s => pure $ quote s\n\n-- `@OfNat.ofNat _ n _` ~> `n`\n@[builtinDelab app.OfNat.ofNat]\ndef delabOfNat : Delab := whenPPOption getPPCoercions do\n  let (Expr.app (Expr.app _ (Expr.lit (Literal.natVal n) _) _) _ _) \u2190 getExpr | failure\n  return quote n\n\n-- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true`\n@[builtinDelab app.OfScientific.ofScientific]\ndef delabOfScientific : Delab := whenPPOption getPPCoercions do\n  let expr \u2190 getExpr\n  guard <| expr.getAppNumArgs == 5\n  let Expr.lit (Literal.natVal m) _ \u2190 pure (expr.getArg! 2) | failure\n  let Expr.lit (Literal.natVal e) _ \u2190 pure (expr.getArg! 4) | failure\n  let s \u2190 match expr.getArg! 3 with\n    | Expr.const `Bool.true _ _  => pure true\n    | Expr.const `Bool.false _ _ => pure false\n    | _ => failure\n  let str  := toString m\n  if s && e == str.length then\n    return Syntax.mkScientificLit (\"0.\" ++ str)\n  else if s && e < str.length then\n    let mStr := str.extract 0 (str.length - e)\n    let eStr := str.extract (str.length - e) str.length\n    return Syntax.mkScientificLit (mStr ++ \".\" ++ eStr)\n  else\n    return Syntax.mkScientificLit (str ++ \"e\" ++ (if s then \"-\" else \"\") ++ toString e)\n\n/--\nDelaborate a projection primitive. These do not usually occur in\nuser code, but are pretty-printed when e.g. `#print`ing a projection\nfunction.\n-/\n@[builtinDelab proj]\ndef delabProj : Delab := do\n  let Expr.proj _ idx _ _ \u2190 getExpr | unreachable!\n  let e \u2190 withProj delab\n  -- not perfectly authentic: elaborates to the `idx`-th named projection\n  -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual\n  -- `proj`.\n  let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1));\n  `($(e).$idx:fieldIdx)\n\n/-- Delaborate a call to a projection function such as `Prod.fst`. -/\n@[builtinDelab app]\ndef delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do\n  let e@(Expr.app fn _ _) \u2190 getExpr | failure\n  let Expr.const c@(Name.str _ f _) _ _ \u2190 pure fn.getAppFn | failure\n  let env \u2190 getEnv\n  let some info \u2190 pure $ env.getProjectionFnInfo? c | failure\n  -- can't use with classes since the instance parameter is implicit\n  guard $ !info.fromClass\n  -- projection function should be fully applied (#struct params + 1 instance parameter)\n  -- TODO: support over-application\n  guard $ e.getAppNumArgs == info.numParams + 1\n  -- If pp.explicit is true, and the structure has parameters, we should not\n  -- use field notation because we will not be able to see the parameters.\n  let expl \u2190 getPPOption getPPExplicit\n  guard $ !expl || info.numParams == 0\n  let appStx \u2190 withAppArg delab\n  `($(appStx).$(mkIdent f):ident)\n\n@[builtinDelab app.dite]\ndef delabDIte : Delab := whenPPOption getPPNotation do\n  -- Note: we keep this as a delaborator for now because it actually accesses the expression.\n  guard $ (\u2190 getExpr).getAppNumArgs == 5\n  let c \u2190 withAppFn $ withAppFn $ withAppFn $ withAppArg delab\n  let (t, h) \u2190 withAppFn $ withAppArg $ delabBranch none\n  let (e, _) \u2190 withAppArg $ delabBranch h\n  `(if $(mkIdent h):ident : $c then $t else $e)\nwhere\n  delabBranch (h? : Option Name) : DelabM (Syntax \u00d7 Name) := do\n    let e \u2190 getExpr\n    guard e.isLambda\n    let h \u2190 match h? with\n      | some h => return (\u2190 withBindingBody h delab, h)\n      | none   => withBindingBodyUnusedName fun h => do\n        return (\u2190 delab, h.getId)\n\n@[builtinDelab app.namedPattern]\ndef delabNamedPattern : Delab := do\n  -- Note: we keep this as a delaborator because it accesses the DelabM context\n  guard (\u2190 read).inPattern\n  guard $ (\u2190 getExpr).getAppNumArgs == 4\n  let x \u2190 withAppFn $ withAppFn $ withAppArg delab\n  let p \u2190 withAppFn $ withAppArg delab\n  -- TODO: we should hide `h` if it has an inaccessible name and is not used in the rhs\n  let h \u2190 withAppArg delab\n  guard x.isIdent\n  `($x:ident@$h:ident:$p:term)\n\n-- Sigma and PSigma delaborators\ndef delabSigmaCore (sigma : Bool) : Delab := whenPPOption getPPNotation do\n  guard $ (\u2190 getExpr).getAppNumArgs == 2\n  guard $ (\u2190 getExpr).appArg!.isLambda\n  withAppArg do\n    let \u03b1 \u2190 withBindingDomain delab\n    let bodyExpr := (\u2190 getExpr).bindingBody!\n    withBindingBodyUnusedName fun n => do\n      let b \u2190 delab\n      if bodyExpr.hasLooseBVars then\n        if sigma then `(($n:ident : $\u03b1) \u00d7 $b) else `(($n:ident : $\u03b1) \u00d7' $b)\n      else\n        if sigma then `((_ : $\u03b1) \u00d7 $b) else `((_ : $\u03b1) \u00d7' $b)\n\n@[builtinDelab app.Sigma]\ndef delabSigma : Delab := delabSigmaCore (sigma := true)\n\n@[builtinDelab app.PSigma]\ndef delabPSigma : Delab := delabSigmaCore (sigma := false)\n\npartial def delabDoElems : DelabM (List Syntax) := do\n  let e \u2190 getExpr\n  if e.isAppOfArity `Bind.bind 6 then\n    -- Bind.bind.{u, v} : {m : Type u \u2192 Type v} \u2192 [self : Bind m] \u2192 {\u03b1 \u03b2 : Type u} \u2192 m \u03b1 \u2192 (\u03b1 \u2192 m \u03b2) \u2192 m \u03b2\n    let \u03b1 := e.getAppArgs[2]\n    let ma \u2190 withAppFn $ withAppArg delab\n    withAppArg do\n      match (\u2190 getExpr) with\n      | Expr.lam _ _ body _ =>\n        withBindingBodyUnusedName fun n => do\n          if body.hasLooseBVars then\n            prependAndRec `(doElem|let $n:term \u2190 $ma:term)\n          else if \u03b1.isConstOf `Unit || \u03b1.isConstOf `PUnit then\n            prependAndRec `(doElem|$ma:term)\n          else\n            prependAndRec `(doElem|let _ \u2190 $ma:term)\n      | _ => failure\n  else if e.isLet then\n    let Expr.letE n t v b _ \u2190 getExpr | unreachable!\n    let n \u2190 getUnusedName n b\n    let stxT \u2190 descend t 0 delab\n    let stxV \u2190 descend v 1 delab\n    withLetDecl n t v fun fvar =>\n      let b := b.instantiate1 fvar\n      descend b 2 $\n        prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV)\n  else\n    let stx \u2190 delab\n    return [\u2190`(doElem|$stx:term)]\n  where\n    prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems\n\n@[builtinDelab app.Bind.bind]\ndef delabDo : Delab := whenPPOption getPPNotation do\n  guard <| (\u2190 getExpr).isAppOfArity `Bind.bind 6\n  let elems \u2190 delabDoElems\n  let items \u2190 elems.toArray.mapM (`(doSeqItem|$(\u00b7):doElem))\n  `(do $items:doSeqItem*)\n\ndef reifyName : Expr \u2192 DelabM Name\n  | Expr.const ``Lean.Name.anonymous .. => return Name.anonymous\n  | Expr.app (Expr.app (Expr.const ``Lean.Name.mkStr ..) n _) (Expr.lit (Literal.strVal s) _) _ => return (\u2190 reifyName n).mkStr s\n  | Expr.app (Expr.app (Expr.const ``Lean.Name.mkNum ..) n _) (Expr.lit (Literal.natVal i) _) _ => return (\u2190 reifyName n).mkNum i\n  | _ => failure\n\n@[builtinDelab app.Lean.Name.mkStr]\ndef delabNameMkStr : Delab := whenPPOption getPPNotation do\n  let n \u2190 reifyName (\u2190 getExpr)\n  -- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version\n  return mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{n}\"]\n\n@[builtinDelab app.Lean.Name.mkNum]\ndef delabNameMkNum : Delab := delabNameMkStr\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/Builtins.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.041462274636121815, "lm_q1q2_score": 0.010282122773076288}}
{"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.Data.LOption\nimport Lean.Environment\nimport Lean.Class\nimport Lean.ReducibilityAttrs\nimport Lean.Util.Trace\nimport Lean.Util.RecDepth\nimport Lean.Util.PPExt\nimport Lean.Util.ReplaceExpr\nimport Lean.Util.OccursCheck\nimport Lean.Util.MonadBacktrack\nimport Lean.Compiler.InlineAttrs\nimport Lean.Meta.TransparencyMode\nimport Lean.Meta.DiscrTreeTypes\nimport Lean.Eval\nimport Lean.CoreM\n\n/-\nThis module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.\n1- Weak head normal form computation with support for metavariables and transparency modes.\n2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).\n3- Type inference.\n4- Type class resolution.\n\nThey are packed into the MetaM monad.\n-/\n\nnamespace Lean.Meta\n\nbuiltin_initialize isDefEqStuckExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `isDefEqStuck\n\nstructure Config where\n  foApprox           : Bool := false\n  ctxApprox          : Bool := false\n  quasiPatternApprox : Bool := false\n  /-- When `constApprox` is set to true,\n     we solve `?m t =?= c` using\n     `?m := fun _ => c`\n     when `?m t` is not a higher-order pattern and `c` is not an application as -/\n  constApprox        : Bool := false\n  /--\n    When the following flag is set,\n    `isDefEq` throws the exeption `Exeption.isDefEqStuck`\n    whenever it encounters a constraint `?m ... =?= t` where\n    `?m` is read only.\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  isDefEqStuckEx     : Bool := false\n  transparency       : TransparencyMode := TransparencyMode.default\n  /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/\n  zetaNonDep         : Bool := true\n  /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/\n  trackZeta          : Bool := false\n  unificationHints   : Bool := true\n  /-- Enables proof irrelevance at `isDefEq` -/\n  proofIrrelevance   : Bool := true\n  /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make\n      sure typing constraints resolved during elaboration should not \"fill\" holes that are supposed to be filled using tactics.\n      However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill\n      named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify\n      the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because\n      this last unification step is not really part of the term elaboration. -/\n  assignSyntheticOpaque : Bool := false\n  /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth\n      can be assigned.\n      We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few\n      cases. Recall that universe levels are often ignored by users, they may not even be aware they exist.\n      We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`.\n      We claim it is reasonable to ignore this restriction for universe metavariables because their values are often\n      contrained by the terms is instances and simp theorems.\n      TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests.\n  -/\n  ignoreLevelMVarDepth  : Bool := true\n  /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/\n  offsetCnstrs          : Bool := true\n  /-- Enable/Disable support for eta-structures. -/\n  etaStruct             : Bool := true\n\nstructure ParamInfo where\n  binderInfo     : BinderInfo := BinderInfo.default\n  hasFwdDeps     : Bool       := false\n  backDeps       : Array Nat  := #[]\n  isProp         : Bool       := false\n  isDecInst      : Bool       := false\n  deriving Inhabited\n\ndef ParamInfo.isImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.implicit\n\ndef ParamInfo.isInstImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.instImplicit\n\ndef ParamInfo.isStrictImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.strictImplicit\n\ndef ParamInfo.isExplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl\n\nstructure FunInfo where\n  paramInfo  : Array ParamInfo := #[]\n  resultDeps : Array Nat       := #[]\n\nstructure InfoCacheKey where\n  transparency : TransparencyMode\n  expr         : Expr\n  nargs?       : Option Nat\n  deriving Inhabited, BEq\n\nnamespace InfoCacheKey\ninstance : Hashable InfoCacheKey :=\n  \u27e8fun \u27e8transparency, expr, nargs\u27e9 => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)\u27e9\nend InfoCacheKey\n\nopen Std (PersistentArray PersistentHashMap)\n\nabbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)\n\nabbrev InferTypeCache := PersistentExprStructMap Expr\nabbrev FunInfoCache   := PersistentHashMap InfoCacheKey FunInfo\nabbrev WhnfCache      := PersistentExprStructMap Expr\n\n/- A set of pairs. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache).\n   We should also investigate the impact on memory consumption. -/\nabbrev DefEqCache := PersistentHashMap (Expr \u00d7 Expr) Unit\n\nstructure Cache where\n  inferType     : InferTypeCache := {}\n  funInfo       : FunInfoCache   := {}\n  synthInstance : SynthInstanceCache := {}\n  whnfDefault   : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`\n  whnfAll       : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`\n  defEqDefault  : DefEqCache := {}\n  defEqAll      : DefEqCache := {}\n  deriving Inhabited\n\n/--\n \"Context\" for a postponed universe constraint.\n `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.\n-/\nstructure DefEqContext where\n  lhs            : Expr\n  rhs            : Expr\n  lctx           : LocalContext\n  localInstances : LocalInstances\n\n/--\n  Auxiliary structure for representing postponed universe constraints.\n  Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.\n  Remark: we may consider improving the error message generation in the future.\n-/\nstructure PostponedEntry where\n  ref  : Syntax -- We save the `ref` at entry creation time\n  lhs  : Level\n  rhs  : Level\n  ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created\n  deriving Inhabited\n\nstructure State where\n  mctx        : MetavarContext := {}\n  cache       : Cache := {}\n  /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/\n  zetaFVarIds : FVarIdSet := {}\n  postponed   : PersistentArray PostponedEntry := {}\n  deriving Inhabited\n\nstructure SavedState where\n  core        : Core.State\n  meta        : State\n  deriving Inhabited\n\nstructure Context where\n  config            : Config               := {}\n  lctx              : LocalContext         := {}\n  localInstances    : LocalInstances       := #[]\n  /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/\n  defEqCtx?         : Option DefEqContext  := none\n  /--\n    Track the number of nested `synthPending` invocations. Nested invocations can happen\n    when the type class resolution invokes `synthPending`.\n\n    Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`.\n    We will add a configuration option if necessary. -/\n  synthPendingDepth : Nat                  := 0\n  /--\n    A predicate to control whether a constant can be unfolded or not at `whnf`.\n    Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/\n  canUnfold?        : Option (Config \u2192 ConstantInfo \u2192 CoreM Bool) := none\n\nabbrev MetaM  := ReaderT Context $ StateRefT State CoreM\n\n-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the\n-- whole monad stack at every use site. May eventually be covered by `deriving`.\ninstance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind }\n\ninstance : Inhabited (MetaM \u03b1) where\n  default := fun _ _ => default\n\ninstance : MonadLCtx MetaM where\n  getLCtx := return (\u2190 read).lctx\n\ninstance : MonadMCtx MetaM where\n  getMCtx    := return (\u2190 get).mctx\n  modifyMCtx f := modify fun s => { s with mctx := f s.mctx }\n\ninstance : AddMessageContext MetaM where\n  addMessageContext := addMessageContextFull\n\nprotected def saveState : MetaM SavedState :=\n  return { core := (\u2190 getThe Core.State), meta := (\u2190 get) }\n\n/-- Restore backtrackable parts of the state. -/\ndef SavedState.restore (b : SavedState) : MetaM Unit := do\n  Core.restore b.core\n  modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }\n\ninstance : MonadBacktrack SavedState MetaM where\n  saveState      := Meta.saveState\n  restoreState s := s.restore\n\n@[inline] def MetaM.run (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM (\u03b1 \u00d7 State) :=\n  x ctx |>.run s\n\n@[inline] def MetaM.run' (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM \u03b1 :=\n  Prod.fst <$> x.run ctx s\n\n@[inline] def MetaM.toIO (x : MetaM \u03b1) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (\u03b1 \u00d7 Core.State \u00d7 State) := do\n  let ((a, s), sCore) \u2190 (x.run ctx s).toIO ctxCore sCore\n  pure (a, sCore, s)\n\ninstance [MetaEval \u03b1] : MetaEval (MetaM \u03b1) :=\n  \u27e8fun env opts x _ => MetaEval.eval env opts x.run' true\u27e9\n\nprotected def throwIsDefEqStuck : MetaM \u03b1 :=\n  throw <| Exception.internal isDefEqStuckExceptionId\n\nbuiltin_initialize\n  registerTraceClass `Meta\n  registerTraceClass `Meta.debug\n\n@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM \u03b1) : m \u03b1 :=\n  liftM x\n\n@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, MetaM \u03b1 \u2192 MetaM \u03b1) {\u03b1} (x : m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f <| runInBase x\n\n@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b => runInBase <| k b\n\n@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 \u03b3 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 \u03b3 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c\n\nsection Methods\nvariable [MonadControlT MetaM n] [Monad n]\n\n@[inline] def modifyCache (f : Cache \u2192 Cache) : MetaM Unit :=\n  modify fun \u27e8mctx, cache, zetaFVarIds, postponed\u27e9 => \u27e8mctx, f cache, zetaFVarIds, postponed\u27e9\n\n@[inline] def modifyInferTypeCache (f : InferTypeCache \u2192 InferTypeCache) : MetaM Unit :=\n  modifyCache fun \u27e8ic, c1, c2, c3, c4, c5, c6\u27e9 => \u27e8f ic, c1, c2, c3, c4, c5, c6\u27e9\n\ndef getLocalInstances : MetaM LocalInstances :=\n  return (\u2190 read).localInstances\n\ndef getConfig : MetaM Config :=\n  return (\u2190 read).config\n\ndef setMCtx (mctx : MetavarContext) : MetaM Unit :=\n  modify fun s => { s with mctx := mctx }\n\ndef resetZetaFVarIds : MetaM Unit :=\n  modify fun s => { s with zetaFVarIds := {} }\n\ndef getZetaFVarIds : MetaM FVarIdSet :=\n  return (\u2190 get).zetaFVarIds\n\ndef getPostponed : MetaM (PersistentArray PostponedEntry) :=\n  return (\u2190 get).postponed\n\ndef setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := postponed }\n\n@[inline] def modifyPostponed (f : PersistentArray PostponedEntry \u2192 PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := f s.postponed }\n\n/- WARNING: The following 4 constants are a hack for simulating forward declarations.\n   They are defined later using the `export` attribute. This is hackish because we\n   have to hard-code the true arity of these definitions here, and make sure the C names match.\n   We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/\n@[extern 6 \"lean_whnf\"] constant whnf : Expr \u2192 MetaM Expr\n@[extern 6 \"lean_infer_type\"] constant inferType : Expr \u2192 MetaM Expr\n@[extern 7 \"lean_is_expr_def_eq\"] constant isExprDefEqAux : Expr \u2192 Expr \u2192 MetaM Bool\n@[extern 7 \"lean_is_level_def_eq\"] constant isLevelDefEqAux : Level \u2192 Level \u2192 MetaM Bool\n@[extern 6 \"lean_synth_pending\"] protected constant synthPending : MVarId \u2192 MetaM Bool\n\ndef whnfForall (e : Expr) : MetaM Expr := do\n  let e' \u2190 whnf e\n  if e'.isForall then pure e' else pure e\n\n-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`\nprotected def withIncRecDepth (x : n \u03b1) : n \u03b1 :=\n  mapMetaM (withIncRecDepth (m := MetaM)) x\n\nprivate def mkFreshExprMVarAtCore\n    (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do\n  modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;\n  return mkMVar mvarId\n\ndef mkFreshExprMVarAt\n    (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  mkFreshExprMVarAtCore (\u2190 mkFreshMVarId) lctx localInsts type kind userName numScopeArgs\n\ndef mkFreshLevelMVar : MetaM Level := do\n  let mvarId \u2190 mkFreshMVarId\n  modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;\n  return mkLevelMVar mvarId\n\nprivate def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do\n  mkFreshExprMVarAt (\u2190 getLCtx) (\u2190 getLocalInstances) type kind userName\n\nprivate def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarCore type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous\n    mkFreshExprMVarCore type kind userName\n\ndef mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  mkFreshExprMVarImpl type? kind userName\n\ndef mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  mkFreshExprMVar (mkSort u) kind userName\n\n/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create\n   the metavar using this method. -/\nprivate def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  mkFreshExprMVarAtCore mvarId (\u2190 getLCtx) (\u2190 getLocalInstances) type kind userName numScopeArgs\n\ndef mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarWithIdCore mvarId type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVar (mkSort u)\n    mkFreshExprMVarWithIdCore mvarId type kind userName\n\ndef mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=\n  num.foldM (init := []) fun _ us =>\n    return (\u2190 mkFreshLevelMVar)::us\n\ndef mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=\n  mkFreshLevelMVars info.numLevelParams\n\ndef mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do\n  let info \u2190 getConstInfo declName\n  return mkConst declName (\u2190 mkFreshLevelMVarsFor info)\n\ndef getTransparency : MetaM TransparencyMode :=\n  return (\u2190 getConfig).transparency\n\ndef shouldReduceAll : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.all\n\ndef shouldReduceReducibleOnly : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.reducible\n\ndef getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do\n  match (\u2190 getMCtx).findDecl? mvarId with\n  | some d => pure d\n  | none   => throwError \"unknown metavariable '?{mvarId.name}'\"\n\ndef setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.setMVarKind mvarId kind\n\n/- Update the type of the given metavariable. This function assumes the new type is\n   definitionally equal to the current one -/\ndef setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.setMVarType mvarId type\n\ndef isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do\n  return (\u2190 getMVarDecl mvarId).depth != (\u2190 getMCtx).depth\n\ndef isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  match mvarDecl.kind with\n  | MetavarKind.syntheticOpaque => return !(\u2190 getConfig).assignSyntheticOpaque\n  | _ => return mvarDecl.depth != (\u2190 getMCtx).depth\n\ndef getLevelMVarDepth (mvarId : MVarId) : MetaM Nat := do\n  match (\u2190 getMCtx).findLevelDepth? mvarId with\n  | some depth => return depth\n  | _          => throwError \"unknown universe metavariable '?{mvarId.name}'\"\n\ndef isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do\n  if (\u2190 getConfig).ignoreLevelMVarDepth then\n    return false\n  else\n    return (\u2190 getLevelMVarDepth mvarId) != (\u2190 getMCtx).depth\n\ndef renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName\n\ndef isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).isExprAssigned mvarId\n\ndef getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=\n  return (\u2190 getMCtx).getExprAssignment? mvarId\n\n/-- Return true if `e` contains `mvarId` directly or indirectly -/\ndef occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool :=\n  return (\u2190 getMCtx).occursCheck mvarId e\n\ndef assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.assignExpr mvarId val\n\ndef isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).isDelayedAssigned mvarId\n\ndef getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=\n  return (\u2190 getMCtx).getDelayedAssignment? mvarId\n\ndef hasAssignableMVar (e : Expr) : MetaM Bool :=\n  return (\u2190 getMCtx).hasAssignableMVar e\n\ndef throwUnknownFVar (fvarId : FVarId) : MetaM \u03b1 :=\n  throwError \"unknown free variable '{mkFVar fvarId}'\"\n\ndef findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=\n  return (\u2190 getLCtx).find? fvarId\n\ndef getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).find? fvarId with\n  | some d => pure d\n  | none   => throwUnknownFVar fvarId\n\ndef getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=\n  getLocalDecl fvar.fvarId!\n\ndef getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).findFromUserName? userName with\n  | some d => pure d\n  | none   => throwError \"unknown local declaration '{userName}'\"\n\ndef instantiateLevelMVars (u : Level) : MetaM Level :=\n  MetavarContext.instantiateLevelMVars u\n\ndef instantiateMVars (e : Expr) : MetaM Expr :=\n  (MetavarContext.instantiateExprMVars e).run\n\ndef instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl :=\n  match localDecl with\n  | LocalDecl.cdecl idx id n type bi  =>\n    return LocalDecl.cdecl idx id n (\u2190 instantiateMVars type) bi\n  | LocalDecl.ldecl idx id n type val nonDep =>\n    return LocalDecl.ldecl idx id n (\u2190 instantiateMVars type) (\u2190 instantiateMVars val) nonDep\n\n@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM \u03b1) : MetaM \u03b1 := do\n  match x (\u2190 getLCtx) { mctx := (\u2190 getMCtx), ngen := (\u2190 getNGen) } with\n  | EStateM.Result.ok e newS => do\n    setNGen newS.ngen;\n    setMCtx newS.mctx;\n    pure e\n  | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do\n    setMCtx newS.mctx;\n    setNGen newS.ngen;\n    throwError \"failed to create binder due to failure when reverting variable dependencies\"\n\ndef abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr :=\n  liftMkBindingM <| MetavarContext.abstractRange e n xs\n\ndef abstract (e : Expr) (xs : Array Expr) : MetaM Expr :=\n  abstractRange e xs.size xs\n\ndef mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly\n\ndef mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly\n\ndef mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr :=\n  mkLambdaFVars xs e (usedLetOnly := usedLetOnly)\n\ndef mkArrow (d b : Expr) : MetaM Expr :=\n  return Lean.mkForall (\u2190 mkFreshUserName `x) BinderInfo.default d b\n\n/-- `fun _ : Unit => a` -/\ndef mkFunUnit (a : Expr) : MetaM Expr :=\n  return Lean.mkLambda (\u2190 mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a\n\ndef elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder\n\n@[inline] def withConfig (f : Config \u2192 Config) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })\n\n@[inline] def withTrackingZeta (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with trackZeta := true }) x\n\n@[inline] def withoutProofIrrelevance (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with proofIrrelevance := false }) x\n\n@[inline] def withTransparency (mode : TransparencyMode) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withConfig (fun config => { config with transparency := mode })\n\n@[inline] def withDefault (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.default x\n\n@[inline] def withReducible (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.reducible x\n\n@[inline] def withReducibleAndInstances (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.instances x\n\n@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n \u03b1) : n \u03b1 :=\n  withConfig\n    (fun config =>\n      let oldMode := config.transparency\n      let mode    := if oldMode.lt mode then mode else oldMode\n      { config with transparency := mode })\n    x\n\n/-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/\n@[inline] def withAssignableSyntheticOpaque (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun config => { config with assignSyntheticOpaque := true }) x\n\n/-- Save cache, execute `x`, restore cache -/\n@[inline] private def savingCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let savedCache := (\u2190 get).cache\n  try x finally modify fun s => { s with cache := savedCache }\n\n@[inline] def savingCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM savingCacheImpl\n\ndef getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  if (\u2190 shouldReduceAll) then\n    return some info\n  else\n    return none\n\nprivate def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getTransparency) with\n  | TransparencyMode.all => return some info\n  | TransparencyMode.default => return some info\n  | _ =>\n    if (\u2190 isReducible info.name) then\n      return some info\n    else\n      return none\n\n/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.\n   This method is only used to implement `isClassQuickConst?`.\n   It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and\n   `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/\nprivate def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getEnv).find? constName with\n  | some (info@(ConstantInfo.thmInfo _))  => getTheoremInfo info\n  | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info\n  | some info                             => pure (some info)\n  | none                                  => throwUnknownConstant constName\n\nprivate def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do\n  if isClass (\u2190 getEnv) constName then\n    pure (LOption.some constName)\n  else\n    match (\u2190 getConstTemp? constName) with\n    | some _ => pure LOption.undef\n    | none   => pure LOption.none\n\nprivate partial def isClassQuick? : Expr \u2192 MetaM (LOption Name)\n  | Expr.bvar ..         => pure LOption.none\n  | Expr.lit ..          => pure LOption.none\n  | Expr.fvar ..         => pure LOption.none\n  | Expr.sort ..         => pure LOption.none\n  | Expr.lam ..          => pure LOption.none\n  | Expr.letE ..         => pure LOption.undef\n  | Expr.proj ..         => pure LOption.undef\n  | Expr.forallE _ _ b _ => isClassQuick? b\n  | Expr.mdata _ e _     => isClassQuick? e\n  | Expr.const n _ _     => isClassQuickConst? n\n  | Expr.mvar mvarId _   => do\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => isClassQuick? val\n    | none     => pure LOption.none\n  | Expr.app f _ _       =>\n    match f.getAppFn with\n    | Expr.const n .. => isClassQuickConst? n\n    | Expr.lam ..     => pure LOption.undef\n    | _              => pure LOption.none\n\ndef saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do\n  let savedSythInstance := (\u2190 get).cache.synthInstance\n  modifyCache fun c => { c with synthInstance := {} }\n  pure savedSythInstance\n\ndef restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=\n  modifyCache fun c => { c with synthInstance := cache }\n\n@[inline] private def resettingSynthInstanceCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let savedSythInstance \u2190 saveAndResetSynthInstanceCache\n  try x finally restoreSynthInstanceCache savedSythInstance\n\n/-- Reset `synthInstance` cache, execute `x`, and restore cache -/\n@[inline] def resettingSynthInstanceCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM resettingSynthInstanceCacheImpl\n\n@[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n \u03b1) : n \u03b1 :=\n  if b then resettingSynthInstanceCache x else x\n\nprivate def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let localDecl \u2190 getFVarLocalDecl fvar\n  /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/\n  match localDecl.binderInfo with\n  | BinderInfo.auxDecl => k\n  | _ =>\n    resettingSynthInstanceCache <|\n      withReader\n        (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })\n        k\n\n/-- Add entry `{ className := className, fvar := fvar }` to localInstances,\n    and then execute continuation `k`.\n    It resets the type class cache using `resettingSynthInstanceCache`. -/\ndef withNewLocalInstance (className : Name) (fvar : Expr) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstanceImp className fvar\n\nprivate def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=\n  match maxFVars? with\n  | some maxFVars => fvars.size < maxFVars\n  | none          => true\n\nmutual\n  /--\n    `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances\n    using free variables `fvars[j] ... fvars.back`, and execute `k`.\n\n    - `isClassExpensive` is defined later.\n    - The type class chache is reset whenever a new local instance is found.\n    - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.\n      Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/\n  private partial def withNewLocalInstancesImp\n      (fvars : Array Expr) (i : Nat) (k : MetaM \u03b1) : MetaM \u03b1 := do\n    if h : i < fvars.size then\n      let fvar := fvars.get \u27e8i, h\u27e9\n      let decl \u2190 getFVarLocalDecl fvar\n      match (\u2190 isClassQuick? decl.type) with\n      | LOption.none   => withNewLocalInstancesImp fvars (i+1) k\n      | LOption.undef  =>\n        match (\u2190 isClassExpensive? decl.type) with\n        | none   => withNewLocalInstancesImp fvars (i+1) k\n        | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n      | LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n    else\n      k\n\n  /--\n    `forallTelescopeAuxAux lctx fvars j type`\n    Remarks:\n    - `lctx` is the `MetaM` local context extended with declarations for `fvars`.\n    - `type` is the type we are computing the telescope for. It contains only\n      dangling bound variables in the range `[j, fvars.size)`\n    - if `reducing? == true` and `type` is not `forallE`, we use `whnf`.\n    - when `type` is not a `forallE` nor it can't be reduced to one, we\n      excute the continuation `k`.\n\n    Here is an example that demonstrates the `reducing?`.\n    Suppose we have\n    ```\n    abbrev StateM s a := s -> Prod a s\n    ```\n    Now, assume we are trying to build the telescope for\n    ```\n    forall (x : Nat), StateM Int Bool\n    ```\n    if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.\n    if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`\n\n    if `maxFVars?` is `some max`, then we interrupt the telescope construction\n    when `fvars.size == max`\n  -/\n  private partial def forallTelescopeReducingAuxAux\n      (reducing          : Bool) (maxFVars? : Option Nat)\n      (type              : Expr)\n      (k                 : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM \u03b1 := do\n      match type with\n      | Expr.forallE n d b c =>\n        if fvarsSizeLtMaxFVars fvars maxFVars? then\n          let d     := d.instantiateRevRange j fvars.size fvars\n          let fvarId \u2190 mkFreshFVarId\n          let lctx  := lctx.mkLocalDecl fvarId n d c.binderInfo\n          let fvar  := mkFVar fvarId\n          let fvars := fvars.push fvar\n          process lctx fvars j b\n        else\n          let type := type.instantiateRevRange j fvars.size fvars;\n          withReader (fun ctx => { ctx with lctx := lctx }) do\n            withNewLocalInstancesImp fvars j do\n              k fvars type\n      | _ =>\n        let type := type.instantiateRevRange j fvars.size fvars;\n        withReader (fun ctx => { ctx with lctx := lctx }) do\n          withNewLocalInstancesImp fvars j do\n            if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then\n              let newType \u2190 whnf type\n              if newType.isForall then\n                process lctx fvars fvars.size newType\n              else\n                k fvars type\n            else\n              k fvars type\n    process (\u2190 getLCtx) #[] 0 type\n\n  private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    match maxFVars? with\n    | some 0 => k #[] type\n    | _ => do\n      let newType \u2190 whnf type\n      if newType.isForall then\n        forallTelescopeReducingAuxAux true maxFVars? newType k\n      else\n        k #[] type\n\n  private partial def isClassExpensive? : Expr \u2192 MetaM (Option Name)\n    | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.\n      forallTelescopeReducingAux type none fun xs type => do\n        let env \u2190 getEnv\n        match type.getAppFn with\n        | Expr.const c _ _ => do\n          if isClass env c then\n            return some c\n          else\n            -- make sure abbreviations are unfolded\n            match (\u2190 whnf type).getAppFn with\n            | Expr.const c _ _ => return if isClass env c then some c else none\n            | _ => return none\n        | _ => return none\n\n  private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do\n    match (\u2190 isClassQuick? type) with\n    | LOption.none   => pure none\n    | LOption.some c => pure (some c)\n    | LOption.undef  => isClassExpensive? type\n\nend\n\ndef isClass? (type : Expr) : MetaM (Option Name) :=\n  try isClassImp? type catch _ => pure none\n\nprivate def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImp fvars j\n\npartial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImpAux fvars j\n\n@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k\n\n/--\n  Given `type` of the form `forall xs, A`, execute `k xs A`.\n  This combinator will declare local declarations, create free variables for them,\n  execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/\ndef forallTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeImp type k) k\n\nprivate def forallTelescopeReducingImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type (maxFVars? := none) k\n\n/--\n  Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,\n  it reduces `A` and continues bulding the telescope if it is a `forall`. -/\ndef forallTelescopeReducing (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeReducingImp type k) k\n\nprivate def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type maxFVars? k\n\n/--\n  Similar to `forallTelescopeReducing`, stops constructing the telescope when\n  it reaches size `maxFVars`. -/\ndef forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k\n\nprivate partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  process consumeLet (\u2190 getLCtx) #[] 0 e\nwhere\n  process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM \u03b1 := do\n    match consumeLet, e with\n    | _, Expr.lam n d b c =>\n      let d := d.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshFVarId\n      let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo\n      let fvar := mkFVar fvarId\n      process consumeLet lctx (fvars.push fvar) j b\n    | true, Expr.letE n t v b _ => do\n      let t := t.instantiateRevRange j fvars.size fvars\n      let v := v.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshFVarId\n      let lctx := lctx.mkLetDecl fvarId n t v\n      let fvar := mkFVar fvarId\n      process true lctx (fvars.push fvar) j b\n    | _, e =>\n      let e := e.instantiateRevRange j fvars.size fvars\n      withReader (fun ctx => { ctx with lctx := lctx }) do\n        withNewLocalInstancesImp fvars j do\n          k fvars e\n\n/-- Similar to `forallTelescope` but for lambda and let expressions. -/\ndef lambdaLetTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp type true k) k\n\n/-- Similar to `forallTelescope` but for lambda expressions. -/\ndef lambdaTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp type false k) k\n\n/-- Return the parameter names for the givel global declaration. -/\ndef getParamNames (declName : Name) : MetaM (Array Name) := do\n  forallTelescopeReducing (\u2190 getConstInfo declName).type fun xs _ => do\n    xs.mapM fun x => do\n      let localDecl \u2190 getLocalDecl x.fvarId!\n      pure localDecl.userName\n\n-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.\nprivate partial def forallMetaTelescopeReducingAux\n    (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  process #[] #[] 0 e\nwhere\n  process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    if maxMVars?.isEqSome mvars.size then\n      let type := type.instantiateRevRange j mvars.size mvars;\n      return (mvars, bis, type)\n    else\n      match type with\n      | Expr.forallE n d b c =>\n        let d  := d.instantiateRevRange j mvars.size mvars\n        let k  := if c.binderInfo.isInstImplicit then  MetavarKind.synthetic else kind\n        let mvar \u2190 mkFreshExprMVar d k n\n        let mvars := mvars.push mvar\n        let bis   := bis.push c.binderInfo\n        process mvars bis j b\n      | _ =>\n        let type := type.instantiateRevRange j mvars.size mvars;\n        if reducing then do\n          let newType \u2190 whnf type;\n          if newType.isForall then\n            process mvars bis mvars.size newType\n          else\n            return (mvars, bis, type)\n        else\n          return (mvars, bis, type)\n\n/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/\ndef forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind\n\n/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/\ndef forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind\n\n/-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/\ndef forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind)\n\n/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/\npartial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  process #[] #[] 0 e\nwhere\n  process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    let finalize : Unit \u2192 MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := fun _ => do\n      let type := type.instantiateRevRange j mvars.size mvars\n      pure (mvars, bis, type)\n    if maxMVars?.isEqSome mvars.size then\n      finalize ()\n    else\n      match type with\n      | Expr.lam n d b c =>\n        let d     := d.instantiateRevRange j mvars.size mvars\n        let mvar \u2190 mkFreshExprMVar d\n        let mvars := mvars.push mvar\n        let bis   := bis.push c.binderInfo\n        process mvars bis j b\n      | _ => finalize ()\n\nprivate def withNewFVar (fvar fvarType : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  match (\u2190 isClass? fvarType) with\n  | none   => k fvar\n  | some c => withNewLocalInstance c fvar <| k fvar\n\nprivate def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshFVarId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLocalDecl fvarId n type bi\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar fvar type k\n\ndef withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  map1MetaM (fun k => withLocalDeclImp name bi type k) k\n\ndef withLocalDeclD (name : Name) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecl name BinderInfo.default type k\n\npartial def withLocalDecls\n    [Inhabited \u03b1]\n    (declInfos : Array (Name \u00d7 BinderInfo \u00d7 (Array Expr \u2192 n Expr)))\n    (k : (xs : Array Expr) \u2192 n \u03b1)\n    : n \u03b1 :=\n  loop #[]\nwhere\n  loop [Inhabited \u03b1] (acc : Array Expr) : n \u03b1 := do\n    if acc.size < declInfos.size then\n      let (name, bi, typeCtor) := declInfos[acc.size]\n      withLocalDecl name bi (\u2190typeCtor acc) fun x => loop (acc.push x)\n    else\n      k acc\n\ndef withLocalDeclsD [Inhabited \u03b1] (declInfos : Array (Name \u00d7 (Array Expr \u2192 n Expr))) (k : (xs : Array Expr) \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecls\n    (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k\n\nprivate def withNewBinderInfosImp (bs : Array (FVarId \u00d7 BinderInfo)) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let lctx := bs.foldl (init := (\u2190 getLCtx)) fun lctx (fvarId, bi) =>\n      lctx.setBinderInfo fvarId bi\n  withReader (fun ctx => { ctx with lctx := lctx }) k\n\ndef withNewBinderInfos (bs : Array (FVarId \u00d7 BinderInfo)) (k : n \u03b1) : n \u03b1 :=\n  mapMetaM (fun k => withNewBinderInfosImp bs k) k\n\nprivate def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshFVarId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLetDecl fvarId n type val\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar fvar type k\n\ndef withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  map1MetaM (fun k => withLetDeclImp name type val k) k\n\nprivate def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let ctx \u2190 read\n  let numLocalInstances := ctx.localInstances.size\n  let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    let newLocalInsts \u2190 decls.foldlM\n      (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {\n        match (\u2190 isClass? decl.type) with\n        | none   => pure newlocalInsts\n        | some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))\n      ctx.localInstances;\n    if newLocalInsts.size == numLocalInstances then\n      k\n    else\n      resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k\n\ndef withExistingLocalDecls (decls : List LocalDecl) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withExistingLocalDeclsImp decls\n\nprivate def withNewMCtxDepthImp (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let saved \u2190 get\n  modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} }\n  try\n    x\n  finally\n    modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }\n\n/--\n  Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,\n  and restore saved data. -/\ndef withNewMCtxDepth : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM withNewMCtxDepthImp\n\nprivate def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let localInstsCurr \u2190 getLocalInstances\n  withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do\n    if localInsts == localInstsCurr then\n      x\n    else\n      resettingSynthInstanceCache x\n\ndef withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withLocalContextImp lctx localInsts\n\nprivate def withMVarContextImp (mvarId : MVarId) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mvarDecl \u2190 getMVarDecl mvarId\n  withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x\n\n/--\n  Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.\n  The type class resolution cache is flushed when executing `x` if its `LocalInstances` are\n  different from the current ones. -/\ndef withMVarContext (mvarId : MVarId) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMVarContextImp mvarId\n\nprivate def withMCtxImp (mctx : MetavarContext) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mctx' \u2190 getMCtx\n  setMCtx mctx\n  try x finally setMCtx mctx'\n\ndef withMCtx (mctx : MetavarContext) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMCtxImp mctx\n\n@[inline] private def approxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x\n\n/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`.  -/\n@[inline] def approxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM approxDefEqImp\n\n@[inline] private def fullApproxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x\n\n/--\n  Similar to `approxDefEq`, but uses all available approximations.\n  We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.\n  For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.\n  Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved\n  as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to\n  solve `[Pure (fun _ => IO Bool)]` -/\n@[inline] def fullApproxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM fullApproxDefEqImp\n\ndef normalizeLevel (u : Level) : MetaM Level := do\n  let u \u2190 instantiateLevelMVars u\n  pure u.normalize\n\ndef assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.assignLevel mvarId u\n\ndef whnfR (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.reducible <| whnf e\n\ndef whnfD (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.default <| whnf e\n\ndef whnfI (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.instances <| whnf e\n\ndef setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do\n  let env \u2190 getEnv\n  match Compiler.setInlineAttribute env declName kind with\n  | Except.ok env    => setEnv env\n  | Except.error msg => throwError msg\n\nprivate partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    match (\u2190 whnf e) with\n    | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)\n    | _                    => throwError \"invalid instantiateForall, too many parameters\"\n  else\n    pure e\n\n/- Given `e` 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`, return `B[p_1, ..., p_n]`. -/\ndef instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateForallAux ps 0 e\n\nprivate partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    match (\u2190 whnf e) with\n    | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)\n    | _                => throwError \"invalid instantiateLambda, too many parameters\"\n  else\n    pure e\n\n/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.\n   It uses `whnf` to reduce `e` if it is not a lambda -/\ndef instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateLambdaAux ps 0 e\n\n/-- Return true iff `e` depends on the free variable `fvarId` -/\ndef dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=\n  return (\u2190 getMCtx).exprDependsOn e fvarId\n\n/-- Return true iff `e` depends on a free variable `x` s.t. `p x` -/\ndef dependsOnPred (e : Expr) (p : FVarId \u2192 Bool) : MetaM Bool :=\n  return (\u2190 getMCtx).findExprDependsOn e p\n\n/-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `p x` -/\ndef localDeclDependsOnPred (localDecl : LocalDecl) (p : FVarId \u2192 Bool) : MetaM Bool := do\n  return (\u2190 getMCtx).findLocalDeclDependsOn localDecl p\n\ndef ppExpr (e : Expr) : MetaM Format := do\n  let ctxCore  \u2190 readThe Core.Context\n  Lean.ppExpr { env := (\u2190 getEnv), mctx := (\u2190 getMCtx), lctx := (\u2190 getLCtx), opts := (\u2190 getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls  } e\n\n@[inline] protected def orElse (x : MetaM \u03b1) (y : Unit \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let s \u2190 saveState\n  try x catch _ => s.restore; y ()\n\ninstance : OrElse (MetaM \u03b1) := \u27e8Meta.orElse\u27e9\n\ninstance : Alternative MetaM where\n  failure := fun {\u03b1} => throwError \"failed\"\n  orElse  := Meta.orElse\n\n@[inline] private def orelseMergeErrorsImp (x y : MetaM \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 r\u2082 => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ m\u2082) : MetaM \u03b1 := do\n  let env  \u2190 getEnv\n  let mctx \u2190 getMCtx\n  try\n    x\n  catch ex =>\n    setEnv env\n    setMCtx mctx\n    match ex with\n    | Exception.error ref\u2081 m\u2081 =>\n      try\n        y\n      catch\n        | Exception.error ref\u2082 m\u2082 => throw <| Exception.error (mergeRef ref\u2081 ref\u2082) (mergeMsg m\u2081 m\u2082)\n        | ex => throw ex\n    | ex => throw ex\n\n/--\n  Similar to `orelse`, but merge errors. Note that internal errors are not caught.\n  The default `mergeRef` uses the `ref` (position information) for the first message.\n  The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/\n@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 r\u2082 => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ Format.line ++ m\u2082) : m \u03b1 := do\n  controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg\n\n/-- Execute `x`, and apply `f` to the produced error message -/\ndef mapErrorImp (x : MetaM \u03b1) (f : MessageData \u2192 MessageData) : MetaM \u03b1 := do\n  try\n    x\n  catch\n    | Exception.error ref msg => throw <| Exception.error ref <| f msg\n    | ex => throw ex\n\n@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m \u03b1) (f : MessageData \u2192 MessageData) : m \u03b1 :=\n  controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f\n\n/--\n  Sort free variables using an order `x < y` iff `x` was defined before `y`.\n  If a free variable is not in the local context, we use their id. -/\ndef sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do\n  let lctx \u2190 getLCtx\n  return fvarIds.qsort fun fvarId\u2081 fvarId\u2082 =>\n    match lctx.find? fvarId\u2081, lctx.find? fvarId\u2082 with\n    | some d\u2081, some d\u2082 => d\u2081.index < d\u2082.index\n    | some _,  none    => false\n    | none,    some _  => true\n    | none,    none    => Name.quickLt fvarId\u2081.name fvarId\u2082.name\n\nend Methods\n\ndef isInductivePredicate (declName : Name) : MetaM Bool := do\n  match (\u2190 getEnv).find? declName with\n  | some (ConstantInfo.inductInfo { type := type, ..}) =>\n    forallTelescopeReducing type fun _ type => do\n      match (\u2190 whnfD type) with\n      | Expr.sort u .. => return u == levelZero\n      | _ => return false\n  | _ => return false\n\n/- -/\ndef isListLevelDefEqAux : List Level \u2192 List Level \u2192 MetaM Bool\n  | [],    []    => return true\n  | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs\n  | _,     _     => return false\n\nprivate def getNumPostponed : MetaM Nat := do\n  return (\u2190 getPostponed).size\n\ndef getResetPostponed : MetaM (PersistentArray PostponedEntry) := do\n  let ps \u2190 getPostponed\n  setPostponed {}\n  return ps\n\n/-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/\nprivate def exposeRelevantUniverses (e : Expr) (p : Level \u2192 Bool) : Expr :=\n  e.replace fun\n    | Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none\n    | Expr.sort u _     => if p u then some (e.setPPUniverses true) else none\n    | _                 => none\n\nprivate def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do\n  match entry.ctx? with\n  | none =>\n    return m!\"{header}{indentD m!\"{entry.lhs} =?= {entry.rhs}\"}\"\n  | some ctx =>\n    withLCtx ctx.lctx ctx.localInstances do\n      let s   := entry.lhs.collectMVars entry.rhs.collectMVars\n      /- `p u` is true if it contains a universe metavariable in `s` -/\n      let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false\n      let lhs := exposeRelevantUniverses (\u2190 instantiateMVars ctx.lhs) p\n      let rhs := exposeRelevantUniverses (\u2190 instantiateMVars ctx.rhs) p\n      try\n        addMessageContext m!\"{header}{indentD m!\"{entry.lhs} =?= {entry.rhs}\"}\\nwhile trying to unify{indentD m!\"{lhs} : {\u2190 inferType lhs}\"}\\nwith{indentD m!\"{rhs} : {\u2190 inferType rhs}\"}\"\n      catch _ =>\n        addMessageContext m!\"{header}{indentD m!\"{entry.lhs} =?= {entry.rhs}\"}\\nwhile trying to unify{indentD lhs}\\nwith{indentD rhs}\"\n\ndef mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do\n  mkLeveErrorMessageCore \"stuck at solving universe constraint\" entry\n\ndef mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do\n  mkLeveErrorMessageCore \"failed to solve universe constraint\" entry\n\nprivate def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool :=\n  traceCtx `Meta.isLevelDefEq.postponed.step do\n    let ps \u2190 getResetPostponed\n    for p in ps do\n      unless (\u2190 withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do\n        if exceptionOnFailure then\n          throwError (\u2190 mkLevelErrorMessage p)\n        else\n          return false\n    return true\n\npartial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do\n  if (\u2190 getNumPostponed) == 0 then\n    return true\n  else\n    traceCtx `Meta.isLevelDefEq.postponed do\n      let rec loop : MetaM Bool := do\n        let numPostponed \u2190 getNumPostponed\n        if numPostponed == 0 then\n          return true\n        else\n          trace[Meta.isLevelDefEq.postponed] \"processing #{numPostponed} postponed is-def-eq level constraints\"\n          if !(\u2190 processPostponedStep exceptionOnFailure) then\n            return false\n          else\n            let numPostponed' \u2190 getNumPostponed\n            if numPostponed' == 0 then\n              return true\n            else if numPostponed' < numPostponed then\n              loop\n            else\n              trace[Meta.isLevelDefEq.postponed] \"no progress solving pending is-def-eq level constraints\"\n              return mayPostpone\n      loop\n\n/--\n  `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`.\n  We keep the modifications only if `processPostponed` return true and `x` returned `true`.\n\n  If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning.\n  We currently try to postpone universe constraints as much as possible, even when by postponing them we\n  are not sure whether `x` really succeeded or not.\n-/\n@[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do\n  let s \u2190 saveState\n  let postponed \u2190 getResetPostponed\n  try\n    if (\u2190 x) then\n      if (\u2190 processPostponed mayPostpone) then\n        let newPostponed \u2190 getPostponed\n        setPostponed (postponed ++ newPostponed)\n        return true\n      else\n        s.restore\n        return false\n    else\n      s.restore\n      return false\n  catch ex =>\n    s.restore\n    throw ex\n\ndef isLevelDefEq (u v : Level) : MetaM Bool :=\n  traceCtx `Meta.isLevelDefEq do\n    let b \u2190 checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v\n    trace[Meta.isLevelDefEq] \"{u} =?= {v} ... {if b then \"success\" else \"failure\"}\"\n    return b\n\ndef isExprDefEq (t s : Expr) : MetaM Bool :=\n  traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do\n    let b \u2190 checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s\n    trace[Meta.isDefEq] \"{t} =?= {s} ... {if b then \"success\" else \"failure\"}\"\n    return b\n\nabbrev isDefEq (t s : Expr) : MetaM Bool :=\n  isExprDefEq t s\n\ndef isExprDefEqGuarded (a b : Expr) : MetaM Bool := do\n  try isExprDefEq a b catch _ => return false\n\nabbrev isDefEqGuarded (t s : Expr) : MetaM Bool :=\n  isExprDefEqGuarded t s\n\ndef isDefEqNoConstantApprox (t s : Expr) : MetaM Bool :=\n  approxDefEq <| isDefEq t s\n\nend Meta\n\nbuiltin_initialize\n  registerTraceClass `Meta.isLevelDefEq.postponed\n\nexport Meta (MetaM)\n\nend Lean\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/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.028870906110708947, "lm_q1q2_score": 0.010271543547179495}}
{"text": "import super.prover_state super.selection\n  super.inferences.distinct super.inferences.resolution\n  super.inferences.clausify super.inferences.empty_clause\n  super.inferences.subsumption super.inferences.superposition\n  super.inferences.factoring super.inferences.inhabited\n  super.inferences.demod\n  super.eqn_lemmas\n\nnamespace super\nopen native tactic\n\nmeta def default_preprocessing_rules : list preprocessing_rule :=\n[ preprocessing.empty_clause,\n  preprocessing.clausify,\n  preprocessing.distinct,\n  preprocessing.inhabited,\n  preprocessing.pos_refl,\n  preprocessing.neg_refl,\n  preprocessing.flip_eq,\n  preprocessing.distinct,\n  preprocessing.subsumption_interreduction\n  -- preprocessing.forward_subsumption,\n]\n\nmeta def default_simplification_rules : list simplification_rule :=\n[ simplification.forward_demod,\n  simplification.pos_refl,\n  simplification.neg_refl,\n  simplification.forward_subsumption ]\n\nmeta def default_inference_rules : list inference_rule :=\n[ inference.backward_subsumption,\n  inference.backward_demod,\n  inference.resolution,\n  inference.factoring,\n  inference.forward_superposition,\n  inference.backward_superposition,\n  inference.unify_eq ]\n\nmeta structure options :=\n(literal_selection : literal_selection_strategy := selection21)\n(clause_selection : clause_selection_strategy := age_weight_clause_selection 3 4)\n(simpl_rules : list simplification_rule := default_simplification_rules)\n(inf_rules : list inference_rule := default_inference_rules)\n(preproc_rules : list preprocessing_rule := default_preprocessing_rules)\n\nmeta def do_simplification (opts : options)\n  (given : derived_clause) : prover (option derived_clause) := do\ncls : option clause \u2190 opts.simpl_rules.mfoldl (\u03bb cls sr,\n  match (cls : option clause) with\n  | some cls := sr cls\n  | none := pure none\n  end) (some given.cls),\npure $ cls.map $ \u03bb cls, { cls := cls, ..given }\n\nmeta def do_preprocessing (opts : options) : list clause \u2192 prover (list clause) | newly_derived := do\nnewly_derived \u2190 opts.preproc_rules.mfoldl (\u03bb cls pr, pr cls) newly_derived,\nif \u00ac newly_derived.existsb (\u03bb c : clause, c.ty.literals = []) then\n  pure newly_derived\nelse do\n  newly_derived \u2190 preprocessing.empty_clause newly_derived,\n  if \u00ac newly_derived.existsb (\u03bb c : clause, c.ty.literals = []) then\n    do_preprocessing newly_derived\n  else\n    pure newly_derived\n\ndeclare_trace super\n\nmeta def main_loop (opts : options) : list clause \u2192 \u2115 \u2192 prover (option expr) | newly_derived n := do\nnewly_derived \u2190 do_preprocessing opts newly_derived,\nlet derived_empty_clauses := newly_derived.filter (\u03bb c, c.ty.literals = []),\nmatch derived_empty_clauses with\n| (c::_) := do\n  c \u2190 c.instantiate_mvars,\n  c.check,\n  prf \u2190 unfold_defs c.prf,\n  type_check prf,\n  state_t.lift $ infer_type prf >>= is_def_eq `(false),\n  pure prf\n| _ := do\nnewly_derived.mmap' (add_passive opts.literal_selection),\npassive_size \u2190 rb_map.size <$> get_passive,\nif passive_size = 0 then\n  do act \u2190 get_active, tactic.trace act.values,\n  pure none -- saturation\nelse do\n  given_id \u2190 opts.clause_selection n,\n  given \u2190 consume_passive given_id,\n  given \u2190 do_simplification opts given,\n  match given with\n  | none := main_loop [] (n+1)\n  | some given := do\n    if given.cls.literals = [] then main_loop [given.cls] (n+1) else do\n    when (is_trace_enabled_for `super)\n      (do act \u2190 get_active,\n          given \u2190 pp given,\n          trace $ \"[a=\" ++ to_string act.size ++\n                  \",p=\" ++ to_string passive_size ++\n                  \"] \" ++ to_string given),\n    given.cls.check,\n    given \u2190 intern_derived given,\n    add_active given,\n    given' \u2190 given.clone,\n    newly_derived \u2190 list.join <$> opts.inf_rules.mmap (\u03bb ir, ir given'),\n    main_loop newly_derived (n+1)\n  end\nend\n\nmeta def main (opts : options) (initial : list clause) : tactic (option expr) := do\ninitial \u2190 initial.mmap clause.clone, -- work around local context restriction\nprod.fst <$> state_t.run (main_loop opts initial 0) prover_state.initial\n\nmeta def with_ground_mvars {\u03b1} (tac : tactic \u03b1) : tactic \u03b1 := do\nreverted_goal \u2190 tactic.retrieve (unfreeze_local_instances >> revert_all >> target),\nreverted_goal \u2190 instantiate_mvars reverted_goal,\nmvars \u2190 reverted_goal.sorted_mvars,\nlcs \u2190 mk_locals_core mvars,\nlet univ_mvars := (reverted_goal.mk_app lcs).univ_meta_vars.to_list,\nups \u2190 univ_mvars.mmap (\u03bb _, mk_fresh_name),\n(goal::goals) \u2190 get_goals,\n(res, proof) \u2190 tactic.retrieve (do\n  (mvars.zip lcs).mmap' (\u03bb \u27e8m, lc\u27e9, unify m lc),\n  (univ_mvars.zip ups).mmap (\u03bb \u27e8m, up\u27e9, unify_level (level.mvar m) (level.param up)),\n  set_goals [goal],\n  instantiate_mvars_in_target,\n  res \u2190 tac,\n  done,\n  proof \u2190 instantiate_mvars goal,\n  pure (res, proof)),\nlet proof := (proof.abstract_locals (lcs.map expr.local_uniq_name)).instantiate_vars mvars,\nlet proof := proof.instantiate_univ_params\n  ((ups.zip univ_mvars).map (\u03bb \u27e8up, m\u27e9, (up, level.mvar m))),\nexact proof,\npure res\n\nmeta def solve (opts : options) (initial : list clause) : tactic unit := do\nsome empty_clause \u2190 main opts initial | fail \"saturation\",\n(target >>= is_def_eq `(false)) <|> exfalso,\nexact empty_clause\n\nmeta def intros' : tactic (list expr) :=\n(do x \u2190 intro_core `_, xs \u2190 intros', pure (x::xs)) <|> pure []\n\nnoncomputable lemma {u} super_contradiction {\u03b1 : Sort u} (h : (\u03b1 \u2192 false) \u2192 false) : \u03b1 :=\nmatch classical.type_decidable \u03b1 with\n| psum.inl a := a\n| psum.inr nota := @false.rec _ (h nota)\nend\n\nmeta def better_contradiction : tactic expr :=\ntactic.by_contradiction `h <|>\n  (applyc ``super_contradiction >> intro1)\n\nmeta def solve_with_goal (opts : options) (initial : list clause) : tactic unit := do\nclassical,\nhs \u2190 intros',\ntgt \u2190 target,\nhs \u2190 if tgt = `(false) then pure hs else\n  (::) <$> better_contradiction <*> pure hs,\ninitial \u2190 (++ initial) <$> hs.mmap clause.of_proof,\n-- FIXME: happens e.g. with eq.mpr\ninitial \u2190 initial.mfilter (\u03bb c, do\n  is_ok \u2190 succeeds c.check,\n  if is_ok then pure tt else do\n  trace \"discarding clause, invalid type\",\n  pure ff),\nsome empty_clause \u2190 main opts initial | fail \"saturation\",\nexact empty_clause\n\nmeta def aux_lemma_clauses_of_pexpr_name (n : name) : tactic (list clause) := do\np \u2190 resolve_name n,\nlet e := p.erase_annotations.get_app_fn.erase_annotations,\nmatch e with\n| expr.const n _ := get_aux_lemma_clauses n\n| _ := pure []\nend\n\nmeta def aux_lemma_clauses_of_pexpr : pexpr \u2192 tactic (list clause)\n| (expr.const n _) := aux_lemma_clauses_of_pexpr_name n\n| (expr.local_const n _ _ _) := aux_lemma_clauses_of_pexpr_name n\n| _ := pure []\n\nmeta def clauses_of_simp_arg_type : simp_arg_type \u2192 tactic (list clause)\n| simp_arg_type.all_hyps := do lctx \u2190 local_context, lctx.mmap clause.of_proof\n| (simp_arg_type.except _) := fail \"super [-foo] not supported\"\n| (simp_arg_type.symm_expr e) := clauses_of_simp_arg_type (simp_arg_type.expr e)\n| (simp_arg_type.expr e) := do\n  eqn_lems \u2190 aux_lemma_clauses_of_pexpr e,\n  cls \u2190 tactic.retrieve (to_expr e >>= clause.of_proof >>= clause.pack) >>= packed_clause.unpack,\n  pure (cls :: eqn_lems)\n\nmeta def clauses_of_simp_arg_type_list (simp_args : list simp_arg_type) : tactic (list clause) :=\nlist.join <$> simp_args.mmap clauses_of_simp_arg_type\n\nend super\n\nnamespace tactic.interactive\nopen lean.parser\nopen interactive\nopen interactive.types\nopen tactic\n\n-- TODO: show unused arguments\nmeta def super (args : parse simp_arg_list)\n               (opts : super.options := {}) : tactic unit :=\n_root_.super.with_ground_mvars $ do\ncs \u2190 _root_.super.clauses_of_simp_arg_type_list args,\n_root_.super.solve_with_goal opts cs\n\nend tactic.interactive\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/prover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052574867685, "lm_q2_score": 0.02976009728049914, "lm_q1q2_score": 0.010270366034817935}}
{"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) : \u2115 :=\n  string.fold 1\n    (fun (h : \u2115) (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 \u2192 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 \u00d7 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 : \u2115 := 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 \u00d7 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 : \u2115) (f : \u2115 \u2192 \u2115) (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 : \u2115 \u2192 \u2115) (x : \u2115)\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 <https://leanprover-community.github.io/extras/conv.html> 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 : \u2115) (h\u2081 : b = c) (h\u2082 : a + c = a + d) : a + b = a + d :=\nby conv {\n  to_lhs,\n  conv {\n    congr, skip,\n    rw h\u2081,\n  },\n  rw h\u2082,\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 : \u2115) where proof : m < n\ninstance NatLt.one (n : \u2115) : NatLt 0 n.succ := \u27e8Nat.succ_pos _\u27e9\ninstance NatLt.trans (m n : \u2115) [h : NatLt m n] : NatLt (m+1) (n+1) :=\n\u27e8Nat.succ_lt_succ h.proof\u27e9\n\n-- example : NatLt 3 2 := inferInstance -- no\nexample : NatLt 1 3 := inferInstance\n\nuniverse u v\n\nclass Atomic (\u03b1 : Type u)\n\n@[reducible] def Ind (_ : \u2115) (\u03b9 : Type _) := \u03b9\n\nclass IndexedFunctor (f : \u2115 \u2192 Type u \u2192 Type v) : Type (max (u+1) v) where\n  imap : {i : \u2115} \u2192 {\u03b1 \u03b2 : Type u} \u2192 (\u03b1 \u2192 \u03b2) \u2192 f i \u03b1 \u2192 f i \u03b2\n  imapConst : {i : \u2115} \u2192 {\u03b1 \u03b2 : Type u} \u2192 \u03b1 \u2192 f i \u03b2 \u2192 f i \u03b1 := imap \u2218 (Function.const _)\n\ninstance [IndexedFunctor F] : Functor (F n) where\n  map := IndexedFunctor.imap\n  mapConst := IndexedFunctor.imapConst\n\ninductive StrF (\u03b9 : Type _) (n : \u2115) (\u03b1 : Type _)\n| fun (v : Ind n \u03b9 \u2192\u2090 \u03b1) : StrF \u03b9 n \u03b1\n\ninstance : IndexedFunctor (StrF \u03b9) where\n  imap | f, .fun v => .fun (f \u2218 v)\n\ninductive StrS (\u03b9 : Type _) (n : \u2115) (\u03b1 : Type _)\n| str (s : Ind n \u03b9 \u2192\u209b \u03b1) : StrS \u03b9 n \u03b1\n\ninstance : IndexedFunctor (StrS \u03b9) where\n  imap | f, .str g => .str { g with value := f \u2218 g.value }\n\nsection HMul\nvariable {\u03b9 : Type} [Tagged \u03b9] [DecidableEq \u03b9] [Max \u03b9]\nvariable [IndexedFunctor F] [IndexedFunctor F'] [Atomic \u03c1]\n\ninstance instHMul.Merge.succ_ss [HMul \u03b1 \u03b2 \u03b3] : HMul (StrS \u03b9 i \u03b1) (StrS \u03b9 i \u03b2) (StrS \u03b9 i \u03b3) :=\n\u27e8fun | .str s\u2081, .str s\u2082 => .str (s\u2081 * s\u2082)\u27e9\ninstance instHMul.Merge.succ_sf [HMul \u03b1 \u03b2 \u03b3] : HMul (StrS \u03b9 i \u03b1) (StrF \u03b9 i \u03b2) (StrS \u03b9 i \u03b3) :=\n\u27e8fun | .str s\u2081, .fun s\u2082 => .str (s\u2081 * s\u2082)\u27e9\ninstance instHMul.Merge.succ_fs [HMul \u03b1 \u03b2 \u03b3] : HMul (StrF \u03b9 i \u03b1) (StrS \u03b9 i \u03b2) (StrS \u03b9 i \u03b3) :=\n\u27e8fun | .fun s\u2081, .str s\u2082 => .str (s\u2081 * s\u2082)\u27e9\ninstance instHMul.Merge.succ_ff [HMul \u03b1 \u03b2 \u03b3] : HMul (StrF \u03b9 i \u03b1) (StrF \u03b9 i \u03b2) (StrF \u03b9 i \u03b3) :=\n\u27e8fun | .fun s\u2081, .fun s\u2082 => .fun (s\u2081 * s\u2082)\u27e9\n\ninstance instHMul.Merge.scalar_r [HMul \u03b1 \u03c1 \u03b1] : HMul (F i \u03b1) \u03c1 (F i \u03b1) :=\n\u27e8fun s\u2081 k => (\u00b7 * k) <$> s\u2081\u27e9\ninstance instHMul.Merge.lt [NatLt i j] [HMul \u03b1 (F' j \u03b2) \u03b3] : HMul (F i \u03b1) (F' j \u03b2) (F i \u03b3) :=\n\u27e8fun s\u2081 k => (\u00b7 * k) <$> s\u2081\u27e9\ninstance instHMul.Merge.scalar_l [HMul \u03c1 \u03b1 \u03b1] : HMul \u03c1 (F i \u03b1) (F i \u03b1) :=\n\u27e8fun k s\u2082 => (k * \u00b7) <$> s\u2082\u27e9\ninstance instHMul.Merge.gt [NatLt j i] [HMul (F' i \u03b1) \u03b2 \u03b3] : HMul (F' i \u03b1) (F j \u03b2) (F j \u03b3) :=\n\u27e8fun k s\u2082 => (k * \u00b7) <$> s\u2082\u27e9\n\ninstance [Mul \u03b1] : Mul (StrS \u03b9 i \u03b1) := \u27e8HMul.hMul\u27e9 \ninstance [Mul \u03b1] : Mul (StrF \u03b9 i \u03b1) := \u27e8HMul.hMul\u27e9 \n\n-- Special: bool * S\ninstance instHMul.Merge.scalar_r_bool : HMul (StrS \u03b9 i \u03b1) (E Bool) (StrS \u03b9 i \u03b1) :=\n\u27e8fun | .str s\u2081, k => .str (Guard.guard k s\u2081)\u27e9\ninstance instHMul.Merge.scalar_l_bool : HMul (E Bool) (StrS \u03b9 i \u03b1) (StrS \u03b9 i \u03b1) :=\n\u27e8fun | k, .str s\u2082 => .str (Guard.guard k s\u2082)\u27e9\ninstance instHMul.Merge.succ_sf_bool : HMul (StrS \u03b9 i \u03b1) (StrF \u03b9 i (E Bool)) (StrS \u03b9 i \u03b1) :=\n\u27e8fun | .str s\u2081, .fun s\u2082 => .str (s\u2081 * s\u2082)\u27e9\ninstance instHMul.Merge.succ_fs_bool : HMul (StrF \u03b9 i (E Bool)) (StrS \u03b9 i \u03b2) (StrS \u03b9 i \u03b2) :=\n\u27e8fun | .fun s\u2081, .str s\u2082 => .str (s\u2081 * s\u2082)\u27e9\nend HMul\n\nsection HAdd\nvariable {\u03b1 \u03b2 \u03b3 \u03b9 : Type}\n  [Tagged \u03b9] [TaggedC \u03b9] [DecidableEq \u03b9]\n  [LT \u03b9] [LE \u03b9] [DecidableRel (LT.lt : \u03b9 \u2192 \u03b9 \u2192 Prop)]\n  [DecidableRel (LE.le : \u03b9 \u2192 \u03b9 \u2192 _)]\n  {i : \u2115}\n  [Guard \u03b1] [Guard \u03b2]\nvariable [IndexedFunctor F] [IndexedFunctor F'] [Atomic \u03c1]\n\ninstance instHAdd.Merge.succ_ss [HAdd \u03b1 \u03b2 \u03b3] : HAdd (StrS \u03b9 i \u03b1) (StrS \u03b9 i \u03b2) (StrS \u03b9 i \u03b3) :=\n\u27e8fun | .str s\u2081, .str s\u2082 => .str (s\u2081 + s\u2082)\u27e9\ninstance instHAdd.Merge.succ_sf [HAdd \u03b1 \u03b2 \u03b3] : HAdd (StrS \u03b9 i \u03b1) (StrF \u03b9 i \u03b2) (StrS \u03b9 i \u03b3) :=\n\u27e8fun | .str s\u2081, .fun s\u2082 => .str (s\u2081 + s\u2082)\u27e9\ninstance instHAdd.Merge.succ_fs [HAdd \u03b1 \u03b2 \u03b3] : HAdd (StrF \u03b9 i \u03b1) (StrS \u03b9 i \u03b2) (StrS \u03b9 i \u03b3) :=\n\u27e8fun | .fun s\u2081, .str s\u2082 => .str (s\u2081 + s\u2082)\u27e9\ninstance instHAdd.Merge.succ_ff [HAdd \u03b1 \u03b2 \u03b3] : HAdd (StrF \u03b9 i \u03b1) (StrF \u03b9 i \u03b2) (StrF \u03b9 i \u03b3) :=\n\u27e8fun | .fun s\u2081, .fun s\u2082 => .fun (s\u2081 + s\u2082)\u27e9\n\ninstance instHAdd.Merge.scalar_r [HAdd \u03b1 \u03c1 \u03b1] : HAdd (F i \u03b1) \u03c1 (F i \u03b1) :=\n\u27e8fun s\u2081 k => (\u00b7 + k) <$> s\u2081\u27e9\ninstance instHAdd.Merge.lt [NatLt i j] [HAdd \u03b1 (F' j \u03b2) \u03b3] : HAdd (F i \u03b1) (F' j \u03b2) (F i \u03b3) :=\n\u27e8fun s\u2081 k => (\u00b7 + k) <$> s\u2081\u27e9\ninstance instHAdd.Merge.scalar_l [HAdd \u03c1 \u03b1 \u03b1] : HAdd \u03c1 (F i \u03b1) (F i \u03b1) :=\n\u27e8fun k s\u2082 => (k + \u00b7) <$> s\u2082\u27e9\ninstance instHAdd.Merge.gt [NatLt j i] [HAdd (F i \u03b1) \u03b2 \u03b3] : HAdd (F i \u03b1) (F' j \u03b2) (F' j \u03b3) :=\n\u27e8fun k s\u2082 => (k + \u00b7) <$> s\u2082\u27e9\n\ninstance [Add \u03b1] : Add (StrS \u03b9 i \u03b1) := \u27e8HAdd.hAdd\u27e9 \ninstance [Add \u03b1] : Add (StrF \u03b9 i \u03b1) := \u27e8HAdd.hAdd\u27e9 \nend HAdd\n\ninstance : Atomic (E \u03b1) := \u27e8\u27e9\n\nnotation:37 a:36 \" \u00d7 \" b:36 \" \u27f6\u2090 \" c:36  => StrF b a c\ninfixr:25 \" \u21a0\u2090 \" => \u03bb (p : \u2115\u00d7Type) c => StrF (Prod.snd p) (Prod.fst p) c\nnotation:37 a:36 \" \u00d7 \" b:36 \" \u27f6\u209b \" c:36  => StrS b a c\ninfixr:25 \" \u21a0\u209b \" => \u03bb (p : \u2115\u00d7Type) c => StrS (Prod.snd p) (Prod.fst p) c\n\ninstance [Guard \u03b1] : Guard (n \u00d7 \u03b9 \u27f6\u209b \u03b1) where\n  guard b := fun | .str f => .str (Guard.guard b f)\n\ninstance [Tagged \u03b1] [Zero \u03b1] : Guard (n \u00d7 \u03b9 \u27f6\u2090 E \u03b1) where\n  guard b := fun | .fun f => .fun (Guard.guard b f)\n\nvariable\n{\u03b1 \u03b2 \u03b3 : Type _}\n(n : \u2115)\n{\u03b9 : Type _} [Tagged \u03b9] [TaggedC \u03b9] [DecidableEq \u03b9]\n[LT \u03b9] [DecidableRel (LT.lt : \u03b9 \u2192 \u03b9 \u2192 _)] [Zero \u03b9]\n[LE \u03b9] [DecidableRel (LE.le : \u03b9 \u2192 \u03b9 \u2192 _)]\n[Max \u03b9]\n\ninstance StrS.Mul [Mul \u03b3] : Mul (i \u00d7 \u03b9 \u27f6\u209b \u03b3) := \u27e8HMul.hMul\u27e9\ninstance StrF.Mul [Mul \u03b3] : Mul (i \u00d7 \u03b9 \u27f6\u2090 \u03b3) := \u27e8HMul.hMul\u27e9\n\ninstance : Coe (\u03b9 \u2192\u209b \u03b1) (n \u00d7 \u03b9 \u27f6\u209b \u03b1) := \u27e8.str\u27e9\ninstance : Coe (\u03b9 \u2192\u2090 \u03b1) (n \u00d7 \u03b9 \u27f6\u2090 \u03b1) := \u27e8.fun\u27e9\ninstance [Coe \u03b1 \u03b2] : Coe (\u03b9 \u2192\u209b \u03b1) (n \u00d7 \u03b9 \u27f6\u209b \u03b2) := \u27e8.str \u2218 Functor.map Coe.coe\u27e9\ninstance [Coe \u03b1 \u03b2] : Coe (\u03b9 \u2192\u2090 \u03b1) (n \u00d7 \u03b9 \u27f6\u2090 \u03b2) := \u27e8.fun \u2218 Functor.map Coe.coe\u27e9\n\nclass of_stream (\u03b1 \u03b2 : Type _) := (coe : \u03b1 \u2192 \u03b2)\ninstance base.of_stream : of_stream \u03b1 \u03b1 := \u27e8id\u27e9\n\ndef Stream.of [of_stream \u03b1 \u03b2] : \u03b1 \u2192 \u03b2 := of_stream.coe\n\nclass SumIndex (n : \u2115) (\u03b1 : Type _) (\u03b2 : outParam $ Type _) := (sum : \u03b1 \u2192 \u03b2)\ninstance sum_eq (n : \u2115) : SumIndex n (n \u00d7 \u03b9 \u27f6\u209b \u03b1) (Contraction \u03b1) := \u27e8fun | .str s => S.contract s\u27e9\ninstance sum_lt_f [IndexedFunctor F] (m n : \u2115) [NatLt n m] [SumIndex m \u03b1 \u03b2] : SumIndex m (F n \u03b1) (F n \u03b2) := \u27e8IndexedFunctor.imap $ SumIndex.sum m\u27e9\ninstance sum_lt_s [IndexedFunctor F] (m n : \u2115) [NatLt n m] [SumIndex m \u03b1 \u03b2] : SumIndex m (F n \u03b1) (F n \u03b2) := \u27e8IndexedFunctor.imap $ SumIndex.sum m\u27e9\n\nnotation:35 \"\u2211\" i:34 \":\" v:34 => SumIndex.sum i.1 v\nnotation:35 \"\u2211\" i:34 \",\" j:34 \":\" v:34 => SumIndex.sum i.1 (SumIndex.sum j.1 v)\nnotation:35 \"\u2211\" i:34 \",\" j:34 \",\" k:34 \":\" v:34 => SumIndex.sum i.1 (SumIndex.sum j.1 (SumIndex.sum k.1 v))\nnotation:35 \"\u2211\" 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 \"\u2211\" i:term ws j:term \",\" v:term : term => `(SumIndex.sum $i.1 (SumIndex.sum $j.1 $v))\n--macro \"\u2211\" i:term \",\" v:term : term => `(SumIndex.sum $i.1 $v)\n--macro \"\u2211\" i:term+ \",\" v:term : term => `(SumIndex.sum $(i[0]!).1 $v)\n\nclass ApplyScalarFn (\u03b1 \u03b2 \u03b3 : Type _) (\u03b4 : outParam $ Type _) := (map : (E \u03b1 \u2192 E \u03b2) \u2192 \u03b3 \u2192 \u03b4)\ninstance : ApplyScalarFn \u03b1 \u03b2 (E \u03b1) (E \u03b2) := \u27e8 (. $ .) \u27e9\ninstance [IndexedFunctor F] [ApplyScalarFn \u03b1 \u03b2 \u03b1' \u03b2'] : ApplyScalarFn \u03b1 \u03b2 (F n \u03b1') (F n \u03b2') := \u27e8 \u03bb f x => ApplyScalarFn.map f <$> x \u27e9\ninfixr:10 \" <$$> \"  => ApplyScalarFn.map\n\nsection tests\n\nvariable (a : 0 \u00d7 \u2115 \u27f6\u209b E R)\nvariable (A : \u2115 \u2192\u209b \u2115 \u2192\u209b E R)\nvariable (B : \u2115 \u2192\u2090 \u2115 \u2192\u209b E R)\nprivate abbrev i := (0, \u2115)\nprivate abbrev j := (1, \u2115)\nprivate abbrev k := (2, \u2115)\n#check SumIndex.sum 0 a\n#check \u2211 i: (A : i \u21a0\u209b j \u21a0\u209b E R)\n#check \u2211 i, j: (A : i \u21a0\u209b j \u21a0\u209b E R)\n#check (A : i \u21a0\u209b j \u21a0\u209b E R) * (B : j \u21a0\u2090 k \u21a0\u209b E R)\n--#check \u2211 i, j: (A : i \u21a0 j \u21a0 E R)\n--#check \u2211 j, k: (A : i \u21a0 j \u21a0 E R) * (B : j \u21a0 k \u21a0 E R)\n\nend tests\n\n/-\n#check Nat.add\ninductive St (\u03b1 : Type) : \u2115 \u2192 Type\n| base : St \u03b1 0\n| vec (\u03b4) {n} (of : St \u03b1 n) : St \u03b1 (n+\u03b4)\n\n-- no\ndef St.eval {n \u03b1} (ctxt : Fin n \u2192 Type) : St \u03b1 n \u2192 List Type\n| base => []\n| vec d x => ctxt \u27e8d, Nat.add\u27e9 :: x.eval _\n\nclass Broadcast (\u03b1 \u03b2 : Type _) (\u03b3 : outParam $ Type _) :=\n  broadcast : List \u2115 \u2192 \u03b1 \u2192 \u03b2 \u2192 \u03b3 \u00d7 \u03b3\n\ninstance [Rectangle f] [Broadcast \u03b1 \u03b2 \u03b3] : Broadcast (f i \u03b1) (f j \u03b2) (f\n\ndef broadcast (ordering : List \u2115) (a : f i \u03b1) (b : g i \u03b2)\n/- todo\n  fix \u2211 notation (use \u2203 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": "/-\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.CollectFVars\nimport Lean.Meta.Match.MatchPatternAttr\nimport Lean.Meta.Match.Match\nimport Lean.Meta.SortLocalDecls\nimport Lean.Meta.GeneralizeVars\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.Arg\nimport Lean.Parser.Term\nimport Lean.Elab.PatternVar\n\nnamespace Lean.Elab.Term\nopen Meta\nopen Lean.Parser.Term\n\nprivate def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let newStx \u2190 `(let $lhsVar := $discr; $rhs)\n  withMacroExpansion stx newStx <| elabTerm newStx expectedType?\n\nprivate def mkUserNameFor (e : Expr) : TermElabM Name := do\n  match e with\n  /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/\n  | Expr.fvar fvarId _ => mkFreshUserName ((\u2190 getLocalDecl fvarId).userName)\n  | _                  => mkFreshBinderName\n\n/-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/\ndef isAuxDiscrName (n : Name) : Bool :=\n  n.hasMacroScopes && n.eraseMacroScopes == `_discr\n\n/--\n   We treat `@x` as atomic to avoid unnecessary extra local declarations from being\n   inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier.\n   Thus this is kind of discriminant is quite common.\n\n   Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression.\n   This can happen due to error recovery. Example\n   ```\n   example : (p \u2228 p) \u2192 p := fun h => match\n   ```\n   If we don't abort, the elaborator loops because we will keep trying to expand\n   ```\n   match\n   ```\n   into\n   ```\n   let d := <Syntax.missing>; match\n   ```\n   Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/\ndef isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do\n  match discr with\n  | `($x:ident)  => isLocalIdent? x\n  | `(@$x:ident) => isLocalIdent? x\n  | _ => if discr.isMissing then throwAbortTerm else return none\n\n-- See expandNonAtomicDiscrs?\nprivate def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do\n  let term := discr[1]\n  match (\u2190 isAtomicDiscr? term) with\n  | some e@(Expr.fvar fvarId _) =>\n    let localDecl \u2190 getLocalDecl fvarId\n    if !isAuxDiscrName localDecl.userName then\n      addTermInfo discr e\n      return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`\n    else\n      instantiateMVars localDecl.value\n  | _ => throwErrorAt discr \"unexpected discriminant\"\n\nstructure ElabMatchTypeAndDiscrsResult where\n  discrs    : Array Expr\n  matchType : Expr\n  /- `true` when performing dependent elimination. We use this to decide whether we optimize the \"match unit\" case.\n     See `isMatchUnit?`. -/\n  isDep     : Bool\n  alts      : Array MatchAltView\n\nprivate partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)\n      : TermElabM ElabMatchTypeAndDiscrsResult := do\n    let numDiscrs := discrStxs.size\n    if matchOptType.isNone then\n      elabDiscrs 0 #[]\n    else\n      let matchTypeStx := matchOptType[0][1]\n      let matchType \u2190 elabType matchTypeStx\n      let (discrs, isDep) \u2190 elabDiscrsWitMatchType matchType expectedType\n      return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }\n  where\n    /- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user.  -/\n    elabDiscrsWitMatchType (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr \u00d7 Bool) := do\n      let mut discrs := #[]\n      let mut i := 0\n      let mut matchType := matchType\n      let mut isDep := false\n      for discrStx in discrStxs do\n        i := i + 1\n        matchType \u2190 whnf matchType\n        match matchType with\n        | Expr.forallE _ d b _ =>\n          let discr \u2190 fullApproxDefEq <| elabTermEnsuringType discrStx[1] d\n          trace[Elab.match] \"discr #{i} {discr} : {d}\"\n          if b.hasLooseBVars then\n            isDep := true\n          matchType := b.instantiate1 discr\n          discrs := discrs.push discr\n        | _ =>\n          throwError \"invalid type provided to match-expression, function type with arity #{discrStxs.size} expected\"\n      return (discrs, isDep)\n\n    markIsDep (r : ElabMatchTypeAndDiscrsResult) :=\n      { r with isDep := true }\n\n    /- Elaborate discriminants inferring the match-type -/\n    elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do\n      if h : i < discrStxs.size then\n        let discrStx := discrStxs.get \u27e8i, h\u27e9\n        let discr     \u2190 elabAtomicDiscr discrStx\n        let discr     \u2190 instantiateMVars discr\n        let discrType \u2190 inferType discr\n        let discrType \u2190 instantiateMVars discrType\n        let discrs    := discrs.push discr\n        let userName \u2190 mkUserNameFor discr\n        if discrStx[0].isNone then\n          let mut result \u2190 elabDiscrs (i + 1) discrs\n          let matchTypeBody \u2190 kabstract result.matchType discr\n          if matchTypeBody.hasLooseBVars then\n            result := markIsDep result\n          return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody }\n        else\n          let discrs := discrs.push (\u2190 mkEqRefl discr)\n          let result \u2190 elabDiscrs (i + 1) discrs\n          let result := markIsDep result\n          let identStx := discrStx[0][0]\n          withLocalDeclD userName discrType fun x => do\n            let eqType \u2190 mkEq discr x\n            withLocalDeclD identStx.getId eqType fun h => do\n              let matchTypeBody \u2190 kabstract result.matchType discr\n              let matchTypeBody := matchTypeBody.instantiate1 x\n              let matchType \u2190 mkForallFVars #[x, h] matchTypeBody\n              return { result with\n                matchType := matchType\n                alts      := result.alts.map fun altView =>\n                  if i+1 > altView.patterns.size then\n                    -- Unexpected number of patterns. The input is invalid, but we want to process whatever to provide info to users.\n                    altView\n                  else\n                    { altView with patterns := altView.patterns.insertAt (i+1) identStx }\n              }\n      else\n        return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType }\n\ndef expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do\n  matchAlts.mapM fun matchAlt => do\n    let patterns \u2190 matchAlt.patterns.mapM expandMacros\n    pure { matchAlt with patterns := patterns }\n\nprivate def getMatchGeneralizing? : Syntax \u2192 Option Bool\n  | `(match (generalizing := true)  $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true\n  | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false\n  | _ => none\n\n/- Given `stx` a match-expression, return its alternatives. -/\nprivate def getMatchAlts : Syntax \u2192 Array MatchAltView\n  | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) =>\n    alts.filterMap fun alt => match alt with\n      | `(matchAltExpr| | $patterns,* => $rhs) => some {\n          ref      := alt,\n          patterns := patterns,\n          rhs      := rhs\n        }\n      | _ => none\n  | _ => #[]\n\nbuiltin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind\n\n/--\n  The elaboration function for `Syntax` created using `mkMVarSyntax`.\n  It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/\n@[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? =>\n  return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx)\n\n@[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do\n  let e \u2190 elabTerm stx[1] expectedType?\n  return mkInaccessible e\n\nopen Lean.Elab.Term.Quotation in\n@[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck\n  | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do\n    discrs.forM precheck\n    for (pats, rhs) in patss.zip rhss do\n      let vars \u2190\n        try\n          getPatternsVars pats\n        catch\n          | _ => return  -- can happen in case of pattern antiquotations\n      Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs\n  | _ => throwUnsupportedSyntax\n\n/- We convert the collected `PatternVar`s intro `PatternVarDecl` -/\ninductive PatternVarDecl where\n  /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable\n     when it is not assigned during pattern elaboration. -/\n  | anonymousVar (mvarId : MVarId) (fvarId : FVarId)\n  | localVar     (fvarId : FVarId)\n\nprivate partial def withPatternVars {\u03b1} (pVars : Array PatternVar) (k : Array PatternVarDecl \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (decls : Array PatternVarDecl) := do\n    if h : i < pVars.size then\n      match pVars.get \u27e8i, h\u27e9 with\n      | PatternVar.anonymousVar mvarId =>\n        let type \u2190 mkFreshTypeMVar\n        let userName \u2190 mkFreshBinderName\n        withLocalDecl userName BinderInfo.default type fun x =>\n          loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!))\n      | PatternVar.localVar userName   =>\n        let type \u2190 mkFreshTypeMVar\n        withLocalDecl userName BinderInfo.default type fun x =>\n          loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!))\n    else\n      /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`.\n         Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/\n      decls.forM fun decl => match decl with\n        | PatternVarDecl.anonymousVar mvarId fvarId => do\n          let type \u2190 inferType (mkFVar fvarId)\n          discard <| mkFreshExprMVarWithId mvarId type\n        | _ => pure ()\n      k decls\n  loop 0 #[]\n\n/-\nRemark: when performing dependent pattern matching, we often had to write code such as\n\n```lean\ndef Vec.map' (f : \u03b1 \u2192 \u03b2) (xs : Vec \u03b1 n) : Vec \u03b2 n :=\n  match n, xs with\n  | _, nil       => nil\n  | _, cons a as => cons (f a) (map' f as)\n```\nWe had to include `n` and the `_`s because the type of `xs` depends on `n`.\nMoreover, `nil` and `cons a as` have different types.\nThis was quite tedious. So, we have implemented an automatic \"discriminant refinement procedure\".\nThe procedure is based on the observation that we get a type error whenenver we forget to include `_`s\nand the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant\nis an indexed family, and add their indices as new discriminants.\n\nThe current implementation, adds indices as they are found, and does not\ntry to \"sort\" the new discriminants.\n\nIf the refinement process fails, we report the original error message.\n-/\n\n/- Auxiliary structure for storing an type mismatch exception when processing the\n   pattern #`idx` of some alternative. -/\nstructure PatternElabException where\n  ex          : Exception\n  patternIdx  : Nat -- Discriminant that sh\n  pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch\n\n/--\n  This method is part of the \"discriminant refinement\" procedure. It in invoked when the\n  type of the `pattern` does not match the expected type. The expected type is based on the\n  motive computed using the `match` discriminants.\n  It tries to compute a path to an index of the discriminant type.\n  For example, suppose the user has written\n  ```\n  inductive Mem (a : \u03b1) : List \u03b1 \u2192 Prop where\n    | head {as} : Mem a (a::as)\n    | tail {as} : Mem a as \u2192 Mem a (a'::as)\n\n  infix:50 \" \u2208 \" => Mem\n\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match h with\n  | Mem.head => rfl\n  ```\n  The motive for the match is `a \u2208 [b] \u2192 b = a`, and get a type mismatch between the type\n  of `Mem.head` and `a \u2208 [b]`. This procedure return the path `[2, 1]` to the index `b`.\n  We use it to produce the following refinement\n  ```\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match b, h with\n  | _, Mem.head => rfl\n  ```\n  which produces the new motive `(x : Nat) \u2192  a \u2208 [x] \u2192 x = a`\n  After this refinement step, the `match` is elaborated successfully.\n\n  This method relies on the fact that the dependent pattern matcher compiler solves equations\n  between indices of indexed inductive families.\n  The following kinds of equations are supported by this compiler:\n  - `x = t`\n  - `t = x`\n  - `ctor ... = ctor ...`\n\n  where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor.\n  Our procedure ensures that \"information\" is not lost, and will *not* succeed in an\n  example such as\n  ```\n  example (a b : Nat) (f : Nat \u2192 Nat) (h : f a \u2208 [f b]) : f b = f a :=\n    match h with\n    | Mem.head => rfl\n  ```\n  and will not add `f b` as a new discriminant. We may add an option in the future to\n  enable this more liberal form of refinement.\n-/\nprivate partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do\n  goType (\u2190 instantiateMVars (\u2190 inferType pattern)) expected\nwhere\n  checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do\n    guard d.isApp\n    guard <| t.getAppNumArgs == d.getAppNumArgs\n    let tFn := t.getAppFn\n    let dFn := d.getAppFn\n    guard <| tFn.isConst && dFn.isConst\n    guard (\u2190 isDefEq tFn dFn)\n\n  -- Visitor for inductive types\n  goType (t d : Expr) : OptionT MetaM (List Nat) := do\n    trace[Meta.debug] \"type {t} =?= {d}\"\n    let t \u2190 whnf t\n    let d \u2190 whnf d\n    checkCompatibleApps t d\n    matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do\n      let tArgs := t.getAppArgs\n      let dArgs := d.getAppArgs\n      for i in [:info.numParams] do\n        let tArg := tArgs[i]\n        let dArg := dArgs[i]\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goType tArg dArg)\n      for i in [info.numParams : tArgs.size] do\n        let tArg := tArgs[i]\n        let dArg := dArgs[i]\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goIndex tArg dArg)\n      failure\n\n  -- Visitor for indexed families\n  goIndex (t d : Expr) : OptionT MetaM (List Nat) := do\n    let t \u2190 whnfD t\n    let d \u2190 whnfD d\n    if t.isFVar || d.isFVar then\n      return [] -- Found refinement path\n    else\n      trace[Meta.debug] \"index {t} =?= {d}\"\n      checkCompatibleApps t d\n      matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do\n        let tArgs := t.getAppArgs\n        let dArgs := d.getAppArgs\n        for i in [:info.numParams] do\n          let tArg := tArgs[i]\n          let dArg := dArgs[i]\n          unless (\u2190 isDefEq tArg dArg) do\n            failure\n        for i in [info.numParams : tArgs.size] do\n          let tArg := tArgs[i]\n          let dArg := dArgs[i]\n          unless (\u2190 isDefEq tArg dArg) do\n            return i :: (\u2190 goIndex tArg dArg)\n        failure\n\nprivate partial def eraseIndices (type : Expr) : MetaM Expr := do\n  let type' \u2190 whnfD type\n  matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do\n    let args := type'.getAppArgs\n    let params \u2190 args[:info.numParams].toArray.mapM eraseIndices\n    let result := mkAppN type'.getAppFn params\n    let resultType \u2190 inferType result\n    let (newIndices, _, _) \u2190  forallMetaTelescopeReducing resultType (some (args.size - info.numParams))\n    return mkAppN result newIndices\n\nprivate def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr \u00d7 Expr) :=\n  withReader (fun ctx => { ctx with implicitLambda := false }) do\n    let mut patterns  := #[]\n    let mut matchType := matchType\n    for idx in [:patternStxs.size] do\n      let patternStx := patternStxs[idx]\n      matchType \u2190 whnf matchType\n      match matchType with\n      | Expr.forallE _ d b _ =>\n        let pattern \u2190 do\n          let s \u2190 saveState\n          try\n            liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d\n          catch ex : Exception =>\n            restoreState s\n            match (\u2190 liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (\u2190 eraseIndices d)) with\n            | some pattern =>\n              match (\u2190 findDiscrRefinementPath pattern d |>.run) with\n              | some path =>\n                trace[Meta.debug] \"refinement path: {path}\"\n                restoreState s\n                -- Wrap the type mismatch exception for the \"discriminant refinement\" feature.\n                throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path }\n              | none => restoreState s; throw ex\n            | none => throw ex\n        matchType := b.instantiate1 pattern\n        patterns  := patterns.push pattern\n      | _ => throwError \"unexpected match type\"\n    return (patterns, matchType)\n\ndef finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do\n  let mut decls := #[]\n  for pdecl in patternVarDecls do\n    match pdecl with\n    | PatternVarDecl.localVar fvarId =>\n      let decl \u2190 getLocalDecl fvarId\n      let decl \u2190 instantiateLocalDeclMVars decl\n      decls := decls.push decl\n    | PatternVarDecl.anonymousVar mvarId fvarId =>\n       let e \u2190 instantiateMVars (mkMVar mvarId);\n       trace[Elab.match] \"finalizePatternDecls: mvarId: {mvarId.name} := {e}, fvar: {mkFVar fvarId}\"\n       match e with\n       | Expr.mvar newMVarId _ =>\n         /- Metavariable was not assigned, or assigned to another metavariable. So,\n            we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/\n         assignExprMVar newMVarId (mkFVar fvarId)\n         trace[Elab.match] \"finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}\"\n         let decl \u2190 getLocalDecl fvarId\n         let decl \u2190 instantiateLocalDeclMVars decl\n         decls := decls.push decl\n       | _ => pure ()\n  /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d\u2081 may occur after d\u2082 when d\u2082 depends on d\u2081. -/\n  sortLocalDecls decls\n\nopen Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)\n\nnamespace ToDepElimPattern\n\nstructure State where\n  found      : FVarIdSet := {}\n  localDecls : Array LocalDecl\n  newLocals  : FVarIdSet := {}\n\nabbrev M := StateRefT State TermElabM\n\nprivate def alreadyVisited (fvarId : FVarId) : M Bool := do\n  let s \u2190 get\n  return s.found.contains fvarId\n\nprivate def markAsVisited (fvarId : FVarId) : M Unit :=\n  modify fun s => { s with found := s.found.insert fvarId }\n\nprivate def throwInvalidPattern {\u03b1} (e : Expr) : M \u03b1 :=\n  throwError \"invalid pattern {indentExpr e}\"\n\n/- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/\nprivate def mkLocalDeclFor (mvar : Expr) : M Pattern := do\n  let mvarId := mvar.mvarId!\n  let s \u2190 get\n  match (\u2190 getExprMVarAssignment? mvarId) with\n  | some val => return Pattern.inaccessible val\n  | none =>\n    let fvarId \u2190 mkFreshFVarId\n    let type   \u2190 inferType mvar\n    /- HACK: `fvarId` is not in the scope of `mvarId`\n       If this generates problems in the future, we should update the metavariable declarations. -/\n    assignExprMVar mvarId (mkFVar fvarId)\n    let userName \u2190 mkFreshBinderName\n    let newDecl := LocalDecl.cdecl default fvarId userName type BinderInfo.default;\n    modify fun s =>\n      { s with\n        newLocals  := s.newLocals.insert fvarId,\n        localDecls :=\n        match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with\n        | none   => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar`\n        | some i => s.localDecls.insertAt i newDecl }\n    return Pattern.var fvarId\n\npartial def main (e : Expr) : M Pattern := do\n  let isLocalDecl (fvarId : FVarId) : M Bool := do\n    return (\u2190 get).localDecls.any fun d => d.fvarId == fvarId\n  let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do\n    if (\u2190 alreadyVisited fvarId) then\n      return Pattern.inaccessible e\n    else\n      markAsVisited fvarId\n      return Pattern.var e.fvarId!\n  let mkInaccessible (e : Expr) : M Pattern := do\n    match e with\n    | Expr.fvar fvarId _ =>\n      if (\u2190 isLocalDecl fvarId) then\n        mkPatternVar fvarId e\n      else\n        return Pattern.inaccessible e\n    | _ =>\n      return Pattern.inaccessible e\n  match inaccessible? e with\n  | some t => mkInaccessible t\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) =>\n      return Pattern.arrayLit \u03b1 (\u2190 lits.mapM main)\n    | none =>\n      -- TODO: namedPattern will have 4 arguments\n      if e.isAppOfArity ``_root_.namedPattern 4 then\n        let p \u2190 main <| e.getArg! 2\n        match e.getArg! 1, e.getArg! 3 with\n        | Expr.fvar x _, Expr.fvar h _ => return Pattern.as x p h\n        | _,             _             => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if isMatchValue e then\n        return Pattern.val e\n      else if e.isFVar then\n        let fvarId := e.fvarId!\n        unless (\u2190 isLocalDecl fvarId) do\n          throwInvalidPattern e\n        mkPatternVar fvarId e\n      else if e.isMVar then\n        mkLocalDeclFor e\n      else\n        let newE \u2190 whnf e\n        if newE != e then\n          main newE\n        else\n         matchConstCtor e.getAppFn\n           (fun _ => do\n              if (\u2190 isProof e) then\n                /- We mark nested proofs as inaccessible. This is fine due to proof irrelevance.\n                   We need this feature to be able to elaborate definitions such as:\n                   ```\n                    def f : Fin 2 \u2192 Nat\n                      | 0 => 5\n                      | 1 => 45\n                   ```\n                -/\n                return Pattern.inaccessible e\n              else\n                throwInvalidPattern e)\n           (fun v us => do\n              let args := e.getAppArgs\n              unless args.size == v.numParams + v.numFields do\n                throwInvalidPattern e\n              let params := args.extract 0 v.numParams\n              let fields := args.extract v.numParams args.size\n              let fields \u2190 fields.mapM main\n              return Pattern.ctor v.name us params.toList fields.toList)\n\nend ToDepElimPattern\n\ndef withDepElimPatterns {\u03b1} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl \u2192 Array Pattern \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (patterns, s) \u2190 (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls }\n  let localDecls \u2190 s.localDecls.mapM fun d => instantiateLocalDeclMVars d\n  /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/\n  let lctx \u2190 getLCtx\n  let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx\n  let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx\n  withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do\n    k localDecls patterns\n\nprivate def withElaboratedLHS {\u03b1} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)\n    (k : AltLHS \u2192 Expr \u2192 TermElabM \u03b1) : ExceptT PatternElabException TermElabM \u03b1 := do\n  let (patterns, matchType) \u2190 withSynthesize <| elabPatterns patternStxs matchType\n  id (\u03b1 := TermElabM \u03b1) do\n    let localDecls \u2190 finalizePatternDecls patternVarDecls\n    let patterns \u2190 patterns.mapM (instantiateMVars \u00b7)\n    withDepElimPatterns localDecls patterns fun localDecls patterns =>\n      k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType\n\nprivate def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS \u00d7 Expr) := withRef alt.ref do\n  let (patternVars, alt) \u2190 collectPatternVars alt\n  trace[Elab.match] \"patternVars: {patternVars}\"\n  withPatternVars patternVars fun patternVarDecls => do\n    withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do\n      let rhs \u2190 elabTermEnsuringType alt.rhs matchType\n      let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr\n      let rhs \u2190 if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs\n      trace[Elab.match] \"rhs: {rhs}\"\n      return (altLHS, rhs)\n\n/--\n  Collect problematic index for the \"discriminant refinement feature\". This method is invoked\n  when we detect a type mismatch at a pattern #`idx` of some alternative. -/\nprivate partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do\n  go (\u2190 inferType discr) pathToIndex |>.run\nwhere\n  go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do\n    match path with\n    | [] => return e\n    | i::path =>\n      let e \u2190 whnfD e\n      guard <| e.isApp && i < e.getAppNumArgs\n      go (e.getArg! i) path\n\n/--\n  \"Generalize\" variables that depend on the discriminants.\n\n  Remarks and limitations:\n  - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`.\n    Motivation: users should have control about the actual `match`-expressions in their programs.\n  - We currently do not generalize let-decls.\n  - We abort generalization if the new `matchType` is type incorrect.\n  - Only discriminants that are free variables are considered during specialization.\n  - We \"generalize\" by adding new discriminants and pattern variables. We do not \"clear\" the generalized variables,\n    but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since\n    this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode.\n-/\nprivate def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr \u00d7 Expr \u00d7 Array MatchAltView \u00d7 Bool) := do\n  let gen \u2190\n    match generalizing? with\n    | some g => pure g\n    | _ => isProp matchType\n  if !gen then\n    return (discrs, matchType, altViews, false)\n  else\n    let ysFVarIds \u2190 getFVarsToGeneralize discrs\n    /- let-decls are currently being ignored by the generalizer. -/\n    let ysFVarIds \u2190 ysFVarIds.filterM fun fvarId => return !(\u2190 getLocalDecl fvarId).isLet\n    if ysFVarIds.isEmpty then\n      return (discrs, matchType, altViews, false)\n    else\n      let ys := ysFVarIds.map mkFVar\n      -- trace[Meta.debug] \"ys: {ys}, discrs: {discrs}\"\n      let matchType' \u2190 forallBoundedTelescope matchType discrs.size fun ds type => do\n        let type \u2190 mkForallFVars ys type\n        let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar\n        let type := type.replaceFVars discrs' ds'\n        mkForallFVars ds type\n      -- trace[Meta.debug] \"matchType': {matchType'}\"\n      if (\u2190 isTypeCorrect matchType') then\n        let discrs := discrs ++ ys\n        let altViews \u2190 altViews.mapM fun altView => do\n          let patternVars \u2190 getPatternsVars altView.patterns\n          -- We traverse backwards because we want to keep the most recent names.\n          -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`,\n          -- since it is already shadowed by the second.\n          let ysUserNames \u2190 ys.foldrM (init := #[]) fun ys ysUserNames => do\n            let yDecl \u2190 getLocalDecl ys.fvarId!\n            let mut yUserName := yDecl.userName\n            if ysUserNames.contains yUserName then\n              yUserName \u2190 mkFreshUserName yUserName\n            -- Explicitly provided pattern variables shadow `y`\n            else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then\n              yUserName \u2190 mkFreshUserName yUserName\n            return ysUserNames.push yUserName\n          let ysIds \u2190 ysUserNames.reverse.mapM fun n => return mkIdentFrom (\u2190 getRef) n\n          return { altView with patterns := altView.patterns ++ ysIds }\n        return (discrs, matchType', altViews, true)\n      else\n        return (discrs, matchType, altViews, true)\n\nprivate partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n  loop discrs matchType altViews none\nwhere\n  /-\n    \"Discriminant refinement\" main loop.\n    `first?` contains the first error message we found before updated the `discrs`. -/\n  loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState \u00d7 Exception))\n      : TermElabM (Array Expr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n    let s \u2190 saveState\n    let (discrs', matchType', altViews', refined) \u2190 generalize discrs matchType altViews generalizing?\n    match (\u2190 altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run) with\n    | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined)\n    | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } =>\n      trace[Meta.debug] \"pathToIndex: {toString pathToIndex}\"\n      let some index \u2190 getIndexToInclude? discrs[patternIdx] pathToIndex\n        | throwEx (\u2190 updateFirst first? ex)\n      trace[Meta.debug] \"index: {index}\"\n      if (\u2190 discrs.anyM fun discr => isDefEq discr index) then\n        throwEx (\u2190 updateFirst first? ex)\n      let first \u2190 updateFirst first? ex\n      s.restore\n      let indices \u2190 collectDeps #[index] discrs\n      let matchType \u2190\n        try\n          updateMatchType indices matchType\n        catch ex =>\n          throwEx first\n      let altViews  \u2190 addWildcardPatterns indices.size altViews\n      let discrs    := indices ++ discrs\n      loop discrs matchType altViews first\n\n  throwEx {\u03b1} (p : SavedState \u00d7 Exception) : TermElabM \u03b1 := do\n    p.1.restore; throw p.2\n\n  updateFirst (first? : Option (SavedState \u00d7 Exception)) (ex : Exception) : TermElabM (SavedState \u00d7 Exception) := do\n    match first? with\n    | none       => return (\u2190 saveState, ex)\n    | some first => return first\n\n  containsFVar (es : Array Expr) (fvarId : FVarId) : Bool :=\n    es.any fun e => e.isFVar && e.fvarId! == fvarId\n\n  /- Update `indices` by including any free variable `x` s.t.\n     - Type of some `discr` depends on `x`.\n     - Type of `x` depends on some free variable in `indices`.\n\n     If we don't include these extra variables in indices, then\n     `updateMatchType` will generate a type incorrect term.\n     For example, suppose `discr` contains `h : @HEq \u03b1 a \u03b1 b`, and\n     `indices` is `#[\u03b1, b]`, and `matchType` is `@HEq \u03b1 a \u03b1 b \u2192 B`.\n     `updateMatchType indices matchType` produces the type\n     `(\u03b1' : Type) \u2192 (b : \u03b1') \u2192 @HEq \u03b1' a \u03b1' b \u2192 B` which is type incorrect\n     because we have `a : \u03b1`.\n     The method `collectDeps` will include `a` into `indices`.\n\n     This method does not handle dependencies among non-free variables.\n     We rely on the type checking method `check` at `updateMatchType`.\n\n     Remark: `indices : Array Expr` does not need to be an array anymore.\n     We should cleanup this code, and use `index : Expr` instead.\n   -/\n  collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do\n    let mut s : CollectFVars.State := {}\n    for discr in discrs do\n      s := collectFVars s (\u2190 instantiateMVars (\u2190 inferType discr))\n    let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar\n    let indicesFVar := indicesFVar.map Expr.fvarId!\n    let mut toAdd := #[]\n    for fvarId in s.fvarSet.toList do\n      unless containsFVar discrs fvarId || containsFVar indices fvarId do\n        let localDecl \u2190 getLocalDecl fvarId\n        let mctx \u2190 getMCtx\n        for indexFVarId in indicesFVar do\n          if mctx.localDeclDependsOn localDecl indexFVarId then\n            toAdd := toAdd.push fvarId\n    let indicesFVar \u2190 sortFVarIds (indicesFVar ++ toAdd)\n    return indicesFVar.map mkFVar ++ indicesNonFVar\n\n  updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do\n    let matchType \u2190 indices.foldrM (init := matchType) fun index matchType => do\n      let indexType \u2190 inferType index\n      let matchTypeBody \u2190 kabstract matchType index\n      let userName \u2190 mkUserNameFor index\n      return Lean.mkForall userName BinderInfo.default indexType matchTypeBody\n    check matchType\n    return matchType\n\n  addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do\n    let hole := mkHole (\u2190 getRef)\n    let wildcards := mkArray num hole\n    return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns }\n\ndef mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult :=\n  Meta.Match.mkMatcher input\n\nregister_builtin_option match.ignoreUnusedAlts : Bool := {\n  defValue := false\n  descr := \"if true, do not generate error if an alternative is not used\"\n}\n\ndef reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do\n  unless result.counterExamples.isEmpty do\n    withHeadRefOnly <| logError m!\"missing cases:\\n{Meta.Match.counterExamplesToMessageData result.counterExamples}\"\n  unless match.ignoreUnusedAlts.get (\u2190 getOptions) || result.unusedAltIdxs.isEmpty do\n    let mut i := 0\n    for alt in altLHSS do\n      if result.unusedAltIdxs.contains i then\n        withRef alt.ref do\n          logError \"redundant alternative\"\n      i := i + 1\n\n/--\n  If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]`\n  Otherwise, return none.\n-/\nprivate def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do\n  assert! altLHSS.length == rhss.size\n  match altLHSS with\n  | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] =>\n    /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/\n    match rhss[0] with\n    | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b\n    | _ => return none\n  | _ => return none\nprivate def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr)\n    : TermElabM Expr := do\n  let mut generalizing? := generalizing?\n  if !matchOptType.isNone then\n    if generalizing? == some true then\n      throwError \"the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided\"\n    generalizing? := some false\n  let (discrs, matchType, altLHSS, isDep, rhss) \u2190 commitIfDidNotPostpone do\n    let \u27e8discrs, matchType, isDep, altViews\u27e9 \u2190 elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType\n    let matchAlts \u2190 liftMacroM <| expandMacrosInPatterns altViews\n    trace[Elab.match] \"matchType: {matchType}\"\n    let (discrs, matchType, alts, refined) \u2190 elabMatchAltViews generalizing? discrs matchType matchAlts\n    let isDep := isDep || refined\n    /-\n     We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be\n     able to elaborate examples such as:\n     ```\n     def f (x : Nat) : Option Nat := none\n\n     def g (xs : List (Nat \u00d7 Nat)) : IO Unit :=\n     xs.forM fun x =>\n       match f x.fst with\n       | _ => pure ()\n     ```\n     If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because\n     the type of `x` is only available after we proces the last argument of `List.forM`.\n\n     We apply pending default types to make sure we can process examples such as\n     ```\n     let (a, b) := (0, 0)\n     ```\n    -/\n    synthesizeSyntheticMVarsUsingDefault\n    let rhss := alts.map Prod.snd\n    let matchType \u2190 instantiateMVars matchType\n    let altLHSS \u2190 alts.toList.mapM fun alt => do\n      let altLHS \u2190 Match.instantiateAltLHSMVars alt.1\n      /- Remark: we try to postpone before throwing an error.\n         The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed.\n         The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here.\n         Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here.\n         ```\n          def bad (ps : Array (Nat \u00d7 Nat)) : Array (Nat \u00d7 Nat) :=\n            (ps.filter fun (p : Prod _ _) =>\n              match p with\n              | (x, y) => x == 0)\n            ++\n            ps\n         ```\n         When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet\n         because `Array.filter` has type `{\u03b1 : Type u_1} \u2192 (\u03b1 \u2192 Bool) \u2192 (as : Array \u03b1) \u2192 optParam Nat 0 \u2192 optParam Nat (Array.size as) \u2192 Array \u03b1`\n         However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`.\n      -/\n      withRef altLHS.ref do\n        for d in altLHS.fvarDecls do\n            if d.hasExprMVar then\n            withExistingLocalDecls altLHS.fvarDecls do\n              tryPostpone\n              throwMVarError m!\"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}\"\n        for p in altLHS.patterns do\n          if p.hasExprMVar then\n            withExistingLocalDecls altLHS.fvarDecls do\n              tryPostpone\n              throwMVarError m!\"invalid match-expression, pattern contains metavariables{indentExpr (\u2190 p.toExpr)}\"\n        pure altLHS\n    return (discrs, matchType, altLHSS, isDep, rhss)\n  if let some r \u2190 if isDep then pure none else isMatchUnit? altLHSS rhss then\n    return r\n  else\n    let numDiscrs := discrs.size\n    let matcherName \u2190 mkAuxName `match\n    let matcherResult \u2190 mkMatcher { matcherName, matchType, numDiscrs, lhss := altLHSS }\n    matcherResult.addMatcher\n    let motive \u2190 forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType\n    reportMatcherResultErrors altLHSS matcherResult\n    let r := mkApp matcherResult.matcher motive\n    let r := mkAppN r discrs\n    let r := mkAppN r rhss\n    trace[Elab.match] \"result: {r}\"\n    return r\n\nprivate def getDiscrs (matchStx : Syntax) : Array Syntax :=\n  matchStx[2].getSepArgs\n\nprivate def getMatchOptType (matchStx : Syntax) : Syntax :=\n  matchStx[3]\n\nprivate def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=\n  let matchOptType := getMatchOptType matchStx;\n  if matchOptType.isNone then do\n    let discrs := getDiscrs matchStx;\n    let allLocal \u2190 discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1]\n    if allLocal then\n      return none\n    else\n      -- We use `foundFVars` to make sure the discriminants are distinct variables.\n      -- See: code for computing \"matchType\" at `elabMatchTypeAndDiscrs`\n      let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : FVarIdSet) := do\n        match discrs with\n        | [] =>\n          let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx \", \");\n          pure (matchStx.setArg 2 discrs)\n        | discr :: discrs =>\n          -- Recall that\n          -- matchDiscr := leading_parser optional (ident >> \":\") >> termParser\n          let term := discr[1]\n          let addAux : TermElabM Syntax := withFreshMacroScope do\n            let d \u2190 `(_discr);\n            unless isAuxDiscrName d.getId do -- Use assertion?\n              throwError \"unexpected internal auxiliary discriminant name\"\n            let discrNew := discr.setArg 1 d;\n            let r \u2190 loop discrs (discrsNew.push discrNew) foundFVars\n            `(let _discr := $term; $r)\n          match (\u2190 isAtomicDiscr? term) with\n          | some x  => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux\n          | none    => addAux\n      return some (\u2190 loop discrs.toList #[] {})\n  else\n    -- We do not pull non atomic discriminants when match type is provided explicitly by the user\n    return none\n\nprivate def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  match expectedType? with\n    | some expectedType => pure expectedType\n    | none              => mkFreshTypeMVar\n\nprivate def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do\n  -- We don't wait for the discriminants types when match type is provided by user\n  if getMatchOptType matchStx |>.isNone then\n    let discrs := getDiscrs matchStx\n    for discr in discrs do\n      let term := discr[1]\n      match (\u2190 isAtomicDiscr? term) with\n      | none   => throwErrorAt discr \"unexpected discriminant\" -- see `expandNonAtomicDiscrs?\n      | some d =>\n        let dType \u2190 inferType d\n        trace[Elab.match] \"discr {d} : {dType}\"\n        tryPostponeIfMVar dType\n\n/-\nWe (try to) elaborate a `match` only when the expected type is available.\nIf the `matchType` has not been provided by the user, we also try to postpone elaboration if the type\nof a discriminant is not available. That is, it is of the form `(?m ...)`.\nWe use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables.\nThis is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.\nSuppose, we are trying to elaborate\n```\nmatch g x with\n  | ... => ...\n```\n`expandNonAtomicDiscrs?` converts it intro\n```\nlet _discr := g x\nmatch _discr with\n  | ... => ...\n```\nThus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`.\nNote that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`.\n\nThis elaboration technique is needed to elaborate terms such as:\n```lean\nxs.filter fun (a, b) => a > b\n```\nwhich are syntax sugar for\n```lean\nList.filter (fun p => match p with | (a, b) => a > b) xs\n```\nWhen we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.\n-/\nprivate def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  tryPostponeIfDiscrTypeIsMVar matchStx\n  match expectedType? with\n  | some expectedType => return expectedType\n  | none              => mkFreshTypeMVar\n\n/-\n```\nleading_parser:leadPrec \"match \" >> sepBy1 matchDiscr \", \" >> optType >> \" with \" >> matchAlts\n```\nRemark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.\n-/\nprivate def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 waitExpectedTypeAndDiscrs stx expectedType?\n  let discrStxs := (getDiscrs stx).map fun d => d\n  let gen?         := getMatchGeneralizing? stx\n  let altViews     := getMatchAlts stx\n  let matchOptType := getMatchOptType stx\n  elabMatchAux gen? discrStxs altViews matchOptType expectedType\n\nprivate def isPatternVar (stx : Syntax) : TermElabM Bool := do\n  match (\u2190 resolveId? stx \"pattern\") with\n  | none   => return isAtomicIdent stx\n  | some f => match f with\n    | Expr.const fName _ _ =>\n      match (\u2190 getEnv).find? fName with\n      | some (ConstantInfo.ctorInfo _) => return false\n      | some _                         => return !hasMatchPatternAttribute (\u2190 getEnv) fName\n      | _                              => return isAtomicIdent stx\n    | _ => return isAtomicIdent stx\nwhere\n  isAtomicIdent (stx : Syntax) : Bool :=\n    stx.isIdent && stx.getId.eraseMacroScopes.isAtomic\n\n-- leading_parser \"match \" >> sepBy1 termParser \", \" >> optType >> \" with \" >> matchAlts\n/--\nPattern matching. `match e, ... with | p, ... => f | ...` matches each given\nterm `e` against each pattern `p` of a match alternative. When all patterns\nof an alternative match, the `match` term evaluates to the value of the\ncorresponding right-hand side `f` with the pattern variables bound to the\nrespective matched values.\nWhen not constructing a proof, `match` does not automatically substitute variables\nmatched on in dependent variables' types. Use `match (generalizing := true) ...` to\nenforce this. -/\n@[builtinTermElab \u00abmatch\u00bb] def elabMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(match $discr:term with | $y:ident => $rhs:term) =>\n     if (\u2190 isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?\n  | _ => elabMatchDefault stx expectedType?\nwhere\n  elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n    match (\u2190 expandNonAtomicDiscrs? stx) with\n    | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n    | none =>\n      let discrs       := getDiscrs stx;\n      let matchOptType := getMatchOptType stx;\n      if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then\n        throwErrorAt matchOptType \"match expected type should not be provided when discriminants with equality proofs are used\"\n      elabMatchCore stx expectedType?\n\nbuiltin_initialize\n  registerTraceClass `Elab.match\n\n-- leading_parser:leadPrec \"nomatch \" >> termParser\n/-- Empty match/ex falso. `nomatch e` is of arbitrary type `\u03b1 : Sort u` if\nLean can show that an empty set of patterns is exhaustive given `e`'s type,\ne.g. because it has no constructors. -/\n@[builtinTermElab \u00abnomatch\u00bb] def elabNoMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(nomatch $discrExpr) =>\n    match (\u2190 isLocalIdent? discrExpr) with\n    | some _ =>\n      let expectedType \u2190 waitExpectedType expectedType?\n      let discr := mkNode ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]\n      elabMatchAux none #[discr] #[] mkNullNode expectedType\n    | _ =>\n      let stxNew \u2190 `(let _discr := $discrExpr; nomatch _discr)\n      withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | _ => throwUnsupportedSyntax\n\nend Lean.Elab.Term\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/Elab/Match.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.04672496194471053, "lm_q1q2_score": 0.010155087873819793}}
{"text": "import .simulation\n\nimport ..scheduling\nimport ..spec\n\nuniverse variables u u\u2080 u\u2081 u\u2082\nopen predicate nat\nlocal infix ` \u2243 `:75 := v_eq\nlocal prefix `\u266f `:0 := cast (by simp)\n\nnamespace temporal\n\nnamespace one_to_one\nsection\nopen fairness\nparameters {\u03b1 : Type u} {\u03b2 : Type u\u2080} {\u03b3 : Type u\u2081 }\nparameters {evt : Type u\u2082}\nparameters {m\u2080 : mch' evt (\u03b3\u00d7\u03b1)} {m\u2081 : mch' evt (\u03b3\u00d7\u03b2)}\nlocal notation `p` := m\u2080.init\nlocal notation `q` := m\u2081.init\nlocal notation `aevt` := m\u2080.evt\nlocal notation `cevt` := m\u2081.evt\nlocal notation `cs\u2080` := m\u2080.cs\nlocal notation `fs\u2080` := m\u2080.fs\nlocal notation `cs\u2081` := m\u2081.cs\nlocal notation `fs\u2081` := m\u2081.fs\nlocal notation `A` := m\u2080.A\nlocal notation `C` := m\u2081.A\nparameters (J : pred' (\u03b3\u00d7\u03b1\u00d7\u03b2))\nparameters (J\u2090 : pred' (\u03b3\u00d7\u03b1))\n\ndef C' (e : evt) : act (evt\u00d7\u03b3\u00d7\u03b2) :=\n\u03bb \u27e8sch,s\u27e9 \u27e8_,s'\u27e9, sch = e \u2227 C e s s'\n\nabbreviation ae (i : evt) : event (\u03b3\u00d7\u03b1) := \u27e8cs\u2080 i,fs\u2080 i,A i\u27e9\nabbreviation ce (i : evt) : event (evt\u00d7\u03b3\u00d7\u03b2) := \u27e8cs\u2081 i!pair.snd,fs\u2081 i!pair.snd,C' i\u27e9\n\nsection specs\n\nparameters m\u2080 m\u2081\n\ndef SPEC\u2080.saf' (v : tvar \u03b1) (o : tvar \u03b3) (sch : tvar evt) : cpred :=\nspec_saf_spec m\u2080 \u2983o,v\u2984 sch\n\ndef SPEC\u2080 (v : tvar \u03b1) (o : tvar \u03b3) : cpred :=\nspec m\u2080 \u2983o,v\u2984\n\ndef SPEC\u2081 (v : tvar \u03b2) (o : tvar \u03b3) : cpred :=\nspec m\u2081 \u2983o,v\u2984\n\ndef SPEC\u2082 (v : tvar \u03b2) (o : tvar \u03b3) (s : tvar evt) : cpred :=\nspec_sch m\u2081 \u2983o,v\u2984 s\n\nend specs\n\nparameters [inhabited \u03b1] [inhabited evt]\n\nparameter init_J\u2090 : \u2200 w o, (o,w) \u22a8 p \u2192 (o,w) \u22a8 J\u2090\nparameter evt_J\u2090  : \u2200 w o w' o' e,\n                          (o,w) \u22a8 J\u2090 \u2192\n                          (o,w) \u22a8 cs\u2080 e \u2192\n                          (o,w) \u22a8 fs\u2080 e \u2192\n                          A e (o,w) (o',w') \u2192\n                          (o',w') \u22a8 J\u2090\n\nparameter SIM\u2080 : \u2200 v o, (o,v) \u22a8 q \u2192 \u2203 w, (o,w) \u22a8 p \u2227 (o,w,v) \u22a8 J\nparameter SIM\n: \u2200 w v o v' o' e,\n  (o,w,v) \u22a8 J \u2192\n  (o,w) \u22a8 J\u2090 \u2192\n  (o,v) \u22a8 cs\u2081 e \u2192\n  (o,v) \u22a8 fs\u2081 e \u2192\n  C e (o,v) (o',v') \u2192\n  \u2203 w', (o,w) \u22a8 cs\u2080 e \u2227\n        (o,w) \u22a8 fs\u2080 e \u2227\n        A e (o,w) (o',w') \u2227\n        (o',w',v') \u22a8 J\n\nparameters (v : tvar \u03b2) (o : tvar \u03b3) (sch : tvar evt)\n\nvariable (\u0393 : cpred)\n\nparameters \u03b2 \u03b3\n\nvariable Hpo : \u2200 w e sch,\n  one_to_one_po' (SPEC\u2081 v o \u22c0 SPEC\u2080.saf' w o sch \u22c0 \u25fb(J ! \u2983o,w,v\u2984))\n     (ce e) (ae e) \u2983sch,o,v\u2984 \u2983o,w\u2984\n\nparameters {\u03b2 \u03b3}\n\nsection SPEC\u2082\nvariables H : \u0393 \u22a2 SPEC\u2082 v o sch\n\nopen prod temporal.prod\n\ndef Next_a : act $ (\u03b3 \u00d7 evt) \u00d7 \u03b1 :=\n\u03bb \u03c3 \u03c3',\n\u2203 e, \u03c3.1.2 = e \u2227\n     map_left fst \u03c3 \u22a8 cs\u2080 e \u2227\n     map_left fst \u03c3 \u22a8 fs\u2080 e \u2227\n     (A e on map_left fst) \u03c3 \u03c3'\n\ndef Next_c : act $ (\u03b3 \u00d7 evt) \u00d7 \u03b2 :=\n\u03bb \u03c3 \u03c3',\n\u2203 e, \u03c3.1.2 = e \u2227\n     map_left fst \u03c3 \u22a8 cs\u2081 e \u2227\n     map_left fst \u03c3 \u22a8 fs\u2081 e \u2227\n     (C e on map_left fst) \u03c3 \u03c3'\n\nsection J\ndef J' : pred' ((\u03b3 \u00d7 evt) \u00d7 \u03b1 \u00d7 \u03b2) :=\nJ ! \u27e8 prod.map_left fst \u27e9\n\ndef JJ\u2090 : pred' ((\u03b3 \u00d7 evt) \u00d7 \u03b1) :=\nJ\u2090 ! \u27e8 prod.map_left fst \u27e9\n\ndef p' : pred' ((\u03b3 \u00d7 evt) \u00d7 \u03b1) :=\np ! \u27e8 prod.map_left fst \u27e9\n\ndef q' : pred' ((\u03b3 \u00d7 evt) \u00d7 \u03b2) :=\nq ! \u27e8 prod.map_left fst \u27e9\n\nend J\n\nvariable w : tvar \u03b1\nopen simulation function\nnoncomputable def Wtn := Wtn p' Next_a J' v \u2983o,sch\u2984\n\nvariable valid_witness\n: \u0393 \u22a2 Wtn w\n\nlemma abstract_sch (e : evt)\n: \u0393 \u22a2 sch \u2243 e \u22c0 cs\u2080 e ! \u2983o,w\u2984 \u22c0 fs\u2080 e ! \u2983o,w\u2984 \u22c0 \u27e6 o,w | A e \u27e7 \u2261\n      sch \u2243 e \u22c0 \u27e6 \u2983o,sch\u2984,w | Next_a \u27e7 :=\nbegin\n  lifted_pred,\n  split ; intro h ; split\n  ; casesm* _ \u2227 _ ; try { assumption }\n  ; simp [Next_a,on_fun] at * ; cc,\nend\n\nsection Simulation_POs\ninclude SIM\u2080\nlemma SIM\u2080' (v : \u03b2) (o : \u03b3 \u00d7 evt)\n  (h : (o, v) \u22a8 q')\n: (\u2203 (w : \u03b1), (o, w) \u22a8 p' \u2227 (o, w, v) \u22a8 J') :=\nbegin\n  simp [q',prod.map_left] at h,\n  specialize SIM\u2080 v o.1 h,\n  revert SIM\u2080, intros_mono,\n  simp [J',p',map], intros,\n  constructor_matching* [Exists _, _ \u2227 _] ;\n  tauto,\nend\n\nomit SIM\u2080\ninclude SIM\nlemma SIM' (w : \u03b1) (v : \u03b2) (o : \u03b3 \u00d7 evt) (v' : \u03b2) (o' : \u03b3 \u00d7 evt)\n  (h\u2080 : (o, w, v) \u22a8 J')\n  (h\u2083 : (o, w) \u22a8 JJ\u2090)\n  (h\u2084 : Next_c (o, v) (o', v'))\n: (\u2203 w', Next_a (o,w) (o',w') \u2227 (o', w', v') \u22a8 J') :=\nbegin\n  simp [J',map] at h\u2080,\n  simp [Next_c,on_fun] at h\u2084,\n  casesm* _ \u2227 _,\n  simp [JJ\u2090] at h\u2083,\n  specialize SIM w v o.1 v' o'.1 o.2 h\u2080 _ _ _ _\n  ; try { assumption },\n  cases SIM with w' SIM,\n  existsi [w'],\n  simp [Next_a, J',on_fun,map,h\u2080],\n  tauto,\nend\n\ninclude H\nomit SIM\nlemma H'\n: \u0393 \u22a2 simulation.SPEC\u2081 q' Next_c v \u2983o,sch\u2984 :=\nbegin [temporal]\n  simp [SPEC\u2082,simulation.SPEC\u2081,q'] at H \u22a2,\n  split, tauto,\n  casesm* _ \u22c0 _,\n  select h : \u25fbp_exists _,\n  henceforth! at h \u22a2,\n  cases h with e h,\n  explicit' [Next_c,sched] with h\n  { casesm* _ \u2227 _, subst e, tauto, }\nend\n\nomit H\nsection\ninclude init_J\u2090\nlemma init_J\u2090' (w : \u03b1) (o : \u03b3 \u00d7 evt)\n  (h : (o, w) \u22a8 p')\n: (o, w) \u22a8 JJ\u2090 :=\nby { cases o, simp [JJ\u2090,p'] at *, solve_by_elim }\nend\n\nsection\ninclude evt_J\u2090\nlemma evt_J\u2090' (w : \u03b1) (o : \u03b3 \u00d7 evt) (w' : \u03b1) (o' : \u03b3 \u00d7 evt)\n  (h\u2080 : (o, w) \u22a8 JJ\u2090)\n  (h\u2081 : Next_a (o, w) (o', w'))\n: (o', w') \u22a8 JJ\u2090 :=\nby { cases o, simp [JJ\u2090,p',Next_a,on_fun] at *, tauto }\nend\n\ninclude SIM\u2080 SIM init_J\u2090 evt_J\u2090 H\nlemma witness_imp_SPEC\u2080_saf\n  (h : \u0393 \u22a2 Wtn w)\n: \u0393 \u22a2 SPEC\u2080.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\u2090\n                        temporal.one_to_one.init_J\u2090'\n                        temporal.one_to_one.evt_J\u2090'\n                        temporal.one_to_one.SIM\u2080'\n                        temporal.one_to_one.SIM'\n                        v \u2983o,sch\u2984 \u0393\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\u2090\n                        temporal.one_to_one.init_J\u2090'\n                        temporal.one_to_one.evt_J\u2090'\n                        temporal.one_to_one.SIM\u2080'\n                        temporal.one_to_one.SIM'\n                        v \u2983o,sch\u2984 \u0393\n                        (temporal.one_to_one.H' _ H)\n                        _ h ,\n  simp [SPEC\u2080.saf',SPEC\u2082,Wtn,simulation.Wtn] at h \u22a2 H,\n  casesm* _ \u22c0 _,\n  split,\n  { clear SIM hJ,\n    select h : w \u2243 _,\n    select h' : q ! _,\n    rw [\u2190 pair.snd_mk sch w,h],\n    explicit\n    { simp [Wx\u2080] at \u22a2 h', unfold_coes,\n      simp [Wx\u2080_f,p',J',map],\n      cases SIM\u2080 (\u03c3 \u22a8 v) (\u03c3 \u22a8 o) h',\n      apply_epsilon_spec, } },\n  { clear SIM\u2080,\n    select h : \u25fb(_ \u2243 _),\n    select h' : \u25fb(p_exists _),\n    henceforth! at h h' \u22a2 hJ hJ',\n    explicit' [Wf,Wf_f,J',JJ\u2090]\n      with  h h' hJ hJ'\n    { simp [Next_a,on_fun] at h h',\n      casesm* [_ \u2227 _,Exists _],\n      subst w', subst h'_w,\n      apply_epsilon_spec,\n      have : (\u2203 (w' : \u03b1), (o, w) \u22a8 cs\u2080 sch \u2227\n      (o, w) \u22a8 fs\u2080 sch \u2227 A sch (o, w) (o', w') \u2227 (o', w', v') \u22a8 J), solve_by_elim,\n      cases this, tauto, } },\nend\n\nomit H\nparameters p q cs\u2081 fs\u2081\ninclude Hpo p\n\nlemma SPEC\u2082_imp_SPEC\u2081\n: (SPEC\u2082 v o sch) \u27f9 (SPEC\u2081 v o) :=\nbegin [temporal]\n  simp only [SPEC\u2081,SPEC\u2082,temporal.one_to_one.SPEC\u2081,temporal.one_to_one.SPEC\u2082],\n  monotonicity, apply ctx_p_and_p_imp_p_and',\n  { monotonicity, simp, intros x h\u2080 h\u2081 _ _,\n    existsi x, tauto, },\n  { intros h i h\u2080 h\u2081,\n    replace h := h _ h\u2080 h\u2081,\n    revert h, monotonicity, simp, }\nend\n\nlemma H_C_imp_A (e : evt)\n: SPEC\u2082 v o sch \u22c0 Wtn w \u22c0 \u25fb(J ! \u2983o,w,v\u2984) \u27f9\n  \u25fb(cs\u2081 e ! \u2983o,v\u2984 \u22c0 fs\u2081 e ! \u2983o,v\u2984 \u22c0 sch \u2243 \u2191e \u22c0 \u27e6 o,v | C e \u27e7 \u27f6\n    cs\u2080 e ! \u2983o,w\u2984 \u22c0 fs\u2080 e ! \u2983o,w\u2984 \u22c0 \u27e6 o,w | A e \u27e7) :=\nbegin [temporal]\n  intro H',\n  have H : temporal.one_to_one.SPEC\u2081 v o \u22c0\n           temporal.one_to_one.Wtn w \u22c0\n           \u25fb(J ! \u2983o,w,v\u2984),\n  { revert H',  persistent,\n    intro, casesm* _ \u22c0 _, split* ; try { assumption },\n    apply temporal.one_to_one.SPEC\u2082_imp_SPEC\u2081 _ \u0393 _,\n    solve_by_elim, casesm* _ \u22c0 _, solve_by_elim, },\n  clear Hpo,\n  let J' := temporal.one_to_one.J',\n  have init_J\u2090' := temporal.one_to_one.init_J\u2090', clear init_J\u2090,\n  have evt_J\u2090' := temporal.one_to_one.evt_J\u2090',  clear evt_J\u2090,\n  have SIM\u2080' := temporal.one_to_one.SIM\u2080', clear SIM\u2080,\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\u2090' evt_J\u2090'\n    SIM\u2080' SIM' v \u2983o,sch\u2984 \u0393 _ w _,\n  { henceforth! at this \u22a2,\n    simp, intros h\u2080 h\u2081 h\u2082 h\u2083, clear_except this h\u2080 h\u2081 h\u2082 h\u2083,\n    suffices : sch \u2243 \u2191e \u22c0 cs\u2080 e ! \u2983o,w\u2984 \u22c0 fs\u2080 e ! \u2983o,w\u2984 \u22c0 \u27e6 o,w | A e \u27e7,\n    { tauto },\n    rw abstract_sch, split, assumption,\n    apply this _,\n    simp [Next_c],\n    suffices : \u27e6 \u2983o,sch\u2984,v | \u03bb (\u03c3 \u03c3' : (\u03b3 \u00d7 evt) \u00d7 \u03b2), (\u03c3.fst).snd = e \u2227 (C e on map_left fst) \u03c3 \u03c3' \u27e7,\n    { explicit' with h\u2080 h\u2081 h\u2082 h\u2083 { cc, }, },\n    rw [\u2190 action_and_action,\u2190 init_eq_action,action_on'], split,\n    explicit\n    { simp at \u22a2 h\u2080, assumption },\n    simp [h\u2083], },\n  clear_except H',\n  simp [simulation.SPEC\u2081,SPEC\u2082,temporal.one_to_one.SPEC\u2082] at H' \u22a2,\n  cases_matching* _ \u22c0 _, split,\n  { simp [q'], assumption, },\n  { select H' : \u25fb(p_exists _), clear_except H',\n    henceforth at H' \u22a2, cases H' with i H',\n    simp [Next_c],\n    suffices : \u27e6 \u2983o,sch\u2984,v | \u03bb (\u03c3 \u03c3' : (\u03b3 \u00d7 evt) \u00d7 \u03b2), (\u03c3.fst).snd = i \u2227 (C i on map_left fst) \u03c3 \u03c3' \u27e7,\n    { explicit'* { cases this, subst i, tauto, } },\n    explicit'* { cc }, },\n  { cases_matching* _ \u22c0 _, assumption, },\nend\n\nlemma Hpo' (e : evt)\n: one_to_one_po (SPEC\u2082 v o sch \u22c0 Wtn w \u22c0 \u25fb(J ! \u2983o,w,v\u2984))\n/- -/ (cs\u2081 e ! \u2983o,v\u2984)\n      (fs\u2081 e ! \u2983o,v\u2984)\n      (sch \u2243 \u2191e \u22c0 \u27e6 o,v | C e \u27e7)\n/- -/ (cs\u2080 e ! \u2983o,w\u2984)\n      (fs\u2080 e ! \u2983o,w\u2984)\n      \u27e6 o,w | A e \u27e7 :=\nbegin\n  have\n  : temporal.one_to_one.SPEC\u2082 v o sch \u22c0 temporal.one_to_one.Wtn w \u22c0 \u25fb(J ! \u2983o,w,v\u2984) \u27f9\n    temporal.one_to_one.SPEC\u2081 v o \u22c0 temporal.one_to_one.SPEC\u2080.saf' w o sch \u22c0 \u25fb(J ! \u2983o,w,v\u2984),\n  begin [temporal]\n    simp, intros h\u2080 h\u2081 h\u2082,\n    split*,\n    { apply temporal.one_to_one.SPEC\u2082_imp_SPEC\u2081 Hpo _ h\u2080, },\n    { apply temporal.one_to_one.witness_imp_SPEC\u2080_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 \u22a2 H_imp,\n    simp at H_imp \u22a2,\n    exact H_imp,\n  end\nend\n\nend Simulation_POs\n\ninclude H SIM\u2080 SIM Hpo init_J\u2090 evt_J\u2090\n\nlemma sched_ref (i : evt) (w : tvar \u03b1)\n (Hw : \u0393 \u22a2 Wtn w)\n (h : \u0393 \u22a2 sched (cs\u2081 i ! \u2983o,v\u2984) (fs\u2081 i ! \u2983o,v\u2984) (sch \u2243 \u2191i \u22c0 \u27e6 o,v | C i \u27e7))\n: \u0393 \u22a2 sched (cs\u2080 i ! \u2983o,w\u2984) (fs\u2080 i ! \u2983o,w\u2984)\n            \u27e6 o,w | A i \u27e7 :=\nbegin [temporal]\n  have H' := one_to_one.H' C v o sch _ H,\n  have hJ : \u25fb(J' J ! \u2983\u2983o,sch\u2984,w,v\u2984),\n  { replace SIM\u2080 := SIM\u2080' _ SIM\u2080,\n    replace SIM := SIM' A C J _ SIM,\n    apply simulation.J_inv_in_w p' q' (Next_a A) _ (J' J) _ _ _ SIM\u2080 SIM _ \u2983o,sch\u2984 _ H' w Hw,\n    apply temporal.one_to_one.init_J\u2090',\n    apply temporal.one_to_one.evt_J\u2090' },\n  simp [J'] at hJ,\n  have Hpo' := temporal.one_to_one.Hpo' Hpo w i,\n  apply replacement Hpo' \u0393 _,\n  tauto, solve_by_elim,\nend\n\nlemma one_to_one\n: \u0393 \u22a2 \u2203\u2203 w, SPEC\u2080 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\u2080,SPEC\u2081],\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\u2080 Hw H,\n    replace SIM\u2080 := temporal.one_to_one.SIM\u2080',\n    have := init_in_w p' q' (Next_a A) (J' J) SIM\u2080 v \u2983o,sch\u2984 \u0393 _ Hw,\n    intro Hq,\n    simp [p',q'] at this,\n    solve_by_elim, },\n  { clear_except SIM SIM\u2080 Hw H init_J\u2090 evt_J\u2090,\n    have H' := H' C v o sch _ H,\n    replace SIM\u2080 := SIM\u2080' _ SIM\u2080,\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\u2080 SIM v \u2983o,sch\u2984 _ H' w Hw,\n    { monotonicity!,\n      simp [exists_action],\n      intros e h\u2080 h\u2081 h\u2082 h\u2083, replace this := this _,\n      explicit'* [Next_a]\n      { intros, casesm* _ \u2227 _,\n        constructor_matching* [Exists _,_ \u2227 _] ; solve_by_elim, },\n      simp [Next_c],\n      suffices : \u27e6 \u2983o,sch\u2984,v | \u03bb (\u03c3 \u03c3' : (\u03b3 \u00d7 evt) \u00d7 \u03b2), map_left prod.fst \u03c3 \u22a8 fs\u2081 e \u2227 ((\u03bb s s', s = e) on (prod.snd \u2218 prod.fst)) \u03c3 \u03c3' \u2227 (C e on map_left prod.fst) \u03c3 \u03c3' \u27e7,\n      explicit' with h\u2080 h\u2081 this\n      { intros, subst e, tauto, },\n      henceforth at this,\n      explicit'* [Next_c]\n      { tauto } },\n    { apply temporal.one_to_one.init_J\u2090' },\n    { apply temporal.one_to_one.evt_J\u2090' }, },\n  { intros h i,\n    replace h := h i,\n    apply temporal.one_to_one.sched_ref; solve_by_elim },\nend\nend SPEC\u2082\n\nsection refinement_SPEC\u2082\ninclude Hpo SIM\u2080 SIM init_J\u2090 evt_J\u2090\nparameters m\u2081 m\u2080\n\nlemma refinement_SPEC\u2082\n: \u0393 \u22a2 (\u2203\u2203 sch, SPEC\u2082 v o sch) \u27f6 (\u2203\u2203 a, SPEC\u2080 a o) :=\nbegin [temporal]\n  simp, intros sch Hc,\n  apply one_to_one J J\u2090 init_J\u2090 evt_J\u2090 SIM\u2080 SIM _ _ _ _ _  Hc,\n  apply Hpo,\nend\nend refinement_SPEC\u2082\n\nlemma refinement_SPEC\u2081 [schedulable evt]\n: SPEC\u2081 v o \u27f9 (\u2203\u2203 sch, SPEC\u2082 v o sch) :=\nassume \u0393,\nsch_intro _ _ _ _ _ _\n\ninclude SIM\u2080 SIM init_J\u2090 evt_J\u2090\nlemma refinement [schedulable evt]\n  (h : \u2200 c a e sch, one_to_one_po' (SPEC\u2081 c o \u22c0 SPEC\u2080.saf' a o sch \u22c0 \u25fb(J ! \u2983o,a,c\u2984))\n         \u27e8cs\u2081 e!pair.snd,fs\u2081 e!pair.snd,C' e\u27e9\n         \u27e8cs\u2080 e,fs\u2080 e,A e\u27e9 \u2983sch,o,c\u2984 \u2983o,a\u2984)\n: (\u2203\u2203 c, SPEC\u2081 c o) \u27f9 (\u2203\u2203 a, SPEC\u2080 a o) :=\nbegin [temporal]\n  transitivity (\u2203\u2203 c sch, SPEC\u2082 q C cs\u2081 fs\u2081 c o sch),\n  { apply p_exists_p_imp_p_exists ,\n    intro v,\n    apply refinement_SPEC\u2081, },\n  { simp, intros c sch Hspec,\n    specialize h c, simp [one_to_one_po'] at h,\n    apply refinement_SPEC\u2082 A C cs\u2080 fs\u2080 cs\u2081 fs\u2081 J J\u2090 init_J\u2090 evt_J\u2090 SIM\u2080 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": "import tactic.doc_commands\nimport tactic.reserved_notation\n\n\nopen function\nlocal attribute [instance, priority 10] classical.prop_decidable\n\nsection miscellany\n\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 {\u03b1 : Type*} {\u03b2 : Type*}\n\n@[reducible] def hidden {\u03b1 : Sort*} {a : \u03b1} := a\n\ndef empty.elim {C : Sort*} : empty \u2192 C.\n\ninstance : subsingleton empty := \u27e8\u03bba, a.elim\u27e9\n\ninstance subsingleton.prod {\u03b1 \u03b2 : Type*} [subsingleton \u03b1] [subsingleton \u03b2] : subsingleton (\u03b1 \u00d7 \u03b2) :=\n\u27e8by { intros a b, cases a, cases b, congr, }\u27e9\n\ninstance : decidable_eq empty := \u03bba, a.elim\n\ninstance sort.inhabited : inhabited Sort* := \u27e8punit\u27e9\ninstance sort.inhabited' : inhabited default := \u27e8punit.star\u27e9\n\ninstance psum.inhabited_left {\u03b1 \u03b2} [inhabited \u03b1] : inhabited (psum \u03b1 \u03b2) := \u27e8psum.inl default\u27e9\ninstance psum.inhabited_right {\u03b1 \u03b2} [inhabited \u03b2] : inhabited (psum \u03b1 \u03b2) := \u27e8psum.inr default\u27e9\n\n@[priority 10] instance decidable_eq_of_subsingleton\n  {\u03b1} [subsingleton \u03b1] : decidable_eq \u03b1\n| a b := is_true (subsingleton.elim a b)\n\n@[simp] lemma eq_iff_true_of_subsingleton {\u03b1 : Sort*} [subsingleton \u03b1] (x y : \u03b1) :\n  x = y \u2194 true :=\nby cc\n\nlemma subsingleton_of_forall_eq {\u03b1 : Sort*} (x : \u03b1) (h : \u2200 y, y = x) : subsingleton \u03b1 :=\n\u27e8\u03bb a b, (h a).symm \u25b8 (h b).symm \u25b8 rfl\u27e9\n\nlemma subsingleton_iff_forall_eq {\u03b1 : Sort*} (x : \u03b1) : subsingleton \u03b1 \u2194 \u2200 y, y = x :=\n\u27e8\u03bb h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x\u27e9\n\nlemma subtype.subsingleton (\u03b1 : Sort*) [subsingleton \u03b1] (p : \u03b1 \u2192 Prop) : subsingleton (subtype p) :=\n\u27e8\u03bb \u27e8x, _\u27e9 \u27e8y, _\u27e9, have x = y, from subsingleton.elim _ _, by { cases this, refl }\u27e9\n\n@[simp] theorem coe_coe {\u03b1 \u03b2 \u03b3} [has_coe \u03b1 \u03b2] [has_coe_t \u03b2 \u03b3]\n  (a : \u03b1) : (a : \u03b3) = (a : \u03b2) := rfl\n\ntheorem coe_fn_coe_trans\n  {\u03b1 \u03b2 \u03b3 \u03b4} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_fun \u03b3 \u03b4]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\ntheorem coe_fn_coe_trans'\n  {\u03b1 \u03b2 \u03b3} {\u03b4 : out_param $ _} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_fun \u03b3 (\u03bb _, \u03b4)]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\n@[simp] theorem coe_fn_coe_base\n  {\u03b1 \u03b2 \u03b3} [has_coe \u03b1 \u03b2] [has_coe_to_fun \u03b2 \u03b3]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\ntheorem coe_fn_coe_base'\n  {\u03b1 \u03b2} {\u03b3 : out_param $ _} [has_coe \u03b1 \u03b2] [has_coe_to_fun \u03b2 (\u03bb _, \u03b3)]\n  (x : \u03b1) : @coe_fn \u03b1 _ _ x = @coe_fn \u03b2 _ _ x := rfl\n\ntheorem coe_sort_coe_trans\n  {\u03b1 \u03b2 \u03b3 \u03b4} [has_coe \u03b1 \u03b2] [has_coe_t_aux \u03b2 \u03b3] [has_coe_to_sort \u03b3 \u03b4]\n  (x : \u03b1) : @coe_sort \u03b1 _ _ x = @coe_sort \u03b2 _ _ x := rfl\n\nlibrary_note \"function coercion\"\n\n@[simp] theorem coe_sort_coe_base\n  {\u03b1 \u03b2 \u03b3} [has_coe \u03b1 \u03b2] [has_coe_to_sort \u03b2 \u03b3]\n  (x : \u03b1) : @coe_sort \u03b1 _ _ x = @coe_sort \u03b2 _ _ x := rfl\n\n@[derive decidable_eq]\ninductive {u} pempty : Sort u\n\ndef pempty.elim {C : Sort*} : pempty \u2192 C.\n\ninstance subsingleton_pempty : subsingleton pempty := \u27e8\u03bba, a.elim\u27e9\n\n@[simp] lemma not_nonempty_pempty : \u00ac nonempty pempty :=\nassume \u27e8h\u27e9, h.elim\n\n@[simp] theorem forall_pempty {P : pempty \u2192 Prop} : (\u2200 x : pempty, P x) \u2194 true :=\n\u27e8\u03bb h, trivial, \u03bb h x, by cases x\u27e9\n\n@[simp] theorem exists_pempty {P : pempty \u2192 Prop} : (\u2203 x : pempty, P x) \u2194 false :=\n\u27e8\u03bb h, by { cases h with w, cases w }, false.elim\u27e9\n\nlemma congr_heq {\u03b1 \u03b2 \u03b3 : Sort*} {f : \u03b1 \u2192 \u03b3} {g : \u03b2 \u2192 \u03b3} {x : \u03b1} {y : \u03b2} (h\u2081 : f == g)\n  (h\u2082 : x == y) : f x = g y :=\nby { cases h\u2082, cases h\u2081, refl }\n\nlemma congr_arg_heq {\u03b1} {\u03b2 : \u03b1 \u2192 Sort*} (f : \u2200 a, \u03b2 a) : \u2200 {a\u2081 a\u2082 : \u03b1}, a\u2081 = a\u2082 \u2192 f a\u2081 == f a\u2082\n| a _ rfl := heq.rfl\n\nlemma ulift.down_injective {\u03b1 : Sort*} : function.injective (@ulift.down \u03b1)\n| \u27e8a\u27e9 \u27e8b\u27e9 rfl := rfl\n\n@[simp] lemma ulift.down_inj {\u03b1 : Sort*} {a b : ulift \u03b1} : a.down = b.down \u2194 a = b :=\n\u27e8\u03bb h, ulift.down_injective h, \u03bb h, by rw h\u27e9\n\nlemma plift.down_injective {\u03b1 : Sort*} : function.injective (@plift.down \u03b1)\n| \u27e8a\u27e9 \u27e8b\u27e9 rfl := rfl\n\n@[simp] lemma plift.down_inj {\u03b1 : Sort*} {a b : plift \u03b1} : a.down = b.down \u2194 a = b :=\n\u27e8\u03bb h, plift.down_injective h, \u03bb h, by rw h\u27e9\n\nattribute [symm] ne.symm\n\nlemma ne_comm {\u03b1} {a b : \u03b1} : a \u2260 b \u2194 b \u2260 a := \u27e8ne.symm, ne.symm\u27e9\n\n@[simp] lemma eq_iff_eq_cancel_left {b c : \u03b1} :\n  (\u2200 {a}, a = b \u2194 a = c) \u2194 (b = c) :=\n\u27e8\u03bb h, by rw [\u2190 h], \u03bb h a, by rw h\u27e9\n\n@[simp] lemma eq_iff_eq_cancel_right {a b : \u03b1} :\n  (\u2200 {c}, a = c \u2194 b = c) \u2194 (a = b) :=\n\u27e8\u03bb h, by rw h, \u03bb h a, by rw h\u27e9\n\nclass fact (p : Prop) : Prop := (out [] : p)\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 \u2194 p := \u27e8\u03bb h, h.1, \u03bb h, \u27e8h\u27e9\u27e9\n\n@[reducible] def function.swap\u2082 {\u03b9\u2081 \u03b9\u2082 : Sort*} {\u03ba\u2081 : \u03b9\u2081 \u2192 Sort*} {\u03ba\u2082 : \u03b9\u2082 \u2192 Sort*}\n  {\u03c6 : \u03a0 i\u2081, \u03ba\u2081 i\u2081 \u2192 \u03a0 i\u2082, \u03ba\u2082 i\u2082 \u2192 Sort*} (f : \u03a0 i\u2081 j\u2081 i\u2082 j\u2082, \u03c6 i\u2081 j\u2081 i\u2082 j\u2082) :\n  \u03a0 i\u2082 j\u2082 i\u2081 j\u2081, \u03c6 i\u2081 j\u2081 i\u2082 j\u2082 :=\n\u03bb i\u2082 j\u2082 i\u2081 j\u2081, f i\u2081 j\u2081 i\u2082 j\u2082\n\ndef auto_param.out {\u03b1 : Sort*} {n : name} (x : auto_param \u03b1 n) : \u03b1 := x\n\ndef opt_param.out {\u03b1 : Sort*} {d : \u03b1} (x : \u03b1 := d) : \u03b1 := x\n\nend miscellany\n\nopen function\n\n\ntheorem false_ne_true : false \u2260 true\n| h := h.symm \u25b8 trivial\n\nsection propositional\nvariables {a b c d e f : Prop}\n\n\ninstance : is_refl Prop iff := \u27e8iff.refl\u27e9\ninstance : is_trans Prop iff := \u27e8\u03bb _ _ _, iff.trans\u27e9\n\ntheorem iff_of_eq (e : a = b) : a \u2194 b := e \u25b8 iff.rfl\n\ntheorem iff_iff_eq : (a \u2194 b) \u2194 a = b := \u27e8propext, iff_of_eq\u27e9\n\n@[simp] lemma eq_iff_iff {p q : Prop} : (p = q) \u2194 (p \u2194 q) := iff_iff_eq.symm\n\n@[simp] theorem imp_self : (a \u2192 a) \u2194 true := iff_true_intro id\n\nlemma iff.imp (h\u2081 : a \u2194 b) (h\u2082 : c \u2194 d) : (a \u2192 c) \u2194 (b \u2192 d) := imp_congr h\u2081 h\u2082\n\n@[simp] lemma eq_true_eq_id : eq true = id :=\nby { funext, simp only [true_iff, id.def, iff_self, eq_iff_iff], }\n\ntheorem imp_intro {\u03b1 \u03b2 : Prop} (h : \u03b1) : \u03b2 \u2192 \u03b1 := \u03bb _, h\n\ntheorem imp_false : (a \u2192 false) \u2194 \u00ac a := iff.rfl\n\ntheorem imp_and_distrib {\u03b1} : (\u03b1 \u2192 b \u2227 c) \u2194 (\u03b1 \u2192 b) \u2227 (\u03b1 \u2192 c) :=\n\u27e8\u03bb h, \u27e8\u03bb ha, (h ha).left, \u03bb ha, (h ha).right\u27e9, \n\u03bb h ha, \u27e8h.left ha, h.right ha\u27e9\u27e9\n\n@[simp] theorem and_imp : (a \u2227 b \u2192 c) \u2194 (a \u2192 b \u2192 c) :=\niff.intro (\u03bb h ha hb, h \u27e8ha, hb\u27e9) (\u03bb h \u27e8ha, hb\u27e9, h ha hb)\n\ntheorem iff_def : (a \u2194 b) \u2194 (a \u2192 b) \u2227 (b \u2192 a) :=\niff_iff_implies_and_implies _ _\n\ntheorem iff_def' : (a \u2194 b) \u2194 (b \u2192 a) \u2227 (a \u2192 b) :=\niff_def.trans and.comm\n\ntheorem imp_true_iff {\u03b1 : Sort*} : (\u03b1 \u2192 true) \u2194 true :=\niff_true_intro $ \u03bb_, trivial\n\ntheorem imp_iff_right (ha : a) : (a \u2192 b) \u2194 b :=\n\u27e8\u03bbf, f ha, imp_intro\u27e9\n\nlemma imp_iff_not (hb : \u00ac b) : a \u2192 b \u2194 \u00ac a := imp_congr_right $ \u03bb _, iff_false_intro hb\n\ntheorem decidable.imp_iff_right_iff [decidable a] : ((a \u2192 b) \u2194 b) \u2194 (a \u2228 b) :=\n\u27e8\u03bb H, (decidable.em a).imp_right $ \u03bb ha', H.1 $ \u03bb ha, (ha' ha).elim, \n  \u03bb H, H.elim imp_iff_right $ \u03bb hb, \u27e8\u03bb hab, hb, \u03bb _ _, hb\u27e9\u27e9\n\n@[simp] theorem imp_iff_right_iff : ((a \u2192 b) \u2194 b) \u2194 (a \u2228 b) :=\ndecidable.imp_iff_right_iff\n\nlemma decidable.and_or_imp [decidable a] : (a \u2227 b) \u2228 (a \u2192 c) \u2194 a \u2192 (b \u2228 c) :=\nif ha : a then by simp only [ha, true_and, true_implies_iff]\n          else by simp only [ha, false_or, false_and, false_implies_iff]\n\n@[simp] theorem and_or_imp : (a \u2227 b) \u2228 (a \u2192 c) \u2194 a \u2192 (b \u2228 c) :=\ndecidable.and_or_imp\n\n\ndef not.elim {\u03b1 : Sort*} (H1 : \u00aca) (H2 : a) : \u03b1 := absurd H2 H1\n\n@[reducible] theorem not.imp {a b : Prop} (H2 : \u00acb) (H1 : a \u2192 b) : \u00aca := mt H1 H2\n\ntheorem not_not_of_not_imp : \u00ac(a \u2192 b) \u2192 \u00ac\u00aca :=\nmt not.elim\n\ntheorem not_of_not_imp {a : Prop} : \u00ac(a \u2192 b) \u2192 \u00acb :=\nmt imp_intro\n\ntheorem dec_em (p : Prop) [decidable p] : p \u2228 \u00acp := decidable.em p\n\ntheorem dec_em' (p : Prop) [decidable p] : \u00acp \u2228 p := (dec_em p).swap\n\ntheorem em (p : Prop) : p \u2228 \u00acp := classical.em _\n\ntheorem em' (p : Prop) : \u00acp \u2228 p := (em p).swap\n\ntheorem or_not {p : Prop} : p \u2228 \u00acp := em _\n\nsection eq_or_ne\n\nvariables {\u03b1 : Sort*} (x y : \u03b1)\n\ntheorem decidable.eq_or_ne [decidable (x = y)] : x = y \u2228 x \u2260 y := dec_em $ x = y\n\ntheorem decidable.ne_or_eq [decidable (x = y)] : x \u2260 y \u2228 x = y := dec_em' $ x = y\n\ntheorem eq_or_ne : x = y \u2228 x \u2260 y := em $ x = y\n\ntheorem ne_or_eq : x \u2260 y \u2228 x = y := em' $ x = y\n\nend eq_or_ne\n\ntheorem by_contradiction {p} : (\u00acp \u2192 false) \u2192 p := decidable.by_contradiction\n\ntheorem by_contra {p} : (\u00acp \u2192 false) \u2192 p := decidable.by_contradiction\n\nlibrary_note \"decidable namespace\"\n\nlibrary_note \"decidable arguments\"\n\nprotected theorem decidable.not_not [decidable a] : \u00ac\u00aca \u2194 a :=\niff.intro decidable.by_contradiction not_not_intro\n\n@[simp] theorem not_not : \u00ac\u00aca \u2194 a := decidable.not_not\n\ntheorem of_not_not : \u00ac\u00aca \u2192 a := by_contra\n\nlemma not_ne_iff {\u03b1 : Sort*} {a b : \u03b1} : \u00ac a \u2260 b \u2194 a = b := not_not\n\nprotected theorem decidable.of_not_imp [decidable a] (h : \u00ac (a \u2192 b)) : a :=\ndecidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp : \u00ac (a \u2192 b) \u2192 a := decidable.of_not_imp\n\nprotected theorem decidable.not_imp_symm [decidable a] (h : \u00aca \u2192 b) (hb : \u00acb) : a :=\ndecidable.by_contradiction $ hb \u2218 h\n\ntheorem not.decidable_imp_symm [decidable a] : (\u00aca \u2192 b) \u2192 \u00acb \u2192 a := decidable.not_imp_symm\n\ntheorem not.imp_symm : (\u00aca \u2192 b) \u2192 \u00acb \u2192 a := not.decidable_imp_symm\n\nprotected theorem decidable.not_imp_comm [decidable a] [decidable b] : (\u00aca \u2192 b) \u2194 (\u00acb \u2192 a) :=\n\u27e8not.decidable_imp_symm, not.decidable_imp_symm\u27e9\n\ntheorem not_imp_comm : (\u00aca \u2192 b) \u2194 (\u00acb \u2192 a) := decidable.not_imp_comm\n\n@[simp] theorem imp_not_self : (a \u2192 \u00aca) \u2194 \u00aca := \u27e8\u03bb h ha, h ha ha, \u03bb h _, h\u27e9\n\ntheorem decidable.not_imp_self [decidable a] : (\u00aca \u2192 a) \u2194 a :=\nby { have := @imp_not_self (\u00aca), rwa decidable.not_not at this }\n\n@[simp] theorem not_imp_self : (\u00aca \u2192 a) \u2194 a := decidable.not_imp_self\n\ntheorem imp.swap : (a \u2192 b \u2192 c) \u2194 (b \u2192 a \u2192 c) :=\n\u27e8swap, swap\u27e9\n\ntheorem imp_not_comm : (a \u2192 \u00acb) \u2194 (b \u2192 \u00aca) :=\nimp.swap\n\nlemma iff.not (h : a \u2194 b) : \u00ac a \u2194 \u00ac b := not_congr h\nlemma iff.not_left (h : a \u2194 \u00ac b) : \u00ac a \u2194 b := h.not.trans not_not\nlemma iff.not_right (h : \u00ac a \u2194 b) : a \u2194 \u00ac b := not_not.symm.trans h.not\n\n\n@[simp] theorem xor_true : xor true = not := funext $ \u03bb a, by simp [xor]\n\n@[simp] theorem xor_false : xor false = id := funext $ \u03bb 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 := \u27e8xor_comm\u27e9\n\n@[simp] theorem xor_self (a : Prop) : xor a a = false := by simp [xor]\n\n\nlemma iff.and (h\u2081 : a \u2194 b) (h\u2082 : c \u2194 d) : a \u2227 c \u2194 b \u2227 d := and_congr h\u2081 h\u2082\n\ntheorem and_congr_left (h : c \u2192 (a \u2194 b)) : a \u2227 c \u2194 b \u2227 c :=\nand.comm.trans $ (and_congr_right h).trans and.comm\n\ntheorem and_congr_left' (h : a \u2194 b) : a \u2227 c \u2194 b \u2227 c := h.and iff.rfl\n\ntheorem and_congr_right' (h : b \u2194 c) : a \u2227 b \u2194 a \u2227 c := iff.rfl.and h\n\ntheorem not_and_of_not_left (b : Prop) : \u00aca \u2192 \u00ac(a \u2227 b) :=\nmt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : \u00acb \u2192 \u00ac(a \u2227 b) :=\nmt and.right\n\ntheorem and.imp_left (h : a \u2192 b) : a \u2227 c \u2192 b \u2227 c :=\nand.imp h id\n\ntheorem and.imp_right (h : a \u2192 b) : c \u2227 a \u2192 c \u2227 b :=\nand.imp id h\n\nlemma and.right_comm : (a \u2227 b) \u2227 c \u2194 (a \u2227 c) \u2227 b :=\nby simp only [and.left_comm, and.comm]\n\nlemma and_and_and_comm (a b c d : Prop) : (a \u2227 b) \u2227 c \u2227 d \u2194 (a \u2227 c) \u2227 b \u2227 d :=\nby rw [\u2190and_assoc, @and.right_comm a, and_assoc]\n\nlemma and_and_distrib_left (a b c : Prop) : a \u2227 (b \u2227 c) \u2194 (a \u2227 b) \u2227 (a \u2227 c) :=\nby rw [and_and_and_comm, and_self]\n\nlemma and_and_distrib_right (a b c : Prop) : (a \u2227 b) \u2227 c \u2194 (a \u2227 c) \u2227 (b \u2227 c) :=\nby rw [and_and_and_comm, and_self]\n\nlemma and_rotate : a \u2227 b \u2227 c \u2194 b \u2227 c \u2227 a := by simp only [and.left_comm, and.comm]\nlemma and.rotate : a \u2227 b \u2227 c \u2192 b \u2227 c \u2227 a := and_rotate.1\n\ntheorem and_not_self_iff (a : Prop) : a \u2227 \u00ac a \u2194 false :=\niff.intro (assume h, (h.right) (h.left)) (assume h, h.elim)\n\ntheorem not_and_self_iff (a : Prop) : \u00ac a \u2227 a \u2194 false :=\niff.intro (assume \u27e8hna, ha\u27e9, hna ha) false.elim\n\ntheorem and_iff_left_of_imp {a b : Prop} (h : a \u2192 b) : (a \u2227 b) \u2194 a :=\niff.intro and.left (\u03bb ha, \u27e8ha, h ha\u27e9)\n\ntheorem and_iff_right_of_imp {a b : Prop} (h : b \u2192 a) : (a \u2227 b) \u2194 b :=\niff.intro and.right (\u03bb hb, \u27e8h hb, hb\u27e9)\n\n@[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a \u2227 b) \u2194 a) \u2194 (a \u2192 b) :=\n\u27e8\u03bb h ha, (h.2 ha).2, and_iff_left_of_imp\u27e9\n\n@[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a \u2227 b) \u2194 b) \u2194 (b \u2192 a) :=\n\u27e8\u03bb h ha, (h.2 ha).1, and_iff_right_of_imp\u27e9\n\n@[simp] lemma iff_self_and {p q : Prop} : (p \u2194 p \u2227 q) \u2194 (p \u2192 q) :=\nby rw [@iff.comm p, and_iff_left_iff_imp]\n\n@[simp] lemma iff_and_self {p q : Prop} : (p \u2194 q \u2227 p) \u2194 (p \u2192 q) :=\nby rw [and_comm, iff_self_and]\n\n@[simp] lemma and.congr_right_iff : (a \u2227 b \u2194 a \u2227 c) \u2194 (a \u2192 (b \u2194 c)) :=\n\u27e8\u03bb h ha, by simp [ha] at h; exact h, and_congr_right\u27e9\n\n@[simp] lemma and.congr_left_iff : (a \u2227 c \u2194 b \u2227 c) \u2194 c \u2192 (a \u2194 b) :=\nby simp only [and.comm, \u2190 and.congr_right_iff]\n\n@[simp] lemma and_self_left : a \u2227 a \u2227 b \u2194 a \u2227 b :=\n\u27e8\u03bb h, \u27e8h.1, h.2.2\u27e9, \u03bb h, \u27e8h.1, h.1, h.2\u27e9\u27e9\n\n@[simp] lemma and_self_right : (a \u2227 b) \u2227 b \u2194 a \u2227 b :=\n\u27e8\u03bb h, \u27e8h.1.1, h.2\u27e9, \u03bb h, \u27e8\u27e8h.1, h.2\u27e9, h.2\u27e9\u27e9\n\n\nlemma iff.or (h\u2081 : a \u2194 b) (h\u2082 : c \u2194 d) : a \u2228 c \u2194 b \u2228 d := or_congr h\u2081 h\u2082\n\nlemma or_congr_left' (h : a \u2194 b) : a \u2228 c \u2194 b \u2228 c := h.or iff.rfl\nlemma or_congr_right' (h : b \u2194 c) : a \u2228 b \u2194 a \u2228 c := iff.rfl.or h\n\ntheorem or.right_comm : (a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 b := by rw [or_assoc, or_assoc, or_comm b]\n\nlemma or_or_or_comm (a b c d : Prop) : (a \u2228 b) \u2228 c \u2228 d \u2194 (a \u2228 c) \u2228 b \u2228 d :=\nby rw [\u2190or_assoc, @or.right_comm a, or_assoc]\n\nlemma or_or_distrib_left (a b c : Prop) : a \u2228 (b \u2228 c) \u2194 (a \u2228 b) \u2228 (a \u2228 c) :=\nby rw [or_or_or_comm, or_self]\n\nlemma or_or_distrib_right (a b c : Prop) : (a \u2228 b) \u2228 c \u2194 (a \u2228 c) \u2228 (b \u2228 c) :=\nby rw [or_or_or_comm, or_self]\n\nlemma or_rotate : a \u2228 b \u2228 c \u2194 b \u2228 c \u2228 a := by simp only [or.left_comm, or.comm]\nlemma or.rotate : a \u2228 b \u2228 c \u2192 b \u2228 c \u2228 a := or_rotate.1\n\ntheorem or_of_or_of_imp_of_imp (h\u2081 : a \u2228 b) (h\u2082 : a \u2192 c) (h\u2083 : b \u2192 d) : c \u2228 d :=\nor.imp h\u2082 h\u2083 h\u2081\n\ntheorem or_of_or_of_imp_left (h\u2081 : a \u2228 c) (h : a \u2192 b) : b \u2228 c :=\nor.imp_left h h\u2081\n\ntheorem or_of_or_of_imp_right (h\u2081 : c \u2228 a) (h : a \u2192 b) : c \u2228 b :=\nor.imp_right h h\u2081\n\ntheorem or.elim3 (h : a \u2228 b \u2228 c) (ha : a \u2192 d) (hb : b \u2192 d) (hc : c \u2192 d) : d :=\nor.elim h ha (assume h\u2082, or.elim h\u2082 hb hc)\n\nlemma or.imp3 (had : a \u2192 d) (hbe : b \u2192 e) (hcf : c \u2192 f) : a \u2228 b \u2228 c \u2192 d \u2228 e \u2228 f :=\nor.imp had $ or.imp hbe hcf\n\ntheorem or_imp_distrib : (a \u2228 b \u2192 c) \u2194 (a \u2192 c) \u2227 (b \u2192 c) :=\n\u27e8assume h, \u27e8assume ha, h (or.inl ha), assume hb, h (or.inr hb)\u27e9, \n  assume \u27e8ha, hb\u27e9, or.rec ha hb\u27e9\n\nprotected theorem decidable.or_iff_not_imp_left [decidable a] : a \u2228 b \u2194 (\u00ac a \u2192 b) :=\n\u27e8or.resolve_left, \u03bb h, dite _ or.inl (or.inr \u2218 h)\u27e9\n\ntheorem or_iff_not_imp_left : a \u2228 b \u2194 (\u00ac a \u2192 b) := decidable.or_iff_not_imp_left\n\nprotected theorem decidable.or_iff_not_imp_right [decidable b] : a \u2228 b \u2194 (\u00ac b \u2192 a) :=\nor.comm.trans decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right : a \u2228 b \u2194 (\u00ac b \u2192 a) := decidable.or_iff_not_imp_right\n\nprotected lemma decidable.not_or_of_imp [decidable a] (h : a \u2192 b) : \u00ac a \u2228 b :=\ndite _ (or.inr \u2218 h) or.inl\n\nlemma not_or_of_imp : (a \u2192 b) \u2192 \u00ac a \u2228 b := decidable.not_or_of_imp\n\nprotected lemma decidable.or_not_of_imp [decidable a] (h : a \u2192 b) : b \u2228 \u00ac a :=\ndite _ (or.inl \u2218 h) or.inr\n\nlemma or_not_of_imp : (a \u2192 b) \u2192 b \u2228 \u00ac a := decidable.or_not_of_imp\n\nprotected lemma decidable.imp_iff_not_or [decidable a] : a \u2192 b \u2194 \u00ac a \u2228 b :=\n\u27e8decidable.not_or_of_imp, or.neg_resolve_left\u27e9\n\nlemma imp_iff_not_or : a \u2192 b \u2194 \u00ac a \u2228 b := decidable.imp_iff_not_or\n\nprotected lemma decidable.imp_iff_or_not [decidable b] : b \u2192 a \u2194 a \u2228 \u00ac b :=\ndecidable.imp_iff_not_or.trans or.comm\n\nlemma imp_iff_or_not : b \u2192 a \u2194 a \u2228 \u00ac b := decidable.imp_iff_or_not\n\nprotected theorem decidable.not_imp_not [decidable a] : (\u00ac a \u2192 \u00ac b) \u2194 (b \u2192 a) :=\n\u27e8assume h hb, decidable.by_contradiction $ assume na, h na hb, mt\u27e9\n\ntheorem not_imp_not : (\u00ac a \u2192 \u00ac b) \u2194 (b \u2192 a) := decidable.not_imp_not\n\nprotected lemma decidable.or_congr_left [decidable c] (h : \u00ac c \u2192 (a \u2194 b)) : a \u2228 c \u2194 b \u2228 c :=\nby { rw [decidable.or_iff_not_imp_right, decidable.or_iff_not_imp_right], exact imp_congr_right h }\n\nlemma or_congr_left (h : \u00ac c \u2192 (a \u2194 b)) : a \u2228 c \u2194 b \u2228 c :=\ndecidable.or_congr_left h\n\nprotected lemma decidable.or_congr_right [decidable a] (h : \u00ac a \u2192 (b \u2194 c)) : a \u2228 b \u2194 a \u2228 c :=\nby { rw [decidable.or_iff_not_imp_left, decidable.or_iff_not_imp_left], exact imp_congr_right h }\n\nlemma or_congr_right (h : \u00ac a \u2192 (b \u2194 c)) : a \u2228 b \u2194 a \u2228 c :=\ndecidable.or_congr_right h\n\n@[simp] theorem or_iff_left_iff_imp : (a \u2228 b \u2194 a) \u2194 (b \u2192 a) :=\n\u27e8\u03bb h hb, h.1 (or.inr hb), or_iff_left_of_imp\u27e9\n\n@[simp] theorem or_iff_right_iff_imp : (a \u2228 b \u2194 b) \u2194 (a \u2192 b) :=\nby rw [or_comm, or_iff_left_iff_imp]\n\nlemma or_iff_left (hb : \u00ac b) : a \u2228 b \u2194 a := \u27e8\u03bb h, h.resolve_right hb, or.inl\u27e9\nlemma or_iff_right (ha : \u00ac a) : a \u2228 b \u2194 b := \u27e8\u03bb h, h.resolve_left ha, or.inr\u27e9\n\n\ntheorem and_or_distrib_left : a \u2227 (b \u2228 c) \u2194 (a \u2227 b) \u2228 (a \u2227 c) :=\n\u27e8\u03bb \u27e8ha, hbc\u27e9, hbc.imp (and.intro ha) (and.intro ha), \nor.rec (and.imp_right or.inl) (and.imp_right or.inr)\u27e9\n\ntheorem or_and_distrib_right : (a \u2228 b) \u2227 c \u2194 (a \u2227 c) \u2228 (b \u2227 c) :=\n(and.comm.trans and_or_distrib_left).trans (and.comm.or and.comm)\n\ntheorem or_and_distrib_left : a \u2228 (b \u2227 c) \u2194 (a \u2228 b) \u2227 (a \u2228 c) :=\n\u27e8or.rec (\u03bbha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr), \nand.rec $ or.rec (imp_intro \u2218 or.inl) (or.imp_right \u2218 and.intro)\u27e9\n\ntheorem and_or_distrib_right : (a \u2227 b) \u2228 c \u2194 (a \u2228 c) \u2227 (b \u2228 c) :=\n(or.comm.trans or_and_distrib_left).trans (or.comm.and or.comm)\n\n@[simp] lemma or_self_left : a \u2228 a \u2228 b \u2194 a \u2228 b :=\n\u27e8\u03bb h, h.elim or.inl id, \u03bb h, h.elim or.inl (or.inr \u2218 or.inr)\u27e9\n\n@[simp] lemma or_self_right : (a \u2228 b) \u2228 b \u2194 a \u2228 b :=\n\u27e8\u03bb h, h.elim id or.inr, \u03bb h, h.elim (or.inl \u2218 or.inl) or.inr\u27e9\n\n\nlemma iff.iff (h\u2081 : a \u2194 b) (h\u2082 : c \u2194 d) : (a \u2194 c) \u2194 (b \u2194 d) := iff_congr h\u2081 h\u2082\n\ntheorem iff_of_true (ha : a) (hb : b) : a \u2194 b :=\n\u27e8\u03bb_, hb, \u03bb _, ha\u27e9\n\ntheorem iff_of_false (ha : \u00aca) (hb : \u00acb) : a \u2194 b :=\n\u27e8ha.elim, hb.elim\u27e9\n\ntheorem iff_true_left (ha : a) : (a \u2194 b) \u2194 b :=\n\u27e8\u03bb h, h.1 ha, iff_of_true ha\u27e9\n\ntheorem iff_true_right (ha : a) : (b \u2194 a) \u2194 b :=\niff.comm.trans (iff_true_left ha)\n\ntheorem iff_false_left (ha : \u00aca) : (a \u2194 b) \u2194 \u00acb :=\n\u27e8\u03bb h, mt h.2 ha, iff_of_false ha\u27e9\n\ntheorem iff_false_right (ha : \u00aca) : (b \u2194 a) \u2194 \u00acb :=\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\nprotected theorem decidable.imp_or_distrib [decidable a] : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\nby simp [decidable.imp_iff_not_or, or.comm, or.left_comm]\n\ntheorem imp_or_distrib : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) := decidable.imp_or_distrib\n\nprotected theorem decidable.imp_or_distrib' [decidable b] : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) :=\nby by_cases b; simp [h, or_iff_right_of_imp ((\u2218) false.elim)]\n\ntheorem imp_or_distrib' : (a \u2192 b \u2228 c) \u2194 (a \u2192 b) \u2228 (a \u2192 c) := decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not : a \u2227 \u00ac b \u2192 \u00ac (a \u2192 b)\n| \u27e8ha, hb\u27e9 h := hb $ h ha\n\nprotected theorem decidable.not_imp [decidable a] : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb :=\n\u27e8\u03bb h, \u27e8decidable.of_not_imp h, not_of_not_imp h\u27e9, not_imp_of_and_not\u27e9\n\ntheorem not_imp : \u00ac(a \u2192 b) \u2194 a \u2227 \u00acb := decidable.not_imp\n\nlemma imp_imp_imp (h\u2080 : c \u2192 a) (h\u2081 : b \u2192 d) : (a \u2192 b) \u2192 (c \u2192 d) :=\nassume (h\u2082 : a \u2192 b), h\u2081 \u2218 h\u2082 \u2218 h\u2080\n\nprotected theorem decidable.peirce (a b : Prop) [decidable a] : ((a \u2192 b) \u2192 a) \u2192 a :=\nif ha : a then \u03bb h, ha else \u03bb h, h ha.elim\n\ntheorem peirce (a b : Prop) : ((a \u2192 b) \u2192 a) \u2192 a := decidable.peirce _ _\n\ntheorem peirce' {a : Prop} (H : \u2200 b : Prop, (a \u2192 b) \u2192 a) : a := H _ id\n\nprotected theorem decidable.not_iff_not [decidable a] [decidable b] : (\u00ac a \u2194 \u00ac b) \u2194 (a \u2194 b) :=\nby rw [@iff_def (\u00ac a), @iff_def' a]; exact decidable.not_imp_not.and decidable.not_imp_not\n\ntheorem not_iff_not : (\u00ac a \u2194 \u00ac b) \u2194 (a \u2194 b) := decidable.not_iff_not\n\nprotected theorem decidable.not_iff_comm [decidable a] [decidable b] : (\u00ac a \u2194 b) \u2194 (\u00ac b \u2194 a) :=\nby rw [@iff_def (\u00ac a), @iff_def (\u00ac b)]; exact decidable.not_imp_comm.and imp_not_comm\n\ntheorem not_iff_comm : (\u00ac a \u2194 b) \u2194 (\u00ac b \u2194 a) := decidable.not_iff_comm\n\nprotected theorem decidable.not_iff : \u2200 [decidable b], \u00ac (a \u2194 b) \u2194 (\u00ac a \u2194 b) :=\nby intro h; cases h; simp only [h, iff_true, iff_false]\n\ntheorem not_iff : \u00ac (a \u2194 b) \u2194 (\u00ac a \u2194 b) := decidable.not_iff\n\nprotected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a \u2194 \u00ac b) \u2194 (b \u2194 \u00ac a) :=\nby rw [@iff_def a, @iff_def b]; exact imp_not_comm.and decidable.not_imp_comm\n\ntheorem iff_not_comm : (a \u2194 \u00ac b) \u2194 (b \u2194 \u00ac a) := decidable.iff_not_comm\n\nprotected theorem decidable.iff_iff_and_or_not_and_not [decidable b] :\n  (a \u2194 b) \u2194 (a \u2227 b) \u2228 (\u00ac a \u2227 \u00ac 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 \u2194 b) \u2194 (a \u2227 b) \u2228 (\u00ac a \u2227 \u00ac 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 \u2194 b) \u2194 ((\u00aca \u2228 b) \u2227 (a \u2228 \u00acb)) :=\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 \u2194 b) \u2194 ((\u00aca \u2228 b) \u2227 (a \u2228 \u00acb)) :=\ndecidable.iff_iff_not_or_and_or_not\n\nprotected theorem decidable.not_and_not_right [decidable b] : \u00ac(a \u2227 \u00acb) \u2194 (a \u2192 b) :=\n\u27e8\u03bb h ha, h.decidable_imp_symm $ and.intro ha, \u03bb h \u27e8ha, hb\u27e9, hb $ h ha\u27e9\n\ntheorem not_and_not_right : \u00ac(a \u2227 \u00acb) \u2194 (a \u2192 b) := decidable.not_and_not_right\n\n@[inline] def decidable_of_iff (a : Prop) (h : a \u2194 b) [D : decidable a] : decidable b :=\ndecidable_of_decidable_of_iff D h\n\n@[inline] def decidable_of_iff' (b : Prop) (h : a \u2194 b) [D : decidable b] : decidable a :=\ndecidable_of_decidable_of_iff D h.symm\n\ndef decidable_of_bool : \u2200 (b : bool) (h : b \u2194 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\ntheorem not_and_of_not_or_not (h : \u00ac a \u2228 \u00ac b) : \u00ac (a \u2227 b)\n| \u27e8ha, hb\u27e9 := or.elim h (absurd ha) (absurd hb)\n\nprotected theorem decidable.not_and_distrib [decidable a] : \u00ac (a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\n\u27e8\u03bb h, if ha : a then or.inr (\u03bb hb, h \u27e8ha, hb\u27e9) else or.inl ha, not_and_of_not_or_not\u27e9\n\nprotected theorem decidable.not_and_distrib' [decidable b] : \u00ac (a \u2227 b) \u2194 \u00aca \u2228 \u00acb :=\n\u27e8\u03bb h, if hb : b then or.inl (\u03bb ha, h \u27e8ha, hb\u27e9) else or.inr hb, not_and_of_not_or_not\u27e9\n\ntheorem not_and_distrib : \u00ac (a \u2227 b) \u2194 \u00aca \u2228 \u00acb := decidable.not_and_distrib\n\n@[simp] theorem not_and : \u00ac (a \u2227 b) \u2194 (a \u2192 \u00ac b) := and_imp\n\ntheorem not_and' : \u00ac (a \u2227 b) \u2194 b \u2192 \u00aca :=\nnot_and.trans imp_not_comm\n\ntheorem not_or_distrib : \u00ac (a \u2228 b) \u2194 \u00ac a \u2227 \u00ac b :=\n\u27e8\u03bb h, \u27e8\u03bb ha, h (or.inl ha), \u03bb hb, h (or.inr hb)\u27e9, \n\u03bb \u27e8h\u2081, h\u2082\u27e9 h, or.elim h h\u2081 h\u2082\u27e9\n\nprotected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a \u2228 b \u2194 \u00ac (\u00aca \u2227 \u00acb) :=\nby rw [\u2190 not_or_distrib, decidable.not_not]\n\ntheorem or_iff_not_and_not : a \u2228 b \u2194 \u00ac (\u00aca \u2227 \u00acb) := decidable.or_iff_not_and_not\n\nprotected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] :\n  a \u2227 b \u2194 \u00ac (\u00ac a \u2228 \u00ac b) :=\nby rw [\u2190 decidable.not_and_distrib, decidable.not_not]\n\ntheorem and_iff_not_or_not : a \u2227 b \u2194 \u00ac (\u00ac a \u2228 \u00ac b) := decidable.and_iff_not_or_not\n\n@[simp] theorem not_xor (P Q : Prop) : \u00ac xor P Q \u2194 (P \u2194 Q) :=\nby simp only [not_and, xor, not_or_distrib, not_not, \u2190 iff_iff_implies_and_implies]\n\ntheorem xor_iff_not_iff (P Q : Prop) : xor P Q \u2194 \u00ac (P \u2194 Q) :=\nby rw [iff_not_comm, not_xor]\n\n\nend propositional\n\n\nsection mem\nvariables {\u03b1 \u03b2 : Type*} [has_mem \u03b1 \u03b2] {s t : \u03b2} {a b : \u03b1}\n\nlemma ne_of_mem_of_not_mem (h : a \u2208 s) : b \u2209 s \u2192 a \u2260 b := mt $ \u03bb e, e \u25b8 h\nlemma ne_of_mem_of_not_mem' (h : a \u2208 s) : a \u2209 t \u2192 s \u2260 t := mt $ \u03bb e, e \u25b8 h\n\nlemma has_mem.mem.ne_of_not_mem : a \u2208 s \u2192 b \u2209 s \u2192 a \u2260 b := ne_of_mem_of_not_mem\nlemma has_mem.mem.ne_of_not_mem' : a \u2208 s \u2192 a \u2209 t \u2192 s \u2260 t := ne_of_mem_of_not_mem'\n\nend mem\n\nsection equality\nvariables {\u03b1 : Sort*} {a b : \u03b1}\n\n@[simp] theorem heq_iff_eq : a == b \u2194 a = b :=\n\u27e8eq_of_heq, heq_of_eq\u27e9\n\ntheorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq :=\nhave p = q, from propext \u27e8\u03bb _, hq, \u03bb _, hp\u27e9, \nby subst q; refl\n\nlemma ball_cond_comm {\u03b1} {s : \u03b1 \u2192 Prop} {p : \u03b1 \u2192 \u03b1 \u2192 Prop} :\n  (\u2200 a, s a \u2192 \u2200 b, s b \u2192 p a b) \u2194 (\u2200 a b, s a \u2192 s b \u2192 p a b) :=\n\u27e8\u03bb h a b ha hb, h a ha b hb, \u03bb h a ha b hb, h a b ha hb\u27e9\n\nlemma ball_mem_comm {\u03b1 \u03b2} [has_mem \u03b1 \u03b2] {s : \u03b2} {p : \u03b1 \u2192 \u03b1 \u2192 Prop} :\n  (\u2200 a b \u2208 s, p a b) \u2194 (\u2200 a b, a \u2208 s \u2192 b \u2208 s \u2192 p a b) :=\nball_cond_comm\n\nlemma ne_of_apply_ne {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) {x y : \u03b1} (h : f x \u2260 f y) : x \u2260 y :=\n\u03bb (w : x = y), h (congr_arg f w)\n\ntheorem eq_equivalence : equivalence (@eq \u03b1) :=\n\u27e8eq.refl, @eq.symm _, @eq.trans _\u27e9\n\n@[simp]\nlemma eq_rec_constant {\u03b1 : Sort*} {a a' : \u03b1} {\u03b2 : Sort*} (y : \u03b2) (h : a = a') :\n  (@eq.rec \u03b1 a (\u03bb a, \u03b2) y a' h) = y :=\nby { cases h, refl, }\n\n@[simp]\nlemma eq_mp_eq_cast {\u03b1 \u03b2 : Sort*} (h : \u03b1 = \u03b2) : eq.mp h = cast h := rfl\n\n@[simp]\nlemma eq_mpr_eq_cast {\u03b1 \u03b2 : Sort*} (h : \u03b1 = \u03b2) : eq.mpr h = cast h.symm := rfl\n\n@[simp]\nlemma cast_cast : \u2200 {\u03b1 \u03b2 \u03b3 : Sort*} (ha : \u03b1 = \u03b2) (hb : \u03b2 = \u03b3) (a : \u03b1), \n  cast hb (cast ha a) = cast (ha.trans hb) a\n| _ _ _ rfl rfl a := rfl\n\n@[simp] lemma congr_refl_left {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) {a b : \u03b1} (h : a = b) :\n  congr (eq.refl f) h = congr_arg f h :=\nrfl\n\n@[simp] lemma congr_refl_right {\u03b1 \u03b2 : Sort*} {f g : \u03b1 \u2192 \u03b2} (h : f = g) (a : \u03b1) :\n  congr h (eq.refl a) = congr_fun h a :=\nrfl\n\n@[simp] lemma congr_arg_refl {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n  congr_arg f (eq.refl a) = eq.refl (f a) :=\nrfl\n\n@[simp] lemma congr_fun_rfl {\u03b1 \u03b2 : Sort*} (f : \u03b1 \u2192 \u03b2) (a : \u03b1) :\n  congr_fun (eq.refl f) a = eq.refl (f a) :=\nrfl\n\n@[simp] lemma congr_fun_congr_arg {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) {a a' : \u03b1} (p : a = a') (b : \u03b2) :\n  congr_fun (congr_arg f p) b = congr_arg (\u03bb a, f a b) p :=\nrfl\n\nlemma heq_of_cast_eq :\n  \u2200 {\u03b1 \u03b2 : Sort*} {a : \u03b1} {a' : \u03b2} (e : \u03b1 = \u03b2) (h\u2082 : cast e a = a'), a == a'\n| \u03b1._ a a' rfl h := eq.rec_on h (heq.refl _)\n\nlemma cast_eq_iff_heq {\u03b1 \u03b2 : Sort*} {a : \u03b1} {a' : \u03b2} {e : \u03b1 = \u03b2} : cast e a = a' \u2194 a == a' :=\n\u27e8heq_of_cast_eq _, \u03bb h, by cases h; refl\u27e9\n\nlemma rec_heq_of_heq {\u03b2} {C : \u03b1 \u2192 Sort*} {x : C a} {y : \u03b2} (eq : a = b) (h : x == y) :\n  @eq.rec \u03b1 a C x b eq == y :=\nby subst eq; exact h\n\nprotected lemma eq.congr {x\u2081 x\u2082 y\u2081 y\u2082 : \u03b1} (h\u2081 : x\u2081 = y\u2081) (h\u2082 : x\u2082 = y\u2082) :\n  (x\u2081 = x\u2082) \u2194 (y\u2081 = y\u2082) :=\nby { subst h\u2081, subst h\u2082 }\n\nlemma eq.congr_left {x y z : \u03b1} (h : x = y) : x = z \u2194 y = z := by rw [h]\nlemma eq.congr_right {x y z : \u03b1} (h : x = y) : z = x \u2194 z = y := by rw [h]\n\nlemma congr_arg2 {\u03b1 \u03b2 \u03b3 : Sort*} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) {x x' : \u03b1} {y y' : \u03b2}\n  (hx : x = x') (hy : y = y') : f x y = f x' y' :=\nby { subst hx, subst hy }\n\nvariables {\u03b2 : \u03b1 \u2192 Sort*} {\u03b3 : \u03a0 a, \u03b2 a \u2192 Sort*} {\u03b4 : \u03a0 a b, \u03b3 a b \u2192 Sort*}\n\nlemma congr_fun\u2082 {f g : \u03a0 a b, \u03b3 a b} (h : f = g) (a : \u03b1) (b : \u03b2 a) : f a b = g a b :=\ncongr_fun (congr_fun h _) _\n\nlemma congr_fun\u2083 {f g : \u03a0 a b c, \u03b4 a b c} (h : f = g) (a : \u03b1) (b : \u03b2 a) (c : \u03b3 a b) :\n  f a b c = g a b c :=\ncongr_fun\u2082 (congr_fun h _) _ _\n\nlemma funext\u2082 {f g : \u03a0 a, \u03b2 a \u2192 Prop} (h : \u2200 a b, f a b = g a b) : f = g :=\nfunext $ \u03bb _, funext $ h _\n\nlemma funext\u2083 {f g : \u03a0 a b, \u03b3 a b \u2192 Prop} (h : \u2200 a b c, f a b c = g a b c) : f = g :=\nfunext $ \u03bb _, funext\u2082 $ h _\n\nend equality\n\n\nsection quantifiers\nvariables {\u03b1 : Sort*}\n\nsection dependent\nvariables {\u03b2 : \u03b1 \u2192 Sort*} {\u03b3 : \u03a0 a, \u03b2 a \u2192 Sort*} {\u03b4 : \u03a0 a b, \u03b3 a b \u2192 Sort*}\n  {\u03b5 : \u03a0 a b c, \u03b4 a b c \u2192 Sort*}\n\nlemma pi_congr {\u03b2' : \u03b1 \u2192 Sort*} (h : \u2200 a, \u03b2 a = \u03b2' a) : (\u03a0 a, \u03b2 a) = \u03a0 a, \u03b2' a :=\n(funext h : \u03b2 = \u03b2') \u25b8 rfl\n\nlemma forall\u2082_congr {p q : \u03a0 a, \u03b2 a \u2192 Prop} (h : \u2200 a b, p a b \u2194 q a b) :\n  (\u2200 a b, p a b) \u2194 \u2200 a b, q a b :=\nforall_congr $ \u03bb a, forall_congr $ h a\n\nlemma forall\u2083_congr {p q : \u03a0 a b, \u03b3 a b \u2192 Prop} (h : \u2200 a b c, p a b c \u2194 q a b c) :\n  (\u2200 a b c, p a b c) \u2194 \u2200 a b c, q a b c :=\nforall_congr $ \u03bb a, forall\u2082_congr $ h a\n\nlemma forall\u2084_congr {p q : \u03a0 a b c, \u03b4 a b c \u2192 Prop} (h : \u2200 a b c d, p a b c d \u2194 q a b c d) :\n  (\u2200 a b c d, p a b c d) \u2194 \u2200 a b c d, q a b c d :=\nforall_congr $ \u03bb a, forall\u2083_congr $ h a\n\nlemma forall\u2085_congr {p q : \u03a0 a b c d, \u03b5 a b c d \u2192 Prop}\n  (h : \u2200 a b c d e, p a b c d e \u2194 q a b c d e) :\n  (\u2200 a b c d e, p a b c d e) \u2194 \u2200 a b c d e, q a b c d e :=\nforall_congr $ \u03bb a, forall\u2084_congr $ h a\n\nlemma exists\u2082_congr {p q : \u03a0 a, \u03b2 a \u2192 Prop} (h : \u2200 a b, p a b \u2194 q a b) :\n  (\u2203 a b, p a b) \u2194 \u2203 a b, q a b :=\nexists_congr $ \u03bb a, exists_congr $ h a\n\nlemma exists\u2083_congr {p q : \u03a0 a b, \u03b3 a b \u2192 Prop} (h : \u2200 a b c, p a b c \u2194 q a b c) :\n  (\u2203 a b c, p a b c) \u2194 \u2203 a b c, q a b c :=\nexists_congr $ \u03bb a, exists\u2082_congr $ h a\n\nlemma exists\u2084_congr {p q : \u03a0 a b c, \u03b4 a b c \u2192 Prop} (h : \u2200 a b c d, p a b c d \u2194 q a b c d) :\n  (\u2203 a b c d, p a b c d) \u2194 \u2203 a b c d, q a b c d :=\nexists_congr $ \u03bb a, exists\u2083_congr $ h a\n\nlemma exists\u2085_congr {p q : \u03a0 a b c d, \u03b5 a b c d \u2192 Prop}\n  (h : \u2200 a b c d e, p a b c d e \u2194 q a b c d e) :\n  (\u2203 a b c d e, p a b c d e) \u2194 \u2203 a b c d e, q a b c d e :=\nexists_congr $ \u03bb a, exists\u2084_congr $ h a\n\nlemma forall_imp {p q : \u03b1 \u2192 Prop} (h : \u2200 a, p a \u2192 q a) : (\u2200 a, p a) \u2192 \u2200 a, q a := \u03bb h' a, h a (h' a)\n\nlemma forall\u2082_imp {p q : \u03a0 a, \u03b2 a \u2192 Prop} (h : \u2200 a b, p a b \u2192 q a b) :\n  (\u2200 a b, p a b) \u2192 \u2200 a b, q a b :=\nforall_imp $ \u03bb i, forall_imp $ h i\n\nlemma forall\u2083_imp {p q : \u03a0 a b, \u03b3 a b \u2192 Prop} (h : \u2200 a b c, p a b c \u2192 q a b c) :\n  (\u2200 a b c, p a b c) \u2192 \u2200 a b c, q a b c :=\nforall_imp $ \u03bb a, forall\u2082_imp $ h a\n\nlemma Exists.imp {p q : \u03b1 \u2192 Prop} (h : \u2200 a, (p a \u2192 q a)) : (\u2203 a, p a) \u2192 \u2203 a, q a :=\nexists_imp_exists h\n\nlemma Exists\u2082.imp {p q : \u03a0 a, \u03b2 a \u2192 Prop} (h : \u2200 a b, p a b \u2192 q a b) :\n  (\u2203 a b, p a b) \u2192 \u2203 a b, q a b :=\nExists.imp $ \u03bb a, Exists.imp $ h a\n\nlemma Exists\u2083.imp {p q : \u03a0 a b, \u03b3 a b \u2192 Prop} (h : \u2200 a b c, p a b c \u2192 q a b c) :\n  (\u2203 a b c, p a b c) \u2192 \u2203 a b c, q a b c :=\nExists.imp $ \u03bb a, Exists\u2082.imp $ h a\n\nend dependent\n\nvariables {\u03b9 \u03b2 : Sort*} {\u03ba : \u03b9 \u2192 Sort*} {p q : \u03b1 \u2192 Prop} {b : Prop}\n\nlemma exists_imp_exists' {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} (f : \u03b1 \u2192 \u03b2) (hpq : \u2200 a, p a \u2192 q (f a))\n  (hp : \u2203 a, p a) : \u2203 b, q b :=\nexists.elim hp (\u03bb a hp', \u27e8_, hpq _ hp'\u27e9)\n\ntheorem forall_swap {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2200 x y, p x y) \u2194 \u2200 y x, p x y :=\n\u27e8swap, swap\u27e9\n\nlemma forall\u2082_swap {\u03b9\u2081 \u03b9\u2082 : Sort*} {\u03ba\u2081 : \u03b9\u2081 \u2192 Sort*} {\u03ba\u2082 : \u03b9\u2082 \u2192 Sort*}\n  {p : \u03a0 i\u2081, \u03ba\u2081 i\u2081 \u2192 \u03a0 i\u2082, \u03ba\u2082 i\u2082 \u2192 Prop} :\n  (\u2200 i\u2081 j\u2081 i\u2082 j\u2082, p i\u2081 j\u2081 i\u2082 j\u2082) \u2194 \u2200 i\u2082 j\u2082 i\u2081 j\u2081, p i\u2081 j\u2081 i\u2082 j\u2082 :=\n\u27e8swap\u2082, swap\u2082\u27e9\n\nlemma imp_forall_iff {\u03b1 : Type*} {p : Prop} {q : \u03b1 \u2192 Prop} : (p \u2192 \u2200 x, q x) \u2194 (\u2200 x, p \u2192 q x) :=\nforall_swap\n\ntheorem exists_swap {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 x y, p x y) \u2194 \u2203 y x, p x y :=\n\u27e8\u03bb \u27e8x, y, h\u27e9, \u27e8y, x, h\u27e9, \u03bb \u27e8y, x, h\u27e9, \u27e8x, y, h\u27e9\u27e9\n\n@[simp] theorem forall_exists_index {q : (\u2203 x, p x) \u2192 Prop} :\n  (\u2200 h, q h) \u2194 \u2200 x (h : p x), q \u27e8x, h\u27e9 :=\n\u27e8\u03bb h x hpx, h \u27e8x, hpx\u27e9, \u03bb h \u27e8x, hpx\u27e9, h x hpx\u27e9\n\ntheorem exists_imp_distrib : ((\u2203 x, p x) \u2192 b) \u2194 \u2200 x, p x \u2192 b :=\nforall_exists_index\n\n@[reducible] noncomputable def Exists.some {p : \u03b1 \u2192 Prop} (P : \u2203 a, p a) : \u03b1 := classical.some P\n\nlemma Exists.some_spec {p : \u03b1 \u2192 Prop} (P : \u2203 a, p a) : p (P.some) := classical.some_spec P\n\n\ntheorem not_exists_of_forall_not (h : \u2200 x, \u00ac p x) : \u00ac \u2203 x, p x :=\nexists_imp_distrib.2 h\n\n@[simp] theorem not_exists : (\u00ac \u2203 x, p x) \u2194 \u2200 x, \u00ac p x :=\nexists_imp_distrib\n\ntheorem not_forall_of_exists_not : (\u2203 x, \u00ac p x) \u2192 \u00ac \u2200 x, p x\n| \u27e8x, hn\u27e9 h := hn (h x)\n\nprotected theorem decidable.not_forall {p : \u03b1 \u2192 Prop}\n  [decidable (\u2203 x, \u00ac p x)] [\u2200 x, decidable (p x)] : (\u00ac \u2200 x, p x) \u2194 \u2203 x, \u00ac p x :=\n\u27e8not.decidable_imp_symm $ \u03bb nx x, nx.decidable_imp_symm $ \u03bb h, \u27e8x, h\u27e9, \nnot_forall_of_exists_not\u27e9\n\n@[simp] theorem not_forall {p : \u03b1 \u2192 Prop} : (\u00ac \u2200 x, p x) \u2194 \u2203 x, \u00ac p x := decidable.not_forall\n\nprotected theorem decidable.not_forall_not [decidable (\u2203 x, p x)] :\n  (\u00ac \u2200 x, \u00ac p x) \u2194 \u2203 x, p x :=\n(@decidable.not_iff_comm _ _ _ (decidable_of_iff (\u00ac \u2203 x, p x) not_exists)).1 not_exists\n\ntheorem not_forall_not : (\u00ac \u2200 x, \u00ac p x) \u2194 \u2203 x, p x := decidable.not_forall_not\n\nprotected theorem decidable.not_exists_not [\u2200 x, decidable (p x)] : (\u00ac \u2203 x, \u00ac p x) \u2194 \u2200 x, p x :=\nby simp [decidable.not_not]\n\n@[simp] theorem not_exists_not : (\u00ac \u2203 x, \u00ac p x) \u2194 \u2200 x, p x := decidable.not_exists_not\n\ntheorem forall_imp_iff_exists_imp [ha : nonempty \u03b1] : ((\u2200 x, p x) \u2192 b) \u2194 \u2203 x, p x \u2192 b :=\nlet \u27e8a\u27e9 := ha in\n\u27e8\u03bb h, not_forall_not.1 $ \u03bb h', classical.by_cases (\u03bb hb : b, h' a $ \u03bb _, hb)\n  (\u03bb hb, hb $ h $ \u03bb x, (not_imp.1 (h' x)).1), \u03bb \u27e8x, hx\u27e9 h, hx (h x)\u27e9\n\ntheorem forall_true_iff : (\u03b1 \u2192 true) \u2194 true :=\nimplies_true_iff \u03b1\n\ntheorem forall_true_iff' (h : \u2200 a, p a \u2194 true) : (\u2200 a, p a) \u2194 true :=\niff_true_intro (\u03bb _, of_iff_true (h _))\n\n@[simp] theorem forall_2_true_iff {\u03b2 : \u03b1 \u2192 Sort*} : (\u2200 a, \u03b2 a \u2192 true) \u2194 true :=\nforall_true_iff' $ \u03bb _, forall_true_iff\n\n@[simp] theorem forall_3_true_iff {\u03b2 : \u03b1 \u2192 Sort*} {\u03b3 : \u03a0 a, \u03b2 a \u2192 Sort*} :\n  (\u2200 a (b : \u03b2 a), \u03b3 a b \u2192 true) \u2194 true :=\nforall_true_iff' $ \u03bb _, forall_2_true_iff\n\nlemma exists_unique.exists {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} (h : \u2203! x, p x) : \u2203 x, p x :=\nexists.elim h (\u03bb x hx, \u27e8x, and.left hx\u27e9)\n\n@[simp] lemma exists_unique_iff_exists {\u03b1 : Sort*} [subsingleton \u03b1] {p : \u03b1 \u2192 Prop} :\n  (\u2203! x, p x) \u2194 \u2203 x, p x :=\n\u27e8\u03bb h, h.exists, Exists.imp $ \u03bb x hx, \u27e8hx, \u03bb y _, subsingleton.elim y x\u27e9\u27e9\n\n@[simp] theorem forall_const (\u03b1 : Sort*) [i : nonempty \u03b1] : (\u03b1 \u2192 b) \u2194 b :=\n\u27e8i.elim, \u03bb hb x, hb\u27e9\n\n@[simp] theorem exists_const (\u03b1 : Sort*) [i : nonempty \u03b1] : (\u2203 x : \u03b1, b) \u2194 b :=\n\u27e8\u03bb \u27e8x, h\u27e9, h, i.elim exists.intro\u27e9\n\ntheorem exists_unique_const (\u03b1 : Sort*) [i : nonempty \u03b1] [subsingleton \u03b1] :\n  (\u2203! x : \u03b1, b) \u2194 b :=\nby simp\n\ntheorem forall_and_distrib : (\u2200 x, p x \u2227 q x) \u2194 (\u2200 x, p x) \u2227 (\u2200 x, q x) :=\n\u27e8\u03bb h, \u27e8\u03bb x, (h x).left, \u03bb x, (h x).right\u27e9, \u03bb \u27e8h\u2081, h\u2082\u27e9 x, \u27e8h\u2081 x, h\u2082 x\u27e9\u27e9\n\ntheorem exists_or_distrib : (\u2203 x, p x \u2228 q x) \u2194 (\u2203 x, p x) \u2228 (\u2203 x, q x) :=\n\u27e8\u03bb \u27e8x, hpq\u27e9, hpq.elim (\u03bb hpx, or.inl \u27e8x, hpx\u27e9) (\u03bb hqx, or.inr \u27e8x, hqx\u27e9), \n\u03bb hepq, hepq.elim (\u03bb \u27e8x, hpx\u27e9, \u27e8x, or.inl hpx\u27e9) (\u03bb \u27e8x, hqx\u27e9, \u27e8x, or.inr hqx\u27e9)\u27e9\n\n@[simp] theorem exists_and_distrib_left {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2203x, q \u2227 p x) \u2194 q \u2227 (\u2203x, p x) :=\n\u27e8\u03bb \u27e8x, hq, hp\u27e9, \u27e8hq, x, hp\u27e9, \u03bb \u27e8hq, x, hp\u27e9, \u27e8x, hq, hp\u27e9\u27e9\n\n@[simp] theorem exists_and_distrib_right {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2203x, p x \u2227 q) \u2194 (\u2203x, p x) \u2227 q :=\nby simp [and_comm]\n\n@[simp] theorem forall_eq {a' : \u03b1} : (\u2200a, a = a' \u2192 p a) \u2194 p a' :=\n\u27e8\u03bb h, h a' rfl, \u03bb h a e, e.symm \u25b8 h\u27e9\n\n@[simp] theorem forall_eq' {a' : \u03b1} : (\u2200a, a' = a \u2192 p a) \u2194 p a' :=\nby simp [@eq_comm _ a']\n\ntheorem and_forall_ne (a : \u03b1) : (p a \u2227 \u2200 b \u2260 a, p b) \u2194 \u2200 b, p b :=\nby simp only [\u2190 @forall_eq _ p a, \u2190 forall_and_distrib, \u2190 or_imp_distrib, classical.em, \n  forall_const]\n\n@[simp] theorem forall_eq_or_imp {a' : \u03b1} : (\u2200 a, a = a' \u2228 q a \u2192 p a) \u2194 p a' \u2227 \u2200 a, q a \u2192 p a :=\nby simp only [or_imp_distrib, forall_and_distrib, forall_eq]\n\ntheorem exists_eq {a' : \u03b1} : \u2203 a, a = a' := \u27e8_, rfl\u27e9\n\n@[simp] theorem exists_eq' {a' : \u03b1} : \u2203 a, a' = a := \u27e8_, rfl\u27e9\n\n@[simp] theorem exists_unique_eq {a' : \u03b1} : \u2203! a, a = a' :=\nby simp only [eq_comm, exists_unique, and_self, forall_eq', exists_eq']\n\n@[simp] theorem exists_unique_eq' {a' : \u03b1} : \u2203! a, a' = a :=\nby simp only [exists_unique, and_self, forall_eq', exists_eq']\n\n@[simp] theorem exists_eq_left {a' : \u03b1} : (\u2203 a, a = a' \u2227 p a) \u2194 p a' :=\n\u27e8\u03bb \u27e8a, e, h\u27e9, e \u25b8 h, \u03bb h, \u27e8_, rfl, h\u27e9\u27e9\n\n@[simp] theorem exists_eq_right {a' : \u03b1} : (\u2203 a, p a \u2227 a = a') \u2194 p a' :=\n(exists_congr $ by exact \u03bb a, and.comm).trans exists_eq_left\n\n@[simp] theorem exists_eq_right_right {a' : \u03b1} :\n  (\u2203 (a : \u03b1), p a \u2227 q a \u2227 a = a') \u2194 p a' \u2227 q a' :=\n\u27e8\u03bb \u27e8_, hp, hq, rfl\u27e9, \u27e8hp, hq\u27e9, \u03bb \u27e8hp, hq\u27e9, \u27e8a', hp, hq, rfl\u27e9\u27e9\n\n@[simp] theorem exists_eq_right_right' {a' : \u03b1} :\n  (\u2203 (a : \u03b1), p a \u2227 q a \u2227 a' = a) \u2194 p a' \u2227 q a' :=\n\u27e8\u03bb \u27e8_, hp, hq, rfl\u27e9, \u27e8hp, hq\u27e9, \u03bb \u27e8hp, hq\u27e9, \u27e8a', hp, hq, rfl\u27e9\u27e9\n\n@[simp] theorem exists_apply_eq_apply (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) : \u2203 a, f a = f a' := \u27e8a', rfl\u27e9\n\n@[simp] theorem exists_apply_eq_apply' (f : \u03b1 \u2192 \u03b2) (a' : \u03b1) : \u2203 a, f a' = f a := \u27e8a', rfl\u27e9\n\n@[simp] theorem exists_exists_and_eq_and {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} :\n  (\u2203 b, (\u2203 a, p a \u2227 f a = b) \u2227 q b) \u2194 \u2203 a, p a \u2227 q (f a) :=\n\u27e8\u03bb \u27e8b, \u27e8a, ha, hab\u27e9, hb\u27e9, \u27e8a, ha, hab.symm \u25b8 hb\u27e9, \u03bb \u27e8a, hp, hq\u27e9, \u27e8f a, \u27e8a, hp, rfl\u27e9, hq\u27e9\u27e9\n\n@[simp] theorem exists_exists_eq_and {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2203 b, (\u2203 a, f a = b) \u2227 p b) \u2194 \u2203 a, p (f a) :=\n\u27e8\u03bb \u27e8b, \u27e8a, ha\u27e9, hb\u27e9, \u27e8a, ha.symm \u25b8 hb\u27e9, \u03bb \u27e8a, ha\u27e9, \u27e8f a, \u27e8a, rfl\u27e9, ha\u27e9\u27e9\n\n@[simp] lemma exists_or_eq_left (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), x = y \u2228 p x :=\n\u27e8y, or.inl rfl\u27e9\n\n@[simp] lemma exists_or_eq_right (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), p x \u2228 x = y :=\n\u27e8y, or.inr rfl\u27e9\n\n@[simp] lemma exists_or_eq_left' (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), y = x \u2228 p x :=\n\u27e8y, or.inl rfl\u27e9\n\n@[simp] lemma exists_or_eq_right' (y : \u03b1) (p : \u03b1 \u2192 Prop) : \u2203 (x : \u03b1), p x \u2228 y = x :=\n\u27e8y, or.inr rfl\u27e9\n\n@[simp] theorem forall_apply_eq_imp_iff {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 a, \u2200 b, f a = b \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\n\u27e8\u03bb h a, h a (f a) rfl, \u03bb h a b hab, hab \u25b8 h a\u27e9\n\n@[simp] theorem forall_apply_eq_imp_iff' {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 b, \u2200 a, f a = b \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\nby { rw forall_swap, simp }\n\n@[simp] theorem forall_eq_apply_imp_iff {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 a, \u2200 b, b = f a \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\nby simp [@eq_comm _ _ (f _)]\n\n@[simp] theorem forall_eq_apply_imp_iff' {f : \u03b1 \u2192 \u03b2} {p : \u03b2 \u2192 Prop} :\n  (\u2200 b, \u2200 a, b = f a \u2192 p b) \u2194 (\u2200 a, p (f a)) :=\nby { rw forall_swap, simp }\n\n@[simp] theorem forall_apply_eq_imp_iff\u2082 {f : \u03b1 \u2192 \u03b2} {p : \u03b1 \u2192 Prop} {q : \u03b2 \u2192 Prop} :\n  (\u2200 b, \u2200 a, p a \u2192 f a = b \u2192 q b) \u2194 \u2200 a, p a \u2192 q (f a) :=\n\u27e8\u03bb h a ha, h (f a) a ha rfl, \u03bb h b a ha hb, hb \u25b8 h a ha\u27e9\n\n@[simp] theorem exists_eq_left' {a' : \u03b1} : (\u2203 a, a' = a \u2227 p a) \u2194 p a' :=\nby simp [@eq_comm _ a']\n\n@[simp] theorem exists_eq_right' {a' : \u03b1} : (\u2203 a, p a \u2227 a' = a) \u2194 p a' :=\nby simp [@eq_comm _ a']\n\ntheorem exists_comm {p : \u03b1 \u2192 \u03b2 \u2192 Prop} : (\u2203 a b, p a b) \u2194 \u2203 b a, p a b :=\n\u27e8\u03bb \u27e8a, b, h\u27e9, \u27e8b, a, h\u27e9, \u03bb \u27e8b, a, h\u27e9, \u27e8a, b, h\u27e9\u27e9\n\nlemma exists\u2082_comm {\u03b9\u2081 \u03b9\u2082 : Sort*} {\u03ba\u2081 : \u03b9\u2081 \u2192 Sort*} {\u03ba\u2082 : \u03b9\u2082 \u2192 Sort*}\n  {p : \u03a0 i\u2081, \u03ba\u2081 i\u2081 \u2192 \u03a0 i\u2082, \u03ba\u2082 i\u2082 \u2192 Prop} :\n  (\u2203 i\u2081 j\u2081 i\u2082 j\u2082, p i\u2081 j\u2081 i\u2082 j\u2082) \u2194 \u2203 i\u2082 j\u2082 i\u2081 j\u2081, p i\u2081 j\u2081 i\u2082 j\u2082 :=\nby simp only [@exists_comm (\u03ba\u2081 _), @exists_comm \u03b9\u2081]\n\ntheorem and.exists {p q : Prop} {f : p \u2227 q \u2192 Prop} : (\u2203 h, f h) \u2194 \u2203 hp hq, f \u27e8hp, hq\u27e9 :=\n\u27e8\u03bb \u27e8h, H\u27e9, \u27e8h.1, h.2, H\u27e9, \u03bb \u27e8hp, hq, H\u27e9, \u27e8\u27e8hp, hq\u27e9, H\u27e9\u27e9\n\ntheorem forall_or_of_or_forall (h : b \u2228 \u2200x, p x) (x) : b \u2228 p x :=\nh.imp_right $ \u03bb h\u2082, h\u2082 x\n\nprotected theorem decidable.forall_or_distrib_left {q : Prop} {p : \u03b1 \u2192 Prop} [decidable q] :\n  (\u2200x, q \u2228 p x) \u2194 q \u2228 (\u2200x, p x) :=\n\u27e8\u03bb h, if hq : q then or.inl hq else or.inr $ \u03bb x, (h x).resolve_left hq, \n  forall_or_of_or_forall\u27e9\n\ntheorem forall_or_distrib_left {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2200x, q \u2228 p x) \u2194 q \u2228 (\u2200x, p x) := decidable.forall_or_distrib_left\n\nprotected theorem decidable.forall_or_distrib_right {q : Prop} {p : \u03b1 \u2192 Prop} [decidable q] :\n  (\u2200x, p x \u2228 q) \u2194 (\u2200x, p x) \u2228 q :=\nby simp [or_comm, decidable.forall_or_distrib_left]\n\ntheorem forall_or_distrib_right {q : Prop} {p : \u03b1 \u2192 Prop} :\n  (\u2200x, p x \u2228 q) \u2194 (\u2200x, p x) \u2228 q := decidable.forall_or_distrib_right\n\n@[simp] theorem exists_prop {p q : Prop} : (\u2203 h : p, q) \u2194 p \u2227 q :=\n\u27e8\u03bb \u27e8h\u2081, h\u2082\u27e9, \u27e8h\u2081, h\u2082\u27e9, \u03bb \u27e8h\u2081, h\u2082\u27e9, \u27e8h\u2081, h\u2082\u27e9\u27e9\n\ntheorem exists_unique_prop {p q : Prop} : (\u2203! h : p, q) \u2194 p \u2227 q :=\nby simp\n\n@[simp] theorem exists_false : \u00ac (\u2203a:\u03b1, false) := assume \u27e8a, h\u27e9, h\n\n@[simp] lemma exists_unique_false : \u00ac (\u2203! (a : \u03b1), false) := assume \u27e8a, h, h'\u27e9, h\n\ntheorem Exists.fst {p : b \u2192 Prop} : Exists p \u2192 b\n| \u27e8h, _\u27e9 := h\n\ntheorem Exists.snd {p : b \u2192 Prop} : \u2200 h : Exists p, p h.fst\n| \u27e8_, h\u27e9 := h\n\ntheorem forall_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2200 h' : p, q h') \u2194 q h :=\n@forall_const (q h) p \u27e8h\u27e9\n\ntheorem exists_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2203 h' : p, q h') \u2194 q h :=\n@exists_const (q h) p \u27e8h\u27e9\n\nlemma exists_iff_of_forall {p : Prop} {q : p \u2192 Prop} (h : \u2200 h, q h) : (\u2203 h, q h) \u2194 p :=\n\u27e8Exists.fst, \u03bb H, \u27e8H, h H\u27e9\u27e9\n\ntheorem exists_unique_prop_of_true {p : Prop} {q : p \u2192 Prop} (h : p) : (\u2203! h' : p, q h') \u2194 q h :=\n@exists_unique_const (q h) p \u27e8h\u27e9 _\n\ntheorem forall_prop_of_false {p : Prop} {q : p \u2192 Prop} (hn : \u00ac p) :\n  (\u2200 h' : p, q h') \u2194 true :=\niff_true_intro $ \u03bb h, hn.elim h\n\ntheorem exists_prop_of_false {p : Prop} {q : p \u2192 Prop} : \u00ac p \u2192 \u00ac (\u2203 h' : p, q h') :=\nmt Exists.fst\n\n@[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : Exists q \u2194 \u2203 h : p', q' (hp.2 h) :=\n\u27e8\u03bb \u27e8_, _\u27e9, \u27e8hp.1 \u2039_\u203a, (hq _).1 \u2039_\u203a\u27e9, \u03bb \u27e8_, _\u27e9, \u27e8_, (hq _).2 \u2039_\u203a\u27e9\u27e9\n\n@[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : Exists q = \u2203 h : p', q' (hp.2 h) :=\npropext (exists_prop_congr hq _)\n\n@[simp] lemma exists_true_left (p : true \u2192 Prop) : (\u2203 x, p x) \u2194 p true.intro :=\nexists_prop_of_true _\n\n@[simp] lemma exists_false_left (p : false \u2192 Prop) : \u00ac \u2203 x, p x :=\nexists_prop_of_false not_false\n\nlemma exists_unique.unique {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} (h : \u2203! x, p x)\n  {y\u2081 y\u2082 : \u03b1} (py\u2081 : p y\u2081) (py\u2082 : p y\u2082) : y\u2081 = y\u2082 :=\nunique_of_exists_unique h py\u2081 py\u2082\n\n@[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : (\u2200 h, q h) \u2194 \u2200 h : p', q' (hp.2 h) :=\n\u27e8\u03bb h1 h2, (hq _).1 (h1 (hp.2 _)), \u03bb h1 h2, (hq _).2 (h1 (hp.1 h2))\u27e9\n\n@[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p \u2192 Prop}\n  (hq : \u2200 h, q h \u2194 q' h) (hp : p \u2194 p') : (\u2200 h, q h) = \u2200 h : p', q' (hp.2 h) :=\npropext (forall_prop_congr hq _)\n\n@[simp] lemma forall_true_left (p : true \u2192 Prop) : (\u2200 x, p x) \u2194 p true.intro :=\nforall_prop_of_true _\n\n@[simp] lemma forall_false_left (p : false \u2192 Prop) : (\u2200 x, p x) \u2194 true :=\nforall_prop_of_false not_false\n\nlemma exists_unique.elim2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} [\u2200 x, subsingleton (p x)]\n  {q : \u03a0 x (h : p x), Prop} {b : Prop} (h\u2082 : \u2203! x (h : p x), q x h)\n  (h\u2081 : \u2200 x (h : p x), q x h \u2192 (\u2200 y (hy : p y), q y hy \u2192 y = x) \u2192 b) : b :=\nbegin\n  simp only [exists_unique_iff_exists] at h\u2082, \n  apply h\u2082.elim, \n  exact \u03bb x \u27e8hxp, hxq\u27e9 H, h\u2081 x hxp hxq (\u03bb y hyp hyq, H y \u27e8hyp, hyq\u27e9)\nend\n\nlemma exists_unique.intro2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} [\u2200 x, subsingleton (p x)]\n  {q : \u03a0 (x : \u03b1) (h : p x), Prop} (w : \u03b1) (hp : p w) (hq : q w hp)\n  (H : \u2200 y (hy : p y), q y hy \u2192 y = w) :\n  \u2203! x (hx : p x), q x hx :=\nbegin\n  simp only [exists_unique_iff_exists], \n  exact exists_unique.intro w \u27e8hp, hq\u27e9 (\u03bb y \u27e8hyp, hyq\u27e9, H y hyp hyq)\nend\n\nlemma exists_unique.exists2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} {q : \u03a0 (x : \u03b1) (h : p x), Prop}\n  (h : \u2203! x (hx : p x), q x hx) :\n  \u2203 x (hx : p x), q x hx :=\nh.exists.imp (\u03bb x hx, hx.exists)\n\nlemma exists_unique.unique2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Sort*} [\u2200 x, subsingleton (p x)]\n  {q : \u03a0 (x : \u03b1) (hx : p x), Prop} (h : \u2203! x (hx : p x), q x hx)\n  {y\u2081 y\u2082 : \u03b1} (hpy\u2081 : p y\u2081) (hqy\u2081 : q y\u2081 hpy\u2081)\n  (hpy\u2082 : p y\u2082) (hqy\u2082 : q y\u2082 hpy\u2082) : y\u2081 = y\u2082 :=\nbegin\n  simp only [exists_unique_iff_exists] at h, \n  exact h.unique \u27e8hpy\u2081, hqy\u2081\u27e9 \u27e8hpy\u2082, hqy\u2082\u27e9\nend\n\nend quantifiers\n\n\nnamespace classical\nvariables {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop}\n\ntheorem cases {p : Prop \u2192 Prop} (h1 : p true) (h2 : p false) : \u2200a, p a :=\nassume a, cases_on a h1 h2\n\nnoncomputable def dec (p : Prop) : decidable p :=\nby apply_instance\nnoncomputable def dec_pred (p : \u03b1 \u2192 Prop) : decidable_pred p :=\nby apply_instance\nnoncomputable def dec_rel (p : \u03b1 \u2192 \u03b1 \u2192 Prop) : decidable_rel p :=\nby apply_instance\nnoncomputable def dec_eq (\u03b1 : Sort*) : decidable_eq \u03b1 :=\nby apply_instance\n\n@[elab_as_eliminator]\nnoncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : \u2200 a, p a \u2192 C) : C :=\nif h : \u2203 a, p a then H (classical.some h) (classical.some_spec h) else H0\n\nlemma some_spec2 {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} {h : \u2203a, p a}\n  (q : \u03b1 \u2192 Prop) (hpq : \u2200a, p a \u2192 q a) : q (some h) :=\nhpq _ $ some_spec _\n\nnoncomputable def subtype_of_exists {\u03b1 : Type*} {P : \u03b1 \u2192 Prop} (h : \u2203 x, P x) : {x // P x} :=\n\u27e8classical.some h, classical.some_spec h\u27e9\n\nprotected noncomputable def by_contradiction' {\u03b1 : Sort*} (H : \u00ac (\u03b1 \u2192 false)) : \u03b1 :=\nclassical.choice $ peirce _ false $ \u03bb h, (H $ \u03bb a, h \u27e8a\u27e9).elim\n\ndef choice_of_by_contradiction' {\u03b1 : Sort*} (contra : \u00ac (\u03b1 \u2192 false) \u2192 \u03b1) : nonempty \u03b1 \u2192 \u03b1 :=\n\u03bb H, contra H.elim\n\nend classical\n\n@[elab_as_eliminator]\nnoncomputable def {u} exists.classical_rec_on\n{\u03b1} {p : \u03b1 \u2192 Prop} (h : \u2203 a, p a) {C : Sort u} (H : \u2200 a, p a \u2192 C) : C :=\nH (classical.some h) (classical.some_spec h)\n\n\nsection bounded_quantifiers\nvariables {\u03b1 : Sort*} {r p q : \u03b1 \u2192 Prop} {P Q : \u2200 x, p x \u2192 Prop} {b : Prop}\n\ntheorem bex_def : (\u2203 x (h : p x), q x) \u2194 \u2203 x, p x \u2227 q x :=\n\u27e8\u03bb \u27e8x, px, qx\u27e9, \u27e8x, px, qx\u27e9, \u03bb \u27e8x, px, qx\u27e9, \u27e8x, px, qx\u27e9\u27e9\n\ntheorem bex.elim {b : Prop} : (\u2203 x h, P x h) \u2192 (\u2200 a h, P a h \u2192 b) \u2192 b\n| \u27e8a, h\u2081, h\u2082\u27e9 h' := h' a h\u2081 h\u2082\n\ntheorem bex.intro (a : \u03b1) (h\u2081 : p a) (h\u2082 : P a h\u2081) : \u2203 x (h : p x), P x h :=\n\u27e8a, h\u2081, h\u2082\u27e9\n\ntheorem ball_congr (H : \u2200 x h, P x h \u2194 Q x h) :\n  (\u2200 x h, P x h) \u2194 (\u2200 x h, Q x h) :=\nforall_congr $ \u03bb x, forall_congr (H x)\n\ntheorem bex_congr (H : \u2200 x h, P x h \u2194 Q x h) :\n  (\u2203 x h, P x h) \u2194 (\u2203 x h, Q x h) :=\nexists_congr $ \u03bb x, exists_congr (H x)\n\ntheorem bex_eq_left {a : \u03b1} : (\u2203 x (_ : x = a), p x) \u2194 p a :=\nby simp only [exists_prop, exists_eq_left]\n\ntheorem ball.imp_right (H : \u2200 x h, (P x h \u2192 Q x h))\n  (h\u2081 : \u2200 x h, P x h) (x h) : Q x h :=\nH _ _ $ h\u2081 _ _\n\ntheorem bex.imp_right (H : \u2200 x h, (P x h \u2192 Q x h)) :\n  (\u2203 x h, P x h) \u2192 \u2203 x h, Q x h\n| \u27e8x, h, h'\u27e9 := \u27e8_, _, H _ _ h'\u27e9\n\ntheorem ball.imp_left (H : \u2200 x, p x \u2192 q x)\n  (h\u2081 : \u2200 x, q x \u2192 r x) (x) (h : p x) : r x :=\nh\u2081 _ $ H _ h\n\ntheorem bex.imp_left (H : \u2200 x, p x \u2192 q x) :\n  (\u2203 x (_ : p x), r x) \u2192 \u2203 x (_ : q x), r x\n| \u27e8x, hp, hr\u27e9 := \u27e8x, H _ hp, hr\u27e9\n\ntheorem ball_of_forall (h : \u2200 x, p x) (x) : p x :=\nh x\n\ntheorem forall_of_ball (H : \u2200 x, p x) (h : \u2200 x, p x \u2192 q x) (x) : q x :=\nh x $ H x\n\ntheorem bex_of_exists (H : \u2200 x, p x) : (\u2203 x, q x) \u2192 \u2203 x (_ : p x), q x\n| \u27e8x, hq\u27e9 := \u27e8x, H x, hq\u27e9\n\ntheorem exists_of_bex : (\u2203 x (_ : p x), q x) \u2192 \u2203 x, q x\n| \u27e8x, _, hq\u27e9 := \u27e8x, hq\u27e9\n\n@[simp] theorem bex_imp_distrib : ((\u2203 x h, P x h) \u2192 b) \u2194 (\u2200 x h, P x h \u2192 b) :=\nby simp\n\ntheorem not_bex : (\u00ac \u2203 x h, P x h) \u2194 \u2200 x h, \u00ac P x h :=\nbex_imp_distrib\n\ntheorem not_ball_of_bex_not : (\u2203 x h, \u00ac P x h) \u2192 \u00ac \u2200 x h, P x h\n| \u27e8x, h, hp\u27e9 al := hp $ al x h\n\nprotected theorem decidable.not_ball [decidable (\u2203 x h, \u00ac P x h)] [\u2200 x h, decidable (P x h)] :\n  (\u00ac \u2200 x h, P x h) \u2194 (\u2203 x h, \u00ac P x h) :=\n\u27e8not.decidable_imp_symm $ \u03bb nx x h, nx.decidable_imp_symm $ \u03bb h', \u27e8x, h, h'\u27e9, \nnot_ball_of_bex_not\u27e9\n\ntheorem not_ball : (\u00ac \u2200 x h, P x h) \u2194 (\u2203 x h, \u00ac P x h) := decidable.not_ball\n\ntheorem ball_true_iff (p : \u03b1 \u2192 Prop) : (\u2200 x, p x \u2192 true) \u2194 true :=\niff_true_intro (\u03bb h hrx, trivial)\n\ntheorem ball_and_distrib : (\u2200 x h, P x h \u2227 Q x h) \u2194 (\u2200 x h, P x h) \u2227 (\u2200 x h, Q x h) :=\niff.trans (forall_congr $ \u03bb x, forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib : (\u2203 x h, P x h \u2228 Q x h) \u2194 (\u2203 x h, P x h) \u2228 (\u2203 x h, Q x h) :=\niff.trans (exists_congr $ \u03bb x, exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib : (\u2200 x, p x \u2228 q x \u2192 r x) \u2194 (\u2200 x, p x \u2192 r x) \u2227 (\u2200 x, q x \u2192 r x) :=\niff.trans (forall_congr $ \u03bb x, or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib :\n  (\u2203 x (_ : p x \u2228 q x), r x) \u2194 (\u2203 x (_ : p x), r x) \u2228 (\u2203 x (_ : q x), r x) :=\nby simp only [exists_prop]; exact\niff.trans (exists_congr $ \u03bb x, or_and_distrib_right) exists_or_distrib\n\nend bounded_quantifiers\n\nnamespace classical\nlocal attribute [instance] prop_decidable\n\ntheorem not_ball {\u03b1 : Sort*} {p : \u03b1 \u2192 Prop} {P : \u03a0 (x : \u03b1), p x \u2192 Prop} :\n  (\u00ac \u2200 x h, P x h) \u2194 (\u2203 x h, \u00ac P x h) := _root_.not_ball\n\nend classical\n\nsection ite\nvariables {\u03b1 \u03b2 \u03b3 : Sort*} {\u03c3 : \u03b1 \u2192 Sort*} (f : \u03b1 \u2192 \u03b2) {P Q : Prop} [decidable P] [decidable Q]\n  {a b c : \u03b1} {A : P \u2192 \u03b1} {B : \u00ac P \u2192 \u03b1}\n\nlemma dite_eq_iff : dite P A B = c \u2194 (\u2203 h, A h = c) \u2228 \u2203 h, B h = c := by by_cases P; simp *\nlemma ite_eq_iff : ite P a b = c \u2194 P \u2227 a = c \u2228 \u00ac P \u2227 b = c :=\ndite_eq_iff.trans $ by rw [exists_prop, exists_prop]\n\n@[simp] lemma dite_eq_left_iff : dite P (\u03bb _, a) B = a \u2194 \u2200 h, B h = a := by by_cases P; simp *\n@[simp] lemma dite_eq_right_iff : dite P A (\u03bb _, b) = b \u2194 \u2200 h, A h = b := by by_cases P; simp *\n@[simp] lemma ite_eq_left_iff : ite P a b = a \u2194 (\u00ac P \u2192 b = a) := dite_eq_left_iff\n@[simp] lemma ite_eq_right_iff : ite P a b = b \u2194 (P \u2192 a = b) := dite_eq_right_iff\n\nlemma dite_ne_left_iff : dite P (\u03bb _, a) B \u2260 a \u2194 \u2203 h, a \u2260 B h :=\nby { rw [ne.def, dite_eq_left_iff, not_forall], exact exists_congr (\u03bb h, by rw ne_comm) }\n\nlemma dite_ne_right_iff : dite P A (\u03bb _, b) \u2260 b \u2194 \u2203 h, A h \u2260 b :=\nby simp only [ne.def, dite_eq_right_iff, not_forall]\n\nlemma ite_ne_left_iff : ite P a b \u2260 a \u2194 \u00ac P \u2227 a \u2260 b := dite_ne_left_iff.trans $ by rw exists_prop\nlemma ite_ne_right_iff : ite P a b \u2260 b \u2194 P \u2227 a \u2260 b := dite_ne_right_iff.trans $ by rw exists_prop\n\nprotected lemma ne.dite_eq_left_iff (h : \u2200 h, a \u2260 B h) : dite P (\u03bb _, a) B = a \u2194 P :=\ndite_eq_left_iff.trans $ \u27e8\u03bb H, of_not_not $ \u03bb h', h h' (H h').symm, \u03bb h H, (H h).elim\u27e9\n\nprotected lemma ne.dite_eq_right_iff (h : \u2200 h, A h \u2260 b) : dite P A (\u03bb _, b) = b \u2194 \u00ac P :=\ndite_eq_right_iff.trans $ \u27e8\u03bb H h', h h' (H h'), \u03bb h' H, (h' H).elim\u27e9\n\nprotected lemma ne.ite_eq_left_iff (h : a \u2260 b) : ite P a b = a \u2194 P := ne.dite_eq_left_iff $ \u03bb _, h\nprotected lemma ne.ite_eq_right_iff (h : a \u2260 b) : ite P a b = b \u2194 \u00ac P :=\nne.dite_eq_right_iff $ \u03bb _, h\n\nprotected lemma ne.dite_ne_left_iff (h : \u2200 h, a \u2260 B h) : dite P (\u03bb _, a) B \u2260 a \u2194 \u00ac P :=\ndite_ne_left_iff.trans $ exists_iff_of_forall h\n\nprotected lemma ne.dite_ne_right_iff (h : \u2200 h, A h \u2260 b) : dite P A (\u03bb _, b) \u2260 b \u2194 P :=\ndite_ne_right_iff.trans $ exists_iff_of_forall h\n\nprotected lemma ne.ite_ne_left_iff (h : a \u2260 b) : ite P a b \u2260 a \u2194 \u00ac P := ne.dite_ne_left_iff $ \u03bb _, h\n\nprotected lemma ne.ite_ne_right_iff (h : a \u2260 b) : ite P a b \u2260 b \u2194 P := ne.dite_ne_right_iff $ \u03bb _, h\n\nvariables (P Q) (a b)\n\n@[simp] lemma dite_eq_ite : dite P (\u03bb h, a) (\u03bb h, b) = ite P a b := rfl\n\nlemma dite_eq_or_eq : (\u2203 h, dite P A B = A h) \u2228 \u2203 h, dite P A B = B h :=\ndecidable.by_cases (\u03bb h, or.inl \u27e8h, dif_pos h\u27e9) (\u03bb h, or.inr \u27e8h, dif_neg h\u27e9)\n\nlemma ite_eq_or_eq : ite P a b = a \u2228 ite P a b = b :=\ndecidable.by_cases (\u03bb h, or.inl (if_pos h)) (\u03bb h, or.inr (if_neg h))\n\nlemma apply_dite (x : P \u2192 \u03b1) (y : \u00acP \u2192 \u03b1) : f (dite P x y) = dite P (\u03bb h, f (x h)) (\u03bb h, f (y h)) :=\nby by_cases h : P; simp [h]\n\nlemma apply_ite : f (ite P a b) = ite P (f a) (f b) := apply_dite f P (\u03bb _, a) (\u03bb _, b)\n\nlemma apply_dite2 (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop) [decidable P] (a : P \u2192 \u03b1) (b : \u00acP \u2192 \u03b1) (c : P \u2192 \u03b2)\n  (d : \u00acP \u2192 \u03b2) :\n  f (dite P a b) (dite P c d) = dite P (\u03bb h, f (a h) (c h)) (\u03bb h, f (b h) (d h)) :=\nby by_cases h : P; simp [h]\n\nlemma apply_ite2 (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (P : Prop) [decidable P] (a b : \u03b1) (c d : \u03b2) :\n  f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=\napply_dite2 f P (\u03bb _, a) (\u03bb _, b) (\u03bb _, c) (\u03bb _, d)\n\nlemma dite_apply (f : P \u2192 \u03a0 a, \u03c3 a) (g : \u00ac P \u2192 \u03a0 a, \u03c3 a) (a : \u03b1) :\n  (dite P f g) a = dite P (\u03bb h, f h a) (\u03bb h, g h a) :=\nby by_cases h : P; simp [h]\n\nlemma ite_apply (f g : \u03a0 a, \u03c3 a) (a : \u03b1) : (ite P f g) a = ite P (f a) (g a) :=\ndite_apply P (\u03bb _, f) (\u03bb _, g) a\n\n@[simp] lemma dite_not (x : \u00ac P \u2192 \u03b1) (y : \u00ac\u00ac P \u2192 \u03b1) :\n  dite (\u00ac P) x y = dite P (\u03bb h, y (not_not_intro h)) x :=\nby by_cases h : P; simp [h]\n\n@[simp] lemma ite_not : ite (\u00ac P) a b = ite P b a := dite_not P (\u03bb _, a) (\u03bb _, b)\n\nlemma ite_and : ite (P \u2227 Q) a b = ite P (ite Q a b) b :=\nby by_cases hp : P; by_cases hq : Q; simp [hp, hq]\n\nend ", "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/simple_tokenizer/out.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370636758849894, "lm_q2_score": 0.04336579412757391, "lm_q1q2_score": 0.010134862223145956}}
{"text": "/-\nimport Std.Data.HashSet\nimport Std.Data.AssocList\n/-\nTODO: \u30b9\u30c6\u30c3\u30d7\u306e\u9032\u884c\u6642\u306b\u8a98\u767a\u578b\u80fd\u529b\u306e\u8a98\u767a\u3092\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\uff0e\n\u7f6e\u63db\u578b\u80fd\u529b\u3092\u53d6\u308a\u6271\u3046\u305f\u3081\uff0cevent\u30ad\u30e5\u30fc\u3092\u7528\u610f\u3057\uff0c\u30b2\u30fc\u30e0\u5185\u306e\u884c\u52d5\u306f\u4e00\u65e6\u3053\u306e\u30ad\u30e5\u30fc\u306b\u30a8\u30f3\u30ad\u30e5\u30fc\u3055\u308c\u308b\uff0e\n  \u7f6e\u63db\u578b\u80fd\u529b\u306f\u7f6e\u63db\u3059\u308b\u30a4\u30d9\u30f3\u30c8\u3068\u7f6e\u63db\u5f8c\u306e\u30a4\u30d9\u30f3\u30c8\u3067\u8868\u3055\u308c\u308b\uff0e\n  \u3042\u308b\u72b6\u614b\u3067\u306e\u7f6e\u63db\u578b\u80fd\u529b\u306e\u96c6\u5408\u3092\u7528\u610f\u3057\u3066\u304a\u304d\uff0cevent\u30ad\u30e5\u30fc\u306e\u5148\u7aef\u306e\u30a4\u30d9\u30f3\u30c8\u3067\u305d\u306e\u96c6\u5408\u306bfilter\u3057\u5bfe\u5fdc\u3059\u308b\u7f6e\u63db\u578b\u80fd\u529b\u3092\u9069\u7528\u3059\u308b\n  \u7f6e\u63db\u578b\u80fd\u529b\u306b\u7f6e\u63db\u3059\u308b\u512a\u5148\u5ea6\u3092\u5b9a\u7fa9\u3059\u308b\u304c\uff0c\u540c\u3058\u5834\u5408\u306f\u3053\u3053\u306b\u30e6\u30fc\u30b6\u30fc\u306e\u9078\u629e\u304c\u5165\u308b\n  \u300c\u7981\u6b62\u3059\u308b\u300d\u52b9\u679c\u306f\u300c\u4f55\u3082\u3057\u306a\u3044\u300d\u306b\u7f6e\u63db\u3059\u308b\u7f6e\u63db\u578b\u52b9\u679c\u3068\u3057\u3066\u6271\u3044\uff0c\u6700\u3082\u9ad8\u3044\u512a\u5148\u5ea6\u3092\u6301\u3064\uff0e\n\u30b9\u30c6\u30c3\u30d7\u3092\u958b\u59cb\u3059\u308b\u3068\u304d\u306e\u7f6e\u63db\u578b\u80fd\u529b\u3068\u8a98\u767a\u578b\u80fd\u529b\u3092\u3069\u3046\u3059\u308b\u304b\u6c7a\u3081\u3066\u306a\u3044\u306d\n\u30eb\u30fc\u30d7\u306e\u6271\u3044\n  \u3042\u308b\u72b6\u614b\u3067\u3042\u308b\u884c\u52d5\u3092\u3057\u305f\u3068\u304d\u306b\u4f55\u3089\u304b\u306e\u80fd\u529b\uff08\u7fa4\uff09\u304c\u751f\u6210\u3055\u308c\uff0c\u30e6\u30fc\u30b6\u304c\u884c\u52d5\u3059\u308b\u524d\u306b\u540c\u3058\u80fd\u529b\u304c\u6709\u9650\u500b\u306e\u9055\u3044\u3092\u9664\u3044\u305f\u72b6\u614bs1\u3068s2\u3067\u751f\u6210\u3055\u308c\u305f\u3068\u304d\uff0c\u7121\u9650\u30eb\u30fc\u30d7\u3068\u3059\u308b\uff0e\n  \u2191\u306b\u52a0\u3048\u3066\u30e6\u30fc\u30b6\u306e\u884c\u52d5\u304c\u5165\u308b\u5834\u5408\uff0c\u300c\u524d\u56de\u3068\u540c\u3058\u884c\u52d5\u3092\u3059\u308b\u300d\u3068\u3044\u3046\u524d\u63d0\u3092\u52a0\u3048\u308c\u3070\u7121\u9650\u30eb\u30fc\u30d7\u306b\u306a\u308b\u3068\u304d\uff0c\u30eb\u30fc\u30d7\u3068\u3059\u308b\uff0e\n  \u30eb\u30fc\u30d7\u304c\u5b58\u5728\u3059\u308b\u3068\u304d\uff0c\u6709\u9650\u56de\u5f8c\u306b\u30e6\u30fc\u30b6\u306e\u884c\u52d5\u3092\u5909\u5316\u3055\u305b\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\uff0e\n  \u57fa\u672c\u7684\u306b\u80fd\u529b\u306f\u5f37\u5236\u52b9\u679c\u300c\u301c\u3059\u308b\u300d\u3067\u3042\u308a\uff0c\u7121\u9650\u30eb\u30fc\u30d7\u306b\u306a\u308b\u3068\u304d\u306b\u9650\u308a\u3057\u306a\u3044\u3053\u3068\u3092\u9078\u629e\u3067\u304d\u308b\uff0e\n  \u4efb\u610f\u52b9\u679c\u300c\u3057\u3066\u3082\u3088\u3044\u300d\u304c\u30eb\u30fc\u30d7\u3092\u5f62\u6210\u3059\u308b\u5834\u5408\uff0c\u2191\u306b\u6e96\u305a\u308b\uff0e\n  \u30eb\u30fc\u30d7\u3092\u5f62\u6210\u3059\u308b\u5834\u5408\uff0c\u6709\u9650\u500b\u306e\u9055\u3044\u3092\u5909\u6570\u5316\u3057\u3066\u4e00\u6c17\u306b\u51e6\u7406\u3057\u305f\u3044\u304c\u53b3\u3057\u305d\u3046\n-/\ninductive Player: Type\n| player\u2081\n| player\u2082\n| player\u2083\n| player\u2084\nderiving DecidableEq\nopen Player\ninstance : Inhabited Player where default := player\u2081\ndef NextPlayerType := \u2203f: Player \u2192 Player, \u2200p: Player, \u00acf p = p\ndef NextPlayerType.default: NextPlayerType := by {\n  let f \n  | player\u2081 => player\u2082\n  | player\u2082 => player\u2083\n  | player\u2083 => player\u2084\n  | player\u2084 => player\u2081\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 \u2192 Nat\n| player\u2081 => 0\n| player\u2082 => 1\n| player\u2083 => 2\n| player\u2084 => 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\u2081 true\n      |> Std.AssocList.cons player\u2082 true\n      |> Std.AssocList.cons player\u2083 true\n      |> Std.AssocList.cons player\u2084 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\u2081: PlayerState\n  p\u2082: PlayerState\n  p\u2083: PlayerState\n  p\u2084: PlayerState\ndef PlayerStateStore.default: PlayerStateStore := {\n  p\u2081:= PlayerState.default, \n  p\u2082:= PlayerState.default,\n  p\u2083:= PlayerState.default,\n  p\u2084:= 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\u2081 => {st with p\u2081 := ps}\n  | player\u2082 => {st with p\u2082 := ps}\n  | player\u2083 => {st with p\u2083 := ps}\n  | player\u2084 => {st with p\u2084 := ps}\ndef PlayerStateStore.getOp (self: PlayerStateStore) (idx: Player) : PlayerState :=\n  match idx with\n  | player\u2081 => self.p\u2081\n  | player\u2082 => self.p\u2082\n  | player\u2083 => self.p\u2083\n  | player\u2084 => self.p\u2084\nnotation:100 st \"[ \" pl \" \u21a6 \" 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\u2081\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\u2081],\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 \u21a6 {ps[pl] with passPriority := p}]\ndef updateEveryPriority (ps: PlayerStateStore) (p: Bool) :=\n  let ps\u2081 := updatePriority ps player\u2081 p;\n  let ps\u2082 := updatePriority ps\u2081 player\u2082 p;\n  let ps\u2083 := updatePriority ps\u2082 player\u2083 p;\n  updatePriority ps\u2083 player\u2084 p\n\ntheorem preservePlayerState : \u2200s p p' b, p \u2260 p' \u2192 (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 \u2192 GameState \u2192 Prop\n| passPriority: \u2200(s: GameState) (p: Player),\n  s.priority = PriorityOwner.player p \u2227 s.playerStates[p].passPriority = false -- \u304b\u3064 \u30bf\u30fc\u30f3\u8d77\u56e0\u51e6\u7406\u3068\u8a98\u767a\u578b\u80fd\u529b\u3092\u7a4d\u307f\u7d42\u308f\u3063\u305f\n  \u2192 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: \u2200s\u2081 s\u2082 s\u2083,\n  PriorityRel s\u2081 s\u2082\n  \u2192 PriorityRel s\u2082 s\u2083\n  \u2192 PriorityRel s\u2081 s\u2083\n| everyPlayerPassTheirPriority: \u2200(s: GameState) (p: Player) (tl: TurnList),\n  s.priority = PriorityOwner.player p\n  \u2227 s.turnList = p :: tl\n  \u2227 (\u2200(p: Player),\n    Std.AssocList.contains p s.setting.joinedPlayers\n    \u2227 Std.AssocList.find? p s.setting.joinedPlayers = some true\n    \u2227 s.playerStates[p].passPriority = true)\n  \u2192 PriorityRel s\n  {\n    s with\n    playerStates := updateEveryPriority s.playerStates false,\n    didEveryPlayerPassTheirPriority := true,\n  }\n-- \u305d\u306e\u4ed6\u306e\u884c\u52d5\u3092\u3067\u304d\u308b\u3088\u3046\u306b\u3059\u308b\n\ntheorem proofOfPassPriority: \u2200s p,\ns.priority = (PriorityOwner.player p)\n\u2227 s.playerStates[p].passPriority = false\n\u2192 \u2203s', PriorityRel s s' \n\u2227 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: \u2200s p tl,\ns.priority = PriorityOwner.player p\n\u2227 s.turnList = p :: tl\n\u2227 (\u2200(p: Player),\n  Std.AssocList.contains p s.setting.joinedPlayers\n  \u2227 Std.AssocList.find? p s.setting.joinedPlayers = some true\n  \u2227 s.playerStates[p].passPriority = true)\n\u2192 \u2203s', PriorityRel s s'\n\u2227 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 \u2192 GameState \u2192 Prop\n| nextStep: \u2200(s: GameState) (p: Phase) (next: PhaseList),\n  s.phaseList = p::next \u2227 s.didEveryPlayerPassTheirPriority = true\n  \u2192 ProgressPhaseRel s {s with phaseList := next, didEveryPlayerPassTheirPriority := false}\n  -- \u30bf\u30fc\u30f3\u8d77\u56e0\u51e6\u7406\u3068\u72b6\u6cc1\u8d77\u56e0\u51e6\u7406\uff0c\u8a98\u767a\u578b\u80fd\u529b\u306e\u8a98\u767a\u3092\u3057\u305f\u72b6\u614b\u306b\u3059\u308b\n| transStep: \u2200s\u2081 s\u2082 s\u2083,\n  ProgressPhaseRel s\u2081 s\u2082\n  \u2192 ProgressPhaseRel s\u2082 s\u2083\n  \u2192 ProgressPhaseRel s\u2081 s\u2083\n| priorityRel: \u2200s\u2081 s\u2082 s\u2083,\n  PriorityRel s\u2081 s\u2082\n  \u2192 ProgressPhaseRel s\u2082 s\u2083\n  \u2192 ProgressPhaseRel s\u2081 s\u2083\n\ninductive ProgressTurnRel: GameState \u2192 GameState \u2192 Prop\n| nextTurn:\n  \u2200 (s: GameState) (p: Player),\n  s.turnList = [p] \u2227 s.phaseList = []\n  \u2192 ProgressTurnRel s {s with turnList := [s.setting.nextplayer.1 p], phaseList := defaultPhaseList}\n  -- \u30bf\u30fc\u30f3\u8d77\u56e0\u51e6\u7406\u3068\u72b6\u6cc1\u8d77\u56e0\u51e6\u7406\uff0c\u8a98\u767a\u578b\u80fd\u529b\u306e\u8a98\u767a\u3092\u3057\u305f\u72b6\u614b\u306b\u3059\u308b\uff0e\n-- | untapStep\n-- \u30a2\u30f3\u30bf\u30c3\u30d7\u30fb\u30b9\u30c6\u30c3\u30d7\u306e\u30bf\u30fc\u30f3\u8d77\u56e0\u51e6\u7406\u95a2\u9023\u306f\u3053\u3053\u3067\u884c\u308f\u306a\u3044\u3068\u3044\u3051\u306a\u3044\n| extraTurn:\n  \u2200 (s: GameState) (p : Player) (next: TurnList),\n  \u00ac next = [] \n  \u2227 s.turnList = p::next \u2227 s.phaseList = []\n  \u2192 ProgressTurnRel s {s with turnList := next, phaseList := defaultPhaseList}\n| transTurn: \u2200s\u2081 s\u2082 s\u2083,\n  ProgressTurnRel s\u2081 s\u2082\n  \u2192 ProgressTurnRel s\u2082 s\u2083\n  \u2192 ProgressTurnRel s\u2081 s\u2083\n| phaseRel: \u2200s\u2081 s\u2082 s\u2083,\n  ProgressPhaseRel s\u2081 s\u2082\n  \u2192 ProgressTurnRel s\u2082 s\u2083\n  \u2192 ProgressTurnRel s\u2081 s\u2083\n\n--#print List\n\nexample : ProgressTurnRel GameState.default {GameState.default with turnList := [player\u2082]} := by {\n  let s: GameState := GameState.default;\n  have h0: s = GameState.default := rfl;\n  have h1: s.turnList = [player\u2081] := rfl;\n  have h2: s.priority = PriorityOwner.player player\u2081 := rfl;\n  have h3: s.playerStates[player\u2081].passPriority = false := rfl;\n  rw [h0] at *;\n  have \u27e8s1, \u27e8h4, h5\u27e9\u27e9 := proofOfPassPriority s player\u2081 (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) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Parser.Term\nimport Lean.Parser.Do\n\nnamespace Lean\nnamespace Parser\n\n/--\n  Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like\n  `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead.\n  Multiple command will be put in a `` `null `` node, but a single command will not (so that you can directly\n  match against a quotation in a command kind's elaborator). -/\n-- TODO: use two separate quotation parsers with parser priorities instead\n@[builtinTermParser] def Term.quot := leading_parser \"`(\" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> \")\"\n@[builtinTermParser] def Term.precheckedQuot := leading_parser \"`\" >> Term.quot\n\nnamespace Command\n\n/--\n  A mutual block may be broken in different cliques, we identify them using an `ident` (an element of the clique)\n  We provide two kinds of hints to the termination checker:\n  1- A wellfounded relation (`p` is `termParser`)\n  2- A tactic for proving the recursive applications are \"decreasing\" (`p` is `tacticSeq`)\n-/\ndef terminationHintMany (p : Parser) := leading_parser atomic (lookahead (ident >> \" => \")) >> many1Indent (group (ppLine >> ident >> \" => \" >> p >> optional \";\"))\ndef terminationHint1 (p : Parser) := leading_parser p\ndef terminationHint (p : Parser) := terminationHintMany p <|> terminationHint1 p\n\ndef terminationByCore := leading_parser \"termination_by' \" >> terminationHint termParser\ndef decreasingBy := leading_parser \"decreasing_by \" >> terminationHint Tactic.tacticSeq\n\ndef terminationByElement   := leading_parser ppLine >> (ident <|> \"_\") >> many (ident <|> \"_\") >> \" => \" >> termParser >> optional \";\"\ndef terminationBy          := leading_parser ppLine >> \"termination_by \" >> many1Indent terminationByElement\n\ndef terminationSuffix := optional (terminationBy <|> terminationByCore) >> optional decreasingBy\n\n@[builtinCommandParser]\ndef moduleDoc := leading_parser ppDedent $ \"/-!\" >> commentBody >> ppLine\n\ndef namedPrio := leading_parser (atomic (\"(\" >> nonReservedSymbol \"priority\") >> \" := \" >> priorityParser >> \")\")\ndef optNamedPrio := optional (ppSpace >> namedPrio)\n\ndef \u00abprivate\u00bb        := leading_parser \"private \"\ndef \u00abprotected\u00bb      := leading_parser \"protected \"\ndef visibility       := \u00abprivate\u00bb <|> \u00abprotected\u00bb\ndef \u00abnoncomputable\u00bb  := leading_parser \"noncomputable \"\ndef \u00abunsafe\u00bb         := leading_parser \"unsafe \"\ndef \u00abpartial\u00bb        := leading_parser \"partial \"\ndef \u00abnonrec\u00bb         := leading_parser \"nonrec \"\ndef declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.\u00abattributes\u00bb >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional \u00abnoncomputable\u00bb >> optional \u00abunsafe\u00bb >> optional (\u00abpartial\u00bb <|> \u00abnonrec\u00bb)\ndef declId           := leading_parser ident >> optional (\".{\" >> sepBy1 ident \", \" >> \"}\")\ndef declSig          := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec\ndef optDeclSig       := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType\ndef declValSimple    := leading_parser \" :=\" >> ppHardLineUnlessUngrouped >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef whereStructField := leading_parser Term.letDecl\ndef whereStructInst  := leading_parser \" where\" >> many1Indent (ppLine >> ppGroup (group (whereStructField >> optional \";\")))\n/-\n  Remark: we should not use `Term.whereDecls` at `declVal` because `Term.whereDecls` is defined using `Term.letRecDecl` which may contain attributes.\n  Issue #753 showns an example that fails to be parsed when we used `Term.whereDecls`.\n-/\ndef declVal          := declValSimple <|> declValEqns <|> whereStructInst\ndef \u00ababbrev\u00bb         := leading_parser \"abbrev \" >> declId >> ppIndent optDeclSig >> declVal\ndef optDefDeriving   := optional (atomic (\"deriving \" >> notSymbol \"instance\") >> sepBy1 ident \", \")\ndef \u00abdef\u00bb            := leading_parser \"def \" >> declId >> ppIndent optDeclSig >> declVal >> optDefDeriving >> terminationSuffix\ndef \u00abtheorem\u00bb        := leading_parser \"theorem \" >> declId >> ppIndent declSig >> declVal >> terminationSuffix\ndef \u00abconstant\u00bb       := leading_parser \"constant \" >> declId >> ppIndent declSig >> optional declValSimple\n/- As `declSig` starts with a space, \"instance\" does not need a trailing space if we put `ppSpace` in the optional fragments. -/\ndef \u00abinstance\u00bb       := leading_parser Term.attrKind >> \"instance\" >> optNamedPrio >> optional (ppSpace >> declId) >> ppIndent declSig >> declVal >> terminationSuffix\ndef \u00abaxiom\u00bb          := leading_parser \"axiom \" >> declId >> ppIndent declSig\n/- As `declSig` starts with a space, \"example\" does not need a trailing space. -/\ndef \u00abexample\u00bb        := leading_parser \"example\" >> ppIndent declSig >> declVal\ndef inferMod         := leading_parser ppSpace >> atomic (symbol \"{\" >> \"}\")\ndef ctor             := leading_parser \"\\n| \" >> ppIndent (declModifiers true >> ident >> optional inferMod >> optDeclSig)\ndef derivingClasses  := sepBy1 (group (ident >> optional (\" with \" >> Term.structInst))) \", \"\ndef optDeriving      := leading_parser optional (ppLine >> atomic (\"deriving \" >> notSymbol \"instance\") >> derivingClasses)\ndef \u00abinductive\u00bb      := leading_parser \"inductive \" >> declId >> optDeclSig >> optional (symbol \" :=\" <|> \" where\") >> many ctor >> optDeriving\ndef classInductive   := leading_parser atomic (group (symbol \"class \" >> \"inductive \")) >> declId >> ppIndent optDeclSig >> optional (symbol \" :=\" <|> \" where\") >> many ctor >> optDeriving\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optional inferMod >> ppIndent optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> optional inferMod >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> optional inferMod >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser manyIndent (ppLine >> checkColGe >> ppGroup (structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder))\ndef structCtor           := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> \" :: \")\ndef structureTk          := leading_parser \"structure \"\ndef classTk              := leading_parser \"class \"\ndef \u00abextends\u00bb            := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef \u00abstructure\u00bb          := leading_parser\n    (structureTk <|> classTk) >> declId >> many (ppSpace >> Term.bracketedBinder) >> optional \u00abextends\u00bb >> Term.optType\n    >> optional ((symbol \" := \" <|> \" where \") >> optional structCtor >> structFields)\n    >> optDeriving\n@[builtinCommandParser] def declaration := leading_parser\ndeclModifiers false >> (\u00ababbrev\u00bb <|> \u00abdef\u00bb <|> \u00abtheorem\u00bb <|> \u00abconstant\u00bb <|> \u00abinstance\u00bb <|> \u00abaxiom\u00bb <|> \u00abexample\u00bb <|> \u00abinductive\u00bb <|> classInductive <|> \u00abstructure\u00bb)\n@[builtinCommandParser] def \u00abderiving\u00bb     := leading_parser \"deriving \" >> \"instance \" >> derivingClasses >> \" for \" >> sepBy1 ident \", \"\n@[builtinCommandParser] def noncomputableSection := leading_parser \"noncomputable \" >> \"section \" >> optional ident\n@[builtinCommandParser] def \u00absection\u00bb      := leading_parser \"section \" >> optional ident\n@[builtinCommandParser] def \u00abnamespace\u00bb    := leading_parser \"namespace \" >> ident\n@[builtinCommandParser] def \u00abend\u00bb          := leading_parser \"end \" >> optional ident\n@[builtinCommandParser] def \u00abvariable\u00bb     := leading_parser \"variable\" >> many1 (ppSpace >> Term.bracketedBinder)\n@[builtinCommandParser] def \u00abuniverse\u00bb     := leading_parser \"universe \" >> many1 ident\n@[builtinCommandParser] def check          := leading_parser \"#check \" >> termParser\n@[builtinCommandParser] def check_failure  := leading_parser \"#check_failure \" >> termParser -- Like `#check`, but succeeds only if term does not type check\n@[builtinCommandParser] def reduce         := leading_parser \"#reduce \" >> termParser\n@[builtinCommandParser] def eval           := leading_parser \"#eval \" >> termParser\n@[builtinCommandParser] def synth          := leading_parser \"#synth \" >> termParser\n@[builtinCommandParser] def exit           := leading_parser \"#exit\"\n@[builtinCommandParser] def print          := leading_parser \"#print \" >> (ident <|> strLit)\n@[builtinCommandParser] def printAxioms    := leading_parser \"#print \" >> nonReservedSymbol \"axioms \" >> ident\n@[builtinCommandParser] def \u00abresolve_name\u00bb := leading_parser \"#resolve_name \" >> ident\n@[builtinCommandParser] def \u00abinit_quot\u00bb    := leading_parser \"init_quot\"\ndef optionValue := nonReservedSymbol \"true\" <|> nonReservedSymbol \"false\" <|> strLit <|> numLit\n@[builtinCommandParser] def \u00abset_option\u00bb   := leading_parser \"set_option \" >> ident >> ppSpace >> optionValue\ndef eraseAttr := leading_parser \"-\" >> rawIdent\n@[builtinCommandParser] def \u00abattribute\u00bb    := leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"] \" >> many1 ident\n@[builtinCommandParser] def \u00abexport\u00bb       := leading_parser \"export \" >> ident >> \" (\" >> many1 ident >> \")\"\ndef openHiding       := leading_parser atomic (ident >> \"hiding\") >> many1 (checkColGt >> ident)\ndef openRenamingItem := leading_parser ident >> unicodeSymbol \" \u2192 \" \" -> \" >> checkColGt >> ident\ndef openRenaming     := leading_parser atomic (ident >> \"renaming\") >> sepBy1 openRenamingItem \", \"\ndef openOnly         := leading_parser atomic (ident >> \" (\") >> many1 ident >> \")\"\ndef openSimple       := leading_parser many1 (checkColGt >> ident)\ndef openScoped       := leading_parser \"scoped \" >> many1 (checkColGt >> ident)\ndef openDecl         := openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped\n@[builtinCommandParser] def \u00abopen\u00bb    := leading_parser withPosition (\"open \" >> openDecl)\n\n@[builtinCommandParser] def \u00abmutual\u00bb := leading_parser \"mutual \" >> many1 (ppLine >> notSymbol \"end\" >> commandParser) >> ppDedent (ppLine >> \"end\") >> terminationSuffix\n@[builtinCommandParser] def \u00abinitialize\u00bb := leading_parser optional visibility >> \"initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n@[builtinCommandParser] def \u00abbuiltin_initialize\u00bb := leading_parser optional visibility >> \"builtin_initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n\n@[builtinCommandParser] def \u00abin\u00bb  := trailing_parser withOpen (\" in \" >> commandParser)\n\n/-\n  This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`.\n  It is meant for bootstrapping purposes only. -/\n@[builtinCommandParser] def genInjectiveTheorems := leading_parser \"gen_injective_theorems% \" >> ident\n\n@[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false\n@[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true\n\nbuiltin_initialize\n  register_parser_alias \"declModifiers\"       declModifiersF\n  register_parser_alias \"nestedDeclModifiers\" declModifiersT\n  register_parser_alias                       declId\n  register_parser_alias                       declSig\n  register_parser_alias                       declVal\n  register_parser_alias                       optDeclSig\n  register_parser_alias                       openDecl\n\nend Command\n\nnamespace Term\n@[builtinTermParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> termParser)\n@[builtinTermParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> termParser\nend Term\n\nnamespace Tactic\n@[builtinTacticParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> tacticSeq)\n@[builtinTacticParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> tacticSeq\nend Tactic\n\nend Parser\nend Lean\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/Parser/Command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934935817440722, "lm_q2_score": 0.04208773076923105, "lm_q1q2_score": 0.010073671346632703}}
{"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 \u00d7 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, _) \u2190 getExpectedNumArgsAux e\n  pure numArgs\n\nprivate def throwApplyError {\u03b1} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM \u03b1 :=\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 || !(\u2190 mvar.mvarId!.isAssigned) then\n        let mvarType \u2190 inferType mvar\n        let mvarVal  \u2190 synthInstance mvarType\n        unless (\u2190 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 \u2190 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 (\u2190 mvarIdNew.isAssigned) do\n          unless binderInfos[i]!.isInstImplicit do\n            let currTag \u2190 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 \u2190 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 \u00d7 Array MVarId) :=\n  mvars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do\n    let currMVarId := mvar.mvarId!\n    if (\u2190 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 \u2192 MetaM (List MVarId)\n  | ApplyNewGoals.nonDependentFirst => do\n      let (nonDeps, deps) \u2190 partitionDependentMVars mvars\n      return nonDeps.toList ++ deps.toList\n  | ApplyNewGoals.nonDependentOnly => do\n      let (nonDeps, _) \u2190 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 \u2190 mvarId.getType\n    let eType      \u2190 inferType e\n    let (numArgs, hasMVarHead) \u2190 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 {\u03b1 \u03b2} [LE_trans \u03b2] (x y z : \u03b1 \u2192 \u03b2) (h\u2080 : x \u2264 y) (h\u2081 : y \u2264 z) : x \u2264 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 {\u03b1 : Type u} {\u03b2 : Type v} [LE \u03b2] : LE (\u03b1 \u2192 \u03b2) where\n      le f g := \u2200 i, f i \u2264 g i\n    ```\n    -/\n    let rangeNumArgs \u2190 if hasMVarHead then\n      pure [numArgs : numArgs+1]\n    else\n      let targetTypeNumArgs \u2190 getExpectedNumArgs targetType\n      pure [numArgs - targetTypeNumArgs : numArgs+1]\n    /-\n    Auxiliary function for trying to add `n` underscores where `n \u2208 [i: rangeNumArgs.stop)`\n    See comment above\n    -/\n    let rec go (i : Nat) : MetaM (Array Expr \u00d7 Array BinderInfo) := do\n      if i < rangeNumArgs.stop then\n        let s \u2190 saveState\n        let (newMVars, binderInfos, eType) \u2190 forallMetaTelescopeReducing eType i\n        if (\u2190 isDefEqApply cfg eType targetType) then\n          return (newMVars, binderInfos)\n        else\n          s.restore\n          go (i+1)\n      else\n        let (_, _, eType) \u2190 forallMetaTelescopeReducing eType (some rangeNumArgs.start)\n        throwApplyError mvarId eType targetType\n    let (newMVars, binderInfos) \u2190 go rangeNumArgs.start\n    postprocessAppMVars `apply mvarId newMVars binderInfos cfg.synthAssignedInstances\n    let e \u2190 instantiateMVars e\n    mvarId.assign (mkAppN e newMVars)\n    let newMVars \u2190 newMVars.filterM fun mvar => not <$> mvar.mvarId!.isAssigned\n    let otherMVarIds \u2190 getMVarsNoDelayed e\n    let newMVarIds \u2190 reorderGoals newMVars cfg.newGoals\n    let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId\n    let result := newMVarIds ++ otherMVarIds.toList\n    result.forM (\u00b7.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 \u2190 mvarId.getType'\n    if !type.isAppOfArity ``And 2 then\n      return [mvarId]\n    else\n      let tag \u2190 mvarId.getTag\n      let rec go (type : Expr) : StateRefT (Array MVarId) MetaM Expr := do\n        let type \u2190 whnf type\n        if type.isAppOfArity ``And 2 then\n          let p\u2081 := type.appFn!.appArg!\n          let p\u2082 := type.appArg!\n          return mkApp4 (mkConst ``And.intro) p\u2081 p\u2082 (\u2190 go p\u2081) (\u2190 go p\u2082)\n        else\n          let idx := (\u2190 get).size + 1\n          let mvar \u2190 mkFreshExprSyntheticOpaqueMVar type (tag ++ (`h).appendIndexAfter idx)\n          modify fun s => s.push mvar.mvarId!\n          return mvar\n      let (val, s) \u2190 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 \u2190 instantiateMVars (\u2190 mvarId.getType)\n    let u \u2190 getLevel target\n    let mvarIdNew \u2190 mkFreshExprSyntheticOpaqueMVar (mkConst ``False) (tag := (\u2190 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 \u2192 F\nvariable  \u03c3 : 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 \u03c3.pc\n    (h_mem : mem_at mem code_ec_mul \u03c3.pc)\n    -- all dependencies are in memory\n    (h_mem_4 : mem_at mem code_nondet_bigint3 (\u03c3.pc  - 561))\n    (h_mem_5 : mem_at mem code_unreduced_mul (\u03c3.pc  - 549))\n    (h_mem_6 : mem_at mem code_unreduced_sqr (\u03c3.pc  - 529))\n    (h_mem_7 : mem_at mem code_verify_zero (\u03c3.pc  - 513))\n    (h_mem_8 : mem_at mem code_is_zero (\u03c3.pc  - 490))\n    (h_mem_12 : mem_at mem code_compute_doubling_slope (\u03c3.pc  - 385))\n    (h_mem_13 : mem_at mem code_compute_slope (\u03c3.pc  - 341))\n    (h_mem_14 : mem_at mem code_ec_double (\u03c3.pc  - 317))\n    (h_mem_15 : mem_at mem code_fast_ec_add (\u03c3.pc  - 244))\n    (h_mem_16 : mem_at mem code_ec_add (\u03c3.pc  - 157))\n    (h_mem_17 : mem_at mem code_ec_mul_inner (\u03c3.pc  - 101))\n    -- input arguments on the stack\n    (hin_range_check_ptr : range_check_ptr = mem (\u03c3.fp - 12))\n    (hin_point : point = cast_EcPoint mem (\u03c3.fp - 11))\n    (hin_scalar : scalar = cast_BigInt3 mem (\u03c3.fp - 5))\n    -- conclusion\n  : ensures_ret mem \u03c3 (\u03bb \u03ba \u03c4,\n      \u2203 \u03bc \u2264 \u03ba, rc_ensures mem (rc_bound F) \u03bc (mem (\u03c3.fp - 12)) (mem $ \u03c4.ap - 7)\n        (spec_ec_mul mem \u03ba range_check_ptr point scalar (mem (\u03c4.ap - 7)) (cast_EcPoint mem (\u03c4.ap - 6)))) :=\nbegin\n  apply ensures_of_ensuresb, intro \u03bdbound,\n  have h_mem_rec := h_mem,\n  unpack_memory code_ec_mul at h_mem with \u27e8hpc0, 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\u27e9,\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 \u03ba_call14 ap14 h_call14,\n  rcases h_call14 with \u27e8rc_m14, rc_mle14, hl_range_check_ptr\u2081, h_call14\u27e9,\n  generalize' hr_rev_range_check_ptr\u2081: mem (ap14 - 13) = range_check_ptr\u2081,\n  have htv_range_check_ptr\u2081 := hr_rev_range_check_ptr\u2081.symm, clear hr_rev_range_check_ptr\u2081,\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\u2081 },\n  rw [\u2190htv_range_check_ptr\u2081, \u2190hin_range_check_ptr] at hl_range_check_ptr\u2081,\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 \u03c3.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\u2081 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\u2081, 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\u2081, 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\u2081, 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\u2081, 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 \u03ba_call32 ap32 h_call32,\n  rcases h_call32 with \u27e8rc_m32, rc_mle32, hl_range_check_ptr\u2082, h_call32\u27e9,\n  generalize' hr_rev_range_check_ptr\u2082: mem (ap32 - 13) = range_check_ptr\u2082,\n  have htv_range_check_ptr\u2082 := hr_rev_range_check_ptr\u2082.symm, clear hr_rev_range_check_ptr\u2082,\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\u2082 },\n  rw [\u2190htv_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2081] at hl_range_check_ptr\u2082,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call32 },\n  rw [\u2190htv_range_check_ptr\u2081, hl_range_check_ptr\u2081, 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 (\u03c3.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\u2082 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, 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 \u03ba_call50 ap50 h_call50,\n  rcases h_call50 with \u27e8rc_m50, rc_mle50, hl_range_check_ptr\u2083, h_call50\u27e9,\n  generalize' hr_rev_range_check_ptr\u2083: mem (ap50 - 13) = range_check_ptr\u2083,\n  have htv_range_check_ptr\u2083 := hr_rev_range_check_ptr\u2083.symm, clear hr_rev_range_check_ptr\u2083,\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\u2083 },\n  rw [\u2190htv_range_check_ptr\u2083, \u2190htv_range_check_ptr\u2082] at hl_range_check_ptr\u2083,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call50 },\n  rw [\u2190htv_range_check_ptr\u2082, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 (\u03c3.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\u2083 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, 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 \u03ba_call71 ap71 h_call71,\n  rcases h_call71 with \u27e8rc_m71, rc_mle71, hl_range_check_ptr\u2084, h_call71\u27e9,\n  generalize' hr_rev_range_check_ptr\u2084: mem (ap71 - 7) = range_check_ptr\u2084,\n  have htv_range_check_ptr\u2084 := hr_rev_range_check_ptr\u2084.symm, clear hr_rev_range_check_ptr\u2084,\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\u2084 },\n  rw [\u2190htv_range_check_ptr\u2084, \u2190htv_range_check_ptr\u2083] at hl_range_check_ptr\u2084,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call71 },\n  rw [\u2190htv_range_check_ptr\u2083, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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\u2084 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, htv_res2, lc_res2, htv_range_check_ptr\u2084, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, htv_res2, lc_res2, htv_range_check_ptr\u2084, 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, htv_res2, lc_res2, htv_range_check_ptr\u2084, 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 \u03ba_call79 ap79 h_call79,\n  rcases h_call79 with \u27e8rc_m79, rc_mle79, hl_range_check_ptr\u2085, h_call79\u27e9,\n  generalize' hr_rev_range_check_ptr\u2085: mem (ap79 - 7) = range_check_ptr\u2085,\n  have htv_range_check_ptr\u2085 := hr_rev_range_check_ptr\u2085.symm, clear hr_rev_range_check_ptr\u2085,\n  generalize' hr_rev_res\u2081: cast_EcPoint mem (ap79 - 6) = res\u2081,\n  simp only [hr_rev_res\u2081] at h_call79,\n  have htv_res\u2081 := hr_rev_res\u2081.symm, clear hr_rev_res\u2081,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5] at hl_range_check_ptr\u2085 },\n  rw [\u2190htv_range_check_ptr\u2085, \u2190htv_range_check_ptr\u2084] at hl_range_check_ptr\u2085,\n  try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5] at h_call79 },\n  rw [\u2190htv_range_check_ptr\u2084, hl_range_check_ptr\u2084, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u2190htv_range_check_ptr\u2085, hl_range_check_ptr\u2085, hl_range_check_ptr\u2084, hl_range_check_ptr\u2083, hl_range_check_ptr\u2082, hl_range_check_ptr\u2081, 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 [\u03ba_call14],\n  use_only [range_check_ptr\u2081],\n  use_only [pow2_0],\n  use_only [res0],\n  have rc_h_range_check_ptr\u2081 := range_checked_offset' rc_h_range_check_ptr,\n  have rc_h_range_check_ptr\u2081' := range_checked_add_right rc_h_range_check_ptr\u2081, try { norm_cast at rc_h_range_check_ptr\u2081' },\n  have spec14 := h_call14 rc_h_range_check_ptr',\n  rw [\u2190hin_range_check_ptr, \u2190htv_range_check_ptr\u2081] at spec14,\n  try { dsimp at spec14, arith_simps at spec14 },\n  use_only [spec14],\n  use_only [\u03ba_call32],\n  use_only [range_check_ptr\u2082],\n  use_only [pow2_1],\n  use_only [res1],\n  have rc_h_range_check_ptr\u2082 := range_checked_offset' rc_h_range_check_ptr\u2081,\n  have rc_h_range_check_ptr\u2082' := range_checked_add_right rc_h_range_check_ptr\u2082, try { norm_cast at rc_h_range_check_ptr\u2082' },\n  have spec32 := h_call32 rc_h_range_check_ptr\u2081',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190htv_range_check_ptr\u2082] at spec32,\n  try { dsimp at spec32, arith_simps at spec32 },\n  use_only [spec32],\n  use_only [\u03ba_call50],\n  use_only [range_check_ptr\u2083],\n  use_only [(cast_EcPoint mem (ap50 - 12))],\n  use_only [res2],\n  have rc_h_range_check_ptr\u2083 := range_checked_offset' rc_h_range_check_ptr\u2082,\n  have rc_h_range_check_ptr\u2083' := range_checked_add_right rc_h_range_check_ptr\u2083, try { norm_cast at rc_h_range_check_ptr\u2083' },\n  have spec50 := h_call50 rc_h_range_check_ptr\u2082',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190htv_range_check_ptr\u2083] at spec50,\n  try { dsimp at spec50, arith_simps at spec50 },\n  use_only [spec50],\n  use_only [\u03ba_call71],\n  use_only [range_check_ptr\u2084],\n  use_only [res],\n  have rc_h_range_check_ptr\u2084 := range_checked_offset' rc_h_range_check_ptr\u2083,\n  have rc_h_range_check_ptr\u2084' := range_checked_add_right rc_h_range_check_ptr\u2084, try { norm_cast at rc_h_range_check_ptr\u2084' },\n  have spec71 := h_call71 rc_h_range_check_ptr\u2083',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190hl_range_check_ptr\u2083, \u2190htv_range_check_ptr\u2084] at spec71,\n  try { dsimp at spec71, arith_simps at spec71 },\n  use_only [spec71],\n  use_only [\u03ba_call79],\n  use_only [range_check_ptr\u2085],\n  use_only [res\u2081],\n  have rc_h_range_check_ptr\u2085 := range_checked_offset' rc_h_range_check_ptr\u2084,\n  have rc_h_range_check_ptr\u2085' := range_checked_add_right rc_h_range_check_ptr\u2085, try { norm_cast at rc_h_range_check_ptr\u2085' },\n  have spec79 := h_call79 rc_h_range_check_ptr\u2084',\n  rw [\u2190hin_range_check_ptr, \u2190hl_range_check_ptr\u2081, \u2190hl_range_check_ptr\u2082, \u2190hl_range_check_ptr\u2083, \u2190hl_range_check_ptr\u2084, \u2190htv_range_check_ptr\u2085] 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\u2081, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr\u2082, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr\u2083, htv_res2, lc_res2, htv_range_check_ptr\u2084, htv_res, htv_range_check_ptr\u2085, htv_res\u2081] }, },\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": "/-\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 Mathlib.Lean.Expr.Basic\n\n/-!\n\n# The `#help` command\n\nThe `#help` command can be used to list all definitions in a variety of extensible aspects of lean.\n\n* `#help option` lists options (used in `set_option myOption`)\n* `#help attr` lists attributes (used in `@[myAttr] def foo := ...`)\n* `#help cats` lists syntax categories (like `term`, `tactic`, `stx` etc)\n* `#help cat C` lists elements of syntax category C\n  * `#help term`, `#help tactic`, `#help conv`, `#help command`\n    are shorthand for `#help cat term` etc.\n  * `#help cat+ C` also shows `elab` and `macro` definitions associated to the syntaxes\n\nAll forms take an optional identifier to narrow the search; for example `#help option pp` shows\nonly `pp.*` options.\n\n-/\n\nnamespace Mathlib.Tactic\nopen Lean Meta Elab Tactic Command\n\n/--\nThe command `#help option` shows all options that have been defined in the current environment.\nEach option has a format like:\n```\noption pp.all : Bool := false\n  (pretty printer) display coercions, implicit parameters, proof terms, fully qualified names,\n  universe, and disable beta reduction and notations during pretty printing\n```\nThis says that `pp.all` is an option which can be set to a `Bool` value, and the default value is\n`false`. If an option has been modified from the default using e.g. `set_option pp.all true`,\nit will appear as a `(currently: true)` note next to the option.\n\nThe form `#help option id` will show only options that begin with `id`.\n-/\nelab \"#help\" &\"option\" id:(ident)? : command => do\n  let id := id.map (\u00b7.getId.toString false)\n  let mut decls : Lean.RBMap _ _ compare := {}\n  for (name, decl) in show Lean.RBMap .. from \u2190 getOptionDecls do\n    let name := name.toString false\n    if let some id := id then\n      if !id.isPrefixOf name then\n        continue\n    decls := decls.insert name decl\n  let mut msg := Format.nil\n  let opts \u2190 getOptions\n  if decls.isEmpty then\n    match id with\n    | some id => throwError \"no options start with {id}\"\n    | none => throwError \"no options found (!)\"\n  for (name, decl) in decls do\n    let mut msg1 := match decl.defValue with\n    | .ofString val => s!\"String := {repr val}\"\n    | .ofBool val => s!\"Bool := {repr val}\"\n    | .ofName val => s!\"Name := {repr val}\"\n    | .ofNat val => s!\"Nat := {repr val}\"\n    | .ofInt val => s!\"Int := {repr val}\"\n    | .ofSyntax val => s!\"Syntax := {repr val}\"\n    if let some val := opts.find name then\n      msg1 := s!\"{msg1}  (currently: {val})\"\n    msg := msg ++ .nest 2 (f!\"option {name} : {msg1}\" ++ .line ++ decl.descr) ++ .line ++ .line\n  logInfo msg\n\n/--\nThe command `#help attribute` (or the short form `#help attr`) shows all attributes that have been\ndefined in the current environment.\nEach option has a format like:\n```\n[inline]: mark definition to always be inlined\n```\nThis says that `inline` is an attribute that can be placed on definitions like\n`@[inline] def foo := 1`. (Individual attributes may have restrictions on where they can be\napplied; see the attribute's documentation for details.) Both the attribute's `descr` field as well\nas the docstring will be displayed here.\n\nThe form `#help attr id` will show only attributes that begin with `id`.\n-/\nelab \"#help\" (&\"attr\" <|> &\"attribute\") id:(ident)? : command => do\n  let id := id.map (\u00b7.getId.toString false)\n  let mut decls : Lean.RBMap _ _ compare := {}\n  for (name, decl) in \u2190 attributeMapRef.get do\n    let name := name.toString false\n    if let some id := id then\n      if !id.isPrefixOf name then\n        continue\n    decls := decls.insert name decl\n  let mut msg := Format.nil\n  let env \u2190 getEnv\n  if decls.isEmpty then\n    match id with\n    | some id => throwError \"no attributes start with {id}\"\n    | none => throwError \"no attributes found (!)\"\n  for (name, decl) in decls do\n    let mut msg1 := s!\"[{name}]: {decl.descr}\"\n    if let some doc \u2190 findDocString? env decl.ref then\n      msg1 := s!\"{msg1}\\n{doc.trim}\"\n    msg := msg ++ .nest 2 msg1 ++ .line ++ .line\n  logInfo msg\n\n/-- Gets the initial string token in a parser description. For example, for a declaration like\n`syntax \"bla\" \"baz\" term : tactic`, it returns `some \"bla\"`. Returns `none` for syntax declarations\nthat don't start with a string constant. -/\npartial def getHeadTk (e : Expr) : Option String :=\n  match e.getAppFnArgs with\n  | (``ParserDescr.node, #[_, _, p]) => getHeadTk p\n  | (``ParserDescr.unary, #[.app _ (.lit (.strVal \"withPosition\")), p]) => getHeadTk p\n  | (``ParserDescr.unary, #[.app _ (.lit (.strVal \"atomic\")), p]) => getHeadTk p\n  | (``ParserDescr.binary, #[.app _ (.lit (.strVal \"andthen\")), p, _]) => getHeadTk p\n  | (``ParserDescr.nonReservedSymbol, #[.lit (.strVal tk), _]) => some tk\n  | (``ParserDescr.symbol, #[.lit (.strVal tk)]) => some tk\n  | (``Parser.withAntiquot, #[_, p]) => getHeadTk p\n  | (``Parser.leadingNode, #[_, _, p]) => getHeadTk p\n  | (``HAndThen.hAndThen, #[_, _, _, _, p, _]) => getHeadTk p\n  | (``Parser.nonReservedSymbol, #[.lit (.strVal tk), _]) => some tk\n  | (``Parser.symbol, #[.lit (.strVal tk)]) => some tk\n  | _ => none\n\n/--\nThe command `#help cats` shows all syntax categories that have been defined in the\ncurrent environment.\nEach syntax has a format like:\n```\ncategory command [Lean.Parser.initFn\u271d]\n```\nThe name of the syntax category in this case is `command`, and `Lean.Parser.initFn\u271d` is the\nname of the declaration that introduced it. (It is often an anonymous declaration like this,\nbut you can click to go to the definition.) It also shows the doc string if available.\n\nThe form `#help cats id` will show only syntax categories that begin with `id`.\n-/\nelab \"#help\" &\"cats\" id:(ident)? : command => do\n  let id := id.map (\u00b7.getId.toString false)\n  let mut decls : Lean.RBMap _ _ compare := {}\n  for (name, cat) in (Parser.parserExtension.getState (\u2190 getEnv)).categories do\n    let name := name.toString false\n    if let some id := id then\n      if !id.isPrefixOf name then\n        continue\n    decls := decls.insert name cat\n  let mut msg := MessageData.nil\n  let env \u2190 getEnv\n  if decls.isEmpty then\n    match id with\n    | some id => throwError \"no syntax categories start with {id}\"\n    | none => throwError \"no syntax categories found (!)\"\n  for (name, cat) in decls do\n    let mut msg1 := m!\"category {name} [{mkConst cat.declName}]\"\n    if let some doc \u2190 findDocString? env cat.declName then\n      msg1 := msg1 ++ Format.line ++ doc.trim\n    msg := msg ++ .nest 2 msg1 ++ (.line ++ .line : Format)\n  logInfo msg\n\n/--\nThe command `#help cat C` shows all syntaxes that have been defined in syntax category `C` in the\ncurrent environment.\nEach syntax has a format like:\n```\nsyntax \"first\"... [Parser.tactic.first]\n  `first | tac | ...` runs each `tac` until one succeeds, or else fails.\n```\nThe quoted string is the leading token of the syntax, if applicable. It is followed by the full\nname of the syntax (which you can also click to go to the definition), and the documentation.\n\n* The form `#help cat C id` will show only attributes that begin with `id`.\n* The form `#help cat+ C` will also show information about any `macro`s and `elab`s\n  associated to the listed syntaxes.\n-/\nelab \"#help\" &\"cat\" more:\"+\"? catStx:ident id:(ident <|> str)? : command => do\n  let id := id.map fun id \u21a6 match id.raw with\n    | .ident _ _ v _ => v.toString false\n    | id => id.isStrLit?.get!\n  let mut decls : Lean.RBMap _ _ compare := {}\n  let mut rest : Lean.RBMap _ _ compare := {}\n  let catName := catStx.getId.eraseMacroScopes\n  let some cat := (Parser.parserExtension.getState (\u2190 getEnv)).categories.find? catName\n    | throwErrorAt catStx \"{catStx} is not a syntax category\"\n  liftTermElabM <| Term.addCategoryInfo catStx catName\n  let env \u2190 getEnv\n  for (k, _) in cat.kinds do\n    let mut used := false\n    if let some tk := do getHeadTk (\u2190 (\u2190 env.find? k).value?) then\n      let tk := tk.trim\n      if let some id := id then\n        if !id.isPrefixOf tk then\n          continue\n      used := true\n      decls := decls.insert tk ((decls.findD tk #[]).push k)\n    if !used && id.isNone then\n      rest := rest.insert (k.toString false) k\n  let mut msg := MessageData.nil\n  if decls.isEmpty && rest.isEmpty then\n    match id with\n    | some id => throwError \"no {catName} declarations start with {id}\"\n    | none => throwError \"no {catName} declarations found\"\n  let env \u2190 getEnv\n  let addMsg (k : SyntaxNodeKind) (msg msg1 : MessageData) : CommandElabM MessageData := do\n    let mut msg1 := msg1\n    if let some doc \u2190 findDocString? env k then\n      msg1 := msg1 ++ Format.line ++ doc.trim\n    msg1 := .nest 2 msg1\n    if more.isSome then\n      let addElabs {\u03b1} (type : String) (attr : KeyedDeclsAttribute \u03b1)\n          (msg : MessageData) : CommandElabM MessageData := do\n        let mut msg := msg\n        for e in attr.getEntries env k do\n          let x := e.declName\n          msg := msg ++ Format.line ++ m!\"+ {type} {mkConst x}\"\n          if let some doc \u2190 findDocString? env x then\n            msg := msg ++ .nest 2 (Format.line ++ doc.trim)\n        pure msg\n      msg1 \u2190 addElabs \"macro\" macroAttribute msg1\n      match catName with\n      | `term => msg1 \u2190 addElabs \"term elab\" Term.termElabAttribute msg1\n      | `command => msg1 \u2190 addElabs \"command elab\" commandElabAttribute msg1\n      | `tactic | `conv => msg1 \u2190 addElabs \"tactic elab\" tacticElabAttribute msg1\n      | _ => pure ()\n    return msg ++ msg1 ++ (.line ++ .line : Format)\n  for (name, ks) in decls do\n    for k in ks do\n      msg \u2190 addMsg k msg m!\"syntax {repr name}... [{mkConst k}]\"\n  for (_, k) in rest do\n    msg \u2190 addMsg k msg m!\"syntax ... [{mkConst k}]\"\n  logInfo msg\n\n/--\nThe command `#help term` shows all term syntaxes that have been defined in the current environment.\nSee `#help cat` for more information.\n-/\nmacro \"#help\" tk:&\"term\" more:\"+\"? id:(ident <|> str)? : command =>\n  `(#help cat$[+%$more]? $(mkIdentFrom tk `term) $(id.map (\u27e8\u00b7.raw\u27e9))?)\n\n/--\nThe command `#help tactic` shows all tactics that have been defined in the current environment.\nSee `#help cat` for more information.\n-/\nmacro \"#help\" tk:&\"tactic\" more:\"+\"? id:(ident <|> str)? : command => do\n  `(#help cat$[+%$more]? $(mkIdentFrom tk `tactic) $(id.map (\u27e8\u00b7.raw\u27e9))?)\n\n/--\nThe command `#help conv` shows all tactics that have been defined in the current environment.\nSee `#help cat` for more information.\n-/\nmacro \"#help\" tk:&\"conv\" more:\"+\"? id:(ident <|> str)? : command =>\n  `(#help cat$[+%$more]? $(mkIdentFrom tk `conv) $(id.map (\u27e8\u00b7.raw\u27e9))?)\n\n/--\nThe command `#help command` shows all commands that have been defined in the current environment.\nSee `#help cat` for more information.\n-/\nmacro \"#help\" tk:&\"command\" more:\"+\"? id:(ident <|> str)? : command =>\n  `(#help cat$[+%$more]? $(mkIdentFrom tk `command) $(id.map (\u27e8\u00b7.raw\u27e9))?)\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/HelpCmd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1871326821624266, "lm_q2_score": 0.053403324903538434, "lm_q1q2_score": 0.009993507425590659}}
{"text": "import Straume.Chunk\nimport Straume.Coco\nimport Straume.Flood\nimport Straume.Iterator\nimport Straume.Zeptoparsec\n\nopen Straume.Chunk (Chunk Terminable coreturn)\nopen Straume.Coco (Coco)\nopen Straume.Flood (Flood)\nopen Straume.Iterator (Iterable iter)\nopen Straume.Iterator (Bijection)\nopen Zeptoparsec renaming Parsec \u2192 Zepto.Parsec\nopen Zeptoparsec renaming ParseResult \u2192 Zepto.Res\n\n\n/-\n  This module is designed first and foremost to provide Megaparsec users\n  with a way to work with greater-than-RAM and infinite streams.\n-/\nnamespace Straume.Aka\n\nuniverse u\nuniverse v\n\n-- class Stream (S : Type) where\n--   Token : Type\n--   ordToken : Ord Token\n--   Chunk \\a : Type\n--   ordChunk \\a : Ord Chunk \\a\n--   tokenToChunk : Token \u2192 Chunk \\a\n--   tokensToChunk : List Token \u2192 Chunk \\a\n--   chunkToChunk \\a : Chunk \\a \u2192 List Token\n--   chunkLength : Chunk \\a \u2192 Nat\n--   take1 : S \u2192 Option (Token \u00d7 S)\n--   takeN : Nat \u2192 S \u2192 Option (Chunk \\a \u00d7 S)\n--   takeWhile : (Token \u2192 Bool) \u2192 S \u2192 (Chunk \\a \u00d7 S)\n\n-------------------------------\n----         takeN         ----\n-------------------------------\n\ndef takeN {f : Type u \u2192 Type u} {\u03b1 \u03b2 : Type u}\n          (n : Nat) (src : s) (b : Nat := 2048)\n          [Coco \u03b1 s] [Flood m s] [Terminable f] [Monad m] [Iterable \u03b1 \u03b2]\n          : m (f \u03b1 \u00d7 s) := do\n  -- BEST EFFORT\n  let l := Iterable.length (Coco.coco src : \u03b1)\n  let src\u2091 \u2190 Flood.flood src $ max b ((n - l) + 1) -- We expand the buffer\n  -- EXTRACTION\n  let it\u2080 := iter $ Coco.coco src\u2091\n  let it\u2081 := { it\u2080 with i := n }\n  let firstN := Iterable.extract it\u2080 it\u2081\n  -- CHUNK PREPARATION\n  let k := Iterable.length $ it\u2080.s\n  let res :=\n    if k == 0 && l == 0\n    then Terminable.mkNil -- Expansion unsuccessful => Stream was always empty\n    else match k - n with\n      | 0 => Terminable.mkFin firstN -- We expanded to less than `n`\n      | _otherwise => Terminable.mkCont firstN\n  pure (res, Coco.replace src\u2091 $ Iterable.extract it\u2081 { it\u2081 with i := k })\n\n-------------------------------\n----         take1         ----\n-------------------------------\n\n-- We use `takeN` to snip off `\u03b1` of length 1 and then use\n-- `Iterable` to take the first (and only) element.\ndef take1 {f : Type u \u2192 Type u} {\u03b1 \u03b2 : Type u}\n          (src : s) (b := 2048)\n          [Coco \u03b1 s] [Flood m s] [Terminable f] [Monad m]\n          [Iterable \u03b1 \u03b2] [Bijection \u03b2 \u03b1] : m ((f \u03b2) \u00d7 s) :=\n  takeN 1 src b >>= fun ((y : f \u03b1), s\u2081) =>\n    pure ((Iterable.curr \u2218 iter) <$> y, s\u2081)\n\n\n-------------------------------\n----       takeWhile       ----\n-------------------------------\n\nprivate partial def takeWhileDo\n    {f : Type u \u2192 Type u} {\u03b1 \u03b2 : Type u}\n    (\u03c6 : \u03b2 \u2192 Bool) (stream\u2080 : s) (b : Nat) (acc : f \u03b1)\n    [Coco \u03b1 s] [Iterable \u03b1 \u03b2] [Terminable f] [Monad m]\n    [Inhabited (m (f \u03b1 \u00d7 s))] [Inhabited \u03b1] [Flood m s]\n    : m (f \u03b1 \u00d7 s) := do\n  let ((atom : f \u03b2), stream) \u2190 take1 stream\u2080 b\n  match Terminable.un atom with\n  | .none => pure (acc, stream\u2080)\n  | .some c =>\n    if \u03c6 c then\n      match (Terminable.reason acc, Terminable.reason atom) with\n      -- cont cases\n      | (.none, .none) =>\n        takeWhileDo \u03c6 stream b $\n          Terminable.mkCont $ Iterable.push (coreturn acc) c\n      -- fin cases\n      | (.none, .some ()) =>\n        pure (Terminable.mkFin $ Iterable.push (coreturn acc) c, stream)\n      -- nil case\n      | _otherwise => pure (acc, stream\u2080)\n    else\n      pure (acc, stream\u2080)\n\npartial def takeWhile\n    {f : Type u \u2192 Type u} {\u03b1 \u03b2 : Type u}\n    (\u03c6 : \u03b2 \u2192 Bool) (src : s) (b : Nat := 2048)\n    [Coco \u03b1 s] [Iterable \u03b1 \u03b2] [Terminable f] [Monad m]\n    [Inhabited (m (f \u03b1 \u00d7 s))] [Inhabited \u03b1] [Flood m s]\n    : m (f \u03b1 \u00d7 s) :=\n  takeWhileDo \u03c6 src b Terminable.mkNil\n\nopen Straume.Combinators\n\n-------------------------------\n----      chunkLength      ----\n-------------------------------\n\ndef chunkLength (fx : f \u03b1) [Terminable f] [Iterable \u03b1 \u03b2] : Nat :=\n  match (Terminable.un fx) with\n  | .none => 0\n  | .some e => Iterable.length e\n\ndef storeLength (fx : f \u03b1) [Terminable f] [Iterable \u03b1 \u03b2] : f Nat :=\n  Iterable.length <$> fx\n\n-------------------------------\n----       Aka class       ----\n-------------------------------\n\n/-\n  A way to read atomic values `v` out of a source `s`,\n  which emits `Iterable \u03b1 v`.\n  The information about finality is tacked onto the values of type `v`\n  via type `f`.\n  An example of such `f` is `Chunk`.\n-/\nclass Aka (m : Type u \u2192 Type v)\n          (s : Type u)\n          (f : Type u \u2192 Type u)\n          (v : Type u) where\n                        -- TODO: Can we express _buffer > 0 in types?\n  take1 (_source : s) (_buffer : Nat := 2048) : m ((f v) \u00d7 s)\n\ninstance : Aka IO (String \u00d7 IO.FS.Handle) Chunk Char where\n  take1 src b := take1 src b\n", "meta": {"author": "lurk-lab", "repo": "straume", "sha": "94c21db8da739e9f344ee9c23c75fd4a00d538f9", "save_path": "github-repos/lean/lurk-lab-straume", "path": "github-repos/lean/lurk-lab-straume/straume-94c21db8da739e9f344ee9c23c75fd4a00d538f9/Straume/Aka.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.033589508431438486, "lm_q1q2_score": 0.009991869145223275}}
{"text": "example : 1 = 2 := calc\n  _ = _ := sorry\n\nexample : 1 = 2 :=\n  calc\n  _ = _ := sorry\n\nexample : 1 = 2 := by calc\n  _ = _ := sorry\n\nexample : 1 = 2 := by\n  calc\n  _ = _ := 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/1267.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746994260479465, "lm_q2_score": 0.033589506617524655, "lm_q1q2_score": 0.00999186860563843}}
{"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.CongrTheorems\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 \u2190\n  registerInternalExceptionId `congrHypothesisFailed\n\ndef throwCongrHypothesisFailed : MetaM \u03b1 :=\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\u2081 r\u2082 : Result) : MetaM Result := do\n  match r\u2081.proof? with\n  | none => return r\u2082\n  | some p\u2081 => match r\u2082.proof? with\n    | none    => return { r\u2082 with proof? := r\u2081.proof? }\n    | some p\u2082 => return { r\u2082 with proof? := (\u2190 Meta.mkEqTrans p\u2081 p\u2082) }\n\ndef 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? := (\u2190 Meta.mkCongrFun h a) }\n\ndef mkCongr (r\u2081 r\u2082 : Result) : MetaM Result :=\n  let e := mkApp r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | some h,  none    => return { expr := e, proof? := (\u2190 Meta.mkCongrFun h r\u2082.expr) }\n  | none,    some h  => return { expr := e, proof? := (\u2190 Meta.mkCongrArg r\u2081.expr h) }\n  | some h\u2081, some h\u2082 => return { expr := e, proof? := (\u2190 Meta.mkCongr h\u2081 h\u2082) }\n\nprivate def mkImpCongr (r\u2081 r\u2082 : Result) : MetaM Result := do\n  let e \u2190 mkArrow r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | _,        _      => return { expr := e, proof? := (\u2190 Meta.mkImpCongr (\u2190 r\u2081.getProof) (\u2190 r\u2082.getProof)) } -- TODO specialize if bootleneck\n\n/-- Return true if `e` is of the form `ofNat n` where `n` is a kernel Nat literal -/\ndef isOfNatNatLit (e : Expr) : Bool :=\n  e.isAppOfArity ``OfNat.ofNat 3 && e.appFn!.appArg!.isNatLit\n\nprivate def reduceProj (e : Expr) : MetaM Expr := do\n  match (\u2190 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 (\u2190 getProjectionFnInfo? cinfo.name) with\n    | none => return none\n    | some projInfo =>\n      if projInfo.fromClass then\n        if (\u2190 read).simpTheorems.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 (\u2190 unfoldDefinition? e) with\n        | none   => pure none\n        | some e =>\n          match (\u2190 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 (\u2190 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 (\u2190 isProjectionFn fName) then\n    return none -- should be reduced by `reduceProjFn?`\n  if (\u2190 read).simpTheorems.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 := (\u2190 read).config\n  if cfg.beta then\n    let e' := e.headBeta\n    if e' != e then\n      return (\u2190 reduce e')\n  -- TODO: eta reduction\n  if cfg.proj then\n    match (\u2190 reduceProjFn? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  if cfg.iota then\n    match (\u2190 reduceRecMatcher? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  match (\u2190 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 (\u2190 reduce e))\n\ninductive SimpLetCase where\n  | dep -- `let x := v; b` is not equivalent to `(fun x => b) v`\n  | nondepDepVar -- `let x := v; b` is equivalent to `(fun x => b) v`, but result type depends on `x`\n  | nondep -- `let x := v; b` is equivalent to `(fun x => b) v`, and result type does not depend on `x`\n\ndef getSimpLetCase (n : Name) (t : Expr) (v : Expr) (b : Expr) : MetaM SimpLetCase := do\n  withLocalDeclD n t fun x => do\n    let bx := b.instantiate1 x\n    /- The following step is potentially very expensive when we have many nested let-decls.\n       TODO: handle a block of nested let decls in a single pass if this becomes a performance problem. -/\n    if (\u2190 isTypeCorrect bx) then\n      let bxType \u2190 whnf (\u2190 inferType bx)\n      if (\u2190 dependsOn bxType x.fvarId!) then\n        return SimpLetCase.nondepDepVar\n      else\n        return SimpLetCase.nondep\n    else\n      return SimpLetCase.dep\n\n/-- Given the application `e`, remove unnecessary casts of the form `Eq.rec a rfl` and `Eq.ndrec a rfl`. -/\npartial def removeUnnecessaryCasts (e : Expr) : MetaM Expr := do\n  let mut args := e.getAppArgs\n  let mut modified := false\n  for i in [:args.size] do\n    let arg := args[i]\n    if isDummyEqRec arg then\n      args := args.set! i (elimDummyEqRec arg)\n      modified := true\n  if modified then\n    return mkAppN e.getAppFn args\n  else\n    return e\nwhere\n  isDummyEqRec (e : Expr) : Bool :=\n    (e.isAppOfArity ``Eq.rec 6 || e.isAppOfArity ``Eq.ndrec 6) && e.appArg!.isAppOf ``Eq.refl\n\n  elimDummyEqRec (e : Expr) : Expr :=\n    if isDummyEqRec e then\n      elimDummyEqRec e.appFn!.appFn!.appArg!\n    else\n      e\n\npartial def simp (e : Expr) : M Result := withIncRecDepth do\n  checkMaxHeartbeats \"simp\"\n  let cfg \u2190 getConfig\n  if (\u2190 isProof e) then\n    return { expr := e }\n  if cfg.memoize then\n    if let some result := (\u2190 get).cache.find? e then\n      return result\n  simpLoop { expr := e }\n\nwhere\n  simpLoop (r : Result) : M Result := do\n    let cfg \u2190 getConfig\n    if (\u2190 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 (\u2190 pre r.expr) with\n      | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n      | Step.visit r' =>\n        let r \u2190 mkEqTrans r r'\n        let r \u2190 mkEqTrans r (\u2190 simpStep r.expr)\n        match (\u2190 post r.expr) with\n        | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n        | Step.visit r' =>\n          let r \u2190 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 m e _ => let r \u2190 simp e; return { r with expr := mkMData m r.expr }\n    | Expr.proj ..     => simpProj 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 ..     => return { expr := e }\n    | Expr.lit ..      => simpLit e\n    | Expr.mvar ..     => return { expr := (\u2190 instantiateMVars e) }\n    | Expr.fvar ..     => return { expr := (\u2190 reduceFVar (\u2190 getConfig) e) }\n\n  simpLit (e : Expr) : M Result := do\n    match e.natLit? with\n    | some n =>\n      /- If `OfNat.ofNat` is marked to be unfolded, we do not pack orphan nat literals as `OfNat.ofNat` applications\n         to avoid non-termination. See issue #788.  -/\n      if (\u2190 getSimpTheorems).isDeclToUnfold ``OfNat.ofNat then\n        return { expr := e }\n      else\n        return { expr := (\u2190 mkNumeral (mkConst ``Nat) n) }\n    | none   => return { expr := e }\n\n  simpProj (e : Expr) : M Result := do\n    match (\u2190 reduceProj? e) with\n    | some e => return { expr := e }\n    | none =>\n      let s := e.projExpr!\n      let motive? \u2190 withLocalDeclD `s (\u2190 inferType s) fun s => do\n        let p := e.updateProj! s\n        if (\u2190 dependsOn (\u2190 inferType p) s.fvarId!) then\n          return none\n        else\n          let motive \u2190 mkLambdaFVars #[s] (\u2190 mkEq e p)\n          if !(\u2190 isTypeCorrect motive) then\n            return none\n          else\n            return some motive\n      if let some motive := motive? then\n        let r \u2190 simp s\n        let eNew := e.updateProj! r.expr\n        match r.proof? with\n        | none => return { expr := eNew }\n        | some h =>\n          let hNew \u2190 mkEqNDRec motive (\u2190 mkEqRefl e) h\n          return { expr := eNew, proof? := some hNew }\n      else\n        return { expr := (\u2190 dsimp e) }\n\n  congrArgs (r : Result) (args : Array Expr) : M Result := do\n    if args.isEmpty then\n      return r\n    else\n      let infos := (\u2190 getFunInfoNArgs r.expr args.size).paramInfo\n      let mut r := r\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 \u2190 mkCongr r (\u2190 simp arg)\n        else if (\u2190 whnfD (\u2190 inferType r.expr)).isArrow then\n          r \u2190 mkCongr r (\u2190 simp arg)\n        else\n          r \u2190 mkCongrFun r (\u2190 dsimp arg)\n        i := i + 1\n      return r\n\n  visitFn (e : Expr) : M Result := do\n    let f := e.getAppFn\n    let fNew \u2190 simp f\n    if fNew.expr == f then\n      return { expr := e }\n    else\n      let args := e.getAppArgs\n      let eNew := mkAppN fNew.expr args\n      if fNew.proof?.isNone then return { expr := eNew }\n      let mut proof \u2190 fNew.getProof\n      for arg in args do\n        proof \u2190 Meta.mkCongrFun proof arg\n      return { expr := eNew, proof? := proof }\n\n  mkCongrSimp? (f : Expr) : M (Option CongrTheorem) := do\n    if f.isConst then if (\u2190 isMatcher f.constName!) then\n      -- We always use simple congruence theorems for auxiliary match applications\n      return none\n    let info \u2190 getFunInfo f\n    let kinds := getCongrSimpKinds info\n    if kinds.all fun k => match k with | CongrArgKind.fixed => true | CongrArgKind.eq => true | _ => false then\n      /- If all argument kinds are `fixed` or `eq`, then using\n         simple congruence theorems `congr`, `congrArg`, and `congrFun` produces a more compact proof -/\n      return none\n    match (\u2190 get).congrCache.find? f with\n    | some thm? => return thm?\n    | none =>\n      let thm? \u2190 mkCongrSimpCore? f info kinds\n      modify fun s => { s with congrCache := s.congrCache.insert f thm? }\n      return thm?\n\n  /-- Try to use automatically generated congruence theorems. See `mkCongrSimp?`. -/\n  tryAutoCongrTheorem? (e : Expr) : M (Option Result) := do\n    let f := e.getAppFn\n    -- TODO: cache\n    let some cgrThm \u2190 mkCongrSimp? f | return none\n    if cgrThm.argKinds.size != e.getAppNumArgs then return none\n    let mut simplified := false\n    let mut hasProof   := false\n    let mut hasCast    := false\n    let mut argsNew    := #[]\n    let mut argResults := #[]\n    let args := e.getAppArgs\n    for arg in args, kind in cgrThm.argKinds do\n      match kind with\n      | CongrArgKind.fixed => argsNew := argsNew.push arg\n      | CongrArgKind.cast  => hasCast := true; argsNew := argsNew.push arg\n      | CongrArgKind.subsingletonInst => argsNew := argsNew.push arg\n      | CongrArgKind.eq =>\n        let argResult \u2190 simp arg\n        argResults := argResults.push argResult\n        argsNew    := argsNew.push argResult.expr\n        if argResult.proof?.isSome then hasProof := true\n        if arg != argResult.expr then simplified := true\n      | _ => unreachable!\n    if !simplified then return some { expr := e }\n    if !hasProof then return some { expr := mkAppN f argsNew }\n    let mut proof := cgrThm.proof\n    let mut type  := cgrThm.type\n    let mut j := 0 -- index at argResults\n    let mut subst := #[]\n    for arg in args, kind in cgrThm.argKinds do\n      proof := mkApp proof arg\n      subst := subst.push arg\n      type := type.bindingBody!\n      match kind with\n      | CongrArgKind.fixed => pure ()\n      | CongrArgKind.cast  => pure ()\n      | CongrArgKind.subsingletonInst =>\n        let clsNew := type.bindingDomain!.instantiateRev subst\n        let instNew \u2190\n          if (\u2190 isDefEq (\u2190 inferType arg) clsNew) then\n            pure arg\n          else\n            match (\u2190 trySynthInstance clsNew) with\n            | LOption.some val => pure val\n            | _ =>\n              trace[Meta.Tactic.simp.congr] \"failed to synthesize instance{indentExpr clsNew}\"\n              return none\n        proof := mkApp proof instNew\n        subst := subst.push instNew\n        type := type.bindingBody!\n      | CongrArgKind.eq =>\n        let argResult := argResults[j]\n        let argProof \u2190 argResult.getProof\n        j := j + 1\n        proof := mkApp2 proof argResult.expr argProof\n        subst := subst.push argResult.expr |>.push argProof\n        type := type.bindingBody!.bindingBody!\n      | _ => unreachable!\n    let some (_, _, rhs) := type.instantiateRev subst |>.eq? | unreachable!\n    let rhs \u2190 if hasCast then removeUnnecessaryCasts rhs else pure rhs\n    return some { expr := rhs, proof? := proof }\n\n  congrDefault (e : Expr) : M Result := do\n    if let some result \u2190 tryAutoCongrTheorem? e then\n      mkEqTrans result (\u2190 visitFn result.expr)\n    else\n      withParent e <| e.withApp fun f args => do\n        congrArgs (\u2190 simp f) args\n\n  /- Return true iff processing the given congruence theorem hypothesis produced a non-refl proof. -/\n  processCongrHypothesis (h : Expr) : M Bool := do\n    forallTelescopeReducing (\u2190 inferType h) fun xs hType => withNewLemmas xs do\n      let lhs \u2190 instantiateMVars hType.appFn!.appArg!\n      let r \u2190 simp lhs\n      let rhs := hType.appArg!\n      rhs.withApp fun m zs => do\n        let val \u2190 mkLambdaFVars zs r.expr\n        unless (\u2190 isDefEq m val) do\n          throwCongrHypothesisFailed\n        unless (\u2190 isDefEq h (\u2190 mkLambdaFVars xs (\u2190 r.getProof))) do\n          throwCongrHypothesisFailed\n        return r.proof?.isSome\n\n  /- Try to rewrite `e` children using the given congruence theorem -/\n  trySimpCongrTheorem? (c : SimpCongrTheorem) (e : Expr) : M (Option Result) := withNewMCtxDepth do\n    trace[Debug.Meta.Tactic.simp.congr] \"{c.theoremName}, {e}\"\n    let thm \u2190 mkConstWithFreshMVarLevels c.theoremName\n    let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType thm)\n    if c.hypothesesPos.any (\u00b7 \u2265 xs.size) then\n      return none\n    let lhs := type.appFn!.appArg!\n    let rhs := type.appArg!\n    let numArgs := lhs.getAppNumArgs\n    let mut e := e\n    let mut extraArgs := #[]\n    if e.getAppNumArgs > numArgs then\n      let args := e.getAppArgs\n      e := mkAppN e.getAppFn args[:numArgs]\n      extraArgs := args[numArgs:].toArray\n    if (\u2190 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 (\u2190 processCongrHypothesis x) then\n            modified := true\n        catch ex =>\n          trace[Meta.Tactic.simp.congr] \"processCongrHypothesis {c.theoremName} failed {\u2190 inferType x}\"\n          if ex.isMaxRecDepth then\n            -- Recall that `processCongrHypothesis` invokes `simp` recursively.\n            throw ex\n          else\n            return none\n      unless modified do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} not modified\"\n        return none\n      unless (\u2190 synthesizeArgs c.theoremName xs bis (\u2190 read).discharge?) do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} synthesizeArgs failed\"\n        return none\n      let eNew \u2190 instantiateMVars rhs\n      let proof \u2190 instantiateMVars (mkAppN thm xs)\n      congrArgs { expr := eNew, proof? := proof } extraArgs\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 congrThms \u2190 getSimpCongrTheorems\n      let cs := congrThms.get f.constName!\n      for c in cs do\n        match (\u2190 trySimpCongrTheorem? 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 \u2190 reduce e\n    if !e.isApp then\n      simp e\n    else if isOfNatNatLit e then\n      -- Recall that we expand \"orphan\" kernel nat literals `n` into `ofNat n`\n      return { expr := e }\n    else\n      congr e\n\n  simpConst (e : Expr) : M Result :=\n    return { expr := (\u2190 reduce e) }\n\n  withNewLemmas {\u03b1} (xs : Array Expr) (f : M \u03b1) : M \u03b1 := do\n    if (\u2190 getConfig).contextual then\n      let mut s \u2190 getSimpTheorems\n      let mut updated := false\n      for x in xs do\n        if (\u2190 isProof x) then\n          s \u2190 s.add #[] x\n          updated := true\n      if updated then\n        withSimpTheorems 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 \u2190 simp e\n      let eNew \u2190 mkLambdaFVars xs r.expr\n      match r.proof? with\n      | none   => return { expr := eNew }\n      | some h =>\n        let p \u2190 xs.foldrM (init := h) fun x h => do\n          mkFunExt (\u2190 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 \u2190 simp p\n    trace[Debug.Meta.Tactic.simp] \"arrow [{(\u2190 getConfig).contextual}] {p} [{\u2190 isProp p}] -> {q} [{\u2190 isProp q}]\"\n    if (\u2190 pure (\u2190 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 \u2190 getSimpTheorems\n        let s \u2190 s.add #[] h\n        withSimpTheorems s do\n          let rq \u2190 simp q\n          match rq.proof? with\n          | none    => mkImpCongr rp rq\n          | some hq =>\n            let hq \u2190 mkLambdaFVars #[h] hq\n            return { expr := (\u2190 mkArrow rp.expr rq.expr), proof? := (\u2190 mkImpCongrCtx (\u2190 rp.getProof) hq) }\n    else\n      mkImpCongr rp (\u2190 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 (\u2190 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 \u2190 simp b\n        let eNew \u2190 mkForallFVars #[x] rb.expr\n        match rb.proof? with\n        | none   => return { expr := eNew }\n        | some h => return { expr := eNew, proof? := (\u2190 mkForallCongr (\u2190 mkLambdaFVars #[x] h)) }\n    else\n      return { expr := (\u2190 dsimp e) }\n\n  simpLet (e : Expr) : M Result := do\n    let Expr.letE n t v b _ := e | unreachable!\n    if (\u2190 getConfig).zeta then\n      return { expr := b.instantiate1 v }\n    else\n      match (\u2190 getSimpLetCase n t v b) with\n      | SimpLetCase.dep => return { expr := (\u2190 dsimp e) }\n      | SimpLetCase.nondep =>\n        let rv \u2190 simp v\n        withLocalDeclD n t fun x => do\n          let bx := b.instantiate1 x\n          let rbx \u2190 simp bx\n          let hb? \u2190 match rbx.proof? with\n            | none => pure none\n            | some h => pure (some (\u2190 mkLambdaFVars #[x] h))\n          let e' := mkLet n t rv.expr (\u2190 abstract rbx.expr #[x])\n          match rv.proof?, hb? with\n          | none,   none   => return { expr := e' }\n          | some h, none   => return { expr := e', proof? := some (\u2190 mkLetValCongr (\u2190 mkLambdaFVars #[x] rbx.expr) h) }\n          | _,      some h => return { expr := e', proof? := some (\u2190 mkLetCongr (\u2190 rv.getProof) h) }\n      | SimpLetCase.nondepDepVar =>\n        let v' \u2190 dsimp v\n        withLocalDeclD n t fun x => do\n          let bx := b.instantiate1 x\n          let rbx \u2190 simp bx\n          let e' := mkLet n t v' (\u2190 abstract rbx.expr #[x])\n          match rbx.proof? with\n          | none => return { expr := e' }\n          | some h =>\n            let h \u2190 mkLambdaFVars #[x] h\n            return { expr := e', proof? := some (\u2190 mkLetBodyCongr v' h) }\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 :=\n  withConfig (fun c => { c with etaStruct := ctx.config.etaStruct }) <| withReducible do\n    try\n      simp e methods ctx |>.run' {}\n    catch ex =>\n      if ex.isMaxHeartbeat then throwNestedTacticEx `simp ex else throw ex\n\npartial def isEqnThmHypothesis (e : Expr) : Bool :=\n  e.isForall && go e\nwhere\n  go (e : Expr) : Bool :=\n    if e.isForall then\n      go e.bindingBody!\n    else\n      e.isConstOf ``False\n\nabbrev Discharge := Expr \u2192 SimpM (Option Expr)\n\ndef dischargeUsingAssumption (e : Expr) : SimpM (Option Expr) := do\n  (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n    if localDecl.isAuxDecl then\n      return none\n    else if (\u2190 isDefEq e localDecl.type) then\n      return some localDecl.toExpr\n    else\n      return none\n\nnamespace DefaultMethods\nmutual\n  partial def discharge? (e : Expr) : SimpM (Option Expr) := do\n    if isEqnThmHypothesis e then\n      let r \u2190 dischargeUsingAssumption e\n      if r.isSome then\n        return r\n    let ctx \u2190 read\n    trace[Meta.Tactic.simp.discharge] \">> discharge?: {e}\"\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 \u2190 simp e { pre := pre, post := post, discharge? := discharge? }\n        if r.expr.isConstOf ``True then\n          try\n            return some (\u2190 mkOfEqTrue (\u2190 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?\nend\n\ndef methods : Methods :=\n  { pre := pre, post := post, discharge? := discharge? }\n\nend DefaultMethods\n\nend Simp\n\ndef simp (e : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM Simp.Result := do profileitM Exception \"simp\" (\u2190 getOptions) do\n  match discharge? with\n  | none   => Simp.main e ctx (methods := Simp.DefaultMethods.methods)\n  | some d => Simp.main e ctx (methods := { pre := (Simp.preDefault . d), post := (Simp.postDefault . d), discharge? := d })\n\n/--\n  Auxiliary method.\n  Given the current `target` of `mvarId`, apply `r` which is a new target and proof that it is equaal to the current one.\n-/\ndef applySimpResultToTarget (mvarId : MVarId) (target : Expr) (r : Simp.Result) : MetaM MVarId := do\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/-- 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) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) := do\n  let target \u2190 instantiateMVars (\u2190 getMVarType mvarId)\n  let r \u2190 simp target ctx discharge?\n  if r.expr.isConstOf ``True then\n    match r.proof? with\n    | some proof => assignExprMVar mvarId  (\u2190 mkOfEqTrue proof)\n    | none => assignExprMVar mvarId (mkConst ``True.intro)\n    return none\n  else\n    applySimpResultToTarget mvarId target r\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) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) :=\n  withMVarContext mvarId do\n    checkNotAssigned mvarId `simp\n    simpTargetCore mvarId ctx discharge?\n\n/--\n  Apply the result `r` for `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 applySimpResultToProp (mvarId : MVarId) (proof : Expr) (prop : Expr) (r : Simp.Result) : MetaM (Option (Expr \u00d7 Expr)) := do\n  if r.expr.isConstOf ``False then\n    match r.proof? with\n    | some eqProof => assignExprMVar mvarId (\u2190 mkFalseElim (\u2190 getMVarType mvarId) (\u2190 mkEqMP eqProof proof))\n    | none => assignExprMVar mvarId (\u2190 mkFalseElim (\u2190 getMVarType mvarId) proof)\n    return none\n  else\n    match r.proof? with\n    | some eqProof => return some ((\u2190 mkEqMP eqProof proof), r.expr)\n    | none =>\n      if r.expr != prop then\n        return some ((\u2190 mkExpectedTypeHint proof r.expr), r.expr)\n      else\n        return some (proof, r.expr)\n\ndef applySimpResultToFVarId (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) : MetaM (Option (Expr \u00d7 Expr)) := do\n  let localDecl \u2190 getLocalDecl fvarId\n  applySimpResultToProp mvarId (mkFVar fvarId) localDecl.type r\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) (discharge? : Option Simp.Discharge := none) : MetaM (Option (Expr \u00d7 Expr)) := do\n  let r \u2190 simp prop ctx discharge?\n  applySimpResultToProp mvarId proof prop r\n\ndef applySimpResultToLocalDeclCore (mvarId : MVarId) (fvarId : FVarId) (r : Option (Expr \u00d7 Expr)) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  match r with\n  | none => return none\n  | some (value, type') =>\n    let localDecl \u2190 getLocalDecl fvarId\n    if localDecl.type != type' then\n      let mvarId \u2190 assert mvarId localDecl.userName type' value\n      let mvarId \u2190 tryClear mvarId localDecl.fvarId\n      let (fvarId, mvarId) \u2190 intro1P mvarId\n      return some (fvarId, mvarId)\n    else\n      return some (fvarId, mvarId)\n\n/--\n  Simplify `simp` result to the given local declaration. Return `none` if the goal was closed.\n  This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/\ndef applySimpResultToLocalDecl (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  applySimpResultToLocalDeclCore mvarId fvarId (\u2190 applySimpResultToFVarId mvarId fvarId r)\n\ndef simpLocalDecl (mvarId : MVarId) (fvarId : FVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  withMVarContext mvarId do\n    checkNotAssigned mvarId `simp\n    let localDecl \u2190 getLocalDecl fvarId\n    let type \u2190 instantiateMVars localDecl.type\n    applySimpResultToLocalDeclCore mvarId fvarId (\u2190 simpStep mvarId (mkFVar fvarId) type ctx discharge?)\n\nabbrev FVarIdToLemmaId := FVarIdMap Name\n\ndef simpGoal (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[]) (fvarIdToLemmaId : FVarIdToLemmaId := {}) : MetaM (Option (Array FVarId \u00d7 MVarId)) := do\n  withMVarContext mvarId do\n    checkNotAssigned mvarId `simp\n    let mut mvarId := mvarId\n    let mut toAssert : Array Hypothesis := #[]\n    for fvarId in fvarIdsToSimp do\n      let localDecl \u2190 getLocalDecl fvarId\n      let type \u2190 instantiateMVars localDecl.type\n      let ctx \u2190 match fvarIdToLemmaId.find? localDecl.fvarId with\n        | none => pure ctx\n        | some thmId => pure { ctx with simpTheorems := ctx.simpTheorems.eraseCore thmId }\n      match (\u2190 simpStep mvarId (mkFVar fvarId) type ctx discharge?) with\n      | none => return none\n      | some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value }\n    if simplifyTarget then\n      match (\u2190 simpTarget mvarId ctx discharge?) with\n      | none => return none\n      | some mvarIdNew => mvarId := mvarIdNew\n    let (fvarIdsNew, mvarIdNew) \u2190 assertHypotheses mvarId toAssert\n    let mvarIdNew \u2190 tryClearMany mvarIdNew fvarIdsToSimp\n    return (fvarIdsNew, mvarIdNew)\n\ndef simpTargetStar (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM TacticResultCNM := withMVarContext mvarId do\n  trace[Meta.debug] \"simpTargetStar:\\n{mvarId}\"\n  let mut ctx := ctx\n  for h in (\u2190 getPropHyps) do\n    let localDecl \u2190 getLocalDecl h\n    let proof  := localDecl.toExpr\n    trace[Meta.debug] \"adding {localDecl.toExpr}\"\n    let simpTheorems \u2190 ctx.simpTheorems.add #[] proof\n    ctx := { ctx with simpTheorems }\n  match (\u2190 simpTarget mvarId ctx discharge?) with\n  | none => return TacticResultCNM.closed\n  | some mvarId' =>\n    trace[Meta.debug] \"simpTargetStar result:\\n{mvarId'}\"\n    if (\u2190 getMVarType mvarId) == (\u2190 getMVarType mvarId') then\n      return TacticResultCNM.noChange\n    else\n      return TacticResultCNM.modified mvarId'\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/src/Lean/Meta/Tactic/Simp/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297357103299, "lm_q2_score": 0.03622005183364063, "lm_q1q2_score": 0.009965213288403997}}
{"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.CollectFVars\nimport Lean.Meta.Match.MatchPatternAttr\nimport Lean.Meta.Match.Match\nimport Lean.Meta.SortLocalDecls\nimport Lean.Meta.GeneralizeVars\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.Arg\nimport Lean.Parser.Term\nimport Lean.Elab.PatternVar\n\nnamespace Lean.Elab.Term\nopen Meta\nopen Lean.Parser.Term\n\nprivate def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let newStx \u2190 `(let $lhsVar := $discr; $rhs)\n  withMacroExpansion stx newStx <| elabTerm newStx expectedType?\n\nprivate def mkUserNameFor (e : Expr) : TermElabM Name := do\n  match e with\n  /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/\n  | Expr.fvar fvarId _ => mkFreshUserName ((\u2190 getLocalDecl fvarId).userName)\n  | _                  => mkFreshBinderName\n\n/-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/\ndef isAuxDiscrName (n : Name) : Bool :=\n  n.hasMacroScopes && n.eraseMacroScopes == `_discr\n\n/- We treat `@x` as atomic to avoid unnecessary extra local declarations from being\n   inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier.\n   Thus this is kind of discriminant is quite common.\n\n   Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression.\n   This can happen due to error recovery. Example\n   ```\n   example : (p \u2228 p) \u2192 p := fun h => match\n   ```\n   If we don't abort, the elaborator loops because we will keep trying to expand\n   ```\n   match\n   ```\n   into\n   ```\n   let d := <Syntax.missing>; match\n   ```\n   Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/\ndef isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do\n  match discr with\n  | `($x:ident)  => isLocalIdent? x\n  | `(@$x:ident) => isLocalIdent? x\n  | _ => if discr.isMissing then throwAbortTerm else return none\n\n-- See expandNonAtomicDiscrs?\nprivate def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do\n  let term := discr[1]\n  match (\u2190 isAtomicDiscr? term) with\n  | some e@(Expr.fvar fvarId _) =>\n    let localDecl \u2190 getLocalDecl fvarId\n    if !isAuxDiscrName localDecl.userName then\n      return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`\n    else\n      instantiateMVars localDecl.value\n  | _ => throwErrorAt discr \"unexpected discriminant\"\n\nstructure ElabMatchTypeAndDiscrsResult where\n  discrs    : Array Expr\n  matchType : Expr\n  /- `true` when performing dependent elimination. We use this to decide whether we optimize the \"match unit\" case.\n     See `isMatchUnit?`. -/\n  isDep     : Bool\n  alts      : Array MatchAltView\n\nprivate partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)\n      : TermElabM ElabMatchTypeAndDiscrsResult := do\n    let numDiscrs := discrStxs.size\n    if matchOptType.isNone then\n      elabDiscrs 0 #[]\n    else\n      let matchTypeStx := matchOptType[0][1]\n      let matchType \u2190 elabType matchTypeStx\n      let (discrs, isDep) \u2190 elabDiscrsWitMatchType matchType expectedType\n      return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }\n  where\n    /- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user.  -/\n    elabDiscrsWitMatchType (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr \u00d7 Bool) := do\n      let mut discrs := #[]\n      let mut i := 0\n      let mut matchType := matchType\n      let mut isDep := false\n      for discrStx in discrStxs do\n        i := i + 1\n        matchType \u2190 whnf matchType\n        match matchType with\n        | Expr.forallE _ d b _ =>\n          let discr \u2190 fullApproxDefEq <| elabTermEnsuringType discrStx[1] d\n          trace[Elab.match] \"discr #{i} {discr} : {d}\"\n          if b.hasLooseBVars then\n            isDep := true\n          matchType \u2190 b.instantiate1 discr\n          discrs := discrs.push discr\n        | _ =>\n          throwError \"invalid type provided to match-expression, function type with arity #{discrStxs.size} expected\"\n      return (discrs, isDep)\n\n    markIsDep (r : ElabMatchTypeAndDiscrsResult) :=\n      { r with isDep := true }\n\n    /- Elaborate discriminants inferring the match-type -/\n    elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do\n      if h : i < discrStxs.size then\n        let discrStx := discrStxs.get \u27e8i, h\u27e9\n        let discr     \u2190 elabAtomicDiscr discrStx\n        let discr     \u2190 instantiateMVars discr\n        let discrType \u2190 inferType discr\n        let discrType \u2190 instantiateMVars discrType\n        let discrs    := discrs.push discr\n        let userName \u2190 mkUserNameFor discr\n        if discrStx[0].isNone then\n          let mut result \u2190 elabDiscrs (i + 1) discrs\n          let matchTypeBody \u2190 kabstract result.matchType discr\n          if matchTypeBody.hasLooseBVars then\n            result := markIsDep result\n          return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody }\n        else\n          let discrs := discrs.push (\u2190 mkEqRefl discr)\n          let result \u2190 elabDiscrs (i + 1) discrs\n          let result := markIsDep result\n          let identStx := discrStx[0][0]\n          withLocalDeclD userName discrType fun x => do\n            let eqType \u2190 mkEq discr x\n            withLocalDeclD identStx.getId eqType fun h => do\n              let matchTypeBody \u2190 kabstract result.matchType discr\n              let matchTypeBody := matchTypeBody.instantiate1 x\n              let matchType \u2190 mkForallFVars #[x, h] matchTypeBody\n              return { result with\n                matchType := matchType\n                alts      := result.alts.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx }\n              }\n      else\n        return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType }\n\ndef expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do\n  matchAlts.mapM fun matchAlt => do\n    let patterns \u2190 matchAlt.patterns.mapM expandMacros\n    pure { matchAlt with patterns := patterns }\n\nprivate def getMatchGeneralizing? : Syntax \u2192 Option Bool\n  | `(match (generalizing := true)  $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true\n  | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false\n  | _ => none\n\n/- Given `stx` a match-expression, return its alternatives. -/\nprivate def getMatchAlts : Syntax \u2192 Array MatchAltView\n  | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) =>\n    alts.filterMap fun alt => match alt with\n      | `(matchAltExpr| | $patterns,* => $rhs) => some {\n          ref      := alt,\n          patterns := patterns,\n          rhs      := rhs\n        }\n      | _ => none\n  | _ => #[]\n\nbuiltin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind\n\nopen Meta.Match (mkInaccessible inaccessible?)\n\n/--\n  The elaboration function for `Syntax` created using `mkMVarSyntax`.\n  It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/\n@[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? =>\n  return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx)\n\n@[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do\n  let e \u2190 elabTerm stx[1] expectedType?\n  return mkInaccessible e\n\nopen Lean.Elab.Term.Quotation in\n@[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck\n  | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do\n    discrs.forM precheck\n    for (pats, rhs) in patss.zip rhss do\n      let vars \u2190\n        try\n          getPatternsVars pats\n        catch\n          | _ => return  -- can happen in case of pattern antiquotations\n      Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs\n  | _ => throwUnsupportedSyntax\n\n/- We convert the collected `PatternVar`s intro `PatternVarDecl` -/\ninductive PatternVarDecl where\n  /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable\n     when it is not assigned during pattern elaboration. -/\n  | anonymousVar (mvarId : MVarId) (fvarId : FVarId)\n  | localVar     (fvarId : FVarId)\n\nprivate partial def withPatternVars {\u03b1} (pVars : Array PatternVar) (k : Array PatternVarDecl \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (decls : Array PatternVarDecl) := do\n    if h : i < pVars.size then\n      match pVars.get \u27e8i, h\u27e9 with\n      | PatternVar.anonymousVar mvarId =>\n        let type \u2190 mkFreshTypeMVar\n        let userName \u2190 mkFreshBinderName\n        withLocalDecl userName BinderInfo.default type fun x =>\n          loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!))\n      | PatternVar.localVar userName   =>\n        let type \u2190 mkFreshTypeMVar\n        withLocalDecl userName BinderInfo.default type fun x =>\n          loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!))\n    else\n      /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`.\n         Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/\n      decls.forM fun decl => match decl with\n        | PatternVarDecl.anonymousVar mvarId fvarId => do\n          let type \u2190 inferType (mkFVar fvarId)\n          discard <| mkFreshExprMVarWithId mvarId type\n        | _ => pure ()\n      k decls\n  loop 0 #[]\n\n/-\nRemark: when performing dependent pattern matching, we often had to write code such as\n\n```lean\ndef Vec.map' (f : \u03b1 \u2192 \u03b2) (xs : Vec \u03b1 n) : Vec \u03b2 n :=\n  match n, xs with\n  | _, nil       => nil\n  | _, cons a as => cons (f a) (map' f as)\n```\nWe had to include `n` and the `_`s because the type of `xs` depends on `n`.\nMoreover, `nil` and `cons a as` have different types.\nThis was quite tedious. So, we have implemented an automatic \"discriminant refinement procedure\".\nThe procedure is based on the observation that we get a type error whenenver we forget to include `_`s\nand the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant\nis an indexed family, and add their indices as new discriminants.\n\nThe current implementation, adds indices as they are found, and does not\ntry to \"sort\" the new discriminants.\n\nIf the refinement process fails, we report the original error message.\n-/\n\n/- Auxiliary structure for storing an type mismatch exception when processing the\n   pattern #`idx` of some alternative. -/\nstructure PatternElabException where\n  ex          : Exception\n  patternIdx  : Nat -- Discriminant that sh\n  pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch\n\n/--\n  This method is part of the \"discriminant refinement\" procedure. It in invoked when the\n  type of the `pattern` does not match the expected type. The expected type is based on the\n  motive computed using the `match` discriminants.\n  It tries to compute a path to an index of the discriminant type.\n  For example, suppose the user has written\n  ```\n  inductive Mem (a : \u03b1) : List \u03b1 \u2192 Prop where\n    | head {as} : Mem a (a::as)\n    | tail {as} : Mem a as \u2192 Mem a (a'::as)\n\n  infix:50 \" \u2208 \" => Mem\n\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match h with\n  | Mem.head => rfl\n  ```\n  The motive for the match is `a \u2208 [b] \u2192 b = a`, and get a type mismatch between the type\n  of `Mem.head` and `a \u2208 [b]`. This procedure return the path `[2, 1]` to the index `b`.\n  We use it to produce the following refinement\n  ```\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match b, h with\n  | _, Mem.head => rfl\n  ```\n  which produces the new motive `(x : Nat) \u2192  a \u2208 [x] \u2192 x = a`\n  After this refinement step, the `match` is elaborated successfully.\n\n  This method relies on the fact that the dependent pattern matcher compiler solves equations\n  between indices of indexed inductive families.\n  The following kinds of equations are supported by this compiler:\n  - `x = t`\n  - `t = x`\n  - `ctor ... = ctor ...`\n\n  where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor.\n  Our procedure ensures that \"information\" is not lost, and will *not* succeed in an\n  example such as\n  ```\n  example (a b : Nat) (f : Nat \u2192 Nat) (h : f a \u2208 [f b]) : f b = f a :=\n    match h with\n    | Mem.head => rfl\n  ```\n  and will not add `f b` as a new discriminant. We may add an option in the future to\n  enable this more liberal form of refinement.\n-/\nprivate partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do\n  goType (\u2190 instantiateMVars (\u2190 inferType pattern)) expected\nwhere\n  checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do\n    guard d.isApp\n    guard <| t.getAppNumArgs == d.getAppNumArgs\n    let tFn := t.getAppFn\n    let dFn := d.getAppFn\n    guard <| tFn.isConst && dFn.isConst\n    guard (\u2190 isDefEq tFn dFn)\n\n  -- Visitor for inductive types\n  goType (t d : Expr) : OptionT MetaM (List Nat) := do\n    trace[Meta.debug] \"type {t} =?= {d}\"\n    let t \u2190 whnf t\n    let d \u2190 whnf d\n    checkCompatibleApps t d\n    matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do\n      let tArgs := t.getAppArgs\n      let dArgs := d.getAppArgs\n      for i in [:info.numParams] do\n        let tArg := tArgs[i]\n        let dArg := dArgs[i]\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goType tArg dArg)\n      for i in [info.numParams : tArgs.size] do\n        let tArg := tArgs[i]\n        let dArg := dArgs[i]\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goIndex tArg dArg)\n      failure\n\n  -- Visitor for indexed families\n  goIndex (t d : Expr) : OptionT MetaM (List Nat) := do\n    let t \u2190 whnfD t\n    let d \u2190 whnfD d\n    if t.isFVar || d.isFVar then\n      return [] -- Found refinement path\n    else\n      trace[Meta.debug] \"index {t} =?= {d}\"\n      checkCompatibleApps t d\n      matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do\n        let tArgs := t.getAppArgs\n        let dArgs := d.getAppArgs\n        for i in [:info.numParams] do\n          let tArg := tArgs[i]\n          let dArg := dArgs[i]\n          unless (\u2190 isDefEq tArg dArg) do\n            failure\n        for i in [info.numParams : tArgs.size] do\n          let tArg := tArgs[i]\n          let dArg := dArgs[i]\n          unless (\u2190 isDefEq tArg dArg) do\n            return i :: (\u2190 goIndex tArg dArg)\n        failure\n\nprivate partial def eraseIndices (type : Expr) : MetaM Expr := do\n  let type' \u2190 whnfD type\n  matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do\n    let args := type'.getAppArgs\n    let params \u2190 args[:info.numParams].toArray.mapM eraseIndices\n    let result := mkAppN type'.getAppFn params\n    let resultType \u2190 inferType result\n    let (newIndices, _, _) \u2190  forallMetaTelescopeReducing resultType (some (args.size - info.numParams))\n    return mkAppN result newIndices\n\nprivate def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr \u00d7 Expr) :=\n  withReader (fun ctx => { ctx with implicitLambda := false }) do\n    let mut patterns  := #[]\n    let mut matchType := matchType\n    for idx in [:patternStxs.size] do\n      let patternStx := patternStxs[idx]\n      matchType \u2190 whnf matchType\n      match matchType with\n      | Expr.forallE _ d b _ =>\n        let pattern \u2190 do\n          let s \u2190 saveState\n          try\n            liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d\n          catch ex : Exception =>\n            restoreState s\n            match (\u2190 liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (\u2190 eraseIndices d)) with\n            | some pattern =>\n              match (\u2190 findDiscrRefinementPath pattern d |>.run) with\n              | some path =>\n                trace[Meta.debug] \"refinement path: {path}\"\n                restoreState s\n                -- Wrap the type mismatch exception for the \"discriminant refinement\" feature.\n                throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path }\n              | none => restoreState s; throw ex\n            | none => throw ex\n        matchType := b.instantiate1 pattern\n        patterns  := patterns.push pattern\n      | _ => throwError \"unexpected match type\"\n    return (patterns, matchType)\n\ndef finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do\n  let mut decls := #[]\n  for pdecl in patternVarDecls do\n    match pdecl with\n    | PatternVarDecl.localVar fvarId =>\n      let decl \u2190 getLocalDecl fvarId\n      let decl \u2190 instantiateLocalDeclMVars decl\n      decls := decls.push decl\n    | PatternVarDecl.anonymousVar mvarId fvarId =>\n       let e \u2190 instantiateMVars (mkMVar mvarId);\n       trace[Elab.match] \"finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}\"\n       match e with\n       | Expr.mvar newMVarId _ =>\n         /- Metavariable was not assigned, or assigned to another metavariable. So,\n            we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/\n         assignExprMVar newMVarId (mkFVar fvarId)\n         trace[Elab.match] \"finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}\"\n         let decl \u2190 getLocalDecl fvarId\n         let decl \u2190 instantiateLocalDeclMVars decl\n         decls := decls.push decl\n       | _ => pure ()\n  /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d\u2081 may occur after d\u2082 when d\u2082 depends on d\u2081. -/\n  sortLocalDecls decls\n\nopen Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)\n\nnamespace ToDepElimPattern\n\nstructure State where\n  found      : NameSet := {}\n  localDecls : Array LocalDecl\n  newLocals  : NameSet := {}\n\nabbrev M := StateRefT State TermElabM\n\nprivate def alreadyVisited (fvarId : FVarId) : M Bool := do\n  let s \u2190 get\n  return s.found.contains fvarId\n\nprivate def markAsVisited (fvarId : FVarId) : M Unit :=\n  modify fun s => { s with found := s.found.insert fvarId }\n\nprivate def throwInvalidPattern {\u03b1} (e : Expr) : M \u03b1 :=\n  throwError \"invalid pattern {indentExpr e}\"\n\n/- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/\nprivate def mkLocalDeclFor (mvar : Expr) : M Pattern := do\n  let mvarId := mvar.mvarId!\n  let s \u2190 get\n  match (\u2190 getExprMVarAssignment? mvarId) with\n  | some val => return Pattern.inaccessible val\n  | none =>\n    let fvarId \u2190 mkFreshId\n    let type   \u2190 inferType mvar\n    /- HACK: `fvarId` is not in the scope of `mvarId`\n       If this generates problems in the future, we should update the metavariable declarations. -/\n    assignExprMVar mvarId (mkFVar fvarId)\n    let userName \u2190 mkFreshBinderName\n    let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default;\n    modify fun s =>\n      { s with\n        newLocals  := s.newLocals.insert fvarId,\n        localDecls :=\n        match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with\n        | none   => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar`\n        | some i => s.localDecls.insertAt i newDecl }\n    return Pattern.var fvarId\n\npartial def main (e : Expr) : M Pattern := do\n  let isLocalDecl (fvarId : FVarId) : M Bool := do\n    return (\u2190 get).localDecls.any fun d => d.fvarId == fvarId\n  let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do\n    if (\u2190 alreadyVisited fvarId) then\n      return Pattern.inaccessible e\n    else\n      markAsVisited fvarId\n      return Pattern.var e.fvarId!\n  let mkInaccessible (e : Expr) : M Pattern := do\n    match e with\n    | Expr.fvar fvarId _ =>\n      if (\u2190 isLocalDecl fvarId) then\n        mkPatternVar fvarId e\n      else\n        return Pattern.inaccessible e\n    | _ =>\n      return Pattern.inaccessible e\n  match inaccessible? e with\n  | some t => mkInaccessible t\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) =>\n      return Pattern.arrayLit \u03b1 (\u2190 lits.mapM main)\n    | none =>\n      if e.isAppOfArity `namedPattern 3 then\n        let p \u2190 main <| e.getArg! 2\n        match e.getArg! 1 with\n        | Expr.fvar fvarId _ => return Pattern.as fvarId p\n        | _                  => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if e.isNatLit || e.isStringLit || e.isCharLit then\n        return Pattern.val e\n      else if e.isFVar then\n        let fvarId := e.fvarId!\n        unless (\u2190 isLocalDecl fvarId) do\n          throwInvalidPattern e\n        mkPatternVar fvarId e\n      else if e.isMVar then\n        mkLocalDeclFor e\n      else\n        let newE \u2190 whnf e\n        if newE != e then\n          main newE\n        else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do\n          let args := e.getAppArgs\n          unless args.size == v.numParams + v.numFields do\n            throwInvalidPattern e\n          let params := args.extract 0 v.numParams\n          let fields := args.extract v.numParams args.size\n          let fields \u2190 fields.mapM main\n          return Pattern.ctor v.name us params.toList fields.toList\n\nend ToDepElimPattern\n\ndef withDepElimPatterns {\u03b1} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl \u2192 Array Pattern \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (patterns, s) \u2190 (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls }\n  let localDecls \u2190 s.localDecls.mapM fun d => instantiateLocalDeclMVars d\n  /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/\n  let lctx \u2190 getLCtx\n  let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx\n  let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx\n  withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do\n    k localDecls patterns\n\nprivate def withElaboratedLHS {\u03b1} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)\n    (k : AltLHS \u2192 Expr \u2192 TermElabM \u03b1) : ExceptT PatternElabException TermElabM \u03b1 := do\n  let (patterns, matchType) \u2190 withSynthesize <| elabPatterns patternStxs matchType\n  id (\u03b1 := TermElabM \u03b1) do\n    let localDecls \u2190 finalizePatternDecls patternVarDecls\n    let patterns \u2190 patterns.mapM (instantiateMVars \u00b7)\n    withDepElimPatterns localDecls patterns fun localDecls patterns =>\n      k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType\n\nprivate def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS \u00d7 Expr) := withRef alt.ref do\n  let (patternVars, alt) \u2190 collectPatternVars alt\n  trace[Elab.match] \"patternVars: {patternVars}\"\n  withPatternVars patternVars fun patternVarDecls => do\n    withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do\n      let rhs \u2190 elabTermEnsuringType alt.rhs matchType\n      let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr\n      let rhs \u2190 if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs\n      trace[Elab.match] \"rhs: {rhs}\"\n      return (altLHS, rhs)\n\n/--\n  Collect problematic index for the \"discriminant refinement feature\". This method is invoked\n  when we detect a type mismatch at a pattern #`idx` of some alternative. -/\nprivate partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do\n  go (\u2190 inferType discr) pathToIndex |>.run\nwhere\n  go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do\n    match path with\n    | [] => return e\n    | i::path =>\n      let e \u2190 whnfD e\n      guard <| e.isApp && i < e.getAppNumArgs\n      go (e.getArg! i) path\n\n/--\n  \"Generalize\" variables that depend on the discriminants.\n\n  Remarks and limitations:\n  - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`.\n    Motivation: users should have control about the actual `match`-expressions in their programs.\n  - We currently do not generalize let-decls.\n  - We abort generalization if the new `matchType` is type incorrect.\n  - Only discriminants that are free variables are considered during specialization.\n  - We \"generalize\" by adding new discriminants and pattern variables. We do not \"clear\" the generalized variables,\n    but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since\n    this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode.\n-/\nprivate def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr \u00d7 Expr \u00d7 Array MatchAltView \u00d7 Bool) := do\n  let gen \u2190\n    match generalizing? with\n    | some g => pure g\n    | _ => isProp matchType\n  if !gen then\n    return (discrs, matchType, altViews, false)\n  else\n    let ysFVarIds \u2190 getFVarsToGeneralize discrs\n    /- let-decls are currently being ignored by the generalizer. -/\n    let ysFVarIds \u2190 ysFVarIds.filterM fun fvarId => return !(\u2190 getLocalDecl fvarId).isLet\n    if ysFVarIds.isEmpty then\n      return (discrs, matchType, altViews, false)\n    else\n      let ys := ysFVarIds.map mkFVar\n      -- trace[Meta.debug] \"ys: {ys}, discrs: {discrs}\"\n      let matchType' \u2190 forallBoundedTelescope matchType discrs.size fun ds type => do\n        let type \u2190 mkForallFVars ys type\n        let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar\n        let type := type.replaceFVars discrs' ds'\n        mkForallFVars ds type\n      -- trace[Meta.debug] \"matchType': {matchType'}\"\n      if (\u2190 isTypeCorrect matchType') then\n        let discrs := discrs ++ ys\n        let altViews \u2190 altViews.mapM fun altView => do\n          let patternVars \u2190 getPatternsVars altView.patterns\n          -- We traverse backwards because we want to keep the most recent names.\n          -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`,\n          -- since it is already shadowed by the second.\n          let ysUserNames \u2190 ys.foldrM (init := #[]) fun ys ysUserNames => do\n            let yDecl \u2190 getLocalDecl ys.fvarId!\n            let mut yUserName := yDecl.userName\n            if ysUserNames.contains yUserName then\n              yUserName \u2190 mkFreshUserName yUserName\n            -- Explicitly provided pattern variables shadow `y`\n            else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then\n              yUserName \u2190 mkFreshUserName yUserName\n            return ysUserNames.push yUserName\n          let ysIds \u2190 ysUserNames.reverse.mapM fun n => return mkIdentFrom (\u2190 getRef) n\n          return { altView with patterns := altView.patterns ++ ysIds }\n        return (discrs, matchType', altViews, true)\n      else\n        return (discrs, matchType, altViews, true)\n\nprivate partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n  loop discrs matchType altViews none\nwhere\n  /-\n    \"Discriminant refinement\" main loop.\n    `first?` contains the first error message we found before updated the `discrs`. -/\n  loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState \u00d7 Exception))\n      : TermElabM (Array Expr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n    let s \u2190 saveState\n    let (discrs', matchType', altViews', refined) \u2190 generalize discrs matchType altViews generalizing?\n    match (\u2190 altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run) with\n    | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined)\n    | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } =>\n      trace[Meta.debug] \"pathToIndex: {toString pathToIndex}\"\n      let some index \u2190 getIndexToInclude? discrs[patternIdx] pathToIndex\n        | throwEx (\u2190 updateFirst first? ex)\n      trace[Meta.debug] \"index: {index}\"\n      if (\u2190 discrs.anyM fun discr => isDefEq discr index) then\n        throwEx (\u2190 updateFirst first? ex)\n      let first \u2190 updateFirst first? ex\n      s.restore\n      let indices \u2190 collectDeps #[index] discrs\n      let matchType \u2190\n        try\n          updateMatchType indices matchType\n        catch ex =>\n          throwEx first\n      let altViews  \u2190 addWildcardPatterns indices.size altViews\n      let discrs    := indices ++ discrs\n      loop discrs matchType altViews first\n\n  throwEx {\u03b1} (p : SavedState \u00d7 Exception) : TermElabM \u03b1 := do\n    p.1.restore; throw p.2\n\n  updateFirst (first? : Option (SavedState \u00d7 Exception)) (ex : Exception) : TermElabM (SavedState \u00d7 Exception) := do\n    match first? with\n    | none       => return (\u2190 saveState, ex)\n    | some first => return first\n\n  containsFVar (es : Array Expr) (fvarId : FVarId) : Bool :=\n    es.any fun e => e.isFVar && e.fvarId! == fvarId\n\n  /- Update `indices` by including any free variable `x` s.t.\n     - Type of some `discr` depends on `x`.\n     - Type of `x` depends on some free variable in `indices`.\n\n     If we don't include these extra variables in indices, then\n     `updateMatchType` will generate a type incorrect term.\n     For example, suppose `discr` contains `h : @HEq \u03b1 a \u03b1 b`, and\n     `indices` is `#[\u03b1, b]`, and `matchType` is `@HEq \u03b1 a \u03b1 b \u2192 B`.\n     `updateMatchType indices matchType` produces the type\n     `(\u03b1' : Type) \u2192 (b : \u03b1') \u2192 @HEq \u03b1' a \u03b1' b \u2192 B` which is type incorrect\n     because we have `a : \u03b1`.\n     The method `collectDeps` will include `a` into `indices`.\n\n     This method does not handle dependencies among non-free variables.\n     We rely on the type checking method `check` at `updateMatchType`.\n\n     Remark: `indices : Array Expr` does not need to be an array anymore.\n     We should cleanup this code, and use `index : Expr` instead.\n   -/\n  collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do\n    let mut s : CollectFVars.State := {}\n    for discr in discrs do\n      s := collectFVars s (\u2190 instantiateMVars (\u2190 inferType discr))\n    let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar\n    let indicesFVar := indicesFVar.map Expr.fvarId!\n    let mut toAdd := #[]\n    for fvarId in s.fvarSet.toList do\n      unless containsFVar discrs fvarId || containsFVar indices fvarId do\n        let localDecl \u2190 getLocalDecl fvarId\n        let mctx \u2190 getMCtx\n        for indexFVarId in indicesFVar do\n          if mctx.localDeclDependsOn localDecl indexFVarId then\n            toAdd := toAdd.push fvarId\n    let lctx \u2190 getLCtx\n    let indicesFVar := (indicesFVar ++ toAdd).qsort fun fvarId\u2081 fvarId\u2082 =>\n      (lctx.get! fvarId\u2081).index < (lctx.get! fvarId\u2082).index\n    return indicesFVar.map mkFVar ++ indicesNonFVar\n\n  updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do\n    let matchType \u2190 indices.foldrM (init := matchType) fun index matchType => do\n      let indexType \u2190 inferType index\n      let matchTypeBody \u2190 kabstract matchType index\n      let userName \u2190 mkUserNameFor index\n      return Lean.mkForall userName BinderInfo.default indexType matchTypeBody\n    check matchType\n    return matchType\n\n  addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do\n    let hole := mkHole (\u2190 getRef)\n    let wildcards := mkArray num hole\n    return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns }\n\ndef mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult :=\n  Meta.Match.mkMatcher input\n\nregister_builtin_option match.ignoreUnusedAlts : Bool := {\n  defValue := false\n  descr := \"if true, do not generate error if an alternative is not used\"\n}\n\ndef reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do\n  unless result.counterExamples.isEmpty do\n    withHeadRefOnly <| logError m!\"missing cases:\\n{Meta.Match.counterExamplesToMessageData result.counterExamples}\"\n  unless match.ignoreUnusedAlts.get (\u2190 getOptions) || result.unusedAltIdxs.isEmpty do\n    let mut i := 0\n    for alt in altLHSS do\n      if result.unusedAltIdxs.contains i then\n        withRef alt.ref do\n          logError \"redundant alternative\"\n      i := i + 1\n\n/--\n  If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]`\n  Otherwise, return none.\n-/\nprivate def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do\n  assert! altLHSS.length == rhss.size\n  match altLHSS with\n  | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] =>\n    /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/\n    match rhss[0] with\n    | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b\n    | _ => return none\n  | _ => return none\nprivate def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr)\n    : TermElabM Expr := do\n  let mut generalizing? := generalizing?\n  if !matchOptType.isNone then\n    if generalizing? == some true then\n      throwError \"the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided\"\n    generalizing? := some false\n  let (discrs, matchType, altLHSS, isDep, rhss) \u2190 commitIfDidNotPostpone do\n    let \u27e8discrs, matchType, isDep, altViews\u27e9 \u2190 elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType\n    let matchAlts \u2190 liftMacroM <| expandMacrosInPatterns altViews\n    trace[Elab.match] \"matchType: {matchType}\"\n    let (discrs, matchType, alts, refined) \u2190 elabMatchAltViews generalizing? discrs matchType matchAlts\n    let isDep := isDep || refined\n    /-\n     We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be\n     able to elaborate examples such as:\n     ```\n     def f (x : Nat) : Option Nat := none\n\n     def g (xs : List (Nat \u00d7 Nat)) : IO Unit :=\n     xs.forM fun x =>\n       match f x.fst with\n       | _ => pure ()\n     ```\n     If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because\n     the type of `x` is only available after we proces the last argument of `List.forM`.\n\n     We apply pending default types to make sure we can process examples such as\n     ```\n     let (a, b) := (0, 0)\n     ```\n    -/\n    synthesizeSyntheticMVarsUsingDefault\n    let rhss := alts.map Prod.snd\n    let matchType \u2190 instantiateMVars matchType\n    let altLHSS \u2190 alts.toList.mapM fun alt => do\n      let altLHS \u2190 Match.instantiateAltLHSMVars alt.1\n      /- Remark: we try to postpone before throwing an error.\n         The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed.\n         The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here.\n         Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here.\n         ```\n          def bad (ps : Array (Nat \u00d7 Nat)) : Array (Nat \u00d7 Nat) :=\n            (ps.filter fun (p : Prod _ _) =>\n              match p with\n              | (x, y) => x == 0)\n            ++\n            ps\n         ```\n         When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet\n         because `Array.filter` has type `{\u03b1 : Type u_1} \u2192 (\u03b1 \u2192 Bool) \u2192 (as : Array \u03b1) \u2192 optParam Nat 0 \u2192 optParam Nat (Array.size as) \u2192 Array \u03b1`\n         However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`.\n      -/\n      withRef altLHS.ref do\n        for d in altLHS.fvarDecls do\n            if d.hasExprMVar then\n            withExistingLocalDecls altLHS.fvarDecls do\n              tryPostpone\n              throwMVarError m!\"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}\"\n        for p in altLHS.patterns do\n          if p.hasExprMVar then\n            withExistingLocalDecls altLHS.fvarDecls do\n              tryPostpone\n              throwMVarError m!\"invalid match-expression, pattern contains metavariables{indentExpr (\u2190 p.toExpr)}\"\n        pure altLHS\n    return (discrs, matchType, altLHSS, isDep, rhss)\n  if let some r \u2190 if isDep then pure none else isMatchUnit? altLHSS rhss then\n    return r\n  else\n    let numDiscrs := discrs.size\n    let matcherName \u2190 mkAuxName `match\n    let matcherResult \u2190 mkMatcher { matcherName, matchType, numDiscrs, lhss := altLHSS }\n    matcherResult.addMatcher\n    let motive \u2190 forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType\n    reportMatcherResultErrors altLHSS matcherResult\n    let r := mkApp matcherResult.matcher motive\n    let r := mkAppN r discrs\n    let r := mkAppN r rhss\n    trace[Elab.match] \"result: {r}\"\n    return r\n\nprivate def getDiscrs (matchStx : Syntax) : Array Syntax :=\n  matchStx[2].getSepArgs\n\nprivate def getMatchOptType (matchStx : Syntax) : Syntax :=\n  matchStx[3]\n\nprivate def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=\n  let matchOptType := getMatchOptType matchStx;\n  if matchOptType.isNone then do\n    let discrs := getDiscrs matchStx;\n    let allLocal \u2190 discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1]\n    if allLocal then\n      return none\n    else\n      -- We use `foundFVars` to make sure the discriminants are distinct variables.\n      -- See: code for computing \"matchType\" at `elabMatchTypeAndDiscrs`\n      let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : NameSet) := do\n        match discrs with\n        | [] =>\n          let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx \", \");\n          pure (matchStx.setArg 2 discrs)\n        | discr :: discrs =>\n          -- Recall that\n          -- matchDiscr := leading_parser optional (ident >> \":\") >> termParser\n          let term := discr[1]\n          let addAux : TermElabM Syntax := withFreshMacroScope do\n            let d \u2190 `(_discr);\n            unless isAuxDiscrName d.getId do -- Use assertion?\n              throwError \"unexpected internal auxiliary discriminant name\"\n            let discrNew := discr.setArg 1 d;\n            let r \u2190 loop discrs (discrsNew.push discrNew) foundFVars\n            `(let _discr := $term; $r)\n          match (\u2190 isAtomicDiscr? term) with\n          | some x  => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux\n          | none    => addAux\n      return some (\u2190 loop discrs.toList #[] {})\n  else\n    -- We do not pull non atomic discriminants when match type is provided explicitly by the user\n    return none\n\nprivate def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  match expectedType? with\n    | some expectedType => pure expectedType\n    | none              => mkFreshTypeMVar\n\nprivate def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do\n  -- We don't wait for the discriminants types when match type is provided by user\n  if getMatchOptType matchStx |>.isNone then\n    let discrs := getDiscrs matchStx\n    for discr in discrs do\n      let term := discr[1]\n      match (\u2190 isAtomicDiscr? term) with\n      | none   => throwErrorAt discr \"unexpected discriminant\" -- see `expandNonAtomicDiscrs?\n      | some d =>\n        let dType \u2190 inferType d\n        trace[Elab.match] \"discr {d} : {dType}\"\n        tryPostponeIfMVar dType\n\n/-\nWe (try to) elaborate a `match` only when the expected type is available.\nIf the `matchType` has not been provided by the user, we also try to postpone elaboration if the type\nof a discriminant is not available. That is, it is of the form `(?m ...)`.\nWe use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables.\nThis is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.\nSuppose, we are trying to elaborate\n```\nmatch g x with\n  | ... => ...\n```\n`expandNonAtomicDiscrs?` converts it intro\n```\nlet _discr := g x\nmatch _discr with\n  | ... => ...\n```\nThus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`.\nNote that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`.\n\nThis elaboration technique is needed to elaborate terms such as:\n```lean\nxs.filter fun (a, b) => a > b\n```\nwhich are syntax sugar for\n```lean\nList.filter (fun p => match p with | (a, b) => a > b) xs\n```\nWhen we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.\n-/\nprivate def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  tryPostponeIfDiscrTypeIsMVar matchStx\n  match expectedType? with\n  | some expectedType => return expectedType\n  | none              => mkFreshTypeMVar\n\n/-\n```\nleading_parser:leadPrec \"match \" >> sepBy1 matchDiscr \", \" >> optType >> \" with \" >> matchAlts\n```\nRemark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.\n-/\nprivate def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 waitExpectedTypeAndDiscrs stx expectedType?\n  let discrStxs := (getDiscrs stx).map fun d => d\n  let gen?         := getMatchGeneralizing? stx\n  let altViews     := getMatchAlts stx\n  let matchOptType := getMatchOptType stx\n  elabMatchAux gen? discrStxs altViews matchOptType expectedType\n\nprivate def isPatternVar (stx : Syntax) : TermElabM Bool := do\n  match (\u2190 resolveId? stx \"pattern\") with\n  | none   => isAtomicIdent stx\n  | some f => match f with\n    | Expr.const fName _ _ =>\n      match (\u2190 getEnv).find? fName with\n      | some (ConstantInfo.ctorInfo _) => return false\n      | some _                         => return !hasMatchPatternAttribute (\u2190 getEnv) fName\n      | _                              => isAtomicIdent stx\n    | _ => isAtomicIdent stx\nwhere\n  isAtomicIdent (stx : Syntax) : Bool :=\n    stx.isIdent && stx.getId.eraseMacroScopes.isAtomic\n\n-- leading_parser \"match \" >> sepBy1 termParser \", \" >> optType >> \" with \" >> matchAlts\n@[builtinTermElab \u00abmatch\u00bb] def elabMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(match $discr:term with | $y:ident => $rhs:term) =>\n     if (\u2190 isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?\n  | _ => elabMatchDefault stx expectedType?\nwhere\n  elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n    match (\u2190 expandNonAtomicDiscrs? stx) with\n    | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n    | none =>\n      let discrs       := getDiscrs stx;\n      let matchOptType := getMatchOptType stx;\n      if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then\n        throwErrorAt matchOptType \"match expected type should not be provided when discriminants with equality proofs are used\"\n      elabMatchCore stx expectedType?\n\nbuiltin_initialize\n  registerTraceClass `Elab.match\n\n-- leading_parser:leadPrec \"nomatch \" >> termParser\n@[builtinTermElab \u00abnomatch\u00bb] def elabNoMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(nomatch $discrExpr) =>\n    match (\u2190 isLocalIdent? discrExpr) with\n    | some _ =>\n      let expectedType \u2190 waitExpectedType expectedType?\n      let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]\n      elabMatchAux none #[discr] #[] mkNullNode expectedType\n    | _ =>\n      let stxNew \u2190 `(let _discr := $discrExpr; nomatch _discr)\n      withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | _ => throwUnsupportedSyntax\n\nend Lean.Elab.Term\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Elab/Match.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.039638839668221494, "lm_q1q2_score": 0.009945891730051944}}
{"text": "import sheaves.sheaf_of_rings Kenny.sheaf_on_opens ring_theory.subring\n\nuniverses v w u\u2081 v\u2081 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) : \u03a0 (V : opens X), V \u2264 U \u2192 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) : \u03a0 (V : opens X) (HVU : V \u2264 U) (W : opens X) (HWU : W \u2264 U) (HWV : W \u2264 V), F.to_sheaf_on_opens.eval V HVU \u2192 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 \u2264 U) (W : opens X) (HWU : W \u2264 U) (HWV : W \u2264 V)\nvariables (x y : F.to_sheaf_on_opens.eval V HVU) (n : \u2115)\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 : \u2200 i : OC.\u03b3, 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 : \u03a0 i : OC.\u03b3, F.to_sheaf_on_opens.eval (OC.Uis i) (le_trans (subset_covering i) HVU))\n--   (H : \u2200 i j : OC.\u03b3, F.to_sheaf_on_opens.res _ _ (OC.Uis i \u2293 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 \u2293 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 : \u03a0 i : OC.\u03b3, F.to_sheaf_on_opens.eval (OC.Uis i) (le_trans (subset_covering i) HVU)) (H t)\n--   (ht : \u2200 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 $ \u03bb i, by rw [res_glue, ht]\n\ndef res_subset (F : sheaf_of_rings_on_opens X U) (V : opens X) (HVU : V \u2264 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 \u2208 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 \u2208 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 \u2208 U) (V : opens X) (hxV : x \u2208 V) (HVU : V \u2264 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 \u2208 U) (V : opens X) (hxV : x \u2208 V) (HVU : V \u2264 U)\nvariables (s t : F.to_sheaf_on_opens.eval V HVU) (n : \u2115)\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 \u2208 U) (V : opens X) (hxV : x \u2208 V) (HVU : V \u2264 U)\n  (W : opens X) (hxW : x \u2208 W) (HWV : W \u2264 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 \u2208 U}\n  {C : F.to_sheaf_on_opens.stalk x hx \u2192 Prop} (g : F.to_sheaf_on_opens.stalk x hx)\n  (H : \u2200 V : opens X, \u2200 hxV : x \u2208 V, \u2200 HVU : V \u2264 U, \u2200 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 $ \u03bb e,\nhave (\u27e6e\u27e7 : F.to_sheaf_on_opens.stalk x hx) = \u27e6\u27e8e.1 \u2293 U, \u27e8e.2, hx\u27e9, F.F.res _ _ (set.inter_subset_left _ _) e.3\u27e9\u27e7,\nfrom quotient.sound \u27e8e.1 \u2293 U, \u27e8e.2, hx\u27e9, set.inter_subset_left _ _, set.subset.refl _,\n  by dsimp only [to_sheaf_on_opens]; rw \u2190 presheaf.Hcomp'; refl\u27e9,\nthis.symm \u25b8 H (e.1 \u2293 U) \u27e8e.2, hx\u27e9 inf_le_right _\n\n@[elab_as_eliminator] theorem stalk.induction_on\u2082 {F : sheaf_of_rings_on_opens X U} {x : X} {hx : x \u2208 U}\n  {C : F.to_sheaf_on_opens.stalk x hx \u2192 F.to_sheaf_on_opens.stalk x hx \u2192 Prop} (g1 g2 : F.to_sheaf_on_opens.stalk x hx)\n  (H : \u2200 V : opens X, \u2200 hxV : x \u2208 V, \u2200 HVU : V \u2264 U, \u2200 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\u2082 g1 g2 $ \u03bb e1 e2,\nhave h1 : (\u27e6e1\u27e7 : F.to_sheaf_on_opens.stalk x hx) = _root_.to_stalk F.F x (e1.1 \u2293 e2.1 \u2293 U) \u27e8\u27e8e1.2, e2.2\u27e9, hx\u27e9 (F.F.res _ _ (\u03bb p hp, hp.1.1) e1.3),\nby erw [_root_.to_stalk_res]; cases e1; refl,\nhave h2 : (\u27e6e2\u27e7 : F.to_sheaf_on_opens.stalk x hx) = _root_.to_stalk F.F x (e1.1 \u2293 e2.1 \u2293 U) \u27e8\u27e8e1.2, e2.2\u27e9, hx\u27e9 (F.F.res _ _ (\u03bb p hp, hp.1.2) e2.3),\nby erw [_root_.to_stalk_res]; cases e2; refl,\nh1.symm \u25b8 h2.symm \u25b8 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(\u03b7 : F.to_sheaf_on_opens.morphism G.to_sheaf_on_opens)\n[hom : \u2200 V HV, is_ring_hom (\u03b7.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 (\u03b7 : F.morphism G) (V : opens X) (HVU : V \u2264 U) (x y : F.to_sheaf_on_opens.eval V HVU) (n : \u2115)\n@[simp] lemma map_add : \u03b7.1.map V HVU (x + y) = \u03b7.1.map V HVU x + \u03b7.1.map V HVU y := is_ring_hom.map_add _\n@[simp] lemma map_zero : \u03b7.1.map V HVU 0 = 0 := is_ring_hom.map_zero _\n@[simp] lemma map_neg : \u03b7.1.map V HVU (-x) = -\u03b7.1.map V HVU x := is_ring_hom.map_neg _\n@[simp] lemma map_sub : \u03b7.1.map V HVU (x - y) = \u03b7.1.map V HVU x - \u03b7.1.map V HVU y := is_ring_hom.map_sub _\n@[simp] lemma map_mul : \u03b7.1.map V HVU (x * y) = \u03b7.1.map V HVU x * \u03b7.1.map V HVU y := is_ring_hom.map_mul _\n@[simp] lemma map_one : \u03b7.1.map V HVU 1 = 1 := is_ring_hom.map_one _\n@[simp] lemma map_pow : \u03b7.1.map V HVU (x^n) = (\u03b7.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{ \u03b7 := sheaf_on_opens.morphism.id _,\n  hom := \u03bb _ _, 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\u2081} X U}\n  (\u03b7 : G.morphism H) (\u03be : F.morphism G) : F.morphism H :=\n{ \u03b7 := \u03b7.1.comp \u03be.1,\n  hom := \u03bb _ _, 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\u2081} X U}\n  (\u03b7 : G.morphism H) (\u03be : F.morphism G) (V HV s) :\n  (\u03b7.comp \u03be).1.1 V HV s = \u03b7.1.1 V HV (\u03be.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  {\u03b7 \u03be : F.morphism G} (H : \u2200 V HV x, \u03b7.1.map V HV x = \u03be.1.map V HV x) : \u03b7 = \u03be :=\nby cases \u03b7; cases \u03be; 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} (\u03b7 : F.morphism G) :\n  (morphism.id G).comp \u03b7 = \u03b7 :=\next $ \u03bb 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} (\u03b7 : F.morphism G) :\n  \u03b7.comp (morphism.id F) = \u03b7 :=\next $ \u03bb 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\u2081} X U} {I : sheaf_of_rings_on_opens.{v\u2081} X U}\n  (\u03b7 : H.morphism I) (\u03be : G.morphism H) (\u03c7 : F.morphism G) :\n  (\u03b7.comp \u03be).comp \u03c7 = \u03b7.comp (\u03be.comp \u03c7) :=\nrfl\n\ndef res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (\u03b7 : F.morphism G) (V : opens X) (HVU : V \u2264 U) :\n  (F.res_subset V HVU).morphism (G.res_subset V HVU) :=\n{ \u03b7 := \u03b7.1.res_subset V HVU,\n  hom := \u03bb _ _, \u03b7.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} (\u03b7 : F.morphism G) (V : opens X) (HVU : V \u2264 U)\n  (W HWV s) : (\u03b7.res_subset V HVU).1.1 W HWV s = \u03b7.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\u2081} X U}\n  (\u03b7 : G.morphism H) (\u03be : F.morphism G) (V : opens X) (HVU : V \u2264 U) :\n  (\u03b7.res_subset V HVU).comp (\u03be.res_subset V HVU) = (\u03b7.comp \u03be).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 \u2264 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} (\u03b7 : F.morphism G) (x : X) (hx : x \u2208 U)\n--   (s : F.to_sheaf_on_opens.stalk x hx) : G.to_sheaf_on_opens.stalk x hx :=\n-- quotient.lift_on s (\u03bb g, \u27e6(\u27e8g.1 \u2293 U, (\u27e8g.2, hx\u27e9 : x \u2208 g.1 \u2293 U),\n--   \u03b7.1.map _ inf_le_right (presheaf.res F.1.1 _ _ (set.inter_subset_left _ _) g.3)\u27e9 : stalk.elem _ _)\u27e7) $\n-- \u03bb g\u2081 g\u2082 \u27e8V, hxV, HV1, HV2, hg\u27e9, quotient.sound \u27e8V \u2293 U, \u27e8hxV, hx\u27e9, set.inter_subset_inter_left _ HV1, set.inter_subset_inter_left _ HV2,\n-- calc  G.to_sheaf_on_opens.res _ _ (V \u2293 U) inf_le_right (inf_le_inf HV1 (le_refl _)) (\u03b7.1.map (g\u2081.U \u2293 U) inf_le_right ((F.F).res (g\u2081.U) (g\u2081.U \u2293 U) (set.inter_subset_left _ _) (g\u2081.s)))\n--     = \u03b7.1.map (V \u2293 U) inf_le_right ((F.F).res V (V \u2293 U) (set.inter_subset_left _ _) ((F.F).res (g\u2081.U) V HV1 (g\u2081.s))) :\n--   by rw \u2190 \u03b7.3; dsimp only [sheaf_on_opens.res, sheaf_of_rings_on_opens.to_sheaf_on_opens]; rw [\u2190 presheaf.Hcomp', \u2190 presheaf.Hcomp']\n-- ... = G.to_sheaf_on_opens.res _ _ (V \u2293 U) _ _ (\u03b7.1.map (g\u2082.U \u2293 U) inf_le_right ((F.F).res (g\u2082.U) (g\u2082.U \u2293 U) _ (g\u2082.s))) :\n--   by erw [hg, \u2190 \u03b7.3]; dsimp only [sheaf_on_opens.res, sheaf_of_rings_on_opens.to_sheaf_on_opens]; rw [\u2190 presheaf.Hcomp', \u2190 presheaf.Hcomp']\u27e9\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} (\u03b7 : F.morphism G) (x : X) (hx : x \u2208 U)\n--   (V : opens X) (HVU : V \u2264 U) (hxV : x \u2208 V) (s : F.to_sheaf_on_opens.eval V HVU) :\n--   \u03b7.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 (\u03b7.1.map V HVU s) :=\n-- quotient.sound \u27e8V, hxV, set.subset_inter (set.subset.refl _) HVU, set.subset.refl _,\n-- calc  G.to_sheaf_on_opens.res (V \u2293 U) inf_le_right V HVU (le_inf (le_refl V) HVU) (\u03b7.1.map (V \u2293 U) inf_le_right (F.to_sheaf_on_opens.res V HVU (V \u2293 U) inf_le_right inf_le_left s))\n--     = G.to_sheaf_on_opens.res V HVU V HVU (le_refl V) (\u03b7.1.map V HVU s) : by rw [\u03b7.3, res_res]\u27e9\n\ninstance is_ring_hom_stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (\u03b7 : F.morphism G) (x : X) (hx : x \u2208 U) :\n  is_ring_hom (\u03b7.1.stalk x hx) :=\n{ map_one := quotient.sound \u27e8U, 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, \u03b7.map_one, _root_.res_one, _root_.res_one]\u27e9,\n  map_mul := \u03bb y z, stalk.induction_on\u2082 y z $ \u03bb V hxV HVU s t,\n    by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, \u2190 to_stalk_mul,\n      sheaf_on_opens.morphism.stalk_to_stalk, \u03b7.map_mul, to_stalk_mul],\n  map_add := \u03bb y z, stalk.induction_on\u2082 y z $ \u03bb V hxV HVU s t,\n    by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, \u2190 to_stalk_add,\n      sheaf_on_opens.morphism.stalk_to_stalk, \u03b7.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} (\u03b7 : F.morphism G) (x : X) (hx : x \u2208 U)\nvariables (s t : F.to_sheaf_on_opens.stalk x hx) (n : \u2115)\n@[simp] lemma stalk_add : \u03b7.1.stalk x hx (s + t) = \u03b7.1.stalk x hx s + \u03b7.1.stalk x hx t := is_ring_hom.map_add _\n@[simp] lemma stalk_zero : \u03b7.1.stalk x hx 0 = 0 := is_ring_hom.map_zero _\n@[simp] lemma stalk_neg : \u03b7.1.stalk x hx (-s) = -\u03b7.1.stalk x hx s := is_ring_hom.map_neg _\n@[simp] lemma stalk_sub : \u03b7.1.stalk x hx (s - t) = \u03b7.1.stalk x hx s - \u03b7.1.stalk x hx t := is_ring_hom.map_sub _\n@[simp] lemma stalk_mul : \u03b7.1.stalk x hx (s * t) = \u03b7.1.stalk x hx s * \u03b7.1.stalk x hx t := is_ring_hom.map_mul _\n@[simp] lemma stalk_one : \u03b7.1.stalk x hx 1 = 1 := is_ring_hom.map_one _\n@[simp] lemma stalk_pow : \u03b7.1.stalk x hx (s^n) = (\u03b7.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 : \u2200 V HVU s, inv_fun.1 V HVU (to_fun.1.1 V HVU s) = s)\n(right_inv : \u2200 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 \u2243+* 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\u27e8morphism.id F, sheaf_on_opens.morphism.id F.to_sheaf_on_opens, \u03bb _ _ _, rfl, \u03bb _ _ _, rfl\u27e9\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\u27e8{ \u03b7 := e.2,\n   hom := \u03bb V HVU, (ring_equiv.symm (e.to_ring_equiv V HVU)).hom },\ne.1.1, e.4, e.3\u27e9\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\u2081} X U}\n  (e\u2081 : equiv F G) (e\u2082 : equiv G H) : equiv F H :=\n\u27e8e\u2082.1.comp e\u2081.1, e\u2081.2.comp e\u2082.2,\n\u03bb _ _ _, by rw [morphism.comp_apply, sheaf_on_opens.morphism.comp_apply, e\u2082.3, e\u2081.3],\n\u03bb _ _ _, by rw [morphism.comp_apply, sheaf_on_opens.morphism.comp_apply, e\u2081.4, e\u2082.4]\u27e9\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\u2081} X U}\n  (e\u2081 : equiv F G) (e\u2082 : equiv G H) (V HV s) :\n  (e\u2081.trans e\u2082).1.1.1 V HV s = e\u2082.1.1.1 V HV (e\u2081.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 \u2264 U) : equiv (F.res_subset V HVU) (G.res_subset V HVU) :=\n\u27e8e.1.res_subset V HVU, e.2.res_subset V HVU,\n\u03bb _ _ _, by rw [morphism.res_subset_apply, sheaf_on_opens.morphism.res_subset_apply, e.3],\n\u03bb _ _ _, by rw [morphism.res_subset_apply, sheaf_on_opens.morphism.res_subset_apply, e.4]\u27e9\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 \u2264 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 \u2208 U) :\n--   F.to_sheaf_on_opens.stalk x hx \u2243 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 := \u03bb g, stalk.induction_on g $ \u03bb 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 := \u03bb g, stalk.induction_on g $ \u03bb 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 \u2192 opens X) (F : \u03a0 (i : I), sheaf_of_rings_on_opens.{v} X (S i))\n  (\u03c6 : \u03a0 i j, equiv ((F i).res_subset ((S i) \u2293 (S j)) inf_le_left) ((F j).res_subset ((S i) \u2293 (S j)) inf_le_right)) :\n  sheaf_of_rings_on_opens.{max u v} X (\u22c3S) :=\n{ F :=\n  { Fring := \u03bb U, @subtype.comm_ring (\u03a0 (i : I), (F i).to_sheaf_on_opens.eval (S i \u2293 U) inf_le_left) _\n      { f | \u2200 (i j : I), (\u03c6 i j).1.1.1 (S i \u2293 S j \u2293 U) inf_le_left\n              ((F i).to_sheaf_on_opens.res (S i \u2293 U) inf_le_left (S i \u2293 S j \u2293 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 \u2293 U) inf_le_left (S i \u2293 S j \u2293 U) (le_trans inf_le_left inf_le_right)\n              (by rw inf_assoc; exact inf_le_right)\n              (f j) }\n      { add_mem := \u03bb f g hf hg i j, by erw [res_add, morphism.map_add, res_add, hf i j, hg i j],\n        zero_mem := \u03bb i j, by erw [res_zero, morphism.map_zero, res_zero]; refl,\n        neg_mem := \u03bb f hf i j, by erw [res_neg, morphism.map_neg, res_neg, hf i j],\n        one_mem := \u03bb i j, by erw [res_one, morphism.map_one, res_one]; refl,\n        mul_mem := \u03bb 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 := \u03bb U V HVU,\n      { map_one := subtype.eq $ funext $ \u03bb i, res_one _ _ _ _ _ _,\n        map_mul := \u03bb f g, subtype.eq $ funext $ \u03bb i, res_mul _ _ _ _ _ _ _ _,\n        map_add := \u03bb f g, subtype.eq $ funext $ \u03bb i, res_add _ _ _ _ _ _ _ _ },\n    .. sheaf_on_opens.sheaf_glue S (\u03bb i, (F i).to_sheaf_on_opens) (\u03bb i j, (\u03c6 i j).to_sheaf_on_opens) }\n  .. sheaf_on_opens.sheaf_glue S (\u03bb i, (F i).to_sheaf_on_opens) (\u03bb i j, (\u03c6 i j).to_sheaf_on_opens) }\n\n@[simp] lemma sheaf_glue_res_val {I : Type u} (S : I \u2192 opens X) (F : \u03a0 (i : I), sheaf_of_rings_on_opens.{v} X (S i))\n  (\u03c6 : \u03a0 i j, equiv ((F i).res_subset ((S i) \u2293 (S j)) inf_le_left) ((F j).res_subset ((S i) \u2293 (S j)) inf_le_right))\n  (U HU V HV HVU s i) :\n  ((sheaf_glue S F \u03c6).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 \u2192 opens X) (F : \u03a0 (i : I), sheaf_of_rings_on_opens.{v} X (S i))\n  (\u03c6 : \u03a0 i j, equiv ((F i).res_subset ((S i) \u2293 (S j)) inf_le_left) ((F j).res_subset ((S i) \u2293 (S j)) inf_le_right))\n  (H\u03c61 : \u2200 i V HV s, (\u03c6 i i).1.1.1 V HV s = s)\n  (H\u03c62 : \u2200 i j k V HV1 HV2 HV3 s, (\u03c6 j k).1.1.1 V HV1 ((\u03c6 i j).1.1.1 V HV2 s) = (\u03c6 i k).1.1.1 V HV3 s)\n  (i : I) :\n  equiv (res_subset (sheaf_glue S F \u03c6) (S i) (le_supr S i)) (F i) :=\n{ to_fun :=\n  { \u03b7 := (sheaf_on_opens.universal_property I S (\u03bb i, (F i).to_sheaf_on_opens) (\u03bb i j, (\u03c6 i j).to_sheaf_on_opens) H\u03c61 H\u03c62 i).1,\n    hom := \u03bb U HU,\n    { map_one := res_one _ _ _ _ _ _,\n      map_mul := \u03bb x y, res_mul _ _ _ _ _ _ _ _,\n      map_add := \u03bb x y, res_add _ _ _ _ _ _ _ _ } },\n  .. sheaf_on_opens.universal_property I S (\u03bb i, (F i).to_sheaf_on_opens) (\u03bb i j, (\u03c6 i j).to_sheaf_on_opens) H\u03c61 H\u03c62 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 \u2190 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 \u03b1] : HAdd \u03b1 \u03b1 \u03b1 where ...\n@[default_instance default] instance [Sub \u03b1] : HSub \u03b1 \u03b1 \u03b1 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\u2081 <|> $p\u2082) => `(stx| orelse($p\u2081, $p\u2082))\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 \" \u2218 \"  => Function.comp\n@[inherit_doc] infixr:35 \" \u00d7 \"  => 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 \" \u2264 \"  => LE.le\n@[inherit_doc] infix:50 \" < \"  => LT.lt\n@[inherit_doc] infix:50 \" >= \" => GE.ge\n@[inherit_doc] infix:50 \" \u2265 \"  => 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 \u2264 $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 \u2265 $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 \" \u2227 \"   => And\n@[inherit_doc] infixr:30 \" \\\\/ \" => Or\n@[inherit_doc] infixr:30 \" \u2228  \"  => Or\n@[inherit_doc] notation:max \"\u00ac\" 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 \" \u2208 \" => Membership.mem\n/-- `a \u2209 b` is negated elementhood. It is notation for `\u00ac (a \u2208 b)`. -/\nnotation:50 a:50 \" \u2209 \" b:50 => \u00ac (a \u2208 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\u2081 ... x\u2099`; it refers to tag `tag` and renames\nthe last `n` hypotheses to `x\u2081 ... x\u2099`.\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 \u2190 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 \u2190 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 \u2190 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 `\u27e8...\u27e9` 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  (\u2190 ``(List.cons $(\u27e8elems.elemsAndSeps.get! i\u27e9) $result))\n    if elems.elemsAndSeps.size < 64 then\n      expandListLit elems.elemsAndSeps.size false (\u2190 ``(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 (\u27e8(Syntax.ident tk.getHeadInfo \"this\".toSubstring `this [])\u27e9 : 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 := \u27e8stx\u27e9\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' : \u211d\u22650)\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 (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{u} r')\n\nsection preps\n\nvariables (V : SemiNormedGroup.{u}) [complete_space V] [separated_space V]\nvariables (\u03b9 : ulift.{u+1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9)\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] {\u03b1 : Type v} (X : \u03b1 \u2192 bounded_homotopy_category A)\n  [uniformly_bounded X] : homotopy_category.is_bounded_above\n  (homotopy_category.colimit_cofan $ \u03bb a : \u03b1, (X a).val).X :=\nbegin\n    obtain \u27e8n,hn\u27e9 := homotopy_category.is_uniformly_bounded_above.cond (val \u2218 X),\n      use n, intros i hi,\n    dsimp [homotopy_category.colimit_cofan],\n    let e : (\u2210 \u03bb (a : \u03b1), (X a).val.as).X i \u2245\n      (\u2210 \u03bb (a : \u03b1), (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 : \u2124) : commsq.{u+2 u+1}\n  (shift_sub_id.{u+1}\n     ((QprimeFP.{u} r' BD.data \u03ba\u2082 M).op \u22d9\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     \u03b9\n     h\u03b9)\n  (pi_Ext_iso_Ext_sigma.{u} BD \u03ba\u2082 M V (\u03bb (k : ulift.{u+1 0} \u2115), \u03b9 k) i).hom\n  (pi_Ext_iso_Ext_sigma.{u} BD \u03ba\u2082 M V (\u03bb (k : ulift.{u+1 0} \u2115), \u03b9 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} \u03b9 h\u03b9 (QprimeFP_int.{u} r' BD.data \u03ba\u2082 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} \u21a5V))) :=\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 \u2190 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, \u2190 nat_trans.comp_app_assoc, \u2190 functor.map_comp_assoc,\n      \u2190 functor.map_comp, iso.op_inv, \u2190 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      (\u03bb (k : ulift \u2115), (QprimeFP r' BD.data \u03ba\u2082 M).obj (\u03b9 k))\n      (\u03bb k, (QprimeFP r' BD.data \u03ba\u2082 M).map (hom_of_le $ h\u03b9 $\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_\u03c0\n  (A : Type u) [category.{v} A] [abelian A] [enough_projectives A] [has_coproducts A] [AB4 A]\n  (X : ulift.{v} \u2115 \u2192 bounded_homotopy_category A) [uniformly_bounded X] (i : \u2124) (Y) (k) :\n  (Ext_coproduct_iso X i Y).hom \u226b pi.\u03c0 _ k =\n  ((Ext i).map $ quiver.hom.op $ sigma.\u03b9 _ _).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_\u03c0, limit.lift_\u03c0_assoc, fan.mk_\u03c0_app],\n  dsimp only [Ext_iso, iso.symm_hom, functor.map_iso_hom, functor.map_iso_inv],\n  simp only [\u2190 functor.map_comp, iso.op_hom, iso.op_inv, \u2190 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_\u03c0, colimit.\u03b9_desc, cofan.mk_\u03b9_app, lift_lifts_assoc],\n  refl,\nend\n\nlemma Tinv2_iso_of_bicartesian_aux_2\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (j) {e : (homotopy_category.colimit_cofan.{u+1 u+2}\n     (\u03bb (a : ulift.{u+1 0} \u2115),\n        ((\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba\u2082 M).obj (\u03b9 k)) a).val)).X.is_bounded_above } :\n  ((cofan.{u+1 u+2} (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba\u2082 M).obj (\u03b9 k))).\u03b9.app j \u226b\n     of_hom.{u+1 u+2} (sigma_map.{u u+2 u+1} \u03b9 (QprimeFP_int.Tinv.{u} BD.data \u03ba\u2082 \u03ba M))) \u226b\n  (cofan_point_iso_colimit.{u} (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba M).obj (\u03b9 k))).hom =\n  (QprimeFP.Tinv _ _ _ _).app _ \u226b\n  sigma.\u03b9 (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba M).obj (\u03b9 k)) j :=\nbegin\n  rw [\u2190 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_\u03b9_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 [\u2190 (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} \u2124)).map_comp],\n  erw [\u2190 (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} \u2124)).map_comp],\n  congr' 1,\n  dsimp only [sigma_map],\n  erw [colimit.\u03b9_desc],\n  refl,\nend\n\nlemma Tinv2_iso_of_bicartesian_aux_3\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)]\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (j)\n  {e : (homotopy_category.colimit_cofan.{u+1 u+2}\n     (\u03bb (a : ulift.{u+1 0} \u2115),\n        ((\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba\u2082 M).obj (\u03b9 k)) a).val)).X.is_bounded_above} :\n  (cofan.{u+1 u+2} (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba\u2082 M).obj (\u03b9 k))).\u03b9.app j \u226b\n  of_hom.{u+1 u+2} (sigma_map.{u u+2 u+1} \u03b9 (QprimeFP_int.\u03b9.{u} BD.data \u03ba\u2082 \u03ba M)) \u226b\n    (cofan_point_iso_colimit.{u} (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba M).obj (\u03b9 k))).hom =\n  (QprimeFP.\u03b9 _ \u03ba\u2082 \u03ba M).app _ \u226b\n  sigma.\u03b9 ((\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba M).obj (\u03b9 k))) j :=\nbegin\n  simp only [\u2190 category.assoc], rw [\u2190 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_\u03b9_app, of_hom,\n    homotopy_category.colimit_cofan, QprimeFP.\u03b9, whisker_right_app,\n    chain_complex.to_bounded_homotopy_category, functor.comp_map],\n  erw [\u2190 (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} \u2124)).map_comp],\n  erw [\u2190 (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} \u2124)).map_comp],\n  congr' 1,\n  dsimp only [sigma_map],\n  erw [colimit.\u03b9_desc],\n  refl,\nend\n\nlemma Tinv2_iso_of_bicartesian_aux [normed_with_aut r V]\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (i : \u2124)\n  (H1 : (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data \u03ba \u03ba\u2082 M V i) \u03b9 h\u03b9).bicartesian) :\n  (Ext_Tinv2_commsq (of_hom (sigma_map (\u03bb (k : ulift \u2115), \u03b9 k) (QprimeFP_int.Tinv BD.data \u03ba\u2082 \u03ba M)))\n  (of_hom (sigma_map (\u03bb (k : ulift \u2115), \u03b9 k) (QprimeFP_int.\u03b9 BD.data \u03ba\u2082 \u03ba M)))\n  (of_hom (sigma_map (\u03bb (k : ulift \u2115), \u03b9 k) (QprimeFP_int.Tinv BD.data \u03ba\u2082 \u03ba M)))\n  (of_hom (sigma_map (\u03bb (k : ulift \u2115), \u03b9 k) (QprimeFP_int.\u03b9 BD.data \u03ba\u2082 \u03ba M)))\n  (of_hom (QprimeFP.shift_sub_id \u03b9 h\u03b9 (QprimeFP_int r' BD.data \u03ba\u2082 M)))\n  (of_hom (QprimeFP.shift_sub_id \u03b9 h\u03b9 (QprimeFP_int r' BD.data \u03ba M)))\n  (auux $ commsq_shift_sub_id_Tinv _ _ _ _ _ _)\n  (auux $ commsq_shift_sub_id_\u03b9 _ _ _ _ _ _)\n  ((single _ 0).map (Condensed.of_top_ab_map (normed_group_hom.to_add_monoid_hom (normed_with_aut.T.inv : V \u27f6 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 \u2190 iso.eq_comp_inv,\n    apply limit.hom_ext, intros j, rw lim_map_\u03c0,\n    dsimp [pi_Ext_iso_Ext_sigma],\n    simp only [category.assoc],\n    have := Ext_coproduct_iso_\u03c0 _\n      (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba\u2082 M).obj (\u03b9 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, \u2190 nat_trans.comp_app, \u2190 functor.map_comp, \u2190 op_comp],\n    clear this,\n    erw colimit.\u03b9_desc,\n    dsimp [Ext_Tinv2, ExtQprime.Tinv2],\n    simp only [sub_comp, comp_sub],\n    refine congr_arg2 _ _ _,\n    { simp only [\u2190 nat_trans.comp_app, \u2190 functor.map_comp, \u2190 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_\u03c0 _\n        (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba M).obj (\u03b9 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 \u2190 iso.eq_inv_comp at this,\n      rw \u2190 reassoc_of this, refl },\n    { simp only [category.assoc, nat_trans.naturality, \u2190 nat_trans.comp_app_assoc,\n        \u2190 functor.map_comp_assoc, \u2190 functor.map_comp, \u2190 nat_trans.comp_app, \u2190 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_\u03c0 _\n        (\u03bb (k : ulift.{u+1 0} \u2115), (QprimeFP.{u} r' BD.data \u03ba M).obj (\u03b9 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 \u2190 iso.eq_inv_comp at this,\n      rw \u2190 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (h\u03ba : Lbar.sufficiently_increasing \u03ba \u03b9)\n  (h\u03ba\u2082 : Lbar.sufficiently_increasing \u03ba\u2082 \u03b9)\n  (i : \u2124)\n  (H1 : (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data \u03ba \u03ba\u2082 M V i) \u03b9 h\u03b9).bicartesian)\n  (H2 : (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data \u03ba \u03ba\u2082 M V (i+1)) \u03b9 h\u03b9).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\u2081 := QprimeFP.short_exact BD \u03ba\u2082 M \u03b9 h\u03b9 h\u03ba\u2082,\n  have SES\u2082 := QprimeFP.short_exact BD \u03ba M \u03b9 h\u03b9 h\u03ba,\n  have := Ext_iso_of_bicartesian_of_bicartesian SES\u2081 SES\u2082\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.\u03b9 BD.data _ _ M))\n    (sigma_map _ (QprimeFP_int.\u03b9 BD.data _ _ M))\n    (commsq_shift_sub_id_Tinv BD.data _ _ M \u03b9 h\u03b9)\n    (commsq_sigma_proj_Tinv BD _ _ M \u03b9)\n    (commsq_shift_sub_id_\u03b9 BD.data _ _ M \u03b9 h\u03b9)\n    (commsq_sigma_proj_\u03b9 BD _ _ M \u03b9)\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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (H : \u2200 i, \u2203 (\u03b9) (h\u03b9),\n    Lbar.sufficiently_increasing \u03ba \u03b9 \u2227\n    Lbar.sufficiently_increasing \u03ba\u2082 \u03b9 \u2227\n    (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data \u03ba \u03ba\u2082 M V i) \u03b9 h\u03b9).bicartesian \u2227\n    (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data \u03ba \u03ba\u2082 M V (i+1)) \u03b9 h\u03b9).bicartesian)\n  (i : \u2124) :\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 \u27e8i, rfl\u27e9 : \u2203 k, k+1 = i := \u27e8i-1, sub_add_cancel _ _\u27e9,\n  obtain \u27e8\u03b9, h\u03b9, h\u03ba, h\u03ba\u2082, H1, H2\u27e9 := H i,\n  apply Tinv2_iso_of_bicartesian _ _ _ _ _ _ \u03b9 h\u03b9 h\u03ba h\u03ba\u2082 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 \u03b1] {s\u2081 s\u2082 : State \u03b1}\n\ntheorem progress_not_mem_rcns (e : s\u2081 \u21d3\u1d62* s\u2082) (h : rcn \u2208 s\u2081.progress) : rcn \u2209 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 \u25b8 h) e.rcn_not_mem_progress\n\ntheorem mem_progress_iff (e : s\u2081 \u21d3\u1d62* s\u2082) : \n    (rcn \u2208 s\u2082.progress) \u2194 (rcn \u2208 e.rcns \u2228 rcn \u2208 s\u2081.progress) := by\n  induction e <;> simp [rcns]\n  case trans s\u2081 s\u2082 s\u2083 e e' hi => \n    simp [hi]\n    constructor <;> intro\n    all_goals repeat cases \u2039_ \u2228 _\u203a <;> 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\u2081 \u21d3\u1d62* s\u2082) (h : rcn \u2208 e.rcns) : rcn \u2208 s\u2082.progress := \n  e.mem_progress_iff.mpr $ .inl h\n\ntheorem rcns_nodup {s\u2081 s\u2082 : State \u03b1} : (e : s\u2081 \u21d3\u1d62* s\u2082) \u2192 e.rcns.Nodup\n  | refl       => List.nodup_nil\n  | trans e e' => List.nodup_cons.mpr \u27e8e'.progress_not_mem_rcns e.rcn_mem_progress, e'.rcns_nodup\u27e9\n\ntheorem progress_eq_rcns_perm \n    (e\u2081 : s \u21d3\u1d62* s\u2081) (e\u2082 : s \u21d3\u1d62* s\u2082) (hp : s\u2081.progress = s\u2082.progress) : e\u2081.rcns ~ e\u2082.rcns := by\n  apply List.perm_ext e\u2081.rcns_nodup e\u2082.rcns_nodup |>.mpr\n  intro rcn\n  by_cases hc : rcn \u2208 s.progress\n  case pos => simp [e\u2081.progress_not_mem_rcns hc, e\u2082.progress_not_mem_rcns hc]\n  case neg =>\n    constructor <;> intro hm\n    case mp  => exact e\u2082.mem_progress_iff.mp (hp \u25b8 e\u2081.rcns_mem_progress hm) |>.resolve_right hc\n    case mpr => exact e\u2081.mem_progress_iff.mp (hp \u25b8 e\u2082.rcns_mem_progress hm) |>.resolve_right hc\n\ntheorem preserves_tag {s\u2081 s\u2082 : State \u03b1} : (s\u2081 \u21d3\u1d62* s\u2082) \u2192 s\u2081.tag = s\u2082.tag\n  | refl => rfl\n  | trans e e' => e.preserves_tag.trans e'.preserves_tag\n\ntheorem rcns_trans_eq_cons (e\u2081 : s \u21d3\u1d62 s\u2081) (e\u2082 : s\u2081 \u21d3\u1d62* s\u2082) : \n    (trans e\u2081 e\u2082).rcns = e\u2081.rcn :: e\u2082.rcns := by\n  simp [rcns, Step.rcn]\n\ntheorem progress_eq {s\u2081 s\u2082 : State \u03b1} : \n    (e : s\u2081 \u21d3\u1d62* s\u2082) \u2192 s\u2082.progress = s\u2081.progress \u222a { i | i \u2208 e.rcns }\n  | refl => by simp [rcns]\n  | trans e e' => by \n    simp [e.progress_eq \u25b8 e'.progress_eq, rcns_trans_eq_cons]\n    apply Set.insert_union'\n\ntheorem mem_rcns_not_mem_progress (e : s\u2081 \u21d3\u1d62* s\u2082) (h : rcn \u2208 e.rcns) : rcn \u2209 s\u2081.progress := by\n  induction e\n  case refl => contradiction\n  case trans e e' hi =>\n    cases e'.rcns_trans_eq_cons e \u25b8 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\u2081 \u21d3\u1d62* s\u2082) : rcn \u2208 e.rcns \u2194 (rcn \u2208 s\u2082.progress \u2227 rcn \u2209 s\u2081.progress) := by\n  simp [e.progress_eq, s\u2081.mem_record'_progress_iff e.rcns rcn, or_and_right]\n  exact e.mem_rcns_not_mem_progress\n\ntheorem equiv {s\u2081 s\u2082 : State \u03b1} : (s\u2081 \u21d3\u1d62* s\u2082) \u2192 s\u2081.rtr \u2248 s\u2082.rtr\n  | refl => .refl\n  | trans e e' => ReactorType.Equivalent.trans e.equiv e'.equiv\n\ntheorem head_minimal (e : s\u2081 \u21d3\u1d62 s\u2082) (e' : s\u2082 \u21d3\u1d62* s\u2083) : (e.rcn :: e'.rcns) \u226e[s\u2081.rtr] e.rcn := by\n  by_contra hc\n  simp [Minimal] at hc\n  have \u27e8_, hm, h\u27e9 := 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\u2081 \u21d3\u1d62 s\u2082) (e' : s\u2082 \u21d3\u1d62* s\u2083) (h : i \u2208 e'.rcns) : e.rcn \u2260 i := by\n  intro hc\n  have := trans e e' |>.rcns_nodup\n  have := hc.symm \u25b8 List.not_nodup_cons_of_mem h\n  contradiction\n\n-- The core lemma for `prepend_minimal`.\ntheorem cons_prepend_minimal \n    (e : s\u2081 \u21d3\u1d62 s\u2082) (e' : s\u2082 \u21d3\u1d62* s\u2083) (hm : i \u2208 e'.rcns) (hr : (e.rcn :: e'.rcns) \u226e[s\u2081.rtr] i) : \n    \u2203 f : s\u2081 \u21d3\u1d62* s\u2083, f.rcns = i :: e.rcn :: (e'.rcns.erase i) := by\n  induction e' generalizing s\u2081 <;> simp [rcns] at *\n  case trans s\u2081 s\u2082 s\u2084 e' e'' hi =>\n    cases hm\n    case inl hm =>\n      simp [hm] at hr\n      have \u27e8_, f, f', \u27e8hf\u2081, hf\u2082\u27e9\u27e9 := e.prepend_indep e' hr.cons_head\n      exists trans f $ trans f' e''\n      simp [hm, rcns, \u2190hf\u2081, \u2190hf\u2082]\n    case inr hm =>\n      have \u27e8f, hf\u27e9 :=  hi e' hm $ hr.cons_tail.equiv e.equiv\n      cases f <;> simp [rcns] at hf\n      case trans f f'' =>\n        have \u27e8h\u2081, h\u2082\u27e9 := hf\n        have \u27e8_, f, f', \u27e8hf\u2081, hf\u2082\u27e9\u27e9 := e.prepend_indep f $ h\u2081.symm \u25b8 hr |>.cons_head\n        exists trans f $ trans f' f''\n        simp [rcns, hf\u2081, h\u2081, hf\u2082, h\u2082, e''.rcns.erase_cons_tail $ head_not_mem_tail e' e'' hm]\n\ntheorem prepend_minimal (e : s\u2081 \u21d3\u1d62* s\u2082) (hm : i \u2208 e.rcns) (hr : e.rcns \u226e[s\u2081.rtr] i) :\n    \u2203 (e' : s\u2081 \u21d3\u1d62* s\u2082), e'.rcns = i :: (e.rcns.erase i) := by\n  cases e <;> simp [rcns] at *; cases \u2039_ \u2228 _\u203a \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) \u25b8 cons_prepend_minimal e e' h hr\n        \ntheorem rcns_perm_deterministic \n    (e\u2081 : s \u21d3\u1d62* s\u2081) (e\u2082 : s \u21d3\u1d62* s\u2082) (hp : e\u2081.rcns ~ e\u2082.rcns) : s\u2081.rtr = s\u2082.rtr := by\n  induction e\u2081\n  case refl => cases e\u2082 <;> simp [rcns] at hp \u22a2 \n  case trans s s\u2098\u2081 s\u2081 e\u2081 e\u2081' hi =>\n    have hm := hp.mem_iff.mp $ List.mem_cons_self _ _\n    have hm' := e\u2081'.head_minimal e\u2081 |>.perm hp\n    have \u27e8e\u2082, he\u2082\u27e9 := e\u2082.prepend_minimal hm hm'\n    cases e\u2082 <;> simp [rcns] at he\u2082\n    case trans s\u2098\u2082 e\u2082 e\u2082' =>\n      have \u27e8h, h'\u27e9 := he\u2082 \n      cases e\u2081.deterministic e\u2082 h.symm\n      apply hi e\u2082'\n      rw [h']\n      exact List.perm_cons _ |>.mp (hp.trans $ List.perm_cons_erase hm)\n\nprotected theorem deterministic \n    (e\u2081 : s \u21d3\u1d62* s\u2081) (e\u2082 : s \u21d3\u1d62* s\u2082) (ht : s\u2081.tag = s\u2082.tag) (hp : s\u2081.progress = s\u2082.progress) : \n    s\u2081 = s\u2082 := by\n  ext1 <;> try assumption\n  exact rcns_perm_deterministic e\u2081 e\u2082 $ progress_eq_rcns_perm e\u2081 e\u2082 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": "import data.real.irrational\nimport topology.basic\nimport algebra.order.floor\n\n\n--OUTPUT 1\ntheorem irrational_orbit_dense {\u03b1 : \u211d} (h\u03b1_irrat : irrational \u03b1) : closure ((\u03bb m : \u2124, int.fract (\u03b1 * \u2191m)) '' (@set.univ \u2124)) = set.Icc 0 1 :=\nbegin\n  have h1 : \u2200 i j : \u2124, i \u2260 j \u2192 int.fract (\u03b1 * \u2191i) \u2260 int.fract (\u03b1 * \u2191j), from by auto [int.fract_eq_iff, h\u03b1_irrat],\n  have h2 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h1],\n  have h3 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h2],\n  have h4 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h3],\n  have h5 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h4],\n  have h6 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h5],\n  have h7 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h6],\n  have h8 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h7],\n  have h9 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h8],\n  have h10 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h9],\n  have h11 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h10],\n  have h12 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h11],\n  have h13 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h12],\n  have h14 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h13],\n  have h15 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h14],\n  have h16 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h15],\n  have h17 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h16],\n  have h18 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h17],\n  have h19 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h18],\n  have h20 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h19],\n  have h21 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h20],\n  have h22 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h21],\n  have h23 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h22],\n  have h24 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h23],\n  have h25 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h24],\n  have h26 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h25],\n  have h27 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h26],\n  have h28 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h27],\n  have h29 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h28],\n  have h30 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h29],\n  have h31 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h30],\n  have h32 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h31],\n  have h33 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h32],\n  have h34 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h33],\n  have h35 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h34],\n  have h36 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h35],\n  have h37 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h36],\n  have h38 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h37],\n  have h39 : \u2200 i j : \u2124, i \u2260 j \u2192 (int.fract (\u03b1 * \u2191i)) \u2260 (int.fract (\u03b1 * \u2191j)), from by auto [h38\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 {\u03b1 : Type*} (S : set \u03b1) : \u2200 A B \u2208 \ud835\udcab S, (A \u2229 B) \u2208 \ud835\udcab S :=\nbegin\n  assume (A : set \u03b1) (hA : A \u2208 \ud835\udcab S) (B : set \u03b1) (hB : B \u2208 \ud835\udcab S),\n  have h1 : (A \u2286 S) \u2227 (B \u2286 S), from by auto [set.subset_of_mem_powerset, set.subset_of_mem_powerset],\n  have h2 : (A \u2229 B) \u2286 A, from by auto [set.inter_subset_left],\n  have h3 : (A \u2229 B) \u2286 S, from by auto [set.subset.trans],\n  show (A \u2229 B) \u2208  \ud835\udcab S, from by auto [set.mem_powerset],\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 : \u211d) : (x + y)^2 = (x^2 + 2*x*y + y^2) := \nbegin\n  calc (x + y)^2 = (x+y)*(x+y) : by auto [sq]\n  ... = x*(x+y) + y*(x+y) : by auto [add_mul]\n  ... = x*x + x*y + y*x + y*y : by auto [mul_comm, add_mul] using [ring]\n  ... = x^2 + 2*x*y + y^2 : by auto [sq, mul_comm] using [ring]\nend\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] : \u2203! e : G, \u2200 a : G, e * a = a \u2227 a * e = a :=\nbegin\n  have h1 : \u2200 a b : G, \u2203! x : G, a * x = b, from by auto using [use (a\u207b\u00b9 * b)],\n  have h2 : \u2200 a b : G, \u2203! y : G, y * a = b, from by auto using [use b * a\u207b\u00b9], \n\n  have h3 : \u2200 a : G, \u2203! x : G, a * x = a, from by auto [h1],\n  have h4 : \u2200 a : G, \u2203! y : G, y * a = a, from by auto [h2],\n\n  have h5 : \u2200 a : G, classical.some (h3 a).exists = (1 : G), from by auto [exists_unique.unique, h3, classical.some_spec, exists_unique.exists, mul_one],\n  have h6 : \u2200 a : G, classical.some (h4 a).exists = (1 : G), from by auto [exists_unique.unique, h4, classical.some_spec, exists_unique.exists, one_mul],\n\n  show \u2203! e : G, \u2200 a : G, e * a = a \u2227 a * e = a, from by auto [h3, h4, exists_unique.unique, classical.some_spec, exists_unique.exists] using [use (1 : G)],\nend\n\n/--`theorem`\nDensity of irrational orbit\nThe fractional parts of the integer multiples of an irrational number form a dense subset of the unit interval\n`proof`\nLet $\\alpha$ be an irrational number. Then for distinct $i, j \\in \\mathbb{Z}$, we must have $\\{i \\alpha\\} \\neq\\{j \\alpha\\}$. If this were not true, then\n$$\ni \\alpha-\\lfloor i \\alpha\\rfloor=\\{i \\alpha\\}=\\{j \\alpha\\}=j \\alpha-\\lfloor j \\alpha\\rfloor,\n$$\nwhich yields the false statement $\\alpha=\\frac{\\lfloor i \\alpha\\rfloor-\\lfloor j \\alpha\\rfloor}{i-j} \\in \\mathbb{Q}$. Hence,\n$$\nS:=\\{\\{i \\alpha\\} \\mid i \\in \\mathbb{Z}\\}\n$$\nis an infinite subset of $\\left[0,1\\right]$.\n\nBy the Bolzano-Weierstrass theorem, $S$ has a limit point in $[0, 1]$. One can thus find pairs of elements of $S$ that are arbitrarily close. Since (the absolute value of) the difference of any two elements of $S$ is also an element of $S$, it follows that $0$ is a limit point of $S$.\n\nTo show that $S$ is dense in $[0, 1]$, consider $y \\in[0,1]$, and $\\epsilon>0$. Then by selecting $x \\in S$ such that $\\{x\\}<\\epsilon$ (which exists as $0$ is a limit point), and $N$ such that $N \\cdot\\{x\\} \\leq y<(N+1) \\cdot\\{x\\}$, we get: $|y-\\{N x\\}|<\\epsilon$.\n\nQED\n-/\ntheorem  irrational_orbit_dense {\u03b1 : \u211d} (h\u03b1_irrat : irrational \u03b1) : closure ((\u03bb m : \u2124, int.fract (\u03b1 * \u2191m)) '' (@set.univ \u2124)) = set.Icc 0 1 :=\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_auto-Natural-Language-Proof-Translation/Correct_statement-lean_proof_auto-3_few_shot_temperature_0_max_tokens_2000_n_1/clean_files/Density of irrational orbit.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.020964241085739674, "lm_q1q2_score": 0.009909450361116345}}
{"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 \u2190 mvarId.getType\n  if let some (_, lhs, _) \u2190 matchEq? target then\n    if let some fvarId \u2190 findFVar? lhs then\n      return (\u2190  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 (\u2190 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 \u2190 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) \u2192 (eqs : Array Expr) \u2192 (args : Array Expr) \u2192 (mask : Array Bool) \u2192 (type : Expr) \u2192 MetaM \u03b1)\n    : MetaM \u03b1 := 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 \u03b1 := do\n    let type \u2190 whnfForall type\n    match type with\n    | Expr.forallE n d b .. =>\n      if i < numNonEqParams then\n        let d \u2190 unfoldNamedPattern d\n        withLocalDeclD n d fun y => do\n          let typeNew := b.instantiate1 y\n          if let some (_, lhs, rhs) \u2190 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 (\u2190 mkEqRefl rhs)\n               let typeNew := typeNew.replaceFVar lhs rhs\n               return (\u2190 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 \u2190 if let some (_, _, rhs) \u2190 matchEq? d then\n          mkEqRefl rhs\n        else if let some (_, _, _, rhs) \u2190 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 \u2190 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 (\u2190 inferType ys[0]!).isConstOf ``Unit && !(\u2190 dependsOn type ys[0]!.fvarId!) then\n          return (\u2190 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 \u2192 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! (\u2190 get).xs.contains rhs\n  let (subst, mvarId) \u2190 substCore (\u2190 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 (\u2190 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 \u2190 substVars mvarId\n    match (\u2190 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 \u2190 get\n  s.mvarId.withContext do\n    -- If the goal is contradictory, the hypothesis is redundant.\n    if (\u2190 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 \u2190 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) \u2190 matchEq? eqType then\n        if (\u2190 isDefEq lhs rhs) then\n          return true\n        if rhs.isFVar then\n          substRHS eq rhs.fvarId!\n          return true\n      if let some (\u03b1, lhs, \u03b2, rhs) \u2190 matchHEq? eqType then\n        -- Try to convert `HEq` into `Eq`\n        if (\u2190 isDefEq \u03b1 \u03b2) then\n          let (eqNew, mvarId) \u2190 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? (\u2190 getEnv), rhs.isConstructorApp? (\u2190 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 (\u2190 trySubstVarsAndContradiction s.mvarId) then\n              return false\n          | _, _ =>\n            if (\u2190 trySubstVarsAndContradiction s.mvarId) then\n              return false\n      try\n        -- Try to simplify equation using `injection` tactic.\n        match (\u2190 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 (\u2190 isDone) then\n    return true\n  else if (\u2190 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 \u2190 forallTelescope h fun ys _ => pure (ys.size - numEqs)\n  let mvarId := (\u2190 mkFreshExprSyntheticOpaqueMVar h).mvarId!\n  let (xs, mvarId) \u2190 mvarId.introN numVars\n  let (eqs, mvarId) \u2190 mvarId.introN numEqs\n  let (r, s) \u2190 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 \u2190 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 (\u2190 dependsOn r x) then\n          r \u2190 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 (\u2190 getLCtx) do\n    if let some (_, lhs, rhs) \u2190 matchEq? localDecl.type then\n      if lhs.isFVar then\n        if !(\u2190 dependsOn rhs lhs.fvarId!) then\n          match (\u2190 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 \u2190 instantiateMVars type\n  forallTelescope type fun ys target => do\n    let mvar0  \u2190 mkFreshExprSyntheticOpaqueMVar target\n    trace[Meta.Match.matchEqs] \"proveCondEqThm {mvar0.mvarId!}\"\n    let mvarId \u2190 mvar0.mvarId!.deltaTarget (\u00b7 == matchDeclName)\n    withDefault <| go mvarId 0\n    mkLambdaFVars ys (\u2190 instantiateMVars mvar0)\nwhere\n  go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do\n    trace[Meta.Match.matchEqs] \"proveCondEqThm.go {mvarId}\"\n    let mvarId' \u2190 mvarId.modifyTargetEqLHS whnfCore\n    let mvarId := mvarId'\n    let subgoals \u2190\n      (do mvarId.refl; return #[])\n      <|>\n      (do mvarId.contradiction { genDiseq := true }; return #[])\n      <|>\n      (casesOnStuckLHS mvarId)\n      <|>\n      (do let mvarId' \u2190 simpIfTarget mvarId (useDecide := true)\n          if mvarId' == mvarId then throwError \"simpIf failed\"\n          return #[mvarId'])\n      <|>\n      (do if let some (s\u2081, s\u2082) \u2190 splitIfTarget? mvarId then\n            let mvarId\u2081 \u2190 trySubst s\u2081.mvarId s\u2081.fvarId\n            return #[mvarId\u2081, s\u2082.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 \u00b7 (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 \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let rec go (i : Nat) (xs : Array Expr) : MetaM \u03b1 := do\n    if h : i < altTypes.size then\n      let hName := (`h).appendIndexAfter (i+1)\n      withLocalDeclD hName (altTypes.get \u27e8i, h\u27e9) 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 \u00d7 Expr)) := do\n  if let some (_, lhs, rhs) \u2190 matchEq? type then\n    return some (lhs, rhs)\n  else if let some (\u03b1, lhs, \u03b2, rhs) \u2190 matchHEq? type then\n    if (\u2190 isDefEq \u03b1 \u03b2) 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 (\u2190 getLCtx) do\n      if let some (lhs, rhs) \u2190 injectionAnyCandidate? localDecl.type then\n        unless (\u2190 isDefEq lhs rhs) do\n          let lhs \u2190 whnf lhs\n          let rhs \u2190 whnf rhs\n          unless lhs.isNatLit && rhs.isNatLit do\n            try\n              match (\u2190 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 \u00d7 Nat \u00d7 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) \u2190 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 \u00d7 Nat \u00d7 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 && (\u2190 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 \u2192 Type _\n    | nil             : Foo 0\n    | cons  (t: Foo l): Foo l\n\n    def Foo.bar (t\u2081: Foo l\u2081): Foo l\u2082 \u2192 Bool\n    | cons s\u2081 => t\u2081.bar s\u2081\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\u2082 : Nat} \u2192\n      (t\u2082 : Foo l\u2082) \u2192\n        (motive : Foo l\u2082 \u2192 Sort u_1) \u2192\n          (t\u2082 : Foo l\u2082) \u2192 ((s\u2081 : Foo l\u2082) \u2192 motive (Foo.cons s\u2081)) \u2192 ((x : Foo l\u2082) \u2192 motive x) \u2192 motive t\u2082 :=\n    fun {l\u2082} t\u2082 motive t\u2082_1 h_1 h_2 =>\n      (fun t\u2082_2 =>\n          Foo.casesOn (motive := fun a x => l\u2082 = a \u2192 HEq t\u2082_1 x \u2192 motive t\u2082_1) t\u2082_2\n            (fun h =>\n              Eq.ndrec (motive := fun {l\u2082} =>\n                (t\u2082 t\u2082 : Foo l\u2082) \u2192\n                  (motive : Foo l\u2082 \u2192 Sort u_1) \u2192\n                    ((s\u2081 : Foo l\u2082) \u2192 motive (Foo.cons s\u2081)) \u2192 ((x : Foo l\u2082) \u2192 motive x) \u2192 HEq t\u2082 Foo.nil \u2192 motive t\u2082)\n                (fun t\u2082 t\u2082 motive h_1 h_2 h => Eq.symm (eq_of_heq h) \u25b8 h_2 Foo.nil) (Eq.symm h) t\u2082 t\u2082_1 motive h_1 h_2) --- HERE\n            fun {l} t h =>\n            Eq.ndrec (motive := fun {l} => (t : Foo l) \u2192 HEq t\u2082_1 (Foo.cons t) \u2192 motive t\u2082_1)\n              (fun t h => Eq.symm (eq_of_heq h) \u25b8 h_1 t) h t)\n        t\u2082_1 (Eq.refl l\u2082) (HEq.refl t\u2082_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! (\u2190 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 (\u2190 read).find? arg.fvarId! with\n          | some (altNew, _, _) =>\n            argsNew := argsNew.set! i altNew\n            trace[Meta.Match.matchEqs] \"arg: {arg} : {\u2190 inferType arg}, altNew: {altNew} : {\u2190 inferType altNew}\"\n            isAlt := isAlt.push true\n          | none =>\n            argsNew := argsNew.set! i (\u2190 convertTemplate arg)\n            isAlt := isAlt.push false\n        else\n          argsNew := argsNew.set! i (\u2190 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 \u2190 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 \u27e8i, h\u27e9\n              if i < isAlt.size && isAlt[i]! then\n                let altNew := argsNew[6+i]! -- Recall that `Eq.ndrec` has 6 arguments\n                let altTypeNew \u2190 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 := (\u2190 kabstract altTypeNew rhs).instantiate1 x\n                -- Replace args[6:6+i] with `motiveTypeArgsNew`\n                for j in [:i] do\n                  altTypeNewAbst := (\u2190 kabstract altTypeNewAbst argsNew[6+j]!).instantiate1 motiveTypeArgsNew[j]!\n                let localDecl \u2190 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 (\u2190 mkForallFVars motiveTypeArgsNew resultType)\n          go 0 #[]\n      trace[Meta.Match.matchEqs] \"new motive: {motiveNew}\"\n      unless (\u2190 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 .. \u2190 whnf (\u2190 inferType eqRecNewPrefix) | unreachable!\n      trace[Meta.Match.matchEqs] \"new minor type: {minorTypeNew}\"\n      let minor := args[3]!\n      let minorNew \u2190 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 \u2190 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 \u2190 withReader (fun _ => m) <| convertTemplate minorBodyNew\n        trace[Meta.Match.matchEqs] \"minor premise new body after convertTemplate:{indentExpr minorBodyNew}\"\n        mkLambdaFVars minorArgsNew minorBodyNew\n      unless (\u2190 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 (\u2190 isCastEqRec e) then\n        return .done (\u2190 convertCastEqRec e)\n      else\n        let Expr.fvar fvarId .. := e.getAppFn | return .continue\n        let some (altNew, numParams, argMask) := (\u2190 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 \u2265 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, _, _) \u2190 forallMetaBoundedTelescope (\u2190 inferType eNew) (numParams - newArgs.size) (kind := MetavarKind.syntheticOpaque)\n        modify fun s => s ++ (mvars.map (\u00b7.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 (\u2190 injectionAny mvarId) with\n    | InjectionAnyResult.solved => return ()\n    | InjectionAnyResult.failed =>\n      let mvarId' \u2190 substVars mvarId\n      if mvarId' == mvarId then\n        if (\u2190 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 (\u2190 mvarId.getDecl).kind}, {\u2190 mvarId.isAssigned}\\n{MessageData.ofGoal mvarId}\"\n    let (_, mvarId) \u2190 mvarId.intros\n    let mvarId \u2190 mvarId.tryClearMany (alts.map (\u00b7.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 \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  if numDiscrEqs == 0 then\n    k alts\n  else\n    go 0 #[]\nwhere\n  go (i : Nat) (altsNew : Array Expr) : MetaM \u03b1 := do\n   if h : i < alts.size then\n     let alt := alts.get \u27e8i, h\u27e9\n     let altLocalDecl \u2190 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 (\u2190 getEnv) matchDeclName\n  let constInfo \u2190 getConstInfo matchDeclName\n  let us := constInfo.levelParams.map mkLevelParam\n  let some matchInfo \u2190 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) \u2190 forallAltTelescope (\u2190 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 \u2190 instantiateForall notAlt patterns\n          if let some h \u2190 simpH? h patterns.size then\n            hs := hs.push h\n        trace[Meta.Match.matchEqs] \"hs: {hs}\"\n        let splitterAltType \u2190 mkForallFVars ys (\u2190 hs.foldrM (init := (\u2190 mkForallFVars eqs altResultType)) (mkArrow \u00b7 \u00b7))\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 \u2190 mkArrow (\u2190 mkEqHEq discr pattern) notAlt\n        notAlt \u2190 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 \u2190 mkEq lhs rhs\n          let thmType \u2190 hs.foldrM (init := thmType) (mkArrow \u00b7 \u00b7)\n          let thmType \u2190 mkForallFVars (params ++ #[motive] ++ ys ++ alts) thmType\n          let thmType \u2190 unfoldNamedPattern thmType\n          let thmVal \u2190 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 \u2190 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 \u2190 deltaExpand template (\u00b7 == constInfo.name)\n      let template := template.headBeta\n      let splitterVal \u2190 mkLambdaFVars splitterParams (\u2190 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 (\u2190 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' : \u211d\u22650)\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 (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{u} r')\n\nnamespace Lbar\n\nopen ProFiltPseuNormGrpWithTinv\u2081 ProFiltPseuNormGrp\u2081 CompHausFiltPseuNormGrp\u2081\nopen bounded_homotopy_category\n\nvariables (r r')\n\ndef Tinv_sub (S : Profinite.{u}) (V : SemiNormedGroup.{u}) [normed_with_aut r V] (i : \u2124) :\n  ((Ext' i).obj (op $ (Lbar.condensed.{u} r').obj S)).obj V.to_Cond \u27f6\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' \u22d9 PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r') \u2245\n  (Profinite.extend (Fintype_Lbar.{0 0} r')) \u22d9\n    (PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r' \u22d9 CHFPNG\u2081_to_CHFPNG\u2091\u2097.{0} \u22d9\n  CompHausFiltPseuNormGrp.to_Condensed.{0}) :=\n(((whiskering_left _ _ _).map_iso $\n  Profinite.extend_commutes (Fintype_Lbar.{0 0} r') (PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r')).app\n    (CHFPNG\u2081_to_CHFPNG\u2091\u2097.{0} \u22d9 CompHausFiltPseuNormGrp.to_Condensed.{0})).symm\n\ndef condensify_iso_extend' :\n  (condensify (Fintype_Lbar.{0 0} r' \u22d9 PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r')).obj S \u2245\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} \u2964 C)\nvariables {D : Type u'} [category.{v} D]\nvariable [\u2200 X : Profinite, has_limit (X.fintype_diagram \u22d9 F)]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends' (G : C \u2964 D)\n  [\u2200 X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n  [\u2200 X : Profinite.{v}, has_limit (X.fintype_diagram \u22d9 F \u22d9 G)] :\n  whisker_left Fintype.to_Profinite (extend_commutes F G).hom =\n  (functor.associator _ _ _).inv \u226b (whisker_right (extend_extends _).hom G) \u226b\n    (extend_extends _).inv :=\nby rw [\u2190 category.assoc, iso.eq_comp_inv, extend_commutes_comp_extend_extends]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends'' (G : C \u2964 D)\n  [\u2200 X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n  [\u2200 X : Profinite.{v}, has_limit (X.fintype_diagram \u22d9 F \u22d9 G)] :\n  whisker_left Fintype.to_Profinite (extend_commutes F G).inv =\n  (extend_extends _).hom \u226b (whisker_right (extend_extends _).inv G) \u226b\n    (functor.associator _ _ _).hom :=\nbegin\n  rw [\u2190 iso.inv_comp_eq, \u2190 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    \u2190 iso_whisker_right_hom, \u2190 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') \u226b (condensify_iso_extend r').hom =\n  (condensify_iso_extend r').hom \u226b (@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, \u2190 iso.app_inv, \u2190 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, \u2190 functor.map_comp, \u2190 functor.map_comp],\n  congr' 1,\n  rw [iso.app_inv, iso.app_hom, \u2190 whisker_right_app, \u2190 whisker_right_app,\n    \u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app],\n  congr' 1,\n  refine nonstrict_extend_ext _ _ (r'\u207b\u00b9) (1 * (r'\u207b\u00b9 * 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, \u2190 whisker_right_left, \u2190 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 [\u2190 iso.app_hom, \u2190 iso.app_inv, \u2190 functor.map_iso_hom, \u2190 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 \u226b (condensify_iso_extend' r' S).hom =\n  (condensify_iso_extend' r' S).hom \u226b ((Profinite.extend (Fintype_Lbar.{0 0} r')).obj S).Tinv_cond :=\nbegin\n  have := condensify_Tinv_iso r',\n  apply_fun (\u03bb \u03b7, \u03b7.app S) at this,\n  exact this,\nend\n\ndef useful_commsq (i : \u2124) (\u03b9 : ulift.{1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9) [normed_with_aut r V] :=\n  shift_sub_id.commsq\n    (ExtQprime.Tinv2 r r' breen_deligne.eg.data\n      (\u03bb c n, c * breen_deligne.eg.\u03ba r r' n)\n      (\u03bb c n, r' * (c * breen_deligne.eg.\u03ba r r' n))\n      ((Lbar.functor.{0 0} r').obj S) V i) \u03b9 h\u03b9\n\nsection\nopen breen_deligne thm95.universal_constants\n\nvariables (i : \u2115)\n\nlemma useful_commsq_bicartesian (\u03b9 : ulift.{1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9) [normed_with_aut r V]\n  (H1 : \u2200 j, c\u2080 r r' eg (\u03bb n, eg.\u03ba r r' n) (eg.\u03ba' r r') (i+1) \u27e8\u2124\u27e9 \u2264 \u03b9 j)\n  (H2 : \u2200 j, k (eg.\u03ba' r r') i ^ 2 * \u03b9 j \u2264 \u03b9 (j + 1))\n  (H3 : \u2200 j, k (eg.\u03ba' r r') (i+1) ^ 2 * \u03b9 j \u2264 \u03b9 (j + 1)) :\n  (useful_commsq r r' S V i \u03b9 h\u03b9).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 \u03b9 h\u03b9\n    (ExtQprime_iso_aux_system_comm' _ _ _ _ _ _ _ _),\n  rw [\u2190 whisker_right_twice],\n  refine shift_sub_id.bicartesian (aux_system.incl'.{0 1} r r' _ _ _ (eg.\u03ba r r')) _\n    i \u03b9 h\u03b9 _ _ _,\n  { apply_with system_of_complexes.shift_eq_zero {instances := ff},\n    swap 3, { apply thm94.explicit r r' _ _ (eg.\u03ba' r r'), },\n    any_goals { apply_instance },\n    { intro j,\n      refine le_trans _ ((c\u2080_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.\u03ba' r r'), },\n    any_goals { apply_instance },\n    { exact H1 },\n    { exact H3 } },\n  { intros c n,\n    let \u03ba := eg.\u03ba r r',\n    apply aux_system.short_exact r r' _ _ _ (\u03bb c n, r' * (c * \u03ba n)) \u03ba,\n    intro c, dsimp, apply_instance, }\nend\n\nlemma bicartesian_of_is_zero {\ud835\udcd2 : Type*} [category \ud835\udcd2] [abelian \ud835\udcd2]\n  {A B C D : \ud835\udcd2} (f\u2081 : A \u27f6 B) (g\u2081 : A \u27f6 C) (g\u2082 : B \u27f6 D) (f\u2082 : C \u27f6 D) (h : commsq f\u2081 g\u2081 g\u2082 f\u2082)\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 \u27e8\u03bb X f g h, _\u27e9, apply hA.eq_of_tgt },\n  { refine \u27e8\u03bb X f g h, _\u27e9, 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 {\ud835\udcd2 : Type*} [category \ud835\udcd2] [abelian \ud835\udcd2] {\u03b9 : Type*} (f : \u03b9 \u2192 \ud835\udcd2) [has_product f]\n  (hf : \u2200 i, is_zero (f i)) :\n  is_zero (\u220f 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  (\u03b9 : ulift.{1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9) [normed_with_aut r V]\n  (i : \u2124) (hi : i < 0) :\n  (useful_commsq r r' S V i \u03b9 h\u03b9).bicartesian :=\nbegin\n  have : 1 + i \u2264 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 {\ud835\udcd2 : Type*} [category \ud835\udcd2] {X Y : \ud835\udcd2} (f\u2081 : X \u27f6 X) (f\u2082 : Y \u27f6 Y)\n  (e : X \u2245 Y) (h : f\u2081 \u226b e.hom = e.hom \u226b f\u2082) (h\u2081 : is_iso f\u2081) :\n  is_iso f\u2082 :=\nby { rw [\u2190 iso.inv_comp_eq] at h, rw \u2190 h, apply_instance }\n\nopen category_theory.preadditive\n\nlemma is_iso_sq' {\ud835\udcd2 : Type*} [category \ud835\udcd2] [abelian \ud835\udcd2] [enough_projectives \ud835\udcd2]\n  {X Y Z : bounded_homotopy_category \ud835\udcd2} (f\u2081 : X \u27f6 X) (f\u2082 : Y \u27f6 Y) (f\u2083 : Z \u27f6 Z)\n  (e : Y \u2245 X) (h : e.hom \u226b f\u2081 = f\u2082 \u226b e.hom) (i : \u2124)\n  (h\u2081 : is_iso (((Ext i).map f\u2081.op).app Z - ((Ext i).obj _).map f\u2083)) :\n  is_iso (((Ext i).map f\u2082.op).app Z - ((Ext i).obj _).map f\u2083) :=\nbegin\n  refine is_iso_sq _ _ ((functor.map_iso _ e.op).app _) _ h\u2081,\n  rw [iso.app_hom, functor.map_iso_hom, sub_comp, comp_sub, nat_trans.naturality,\n      \u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app, \u2190 functor.map_comp, \u2190 functor.map_comp,\n      iso.op_hom, \u2190 op_comp, \u2190 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] : \u2200 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, \u2190 functor.map_comp, \u2190 functor.map_comp, condensify_Tinv_iso'], },\n  revert i,\n  refine Tinv2_iso_of_bicartesian' r breen_deligne.eg\n      (\u03bb c n, c * breen_deligne.eg.\u03ba r r' n)\n      (\u03bb c n, r' * (c * breen_deligne.eg.\u03ba r r' n))\n    ((Lbar.functor.{0 0} r').obj S) V _,\n  rintro (i|(_|i)),\n  { refine \u27e8\u03b9 r r' i, h\u03b9 r r' i, _, _, _, _\u27e9,\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 \u27e8j\u27e9, apply H\u03b91 },\n    { rintro \u27e8j\u27e9, apply H\u03b92a },\n    { rintro \u27e8j\u27e9, apply H\u03b92b },\n    { rintro \u27e8j\u27e9, apply H\u03b91' },\n    { rintro \u27e8j\u27e9, apply H\u03b92b },\n    { rintro \u27e8j\u27e9, apply H\u03b92c } },\n  { refine \u27e8\u03b9 r r' 0, h\u03b9 r r' 0, _, _, _, _\u27e9,\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 \u27e8j\u27e9, apply H\u03b91 },\n    { rintro \u27e8j\u27e9, apply H\u03b92a },\n    { rintro \u27e8j\u27e9, apply H\u03b92b }, }, },\n  { refine \u27e8\u03b9 r r' 0, h\u03b9 r r' 0, _, _, _, _\u27e9,\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 : \u2200 (v : V), (normed_with_aut.T.inv v) = 2 \u2022 v) :\n  \u2200 i, is_iso (((Ext' i).map ((condensify_Tinv2 (Fintype_Lbar.{0 0} r')).app S).op).app\n    (Condensed.of_top_ab \u21a5V)) :=\nbegin\n  intro i,\n  rw [condensify_Tinv2_eq, \u2190 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 \u2022 \ud835\udfd9 _,\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 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n-/\n\nimport Aesop.Builder.Constructors\nimport Aesop.Builder.NormSimp\nimport Aesop.Builder.Tactic\n\nopen Lean\nopen Lean.Meta\n\nnamespace Aesop\n\n-- TODO In the default builders below, we should distinguish between fatal and\n-- nonfatal errors. E.g. if the `tactic` builder finds a declaration that is not\n-- of tactic type, this is a nonfatal error and we should continue with the next\n-- builder. But if the simp builder finds an equation that cannot be interpreted\n-- as a simp lemma for some reason, this is a fatal error. Continuing with the\n-- next builder is more confusing than anything because the user probably\n-- intended to add a simp lemma.\n\nnamespace RuleBuilder\n\nprivate def err (ruleType : String) : RuleBuilder := \u03bb input =>\n  throwError m!\"aesop: Unable to interpret {input.kind.toRuleIdent} as {ruleType} rule. Try specifying a builder.\"\n\ndef default : RuleBuilder := \u03bb input =>\n  match input.phase with\n  | PhaseName.safe =>\n    constructorsDef input <|>\n    tacticDef input <|>\n    applyDef input <|>\n    err \"a safe\" input\n  | PhaseName.unsafe =>\n    constructorsDef input <|>\n    tacticDef input <|>\n    applyDef input <|>\n    err \"an unsafe\" input\n  | PhaseName.norm =>\n    constructorsDef input <|>\n    tacticDef input <|>\n    simp input <|>\n    applyDef input <|>\n    err \"a norm\" input\n  where\n    tacticDef := tactic RegularBuilderOptions.default\n    applyDef := apply RegularBuilderOptions.default\n    constructorsDef := constructors RegularBuilderOptions.default\n\nend RuleBuilder\n\nend Aesop\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/Aesop/Builder/Default.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651622568252118, "lm_q2_score": 0.04146227345168354, "lm_q1q2_score": 0.00980650042500879}}
{"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\u2081 v\u2082 u\u2081 u\u2082\n\nopen CategoryTheory\n\nopen CategoryTheory.MonoidalCategory\n\nvariable {C : Type u\u2081} [Category.{v\u2081} C] [MonoidalCategory.{v\u2081} C]\n\nsection\n\nopen CategoryTheory.Limits\n\nvariable [HasCoequalizers C]\n\nsection\n\nvariable [\u2200 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_\u03c0_preserves_coequalizer_inv_desc {W X Y Z : C} (f g : X \u27f6 Y) (h : Z \u2297 Y \u27f6 W)\n    (wh : (\ud835\udfd9 Z \u2297 f) \u226b h = (\ud835\udfd9 Z \u2297 g) \u226b h) :\n    (\ud835\udfd9 Z \u2297 coequalizer.\u03c0 f g) \u226b\n        (PreservesCoequalizer.iso (tensorLeft Z) f g).inv \u226b coequalizer.desc h wh =\n      h :=\n  map_\u03c0_preserves_coequalizer_inv_desc (tensorLeft Z) f g h wh\n#align id_tensor_\u03c0_preserves_coequalizer_inv_desc id_tensor_\u03c0_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_\u03c0_preserves_coequalizer_inv_colimMap_desc {X Y Z X' Y' Z' : C} (f g : X \u27f6 Y)\n    (f' g' : X' \u27f6 Y') (p : Z \u2297 X \u27f6 X') (q : Z \u2297 Y \u27f6 Y') (wf : (\ud835\udfd9 Z \u2297 f) \u226b q = p \u226b f')\n    (wg : (\ud835\udfd9 Z \u2297 g) \u226b q = p \u226b g') (h : Y' \u27f6 Z') (wh : f' \u226b h = g' \u226b h) :\n    (\ud835\udfd9 Z \u2297 coequalizer.\u03c0 f g) \u226b\n        (PreservesCoequalizer.iso (tensorLeft Z) f g).inv \u226b\n          colimMap (parallelPairHom (\ud835\udfd9 Z \u2297 f) (\ud835\udfd9 Z \u2297 g) f' g' p q wf wg) \u226b coequalizer.desc h wh =\n      q \u226b h :=\n  map_\u03c0_preserves_coequalizer_inv_colimMap_desc (tensorLeft Z) f g f' g' p q wf wg h wh\n#align id_tensor_\u03c0_preserves_coequalizer_inv_colim_map_desc id_tensor_\u03c0_preserves_coequalizer_inv_colimMap_desc\n\nend\n\nsection\n\nvariable [\u2200 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 \u03c0_tensor_id_preserves_coequalizer_inv_desc {W X Y Z : C} (f g : X \u27f6 Y) (h : Y \u2297 Z \u27f6 W)\n    (wh : (f \u2297 \ud835\udfd9 Z) \u226b h = (g \u2297 \ud835\udfd9 Z) \u226b h) :\n    (coequalizer.\u03c0 f g \u2297 \ud835\udfd9 Z) \u226b\n        (PreservesCoequalizer.iso (tensorRight Z) f g).inv \u226b coequalizer.desc h wh =\n      h :=\n  map_\u03c0_preserves_coequalizer_inv_desc (tensorRight Z) f g h wh\n#align \u03c0_tensor_id_preserves_coequalizer_inv_desc \u03c0_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 \u03c0_tensor_id_preserves_coequalizer_inv_colimMap_desc {X Y Z X' Y' Z' : C} (f g : X \u27f6 Y)\n    (f' g' : X' \u27f6 Y') (p : X \u2297 Z \u27f6 X') (q : Y \u2297 Z \u27f6 Y') (wf : (f \u2297 \ud835\udfd9 Z) \u226b q = p \u226b f')\n    (wg : (g \u2297 \ud835\udfd9 Z) \u226b q = p \u226b g') (h : Y' \u27f6 Z') (wh : f' \u226b h = g' \u226b h) :\n    (coequalizer.\u03c0 f g \u2297 \ud835\udfd9 Z) \u226b\n        (PreservesCoequalizer.iso (tensorRight Z) f g).inv \u226b\n          colimMap (parallelPairHom (f \u2297 \ud835\udfd9 Z) (g \u2297 \ud835\udfd9 Z) f' g' p q wf wg) \u226b coequalizer.desc h wh =\n      q \u226b h :=\n  map_\u03c0_preserves_coequalizer_inv_colimMap_desc (tensorRight Z) f g f' g' p q wf wg h wh\n#align \u03c0_tensor_id_preserves_coequalizer_inv_colim_map_desc \u03c0_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 \u2297 X \u27f6 X\n  one_act_left' : (A.one \u2297 \ud835\udfd9 X) \u226b act_left = (\u03bb_ X).Hom := by obviously\n  left_assoc' :\n    (A.mul \u2297 \ud835\udfd9 X) \u226b act_left = (\u03b1_ A.pt A.pt X).Hom \u226b (\ud835\udfd9 A.pt \u2297 act_left) \u226b act_left := by obviously\n  actRight : X \u2297 B.pt \u27f6 X\n  actRight_one' : (\ud835\udfd9 X \u2297 B.one) \u226b act_right = (\u03c1_ X).Hom := by obviously\n  right_assoc' :\n    (\ud835\udfd9 X \u2297 B.mul) \u226b act_right = (\u03b1_ X B.pt B.pt).inv \u226b (act_right \u2297 \ud835\udfd9 B.pt) \u226b act_right := by\n    obviously\n  middle_assoc' :\n    (act_left \u2297 \ud835\udfd9 B.pt) \u226b act_right = (\u03b1_ A.pt X B.pt).Hom \u226b (\ud835\udfd9 A.pt \u2297 act_right) \u226b 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 \u27f6 N.pt\n  left_act_hom' : M.actLeft \u226b hom = (\ud835\udfd9 A.pt \u2297 hom) \u226b N.actLeft := by obviously\n  right_act_hom' : M.actRight \u226b hom = (hom \u2297 \ud835\udfd9 B.pt) \u226b 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 := \ud835\udfd9 M.pt\n#align Bimod.id' Bimod.id'\n\ninstance homInhabited (M : Bimod A B) : Inhabited (Hom M M) :=\n  \u27e8id' M\u27e9\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 \u226b 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) : (\ud835\udfd9 M : Hom M M).Hom = \ud835\udfd9 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 \u27f6 N) (g : N \u27f6 K) :\n    (f \u226b g : Hom M K).Hom = f.Hom \u226b 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 \u2245 Q.pt)\n    (f_left_act_hom : P.actLeft \u226b f.Hom = (\ud835\udfd9 X.pt \u2297 f.Hom) \u226b Q.actLeft)\n    (f_right_act_hom : P.actRight \u226b f.Hom = (f.Hom \u2297 \ud835\udfd9 Y.pt) \u226b Q.actRight) : P \u2245 Q\n    where\n  Hom := \u27e8f.Hom\u27e9\n  inv :=\n    { Hom := f.inv\n      left_act_hom' := by\n        rw [\u2190 cancel_mono f.hom, category.assoc, category.assoc, iso.inv_hom_id, category.comp_id,\n          f_left_act_hom, \u2190 category.assoc, \u2190 id_tensor_comp, iso.inv_hom_id,\n          monoidal_category.tensor_id, category.id_comp]\n      right_act_hom' := by\n        rw [\u2190 cancel_mono f.hom, category.assoc, category.assoc, iso.inv_hom_id, category.comp_id,\n          f_right_act_hom, \u2190 category.assoc, \u2190 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  \u27e8regular A\u27e9\n\n/-- The forgetful functor from bimodule objects to the ambient category. -/\ndef forget : Bimod A B \u2964 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 \u2297 \ud835\udfd9 Q.pt) ((\u03b1_ _ _ _).Hom \u226b (\ud835\udfd9 P.pt \u2297 Q.actLeft))\n#align Bimod.tensor_Bimod.X Bimod.TensorBimod.x\n\nsection\n\nvariable [\u2200 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 \u2297 x P Q \u27f6 x P Q :=\n  (PreservesCoequalizer.iso (tensorLeft R.pt) _ _).inv \u226b\n    colimMap\n      (parallelPairHom _ _ _ _\n        ((\ud835\udfd9 _ \u2297 (\u03b1_ _ _ _).Hom) \u226b (\u03b1_ _ _ _).inv \u226b (P.actLeft \u2297 \ud835\udfd9 S.pt \u2297 \ud835\udfd9 Q.pt) \u226b (\u03b1_ _ _ _).inv)\n        ((\u03b1_ _ _ _).inv \u226b (P.actLeft \u2297 \ud835\udfd9 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 [\u2190 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_\u03c0_actLeft :\n    (\ud835\udfd9 R.pt \u2297 coequalizer.\u03c0 _ _) \u226b actLeft P Q =\n      (\u03b1_ _ _ _).inv \u226b (P.actLeft \u2297 \ud835\udfd9 Q.pt) \u226b coequalizer.\u03c0 _ _ :=\n  by\n  erw [map_\u03c0_preserves_coequalizer_inv_colim_map (tensor_left _)]\n  simp only [category.assoc]\n#align Bimod.tensor_Bimod.id_tensor_\u03c0_act_left Bimod.TensorBimod.id_tensor_\u03c0_actLeft\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem one_act_left' : (R.one \u2297 \ud835\udfd9 _) \u226b actLeft P Q = (\u03bb_ _).Hom :=\n  by\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp [X]\n  slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, \u2190 tensor_id_comp_id_tensor]\n  slice_lhs 2 3 => rw [id_tensor_\u03c0_act_left]\n  slice_lhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_inv_naturality]\n  slice_lhs 2 3 => rw [\u2190 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 \u2297 \ud835\udfd9 _) \u226b actLeft P Q = (\u03b1_ R.pt R.pt _).Hom \u226b (\ud835\udfd9 R.pt \u2297 actLeft P Q) \u226b actLeft P Q :=\n  by\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp [X]\n  slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, \u2190 tensor_id_comp_id_tensor]\n  slice_lhs 2 3 => rw [id_tensor_\u03c0_act_left]\n  slice_lhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_inv_naturality]\n  slice_lhs 2 3 => rw [\u2190 comp_tensor_id, left_assoc, comp_tensor_id, comp_tensor_id]\n  slice_rhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n  slice_rhs 2 3 => rw [\u2190 id_tensor_comp, id_tensor_\u03c0_act_left, id_tensor_comp, id_tensor_comp]\n  slice_rhs 4 5 => rw [id_tensor_\u03c0_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 [\u2200 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 \u2297 T.pt \u27f6 x P Q :=\n  (PreservesCoequalizer.iso (tensorRight T.pt) _ _).inv \u226b\n    colimMap\n      (parallelPairHom _ _ _ _\n        ((\u03b1_ _ _ _).Hom \u226b (\u03b1_ _ _ _).Hom \u226b (\ud835\udfd9 P.pt \u2297 \ud835\udfd9 S.pt \u2297 Q.actRight) \u226b (\u03b1_ _ _ _).inv)\n        ((\u03b1_ _ _ _).Hom \u226b (\ud835\udfd9 P.pt \u2297 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 [\u2190 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 [\u2190 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 \u03c0_tensor_id_actRight :\n    (coequalizer.\u03c0 _ _ \u2297 \ud835\udfd9 T.pt) \u226b actRight P Q =\n      (\u03b1_ _ _ _).Hom \u226b (\ud835\udfd9 P.pt \u2297 Q.actRight) \u226b coequalizer.\u03c0 _ _ :=\n  by\n  erw [map_\u03c0_preserves_coequalizer_inv_colim_map (tensor_right _)]\n  simp only [category.assoc]\n#align Bimod.tensor_Bimod.\u03c0_tensor_id_act_right Bimod.TensorBimod.\u03c0_tensor_id_actRight\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem actRight_one' : (\ud835\udfd9 _ \u2297 T.one) \u226b actRight P Q = (\u03c1_ _).Hom :=\n  by\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp [X]\n  slice_lhs 1 2 => rw [tensor_id_comp_id_tensor, \u2190 id_tensor_comp_tensor_id]\n  slice_lhs 2 3 => rw [\u03c0_tensor_id_act_right]\n  slice_lhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n  slice_lhs 2 3 => rw [\u2190 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    (\ud835\udfd9 _ \u2297 T.mul) \u226b actRight P Q = (\u03b1_ _ T.pt T.pt).inv \u226b (actRight P Q \u2297 \ud835\udfd9 T.pt) \u226b actRight P Q :=\n  by\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp [X]\n  slice_lhs 1 2 => rw [tensor_id_comp_id_tensor, \u2190 id_tensor_comp_tensor_id]\n  slice_lhs 2 3 => rw [\u03c0_tensor_id_act_right]\n  slice_lhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n  slice_lhs 2 3 => rw [\u2190 id_tensor_comp, right_assoc, id_tensor_comp, id_tensor_comp]\n  slice_rhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_inv_naturality]\n  slice_rhs 2 3 => rw [\u2190 comp_tensor_id, \u03c0_tensor_id_act_right, comp_tensor_id, comp_tensor_id]\n  slice_rhs 4 5 => rw [\u03c0_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 [\u2200 X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [\u2200 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 \u2297 \ud835\udfd9 T.pt) \u226b actRight P Q =\n      (\u03b1_ R.pt _ T.pt).Hom \u226b (\ud835\udfd9 R.pt \u2297 actRight P Q) \u226b actLeft P Q :=\n  by\n  refine' (cancel_epi ((tensor_left _ \u22d9 tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp [X]\n  slice_lhs 1 2 => rw [\u2190 comp_tensor_id, id_tensor_\u03c0_act_left, comp_tensor_id, comp_tensor_id]\n  slice_lhs 3 4 => rw [\u03c0_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 [\u2190 id_tensor_comp, \u03c0_tensor_id_act_right, id_tensor_comp, id_tensor_comp]\n  slice_rhs 4 5 => rw [id_tensor_\u03c0_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 [\u2200 X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [\u2200 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\u2081 M\u2082 : Bimod X Y} {N\u2081 N\u2082 : Bimod Y Z} (f : M\u2081 \u27f6 M\u2082)\n    (g : N\u2081 \u27f6 N\u2082) : M\u2081.tensorBimod N\u2081 \u27f6 M\u2082.tensorBimod N\u2082\n    where\n  Hom :=\n    colimMap\n      (parallelPairHom _ _ _ _ ((f.Hom \u2297 \ud835\udfd9 Y.pt) \u2297 g.Hom) (f.Hom \u2297 g.Hom)\n        (by\n          rw [\u2190 tensor_comp, \u2190 tensor_comp, hom.right_act_hom, category.id_comp, category.comp_id])\n        (by\n          slice_lhs 2 3 => rw [\u2190 tensor_comp, hom.left_act_hom, category.id_comp]\n          slice_rhs 1 2 => rw [associator_naturality]\n          slice_rhs 2 3 => rw [\u2190 tensor_comp, category.comp_id]))\n  left_act_hom' :=\n    by\n    refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n    dsimp\n    slice_lhs 1 2 => rw [tensor_Bimod.id_tensor_\u03c0_act_left]\n    slice_lhs 3 4 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n    slice_lhs 2 3 => rw [\u2190 tensor_comp, hom.left_act_hom, category.id_comp]\n    slice_rhs 1 2 => rw [\u2190 id_tensor_comp, \u03b9_colim_map, parallel_pair_hom_app_one, id_tensor_comp]\n    slice_rhs 2 3 => rw [tensor_Bimod.id_tensor_\u03c0_act_left]\n    slice_rhs 1 2 => rw [associator_inv_naturality]\n    slice_rhs 2 3 => rw [\u2190 tensor_comp, category.comp_id]\n  right_act_hom' :=\n    by\n    refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n    dsimp\n    slice_lhs 1 2 => rw [tensor_Bimod.\u03c0_tensor_id_act_right]\n    slice_lhs 3 4 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n    slice_lhs 2 3 => rw [\u2190 tensor_comp, category.id_comp, hom.right_act_hom]\n    slice_rhs 1 2 => rw [\u2190 comp_tensor_id, \u03b9_colim_map, parallel_pair_hom_app_one, comp_tensor_id]\n    slice_rhs 2 3 => rw [tensor_Bimod.\u03c0_tensor_id_act_right]\n    slice_rhs 1 2 => rw [associator_naturality]\n    slice_rhs 2 3 => rw [\u2190 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 (\ud835\udfd9 M) (\ud835\udfd9 N) = \ud835\udfd9 (M.tensorBimod N) :=\n  by\n  ext\n  simp only [id_hom', tensor_id, tensor_hom_hom, \u03b9_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\u2081 M\u2082 M\u2083 : Bimod X Y} {N\u2081 N\u2082 N\u2083 : Bimod Y Z} (f\u2081 : M\u2081 \u27f6 M\u2082)\n    (f\u2082 : M\u2082 \u27f6 M\u2083) (g\u2081 : N\u2081 \u27f6 N\u2082) (g\u2082 : N\u2082 \u27f6 N\u2083) :\n    tensorHom (f\u2081 \u226b f\u2082) (g\u2081 \u226b g\u2082) = tensorHom f\u2081 g\u2081 \u226b tensorHom f\u2082 g\u2082 :=\n  by\n  ext\n  simp only [comp_hom', tensor_comp, tensor_hom_hom, \u03b9_colim_map, parallel_pair_hom_app_one,\n    category.assoc, \u03b9_colim_map_assoc]\n#align Bimod.tensor_comp Bimod.tensor_comp\n\nend\n\nnamespace AssociatorBimod\n\nvariable [\u2200 X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [\u2200 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 \u2297 L.pt \u27f6 (P.tensorBimod (Q.tensorBimod L)).pt :=\n  (PreservesCoequalizer.iso (tensorRight L.pt) _ _).inv \u226b\n    coequalizer.desc ((\u03b1_ _ _ _).Hom \u226b (\ud835\udfd9 P.pt \u2297 coequalizer.\u03c0 _ _) \u226b coequalizer.\u03c0 _ _)\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, \u2190 id_tensor_comp_tensor_id]\n        slice_lhs 3 4 => rw [coequalizer.condition]\n        slice_lhs 2 3 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n        slice_lhs 3 4 => rw [\u2190 id_tensor_comp, tensor_Bimod.id_tensor_\u03c0_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 [\u2190 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 \u27f6 (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 _ \u22d9 tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n      dsimp [tensor_Bimod.X]\n      slice_lhs 1 2 =>\n        rw [\u2190 comp_tensor_id, tensor_Bimod.\u03c0_tensor_id_act_right, comp_tensor_id, comp_tensor_id]\n      slice_lhs 3 5 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n      slice_lhs 2 3 => rw [associator_naturality]\n      slice_lhs 3 4 => rw [\u2190 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, \u2190 id_tensor_comp_tensor_id]\n      slice_rhs 3 5 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n      slice_rhs 2 3 => rw [\u2190 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 \u226b hom P Q L =\n      (\ud835\udfd9 R.pt \u2297 hom P Q L) \u226b (P.tensorBimod (Q.tensorBimod L)).actLeft :=\n  by\n  dsimp; dsimp [hom, hom_aux]\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_left_map]\n  slice_lhs 1 2 => rw [tensor_Bimod.id_tensor_\u03c0_act_left]\n  slice_lhs 3 4 => rw [coequalizer.\u03c0_desc]\n  slice_rhs 1 2 => rw [\u2190 id_tensor_comp, coequalizer.\u03c0_desc, id_tensor_comp]\n  refine' (cancel_epi ((tensor_right _ \u22d9 tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp; dsimp [tensor_Bimod.X]\n  slice_lhs 1 2 => rw [associator_inv_naturality]\n  slice_lhs 2 3 =>\n    rw [\u2190 comp_tensor_id, tensor_Bimod.id_tensor_\u03c0_act_left, comp_tensor_id, comp_tensor_id]\n  slice_lhs 4 6 => rw [\u03c0_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 [\u2190 id_tensor_comp, \u2190 id_tensor_comp, \u03c0_tensor_id_preserves_coequalizer_inv_desc,\n      id_tensor_comp, id_tensor_comp]\n  slice_rhs 3 4 => erw [tensor_Bimod.id_tensor_\u03c0_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 \u226b hom P Q L =\n      (hom P Q L \u2297 \ud835\udfd9 U.pt) \u226b (P.tensorBimod (Q.tensorBimod L)).actRight :=\n  by\n  dsimp; dsimp [hom, hom_aux]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_right_map]\n  slice_lhs 1 2 => rw [tensor_Bimod.\u03c0_tensor_id_act_right]\n  slice_lhs 3 4 => rw [coequalizer.\u03c0_desc]\n  slice_rhs 1 2 => rw [\u2190 comp_tensor_id, coequalizer.\u03c0_desc, comp_tensor_id]\n  refine' (cancel_epi ((tensor_right _ \u22d9 tensor_right _).map (coequalizer.\u03c0 _ _))).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, \u2190 id_tensor_comp_tensor_id]\n  slice_lhs 3 5 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_lhs 2 3 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n  slice_rhs 1 3 =>\n    rw [\u2190 comp_tensor_id, \u2190 comp_tensor_id, \u03c0_tensor_id_preserves_coequalizer_inv_desc,\n      comp_tensor_id, comp_tensor_id]\n  slice_rhs 3 4 => erw [tensor_Bimod.\u03c0_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 [\u2190 id_tensor_comp, tensor_Bimod.\u03c0_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 \u2297 (Q.tensorBimod L).pt \u27f6 ((P.tensorBimod Q).tensorBimod L).pt :=\n  (PreservesCoequalizer.iso (tensorLeft P.pt) _ _).inv \u226b\n    coequalizer.desc ((\u03b1_ _ _ _).inv \u226b (coequalizer.\u03c0 _ _ \u2297 \ud835\udfd9 L.pt) \u226b coequalizer.\u03c0 _ _)\n      (by\n        dsimp; dsimp [tensor_Bimod.X]\n        slice_lhs 1 2 => rw [associator_inv_naturality]\n        rw [\u2190 iso.inv_hom_id_assoc (\u03b1_ _ _ _) (\ud835\udfd9 P.X \u2297 Q.act_right), comp_tensor_id]\n        slice_lhs 3 4 =>\n          rw [\u2190 comp_tensor_id, category.assoc, \u2190 tensor_Bimod.\u03c0_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 \u27f6 ((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.\u03c0 _ _))).1 _\n      dsimp [tensor_Bimod.X]\n      slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, \u2190 tensor_id_comp_id_tensor]\n      slice_lhs 2 4 => rw [id_tensor_\u03c0_preserves_coequalizer_inv_desc]\n      slice_lhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_inv_naturality]\n      slice_lhs 2 3 => rw [\u2190 comp_tensor_id, coequalizer.condition, comp_tensor_id, comp_tensor_id]\n      slice_rhs 1 2 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n      slice_rhs 2 3 =>\n        rw [\u2190 id_tensor_comp, tensor_Bimod.id_tensor_\u03c0_act_left, id_tensor_comp, id_tensor_comp]\n      slice_rhs 4 6 => rw [id_tensor_\u03c0_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 \u226b inv P Q L = \ud835\udfd9 _ :=\n  by\n  dsimp [hom, hom_aux, inv, inv_aux]\n  ext\n  slice_lhs 1 2 => rw [coequalizer.\u03c0_desc]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_right_map]\n  slice_lhs 1 3 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_lhs 3 4 => rw [coequalizer.\u03c0_desc]\n  slice_lhs 2 4 => rw [id_tensor_\u03c0_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 \u226b hom P Q L = \ud835\udfd9 _ :=\n  by\n  dsimp [hom, hom_aux, inv, inv_aux]\n  ext\n  slice_lhs 1 2 => rw [coequalizer.\u03c0_desc]\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_left_map]\n  slice_lhs 1 3 => rw [id_tensor_\u03c0_preserves_coequalizer_inv_desc]\n  slice_lhs 3 4 => rw [coequalizer.\u03c0_desc]\n  slice_lhs 2 4 => rw [\u03c0_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 \u27f6 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 \u27f6 TensorBimod.x (regular R) P :=\n  (\u03bb_ P.pt).inv \u226b (R.one \u2297 \ud835\udfd9 _) \u226b coequalizer.\u03c0 _ _\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 \u226b inv P = \ud835\udfd9 _ :=\n  by\n  dsimp only [hom, inv, tensor_Bimod.X]\n  ext; dsimp\n  slice_lhs 1 2 => rw [coequalizer.\u03c0_desc]\n  slice_lhs 1 2 => rw [left_unitor_inv_naturality]\n  slice_lhs 2 3 => rw [id_tensor_comp_tensor_id, \u2190 tensor_id_comp_id_tensor]\n  slice_lhs 3 3 => rw [\u2190 iso.inv_hom_id_assoc (\u03b1_ R.X R.X P.X) (\ud835\udfd9 R.X \u2297 P.act_left)]\n  slice_lhs 4 6 => rw [\u2190 category.assoc, \u2190 coequalizer.condition]\n  slice_lhs 2 3 => rw [\u2190 monoidal_category.tensor_id, associator_inv_naturality]\n  slice_lhs 3 4 => rw [\u2190 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 \u226b hom P = \ud835\udfd9 _ :=\n  by\n  dsimp [hom, inv]\n  slice_lhs 3 4 => rw [coequalizer.\u03c0_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 [\u2200 X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [\u2200 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 \u226b hom P = (\ud835\udfd9 R.pt \u2297 hom P) \u226b P.actLeft :=\n  by\n  dsimp; dsimp [hom, tensor_Bimod.act_left, regular]\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp\n  slice_lhs 1 4 => rw [id_tensor_\u03c0_preserves_coequalizer_inv_colimMap_desc]\n  slice_lhs 2 3 => rw [left_assoc]\n  slice_rhs 1 2 => rw [\u2190 id_tensor_comp, coequalizer.\u03c0_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 \u226b hom P = (hom P \u2297 \ud835\udfd9 S.pt) \u226b P.actRight :=\n  by\n  dsimp; dsimp [hom, tensor_Bimod.act_right, regular]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp\n  slice_lhs 1 4 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_colimMap_desc]\n  slice_rhs 1 2 => rw [\u2190 comp_tensor_id, coequalizer.\u03c0_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) \u27f6 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 \u27f6 TensorBimod.x P (regular S) :=\n  (\u03c1_ P.pt).inv \u226b (\ud835\udfd9 _ \u2297 S.one) \u226b coequalizer.\u03c0 _ _\n#align Bimod.right_unitor_Bimod.inv Bimod.RightUnitorBimod.inv\n\ntheorem hom_inv_id : hom P \u226b inv P = \ud835\udfd9 _ :=\n  by\n  dsimp only [hom, inv, tensor_Bimod.X]\n  ext; dsimp\n  slice_lhs 1 2 => rw [coequalizer.\u03c0_desc]\n  slice_lhs 1 2 => rw [right_unitor_inv_naturality]\n  slice_lhs 2 3 => rw [tensor_id_comp_id_tensor, \u2190 id_tensor_comp_tensor_id]\n  slice_lhs 3 4 => rw [coequalizer.condition]\n  slice_lhs 2 3 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n  slice_lhs 3 4 => rw [\u2190 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 \u226b hom P = \ud835\udfd9 _ :=\n  by\n  dsimp [hom, inv]\n  slice_lhs 3 4 => rw [coequalizer.\u03c0_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 [\u2200 X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [\u2200 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 \u226b hom P = (\ud835\udfd9 R.pt \u2297 hom P) \u226b P.actLeft :=\n  by\n  dsimp; dsimp [hom, tensor_Bimod.act_left, regular]\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp\n  slice_lhs 1 4 => rw [id_tensor_\u03c0_preserves_coequalizer_inv_colimMap_desc]\n  slice_lhs 2 3 => rw [middle_assoc]\n  slice_rhs 1 2 => rw [\u2190 id_tensor_comp, coequalizer.\u03c0_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 \u226b hom P = (hom P \u2297 \ud835\udfd9 S.pt) \u226b P.actRight :=\n  by\n  dsimp; dsimp [hom, tensor_Bimod.act_right, regular]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp\n  slice_lhs 1 4 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_colimMap_desc]\n  slice_lhs 2 3 => rw [right_assoc]\n  slice_rhs 1 2 => rw [\u2190 comp_tensor_id, coequalizer.\u03c0_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 [\u2200 X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [\u2200 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 \u2245 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 \u2245 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) \u2245 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 \u27f6 P)\n    (g : P \u27f6 Q) : tensorHom (\ud835\udfd9 M) (f \u226b g) = tensorHom (\ud835\udfd9 M) f \u226b tensorHom (\ud835\udfd9 M) g := by\n  rw [\u2190 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 \u27f6 N) :\n    tensorHom (\ud835\udfd9 (regular X)) f = (leftUnitorBimod M).Hom \u226b f \u226b (leftUnitorBimod N).inv :=\n  by\n  dsimp [tensor_hom, regular, left_unitor_Bimod]\n  ext; dsimp\n  slice_lhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [left_unitor_Bimod.hom]\n  slice_rhs 1 2 => rw [coequalizer.\u03c0_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, \u2190 tensor_id_comp_id_tensor]\n  slice_rhs 4 4 => rw [\u2190 iso.inv_hom_id_assoc (\u03b1_ X.X X.X N.X) (\ud835\udfd9 X.X \u2297 N.act_left)]\n  slice_rhs 5 7 => rw [\u2190 category.assoc, \u2190 coequalizer.condition]\n  slice_rhs 3 4 => rw [\u2190 monoidal_category.tensor_id, associator_inv_naturality]\n  slice_rhs 4 5 => rw [\u2190 comp_tensor_id, Mon_.one_mul]\n  have : (\u03bb_ (X.X \u2297 N.X)).inv \u226b (\u03b1_ (\ud835\udfd9_ C) X.X N.X).inv \u226b ((\u03bb_ X.X).Hom \u2297 \ud835\udfd9 N.X) = \ud835\udfd9 _ := 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 \u27f6 P') :\n    tensorHom (\ud835\udfd9 (M.tensorBimod N)) f =\n      (associatorBimod M N P).Hom \u226b\n        tensorHom (\ud835\udfd9 M) (tensorHom (\ud835\udfd9 N) f) \u226b (associatorBimod M N P').inv :=\n  by\n  dsimp [tensor_hom, tensor_Bimod, associator_Bimod]\n  ext; dsimp\n  slice_lhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [tensor_Bimod.X, associator_Bimod.hom]\n  slice_rhs 1 2 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.hom_aux, associator_Bimod.inv]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_right_map]\n  slice_rhs 1 3 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_rhs 3 4 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 2 3 => rw [\u2190 id_tensor_comp, \u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 3 4 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.inv_aux]\n  slice_rhs 2 2 => rw [id_tensor_comp]\n  slice_rhs 3 5 => rw [id_tensor_\u03c0_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, \u2190 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 \u27f6 N) (g : N \u27f6 P)\n    (Q : Bimod Y Z) : tensorHom (f \u226b g) (\ud835\udfd9 Q) = tensorHom f (\ud835\udfd9 Q) \u226b tensorHom g (\ud835\udfd9 Q) := by\n  rw [\u2190 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 \u27f6 N) :\n    tensorHom f (\ud835\udfd9 (regular Y)) = (rightUnitorBimod M).Hom \u226b f \u226b (rightUnitorBimod N).inv :=\n  by\n  dsimp [tensor_hom, regular, right_unitor_Bimod]\n  ext; dsimp\n  slice_lhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [right_unitor_Bimod.hom]\n  slice_rhs 1 2 => rw [coequalizer.\u03c0_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, \u2190 id_tensor_comp_tensor_id]\n  slice_rhs 4 5 => rw [coequalizer.condition]\n  slice_rhs 3 4 => rw [\u2190 monoidal_category.tensor_id, associator_naturality]\n  slice_rhs 4 5 => rw [\u2190 id_tensor_comp, Mon_.mul_one]\n  have : (\u03c1_ (N.X \u2297 Y.X)).inv \u226b (\u03b1_ N.X Y.X (\ud835\udfd9_ C)).Hom \u226b (\ud835\udfd9 N.X \u2297 (\u03c1_ Y.X).Hom) = \ud835\udfd9 _ := 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 \u27f6 M') (N : Bimod X Y)\n    (P : Bimod Y Z) :\n    tensorHom f (\ud835\udfd9 (N.tensorBimod P)) =\n      (associatorBimod M N P).inv \u226b\n        tensorHom (tensorHom f (\ud835\udfd9 N)) (\ud835\udfd9 P) \u226b (associatorBimod M' N P).Hom :=\n  by\n  dsimp [tensor_hom, tensor_Bimod, associator_Bimod]\n  ext; dsimp\n  slice_lhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [tensor_Bimod.X, associator_Bimod.inv]\n  slice_rhs 1 2 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.inv_aux, associator_Bimod.hom]\n  refine' (cancel_epi ((tensor_left _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_left_map]\n  slice_rhs 1 3 => rw [id_tensor_\u03c0_preserves_coequalizer_inv_desc]\n  slice_rhs 3 4 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 2 3 => rw [\u2190 comp_tensor_id, \u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 3 4 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.hom_aux]\n  slice_rhs 2 2 => rw [comp_tensor_id]\n  slice_rhs 3 5 => rw [\u03c0_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, \u2190 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 \u27f6 N')\n    (P : Bimod Y Z) :\n    tensorHom (tensorHom (\ud835\udfd9 M) f) (\ud835\udfd9 P) =\n      (associatorBimod M N P).Hom \u226b\n        tensorHom (\ud835\udfd9 M) (tensorHom f (\ud835\udfd9 P)) \u226b (associatorBimod M N' P).inv :=\n  by\n  dsimp [tensor_hom, tensor_Bimod, associator_Bimod]\n  ext; dsimp\n  slice_lhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [associator_Bimod.hom]\n  slice_rhs 1 2 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.hom_aux]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  rw [tensor_right_map]\n  slice_lhs 1 2 => rw [\u2190 comp_tensor_id, \u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 1 3 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_rhs 3 4 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 2 3 => rw [\u2190 id_tensor_comp, \u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [associator_Bimod.inv]\n  slice_rhs 3 4 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.inv_aux]\n  slice_rhs 2 2 => rw [id_tensor_comp]\n  slice_rhs 3 5 => rw [id_tensor_\u03c0_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 \u27f6 N)\n    (g : P \u27f6 Q) : tensorHom (\ud835\udfd9 M) g \u226b tensorHom f (\ud835\udfd9 Q) = tensorHom f (\ud835\udfd9 P) \u226b tensorHom (\ud835\udfd9 N) g :=\n  by\n  dsimp [tensor_hom]\n  ext; dsimp\n  slice_lhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_lhs 2 3 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_lhs 1 2 => rw [id_tensor_comp_tensor_id]\n  slice_rhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_rhs 2 3 => rw [\u03b9_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 (\ud835\udfd9 Q) \u226b\n        (associatorBimod M (N.tensorBimod P) Q).Hom \u226b tensorHom (\ud835\udfd9 M) (associatorBimod N P Q).Hom =\n      (associatorBimod (M.tensorBimod N) P Q).Hom \u226b (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 [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_lhs 2 3 => rw [coequalizer.\u03c0_desc]\n  slice_rhs 1 2 => rw [coequalizer.\u03c0_desc]\n  dsimp [associator_Bimod.hom_aux]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp\n  slice_lhs 1 2 => rw [\u2190 comp_tensor_id, coequalizer.\u03c0_desc]\n  slice_rhs 1 3 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_rhs 3 4 => rw [coequalizer.\u03c0_desc]\n  refine' (cancel_epi ((tensor_right _ \u22d9 tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp\n  slice_lhs 1 2 =>\n    rw [\u2190 comp_tensor_id, \u03c0_tensor_id_preserves_coequalizer_inv_desc, comp_tensor_id,\n      comp_tensor_id]\n  slice_lhs 3 5 => rw [\u03c0_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 [\u03b9_colim_map, parallel_pair_hom_app_one]\n  slice_lhs 4 5 => rw [\u2190 id_tensor_comp, coequalizer.\u03c0_desc]\n  slice_lhs 3 4 =>\n    rw [\u2190 id_tensor_comp, \u03c0_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, \u2190 id_tensor_comp_tensor_id]\n  slice_rhs 3 5 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_rhs 2 3 => rw [\u2190 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 \u226b tensorHom (\ud835\udfd9 M) (leftUnitorBimod N).Hom =\n      tensorHom (rightUnitorBimod M).Hom (\ud835\udfd9 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.\u03c0_desc]\n  dsimp [associator_Bimod.hom_aux]\n  slice_rhs 1 2 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [right_unitor_Bimod.hom]\n  refine' (cancel_epi ((tensor_right _).map (coequalizer.\u03c0 _ _))).1 _\n  dsimp [regular]\n  slice_lhs 1 3 => rw [\u03c0_tensor_id_preserves_coequalizer_inv_desc]\n  slice_lhs 3 4 => rw [\u03b9_colim_map, parallel_pair_hom_app_one]\n  dsimp [left_unitor_Bimod.hom]\n  slice_lhs 2 3 => rw [\u2190 id_tensor_comp, coequalizer.\u03c0_desc]\n  slice_rhs 1 2 => rw [\u2190 comp_tensor_id, coequalizer.\u03c0_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 (\ud835\udfd9 L) f\n  whiskerRight _ _ _ _ _ f N := tensorHom f (\ud835\udfd9 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 `\u03c6` based on `P`, `AsEmpValid1` is used, since `\u03c6` is declared as an\n`outParam`. Consequently, if type class instance search is supposed to generate `P`, `AsEmpValid2`\nis used. -/\n\nclass AsEmpValid1 (\u03c6 : outParam Prop) {PROP : Type} (P : PROP) where\n  [bi : BI PROP]\n  as_emp_valid : \u03c6 \u2194 \u22a2 P\n\nclass AsEmpValid2 (\u03c6 : Prop) {PROP : outParam Type} (P : outParam PROP) where\n  [bi : BI PROP]\n  as_emp_valid : \u03c6 \u2194 \u22a2 P\n\nattribute [instance (default - 100)] AsEmpValid1.bi\nattribute [instance (default - 100)] AsEmpValid2.bi\n\nclass AsEmpValid (\u03c6 : Prop) {PROP : Type} (P : PROP) extends\n  AsEmpValid1 \u03c6 P,\n  AsEmpValid2 \u03c6 P\n\ntheorem as_emp_valid_1 (P : PROP) [AsEmpValid1 \u03c6 P] : \u03c6 \u2192 \u22a2 P :=\n  AsEmpValid1.as_emp_valid.mp\ntheorem as_emp_valid_2 (\u03c6 : Prop) [AsEmpValid2 \u03c6 P] : (\u22a2 P) \u2192 \u03c6 :=\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 \u2192 Q2) \u22a2 P\nexport FromImpl (from_impl)\n\nclass FromWand [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n  from_wand : (Q1 -\u2217 Q2) \u22a2 P\nexport FromWand (from_wand)\n\nclass IntoWand [BI PROP] (p q : Bool) (R P : PROP) (Q : outParam PROP) where\n  into_wand : \u25a1?p R \u22a2 \u25a1?q P -\u2217 Q\nexport IntoWand (into_wand)\n\nclass FromForall [BI PROP] (P : PROP) {\u03b1 : outParam Type} (\u03a8 : outParam <| \u03b1 \u2192 PROP) where\n  from_forall : (\u2200 x, \u03a8 x) \u22a2 P\nexport FromForall (from_forall)\n\nclass IntoForall [BI PROP] (P : PROP) {\u03b1 : outParam Type} (\u03a6 : outParam <| \u03b1 \u2192 PROP) where\n  into_forall : P \u22a2 \u2200 x, \u03a6 x\nexport IntoForall (into_forall)\n\nclass FromExist [BI PROP] (P : PROP) {\u03b1 : outParam Type} (\u03a6 : outParam <| \u03b1 \u2192 PROP) where\n  from_exist : (\u2203 x, \u03a6 x) \u22a2 P\nexport FromExist (from_exist)\n\nclass IntoExist [BI PROP] (P : PROP) {\u03b1 : outParam Type} (\u03a6 : outParam <| \u03b1 \u2192 PROP) where\n  into_exist : P \u22a2 \u2203 x, \u03a6 x\nexport IntoExist (into_exist)\n\nclass FromAnd [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n  from_and : Q1 \u2227 Q2 \u22a2 P\nexport FromAnd (from_and)\n\nclass IntoAnd (p : Bool) [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n  into_and : \u25a1?p P \u22a2 \u25a1?p (Q1 \u2227 Q2)\nexport IntoAnd (into_and)\n\nclass FromSep [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n  from_sep : Q1 \u2217 Q2 \u22a2 P\nexport FromSep (from_sep)\n\nclass IntoSep [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) :=\n  into_sep : P \u22a2 Q1 \u2217 Q2\nexport IntoSep (into_sep)\n\nclass FromOr [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n  from_or : Q1 \u2228 Q2 \u22a2 P\nexport FromOr (from_or)\n\nclass IntoOr [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n  into_or : P \u22a2 Q1 \u2228 Q2\nexport IntoOr (into_or)\n\n\nclass IntoPersistent (p : Bool) [BI PROP] (P : PROP) (Q : outParam PROP) where\n  into_persistent : <pers>?p P \u22a2 <pers> Q\nexport IntoPersistent (into_persistent)\n\nclass FromAffinely [BI PROP] (P : outParam PROP) (Q : PROP) (p : Bool := true) where\n  from_affinely : <affine>?p Q \u22a2 P\nexport FromAffinely (from_affinely)\n\nclass IntoAbsorbingly [BI PROP] (P : outParam PROP) (Q : PROP) where\n  into_absorbingly : P \u22a2 <absorb> Q\nexport IntoAbsorbingly (into_absorbingly)\n\n\nclass FromAssumption (p : Bool) [BI PROP] (P Q : PROP) where\n  from_assumption : \u25a1?p P \u22a2 Q\nexport FromAssumption (from_assumption)\n\nclass IntoPure [BI PROP] (P : PROP) (\u03c6 : outParam Prop) where\n  into_pure : P \u22a2 \u231c\u03c6\u231d\nexport IntoPure (into_pure)\n\nclass FromPure [BI PROP] (a : outParam Bool) (P : PROP) (\u03c6 : outParam Prop) where\n  from_pure : <affine>?a \u231c\u03c6\u231d \u22a2 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": "theorem unsound : False := -- Error\n  unsound\n\npartial theorem unsound : False := -- Error\n  unsound\n\nunsafe theorem unsound : False := -- Error\n  unsound\n\nconstant unsound : False  -- Error\n\naxiom magic : False -- OK\n\npartial def foo (x : Nat) : Nat := foo x  -- OK\n\nunsafe def unsound2 : False := unsound  -- OK\n\npartial def unsound3 : False := unsound3  -- Error\n\npartial def unsound4 (x : Unit) : False := unsound4 ()  -- Error\n\npartial def badcast1 (x : Nat) : Bool :=\n  unsafeCast x -- Error: partial cannot use unsafe constant\n\npartial def badcast2 (x : Nat) : Bool :=\n  if x == 0 then unsafeCast x -- Error: partial cannot use unsafe constant\n  else badcast2 (x + 1)\n\nunsafe def badcast3 (x : Nat) : Bool := -- OK\n  if x == 0 then unsafeCast x\n  else badcast3 (x + 1)\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/sanitychecks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535945, "lm_q2_score": 0.040237945500944707, "lm_q1q2_score": 0.009745856888673061}}
{"text": "import Runtime.Execution.ReactionOutput\n\nnamespace Execution.Executable\nopen Network\n\n/--\nApplies the changes described by a given reaction-output to the given executable. This includes:\n* merging events into the event queue.\n* updating the executable's state if a stop request was performed.\n* updating the state variables of the reaction's parent reactor.\n* setting the values of the reaction's effect ports.\n-/\ndef apply (exec : Executable net) (output : ReactionOutput exec) : Executable net := { exec with\n  queue := exec.queue.merge output.actionEvents\n  state := stateAfter output\n  reactors := fun id => { exec.reactors id with\n    interface :=\n      if      h : id = output.reactor then h \u25b8 container output -- Updates the output ports of the reaction's container.\n      else if h : id \u227b output.reactor then child output \u27e8id, h\u27e9 -- Updates the input ports of child reactors.\n      else                                 exec.interface id    -- Unaffected reactors.\n  }\n  toPropagate := exec.toPropagate ++ output.writtenPortsWithDelayedConnections\n}\nwhere\n  container (output : ReactionOutput exec) : (kind : Reactor.InterfaceKind) \u2192 kind.interfaceType (output.reactor.class.interface kind)\n    | .outputs => fun var => (output.local var).orElse (fun _ => exec.interface output.reactor .outputs var)\n    | .state   => output.reaction.eqState \u25b8 output.raw.state\n    | _        => exec.interface output.reactor _\n\n  child (output : ReactionOutput exec) (child : ReactorId.Child output.reactor) : (kind : Reactor.InterfaceKind) \u2192 kind.interfaceType ((child : ReactorId net).class.interface kind)\n    | .inputs => fun var => (output.child var).orElse (fun _ => exec.interface child .inputs var)\n    | _       => exec.interface child _\n\n  stateAfter (output : ReactionOutput exec) : Executable.State :=\n    if output.stopRequested then\n      -- When requesting to stop, we need to make sure we don't override\n      -- if we're already in the process of shutting down.\n      match exec.state with\n      | .shuttingDown                 => .shuttingDown\n      | .executing | .shutdownPending => .shutdownPending\n    else\n      exec.state\n\ntheorem apply_scheduled_action_mem_queue {output : ReactionOutput exec} :\n  (.action t i v \u2208 output.actionEvents) \u2192 (.action t i v \u2208 (exec.apply output).queue) :=\n  Queue.merge_mem\u2082\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/Apply.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.02517884115198132, "lm_q1q2_score": 0.009691641743429446}}
{"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 \u2964 D) [functor.additive F]\n  (F' : C \u2964 D) [functor.additive F'] (\u03c4 : F \u27f6 F') (n : \u2115)\n\n@[simps]\ndef apply_Pow : Pow n \u22d9 F \u2245 F \u22d9 Pow n := nat_iso.of_components (\u03bb A,\n  { hom := biproduct.lift (\u03bb i, F.map (biproduct.\u03c0 _ i)),\n    inv := biproduct.desc (\u03bb i, F.map (biproduct.\u03b9 _ i)),\n    hom_inv_id' := by simpa only [biproduct.lift_desc, \u2190 F.map_comp, \u2190 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.\u03b9_desc_assoc, category.assoc, biproduct.lift_\u03c0,\n          category.comp_id, biproduct.\u03b9_\u03c0_self, \u2190 F.map_comp, F.map_id], },\n      { dsimp,\n        simp only [biproduct.\u03b9_desc_assoc, category.assoc, biproduct.lift_\u03c0,\n          category.comp_id, \u2190 F.map_comp, limits.biproduct.\u03b9_\u03c0_ne _ h,\n          functor.map_zero], },\n    end, })\n(\u03bb X Y f, by { ext, simp only [category.assoc, biproduct.lift_\u03c0,\n  functor.comp_map, Pow_map, biproduct.lift_map, \u2190 F.map_comp, biproduct.map_\u03c0], })\n\nlemma apply_Pow_naturality (M : C) :\n  \u03c4.app ((Pow n).obj M) \u226b (apply_Pow F' n).hom.app M =\n  (apply_Pow F n).hom.app M \u226b (Pow n).map (\u03c4.app M) :=\nbegin\n  rw [\u2190 cancel_epi ((apply_Pow F n).inv.app M)],\n  slice_rhs 1 2 { rw [\u2190 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_\u03c0, biproduct.\u03b9_desc_assoc, Pow_map, biproduct.map_\u03c0],\n  erw [\u03c4.naturality_assoc, \u2190 F'.map_comp],\n  by_cases i = j,\n  { subst h,\n    erw [biproduct.\u03b9_\u03c0_self_assoc, biproduct.\u03b9_\u03c0_self, F'.map_id, category.comp_id], },\n  { erw [biproduct.\u03b9_\u03c0_ne_assoc _ h, biproduct.\u03b9_\u03c0_ne _ h, F'.map_zero, comp_zero, zero_comp], },\nend\n\nopen breen_deligne breen_deligne.universal_map\n\nvariables {A\u2081 A\u2082 : Type*} [category.{v} A\u2081] [category.{v} A\u2082] [preadditive A\u2081] [preadditive A\u2082]\n  [has_finite_biproducts A\u2081] [has_finite_biproducts A\u2082]\n  (F\u2081 : A\u2081 \u2964 A\u2081) (F\u2082 : A\u2082 \u2964 A\u2082) (G : A\u2081 \u2964 A\u2082)\n  [functor.additive G]\n\ndef eval_Pow_functor_comp (e : F\u2081 \u22d9 G \u2245 G \u22d9 F\u2082) :\n  eval_Pow_functor F\u2082 \u22d9 ((whiskering_left _ _ A\u2082).obj G) \u2245\n  eval_Pow_functor F\u2081 \u22d9 (whiskering_right A\u2081 _ _).obj G :=\nnat_iso.of_components\n(\u03bb n, begin\n  apply iso.symm,\n  refine (functor.associator _ _ _) \u226a\u226b iso_whisker_left _ e \u226a\u226b _,\n  refine (functor.associator _ _ _).symm \u226a\u226b _ \u226a\u226b (functor.associator _ _ _),\n  refine iso_whisker_right (apply_Pow G n) _,\nend)\n(\u03bb 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\u2081 G M, category.assoc, \u2190 congr_eval_Pow' f e.inv],\n  simp only [\u2190 category.assoc],\n  congr' 1,\n  revert f,\n  let \u03c6\u2081 : universal_map n m \u2192+ ((G \u22d9 Pow n \u22d9 F\u2082).obj M \u27f6 F\u2082.obj ((Pow m \u22d9 G).obj M)) :=\n  { to_fun := \u03bb f, ((eval_Pow F\u2082) f).app (G.obj M) \u226b F\u2082.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' := \u03bb f\u2081 f\u2082, by simp only [map_add, nat_trans.app_add, add_comp], },\n  let \u03c6\u2082 : universal_map n m \u2192+ ((G \u22d9 Pow n \u22d9 F\u2082).obj M \u27f6 F\u2082.obj ((Pow m \u22d9 G).obj M)) :=\n  { to_fun := \u03bb f, F\u2082.map ((apply_Pow G n).inv.app M) \u226b ((eval_Pow' (G \u22d9 F\u2082)) f).app M,\n    map_zero' := by simp only [map_zero, nat_trans.app_zero, comp_zero],\n    map_add' := \u03bb f\u2081 f\u2082, by simp only [map_add, nat_trans.app_add, comp_add], },\n  suffices : \u03c6\u2081 = \u03c6\u2082,\n  { intro f,\n    change \u03c6\u2081 f = \u03c6\u2082 f,\n    rw this, },\n  ext f,\n  dsimp only [\u03c6\u2081, \u03c6\u2082], clear \u03c6\u2081 \u03c6\u2082,\n  simp only [add_monoid_hom.coe_mk, eval_Pow'_of, eval_Pow_of, whisker_right_app,\n    \u2190 F\u2082.map_comp, functor.comp_map],\n  congr' 1,\n  erw [\u2190 cancel_mono ((apply_Pow G m).hom.app M), category.assoc,\n    \u2190 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_\u03c0, biproduct.\u03b9_desc, category.assoc, biproduct.lift_\u03c0,\n    biproduct.\u03b9_desc_assoc, \u2190 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\u2081 A\u2082 : Type*} [category.{v} A\u2081] [category.{v} A\u2082]\n  (BD : data)\n  (F\u2081 : A\u2081 \u2964 A\u2081) (F\u2082 : A\u2082 \u2964 A\u2082) (G : A\u2081 \u2964 A\u2082)\n  (e : F\u2081 \u22d9 G \u2245 G \u22d9 F\u2082)\n\nvariables [preadditive A\u2082]\n\ninstance additive_whiskering_left :\n  functor.additive ((whiskering_left _ _ A\u2082).obj G) := { }\n\nvariables [preadditive A\u2081] [functor.additive G]\n\ninstance additive_whiskering_right :\n  functor.additive ((whiskering_right A\u2081 _ _).obj G) := { }\n\nvariables [has_finite_biproducts A\u2081] [has_finite_biproducts A\u2082]\n\ninclude e\ndef eval_functor'_comp :\n  (eval_functor' F\u2082 \u22d9 ((whiskering_left _ _ A\u2082).obj G).map_homological_complex _ \u2245\n  eval_functor' F\u2081 \u22d9 ((whiskering_right A\u2081 _ _).obj G).map_homological_complex _) :=\ncategory_theory.nat_iso.map_homological_complex (eval_Pow_functor_comp F\u2081 F\u2082 G e) _\n\ndef eval_functor_comp :\n  eval_functor F\u2082 \u22d9 (whiskering_left _ _ _).obj G \u2245\n  eval_functor F\u2081 \u22d9 (whiskering_right A\u2081 _ _).obj (G.map_homological_complex _) :=\niso_whisker_right (eval_functor'_comp F\u2081 F\u2082 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 ProofWidgets.Data.Html\n\nnamespace ProofWidgets\nopen Lean Server\n\n/-- An `Expr` presenter is similar to a delaborator but outputs HTML trees instead of syntax, and\nthe output HTML can contain elements which interact with the original `Expr` in some way. We call\ninteractive outputs with a reference to the original input *presentations*. -/\nstructure ExprPresenter where\n  /-- A user-friendly name for this presenter. For example, \"LaTeX\". -/\n  userName : String\n  /- TODO: there is a general problem of writing env extensions which store an extendable list of\n  functions to run on `Expr`s, but not all of which are applicable to any single `Expr` (actually,\n  most are not). Invoking them in sequence is O(n); we should better use sth like `DiscrTree`.\n  Registering new entries would need to extend the DiscrTree, perhaps like\n  `registerSelf : DiscrTree ExprPresenter \u2192 DiscrTree ExprPresenter`.\n  Dispatching on just one constant like e.g. delaborators (`app.MyType.myCtr`) does not appear\n  sufficient because one entry may apply to multiple expressions of a given form which could be\n  represented as a schematic with mvars, say `@ofNat ? 0 ?`.\n  TODO: actually, for most use cases name-based dispatch might be sufficient, and it's simple. -/\n  /-- Should quickly determine if the `Expr` is within this presenter's domain of applicability.\n  For example it could check for a constant like the `` `name `` in ``@[delab `name]``. -/\n  isApplicable : Expr \u2192 MetaM Bool\n  /-- Whether the output should use inline (think something which fits in the space normally\n  occupied by an `Expr`, e.g. LaTeX) or block (think large diagram which needs dedicated space)\n  HTML layout. -/\n  layoutKind : LayoutKind := .block\n  /-- *Must* return `some _` or throw when `isApplicable` is `true`. -/\n  present : Expr \u2192 MetaM (Option Html)\n\ninitialize exprPresenters : TagAttribute \u2190\n  registerTagAttribute `expr_presenter\n    \"Register an Expr presenter. It must have the type `ProofWidgets.ExprPresenter`.\"\n    (validate := fun nm => do\n      let const \u2190 getConstInfo nm\n      if !const.type.isConstOf ``ExprPresenter then\n        throwError m!\"type mismatch, expected {mkConst ``ExprPresenter} but got {const.type}\"\n      return ())\n\nprivate unsafe def evalExprPresenterUnsafe (env : Environment) (opts : Options)\n    (constName : Name) : Except String ExprPresenter :=\n  env.evalConstCheck ExprPresenter opts ``ExprPresenter constName\n\n@[implemented_by evalExprPresenterUnsafe]\nopaque evalExprPresenter (env : Environment) (opts : Options) (constName : Name) :\n  Except String ExprPresenter\n\nstructure ApplicableExprPresentersParams where\n  expr : WithRpcRef ExprWithCtx\n\n#mkrpcenc ApplicableExprPresentersParams\n\nstructure ExprPresenterId where\n  name : Name\n  userName : String\n  deriving FromJson, ToJson\n\nstructure ApplicableExprPresenters where\n  presenters : Array ExprPresenterId\n  deriving FromJson, ToJson\n\n@[server_rpc_method]\ndef applicableExprPresenters : ApplicableExprPresentersParams \u2192\n    RequestM (RequestTask ApplicableExprPresenters)\n  | \u27e8\u27e8expr\u27e9\u27e9 => RequestM.asTask do\n    let mut presenters : Array ExprPresenterId := #[]\n    let ci := expr.ci\n    for nm in exprPresenters.ext.getState expr.ci.env do\n      match evalExprPresenter ci.env ci.options nm with\n      | .ok p =>\n        if \u2190 expr.runMetaM p.isApplicable then\n          presenters := presenters.push \u27e8nm, p.userName\u27e9\n      | .error e =>\n        throw <| RequestError.internalError s!\"Failed to evaluate Expr presenter '{nm}': {e}\"\n    return { presenters }\n\nstructure GetExprPresentationParams where\n  expr : WithRpcRef ExprWithCtx\n  /-- Name of the presenter to use. -/\n  name : Name\n\n#mkrpcenc GetExprPresentationParams\n\n@[server_rpc_method]\ndef getExprPresentation : GetExprPresentationParams \u2192\n    RequestM (RequestTask Html)\n  | { expr := \u27e8expr\u27e9, name } => RequestM.asTask do\n    let ci := expr.ci\n    if !exprPresenters.hasTag ci.env name then\n      throw <| RequestError.invalidParams s!\"The constant '{name}' is not an Expr presenter.\"\n    match evalExprPresenter ci.env ci.options name with\n    | .ok p =>\n      let some ret \u2190 expr.runMetaM p.present\n        | throw <| RequestError.internalError <|\n          s!\"Got none from {name}.present e, expected some _ because {name}.isApplicable e \" ++\n          s!\"returned true, where e := {expr.expr}\"\n      return ret\n    | .error e =>\n      throw <| RequestError.internalError s!\"Failed to evaluate Expr presenter '{name}': {e}\"\n\nstructure ExprPresentationProps where\n  expr : WithRpcRef ExprWithCtx\n\n#mkrpcenc ExprPresentationProps\n\n/-- This component shows a selection of all known and applicable `ProofWidgets.ExprPresenter`s which\nare used to render the expression when selected. By default `ProofWidgets.InteractiveExpr` is shown. -/\n@[widget_module]\ndef ExprPresentation : Component ExprPresentationProps where\n  javascript := include_str \"..\" / \"..\" / \"build\" / \"js\" / \"exprPresentation.js\"\n\nend ProofWidgets\n", "meta": {"author": "EdAyers", "repo": "ProofWidgets4", "sha": "c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e", "save_path": "github-repos/lean/EdAyers-ProofWidgets4", "path": "github-repos/lean/EdAyers-ProofWidgets4/ProofWidgets4-c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e/ProofWidgets/Presentation/Expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2365162472088944, "lm_q2_score": 0.04084572028835885, "lm_q1q2_score": 0.009660676477146836}}
{"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.FindExpr\nimport Lean.Parser.Term\nimport Lean.Elab.App\nimport Lean.Elab.Binders\n\nnamespace Lean.Elab.Term.StructInst\n\nopen Std (HashMap)\nopen Meta\n\n/-\n  Structure instances are of the form:\n\n      \"{\" >> optional (atomic (termParser >> \" with \"))\n          >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))\n          >> optEllipsis\n          >> optional (\" : \" >> termParser)\n          >> \" }\"\n-/\n\n@[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx =>\n  let expectedArg := stx[4]\n  if expectedArg.isNone then\n    Macro.throwUnsupported\n  else\n    let expected := expectedArg[1]\n    let stxNew   := stx.setArg 4 mkNullNode\n    `(($stxNew : $expected))\n\n/-\nIf `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`.\n\nNote that this one is not a `Macro` because we need to access the local context.\n-/\nprivate def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) :=\n  withFreshMacroScope do\n    let sourceOpt := stx[1]\n    if sourceOpt.isNone then\n      pure none\n    else\n      let source := sourceOpt[0]\n      match (\u2190 isLocalIdent? source) with\n      | some _ => pure none\n      | none   =>\n        if source.isMissing then\n          throwAbortTerm\n        else\n          let src \u2190 `(src)\n          let sourceOpt := sourceOpt.setArg 0 src\n          let stxNew    := stx.setArg 1 sourceOpt\n          `(let src := $source; $stxNew)\n\ninductive Source where\n  | none     -- structure instance source has not been provieded\n  | implicit (stx : Syntax) -- `..`\n  | explicit (stx : Syntax) (src : Expr) -- `src with`\n  deriving Inhabited\n\ndef Source.isNone : Source \u2192 Bool\n  | Source.none => true\n  | _           => false\n\ndef setStructSourceSyntax (structStx : Syntax) : Source \u2192 Syntax\n  | Source.none           => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode\n  | Source.implicit stx   => (structStx.setArg 1 mkNullNode).setArg 3 stx\n  | Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode\n\nprivate def getStructSource (stx : Syntax) : TermElabM Source :=\n  withRef stx do\n    let explicitSource := stx[1]\n    let implicitSource := stx[3]\n    if explicitSource.isNone && implicitSource[0].isNone then\n      return Source.none\n    else if explicitSource.isNone then\n      return Source.implicit implicitSource\n    else if implicitSource[0].isNone then\n      let fvar? \u2190 isLocalIdent? explicitSource[0]\n      match fvar? with\n      | none      => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here\n      | some src  => return Source.explicit explicitSource src\n    else\n      throwError \"invalid structure instance `with` and `..` cannot be used together\"\n\n/-\n  We say a `{ ... }` notation is a `modifyOp` if it contains only one\n  ```\n  def structInstArrayRef := leading_parser \"[\" >> termParser >>\"]\"\n  ```\n-/\nprivate def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do\n  let s? \u2190 stx[2].getArgs.foldlM (init := none) fun s? p =>\n    /- p is of the form `(group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))` -/\n    let arg := p[0]\n    if arg.getKind == ``Lean.Parser.Term.structInstField then\n      /- Remark: the syntax for `structInstField` is\n         ```\n         def structInstLVal   := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (group (\".\" >> (ident <|> numLit)) <|> structInstArrayRef)\n         def structInstField  := leading_parser structInstLVal >> \" := \" >> termParser\n         ```\n      -/\n      let lval := arg[0]\n      let k    := lval[0].getKind\n      if k == ``Lean.Parser.Term.structInstArrayRef then\n        match s? with\n        | none   => pure (some arg)\n        | some s =>\n          if s.getKind == ``Lean.Parser.Term.structInstArrayRef then\n            throwErrorAt arg \"invalid \\{...} notation, at most one `[..]` at a given level\"\n          else\n            throwErrorAt arg \"invalid \\{...} notation, can't mix field and `[..]` at a given level\"\n      else\n        match s? with\n        | none   => pure (some arg)\n        | some s =>\n          if s.getKind == ``Lean.Parser.Term.structInstArrayRef then\n            throwErrorAt arg \"invalid \\{...} notation, can't mix field and `[..]` at a given level\"\n          else\n            pure s?\n    else\n      pure s?\n  match s? with\n  | none   => pure none\n  | some s => if s[0][0].getKind == ``Lean.Parser.Term.structInstArrayRef then pure s? else pure none\n\nprivate def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let cont (val : Syntax) : TermElabM Expr := do\n    let lval := modifyOp[0][0]\n    let idx  := lval[1]\n    let self := source[0]\n    let stxNew \u2190 `($(self).modifyOp (idx := $idx) (fun s => $val))\n    trace[Elab.struct.modifyOp] \"{stx}\\n===>\\n{stxNew}\"\n    withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  trace[Elab.struct.modifyOp] \"{modifyOp}\\nSource: {source}\"\n  let rest := modifyOp[0][1]\n  if rest.isNone then\n    cont modifyOp[2]\n  else\n    let s \u2190 `(s)\n    let valFirst  := rest[0]\n    let valFirst  := if valFirst.getKind == ``Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1]\n    let restArgs  := rest.getArgs\n    let valRest   := mkNullNode restArgs[1:restArgs.size]\n    let valField  := modifyOp.setArg 0 <| Syntax.node ``Parser.Term.structInstLVal #[valFirst, valRest]\n    let valSource := source.modifyArg 0 fun _ => s\n    let val       := stx.setArg 1 valSource\n    let val       := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]]\n    trace[Elab.struct.modifyOp] \"{stx}\\nval: {val}\"\n    cont val\n\n/- Get structure name and elaborate explicit source (if available) -/\nprivate def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM (Name \u00d7 Expr) := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let useSource : Unit \u2192 TermElabM (Name \u00d7 Expr) := fun _ =>\n    match sourceView, expectedType? with\n    | Source.explicit _ src, _ => do\n      let srcType \u2190 inferType src\n      let srcType \u2190 whnf srcType\n      tryPostponeIfMVar srcType\n      match srcType.getAppFn with\n      | Expr.const constName _ _ => return (constName, srcType)\n      | _ => throwUnexpectedExpectedType srcType \"source\"\n    | _, some expectedType => throwUnexpectedExpectedType expectedType\n    | _, none              => throwUnknownExpectedType\n  match expectedType? with\n  | none => useSource ()\n  | some expectedType =>\n    let expectedType \u2190 whnf expectedType\n    match expectedType.getAppFn with\n    | Expr.const constName _ _ => return (constName, expectedType)\n    | _                        => useSource ()\nwhere\n  throwUnknownExpectedType :=\n    throwError \"invalid \\{...} notation, expected type is not known\"\n  throwUnexpectedExpectedType type (kind := \"expected\") := do\n    let type \u2190 instantiateMVars type\n    if type.getAppFn.isMVar then\n      throwUnknownExpectedType\n    else\n      throwError \"invalid \\{...} notation, {kind} type is not of the form (C ...){indentExpr type}\"\n\ninductive FieldLHS where\n  | fieldName  (ref : Syntax) (name : Name)\n  | fieldIndex (ref : Syntax) (idx : Nat)\n  | modifyOp   (ref : Syntax) (index : Syntax)\n  deriving Inhabited\n\ninstance : ToFormat FieldLHS := \u27e8fun lhs =>\n  match lhs with\n  | FieldLHS.fieldName _ n  => fmt n\n  | FieldLHS.fieldIndex _ i => fmt i\n  | FieldLHS.modifyOp _ i   => \"[\" ++ i.prettyPrint ++ \"]\"\u27e9\n\ninductive FieldVal (\u03c3 : Type) where\n  | term  (stx : Syntax) : FieldVal \u03c3\n  | nested (s : \u03c3)       : FieldVal \u03c3\n  | default              : FieldVal \u03c3 -- mark that field must be synthesized using default value\n  deriving Inhabited\n\nstructure Field (\u03c3 : Type) where\n  ref : Syntax\n  lhs : List FieldLHS\n  val : FieldVal \u03c3\n  expr? : Option Expr := none\n  deriving Inhabited\n\ndef Field.isSimple {\u03c3} : Field \u03c3 \u2192 Bool\n  | { lhs := [_], .. } => true\n  | _                  => false\n\ninductive Struct where\n  | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source)\n  deriving Inhabited\n\nabbrev Fields := List (Field Struct)\n\n/- true if all fields of the given structure are marked as `default` -/\npartial def Struct.allDefault : Struct \u2192 Bool\n  | \u27e8_, _, fields, _\u27e9 => fields.all fun \u27e8_, _, val, _\u27e9 => match val with\n    | FieldVal.term _   => false\n    | FieldVal.default  => true\n    | FieldVal.nested s => allDefault s\n\ndef Struct.ref : Struct \u2192 Syntax\n  | \u27e8ref, _, _, _\u27e9 => ref\n\ndef Struct.structName : Struct \u2192 Name\n  | \u27e8_, structName, _, _\u27e9 => structName\n\ndef Struct.fields : Struct \u2192 Fields\n  | \u27e8_, _, fields, _\u27e9 => fields\n\ndef Struct.source : Struct \u2192 Source\n  | \u27e8_, _, _, s\u27e9 => s\n\ndef formatField (formatStruct : Struct \u2192 Format) (field : Field Struct) : Format :=\n  Format.joinSep field.lhs \" . \" ++ \" := \" ++\n    match field.val with\n    | FieldVal.term v   => v.prettyPrint\n    | FieldVal.nested s => formatStruct s\n    | FieldVal.default  => \"<default>\"\n\npartial def formatStruct : Struct \u2192 Format\n  | \u27e8_, structName, fields, source\u27e9 =>\n    let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) \", \"\n    match source with\n    | Source.none           => \"{\" ++ fieldsFmt ++ \"}\"\n    | Source.implicit _     => \"{\" ++ fieldsFmt ++ \" .. }\"\n    | Source.explicit _ src => \"{\" ++ format src ++ \" with \" ++ fieldsFmt ++ \"}\"\n\ninstance : ToFormat Struct     := \u27e8formatStruct\u27e9\ninstance : ToString Struct := \u27e8toString \u2218 format\u27e9\n\ninstance : ToFormat (Field Struct) := \u27e8formatField formatStruct\u27e9\ninstance : ToString (Field Struct) := \u27e8toString \u2218 format\u27e9\n\n/-\nRecall that `structInstField` elements have the form\n```\n   def structInstField  := leading_parser structInstLVal >> \" := \" >> termParser\n   def structInstLVal   := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many ((\".\" >> (ident <|> numLit)) <|> structInstArrayRef)\n   def structInstArrayRef := leading_parser \"[\" >> termParser >>\"]\"\n```\n-/\n-- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName`\ndef FieldLHS.toSyntax (first : Bool) : FieldLHS \u2192 Syntax\n  | FieldLHS.modifyOp   stx _    => stx\n  | FieldLHS.fieldName  stx name => if first then mkIdentFrom stx name else mkGroupNode #[mkAtomFrom stx \".\", mkIdentFrom stx name]\n  | FieldLHS.fieldIndex stx _    => if first then stx else mkGroupNode #[mkAtomFrom stx \".\", stx]\n\ndef FieldVal.toSyntax : FieldVal Struct \u2192 Syntax\n  | FieldVal.term stx => stx\n  | _                 => unreachable!\n\ndef Field.toSyntax : Field Struct \u2192 Syntax\n  | field =>\n    let stx := field.ref\n    let stx := stx.setArg 2 field.val.toSyntax\n    match field.lhs with\n    | first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ]\n    | _ => unreachable!\n\nprivate def toFieldLHS (stx : Syntax) : MacroM FieldLHS :=\n  if stx.getKind == ``Lean.Parser.Term.structInstArrayRef then\n    return FieldLHS.modifyOp stx stx[1]\n  else\n    -- Note that the representation of the first field is different.\n    let stx := if stx.getKind == groupKind then stx[1] else stx\n    if stx.isIdent then\n      return FieldLHS.fieldName stx stx.getId.eraseMacroScopes\n    else match stx.isFieldIdx? with\n      | some idx => return FieldLHS.fieldIndex stx idx\n      | none     => Macro.throwError \"unexpected structure syntax\"\n\nprivate def mkStructView (stx : Syntax) (structName : Name) (source : Source) : MacroM Struct := do\n  /- Recall that `stx` is of the form\n     ```\n     leading_parser \"{\" >> optional (atomic (termParser >> \" with \"))\n                 >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))\n                 >> optional \"..\"\n                 >> optional (\" : \" >> termParser)\n                 >> \" }\"\n     ```\n  -/\n  let fieldsStx \u2190 stx[2].getArgs.mapM fun stx =>\n    let stx := stx[0]\n    if stx.getKind == ``Lean.Parser.Term.structInstField then\n      return stx\n    else\n      let id := stx[0]\n      `(Lean.Parser.Term.structInstField| $id:ident := $id:ident)\n  let fields \u2190 fieldsStx.toList.mapM fun fieldStx => do\n    let val   := fieldStx[2]\n    let first \u2190 toFieldLHS fieldStx[0][0]\n    let rest  \u2190 fieldStx[0][1].getArgs.toList.mapM toFieldLHS\n    pure { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct }\n  pure \u27e8stx, structName, fields, source\u27e9\n\ndef Struct.modifyFieldsM {m : Type \u2192 Type} [Monad m] (s : Struct) (f : Fields \u2192 m Fields) : m Struct :=\n  match s with\n  | \u27e8ref, structName, fields, source\u27e9 => return \u27e8ref, structName, (\u2190 f fields), source\u27e9\n\n@[inline] def Struct.modifyFields (s : Struct) (f : Fields \u2192 Fields) : Struct :=\n  Id.run <| s.modifyFieldsM f\n\ndef Struct.setFields (s : Struct) (fields : Fields) : Struct :=\n  s.modifyFields fun _ => fields\n\nprivate def expandCompositeFields (s : Struct) : Struct :=\n  s.modifyFields fun fields => fields.map fun field => match field with\n    | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field\n    | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } =>\n      let newEntries := n.components.map <| FieldLHS.fieldName ref\n      { field with lhs := newEntries ++ rest }\n    | _ => field\n\nprivate def expandNumLitFields (s : Struct) : TermElabM Struct :=\n  s.modifyFieldsM fun fields => do\n    let env \u2190 getEnv\n    let fieldNames := getStructureFields env s.structName\n    fields.mapM fun field => match field with\n      | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } =>\n        if idx == 0 then throwErrorAt ref \"invalid field index, index must be greater than 0\"\n        else if idx > fieldNames.size then throwErrorAt ref \"invalid field index, structure has only #{fieldNames.size} fields\"\n        else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest }\n      | _ => pure field\n\n/- For example, consider the following structures:\n   ```\n   structure A where\n     x : Nat\n\n   structure B extends A where\n     y : Nat\n\n   structure C extends B where\n     z : Bool\n   ```\n   This method expands parent structure fields using the path to the parent structure.\n   For example,\n   ```\n   { x := 0, y := 0, z := true : C }\n   ```\n   is expanded into\n   ```\n   { toB.toA.x := 0, toB.y := 0, z := true : C }\n   ```\n-/\nprivate def expandParentFields (s : Struct) : TermElabM Struct := do\n  let env \u2190 getEnv\n  s.modifyFieldsM fun fields => fields.mapM fun field => match field with\n    | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } =>\n      match findField? env s.structName fieldName with\n      | none => throwErrorAt ref \"'{fieldName}' is not a field of structure '{s.structName}'\"\n      | some baseStructName =>\n        if baseStructName == s.structName then pure field\n        else match getPathToBaseStructure? env baseStructName s.structName with\n          | some path => do\n            let path := path.map fun funName => match funName with\n              | Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s)\n              | _              => unreachable!\n            pure { field with lhs := path ++ field.lhs }\n          | _ => throwErrorAt ref \"failed to access field '{fieldName}' in parent structure\"\n    | _ => pure field\n\nprivate abbrev FieldMap := HashMap Name Fields\n\nprivate def mkFieldMap (fields : Fields) : TermElabM FieldMap :=\n  fields.foldlM (init := {}) fun fieldMap field =>\n    match field.lhs with\n    | FieldLHS.fieldName _ fieldName :: rest =>\n      match fieldMap.find? fieldName with\n      | some (prevField::restFields) =>\n        if field.isSimple || prevField.isSimple then\n          throwErrorAt field.ref \"field '{fieldName}' has already beed specified\"\n        else\n          return fieldMap.insert fieldName (field::prevField::restFields)\n      | _ => return fieldMap.insert fieldName [field]\n    | _ => unreachable!\n\nprivate def isSimpleField? : Fields \u2192 Option (Field Struct)\n  | [field] => if field.isSimple then some field else none\n  | _       => none\n\nprivate def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do\n  match fieldNames.findIdx? fun n => n == fieldName with\n  | some idx => pure idx\n  | none     => throwError \"field '{fieldName}' is not a valid field of '{structName}'\"\n\nprivate def mkProjStx (s : Syntax) (fieldName : Name) : Syntax :=\n  Syntax.node ``Lean.Parser.Term.proj #[s, mkAtomFrom s \".\", mkIdentFrom s fieldName]\n\nprivate def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source :=\n  match src with\n  | Source.explicit stx src => do\n    let idx \u2190 getFieldIdx structName fieldNames fieldName\n    let stx := stx.modifyArg 0 fun stx => mkProjStx stx fieldName\n    return Source.explicit stx (mkProj structName idx src)\n  | s => return s\n\n@[specialize] private def groupFields (expandStruct : Struct \u2192 TermElabM Struct) (s : Struct) : TermElabM Struct := do\n  let env \u2190 getEnv\n  let fieldNames := getStructureFields env s.structName\n  withRef s.ref do\n  s.modifyFieldsM fun fields => do\n    let fieldMap \u2190 mkFieldMap fields\n    fieldMap.toList.mapM fun \u27e8fieldName, fields\u27e9 => do\n      match isSimpleField? fields with\n      | some field => pure field\n      | none =>\n        let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! }\n        let substructSource \u2190 mkSubstructSource s.structName fieldNames fieldName s.source\n        let field := fields.head!\n        match Lean.isSubobjectField? env s.structName fieldName with\n        | some substructName =>\n          let substruct := Struct.mk s.ref substructName substructFields substructSource\n          let substruct \u2190 expandStruct substruct\n          pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct }\n        | none => do\n          -- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them.\n          let valStx := s.ref -- construct substructure syntax using s.ref as template\n          let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type\n          let args   := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode]\n          let valStx := valStx.setArg 2 (mkNullNode args)\n          let valStx := setStructSourceSyntax valStx substructSource\n          pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx }\n\ndef findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) :=\n  fields.find? fun field =>\n    match field.lhs with\n    | [FieldLHS.fieldName _ n] => n == fieldName\n    | _                        => false\n\n@[specialize] private def addMissingFields (expandStruct : Struct \u2192 TermElabM Struct) (s : Struct) : TermElabM Struct := do\n  let env \u2190 getEnv\n  let fieldNames := getStructureFields env s.structName\n  let ref := s.ref\n  withRef ref do\n    let fields \u2190 fieldNames.foldlM (init := []) fun fields fieldName => do\n      match findField? s.fields fieldName with\n      | some field => return field::fields\n      | none       =>\n        let addField (val : FieldVal Struct) : TermElabM Fields := do\n          return { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields\n        match Lean.isSubobjectField? env s.structName fieldName with\n        | some substructName => do\n          let substructSource \u2190 mkSubstructSource s.structName fieldNames fieldName s.source\n          let substruct := Struct.mk s.ref substructName [] substructSource\n          let substruct \u2190 expandStruct substruct\n          addField (FieldVal.nested substruct)\n        | none =>\n          match s.source with\n          | Source.none           => addField FieldVal.default\n          | Source.implicit _     => addField (FieldVal.term (mkHole s.ref))\n          | Source.explicit stx _ =>\n            -- stx is of the form `optional (try (termParser >> \"with\"))`\n            let src := stx[0]\n            let val := mkProjStx src fieldName\n            addField (FieldVal.term val)\n    return s.setFields fields.reverse\n\nprivate partial def expandStruct (s : Struct) : TermElabM Struct := do\n  let s := expandCompositeFields s\n  let s \u2190 expandNumLitFields s\n  let s \u2190 expandParentFields s\n  let s \u2190 groupFields expandStruct s\n  addMissingFields expandStruct s\n\nstructure CtorHeaderResult where\n  ctorFn     : Expr\n  ctorFnType : Expr\n  instMVars  : Array MVarId := #[]\n\nprivate def mkCtorHeaderAux : Nat \u2192 Expr \u2192 Expr \u2192 Array MVarId \u2192 TermElabM CtorHeaderResult\n  | 0,   type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars }\n  | n+1, type, ctorFn, instMVars => do\n    let type \u2190 whnfForall type\n    match type with\n    | Expr.forallE _ d b c =>\n      match c.binderInfo with\n      | BinderInfo.instImplicit =>\n        let a \u2190 mkFreshExprMVar d MetavarKind.synthetic\n        mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!)\n      | _ =>\n        let a \u2190 mkFreshExprMVar d\n        mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars\n    | _ => throwError \"unexpected constructor type\"\n\nprivate partial def getForallBody : Nat \u2192 Expr \u2192 Option Expr\n  | i+1, Expr.forallE _ _ b _ => getForallBody i b\n  | i+1, _                    => none\n  | 0,   type                 => type\n\nprivate def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit :=\n  match expectedType? with\n  | none              => pure ()\n  | some expectedType => do\n    match getForallBody numFields type with\n      | none           => pure ()\n      | some typeBody =>\n        unless typeBody.hasLooseBVars do\n          discard <| isDefEq expectedType typeBody\n\nprivate def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do\n  let us \u2190 mkFreshLevelMVars ctorVal.levelParams.length\n  let val  := Lean.mkConst ctorVal.name us\n  let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams us\n  let r \u2190 mkCtorHeaderAux ctorVal.numParams type val #[]\n  propagateExpectedType r.ctorFnType ctorVal.numFields expectedType?\n  synthesizeAppInstMVars r.instMVars\n  pure r\n\ndef markDefaultMissing (e : Expr) : Expr :=\n  mkAnnotation `structInstDefault e\n\ndef defaultMissing? (e : Expr) : Option Expr :=\n  annotation? `structInstDefault e\n\ndef throwFailedToElabField {\u03b1} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM \u03b1 :=\n  throwError \"failed to elaborate field '{fieldName}' of '{structName}, {msgData}\"\n\ndef trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do\n  if !s.allDefault then\n    pure none\n  else\n    try synthInstance? expectedType catch _ => pure none\n\nprivate partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr \u00d7 Struct) := withRef s.ref do\n  let env \u2190 getEnv\n  let ctorVal := getStructureCtor env s.structName\n  let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } \u2190 mkCtorHeader ctorVal expectedType?\n  let (e, _, fields) \u2190 s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field =>\n    match field.lhs with\n    | [FieldLHS.fieldName ref fieldName] => do\n      let type \u2190 whnfForall type\n      match type with\n      | Expr.forallE _ d b c =>\n        let cont (val : Expr) (field : Field Struct) : TermElabM (Expr \u00d7 Expr \u00d7 Fields) := do\n          pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo { lctx := (\u2190 getLCtx), val := val, name := fieldName, stx := ref }\n          let e     := mkApp e val\n          let type  := b.instantiate1 val\n          let field := { field with expr? := some val }\n          pure (e, type, field::fields)\n        match field.val with\n        | FieldVal.term stx => cont (\u2190 elabTermEnsuringType stx d) field\n        | FieldVal.nested s => do\n          -- if all fields of `s` are marked as `default`, then try to synthesize instance\n          match (\u2190 trySynthStructInstance? s d) with\n          | some val => cont val { field with val := FieldVal.term (mkHole field.ref) }\n          | none     => do let (val, sNew) \u2190 elabStruct s (some d); let val \u2190 ensureHasType d val; cont val { field with val := FieldVal.nested sNew }\n        | FieldVal.default  => do let val \u2190 withRef field.ref <| mkFreshExprMVar (some d); cont (markDefaultMissing val) field\n      | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!\"unexpected constructor type{indentExpr type}\"\n    | _ => throwErrorAt field.ref \"unexpected unexpanded structure field\"\n  pure (e, s.setFields fields.reverse)\n\nnamespace DefaultFields\n\nstructure Context where\n  -- We must search for default values overriden in derived structures\n  structs : Array Struct := #[]\n  allStructNames : Array Name := #[]\n  /--\n  Consider the following example:\n  ```\n  structure A where\n    x : Nat := 1\n\n  structure B extends A where\n    y : Nat := x + 1\n    x := y + 1\n\n  structure C extends B where\n    z : Nat := 2*y\n    x := z + 3\n  ```\n  And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`.\n  We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2.\n  The field `maxDistance` specifies the maximum distance considered in a round of Default field computation.\n  Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0.\n\n  The fixpoint for setting default values works in the following way.\n  - Keep computing default values using `maxDistance == 0`.\n  - We increase `maxDistance` whenever we failed to compute a new default value in a round.\n  - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value.\n    We use depth-first search.\n  - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above).\n  -/\n  maxDistance : Nat := 0\n\nstructure State where\n  progress : Bool := false\n\npartial def collectStructNames (struct : Struct) (names : Array Name) : Array Name :=\n  let names := names.push struct.structName\n  struct.fields.foldl (init := names) fun names field =>\n    match field.val with\n    | FieldVal.nested struct => collectStructNames struct names\n    | _ => names\n\npartial def getHierarchyDepth (struct : Struct) : Nat :=\n  struct.fields.foldl (init := 0) fun max field =>\n    match field.val with\n    | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1)\n    | _ => max\n\npartial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) :=\n  struct.fields.findSome? fun field =>\n   match field.val with\n   | FieldVal.nested struct => findDefaultMissing? mctx struct\n   | _ => match field.expr? with\n     | none      => unreachable!\n     | some expr => match defaultMissing? expr with\n       | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field\n       | _                         => none\n\ndef getFieldName (field : Field Struct) : Name :=\n  match field.lhs with\n  | [FieldLHS.fieldName _ fieldName] => fieldName\n  | _ => unreachable!\n\nabbrev M := ReaderT Context (StateRefT State TermElabM)\n\ndef isRoundDone : M Bool := do\n  return (\u2190 get).progress && (\u2190 read).maxDistance > 0\n\ndef getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr :=\n  struct.fields.findSome? fun field =>\n    if getFieldName field == fieldName then\n      field.expr?\n    else\n      none\n\npartial def mkDefaultValueAux? (struct : Struct) : Expr \u2192 TermElabM (Option Expr)\n  | Expr.lam n d b c => withRef struct.ref do\n    if c.binderInfo.isExplicit then\n      let fieldName := n\n      match getFieldValue? struct fieldName with\n      | none     => pure none\n      | some val =>\n        let valType \u2190 inferType val\n        if (\u2190 isDefEq valType d) then\n          mkDefaultValueAux? struct (b.instantiate1 val)\n        else\n          pure none\n    else\n      let arg \u2190 mkFreshExprMVar d\n      mkDefaultValueAux? struct (b.instantiate1 arg)\n  | e =>\n    if e.isAppOfArity ``id 2 then\n      pure (some e.appArg!)\n    else\n      pure (some e)\n\ndef mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) :=\n  withRef struct.ref do\n  let us \u2190 mkFreshLevelMVarsFor cinfo\n  mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us)\n\n/-- If `e` is a projection function of one of the given structures, then reduce it -/\ndef reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do\n  if !e.isApp then pure none\n  else match e.getAppFn with\n    | Expr.const name _ _ => do\n      let env \u2190 getEnv\n      match env.getProjectionStructureName? name with\n      | some structName =>\n        if structNames.contains structName then\n          Meta.unfoldDefinition? e\n        else\n          pure none\n      | none => pure none\n    | _ => pure none\n\n/-- Reduce default value. It performs beta reduction and projections of the given structures. -/\npartial def reduce (structNames : Array Name) : Expr \u2192 MetaM Expr\n  | e@(Expr.lam _ _ _ _)     => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (\u2190 reduce structNames b)\n  | e@(Expr.forallE _ _ _ _) => forallTelescope e fun xs b => do mkForallFVars xs (\u2190 reduce structNames b)\n  | e@(Expr.letE _ _ _ _ _)  => lambdaLetTelescope e fun xs b => do mkLetFVars xs (\u2190 reduce structNames b)\n  | e@(Expr.proj _ i b _)    => do\n    match (\u2190 Meta.project? b i) with\n    | some r => reduce structNames r\n    | none   => return e.updateProj! (\u2190 reduce structNames b)\n  | e@(Expr.app f _ _) => do\n    match (\u2190 reduceProjOf? structNames e) with\n    | some r => reduce structNames r\n    | none   =>\n      let f := f.getAppFn\n      let f' \u2190 reduce structNames f\n      if f'.isLambda then\n        let revArgs := e.getAppRevArgs\n        reduce structNames (f'.betaRev revArgs)\n      else\n        let args \u2190 e.getAppArgs.mapM (reduce structNames)\n        return (mkAppN f' args)\n  | e@(Expr.mdata _ b _) => do\n    let b \u2190 reduce structNames b\n    if (defaultMissing? e).isSome && !b.isMVar then\n      return b\n    else\n      return e.updateMData! b\n  | e@(Expr.mvar mvarId _) => do\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => if val.isMVar then reduce structNames val else pure val\n    | none     => return e\n  | e => return e\n\npartial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool :=\n  let rec loop (i : Nat) (dist : Nat) := do\n    if dist > maxDistance then\n      pure false\n    else if h : i < structs.size then do\n      let struct := structs.get \u27e8i, h\u27e9\n      let defaultName := struct.structName ++ fieldName ++ `_default\n      let env \u2190 getEnv\n      match env.find? defaultName with\n      | some cinfo@(ConstantInfo.defnInfo defVal) => do\n        let mctx \u2190 getMCtx\n        let val? \u2190 mkDefaultValue? struct cinfo\n        match val? with\n        | none     => do setMCtx mctx; loop (i+1) (dist+1)\n        | some val => do\n          let val \u2190 reduce allStructNames val\n          match val.find? fun e => (defaultMissing? e).isSome with\n          | some _ => setMCtx mctx; loop (i+1) (dist+1)\n          | none   =>\n            let mvarDecl \u2190 getMVarDecl mvarId\n            let val \u2190 ensureHasType mvarDecl.type val\n            assignExprMVar mvarId val\n            pure true\n      | _ => loop (i+1) dist\n    else\n      pure false\n  loop 0 0\n\npartial def step (struct : Struct) : M Unit :=\n  unless (\u2190 isRoundDone) do\n    withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do\n      for field in struct.fields do\n        match field.val with\n        | FieldVal.nested struct => step struct\n        | _ => match field.expr? with\n          | none      => unreachable!\n          | some expr => match defaultMissing? expr with\n            | some (Expr.mvar mvarId _) =>\n              unless (\u2190 isExprMVarAssigned mvarId) do\n                let ctx \u2190 read\n                if (\u2190 withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then\n                  modify fun s => { s with progress := true }\n            | _ => pure ()\n\npartial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do\n  match findDefaultMissing? (\u2190 getMCtx) struct with\n  | none       => pure () -- Done\n  | some field =>\n    if d > hierarchyDepth then\n      throwErrorAt field.ref \"field '{getFieldName field}' is missing\"\n    else withReader (fun ctx => { ctx with maxDistance := d }) do\n      modify fun s => { s with progress := false }\n      step struct\n      if (\u2190 get).progress then do\n        propagateLoop hierarchyDepth 0 struct\n      else\n        propagateLoop hierarchyDepth (d+1) struct\n\ndef propagate (struct : Struct) : TermElabM Unit :=\n  let hierarchyDepth := getHierarchyDepth struct\n  let structNames := collectStructNames struct #[]\n  (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {}\n\nend DefaultFields\n\nprivate def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do\n  let (structName, structType) \u2190 getStructName stx expectedType? source\n  unless isStructureLike (\u2190 getEnv) structName do\n    throwError \"invalid \\{...} notation, structure type expected{indentExpr structType}\"\n  let struct \u2190 liftMacroM <| mkStructView stx structName source\n  let struct \u2190 expandStruct struct\n  trace[Elab.struct] \"{struct}\"\n  let (r, struct) \u2190 elabStruct struct expectedType?\n  DefaultFields.propagate struct\n  return r\n\n@[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do\n  match (\u2190 expandNonAtomicExplicitSource stx) with\n  | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | none =>\n    let sourceView \u2190 getStructSource stx\n    match (\u2190 isModifyOp? stx), sourceView with\n    | some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType?\n    | some _,        _                        => throwError \"invalid \\{...} notation, explicit source is required when using '[<index>] := <value>'\"\n    | _,             _                        => elabStructInstAux stx expectedType? sourceView\n\nbuiltin_initialize registerTraceClass `Elab.struct\n\nend Lean.Elab.Term.StructInst\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/Elab/StructInst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010667288817792, "lm_q2_score": 0.05340332565681315, "lm_q1q2_score": 0.009618295305212484}}
{"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 `\u00b0`:std.prec.max_plus C := C\u1d52\u1d56 \u2964 Type u\nlocal notation `\u20b8` := \u22a4_ (\u00b0C)\n\n-- Abbreviation for Yoneda on objects and on maps\nabbreviation yob (c : C\u1d52\u1d56) := yoneda.obj c.unop\nabbreviation yom {c d : C\u1d52\u1d56} (f : c \u27f6 d) : yob d \u27f6 yob c := yoneda.map f.unop\n\nstructure forces {X : \u00b0C} (\u03c3 : X \u27f6 \u03a9 \u00b0C) {c : C\u1d52\u1d56} (x : yob c \u27f6 X) :=\n(lift : yob c \u27f6 s{ \u03c3 }s)\n(comm' : lift \u226b canonical_incl \u03c3 = x. obviously)\n\nrestate_axiom forces.comm'\nattribute [simp, reassoc] forces.comm\n\n@[ext]\nprotected lemma lift_ext {X : \u00b0C} (\u03c3 : X \u27f6 \u03a9 \u00b0C) {c : C\u1d52\u1d56} (x : yob c \u27f6 X) : \n  \u03a0 {\u03b1 \u03b2 : forces \u03c3 x}, \u03b1.lift = \u03b2.lift \u2192 \u03b1 = \u03b2\n| \u27e8Ra, _\u27e9 \u27e8Sa, _\u27e9 rfl := rfl\n\ninstance subsingleton_forces {X : \u00b0C} (\u03c3 : X \u27f6 \u03a9 \u00b0C) {c : C\u1d52\u1d56} (x : yob c \u27f6 X) : \n  subsingleton (forces \u03c3 x) :=\nbegin\n  fsplit, intros, ext1,\n  apply pullback.hom_ext,\n  { rw [a.comm, b.comm] },\n  { simp }\nend\n\ndef pforces {X : \u00b0C} (\u03c3 : X \u27f6 \u03a9 \u00b0C) {c : C\u1d52\u1d56} (x : yob c \u27f6 X) : Prop := \n  \u2203 lift : yob c \u27f6 s{ \u03c3 }s, lift \u226b canonical_incl \u03c3 = x \n\nvariables {X : \u00b0C} (\u03c3 : X \u27f6 \u03a9 \u00b0C) {c : C\u1d52\u1d56} (x : yob c \u27f6 X)\n\nlemma forces_to_pforces {x : yob c \u27f6 X} (\u03b1 : forces \u03c3 x) : pforces \u03c3 x := \u27e8\u03b1.lift, \u03b1.comm\u27e9\nlemma pforces_to_forces {x : yob c \u27f6 X} (\u03b1 : pforces \u03c3 x) : forces \u03c3 x :=\n{ lift := (classical.indefinite_description _ \u03b1).val,\n  comm' := (classical.indefinite_description _ \u03b1).prop }\n\nlemma pforces_of_valid (h : validity.is_valid \u03c3) : pforces \u03c3 x :=\nbegin\n  rw validity.valid_iff_is_iso at h,\n  resetI,\n  refine \u27e8 x \u226b (as_iso (canonical_incl \u03c3)).inv, _ \u27e9,\n  rw [assoc, as_iso_inv, is_iso.inv_hom_id, comp_id]\nend\n\nlemma valid_yoneda_iff_pforces : \n  pforces \u03c3 x \u2194 validity.is_valid (x \u226b \u03c3) :=\nbegin\n  split,\n  { intro h, cases h with w h, dunfold validity.is_valid,\n    rw [\u2190h, assoc, canonical_incl_comm, \u2190assoc, limits.terminal.comp_from w]\n  },\n  { intro h, dunfold validity.is_valid at h,\n    exact \u27e8pullback.lift x (terminal.from (yob c)) h, pullback.lift_fst _ _ _\u27e9 }\nend\n\ndef \u03c0_el.obj (d : (X.elements)\u1d52\u1d56) := (category_of_elements.\u03c0 X).obj d.unop\ndef \u03c0_el.map {d e : (X.elements)\u1d52\u1d56} (f : d \u27f6 e) : \u03c0_el.obj e \u27f6 \u03c0_el.obj d := \n(category_of_elements.\u03c0 X).map f.unop\n\n@[simp] lemma simp_el_yob (d : (X.elements)\u1d52\u1d56) : \n  (functor_to_representables X).obj d = yob (\u03c0_el.obj d) := \nbegin\n   unfold functor_to_representables \u03c0_el.obj,\n   rw functor.comp_obj,\n   simp\nend\n-- set_option trace.simp_lemmas true\ndef forall_pforces_to_cocone (u : \u2200 (c : C\u1d52\u1d56) (x : yob c \u27f6 X), forces \u03c3 x) : \n  cocone (functor_to_representables X) :=\n{ X := s{ \u03c3 }s, \n  \u03b9 := { app := \u03bb d, (u (\u03c0_el.obj d) ((cocone_of_representable X).\u03b9.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.\u03c0_map, \n                       subtype.val_eq_coe, functor.const_obj_map],\n            rw [@comp_id _ _ _ (s{\u03c3}s), \u2190cancel_mono (canonical_incl \u03c3), assoc, (u _ _).comm,\n                (u _ _).comm, cocone_of_representable_\u03b9_app, cocone_of_representable_\u03b9_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 : \u2200 (c : C\u1d52\u1d56) (x : yob c \u27f6 X), forces \u03c3 x) (d : (functor.elements X)\u1d52\u1d56) : \n  (forall_pforces_to_cocone \u03c3 u).\u03b9.app d = \n  (u (\u03c0_el.obj d) ((cocone_of_representable X).\u03b9.app d)).lift := by { refl }\n\ndef forall_pforces_to_split_epi (u : \u2200 (c : C\u1d52\u1d56) (x : yob c \u27f6 X), forces \u03c3 x) : \n  split_epi (canonical_incl \u03c3) := \n{ section_ := is_colimit.desc (colimit_of_representable X) (forall_pforces_to_cocone \u03c3 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 : \u00b0C} (\u03c3 : X \u27f6 \u03a9 \u00b0C) :\n  validity.is_valid \u03c3 \u2194 \u2200 (c : C\u1d52\u1d56) (x : yob c \u27f6 X), pforces \u03c3 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 \u226b 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 \u03c3 (\u03bb c x, pforces_to_forces \u03c3 (u c x)) }\nend\n\nlemma monotonicity (h : forces \u03c3 x) {b : C\u1d52\u1d56} (f : c \u27f6 b) : forces \u03c3 (yom f \u226b x) :=\n{ lift := yom f \u226b h.lift,\n  comm' := by rw [assoc, h.comm] }\n\ndef yob_terminal_iso_terminal [has_terminal C] : (yob (opposite.op (\u22a4_ C))) \u2245 \u20b8 :=\nbegin\n  rw [\u2190as_empty_cone_X (\u22a4_ \u00b0C), \u2190as_empty_cone_X (yob (opposite.op (\u22a4_ 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] (\u03c4 : \u20b8 \u27f6 \u03a9 \u00b0C) : \n  pforces \u03c4 (terminal.from (yob (opposite.op (\u22a4_ C)))) \u2194 validity.is_valid \u03c4 :=\nbegin\n  rw validity.valid_iff_section,\n  split,\n  { intro u, fsplit, fsplit,\n    refine \u27e8yob_terminal_iso_terminal.inv \u226b (pforces_to_forces _ u).lift, _\u27e9,\n    simp only [eq_iff_true_of_subsingleton],\n  },\n  { intro h, \n    resetI,\n    refine \u27e8yob_terminal_iso_terminal.hom \u226b (section_ (canonical_incl \u03c4)), _\u27e9,\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 : \u00ac pforces \u22a5 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 \u22a4 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 (\u03c3) (\u03c4 : X \u27f6 \u03a9 \u00b0C)\n\nlemma forcing_and : pforces (\u03c3 \u2293 \u03c4) x \u2194 pforces \u03c3 x \u2227 pforces \u03c4 x :=\nbegin\n  split; intro h,\n  { split; cases h with u h,\n      use u \u226b pullback.lift (canonical_incl (\u03c3 \u2293 \u03c4)) (terminal.from _) \n                (external_iso_internal.left_square_commutes_fst \u03c3 \u03c4),\n      rwa [assoc, pullback.lift_fst],\n      use u \u226b pullback.lift (canonical_incl (\u03c3 \u2293 \u03c4)) (terminal.from _) \n                (external_iso_internal.left_square_commutes_snd \u03c3 \u03c4),\n      rwa [assoc, pullback.lift_fst] },\n  { have comm : x \u226b limits.prod.lift \u03c3 \u03c4 = terminal.from _ \u226b truth_truth \u00b0C := \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 [\u2190hu, assoc, canonical_incl_comm, \u2190assoc, terminal.comp_from u],\n        repeat { rw limits.prod.lift_snd }, cases h.right with u hu,\n        rw [\u2190hu, assoc, canonical_incl_comm, \u2190assoc, terminal.comp_from u],\n    end,\n    let l := pullback_cone.is_limit.lift' (external_iso_internal.is_pullback_and_left \u03c3 \u03c4) \n              x (terminal.from _) comm,\n    exact \u27e8l.val, l.prop.left \u27e9 }\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 \u03b1 := RBMap.empty\n\ninstance : ForIn m (NameMap \u03b1) (Name \u00d7 \u03b1) 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 \u2194 \u00ac (m = n) := by\n  rw [\u2190 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} : \u00ac n.hasMacroScopes \u2192 \u00ac m.hasMacroScopes \u2192 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 : \u2200 {n n'}, quickCmpAux n n' = .eq \u2194 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\u2081 n\u2081, .num p\u2082 n\u2082 => by\n  simp only [quickCmpAux]; split <;>\n  simp_all [quickCmpAux_iff_eq, show \u2200 p, (p \u2192 False) \u2194 \u00ac p from fun _ => .rfl]\n| .str p\u2081 s\u2081, .str p\u2082 s\u2082 => by\n  simp only [quickCmpAux]; split <;>\n  simp_all [quickCmpAux_iff_eq, show \u2200 p, (p \u2192 False) \u2194 \u00ac 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 \u2192 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 \u2192 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": "import Lean.Hygiene\n\ndef otherInhabited : Inhabited Nat := \u27e842\u27e9\n\ndef f := Id.run do\n  let \u27e8n\u27e9 \u2190 pure otherInhabited\n  -- do-notation expands to `pure otherInhabited >>= fun x : Inhabited Nat => ...`\n  -- the `x : Inhabited Nat` should not be available for TC synth (i.e., `default` should be 0)\n  return default + n\n\nexample : f = 42 := rfl\n\nopen Lean\ndef g : Syntax :=\n  let rec stx : Syntax := Unhygienic.run `(f 0 1)\n  let stx := stx\n  match stx with\n  | `(f $_args*) => \u2039Syntax\u203a -- should not resolve to tmp var created by stx matcher\n  | _ => default\n\nexample : g = g.stx := 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/1692.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25386099567919973, "lm_q2_score": 0.03732688667481418, "lm_q1q2_score": 0.00947584061687298}}
{"text": "import ..flocq\n\n/- Architecture-dependent parameters for ARM -/\n\nnamespace archi\nopen flocq\n\ndef ptr64 : bool := ff\n\ndef big_endian : bool := sorry\n\ndef align_int64 := 8\ndef align_float64 := 8\n\ndef splitlong := tt\n\nlemma splitlong_ptr32 : splitlong = tt \u2192 ptr64 = ff := \u03bb_, rfl\n\ndef default_pl_64 : bool \u00d7 nan_pl 53 :=\n(ff, word.repr (2^51))\n  \ndef choose_binop_pl_64 (s1 : bool) (pl1 : nan_pl 53) (s2 : bool) (pl2 : nan_pl 53) : bool :=\n/- Choose second NaN if pl2 is sNaN but pl1 is qNan.\n   In all other cases, choose first NaN -/\npl1.unsigned.test_bit 51 && bnot (pl2.unsigned.test_bit 51)\n\ndef default_pl_32 : bool \u00d7 nan_pl 24 :=\n(ff,  word.repr (2^22))\n  \ndef choose_binop_pl_32 (s1 : bool) (pl1 : nan_pl 24) (s2 : bool) (pl2 : nan_pl 24) : bool :=\n/- Choose second NaN if pl2 is sNaN but pl1 is qNan.\n   In all other cases, choose first NaN -/\npl1.unsigned.test_bit 22 && bnot (pl2.unsigned.test_bit 22)\n   \ndef float_of_single_preserves_sNaN := ff\n    \n/- Which ABI to use : either the standard ARM EABI with floats passed\n  in integer registers, or the \"hardfloat\" variant of the EABI\n  that uses FP registers instead. -/\n\ninductive abi_kind | Softfloat | Hardfloat\nconstant abi : abi_kind\n\nend archi", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/archi/arm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.02517884398652089, "lm_q1q2_score": 0.009413761011900683}}
{"text": "/-\nCopyright (c) E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: E.W.Ayers\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.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.mk_dec_eq_instance\nimport Mathlib.Lean3Lib.init.meta.json\n\nuniverses l \n\nnamespace Mathlib\n\n/-! A component is a piece of UI which may contain internal state. Use component.mk to build new components.\n\n## Using widgets.\n\nTo make a widget, you need to make a custom executor object and then instead of calling `save_info_thunk` you call `save_widget`.\n\nAdditionally, you will need a compatible build of the vscode extension or web app to use widgets in vscode.\n\n## How it works:\n\nThe design is inspired by React.\nIf you are familiar with using React or Elm or a similar functional UI framework then that's helpful for this.\nThe [React article on reconciliation](https://reactjs.org/docs/reconciliation.html) might be helpful.\n\nOne can imagine making a UI for a particular object as just being a function `f : \u03b1 \u2192 UI` where `UI` is some inductive datatype for buttons, textboxes, lists and so on.\nThe process of evaluating `f` is called __rendering__.\nSo for example `\u03b1` could be `tactic_state` and the function renders a goal view.\n\n## HTML\n\nFor our purposes, `UI` is an HTML tree and is written `html \u03b1 : Type`. I'm going to assume some familiarity with HTML for the purposes of this document.\nAn HTML tree is composed of elements and strings.\nEach element has a tag such as \"div\", \"span\", \"article\" and so on and a set of attributes and child html.\nUse the helper function `h : string \u2192 list (attr \u03b1) \u2192 list (html \u03b1) \u2192 html \u03b1` to build new pieces of `html`. So for example:\n\n```lean\nh \"ul\" [] [\n     h \"li\" [] [\"this is list item 1\"],\n     h \"li\" [style [(\"color\", \"blue\")]] [\"this is list item 2\"],\n     h \"hr\" [] [],\n     h \"li\" [] [\n          h \"span\" [] [\"there is a button here\"],\n          h \"button\" [on_click (\u03bb _, 3)] [\"click me!\"]\n     ]\n]\n```\nHas the type `html nat`.\nThe `nat` type is called the __action__ and whenever the user interacts with the UI, the html will emit an object of type `nat`.\nSo for example if the user clicks the button above, the html will 'emit' `3`.\nThe above example is compiled to the following piece of html:\n\n```html\n<ul>\n  <li>this is list item 1</li>\n  <li style=\"{ color: blue; }\">this is list item 2</li>\n  <hr/>\n  <li>\n     <span>There is a button here</span>\n     <button onClick=\"[handler]\">click me!</button>\n  </li>\n</ul>\n```\n\n## Components\n\nIn order for the UI to react to events, you need to be able to take these actions \u03b1 and alter some state.\nTo do this we use __components__. `component` takes two type arguments: `\u03c0` and `\u03b1`. `\u03b1` is called the 'action' and `\u03c0` are the 'props'.\nThe props can be thought of as a kind of wrapped function domain for `component`. So given `C : component nat \u03b1`, one can turn this into html with\n`html.of_component 4 C : html \u03b1`.\n\nThe base constructor for a component is `pure`:\n```lean\nmeta def Hello : component string \u03b1 := component.pure (\u03bb s, [\"hello, \", s, \", good day!\"])\n\n#html Hello \"lean\" -- renders \"hello, lean, good day!\"\n```\nSo here a pure component is just a simple function `\u03c0 \u2192 list (html \u03b1)`.\nHowever, one can augment components with __hooks__.\nThe hooks available for compoenents are listed in the inductive definition for component.\n\nHere we will just look at the `with_state` hook, which can be used to build components with inner state.\n\n```\nmeta inductive my_action\n| increment\n| decrement\nopen my_action\n\nmeta def Counter : component unit \u03b1 :=\ncomponent.with_state\n     my_action          -- the action of the inner component\n     int                -- the state\n     (\u03bb _, 0)           -- initialise the state\n     (\u03bb _ _ s, s)       -- update the state if the props change\n     (\u03bb _ s a,          -- update the state if an action was received\n          match a with\n          | increment := (s + 1, none) -- replace `none` with `some _` to emit an action\n          | decrement := (s - 1, none)\n          end\n     )\n$ component.pure (\u03bb \u27e8state, \u27e8\u27e9\u27e9, [\n     button \"+\" (\u03bb _, increment),\n     to_string state,\n     button \"-\" (\u03bb _, decrement)\n  ])\n\n#html Counter ()\n```\n\nYou can add many hooks to a component.\n\n- `filter_map_action` lets you filter or map actions that are emmitted by the component\n- `map_props` lets you map the props.\n- `with_should_update` will not re-render the child component if the given test returns false. This can be useful for efficiency.\n- `with_state` discussed above.`\n- `with_mouse` subscribes the component to the mouse state, for example whether or not the mouse is over the component. See the `tests/lean/widget/widget_mouse.lean` test for an example.\n\nGiven an active document, Lean (in server mode) maintains a set of __widgets__ for the document.\nA widget is a component `c`, some `p : Props` and an internal state-manager which manages the states\nof the component and subcomponents and also handles the routing of events from the UI.\n\n## Reconciliation\n\nIf a parent component's state changes, this can cause child components to change position or to appear and dissappear.\nHowever we want to preserve the state of these child components where we can.\nThe UI system will try to match up these child components through a process called __reconciliation__.\n\nReconciliation will make sure that the states are carried over correctly and will also not rerender subcomponents if they haven't changed their props or state.\nTo compute whether two components are the same, the system will perform a hash on their VM objects.\nNot all VM objects can be hashed, so it's important to make sure that any items that you expect to change over the lifetime of the component are fed through the 'Props' argument.\nThis is why we need the props argument on `component`.\nThe reconciliation engine uses the `props_eq` predicate passed to the component constructor to determine whether the props have changed and hence whether the component should be re-rendered.\n\n## Keys\n\nIf you have some list of components and the list changes according to some state, it is important to add keys to the components so\nthat if two components change order in the list their states are preserved.\nIf you don't provide keys or there are duplicate keys then you may get some strange behaviour in both the Lean widget engine and react.\n\nIt is possible to use incorrect HTML tags and attributes, there is (currently) no type checking that the result is a valid piece of HTML.\nSo for example, the client widget system will error if you add a `text_change_event` attribute to anything other than an element tagged with `input`.\n\n## Styles with Tachyons\n\nThe widget system assumes that a stylesheet called 'tachyons' is present.\nYou can find documentation for this stylesheet at [Tachyons.io](http://tachyons.io/).\nTachyons was chosen because it is very terse and allows arbitrary styling without using inline styles and without needing to dynamically load a stylesheet.\n\n## Further work (up for grabs!)\n\n- Add type checking for html.\n- Better error handling when the html tree is malformed.\n- Better error handling when keys are malformed.\n- Add a 'with_task' which lets long-running operations (eg running `simp`) not block the UI update.\n- Timers, animation (ambitious).\n- More event handlers\n- Drag and drop support.\n- The current perf bottleneck is sending the full UI across to the server for every update.\n  Instead, it should be possible to send a smaller [JSON Patch](http://jsonpatch.com).\n  Which is already supported by `json.hpp` and javascript ecosystem.\n\n-/\n\nnamespace widget\n\n\ninductive mouse_event_kind where\n| on_click : mouse_event_kind\n| on_mouse_enter : mouse_event_kind\n| on_mouse_leave : mouse_event_kind\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/widget/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530884, "lm_q2_score": 0.042087724160866216, "lm_q1q2_score": 0.009372942013466211}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Util.CollectLevelParams\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.DefView\nimport Lean.Elab.Inductive\nimport Lean.Elab.Structure\nimport Lean.Elab.MutualDef\nimport Lean.Elab.DeclarationRange\nnamespace Lean.Elab.Command\n\nopen Meta\n\n/- Auxiliary function for `expandDeclNamespace?` -/\ndef expandDeclIdNamespace? (declId : Syntax) : Option (Name \u00d7 Syntax) :=\n  let (id, optUnivDeclStx) := expandDeclIdCore declId\n  let scpView := extractMacroScopes id\n  match scpView.name with\n  | Name.str Name.anonymous s _ => none\n  | Name.str pre s _            =>\n    let nameNew := { scpView with name := Name.mkSimple s }.review\n    if declId.isIdent then\n      some (pre, mkIdentFrom declId nameNew)\n    else\n      some (pre, declId.setArg 0 (mkIdentFrom declId nameNew))\n  | _ => none\n\n/- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/\ndef expandDeclNamespace? (stx : Syntax) : Option (Name \u00d7 Syntax) :=\n  if !stx.isOfKind `Lean.Parser.Command.declaration then none\n  else\n    let decl := stx[1]\n    let k := decl.getKind\n    if k == `Lean.Parser.Command.abbrev ||\n       k == `Lean.Parser.Command.def ||\n       k == `Lean.Parser.Command.theorem ||\n       k == `Lean.Parser.Command.constant ||\n       k == `Lean.Parser.Command.axiom ||\n       k == `Lean.Parser.Command.inductive ||\n       k == `Lean.Parser.Command.classInductive ||\n       k == `Lean.Parser.Command.structure then\n      match expandDeclIdNamespace? decl[1] with\n      | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId))\n      | none              => none\n    else if k == `Lean.Parser.Command.instance then\n      let optDeclId := decl[3]\n      if optDeclId.isNone then none\n      else match expandDeclIdNamespace? optDeclId[0] with\n        | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId)))\n        | none              => none\n    else\n      none\n\ndef elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  -- leading_parser \"axiom \" >> declId >> declSig\n  let declId             := stx[1]\n  let (binders, typeStx) := expandDeclSig stx[2]\n  let scopeLevelNames \u2190 getLevelNames\n  let \u27e8name, declName, allUserLevelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName stx\n  runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do\n    Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration\n    let type \u2190 Term.elabType typeStx\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let type \u2190 instantiateMVars type\n    let type \u2190 mkForallFVars xs type\n    let type \u2190 mkForallFVars vars type (usedOnly := true)\n    let (type, _) \u2190 Term.levelMVarToParam type\n    let usedParams  := collectLevelParams {} type |>.params\n    match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with\n    | Except.error msg      => throwErrorAt stx msg\n    | Except.ok levelParams =>\n      let decl := Declaration.axiomDecl {\n        name        := declName,\n        levelParams := levelParams,\n        type        := type,\n        isUnsafe    := modifiers.isUnsafe\n      }\n      Term.ensureNoUnassignedMVars decl\n      addDecl decl\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking\n      if isExtern (\u2190 getEnv) declName then\n        compileDecl decl\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation\n\n/-\nleading_parser \"inductive \" >> declId >> optDeclSig >> optional \":=\" >> many ctor\nleading_parser atomic (group (\"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional \":=\" >> many ctor >> optDeriving\n-/\nprivate def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do\n  checkValidInductiveModifier modifiers\n  let (binders, type?) := expandOptDeclSig decl[2]\n  let declId           := decl[1]\n  let \u27e8name, declName, levelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName decl\n  let ctors      \u2190 decl[4].getArgs.mapM fun ctor => withRef ctor do\n    -- def ctor := leading_parser \" | \" >> declModifiers >> ident >> optional inferMod >> optDeclSig\n    let ctorModifiers \u2190 elabModifiers ctor[1]\n    if ctorModifiers.isPrivate && modifiers.isPrivate then\n      throwError \"invalid 'private' constructor in a 'private' inductive datatype\"\n    if ctorModifiers.isProtected && modifiers.isPrivate then\n      throwError \"invalid 'protected' constructor in a 'private' inductive datatype\"\n    checkValidCtorModifier ctorModifiers\n    let ctorName := ctor.getIdAt 2\n    let ctorName := declName ++ ctorName\n    let ctorName \u2190 withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName\n    let inferMod := !ctor[3].isNone\n    let (binders, type?) := expandOptDeclSig ctor[4]\n    addDocString' ctorName ctorModifiers.docString?\n    addAuxDeclarationRanges ctorName ctor ctor[2]\n    pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView }\n  let classes \u2190 getOptDerivingClasses decl[5]\n  pure {\n    ref             := decl\n    modifiers       := modifiers\n    shortDeclName   := name\n    declName        := declName\n    levelNames      := levelNames\n    binders         := binders\n    type?           := type?\n    ctors           := ctors\n    derivingClasses := classes\n  }\n\nprivate def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView :=\n  inductiveSyntaxToView modifiers decl\n\ndef elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let v \u2190 inductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\ndef elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let modifiers := modifiers.addAttribute { name := `class }\n  let v \u2190 classInductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\n@[builtinCommandElab declaration]\ndef elabDeclaration : CommandElab := fun stx =>\n  match expandDeclNamespace? stx with\n  | some (ns, newStx) => do\n    let ns := mkIdentFrom stx ns\n    let newStx \u2190 `(namespace $ns:ident $newStx end $ns:ident)\n    withMacroExpansion stx newStx $ elabCommand newStx\n  | none => do\n    let modifiers \u2190 elabModifiers stx[0]\n    let decl     := stx[1]\n    let declKind := decl.getKind\n    if declKind == `Lean.Parser.Command.\u00abaxiom\u00bb then\n      elabAxiom modifiers decl\n    else if declKind == `Lean.Parser.Command.\u00abinductive\u00bb then\n      elabInductive modifiers decl\n    else if declKind == `Lean.Parser.Command.classInductive then\n      elabClassInductive modifiers decl\n    else if declKind == `Lean.Parser.Command.\u00abstructure\u00bb then\n      elabStructure modifiers decl\n    else if isDefLike decl then\n      elabMutualDef #[stx]\n    else\n      throwError \"unexpected declaration\"\n\n/- Return true if all elements of the mutual-block are inductive declarations. -/\nprivate def isMutualInductive (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl     := elem[1]\n    let declKind := decl.getKind\n    declKind == `Lean.Parser.Command.inductive\n\nprivate def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do\n  let views \u2190 elems.mapM fun stx => do\n     let modifiers \u2190 elabModifiers stx[0]\n     inductiveSyntaxToView modifiers stx[1]\n  elabInductiveViews views\n\n/- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/\nprivate def isMutualDef (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl := elem[1]\n    isDefLike decl\n\nprivate def isMutualPreambleCommand (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  k == `Lean.Parser.Command.variable ||\n  k == `Lean.Parser.Command.variables ||\n  k == `Lean.Parser.Command.universe ||\n  k == `Lean.Parser.Command.universes ||\n  k == `Lean.Parser.Command.check ||\n  k == `Lean.Parser.Command.set_option ||\n  k == `Lean.Parser.Command.open\n\nprivate partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax \u00d7 Array Syntax) :=\n  let rec loop (i : Nat) : Option (Array Syntax \u00d7 Array Syntax) :=\n    if h : i < elems.size then\n      let elem := elems.get \u27e8i, h\u27e9\n      if isMutualPreambleCommand elem then\n        loop (i+1)\n      else if i == 0 then\n        none -- `mutual` block does not contain any preamble commands\n      else\n        some (elems[0:i], elems[i:elems.size])\n    else\n      none -- a `mutual` block containing only preamble commands is not a valid `mutual` block\n  loop 0\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualNamespace : Macro := fun stx => do\n  let mut ns?      := none\n  let mut elemsNew := #[]\n  for elem in stx[1].getArgs do\n    match ns?, expandDeclNamespace? elem with\n    | _, none                         => elemsNew := elemsNew.push elem\n    | none, some (ns, elem)           => ns? := some ns; elemsNew := elemsNew.push elem\n    | some nsCurr, some (nsNew, elem) =>\n      if nsCurr == nsNew then\n        elemsNew := elemsNew.push elem\n      else\n        Macro.throwErrorAt elem s!\"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration\"\n  match ns? with\n  | some ns =>\n    let ns := mkIdentFrom stx ns\n    let stxNew := stx.setArg 1 (mkNullNode elemsNew)\n    `(namespace $ns:ident $stxNew end $ns:ident)\n  | none => Macro.throwUnsupported\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualElement : Macro := fun stx => do\n  let mut elemsNew := #[]\n  let mut modified := false\n  for elem in stx[1].getArgs do\n    match (\u2190 expandMacro? elem) with\n    | some elemNew => elemsNew := elemsNew.push elemNew; modified := true\n    | none         => elemsNew := elemsNew.push elem\n  if modified then\n    pure $ stx.setArg 1 (mkNullNode elemsNew)\n  else\n    Macro.throwUnsupported\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualPreamble : Macro := fun stx =>\n  match splitMutualPreamble stx[1].getArgs with\n  | none => Macro.throwUnsupported\n  | some (preamble, rest) => do\n    let secCmd    \u2190 `(section)\n    let newMutual := stx.setArg 1 (mkNullNode rest)\n    let endCmd    \u2190 `(end)\n    pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd])\n\n@[builtinCommandElab \u00abmutual\u00bb]\ndef elabMutual : CommandElab := fun stx => do\n  if isMutualInductive stx then\n    elabMutualInductive stx[1].getArgs\n  else if isMutualDef stx then\n    elabMutualDef stx[1].getArgs\n  else\n    throwError \"invalid mutual block\"\n\n/- leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"]\" >> many1 ident -/\n@[builtinCommandElab \u00abattribute\u00bb] def elabAttr : CommandElab := fun stx => do\n  let mut attrInsts := #[]\n  let mut toErase := #[]\n  for attrKindStx in stx[2].getSepArgs do\n    if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then\n      let attrName := attrKindStx[1].getId.eraseMacroScopes\n      unless isAttribute (\u2190 getEnv) attrName do\n        throwError \"unknown attribute [{attrName}]\"\n      toErase := toErase.push attrName\n    else\n      attrInsts := attrInsts.push attrKindStx\n  let attrs \u2190 elabAttrs attrInsts\n  let idents := stx[4].getArgs\n  for ident in idents do withRef ident <| liftTermElabM none do\n    let declName \u2190 resolveGlobalConstNoOverloadWithInfo ident\n    Term.applyAttributes declName attrs\n    for attrName in toErase do\n      Attribute.erase declName attrName\n\ndef expandInitCmd (builtin : Bool) : Macro := fun stx =>\n  let optHeader := stx[1]\n  let doSeq     := stx[2]\n  let attrId    := mkIdentFrom stx $ if builtin then `builtinInit else `init\n  if optHeader.isNone then\n    `(@[$attrId:ident]def initFn : IO Unit := do $doSeq)\n  else\n    let id   := optHeader[0]\n    let type := optHeader[1][1]\n    `(def initFn : IO $type := do $doSeq\n      @[$attrId:ident initFn]constant $id : $type)\n\n@[builtinMacro Lean.Parser.Command.\u00abinitialize\u00bb] def expandInitialize : Macro :=\n  expandInitCmd (builtin := false)\n\n@[builtinMacro Lean.Parser.Command.\u00abbuiltin_initialize\u00bb] def expandBuiltinInitialize : Macro :=\n  expandInitCmd (builtin := true)\n\nend Lean.Elab.Command\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/Elab/Declaration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567817320044, "lm_q2_score": 0.03358950843143849, "lm_q1q2_score": 0.009346508516092103}}
{"text": "import macro\n\ndef \u03b1_conv (rsm : resolve_map) (\u03c3 : syntax_id \u2192 name) : syntax \u2192 syntax\n| (syntax.ident ident) := match rsm.find ident.id with\n  -- TODO: renaming of globals?\n  | some r@{decl := sum.inl id, ..} := syntax.ident {ident with sp := none, name := ident.name.replace_prefix' r.prefix (\u03c3 id)}\n  | _   := syntax.ident {ident with sp := none, name := \u03c3 ident.id}\n  end\n| (syntax.node node) := syntax.node {node with args := node.args.map (\u03bb a, \u03b1_conv a)}\n| (syntax.list ls) := syntax.list (ls.map (\u03bb a, \u03b1_conv a))\n| a@(syntax.atom _) := a\nusing_well_founded { dec_tac := tactic.admit }\n\ndef \u03b1_equiv (rsm : resolve_map) (s\u2081 s\u2082 : syntax) :=\n\u2203 \u03c3, \u03b1_conv rsm \u03c3 s\u2081 = s\u2082\n\n@[simp] protected def except.passert {\u03b5} : except \u03b5 Prop \u2192 Prop\n| (except.ok p)    := p\n| (except.error _) := true\n\n@[simp] lemma except.passert_pure {\u03b5 p} : except.passert (pure p : except \u03b5 Prop) = p := rfl\n\nsection\nopen interactive\nopen interactive.types\nopen tactic\nmeta def tactic.interactive.simp_val (p : parse texpr) : tactic unit :=\ndo e \u2190 i_to_expr_strict p,\n   (e', _) \u2190 conv.convert (conv.interactive.simp ff [] []) e,\n   exact e'\nend\n\nnamespace parse_m\nvariables {r \u03c3 \u03b1 : Type} (cfg : r) (st : \u03c3)\n\nprotected def run_cont {\u03b2} (x : parse_m r \u03c3 \u03b1) (cont : \u03c3 \u2192 \u03b1 \u2192 except string \u03b2) : except string \u03b2 :=\nmatch parse_m.run cfg st x with\n| (except.ok a, st)   := cont st a\n| (except.error e, _) := except.error e\nend\n\nprotected def passert_cont (x : parse_m r \u03c3 \u03b1) (cont : \u03c3 \u2192 \u03b1 \u2192 Prop) : Prop :=\nexcept.passert $ parse_m.run_cont cfg st x $ \u03bb st a, pure (cont st a)\n\nprotected def passert (x : parse_m r \u03c3 Prop) : Prop :=\nparse_m.passert_cont cfg st x (\u03bb st, id)\n\nvariables {cfg} {st}\nvariables {\u03b2 \u03b3 : Type} (p : \u03c3 \u2192 \u03b2 \u2192 except string \u03b3)\nvariables (q : \u03c3 \u2192 \u03b1 \u2192 except string \u03b2)\n\nlocal attribute [simp] parse_m.run_cont parse_m.run\nattribute [reducible] parse_m\nattribute [reducible]\n  parse_m.monad_run except_t.monad_run state_t.monad_run reader_t.monad_run id.monad_run\n\nvariable (x : parse_m r \u03c3 \u03b1)\n\n@[simp] lemma run_cont_pure (a : \u03b1) : parse_m.run_cont cfg st (pure a) q = q st a := rfl\n\n@[simp] lemma run_cont_bind (f : \u03b1 \u2192 parse_m r \u03c3 \u03b2) :\n  parse_m.run_cont cfg st (x >>= f) p =\n  parse_m.run_cont cfg st x (\u03bb st' a, parse_m.run_cont cfg st' (f a) p) :=\nby simp; cases (by simp_val parse_m.run cfg st x); cases fst; simp [except_t.bind_cont]\n\n@[simp] lemma run_cont_map (f : \u03b1 \u2192 \u03b2) :\n  parse_m.run_cont cfg st (f <$> x) p =\n  parse_m.run_cont cfg st x (\u03bb st' a, p st' (f a)) :=\nby simp; cases (by simp_val parse_m.run cfg st x); cases fst; simp [except.map]\n\n@[simp] lemma run_cont_adapt_state {\u03c3' \u03c3''} (f : \u03c3 \u2192 \u03c3' \u00d7 \u03c3'') (f') (x : parse_m r \u03c3' \u03b1) :\n  parse_m.run_cont cfg st (adapt_state f f' x) q =\n    let (st',st'') := f st in parse_m.run_cont cfg st' x (\u03bb st', q (f' st' st'')) :=\nby cases h : f st with st' st''; simp [adapt_state]; rw [h]; simp; cases (by simp_val parse_m.run cfg st' x); cases fst; simp\n\n@[simp] lemma run_cont_put (p : \u03c3 \u2192 punit \u2192 except string \u03b3) (st') :\n  parse_m.run_cont cfg st (put st') p = p st' punit.star :=\nby simp [put, monad_state.lift]\n\n@[simp] lemma run_cont_read (p : \u03c3 \u2192 r \u2192 except string \u03b3) :\n  parse_m.run_cont cfg st read p = p st cfg :=\nby simp [read]\n\n@[simp] lemma run_cont_throw (e) (p : \u03c3 \u2192 \u03b1 \u2192 except string \u03b3) :\n  parse_m.run_cont cfg st (throw e) p = except.error e :=\nby simp [throw]\n\nlemma passert_mp {p : parse_m r \u03c3 \u03b1} {s\u2080 : \u03c3} {post\u2081 post\u2082 : \u03c3 \u2192 \u03b1 \u2192 except string Prop} :\n  except.passert (parse_m.run_cont cfg s\u2080 p post\u2081) \u2192 (\u2200 s a, except.passert (post\u2081 s a) \u2192 except.passert (post\u2082 s a)) \u2192 except.passert (parse_m.run_cont cfg s\u2080 p post\u2082) :=\nbegin\n  simp,\n  intros hpost\u2081 hmp,\n  cases (by simp_val parse_m.run cfg s\u2080 p); cases fst; simp [parse_m.run_cont] at *,\n  apply hmp _ _ hpost\u2081\nend\n\n@[simp] lemma passert_invariant {p : parse_m r \u03c3 \u03b1} {s\u2080 : \u03c3} {post : except string Prop} :\n  except.passert post \u2192 except.passert (parse_m.run_cont cfg s\u2080 p (\u03bb _ _, post)) :=\nbegin\n  simp,\n  cases (by simp_val parse_m.run cfg s\u2080 p); cases fst; simp [parse_m.run_cont] at *,\n  exact id\nend\n\nend parse_m\n\ntheorem hygienic (s\u2081 s\u2082 : syntax) (st : parse_state) :\nparse_m.passert st () $\ndo s\u2081' \u2190 expand' s\u2081,\n   s\u2082' \u2190 expand' s\u2082,\n   (_, rst) \u2190 resolve' s\u2081',\n   pure $ \u03b1_equiv rst.resolve_map s\u2081 s\u2082 \u2192 \u03b1_equiv rst.resolve_map s\u2081' s\u2082' := sorry\n\nlemma expand_idem (s : syntax) (cfg : parse_state) :\nparse_m.passert cfg () $\ndo s' \u2190 expand' s,\n   s'' \u2190 expand' s',\n   pure $ s'' = s' :=\nbegin\n  -- generalize states (irrelevant) and step counts\n  suffices : \u2200 st steps steps\u2082, steps \u2264 steps\u2082 \u2192\n(parse_m.passert_cont cfg st (expand steps s) $ \u03bb _ s',\n \u2200 st\u2082, parse_m.passert_cont cfg st\u2082 (expand steps\u2082 s') $ \u03bb _ s'',\n s'' = s'),\n  { simp [parse_m.passert, parse_m.passert_cont, expand'] at *,\n    apply parse_m.passert_mp, apply this, apply le_refl,\n    intros st' s' x, apply x },\n  simp [parse_m.passert_cont],\n  intros st steps steps\u2082,\n  induction steps with steps generalizing s st steps\u2082,\n  -- `expand s` out of steps: trivial\n  { intros; simp [expand] },\n  { intro hsteps\u2082,\n    -- `expand s'` can do at least one step as well\n    cases steps\u2082 with steps\u2082, { exfalso, apply nat.not_succ_le_zero _ hsteps\u2082 },\n    -- recursive case 1: holds when expanding all children (when s is not a macro)\n    have expand_mmap : \u2200 (val : syntax_node syntax),\n      parse_m.passert_cont cfg st (mmap (expand steps) (val.args)) $ \u03bb _ args',\n      \u2200 st\u2082, parse_m.passert_cont cfg st\u2082 (mmap (expand steps\u2082) args') $ \u03bb _ args'',\n        args'' = args',\n    begin\n        intro,\n        simp [parse_m.passert_cont] at *,\n        induction val.args generalizing st; simp [mmap],\n        case list.cons {\n          apply parse_m.passert_mp (steps_ih _ st _ (nat.le_of_succ_le_succ hsteps\u2082)), intros st' s' expand_s',\n          clear steps_ih,\n          apply parse_m.passert_mp (ih st'), intros st'' args' mmap_args' st\u2082,\n          clear ih,\n          apply parse_m.passert_mp (expand_s' _), intros st''' s''' h,\n          apply parse_m.passert_mp (mmap_args' _), intros st'''' args this,\n          simp * at *,\n        }\n    end,\n    cases hs : s; simp [expand],\n    --TODO `case` for ginductives\n    --case syntax.node n {\n    { cases h : rbmap.find cfg.macros val.m with m,\n      case none { simp [expand, h], apply expand_mmap },\n      case some {\n        cases m, cases m_expand,\n        case none { simp [expand, h], apply expand_mmap },\n        case some {\n          -- recursive case 1: re-expand the expansion of s. `expand s` will do one more step than `expand s'`.\n          -- `mk_tag` is so simple that `simp` can automatically transform it to its spec\n          simp [expand, mk_tag],\n          apply parse_m.passert_mp (steps_ih _ _ _ (nat.le_of_succ_le hsteps\u2082)), intros st' s' expand_s',\n          apply expand_s',\n        },\n      }\n    }\n  }\nend\n", "meta": {"author": "Kha", "repo": "syntax", "sha": "af05028581955d9fd5af99be9cbb82f5c9226551", "save_path": "github-repos/lean/Kha-syntax", "path": "github-repos/lean/Kha-syntax/syntax-af05028581955d9fd5af99be9cbb82f5c9226551/hygiene.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804614657029, "lm_q2_score": 0.03514484854829156, "lm_q1q2_score": 0.009344328550161997}}
{"text": "\n\nexample (M : Type \u2192 Type) [Monad M] : ExceptT Unit (ReaderT Unit (StateT Unit M)) Unit := do\nlet ctx \u2190 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' : \u211d\u22650)\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 (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{u} r')\n\nsection preps\n\nvariables (V : SemiNormedGroup.{u}) [complete_space V] [separated_space V]\nvariables (\u03b9 : ulift.{u+1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9)\n\nset_option pp.universes true\n\nlemma cofan_point_iso_colimit_conj_eq_desc\n  {e : (homotopy_category.colimit_cofan\n     (\u03bb (a : ulift \u2115), ((\u03bb (k : ulift \u2115),\n     (QprimeFP r' BD.data \u03ba\u2082 M).obj (\u03b9 k)) a).val)).X.is_bounded_above} :\n  (cofan_point_iso_colimit\n    (\u03bb (k : ulift \u2115), (QprimeFP r' BD.data \u03ba\u2082 M).obj (\u03b9 k))).inv \u226b\n  of_hom (sigma_shift \u03b9 h\u03b9 (QprimeFP_int r' BD.data \u03ba\u2082 M)) \u226b\n    (cofan_point_iso_colimit (\u03bb (k : ulift \u2115),\n    (QprimeFP r' BD.data \u03ba\u2082 M).obj (\u03b9 k))).hom =\n  begin\n    apply sigma.desc,\n    intros k,\n    refine _ \u226b sigma.\u03b9 _ (ulift.up $ ulift.down k + 1),\n    refine (QprimeFP r' BD.data \u03ba\u2082 M).map _,\n    refine hom_of_le (h\u03b9 _),\n    exact_mod_cast k.down.le_succ,\n  end :=\nbegin\n  ext j,\n  dsimp only [cofan_point_iso_colimit],\n  rw [colimit.\u03b9_desc, cofan.mk_\u03b9_app,\n      colimit.comp_cocone_point_unique_up_to_iso_inv_assoc],\n  simp only [\u2190 category.assoc], rw [\u2190 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_\u03b9_app,\n    of_hom, homotopy_category.colimit_cofan],\n  erw [\u2190 functor.map_comp, colimit.\u03b9_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 : \u2124) :\n  (\u220f \u03bb (k : ulift \u2115), ((QprimeFP r' BD.data \u03ba\u2082 M).op \u22d9\n    (Ext i).flip.obj ((single (Condensed Ab) 0).obj V.to_Cond)).obj (op (\u03b9 k))) \u2245\n  ((Ext i).obj (op (of' (\u2210 \u03bb (k : ulift \u2115), (QprimeFP_int r' BD.data \u03ba\u2082 M).obj (\u03b9 k))))).obj\n    ((single (Condensed Ab) 0).obj (Condensed.of_top_ab \u21a5V)) :=\n(Ext_coproduct_iso\n  (\u03bb k : ulift \u2115, (QprimeFP r' BD.data \u03ba\u2082 M).obj (\u03b9 k)) i\n  ((single (Condensed Ab) 0).obj V.to_Cond)).symm \u226a\u226b\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    (\u03bb (k : ulift \u2115), (QprimeFP r' BD.data \u03ba\u2082 M).obj (\u03b9 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 : \u2115) (f : X \u27f6 Y) :\n  (n \u2022 f).op = n \u2022 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 \u27f6 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 \u2124)) (f g : X \u27f6 Y)\n  [((homotopy_category.quotient C (complex_shape.up \u2124)).obj X).is_bounded_above]\n  [((homotopy_category.quotient C (complex_shape.up \u2124)).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  {\u03b1 : Type v}\n  (X\u2081 X\u2082 : \u03b1 \u2192 bounded_homotopy_category A)\n  [uniformly_bounded X\u2081]\n  [uniformly_bounded X\u2082]\n  (g : X\u2081 \u27f6 X\u2082)\n  (i : \u2124) (Y) :\n  (Ext_coproduct_iso _ _ _).inv \u226b\n  ((Ext i).map (sigma.desc (\u03bb b, g b \u226b sigma.\u03b9 X\u2082 b) : \u2210 X\u2081 \u27f6 \u2210 X\u2082).op).app Y =\n  pi.lift (\u03bb b, pi.\u03c0 _ b \u226b ((Ext i).map (g b).op).app Y) \u226b (Ext_coproduct_iso _ _ _).inv :=\nbegin\n  rw [iso.inv_comp_eq, \u2190 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": "structure Var : Type := (name : String)\ninstance Var.nameCoe : HasCoe String Var := \u27e8Var.mk\u27e9\n\nstructure A : Type := (u : Unit)\nstructure B : Type := (u : Unit)\n\ndef a : A := A.mk ()\ndef b : B := B.mk ()\n\ndef Foo.chalk : A \u2192 List Var \u2192 Unit := \u03bb _ _ => ()\ndef Bar.chalk : B \u2192 Unit := \u03bb _ => ()\n\nopen Foo\nopen Bar\n\ninstance listCoe {\u03b1 \u03b2} [HasCoe \u03b1 \u03b2] : HasCoe (List \u03b1) (List \u03b2) :=\n\u27e8fun as => as.map coe\u27e9\n\n/- The following succeeds: -/\n#check Foo.chalk a [\"foo\"] -- succeeds\n\n/-\nThe following application fails, due to a curious interaction\nbetween coercions and ad-hoc overloading.\n-/\n#check chalk a [\"foo\"] -- fails\n\n/-\nNote that the first argument clearly distinguishes the two\n`chalk` applications, and there are no coercions in play for the first argument.\n\nI am not arguing that we should support this case, merely logging that it surprised me,\nand that I can not employ an otherwise desirable use of overloading because of it.\n\nNote: it works if `Foo.chalk` takes `A` and `Var` and we pass `a` and `\"foo\"`.\n-/\n\n/-\n\nHere is the analysis of why it doesn't work.\nGiven `chalk a [\"foo\"]` where `chalk` is overloaded,\nthe current elaborator performs the following steps:\n\n1- Elaborate the arguments `a` and `[\"foo\"]` without an expected\ntype. Thus, `[\"foo\"]` is elaborated as a list of strings.\n\n2- For each possible interpretation of `chalk`, we try to match the\narguments with the expected types. `Bar.chalk` fails because there is\nno coercion from `A` to `B`. `Foo.chalk` fails because there is no\ncoercion from `List String` to `List Var`. Note that the example would\nwork if we had the coercion\n\n```\ninstance listCoe {\u03b1 \u03b2} [HasCoe \u03b1 \u03b2] : HasCoe (List \u03b1) (List \u03b2) :=\n\u27e8fun as => as.map coe\u27e9\n```\nHowever, users could still be surprised by the fact that the `chalk a [\"foo\"]` is\nelaborated as `Foo.chalk a (coe [\"foo\"])` instead of `Foo.chalk a [coe \"foo\"]`.\n\nHere are some alternative elaboration strategies I have considered.\nWe should discuss them in the next Dev meeting.\n\n1- Instead of elaborating all arguments without an expected type, we\nelaborate only the shortest argument prefix that is sufficient for\nselecting the right overload candidate. Daniel's comments above\nsuggest this is the strategy he expected. It would fix this particular\ninstance, but it would still confuse users. For example, we can create\nthe alternative problem `chalk [\"foo\"] a`. Users could say \"the second\nargument clearly distinguishes the two applications.\"\n\n2- Elaborate `chalk a [\"foo\"]` for each possible overload.  This is a\nrobust solution but may produce an exponential blowup. For example,\nsuppose we have `f_1 (f_2 (f_3 (f_4 ... (f_n a) ... )))` where all\n`f_i` are overloaded. Moreover, every overload has the same result\ntype. Thus, we cannot prune the search space using the expected\ntype. This situation does not seem to occur in our code base.  It did\nhappen in Lean2, when we used to overload symbols such as `+` and `*`.\nWe should ask Reid how often overloads are used in mathlib, and\nwhether the exponential blowup is a real problem or not for them.\n\n3- Use Lean3 approach, but when we get a typing error after we\nselected the right overload candidate, we re-elaborate it using the\nexpected type instead of failing. This approach looks too haskish, and\nit may still produce an exponential blowup.\n\nI am inclined to (try to) use solution 2 in Lean4. We can have a\nthreshold on the amount of backtracking, and when it exceeds we\nproduce an error message stating all overloads that are generating\nthe huge search space.\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/overload_with_list_coercion.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799314806233, "lm_q2_score": 0.04672496327215783, "lm_q1q2_score": 0.009312658659690698}}
{"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.Parser.Command\nimport Lean.Meta.Closure\nimport Lean.Meta.SizeOf\nimport Lean.Meta.Injective\nimport Lean.Meta.Structure\nimport Lean.Meta.AppBuilder\nimport Lean.Elab.Command\nimport Lean.Elab.DeclModifiers\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.Inductive\nimport Lean.Elab.DeclarationRange\nimport Lean.Elab.Binders\n\nnamespace Lean.Elab.Command\n\nopen Meta\n\n/- Recall that the `structure command syntax is\n```\nleading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType >> optional (\" := \" >> optional structCtor >> structFields)\n```\n-/\n\nstructure StructCtorView where\n  ref       : Syntax\n  modifiers : Modifiers\n  inferMod  : Bool  -- true if `{}` is used in the constructor declaration\n  name      : Name\n  declName  : Name\n\nstructure StructFieldView where\n  ref        : Syntax\n  modifiers  : Modifiers\n  binderInfo : BinderInfo\n  inferMod   : Bool\n  declName   : Name\n  name       : Name\n  binders    : Syntax\n  type?      : Option Syntax\n  value?     : Option Syntax\n\nstructure StructView where\n  ref               : Syntax\n  modifiers         : Modifiers\n  scopeLevelNames   : List Name  -- All `universe` declarations in the current scope\n  allUserLevelNames : List Name  -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command\n  isClass           : Bool\n  declName          : Name\n  scopeVars         : Array Expr -- All `variable` declaration in the current scope\n  params            : Array Expr -- Explicit parameters provided in the `structure` command\n  parents           : Array Syntax\n  type              : Syntax\n  ctor              : StructCtorView\n  fields            : Array StructFieldView\n\ninductive StructFieldKind where\n  | newField | copiedField | fromParent | subobject\n  deriving Inhabited, BEq\n\nstructure StructFieldInfo where\n  name     : Name\n  declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary \"default value\" functions.\n  fvar     : Expr\n  kind     : StructFieldKind\n  inferMod : Bool := false\n  value?   : Option Expr := none\n  deriving Inhabited\n\ndef StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool :=\n  match info.kind with\n  | StructFieldKind.fromParent => true\n  | _                          => false\n\ndef StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool :=\n  match info.kind with\n  | StructFieldKind.subobject => true\n  | _                         => false\n\n/- Auxiliary declaration for `mkProjections` -/\nstructure ProjectionInfo where\n  declName : Name\n  inferMod : Bool\n\nstructure ElabStructResult where\n  decl            : Declaration\n  projInfos       : List ProjectionInfo\n  projInstances   : List Name -- projections (to parent classes) that must be marked as instances.\n  mctx            : MetavarContext\n  lctx            : LocalContext\n  localInsts      : LocalInstances\n  defaultAuxDecls : Array (Name \u00d7 Expr \u00d7 Expr)\n\nprivate def defaultCtorName := `mk\n\n/-\nThe structure constructor syntax is\n```\nleading_parser try (declModifiers >> ident >> optional inferMod >> \" :: \")\n```\n-/\nprivate def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do\n  let useDefault := do\n    let declName := structDeclName ++ defaultCtorName\n    addAuxDeclarationRanges declName structStx[2] structStx[2]\n    pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName }\n  if structStx[5].isNone then\n    useDefault\n  else\n    let optCtor := structStx[5][1]\n    if optCtor.isNone then\n      useDefault\n    else\n      let ctor := optCtor[0]\n      withRef ctor do\n      let ctorModifiers \u2190 elabModifiers ctor[0]\n      checkValidCtorModifier ctorModifiers\n      if ctorModifiers.isPrivate && structModifiers.isPrivate then\n        throwError \"invalid 'private' constructor in a 'private' structure\"\n      if ctorModifiers.isProtected && structModifiers.isPrivate then\n        throwError \"invalid 'protected' constructor in a 'private' structure\"\n      let inferMod := !ctor[2].isNone\n      let name := ctor[1].getId\n      let declName := structDeclName ++ name\n      let declName \u2190 applyVisibility ctorModifiers.visibility declName\n      addDocString' declName ctorModifiers.docString?\n      addAuxDeclarationRanges declName ctor[1] ctor[1]\n      pure { ref := ctor, name, modifiers := ctorModifiers, inferMod, declName }\n\ndef checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do\n  if modifiers.isNoncomputable then\n    throwError \"invalid use of 'noncomputable' in field declaration\"\n  if modifiers.isPartial then\n    throwError \"invalid use of 'partial' in field declaration\"\n  if modifiers.isUnsafe then\n    throwError \"invalid use of 'unsafe' in field declaration\"\n  if modifiers.attrs.size != 0 then\n    throwError \"invalid use of attributes in field declaration\"\n\n/-\n```\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> optional inferMod >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> optional inferMod >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)\n```\n-/\nprivate def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) :=\n  let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs\n  fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do\n    let mut fieldBinder := fieldBinder\n    if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then\n      fieldBinder := Syntax.node ``Parser.Command.structExplicitBinder\n        #[ fieldBinder[0], mkAtomFrom fieldBinder \"(\", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder \")\" ]\n    let k := fieldBinder.getKind\n    let binfo \u2190\n      if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default\n      else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit\n      else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit\n      else throwError \"unexpected kind of structure field\"\n    let fieldModifiers \u2190 elabModifiers fieldBinder[0]\n    checkValidFieldModifier fieldModifiers\n    if fieldModifiers.isPrivate && structModifiers.isPrivate then\n      throwError \"invalid 'private' field in a 'private' structure\"\n    if fieldModifiers.isProtected && structModifiers.isPrivate then\n      throwError \"invalid 'protected' field in a 'private' structure\"\n    let inferMod         := !fieldBinder[3].isNone\n    let (binders, type?) \u2190\n      if binfo == BinderInfo.default then\n        let (binders, type?) := expandOptDeclSig fieldBinder[4]\n        let optBinderTacticDefault := fieldBinder[5]\n        if optBinderTacticDefault.isNone then\n          pure (binders, type?)\n        else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then\n          pure (binders, type?)\n        else\n          let binderTactic := optBinderTacticDefault[0]\n          match type? with\n          | none => throwErrorAt binderTactic \"invalid field declaration, type must be provided when auto-param (tactic) is used\"\n          | some type =>\n            let tac := binderTactic[2]\n            let name \u2190 Term.declareTacticSyntax tac\n            -- The tactic should be for binders+type.\n            -- It is safe to reset the binders to a \"null\" node since there is no value to be elaborated\n            let type \u2190 `(forall $(binders.getArgs):bracketedBinder*, $type)\n            let type \u2190 `(autoParam $type $(mkIdentFrom tac name))\n            pure (mkNullNode, some type)\n      else\n        let (binders, type) := expandDeclSig fieldBinder[4]\n        pure (binders, some type)\n    let value? \u2190\n      if binfo != BinderInfo.default then\n        pure none\n      else\n        let optBinderTacticDefault := fieldBinder[5]\n        -- trace[Elab.struct] \">>> {optBinderTacticDefault}\"\n        if optBinderTacticDefault.isNone then\n          pure none\n        else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then\n          pure none\n        else\n          -- binderDefault := leading_parser \" := \" >> termParser\n          pure (some optBinderTacticDefault[0][1])\n    let idents := fieldBinder[2].getArgs\n    idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do\n      let name := ident.getId.eraseMacroScopes\n      unless name.isAtomic do\n        throwErrorAt ident \"invalid field name '{name.eraseMacroScopes}', field names must be atomic\"\n      let declName := structDeclName ++ name\n      let declName \u2190 applyVisibility fieldModifiers.visibility declName\n      addDocString' declName fieldModifiers.docString?\n      return views.push {\n        ref        := ident\n        modifiers  := fieldModifiers\n        binderInfo := binfo\n        inferMod\n        declName\n        name\n        binders\n        type?\n        value?\n      }\n\nprivate def validStructType (type : Expr) : Bool :=\n  match type with\n  | Expr.sort .. => true\n  | _            => false\n\nprivate def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo :=\n  infos.find? fun info => info.name == fieldName\n\nprivate def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool :=\n  (findFieldInfo? infos fieldName).isSome\n\nprivate def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo :=\n  infos.map fun info =>\n    if info.name == fieldName then\n      { info with value? := value  }\n    else\n      info\n\nregister_builtin_option structureDiamondWarning : Bool := {\n  defValue := false\n  descr    := \"enable/disable warning messages for structure diamonds\"\n}\n\n/-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/\nprivate def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do\n  let fieldNames := getStructureFieldsFlattened (\u2190 getEnv) parentStructName\n  for fieldName in fieldNames do\n    if containsFieldName infos fieldName then\n      return some fieldName\n  return none\n\nprivate partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name)\n    (infos : Array StructFieldInfo) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  go 0 infos\nwhere\n  go (i : Nat) (infos : Array StructFieldInfo) := do\n    if h : i < subfieldNames.size then\n      let subfieldName := subfieldNames.get \u27e8i, h\u27e9\n      if containsFieldName infos subfieldName then\n        throwError \"field '{subfieldName}' from '{parentStructName}' has already been declared\"\n      let val  \u2190 mkProjection parentFVar subfieldName\n      let type \u2190 inferType val\n      withLetDecl subfieldName type val fun subfieldFVar =>\n        /- The following `declName` is only used for creating the `_default` auxiliary declaration name when\n           its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/\n        let declName := structDeclName ++ subfieldName\n        let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent }\n        go (i+1) infos\n    else\n      k infos\n\n/-- Return `some (structName, fieldName, struct)` if `e` is a projection function application -/\nprivate def isProjFnApp? (e : Expr) : MetaM (Option (Name \u00d7 Name \u00d7 Expr)) := do\n  match e.getAppFn with\n  | Expr.const declName .. =>\n    match (\u2190 getProjectionFnInfo? declName) with\n    | some { ctorName := ctorName, numParams := n, .. } =>\n      if declName.isStr && e.getAppNumArgs == n+1 then\n        let ConstantInfo.ctorInfo ctorVal \u2190 getConstInfo ctorName | unreachable!\n        return some (ctorVal.induct, declName.getString!, e.appArg!)\n      else\n        return none\n    | _ => return none\n  | _ => return none\n\n/--\n  Return `some fieldName`, if `e` is an expression that represents an access to field `fieldName` of the structure `s`.\n  The name of the structure type must be `structName`. -/\nprivate partial def isProjectionOf? (e : Expr) (structName : Name) (s : Expr) : MetaM (Option Name) := do\n  if let some (baseStructName, fieldName, e) \u2190 isProjFnApp? e then\n    if let some path \u2190 visit e #[] then\n      if let some path' := getPathToBaseStructure? (\u2190 getEnv) baseStructName structName then\n        if path'.toArray == path.reverse then\n          return some fieldName\n  return none\nwhere\n  visit (e : Expr) (path : Array Name) : MetaM (Option (Array Name)) := do\n    if e == s then return some path\n    -- Check whether `e` is a `toParent` field\n    if let some (_, _, e') \u2190 isProjFnApp? e then\n      visit e' (path.push e.getAppFn.constName!)\n    else\n      return none\n\n/-- Auxiliary method for `copyNewFieldsFrom`. -/\nprivate def getFieldType (infos : Array StructFieldInfo) (parentStructName : Name) (parentType : Expr) (fieldName : Name) : MetaM Expr := do\n  withLocalDeclD (\u2190 mkFreshId) parentType fun parent => do\n    let proj \u2190 mkProjection parent fieldName\n    let projType \u2190 inferType proj\n    /- Eliminate occurrences of `parent`. This may happen when structure contains dependent fields. -/\n    let visit (e : Expr) : MetaM TransformStep := do\n      if let some fieldName \u2190 isProjectionOf? e parentStructName parent then\n        -- trace[Meta.debug] \"field '{fieldName}' of {e}\"\n        match (\u2190 findFieldInfo? infos fieldName) with\n        | some existingFieldInfo => return TransformStep.done existingFieldInfo.fvar\n        | none => throwError \"unexpected field access {indentExpr e}\"\n      else\n        return TransformStep.done e\n    Meta.transform projType (post := visit)\n\nprivate def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do\n  if isProtected (\u2190 getEnv) fieldInfo.projFn then\n    return Visibility.protected\n  else if isPrivateName fieldInfo.projFn then\n    return Visibility.private\n  else\n    return Visibility.regular\n\nabbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field\n\n/-- Reduce projetions of the structures in `structNames` -/\nprivate def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr :=\n  let reduce (e : Expr) : MetaM TransformStep := do\n    match (\u2190 reduceProjOf? e structNames.contains) with\n    | some v => return TransformStep.done v\n    | _ => return TransformStep.done e\n  transform e (post := reduce)\n\n/--\n  Copy the default value for field `fieldName` set at structure `structName`.\n  The arguments for the `_default` auxiliary function are provided by `fieldMap`.\n  Recall some of the entries in `fieldMap` are constructor applications, and they needed\n  to be reduced using `reduceProjs`. Otherwise, the produced default value may be \"cyclic\".\n  That is, we reduce projections of the structures in `expandedStructNames`. Here is\n  an example that shows why the reduction is needed.\n  ```\n  structure A where\n    a : Nat\n\n  structure B where\n    a : Nat\n    b : Nat\n    c : Nat\n\n  structure C extends B where\n    d : Nat\n    c := b + d\n\n  structure D extends A, C\n\n  #print D.c._default\n  ```\n  Without the reduction, it produces\n  ```\n  def D.c._default : A \u2192 Nat \u2192 Nat \u2192 Nat \u2192 Nat :=\n  fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d)\n  ```\n-/\nprivate partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do\n  match getDefaultFnForField? (\u2190 getEnv) structName fieldName with\n  | none => return none\n  | some defaultFn =>\n    let cinfo \u2190 getConstInfo defaultFn\n    let us \u2190 mkFreshLevelMVarsFor cinfo\n    go? (cinfo.instantiateValueLevelParams us)\nwhere\n  failed : TermElabM (Option Expr) := do\n    logWarning s!\"ignoring default value for field '{fieldName}' defined at '{structName}'\"\n    return none\n\n  go? (e : Expr) : TermElabM (Option Expr) := do\n    match e with\n    | Expr.lam n d b c =>\n      if c.binderInfo.isExplicit then\n        let fieldName := n\n        match fieldMap.find? n with\n        | none => failed\n        | some val =>\n          let valType \u2190 inferType val\n          if (\u2190 isDefEq valType d) then\n            go? (b.instantiate1 val)\n          else\n            failed\n      else\n        let arg \u2190 mkFreshExprMVar d\n        go? (b.instantiate1 arg)\n    | e =>\n      let r := if e.isAppOfArity ``id 2 then e.appArg! else e\n      return some (\u2190 reduceProjs (\u2190 instantiateMVars e.appArg!) expandedStructNames)\n\nprivate partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  copyFields infos {} parentType fun infos _ _ => k infos\nwhere\n  copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo \u2192 FieldMap \u2192 NameSet \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n    let parentStructName \u2190 getStructureName parentType\n    let fieldNames := getStructureFields (\u2190 getEnv) parentStructName\n    let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM \u03b1 := do\n      if h : i < fieldNames.size then\n        let fieldName := fieldNames.get \u27e8i, h\u27e9\n        let fieldType \u2190 getFieldType infos parentStructName parentType fieldName\n        match (\u2190 findFieldInfo? infos fieldName) with\n        | some existingFieldInfo =>\n          let existingFieldType \u2190 inferType existingFieldInfo.fvar\n          unless (\u2190 isDefEq fieldType existingFieldType) do\n            throwError \"parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {\u2190 mkHasTypeButIsExpectedMsg fieldType existingFieldType}\"\n          /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/\n          copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames\n        | none =>\n          let some fieldInfo \u2190 getFieldInfo? (\u2190 getEnv) parentStructName fieldName | unreachable!\n          let addNewField : TermElabM \u03b1 := do\n            let value? \u2190 copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName\n            withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do\n              let fieldDeclName := structDeclName ++ fieldName\n              let fieldDeclName \u2190 applyVisibility (\u2190 toVisibility fieldInfo) fieldDeclName\n              let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?,\n                                        kind := StructFieldKind.copiedField, inferMod := fieldInfo.inferMod }\n              copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames\n          if fieldInfo.subobject?.isSome then\n            let fieldParentStructName \u2190 getStructureName fieldType\n            if (\u2190 findExistingField? infos fieldParentStructName).isSome then\n              -- See comment at `copyDefaultValue?`\n              let expandedStructNames := expandedStructNames.insert fieldParentStructName\n              copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do\n                let fieldVal \u2190 mkCompositeField fieldType nestedFieldMap\n                trace[Meta.debug] \"composite, {fieldName} := {fieldVal}\"\n                copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames\n            else\n              addNewField\n          else\n            addNewField\n      else\n        let infos \u2190 processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName\n        k infos fieldMap expandedStructNames\n    copy 0 infos {} expandedStructNames\n\n  processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) :=\n    infos.mapM fun info => do\n      match (\u2190 copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with\n      | some value => return { info with value? := value }\n      | none       => return info\n\n  mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do\n    let env \u2190 getEnv\n    let Expr.const parentStructName us _ \u2190 pure parentType.getAppFn | unreachable!\n    let parentCtor := getStructureCtor env parentStructName\n    let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs\n    for fieldName in getStructureFields env parentStructName do\n      match fieldMap.find? fieldName with\n      | some val => result := mkApp result val\n      | none => throwError \"failed to copied fields from parent structure{indentExpr parentType}\" -- TODO improve error message\n    return result\n\nprivate partial def mkToParentName (parentStructName : Name) (p : Name \u2192 Bool) : Name := do\n  let base := Name.mkSimple $ \"to\" ++ parentStructName.eraseMacroScopes.getString!\n  if p base then\n    base\n  else\n    let rec go (i : Nat) : Name :=\n      let curr := base.appendIndexAfter i\n      if p curr then curr else go (i+1)\n    go 1\n\nprivate partial def withParents (view : StructView) (k : Array StructFieldInfo \u2192 Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 #[] #[]\nwhere\n  go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM \u03b1 := do\n    if h : i < view.parents.size then\n      let parentStx := view.parents.get \u27e8i, h\u27e9\n      withRef parentStx do\n      let parentType \u2190 Term.elabType parentStx\n      let parentStructName \u2190 getStructureName parentType\n      if let some existingFieldName \u2190 findExistingField? infos parentStructName then\n        if structureDiamondWarning.get (\u2190 getOptions) then\n          logWarning s!\"field '{existingFieldName}' from '{parentStructName}' has already been declared\"\n        copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType)\n        -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure`\n      else\n        let env \u2190 getEnv\n        let subfieldNames := getStructureFieldsFlattened env parentStructName\n        let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n\n        let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default\n        withLocalDecl toParentName binfo parentType fun parentFVar =>\n          let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject }\n          processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents\n    else\n      k infos copiedParents\n\nprivate def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr \u00d7 Option Expr) := do\n  Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do\n    match view.type? with\n    | none         =>\n      match view.value? with\n      | none        => return (none, none)\n      | some valStx =>\n        Term.synthesizeSyntheticMVarsNoPostponing\n        let params \u2190 Term.addAutoBoundImplicits params\n        let value \u2190 Term.elabTerm valStx none\n        let value \u2190 mkLambdaFVars params value\n        return (none, value)\n    | some typeStx =>\n      let type \u2190 Term.elabType typeStx\n      Term.synthesizeSyntheticMVarsNoPostponing\n      let params \u2190 Term.addAutoBoundImplicits params\n      match view.value? with\n      | none        =>\n        let type  \u2190 mkForallFVars params type\n        return (type, none)\n      | some valStx =>\n        let value \u2190 Term.elabTermEnsuringType valStx type\n        Term.synthesizeSyntheticMVarsNoPostponing\n        let type  \u2190 mkForallFVars params type\n        let value \u2190 mkLambdaFVars params value\n        return (type, value)\n\nprivate partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 {} infos\nwhere\n  go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM \u03b1 := do\n    if h : i < views.size then\n      let view := views.get \u27e8i, h\u27e9\n      withRef view.ref do\n      match findFieldInfo? infos view.name with\n      | none      =>\n        let (type?, value?) \u2190 elabFieldTypeValue view\n        match type?, value? with\n        | none,      none => throwError \"invalid field, type expected\"\n        | some type, _    =>\n          withLocalDecl view.name view.binderInfo type fun fieldFVar =>\n            let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?,\n                                      kind := StructFieldKind.newField, inferMod := view.inferMod }\n            go (i+1) defaultValsOverridden infos\n        | none, some value =>\n          let type \u2190 inferType value\n          withLocalDecl view.name view.binderInfo type fun fieldFVar =>\n            let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value,\n                                      kind := StructFieldKind.newField, inferMod := view.inferMod }\n            go (i+1) defaultValsOverridden infos\n      | some info =>\n        let updateDefaultValue (fromParent : Bool) : TermElabM \u03b1 := do\n          match view.value? with\n          | none       => throwError \"field '{view.name}' has been declared in parent structure\"\n          | some valStx =>\n            if let some type := view.type? then\n              throwErrorAt type \"omit field '{view.name}' type to set default value\"\n            else\n              if defaultValsOverridden.contains info.name then\n                throwError \"field '{view.name}' new default value has already been set\"\n              let defaultValsOverridden := defaultValsOverridden.insert info.name\n              let mut valStx := valStx\n              if view.binders.getArgs.size > 0 then\n                valStx \u2190 `(fun $(view.binders.getArgs)* => $valStx:term)\n              let fvarType \u2190 inferType info.fvar\n              let value \u2190 Term.elabTermEnsuringType valStx fvarType\n              let infos := updateFieldInfoVal infos info.name value\n              go (i+1) defaultValsOverridden infos\n        match info.kind with\n        | StructFieldKind.newField    => throwError \"field '{view.name}' has already been declared\"\n        | StructFieldKind.subobject   => throwError \"unexpected subobject field reference\" -- improve error message\n        | StructFieldKind.copiedField => updateDefaultValue false\n        | StructFieldKind.fromParent  => updateDefaultValue true\n    else\n      k infos\n\nprivate def getResultUniverse (type : Expr) : TermElabM Level := do\n  let type \u2190 whnf type\n  match type with\n  | Expr.sort u _ => pure u\n  | _             => throwError \"unexpected structure resulting type\"\n\nprivate def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do\n  params.forM fun p => do\n    let type \u2190 inferType p\n    Term.collectUsedFVars type\n  fieldInfos.forM fun info => do\n    let fvarType \u2190 inferType info.fvar\n    Term.collectUsedFVars fvarType\n    match info.value? with\n    | none       => pure ()\n    | some value => Term.collectUsedFVars value\n\nprivate def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed params fieldInfos).run {}\n  Term.removeUnused scopeVars used\n\nprivate def withUsed {\u03b1} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr \u2192 TermElabM \u03b1)\n    : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnused scopeVars params fieldInfos\n  withLCtx lctx localInsts <| k vars\n\nprivate def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do\n  let type \u2190 inferType fvar\n  discard <| Term.levelMVarToParam' type\n\nprivate def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit :=\n  fvars.forM levelMVarToParamFVar\n\nprivate def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : StateRefT Nat TermElabM (Array StructFieldInfo) := do\n  levelMVarToParamFVars scopeVars\n  levelMVarToParamFVars params\n  fieldInfos.mapM fun info => do\n    levelMVarToParamFVar info.fvar\n    match info.value? with\n    | none       => pure info\n    | some value =>\n      let value \u2190 Term.levelMVarToParam' value\n      pure { info with value? := value }\n\nprivate def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) :=\n  (levelMVarToParamAux scopeVars params fieldInfos).run' 1\n\nprivate partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do\n  fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do\n    let type \u2190 inferType info.fvar\n    let u \u2190 getLevel type\n    let u \u2190 instantiateLevelMVars u\n    accLevelAtCtor u r rOffset us\n\nprivate def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do\n  let r \u2190 getResultUniverse type\n  let rOffset : Nat   := r.getOffset\n  let r       : Level := r.getLevelOffset\n  match r with\n  | Level.mvar mvarId _ =>\n    let us \u2190 collectUniversesFromFields r rOffset fieldInfos\n    let rNew := mkResultUniverse us rOffset\n    assignLevelMVar mvarId rNew\n    instantiateMVars type\n  | _ => throwError \"failed to compute resulting universe level of structure, provide universe explicitly\"\n\nprivate def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do\n  let type \u2190 inferType fvar\n  let type \u2190 instantiateMVars type\n  return collectLevelParams s type\n\nprivate def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State :=\n  fvars.foldlM collectLevelParamsInFVar s\n\nprivate def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : TermElabM (Array Name) := do\n  let s := collectLevelParams {} structType\n  let s \u2190 collectLevelParamsInFVars scopeVars s\n  let s \u2190 collectLevelParamsInFVars params s\n  let s \u2190 fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar\n  return s.params\n\nprivate def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat \u2192 Expr \u2192 TermElabM Expr\n  | 0,   type => pure type\n  | i+1, type => do\n    let info := fieldInfos[i]\n    let decl \u2190 Term.getFVarLocalDecl! info.fvar\n    let type \u2190 instantiateMVars type\n    let type := type.abstract #[info.fvar]\n    match info.kind with\n    | StructFieldKind.fromParent =>\n      let val := decl.value\n      addCtorFields fieldInfos i (type.instantiate1 val)\n    | _  =>\n      addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type)\n\nprivate def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor :=\n  withRef view.ref do\n  let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params\n  let type \u2190 addCtorFields fieldInfos fieldInfos.size type\n  let type \u2190 mkForallFVars params type\n  let type \u2190 instantiateMVars type\n  let type := type.inferImplicit params.size !view.ctor.inferMod\n  -- trace[Meta.debug] \"ctor type {type}\"\n  pure { name := view.ctor.declName, type }\n\n@[extern \"lean_mk_projections\"]\nprivate constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment\n\nprivate def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do\n  let env \u2190 getEnv\n  match mkProjections env structName projs isClass with\n  | Except.ok env   => setEnv env\n  | Except.error ex => throwKernelException ex\n\nprivate def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do\n  let fields \u2190 infos.filterMapM fun info => do\n      if info.kind == StructFieldKind.fromParent then\n        return none\n      else\n        return some {\n          fieldName  := info.name\n          projFn     := info.declName\n          inferMod   := info.inferMod\n          binderInfo := (\u2190 getFVarLocalDecl info.fvar).binderInfo\n          subobject? :=\n            if info.kind == StructFieldKind.subobject then\n              match (\u2190 getEnv).find? info.declName with\n              | some (ConstantInfo.defnInfo val) =>\n                match val.type.getForallBody.getAppFn with\n                | Expr.const parentName .. => some parentName\n                | _ => panic! \"ill-formed structure\"\n              | _ => panic! \"ill-formed environment\"\n            else\n              none\n        }\n  modifyEnv fun env => Lean.registerStructure env { structName, fields }\n\nprivate def mkAuxConstructions (declName : Name) : TermElabM Unit := do\n  let env \u2190 getEnv\n  let hasUnit := env.contains `PUnit\n  let hasEq   := env.contains `Eq\n  let hasHEq  := env.contains `HEq\n  mkRecOn declName\n  if hasUnit then mkCasesOn declName\n  if hasUnit && hasEq && hasHEq then mkNoConfusion declName\n\nprivate def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name \u00d7 Expr \u00d7 Expr)) : TermElabM Unit := do\n  let localInsts \u2190 getLocalInstances\n  withLCtx lctx localInsts do\n    defaultAuxDecls.forM fun (declName, type, value) => do\n      let value \u2190 instantiateMVars value\n      if value.hasExprMVar then\n        throwError \"invalid default value for field, it contains metavariables{indentExpr value}\"\n      /- The identity function is used as \"marker\". -/\n      let value \u2190 mkId value\n      discard <| mkAuxDefinition declName type value (zeta := true)\n      setReducibleAttribute declName\n\nprivate partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do\n  let env \u2190 getEnv\n  let structName := view.declName\n  let sourceFieldNames := getStructureFieldsFlattened env structName\n  let structType \u2190 mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params\n  let Expr.const parentStructName us _ \u2190 pure parentType.getAppFn | unreachable!\n  let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default\n  withLocalDecl `self binfo structType fun source => do\n    let declType \u2190 instantiateMVars (\u2190 mkForallFVars params (\u2190 mkForallFVars #[source] parentType))\n    let declType := declType.inferImplicit params.size true\n    let rec copyFields (parentType : Expr) : MetaM Expr := do\n      let Expr.const parentStructName us _ \u2190 pure parentType.getAppFn | unreachable!\n      let parentCtor := getStructureCtor env parentStructName\n      let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs\n      for fieldName in getStructureFields env parentStructName do\n        if sourceFieldNames.contains fieldName then\n          let fieldVal \u2190 mkProjection source fieldName\n          result := mkApp result fieldVal\n        else\n          -- fieldInfo must be a field of `parentStructName`\n          let some fieldInfo \u2190 getFieldInfo? env parentStructName fieldName | unreachable!\n          if fieldInfo.subobject?.isNone then throwError \"failed to build coercion to parent structure\"\n          let resultType \u2190 whnfD (\u2190 inferType result)\n          unless resultType.isForall do throwError \"failed to build coercion to parent structure, unexpect type{indentExpr resultType}\"\n          let fieldVal \u2190 copyFields resultType.bindingDomain!\n          result := mkApp result fieldVal\n      return result\n    let declVal \u2190 instantiateMVars (\u2190 mkLambdaFVars params (\u2190 mkLambdaFVars #[source] (\u2190 copyFields parentType)))\n    let declName := structName ++ mkToParentName (\u2190 getStructureName parentType) fun n => !env.contains (structName ++ n)\n    addAndCompile <| Declaration.defnDecl {\n      name        := declName\n      levelParams := levelParams\n      type        := declType\n      value       := declVal\n      hints       := ReducibilityHints.abbrev\n      safety      := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe\n    }\n    if binfo.isInstImplicit then\n      addInstance declName AttributeKind.global (eval_prio default)\n    else\n      setReducibleAttribute declName\n\nprivate def elabStructureView (view : StructView) : TermElabM Unit := do\n  view.fields.forM fun field => do\n    if field.declName == view.ctor.declName then\n      throwErrorAt field.ref \"invalid field name '{field.name}', it is equal to structure constructor name\"\n    addAuxDeclarationRanges field.declName field.ref field.ref\n  let numExplicitParams := view.params.size\n  let type \u2190 Term.elabType view.type\n  unless validStructType type do throwErrorAt view.type \"expected Type\"\n  withRef view.ref do\n  withParents view fun fieldInfos copiedParents => do\n  withFields view.fields fieldInfos fun fieldInfos => do\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let u \u2190 getResultUniverse type\n    let inferLevel \u2190 shouldInferResultUniverse u\n    withUsed view.scopeVars view.params fieldInfos fun scopeVars => do\n      let numParams := scopeVars.size + numExplicitParams\n      let fieldInfos \u2190 levelMVarToParam scopeVars view.params fieldInfos\n      let type \u2190 withRef view.ref do\n        if inferLevel then\n          updateResultingUniverse fieldInfos type\n        else\n          checkResultingUniverse (\u2190 getResultUniverse type)\n          pure type\n      trace[Elab.structure] \"type: {type}\"\n      let usedLevelNames \u2190 collectLevelParamsInStructure type scopeVars view.params fieldInfos\n      match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with\n      | Except.error msg      => withRef view.ref <| throwError msg\n      | Except.ok levelParams =>\n        let params := scopeVars ++ view.params\n        let ctor \u2190 mkCtor view levelParams params fieldInfos\n        let type \u2190 mkForallFVars params type\n        let type \u2190 instantiateMVars type\n        let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType }\n        let decl    := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe\n        Term.ensureNoUnassignedMVars decl\n        addDecl decl\n        let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) =>\n          { declName := info.declName, inferMod := info.inferMod : ProjectionInfo }\n        addProjections view.declName projInfos view.isClass\n        registerStructure view.declName fieldInfos\n        mkAuxConstructions view.declName\n        let instParents \u2190 fieldInfos.filterM fun info => do\n          let decl \u2190 Term.getFVarLocalDecl! info.fvar\n          pure (info.isSubobject && decl.binderInfo.isInstImplicit)\n        let projInstances := instParents.toList.map fun info => info.declName\n        Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking\n        projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default)\n        copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent\n        let lctx \u2190 getLCtx\n        let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome\n        let defaultAuxDecls \u2190 fieldsWithDefault.mapM fun info => do\n          let type \u2190 inferType info.fvar\n          pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!)\n        /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary \"default value\" declarations\n           The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/\n        let lctx :=\n          params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) =>\n            lctx.setBinderInfo p.fvarId! BinderInfo.implicit\n        let lctx :=\n          fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) =>\n            if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating \"default value\" auxiliary functions\n            else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default\n        addDefaults lctx defaultAuxDecls\n\n/-\nleading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType >> \" := \" >> optional structCtor >> structFields >> optDeriving\n\nwhere\ndef \u00abextends\u00bb := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef typeSpec := leading_parser \" : \" >> termParser\ndef optType : Parser := optional typeSpec\n\ndef structFields         := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)\ndef structCtor           := leading_parser try (declModifiers >> ident >> optional inferMod >> \" :: \")\n\n-/\ndef elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  checkValidInductiveModifier modifiers\n  let isClass   := stx[0].getKind == ``Parser.Command.classTk\n  let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers\n  let declId    := stx[1]\n  let params    := stx[2].getArgs\n  let exts      := stx[3]\n  let parents   := if exts.isNone then #[] else exts[0][1].getSepArgs\n  let optType   := stx[4]\n  let derivingClassViews \u2190 getOptDerivingClasses stx[6]\n  let type \u2190 if optType.isNone then `(Sort _) else pure optType[0][1]\n  let declName \u2190\n    runTermElabM none fun scopeVars => do\n      let scopeLevelNames \u2190 Term.getLevelNames\n      let \u27e8name, declName, allUserLevelNames\u27e9 \u2190 Elab.expandDeclId (\u2190 getCurrNamespace) scopeLevelNames declId modifiers\n      addDeclarationRanges declName stx\n      Term.withDeclName declName do\n        let ctor \u2190 expandCtor stx modifiers declName\n        let fields \u2190 expandFields stx modifiers declName\n        Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <|\n          Term.elabBinders params fun params => do\n            Term.synthesizeSyntheticMVarsNoPostponing\n            let params \u2190 Term.addAutoBoundImplicits params\n            let allUserLevelNames \u2190 Term.getLevelNames\n            elabStructureView {\n              ref := stx\n              modifiers\n              scopeLevelNames\n              allUserLevelNames\n              declName\n              isClass\n              scopeVars\n              params\n              parents\n              type\n              ctor\n              fields\n            }\n            unless isClass do\n              mkSizeOfInstances declName\n              mkInjectiveTheorems declName\n            return declName\n  derivingClassViews.forM fun view => view.applyHandlers #[declName]\n\nbuiltin_initialize registerTraceClass `Elab.structure\n\nend Lean.Elab.Command\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/Elab/Structure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.03789242921002376, "lm_q1q2_score": 0.009286866510556139}}
{"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  \u27e8\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    ]\u27e9\n/-(\u27e8mk_time _ 0,sorry\u27e9-/\n\n#eval ser\n\ndef v1 := mk_displacement3d_timefixed_at_time ser (mk_time ts (0.4:\u211a)) 1 1 1\n#check v1\n\ndef v2 := mk_displacement3d_timefixed_at_time ser (mk_time ts (0.5:\u211a)) 1 1 1\n#check v2\n\n#check v1 +\u1d65 v2\ndef s1 : series_index ts ser := \u27e8mk_time ts (0.5:\u211a)\u27e9\ndef s2 : series_index ts ser := \u27e8mk_time ts (2.5:\u211a)\u27e9\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 {\u03b1 : Sort u} {\u03b2 : Sort v} [s : setoid \u03b1] (f : \u03b1 \u2192 \u03b2) : (\u2200 a b, a \u2248 b \u2192 f a = f b) \u2192 quotient s \u2192 \u03b2 :=\nquot.lift f\n-/\ndef lift_si : series_index ts ser \u2192 time ts :=\n  \u03bbsi, (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 \u27e6s1\u27e7=\u27e6s2\u27e7\n#eval (lift_ \u27e6s1\u27e7).coord\n#eval (lift_ \u27e6s2\u27e7).coord\n#eval (lift_ \u27e6s1\u27e7)\n#eval (lift_ \u27e6s2\u27e7)\n\ndef pt111 : (lift_ \u27e6s1\u27e7).coord = (lift_ \u27e6s2\u27e7).coord := begin\n  simp *,\nend\n\ndef pttt : (lift_ \u27e6s1\u27e7).coord = (lift_ \u27e6s2\u27e7).coord := begin\n  unfold lift_,\nend\n\n\ndef lift_2 : \u2115 \u2192 \u211a :=\n  \u03bbsi, si\n\ninstance : setoid \u2115 := \u27e8 \n  (\u03bbn1 n2, n1=n2), sorry\n\u27e9\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 := \u27e61\u27e7\ndef ss22 := \u27e61\u27e7\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": "/-\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.Basic\n\nnamespace Lean.Elab.Term\n\n/-\n  Set isDefEq configuration for the elaborator.\n  Note that we enable all approximations but `quasiPatternApprox`\n\n  In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.\n  The example:\n  ```\n  def ex : StateT \u03b4 (StateT \u03c3 Id) \u03c3 :=\n  monadLift (get : StateT \u03c3 Id \u03c3)\n  ```\n  demonstrates why it produces counterintuitive behavior.\n  We have the `Monad-lift` application:\n  ```\n  @monadLift ?m ?n ?c ?\u03b1 (get : StateT \u03c3 id \u03c3) : ?n ?\u03b1\n  ```\n  It produces the following unification problem when we process the expected type:\n  ```\n  ?n ?\u03b1 =?= StateT \u03b4 (StateT \u03c3 id) \u03c3\n  ==> (approximate using first-order unification)\n  ?n := StateT \u03b4 (StateT \u03c3 id)\n  ?\u03b1 := \u03c3\n  ```\n  Then, we need to solve:\n  ```\n  ?m ?\u03b1 =?= StateT \u03c3 id \u03c3\n  ==> instantiate metavars\n  ?m \u03c3 =?= StateT \u03c3 id \u03c3\n  ==> (approximate since it is a quasi-pattern unification constraint)\n  ?m := fun \u03c3 => StateT \u03c3 id \u03c3\n  ```\n  Note that the constraint is not a Milner pattern because \u03c3 is in\n  the local context of `?m`. We are ignoring the other possible solutions:\n  ```\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3' id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3'\n  ```\n\n  We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).\n\n  If we had use first-order unification, then we would have produced\n  the right answer: `?m := StateT \u03c3 id`\n\n  Haskell would work on this example since it always uses\n  first-order unification.\n-/\ndef setElabConfig (cfg : Meta.Config) : Meta.Config :=\n  { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }\n\n\nend Lean.Elab.Term\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/Elab/Config.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561049052975445, "lm_q2_score": 0.0592102478360753, "lm_q1q2_score": 0.009243010131094674}}
{"text": "import Preloaded Solution\n\ntheorem task_1 : TASK_1 := one_plus_one_is_three\n#print axioms task_1\n\ntheorem task_2 : TASK_2 := two_plus_two_is_five\n#print axioms task_2", "meta": {"author": "DonaldKellett", "repo": "CW-Lean3-Examples", "sha": "9dd81b7c9327b029c859f37534232ab556f69699", "save_path": "github-repos/lean/DonaldKellett-CW-Lean3-Examples", "path": "github-repos/lean/DonaldKellett-CW-Lean3-Examples/CW-Lean3-Examples-9dd81b7c9327b029c859f37534232ab556f69699/kata5/SolutionTest.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557748798522984, "lm_q2_score": 0.025957354325043223, "lm_q1q2_score": 0.00923497461627579}}
{"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Sebastian Ullrich, Mac Malone\n-/\nimport Lake.Util.Git\nimport Lake.Util.Sugar\nimport Lake.Config.Package\nimport Lake.Config.Workspace\nimport Lake.Load.Config\nimport Lake.Build.Actions\n\nnamespace Lake\nopen Git System\n\n/-- The default module of an executable in `std` package. -/\ndef defaultExeRoot : Name := `Main\n\n/-- `elan` toolchain file name -/\ndef toolchainFileName : FilePath :=\n  \"lean-toolchain\"\n\ndef gitignoreContents :=\ns!\"/{defaultBuildDir}\n/{defaultPackagesDir}/*\n\"\n\ndef libFileContents :=\n  s!\"def hello := \\\"world\\\"\"\n\ndef mainFileName : FilePath :=\n  s!\"{defaultExeRoot}.lean\"\n\ndef mainFileContents (libRoot : String) :=\ns!\"import {libRoot}\n\ndef main : IO Unit :=\n  IO.println s!\\\"Hello, \\{hello}!\\\"\n\"\n\ndef exeFileContents :=\ns!\"def main : IO Unit :=\n  IO.println s!\\\"Hello, world!\\\"\n\"\n\ndef stdConfigFileContents (pkgName libRoot : String) :=\ns!\"import Lake\nopen Lake DSL\n\npackage {pkgName} \\{\n  -- add package configuration options here\n}\n\nlean_lib {libRoot} \\{\n  -- add library configuration options here\n}\n\n@[default_target]\nlean_exe {pkgName} \\{\n  root := `Main\n}\n\"\n\ndef exeConfigFileContents (pkgName exeRoot : String) :=\ns!\"import Lake\nopen Lake DSL\n\npackage {pkgName} \\{\n  -- add package configuration options here\n}\n\n@[default_target]\nlean_exe {exeRoot} \\{\n  -- add executable configuration options here\n}\n\"\n\ndef libConfigFileContents (pkgName libRoot : String) :=\ns!\"import Lake\nopen Lake DSL\n\npackage {pkgName} \\{\n  -- add package configuration options here\n}\n\n@[default_target]\nlean_lib {libRoot} \\{\n  -- add library configuration options here\n}\n\"\n\ndef mathConfigFileContents (pkgName libRoot : String) :=\ns!\"import Lake\nopen Lake DSL\n\npackage {pkgName} \\{\n  -- add any package configuration options here\n}\n\nrequire mathlib from git\n  \\\"https://github.com/leanprover-community/mathlib4.git\\\"\n\n@[default_target]\nlean_lib {libRoot} \\{\n  -- add any library configuration options here\n}\n\"\n\ndef mathToolchainUrl : String :=\n  \"https://raw.githubusercontent.com/leanprover-community/mathlib4/master/lean-toolchain\"\n\n/-- The options for the template argument to `initPkg`. -/\ninductive InitTemplate\n| std | exe | lib | math\nderiving Repr, DecidableEq\n\ninstance : Inhabited InitTemplate := \u27e8.std\u27e9\n\ndef InitTemplate.parse? : String \u2192 Option InitTemplate\n| \"std\" => some .std\n| \"exe\" => some .exe\n| \"lib\" => some .lib\n| \"math\" => some .math\n| _ => none\n\ndef InitTemplate.configFileContents (pkgName root : String) : InitTemplate \u2192 String\n| .std => stdConfigFileContents pkgName root\n| .lib => libConfigFileContents pkgName root\n| .exe => exeConfigFileContents pkgName root\n| .math => mathConfigFileContents pkgName root\n\ndef escapeName! : Name \u2192 String\n| .anonymous        => \"[anonymous]\"\n| .str .anonymous s => escape s\n| .str n s          => escapeName! n ++ \".\" ++ escape s\n| _                 => unreachable!\nwhere\n  escape s :=  Lean.idBeginEscape.toString ++ s ++ Lean.idEndEscape.toString\n\n/-- Initialize a new Lake package in the given directory with the given name. -/\ndef initPkg (dir : FilePath) (name : String) (tmp : InitTemplate) : LogIO PUnit := do\n  let pkgName := name.decapitalize.toName\n\n  -- determine the name to use for the root\n  -- use upper camel case unless the specific module name already exists\n  let (root, rootFile, rootExists) \u2190 do\n    let root := name.toName\n    let rootFile := Lean.modToFilePath dir root \"lean\"\n    let rootExists \u2190 rootFile.pathExists\n    if tmp = .exe || rootExists then\n      pure (root, rootFile, rootExists)\n    else\n      let root := toUpperCamelCase root\n      let rootFile := Lean.modToFilePath dir root \"lean\"\n      pure (root, rootFile, \u2190 rootFile.pathExists)\n\n  -- write default configuration file\n  let configFile := dir / defaultConfigFile\n  if (\u2190 configFile.pathExists) then\n    error  \"package already initialized\"\n  let rootNameStr := escapeName! root\n  let contents := tmp.configFileContents (escapeName! pkgName) rootNameStr\n  IO.FS.writeFile configFile contents\n\n  -- write example code if the files do not already exist\n  if tmp = .exe then\n    unless (\u2190 rootFile.pathExists) do\n      IO.FS.writeFile rootFile exeFileContents\n  else\n    if !rootExists then\n      IO.FS.createDirAll rootFile.parent.get!\n      IO.FS.writeFile rootFile libFileContents\n    if tmp = .std then\n      let mainFile := dir / mainFileName\n      unless (\u2190 mainFile.pathExists) do\n        IO.FS.writeFile mainFile <| mainFileContents rootNameStr\n\n  -- write Lean's toolchain to file (if it has one) for `elan`\n  if Lean.toolchain \u2260 \"\" then\n    if tmp = .math then\n      download \"lean-toolchain\" mathToolchainUrl (dir / toolchainFileName)\n    else\n      IO.FS.writeFile (dir / toolchainFileName) <| Lean.toolchain ++ \"\\n\"\n\n  -- update `.gitignore` with additional entries for Lake\n  let h \u2190 IO.FS.Handle.mk (dir / \".gitignore\") IO.FS.Mode.append\n  h.putStr gitignoreContents\n\n  -- initialize a `.git` repository if none already\n  unless (\u2190 FilePath.isDir <| dir / \".git\") do\n    let repo := GitRepo.mk dir\n    try\n      repo.quietInit\n      unless upstreamBranch = \"master\" do\n        repo.checkoutBranch upstreamBranch\n    else\n      logWarning \"failed to initialize git repository\"\n\ndef init (pkgName : String) (tmp : InitTemplate) : LogIO PUnit :=\n  initPkg \".\" pkgName tmp\n\ndef new (pkgName : String) (tmp : InitTemplate) : LogIO PUnit := do\n  let dirName := pkgName.map fun chr => if chr == '.' then '-' else chr\n  IO.FS.createDir dirName\n  initPkg dirName pkgName tmp\n", "meta": {"author": "leanprover", "repo": "lake", "sha": "6de8ee8817c3e6bb01f9f48c2f22f7979e4ac526", "save_path": "github-repos/lean/leanprover-lake", "path": "github-repos/lean/leanprover-lake/lake-6de8ee8817c3e6bb01f9f48c2f22f7979e4ac526/Lake/CLI/Init.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238004477370332, "lm_q2_score": 0.056652419335261495, "lm_q1q2_score": 0.009199222388198378}}
{"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, --\u22d9 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 \u27e8_,_,_\u27e9,\n    { dsimp [functor.empty_condition],\n      split,\n      { rintros _ _ _,\n        ext \u27e8\u27e9 },\n      { intros x,\n        refine \u27e8\u27e8Profinite.empty.elim _\u27e9, _\u27e9,\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 (\u03bb e, e.fst.down t) at h, exact h },\n        { apply_fun (\u03bb e, e.snd.down t) at h, exact h } },\n      { rintros \u27e8a,b\u27e9,\n        refine \u27e8\u27e8_\u27e9,_\u27e9,\n        dsimp,\n        refine Profinite.sum.desc _ _ a.down b.down,\n        ext, refl, refl } },\n    { intros X B \u03c0 hh,\n      split,\n      { intros x y h,\n        dsimp [yoneda, functor.map_to_equalizer] at h,\n        ext t,\n        obtain \u27e8t,rfl\u27e9 := hh t,\n        apply_fun (\u03bb e, e.val.down t) at h,\n        exact h },\n      { rintros \u27e8\u27e8t\u27e9,ht\u27e9,\n        refine \u27e8\u27e8Profinite.descend \u03c0 t hh _\u27e9, _\u27e9,\n        dsimp at ht,\n        apply_fun (\u03bb 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.\u03c0_descend } }\n  end } .\n\n@[simps]\ndef Profinite_to_Condensed : Profinite \u2964 CondensedSet :=\n{ obj := \u03bb X, X.to_Condensed,\n  map := \u03bb X Y f, \u27e8whisker_right (yoneda.map f) _\u27e9,\n  map_id' := \u03bb X, by { ext1, dsimp, erw [yoneda.map_id, whisker_right_id], refl },\n  map_comp' := \u03bb 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 \u22d9 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 \u22d9 yoneda'.obj T)).out 0 5,\n    refine \u27e8_,_,_\u27e9,\n    { dsimp [functor.empty_condition],\n      split,\n      { rintros _ _ _,\n        ext \u27e8\u27e9 },\n      { intros x,\n        dsimp,\n        refine \u27e8\u27e8\u27e8\u03bb x, x.elim, by continuity\u27e9\u27e9, _\u27e9,\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 (\u03bb e, e.fst.down t) at h, exact h },\n        { apply_fun (\u03bb e, e.snd.down t) at h, exact h } },\n      { rintros \u27e8a,b\u27e9,\n        dsimp [ulift_functor] at a b,\n        refine \u27e8\u27e8\u27e8_,_\u27e9\u27e9,_\u27e9,\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 \u27e8a.down.continuous, b.down.continuous\u27e9 },\n        { ext, refl, refl } } },\n    { intros X B \u03c0 hh,\n      split,\n      { intros x y h,\n        dsimp [yoneda, functor.map_to_equalizer] at h,\n        ext t,\n        obtain \u27e8t,rfl\u27e9 := hh t,\n        apply_fun (\u03bb e, e.val.down t) at h,\n        exact h },\n      { rintros \u27e8\u27e8t\u27e9,ht\u27e9,\n        refine \u27e8\u27e8Profinite.descend_to_Top \u03c0 t hh _\u27e9, _\u27e9,\n        dsimp at ht,\n        apply_fun (\u03bb 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.\u03c0_descend_to_Top,\n      } }\n  end }\n\n@[simps]\ndef Top_to_Condensed : Top \u2964 CondensedSet :=\n{ obj := \u03bb X, X.to_Condensed,\n  map := \u03bb X Y f, \u27e8whisker_left _ $ whisker_right (yoneda.map f) _\u27e9,\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 \u2964 C :=\nSheaf_to_presheaf _ _ \u22d9 (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} \u2964 Type (u+1) :=\nSheaf_to_presheaf _ _ \u22d9 (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 \u2964 _) \u22d9\n    ((whiskering_left _ _ _).obj ExtrDisc_to_Profinite.op)) \u22d9\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 \u27e8S\u27e9 _\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} \u2964 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 \u00d7 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 \u00d7 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 \u2264 o j l \u2194 i \u2264 j \u2227 k \u2264 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 \u2264 j . hom_tac) : i \u27f6 j := hom_of_le hij\n\nlemma hom_ext {i j : snake_diagram} (f g : i \u27f6 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 \u2192 fin 3 \u2192 C)\nparameters (f0 : F 0 0 \u27f6 F 0 1) (g0 : F 0 1 \u27f6 F 0 2)\nparameters (a0 : F 0 0 \u27f6 F 1 0) (b0 : F 0 1 \u27f6 F 1 1) (c0 : F 0 2 \u27f6 F 1 2)\nparameters (f1 : F 1 0 \u27f6 F 1 1) (g1 : F 1 1 \u27f6 F 1 2)\nparameters (a1 : F 1 0 \u27f6 F 2 0) (b1 : F 1 1 \u27f6 F 2 1) (c1 : F 1 2 \u27f6 F 2 2)\nparameters (f2 : F 2 0 \u27f6 F 2 1) (g2 : F 2 1 \u27f6 F 2 2)\nparameters (a2 : F 2 0 \u27f6 F 3 0) (b2 : F 2 1 \u27f6 F 3 1) (c2 : F 2 2 \u27f6 F 3 2)\nparameters (f3 : F 3 0 \u27f6 F 3 1) (g3 : F 3 1 \u27f6 F 3 2)\nparameters (sq00 : a0 \u226b f1 = f0 \u226b b0) (sq01 : b0 \u226b g1 = g0 \u226b c0)\nparameters (sq10 : a1 \u226b f2 = f1 \u226b b1) (sq11 : b1 \u226b g2 = g1 \u226b c1)\nparameters (sq20 : a2 \u226b f3 = f2 \u226b b2) (sq21 : b2 \u226b g3 = g2 \u226b c2)\n\nnamespace mk_functor\n\ndef col : \u03a0 (j : fin 3), fin 4 \u2964 C\n| \u27e80,h\u27e9 := fin4_functor_mk (flip F 0) a0 a1 a2\n| \u27e81,h\u27e9 := fin4_functor_mk (flip F 1) b0 b1 b2\n| \u27e82,h\u27e9 := fin4_functor_mk (flip F 2) c0 c1 c2\n| \u27e8j+3,h\u27e9 := by { exfalso, revert h, dec_trivial }\n\ndef row : \u03a0 (i : fin 4), fin 3 \u2964 C\n| \u27e80,h\u27e9 := fin3_functor_mk (F 0) f0 g0\n| \u27e81,h\u27e9 := fin3_functor_mk (F 1) f1 g1\n| \u27e82,h\u27e9 := fin3_functor_mk (F 2) f2 g2\n| \u27e83,h\u27e9 := fin3_functor_mk (F 3) f3 g3\n| \u27e8j+4,h\u27e9 := 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 \u2264 y) : F x.1 x.2 \u27f6 F y.1 y.2 :=\neq_to_hom (by rw [row_obj]) \u226b\n(row x.1).map h.2.hom \u226b eq_to_hom (by rw [row_obj, col_obj]) \u226b\n(col y.2).map h.1.hom \u226b eq_to_hom (by rw [col_obj])\n\nlemma map'_id (x : snake_diagram) : map' x x le_rfl = \ud835\udfd9 _ :=\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 \u2264 j) (hkl : k \u2264 l) : Prop :=\n(col k).map hij.hom \u226b eq_to_hom (by rw [row_obj, col_obj]) \u226b\n(row j).map hkl.hom =\neq_to_hom (by rw [col_obj]; refl) \u226b\nmap' (o i k) (o j l) \u27e8hij, hkl\u27e9 \u226b 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 \u2264 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 [\u2190 category.assoc, eq_comm],\n  convert category.comp_id _,\nend\n\nlemma square_commutes_col (i j : fin 4) (k : fin 3) (hij : i \u2264 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 \u2264 j) (hjk : j \u2264 k) (hlm : l \u2264 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 \u22a2,\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 \u22a2,\n  let \u03c6 : _ := _, let \u03c8 : _ := _,\n  calc _ = \u03c6 \u226b h2.lhs : _\n     ... = \u03c6 \u226b h2.rhs : by { congr' 1, }\n     ... = h1.lhs \u226b \u03c8 : _\n     ... = h1.rhs \u226b \u03c8 : by { congr' 1, }\n     ... = _ : _,\n  swap 5, { exact functor.map _ hij.hom },\n  swap 4, { refine (eq_to_hom _ \u226b _ \u226b 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 [\u03c6, \u03c8, eq.lhs_def, eq.rhs_def] },\n  { simp only [\u2190 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, \u2190 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 \u2264 j) (hlm : l \u2264 m) (hmn : m \u2264 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 \u22a2,\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 \u22a2,\n  let \u03c6 : _ := _, let \u03c8 : _ := _,\n  calc _ = h1.lhs \u226b \u03c6 : _\n     ... = h1.rhs \u226b \u03c6 : by { congr' 1, }\n     ... = \u03c8 \u226b h2.lhs : _\n     ... = \u03c8 \u226b h2.rhs : by { congr' 1, }\n     ... = _ : _,\n  swap 5, { exact functor.map _ hmn.hom },\n  swap 4, { refine (eq_to_hom _ \u226b _ \u226b 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 [\u03c6, \u03c8, eq.lhs_def, eq.rhs_def] },\n  { simp only [category.assoc, \u2190 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, \u2190 functor.map_comp_assoc],\n    refl, },\nend\n\nlemma col_comp_row (i j : fin 4) (k l : fin 3) (hij : i \u2264 j) (hkl : k \u2264 l) :\n  (col k).map hij.hom \u226b eq_to_hom (by rw [row_obj, col_obj]) \u226b\n  (row j).map hkl.hom =\n  eq_to_hom (by rw [col_obj]; refl) \u226b\n  map' (o i k) (o j l) \u27e8hij, hkl\u27e9 \u226b 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 [\u2190 fin.coe_fin_le, fin.coe_mk, fin.coe_mk] at hij hkl,\n  obtain \u27e8j, rfl\u27e9 := nat.exists_eq_add_of_le hij,\n  obtain \u27e8l, rfl\u27e9 := 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 \u27e8i, hi\u27e9 \u27e8i+j, _\u27e9 _ _ _ _ _ hkl' _ _,\n  { refine lt_trans _ hj, exact lt_add_one (i+j) },\n  { simp only [\u2190 fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n  { simp only [\u2190 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 _ _ \u27e8k, hk\u27e9 \u27e8k+l, _\u27e9 _ _ _ _ _ _,\n  { refine lt_trans _ hl, exact lt_add_one (k+l) },\n  { simp only [\u2190 fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n  { simp only [\u2190 fin.coe_fin_le, fin.coe_mk], exact (lt_add_one (k+l)).le },\n  { refine IHl _ _ _, simp only [\u2190 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 [\u2190 fin.coe_fin_lt, fin.coe_mk], refine nat.lt_of_succ_lt_succ hj, },\n  { rw [\u2190 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 \u2264 y) (hyz : y \u2264 z) :\n  map' x y hxy \u226b 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, \u2190 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 \u2964 C :=\n{ obj := function.uncurry F,\n  map := \u03bb 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' := \u03bb 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' := \u03bb 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 {\ud835\udc9c \u212c : Type*} [category \ud835\udc9c] [category \u212c]\nvariables (A : fin 3 \u2192 \ud835\udc9c) (F : fin 4 \u2192 \ud835\udc9c \u2964 \u212c)\nvariables (f : A 0 \u27f6 A 1) (g : A 1 \u27f6 A 2) (\u03b1 : F 0 \u27f6 F 1) (\u03b2 : F 1 \u27f6 F 2) (\u03b3 : F 2 \u27f6 F 3)\n\ndef mk_functor' : snake_diagram \u2964 \u212c :=\nmk_functor (\u03bb i, (F i).obj \u2218 A)\n  /- FA\u2080\u2080 -/  ((F 0).map f)  /- FA\u2080\u2081 -/  ((F 0).map g)  /- FA\u2080\u2082 -/\n  (\u03b1.app _)                  (\u03b1.app _)                  (\u03b1.app _)\n  /- FA\u2081\u2080 -/  ((F 1).map f)  /- FA\u2081\u2081 -/  ((F 1).map g)  /- FA\u2081\u2082 -/\n  (\u03b2.app _)                  (\u03b2.app _)                  (\u03b2.app _)\n  /- FA\u2082\u2080 -/  ((F 2).map f)  /- FA\u2082\u2081 -/  ((F 2).map g)  /- FA\u2082\u2082 -/\n  (\u03b3.app _)                  (\u03b3.app _)                  (\u03b3.app _)\n  /- FA\u2083\u2080 -/  ((F 3).map f)  /- FA\u2083\u2081 -/  ((F 3).map g)  /- FA\u2083\u2082 -/\n(\u03b1.naturality _).symm (\u03b1.naturality _).symm\n(\u03b2.naturality _).symm (\u03b2.naturality _).symm\n(\u03b3.naturality _).symm (\u03b3.naturality _).symm\n\nend\n\nsection\n\nvariables {\ud835\udc9c \u212c \ud835\udc9e : Type*} [category \ud835\udc9c] [category \u212c] [category \ud835\udc9e]\nvariables (A : fin 3 \u2192 \ud835\udc9c \u2964 \u212c) (F : fin 4 \u2192 \u212c \u2964 \ud835\udc9e)\nvariables (f : A 0 \u27f6 A 1) (g : A 1 \u27f6 A 2) (\u03b1 : F 0 \u27f6 F 1) (\u03b2 : F 1 \u27f6 F 2) (\u03b3 : F 2 \u27f6 F 3)\n\ndef mk_functor'' : \ud835\udc9c \u2192 snake_diagram \u2964 \ud835\udc9e :=\n\u03bb x, mk_functor' ![(A 0).obj x, (A 1).obj x, (A 2).obj x] F (f.app x) (g.app x) \u03b1 \u03b2 \u03b3\n\nend\n\nsection\n\nvariables {\ud835\udc9c : Type*} [category \ud835\udc9c] [abelian \ud835\udc9c]\n\n-- move (ang generalize) this\nlemma exact_kernel_\u03b9_self {A B : \ud835\udc9c} (f : A \u27f6 B) : exact (kernel.\u03b9 f) f :=\nby { rw abelian.exact_iff, tidy } -- why do we not have abelian.exact_kernel?\n\n-- move this\nlemma exact_self_cokernel_\u03c0 {A B : \ud835\udc9c} (f : A \u27f6 B) : exact f (cokernel.\u03c0 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 \ud835\udc9c) (f : A \u27f6 B) :\n  snake_diagram \u2964 \ud835\udc9c :=\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.\u03b9 _)                         (kernel.\u03b9 _)                         (kernel.\u03b9 _)\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.\u03c0 _)                       (cokernel.\u03c0 _)                       (cokernel.\u03c0 _)\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_\u03b9] }) (by { delta kernel.map, rw [kernel.lift_\u03b9] })\nf.sq1 f.sq2\n(by { delta cokernel.map, rw [cokernel.\u03c0_desc] }) (by { delta cokernel.map, rw [cokernel.\u03c0_desc] })\n.\n\nend\n\nend snake_diagram\n\nopen snake_diagram (o hom)\n\nexample (i : fin 4) : o i 0 \u27f6 o i 1 := hom (i,0) (i,1)\n\nlocal notation x `\u27f6[`D`]` y := D.map (hom x y)\n\nsection definitions\n\nvariables (\ud835\udc9c : Type u) [category.{v} \ud835\udc9c] [has_images \ud835\udc9c] [has_zero_morphisms \ud835\udc9c] [has_kernels \ud835\udc9c]\n\nvariables {\ud835\udc9c}\n\nstructure is_snake_input (D : snake_diagram \u2964 \ud835\udc9c) : Prop :=\n(row_exact\u2081 : exact ((1,0) \u27f6[D] (1,1)) ((1,1) \u27f6[D] (1,2)))\n(row_exact\u2082 : exact ((2,0) \u27f6[D] (2,1)) ((2,1) \u27f6[D] (2,2)))\n(col_exact\u2081 : \u2200 j, exact ((0,j) \u27f6[D] (1,j)) ((1,j) \u27f6[D] (2,j)))\n(col_exact\u2082 : \u2200 j, exact ((1,j) \u27f6[D] (2,j)) ((2,j) \u27f6[D] (3,j)))\n(col_mono : \u2200 j, mono ((0,j) \u27f6[D] (1,j)))\n(col_epi  : \u2200 j, epi ((2,j) \u27f6[D] (3,j)))\n(row_mono : mono ((2,0) \u27f6[D] (2,1)))\n(row_epi  : epi ((1,1) \u27f6[D] (1,2)))\n\nnamespace is_snake_input\n\nvariables {D : snake_diagram \u2964 \ud835\udc9c}\n\n@[nolint unused_arguments]\nlemma map_eq (hD : is_snake_input D) {x y : snake_diagram} (f g : x \u27f6 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 \u27f6 x) : D.map f = \ud835\udfd9 _ :=\nby rw [snake_diagram.hom_ext f (\ud835\udfd9 x), D.map_id]\n\nlemma hom_eq_zero\u2081 (hD : is_snake_input D) {x y : snake_diagram} (f : x \u27f6 y)\n  (h : x.1 < 2 \u2227 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\u2080 h\u2081, rcases f with \u27e8\u27e8\u27e8hik, hjl\u27e9\u27e9\u27e9,\n  dsimp at h\u2080 h\u2081 hik hjl,\n  let f\u2081 := hom (i,j) (i+1,j),\n  let f\u2082 := hom (i+1,j) (i+2,j),\n  let f\u2083 := hom (i+2,j) (k,l),\n  calc D.map _\n      = D.map ((f\u2081 \u226b f\u2082) \u226b f\u2083)             : hD.map_eq _ _\n  ... = ((D.map f\u2081) \u226b D.map f\u2082) \u226b D.map f\u2083 : by simp only [D.map_comp]\n  ... = 0 \u226b D.map f\u2083                        : _\n  ... = 0                                   : zero_comp,\n  congr' 1,\n  obtain (rfl|rfl) : i = 0 \u2228 i = 1, { dec_trivial! },\n  { exact (hD.col_exact\u2081 j).w },\n  { exact (hD.col_exact\u2082 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 {\ud835\udc9c : Type*} [category \ud835\udc9c] [abelian \ud835\udc9c]\n  (A B : short_exact_sequence \ud835\udc9c) (f : A \u27f6 B) :\n  is_snake_input (snake_diagram.mk_of_short_exact_sequence_hom A B f) :=\n{ row_exact\u2081 := by { aux_simp, exact A.exact' },\n  row_exact\u2082 := by { aux_simp, exact B.exact' },\n  col_exact\u2081 := \u03bb j, by { fin_cases j; aux_simp, all_goals { apply exact_kernel_\u03b9_self, } },\n  col_exact\u2082 := \u03bb j, by { fin_cases j; aux_simp, all_goals { apply exact_self_cokernel_\u03c0 } },\n  col_mono := \u03bb j, by { fin_cases j; aux_simp, all_goals { apply_instance } },\n  col_epi := \u03bb 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 {\ud835\udc9c : Type u} [category.{v} \ud835\udc9c] [abelian \ud835\udc9c]\nvariables {D : snake_diagram \u2964 \ud835\udc9c}\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 : \ud835\udc9c} (f : P \u27f6 Q) : function.injective f \u2194 mono f :=\n\u27e8\u03bb h, mono_of_zero_of_map_zero _ (zero_of_map_zero _ h),\n  by introsI h; apply pseudo_injective_of_mono\u27e9\n\nlemma surjective_iff_epi {P Q : \ud835\udc9c} (f : P \u27f6 Q) : function.surjective f \u2194 epi f :=\n\u27e8epi_of_pseudo_surjective _, by introI h; apply pseudo_surjective_of_epi\u27e9\n\nlemma exists_of_exact {P Q R : \ud835\udc9c} {f : P \u27f6 Q} {g : Q \u27f6 R} (e : exact f g) (q) (hq : g q = 0) :\n  \u2203 p, f p = q :=\n(pseudo_exact_of_exact e).2 _ hq\n\nlemma eq_zero_of_exact {P Q R : \ud835\udc9c} {f : P \u27f6 Q} {g : Q \u27f6 R} (e : exact f g) (p) : g (f p) = 0 :=\n(pseudo_exact_of_exact e).1 _\n\n@[simp]\nlemma kernel_\u03b9_apply {P Q : \ud835\udc9c} (f : P \u27f6 Q) (a) : f (kernel.\u03b9 f a) = 0 :=\nbegin\n  rw \u2190 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_\u03b9_eq_zero {P Q : \ud835\udc9c} (f : P \u27f6 Q) (q) : kernel.\u03b9 f q = 0 \u2194 q = 0 :=\nbegin\n  split,\n  { intro h,\n    apply_fun kernel.\u03b9 f,\n    simp [h],\n    rw injective_iff_mono,\n    apply_instance },\n  { intro h,\n    simp [h] },\nend\n\n@[simp]\nlemma cokernel_\u03c0_apply {P Q : \ud835\udc9c} (f : P \u27f6 Q) (a) : cokernel.\u03c0 f (f a) = 0 :=\nbegin\n  rw \u2190 abelian.pseudoelement.comp_apply,\n  simp,\nend\n\nlemma exists_of_cokernel_\u03c0_eq_zero {P Q : \ud835\udc9c} (f : P \u27f6 Q) (a) :\n  cokernel.\u03c0 f a = 0 \u2192 \u2203 b, f b = a :=\nbegin\n  intro h,\n  apply exists_of_exact _ _ h,\n  apply snake_diagram.exact_self_cokernel_\u03c0,\nend\n\nlemma cokernel_\u03c0_surjective {P Q : \ud835\udc9c} (f : P \u27f6 Q) : function.surjective (cokernel.\u03c0 f) :=\nbegin\n  rw surjective_iff_epi,\n  apply_instance,\nend\n\n--move\nlemma exact_is_iso_iff {P Q Q' R : \ud835\udc9c} (f : P \u27f6 Q) (g : Q' \u27f6 R) (e : Q \u27f6 Q') [is_iso e] :\n  exact f (e \u226b g) \u2194 exact (f \u226b e) g :=\nbegin\n  let E := as_iso e,\n  change exact f (E.hom \u226b g) \u2194 exact (f \u226b E.hom) g,\n  conv_rhs { rw (show g = E.inv \u226b E.hom \u226b g, by simp) },\n  rw exact_comp_hom_inv_comp_iff\nend\n\n--lemma exact_comp_is_iso {P Q R R' : \ud835\udc9c} (f : P \u27f6 Q) (g : Q \u27f6 R) (e : R \u27f6 R') [is_iso e] :\n--  exact f (g \u226b e) \u2194 exact f g := exact_comp_iso\n\nend move_me\n\nlemma row_exact\u2080 (hD : is_snake_input D) : exact ((0,0) \u27f6[D] (0,1)) ((0,1) \u27f6[D] (0,2)) :=\nbegin\n  refine exact_of_pseudo_exact _ _ \u27e8\u03bb a, _, _\u27e9,\n  { apply_fun ((0,2) \u27f6[D] (1,2)),\n    swap, { rw injective_iff_mono, exact hD.col_mono _ },\n    simp_rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, abelian.pseudoelement.apply_zero],\n    change D.map (hom (0,0) (1,0) \u226b hom (1,0) (1,1) \u226b hom (1,1) (1,2)) a = 0,\n    simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact hD.row_exact\u2081] },\n  { intros b hb,\n    apply_fun ((0,2) \u27f6[D] (1,2)) at hb,\n    simp_rw [\u2190 abelian.pseudoelement.comp_apply,\n      \u2190 D.map_comp, abelian.pseudoelement.apply_zero] at hb,\n    change D.map (hom (0,1) (1,1) \u226b 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) \u27f6[D] (1,1)) b,\n    change ((1,1) \u27f6[D] (1,2)) b' = 0 at hb,\n    obtain \u27e8c,hc\u27e9 := exists_of_exact hD.row_exact\u2081 b' hb,\n    have hcz : ((1,0) \u27f6[D] (2,0)) c = 0,\n    { apply_fun ((2,0) \u27f6[D] (2,1)),\n      swap, { rw injective_iff_mono, apply hD.row_mono },\n      simp_rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, abelian.pseudoelement.apply_zero],\n      change D.map (hom (1,0) (1,1) \u226b 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\u2081 },\n    obtain \u27e8d,hd\u27e9 := exists_of_exact (hD.col_exact\u2081 _) c hcz,\n    use d,\n    apply_fun ((0,1) \u27f6[D] (1,1)),\n    swap, { rw injective_iff_mono, exact hD.col_mono _ },\n    dsimp only [b'] at hc,\n    rw [\u2190 hc, \u2190 hd],\n    simp_rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp],\n    refl }\nend\n\nlemma row_exact\u2083 (hD : is_snake_input D) : exact ((3,0) \u27f6[D] (3,1)) ((3,1) \u27f6[D] (3,2)) :=\nbegin\n  refine exact_of_pseudo_exact _ _ \u27e8\u03bb a, _,\u03bb b hb, _\u27e9,\n  { obtain \u27e8b, hb\u27e9 := (surjective_iff_epi ((2,0) \u27f6[D] (3,0))).2 (hD.col_epi 0) a,\n    rw [\u2190 hb, \u2190 abelian.pseudoelement.comp_apply, \u2190 abelian.pseudoelement.comp_apply,\n      \u2190 D.map_comp, \u2190 D.map_comp, map_eq hD ((hom (2, 0) (3, 0)) \u226b (hom _ (3, 1)) \u226b\n      (hom _ (3, 2))) ((hom (2, 0) (2, 1)) \u226b (hom _ (2, 2)) \u226b (hom _ _)), \u2190 category.assoc,\n      D.map_comp _ (hom (2, 2) (3, 2)), D.map_comp, hD.row_exact\u2082.w, zero_comp, zero_apply] },\n  { set f\u2081 := hom (2, 1) (2, 2),\n    set f\u2082 := hom (2, 2) (3, 2),\n    set f\u2083 := hom (1, 1) (2, 1),\n    set f\u2084 := hom (2, 0) (3, 0),\n    set f\u2085 := hom (3, 0) (3, 1),\n    obtain \u27e8c, hc\u27e9 := (surjective_iff_epi ((2,1) \u27f6[D] (3,1))).2 (hD.col_epi 1) b,\n    let d := D.map f\u2081 c,\n    have hd : D.map f\u2082 d = 0,\n    { rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD ((hom (2, 1) (2, 2)) \u226b\n      (hom _ (3, 2))) ((hom (2, 1) (3, 1)) \u226b (hom _ (3, 2))), D.map_comp,\n      abelian.pseudoelement.comp_apply, hc, hb] },\n    obtain \u27e8e, he\u27e9 := exists_of_exact (hD.col_exact\u2082 2) d hd,\n    obtain \u27e8f, hf\u27e9 := (surjective_iff_epi ((1,1) \u27f6[D] (1,2))).2 hD.row_epi e,\n    have hfzero : ((2,1) \u27f6[D] (3,1)) ((D.map f\u2083) f) = 0,\n    { rw [\u2190 abelian.pseudoelement.comp_apply, (hD.col_exact\u2082 1).w, zero_apply] },\n    have hdiff : D.map f\u2081 c = D.map f\u2081 (D.map f\u2083 f),\n    { rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD ((hom (1, 1) (2, 1)) \u226b\n      (hom _ (2, 2))) ((hom (1, 1) (1, 2)) \u226b (hom _ (2, 2))), D.map_comp,\n      abelian.pseudoelement.comp_apply, hf, he] },\n    obtain \u27e8g, \u27e8hg\u2081, hg\u2082\u27e9\u27e9 := sub_of_eq_image _ _ _ hdiff,\n    obtain \u27e8h, hh\u27e9 := exists_of_exact hD.row_exact\u2082 g hg\u2081,\n    use D.map f\u2084 h,\n    rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n      ((hom (2, 0) (3, 0)) \u226b (hom _ (3, 1))) ((hom _ (2, 1)) \u226b (hom _ _)), D.map_comp,\n      abelian.pseudoelement.comp_apply, hh, hg\u2082 _ ((2,1) \u27f6[D] (3,1)) hfzero, hc] }\nend\n\nlemma row_exact (hD : is_snake_input D) (i : fin 4) :\n  exact ((i,0) \u27f6[D] (i,1)) ((i,1) \u27f6[D] (i,2)) :=\nby { fin_cases i, exacts [hD.row_exact\u2080, hD.row_exact\u2081, hD.row_exact\u2082, hD.row_exact\u2083] }\n\nlemma hom_eq_zero\u2082 (hD : is_snake_input D) {x y : snake_diagram} (f : x \u27f6 y)\n  (h : x.2 = 0 \u2227 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 \u27e8\u27e8\u27e8hik, hjl\u27e9\u27e9\u27e9,\n  dsimp at h hik hjl, rcases h with \u27e8rfl, rfl\u27e9,\n  let f\u2081 := hom (i,0) (i,1),\n  let f\u2082 := hom (i,1) (i,2),\n  let f\u2083 := hom (i,2) (k,2),\n  calc D.map _\n      = D.map ((f\u2081 \u226b f\u2082) \u226b f\u2083)             : hD.map_eq _ _\n  ... = ((D.map f\u2081) \u226b D.map f\u2082) \u226b D.map f\u2083 : 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\u2081_to_row\u2082 (hD : is_snake_input D) :\n  (kernel.\u03b9 ((1,0) \u27f6[D] (1,1))) \u226b ((1,0) \u27f6[D] (2,0)) = 0 :=\nbegin\n  refine zero_morphism_ext _ (\u03bb a, (injective_iff_mono ((2,0) \u27f6[D] (2,1))).2 hD.row_mono _),\n  rw [apply_zero, \u2190 abelian.pseudoelement.comp_apply, category.assoc,\n    abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n    ((hom (1, 0) (2, 0)) \u226b (hom _ (2, 1))) ((hom _ (1, 1)) \u226b (hom _ _)), D.map_comp,\n    abelian.pseudoelement.comp_apply, kernel_\u03b9_apply, apply_zero]\nend\n\ndef ker_row\u2081_to_top_left (hD : is_snake_input D) : kernel ((1,0) \u27f6[D] (1,1)) \u27f6 D.obj (0, 0) :=\nby { letI := hD.col_mono 0, exact (limits.kernel.lift _ _ (ker_row\u2081_to_row\u2082 hD)) \u226b\n    (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact\u2081 0)).2)) \u226b\n    inv (abelian.factor_thru_image ((0,0) \u27f6[D] (1,0))) }\n\nlemma ker_row\u2081_to_top_left_mono (hD : is_snake_input D) : mono (ker_row\u2081_to_top_left hD) :=\nbegin\n  suffices : mono ((limits.kernel.lift _ _ (ker_row\u2081_to_row\u2082 hD)) \u226b\n    (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact\u2081 0)).2))),\n  { letI := this, exact mono_comp _ _, },\n  exact mono_comp _ _\nend\n\nlemma ker_row\u2081_to_top_left_comp_eq_\u03b9 (hD : is_snake_input D) : ker_row\u2081_to_top_left hD \u226b\n  ((0,0) \u27f6[D] (1,0)) = kernel.\u03b9 ((1,0) \u27f6[D] (1,1)) :=\nbegin\n  letI := hD.col_mono 0,\n  have : inv (abelian.factor_thru_image ((0,0) \u27f6[D] (1,0))) \u226b ((0,0) \u27f6[D] (1,0)) =\n    category_theory.abelian.image.\u03b9 _ := by simp,\n  rw [ker_row\u2081_to_top_left, category.assoc, category.assoc, this],\n  simp\nend\n\nlemma long_row\u2080_exact (hD : is_snake_input D) :\n  exact (ker_row\u2081_to_top_left hD) ((0,0) \u27f6[D] (0,1)) :=\nbegin\n  refine abelian.pseudoelement.exact_of_pseudo_exact _ _ \u27e8\u03bb a, _, \u03bb a ha, _\u27e9,\n  { refine (injective_iff_mono _).2 (hD.col_mono _) _,\n    rw [apply_zero, \u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n      ((hom (0, 0) (0, 1)) \u226b (hom _ (1, 1))) ((hom _ (1, 0)) \u226b (hom _ _)), D.map_comp,\n      \u2190 abelian.pseudoelement.comp_apply, \u2190 category.assoc, ker_row\u2081_to_top_left_comp_eq_\u03b9 hD,\n      abelian.pseudoelement.comp_apply, kernel_\u03b9_apply] },\n  { let b := ((0,0) \u27f6[D] (1,0)) a,\n    have hb : ((1,0) \u27f6[D] (1,1)) b = 0,\n    { rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n        ((hom (0, 0) (1, 0)) \u226b (hom _ (1, 1))) ((hom _ (0, 1)) \u226b (hom _ _)), D.map_comp,\n        abelian.pseudoelement.comp_apply, ha, apply_zero] },\n    obtain \u27e8c, hc\u27e9 := exists_of_exact category_theory.exact_kernel_\u03b9 _ hb,\n    refine \u27e8c, (injective_iff_mono _).2 (hD.col_mono _) _\u27e9,\n    rw [\u2190 abelian.pseudoelement.comp_apply, ker_row\u2081_to_top_left_comp_eq_\u03b9 hD, hc] }\nend\n\nlemma row\u2081_middle_to_coker_row\u2082_eq_zero (hD : is_snake_input D) :\n   ((1,1) \u27f6[D] (1,2)) \u226b ((1,2) \u27f6[D] (2,2)) \u226b (limits.cokernel.\u03c0 ((2,1) \u27f6[D] (2,2))) = 0 :=\nbegin\n  refine zero_morphism_ext _ (\u03bb a, _),\n  rw [\u2190 category.assoc, abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n    ((hom (1, 1) (1, 2)) \u226b (hom _ (2, 2))) ((hom _ (2, 1)) \u226b (hom _ _)), D.map_comp,\n    \u2190 abelian.pseudoelement.comp_apply],\n  simp,\nend\n\nlemma row\u2081_to_coker_row\u2082_eq_zero (hD : is_snake_input D) :\n  ((1,2) \u27f6[D] (2,2)) \u226b (limits.cokernel.\u03c0 ((2,1) \u27f6[D] (2,2))) = 0 :=\nbegin\n  letI := hD.row_epi,\n  have := row\u2081_middle_to_coker_row\u2082_eq_zero hD,\n  rw [\u2190 limits.comp_zero] at this,\n  exact (cancel_epi _).1 this\nend\n\nlemma ker_col\u2082_to_coker_row\u2082_eq_zero (hD : is_snake_input D) :\n  kernel.\u03b9 ((2,2) \u27f6[D] (3,2)) \u226b (limits.cokernel.\u03c0 ((1,2) \u27f6[D] (2,2))) = 0 :=\nbegin\n  refine zero_morphism_ext _ (\u03bb a, _),\n  obtain \u27e8c, hc\u27e9 := exists_of_exact (hD.col_exact\u2082 2) (kernel.\u03b9 (_ \u27f6[D] _) a) (kernel_\u03b9_apply _ _),\n  rw [abelian.pseudoelement.comp_apply, \u2190 hc, cokernel_\u03c0_apply]\nend\n\ndef bottom_right_to_coker_row\u2082 (hD : is_snake_input D) :\n  D.obj (3, 2) \u27f6 cokernel ((2,1) \u27f6[D] (2,2)) :=\nby { letI := hD.col_epi 2, exact\n  (inv (abelian.factor_thru_coimage ((2,2) \u27f6[D] (3,2)))) \u226b\n  (limits.cokernel.desc _ _ (ker_col\u2082_to_coker_row\u2082_eq_zero hD)) \u226b\n  (limits.cokernel.desc _ _ (row\u2081_to_coker_row\u2082_eq_zero hD)) }\n\nlemma bottom_right_to_coker_row\u2082_epi (hD : is_snake_input D) : epi (bottom_right_to_coker_row\u2082 hD) :=\nbegin\n  suffices : epi ((limits.cokernel.desc _ _ (ker_col\u2082_to_coker_row\u2082_eq_zero hD)) \u226b\n    (limits.cokernel.desc _ _ (row\u2081_to_coker_row\u2082_eq_zero hD))),\n  { letI := this, exact epi_comp _ _ },\n  exact epi_comp _ _,\nend\n\nlemma bottom_right_to_coker_row\u2082_comp_eq_\u03c0 (hD : is_snake_input D) : ((2,2) \u27f6[D] (3,2))  \u226b\n  bottom_right_to_coker_row\u2082 hD = cokernel.\u03c0 ((2,1) \u27f6[D] (2,2)) :=\nbegin\n  letI := hD.col_epi 2,\n  have : ((2,2) \u27f6[D] (3,2)) \u226b inv (abelian.factor_thru_coimage ((2,2) \u27f6[D] (3,2))) =\n    category_theory.abelian.coimage.\u03c0 _ := by simp,\n  rw [bottom_right_to_coker_row\u2082, \u2190 category.assoc, \u2190 category.assoc, this],\n  simp\nend\n\nlemma long_row\u2083_exact (hD : is_snake_input D) :\n  exact ((3,1) \u27f6[D] (3,2)) (bottom_right_to_coker_row\u2082 hD) :=\nbegin\n  refine abelian.pseudoelement.exact_of_pseudo_exact _ _ \u27e8\u03bb a, _, \u03bb a ha, _\u27e9,\n  { letI := hD.col_epi 1,\n    obtain \u27e8b, hb\u27e9 := abelian.pseudoelement.pseudo_surjective_of_epi ((2,1) \u27f6[D] (3,1)) a,\n    rw [\u2190 hb, \u2190 abelian.pseudoelement.comp_apply, \u2190 abelian.pseudoelement.comp_apply,\n      \u2190 category.assoc, \u2190 D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) \u226b (hom _ (3, 2)))\n      ((hom _ (2, 2)) \u226b (hom _ _)), D.map_comp, category.assoc,\n      bottom_right_to_coker_row\u2082_comp_eq_\u03c0 hD, (snake_diagram.exact_self_cokernel_\u03c0 _).w,\n      zero_apply], },\n  { letI := hD.col_epi 2,\n    obtain \u27e8b, hb\u27e9 := abelian.pseudoelement.pseudo_surjective_of_epi ((2,2) \u27f6[D] (3,2)) a,\n    rw [\u2190 hb, \u2190 abelian.pseudoelement.comp_apply, bottom_right_to_coker_row\u2082_comp_eq_\u03c0 hD] at ha,\n    obtain \u27e8c, hc\u27e9 := exists_of_exact (abelian.exact_cokernel _) _ ha,\n    refine \u27e8((2,1) \u27f6[D] (3,1)) c, _\u27e9,\n    rw [\u2190 hb, \u2190 hc, \u2190 abelian.pseudoelement.comp_apply, \u2190 abelian.pseudoelement.comp_apply,\n      \u2190 D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) \u226b (hom _ (3, 2))) ((hom _ (2, 2)) \u226b (hom _ _)),\n      D.map_comp] }\nend\n\nend long_snake\n\nexample (hD : is_snake_input D) (f : (o 1 0) \u27f6 (o 2 2)) : D.map f = 0 := hD.hom_eq_zero\u2082 f\n\nsection delta\n\nvariable (hD : is_snake_input D)\ninclude hD\n\ndef to_top_right_kernel : D.obj (1,0) \u27f6 kernel ((1,1) \u27f6[D] (2,2)) :=\nkernel.lift _ (_ \u27f6[D] _)\nbegin\n  rw \u2190 D.map_comp,\n  change D.map (hom (1,0) (2,0) \u226b hom (2,0) (2,1) \u226b hom (2,1) (2,2)) = 0,\n  simp [hD.row_exact\u2082.1],\nend\n\ndef cokernel_to_top_right_kernel_to_right_kernel :\n  cokernel hD.to_top_right_kernel \u27f6 kernel ((1,2) \u27f6[D] (2,2)) :=\ncokernel.desc _ (kernel.lift _ (kernel.\u03b9 _ \u226b (_ \u27f6[D] _)) begin\n  rw [category.assoc, \u2190 D.map_comp],\n  have : hom (1,1) (1,2) \u226b 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.\u03b9 (D.map (hom (1, 2) (2, 2))),\n  swap, { rw injective_iff_mono, apply_instance },\n  simp [\u2190 abelian.pseudoelement.comp_apply, hD.row_exact\u2081.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 \u27e8b,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n  rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero at h,\n  simp [\u2190 abelian.pseudoelement.comp_apply, cokernel_to_top_right_kernel_to_right_kernel] at h,\n  simp [ abelian.pseudoelement.comp_apply] at h,\n  have : \u2203 c, ((1,0) \u27f6[D] (1,1)) c = kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) b,\n  { apply exists_of_exact _ _ h,\n    exact hD.row_exact\u2081 },\n  obtain \u27e8c,hc\u27e9 := this,\n  let f : cokernel hD.to_top_right_kernel \u27f6 cokernel ((1,0) \u27f6[D] (1,1)) :=\n    cokernel.desc _ _ _,\n  swap, { refine kernel.\u03b9 _ \u226b cokernel.\u03c0 _ },\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 \u27e8a,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n    simp [\u2190 abelian.pseudoelement.comp_apply] at ha,\n    simp [abelian.pseudoelement.comp_apply] at ha,\n    have : \u2203 c, ((1,0) \u27f6[D] (1,1)) c = kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) a,\n    { apply exists_of_exact _ _ ha,\n      apply snake_diagram.exact_self_cokernel_\u03c0, },\n    obtain \u27e8c,hc\u27e9 := this,\n    have : hD.to_top_right_kernel c = a,\n    { apply_fun kernel.\u03b9 ((1,1) \u27f6[D] (2,2)),\n      swap, { rw injective_iff_mono, apply_instance },\n      dsimp [to_top_right_kernel],\n      simp [\u2190 abelian.pseudoelement.comp_apply],\n      erw kernel.lift_\u03b9,\n      exact hc },\n    simp [\u2190 this] },\n  dsimp only [f],\n  simp [\u2190 abelian.pseudoelement.comp_apply, to_top_right_kernel],\n  simp [abelian.pseudoelement.comp_apply, \u2190 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.\u03b9 ((1,2) \u27f6[D] (2,2)) a,\n  obtain \u27e8b,hb\u27e9 : \u2203 b, ((1,1) \u27f6[D] (1,2)) b = a',\n  { suffices : function.surjective ((1,1) \u27f6[D] (1,2)), by apply this,\n    rw surjective_iff_epi,\n    apply hD.row_epi },\n  obtain \u27e8c,hc\u27e9 : \u2203 c, kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) c = b,\n  { have : exact (kernel.\u03b9 ((1,1) \u27f6[D] (2,2))) ((1,1) \u27f6[D] (2,2)) := exact_kernel_\u03b9,\n    apply exists_of_exact this,\n    rw [(show hom (1,1) (2,2) = hom (1,1) (1,2) \u226b 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.\u03c0 hD.to_top_right_kernel c,\n  apply_fun kernel.\u03b9 ((1,2) \u27f6[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 [\u2190 abelian.pseudoelement.comp_apply],\n  change _ = a',\n  rw \u2190 hb,\n  simp [\u2190 hb, abelian.pseudoelement.comp_apply, \u2190 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) \u27f6[D] (2,1)) \u27f6 D.obj (2,2) :=\ncokernel.desc _ (_ \u27f6[D] _)\nbegin\n  rw \u2190 D.map_comp,\n  change D.map (hom (1,0) (2,0) \u226b hom (2,0) (2,1) \u226b hom (2,1) (2,2)) = 0,\n  simp_rw D.map_comp,\n  simp [hD.row_exact\u2082.1],\nend\n\ndef left_cokernel_to_kernel_bottom_left_cokernel_to :\n  cokernel ((1,0) \u27f6[D] (2,0)) \u27f6 kernel hD.bottom_left_cokernel_to :=\nkernel.lift _ (cokernel.desc _ ((_ \u27f6[D] _) \u226b cokernel.\u03c0 _) begin\n  rw [\u2190 category.assoc, \u2190 D.map_comp],\n  have : hom (1,0) (2,0) \u226b 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 \u27e8b,rfl\u27e9 : \u2203 b, cokernel.\u03c0 ((1,0) \u27f6[D] (2,0)) b = a,\n  { have : function.surjective (cokernel.\u03c0 ((1,0) \u27f6[D] (2,0))),\n    by { rw surjective_iff_epi, apply_instance },\n    apply this },\n  simp [\u2190 abelian.pseudoelement.comp_apply, hD.row_exact\u2082.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 \u27e8a,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n  dsimp [left_cokernel_to_kernel_bottom_left_cokernel_to] at ha,\n  rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero at ha,\n  simp [\u2190 abelian.pseudoelement.comp_apply] at ha,\n  simp [abelian.pseudoelement.comp_apply] at ha,\n  obtain \u27e8c,hc\u27e9 : \u2203 c, ((1,0) \u27f6[D] (2,1)) c = ((2,0) \u27f6[D] (2,1)) a,\n  { apply exists_of_exact _ _ ha,\n    apply abelian.exact_cokernel, },\n  have : ((1,0) \u27f6[D] (2,0)) c = a,\n  { apply_fun ((2,0) \u27f6[D] (2,1)),\n    swap, { rw injective_iff_mono, apply hD.row_mono },\n    simpa only [\u2190 hc, \u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp] },\n  simp [\u2190 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.\u03b9 hD.bottom_left_cokernel_to a,\n  obtain \u27e8b,hb\u27e9 := cokernel_\u03c0_surjective _ a',\n  have : ((2,1) \u27f6[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 [\u2190 abelian.pseudoelement.comp_apply] using hb },\n  obtain \u27e8c,hc\u27e9 : \u2203 c, ((2,0) \u27f6[D] (2,1)) c = b,\n  { apply exists_of_exact _ _ this,\n    exact hD.row_exact\u2082 },\n  use cokernel.\u03c0 ((1,0) \u27f6[D] (2,0)) c,\n  apply_fun kernel.\u03b9 hD.bottom_left_cokernel_to,\n  swap, { rw injective_iff_mono, apply_instance },\n  change _ = a',\n  simp [\u2190 abelian.pseudoelement.comp_apply, \u2190 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 \u03b4_aux : cokernel hD.to_top_right_kernel \u27f6 kernel hD.bottom_left_cokernel_to :=\ncokernel.desc _ (kernel.lift _ (kernel.\u03b9 _ \u226b (_ \u27f6[D] _) \u226b cokernel.\u03c0 _) begin\n  dsimp only [bottom_left_cokernel_to],\n  simp,\n  rw \u2190 D.map_comp,\n  have : hom (1,1) (2,1) \u226b 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.\u03b9 hD.bottom_left_cokernel_to,\n  swap, { rw injective_iff_mono, apply_instance },\n  simp [\u2190 abelian.pseudoelement.comp_apply],\n  rw [\u2190 category.assoc, \u2190 D.map_comp],\n  have : hom (1,0) (1,1) \u226b 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) \u27f6 kernel ((1,2) \u27f6[D] (2,2)) :=\nkernel.lift _ (_ \u27f6[D] _) (hD.col_exact\u2081 _).1\n\ninstance : mono hD.to_kernel :=\nbegin\n  dsimp [to_kernel],\n  haveI : mono ((0,2) \u27f6[D] (1,2)) := hD.col_mono _,\n  apply_instance,\nend\n\ninstance : epi hD.to_kernel :=\nkernel.lift.epi (hD.col_exact\u2081 _)\n\ninstance : is_iso hD.to_kernel :=\nis_iso_of_mono_of_epi _\n\ndef cokernel_to : cokernel ((1,0) \u27f6[D] (2,0)) \u27f6 D.obj (3,0) :=\ncokernel.desc _ (_ \u27f6[D] _) (hD.col_exact\u2082 _).1\n\ninstance : mono hD.cokernel_to :=\nabelian.category_theory.limits.cokernel.desc.category_theory.mono _ _ (hD.col_exact\u2082 _)\n\ninstance : epi hD.cokernel_to :=\nbegin\n  dsimp [cokernel_to],\n  haveI : epi ((2,0) \u27f6[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 \u03b4 : D.obj (0,2) \u27f6 D.obj (3,0) :=\n  hD.to_kernel \u226b inv hD.cokernel_to_top_right_kernel_to_right_kernel \u226b  -- <-- this is an iso\n  hD.\u03b4_aux \u226b -- <- this is the key\n  inv hD.left_cokernel_to_kernel_bottom_left_cokernel_to \u226b hD.cokernel_to -- <-- this is an iso\n\ndef to_\u03b4_aux : D.obj (0,1) \u27f6 cokernel hD.to_top_right_kernel :=\nkernel.lift _ ((0,1) \u27f6[D] (1,1)) begin\n  rw [(show (hom (1,1) (2,2) = hom (1,1) (2,1) \u226b hom _ _), by refl), D.map_comp,\n    \u2190 category.assoc, (hD.col_exact\u2081 _).1],\n  simp,\nend \u226b cokernel.\u03c0 _\n\ndef from_\u03b4_aux : kernel hD.bottom_left_cokernel_to \u27f6 D.obj (3,1) :=\nkernel.\u03b9 _ \u226b cokernel.desc _ ((2,1) \u27f6[D] (3,1)) begin\n  rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) \u226b hom (1,1) (2,1), by refl),\n    D.map_comp, category.assoc, (hD.col_exact\u2082 _).w],\n  simp,\nend\n\ntheorem exact_to_\u03b4_aux : exact hD.to_\u03b4_aux hD.\u03b4_aux :=\nbegin\n  apply exact_of_pseudo_exact,\n  split,\n  { intros a,\n    dsimp [\u03b4_aux, to_\u03b4_aux],\n    rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero,\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc,\n      kernel.lift_\u03b9_assoc, category.assoc, kernel.lift_\u03b9],\n    simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact\u2081 _)] },\n  { intros b hb,\n    obtain \u27e8b,rfl\u27e9 := cokernel_\u03c0_surjective _ b,\n    dsimp [\u03b4_aux] at hb,\n    rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero at hb,\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc, kernel.lift_\u03b9] at hb,\n    simp only [abelian.pseudoelement.comp_apply] at hb,\n    let b' := kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) b,\n    obtain \u27e8c,hc\u27e9 := exists_of_cokernel_\u03c0_eq_zero _ _ hb, clear hb,\n    change _ = ((1,1) \u27f6[D] (2,1)) b' at hc,\n    rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) \u226b hom _ _, by refl), D.map_comp,\n      abelian.pseudoelement.comp_apply] at hc,\n    obtain \u27e8z,h1,h2\u27e9 := sub_of_eq_image _ _ _ hc.symm, clear hc,\n    specialize h2 _ ((1,1) \u27f6[D] (1,2)) (eq_zero_of_exact hD.row_exact\u2081 _),\n    obtain \u27e8w,hw\u27e9 : \u2203 w, ((0,1) \u27f6[D] (1,1)) w = z := exists_of_exact (hD.col_exact\u2081 _) _ h1,\n    clear h1,\n    use w,\n    dsimp only [b'] at h2,\n    dsimp only [to_\u03b4_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 [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc, category.assoc],\n    simp only [abelian.pseudoelement.comp_apply],\n    apply_fun kernel.\u03b9 ((1,2) \u27f6[D] (2,2)),\n    swap, { rw injective_iff_mono, apply_instance },\n    simp only [\u2190abelian.pseudoelement.comp_apply, kernel.lift_\u03b9_assoc,\n      category.assoc, kernel.lift_\u03b9],\n    simp only [abelian.pseudoelement.comp_apply],\n    rw [hw, h2] }\nend\n\ntheorem exact_from_\u03b4_aux : exact hD.\u03b4_aux hD.from_\u03b4_aux :=\nbegin\n  apply exact_of_pseudo_exact,\n  split,\n  { intros a,\n    dsimp [\u03b4_aux, from_\u03b4_aux],\n    obtain \u27e8a,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n    simp only [\u2190abelian.pseudoelement.comp_apply,\n      cokernel.\u03c0_desc, kernel.lift_\u03b9_assoc, category.assoc],\n    simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact\u2082 _)] },\n  { intros b hb,\n    let b' := kernel.\u03b9 hD.bottom_left_cokernel_to b,\n    obtain \u27e8c,hc\u27e9 := cokernel_\u03c0_surjective _ b',\n    simp only [from_\u03b4_aux, abelian.pseudoelement.comp_apply] at hb,\n    change cokernel.desc ((1,0) \u27f6[D] (2,1)) _ _ b' = 0 at hb,\n    rw \u2190 hc at hb,\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc] at hb,\n    obtain \u27e8d,hd\u27e9 : \u2203 d, ((1,1) \u27f6[D] (2,1)) d = c := exists_of_exact (hD.col_exact\u2082 _) _ hb,\n    obtain \u27e8e,he\u27e9 : \u2203 e, kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) e = d,\n    { apply exists_of_exact _ _ (_ : ((1,1) \u27f6[D] (2,2)) d = 0),\n      { apply exact_kernel_\u03b9 },\n      dsimp [b'] at hc,\n      apply_fun hD.bottom_left_cokernel_to at hc,\n      simp only [bottom_left_cokernel_to, \u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc] at hc,\n      rw [(show hom (1,1) (2,2) = hom (1,1) (2,1) \u226b 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.\u03b9 hD.bottom_left_cokernel_to b) = 0,\n      apply kernel_\u03b9_apply },\n    use cokernel.\u03c0 hD.to_top_right_kernel e,\n    apply_fun kernel.\u03b9 hD.bottom_left_cokernel_to,\n    swap, { rw injective_iff_mono, apply_instance },\n    change _ = b',\n    dsimp [\u03b4_aux],\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc, kernel.lift_\u03b9],\n    simp only [abelian.pseudoelement.comp_apply],\n    rw [he, hd, hc] }\nend\n\ntheorem exact_to_\u03b4 : exact ((0,1) \u27f6[D] (0,2)) hD.\u03b4 :=\nbegin\n  dsimp [\u03b4],\n  rw [exact_is_iso_iff, exact_is_iso_iff, exact_comp_iso],\n  convert hD.exact_to_\u03b4_aux using 1,\n  rw is_iso.comp_inv_eq,\n  dsimp [to_kernel, to_\u03b4_aux, cokernel_to_top_right_kernel_to_right_kernel],\n  ext,\n  simp only [cokernel.\u03c0_desc, kernel.lift_\u03b9_assoc, category.assoc, kernel.lift_\u03b9],\n  simpa only [\u2190 D.map_comp],\nend\n\ntheorem exact_from_\u03b4 : exact hD.\u03b4 ((3,0) \u27f6[D] (3,1)) :=\nbegin\n  dsimp [\u03b4],\n  rw [\u2190 category.assoc, \u2190 category.assoc, \u2190 exact_is_iso_iff, exact_iso_comp],\n  convert hD.exact_from_\u03b4_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_\u03b4_aux],\n  ext,\n  simp only [cokernel.\u03c0_desc, kernel.lift_\u03b9_assoc, cokernel.\u03c0_desc_assoc, category.assoc],\n  simpa only [\u2190 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) \u27f6[D] (2,2)) \u27f6 D.obj (0,2) :=\nkernel.lift _ (kernel.\u03b9 _ \u226b D.map (hom (1,1) (1,2))) begin\n  erw [category.assoc, \u2190 D.map_comp, kernel.condition],\nend \u226b 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) \u27f6[D] (1,2)) := hD.row_epi,\n  replace hh := pseudo_surjective_of_epi ((1,1) \u27f6[D] (1,2)),\n  apply epi_of_pseudo_surjective,\n  intros t,\n  obtain \u27e8s,hs\u27e9 := hh (kernel.\u03b9 ((1,2) \u27f6[D] (2,2)) t),\n  obtain \u27e8w,hw\u27e9 : \u2203 w, kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) w = s,\n  { have : exact (kernel.\u03b9 ((1,1) \u27f6[D] (2,2))) ((1,1) \u27f6[D] (2,2)) :=\n      exact_kernel_\u03b9,\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) \u226b hom (1,2) (2,2), by refl),\n      functor.map_comp, abelian.pseudoelement.comp_apply, hs,\n      \u2190 abelian.pseudoelement.comp_apply, kernel.condition,\n      abelian.pseudoelement.zero_apply] },\n  use w,\n  apply abelian.pseudoelement.pseudo_injective_of_mono\n    (kernel.\u03b9 ((1,2) \u27f6[D] (2,2))),\n  rw [\u2190 hs, \u2190 abelian.pseudoelement.comp_apply, kernel.lift_\u03b9,\n    abelian.pseudoelement.comp_apply, hw],\nend\n\ndef cokernel_to' : D.obj (3,0) \u27f6 cokernel ((1,0) \u27f6[D] (2,1)) :=\ninv hD.cokernel_to \u226b cokernel.desc _ (D.map (hom (2,0) (2,1)) \u226b cokernel.\u03c0 _) begin\n  erw [\u2190 category.assoc, \u2190 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 \u27e8b,rfl\u27e9 : \u2203 b, cokernel.\u03c0 ((1,0) \u27f6[D] (2,0)) b = a,\n  { apply abelian.pseudoelement.pseudo_surjective_of_epi },\n  rw [\u2190 abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc,\n    abelian.pseudoelement.comp_apply] at ha,\n  obtain \u27e8c,hc\u27e9 : \u2203 c, ((1,0) \u27f6[D] (2,1)) c = ((2,0) \u27f6[D] (2,1)) b,\n  { have : exact ((1,0) \u27f6[D] (2,1)) (cokernel.\u03c0 _) := abelian.exact_cokernel _,\n    replace this := pseudo_exact_of_exact this,\n    apply this.2,\n    exact ha },\n  have hc' : ((1,0) \u27f6[D] (2,0)) c = b,\n  { haveI : mono ((2,0) \u27f6[D] (2,1)) := hD.row_mono,\n    apply abelian.pseudoelement.pseudo_injective_of_mono ((2,0) \u27f6[D] (2,1)),\n    rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp],\n    exact hc },\n  rw [\u2190 hc', \u2190 abelian.pseudoelement.comp_apply, cokernel.condition,\n    abelian.pseudoelement.zero_apply],\nend\n\nlemma \u03b4_spec : hD.to_kernel' \u226b hD.\u03b4 \u226b hD.cokernel_to' =\n  kernel.\u03b9 _ \u226b D.map (hom (1,1) (2,1)) \u226b cokernel.\u03c0 _ :=\nbegin\n  dsimp only [is_snake_input.\u03b4 ,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.\u03b4_aux],\n  let t := _, change _ \u226b _ \u226b _ \u226b t = _,\n  have ht : t = kernel.\u03b9 _,\n  { dsimp [t],\n    rw is_iso.inv_comp_eq,\n    apply coequalizer.hom_ext,\n    simp only [cokernel.\u03c0_desc, category.assoc, kernel.lift_\u03b9, cokernel.\u03c0_desc_assoc] },\n  rw ht, clear ht, clear t,\n  let t := _, change t \u226b _ = _,\n  let s := _, change t \u226b s \u226b _ = _,\n  have hst : t \u226b s = cokernel.\u03c0 _,\n  { dsimp [s,t],\n    rw is_iso.comp_inv_eq,\n    apply equalizer.hom_ext,\n    simp only [cokernel.\u03c0_desc] },\n  rw reassoc_of hst, clear hst, clear s, clear t,\n  simp only [cokernel.\u03c0_desc_assoc, kernel.lift_\u03b9],\nend\n\nlemma eq_\u03b4_of_spec (e : D.obj (0,2) \u27f6 D.obj (3,0))\n  (he : hD.to_kernel' \u226b e \u226b hD.cokernel_to' = kernel.\u03b9 _ \u226b\n    D.map (hom (1,1) (2,1)) \u226b cokernel.\u03c0 _) :\n  e = hD.\u03b4 :=\nbegin\n  rw \u2190 cancel_mono hD.cokernel_to',\n  rw \u2190 cancel_epi hD.to_kernel',\n  rw [he, \u03b4_spec],\nend\n\nend delta_spec\n\nlocal attribute [instance] limits.has_zero_object.has_zero\n\nlemma exact_zero_to_ker_row\u2081_to_top_left (hD : is_snake_input D) :\n  exact (0 : 0 \u27f6 kernel ((1,0) \u27f6[D] (1,1))) hD.ker_row\u2081_to_top_left :=\nbegin\n  haveI : mono hD.ker_row\u2081_to_top_left := ker_row\u2081_to_top_left_mono hD,\n  apply exact_zero_left_of_mono,\nend\n\nlemma exact_bottom_right_to_coker_row\u2082_to_zero (hD : is_snake_input D) :\n  exact hD.bottom_right_to_coker_row\u2082 (0 : cokernel ((2,1) \u27f6[D] (2,2)) \u27f6 0) :=\nbegin\n  rw \u2190 epi_iff_exact_zero_right,\n  apply bottom_right_to_coker_row\u2082_epi hD,\nend\n\nlemma ten_term_exact_seq (hD : is_snake_input D) :\n  exact_seq \ud835\udc9c [\n    (0 : 0 \u27f6 kernel ((1,0) \u27f6[D] (1,1))),\n    hD.ker_row\u2081_to_top_left, (0,0) \u27f6[D] (0,1), (0,1) \u27f6[D] (0,2),\n    hD.\u03b4,\n    (3,0) \u27f6[D] (3,1), (3,1) \u27f6[D] (3,2), hD.bottom_right_to_coker_row\u2082,\n    (0 : cokernel ((2,1) \u27f6[D] (2,2)) \u27f6 0)] :=\nbegin\n  refine exact_seq.cons _ _ hD.exact_zero_to_ker_row\u2081_to_top_left _ _,\n  refine exact_seq.cons _ _ hD.long_row\u2080_exact _ _,\n  refine exact_seq.cons _ _ hD.row_exact\u2080 _ _,\n  refine exact_seq.cons _ _ hD.exact_to_\u03b4 _ _,\n  refine exact_seq.cons _ _ hD.exact_from_\u03b4 _ _,\n  refine exact_seq.cons _ _ hD.row_exact\u2083 _ _,\n  refine exact_seq.cons _ _ hD.long_row\u2083_exact _ _,\n  refine exact_seq.cons _ _ hD.exact_bottom_right_to_coker_row\u2082_to_zero _ _,\n  refine exact_seq.single _,\nend\n\nlemma eight_term_exact_seq (hD : is_snake_input D) :\n  exact_seq \ud835\udc9c [hD.ker_row\u2081_to_top_left, (0,0) \u27f6[D] (0,1), (0,1) \u27f6[D] (0,2),\n    hD.\u03b4,\n    (3,0) \u27f6[D] (3,1), (3,1) \u27f6[D] (3,2), hD.bottom_right_to_coker_row\u2082] :=\nexact_seq.extract hD.ten_term_exact_seq 1 7\n\nlemma six_term_exact_seq (hD : is_snake_input D) :\n  exact_seq \ud835\udc9c [(0,0) \u27f6[D] (0,1), (0,1) \u27f6[D] (0,2), hD.\u03b4, (3,0) \u27f6[D] (3,1), (3,1) \u27f6[D] (3,2)] :=\nexact_seq.extract hD.eight_term_exact_seq 1 5\n\nend is_snake_input\n\nvariables (\ud835\udc9c)\n\nstructure snake_input extends snake_diagram \u2964 \ud835\udc9c :=\n(is_snake_input : is_snake_input to_functor)\n\nnamespace snake_input\n\ninstance : category (snake_input \ud835\udc9c) := induced_category.category to_functor\n\n@[simps] def proj (x : snake_diagram) : snake_input \ud835\udc9c \u2964 \ud835\udc9c :=\ninduced_functor _ \u22d9 (evaluation _ _).obj x\n\ndef mk_of_short_exact_sequence_hom (A B : short_exact_sequence \ud835\udc9c) (f : A \u27f6 B) :\n  snake_input \ud835\udc9c :=\n\u27e8snake_diagram.mk_of_short_exact_sequence_hom A B f,\nis_snake_input.mk_of_short_exact_sequence_hom A B f\u27e9\n\ndef kernel_sequence (D : snake_input \ud835\udc9c)\n  (h1 : mono ((1,0) \u27f6[D] (1,1))) (h2 : is_zero (D.obj (3,0))) :\n  short_exact_sequence \ud835\udc9c :=\n{ fst := D.obj (0,0),\n  snd := D.obj (0,1),\n  trd := D.obj (0,2),\n  f := (0,0) \u27f6[D] (0,1),\n  g := (0,1) \u27f6[D] (0,2),\n  mono' :=\n  begin\n    letI := h1,\n    refine abelian.pseudoelement.mono_of_zero_of_map_zero _ (\u03bb a ha, _),\n    obtain \u27e8b, hb\u27e9 := is_snake_input.exists_of_exact\n      (is_snake_input.long_row\u2080_exact D.is_snake_input) a ha,\n    rw [\u2190 hb],\n    simp [is_snake_input.ker_row\u2081_to_top_left, limits.kernel.\u03b9_of_mono ((1,0) \u27f6[D] (1,1))]\n  end,\n  epi' :=\n  begin\n    rw (abelian.tfae_epi (D.obj (3,0)) ((0,1) \u27f6[D] (0,2))).out 0 2,\n    convert D.2.exact_to_\u03b4,\n    apply h2.eq_of_tgt,\n  end,\n  exact' := D.2.row_exact _ }\n\nend snake_input\n\nclass has_snake_lemma :=\n(\u03b4 : snake_input.proj \ud835\udc9c (0,2) \u27f6 snake_input.proj \ud835\udc9c (3,0))\n(exact_\u03b4 : \u2200 (D : snake_input \ud835\udc9c), exact ((0,1) \u27f6[D] (0,2)) (\u03b4.app D))\n(\u03b4_exact : \u2200 (D : snake_input \ud835\udc9c), exact (\u03b4.app D) ((3,0) \u27f6[D.1] (3,1))) -- why can't I write `\u27f6[D]`\n\nnamespace snake_lemma\n\nvariables [has_snake_lemma \ud835\udc9c]\n\nvariables {\ud835\udc9c}\n\ndef \u03b4 (D : snake_input \ud835\udc9c) : D.obj (0,2) \u27f6 D.obj (3,0) := has_snake_lemma.\u03b4.app D\n\nlemma exact_\u03b4 (D : snake_input \ud835\udc9c) : exact ((0,1) \u27f6[D] (0,2)) (\u03b4 D) :=\nhas_snake_lemma.exact_\u03b4 D\n\nlemma \u03b4_exact (D : snake_input \ud835\udc9c) : exact (\u03b4 D) ((3,0) \u27f6[D] (3,1)) :=\nhas_snake_lemma.\u03b4_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<http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html>\n-/\nimport control.monad.basic\nimport control.monad.writer\n\nuniverses u v w u\u2080 u\u2081 v\u2080 v\u2081\n\nstructure monad_cont.label (\u03b1 : Type w) (m : Type u \u2192 Type v) (\u03b2 : Type u) :=\n(apply : \u03b1 \u2192 m \u03b2)\n\ndef monad_cont.goto {\u03b1 \u03b2} {m : Type u \u2192 Type v} (f : monad_cont.label \u03b1 m \u03b2) (x : \u03b1) := f.apply x\n\nclass monad_cont (m : Type u \u2192 Type v) :=\n(call_cc : \u03a0 {\u03b1 \u03b2}, ((monad_cont.label \u03b1 m \u03b2) \u2192 m \u03b1) \u2192 m \u03b1)\n\nopen monad_cont\n\nclass is_lawful_monad_cont (m : Type u \u2192 Type v) [monad m] [monad_cont m]\nextends is_lawful_monad m :=\n(call_cc_bind_right {\u03b1 \u03c9 \u03b3} (cmd : m \u03b1) (next : (label \u03c9 m \u03b3) \u2192 \u03b1 \u2192 m \u03c9) :\n  call_cc (\u03bb f, cmd >>= next f) = cmd >>= \u03bb x, call_cc (\u03bb f, next f x))\n(call_cc_bind_left {\u03b1} (\u03b2) (x : \u03b1) (dead : label \u03b1 m \u03b2 \u2192 \u03b2 \u2192 m \u03b1) :\n  call_cc (\u03bb f : label \u03b1 m \u03b2, goto f x >>= dead f) = pure x)\n(call_cc_dummy {\u03b1 \u03b2} (dummy : m \u03b1) :\n  call_cc (\u03bb f : label \u03b1 m \u03b2, dummy) = dummy)\n\nexport is_lawful_monad_cont\n\ndef cont_t (r : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type w) := (\u03b1 \u2192 m r) \u2192 m r\n\n@[reducible] def cont (r : Type u) (\u03b1 : Type w) := cont_t r id \u03b1\n\nnamespace cont_t\n\nexport monad_cont (label goto)\n\nvariables {r : Type u} {m : Type u \u2192 Type v} {\u03b1 \u03b2 \u03b3 \u03c9 : Type w}\n\ndef run : cont_t r m \u03b1 \u2192 (\u03b1 \u2192 m r) \u2192 m r := id\n\ndef map (f : m r \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b1 := f \u2218 x\n\nlemma run_cont_t_map_cont_t (f : m r \u2192 m r) (x : cont_t r m \u03b1) :\n  run (map f x) = f \u2218 run x := rfl\n\ndef with_cont_t (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) : cont_t r m \u03b2 :=\n\u03bb g, x $ f g\n\nlemma run_with_cont_t (f : (\u03b2 \u2192 m r) \u2192 \u03b1 \u2192 m r) (x : cont_t r m \u03b1) :\n  run (with_cont_t f x) = run x \u2218 f := rfl\n\n@[ext]\nprotected lemma ext {x y : cont_t r m \u03b1}\n  (h : \u2200 f, x.run f = y.run f) :\n  x = y := by { ext; apply h }\n\ninstance : monad (cont_t r m) :=\n{ pure := \u03bb \u03b1 x f, f x,\n  bind := \u03bb \u03b1 \u03b2 x f g, x $ \u03bb 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] {\u03b1} : m \u03b1 \u2192 cont_t r m \u03b1 :=\n\u03bb x f, x >>= f\n\ninstance [monad m] : has_monad_lift m (cont_t r m) :=\n{ monad_lift := \u03bb \u03b1, cont_t.monad_lift }\n\nlemma monad_lift_bind [monad m] [is_lawful_monad m] {\u03b1 \u03b2} (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) :\n  (monad_lift (x >>= f) : cont_t r m \u03b2) = monad_lift x >>= monad_lift \u2218 f :=\nbegin\n  ext,\n  simp only [monad_lift,has_monad_lift.monad_lift,(\u2218),(>>=),bind_assoc,id.def,run,cont_t.monad_lift]\nend\n\ninstance : monad_cont (cont_t r m) :=\n{ call_cc := \u03bb \u03b1 \u03b2 f g, f \u27e8\u03bb x h, g x\u27e9 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 (\u03b5) [monad_except \u03b5 m] : monad_except \u03b5 (cont_t r m) :=\n{ throw := \u03bb x e f, throw e,\n  catch := \u03bb \u03b1 act h f, catch (act f) (\u03bb e, h e f) }\n\ninstance : monad_run (\u03bb \u03b1, (\u03b1 \u2192 m r) \u2192 ulift.{u v} (m r)) (cont_t.{u v u} r m) :=\n{ run := \u03bb \u03b1 f x, \u27e8 f x \u27e9 }\n\nend cont_t\n\nvariables {m : Type u \u2192 Type v} [monad m]\n\ndef except_t.mk_label {\u03b1 \u03b2 \u03b5} : label (except.{u u} \u03b5 \u03b1) m \u03b2 \u2192 label \u03b1 (except_t \u03b5 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, monad_lift $ f (except.ok a) \u27e9\n\nlemma except_t.goto_mk_label {\u03b1 \u03b2 \u03b5 : Type*} (x : label (except.{u u} \u03b5 \u03b1) m \u03b2) (i : \u03b1) :\n  goto (except_t.mk_label x) i = \u27e8 except.ok <$> goto x (except.ok i) \u27e9 := by cases x; refl\n\ndef except_t.call_cc\n  {\u03b5} [monad_cont m] {\u03b1 \u03b2 : Type*} (f : label \u03b1 (except_t \u03b5 m) \u03b2 \u2192 except_t \u03b5 m \u03b1) :\n  except_t \u03b5 m \u03b1 :=\nexcept_t.mk (call_cc $ \u03bb x : label _ m \u03b2, except_t.run $ f (except_t.mk_label x) : m (except \u03b5 \u03b1))\n\ninstance {\u03b5} [monad_cont m] : monad_cont (except_t \u03b5 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, except_t.call_cc }\n\ninstance {\u03b5} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t \u03b5 m) :=\n{ call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp,\n    congr' with \u27e8 \u27e9; 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 {\u03b1 \u03b2} : label (option.{u} \u03b1) m \u03b2 \u2192 label \u03b1 (option_t m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, monad_lift $ f (some a) \u27e9\n\nlemma option_t.goto_mk_label {\u03b1 \u03b2 : Type*} (x : label (option.{u} \u03b1) m \u03b2) (i : \u03b1) :\n  goto (option_t.mk_label x) i = \u27e8 some <$> goto x (some i) \u27e9 := by cases x; refl\n\ndef option_t.call_cc [monad_cont m] {\u03b1 \u03b2 : Type*} (f : label \u03b1 (option_t m) \u03b2 \u2192 option_t m \u03b1) :\n  option_t m \u03b1 :=\noption_t.mk (call_cc $ \u03bb x : label _ m \u03b2, option_t.run $ f (option_t.mk_label x) : m (option \u03b1))\n\ninstance [monad_cont m] : monad_cont (option_t m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, 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 \u27e8 \u27e9; 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 {\u03b1 \u03b2 \u03c9} [has_one \u03c9] : label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 label \u03b1 (writer_t \u03c9 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, monad_lift $ f (a,1) \u27e9\n\nlemma writer_t.goto_mk_label {\u03b1 \u03b2 \u03c9 : Type*} [has_one \u03c9] (x : label (\u03b1 \u00d7 \u03c9) m \u03b2) (i : \u03b1) :\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] {\u03b1 \u03b2 \u03c9 : Type*} [has_one \u03c9]\n  (f : label \u03b1 (writer_t \u03c9 m) \u03b2 \u2192 writer_t \u03c9 m \u03b1) : writer_t \u03c9 m \u03b1 :=\n\u27e8 call_cc (writer_t.run \u2218 f \u2218 writer_t.mk_label : label (\u03b1 \u00d7 \u03c9) m \u03b2 \u2192 m (\u03b1 \u00d7 \u03c9)) \u27e9\n\ninstance (\u03c9) [monad m] [has_one \u03c9] [monad_cont m] : monad_cont (writer_t \u03c9 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, writer_t.call_cc }\n\ndef state_t.mk_label {\u03b1 \u03b2 \u03c3 : Type u} : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3) \u2192 label \u03b1 (state_t \u03c3 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 \u03bb a, \u27e8 \u03bb s, f (a,s) \u27e9 \u27e9\n\nlemma state_t.goto_mk_label {\u03b1 \u03b2 \u03c3 : Type u} (x : label (\u03b1 \u00d7 \u03c3) m (\u03b2 \u00d7 \u03c3)) (i : \u03b1) :\n  goto (state_t.mk_label x) i = \u27e8 \u03bb s, (goto x (i,s)) \u27e9 := by cases x; refl\n\ndef state_t.call_cc {\u03c3}  [monad_cont m] {\u03b1 \u03b2 : Type*}\n  (f : label \u03b1 (state_t \u03c3 m) \u03b2 \u2192 state_t \u03c3 m \u03b1) : state_t \u03c3 m \u03b1 :=\n\u27e8 \u03bb r, call_cc (\u03bb f', (f $ state_t.mk_label f').run r) \u27e9\n\ninstance {\u03c3} [monad_cont m] : monad_cont (state_t \u03c3 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, state_t.call_cc }\n\ninstance {\u03c3} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t \u03c3 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 \u27e8x\u2080,x\u2081\u27e9, 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 {\u03b1 \u03b2} (\u03c1) : label \u03b1 m \u03b2 \u2192 label \u03b1 (reader_t \u03c1 m) \u03b2\n| \u27e8 f \u27e9 := \u27e8 monad_lift \u2218 f \u27e9\n\nlemma reader_t.goto_mk_label {\u03b1 \u03c1 \u03b2} (x : label \u03b1 m \u03b2) (i : \u03b1) :\n  goto (reader_t.mk_label \u03c1 x) i = monad_lift (goto x i) := by cases x; refl\n\ndef reader_t.call_cc {\u03b5}  [monad_cont m] {\u03b1 \u03b2 : Type*}\n  (f : label \u03b1 (reader_t \u03b5 m) \u03b2 \u2192 reader_t \u03b5 m \u03b1) : reader_t \u03b5 m \u03b1 :=\n\u27e8 \u03bb r, call_cc (\u03bb f', (f $ reader_t.mk_label _ f').run r) \u27e9\n\ninstance {\u03c1} [monad_cont m] : monad_cont (reader_t \u03c1 m) :=\n{ call_cc := \u03bb \u03b1 \u03b2, reader_t.call_cc }\n\ninstance {\u03c1} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t \u03c1 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\u2081 : Type u\u2080 \u2192 Type v\u2080} {m\u2082 : Type u\u2081 \u2192 Type v\u2081}\n  {\u03b1\u2081 r\u2081 : Type u\u2080} {\u03b1\u2082 r\u2082 : Type u\u2081} (F : m\u2081 r\u2081 \u2243 m\u2082 r\u2082) (G : \u03b1\u2081 \u2243 \u03b1\u2082) :\n  cont_t r\u2081 m\u2081 \u03b1\u2081 \u2243 cont_t r\u2082 m\u2082 \u03b1\u2082 :=\n{ to_fun := \u03bb f r, F $ f $ \u03bb x, F.symm $ r $ G x,\n  inv_fun := \u03bb f r, F.symm $ f $ \u03bb x, F $ r $ G.symm x,\n  left_inv := \u03bb f, by funext r; simp,\n  right_inv := \u03bb 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 Smt\n\ntheorem replace : \"a\".replace \"a\" \"b\" = \"b\" := by\n  smt\n  admit\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/Test/String/Replace.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713269122913015, "lm_q2_score": 0.04885777342867017, "lm_q1q2_score": 0.009142886629170134}}
{"text": "\nimport Lib.Meta\nimport Lib.Tactic\n\nnamespace Lean.Elab.Tactic\n\nopen Lean.Elab.Tactic\nopen Lean Lean.Meta\nopen Lean.Elab\nopen Lean.Elab.Term\nopen Lean.PrettyPrinter.Delaborator.TopDownAnalyze\nopen Lean.Elab.Tactic\n\ndeclare_syntax_cat move_intro_pat\ndeclare_syntax_cat move_revert_pat\nsyntax tactic colGt \" => \" (colGt move_intro_pat)+ : tactic\n\n-- #exit\n\nsyntax (name := skip) \"_\" : move_intro_pat\nsyntax (name := auto) \"//\" : move_intro_pat\nsyntax (name := simp) \"/=\" : move_intro_pat\nsyntax (name := autoSimp) \"//=\" : move_intro_pat\nsyntax (name := introIdent) ident : move_intro_pat\nsyntax (name := apply) \"/\" group(ident <|>  (\"(\" term \")\")) : move_intro_pat\n-- syntax (name := applyTerm) \"/\" \"(\" term \")\" : move_intro_pat\nsyntax (name := casePat) \"[\" sepBy(move_intro_pat*, \"|\", \" | \")  \"]\" : move_intro_pat\n\nsyntax (name := revertIdent) ident : move_revert_pat\nsyntax (name := revertGen) (group((\"!\")? \"(\" term \")\") <|> group(\"!\" ident)) : move_revert_pat\n\n-- TODO: clear pattern, `_`, `?` patterns\n-- TODO: using intro patterns with `have`\n\n-- #exit\n\n-- syntax \"move\" : tactic\n-- syntax withPosition(\"move\" \":\" (colGt move_revert_pat)+) : tactic\n\n-- #exit\n\ninductive MoveIntroPat where\n-- | auto (ref : Syntax)\n-- | simp (ref : Syntax)\n| autoSimp (ref : Syntax) (simp auto : Bool := true)\n| intro (ref : Syntax) (n : Name)\n| apply (e : Syntax)\n| case (opS clS : Syntax) (brs : Array (Array MoveIntroPat))\nderiving Repr, Inhabited, BEq -- , DecidableEq\n\ndef MoveIntroPat.auto (ref : Syntax) : MoveIntroPat :=\n.autoSimp ref false true\n\ndef MoveIntroPat.simp (ref : Syntax) : MoveIntroPat :=\n.autoSimp ref true false\n\nmutual\n\npartial def parseMoveIntroPat (pat : Syntax) : TacticM MoveIntroPat := do\nif pat.getKind == ``skip then\n  return .intro pat `_\nelse if pat.getKind == ``introIdent then\n  return .intro pat pat[0].getId\nelse if pat.getKind == ``auto then\n  return .auto pat\nelse if pat.getKind == ``simp then\n  return .simp pat\nelse if pat.getKind == ``autoSimp then\n  return .autoSimp pat\nelse if pat.getKind == ``apply then\n  let fn := pat[1]\n  if pat[1].getNumArgs == 1 then\n    return .apply pat[1][0]\n  if pat[1].getNumArgs == 3 then\n    return .apply pat[1][1]\nelse if pat.getKind == ``casePat then\n  return .case pat[0] pat[2] (\u2190 pat[1].getArgs.getSepElems.mapM parseMoveIntroPatArray)\nthrowIllFormedSyntax\n\npartial def parseMoveIntroPatArray (pat : Syntax) :\n  TacticM (Array MoveIntroPat) := do\npat.getArgs.mapM parseMoveIntroPat\n\nend\n\n\n/-\n\n6 2 1 0 0 0 1 0 0 0\n0 1 2 3 4 5 6 7 8 9\n\n-/\n-- #exit\n\ndef runintro (ref : Syntax) (n : Name) : TacticM Unit :=\n  withTacticInfoContext ref <|\n    discard <| liftMetaTactic1' (intro . n)\n\n-- #fullname auto\n-- #check Lean.Elab.Tactic.auto\n-- #check autoTac\n\npartial def runMoveIntroPat : MoveIntroPat \u2192 TacticM Unit\n| .intro ref n =>\n  -- runintro ref n\n  withTacticInfoContext ref <|\n    discard <| liftMetaTactic1' (intro . n)\n| .case opBrack clBrack pats => do\n  withTacticInfoContext opBrack (pure ())\n  liftMetaTactic \u03bb g => do\n    let (v, g) \u2190 intro1 g\n    let gs \u2190 cases g v\n    -- let mut gs' := #[]\n    unless pats.size == gs.size ||\n           (pats == #[#[]]) do\n      throwError \"mismatched numbers of branches and patterns\"\n    gs.toList.mapM \u03bb \u27e8g, p\u27e9 => do\n      let vs := g.fields.map (\u00b7.fvarId!)\n      let g  := g.mvarId\n      (\u00b7.2) <$> revert g vs\n  let gs \u2190 getGoals\n  let gs' \u2190 gs.zip pats.toList |>.mapM \u03bb \u27e8g,ps\u27e9 => do\n    setGoals [g]\n    for p in ps do\n      allGoals <| runMoveIntroPat p\n    getGoals\n  setGoals gs'.join\n  withTacticInfoContext clBrack (pure ())\n| .apply rule =>\n  withTacticInfoContext rule <|\n  liftMetaTactic1' \u03bb g => do\n    let (v, g) \u2190 intro1 g\n    let rule \u2190 Term.elabTerm rule none |>.run'\n    withMVarContext g do\n    let pr  \u2190 mkAppM' rule #[mkFVar v]\n    let typ \u2190 inferType pr\n    let g \u2190 assert g `h typ pr\n    let g \u2190 clear g v\n    return ((), g)\n-- | .auto ref =>\n| .autoSimp ref callSimp callAuto => do\n  -- let stx \u2190 `(tactic| simp)\n  if callSimp then\n    withTacticInfoContext ref <|\n      liftMetaTactic1 (simpTarget . {})\n  if callAuto then\n    withTacticInfoContext ref autoTac\n    -- evalTactic (\u2190 `(tactic| try auto))\n-- | _ => throwError \"foo\"\n\n\n-- #check Lean.Elab.Tactic.simp\n-- #check Lean.Meta.Simp.simp\n\n-- partial def runMoveIntroPat : MoveIntroPat \u2192 TacticM Unit\n-- | .intro ref n => runintro ref n\n--   -- withTacticInfoContext ref <|\n--     -- discard <| liftMetaTactic1' (intro . n)\n-- | .case opBrack clBrack pats => do\n--   withTacticInfoContext opBrack (pure ())\n--   liftMetaTactic \u03bb g => do\n--     let (v, g) \u2190 intro1 g\n--     let gs \u2190 cases g v\n--     -- let mut gs' := #[]\n--     unless pats.size == gs.size ||\n--            (pats == #[#[]]) do\n--       throwError \"mismatched numbers of branches and patterns\"\n--     gs.toList.mapM \u03bb g => do\n--       let vs := g.fields.map (\u00b7.fvarId!)\n--       let g  := g.mvarId\n--       (\u00b7.2) <$> revert g vs\n--   withTacticInfoContext clBrack (pure ())\n--   -- sorry\n-- -- | .apply rule =>\n-- --   withTacticInfoContext rule <|\n-- --   liftMetaTactic1' \u03bb g => do\n-- --     let (v, g) \u2190 intro1 g\n-- --     let rule \u2190 Term.elabTerm rule none |>.run'\n-- --     withMVarContext g do\n-- --     let pr  \u2190 mkAppM' rule #[mkFVar v]\n-- --     let typ \u2190 inferType pr\n-- --     let g \u2190 assert g `h typ pr\n-- --     let g \u2190 clear g v\n-- --     return ((), g)\n-- -- | .simp ref => do\n-- --   -- let stx \u2190 `(tactic| simp)\n-- --   withTacticInfoContext ref do\n-- --     Elab.Tactic.simp\n-- -- | .auto ref =>\n-- --   withTacticInfoContext ref do\n-- --     evalTactic (\u2190 `(tactic| try auto))\n-- -- | .autoSimp ref => sorry\n-- --   -- withTacticInfoContext ref do\n-- --     -- evalTactic (\u2190 `(tactic| simp; try auto))\n-- | _ => throwError \"foo\"\n\n-- #synth BEq Syntax\n-- #print Syntax.instBEqSyntax\n\ninductive MoveRevertPat where\n  | revert (ref : Syntax) (n : Name)\n  | generalize (ref : Syntax) (n : Bool) (t : Syntax)\nderiving Repr, BEq\n\n-- #check BEq\n\n-- #exit\n\n-- #check SepArray.getSepElems\ndef parseMoveRevertPat (s : Syntax) : TacticM MoveRevertPat := do\nif s.getKind == ``revertIdent then\n  return .revert s s[0].getId\nelse if s.getKind == ``revertGen then\n  -- let tag :=\n  --   if\n  --     then none\n  --     else some s[0][0].getId\n  let term :=\n    if s[0].getKind == groupKind\n      then s[0][2]\n      else s[0]\n  return .generalize s (s[0].getNumArgs != 0) term\nthrowError \"invalid revert pattern {s} ({s.getKind}, {s.getArgs})\"\n\ndef MoveRevertPat.toRef : MoveRevertPat \u2192 Syntax\n| .revert ref n => ref\n| .generalize ref _ _ => ref\n\ndef runMoveRevertPat : MoveRevertPat \u2192 TacticM Unit\n| .revert ref n =>\nwithMainContext do\n-- withTacticInfoContext ref <| do\n  let v \u2190 getLocalDeclFromUserName n\n  discard <| liftMetaTactic1' (revert . #[v.fvarId])\n| .generalize ref h e =>\nwithMainContext do\n-- withTacticInfoContext ref <| do\n  -- print_vars![mainGoal, e]\n  let e \u2190 elabTerm e none\n  let h := if h then some `h else none\n  print_vars![mainGoal, e]\n  let vs \u2190 liftMetaTactic1' (generalize .\n    #[ { expr := e, hName? := h, xName? := some `x }])\n  withMainContext do\n  discard <| liftMetaTactic1' (revert . vs.reverse)\n\n-- #eval \"A\"\n-- #exit\n\n-- macro_rules\n-- | `(tactic| move ) => `(tactic| skip)\n\n-- #eval \"A\"\n\ndeclare_syntax_cat revert_pats\n\n-- #eval \"A\"\n\nsyntax \":\" (colGt move_revert_pat)+ : revert_pats\n-- #eval \"A\"\n\nsyntax \"move\" (colGt revert_pats)?  : tactic\n\nelab_rules : tactic\n| `(tactic| move%$token $[$xs:revert_pats]? ) => do\nmatch xs with\n| some xs =>\n  let colon := xs[0]\n  let xs := xs[1].getArgs\n  withTacticInfoContext (mkNullNode #[token, colon]) (pure ())\n  for x in xs.reverse do\n    let x' \u2190 parseMoveRevertPat x\n    runMoveRevertPat x'\n| none => return ()\n  -- println!\"{}\"\n  -- xs.reverse.forM runMoveRevertPat\n\n-- #eval \"B\"\n-- #exit\n\nelab_rules : tactic\n| `(tactic| $tac => $pats*) => do\n  -- let pats' \u2190 pats.mapM parseMoveIntroPat\n  evalTactic tac\n  let arrow := (\u2190 getRef)[1]\n  withTacticInfoContext arrow (pure ())\n  for pat in pats do\n    let pat' \u2190 parseMoveIntroPat pat\n    -- let next := pats.getD (i+1) Syntax.missing\n    allGoals <| runMoveIntroPat pat'\n  -- println!\"repr: {repr xs}\"\n-- #check [1:3]\n-- #check Std.Range\n\n-- move => a b c\n--        ^\n-- -- \u22a2 T \u2192 V \u2192 U \u2192 True\n-- move => a b c\n--          ^\n-- \u22a2 T \u2192 V \u2192 U \u2192 True\n\n-- u : T\n-- \u22a2 V \u2192 U \u2192 True\n\n\n-- example : True := by\n-- let T := True\n-- let U := True\n-- let V := True\n-- -- have h\u2080 : T \u2194 U := sorry\n-- -- have h\u2081 : U \u2194 V := sorry\n-- have t : T := True.intro\n-- have v : V := True.intro\n-- have u : U := True.intro\n-- have x : Nat \u00d7 Nat := sorry\n-- have y : List Nat \u2295 List Nat := sorry\n-- -- revert e\n-- -- rewrite [h\u2080, h\u2081]\n-- have f : T \u2192 U := id\n-- -- move: t u v => /f u v t\n-- -- have' h : T \u2295' U := sorry\n-- -- move: !(T \u2295' U) h\n-- move: t u v y x\n-- move => v u t\n-- move => [ |] ys [ x y ] ;\n-- -- move => [ x y ]\n-- -- move => [ xs |]\n-- skip\n-- -- move: f h:(f) => y x\n-- -- move => /f d // ;\n\n\nend Lean.Elab.Tactic\n\n-- Local Variables:\n-- lean4-test-file: \"/Users/simon/google stuff/lean/sat/concrete-semantics/ConcreteSemantics/ch7.lean\"\n-- End:\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/Tactic/Move.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245628973633, "lm_q2_score": 0.033589505287321235, "lm_q1q2_score": 0.009137170493722233}}
{"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' : \u211d\u22650)\nvariables [fact (0 < r)] [fact (r < r')] [fact (r < 1)]\n\nsection\n\nopen bounded_homotopy_category\n\nvariables (BD : breen_deligne.data)\nvariables (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{u} r')\nvariables (V : SemiNormedGroup.{u})\n\nlemma QprimeFP_map (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) :\n  (QprimeFP r' BD \u03ba M).map h = of'_hom ((QprimeFP_int r' BD \u03ba _).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 : \u211d\u22650) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V \u27f6 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\u2081 (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\u2082 [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\u2083 [normed_with_aut r V] (X : Profinite) :\n  continuous.{u u}\n  (\u03bb (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 \u21a5V)).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 {\u03b2 : Type*} [uniform_space \u03b2] (a : abstract_completion \u03b2) : uniform_space a.space :=\nby apply_instance\n\nlemma final_boss_aux\u2084 [normed_with_aut r V] (X : Profinite) :\n@continuous.{u u} _ _ _ (uniform_space.completion.cpkg.uniform_struct.to_topological_space)\n  (\u03bb (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) \u2218 x.to_fun, continuous_to_fun :=\n  (normed_with_aut.T.inv.continuous.comp x.2)})) :=\nbegin\n  let e : C(X,V) \u2192 C(X,V) := \u03bb e, \u27e8(V_T_inv r V) \u2218 e,\n    (V_T_inv r V).continuous.comp e.2\u27e9,\n  have he : continuous e := continuous_map.continuous_comp\n    ((\u27e8(V_T_inv r V), (V_T_inv r V).continuous\u27e9 : 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) \u2218 x.1, continuous_to_fun :=\n      (normed_with_aut.T.inv.continuous.comp x.2)} :=\nbegin\n  rw final_boss_aux\u2081,\n  rw final_boss_aux\u2081,\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 \u21a5V) x,\n  { apply is_closed_eq,\n    { apply final_boss_aux\u2083 },\n    { apply final_boss_aux\u2084 } },\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 \u21a5V).compare uniform_space.completion.cpkg.{u}\n       ((locally_constant.pkg.{u} X \u21a5V).coe x)) = _,\n  --dsimp [abstract_completion.compare_equiv],\n  rw abstract_completion.compare_coe,\n  erw final_boss_aux\u2082,\n  erw uniform_space.completion.map_coe,\n  let q : C(X,V) :=\n    {to_fun := (normed_with_aut.T.{u}.inv) \u2218 ((locally_constant.pkg.{u} X \u21a5V).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 \u21a5V).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 \u21a5V).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\u2081 (X Y : Profinite.{u}) (f : X \u27f6 Y) :\n  (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map (freeCond.{u}.map f).op \u226b\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 \u226b\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 \u2192+ B) (g : B \u2192+ 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 \u2192+ B) (g : B \u2192+ 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 \u2192 Y) (hf : continuous f) (g : normed_group_hom V W) (\u03c6 : locally_constant Y V) :\n  locally_constant.comap_hom f hf (locally_constant.map_hom g \u03c6) =\n  ((locally_constant.map_hom g) \u2218 (locally_constant.comap_hom f hf)) \u03c6 :=\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 \u21a5(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 \u27f6 Y) (x) :\n  V.to_Cond.val.map f.op x = \u27e8continuous_map.comp_right_continuous_map V f x.down\u27e9 :=\nrfl\n\nlemma to_Cond_val_map (X Y : Profinite.{u}) (f : X \u27f6 Y) :\n  \u21d1(V.to_Cond.val.map f.op) =\n  (\u03bb x, \u27e8continuous_map.comp_right_continuous_map V f x.down\u27e9 : \u21a5(V.to_Cond.val.obj (op Y)) \u2192 \u21a5(V.to_Cond.val.obj (op X))) :=\nby { ext x, rw to_Cond_val_map_apply }\n\nlemma massive_aux\u2082 (X Y : Profinite.{u}) (f : X \u27f6 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 \u21a5V).compare uniform_space.completion.cpkg.{u} x.down) =\n  ((locally_constant.pkg.{u} X \u21a5V).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 \u03c6 : C(Y, V) \u2192 C(X, V) := _, change continuous \u03c6,\n      let \u03c8 := V.to_Cond.val.map f.op, have h\u03c8 : \u03c6 = ulift.down \u2218 \u03c8 \u2218 ulift.up := rfl,\n      rw h\u03c8, clear h\u03c8,\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 \u21a5V f)).comp continuous_induced_dom, } },\n  { intro \u03c6,\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 \u21a5(X.to_CompHaus.to_Top) \u21a5V),\n      { exact locally_constant.semi_normed_group },\n      letI : semi_normed_group (locally_constant \u21a5(Y.to_CompHaus.to_Top) \u21a5V),\n      { exact locally_constant.semi_normed_group },\n      exact normed_group_hom.uniform_continuous _, },\n    have : (continuous_map.comp_right_continuous_map \u21a5V f) ((locally_constant.pkg Y V).coe \u03c6) =\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 \u27f6 Y) :\n  (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y).hom \u226b\n      Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} Y)) \u226b\n        (ExtQprime_iso_aux_system_obj_aux'.{u} V Y).hom \u226b\n          (forget\u2082.{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}\u1d52\u1d56).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 \u226b\n      (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X).hom \u226b\n        Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} X)) \u226b\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\u2081_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\u2082_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 \u2218 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} \u21a5(unop.{u+2} (op.{u+2} X)) \u21a5V) := _,\n  erw [\u2190 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\u2082 V X Y f x,\nend\n\nlemma massive (X Y : FreeAb Profinite.{u}) (f : X \u27f6 Y) :\n  (((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y.as).hom \u226b\n    (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} Y.as) \u226b\n    (ExtQprime_iso_aux_system_obj_aux'.{u} V Y.as).hom) \u226b\n    (\ud835\udfd9 _)) \u226b\n    (forget\u2082.{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 \u22d9\n        FreeAb.eval.{u+1 u+2} SemiNormedGroup.{u+1}\u1d52\u1d56).map f).unop =\n  (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map\n    ((freeCond.{u}.map_FreeAb \u22d9 FreeAb.eval.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1})).map f).op \u226b\n    ((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X.as).hom \u226b\n    (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} X.as) \u226b\n    (ExtQprime_iso_aux_system_obj_aux'.{u} V X.as).hom) \u226b  \ud835\udfd9 _ :=\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\u2081 c\u2082) (h : c\u2081 \u27f6 c\u2082) :\n  (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c\u2082).hom \u226b\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) \u226b (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c\u2081).hom :=\nbegin\n  ext n : 2,\n  have aux : \u2200 (n : \u2115), (monotone.{0 0} (function.swap.{1 1 1} \u03ba n)),\n  { intro n, exact fact.out _ },\n  haveI : fact (\u03ba c\u2081 n \u2264 \u03ba c\u2082 n) := \u27e8aux n h.le\u27e9,\n  have := massive V\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c\u2081 n)\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c\u2082 n)\n    ((breen_deligne.FP2.res.{u} r' _ _ _).app \u27e8M\u27e9),\n  exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_\u03ba (c : (\u211d\u22650))\n  [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 \u03ba c n)] :\n  (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c).hom \u226b\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.\u03b9 BD \u03ba\u2082 \u03ba M).app _,\n  end \u226b (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba\u2082 M V c).hom :=\nbegin\n  ext n : 2,\n  have := massive V\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba\u2082 c n)\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c n)\n    ((breen_deligne.FP2.res.{u} r' _ _ _).app \u27e8M\u27e9),\n  exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv (c : \u211d\u22650)\n  [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] :\n  (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c).hom \u226b\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 \u03ba\u2082 \u03ba M).app _,\n  end\n  \u226b (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba\u2082 M V c).hom :=\nbegin\n  ext n : 2,\n  have := massive V\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba\u2082 c n)\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c n)\n    (((breen_deligne.FPsystem.Tinv.{u} r' BD \u27e8M\u27e9 \u03ba\u2082 \u03ba).app c).f n),\n  exact this,\nend\n\n\n\ndef to_Cond_T_inv (r : \u211d\u22650) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V.to_Cond \u27f6 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  {\u03b1 \u03b2 \u03b3 : Type*} [uniform_space \u03b1] [uniform_space \u03b2] [uniform_space \u03b3]\n  {g : \u03b2 \u2192 \u03b3} {f : \u03b1 \u2192 \u03b2}\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 \u2218 f) x :=\nbegin\n  rw [\u2190 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 : \u211d\u22650) (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 \u226b\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 _ _) _) \u226b\n  (ExtQprime_iso_aux_system_obj_aux' V X).hom\n   :=\nbegin\n  ext1 \u27e8f\u27e9,\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\u2082_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  \u226b (Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app (op X)\n  \u226b\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 _ \u226b\n  (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom \u226b\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 \u2190 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 \u2190 nat_trans.comp_app,\n  rw \u2190 Sheaf.hom.comp_val, -- how to make those commute?\n  ext \u27e8x\u27e9,\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\u2082, has_forget\u2082.forget\u2082],\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 : \u211d\u22650)\n  [normed_with_aut r V] (n : \u2115) (t) :\n((forget\u2082.{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 \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba).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 \u27e8M\u27e9 \u03ba).obj c).X n)).unop) t) =\n  (((ExtQprime_iso_aux_system_obj_aux.{u} V).hom.app\n        (((breen_deligne.FPsystem.{u} r' BD \u27e8M\u27e9 \u03ba).obj c).X n)).unop)\n        (t \u226b 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\u2082, has_forget\u2082.forget\u2082, 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\u2082, has_forget\u2082.forget\u2082, 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 \u27e8M\u27e9 \u03ba).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 (\u03bb 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 (\u03bb e, e s) at this,\n  erw this, clear this,\n  simp only [comp_apply],\n  congr' 1, dsimp only [s],\n  simp only [\u2190 comp_apply],\n  congr' 1,\n  simp only [category.assoc],\n  erw \u2190 another_aux_lemma r V X,\n  congr' 2,\n  ext1 \u27e8x\u27e9, 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 : \u211d\u22650)\n  [normed_with_aut r V] :\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V c).hom \u226b\n  ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n       (complex_shape.up.{0} \u2115)).map (nat_trans.app\n        ((aux_system.T_inv.{u u+1} r r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba)) _) =\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 \u2115).symm,\n    let Q := ((QprimeFP_nat r' BD \u03ba M).obj c).op,\n    exact e'.app Q,\n  end \u226b\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba 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\u2082_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\u2081 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) :\nhomological_complex.unop_functor.{u+2 u+1 0}.map\n    (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n         forget\u2082.{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} \u2124)).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 \u03ba M).map h))).op \u226b\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 \u22d9\n             forget\u2082.{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 \u03ba M).obj c\u2081)).op \u226b\n    embed_unop.{u+2 u+1}.hom.app\n      (op.{u+3}\n         (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n              forget\u2082.{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} \u2115)).obj\n            ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081))) =\n  begin\n    dsimp,\n    let e := (QprimeFP_nat r' BD \u03ba M).map h,\n    let e\u2081 := ((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n      forget\u2082.{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} \u2115)).map e,\n    let e\u2082 := homological_complex.unop_functor.map e\u2081.op,\n    refine _ \u226b\n      (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down).map\n      e\u2082,\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 \u22d9\n           forget\u2082.{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 \u03ba M).obj c\u2082)).op \u226b\n    embed_unop.{u+2 u+1}.hom.app\n    (op.{u+3}\n       (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n            forget\u2082.{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} \u2115)).obj\n          ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082)))\n  end := admit\n\ndef F : \u211d\u22650 \u2964\n  (homological_complex.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.down.{0} \u2115).symm)\u1d52\u1d56 :=\nQprimeFP_nat.{u} r' BD \u03ba M \u22d9\n  (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n     forget\u2082.{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} \u2115) \u22d9 homological_complex.unop_functor.right_op\n\n@[reassoc]\nlemma naturality_helper {c\u2081 c\u2082 : \u211d\u22650} (h : c\u2081 \u27f6 c\u2082) (n : \u2115) (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 (-\u2191n) w1).hom.app\n    (((preadditive_yoneda.{u+1 u+2}.obj\n    V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} \u2115)).obj\n     ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082)).unop \u226b\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) \u226b\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 (-\u2191n) w2).hom.app\n    (((preadditive_yoneda.{u+1 u+2}.obj\n    V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} \u2115)).obj\n    ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081)).unop :=\nadmit\n-/\n\nlemma aux\u2081 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V c\u2082).hom \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  ((aux_system.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba).to_Ab.map h.op) =\n  (homology_functor _ _ _).map\n  (category_theory.functor.map _\n      (homological_complex.op_functor.map ((QprimeFP_nat r' BD \u03ba M).map h).op)) \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V c\u2081).hom :=\nbegin\n  rw [\u2190 functor.map_comp, \u2190 functor.map_comp],\n  congr' 1,\n  erw \u2190 hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_c,\nend\n\nlemma aux\u2082 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\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 (-\u2191n) (by { cases n; refl})).hom.app\n    (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond) \u226b\n    (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n    (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n    (complex_shape.down.{0} \u2115).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n    ((QprimeFP_nat.{u} r' BD \u03ba M).map h).op)) =\n  (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down \u22d9\n  homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} \u2124) (-\u2191n)).map\n  (category_theory.functor.map _\n      (homological_complex.op_functor.map ((QprimeFP_nat r' BD \u03ba M).map h).op)) \u226b\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 (-\u2191n) (by { cases n; refl})).hom.app\n  (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081) V.to_Cond) :=\nbegin\n  erw nat_trans.naturality,\nend\n\n\nlemma aux\u2083 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond).hom \u226b\n  (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down \u22d9\n  homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} \u2124) (-\u2191n)).map\n  (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n  (complex_shape.down.{0} \u2115).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n  ((QprimeFP_nat.{u} r' BD \u03ba M).map h).op))\n  =\n  ((homology_functor.{u+1 u+2 0} AddCommGroup.{u+1}\n  (complex_shape.up.{0} \u2124).symm (-\u2191n)).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} \u2124)).map ((QprimeFP_int.{u} r' BD \u03ba M).map h)))).unop \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081) V.to_Cond).hom\n  :=\nbegin\n  dsimp only [functor.op_map, functor.comp_map],\n  erw [\u2190 functor.map_comp],\n  erw [\u2190 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\u2082 : \u211d\u22650} (n : \u2115) :\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond).hom \u226b\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 (-\u2191n) (by { cases n; refl})).hom.app\n  (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond) =\n  _\n-/\n\nend ExtQprime_iso_aux_system_obj_naturality_setup\n\nlemma QprimeFP_acyclic (c) (k i : \u2124) (hi : 0 < i) :\n  is_zero (((Ext' i).obj (op (((QprimeFP_int.{u} r' BD \u03ba M).obj c).X k))).obj V.to_Cond) :=\nbegin\n  rcases k with ((_|k)|k),\n  { apply free_acyclic, exact hi },\n  { rw [\u2190 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\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\n  (ExtQprime_iso_aux_system_obj r' BD \u03ba M V c\u2082 n).hom \u226b\n  (homology_functor _ _ _).map\n  ((system_of_complexes.to_Ab _).map h.op)  =\n  ((Ext n).map ((QprimeFP r' BD \u03ba _).map h).op).app _ \u226b\n  (ExtQprime_iso_aux_system_obj r' BD \u03ba M V c\u2081 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2081)).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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2082)).is_bounded_above :=\n    chain_complex.is_bounded_above _,\n  have := Ext_compute_with_acyclic_naturality\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2081)\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2082)\n    V.to_Cond _ _\n    ((QprimeFP_int.{u} r' BD \u03ba 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\u2081 r' BD \u03ba M V c\u2081 c\u2082 h n,\n  simp only [\u2190 category.assoc], congr' 1,\n  simp only [category.assoc],\n  rw ExtQprime_iso_aux_system_obj_naturality_setup.aux\u2082 r' BD \u03ba M V c\u2081 c\u2082 h n,\n  simp only [\u2190 category.assoc], congr' 1,\n\n  exact ExtQprime_iso_aux_system_obj_naturality_setup.aux\u2083 r' BD \u03ba M V c\u2081 c\u2082 h n,\n\n  --- OLD PROOF FROM HERE\n  --have := ExtQprime_iso_aux_system_obj_naturality_setup.naturality_helper r' BD \u03ba\n  --  M V h n _ _,\n  --simp only [category.assoc, functor.map_comp],\n  --slice_rhs 3 4\n  --{ erw \u2190 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 [\u2190 functor.map_comp, \u2190 functor.map_comp_assoc, category.assoc],\n  dsimp [-homology_functor_map],\n  rw ExtQprime_iso_aux_system_obj_naturality_setup.aux\u2081,\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 [\u2190 functor.comp_map, \u2190 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 : \u2115) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u2245\n  aux_system r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba \u22d9\n    (forget\u2082 _ Ab).map_homological_complex _ \u22d9 homology_functor _ _ n :=\nnat_iso.of_components (\u03bb c, ExtQprime_iso_aux_system_obj r' BD \u03ba M V (unop c) n)\nbegin\n  intros c\u2081 c\u2082 h,\n  dsimp [-homology_functor_map],\n  rw \u2190 ExtQprime_iso_aux_system_obj_natrality,\n  refl,\nend\n\n/-- The `Tinv` map induced by `M` -/\ndef ExtQprime.Tinv\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (n : \u2124) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u27f6\n  (QprimeFP r' BD \u03ba\u2082 M).op \u22d9 (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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (n : \u2124) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u27f6\n  (QprimeFP r' BD \u03ba\u2082 M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nwhisker_right (nat_trans.op $ QprimeFP.\u03b9 BD _ _ M) _ \u226b 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (n : \u2124) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u27f6\n  (QprimeFP r' BD \u03ba\u2082 M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nExtQprime.Tinv r' BD \u03ba \u03ba\u2082 M V n - ExtQprime.T_inv r r' BD \u03ba \u03ba\u2082 M V n\n\nnamespace ExtQprime_iso_aux_system_comm_Tinv_setup\n\nvariables (c : (\u211d\u22650)\u1d52\u1d56) (n : \u2115)\n  [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n\nlemma aux\u2081  :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n    (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V (unop.{1} c)).hom \u226b\n  ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n       (complex_shape.up.{0} \u2115) \u22d9\n     homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n    ((aux_system.Tinv.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba\u2082 \u03ba).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 \u03ba\u2082 \u03ba M).app _))) \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba\u2082 M V (unop.{1} c)).hom :=\nbegin\n  simp only [\u2190 functor.map_comp, functor.comp_map], congr' 1,\n  apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv,\nend\n\nlemma aux\u2082 :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n      (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj (unop.{1} c)) V.to_Cond).hom \u226b\n    (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down \u22d9\n       homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} \u2124) (-\u2191n)).map\n      (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex (complex_shape.down.{0} \u2115).symm).map\n         (homological_complex.op_functor.{u+2 u+1 0}.map ((QprimeFP_nat.Tinv.{u} BD \u03ba\u2082 \u03ba 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} \u2124) \u22d9\n        homological_complex.unop_functor.{u+2 u+1 0}.right_op \u22d9\n          (homology_functor.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).op).map\n       ((QprimeFP_int.Tinv.{u} BD \u03ba\u2082 \u03ba M).app (unop.{1} c))).unop \u226b\n    (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n      (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom :=\nbegin\n  dsimp only [functor.op_map, functor.comp_map],\n  erw [\u2190 functor.map_comp],\n  erw [\u2190 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] (n : \u2115) :\n  (ExtQprime_iso_aux_system r' BD \u03ba M V n).hom \u226b\n  whisker_right (aux_system.Tinv.{u} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba\u2082 \u03ba)\n    ((forget\u2082 _ _).map_homological_complex _ \u22d9 homology_functor Ab.{u+1} (complex_shape.up \u2115) n) =\n  ExtQprime.Tinv r' BD \u03ba \u03ba\u2082 M V n \u226b\n  (ExtQprime_iso_aux_system r' BD \u03ba\u2082 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba\u2082 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 \u03ba\u2082 M).obj c.unop)\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c.unop)\n    V.to_Cond _ _\n    ((QprimeFP_int.Tinv BD \u03ba\u2082 \u03ba 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\u2081 r' BD \u03ba \u03ba\u2082 M V c n,\n  simp only [\u2190 category.assoc], congr' 1, simp only [category.assoc],\n  erw \u2190 nat_trans.naturality,\n  simp only [\u2190 category.assoc], congr' 1,\n  exact ExtQprime_iso_aux_system_comm_Tinv_setup.aux\u2082 r' BD \u03ba \u03ba\u2082 M V c n,\nend\n\n\n-- lemma ExtQprime_iso_aux_system_comm_T_inv [normed_with_aut r V] (n : \u2115) (c : \u211d\u22650\u1d52\u1d56) :\n--   (ExtQprime_iso_aux_system_obj.{u} r' BD \u03ba\u2082 M V (unop.{1} c) n).hom \u226b\n--     ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex (complex_shape.up.{0} \u2115) \u22d9\n--    homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n--   ((aux_system.res.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba\u2082 \u03ba).app c) =\n--   ((Ext.{u+1 u+2} \u2191n).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 \u03ba\u2082 M).op.obj c) \u226b\n--     (ExtQprime_iso_aux_system_obj.{u} r' BD \u03ba\u2082 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\u2081 C\u2082 : homological_complex A\u1d52\u1d56 c) (f : C\u2081 \u27f6 C\u2082) :\n  C\u2082.unop \u27f6 C\u2081.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] [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 \u03ba c n)]\n\ndef hom_complex_map_T_inv (c : (\u211d\u22650)\u1d52\u1d56) :\n  hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj (unop.{1} c)) V.to_Cond \u27f6\n  hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 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 \u226b\n  (category_theory.functor.map _\n      (homological_complex.op_functor.map (quiver.hom.op $\n      (QprimeFP_nat.\u03b9 BD \u03ba\u2082 \u03ba M).app _)))\n\nomit r\n\nlemma embed_hom_complex_nat_iso\u2080 (c : (\u211d\u22650)\u1d52\u1d56) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom.f (int.of_nat 0) = \ud835\udfd9 _ := rfl\n\nlemma embed_hom_complex_nat_iso_neg (n : \u2115) (c : (\u211d\u22650)\u1d52\u1d56) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom.f (-[1+ n]) = \ud835\udfd9 _ := rfl\n\n\nlemma add_equiv.to_AddCommGroup_iso_apply (A B : AddCommGroup.{u})\n  (e : A \u2243+ 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\u2081 (c : (\u211d\u22650)\u1d52\u1d56):\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V (unop.{1} c)).hom \u226b\n  ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n     (complex_shape.up.{0} \u2115)).map ((aux_system.T_inv.{u u+1} r r' BD\n    \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba).app c \u226b\n  (aux_system.res.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba\u2082 \u03ba).app c) =\n  hom_complex_map_T_inv _ _ _ _ _ _ _ _ \u226b\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba\u2082 M V (unop.{1} c)).hom :=\nbegin\n  --simp only [\u2190 category_theory.functor.map_comp, functor.comp_map], congr' 1,\n  dsimp only [hom_complex_map_T_inv], simp only [category.assoc],\n  rw \u2190 hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_\u03ba r' BD \u03ba \u03ba\u2082 M V c.unop,\n  simp only [functor.map_comp, \u2190 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\u2082_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\u2082 (c : (\u211d\u22650)\u1d52\u1d56) :\n((((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} \u21a5V)).right_op.map_homological_complex\n         (complex_shape.up.{0} \u2124)).obj\n        ((QprimeFP_int.{u} r' BD \u03ba M).obj (unop.{1} c))).map_unop\n       (((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} \u21a5V)).right_op.map_homological_complex\n           (complex_shape.up.{0} \u2124)).obj\n          ((QprimeFP_int.{u} r' BD \u03ba 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} \u2124)).app\n          ((QprimeFP_int.{u} r' BD \u03ba M).obj (unop.{1} c))) \u226b\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} \u2124)).map\n           ((QprimeFP_int.\u03b9.{u} BD \u03ba\u2082 \u03ba M).app (unop.{1} c)))).unop) \u226b\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom =\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj (unop.{1} c)) V.to_Cond).hom \u226b\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\u2080,\n  rw embed_hom_complex_nat_iso\u2080,\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 \u2124)\n  [((homotopy_category.quotient A (complex_shape.up.{0} \u2124)).obj X).is_bounded_above]\n  {B\u2081 B\u2082 : A} (f : B\u2081 \u27f6 B\u2082) -- (h\u2081) (h\u2082) (i)\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux\u2081_naturality_snd_var (i)\n  (e : (0 : \u2124) - i = -i) :\n  (Ext_compute_with_acyclic_aux\u2081 X B\u2081 i).hom \u226b\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) \u226b\n  (Ext_compute_with_acyclic_aux\u2081 X B\u2082 i).hom :=\nbegin\n  ext t,\n  simp only [comp_apply],\n  dsimp [Ext_compute_with_acyclic_aux\u2081, Ext],\n  simp only [category.assoc],\n  generalize_proofs h1 h2,\n  let \u03c6\u2081 := \u03bb j, (single _ j).obj B\u2081,\n  let \u03c6\u2082 := \u03bb j, (single _ j).obj B\u2082,\n  change t \u226b _ \u226b eq_to_hom (congr_arg \u03c6\u2081 e) \u226b _ =\n    _ \u226b _ \u226b _ \u226b eq_to_hom (congr_arg \u03c6\u2082 e),\n  induction e,\n  dsimp, simp only [category.id_comp, category.comp_id],\n  erw \u2190 nat_trans.naturality,\n  refl,\nend\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux\u2082_naturality_snd_var (i) :\n  (Ext_compute_with_acyclic_aux\u2082 X B\u2081 i).hom \u226b\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) _ \u226b\n  (Ext_compute_with_acyclic_aux\u2082 X B\u2082 i).hom :=\nbegin\n  dsimp only [Ext_compute_with_acyclic_aux\u2082, unop_op],\n  have := hom_single_iso_naturality_snd_var_good (of' X).replace (-i) f,\n  erw \u2190 this,\nend\n\ninclude f\nlemma Ext_compute_with_acyclic_aux\u2083_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 \u226b Ext_compute_with_acyclic_aux\u2083 X B\u2082 i =\n  Ext_compute_with_acyclic_aux\u2083 X B\u2081 i \u226b\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\u2083],\n  erw \u2190 (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n    (complex_shape.up.{0} \u2124).symm (-i)).map_comp,\n  erw \u2190 (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n    (complex_shape.up.{0} \u2124).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\u2081) (h\u2082) (i) :\n  (Ext_compute_with_acyclic X B\u2081 h\u2081 i).hom \u226b\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) \u226b (Ext_compute_with_acyclic X B\u2082 h\u2082 i).hom :=\nbegin\n  dsimp [Ext_compute_with_acyclic, - homology_functor_map],\n  simp only [category.assoc],\n  rw \u2190 Ext_compute_with_acyclic_aux\u2081_naturality_snd_var_assoc,\n  rw \u2190 Ext_compute_with_acyclic_aux\u2082_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\u2083_naturality_snd_var,\n  simp,\nend\n\nend naturality_snd_var\n\nlemma ExtQprime_iso_aux_system_comm [normed_with_aut r V]\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] (n : \u2115) :\n  (ExtQprime_iso_aux_system r' BD \u03ba M V n).hom \u226b\n  whisker_right (aux_system.Tinv2.{u} r r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba\u2082 \u03ba)\n    ((forget\u2082 _ _).map_homological_complex _ \u22d9 homology_functor Ab.{u+1} (complex_shape.up \u2115) n) =\n  ExtQprime.Tinv2 r r' BD \u03ba \u03ba\u2082 M V n \u226b\n  (ExtQprime_iso_aux_system r' BD \u03ba\u2082 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 [\u2190 nat_trans.comp_app, \u2190 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba\u2082 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 \u03ba\u2082 M).obj c.unop)\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c.unop)\n    V.to_Cond _ _\n    ((QprimeFP_int.\u03b9 BD \u03ba\u2082 \u03ba 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 \u03b7 := (Ext.{u+1 u+2} \u2191n).map ((nat_trans.op.{0 u+1 0 u+2} (QprimeFP.\u03b9.{u} BD \u03ba\u2082 \u03ba M)).app c),\n\n  slice_rhs 1 2 { erw \u2190 \u03b7.naturality },\n  slice_rhs 2 3 { erw this },\n  simp only [category.assoc], clear this \u03b7,\n\n  let t : Condensed.of_top_ab V \u27f6 _ :=\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 \u03ba 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 \u2190 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 \u2190 category_theory.functor.map_comp },\n  slice_lhs 4 5 { rw \u2190 category_theory.functor.map_comp },\n  simp only [category.assoc,\n    \u2190 category_theory.functor.map_comp, \u2190 functor.map_comp_assoc],\n\n  rw ExtQprime_iso_aux_system_comm_setup.aux\u2081 r r' BD \u03ba \u03ba\u2082 M V c,\n  slice_lhs 2 4\n  { simp only [category_theory.functor.map_comp] },\n\n  simp only [\u2190 category.assoc], congr' 1,\n\n  rw ExtQprime_iso_aux_system_comm_setup.aux\u2082 r r' BD \u03ba \u03ba\u2082 M V c,\n  simp only [category_theory.functor.map_comp, category.assoc],\n  congr' 1,\n\n  rw [nat_iso.app_hom, \u2190 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] (n : \u2115) :\n  whisker_right (aux_system.Tinv2.{u} r r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba\u2082 \u03ba)\n    ((forget\u2082 _ _).map_homological_complex _ \u22d9 homology_functor Ab.{u+1} (complex_shape.up \u2115) n) \u226b\n  (ExtQprime_iso_aux_system r' BD \u03ba\u2082 M V n).inv =\n  (ExtQprime_iso_aux_system r' BD \u03ba M V n).inv \u226b\n  ExtQprime.Tinv2 r r' BD \u03ba \u03ba\u2082 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 \u2964 D) {X Y Z W : C}\n  {f\u2081 : X \u27f6 Y} {g\u2081 : X \u27f6 Z} {g\u2082 : Y \u27f6 W} {f\u2082 : Z \u27f6 W} (sq : commsq f\u2081 g\u2081 g\u2082 f\u2082) :\n  commsq (F.map f\u2081) (F.map g\u2081) (F.map g\u2082) (F.map f\u2082) :=\ncommsq.of_eq $ by rw [\u2190 F.map_comp, sq.w, F.map_comp]\n\nend\n\nsection\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{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 \u2124)).obj\n    ((BD.eval' freeCond').obj M.to_Condensed)).is_bounded_above :=\nby { delta breen_deligne.package.eval', refine \u27e8\u27e81, _\u27e9\u27e9, apply chain_complex.bounded_by_one }\n\nvariables (\u03b9 : ulift.{u+1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9)\n\ndef Ext_Tinv2\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A B V : bounded_homotopy_category \ud835\udcd0}\n  (Tinv : A \u27f6 B) (\u03b9 : A \u27f6 B) (T_inv : V \u27f6 V) (i : \u2124) :\n  ((Ext i).obj (op B)).obj V \u27f6 ((Ext i).obj (op A)).obj V :=\n(((Ext i).map Tinv.op).app V - (((Ext i).map \u03b9.op).app V \u226b ((Ext i).obj _).map T_inv))\n\nopen category_theory.preadditive\n\ndef Ext_Tinv2_commsq\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A\u2081 B\u2081 A\u2082 B\u2082 V : bounded_homotopy_category \ud835\udcd0}\n  (Tinv\u2081 : A\u2081 \u27f6 B\u2081) (\u03b9\u2081 : A\u2081 \u27f6 B\u2081)\n  (Tinv\u2082 : A\u2082 \u27f6 B\u2082) (\u03b9\u2082 : A\u2082 \u27f6 B\u2082)\n  (f : A\u2081 \u27f6 A\u2082) (g : B\u2081 \u27f6 B\u2082) (sqT : f \u226b Tinv\u2082 = Tinv\u2081 \u226b g) (sq\u03b9 : f \u226b \u03b9\u2082 = \u03b9\u2081 \u226b g)\n  (T_inv : V \u27f6 V) (i : \u2124) :\n  commsq\n    (((Ext i).map g.op).app V)\n    (Ext_Tinv2 Tinv\u2082 \u03b9\u2082 T_inv i)\n    (Ext_Tinv2 Tinv\u2081 \u03b9\u2081 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, \u2190 nat_trans.comp_app, \u2190 functor.map_comp, \u2190 op_comp, sqT,\n    \u2190 nat_trans.naturality, \u2190 nat_trans.naturality_assoc, category.assoc, sq\u03b9],\nend\n\nopen category_theory.preadditive\n\nlemma auux\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A\u2081 B\u2081 A\u2082 B\u2082 : cochain_complex \ud835\udcd0 \u2124}\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2082).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2082).is_bounded_above]\n  {f\u2081 : A\u2081 \u27f6 B\u2081} {f\u2082 : A\u2082 \u27f6 B\u2082} {\u03b1 : A\u2081 \u27f6 A\u2082} {\u03b2 : B\u2081 \u27f6 B\u2082}\n  (sq1 : commsq f\u2081 \u03b1 \u03b2 f\u2082) :\n  of_hom f\u2081 \u226b of_hom \u03b2 = of_hom \u03b1 \u226b of_hom f\u2082 :=\nbegin\n  have := sq1.w,\n  apply_fun (\u03bb 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  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A : cochain_complex \ud835\udcd0 \u2124}\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A).is_bounded_above] :\n  of_hom (\ud835\udfd9 A) = \ud835\udfd9 _ :=\nby { delta of_hom, rw [category_theory.functor.map_id], refl }\n\nlemma Ext_iso_of_bicartesian_of_bicartesian\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A\u2081 B\u2081 C A\u2082 B\u2082 : cochain_complex \ud835\udcd0 \u2124}\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj C).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2082).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2082).is_bounded_above]\n  {f\u2081 : A\u2081 \u27f6 B\u2081} {g\u2081 : B\u2081 \u27f6 C} (w\u2081 : \u2200 n, short_exact (f\u2081.f n) (g\u2081.f n))\n  {f\u2082 : A\u2082 \u27f6 B\u2082} {g\u2082 : B\u2082 \u27f6 C} (w\u2082 : \u2200 n, short_exact (f\u2082.f n) (g\u2082.f n))\n  (\u03b1 : A\u2081 \u27f6 A\u2082) (\u03b2 : B\u2081 \u27f6 B\u2082) (\u03b3 : C \u27f6 C)\n  (\u03b9A : A\u2081 \u27f6 A\u2082) (\u03b9B : B\u2081 \u27f6 B\u2082)\n  (sq1 : commsq f\u2081 \u03b1 \u03b2 f\u2082) (sq2 : commsq g\u2081 \u03b2 \u03b3 g\u2082)\n  (sq1' : commsq f\u2081 \u03b9A \u03b9B f\u2082) (sq2' : commsq g\u2081 \u03b9B (\ud835\udfd9 _) g\u2082)\n  (V : bounded_homotopy_category \ud835\udcd0) (T_inv : V \u27f6 V)\n  (i : \u2124)\n  (H1 : (Ext_Tinv2_commsq (of_hom \u03b1) (of_hom \u03b9A) (of_hom \u03b2) (of_hom \u03b9B) (of_hom f\u2081) (of_hom f\u2082)\n    (auux sq1) (auux sq1') T_inv i).bicartesian)\n  (H2 : (Ext_Tinv2_commsq (of_hom \u03b1) (of_hom \u03b9A) (of_hom \u03b2) (of_hom \u03b9B) (of_hom f\u2081) (of_hom f\u2082)\n    (auux sq1) (auux sq1') T_inv (i+1)).bicartesian) :\n  is_iso (Ext_Tinv2 (of_hom \u03b3) (\ud835\udfd9 _) T_inv (i+1)) :=\nbegin\n  have LES\u2081 := (((Ext_five_term_exact_seq' _ _ i V w\u2081).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w\u2081)),\n  replace LES\u2081 := (((Ext_five_term_exact_seq' _ _ i V w\u2081).drop 1).pair.cons LES\u2081).extract 0 4,\n  have LES\u2082 := (((Ext_five_term_exact_seq' _ _ i V w\u2082).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w\u2082)).extract 0 4,\n  replace LES\u2082 := (((Ext_five_term_exact_seq' _ _ i V w\u2082).drop 1).pair.cons LES\u2082).extract 0 4,\n  refine iso_of_bicartesian_of_bicartesian LES\u2082 LES\u2081 _ _ _ _ H1 H2,\n  { apply commsq.of_eq, delta Ext_Tinv2, clear LES\u2081 LES\u2082,\n    rw [sub_comp, comp_sub, \u2190 functor.flip_obj_map, \u2190 functor.flip_obj_map],\n    rw \u2190 Ext_\u03b4_natural i V _ _ _ _ \u03b1 \u03b2 \u03b3 sq1.w sq2.w w\u2081 w\u2082,\n    congr' 1,\n    rw [\u2190 nat_trans.naturality, \u2190 functor.flip_obj_map, category.assoc,\n      Ext_\u03b4_natural i V _ _ _ _ \u03b9A \u03b9B (\ud835\udfd9 _) sq1'.w sq2'.w w\u2081 w\u2082],\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_\u03b4_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": "meta def get_file (fn : name) : vm format :=\ndo {\n  d \u2190 vm.get_decl fn,\n  some n \u2190 return (vm_decl.olean d) | failure,\n  return (to_fmt n)\n}\n<|>\nreturn (to_fmt \"<curr file>\")\n\nmeta def pos_info (fn : name) : vm format :=\ndo {\n  d        \u2190 vm.get_decl fn,\n  some pos \u2190 return (vm_decl.pos d) | failure,\n  file             \u2190 get_file fn,\n  return (file ++ \":\" ++ pos.1 ++ \":\" ++ pos.2)\n}\n<|>\nreturn (to_fmt \"<position not available>\")\n\nmeta def obj_fmt (o : vm_obj) : vm format :=\nmatch o^.kind with\n| vm_obj_kind.tactic_state :=\n     return (to_fmt \"state:\" ++ format.nest 8 (format.line ++ o^.to_tactic_state^.to_format))\n| _ := do s \u2190 vm.obj_to_string o, return $ to_fmt s\nend\n\nmeta def display_args_aux : nat \u2192 vm unit\n| i := do\n   sz \u2190 vm.stack_size,\n   if i = sz then return ()\n   else do\n     o \u2190 vm.stack_obj i,\n     (n, t) \u2190 vm.stack_obj_info i,\n     fmt \u2190 obj_fmt o,\n     vm.trace (to_fmt \"  \" ++ to_fmt n ++ \" := \" ++ fmt),\n     display_args_aux (i+1)\n\nmeta def display_args : vm unit :=\ndo bp \u2190 vm.bp,\n   display_args_aux bp\n\n@[vm_monitor]\nmeta def basic_monitor : vm_monitor nat :=\n{ init := 1000,\n  step := \u03bb sz, do\n    csz \u2190 vm.call_stack_size,\n    if sz = csz then return sz\n    else\n      do {\n      fn  \u2190 vm.curr_fn,\n      pos \u2190 pos_info fn,\n      vm.trace (to_fmt \"[\" ++ csz ++ \"]: \" ++ to_fmt fn ++ \" @ \" ++ pos),\n      display_args,\n      return csz\n      }\n      <|>\n      return csz -- curr_fn failed\n}\n\n\nset_option debugger true\nopen tactic\n\nexample (a b : Prop) : a \u2192 b \u2192 a \u2227 b :=\nby (intros >> constructor >> repeat assumption)", "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/tests/basic_monitor3.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.0367694634367915, "lm_q1q2_score": 0.009118364601923166}}
{"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) : \u2115 :=\n  string.fold 1 (fun (h : \u2115) (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 \u2192 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 \u00d7 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 : \u2115 := 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 \u00d7 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 : \u2115) (f : \u2115 \u2192 \u2115) (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 : \u2115 \u2192 \u2115) (x : \u2115)\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 <https://leanprover-community.github.io/extras/conv.html> 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 : \u2115) (h\u2081 : b = c) (h\u2082 : a + c = a + d) : a + b = a + d :=\nby conv {\n  to_lhs,\n  conv {\n    congr, skip,\n    rw h\u2081,\n  },\n  rw h\u2082,\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": "/-\nCopyright (c) 2018 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Sebastian Ullrich\n\nTerm-Level parsers\n-/\nprelude\nimport init.lean.parser.level init.lean.parser.notation\nimport init.lean.expr\n\nnamespace Lean\nnamespace Parser\nopen Combinators Parser.HasView MonadParsec\n\nlocal postfix `?`:10000 := optional\nlocal postfix *:10000 := Combinators.many\nlocal postfix +:10000 := Combinators.many1\n\nset_option class.instance_max_depth 200\n\n@[derive Parser.HasTokens Parser.HasView]\ndef identUnivSpec.Parser : basicParser :=\nnode! identUnivSpec [\".{\", levels: Level.Parser+, \"}\"]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef identUnivs.Parser : termParser :=\nnode! identUnivs [id: ident.Parser, univs: (monadLift identUnivSpec.Parser)?]\n\nnamespace Term\n/-- Access leading Term -/\ndef getLeading : trailingTermParser := read\ninstance : HasTokens getLeading := default _\ninstance : HasView Syntax getLeading := default _\n\n@[derive Parser.HasTokens Parser.HasView]\ndef paren.Parser : termParser :=\nnode! \u00abparen\u00bb [\"(\":maxPrec,\n  content: node! parenContent [\n    Term: Term.Parser,\n    special: nodeChoice! parenSpecial {\n      /- Do not allow trailing comma. Looks a bit weird and would clash with\n      adding support for tuple sections (https://downloads.haskell.org/~ghc/8.2.1/docs/html/usersGuide/glasgowExts.html#tuple-sections). -/\n      tuple: node! tuple [\", \", tail: sepBy (Term.Parser 0) (symbol \", \") false],\n      typed: node! typed [\" : \", type: Term.Parser],\n    }?,\n  ]?,\n  \")\"\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef hole.Parser : termParser :=\nnode! hole [hole: symbol \"_\" maxPrec]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef sort.Parser : termParser :=\nnodeChoice! sort {\"Sort\":maxPrec, \"Type\":maxPrec}\n\n@[derive HasTokens HasView]\ndef typeSpec.Parser : termParser :=\nnode! typeSpec [\" : \", type: Term.Parser 0]\n\n@[derive HasTokens HasView]\ndef optType.Parser : termParser :=\ntypeSpec.Parser?\n\ninstance optType.viewDefault : HasViewDefault optType.Parser _ none := \u27e8\u27e9\n\nsection binder\n@[derive HasTokens HasView]\ndef binderIdent.Parser : termParser :=\nnodeChoice! binderIdent {id: ident.Parser, hole: hole.Parser}\n\n@[derive HasTokens HasView]\ndef binderDefault.Parser : termParser :=\nnodeChoice! binderDefault {\n  val: node! binderDefaultVal [\":=\", Term: Term.Parser 0],\n  tac: node! binderDefaultTac [\".\", Term: Term.Parser 0],\n}\n\n@[derive HasTokens HasView]\ndef binderContent.Parser (requireType := false) : termParser :=\nnode! binderContent [\n  ids: binderIdent.Parser+,\n  type: optional typeSpec.Parser requireType,\n  default: binderDefault.Parser?\n]\n\n@[derive HasTokens HasView]\ndef simpleBinder.Parser : termParser :=\nnodeChoice! simpleBinder {\n  explicit: node! simpleExplicitBinder [\"(\", id: ident.Parser, \" : \", type: Term.Parser 0, right: symbol \")\"],\n  implicit: node! simpleImplicitBinder [\"{\", id: ident.Parser, \" : \", type: Term.Parser 0, right: symbol \"}\"],\n  strictImplicit: node! simpleStrictImplicitBinder [\"\u2983\", id: ident.Parser, \" : \", type: Term.Parser 0, right: symbol \"\u2984\"],\n  instImplicit: node! simpleInstImplicitBinder [\"[\", id: ident.Parser, \" : \", type: Term.Parser 0, right: symbol \"]\"],\n}\n\ndef simpleBinder.View.toBinderInfo : simpleBinder.View \u2192 (BinderInfo \u00d7 SyntaxIdent \u00d7 Syntax)\n| (simpleBinder.View.explicit {id := id, type := type})       := (BinderInfo.default, id, type)\n| (simpleBinder.View.implicit {id := id, type := type})       := (BinderInfo.implicit, id, type)\n| (simpleBinder.View.strictImplicit {id := id, type := type}) := (BinderInfo.strictImplicit, id, type)\n| (simpleBinder.View.instImplicit {id := id, type := type})   := (BinderInfo.instImplicit, id, type)\n\n@[derive Parser.HasTokens Parser.HasView]\ndef anonymousConstructor.Parser : termParser :=\nnode! anonymousConstructor [\"\u27e8\":maxPrec, args: sepBy (Term.Parser 0) (symbol \",\"), \"\u27e9\"]\n\n/- All binders must be surrounded with some kind of bracket. (e.g., '()', '{}', '[]').\n   We use this feature when parsing examples/definitions/theorems. The goal is to avoid counter-intuitive\n   declarations such as:\n\n     example p : False := trivial\n     def main proof : False := trivial\n\n   which would be parsed as\n\n     example (p : False) : _ := trivial\n\n     def main (proof : False) : _ := trivial\n\n   where `_` in both cases is elaborated into `True`. This issue was raised by @gebner in the slack channel.\n\n\n   Remark: we still want implicit delimiters for lambda/pi expressions. That is, we want to\n   write\n\n       fun x : t, s\n   or\n       fun x, s\n\n   instead of\n\n       fun (x : t), s -/\n@[derive HasTokens HasView]\ndef bracketedBinder.Parser (requireType := false) : termParser :=\nnodeChoice! bracketedBinder {\n  explicit: node! explicitBinder [\"(\", content: nodeChoice! explicitBinderContent {\n    \u00abnotation\u00bb: command.notationLike.Parser,\n    other: binderContent.Parser requireType\n  }, right: symbol \")\"],\n  implicit: node! implicitBinder [\"{\", content: binderContent.Parser, \"}\"],\n  strictImplicit: node! strictImplicitBinder [\"\u2983\", content: binderContent.Parser, \"\u2984\"],\n  instImplicit: node! instImplicitBinder [\"[\", content: nodeLongestChoice! instImplicitBinderContent {\n    named: node! instImplicitNamedBinder [id: ident.Parser, \" : \", type: Term.Parser 0],\n    anonymous: node! instImplicitAnonymousBinder [type: Term.Parser 0]\n  }, \"]\"],\n  anonymousConstructor: anonymousConstructor.Parser,\n}\n\n@[derive HasTokens HasView]\ndef binder.Parser : termParser :=\nnodeChoice! binder {\n  bracketed: bracketedBinder.Parser,\n  unbracketed: binderContent.Parser,\n}\n\n@[derive HasTokens HasView]\ndef bindersExt.Parser : termParser :=\nnode! bindersExt [\n  leadingIds: binderIdent.Parser*,\n  remainder: nodeChoice! bindersRemainder {\n    type: node! bindersTypes [\":\", type: Term.Parser 0],\n    -- we allow mixing like in `a (b : \u03b2) c`, but not `a : \u03b1 (b : \u03b2) c : \u03b3`\n    mixed: nodeChoice! mixedBinder {\n      bracketed: bracketedBinder.Parser,\n      id: binderIdent.Parser,\n    }+,\n  }?\n]\n\n/-- We normalize binders to simpler singleton ones during expansion. -/\n@[derive HasTokens HasView]\ndef binders.Parser : termParser :=\nnodeChoice! binders {\n  extended: bindersExt.Parser,\n  -- a strict subset of `extended`, so only useful after parsing\n  simple: simpleBinder.Parser,\n}\n\n/-- We normalize binders to simpler ones during expansion. These always-bracketed\n    binders are used in declarations and cannot be reduced to nested singleton binders. -/\n@[derive HasTokens HasView]\ndef bracketedBinders.Parser : termParser :=\nnodeChoice! bracketedBinders {\n  extended: bracketedBinder.Parser*,\n  -- a strict subset of `extended`, so only useful after parsing\n  simple: simpleBinder.Parser*,\n}\nend binder\n\n@[derive Parser.HasTokens Parser.HasView]\ndef lambda.Parser : termParser :=\nnode! lambda [\n  op: unicodeSymbol \"\u03bb\" \"fun\" maxPrec,\n  binders: binders.Parser,\n  \",\",\n  body: Term.Parser 0\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef assume.Parser : termParser :=\nnode! \u00abassume\u00bb [\n  \"assume \":maxPrec,\n  binders: nodeChoice! assumeBinders {\n    anonymous: node! assumeAnonymous [\": \", type: Term.Parser],\n    binders: binders.Parser\n  },\n  \", \",\n  body: Term.Parser 0\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef pi.Parser : termParser :=\nnode! pi [\n  op: anyOf [unicodeSymbol \"\u03a0\" \"Pi\" maxPrec, unicodeSymbol \"\u2200\" \"forall\" maxPrec],\n  binders: binders.Parser,\n  \",\",\n  range: Term.Parser 0\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef explicit.Parser : termParser :=\nnode! explicit [\n  mod: nodeChoice! explicitModifier {\n    explicit: symbol \"@\" maxPrec,\n    partialExplicit: symbol \"@@\" maxPrec\n  },\n  id: identUnivs.Parser\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef from.Parser : termParser :=\nnode! \u00abfrom\u00bb [\"from \", proof: Term.Parser]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef let.Parser : termParser :=\nnode! \u00ablet\u00bb [\n  \"let \",\n  lhs: nodeChoice! letLhs {\n    id: node! letLhsId [\n      id: ident.Parser,\n      -- NOTE: after expansion, binders are Empty\n      binders: bracketedBinder.Parser*,\n      type: optType.Parser,\n    ],\n    pattern: Term.Parser\n  },\n  \" := \",\n  value: Term.Parser,\n  \" in \",\n  body: Term.Parser,\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef optIdent.Parser : termParser :=\n(try node! optIdent [id: ident.Parser, \" : \"])?\n\n@[derive Parser.HasTokens Parser.HasView]\ndef have.Parser : termParser :=\nnode! \u00abhave\u00bb [\n  \"have \",\n  id: optIdent.Parser,\n  prop: Term.Parser,\n  proof: nodeChoice! haveProof {\n    Term: node! haveTerm [\" := \", Term: Term.Parser],\n    \u00abfrom\u00bb: node! haveFrom [\", \", \u00abfrom\u00bb: from.Parser],\n  },\n  \", \",\n  body: Term.Parser,\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef show.Parser : termParser :=\nnode! \u00abshow\u00bb [\n  \"show \",\n  prop: Term.Parser,\n  \", \",\n  \u00abfrom\u00bb: from.Parser,\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef match.Parser : termParser :=\nnode! \u00abmatch\u00bb [\n  \"match \",\n  scrutinees: sepBy1 Term.Parser (symbol \", \") false,\n  type: optType.Parser,\n  \" with \",\n  optBar: (symbol \" | \")?,\n  equations: sepBy1\n    node! \u00abmatchEquation\u00bb [\n      lhs: sepBy1 Term.Parser (symbol \", \") false, \":=\", rhs: Term.Parser]\n    (symbol \" | \") false,\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef if.Parser : termParser :=\nnode! \u00abif\u00bb [\n  \"if \",\n  id: optIdent.Parser,\n  prop: Term.Parser,\n  \" then \",\n  thenBranch: Term.Parser,\n  \" else \",\n  elseBranch: Term.Parser,\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef structInst.Parser : termParser :=\nnode! structInst [\n  \"{\":maxPrec,\n  type: (try node! structInstType [id: ident.Parser, \" . \"])?,\n  \u00abwith\u00bb: (try node! structInstWith [source: Term.Parser, \" with \"])?,\n  items: sepBy nodeChoice! structInstItem {\n    field: node! structInstField [id: ident.Parser, \" := \", val: Term.Parser],\n    source: node! structInstSource [\"..\", source: Term.Parser?],\n  } (symbol \", \"),\n  \"}\",\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef Subtype.Parser : termParser :=\nnode! Subtype [\n  \"{\":maxPrec,\n  id: ident.Parser,\n  type: optType.Parser,\n  \"//\",\n  prop: Term.Parser,\n  \"}\"\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef inaccessible.Parser : termParser :=\nnode! inaccessible [\".(\":maxPrec, Term: Term.Parser, \")\"]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef anonymousInaccessible.Parser : termParser :=\nnode! anonymousInaccessible [\"._\":maxPrec]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef sorry.Parser : termParser :=\nnode! \u00absorry\u00bb [\"sorry\":maxPrec]\n\ndef borrowPrec := maxPrec - 1\n@[derive Parser.HasTokens Parser.HasView]\ndef borrowed.Parser : termParser :=\nnode! borrowed [\"@&\":maxPrec, Term: Term.Parser borrowPrec]\n\n--- Agda's `(x : e) \u2192 f`\n@[derive Parser.HasTokens Parser.HasView]\ndef depArrow.Parser : termParser :=\nnode! depArrow [binder: bracketedBinder.Parser true, op: unicodeSymbol \"\u2192\" \"->\" 25, range: Term.Parser 24]\n\n-- TODO(Sebastian): replace with attribute\n@[derive HasTokens]\ndef builtinLeadingParsers : TokenMap termParser := TokenMap.ofList [\n  (`ident, identUnivs.Parser),\n  (number.name, number.Parser),\n  (stringLit.name, stringLit.Parser),\n  (\"(\", paren.Parser),\n  (\"(\", depArrow.Parser),\n  (\"_\", hole.Parser),\n  (\"Sort\", sort.Parser),\n  (\"Type\", sort.Parser),\n  (\"\u03bb\", lambda.Parser),\n  (\"fun\", lambda.Parser),\n  (\"\u03a0\", pi.Parser),\n  (\"Pi\", pi.Parser),\n  (\"\u2200\", pi.Parser),\n  (\"forall\", pi.Parser),\n  (\"\u27e8\", anonymousConstructor.Parser),\n  (\"@\", explicit.Parser),\n  (\"@@\", explicit.Parser),\n  (\"let\", let.Parser),\n  (\"have\", have.Parser),\n  (\"show\", show.Parser),\n  (\"assume\", assume.Parser),\n  (\"match\", match.Parser),\n  (\"if\", if.Parser),\n  (\"{\", structInst.Parser),\n  (\"{\", Subtype.Parser),\n  (\"{\", depArrow.Parser),\n  (\"[\", depArrow.Parser),\n  (\".(\", inaccessible.Parser),\n  (\"._\", anonymousInaccessible.Parser),\n  (\"sorry\", sorry.Parser),\n  (\"@&\", borrowed.Parser)\n]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef sortApp.Parser : trailingTermParser :=\ndo { l \u2190 getLeading, guard $ l.isOfKind sort } *>\nnode! sortApp [fn: getLeading, Arg: monadLift (Level.Parser maxPrec).run]\n\n@[derive Parser.HasTokens Parser.HasView]\ndef app.Parser : trailingTermParser :=\nnode! app [fn: getLeading, Arg: Term.Parser maxPrec]\n\ndef mkApp (fn : Syntax) (args : List Syntax) : Syntax :=\nargs.foldl (\u03bb fn Arg, Syntax.mkNode app [fn, Arg]) fn\n\n@[derive Parser.HasTokens Parser.HasView]\ndef arrow.Parser : trailingTermParser :=\nnode! arrow [dom: getLeading, op: unicodeSymbol \"\u2192\" \"->\" 25, range: Term.Parser 24]\n\n@[derive Parser.HasView]\ndef projection.Parser : trailingTermParser :=\ntry $ node! projection [\n  Term: getLeading,\n  -- do not consume trailing whitespace\n  \u00ab.\u00bb: rawStr \".\",\n  proj: nodeChoice! projectionSpec {\n    id: Parser.ident.Parser,\n    num: number.Parser,\n  },\n]\n\n-- register '.' manually because of `rawStr`\ninstance projection.tokens : HasTokens projection.Parser :=\n/- Use maxPrec + 1 so that it bind more tightly than application:\n   `a (b).c` should be parsed as `a ((b).c)`. -/\n\u27e8[{\u00abprefix\u00bb := \".\", lbp := maxPrec.succ}]\u27e9\n\n@[derive HasTokens]\ndef builtinTrailingParsers : TokenMap trailingTermParser := TokenMap.ofList [\n  (\"\u2192\", arrow.Parser),\n  (\"->\", arrow.Parser),\n  (\".\", projection.Parser)\n]\n\nend Term\n\nprivate def trailing (cfg : CommandParserConfig) : trailingTermParser :=\n-- try local parsers first, starting with the newest one\n(do ps \u2190 indexed cfg.localTrailingTermParsers, ps.foldr (<|>) (error \"\"))\n<|>\n-- next try all non-local parsers\n(do ps \u2190 indexed cfg.trailingTermParsers, longestMatch ps)\n<|>\n-- The application parsers should only be tried as a fall-back;\n-- e.g. `a + b` should not be parsed as `a (+ b)`.\n-- TODO(Sebastian): We should be able to remove this workaround using\n-- the proposed more robust precedence handling\nanyOf [Term.sortApp.Parser, Term.app.Parser]\n\nprivate def leading (cfg : CommandParserConfig) : termParser :=\n(do ps \u2190 indexed cfg.localLeadingTermParsers, ps.foldr (<|>) (error \"\"))\n<|>\n(do ps \u2190 indexed cfg.leadingTermParsers, longestMatch ps)\n\ndef termParser.run (p : termParser) : commandParser :=\ndo cfg \u2190 read,\n   adaptReader coe $ prattParser (leading cfg) (trailing cfg) p\n\nend Parser\nend Lean\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/tmp/new-frontend/parser/term.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2628418489200747, "lm_q2_score": 0.03461883672266573, "lm_q1q2_score": 0.009099279051647641}}
{"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, Sebastian Ullrich\n-/\nimport Std.ShareCommon\nimport Lean.Parser.Command\nimport Lean.Util.CollectLevelParams\nimport Lean.Util.FoldConsts\nimport Lean.Meta.ForEachExpr\nimport Lean.Meta.CollectFVars\nimport Lean.Elab.Command\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.Binders\nimport Lean.Elab.DeclUtil\nnamespace Lean.Elab\n\ninductive DefKind where\n  | \u00abdef\u00bb | \u00abtheorem\u00bb | \u00abexample\u00bb | \u00abopaque\u00bb | \u00ababbrev\u00bb\n  deriving Inhabited, BEq\n\ndef DefKind.isTheorem : DefKind \u2192 Bool\n  | \u00abtheorem\u00bb => true\n  | _         => false\n\ndef DefKind.isDefOrAbbrevOrOpaque : DefKind \u2192 Bool\n  | \u00abdef\u00bb    => true\n  | \u00abopaque\u00bb => true\n  | \u00ababbrev\u00bb => true\n  | _        => false\n\ndef DefKind.isExample : DefKind \u2192 Bool\n  | \u00abexample\u00bb => true\n  | _         => false\n\nstructure DefView where\n  kind          : DefKind\n  ref           : Syntax\n  modifiers     : Modifiers\n  declId        : Syntax\n  binders       : Syntax\n  type?         : Option Syntax\n  value         : Syntax\n  deriving?     : Option (Array Syntax) := none\n  deriving Inhabited\n\nnamespace Command\n\nopen Meta\n\ndef mkDefViewOfAbbrev (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\n  let (binders, type) := expandOptDeclSig stx[2]\n  let modifiers       := modifiers.addAttribute { name := `inline }\n  let modifiers       := modifiers.addAttribute { name := `reducible }\n  { ref := stx, kind := DefKind.abbrev, modifiers,\n    declId := stx[1], binders, type? := type, value := stx[3] }\n\ndef mkDefViewOfDef (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"def \" >> declId >> optDeclSig >> declVal >> optDefDeriving\n  let (binders, type) := expandOptDeclSig stx[2]\n  let deriving? := if stx[4].isNone then none else some stx[4][1].getSepArgs\n  { ref := stx, kind := DefKind.def, modifiers,\n    declId := stx[1], binders, type? := type, value := stx[3], deriving? }\n\ndef mkDefViewOfTheorem (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"theorem \" >> declId >> declSig >> declVal\n  let (binders, type) := expandDeclSig stx[2]\n  { ref := stx, kind := DefKind.theorem, modifiers,\n    declId := stx[1], binders, type? := some type, value := stx[3] }\n\ndef mkFreshInstanceName : CommandElabM Name := do\n  let s \u2190 get\n  let idx := s.nextInstIdx\n  modify fun s => { s with nextInstIdx := s.nextInstIdx + 1 }\n  return Lean.Elab.mkFreshInstanceName s.env idx\n\n/--\n  Generate a name for an instance with the given type.\n  Note that we elaborate the type twice. Once for producing the name, and another when elaborating the declaration. -/\ndef mkInstanceName (binders : Array Syntax) (type : Syntax) : CommandElabM Name := do\n  let savedState \u2190 get\n  try\n    let result \u2190 runTermElabM `inst fun _ => Term.withAutoBoundImplicit <| Term.elabBinders binders fun _ => Term.withoutErrToSorry do\n      let type \u2190 instantiateMVars (\u2190 Term.elabType type)\n      let ref \u2190 IO.mkRef \"\"\n      Meta.forEachExpr type fun e => do\n        if e.isForall then ref.modify (. ++ \"ForAll\")\n        else if e.isProp then ref.modify (. ++ \"Prop\")\n        else if e.isType then ref.modify (. ++ \"Type\")\n        else if e.isSort then ref.modify (. ++ \"Sort\")\n        else if e.isConst then\n          match e.constName!.eraseMacroScopes with\n          | Name.str _ str _ =>\n              if str[0].isLower then\n                ref.modify (. ++ str.capitalize)\n              else\n                ref.modify (. ++ str)\n          | _ => pure ()\n      ref.get\n    set savedState\n    liftMacroM <| mkUnusedBaseName <| Name.mkSimple (\"inst\" ++ result)\n  catch ex =>\n    set savedState\n    mkFreshInstanceName\n\ndef mkDefViewOfInstance (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal\n  let attrKind        \u2190 liftMacroM <| toAttributeKind stx[0]\n  let prio            \u2190 liftMacroM <| expandOptNamedPrio stx[2]\n  let attrStx         \u2190 `(attr| instance $(quote prio):numLit)\n  let (binders, type) := expandDeclSig stx[4]\n  let modifiers       := modifiers.addAttribute { kind := attrKind, name := `instance, stx := attrStx }\n  let declId \u2190 match stx[3].getOptional? with\n    | some declId => pure declId\n    | none        =>\n      let id \u2190 mkInstanceName binders.getArgs type\n      pure <| mkNode ``Parser.Command.declId #[mkIdentFrom stx id, mkNullNode]\n  return {\n    ref := stx, kind := DefKind.def, modifiers := modifiers,\n    declId := declId, binders := binders, type? := type, value := stx[5]\n  }\n\ndef mkDefViewOfConstant (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView := do\n  -- leading_parser \"constant \" >> declId >> declSig >> optional declValSimple\n  let (binders, type) := expandDeclSig stx[2]\n  let val \u2190 match stx[3].getOptional? with\n    | some val => pure val\n    | none     =>\n      let val \u2190 `(default_or_ofNonempty%)\n      pure <| mkNode ``Parser.Command.declValSimple #[ mkAtomFrom stx \":=\", val ]\n  return {\n    ref := stx, kind := DefKind.opaque, modifiers := modifiers,\n    declId := stx[1], binders := binders, type? := some type, value := val\n  }\n\ndef mkDefViewOfExample (modifiers : Modifiers) (stx : Syntax) : DefView :=\n  -- leading_parser \"example \" >> declSig >> declVal\n  let (binders, type) := expandDeclSig stx[1]\n  let id              := mkIdentFrom stx `_example\n  let declId          := mkNode ``Parser.Command.declId #[id, mkNullNode]\n  { ref := stx, kind := DefKind.example, modifiers := modifiers,\n    declId := declId, binders := binders, type? := some type, value := stx[2] }\n\ndef isDefLike (stx : Syntax) : Bool :=\n  let declKind := stx.getKind\n  declKind == ``Parser.Command.\u00ababbrev\u00bb ||\n  declKind == ``Parser.Command.\u00abdef\u00bb ||\n  declKind == ``Parser.Command.\u00abtheorem\u00bb ||\n  declKind == ``Parser.Command.\u00abconstant\u00bb ||\n  declKind == ``Parser.Command.\u00abinstance\u00bb ||\n  declKind == ``Parser.Command.\u00abexample\u00bb\n\ndef mkDefView (modifiers : Modifiers) (stx : Syntax) : CommandElabM DefView :=\n  let declKind := stx.getKind\n  if declKind == ``Parser.Command.\u00ababbrev\u00bb then\n    return mkDefViewOfAbbrev modifiers stx\n  else if declKind == ``Parser.Command.\u00abdef\u00bb then\n    return mkDefViewOfDef modifiers stx\n  else if declKind == ``Parser.Command.\u00abtheorem\u00bb then\n    return mkDefViewOfTheorem modifiers stx\n  else if declKind == ``Parser.Command.\u00abconstant\u00bb then\n    mkDefViewOfConstant modifiers stx\n  else if declKind == ``Parser.Command.\u00abinstance\u00bb then\n    mkDefViewOfInstance modifiers stx\n  else if declKind == ``Parser.Command.\u00abexample\u00bb then\n    return mkDefViewOfExample modifiers stx\n  else\n    throwError \"unexpected kind of definition\"\n\nbuiltin_initialize registerTraceClass `Elab.definition\n\nend Command\nend Lean.Elab\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/Elab/DefView.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19930799790404563, "lm_q2_score": 0.04535258523169172, "lm_q1q2_score": 0.009039132962301065}}
{"text": "import tactic.interactive\n\nnamespace tactic.interactive\n\nmeta def get_nat (x : expr) : tactic unit :=\nbegin\n  \nend\n\nend tactic.interactive\n\nlemma (n : \u2115) : ", "meta": {"author": "ChrisHughes24", "repo": "leanstuff", "sha": "9efa85f72efaccd1d540385952a6acc18fce8687", "save_path": "github-repos/lean/ChrisHughes24-leanstuff", "path": "github-repos/lean/ChrisHughes24-leanstuff/leanstuff-9efa85f72efaccd1d540385952a6acc18fce8687/tactic_scratch.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.21733751090819795, "lm_q2_score": 0.041462275820560134, "lm_q1q2_score": 0.009011307823429699}}
{"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 \u2190 h at h'\n  exact h'\n\ndef discussOr (input : Term) : TacticM Unit := do \n    evalApplyLikeTactic Meta.apply <| \u2190 `(Or.elim $input)\n\nelab \"We\" \"discuss using\" exp:term : tactic => \n  discussOr exp\n\nexample (P Q : Prop) (h : P \u2228 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": "/-\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.Basic\n\nnamespace Lean.Elab.Term\n\n/--\n  Set `isDefEq` configuration for the elaborator.\n  Note that we enable all approximations but `quasiPatternApprox`\n\n  In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.\n  The example:\n  ```\n  def ex : StateT \u03b4 (StateT \u03c3 Id) \u03c3 :=\n  monadLift (get : StateT \u03c3 Id \u03c3)\n  ```\n  demonstrates why it produces counterintuitive behavior.\n  We have the `Monad-lift` application:\n  ```\n  @monadLift ?m ?n ?c ?\u03b1 (get : StateT \u03c3 id \u03c3) : ?n ?\u03b1\n  ```\n  It produces the following unification problem when we process the expected type:\n  ```\n  ?n ?\u03b1 =?= StateT \u03b4 (StateT \u03c3 id) \u03c3\n  ==> (approximate using first-order unification)\n  ?n := StateT \u03b4 (StateT \u03c3 id)\n  ?\u03b1 := \u03c3\n  ```\n  Then, we need to solve:\n  ```\n  ?m ?\u03b1 =?= StateT \u03c3 id \u03c3\n  ==> instantiate metavars\n  ?m \u03c3 =?= StateT \u03c3 id \u03c3\n  ==> (approximate since it is a quasi-pattern unification constraint)\n  ?m := fun \u03c3 => StateT \u03c3 id \u03c3\n  ```\n  Note that the constraint is not a Milner pattern because \u03c3 is in\n  the local context of `?m`. We are ignoring the other possible solutions:\n  ```\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3' id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3'\n  ```\n\n  We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).\n\n  If we had use first-order unification, then we would have produced\n  the right answer: `?m := StateT \u03c3 id`\n\n  Haskell would work on this example since it always uses\n  first-order unification.\n-/\ndef setElabConfig (cfg : Meta.Config) : Meta.Config :=\n  { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }\n\n\nend Lean.Elab.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/Lean/Elab/Config.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405755880753266, "lm_q2_score": 0.058345834880825495, "lm_q1q2_score": 0.008988616888327364}}
{"text": "import data.list\nimport data.rbmap\nimport tactic.linarith\n\nimport .ast\nimport .sized\n  \n\nlemma rbmap_insert_lookup_eq {\u03b1:Type} {\u03b2:Type} {lt:\u03b1 \u2192 \u03b1 \u2192 Prop} [Hdec:decidable_rel lt]\n  (m:rbmap \u03b1 \u03b2 lt)\n  (k:\u03b1) (x:\u03b2)\n  : forall a, cmp_using lt a k = ordering.eq \u2192 rbmap.find (rbmap.insert m k x) a = some x \n:= sorry\n\nlemma rbmap_insert_lookup_neq {\u03b1:Type} {\u03b2:Type} {lt:\u03b1 \u2192 \u03b1 \u2192 Prop} [Hdec:decidable_rel lt]\n  (m:rbmap \u03b1 \u03b2 lt)\n  (k:\u03b1) (x:\u03b2)\n  : forall a, cmp_using lt a k \u2260 ordering.eq \u2192 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 \u2192 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 (\u03bb 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 (\u03bb x H, mentions x))\n| (llvm_type.packed_struct fs) := list.join (sized.map_over fs (\u03bb x H, mentions x))\n| (llvm_type.vector _n tp) := mentions tp\n| (llvm_type.opaque) := []\n\nusing_well_founded \u27e8\u03bb _ _, `[exact \u27e8measure sizeof, measure_wf _\u27e9] , llvm_type_tac\u27e9\n.\n\n@[reducible,simp]\ndef alias_rel (am:strmap llvm_type) (x y:ident) : Prop :=\n  \u2203tp, am.find y.ident = some tp /\\ x \u2208 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 {\u03b1:Type} (p:\u03b1 \u2192 Prop) (l:list \u03b1) :\n  (\u2200x, x \u2208 l \u2192 decidable (p x)) \u2192\n  decidable (\u2200x, x \u2208 l \u2192 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 : (\u03a0 (x : \u03b1), x \u2208 l_tl \u2192 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 {\u03b1:Type} (p:\u03b1 \u2192 Prop) (l:list \u03b1) :\n  (\u2200x, x \u2208 l \u2192 decidable (p x)) \u2192\n  decidable (\u2203x, x \u2208 l \u2227 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 : (\u03a0 (x : \u03b1), x \u2208 l_tl \u2192 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 (\u2203i, i \u2208 mentions tp \u2227 (i = x \u2228 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 \u2192 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 \u2260 x)\n  (Hntc: \u00ac(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 : \u00ac\u2203y, y \u2208 mentions tp \u2227 (y = x \u2228 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 (\u2203y, y \u2208 mentions tp \u2227 (y = x \u2228 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 \u27e8rbmap.insert am.val k.ident tp, insert_alias_map_wf am.val k tp am.property H\u27e9\n  end\n\ndef build : list type_decl \u2192 alias_map \u2192 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 \u00d7 MVarId) := do\n  let tgt \u2190 whnf (\u2190 getMVarType mvarId)\n  if tgt.isForall \u2228 tgt.isLet then\n    let (fvar, newmvarId) \u2190 intro mvarId name\n    withMVarContext newmvarId do\n      let t := (\u2190 getLocalDecl fvar).type\n      if (\u2190 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 \u2192 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) \u2190 introObj (\u2190 getMainGoal) n\n    -- Change the default MVarContext to the newly created one for the benefit of `elabTerm`\n    withMVarContext new_goal do\n      replaceMainGoal [\u2190 changeLocalDecl new_goal n_fvar (\u2190 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) \u2190 introObj (\u2190 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) \u2190 introObj (\u2190 getMainGoal) n\n    withMVarContext new_goal do\n      let n_decl \u2190 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) \u2190 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) \u2190 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) \u2190 intro new_goal hyp_name\n      withMVarContext newer_goal do\n        let new_mvarid \u2190 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 (\"<=\" <|> \"\u2264\") term : fixDecl\nsyntax ident (\">=\" <|> \"\u2265\") term : fixDecl\nsyntax ident \"\u2208\" term : fixDecl\nsyntax \"(\" fixDecl \")\" : fixDecl\n\nsyntax \"Fix\u2081 \" colGt fixDecl : tactic\nsyntax \"Fix \" (colGt fixDecl)+ : tactic\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident) => Fix1 (introduced.bare x x.getId)\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident : $type) =>\n    Fix1 (introduced.typed (mkNullNode #[x, type]) x.getId type)\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident < $bound) =>\n    Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.lt bound)\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident > $bound) =>\n    Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.gt bound)\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident \u2264 $bound) =>\n    Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.le bound)\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident \u2265 $bound) =>\n    Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.ge bound)\n\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 $x:ident \u2208 $set) =>\n    Fix1 (introduced.related (mkNullNode #[x, set]) x.getId intro_rel.mem set)\n\nelab_rules : tactic\n  | `(tactic| Fix\u2081 ( $decl:fixDecl )) => do evalTactic (\u2190 `(tactic| Fix\u2081 $decl:fixDecl))\n\n\nmacro_rules\n  | `(tactic| Fix $decl:fixDecl) => `(tactic| Fix\u2081 $decl)\n\nmacro_rules\n  | `(tactic| Fix $decl:fixDecl $decls:fixDecl*) => `(tactic| Fix\u2081 $decl; Fix $decls:fixDecl*)\n\n\nmacro_rules\n| `(\u2115) => `(Nat)\n\n-- requires the extended binder import\n#check \u2200 n \u2265 2, true\n\n#check \u2203 n \u2265 2, true\n\nexample : \u2200 b : \u2115, \u2200 a : Nat, a \u2265 2 \u2192 a = a \u2227 b = b := by\n  Fix b (a \u2265 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": "/-\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.meta.smt.smt_tactic init.meta.interactive_base\nimport init.meta.smt.rsimp\n\nnamespace smt_tactic\nmeta def save_info (p : pos) : smt_tactic unit :=\ndo (ss, ts) \u2190 smt_tactic.read,\n   tactic.save_info_thunk p (\u03bb _, smt_state.to_format ss ts)\n\nmeta def skip : smt_tactic unit :=\nreturn ()\n\nmeta def solve_goals : smt_tactic unit :=\niterate close\n\nmeta def step {\u03b1 : Type} (tac : smt_tactic \u03b1) : smt_tactic unit :=\ntac >> solve_goals\n\nmeta def istep {\u03b1 : Type} (line0 col0 line col ast : nat) (tac : smt_tactic \u03b1) : smt_tactic unit :=\n\u27e8\u03bb ss ts, (@scope_trace _ line col (\u03bb _,\n  tactic.with_ast ast ((tac >> solve_goals).run ss) ts)).clamp_pos line0 line col\u27e9\n\nmeta def execute (tac : smt_tactic unit) : tactic unit :=\nusing_smt tac\n\nmeta def execute_with (cfg : smt_config) (tac : smt_tactic unit) : tactic unit :=\nusing_smt tac cfg\n\nmeta instance : interactive.executor smt_tactic :=\n{ config_type := smt_config,\n  inhabited := \u27e8{}\u27e9,\n  execute_with := \u03bb cfg tac, using_smt tac cfg, }\n\nnamespace interactive\nopen lean.parser\nopen _root_.interactive\nopen interactive.types\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nmeta def itactic : Type :=\nsmt_tactic unit\n\nmeta def intros : parse ident* \u2192 smt_tactic unit\n| [] := smt_tactic.intros\n| hs := smt_tactic.intro_lst hs\n\n/--\n  Try to close main goal by using equalities implied by the congruence\n  closure module.\n-/\nmeta def close : smt_tactic unit :=\nsmt_tactic.close\n\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-/\nmeta def ematch : smt_tactic unit :=\nsmt_tactic.ematch\n\nmeta def apply (q : parse texpr) : smt_tactic unit :=\ntactic.interactive.apply q\n\nmeta def fapply (q : parse texpr) : smt_tactic unit :=\ntactic.interactive.fapply q\n\nmeta def apply_instance : smt_tactic unit :=\ntactic.apply_instance\n\nmeta def change (q : parse texpr) : smt_tactic unit :=\ntactic.interactive.change q none (loc.ns [none])\n\nmeta def exact (q : parse texpr) : smt_tactic unit :=\ntactic.interactive.exact q\n\nmeta def \u00abfrom\u00bb := exact\n\nmeta def \u00abassume\u00bb := tactic.interactive.assume\n\nmeta def \u00abhave\u00bb (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?) (q\u2082 : parse $ (tk \":=\" *> texpr)?) : smt_tactic unit :=\nlet h := h.get_or_else `this in\nmatch q\u2081, q\u2082 with\n| some e, some p := do\n  t \u2190 tactic.to_expr e,\n  v \u2190 tactic.to_expr ``(%%p : %%t),\n  smt_tactic.assertv h t v\n| none, some p := do\n  p \u2190 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  u \u2190 tactic.mk_meta_univ,\n  e \u2190 tactic.mk_meta_var (expr.sort u),\n  smt_tactic.assert h e\nend >> return ()\n\nmeta def \u00ablet\u00bb (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?) (q\u2082 : parse $ (tk \":=\" *> texpr)?) : smt_tactic unit :=\nlet h := h.get_or_else `this in\nmatch q\u2081, q\u2082 with\n| some e, some p := do\n  t \u2190 tactic.to_expr e,\n  v \u2190 tactic.to_expr ``(%%p : %%t),\n  smt_tactic.definev h t v\n| none, some p := do\n  p \u2190 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  u \u2190 tactic.mk_meta_univ,\n  e \u2190 tactic.mk_meta_var (expr.sort u),\n  smt_tactic.define h e\nend >> return ()\n\nmeta def add_fact (q : parse texpr) : smt_tactic unit :=\ndo h \u2190 tactic.get_unused_name `h none,\n   p \u2190 tactic.to_expr_strict q,\n   smt_tactic.note h none p\n\nmeta def trace_state : smt_tactic unit :=\nsmt_tactic.trace_state\n\nmeta def trace {\u03b1 : Type} [has_to_tactic_format \u03b1] (a : \u03b1) : smt_tactic unit :=\ntactic.trace a\n\nmeta def destruct (q : parse texpr) : smt_tactic unit :=\ndo p \u2190 tactic.to_expr_strict q,\n   smt_tactic.destruct p\n\nmeta def by_cases (q : parse texpr) : smt_tactic unit :=\ndo p \u2190 tactic.to_expr_strict q,\n   smt_tactic.by_cases p\n\nmeta def by_contradiction : smt_tactic unit :=\nsmt_tactic.by_contradiction\n\nmeta def by_contra : smt_tactic unit :=\nsmt_tactic.by_contradiction\n\nopen tactic (resolve_name transparency to_expr)\n\nprivate meta def report_invalid_em_lemma {\u03b1 : Type} (n : name) : smt_tactic \u03b1 :=\nfail format!\"invalid ematch lemma '{n}'\"\n\nprivate meta def add_lemma_name (md : transparency) (lhs_lemma : bool) (n : name) (ref : pexpr) : smt_tactic unit :=\ndo\n  p \u2190 resolve_name n,\n  match p with\n  | expr.const n _           := (add_ematch_lemma_from_decl_core md lhs_lemma n >> tactic.save_const_type_info n ref) <|> report_invalid_em_lemma n\n  | _                        := (do e \u2190 to_expr p, add_ematch_lemma_core md lhs_lemma e >> try (tactic.save_type_info e ref)) <|> report_invalid_em_lemma n\n  end\n\n\nprivate meta def add_lemma_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) : smt_tactic unit :=\nmatch 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 new_e \u2190 to_expr p, add_ematch_lemma_core md lhs_lemma new_e\nend\n\nprivate meta def add_lemma_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr \u2192 smt_tactic unit\n| []      := return ()\n| (p::ps) := add_lemma_pexpr md lhs_lemma p >> add_lemma_pexprs ps\n\nmeta def add_lemma (l : parse pexpr_list_or_texpr) : smt_tactic unit :=\nadd_lemma_pexprs reducible ff l\n\nmeta def add_lhs_lemma (l : parse pexpr_list_or_texpr) : smt_tactic unit :=\nadd_lemma_pexprs reducible tt l\n\nprivate meta def add_eqn_lemmas_for_core (md : transparency) : list name \u2192 smt_tactic unit\n| []      := return ()\n| (c::cs) := do\n  p \u2190 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 format!\"'{c}' is not a constant\"\n  end\n\nmeta def add_eqn_lemmas_for (ids : parse ident*) : smt_tactic unit :=\nadd_eqn_lemmas_for_core reducible ids\n\nmeta def add_eqn_lemmas (ids : parse ident*) : smt_tactic unit :=\nadd_eqn_lemmas_for ids\n\nprivate meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name) (hs : hinst_lemmas) (ref : pexpr) : smt_tactic hinst_lemmas :=\ndo\n  p \u2190 resolve_name n,\n  match p with\n  | expr.const n _           :=\n    (do h \u2190 hinst_lemma.mk_from_decl_core md n lhs_lemma, tactic.save_const_type_info n ref, return $ hs.add h)\n    <|>\n    (do hs\u2081 \u2190 mk_ematch_eqn_lemmas_for_core md n, tactic.save_const_type_info n ref, return $ hs.merge hs\u2081)\n    <|>\n    report_invalid_em_lemma n\n  | _ :=\n    (do e \u2190 to_expr p, h \u2190 hinst_lemma.mk_core md e lhs_lemma, try (tactic.save_type_info e ref), return $ hs.add h)\n    <|>\n    report_invalid_em_lemma n\n  end\n\nprivate meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas :=\nmatch 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 new_e \u2190 to_expr p, h \u2190 hinst_lemma.mk_core md new_e lhs_lemma, return $ hs.add h\nend\n\nprivate meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr \u2192 hinst_lemmas \u2192 smt_tactic hinst_lemmas\n| []      hs := return hs\n| (p::ps) hs := do hs\u2081 \u2190 add_hinst_lemma_from_pexpr md lhs_lemma p hs, add_hinst_lemmas_from_pexprs ps hs\u2081\n\nmeta def ematch_using (l : parse pexpr_list_or_texpr) : smt_tactic unit :=\ndo hs \u2190 add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk,\n   smt_tactic.ematch_using hs\n\n/-- Try the given tactic, and do nothing if it fails. -/\nmeta def try (t : itactic) : smt_tactic unit :=\nsmt_tactic.try t\n\n/-- Keep applying the given tactic until it fails. -/\nmeta def iterate (t : itactic) : smt_tactic unit :=\nsmt_tactic.iterate t\n\n/-- Apply the given tactic to all remaining goals. -/\nmeta def all_goals (t : itactic) : smt_tactic unit :=\nsmt_tactic.all_goals t\n\nmeta def induction (p : parse tactic.interactive.cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list)\n  (revert : parse $ (tk \"generalizing\" *> ident*)?) : smt_tactic unit :=\nslift (tactic.interactive.induction p rec_name ids revert)\n\nopen tactic\n\n/-- Simplify the target type of the main goal. -/\nmeta def simp (use_iota_eqn : parse $ (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n              (attr_names : parse with_ident_list) (cfg : simp_config_ext := {}) : smt_tactic unit :=\ntactic.interactive.simp use_iota_eqn none no_dflt hs attr_names (loc.ns [none]) cfg\n\nmeta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) : smt_tactic unit :=\ntactic.interactive.dsimp no_dflt es attr_names (loc.ns [none])\n\nmeta def rsimp : smt_tactic unit :=\ndo ccs \u2190 to_cc_state, _root_.rsimp.rsimplify_goal ccs\n\nmeta def add_simp_lemmas : smt_tactic unit :=\nget_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas\n\n/-- Keep applying heuristic instantiation until the current goal is solved, or it fails. -/\nmeta def eblast : smt_tactic unit :=\nsmt_tactic.eblast\n\n/-- Keep applying heuristic instantiation using the given lemmas until the current goal is solved, or it fails. -/\nmeta def eblast_using (l : parse pexpr_list_or_texpr) : smt_tactic unit :=\ndo hs \u2190 add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk,\n   smt_tactic.iterate (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close)\n\nmeta def guard_expr_eq (t : expr) (p : parse $ tk \":=\" *> texpr) : smt_tactic unit :=\ndo e \u2190 to_expr p, guard (expr.alpha_eqv t e)\n\nmeta def guard_target (p : parse texpr) : smt_tactic unit :=\ndo t \u2190 target, guard_expr_eq t p\n\nend interactive\nend smt_tactic\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885696887202595, "lm_q2_score": 0.05261895149064917, "lm_q1q2_score": 0.008885076653935191}}
{"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.name init.meta.options init.meta.format init.meta.rb_map\nimport init.meta.level init.meta.expr init.meta.environment init.meta.attribute\nimport init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic\nimport init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info\nimport init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics\nimport init.meta.backward init.meta.rewrite_tactic\nimport init.meta.derive init.meta.mk_dec_eq_instance\nimport init.meta.simp_tactic init.meta.set_get_option_tactics\nimport init.meta.interactive init.meta.converter init.meta.vm\nimport init.meta.comp_value_tactics init.meta.smt\nimport init.meta.async_tactic init.meta.ref\nimport init.meta.hole_command init.meta.congr_tactic\nimport init.meta.local_context init.meta.type_context\nimport init.meta.instance_cache\nimport init.meta.module_info\nimport init.meta.expr_address\nimport init.meta.tagged_format", "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/default.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2337063569140403, "lm_q2_score": 0.037892424728248074, "lm_q1q2_score": 0.00885570053787835}}
{"text": "import control.traversable.derive\nimport control.traversable.instances\n\nuniverses u\n\n/- traversable -/\nopen tactic.interactive\n\nrun_cmd do\nlawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list\n-- the above creates local instances of `traversable` and `is_lawful_traversable`\n-- for `list`\n-- do not put in instances because they are not universe polymorphic\n\n@[derive [traversable, is_lawful_traversable]]\nstructure my_struct (\u03b1 : Type) :=\n  (y : \u2124)\n\n@[derive [traversable, is_lawful_traversable]]\ninductive either (\u03b1 : Type u)\n| left : \u03b1 \u2192 \u2124 \u2192 either\n| right : \u03b1 \u2192 either\n\n@[derive [traversable, is_lawful_traversable]]\nstructure my_struct2 (\u03b1 : Type u) : Type u :=\n  (x : \u03b1)\n  (y : \u2124)\n  (\u03b7 : list \u03b1)\n  (k : list (list \u03b1))\n\n@[derive [traversable, is_lawful_traversable]]\ninductive rec_data3 (\u03b1 : Type u) : Type u\n| nil : rec_data3\n| cons : \u2115 \u2192 \u03b1 \u2192 rec_data3 \u2192 rec_data3 \u2192 rec_data3\n\n@[derive traversable]\nmeta structure meta_struct (\u03b1 : Type u) : Type u :=\n  (x : \u03b1)\n  (y : \u2124)\n  (z : list \u03b1)\n  (k : list (list \u03b1))\n  (w : expr)\n\n@[derive [traversable,is_lawful_traversable]]\ninductive my_tree (\u03b1 : Type)\n| leaf : my_tree\n| node : my_tree \u2192 my_tree \u2192 \u03b1 \u2192 my_tree\n\nsection\nopen my_tree (hiding traverse)\n\ndef x : my_tree (list nat) :=\nnode\n  leaf\n  (node\n    (node leaf leaf [1,2,3])\n    leaf\n    [3,2])\n  [1]\n\n/-- demonstrate the nested use of `traverse`. It traverses each node of the tree and\nin each node, traverses each list. For each `\u2115` visited, apply an action `\u2115 -> state (list \u2115) unit`\nwhich adds its argument to the state. -/\ndef ex : state (list \u2115) (my_tree $ list unit) :=\ndo xs \u2190 traverse (traverse $ \u03bb a, modify $ list.cons a) x,\n   pure xs\n\nexample : (ex.run []).1 = node leaf (node (node leaf leaf [(), (), ()]) leaf [(), ()]) [()] := rfl\nexample : (ex.run []).2 = [1, 2, 3, 3, 2, 1] := rfl\nexample : is_lawful_traversable my_tree := my_tree.is_lawful_traversable\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/test/traversable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.028436036338298564, "lm_q1q2_score": 0.008834916771194315}}
{"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 \u224c D)\n  {X Y B : D} (f : X \u27f6 B) (g : Y \u27f6 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 \u27f6 e.functor.obj Y)\n  (g : X \u27f6 Y) : e.inverse.map f = e.symm.counit.app _ \u226b g \u226b e.unit.app _ \u2192\n  f = e.functor.map g :=\nbegin\n  intros h,\n  change _ = (e.unit_iso.app _).inv \u226b g \u226b (e.unit_iso.app _).hom at h,\n  rw iso.eq_inv_comp at h,\n  replace h := h.symm,\n  rw \u2190 iso.eq_comp_inv at h,\n  rw h,\n  simp,\n  nth_rewrite 0 \u2190 category.id_comp f,\n  simp_rw \u2190 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  \u03c0 :=\n  { app := \u03bb i,\n    match i with\n    | none := e.functor.map pullback.fst \u226b e.counit.app X \u226b f\n    | walking_cospan.left := e.functor.map pullback.fst \u226b e.counit.app X\n    | walking_cospan.right := e.functor.map pullback.snd \u226b 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 \u226b f = e.functor.map (e.inverse.map f) \u226b e.counit.app B, by tidy,\n        rw this, clear this,\n        have : e.counit.app Y \u226b g = e.functor.map (e.inverse.map g) \u226b e.counit.app B, by tidy,\n        rw this, clear this,\n        simp_rw [\u2190 category.assoc, \u2190 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 := \u03bb S, e.symm.unit.app S.X \u226b\n    e.functor.map (pullback.lift (e.inverse.map (S.\u03c0.app walking_cospan.left))\n      (e.inverse.map (S.\u03c0.app walking_cospan.right)) begin\n        simp_rw \u2190 e.inverse.map_comp,\n        congr' 1,\n        have := cospan_map_inl f g,\n        change _ \u226b (cospan f g).map walking_cospan.hom.inl =\n          _ \u226b (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 \u226b f = e.functor.map (e.inverse.map f) \u226b e.counit.app B, by tidy,\n      rw this, clear this,\n      simp_rw [\u2190 category.assoc _ _ (e.counit.app B), \u2190 e.functor.map_comp],\n      simp,\n      dsimp,\n      simp,\n      change _ \u226b (cospan f g).map walking_cospan.hom.inl = _,\n      rw S.w },\n    { dsimp [equivalence.pullback_cone._match_1], simp,\n      simp_rw [\u2190 category.assoc _ _ (e.counit.app X), \u2190 e.functor.map_comp],\n      simp,\n      dsimp,\n      simp },\n    { dsimp [equivalence.pullback_cone._match_1], simp,\n      simp_rw [\u2190 category.assoc _ _ (e.counit.app Y), \u2190 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 \u226b _,\n    rw iso.eq_inv_comp,\n    apply equivalence.hom_eq_map,\n    change _ = (e.unit_iso.app _).inv \u226b _ \u226b (e.unit_iso.app _).hom,\n    rw iso.eq_inv_comp,\n    symmetry,\n    rw \u2190 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 \u2190 h,\n      simp,\n      simp_rw \u2190 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 \u2190 h,\n      simp,\n      simp_rw \u2190 category.assoc,\n      congr' 2,\n      simp }\n  end } .\n\ninclude e\n\nlemma equivalence.has_pullback {X Y B : D} (f : X \u27f6 B) (g : Y \u27f6 B)\n  [has_pullback (e.inverse.map f) (e.inverse.map g)] : has_pullback f g :=\nlimits.has_limit.mk \u27e8e.pullback_cone _ _, e.is_limit_pullback_cone _ _\u27e9\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": "/-\nCopyright (c) 2022 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\nimport Lean.Elab.ElabRules\nopen Lean Elab Parser Term Meta Macro\n\n/-!\nDefines variants of `have` and `let` syntax which do not produce `let_fun` or `let` bindings,\nbut instead inline the value instead.\n\nThis is useful to declare local instances and proofs in theorem statements\nand subgoals, where the extra binding is inconvenient.\n-/\n\nnamespace Std.Tactic\n\n/-- `haveI` behaves like `have`, but inlines the value instead of producing a `let_fun` term. -/\n@[term_parser] def \u00abhaveI\u00bb := leading_parser withPosition (\"haveI \" >> haveDecl) >> optSemicolon termParser\n/-- `letI` behaves like `let`, but inlines the value instead of producing a `let_fun` term. -/\n@[term_parser] def \u00abletI\u00bb := leading_parser withPosition (\"letI \" >> haveDecl) >> optSemicolon termParser\n\nmacro_rules\n  | `(haveI $_ : $_ := $_; $_) => throwUnsupported -- handled by elab\n  | `(haveI $[: $ty]? := $val; $body) => `(haveI $(mkIdent `this) $[: $ty]? := $val; $body)\n  | `(haveI $x := $val; $body) => `(haveI $x : _ := $val; $body)\n  | `(haveI $decl:haveDecl; $body) => `(haveI x := have $decl:haveDecl; x; $body)\n\nmacro_rules\n  | `(letI $_ : $_ := $_; $_) => throwUnsupported -- handled by elab\n  | `(letI $[: $ty]? := $val; $body) => `(letI $(mkIdent `this) $[: $ty]? := $val; $body)\n  | `(letI $x := $val; $body) => `(letI $x : _ := $val; $body)\n  | `(letI $decl:haveDecl; $body) => `(letI x := have $decl:haveDecl; x; $body)\n\nelab_rules <= expectedType\n  | `(haveI $x : $ty := $val; $body) => do\n    let ty \u2190 elabType ty\n    let val \u2190 elabTermEnsuringType val ty\n    withLocalDeclD x.getId ty fun x => do\n      return (\u2190 (\u2190 elabTerm body expectedType).abstractM #[x]).instantiate #[val]\n\nelab_rules <= expectedType\n  | `(letI $x : $ty := $val; $body) => do\n    let ty \u2190 elabType ty\n    let val \u2190 elabTermEnsuringType val ty\n    withLetDecl x.getId ty val fun x => do\n      return (\u2190 (\u2190 elabTerm body expectedType).abstractM #[x]).instantiate #[val]\n\n/-- `haveI` behaves like `have`, but inlines the value instead of producing a `let_fun` term. -/\nmacro \"haveI \" d:haveDecl : tactic => `(tactic| refine_lift haveI $d:haveDecl; ?_)\n/-- `letI` behaves like `let`, but inlines the value instead of producing a `let_fun` term. -/\nmacro \"letI \" d:haveDecl : tactic => `(tactic| refine_lift letI $d:haveDecl; ?_)\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/HaveI.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436780168531517, "lm_q2_score": 0.045352579425282445, "lm_q1q2_score": 0.008815081163650804}}
{"text": "import .cofibration_category\nimport .cylinder\nimport .lifting\n\nuniverses v u\n\nopen category_theory\nopen category_theory.category\nlocal notation f ` \u2218 `:80 g:80 := g \u226b 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 \u27f6 b} {hj : is_cof j}\n\nstructure homotopy_on (c : relative_cylinder hj) {x : C} (f\u2080 f\u2081 : b \u27f6 x) :=\n(H : c.ob \u27f6 x)\n(Hi\u2080 : H \u2218 c.i\u2080 = f\u2080)\n(Hi\u2081 : H \u2218 c.i\u2081 = f\u2081)\n\n@[ext] lemma homotopy_on.ext (c : relative_cylinder hj) {x : C} (f\u2080 f\u2081 : b \u27f6 x)\n  (H H' : homotopy_on c f\u2080 f\u2081) (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 \u27f6 x) :\n  homotopy_on c f f :=\n\u27e8f \u2218 c.p, by rw [\u2190assoc, c.pi\u2080]; simp, by rw [\u2190assoc, c.pi\u2081]; simp\u27e9\n\ndef homotopy_on.symm {c : relative_cylinder hj} {x : C} {f\u2080 f\u2081 : b \u27f6 x} :\n  homotopy_on c f\u2080 f\u2081 \u2192 homotopy_on c.reverse f\u2081 f\u2080 :=\n\u03bb H, \u27e8H.H, by convert H.Hi\u2081; simp, by convert H.Hi\u2080; simp\u27e9\n\ndef homotopy_on.trans {c\u2080 c\u2081 : relative_cylinder hj} {x : C} {f\u2080 f\u2081 f\u2082 : b \u27f6 x} :\n  homotopy_on c\u2080 f\u2080 f\u2081 \u2192 homotopy_on c\u2081 f\u2081 f\u2082 \u2192 homotopy_on (c\u2080.glue c\u2081) f\u2080 f\u2082 :=\n\u03bb H\u2080 H\u2081,\n\u27e8(pushout_by_cof c\u2080.i\u2081 c\u2081.i\u2080 c\u2080.acof_i\u2081.1).is_pushout.induced\n  H\u2080.H H\u2081.H (H\u2080.Hi\u2081.trans H\u2081.Hi\u2080.symm),\n by convert H\u2080.Hi\u2080 using 1; simp, by convert H\u2081.Hi\u2081 using 1; simp\u27e9\n\n-- Two maps f\u2080, f\u2081 are homotopic rel j with respect to a chosen\n-- cylinder object on j if there exists a homotopy from f\u2080 to f\u2081\n-- defined on that cylinder.\ndef homotopic_wrt (c : relative_cylinder hj) {x : C} (f\u2080 f\u2081 : b \u27f6 x) : Prop :=\nnonempty (homotopy_on c f\u2080 f\u2081)\n\n-- If x is fibrant, then any two cylinders define the same homotopy\n-- rel j relation on maps b \u27f6 x.\nlemma homotopic_iff_of_embedding {c c' : relative_cylinder hj}\n  (m : cylinder_embedding c c') {x : C} (hx : fibrant x) (f\u2080 f\u2081 : b \u27f6 x) :\n  homotopic_wrt c f\u2080 f\u2081 \u2194 homotopic_wrt c' f\u2080 f\u2081 :=\niff.intro\n  (assume \u27e8\u27e8H, Hi\u2080, Hi\u2081\u27e9\u27e9,\n    let \u27e8H', hH'\u27e9 := fibrant_iff_rlp.mp hx m.acof_k H in\n    \u27e8\u27e8H', by rw \u2190m.hki\u2080; simp [hH', Hi\u2080], by rw \u2190m.hki\u2081; simp [hH', Hi\u2081]\u27e9\u27e9)\n  (assume \u27e8\u27e8H, Hi\u2080, Hi\u2081\u27e9\u27e9,\n    \u27e8\u27e8H \u2218 m.k, by rw [\u2190assoc, m.hki\u2080, Hi\u2080], by rw [\u2190assoc, m.hki\u2081, Hi\u2081]\u27e9\u27e9)\n\nlemma homotopic_iff (c\u2080 c\u2081 : relative_cylinder hj) {x : C} (hx : fibrant x) (f\u2080 f\u2081 : b \u27f6 x) :\n  homotopic_wrt c\u2080 f\u2080 f\u2081 \u2194 homotopic_wrt c\u2081 f\u2080 f\u2081 :=\nlet \u27e8\u27e8c', m\u2080, m\u2081\u27e9\u27e9 := exists_common_embedding c\u2080 c\u2081 in\n(homotopic_iff_of_embedding m\u2080 hx f\u2080 f\u2081).trans\n  (homotopic_iff_of_embedding m\u2081 hx f\u2080 f\u2081).symm\n\nvariables (hj)\ndef homotopic_rel {x} (f\u2080 f\u2081 : b \u27f6 x) : Prop :=\n\u2203 c : relative_cylinder hj, homotopic_wrt c f\u2080 f\u2081\n\nvariables {hj}\nlemma homotopic_rel' (c : relative_cylinder hj) {x} (hx : fibrant x) (f\u2080 f\u2081 : b \u27f6 x)\n  (h : homotopic_rel hj f\u2080 f\u2081) : homotopic_wrt c f\u2080 f\u2081 :=\nlet \u27e8c', hw\u27e9 := h in (homotopic_iff c' c hx f\u2080 f\u2081).mp hw\n\n@[refl] lemma homotopic_rel.refl {x} (f : b \u27f6 x) : homotopic_rel hj f f :=\nlet \u27e8c\u27e9 := exists_relative_cylinder hj in\n\u27e8c, \u27e8homotopy_on.refl f\u27e9\u27e9\n\n@[symm] lemma homotopic_rel.symm {x} {f\u2080 f\u2081 : b \u27f6 x} :\n  homotopic_rel hj f\u2080 f\u2081 \u2192 homotopic_rel hj f\u2081 f\u2080 :=\nassume \u27e8c, \u27e8H\u27e9\u27e9, \u27e8c.reverse, \u27e8homotopy_on.symm H\u27e9\u27e9\n\n@[trans] lemma homotopic_rel.trans {x} {f\u2080 f\u2081 f\u2082 : b \u27f6 x} :\n  homotopic_rel hj f\u2080 f\u2081 \u2192 homotopic_rel hj f\u2081 f\u2082 \u2192 homotopic_rel hj f\u2080 f\u2082 :=\nassume \u27e8c\u2080, \u27e8H\u2080\u27e9\u27e9 \u27e8c\u2081, \u27e8H\u2081\u27e9\u27e9,\n\u27e8c\u2080.glue c\u2081, \u27e8H\u2080.trans H\u2081\u27e9\u27e9\n\nlemma homotopic_rel_is_equivalence {x : C} :\n  equivalence (homotopic_rel hj : (b \u27f6 x) \u2192 (b \u27f6 x) \u2192 Prop) :=\n\u27e8homotopic_rel.refl,\n \u03bb f\u2080 f\u2081, homotopic_rel.symm,\n \u03bb f\u2080 f\u2081 f\u2082, homotopic_rel.trans\u27e9\n\nnotation f\u2080 ` \u2243 `:50 f\u2081:50 ` rel `:50 hj:50 := homotopic_rel hj f\u2080 f\u2081\n\nvariables (hj)\ndef homotopic_rel_setoid (x : C) : setoid (b \u27f6 x) :=\n{ r := \u03bb f\u2080 f\u2081, homotopic_rel hj f\u2080 f\u2081,\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 \u27f6 x)\n  {g\u2080 g\u2081 : b \u27f6 x} (hg\u2080 : g\u2080 \u2218 j = f) (hg\u2081 : g\u2081 \u2218 j = f) : g\u2080 \u2243 g\u2081 rel hj.1 :=\nlet \u27e8c\u27e9 := exists_relative_cylinder hj.1,\n    \u27e8H, h\u27e9 := fibrant_iff_rlp.mp hx (c.acof_ii hj.2)\n      ((pushout_by_cof j j hj.1).is_pushout.induced g\u2080 g\u2081 (hg\u2080.trans hg\u2081.symm)) in\n\u27e8c, \u27e8\u27e8H, by simp [relative_cylinder.i\u2080, h], by simp [relative_cylinder.i\u2081, h]\u27e9\u27e9\u27e9\n\nsection congr_left\nvariables {x y : C} (g : x \u27f6 y)\n\ndef homotopy_on.congr_left {c : relative_cylinder hj} {f\u2080 f\u2081 : b \u27f6 x} :\n  homotopy_on c f\u2080 f\u2081 \u2192 homotopy_on c (g \u2218 f\u2080) (g \u2218 f\u2081) :=\n\u03bb H, \u27e8g \u2218 H.H, by rw [\u2190assoc, H.Hi\u2080], by rw [\u2190assoc, H.Hi\u2081]\u27e9\n\nlemma homotopic_rel.congr_left {f\u2080 f\u2081 : b \u27f6 x} :\n  homotopic_rel hj f\u2080 f\u2081 \u2192 homotopic_rel hj (g \u2218 f\u2080) (g \u2218 f\u2081) :=\n\u03bb \u27e8c, \u27e8H\u27e9\u27e9, \u27e8c, \u27e8H.congr_left hj g\u27e9\u27e9\n\nend congr_left\n\nsection congr_right\nvariables {a' b' : C} {j' : a' \u27f6 b'} (hj' : is_cof j')\n\nlemma homotopic_rel.congr_right (h : pair_map hj' hj) {x : C} (hx : fibrant x)\n  (f\u2080 f\u2081 : b \u27f6 x) : f\u2080 \u2243 f\u2081 rel hj \u2192 f\u2080 \u2218 h.h \u2243 f\u2081 \u2218 h.h rel hj' :=\nassume \u27e8c, H\u27e9,\nlet \u27e8c'\u27e9 := exists_relative_cylinder hj',\n    \u27e8c'', m', m, \u27e8\u27e9\u27e9 := exists_of_pair_map h c' c,\n    \u27e8H'\u27e9 := (homotopic_iff_of_embedding m hx f\u2080 f\u2081).mp H in\n\u27e8c',\n \u27e8\u27e8H'.H \u2218 m'.k,\n   by rw [\u2190assoc, m'.hki\u2080, assoc, H'.Hi\u2080],\n   by rw [\u2190assoc, m'.hki\u2081, assoc, H'.Hi\u2081]\u27e9\u27e9\u27e9\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": "example (h : x \u2260 0) : Unit := by\n  simp_all\n  trace_state\n  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/1027.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541662624228417, "lm_q2_score": 0.03904828825307405, "lm_q1q2_score": 0.008802133398544168}}
{"text": "def hello := \"world\"\n\naxiom A : Prop\ndef claim: Prop := \u2200 (x: A), A\n\ndef ja (_s : String) : Prop :=\n  claim\n\ntheorem test : ja \"\u3042\u3042\u3042\" := by\n  intro a; exact a\n\nunsafe\ndef lbUnsafe (japanese: String) : Prop :=\n  True\n\n@[implementedBy lbUnsafe]\ndef lb (japanese : String) : Prop :=\n  claim\n\ntheorem t2 : lb \"\u3042\u3042\u3042\u3042\u3042\" := by\n  intro a;exact a\n\ndef ko := Lean.Quote\n\nunsafe\ndef u :Prop := claim\n\ndef h: IO Prop := do\n  IO.print \"aaaaa\"\n  pure claim\n\nunsafe\ndef hu : Prop :=\n  match unsafeIO h with\n  | Except.ok p => p\n  | Except.error _ => True\n\ntheorem k: hu := by\n  \n", "meta": {"author": "denjiry", "repo": "leanhello", "sha": "3f2a471a78a63c4124d39b39b551c63586e68590", "save_path": "github-repos/lean/denjiry-leanhello", "path": "github-repos/lean/denjiry-leanhello/leanhello-3f2a471a78a63c4124d39b39b551c63586e68590/Leanhello.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.021948253195069045, "lm_q1q2_score": 0.008775167121293004}}
{"text": "-- See Lean doc/monads/transformers.lean\nnamespace Args2\n\nabbrev Arguments := List String\n\ndef indexOf? [BEq \u03b1] (xs : List \u03b1) (s : \u03b1) (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) : ExceptT String (ReaderM Arguments) String := do\n  let args \u2190 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) : ExceptT String (ReaderM Arguments) Bool := do\n  let args \u2190 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\n\nstructure Config where\n  help : Bool := false\n  verbose : Bool := false\n  input : String := \"\"\n  deriving Repr\n\nabbrev CliConfigM := StateT Config (ExceptT String (ReaderM Arguments))\n\ndef parseArguments : CliConfigM Bool := do\n  let mut config \u2190 get\n  if (\u2190 optionalSwitch \"--help\") then\n    throw \"Usage: example [--help] [--verbose] [--input <input file>]\"\n  config := { config with\n    verbose := (\u2190 optionalSwitch \"--verbose\"),\n    input := (\u2190 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 <input file>]\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\nend Args2", "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/Args2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18476750166984324, "lm_q2_score": 0.04742587199949359, "lm_q1q2_score": 0.008762759883860204}}
{"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, Jannis Limperg\n-/\nprelude\nimport init.meta.tactic init.meta.type_context init.meta.rewrite_tactic init.meta.simp_tactic\nimport init.meta.smt.congruence_closure init.control.combinators\nimport init.meta.interactive_base init.meta.derive init.meta.match_tactic\nimport init.meta.congr_tactic init.meta.case_tag\n\nopen lean\nopen lean.parser\nopen native\n\nprecedence `?` : max\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nnamespace tactic\n/- allows metavars -/\nmeta def i_to_expr (q : pexpr) : tactic expr :=\nto_expr q tt\n\n/- allow metavars and no subgoals -/\nmeta def i_to_expr_no_subgoals (q : pexpr) : tactic expr :=\nto_expr q tt ff\n\n/- doesn't allows metavars -/\nmeta def i_to_expr_strict (q : pexpr) : tactic expr :=\nto_expr q ff\n\n/- Auxiliary version of i_to_expr for apply-like tactics.\n   This is a workaround for comment\n      https://github.com/leanprover/lean/issues/1342#issuecomment-307912291\n   at issue #1342.\n\n   In interactive mode, given a tactic\n\n        apply f\n\n   we want the apply tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n\n   Before we added `i_to_expr_for_apply`, the tactic\n\n       apply le_antisymm\n\n   would first elaborate `le_antisymm`, and create\n\n       @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4\n\n   The type class resolution problem\n        ?m_2 : weak_order ?m_1\n   by the elaborator since ?m_1 is not assigned yet, and the problem is\n   discarded.\n\n   Then, we would invoke `apply_core`, which would create two\n   new metavariables for the explicit arguments, and try to unify the resulting\n   type with the current target. After the unification,\n   the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost\n   the information about the pending type class resolution problem.\n\n   With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,\n   the apply_core tactic creates all metavariables, and solves the ones that\n   can be solved by type class resolution.\n\n   Another possible fix: we modify the elaborator to return pending\n   type class resolution problems, and store them in the tactic_state.\n-/\nmeta def i_to_expr_for_apply (q : pexpr) : tactic expr :=\nlet aux (n : name) : tactic expr := do\n  p \u2190 resolve_name n,\n  match p with\n  | (expr.const c []) := do r \u2190 mk_const c, save_type_info r q, return r\n  | _                 := i_to_expr p\n  end\nin match q with\n| (expr.const c [])          := aux c\n| (expr.local_const c _ _ _) := aux c\n| _                          := i_to_expr q\nend\n\nnamespace interactive\nopen _root_.interactive interactive.types expr\n\n/--\nitactic: parse a nested \"interactive\" tactic. That is, parse\n  `{` tactic `}`\n-/\nmeta def itactic : Type :=\ntactic unit\n\nmeta def propagate_tags (tac : itactic) : tactic unit :=\ndo tag \u2190 get_main_tag,\n   if tag = [] then tac\n   else focus1 $ do\n     tac,\n     gs \u2190 get_goals,\n     when (bnot gs.empty) $ do\n       new_tag \u2190 get_main_tag,\n       when new_tag.empty $ with_enable_tags (set_main_tag tag)\n\nmeta def concat_tags (tac : tactic (list (name \u00d7 expr))) : tactic unit :=\nmcond tags_enabled\n  (do in_tag \u2190 get_main_tag,\n      r \u2190 tac,\n      /- remove assigned metavars -/\n      r \u2190 r.mfilter $ \u03bb \u27e8n, m\u27e9, bnot <$> is_assigned m,\n      match r with\n      | [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/\n      | _        := r.mmap' (\u03bb \u27e8n, m\u27e9, set_tag m (n::in_tag))\n      end)\n  (tac >> skip)\n\n/--\nIf the current goal is a Pi/forall `\u2200 x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.\n\nIf the goal is an arrow `t \u2192 u`, then it puts `h : t` in the local context and the new goal target is `u`.\n\nIf the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.\n-/\nmeta def intro : parse ident_? \u2192 tactic unit\n| none     := propagate_tags (intro1 >> skip)\n| (some h) := propagate_tags (tactic.intro h >> skip)\n\n/--\nSimilar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.\n\nThe variant `intros h\u2081 ... h\u2099` introduces `n` new hypotheses using the given identifiers to name them.\n-/\nmeta def intros : parse ident_* \u2192 tactic unit\n| [] := propagate_tags (tactic.intros >> skip)\n| hs := propagate_tags (intro_lst hs >> skip)\n\n/--\nThe tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.\n\nExamples:\n```\nexample : \u2200 a b : nat, a = b \u2192 b = a :=\nbegin\n  introv h,\n  exact h.symm\nend\n```\nThe state after `introv h` is\n```\na b : \u2115,\nh : a = b\n\u22a2 b = a\n```\n\n```\nexample : \u2200 a b : nat, a = b \u2192 \u2200 c, b = c \u2192 a = c :=\nbegin\n  introv h\u2081 h\u2082,\n  exact h\u2081.trans h\u2082\nend\n```\nThe state after `introv h\u2081 h\u2082` is\n```\na b : \u2115,\nh\u2081 : a = b,\nc : \u2115,\nh\u2082 : b = c\n\u22a2 a = c\n```\n-/\nmeta def introv (ns : parse ident_*) : tactic unit :=\npropagate_tags (tactic.introv ns >> return ())\n\n/-- Parse a current name and new name for `rename`. -/\nprivate meta def rename_arg_parser : parser (name \u00d7 name) :=\n  prod.mk <$> ident <*> (optional (tk \"->\") *> ident)\n\n/-- Parse the arguments of `rename`. -/\nprivate meta def rename_args_parser : parser (list (name \u00d7 name)) :=\n  (functor.map (\u03bb x, [x]) rename_arg_parser)\n  <|>\n  (tk \"[\" *> sep_by (tk \",\") rename_arg_parser <* tk \"]\")\n\n/--\nRename one or more local hypotheses. The renamings are given as follows:\n\n```\nrename x y             -- rename x to y\nrename x \u2192 y           -- ditto\nrename [x y, a b]      -- rename x to y and a to b\nrename [x \u2192 y, a \u2192 b]  -- ditto\n```\n\nNote that if there are multiple hypotheses called `x` in the context, then\n`rename x y` will rename *all* of them. If you want to rename only one, use\n`dedup` first.\n-/\nmeta def rename (renames : parse rename_args_parser) : tactic unit :=\npropagate_tags $ tactic.rename_many $ native.rb_map.of_list renames\n\n/--\nThe `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\nmeta def apply (q : parse texpr) : tactic unit :=\nconcat_tags (do h \u2190 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 been 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 \u2190 i_to_expr_for_apply q, tactic.apply e cfg)\n\n/--\nSimilar to the `apply` tactic, but uses matching instead of unification.\n`apply_match t` is equivalent to `apply_with t {unify := ff}`\n-/\nmeta def mapply (q : parse texpr) : tactic unit :=\nconcat_tags (do e \u2190 i_to_expr_for_apply q, tactic.apply e {unify := ff})\n\n/--\nThis tactic tries to close the main goal `... \u22a2 t` by generating a term of type `t` using type class resolution.\n-/\nmeta def apply_instance : tactic unit :=\ntactic.apply_instance\n\n/--\nThis tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.\n\nNote that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat \u2192 Prop)`.\n-/\nmeta def refine (q : parse texpr) : tactic unit :=\ntactic.refine q\n\n/--\nThis tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.\n-/\nmeta def assumption : tactic unit :=\ntactic.assumption\n\n/-- Try to apply `assumption` to all goals. -/\nmeta def assumption' : tactic unit :=\ntactic.any_goals' tactic.assumption\n\nprivate meta def change_core (e : expr) : option expr \u2192 tactic unit\n| none     := tactic.change e\n| (some h) :=\n  do num_reverted : \u2115 \u2190 revert h,\n     expr.pi n bi d b \u2190 target,\n     tactic.change $ expr.pi n bi e b,\n     intron num_reverted\n\n/--\n`change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.\n\n`change u at h` will change a local hypothesis to `u`.\n\n`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.\n-/\nmeta def change (q : parse texpr) : parse (tk \"with\" *> texpr)? \u2192 parse location \u2192 tactic unit\n| none (loc.ns [none]) := do e \u2190 i_to_expr q, change_core e none\n| none (loc.ns [some h]) := do eq \u2190 i_to_expr q, eh \u2190 get_local h, change_core eq (some eh)\n| none _ := fail \"change-at does not support multiple locations\"\n| (some w) l :=\n  do u \u2190 mk_meta_univ,\n     ty \u2190 mk_meta_var (sort u),\n     eq \u2190 i_to_expr ``(%%q : %%ty),\n     ew \u2190 i_to_expr ``(%%w : %%ty),\n     let repl := \u03bbe : expr, e.replace (\u03bb a n, if a = eq then some ew else none),\n     l.try_apply\n       (\u03bbh, do e \u2190 infer_type h, change_core (repl e) (some h))\n       (do g \u2190 target, change_core (repl g) none)\n\n/--\nThis tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.\n-/\nmeta def exact (q : parse texpr) : tactic unit :=\ndo tgt : expr \u2190 target,\n   i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact\n/--\nLike `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.\n-/\nmeta def exacts : parse pexpr_list_or_texpr \u2192 tactic unit\n| [] := done\n| (t :: ts) := exact t >> exacts ts\n\n/--\nA synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.\n-/\nmeta def \u00abfrom\u00bb := exact\n\n/--\n`revert h\u2081 ... h\u2099` applies to any goal with hypotheses `h\u2081` ... `h\u2099`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.\n-/\nmeta def revert (ids : parse ident*) : tactic unit :=\npropagate_tags (do hs \u2190 mmap tactic.get_local ids, revert_lst hs, skip)\n\nprivate meta def resolve_name' (n : name) : tactic expr :=\ndo {\n  p \u2190 resolve_name n,\n  match p with\n  | expr.const n _ := mk_const n -- create metavars for universe levels\n  | _              := i_to_expr p\n  end\n}\n\n/- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.\n   This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.\n   Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.\n   Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/\nmeta def to_expr' (p : pexpr) : tactic expr :=\nmatch p with\n| (const c [])          := do new_e \u2190 resolve_name' c, save_type_info new_e p, return new_e\n| (local_const c _ _ _) := do new_e \u2190 resolve_name' c, save_type_info new_e p, return new_e\n| _                     := i_to_expr p\nend\n\n@[derive has_reflect]\nmeta structure rw_rule :=\n(pos  : pos)\n(symm : bool)\n(rule : pexpr)\n\nmeta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) :=\nlet aux (n : name) : tactic (list name) := do {\n  p \u2190 resolve_name n,\n  -- unpack local refs\n  let e := p.erase_annotations.get_app_fn.erase_annotations,\n  match e with\n  | const n _ := get_eqn_lemmas_for tt n\n  | _         := return []\n  end } <|> return [] in\nmatch r.rule with\n| const n _           := aux n\n| local_const n _ _ _ := aux n\n| _                   := return []\nend\n\nprivate meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit :=\nrs.mmap' $ \u03bb r, do\n save_info r.pos,\n eq_lemmas \u2190 get_rule_eqn_lemmas r,\n orelse'\n   (do e \u2190 to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg})\n   (eq_lemmas.mfirst $ \u03bb n, do e \u2190 mk_const n, rewrite_target e {symm := r.symm, ..cfg})\n   (eq_lemmas.empty)\n\nprivate meta def uses_hyp (e : expr) (h : expr) : bool :=\ne.fold ff $ \u03bb t _ r, r || to_bool (t = h)\n\nprivate meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule \u2192 expr \u2192 tactic unit\n| []      hyp := skip\n| (r::rs) hyp := do\n  save_info r.pos,\n  eq_lemmas \u2190 get_rule_eqn_lemmas r,\n  orelse'\n    (do e \u2190 to_expr' r.rule,\n      (if uses_hyp e hyp then pure e else rewrite_hyp e hyp {symm := r.symm, ..cfg}) >>= rw_hyp rs)\n    (eq_lemmas.mfirst $ \u03bb n, do e \u2190 mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)\n    (eq_lemmas.empty)\n\nmeta def rw_rule_p (ep : parser pexpr) : parser rw_rule :=\nrw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc \"\u2190\" (tk \"\u2190\" <|> tk \"<-\"))?) <*> ep\n\n@[derive has_reflect]\nmeta structure rw_rules_t :=\n(rules   : list rw_rule)\n(end_pos : option pos)\n\n-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations\nmeta def rw_rules : parser rw_rules_t :=\n(tk \"[\" *>\n rw_rules_t.mk <$> sep_by (skip_info (tk \",\")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0))\n               <*> (some <$> cur_pos <* set_goal_info_pos (tk \"]\")))\n<|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none\n\nprivate meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit :=\nmatch loca with\n| loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)\n| _            := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)\nend >> try (reflexivity reducible)\n    >> (returnopt rs.end_pos >>= save_info <|> skip)\n\n/--\n`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`\u2190` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.\n\n`rewrite [e\u2081, ..., e\u2099]` applies the given rules sequentially.\n\n`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `\u22a2` or `|-` can also be used, to signify the target of the goal.\n-/\nmeta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=\npropagate_tags (rw_core q l cfg)\n\n/--\nAn abbreviation for `rewrite`.\n-/\nmeta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=\npropagate_tags (rw_core q l cfg)\n\n/--\n`rewrite` followed by `assumption`.\n-/\nmeta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=\nrewrite q l cfg >> try assumption\n\n/--\nA variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.\n-/\nmeta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=\npropagate_tags (rw_core q l cfg)\n\n/--\nAn abbreviation for `erewrite`.\n-/\nmeta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=\npropagate_tags (rw_core q l cfg)\n\n/--\nReturns the unique names of all hypotheses (local constants) in the context.\n-/\nprivate meta def hyp_unique_names : tactic name_set :=\ndo ctx \u2190 local_context,\n   pure $ ctx.foldl (\u03bb r h, r.insert h.local_uniq_name) mk_name_set\n\n/--\nReturns all hypotheses (local constants) from the context except those whose\nunique names are in `hyp_uids`.\n-/\nprivate meta def hyps_except (hyp_uids : name_set) : tactic (list expr) :=\ndo ctx \u2190 local_context,\n   pure $ ctx.filter (\u03bb (h : expr), \u00ac hyp_uids.contains h.local_uniq_name)\n\n/--\nApply `t` to the main goal and revert any new hypothesis in the generated goals.\nIf `t` is a supported tactic or chain of supported tactics (e.g. `induction`,\n`cases`, `apply`, `constructor`), the generated goals are also tagged with case\ntags. You can then use `case` to focus such tagged goals.\n\nTwo typical uses of `with_cases`:\n\n1. Applying a custom eliminator:\n\n   ```\n   lemma my_nat_rec :\n     \u2200 n {P : \u2115 \u2192 Prop} (zero : P 0) (succ : \u2200 n, P n \u2192 P (n + 1)), P n := ...\n\n   example (n : \u2115) : n = n :=\n   begin\n     with_cases { apply my_nat_rec n },\n     case zero { refl },\n     case succ : m ih { refl }\n   end\n   ```\n\n2. Enabling the use of `case` after a chain of case-splitting tactics:\n\n   ```\n   example (n m : \u2115) : unit :=\n   begin\n     with_cases { cases n; induction m },\n     case nat.zero nat.zero { exact () },\n     case nat.zero nat.succ : k { exact () },\n     case nat.succ nat.zero : i { exact () },\n     case nat.succ nat.succ : k i ih_i { exact () }\n   end\n   ```\n-/\nmeta def with_cases (t : itactic) : tactic unit :=\nwith_enable_tags $ focus1 $ do\n  input_hyp_uids \u2190 hyp_unique_names,\n  t,\n  all_goals' $ do\n    in_tag \u2190 get_main_tag,\n    new_hyps \u2190 hyps_except input_hyp_uids,\n    n \u2190 revert_lst new_hyps,\n    set_main_tag (case_tag.from_tag_pi in_tag n).render\n\nprivate meta def generalize_arg_p_aux : pexpr \u2192 parser (pexpr \u00d7 name)\n| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)\n| _ := fail \"parse error\"\n\nprivate meta def generalize_arg_p : parser (pexpr \u00d7 name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\n/--\n`generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.\n\n`generalize h : e = x` in addition registers the hypothesis `h : e = x`.\n-/\nmeta def generalize (h : parse ident?) (_ : parse $ tk \":\") (p : parse generalize_arg_p) : tactic unit :=\npropagate_tags $\ndo let (p, x) := p,\n   e \u2190 i_to_expr p,\n   some h \u2190 pure h | tactic.generalize e x >> intro1 >> skip,\n   tgt \u2190 target,\n   -- if generalizing fails, fall back to not replacing anything\n   tgt' \u2190 do {\n     \u27e8tgt', _\u27e9 \u2190 solve_aux tgt (tactic.generalize e x >> target),\n     to_expr ``(\u03a0 x, %%e = x \u2192 %%(tgt'.binding_body.lift_vars 0 1))\n   } <|> to_expr ``(\u03a0 x, %%e = x \u2192 %%tgt),\n   t \u2190 assert h tgt',\n   swap,\n   exact ``(%%t %%e rfl),\n   intro x,\n   intro h\n\nmeta def cases_arg_p : parser (option name \u00d7 pexpr) :=\nwith_desc \"(id :)? expr\" $ do\n  t \u2190 texpr,\n  match t with\n  | (local_const x _ _ _) :=\n    (tk \":\" *> do t \u2190 texpr, pure (some x, t)) <|> pure (none, t)\n  | _ := pure (none, t)\n  end\n\n/--\n  Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag`\n  is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was\n  applied. `rs` should contain, for each subgoal, the constructor name\n  associated with that goal and the hypotheses that were introduced.\n-/\nprivate meta def set_cases_tags (in_tag : tag) (rs : list (name \u00d7 list expr)) : tactic unit :=\ndo gs \u2190 get_goals,\n   match gs with\n    -- if only one goal was produced, we should not make the tag longer\n   | [g] := set_tag g in_tag\n   | _   :=\n     let tgs : list (name \u00d7 list expr \u00d7 expr) :=\n       rs.map\u2082 (\u03bb \u27e8n, new_hyps\u27e9 g, \u27e8n, new_hyps, g\u27e9) gs in\n     tgs.mmap' $ \u03bb \u27e8n, new_hyps, g\u27e9, with_enable_tags $\n        set_tag g $\n          (case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render\n   end\n\nprecedence `generalizing` : 0\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih\u2081 : P a \u2192 Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih\u2081` ire chosen automatically.\n\n`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.\n\n`induction e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.\n\n`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables\n\n`induction e generalizing z\u2081 ... z\u2099`, where `z\u2081 ... z\u2099` are variables in the local context, generalizes over `z\u2081 ... z\u2099` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.\n\n`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.\n-/\nmeta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list)\n  (revert : parse $ (tk \"generalizing\" *> ident*)?) : tactic unit :=\ndo in_tag \u2190 get_main_tag,\nfocus1 $ do {\n    -- process `h : t` case\n    e \u2190 match hp with\n       | (some h, p) := do\n         x \u2190 get_unused_name,\n         generalize h () (p, x),\n         get_local x\n       | (none, p) := i_to_expr p\n       end,\n\n   -- generalize major premise\n   e \u2190 if e.is_local_constant then pure e\n       else tactic.generalize e >> intro1,\n\n   -- generalize major premise args\n   (e, newvars, locals) \u2190 do {\n      none \u2190 pure rec_name | pure (e, [], []),\n      t \u2190 infer_type e,\n      t \u2190 whnf_ginductive t,\n      const n _ \u2190 pure t.get_app_fn | pure (e, [], []),\n      env \u2190 get_env,\n      tt \u2190 pure $ env.is_inductive n | pure (e, [], []),\n      let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition\n        (\u03bb arg : expr, arg.is_local_constant),\n      _ :: _ \u2190 pure nonlocals | pure (e, [], []),\n\n      n \u2190 tactic.revert e,\n      newvars \u2190 nonlocals.mmap $ \u03bb arg, do {\n        n \u2190 revert_kdeps arg,\n        tactic.generalize arg,\n        h \u2190 intro1,\n        intron n,\n        -- now try to clear hypotheses that may have been abstracted away\n        let locals := arg.fold [] (\u03bb e _ acc, if e.is_local_constant then e::acc else acc),\n        locals.mmap' (try \u2218 clear),\n        pure h\n      },\n      intron (n-1),\n      e \u2190 intro1,\n      pure (e, newvars, locals)\n   },\n\n   -- revert `generalizing` params (and their dependencies, if any)\n   to_generalize \u2190 (revert.get_or_else []).mmap tactic.get_local,\n   num_generalized \u2190 revert_lst to_generalize,\n\n   -- perform the induction\n   rs \u2190 tactic.induction e ids rec_name,\n\n   -- re-introduce the generalized hypotheses\n   gen_hyps \u2190 all_goals $ do {\n     new_hyps \u2190 intron' num_generalized,\n     clear_lst (newvars.map local_pp_name),\n     (e::locals).mmap' (try \u2218 clear),\n     pure new_hyps\n   },\n\n   set_cases_tags in_tag $\n     @list.map\u2082 (name \u00d7 list expr \u00d7 list (name \u00d7 expr)) _ (name \u00d7 list expr)\n       (\u03bb \u27e8n, hyps, _\u27e9 gen_hyps, \u27e8n, hyps ++ gen_hyps\u27e9) rs gen_hyps\n}\n\nopen case_tag.match_result\n\nprivate meta def goals_with_matching_tag (ns : list name) :\n  tactic (list (expr \u00d7 case_tag) \u00d7 list (expr \u00d7 case_tag)) :=\ndo gs \u2190 get_goals,\n   (gs : list (expr \u00d7 tag)) \u2190 gs.mmap (\u03bb g, do t \u2190 get_tag g, pure (g, t)),\n   pure $ gs.foldr\n     (\u03bb \u27e8g, t\u27e9 \u27e8exact_matches, suffix_matches\u27e9,\n       match case_tag.parse t with\n       | none := \u27e8exact_matches, suffix_matches\u27e9\n       | some t :=\n         match case_tag.match_tag ns t with\n         | exact_match := \u27e8\u27e8g, t\u27e9 :: exact_matches, suffix_matches\u27e9\n         | fuzzy_match := \u27e8exact_matches, \u27e8g, t\u27e9 :: suffix_matches\u27e9\n         | no_match := \u27e8exact_matches, suffix_matches\u27e9\n         end\n       end)\n     ([], [])\n\nprivate meta def goal_with_matching_tag (ns : list name) : tactic (expr \u00d7 case_tag) :=\ndo \u27e8exact_matches, suffix_matches\u27e9 \u2190 goals_with_matching_tag ns,\n   match exact_matches, suffix_matches with\n   | [] , []  := fail format!\n     \"Invalid `case`: there is no goal tagged with suffix {ns}.\"\n   | [] , [g] := pure g\n   | [] , _   :=\n     let tags : list (list name) := suffix_matches.map (\u03bb \u27e8_, t\u27e9, t.case_names.reverse) in\n     fail format!\n     \"Invalid `case`: there is more than one goal tagged with suffix {ns}.\\nMatching tags: {tags}\"\n   | [g], _   := pure g\n   | _  , _   := fail format!\n     \"Invalid `case`: there is more than one goal tagged with tag {ns}.\"\n   end\n\nmeta def case_arg_parser : lean.parser (list name \u00d7 option (list name)) :=\nprod.mk <$> ident_* <*> (tk \":\" *> ident_*)?\n\nmeta def case_parser : lean.parser (list (list name \u00d7 option (list name))) :=\n  (list_of case_arg_parser)\n  <|>\n  (functor.map (\u03bb x, [x]) case_arg_parser)\n\n\n/--\nFocuses on a goal ('case') generated by `induction`, `cases` or `with_cases`.\n\nThe goal is selected by giving one or more names which must match exactly one\ngoal. A goal is matched if the given names are a suffix of its goal tag.\nAdditionally, each name in the sequence can be abbreviated to a suffix of the\ncorresponding name in the goal tag. Thus, a goal with tag\n```\nnat.zero, list.nil\n```\ncan be selected with any of these invocations (among others):\n```\ncase nat.zero list.nil {...}\ncase nat.zero nil      {...}\ncase zero     nil      {...}\ncase          nil      {...}\n```\n\nAdditionally, the form\n```\ncase C : N\u2080 ... N\u2099 {...}\n```\ncan be used to rename hypotheses introduced by the preceding\n`cases`/`induction`/`with_cases`, using the names `N\u1d62`. For example:\n```\nexample (xs : list \u2115) : xs = xs :=\nbegin\n  induction xs,\n  case nil { reflexivity },\n  case cons : x xs ih {\n    -- x : \u2115, xs : list \u2115, ih : xs = xs\n    reflexivity }\nend\n```\n\nNote that this renaming functionality only work reliably *directly after* an\n`induction`/`cases`/`with_cases`. If you need to perform additional work after\nan `induction` or `cases` (e.g. introduce hypotheses in all goals), use\n`with_cases`.\n\nMultiple cases can be handled by the same tactic block with\n```\ncase [A : N\u2080 ... N\u2099, B : M\u2080 ... M\u2099] {...}\n```\n-/\n/-\nTODO `case` could be generalised to work with zero names as well. The form\n\n  case : x y z { ... }\n\nwould select the first goal (or the first goal with a case tag), renaming\nhypotheses to `x, y, z`. The renaming functionality would be available only if\nthe goal has a case tag.\n-/\nmeta def case (args : parse case_parser) (tac : itactic) : tactic unit :=\ndo\n  target_goals \u2190 args.mmap (\u03bb \u27e8ns, ids\u27e9, do\n    \u27e8goal, tag\u27e9 \u2190 goal_with_matching_tag ns,\n    let ids := ids.get_or_else [],\n    let num_ids := ids.length,\n    goals \u2190 get_goals,\n    let other_goals := goals.filter (\u2260 goal),\n    set_goals [goal],\n    match tag with\n    | (case_tag.pi _ num_args) := do\n      intro_lst ids,\n      when (num_ids < num_args) $ intron (num_args - num_ids)\n    | (case_tag.hyps _ new_hyp_names) := do\n        let num_new_hyps := new_hyp_names.length,\n        when (num_ids > num_new_hyps) $ fail format!\n          (\"Invalid `case`: You gave {num_ids} names, but the case introduces \" ++\n          \"{num_new_hyps} new hypotheses.\"),\n        let renamings := native.rb_map.of_list (new_hyp_names.zip ids),\n        propagate_tags $ tactic.rename_many renamings tt tt\n    end,\n    goals \u2190 get_goals,\n    set_goals other_goals,\n    match goals with\n    | [g] := return g\n    | _ := fail \"Unexpected goals introduced by renaming\"\n    end),\n  remaining_goals \u2190 get_goals,\n  set_goals target_goals,\n  tac,\n  unsolved_goals \u2190 get_goals,\n  match unsolved_goals with\n  | [] := set_goals remaining_goals\n  | _ := fail \"case tactic failed, focused goals have not been solved\"\n  end\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 \u2192 Q n`, and one goal with target `\u2200 (a : \u2115), (\u03bb (w : \u2115), n = w \u2192 Q n) (nat.succ a)`. Here the name `a` is chosen automatically.\n-/\nmeta def destruct (p : parse texpr) : tactic unit :=\ni_to_expr p >>= tactic.destruct\n\nmeta def cases_core (e : expr) (ids : list name := []) : tactic unit :=\ndo in_tag \u2190 get_main_tag,\n   focus1 $ do\n     rs \u2190 tactic.cases e ids,\n     set_cases_tags in_tag rs\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.\n\n`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.\n\n`cases e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.\n\n`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.\n-/\nmeta def cases : parse cases_arg_p \u2192 parse with_ident_list \u2192 tactic unit\n| (none,   p) ids := do\n  e \u2190 i_to_expr p,\n  cases_core e ids\n| (some h, p) ids := do\n  x   \u2190 get_unused_name,\n  generalize h () (p, x),\n  hx  \u2190 get_local x,\n  cases_core hx ids\n\n\nprivate meta def find_matching_hyp (ps : list pattern) : tactic expr :=\nany_hyp $ \u03bb h, do\n  type \u2190 infer_type h,\n  ps.mfirst $ \u03bb p, do\n  match_pattern p type,\n  return h\n\n/--\n`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.\n`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.\n`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_matching* [_ \u2228 _, _ \u2227 _]\n```\n-/\nmeta def cases_matching (rec : parse $ (tk \"*\")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=\ndo ps \u2190 ps.mmap pexpr_to_pattern,\n   if rec.is_none\n   then find_matching_hyp ps >>= cases_core\n   else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core\n\n/-- Shorthand for `cases_matching` -/\nmeta def casesm (rec : parse $ (tk \"*\")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=\ncases_matching rec ps\n\nprivate meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit :=\nany_hyp $ \u03bb h, do\n  I \u2190 expr.get_app_fn <$> (infer_type h >>= head_beta),\n  guard I.is_constant,\n  guard (I.const_name \u2208 type_names),\n  tactic.focus1 (cases_core h >> if at_most_one then do n \u2190 num_goals, guard (n <= 1) else skip)\n\n/--\n`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`\n`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`\n`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`\n`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_type* or and\n```\n-/\nmeta def cases_type (one : parse $ (tk \"!\")?) (rec : parse $ (tk \"*\")?) (type_names : parse ident*) : tactic unit :=\ndo type_names \u2190 type_names.mmap resolve_constant,\n   if rec.is_none\n   then try_cases_for_types type_names (bnot one.is_none)\n   else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none)\n\n/--\nTries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.\n-/\nmeta def trivial : tactic unit :=\ntactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail \"trivial tactic failed\"\n\n/--\nCloses the main goal using `sorry`.\n-/\nmeta def admit : tactic unit := tactic.admit\n\n/--\nCloses the main goal using `sorry`.\n-/\nmeta def \u00absorry\u00bb : tactic unit := tactic.admit\n\n/--\nThe contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.\n-/\nmeta def contradiction : tactic unit :=\ntactic.contradiction\n\n/--\n`iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.\n\n`iterate n { t }` applies `t` `n` times.\n-/\nmeta def iterate (n : parse small_nat?) (t : itactic) : tactic unit :=\nmatch n with\n| none   := tactic.iterate' t\n| some n := iterate_exactly' n t\nend\n\n/--\n`repeat { t }` applies `t` to each goal. If the application succeeds,\nthe tactic is applied recursively to all the generated subgoals until it eventually fails.\nThe recursion stops in a subgoal when the tactic has failed to make progress.\nThe tactic `repeat { t }` never fails.\n-/\nmeta def repeat : itactic \u2192 tactic unit :=\ntactic.repeat\n\n/--\n`try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.\n-/\nmeta def try : itactic \u2192 tactic unit :=\ntactic.try\n\n/--\nA do-nothing tactic that always succeeds.\n-/\nmeta def skip : tactic unit :=\ntactic.skip\n\n/--\n`solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.\n-/\nmeta def solve1 : itactic \u2192 tactic unit :=\ntactic.solve1\n\n/--\n`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.\n-/\nmeta def abstract (id : parse ident?) (tac : itactic) : tactic unit :=\ntactic.abstract tac id\n\n/--\n`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.\n-/\nmeta def all_goals : itactic \u2192 tactic unit :=\ntactic.all_goals'\n\n/--\n`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.\n-/\nmeta def any_goals : itactic \u2192 tactic unit :=\ntactic.any_goals'\n\n/--\n`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.\n-/\nmeta def focus (tac : itactic) : tactic unit :=\ntactic.focus1 tac\n\nprivate meta def assume_core (n : name) (ty : pexpr) :=\ndo t \u2190 target,\n    when (not $ t.is_pi \u2228 t.is_let) whnf_target,\n    t \u2190 target,\n    when (not $ t.is_pi \u2228 t.is_let) $\n      fail \"assume tactic failed, Pi/let expression expected\",\n    ty \u2190 i_to_expr ``(%%ty : Sort*),\n    unify ty t.binding_domain,\n    intro_core n >> skip\n\n/--\nAssuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.\n\n`assume (h\u2081 : t\u2081) ... (h\u2099 : t\u2099)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.\n-/\nmeta def \u00abassume\u00bb : parse (sum.inl <$> (tk \":\" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) \u2192 tactic unit\n| (sum.inl ty)      := assume_core `this ty\n| (sum.inr binders) :=\n  binders.mmap' $ \u03bb b, assume_core b.local_pp_name b.local_type\n\n/--\n`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\nmeta def \u00abhave\u00bb (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?) (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\nlet h := h.get_or_else `this in\nmatch q\u2081, q\u2082 with\n| some e, some p := do\n  t \u2190 i_to_expr ``(%%e : Sort*),\n  v \u2190 i_to_expr ``(%%p : %%t),\n  tactic.assertv h t v\n| none, some p := do\n  p \u2190 i_to_expr p,\n  tactic.note h none p\n| some e, none := i_to_expr ``(%%e : Sort*) >>= tactic.assert h\n| none, none := do\n  u \u2190 mk_meta_univ,\n  e \u2190 mk_meta_var (sort u),\n  tactic.assert h e\nend >> skip\n\n/--\n`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\nmeta def \u00ablet\u00bb (h : parse ident?) (q\u2081 : parse (tk \":\" *> texpr)?) (q\u2082 : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\nlet h := h.get_or_else `this in\nmatch q\u2081, q\u2082 with\n| some e, some p := do\n  t \u2190 i_to_expr ``(%%e : Sort*),\n  v \u2190 i_to_expr ``(%%p : %%t),\n  tactic.definev h t v\n| none, some p := do\n  p \u2190 i_to_expr p,\n  tactic.pose h none p\n| some e, none := i_to_expr ``(%%e : Sort*) >>= tactic.define h\n| none, none := do\n  u \u2190 mk_meta_univ,\n  e \u2190 mk_meta_var (sort u),\n  tactic.define h e\nend >> skip\n\n/--\n`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.\n-/\nmeta def \u00absuffices\u00bb (h : parse ident?) (t : parse (tk \":\" *> texpr)?) : tactic unit :=\n\u00abhave\u00bb h t none >> tactic.swap\n\n/--\nThis tactic displays the current state in the tracing buffer.\n-/\nmeta def trace_state : tactic unit :=\ntactic.trace_state\n\n/--\n`trace a` displays `a` in the tracing buffer.\n-/\nmeta def trace {\u03b1 : Type} [has_to_tactic_format \u03b1] (a : \u03b1) : tactic unit :=\ntactic.trace a\n\n/--\n`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.\n\n`existsi [e\u2081, ..., e\u2099]` iteratively does the same for each expression in the list.\n-/\nmeta def existsi : parse pexpr_list_or_texpr \u2192 tactic unit\n| []      := return ()\n| (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps\n\n/--\nThis tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.\n-/\nmeta def constructor : tactic unit :=\nconcat_tags tactic.constructor\n\n/--\nSimilar to `constructor`, but only non-dependent premises are added as new goals.\n-/\nmeta def econstructor : tactic unit :=\nconcat_tags tactic.econstructor\n\n/--\nApplies the first constructor when the type of the target is an inductive data type with two constructors.\n-/\nmeta def left : tactic unit :=\nconcat_tags tactic.left\n\n/--\nApplies the second constructor when the type of the target is an inductive data type with two constructors.\n-/\nmeta def right : tactic unit :=\nconcat_tags tactic.right\n\n/--\nApplies the constructor when the type of the target is an inductive data type with one constructor.\n-/\nmeta def split : tactic unit :=\nconcat_tags tactic.split\n\nprivate meta def constructor_matching_aux (ps : list pattern) : tactic unit :=\ndo t \u2190 target, ps.mfirst (\u03bb p, match_pattern p t), constructor\n\nmeta def constructor_matching (rec : parse $ (tk \"*\")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=\ndo ps \u2190 ps.mmap pexpr_to_pattern,\n   if rec.is_none then constructor_matching_aux ps\n   else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps\n\n/--\nReplaces the target of the main goal by `false`.\n-/\nmeta def exfalso : tactic unit :=\ntactic.exfalso\n\n/--\nThe `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t\u2081)` and `(c t\u2082)` are two terms that are equal then  `t\u2081` and `t\u2082` are equal too.\n\nIf `q` is a proof of a statement of conclusion `t\u2081 = t\u2082`, then injection applies injectivity to derive the equality of all arguments of `t\u2081` and `t\u2082` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t\u2081` and `t\u2082` should be constructor applications of the same constructor.\n\nGiven `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h\u2081 h\u2082` uses the names `h\u2081` and `h\u2082` to name the new hypotheses.\n-/\nmeta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit :=\ndo e \u2190 i_to_expr q, tactic.injection_with e hs, try assumption\n\n/--\n`injections with h\u2081 ... h\u2099` iteratively applies `injection` to hypotheses using the names `h\u2081 ... h\u2099`.\n-/\nmeta def injections (hs : parse with_ident_list) : tactic unit :=\ndo tactic.injections_with hs, try assumption\n\nend interactive\n\nmeta structure simp_config_ext extends simp_config :=\n(discharger : tactic unit := failed)\n\nsection mk_simp_set\nopen expr interactive.types\n\n@[derive has_reflect]\nmeta inductive simp_arg_type : Type\n| all_hyps  : simp_arg_type\n| except    : name  \u2192 simp_arg_type\n| expr      : pexpr \u2192 simp_arg_type\n| symm_expr : pexpr \u2192 simp_arg_type\n\nmeta instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type :=\n\u27e8\u03bb a, match a with\n| simp_arg_type.all_hyps := pure \"*\"\n| (simp_arg_type.except n) := pure format!\"-{n}\"\n| (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp\n| (simp_arg_type.symm_expr e) := ((++) \"\u2190\") <$> (i_to_expr_no_subgoals e >>= pp)\nend\u27e9\n\nmeta def simp_arg : parser simp_arg_type :=\n(tk \"*\" *> return simp_arg_type.all_hyps) <|>\n(tk \"-\" *> simp_arg_type.except <$> ident) <|>\n(tk \"<-\" *> simp_arg_type.symm_expr <$> texpr) <|>\n(simp_arg_type.expr <$> texpr)\n\nmeta def simp_arg_list : parser (list simp_arg_type) :=\n(tk \"*\" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return []\n\nprivate meta def resolve_exception_ids (all_hyps : bool) : list name \u2192 list name \u2192 list name \u2192 tactic (list name \u00d7 list name)\n| []        gex hex := return (gex.reverse, hex.reverse)\n| (id::ids) gex hex := do\n  p \u2190 resolve_name id,\n  let e := p.erase_annotations.get_app_fn.erase_annotations,\n  match e with\n  | const n _           := resolve_exception_ids ids (n::gex) hex\n  | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! \"invalid local exception {id}, '*' was not used\") >>\n                           resolve_exception_ids ids gex (n::hex)\n  | _                   := fail $ sformat! \"invalid exception {id}, unknown identifier\"\n  end\n\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`.\n  This version fails when an argument of the form `simp_arg_type.symm_expr`\n  is included, so that `simp`-like tactics that do not (yet) support backwards rewriting\n  should properly report an error but function normally on other inputs.\n-/\nmeta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr \u00d7 list name \u00d7 list name \u00d7 bool :=\ndo\n  (hs, ex, all) \u2190 hs.mfoldl\n    (\u03bb (r : (list pexpr \u00d7 list name \u00d7 bool)) h, do\n      let (es, ex, all) := r,\n      match h with\n      | simp_arg_type.all_hyps    := pure (es, ex, tt)\n      | simp_arg_type.except id   := pure (es, id::ex, all)\n      | simp_arg_type.expr e      := pure (e::es, ex, all)\n      | simp_arg_type.symm_expr _ := fail \"arguments of the form '\u2190...' are not supported\"\n      end)\n    ([], [], ff),\n  (gex, hex) \u2190 resolve_exception_ids all ex [] [],\n  return (hs.reverse, gex, hex, all)\n\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is the newer version of `decode_simp_arg_list`,\n  and has a new name for backwards compatibility.\n  This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`.\n-/\nmeta def decode_simp_arg_list_with_symm (hs : list simp_arg_type) : tactic $ list (pexpr \u00d7 bool) \u00d7 list name \u00d7 list name \u00d7 bool :=\ndo\n  let (hs, ex, all) := hs.foldl\n    (\u03bb r h,\n       match r, h with\n       | (es, ex, all), simp_arg_type.all_hyps    := (es, ex, tt)\n       | (es, ex, all), simp_arg_type.except id   := (es, id::ex, all)\n       | (es, ex, all), simp_arg_type.expr e      := ((e, ff)::es, ex, all)\n       | (es, ex, all), simp_arg_type.symm_expr e := ((e, tt)::es, ex, all)\n       end)\n    ([], [], ff),\n  (gex, hex) \u2190 resolve_exception_ids all ex [] [],\n  return (hs.reverse, gex, hex, all)\n\nprivate meta def add_simps : simp_lemmas \u2192 list (name \u00d7 bool) \u2192 tactic simp_lemmas\n| s []      := return s\n| s (n::ns) := do s' \u2190 s.add_simp n.fst n.snd, add_simps s' ns\n\nprivate meta def report_invalid_simp_lemma {\u03b1 : Type} (n : name): tactic \u03b1 :=\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 (\u03bb p, (to_fmt p).indent 4))\n  | _ := failed\n  end\n\nprivate meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) (symm : bool) :\n  tactic (simp_lemmas \u00d7 list name) :=\ndo\n  p \u2190 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 guard (\u00ac symm), has_attribute `congr n, s \u2190 s.add_congr n, pure (s, u))\n    <|>\n    (do b \u2190 is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s \u2190 s.add_simp n symm, return (s, u))\n    <|>\n    (do eqns \u2190 get_eqn_lemmas_for tt n,\n        guard (eqns.length > 0),\n        save_const_type_info n ref,\n        s \u2190 add_simps s (eqns.map (\u03bb e, (e, ff))),\n        return (s, u))\n    <|>\n    (do env \u2190 get_env, guard (env.is_projection n).is_some, return (s, n::u))\n    <|>\n    report_invalid_simp_lemma n\n  | _ :=\n    (do e \u2190 i_to_expr_no_subgoals p, b \u2190 is_valid_simp_lemma e, guard b, try (save_type_info e ref), s \u2190 s.add e symm, return (s, u))\n    <|>\n    report_invalid_simp_lemma n\n  end\n\nprivate meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) (symm : bool) :\n  tactic (simp_lemmas \u00d7 list name) :=\nmatch p with\n| (const c [])          := simp_lemmas.resolve_and_add s u c p symm\n| (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p symm\n| _                     := do new_e \u2190 i_to_expr_no_subgoals p,\n                              s \u2190 s.add new_e symm,\n                              return (s, u)\nend\n\nprivate meta def simp_lemmas.append_pexprs :\n  simp_lemmas \u2192 list name \u2192 list (pexpr \u00d7 bool) \u2192 tactic (simp_lemmas \u00d7 list name)\n| s u []                 := return (s, u)\n| s u (l::ls) := do\n  (s, u) \u2190 simp_lemmas.add_pexpr s u l.fst l.snd,\n  simp_lemmas.append_pexprs s u ls\n\nmeta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool)\n                          : tactic (bool \u00d7 simp_lemmas \u00d7 list name) :=\ndo (hs, gex, hex, all_hyps) \u2190 decode_simp_arg_list_with_symm hs,\n   when (all_hyps \u2227 at_star \u2227 not hex.empty) $ fail \"A tactic of the form `simp [*, -h] at *` is currently not supported\",\n   s      \u2190 join_user_simp_lemmas no_dflt attr_names,\n   -- Erase `h` from the default simp set for calls of the form `simp [\u2190h]`.\n   let to_erase := hs.foldl (\u03bb l h, match h with\n                                    | (const id _, tt) := id :: l\n                                    | (local_const id _ _ _, tt) := id :: l\n                                    | _ := l\n                                    end ) [],\n   let s := s.erase to_erase,\n   (s, u) \u2190 simp_lemmas.append_pexprs s [] hs,\n   s      \u2190 if not at_star \u2227 all_hyps then do\n              ctx \u2190 collect_ctx_simps,\n              let ctx := ctx.filter (\u03bb h, h.local_uniq_name \u2209 hex), -- remove local exceptions\n              s.append ctx\n            else return s,\n   -- add equational lemmas, if any\n   gex \u2190 gex.mmap (\u03bb n, list.cons n <$> get_eqn_lemmas_for tt n),\n   return (all_hyps, simp_lemmas.erase s $ gex.join, u)\n\nmeta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas \u00d7 list name) :=\nprod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff)\nend mk_simp_set\n\nnamespace interactive\nopen _root_.interactive interactive.types expr\n\nmeta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic name_set :=\ndo (to_remove, lmss) \u2190 @list.mfoldl tactic _ (list expr \u00d7 name_set) _ (\u03bb \u27e8hs, lms\u27e9 h,\n  do h_type \u2190 infer_type h,\n    (do (new_h_type, pr, new_lms) \u2190 simplify s u h_type cfg `eq discharger,\n             assert h.local_pp_name new_h_type,\n             mk_eq_mp pr h >>= tactic.exact >> return (h::hs, lms.union new_lms))\n         <|>\n         (return (hs, lms)))\n      ([], mk_name_set) hs,\n   (lms, goal_simplified) \u2190 if tgt\n     then (simp_target s u cfg discharger >>= \u03bb ns, return (ns, tt)) <|> (return (mk_name_set, ff))\n     else (return (mk_name_set, ff)),\n   guard (cfg.fail_if_unchanged = ff \u2228 to_remove.length > 0 \u2228 goal_simplified) <|> fail \"simplify tactic failed to simplify\",\n   to_remove.reverse.mmap' (\u03bb h, try (clear h)),\n   return (lmss.union lms)\n\nmeta def simp_core (cfg : simp_config) (discharger : tactic unit)\n                   (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name)\n                   (locat : loc) : tactic name_set :=\ndo lms \u2190 match locat with\n  | loc.wildcard := do (all_hyps, s, u) \u2190 mk_simp_set_core no_dflt attr_names hs tt,\n                      if all_hyps then tactic.simp_all s u cfg discharger\n                      else do hyps \u2190 non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt\n  | _            := do (s, u) \u2190 mk_simp_set no_dflt attr_names hs,\n                      ns \u2190 locat.get_locals,\n                      simp_core_aux cfg discharger s u ns locat.include_goal\n  end,\n  try tactic.triv,\n  try (tactic.reflexivity reducible),\n  return lms\n\n/--\nThe `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.\n\n`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.\n\n`simp [h\u2081 h\u2082 ... h\u2099]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h\u1d62`'s, where the `h\u1d62`'s are expressions. If `h\u1d62` is preceded by left arrow (`\u2190` or `<-`), the simplification is performed in the reverse direction. If an `h\u1d62` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.\n\n`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.\n\n`simp *` is a shorthand for `simp [*]`.\n\n`simp only [h\u2081 h\u2082 ... h\u2099]` is like `simp [h\u2081 h\u2082 ... h\u2099]` but does not use `[simp]` lemmas\n\n`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id\u1d62`.\n\n`simp at h\u2081 h\u2082 ... h\u2099` simplifies the non-dependent hypotheses `h\u2081 : T\u2081` ... `h\u2099 : T\u2099`. The tactic fails if the target or another hypothesis depends on one of them. The token `\u22a2` or `|-` can be added to the list to include the target.\n\n`simp at *` simplifies all the hypotheses and the target.\n\n`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.\n\n`simp with attr\u2081 ... attr\u2099` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr\u2081]`, ..., `[attr\u2099]` or `[simp]`.\n-/\nmeta def simp (use_iota_eqn : parse $ (tk \"!\")?) (trace_lemmas : parse $ (tk \"?\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n              (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit :=\nlet cfg := match use_iota_eqn, trace_lemmas with\n| none    , none     := cfg\n| (some _), none     := {iota_eqn := tt, ..cfg}\n| none    , (some _) := {trace_lemmas := tt, ..cfg}\n| (some _), (some _) := {iota_eqn := tt, trace_lemmas := tt, ..cfg}\nend in\npropagate_tags $\ndo lms \u2190 simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat,\n  if cfg.trace_lemmas then trace (\u2191\"Try this: simp only \" ++ to_fmt lms.to_list) else skip\n\n/--\nJust construct the simp set and trace it. Used for debugging.\n-/\nmeta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit :=\ndo (s, _) \u2190 mk_simp_set no_dflt attr_names hs,\n   s.pp >>= trace\n\n/--\n`simp_intros h\u2081 h\u2082 ... h\u2099` is similar to `intros h\u2081 h\u2082 ... h\u2099` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.\n\nAs with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.\n-/\nmeta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n                     (cfg : simp_intros_config := {}) : tactic unit :=\ndo (s, u) \u2190 mk_simp_set no_dflt attr_names hs,\n   when (\u00acu.empty) (fail (sformat! \"simp_intros tactic does not support {u}\")),\n   tactic.simp_intros s u ids cfg,\n   try triv >> try (reflexivity reducible)\n\nprivate meta def to_simp_arg_list (symms : list bool) (es : list pexpr) : list simp_arg_type :=\n(symms.zip es).map (\u03bb \u27e8s, e\u27e9, if s then simp_arg_type.symm_expr e else simp_arg_type.expr e)\n\n/--\n`dsimp` is similar to `simp`, except that it only uses definitional equalities.\n-/\nmeta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list)\n               (l : parse location) (cfg : dsimp_config := {}) : tactic unit :=\ndo (s, u) \u2190 mk_simp_set no_dflt attr_names es,\nmatch l with\n| loc.wildcard :=\n  /- Remark: we cannot revert frozen local instances.\n     We disable zeta expansion because to prevent `intron n` from failing.\n     Another option is to put a \"marker\" at the current target, and\n     implement `intro_upto_marker`. -/\n  do n \u2190 revert_all,\n     dsimp_target s u {zeta := ff ..cfg},\n     intron n\n| _ := l.apply (\u03bb h, dsimp_hyp h s u cfg) (dsimp_target s u cfg)\nend\n\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.\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/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.\n-/\nmeta def symmetry : tactic unit :=\ntactic.symmetry\n\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.\n\n`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.\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) \u2190 target_lhs_rhs,\n     i_to_expr q >>= unify rhs\nend\n\n/--\nProves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.\n-/\nmeta def ac_reflexivity : tactic unit :=\ntactic.ac_refl\n\n/--\nAn abbreviation for `ac_reflexivity`.\n-/\nmeta def ac_refl : tactic unit :=\ntactic.ac_refl\n\n/--\nTries to prove the main goal using congruence closure.\n-/\nmeta def cc : tactic unit :=\ntactic.cc\n\n/--\nGiven hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\n-/\nmeta def subst (q : parse texpr) : tactic unit :=\ni_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible)\n\n/--\nApply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.\n-/\nmeta def subst_vars : tactic unit :=\ntactic.subst_vars\n\n/--\n`clear h\u2081 ... h\u2099` tries to clear each hypothesis `h\u1d62` from the local context.\n-/\nmeta def clear : parse ident* \u2192 tactic unit :=\ntactic.clear_lst\n\nprivate meta def to_qualified_name_core : name \u2192 list name \u2192 tactic name\n| n []        := fail $ \"unknown declaration '\" ++ to_string n ++ \"'\"\n| n (ns::nss) := do\n  curr \u2190 return $ ns ++ n,\n  env  \u2190 get_env,\n  if env.contains curr then return curr\n  else to_qualified_name_core n nss\n\nprivate meta def to_qualified_name (n : name) : tactic name :=\ndo env \u2190 get_env,\n   if env.contains n then return n\n   else do\n     ns \u2190 open_namespaces,\n     to_qualified_name_core n ns\n\nprivate meta def to_qualified_names : list name \u2192 tactic (list name)\n| []      := return []\n| (c::cs) := do new_c \u2190 to_qualified_name c, new_cs \u2190 to_qualified_names cs, return (new_c::new_cs)\n\n/--\nSimilar to `unfold`, but only uses definitional equalities.\n-/\nmeta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit :=\nmatch l with\n| (loc.wildcard) := do ls \u2190 tactic.local_context,\n                          n \u2190 revert_lst ls,\n                          new_cs \u2190 to_qualified_names cs,\n                          dunfold_target new_cs cfg,\n                          intron n\n| _              := do new_cs \u2190 to_qualified_names cs, l.apply (\u03bb h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg)\nend\n\nprivate meta def delta_hyps : list name \u2192 list name \u2192 tactic unit\n| cs []      := skip\n| cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs\n\n/--\nSimilar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.\n-/\nmeta def delta : parse ident* \u2192 parse location \u2192 tactic unit\n| cs (loc.wildcard) := do ls \u2190 tactic.local_context,\n                          n \u2190 revert_lst ls,\n                          new_cs \u2190 to_qualified_names cs,\n                          delta_target new_cs,\n                          intron n\n| cs l              := do new_cs \u2190 to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs)\n\nprivate meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool :=\nhs.mfoldl (\u03bb r h, do h \u2190 get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff\n\n/--\nThis tactic unfolds all structure projections.\n-/\nmeta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit :=\nmatch l with\n| loc.wildcard := do ls \u2190 local_context,\n                     b\u2081 \u2190 unfold_projs_hyps cfg (ls.map expr.local_pp_name),\n                     b\u2082 \u2190 (tactic.unfold_projs_target cfg >> return tt) <|> return ff,\n                     when (not b\u2081 \u2227 not b\u2082) (fail \"unfold_projs failed to simplify\")\n| _            :=\n  l.try_apply (\u03bb h, unfold_projs_hyp h cfg)\n    (tactic.unfold_projs_target cfg) <|> fail \"unfold_projs failed to simplify\"\nend\n\nend interactive\n\nmeta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) :=\ncs.mmap $ \u03bb c, do\n  n   \u2190 resolve_name c,\n  hs  \u2190 get_eqn_lemmas_for ff n.const_name,\n  env \u2190 get_env,\n  let p := env.is_projection n.const_name,\n  when (hs.empty \u2227 p.is_none) (fail (sformat! \"{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection\")),\n  return $ simp_arg_type.expr (expr.const c [])\n\nstructure unfold_config extends simp_config :=\n(zeta               := ff)\n(proj               := ff)\n(eta                := ff)\n(canonize_instances := ff)\n(constructor_eq     := ff)\n\nnamespace interactive\nopen _root_.interactive interactive.types expr\n\n/--\nGiven defined constants `e\u2081 ... e\u2099`, `unfold e\u2081 ... e\u2099` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.\n\nAs with `simp`, the `at` modifier can be used to specify locations for the unfolding.\n-/\nmeta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit :=\ndo es \u2190 ids_to_simp_arg_list \"unfold\" cs,\n   let no_dflt := tt,\n   simp_core cfg.to_simp_config failed no_dflt es [] locat,\n   skip\n\n/--\nSimilar to `unfold`, but does not iterate the unfolding.\n-/\nmeta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit :=\nunfold cs locat cfg\n\n/--\nIf the target of the main goal is an `opt_param`, assigns the default value.\n-/\nmeta def apply_opt_param : tactic unit :=\ntactic.apply_opt_param\n\n/--\nIf the target of the main goal is an `auto_param`, executes the associated tactic.\n-/\nmeta def apply_auto_param : tactic unit :=\ntactic.apply_auto_param\n\n/--\nFails if the given tactic succeeds.\n-/\nmeta def fail_if_success (tac : itactic) : tactic unit :=\ntactic.fail_if_success tac\n\n/--\nSucceeds if the given tactic fails.\n-/\nmeta def success_if_fail (tac : itactic) : tactic unit :=\ntactic.success_if_fail tac\n\nmeta def guard_expr_eq (t : expr) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo e \u2190 to_expr p, guard (alpha_eqv t e)\n\n/--\n`guard_target t` fails if the target of the main goal is not `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_target (p : parse texpr) : tactic unit :=\ndo t \u2190 target, guard_expr_eq t p\n\n/--\n`guard_hyp h : t` fails if the hypothesis `h` does not have type `t`.\nWe use this tactic for writing tests.\n-/\nmeta def guard_hyp (n : parse ident)\n  (ty : parse (tk \":\" *> texpr)?)\n  (val : parse (tk \":=\" *> texpr)?) : tactic unit := do\n  h \u2190 get_local n,\n  ldecl \u2190 tactic.unsafe.type_context.run (do\n    lctx \u2190 unsafe.type_context.get_local_context,\n    pure $ lctx.get_local_decl h.local_uniq_name),\n  ldecl \u2190 ldecl | fail format!\"hypothesis {h} not found\",\n  match ty with\n  | some p := guard_expr_eq ldecl.type p\n  | none := skip\n  end,\n  match ldecl.value, val with\n  | none, some _ := fail format!\"{h} is not a let binding\"\n  | some _, none := fail format!\"{h} is a let binding\"\n  | some hval, some val := guard_expr_eq hval val\n  | none, none := skip\n  end\n\n/--\n`match_target t` fails if target does not match pattern `t`.\n-/\nmeta def match_target (t : parse texpr) (m := reducible) : tactic unit :=\ntactic.match_target t m >> skip\n\n/--\n`by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and\n`h : \u00ac p` in the second branch. You can specify the name of the new hypothesis using the syntax\n`by_cases h : p`.\n-/\nmeta def by_cases : parse cases_arg_p \u2192 tactic unit\n| (n, q) := concat_tags $ do\n  p \u2190 tactic.to_expr_strict q,\n  tactic.by_cases p (n.get_or_else `h),\n  pos_g :: neg_g :: rest \u2190 get_goals,\n  return [(`pos, pos_g), (`neg, neg_g)]\n\n/--\nApply function extensionality and introduce new hypotheses.\nThe tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to\n```\n  |-  ((fun x, ...) = (fun x, ...))\n```\nThe variant `funext h\u2081 ... h\u2099` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.\n-/\nmeta def funext : parse ident_* \u2192 tactic unit\n| [] := tactic.funext >> skip\n| hs := funext_lst hs >> skip\n\n/--\nIf the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contradiction h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\nmeta def by_contradiction (n : parse ident?) : tactic unit :=\ntactic.by_contradiction (n.get_or_else `h) $> ()\n\n/--\nIf the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contra h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\nmeta def by_contra (n : parse ident?) : tactic unit :=\nby_contradiction n\n\n/--\nType check the given expression, and trace its type.\n-/\nmeta def type_check (p : parse texpr) : tactic unit :=\ndo e \u2190 to_expr p, tactic.type_check e, infer_type e >>= trace\n\n/--\nFail if there are unsolved goals.\n-/\nmeta def done : tactic unit :=\ntactic.done\n\nprivate meta def show_aux (p : pexpr) : list expr \u2192 list expr \u2192 tactic unit\n| []      r := fail \"show tactic failed\"\n| (g::gs) r := do\n  do {set_goals [g], g_ty \u2190 target, ty \u2190 i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty}\n  <|>\n  show_aux gs (g::r)\n\n/--\n`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.\n-/\nmeta def \u00abshow\u00bb (q : parse texpr) : tactic unit :=\ndo gs \u2190 get_goals,\n   show_aux q gs []\n\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a\u2081` ... `a\u2099`. The tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099` and tries to clear the previous one.\n-/\nmeta def specialize (p : parse texpr) : tactic unit :=\nfocus1 $\ndo e \u2190 i_to_expr p,\n   let h := expr.get_app_fn e,\n   if h.is_local_constant\n   then tactic.note h.local_pp_name none e >> try (tactic.clear h) >> rotate 1\n   else tactic.fail \"specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context\"\n\nmeta def congr := tactic.congr\n\nend interactive\nend tactic\n\nsection add_interactive\nopen tactic\n\n/- See add_interactive -/\nprivate meta def add_interactive_aux (new_namespace : name) : list name \u2192 command\n| []      := return ()\n| (n::ns) := do\n  env    \u2190 get_env,\n  d_name \u2190 resolve_constant n,\n  (declaration.defn _ ls ty val hints trusted) \u2190 env.get d_name,\n  (name.mk_string h _) \u2190 return d_name,\n  let new_name := new_namespace <.> h,\n  add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted),\n  do {\n    doc \u2190 doc_string d_name,\n    add_doc_string new_name doc\n  } <|> skip,\n  add_interactive_aux ns\n\n/--\nCopy a list of meta definitions in the current namespace to tactic.interactive.\n\nThis command is useful when we want to update tactic.interactive without closing the current namespace.\n-/\nmeta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command :=\nadd_interactive_aux p ns\n\nmeta def has_dup : tactic bool :=\ndo ctx \u2190 local_context,\n   let p : name_set \u00d7 bool :=\n       ctx.foldl (\u03bb \u27e8s, r\u27e9 h,\n          if r then (s, r)\n          else if s.contains h.local_pp_name then (s, tt)\n          else (s.insert h.local_pp_name, ff))\n        (mk_name_set, ff),\n   return p.2\n\n/--\nRenames hypotheses with the same name.\n-/\nmeta def dedup : tactic unit :=\nmwhen has_dup $ do\n  ctx \u2190 local_context,\n  n   \u2190 revert_lst ctx,\n  intron n\n\nend add_interactive\n\nnamespace tactic\n/- Helper tactic for `mk_inj_eq -/\nprotected meta def apply_inj_lemma : tactic unit :=\ndo h \u2190 intro `h,\n   some (lhs, rhs) \u2190 expr.is_eq <$> infer_type h,\n   (expr.const C _) \u2190 return lhs.get_app_fn,\n   -- We disable auto_param and opt_param support to address issue #1943\n   applyc (name.mk_string \"inj\" C) {auto_param := ff, opt_param := ff},\n   assumption\n\n/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.\n   These lemmas are automatically generated by the equation compiler.\n   Example:\n   ```\n   list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 \u2227 t1 = t2) :=\n   by mk_inj_eq\n   ```\n-/\nmeta def mk_inj_eq : tactic unit :=\n`[\n  intros,\n  /-\n     We use `_root_.*` in the following tactics because\n     names are resolved at tactic execution time in interactive mode.\n     See PR #1913\n\n     TODO(Leo): This is probably not the only instance of this problem.\n     `[ ... ] blocks are convenient to use because they allow us to use the interactive\n     mode to write non interactive tactics.\n     One potential fix for this issue is to resolve names in `[ ... ] at tactic\n     compilation time.\n     After this issue is fixed, we should remove the `_root_.*` workaround.\n  -/\n  apply _root_.propext,\n  apply _root_.iff.intro,\n  { tactic.apply_inj_lemma },\n  { intro _, try { cases_matching* _ \u2227 _ }, refl <|> { congr; { assumption <|> subst_vars } } }\n]\nend tactic\n\n/- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/\n\nuniverses u v\n\nlemma sum.inl.inj_eq {\u03b1 : Type u} (\u03b2 : Type v) (a\u2081 a\u2082 : \u03b1) : (@sum.inl \u03b1 \u03b2 a\u2081 = sum.inl a\u2082) = (a\u2081 = a\u2082) :=\nby tactic.mk_inj_eq\n\nlemma sum.inr.inj_eq (\u03b1 : Type u) {\u03b2 : Type v} (b\u2081 b\u2082 : \u03b2) : (@sum.inr \u03b1 \u03b2 b\u2081 = sum.inr b\u2082) = (b\u2081 = b\u2082) :=\nby tactic.mk_inj_eq\n\nlemma psum.inl.inj_eq {\u03b1 : Sort u} (\u03b2 : Sort v) (a\u2081 a\u2082 : \u03b1) : (@psum.inl \u03b1 \u03b2 a\u2081 = psum.inl a\u2082) = (a\u2081 = a\u2082) :=\nby tactic.mk_inj_eq\n\nlemma psum.inr.inj_eq (\u03b1 : Sort u) {\u03b2 : Sort v} (b\u2081 b\u2082 : \u03b2) : (@psum.inr \u03b1 \u03b2 b\u2081 = psum.inr b\u2082) = (b\u2081 = b\u2082) :=\nby tactic.mk_inj_eq\n\nlemma sigma.mk.inj_eq {\u03b1 : Type u} {\u03b2 : \u03b1 \u2192 Type v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) : (sigma.mk a\u2081 b\u2081 = sigma.mk a\u2082 b\u2082) = (a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082) :=\nby tactic.mk_inj_eq\n\nlemma psigma.mk.inj_eq {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) : (psigma.mk a\u2081 b\u2081 = psigma.mk a\u2082 b\u2082) = (a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082) :=\nby tactic.mk_inj_eq\n\nlemma subtype.mk.inj_eq {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} (a\u2081 : \u03b1) (h\u2081 : p a\u2081) (a\u2082 : \u03b1) (h\u2082 : p a\u2082) : (subtype.mk a\u2081 h\u2081 = subtype.mk a\u2082 h\u2082) = (a\u2081 = a\u2082) :=\nby tactic.mk_inj_eq\n\nlemma option.some.inj_eq {\u03b1 : Type u} (a\u2081 a\u2082 : \u03b1) : (some a\u2081 = some a\u2082) = (a\u2081 = a\u2082) :=\nby tactic.mk_inj_eq\n\nlemma list.cons.inj_eq {\u03b1 : Type u} (h\u2081 : \u03b1) (t\u2081 : list \u03b1) (h\u2082 : \u03b1) (t\u2082 : list \u03b1) : (list.cons h\u2081 t\u2081 = list.cons h\u2082 t\u2082) = (h\u2081 = h\u2082 \u2227 t\u2081 = t\u2082) :=\nby tactic.mk_inj_eq\n\nlemma nat.succ.inj_eq (n\u2081 n\u2082 : nat) : (nat.succ n\u2081 = nat.succ n\u2082) = (n\u2081 = n\u2082) :=\nby tactic.mk_inj_eq\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2227001285074597, "lm_q2_score": 0.039048289790720114, "lm_q1q2_score": 0.008696059154389896}}
{"text": "/-\nCopyright (c) 2020 Chris Hughes. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Chris Hughes\n-/\nimport tactic.core\n/-!\n## `protected` and `protect_proj` user attributes\n\n`protected` is an attribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj` attribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n# Examples\n\nIn this example all of `foo.bar`, `foo.baz` and `foo.qux` will be protected.\n```\n@[protect_proj] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n\nThe following code example define the structure `foo`, and the projections `foo.qux`\nwill be protected, but not `foo.baz` or `foo.bar`\n\n```\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\nnamespace tactic\n\n/--\nAttribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\nProtectedness is a built in parser feature that is independent of this attribute.\nA declaration may be protected even if it does not have the `@[protected]` attribute.\nThis provides a convenient way to protect many declarations at once.\n-/\n@[user_attribute] meta def protected_attr : user_attribute :=\n{ name := \"protected\",\n  descr := \"Attribute to protect a declaration\n    If a declaration `foo.bar` is marked protected, then it must be referred to\n    by its full name `foo.bar`, even when the `foo` namespace is open.\",\n  after_set := some (\u03bb n _ _, mk_protected n) }\n\nadd_tactic_doc\n{ name        := \"protected\",\n  category    := doc_category.attr,\n  decl_names  := [`tactic.protected_attr],\n  tags        := [\"parsing\", \"environment\"] }\n\n/-- Tactic that is executed when a structure is marked with the `protect_proj` attribute -/\nmeta def protect_proj_tac (n : name) (l : list name) : tactic unit :=\ndo env \u2190 get_env,\nmatch env.structure_fields_full n with\n| none := fail \"protect_proj failed: declaration is not a structure\"\n| some fields := fields.mmap' $ \u03bb field,\n    when (l.all $ \u03bb m, bnot $ m.is_suffix_of field) $ mk_protected field\nend\n\n/--\nAttribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected, meaning they must always be referred to by\ntheir full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n```lean\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\n@[user_attribute] meta def protect_proj_attr : user_attribute unit (list name) :=\n{ name := \"protect_proj\",\n  descr := \"Attribute to protect the projections of a structure.\n    If a structure `foo` is marked with the `protect_proj` user attribute, then\n    all of the projections become protected, meaning they must always be referred to by\n    their full name `foo.bar`, even when the `foo` namespace is open.\n\n    `protect_proj without bar baz` will protect all projections except for bar and baz\",\n  after_set := some (\u03bb n _ _, do l \u2190 protect_proj_attr.get_param n,\n    protect_proj_tac n l),\n  parser := interactive.types.without_ident_list }\n\nadd_tactic_doc\n{ name        := \"protect_proj\",\n  category    := doc_category.attr,\n  decl_names  := [`tactic.protect_proj_attr],\n  tags        := [\"parsing\", \"environment\", \"structures\"] }\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/protected.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033623510843832, "lm_q2_score": 0.061875985291156274, "lm_q1q2_score": 0.008683442819385979}}
{"text": "import Lean\n\nopen Lean Elab Command\n\n#eval do\n  let id := mkIdent `foo\n  elabCommand (\u2190 `(def $id := 10))\n\nexample : foo = 10 := rfl\n\n#eval do\n  let id := mkIdent `boo\n  elabCommand (\u2190 `(def $id := false))\n  return 5\n\nexample : boo = false := 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/evalCmd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.038466194222894164, "lm_q1q2_score": 0.00867091892545393}}
{"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 \u00d7 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 \u00d7 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 \u2264 o j l \u2194 i \u2264 j \u2227 k \u2264 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 \u2264 j . hom_tac) : i \u27f6 j := hom_of_le hij\n\nlemma hom_ext {i j : snake_diagram} (f g : i \u27f6 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 \u2192 fin 3 \u2192 C)\nparameters (f0 : F 0 0 \u27f6 F 0 1) (g0 : F 0 1 \u27f6 F 0 2)\nparameters (a0 : F 0 0 \u27f6 F 1 0) (b0 : F 0 1 \u27f6 F 1 1) (c0 : F 0 2 \u27f6 F 1 2)\nparameters (f1 : F 1 0 \u27f6 F 1 1) (g1 : F 1 1 \u27f6 F 1 2)\nparameters (a1 : F 1 0 \u27f6 F 2 0) (b1 : F 1 1 \u27f6 F 2 1) (c1 : F 1 2 \u27f6 F 2 2)\nparameters (f2 : F 2 0 \u27f6 F 2 1) (g2 : F 2 1 \u27f6 F 2 2)\nparameters (a2 : F 2 0 \u27f6 F 3 0) (b2 : F 2 1 \u27f6 F 3 1) (c2 : F 2 2 \u27f6 F 3 2)\nparameters (f3 : F 3 0 \u27f6 F 3 1) (g3 : F 3 1 \u27f6 F 3 2)\nparameters (sq00 : a0 \u226b f1 = f0 \u226b b0) (sq01 : b0 \u226b g1 = g0 \u226b c0)\nparameters (sq10 : a1 \u226b f2 = f1 \u226b b1) (sq11 : b1 \u226b g2 = g1 \u226b c1)\nparameters (sq20 : a2 \u226b f3 = f2 \u226b b2) (sq21 : b2 \u226b g3 = g2 \u226b c2)\n\nnamespace mk_functor\n\ndef col : \u03a0 (j : fin 3), fin 4 \u2964 C\n| \u27e80,h\u27e9 := fin4_functor_mk (flip F 0) a0 a1 a2\n| \u27e81,h\u27e9 := fin4_functor_mk (flip F 1) b0 b1 b2\n| \u27e82,h\u27e9 := fin4_functor_mk (flip F 2) c0 c1 c2\n| \u27e8j+3,h\u27e9 := by { exfalso, revert h, dec_trivial }\n\ndef row : \u03a0 (i : fin 4), fin 3 \u2964 C\n| \u27e80,h\u27e9 := fin3_functor_mk (F 0) f0 g0\n| \u27e81,h\u27e9 := fin3_functor_mk (F 1) f1 g1\n| \u27e82,h\u27e9 := fin3_functor_mk (F 2) f2 g2\n| \u27e83,h\u27e9 := fin3_functor_mk (F 3) f3 g3\n| \u27e8j+4,h\u27e9 := 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 \u2264 y) : F x.1 x.2 \u27f6 F y.1 y.2 :=\neq_to_hom (by rw [row_obj]) \u226b\n(row x.1).map h.2.hom \u226b eq_to_hom (by rw [row_obj, col_obj]) \u226b\n(col y.2).map h.1.hom \u226b eq_to_hom (by rw [col_obj])\n\nlemma map'_id (x : snake_diagram) : map' x x le_rfl = \ud835\udfd9 _ :=\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 \u2264 j) (hkl : k \u2264 l) : Prop :=\n(col k).map hij.hom \u226b eq_to_hom (by rw [row_obj, col_obj]) \u226b\n(row j).map hkl.hom =\neq_to_hom (by rw [col_obj]; refl) \u226b\nmap' (o i k) (o j l) \u27e8hij, hkl\u27e9 \u226b 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 \u2264 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 [\u2190 category.assoc, eq_comm],\n  convert category.comp_id _,\nend\n\nlemma square_commutes_col (i j : fin 4) (k : fin 3) (hij : i \u2264 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 \u2264 j) (hjk : j \u2264 k) (hlm : l \u2264 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 \u22a2,\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 \u22a2,\n  let \u03c6 : _ := _, let \u03c8 : _ := _,\n  calc _ = \u03c6 \u226b h2.lhs : _\n     ... = \u03c6 \u226b h2.rhs : by { congr' 1, }\n     ... = h1.lhs \u226b \u03c8 : _\n     ... = h1.rhs \u226b \u03c8 : by { congr' 1, }\n     ... = _ : _,\n  swap 5, { exact functor.map _ hij.hom },\n  swap 4, { refine (eq_to_hom _ \u226b _ \u226b 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 [\u03c6, \u03c8, eq.lhs_def, eq.rhs_def] },\n  { simp only [\u2190 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, \u2190 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 \u2264 j) (hlm : l \u2264 m) (hmn : m \u2264 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 \u22a2,\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 \u22a2,\n  let \u03c6 : _ := _, let \u03c8 : _ := _,\n  calc _ = h1.lhs \u226b \u03c6 : _\n     ... = h1.rhs \u226b \u03c6 : by { congr' 1, }\n     ... = \u03c8 \u226b h2.lhs : _\n     ... = \u03c8 \u226b h2.rhs : by { congr' 1, }\n     ... = _ : _,\n  swap 5, { exact functor.map _ hmn.hom },\n  swap 4, { refine (eq_to_hom _ \u226b _ \u226b 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 [\u03c6, \u03c8, eq.lhs_def, eq.rhs_def] },\n  { simp only [category.assoc, \u2190 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, \u2190 functor.map_comp_assoc],\n    refl, },\nend\n\nlemma col_comp_row (i j : fin 4) (k l : fin 3) (hij : i \u2264 j) (hkl : k \u2264 l) :\n  (col k).map hij.hom \u226b eq_to_hom (by rw [row_obj, col_obj]) \u226b\n  (row j).map hkl.hom =\n  eq_to_hom (by rw [col_obj]; refl) \u226b\n  map' (o i k) (o j l) \u27e8hij, hkl\u27e9 \u226b 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 [\u2190 fin.coe_fin_le, fin.coe_mk, fin.coe_mk] at hij hkl,\n  obtain \u27e8j, rfl\u27e9 := nat.exists_eq_add_of_le hij,\n  obtain \u27e8l, rfl\u27e9 := 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 \u27e8i, hi\u27e9 \u27e8i+j, _\u27e9 _ _ _ _ _ hkl' _ _,\n  { refine lt_trans _ hj, exact lt_add_one (i+j) },\n  { simp only [\u2190 fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n  { simp only [\u2190 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 _ _ \u27e8k, hk\u27e9 \u27e8k+l, _\u27e9 _ _ _ _ _ _,\n  { refine lt_trans _ hl, exact lt_add_one (k+l) },\n  { simp only [\u2190 fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n  { simp only [\u2190 fin.coe_fin_le, fin.coe_mk], exact (lt_add_one (k+l)).le },\n  { refine IHl _ _ _, simp only [\u2190 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 [\u2190 fin.coe_fin_lt, fin.coe_mk], refine nat.lt_of_succ_lt_succ hj, },\n  { rw [\u2190 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 \u2264 y) (hyz : y \u2264 z) :\n  map' x y hxy \u226b 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, \u2190 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 \u2964 C :=\n{ obj := function.uncurry F,\n  map := \u03bb 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' := \u03bb 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' := \u03bb 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 {\ud835\udc9c \u212c : Type*} [category \ud835\udc9c] [category \u212c]\nvariables (A : fin 3 \u2192 \ud835\udc9c) (F : fin 4 \u2192 \ud835\udc9c \u2964 \u212c)\nvariables (f : A 0 \u27f6 A 1) (g : A 1 \u27f6 A 2) (\u03b1 : F 0 \u27f6 F 1) (\u03b2 : F 1 \u27f6 F 2) (\u03b3 : F 2 \u27f6 F 3)\n\ndef mk_functor' : snake_diagram \u2964 \u212c :=\nmk_functor (\u03bb i, (F i).obj \u2218 A)\n  /- FA\u2080\u2080 -/  ((F 0).map f)  /- FA\u2080\u2081 -/  ((F 0).map g)  /- FA\u2080\u2082 -/\n  (\u03b1.app _)                  (\u03b1.app _)                  (\u03b1.app _)\n  /- FA\u2081\u2080 -/  ((F 1).map f)  /- FA\u2081\u2081 -/  ((F 1).map g)  /- FA\u2081\u2082 -/\n  (\u03b2.app _)                  (\u03b2.app _)                  (\u03b2.app _)\n  /- FA\u2082\u2080 -/  ((F 2).map f)  /- FA\u2082\u2081 -/  ((F 2).map g)  /- FA\u2082\u2082 -/\n  (\u03b3.app _)                  (\u03b3.app _)                  (\u03b3.app _)\n  /- FA\u2083\u2080 -/  ((F 3).map f)  /- FA\u2083\u2081 -/  ((F 3).map g)  /- FA\u2083\u2082 -/\n(\u03b1.naturality _).symm (\u03b1.naturality _).symm\n(\u03b2.naturality _).symm (\u03b2.naturality _).symm\n(\u03b3.naturality _).symm (\u03b3.naturality _).symm\n\nend\n\nsection\n\nvariables {\ud835\udc9c \u212c \ud835\udc9e : Type*} [category \ud835\udc9c] [category \u212c] [category \ud835\udc9e]\nvariables (A : fin 3 \u2192 \ud835\udc9c \u2964 \u212c) (F : fin 4 \u2192 \u212c \u2964 \ud835\udc9e)\nvariables (f : A 0 \u27f6 A 1) (g : A 1 \u27f6 A 2) (\u03b1 : F 0 \u27f6 F 1) (\u03b2 : F 1 \u27f6 F 2) (\u03b3 : F 2 \u27f6 F 3)\n\ndef mk_functor'' : \ud835\udc9c \u2192 snake_diagram \u2964 \ud835\udc9e :=\n\u03bb x, mk_functor' ![(A 0).obj x, (A 1).obj x, (A 2).obj x] F (f.app x) (g.app x) \u03b1 \u03b2 \u03b3\n\nend\n\nsection\n\nvariables {\ud835\udc9c : Type*} [category \ud835\udc9c] [abelian \ud835\udc9c]\n\n-- move (ang generalize) this\nlemma exact_kernel_\u03b9_self {A B : \ud835\udc9c} (f : A \u27f6 B) : exact (kernel.\u03b9 f) f :=\nby { rw abelian.exact_iff, tidy } -- why do we not have abelian.exact_kernel?\n\n-- move this\nlemma exact_self_cokernel_\u03c0 {A B : \ud835\udc9c} (f : A \u27f6 B) : exact f (cokernel.\u03c0 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 \ud835\udc9c) (f : A \u27f6 B) :\n  snake_diagram \u2964 \ud835\udc9c :=\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.\u03b9 _)                         (kernel.\u03b9 _)                         (kernel.\u03b9 _)\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.\u03c0 _)                       (cokernel.\u03c0 _)                       (cokernel.\u03c0 _)\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_\u03b9] }) (by { delta kernel.map, rw [kernel.lift_\u03b9] })\nf.sq1 f.sq2\n(by { delta cokernel.map, rw [cokernel.\u03c0_desc] }) (by { delta cokernel.map, rw [cokernel.\u03c0_desc] })\n.\n\nend\n\nend snake_diagram\n\nopen snake_diagram (o hom)\n\nexample (i : fin 4) : o i 0 \u27f6 o i 1 := hom (i,0) (i,1)\n\nlocal notation x `\u27f6[`D`]` y := D.map (hom x y)\n\nsection definitions\n\nvariables (\ud835\udc9c : Type u) [category.{v} \ud835\udc9c] [has_images \ud835\udc9c] [has_zero_morphisms \ud835\udc9c] [has_kernels \ud835\udc9c]\n\nvariables {\ud835\udc9c}\n\nstructure is_snake_input (D : snake_diagram \u2964 \ud835\udc9c) : Prop :=\n(row_exact\u2081 : exact ((1,0) \u27f6[D] (1,1)) ((1,1) \u27f6[D] (1,2)))\n(row_exact\u2082 : exact ((2,0) \u27f6[D] (2,1)) ((2,1) \u27f6[D] (2,2)))\n(col_exact\u2081 : \u2200 j, exact ((0,j) \u27f6[D] (1,j)) ((1,j) \u27f6[D] (2,j)))\n(col_exact\u2082 : \u2200 j, exact ((1,j) \u27f6[D] (2,j)) ((2,j) \u27f6[D] (3,j)))\n(col_mono : \u2200 j, mono ((0,j) \u27f6[D] (1,j)))\n(col_epi  : \u2200 j, epi ((2,j) \u27f6[D] (3,j)))\n(row_mono : mono ((2,0) \u27f6[D] (2,1)))\n(row_epi  : epi ((1,1) \u27f6[D] (1,2)))\n\nnamespace is_snake_input\n\nvariables {D : snake_diagram \u2964 \ud835\udc9c}\n\n@[nolint unused_arguments]\nlemma map_eq (hD : is_snake_input D) {x y : snake_diagram} (f g : x \u27f6 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 \u27f6 x) : D.map f = \ud835\udfd9 _ :=\nby rw [snake_diagram.hom_ext f (\ud835\udfd9 x), D.map_id]\n\nlemma hom_eq_zero\u2081 (hD : is_snake_input D) {x y : snake_diagram} (f : x \u27f6 y)\n  (h : x.1 < 2 \u2227 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\u2080 h\u2081, rcases f with \u27e8\u27e8\u27e8hik, hjl\u27e9\u27e9\u27e9,\n  dsimp at h\u2080 h\u2081 hik hjl,\n  let f\u2081 := hom (i,j) (i+1,j),\n  let f\u2082 := hom (i+1,j) (i+2,j),\n  let f\u2083 := hom (i+2,j) (k,l),\n  calc D.map _\n      = D.map ((f\u2081 \u226b f\u2082) \u226b f\u2083)             : hD.map_eq _ _\n  ... = ((D.map f\u2081) \u226b D.map f\u2082) \u226b D.map f\u2083 : by simp only [D.map_comp]\n  ... = 0 \u226b D.map f\u2083                        : _\n  ... = 0                                   : zero_comp,\n  congr' 1,\n  obtain (rfl|rfl) : i = 0 \u2228 i = 1, { dec_trivial! },\n  { exact (hD.col_exact\u2081 j).w },\n  { exact (hD.col_exact\u2082 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 {\ud835\udc9c : Type*} [category \ud835\udc9c] [abelian \ud835\udc9c]\n  (A B : short_exact_sequence \ud835\udc9c) (f : A \u27f6 B) :\n  is_snake_input (snake_diagram.mk_of_short_exact_sequence_hom A B f) :=\n{ row_exact\u2081 := by { aux_simp, exact A.exact' },\n  row_exact\u2082 := by { aux_simp, exact B.exact' },\n  col_exact\u2081 := \u03bb j, by { fin_cases j; aux_simp, all_goals { apply exact_kernel_\u03b9_self, } },\n  col_exact\u2082 := \u03bb j, by { fin_cases j; aux_simp, all_goals { apply exact_self_cokernel_\u03c0 } },\n  col_mono := \u03bb j, by { fin_cases j; aux_simp, all_goals { apply_instance } },\n  col_epi := \u03bb 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 {\ud835\udc9c : Type u} [category.{v} \ud835\udc9c] [abelian \ud835\udc9c]\nvariables {D : snake_diagram \u2964 \ud835\udc9c}\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 : \ud835\udc9c} (f : P \u27f6 Q) : function.injective f \u2194 mono f :=\n\u27e8\u03bb h, mono_of_zero_of_map_zero _ (zero_of_map_zero _ h),\n  by introsI h; apply pseudo_injective_of_mono\u27e9\n\nlemma surjective_iff_epi {P Q : \ud835\udc9c} (f : P \u27f6 Q) : function.surjective f \u2194 epi f :=\n\u27e8epi_of_pseudo_surjective _, by introI h; apply pseudo_surjective_of_epi\u27e9\n\nlemma exists_of_exact {P Q R : \ud835\udc9c} {f : P \u27f6 Q} {g : Q \u27f6 R} (e : exact f g) (q) (hq : g q = 0) :\n  \u2203 p, f p = q :=\n(pseudo_exact_of_exact e).2 _ hq\n\nlemma eq_zero_of_exact {P Q R : \ud835\udc9c} {f : P \u27f6 Q} {g : Q \u27f6 R} (e : exact f g) (p) : g (f p) = 0 :=\n(pseudo_exact_of_exact e).1 _\n\n@[simp]\nlemma kernel_\u03b9_apply {P Q : \ud835\udc9c} (f : P \u27f6 Q) (a) : f (kernel.\u03b9 f a) = 0 :=\nbegin\n  rw \u2190 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_\u03b9_eq_zero {P Q : \ud835\udc9c} (f : P \u27f6 Q) (q) : kernel.\u03b9 f q = 0 \u2194 q = 0 :=\nbegin\n  split,\n  { intro h,\n    apply_fun kernel.\u03b9 f,\n    simp [h],\n    rw injective_iff_mono,\n    apply_instance },\n  { intro h,\n    simp [h] },\nend\n\n@[simp]\nlemma cokernel_\u03c0_apply {P Q : \ud835\udc9c} (f : P \u27f6 Q) (a) : cokernel.\u03c0 f (f a) = 0 :=\nbegin\n  rw \u2190 abelian.pseudoelement.comp_apply,\n  simp,\nend\n\nlemma exists_of_cokernel_\u03c0_eq_zero {P Q : \ud835\udc9c} (f : P \u27f6 Q) (a) :\n  cokernel.\u03c0 f a = 0 \u2192 \u2203 b, f b = a :=\nbegin\n  intro h,\n  apply exists_of_exact _ _ h,\n  apply snake_diagram.exact_self_cokernel_\u03c0,\nend\n\nlemma cokernel_\u03c0_surjective {P Q : \ud835\udc9c} (f : P \u27f6 Q) : function.surjective (cokernel.\u03c0 f) :=\nbegin\n  rw surjective_iff_epi,\n  apply_instance,\nend\n\n--move\nlemma exact_is_iso_iff {P Q Q' R : \ud835\udc9c} (f : P \u27f6 Q) (g : Q' \u27f6 R) (e : Q \u27f6 Q') [is_iso e] :\n  exact f (e \u226b g) \u2194 exact (f \u226b e) g :=\nbegin\n  let E := as_iso e,\n  change exact f (E.hom \u226b g) \u2194 exact (f \u226b E.hom) g,\n  conv_rhs { rw (show g = E.inv \u226b E.hom \u226b g, by simp) },\n  rw exact_comp_hom_inv_comp_iff\nend\n\n--lemma exact_comp_is_iso {P Q R R' : \ud835\udc9c} (f : P \u27f6 Q) (g : Q \u27f6 R) (e : R \u27f6 R') [is_iso e] :\n--  exact f (g \u226b e) \u2194 exact f g := exact_comp_iso\n\nend move_me\n\nlemma row_exact\u2080 (hD : is_snake_input D) : exact ((0,0) \u27f6[D] (0,1)) ((0,1) \u27f6[D] (0,2)) :=\nbegin\n  refine exact_of_pseudo_exact _ _ \u27e8\u03bb a, _, _\u27e9,\n  { apply_fun ((0,2) \u27f6[D] (1,2)),\n    swap, { rw injective_iff_mono, exact hD.col_mono _ },\n    simp_rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, abelian.pseudoelement.apply_zero],\n    change D.map (hom (0,0) (1,0) \u226b hom (1,0) (1,1) \u226b hom (1,1) (1,2)) a = 0,\n    simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact hD.row_exact\u2081] },\n  { intros b hb,\n    apply_fun ((0,2) \u27f6[D] (1,2)) at hb,\n    simp_rw [\u2190 abelian.pseudoelement.comp_apply,\n      \u2190 D.map_comp, abelian.pseudoelement.apply_zero] at hb,\n    change D.map (hom (0,1) (1,1) \u226b 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) \u27f6[D] (1,1)) b,\n    change ((1,1) \u27f6[D] (1,2)) b' = 0 at hb,\n    obtain \u27e8c,hc\u27e9 := exists_of_exact hD.row_exact\u2081 b' hb,\n    have hcz : ((1,0) \u27f6[D] (2,0)) c = 0,\n    { apply_fun ((2,0) \u27f6[D] (2,1)),\n      swap, { rw injective_iff_mono, apply hD.row_mono },\n      simp_rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, abelian.pseudoelement.apply_zero],\n      change D.map (hom (1,0) (1,1) \u226b 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\u2081 },\n    obtain \u27e8d,hd\u27e9 := exists_of_exact (hD.col_exact\u2081 _) c hcz,\n    use d,\n    apply_fun ((0,1) \u27f6[D] (1,1)),\n    swap, { rw injective_iff_mono, exact hD.col_mono _ },\n    dsimp only [b'] at hc,\n    rw [\u2190 hc, \u2190 hd],\n    simp_rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp],\n    refl }\nend\n\nlemma row_exact\u2083 (hD : is_snake_input D) : exact ((3,0) \u27f6[D] (3,1)) ((3,1) \u27f6[D] (3,2)) :=\nbegin\n  refine exact_of_pseudo_exact _ _ \u27e8\u03bb a, _,\u03bb b hb, _\u27e9,\n  { obtain \u27e8b, hb\u27e9 := (surjective_iff_epi ((2,0) \u27f6[D] (3,0))).2 (hD.col_epi 0) a,\n    rw [\u2190 hb, \u2190 abelian.pseudoelement.comp_apply, \u2190 abelian.pseudoelement.comp_apply,\n      \u2190 D.map_comp, \u2190 D.map_comp, map_eq hD ((hom (2, 0) (3, 0)) \u226b (hom _ (3, 1)) \u226b\n      (hom _ (3, 2))) ((hom (2, 0) (2, 1)) \u226b (hom _ (2, 2)) \u226b (hom _ _)), \u2190 category.assoc,\n      D.map_comp _ (hom (2, 2) (3, 2)), D.map_comp, hD.row_exact\u2082.w, zero_comp, zero_apply] },\n  { set f\u2081 := hom (2, 1) (2, 2),\n    set f\u2082 := hom (2, 2) (3, 2),\n    set f\u2083 := hom (1, 1) (2, 1),\n    set f\u2084 := hom (2, 0) (3, 0),\n    set f\u2085 := hom (3, 0) (3, 1),\n    obtain \u27e8c, hc\u27e9 := (surjective_iff_epi ((2,1) \u27f6[D] (3,1))).2 (hD.col_epi 1) b,\n    let d := D.map f\u2081 c,\n    have hd : D.map f\u2082 d = 0,\n    { rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD ((hom (2, 1) (2, 2)) \u226b\n      (hom _ (3, 2))) ((hom (2, 1) (3, 1)) \u226b (hom _ (3, 2))), D.map_comp,\n      abelian.pseudoelement.comp_apply, hc, hb] },\n    obtain \u27e8e, he\u27e9 := exists_of_exact (hD.col_exact\u2082 2) d hd,\n    obtain \u27e8f, hf\u27e9 := (surjective_iff_epi ((1,1) \u27f6[D] (1,2))).2 hD.row_epi e,\n    have hfzero : ((2,1) \u27f6[D] (3,1)) ((D.map f\u2083) f) = 0,\n    { rw [\u2190 abelian.pseudoelement.comp_apply, (hD.col_exact\u2082 1).w, zero_apply] },\n    have hdiff : D.map f\u2081 c = D.map f\u2081 (D.map f\u2083 f),\n    { rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD ((hom (1, 1) (2, 1)) \u226b\n      (hom _ (2, 2))) ((hom (1, 1) (1, 2)) \u226b (hom _ (2, 2))), D.map_comp,\n      abelian.pseudoelement.comp_apply, hf, he] },\n    obtain \u27e8g, \u27e8hg\u2081, hg\u2082\u27e9\u27e9 := sub_of_eq_image _ _ _ hdiff,\n    obtain \u27e8h, hh\u27e9 := exists_of_exact hD.row_exact\u2082 g hg\u2081,\n    use D.map f\u2084 h,\n    rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n      ((hom (2, 0) (3, 0)) \u226b (hom _ (3, 1))) ((hom _ (2, 1)) \u226b (hom _ _)), D.map_comp,\n      abelian.pseudoelement.comp_apply, hh, hg\u2082 _ ((2,1) \u27f6[D] (3,1)) hfzero, hc] }\nend\n\nlemma row_exact (hD : is_snake_input D) (i : fin 4) :\n  exact ((i,0) \u27f6[D] (i,1)) ((i,1) \u27f6[D] (i,2)) :=\nby { fin_cases i, exacts [hD.row_exact\u2080, hD.row_exact\u2081, hD.row_exact\u2082, hD.row_exact\u2083] }\n\nlemma hom_eq_zero\u2082 (hD : is_snake_input D) {x y : snake_diagram} (f : x \u27f6 y)\n  (h : x.2 = 0 \u2227 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 \u27e8\u27e8\u27e8hik, hjl\u27e9\u27e9\u27e9,\n  dsimp at h hik hjl, rcases h with \u27e8rfl, rfl\u27e9,\n  let f\u2081 := hom (i,0) (i,1),\n  let f\u2082 := hom (i,1) (i,2),\n  let f\u2083 := hom (i,2) (k,2),\n  calc D.map _\n      = D.map ((f\u2081 \u226b f\u2082) \u226b f\u2083)             : hD.map_eq _ _\n  ... = ((D.map f\u2081) \u226b D.map f\u2082) \u226b D.map f\u2083 : 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\u2081_to_row\u2082 (hD : is_snake_input D) :\n  (kernel.\u03b9 ((1,0) \u27f6[D] (1,1))) \u226b ((1,0) \u27f6[D] (2,0)) = 0 :=\nbegin\n  refine zero_morphism_ext _ (\u03bb a, (injective_iff_mono ((2,0) \u27f6[D] (2,1))).2 hD.row_mono _),\n  rw [apply_zero, \u2190 abelian.pseudoelement.comp_apply, category.assoc,\n    abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n    ((hom (1, 0) (2, 0)) \u226b (hom _ (2, 1))) ((hom _ (1, 1)) \u226b (hom _ _)), D.map_comp,\n    abelian.pseudoelement.comp_apply, kernel_\u03b9_apply, apply_zero]\nend\n\ndef ker_row\u2081_to_top_left (hD : is_snake_input D) : kernel ((1,0) \u27f6[D] (1,1)) \u27f6 D.obj (0, 0) :=\nby { letI := hD.col_mono 0, exact (limits.kernel.lift _ _ (ker_row\u2081_to_row\u2082 hD)) \u226b\n    (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact\u2081 0)).2)) \u226b\n    inv (abelian.factor_thru_image ((0,0) \u27f6[D] (1,0))) }\n\nlemma ker_row\u2081_to_top_left_mono (hD : is_snake_input D) : mono (ker_row\u2081_to_top_left hD) :=\nbegin\n  suffices : mono ((limits.kernel.lift _ _ (ker_row\u2081_to_row\u2082 hD)) \u226b\n    (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact\u2081 0)).2))),\n  { letI := this, exact mono_comp _ _, },\n  exact mono_comp _ _\nend\n\nlemma ker_row\u2081_to_top_left_comp_eq_\u03b9 (hD : is_snake_input D) : ker_row\u2081_to_top_left hD \u226b\n  ((0,0) \u27f6[D] (1,0)) = kernel.\u03b9 ((1,0) \u27f6[D] (1,1)) :=\nbegin\n  letI := hD.col_mono 0,\n  have : inv (abelian.factor_thru_image ((0,0) \u27f6[D] (1,0))) \u226b ((0,0) \u27f6[D] (1,0)) =\n    category_theory.abelian.image.\u03b9 _ := by simp,\n  rw [ker_row\u2081_to_top_left, category.assoc, category.assoc, this],\n  simp\nend\n\nlemma long_row\u2080_exact (hD : is_snake_input D) :\n  exact (ker_row\u2081_to_top_left hD) ((0,0) \u27f6[D] (0,1)) :=\nbegin\n  refine abelian.pseudoelement.exact_of_pseudo_exact _ _ \u27e8\u03bb a, _, \u03bb a ha, _\u27e9,\n  { refine (injective_iff_mono _).2 (hD.col_mono _) _,\n    rw [apply_zero, \u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n      ((hom (0, 0) (0, 1)) \u226b (hom _ (1, 1))) ((hom _ (1, 0)) \u226b (hom _ _)), D.map_comp,\n      \u2190 abelian.pseudoelement.comp_apply, \u2190 category.assoc, ker_row\u2081_to_top_left_comp_eq_\u03b9 hD,\n      abelian.pseudoelement.comp_apply, kernel_\u03b9_apply] },\n  { let b := ((0,0) \u27f6[D] (1,0)) a,\n    have hb : ((1,0) \u27f6[D] (1,1)) b = 0,\n    { rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n        ((hom (0, 0) (1, 0)) \u226b (hom _ (1, 1))) ((hom _ (0, 1)) \u226b (hom _ _)), D.map_comp,\n        abelian.pseudoelement.comp_apply, ha, apply_zero] },\n    obtain \u27e8c, hc\u27e9 := exists_of_exact category_theory.exact_kernel_\u03b9 _ hb,\n    refine \u27e8c, (injective_iff_mono _).2 (hD.col_mono _) _\u27e9,\n    rw [\u2190 abelian.pseudoelement.comp_apply, ker_row\u2081_to_top_left_comp_eq_\u03b9 hD, hc] }\nend\n\nlemma row\u2081_middle_to_coker_row\u2082_eq_zero (hD : is_snake_input D) :\n   ((1,1) \u27f6[D] (1,2)) \u226b ((1,2) \u27f6[D] (2,2)) \u226b (limits.cokernel.\u03c0 ((2,1) \u27f6[D] (2,2))) = 0 :=\nbegin\n  refine zero_morphism_ext _ (\u03bb a, _),\n  rw [\u2190 category.assoc, abelian.pseudoelement.comp_apply, \u2190 D.map_comp, map_eq hD\n    ((hom (1, 1) (1, 2)) \u226b (hom _ (2, 2))) ((hom _ (2, 1)) \u226b (hom _ _)), D.map_comp,\n    \u2190 abelian.pseudoelement.comp_apply],\n  simp,\nend\n\nlemma row\u2081_to_coker_row\u2082_eq_zero (hD : is_snake_input D) :\n  ((1,2) \u27f6[D] (2,2)) \u226b (limits.cokernel.\u03c0 ((2,1) \u27f6[D] (2,2))) = 0 :=\nbegin\n  letI := hD.row_epi,\n  have := row\u2081_middle_to_coker_row\u2082_eq_zero hD,\n  rw [\u2190 limits.comp_zero] at this,\n  exact (cancel_epi _).1 this\nend\n\nlemma ker_col\u2082_to_coker_row\u2082_eq_zero (hD : is_snake_input D) :\n  kernel.\u03b9 ((2,2) \u27f6[D] (3,2)) \u226b (limits.cokernel.\u03c0 ((1,2) \u27f6[D] (2,2))) = 0 :=\nbegin\n  refine zero_morphism_ext _ (\u03bb a, _),\n  obtain \u27e8c, hc\u27e9 := exists_of_exact (hD.col_exact\u2082 2) (kernel.\u03b9 (_ \u27f6[D] _) a) (kernel_\u03b9_apply _ _),\n  rw [abelian.pseudoelement.comp_apply, \u2190 hc, cokernel_\u03c0_apply]\nend\n\ndef bottom_right_to_coker_row\u2082 (hD : is_snake_input D) :\n  D.obj (3, 2) \u27f6 cokernel ((2,1) \u27f6[D] (2,2)) :=\nby { letI := hD.col_epi 2, exact\n  (inv (abelian.factor_thru_coimage ((2,2) \u27f6[D] (3,2)))) \u226b\n  (limits.cokernel.desc _ _ (ker_col\u2082_to_coker_row\u2082_eq_zero hD)) \u226b\n  (limits.cokernel.desc _ _ (row\u2081_to_coker_row\u2082_eq_zero hD)) }\n\nlemma bottom_right_to_coker_row\u2082_epi (hD : is_snake_input D) : epi (bottom_right_to_coker_row\u2082 hD) :=\nbegin\n  suffices : epi ((limits.cokernel.desc _ _ (ker_col\u2082_to_coker_row\u2082_eq_zero hD)) \u226b\n    (limits.cokernel.desc _ _ (row\u2081_to_coker_row\u2082_eq_zero hD))),\n  { letI := this, exact epi_comp _ _ },\n  exact epi_comp _ _,\nend\n\nlemma bottom_right_to_coker_row\u2082_comp_eq_\u03c0 (hD : is_snake_input D) : ((2,2) \u27f6[D] (3,2))  \u226b\n  bottom_right_to_coker_row\u2082 hD = cokernel.\u03c0 ((2,1) \u27f6[D] (2,2)) :=\nbegin\n  letI := hD.col_epi 2,\n  have : ((2,2) \u27f6[D] (3,2)) \u226b inv (abelian.factor_thru_coimage ((2,2) \u27f6[D] (3,2))) =\n    category_theory.abelian.coimage.\u03c0 _ := by simp,\n  rw [bottom_right_to_coker_row\u2082, \u2190 category.assoc, \u2190 category.assoc, this],\n  simp\nend\n\nlemma long_row\u2083_exact (hD : is_snake_input D) :\n  exact ((3,1) \u27f6[D] (3,2)) (bottom_right_to_coker_row\u2082 hD) :=\nbegin\n  refine abelian.pseudoelement.exact_of_pseudo_exact _ _ \u27e8\u03bb a, _, \u03bb a ha, _\u27e9,\n  { letI := hD.col_epi 1,\n    obtain \u27e8b, hb\u27e9 := abelian.pseudoelement.pseudo_surjective_of_epi ((2,1) \u27f6[D] (3,1)) a,\n    rw [\u2190 hb, \u2190 abelian.pseudoelement.comp_apply, \u2190 abelian.pseudoelement.comp_apply,\n      \u2190 category.assoc, \u2190 D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) \u226b (hom _ (3, 2)))\n      ((hom _ (2, 2)) \u226b (hom _ _)), D.map_comp, category.assoc,\n      bottom_right_to_coker_row\u2082_comp_eq_\u03c0 hD, (snake_diagram.exact_self_cokernel_\u03c0 _).w,\n      zero_apply], },\n  { letI := hD.col_epi 2,\n    obtain \u27e8b, hb\u27e9 := abelian.pseudoelement.pseudo_surjective_of_epi ((2,2) \u27f6[D] (3,2)) a,\n    rw [\u2190 hb, \u2190 abelian.pseudoelement.comp_apply, bottom_right_to_coker_row\u2082_comp_eq_\u03c0 hD] at ha,\n    obtain \u27e8c, hc\u27e9 := exists_of_exact (abelian.exact_cokernel _) _ ha,\n    refine \u27e8((2,1) \u27f6[D] (3,1)) c, _\u27e9,\n    rw [\u2190 hb, \u2190 hc, \u2190 abelian.pseudoelement.comp_apply, \u2190 abelian.pseudoelement.comp_apply,\n      \u2190 D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) \u226b (hom _ (3, 2))) ((hom _ (2, 2)) \u226b (hom _ _)),\n      D.map_comp] }\nend\n\nend long_snake\n\nexample (hD : is_snake_input D) (f : (o 1 0) \u27f6 (o 2 2)) : D.map f = 0 := hD.hom_eq_zero\u2082 f\n\nsection delta\n\nvariable (hD : is_snake_input D)\ninclude hD\n\ndef to_top_right_kernel : D.obj (1,0) \u27f6 kernel ((1,1) \u27f6[D] (2,2)) :=\nkernel.lift _ (_ \u27f6[D] _)\nbegin\n  rw \u2190 D.map_comp,\n  change D.map (hom (1,0) (2,0) \u226b hom (2,0) (2,1) \u226b hom (2,1) (2,2)) = 0,\n  simp [hD.row_exact\u2082.1],\nend\n\ndef cokernel_to_top_right_kernel_to_right_kernel :\n  cokernel hD.to_top_right_kernel \u27f6 kernel ((1,2) \u27f6[D] (2,2)) :=\ncokernel.desc _ (kernel.lift _ (kernel.\u03b9 _ \u226b (_ \u27f6[D] _)) begin\n  rw [category.assoc, \u2190 D.map_comp],\n  have : hom (1,1) (1,2) \u226b 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.\u03b9 (D.map (hom (1, 2) (2, 2))),\n  swap, { rw injective_iff_mono, apply_instance },\n  simp [\u2190 abelian.pseudoelement.comp_apply, hD.row_exact\u2081.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 \u27e8b,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n  rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero at h,\n  simp [\u2190 abelian.pseudoelement.comp_apply, cokernel_to_top_right_kernel_to_right_kernel] at h,\n  simp [ abelian.pseudoelement.comp_apply] at h,\n  have : \u2203 c, ((1,0) \u27f6[D] (1,1)) c = kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) b,\n  { apply exists_of_exact _ _ h,\n    exact hD.row_exact\u2081 },\n  obtain \u27e8c,hc\u27e9 := this,\n  let f : cokernel hD.to_top_right_kernel \u27f6 cokernel ((1,0) \u27f6[D] (1,1)) :=\n    cokernel.desc _ _ _,\n  swap, { refine kernel.\u03b9 _ \u226b cokernel.\u03c0 _ },\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 \u27e8a,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n    simp [\u2190 abelian.pseudoelement.comp_apply] at ha,\n    simp [abelian.pseudoelement.comp_apply] at ha,\n    have : \u2203 c, ((1,0) \u27f6[D] (1,1)) c = kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) a,\n    { apply exists_of_exact _ _ ha,\n      apply snake_diagram.exact_self_cokernel_\u03c0, },\n    obtain \u27e8c,hc\u27e9 := this,\n    have : hD.to_top_right_kernel c = a,\n    { apply_fun kernel.\u03b9 ((1,1) \u27f6[D] (2,2)),\n      swap, { rw injective_iff_mono, apply_instance },\n      dsimp [to_top_right_kernel],\n      simp [\u2190 abelian.pseudoelement.comp_apply],\n      erw kernel.lift_\u03b9,\n      exact hc },\n    simp [\u2190 this] },\n  dsimp only [f],\n  simp [\u2190 abelian.pseudoelement.comp_apply, to_top_right_kernel],\n  simp [abelian.pseudoelement.comp_apply, \u2190 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.\u03b9 ((1,2) \u27f6[D] (2,2)) a,\n  obtain \u27e8b,hb\u27e9 : \u2203 b, ((1,1) \u27f6[D] (1,2)) b = a',\n  { suffices : function.surjective ((1,1) \u27f6[D] (1,2)), by apply this,\n    rw surjective_iff_epi,\n    apply hD.row_epi },\n  obtain \u27e8c,hc\u27e9 : \u2203 c, kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) c = b,\n  { have : exact (kernel.\u03b9 ((1,1) \u27f6[D] (2,2))) ((1,1) \u27f6[D] (2,2)) := exact_kernel_\u03b9,\n    apply exists_of_exact this,\n    rw [(show hom (1,1) (2,2) = hom (1,1) (1,2) \u226b 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.\u03c0 hD.to_top_right_kernel c,\n  apply_fun kernel.\u03b9 ((1,2) \u27f6[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 [\u2190 abelian.pseudoelement.comp_apply],\n  change _ = a',\n  rw \u2190 hb,\n  simp [\u2190 hb, abelian.pseudoelement.comp_apply, \u2190 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) \u27f6[D] (2,1)) \u27f6 D.obj (2,2) :=\ncokernel.desc _ (_ \u27f6[D] _)\nbegin\n  rw \u2190 D.map_comp,\n  change D.map (hom (1,0) (2,0) \u226b hom (2,0) (2,1) \u226b hom (2,1) (2,2)) = 0,\n  simp_rw D.map_comp,\n  simp [hD.row_exact\u2082.1],\nend\n\ndef left_cokernel_to_kernel_bottom_left_cokernel_to :\n  cokernel ((1,0) \u27f6[D] (2,0)) \u27f6 kernel hD.bottom_left_cokernel_to :=\nkernel.lift _ (cokernel.desc _ ((_ \u27f6[D] _) \u226b cokernel.\u03c0 _) begin\n  rw [\u2190 category.assoc, \u2190 D.map_comp],\n  have : hom (1,0) (2,0) \u226b 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 \u27e8b,rfl\u27e9 : \u2203 b, cokernel.\u03c0 ((1,0) \u27f6[D] (2,0)) b = a,\n  { have : function.surjective (cokernel.\u03c0 ((1,0) \u27f6[D] (2,0))),\n    by { rw surjective_iff_epi, apply_instance },\n    apply this },\n  simp [\u2190 abelian.pseudoelement.comp_apply, hD.row_exact\u2082.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 \u27e8a,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n  dsimp [left_cokernel_to_kernel_bottom_left_cokernel_to] at ha,\n  rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero at ha,\n  simp [\u2190 abelian.pseudoelement.comp_apply] at ha,\n  simp [abelian.pseudoelement.comp_apply] at ha,\n  obtain \u27e8c,hc\u27e9 : \u2203 c, ((1,0) \u27f6[D] (2,1)) c = ((2,0) \u27f6[D] (2,1)) a,\n  { apply exists_of_exact _ _ ha,\n    apply abelian.exact_cokernel, },\n  have : ((1,0) \u27f6[D] (2,0)) c = a,\n  { apply_fun ((2,0) \u27f6[D] (2,1)),\n    swap, { rw injective_iff_mono, apply hD.row_mono },\n    simpa only [\u2190 hc, \u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp] },\n  simp [\u2190 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.\u03b9 hD.bottom_left_cokernel_to a,\n  obtain \u27e8b,hb\u27e9 := cokernel_\u03c0_surjective _ a',\n  have : ((2,1) \u27f6[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 [\u2190 abelian.pseudoelement.comp_apply] using hb },\n  obtain \u27e8c,hc\u27e9 : \u2203 c, ((2,0) \u27f6[D] (2,1)) c = b,\n  { apply exists_of_exact _ _ this,\n    exact hD.row_exact\u2082 },\n  use cokernel.\u03c0 ((1,0) \u27f6[D] (2,0)) c,\n  apply_fun kernel.\u03b9 hD.bottom_left_cokernel_to,\n  swap, { rw injective_iff_mono, apply_instance },\n  change _ = a',\n  simp [\u2190 abelian.pseudoelement.comp_apply, \u2190 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 \u03b4_aux : cokernel hD.to_top_right_kernel \u27f6 kernel hD.bottom_left_cokernel_to :=\ncokernel.desc _ (kernel.lift _ (kernel.\u03b9 _ \u226b (_ \u27f6[D] _) \u226b cokernel.\u03c0 _) begin\n  dsimp only [bottom_left_cokernel_to],\n  simp,\n  rw \u2190 D.map_comp,\n  have : hom (1,1) (2,1) \u226b 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.\u03b9 hD.bottom_left_cokernel_to,\n  swap, { rw injective_iff_mono, apply_instance },\n  simp [\u2190 abelian.pseudoelement.comp_apply],\n  rw [\u2190 category.assoc, \u2190 D.map_comp],\n  have : hom (1,0) (1,1) \u226b 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) \u27f6 kernel ((1,2) \u27f6[D] (2,2)) :=\nkernel.lift _ (_ \u27f6[D] _) (hD.col_exact\u2081 _).1\n\ninstance : mono hD.to_kernel :=\nbegin\n  dsimp [to_kernel],\n  haveI : mono ((0,2) \u27f6[D] (1,2)) := hD.col_mono _,\n  apply_instance,\nend\n\ninstance : epi hD.to_kernel :=\nkernel.lift.epi (hD.col_exact\u2081 _)\n\ninstance : is_iso hD.to_kernel :=\nis_iso_of_mono_of_epi _\n\ndef cokernel_to : cokernel ((1,0) \u27f6[D] (2,0)) \u27f6 D.obj (3,0) :=\ncokernel.desc _ (_ \u27f6[D] _) (hD.col_exact\u2082 _).1\n\ninstance : mono hD.cokernel_to :=\nabelian.category_theory.limits.cokernel.desc.category_theory.mono _ _ (hD.col_exact\u2082 _)\n\ninstance : epi hD.cokernel_to :=\nbegin\n  dsimp [cokernel_to],\n  haveI : epi ((2,0) \u27f6[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 \u03b4 : D.obj (0,2) \u27f6 D.obj (3,0) :=\n  hD.to_kernel \u226b inv hD.cokernel_to_top_right_kernel_to_right_kernel \u226b  -- <-- this is an iso\n  hD.\u03b4_aux \u226b -- <- this is the key\n  inv hD.left_cokernel_to_kernel_bottom_left_cokernel_to \u226b hD.cokernel_to -- <-- this is an iso\n\ndef to_\u03b4_aux : D.obj (0,1) \u27f6 cokernel hD.to_top_right_kernel :=\nkernel.lift _ ((0,1) \u27f6[D] (1,1)) begin\n  rw [(show (hom (1,1) (2,2) = hom (1,1) (2,1) \u226b hom _ _), by refl), D.map_comp,\n    \u2190 category.assoc, (hD.col_exact\u2081 _).1],\n  simp,\nend \u226b cokernel.\u03c0 _\n\ndef from_\u03b4_aux : kernel hD.bottom_left_cokernel_to \u27f6 D.obj (3,1) :=\nkernel.\u03b9 _ \u226b cokernel.desc _ ((2,1) \u27f6[D] (3,1)) begin\n  rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) \u226b hom (1,1) (2,1), by refl),\n    D.map_comp, category.assoc, (hD.col_exact\u2082 _).w],\n  simp,\nend\n\ntheorem exact_to_\u03b4_aux : exact hD.to_\u03b4_aux hD.\u03b4_aux :=\nbegin\n  apply exact_of_pseudo_exact,\n  split,\n  { intros a,\n    dsimp [\u03b4_aux, to_\u03b4_aux],\n    rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero,\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc,\n      kernel.lift_\u03b9_assoc, category.assoc, kernel.lift_\u03b9],\n    simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact\u2081 _)] },\n  { intros b hb,\n    obtain \u27e8b,rfl\u27e9 := cokernel_\u03c0_surjective _ b,\n    dsimp [\u03b4_aux] at hb,\n    rw \u2190 eq_zero_iff_kernel_\u03b9_eq_zero at hb,\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc, kernel.lift_\u03b9] at hb,\n    simp only [abelian.pseudoelement.comp_apply] at hb,\n    let b' := kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) b,\n    obtain \u27e8c,hc\u27e9 := exists_of_cokernel_\u03c0_eq_zero _ _ hb, clear hb,\n    change _ = ((1,1) \u27f6[D] (2,1)) b' at hc,\n    rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) \u226b hom _ _, by refl), D.map_comp,\n      abelian.pseudoelement.comp_apply] at hc,\n    obtain \u27e8z,h1,h2\u27e9 := sub_of_eq_image _ _ _ hc.symm, clear hc,\n    specialize h2 _ ((1,1) \u27f6[D] (1,2)) (eq_zero_of_exact hD.row_exact\u2081 _),\n    obtain \u27e8w,hw\u27e9 : \u2203 w, ((0,1) \u27f6[D] (1,1)) w = z := exists_of_exact (hD.col_exact\u2081 _) _ h1,\n    clear h1,\n    use w,\n    dsimp only [b'] at h2,\n    dsimp only [to_\u03b4_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 [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc, category.assoc],\n    simp only [abelian.pseudoelement.comp_apply],\n    apply_fun kernel.\u03b9 ((1,2) \u27f6[D] (2,2)),\n    swap, { rw injective_iff_mono, apply_instance },\n    simp only [\u2190abelian.pseudoelement.comp_apply, kernel.lift_\u03b9_assoc,\n      category.assoc, kernel.lift_\u03b9],\n    simp only [abelian.pseudoelement.comp_apply],\n    rw [hw, h2] }\nend\n\ntheorem exact_from_\u03b4_aux : exact hD.\u03b4_aux hD.from_\u03b4_aux :=\nbegin\n  apply exact_of_pseudo_exact,\n  split,\n  { intros a,\n    dsimp [\u03b4_aux, from_\u03b4_aux],\n    obtain \u27e8a,rfl\u27e9 := cokernel_\u03c0_surjective _ a,\n    simp only [\u2190abelian.pseudoelement.comp_apply,\n      cokernel.\u03c0_desc, kernel.lift_\u03b9_assoc, category.assoc],\n    simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact\u2082 _)] },\n  { intros b hb,\n    let b' := kernel.\u03b9 hD.bottom_left_cokernel_to b,\n    obtain \u27e8c,hc\u27e9 := cokernel_\u03c0_surjective _ b',\n    simp only [from_\u03b4_aux, abelian.pseudoelement.comp_apply] at hb,\n    change cokernel.desc ((1,0) \u27f6[D] (2,1)) _ _ b' = 0 at hb,\n    rw \u2190 hc at hb,\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc] at hb,\n    obtain \u27e8d,hd\u27e9 : \u2203 d, ((1,1) \u27f6[D] (2,1)) d = c := exists_of_exact (hD.col_exact\u2082 _) _ hb,\n    obtain \u27e8e,he\u27e9 : \u2203 e, kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) e = d,\n    { apply exists_of_exact _ _ (_ : ((1,1) \u27f6[D] (2,2)) d = 0),\n      { apply exact_kernel_\u03b9 },\n      dsimp [b'] at hc,\n      apply_fun hD.bottom_left_cokernel_to at hc,\n      simp only [bottom_left_cokernel_to, \u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc] at hc,\n      rw [(show hom (1,1) (2,2) = hom (1,1) (2,1) \u226b 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.\u03b9 hD.bottom_left_cokernel_to b) = 0,\n      apply kernel_\u03b9_apply },\n    use cokernel.\u03c0 hD.to_top_right_kernel e,\n    apply_fun kernel.\u03b9 hD.bottom_left_cokernel_to,\n    swap, { rw injective_iff_mono, apply_instance },\n    change _ = b',\n    dsimp [\u03b4_aux],\n    simp only [\u2190abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc, kernel.lift_\u03b9],\n    simp only [abelian.pseudoelement.comp_apply],\n    rw [he, hd, hc] }\nend\n\ntheorem exact_to_\u03b4 : exact ((0,1) \u27f6[D] (0,2)) hD.\u03b4 :=\nbegin\n  dsimp [\u03b4],\n  rw [exact_is_iso_iff, exact_is_iso_iff, exact_comp_iso],\n  convert hD.exact_to_\u03b4_aux using 1,\n  rw is_iso.comp_inv_eq,\n  dsimp [to_kernel, to_\u03b4_aux, cokernel_to_top_right_kernel_to_right_kernel],\n  ext,\n  simp only [cokernel.\u03c0_desc, kernel.lift_\u03b9_assoc, category.assoc, kernel.lift_\u03b9],\n  simpa only [\u2190 D.map_comp],\nend\n\ntheorem exact_from_\u03b4 : exact hD.\u03b4 ((3,0) \u27f6[D] (3,1)) :=\nbegin\n  dsimp [\u03b4],\n  rw [\u2190 category.assoc, \u2190 category.assoc, \u2190 exact_is_iso_iff, exact_iso_comp],\n  convert hD.exact_from_\u03b4_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_\u03b4_aux],\n  ext,\n  simp only [cokernel.\u03c0_desc, kernel.lift_\u03b9_assoc, cokernel.\u03c0_desc_assoc, category.assoc],\n  simpa only [\u2190 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) \u27f6[D] (2,2)) \u27f6 D.obj (0,2) :=\nkernel.lift _ (kernel.\u03b9 _ \u226b D.map (hom (1,1) (1,2))) begin\n  erw [category.assoc, \u2190 D.map_comp, kernel.condition],\nend \u226b 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) \u27f6[D] (1,2)) := hD.row_epi,\n  replace hh := pseudo_surjective_of_epi ((1,1) \u27f6[D] (1,2)),\n  apply epi_of_pseudo_surjective,\n  intros t,\n  obtain \u27e8s,hs\u27e9 := hh (kernel.\u03b9 ((1,2) \u27f6[D] (2,2)) t),\n  obtain \u27e8w,hw\u27e9 : \u2203 w, kernel.\u03b9 ((1,1) \u27f6[D] (2,2)) w = s,\n  { have : exact (kernel.\u03b9 ((1,1) \u27f6[D] (2,2))) ((1,1) \u27f6[D] (2,2)) :=\n      exact_kernel_\u03b9,\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) \u226b hom (1,2) (2,2), by refl),\n      functor.map_comp, abelian.pseudoelement.comp_apply, hs,\n      \u2190 abelian.pseudoelement.comp_apply, kernel.condition,\n      abelian.pseudoelement.zero_apply] },\n  use w,\n  apply abelian.pseudoelement.pseudo_injective_of_mono\n    (kernel.\u03b9 ((1,2) \u27f6[D] (2,2))),\n  rw [\u2190 hs, \u2190 abelian.pseudoelement.comp_apply, kernel.lift_\u03b9,\n    abelian.pseudoelement.comp_apply, hw],\nend\n\ndef cokernel_to' : D.obj (3,0) \u27f6 cokernel ((1,0) \u27f6[D] (2,1)) :=\ninv hD.cokernel_to \u226b cokernel.desc _ (D.map (hom (2,0) (2,1)) \u226b cokernel.\u03c0 _) begin\n  erw [\u2190 category.assoc, \u2190 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 \u27e8b,rfl\u27e9 : \u2203 b, cokernel.\u03c0 ((1,0) \u27f6[D] (2,0)) b = a,\n  { apply abelian.pseudoelement.pseudo_surjective_of_epi },\n  rw [\u2190 abelian.pseudoelement.comp_apply, cokernel.\u03c0_desc,\n    abelian.pseudoelement.comp_apply] at ha,\n  obtain \u27e8c,hc\u27e9 : \u2203 c, ((1,0) \u27f6[D] (2,1)) c = ((2,0) \u27f6[D] (2,1)) b,\n  { have : exact ((1,0) \u27f6[D] (2,1)) (cokernel.\u03c0 _) := abelian.exact_cokernel _,\n    replace this := pseudo_exact_of_exact this,\n    apply this.2,\n    exact ha },\n  have hc' : ((1,0) \u27f6[D] (2,0)) c = b,\n  { haveI : mono ((2,0) \u27f6[D] (2,1)) := hD.row_mono,\n    apply abelian.pseudoelement.pseudo_injective_of_mono ((2,0) \u27f6[D] (2,1)),\n    rw [\u2190 abelian.pseudoelement.comp_apply, \u2190 D.map_comp],\n    exact hc },\n  rw [\u2190 hc', \u2190 abelian.pseudoelement.comp_apply, cokernel.condition,\n    abelian.pseudoelement.zero_apply],\nend\n\nlemma \u03b4_spec : hD.to_kernel' \u226b hD.\u03b4 \u226b hD.cokernel_to' =\n  kernel.\u03b9 _ \u226b D.map (hom (1,1) (2,1)) \u226b cokernel.\u03c0 _ :=\nbegin\n  dsimp only [is_snake_input.\u03b4 ,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.\u03b4_aux],\n  let t := _, change _ \u226b _ \u226b _ \u226b t = _,\n  have ht : t = kernel.\u03b9 _,\n  { dsimp [t],\n    rw is_iso.inv_comp_eq,\n    apply coequalizer.hom_ext,\n    simp only [cokernel.\u03c0_desc, category.assoc, kernel.lift_\u03b9, cokernel.\u03c0_desc_assoc] },\n  rw ht, clear ht, clear t,\n  let t := _, change t \u226b _ = _,\n  let s := _, change t \u226b s \u226b _ = _,\n  have hst : t \u226b s = cokernel.\u03c0 _,\n  { dsimp [s,t],\n    rw is_iso.comp_inv_eq,\n    apply equalizer.hom_ext,\n    simp only [cokernel.\u03c0_desc] },\n  rw reassoc_of hst, clear hst, clear s, clear t,\n  simp only [cokernel.\u03c0_desc_assoc, kernel.lift_\u03b9],\nend\n\nlemma eq_\u03b4_of_spec (e : D.obj (0,2) \u27f6 D.obj (3,0))\n  (he : hD.to_kernel' \u226b e \u226b hD.cokernel_to' = kernel.\u03b9 _ \u226b\n    D.map (hom (1,1) (2,1)) \u226b cokernel.\u03c0 _) :\n  e = hD.\u03b4 :=\nbegin\n  rw \u2190 cancel_mono hD.cokernel_to',\n  rw \u2190 cancel_epi hD.to_kernel',\n  rw [he, \u03b4_spec],\nend\n\nend delta_spec\n\nlocal attribute [instance] limits.has_zero_object.has_zero\n\nlemma exact_zero_to_ker_row\u2081_to_top_left (hD : is_snake_input D) :\n  exact (0 : 0 \u27f6 kernel ((1,0) \u27f6[D] (1,1))) hD.ker_row\u2081_to_top_left :=\nbegin\n  haveI : mono hD.ker_row\u2081_to_top_left := ker_row\u2081_to_top_left_mono hD,\n  apply exact_zero_left_of_mono,\nend\n\nlemma exact_bottom_right_to_coker_row\u2082_to_zero (hD : is_snake_input D) :\n  exact hD.bottom_right_to_coker_row\u2082 (0 : cokernel ((2,1) \u27f6[D] (2,2)) \u27f6 0) :=\nbegin\n  rw \u2190 epi_iff_exact_zero_right,\n  apply bottom_right_to_coker_row\u2082_epi hD,\nend\n\nlemma ten_term_exact_seq (hD : is_snake_input D) :\n  exact_seq \ud835\udc9c [\n    (0 : 0 \u27f6 kernel ((1,0) \u27f6[D] (1,1))),\n    hD.ker_row\u2081_to_top_left, (0,0) \u27f6[D] (0,1), (0,1) \u27f6[D] (0,2),\n    hD.\u03b4,\n    (3,0) \u27f6[D] (3,1), (3,1) \u27f6[D] (3,2), hD.bottom_right_to_coker_row\u2082,\n    (0 : cokernel ((2,1) \u27f6[D] (2,2)) \u27f6 0)] :=\nbegin\n  refine exact_seq.cons _ _ hD.exact_zero_to_ker_row\u2081_to_top_left _ _,\n  refine exact_seq.cons _ _ hD.long_row\u2080_exact _ _,\n  refine exact_seq.cons _ _ hD.row_exact\u2080 _ _,\n  refine exact_seq.cons _ _ hD.exact_to_\u03b4 _ _,\n  refine exact_seq.cons _ _ hD.exact_from_\u03b4 _ _,\n  refine exact_seq.cons _ _ hD.row_exact\u2083 _ _,\n  refine exact_seq.cons _ _ hD.long_row\u2083_exact _ _,\n  refine exact_seq.cons _ _ hD.exact_bottom_right_to_coker_row\u2082_to_zero _ _,\n  refine exact_seq.single _,\nend\n\nlemma eight_term_exact_seq (hD : is_snake_input D) :\n  exact_seq \ud835\udc9c [hD.ker_row\u2081_to_top_left, (0,0) \u27f6[D] (0,1), (0,1) \u27f6[D] (0,2),\n    hD.\u03b4,\n    (3,0) \u27f6[D] (3,1), (3,1) \u27f6[D] (3,2), hD.bottom_right_to_coker_row\u2082] :=\nexact_seq.extract hD.ten_term_exact_seq 1 7\n\nlemma six_term_exact_seq (hD : is_snake_input D) :\n  exact_seq \ud835\udc9c [(0,0) \u27f6[D] (0,1), (0,1) \u27f6[D] (0,2), hD.\u03b4, (3,0) \u27f6[D] (3,1), (3,1) \u27f6[D] (3,2)] :=\nexact_seq.extract hD.eight_term_exact_seq 1 5\n\nend is_snake_input\n\nvariables (\ud835\udc9c)\n\nstructure snake_input extends snake_diagram \u2964 \ud835\udc9c :=\n(is_snake_input : is_snake_input to_functor)\n\nnamespace snake_input\n\ninstance : category (snake_input \ud835\udc9c) := induced_category.category to_functor\n\n@[simps] def proj (x : snake_diagram) : snake_input \ud835\udc9c \u2964 \ud835\udc9c :=\ninduced_functor _ \u22d9 (evaluation _ _).obj x\n\ndef mk_of_short_exact_sequence_hom (A B : short_exact_sequence \ud835\udc9c) (f : A \u27f6 B) :\n  snake_input \ud835\udc9c :=\n\u27e8snake_diagram.mk_of_short_exact_sequence_hom A B f,\nis_snake_input.mk_of_short_exact_sequence_hom A B f\u27e9\n\ndef kernel_sequence (D : snake_input \ud835\udc9c)\n  (h1 : mono ((1,0) \u27f6[D] (1,1))) (h2 : is_zero (D.obj (3,0))) :\n  short_exact_sequence \ud835\udc9c :=\n{ fst := D.obj (0,0),\n  snd := D.obj (0,1),\n  trd := D.obj (0,2),\n  f := (0,0) \u27f6[D] (0,1),\n  g := (0,1) \u27f6[D] (0,2),\n  mono' :=\n  begin\n    letI := h1,\n    refine abelian.pseudoelement.mono_of_zero_of_map_zero _ (\u03bb a ha, _),\n    obtain \u27e8b, hb\u27e9 := is_snake_input.exists_of_exact\n      (is_snake_input.long_row\u2080_exact D.is_snake_input) a ha,\n    rw [\u2190 hb],\n    simp [is_snake_input.ker_row\u2081_to_top_left, limits.kernel.\u03b9_of_mono ((1,0) \u27f6[D] (1,1))]\n  end,\n  epi' :=\n  begin\n    rw (abelian.tfae_epi (D.obj (3,0)) ((0,1) \u27f6[D] (0,2))).out 0 2,\n    convert D.2.exact_to_\u03b4,\n    apply h2.eq_of_tgt,\n  end,\n  exact' := D.2.row_exact _ }\n\nend snake_input\n\nclass has_snake_lemma :=\n(\u03b4 : snake_input.proj \ud835\udc9c (0,2) \u27f6 snake_input.proj \ud835\udc9c (3,0))\n(exact_\u03b4 : \u2200 (D : snake_input \ud835\udc9c), exact ((0,1) \u27f6[D] (0,2)) (\u03b4.app D))\n(\u03b4_exact : \u2200 (D : snake_input \ud835\udc9c), exact (\u03b4.app D) ((3,0) \u27f6[D.1] (3,1))) -- why can't I write `\u27f6[D]`\n\nnamespace snake_lemma\n\nvariables [has_snake_lemma \ud835\udc9c]\n\nvariables {\ud835\udc9c}\n\ndef \u03b4 (D : snake_input \ud835\udc9c) : D.obj (0,2) \u27f6 D.obj (3,0) := has_snake_lemma.\u03b4.app D\n\nlemma exact_\u03b4 (D : snake_input \ud835\udc9c) : exact ((0,1) \u27f6[D] (0,2)) (\u03b4 D) :=\nhas_snake_lemma.exact_\u03b4 D\n\nlemma \u03b4_exact (D : snake_input \ud835\udc9c) : exact (\u03b4 D) ((3,0) \u27f6[D] (3,1)) :=\nhas_snake_lemma.\u03b4_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 \u00d7 expr))\n(hyps_mask : list bool) -- TODO(): convert hyps_mask and decl_premises_mask into name_sets?\n(decl_premises : list (expr \u00d7 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 \u00d7 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\u27e8\u03bb e, (json.of_string \u2218 format.to_string \u2218 format.flatten) <$> tactic.pp e\u27e9\n\nmeta instance has_to_tactic_json_of_has_coe_json {\u03b1} [has_coe \u03b1 json] : has_to_tactic_json \u03b1 :=\n\u27e8\u03bb x, pure \u2191x\u27e9\n\nmeta instance has_to_tactic_json_list {\u03b1} [has_to_tactic_json \u03b1] : has_to_tactic_json (list \u03b1) :=\nlet fn : list \u03b1 \u2192 tactic json := \u03bb xs, json.array <$> (xs.mmap to_tactic_json) in\n\u27e8fn\u27e9\n\nmeta instance has_to_tactic_json_prod {\u03b1 \u03b2} [has_to_tactic_json \u03b1] [has_to_tactic_json \u03b2] : has_to_tactic_json (\u03b1 \u00d7 \u03b2) :=\nlet fn : \u03b1 \u00d7 \u03b2 \u2192 tactic json := \u03bb \u27e8a,b\u27e9,\njson.array <$> ((::) <$> to_tactic_json a <*> pure <$> to_tactic_json b)\nin \u27e8fn\u27e9\n\nmeta def name.to_json' : name \u2192 json := \u03bb nm, json.of_string nm.to_string\n\nmeta instance has_to_tactic_json_option {\u03b1} [has_to_tactic_json \u03b1] : has_to_tactic_json (option \u03b1) :=\nlet fn : option \u03b1 \u2192 tactic json := \u03bb x,\n  match x with\n  | (some val) := to_tactic_json val\n  | none := pure $ json.null\n  end in \u27e8fn\u27e9\n\nmeta instance : has_to_tactic_json LeanStepDatapoint :=\nlet fn : LeanStepDatapoint \u2192 tactic json := \u03bb 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  | \u27e8decl_nm, decl_tp, hyps, hyps_mask,\n     decl_premises, decl_premises_mask,\n     goal, proof_term, result, next_lemma, goal_is_prop\u27e9 := do {\n    json.object <$> do {\n      decl_tp_json \u2190 to_tactic_json decl_tp,\n      hyps_json \u2190 to_tactic_json hyps,\n      hyps_mask_json \u2190 to_tactic_json hyps_mask,\n      decl_premises_json \u2190 to_tactic_json decl_premises,\n      decl_premises_mask_json \u2190  to_tactic_json decl_premises_mask,\n      goal_json \u2190 to_tactic_json goal,\n      proof_term_json \u2190 to_tactic_json proof_term,\n      result_json \u2190  to_tactic_json result,\n      verbose_goal_json \u2190 with_verbose $ to_tactic_json goal,\n      verbose_result_json \u2190 with_verbose $ to_tactic_json result,\n      verbose_proof_term_json \u2190 with_verbose $ to_tactic_json proof_term,\n      next_lemma_json \u2190 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 \u27e8fn\u27e9\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 \u2190 tactic.mk_const `PREDICT,\n  pure $ pf.replace (\u03bb e _, if e.hash = subterm.hash then pure c else none)\nsection replace_at\nopen expr\n\nmeta def expr.replace_at : expr \u2192 expr.address \u2192 expr \u2192 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\u2081 e\u2082) addr e' := match addr with\n  | [] := pure e'\n  | (expr.coord.app_fn::xs) := do {\n  new_hd \u2190 expr.replace_at e\u2081 xs e',\n  pure $ app new_hd e\u2082\n}\n  | (expr.coord.app_arg::xs) := app e\u2081 <$> expr.replace_at e\u2082 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  \u27e8[b], new_body\u27e9 \u2190 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  \u27e8[b], new_body\u27e9 \u2190 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 >>= \u03bb 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 \u2190 tactic.mk_const `PREDICT,\n  pf.replace_at addr c\n}\n\nmeta structure LeanStepState : Type :=\n(count : \u2115 := 0)\n\nmeta structure LeanStepOpts : Type :=\n(rec_limit := 5000)\n\nopen expr\n\nmeta def extract_next_lemma : expr \u2192 tactic (expr \u00d7 expr)\n| e@(app e\u2081 e\u2082) := 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 {\u03b1} : rb_set \u03b1 \u2192 rb_set \u03b1 \u2192 rb_set \u03b1 :=\n\u03bb s\u2081 s\u2082, rb_set.fold s\u2081 s\u2082 $ 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 \u00d7 expr))\n  (main_pf : expr)\n  (dp_handler : LeanStepDatapoint \u2192 tactic unit) : \u03a0\n  (acc : LeanStepState)\n  (opts : LeanStepOpts)\n  (bs : list (expr \u00d7 expr))\n  (addr : expr.address) /- always the current address of `pf` wrt `main_pf` -/\n  (pf : expr), tactic (expr_set \u00d7 name_set \u00d7 LeanStepState) := \u03bb acc opts bs addr pf,\n(guard (acc.count \u2264 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 $ \u27e8mk_expr_set, mk_name_set, {count := acc.count + 1}\u27e9\n| acc, opts, bs, addr, e@(sort _) := do lean_step_trace \"[lean_step_main_core_aux] SORT CASE\",\n  pure $ \u27e8mk_expr_set, mk_name_set, {count := acc.count + 1}\u27e9\n| acc, opts, bs, addr, e@(mvar _ _ _) := do lean_step_trace \"[lean_step_main_core_aux] MVAR CASE\",\n  pure $ \u27e8mk_expr_set, mk_name_set, {count := acc.count + 1}\u27e9\n| acc, opts, bs, addr, e@(const nm ls) := do lean_step_trace \"[lean_step_main_core_aux] CONST CASE\", do {\n  (dp : LeanStepDatapoint) \u2190 do {\n    goal \u2190 tactic.infer_type e,\n    goal_is_prop \u2190 tactic.is_prop goal,\n    result \u2190 main_pf.replace_with_predict e,\n    next_lemma \u2190 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 (\u03bb 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 \u27e8mk_expr_set, mk_name_set.insert nm, {count := acc.count + 1}\u27e9\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) \u2190 do {\n    goal \u2190 tactic.infer_type e,\n    goal_is_prop \u2190 tactic.is_prop goal,\n    result \u2190 main_pf.replace_with_predict_at addr,\n    next_lemma \u2190 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 (\u03bb 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 \u27e8mk_expr_set.insert e, mk_name_set, {count := acc.count + 1}\u27e9\n}\n| acc, opts, bs, addr, e@(app e\u2081 e\u2082) := do lean_step_trace \"[lean_step_main_core_aux] APP CASE\", do {\n    \u27e8lc_set\u2081, c_set\u2081, acc\u27e9 \u2190 lean_step_main_core_aux acc opts bs (addr ++ [expr.coord.app_fn]) e\u2081,\n    (lc_set\u2082, c_set\u2082, acc) \u2190 lean_step_main_core_aux acc opts bs (addr ++ [expr.coord.app_arg]) e\u2082,\n    let lc_set : expr_set := lc_set\u2081.union lc_set\u2082,\n    let hyps_mask := bs.map (\u03bb c, lc_set.contains c.1),\n    let c_set : name_set := c_set\u2081.union c_set\u2082,\n    let decl_premises_mask := decl_premises.map (\u03bb c, c_set.contains c.1.const_name),\n  (dp : LeanStepDatapoint) \u2190 do {\n    goal \u2190 tactic.infer_type e,\n    goal_is_prop \u2190 tactic.is_prop goal,\n    result \u2190 main_pf.replace_with_predict_at addr,\n    next_lemma \u2190 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 \u27e8lc_set, c_set, {count := acc.count + 1}\u27e9\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  \u27e8[b], new_body\u27e9 \u2190 tactic.open_n_lambdas e 1,\n  -- new_bs \u2190 mcond (tactic.is_proof b) (pure $ b::bs) (pure bs),\n\n  new_bs \u2190 (++) bs <$> pure <$> mk_type_annotation b,\n\n  \u27e8lc_set, c_set, acc\u27e9 \u2190 lean_step_main_core_aux acc opts new_bs (addr ++ [coord.lam_body]) new_body,\n  (dp : LeanStepDatapoint) \u2190 do {\n    goal \u2190 tactic.infer_type e,\n    goal_is_prop \u2190 tactic.is_prop goal,\n    result \u2190 main_pf.replace_with_predict_at addr,\n    next_lemma \u2190 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 (\u03bb x, lc_set.contains x.1)\n      , decl_premises := decl_premises\n      , decl_premises_mask := decl_premises.map (\u03bb 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 \u27e8lc_set, c_set, {count := acc.count + 1}\u27e9\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  \u27e8[b], new_body\u27e9 \u2190 tactic.open_n_pis e 1,\n  -- new_bs \u2190 mcond (tactic.is_proof b) (pure $ b::bs) (pure bs),\n\n  new_bs \u2190 (++) bs <$> pure <$> mk_type_annotation b,\n\n  \u27e8lc_set, c_set, acc\u27e9 \u2190 lean_step_main_core_aux acc opts new_bs (addr ++ [coord.pi_body]) new_body,\n  (dp : LeanStepDatapoint) \u2190 do {\n    goal \u2190 tactic.infer_type e,\n    goal_is_prop \u2190 tactic.is_prop goal,\n    result \u2190 main_pf.replace_with_predict_at addr,\n    next_lemma \u2190 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 (\u03bb x, lc_set.contains x.1)\n      , decl_premises := decl_premises\n      , decl_premises_mask := decl_premises.map (\u03bb 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 \u27e8lc_set, c_set, {count := acc.count + 1}\u27e9\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 \u00d7 expr))\n(main_pf : expr)\n(dp_handler : LeanStepDatapoint \u2192 tactic unit)\n(opts : LeanStepOpts)\n: \u03a0 (pf : expr), tactic unit := \u03bb 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 \u2190\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 \u2192 Waiter\n  | root         : Waiter\n\ndef Waiter.isRoot : Waiter \u2192 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.<idx>`. 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! (\u2190 normLevel v)\n    | Level.max v w _     => return u.updateMax! (\u2190 normLevel v) (\u2190 normLevel w)\n    | Level.imax v w _    => return u.updateIMax! (\u2190 normLevel v) (\u2190 normLevel w)\n    | Level.mvar mvarId _ =>\n      let mctx \u2190 read\n      if !mctx.isLevelAssignable mvarId then\n        pure u\n      else\n        let s \u2190 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! (\u2190 us.mapM normLevel)\n    | Expr.sort u _        => return e.updateSort! (\u2190 normLevel u)\n    | Expr.app f a _       => return e.updateApp! (\u2190 normExpr f) (\u2190 normExpr a)\n    | Expr.letE _ t v b _  => return e.updateLet! (\u2190 normExpr t) (\u2190 normExpr v) (\u2190 normExpr b)\n    | Expr.forallE _ d b _ => return e.updateForallE! (\u2190 normExpr d) (\u2190 normExpr b)\n    | Expr.lam _ d b _     => return e.updateLambdaE! (\u2190 normExpr d) (\u2190 normExpr b)\n    | Expr.mdata _ b _     => return e.updateMData! (\u2190 normExpr b)\n    | Expr.proj _ _ b _    => return e.updateProj! (\u2190 normExpr b)\n    | Expr.mvar mvarId _   =>\n      let mctx \u2190 read\n      if !mctx.isExprAssignable mvarId then\n        pure e\n      else\n        let s \u2190 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 \u00d7 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 (\u2190 read).maxHeartbeats\n\n@[inline] def mapMetaM (f : forall {\u03b1}, MetaM \u03b1 \u2192 MetaM \u03b1) {\u03b1} : SynthM \u03b1 \u2192 SynthM \u03b1 :=\n  monadMap @f\n\ninstance : Inhabited (SynthM \u03b1) 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 \u2190 getLocalInstances\n  forallTelescopeReducing type fun _ type => do\n    let className? \u2190 isClass? type\n    match className? with\n    | none   => throwError \"type class instance expected{indentExpr type}\"\n    | some className =>\n      let globalInstances \u2190 getGlobalInstancesIndex\n      let result \u2190 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\u2081 e\u2082 => e\u2081.priority < e\u2082.priority\n      let erasedInstances \u2190 getErasedInstances\n      let result \u2190 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! (\u2190 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  \u2190 inferType mvar\n  let mvarType  \u2190 instantiateMVars mvarType\n  let instances \u2190 getInstances mvarType\n  if instances.isEmpty then\n    pure none\n  else\n    let mctx \u2190 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 (\u2190 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 (\u2190 get).tableEntries.find? key\n\ndef getEntry (key : Expr) : SynthM TableEntry := do\n  match (\u2190 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 \u2190 inferType mvar\n    let mvarType \u2190 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 \u2192 Nat \u2192 List Expr \u2192 Expr \u2192 Expr \u2192 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 \u2190 mkForallFVars xs d\n    let mvar     \u2190 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 \u2190 whnf type\n    if type.isForall then\n      getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type\n    else\n      pure \u27e8subgoals, instVal, type\u27e9\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 \u2190 inferType inst\n  let result \u2190 getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType\n  match inst.getAppFn with\n  | Expr.const constName _ _ =>\n    let env \u2190 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 \u00d7 List Expr)) := do\n  let mvar \u2190 instantiateMVars mvar\n  if !(\u2190 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} \u2192 {M : Type u_2} \u2192\n         [_inst_1 : Semiring R] \u2192\n         [_inst_2 : AddCommMonoid M] \u2192\n         [_inst_3 : @ModuleS R M _inst_1 _inst_2] \u2192\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 ((\u2190 getMCtx), [])\n  let mvarType   \u2190 inferType mvar\n  let lctx       \u2190 getLCtx\n  let localInsts \u2190 getLocalInstances\n  forallTelescopeReducing mvarType fun xs mvarTypeBody => do\n    let \u27e8subgoals, instVal, instTypeBody\u27e9 \u2190 getSubgoals lctx localInsts xs inst\n    trace[Meta.synthInstance.tryResolve] \"{mvarTypeBody} =?= {instTypeBody}\"\n    if (\u2190 isDefEq mvarTypeBody instTypeBody) then\n      let instVal \u2190 mkLambdaFVars xs instVal\n      if (\u2190 isDefEq mvar instVal) then\n        trace[Meta.synthInstance.tryResolve] \"success\"\n        pure (some ((\u2190 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 \u00d7 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) \u2190 openAbstractMVarsResult answer.result\n    if (\u2190 isDefEq mvar val) then\n      pure (some (\u2190 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 \u2192 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) \u2190 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 \u2190 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}, {\u2190 inferType cNode.mvar}\"\n    let val \u2190 instantiateMVars cNode.mvar\n    trace[Meta.synthInstance.newAnswer] \"val: {val}\"\n    let result \u2190 abstractMVars val -- assignable metavariables become parameters\n    let resultType \u2190 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 \u2265 (\u2190 read).maxResultSize then\n    traceM `Meta.synthInstance.discarded do withMCtx cNode.mctx do pure m!\"size: {cNode.size} \u2265 {(\u2190 read).maxResultSize}, {\u2190 inferType cNode.mvar}\"\n    return ()\n  else\n    let answer \u2190 mkAnswer cNode\n    -- Remark: `answer` does not contain assignable or assigned metavariables.\n    let key := cNode.key\n    let entry \u2190 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) \u2192 ... \u2192 (a_n : A_n) \u2192 B` has an unused argument `a_i`.\n\n  Remark: This is syntactic check and no reduction is performed.\n-/\nprivate def hasUnusedArguments : Expr \u2192 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 `(\u03b1, transformer)`\n  where `\u03b1` is a new type without the unused arguments and the `transformer` is a function for coverting a\n  solution with type `\u03b1` into a value that can be assigned to `mvar`.\n  Example: suppose `mvar` has type `(a : A) \u2192 (b : B a) \u2192 (c : C a) \u2192 D a c`, the result is the pair\n  ```\n  ((a : A) \u2192 (c : C a) \u2192 D a c,\n   fun (f : (a : A) \u2192 (c : C a) \u2192 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 \u2192 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 \u2192 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 \u00d7 Expr)) :=\n  withMCtx mctx do\n    let mvarType \u2190 instantiateMVars (\u2190 inferType mvar)\n    if !hasUnusedArguments mvarType then\n      return none\n    else\n      forallTelescope mvarType fun xs body => do\n        let ys \u2190 xs.foldrM (init := []) fun x ys => do\n          if body.containsFVar x.fvarId! then\n            return x :: ys\n          else if (\u2190 ys.anyM fun y => return (\u2190 inferType y).containsFVar x.fvarId!) then\n            return x :: ys\n          else\n            return ys\n        let ys := ys.toArray\n        let mvarType' \u2190 mkForallFVars ys body\n        withLocalDeclD `redf mvarType' fun f => do\n          let transformer \u2190 mkLambdaFVars #[f] (\u2190 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 \u2190 mkTableKeyFor cNode.mctx mvar\n     let entry? \u2190 findEntry? key\n     match entry? with\n     | none       =>\n       -- Remove unused arguments and try again, see comment at `removeUnusedArguments?`\n       match (\u2190 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 (\u2190 findEntry? key') with\n         | none => do\n           let (mctx', mvar') \u2190 withMCtx cNode.mctx do\n             let mvar' \u2190 mkFreshExprMVar mvarType'\n             return (\u2190 getMCtx, mvar')\n           newSubgoal mctx' key' mvar' (Waiter.consumerNode { cNode with mctx := mctx', subgoals := mvar'::cNode.subgoals })\n         | some entry' => do\n           let answers' \u2190 entry'.answers.mapM fun a => withMCtx cNode.mctx do\n             let trAnswr := Expr.betaRev transformer #[\u2190 instantiateMVars a.result.expr]\n             let trAnswrType \u2190 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 (\u2190 get).generatorStack.back\n\n@[inline] def modifyTop (f : GeneratorNode \u2192 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 \u2190 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 (\u2190 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 \u00d7 Answer) := do\n  let s \u2190 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) \u2190 getNextToResume\n  match cNode.subgoals with\n  | []         => panic! \"resume found no remaining subgoals\"\n  | mvar::rest =>\n    match (\u2190 tryAnswer cNode.mctx mvar answer) with\n    | none      => pure ()\n    | some mctx =>\n      withMCtx mctx <| traceM `Meta.synthInstance.resume do\n        let goal    \u2190 inferType cNode.mvar\n        let subgoal \u2190 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 \u2190 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 (\u2190 get).result?\n\npartial def synth : SynthM (Option AbstractMVarsResult) := do\n  if (\u2190 step) then\n    match (\u2190 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 \u2190 mkFreshExprMVar type\n     let mctx \u2190 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 (\u2190 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 \u2190 whnf type\n    mkForallFVars xs type\n\nprivate def preprocessLevels (us : List Level) : MetaM (List Level \u00d7 Bool) := do\n  let mut r := #[]\n  let mut modified := false\n  for u in us do\n    let u \u2190 instantiateLevelMVars u\n    if u.hasMVar then\n      r := r.push (\u2190 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 \u2190 whnf type\n    match type with\n    | Expr.forallE _ d b _ => do\n      let arg := args.get \u27e8i, h\u27e9\n      let arg \u2190 if isOutParam d then mkFreshExprMVar d else pure arg\n      let args := args.set \u27e8i, h\u27e9 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 \u2190 getEnv\n      if !hasOutParams env constName then\n        return type\n      else\n        let args := typeBody.getAppArgs\n        let cType \u2190 inferType c\n        let args \u2190 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\" (\u2190 getOptions) do\n  let opts \u2190 getOptions\n  let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts)\n  let inputConfig \u2190 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 \u2190 instantiateMVars type\n    let type \u2190 preprocess type\n    let s \u2190 get\n    match s.cache.synthInstance.find? type with\n    | some result => pure result\n    | none        =>\n      let result? \u2190 withNewMCtxDepth do\n        let normType \u2190 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? \u2190 match result? with\n        | none        => pure none\n        | some result => do\n          let (_, _, result) \u2190 openAbstractMVarsResult result\n          trace[Meta.synthInstance] \"result {result}\"\n          let resultType \u2190 inferType result\n          if (\u2190 withConfig (fun _ => inputConfig) <| isDefEq type resultType) then\n            let result \u2190 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) (\u03b1 : Sort u)\n                class C {a : A} (\u03b1 : Sort u) [B a \u03b1]\n                class D {a : A} (\u03b1 : Sort u) [B a \u03b1] [c : C \u03b1]\n                class E (a : A) where [c (\u03b1 : Sort u) [B a \u03b1] : C \u03b1]\n                instance c {a : A} [e : E a] (\u03b1 : Sort u) [B a \u03b1] : C \u03b1 := e.c \u03b1\n\n                def d {a : A} [e : E a] (\u03b1 : Sort u) [b : B a \u03b1] : D \u03b1 := \u27e8\u27e9\n               ```\n               The term `D \u03b1` has two instance implicit arguments. The second one has type `C \u03b1`, and TC\n               resolution produces the result `@c.{u} a e \u03b1 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 \u03b1 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? \u2190 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 \u2190 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 (\u2190 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 (\u2190 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? \u2190 catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none)\n          match val? with\n          | none     =>\n            return false\n          | some val =>\n            if (\u2190 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 \"\u03a0\" many1(binderIdent <|> bracketedBinder) \", \" term : term\nmacro_rules | `(\u03a0 $xs*, $y) => `(\u2200 $xs*, $y)\n\nmacro \"\u03bb \" 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 \u2192 Sexp\n| list: List Sexp \u2192 Sexp\nderiving BEq, Inhabited, Repr\n\ndef Sexp.fromString : String \u2192 Sexp\n| s => Sexp.atom s\n\ninstance : Coe String Sexp where\n  coe s := Sexp.fromString s\n\ndef Sexp.fromList : List Sexp \u2192 Sexp\n| xs => Sexp.list xs\n\ninstance : Coe (List Sexp) Sexp where\n  coe := Sexp.fromList\n\n\npartial def Sexp.toString : Sexp \u2192 String\n| .atom s => s\n| .list xs => \"(\" ++ \" \".intercalate (xs.map Sexp.toString) ++ \")\"\n\ninstance : ToString Sexp := \u27e8Sexp.toString\u27e9\n\ndef Sexp.toList? : Sexp \u2192 Option (List Sexp)\n| .atom _ => .none\n| .list xs => .some xs\n\ndef Sexp.toAtom! : Sexp \u2192 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 \u2192  SexpTok\n| opening: String.Pos \u2192 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 := \u03bb 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 \u00d7 String.Pos)) := do\n  let state \u2190 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 \u2190 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 \u2190 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 \u2190 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 \u03b1] : Inhabited (SexpM \u03b1) where\n  default := do return default\n\n\ndef SexpM.pop: SexpM SexpTok := do\n  let state \u2190 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 \u00d7 (List SexpTok) \u00d7 (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 \u2190 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 (\u2190 SexpM.peek) with\n  | .none => SexpM.mkSubstring startPos (\u2190 SexpM.curPos)\n  | .some (' ', _) => SexpM.mkSubstring startPos (\u2190 SexpM.curPos)\n  | .some ('(', _) => SexpM.mkSubstring startPos (\u2190 SexpM.curPos)\n  | .some (')', _) => SexpM.mkSubstring startPos (\u2190 SexpM.curPos)\n  | .some _ => do\n     SexpM.advance\n     SexpM.takeString startPos\n\npartial def SexpM.parse: SexpM Unit := do\n  match (\u2190 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 \u2190 SexpM.takeString i\n      SexpM.pushSexp ((Sexp.atom s.toString))\n      SexpM.parse\n  | .none => do\n      let state \u2190 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 (\u2190 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 \u00b7 subExpr)\n\npartial def Sexp.vars : Sexp \u2192 List String\n  | .atom s => [s]\n  | .list sexps => List.join $ sexps.map vars\n\npartial def Sexp.fvarsConstsVars : Sexp \u2192 List Sexp \u00d7 List Sexp \u00d7 List String\n  | .atom s => ([],[],[s])\n  | c@(.list (\"const\"::_)) => ([],[c],[])\n  | fvar@(.list (\"fvar\"::_)) => ([fvar],[],[])\n  | .list sexps => sexps.foldl (init := ([],[],[]))\n    \u03bb (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 \u00d7 Sexp)\n\n-- Some generic helper functions\ndef _root_.List.revLookup? {\u03b1 \u03b2 : Type 0} [BEq \u03b2] : List (\u03b1 \u00d7 \u03b2) \u2192 \u03b2 \u2192 Option \u03b1\n  | [], _ => none\n  | (a,b)::rest, b' => if b == b' then some a else rest.revLookup? b'\n\ndef _root_.List.unique {\u03b1 : Type 0} [BEq \u03b1] : List \u03b1 \u2192 List \u03b1\n  | [] => []\n  | a :: as => if as.contains a then as.unique else (a :: as.unique)\n\ndef _root_.List.unzip3 {\u03b1 \u03b2 \u03b3 : Type 0} : List (\u03b1 \u00d7 \u03b2 \u00d7 \u03b3) \u2192 List \u03b1 \u00d7 List \u03b2 \u00d7 List \u03b3\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 \u2192 String\n  | .atom s => s\n  | .list [] => \"\"\n  | .list (hd::_) => head hd\n\ndef Sexp.uncurry : Sexp \u2192 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 \u2192 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 \u2192 List Sexp \u00d7 VariableMapping\n  | sexps =>\n    let fvarsConstsVars := sexps.foldl (init := ([],[],[]))\n      \u03bb (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 \u03bb 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 \u03bb exp => replaceTerm c (Sexp.atom vname) exp\n      return (exps, mapping)\n\ndef Sexp.unsimplify : Sexp \u2192  VariableMapping \u2192 Sexp\n  | sexp, mapping => sexp.vars.foldl (init := sexp)\n    \u03bb e var => match mapping.lookup var with\n      | none => e\n      | some subexp => replaceTerm (Sexp.atom var) subexp e\n\ndef unsimplifySExps : List Sexp \u2192  VariableMapping \u2192 List Sexp\n  | sexps, mapping => sexps.map\n    \u03bb exp => exp.vars.foldl (init := exp)\n      \u03bb 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 (\u03bb e => e.uncurry ) |>.map toString\n#eval (realexampleSimplified.1.map (\u03bb e => e.uncurry.curry) |>.zip realexampleSimplified.1).map \u03bb (a,b) => a == b\n\n#eval realexampleSimplified.2.map \u03bb (s,sexp) => (s,sexp.toString)\n#eval realexampleSimplified.1.map (Sexp.unsimplify \u00b7 realexampleSimplified.2) |>.zip realexample |>.map \u03bb (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 {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (b : \u03b2) : HasExternalFunctors.IsFun (\u03bb a : \u03b1 => F a b) :=\n  h.compIsFun F (appFun' b \u03b3)\n\n  def swapFun' {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (b : \u03b2) : \u03b1 \u27f6' \u03b3 := BundledFunctor.mkFun (swapIsFun F b)\n  def swapFun  {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6  \u03b2 \u27f6 \u03b3) (b : \u03b2) : \u03b1 \u27f6  \u03b3 := HasInternalFunctors.fromBundled (swapFun' (HasInternalFunctors.toBundled F) b)\n\n  @[simp] theorem swapFun.eff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (b : \u03b2) (a : \u03b1) : (swapFun F b) a = F a b :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  theorem swapFunFun.def {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (b : \u03b2) :\n    HasInternalFunctors.fromBundled (swapFun' F b) = HasInternalFunctors.fromBundled (HasInternalFunctors.toBundled (appFun b \u03b3) \u2299' F) :=\n  HasInternalFunctors.toFromBundled (appFun' b \u03b3) \u25b8 rfl\n\n  def swapFunIsFun {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) : HasExternalFunctors.IsFun (\u03bb b : \u03b2 => HasInternalFunctors.fromBundled (swapFun' F b)) :=\n  funext (swapFunFun.def F) \u25b8 h.compIsFun (appFunFun' \u03b2 \u03b3) (compFunFun' F \u03b3)\n\n  def swapFunFun' {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) : \u03b2 \u27f6' \u03b1 \u27f6 \u03b3 := BundledFunctor.mkFun (swapFunIsFun F)\n  def swapFunFun  {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6  \u03b2 \u27f6 \u03b3) : \u03b2 \u27f6  \u03b1 \u27f6 \u03b3 := HasInternalFunctors.fromBundled (swapFunFun' (HasInternalFunctors.toBundled F))\n\n  @[simp] theorem swapFunFun.eff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (b : \u03b2) : (swapFunFun F) b = swapFun F b :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  @[simp] theorem swapFunFun.effEff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (b : \u03b2) (a : \u03b1) : ((swapFunFun F) b) a = F a b :=\n  by simp\n\n  theorem swapFunFunFun.def (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) :\n    HasInternalFunctors.mkFun (swapFunIsFun (HasInternalFunctors.toBundled F)) = HasInternalFunctors.fromBundled (HasInternalFunctors.toBundled (compFunFun F \u03b3) \u2299' appFunFun' \u03b2 \u03b3) :=\n  HasInternalFunctors.toFromBundled (compFunFun' (HasInternalFunctors.toBundled F) \u03b3) \u25b8 elimRec\n\n  def swapFunFunIsFun (\u03b1 \u03b2 \u03b3 : U) : HasExternalFunctors.IsFun (\u03bb F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3 => swapFunFun F) :=\n  funext (swapFunFunFun.def \u03b1 \u03b2 \u03b3) \u25b8 h.compIsFun (compFunFunFun' \u03b1 (\u03b2 \u27f6 \u03b3) \u03b3) (compFunFun' (appFunFun' \u03b2 \u03b3) (\u03b1 \u27f6 \u03b3))\n\n  def swapFunFunFun' (\u03b1 \u03b2 \u03b3 : U) : (\u03b1 \u27f6 \u03b2 \u27f6 \u03b3) \u27f6' (\u03b2 \u27f6 \u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (swapFunFunIsFun \u03b1 \u03b2 \u03b3)\n  def swapFunFunFun  (\u03b1 \u03b2 \u03b3 : U) : (\u03b1 \u27f6 \u03b2 \u27f6 \u03b3) \u27f6  (\u03b2 \u27f6 \u03b1 \u27f6 \u03b3) := HasInternalFunctors.fromBundled (swapFunFunFun' \u03b1 \u03b2 \u03b3)\n\n  @[simp] theorem swapFunFunFun.eff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) : (swapFunFunFun \u03b1 \u03b2 \u03b3) F = swapFunFun F :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  @[simp] theorem swapFunFunFun.effEff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (b : \u03b2) : ((swapFunFunFun \u03b1 \u03b2 \u03b3) F) b = swapFun F b :=\n  by simp\n\n  @[simp] theorem swapFunFunFun.effEffEff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (b : \u03b2) (a : \u03b1) : (((swapFunFunFun \u03b1 \u03b2 \u03b3) F) b) a = F a b :=\n  by simp\n\n  -- In particular, reverse composition is also functorial.\n\n  def revCompFun {\u03b1 \u03b2 \u03b3 : U} (G : \u03b2 \u27f6  \u03b3) (F : \u03b1 \u27f6  \u03b2) : \u03b1 \u27f6 \u03b3 := compFun F G\n  infixr:90 \" \u2299 \"  => HasLinearFunOp.revCompFun\n\n  @[simp] theorem revCompFun.eff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2) (G : \u03b2 \u27f6 \u03b3) (a : \u03b1) : (G \u2299 F) a = G (F a) :=\n  compFun.eff F G a\n\n  theorem revCompFunFun.def (\u03b1 : U) {\u03b2 \u03b3 : U} (G : \u03b2 \u27f6' \u03b3) (F : \u03b1 \u27f6 \u03b2) :\n    HasInternalFunctors.fromBundled (G \u2299' HasInternalFunctors.toBundled F) = (compFunFun F \u03b3) (HasInternalFunctors.fromBundled G) :=\n  Eq.subst (motive := \u03bb H => HasInternalFunctors.fromBundled (H \u2299' HasInternalFunctors.toBundled F) = (compFunFun F \u03b3) (HasInternalFunctors.fromBundled G))\n           (HasInternalFunctors.toFromBundled G)\n           (Eq.symm (compFunFun.eff F \u03b3 (HasInternalFunctors.fromBundled G)))\n\n  def revCompFunIsFun (\u03b1 : U) {\u03b2 \u03b3 : U} (G : \u03b2 \u27f6' \u03b3) :\n    HasExternalFunctors.IsFun (\u03bb F : \u03b1 \u27f6 \u03b2 => HasInternalFunctors.fromBundled (G \u2299' HasInternalFunctors.toBundled F)) :=\n  funext (revCompFunFun.def \u03b1 G) \u25b8 swapIsFun (compFunFunFun' \u03b1 \u03b2 \u03b3) (HasInternalFunctors.fromBundled G)\n\n  def revCompFunFun' (\u03b1 : U) {\u03b2 \u03b3 : U} (G : \u03b2 \u27f6' \u03b3) : (\u03b1 \u27f6 \u03b2) \u27f6' (\u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (revCompFunIsFun \u03b1 G)\n  def revCompFunFun  (\u03b1 : U) {\u03b2 \u03b3 : U} (G : \u03b2 \u27f6  \u03b3) : (\u03b1 \u27f6 \u03b2) \u27f6  (\u03b1 \u27f6 \u03b3) := HasInternalFunctors.fromBundled (revCompFunFun' \u03b1 (HasInternalFunctors.toBundled G))\n\n  @[simp] theorem revCompFunFun.eff (\u03b1 : U) {\u03b2 \u03b3 : U} (G : \u03b2 \u27f6 \u03b3) (F : \u03b1 \u27f6 \u03b2) : (revCompFunFun \u03b1 G) F = G \u2299 F :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  @[simp] theorem revCompFunFun.effEff (\u03b1 : U) {\u03b2 \u03b3 : U} (G : \u03b2 \u27f6 \u03b3) (F : \u03b1 \u27f6 \u03b2) (a : \u03b1) : ((revCompFunFun \u03b1 G) F) a = G (F a) :=\n  by simp\n\n  theorem revCompFunFunFun.def (\u03b1 \u03b2 \u03b3 : U) (G : \u03b2 \u27f6 \u03b3) :\n    HasInternalFunctors.mkFun (revCompFunIsFun \u03b1 (HasInternalFunctors.toBundled G)) = HasInternalFunctors.fromBundled (swapFun' (compFunFunFun' \u03b1 \u03b2 \u03b3) G) :=\n  congrArg (\u03bb H => HasInternalFunctors.fromBundled (swapFun' (compFunFunFun' \u03b1 \u03b2 \u03b3) H)) (HasInternalFunctors.fromToBundled G) \u25b8 elimRec\n\n  def revCompFunFunIsFun (\u03b1 \u03b2 \u03b3 : U) : HasExternalFunctors.IsFun (\u03bb G : \u03b2 \u27f6 \u03b3 => revCompFunFun \u03b1 G) :=\n  funext (revCompFunFunFun.def \u03b1 \u03b2 \u03b3) \u25b8 swapFunIsFun (compFunFunFun' \u03b1 \u03b2 \u03b3)\n\n  def revCompFunFunFun' (\u03b1 \u03b2 \u03b3 : U) : (\u03b2 \u27f6 \u03b3) \u27f6' (\u03b1 \u27f6 \u03b2) \u27f6 (\u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (revCompFunFunIsFun \u03b1 \u03b2 \u03b3)\n  def revCompFunFunFun  (\u03b1 \u03b2 \u03b3 : U) : (\u03b2 \u27f6 \u03b3) \u27f6  (\u03b1 \u27f6 \u03b2) \u27f6 (\u03b1 \u27f6 \u03b3) := HasInternalFunctors.fromBundled (revCompFunFunFun' \u03b1 \u03b2 \u03b3)\n\n  @[simp] theorem revCompFunFunFun.eff (\u03b1 \u03b2 \u03b3 : U) (G : \u03b2 \u27f6 \u03b3) : (revCompFunFunFun \u03b1 \u03b2 \u03b3) G = revCompFunFun \u03b1 G :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  @[simp] theorem revCompFunFunFun.effEff (\u03b1 \u03b2 \u03b3 : U) (G : \u03b2 \u27f6 \u03b3) (F : \u03b1 \u27f6 \u03b2) : ((revCompFunFunFun \u03b1 \u03b2 \u03b3) G) F = G \u2299 F :=\n  by simp\n\n  @[simp] theorem revCompFunFunFun.effEffEff (\u03b1 \u03b2 \u03b3 : U) (G : \u03b2 \u27f6 \u03b3) (F : \u03b1 \u27f6 \u03b2) (a : \u03b1) : (((revCompFunFunFun \u03b1 \u03b2 \u03b3) G) F) a = G (F a) :=\n  by simp\n\n  -- Composition of a function with two arguments.\n\n  def compFun\u2082 {\u03b1 \u03b2 \u03b3 \u03b4 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (G : \u03b3 \u27f6 \u03b4) : \u03b1 \u27f6 \u03b2 \u27f6 \u03b4 := swapFunFun (revCompFunFun \u03b1 G \u2299 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 : \u03b2 \u27f6 \u03b3` and an argument `b : \u03b2`, then the\n  -- construction of `H b` is also functorial.\n\n  theorem substFun.def {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6' \u03b2) (a : \u03b1) :\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 {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6' \u03b2) : HasExternalFunctors.IsFun (\u03bb a : \u03b1 => F a (G a)) :=\n  funext (substFun.def F G) \u25b8 h.dupIsFun (HasLinearFunOp.swapFunFun' F \u2299' G)\n\n  def substFun' {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6' \u03b2) : \u03b1 \u27f6' \u03b3 := BundledFunctor.mkFun (substIsFun F G)\n  def substFun  {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6  \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6  \u03b2) : \u03b1 \u27f6  \u03b3 := HasInternalFunctors.fromBundled (substFun' (HasInternalFunctors.toBundled F) (HasInternalFunctors.toBundled G))\n\n  @[simp] theorem substFun.eff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6 \u03b2) (a : \u03b1) : (substFun F G) a = F a (G a) :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  theorem substFunFun.def {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6 \u03b2) :\n    HasInternalFunctors.mkFun (substIsFun F (HasInternalFunctors.toBundled G)) =\n    HasInternalFunctors.fromBundled (HasNonLinearFunOp.dupFun' (HasInternalFunctors.toBundled (HasInternalFunctors.fromBundled (HasLinearFunOp.swapFunFun' F \u2299' HasInternalFunctors.toBundled G)))) :=\n  HasInternalFunctors.toFromBundled _ \u25b8 elimRec\n\n  def substFunIsFun {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) :\n    HasExternalFunctors.IsFun (\u03bb G : \u03b1 \u27f6 \u03b2 => HasInternalFunctors.fromBundled (substFun' F (HasInternalFunctors.toBundled G))) :=\n  funext (substFunFun.def F) \u25b8 h.compIsFun (HasLinearFunOp.revCompFunFun' \u03b1 (HasLinearFunOp.swapFunFun' F)) (HasNonLinearFunOp.dupFunFun' \u03b1 \u03b3)\n\n  def substFunFun' {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6' \u03b2 \u27f6 \u03b3) : (\u03b1 \u27f6 \u03b2) \u27f6' (\u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (substFunIsFun F)\n  def substFunFun  {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6  \u03b2 \u27f6 \u03b3) : (\u03b1 \u27f6 \u03b2) \u27f6  (\u03b1 \u27f6 \u03b3) := HasInternalFunctors.fromBundled (substFunFun' (HasInternalFunctors.toBundled F))\n\n  @[simp] theorem substFunFun.eff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6 \u03b2) : (substFunFun F) G = substFun F G :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  @[simp] theorem substFunFun.effEff {\u03b1 \u03b2 \u03b3 : U} (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6 \u03b2) (a : \u03b1) : ((substFunFun F) G) a = F a (G a) :=\n  by simp\n\n  theorem substFunFunFun.def (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) :\n    HasInternalFunctors.mkFun (substFunIsFun (HasInternalFunctors.toBundled F)) = HasInternalFunctors.fromBundled (HasNonLinearFunOp.dupFunFun' \u03b1 \u03b3 \u2299' HasInternalFunctors.toBundled (HasLinearFunOp.revCompFunFun \u03b1 (HasLinearFunOp.swapFunFun F))) :=\n  HasInternalFunctors.toFromBundled _ \u25b8 HasInternalFunctors.toFromBundled _ \u25b8 elimRec\n\n  def substFunFunIsFun (\u03b1 \u03b2 \u03b3 : U) : HasExternalFunctors.IsFun (\u03bb F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3 => substFunFun F) :=\n  funext (substFunFunFun.def \u03b1 \u03b2 \u03b3) \u25b8 h.compIsFun (HasLinearFunOp.revCompFunFunFun' \u03b1 \u03b2 (\u03b1 \u27f6 \u03b3) \u2299' HasLinearFunOp.swapFunFunFun' \u03b1 \u03b2 \u03b3)\n                                                  (HasLinearFunOp.revCompFunFun' (\u03b1 \u27f6 \u03b2) (HasNonLinearFunOp.dupFunFun' \u03b1 \u03b3))\n\n  def substFunFunFun' (\u03b1 \u03b2 \u03b3 : U) : (\u03b1 \u27f6 \u03b2 \u27f6 \u03b3) \u27f6' (\u03b1 \u27f6 \u03b2) \u27f6 (\u03b1 \u27f6 \u03b3) := BundledFunctor.mkFun (substFunFunIsFun \u03b1 \u03b2 \u03b3)\n  def substFunFunFun  (\u03b1 \u03b2 \u03b3 : U) : (\u03b1 \u27f6 \u03b2 \u27f6 \u03b3) \u27f6  (\u03b1 \u27f6 \u03b2) \u27f6 (\u03b1 \u27f6 \u03b3) := HasInternalFunctors.fromBundled (substFunFunFun' \u03b1 \u03b2 \u03b3)\n\n  @[simp] theorem substFunFunFun.eff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) : (substFunFunFun \u03b1 \u03b2 \u03b3) F = substFunFun F :=\n  by apply HasInternalFunctors.fromBundled.eff\n\n  @[simp] theorem substFunFunFun.effEff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6 \u03b2) : ((substFunFunFun \u03b1 \u03b2 \u03b3) F) G = substFun F G :=\n  by simp\n\n  @[simp] theorem substFunFunFun.effEffEff (\u03b1 \u03b2 \u03b3 : U) (F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3) (G : \u03b1 \u27f6 \u03b2) (a : \u03b1) : (((substFunFunFun \u03b1 \u03b2 \u03b3) 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 (\u03bb a : \u03b1 => t)`\n-- is as follows:\n--\n--  Case                           | Proof\n-- --------------------------------+--------------------------------------------------------------\n--  `t` does not contain `a`       | `constIsFun \u03b1 t`\n--  `t` is `a`                     | `idIsFun \u03b1`\n--  `t` is `G b` with `G : \u03b2 \u27f6 \u03b3`: |\n--    `a` appears only in `b`      | Prove that `\u03bb a => b` is functorial, yielding a functor\n--                                 | `F : \u03b1 \u27f6 \u03b2`. Then the proof is `compIsFun F G`.\n--      `b` is `a`                 | Optimization: `HasInternalFunctors.isFun G`\n--    `a` appears only in `G`      | Prove that `\u03bb a => G` is functorial, yielding a functor\n--                                 | `F : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3`. Then the proof is `swapIsFun F b`.\n--      `G` is `a`                 | Optimization: `appIsFun b \u03b3`\n--    `a` appears in both          | Prove that `\u03bb a => G` is functorial, yielding a functor\n--                                 | `F\u2081 : \u03b1 \u27f6 \u03b2 \u27f6 \u03b3`. Prove that `\u03bb a => b` is functorial,\n--                                 | yielding a functor `F\u2082 : \u03b1 \u27f6 \u03b2`. Then the proof is\n--                                 | `substIsFun F\u2081 F\u2082`.\n--  `t` is `mkFun (\u03bb b : \u03b2 => c)`  | Prove that `\u03bb a => c` is functorial when regarding `b` as\n--                                 | a constant, yielding a functor `F : \u03b1 \u27f6 \u03b3` for every `b`.\n--                                 | Prove that  `\u03bb b => F` is functorial, yielding a functor\n--                                 | `G : \u03b2 \u27f6 \u03b1 \u27f6 \u03b3`. 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 : \u2200n 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 \u2192 Ref\n| null : Ref\n\ninstance dec_eq_ref (r r' : Ref) [o_dec : \u2200o o' : O, decidable (o = o')] [f_dec : decidable false] [t_dec : decidable true] : decidable (r = r') := begin\n  have ineq : \u2200o : O, (Ref.null = Ref.o o) = false, cc,\n  have ineq' : \u2200o : 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 \u2192 V\n| z : \u2124 \u2192 V\n| q : \u211a* \u2192 V\n| o : Ref \u2192 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 \u2192 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 \u00d7 O \u2192 V\ndef S := var \u2192 V\ndef FieldPermMask := mask (field \u00d7 O)\ndef PredPermMask := mask (pred \u00d7 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 \u2192 E\n| const_n : \u2124 \u2192 E\n| x : var \u2192 E\n| deref : E \u2192 field \u2192 E\n| negate : E \u2192 E\n| add : E \u2192 E \u2192 E\n| div : E \u2192 E \u2192 E\n| not : E \u2192 E\n| eq : E \u2192 E \u2192 E\n| apply : func \u2192 list E \u2192 E\n| unfolding : pred \u2192 list E \u2192 E \u2192 E \u2192 E\n| fieldPerm : E \u2192 field \u2192 E\n| predPerm : pred \u2192 list E \u2192 E\n\ninductive A\n| e : E \u2192 A\n| fieldAcc : E \u2192 field \u2192 E \u2192 A\n| predAcc : pred \u2192 list E \u2192 E \u2192 A\n| imp : E \u2192 A \u2192 A\n| conj : A \u2192 A \u2192 A\n| all : T \u2192 (E \u2192 A) \u2192 A\n| ex : T \u2192 (E \u2192 A) \u2192 A\n| forperm : field \u2192 E \u2192 A\n\ninductive Eval\n| type_err : Eval\n| err : X \u2192 Eval\n| ok : V \u2192 Eval\n\ndef Eval.is_x : Eval \u2192 Prop\n| Eval.type_err := false\n| (Eval.err _) := true\n| (Eval.ok _) := false\n\ndef Eval.is_v : Eval \u2192 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 \u2192 T \u2192 Prop\n| Eval.type_err _ := false\n| (Eval.err _) _ := false\n| (Eval.ok v) t := v.typ = t\n\nstructure defs :=\n(var : var \u2192 T) \n(field : field \u2192 T)\n(func : func \u2192 (list T) \u00d7 T \u00d7 (list V \u2192 Eval)) -- shamelessly shallowly embed lean functions, to not deal with termination.\n(pred : pred \u2192 (list T))\n\ndef E.typ (d : defs) : E \u2192 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 \u2192 list T \u2192 Prop\n| [] [] := true\n| [] (_ :: _) := false\n| (_ :: _) [] := false\n| (e :: es) (t :: ts) := e.typ d = t \u2227 all_typed es ts\n\nmutual def all_wt, wt (d : defs)\nwith all_wt : list E \u2192 Prop\n| [] := true\n| (e :: es) := (wt e \u2227 all_wt es)\n\nwith wt : E \u2192 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 \u2227 wt o\n| (E.negate z) := z.typ d = T.Z \u2227 wt z\n| (E.add z z') := z.typ d = z'.typ d \u2227 (z.typ d = T.Z \u2228 z.typ d = T.Q) \u2227 wt z \u2227 wt z'\n| (E.div z z') := z.typ d = z'.typ d \u2227 (z.typ d = T.Z \u2228 z.typ d = T.Q) \u2227 wt z \u2227 wt z'\n| (E.not b) := b.typ d = T.B \u2227 wt b\n| (E.eq v v') := v.typ d = v'.typ d \u2227 wt v \u2227 wt v'\n| (E.apply f args) := all_typed d args (d.func f).fst \u2227 all_wt args\n| (E.unfolding p args q e) := all_typed d args (d.pred p) \u2227 all_wt args \u2227 wt q \u2227 wt e\n| (E.fieldPerm o f) := o.typ d = T.O \u2227 wt o\n| (E.predPerm p args) := all_typed d args (d.pred p) \u2227 all_wt args\n\ndef conf.wt (d : defs) (c : conf) : Prop :=\n  (\u2200x, (c.s x).typ = d.var x)\n  \u2227 (\u2200f o, (c.h (f, o)).typ = d.field f)\n\ndef Eval.map_v (e : Eval) (f : V \u2192 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  : \u2200 {t t' : T} {f : V \u2192 Eval} (e : Eval),\n    e.is_x \u2228 e.is_t t' \u2192\n    (\u2200 (v : V) (h : e = Eval.ok v), (f v).is_x \u2228 (f v).is_t t) \u2192 \n    (e.map_v f).is_x \u2228 (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 \u2194 v.typ = t := by simp [Eval.is_t]\n\ndef Eval.cases_v (e : Eval) (f_b : bool \u2192 Eval) (f_z : \u2124 \u2192 Eval) (f_q : \u211a* \u2192 Eval) (f_o : Ref \u2192 Eval) :=\n  e.map_v $ \u03bbv, 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 \u2192 (list V \u2192 Eval) \u2192 list Eval \u2192 Eval\n| acc f [] := f acc\n| acc f (e :: es) := e.map_v $ \u03bbv, evals_map' (acc ++ [v]) f es\n\ndef evals_map (es : list Eval) (f : list V \u2192 Eval) : Eval :=\n  evals_map' [] f es\n\nlemma evals_map_x_or_t : \n  \u2200 {t  : T} (f : list V \u2192 Eval) (es : list Eval),\n    (\u2200e : Eval, \u2203t : T, e \u2208 es \u2192 e.is_x \u2228 e.is_t t) \u2192\n    (\u2200 (vs : list V) (h : es = vs.map Eval.ok), (f vs).is_x \u2228 (f vs).is_t t) \u2192\n    (evals_map es f).is_x \u2228 (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 \u2192 E \u2192 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 $ \u03bbv, \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 $ \u03bbv,\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 $ \u03bbz, (eval c z').map_v $ \u03bbz',\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 $ \u03bbz, (eval c z').map_v $ \u03bbz',\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 $ \u03bbv,\n  match v with\n  | (V.b b) := Eval.ok $ V.b \u00acb\n  | _ := Eval.type_err\n  end\n| c (E.eq v v') := (eval c v).map_v $ \u03bbv, (eval c v').map_v $ \u03bbv',\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) $ \u03bbargs, ((d.func f).snd.snd args)\n| c (E.unfolding p args q e) := evals_map (evals c args) $\n    \u03bbargs, if c.predPerm (p, args) < 1\n      then Eval.err X.perm\n      else (eval c e).map_v $ \u03bbbody, Eval.ok (V.b ff)\n| c (E.fieldPerm o f) := (eval c o).map_v $ \u03bbo,\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)$ \u03bbargs, \n    Eval.ok $ V.q $ c.predPerm (p, args)\n\nwith evals : conf \u2192 list E \u2192 list Eval\n| c [] := []\n| c (e :: es) := (eval c e) :: (evals c es)\n\n#print decidable.rec\n\nlemma x {\u03b1 : Type} (c : Prop) [decidable c] (a a' : \u03b1) : (ite c a a') = (ite (\u00acc) a' a) := begin\n  exact (ite_not c a' a).symm\nend \n\nlemma ite_prop {\u03b1 : Type} {prop : \u03b1 \u2192 Prop} {c : Prop} [h : decidable c] {a a' : \u03b1} :\n  (c \u2192 prop a) \u2227 (\u00acc \u2192 prop a') \u2194 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 \u2228 (eval d c e).is_t (e.typ d) := \nbegin\n  rw conf.wt at ch,\n  have var_ok : \u2200x, (c.s x).typ = d.var x, exact and.elim_left ch,\n  have field_ok : \u2200f 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 \u2190ite_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, \u2190h.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, \u2190h.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, \u2190h.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 \u2190ite_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, \u2190h.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 \u2190ite_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, \u2190t_eq, \u2190ih 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": "/-\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.smt.congruence_closure\nimport Mathlib.Lean3Lib.init.meta.attribute\nimport Mathlib.Lean3Lib.init.meta.simp_tactic\nimport Mathlib.Lean3Lib.init.meta.interactive_base\nimport Mathlib.Lean3Lib.init.meta.derive\n \n\nuniverses l \n\nnamespace Mathlib\n\n/-- Heuristic instantiation lemma -/\n/-- `mk_core m e as_simp`, m is used to decide which definitions will be unfolded in patterns.\n   If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion\n   as a pattern. -/\n/--\nCreate a new \"cached\" attribute (attr_name : user_attribute hinst_lemmas).\nIt also creates \"cached\" attributes for each attr_names and simp_attr_names if they have not been defined\nyet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with\n    attr_name, attrs_name, and simp_attr_names.\nFor the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern.\n-/\nstructure ematch_config \nwhere\n  max_instances : \u2115\n  max_generation : \u2115\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/smt/ematch.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.34158248603300034, "lm_q2_score": 0.024798161907285888, "lm_q1q2_score": 0.008470617793339562}}
{"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 : \u2200 x : \u03b1, has_uncurry (list (\u03b2 x) \u2192 list (\u03b2 x) \u2192 list (\u03b2 x)) _ _)\n-- unless all the underscores are made explicit for some reason.\n-- (infer_instance : \u2200 x : \u03b1, has_uncurry (list (\u03b2 x) \u2192 list (\u03b2 x) \u2192 list (\u03b2 x)) (list (\u03b2 x) \u00d7 list (\u03b2 x)) (list $ \u03b2 x))\n\n-- This is why we make the following instances\n-- -/\n-- universes u v\n-- variables {\u03b1 : Type} {\u03b2 \u03b2\u2081 \u03b2\u2082 \u03b3 \u03b4 : \u03b1 \u2192 Type}\n\n-- class has_uncurry_dep {\u03b1 : Type} (\u03b2 : \u03b1 \u2192 Type) (\u03b2\u2081 \u03b2\u2082 : out_param (\u03b1 \u2192 Type)) :=\n-- (uncurry : \u2200 {x}, (\u03b2 x) \u2192 ((\u03b2\u2081 x) \u2192 (\u03b2\u2082 x)))\n\n-- notation (name := uncurry_dep) `\u21be`:max x:max := has_uncurry_dep.uncurry _ x\n\n-- instance has_uncurry_dep_base : has_uncurry_dep (\u03bb x, (\u03b2\u2081 x \u2192 \u03b2\u2082 x)) \u03b2\u2081 \u03b2\u2082 := \u27e8\u03bb x y, y\u27e9\n\n-- instance has_uncurry_dep_induction [has_uncurry_dep \u03b3 \u03b2\u2081 \u03b2\u2082] : has_uncurry_dep (\u03bb x, \u03b4 x \u2192 \u03b3 x) (\u03bb x, \u03b4 x \u00d7 \u03b2\u2081 x) \u03b2\u2082 :=\n-- \u27e8\u03bb x f p, \u21be(f p.1) p.2\u27e9\n\n-- end function\n\n-- open_locale complexity_class\n-- open function tencodable\n\n-- namespace complexity_class\n\n-- variables {\u03b1 : Type} {\u03b2 : \u03b1 \u2192 Type} {\u03b2\u2081 : \u03b1 \u2192 Type} {\u03b2\u2082 : \u03b1 \u2192 Type} {\u03b3 \u03b4 : Type}\n--   [tencodable \u03b1] [\u2200 x, tencodable (\u03b2 x)] [\u2200 x, tencodable (\u03b2\u2081 x)] [\u2200 x, tencodable (\u03b2\u2082 x)]\n--   [tencodable \u03b3] [tencodable \u03b4] {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\u2082`?\n--   Can we and should we use has_uncurry_dep so that `mem_dep\u2082` is automatically\n--   generalized for >2 arguments?\n  \n--   Should we generate composition lemmas for `mem_dep` and `mem_dep\u2082`? If so, what are they?  -/\n-- def mem_dep (f : \u2200 x, \u03b2 x) (C : complexity_class) : Prop :=\n-- \u2203 (f' : tree unit \u2192 tree unit), f' \u2208\u2091 C \u2227\n--   \u2200 x : \u03b1, f' (encode x) = encode (f x)\n\n-- localized \"infix ` \u2208\u2090 `:50 := complexity_class.mem_dep\" in complexity_class\n\n-- /-- `fintype` but \"C\"-constructible -/\n-- def mem_types (\u03b2 : \u03b1 \u2192 Type) [\u2200 x, tencodable (\u03b2 x)] [\u2200 x, decidable_eq (\u03b2 x)]\n--   [\u2200 x, fintype (\u03b2 x)] (C : complexity_class) : Prop :=\n-- (\u03bb x : \u03b1, @finset.univ (\u03b2 x) _) \u2208\u2090 C\n\n-- def mem_dep\u2082 (f : \u2200 x, \u03b2\u2081 x \u2192 \u03b2\u2082 x) (C : complexity_class) : Prop :=\n-- (\u03bb x : sigma \u03b2\u2081, f x.1 x.2) \u2208\u2090 C\n\n-- -- \"t\" for \"two\" ??\n-- localized \"infix ` \u2208\u209c `:50 := complexity_class.mem_dep\u2082\" in complexity_class\n-- open_locale tree\n\n-- @[simp] lemma mem_dep_iff {f : \u03b1 \u2192 \u03b3} : f \u2208\u2090 C \u2194 f \u2208\u2091 C :=\n-- by { simp_rw [mem_dep, \u2190 prop_iff_mem], refl, }\n\n-- lemma mem_dep\u2082_iff {f : \u03b1 \u2192 \u03b3 \u2192 \u03b4} : f \u2208\u209c C \u2194 f \u2208\u2091 C :=\n-- by { dunfold mem_dep\u2082, rw mem_dep_iff, split; { rintro \u27e8f', pf, hf\u27e9, refine \u27e8f', pf, _\u27e9, rintro \u27e8a, b\u27e9, exact hf \u27e8a, b\u27e9, }, }\n\n-- @[complexity] lemma mem_dep_of_mem {f : \u03b1 \u2192 \u03b3} (h : f \u2208\u2091 C) : f \u2208\u2090 C := by rwa mem_dep_iff\n-- @[complexity] lemma mem_dep\u2082_of_mem {f : \u03b1 \u2192 \u03b3 \u2192 \u03b4} (h : f \u2208\u2091 C) : f \u2208\u209c C := by rwa mem_dep\u2082_iff \n\n-- lemma mem_iff_comp_encode_dep {f : \u2200 x, \u03b2 x} :\n--   f \u2208\u2090 C \u2194 (\u03bb x, encode (f x)) \u2208\u2091 C :=\n-- by { rw \u2190 mem_dep_iff, refl, }\n\n-- lemma _root_.list.encode_map_encode (l : list \u03b1) :\n--   encode (l.map encode) = encode l := by simp only [encode, list.map_id]\n\n-- lemma mem_iff_comp_list_encode_dep {f : \u2200 x, list (\u03b2 x)} :\n--   f \u2208\u2090 C \u2194 (\u03bb x, (f x).map encode) \u2208\u2091 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 (\u03b1 \u03b2 : Type*) :=\n-- (to_fun : \u03b1 \u2192 \u03b2)\n\n-- namespace complexity_class.table_fun\n-- open_locale complexity_class\n-- variables {\u03b1 \u03b2 \u03b3 : Type*}\n\n-- localized \"infixr ` [\u2192] `:25 := complexity_class.table_fun\" in complexity_class\n\n-- instance : has_coe_to_fun (\u03b1 [\u2192] \u03b2) (\u03bb _, \u03b1 \u2192 \u03b2) := \u27e8table_fun.to_fun\u27e9\n\n-- @[ext]\n-- protected lemma ext : \u2200 (f g : \u03b1 [\u2192] \u03b2), \u21d1f = (by exact \u21d1g) \u2192 f = g\n-- | \u27e8f\u27e9 \u27e8g\u27e9 rfl := rfl\n\n-- @[simp] lemma to_fun_eq_coe (f : \u03b1 [\u2192] \u03b2) : f.to_fun = \u21d1f := rfl\n\n-- @[simps]\n-- def equiv_fun : (\u03b1 [\u2192] \u03b2) \u2243 (\u03b1 \u2192 \u03b2) := \u27e8\u03bb f, \u21d1f, \u03bb f, \u27e8f\u27e9, \u03bb f, by ext; refl, \u03bb f, rfl\u27e9\n\n-- @[simps]\n-- def sum (f : \u03b1 [\u2192] \u03b3) (g : \u03b2 [\u2192] \u03b3) : \u03b1 \u2295 \u03b2 [\u2192] \u03b3 := \u27e8sum.elim \u21d1f \u21d1g\u27e9\n\n-- @[simps]\n-- def map (f : \u03b1 [\u2192] \u03b2) (g : \u03b2 \u2192 \u03b3) : \u03b1 [\u2192] \u03b3 := \u27e8\u03bb x, g (f x)\u27e9\n\n-- @[simps]\n-- def comp (f : \u03b1 [\u2192] \u03b2) (g : \u03b3 [\u2192] \u03b1) : \u03b3 [\u2192] \u03b2 := \u27e8\u03bb x, f (g x)\u27e9\n\n-- def finmap_equiv_fun [fintype \u03b1] [decidable_eq \u03b1] :\n--   {x : @finmap \u03b1 (\u03bb _, \u03b2) // \u2200 k : \u03b1, k \u2208 x} \u2243 (\u03b1 \u2192 \u03b2) :=\n-- { to_fun := \u03bb f x, @option.get _ ((\u2191f : finmap _).lookup x) (finmap.lookup_is_some.mpr $ f.prop x),\n--   inv_fun := \u03bb f, \u27e8finmap.of_fun f, \u03bb k, finmap.mem_iff.mpr \u27e8_, finmap.of_fun_lookup k\u27e9\u27e9,\n--   left_inv := \u03bb f, by { ext : 1, apply finmap.ext_lookup, simp, },\n--   right_inv := \u03bb f, by { ext, simp, } } \n\n-- variables [tencodable \u03b1] [fintype \u03b1] [decidable_eq \u03b1] [tencodable \u03b2] [tencodable \u03b3]\n\n-- instance : tencodable (\u03b1 [\u2192] \u03b2) :=\n-- tencodable.of_equiv _ (equiv_fun.trans finmap_equiv_fun.symm)\n\n-- lemma encode_table_fun (f : \u03b1 [\u2192] \u03b2) : encode f = encode (finmap_equiv_fun.symm \u21d1f) :=\n-- rfl\n\n-- lemma table_fun_mk_of {\u03b3 : Type} {\u03c8\u2081 \u03c8\u2082 : \u03b3 \u2192 Type} [tencodable \u03b3] [\u2200 x, tencodable (\u03c8\u2081 x)] \n--   [\u2200 x, fintype (\u03c8\u2081 x)] [\u2200 x, decidable_eq (\u03c8\u2081 x)] [\u2200 x, tencodable (\u03c8\u2082 x)] {f : \u2200 x, (\u03c8\u2081 x \u2192 \u03c8\u2082 x)}\n--   (h\u03c8 : polytime.mem_types \u03c8\u2081) (hf : f \u2208\u209c PTIME) : (\u03bb x, table_fun.mk (f x) : \u2200 x, \u03c8\u2081 x [\u2192] \u03c8\u2082 x) \u2208\u2090 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 {\u03b1 : Type} {\u03b2 : \u03b1 \u2192 Type} {\u03b2\u2081 : \u03b1 \u2192 Type} {\u03b2\u2082 : \u03b1 \u2192 Type} {\u03b3 \u03b4 : Type}\n--   [tencodable \u03b1] [\u2200 x, tencodable (\u03b2 x)] [\u2200 x, tencodable (\u03b2\u2081 x)] [\u2200 x, tencodable (\u03b2\u2082 x)]\n--   [tencodable \u03b3] [tencodable \u03b4] {C : complexity_class}\n\n-- @[complexity] lemma list_map_dep {l : \u2200 x, list (\u03b2\u2081 x)} {f : \u2200 x, \u03b2\u2081 x \u2192 \u03b2\u2082 x} (hl : l \u2208\u2090 PTIME)\n--   (hf : f \u2208\u209c PTIME) : (\u03bb x : \u03b1, (l x).map (f x) : \u2200 x, list (\u03b2\u2082 x)) \u2208\u2090 PTIME :=\n-- begin\n--   rcases hf with \u27e8f', pf, hf\u27e9,\n--   rw mem_iff_comp_list_encode_dep at \u22a2 hl,\n--   complexity using \u03bb x, ((l x).map encode).map (\u03bb y, f' (encode x \u25b3 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\u2081 l\u2082 : \u2200 x, list (\u03b2 x)} (hl\u2081 : l\u2081 \u2208\u2090 PTIME) (hl\u2082 : l\u2082 \u2208\u2090 PTIME) :\n--   (\u03bb x, (l\u2081 x) ++ (l\u2082 x)) \u2208\u2090 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 \u2192 Type v) (n : Type u \u2192 Type w) where\n  monad_lift : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 n \u03b1\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 \u2192 Type v) (n : Type u \u2192 Type w) where\n  monad_lift : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 n \u03b1\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 \u2192 Type u_2} {n : Type u_1 \u2192 Type u_3}\n    [has_monad_lift_t m n] {\u03b1 : Type u_1} : has_coe (m \u03b1) (n \u03b1) :=\n  has_coe.mk monad_lift\n\nprotected instance has_monad_lift_t_trans (m : Type u_1 \u2192 Type u_2) (n : Type u_1 \u2192 Type u_3)\n    (o : Type u_1 \u2192 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 (\u03b1 : Type u_1) (ma : m \u03b1) => has_monad_lift.monad_lift (monad_lift ma)\n\nprotected instance has_monad_lift_t_refl (m : Type u_1 \u2192 Type u_2) : has_monad_lift_t m m :=\n  has_monad_lift_t.mk fun (\u03b1 : Type u_1) => id\n\n@[simp] theorem monad_lift_refl {m : Type u \u2192 Type v} {\u03b1 : 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 \u2192 Type v) (m' : Type u \u2192 Type v) (n : Type u \u2192 Type w)\n    (n' : Type u \u2192 Type w)\n    where\n  monad_map : {\u03b1 : Type u} \u2192 ({\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1\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 \u2192 Type v) (m' : Type u \u2192 Type v) (n : Type u \u2192 Type w)\n    (n' : Type u \u2192 Type w)\n    where\n  monad_map : {\u03b1 : Type u} \u2192 ({\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) \u2192 n \u03b1 \u2192 n' \u03b1\n\nprotected instance monad_functor_t_trans (m : Type u_1 \u2192 Type u_2) (m' : Type u_1 \u2192 Type u_2)\n    (n : Type u_1 \u2192 Type u_3) (n' : Type u_1 \u2192 Type u_3) (o : Type u_1 \u2192 Type u_4)\n    (o' : Type u_1 \u2192 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 (\u03b1 : Type u_1) (f : {\u03b1 : Type u_1} \u2192 m \u03b1 \u2192 m' \u03b1) =>\n      monad_functor.monad_map fun (\u03b1 : Type u_1) => monad_map f\n\nprotected instance monad_functor_t_refl (m : Type u_1 \u2192 Type u_2) (m' : Type u_1 \u2192 Type u_2) :\n    monad_functor_t m m' m m' :=\n  monad_functor_t.mk fun (\u03b1 : Type u_1) (f : {\u03b1 : Type u_1} \u2192 m \u03b1 \u2192 m' \u03b1) => f\n\n@[simp] theorem monad_map_refl {m : Type u \u2192 Type v} {m' : Type u \u2192 Type v}\n    (f : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 m' \u03b1) {\u03b1 : 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 {\u03b1 : Type} (x : my_monad \u03b1) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n    def my_monad.run {\u03b1 : Type} (x : my_monad \u03b1) := monad_run.run x\n    ```\n    -/\nclass monad_run (out : outParam (Type u \u2192 Type v)) (m : Type u \u2192 Type v) where\n  run : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 out \u03b1\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) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.CollectMVars\nimport Lean.Meta.Coe\nimport Lean.Linter.Deprecated\nimport Lean.Elab.Config\nimport Lean.Elab.Level\nimport Lean.Elab.DeclModifiers\n\nnamespace Lean.Elab\n\nnamespace Term\n\n/-- Saved context for postponed terms and tactics to be executed. -/\nstructure SavedContext where\n  declName?  : Option Name\n  options    : Options\n  openDecls  : List OpenDecl\n  macroStack : MacroStack\n  errToSorry : Bool\n  levelNames : List Name\n\n/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/\ninductive SyntheticMVarKind where\n  /-- Use typeclass resolution to synthesize value for metavariable. -/\n  | typeClass\n  /-- Use coercion to synthesize value for the metavariable.\n  if `f?` is `some f`, we produce an application type mismatch error message.\n  Otherwise, if `header?` is `some header`, we generate the error `(header ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)`\n  Otherwise, we generate the error `(\"type mismatch\" ++ e ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)` -/\n  | coe (header? : Option String) (expectedType : Expr) (e : Expr) (f? : Option Expr)\n  /-- Use tactic to synthesize value for metavariable. -/\n  | tactic (tacticCode : Syntax) (ctx : SavedContext)\n  /-- Metavariable represents a hole whose elaboration has been postponed. -/\n  | postponed (ctx : SavedContext)\n  deriving Inhabited\n\ninstance : ToString SyntheticMVarKind where\n  toString\n    | .typeClass    => \"typeclass\"\n    | .coe ..       => \"coe\"\n    | .tactic ..    => \"tactic\"\n    | .postponed .. => \"postponed\"\n\nstructure SyntheticMVarDecl where\n  stx : Syntax\n  kind : SyntheticMVarKind\n  deriving Inhabited\n\n/--\n  We can optionally associate an error context with a metavariable (see `MVarErrorInfo`).\n  We have three different kinds of error context.\n-/\ninductive MVarErrorKind where\n  /-- Metavariable for implicit arguments. `ctx` is the parent application. -/\n  | implicitArg (ctx : Expr)\n  /-- Metavariable for explicit holes provided by the user (e.g., `_` and `?m`) -/\n  | hole\n  /-- \"Custom\", `msgData` stores the additional error messages. -/\n  | custom (msgData : MessageData)\n  deriving Inhabited\n\ninstance : ToString MVarErrorKind where\n  toString\n    | .implicitArg _   => \"implicitArg\"\n    | .hole            => \"hole\"\n    | .custom _        => \"custom\"\n\n/--\n  We can optionally associate an error context with metavariables.\n-/\nstructure MVarErrorInfo where\n  mvarId    : MVarId\n  ref       : Syntax\n  kind      : MVarErrorKind\n  argName?  : Option Name := none\n  deriving Inhabited\n\n/--\n  Nested `let rec` expressions are eagerly lifted by the elaborator.\n  We store the information necessary for performing the lifting here.\n-/\nstructure LetRecToLift where\n  ref            : Syntax\n  fvarId         : FVarId\n  attrs          : Array Attribute\n  shortDeclName  : Name\n  declName       : Name\n  lctx           : LocalContext\n  localInstances : LocalInstances\n  type           : Expr\n  val            : Expr\n  mvarId         : MVarId\n  deriving Inhabited\n\n/--\n  State of the `TermElabM` monad.\n-/\nstructure State where\n  levelNames        : List Name       := []\n  syntheticMVars    : MVarIdMap SyntheticMVarDecl := {}\n  pendingMVars      : List MVarId := {}\n  mvarErrorInfos    : MVarIdMap MVarErrorInfo := {}\n  letRecsToLift     : List LetRecToLift := []\n  deriving Inhabited\n\nend Term\n\nnamespace Tactic\n\n/--\n  State of the `TacticM` monad.\n-/\nstructure State where\n  goals : List MVarId\n  deriving Inhabited\n\n/--\n  Snapshots are used to implement the `save` tactic.\n  This tactic caches the state of the system, and allows us to \"replay\"\n  expensive proofs efficiently. This is only relevant implementing the\n  LSP server.\n-/\nstructure Snapshot where\n  core   : Core.State\n  meta   : Meta.State\n  term   : Term.State\n  tactic : Tactic.State\n  stx    : Syntax\n\n/--\n  Key for the cache used to implement the `save` tactic.\n-/\nstructure CacheKey where\n  mvarId : MVarId -- TODO: should include all goals\n  pos    : String.Pos\n  deriving BEq, Hashable, Inhabited\n\n/--\n  Cache for the `save` tactic.\n-/\nstructure Cache where\n   pre  : PHashMap CacheKey Snapshot := {}\n   post : PHashMap CacheKey Snapshot := {}\n   deriving Inhabited\n\nend Tactic\n\nnamespace Term\n\nstructure Context where\n  declName? : Option Name := none\n  /--\n    Map `.auxDecl` local declarations used to encode recursive declarations to their full-names.\n  -/\n  auxDeclToFullName : FVarIdMap Name  := {}\n  macroStack        : MacroStack      := []\n  /--\n     When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.\n     The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in\n     the list of pending synthetic metavariables, and returns `?m`. -/\n  mayPostpone : Bool := true\n  /--\n     When `errToSorry` is set to true, the method `elabTerm` catches\n     exceptions and converts them into synthetic `sorry`s.\n     The implementation of choice nodes and overloaded symbols rely on the fact\n     that when `errToSorry` is set to false for an elaboration function `F`, then\n     `errToSorry` remains `false` for all elaboration functions invoked by `F`.\n     That is, it is safe to transition `errToSorry` from `true` to `false`, but\n     we must not set `errToSorry` to `true` when it is currently set to `false`. -/\n  errToSorry : Bool := true\n  /--\n     When `autoBoundImplicit` is set to true, instead of producing\n     an \"unknown identifier\" error for unbound variables, we generate an\n     internal exception. This exception is caught at `elabBinders` and\n     `elabTypeWithUnboldImplicit`. Both methods add implicit declarations\n     for the unbound variable and try again. -/\n  autoBoundImplicit  : Bool            := false\n  autoBoundImplicits : PArray Expr := {}\n  /--\n    A name `n` is only eligible to be an auto implicit name if `autoBoundImplicitForbidden n = false`.\n    We use this predicate to disallow `f` to be considered an auto implicit name in a definition such\n    as\n    ```\n    def f : f \u2192 Bool := fun _ => true\n    ```\n  -/\n  autoBoundImplicitForbidden : Name \u2192 Bool := fun _ => false\n  /-- Map from user name to internal unique name -/\n  sectionVars        : NameMap Name    := {}\n  /-- Map from internal name to fvar -/\n  sectionFVars       : NameMap Expr    := {}\n  /-- Enable/disable implicit lambdas feature. -/\n  implicitLambda     : Bool            := true\n  /-- Noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for. -/\n  isNoncomputableSection : Bool        := false\n  /-- When `true` we skip TC failures. We use this option when processing patterns. -/\n  ignoreTCFailures : Bool := false\n  /-- `true` when elaborating patterns. It affects how we elaborate named holes. -/\n  inPattern        : Bool := false\n  /-- Cache for the `save` tactic. It is only `some` in the LSP server. -/\n  tacticCache?     : Option (IO.Ref Tactic.Cache) := none\n  /--\n  If `true`, we store in the `Expr` the `Syntax` for recursive applications (i.e., applications\n  of free variables tagged with `isAuxDecl`). We store the `Syntax` using `mkRecAppWithSyntax`.\n  We use the `Syntax` object to produce better error messages at `Structural.lean` and `WF.lean`. -/\n  saveRecAppSyntax : Bool := true\n  /--\n  If `holesAsSyntheticOpaque` is `true`, then we mark metavariables associated\n  with `_`s as `synthethicOpaque` if they do not occur in patterns.\n  This option is useful when elaborating terms in tactics such as `refine'` where\n  we want holes there to become new goals. See issue #1681, we have\n  `refine' (fun x => _)\n  -/\n  holesAsSyntheticOpaque : Bool := false\n\nabbrev TermElabM := ReaderT Context $ StateRefT State MetaM\nabbrev TermElab  := Syntax \u2192 Option Expr \u2192 TermElabM Expr\n\n/-\nMake the compiler generate specialized `pure`/`bind` so we do not have to optimize through the\nwhole monad stack at every use site. May eventually be covered by `deriving`.\n-/\n@[always_inline]\ninstance : Monad TermElabM :=\n  let i := inferInstanceAs (Monad TermElabM)\n  { pure := i.pure, bind := i.bind }\n\nopen Meta\n\ninstance : Inhabited (TermElabM \u03b1) where\n  default := throw default\n\n/--\n  Backtrackable state for the `TermElabM` monad.\n-/\nstructure SavedState where\n  meta   : Meta.SavedState\n  \u00abelab\u00bb : State\n  deriving Nonempty\n\nprotected def saveState : TermElabM SavedState :=\n  return { meta := (\u2190 Meta.saveState), \u00abelab\u00bb := (\u2190 get) }\n\ndef SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do\n  let traceState \u2190 getTraceState -- We never backtrack trace message\n  let infoState \u2190 getInfoState -- We also do not backtrack the info nodes when `restoreInfo == false`\n  s.meta.restore\n  set s.elab\n  setTraceState traceState\n  unless restoreInfo do\n    setInfoState infoState\n\ninstance : MonadBacktrack SavedState TermElabM where\n  saveState      := Term.saveState\n  restoreState b := b.restore\n\nabbrev TermElabResult (\u03b1 : Type) := EStateM.Result Exception SavedState \u03b1\n\n/--\n  Execute `x`, save resulting expression and new state.\n  We remove any `Info` created by `x`.\n  The info nodes are committed when we execute `applyResult`.\n  We use `observing` to implement overloaded notation and decls.\n  We want to save `Info` nodes for the chosen alternative.\n-/\ndef observing (x : TermElabM \u03b1) : TermElabM (TermElabResult \u03b1) := do\n  let s \u2190 saveState\n  try\n    let e \u2190 x\n    let sNew \u2190 saveState\n    s.restore (restoreInfo := true)\n    return EStateM.Result.ok e sNew\n  catch\n    | ex@(.error ..) =>\n      let sNew \u2190 saveState\n      s.restore (restoreInfo := true)\n      return .error ex sNew\n    | ex@(.internal id _) =>\n      if id == postponeExceptionId then\n        s.restore (restoreInfo := true)\n      throw ex\n\n/--\n  Apply the result/exception and state captured with `observing`.\n  We use this method to implement overloaded notation and symbols. -/\ndef applyResult (result : TermElabResult \u03b1) : TermElabM \u03b1 := do\n  match result with\n  | .ok a r     => r.restore (restoreInfo := true); return a\n  | .error ex r => r.restore (restoreInfo := true); throw ex\n\n/--\n  Execute `x`, but keep state modifications only if `x` did not postpone.\n  This method is useful to implement elaboration functions that cannot decide whether\n  they need to postpone or not without updating the state. -/\ndef commitIfDidNotPostpone (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  -- We just reuse the implementation of `observing` and `applyResult`.\n  let r \u2190 observing x\n  applyResult r\n\n/--\n  Return the universe level names explicitly provided by the user.\n-/\ndef getLevelNames : TermElabM (List Name) :=\n  return (\u2190 get).levelNames\n\n/--\n  Given a free variable `fvar`, return its declaration.\n  This function panics if `fvar` is not a free variable.\n-/\ndef getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do\n  match (\u2190 getLCtx).find? fvar.fvarId! with\n  | some d => pure d\n  | none   => unreachable!\n\ninstance : AddErrorMessageContext TermElabM where\n  add ref msg := do\n    let ctx \u2190 read\n    let ref := getBetterRef ref ctx.macroStack\n    let msg \u2190 addMessageContext msg\n    let msg \u2190 addMacroStack msg ctx.macroStack\n    pure (ref, msg)\n\n/--\n  Execute `x` but discard changes performed at `Term.State` and `Meta.State`.\n  Recall that the `Environment` and `InfoState` are at `Core.State`. Thus, any updates to it will\n  be preserved. This method is useful for performing computations where all\n  metavariable must be resolved or discarded.\n  The `InfoTree`s are not discarded, however, and wrapped in `InfoTree.Context`\n  to store their metavariable context. -/\ndef withoutModifyingElabMetaStateWithInfo (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let s \u2190 get\n  let sMeta \u2190 getThe Meta.State\n  try\n    withSaveInfoContext x\n  finally\n    set s\n    set sMeta\n\n/--\n  Execute `x` but discard changes performed to the state.\n  However, the info trees and messages are not discarded. -/\nprivate def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let saved \u2190 saveState\n  try\n    withSaveInfoContext x\n  finally\n    let saved := { saved with meta.core.infoState := (\u2190 getInfoState), meta.core.messages := (\u2190 getThe Core.State).messages }\n    restoreState saved\n\n/--\n  Execute `x` without storing `Syntax` for recursive applications. See `saveRecAppSyntax` field at `Context`.\n-/\ndef withoutSavingRecAppSyntax (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with saveRecAppSyntax := false }) x\n\nunsafe def mkTermElabAttributeUnsafe (ref : Name) : IO (KeyedDeclsAttribute TermElab) :=\n  mkElabAttribute TermElab `builtin_term_elab `term_elab `Lean.Parser.Term `Lean.Elab.Term.TermElab \"term\" ref\n\n@[implemented_by mkTermElabAttributeUnsafe]\nopaque mkTermElabAttribute (ref : Name) : IO (KeyedDeclsAttribute TermElab)\n\nbuiltin_initialize termElabAttribute : KeyedDeclsAttribute TermElab \u2190 mkTermElabAttribute decl_name%\n\n/--\n  Auxiliary datatype for presenting a Lean lvalue modifier.\n  We represent an unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.\n  Example: `a.foo.1` is represented as the `Syntax` `a` and the list\n  `[LVal.fieldName \"foo\", LVal.fieldIdx 1]`.\n-/\ninductive LVal where\n  | fieldIdx  (ref : Syntax) (i : Nat)\n  /-- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierarchical/composite name.\n  `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/\n  | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)\n\ndef LVal.getRef : LVal \u2192 Syntax\n  | .fieldIdx ref _    => ref\n  | .fieldName ref ..  => ref\n\ndef LVal.isFieldName : LVal \u2192 Bool\n  | .fieldName .. => true\n  | _ => false\n\ninstance : ToString LVal where\n  toString\n    | .fieldIdx _ i     => toString i\n    | .fieldName _ n .. => n\n\n/-- Return the name of the declaration being elaborated if available. -/\ndef getDeclName? : TermElabM (Option Name) := return (\u2190 read).declName?\n/-- Return the list of nested `let rec` declarations that need to be lifted. -/\ndef getLetRecsToLift : TermElabM (List LetRecToLift) := return (\u2190 get).letRecsToLift\n/-- Return the declaration of the given metavariable -/\ndef getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (\u2190 getMCtx).getDecl mvarId\n\n/-- Execute `x` with `declName? := name`. See `getDeclName?`. -/\ndef withDeclName (name : Name) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with declName? := name }) x\n\n/-- Update the universe level parameter names. -/\ndef setLevelNames (levelNames : List Name) : TermElabM Unit :=\n  modify fun s => { s with levelNames := levelNames }\n\n/-- Execute `x` using `levelNames` as the universe level parameter names. See `getLevelNames`. -/\ndef withLevelNames (levelNames : List Name) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let levelNamesSaved \u2190 getLevelNames\n  setLevelNames levelNames\n  try x finally setLevelNames levelNamesSaved\n\n/--\n  Declare an auxiliary local declaration `shortDeclName : type` for elaborating recursive declaration `declName`,\n  update the mapping `auxDeclToFullName`, and then execute `k`.\n-/\ndef withAuxDecl (shortDeclName : Name) (type : Expr) (declName : Name) (k : Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  withLocalDecl shortDeclName .default (kind := .auxDecl) type fun x =>\n    withReader (fun ctx => { ctx with auxDeclToFullName := ctx.auxDeclToFullName.insert x.fvarId! declName }) do\n      k x\n\ndef withoutErrToSorryImp (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with errToSorry := false }) x\n\n/--\n  Execute `x` without converting errors (i.e., exceptions) to `sorry` applications.\n  Recall that when `errToSorry = true`, the method `elabTerm` catches exceptions and converts them into `sorry` applications.\n-/\ndef withoutErrToSorry [MonadFunctorT TermElabM m] : m \u03b1 \u2192 m \u03b1 :=\n  monadMap (m := TermElabM) withoutErrToSorryImp\n\n/-- For testing `TermElabM` methods. The #eval command will sign the error. -/\ndef throwErrorIfErrors : TermElabM Unit := do\n  if (\u2190 MonadLog.hasErrors) then\n    throwError \"Error(s)\"\n\ndef traceAtCmdPos (cls : Name) (msg : Unit \u2192 MessageData) : TermElabM Unit :=\n  withRef Syntax.missing <| trace cls msg\n\ndef ppGoal (mvarId : MVarId) : TermElabM Format :=\n  Meta.ppGoal mvarId\n\nopen Level (LevelElabM)\n\ndef liftLevelM (x : LevelElabM \u03b1) : TermElabM \u03b1 := do\n  let ctx \u2190 read\n  let mctx \u2190 getMCtx\n  let ngen \u2190 getNGen\n  let lvlCtx : Level.Context := { options := (\u2190 getOptions), ref := (\u2190 getRef), autoBoundImplicit := ctx.autoBoundImplicit }\n  match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (\u2190 getLevelNames) } with\n  | .ok a newS  => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a\n  | .error ex _ => throw ex\n\ndef elabLevel (stx : Syntax) : TermElabM Level :=\n  liftLevelM <| Level.elabLevel stx\n\n/-- Elaborate `x` with `stx` on the macro stack -/\ndef withPushMacroExpansionStack (beforeStx afterStx : Syntax) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x\n\n/-- Elaborate `x` with `stx` on the macro stack and produce macro expansion info -/\ndef withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withMacroExpansionInfo beforeStx afterStx do\n    withPushMacroExpansionStack beforeStx afterStx x\n\n/--\n  Add the given metavariable to the list of pending synthetic metavariables.\n  The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/\ndef registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  modify fun s => { s with syntheticMVars := s.syntheticMVars.insert mvarId { stx, kind }, pendingMVars := mvarId :: s.pendingMVars }\n\ndef registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  registerSyntheticMVar (\u2190 getRef) mvarId kind\n\ndef registerMVarErrorInfo (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit :=\n  modify fun s => { s with mvarErrorInfos := s.mvarErrorInfos.insert mvarErrorInfo.mvarId mvarErrorInfo }\n\ndef registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit :=\n  registerMVarErrorInfo { mvarId, ref, kind := .hole }\n\ndef registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do\n  registerMVarErrorInfo { mvarId, ref, kind := .implicitArg app }\n\ndef registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do\n  registerMVarErrorInfo { mvarId, ref, kind := .custom msgData }\n\ndef getMVarErrorInfo? (mvarId : MVarId) : TermElabM (Option MVarErrorInfo) := do\n  return (\u2190 get).mvarErrorInfos.find? mvarId\n\ndef registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=\n  match e.getAppFn with\n  | Expr.mvar mvarId => registerMVarErrorCustomInfo mvarId ref msgData\n  | _ => pure ()\n\n/--\n  Auxiliary method for reporting errors of the form \"... contains metavariables ...\".\n  This kind of error is thrown, for example, at `Match.lean` where elaboration\n  cannot continue if there are metavariables in patterns.\n  We only want to log it if we haven't logged any errors so far. -/\ndef throwMVarError (m : MessageData) : TermElabM \u03b1 := do\n  if (\u2190 MonadLog.hasErrors) then\n    throwAbortTerm\n  else\n    throwError m\n\ndef MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do\n  match mvarErrorInfo.kind with\n  | MVarErrorKind.implicitArg app => do\n    let app \u2190 instantiateMVars app\n    let msg := addArgName \"don't know how to synthesize implicit argument\"\n    let msg := msg ++ m!\"{indentExpr app.setAppPPExplicitForExposingMVars}\" ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\n  | MVarErrorKind.hole => do\n    let msg := addArgName \"don't know how to synthesize placeholder\" \" for argument\"\n    let msg := msg ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)\n  | MVarErrorKind.custom msg =>\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\nwhere\n  /-- Append `mvarErrorInfo` argument name (if available) to the message.\n      Remark: if the argument name contains macro scopes we do not append it. -/\n  addArgName (msg : MessageData) (extra : String := \"\") : MessageData :=\n    match mvarErrorInfo.argName? with\n    | none => msg\n    | some argName => if argName.hasMacroScopes then msg else msg ++ extra ++ m!\" '{argName}'\"\n\n  appendExtra (msg : MessageData) : MessageData :=\n    match extraMsg? with\n    | none => msg\n    | some extraMsg => msg ++ extraMsg\n\n/--\n  Try to log errors for the unassigned metavariables `pendingMVarIds`.\n\n  Return `true` if there were \"unfilled holes\", and we should \"abort\" declaration.\n  TODO: try to fill \"all\" holes using synthetic \"sorry's\"\n\n  Remark: We only log the \"unfilled holes\" as new errors if no error has been logged so far. -/\ndef logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do\n  if pendingMVarIds.isEmpty then\n    return false\n  else\n    let hasOtherErrors \u2190 MonadLog.hasErrors\n    let mut hasNewErrors := false\n    let mut alreadyVisited : MVarIdSet := {}\n    let mut errors : Array MVarErrorInfo := #[]\n    for (_, mvarErrorInfo) in (\u2190 get).mvarErrorInfos do\n      let mvarId := mvarErrorInfo.mvarId\n      unless alreadyVisited.contains mvarId do\n        alreadyVisited := alreadyVisited.insert mvarId\n        /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or\n           delayed assigned to another metavariable that is unassigned. -/\n        let mvarDeps \u2190 getMVars (mkMVar mvarId)\n        if mvarDeps.any pendingMVarIds.contains then do\n          unless hasOtherErrors do\n            errors := errors.push mvarErrorInfo\n          hasNewErrors := true\n    -- To sort the errors by position use\n    -- let sortedErrors := errors.qsort fun e\u2081 e\u2082 => e\u2081.ref.getPos?.getD 0 < e\u2082.ref.getPos?.getD 0\n    for error in errors do\n      error.mvarId.withContext do\n        error.logError extraMsg?\n    return hasNewErrors\n\n/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/\ndef ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do\n  let pendingMVarIds \u2190 getMVarsAtDecl decl\n  if (\u2190 logUnassignedUsingErrorInfos pendingMVarIds) then\n    throwAbortCommand\n\n/--\n  Execute `x` without allowing it to postpone elaboration tasks.\n  That is, `tryPostpone` is a noop. -/\ndef withoutPostponing (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with mayPostpone := false }) x\n\n/-- Creates syntax for `(` <ident> `:` <type> `)` -/\ndef mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=\n  mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom \"(\", mkNullNode #[ident], mkNullNode #[mkAtom \":\", type], mkNullNode, mkAtom \")\"]\n\n/--\n  Convert unassigned universe level metavariables into parameters.\n  The new parameter names are fresh names of the form `u_i` with regard to `ctx.levelNames`, which is updated with the new names. -/\ndef levelMVarToParam (e : Expr) (except : LMVarId \u2192 Bool := fun _ => false) : TermElabM Expr := do\n  let levelNames \u2190 getLevelNames\n  let r := (\u2190 getMCtx).levelMVarToParam (fun n => levelNames.elem n) except e `u 1\n  setLevelNames (levelNames ++ r.newParamNames.toList)\n  setMCtx r.mctx\n  return r.expr\n\n/--\n  Auxiliary method for creating fresh binder names.\n  Do not confuse with the method for creating fresh free/meta variable ids. -/\ndef mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=\n  withFreshMacroScope <| MonadQuotation.addMacroScope `x\n\n/--\n  Auxiliary method for creating a `Syntax.ident` containing\n  a fresh name. This method is intended for creating fresh binder names.\n  It is just a thin layer on top of `mkFreshUserName`. -/\ndef mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) (canonical := false) : m Ident :=\n  return mkIdentFrom ref (\u2190 mkFreshBinderName) canonical\n\nprivate def applyAttributesCore\n    (declName : Name) (attrs : Array Attribute)\n    (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := do profileitM Exception \"attribute application\" (\u2190 getOptions) do\n  for attr in attrs do\n    withRef attr.stx do withLogging do\n    let env \u2190 getEnv\n    match getAttributeImpl env attr.name with\n    | Except.error errMsg => throwError errMsg\n    | Except.ok attrImpl  =>\n      let runAttr := attrImpl.add declName attr.stx attr.kind\n      let runAttr := do\n        -- not truly an elaborator, but a sensible target for go-to-definition\n        let elaborator := attrImpl.ref\n        if (\u2190 getInfoState).enabled && (\u2190 getEnv).contains elaborator then\n          withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do\n            try runAttr\n            finally if attr.stx[0].isIdent || attr.stx[0].isAtom then\n              -- Add an additional node over the leading identifier if there is one to make it look more function-like.\n              -- Do this last because we want user-created infos to take precedence\n              pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] }\n        else\n          runAttr\n      match applicationTime? with\n      | none => runAttr\n      | some applicationTime =>\n        if applicationTime == attrImpl.applicationTime then\n          runAttr\n\n/-- Apply given attributes **at** a given application time -/\ndef applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=\n  applyAttributesCore declName attrs applicationTime\n\ndef applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=\n  applyAttributesCore declName attrs none\n\ndef mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do\n  let header : MessageData := match header? with\n    | some header => m!\"{header} \"\n    | none        => m!\"type mismatch{indentExpr e}\\n\"\n  return m!\"{header}{\u2190 mkHasTypeButIsExpectedMsg eType expectedType}\"\n\ndef throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM \u03b1 := do\n  /-\n    We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was\n    always of the form:\n    ```\n    failed to synthesize instance\n      CoeT <eType> <e> <expectedType>\n    ```\n    We should revisit this decision in the future and decide whether it may contain useful information\n    or not. -/\n  let extraMsg := Format.nil\n  /-\n  let extraMsg : MessageData := match extraMsg? with\n    | none          => Format.nil\n    | some extraMsg => Format.line ++ extraMsg;\n  -/\n  match f? with\n  | none   => throwError \"{\u2190 mkTypeMismatchError header? e eType expectedType}{extraMsg}\"\n  | some f => Meta.throwAppTypeMismatch f e\n\ndef withoutMacroStackAtErr (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x\n\nnamespace ContainsPendingMVar\n\nabbrev M := MonadCacheT Expr Unit (OptionT MetaM)\n\n/-- See `containsPostponedTerm` -/\npartial def visit (e : Expr) : M Unit := do\n  checkCache e fun _ => do\n    match e with\n    | .forallE _ d b _   => visit d; visit b\n    | .lam _ d b _       => visit d; visit b\n    | .letE _ t v b _    => visit t; visit v; visit b\n    | .app f a           => visit f; visit a\n    | .mdata _ b         => visit b\n    | .proj _ _ b        => visit b\n    | .fvar fvarId ..    =>\n      match (\u2190 fvarId.getDecl) with\n      | .cdecl .. => return ()\n      | .ldecl (value := v) .. => visit v\n    | .mvar mvarId ..    =>\n      let e' \u2190 instantiateMVars e\n      if e' != e then\n        visit e'\n      else\n        match (\u2190 getDelayedMVarAssignment? mvarId) with\n        | some d => visit (mkMVar d.mvarIdPending)\n        | none   => failure\n    | _ => return ()\n\nend ContainsPendingMVar\n\n/-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/\ndef containsPendingMVar (e : Expr) : MetaM Bool := do\n  match (\u2190 ContainsPendingMVar.visit e |>.run.run) with\n  | some _ => return false\n  | none   => return true\n\n/--\n  Try to synthesize metavariable using type class resolution.\n  This method assumes the local context and local instances of `instMVar` coincide\n  with the current local context and local instances.\n  Return `true` if the instance was synthesized successfully, and `false` if\n  the instance contains unassigned metavariables that are blocking the type class\n  resolution procedure. Throw an exception if resolution or assignment irrevocably fails.\n-/\ndef synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do\n  let instMVarDecl \u2190 getMVarDecl instMVar\n  let type := instMVarDecl.type\n  let type \u2190 instantiateMVars type\n  let result \u2190 trySynthInstance type maxResultSize?\n  match result with\n  | LOption.some val =>\n    if (\u2190 instMVar.isAssigned) then\n      let oldVal \u2190 instantiateMVars (mkMVar instMVar)\n      unless (\u2190 isDefEq oldVal val) do\n        if (\u2190 containsPendingMVar oldVal <||> containsPendingMVar val) then\n          /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration),\n             we return `false` to indicate we should try again later. This is very coarse grain since\n             the metavariable may not be responsible for the failure. We should refine the test in the future if needed.\n             This check has been added to address dependencies between postponed metavariables. The following\n             example demonstrates the issue fixed by this test.\n             ```\n               structure Point where\n                 x : Nat\n                 y : Nat\n\n               def Point.compute (p : Point) : Point :=\n                 let p := { p with x := 1 }\n                 let p := { p with y := 0 }\n                 if (p.x - p.y) > p.x then p else p\n             ```\n             The `isDefEq` test above fails for `Decidable (p.x - p.y \u2264 p.x)` when the structure instance assigned to\n             `p` has not been elaborated yet.\n           -/\n          return false -- we will try again later\n        let oldValType \u2190 inferType oldVal\n        let valType \u2190 inferType val\n        unless (\u2190 isDefEq oldValType valType) do\n          throwError \"synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\\nhas type{indentExpr valType}\\nexpected{indentExpr oldValType}\"\n        throwError \"synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\\ninferred{indentExpr oldVal}\"\n    else\n      unless (\u2190 isDefEq (mkMVar instMVar) val) do\n        throwError \"failed to assign synthesized type class instance{indentExpr val}\"\n    return true\n  | .undef => return false -- we will try later\n  | .none  =>\n    if (\u2190 read).ignoreTCFailures then\n      return false\n    else\n      throwError \"failed to synthesize instance{indentExpr type}\"\n\ndef mkCoe (expectedType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  trace[Elab.coe] \"adding coercion for {e} : {\u2190 inferType e} =?= {expectedType}\"\n  try\n    withoutMacroStackAtErr do\n      match \u2190 coerce? e expectedType with\n      | .some eNew => return eNew\n      | .none => failure\n      | .undef =>\n        let mvarAux \u2190 mkFreshExprMVar expectedType MetavarKind.syntheticOpaque\n        registerSyntheticMVarWithCurrRef mvarAux.mvarId! (.coe errorMsgHeader? expectedType e f?)\n        return mvarAux\n  catch\n    | .error _ msg => throwTypeMismatchError errorMsgHeader? expectedType (\u2190 inferType e) e f? msg\n    | _            => throwTypeMismatchError errorMsgHeader? expectedType (\u2190 inferType e) e f?\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.\n  If they are not, then try coercions.\n\n  Argument `f?` is used only for generating error messages. -/\ndef ensureHasType (expectedType? : Option Expr) (e : Expr)\n    (errorMsgHeader? : Option String := none) (f? : Option Expr := none) : TermElabM Expr := do\n  let some expectedType := expectedType? | return e\n  if (\u2190 isDefEq (\u2190 inferType e) expectedType) then\n    return e\n  else\n    mkCoe expectedType e f? errorMsgHeader?\n\n/--\n  Create a synthetic sorry for the given expected type. If `expectedType? = none`, then a fresh\n  metavariable is created to represent the type.\n-/\nprivate def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 match expectedType? with\n    | none              => mkFreshTypeMVar\n    | some expectedType => pure expectedType\n  mkSyntheticSorry expectedType\n\n/--\n  Log the given exception, and create a synthetic sorry for representing the failed\n  elaboration step with exception `ex`.\n-/\ndef exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do\n  let syntheticSorry \u2190 mkSyntheticSorryFor expectedType?\n  logException ex\n  pure syntheticSorry\n\n/-- If `mayPostpone == true`, throw `Expection.postpone`. -/\ndef tryPostpone : TermElabM Unit := do\n  if (\u2190 read).mayPostpone then\n    throwPostpone\n\n/-- Return `true` if `e` reduces (by unfolding only `[reducible]` declarations) to `?m ...` -/\ndef isMVarApp (e : Expr) : TermElabM Bool :=\n  return (\u2190 whnfR e).getAppFn.isMVar\n\n/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/\ndef tryPostponeIfMVar (e : Expr) : TermElabM Unit := do\n  if (\u2190 isMVarApp e) then\n    tryPostpone\n\n/-- If `e? = some e`, then `tryPostponeIfMVar e`, otherwise it is just `tryPostpone`. -/\ndef tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=\n  match e? with\n  | some e => tryPostponeIfMVar e\n  | none   => tryPostpone\n\n/--\n  Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables.\n  It is a noop if `mayPostpone == false`.\n-/\ndef tryPostponeIfHasMVars? (expectedType? : Option Expr) : TermElabM (Option Expr) := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let some expectedType := expectedType? | return none\n  let expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasExprMVar then\n    tryPostpone\n    return none\n  return some expectedType\n\n/--\n  Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables.\n  If `mayPostpone == false`, it throws error `msg`.\n-/\ndef tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do\n  let some expectedType \u2190 tryPostponeIfHasMVars? expectedType? |\n    throwError \"{msg}, expected type contains metavariables{indentD expectedType?}\"\n  return expectedType\n\n/--\n  Save relevant context for term elaboration postponement.\n-/\ndef saveContext : TermElabM SavedContext :=\n  return {\n    macroStack := (\u2190 read).macroStack\n    declName?  := (\u2190 read).declName?\n    options    := (\u2190 getOptions)\n    openDecls  := (\u2190 getOpenDecls)\n    errToSorry := (\u2190 read).errToSorry\n    levelNames := (\u2190 get).levelNames\n  }\n\n/--\n  Execute `x` with the context saved using `saveContext`.\n-/\ndef withSavedContext (savedCtx : SavedContext) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|\n    withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) <|\n      withLevelNames savedCtx.levelNames x\n\n/--\nDelay the elaboration of `stx`, and return a fresh metavariable that works a placeholder.\nRemark: the caller is responsible for making sure the info tree is properly updated.\nThis method is used only at `elabUsingElabFnsAux`.\n-/\nprivate def postponeElabTermCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  trace[Elab.postpone] \"{stx} : {expectedType?}\"\n  let mvar \u2190 mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque\n  registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (\u2190 saveContext))\n  return mvar\n\ndef getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=\n  return (\u2190 get).syntheticMVars.find? mvarId\n\n/--\n  Create an auxiliary annotation to make sure we create an `Info` even if `e` is a metavariable.\n  See `mkTermInfo`.\n\n  We use this function because some elaboration functions elaborate subterms that may not be immediately\n  part of the resulting term. Example:\n  ```\n  let_mvar% ?m := b; wait_if_type_mvar% ?m; body\n  ```\n  If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just returns a fresh\n  metavariable `?n`. The elaborator for\n  ```\n  let_mvar% ?m := b; wait_if_type_mvar% ?m; body\n  ```\n  returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are \"saved\".\n  This is a bit hackish, but elaborators like `let_mvar%` are rare.\n-/\ndef mkSaveInfoAnnotation (e : Expr) : Expr :=\n  if e.isMVar then\n    mkAnnotation `save_info e\n  else\n    e\n\ndef isSaveInfoAnnotation? (e : Expr) : Option Expr :=\n  annotation? `save_info e\n\npartial def removeSaveInfoAnnotation (e : Expr) : Expr :=\n  match isSaveInfoAnnotation? e with\n  | some e => removeSaveInfoAnnotation e\n  | _ => e\n\n/--\n  Return `some mvarId` if `e` corresponds to a hole that is going to be filled \"later\" by executing a tactic or resuming elaboration.\n\n  We do not save `ofTermInfo` for this kind of node in the `InfoTree`.\n-/\ndef isTacticOrPostponedHole? (e : Expr) : TermElabM (Option MVarId) := do\n  match e with\n  | Expr.mvar mvarId =>\n    match (\u2190 getSyntheticMVarDecl? mvarId) with\n    | some { kind := .tactic .., .. }    => return mvarId\n    | some { kind := .postponed .., .. } => return mvarId\n    | _                                  => return none\n  | _ => pure none\n\ndef mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do\n  match (\u2190 isTacticOrPostponedHole? e) with\n  | some mvarId => return Sum.inr mvarId\n  | none =>\n    let e := removeSaveInfoAnnotation e\n    return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (\u2190 getLCtx), expr := e, stx, expectedType?, isBinder }\n\n/--\nPushes a new leaf node to the info tree associating the expression `e` to the syntax `stx`.\nAs a result, when the user hovers over `stx` they will see the type of `e`, and if `e`\nis a constant they will see the constant's doc string.\n\n* `expectedType?`: the expected type of `e` at the point of elaboration, if available\n* `lctx?`: the local context in which to interpret `e` (otherwise it will use `\u2190 getLCtx`)\n* `elaborator`: a declaration name used as an alternative target for go-to-definition\n* `isBinder`: if true, this will be treated as defining `e` (which should be a local constant)\n  for the purpose of go-to-definition on local variables\n* `force`: In patterns, the effect of `addTermInfo` is usually suppressed and replaced\n  by a `patternWithRef?` annotation which will be turned into a term info on the\n  post-match-elaboration expression. This flag overrides that behavior and adds the term\n  info immediately. (See https://github.com/leanprover/lean4/pull/1664.)\n-/\ndef addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none)\n    (lctx? : Option LocalContext := none) (elaborator := Name.anonymous)\n    (isBinder := false) (force := false) : TermElabM Expr := do\n  if (\u2190 read).inPattern && !force then\n    return mkPatternWithRef e stx\n  else\n    withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard\n    return e\n\ndef addTermInfo' (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit :=\n  discard <| addTermInfo stx e expectedType? lctx? elaborator isBinder\n\ndef withInfoContext' (stx : Syntax) (x : TermElabM Expr) (mkInfo : Expr \u2192 TermElabM (Sum Info MVarId)) : TermElabM Expr := do\n  if (\u2190 read).inPattern then\n    let e \u2190 x\n    return mkPatternWithRef e stx\n  else\n    Elab.withInfoContext' x mkInfo\n\n/--\nPostpone the elaboration of `stx`, return a metavariable that acts as a placeholder, and\nensures the info tree is updated and a hole id is introduced.\nWhen `stx` is elaborated, new info nodes are created and attached to the new hole id in the info tree.\n-/\ndef postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  withInfoContext' stx (mkInfo := mkTermInfo .anonymous (expectedType? := expectedType?) stx) do\n    postponeElabTermCore stx expectedType?\n\n/--\n  Helper function for `elabTerm` that tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or\n  an error is found. -/\nprivate def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)\n    : List (KeyedDeclsAttribute.AttributeEntry TermElab) \u2192 TermElabM Expr\n  | []                => do throwError \"unexpected syntax{indentD stx}\"\n  | (elabFn::elabFns) =>\n    try\n      -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`)\n      withInfoContext' stx (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx)\n        (try\n          elabFn.value stx expectedType?\n        catch ex => match ex with\n          | .error .. =>\n            if (\u2190 read).errToSorry then\n              exceptionToSorry ex expectedType?\n            else\n              throw ex\n          | .internal id _ =>\n            if (\u2190 read).errToSorry && id == abortTermExceptionId then\n              exceptionToSorry ex expectedType?\n            else if id == unsupportedSyntaxExceptionId then\n              throw ex  -- to outer try\n            else if catchExPostpone && id == postponeExceptionId then\n              /- If `elab` threw `Exception.postpone`, we reset any state modifications.\n                For example, we want to make sure pending synthetic metavariables created by `elab` before\n                it threw `Exception.postpone` are discarded.\n                Note that we are also discarding the messages created by `elab`.\n\n                For example, consider the expression.\n                `((f.x a1).x a2).x a3`\n                Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.\n                Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`\n                because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and\n                finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would\n                keep \"dead\" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is\n                wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch\n                and new metavariables are created for the nested functions. -/\n              s.restore\n              postponeElabTermCore stx expectedType?\n            else\n              throw ex)\n    catch ex => match ex with\n      | .internal id _ =>\n        if id == unsupportedSyntaxExceptionId then\n          s.restore  -- also removes the info tree created above\n          elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n        else\n          throw ex\n      | _ => throw ex\n\nprivate def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do\n  let s \u2190 saveState\n  let k := stx.getKind\n  match termElabAttribute.getEntries (\u2190 getEnv) k with\n  | []      => throwError \"elaboration function for '{k}' has not been implemented{indentD stx}\"\n  | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n\ninstance : MonadMacroAdapter TermElabM where\n  getCurrMacroScope := getCurrMacroScope\n  getNextMacroScope := return (\u2190 getThe Core.State).nextMacroScope\n  setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }\n\nprivate def isExplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(@$_) => true\n  | _      => false\n\nprivate def isExplicitApp (stx : Syntax) : Bool :=\n  stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]\n\n/--\n  Return true if `stx` is a lambda abstraction containing a `{}` or `[]` binder annotation.\n  Example: `fun {\u03b1} (a : \u03b1) => a` -/\nprivate def isLambdaWithImplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(fun $binders* => $_) => binders.raw.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder\n  | _                      => false\n\nprivate partial def dropTermParens : Syntax \u2192 Syntax := fun stx =>\n  match stx with\n  | `(($stx)) => dropTermParens stx\n  | _         => stx\n\nprivate def isHole (stx : Syntax) : Bool :=\n  match stx with\n  | `(_)          => true\n  | `(? _)        => true\n  | `(? $_:ident) => true\n  | _             => false\n\nprivate def isTacticBlock (stx : Syntax) : Bool :=\n  match stx with\n  | `(by $_:tacticSeq) => true\n  | _ => false\n\nprivate def isNoImplicitLambda (stx : Syntax) : Bool :=\n  match stx with\n  | `(no_implicit_lambda% $_:term) => true\n  | _ => false\n\nprivate def isTypeAscription (stx : Syntax) : Bool :=\n  match stx with\n  | `(($_ : $_)) => true\n  | _            => false\n\ndef hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=\n  annotation? `noImplicitLambda type |>.isSome\n\ndef mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=\n  if hasNoImplicitLambdaAnnotation type then\n    type\n  else\n    mkAnnotation `noImplicitLambda type\n\n/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/\ndef blockImplicitLambda (stx : Syntax) : Bool :=\n  let stx := dropTermParens stx\n  -- TODO: make it extensible\n  isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||\n  isNoImplicitLambda stx || isTypeAscription stx\n\ndef resolveLocalName (n : Name) : TermElabM (Option (Expr \u00d7 List String)) := do\n  let lctx \u2190 getLCtx\n  let auxDeclToFullName := (\u2190 read).auxDeclToFullName\n  let currNamespace \u2190 getCurrNamespace\n  let view := extractMacroScopes n\n  /- Simple case. \"Match\" function for regular local declarations. -/\n  let matchLocalDecl? (localDecl : LocalDecl) (givenName : Name) : Option LocalDecl := do\n    guard (localDecl.userName == givenName)\n    return localDecl\n  /-\n  \"Match\" function for auxiliary declarations that correspond to recursive definitions being defined.\n  This function is used in the first-pass.\n  Note that we do not check for `localDecl.userName == givenName` in this pass as we do for regular local declarations.\n  Reason: consider the following example\n  ```\n    mutual\n      inductive Foo\n      | somefoo : Foo | bar : Bar \u2192 Foo \u2192 Foo\n      inductive Bar\n      | somebar : Bar| foobar : Foo \u2192 Bar \u2192 Bar\n    end\n\n    mutual\n      private def Foo.toString : Foo \u2192 String\n        | Foo.somefoo => go 2 ++ toString.go 2 ++ Foo.toString.go 2\n        | Foo.bar b f => toString f ++ Bar.toString b\n      where\n        go (x : Nat) := s!\"foo {x}\"\n\n      private def _root_.Ex2.Bar.toString : Bar \u2192 String\n        | Bar.somebar => \"bar\"\n        | Bar.foobar f b => Foo.toString f ++ Bar.toString b\n    end\n  ```\n  In the example above, we have two local declarations named `toString` in the local context, and\n  we want the `toString f` to be resolved to `Foo.toString f`.\n  -/\n  let matchAuxRecDecl? (localDecl : LocalDecl) (fullDeclName : Name) (givenNameView : MacroScopesView) : Option LocalDecl := do\n    let fullDeclView := extractMacroScopes fullDeclName\n    /- First cleanup private name annotations -/\n    let fullDeclView := { fullDeclView with name := (privateToUserName? fullDeclView.name).getD fullDeclView.name }\n    let fullDeclName := fullDeclView.review\n    let localDeclNameView := extractMacroScopes localDecl.userName\n    /- If the current namespace is a prefix of the full declaration name,\n       we use a relaxed matching test where we must satisfy the following conditions\n       - The local declaration is a suffix of the given name.\n       - The given name is a suffix of the full declaration.\n\n       Recall the `let rec`/`where` declaration naming convention. For example, suppose we have\n       ```\n       def Foo.Bla.f ... :=\n         ... go ...\n       where\n          go ... := ...\n       ```\n       The current namespace is `Foo.Bla`, and the full name for `go` is `Foo.Bla.f.g`, but we want to\n       refer to it using just `go`. It is also accepted to refer to it using `f.go`, `Bla.f.go`, etc.\n\n    -/\n    if currNamespace.isPrefixOf fullDeclName then\n      /- Relaxed mode that allows us to access `let rec` declarations using shorter names -/\n      guard (localDeclNameView.isSuffixOf givenNameView)\n      guard (givenNameView.isSuffixOf fullDeclView)\n      return localDecl\n    else\n      /-\n         It is the standard algorithm we are using at `resolveGlobalName` for processing namespaces.\n\n         The current solution also has a limitation when using `def _root_` in a mutual block.\n         The non `def _root_` declarations may update the namespace. See the following example:\n         ```\n         mutual\n           def Foo.f ... := ...\n           def _root_.g ... := ...\n             let rec h := ...\n             ...\n         end\n         ```\n         `def Foo.f` updates the namespace. Then, even when processing `def _root_.g ...`\n         the condition `currNamespace.isPrefixOf fullDeclName` does not hold.\n         This is not a big problem because we are planning to modify how we handle the mutual block in the future.\n\n         Note that we don't check for `localDecl.userName == givenName` here.\n      -/\n      let rec go (ns : Name) : Option LocalDecl := do\n        if { givenNameView with name := ns ++ givenNameView.name }.review == fullDeclName then\n          return localDecl\n        match ns with\n        | .str pre .. => go pre\n        | _ => failure\n      return (\u2190 go currNamespace)\n  /- Traverse the local context backwards looking for match `givenNameView`.\n     If `skipAuxDecl` we ignore `auxDecl` local declarations. -/\n  let findLocalDecl? (givenNameView : MacroScopesView) (skipAuxDecl : Bool) : Option LocalDecl :=\n    let givenName := givenNameView.review\n    let localDecl? := lctx.decls.findSomeRev? fun localDecl? => do\n      let localDecl \u2190 localDecl?\n      if localDecl.isAuxDecl then\n        guard (not skipAuxDecl)\n        if let some fullDeclName := auxDeclToFullName.find? localDecl.fvarId then\n          matchAuxRecDecl? localDecl fullDeclName givenNameView\n        else\n          matchLocalDecl? localDecl givenName\n      else\n        matchLocalDecl? localDecl givenName\n    if localDecl?.isSome || skipAuxDecl then\n      localDecl?\n    else\n      -- Search auxDecls again trying an exact match of the given name\n      lctx.decls.findSomeRev? fun localDecl? => do\n        let localDecl \u2190 localDecl?\n        guard localDecl.isAuxDecl\n        matchLocalDecl? localDecl givenName\n  /-\n  We use the parameter `globalDeclFound` to decide whether we should skip auxiliary declarations or not.\n  We set it to true if we found a global declaration `n` as we iterate over the `loop`.\n  Without this workaround, we would not be able to elaborate an example such as\n  ```\n  def foo.aux := 1\n  def foo : Nat \u2192 Nat\n    | n => foo.aux -- should not be interpreted as `(foo).bar`\n  ```\n  See test `aStructPerfIssue.lean` for another example.\n  We skip auxiliary declarations when `projs` is not empty and `globalDeclFound` is true.\n  Remark: we did not use to have the `globalDeclFound` parameter. Without this extra check we failed\n  to elaborate\n  ```\n  example : Nat :=\n    let n := 0\n    n.succ + (m |>.succ) + m.succ\n  where\n    m := 1\n  ```\n  See issue #1850.\n  -/\n  let rec loop (n : Name) (projs : List String) (globalDeclFound : Bool) := do\n    let givenNameView := { view with name := n }\n    let mut globalDeclFound := globalDeclFound\n    unless globalDeclFound do\n      let r \u2190 resolveGlobalName givenNameView.review\n      let r := r.filter fun (_, fieldList) => fieldList.isEmpty\n      unless r.isEmpty do\n        globalDeclFound := true\n    match findLocalDecl? givenNameView (skipAuxDecl := globalDeclFound && not projs.isEmpty) with\n    | some decl => return some (decl.toExpr, projs)\n    | none => match n with\n      | .str pre s => loop pre (s::projs) globalDeclFound\n      | _ => return none\n  loop view.name [] (globalDeclFound := false)\n\n/-- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/\ndef isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val _ => do\n    let r? \u2190 resolveLocalName val\n    match r? with\n    | some (fvar, []) => return some fvar\n    | _               => return none\n  | _ => return none\n\ninductive UseImplicitLambdaResult where\n  | no\n  | yes (expectedType : Expr)\n  | postpone\n\n/--\n  Return normalized expected type if it is of the form `{a : \u03b1} \u2192 \u03b2` or `[a : \u03b1] \u2192 \u03b2` and\n  `blockImplicitLambda stx` is not true, else return `none`.\n\n  Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : \u03b1}} \u2192 \u03b2`\n-/\nprivate def useImplicitLambda (stx : Syntax) (expectedType? : Option Expr) : TermElabM UseImplicitLambdaResult := do\n  if blockImplicitLambda stx then\n    return .no\n  let some expectedType := expectedType? | return .no\n  if hasNoImplicitLambdaAnnotation expectedType then\n    return .no\n  let expectedType \u2190 whnfForall expectedType\n  let .forallE _ _ _ c := expectedType | return .no\n  unless c.isImplicit || c.isInstImplicit do\n    return .no\n  if let some x \u2190 isLocalIdent? stx then\n    if (\u2190 isMVarApp (\u2190 inferType x)) then\n      /-\n      If `stx` is a local variable without type information, then adding implicit lambdas makes elaboration fail.\n      We should try to postpone elaboration until the type of the local variable becomes available, or disable\n      implicit lambdas if we cannot postpone anymore.\n      Here is an example where this special case is useful.\n      ```\n      def foo2mk (_ : \u2200 {\u03b1 : Type} (a : \u03b1), a = a) : nat := 37\n      example (x) : foo2mk x = foo2mk x := rfl\n      ```\n      The example about would fail without this special case.\n      The expected type would be `(a : \u03b1\u271d) \u2192 a = a`, where `\u03b1\u271d` is a new free variable introduced by the implicit lambda.\n      Now, let `?m` be the type of `x`. Then, the constraint `?m =?= (a : \u03b1\u271d) \u2192 a = a` cannot be solved using the\n      assignment `?m := (a : \u03b1\u271d) \u2192 a = a` since `\u03b1\u271d` is not in the scope of `?m`.\n\n      Note that, this workaround does not prevent the following example from failing.\n      ```\n      example (x) : foo2mk (id x) = 37 := rfl\n      ```\n      The user can write\n      ```\n      example (x) : foo2mk (id @x) = 37 := rfl\n      ```\n      -/\n      return .postpone\n  return .yes expectedType\n\nprivate def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do\n  match ex with\n  | .error ref msg =>\n    if impFVars.isEmpty then\n      return Exception.error ref msg\n    else\n      let mut msg := m!\"{msg}\\nthe following variables have been introduced by the implicit lambda feature\"\n      for impFVar in impFVars do\n        let auxMsg := m!\"{impFVar} : {\u2190 inferType impFVar}\"\n        let auxMsg \u2190 addMessageContext auxMsg\n        msg := m!\"{msg}{indentD auxMsg}\"\n      msg := m!\"{msg}\\nyou can disable implicit lambdas using `@` or writing a lambda expression with `\\{}` or `[]` binder annotations.\"\n      return Exception.error ref msg\n  | _ => return ex\n\nprivate def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do\n  let body \u2190 elabUsingElabFns stx expectedType catchExPostpone\n  try\n    let body \u2190 ensureHasType expectedType body\n    let r \u2190 mkLambdaFVars impFVars body\n    trace[Elab.implicitForall] r\n    return r\n  catch ex =>\n    throw (\u2190 decorateErrorMessageWithLambdaImplicitVars ex impFVars)\n\nprivate partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=\n  loop type #[]\nwhere\n  loop (type : Expr) (fvars : Array Expr) : TermElabM Expr := do\n    match (\u2190 whnfForall type) with\n    | .forallE n d b c =>\n      if c.isExplicit then\n        elabImplicitLambdaAux stx catchExPostpone type fvars\n      else withFreshMacroScope do\n        let n \u2190 MonadQuotation.addMacroScope n\n        withLocalDecl n c d fun fvar => do\n          let type := b.instantiate1 fvar\n          loop type (fvars.push fvar)\n    | _ =>\n      elabImplicitLambdaAux stx catchExPostpone type fvars\n\n/-- Main loop for `elabTerm` -/\nprivate partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax \u2192 TermElabM Expr\n  | .missing => mkSyntheticSorryFor expectedType?\n  | stx => withFreshMacroScope <| withIncRecDepth do\n    withTraceNode `Elab.step (fun _ => return m!\"expected type: {expectedType?}, term\\n{stx}\") do\n    checkMaxHeartbeats \"elaborator\"\n    let env \u2190 getEnv\n    let result \u2190 match (\u2190 liftMacroM (expandMacroImpl? env stx)) with\n    | some (decl, stxNew?) =>\n      let stxNew \u2190 liftMacroM <| liftExcept stxNew?\n      withInfoContext' stx (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <|\n        withMacroExpansion stx stxNew <|\n          withRef stxNew <|\n            elabTermAux expectedType? catchExPostpone implicitLambda stxNew\n    | _ =>\n      let useImplicitResult \u2190 if implicitLambda && (\u2190 read).implicitLambda then useImplicitLambda stx expectedType? else pure .no\n      match useImplicitResult with\n      | .yes expectedType => elabImplicitLambda stx catchExPostpone expectedType\n      | .no => elabUsingElabFns stx expectedType? catchExPostpone\n      | .postpone =>\n        /-\n        Try to postpone elaboration, and if we cannot postpone anymore disable implicit lambdas.\n        See comment at `useImplicitLambda`.\n        -/\n        if (\u2190 read).mayPostpone then\n          if catchExPostpone then\n            postponeElabTerm stx expectedType?\n          else\n            throwPostpone\n        else\n          elabUsingElabFns stx expectedType? catchExPostpone\n    trace[Elab.step.result] result\n    pure result\n\n/-- Store in the `InfoTree` that `e` is a \"dot\"-completion target. -/\ndef addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do\n  addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (\u2190 getLCtx), elaborator := .anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?)\n\n/--\n  Main function for elaborating terms.\n  It extracts the elaboration methods from the environment using the node kind.\n  Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.\n  It creates a fresh macro scope for executing the elaboration method.\n  All unlogged trace messages produced by the elaboration method are logged using\n  the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,\n  the error is logged and a synthetic sorry expression is returned.\n  If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,\n  a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,\n  and returned.\n  The option `catchExPostpone == false` is used to implement `resumeElabTerm`\n  to prevent the creation of another synthetic metavariable when resuming the elaboration.\n\n  If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.\n  We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.\n  -/\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=\n  withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  let e \u2190 elabTerm stx expectedType? catchExPostpone implicitLambda\n  withRef stx <| ensureHasType expectedType? e errorMsgHeader?\n\n/-- Execute `x` and return `some` if no new errors were recorded or exceptions were thrown. Otherwise, return `none`. -/\ndef commitIfNoErrors? (x : TermElabM \u03b1) : TermElabM (Option \u03b1) := do\n  let saved \u2190 saveState\n  Core.resetMessageLog\n  try\n    let a \u2190 x\n    if (\u2190 MonadLog.hasErrors) then\n      restoreState saved\n      return none\n    else\n      Core.setMessageLog (saved.meta.core.messages ++ (\u2190 Core.getMessageLog))\n      return a\n  catch _ =>\n    restoreState saved\n    return none\n\n/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/\ndef adaptExpander (exp : Syntax \u2192 TermElabM Syntax) : TermElab := fun stx expectedType? => do\n  let stx' \u2190 exp stx\n  withMacroExpansion stx stx' <| elabTerm stx' expectedType?\n\n/--\n  Create a new metavariable with the given type, and try to synthesize it.\n  If type class resolution cannot be executed (e.g., it is stuck because of metavariables in `type`),\n  register metavariable as a pending one.\n-/\ndef mkInstMVar (type : Expr) : TermElabM Expr := do\n  let mvar \u2190 mkFreshExprMVar type MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  unless (\u2190 synthesizeInstMVarCore mvarId) do\n    registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass\n  return mvar\n\n/--\n  Make sure `e` is a type by inferring its type and making sure it is an `Expr.sort`\n  or is unifiable with `Expr.sort`, or can be coerced into one. -/\ndef ensureType (e : Expr) : TermElabM Expr := do\n  if (\u2190 isType e) then\n    return e\n  else\n    let eType \u2190 inferType e\n    let u \u2190 mkFreshLevelMVar\n    if (\u2190 isDefEq eType (mkSort u)) then\n      return e\n    else if let some coerced \u2190 coerceToSort? e then\n      return coerced\n    else\n      if (\u2190 instantiateMVars e).hasSyntheticSorry then\n        throwAbortTerm\n      throwError \"type expected, got\\n  ({\u2190 instantiateMVars e} : {\u2190 instantiateMVars eType})\"\n\n/-- Elaborate `stx` and ensure result is a type. -/\ndef elabType (stx : Syntax) : TermElabM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  let type \u2190 elabTerm stx (mkSort u)\n  withRef stx <| ensureType type\n\n/--\n  Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,\n  a new local declaration is created, registered, and `k` is tried to be executed again. -/\npartial def withAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let flag := autoImplicit.get (\u2190 getOptions)\n  if flag then\n    withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do\n      let rec loop (s : SavedState) : TermElabM \u03b1 := do\n        try\n          k\n        catch\n          | ex => match isAutoBoundImplicitLocalException? ex with\n            | some n =>\n              -- Restore state, declare `n`, and try again\n              s.restore\n              withLocalDecl n .implicit (\u2190 mkFreshTypeMVar) fun x =>\n                withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do\n                  loop (\u2190 saveState)\n            | none   => throw ex\n      loop (\u2190 saveState)\n  else\n    k\n\ndef withoutAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k\n\npartial def withAutoBoundImplicitForbiddenPred (p : Name \u2192 Bool) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with autoBoundImplicitForbidden := fun n => p n || ctx.autoBoundImplicitForbidden n }) x\n\n/--\n  Collect unassigned metavariables in `type` that are not already in `init` and not satisfying `except`.\n-/\npartial def collectUnassignedMVars (type : Expr) (init : Array Expr := #[]) (except : MVarId \u2192 Bool := fun _ => false)\n    : TermElabM (Array Expr) := do\n  let mvarIds \u2190 getMVars type\n  if mvarIds.isEmpty then\n    return init\n  else\n    go mvarIds.toList init\nwhere\n  go (mvarIds : List MVarId) (result : Array Expr) : TermElabM (Array Expr) := do\n    match mvarIds with\n    | [] => return result\n    | mvarId :: mvarIds => do\n      if (\u2190 mvarId.isAssigned) then\n        go mvarIds result\n      else if result.contains (mkMVar mvarId) || except mvarId then\n        go mvarIds result\n      else\n        let mvarType := (\u2190 getMVarDecl mvarId).type\n        let mvarIdsNew \u2190 getMVars mvarType\n        let mvarIdsNew := mvarIdsNew.filter fun mvarId => !result.contains (mkMVar mvarId)\n        if mvarIdsNew.isEmpty then\n          go  mvarIds (result.push (mkMVar mvarId))\n        else\n          go (mvarIdsNew.toList ++ mvarId :: mvarIds) result\n\n/--\n  Return `autoBoundImplicits ++ xs`\n  This method throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs`.\n  The `autoBoundImplicits` may contain free variables created by the auto-implicit feature, and unassigned free variables.\n  It avoids the hack used at `autoBoundImplicitsOld`.\n\n  Remark: we cannot simply replace every occurrence of `addAutoBoundImplicitsOld` with this one because a particular\n  use-case may not be able to handle the metavariables in the array being given to `k`.\n-/\ndef addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do\n  let autos := (\u2190 read).autoBoundImplicits\n  go autos.toList #[]\nwhere\n  go (todo : List Expr) (autos : Array Expr) : TermElabM (Array Expr) := do\n    match todo with\n    | [] =>\n      for auto in autos do\n        if auto.isFVar then\n          let localDecl \u2190 auto.fvarId!.getDecl\n          for x in xs do\n            if (\u2190 localDeclDependsOn localDecl x.fvarId!) then\n              throwError \"invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'\"\n      return autos ++ xs\n    | auto :: todo =>\n      let autos \u2190 collectUnassignedMVars (\u2190 inferType auto) autos\n      go todo (autos.push auto)\n\n/--\n  Similar to `autoBoundImplicits`, but immediately if the resulting array of expressions contains metavariables,\n  it immediately uses `mkForallFVars` + `forallBoundedTelescope` to convert them into free variables.\n  The type `type` is modified during the process if type depends on `xs`.\n  We use this method to simplify the conversion of code using `autoBoundImplicitsOld` to `autoBoundImplicits`.\n-/\ndef addAutoBoundImplicits' (xs : Array Expr) (type : Expr) (k : Array Expr \u2192 Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let xs \u2190 addAutoBoundImplicits xs\n  if xs.all (\u00b7.isFVar) then\n    k xs type\n  else\n    forallBoundedTelescope (\u2190 mkForallFVars xs type) xs.size fun xs type => k xs type\n\ndef mkAuxName (suffix : Name) : TermElabM Name := do\n  match (\u2190 read).declName? with\n  | none          => throwError \"auxiliary declaration cannot be created when declaration name is not available\"\n  | some declName => Lean.mkAuxName (declName ++ suffix) 1\n\nbuiltin_initialize registerTraceClass `Elab.letrec\n\n/-- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it\n   is delayed assigned to one. -/\ndef isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do\n  trace[Elab.letrec] \"mvarId: {mkMVar mvarId} letrecMVars: {(\u2190 get).letRecsToLift.map (mkMVar $ \u00b7.mvarId)}\"\n  let mvarId \u2190 getDelayedMVarRoot mvarId\n  trace[Elab.letrec] \"mvarId root: {mkMVar mvarId}\"\n  return (\u2190 get).letRecsToLift.any (\u00b7.mvarId == mvarId)\n\n/--\n  Create an `Expr.const` using the given name and explicit levels.\n  Remark: fresh universe metavariables are created if the constant has more universe\n  parameters than `explicitLevels`. -/\ndef mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do\n  let cinfo \u2190 getConstInfo constName\n  if explicitLevels.length > cinfo.levelParams.length then\n    throwError \"too many explicit universe levels for '{constName}'\"\n  else\n    let numMissingLevels := cinfo.levelParams.length - explicitLevels.length\n    let us \u2190 mkFreshLevelMVars numMissingLevels\n    return Lean.mkConst constName (explicitLevels ++ us)\n\nprivate def mkConsts (candidates : List (Name \u00d7 List String)) (explicitLevels : List Level) : TermElabM (List (Expr \u00d7 List String)) := do\n  candidates.foldlM (init := []) fun result (declName, projs) => do\n    -- TODO: better support for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.\n    Linter.checkDeprecated declName -- TODO: check is occurring too early if there are multiple alternatives. Fix if it is not ok in practice\n    let const \u2190 mkConst declName explicitLevels\n    return (const, projs) :: result\n\ndef resolveName (stx : Syntax) (n : Name) (preresolved : List Syntax.Preresolved) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 List String)) := do\n  addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n  if let some (e, projs) \u2190 resolveLocalName n then\n    unless explicitLevels.isEmpty do\n      throwError \"invalid use of explicit universe parameters, '{e}' is a local\"\n    return [(e, projs)]\n  let preresolved := preresolved.filterMap fun\n    | .decl n projs => some (n, projs)\n    | _             => none\n  -- check for section variable capture by a quotation\n  let ctx \u2190 read\n  if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (\u00b7, projs) then\n    return [(e, projs)]  -- section variables should shadow global decls\n  if preresolved.isEmpty then\n    process (\u2190 resolveGlobalName n)\n  else\n    process preresolved\nwhere\n  process (candidates : List (Name \u00d7 List String)) : TermElabM (List (Expr \u00d7 List String)) := do\n    if candidates.isEmpty then\n      if (\u2190 read).autoBoundImplicit &&\n           !(\u2190 read).autoBoundImplicitForbidden n &&\n           isValidAutoBoundImplicitName n (relaxedAutoImplicit.get (\u2190 getOptions)) then\n        throwAutoBoundImplicitLocal n\n      else\n        throwError \"unknown identifier '{Lean.mkConst n}'\"\n    mkConsts candidates explicitLevels\n\n/--\n  Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.\n  Example: Assume resolveName `v.head.bla.boo` produces `(v.head, [\"bla\", \"boo\"])`, then this method produces\n  `(v.head, id, [f\u2081, f\u2082])` where `id` is an identifier for `v.head`, and `f\u2081` and `f\u2082` are identifiers for fields `\"bla\"` and `\"boo\"`. -/\ndef resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 Syntax \u00d7 List Syntax)) := do\n  match ident with\n  | .ident _ _ n preresolved =>\n    let r \u2190 resolveName ident n preresolved explicitLevels expectedType?\n    r.mapM fun (c, fields) => do\n      let ids := ident.identComponents (nFields? := fields.length)\n      return (c, ids.head!, ids.tail!)\n  | _ => throwError \"identifier expected\"\n\ndef resolveId? (stx : Syntax) (kind := \"term\") (withInfo := false) : TermElabM (Option Expr) :=\n  match stx with\n  | .ident _ _ val preresolved => do\n    let rs \u2190 try resolveName stx val preresolved [] catch _ => pure []\n    let rs := rs.filter fun \u27e8_, projs\u27e9 => projs.isEmpty\n    let fs := rs.map fun (f, _) => f\n    match fs with\n    | []  => return none\n    | [f] =>\n      let f \u2190 if withInfo then addTermInfo stx f else pure f\n      return some f\n    | _   => throwError \"ambiguous {kind}, use fully qualified name, possible interpretations {fs}\"\n  | _ => throwError \"identifier expected\"\n\n\ndef TermElabM.run (x : TermElabM \u03b1) (ctx : Context := {}) (s : State := {}) : MetaM (\u03b1 \u00d7 State) :=\n  withConfig setElabConfig (x ctx |>.run s)\n\n@[inline] def TermElabM.run' (x : TermElabM \u03b1) (ctx : Context := {}) (s : State := {}) : MetaM \u03b1 :=\n  (\u00b7.1) <$> x.run ctx s\n\ndef TermElabM.toIO (x : TermElabM \u03b1)\n    (ctxCore : Core.Context) (sCore : Core.State)\n    (ctxMeta : Meta.Context) (sMeta : Meta.State)\n    (ctx : Context) (s : State) : IO (\u03b1 \u00d7 Core.State \u00d7 Meta.State \u00d7 State) := do\n  let ((a, s), sCore, sMeta) \u2190 (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta\n  return (a, sCore, sMeta, s)\n\ninstance [MetaEval \u03b1] : MetaEval (TermElabM \u03b1) where\n  eval env opts x _ := do\n    let x : TermElabM \u03b1 := do\n      try x finally\n        (\u2190 Core.getMessageLog).forM fun msg => do IO.println (\u2190 msg.toString)\n    MetaEval.eval env opts (hideUnit := true) <| x.run' {}\n\n/--\n  Execute `x` and then tries to solve pending universe constraints.\n  Note that, stuck constraints will not be discarded.\n-/\ndef universeConstraintsCheckpoint (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let a \u2190 x\n  discard <| processPostponed (mayPostpone := true) (exceptionOnFailure := true)\n  return a\n\ndef expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : TermElabM ExpandDeclIdResult := do\n  let r \u2190 Elab.expandDeclId currNamespace currLevelNames declId modifiers\n  if (\u2190 read).sectionVars.contains r.shortName then\n    throwError \"invalid declaration name '{r.shortName}', there is a section variable with the same name\"\n  return r\n\n/--\n  Helper function for \"embedding\" an `Expr` in `Syntax`.\n  It creates a named hole `?m` and immediately assigns `e` to it.\n  Examples:\n  ```lean\n  let e := mkConst ``Nat.zero\n  `(Nat.succ $(\u2190 exprToSyntax e))\n  ```\n-/\ndef exprToSyntax (e : Expr) : TermElabM Term := withFreshMacroScope do\n  let result \u2190 `(?m)\n  let eType \u2190 inferType e\n  let mvar \u2190 elabTerm result eType\n  mvar.mvarId!.assign e\n  return result\n\nend Term\n\nopen Term in\ndef withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m \u03b1) : m \u03b1 := do\n  controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x\n\nbuiltin_initialize\n  registerTraceClass `Elab.postpone\n  registerTraceClass `Elab.coe\n  registerTraceClass `Elab.debug\n\nexport Term (TermElabM)\n\nend Lean.Elab\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/Term.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020279, "lm_q2_score": 0.034100423749078415, "lm_q1q2_score": 0.008456476319234242}}
{"text": "-- See Lean doc/monads/transformers.lean\nnamespace Args1\n\nabbrev Arguments := List String\n\ndef indexOf? [BEq \u03b1] (xs : List \u03b1) (s : \u03b1) (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 \u2190 read\n  match indexOf? args name with\n    | some i => \n      if h : i + 1 < args.length then \n        return args[i+1]'h \n      else\n        throw s!\"Value required for command line argument {name}\"\n    | none => \n      throw s!\"Command line argument {name} missing\"\n\ndef optionalSwitch (name : String) : ReaderT Arguments (Except String) Bool := do\n  let args \u2190 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 [\"--input\"]\n-- Except.error \"Value required for command line argument --input\"\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\n\nstructure Config where\n  help : Bool := false\n  verbose : Bool := false\n  input : List String := []\n  deriving Repr\n\nabbrev CliConfigM := StateT Config (ReaderT Arguments (Except String))\n\ndef parseArguments : CliConfigM Bool := do\n  let mut config \u2190 get\n  if (\u2190 optionalSwitch \"--help\") then\n    throw \"Usage: example [--help] [--verbose] [--input <input file>]\"\n  dbg_trace \"config: \"\n  config := { config with\n    verbose := (\u2190 optionalSwitch \"--verbose\"),\n    input := config.input.concat (\u2190 requiredArgument \"--input\") }\n  set config\n  return true\n\ndef main (args : List String) : IO Unit := do\n  let config : Config := {}\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  \nset_option trace.Meta.Match.debug true\nset_option trace.Meta.synthInstance true\nset_option trace.Elab.definition true\nset_option pp.all true\n\n#eval main [\"--help\"]\n-- Usage: example [--help] [--verbose] [--input <input file>]\n\n#eval main [\"--input\", \"foo\"]\n-- Processing input file 'foo' with verbose=false\n\n#eval main [\"--verbose\", \"--input\", \"bar\", \"--input\", \"foo\"]\n-- Processing input 'bar' with verbose=true\n\nend Args1", "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/Args1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919328049359536, "lm_q2_score": 0.04401865190087806, "lm_q1q2_score": 0.008448623328834871}}
{"text": "/-\nCopyright (c) 2021 OpenAI. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Stanislas Polu, Jesse Michael Han\n\nHelper functions to work with the tactic monad.\n-/\nimport tactic\nimport tactic.core\nimport util.io\nimport system.io\nimport basic.control\nimport util.util\n\nsection run_with_state'\n\nnamespace interaction_monad\nopen interaction_monad.result\nmeta def run_with_state' {\u03c3\u2081 \u03c3\u2082 : Type} {\u03b1 : Type*} (state : \u03c3\u2081) (tac : interaction_monad \u03c3\u2081 \u03b1) : interaction_monad \u03c3\u2082 \u03b1 :=\n\u03bb s, match (tac state) with\n     | (success val _) := success val s\n     | (exception fn pos _) := exception fn pos s\n     end\nend interaction_monad\nend run_with_state'\n\nnamespace tactic\n\nopen interaction_monad interaction_monad.result\n\n/- capture but backtrack the state -/\nmeta def capture' {\u03b1} (t : tactic \u03b1) : tactic (tactic_result \u03b1) :=\n\u03bb s, match t s with\n| (success r s') := success (success r s') s\n| (exception f p s') := success (exception f p s') s\nend\n\nmeta def set_goal_to (goal : expr) : tactic unit :=\nmk_meta_var goal >>= set_goals \u2218 pure\n\nmeta def guard_sorry (e : expr) : tactic unit := guard $ bnot e.contains_sorry\n\nmeta def guard_undefined (e : expr) : tactic unit := guard $ bnot e.contains_undefined\n\nend tactic\n\nsection validate\n\nmeta def kernel_type_check (pf : expr) : tactic unit := do {\n  tp \u2190 tactic.infer_type pf,\n  env \u2190 tactic.get_env,\n  let decl := (declaration.defn `_ (expr.collect_univ_params pf) tp pf reducibility_hints.opaque ff),\n  res \u2190 tactic.capture' (env.add decl $> ()),\n  match res with\n  | (interaction_monad.result.success _ _) := pure ()\n  | (interaction_monad.result.exception msg _ _) := let msg := msg.get_or_else (\u03bb _, (\"\" : format)) in\n    tactic.fail format! \"kernel type check failed:\\n---\\n{msg ()}\\n---\\n\"\n  end\n}\n\nmeta def validate_proof (tgt: expr) (pf: expr) : tactic unit := do {\n    env \u2190 tactic.get_env,\n    pf \u2190 pure $ env.unfold_untrusted_macros pf,\n    pft \u2190 tactic.infer_type pf,\n    tactic.type_check pf tactic.transparency.all,\n    guard (bnot pf.has_meta_var) <|> do {\n      tactic.fail format! \"proof contains metavariables\"\n    },\n    tactic.guard_sorry pf <|> do {\n      tactic.fail format! \"proof contains `sorry`\"\n    },\n    tactic.guard_undefined pf <|> do {\n      tactic.fail format! \"proof contains `undefined`\"\n    },\n    tactic.is_def_eq tgt pft <|> do {\n      tgt_fmt \u2190 tactic.pp tgt,\n      pft_fmt \u2190 tactic.pp pft,\n      tactic.fail format! \"proof type mismatch: {tgt_fmt} != {pft_fmt}\"\n    },\n    kernel_type_check pf\n}\n\nmeta def validate_decl (nm : name) : tactic unit := do {\n  env \u2190 tactic.get_env,\n  d \u2190 env.get nm,\n  validate_proof d.type d.value\n}\n\nend validate\n\nsection add_open_namespace\n\nmeta def add_open_namespace : name \u2192 tactic unit := \u03bb nm, do\nenv \u2190 tactic.get_env, tactic.set_env (env.execute_open nm)\n\nmeta def add_open_namespaces (nms : list name) : tactic unit :=\nnms.mmap' add_open_namespace\n\nend add_open_namespace\n\nsection tactic_state\nopen interaction_monad.result\nsetup_tactic_parser\n\nmeta def num_goals' : tactic_state \u2192 option \u2115 :=\n\u03bb ts, match tactic.num_goals ts with | (success val _) := pure val | _ := none end\n\nmeta def postprocess_tactic_state (ts : tactic_state) : tactic string := do\n  -- Note: we do not postprocess here, because we assume that there are other\n  -- data sources that use default `pp` settings.\n  pure $ to_string (to_fmt ts)\n\nend tactic_state\n\n\nsection parse_tac\n\nsetup_tactic_parser\n\nopen tactic\n\n/-- Run the given parser on the given string input. -/\nmeta def run_on_input {\u03b1} (p : lean.parser \u03b1) (s : string) : tactic \u03b1 :=\nlean.parser.run $ do\n  get_state >>= \u03bb ps, of_tactic $ do\n    tactic.set_env ps.env,\n    -- eval_trace format!\"[parse_itactic_reflected] TRYING TO PARSE {itactic_string}\",\n    prod.fst <$> (@interaction_monad.run_with_state' parser_state _ _ ps $ with_input p s)\n\n/-- Parse a reflected interactive tactic from a string.\n    The result can be evaluated to a `tactic unit` by using\n    `eval_expr (tactic unit)`. -/\nmeta def parse_itactic_reflected (tactic_string : string) : tactic expr := do\nlet itactic_string := \"{ \" ++ tactic_string ++  \" }\",\nr \u2190 run_on_input parser.itactic_reflected itactic_string,\npure $ reflected_value.expr r\n\n/-- Parse an interactive tactic from a string. -/\nmeta def parse_itactic (tactic_string : string) : tactic (tactic string) :=\ndo\n  rtac \u2190 parse_itactic_reflected tactic_string,\n  u \u2190 eval_expr (tactic unit) rtac,\n  pure (u *> pure tactic_string)\n\n\nmeta def get_tac_and_capture_result (next_candidate : string) (timeout : \u2115 := 5000) : tactic (tactic_result _) := do {\n  tac \u2190 do {\n    env \u2190 tactic.get_env,\n    tac \u2190 parse_itactic next_candidate,\n    tactic.set_env env,\n    pure tac\n  },\n  result \u2190 tactic.capture' (tactic.try_for_time timeout $ tactic.try_for 200000 tac), -- if `tac` fails, exception is captured here\n  pure result\n}\n\nend parse_tac\n\nsection misc\n\nmeta def tactic.is_theorem (nm : name) : tactic bool := do {\n  env \u2190 tactic.get_env,\n  declaration.is_theorem <$> env.get nm\n}\n\nend misc\n", "meta": {"author": "openai", "repo": "lean-gym", "sha": "1585ac4d2e56a1ceb72243ce859645b9d0069d34", "save_path": "github-repos/lean/openai-lean-gym", "path": "github-repos/lean/openai-lean-gym/lean-gym-1585ac4d2e56a1ceb72243ce859645b9d0069d34/src/util/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181321265898594, "lm_q2_score": 0.0414622767088889, "lm_q1q2_score": 0.008367635266776715}}
{"text": "import a\n\nlemma aa : true :=\nbegin\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 300 + 1 = 6001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  trivial,\nend\n\n\nlemma ab : true :=\nbegin\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 300 + 1 = 6001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  have : 20 * 200 + 1 = 4001 := rfl,\n  trivial,\nend\n", "meta": {"author": "alexjbest", "repo": "pole-test", "sha": "a8458dea5dfa337d85bf50c4698eae668759a487", "save_path": "github-repos/lean/alexjbest-pole-test", "path": "github-repos/lean/alexjbest-pole-test/pole-test-a8458dea5dfa337d85bf50c4698eae668759a487/src/b.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262785020255, "lm_q2_score": 0.026355350169495265, "lm_q1q2_score": 0.008365880722920608}}
{"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 := \u00abvariables\u00bb) \"variables\" (bracketedBinder)* : command\n\n@[command_elab \u00abvariables\u00bb] def elabVariables : CommandElab\n  | `(variables%$pos $binders*) => do\n    logWarningAt pos \"'variables' has been replaced by 'variable' in lean 4\"\n    elabVariable (\u2190 `(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 \u00ablemma\u00bb] 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 \u00b7 \"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 \u2192 Array FVarId \u2192 MetaM (\u03b1 \u00d7 Array (Option FVarId) \u00d7 MVarId))\n    (clearAuxDeclsInsteadOfRevert := false) : MetaM (\u03b1 \u00d7 MVarId) := do\n  let (xs, mvarId) \u2190 mvarId.revert fvarIds true clearAuxDeclsInsteadOfRevert\n  let (r, xs', mvarId) \u2190 k mvarId xs\n  let (ys, mvarId) \u2190 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 := \u2190 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) \u2190 mvarId.withReverted #[fvarId] fun mvarId fvars => mvarId.withContext do\n    let check (typeOld : Expr) : MetaM Unit := do\n      if checkDefEq then\n        unless \u2190 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, \u2190 mvarId.replaceTargetDefEq targetNew)\n    match \u2190 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 : \u2115` and the current goal is `\u22a2 n + 2 = 2`, then\n```lean\nchange _ + 1 = _\n```\nchanges the goal to `\u22a2 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 \u21a6 do\n        let hTy \u2190 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 \u2190 mkFreshExprMVar none\n        let (_, mvars) \u2190 elabTermWithHoles\n                          (\u2190 `(term | show $newType from $(\u2190 Term.exprToSyntax mvar))) hTy `change\n        liftMetaTactic fun mvarId \u21a6 do\n          return (\u2190 mvarId.changeLocalDecl' h (\u2190 inferType mvar)) :: mvars)\n      (atTarget := evalTactic <| \u2190 `(tactic| show $newType))\n      (failed := fun _ \u21a6 throwError \"change tactic failed\")\n\n/--\n`by_cases p` makes a case distinction on `p`,\nresulting in two subgoals `h : p \u22a2` and `h : \u00ac p \u22a2`.\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 : \u2200 a b : Nat, a = b \u2192 b = a := by\n  introv h,\n  exact h.symm\n```\nThe state after `introv h` is\n```\na b : \u2115,\nh : a = b\n\u22a2 b = a\n```\n\n```\nexample : \u2200 a b : Nat, a = b \u2192 \u2200 c, b = c \u2192 a = c := by\n  introv h\u2081 h\u2082,\n  exact h\u2081.trans h\u2082\n```\nThe state after `introv h\u2081 h\u2082` is\n```\na b : \u2115,\nh\u2081 : a = b,\nc : \u2115,\nh\u2082 : b = c\n\u22a2 a = c\n```\n-/\nsyntax (name := introv) \"introv \" (colGt binderIdent)* : tactic\n@[tactic introv] partial def evalIntrov : Tactic := fun stx \u21a6 do\n  match stx with\n  | `(tactic| introv)                     => introsDep\n  | `(tactic| introv $h:ident $hs:binderIdent*) =>\n    evalTactic (\u2190 `(tactic| introv; intro $h:ident; introv $hs:binderIdent*))\n  | `(tactic| introv _%$tk $hs:binderIdent*) =>\n    evalTactic (\u2190 `(tactic| introv; intro _%$tk; introv $hs:binderIdent*))\n  | _ => throwUnsupportedSyntax\nwhere\n  introsDep : TacticM Unit := do\n    let t \u2190 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 \u21a6 do\n      let (_, goal) \u2190 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) \u2190 elabTerm t (\u2190 inferType (\u2190 getMainTarget))\n    if not (\u2190 isDefEq val (\u2190 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 \u2190 getMainGoal\n  for ldec in \u2190 getLCtx do\n    if ldec.isAuxDecl then\n      g \u2190 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 \u2190 mvarId.getTag\n  let (_, mvarId) \u2190 mvarId.withReverted #[fvarId] fun mvarId' fvars => mvarId'.withContext do\n    let tgt \u2190 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 \u2190 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'' \u2190 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\u2081 n\u2082 ...` clears the bodies of the local definitions `n\u2081, n\u2082 ...`, changing them\ninto regular hypotheses. A hypothesis `n : \u03b1 := t` is changed to `n : \u03b1`.\n\nThe order of `n\u2081 n\u2082 ...` 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 \u2190 getFVarIds hs\n  let fvarIds \u2190 withMainContext <| sortFVarIds fvarIds\n  for fvarId in fvarIds.reverse do\n    withMainContext do\n      let mvarId \u2190 (\u2190 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": "/-\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 tactic.find_unused\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.Meta.RbMap\nimport Mathbin.Tactic.Core\n\n/-!\n# list_unused_decls\n\n`#list_unused_decls` is a command used for theory development.\nWhen writing a new theory one often tries\nmultiple variations of the same definitions: `foo`, `foo'`, `foo\u2082`,\n`foo\u2083`, etc. Once the main definition or theorem has been written,\nit's time to clean up and the file can contain a lot of dead code.\nMark the main declarations with `@[main_declaration]` and\n`#list_unused_decls` will show the declarations in the file\nthat are not needed to define the main declarations.\n\nSome of the so-called \"unused\" declarations may turn out to be useful\nafter all. The oversight can be corrected by marking those as\n`@[main_declaration]`. `#list_unused_decls` will revise the list of\nunused declarations. By default, the list of unused declarations will\nnot include any dependency of the main declarations.\n\nThe `@[main_declaration]` attribute should be removed before submitting\ncode to mathlib as it is merely a tool for cleaning up a module.\n-/\n\n\nnamespace Tactic\n\n/-- Attribute `main_declaration` is used to mark declarations that are featured\nin the current file.  Then, the `#list_unused_decls` command can be used to\nlist the declaration present in the file that are not used by the main\ndeclarations of the file. -/\n@[user_attribute]\nunsafe def main_declaration_attr : user_attribute\n    where\n  Name := `main_declaration\n  descr := \"tag essential declarations to help identify unused definitions\"\n#align tactic.main_declaration_attr tactic.main_declaration_attr\n\n/-- `update_unsed_decls_list n m` removes from the map of unneeded declarations those\nreferenced by declaration named `n` which is considerred to be a\nmain declaration -/\nprivate unsafe def update_unsed_decls_list :\n    Name \u2192 name_map declaration \u2192 tactic (name_map declaration)\n  | n, m => do\n    let d \u2190 get_decl n\n    if m n then do\n        let m := m n\n        let ns := d d\n        ns m update_unsed_decls_list\n      else pure m\n#align tactic.update_unsed_decls_list tactic.update_unsed_decls_list\n\n/-- In the current file, list all the declaration that are not marked as `@[main_declaration]` and\nthat are not referenced by such declarations -/\nunsafe def all_unused (fs : List (Option String)) : tactic (name_map declaration) := do\n  let ds \u2190 get_decls_from fs\n  let ls \u2190 ds.keys.filterM (succeeds \u2218 user_attribute.get_param_untyped main_declaration_attr)\n  let ds \u2190 ls.foldlM (flip update_unsed_decls_list) ds\n  ds fun n d => do\n      let e \u2190 get_env\n      return <| !d e\n#align tactic.all_unused tactic.all_unused\n\n/-- expecting a string literal (e.g. `\"src/tactic/find_unused.lean\"`)\n-/\nunsafe def parse_file_name (fn : pexpr) : tactic (Option String) :=\n  some <$> (to_expr fn >>= eval_expr String) <|> fail \"expecting: \\\"src/dir/file-name\\\"\"\n#align tactic.parse_file_name tactic.parse_file_name\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\n/-- The command `#list_unused_decls` lists the declarations that that\nare not used the main features of the present file. The main features\nof a file are taken as the declaration tagged with\n`@[main_declaration]`.\n\nA list of files can be given to `#list_unused_decls` as follows:\n\n```lean\n#list_unused_decls [\"src/tactic/core.lean\",\"src/tactic/interactive.lean\"]\n```\n\nThey are given in a list that contains file names written as Lean\nstrings. With a list of files, the declarations from all those files\nin addition to the declarations above `#list_unused_decls` in the\ncurrent file will be considered and their interdependencies will be\nanalyzed to see which declarations are unused by declarations marked\nas `@[main_declaration]`. The files listed must be imported by the\ncurrent file. The path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present).\n\nNeither `#list_unused_decls` nor `@[main_declaration]` should appear\nin a finished mathlib development. -/\n@[user_command]\nunsafe def unused_decls_cmd (_ : parse <| tk \"#list_unused_decls\") : lean.parser Unit := do\n  let fs \u2190 pexpr_list\n  show tactic Unit from do\n      let fs \u2190 fs parse_file_name\n      let ds \u2190 all_unused <| none :: fs\n      ds fun \u27e8n, _\u27e9 =>\n          \u2190 do\n            dbg_trace \"#print {\u2190 n}\"\n#align tactic.unused_decls_cmd tactic.unused_decls_cmd\n\nadd_tactic_doc\n  { Name := \"#list_unused_decls\"\n    category := DocCategory.cmd\n    declNames := [`tactic.unused_decls_cmd]\n    tags := [\"debugging\"] }\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/FindUnused.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106120013047907, "lm_q2_score": 0.04885777792970757, "lm_q1q2_score": 0.008357670128364211}}
{"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 \u2190 expandStmt (\u2190 `(stmt| expand! break in $s))\n    let hasBreak := sb.raw.count (\u00b7 matches `(stmt| break)) < s.raw.count (\u00b7 matches `(stmt| break))\n    if hasBreak then\n      s := sb\n    let sc \u2190 expandStmt (\u2190 `(stmt| expand! continue in $s))\n    let hasContinue := sc.raw.count (\u00b7 matches `(stmt| continue)) < s.raw.count (\u00b7 matches `(stmt| continue))\n    if hasContinue then\n      s := sc\n    let mut body \u2190 `(d! $s)\n    if hasContinue then\n      body \u2190 `(ExceptCpsT.runCatch $body)\n    let mut loop \u2190 `(forM $e (fun $x => $body))\n    if hasBreak then\n      loop \u2190 `(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 \u2190 get; expand! mut $y in $s })  -- (S9)\n\nvariable [Monad m]\nvariable (ma ma' : m \u03b1)\nvariable (b : Bool)\nvariable (xs : List \u03b1) (act : \u03b1 \u2192 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 : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) (init : \u03b2) (xs : List \u03b1) : m \u03b2 := do'\n  let mut y := init;\n  for x in xs do' {\n    y \u2190 f y x\n  };\n  return y\n\nexample [LawfulMonad m] (f : \u03b2 \u2192 \u03b1 \u2192 m \u03b2) :\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 \u03b1} : (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 : \u03b1 \u2192 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 : \u03b1 \u2192 m Bool)\n\ntheorem byCases_Bool_bind (x : m Bool) (f g : Bool \u2192 m \u03b2) (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 \u2190 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?, \u2190 ih]; simp\n        apply byCases_Bool_bind <;> simp\n\ndef ex3 [Monad m] (p : \u03b1 \u2192 m Bool) (xss : List (List \u03b1)) : m (Option \u03b1) := do'\n  for xs in xss do' {\n    for x in xs do' {\n      let b \u2190 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 \u03b1)) :\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 [\u2190 ih, \u2190 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 : \u03b1 \u2192 m Bool) : List \u03b1 \u2192 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 \u2190 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 [\u2190 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 \u2192 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 ..flocq\n\n/- Architecture-dependent parameters for PowerPC -/\n\nnamespace archi\nopen flocq\n\ndef ptr64 : bool := ff\n\ndef big_endian : bool := tt\n\ndef align_int64 := 8\ndef align_float64 := 8\n\ndef splitlong := tt\n\nlemma splitlong_ptr32 : splitlong = tt \u2192 ptr64 = ff := \u03bb_, rfl\n\ndef default_pl_64 : bool \u00d7 nan_pl 53 :=\n(ff, word.repr (2^51))\n  \ndef choose_binop_pl_64 (s1 : bool) (pl1 : nan_pl 53) (s2 : bool) (pl2 : nan_pl 53) : bool :=\nff /- always choose first NaN -/\n\ndef default_pl_32 : bool \u00d7 nan_pl 24 :=\n(ff,  word.repr (2^22))\n  \ndef choose_binop_pl_32 (s1 : bool) (pl1 : nan_pl 24) (s2 : bool) (pl2 : nan_pl 24) : bool :=\nff /- always choose first NaN -/\n   \ndef float_of_single_preserves_sNaN := tt\n\n/- Can we use the 64-bit extensions to the PowerPC architecture? -/\nconstant ppc64 : bool\n\nend archi", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/archi/powerpc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.02405355525560635, "lm_q1q2_score": 0.008301008703986186}}
{"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 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2)\n\ndef map' : \u03a0 (i j : fin 3) (hij : i \u2264 j), F i \u27f6 F j\n| \u27e80,hi\u27e9 \u27e80,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e81,hi\u27e9 \u27e81,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e82,hi\u27e9 \u27e82,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e80,hi\u27e9 \u27e81,hj\u27e9 _ := a\n| \u27e81,hi\u27e9 \u27e82,hj\u27e9 _ := b\n| \u27e80,hi\u27e9 \u27e82,hj\u27e9 _ := a \u226b b\n| \u27e8i+3,hi\u27e9 _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+3,hj\u27e9 _ := by { exfalso, revert hj, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : \u2200 (i : fin 3), map' F a b i i le_rfl = \ud835\udfd9 _\n| \u27e80,hi\u27e9 := rfl\n| \u27e81,hi\u27e9 := rfl\n| \u27e82,hi\u27e9 := rfl\n| \u27e8i+3,hi\u27e9 := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : \u03a0 (i j k : fin 3) (hij : i \u2264 j) (hjk : j \u2264 k),\n  map' F a b i j hij \u226b map' F a b j k hjk = map' F a b i k (hij.trans hjk)\n| \u27e80, _\u27e9 \u27e80, _\u27e9 k _ _ := category.id_comp _\n| \u27e81, _\u27e9 \u27e81, _\u27e9 k _ _ := category.id_comp _\n| i \u27e81, _\u27e9 \u27e81, _\u27e9 _ _ := category.comp_id _\n| i \u27e82, _\u27e9 \u27e82, _\u27e9 _ _ := category.comp_id _\n| \u27e80, _\u27e9 \u27e81, _\u27e9 \u27e82, _\u27e9 _ _ := rfl\n| \u27e8i+3,hi\u27e9 _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+3,hj\u27e9 _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ \u27e8k+3,hk\u27e9 _ _ := by { exfalso, revert hk, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin3_functor_mk\n\ndef fin3_functor_mk (F : fin 3 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2) : fin 3 \u2964 C :=\n{ obj := F,\n  map := \u03bb i j hij, fin3_functor_mk.map' F a b i j hij.le,\n  map_id' := \u03bb i, fin3_functor_mk.map'_id F a b i,\n  map_comp' := \u03bb 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 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2) (c : F 2 \u27f6 F 3)\n\ndef map' : \u03a0 (i j : fin 4) (hij : i \u2264 j), F i \u27f6 F j\n| \u27e80,hi\u27e9 \u27e80,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e81,hi\u27e9 \u27e81,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e82,hi\u27e9 \u27e82,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e83,hi\u27e9 \u27e83,hj\u27e9 _ := \ud835\udfd9 _\n| \u27e80,hi\u27e9 \u27e81,hj\u27e9 _ := a\n| \u27e81,hi\u27e9 \u27e82,hj\u27e9 _ := b\n| \u27e82,hi\u27e9 \u27e83,hj\u27e9 _ := c\n| \u27e80,hi\u27e9 \u27e82,hj\u27e9 _ := a \u226b b\n| \u27e81,hi\u27e9 \u27e83,hj\u27e9 _ := b \u226b c\n| \u27e80,hi\u27e9 \u27e83,hj\u27e9 _ := a \u226b b \u226b c\n| \u27e8i+4,hi\u27e9 _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+4,hj\u27e9 _ := by { exfalso, revert hj, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n| \u27e83,hi\u27e9 \u27e82,hj\u27e9 H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : \u2200 (i : fin 4), map' F a b c i i le_rfl = \ud835\udfd9 _\n| \u27e80,hi\u27e9 := rfl\n| \u27e81,hi\u27e9 := rfl\n| \u27e82,hi\u27e9 := rfl\n| \u27e83,hi\u27e9 := rfl\n| \u27e8i+4,hi\u27e9 := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : \u03a0 (i j k : fin 4) (hij : i \u2264 j) (hjk : j \u2264 k),\n  map' F a b c i j hij \u226b map' F a b c j k hjk = map' F a b c i k (hij.trans hjk)\n| \u27e80, _\u27e9 \u27e80, _\u27e9 k _ _ := category.id_comp _\n| \u27e81, _\u27e9 \u27e81, _\u27e9 k _ _ := category.id_comp _\n| \u27e82, _\u27e9 \u27e82, _\u27e9 k _ _ := category.id_comp _\n| i \u27e81, _\u27e9 \u27e81, _\u27e9 _ _ := category.comp_id _\n| i \u27e82, _\u27e9 \u27e82, _\u27e9 _ _ := category.comp_id _\n| i \u27e83, _\u27e9 \u27e83, _\u27e9 _ _ := category.comp_id _\n| \u27e80, _\u27e9 \u27e81, _\u27e9 \u27e82, _\u27e9 _ _ := rfl\n| \u27e80, _\u27e9 \u27e81, _\u27e9 \u27e83, _\u27e9 _ _ := rfl\n| \u27e80, _\u27e9 \u27e82, _\u27e9 \u27e83, _\u27e9 _ _ := category.assoc a b c\n| \u27e81, _\u27e9 \u27e82, _\u27e9 \u27e83, _\u27e9 _ _ := rfl\n| \u27e8i+4,hi\u27e9 _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ \u27e8j+4,hj\u27e9 _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ \u27e8k+4,hk\u27e9 _ _ := by { exfalso, revert hk, dec_trivial }\n| \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| \u27e83,hi\u27e9 \u27e82,hj\u27e9 _ H _ := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+1,hi\u27e9 \u27e80,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n| _ \u27e8i+2,hi\u27e9 \u27e81,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n| _ \u27e83,hi\u27e9 \u27e82,hj\u27e9 _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin4_functor_mk\n\ndef fin4_functor_mk (F : fin 4 \u2192 C) (a : F 0 \u27f6 F 1) (b : F 1 \u27f6 F 2) (c : F 2 \u27f6 F 3) : fin 4 \u2964 C :=\n{ obj := F,\n  map := \u03bb i j hij, fin4_functor_mk.map' F a b c i j hij.le,\n  map_id' := \u03bb i, fin4_functor_mk.map'_id F a b c i,\n  map_comp' := \u03bb 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": "/-\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.Data.LOption\nimport Lean.Environment\nimport Lean.Class\nimport Lean.ReducibilityAttrs\nimport Lean.Util.ReplaceExpr\nimport Lean.Util.MonadBacktrack\nimport Lean.Compiler.InlineAttrs\nimport Lean.Meta.TransparencyMode\n\n/-!\nThis module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.\n1- Weak head normal form computation with support for metavariables and transparency modes.\n2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).\n3- Type inference.\n4- Type class resolution.\n\nThey are packed into the MetaM monad.\n-/\n\nnamespace Lean.Meta\n\nbuiltin_initialize isDefEqStuckExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `isDefEqStuck\n\n/--\nConfiguration flags for the `MetaM` monad.\nMany of them are used to control the `isDefEq` function that checks whether two terms are definitionally equal or not.\nRecall that when `isDefEq` is trying to check whether\n`?m@C a\u2081 ... a\u2099` and `t` are definitionally equal (`?m@C a\u2081 ... a\u2099 =?= t`), where\n`?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`.\nWe solve it using the assignment `?m := fun a\u2081 ... a\u2099 => t` if\n1) `a\u2081 ... a\u2099` are pairwise distinct free variables that are \u200b*not*\u200b let-variables.\n2) `a\u2081 ... a\u2099` are not in `C`\n3) `t` only contains free variables in `C` and/or `{a\u2081, ..., a\u2099}`\n4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C`\n5) `?m` does not occur in `t`\n-/\nstructure Config where\n  /--\n    If `foApprox` is set to true, and some `a\u1d62` is not a free variable,\n    then we use first-order unification\n    ```\n      ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k\n    ```\n    reduces to\n    ```\n      ?m a_1 ... a_i =?= f\n      a_{i+1}        =?= b_1\n      ...\n      a_{i+k}        =?= b_k\n    ```\n  -/\n  foApprox           : Bool := false\n  /--\n    When `ctxApprox` is set to true, we relax condition 4, by creating an\n    auxiliary metavariable `?n'` with a smaller context than `?m'`.\n  -/\n  ctxApprox          : Bool := false\n  /--\n    When `quasiPatternApprox` is set to true, we ignore condition 2.\n  -/\n  quasiPatternApprox : Bool := false\n  /-- When `constApprox` is set to true,\n     we solve `?m t =?= c` using\n     `?m := fun _ => c`\n     when `?m t` is not a higher-order pattern and `c` is not an application as -/\n  constApprox        : Bool := false\n  /--\n    When the following flag is set,\n    `isDefEq` throws the exeption `Exeption.isDefEqStuck`\n    whenever it encounters a constraint `?m ... =?= t` where\n    `?m` is read only.\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  isDefEqStuckEx     : Bool := false\n  /--\n    Controls which definitions and theorems can be unfolded by `isDefEq` and `whnf`.\n   -/\n  transparency       : TransparencyMode := TransparencyMode.default\n  /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/\n  zetaNonDep         : Bool := true\n  /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/\n  trackZeta          : Bool := false\n  /-- Enable/disable the unification hints feature. -/\n  unificationHints   : Bool := true\n  /-- Enables proof irrelevance at `isDefEq` -/\n  proofIrrelevance   : Bool := true\n  /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make\n      sure typing constraints resolved during elaboration should not \"fill\" holes that are supposed to be filled using tactics.\n      However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill\n      named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify\n      the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because\n      this last unification step is not really part of the term elaboration. -/\n  assignSyntheticOpaque : Bool := false\n  /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/\n  offsetCnstrs          : Bool := true\n  /-- Eta for structures configuration mode. -/\n  etaStruct             : EtaStructMode := .all\n\n/--\n  Function parameter information cache.\n-/\nstructure ParamInfo where\n  /-- The binder annotation for the parameter. -/\n  binderInfo     : BinderInfo := BinderInfo.default\n  /-- `hasFwdDeps` is true if there is another parameter whose type depends on this one. -/\n  hasFwdDeps     : Bool       := false\n  /-- `backDeps` contains the backwards dependencies. That is, the (0-indexed) position of previous parameters that this one depends on. -/\n  backDeps       : Array Nat  := #[]\n  /-- `isProp` is true if the parameter is always a proposition. -/\n  isProp         : Bool       := false\n  /--\n    `isDecInst` is true if the parameter's type is of the form `Decidable ...`.\n    This information affects the generation of congruence theorems.\n  -/\n  isDecInst      : Bool       := false\n  /--\n    `higherOrderOutParam` is true if this parameter is a higher-order output parameter\n    of local instance.\n    Example:\n    ```\n    getElem :\n      {cont : Type u_1} \u2192 {idx : Type u_2} \u2192 {elem : Type u_3} \u2192\n      {dom : cont \u2192 idx \u2192 Prop} \u2192 [self : GetElem cont idx elem dom] \u2192\n      (xs : cont) \u2192 (i : idx) \u2192 dom xs i \u2192 elem\n    ```\n    This flag is true for the parameter `dom` because it is output parameter of\n    `[self : GetElem cont idx elem dom]`\n   -/\n  higherOrderOutParam : Bool  := false\n  /--\n    `dependsOnHigherOrderOutParam` is true if the type of this parameter depends on\n    the higher-order output parameter of a previous local instance.\n    Example:\n    ```\n    getElem :\n      {cont : Type u_1} \u2192 {idx : Type u_2} \u2192 {elem : Type u_3} \u2192\n      {dom : cont \u2192 idx \u2192 Prop} \u2192 [self : GetElem cont idx elem dom] \u2192\n      (xs : cont) \u2192 (i : idx) \u2192 dom xs i \u2192 elem\n    ```\n    This flag is true for the parameter with type `dom xs i` since `dom` is an output parameter\n    of the instance `[self : GetElem cont idx elem dom]`\n  -/\n  dependsOnHigherOrderOutParam : Bool := false\n  deriving Inhabited\n\ndef ParamInfo.isImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.implicit\n\ndef ParamInfo.isInstImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.instImplicit\n\ndef ParamInfo.isStrictImplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.strictImplicit\n\ndef ParamInfo.isExplicit (p : ParamInfo) : Bool :=\n  p.binderInfo == BinderInfo.default\n\n\n/--\n  Function information cache. See `ParamInfo`.\n-/\nstructure FunInfo where\n  /-- Parameter information cache. -/\n  paramInfo  : Array ParamInfo := #[]\n  /--\n    `resultDeps` contains the function result type backwards dependencies.\n    That is, the (0-indexed) position of parameters that the result type depends on.\n  -/\n  resultDeps : Array Nat       := #[]\n\n/--\n  Key for the function information cache.\n-/\nstructure InfoCacheKey where\n  /-- The transparency mode used to compute the `FunInfo`. -/\n  transparency : TransparencyMode\n  /-- The function being cached information about. It is quite often an `Expr.const`. -/\n  expr         : Expr\n  /--\n    `nargs? = some n` if the cached information was computed assuming the function has arity `n`.\n    If `nargs? = none`, then the cache information consumed the arrow type as much as possible\n    unsing the current transparency setting.\n  X-/\n  nargs?       : Option Nat\n  deriving Inhabited, BEq\n\nnamespace InfoCacheKey\ninstance : Hashable InfoCacheKey :=\n  \u27e8fun \u27e8transparency, expr, nargs\u27e9 => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)\u27e9\nend InfoCacheKey\n\nabbrev SynthInstanceCache := PersistentHashMap (LocalInstances \u00d7 Expr) (Option Expr)\n\nabbrev InferTypeCache := PersistentExprStructMap Expr\nabbrev FunInfoCache   := PersistentHashMap InfoCacheKey FunInfo\nabbrev WhnfCache      := PersistentExprStructMap Expr\n\n/--\n  A mapping `(s, t) \u21a6 isDefEq s t`.\n  TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache).\n  We should also investigate the impact on memory consumption. -/\nabbrev DefEqCache := PersistentHashMap (Expr \u00d7 Expr) Bool\n\n/--\n  Cache datastructures for type inference, type class resolution, whnf, and definitional equality.\n-/\nstructure Cache where\n  inferType      : InferTypeCache := {}\n  funInfo        : FunInfoCache   := {}\n  synthInstance  : SynthInstanceCache := {}\n  whnfDefault    : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default`\n  whnfAll        : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all`\n  defEq          : DefEqCache := {}\n  deriving Inhabited\n\n/--\n \"Context\" for a postponed universe constraint.\n `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created.\n-/\nstructure DefEqContext where\n  lhs            : Expr\n  rhs            : Expr\n  lctx           : LocalContext\n  localInstances : LocalInstances\n\n/--\n  Auxiliary structure for representing postponed universe constraints.\n  Remark: the fields `ref` and `rootDefEq?` are used for error message generation only.\n  Remark: we may consider improving the error message generation in the future.\n-/\nstructure PostponedEntry where\n  /-- We save the `ref` at entry creation time. This is used for reporting errors back to the user. -/\n  ref  : Syntax\n  lhs  : Level\n  rhs  : Level\n  /-- Context for the surrounding `isDefEq` call when entry was created. -/\n  ctx? : Option DefEqContext\n  deriving Inhabited\n\n/--\n  `MetaM` monad state.\n-/\nstructure State where\n  mctx           : MetavarContext := {}\n  cache          : Cache := {}\n  /-- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/\n  zetaFVarIds    : FVarIdSet := {}\n  /-- Array of postponed universe level constraints -/\n  postponed      : PersistentArray PostponedEntry := {}\n  deriving Inhabited\n\n/--\n  Backtrackable state for the `MetaM` monad.\n-/\nstructure SavedState where\n  core        : Core.State\n  meta        : State\n  deriving Nonempty\n\n/--\n  Contextual information for the `MetaM` monad.\n-/\nstructure Context where\n  config            : Config               := {}\n  /-- Local context -/\n  lctx              : LocalContext         := {}\n  /-- Local instances in `lctx`. -/\n  localInstances    : LocalInstances       := #[]\n  /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/\n  defEqCtx?         : Option DefEqContext  := none\n  /--\n    Track the number of nested `synthPending` invocations. Nested invocations can happen\n    when the type class resolution invokes `synthPending`.\n\n    Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`.\n    We will add a configuration option if necessary. -/\n  synthPendingDepth : Nat                  := 0\n  /--\n    A predicate to control whether a constant can be unfolded or not at `whnf`.\n    Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/\n  canUnfold?        : Option (Config \u2192 ConstantInfo \u2192 CoreM Bool) := none\n\nabbrev MetaM  := ReaderT Context $ StateRefT State CoreM\n\n-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the\n-- whole monad stack at every use site. May eventually be covered by `deriving`.\n@[always_inline]\ninstance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind }\n\ninstance : Inhabited (MetaM \u03b1) where\n  default := fun _ _ => default\n\ninstance : MonadLCtx MetaM where\n  getLCtx := return (\u2190 read).lctx\n\ninstance : MonadMCtx MetaM where\n  getMCtx    := return (\u2190 get).mctx\n  modifyMCtx f := modify fun s => { s with mctx := f s.mctx }\n\ninstance : MonadEnv MetaM where\n  getEnv      := return (\u2190 getThe Core.State).env\n  modifyEnv f := do modifyThe Core.State fun s => { s with env := f s.env, cache := {} }; modify fun s => { s with cache := {} }\n\ninstance : AddMessageContext MetaM where\n  addMessageContext := addMessageContextFull\n\nprotected def saveState : MetaM SavedState :=\n  return { core := (\u2190 getThe Core.State), meta := (\u2190 get) }\n\n/-- Restore backtrackable parts of the state. -/\ndef SavedState.restore (b : SavedState) : MetaM Unit := do\n  Core.restore b.core\n  modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed }\n\ninstance : MonadBacktrack SavedState MetaM where\n  saveState      := Meta.saveState\n  restoreState s := s.restore\n\n@[inline] def MetaM.run (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM (\u03b1 \u00d7 State) :=\n  x ctx |>.run s\n\n@[inline] def MetaM.run' (x : MetaM \u03b1) (ctx : Context := {}) (s : State := {}) : CoreM \u03b1 :=\n  Prod.fst <$> x.run ctx s\n\n@[inline] def MetaM.toIO (x : MetaM \u03b1) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (\u03b1 \u00d7 Core.State \u00d7 State) := do\n  let ((a, s), sCore) \u2190 (x.run ctx s).toIO ctxCore sCore\n  pure (a, sCore, s)\n\ninstance [MetaEval \u03b1] : MetaEval (MetaM \u03b1) :=\n  \u27e8fun env opts x _ => MetaEval.eval env opts x.run' true\u27e9\n\nprotected def throwIsDefEqStuck : MetaM \u03b1 :=\n  throw <| Exception.internal isDefEqStuckExceptionId\n\nbuiltin_initialize\n  registerTraceClass `Meta\n  registerTraceClass `Meta.debug\n\nexport Core (instantiateTypeLevelParams instantiateValueLevelParams)\n\n@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM \u03b1) : m \u03b1 :=\n  liftM x\n\n@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, MetaM \u03b1 \u2192 MetaM \u03b1) {\u03b1} (x : m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f <| runInBase x\n\n@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b => runInBase <| k b\n\n@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {\u03b1}, (\u03b2 \u2192 \u03b3 \u2192 MetaM \u03b1) \u2192 MetaM \u03b1) {\u03b1} (k : \u03b2 \u2192 \u03b3 \u2192 m \u03b1) : m \u03b1 :=\n  controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c\n\nsection Methods\nvariable [MonadControlT MetaM n] [Monad n]\n\n@[inline] def modifyCache (f : Cache \u2192 Cache) : MetaM Unit :=\n  modify fun \u27e8mctx, cache, zetaFVarIds, postponed\u27e9 => \u27e8mctx, f cache, zetaFVarIds, postponed\u27e9\n\n@[inline] def modifyInferTypeCache (f : InferTypeCache \u2192 InferTypeCache) : MetaM Unit :=\n  modifyCache fun \u27e8ic, c1, c2, c3, c4, c5\u27e9 => \u27e8f ic, c1, c2, c3, c4, c5\u27e9\n\n@[inline] def modifyDefEqCache (f : DefEqCache \u2192 DefEqCache) : MetaM Unit :=\n  modifyCache fun \u27e8c1, c2, c3, c4, c5, defeq\u27e9 => \u27e8c1, c2, c3, c4, c5, f defeq\u27e9\n\ndef getLocalInstances : MetaM LocalInstances :=\n  return (\u2190 read).localInstances\n\ndef getConfig : MetaM Config :=\n  return (\u2190 read).config\n\ndef resetZetaFVarIds : MetaM Unit :=\n  modify fun s => { s with zetaFVarIds := {} }\n\ndef getZetaFVarIds : MetaM FVarIdSet :=\n  return (\u2190 get).zetaFVarIds\n\n/-- Return the array of postponed universe level constraints. -/\ndef getPostponed : MetaM (PersistentArray PostponedEntry) :=\n  return (\u2190 get).postponed\n\n/-- Set the array of postponed universe level constraints. -/\ndef setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := postponed }\n\n/-- Modify the array of postponed universe level constraints. -/\n@[inline] def modifyPostponed (f : PersistentArray PostponedEntry \u2192 PersistentArray PostponedEntry) : MetaM Unit :=\n  modify fun s => { s with postponed := f s.postponed }\n\n/--\n  `useEtaStruct inductName` return `true` if we eta for structures is enabled for\n  for the inductive datatype `inductName`.\n\n  Recall we have three different settings: `.none` (never use it), `.all` (always use it), `.notClasses`\n  (enabled only for structure-like inductive types that are not classes).\n\n  The parameter `inductName` affects the result only if the current setting is `.notClasses`.\n-/\ndef useEtaStruct (inductName : Name) : MetaM Bool := do\n  match (\u2190 getConfig).etaStruct with\n  | .none => return false\n  | .all  => return true\n  | .notClasses => return !isClass (\u2190 getEnv) inductName\n\n/-! WARNING: The following 4 constants are a hack for simulating forward declarations.\n   They are defined later using the `export` attribute. This is hackish because we\n   have to hard-code the true arity of these definitions here, and make sure the C names match.\n   We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/\n\n/-- Reduces an expression to its Weak Head Normal Form.\nThis is when the topmost expression has been fully reduced,\nbut may contain subexpressions which have not been reduced. -/\n@[extern 6 \"lean_whnf\"] opaque whnf : Expr \u2192 MetaM Expr\n/-- Returns the inferred type of the given expression, or fails if it is not type-correct. -/\n@[extern 6 \"lean_infer_type\"] opaque inferType : Expr \u2192 MetaM Expr\n@[extern 7 \"lean_is_expr_def_eq\"] opaque isExprDefEqAux : Expr \u2192 Expr \u2192 MetaM Bool\n@[extern 7 \"lean_is_level_def_eq\"] opaque isLevelDefEqAux : Level \u2192 Level \u2192 MetaM Bool\n@[extern 6 \"lean_synth_pending\"] protected opaque synthPending : MVarId \u2192 MetaM Bool\n\ndef whnfForall (e : Expr) : MetaM Expr := do\n  let e' \u2190 whnf e\n  if e'.isForall then pure e' else pure e\n\n-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`\nprotected def withIncRecDepth (x : n \u03b1) : n \u03b1 :=\n  mapMetaM (withIncRecDepth (m := MetaM)) x\n\nprivate def mkFreshExprMVarAtCore\n    (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do\n  modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;\n  return mkMVar mvarId\n\ndef mkFreshExprMVarAt\n    (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  mkFreshExprMVarAtCore (\u2190 mkFreshMVarId) lctx localInsts type kind userName numScopeArgs\n\ndef mkFreshLevelMVar : MetaM Level := do\n  let mvarId \u2190 mkFreshLMVarId\n  modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;\n  return mkLevelMVar mvarId\n\nprivate def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do\n  mkFreshExprMVarAt (\u2190 getLCtx) (\u2190 getLocalInstances) type kind userName\n\nprivate def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarCore type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous\n    mkFreshExprMVarCore type kind userName\n\ndef mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  mkFreshExprMVarImpl type? kind userName\n\ndef mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  mkFreshExprMVar (mkSort u) kind userName\n\n/-- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create\n   the metavar using this method. -/\nprivate def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)\n    (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)\n    : MetaM Expr := do\n  mkFreshExprMVarAtCore mvarId (\u2190 getLCtx) (\u2190 getLocalInstances) type kind userName numScopeArgs\n\ndef mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=\n  match type? with\n  | some type => mkFreshExprMVarWithIdCore mvarId type kind userName\n  | none      => do\n    let u \u2190 mkFreshLevelMVar\n    let type \u2190 mkFreshExprMVar (mkSort u)\n    mkFreshExprMVarWithIdCore mvarId type kind userName\n\ndef mkFreshLevelMVars (num : Nat) : MetaM (List Level) :=\n  num.foldM (init := []) fun _ us =>\n    return (\u2190 mkFreshLevelMVar)::us\n\ndef mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) :=\n  mkFreshLevelMVars info.numLevelParams\n\n/--\nCreate a constant with the given name and new universe metavariables.\nExample: ``mkConstWithFreshMVarLevels `Monad`` returns `@Monad.{?u, ?v}`\n-/\ndef mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do\n  let info \u2190 getConstInfo declName\n  return mkConst declName (\u2190 mkFreshLevelMVarsFor info)\n\n/-- Return current transparency setting/mode. -/\ndef getTransparency : MetaM TransparencyMode :=\n  return (\u2190 getConfig).transparency\n\ndef shouldReduceAll : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.all\n\ndef shouldReduceReducibleOnly : MetaM Bool :=\n  return (\u2190 getTransparency) == TransparencyMode.reducible\n\n/--\nReturn `some mvarDecl` where `mvarDecl` is `mvarId` declaration in the current metavariable context.\nReturn `none` if `mvarId` has no declaration in the current metavariable context.\n-/\ndef _root_.Lean.MVarId.findDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) :=\n  return (\u2190 getMCtx).findDecl? mvarId\n\n@[deprecated MVarId.findDecl?]\ndef findMVarDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) :=\n  mvarId.findDecl?\n\n/--\nReturn `mvarId` declaration in the current metavariable context.\nThrow an exception if `mvarId` is not declarated in the current metavariable context.\n-/\ndef _root_.Lean.MVarId.getDecl (mvarId : MVarId) : MetaM MetavarDecl := do\n  match (\u2190 mvarId.findDecl?) with\n  | some d => pure d\n  | none   => throwError \"unknown metavariable '?{mvarId.name}'\"\n\n@[deprecated MVarId.getDecl]\ndef getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do\n  mvarId.getDecl\n\n/--\nReturn `mvarId` kind. Throw an exception if `mvarId` is not declarated in the current metavariable context.\n-/\ndef _root_.Lean.MVarId.getKind (mvarId : MVarId) : MetaM MetavarKind :=\n  return (\u2190 mvarId.getDecl).kind\n\n@[deprecated MVarId.getKind]\ndef getMVarDeclKind (mvarId : MVarId) : MetaM MetavarKind :=\n  mvarId.getKind\n\n/-- Reture `true` if `e` is a synthetic (or synthetic opaque) metavariable -/\ndef isSyntheticMVar (e : Expr) : MetaM Bool := do\n  if e.isMVar then\n     return (\u2190 e.mvarId!.getKind) matches .synthetic | .syntheticOpaque\n  else\n     return false\n\n/--\nSet `mvarId` kind in the current metavariable context.\n-/\ndef _root_.Lean.MVarId.setKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.setMVarKind mvarId kind\n\n@[deprecated MVarId.setKind]\ndef setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=\n  mvarId.setKind kind\n\n/-- Update the type of the given metavariable. This function assumes the new type is\n   definitionally equal to the current one -/\ndef _root_.Lean.MVarId.setType (mvarId : MVarId) (type : Expr) : MetaM Unit := do\n  modifyMCtx fun mctx => mctx.setMVarType mvarId type\n\n@[deprecated MVarId.setType]\ndef setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do\n  mvarId.setType type\n\n/--\nReturn true if the given metavariable is \"read-only\".\nThat is, its `depth` is different from the current metavariable context depth.\n-/\ndef _root_.Lean.MVarId.isReadOnly (mvarId : MVarId) : MetaM Bool := do\n  return (\u2190 mvarId.getDecl).depth != (\u2190 getMCtx).depth\n\n@[deprecated MVarId.isReadOnly]\ndef isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do\n  mvarId.isReadOnly\n\n/--\nReturn true if `mvarId.isReadOnly` return true or if `mvarId` is a synthetic opaque metavariable.\n\nRecall `isDefEq` will not assign a value to `mvarId` if `mvarId.isReadOnlyOrSyntheticOpaque`.\n-/\ndef _root_.Lean.MVarId.isReadOnlyOrSyntheticOpaque (mvarId : MVarId) : MetaM Bool := do\n  let mvarDecl \u2190 mvarId.getDecl\n  match mvarDecl.kind with\n  | MetavarKind.syntheticOpaque => return !(\u2190 getConfig).assignSyntheticOpaque\n  | _ => return mvarDecl.depth != (\u2190 getMCtx).depth\n\n@[deprecated MVarId.isReadOnlyOrSyntheticOpaque]\ndef isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do\n  mvarId.isReadOnlyOrSyntheticOpaque\n\n/--\nReturn the level of the given universe level metavariable.\n-/\ndef _root_.Lean.LMVarId.getLevel (mvarId : LMVarId) : MetaM Nat := do\n  match (\u2190 getMCtx).findLevelDepth? mvarId with\n  | some depth => return depth\n  | _          => throwError \"unknown universe metavariable '?{mvarId.name}'\"\n\n@[deprecated LMVarId.getLevel]\ndef getLevelMVarDepth (mvarId : LMVarId) : MetaM Nat :=\n  mvarId.getLevel\n\n/--\nReturn true if the given universe metavariable is \"read-only\".\nThat is, its `depth` is different from the current metavariable context depth.\n-/\ndef _root_.Lean.LMVarId.isReadOnly (mvarId : LMVarId) : MetaM Bool :=\n  return (\u2190 mvarId.getLevel) < (\u2190 getMCtx).levelAssignDepth\n\n@[deprecated LMVarId.isReadOnly]\ndef isReadOnlyLevelMVar (mvarId : LMVarId) : MetaM Bool := do\n  mvarId.isReadOnly\n\n/--\nSet the user-facing name for the given metavariable.\n-/\ndef _root_.Lean.MVarId.setUserName (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=\n  modifyMCtx fun mctx => mctx.setMVarUserName mvarId newUserName\n\n@[deprecated MVarId.setUserName]\ndef setMVarUserName (mvarId : MVarId) (userNameNew : Name) : MetaM Unit :=\n  mvarId.setUserName userNameNew\n\n/--\nThrow an exception saying `fvarId` is not declared in the current local context.\n-/\ndef _root_.Lean.FVarId.throwUnknown (fvarId : FVarId) : CoreM \u03b1 :=\n  throwError \"unknown free variable '{mkFVar fvarId}'\"\n\n@[deprecated FVarId.throwUnknown]\ndef throwUnknownFVar (fvarId : FVarId) : MetaM \u03b1 :=\n  fvarId.throwUnknown\n\n/--\nReturn `some decl` if `fvarId` is declared in the current local context.\n-/\ndef _root_.Lean.FVarId.findDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=\n  return (\u2190 getLCtx).find? fvarId\n\n@[deprecated FVarId.findDecl?]\ndef findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=\n  fvarId.findDecl?\n\n/--\n  Return the local declaration for the given free variable.\n  Throw an exception if local declaration is not in the current local context.\n-/\ndef _root_.Lean.FVarId.getDecl (fvarId : FVarId) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).find? fvarId with\n  | some d => return d\n  | none   => fvarId.throwUnknown\n\n@[deprecated FVarId.getDecl]\ndef getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do\n  fvarId.getDecl\n\n/-- Return the type of the given free variable. -/\ndef _root_.Lean.FVarId.getType (fvarId : FVarId) : MetaM Expr :=\n  return (\u2190 fvarId.getDecl).type\n\n/-- Return the binder information for the given free variable. -/\ndef _root_.Lean.FVarId.getBinderInfo (fvarId : FVarId) : MetaM BinderInfo :=\n  return (\u2190 fvarId.getDecl).binderInfo\n\n/-- Return `some value` if the given free variable is a let-declaration, and `none` otherwise. -/\ndef _root_.Lean.FVarId.getValue? (fvarId : FVarId) : MetaM (Option Expr) :=\n  return (\u2190 fvarId.getDecl).value?\n\n/-- Return the user-facing name for the given free variable. -/\ndef _root_.Lean.FVarId.getUserName (fvarId : FVarId) : MetaM Name :=\n  return (\u2190 fvarId.getDecl).userName\n\n/-- Return `true` is the free variable is a let-variable. -/\ndef _root_.Lean.FVarId.isLetVar (fvarId : FVarId) : MetaM Bool :=\n  return (\u2190 fvarId.getDecl).isLet\n\n/-- Get the local declaration associated to the given `Expr` in the current local\ncontext. Fails if the given expression is not a fvar or if no such declaration exists. -/\ndef getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=\n  fvar.fvarId!.getDecl\n\n/--\nGiven a user-facing name for a free variable, return its declaration in the current local context.\nThrow an exception if free variable is not declared.\n-/\ndef getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do\n  match (\u2190 getLCtx).findFromUserName? userName with\n  | some d => pure d\n  | none   => throwError \"unknown local declaration '{userName}'\"\n\n/-- Given a user-facing name for a free variable, return the free variable or throw if not declared. -/\ndef getFVarFromUserName (userName : Name) : MetaM Expr := do\n  let d \u2190 getLocalDeclFromUserName userName\n  return Expr.fvar d.fvarId\n\n/--\nLift a `MkBindingM` monadic action `x` to `MetaM`.\n-/\n@[inline] def liftMkBindingM (x : MetavarContext.MkBindingM \u03b1) : MetaM \u03b1 := do\n  match x { lctx := (\u2190 getLCtx), mainModule := (\u2190 getEnv).mainModule } { mctx := (\u2190 getMCtx), ngen := (\u2190 getNGen), nextMacroScope := (\u2190 getThe Core.State).nextMacroScope } with\n  | .ok e sNew => do\n    setMCtx sNew.mctx\n    modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope }\n    pure e\n  | .error (.revertFailure ..) sNew => do\n    setMCtx sNew.mctx\n    modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope }\n    throwError \"failed to create binder due to failure when reverting variable dependencies\"\n\n/--\nSimilar to `abstracM` but consider only the first `min n xs.size` entries in `xs`\n\nIt is also similar to `Expr.abstractRange`, but handles metavariables correctly.\nIt uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not\ncontain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`.\n-/\ndef _root_.Lean.Expr.abstractRangeM (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr :=\n  liftMkBindingM <| MetavarContext.abstractRange e n xs\n\n@[deprecated Expr.abstractRangeM]\ndef abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr :=\n  e.abstractRangeM n xs\n\n/--\nReplace free (or meta) variables `xs` with loose bound variables.\nSimilar to `Expr.abstract`, but handles metavariables correctly.\n-/\ndef _root_.Lean.Expr.abstractM (e : Expr) (xs : Array Expr) : MetaM Expr :=\n  e.abstractRangeM xs.size xs\n\n@[deprecated Expr.abstractM]\ndef abstract (e : Expr) (xs : Array Expr) : MetaM Expr :=\n  e.abstractM xs\n\n/--\nCollect forward dependencies for the free variables in `toRevert`.\nRecall that when reverting free variables `xs`, we must also revert their forward dependencies.\n-/\ndef collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MetaM (Array Expr) := do\n  liftMkBindingM <| MetavarContext.collectForwardDeps toRevert preserveOrder\n\n/-- Takes an array `xs` of free variables or metavariables and a term `e` that may contain those variables, and abstracts and binds them as universal quantifiers.\n\n- if `usedOnly = true` then only variables that the expression body depends on will appear.\n- if `usedLetOnly = true` same as `usedOnly` except for let-bound variables. (That is, local constants which have been assigned a value.)\n -/\ndef mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr :=\n  if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly binderInfoForMVars\n\n/-- Takes an array `xs` of free variables and metavariables and a\nbody term `e` and creates `fun ..xs => e`, suitably\nabstracting `e` and the types in `xs`. -/\ndef mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr :=\n  if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly binderInfoForMVars\n\ndef mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr :=\n  mkLambdaFVars xs e (usedLetOnly := usedLetOnly) (binderInfoForMVars := binderInfoForMVars)\n\n/-- `fun _ : Unit => a` -/\ndef mkFunUnit (a : Expr) : MetaM Expr :=\n  return Lean.mkLambda (\u2190 mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a\n\ndef elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=\n  if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder\n\n/-- `withConfig f x` executes `x` using the updated configuration object obtained by applying `f`. -/\n@[inline] def withConfig (f : Config \u2192 Config) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })\n\n@[inline] def withTrackingZeta (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with trackZeta := true }) x\n\n@[inline] def withoutProofIrrelevance (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun cfg => { cfg with proofIrrelevance := false }) x\n\n@[inline] def withTransparency (mode : TransparencyMode) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withConfig (fun config => { config with transparency := mode })\n\n/-- `withDefault x` excutes `x` using the default transparency setting. -/\n@[inline] def withDefault (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.default x\n\n/-- `withReducible x` excutes `x` using the reducible transparency setting. In this setting only definitions tagged as `[reducible]` are unfolded. -/\n@[inline] def withReducible (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.reducible x\n\n/--\n`withReducibleAndInstances x` excutes `x` using the `.instances` transparency setting. In this setting only definitions tagged as `[reducible]`\nor type class instances are unfolded.\n-/\n@[inline] def withReducibleAndInstances (x : n \u03b1) : n \u03b1 :=\n  withTransparency TransparencyMode.instances x\n\n/--\nExecute `x` ensuring the transparency setting is at least `mode`.\nRecall that `.all > .default > .instances > .reducible`.\n-/\n@[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n \u03b1) : n \u03b1 :=\n  withConfig\n    (fun config =>\n      let oldMode := config.transparency\n      let mode    := if oldMode.lt mode then mode else oldMode\n      { config with transparency := mode })\n    x\n\n/-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/\n@[inline] def withAssignableSyntheticOpaque (x : n \u03b1) : n \u03b1 :=\n  withConfig (fun config => { config with assignSyntheticOpaque := true }) x\n\n/-- Save cache, execute `x`, restore cache -/\n@[inline] private def savingCacheImpl (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let savedCache := (\u2190 get).cache\n  try x finally modify fun s => { s with cache := savedCache }\n\n@[inline] def savingCache : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM savingCacheImpl\n\ndef getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  if (\u2190 shouldReduceAll) then\n    return some info\n  else\n    return none\n\nprivate def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getTransparency) with\n  | TransparencyMode.all => return some info\n  | TransparencyMode.default => return some info\n  | _ =>\n    if (\u2190 isReducible info.name) then\n      return some info\n    else\n      return none\n\n/-- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.\n   This method is only used to implement `isClassQuickConst?`.\n   It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and\n   `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/\nprivate def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do\n  match (\u2190 getEnv).find? constName with\n  | some (info@(ConstantInfo.thmInfo _))  => getTheoremInfo info\n  | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info\n  | some info                             => pure (some info)\n  | none                                  => throwUnknownConstant constName\n\nprivate def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do\n  if isClass (\u2190 getEnv) constName then\n    return .some constName\n  else\n    match (\u2190 getConstTemp? constName) with\n    | some (.defnInfo ..) => return .undef -- We may be able to unfold the definition\n    | _ => return .none\n\nprivate partial def isClassQuick? : Expr \u2192 MetaM (LOption Name)\n  | .bvar ..         => return .none\n  | .lit ..          => return .none\n  | .fvar ..         => return .none\n  | .sort ..         => return .none\n  | .lam ..          => return .none\n  | .letE ..         => return .undef\n  | .proj ..         => return .undef\n  | .forallE _ _ b _ => isClassQuick? b\n  | .mdata _ e       => isClassQuick? e\n  | .const n _       => isClassQuickConst? n\n  | .mvar mvarId     => do\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => isClassQuick? val\n    | none     => return .none\n  | .app f _         =>\n    match f.getAppFn with\n    | .const n .. => isClassQuickConst? n\n    | .lam ..     => return .undef\n    | _           => return .none\n\nprivate def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let localDecl \u2190 getFVarLocalDecl fvar\n  if localDecl.isImplementationDetail then\n    k\n  else\n    withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k\n\n/-- Add entry `{ className := className, fvar := fvar }` to localInstances,\n    and then execute continuation `k`. -/\ndef withNewLocalInstance (className : Name) (fvar : Expr) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstanceImp className fvar\n\nprivate def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=\n  match maxFVars? with\n  | some maxFVars => fvars.size < maxFVars\n  | none          => true\n\nmutual\n  /--\n    `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances\n    using free variables `fvars[j] ... fvars.back`, and execute `k`.\n\n    - `isClassExpensive` is defined later.\n    - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. -/\n  private partial def withNewLocalInstancesImp\n      (fvars : Array Expr) (i : Nat) (k : MetaM \u03b1) : MetaM \u03b1 := do\n    if h : i < fvars.size then\n      let fvar := fvars.get \u27e8i, h\u27e9\n      let decl \u2190 getFVarLocalDecl fvar\n      match (\u2190 isClassQuick? decl.type) with\n      | .none   => withNewLocalInstancesImp fvars (i+1) k\n      | .undef  =>\n        match (\u2190 isClassExpensive? decl.type) with\n        | none   => withNewLocalInstancesImp fvars (i+1) k\n        | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n      | .some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k\n    else\n      k\n\n  /--\n    `forallTelescopeAuxAux lctx fvars j type`\n    Remarks:\n    - `lctx` is the `MetaM` local context extended with declarations for `fvars`.\n    - `type` is the type we are computing the telescope for. It contains only\n      dangling bound variables in the range `[j, fvars.size)`\n    - if `reducing? == true` and `type` is not `forallE`, we use `whnf`.\n    - when `type` is not a `forallE` nor it can't be reduced to one, we\n      excute the continuation `k`.\n\n    Here is an example that demonstrates the `reducing?`.\n    Suppose we have\n    ```\n    abbrev StateM s a := s -> Prod a s\n    ```\n    Now, assume we are trying to build the telescope for\n    ```\n    forall (x : Nat), StateM Int Bool\n    ```\n    if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.\n    if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`\n\n    if `maxFVars?` is `some max`, then we interrupt the telescope construction\n    when `fvars.size == max`\n  -/\n  private partial def forallTelescopeReducingAuxAux\n      (reducing          : Bool) (maxFVars? : Option Nat)\n      (type              : Expr)\n      (k                 : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM \u03b1 := do\n      match type with\n      | .forallE n d b bi =>\n        if fvarsSizeLtMaxFVars fvars maxFVars? then\n          let d     := d.instantiateRevRange j fvars.size fvars\n          let fvarId \u2190 mkFreshFVarId\n          let lctx  := lctx.mkLocalDecl fvarId n d bi\n          let fvar  := mkFVar fvarId\n          let fvars := fvars.push fvar\n          process lctx fvars j b\n        else\n          let type := type.instantiateRevRange j fvars.size fvars;\n          withReader (fun ctx => { ctx with lctx := lctx }) do\n            withNewLocalInstancesImp fvars j do\n              k fvars type\n      | _ =>\n        let type := type.instantiateRevRange j fvars.size fvars;\n        withReader (fun ctx => { ctx with lctx := lctx }) do\n          withNewLocalInstancesImp fvars j do\n            if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then\n              let newType \u2190 whnf type\n              if newType.isForall then\n                process lctx fvars fvars.size newType\n              else\n                k fvars type\n            else\n              k fvars type\n    process (\u2190 getLCtx) #[] 0 type\n\n  private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    match maxFVars? with\n    | some 0 => k #[] type\n    | _ => do\n      let newType \u2190 whnf type\n      if newType.isForall then\n        forallTelescopeReducingAuxAux true maxFVars? newType k\n      else\n        k #[] type\n\n  private partial def isClassExpensive? (type : Expr) : MetaM (Option Name) :=\n    withReducible do -- when testing whether a type is a type class, we only unfold reducible constants.\n      forallTelescopeReducingAux type none fun _ type => do\n        let env \u2190 getEnv\n        match type.getAppFn with\n        | .const c _ => do\n          if isClass env c then\n            return some c\n          else\n            -- make sure abbreviations are unfolded\n            match (\u2190 whnf type).getAppFn with\n            | .const c _ => return if isClass env c then some c else none\n            | _ => return none\n        | _ => return none\n\n  private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do\n    match (\u2190 isClassQuick? type) with\n    | .none   => return none\n    | .some c => return (some c)\n    | .undef  => isClassExpensive? type\n\nend\n\n/--\n  `isClass? type` return `some ClsName` if `type` is an instance of the class `ClsName`.\n  Example:\n  ```\n  #eval do\n    let x \u2190 mkAppM ``Inhabited #[mkConst ``Nat]\n    IO.println (\u2190 isClass? x)\n    -- (some Inhabited)\n  ```\n-/\ndef isClass? (type : Expr) : MetaM (Option Name) :=\n  try isClassImp? type catch _ => return none\n\nprivate def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImp fvars j\n\npartial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withNewLocalInstancesImpAux fvars j\n\n@[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k\n\n/--\n  Given `type` of the form `forall xs, A`, execute `k xs A`.\n  This combinator will declare local declarations, create free variables for them,\n  execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/\ndef forallTelescope (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeImp type k) k\n\nprivate def forallTelescopeReducingImp (type : Expr) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type (maxFVars? := none) k\n\n/--\n  Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,\n  it reduces `A` and continues bulding the telescope if it is a `forall`. -/\ndef forallTelescopeReducing (type : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallTelescopeReducingImp type k) k\n\nprivate def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n  forallTelescopeReducingAux type maxFVars? k\n\n/--\n  Similar to `forallTelescopeReducing`, stops constructing the telescope when\n  it reaches size `maxFVars`. -/\ndef forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k\n\nprivate partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr \u2192 Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  process consumeLet (\u2190 getLCtx) #[] 0 e\nwhere\n  process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM \u03b1 := do\n    match consumeLet, e with\n    | _, .lam n d b bi =>\n      let d := d.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshFVarId\n      let lctx := lctx.mkLocalDecl fvarId n d bi\n      let fvar := mkFVar fvarId\n      process consumeLet lctx (fvars.push fvar) j b\n    | true, .letE n t v b _ => do\n      let t := t.instantiateRevRange j fvars.size fvars\n      let v := v.instantiateRevRange j fvars.size fvars\n      let fvarId \u2190 mkFreshFVarId\n      let lctx := lctx.mkLetDecl fvarId n t v\n      let fvar := mkFVar fvarId\n      process true lctx (fvars.push fvar) j b\n    | _, e =>\n      let e := e.instantiateRevRange j fvars.size fvars\n      withReader (fun ctx => { ctx with lctx := lctx }) do\n        withNewLocalInstancesImp fvars j do\n          k fvars e\n\n/-- Similar to `lambdaTelescope` but for lambda and let expressions. -/\ndef lambdaLetTelescope (e : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp e true k) k\n\n/--\n  Given `e` of the form `fun ..xs => A`, execute `k xs A`.\n  This combinator will declare local declarations, create free variables for them,\n  execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/\ndef lambdaTelescope (e : Expr) (k : Array Expr \u2192 Expr \u2192 n \u03b1) : n \u03b1 :=\n  map2MetaM (fun k => lambdaTelescopeImp e false k) k\n\n/-- Return the parameter names for the given global declaration. -/\ndef getParamNames (declName : Name) : MetaM (Array Name) := do\n  forallTelescopeReducing (\u2190 getConstInfo declName).type fun xs _ => do\n    xs.mapM fun x => do\n      let localDecl \u2190 x.fvarId!.getDecl\n      return localDecl.userName\n\n-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.\nprivate partial def forallMetaTelescopeReducingAux\n    (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  process #[] #[] 0 e\nwhere\n  process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    if maxMVars?.isEqSome mvars.size then\n      let type := type.instantiateRevRange j mvars.size mvars;\n      return (mvars, bis, type)\n    else\n      match type with\n      | .forallE n d b bi =>\n        let d  := d.instantiateRevRange j mvars.size mvars\n        let k  := if bi.isInstImplicit then  MetavarKind.synthetic else kind\n        let mvar \u2190 mkFreshExprMVar d k n\n        let mvars := mvars.push mvar\n        let bis   := bis.push bi\n        process mvars bis j b\n      | _ =>\n        let type := type.instantiateRevRange j mvars.size mvars;\n        if reducing then do\n          let newType \u2190 whnf type;\n          if newType.isForall then\n            process mvars bis mvars.size newType\n          else\n            return (mvars, bis, type)\n        else\n          return (mvars, bis, type)\n\n/-- Given `e` of the form `forall ..xs, A`, this combinator will create a new\n  metavariable for each `x` in `xs` and instantiate `A` with these.\n  Returns a product containing\n  - the new metavariables\n  - the binder info for the `xs`\n  - the instantiated `A`\n  -/\ndef forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind\n\n/-- Similar to `forallMetaTelescope`, but if `e = forall ..xs, A`\nit will reduce `A` to construct further mvars.  -/\ndef forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind\n\n/-- Similar to `forallMetaTelescopeReducing`, stops\nconstructing the telescope when it reaches size `maxMVars`. -/\ndef forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind)\n\n/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/\npartial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) :=\n  process #[] #[] 0 e\nwhere\n  process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := do\n    let finalize : Unit \u2192 MetaM (Array Expr \u00d7 Array BinderInfo \u00d7 Expr) := fun _ => do\n      let type := type.instantiateRevRange j mvars.size mvars\n      return (mvars, bis, type)\n    if maxMVars?.isEqSome mvars.size then\n      finalize ()\n    else\n      match type with\n      | .lam _ d b bi =>\n        let d     := d.instantiateRevRange j mvars.size mvars\n        let mvar \u2190 mkFreshExprMVar d\n        let mvars := mvars.push mvar\n        let bis   := bis.push bi\n        process mvars bis j b\n      | _ => finalize ()\n\nprivate def withNewFVar (n : Name) (fvar fvarType : Expr) (k : Expr \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  if let some c \u2190 isClass? fvarType then\n    withNewLocalInstance c fvar <| k fvar\n  else\n    k fvar\n\nprivate def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 MetaM \u03b1) (kind : LocalDeclKind) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshFVarId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLocalDecl fvarId n type bi kind\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar n fvar type k\n\n/-- Create a free variable `x` with name, binderInfo and type, add it to the context and run in `k`.\nThen revert the context. -/\ndef withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr \u2192 n \u03b1) (kind : LocalDeclKind := .default) : n \u03b1 :=\n  map1MetaM (fun k => withLocalDeclImp name bi type k kind) k\n\ndef withLocalDeclD (name : Name) (type : Expr) (k : Expr \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecl name BinderInfo.default type k\n\n/-- Append an array of free variables `xs` to the local context and execute `k xs`.\ndeclInfos takes the form of an array consisting of:\n- the name of the variable\n- the binder info of the variable\n- a type constructor for the variable, where the array consists of all of the free variables\n  defined prior to this one. This is needed because the type of the variable may depend on prior variables.\n-/\npartial def withLocalDecls\n    [Inhabited \u03b1]\n    (declInfos : Array (Name \u00d7 BinderInfo \u00d7 (Array Expr \u2192 n Expr)))\n    (k : (xs : Array Expr) \u2192 n \u03b1)\n    : n \u03b1 :=\n  loop #[]\nwhere\n  loop [Inhabited \u03b1] (acc : Array Expr) : n \u03b1 := do\n    if acc.size < declInfos.size then\n      let (name, bi, typeCtor) := declInfos[acc.size]!\n      withLocalDecl name bi (\u2190typeCtor acc) fun x => loop (acc.push x)\n    else\n      k acc\n\ndef withLocalDeclsD [Inhabited \u03b1] (declInfos : Array (Name \u00d7 (Array Expr \u2192 n Expr))) (k : (xs : Array Expr) \u2192 n \u03b1) : n \u03b1 :=\n  withLocalDecls\n    (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k\n\nprivate def withNewBinderInfosImp (bs : Array (FVarId \u00d7 BinderInfo)) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let lctx := bs.foldl (init := (\u2190 getLCtx)) fun lctx (fvarId, bi) =>\n      lctx.setBinderInfo fvarId bi\n  withReader (fun ctx => { ctx with lctx := lctx }) k\n\ndef withNewBinderInfos (bs : Array (FVarId \u00d7 BinderInfo)) (k : n \u03b1) : n \u03b1 :=\n  mapMetaM (fun k => withNewBinderInfosImp bs k) k\n\n/--\n Execute `k` using a local context where any `x` in `xs` that is tagged as\n instance implicit is treated as a regular implicit. -/\ndef withInstImplicitAsImplict (xs : Array Expr) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let newBinderInfos \u2190 xs.filterMapM fun x => do\n    let bi \u2190 x.fvarId!.getBinderInfo\n    if bi == .instImplicit then\n      return some (x.fvarId!, .implicit)\n    else\n      return none\n  withNewBinderInfos newBinderInfos k\n\nprivate def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr \u2192 MetaM \u03b1) (kind : LocalDeclKind) : MetaM \u03b1 := do\n  let fvarId \u2190 mkFreshFVarId\n  let ctx \u2190 read\n  let lctx := ctx.lctx.mkLetDecl fvarId n type val (nonDep := false) kind\n  let fvar := mkFVar fvarId\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withNewFVar n fvar type k\n\n/--\n  Add the local declaration `<name> : <type> := <val>` to the local context and execute `k x`, where `x` is a new\n  free variable corresponding to the `let`-declaration. After executing `k x`, the local context is restored.\n-/\ndef withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr \u2192 n \u03b1) (kind : LocalDeclKind := .default) : n \u03b1 :=\n  map1MetaM (fun k => withLetDeclImp name type val k kind) k\n\ndef withLocalInstancesImp (decls : List LocalDecl) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let mut localInsts := (\u2190 read).localInstances\n  let size := localInsts.size\n  for decl in decls do\n    unless decl.isImplementationDetail do\n      if let some className \u2190 isClass? decl.type then\n        localInsts := localInsts.push { className, fvar := decl.toExpr }\n  if localInsts.size == size then\n    k\n  else\n    withReader (fun ctx => { ctx with localInstances := localInsts }) k\n\n/-- Register any local instance in `decls` -/\ndef withLocalInstances (decls : List LocalDecl) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withLocalInstancesImp decls\n\nprivate def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM \u03b1) : MetaM \u03b1 := do\n  let ctx \u2190 read\n  let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx\n  withReader (fun ctx => { ctx with lctx := lctx }) do\n    withLocalInstancesImp decls k\n\n/--\n  `withExistingLocalDecls decls k`, adds the given local declarations to the local context,\n  and then executes `k`. This method assumes declarations in `decls` have valid `FVarId`s.\n  After executing `k`, the local context is restored.\n\n  Remark: this method is used, for example, to implement the `match`-compiler.\n  Each `match`-alternative commes with a local declarations (corresponding to pattern variables),\n  and we use `withExistingLocalDecls` to add them to the local context before we process\n  them.\n-/\ndef withExistingLocalDecls (decls : List LocalDecl) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withExistingLocalDeclsImp decls\n\nprivate def withNewMCtxDepthImp (allowLevelAssignments : Bool) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let saved \u2190 get\n  modify fun s => { s with mctx := s.mctx.incDepth allowLevelAssignments, postponed := {} }\n  try\n    x\n  finally\n    modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed }\n\n/--\n  `withNewMCtxDepth k` executes `k` with a higher metavariable context depth,\n  where metavariables created outside the `withNewMCtxDepth` (with a lower depth) cannot be assigned.\n  If `allowLevelAssignments` is set to true, then the level metavariable depth\n  is not increased, and level metavariables from the outer scope can be\n  assigned.  (This is used by TC synthesis.)\n-/\ndef withNewMCtxDepth (k : n \u03b1) (allowLevelAssignments := false) : n \u03b1 :=\n  mapMetaM (withNewMCtxDepthImp allowLevelAssignments) k\n\nprivate def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do\n    x\n\n/--\n  `withLCtx lctx localInsts k` replaces the local context and local instances, and then executes `k`.\n  The local context and instances are restored after executing `k`.\n  This method assumes that the local instances in `localInsts` are in the local context `lctx`.\n-/\ndef withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withLocalContextImp lctx localInsts\n\nprivate def withMVarContextImp (mvarId : MVarId) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mvarDecl \u2190 mvarId.getDecl\n  withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x\n\n/--\n  Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.\n  The type class resolution cache is flushed when executing `x` if its `LocalInstances` are\n  different from the current ones. -/\ndef _root_.Lean.MVarId.withContext (mvarId : MVarId) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMVarContextImp mvarId\n\n@[deprecated MVarId.withContext]\ndef withMVarContext (mvarId : MVarId) : n \u03b1 \u2192 n \u03b1 :=\n  mvarId.withContext\n\nprivate def withMCtxImp (mctx : MetavarContext) (x : MetaM \u03b1) : MetaM \u03b1 := do\n  let mctx' \u2190 getMCtx\n  setMCtx mctx\n  try x finally setMCtx mctx'\n\n/--\n  `withMCtx mctx k` replaces the metavariable context and then executes `k`.\n  The metavariable context is restored after executing `k`.\n\n  This method is used to implement the type class resolution procedure. -/\ndef withMCtx (mctx : MetavarContext) : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM <| withMCtxImp mctx\n\n@[inline] private def approxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x\n\n/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`.  -/\n@[inline] def approxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM approxDefEqImp\n\n@[inline] private def fullApproxDefEqImp (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x\n\n/--\n  Similar to `approxDefEq`, but uses all available approximations.\n  We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.\n  For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.\n  Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved\n  as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to\n  solve `[Pure (fun _ => IO Bool)]` -/\n@[inline] def fullApproxDefEq : n \u03b1 \u2192 n \u03b1 :=\n  mapMetaM fullApproxDefEqImp\n\n/-- Instantiate assigned universe metavariables in `u`, and then normalize it. -/\ndef normalizeLevel (u : Level) : MetaM Level := do\n  let u \u2190 instantiateLevelMVars u\n  pure u.normalize\n\n/-- `whnf` with reducible transparency.-/\ndef whnfR (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.reducible <| whnf e\n\n/-- `whnf` with default transparency.-/\ndef whnfD (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.default <| whnf e\n\n/-- `whnf` with instances transparency.-/\ndef whnfI (e : Expr) : MetaM Expr :=\n  withTransparency TransparencyMode.instances <| whnf e\n\n/--\n  Mark declaration `declName` with the attribute `[inline]`.\n  This method does not check whether the given declaration is a definition.\n\n  Recall that this attribute can only be set in the same module where `declName` has been declared.\n-/\ndef setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do\n  let env \u2190 getEnv\n  match Compiler.setInlineAttribute env declName kind with\n  | .ok env    => setEnv env\n  | .error msg => throwError msg\n\nprivate partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    match (\u2190 whnf e) with\n    | .forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)\n    | _                => throwError \"invalid instantiateForall, too many parameters\"\n  else\n    return e\n\n/-- Given `e` 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`, return `B[p_1, ..., p_n]`. -/\ndef instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateForallAux ps 0 e\n\nprivate partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do\n  if h : i < ps.size then\n    let p := ps.get \u27e8i, h\u27e9\n    match (\u2190 whnf e) with\n    | .lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)\n    | _            => throwError \"invalid instantiateLambda, too many parameters\"\n  else\n    return e\n\n/-- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.\n   It uses `whnf` to reduce `e` if it is not a lambda -/\ndef instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=\n  instantiateLambdaAux ps 0 e\n\n/-- Pretty-print the given expression. -/\ndef ppExprWithInfos (e : Expr) : MetaM FormatWithInfos := do\n  let ctxCore  \u2190 readThe Core.Context\n  Lean.ppExprWithInfos { env := (\u2190 getEnv), mctx := (\u2190 getMCtx), lctx := (\u2190 getLCtx), opts := (\u2190 getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e\n\n/-- Pretty-print the given expression. -/\ndef ppExpr (e : Expr) : MetaM Format := (\u00b7.fmt) <$> ppExprWithInfos e\n\n@[inline] protected def orElse (x : MetaM \u03b1) (y : Unit \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n  let s \u2190 saveState\n  try x catch _ => s.restore; y ()\n\ninstance : OrElse (MetaM \u03b1) := \u27e8Meta.orElse\u27e9\n\ninstance : Alternative MetaM where\n  failure := fun {_} => throwError \"failed\"\n  orElse  := Meta.orElse\n\n@[inline] private def orelseMergeErrorsImp (x y : MetaM \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 _ => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ m\u2082) : MetaM \u03b1 := do\n  let env  \u2190 getEnv\n  let mctx \u2190 getMCtx\n  try\n    x\n  catch ex =>\n    setEnv env\n    setMCtx mctx\n    match ex with\n    | Exception.error ref\u2081 m\u2081 =>\n      try\n        y\n      catch\n        | Exception.error ref\u2082 m\u2082 => throw <| Exception.error (mergeRef ref\u2081 ref\u2082) (mergeMsg m\u2081 m\u2082)\n        | ex => throw ex\n    | ex => throw ex\n\n/--\n  Similar to `orelse`, but merge errors. Note that internal errors are not caught.\n  The default `mergeRef` uses the `ref` (position information) for the first message.\n  The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/\n@[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m \u03b1)\n    (mergeRef : Syntax \u2192 Syntax \u2192 Syntax := fun r\u2081 _ => r\u2081)\n    (mergeMsg : MessageData \u2192 MessageData \u2192 MessageData := fun m\u2081 m\u2082 => m\u2081 ++ Format.line ++ Format.line ++ m\u2082) : m \u03b1 := do\n  controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg\n\n/-- Execute `x`, and apply `f` to the produced error message -/\ndef mapErrorImp (x : MetaM \u03b1) (f : MessageData \u2192 MessageData) : MetaM \u03b1 := do\n  try\n    x\n  catch\n    | Exception.error ref msg => throw <| Exception.error ref <| f msg\n    | ex => throw ex\n\n@[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m \u03b1) (f : MessageData \u2192 MessageData) : m \u03b1 :=\n  controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f\n\n/--\n  Sort free variables using an order `x < y` iff `x` was defined before `y`.\n  If a free variable is not in the local context, we use their id. -/\ndef sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do\n  let lctx \u2190 getLCtx\n  return fvarIds.qsort fun fvarId\u2081 fvarId\u2082 =>\n    match lctx.find? fvarId\u2081, lctx.find? fvarId\u2082 with\n    | some d\u2081, some d\u2082 => d\u2081.index < d\u2082.index\n    | some _,  none    => false\n    | none,    some _  => true\n    | none,    none    => Name.quickLt fvarId\u2081.name fvarId\u2082.name\n\nend Methods\n\n/-- Return `true` if `declName` is an inductive predicate. That is, `inductive` type in `Prop`. -/\ndef isInductivePredicate (declName : Name) : MetaM Bool := do\n  match (\u2190 getEnv).find? declName with\n  | some (.inductInfo { type := type, ..}) =>\n    forallTelescopeReducing type fun _ type => do\n      match (\u2190 whnfD type) with\n      | .sort u .. => return u == levelZero\n      | _ => return false\n  | _ => return false\n\ndef isListLevelDefEqAux : List Level \u2192 List Level \u2192 MetaM Bool\n  | [],    []    => return true\n  | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs\n  | _,     _     => return false\n\ndef getNumPostponed : MetaM Nat := do\n  return (\u2190 getPostponed).size\n\ndef getResetPostponed : MetaM (PersistentArray PostponedEntry) := do\n  let ps \u2190 getPostponed\n  setPostponed {}\n  return ps\n\n/-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/\nprivate def exposeRelevantUniverses (e : Expr) (p : Level \u2192 Bool) : Expr :=\n  e.replace fun\n    | .const _ us => if us.any p then some (e.setPPUniverses true) else none\n    | .sort u     => if p u then some (e.setPPUniverses true) else none\n    | _           => none\n\nprivate def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do\n  match entry.ctx? with\n  | none =>\n    return m!\"{header}{indentD m!\"{entry.lhs} =?= {entry.rhs}\"}\"\n  | some ctx =>\n    withLCtx ctx.lctx ctx.localInstances do\n      let s   := entry.lhs.collectMVars entry.rhs.collectMVars\n      /- `p u` is true if it contains a universe metavariable in `s` -/\n      let p (u : Level) := u.any fun | .mvar m => s.contains m | _ => false\n      let lhs := exposeRelevantUniverses (\u2190 instantiateMVars ctx.lhs) p\n      let rhs := exposeRelevantUniverses (\u2190 instantiateMVars ctx.rhs) p\n      try\n        addMessageContext m!\"{header}{indentD m!\"{entry.lhs} =?= {entry.rhs}\"}\\nwhile trying to unify{indentD m!\"{lhs} : {\u2190 inferType lhs}\"}\\nwith{indentD m!\"{rhs} : {\u2190 inferType rhs}\"}\"\n      catch _ =>\n        addMessageContext m!\"{header}{indentD m!\"{entry.lhs} =?= {entry.rhs}\"}\\nwhile trying to unify{indentD lhs}\\nwith{indentD rhs}\"\n\ndef mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do\n  mkLeveErrorMessageCore \"stuck at solving universe constraint\" entry\n\ndef mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do\n  mkLeveErrorMessageCore \"failed to solve universe constraint\" entry\n\nprivate def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := do\n  let ps \u2190 getResetPostponed\n  for p in ps do\n    unless (\u2190 withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do\n      if exceptionOnFailure then\n        withRef p.ref do\n          throwError (\u2190 mkLevelErrorMessage p)\n      else\n        return false\n  return true\n\npartial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do\n  if (\u2190 getNumPostponed) == 0 then\n    return true\n  else\n    let numPostponedBegin \u2190 getNumPostponed\n    withTraceNode `Meta.isLevelDefEq.postponed\n        (fun _ => return m!\"processing #{numPostponedBegin} postponed is-def-eq level constraints\") do\n      let rec loop : MetaM Bool := do\n        let numPostponed \u2190 getNumPostponed\n        if numPostponed == 0 then\n          return true\n        else\n          if !(\u2190 processPostponedStep exceptionOnFailure) then\n            return false\n          else\n            let numPostponed' \u2190 getNumPostponed\n            if numPostponed' == 0 then\n              return true\n            else if numPostponed' < numPostponed then\n              loop\n            else\n              trace[Meta.isLevelDefEq.postponed] \"no progress solving pending is-def-eq level constraints\"\n              return mayPostpone\n      loop\n\n/--\n  `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`.\n  We keep the modifications only if `processPostponed` return true and `x` returned `true`.\n\n  If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning.\n  We currently try to postpone universe constraints as much as possible, even when by postponing them we\n  are not sure whether `x` really succeeded or not.\n-/\n@[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do\n  let s \u2190 saveState\n  /-\n    It is not safe to use the `isDefEq` cache between different `isDefEq` calls.\n    Reason: different configuration settings, and result depends on the state of the `MetavarContext`\n    We have tried in the past to track when the result was independent of the `MetavarContext` state\n    but it was not effective. It is more important to cache aggressively inside of a single `isDefEq`\n    call because some of the heuristics create many similar subproblems.\n    See issue #1102 for an example that triggers an exponential blowup if we don't use this more\n    aggresive form of caching.\n  -/\n  modifyDefEqCache fun _ => {}\n  let postponed \u2190 getResetPostponed\n  try\n    if (\u2190 x) then\n      if (\u2190 processPostponed mayPostpone) then\n        let newPostponed \u2190 getPostponed\n        setPostponed (postponed ++ newPostponed)\n        return true\n      else\n        s.restore\n        return false\n    else\n      s.restore\n      return false\n  catch ex =>\n    s.restore\n    throw ex\n\n/--\n  Determines whether two universe level expressions are definitionally equal to each other.\n-/\ndef isLevelDefEq (u v : Level) : MetaM Bool :=\n  checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v\n\n/-- See `isDefEq`. -/\ndef isExprDefEq (t s : Expr) : MetaM Bool :=\n  withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do\n    checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s\n\n/--\n  Determines whether two expressions are definitionally equal to each other.\n\n  To control how metavariables are assigned and unified, metavariables and their context have a \"depth\".\n  Given a metavariable `?m` and a `MetavarContext` `mctx`, `?m` is not assigned if `?m.depth != mctx.depth`.\n  The combinator `withNewMCtxDepth x` will bump the depth while executing `x`.\n  So, `withNewMCtxDepth (isDefEq a b)` is `isDefEq` without any mvar assignment happening\n  whereas `isDefEq a b` will assign any metavariables of the current depth in `a` and `b` to unify them.\n\n  For matching (where only mvars in `b` should be assigned), we create the term inside the `withNewMCtxDepth`.\n  For an example, see [Lean.Meta.Simp.tryTheoremWithExtraArgs?](https://github.com/leanprover/lean4/blob/master/src/Lean/Meta/Tactic/Simp/Rewrite.lean#L100-L106)\n -/\nabbrev isDefEq (t s : Expr) : MetaM Bool :=\n  isExprDefEq t s\n\ndef isExprDefEqGuarded (a b : Expr) : MetaM Bool := do\n  try isExprDefEq a b catch _ => return false\n\n/-- Similar to `isDefEq`, but returns `false` if an exception has been thrown. -/\nabbrev isDefEqGuarded (t s : Expr) : MetaM Bool :=\n  isExprDefEqGuarded t s\n\ndef isDefEqNoConstantApprox (t s : Expr) : MetaM Bool :=\n  approxDefEq <| isDefEq t s\n\n/--\n  Eta expand the given expression.\n  Example:\n  ```\n  etaExpand (mkConst ``Nat.add)\n  ```\n  produces `fun x y => Nat.add x y`\n-/\ndef etaExpand (e : Expr) : MetaM Expr :=\n  withDefault do forallTelescopeReducing (\u2190 inferType e) fun xs _ => mkLambdaFVars xs (mkAppN e xs)\n\nend Meta\n\nbuiltin_initialize\n  registerTraceClass `Meta.isLevelDefEq.postponed\n\nexport Meta (MetaM)\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/Meta/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894279828469, "lm_q2_score": 0.024798162222599104, "lm_q1q2_score": 0.008297202913085278}}
{"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\u27e8 lol.context.empty, rb_map.mk _ _ \u27e9\n\n@[reducible] meta def smt2_m (\u03b1 : Type) :=\nstate_t smt2_state tactic \u03b1\n\nmeta instance tactic_to_smt2_m (\u03b1 : Type) : has_coe (tactic \u03b1) (smt2_m \u03b1) :=\n\u27e8 fun tc, state_t.mk (fun s, do res \u2190 tc, return (res, s)) \u27e9\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 {\u03b1 : Type} (msg : string) : smt2_m \u03b1 :=\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 \u2190 get,\n   put \u27e8\n     st.ctxt.declare_type n lty,\n     st.type_map.insert ty lty\n   \u27e9\n\nmeta def fn_type : expr \u2192 (list expr \u00d7 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 \u2192 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 \u2192 smt2_m lol.type :=\nfun ty,\ndo st \u2190 get,\n   match st.type_map.find ty with\n   | some lty := return lty\n   | none := do\n     lty \u2190 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 \u2190 get,\n     ct \u2190 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 \u2190 infer_type e,\n--    let (arg_tys, ret_ty) := fn_type ty,\n--    let mangled_name := mangle_name n,\n--    arg_sorts \u2190 monad.mapm compile_type arg_tys,\n--    ret_sort \u2190 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) \u2190 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 \u00d7 expr \u00d7 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 \u2192 smt2_m lol.term) : smt2_m lol.term :=\nif source = `(nat) \u2227 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 \u2192 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) \u2190 extract_coe_args args,\n                   reflect_coercion source target e callback\n          else do ty \u2190 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) \u2228 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 \u2192 smt2_m lol.term) : expr \u2192 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 \u2190 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 \u2190 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 \u2190 infer_type e,\n   return $ (ty = `(int)) || (ty = `(nat))\n\nmeta def unsupported_ordering_on {\u03b1 : Type} (elem : expr) : tactic \u03b1 :=\ndo ty \u2190 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 \u2192 smt2_m lol.term) (R : lol.term \u2192 lol.term \u2192 lol.term) (P Q : expr) : smt2_m lol.term :=\ndo is \u2190 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 \u2190 get,\n     put { st with ctxt := st.ctxt.assert t }\n\nmeta def compile_pi (e : expr) (cb : expr \u2192 smt2_m lol.term) : smt2_m lol.term :=\nif supported_pi_binder e.binding_domain\nthen do loc \u2190 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 \u03a0 types are not supported, unable to translate term: `\" ++ to_string e ++ \"`\"\n\nmeta def reflect_prop_formula' : expr \u2192 smt2_m lol.term\n| `(\u00ac %%P) := lol.term.not <$> (reflect_prop_formula' P)\n| `(%%P = %% Q) := lol.term.equals <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P \u2227 %%Q) := lol.term.and <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P \u2228 %%Q) := lol.term.or <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P \u2194 %%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 \u2190 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 \u2192 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 \u2190 infer_type e,\n   prop_sorted \u2190 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 \u2228 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 \u2190 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 \u2190 attribute.get_instances `smt2,\n   bs \u2190 monad.mapm reflect_attr_decl decls.reverse,\n   return ()\n\nmeta def reflect_context : smt2_m unit :=\n do ls \u2190 local_context,\n    bs \u2190 monad.mapm (fun e, compile_local e) ls,\n    return ()\n\nmeta def reflect_goal : smt2_m unit :=\n  do tgt \u2190 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 \u2190 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, _) \u2190 smt2.reflect.run smt2_state.initial,\n   resp \u2190 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 \u2190 target,\n        sry \u2190 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 : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b3} :\n  g (f x) = y \u2192\n  (g \u2218 f) x = y := id\n\ntheorem pointfree_right {f : \u03b1 \u2192 \u03b2} {g : \u03b2 \u2192 \u03b3} :\n  x = g (f y) \u2192\n  x = (g \u2218 f) y := id\n\ntheorem finish_pointfree {f g : \u03b1 \u2192 \u03b2} :\n  (\u2200 x, f x = g x) \u2192 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 \u2190 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 \u00d7 Expr) := do\nmatch (\u2190 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', (\u2190 mkLambdaFVars #[x] pr)]\n  let l \u2190 mkAppOptM ``finish_pointfree args\n  return (x', l)\n| t => do\n  throwError \"bad shape {(\u2190 ppExpr t)}\"\n\n-- #check @pointfree_right\n\npartial def mkPointFreeRight (pr : Expr) : MetaM (FVarId \u00d7 Expr) := do\nmatch (\u2190 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 \u00d7 Expr) := do\nmatch (\u2190 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 \u00d7 Name) := do\nlet info \u2190 getConstInfo n\nlet ls : List Name := info.levelParams\nlet l \u2190 mkConst n (ls.map mkLevelParam)\nlet n' := Name.appendAfter info.name \"_pointfree\"\nlet t \u2190 inferType l\nforallTelescopeReducing t \u03bb args hd => do\n  for x in args do\n    IO.println s!\"{(\u2190 ppExpr x)} : {(\u2190 ppExpr (\u2190 inferType x))}\"\n  IO.println s!\"{(\u2190 ppExpr hd)}\"\n  let l' := mkAppN l args\n  IO.println s!\"{(\u2190 ppExpr l')}\"\n  IO.println s!\"{(\u2190 ppExpr (\u2190 inferType l'))}\"\n  let (v, e) \u2190 mkPointFreeLeft l'\n  let args := args.erase (mkFVar v)\n  let e \u2190 mkLambdaFVars args e\n  let t \u2190 inferType e\n  -- let t \u2190 mkForallFVars args (\u2190 inferType e)\n  modifyEnv \u03bb env => env.add\n    <| ConstantInfo.thmInfo\n    <| { name := n',\n         levelParams := ls,\n         type := t,\n         value := e }\n  IO.println s!\"{(\u2190 ppExpr e)} : {(\u2190 ppExpr (\u2190 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 \u2192 Expr \u2192 MetaM Bool\n  | Expr.app f\u2081 a\u2081 _, Expr.app f\u2082 a\u2082 _ => isPerm f\u2081 f\u2082 <&&> isPerm a\u2081 a\u2082\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\u2081 d\u2081 b\u2081 _, Expr.forallE n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.lam n\u2081 d\u2081 b\u2081 _, Expr.lam n\u2082 d\u2082 b\u2082 _ => isPerm d\u2081 d\u2082 <&&> withLocalDeclD n\u2081 d\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.letE n\u2081 t\u2081 v\u2081 b\u2081 _, Expr.letE n\u2082 t\u2082 v\u2082 b\u2082 _ =>\n    isPerm t\u2081 t\u2082 <&&> isPerm v\u2081 v\u2082 <&&> withLetDecl n\u2081 t\u2081 v\u2081 fun x => isPerm (b\u2081.instantiate1 x) (b\u2082.instantiate1 x)\n  | Expr.proj _ i\u2081 b\u2081 _, Expr.proj _ i\u2082 b\u2082 _ => i\u2081 == i\u2082 <&&> isPerm b\u2081 b\u2082\n  | s, t => s == t\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n  unless (\u2190 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 \u2190 instantiateMVars (\u2190 inferType e)\n  withNewMCtxDepth do\n    let (xs, _, type) \u2190 withReducible <| forallMetaTelescopeReducing type\n    let type \u2190 whnfR type\n    let (keys, perm) \u2190\n      match type.eq? with\n      | some (_, lhs, rhs) => pure (\u2190 DiscrTree.mkPath lhs, \u2190 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 \u00d7 Expr)) := do\n  let type \u2190 whnf type\n  if type.isForall then\n    forallTelescopeReducing type fun xs type => do\n      let e := mkAppN e xs\n      let ps \u2190 preprocess e type inv\n      ps.mapM fun (e, type) =>\n        return (\u2190 mkLambdaFVars xs e, \u2190 mkForallFVars xs type)\n  else if let some (_, lhs, rhs) := type.eq? then\n    if inv then\n      let type \u2190 mkEq rhs lhs\n      let e    \u2190 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 \u2190 mkEq rhs lhs\n      let e    \u2190 mkEqSymm (\u2190 mkPropExt e)\n      return [(e, type)]\n    else\n      let type \u2190 mkEq lhs rhs\n      let e    \u2190 mkPropExt e\n      return [(e, type)]\n  else if let some (_, lhs, rhs) := type.ne? then\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'False'\"\n    let type \u2190 mkEq (\u2190 mkEq lhs rhs) (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some p := type.not? then\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'False'\"\n    let type \u2190 mkEq p (mkConst ``False)\n    let e    \u2190 mkEqFalse e\n    return [(e, type)]\n  else if let some (type\u2081, type\u2082) := type.and? then\n    let e\u2081 := mkProj ``And 0 e\n    let e\u2082 := mkProj ``And 1 e\n    return (\u2190 preprocess e\u2081 type\u2081 inv) ++ (\u2190 preprocess e\u2082 type\u2082 inv)\n  else\n    if inv then\n      throwError \"invalid '\u2190' modifier in rewrite rule to 'True'\"\n    let type \u2190 mkEq type (mkConst ``True)\n    let e    \u2190 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 \u2190 getConstInfo declName\n  let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n  withReducible do\n    let type \u2190 inferType val\n    checkTypeIsProp type\n    if inv || (\u2190 shouldPreprocess type) then\n      let mut r := #[]\n      for (val, type) in (\u2190 preprocess val type inv) do\n        let auxName \u2190 mkAuxLemma cinfo.levelParams type val\n        r := r.push <| (\u2190 mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n      return r\n    else\n      #[\u2190 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 (\u2190 getEnv)\n\ndef addSimpLemma (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n  let simpLemmas \u2190 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 \u2190 getConstInfo declName\n        if (\u2190 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 \u2190 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 \u2190 ext.getState (\u2190 getEnv)\n      let s \u2190 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 \u2190 mkSimpExt extName\n  mkSimpAttr attrName attrDescr ext\n  return ext\n\nbuiltin_initialize mySimpExtension : SimpExtension \u2190 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 \u2190 getConstInfo declName\n    if (\u2190 isProp info.type) then\n      lemmas.addConst declName (post := post) (inv := inv)\n    else\n      if inv then\n        throwError \"invalid '\u2190' 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) \u2190 Term.withoutModifyingElabMetaStateWithInfo <| withRef stx <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx none\n    Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)\n    let e \u2190 instantiateMVars e\n    let e := e.eta\n    if e.hasMVar then\n      let r \u2190 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 := \"\u2193\"\n    syntax simpPost := \"\u2191\"\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 && (\u2190 Term.isLocalIdent? arg[1]).isSome then\n            -- We use `eraseCore` because the simp lemma for the hypothesis was not added yet\n            lemmas \u2190 lemmas.eraseCore arg[1].getId\n          else\n            let declName \u2190 resolveGlobalConstNoOverloadWithInfo arg[1]\n            lemmas \u2190 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 (\u2190 resolveSimpIdLemma? term) with\n          | some e => lemmas \u2190 addDeclToUnfoldOrLemma lemmas e post inv\n          | _      => lemmas \u2190 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) \u2190 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 (\u2190 getLCtx) do\n    unless localDecl.isAuxDecl do\n      if (\u2190 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 \u2190 mkDischargeWrapper stx[2]\n  let simpOnly := !stx[3].isNone\n  let simpLemmas \u2190\n    if simpOnly then\n      ({} : SimpLemmas).addConst ``eq_self\n    else\n      getSimpLemmas\n  let congrLemmas \u2190 getCongrLemmas\n  let r \u2190 elabSimpArgs stx[4] (eraseLocal := eraseLocal) {\n    config      := (\u2190 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 \u2190 getPropHyps\n    let mut ctx := ctx\n    let mut fvarIdToLemmaId := {}\n    for h in hs do\n      let localDecl \u2190 getLocalDecl h\n      unless erased.contains localDecl.userName do\n        let fvarId := localDecl.fvarId\n        let proof  := localDecl.toExpr\n        let id     \u2190 mkFreshUserName `h\n        fvarIdToLemmaId := fvarIdToLemmaId.insert fvarId id\n        let simpLemmas \u2190 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 } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false)\n  -- -- trace[Meta.debug] \"Lemmas {\u2190 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": "/-\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 {\u03b5 : Type u}\n\n@[inline] protected def pure (a : \u03b1) : Except \u03b5 \u03b1 :=\n  Except.ok a\n\n@[inline] protected def map (f : \u03b1 \u2192 \u03b2) : Except \u03b5 \u03b1 \u2192 Except \u03b5 \u03b2\n  | Except.error err => Except.error err\n  | Except.ok v => Except.ok <| f v\n\n@[simp] theorem map_id : Except.map (\u03b5 := \u03b5) (\u03b1 := \u03b1) (\u03b2 := \u03b1) id = id := by\n  apply funext\n  intro e\n  simp [Except.map]; cases e <;> rfl\n\n@[inline] protected def mapError (f : \u03b5 \u2192 \u03b5') : Except \u03b5 \u03b1 \u2192 Except \u03b5' \u03b1\n  | Except.error err => Except.error <| f err\n  | Except.ok v      => Except.ok v\n\n@[inline] protected def bind (ma : Except \u03b5 \u03b1) (f : \u03b1 \u2192 Except \u03b5 \u03b2) : Except \u03b5 \u03b2 :=\n  match ma with\n  | Except.error err => Except.error err\n  | Except.ok v      => f v\n\n@[inline] protected def toBool : Except \u03b5 \u03b1 \u2192 Bool\n  | Except.ok _    => true\n  | Except.error _ => false\n\n@[inline] protected def toOption : Except \u03b5 \u03b1 \u2192 Option \u03b1\n  | Except.ok a    => some a\n  | Except.error _ => none\n\n@[inline] protected def tryCatch (ma : Except \u03b5 \u03b1) (handle : \u03b5 \u2192 Except \u03b5 \u03b1) : Except \u03b5 \u03b1 :=\n  match ma with\n  | Except.ok a    => Except.ok a\n  | Except.error e => handle e\n\ninstance : Monad (Except \u03b5) where\n  pure := Except.pure\n  bind := Except.bind\n  map  := Except.map\n\nend Except\n\ndef ExceptT (\u03b5 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) : Type v :=\n  m (Except \u03b5 \u03b1)\n\n@[inline] def ExceptT.mk {\u03b5 : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type u} (x : m (Except \u03b5 \u03b1)) : ExceptT \u03b5 m \u03b1 := x\n@[inline] def ExceptT.run {\u03b5 : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type u} (x : ExceptT \u03b5 m \u03b1) : m (Except \u03b5 \u03b1) := x\n\nnamespace ExceptT\n\nvariable {\u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m]\n\n@[inline] protected def pure {\u03b1 : Type u} (a : \u03b1) : ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk <| pure (Except.ok a)\n\n@[inline] protected def bindCont {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : Except \u03b5 \u03b1 \u2192 m (Except \u03b5 \u03b2)\n  | Except.ok a    => f a\n  | Except.error e => pure (Except.error e)\n\n@[inline] protected def bind {\u03b1 \u03b2 : Type u} (ma : ExceptT \u03b5 m \u03b1) (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : ExceptT \u03b5 m \u03b2 :=\n  ExceptT.mk <| ma >>= ExceptT.bindCont f\n\n@[inline] protected def map {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1) : ExceptT \u03b5 m \u03b2 :=\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@[inline] protected def lift {\u03b1 : Type u} (t : m \u03b1) : ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk <| Except.ok <$> t\n\ninstance : MonadLift (Except \u03b5) (ExceptT \u03b5 m) := \u27e8fun e => ExceptT.mk <| pure e\u27e9\ninstance : MonadLift m (ExceptT \u03b5 m) := \u27e8ExceptT.lift\u27e9\n\n@[inline] protected def tryCatch {\u03b1 : Type u} (ma : ExceptT \u03b5 m \u03b1) (handle : \u03b5 \u2192 ExceptT \u03b5 m \u03b1) : ExceptT \u03b5 m \u03b1 :=\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 \u03b5 m) := \u27e8fun f x => f x\u27e9\n\ninstance : Monad (ExceptT \u03b5 m) where\n  pure := ExceptT.pure\n  bind := ExceptT.bind\n  map  := ExceptT.map\n\n@[inline] protected def adapt {\u03b5' \u03b1 : Type u} (f : \u03b5 \u2192 \u03b5') : ExceptT \u03b5 m \u03b1 \u2192 ExceptT \u03b5' m \u03b1 := fun x =>\n  ExceptT.mk <| Except.mapError f <$> x\n\nend ExceptT\n\ninstance (m : Type u \u2192 Type v) (\u03b5\u2081 : Type u) (\u03b5\u2082 : Type u) [Monad m] [MonadExceptOf \u03b5\u2081 m] : MonadExceptOf \u03b5\u2081 (ExceptT \u03b5\u2082 m) where\n  throw e := ExceptT.mk <| throwThe \u03b5\u2081 e\n  tryCatch x handle := ExceptT.mk <| tryCatchThe \u03b5\u2081 x handle\n\ninstance (m : Type u \u2192 Type v) (\u03b5 : Type u) [Monad m] : MonadExceptOf \u03b5 (ExceptT \u03b5 m) where\n  throw e := ExceptT.mk <| pure (Except.error e)\n  tryCatch := ExceptT.tryCatch\n\ninstance [Monad m] [Inhabited \u03b5] : Inhabited (ExceptT \u03b5 m \u03b1) where\n  default := throw arbitrary\n\ninstance (\u03b5) : MonadExceptOf \u03b5 (Except \u03b5) where\n  throw    := Except.error\n  tryCatch := Except.tryCatch\n\nnamespace MonadExcept\nvariable {\u03b5 : Type u} {m : Type v \u2192 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@[inline] def orelse' [MonadExcept \u03b5 m] {\u03b1 : Type v} (t\u2081 t\u2082 : m \u03b1) (useFirstEx := true) : m \u03b1 :=\n  tryCatch t\u2081 fun e\u2081 => tryCatch t\u2082 fun e\u2082 => throw (if useFirstEx then e\u2081 else e\u2082)\n\nend MonadExcept\n\n@[inline] def observing {\u03b5 \u03b1 : Type u} {m : Type u \u2192 Type v} [Monad m] [MonadExcept \u03b5 m] (x : m \u03b1) : m (Except \u03b5 \u03b1) :=\n  tryCatch (do let a \u2190 x; pure (Except.ok a)) (fun ex => pure (Except.error ex))\n\ninstance (\u03b5 : Type u) (m : Type u \u2192 Type v) [Monad m] : MonadControl m (ExceptT \u03b5 m) where\n  stM        := Except \u03b5\n  liftWith f := liftM <| f fun x => x.run\n  restoreM x := x\n\nclass MonadFinally (m : Type u \u2192 Type v) where\n  tryFinally' {\u03b1 \u03b2} : m \u03b1 \u2192 (Option \u03b1 \u2192 m \u03b2) \u2192 m (\u03b1 \u00d7 \u03b2)\n\nexport MonadFinally (tryFinally')\n\n/-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/\n@[inline] def tryFinally {m : Type u \u2192 Type v} {\u03b1 \u03b2 : Type u} [MonadFinally m] [Functor m] (x : m \u03b1) (finalizer : m \u03b2) : m \u03b1 :=\n  let y := tryFinally' x (fun _ => finalizer)\n  (\u00b7.1) <$> y\n\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\ninstance ExceptT.finally {m : Type u \u2192 Type v} {\u03b5 : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT \u03b5 m) where\n  tryFinally' := fun x h => ExceptT.mk do\n    let r \u2190 tryFinally' x fun e? => match e? with\n        | some (Except.ok a) => h (some a)\n        | _                  => h none\n    match r with\n    | (Except.ok a,    Except.ok b)    => pure (Except.ok (a, b))\n    | (_,              Except.error e) => pure (Except.error e)  -- second error has precedence\n    | (Except.error e, _)              => pure (Except.error e)\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/Except.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1276526352779213, "lm_q2_score": 0.0646534955652171, "lm_q1q2_score": 0.008253189088829362}}
{"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' : \u211d\u22650)\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 (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{u} r')\n\nnamespace Lbar\n\nopen ProFiltPseuNormGrpWithTinv\u2081 ProFiltPseuNormGrp\u2081 CompHausFiltPseuNormGrp\u2081\nopen bounded_homotopy_category\n\nvariables (r r')\n\ndef Tinv_sub (S : Profinite.{u}) (V : SemiNormedGroup.{u}) [normed_with_aut r V] (i : \u2124) :\n  ((Ext' i).obj (op $ (Lbar.condensed.{u} r').obj S)).obj V.to_Cond \u27f6\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} \u21a5X) (PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097.{0} r') := {}\n\nset_option pp.universes true\ndef condensify_iso_extend :\n  condensify (Fintype_Lbar.{0 0} r' \u22d9 PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r') \u2245\n  (Profinite.extend (Fintype_Lbar.{0 0} r')) \u22d9\n    (PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r' \u22d9 CHFPNG\u2081_to_CHFPNG\u2091\u2097.{0} \u22d9\n  CompHausFiltPseuNormGrp.to_Condensed.{0}) :=\n(((whiskering_left _ _ _).map_iso $\n  Profinite.extend_commutes (Fintype_Lbar.{0 0} r') (PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r')).app\n    (CHFPNG\u2081_to_CHFPNG\u2091\u2097.{0} \u22d9 CompHausFiltPseuNormGrp.to_Condensed.{0})).symm\n\ndef condensify_iso_extend' :\n  (condensify (Fintype_Lbar.{0 0} r' \u22d9 PFPNGT\u2081_to_CHFPNG\u2081\u2091\u2097 r')).obj S \u2245\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} \u2964 C)\nvariables {D : Type u'} [category.{v} D]\nvariable [\u2200 X : Profinite, has_limit (X.fintype_diagram \u22d9 F)]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends' (G : C \u2964 D)\n  [\u2200 X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n  [\u2200 X : Profinite.{v}, has_limit (X.fintype_diagram \u22d9 F \u22d9 G)] :\n  whisker_left Fintype.to_Profinite (extend_commutes F G).hom =\n  (functor.associator _ _ _).inv \u226b (whisker_right (extend_extends _).hom G) \u226b\n    (extend_extends _).inv :=\nby rw [\u2190 category.assoc, iso.eq_comp_inv, extend_commutes_comp_extend_extends]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends'' (G : C \u2964 D)\n  [\u2200 X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n  [\u2200 X : Profinite.{v}, has_limit (X.fintype_diagram \u22d9 F \u22d9 G)] :\n  whisker_left Fintype.to_Profinite (extend_commutes F G).inv =\n  (extend_extends _).hom \u226b (whisker_right (extend_extends _).inv G) \u226b\n    (functor.associator _ _ _).hom :=\nbegin\n  rw [\u2190 iso.inv_comp_eq, \u2190 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    \u2190 iso_whisker_right_hom, \u2190 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') \u226b (condensify_iso_extend r').hom =\n  (condensify_iso_extend r').hom \u226b (@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, \u2190 iso.app_inv, \u2190 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, \u2190 functor.map_comp, \u2190 functor.map_comp],\n  congr' 1,\n  rw [iso.app_inv, iso.app_hom, \u2190 whisker_right_app, \u2190 whisker_right_app,\n    \u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app],\n  congr' 1,\n  refine nonstrict_extend_ext _ _ (r'\u207b\u00b9) (1 * (r'\u207b\u00b9 * 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, \u2190 whisker_right_left, \u2190 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 [\u2190 iso.app_hom, \u2190 iso.app_inv, \u2190 functor.map_iso_hom, \u2190 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 \u226b (condensify_iso_extend' r' S).hom =\n  (condensify_iso_extend' r' S).hom \u226b ((Profinite.extend (Fintype_Lbar.{0 0} r')).obj S).Tinv_cond :=\nbegin\n  have := condensify_Tinv_iso r',\n  apply_fun (\u03bb \u03b7, \u03b7.app S) at this,\n  exact this,\nend\n\ndef useful_commsq (i : \u2124) (\u03b9 : ulift.{1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9) [normed_with_aut r V] :=\n  shift_sub_id.commsq\n    (ExtQprime.Tinv2 r r' breen_deligne.eg.data\n      (\u03bb c n, c * breen_deligne.eg.\u03ba r r' n)\n      (\u03bb c n, r' * (c * breen_deligne.eg.\u03ba r r' n))\n      ((Lbar.functor.{0 0} r').obj S) V i) \u03b9 h\u03b9\n\nsection\nopen breen_deligne thm95.universal_constants\n\nvariables (i : \u2115)\n\nlemma useful_commsq_bicartesian (\u03b9 : ulift.{1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9) [normed_with_aut r V]\n  (H1 : \u2200 j, c\u2080 r r' eg (\u03bb n, eg.\u03ba r r' n) (eg.\u03ba' r r') (i+1) \u27e8\u2124\u27e9 \u2264 \u03b9 j)\n  (H2 : \u2200 j, k (eg.\u03ba' r r') i ^ 2 * \u03b9 j \u2264 \u03b9 (j + 1))\n  (H3 : \u2200 j, k (eg.\u03ba' r r') (i+1) ^ 2 * \u03b9 j \u2264 \u03b9 (j + 1)) :\n  (useful_commsq r r' S V i \u03b9 h\u03b9).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 \u03b9 h\u03b9\n    (ExtQprime_iso_aux_system_comm' _ _ _ _ _ _ _ _),\n  rw [\u2190 whisker_right_twice],\n  refine shift_sub_id.bicartesian (aux_system.incl'.{0 1} r r' _ _ _ (eg.\u03ba r r')) _\n    i \u03b9 h\u03b9 _ _ _,\n  { apply_with system_of_complexes.shift_eq_zero {instances := ff},\n    swap 3, { apply thm94.explicit r r' _ _ (eg.\u03ba' r r'), },\n    any_goals { apply_instance },\n    { intro j,\n      refine le_trans _ ((c\u2080_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.\u03ba' r r'), },\n    any_goals { apply_instance },\n    { exact H1 },\n    { exact H3 } },\n  { intros c n,\n    let \u03ba := eg.\u03ba r r',\n    apply aux_system.short_exact r r' _ _ _ (\u03bb c n, r' * (c * \u03ba n)) \u03ba,\n    intro c, dsimp, apply_instance, }\nend\n\nlemma bicartesian_of_is_zero {\ud835\udcd2 : Type*} [category \ud835\udcd2] [abelian \ud835\udcd2]\n  {A B C D : \ud835\udcd2} (f\u2081 : A \u27f6 B) (g\u2081 : A \u27f6 C) (g\u2082 : B \u27f6 D) (f\u2082 : C \u27f6 D) (h : commsq f\u2081 g\u2081 g\u2082 f\u2082)\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 \u27e8\u03bb X f g h, _\u27e9, apply hA.eq_of_tgt },\n  { refine \u27e8\u03bb X f g h, _\u27e9, 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 {\ud835\udcd2 : Type*} [category \ud835\udcd2] [abelian \ud835\udcd2] {\u03b9 : Type*} (f : \u03b9 \u2192 \ud835\udcd2) [has_product f]\n  (hf : \u2200 i, is_zero (f i)) :\n  is_zero (\u220f f) :=\nbegin\n  rw is_zero_iff_id_eq_zero,\n  ext \u27e8j\u27e9,\n  apply (hf j).eq_of_tgt,\nend\n\nlemma useful_commsq_bicartesian_neg  (\u03b9 : ulift.{1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9) [normed_with_aut r V]\n  (i : \u2124) (hi : i < 0) :\n  (useful_commsq r r' S V i \u03b9 h\u03b9).bicartesian :=\nbegin\n  have : 1 + i \u2264 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 {\ud835\udcd2 : Type*} [category \ud835\udcd2] {X Y : \ud835\udcd2} (f\u2081 : X \u27f6 X) (f\u2082 : Y \u27f6 Y)\n  (e : X \u2245 Y) (h : f\u2081 \u226b e.hom = e.hom \u226b f\u2082) (h\u2081 : is_iso f\u2081) :\n  is_iso f\u2082 :=\nby { rw [\u2190 iso.inv_comp_eq] at h, rw \u2190 h, apply_instance }\n\nopen category_theory.preadditive\n\nlemma is_iso_sq' {\ud835\udcd2 : Type*} [category \ud835\udcd2] [abelian \ud835\udcd2] [enough_projectives \ud835\udcd2]\n  {X Y Z : bounded_homotopy_category \ud835\udcd2} (f\u2081 : X \u27f6 X) (f\u2082 : Y \u27f6 Y) (f\u2083 : Z \u27f6 Z)\n  (e : Y \u2245 X) (h : e.hom \u226b f\u2081 = f\u2082 \u226b e.hom) (i : \u2124)\n  (h\u2081 : is_iso (((Ext i).map f\u2081.op).app Z - ((Ext i).obj _).map f\u2083)) :\n  is_iso (((Ext i).map f\u2082.op).app Z - ((Ext i).obj _).map f\u2083) :=\nbegin\n  refine is_iso_sq _ _ ((functor.map_iso _ e.op).app _) _ h\u2081,\n  rw [iso.app_hom, functor.map_iso_hom, sub_comp, comp_sub, nat_trans.naturality,\n      \u2190 nat_trans.comp_app, \u2190 nat_trans.comp_app, \u2190 functor.map_comp, \u2190 functor.map_comp,\n      iso.op_hom, \u2190 op_comp, \u2190 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] : \u2200 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, \u2190 functor.map_comp, \u2190 functor.map_comp, condensify_Tinv_iso'], },\n  revert i,\n  refine Tinv2_iso_of_bicartesian' r breen_deligne.eg\n      (\u03bb c n, c * breen_deligne.eg.\u03ba r r' n)\n      (\u03bb c n, r' * (c * breen_deligne.eg.\u03ba r r' n))\n    ((Lbar.functor.{0 0} r').obj S) V _,\n  rintro (i|(_|i)),\n  { refine \u27e8\u03b9 r r' i, h\u03b9 r r' i, _, _, _, _\u27e9,\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 \u27e8j\u27e9, apply H\u03b91 },\n    { rintro \u27e8j\u27e9, apply H\u03b92a },\n    { rintro \u27e8j\u27e9, apply H\u03b92b },\n    { rintro \u27e8j\u27e9, apply H\u03b91' },\n    { rintro \u27e8j\u27e9, apply H\u03b92b },\n    { rintro \u27e8j\u27e9, apply H\u03b92c } },\n  { refine \u27e8\u03b9 r r' 0, h\u03b9 r r' 0, _, _, _, _\u27e9,\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 \u27e8j\u27e9, apply H\u03b91 },\n    { rintro \u27e8j\u27e9, apply H\u03b92a },\n    { rintro \u27e8j\u27e9, apply H\u03b92b }, }, },\n  { refine \u27e8\u03b9 r r' 0, h\u03b9 r r' 0, _, _, _, _\u27e9,\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 : \u2200 (v : V), (normed_with_aut.T.inv v) = 2 \u2022 v) :\n  \u2200 i, is_iso (((Ext' i).map ((condensify_Tinv2 (Fintype_Lbar.{0 0} r')).app S).op).app\n    (Condensed.of_top_ab \u21a5V)) :=\nbegin\n  intro i,\n  rw [condensify_Tinv2_eq, \u2190 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 \u2022 \ud835\udfd9 _,\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 Init\nimport Lean.Parser\nimport Lean.PrettyPrinter\n\nsection\nopen Lean.Parser\nopen Lean.PrettyPrinter\n\n/-- Like `ident` but with no splitting on dots and accepts anything that's not whitespace\nor parentheses. So e.g. `<=` works. -/\ndef generalIdent : Parser :=\n  withAntiquot (mkAntiquot \"generalIdent\" `generalIdent) {\n    fn := fun c s =>\n      let startPos := s.pos\n      let s := takeWhile1Fn (fun c => !(\"(){}[].\".contains c) \u2227 !c.isWhitespace) \"expected generalized identifier\" c s\n      mkNodeToken `generalIdent startPos c s }\n\ndef Lean.TSyntax.getGeneralId : TSyntax `generalIdent \u2192 String\n  | \u27e8Syntax.node _ `generalIdent args\u27e9 => args[0]!.getAtomVal!\n  | s => panic! s!\"unexpected syntax '{s}'\"\n\n@[combinatorFormatter generalIdent] def generalIdent.formatter : Formatter := pure ()\n@[combinatorParenthesizer generalIdent] def generalIdent.parenthesizer : Parenthesizer := pure ()\nend\n\ninductive Sexp where\n  | atom : String \u2192 Sexp\n  | expr : List Sexp \u2192 Sexp\n  deriving Repr, BEq, Inhabited\n\nnamespace Sexp\n\ninstance : Coe String Sexp :=\n  \u27e8Sexp.atom\u27e9\n\ndeclare_syntax_cat sexp\n\nsyntax generalIdent : sexp\nsyntax \"(\" sexp* \")\" : sexp\nsyntax \"(\" sexp* \"...{\" term \"}\" sexp* \")\" : sexp\nsyntax \"{\" term \"}\" : sexp\n\n-- This coercion is justified by the macro expansions below.\ninstance : Coe (Lean.TSyntax `sexp) (Lean.TSyntax `term) where\n  coe a := \u27e8a.raw\u27e9\n\nmacro_rules\n  | `(sexp| $a:generalIdent) => `(Sexp.atom $(Lean.quote a.getGeneralId))\n  | `(sexp| ( $ss:sexp* )) => `(Sexp.expr [ $ss,* ])\n  | `(sexp| ( $ss:sexp* ...{ $t:term } $ts:sexp* )) => `(Sexp.expr <| [ $ss,* ] ++ ($t : List Sexp) ++ [ $ts,* ])\n  | `(sexp| { $t:term }) => `($t)\n\nsyntax \"sexp!{\" sexp \"}\" : term\nmacro_rules\n  | `(sexp!{ $s:sexp }) => `($s)\n\nsyntax \"sexps!{\" sexp* \"}\" : term\nsyntax \"sexps!{\" sexp* \"...{\" term \"}\" sexp* \"}\" : term\nmacro_rules\n  | `(sexps!{ $ss:sexp* }) => do\n    let ss \u2190 ss.mapM fun s => `(sexp!{ $s })\n    `([ $[$ss],* ])\n  | `(sexps!{ $ss:sexp* ...{ $t:term } $ts:sexp* }) =>\n    `([ $[$ss],* ] ++ ($t : List Sexp) ++ [ $[$ts],* ])\n\npartial def serialize : Sexp \u2192 String\n  | atom s  => s\n  | expr ss => s!\"({\" \".intercalate <| ss.map serialize})\"\n\npartial def serializeMany (ss : List Sexp) : String :=\n  ss.map serialize |> \"\\n\".intercalate\n\ninstance : ToString Sexp :=\n  \u27e8serialize\u27e9\n\ninstance : Repr Sexp where\n  reprPrec s _ := s!\"sexp!\\{{toString s}}\"\n\npartial def parse (s : String) : Except String (List Sexp) :=\n  let tks := tokenize #[] s.toSubstring\n  parseMany #[] tks.toList |>.map Prod.fst |>.map Array.toList\nwhere\n  tokenize (stk : Array Substring) (s : Substring) : Array Substring :=\n    if s.isEmpty then stk\n    else\n      let c := s.front\n      if c == ')' || c == '(' then\n        tokenize (stk.push <| s.take 1) (s.drop 1)\n      else if c.isWhitespace then tokenize stk (s.drop 1)\n      else\n        let tk := s.takeWhile fun c => !c.isWhitespace && c != '(' && c != ')'\n        if tk.bsize > 0 then tokenize (stk.push tk) (s.extract \u27e8tk.bsize\u27e9 \u27e8s.bsize\u27e9)\n        else unreachable!\n\n  parseOne : List Substring \u2192 Except String (Sexp \u00d7 List Substring)\n    | tk :: tks => do\n      if tk.front == ')' then\n        throw \"mismatched parentheses\"\n      if tk.front == '(' then\n        let (ss, tks) \u2190 parseMany #[] tks\n        return (expr ss.toList, tks)\n      else\n        return  (atom tk.toString, tks)\n    | [] => throw \"expected input, got none\"\n\n  parseMany (stk : Array Sexp) : List Substring \u2192 Except String (Array Sexp \u00d7 List Substring)\n    | tk :: tks => do\n      if tk.front == ')' then .ok (stk, tks)\n      else\n        let (e, tks) \u2190 parseOne (tk :: tks)\n        parseMany (stk.push e) tks\n    | [] => .ok (stk, [])\n\nend Sexp\n\nprivate def argsCvc4 : IO.Process.SpawnArgs := {\n  cmd := \"LAMR/bin/cvc4\"\n  args := #[\"--lang\", \"smt\", \"LAMR/bin/temp.smt\"] }\n\nprivate def argsCvc5 : IO.Process.SpawnArgs := {\n  cmd := \"LAMR/bin/cvc5\"\n  args := #[\"--lang\", \"smt\", \"LAMR/bin/temp.smt\"] }\n\nprivate def argsZ3 : IO.Process.SpawnArgs := {\n  cmd := \"LAMR/bin/z3\"\n  args := #[\"-smt2\", \"LAMR/bin/temp.smt\"] }\n\nprivate def argsBoolector : IO.Process.SpawnArgs := {\n  cmd := \"LAMR/bin/boolector\"\n  args := #[\"--smt2\", \"LAMR/bin/temp.smt\"] }\n\n-- Same as IO.Process.run, but does not require exitcode = 0\nprivate def run' (args : IO.Process.SpawnArgs) : IO String := do\n  let out \u2190 IO.Process.output args\n  pure out.stdout\n\n/-- Executes the solver with the provided list of commands in SMT-LIB s-expression format.\nReturns the solver output as s-expressions. -/\nprivate def callSolver (args : IO.Process.SpawnArgs) (commands : List Sexp) (verbose : Bool := false)\n    : IO (List Sexp) := do\n  let cmdStr := Sexp.serializeMany commands\n  if verbose then\n    IO.println \"Sending SMT-LIB problem:\"\n    IO.println cmdStr\n  IO.FS.writeFile \"LAMR/bin/temp.smt\" cmdStr\n  let out \u2190 run' args\n  if verbose then\n    IO.println \"\\nSolver replied:\"\n    IO.println out\n  let out \u2190 IO.ofExcept (Sexp.parse out)\n  return out\n\ndef callCvc4 := @callSolver argsCvc4\ndef callCvc5 := @callSolver argsCvc5\ndef callZ3 := @callSolver argsZ3\ndef callBoolector := @callSolver argsBoolector\n\nprivate def hexdigits : Array Char :=\n  #[ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ]\n\nprivate def enhexByte (x : UInt8) : String :=\n  \u27e8[hexdigits.get! $ UInt8.toNat $ (x.land 0xf0).shiftRight 4,\n    hexdigits.get! $ UInt8.toNat $ x.land 0xf ]\u27e9\n\n/-- Convert a little-endian (LSB first) list of bytes to hexadecimal. -/\nprivate def enhexLE : List UInt8 \u2192 String\n  | [] => \"\"\n  | b::bs => enhexLE bs ++ enhexByte b\n\n/-- Converts a number `n` to its hexadecimal SMT-LIB representation as a `nBits`-bit vector.\nFor example `toBVConst 32 0xf == \"#x0000000f\"`. -/\ndef toBVConst (nBits : Nat) (n : Nat) : String :=\n  assert! nBits % 8 == 0\n  let nBytes := nBits/8\n  let bytes := List.range nBytes |>.map fun i => UInt8.ofNat ((n >>> (i*8)) &&& 0xff)\n  \"#x\" ++ enhexLE bytes\n\nopen Std (AssocList)\n\n/-- Extracts constants assigned in a model returned from an SMT solver.\nThe model is expected to be a single s-expression representing a list,\nwith constant expressions represented by `(define-fun <name> () <type> <body>)`. -/\ndef decodeModelConsts : Sexp \u2192 AssocList String Sexp\n  | Sexp.expr ss =>\n    ss.foldl (init := AssocList.empty) fun\n      | acc, sexp!{(define-fun {Sexp.atom x} () {_} {body})} =>\n        acc.insert x body\n      | acc, _ => acc\n  | _ => AssocList.empty\n\n/-- Evaluates an SMT-LIB constant numeral such as `0` or `#b01` or `#x02`. -/\ndef evalNumConst : Sexp \u2192 Option Nat\n  | Sexp.atom s =>\n    let s' :=\n      if s.startsWith \"#b\" then \"0\" ++ s.drop 1\n      else if s.startsWith \"#x\" then \"0\" ++ s.drop 1\n      else s\n    Lean.Syntax.decodeNatLitVal? s'\n  | Sexp.expr _ => none", "meta": {"author": "avigad", "repo": "lamr", "sha": "b2795a17fb01b7e45aaa1940d4c4200f46800e16", "save_path": "github-repos/lean/avigad-lamr", "path": "github-repos/lean/avigad-lamr/lamr-b2795a17fb01b7e45aaa1940d4c4200f46800e16/LAMR/Util/FirstOrder/Smt.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850131323717, "lm_q2_score": 0.03358950335247998, "lm_q1q2_score": 0.0082322838702524}}
{"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  \u27e8\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    ]\u27e9\n/-(\u27e8mk_time _ 0,sorry\u27e9-/\n\n#eval ser\n\n#check quotient.eq\n\ndef v1 := mk_displacement3d_timefixed_at_time ser (mk_time ts (2.4:\u211a)) 1 1 1\n\ndef v2 := mk_displacement3d_timefixed_at_time ser (mk_time ts (2.5:\u211a)) 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 +\u1d65 v2\n\ndef t1 := \u27e6(\u27e8(mk_time ts (2.4:\u211a))\u27e9 : series_index ts ser)\u27e7\ndef t2 := \u27e6(\u27e8(mk_time ts (2.5:\u211a))\u27e9 : series_index ts ser)\u27e7\n\nexample : t1 = t2 := sorry\n\n#check t1\n\n#check quotient.lift\n\ndef v3 := mk_displacement3d_timefixed_at_time'' ser \u27e6series_index.mk (mk_time ts (2.4:\u211a))\u27e7 1 1 1\n\ndef v4 := mk_displacement3d_timefixed_at_time'' ser \u27e6series_index.mk (mk_time ts (2.5:\u211a))\u27e7 1 1 1\n\n#check v3 +\u1d65 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 ` \u2218 `:80 g:80 := g \u226b 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\u0103dulescu-Banu, Cofibrations in Homotopy Theory, Lemma 1.4.1\n\nvariables {a\u2081 a\u2082 a\u2083 a\u2084 b\u2081 b\u2082 b\u2083 b\u2084 : C}\n  {f\u2081\u2082 : a\u2081 \u27f6 a\u2082} {f\u2081\u2083 : a\u2081 \u27f6 a\u2083} {f\u2082\u2084 : a\u2082 \u27f6 a\u2084} {f\u2083\u2084 : a\u2083 \u27f6 a\u2084}\n  (po_f : Is_pushout f\u2081\u2082 f\u2081\u2083 f\u2082\u2084 f\u2083\u2084)\n  {g\u2081\u2082 : b\u2081 \u27f6 b\u2082} {g\u2081\u2083 : b\u2081 \u27f6 b\u2083} {g\u2082\u2084 : b\u2082 \u27f6 b\u2084} {g\u2083\u2084 : b\u2083 \u27f6 b\u2084}\n  (po_g : Is_pushout g\u2081\u2082 g\u2081\u2083 g\u2082\u2084 g\u2083\u2084)\n  {u\u2081 : a\u2081 \u27f6 b\u2081} {u\u2082 : a\u2082 \u27f6 b\u2082} {u\u2083 : a\u2083 \u27f6 b\u2083} -- u\u2084 will be the induced map of pushouts\n  (ha\u2081 : cofibrant a\u2081) (ha\u2083 : cofibrant a\u2083) (hb\u2081 : cofibrant b\u2081) (hb\u2083 : cofibrant b\u2083)\n  (hf\u2081\u2082 : is_cof f\u2081\u2082) (hg\u2081\u2082 : is_cof g\u2081\u2082)\n  (hwu\u2081 : is_weq u\u2081) (hwu\u2082 : is_weq u\u2082) (hwu\u2083 : is_weq u\u2083)\n  (s\u2081\u2082 : f\u2081\u2082 \u226b u\u2082 = u\u2081 \u226b g\u2081\u2082) (s\u2081\u2083 : f\u2081\u2083 \u226b u\u2083 = u\u2081 \u226b g\u2081\u2083)\n\nlemma gluing_weq_aux (hcu\u2081 : is_cof u\u2081) (hcu\u2083 : is_cof u\u2083)\n  (hcu\u2082'' : is_cof ((pushout_by_cof f\u2081\u2082 u\u2081 hf\u2081\u2082).is_pushout.induced u\u2082 g\u2081\u2082 s\u2081\u2082)) :\n  is_weq (pushout_of_maps po_f po_g u\u2081 u\u2082 u\u2083 s\u2081\u2082 s\u2081\u2083) :=\nhave acof_u\u2081 : is_acof u\u2081 := \u27e8hcu\u2081, hwu\u2081\u27e9,\nhave acof_u\u2083 : is_acof u\u2083 := \u27e8hcu\u2083, hwu\u2083\u27e9,\nlet po\u2081\u2082 := pushout_by_cof f\u2081\u2082 u\u2081 hf\u2081\u2082,\n    u\u2082' := po\u2081\u2082.map\u2080,\n    u\u2082'' := po\u2081\u2082.is_pushout.induced u\u2082 g\u2081\u2082 s\u2081\u2082,\n    u\u2084 := pushout_of_maps po_f po_g u\u2081 u\u2082 u\u2083 s\u2081\u2082 s\u2081\u2083,\n    po\u2083\u2084 := pushout_by_cof f\u2083\u2084 u\u2083 (pushout_is_cof po_f hf\u2081\u2082),\n    u\u2084' := po\u2083\u2084.map\u2080,\n    u\u2084'' := po\u2083\u2084.is_pushout.induced u\u2084 g\u2083\u2084 (by simp) in\nhave acof_u\u2082' : is_acof u\u2082' := pushout_is_acof po\u2081\u2082.is_pushout.transpose acof_u\u2081,\nhave acof_u\u2084' : is_acof u\u2084' := pushout_is_acof po\u2083\u2084.is_pushout.transpose acof_u\u2083,\nhave acof_u\u2082'' : is_acof u\u2082'' := have _ := hwu\u2082, begin\n  refine \u27e8hcu\u2082'', category_with_weak_equivalences.weq_of_comp_weq_left acof_u\u2082'.2 _\u27e9,\n  simpa using this\nend,\nlet k := pushout_of_maps po\u2081\u2082.is_pushout po\u2083\u2084.is_pushout f\u2081\u2083 f\u2082\u2084 g\u2081\u2083 po_f.commutes s\u2081\u2083.symm in\nsuffices Is_pushout u\u2082'' k g\u2082\u2084 u\u2084'',\n  by convert weq_comp acof_u\u2084'.2 (pushout_is_acof this acof_u\u2082'').2; simp,\nhave _ := Is_pushout_of_Is_pushout_of_Is_pushout po_f po\u2083\u2084.is_pushout,\nhave Is_pushout f\u2081\u2082 (u\u2081 \u226b g\u2081\u2083) (u\u2082' \u226b k) po\u2083\u2084.map\u2081 := begin\n  convert this using 1,\n  { exact s\u2081\u2083.symm },\n  { simp }\nend,\nhave Is_pushout po\u2081\u2082.map\u2081 g\u2081\u2083 k po\u2083\u2084.map\u2081 :=\n  Is_pushout_of_Is_pushout_of_Is_pushout' po\u2081\u2082.is_pushout this (by simp),\nhave po_g' : Is_pushout (po\u2081\u2082.map\u2081 \u226b u\u2082'') g\u2081\u2083 g\u2082\u2084 (po\u2083\u2084.map\u2081 \u226b u\u2084'') := by convert po_g using 1; simp,\nIs_pushout_of_Is_pushout_of_Is_pushout_vert' this po_g' $\n  by apply po\u2081\u2082.is_pushout.uniqueness; rw [\u2190category.assoc, \u2190category.assoc]; simp [po_g.commutes]\n\nlemma gluing_weq : is_weq (pushout_of_maps po_f po_g u\u2081 u\u2082 u\u2083 s\u2081\u2082 s\u2081\u2083) :=\nlet \u27e8c\u2081\u27e9 := exists_brown_factorization ha\u2081 hb\u2081 u\u2081,\n    \u27e8c\u2082, h\u2081\u2082, hv\u2082, hr\u2082, hw\u2082, x, y\u27e9 :=\n      exists_relative_brown_factorization\n        ha\u2081 hb\u2081 (cofibrant_of_cof ha\u2081 hf\u2081\u2082) (cofibrant_of_cof hb\u2081 hg\u2081\u2082) u\u2081 u\u2082 f\u2081\u2082 g\u2081\u2082 s\u2081\u2082.symm c\u2081,\n    \u27e8c\u2083, h\u2081\u2083, hv\u2083, hr\u2083, hw\u2083, _, _\u27e9 :=\n      exists_relative_brown_factorization ha\u2081 hb\u2081 ha\u2083 hb\u2083 u\u2081 u\u2083 f\u2081\u2083 g\u2081\u2083 s\u2081\u2083.symm c\u2081,\n    po := pushout_by_cof c\u2081.f' f\u2081\u2082 c\u2081.hf' in\nhave cof_h\u2081\u2082 : is_cof h\u2081\u2082 := begin\n  convert cof_comp (pushout_is_cof po.is_pushout.transpose hf\u2081\u2082) (x hg\u2081\u2082) using 1,\n  simp\nend,\nhave wv : _ := gluing_weq_aux po_f (pushout_by_cof h\u2081\u2082 h\u2081\u2083 cof_h\u2081\u2082).is_pushout hf\u2081\u2082\n  (c\u2081.weq_f' hwu\u2081) (c\u2082.weq_f' hwu\u2082) (c\u2083.weq_f' hwu\u2083) hv\u2082.symm hv\u2083.symm c\u2081.hf' c\u2083.hf'\n  (by rw \u2190Is_pushout.transpose_induced; exact cof_comp (cof_iso _) (x hg\u2081\u2082)),\nhave ww : _ := gluing_weq_aux po_g (pushout_by_cof h\u2081\u2082 h\u2081\u2083 cof_h\u2081\u2082).is_pushout hg\u2081\u2082\n  c\u2081.hs.2 c\u2082.hs.2 c\u2083.hs.2 hw\u2082.symm hw\u2083.symm c\u2081.hs.1 c\u2083.hs.1\n  (by rw \u2190Is_pushout.transpose_induced; exact cof_comp (cof_iso _) (y hf\u2081\u2082).1),\nlet po_h := pushout_by_cof h\u2081\u2082 h\u2081\u2083 cof_h\u2081\u2082 in\nhave wr : is_weq (pushout_of_maps po_h.is_pushout po_g c\u2081.r c\u2082.r c\u2083.r hr\u2082.symm hr\u2083.symm), begin\n  refine (weq_iff_weq_inv _).mp ww,\n  rw \u2190pushout_of_maps_comp,\n  convert pushout_of_maps_id po_g,\n  { exact c\u2081.hsr }, { exact c\u2082.hsr }, { exact c\u2083.hsr }\nend,\nbegin\n  convert weq_comp wv wr,\n  rw \u2190pushout_of_maps_comp,\n  congr,\n  { exact c\u2081.hf'r.symm }, { exact c\u2082.hf'r.symm}, { exact c\u2083.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": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Util.CollectLevelParams\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.DefView\nimport Lean.Elab.Inductive\nimport Lean.Elab.Structure\nimport Lean.Elab.MutualDef\nimport Lean.Elab.DeclarationRange\nnamespace Lean.Elab.Command\n\nopen Meta\n\n/- Auxiliary function for `expandDeclNamespace?` -/\ndef expandDeclIdNamespace? (declId : Syntax) : Option (Name \u00d7 Syntax) :=\n  let (id, optUnivDeclStx) := expandDeclIdCore declId\n  let scpView := extractMacroScopes id\n  match scpView.name with\n  | Name.str Name.anonymous s _ => none\n  | Name.str pre s _            =>\n    let nameNew := { scpView with name := Name.mkSimple s }.review\n    if declId.isIdent then\n      some (pre, mkIdentFrom declId nameNew)\n    else\n      some (pre, declId.setArg 0 (mkIdentFrom declId nameNew))\n  | _ => none\n\n/- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/\ndef expandDeclNamespace? (stx : Syntax) : Option (Name \u00d7 Syntax) :=\n  if !stx.isOfKind `Lean.Parser.Command.declaration then none\n  else\n    let decl := stx[1]\n    let k := decl.getKind\n    if k == ``Lean.Parser.Command.abbrev ||\n       k == ``Lean.Parser.Command.def ||\n       k == ``Lean.Parser.Command.theorem ||\n       k == ``Lean.Parser.Command.constant ||\n       k == ``Lean.Parser.Command.axiom ||\n       k == ``Lean.Parser.Command.inductive ||\n       k == ``Lean.Parser.Command.classInductive ||\n       k == ``Lean.Parser.Command.structure then\n      match expandDeclIdNamespace? decl[1] with\n      | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId))\n      | none              => none\n    else if k == ``Lean.Parser.Command.instance then\n      let optDeclId := decl[3]\n      if optDeclId.isNone then none\n      else match expandDeclIdNamespace? optDeclId[0] with\n        | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId)))\n        | none              => none\n    else\n      none\n\ndef elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  -- leading_parser \"axiom \" >> declId >> declSig\n  let declId             := stx[1]\n  let (binders, typeStx) := expandDeclSig stx[2]\n  let scopeLevelNames \u2190 getLevelNames\n  let \u27e8name, declName, allUserLevelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName stx\n  runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do\n    Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration\n    let type \u2190 Term.elabType typeStx\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let type \u2190 instantiateMVars type\n    let type \u2190 mkForallFVars xs type\n    let type \u2190 mkForallFVars vars type (usedOnly := true)\n    let (type, _) \u2190 Term.levelMVarToParam type\n    let usedParams  := collectLevelParams {} type |>.params\n    match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with\n    | Except.error msg      => throwErrorAt stx msg\n    | Except.ok levelParams =>\n      let decl := Declaration.axiomDecl {\n        name        := declName,\n        levelParams := levelParams,\n        type        := type,\n        isUnsafe    := modifiers.isUnsafe\n      }\n      Term.ensureNoUnassignedMVars decl\n      addDecl decl\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking\n      if isExtern (\u2190 getEnv) declName then\n        compileDecl decl\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation\n\n/-\nleading_parser \"inductive \" >> declId >> optDeclSig >> optional \":=\" >> many ctor\nleading_parser atomic (group (\"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional \":=\" >> many ctor >> optDeriving\n-/\nprivate def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do\n  checkValidInductiveModifier modifiers\n  let (binders, type?) := expandOptDeclSig decl[2]\n  let declId           := decl[1]\n  let \u27e8name, declName, levelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName decl\n  let ctors      \u2190 decl[4].getArgs.mapM fun ctor => withRef ctor do\n    -- def ctor := leading_parser \" | \" >> declModifiers >> ident >> optional inferMod >> optDeclSig\n    let ctorModifiers \u2190 elabModifiers ctor[1]\n    if ctorModifiers.isPrivate && modifiers.isPrivate then\n      throwError \"invalid 'private' constructor in a 'private' inductive datatype\"\n    if ctorModifiers.isProtected && modifiers.isPrivate then\n      throwError \"invalid 'protected' constructor in a 'private' inductive datatype\"\n    checkValidCtorModifier ctorModifiers\n    let ctorName := ctor.getIdAt 2\n    let ctorName := declName ++ ctorName\n    let ctorName \u2190 withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName\n    let inferMod := !ctor[3].isNone\n    let (binders, type?) := expandOptDeclSig ctor[4]\n    addDocString' ctorName ctorModifiers.docString?\n    addAuxDeclarationRanges ctorName ctor ctor[2]\n    pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView }\n  let classes \u2190 getOptDerivingClasses decl[5]\n  pure {\n    ref             := decl\n    modifiers       := modifiers\n    shortDeclName   := name\n    declName        := declName\n    levelNames      := levelNames\n    binders         := binders\n    type?           := type?\n    ctors           := ctors\n    derivingClasses := classes\n  }\n\nprivate def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView :=\n  inductiveSyntaxToView modifiers decl\n\ndef elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let v \u2190 inductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\ndef elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let modifiers := modifiers.addAttribute { name := `class }\n  let v \u2190 classInductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\n@[builtinCommandElab declaration]\ndef elabDeclaration : CommandElab := fun stx =>\n  match expandDeclNamespace? stx with\n  | some (ns, newStx) => do\n    let ns := mkIdentFrom stx ns\n    let newStx \u2190 `(namespace $ns:ident $newStx end $ns:ident)\n    withMacroExpansion stx newStx $ elabCommand newStx\n  | none => do\n    let modifiers \u2190 elabModifiers stx[0]\n    let decl     := stx[1]\n    let declKind := decl.getKind\n    if declKind == ``Lean.Parser.Command.\u00abaxiom\u00bb then\n      elabAxiom modifiers decl\n    else if declKind == ``Lean.Parser.Command.\u00abinductive\u00bb then\n      elabInductive modifiers decl\n    else if declKind == ``Lean.Parser.Command.classInductive then\n      elabClassInductive modifiers decl\n    else if declKind == ``Lean.Parser.Command.\u00abstructure\u00bb then\n      elabStructure modifiers decl\n    else if isDefLike decl then\n      elabMutualDef #[stx]\n    else\n      throwError \"unexpected declaration\"\n\n/- Return true if all elements of the mutual-block are inductive declarations. -/\nprivate def isMutualInductive (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl     := elem[1]\n    let declKind := decl.getKind\n    declKind == `Lean.Parser.Command.inductive\n\nprivate def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do\n  let views \u2190 elems.mapM fun stx => do\n     let modifiers \u2190 elabModifiers stx[0]\n     inductiveSyntaxToView modifiers stx[1]\n  elabInductiveViews views\n\n/- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/\nprivate def isMutualDef (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl := elem[1]\n    isDefLike decl\n\nprivate def isMutualPreambleCommand (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  k == ``Lean.Parser.Command.variable ||\n  k == ``Lean.Parser.Command.universe ||\n  k == ``Lean.Parser.Command.check ||\n  k == ``Lean.Parser.Command.set_option ||\n  k == ``Lean.Parser.Command.open\n\nprivate partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax \u00d7 Array Syntax) :=\n  let rec loop (i : Nat) : Option (Array Syntax \u00d7 Array Syntax) :=\n    if h : i < elems.size then\n      let elem := elems.get \u27e8i, h\u27e9\n      if isMutualPreambleCommand elem then\n        loop (i+1)\n      else if i == 0 then\n        none -- `mutual` block does not contain any preamble commands\n      else\n        some (elems[0:i], elems[i:elems.size])\n    else\n      none -- a `mutual` block containing only preamble commands is not a valid `mutual` block\n  loop 0\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualNamespace : Macro := fun stx => do\n  let mut ns?      := none\n  let mut elemsNew := #[]\n  for elem in stx[1].getArgs do\n    match ns?, expandDeclNamespace? elem with\n    | _, none                         => elemsNew := elemsNew.push elem\n    | none, some (ns, elem)           => ns? := some ns; elemsNew := elemsNew.push elem\n    | some nsCurr, some (nsNew, elem) =>\n      if nsCurr == nsNew then\n        elemsNew := elemsNew.push elem\n      else\n        Macro.throwErrorAt elem s!\"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration\"\n  match ns? with\n  | some ns =>\n    let ns := mkIdentFrom stx ns\n    let stxNew := stx.setArg 1 (mkNullNode elemsNew)\n    `(namespace $ns:ident $stxNew end $ns:ident)\n  | none => Macro.throwUnsupported\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualElement : Macro := fun stx => do\n  let mut elemsNew := #[]\n  let mut modified := false\n  for elem in stx[1].getArgs do\n    match (\u2190 expandMacro? elem) with\n    | some elemNew => elemsNew := elemsNew.push elemNew; modified := true\n    | none         => elemsNew := elemsNew.push elem\n  if modified then\n    pure $ stx.setArg 1 (mkNullNode elemsNew)\n  else\n    Macro.throwUnsupported\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualPreamble : Macro := fun stx =>\n  match splitMutualPreamble stx[1].getArgs with\n  | none => Macro.throwUnsupported\n  | some (preamble, rest) => do\n    let secCmd    \u2190 `(section)\n    let newMutual := stx.setArg 1 (mkNullNode rest)\n    let endCmd    \u2190 `(end)\n    pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd])\n\n@[builtinCommandElab \u00abmutual\u00bb]\ndef elabMutual : CommandElab := fun stx => do\n  if isMutualInductive stx then\n    elabMutualInductive stx[1].getArgs\n  else if isMutualDef stx then\n    elabMutualDef stx[1].getArgs\n  else\n    throwError \"invalid mutual block\"\n\n/- leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"]\" >> many1 ident -/\n@[builtinCommandElab \u00abattribute\u00bb] def elabAttr : CommandElab := fun stx => do\n  let mut attrInsts := #[]\n  let mut toErase := #[]\n  for attrKindStx in stx[2].getSepArgs do\n    if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then\n      let attrName := attrKindStx[1].getId.eraseMacroScopes\n      unless isAttribute (\u2190 getEnv) attrName do\n        throwError \"unknown attribute [{attrName}]\"\n      toErase := toErase.push attrName\n    else\n      attrInsts := attrInsts.push attrKindStx\n  let attrs \u2190 elabAttrs attrInsts\n  let idents := stx[4].getArgs\n  for ident in idents do withRef ident <| liftTermElabM none do\n    let declName \u2190 resolveGlobalConstNoOverloadWithInfo ident\n    Term.applyAttributes declName attrs\n    for attrName in toErase do\n      Attribute.erase declName attrName\n\ndef expandInitCmd (builtin : Bool) : Macro := fun stx => do\n  let optVisibility := stx[0]\n  let optHeader     := stx[2]\n  let doSeq         := stx[3]\n  let attrId        := mkIdentFrom stx $ if builtin then `builtinInit else `init\n  if optHeader.isNone then\n    unless optVisibility.isNone do\n      Macro.throwError \"invalid initialization command, 'visibility' modifer is not allowed\"\n    `(@[$attrId:ident]def initFn : IO Unit := do $doSeq)\n  else\n    let id   := optHeader[0]\n    let type := optHeader[1][1]\n    if optVisibility.isNone then\n      `(def initFn : IO $type := do $doSeq\n        @[$attrId:ident initFn] constant $id : $type)\n    else if optVisibility[0].getKind == ``Parser.Command.private then\n      `(def initFn : IO $type := do $doSeq\n        @[$attrId:ident initFn] private constant $id : $type)\n    else if optVisibility[0].getKind == ``Parser.Command.protected then\n      `(def initFn : IO $type := do $doSeq\n        @[$attrId:ident initFn] protected constant $id : $type)\n    else\n      Macro.throwError \"unexpected visibility annotation\"\n\n@[builtinMacro Lean.Parser.Command.\u00abinitialize\u00bb] def expandInitialize : Macro :=\n  expandInitCmd (builtin := false)\n\n@[builtinMacro Lean.Parser.Command.\u00abbuiltin_initialize\u00bb] def expandBuiltinInitialize : Macro :=\n  expandInitCmd (builtin := true)\n\nend Lean.Elab.Command\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/Elab/Declaration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.029312231175339418, "lm_q1q2_score": 0.008156327463113539}}
{"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' : \u211d\u22650)\nvariables [fact (0 < r)] [fact (r < r')] [fact (r < 1)]\n\nsection\n\nopen bounded_homotopy_category\n\nvariables (BD : breen_deligne.data)\nvariables (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{u} r')\nvariables (V : SemiNormedGroup.{u})\n\nlemma QprimeFP_map (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) :\n  (QprimeFP r' BD \u03ba M).map h = of'_hom ((QprimeFP_int r' BD \u03ba _).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 : \u211d\u22650) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V \u27f6 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\u2081 (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\u2082 [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\u2083 [normed_with_aut r V] (X : Profinite) :\n  continuous.{u u}\n  (\u03bb (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 \u21a5V)).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 {\u03b2 : Type*} [uniform_space \u03b2] (a : abstract_completion \u03b2) : uniform_space a.space :=\nby apply_instance\n\nlemma final_boss_aux\u2084 [normed_with_aut r V] (X : Profinite) :\n@continuous.{u u} _ _ _ (uniform_space.completion.cpkg.uniform_struct.to_topological_space)\n  (\u03bb (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) \u2218 x.to_fun, continuous_to_fun :=\n  (normed_with_aut.T.inv.continuous.comp x.2)})) :=\nbegin\n  let e : C(X,V) \u2192 C(X,V) := \u03bb e, \u27e8(V_T_inv r V) \u2218 e,\n    (V_T_inv r V).continuous.comp e.2\u27e9,\n  have he : continuous e := continuous_map.continuous_comp\n    ((\u27e8(V_T_inv r V), (V_T_inv r V).continuous\u27e9 : 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) \u2218 x.1, continuous_to_fun :=\n      (normed_with_aut.T.inv.continuous.comp x.2)} :=\nbegin\n  rw final_boss_aux\u2081,\n  rw final_boss_aux\u2081,\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 \u21a5V) x,\n  { apply is_closed_eq,\n    { apply final_boss_aux\u2083 },\n    { apply final_boss_aux\u2084 } },\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 \u21a5V).compare uniform_space.completion.cpkg.{u}\n       ((locally_constant.pkg.{u} X \u21a5V).coe x)) = _,\n  --dsimp [abstract_completion.compare_equiv],\n  rw abstract_completion.compare_coe,\n  erw final_boss_aux\u2082,\n  erw uniform_space.completion.map_coe,\n  let q : C(X,V) :=\n    {to_fun := (normed_with_aut.T.{u}.inv) \u2218 ((locally_constant.pkg.{u} X \u21a5V).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 \u21a5V).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 \u21a5V).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\u2081 (X Y : Profinite.{u}) (f : X \u27f6 Y) :\n  (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map (freeCond.{u}.map f).op \u226b\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 \u226b\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 \u2192+ B) (g : B \u2192+ 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 \u2192+ B) (g : B \u2192+ 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 \u2192 Y) (hf : continuous f) (g : normed_add_group_hom V W) (\u03c6 : locally_constant Y V) :\n  locally_constant.comap_hom f hf (locally_constant.map_hom g \u03c6) =\n  ((locally_constant.map_hom g) \u2218 (locally_constant.comap_hom f hf)) \u03c6 :=\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 \u21a5(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 \u27f6 Y) (x) :\n  V.to_Cond.val.map f.op x = \u27e8continuous_map.comp_right_continuous_map V f x.down\u27e9 :=\nrfl\n\nlemma to_Cond_val_map (X Y : Profinite.{u}) (f : X \u27f6 Y) :\n  \u21d1(V.to_Cond.val.map f.op) =\n  (\u03bb x, \u27e8continuous_map.comp_right_continuous_map V f x.down\u27e9 : \u21a5(V.to_Cond.val.obj (op Y)) \u2192 \u21a5(V.to_Cond.val.obj (op X))) :=\nby { ext x, rw to_Cond_val_map_apply }\n\nlemma massive_aux\u2082 (X Y : Profinite.{u}) (f : X \u27f6 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 \u21a5V).compare uniform_space.completion.cpkg.{u} x.down) =\n  ((locally_constant.pkg.{u} X \u21a5V).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 \u03c6 : C(Y, V) \u2192 C(X, V) := _, change continuous \u03c6,\n      let \u03c8 := V.to_Cond.val.map f.op, have h\u03c8 : \u03c6 = ulift.down \u2218 \u03c8 \u2218 ulift.up := rfl,\n      rw h\u03c8, clear h\u03c8,\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 \u21a5V f)).comp continuous_induced_dom, } },\n  { intro \u03c6,\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 \u21a5(X.to_CompHaus.to_Top) \u21a5V),\n      { exact locally_constant.seminormed_add_comm_group },\n      letI : seminormed_add_comm_group (locally_constant \u21a5(Y.to_CompHaus.to_Top) \u21a5V),\n      { exact locally_constant.seminormed_add_comm_group },\n      exact normed_add_group_hom.uniform_continuous _, },\n    have : (continuous_map.comp_right_continuous_map \u21a5V f) ((locally_constant.pkg Y V).coe \u03c6) =\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 \u27f6 Y) :\n  (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y).hom \u226b\n      Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} Y)) \u226b\n        (ExtQprime_iso_aux_system_obj_aux'.{u} V Y).hom \u226b\n          (forget\u2082.{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}\u1d52\u1d56).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 \u226b\n      (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X).hom \u226b\n        Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} X)) \u226b\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\u2081_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\u2082_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 \u2218 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} \u21a5(unop.{u+2} (op.{u+2} X)) \u21a5V) := _,\n  erw [\u2190 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\u2082 V X Y f x,\nend\n\nlemma massive (X Y : FreeAb Profinite.{u}) (f : X \u27f6 Y) :\n  (((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y.as).hom \u226b\n    (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} Y.as) \u226b\n    (ExtQprime_iso_aux_system_obj_aux'.{u} V Y.as).hom) \u226b\n    (\ud835\udfd9 _)) \u226b\n    (forget\u2082.{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 \u22d9\n        FreeAb.eval.{u+1 u+2} SemiNormedGroup.{u+1}\u1d52\u1d56).map f).unop =\n  (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map\n    ((freeCond.{u}.map_FreeAb \u22d9 FreeAb.eval.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1})).map f).op \u226b\n    ((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X.as).hom \u226b\n    (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} X.as) \u226b\n    (ExtQprime_iso_aux_system_obj_aux'.{u} V X.as).hom) \u226b  \ud835\udfd9 _ :=\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\u2081 c\u2082) (h : c\u2081 \u27f6 c\u2082) :\n  (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c\u2082).hom \u226b\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) \u226b (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c\u2081).hom :=\nbegin\n  ext n : 2,\n  have aux : \u2200 (n : \u2115), (monotone.{0 0} (function.swap.{1 1 1} \u03ba n)),\n  { intro n, exact fact.out _ },\n  haveI : fact (\u03ba c\u2081 n \u2264 \u03ba c\u2082 n) := \u27e8aux n h.le\u27e9,\n  have := massive V\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c\u2081 n)\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c\u2082 n)\n    ((breen_deligne.FP2.res.{u} r' _ _ _).app \u27e8M\u27e9),\n  exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_\u03ba (c : (\u211d\u22650))\n  [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 \u03ba c n)] :\n  (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c).hom \u226b\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.\u03b9 BD \u03ba\u2082 \u03ba M).app _,\n  end \u226b (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba\u2082 M V c).hom :=\nbegin\n  ext n : 2,\n  have := massive V\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba\u2082 c n)\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c n)\n    ((breen_deligne.FP2.res.{u} r' _ _ _).app \u27e8M\u27e9),\n  exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv (c : \u211d\u22650)\n  [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] :\n  (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba M V c).hom \u226b\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 \u03ba\u2082 \u03ba M).app _,\n  end\n  \u226b (hom_complex_QprimeFP_nat_iso_aux_system r' BD \u03ba\u2082 M V c).hom :=\nbegin\n  ext n : 2,\n  have := massive V\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba\u2082 c n)\n    (breen_deligne.FPsystem.X.{u} r' BD \u27e8M\u27e9 \u03ba c n)\n    (((breen_deligne.FPsystem.Tinv.{u} r' BD \u27e8M\u27e9 \u03ba\u2082 \u03ba).app c).f n),\n  exact this,\nend\n\n\n\ndef to_Cond_T_inv (r : \u211d\u22650) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V.to_Cond \u27f6 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  {\u03b1 \u03b2 \u03b3 : Type*} [uniform_space \u03b1] [uniform_space \u03b2] [uniform_space \u03b3]\n  {g : \u03b2 \u2192 \u03b3} {f : \u03b1 \u2192 \u03b2}\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 \u2218 f) x :=\nbegin\n  rw [\u2190 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 : \u211d\u22650) (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 \u226b\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 _ _) _) \u226b\n  (ExtQprime_iso_aux_system_obj_aux' V X).hom\n   :=\nbegin\n  ext1 \u27e8f\u27e9,\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\u2082_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  \u226b (Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app (op X)\n  \u226b\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 _ \u226b\n  (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom \u226b\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 \u2190 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 \u2190 nat_trans.comp_app,\n  rw \u2190 Sheaf.hom.comp_val, -- how to make those commute?\n  ext \u27e8x\u27e9,\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\u2082, has_forget\u2082.forget\u2082],\n  apply final_boss,\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux (c : \u211d\u22650)\n  [normed_with_aut r V] (n : \u2115) (t) :\n((forget\u2082.{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 \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba).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 \u27e8M\u27e9 \u03ba).obj c).X n)).unop) t) =\n  (((ExtQprime_iso_aux_system_obj_aux.{u} V).hom.app\n        (((breen_deligne.FPsystem.{u} r' BD \u27e8M\u27e9 \u03ba).obj c).X n)).unop)\n        (t \u226b 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\u2082, has_forget\u2082.forget\u2082, 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\u2082, has_forget\u2082.forget\u2082, 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 \u27e8M\u27e9 \u03ba).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 (\u03bb 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 (\u03bb e, e s) at this,\n  erw this, clear this,\n  simp only [comp_apply],\n  congr' 1, dsimp only [s],\n  simp only [\u2190 comp_apply],\n  congr' 1,\n  simp only [category.assoc],\n  erw \u2190 another_aux_lemma r V X,\n  congr' 2,\n  ext1 \u27e8x\u27e9, 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 : \u211d\u22650)\n  [normed_with_aut r V] :\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V c).hom \u226b\n  ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n       (complex_shape.up.{0} \u2115)).map (nat_trans.app\n        ((aux_system.T_inv.{u u+1} r r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba)) _) =\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 \u2115).symm,\n    let Q := ((QprimeFP_nat r' BD \u03ba M).obj c).op,\n    exact e'.app Q,\n  end \u226b\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba 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\u2082_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\u2081 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) :\nhomological_complex.unop_functor.{u+2 u+1 0}.map\n    (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n         forget\u2082.{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} \u2124)).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 \u03ba M).map h))).op \u226b\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 \u22d9\n             forget\u2082.{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 \u03ba M).obj c\u2081)).op \u226b\n    embed_unop.{u+2 u+1}.hom.app\n      (op.{u+3}\n         (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n              forget\u2082.{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} \u2115)).obj\n            ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081))) =\n  begin\n    dsimp,\n    let e := (QprimeFP_nat r' BD \u03ba M).map h,\n    let e\u2081 := ((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n      forget\u2082.{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} \u2115)).map e,\n    let e\u2082 := homological_complex.unop_functor.map e\u2081.op,\n    refine _ \u226b\n      (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down).map\n      e\u2082,\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 \u22d9\n           forget\u2082.{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 \u03ba M).obj c\u2082)).op \u226b\n    embed_unop.{u+2 u+1}.hom.app\n    (op.{u+3}\n       (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n            forget\u2082.{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} \u2115)).obj\n          ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082)))\n  end := admit\n\ndef F : \u211d\u22650 \u2964\n  (homological_complex.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.down.{0} \u2115).symm)\u1d52\u1d56 :=\nQprimeFP_nat.{u} r' BD \u03ba M \u22d9\n  (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond \u22d9\n     forget\u2082.{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} \u2115) \u22d9 homological_complex.unop_functor.right_op\n\n@[reassoc]\nlemma naturality_helper {c\u2081 c\u2082 : \u211d\u22650} (h : c\u2081 \u27f6 c\u2082) (n : \u2115) (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 (-\u2191n) w1).hom.app\n    (((preadditive_yoneda.{u+1 u+2}.obj\n    V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} \u2115)).obj\n     ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082)).unop \u226b\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) \u226b\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 (-\u2191n) w2).hom.app\n    (((preadditive_yoneda.{u+1 u+2}.obj\n    V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} \u2115)).obj\n    ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081)).unop :=\nadmit\n-/\n\nlemma aux\u2081 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V c\u2082).hom \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  ((aux_system.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba).to_Ab.map h.op) =\n  (homology_functor _ _ _).map\n  (category_theory.functor.map _\n      (homological_complex.op_functor.map ((QprimeFP_nat r' BD \u03ba M).map h).op)) \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V c\u2081).hom :=\nbegin\n  rw [\u2190 functor.map_comp, \u2190 functor.map_comp],\n  congr' 1,\n  erw \u2190 hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_c,\nend\n\nlemma aux\u2082 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\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 (-\u2191n) (by { cases n; refl})).hom.app\n    (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond) \u226b\n    (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n    (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n    (complex_shape.down.{0} \u2115).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n    ((QprimeFP_nat.{u} r' BD \u03ba M).map h).op)) =\n  (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down \u22d9\n  homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} \u2124) (-\u2191n)).map\n  (category_theory.functor.map _\n      (homological_complex.op_functor.map ((QprimeFP_nat r' BD \u03ba M).map h).op)) \u226b\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 (-\u2191n) (by { cases n; refl})).hom.app\n  (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081) V.to_Cond) :=\nbegin\n  erw nat_trans.naturality,\nend\n\n\nlemma aux\u2083 (c\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond).hom \u226b\n  (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down \u22d9\n  homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} \u2124) (-\u2191n)).map\n  (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n  (complex_shape.down.{0} \u2115).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n  ((QprimeFP_nat.{u} r' BD \u03ba M).map h).op))\n  =\n  ((homology_functor.{u+1 u+2 0} AddCommGroup.{u+1}\n  (complex_shape.up.{0} \u2124).symm (-\u2191n)).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} \u2124)).map ((QprimeFP_int.{u} r' BD \u03ba M).map h)))).unop \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2081) V.to_Cond).hom\n  :=\nbegin\n  dsimp only [functor.op_map, functor.comp_map],\n  erw [\u2190 functor.map_comp],\n  erw [\u2190 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\u2082 : \u211d\u22650} (n : \u2115) :\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond).hom \u226b\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 (-\u2191n) (by { cases n; refl})).hom.app\n  (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj c\u2082) V.to_Cond) =\n  _\n-/\n\nend ExtQprime_iso_aux_system_obj_naturality_setup\n\nlemma QprimeFP_acyclic (c) (k i : \u2124) (hi : 0 < i) :\n  is_zero (((Ext' i).obj (op (((QprimeFP_int.{u} r' BD \u03ba M).obj c).X k))).obj V.to_Cond) :=\nbegin\n  rcases k with ((_|k)|k),\n  { apply free_acyclic, exact hi },\n  { rw [\u2190 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\u2081 c\u2082 : \u211d\u22650) (h : c\u2081 \u27f6 c\u2082) (n : \u2115) :\n  (ExtQprime_iso_aux_system_obj r' BD \u03ba M V c\u2082 n).hom \u226b\n  (homology_functor _ _ _).map\n  ((system_of_complexes.to_Ab _).map h.op)  =\n  ((Ext n).map ((QprimeFP r' BD \u03ba _).map h).op).app _ \u226b\n  (ExtQprime_iso_aux_system_obj r' BD \u03ba M V c\u2081 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2081)).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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2082)).is_bounded_above :=\n    chain_complex.is_bounded_above _,\n  have := Ext_compute_with_acyclic_naturality\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2081)\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c\u2082)\n    V.to_Cond _ _\n    ((QprimeFP_int.{u} r' BD \u03ba 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\u2081 r' BD \u03ba M V c\u2081 c\u2082 h n,\n  simp only [\u2190 category.assoc], congr' 1,\n  simp only [category.assoc],\n  rw ExtQprime_iso_aux_system_obj_naturality_setup.aux\u2082 r' BD \u03ba M V c\u2081 c\u2082 h n,\n  simp only [\u2190 category.assoc], congr' 1,\n\n  exact ExtQprime_iso_aux_system_obj_naturality_setup.aux\u2083 r' BD \u03ba M V c\u2081 c\u2082 h n,\n\n  --- OLD PROOF FROM HERE\n  --have := ExtQprime_iso_aux_system_obj_naturality_setup.naturality_helper r' BD \u03ba\n  --  M V h n _ _,\n  --simp only [category.assoc, functor.map_comp],\n  --slice_rhs 3 4\n  --{ erw \u2190 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 [\u2190 functor.map_comp, \u2190 functor.map_comp_assoc, category.assoc],\n  dsimp [-homology_functor_map],\n  rw ExtQprime_iso_aux_system_obj_naturality_setup.aux\u2081,\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 [\u2190 functor.comp_map, \u2190 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 : \u2115) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u2245\n  aux_system r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba \u22d9\n    (forget\u2082 _ Ab).map_homological_complex _ \u22d9 homology_functor _ _ n :=\nnat_iso.of_components (\u03bb c, ExtQprime_iso_aux_system_obj r' BD \u03ba M V (unop c) n)\nbegin\n  intros c\u2081 c\u2082 h,\n  dsimp [-homology_functor_map],\n  rw \u2190 ExtQprime_iso_aux_system_obj_natrality,\n  refl,\nend\n\n/-- The `Tinv` map induced by `M` -/\ndef ExtQprime.Tinv\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (n : \u2124) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u27f6\n  (QprimeFP r' BD \u03ba\u2082 M).op \u22d9 (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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (n : \u2124) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u27f6\n  (QprimeFP r' BD \u03ba\u2082 M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nwhisker_right (nat_trans.op $ QprimeFP.\u03b9 BD _ _ M) _ \u226b 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n  (n : \u2124) :\n  (QprimeFP r' BD \u03ba M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) \u27f6\n  (QprimeFP r' BD \u03ba\u2082 M).op \u22d9 (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nExtQprime.Tinv r' BD \u03ba \u03ba\u2082 M V n - ExtQprime.T_inv r r' BD \u03ba \u03ba\u2082 M V n\n\nnamespace ExtQprime_iso_aux_system_comm_Tinv_setup\n\nvariables (c : (\u211d\u22650)\u1d52\u1d56) (n : \u2115)\n  [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)]\n\nlemma aux\u2081  :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n    (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V (unop.{1} c)).hom \u226b\n  ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n       (complex_shape.up.{0} \u2115) \u22d9\n     homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n    ((aux_system.Tinv.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba\u2082 \u03ba).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 \u03ba\u2082 \u03ba M).app _))) \u226b\n  (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba\u2082 M V (unop.{1} c)).hom :=\nbegin\n  simp only [\u2190 functor.map_comp, functor.comp_map], congr' 1,\n  apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv,\nend\n\nlemma aux\u2082 :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n      (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj (unop.{1} c)) V.to_Cond).hom \u226b\n    (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down \u22d9\n       homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} \u2124) (-\u2191n)).map\n      (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex (complex_shape.down.{0} \u2115).symm).map\n         (homological_complex.op_functor.{u+2 u+1 0}.map ((QprimeFP_nat.Tinv.{u} BD \u03ba\u2082 \u03ba 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} \u2124) \u22d9\n        homological_complex.unop_functor.{u+2 u+1 0}.right_op \u22d9\n          (homology_functor.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).op).map\n       ((QprimeFP_int.Tinv.{u} BD \u03ba\u2082 \u03ba M).app (unop.{1} c))).unop \u226b\n    (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2124).symm (-\u2191n)).map\n      (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom :=\nbegin\n  dsimp only [functor.op_map, functor.comp_map],\n  erw [\u2190 functor.map_comp],\n  erw [\u2190 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] (n : \u2115) :\n  (ExtQprime_iso_aux_system r' BD \u03ba M V n).hom \u226b\n  whisker_right (aux_system.Tinv.{u} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba\u2082 \u03ba)\n    ((forget\u2082 _ _).map_homological_complex _ \u22d9 homology_functor Ab.{u+1} (complex_shape.up \u2115) n) =\n  ExtQprime.Tinv r' BD \u03ba \u03ba\u2082 M V n \u226b\n  (ExtQprime_iso_aux_system r' BD \u03ba\u2082 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba\u2082 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 \u03ba\u2082 M).obj c.unop)\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c.unop)\n    V.to_Cond _ _\n    ((QprimeFP_int.Tinv BD \u03ba\u2082 \u03ba 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\u2081 r' BD \u03ba \u03ba\u2082 M V c n,\n  simp only [\u2190 category.assoc], congr' 1, simp only [category.assoc],\n  erw \u2190 nat_trans.naturality,\n  simp only [\u2190 category.assoc], congr' 1,\n  exact ExtQprime_iso_aux_system_comm_Tinv_setup.aux\u2082 r' BD \u03ba \u03ba\u2082 M V c n,\nend\n\n\n-- lemma ExtQprime_iso_aux_system_comm_T_inv [normed_with_aut r V] (n : \u2115) (c : \u211d\u22650\u1d52\u1d56) :\n--   (ExtQprime_iso_aux_system_obj.{u} r' BD \u03ba\u2082 M V (unop.{1} c) n).hom \u226b\n--     ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex (complex_shape.up.{0} \u2115) \u22d9\n--    homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} \u2115) n).map\n--   ((aux_system.res.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba\u2082 \u03ba).app c) =\n--   ((Ext.{u+1 u+2} \u2191n).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 \u03ba\u2082 M).op.obj c) \u226b\n--     (ExtQprime_iso_aux_system_obj.{u} r' BD \u03ba\u2082 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\u2081 C\u2082 : homological_complex A\u1d52\u1d56 c) (f : C\u2081 \u27f6 C\u2082) :\n  C\u2082.unop \u27f6 C\u2081.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] [\u2200 (c : \u211d\u22650) (n : \u2115), fact (\u03ba\u2082 c n \u2264 \u03ba c n)]\n\ndef hom_complex_map_T_inv (c : (\u211d\u22650)\u1d52\u1d56) :\n  hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj (unop.{1} c)) V.to_Cond \u27f6\n  hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 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 \u226b\n  (category_theory.functor.map _\n      (homological_complex.op_functor.map (quiver.hom.op $\n      (QprimeFP_nat.\u03b9 BD \u03ba\u2082 \u03ba M).app _)))\n\nomit r\n\nlemma embed_hom_complex_nat_iso\u2080 (c : (\u211d\u22650)\u1d52\u1d56) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom.f (int.of_nat 0) = \ud835\udfd9 _ := rfl\n\nlemma embed_hom_complex_nat_iso_neg (n : \u2115) (c : (\u211d\u22650)\u1d52\u1d56) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom.f (-[1+ n]) = \ud835\udfd9 _ := rfl\n\n\nlemma add_equiv.to_AddCommGroup_iso_apply (A B : AddCommGroup.{u})\n  (e : A \u2243+ 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\u2081 (c : (\u211d\u22650)\u1d52\u1d56):\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba M V (unop.{1} c)).hom \u226b\n  ((forget\u2082.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n     (complex_shape.up.{0} \u2115)).map ((aux_system.T_inv.{u u+1} r r' BD\n    \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba).app c \u226b\n  (aux_system.res.{u u+1} r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1 u}.obj V) \u03ba\u2082 \u03ba).app c) =\n  hom_complex_map_T_inv _ _ _ _ _ _ _ _ \u226b\n  (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD \u03ba\u2082 M V (unop.{1} c)).hom :=\nbegin\n  --simp only [\u2190 category_theory.functor.map_comp, functor.comp_map], congr' 1,\n  dsimp only [hom_complex_map_T_inv], simp only [category.assoc],\n  rw \u2190 hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_\u03ba r' BD \u03ba \u03ba\u2082 M V c.unop,\n  simp only [functor.map_comp, \u2190 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\u2082_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\u2082 (c : (\u211d\u22650)\u1d52\u1d56) :\n((((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} \u21a5V)).right_op.map_homological_complex\n         (complex_shape.up.{0} \u2124)).obj\n        ((QprimeFP_int.{u} r' BD \u03ba M).obj (unop.{1} c))).map_unop\n       (((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} \u21a5V)).right_op.map_homological_complex\n           (complex_shape.up.{0} \u2124)).obj\n          ((QprimeFP_int.{u} r' BD \u03ba 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} \u2124)).app\n          ((QprimeFP_int.{u} r' BD \u03ba M).obj (unop.{1} c))) \u226b\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} \u2124)).map\n           ((QprimeFP_int.\u03b9.{u} BD \u03ba\u2082 \u03ba M).app (unop.{1} c)))).unop) \u226b\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba\u2082 M).obj (unop.{1} c)) V.to_Cond).hom =\n  (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD \u03ba M).obj (unop.{1} c)) V.to_Cond).hom \u226b\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\u2080,\n  rw embed_hom_complex_nat_iso\u2080,\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 \u2124)\n  [((homotopy_category.quotient A (complex_shape.up.{0} \u2124)).obj X).is_bounded_above]\n  {B\u2081 B\u2082 : A} (f : B\u2081 \u27f6 B\u2082) -- (h\u2081) (h\u2082) (i)\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux\u2081_naturality_snd_var (i)\n  (e : (0 : \u2124) - i = -i) :\n  (Ext_compute_with_acyclic_aux\u2081 X B\u2081 i).hom \u226b\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) \u226b\n  (Ext_compute_with_acyclic_aux\u2081 X B\u2082 i).hom :=\nbegin\n  ext t,\n  simp only [comp_apply],\n  dsimp [Ext_compute_with_acyclic_aux\u2081, Ext],\n  simp only [category.assoc],\n  generalize_proofs h1 h2,\n  let \u03c6\u2081 := \u03bb j, (single _ j).obj B\u2081,\n  let \u03c6\u2082 := \u03bb j, (single _ j).obj B\u2082,\n  change t \u226b _ \u226b eq_to_hom (congr_arg \u03c6\u2081 e) \u226b _ =\n    _ \u226b _ \u226b _ \u226b eq_to_hom (congr_arg \u03c6\u2082 e),\n  induction e,\n  dsimp, simp only [category.id_comp, category.comp_id],\n  erw \u2190 nat_trans.naturality,\n  refl,\nend\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux\u2082_naturality_snd_var (i) :\n  (Ext_compute_with_acyclic_aux\u2082 X B\u2081 i).hom \u226b\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) _ \u226b\n  (Ext_compute_with_acyclic_aux\u2082 X B\u2082 i).hom :=\nbegin\n  dsimp only [Ext_compute_with_acyclic_aux\u2082, unop_op],\n  have := hom_single_iso_naturality_snd_var_good (of' X).replace (-i) f,\n  erw \u2190 this,\nend\n\ninclude f\nlemma Ext_compute_with_acyclic_aux\u2083_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 \u226b Ext_compute_with_acyclic_aux\u2083 X B\u2082 i =\n  Ext_compute_with_acyclic_aux\u2083 X B\u2081 i \u226b\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\u2083],\n  erw \u2190 (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n    (complex_shape.up.{0} \u2124).symm (-i)).map_comp,\n  erw \u2190 (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n    (complex_shape.up.{0} \u2124).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\u2081) (h\u2082) (i) :\n  (Ext_compute_with_acyclic X B\u2081 h\u2081 i).hom \u226b\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) \u226b (Ext_compute_with_acyclic X B\u2082 h\u2082 i).hom :=\nbegin\n  dsimp [Ext_compute_with_acyclic, - homology_functor_map],\n  simp only [category.assoc],\n  rw \u2190 Ext_compute_with_acyclic_aux\u2081_naturality_snd_var_assoc,\n  rw \u2190 Ext_compute_with_acyclic_aux\u2082_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\u2083_naturality_snd_var,\n  simp,\nend\n\nend naturality_snd_var\n\nlemma ExtQprime_iso_aux_system_comm [normed_with_aut r V]\n  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] (n : \u2115) :\n  (ExtQprime_iso_aux_system r' BD \u03ba M V n).hom \u226b\n  whisker_right (aux_system.Tinv2.{u} r r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba\u2082 \u03ba)\n    ((forget\u2082 _ _).map_homological_complex _ \u22d9 homology_functor Ab.{u+1} (complex_shape.up \u2115) n) =\n  ExtQprime.Tinv2 r r' BD \u03ba \u03ba\u2082 M V n \u226b\n  (ExtQprime_iso_aux_system r' BD \u03ba\u2082 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 [\u2190 nat_trans.comp_app, \u2190 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba 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} \u2124)).obj\n     ((QprimeFP_int.{u} r' BD \u03ba\u2082 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 \u03ba\u2082 M).obj c.unop)\n    ((QprimeFP_int.{u} r' BD \u03ba M).obj c.unop)\n    V.to_Cond _ _\n    ((QprimeFP_int.\u03b9 BD \u03ba\u2082 \u03ba 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 \u03b7 := (Ext.{u+1 u+2} \u2191n).map ((nat_trans.op.{0 u+1 0 u+2} (QprimeFP.\u03b9.{u} BD \u03ba\u2082 \u03ba M)).app c),\n\n  slice_rhs 1 2 { erw \u2190 \u03b7.naturality },\n  slice_rhs 2 3 { erw this },\n  simp only [category.assoc], clear this \u03b7,\n\n  let t : Condensed.of_top_ab V \u27f6 _ :=\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 \u03ba 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 \u2190 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 \u2190 category_theory.functor.map_comp },\n  slice_lhs 4 5 { rw \u2190 category_theory.functor.map_comp },\n  simp only [category.assoc,\n    \u2190 category_theory.functor.map_comp, \u2190 functor.map_comp_assoc],\n\n  rw ExtQprime_iso_aux_system_comm_setup.aux\u2081 r r' BD \u03ba \u03ba\u2082 M V c,\n  slice_lhs 2 4\n  { simp only [category_theory.functor.map_comp] },\n\n  simp only [\u2190 category.assoc], congr' 1,\n\n  rw ExtQprime_iso_aux_system_comm_setup.aux\u2082 r r' BD \u03ba \u03ba\u2082 M V c,\n  simp only [category_theory.functor.map_comp, category.assoc],\n  congr' 1,\n\n  rw [nat_iso.app_hom, \u2190 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  [\u2200 c n, fact (\u03ba\u2082 c n \u2264 \u03ba c n)] [\u2200 c n, fact (\u03ba\u2082 c n \u2264 r' * \u03ba c n)] (n : \u2115) :\n  whisker_right (aux_system.Tinv2.{u} r r' BD \u27e8M\u27e9 (SemiNormedGroup.ulift.{u+1}.obj V) \u03ba\u2082 \u03ba)\n    ((forget\u2082 _ _).map_homological_complex _ \u22d9 homology_functor Ab.{u+1} (complex_shape.up \u2115) n) \u226b\n  (ExtQprime_iso_aux_system r' BD \u03ba\u2082 M V n).inv =\n  (ExtQprime_iso_aux_system r' BD \u03ba M V n).inv \u226b\n  ExtQprime.Tinv2 r r' BD \u03ba \u03ba\u2082 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 \u2964 D) {X Y Z W : C}\n  {f\u2081 : X \u27f6 Y} {g\u2081 : X \u27f6 Z} {g\u2082 : Y \u27f6 W} {f\u2082 : Z \u27f6 W} (sq : commsq f\u2081 g\u2081 g\u2082 f\u2082) :\n  commsq (F.map f\u2081) (F.map g\u2081) (F.map g\u2082) (F.map f\u2082) :=\ncommsq.of_eq $ by rw [\u2190 F.map_comp, sq.w, F.map_comp]\n\nend\n\nsection\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (\u03ba \u03ba\u2082 : \u211d\u22650 \u2192 \u2115 \u2192 \u211d\u22650)\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba c)] [\u2200 n, fact (monotone (function.swap \u03ba n))]\nvariables [\u2200 (c : \u211d\u22650), BD.data.suitable (\u03ba\u2082 c)] [\u2200 n, fact (monotone (function.swap \u03ba\u2082 n))]\nvariables (M : ProFiltPseuNormGrpWithTinv\u2081.{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 \u2124)).obj\n    ((BD.eval' freeCond').obj M.to_Condensed)).is_bounded_above :=\nby { delta breen_deligne.package.eval', refine \u27e8\u27e81, _\u27e9\u27e9, apply chain_complex.bounded_by_one }\n\nvariables (\u03b9 : ulift.{u+1} \u2115 \u2192 \u211d\u22650) (h\u03b9 : monotone \u03b9)\n\ndef Ext_Tinv2\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A B V : bounded_homotopy_category \ud835\udcd0}\n  (Tinv : A \u27f6 B) (\u03b9 : A \u27f6 B) (T_inv : V \u27f6 V) (i : \u2124) :\n  ((Ext i).obj (op B)).obj V \u27f6 ((Ext i).obj (op A)).obj V :=\n(((Ext i).map Tinv.op).app V - (((Ext i).map \u03b9.op).app V \u226b ((Ext i).obj _).map T_inv))\n\nopen category_theory.preadditive\n\ndef Ext_Tinv2_commsq\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A\u2081 B\u2081 A\u2082 B\u2082 V : bounded_homotopy_category \ud835\udcd0}\n  (Tinv\u2081 : A\u2081 \u27f6 B\u2081) (\u03b9\u2081 : A\u2081 \u27f6 B\u2081)\n  (Tinv\u2082 : A\u2082 \u27f6 B\u2082) (\u03b9\u2082 : A\u2082 \u27f6 B\u2082)\n  (f : A\u2081 \u27f6 A\u2082) (g : B\u2081 \u27f6 B\u2082) (sqT : f \u226b Tinv\u2082 = Tinv\u2081 \u226b g) (sq\u03b9 : f \u226b \u03b9\u2082 = \u03b9\u2081 \u226b g)\n  (T_inv : V \u27f6 V) (i : \u2124) :\n  commsq\n    (((Ext i).map g.op).app V)\n    (Ext_Tinv2 Tinv\u2082 \u03b9\u2082 T_inv i)\n    (Ext_Tinv2 Tinv\u2081 \u03b9\u2081 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, \u2190 nat_trans.comp_app, \u2190 functor.map_comp, \u2190 op_comp, sqT,\n    \u2190 nat_trans.naturality, \u2190 nat_trans.naturality_assoc, category.assoc, sq\u03b9],\nend\n\nopen category_theory.preadditive\n\nlemma auux\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A\u2081 B\u2081 A\u2082 B\u2082 : cochain_complex \ud835\udcd0 \u2124}\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2082).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2082).is_bounded_above]\n  {f\u2081 : A\u2081 \u27f6 B\u2081} {f\u2082 : A\u2082 \u27f6 B\u2082} {\u03b1 : A\u2081 \u27f6 A\u2082} {\u03b2 : B\u2081 \u27f6 B\u2082}\n  (sq1 : commsq f\u2081 \u03b1 \u03b2 f\u2082) :\n  of_hom f\u2081 \u226b of_hom \u03b2 = of_hom \u03b1 \u226b of_hom f\u2082 :=\nbegin\n  have := sq1.w,\n  apply_fun (\u03bb 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  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A : cochain_complex \ud835\udcd0 \u2124}\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A).is_bounded_above] :\n  of_hom (\ud835\udfd9 A) = \ud835\udfd9 _ :=\nby { delta of_hom, rw [category_theory.functor.map_id], refl }\n\nlemma Ext_iso_of_bicartesian_of_bicartesian\n  {\ud835\udcd0 : Type*} [category \ud835\udcd0] [abelian \ud835\udcd0] [enough_projectives \ud835\udcd0]\n  {A\u2081 B\u2081 C A\u2082 B\u2082 : cochain_complex \ud835\udcd0 \u2124}\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2081).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj C).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj A\u2082).is_bounded_above]\n  [((homotopy_category.quotient \ud835\udcd0 (complex_shape.up \u2124)).obj B\u2082).is_bounded_above]\n  {f\u2081 : A\u2081 \u27f6 B\u2081} {g\u2081 : B\u2081 \u27f6 C} (w\u2081 : \u2200 n, short_exact (f\u2081.f n) (g\u2081.f n))\n  {f\u2082 : A\u2082 \u27f6 B\u2082} {g\u2082 : B\u2082 \u27f6 C} (w\u2082 : \u2200 n, short_exact (f\u2082.f n) (g\u2082.f n))\n  (\u03b1 : A\u2081 \u27f6 A\u2082) (\u03b2 : B\u2081 \u27f6 B\u2082) (\u03b3 : C \u27f6 C)\n  (\u03b9A : A\u2081 \u27f6 A\u2082) (\u03b9B : B\u2081 \u27f6 B\u2082)\n  (sq1 : commsq f\u2081 \u03b1 \u03b2 f\u2082) (sq2 : commsq g\u2081 \u03b2 \u03b3 g\u2082)\n  (sq1' : commsq f\u2081 \u03b9A \u03b9B f\u2082) (sq2' : commsq g\u2081 \u03b9B (\ud835\udfd9 _) g\u2082)\n  (V : bounded_homotopy_category \ud835\udcd0) (T_inv : V \u27f6 V)\n  (i : \u2124)\n  (H1 : (Ext_Tinv2_commsq (of_hom \u03b1) (of_hom \u03b9A) (of_hom \u03b2) (of_hom \u03b9B) (of_hom f\u2081) (of_hom f\u2082)\n    (auux sq1) (auux sq1') T_inv i).bicartesian)\n  (H2 : (Ext_Tinv2_commsq (of_hom \u03b1) (of_hom \u03b9A) (of_hom \u03b2) (of_hom \u03b9B) (of_hom f\u2081) (of_hom f\u2082)\n    (auux sq1) (auux sq1') T_inv (i+1)).bicartesian) :\n  is_iso (Ext_Tinv2 (of_hom \u03b3) (\ud835\udfd9 _) T_inv (i+1)) :=\nbegin\n  have LES\u2081 := (((Ext_five_term_exact_seq' _ _ i V w\u2081).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w\u2081)),\n  replace LES\u2081 := (((Ext_five_term_exact_seq' _ _ i V w\u2081).drop 1).pair.cons LES\u2081).extract 0 4,\n  have LES\u2082 := (((Ext_five_term_exact_seq' _ _ i V w\u2082).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w\u2082)).extract 0 4,\n  replace LES\u2082 := (((Ext_five_term_exact_seq' _ _ i V w\u2082).drop 1).pair.cons LES\u2082).extract 0 4,\n  refine iso_of_bicartesian_of_bicartesian LES\u2082 LES\u2081 _ _ _ _ H1 H2,\n  { apply commsq.of_eq, delta Ext_Tinv2, clear LES\u2081 LES\u2082,\n    rw [sub_comp, comp_sub, \u2190 functor.flip_obj_map, \u2190 functor.flip_obj_map],\n    rw \u2190 Ext_\u03b4_natural i V _ _ _ _ \u03b1 \u03b2 \u03b3 sq1.w sq2.w w\u2081 w\u2082,\n    congr' 1,\n    rw [\u2190 nat_trans.naturality, \u2190 functor.flip_obj_map, category.assoc,\n      Ext_\u03b4_natural i V _ _ _ _ \u03b9A \u03b9B (\ud835\udfd9 _) sq1'.w sq2'.w w\u2081 w\u2082],\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_\u03b4_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 data.rat\nimport data.list\n\nimport tidy.lib.list\nimport tidy.rewrite_search.core.shared\n\nimport ..types\nimport .common\n\nopen tactic\nopen tidy.rewrite_search\n\nnamespace tidy.rewrite_search.discovery\n\ndef BUNDLE_CHUNK_SIZE := 1\n\n-- TODO Be smarter about calculating this.\nmeta def score_bundle (b : bundle_ref) (sample : list expr) : tactic \u211a := do\n  mems \u2190 b.get_members,\n  mems.mfoldl (\u03bb sum n, do\n    e \u2190 mk_const n,\n    ret \u2190 are_promising_rewrites (rewrite_list_from_lemma e) sample,\n    return $ if ret then sum + 1 else sum\n  ) 0\n\n-- TODO report the lemma(s) which caused a selected bundle to be chosen,\n-- so that that lemma could just be tagged individually.\n\n-- TODO at the end of the search report which \"desperations\" things happened\n-- (bundles added, random lemmas found and used) so that they can be addressed\n-- more easily/conveniently.\n\nmeta def try_bundles (conf : config) (p : progress) (sample : list expr) : tactic (progress \u00d7 list (expr \u00d7 bool)) :=\n  if p.persistence < persistence.try_bundles then\n    return (p, [])\n  else do\n    bs \u2190 list.filter (\u03bb b, \u00acp.seen_bundles.contains b) <$> get_bundles,\n    bs \u2190 bs.mmap $ \u03bb b, (do s \u2190 score_bundle b sample, return (b, s)),\n    (awful_bs, interesting_bs) \u2190 pure $ bs.partition $ \u03bb b, b.2 = 0,\n    let p := {p with seen_bundles := p.seen_bundles.append (awful_bs.map prod.fst)},\n    match interesting_bs.min_rel (\u03bb a b, a.2 > b.2) with\n    | none := do\n      if conf.trace_discovery then\n      discovery_trace format!\"Could not find any promising bundles of the {bs.length} non-suggested bundles considered: {bs.map $ \u03bb b, b.1.bundle.name}\"\n      else skip,\n      return (p, [])\n    | some (b, score) := do\n      if conf.trace_discovery then\n      discovery_trace format!\"Found a promising bundle (of {bs.length} considered) \\\"{b.bundle.name}\\\"! If we succeed, please suggest this bundle for consideration.\"\n      else skip,\n      ms \u2190 b.get_members >>= load_names,\n      return (p, rewrite_list_from_lemmas ms)\n    end\n\nend tidy.rewrite_search.discovery", "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/tidy/rewrite_search/discovery/collector/bundle.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.023330770039329245, "lm_q1q2_score": 0.008134159477807112}}
{"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) \u2190 IO.mkRef (HashMap.empty) \n\ndef getTacticString : TacticM String := do\n  let s \u2190 saveState\n  let target \u2190 getMainTarget\n  let lctx \u2190  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} : {\u2190 t.view}) \"\n      pure ()\n    | some <| LocalDecl.cdecl _ _ n t bi _ => do\n      let core := s!\"{n.eraseMacroScopes} : {\u2190 t.view}\"\n      let typeString :=s!\"{\u2190 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 ++ \": \" ++ (\u2190  target.view)\n  s.restore\n  return statement.replace \"\u271d\" \"\"\n\nelab \"name_inacessibles\" : tactic => do\n  withMainContext do\n  let lctx \u2190  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 (\u2190 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 \u2190 getTacticString\n    logInfo view\n    return ()\n\ndef silly {\u03b1  : Type}(n m : Nat)[DecidableEq \u03b1] : 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)  \u2192  n + m = n + m := by\n    intros\n    show_goal  \n    rfl\n    done\n\nexample : (n m : Nat)  \u2192  n + m = n + m := by\n    intros\n    name_inacessibles  \n    rfl\n    done\n\nstructure TacticStateProxy where\n  binders: Array <| Name \u00d7  BinderInfo\n  letData : Array <| Name \u00d7 Expr \u00d7 Expr\n  target : Expr \n\ndef getTacticStateProxy : TacticM <| Option TacticStateProxy := \n  withoutModifyingState do\n  try \n    let target \u2190 getMainTarget\n    let lctx \u2190  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 \u2190 mkForallFVars fvars t\n        let b \u2190 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 \u2190 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\u2081 s\u2082 : TacticStateProxy) : TacticM Bool := \n   withMainContext do\n    return s\u2081.binders == s\u2082.binders \n            && s\u2081.letData.size == s\u2082.letData.size && \n            (\u2190 isDefEq s\u2081.target s\u2082.target) && \n            (\u2190 (List.range s\u2081.letData.size).allM (fun i => \n              let (n\u2081, t\u2081, b\u2081) := s\u2081.letData.get! i\n              let (n\u2082, t\u2082, b\u2082) := s\u2082.letData.get! i\n              return n\u2081 == n\u2082 && (\u2190 isDefEq t\u2081 t\u2082) && (\u2190 isDefEq b\u2081 b\u2082)))\n\ndef firstEffectiveTactic (tacStrings: List String)(warnOnly: Bool := Bool.true) : TacticM Unit :=\n  withMainContext do\n  let env \u2190 getEnv\n  let goal \u2190 getTacticString\n  logInfo m!\"goal: {goal}\"\n  logInfo m!\"trying tactics: {tacStrings}\"\n  let s \u2190 saveState\n  let s\u2081? \u2190 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 \u2190 getUnsolvedGoals\n          if gs.isEmpty then\n              logInfo m!\"tactic `{tacString}` was effective\"\n              return \n          else\n            let check : Bool \u2190 \n            try \n              let s\u2082? \u2190 getTacticStateProxy  \n              match s\u2081?, s\u2082? with\n              | some s\u2081, some s\u2082 => equalStates s\u2081 s\u2082          \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 \u2190\n                try\n                  let target \u2190 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)  \u2192  n + m = n + m := by\n    first_effective_tactic \n    rfl\n\ndef silly'''' : (n m : Nat)  \u2192  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 \u2190   \n        IO.Process.output {cmd:= \"curl\", args:= \n          #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{\u2190 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 \u2190 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 := \": \u2200 p : Nat, Prime p \u2192 (p % 4 = 1) \u2192 \u2203 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 \u2190 getTacticString\n  let prompts \u2190 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 \u2190 getTacticString\n  let prompts \u2190 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 \u2190 makeTacticPrompt 20 \n  let cache \u2190 cacheTacticJson.get\n  let fullJson \u2190\n    match cache.find? prompt.pretty with\n    | some json => pure json\n    | none =>  \n      let res \u2190 gptQuery prompt 5 \u27e88, 1\u27e9 #[\";\", \"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 \u2190 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 \u2190 tacticList\n    let tacStrings := tacStrings.filter (fun s => s != \"sorry\" && s != \"admit\")\n    let tac \u2190 `(tactic|name_inacessibles)\n    evalTactic tac\n    firstEffectiveTactic tacStrings Bool.true\n\nelab \"aide!\" : tactic =>\n  withMainContext do\n    let tacStrings \u2190 tacticList\n    let tac \u2190 `(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 \u2190 makeTacticPrompt 20\n    logInfo view\n    return ()\n\nelab \"lookahead\" tac:tactic : tactic => \n  withMainContext do\n    let s \u2190 saveState\n    try\n      evalTactic tac\n      s.restore\n    catch e =>\n      s.restore\n      let msg := e.toMessageData\n      throwError s!\"{\u2190 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 \u2190 tacticList\n    let tacStrings := tacStrings.filter (fun s => s != \"sorry\" && s != \"admit\")\n    let tac \u2190 `(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": "/-\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 Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.core\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n# list_unused_decls\n\n`#list_unused_decls` is a command used for theory development.\nWhen writing a new theory one often tries\nmultiple variations of the same definitions: `foo`, `foo'`, `foo\u2082`,\n`foo\u2083`, etc. Once the main definition or theorem has been written,\nit's time to clean up and the file can contain a lot of dead code.\nMark the main declarations with `@[main_declaration]` and\n`#list_unused_decls` will show the declarations in the file\nthat are not needed to define the main declarations.\n\nSome of the so-called \"unused\" declarations may turn out to be useful\nafter all. The oversight can be corrected by marking those as\n`@[main_declaration]`. `#list_unused_decls` will revise the list of\nunused declarations. By default, the list of unused declarations will\nnot include any dependency of the main declarations.\n\nThe `@[main_declaration]` attribute should be removed before submitting\ncode to mathlib as it is merely a tool for cleaning up a module.\n-/\n\nnamespace tactic\n\n\n/-- Attribute `main_declaration` is used to mark declarations that are featured\nin the current file.  Then, the `#list_unused_decls` command can be used to\nlist the declaration present in the file that are not used by the main\ndeclarations of the file. -/\n/-- `update_unsed_decls_list n m` removes from the map of unneeded declarations those\nreferenced by declaration named `n` which is considerred to be a\nmain declaration -/\n/-- In the current file, list all the declaration that are not marked as `@[main_declaration]` and\nthat are not referenced by such declarations -/\n/-- expecting a string literal (e.g. `\"src/tactic/find_unused.lean\"`)\n-/\n/-- The command `#list_unused_decls` lists the declarations that that\nare not used the main features of the present file. The main features\nof a file are taken as the declaration tagged with\n`@[main_declaration]`.\n\nA list of files can be given to `#list_unused_decls` as follows:\n\n```lean\n#list_unused_decls [\"src/tactic/core.lean\",\"src/tactic/interactive.lean\"]\n```\n\nThey are given in a list that contains file names written as Lean\nstrings. With a list of files, the declarations from all those files\nin addition to the declarations above `#list_unused_decls` in the\ncurrent file will be considered and their interdependencies will be\nanalyzed to see which declarations are unused by declarations marked\nas `@[main_declaration]`. The files listed must be imported by the\ncurrent file. The path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present).\n\nNeither `#list_unused_decls` nor `@[main_declaration]` should appear\nin a finished mathlib development. -/\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/find_unused_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.136608397056381, "lm_q2_score": 0.05921025655170758, "lm_q1q2_score": 0.008088618236825853}}
{"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 \u03b1] (xs : List \u03b1) (s : \u03b1) (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 \u2190 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 \u2190 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 \u2190 get\n  if (\u2190 optionalSwitch \"--help\") then\n    throw \"Usage: example [--help] [--verbose] [--input <input file>]\"\n  config := { config with\n    verbose := (\u2190 optionalSwitch \"--verbose\"),\n    input := (\u2190 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 <input file>]\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 \u2192 Type v) (n : Type u \u2192 Type w) where\n  monadLift : {\u03b1 : Type u} \u2192 m \u03b1 \u2192 n \u03b1\n```\n\nSo `monadLift` is a function for lifting a computation from an inner `Monad m \u03b1 ` to an outer `Monad n \u03b1`.\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 {\u03b1 : Type u} (t : m \u03b1) : StateT \u03c3 m \u03b1 :=\n  fun s => do let a \u2190 t; pure (a, s)\n\ninstance : MonadLift m (StateT \u03c3 m) := \u27e8StateT.lift\u27e9\n```\nThis means that any monad `m` can be wrapped in a `StateT` monad by using the function\n`fun s => do let a \u2190 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 \u03c1 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 \u2190 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 \u03b1) : IO \u03b1 := 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 \u2190 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 \u03b1` into `IO \u03b1` 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 \u2190 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 \u03b1 = Fintype.card \u03b2`, 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  `\u03b1` and `\u03b2` 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 `\u03b1 = f a\u2081 ... a\u2098` and `\u03b2 = g b\u2081 ... b\u2098`. If `f` is not definitionally\n    equal to `g` or `m \u2260 n`, then `\u03b1` and `\u03b2` are not plausibly equal.\n  - If there is some `i` such that `a\u1d62` and `b\u1d62` are not plausibly equal, then `\u03b1` and `\u03b2` are\n    not plausibly equal.\n  - Otherwise, `\u03b1` and `\u03b2` are plausibly equal.\n\n  The purpose of this is to prevent considering equalities like `\u2115 = \u2124` 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 \u2264 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 \u2190 observing? do\n    let [mvarId] \u2190 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 \u2190 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 \u2190 withReducible mvarId.getType'\n    let some (ty, _, _) := tgt.eq? | failure\n    guard ty.isProp\n    let [mvarId] \u2190 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 \u2190 observing? do\n      mvarId.checkNotAssigned `proofIrrelHeq\n      let tgt \u2190 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 \u2190 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 \u2190 observing? do\n      mvarId.checkNotAssigned `subsingletonElim\n      let tgt \u2190 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 \u2190 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 \u2190 mvarId.assert (\u2190 mkFreshUserName `h_congr_thm) congrThmType congrThmProof\n    let (fvarId, mvarId) \u2190 mvarId.intro1P\n    let mvarIds \u2190 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\u2081 ... a\u2099) (f' a\u2081' ... a\u2099')`.\nEach argument produces a `HEq a\u1d62 a\u1d62'` 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 \u00d7 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 := (\u2190 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 (\u2190 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 \u2190 mkForallFVars hs (\u2190 mkHEq (mkAppN ef xs) (mkAppN ef' ys))\n      trace[congr!.synthesize] \"simple congrType: {congrType}\"\n      let some proof \u2190 withLCtx lctx (\u2190 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? \u2190 withLCtx lctx (\u2190 getLocalInstances) <| trySolve (\u2190 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' \u2190 mkLambdaFVars fParams (\u2190 mkLambdaFVars (usedOnly := true) hs''\n                    (mkAppN (\u2190 mkLambdaFVars pfVars (proof.beta vals')) pfVals))\n      return (\u2190 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 {\u03b1} (fty : Expr) (numVars : Nat) (fixed : Array Bool)\n      (k : Array Expr \u2192 Array Expr \u2192 Array Bool \u2192 MetaM \u03b1) : MetaM \u03b1 := do\n    let rec loop (i : Nat)\n        (ftyx ftyy : Expr) (xs ys : Array Expr) (fixed' : Array Bool) : MetaM \u03b1 := do\n      if i < numVars then\n        let ftyx \u2190 whnf ftyx\n        let ftyy \u2190 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 {\u03b1} (xs ys : Array Expr) (fixedParams : Array Bool)\n      (k : Array (Option (Expr \u00d7 Expr \u00d7 Expr)) \u2192 MetaM \u03b1) : MetaM \u03b1 :=\n    let rec loop (i : Nat) (eqs : Array (Option (Expr \u00d7 Expr \u00d7 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' \u2190 mkForallFVars (deps.map fun (eq, _, _) => eq) (\u2190 mkEqHEq x y)\n          withLocalDeclD ((`e).appendIndexAfter (i+1)) (\u2190 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 \u2190 mvarId.cleanup\n    let (_, mvarId) \u2190 mvarId.intros\n    let mvarId := (\u2190 mvarId.substEqs).getD mvarId\n    try mvarId.refl; return catch _ => pure ()\n    try mvarId.hrefl; return catch _ => pure ()\n    if \u2190 mvarId.proofIrrelHeq then return\n    -- Make the goal be an eq and then try `Subsingleton.elim`\n    let mvarId \u2190 mvarId.heqOfEq\n    if \u2190 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 \u2190 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 \u2190 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 `\u211d = \u2124`.\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 (\u2190 isProp ty1) && (\u2190 isProp ty2) then\n      return true\n    -- Types from different type universes are not possibly equal\n    unless \u2190 withNewMCtxDepth <| isDefEq (\u2190 inferType ty1) (\u2190 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 \u2190 whnfD ty1\n    let ty2 \u2190 whnfD ty2\n    unless \u2190 withNewMCtxDepth <| isDefEq ty1.getAppFn ty2.getAppFn do\n      return false\n    for arg1 in ty1.getAppArgs, arg2 in ty2.getAppArgs do\n      if (\u2190 isType arg1) && (\u2190 isType arg2) then\n        unless \u2190 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 \u2190 mvarId.eqOfHEq\n      let some (_, lhs, _, rhs) := (\u2190 withReducible mvarId.getType').heq? | return none\n      if let some mvars \u2190 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 \u2190 forSide mvarId fst then\n        return mvars\n      else if let some mvars \u2190 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 \u2190 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 \u2190 withNewMCtxDepth <| isDefEq (\u2190 inferType f) (\u2190 inferType f') do\n        return none\n      let funDefEq \u2190 withReducible <| withNewMCtxDepth <| isDefEq f f'\n      if config.sameFun && not funDefEq then\n        return none\n      let info \u2190 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            (\u2190 isType larg) && (\u2190 isType rarg) && not (\u2190 Congr!.possiblyEqualTypes larg rarg) then\n          fixed := fixed.push true\n        else\n          fixed := fixed.push (\u2190 withReducible <| withNewMCtxDepth <| isDefEq larg rarg)\n      let (congrThm, congrProof) \u2190 Congr!.mkHCongrThm (\u2190 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 \u2190 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 (\u2190 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) \u2190\n      Congr!.mkHCongrThm (\u2190 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) := (\u2190 withReducible mvarId.getType').eq? | return none\n    let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)\n    if let some mvars \u2190 forSide mvarId fst then\n      return mvars\n    else if let some mvars \u2190 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 \u2190 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 := (\u2190 instantiateMVars f).cleanupAnnotations\n    let info \u2190 getFunInfoNArgs f nArgs\n    mkCongrSimpCore? f info\n      (\u2190 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) := (\u2190 withReducible mvarId.getType').eqOrIff? | return none\n    let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)\n    if let some mvars \u2190 forSide fst then\n      return mvars\n    else if let some mvars \u2190 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 := (\u2190 getSimpCongrTheorems).get name\n    -- Note: congruence theorems are provided in decreasing order of priority.\n    for congrTheorem in congrTheorems do\n      let res \u2190 observing? do\n        let cinfo \u2190 getConstInfo congrTheorem.theoremName\n        let us \u2190 cinfo.levelParams.mapM fun _ => mkFreshLevelMVar\n        let proof := mkConst congrTheorem.theoremName us\n        let ptype \u2190 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 : \u03b1 \u2192 \u03b1 \u2192 Prop} (hxy : x = y) (h : R x x) :\n    R x y := hxy \u25b8 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 \u2190 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 \u2190 (Mathlib.Tactic.reflExt.getState (\u2190 getEnv)).getMatch rel\n  for lem in reflLemmas do\n    let res \u2190 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] \u2190\n            mvarId.apply (\u2190 mkConstWithFreshMVarLevels ``Lean.MVarId.rel_of_eq_and_refl)\n        | failure\n      -- Then fill in the proof of the latter by reflexivity.\n      let [] \u2190 mvarIdR.apply (\u2190 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 (\u2190 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) := (\u2190 withReducible mvarId.getType').eq? | failure\n    if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure\n    mvarId.apply (\u2190 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) := (\u2190 withReducible mvarId.getType').heq? | failure\n    if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure\n    mvarId.apply (\u2190 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 \u03b1 x \u03b2 y` to proving `\u03b1 = \u03b2`.\n-/\ndef Lean.MVarId.subsingletonHelim? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n  mvarId.withContext <| observing? do\n    mvarId.checkNotAssigned `subsingletonHelim\n    let some (\u03b1, lhs, \u03b2, rhs) := (\u2190 withReducible mvarId.getType').heq? | failure\n    let eqmvar \u2190 mkFreshExprSyntheticOpaqueMVar (\u2190 mkEq \u03b1 \u03b2) (\u2190 mvarId.getTag)\n    -- First try synthesizing using the left-hand side for the Subsingleton instance\n    if let some pf \u2190 observing? (mkAppM ``Subsingleton.helim #[eqmvar, lhs, rhs]) then\n      mvarId.assign pf\n      return [eqmvar.mvarId!]\n    let eqsymm \u2190 mkAppM ``Eq.symm #[eqmvar]\n    -- Second try synthesizing using the right-hand side for the Subsingleton instance\n    if let some pf \u2190 observing? (mkAppM ``Subsingleton.helim #[eqsymm, rhs, lhs]) then\n      mvarId.assign (\u2190 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 \u00d7 (Congr!.Config \u2192 MVarId \u2192 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 \u2194 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 \u2194 y` if possible.\n-/\npartial\ndef Lean.MVarId.introsClean (mvarId : MVarId) : MetaM (Array FVarId \u00d7 MVarId) :=\n  loop #[] mvarId\nwhere\n  fvarEqOfHEq (mvarId : MVarId) (fvarId : FVarId) : MetaM (Option (FVarId \u00d7 MVarId)) :=\n    observing? <| mvarId.withContext do\n      let pf \u2190 mkEqOfHEq (.fvar fvarId)\n      let decl \u2190 fvarId.getDecl\n      let mvarId \u2190 mvarId.assert decl.userName (\u2190 inferType pf) pf\n      let (fvarId', mvarId) \u2190 mvarId.intro1\n      return (fvarId', \u2190 mvarId.clear fvarId)\n  fvarIffOfEq (mvarId : MVarId) (fvarId : FVarId) : MetaM (Option (FVarId \u00d7 MVarId)) :=\n    observing? <| mvarId.withContext do\n      let pf \u2190 mkIffOfEq (.fvar fvarId)\n      let decl \u2190 fvarId.getDecl\n      let mvarId \u2190 mvarId.assert decl.userName (\u2190 inferType pf) pf\n      let (fvarId', mvarId) \u2190 mvarId.intro1\n      return (fvarId', \u2190 mvarId.clear fvarId)\n  loop (fvars : Array FVarId) (mvarId : MVarId) : MetaM (Array FVarId \u00d7 MVarId) :=\n    mvarId.withContext do\n      let ty \u2190 withReducible <| mvarId.getType'\n      if ty.isForall then\n        let (fvarId, mvarId) \u2190 mvarId.intro1\n        if not ty.isArrow then\n          return \u2190 loop (fvars.push fvarId) mvarId\n        let (fvarId, mvarId) := (\u2190 fvarEqOfHEq mvarId fvarId).getD (fvarId, mvarId)\n        let (fvarId, mvarId) := (\u2190 fvarIffOfEq mvarId fvarId).getD (fvarId, mvarId)\n        mvarId.withContext do\n          let ty \u2190 instantiateMVars (\u2190 fvarId.getType)\n          if (\u2190 isTrivialType ty)\n              || (\u2190 getLCtx).any (fun decl => decl.fvarId != fvarId && decl.type == ty) then\n            let mvarId \u2190 mvarId.clear fvarId\n            return \u2190 loop fvars mvarId\n          return \u2190 loop (fvars.push fvarId) mvarId\n      else\n        return (fvars, mvarId)\n  isTrivialType (ty : Expr) : MetaM Bool := do\n    let ty \u2190 instantiateMVars ty\n    unless \u2190 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 (\u03b1, lhs, \u03b2, rhs) := ty.heq? then\n      if \u03b1.cleanupAnnotations == \u03b2.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) \u2190 mvarId.introsClean\n  -- Next, turn `HEq` and `Iff` into `Eq`\n  let mvarId \u2190 mvarId.heqOfEq\n  -- This is a good time to check whether we have a relevant hypothesis.\n  if \u2190 mvarId.assumptionCore then return none\n  let mvarId \u2190 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 \u2190 mvarId.subsingletonElim then return none\n  if \u2190 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 \u2190 saveState\n  let mvarId \u2190 mvarId.liftReflToEq\n  for (passName, pass) in congrPasses! do\n    try\n      if let some mvarIds \u2190 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 \u2190 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 \u2190 mvarId.preCongr! | return none\n  -- Convert `p = q` to `p \u2194 q`, which is likely the more useful form:\n  let mvarId \u2190 mvarId.propext\n  if \u2190 mvarId.assumptionCore then return none\n  if option.etaExpand then\n    if let some (_, lhs, rhs) := (\u2190 withReducible mvarId.getType').eq? then\n      let lhs' \u2190 Meta.etaExpand lhs\n      let rhs' \u2190 Meta.etaExpand rhs\n      return \u2190 mvarId.change (\u2190 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 \u2190 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) \u2190 go depth depth mvarId |>.run #[]\n  return s.toList\nwhere\n  post (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do\n    let some mvarId \u2190 mvarId.postCongr! config\n        | do trace[congr!] \"Dispatched goal by post-processing step.\"\n             return\n    modify (\u00b7.push mvarId)\n  go (depth : Nat) (n : Nat) (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do\n    let some mvarId \u2190 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 \u2190 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 `\u22a2 f as = g bs` we could get\ntwo goals `\u22a2 f = g` and `\u22a2 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 `\u22a2 R x y` is a reflexive relation, it will convert the goal to `\u22a2 x = y` if possible.\n  The list of reflexive relations is maintained using the `@[refl]` attribute.\n  As a special case, `\u22a2 p \u2194 q` is converted to `\u22a2 p = q` during congruence processing and then\n  returned to `\u22a2 p \u2194 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 `\u22a2 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 `\u22a2 f (g (x + y)) = f (g (y + x))`,\n`congr!` produces the goals `\u22a2 x = y` and `\u22a2 y = x`,\nwhile `congr! 2` produces the intended `\u22a2 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 \u2190 elabConfig (mkOptionalNode cfg)\n  liftMetaTactic fun g \u21a6\n    let depth := n.map (\u00b7.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": "/-\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.Class\nimport Lean.Parser.Command\nimport Lean.Meta.Closure\nimport Lean.Meta.SizeOf\nimport Lean.Meta.Injective\nimport Lean.Meta.Structure\nimport Lean.Meta.AppBuilder\nimport Lean.Elab.Command\nimport Lean.Elab.DeclModifiers\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.Inductive\nimport Lean.Elab.DeclarationRange\nimport Lean.Elab.Binders\n\nnamespace Lean.Elab.Command\n\nopen Meta\nopen TSyntax.Compat\n\n/-! Recall that the `structure command syntax is\n```\nleading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType >> optional (\" := \" >> optional structCtor >> structFields)\n```\n-/\n\nstructure StructCtorView where\n  ref       : Syntax\n  modifiers : Modifiers\n  name      : Name\n  declName  : Name\n\nstructure StructFieldView where\n  ref        : Syntax\n  modifiers  : Modifiers\n  binderInfo : BinderInfo\n  declName   : Name\n  name       : Name -- The field name as it is going to be registered in the kernel. It does not include macroscopes.\n  rawName    : Name -- Same as `name` but including macroscopes.\n  binders    : Syntax\n  type?      : Option Syntax\n  value?     : Option Syntax\n\nstructure StructView where\n  ref               : Syntax\n  modifiers         : Modifiers\n  scopeLevelNames   : List Name  -- All `universe` declarations in the current scope\n  allUserLevelNames : List Name  -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command\n  isClass           : Bool\n  declName          : Name\n  scopeVars         : Array Expr -- All `variable` declaration in the current scope\n  params            : Array Expr -- Explicit parameters provided in the `structure` command\n  parents           : Array Syntax\n  type              : Syntax\n  ctor              : StructCtorView\n  fields            : Array StructFieldView\n\ninductive StructFieldKind where\n  | newField | copiedField | fromParent | subobject\n  deriving Inhabited, DecidableEq, Repr\n\nstructure StructFieldInfo where\n  name     : Name\n  declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary \"default value\" functions.\n  fvar     : Expr\n  kind     : StructFieldKind\n  value?   : Option Expr := none\n  deriving Inhabited, Repr\n\ndef StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool :=\n  match info.kind with\n  | StructFieldKind.fromParent => true\n  | _                          => false\n\ndef StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool :=\n  match info.kind with\n  | StructFieldKind.subobject => true\n  | _                         => false\n\nstructure ElabStructResult where\n  decl            : Declaration\n  projInfos       : List ProjectionInfo\n  projInstances   : List Name -- projections (to parent classes) that must be marked as instances.\n  mctx            : MetavarContext\n  lctx            : LocalContext\n  localInsts      : LocalInstances\n  defaultAuxDecls : Array (Name \u00d7 Expr \u00d7 Expr)\n\nprivate def defaultCtorName := `mk\n\n/-\nThe structure constructor syntax is\n```\nleading_parser try (declModifiers >> ident >> \" :: \")\n```\n-/\nprivate def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do\n  let useDefault := do\n    let declName := structDeclName ++ defaultCtorName\n    addAuxDeclarationRanges declName structStx[2] structStx[2]\n    pure { ref := structStx, modifiers := {}, name := defaultCtorName, declName }\n  if structStx[5].isNone then\n    useDefault\n  else\n    let optCtor := structStx[5][1]\n    if optCtor.isNone then\n      useDefault\n    else\n      let ctor := optCtor[0]\n      withRef ctor do\n      let ctorModifiers \u2190 elabModifiers ctor[0]\n      checkValidCtorModifier ctorModifiers\n      if ctorModifiers.isPrivate && structModifiers.isPrivate then\n        throwError \"invalid 'private' constructor in a 'private' structure\"\n      if ctorModifiers.isProtected && structModifiers.isPrivate then\n        throwError \"invalid 'protected' constructor in a 'private' structure\"\n      let name := ctor[1].getId\n      let declName := structDeclName ++ name\n      let declName \u2190 applyVisibility ctorModifiers.visibility declName\n      addDocString' declName ctorModifiers.docString?\n      addAuxDeclarationRanges declName ctor[1] ctor[1]\n      pure { ref := ctor, name, modifiers := ctorModifiers, declName }\n\ndef checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do\n  if modifiers.isNoncomputable then\n    throwError \"invalid use of 'noncomputable' in field declaration\"\n  if modifiers.isPartial then\n    throwError \"invalid use of 'partial' in field declaration\"\n  if modifiers.isUnsafe then\n    throwError \"invalid use of 'unsafe' in field declaration\"\n  if modifiers.attrs.size != 0 then\n    throwError \"invalid use of attributes in field declaration\"\n\n/-\n```\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)\n```\n-/\nprivate def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) :=\n  let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs\n  fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do\n    let mut fieldBinder := fieldBinder\n    if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then\n      fieldBinder := mkNode ``Parser.Command.structExplicitBinder\n        #[ fieldBinder[0], mkAtomFrom fieldBinder \"(\", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder \")\" ]\n    let k := fieldBinder.getKind\n    let binfo \u2190\n      if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default\n      else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit\n      else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit\n      else throwError \"unexpected kind of structure field\"\n    let fieldModifiers \u2190 elabModifiers fieldBinder[0]\n    checkValidFieldModifier fieldModifiers\n    if fieldModifiers.isPrivate && structModifiers.isPrivate then\n      throwError \"invalid 'private' field in a 'private' structure\"\n    if fieldModifiers.isProtected && structModifiers.isPrivate then\n      throwError \"invalid 'protected' field in a 'private' structure\"\n    let (binders, type?) \u2190\n      if binfo == BinderInfo.default then\n        let (binders, type?) := expandOptDeclSig fieldBinder[3]\n        let optBinderTacticDefault := fieldBinder[4]\n        if optBinderTacticDefault.isNone then\n          pure (binders, type?)\n        else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then\n          pure (binders, type?)\n        else\n          let binderTactic := optBinderTacticDefault[0]\n          match type? with\n          | none => throwErrorAt binderTactic \"invalid field declaration, type must be provided when auto-param (tactic) is used\"\n          | some type =>\n            let tac := binderTactic[2]\n            let name \u2190 Term.declareTacticSyntax tac\n            -- The tactic should be for binders+type.\n            -- It is safe to reset the binders to a \"null\" node since there is no value to be elaborated\n            let type \u2190 `(forall $(binders.getArgs):bracketedBinder*, $type)\n            let type \u2190 `(autoParam $type $(mkIdentFrom tac name))\n            pure (mkNullNode, some type.raw)\n      else\n        let (binders, type) := expandDeclSig fieldBinder[3]\n        pure (binders, some type)\n    let value? \u2190 if binfo != BinderInfo.default then\n      pure none\n    else\n      let optBinderTacticDefault := fieldBinder[4]\n      -- trace[Elab.struct] \">>> {optBinderTacticDefault}\"\n      if optBinderTacticDefault.isNone then\n        pure none\n      else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then\n        pure none\n      else\n        -- binderDefault := leading_parser \" := \" >> termParser\n        pure (some optBinderTacticDefault[0][1])\n    let idents := fieldBinder[2].getArgs\n    idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do\n      let rawName := ident.getId\n      let name    := rawName.eraseMacroScopes\n      unless name.isAtomic do\n        throwErrorAt ident \"invalid field name '{name.eraseMacroScopes}', field names must be atomic\"\n      let declName := structDeclName ++ name\n      let declName \u2190 applyVisibility fieldModifiers.visibility declName\n      addDocString' declName fieldModifiers.docString?\n      return views.push {\n        ref        := ident\n        modifiers  := fieldModifiers\n        binderInfo := binfo\n        declName\n        name\n        rawName\n        binders\n        type?\n        value?\n      }\n\nprivate def validStructType (type : Expr) : Bool :=\n  match type with\n  | Expr.sort .. => true\n  | _            => false\n\nprivate def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo :=\n  infos.find? fun info => info.name == fieldName\n\nprivate def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool :=\n  (findFieldInfo? infos fieldName).isSome\n\nprivate def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo :=\n  infos.map fun info =>\n    if info.name == fieldName then\n      { info with value? := value  }\n    else\n      info\n\nregister_builtin_option structureDiamondWarning : Bool := {\n  defValue := false\n  descr    := \"enable/disable warning messages for structure diamonds\"\n}\n\n/-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/\nprivate def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do\n  let fieldNames := getStructureFieldsFlattened (\u2190 getEnv) parentStructName\n  for fieldName in fieldNames do\n    if containsFieldName infos fieldName then\n      return some fieldName\n  return none\n\nprivate partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name)\n    (infos : Array StructFieldInfo) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  go 0 infos\nwhere\n  go (i : Nat) (infos : Array StructFieldInfo) := do\n    if h : i < subfieldNames.size then\n      let subfieldName := subfieldNames.get \u27e8i, h\u27e9\n      if containsFieldName infos subfieldName then\n        throwError \"field '{subfieldName}' from '{parentStructName}' has already been declared\"\n      let val  \u2190 mkProjection parentFVar subfieldName\n      let type \u2190 inferType val\n      withLetDecl subfieldName type val fun subfieldFVar =>\n        /- The following `declName` is only used for creating the `_default` auxiliary declaration name when\n           its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/\n        let declName := structDeclName ++ subfieldName\n        let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent }\n        go (i+1) infos\n    else\n      k infos\n\n/-- Given `obj.foo.bar.baz`, return `obj`. -/\nprivate partial def getNestedProjectionArg (e : Expr) : MetaM Expr := do\n  if let Expr.const subProjName .. := e.getAppFn then\n    if let some { numParams, .. } \u2190 getProjectionFnInfo? subProjName then\n      if e.getAppNumArgs == numParams + 1 then\n        return \u2190 getNestedProjectionArg e.appArg!\n  return e\n\n/--\n  Get field type of `fieldName` in `parentType`, but replace references\n  to other fields of that structure by existing field fvars.\n  Auxiliary method for `copyNewFieldsFrom`.\n\n-/\nprivate def getFieldType (infos : Array StructFieldInfo) (parentType : Expr) (fieldName : Name) : MetaM Expr := do\n  withLocalDeclD (\u2190 mkFreshId) parentType fun parent => do\n    let proj \u2190 mkProjection parent fieldName\n    let projType \u2190 inferType proj\n    /- Eliminate occurrences of `parent.field`. This happens when the structure contains dependent fields.\n    If the copied parent extended another structure via a subobject,\n    then the occurrence can also look like `parent.toGrandparent.field`\n    (where `toGrandparent` is not a field of the current structure). -/\n    let visit (e : Expr) : MetaM TransformStep := do\n      if let Expr.const subProjName .. := e.getAppFn then\n        if let some { numParams, .. } \u2190 getProjectionFnInfo? subProjName then\n          let Name.str _ subFieldName .. := subProjName\n            | throwError \"invalid projection name {subProjName}\"\n          let args := e.getAppArgs\n          if let some major := args.get? numParams then\n            if (\u2190 getNestedProjectionArg major) == parent then\n              if let some existingFieldInfo := findFieldInfo? infos subFieldName then\n                return TransformStep.done <| mkAppN existingFieldInfo.fvar args[numParams+1:args.size]\n      return TransformStep.done e\n    let projType \u2190 Meta.transform projType (post := visit)\n    if projType.containsFVar parent.fvarId! then\n      throwError \"unsupported dependent field in {fieldName} : {projType}\"\n    if let some info := getFieldInfo? (\u2190 getEnv) (\u2190 getStructureName parentType) fieldName then\n      if let some autoParamExpr := info.autoParam? then\n        return (\u2190 mkAppM ``autoParam #[projType, autoParamExpr])\n    return projType\n\nprivate def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do\n  if isProtected (\u2190 getEnv) fieldInfo.projFn then\n    return Visibility.protected\n  else if isPrivateName fieldInfo.projFn then\n    return Visibility.private\n  else\n    return Visibility.regular\n\nabbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field\n\n/-- Reduce projetions of the structures in `structNames` -/\nprivate def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr :=\n  let reduce (e : Expr) : MetaM TransformStep := do\n    match (\u2190 reduceProjOf? e structNames.contains) with\n    | some v => return TransformStep.done v\n    | _ => return TransformStep.done e\n  transform e (post := reduce)\n\n/--\n  Copy the default value for field `fieldName` set at structure `structName`.\n  The arguments for the `_default` auxiliary function are provided by `fieldMap`.\n  Recall some of the entries in `fieldMap` are constructor applications, and they needed\n  to be reduced using `reduceProjs`. Otherwise, the produced default value may be \"cyclic\".\n  That is, we reduce projections of the structures in `expandedStructNames`. Here is\n  an example that shows why the reduction is needed.\n  ```\n  structure A where\n    a : Nat\n\n  structure B where\n    a : Nat\n    b : Nat\n    c : Nat\n\n  structure C extends B where\n    d : Nat\n    c := b + d\n\n  structure D extends A, C\n\n  #print D.c._default\n  ```\n  Without the reduction, it produces\n  ```\n  def D.c._default : A \u2192 Nat \u2192 Nat \u2192 Nat \u2192 Nat :=\n  fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d)\n  ```\n-/\nprivate partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do\n  match getDefaultFnForField? (\u2190 getEnv) structName fieldName with\n  | none => return none\n  | some defaultFn =>\n    let cinfo \u2190 getConstInfo defaultFn\n    let us \u2190 mkFreshLevelMVarsFor cinfo\n    go? (\u2190 instantiateValueLevelParams cinfo us)\nwhere\n  failed : TermElabM (Option Expr) := do\n    logWarning s!\"ignoring default value for field '{fieldName}' defined at '{structName}'\"\n    return none\n\n  go? (e : Expr) : TermElabM (Option Expr) := do\n    match e with\n    | Expr.lam n d b c =>\n      if c.isExplicit then\n        match fieldMap.find? n with\n        | none => failed\n        | some val =>\n          let valType \u2190 inferType val\n          if (\u2190 isDefEq valType d) then\n            go? (b.instantiate1 val)\n          else\n            failed\n      else\n        let arg \u2190 mkFreshExprMVar d\n        go? (b.instantiate1 arg)\n    | e =>\n      let r := if e.isAppOfArity ``id 2 then e.appArg! else e\n      return some (\u2190 reduceProjs (\u2190 instantiateMVars r) expandedStructNames)\n\nprivate partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  copyFields infos {} parentType fun infos _ _ => k infos\nwhere\n  copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo \u2192 FieldMap \u2192 NameSet \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n    let parentStructName \u2190 getStructureName parentType\n    let fieldNames := getStructureFields (\u2190 getEnv) parentStructName\n    let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM \u03b1 := do\n      if h : i < fieldNames.size then\n        let fieldName := fieldNames.get \u27e8i, h\u27e9\n        let fieldType \u2190 getFieldType infos parentType fieldName\n        match findFieldInfo? infos fieldName with\n        | some existingFieldInfo =>\n          let existingFieldType \u2190 inferType existingFieldInfo.fvar\n          unless (\u2190 isDefEq fieldType existingFieldType) do\n            throwError \"parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {\u2190 mkHasTypeButIsExpectedMsg fieldType existingFieldType}\"\n          /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/\n          copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames\n        | none =>\n          let some fieldInfo := getFieldInfo? (\u2190 getEnv) parentStructName fieldName | unreachable!\n          let addNewField : TermElabM \u03b1 := do\n            let value? \u2190 copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName\n            withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do\n              let fieldDeclName := structDeclName ++ fieldName\n              let fieldDeclName \u2190 applyVisibility (\u2190 toVisibility fieldInfo) fieldDeclName\n              addDocString' fieldDeclName (\u2190 findDocString? (\u2190 getEnv) fieldInfo.projFn)\n              let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?,\n                                        kind := StructFieldKind.copiedField }\n              copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames\n          if fieldInfo.subobject?.isSome then\n            let fieldParentStructName \u2190 getStructureName fieldType\n            if (\u2190 findExistingField? infos fieldParentStructName).isSome then\n              -- See comment at `copyDefaultValue?`\n              let expandedStructNames := expandedStructNames.insert fieldParentStructName\n              copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do\n                let fieldVal \u2190 mkCompositeField fieldType nestedFieldMap\n                copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames\n            else\n              let subfieldNames := getStructureFieldsFlattened (\u2190 getEnv) fieldParentStructName\n              let fieldName := fieldInfo.fieldName\n              withLocalDecl fieldName fieldInfo.binderInfo fieldType fun parentFVar =>\n                let infos := infos.push { name := fieldName, declName := structDeclName ++ fieldName, fvar := parentFVar, kind := StructFieldKind.subobject }\n                processSubfields structDeclName parentFVar fieldParentStructName subfieldNames infos fun infos =>\n                  copy (i+1) infos (fieldMap.insert fieldName parentFVar) expandedStructNames\n          else\n            addNewField\n      else\n        let infos \u2190 processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName\n        k infos fieldMap expandedStructNames\n    copy 0 infos {} expandedStructNames\n\n  processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) :=\n    infos.mapM fun info => do\n      match (\u2190 copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with\n      | some value => return { info with value? := value }\n      | none       => return info\n\n  mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do\n    let env \u2190 getEnv\n    let Expr.const parentStructName us \u2190 pure parentType.getAppFn | unreachable!\n    let parentCtor := getStructureCtor env parentStructName\n    let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs\n    for fieldName in getStructureFields env parentStructName do\n      match fieldMap.find? fieldName with\n      | some val => result := mkApp result val\n      | none => throwError \"failed to copy fields from parent structure{indentExpr parentType}\" -- TODO improve error message\n    return result\n\nprivate partial def mkToParentName (parentStructName : Name) (p : Name \u2192 Bool) : Name := Id.run do\n  let base := Name.mkSimple $ \"to\" ++ parentStructName.eraseMacroScopes.getString!\n  if p base then\n    base\n  else\n    let rec go (i : Nat) : Name :=\n      let curr := base.appendIndexAfter i\n      if p curr then curr else go (i+1)\n    go 1\n\nprivate partial def withParents (view : StructView) (k : Array StructFieldInfo \u2192 Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 #[] #[]\nwhere\n  go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM \u03b1 := do\n    if h : i < view.parents.size then\n      let parentStx := view.parents.get \u27e8i, h\u27e9\n      withRef parentStx do\n      let parentType \u2190 Term.elabType parentStx\n      let parentStructName \u2190 getStructureName parentType\n      if let some existingFieldName \u2190 findExistingField? infos parentStructName then\n        if structureDiamondWarning.get (\u2190 getOptions) then\n          logWarning s!\"field '{existingFieldName}' from '{parentStructName}' has already been declared\"\n        copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType)\n        -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure`\n      else\n        let env \u2190 getEnv\n        let subfieldNames := getStructureFieldsFlattened env parentStructName\n        let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n\n        let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default\n        withLocalDecl toParentName binfo parentType fun parentFVar =>\n          let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject }\n          processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents\n    else\n      k infos copiedParents\n\nprivate def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr \u00d7 Option Expr) :=\n  Term.withAutoBoundImplicit <| Term.withAutoBoundImplicitForbiddenPred (fun n => view.name == n) <| Term.elabBinders view.binders.getArgs fun params => do\n    match view.type? with\n    | none         =>\n      match view.value? with\n      | none        => return (none, none)\n      | some valStx =>\n        Term.synthesizeSyntheticMVarsNoPostponing\n        -- TODO: add forbidden predicate using `shortDeclName` from `view`\n        let params \u2190 Term.addAutoBoundImplicits params\n        let value \u2190 Term.withoutAutoBoundImplicit <| Term.elabTerm valStx none\n        let value \u2190 mkLambdaFVars params value\n        return (none, value)\n    | some typeStx =>\n      let type \u2190 Term.elabType typeStx\n      Term.synthesizeSyntheticMVarsNoPostponing\n      let params \u2190 Term.addAutoBoundImplicits params\n      match view.value? with\n      | none        =>\n        let type  \u2190 mkForallFVars params type\n        return (type, none)\n      | some valStx =>\n        let value \u2190 Term.withoutAutoBoundImplicit <| Term.elabTermEnsuringType valStx type\n        Term.synthesizeSyntheticMVarsNoPostponing\n        let type  \u2190 mkForallFVars params type\n        let value \u2190 mkLambdaFVars params value\n        return (type, value)\n\nprivate partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 {} infos\nwhere\n  go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM \u03b1 := do\n    if h : i < views.size then\n      let view := views.get \u27e8i, h\u27e9\n      withRef view.ref do\n      match findFieldInfo? infos view.name with\n      | none      =>\n        let (type?, value?) \u2190 elabFieldTypeValue view\n        match type?, value? with\n        | none,      none => throwError \"invalid field, type expected\"\n        | some type, _    =>\n          withLocalDecl view.rawName view.binderInfo type fun fieldFVar =>\n            let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?,\n                                      kind := StructFieldKind.newField }\n            go (i+1) defaultValsOverridden infos\n        | none, some value =>\n          let type \u2190 inferType value\n          withLocalDecl view.rawName view.binderInfo type fun fieldFVar =>\n            let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value,\n                                      kind := StructFieldKind.newField }\n            go (i+1) defaultValsOverridden infos\n      | some info =>\n        let updateDefaultValue : TermElabM \u03b1 := do\n          match view.value? with\n          | none       => throwError \"field '{view.name}' has been declared in parent structure\"\n          | some valStx =>\n            if let some type := view.type? then\n              throwErrorAt type \"omit field '{view.name}' type to set default value\"\n            else\n              if defaultValsOverridden.contains info.name then\n                throwError \"field '{view.name}' new default value has already been set\"\n              let defaultValsOverridden := defaultValsOverridden.insert info.name\n              let mut valStx := valStx\n              if view.binders.getArgs.size > 0 then\n                valStx \u2190 `(fun $(view.binders.getArgs)* => $valStx:term)\n              let fvarType \u2190 inferType info.fvar\n              let value \u2190 Term.elabTermEnsuringType valStx fvarType\n              pushInfoLeaf <| .ofFieldRedeclInfo { stx := view.ref }\n              let infos := updateFieldInfoVal infos info.name value\n              go (i+1) defaultValsOverridden infos\n        match info.kind with\n        | StructFieldKind.newField    => throwError \"field '{view.name}' has already been declared\"\n        | StructFieldKind.subobject   => throwError \"unexpected subobject field reference\" -- improve error message\n        | StructFieldKind.copiedField => updateDefaultValue\n        | StructFieldKind.fromParent  => updateDefaultValue\n    else\n      k infos\n\nprivate def getResultUniverse (type : Expr) : TermElabM Level := do\n  let type \u2190 whnf type\n  match type with\n  | Expr.sort u => pure u\n  | _           => throwError \"unexpected structure resulting type\"\n\nprivate def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do\n  params.forM fun p => do\n    let type \u2190 inferType p\n    type.collectFVars\n  fieldInfos.forM fun info => do\n    let fvarType \u2190 inferType info.fvar\n    fvarType.collectFVars\n    match info.value? with\n    | none       => pure ()\n    | some value => value.collectFVars\n\nprivate def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed params fieldInfos).run {}\n  Meta.removeUnused scopeVars used\n\nprivate def withUsed {\u03b1} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr \u2192 TermElabM \u03b1)\n    : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnused scopeVars params fieldInfos\n  withLCtx lctx localInsts <| k vars\n\nprivate def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (univToInfer? : Option LMVarId) : TermElabM (Array StructFieldInfo) := do\n  levelMVarToParamFVars scopeVars\n  levelMVarToParamFVars params\n  fieldInfos.mapM fun info => do\n    levelMVarToParamFVar info.fvar\n    match info.value? with\n    | none       => pure info\n    | some value =>\n      let value \u2190 levelMVarToParam' value\n      pure { info with value? := value }\nwhere\n  levelMVarToParam' (type : Expr) : TermElabM Expr := do\n    Term.levelMVarToParam type (except := fun mvarId => univToInfer? == some mvarId)\n\n  levelMVarToParamFVars (fvars : Array Expr) : TermElabM Unit :=\n    fvars.forM levelMVarToParamFVar\n\n  levelMVarToParamFVar (fvar : Expr) : TermElabM Unit := do\n    let type \u2190 inferType fvar\n    discard <| levelMVarToParam' type\n\n\nprivate partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do\n  let (_, us) \u2190 go |>.run #[]\n  return us\nwhere\n  go : StateRefT (Array Level) TermElabM Unit :=\n    for info in fieldInfos do\n      let type \u2190 inferType info.fvar\n      let u \u2190 getLevel type\n      let u \u2190 instantiateLevelMVars u\n      match (\u2190 modifyGet fun s => accLevel u r rOffset |>.run |>.run s) with\n      | some _ => pure ()\n      | none =>\n        let typeType \u2190 inferType type\n        let mut msg := m!\"failed to compute resulting universe level of structure, field '{info.declName}' has type{indentD m!\"{type} : {typeType}\"}\\nstructure resulting type{indentExpr (mkSort (r.addOffset rOffset))}\"\n        if r.isMVar then\n          msg := msg ++ \"\\nrecall that Lean only infers the resulting universe level automatically when there is a unique solution for the universe level constraints, consider explicitly providing the structure resulting universe level\"\n        throwError msg\n\nprivate def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do\n  let r \u2190 getResultUniverse type\n  let rOffset : Nat   := r.getOffset\n  let r       : Level := r.getLevelOffset\n  match r with\n  | Level.mvar mvarId =>\n    let us \u2190 collectUniversesFromFields r rOffset fieldInfos\n    let rNew := mkResultUniverse us rOffset\n    assignLevelMVar mvarId rNew\n    instantiateMVars type\n  | _ => throwError \"failed to compute resulting universe level of structure, provide universe explicitly\"\n\nprivate def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do\n  let type \u2190 inferType fvar\n  let type \u2190 instantiateMVars type\n  return collectLevelParams s type\n\nprivate def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State :=\n  fvars.foldlM collectLevelParamsInFVar s\n\nprivate def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : TermElabM (Array Name) := do\n  let s := collectLevelParams {} structType\n  let s \u2190 collectLevelParamsInFVars scopeVars s\n  let s \u2190 collectLevelParamsInFVars params s\n  let s \u2190 fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar\n  return s.params\n\nprivate def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat \u2192 Expr \u2192 TermElabM Expr\n  | 0,   type => pure type\n  | i+1, type => do\n    let info := fieldInfos[i]!\n    let decl \u2190 Term.getFVarLocalDecl! info.fvar\n    let type \u2190 instantiateMVars type\n    let type := type.abstract #[info.fvar]\n    match info.kind with\n    | StructFieldKind.fromParent =>\n      let val := decl.value\n      addCtorFields fieldInfos i (type.instantiate1 val)\n    | _  =>\n      addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type)\n\nprivate def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor :=\n  withRef view.ref do\n  let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params\n  let type \u2190 addCtorFields fieldInfos fieldInfos.size type\n  let type \u2190 mkForallFVars params type\n  let type \u2190 instantiateMVars type\n  let type := type.inferImplicit params.size true\n  pure { name := view.ctor.declName, type }\n\n@[extern \"lean_mk_projections\"]\nprivate opaque mkProjections (env : Environment) (structName : Name) (projs : List Name) (isClass : Bool) : Except KernelException Environment\n\nprivate def addProjections (structName : Name) (projs : List Name) (isClass : Bool) : TermElabM Unit := do\n  let env \u2190 getEnv\n  let env \u2190 ofExceptKernelException (mkProjections env structName projs isClass)\n  setEnv env\n\nprivate def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do\n  let fields \u2190 infos.filterMapM fun info => do\n      if info.kind == StructFieldKind.fromParent then\n        return none\n      else\n        return some {\n          fieldName  := info.name\n          projFn     := info.declName\n          binderInfo := (\u2190 getFVarLocalDecl info.fvar).binderInfo\n          autoParam? := (\u2190 inferType info.fvar).getAutoParamTactic?\n          subobject? :=\n            if info.kind == StructFieldKind.subobject then\n              match (\u2190 getEnv).find? info.declName with\n              | some (ConstantInfo.defnInfo val) =>\n                match val.type.getForallBody.getAppFn with\n                | Expr.const parentName .. => some parentName\n                | _ => panic! \"ill-formed structure\"\n              | _ => panic! \"ill-formed environment\"\n            else\n              none\n        }\n  modifyEnv fun env => Lean.registerStructure env { structName, fields }\n\nprivate def mkAuxConstructions (declName : Name) : TermElabM Unit := do\n  let env \u2190 getEnv\n  let hasUnit := env.contains `PUnit\n  let hasEq   := env.contains `Eq\n  let hasHEq  := env.contains `HEq\n  mkRecOn declName\n  if hasUnit then mkCasesOn declName\n  if hasUnit && hasEq && hasHEq then mkNoConfusion declName\n\nprivate def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name \u00d7 Expr \u00d7 Expr)) : TermElabM Unit := do\n  let localInsts \u2190 getLocalInstances\n  withLCtx lctx localInsts do\n    defaultAuxDecls.forM fun (declName, type, value) => do\n      let value \u2190 instantiateMVars value\n      if value.hasExprMVar then\n        throwError \"invalid default value for field, it contains metavariables{indentExpr value}\"\n      /- The identity function is used as \"marker\". -/\n      let value \u2190 mkId value\n      discard <| mkAuxDefinition declName type value (zeta := true)\n      setReducibleAttribute declName\n\n/--\nGiven `type` of the form `forall ... (source : A), B`, return `forall ... [source : A], B`.\n-/\nprivate def setSourceInstImplicit (type : Expr) : Expr :=\n  match type with\n  | .forallE _ d b _ =>\n    if b.isForall then\n      type.updateForallE! d (setSourceInstImplicit b)\n    else\n      type.updateForall! .instImplicit d b\n  | _ => unreachable!\n\nprivate partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do\n  let env \u2190 getEnv\n  let structName := view.declName\n  let sourceFieldNames := getStructureFieldsFlattened env structName\n  let structType := mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params\n  let Expr.const parentStructName _ \u2190 pure parentType.getAppFn | unreachable!\n  let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default\n  withLocalDeclD `self structType fun source => do\n    let mut declType \u2190 instantiateMVars (\u2190 mkForallFVars params (\u2190 mkForallFVars #[source] parentType))\n    declType := mkOutParamArgsImplicit declType\n    if view.isClass && isClass env parentStructName then\n      declType := setSourceInstImplicit declType\n    declType := declType.inferImplicit params.size true\n    let rec copyFields (parentType : Expr) : MetaM Expr := do\n      let Expr.const parentStructName us \u2190 pure parentType.getAppFn | unreachable!\n      let parentCtor := getStructureCtor env parentStructName\n      let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs\n      for fieldName in getStructureFields env parentStructName do\n        if sourceFieldNames.contains fieldName then\n          let fieldVal \u2190 mkProjection source fieldName\n          result := mkApp result fieldVal\n        else\n          -- fieldInfo must be a field of `parentStructName`\n          let some fieldInfo := getFieldInfo? env parentStructName fieldName | unreachable!\n          if fieldInfo.subobject?.isNone then throwError \"failed to build coercion to parent structure\"\n          let resultType \u2190 whnfD (\u2190 inferType result)\n          unless resultType.isForall do throwError \"failed to build coercion to parent structure, unexpect type{indentExpr resultType}\"\n          let fieldVal \u2190 copyFields resultType.bindingDomain!\n          result := mkApp result fieldVal\n      return result\n    let declVal \u2190 instantiateMVars (\u2190 mkLambdaFVars params (\u2190 mkLambdaFVars #[source] (\u2190 copyFields parentType)))\n    let declName := structName ++ mkToParentName (\u2190 getStructureName parentType) fun n => !env.contains (structName ++ n)\n    addAndCompile <| Declaration.defnDecl {\n      name        := declName\n      levelParams := levelParams\n      type        := declType\n      value       := declVal\n      hints       := ReducibilityHints.abbrev\n      safety      := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe\n    }\n    if binfo.isInstImplicit then\n      addInstance declName AttributeKind.global (eval_prio default)\n    else\n      setReducibleAttribute declName\n\nprivate def elabStructureView (view : StructView) : TermElabM Unit := do\n  view.fields.forM fun field => do\n    if field.declName == view.ctor.declName then\n      throwErrorAt field.ref \"invalid field name '{field.name}', it is equal to structure constructor name\"\n    addAuxDeclarationRanges field.declName field.ref field.ref\n  let type \u2190 Term.elabType view.type\n  unless validStructType type do throwErrorAt view.type \"expected Type\"\n  withRef view.ref do\n  withParents view fun fieldInfos copiedParents => do\n  withFields view.fields fieldInfos fun fieldInfos => do\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let u \u2190 getResultUniverse type\n    let univToInfer? \u2190 shouldInferResultUniverse u\n    withUsed view.scopeVars view.params fieldInfos fun scopeVars => do\n      let fieldInfos \u2190 levelMVarToParam scopeVars view.params fieldInfos univToInfer?\n      let type \u2190 withRef view.ref do\n        if univToInfer?.isSome then\n          updateResultingUniverse fieldInfos type\n        else\n          checkResultingUniverse (\u2190 getResultUniverse type)\n          pure type\n      trace[Elab.structure] \"type: {type}\"\n      let usedLevelNames \u2190 collectLevelParamsInStructure type scopeVars view.params fieldInfos\n      match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with\n      | Except.error msg      => withRef view.ref <| throwError msg\n      | Except.ok levelParams =>\n        let params := scopeVars ++ view.params\n        let ctor \u2190 mkCtor view levelParams params fieldInfos\n        let type \u2190 mkForallFVars params type\n        let type \u2190 instantiateMVars type\n        let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType }\n        let decl    := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe\n        Term.ensureNoUnassignedMVars decl\n        addDecl decl\n        let projNames := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => info.declName\n        addProjections view.declName projNames view.isClass\n        registerStructure view.declName fieldInfos\n        mkAuxConstructions view.declName\n        let instParents \u2190 fieldInfos.filterM fun info => do\n          let decl \u2190 Term.getFVarLocalDecl! info.fvar\n          pure (info.isSubobject && decl.binderInfo.isInstImplicit)\n        withSaveInfoContext do  -- save new env\n          Term.addLocalVarInfo view.ref[1] (\u2190 mkConstWithLevelParams view.declName)\n          if let some _ := view.ctor.ref[1].getPos? (canonicalOnly := true) then\n            Term.addTermInfo' view.ctor.ref[1] (\u2190 mkConstWithLevelParams view.ctor.declName) (isBinder := true)\n          for field in view.fields do\n            -- may not exist if overriding inherited field\n            if (\u2190 getEnv).contains field.declName then\n              Term.addTermInfo' field.ref (\u2190 mkConstWithLevelParams field.declName) (isBinder := true)\n        Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking\n        let projInstances := instParents.toList.map fun info => info.declName\n        projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default)\n        copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent\n        let lctx \u2190 getLCtx\n        let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome\n        let defaultAuxDecls \u2190 fieldsWithDefault.mapM fun info => do\n          let type \u2190 inferType info.fvar\n          pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!)\n        /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary \"default value\" declarations\n           The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/\n        let lctx :=\n          params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) =>\n            if p.isFVar then\n              lctx.setBinderInfo p.fvarId! BinderInfo.implicit\n            else\n              lctx\n        let lctx :=\n          fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) =>\n            if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating \"default value\" auxiliary functions\n            else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default\n        addDefaults lctx defaultAuxDecls\n\n/-\nleading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType >> \" := \" >> optional structCtor >> structFields >> optDeriving\n\nwhere\ndef \u00abextends\u00bb := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef typeSpec := leading_parser \" : \" >> termParser\ndef optType : Parser := optional typeSpec\n\ndef structFields         := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)\ndef structCtor           := leading_parser try (declModifiers >> ident >> \" :: \")\n\n-/\ndef elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  checkValidInductiveModifier modifiers\n  let isClass   := stx[0].getKind == ``Parser.Command.classTk\n  let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers\n  let declId    := stx[1]\n  let params    := stx[2].getArgs\n  let exts      := stx[3]\n  let parents   := if exts.isNone then #[] else exts[0][1].getSepArgs\n  let optType   := stx[4]\n  let derivingClassViews \u2190 getOptDerivingClasses stx[6]\n  let type \u2190 if optType.isNone then `(Sort _) else pure optType[0][1]\n  let declName \u2190\n    runTermElabM fun scopeVars => do\n      let scopeLevelNames \u2190 Term.getLevelNames\n      let \u27e8name, declName, allUserLevelNames\u27e9 \u2190 Elab.expandDeclId (\u2190 getCurrNamespace) scopeLevelNames declId modifiers\n      Term.withAutoBoundImplicitForbiddenPred (fun n => name == n) do\n        addDeclarationRanges declName stx\n        Term.withDeclName declName do\n          let ctor \u2190 expandCtor stx modifiers declName\n          let fields \u2190 expandFields stx modifiers declName\n          Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <|\n            Term.elabBinders params fun params => do\n              Term.synthesizeSyntheticMVarsNoPostponing\n              let params \u2190 Term.addAutoBoundImplicits params\n              let allUserLevelNames \u2190 Term.getLevelNames\n              elabStructureView {\n                ref := stx\n                modifiers\n                scopeLevelNames\n                allUserLevelNames\n                declName\n                isClass\n                scopeVars\n                params\n                parents\n                type\n                ctor\n                fields\n              }\n              unless isClass do\n                mkSizeOfInstances declName\n                mkInjectiveTheorems declName\n              return declName\n  derivingClassViews.forM fun view => view.applyHandlers #[declName]\n  runTermElabM fun _ => Term.withDeclName declName do\n    Term.applyAttributesAt declName modifiers.attrs .afterCompilation\n\nbuiltin_initialize registerTraceClass `Elab.structure\n\nend Lean.Elab.Command\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/Structure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181322226037882, "lm_q2_score": 0.0396388365483385, "lm_q1q2_score": 0.007999641330472665}}
{"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}] {\u03b1 : \u039b} [position_data.{}] [phase_2_assumptions \u03b1] {\u03b2 : Iic \u03b1}\n  {\u03b3 : Iic \u03b1} {\u03b4 \u03b5 : Iio \u03b1} (h\u03b4 : (\u03b4 : \u039b) < \u03b3) (h\u03b5 : (\u03b5 : \u039b) < \u03b3) (h\u03b4\u03b5 : \u03b4 \u2260 \u03b5)\n  {A : path (\u03b2 : type_index) \u03b3} {t : tangle \u03b4}\n  (H : hypothesis \u27e8inr (f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t).to_near_litter,\n    (A.cons (coe_lt h\u03b5)).cons (bot_lt_coe _)\u27e9)\n\n/-- The inductive hypothesis used for proving freedom of action:\nEvery free approximation exactly approximates some allowable permutation. -/\ndef foa_ih (\u03b2 : Iic \u03b1) : Prop :=\n\u2200 (\u03c0\u2080 : struct_approx \u03b2), \u03c0\u2080.free \u2192 \u2203 (\u03c0 : allowable \u03b2), \u03c0\u2080.exactly_approximates \u03c0.to_struct_perm\n\n/-- A proof-relevant statement that `L` is `A`-inflexible (excluding `\u03b5 = \u22a5`). -/\nstructure inflexible_coe (L : litter) (A : extended_index \u03b2) :=\n(\u03b3 : Iic \u03b1) (\u03b4 \u03b5 : Iio \u03b1) (h\u03b4 : (\u03b4 : \u039b) < \u03b3) (h\u03b5 : (\u03b5 : \u039b) < \u03b3) (h\u03b4\u03b5 : \u03b4 \u2260 \u03b5)\n(B : quiver.path (\u03b2 : type_index) \u03b3) (t : tangle \u03b4)\n(hL : L = f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t)\n(hA : A = (B.cons (coe_lt h\u03b5)).cons (bot_lt_coe _))\n\ninstance (L : litter) (A : extended_index \u03b2) : subsingleton (inflexible_coe L A) :=\nbegin\n  constructor,\n  rintros \u27e8\u03b3\u2081, \u03b4\u2081, \u03b5\u2081, h\u03b4\u2081, h\u03b5\u2081, h\u03b4\u03b5\u2081, B\u2081, t\u2081, rfl, rfl\u27e9\n    \u27e8\u03b3\u2082, \u03b4\u2082, \u03b5\u2082, h\u03b4\u2082, h\u03b5\u2082, h\u03b4\u03b5\u2082, B\u2082, t\u2082, hL\u2082, hA\u2082\u27e9,\n  cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons hA\u2082)),\n  cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons\n    (path.heq_of_cons_eq_cons hA\u2082).eq)),\n  cases (path.heq_of_cons_eq_cons (path.heq_of_cons_eq_cons hA\u2082).eq).eq,\n  have h\u2081 := f_map_\u03b2 (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5\u2081) t\u2081,\n  have h\u2082 := f_map_\u03b2 (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5\u2082) t\u2082,\n  rw [hL\u2082, h\u2082] at h\u2081,\n  cases subtype.coe_injective (coe_eq_coe.mp h\u2081),\n  cases f_map_injective _ hL\u2082,\n  refl,\nend\n\n/-- A proof-relevant statement that `L` is `A`-inflexible, where `\u03b4 = \u22a5`. -/\nstructure inflexible_bot (L : litter) (A : extended_index \u03b2) :=\n(\u03b3 : Iic \u03b1) (\u03b5 : Iio \u03b1) (h\u03b5 : (\u03b5 : \u039b) < \u03b3)\n(B : quiver.path (\u03b2 : type_index) \u03b3) (a : atom)\n(hL : L = f_map (show (\u22a5 : type_index) \u2260 (\u03b5 : \u039b), from bot_ne_coe) a)\n(hA : A = (B.cons (coe_lt h\u03b5)).cons (bot_lt_coe _))\n\ninstance (L : litter) (A : extended_index \u03b2) : subsingleton (inflexible_bot L A) :=\nbegin\n  constructor,\n  rintros \u27e8\u03b3\u2081, \u03b5\u2081, h\u03b5\u2081, B\u2081, a\u2081, rfl, rfl\u27e9 \u27e8\u03b3\u2082, \u03b5\u2082, h\u03b5\u2082, B\u2082, a\u2082, hL\u2082, hA\u2082\u27e9,\n  cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons hA\u2082)),\n  cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons\n    (path.heq_of_cons_eq_cons hA\u2082).eq)),\n  cases (path.heq_of_cons_eq_cons (path.heq_of_cons_eq_cons hA\u2082).eq).eq,\n  cases f_map_injective _ hL\u2082,\n  refl,\nend\n\nlemma inflexible_bot_inflexible_coe {L : litter} {A : extended_index \u03b2} :\n  inflexible_bot L A \u2192 inflexible_coe L A \u2192 false :=\nbegin\n  rintros \u27e8\u03b3\u2081, \u03b5\u2081, h\u03b5\u2081, B\u2081, a\u2081, rfl, rfl\u27e9 \u27e8\u03b3\u2082, \u03b4\u2082, \u03b5\u2082, h\u03b4\u2082, h\u03b5\u2082, h\u03b4\u03b5\u2082, B\u2082, t\u2082, hL\u2082, hA\u2082\u27e9,\n  have h\u2081 := f_map_\u03b2 (show (\u22a5 : type_index) \u2260 (\u03b5\u2081 : \u039b), from bot_ne_coe) a\u2081,\n  have h\u2082 := f_map_\u03b2 (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5\u2082) t\u2082,\n  rw [hL\u2082, h\u2082] at h\u2081,\n  cases h\u2081,\nend\n\nlemma inflexible_coe.\u03b4_lt_\u03b2 {L : litter} {A : extended_index \u03b2} (h : inflexible_coe L A) :\n  (h.\u03b4 : \u039b) < \u03b2 :=\nh.h\u03b4.trans_le (show _, from coe_le_coe.mp (le_of_path h.B))\n\nlemma inflexible_bot.constrains {L : litter} {A : extended_index \u03b2} (h : inflexible_bot L A) :\n  relation.trans_gen (constrains \u03b1 \u03b2)\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\u03b5 h.B h.a,\n  rw [\u2190 h.hL, \u2190 h.hA] at this,\n  exact relation.trans_gen.single this,\nend\n\nclass freedom_of_action_hypothesis (\u03b2 : Iic \u03b1) :=\n(freedom_of_action_of_lt : \u2200 \u03b3 < \u03b2, foa_ih \u03b3)\n\nexport freedom_of_action_hypothesis (freedom_of_action_of_lt)\n\nvariable [freedom_of_action_hypothesis \u03b2]\n\n/-- For the support map of `t`, we use everything that constrains `t`. -/\ndef inflexible_support {L : litter} {A : extended_index \u03b2} (h : inflexible_coe L A) :\n  set (support_condition h.\u03b4) :=\n(\u03bb c, (c.1, (h.B.cons (coe_lt h.h\u03b4)).comp c.2)) \u207b\u00b9'\n{c | relation.trans_gen (constrains \u03b1 \u03b2) c\n  (inr (f_map (coe_ne_coe.mpr $ coe_ne' h.h\u03b4\u03b5) h.t).to_near_litter,\n    (h.B.cons (coe_lt h.h\u03b5)).cons (bot_lt_coe _))}\n\nlemma inflexible_support_small {L : litter} {A : extended_index \u03b2} (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' \u03b1 (small_singleton\n    (inr (f_map (coe_ne_coe.mpr $ coe_ne' h.h\u03b4\u03b5) h.t).to_near_litter,\n      (h.B.cons (coe_lt h.h\u03b5)).cons (bot_lt_coe _)))),\n    intros c hc,\n    exact \u27e8_, rfl, hc.to_refl\u27e9, },\nend\n\nlemma inflexible_support_supports_f_map {\u03c0 : allowable \u03b2} {\u03b3 : Iic \u03b1} {\u03b4 \u03b5 : Iio \u03b1}\n  (h\u03b4 : (\u03b4 : \u039b) < \u03b3) (h\u03b5 : (\u03b5 : \u039b) < \u03b3) (h\u03b4\u03b5 : \u03b4 \u2260 \u03b5)\n  {B : path (\u03b2 : type_index) \u03b3} {t : tangle \u03b4}\n  (h\u03c0 : \u2200 \u2983a : support_condition \u2191\u03b2\u2984,\n    a \u227a[\u03b1] (inr (f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t).to_near_litter,\n      (B.cons (coe_lt h\u03b5)).cons (bot_lt_coe _)) \u2192 \u03c0 \u2022 a = a)\n  (hc : (f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t).to_near_litter.is_litter \u2192\n    inflexible \u03b1 (f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t)\n      ((B.cons (coe_lt h\u03b5)).cons (bot_lt_coe _))) :\n  (allowable.derivative (show path ((\u03b2 : Iic_index \u03b1) : type_index) (\u03b5 : Iic_index \u03b1),\n      from B.cons (coe_lt h\u03b5)) \u03c0 : allowable (\u03b5 : Iic_index \u03b1)) \u2022\n    f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t =\n    f_map (coe_ne_coe.mpr $ coe_ne' h\u03b4\u03b5) t :=\nbegin\n  have h\u2081 := allowable.derivative_cons (show path ((\u03b2 : Iic_index \u03b1) : type_index)\n    (\u03b3 : Iic_index \u03b1), from B) (coe_lt h\u03b5),\n  have h\u2082 := @smul_f_map _ _ _ _ (\u03b3 : Iic_index \u03b1) (\u03b4 : Iio_index \u03b1) \u03b5\n    (coe_lt h\u03b4) (coe_lt h\u03b5) (Iio.coe_injective.ne h\u03b4\u03b5)\n    (allowable.derivative (show path ((\u03b2 : Iic_index \u03b1) : type_index)\n      (\u03b3 : Iic_index \u03b1), from B) \u03c0) t,\n  rw h\u2081,\n  refine h\u2082.trans (congr_arg _ _),\n  refine (designated_support t).supports _ (\u03bb c hc, _),\n  have := congr_arg prod.fst (h\u03c0 (constrains.f_map h\u03b4 h\u03b5 h\u03b4\u03b5 B t c hc)),\n  obtain \u27e8c, C\u27e9 := c,\n  refine prod.ext (eq.trans _ this) rfl,\n  rw \u2190 allowable.to_struct_perm_smul at this \u22a2,\n  rw [\u2190 phase_2_assumptions.allowable_derivative_eq, \u2190 allowable.derivative_to_struct_perm],\n  change _ \u2022 _ = _ \u2022 _,\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 \u03b2}\n  (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (h : inflexible_coe L A) : Prop :=\n(atom_map_injective : \u2200 a b B\n  (ha : (inl a, B) \u2208 inflexible_support h) (hb : (inl b, B) \u2208 inflexible_support h),\n  H.atom_image a ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n    (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at ha) =\n  H.atom_image b ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n    (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hb) \u2192 a = b)\n(litter_map_injective : \u2200 (L\u2081 L\u2082 : litter) B\n  (hL\u2081 : (inr L\u2081.to_near_litter, B) \u2208 inflexible_support h)\n  (hL\u2082 : (inr L\u2082.to_near_litter, B) \u2208 inflexible_support h),\n  (H.near_litter_image L\u2081.to_near_litter ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n    (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hL\u2081) \u2229\n  H.near_litter_image L\u2082.to_near_litter ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n    (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hL\u2082) : set atom).nonempty \u2192 L\u2081 = L\u2082)\n(atom_mem : \u2200 a (L : litter) B\n  (ha : (inl a, B) \u2208 inflexible_support h) (hL : (inr L.to_near_litter, B) \u2208 inflexible_support h),\n  a \u2208 litter_set L \u2194\n    H.atom_image a ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n      (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at ha) \u2208\n    H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n      (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hL))\n(map_flexible : \u2200 (L : litter) B (hL\u2081 : (inr L.to_near_litter, B) \u2208 inflexible_support h)\n  (hL\u2082 : flexible \u03b1 L B),\n  flexible \u03b1 (H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n    (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hL\u2081)).1 B)\n\ndef hypothesised_weak_struct_approx {L : litter} {A : extended_index \u03b2}\n  (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (h : inflexible_coe L A)\n  (hH : hypothesis_injective_inflexible H h) : weak_struct_approx h.\u03b4 :=\n\u03bb B, {\n  atom_map := \u03bb a, \u27e8(inl a, B) \u2208 inflexible_support h,\n    \u03bb ha, H.atom_image a ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n      (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at ha)\u27e9,\n  litter_map := \u03bb L, \u27e8(inr L.to_near_litter, B) \u2208 inflexible_support h,\n    \u03bb hL, H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n      (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hL)\u27e9,\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 \u27e8\u27e8\u03bb a, \u27e8_, a.prop\u27e9, \u03bb a b h, _\u27e9\u27e9,\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 \u27e8\u27e8\u03bb L, \u27e8_, L.prop\u27e9, \u03bb L\u2081 L\u2082 h, _\u27e9\u27e9,\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 := \u03bb a b ha hb, hH.atom_map_injective a b B ha hb,\n  litter_map_injective := \u03bb L\u2081 L\u2082 hL\u2081 hL\u2082, hH.litter_map_injective L\u2081 L\u2082 B hL\u2081 hL\u2082,\n  atom_mem := \u03bb 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 \u03b2}\n  (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (h : inflexible_coe L A)\n  (hH : hypothesis_injective_inflexible H h) (B : extended_index h.\u03b4) (a : atom) :\n  (hypothesised_weak_struct_approx H h hH B).atom_map a = {\n    dom := (inl a, B) \u2208 inflexible_support h,\n    get := \u03bb ha, H.atom_image a ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n      (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at ha)\n  } := rfl\n\n@[simp] lemma hypothesised_weak_struct_approx_litter_map {L : litter} {A : extended_index \u03b2}\n  (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (h : inflexible_coe L A)\n  (hH : hypothesis_injective_inflexible H h) (B : extended_index h.\u03b4) (L : litter) :\n  (hypothesised_weak_struct_approx H h hH B).litter_map L = {\n    dom := (inr L.to_near_litter, B) \u2208 inflexible_support h,\n    get := \u03bb hL, H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.h\u03b4)).comp B)\n      (by rwa [inflexible_support, \u2190 h.hL, \u2190 h.hA] at hL)\n  } := rfl\n\nlemma hypothesised_weak_struct_approx_free (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free) {L : litter}\n  {A : extended_index \u03b2} (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (h : inflexible_coe L A)\n  (hH : hypothesis_injective_inflexible H h) :\n  @struct_approx.free _ _ _ _ (h.\u03b4 : Iic \u03b1)\n  (hypothesised_weak_struct_approx H h hH).refine.complete :=\nbegin\n  rintros B L' ((hL' | \u27e8L', hL', rfl\u27e9) | 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 (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  {\u03b3 : Iic \u03b1} {\u03b4 : Iio \u03b1} (h\u03b4 : (\u03b4 : \u039b) < \u03b3) (B : path (\u03b2 : type_index) \u03b3)\n  (w : weak_struct_approx \u03b4)\n  (hw : (show struct_approx (\u03b4 : Iic \u03b1), from w.complete).free) :\n  allowable \u03b4 :=\n(freedom_of_action_of_lt (\u03b4 : Iic \u03b1)\n  (h\u03b4.trans_le (show _, from coe_le_coe.mp (le_of_path B))) _ hw).some\n\nlemma allowable_of_weak_struct_approx_exactly_approximates (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  {\u03b3 : Iic \u03b1} {\u03b4 : Iio \u03b1} (h\u03b4 : (\u03b4 : \u039b) < \u03b3) (B : path (\u03b2 : type_index) \u03b3)\n  (w : weak_struct_approx \u03b4)\n  (hw : (show struct_approx (\u03b4 : Iic \u03b1), from w.complete).free) :\n  w.complete.exactly_approximates (allowable_of_weak_struct_approx \u03c0 h\u03c0 h\u03b4 B w hw).to_struct_perm :=\n(freedom_of_action_of_lt (\u03b4 : Iic \u03b1)\n  (h\u03b4.trans_le (show _, from coe_le_coe.mp (le_of_path B))) _ hw).some_spec\n\nnoncomputable def hypothesised_allowable (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  {L : litter} {A : extended_index \u03b2} (h : inflexible_coe L A)\n  (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (hH : hypothesis_injective_inflexible H h) :\n  allowable h.\u03b4 :=\nallowable_of_weak_struct_approx \u03c0 h\u03c0 h.h\u03b4 h.B _ (hypothesised_weak_struct_approx_free \u03c0 h\u03c0 H h hH)\n\nlemma hypothesised_allowable_exactly_approximates (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  {L : litter} {A : extended_index \u03b2} (h : inflexible_coe L A)\n  (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) (hH : hypothesis_injective_inflexible H h) :\n  (hypothesised_weak_struct_approx H h hH).refine.complete.exactly_approximates\n    (hypothesised_allowable \u03c0 h\u03c0 h H hH).to_struct_perm :=\nallowable_of_weak_struct_approx_exactly_approximates \u03c0 h\u03c0 h.h\u03b4 h.B _\n  (hypothesised_weak_struct_approx_free \u03c0 h\u03c0 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 (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  {L : litter} {A : extended_index \u03b2} (h : inflexible_coe L A)\n  (B : extended_index h.\u03b4) (a : atom)\n  (d : support_condition h.\u03b4) (hd\u2081 : d \u2208 designated_support h.t)\n  (hd\u2082 : relation.refl_trans_gen (constrains \u03b1 h.\u03b4) (inl a, B) d) :\n    (inl a, B) \u2208 inflexible_support h :=\nrelation.trans_gen.tail'\n  (refl_trans_gen_constrains_comp hd\u2082 _)\n  (constrains.f_map h.h\u03b4 h.h\u03b5 h.h\u03b4\u03b5 h.B h.t d hd\u2081)\n\nnoncomputable def litter_completion (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  (L : litter) (A : extended_index \u03b2) (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9) : 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\u03b4\u03b5)\n      (hypothesised_allowable \u03c0 h\u03c0 h.some H hH \u2022 h.some.t)\n  else\n    near_litter_approx.flexible_completion \u03b1 (\u03c0 A) A \u2022 L\nelse if h : nonempty (inflexible_bot L A) then\n  f_map (show (\u22a5 : type_index) \u2260 (h.some.\u03b5 : \u039b), 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 \u03b1 (\u03c0 A) A \u2022 L\n\nlemma litter_completion_of_flexible (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  (L : litter) (A : extended_index \u03b2) (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9)\n  (hflex : flexible \u03b1 L A) :\n  litter_completion \u03c0 h\u03c0 L A H = near_litter_approx.flexible_completion \u03b1 (\u03c0 A) A \u2022 L :=\nbegin\n  rw [litter_completion, dif_neg, dif_neg],\n  { rintro \u27e8\u27e8\u03b3, \u03b5, h\u03b5, C, a, rfl, rfl\u27e9\u27e9,\n    exact hflex (inflexible.mk_bot _ _ _), },\n  { rintro \u27e8\u27e8\u03b3, \u03b4, \u03b5, h\u03b4, h\u03b5, h\u03b4\u03b5, C, t, rfl, rfl\u27e9\u27e9,\n    exact hflex (inflexible.mk_coe h\u03b4 _ _ _ _), },\nend\n\nlemma litter_completion_of_inflexible_coe (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  (L : litter) (A : extended_index \u03b2) (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9)\n  (h : inflexible_coe L A) (hH : hypothesis_injective_inflexible H h) :\n  litter_completion \u03c0 h\u03c0 L A H =\n  f_map (coe_ne_coe.mpr $ coe_ne' h.h\u03b4\u03b5) (hypothesised_allowable \u03c0 h\u03c0 h H hH \u2022 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 \u27e8h\u27e9, },\nend\n\nlemma litter_completion_of_inflexible_bot (\u03c0 : struct_approx \u03b2) (h\u03c0 : \u03c0.free)\n  (L : litter) (A : extended_index \u03b2) (H : hypothesis \u27e8inr L.to_near_litter, A\u27e9)\n  (h : inflexible_bot L A) :\n  litter_completion \u03c0 h\u03c0 L A H =\n  f_map (show (\u22a5 : type_index) \u2260 (h.\u03b5 : \u039b), 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 \u27e8h\u27e9, },\n  { rintro \u27e8h'\u27e9,\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": "/-\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.Parser.Command\nimport Lean.Meta.Closure\nimport Lean.Meta.SizeOf\nimport Lean.Meta.Injective\nimport Lean.Meta.Structure\nimport Lean.Meta.AppBuilder\nimport Lean.Elab.Command\nimport Lean.Elab.DeclModifiers\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.Inductive\nimport Lean.Elab.DeclarationRange\nimport Lean.Elab.Binders\n\nnamespace Lean.Elab.Command\n\nopen Meta\n\n/- Recall that the `structure command syntax is\n```\nleading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType >> optional (\" := \" >> optional structCtor >> structFields)\n```\n-/\n\nstructure StructCtorView where\n  ref       : Syntax\n  modifiers : Modifiers\n  inferMod  : Bool  -- true if `{}` is used in the constructor declaration\n  name      : Name\n  declName  : Name\n\nstructure StructFieldView where\n  ref        : Syntax\n  modifiers  : Modifiers\n  binderInfo : BinderInfo\n  inferMod   : Bool\n  declName   : Name\n  name       : Name -- The field name as it is going to be registered in the kernel. It does not include macroscopes.\n  rawName    : Name -- Same as `name` but including macroscopes.\n  binders    : Syntax\n  type?      : Option Syntax\n  value?     : Option Syntax\n\nstructure StructView where\n  ref               : Syntax\n  modifiers         : Modifiers\n  scopeLevelNames   : List Name  -- All `universe` declarations in the current scope\n  allUserLevelNames : List Name  -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command\n  isClass           : Bool\n  declName          : Name\n  scopeVars         : Array Expr -- All `variable` declaration in the current scope\n  params            : Array Expr -- Explicit parameters provided in the `structure` command\n  parents           : Array Syntax\n  type              : Syntax\n  ctor              : StructCtorView\n  fields            : Array StructFieldView\n\ninductive StructFieldKind where\n  | newField | copiedField | fromParent | subobject\n  deriving Inhabited, DecidableEq, Repr\n\nstructure StructFieldInfo where\n  name     : Name\n  declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary \"default value\" functions.\n  fvar     : Expr\n  kind     : StructFieldKind\n  inferMod : Bool := false\n  value?   : Option Expr := none\n  deriving Inhabited, Repr\n\ndef StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool :=\n  match info.kind with\n  | StructFieldKind.fromParent => true\n  | _                          => false\n\ndef StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool :=\n  match info.kind with\n  | StructFieldKind.subobject => true\n  | _                         => false\n\n/- Auxiliary declaration for `mkProjections` -/\nstructure ProjectionInfo where\n  declName : Name\n  inferMod : Bool\n\nstructure ElabStructResult where\n  decl            : Declaration\n  projInfos       : List ProjectionInfo\n  projInstances   : List Name -- projections (to parent classes) that must be marked as instances.\n  mctx            : MetavarContext\n  lctx            : LocalContext\n  localInsts      : LocalInstances\n  defaultAuxDecls : Array (Name \u00d7 Expr \u00d7 Expr)\n\nprivate def defaultCtorName := `mk\n\n/-\nThe structure constructor syntax is\n```\nleading_parser try (declModifiers >> ident >> optional inferMod >> \" :: \")\n```\n-/\nprivate def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do\n  let useDefault := do\n    let declName := structDeclName ++ defaultCtorName\n    addAuxDeclarationRanges declName structStx[2] structStx[2]\n    pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName }\n  if structStx[5].isNone then\n    useDefault\n  else\n    let optCtor := structStx[5][1]\n    if optCtor.isNone then\n      useDefault\n    else\n      let ctor := optCtor[0]\n      withRef ctor do\n      let ctorModifiers \u2190 elabModifiers ctor[0]\n      checkValidCtorModifier ctorModifiers\n      if ctorModifiers.isPrivate && structModifiers.isPrivate then\n        throwError \"invalid 'private' constructor in a 'private' structure\"\n      if ctorModifiers.isProtected && structModifiers.isPrivate then\n        throwError \"invalid 'protected' constructor in a 'private' structure\"\n      let inferMod := !ctor[2].isNone\n      let name := ctor[1].getId\n      let declName := structDeclName ++ name\n      let declName \u2190 applyVisibility ctorModifiers.visibility declName\n      addDocString' declName ctorModifiers.docString?\n      addAuxDeclarationRanges declName ctor[1] ctor[1]\n      pure { ref := ctor, name, modifiers := ctorModifiers, inferMod, declName }\n\ndef checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do\n  if modifiers.isNoncomputable then\n    throwError \"invalid use of 'noncomputable' in field declaration\"\n  if modifiers.isPartial then\n    throwError \"invalid use of 'partial' in field declaration\"\n  if modifiers.isUnsafe then\n    throwError \"invalid use of 'unsafe' in field declaration\"\n  if modifiers.attrs.size != 0 then\n    throwError \"invalid use of attributes in field declaration\"\n\n/-\n```\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> optional inferMod >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> optional inferMod >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)\n```\n-/\nprivate def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) :=\n  let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs\n  fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do\n    let mut fieldBinder := fieldBinder\n    if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then\n      fieldBinder := mkNode ``Parser.Command.structExplicitBinder\n        #[ fieldBinder[0], mkAtomFrom fieldBinder \"(\", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder \")\" ]\n    let k := fieldBinder.getKind\n    let binfo \u2190\n      if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default\n      else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit\n      else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit\n      else throwError \"unexpected kind of structure field\"\n    let fieldModifiers \u2190 elabModifiers fieldBinder[0]\n    checkValidFieldModifier fieldModifiers\n    if fieldModifiers.isPrivate && structModifiers.isPrivate then\n      throwError \"invalid 'private' field in a 'private' structure\"\n    if fieldModifiers.isProtected && structModifiers.isPrivate then\n      throwError \"invalid 'protected' field in a 'private' structure\"\n    let inferMod         := !fieldBinder[3].isNone\n    let (binders, type?) \u2190\n      if binfo == BinderInfo.default then\n        let (binders, type?) := expandOptDeclSig fieldBinder[4]\n        let optBinderTacticDefault := fieldBinder[5]\n        if optBinderTacticDefault.isNone then\n          pure (binders, type?)\n        else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then\n          pure (binders, type?)\n        else\n          let binderTactic := optBinderTacticDefault[0]\n          match type? with\n          | none => throwErrorAt binderTactic \"invalid field declaration, type must be provided when auto-param (tactic) is used\"\n          | some type =>\n            let tac := binderTactic[2]\n            let name \u2190 Term.declareTacticSyntax tac\n            -- The tactic should be for binders+type.\n            -- It is safe to reset the binders to a \"null\" node since there is no value to be elaborated\n            let type \u2190 `(forall $(binders.getArgs):bracketedBinder*, $type)\n            let type \u2190 `(autoParam $type $(mkIdentFrom tac name))\n            pure (mkNullNode, some type)\n      else\n        let (binders, type) := expandDeclSig fieldBinder[4]\n        pure (binders, some type)\n    let value? \u2190\n      if binfo != BinderInfo.default then\n        pure none\n      else\n        let optBinderTacticDefault := fieldBinder[5]\n        -- trace[Elab.struct] \">>> {optBinderTacticDefault}\"\n        if optBinderTacticDefault.isNone then\n          pure none\n        else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then\n          pure none\n        else\n          -- binderDefault := leading_parser \" := \" >> termParser\n          pure (some optBinderTacticDefault[0][1])\n    let idents := fieldBinder[2].getArgs\n    idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do\n      let rawName := ident.getId\n      let name    := rawName.eraseMacroScopes\n      unless name.isAtomic do\n        throwErrorAt ident \"invalid field name '{name.eraseMacroScopes}', field names must be atomic\"\n      let declName := structDeclName ++ name\n      let declName \u2190 applyVisibility fieldModifiers.visibility declName\n      addDocString' declName fieldModifiers.docString?\n      return views.push {\n        ref        := ident\n        modifiers  := fieldModifiers\n        binderInfo := binfo\n        inferMod\n        declName\n        name\n        rawName\n        binders\n        type?\n        value?\n      }\n\nprivate def validStructType (type : Expr) : Bool :=\n  match type with\n  | Expr.sort .. => true\n  | _            => false\n\nprivate def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo :=\n  infos.find? fun info => info.name == fieldName\n\nprivate def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool :=\n  (findFieldInfo? infos fieldName).isSome\n\nprivate def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo :=\n  infos.map fun info =>\n    if info.name == fieldName then\n      { info with value? := value  }\n    else\n      info\n\nregister_builtin_option structureDiamondWarning : Bool := {\n  defValue := false\n  descr    := \"enable/disable warning messages for structure diamonds\"\n}\n\n/-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/\nprivate def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do\n  let fieldNames := getStructureFieldsFlattened (\u2190 getEnv) parentStructName\n  for fieldName in fieldNames do\n    if containsFieldName infos fieldName then\n      return some fieldName\n  return none\n\nprivate partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name)\n    (infos : Array StructFieldInfo) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  go 0 infos\nwhere\n  go (i : Nat) (infos : Array StructFieldInfo) := do\n    if h : i < subfieldNames.size then\n      let subfieldName := subfieldNames.get \u27e8i, h\u27e9\n      if containsFieldName infos subfieldName then\n        throwError \"field '{subfieldName}' from '{parentStructName}' has already been declared\"\n      let val  \u2190 mkProjection parentFVar subfieldName\n      let type \u2190 inferType val\n      withLetDecl subfieldName type val fun subfieldFVar =>\n        /- The following `declName` is only used for creating the `_default` auxiliary declaration name when\n           its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/\n        let declName := structDeclName ++ subfieldName\n        let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent }\n        go (i+1) infos\n    else\n      k infos\n\n/-- Given `obj.foo.bar.baz`, return `obj`. -/\nprivate partial def getNestedProjectionArg (e : Expr) : MetaM Expr := do\n  if let Expr.const subProjName .. := e.getAppFn then\n    if let some { numParams, .. } \u2190 getProjectionFnInfo? subProjName then\n      if e.getAppNumArgs == numParams + 1 then\n        return \u2190 getNestedProjectionArg e.appArg!\n  return e\n\n/-- Get field type of `fieldName` in `parentStructName`, but replace references\n  to other fields of that structure by existing field fvars.\n  Auxiliary method for `copyNewFieldsFrom`. -/\nprivate def getFieldType (infos : Array StructFieldInfo) (parentStructName : Name) (parentType : Expr) (fieldName : Name) : MetaM Expr := do\n  withLocalDeclD (\u2190 mkFreshId) parentType fun parent => do\n    let proj \u2190 mkProjection parent fieldName\n    let projType \u2190 inferType proj\n    /- Eliminate occurrences of `parent.field`. This happens when the structure contains dependent fields.\n    If the copied parent extended another structure via a subobject,\n    then the occurrence can also look like `parent.toGrandparent.field`\n    (where `toGrandparent` is not a field of the current structure). -/\n    let visit (e : Expr) : MetaM TransformStep := do\n      if let Expr.const subProjName .. := e.getAppFn then\n        if let some { ctorName, numParams, .. } \u2190 getProjectionFnInfo? subProjName then\n          let Name.str subStructName subFieldName .. := subProjName\n            | throwError \"invalid projection name {subProjName}\"\n          let args := e.getAppArgs\n          if let some major := args.get? numParams then\n            if (\u2190 getNestedProjectionArg major) == parent then\n              if let some existingFieldInfo := findFieldInfo? infos subFieldName then\n                return TransformStep.done <| mkAppN existingFieldInfo.fvar args[numParams+1:args.size]\n      return TransformStep.done e\n    let projType \u2190 Meta.transform projType (post := visit)\n    if projType.containsFVar parent.fvarId! then\n      throwError \"unsupported dependent field in {fieldName} : {projType}\"\n    return projType\n\nprivate def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do\n  if isProtected (\u2190 getEnv) fieldInfo.projFn then\n    return Visibility.protected\n  else if isPrivateName fieldInfo.projFn then\n    return Visibility.private\n  else\n    return Visibility.regular\n\nabbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field\n\n/-- Reduce projetions of the structures in `structNames` -/\nprivate def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr :=\n  let reduce (e : Expr) : MetaM TransformStep := do\n    match (\u2190 reduceProjOf? e structNames.contains) with\n    | some v => return TransformStep.done v\n    | _ => return TransformStep.done e\n  transform e (post := reduce)\n\n/--\n  Copy the default value for field `fieldName` set at structure `structName`.\n  The arguments for the `_default` auxiliary function are provided by `fieldMap`.\n  Recall some of the entries in `fieldMap` are constructor applications, and they needed\n  to be reduced using `reduceProjs`. Otherwise, the produced default value may be \"cyclic\".\n  That is, we reduce projections of the structures in `expandedStructNames`. Here is\n  an example that shows why the reduction is needed.\n  ```\n  structure A where\n    a : Nat\n\n  structure B where\n    a : Nat\n    b : Nat\n    c : Nat\n\n  structure C extends B where\n    d : Nat\n    c := b + d\n\n  structure D extends A, C\n\n  #print D.c._default\n  ```\n  Without the reduction, it produces\n  ```\n  def D.c._default : A \u2192 Nat \u2192 Nat \u2192 Nat \u2192 Nat :=\n  fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d)\n  ```\n-/\nprivate partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do\n  match getDefaultFnForField? (\u2190 getEnv) structName fieldName with\n  | none => return none\n  | some defaultFn =>\n    let cinfo \u2190 getConstInfo defaultFn\n    let us \u2190 mkFreshLevelMVarsFor cinfo\n    go? (cinfo.instantiateValueLevelParams us)\nwhere\n  failed : TermElabM (Option Expr) := do\n    logWarning s!\"ignoring default value for field '{fieldName}' defined at '{structName}'\"\n    return none\n\n  go? (e : Expr) : TermElabM (Option Expr) := do\n    match e with\n    | Expr.lam n d b c =>\n      if c.binderInfo.isExplicit then\n        let fieldName := n\n        match fieldMap.find? n with\n        | none => failed\n        | some val =>\n          let valType \u2190 inferType val\n          if (\u2190 isDefEq valType d) then\n            go? (b.instantiate1 val)\n          else\n            failed\n      else\n        let arg \u2190 mkFreshExprMVar d\n        go? (b.instantiate1 arg)\n    | e =>\n      let r := if e.isAppOfArity ``id 2 then e.appArg! else e\n      return some (\u2190 reduceProjs (\u2190 instantiateMVars e.appArg!) expandedStructNames)\n\nprivate partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  copyFields infos {} parentType fun infos _ _ => k infos\nwhere\n  copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo \u2192 FieldMap \u2192 NameSet \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n    let parentStructName \u2190 getStructureName parentType\n    let fieldNames := getStructureFields (\u2190 getEnv) parentStructName\n    let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM \u03b1 := do\n      if h : i < fieldNames.size then\n        let fieldName := fieldNames.get \u27e8i, h\u27e9\n        let fieldType \u2190 getFieldType infos parentStructName parentType fieldName\n        match findFieldInfo? infos fieldName with\n        | some existingFieldInfo =>\n          let existingFieldType \u2190 inferType existingFieldInfo.fvar\n          unless (\u2190 isDefEq fieldType existingFieldType) do\n            throwError \"parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {\u2190 mkHasTypeButIsExpectedMsg fieldType existingFieldType}\"\n          /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/\n          copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames\n        | none =>\n          let some fieldInfo := getFieldInfo? (\u2190 getEnv) parentStructName fieldName | unreachable!\n          let addNewField : TermElabM \u03b1 := do\n            let value? \u2190 copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName\n            withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do\n              let fieldDeclName := structDeclName ++ fieldName\n              let fieldDeclName \u2190 applyVisibility (\u2190 toVisibility fieldInfo) fieldDeclName\n              let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?,\n                                        kind := StructFieldKind.copiedField, inferMod := fieldInfo.inferMod }\n              copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames\n          if fieldInfo.subobject?.isSome then\n            let fieldParentStructName \u2190 getStructureName fieldType\n            if (\u2190 findExistingField? infos fieldParentStructName).isSome then\n              -- See comment at `copyDefaultValue?`\n              let expandedStructNames := expandedStructNames.insert fieldParentStructName\n              copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do\n                let fieldVal \u2190 mkCompositeField fieldType nestedFieldMap\n                trace[Meta.debug] \"composite, {fieldName} := {fieldVal}\"\n                copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames\n            else\n              let subfieldNames := getStructureFieldsFlattened (\u2190 getEnv) fieldParentStructName\n              let fieldName := fieldInfo.fieldName\n              withLocalDecl fieldName fieldInfo.binderInfo fieldType fun parentFVar =>\n                let infos := infos.push { name := fieldName, declName := structDeclName ++ fieldName, fvar := parentFVar, kind := StructFieldKind.subobject }\n                processSubfields structDeclName parentFVar fieldParentStructName subfieldNames infos fun infos =>\n                  copy (i+1) infos (fieldMap.insert fieldName parentFVar) expandedStructNames\n          else\n            addNewField\n      else\n        let infos \u2190 processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName\n        k infos fieldMap expandedStructNames\n    copy 0 infos {} expandedStructNames\n\n  processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) :=\n    infos.mapM fun info => do\n      match (\u2190 copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with\n      | some value => return { info with value? := value }\n      | none       => return info\n\n  mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do\n    let env \u2190 getEnv\n    let Expr.const parentStructName us _ \u2190 pure parentType.getAppFn | unreachable!\n    let parentCtor := getStructureCtor env parentStructName\n    let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs\n    for fieldName in getStructureFields env parentStructName do\n      match fieldMap.find? fieldName with\n      | some val => result := mkApp result val\n      | none => throwError \"failed to copy fields from parent structure{indentExpr parentType}\" -- TODO improve error message\n    return result\n\nprivate partial def mkToParentName (parentStructName : Name) (p : Name \u2192 Bool) : Name := Id.run <| do\n  let base := Name.mkSimple $ \"to\" ++ parentStructName.eraseMacroScopes.getString!\n  if p base then\n    base\n  else\n    let rec go (i : Nat) : Name :=\n      let curr := base.appendIndexAfter i\n      if p curr then curr else go (i+1)\n    go 1\n\nprivate partial def withParents (view : StructView) (k : Array StructFieldInfo \u2192 Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 #[] #[]\nwhere\n  go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM \u03b1 := do\n    if h : i < view.parents.size then\n      let parentStx := view.parents.get \u27e8i, h\u27e9\n      withRef parentStx do\n      let parentType \u2190 Term.elabType parentStx\n      let parentStructName \u2190 getStructureName parentType\n      if let some existingFieldName \u2190 findExistingField? infos parentStructName then\n        if structureDiamondWarning.get (\u2190 getOptions) then\n          logWarning s!\"field '{existingFieldName}' from '{parentStructName}' has already been declared\"\n        copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType)\n        -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure`\n      else\n        let env \u2190 getEnv\n        let subfieldNames := getStructureFieldsFlattened env parentStructName\n        let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n\n        let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default\n        withLocalDecl toParentName binfo parentType fun parentFVar =>\n          let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject }\n          processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents\n    else\n      k infos copiedParents\n\nprivate def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr \u00d7 Option Expr) := do\n  Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do\n    match view.type? with\n    | none         =>\n      match view.value? with\n      | none        => return (none, none)\n      | some valStx =>\n        Term.synthesizeSyntheticMVarsNoPostponing\n        let params \u2190 Term.addAutoBoundImplicits params\n        let value \u2190 Term.elabTerm valStx none\n        let value \u2190 mkLambdaFVars params value\n        return (none, value)\n    | some typeStx =>\n      let type \u2190 Term.elabType typeStx\n      Term.synthesizeSyntheticMVarsNoPostponing\n      let params \u2190 Term.addAutoBoundImplicits params\n      match view.value? with\n      | none        =>\n        let type  \u2190 mkForallFVars params type\n        return (type, none)\n      | some valStx =>\n        let value \u2190 Term.elabTermEnsuringType valStx type\n        Term.synthesizeSyntheticMVarsNoPostponing\n        let type  \u2190 mkForallFVars params type\n        let value \u2190 mkLambdaFVars params value\n        return (type, value)\n\nprivate partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 {} infos\nwhere\n  go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM \u03b1 := do\n    if h : i < views.size then\n      let view := views.get \u27e8i, h\u27e9\n      withRef view.ref do\n      match findFieldInfo? infos view.name with\n      | none      =>\n        let (type?, value?) \u2190 elabFieldTypeValue view\n        match type?, value? with\n        | none,      none => throwError \"invalid field, type expected\"\n        | some type, _    =>\n          withLocalDecl view.rawName view.binderInfo type fun fieldFVar =>\n            let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?,\n                                      kind := StructFieldKind.newField, inferMod := view.inferMod }\n            go (i+1) defaultValsOverridden infos\n        | none, some value =>\n          let type \u2190 inferType value\n          withLocalDecl view.rawName view.binderInfo type fun fieldFVar =>\n            let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value,\n                                      kind := StructFieldKind.newField, inferMod := view.inferMod }\n            go (i+1) defaultValsOverridden infos\n      | some info =>\n        let updateDefaultValue (fromParent : Bool) : TermElabM \u03b1 := do\n          match view.value? with\n          | none       => throwError \"field '{view.name}' has been declared in parent structure\"\n          | some valStx =>\n            if let some type := view.type? then\n              throwErrorAt type \"omit field '{view.name}' type to set default value\"\n            else\n              if defaultValsOverridden.contains info.name then\n                throwError \"field '{view.name}' new default value has already been set\"\n              let defaultValsOverridden := defaultValsOverridden.insert info.name\n              let mut valStx := valStx\n              if view.binders.getArgs.size > 0 then\n                valStx \u2190 `(fun $(view.binders.getArgs)* => $valStx:term)\n              let fvarType \u2190 inferType info.fvar\n              let value \u2190 Term.elabTermEnsuringType valStx fvarType\n              let infos := updateFieldInfoVal infos info.name value\n              go (i+1) defaultValsOverridden infos\n        match info.kind with\n        | StructFieldKind.newField    => throwError \"field '{view.name}' has already been declared\"\n        | StructFieldKind.subobject   => throwError \"unexpected subobject field reference\" -- improve error message\n        | StructFieldKind.copiedField => updateDefaultValue false\n        | StructFieldKind.fromParent  => updateDefaultValue true\n    else\n      k infos\n\nprivate def getResultUniverse (type : Expr) : TermElabM Level := do\n  let type \u2190 whnf type\n  match type with\n  | Expr.sort u _ => pure u\n  | _             => throwError \"unexpected structure resulting type\"\n\nprivate def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do\n  params.forM fun p => do\n    let type \u2190 inferType p\n    Meta.collectUsedFVars type\n  fieldInfos.forM fun info => do\n    let fvarType \u2190 inferType info.fvar\n    Meta.collectUsedFVars fvarType\n    match info.value? with\n    | none       => pure ()\n    | some value => Meta.collectUsedFVars value\n\nprivate def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed params fieldInfos).run {}\n  Meta.removeUnused scopeVars used\n\nprivate def withUsed {\u03b1} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr \u2192 TermElabM \u03b1)\n    : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnused scopeVars params fieldInfos\n  withLCtx lctx localInsts <| k vars\n\nprivate def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do\n  let type \u2190 inferType fvar\n  discard <| Term.levelMVarToParam' type\n\nprivate def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit :=\n  fvars.forM levelMVarToParamFVar\n\nprivate def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : StateRefT Nat TermElabM (Array StructFieldInfo) := do\n  levelMVarToParamFVars scopeVars\n  levelMVarToParamFVars params\n  fieldInfos.mapM fun info => do\n    levelMVarToParamFVar info.fvar\n    match info.value? with\n    | none       => pure info\n    | some value =>\n      let value \u2190 Term.levelMVarToParam' value\n      pure { info with value? := value }\n\nprivate def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) :=\n  (levelMVarToParamAux scopeVars params fieldInfos).run' 1\n\nprivate partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do\n  fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do\n    let type \u2190 inferType info.fvar\n    let u \u2190 getLevel type\n    let u \u2190 instantiateLevelMVars u\n    accLevelAtCtor u r rOffset us\n\nprivate def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do\n  let r \u2190 getResultUniverse type\n  let rOffset : Nat   := r.getOffset\n  let r       : Level := r.getLevelOffset\n  match r with\n  | Level.mvar mvarId _ =>\n    let us \u2190 collectUniversesFromFields r rOffset fieldInfos\n    let rNew := mkResultUniverse us rOffset\n    assignLevelMVar mvarId rNew\n    instantiateMVars type\n  | _ => throwError \"failed to compute resulting universe level of structure, provide universe explicitly\"\n\nprivate def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do\n  let type \u2190 inferType fvar\n  let type \u2190 instantiateMVars type\n  return collectLevelParams s type\n\nprivate def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State :=\n  fvars.foldlM collectLevelParamsInFVar s\n\nprivate def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo)\n    : TermElabM (Array Name) := do\n  let s := collectLevelParams {} structType\n  let s \u2190 collectLevelParamsInFVars scopeVars s\n  let s \u2190 collectLevelParamsInFVars params s\n  let s \u2190 fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar\n  return s.params\n\nprivate def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat \u2192 Expr \u2192 TermElabM Expr\n  | 0,   type => pure type\n  | i+1, type => do\n    let info := fieldInfos[i]\n    let decl \u2190 Term.getFVarLocalDecl! info.fvar\n    let type \u2190 instantiateMVars type\n    let type := type.abstract #[info.fvar]\n    match info.kind with\n    | StructFieldKind.fromParent =>\n      let val := decl.value\n      addCtorFields fieldInfos i (type.instantiate1 val)\n    | _  =>\n      addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type)\n\nprivate def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor :=\n  withRef view.ref do\n  let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params\n  let type \u2190 addCtorFields fieldInfos fieldInfos.size type\n  let type \u2190 mkForallFVars params type\n  let type \u2190 instantiateMVars type\n  let type := type.inferImplicit params.size !view.ctor.inferMod\n  -- trace[Meta.debug] \"ctor type {type}\"\n  pure { name := view.ctor.declName, type }\n\n@[extern \"lean_mk_projections\"]\nprivate constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment\n\nprivate def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do\n  let env \u2190 getEnv\n  match mkProjections env structName projs isClass with\n  | Except.ok env   => setEnv env\n  | Except.error ex => throwKernelException ex\n\nprivate def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do\n  let fields \u2190 infos.filterMapM fun info => do\n      if info.kind == StructFieldKind.fromParent then\n        return none\n      else\n        return some {\n          fieldName  := info.name\n          projFn     := info.declName\n          inferMod   := info.inferMod\n          binderInfo := (\u2190 getFVarLocalDecl info.fvar).binderInfo\n          subobject? :=\n            if info.kind == StructFieldKind.subobject then\n              match (\u2190 getEnv).find? info.declName with\n              | some (ConstantInfo.defnInfo val) =>\n                match val.type.getForallBody.getAppFn with\n                | Expr.const parentName .. => some parentName\n                | _ => panic! \"ill-formed structure\"\n              | _ => panic! \"ill-formed environment\"\n            else\n              none\n        }\n  modifyEnv fun env => Lean.registerStructure env { structName, fields }\n\nprivate def mkAuxConstructions (declName : Name) : TermElabM Unit := do\n  let env \u2190 getEnv\n  let hasUnit := env.contains `PUnit\n  let hasEq   := env.contains `Eq\n  let hasHEq  := env.contains `HEq\n  mkRecOn declName\n  if hasUnit then mkCasesOn declName\n  if hasUnit && hasEq && hasHEq then mkNoConfusion declName\n\nprivate def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name \u00d7 Expr \u00d7 Expr)) : TermElabM Unit := do\n  let localInsts \u2190 getLocalInstances\n  withLCtx lctx localInsts do\n    defaultAuxDecls.forM fun (declName, type, value) => do\n      let value \u2190 instantiateMVars value\n      if value.hasExprMVar then\n        throwError \"invalid default value for field, it contains metavariables{indentExpr value}\"\n      /- The identity function is used as \"marker\". -/\n      let value \u2190 mkId value\n      discard <| mkAuxDefinition declName type value (zeta := true)\n      setReducibleAttribute declName\n\nprivate partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do\n  let env \u2190 getEnv\n  let structName := view.declName\n  let sourceFieldNames := getStructureFieldsFlattened env structName\n  let structType := mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params\n  let Expr.const parentStructName us _ \u2190 pure parentType.getAppFn | unreachable!\n  let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default\n  withLocalDecl `self binfo structType fun source => do\n    let declType \u2190 instantiateMVars (\u2190 mkForallFVars params (\u2190 mkForallFVars #[source] parentType))\n    let declType := declType.inferImplicit params.size true\n    let rec copyFields (parentType : Expr) : MetaM Expr := do\n      let Expr.const parentStructName us _ \u2190 pure parentType.getAppFn | unreachable!\n      let parentCtor := getStructureCtor env parentStructName\n      let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs\n      for fieldName in getStructureFields env parentStructName do\n        if sourceFieldNames.contains fieldName then\n          let fieldVal \u2190 mkProjection source fieldName\n          result := mkApp result fieldVal\n        else\n          -- fieldInfo must be a field of `parentStructName`\n          let some fieldInfo := getFieldInfo? env parentStructName fieldName | unreachable!\n          if fieldInfo.subobject?.isNone then throwError \"failed to build coercion to parent structure\"\n          let resultType \u2190 whnfD (\u2190 inferType result)\n          unless resultType.isForall do throwError \"failed to build coercion to parent structure, unexpect type{indentExpr resultType}\"\n          let fieldVal \u2190 copyFields resultType.bindingDomain!\n          result := mkApp result fieldVal\n      return result\n    let declVal \u2190 instantiateMVars (\u2190 mkLambdaFVars params (\u2190 mkLambdaFVars #[source] (\u2190 copyFields parentType)))\n    let declName := structName ++ mkToParentName (\u2190 getStructureName parentType) fun n => !env.contains (structName ++ n)\n    addAndCompile <| Declaration.defnDecl {\n      name        := declName\n      levelParams := levelParams\n      type        := declType\n      value       := declVal\n      hints       := ReducibilityHints.abbrev\n      safety      := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe\n    }\n    if binfo.isInstImplicit then\n      addInstance declName AttributeKind.global (eval_prio default)\n    else\n      setReducibleAttribute declName\n\nprivate def elabStructureView (view : StructView) : TermElabM Unit := do\n  view.fields.forM fun field => do\n    if field.declName == view.ctor.declName then\n      throwErrorAt field.ref \"invalid field name '{field.name}', it is equal to structure constructor name\"\n    addAuxDeclarationRanges field.declName field.ref field.ref\n  let numExplicitParams := view.params.size\n  let type \u2190 Term.elabType view.type\n  unless validStructType type do throwErrorAt view.type \"expected Type\"\n  withRef view.ref do\n  withParents view fun fieldInfos copiedParents => do\n  withFields view.fields fieldInfos fun fieldInfos => do\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let u \u2190 getResultUniverse type\n    let inferLevel \u2190 shouldInferResultUniverse u\n    withUsed view.scopeVars view.params fieldInfos fun scopeVars => do\n      let numParams := scopeVars.size + numExplicitParams\n      let fieldInfos \u2190 levelMVarToParam scopeVars view.params fieldInfos\n      let type \u2190 withRef view.ref do\n        if inferLevel then\n          updateResultingUniverse fieldInfos type\n        else\n          checkResultingUniverse (\u2190 getResultUniverse type)\n          pure type\n      trace[Elab.structure] \"type: {type}\"\n      let usedLevelNames \u2190 collectLevelParamsInStructure type scopeVars view.params fieldInfos\n      match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with\n      | Except.error msg      => withRef view.ref <| throwError msg\n      | Except.ok levelParams =>\n        let params := scopeVars ++ view.params\n        let ctor \u2190 mkCtor view levelParams params fieldInfos\n        let type \u2190 mkForallFVars params type\n        let type \u2190 instantiateMVars type\n        let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType }\n        let decl    := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe\n        Term.ensureNoUnassignedMVars decl\n        addDecl decl\n        let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) =>\n          { declName := info.declName, inferMod := info.inferMod : ProjectionInfo }\n        addProjections view.declName projInfos view.isClass\n        registerStructure view.declName fieldInfos\n        mkAuxConstructions view.declName\n        let instParents \u2190 fieldInfos.filterM fun info => do\n          let decl \u2190 Term.getFVarLocalDecl! info.fvar\n          pure (info.isSubobject && decl.binderInfo.isInstImplicit)\n        withSaveInfoContext do  -- save new env\n          Term.addTermInfo view.ref[1] (\u2190 mkConstWithLevelParams view.declName) (isBinder := true)\n          if let some _ := view.ctor.ref[1].getPos? (originalOnly := true) then\n            Term.addTermInfo view.ctor.ref[1] (\u2190 mkConstWithLevelParams view.ctor.declName) (isBinder := true)\n          for field in view.fields do\n            -- may not exist if overriding inherited field\n            if (\u2190 getEnv).contains field.declName then\n              Term.addTermInfo field.ref (\u2190 mkConstWithLevelParams field.declName) (isBinder := true)\n        Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking\n        let projInstances := instParents.toList.map fun info => info.declName\n        projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default)\n        copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent\n        let lctx \u2190 getLCtx\n        let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome\n        let defaultAuxDecls \u2190 fieldsWithDefault.mapM fun info => do\n          let type \u2190 inferType info.fvar\n          pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!)\n        /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary \"default value\" declarations\n           The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/\n        let lctx :=\n          params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) =>\n            lctx.setBinderInfo p.fvarId! BinderInfo.implicit\n        let lctx :=\n          fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) =>\n            if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating \"default value\" auxiliary functions\n            else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default\n        addDefaults lctx defaultAuxDecls\n\n/-\nleading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType >> \" := \" >> optional structCtor >> structFields >> optDeriving\n\nwhere\ndef \u00abextends\u00bb := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef typeSpec := leading_parser \" : \" >> termParser\ndef optType : Parser := optional typeSpec\n\ndef structFields         := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)\ndef structCtor           := leading_parser try (declModifiers >> ident >> optional inferMod >> \" :: \")\n\n-/\ndef elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  checkValidInductiveModifier modifiers\n  let isClass   := stx[0].getKind == ``Parser.Command.classTk\n  let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers\n  let declId    := stx[1]\n  let params    := stx[2].getArgs\n  let exts      := stx[3]\n  let parents   := if exts.isNone then #[] else exts[0][1].getSepArgs\n  let optType   := stx[4]\n  let derivingClassViews \u2190 getOptDerivingClasses stx[6]\n  let type \u2190 if optType.isNone then `(Sort _) else pure optType[0][1]\n  let declName \u2190\n    runTermElabM none fun scopeVars => do\n      let scopeLevelNames \u2190 Term.getLevelNames\n      let \u27e8name, declName, allUserLevelNames\u27e9 \u2190 Elab.expandDeclId (\u2190 getCurrNamespace) scopeLevelNames declId modifiers\n      addDeclarationRanges declName stx\n      Term.withDeclName declName do\n        let ctor \u2190 expandCtor stx modifiers declName\n        let fields \u2190 expandFields stx modifiers declName\n        Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <|\n          Term.elabBinders params fun params => do\n            Term.synthesizeSyntheticMVarsNoPostponing\n            let params \u2190 Term.addAutoBoundImplicits params\n            let allUserLevelNames \u2190 Term.getLevelNames\n            elabStructureView {\n              ref := stx\n              modifiers\n              scopeLevelNames\n              allUserLevelNames\n              declName\n              isClass\n              scopeVars\n              params\n              parents\n              type\n              ctor\n              fields\n            }\n            unless isClass do\n              mkSizeOfInstances declName\n              mkInjectiveTheorems declName\n            return declName\n  derivingClassViews.forM fun view => view.applyHandlers #[declName]\n\nbuiltin_initialize registerTraceClass `Elab.structure\n\nend Lean.Elab.Command\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/Elab/Structure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270013882530887, "lm_q2_score": 0.035678546904435386, "lm_q1q2_score": 0.007945617348703055}}
{"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 \u2964 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) := \u03bb f,\nbegin\n  unfreezingI { rcases X with \u27e8X, Xcof\u27e9, rcases Y with \u27e8Y, Ycof\u27e9, },\n  let X' := bifibrant_object.mk X,\n  let Y' := bifibrant_object.mk Y,\n  let f' : (bifibrant_object.forget_fib C \u22d9 Lcof).obj X' \u27f6\n    (bifibrant_object.forget_fib C \u22d9 Lcof).obj Y' := f,\n  refine \u27e8(bifibrant_object.forget_fib C).map\n    ((bifibrant_object.forget_fib C \u22d9 Lcof).preimage f'), _\u27e9,\n  rw [\u2190 functor.comp_map, functor.image_preimage],\nend\n\nlemma Lcof_map_eq_iff_bifibrant_Q_map_eq {X Y : bifibrant_object C} (f\u2081 f\u2082 : X \u27f6 Y) :\n  Lcof.map ((bifibrant_object.forget_fib C).map f\u2081) =\n    Lcof.map ((bifibrant_object.forget_fib C).map f\u2082) \u2194\n  bifibrant_object.homotopy_category.Q.map f\u2081 = bifibrant_object.homotopy_category.Q.map f\u2082 :=\nbegin\n  erw \u2190 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) := \u03bb g,\nbegin\n  let X' := cofibrant_object.mk (CM5a.obj (terminal.from X.obj)),\n  let f : X \u27f6 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) \u226b g) with \u27e8\u03c6, h\u03c6\u27e9,\n  exact \u27e8f \u226b \u03c6, by rw [Lcof.map_comp, h\u03c6, is_iso.hom_inv_id_assoc]\u27e9,\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\u2081 f\u2082 : X \u27f6 Y) :\n  Lcof.map f\u2081 = Lcof.map f\u2082 \u2194 nonempty (model_category.right_homotopy P.pre f\u2081 f\u2082) :=\nbegin\n  unfreezingI { rcases X with \u27e8X, Xcof\u27e9, rcases Y with \u27e8Y, Ycof\u27e9, },\n  let g\u2081 : bifibrant_object.mk X \u27f6 bifibrant_object.mk Y := f\u2081,\n  let g\u2082 : bifibrant_object.mk X \u27f6 bifibrant_object.mk Y := f\u2082,\n  let P' : path_object (bifibrant_object.mk Y).obj := P,\n  erw \u2190 bifibrant_object.homotopy_category.Q_map_eq_iff' P' g\u2081 g\u2082,\n  erw \u2190 functor.map_eq_iff_of_nat_iso (Lbif_comp_Hobif_to_Hocof_iso Lcof\n    bifibrant_object.homotopy_category.Q) g\u2081 g\u2082,\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\u2081 f\u2082 : X \u27f6 Y) :\n  Lcof.map f\u2081 = Lcof.map f\u2082 \u2194 nonempty (model_category.right_homotopy P.pre f\u2081 f\u2082) :=\nbegin\n  split,\n  { intro h,\n    let X' := CM5a.obj (terminal.from X.obj),\n    let i : X.obj \u27f6 X' := CM5a.i (terminal.from X.obj),\n    have sq\u2081 : comm_sq ((cofibrant_object.forget C).map f\u2081) i (terminal.from Y.obj) (terminal.from X') := by tidy,\n    have sq\u2082 : comm_sq ((cofibrant_object.forget C).map f\u2082) i (terminal.from Y.obj) (terminal.from X') := by tidy,\n    let g\u2081 : cofibrant_object.mk X' \u27f6 Y := sq\u2081.lift,\n    let g\u2082 : cofibrant_object.mk X' \u27f6 Y := sq\u2082.lift,\n    have eq : Lcof.map g\u2081 = Lcof.map g\u2082,\n    { let j : X \u27f6 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 [\u2190 cancel_epi (Lcof.map j), \u2190 functor.map_comp],\n      convert h,\n      exacts [sq\u2081.fac_left, sq\u2082.fac_left], },\n    rw Lcof_map_eq_iff'_both_fibrant Lcof P g\u2081 g\u2082 at eq,\n    convert nonempty.intro (eq.some.comp_left i),\n    exacts [sq\u2081.fac_left.symm, sq\u2082.fac_left.symm], },\n  { intro h,\n    change (cofibrant_replacement.\u03c0 Lcof).map (cofibrant_object.homotopy_category.Q.map f\u2081) =\n      (cofibrant_replacement.\u03c0 Lcof).map (cofibrant_object.homotopy_category.Q.map f\u2082),\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\u2081 f\u2082 : X \u27f6 Y) :\n  Lcof.map f\u2081 = Lcof.map f\u2082 \u2194 nonempty (left_homotopy Cyl.pre f\u2081 f\u2082) :=\nbegin\n  let P := path_object.some Y.obj,\n  rw Lcof_map_eq_iff' Lcof P,\n  split,\n  { exact \u03bb h, nonempty.intro (h.some.to_left_homotopy Cyl), },\n  { exact \u03bb h, nonempty.intro (h.some.to_right_homotopy P), },\nend\n\nnamespace fundamental_lemma\n\nvariables {Ho : Type*} [category Ho] (L : C \u2964 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' \u27f6 Y := CM5b.p (initial.to Y),\n    haveI := localization.inverts L weq p weak_eq.property,\n    rcases this (g \u226b inv (L.map p)) with \u27e8\u03c6, h\u03c6\u27e9,\n    exact \u27e8\u03c6 \u226b p, by rw [L.map_comp, h\u03c6, assoc, is_iso.inv_hom_id, comp_id]\u27e9, },\n  suffices : \u2200 (A B : cofibrant_object C) [is_fibrant B.obj], function.surjective\n    (@category_theory.functor.map _ _ _ _ (cofibrant_object.forget C \u22d9 L) A B),\n  { exact this (cofibrant_object.mk X) (cofibrant_object.mk Y'), },\n  simp only [\u2190 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 \u27f6 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\u2081 f\u2082 : X \u27f6 Y} {P : precylinder X}\n  (h : left_homotopy P f\u2081 f\u2082) : L.map f\u2081 = L.map f\u2082 :=\nbegin\n  simp only [\u2190 h.h\u2080, \u2190 h.h\u2081, L.map_comp],\n  congr' 1,\n  simp only [\u2190 cancel_mono (L.map P.\u03c3), \u2190 L.map_comp, P.\u03c3d\u2080, P.\u03c3d\u2081],\nend\n\nlemma map_eq_iff {X Y : C} [is_cofibrant X] [is_fibrant Y] (Cyl : cylinder X) (f\u2081 f\u2082 : X \u27f6 Y) :\n  L.map f\u2081 = L.map f\u2082 \u2194 nonempty (left_homotopy Cyl.pre f\u2081 f\u2082) :=\nbegin\n  split,\n  { intro h,\n    let Y' := CM5b.obj (initial.to Y),\n    let i : Y' \u27f6 Y := CM5b.p (initial.to Y),\n    have sq\u2081 : comm_sq (initial.to Y') (initial.to X) i f\u2081 := by tidy,\n    have sq\u2082 : comm_sq (initial.to Y') (initial.to X) i f\u2082 := by tidy,\n    let g\u2081 : cofibrant_object.mk X \u27f6 cofibrant_object.mk Y' := sq\u2081.lift,\n    let g\u2082 : cofibrant_object.mk X \u27f6 cofibrant_object.mk Y' := sq\u2082.lift,\n    haveI := localization.inverts L weq i weak_eq.property,\n    rw [\u2190 sq\u2081.fac_right, \u2190 sq\u2082.fac_right, L.map_comp, L.map_comp,\n      cancel_mono] at h,\n    change (cofibrant_object.forget C \u22d9 L).map g\u2081 =\n      (cofibrant_object.forget C \u22d9 L).map g\u2082 at h,\n    rw \u2190 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\u2081 g\u2082 at h',\n    rw [\u2190 sq\u2081.fac_right, \u2190 sq\u2082.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\u2081 f\u2082 : X \u27f6 Y) :\n  L.map f\u2081 = L.map f\u2082 \u2194 nonempty (right_homotopy P.pre f\u2081 f\u2082) :=\nbegin\n  let Cyl := cylinder.some X,\n  rw map_eq_iff L Cyl f\u2081 f\u2082,\n  split,\n  { exact \u03bb h, nonempty.intro (h.some.to_right_homotopy P), },\n  { exact \u03bb 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": "import basic .hp .hp_component .view\n\nnamespace hp\n\nopen interaction_monad.result widget rc\n-- #check create_hp_state\n-- meta def rc.run_to_tc {\u03c0 \u03b1} [has_should_update \u03c0]: rc \u03c0 \u03b1 \u2192 tc \u03c0 \u03b1\n-- | rr :=\n--   component.with_should_update (\u03bb \u27e8ts\u2081,p\u2081\u27e9 \u27e8ts\u2082, p\u2082\u27e9, (should_update p\u2081 p\u2082))\n--   $ component.with_state\n  -- $ component.with_state\n\n  -- $ component.stateful \u03b2 (result hp_state \u03c3)\n  -- (\u03bb \u27e8ts,p\u27e9 last,\n  --   match last with\n  --   | none := match create_hp_state ts with\n  --             | (success rs _) := let r := run $ i p none in r rs\n  --             | (exception _ _ ts) := undefined_core \"rc.run_to_tc create_hp_state failed\" -- [hack]\n  --             end\n  --   | some (success s rs) := let r := run $  i p (some s) in r rs\n  --   | some (exception _ _ rs) := let r := run $ i p none  in r rs\n  --   end\n  -- ) (\u03bb \u27e8_,p\u27e9 s b,\n  --   match s with\n  --   | (success s rs) := let r := run $ u p s b in let r := r rs in (prod.fst <$> r,result.get r >>= prod.snd)\n  --   | x := (x,none)\n  --   end\n  -- ) (\u03bb \u27e8_,p\u27e9 s,\n  --   match s with\n  --   | (success s rs) := let r := run $ v p s in let r := r rs in [\"error occurred\"] <| r.get\n  --   | (exception msg _ rs) := [\"error: \", show_html msg]\n  --   end\n  -- )\n\n-- meta def rc.run : rc unit string \u2192 component tactic_state string\n-- | r := tc.to_component $ rc.run_to_tc r\n\nopen tactic\nmeta def rt_run {\u03b1 : Type}: hp \u03b1 \u2192 tactic \u03b1\n| r := do\n  rs \u2190 create_hp_state,\n  let r := (run r),\n  match r rs with\n  | (result.success a rs) := do\n    tactic.write rs.ts,\n    (result, gs) \u2190 tactic.unsafe.type_context.run $ box.all_targets rs.b,\n    -- tactic.trace result,\n    tactic.unsafe.assign rs.result result,\n    tactic.set_goals gs,\n    pure a\n  | (result.exception m p rs) := (\u03bb _, result.exception m p rs.ts)\n  end\n\nmeta def rt_run_inst: monad_run tactic hp :=\n{run := @rt_run}\n\n\nmeta def step {\u03b1 : Type} (m : hp \u03b1) : hp unit :=\nm >> pure ()\n\n-- /- istep is used to make an interactive thingy.  -/\n-- meta def istep_core {\u03c3 \u03c4 \u03b1 : Type} (line0 col0 line col : nat) (t : state_t \u03c3 (interaction_monad \u03c4) \u03b1) : state_t \u03c3 (interaction_monad \u03c4) unit :=\n-- \u27e8\u03bb v s,\n--   match (@scope_trace _ line col (\u03bb _, t.run v s)) with\n--   | (success \u27e8a,v\u27e9 s') := success ((),v) s'\n--   | (exception (some msg) p s') := exception (some msg) (some \u27e8line, col \u27e9) s'\n--   | (exception none p s') := silent_fail s'\n--   end\n-- \u27e9\nmeta def istep_core {\u03b1 : Type} (line0 col0 line col : nat) (t : hp \u03b1) : hp unit :=\n-- @monad_lift (interaction_monad hp_state) hp _ unit $\n\u03bb v : hp_state,\n  match ((@scope_trace _ line col (\u03bb _, let r := (run t) in r v)) : interaction_monad.result hp_state \u03b1) with\n  | (success a s') := success () s'\n  | (exception (some msg) p s') := exception (some msg) (some \u27e8line, col \u27e9) s'\n  | (exception none p s') := silent_fail s'\n  end\n\nmeta def istep {\u03b1 : Type} (line0 col0 line col ast : nat) (r : hp \u03b1) : hp unit :=\nistep_core line0 col0 line col r\n\nmeta instance : interactive.executor hp :=\n{ config_type := nat,\n  execute_with := \u03bb n tac, rt_run tac\n}\n\nmeta def main (rs : hp_state) : component tactic_state empty :=\ncomponent.with_should_update (\u03bb _ _, tt)\n$ component.stateful string unit\n(\u03bb _ _, \u27e8\u27e9)\n(\u03bb _ _ _, (\u27e8\u27e9, none))\n(\u03bb _ _, html.of_component rs app)\n\nmeta def save_info (p : pos) : hp unit := do\n  v \u2190 get,\n  monad_lift $ tactic.save_widget p $ main v,\n  pure ()\n\n\nopen tactic.unsafe\n\nmeta def first {\u03b1} : ZR \u03b1 \u2192 hp \u03b1\n| zr := do\n  rs \u2190 get,\n  b \u2190 pure $ rs.b,\n  adrs \u2190 pure $ box.target_addresses b,\n  adrs.mfirst (\u03bb adr, ZR.run $ do\n      ZR.goto adr,\n      zr\n  )\n\nnamespace interactive\n\nmeta def trace_box : hp unit := do\n  rs \u2190 get,\n  \u2350 $ tactic.trace rs.b,\n  pure ()\n\nmeta def trace_writeup : hp unit := do\n  rs \u2190 get,\n  r \u2190 monad_lift $ writeup.write rs.dont_instantiate rs.writeup.reverse,\n  -- [todo] tostring the html?\n  pure ()\n\nmeta def try_targets_with_name {\u03b1} : name \u2192 ZR \u03b1 \u2192 ZR \u03b1 | n z := do\n  \u27e8_,b\u27e9 \u2190 get,\n  adrs \u2190 pure $ box.find_targets_with_name n b,\n  adrs.mfirst (\u03bb a, do\n    \u2350 $ box.Z.down_adr a,\n    z\n  )\n\nmeta def try_with_name {\u03b1} : name \u2192 ZR \u03b1 \u2192 ZR \u03b1 | n z := do\n  -- \u2350 $ trace_m \"try_with_name: \" $ n,\n  \u27e8_, b\u27e9 \u2190 get,\n  adrs \u2190 pure $ box.find_with_name n b,\n  adrs.mfirst (\u03bb a, do\n    \u2350 $ box.Z.down_adr a,\n    z\n  )\n\n\nmeta def try_all_targets {\u03b1} : ZR \u03b1 \u2192 ZR \u03b1 | z := do\n  adrs \u2190 \u2350 $ box.Z.prop_goal_addresses,\n  adrs.mfirst (\u03bb a, do\n    \u2350 $ box.Z.down_adr a,\n    z\n  )\n\nmeta def intros : hp unit :=\n  ZR.run $ try_all_targets $ ZR.intros *> pure ()\n\nmeta def cosplit : hp unit :=\n  ZR.run $ try_all_targets $ ZR.cosplit\n\nmeta def split : hp unit := ZR.run $ try_all_targets $ (split_conj_cmd <|> split_exists) *> pure ()\n\nmeta def trace_commands_at (n : name) : hp unit := do\n  ZR.run (do\n    \u2350 $ box.Z.goto_name n,\n    cs \u2190 get_commands,\n    \u2350 $ tactic.trace $ waterfall_command.display_name <$> cs,\n    pure ()\n  )\n\n@[derive has_reflect, derive has_to_tactic_format]\nmeta inductive source_loc\n| of_name (n : name)\n| of_type_pexpr (t : pexpr)\n| just_pexpr (e : pexpr)\n\n@[reducible]\nmeta def target_loc := option name\n\n\nopen lean.parser\n\nmeta def surround {\u03b1} (l r : string) : lean.parser \u03b1 \u2192 lean.parser \u03b1\n| p := tk l *> p <* tk r\n\nmeta def parse_source_loc : lean.parser (source_loc) :=\n  (pure source_loc.of_name <*> ident)\n  -- <|> surround \"\u2039\" \"\u203a\" (pure source_loc.of_type_pexpr <*> lean.parser.pexpr std.prec.max tt)\n  <|> ((pure source_loc.just_pexpr) <*> interactive.types.texpr)\n\nmeta def goto_source_from_loc : source_loc \u2192 box.Z unit\n| (source_loc.of_name n) := do\n  b \u2190 box.Z.cursor,\n  a \u2190 returnopt $ box.find_source (\u03bb \u0393 s, s.label = n) b,\n  box.Z.goto a\n| _ := notimpl\n\nmeta def get_source_from_loc : source_loc \u2192 list source \u2192 tactic (list source)\n| (source_loc.of_name n) ss := singleton <$> (alternative.returnopt $ ss.find (\u03bb x, x.label = n))\n| (source_loc.of_type_pexpr p) ss := do\n  T \u2190 tactic.to_expr p tt ff,\n  ss.mfilter (\u03bb s, tactic.can_unify s.type T)\n| (source_loc.just_pexpr p) _ := do\n  x \u2190 tactic.to_expr p tt ff,\n\n  s \u2190 source.of_lemma x,\n  pure [s]\n\nmeta def parse_targ_loc : lean.parser target_loc :=\n  (optional (tk \"at\") *> pure some <*> ident) <|> pure none\n\nmeta def try_loc {\u03b1} : option name \u2192 ZR \u03b1 \u2192 ZR \u03b1\n| none z := try_all_targets z\n| (some n) z := try_with_name n z\n\nmeta def apply (s : interactive.parse parse_source_loc) (t : interactive.parse parse_targ_loc) : hp unit :=\n  ZR.run $ try_loc t (do\n    ZR.set_context,\n    g \u2190 \u2350 $ box.Z.down_stub,\n    ss \u2190 \u2350 $ box.Z.source_list,\n    ss \u2190 \u2350 $ get_source_from_loc s ss,\n    ss.mfirst (\u03bb s, do\n      hp.apply s g,\n      ZR.commit\n    ))\n\nmeta def cases (s : interactive.parse parse_source_loc) : hp unit :=\nZR.run (do\n  \u2350 $ goto_source_from_loc s,\n  cases_or <|> cases_and\n)\n\nmeta def expand (s : interactive.parse parse_targ_loc) : hp unit :=\nZR.run $ try_loc s ( (expand_target <|> expand_source) *> pure ())\n\nmeta def unroll (s : interactive.parse parse_targ_loc) : hp unit :=\nZR.run $ try_loc s $ hp.unroll\n\nend interactive\nend hp\n-- set_option pp.all true\nopen hp\nset_option trace.app_builder true\n-- example {P: nat \u2192 nat \u2192 Prop} : \u03a0 (p : \u2200 y, \u2203 x, P y x), \u2203 z, P 0 z :=\n-- begin [hp]\n--   -- (ZR.run (do (\u2350 box.Z.first_goal) *> get_target_commands >>= (list.mmap $ pure \u2218 waterfall_command.display_name))) >>= \u2350 \u2218 tactic.trace,\n--   intros,\n--   -- (ZR.run (\u2350 (box.Z.intros) *> get_target_commands *> ZR.trace_state)),\n--   split,\n--   apply_first `p,\n--   -- (ZR.run (do ((\u2350 box.Z.first_goal) *> (\u2350 box.Z.next)) *> get_target_commands >>= (list.mmap $ pure \u2218 waterfall_command.display_name))) >>= \u2350 \u2218 tactic.trace,\n-- end", "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/tactic/hp_interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.025957355219835304, "lm_q1q2_score": 0.007892117758740378}}
{"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.ForEachExprWhere\nimport Lean.Meta.Match.Match\nimport Lean.Meta.GeneralizeVars\nimport Lean.Meta.ForEachExpr\nimport Lean.Elab.BindersUtil\nimport Lean.Elab.PatternVar\nimport Lean.Elab.Quotation.Precheck\nimport Lean.Elab.SyntheticMVars\n\nnamespace Lean.Elab.Term\nopen Meta\nopen Lean.Parser.Term\n\nprivate def expandSimpleMatch (stx : Syntax) (discr : Term) (lhsVar : Ident) (rhs : Term) (expectedType? : Option Expr) : TermElabM Expr := do\n  let newStx \u2190 `(let $lhsVar := $discr; $rhs)\n  withMacroExpansion stx newStx <| elabTerm newStx expectedType?\n\nprivate def mkUserNameFor (e : Expr) : TermElabM Name := do\n  match e with\n  /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/\n  | .fvar fvarId => mkFreshUserName (\u2190 fvarId.getUserName)\n  | _            => mkFreshBinderName\n\n\n/--\n   Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression.\n   This can happen due to error recovery. Example\n   ```\n   example : (p \u2228 p) \u2192 p := fun h => match\n   ```\n   If we don't abort, the elaborator loops because we will keep trying to expand\n   ```\n   match\n   ```\n   into\n   ```\n   let d := <Syntax.missing>; match\n   ```\n   Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/\ndef isAtomicDiscr (discr : Syntax) : TermElabM Bool := do\n  match discr with\n  | `($_:ident)  => pure true\n  | `(@$_:ident) => pure true\n  | `(?$_:ident) => pure true\n  | _ => if discr.isMissing then throwAbortTerm else pure false\n\n-- See expandNonAtomicDiscrs?\nprivate def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do\n  let term := discr[1]\n  elabTerm term none\n\nstructure Discr where\n  expr : Expr\n  /-- `some h` if discriminant is annotated with the `h : ` notation. -/\n  h?  : Option Syntax := none\n  deriving Inhabited\n\nstructure ElabMatchTypeAndDiscrsResult where\n  discrs    : Array Discr\n  matchType : Expr\n  /-- `true` when performing dependent elimination. We use this to decide whether we optimize the \"match unit\" case.\n     See `isMatchUnit?`. -/\n  isDep     : Bool\n  alts      : Array MatchAltView\n\nprivate partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptMotive : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)\n      : TermElabM ElabMatchTypeAndDiscrsResult := do\n  if matchOptMotive.isNone then\n    elabDiscrs 0 #[]\n  else\n    -- motive := leading_parser atomic (\"(\" >> nonReservedSymbol \"motive\" >> \" := \") >> termParser >> \")\"\n    let matchTypeStx := matchOptMotive[0][3]\n    let matchType \u2190 elabType matchTypeStx\n    let (discrs, isDep) \u2190 elabDiscrsWitMatchType matchType\n    return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }\nwhere\n  /-- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user.  -/\n  elabDiscrsWitMatchType (matchType : Expr) : TermElabM (Array Discr \u00d7 Bool) := do\n    let mut discrs := #[]\n    let mut i := 0\n    let mut matchType := matchType\n    let mut isDep := false\n    for discrStx in discrStxs do\n      i := i + 1\n      matchType \u2190 whnf matchType\n      match matchType with\n      | Expr.forallE _ d b _ =>\n        let discr \u2190 fullApproxDefEq <| elabTermEnsuringType discrStx[1] d\n        trace[Elab.match] \"discr #{i} {discr} : {d}\"\n        if b.hasLooseBVars then\n          isDep := true\n        matchType := b.instantiate1 discr\n        discrs := discrs.push { expr := discr }\n      | _ =>\n        throwError \"invalid motive provided to match-expression, function type with arity #{discrStxs.size} expected\"\n    return (discrs, isDep)\n\n  markIsDep (r : ElabMatchTypeAndDiscrsResult) :=\n    { r with isDep := true }\n\n  /-- Elaborate discriminants inferring the match-type -/\n  elabDiscrs (i : Nat) (discrs : Array Discr) : TermElabM ElabMatchTypeAndDiscrsResult := do\n    if h : i < discrStxs.size then\n      let discrStx := discrStxs.get \u27e8i, h\u27e9\n      let discr     \u2190 elabAtomicDiscr discrStx\n      let discr     \u2190 instantiateMVars discr\n      let userName \u2190 mkUserNameFor discr\n      let h? := if discrStx[0].isNone then none else some discrStx[0][0]\n      let discrs := discrs.push { expr := discr, h? }\n      let mut result \u2190 elabDiscrs (i + 1) discrs\n      let matchTypeBody \u2190 kabstract result.matchType discr\n      if matchTypeBody.hasLooseBVars then\n        result := markIsDep result\n      /-\n        We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions.\n        This transformation was added to address issue #1155, and avoid an unnecessary dependency.\n        In issue #1155, `discrType` was of the form `let _discr := OfNat.ofNat ... 0 ?m; ...`, and not removing\n        the unnecessary `let-expr` was introducing an artificial dependency to `?m`.\n        TODO: make sure that even when this kind of artificial dependecy occurs we catch it before sending\n        the term to the kernel.\n      -/\n      let discrType \u2190 transform (usedLetOnly := true) (\u2190 instantiateMVars (\u2190 inferType discr))\n      let matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody\n      return { result with matchType }\n    else\n      return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType }\n\ndef expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do\n  matchAlts.mapM fun matchAlt => do\n    let patterns \u2190 matchAlt.patterns.mapM expandMacros\n    pure { matchAlt with patterns := patterns }\n\nprivate def getMatchGeneralizing? : Syntax \u2192 Option Bool\n  | `(match (generalizing := true)  $[$motive]? $_discrs,* with $_alts:matchAlt*) => some true\n  | `(match (generalizing := false) $[$motive]? $_discrs,* with $_alts:matchAlt*) => some false\n  | _ => none\n\n/-- Given `stx` a match-expression, return its alternatives. -/\nprivate def getMatchAlts : Syntax \u2192 Array MatchAltView\n  | `(match $[$gen]? $[$motive]? $_discrs,* with $alts:matchAlt*) =>\n    alts.filterMap fun alt => match alt with\n      | `(matchAltExpr| | $patterns,* => $rhs) => some {\n          ref      := alt,\n          patterns := patterns,\n          rhs      := rhs\n        }\n      | _ => none\n  | _ => #[]\n\n@[builtin_term_elab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do\n  let e \u2190 elabTerm stx[1] expectedType?\n  return mkInaccessible e\n\nopen Lean.Elab.Term.Quotation in\n@[builtin_quot_precheck Lean.Parser.Term.match] def precheckMatch : Precheck\n  | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do\n    discrs.forM precheck\n    for (pats, rhs) in patss.zip rhss do\n      let vars \u2190 try\n        getPatternsVars pats\n      catch | _ => return  -- can happen in case of pattern antiquotations\n      Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs\n  | _ => throwUnsupportedSyntax\n\n/-- We convert the collected `PatternVar`s intro `PatternVarDecl` -/\nstructure PatternVarDecl where\n  fvarId : FVarId\n\nprivate partial def withPatternVars {\u03b1} (pVars : Array PatternVar) (k : Array PatternVarDecl \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (decls : Array PatternVarDecl) (userNames : Array Name) := do\n    if h : i < pVars.size then\n      let var := pVars.get \u27e8i, h\u27e9\n      let type \u2190 mkFreshTypeMVar\n      withLocalDecl var.getId BinderInfo.default type fun x =>\n        loop (i+1) (decls.push { fvarId := x.fvarId! }) (userNames.push Name.anonymous)\n    else\n      k decls\n  loop 0 #[] #[]\n\n/-!\nRemark: when performing dependent pattern matching, we often had to write code such as\n\n```lean\ndef Vec.map' (f : \u03b1 \u2192 \u03b2) (xs : Vec \u03b1 n) : Vec \u03b2 n :=\n  match n, xs with\n  | _, nil       => nil\n  | _, cons a as => cons (f a) (map' f as)\n```\nWe had to include `n` and the `_`s because the type of `xs` depends on `n`.\nMoreover, `nil` and `cons a as` have different types.\nThis was quite tedious. So, we have implemented an automatic \"discriminant refinement procedure\".\nThe procedure is based on the observation that we get a type error whenenver we forget to include `_`s\nand the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant\nis an indexed family, and add their indices as new discriminants.\n\nThe current implementation, adds indices as they are found, and does not\ntry to \"sort\" the new discriminants.\n\nIf the refinement process fails, we report the original error message.\n-/\n\n/-- Auxiliary structure for storing an type mismatch exception when processing the\n   pattern #`idx` of some alternative. -/\nstructure PatternElabException where\n  ex          : Exception\n  patternIdx  : Nat -- Discriminant that sh\n  pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch\n\n/--\n  This method is part of the \"discriminant refinement\" procedure. It in invoked when the\n  type of the `pattern` does not match the expected type. The expected type is based on the\n  motive computed using the `match` discriminants.\n  It tries to compute a path to an index of the discriminant type.\n  For example, suppose the user has written\n  ```\n  inductive Mem (a : \u03b1) : List \u03b1 \u2192 Prop where\n    | head {as} : Mem a (a::as)\n    | tail {as} : Mem a as \u2192 Mem a (a'::as)\n\n  infix:50 \" \u2208 \" => Mem\n\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match h with\n  | Mem.head => rfl\n  ```\n  The motive for the match is `a \u2208 [b] \u2192 b = a`, and get a type mismatch between the type\n  of `Mem.head` and `a \u2208 [b]`. This procedure return the path `[2, 1]` to the index `b`.\n  We use it to produce the following refinement\n  ```\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match b, h with\n  | _, Mem.head => rfl\n  ```\n  which produces the new motive `(x : Nat) \u2192  a \u2208 [x] \u2192 x = a`\n  After this refinement step, the `match` is elaborated successfully.\n\n  This method relies on the fact that the dependent pattern matcher compiler solves equations\n  between indices of indexed inductive families.\n  The following kinds of equations are supported by this compiler:\n  - `x = t`\n  - `t = x`\n  - `ctor ... = ctor ...`\n\n  where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor.\n  Our procedure ensures that \"information\" is not lost, and will *not* succeed in an\n  example such as\n  ```\n  example (a b : Nat) (f : Nat \u2192 Nat) (h : f a \u2208 [f b]) : f b = f a :=\n    match h with\n    | Mem.head => rfl\n  ```\n  and will not add `f b` as a new discriminant. We may add an option in the future to\n  enable this more liberal form of refinement.\n-/\nprivate partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do\n  goType (\u2190 instantiateMVars (\u2190 inferType pattern)) expected\nwhere\n  checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do\n    guard d.isApp\n    guard <| t.getAppNumArgs == d.getAppNumArgs\n    let tFn := t.getAppFn\n    let dFn := d.getAppFn\n    guard <| tFn.isConst && dFn.isConst\n    guard (\u2190 isDefEq tFn dFn)\n\n  -- Visitor for inductive types\n  goType (t d : Expr) : OptionT MetaM (List Nat) := do\n    let t \u2190 whnf t\n    let d \u2190 whnf d\n    checkCompatibleApps t d\n    matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do\n      let tArgs := t.getAppArgs\n      let dArgs := d.getAppArgs\n      for i in [:info.numParams] do\n        let tArg := tArgs[i]!\n        let dArg := dArgs[i]!\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goType tArg dArg)\n      for i in [info.numParams : tArgs.size] do\n        let tArg := tArgs[i]!\n        let dArg := dArgs[i]!\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goIndex tArg dArg)\n      failure\n\n  -- Visitor for indexed families\n  goIndex (t d : Expr) : OptionT MetaM (List Nat) := do\n    let t \u2190 whnfD t\n    let d \u2190 whnfD d\n    if t.isFVar || d.isFVar then\n      return [] -- Found refinement path\n    else\n      checkCompatibleApps t d\n      matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do\n        let tArgs := t.getAppArgs\n        let dArgs := d.getAppArgs\n        for i in [:info.numParams] do\n          let tArg := tArgs[i]!\n          let dArg := dArgs[i]!\n          unless (\u2190 isDefEq tArg dArg) do\n            failure\n        for i in [info.numParams : tArgs.size] do\n          let tArg := tArgs[i]!\n          let dArg := dArgs[i]!\n          unless (\u2190 isDefEq tArg dArg) do\n            return i :: (\u2190 goIndex tArg dArg)\n        failure\n\nprivate partial def eraseIndices (type : Expr) : MetaM Expr := do\n  let type' \u2190 whnfD type\n  matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do\n    let args := type'.getAppArgs\n    let params \u2190 args[:info.numParams].toArray.mapM eraseIndices\n    let result := mkAppN type'.getAppFn params\n    let resultType \u2190 inferType result\n    let (newIndices, _, _) \u2190  forallMetaTelescopeReducing resultType (some (args.size - info.numParams))\n    return mkAppN result newIndices\n\nprivate def withPatternElabConfig (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withoutErrToSorry <| withReader (fun ctx => { ctx with inPattern := true }) <| x\n\nprivate def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr \u00d7 Expr) :=\n  withReader (fun ctx => { ctx with implicitLambda := false }) do\n    let mut patterns  := #[]\n    let mut matchType := matchType\n    for idx in [:patternStxs.size] do\n      let patternStx := patternStxs[idx]!\n      matchType \u2190 whnf matchType\n      match matchType with\n      | Expr.forallE _ d b _ =>\n        let pattern \u2190 do\n          let s \u2190 saveState\n          try\n            liftM <| withSynthesize <| withPatternElabConfig <| elabTermEnsuringType patternStx d\n          catch ex : Exception =>\n            restoreState s\n            match (\u2190 liftM <| commitIfNoErrors? <| withPatternElabConfig do elabTermAndSynthesize patternStx (\u2190 eraseIndices d)) with\n            | some pattern =>\n              match (\u2190 findDiscrRefinementPath pattern d |>.run) with\n              | some path =>\n                restoreState s\n                -- Wrap the type mismatch exception for the \"discriminant refinement\" feature.\n                throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path }\n              | none => restoreState s; throw ex\n            | none => throw ex\n        matchType := b.instantiate1 pattern\n        patterns  := patterns.push pattern\n      | _ => throwError \"unexpected match type\"\n    return (patterns, matchType)\n\nopen Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)\n\nnamespace ToDepElimPattern\n\nprivate def throwInvalidPattern (e : Expr) : MetaM \u03b1 :=\n  throwError \"invalid pattern {indentExpr e}\"\n\nstructure State where\n  patternVars : Array Expr := #[]\n\nstructure Context where\n  /--\n    When visiting an assigned metavariable, if it has an user-name. We save it here.\n    We want to preserve these user-names when generating new pattern variables. -/\n  userName : Name := Name.anonymous\n  /--\n    Pattern variables that were explicitly provided by the user.\n    Recall that implicit parameters and `_` are elaborated as metavariables, and then converted into pattern variables\n    by the `normalize` procedure.\n  -/\n  explicitPatternVars : Array FVarId := #[]\n\nabbrev M := ReaderT Context $ StateRefT State TermElabM\n\n/-- Return true iff `e` is an explicit pattern variable provided by the user. -/\ndef isExplicitPatternVar (e : Expr) : M Bool := do\n  if e.isFVar then\n    return (\u2190 read).explicitPatternVars.any (\u00b7 == e.fvarId!)\n  else\n    return false\n\n/--\n  Helper function for \"saving\" the user name associated with `mvarId` (if it is not \"anonymous\") before visiting `x`\n  The auto generalization feature will uses synthetic holes to preserve the name of the free variable included during generalization.\n  For example, if we are generalizing a free variable `bla`, we add the synthetic hole `?bla` for the pattern. We use synthetic hole\n  because we don't know whether `?bla` will become an inaccessible pattern or not.\n  The `withMVar` method makes sure we don't \"lose\" this name when `isDefEq` perform assignments of the form `?bla := ?m` where `?m` has no user name.\n  This can happen, for example, when the user provides a `_` pattern, or for implicit fields.\n-/\nprivate def withMVar (mvarId : MVarId) (x : M \u03b1) : M \u03b1 := do\n  let localDecl \u2190 getMVarDecl mvarId\n  if !localDecl.userName.isAnonymous && (\u2190 read).userName.isAnonymous then\n    withReader (fun ctx => { ctx with userName := localDecl.userName }) x\n  else\n    x\n\n/--\n  Creating a mapping containing `b \u21a6 e'` where `patternWithRef e' = some (stx, b)`,\n  and `e'` is a subterm of `e`.\n\n  This is a helper function for `whnfPreservingPatternRef`. -/\nprivate def mkPatternRefMap (e : Expr) : ExprMap Expr :=\n  runST go\nwhere\n  go (\u03c3) : ST \u03c3 (ExprMap Expr) := do\n   let map : ST.Ref \u03c3 (ExprMap Expr) \u2190 ST.mkRef {}\n   e.forEachWhere isPatternWithRef fun e => do\n     let some (_, b) := patternWithRef? e | unreachable!\n     map.modify (\u00b7.insert b e)\n   map.get\n\n/--\n  Try to restore `Syntax` ref information stored in `map` after\n  applying `whnf` at `whnfPreservingPatternRef`.\n  It assumes `map` has been constructed using `mkPatternRefMap`.\n-/\nprivate def applyRefMap (e : Expr) (map : ExprMap Expr) : Expr :=\n  e.replace fun e =>\n    match patternWithRef? e with\n    | some _ => some e -- stop `e` already has annotation\n    | none => match map.find? e with\n      | some eWithRef => some eWithRef -- stop `e` found annotation\n      | none => none -- continue\n\n/--\n  Applies `whnf` but tries to preserve `PatternWithRef` information.\n  This is a bit hackish, but it is necessary for providing proper\n  jump-to-definition information in examples such as\n  ```\n  def f (x : Nat) : Nat :=\n    match x with\n    | 0 => 1\n    | y + 1 => y\n  ```\n  Without this trick, the `PatternWithRef` is lost for the `y` at the pattern `y+1`.\n-/\nprivate def whnfPreservingPatternRef (e : Expr) : MetaM Expr := do\n  let eNew \u2190 whnf e\n  if eNew.isConstructorApp (\u2190 getEnv) then\n    return eNew\n  else\n    return applyRefMap eNew (mkPatternRefMap e)\n\n/--\n  Normalize the pattern and collect all patterns variables (explicit and implicit).\n  This method is the one that decides where the inaccessible annotations must be inserted.\n  The pattern variables are both free variables (for explicit pattern variables) and metavariables (for implicit ones).\n  Recall that `mkLambdaFVars` now allows us to abstract both free variables and metavariables.\n-/\npartial def normalize (e : Expr) : M Expr := do\n  match inaccessible? e with\n  | some e => processInaccessible e\n  | none =>\n  match patternWithRef? e with\n  | some (ref, e) => return mkPatternWithRef (\u2190 normalize e) ref\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) => mkArrayLit \u03b1 (\u2190 lits.mapM normalize)\n    | none =>\n      if let some e := Match.isNamedPattern? e then\n        let x := e.getArg! 1\n        let p := e.getArg! 2\n        let h := e.getArg! 3\n        unless x.consumeMData.isFVar && h.consumeMData.isFVar do\n          throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n        addVar x\n        let p \u2190 normalize p\n        addVar h\n        return mkApp4 e.getAppFn (e.getArg! 0) x p h\n      else if isMatchValue e then\n        return e\n      else if e.isFVar then\n        if (\u2190 isExplicitPatternVar e) then\n          processVar e\n        else\n          return mkInaccessible e\n      else if e.getAppFn.isMVar then\n        let eNew \u2190 instantiateMVars e\n        if eNew != e then\n          withMVar e.getAppFn.mvarId! <| normalize eNew\n        else if e.isMVar then\n          withMVar e.mvarId! <| processVar e\n        else\n          throwInvalidPattern e\n      else\n        let eNew \u2190 whnfPreservingPatternRef e\n        if eNew != e then\n          normalize eNew\n        else\n          matchConstCtor e.getAppFn\n            (fun _ => return mkInaccessible (\u2190 eraseInaccessibleAnnotations (\u2190 instantiateMVars e)))\n            (fun v _ => do\n              let args := e.getAppArgs\n              unless args.size == v.numParams + v.numFields do\n                throwInvalidPattern e\n              let params := args.extract 0 v.numParams\n              let params \u2190 params.mapM fun p => instantiateMVars p\n              let fields := args.extract v.numParams args.size\n              let fields \u2190 fields.mapM normalize\n              return mkAppN e.getAppFn (params ++ fields))\nwhere\n  addVar (e : Expr) : M Unit := do\n    let e \u2190 erasePatternRefAnnotations e\n    unless (\u2190 get).patternVars.contains e do\n      modify fun s => { s with patternVars := s.patternVars.push e }\n\n  processVar (e : Expr) : M Expr := do\n    let e' \u2190 erasePatternRefAnnotations e\n    if (\u2190 get).patternVars.contains e' then\n      return mkInaccessible (\u2190 eraseInaccessibleAnnotations e)\n    else\n      if e'.isMVar then\n        e'.mvarId!.setTag (\u2190 read).userName\n      modify fun s => { s with patternVars := s.patternVars.push e' }\n      return e\n\n  processInaccessible (e : Expr) : M Expr := do\n    let e' \u2190 erasePatternRefAnnotations e\n    match e' with\n    | Expr.fvar _ =>\n      if (\u2190 isExplicitPatternVar e') then\n        processVar e\n      else\n        return mkInaccessible e\n    | _ =>\n      if e'.getAppFn.isMVar then\n        let eNew \u2190 instantiateMVars e'\n        if eNew != e' then\n          withMVar e'.getAppFn.mvarId! <| processInaccessible eNew\n        else if e'.isMVar then\n          withMVar e'.mvarId! <| processVar e'\n        else\n          throwInvalidPattern e\n      else\n        return mkInaccessible (\u2190 eraseInaccessibleAnnotations (\u2190 instantiateMVars e))\n\n/--\n  Auxiliary function for combining the `matchType` and all patterns into a single expression.\n  We use it before we abstract all patterns variables. -/\nprivate partial def packMatchTypePatterns (matchType : Expr) (ps : Array Expr) : MetaM Expr :=\n  ps.foldlM (init := matchType) fun result p => mkAppM ``PProd.mk #[result, p]\n\n/-- The inverse of `packMatchTypePatterns`. -/\nprivate partial def unpackMatchTypePatterns (p : Expr) : Expr \u00d7 Array Expr :=\n  if p.isAppOf ``PProd.mk then\n    let (matchType, ps) := unpackMatchTypePatterns (p.getArg! 2)\n    (matchType, ps.push (p.getArg! 3))\n  else\n    (p, #[])\n\n/--\n  Convert a (normalized) pattern encoded as an `Expr` into a `Pattern`.\n  This method assumes that `e` has been normalized and the explicit and implicit (i.e., metavariables) pattern variables have\n  already been abstracted and converted back into new free variables.\n -/\nprivate partial def toPattern (e : Expr) : MetaM Pattern := do\n  match inaccessible? e with\n  | some e => return Pattern.inaccessible e\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) => return Pattern.arrayLit \u03b1 (\u2190 lits.mapM toPattern)\n    | none =>\n      if let some e := Match.isNamedPattern? e then\n        let p \u2190 toPattern <| e.getArg! 2\n        match e.getArg! 1, e.getArg! 3 with\n        | Expr.fvar x, Expr.fvar h => return Pattern.as x p h\n        | _,           _           => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if isMatchValue e then\n        return Pattern.val e\n      else if e.isFVar then\n        return Pattern.var e.fvarId!\n      else\n        matchConstCtor e.getAppFn (fun _ => unreachable!) fun v us => do\n          let args := e.getAppArgs\n          let params := args.extract 0 v.numParams\n          let params \u2190 params.mapM fun p => instantiateMVars p\n          let fields := args.extract v.numParams args.size\n          let fields \u2190 fields.mapM toPattern\n          return Pattern.ctor v.name us params.toList fields.toList\n\nstructure TopSort.State where\n  visitedFVars : FVarIdSet := {}\n  visitedMVars : MVarIdSet := {}\n  result       : Array Expr := #[]\n\nabbrev TopSortM := StateRefT TopSort.State TermElabM\n\n/--\n  Topological sort. We need it because inaccessible patterns may contain pattern variables that are declared later.\n  That is, processing patterns from left to right to do not guarantee that the pattern variables are collected in the\n  \"right\" order. \"Right\" here means pattern `x` must occur befor pattern `y` if `y`s type depends on `x`.\n-/\nprivate partial def topSort (patternVars : Array Expr) : TermElabM (Array Expr) := do\n  let (_, s) \u2190 patternVars.mapM visit |>.run {}\n  return s.result\nwhere\n  visit (e : Expr) : TopSortM Unit := do\n    match e with\n    | Expr.proj _ _ e      => visit e\n    | Expr.forallE _ d b _ => visit d; visit b\n    | Expr.lam _ d b _     => visit d; visit b\n    | Expr.letE _ t v b _  => visit t; visit v; visit b\n    | Expr.app f a         => visit f; visit a\n    | Expr.mdata _ b       => visit b\n    | Expr.mvar mvarId     =>\n      let v \u2190 instantiateMVars e\n      if !v.isMVar then\n        visit v\n      else if patternVars.contains e then\n        unless (\u2190 get).visitedMVars.contains mvarId do\n          modify fun s => { s with visitedMVars := s.visitedMVars.insert mvarId }\n          let mvarDecl \u2190 getMVarDecl mvarId\n          visit mvarDecl.type\n          modify fun s => { s with result := s.result.push e }\n    | Expr.fvar fvarId    =>\n      if patternVars.contains e then\n        unless (\u2190 get).visitedFVars.contains fvarId do\n          modify fun s => { s with visitedFVars := s.visitedFVars.insert fvarId }\n          visit (\u2190 fvarId.getType)\n          modify fun s => { s with result := s.result.push e }\n    | _ => return ()\n\n/--\n  Save pattern information in the info tree, and remove `patternWithRef?` annotations.\n-/\npartial def savePatternInfo (p : Expr) : TermElabM Expr :=\n  go p |>.run false\nwhere\n  /-- The `Bool` context is true iff we are inside of an \"inaccessible\" pattern. -/\n  go (p : Expr) : ReaderT Bool TermElabM Expr := do\n    match p with\n    | .forallE n d b bi  => withLocalDecl n bi (\u2190 go d) fun x => do mkForallFVars #[x] (\u2190 go (b.instantiate1 x))\n    | .lam n d b bi      => withLocalDecl n bi (\u2190 go d) fun x => do mkLambdaFVars #[x] (\u2190 go (b.instantiate1 x))\n    | .letE n t v b ..  => withLetDecl n (\u2190 go t) (\u2190 go v) fun x => do mkLetFVars #[x] (\u2190 go (b.instantiate1 x))\n    | .app f a          => return mkApp (\u2190 go f) (\u2190 go a)\n    | .proj _ _ b       => return p.updateProj! (\u2190 go b)\n    | .mdata k b        =>\n      if inaccessible? p |>.isSome then\n        return mkMData k (\u2190 withReader (fun _ => false) (go b))\n      else if let some (stx, p) := patternWithRef? p then\n        Elab.withInfoContext' (go p) fun p => do\n          /- If `p` is a free variable and we are not inside of an \"inaccessible\" pattern, this `p` is a binder. -/\n          mkTermInfo Name.anonymous stx p (isBinder := p.isFVar && !(\u2190 read))\n      else\n        return mkMData k (\u2190 go b)\n    | _ => return p\n\n/--\n  Main method for `withDepElimPatterns`.\n  - `PatternVarDecls`: are the explicit pattern variables provided by the user.\n  - `ps`: are the patterns provided by the user.\n  - `matchType`: the expected typ for this branch. It depends on the explicit pattern variables and the implicit ones that are still represented as metavariables,\n     and are found by this function.\n  - `k` is the continuation that is executed in an updated local context with the all pattern variables (explicit and implicit). Note that, `patternVarDecls` are all\n     replaced since they may depend on implicit pattern variables (i.e., metavariables) that are converted into new free variables by this method.\n -/\npartial def main (patternVarDecls : Array PatternVarDecl) (ps : Array Expr) (matchType : Expr) (k : Array LocalDecl \u2192 Array Pattern \u2192 Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let explicitPatternVars := patternVarDecls.map fun decl => decl.fvarId\n  let (ps, s) \u2190 ps.mapM normalize |>.run { explicitPatternVars } |>.run {}\n  let patternVars \u2190 topSort s.patternVars\n  trace[Elab.match] \"patternVars after topSort: {patternVars}\"\n  for explicit in explicitPatternVars do\n    unless patternVars.any (\u00b7 == mkFVar explicit) do\n      withInPattern do\n        throwError \"invalid patterns, `{mkFVar explicit}` is an explicit pattern variable, but it only occurs in positions that are inaccessible to pattern matching{indentD (MessageData.joinSep (ps.toList.map (MessageData.ofExpr .)) m!\"\\n\\n\")}\"\n  let packed \u2190 pack patternVars ps matchType\n  trace[Elab.match] \"packed: {packed}\"\n  let lctx := explicitPatternVars.foldl (init := (\u2190 getLCtx)) fun lctx d => lctx.erase d\n  withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do\n    check packed\n    unpack packed fun patternVars patterns matchType => do\n      let localDecls \u2190 patternVars.mapM fun x => x.fvarId!.getDecl\n      trace[Elab.match] \"patternVars: {patternVars}, matchType: {matchType}\"\n      k localDecls (\u2190 patterns.mapM fun p => toPattern p) matchType\nwhere\n  pack (patternVars : Array Expr) (ps : Array Expr) (matchType : Expr) : MetaM Expr := do\n    /-\n     Recall that some of the `patternVars` are metavariables without a user facing name.\n     Thus, this method tries to infer names for them using `ps` before performing the `mkLambdaFVars` abstraction.\n     Let `?m` be a metavariable in `patternVars` without a user facing name.\n     The heuristic uses the patterns `ps`. We traverse the patterns from right to left searching for applications\n     `f ... ?m`. The name for the corresponding `f`-parameter is used to name `?m`.\n     We search from right to left to make sure we visit a pattern before visiting its indices. Example:\n     ```\n     #[@List.cons \u03b1 i ?m, @HList.cons \u03b1 \u03b2 i ?m a as, @Member.head \u03b1 i ?m]\n     ```\n    -/\n    let setMVarsAt (e : Expr) : StateRefT (Array MVarId) MetaM Unit := do\n      let mvarIds \u2190 setMVarUserNamesAt (\u2190 erasePatternRefAnnotations e) patternVars\n      modify (\u00b7 ++ mvarIds)\n    let go : StateRefT (Array MVarId) MetaM Expr := do\n      try\n        for p in ps.reverse do\n          setMVarsAt p\n        mkLambdaFVars patternVars (\u2190 packMatchTypePatterns matchType ps) (binderInfoForMVars := BinderInfo.default)\n      finally\n        resetMVarUserNames (\u2190 get)\n    go |>.run' #[]\n\n  unpack (packed : Expr) (k : (patternVars : Array Expr) \u2192 (patterns : Array Expr) \u2192 (matchType : Expr) \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n    let rec go (packed : Expr) (patternVars : Array Expr) : TermElabM \u03b1 := do\n      match packed with\n      | .lam n d b _ =>\n        withLocalDeclD n (\u2190 erasePatternRefAnnotations (\u2190 eraseInaccessibleAnnotations d)) fun patternVar =>\n          go (b.instantiate1 patternVar) (patternVars.push patternVar)\n      | _ =>\n        let (matchType, patterns) := unpackMatchTypePatterns packed\n        let matchType \u2190 erasePatternRefAnnotations (\u2190 eraseInaccessibleAnnotations matchType)\n        let patterns \u2190 patterns.mapM (savePatternInfo \u00b7)\n        k patternVars patterns matchType\n    go packed #[]\n\nend ToDepElimPattern\n\ndef withDepElimPatterns (patternVarDecls : Array PatternVarDecl) (ps : Array Expr) (matchType : Expr) (k : Array LocalDecl \u2192 Array Pattern \u2192 Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  ToDepElimPattern.main patternVarDecls ps matchType k\n\nprivate def withElaboratedLHS {\u03b1} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)\n    (k : AltLHS \u2192 Expr \u2192 TermElabM \u03b1) : ExceptT PatternElabException TermElabM \u03b1 := do\n  let (patterns, matchType) \u2190 withSynthesize <| elabPatterns patternStxs matchType\n  id (\u03b1 := TermElabM \u03b1) do\n    trace[Elab.match] \"patterns: {patterns}\"\n    withDepElimPatterns patternVarDecls patterns matchType fun localDecls patterns matchType => do\n      k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType\n\n/--\n  Try to clear the free variables in `toClear` and auxiliary discriminants, and then execute `k` in the updated local context.\n  If `type` or another local variables depends on a free variable in `toClear`, then it is not cleared.\n-/\nprivate def withToClear (toClear : Array FVarId) (type : Expr) (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  if toClear.isEmpty then\n    k\n  else\n    let toClear \u2190 sortFVarIds toClear\n    trace[Elab.match] \">> toClear {toClear.map mkFVar}\"\n    let mut lctx \u2190 getLCtx\n    let mut localInsts \u2190 getLocalInstances\n    for fvarId in toClear.reverse do\n      if !(\u2190 dependsOn type fvarId) then\n        if !(\u2190 lctx.anyM fun localDecl => pure (localDecl.fvarId != fvarId) <&&> localDeclDependsOn localDecl fvarId) then\n          lctx := lctx.erase fvarId\n          localInsts := localInsts.filter fun localInst => localInst.fvar.fvarId! != fvarId\n    withLCtx lctx localInsts k\n\n/--\n  Generate equalities `h : discr = pattern` for discriminants annotated with `h :`.\n  We use these equalities to elaborate the right-hand-side of a `match` alternative.\n-/\nprivate def withEqs (discrs : Array Discr) (patterns : List Pattern) (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  go 0 patterns #[]\nwhere\n  go (i : Nat) (ps : List Pattern) (eqs : Array Expr) : TermElabM \u03b1 := do\n    match ps with\n    | [] => k eqs\n    | p::ps =>\n      if h : i < discrs.size then\n        let discr := discrs.get \u27e8i, h\u27e9\n        if let some h := discr.h? then\n          withLocalDeclD h.getId (\u2190 mkEqHEq discr.expr (\u2190 p.toExpr)) fun eq => do\n            addTermInfo' h eq (isBinder := true)\n            go (i+1) ps (eqs.push eq)\n        else\n          go (i+1) ps eqs\n      else\n        k eqs\n\n/--\n  Elaborate the `match` alternative `alt` using the given `matchType`.\n  The array `toClear` contains variables that must be cleared before elaborating the `rhs` because\n  they have been generalized/refined.\n-/\nprivate def elabMatchAltView (discrs : Array Discr) (alt : MatchAltView) (matchType : Expr) (toClear : Array FVarId) : ExceptT PatternElabException TermElabM (AltLHS \u00d7 Expr) := withRef alt.ref do\n    let (patternVars, alt) \u2190 collectPatternVars alt\n    trace[Elab.match] \"patternVars: {patternVars}\"\n    withPatternVars patternVars fun patternVarDecls => do\n      withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType =>\n        withEqs discrs altLHS.patterns fun eqs =>\n          withLocalInstances altLHS.fvarDecls do\n            trace[Elab.match] \"elabMatchAltView: {matchType}\"\n            -- connect match-generalized pattern fvars, which are a suffix of `latLHS.fvarDecls`,\n            -- to their original fvars (independently of whether they were cleared successfully) in the info tree\n            for (fvar, baseId) in altLHS.fvarDecls.toArray.reverse.zip toClear.reverse do\n              pushInfoLeaf <| .ofFVarAliasInfo { id := fvar.fvarId, baseId, userName := fvar.userName }\n            let matchType \u2190 instantiateMVars matchType\n            -- If `matchType` is of the form `@m ...`, we create a new metavariable with the current scope.\n            -- This improves the effectiveness of the `isDefEq` default approximations\n            let matchType' \u2190 if matchType.getAppFn.isMVar then mkFreshTypeMVar else pure matchType\n            withToClear toClear matchType' do\n              let rhs \u2190 elabTermEnsuringType alt.rhs matchType'\n              -- We use all approximations to ensure the auxiliary type is defeq to the original one.\n              unless (\u2190 fullApproxDefEq <| isDefEq matchType' matchType) do\n                throwError \"type mistmatch, alternative {\u2190 mkHasTypeButIsExpectedMsg matchType' matchType}\"\n              let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr ++ eqs\n              let rhs \u2190 if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs\n              trace[Elab.match] \"rhs: {rhs}\"\n              return (altLHS, rhs)\n\n/--\n  Collect problematic index for the \"discriminant refinement feature\". This method is invoked\n  when we detect a type mismatch at a pattern #`idx` of some alternative. -/\nprivate partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do\n  go (\u2190 inferType discr) pathToIndex |>.run\nwhere\n  go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do\n    match path with\n    | [] => return e\n    | i::path =>\n      let e \u2190 whnfD e\n      guard <| e.isApp && i < e.getAppNumArgs\n      go (e.getArg! i) path\n\nstructure GeneralizeResult where\n  discrs    : Array Discr\n  /-- `FVarId`s of the variables that have been generalized. We store them to clear after in each branch. -/\n  toClear   : Array FVarId := #[]\n  matchType : Expr\n  altViews  : Array MatchAltView\n  refined   : Bool := false\n\n/--\n  \"Generalize\" variables that depend on the discriminants.\n\n  Remarks and limitations:\n  - We currently do not generalize let-decls.\n  - We abort generalization if the new `matchType` is type incorrect.\n  - Only discriminants that are free variables are considered during specialization.\n  - We \"generalize\" by adding new discriminants and pattern variables. We do not \"clear\" the generalized variables,\n    but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since\n    this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode.\n-/\nprivate def generalize (discrs : Array Discr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM GeneralizeResult := do\n  let gen := if let some g := generalizing? then g else true\n  if !gen then\n    return { discrs, matchType, altViews }\n  else\n    let discrExprs := discrs.map (\u00b7.expr)\n    /- let-decls are currently being ignored by the generalizer. -/\n    let ysFVarIds \u2190 getFVarsToGeneralize discrExprs (ignoreLetDecls := true)\n    if ysFVarIds.isEmpty then\n      return { discrs, matchType, altViews }\n    else\n      let ys := ysFVarIds.map mkFVar\n      let matchType' \u2190 forallBoundedTelescope matchType discrs.size fun ds type => do\n        let type \u2190 mkForallFVars ys type\n        let (discrs', ds') := Array.unzip <| Array.zip discrExprs ds |>.filter fun (di, _) => di.isFVar\n        let type := type.replaceFVars discrs' ds'\n        mkForallFVars ds type\n      if (\u2190 isTypeCorrect matchType') then\n        let discrs := discrs ++  ys.map fun y => { expr := y : Discr }\n        let altViews \u2190 altViews.mapM fun altView => do\n          let patternVars \u2190 getPatternsVars altView.patterns\n          -- We traverse backwards because we want to keep the most recent names.\n          -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`,\n          -- since it is already shadowed by the second.\n          let ysUserNames \u2190 ys.foldrM (init := #[]) fun ys ysUserNames => do\n            let yDecl \u2190 ys.fvarId!.getDecl\n            let mut yUserName := yDecl.userName\n            if ysUserNames.contains yUserName then\n              yUserName \u2190 mkFreshUserName yUserName\n            -- Explicitly provided pattern variables shadow `y`\n            else if patternVars.any fun x => x.getId == yUserName then\n              yUserName \u2190 mkFreshUserName yUserName\n            return ysUserNames.push yUserName\n          let ysIds \u2190 ysUserNames.reverse.mapM fun n => return mkIdentFrom (\u2190 getRef) n\n          return { altView with patterns := altView.patterns ++ ysIds }\n        return { discrs, toClear := ysFVarIds, matchType := matchType', altViews, refined := true }\n      else\n        return { discrs, matchType, altViews }\n\n\nprivate partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Discr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Discr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n  loop discrs #[] matchType altViews none\nwhere\n  /--\n    \"Discriminant refinement\" main loop.\n    `first?` contains the first error message we found before updated the `discrs`. -/\n  loop (discrs : Array Discr) (toClear : Array FVarId) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState \u00d7 Exception))\n      : TermElabM (Array Discr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n    let s \u2190 saveState\n    let { discrs := discrs', toClear := toClear', matchType := matchType', altViews := altViews', refined } \u2190 generalize discrs matchType altViews generalizing?\n    match (\u2190 altViews'.mapM (fun altView => elabMatchAltView discrs' altView matchType' (toClear ++ toClear')) |>.run) with\n    | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined)\n    | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } =>\n      let discr := discrs[patternIdx]!\n      let some index \u2190 getIndexToInclude? discr.expr pathToIndex\n        | throwEx (\u2190 updateFirst first? ex)\n      trace[Elab.match] \"index to include: {index}\"\n      if (\u2190 discrs.anyM fun discr => isDefEq discr.expr index) then\n        throwEx (\u2190 updateFirst first? ex)\n      let first \u2190 updateFirst first? ex\n      s.restore (restoreInfo := true)\n      let indices \u2190 collectDeps #[index] (discrs.map (\u00b7.expr))\n      let matchType \u2190 try\n        updateMatchType indices matchType\n      catch _ => throwEx first\n      let ref \u2190 getRef\n      trace[Elab.match] \"new indices to add as discriminants: {indices}\"\n      let wildcards \u2190 indices.mapM fun index => do\n        if index.isFVar then\n          let localDecl \u2190 index.fvarId!.getDecl\n          if localDecl.userName.hasMacroScopes then\n            return mkHole ref\n          else\n            let id := mkIdentFrom ref localDecl.userName\n            `(?$id)\n        else\n          return mkHole ref\n      let altViews  := altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns }\n      let indDiscrs \u2190 indices.mapM fun i => do\n        match discr.h? with\n        | none => return { expr := i : Discr }\n        | some h =>\n          -- If the discriminant that introduced this index is annotated with `h : discr`, then we should annotate the new discriminant too.\n          let h := mkIdentFrom h (\u2190 mkFreshUserName `h)\n          return { expr := i, h? := h : Discr }\n      let discrs    := indDiscrs ++ discrs\n      let indexFVarIds := indices.filterMap fun | .fvar fvarId .. => some fvarId | _  => none\n      loop discrs (toClear ++ indexFVarIds) matchType altViews first\n\n  throwEx {\u03b1} (p : SavedState \u00d7 Exception) : TermElabM \u03b1 := do\n    p.1.restore (restoreInfo := true); throw p.2\n\n  updateFirst (first? : Option (SavedState \u00d7 Exception)) (ex : Exception) : TermElabM (SavedState \u00d7 Exception) := do\n    match first? with\n    | none       => return (\u2190 saveState, ex)\n    | some first => return first\n\n  containsFVar (es : Array Expr) (fvarId : FVarId) : Bool :=\n    es.any fun e => e.isFVar && e.fvarId! == fvarId\n\n  /-- Update `indices` by including any free variable `x` s.t.\n     - Type of some `discr` depends on `x`.\n     - Type of `x` depends on some free variable in `indices`.\n\n     If we don't include these extra variables in indices, then\n     `updateMatchType` will generate a type incorrect term.\n     For example, suppose `discr` contains `h : @HEq \u03b1 a \u03b1 b`, and\n     `indices` is `#[\u03b1, b]`, and `matchType` is `@HEq \u03b1 a \u03b1 b \u2192 B`.\n     `updateMatchType indices matchType` produces the type\n     `(\u03b1' : Type) \u2192 (b : \u03b1') \u2192 @HEq \u03b1' a \u03b1' b \u2192 B` which is type incorrect\n     because we have `a : \u03b1`.\n     The method `collectDeps` will include `a` into `indices`.\n\n     This method does not handle dependencies among non-free variables.\n     We rely on the type checking method `check` at `updateMatchType`.\n\n     Remark: `indices : Array Expr` does not need to be an array anymore.\n     We should cleanup this code, and use `index : Expr` instead.\n   -/\n  collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do\n    let mut s : CollectFVars.State := {}\n    for discr in discrs do\n      s := collectFVars s (\u2190 instantiateMVars (\u2190 inferType discr))\n    let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar\n    let indicesFVar := indicesFVar.map Expr.fvarId!\n    let mut toAdd := #[]\n    for fvarId in s.fvarSet.toList do\n      unless containsFVar discrs fvarId || containsFVar indices fvarId do\n        let localDecl \u2190 fvarId.getDecl\n        for indexFVarId in indicesFVar do\n          if (\u2190 localDeclDependsOn localDecl indexFVarId) then\n            toAdd := toAdd.push fvarId\n    let indicesFVar \u2190 sortFVarIds (indicesFVar ++ toAdd)\n    return indicesFVar.map mkFVar ++ indicesNonFVar\n\n  updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do\n    let matchType \u2190 indices.foldrM (init := matchType) fun index matchType => do\n      let indexType \u2190 inferType index\n      let matchTypeBody \u2190 kabstract matchType index\n      let userName \u2190 mkUserNameFor index\n      return Lean.mkForall userName BinderInfo.default indexType matchTypeBody\n    check matchType\n    return matchType\n\n\ndef mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult :=\n  Meta.Match.mkMatcher input\n\nregister_builtin_option match.ignoreUnusedAlts : Bool := {\n  defValue := false\n  descr := \"if true, do not generate error if an alternative is not used\"\n}\n\ndef reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do\n  unless result.counterExamples.isEmpty do\n    withHeadRefOnly <| logError m!\"missing cases:\\n{Meta.Match.counterExamplesToMessageData result.counterExamples}\"\n    return ()\n  unless match.ignoreUnusedAlts.get (\u2190 getOptions) || result.unusedAltIdxs.isEmpty do\n    let mut i := 0\n    for alt in altLHSS do\n      if result.unusedAltIdxs.contains i then\n        withRef alt.ref do\n          logError \"redundant alternative\"\n      i := i + 1\n\n/--\n  If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]`\n  Otherwise, return none.\n-/\nprivate def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do\n  assert! altLHSS.length == rhss.size\n  match altLHSS with\n  | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] =>\n    /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/\n    match rhss[0]! with\n    | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b\n    | _ => return none\n  | _ => return none\n\nprivate def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptMotive : Syntax) (expectedType : Expr)\n    : TermElabM Expr := do\n  let mut generalizing? := generalizing?\n  if !matchOptMotive.isNone then\n    if generalizing? == some true then\n      throwError \"the '(generalizing := true)' parameter is not supported when the 'match' motive is explicitly provided\"\n    generalizing? := some false\n  let (discrs, matchType, altLHSS, isDep, rhss) \u2190 commitIfDidNotPostpone do\n    let \u27e8discrs, matchType, isDep, altViews\u27e9 \u2190 elabMatchTypeAndDiscrs discrStxs matchOptMotive altViews expectedType\n    let matchAlts \u2190 liftMacroM <| expandMacrosInPatterns altViews\n    trace[Elab.match] \"matchType: {matchType}\"\n    let (discrs, matchType, alts, refined) \u2190 elabMatchAltViews generalizing? discrs matchType matchAlts\n    let isDep := isDep || refined\n    /-\n     We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be\n     able to elaborate examples such as:\n     ```\n     def f (x : Nat) : Option Nat := none\n\n     def g (xs : List (Nat \u00d7 Nat)) : IO Unit :=\n     xs.forM fun x =>\n       match f x.fst with\n       | _ => pure ()\n     ```\n     If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because\n     the type of `x` is only available after we proces the last argument of `List.forM`.\n\n     We apply pending default types to make sure we can process examples such as\n     ```\n     let (a, b) := (0, 0)\n     ```\n    -/\n    synthesizeSyntheticMVarsUsingDefault\n    let rhss := alts.map Prod.snd\n    let matchType \u2190 instantiateMVars matchType\n    let altLHSS \u2190 alts.toList.mapM fun alt => do\n      let altLHS \u2190 Match.instantiateAltLHSMVars alt.1\n      /- Remark: we try to postpone before throwing an error.\n         The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed.\n         The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here.\n         Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here.\n         ```\n          def bad (ps : Array (Nat \u00d7 Nat)) : Array (Nat \u00d7 Nat) :=\n            (ps.filter fun (p : Prod _ _) =>\n              match p with\n              | (x, y) => x == 0)\n            ++\n            ps\n         ```\n         When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet\n         because `Array.filter` has type `{\u03b1 : Type u_1} \u2192 (\u03b1 \u2192 Bool) \u2192 (as : Array \u03b1) \u2192 optParam Nat 0 \u2192 optParam Nat (Array.size as) \u2192 Array \u03b1`\n         However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`.\n      -/\n      withRef altLHS.ref do\n        for d in altLHS.fvarDecls do\n          if d.hasExprMVar then\n            tryPostpone\n            withExistingLocalDecls altLHS.fvarDecls do\n              runPendingTacticsAt d.type\n              if (\u2190 instantiateMVars d.type).hasExprMVar then\n                throwMVarError m!\"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}\"\n        for p in altLHS.patterns do\n          if (\u2190 Match.instantiatePatternMVars p).hasExprMVar then\n            tryPostpone\n            withExistingLocalDecls altLHS.fvarDecls do\n              throwMVarError m!\"invalid match-expression, pattern contains metavariables{indentExpr (\u2190 p.toExpr)}\"\n        pure altLHS\n    return (discrs, matchType, altLHSS, isDep, rhss)\n  if let some r \u2190 if isDep then pure none else isMatchUnit? altLHSS rhss then\n    return r\n  else\n    let numDiscrs := discrs.size\n    let matcherName \u2190 mkAuxName `match\n    let matcherResult \u2190 mkMatcher { matcherName, matchType, discrInfos := discrs.map fun discr => { hName? := discr.h?.map (\u00b7.getId) }, lhss := altLHSS }\n    reportMatcherResultErrors altLHSS matcherResult\n    matcherResult.addMatcher\n    let motive \u2190 forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType\n    let r := mkApp matcherResult.matcher motive\n    let r := mkAppN r (discrs.map (\u00b7.expr))\n    let r := mkAppN r rhss\n    trace[Elab.match] \"result: {r}\"\n    return r\n\n-- leading_parser \"match \" >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr \", \" >> \" with \" >> ppDedent matchAlts\n\nprivate def getDiscrs (matchStx : Syntax) : Array Syntax :=\n  matchStx[3].getSepArgs\n\nprivate def getMatchOptMotive (matchStx : Syntax) : Syntax :=\n  matchStx[2]\n\nopen TSyntax.Compat in\nprivate def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=\n  let matchOptMotive := getMatchOptMotive matchStx\n  if matchOptMotive.isNone then do\n    let discrs := getDiscrs matchStx\n    let allLocal \u2190 discrs.allM fun discr => isAtomicDiscr discr[1]\n    if allLocal then\n      return none\n    else\n      let rec loop (discrs : List Syntax) (discrsNew : Array Syntax)  := do\n        match discrs with\n        | [] =>\n          let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx \", \")\n          pure (matchStx.setArg 3 discrs)\n        | discr :: discrs =>\n          -- Recall that\n          -- matchDiscr := leading_parser optional (ident >> \":\") >> termParser\n          let term := discr[1]\n          if (\u2190 isAtomicDiscr term) then\n            loop discrs (discrsNew.push discr)\n          else\n            withFreshMacroScope do\n              let discrNew := discr.setArg 1 (\u2190 `(?x))\n              let r \u2190 loop discrs (discrsNew.push discrNew)\n              `(let_mvar% ?x := $term; $r)\n      return some (\u2190 loop discrs.toList #[])\n  else\n    -- We do not pull non atomic discriminants when match type is provided explicitly by the user\n    return none\n\nprivate def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  match expectedType? with\n    | some expectedType => pure expectedType\n    | none              => mkFreshTypeMVar\n\nprivate def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do\n  -- We don't wait for the discriminants types when match type is provided by user\n  if getMatchOptMotive matchStx |>.isNone then\n    let discrs := getDiscrs matchStx\n    for discr in discrs do\n      let term := discr[1]\n      let d \u2190 elabTerm term none\n      let dType \u2190 inferType d\n      trace[Elab.match] \"discr {d} : {\u2190 instantiateMVars dType}\"\n      tryPostponeIfMVar dType\n\n/--\nWe (try to) elaborate a `match` only when the expected type is available.\nIf the `matchType` has not been provided by the user, we also try to postpone elaboration if the type\nof a discriminant is not available. That is, it is of the form `(?m ...)`.\nWe use `expandNonAtomicDiscrs?` to make sure all discriminants are metavariables,\nso that they are not elaborated twice.\nThis is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.\nSuppose, we are trying to elaborate\n```\nmatch g x with\n  | ... => ...\n```\n`expandNonAtomicDiscrs?` converts it intro\n```\nlet_mvar% ?discr := g x\nmatch ?discr with\n  | ... => ...\n```\n\nThis elaboration technique is needed to elaborate terms such as:\n```lean\nxs.filter fun (a, b) => a > b\n```\nwhich are syntax sugar for\n```lean\nList.filter (fun p => match p with | (a, b) => a > b) xs\n```\nWhen we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.\n-/\nprivate def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  tryPostponeIfDiscrTypeIsMVar matchStx\n  match expectedType? with\n  | some expectedType => return expectedType\n  | none              => mkFreshTypeMVar\n\n/--\n```\nleading_parser \"match \" >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr \", \" >> \" with \" >> ppDedent matchAlts\n```\nRemark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.\n-/\nprivate def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType   \u2190 waitExpectedTypeAndDiscrs stx expectedType?\n  let discrStxs      := (getDiscrs stx).map fun d => d\n  let gen?           := getMatchGeneralizing? stx\n  let altViews       := getMatchAlts stx\n  let matchOptMotive := getMatchOptMotive stx\n  elabMatchAux gen? discrStxs altViews matchOptMotive expectedType\n\nprivate def isPatternVar (stx : Syntax) : TermElabM Bool := do\n  match (\u2190 resolveId? stx \"pattern\") with\n  | none   => return isAtomicIdent stx\n  | some f => match f with\n    | Expr.const fName _ =>\n      match (\u2190 getEnv).find? fName with\n      | some (ConstantInfo.ctorInfo _) => return false\n      | some _                         => return !hasMatchPatternAttribute (\u2190 getEnv) fName\n      | _                              => return isAtomicIdent stx\n    | _ => return isAtomicIdent stx\nwhere\n  isAtomicIdent (stx : Syntax) : Bool :=\n    stx.isIdent && stx.getId.eraseMacroScopes.isAtomic\n\n@[builtin_term_elab \u00abmatch\u00bb] def elabMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(match $discr:term with | $y:ident => $rhs) =>\n     if (\u2190 isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?\n  | _ => elabMatchDefault stx expectedType?\nwhere\n  elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n    match (\u2190 liftMacroM <| expandMatchAlts? stx) with\n    | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n    | none =>\n    match (\u2190 expandNonAtomicDiscrs? stx) with\n    | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n    | none =>\n      let discrs         := getDiscrs stx\n      let matchOptMotive := getMatchOptMotive stx\n      if !matchOptMotive.isNone && discrs.any fun d => !d[0].isNone then\n        throwErrorAt matchOptMotive \"match motive should not be provided when discriminants with equality proofs are used\"\n      elabMatchCore stx expectedType?\n\nbuiltin_initialize\n  registerTraceClass `Elab.match\n\n-- leading_parser:leadPrec \"nomatch \" >> termParser\n@[builtin_term_elab \u00abnomatch\u00bb] def elabNoMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(nomatch $discrExpr) =>\n    if (\u2190 isAtomicDiscr discrExpr) then\n      let expectedType \u2190 waitExpectedType expectedType?\n      let discr := mkNode ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]\n      elabMatchAux none #[discr] #[] mkNullNode expectedType\n    else\n      let stxNew \u2190 `(let_mvar% ?x := $discrExpr; nomatch ?x)\n      withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | _ => throwUnsupportedSyntax\n\nend Lean.Elab.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/Lean/Elab/Match.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733753118592733, "lm_q2_score": 0.03622005833579263, "lm_q1q2_score": 0.007871978058111437}}
{"text": "structure Foo where\n  foo : Nat\n\nexample (f : Foo) : f.\n                    --^ textDocument/completion\nexample (f : Foo) : f.f\n                     --^ textDocument/completion\nexample (f : Foo) : id f |>.\n                          --^ textDocument/completion\nexample (f : Foo) : id f |>.f\n                           --^ textDocument/completion\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/completion.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733751090819795, "lm_q2_score": 0.03622005651518997, "lm_q1q2_score": 0.007871976927965646}}
{"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.basic\nimport tactic.simpa\n\nsetup_tactic_parser\n\nprivate meta def loc.to_string_aux : option name \u2192 string\n| none := \"\u22a2\"\n| (some x) := to_string x\n\n/-- pretty print a `loc` -/\nmeta def loc.to_string : loc \u2192 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\n/-- shift `pos` `n` columns to the left -/\nmeta def pos.move_left (p : pos) (n : \u2115) : pos :=\n{ line := p.line, column := p.column - n }\n\nnamespace tactic\n\nattribute [derive decidable_eq] simp_arg_type\n\n/-- Turn a `simp_arg_type` into a string. -/\nmeta instance simp_arg_type.has_to_string : has_to_string simp_arg_type :=\n\u27e8\u03bb a, match a with\n| simp_arg_type.all_hyps := \"*\"\n| (simp_arg_type.except n) := \"-\" ++ to_string n\n| (simp_arg_type.expr e) := to_string e\n| (simp_arg_type.symm_expr e) := \"\u2190\" ++ to_string e\nend\u27e9\n\nopen list\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\nmeta def struct_inst : lean.parser pexpr :=\nwith_desc \"cfg\" $ do\n  tk \"{\",\n  ls \u2190 sep_by (skip_info (tk \",\"))\n    ( sum.inl <$> (tk \"..\" *> texpr) <|>\n      sum.inr <$> (prod.mk <$> ident <* tk \":=\" <*> texpr)),\n  tk \"}\",\n  let (srcs,fields) := partition_map id ls,\n  let (names,values) := unzip fields,\n  pure $ pexpr.mk_structure_instance\n    { field_names := names,\n      field_values := values,\n      sources := srcs }\n\n/-- pretty print structure instance -/\nmeta def struct.to_tactic_format (e : pexpr) : tactic format :=\ndo r \u2190 e.get_structure_instance_info,\n   fs \u2190 mzip_with (\u03bb n v,\n     do v \u2190 to_expr v >>= pp,\n        pure $ format!\"{n} := {v}\" )\n     r.field_names r.field_values,\n   let ss := r.sources.map (\u03bb s, format!\" .. {s}\"),\n   let x : format := format.join $ list.intersperse \", \" (fs ++ ss),\n   pure format!\" {{{x}}}\"\n\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n@[user_attribute]\nprivate meta def squeeze_loc_attr :\n  user_attribute unit (option (list (pos \u00d7 string \u00d7 list simp_arg_type \u00d7 string))) :=\n{ name := `_squeeze_loc,\n  parser := fail \"this attribute should not be used\",\n  descr := \"table to accumulate multiple `squeeze_simp` suggestions\" }\n\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeeze_loc_attr_carrier := ()\n\nrun_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt\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. -/\nmeta def render_simp_arg_list : list simp_arg_type \u2192 format\n| [] := \"\"\n| args := (++) \" \" $ to_line_wrap_format $ args.map to_string\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. -/\nmeta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type)\n  (at_pos := ff) : tactic unit :=\ndo xs \u2190 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       @scope_trace _ p.line p.column $\n         \u03bb _, _root_.trace sformat!\"{pre}{args}{post}\" (pure () : tactic unit)\n     else\n       trace sformat!\"{pre}{args}{post}\"\n   | some xs := do\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff\n   end\n\n/-- translate a `pexpr` into a `simp` configuration -/\nmeta def parse_config : option pexpr \u2192 tactic (simp_config_ext \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr simp_config_ext e\n             <*> struct.to_tactic_format cfg\n\n/-- translate a `pexpr` into a `dsimp` configuration -/\nmeta def parse_dsimp_config : option pexpr \u2192 tactic (dsimp_config \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr dsimp_config e\n             <*> struct.to_tactic_format cfg\n\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\nmeta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool :=\ndo s \u2190 get_proof_state_after tac,\n   pure $ some pr = s\n\n/--\nConsumes the first list of `simp` arguments, accumulating required arguments\non the second one and unnecessary arguments on the third one.\n-/\nprivate meta def filter_simp_set_aux\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (args : list simp_arg_type) (pr : proof_state) :\n  list simp_arg_type \u2192 list simp_arg_type \u2192\n  list simp_arg_type \u2192 tactic (list simp_arg_type \u00d7 list simp_arg_type)\n| [] ys ds := pure (ys, ds)\n| (x :: xs) ys ds :=\n  do b \u2190 same_result pr (tac tt (args ++ xs ++ ys)),\n     if b\n       then filter_simp_set_aux xs ys (ds.concat x)\n       else filter_simp_set_aux xs (ys.concat x) ds\n\ndeclare_trace squeeze.deleted\n\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-/\nmeta def filter_simp_set\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) :=\ndo some s \u2190 get_proof_state_after (tac ff (user_args ++ simp_args)),\n   (simp_args', _)  \u2190 filter_simp_set_aux tac user_args s simp_args [] [],\n   (user_args', ds) \u2190 filter_simp_set_aux tac simp_args' s user_args [] [],\n   when (is_trace_enabled_for `squeeze.deleted = tt \u2227 \u00ac ds.empty)\n     trace!\"deleting provided arguments {ds}\",\n   pure (user_args' ++ simp_args')\n\n/-- make a `simp_arg_type` that references the name given as an argument -/\nmeta def name.to_simp_args (n : name) : simp_arg_type :=\nsimp_arg_type.expr $ @expr.local_const ff n n (default) pexpr.mk_placeholder\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. -/\nmeta def prepend_root_if_needed (n : name) : tactic name :=\ndo x \u2190 resolve_name' n,\nreturn $ match x with\n| expr.macro _ _ := `_root_ ++ n\n| _ := n\nend\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-/\nmeta def squeeze_simp_core\n  (slow no_dflt : bool) (args : list simp_arg_type)\n  (tac : \u03a0 (no_dflt : bool) (args : list simp_arg_type), tactic unit)\n  (mk_suggestion : list simp_arg_type \u2192 tactic unit) : tactic unit :=\ndo v \u2190 target >>= mk_meta_var,\n   args \u2190 if slow then do\n     simp_set \u2190 attribute.get_instances `simp,\n     simp_set \u2190 simp_set.mfilter $ has_attribute' `_refl_lemma,\n     simp_set \u2190 simp_set.mmap $ resolve_name' >=> pure \u2218 simp_arg_type.expr,\n     pure $ args ++ simp_set\n   else pure args,\n   g \u2190 retrieve $ do\n   { g \u2190 main_goal,\n     tac no_dflt args,\n     instantiate_mvars g },\n   let vs := g.list_constant',\n   vs \u2190 vs.mfilter is_simp_lemma,\n   vs \u2190 vs.mmap strip_prefix,\n   vs \u2190 vs.mmap prepend_root_if_needed,\n   with_local_goals' [v] (filter_simp_set tac args $ vs.map name.to_simp_args)\n     >>= mk_suggestion,\n   tac no_dflt args\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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (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-/\nmeta def squeeze_scope (tac : itactic) : tactic unit :=\ndo none \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (),\n   squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff,\n   finally tac $ do\n     some xs \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail \"invalid state\",\n     let m := native.rb_lmap.of_list xs,\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff,\n     m.to_list.reverse.mmap' $ \u03bb \u27e8p,suggs\u27e9, do\n       { let \u27e8pre,_,post\u27e9 := suggs.head,\n         let suggs : list (list simp_arg_type) := suggs.map $ prod.fst \u2218 prod.snd,\n         mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () }\n\n/--\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-/\nmeta def squeeze_simp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\n/-- see `squeeze_simp` -/\nmeta def squeeze_simpa\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (tgt : parse (tk \"using\" *> texpr)?)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   tgt' \u2190 traverse (\u03bb t, do t \u2190 to_expr t >>= pp,\n                            pure format!\" using {t}\") tgt,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            tgt' := tgt'.get_or_else \"\" in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simpa{use_iota_eqn} only\"\n          sformat!\"{attrs}{tgt'}{c}\" args)\n\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 -/\nmeta def squeeze_dsimp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?)\n  (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_dsimp_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: dsimp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\nend interactive\nend tactic\n\nopen tactic.interactive\nadd_tactic_doc\n{ name       := \"squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope\",\n  category   := doc_category.tactic,\n  decl_names :=\n   [``squeeze_simp,\n    ``squeeze_dsimp,\n    ``squeeze_simpa,\n    ``squeeze_scope],\n  tags       := [\"simplification\", \"Try this\"],\n  inherit_description_from := ``squeeze_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/tactic/squeeze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189024594807, "lm_q2_score": 0.038466193671751685, "lm_q1q2_score": 0.007860254725452464}}
{"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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (a : \u03b1) (b : \u03b2) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : zip_with f (a :: l\u2081) (b :: l\u2082) = f a b :: zip_with f l\u2081 l\u2082 :=\n  rfl\n\n@[simp] theorem zip_cons_cons {\u03b1 : Type u} {\u03b2 : Type v} (a : \u03b1) (b : \u03b2) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : zip (a :: l\u2081) (b :: l\u2082) = (a, b) :: zip l\u2081 l\u2082 :=\n  rfl\n\n@[simp] theorem zip_with_nil_left {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l : List \u03b2) : zip_with f [] l = [] :=\n  rfl\n\n@[simp] theorem zip_with_nil_right {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l : List \u03b1) : zip_with f l [] = [] :=\n  list.cases_on l (Eq.refl (zip_with f [] [])) fun (l_hd : \u03b1) (l_tl : List \u03b1) => Eq.refl (zip_with f (l_hd :: l_tl) [])\n\n@[simp] theorem zip_nil_left {\u03b1 : Type u} {\u03b2 : Type v} (l : List \u03b1) : zip [] l = [] :=\n  rfl\n\n@[simp] theorem zip_nil_right {\u03b1 : Type u} {\u03b2 : Type v} (l : List \u03b1) : zip l [] = [] :=\n  zip_with_nil_right Prod.mk l\n\n@[simp] theorem zip_swap {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : map prod.swap (zip l\u2081 l\u2082) = zip l\u2082 l\u2081 := sorry\n\n@[simp] theorem length_zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : length (zip_with f l\u2081 l\u2082) = min (length l\u2081) (length l\u2082) := sorry\n\n@[simp] theorem length_zip {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : length (zip l\u2081 l\u2082) = min (length l\u2081) (length l\u2082) :=\n  length_zip_with Prod.mk\n\ntheorem lt_length_left_of_zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {i : \u2115} {l : List \u03b1} {l' : List \u03b2} (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 {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {i : \u2115} {l : List \u03b1} {l' : List \u03b2} (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 {\u03b1 : Type u} {\u03b2 : Type v} {i : \u2115} {l : List \u03b1} {l' : List \u03b2} (h : i < length (zip l l')) : i < length l :=\n  lt_length_left_of_zip_with h\n\ntheorem lt_length_right_of_zip {\u03b1 : Type u} {\u03b2 : Type v} {i : \u2115} {l : List \u03b1} {l' : List \u03b2} (h : i < length (zip l l')) : i < length l' :=\n  lt_length_right_of_zip_with h\n\ntheorem zip_append {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {r\u2081 : List \u03b1} {l\u2082 : List \u03b2} {r\u2082 : List \u03b2} (h : length l\u2081 = length l\u2082) : zip (l\u2081 ++ r\u2081) (l\u2082 ++ r\u2082) = zip l\u2081 l\u2082 ++ zip r\u2081 r\u2082 := sorry\n\ntheorem zip_map {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {\u03b4 : Type z} (f : \u03b1 \u2192 \u03b3) (g : \u03b2 \u2192 \u03b4) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : zip (map f l\u2081) (map g l\u2082) = map (prod.map f g) (zip l\u2081 l\u2082) := sorry\n\ntheorem zip_map_left {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b3) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : zip (map f l\u2081) l\u2082 = map (prod.map f id) (zip l\u2081 l\u2082) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (zip (map f l\u2081) l\u2082 = map (prod.map f id) (zip l\u2081 l\u2082))) (Eq.symm (zip_map f id l\u2081 l\u2082))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (zip (map f l\u2081) l\u2082 = zip (map f l\u2081) (map id l\u2082))) (map_id l\u2082)))\n      (Eq.refl (zip (map f l\u2081) l\u2082)))\n\ntheorem zip_map_right {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : zip l\u2081 (map f l\u2082) = map (prod.map id f) (zip l\u2081 l\u2082) :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (zip l\u2081 (map f l\u2082) = map (prod.map id f) (zip l\u2081 l\u2082))) (Eq.symm (zip_map id f l\u2081 l\u2082))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (zip l\u2081 (map f l\u2082) = zip (map id l\u2081) (map f l\u2082))) (map_id l\u2081)))\n      (Eq.refl (zip l\u2081 (map f l\u2082))))\n\ntheorem zip_map' {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} (f : \u03b1 \u2192 \u03b2) (g : \u03b1 \u2192 \u03b3) (l : List \u03b1) : zip (map f l) (map g l) = map (fun (a : \u03b1) => (f a, g a)) l := sorry\n\ntheorem mem_zip {\u03b1 : Type u} {\u03b2 : Type v} {a : \u03b1} {b : \u03b2} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2} : (a, b) \u2208 zip l\u2081 l\u2082 \u2192 a \u2208 l\u2081 \u2227 b \u2208 l\u2082 := sorry\n\ntheorem map_fst_zip {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : length l\u2081 \u2264 length l\u2082 \u2192 map prod.fst (zip l\u2081 l\u2082) = l\u2081 := sorry\n\ntheorem map_snd_zip {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) : length l\u2082 \u2264 length l\u2081 \u2192 map prod.snd (zip l\u2081 l\u2082) = l\u2082 := sorry\n\n@[simp] theorem unzip_nil {\u03b1 : Type u} {\u03b2 : Type v} : unzip [] = ([], []) :=\n  rfl\n\n@[simp] theorem unzip_cons {\u03b1 : Type u} {\u03b2 : Type v} (a : \u03b1) (b : \u03b2) (l : List (\u03b1 \u00d7 \u03b2)) : unzip ((a, b) :: l) = (a :: prod.fst (unzip l), b :: prod.snd (unzip l)) := sorry\n\ntheorem unzip_eq_map {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) : unzip l = (map prod.fst l, map prod.snd l) := sorry\n\ntheorem unzip_left {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) : prod.fst (unzip l) = map prod.fst l := sorry\n\ntheorem unzip_right {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) : prod.snd (unzip l) = map prod.snd l := sorry\n\ntheorem unzip_swap {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) : unzip (map prod.swap l) = prod.swap (unzip l) := sorry\n\ntheorem zip_unzip {\u03b1 : Type u} {\u03b2 : Type v} (l : List (\u03b1 \u00d7 \u03b2)) : zip (prod.fst (unzip l)) (prod.snd (unzip l)) = l := sorry\n\ntheorem unzip_zip_left {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2} : length l\u2081 \u2264 length l\u2082 \u2192 prod.fst (unzip (zip l\u2081 l\u2082)) = l\u2081 := sorry\n\ntheorem unzip_zip_right {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2} (h : length l\u2082 \u2264 length l\u2081) : prod.snd (unzip (zip l\u2081 l\u2082)) = l\u2082 :=\n  eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (zip l\u2081 l\u2082)) = l\u2082)) (Eq.symm (zip_swap l\u2082 l\u2081))))\n    (eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (map prod.swap (zip l\u2082 l\u2081))) = l\u2082)) (unzip_swap (zip l\u2082 l\u2081))))\n      (unzip_zip_left h))\n\ntheorem unzip_zip {\u03b1 : Type u} {\u03b2 : Type v} {l\u2081 : List \u03b1} {l\u2082 : List \u03b2} (h : length l\u2081 = length l\u2082) : unzip (zip l\u2081 l\u2082) = (l\u2081, l\u2082) := sorry\n\ntheorem zip_of_prod {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} {l' : List \u03b2} {lp : List (\u03b1 \u00d7 \u03b2)} (hl : map prod.fst lp = l) (hr : map prod.snd lp = l') : lp = zip l l' := sorry\n\ntheorem map_prod_left_eq_zip {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} (f : \u03b1 \u2192 \u03b2) : map (fun (x : \u03b1) => (x, f x)) l = zip l (map f l) := sorry\n\ntheorem map_prod_right_eq_zip {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} (f : \u03b1 \u2192 \u03b2) : map (fun (x : \u03b1) => (f x, x)) l = zip (map f l) l := sorry\n\n@[simp] theorem length_revzip {\u03b1 : Type u} (l : List \u03b1) : length (revzip l) = length l := sorry\n\n@[simp] theorem unzip_revzip {\u03b1 : Type u} (l : List \u03b1) : unzip (revzip l) = (l, reverse l) :=\n  unzip_zip (Eq.symm (length_reverse l))\n\n@[simp] theorem revzip_map_fst {\u03b1 : Type u} (l : List \u03b1) : 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 {\u03b1 : Type u} (l : List \u03b1) : 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 {\u03b1 : Type u} (l : List \u03b1) : reverse (revzip l) = revzip (reverse l) := sorry\n\ntheorem revzip_swap {\u03b1 : Type u} (l : List \u03b1) : map prod.swap (revzip l) = revzip (reverse l) := sorry\n\ntheorem nth_zip_with {\u03b1 : Type u_1} {\u03b2 : Type u_1} {\u03b3 : Type u_1} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) (i : \u2115) : nth (zip_with f l\u2081 l\u2082) i = f <$> nth l\u2081 i <*> nth l\u2082 i := sorry\n\ntheorem nth_zip_with_eq_some {\u03b1 : Type u_1} {\u03b2 : Type u_2} {\u03b3 : Type u_3} (f : \u03b1 \u2192 \u03b2 \u2192 \u03b3) (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) (z : \u03b3) (i : \u2115) : nth (zip_with f l\u2081 l\u2082) i = some z \u2194 \u2203 (x : \u03b1), \u2203 (y : \u03b2), nth l\u2081 i = some x \u2227 nth l\u2082 i = some y \u2227 f x y = z := sorry\n\ntheorem nth_zip_eq_some {\u03b1 : Type u} {\u03b2 : Type v} (l\u2081 : List \u03b1) (l\u2082 : List \u03b2) (z : \u03b1 \u00d7 \u03b2) (i : \u2115) : nth (zip l\u2081 l\u2082) i = some z \u2194 nth l\u2081 i = some (prod.fst z) \u2227 nth l\u2082 i = some (prod.snd z) := sorry\n\n@[simp] theorem nth_le_zip_with {\u03b1 : Type u} {\u03b2 : Type v} {\u03b3 : Type w} {f : \u03b1 \u2192 \u03b2 \u2192 \u03b3} {l : List \u03b1} {l' : List \u03b2} {i : \u2115} {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 {\u03b1 : Type u} {\u03b2 : Type v} {l : List \u03b1} {l' : List \u03b2} {i : \u2115} {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 {\u03b1 : Type u} {l : List \u03b1} {init : List \u03b1} {tail : List \u03b1} : (init, tail) \u2208 zip (inits l) (tails l) \u2194 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 := \u2115\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 \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 C \u2192 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 \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3,\nrw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 Rubik_3, rw Rubik_2, rw \u2190 Rubik_2, rw Rubik_3, rw \u2190 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 Lean\n\nnamespace Lean\nnamespace Expander\n\nopen Lean.Syntax\n\n-- Result of name resolution. As in the paper, we will ignore the second component here.\nabbrev NameRes := Name \u00d7 List String\n-- We model the global context more precisely as a mapping from symbols to qualified symbols,\n-- e.g. (`a \u21a6 [`ns1.a, `ns2.a])\nabbrev GlobalContext := Name \u2192 List NameRes\n\n-- the simplified transformer monad\nstructure TransformerContext where\n  gctx : GlobalContext\n  currMacroScope : MacroScope\n\nabbrev TransformerM := ReaderT TransformerContext Id\nabbrev Transformer := Syntax \u2192 TransformerM Syntax\n\n-- support syntax quotations in transformers\ninstance : MonadQuotation TransformerM where\n  getCurrMacroScope   := do let ctx \u2190 read; pure ctx.currMacroScope\n  -- dummy impls, unused\n  withFreshMacroScope := fun x => x\n  getRef              := pure Syntax.missing\n  withRef             := fun _ x => x\n  -- The actual implementation also adds the current module name to macro scopes for global uniqueness,\n  -- which we can ignore in this single-file example.\n  getMainModule       := pure `Expander\n\n-- the expander extension of the transformer monad\nstructure ExpanderContext extends TransformerContext where\n  lctx : NameSet\n  macros : Name \u2192 Option Transformer\n\nabbrev ExpanderM := ReaderT ExpanderContext <| StateT MacroScope <| ExceptT String <| Id\n\ninstance MonadQuotation : MonadQuotation ExpanderM where\n  getCurrMacroScope   := do let ctx \u2190 read; pure ctx.currMacroScope\n  withFreshMacroScope := fun x => do\n    let fresh \u2190 modifyGet (fun n => (n, n + 1))\n    withReader (fun ctx => { ctx with currMacroScope := fresh }) x\n  getMainModule       := pure `Expander\n  -- dummy impls, unused\n  getRef              := pure Syntax.missing\n  withRef             := fun _ x => x\n\n-- implicitly coerce transformer monad into expander monad\ninstance : Coe (TransformerM \u03b1) (ExpanderM \u03b1) where\n  coe t := fun ctx => t ctx.toTransformerContext\n\n-- simplified: ignore the module name parameter\ndef addMacroScope (n : Name) (scp : MacroScope) : Name :=\n  Lean.addMacroScope `Expander n scp\n\ndef getGlobalContext : TransformerM GlobalContext := do\n  return (\u2190 read).gctx\n\ndef getLocalContext : ExpanderM NameSet := do\n  return (\u2190 read).lctx\n\ndef resolve (gctx : GlobalContext) (n : Name) : List NameRes :=\n  gctx n\n\n-- slightly more meaningful name\ndef getIdentVal : Syntax \u2192 Name := Syntax.getId\n\ndef getPreresolved : Syntax \u2192 List NameRes\n  | Syntax.ident (preresolved := preresolved) .. => preresolved\n  | _                                            => []\n\ndef mkOverloadedIds (cs : List NameRes) : Syntax :=\n  Syntax.node SourceInfo.none choiceKind (cs.toArray.map (mkIdent \u2218 Prod.fst))\n\ndef withLocal (l : Name) : ExpanderM Syntax \u2192 ExpanderM Syntax :=\n  withReader (fun ctx => { ctx with lctx := ctx.lctx.insert l })\n\ndef getTransformerFor (k : SyntaxNodeKind) : ExpanderM (Syntax \u2192 ExpanderM Syntax) := do\n  match (\u2190 read).macros k with\n  | some t => return fun stx => t stx\n  | none   => throw (\"unknown macro \" ++ toString k)\n\n-- slightly simplified from the actual implementation\npartial def getAntiquotationIds (stx : Syntax) : ExpanderM (Array Syntax) := do\n  let mut ids := #[]\n  for stx in stx.topDown do\n    if (isAntiquot stx || isTokenAntiquot stx) && !isEscapedAntiquot stx then\n      let anti := getAntiquotTerm stx\n      if anti.isIdent then ids := ids.push anti\n      else throw \"complex antiquotation not allowed here\"\n  return ids\n\n-- Get all pattern vars (as `Syntax.ident`s) in `stx`\npartial def getPatternVars (stx : Syntax) : ExpanderM (Array Syntax) :=\n  if stx.isQuot then\n    getAntiquotationIds stx\n  else match stx with\n    | `(_)            => pure #[]\n    | `($id:ident)    => pure #[id]\n    | `($id:ident@$e) => do return (\u2190 getPatternVars e).push id\n    | _               => throw \"unsupported pattern in syntax match\"\n\n-- expand\npartial def expand : Syntax \u2192 ExpanderM Syntax\n  | `($id:ident) => do\n    let val : Name := getIdentVal id\n    let gctx \u2190 getGlobalContext\n    let lctx \u2190 getLocalContext\n    if lctx.contains val then\n      pure (mkIdent val)\n    else match resolve gctx val ++ getPreresolved id with\n      | []        => throw (\"unknown identifier \" ++ toString val)\n      | [(id, _)] => pure (mkIdent id)\n      | ids       => pure (mkOverloadedIds ids)\n  | `(fun ($id : $ty) => $e) => do\n    let val := getIdentVal id\n    let ty \u2190 expand ty\n    let e \u2190 withLocal val (expand e)\n    `(fun ($(mkIdent val) : $ty) => $e)\n-- end\n  -- more core forms\n  | `(fun $id:ident => $e) => do\n    let e \u2190 withLocal (getIdentVal id) (expand e)\n    `(fun $id:ident => $e)\n  | `($num:num) => `($num:num)\n  | `($str:str) => `($str:str)\n  | `($n:quotedName) => `($n:quotedName)\n  | `($fn $args*) => do\n    let fn \u2190 expand fn\n    let args \u2190 args.mapM expand\n    `($fn $args*)\n  | `(def $id := $e) => do\n    let e \u2190 expand e\n    `(def $id := $e)\n  -- syntax: keep as-is\n  | `(syntax $[(name := $n)]? $[(priority := $prio)]? $[$args:stx]* : $kind) => `(syntax $[(name := $n)]? $[(priority := $prio)]? $[$args:stx]* : $kind)\n  -- macro_rules: expand rhs (but not lhs) to exercise syntax quotation macro\n  | `(macro_rules | $lhs => $rhs) => do\n    let vars \u2190 getPatternVars lhs\n    let rhs \u2190 vars.foldr (fun var ex => withLocal var.getId ex) (expand rhs)\n    `(macro_rules | $lhs => $rhs)\n  -- we will ignore double-backtick quotations generated by `notation` for this example\n  | `(``($e)) => `(`($e))\n  | stx => do\n    -- expansion consists of multiple commands => yield and get called back per command\n    if stx.isOfKind nullKind then pure stx else do\n    let t \u2190 getTransformerFor stx.getKind\n    let stx \u2190 withFreshMacroScope (t stx)\n    expand stx\n\nopen Lean.Elab.Term.Quotation\n-- quoteSyntax\npartial def quoteSyntax : Syntax \u2192 TransformerM Syntax\n  | Syntax.ident info rawVal val preresolved => do\n    let gctx \u2190 getGlobalContext\n    let preresolved := resolve gctx val ++ preresolved\n    `(Syntax.ident SourceInfo.none $(quote rawVal)\n        (addMacroScope $(quote val) msc) $(quote preresolved))\n  | stx@(Syntax.node _ k args) =>\n    if isAntiquot stx then pure (getAntiquotTerm stx)\n    else do\n      let args \u2190 args.mapM quoteSyntax\n      `(Syntax.node SourceInfo.none $(quote k) $(quote args))\n  | Syntax.atom info val => `(Syntax.atom SourceInfo.none $(quote val))\n  | Syntax.missing => pure Syntax.missing\n\ndef expandStxQuot (stx : Syntax) : TransformerM Syntax := do\n  let stx \u2190 quoteSyntax (stx.getArg 1)\n  `(do msc \u2190 getCurrMacroScope; pure $stx)\n-- end\n\n-- two more, simple macros\ndef expandDo : Transformer\n  | `(do $id:ident \u2190 $val:term; $body:term) => `(Bind.bind $val (fun $id:ident => $body))\n  | _                                  => pure Syntax.missing\n\ndef expandParen : Transformer\n  | `(($e)) => pure e\n  | _       => pure Syntax.missing\n\n-- custom Syntax pretty printer for our core forms that uses the paper's notation for hygienic identifiers\ndef ppIdent (n : Name) : Format :=\n  let v := extractMacroScopes n\n  format <| v.scopes.foldl Name.mkNum v.name\n\n-- flip to make output more readable\ndef hideMacroRulesRhs := false\n\nopen Std.Format\npartial def pp : Syntax \u2192 Format\n  | `($id:ident) => match getPreresolved id with\n    | [] => ppIdent id.getId\n    | ps => ppIdent id.getId ++ bracket \"{\" (joinSep (ps.map (format \u2218 Prod.fst)) \", \") \"}\"\n  | `(fun ($id : $ty) => $e) => paren f!\"fun {paren (pp id ++ \" : \" ++ pp ty)} => {pp e}\"\n  | `(fun $id => $e) => paren f!\"fun {pp id} => {pp e}\"\n  | `($num:num) => format (num.isNatLit?.getD 0)\n  | `($str:str) => repr (str.isStrLit?.getD \"\")\n  | `($fn $args*) => paren <| pp fn ++ \" \" ++ joinSep (args.toList.map pp) line\n  | `(def $id:ident := $e) => f!\"def {ppIdent id.getId} := {pp e}\"\n  | `(syntax $[(name := $n)]? $[(priority := $prio)]? $[$args:stx]* : $kind) => \"syntax ...\"  -- irrelevant for this example\n  | `(macro_rules | $lhs => $rhs) => f!\"macro_rules |{lhs.reprint.getD \"\"} => {if hideMacroRulesRhs then f!\"...\" else pp rhs}\"\n  | stx => f!\"<not a core form: {stx}>\"\n\n-- integrate example expander into frontend, between parser and elaborator. Not pretty.\nsection Elaboration\nopen Lean.Elab\nopen Lean.Elab.Frontend\n\n-- run expander: adapt global context and set of macro from Environment\ndef expanderToFrontend (ref : Syntax) (e : ExpanderM Syntax) : FrontendM Syntax := runCommandElabM <| withRef ref do\n  let st \u2190 get\n  let scope := st.scopes.head!\n  match e {\n    gctx := fun n => (match st.env.find? n with\n      | some _ => [(n, [])]\n      | none   => [] : List NameRes),\n    lctx := {},\n    currMacroScope := st.nextMacroScope,\n    macros := fun k =>\n      -- our hardcoded example macros\n      if k == `Lean.Parser.Term.quot then some expandStxQuot\n      else if k == `Lean.Parser.Term.do then some expandDo\n      else if k == `Lean.Parser.Term.paren then some expandParen\n      -- `notation`, `macro`, and macros generated at runtime\n      else\n        match macroAttribute.getValues st.env k with\n        | t::_ => some (fun stx ctx =>\n          match t stx {\n            mainModule := `Expander\n            currMacroScope := ctx.currMacroScope\n            ref := ref\n            methods := Macro.mkMethods {\n              expandMacro?     := fun stx => do\n                match (\u2190 expandMacroImpl? st.env stx) with\n                | some (_, Except.ok stx') => return some stx'\n                | _                        => return none\n              hasDecl          := fun declName => return st.env.contains declName\n              getCurrNamespace := return scope.currNamespace\n              resolveNamespace? := fun n => return ResolveName.resolveNamespace? st.env scope.currNamespace scope.openDecls n\n              resolveGlobalName := fun n => return ResolveName.resolveGlobalName st.env scope.currNamespace scope.openDecls n\n            }\n          } {\n            macroScope := 0\n          } with\n          | EStateM.Result.ok stx s => stx\n          | _ => Syntax.missing)\n        | _           => none\n  } (st.nextMacroScope + 1) with\n  | Except.ok (stx, nextMacroScope) => do\n    modify (fun st => {st with nextMacroScope := nextMacroScope})\n    pure stx\n  | Except.error e => do\n    logError e\n    pure Syntax.missing\n\npartial def processCommand (cmd : Syntax) : FrontendM Unit := do\n  let cmd' \u2190 expanderToFrontend cmd <| expand cmd\n  if cmd'.isOfKind nullKind then\n    -- expander returned multiple commands => process in turn\n    cmd'.getArgs.forM processCommand\n  else do\n    runCommandElabM <| logInfo (pp cmd')\n    elabCommandAtFrontend cmd'\n\npartial def processCommands : FrontendM Unit := do\n  let cmdState    \u2190 getCommandState\n  let parserState \u2190 getParserState\n  let inputCtx    \u2190 getInputContext\n  let scope := cmdState.scopes.head!\n  let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls }\n  let (cmd, ps, messages) \u2190 pure (Parser.parseCommand inputCtx pmctx parserState cmdState.messages)\n  setParserState ps\n  setMessages messages\n  if Parser.isEOI cmd then do\n    pure ()\n  else do\n    processCommand cmd\n    processCommands\n\ndef process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment \u00d7 MessageLog) := do\n  let fileName   := fileName.getD \"<input>\"\n  let inputCtx   := Parser.mkInputContext input fileName\n  let (_, st) \u2190 processCommands { inputCtx := inputCtx } |>.run { commandState := Command.mkState env {} opts, parserState := {}, cmdPos := 0 }\n  pure (st.commandState.env, st.commandState.messages)\n\ndef run (input : String) : CoreM Unit := do\n  let env  \u2190 getEnv\n  let opts \u2190 getOptions\n  let (env, messages) \u2190 liftM $ process input env opts\n  messages.forM fun msg => do\n    IO.println (\u2190 msg.toString)\n\nend Elaboration\n\n-- examples\n-- see also `hideMacroRulesRhs` above\n\n#eval run \"\ndef x := 1\ndef e := fun (y : Nat) => x\nnotation \\\"const\\\" e => fun (x : Nat) => e\ndef y := const x\n\"\n\n#eval run \"\nmacro \\\"m\\\" n:ident : command => `(\n  def f := 1\n  macro \\\"mm\\\" : command => `(\n    def $n:ident := f\n    def f := $n:ident))\nm f\nmm\nmm\n\"\n\nend Expander\nend Lean\n", "meta": {"author": "Kha", "repo": "macro-supplement", "sha": "1d98fe918cc70433a489cae1dab5b2b2f889829d", "save_path": "github-repos/lean/Kha-macro-supplement", "path": "github-repos/lean/Kha-macro-supplement/macro-supplement-1d98fe918cc70433a489cae1dab5b2b2f889829d/Expander.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682621306573764, "lm_q2_score": 0.039638838108279964, "lm_q1q2_score": 0.007801962395178593}}
{"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.Basic\n\nnamespace Lean.Meta\n\ndef GetEqnsFn := Name \u2192 MetaM (Option (Array Name))\n\nprivate builtin_initialize getEqnsFnsRef : IO.Ref (List GetEqnsFn) \u2190 IO.mkRef []\n\n/--\n  Register a new function for retrieving equation theorems.\n  We generate equations theorems on demand, and they are generated by more than one module.\n  For example, the structural and well-founded recursion modules generate them.\n  Most recent getters are tried first.\n\n  A getter returns an `Option (Array Name)`. The result is `none` if the getter failed.\n  Otherwise, it is a sequence of theorem names where each one of them corresponds to\n  an alternative. Example: the definition\n\n  ```\n  def f (xs : List Nat) : List Nat :=\n    match xs with\n    | [] => []\n    | x::xs => (x+1)::f xs\n  ```\n  should have two equational theorems associated with it\n  ```\n  f [] = []\n  ```\n  and\n  ```\n  (x : Nat) \u2192 (xs : List Nat) \u2192 f (x :: xs) = (x+1) :: f xs\n  ```\n-/\ndef registerGetEqnsFn (f : GetEqnsFn) : IO Unit := do\n  unless (\u2190 initializing) do\n    throw (IO.userError \"failed to register equation getter, this kind of extension can only be registered during initialization\")\n  getEqnsFnsRef.modify (f :: \u00b7)\n\ndef getEqnsFor? (declName : Name) : MetaM (Option (Array Name)) := do\n  for f in (\u2190 getEqnsFnsRef.get) do\n    if let some r \u2190 f declName then\n      return some r\n  return none\n\ndef GetUnfoldEqnFn := Name \u2192 MetaM (Option Name)\n\nprivate builtin_initialize getUnfoldEqnFnsRef : IO.Ref (List GetUnfoldEqnFn) \u2190 IO.mkRef []\n\n/--\n  Register a new function for retrieving a \"unfold\" equation theorem.\n\n  We generate this kind of equation theorem on demand, and it is generated by more than one module.\n  For example, the structural and well-founded recursion modules generate it.\n  Most recent getters are tried first.\n\n  A getter returns an `Option Name`. The result is `none` if the getter failed.\n  Otherwise, it is a theorem name. Example: the definition\n\n  ```\n  def f (xs : List Nat) : List Nat :=\n    match xs with\n    | [] => []\n    | x::xs => (x+1)::f xs\n  ```\n  should have the theorem\n  ```\n  (xs : Nat) \u2192\n    f xs =\n      match xs with\n      | [] => []\n      | x::xs => (x+1)::f xs\n  ```\n-/\ndef registerGetUnfoldEqnFn (f : GetUnfoldEqnFn) : IO Unit := do\n  unless (\u2190 initializing) do\n    throw (IO.userError \"failed to register equation getter, this kind of extension can only be registered during initialization\")\n  getUnfoldEqnFnsRef.modify (f :: \u00b7)\n\ndef getUnfoldEqnFor? (declName : Name) : MetaM (Option Name) := do\n  for f in (\u2190 getUnfoldEqnFnsRef.get) do\n    if let some r \u2190 f declName then\n      return some r\n  return none\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/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713269122913015, "lm_q2_score": 0.041462269454204566, "lm_q1q2_score": 0.007758946067432658}}
{"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.CollectFVars\nimport Lean.Meta.Match.MatchPatternAttr\nimport Lean.Meta.Match.Match\nimport Lean.Meta.SortLocalDecls\nimport Lean.Meta.GeneralizeVars\nimport Lean.Elab.SyntheticMVars\nimport Lean.Elab.App\nimport Lean.Parser.Term\n\nnamespace Lean.Elab.Term\nopen Meta\nopen Lean.Parser.Term\n\n/- This modules assumes \"match\"-expressions use the following syntax.\n\n```lean\ndef matchDiscr := leading_parser optional (try (ident >> checkNoWsBefore \"no space before ':'\" >> \":\")) >> termParser\n\ndef \u00abmatch\u00bb := leading_parser:leadPrec \"match \" >> sepBy1 matchDiscr \", \" >> optType >> \" with \" >> matchAlts\n```\n-/\n\nstructure MatchAltView where\n  ref      : Syntax\n  patterns : Array Syntax\n  rhs      : Syntax\n  deriving Inhabited\n\nprivate def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let newStx \u2190 `(let $lhsVar := $discr; $rhs)\n  withMacroExpansion stx newStx <| elabTerm newStx expectedType?\n\nprivate def mkUserNameFor (e : Expr) : TermElabM Name := do\n  match e with\n  /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/\n  | Expr.fvar fvarId _ => mkFreshUserName ((\u2190 getLocalDecl fvarId).userName)\n  | _                  => mkFreshBinderName\n\n/-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/\ndef isAuxDiscrName (n : Name) : Bool :=\n  n.hasMacroScopes && n.eraseMacroScopes == `_discr\n\n/- We treat `@x` as atomic to avoid unnecessary extra local declarations from being\n   inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier.\n   Thus this is kind of discriminant is quite common.\n\n   Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression.\n   This can happen due to error recovery. Example\n   ```\n   example : (p \u2228 p) \u2192 p := fun h => match\n   ```\n   If we don't abort, the elaborator loops because we will keep trying to expand\n   ```\n   match\n   ```\n   into\n   ```\n   let d := <Syntax.missing>; match\n   ```\n   Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/\ndef isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do\n  match discr with\n  | `($x:ident)  => isLocalIdent? x\n  | `(@$x:ident) => isLocalIdent? x\n  | _ => if discr.isMissing then throwAbortTerm else return none\n\n-- See expandNonAtomicDiscrs?\nprivate def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do\n  let term := discr[1]\n  match (\u2190 isAtomicDiscr? term) with\n  | some e@(Expr.fvar fvarId _) =>\n    let localDecl \u2190 getLocalDecl fvarId\n    if !isAuxDiscrName localDecl.userName then\n      return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`\n    else\n      instantiateMVars localDecl.value\n  | _ => throwErrorAt discr \"unexpected discriminant\"\n\nstructure ElabMatchTypeAndDiscrsResult where\n  discrs    : Array Expr\n  matchType : Expr\n  /- `true` when performing dependent elimination. We use this to decide whether we optimize the \"match unit\" case.\n     See `isMatchUnit?`. -/\n  isDep     : Bool\n  alts      : Array MatchAltView\n\nprivate partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)\n      : TermElabM ElabMatchTypeAndDiscrsResult := do\n    let numDiscrs := discrStxs.size\n    if matchOptType.isNone then\n      elabDiscrs 0 #[]\n    else\n      let matchTypeStx := matchOptType[0][1]\n      let matchType \u2190 elabType matchTypeStx\n      let (discrs, isDep) \u2190 elabDiscrsWitMatchType matchType expectedType\n      return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }\n  where\n    /- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user.  -/\n    elabDiscrsWitMatchType (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr \u00d7 Bool) := do\n      let mut discrs := #[]\n      let mut i := 0\n      let mut matchType := matchType\n      let mut isDep := false\n      for discrStx in discrStxs do\n        i := i + 1\n        matchType \u2190 whnf matchType\n        match matchType with\n        | Expr.forallE _ d b _ =>\n          let discr \u2190 fullApproxDefEq <| elabTermEnsuringType discrStx[1] d\n          trace[Elab.match] \"discr #{i} {discr} : {d}\"\n          if b.hasLooseBVars then\n            isDep := true\n          matchType \u2190 b.instantiate1 discr\n          discrs := discrs.push discr\n        | _ =>\n          throwError \"invalid type provided to match-expression, function type with arity #{discrStxs.size} expected\"\n      return (discrs, isDep)\n\n    markIsDep (r : ElabMatchTypeAndDiscrsResult) :=\n      { r with isDep := true }\n\n    /- Elaborate discriminants inferring the match-type -/\n    elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do\n      if h : i < discrStxs.size then\n        let discrStx := discrStxs.get \u27e8i, h\u27e9\n        let discr     \u2190 elabAtomicDiscr discrStx\n        let discr     \u2190 instantiateMVars discr\n        let discrType \u2190 inferType discr\n        let discrType \u2190 instantiateMVars discrType\n        let discrs    := discrs.push discr\n        let userName \u2190 mkUserNameFor discr\n        if discrStx[0].isNone then\n          let mut result \u2190 elabDiscrs (i + 1) discrs\n          let matchTypeBody \u2190 kabstract result.matchType discr\n          if matchTypeBody.hasLooseBVars then\n            result := markIsDep result\n          return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody }\n        else\n          let discrs := discrs.push (\u2190 mkEqRefl discr)\n          let result \u2190 elabDiscrs (i + 1) discrs\n          let result := markIsDep result\n          let identStx := discrStx[0][0]\n          withLocalDeclD userName discrType fun x => do\n            let eqType \u2190 mkEq discr x\n            withLocalDeclD identStx.getId eqType fun h => do\n              let matchTypeBody \u2190 kabstract result.matchType discr\n              let matchTypeBody := matchTypeBody.instantiate1 x\n              let matchType \u2190 mkForallFVars #[x, h] matchTypeBody\n              return { result with\n                matchType := matchType\n                alts      := result.alts.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx }\n              }\n      else\n        return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType }\n\ndef expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do\n  matchAlts.mapM fun matchAlt => do\n    let patterns \u2190 matchAlt.patterns.mapM expandMacros\n    pure { matchAlt with patterns := patterns }\n\nprivate def getMatchGeneralizing? : Syntax \u2192 Option Bool\n  | `(match (generalizing := true)  $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true\n  | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false\n  | _ => none\n\n/- Given `stx` a match-expression, return its alternatives. -/\nprivate def getMatchAlts : Syntax \u2192 Array MatchAltView\n  | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) =>\n    alts.filterMap fun alt => match alt with\n      | `(matchAltExpr| | $patterns,* => $rhs) => some {\n          ref      := alt,\n          patterns := patterns,\n          rhs      := rhs\n        }\n      | _ => none\n  | _ => #[]\n\ninductive PatternVar where\n  | localVar     (userName : Name)\n  -- anonymous variables (`_`) are encoded using metavariables\n  | anonymousVar (mvarId   : MVarId)\n\ninstance : ToString PatternVar := \u27e8fun\n  | PatternVar.localVar x          => toString x\n  | PatternVar.anonymousVar mvarId => s!\"?m{mvarId}\"\u27e9\n\nbuiltin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind\n\n/--\n  Create an auxiliary Syntax node wrapping a fresh metavariable id.\n  We use this kind of Syntax for representing `_` occurring in patterns.\n  The metavariables are created before we elaborate the patterns into `Expr`s. -/\nprivate def mkMVarSyntax : TermElabM Syntax := do\n  let mvarId \u2190 mkFreshId\n  return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]]\n\n/-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/\nprivate def getMVarSyntaxMVarId (stx : Syntax) : MVarId :=\n  stx[0].getKind\n\nopen Meta.Match (mkInaccessible inaccessible?)\n\n/--\n  The elaboration function for `Syntax` created using `mkMVarSyntax`.\n  It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/\n@[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? =>\n  return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx)\n\n@[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do\n  let e \u2190 elabTerm stx[1] expectedType?\n  return mkInaccessible e\n\n/-\n  Patterns define new local variables.\n  This module collect them and preprocess `_` occurring in patterns.\n  Recall that an `_` may represent anonymous variables or inaccessible terms\n  that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`.\n  After we elaborate the pattern, if the metavariable remains unassigned, we transform it into\n  a regular pattern variable. Otherwise, it becomes an inaccessible term.\n\n  Macros occurring in patterns are expanded before the `collectPatternVars` method is executed.\n  The following kinds of Syntax are handled by this module\n  - Constructor applications\n  - Applications of functions tagged with the `[matchPattern]` attribute\n  - Identifiers\n  - Anonymous constructors\n  - Structure instances\n  - Inaccessible terms\n  - Named patterns\n  - Tuple literals\n  - Type ascriptions\n  - Literals: num, string and char\n-/\nnamespace CollectPatternVars\n\nstructure State where\n  found     : NameSet := {}\n  vars      : Array PatternVar := #[]\n\nabbrev M := StateRefT State TermElabM\n\nprivate def throwCtorExpected {\u03b1} : M \u03b1 :=\n  throwError \"invalid pattern, constructor or constant marked with '[matchPattern]' expected\"\n\nprivate def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat :=\n  forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do\n    let mut result := 0\n    for p in ps do\n      let localDecl \u2190 getLocalDecl p.fvarId!\n      if localDecl.binderInfo.isExplicit then\n        result := result+1\n    pure result\n\nprivate def throwInvalidPattern {\u03b1} : M \u03b1 :=\n  throwError \"invalid pattern\"\n\n/-\nAn application in a pattern can be\n\n1- A constructor application\n   The elaborator assumes fields are accessible and inductive parameters are not accessible.\n\n2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`.\n   The elaborator assumes implicit arguments are not accessible and explicit ones are accessible.\n-/\n\nstructure Context where\n  funId         : Syntax\n  ctorVal?      : Option ConstructorVal -- It is `some`, if constructor application\n  explicit      : Bool\n  ellipsis      : Bool\n  paramDecls    : Array (Name \u00d7 BinderInfo) -- parameters names and binder information\n  paramDeclIdx  : Nat := 0\n  namedArgs     : Array NamedArg\n  args          : List Arg\n  newArgs       : Array Syntax := #[]\n  deriving Inhabited\n\nprivate def isDone (ctx : Context) : Bool :=\n  ctx.paramDeclIdx \u2265 ctx.paramDecls.size\n\nprivate def finalize (ctx : Context) : M Syntax := do\n  if ctx.namedArgs.isEmpty && ctx.args.isEmpty then\n    let fStx \u2190 `(@$(ctx.funId):ident)\n    return Syntax.mkApp fStx ctx.newArgs\n  else\n    throwError \"too many arguments\"\n\nprivate def isNextArgAccessible (ctx : Context) : Bool :=\n  let i := ctx.paramDeclIdx\n  match ctx.ctorVal? with\n  | some ctorVal => i \u2265 ctorVal.numParams -- For constructor applications only fields are accessible\n  | none =>\n    if h : i < ctx.paramDecls.size then\n      -- For `[matchPattern]` applications, only explicit parameters are accessible.\n      let d := ctx.paramDecls.get \u27e8i, h\u27e9\n      d.2.isExplicit\n    else\n      false\n\nprivate def getNextParam (ctx : Context) : (Name \u00d7 BinderInfo) \u00d7 Context :=\n  let i := ctx.paramDeclIdx\n  let d := ctx.paramDecls[i]\n  (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 })\n\nprivate def processVar (idStx : Syntax) : M Syntax := do\n  unless idStx.isIdent do\n    throwErrorAt idStx \"identifier expected\"\n  let id := idStx.getId\n  unless id.eraseMacroScopes.isAtomic do\n    throwError \"invalid pattern variable, must be atomic\"\n  if (\u2190 get).found.contains id then\n    throwError \"invalid pattern, variable '{id}' occurred more than once\"\n  modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id }\n  return idStx\n\nprivate def nameToPattern : Name \u2192 TermElabM Syntax\n  | Name.anonymous => `(Name.anonymous)\n  | Name.str p s _ => do let p \u2190 nameToPattern p; `(Name.str $p $(quote s) _)\n  | Name.num p n _ => do let p \u2190 nameToPattern p; `(Name.num $p $(quote n) _)\n\nprivate def quotedNameToPattern (stx : Syntax) : TermElabM Syntax :=\n  match stx[0].isNameLit? with\n  | some val => nameToPattern val\n  | none     => throwIllFormedSyntax\n\nprivate def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do\n  match stx[1].isNameLit? with\n  | some val => nameToPattern (\u2190 resolveGlobalConstNoOverloadWithInfo stx[1] val)\n  | none     => throwIllFormedSyntax\n\npartial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do\n  let k := stx.getKind\n  if k == identKind then\n    processId stx\n  else if k == ``Lean.Parser.Term.app then\n    processCtorApp stx\n  else if k == ``Lean.Parser.Term.anonymousCtor then\n    let elems \u2190 stx[1].getArgs.mapSepElemsM collect\n    return stx.setArg 1 <| mkNullNode elems\n  else if k == ``Lean.Parser.Term.structInst then\n    /-\n    ```\n    leading_parser \"{\" >> optional (atomic (termParser >> \" with \"))\n                >> manyIndent (group (structInstField >> optional \", \"))\n                >> optional \"..\"\n                >> optional (\" : \" >> termParser)\n                >> \" }\"\n    ```\n    -/\n    let withMod := stx[1]\n    unless withMod.isNone do\n      throwErrorAt withMod \"invalid struct instance pattern, 'with' is not allowed in patterns\"\n    let fields \u2190 stx[2].getArgs.mapM fun p => do\n        -- p is of the form (group (structInstField >> optional \", \"))\n        let field := p[0]\n        -- leading_parser structInstLVal >> \" := \" >> termParser\n        let newVal \u2190 collect field[2]\n        let field := field.setArg 2 newVal\n        pure <| field.setArg 0 field\n    return stx.setArg 2 <| mkNullNode fields\n  else if k == ``Lean.Parser.Term.hole then\n    let r \u2190 mkMVarSyntax\n    modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r }\n    return r\n  else if k == ``Lean.Parser.Term.paren then\n    let arg := stx[1]\n    if arg.isNone then\n      return stx -- `()`\n    else\n      let t := arg[0]\n      let s := arg[1]\n      if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then\n        -- Ignore `s`, since it empty or it is a type ascription\n        let t \u2190 collect t\n        let arg := arg.setArg 0 t\n        return stx.setArg 1 arg\n      else\n        return stx\n  else if k == ``Lean.Parser.Term.explicitUniv then\n    processCtor stx[0]\n  else if k == ``Lean.Parser.Term.namedPattern then\n    /- Recall that\n      def namedPattern := check... >> trailing_parser \"@\" >> termParser -/\n    let id := stx[0]\n    discard <| processVar id\n    let pat := stx[2]\n    let pat \u2190 collect pat\n    `(_root_.namedPattern $id $pat)\n  else if k == ``Lean.Parser.Term.binop then\n    let lhs \u2190 collect stx[2]\n    let rhs \u2190 collect stx[3]\n    return stx.setArg 2 lhs |>.setArg 3 rhs\n  else if k == ``Lean.Parser.Term.inaccessible then\n    return stx\n  else if k == strLitKind then\n    return stx\n  else if k == numLitKind then\n    return stx\n  else if k == scientificLitKind then\n    return stx\n  else if k == charLitKind then\n    return stx\n  else if k == ``Lean.Parser.Term.quotedName then\n    /- Quoted names have an elaboration function associated with them, and they will not be macro expanded.\n      Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum`\n      instead of the constructors `Name.str` and `Name.num` -/\n    quotedNameToPattern stx\n  else if k == ``Lean.Parser.Term.doubleQuotedName then\n    /- Similar to previous case -/\n    doubleQuotedNameToPattern stx\n  else if k == choiceKind then\n    throwError \"invalid pattern, notation is ambiguous\"\n  else\n    throwInvalidPattern\n\nwhere\n\n  processCtorApp (stx : Syntax) : M Syntax := do\n    let (f, namedArgs, args, ellipsis) \u2190 expandApp stx true\n    processCtorAppCore f namedArgs args ellipsis\n\n  processCtor (stx : Syntax) : M Syntax := do\n    processCtorAppCore stx #[] #[] false\n\n  /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/\n  processId (stx : Syntax) : M Syntax := do\n    match (\u2190 resolveId? stx \"pattern\" (withInfo := true)) with\n    | none   => processVar stx\n    | some f => match f with\n      | Expr.const fName _ _ =>\n        match (\u2190 getEnv).find? fName with\n        | some (ConstantInfo.ctorInfo _) => processCtor stx\n        | some _ =>\n          if hasMatchPatternAttribute (\u2190 getEnv) fName then\n            processCtor stx\n          else\n            processVar stx\n        | none => throwCtorExpected\n      | _ => processVar stx\n\n  pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do\n    match arg with\n    | Arg.stx stx =>\n      let stx \u2190 if accessible then collect stx else pure stx\n      return { ctx with newArgs := ctx.newArgs.push stx }\n    | _ => unreachable!\n\n  processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do\n    match ctx.args with\n    | [] =>\n      if ctx.ellipsis then\n        pushNewArg accessible ctx (Arg.stx (\u2190 `(_)))\n      else\n        throwError \"explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}\"\n    | arg::args =>\n      pushNewArg accessible { ctx with args := args } arg\n\n  processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do\n    if ctx.explicit then\n      processExplicitArg accessible ctx\n    else\n      pushNewArg accessible ctx (Arg.stx (\u2190 `(_)))\n\n  processCtorAppContext (ctx : Context) : M Syntax := do\n    if isDone ctx then\n      finalize ctx\n    else\n      let accessible := isNextArgAccessible ctx\n      let (d, ctx)   := getNextParam ctx\n      match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with\n      | some idx =>\n        let arg := ctx.namedArgs[idx]\n        let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx }\n        let ctx \u2190 pushNewArg accessible ctx arg.val\n        processCtorAppContext ctx\n      | none =>\n        let ctx \u2190 match d.2 with\n          | BinderInfo.implicit     => processImplicitArg accessible ctx\n          | BinderInfo.instImplicit => processImplicitArg accessible ctx\n          | _                       => processExplicitArg accessible ctx\n        processCtorAppContext ctx\n\n  processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do\n    let args := args.toList\n    let (fId, explicit) \u2190 match f with\n      | `($fId:ident)  => pure (fId, false)\n      | `(@$fId:ident) => pure (fId, true)\n      | _              => throwError \"identifier expected\"\n    let some (Expr.const fName _ _) \u2190 resolveId? fId \"pattern\" (withInfo := true) | throwCtorExpected\n    let fInfo \u2190 getConstInfo fName\n    let paramDecls \u2190 forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do\n      let d \u2190 getFVarLocalDecl x\n      return (d.userName, d.binderInfo)\n    match fInfo with\n    | ConstantInfo.ctorInfo val =>\n      processCtorAppContext\n        { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }\n    | _ =>\n      if hasMatchPatternAttribute (\u2190 getEnv) fName then\n        processCtorAppContext\n          { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }\n      else\n        throwCtorExpected\n\ndef main (alt : MatchAltView) : M MatchAltView := do\n  let patterns \u2190 alt.patterns.mapM fun p => do\n    trace[Elab.match] \"collecting variables at pattern: {p}\"\n    collect p\n  return { alt with patterns := patterns }\n\nend CollectPatternVars\n\nprivate def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar \u00d7 MatchAltView) := do\n  let (alt, s) \u2190 (CollectPatternVars.main alt).run {}\n  return (s.vars, alt)\n\n/- Return the pattern variables in the given pattern.\n   Remark: this method is not used by the main `match` elaborator, but in the precheck hook and other macros (e.g., at `Do.lean`). -/\ndef getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do\n  let patternStx \u2190 liftMacroM <| expandMacros patternStx\n  let (_, s) \u2190 (CollectPatternVars.collect patternStx).run {}\n  return s.vars\n\ndef getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do\n  let collect : CollectPatternVars.M Unit := do\n    for pattern in patterns do\n      discard <| CollectPatternVars.collect (\u2190 liftMacroM <| expandMacros pattern)\n  let (_, s) \u2190 collect.run {}\n  return s.vars\n\ndef getPatternVarNames (pvars : Array PatternVar) : Array Name :=\n  pvars.filterMap fun\n    | PatternVar.localVar x => some x\n    | _ => none\n\nopen Lean.Elab.Term.Quotation in\n@[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck\n  | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do\n    discrs.forM precheck\n    for (pats, rhs) in patss.zip rhss do\n      let vars \u2190\n        try\n          getPatternsVars pats\n        catch\n          | _ => return  -- can happen in case of pattern antiquotations\n      Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs\n  | _ => throwUnsupportedSyntax\n\n/- We convert the collected `PatternVar`s intro `PatternVarDecl` -/\ninductive PatternVarDecl where\n  /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable\n     when it is not assigned during pattern elaboration. -/\n  | anonymousVar (mvarId : MVarId) (fvarId : FVarId)\n  | localVar     (fvarId : FVarId)\n\nprivate partial def withPatternVars {\u03b1} (pVars : Array PatternVar) (k : Array PatternVarDecl \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (decls : Array PatternVarDecl) := do\n    if h : i < pVars.size then\n      match pVars.get \u27e8i, h\u27e9 with\n      | PatternVar.anonymousVar mvarId =>\n        let type \u2190 mkFreshTypeMVar\n        let userName \u2190 mkFreshBinderName\n        withLocalDecl userName BinderInfo.default type fun x =>\n          loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!))\n      | PatternVar.localVar userName   =>\n        let type \u2190 mkFreshTypeMVar\n        withLocalDecl userName BinderInfo.default type fun x =>\n          loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!))\n    else\n      /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`.\n         Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/\n      decls.forM fun decl => match decl with\n        | PatternVarDecl.anonymousVar mvarId fvarId => do\n          let type \u2190 inferType (mkFVar fvarId)\n          discard <| mkFreshExprMVarWithId mvarId type\n        | _ => pure ()\n      k decls\n  loop 0 #[]\n\n/-\nRemark: when performing dependent pattern matching, we often had to write code such as\n\n```lean\ndef Vec.map' (f : \u03b1 \u2192 \u03b2) (xs : Vec \u03b1 n) : Vec \u03b2 n :=\n  match n, xs with\n  | _, nil       => nil\n  | _, cons a as => cons (f a) (map' f as)\n```\nWe had to include `n` and the `_`s because the type of `xs` depends on `n`.\nMoreover, `nil` and `cons a as` have different types.\nThis was quite tedious. So, we have implemented an automatic \"discriminant refinement procedure\".\nThe procedure is based on the observation that we get a type error whenenver we forget to include `_`s\nand the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant\nis an indexed family, and add their indices as new discriminants.\n\nThe current implementation, adds indices as they are found, and does not\ntry to \"sort\" the new discriminants.\n\nIf the refinement process fails, we report the original error message.\n-/\n\n/- Auxiliary structure for storing an type mismatch exception when processing the\n   pattern #`idx` of some alternative. -/\nstructure PatternElabException where\n  ex          : Exception\n  patternIdx  : Nat -- Discriminant that sh\n  pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch\n\n/--\n  This method is part of the \"discriminant refinement\" procedure. It in invoked when the\n  type of the `pattern` does not match the expected type. The expected type is based on the\n  motive computed using the `match` discriminants.\n  It tries to compute a path to an index of the discriminant type.\n  For example, suppose the user has written\n  ```\n  inductive Mem (a : \u03b1) : List \u03b1 \u2192 Prop where\n    | head {as} : Mem a (a::as)\n    | tail {as} : Mem a as \u2192 Mem a (a'::as)\n\n  infix:50 \" \u2208 \" => Mem\n\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match h with\n  | Mem.head => rfl\n  ```\n  The motive for the match is `a \u2208 [b] \u2192 b = a`, and get a type mismatch between the type\n  of `Mem.head` and `a \u2208 [b]`. This procedure return the path `[2, 1]` to the index `b`.\n  We use it to produce the following refinement\n  ```\n  example (a b : Nat) (h : a \u2208 [b]) : b = a :=\n  match b, h with\n  | _, Mem.head => rfl\n  ```\n  which produces the new motive `(x : Nat) \u2192  a \u2208 [x] \u2192 x = a`\n  After this refinement step, the `match` is elaborated successfully.\n\n  This method relies on the fact that the dependent pattern matcher compiler solves equations\n  between indices of indexed inductive families.\n  The following kinds of equations are supported by this compiler:\n  - `x = t`\n  - `t = x`\n  - `ctor ... = ctor ...`\n\n  where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor.\n  Our procedure ensures that \"information\" is not lost, and will *not* succeed in an\n  example such as\n  ```\n  example (a b : Nat) (f : Nat \u2192 Nat) (h : f a \u2208 [f b]) : f b = f a :=\n    match h with\n    | Mem.head => rfl\n  ```\n  and will not add `f b` as a new discriminant. We may add an option in the future to\n  enable this more liberal form of refinement.\n-/\nprivate partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do\n  goType (\u2190 instantiateMVars (\u2190 inferType pattern)) expected\nwhere\n  checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do\n    guard d.isApp\n    guard <| t.getAppNumArgs == d.getAppNumArgs\n    let tFn := t.getAppFn\n    let dFn := d.getAppFn\n    guard <| tFn.isConst && dFn.isConst\n    guard (\u2190 isDefEq tFn dFn)\n\n  -- Visitor for inductive types\n  goType (t d : Expr) : OptionT MetaM (List Nat) := do\n    trace[Meta.debug] \"type {t} =?= {d}\"\n    let t \u2190 whnf t\n    let d \u2190 whnf d\n    checkCompatibleApps t d\n    matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do\n      let tArgs := t.getAppArgs\n      let dArgs := d.getAppArgs\n      for i in [:info.numParams] do\n        let tArg := tArgs[i]\n        let dArg := dArgs[i]\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goType tArg dArg)\n      for i in [info.numParams : tArgs.size] do\n        let tArg := tArgs[i]\n        let dArg := dArgs[i]\n        unless (\u2190 isDefEq tArg dArg) do\n          return i :: (\u2190 goIndex tArg dArg)\n      failure\n\n  -- Visitor for indexed families\n  goIndex (t d : Expr) : OptionT MetaM (List Nat) := do\n    let t \u2190 whnfD t\n    let d \u2190 whnfD d\n    if t.isFVar || d.isFVar then\n      return [] -- Found refinement path\n    else\n      trace[Meta.debug] \"index {t} =?= {d}\"\n      checkCompatibleApps t d\n      matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do\n        let tArgs := t.getAppArgs\n        let dArgs := d.getAppArgs\n        for i in [:info.numParams] do\n          let tArg := tArgs[i]\n          let dArg := dArgs[i]\n          unless (\u2190 isDefEq tArg dArg) do\n            failure\n        for i in [info.numParams : tArgs.size] do\n          let tArg := tArgs[i]\n          let dArg := dArgs[i]\n          unless (\u2190 isDefEq tArg dArg) do\n            return i :: (\u2190 goIndex tArg dArg)\n        failure\n\nprivate partial def eraseIndices (type : Expr) : MetaM Expr := do\n  let type' \u2190 whnfD type\n  matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do\n    let args := type'.getAppArgs\n    let params \u2190 args[:info.numParams].toArray.mapM eraseIndices\n    let result := mkAppN type'.getAppFn params\n    let resultType \u2190 inferType result\n    let (newIndices, _, _) \u2190  forallMetaTelescopeReducing resultType (some (args.size - info.numParams))\n    return mkAppN result newIndices\n\nprivate def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr \u00d7 Expr) :=\n  withReader (fun ctx => { ctx with implicitLambda := false }) do\n    let mut patterns  := #[]\n    let mut matchType := matchType\n    for idx in [:patternStxs.size] do\n      let patternStx := patternStxs[idx]\n      matchType \u2190 whnf matchType\n      match matchType with\n      | Expr.forallE _ d b _ =>\n        let pattern \u2190 do\n          let s \u2190 saveState\n          try\n            liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d\n          catch ex : Exception =>\n            restoreState s\n            match (\u2190 liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (\u2190 eraseIndices d)) with\n            | some pattern =>\n              match \u2190 findDiscrRefinementPath pattern d |>.run with\n              | some path =>\n                trace[Meta.debug] \"refinement path: {path}\"\n                restoreState s\n                -- Wrap the type mismatch exception for the \"discriminant refinement\" feature.\n                throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path }\n              | none => restoreState s; throw ex\n            | none => throw ex\n        matchType := b.instantiate1 pattern\n        patterns  := patterns.push pattern\n      | _ => throwError \"unexpected match type\"\n    return (patterns, matchType)\n\ndef finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do\n  let mut decls := #[]\n  for pdecl in patternVarDecls do\n    match pdecl with\n    | PatternVarDecl.localVar fvarId =>\n      let decl \u2190 getLocalDecl fvarId\n      let decl \u2190 instantiateLocalDeclMVars decl\n      decls := decls.push decl\n    | PatternVarDecl.anonymousVar mvarId fvarId =>\n       let e \u2190 instantiateMVars (mkMVar mvarId);\n       trace[Elab.match] \"finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}\"\n       match e with\n       | Expr.mvar newMVarId _ =>\n         /- Metavariable was not assigned, or assigned to another metavariable. So,\n            we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/\n         assignExprMVar newMVarId (mkFVar fvarId)\n         trace[Elab.match] \"finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}\"\n         let decl \u2190 getLocalDecl fvarId\n         let decl \u2190 instantiateLocalDeclMVars decl\n         decls := decls.push decl\n       | _ => pure ()\n  /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d\u2081 may occur after d\u2082 when d\u2082 depends on d\u2081. -/\n  sortLocalDecls decls\n\nopen Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)\n\nnamespace ToDepElimPattern\n\nstructure State where\n  found      : NameSet := {}\n  localDecls : Array LocalDecl\n  newLocals  : NameSet := {}\n\nabbrev M := StateRefT State TermElabM\n\nprivate def alreadyVisited (fvarId : FVarId) : M Bool := do\n  let s \u2190 get\n  return s.found.contains fvarId\n\nprivate def markAsVisited (fvarId : FVarId) : M Unit :=\n  modify fun s => { s with found := s.found.insert fvarId }\n\nprivate def throwInvalidPattern {\u03b1} (e : Expr) : M \u03b1 :=\n  throwError \"invalid pattern {indentExpr e}\"\n\n/- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/\nprivate def mkLocalDeclFor (mvar : Expr) : M Pattern := do\n  let mvarId := mvar.mvarId!\n  let s \u2190 get\n  match (\u2190 getExprMVarAssignment? mvarId) with\n  | some val => return Pattern.inaccessible val\n  | none =>\n    let fvarId \u2190 mkFreshId\n    let type   \u2190 inferType mvar\n    /- HACK: `fvarId` is not in the scope of `mvarId`\n       If this generates problems in the future, we should update the metavariable declarations. -/\n    assignExprMVar mvarId (mkFVar fvarId)\n    let userName \u2190 mkFreshBinderName\n    let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default;\n    modify fun s =>\n      { s with\n        newLocals  := s.newLocals.insert fvarId,\n        localDecls :=\n        match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with\n        | none   => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar`\n        | some i => s.localDecls.insertAt i newDecl }\n    return Pattern.var fvarId\n\npartial def main (e : Expr) : M Pattern := do\n  let isLocalDecl (fvarId : FVarId) : M Bool := do\n    return (\u2190 get).localDecls.any fun d => d.fvarId == fvarId\n  let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do\n    if (\u2190 alreadyVisited fvarId) then\n      return Pattern.inaccessible e\n    else\n      markAsVisited fvarId\n      return Pattern.var e.fvarId!\n  let mkInaccessible (e : Expr) : M Pattern := do\n    match e with\n    | Expr.fvar fvarId _ =>\n      if (\u2190 isLocalDecl fvarId) then\n        mkPatternVar fvarId e\n      else\n        return Pattern.inaccessible e\n    | _ =>\n      return Pattern.inaccessible e\n  match inaccessible? e with\n  | some t => mkInaccessible t\n  | none =>\n    match e.arrayLit? with\n    | some (\u03b1, lits) =>\n      return Pattern.arrayLit \u03b1 (\u2190 lits.mapM main)\n    | none =>\n      if e.isAppOfArity `namedPattern 3 then\n        let p \u2190 main <| e.getArg! 2\n        match e.getArg! 1 with\n        | Expr.fvar fvarId _ => return Pattern.as fvarId p\n        | _                  => throwError \"unexpected occurrence of auxiliary declaration 'namedPattern'\"\n      else if e.isNatLit || e.isStringLit || e.isCharLit then\n        return Pattern.val e\n      else if e.isFVar then\n        let fvarId := e.fvarId!\n        unless (\u2190 isLocalDecl fvarId) do\n          throwInvalidPattern e\n        mkPatternVar fvarId e\n      else if e.isMVar then\n        mkLocalDeclFor e\n      else\n        let newE \u2190 whnf e\n        if newE != e then\n          main newE\n        else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do\n          let args := e.getAppArgs\n          unless args.size == v.numParams + v.numFields do\n            throwInvalidPattern e\n          let params := args.extract 0 v.numParams\n          let fields := args.extract v.numParams args.size\n          let fields \u2190 fields.mapM main\n          return Pattern.ctor v.name us params.toList fields.toList\n\nend ToDepElimPattern\n\ndef withDepElimPatterns {\u03b1} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl \u2192 Array Pattern \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (patterns, s) \u2190 (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls }\n  let localDecls \u2190 s.localDecls.mapM fun d => instantiateLocalDeclMVars d\n  /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/\n  let lctx \u2190 getLCtx\n  let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx\n  let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx\n  withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do\n    k localDecls patterns\n\nprivate def withElaboratedLHS {\u03b1} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)\n    (k : AltLHS \u2192 Expr \u2192 TermElabM \u03b1) : ExceptT PatternElabException TermElabM \u03b1 := do\n  let (patterns, matchType) \u2190 withSynthesize <| elabPatterns patternStxs matchType\n  id (\u03b1 := TermElabM \u03b1) do\n    let localDecls \u2190 finalizePatternDecls patternVarDecls\n    let patterns \u2190 patterns.mapM (instantiateMVars \u00b7)\n    withDepElimPatterns localDecls patterns fun localDecls patterns =>\n      k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType\n\nprivate def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS \u00d7 Expr) := withRef alt.ref do\n  let (patternVars, alt) \u2190 collectPatternVars alt\n  trace[Elab.match] \"patternVars: {patternVars}\"\n  withPatternVars patternVars fun patternVarDecls => do\n    withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do\n      let rhs \u2190 elabTermEnsuringType alt.rhs matchType\n      let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr\n      let rhs \u2190 if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs\n      trace[Elab.match] \"rhs: {rhs}\"\n      return (altLHS, rhs)\n\n/--\n  Collect problematic index for the \"discriminant refinement feature\". This method is invoked\n  when we detect a type mismatch at a pattern #`idx` of some alternative. -/\nprivate partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do\n  go (\u2190 inferType discr) pathToIndex |>.run\nwhere\n  go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do\n    match path with\n    | [] => return e\n    | i::path =>\n      let e \u2190 whnfD e\n      guard <| e.isApp && i < e.getAppNumArgs\n      go (e.getArg! i) path\n\n/--\n  \"Generalize\" variables that depend on the discriminants.\n\n  Remarks and limitations:\n  - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`.\n    Motivation: users should have control about the actual `match`-expressions in their programs.\n  - We currently do not generalize let-decls.\n  - We abort generalization if the new `matchType` is type incorrect.\n  - Only discriminants that are free variables are considered during specialization.\n  - We \"generalize\" by adding new discriminants and pattern variables. We do not \"clear\" the generalized variables,\n    but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since\n    this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode.\n-/\nprivate def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr \u00d7 Expr \u00d7 Array MatchAltView \u00d7 Bool) := do\n  let gen \u2190\n    match generalizing? with\n    | some g => pure g\n    | _ => isProp matchType\n  if !gen then\n    return (discrs, matchType, altViews, false)\n  else\n    let ysFVarIds \u2190 getFVarsToGeneralize discrs\n    /- let-decls are currently being ignored by the generalizer. -/\n    let ysFVarIds \u2190 ysFVarIds.filterM fun fvarId => return !(\u2190 getLocalDecl fvarId).isLet\n    if ysFVarIds.isEmpty then\n      return (discrs, matchType, altViews, false)\n    else\n      let ys := ysFVarIds.map mkFVar\n      -- trace[Meta.debug] \"ys: {ys}, discrs: {discrs}\"\n      let matchType' \u2190 forallBoundedTelescope matchType discrs.size fun ds type => do\n        let type \u2190 mkForallFVars ys type\n        let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar\n        let type := type.replaceFVars discrs' ds'\n        mkForallFVars ds type\n      -- trace[Meta.debug] \"matchType': {matchType'}\"\n      if (\u2190 isTypeCorrect matchType') then\n        let discrs := discrs ++ ys\n        let altViews \u2190 altViews.mapM fun altView => do\n          let patternVars \u2190 getPatternsVars altView.patterns\n          -- We traverse backwards because we want to keep the most recent names.\n          -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`,\n          -- since it is already shadowed by the second.\n          let ysUserNames \u2190 ys.foldrM (init := #[]) fun ys ysUserNames => do\n            let yDecl \u2190 getLocalDecl ys.fvarId!\n            let mut yUserName := yDecl.userName\n            if ysUserNames.contains yUserName then\n              yUserName \u2190 mkFreshUserName yUserName\n            -- Explicitly provided pattern variables shadow `y`\n            else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then\n              yUserName \u2190 mkFreshUserName yUserName\n            return ysUserNames.push yUserName\n          let ysIds \u2190 ysUserNames.reverse.mapM fun n => return mkIdentFrom (\u2190 getRef) n\n          return { altView with patterns := altView.patterns ++ ysIds }\n        return (discrs, matchType', altViews, true)\n      else\n        return (discrs, matchType, altViews, true)\n\nprivate partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n  loop discrs matchType altViews none\nwhere\n  /-\n    \"Discriminant refinement\" main loop.\n    `first?` contains the first error message we found before updated the `discrs`. -/\n  loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState \u00d7 Exception))\n      : TermElabM (Array Expr \u00d7 Expr \u00d7 Array (AltLHS \u00d7 Expr) \u00d7 Bool) := do\n    let s \u2190 saveState\n    let (discrs', matchType', altViews', refined) \u2190 generalize discrs matchType altViews generalizing?\n    match \u2190 altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run with\n    | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined)\n    | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } =>\n      trace[Meta.debug] \"pathToIndex: {toString pathToIndex}\"\n      let some index \u2190 getIndexToInclude? discrs[patternIdx] pathToIndex\n        | throwEx (\u2190 updateFirst first? ex)\n      trace[Meta.debug] \"index: {index}\"\n      if (\u2190 discrs.anyM fun discr => isDefEq discr index) then\n        throwEx (\u2190 updateFirst first? ex)\n      let first \u2190 updateFirst first? ex\n      s.restore\n      let indices \u2190 collectDeps #[index] discrs\n      let matchType \u2190\n        try\n          updateMatchType indices matchType\n        catch ex =>\n          throwEx first\n      let altViews  \u2190 addWildcardPatterns indices.size altViews\n      let discrs    := indices ++ discrs\n      loop discrs matchType altViews first\n\n  throwEx {\u03b1} (p : SavedState \u00d7 Exception) : TermElabM \u03b1 := do\n    p.1.restore; throw p.2\n\n  updateFirst (first? : Option (SavedState \u00d7 Exception)) (ex : Exception) : TermElabM (SavedState \u00d7 Exception) := do\n    match first? with\n    | none       => return (\u2190 saveState, ex)\n    | some first => return first\n\n  containsFVar (es : Array Expr) (fvarId : FVarId) : Bool :=\n    es.any fun e => e.isFVar && e.fvarId! == fvarId\n\n  /- Update `indices` by including any free variable `x` s.t.\n     - Type of some `discr` depends on `x`.\n     - Type of `x` depends on some free variable in `indices`.\n\n     If we don't include these extra variables in indices, then\n     `updateMatchType` will generate a type incorrect term.\n     For example, suppose `discr` contains `h : @HEq \u03b1 a \u03b1 b`, and\n     `indices` is `#[\u03b1, b]`, and `matchType` is `@HEq \u03b1 a \u03b1 b \u2192 B`.\n     `updateMatchType indices matchType` produces the type\n     `(\u03b1' : Type) \u2192 (b : \u03b1') \u2192 @HEq \u03b1' a \u03b1' b \u2192 B` which is type incorrect\n     because we have `a : \u03b1`.\n     The method `collectDeps` will include `a` into `indices`.\n\n     This method does not handle dependencies among non-free variables.\n     We rely on the type checking method `check` at `updateMatchType`.\n\n     Remark: `indices : Array Expr` does not need to be an array anymore.\n     We should cleanup this code, and use `index : Expr` instead.\n   -/\n  collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do\n    let mut s : CollectFVars.State := {}\n    for discr in discrs do\n      s := collectFVars s (\u2190 instantiateMVars (\u2190 inferType discr))\n    let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar\n    let indicesFVar := indicesFVar.map Expr.fvarId!\n    let mut toAdd := #[]\n    for fvarId in s.fvarSet.toList do\n      unless containsFVar discrs fvarId || containsFVar indices fvarId do\n        let localDecl \u2190 getLocalDecl fvarId\n        let mctx \u2190 getMCtx\n        for indexFVarId in indicesFVar do\n          if mctx.localDeclDependsOn localDecl indexFVarId then\n            toAdd := toAdd.push fvarId\n    let lctx \u2190 getLCtx\n    let indicesFVar := (indicesFVar ++ toAdd).qsort fun fvarId\u2081 fvarId\u2082 =>\n      (lctx.get! fvarId\u2081).index < (lctx.get! fvarId\u2082).index\n    return indicesFVar.map mkFVar ++ indicesNonFVar\n\n  updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do\n    let matchType \u2190 indices.foldrM (init := matchType) fun index matchType => do\n      let indexType \u2190 inferType index\n      let matchTypeBody \u2190 kabstract matchType index\n      let userName \u2190 mkUserNameFor index\n      return Lean.mkForall userName BinderInfo.default indexType matchTypeBody\n    check matchType\n    return matchType\n\n  addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do\n    let hole := mkHole (\u2190 getRef)\n    let wildcards := mkArray num hole\n    return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns }\n\ndef mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult :=\n  Meta.Match.mkMatcher input\n\nregister_builtin_option match.ignoreUnusedAlts : Bool := {\n  defValue := false\n  descr := \"if true, do not generate error if an alternative is not used\"\n}\n\ndef reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do\n  unless result.counterExamples.isEmpty do\n    withHeadRefOnly <| logError m!\"missing cases:\\n{Meta.Match.counterExamplesToMessageData result.counterExamples}\"\n  unless match.ignoreUnusedAlts.get (\u2190 getOptions) || result.unusedAltIdxs.isEmpty do\n    let mut i := 0\n    for alt in altLHSS do\n      if result.unusedAltIdxs.contains i then\n        withRef alt.ref do\n          logError \"redundant alternative\"\n      i := i + 1\n\n/--\n  If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]`\n  Otherwise, return none.\n-/\nprivate def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do\n  assert! altLHSS.length == rhss.size\n  match altLHSS with\n  | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] =>\n    /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/\n    match rhss[0] with\n    | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b\n    | _ => return none\n  | _ => return none\nprivate def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr)\n    : TermElabM Expr := do\n  let mut generalizing? := generalizing?\n  if !matchOptType.isNone then\n    if generalizing? == some true then\n      throwError \"the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided\"\n    generalizing? := some false\n  let (discrs, matchType, altLHSS, isDep, rhss) \u2190 commitIfDidNotPostpone do\n    let \u27e8discrs, matchType, isDep, altViews\u27e9 \u2190 elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType\n    let matchAlts \u2190 liftMacroM <| expandMacrosInPatterns altViews\n    trace[Elab.match] \"matchType: {matchType}\"\n    let (discrs, matchType, alts, refined) \u2190 elabMatchAltViews generalizing? discrs matchType matchAlts\n    let isDep := isDep || refined\n    /-\n     We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be\n     able to elaborate examples such as:\n     ```\n     def f (x : Nat) : Option Nat := none\n\n     def g (xs : List (Nat \u00d7 Nat)) : IO Unit :=\n     xs.forM fun x =>\n       match f x.fst with\n       | _ => pure ()\n     ```\n     If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because\n     the type of `x` is only available after we proces the last argument of `List.forM`.\n\n     We apply pending default types to make sure we can process examples such as\n     ```\n     let (a, b) := (0, 0)\n     ```\n    -/\n    synthesizeSyntheticMVarsUsingDefault\n    let rhss := alts.map Prod.snd\n    let matchType \u2190 instantiateMVars matchType\n    let altLHSS \u2190 alts.toList.mapM fun alt => do\n      let altLHS \u2190 Match.instantiateAltLHSMVars alt.1\n      /- Remark: we try to postpone before throwing an error.\n         The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed.\n         The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here.\n         Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here.\n         ```\n          def bad (ps : Array (Nat \u00d7 Nat)) : Array (Nat \u00d7 Nat) :=\n            (ps.filter fun (p : Prod _ _) =>\n              match p with\n              | (x, y) => x == 0)\n            ++\n            ps\n         ```\n         When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet\n         because `Array.filter` has type `{\u03b1 : Type u_1} \u2192 (\u03b1 \u2192 Bool) \u2192 (as : Array \u03b1) \u2192 optParam Nat 0 \u2192 optParam Nat (Array.size as) \u2192 Array \u03b1`\n         However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`.\n      -/\n      withRef altLHS.ref do\n        for d in altLHS.fvarDecls do\n            if d.hasExprMVar then\n            withExistingLocalDecls altLHS.fvarDecls do\n              tryPostpone\n              throwMVarError m!\"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}\"\n        for p in altLHS.patterns do\n          if p.hasExprMVar then\n            withExistingLocalDecls altLHS.fvarDecls do\n              tryPostpone\n              throwMVarError m!\"invalid match-expression, pattern contains metavariables{indentExpr (\u2190 p.toExpr)}\"\n        pure altLHS\n    return (discrs, matchType, altLHSS, isDep, rhss)\n  if let some r \u2190 if isDep then pure none else isMatchUnit? altLHSS rhss then\n    return r\n  else\n    let numDiscrs := discrs.size\n    let matcherName \u2190 mkAuxName `match\n    let matcherResult \u2190 mkMatcher { matcherName, matchType, numDiscrs, lhss := altLHSS }\n    matcherResult.addMatcher\n    let motive \u2190 forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType\n    reportMatcherResultErrors altLHSS matcherResult\n    let r := mkApp matcherResult.matcher motive\n    let r := mkAppN r discrs\n    let r := mkAppN r rhss\n    trace[Elab.match] \"result: {r}\"\n    return r\n\nprivate def getDiscrs (matchStx : Syntax) : Array Syntax :=\n  matchStx[2].getSepArgs\n\nprivate def getMatchOptType (matchStx : Syntax) : Syntax :=\n  matchStx[3]\n\nprivate def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=\n  let matchOptType := getMatchOptType matchStx;\n  if matchOptType.isNone then do\n    let discrs := getDiscrs matchStx;\n    let allLocal \u2190 discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1]\n    if allLocal then\n      return none\n    else\n      -- We use `foundFVars` to make sure the discriminants are distinct variables.\n      -- See: code for computing \"matchType\" at `elabMatchTypeAndDiscrs`\n      let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : NameSet) := do\n        match discrs with\n        | [] =>\n          let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx \", \");\n          pure (matchStx.setArg 2 discrs)\n        | discr :: discrs =>\n          -- Recall that\n          -- matchDiscr := leading_parser optional (ident >> \":\") >> termParser\n          let term := discr[1]\n          let addAux : TermElabM Syntax := withFreshMacroScope do\n            let d \u2190 `(_discr);\n            unless isAuxDiscrName d.getId do -- Use assertion?\n              throwError \"unexpected internal auxiliary discriminant name\"\n            let discrNew := discr.setArg 1 d;\n            let r \u2190 loop discrs (discrsNew.push discrNew) foundFVars\n            `(let _discr := $term; $r)\n          match (\u2190 isAtomicDiscr? term) with\n          | some x  => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux\n          | none    => addAux\n      return some (\u2190 loop discrs.toList #[] {})\n  else\n    -- We do not pull non atomic discriminants when match type is provided explicitly by the user\n    return none\n\nprivate def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  match expectedType? with\n    | some expectedType => pure expectedType\n    | none              => mkFreshTypeMVar\n\nprivate def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do\n  -- We don't wait for the discriminants types when match type is provided by user\n  if getMatchOptType matchStx |>.isNone then\n    let discrs := getDiscrs matchStx\n    for discr in discrs do\n      let term := discr[1]\n      match (\u2190 isAtomicDiscr? term) with\n      | none   => throwErrorAt discr \"unexpected discriminant\" -- see `expandNonAtomicDiscrs?\n      | some d =>\n        let dType \u2190 inferType d\n        trace[Elab.match] \"discr {d} : {dType}\"\n        tryPostponeIfMVar dType\n\n/-\nWe (try to) elaborate a `match` only when the expected type is available.\nIf the `matchType` has not been provided by the user, we also try to postpone elaboration if the type\nof a discriminant is not available. That is, it is of the form `(?m ...)`.\nWe use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables.\nThis is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.\nSuppose, we are trying to elaborate\n```\nmatch g x with\n  | ... => ...\n```\n`expandNonAtomicDiscrs?` converts it intro\n```\nlet _discr := g x\nmatch _discr with\n  | ... => ...\n```\nThus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`.\nNote that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`.\n\nThis elaboration technique is needed to elaborate terms such as:\n```lean\nxs.filter fun (a, b) => a > b\n```\nwhich are syntax sugar for\n```lean\nList.filter (fun p => match p with | (a, b) => a > b) xs\n```\nWhen we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.\n-/\nprivate def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  tryPostponeIfDiscrTypeIsMVar matchStx\n  match expectedType? with\n  | some expectedType => return expectedType\n  | none              => mkFreshTypeMVar\n\n/-\n```\nleading_parser:leadPrec \"match \" >> sepBy1 matchDiscr \", \" >> optType >> \" with \" >> matchAlts\n```\nRemark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.\n-/\nprivate def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 waitExpectedTypeAndDiscrs stx expectedType?\n  let discrStxs := (getDiscrs stx).map fun d => d\n  let gen?         := getMatchGeneralizing? stx\n  let altViews     := getMatchAlts stx\n  let matchOptType := getMatchOptType stx\n  elabMatchAux gen? discrStxs altViews matchOptType expectedType\n\nprivate def isPatternVar (stx : Syntax) : TermElabM Bool := do\n  match (\u2190 resolveId? stx \"pattern\") with\n  | none   => isAtomicIdent stx\n  | some f => match f with\n    | Expr.const fName _ _ =>\n      match (\u2190 getEnv).find? fName with\n      | some (ConstantInfo.ctorInfo _) => return false\n      | some _                         => return !hasMatchPatternAttribute (\u2190 getEnv) fName\n      | _                              => isAtomicIdent stx\n    | _ => isAtomicIdent stx\nwhere\n  isAtomicIdent (stx : Syntax) : Bool :=\n    stx.isIdent && stx.getId.eraseMacroScopes.isAtomic\n\n-- leading_parser \"match \" >> sepBy1 termParser \", \" >> optType >> \" with \" >> matchAlts\n@[builtinTermElab \u00abmatch\u00bb] def elabMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(match $discr:term with | $y:ident => $rhs:term) =>\n     if (\u2190 isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?\n  | _ => elabMatchDefault stx expectedType?\nwhere\n  elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n    match (\u2190 expandNonAtomicDiscrs? stx) with\n    | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n    | none =>\n      let discrs       := getDiscrs stx;\n      let matchOptType := getMatchOptType stx;\n      if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then\n        throwErrorAt matchOptType \"match expected type should not be provided when discriminants with equality proofs are used\"\n      elabMatchCore stx expectedType?\n\nbuiltin_initialize\n  registerTraceClass `Elab.match\n\n-- leading_parser:leadPrec \"nomatch \" >> termParser\n@[builtinTermElab \u00abnomatch\u00bb] def elabNoMatch : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(nomatch $discrExpr) =>\n    match \u2190 isLocalIdent? discrExpr with\n    | some _ =>\n      let expectedType \u2190 waitExpectedType expectedType?\n      let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]\n      elabMatchAux none #[discr] #[] mkNullNode expectedType\n    | _ =>\n      let stxNew \u2190 `(let _discr := $discrExpr; nomatch _discr)\n      withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | _ => throwUnsupportedSyntax\n\nend Lean.Elab.Term\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/Elab/Match.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16026601628447606, "lm_q2_score": 0.04742586863357034, "lm_q1q2_score": 0.007600755034733207}}
{"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\u207b\u00b9.\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\u207b\u00b9`. -/\ndef ProFiltPseuNormGrpWithTinv (r : \u211d\u22650) : Type (u+1) :=\nbundled (@profinitely_filtered_pseudo_normed_group_with_Tinv r)\n\nnamespace ProFiltPseuNormGrpWithTinv\n\nvariables (r' : \u211d\u22650)\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') := \u27e8\u27e9\n\nlocal attribute [instance] bundled_hom\n\n/-\ninstance bundled_hom : bundled_hom (@comphaus_filtered_pseudo_normed_group_with_Tinv_hom r') :=\n\u27e8@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'\u27e9\n-/\n\nattribute [derive [\u03bb \u03b1, has_coe_to_sort \u03b1 (Sort*), large_category, concrete_category]]\n  ProFiltPseuNormGrpWithTinv\n\n/-- Construct a bundled `ProFiltPseuNormGrpWithTinv` from the underlying type and typeclass. -/\ndef of (r' : \u211d\u22650) (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\u27e8{ \u03b1 := punit, str := punit.profinitely_filtered_pseudo_normed_group_with_Tinv r' }\u27e9\n\ninstance : inhabited (ProFiltPseuNormGrpWithTinv r') := \u27e80\u27e9\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') : \u21d1(\ud835\udfd9 V) = id := rfl\n\n@[simp] lemma coe_comp {A B C : ProFiltPseuNormGrpWithTinv r'} (f : A \u27f6 B) (g : B \u27f6 C) :\n  \u21d1(f \u226b g) = g \u2218 f := rfl\n\n@[simp] lemma coe_comp_apply {A B C : ProFiltPseuNormGrpWithTinv r'} (f : A \u27f6 B) (g : B \u27f6 C) (x : A) :\n  (f \u226b 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 : \u211d\u22650)\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 : \u211d\u22650) : ProFiltPseuNormGrp \u2964 Profinite :=\n-- { obj := \u03bb M, \u27e8Top.of (filtration M c)\u27e9,\n--   map := \u03bb M\u2081 M\u2082 f, \u27e8f.level c, f.level_continuous c\u27e9,\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\u2081 M\u2082 : ProFiltPseuNormGrpWithTinv.{u} r'}\nvariables {f : M\u2081 \u27f6 M\u2082}\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\u2081 \u2243+ M\u2082) (he : \u2200 x, f x = e x)\n  (strict : \u2200 \u2983c x\u2984, x \u2208 filtration M\u2082 c \u2192 e.symm x \u2208 filtration M\u2081 c) :\n  M\u2081 \u2245 M\u2082 :=\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\u2081 \u2243+ M\u2082) (he : \u2200 x, f x = e x)\n  (strict : \u2200 \u2983c x\u2984, x \u2208 filtration M\u2082 c \u2192 e.symm x \u2208 filtration M\u2081 c) (x : M\u2081) :\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\u2081 \u2243+ M\u2082) (he : \u2200 x, f x = e x)\n  (strict : \u2200 \u2983c x\u2984, x \u2208 filtration M\u2082 c \u2192 e.symm x \u2208 filtration M\u2081 c) (x : M\u2082) :\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\u2081 \u2243+ M\u2082)\n  (strict' : \u2200 c x, x \u2208 filtration M\u2081 c \u2194 e x \u2208 filtration M\u2082 c)\n  (continuous' : \u2200 c, continuous (pseudo_normed_group.level e (\u03bb c x, (strict' c x).1) c))\n  (map_Tinv' : \u2200 x, e (Tinv x) = Tinv (e x)) :\n  M\u2081 \u2245 M\u2082 :=\n@iso_of_equiv_of_strict r' M\u2081 M\u2082\n {to_fun := e,\n  strict' := \u03bb c x, (strict' c x).1,\n  continuous' := continuous',\n  map_Tinv' := map_Tinv',\n  ..e.to_add_monoid_hom } e (\u03bb _, 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\u2081 \u2243+ M\u2082)\n  (strict' : \u2200 c x, x \u2208 filtration M\u2081 c \u2194 e x \u2208 filtration M\u2082 c)\n  (continuous' : \u2200 c, continuous (pseudo_normed_group.level e (\u03bb c x, (strict' c x).1) c))\n  (map_Tinv' : \u2200 x, e (Tinv x) = Tinv (e x))\n  (x : M\u2081) :\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\u2081 \u2243+ M\u2082)\n  (strict' : \u2200 c x, x \u2208 filtration M\u2081 c \u2194 e x \u2208 filtration M\u2082 c)\n  (continuous' : \u2200 c, continuous (pseudo_normed_group.level e (\u03bb c x, (strict' c x).1) c))\n  (map_Tinv' : \u2200 x, e (Tinv x) = Tinv (e x))\n  (x : M\u2082) :\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 : \u2115) : ProFiltPseuNormGrpWithTinv.{u} r' \u2964 ProFiltPseuNormGrpWithTinv.{u} r' :=\n{ obj := \u03bb M, of r' $ M ^ n,\n  map := \u03bb M\u2081 M\u2082 f, profinitely_filtered_pseudo_normed_group_with_Tinv.pi_map r' _ _ (\u03bb i, f),\n  map_id' := \u03bb M, by { ext, refl },\n  map_comp' := by { intros, ext, refl } }\n\n@[simps]\ndef Pow_Pow_X_equiv (N n : \u2115) :\n  M ^ (N * n) \u2243+ (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' := \u03bb 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 : \u2115) (M : ProFiltPseuNormGrpWithTinv.{u} r') :\n  (Pow r' N \u22d9 Pow r' n).obj M \u2245 (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 [\u2190 (filtration_pi_homeo (\u03bb _, M ^ N) c).comp_continuous_iff,\n        \u2190 (filtration_pi_homeo (\u03bb _, M) c).symm.comp_continuous_iff'],\n    apply continuous_pi,\n    intro i,\n    rw [\u2190 (filtration_pi_homeo (\u03bb _, M) c).comp_continuous_iff],\n    apply continuous_pi,\n    intro j,\n    have := @continuous_apply _ (\u03bb _, filtration M c) _ (fin_prod_fin_equiv (j, i)),\n    dsimp [function.comp] at this \u22a2,\n    simpa only [subtype.coe_eta],\n  end\n  (by { intros, ext, refl })\n\n@[simps hom inv]\ndef Pow_mul (N n : \u2115) : Pow r' (N * n) \u2245 Pow r' N \u22d9 Pow r' n :=\nnat_iso.of_components (\u03bb 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 \u27e8_, _\u27e9 \u27e8_, _\u27e9; simp))\n\nclass LawfulCoe (\u03b1 \u03b2) [a : ReactorType \u03b1] [b : ReactorType \u03b2] extends Coe \u03b1 \u03b2 where\n  ports : b.ports \u2218 coe = a.ports                    := by rfl\n  acts  : b.acts  \u2218 coe = a.acts                     := by rfl\n  rcns  : b.rcns  \u2218 coe = a.rcns                     := by rfl\n  state : b.state \u2218 coe = a.state                    := by rfl\n  nest  : b.nest  \u2218 coe = (Partial.map coe) \u2218 a.nest := by lawfulCoe_nest_proof\n  inj   : coe.Injective                              := by lawfulCoe_inj_proof\n\nnamespace LawfulCoe\n\nvariable [a : ReactorType \u03b1] [b : ReactorType \u03b2] [c : LawfulCoe \u03b1 \u03b2] {rtr : \u03b1}\n\ntheorem nest' [a : ReactorType \u03b1] [b : ReactorType \u03b2] [c : LawfulCoe \u03b1 \u03b2] :\n    b.nest (c.coe rtr) = (a.nest rtr).map c.coe := by\n  rw [\u2190Function.comp_apply (f := ReactorType.nest), c.nest]\n  simp\n\ntheorem coe_ext_iff [ReactorType \u03b1] [ReactorType \u03b2] [c : LawfulCoe \u03b1 \u03b2] \n    {rtr\u2081 rtr\u2082 : \u03b1} : rtr\u2081 = rtr\u2082 \u2194 (rtr\u2081 : \u03b2) = (rtr\u2082 : \u03b2) :=\n  \u27e8(congr_arg _ \u00b7), (c.inj \u00b7)\u27e9\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 \u2191o := by\n  split <;> simp_all [cpt?, \u2190c.rcns, \u2190c.ports, \u2190c.acts, \u2190c.state]\n  simp [c.nest', Partial.map_val]\n  exists o\n\ntheorem lower_mem_cpt? (cpt) (h : i \u2208 a.cpt? cpt rtr) : i \u2208 b.cpt? cpt rtr :=\n  \u27e8h.choose, c.lower_cpt?_eq_some _ h.choose_spec\u27e9 \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 \u2039Component.Valued\u203a\n  all_goals simp_all [cpt?, \u2190c.rcns, \u2190c.ports, \u2190c.acts, \u2190c.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 \u2191o) : \n    a.cpt? cpt rtr i = some o := by\n  split at h <;> simp_all [cpt?, \u2190c.rcns, \u2190c.ports, \u2190c.acts, \u2190c.state]\n  simp [c.nest', Partial.map_val] at h\n  have \u27e8_, _, h\u27e9 := h\n  cases c.inj h\n  assumption\n\ntheorem lift_nest_eq_some {i : ID} (h : b.nest rtr i = some n\u2082) : \n    \u2203 n\u2081, (a.nest rtr i = some n\u2081) \u2227 ((n\u2081 : \u03b2) = n\u2082) := 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 \u2208 b.cpt? cpt rtr) (hc : cpt \u2260 .rtr := by simp) : \n    i \u2208 a.cpt? cpt rtr := by\n  cases cpt <;> try cases \u2039Component.Valued\u203a  \n  case rtr => contradiction\n  all_goals exact \u27e8h.choose, c.lift_cpt?_eq_some _ h.choose_spec\u27e9 \n\nend LawfulCoe\n\ndef Member.fromLawfulCoe [ReactorType \u03b1] [ReactorType \u03b2] [c : LawfulCoe \u03b1 \u03b2] {rtr : \u03b1} : \n    (Member cpt i rtr) \u2192 Member cpt i (rtr : \u03b2)\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 \u03b1] [ReactorType \u03b2] [c : LawfulCoe \u03b1 \u03b2] {rtr : \u03b1} :\n    Coe (Member cpt i rtr) (Member cpt i (rtr : \u03b2)) where\n  coe := Member.fromLawfulCoe\n\ninstance [ReactorType \u03b1] [e : Extensional \u03b2] [c : LawfulCoe \u03b1 \u03b2] : Extensional \u03b1 where\n  ext_iff := by\n    intro rtr\u2081 rtr\u2082 \n    simp [c.coe_ext_iff, e.ext_iff, \u2190c.ports, \u2190c.acts, \u2190c.rcns, \u2190c.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 \u03b1] [b : ReactorType.WellFounded \u03b2] [c : LawfulCoe \u03b1 \u03b2] : \n    ReactorType.WellFounded \u03b1 where\n  wf := by\n    suffices h : InvImage Nested c.coe = Nested from h \u25b8 InvImage.wf c.coe b.wf\n    funext rtr\u2081 rtr\u2082\n    simp [Nested, InvImage, c.nest', Partial.map_val]\n    exact \u27e8fun \u27e8_, \u27e8_, hn, h\u27e9\u27e9 => \u27e8_, c.inj h \u25b8 hn\u27e9, fun \u27e8i, h\u27e9 => \u27e8i, rtr\u2081, by simp [h]\u27e9\u27e9  \n\nvariable [ReactorType \u03b1] [ReactorType \u03b2] in section\n\ntheorem RootEqualUpTo.lift [l : LawfulCoe \u03b1 \u03b2] {rtr\u2081 rtr\u2082 : \u03b1} \n    (e : RootEqualUpTo cpt i (rtr\u2081 : \u03b2) (rtr\u2082 : \u03b2)) : RootEqualUpTo cpt i rtr\u2081 rtr\u2082 := by\n  intro c j h\n  have he := e h\n  cases h\u2081 : cpt? c (rtr\u2081 : \u03b2) j <;> cases h\u2082 : cpt? c (rtr\u2082 : \u03b2) j <;> simp_all\n  case none.none => simp [l.lift_cpt?_eq_none _ h\u2081, l.lift_cpt?_eq_none _ h\u2082]\n  case some.some => \n    cases c <;> try cases \u2039Reactor.Component.Valued\u203a \n    all_goals try simp [l.lift_cpt?_eq_some _ h\u2081, l.lift_cpt?_eq_some _ h\u2082]\n    case rtr =>\n      have \u27e8_, _, h\u2081'\u27e9 := l.lift_nest_eq_some h\u2081\n      have \u27e8_, _, h\u2082'\u27e9 := l.lift_nest_eq_some h\u2082\n      subst h\u2081'\n      simp [l.lift_cpt?_eq_some _ h\u2081, l.lift_cpt?_eq_some _ h\u2082]\n\ndef LawfulMemUpdate.lift [c : LawfulCoe \u03b1 \u03b2] {rtr\u2081 rtr\u2082 : \u03b1} :\n    (LawfulMemUpdate cpt i f (rtr\u2081 : \u03b2) (rtr\u2082 : \u03b2)) \u2192 LawfulMemUpdate cpt i f rtr\u2081 rtr\u2082\n  | final e h\u2081 h\u2082 (o := o) => \n    have h\u2081 : cpt? cpt rtr\u2081 i = some o     := by cases cpt <;> exact c.lift_cpt?_eq_some _ h\u2081\n    have h\u2082 : cpt? cpt rtr\u2082 i = some (f o) := by cases cpt <;> exact c.lift_cpt?_eq_some _ h\u2082\n    .final e.lift h\u2081 h\u2082\n  | nest (n\u2081 := n\u2081) (n\u2082 := n\u2082) e h\u2081 h\u2082 u (j := j) => \n    have o\u2081 := c.lift_nest_eq_some h\u2081\n    have o\u2082 := c.lift_nest_eq_some h\u2082\n    have \u27e8h\u2081, h\u2081'\u27e9 := o\u2081.choose_spec\n    have \u27e8h\u2082, h\u2082'\u27e9 := o\u2082.choose_spec \n    let u' : LawfulMemUpdate cpt i f (o\u2081.choose : \u03b2) (o\u2082.choose : \u03b2) := cast (by simp [h\u2081', h\u2082']) u\n    .nest e.lift h\u2081 h\u2082 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\u2081 -u.lift\u2192 rtr\u2082\n--      |             |\n--     coe           coe\n--      \u2193             \u2193\n-- (rtr\u2081 : \u03b2) -u\u2192 (rtr\u2082 : \u03b2)\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 \u03b1 \u03b2] {rtr\u2081 rtr\u2082 : \u03b1} :\n    (LawfulUpdate cpt i f (rtr\u2081 : \u03b2) (rtr\u2082 : \u03b2)) \u2192 LawfulUpdate cpt i f rtr\u2081 rtr\u2082\n  | update u => update u.lift\n  | notMem h eq =>  \n    let u := notMem (byContradiction (h.false $ not_isEmpty_iff.mp \u00b7 |>.some.fromLawfulCoe)) rfl\n    (c.inj eq) \u25b8 u \n\nend\n\nscoped macro \"lawfulUpdatableCoe_update_coe_comm_proof\" : tactic =>\n  `(tactic| simp [Updatable.update, Coe.coe])\n\nclass LawfulUpdatableCoe (\u03b1 \u03b2) [a : Updatable \u03b1] [b : Updatable \u03b2] extends LawfulCoe \u03b1 \u03b2 where\n  update_coe_comm : \n    \u2200 {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 \u03b1] [LawfulUpdatable \u03b2] [c : LawfulUpdatableCoe \u03b1 \u03b2] : LawfulUpdatable \u03b1 where\n  lawful rtr cpt i f := c.update_coe_comm \u25b8 LawfulUpdatable.lawful (rtr : \u03b2) cpt i f |>.lift \n\nvariable [a : Indexable \u03b1] [b : Indexable \u03b2] [c : LawfulCoe \u03b1 \u03b2] {rtr : \u03b1}\n\nnamespace LawfulCoe\n\ntheorem lower_container_eq {m : Member cpt i rtr} (h : m.container = con) : \n    (m : Member cpt i (rtr : \u03b2)).container = \u2191con := by\n  induction m\n  case final =>\n    simp [Member.container] at h \u22a2\n    simp [\u2190h]\n  case nest m hi => \n    cases m \n    case final => \n      simp [Member.fromLawfulCoe, Member.container] at h \u22a2\n      simp [\u2190 h] \n    case nest hi =>\n      simp [Member.container] at h\n      simp [\u2190hi h, Member.fromLawfulCoe, Member.container]\n\ntheorem lower_con?_some (h : rtr[cpt][i]& = some con) : (rtr : \u03b2)[cpt][i]& = some \u2191con := by\n  simp [Indexable.con?] at h \u22a2\n  split at h\n  case inr => contradiction \n  case inl n =>\n    injection h with h\n    simp [(\u27e8n.some\u27e9 : Nonempty (Member cpt i (rtr : \u03b2)))]\n    simp [\u2190c.lower_container_eq h, (\u27e8n.some\u27e9 : Nonempty (Member cpt i (rtr : \u03b2)))]\n    congr\n    apply b.unique_ids.allEq\n\ntheorem lower_obj?_some {i o} (h : rtr[cpt][i] = some o) : (rtr : \u03b2)[cpt][i] = some \u2191o := by\n  cases cpt <;> try cases i\n  case rtr.none => simp_all [Indexable.obj?]\n  all_goals\n    have \u27e8_, h\u2081, h\u2082\u27e9 := a.obj?_to_con?_and_cpt? h\n    simp [Indexable.obj?, bind, c.lower_con?_some h\u2081, c.lower_cpt?_eq_some _ h\u2082]\n\ntheorem lower_mem_obj? {i} (h : i \u2208 rtr[cpt]) : i \u2208 (rtr : \u03b2)[cpt] :=\n  Partial.mem_iff.mpr \u27e8_, c.lower_obj?_some (Partial.mem_iff.mp h).choose_spec\u27e9 \n\nend LawfulCoe\n\ntheorem Dependency.lower [c : LawfulCoe \u03b1 \u03b2] (d : i\u2081 <[rtr] i\u2082) : i\u2081 <[(rtr : \u03b2)] i\u2082 := by\n  induction d with\n  | prio h\u2081 h\u2082 h\u2083 =>\n    exact prio (c.lower_obj?_some h\u2081) (c.lower_cpt?_eq_some .rcn h\u2082) (c.lower_cpt?_eq_some .rcn h\u2083) \n           \u2039_\u203a \u2039_\u203a\n  | mutNorm h\u2081 h\u2082 h\u2083 => \n    exact mutNorm (c.lower_obj?_some h\u2081) (c.lower_cpt?_eq_some .rcn h\u2082)\n          (c.lower_cpt?_eq_some .rcn h\u2083) \u2039_\u203a \u2039_\u203a\n  | depOverlap h\u2081 h\u2082 => \n    exact depOverlap (c.lower_obj?_some h\u2081) (c.lower_obj?_some h\u2082) \u2039_\u203a \u2039_\u203a \u2039_\u203a\n  | mutNest h\u2081 h\u2082 h\u2083 _ h\u2084 => \n    exact mutNest (c.lower_obj?_some h\u2081) (c.lower_cpt?_eq_some .rtr h\u2082)\n          (c.lower_cpt?_eq_some .rcn h\u2083) \u2039_\u203a (c.lower_mem_cpt? .rcn h\u2084) \n  | trans _ _ d\u2081 d\u2082 => \n    exact trans d\u2081 d\u2082\n\ntheorem Dependency.Acyclic.lift [LawfulCoe \u03b1 \u03b2] (a : Acyclic (rtr : \u03b2)) : 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) (\u03b2 := \u03b2) \u25b8 hc \n    simp [Partial.map_val] at h\n    obtain \u27e8_, _, h\u27e9 := 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 \u03b1] [ReactorType \u03b2] [LawfulCoe \u03b1 \u03b2] {rtr : \u03b1} : \n    (ValidDependency (rtr : \u03b2) rk dk d) \u2192 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\u2081 h\u2082 h\u2083 => \n    $(Lean.mkIdentFrom name $ `Wellformed ++ name.getId) \u2039Wellformed (_ : \u03b2)\u203a \n      (LawfulCoe.lower_obj?_some h\u2081) (LawfulCoe.lower_cpt?_eq_some .rcn h\u2082) \n      (LawfulCoe.lower_cpt?_eq_some .rcn h\u2083)\n)\n\ntheorem lift [Indexable \u03b1] [Indexable \u03b2] [c : LawfulCoe \u03b1 \u03b2] {rtr : \u03b1} (wf : Wellformed (rtr : \u03b2)) : \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\u2081 h\u2082 h\u2083 := \n    wf.valid_deps (c.lower_obj?_some h\u2081) (c.lower_cpt?_eq_some .rcn h\u2082) h\u2083 |>.lift\n  unique_inputs h\u2081 h\u2082 _ h\u2083 := \n    wf.unique_inputs (c.lower_obj?_some h\u2081) (c.lower_obj?_some h\u2082) \u2039_\u203a (c.lower_mem_obj? h\u2083)\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": "\n\n-- This file almost qualifies for inclusion in the `core` dir, but\n-- the hooks into non-core pieces, i.e. providing defaults, and also\n-- the external interface it exports is enough to keep it out here.\nimport .core\nimport .module\n\n-- Default strategy, metric, and tracer used as a fallback by the engine\n-- (so must be present)\nimport .strategy.pexplore\nimport .metric.edit_distance\nimport .tracer.unit\n\nimport tactic.iconfig\n\nopen tactic\n\nvariables {\u03b1 \u03b2 \u03b3 \u03b4 : Type}\n\nnamespace tactic.rewrite_search\n\nmeta def default_strategy : expr ff := expr.const `pexplore []\nmeta def default_metric   : expr ff := expr.const `edit_distance []\nmeta def default_tracer   : expr ff := expr.const `unit []\n\n-- Another thing is that we can use our super great config system\n-- when invoking `iconfig_xxx` commands, by just setting up the original\n-- ennvironment.\n\n-- Then, we will finally be able to do the fail-one-at-a-time\n-- thing too.\n\nopen discovery.persistence\n\nmeta def mk_initial_search_state (conf : config) (try_simp : bool) (rs : list (expr \u00d7 bool)) (s : strategy \u03b1 \u03b2 \u03b3 \u03b4) (m : metric \u03b1 \u03b2 \u03b3 \u03b4) (tr : tracer \u03b1 \u03b2 \u03b3 \u03b4) (strat_state : \u03b1) (metric_state : \u03b2) (tr_state : \u03b4) (prog : discovery.progress) : search_state \u03b1 \u03b2 \u03b3 \u03b4 :=\n\u27e8tr, conf, {try_simp := try_simp}, rs, strat_state, metric_state, table.create, table.create, table.create, none, tr_state, prog, statistics.init\u27e9\n\nmeta def mk_instance (conf : config) (try_simp : bool) (rs : list (expr \u00d7 bool)) (s : strategy \u03b1 \u03b2 \u03b3 \u03b4) (m : metric \u03b1 \u03b2 \u03b3 \u03b4) (tr : tracer \u03b1 \u03b2 \u03b3 \u03b4) (s_state : \u03b1) (m_state : \u03b2) (tr_state : \u03b4) (prog : discovery.progress) (eqn : sided_pair expr) : tactic (packet inst) := do\n  i \u2190 tactic.up (do\n    let g := mk_initial_search_state conf try_simp rs s m tr s_state m_state tr_state prog,\n    (g, vl) \u2190 g.add_root_vertex eqn.l side.L,\n    (g, vr) \u2190 g.add_root_vertex eqn.r side.R,\n    g \u2190 s.startup g m vl vr,\n    pure (\u27e8m, s, g\u27e9 : inst \u03b1 \u03b2 \u03b3 \u03b4)\n  ),\n  return \u27e8\u27e8\u03b1, \u03b2, \u03b3, \u03b4\u27e9, i.down\u27e9\n\nmeta def try_mk_search_instance (cfg : iconfig.result) (prog : discovery.progress) (rs : list (expr \u00d7 bool)) (eqn : sided_pair expr) : tactic (option (packet inst)) := do\n  ulift.up conf \u2190 tactic.up $ cfg.struct `tactic.rewrite_search.config tactic.rewrite_search.config,\n  stack \u2190 instantiate_modules\n    (cfg.ipexpr `strategy default_strategy)\n    (cfg.ipexpr `metric   default_metric)\n    (cfg.ipexpr `tracer   default_tracer),\n\n  init_result.try \"strategy\" stack.st.init $ \u03bb strat_state,\n  init_result.try \"metric\"   stack.mt.init $ \u03bb metric_state,\n  init_result.try \"tracer\"   stack.tr.init $ \u03bb tracer_state, do\n  option.some <$>\n    mk_instance conf (cfg.ibool `try_simp ff) rs stack.st stack.mt stack.tr strat_state metric_state tracer_state prog eqn\n\nmeta def try_search (cfg : iconfig.result) (prog : discovery.progress) (rs : list (expr \u00d7 bool)) (eqn : sided_pair expr) : tactic (option string) := tactic.down $ do\n  i \u2190 try_mk_search_instance cfg prog rs eqn,\n  tactic.up $ match i with\n  | none := return none\n  | some i := do\n    (i, result) \u2190 i.v.search_until_solved,\n    match result with\n    | search_result.failure reason := fail reason\n    | search_result.success proof steps := do\n      exact proof,\n      some <$> i.explain proof steps\n    end\n  end\n\n-- TODO If try_search fails due to a failure to init any of the tracer, metric,\n-- or strategy we try again using the \"fallback\" default versions of all three\n-- of these. Instead we could be more thoughtful, and try again only replacing\n-- the failing one of these with its respective fallback module version.\n\nmeta def mk_fallback_config (cfg : iconfig.result) : iconfig.result :=\n  let cfg := cfg.clear `strategy in\n  let cfg := cfg.clear `metric in\n  let cfg := cfg.clear `tracer in\n  cfg\n\nmeta def rewrite_search_pair (cfg : iconfig.result) (prog : discovery.progress) (rs : list (expr \u00d7 bool)) (eqn : sided_pair expr) : tactic string := do\n  result \u2190 try_search cfg prog rs eqn,\n  match result with\n  | some str := return str\n  | none := do\n    trace \"\\nError initialising rewrite_search instance, falling back to emergency config!\",\n    result \u2190 try_search (mk_fallback_config cfg) prog rs eqn,\n    match result with\n    | some str := return str\n    | none := fail \"Could not initialise emergency rewrite_search instance!\"\n    end\n  end\n\n-- TODO: @Keeley: instead of something like\n--     `exprs \u2190 close_under_apps exprs`\n-- the ideal thing would be to look for lemmas that have a metavariable\n-- for their LHS, and try substituting in hypotheses to these.\n\nmeta def collect_rw_lemmas (cfg : collect_config) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr \u00d7 bool)) : tactic (discovery.progress \u00d7 list (expr \u00d7 bool)) := do\n  let per := if cfg.help_me then discovery.persistence.try_everything else per,\n  (prog, rws) \u2190 discovery.collect use_suggest_annotations per cfg.suggest extra_names,\n  hyp_rws \u2190 discovery.rewrite_list_from_hyps,\n  let rws := rws ++ extra_rws ++ hyp_rws,\n\n  locs \u2190 local_context,\n  rws \u2190 if cfg.inflate_rws then list.join <$> (rws.mmap $ discovery.inflate_rw locs)\n        else pure rws,\n  return (prog, rws)\n\nmeta def rewrite_search_target (cfg : iconfig rewrite_search) (try_harder : bool) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr \u00d7 bool)) : tactic string := do\n  cfg \u2190 iconfig.read cfg,\n  let cfg := if \u00actry_harder then cfg\n             else cfg.setl [\n               (`try_simp, cfgopt.value.bool tt),\n               (`max_discovers, cfgopt.value.nat $ max 3 $ cfg.inat `max_discovers 3)\n             ],\n  t \u2190 target,\n  if t.has_meta_var then\n    fail \"rewrite_search is not suitable for goals containing metavariables\"\n  else skip,\n\n  collect_cfg \u2190 cfg.struct `tactic.rewrite_search.collect_config tactic.rewrite_search.collect_config,\n  (prog, rws) \u2190 collect_rw_lemmas collect_cfg use_suggest_annotations per extra_names extra_rws,\n\n  (lhs, rhs) \u2190 rw_equation.split t,\n  rewrite_search_pair cfg prog rws \u27e8lhs, rhs\u27e9\n\nprivate meta def add_simps : simp_lemmas \u2192 list name \u2192 tactic simp_lemmas\n| s []      := return s\n| s (n::ns) := do s' \u2190 s.add_simp n, add_simps s' ns\n\nprivate meta def add_expr (s : simp_lemmas) (u : list name) (e : expr) : tactic (simp_lemmas \u00d7 list name) :=\ndo\n  let e := e.erase_annotations,\n  match e with\n  | expr.const n _           :=\n    (do b \u2190 is_valid_simp_lemma_cnst n, guard b, s \u2190 s.add_simp n, return (s, u))\n    <|>\n    (do eqns \u2190 get_eqn_lemmas_for tt n, guard (eqns.length > 0), s \u2190 add_simps s eqns, return (s, u))\n    <|>\n    (do env \u2190 get_env, guard (env.is_projection n).is_some, return (s, n::u))\n    <|>\n    fail n\n  | _ :=\n    (do b \u2190 is_valid_simp_lemma e, guard b, s \u2190 s.add e, return (s, u))\n    <|>\n    fail e\n  end\n\nmeta def simp_search_target (cfg : iconfig rewrite_search) (use_suggest_annotations : bool) (per : discovery.persistence) (extra_names : list name) (extra_rws : list (expr \u00d7 bool)) : tactic unit := do\n  t \u2190 target,\n  cfg \u2190 iconfig.read cfg,\n\n  collect_cfg \u2190 cfg.struct `collect_config collect_config,\n  (prog, rws) \u2190 collect_rw_lemmas collect_cfg use_suggest_annotations per extra_names extra_rws,\n\n  if cfg.ibool `trace_rules ff then do\n    rs_strings \u2190 rws.mmap pp_rule,\n    trace (\"simp_search using:\\n---\\n\" ++ (string.intercalate \"\\n\" rs_strings) ++ \"\\n---\")\n  else skip,\n\n  (s, to_unfold) \u2190 mk_simp_set ff [] [] >>= \u03bb sset, rws.mfoldl (\u03bb c e, add_expr c.1 c.2 e.1 <|> return c) sset,\n  (n, pf) \u2190 simplify s to_unfold t {contextual := tt} `eq failed,\n  replace_target n pf >> try tactic.triv >> try (tactic.reflexivity reducible)\n\nend tactic.rewrite_search\n\nnamespace tactic\n\nopen tactic.rewrite_search\nopen tactic.rewrite_search.discovery.persistence\n\nmeta def rewrite_search (cfg : iconfig rewrite_search) (try_harder : bool := ff) : tactic string :=\n  rewrite_search_target cfg try_harder tt try_everything [] []\n\nmeta def rewrite_search_with (rs : list interactive.rw_rule) (cfg : iconfig rewrite_search) (try_harder : bool := ff) : tactic string := do\n  extra_rws \u2190 discovery.rewrite_list_from_rw_rules rs,\n  rewrite_search_target cfg try_harder tt speedy [] extra_rws\n\nmeta def rewrite_search_using (as : list name) (cfg : iconfig rewrite_search) (try_harder : bool := ff) : tactic string := do\n  extra_names \u2190 discovery.load_attr_list as,\n  rewrite_search_target cfg try_harder ff try_bundles extra_names []\n\nmeta def simp_search (cfg : iconfig rewrite_search) : tactic unit := do\n  simp_search_target cfg tt try_everything [] []\n\nmeta def simp_search_with (rs : list interactive.rw_rule) (cfg : iconfig rewrite_search) : tactic unit := do\n  extra_rws \u2190 discovery.rewrite_list_from_rw_rules rs,\n  simp_search_target cfg tt try_everything [] extra_rws\n\nend tactic\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/src/tactic/rewrite_search/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.02333077135506419, "lm_q1q2_score": 0.007564661958842612}}
{"text": "import control.traversable.derive\nimport tactic\n\nuniverses u\n\n/- traversable -/\nopen tactic.interactive\n\nrun_cmd do\nlawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list\n-- the above creates local instances of `traversable` and `is_lawful_traversable`\n-- for `list`\n-- do not put in instances because they are not universe polymorphic\n\n@[derive [traversable, is_lawful_traversable]]\nstructure my_struct (\u03b1 : Type) :=\n  (y : \u2124)\n\n@[derive [traversable, is_lawful_traversable]]\ninductive either (\u03b1 : Type u)\n| left : \u03b1 \u2192 \u2124 \u2192 either\n| right : \u03b1 \u2192 either\n\n@[derive [traversable, is_lawful_traversable]]\nstructure my_struct2 (\u03b1 : Type u) : Type u :=\n  (x : \u03b1)\n  (y : \u2124)\n  (\u03b7 : list \u03b1)\n  (k : list (list \u03b1))\n\n@[derive [traversable, is_lawful_traversable]]\ninductive rec_data3 (\u03b1 : Type u) : Type u\n| nil : rec_data3\n| cons : \u2115 \u2192 \u03b1 \u2192 rec_data3 \u2192 rec_data3 \u2192 rec_data3\n\n@[derive traversable]\nmeta structure meta_struct (\u03b1 : Type u) : Type u :=\n  (x : \u03b1)\n  (y : \u2124)\n  (z : list \u03b1)\n  (k : list (list \u03b1))\n  (w : expr)\n\n@[derive [traversable,is_lawful_traversable]]\ninductive my_tree (\u03b1 : Type)\n| leaf : my_tree\n| node : my_tree \u2192 my_tree \u2192 \u03b1 \u2192 my_tree\n\nsection\nopen my_tree (hiding traverse)\n\ndef x : my_tree (list nat) :=\nnode\n  leaf\n  (node\n    (node leaf leaf [1,2,3])\n    leaf\n    [3,2])\n  [1]\n\n/-- demonstrate the nested use of `traverse`. It traverses each node of the tree and\nin each node, traverses each list. For each `\u2115` visited, apply an action `\u2115 -> state (list \u2115) unit`\nwhich adds its argument to the state. -/\ndef ex : state (list \u2115) (my_tree $ list unit) :=\ndo xs \u2190 traverse (traverse $ \u03bb a, modify $ list.cons a) x,\n   pure xs\n\nexample : (ex.run []).1 = node leaf (node (node leaf leaf [(), (), ()]) leaf [(), ()]) [()] := rfl\nexample : (ex.run []).2 = [1, 2, 3, 3, 2, 1] := rfl\nexample : is_lawful_traversable my_tree := my_tree.is_lawful_traversable\n\nend\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/test/traversable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.028007517867811665, "lm_q1q2_score": 0.007532381664414806}}
{"text": "example : False := by\n  have : True := by\n    skip\n  --^ $/lean/plainGoal\n    skip\n  admit\n\nexample : False := by\n  have : True := by\n               --^ $/lean/plainGoal\n    skip\n    skip\n  admit\n\nexample : False := by\n  have : True := by\n               --^ $/lean/plainGoal\n    skip\n    skip\n  admit\n\nexample : False := by\n  have : True := by\n    skip\n--^ $/lean/plainGoal\n    skip\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/interactive/haveInfo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713266402902046, "lm_q2_score": 0.040237945644811146, "lm_q1q2_score": 0.007529833963568431}}
{"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.FindExpr\nimport Lean.Parser.Term\nimport Lean.Meta.Structure\nimport Lean.Elab.App\nimport Lean.Elab.Binders\n\nnamespace Lean.Elab.Term.StructInst\n\nopen Std (HashMap)\nopen Meta\n\n/--\n  Structure instances are of the form:\n\n      \"{\" >> optional (atomic (sepBy1 termParser \", \" >> \" with \"))\n          >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))\n          >> optEllipsis\n          >> optional (\" : \" >> termParser)\n          >> \" }\"\n-/\n\n@[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx =>\n  let expectedArg := stx[4]\n  if expectedArg.isNone then\n    Macro.throwUnsupported\n  else\n    let expected := expectedArg[1]\n    let stxNew   := stx.setArg 4 mkNullNode\n    `(($stxNew : $expected))\n\n/-- Expand field abbreviations. Example: `{ x, y := 0 }` expands to `{ x := x, y := 0 }` -/\n@[builtinMacro Lean.Parser.Term.structInst] def expandStructInstFieldAbbrev : Macro := fun stx => do\n  if stx[2].getArgs.any fun arg => arg[0].getKind == ``Lean.Parser.Term.structInstFieldAbbrev then\n    let fieldsNew \u2190 stx[2].getArgs.mapM fun stx => do\n      let field := stx[0]\n      if field.getKind == ``Lean.Parser.Term.structInstFieldAbbrev then\n        let id := field[0]\n        let fieldNew \u2190 `(Lean.Parser.Term.structInstField| $id:ident := $id:ident)\n        return stx.setArg 0 fieldNew\n      else\n        return stx\n    return stx.setArg 2 (mkNullNode fieldsNew)\n  else\n    Macro.throwUnsupported\n\n/--\n  If `stx` is of the form `{ s\u2081, ..., s\u2099 with ... }` and `s\u1d62` is not a local variable, expand into `let src := s\u1d62; { ..., src, ... with ... }`.\n\n  Note that this one is not a `Macro` because we need to access the local context.\n-/\nprivate def expandNonAtomicExplicitSources (stx : Syntax) : TermElabM (Option Syntax) := do\n  let sourcesOpt := stx[1]\n  if sourcesOpt.isNone then\n    pure none\n  else\n    let sources := sourcesOpt[0]\n    if sources.isMissing then\n      throwAbortTerm\n    let sources := sources.getSepArgs\n    if (\u2190 sources.allM fun source => return (\u2190 isLocalIdent? source).isSome) then\n      return none\n    if sources.any (\u00b7.isMissing) then\n      throwAbortTerm\n    go sources.toList #[]\nwhere\n  go (sources : List Syntax) (sourcesNew : Array Syntax) : TermElabM Syntax := do\n    match sources with\n    | [] =>\n      let sources := Syntax.mkSep sourcesNew (mkAtomFrom stx \", \")\n      return stx.setArg 1 (stx[1].setArg 0 sources)\n    | source :: sources =>\n      if (\u2190 isLocalIdent? source).isSome then\n        go sources (sourcesNew.push source)\n      else\n        withFreshMacroScope do\n          let sourceNew \u2190 `(src)\n          let r \u2190 go sources (sourcesNew.push sourceNew)\n          `(let src := $source; $r)\n\nstructure ExplicitSourceInfo where\n  stx        : Syntax\n  structName : Name\n  deriving Inhabited\n\ninductive Source where\n  | none     -- structure instance source has not been provieded\n  | implicit (stx : Syntax) -- `..`\n  | explicit (sources : Array ExplicitSourceInfo) -- `s\u2081 ... s\u2099 with`\n  deriving Inhabited\n\ndef Source.isNone : Source \u2192 Bool\n  | Source.none => true\n  | _           => false\n\n/-- `optional (atomic (sepBy1 termParser \", \" >> \" with \")` -/\nprivate def mkSourcesWithSyntax (sources : Array Syntax) : Syntax :=\n  let ref := sources[0]\n  let stx := Syntax.mkSep sources (mkAtomFrom ref \", \")\n  mkNullNode #[stx, mkAtomFrom ref \"with \"]\n\nprivate def getStructSource (structStx : Syntax) : TermElabM Source :=\n  withRef structStx do\n    let explicitSource := structStx[1]\n    let implicitSource := structStx[3]\n    if explicitSource.isNone && implicitSource[0].isNone then\n      return Source.none\n    else if explicitSource.isNone then\n      return Source.implicit implicitSource\n    else if implicitSource[0].isNone then\n      let sources \u2190 explicitSource[0].getSepArgs.mapM fun stx => do\n        let some src \u2190 isLocalIdent? stx | unreachable!\n        let srcType \u2190 whnf (\u2190 inferType src)\n        tryPostponeIfMVar srcType\n        let structName \u2190 getStructureName srcType\n        return { stx, structName }\n      return Source.explicit sources\n    else\n      throwError \"invalid structure instance `with` and `..` cannot be used together\"\n\n/--\n  We say a `{ ... }` notation is a `modifyOp` if it contains only one\n  ```\n  def structInstArrayRef := leading_parser \"[\" >> termParser >>\"]\"\n  ```\n-/\nprivate def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do\n  let s? \u2190 stx[2].getArgs.foldlM (init := none) fun s? p =>\n    /- p is of the form `(group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))` -/\n    let arg := p[0]\n    if arg.getKind == ``Lean.Parser.Term.structInstField then\n      /- Remark: the syntax for `structInstField` is\n         ```\n         def structInstLVal   := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (group (\".\" >> (ident <|> numLit)) <|> structInstArrayRef)\n         def structInstField  := leading_parser structInstLVal >> \" := \" >> termParser\n         ```\n      -/\n      let lval := arg[0]\n      let k    := lval[0].getKind\n      if k == ``Lean.Parser.Term.structInstArrayRef then\n        match s? with\n        | none   => pure (some arg)\n        | some s =>\n          if s.getKind == ``Lean.Parser.Term.structInstArrayRef then\n            throwErrorAt arg \"invalid \\{...} notation, at most one `[..]` at a given level\"\n          else\n            throwErrorAt arg \"invalid \\{...} notation, can't mix field and `[..]` at a given level\"\n      else\n        match s? with\n        | none   => pure (some arg)\n        | some s =>\n          if s.getKind == ``Lean.Parser.Term.structInstArrayRef then\n            throwErrorAt arg \"invalid \\{...} notation, can't mix field and `[..]` at a given level\"\n          else\n            pure s?\n    else\n      pure s?\n  match s? with\n  | none   => pure none\n  | some s => if s[0][0].getKind == ``Lean.Parser.Term.structInstArrayRef then pure s? else pure none\n\nprivate def elabModifyOp (stx modifyOp : Syntax) (sources : Array ExplicitSourceInfo) (expectedType? : Option Expr) : TermElabM Expr := do\n  if sources.size > 1 then\n    throwError \"invalid \\{...} notation, multiple sources and array update is not supported.\"\n  let cont (val : Syntax) : TermElabM Expr := do\n    let lval := modifyOp[0][0]\n    let idx  := lval[1]\n    let self := sources[0].stx\n    let stxNew \u2190 `($(self).modifyOp (idx := $idx) (fun s => $val))\n    trace[Elab.struct.modifyOp] \"{stx}\\n===>\\n{stxNew}\"\n    withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  let rest := modifyOp[0][1]\n  if rest.isNone then\n    cont modifyOp[2]\n  else\n    let s \u2190 `(s)\n    let valFirst  := rest[0]\n    let valFirst  := if valFirst.getKind == ``Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1]\n    let restArgs  := rest.getArgs\n    let valRest   := mkNullNode restArgs[1:restArgs.size]\n    let valField  := modifyOp.setArg 0 <| mkNode ``Parser.Term.structInstLVal #[valFirst, valRest]\n    let valSource := mkSourcesWithSyntax #[s]\n    let val       := stx.setArg 1 valSource\n    let val       := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]]\n    trace[Elab.struct.modifyOp] \"{stx}\\nval: {val}\"\n    cont val\n\n/--\n  Get structure name.\n  This method triest to postpone execution if the expected type is not available.\n\n  If the expected type is available and it is a structure, then we use it.\n  Otherwise, we use the type of the first source. -/\nprivate def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let useSource : Unit \u2192 TermElabM Name := fun _ => do\n    match sourceView, expectedType? with\n    | Source.explicit sources, _ =>\n      if sources.size > 1 then\n        throwErrorAt sources[1].stx \"invalid \\{...} notation, expected type is not known, using the type of the first source, extra sources are not needed\"\n      return sources[0].structName\n    | _, some expectedType => throwUnexpectedExpectedType expectedType\n    | _, none              => throwUnknownExpectedType\n  match expectedType? with\n  | none => useSource ()\n  | some expectedType =>\n    let expectedType \u2190 whnf expectedType\n    match expectedType.getAppFn with\n    | Expr.const constName _ _ =>\n      unless isStructure (\u2190 getEnv) constName do\n        throwError \"invalid \\{...} notation, structure type expected{indentExpr expectedType}\"\n      return constName\n    | _                        => useSource ()\nwhere\n  throwUnknownExpectedType :=\n    throwError \"invalid \\{...} notation, expected type is not known\"\n  throwUnexpectedExpectedType type (kind := \"expected\") := do\n    let type \u2190 instantiateMVars type\n    if type.getAppFn.isMVar then\n      throwUnknownExpectedType\n    else\n      throwError \"invalid \\{...} notation, {kind} type is not of the form (C ...){indentExpr type}\"\n\ninductive FieldLHS where\n  | fieldName  (ref : Syntax) (name : Name)\n  | fieldIndex (ref : Syntax) (idx : Nat)\n  | modifyOp   (ref : Syntax) (index : Syntax)\n  deriving Inhabited\n\ninstance : ToFormat FieldLHS := \u27e8fun lhs =>\n  match lhs with\n  | FieldLHS.fieldName _ n  => format n\n  | FieldLHS.fieldIndex _ i => format i\n  | FieldLHS.modifyOp _ i   => \"[\" ++ i.prettyPrint ++ \"]\"\u27e9\n\ninductive FieldVal (\u03c3 : Type) where\n  | term  (stx : Syntax) : FieldVal \u03c3\n  | nested (s : \u03c3)       : FieldVal \u03c3\n  | default              : FieldVal \u03c3 -- mark that field must be synthesized using default value\n  deriving Inhabited\n\nstructure Field (\u03c3 : Type) where\n  ref   : Syntax\n  lhs   : List FieldLHS\n  val   : FieldVal \u03c3\n  expr? : Option Expr := none\n  deriving Inhabited\n\ndef Field.isSimple {\u03c3} : Field \u03c3 \u2192 Bool\n  | { lhs := [_], .. } => true\n  | _                  => false\n\ninductive Struct where\n  | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source)\n  deriving Inhabited\n\nabbrev Fields := List (Field Struct)\n\ndef Struct.ref : Struct \u2192 Syntax\n  | \u27e8ref, _, _, _\u27e9 => ref\n\ndef Struct.structName : Struct \u2192 Name\n  | \u27e8_, structName, _, _\u27e9 => structName\n\ndef Struct.fields : Struct \u2192 Fields\n  | \u27e8_, _, fields, _\u27e9 => fields\n\ndef Struct.source : Struct \u2192 Source\n  | \u27e8_, _, _, s\u27e9 => s\n\n/-- `true` iff all fields of the given structure are marked as `default` -/\npartial def Struct.allDefault (s : Struct) : Bool :=\n  s.fields.all fun { val := val,  .. } => match val with\n    | FieldVal.term _   => false\n    | FieldVal.default  => true\n    | FieldVal.nested s => allDefault s\n\ndef formatField (formatStruct : Struct \u2192 Format) (field : Field Struct) : Format :=\n  Format.joinSep field.lhs \" . \" ++ \" := \" ++\n    match field.val with\n    | FieldVal.term v   => v.prettyPrint\n    | FieldVal.nested s => formatStruct s\n    | FieldVal.default  => \"<default>\"\n\npartial def formatStruct : Struct \u2192 Format\n  | \u27e8_, structName, fields, source\u27e9 =>\n    let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) \", \"\n    match source with\n    | Source.none             => \"{\" ++ fieldsFmt ++ \"}\"\n    | Source.implicit _       => \"{\" ++ fieldsFmt ++ \" .. }\"\n    | Source.explicit sources => \"{\" ++ format (sources.map (\u00b7.stx)) ++ \" with \" ++ fieldsFmt ++ \"}\"\n\ninstance : ToFormat Struct     := \u27e8formatStruct\u27e9\ninstance : ToString Struct := \u27e8toString \u2218 format\u27e9\n\ninstance : ToFormat (Field Struct) := \u27e8formatField formatStruct\u27e9\ninstance : ToString (Field Struct) := \u27e8toString \u2218 format\u27e9\n\n/-\nRecall that `structInstField` elements have the form\n```\n   def structInstField  := leading_parser structInstLVal >> \" := \" >> termParser\n   def structInstLVal   := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many ((\".\" >> (ident <|> numLit)) <|> structInstArrayRef)\n   def structInstArrayRef := leading_parser \"[\" >> termParser >>\"]\"\n```\n-/\n-- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName`\ndef FieldLHS.toSyntax (first : Bool) : FieldLHS \u2192 Syntax\n  | FieldLHS.modifyOp   stx _    => stx\n  | FieldLHS.fieldName  stx name => if first then mkIdentFrom stx name else mkGroupNode #[mkAtomFrom stx \".\", mkIdentFrom stx name]\n  | FieldLHS.fieldIndex stx _    => if first then stx else mkGroupNode #[mkAtomFrom stx \".\", stx]\n\ndef FieldVal.toSyntax : FieldVal Struct \u2192 Syntax\n  | FieldVal.term stx => stx\n  | _                 => unreachable!\n\ndef Field.toSyntax : Field Struct \u2192 Syntax\n  | field =>\n    let stx := field.ref\n    let stx := stx.setArg 2 field.val.toSyntax\n    match field.lhs with\n    | first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ]\n    | _ => unreachable!\n\nprivate def toFieldLHS (stx : Syntax) : MacroM FieldLHS :=\n  if stx.getKind == ``Lean.Parser.Term.structInstArrayRef then\n    return FieldLHS.modifyOp stx stx[1]\n  else\n    -- Note that the representation of the first field is different.\n    let stx := if stx.getKind == groupKind then stx[1] else stx\n    if stx.isIdent then\n      return FieldLHS.fieldName stx stx.getId.eraseMacroScopes\n    else match stx.isFieldIdx? with\n      | some idx => return FieldLHS.fieldIndex stx idx\n      | none     => Macro.throwError \"unexpected structure syntax\"\n\nprivate def mkStructView (stx : Syntax) (structName : Name) (source : Source) : MacroM Struct := do\n  /- Recall that `stx` is of the form\n     ```\n     leading_parser \"{\" >> optional (atomic (sepBy1 termParser \", \" >> \" with \"))\n                 >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional \", \"))\n                 >> optional \"..\"\n                 >> optional (\" : \" >> termParser)\n                 >> \" }\"\n     ```\n\n     This method assumes that `structInstFieldAbbrev` had already been expanded.\n  -/\n  let fields \u2190 stx[2].getArgs.toList.mapM fun stx => do\n    let fieldStx := stx[0]\n    let val      := fieldStx[2]\n    let first    \u2190 toFieldLHS fieldStx[0][0]\n    let rest     \u2190 fieldStx[0][1].getArgs.toList.mapM toFieldLHS\n    return { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct }\n  return \u27e8stx, structName, fields, source\u27e9\n\ndef Struct.modifyFieldsM {m : Type \u2192 Type} [Monad m] (s : Struct) (f : Fields \u2192 m Fields) : m Struct :=\n  match s with\n  | \u27e8ref, structName, fields, source\u27e9 => return \u27e8ref, structName, (\u2190 f fields), source\u27e9\n\ndef Struct.modifyFields (s : Struct) (f : Fields \u2192 Fields) : Struct :=\n  Id.run <| s.modifyFieldsM f\n\ndef Struct.setFields (s : Struct) (fields : Fields) : Struct :=\n  s.modifyFields fun _ => fields\n\nprivate def expandCompositeFields (s : Struct) : Struct :=\n  s.modifyFields fun fields => fields.map fun field => match field with\n    | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field\n    | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } =>\n      let newEntries := n.components.map <| FieldLHS.fieldName ref\n      { field with lhs := newEntries ++ rest }\n    | _ => field\n\nprivate def expandNumLitFields (s : Struct) : TermElabM Struct :=\n  s.modifyFieldsM fun fields => do\n    let env \u2190 getEnv\n    let fieldNames := getStructureFields env s.structName\n    fields.mapM fun field => match field with\n      | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } =>\n        if idx == 0 then throwErrorAt ref \"invalid field index, index must be greater than 0\"\n        else if idx > fieldNames.size then throwErrorAt ref \"invalid field index, structure has only #{fieldNames.size} fields\"\n        else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest }\n      | _ => pure field\n\n/- For example, consider the following structures:\n   ```\n   structure A where\n     x : Nat\n\n   structure B extends A where\n     y : Nat\n\n   structure C extends B where\n     z : Bool\n   ```\n   This method expands parent structure fields using the path to the parent structure.\n   For example,\n   ```\n   { x := 0, y := 0, z := true : C }\n   ```\n   is expanded into\n   ```\n   { toB.toA.x := 0, toB.y := 0, z := true : C }\n   ```\n-/\nprivate def expandParentFields (s : Struct) : TermElabM Struct := do\n  let env \u2190 getEnv\n  s.modifyFieldsM fun fields => fields.mapM fun field => match field with\n    | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } =>\n      match findField? env s.structName fieldName with\n      | none => throwErrorAt ref \"'{fieldName}' is not a field of structure '{s.structName}'\"\n      | some baseStructName =>\n        if baseStructName == s.structName then pure field\n        else match getPathToBaseStructure? env baseStructName s.structName with\n          | some path => do\n            let path := path.map fun funName => match funName with\n              | Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s)\n              | _              => unreachable!\n            pure { field with lhs := path ++ field.lhs }\n          | _ => throwErrorAt ref \"failed to access field '{fieldName}' in parent structure\"\n    | _ => pure field\n\nprivate abbrev FieldMap := HashMap Name Fields\n\nprivate def mkFieldMap (fields : Fields) : TermElabM FieldMap :=\n  fields.foldlM (init := {}) fun fieldMap field =>\n    match field.lhs with\n    | FieldLHS.fieldName _ fieldName :: rest =>\n      match fieldMap.find? fieldName with\n      | some (prevField::restFields) =>\n        if field.isSimple || prevField.isSimple then\n          throwErrorAt field.ref \"field '{fieldName}' has already beed specified\"\n        else\n          return fieldMap.insert fieldName (field::prevField::restFields)\n      | _ => return fieldMap.insert fieldName [field]\n    | _ => unreachable!\n\nprivate def isSimpleField? : Fields \u2192 Option (Field Struct)\n  | [field] => if field.isSimple then some field else none\n  | _       => none\n\nprivate def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do\n  match fieldNames.findIdx? fun n => n == fieldName with\n  | some idx => pure idx\n  | none     => throwError \"field '{fieldName}' is not a valid field of '{structName}'\"\n\ndef mkProjStx? (s : Syntax) (structName : Name) (fieldName : Name) : TermElabM (Option Syntax) := do\n  if (findField? (\u2190 getEnv) structName fieldName).isNone then\n    return none\n  return some $ mkNode ``Lean.Parser.Term.proj #[s, mkAtomFrom s \".\", mkIdentFrom s fieldName]\n\ndef findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) :=\n  fields.find? fun field =>\n    match field.lhs with\n    | [FieldLHS.fieldName _ n] => n == fieldName\n    | _                        => false\n\nmutual\n\n  private partial def groupFields (s : Struct) : TermElabM Struct := do\n    let env \u2190 getEnv\n    let fieldNames := getStructureFields env s.structName\n    withRef s.ref do\n    s.modifyFieldsM fun fields => do\n      let fieldMap \u2190 mkFieldMap fields\n      fieldMap.toList.mapM fun \u27e8fieldName, fields\u27e9 => do\n        match isSimpleField? fields with\n        | some field => pure field\n        | none =>\n          let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! }\n          let field := fields.head!\n          match Lean.isSubobjectField? env s.structName fieldName with\n          | some substructName =>\n            let substruct := Struct.mk s.ref substructName substructFields s.source\n            let substruct \u2190 expandStruct substruct\n            pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct }\n          | none => do\n            let updateSource (structStx : Syntax) : TermElabM Syntax := do\n              match s.source with\n              | Source.none             => return (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode\n              | Source.implicit stx     => return (structStx.setArg 1 mkNullNode).setArg 3 stx\n              | Source.explicit sources =>\n                let sourcesNew \u2190 sources.filterMapM fun source => mkProjStx? source.stx source.structName fieldName\n                if sourcesNew.isEmpty then\n                  return (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode\n                else\n                  return (structStx.setArg 1 (mkSourcesWithSyntax sourcesNew)).setArg 3 mkNullNode\n            let valStx := s.ref -- construct substructure syntax using s.ref as template\n            let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type\n            let args   := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode]\n            let valStx := valStx.setArg 2 (mkNullNode args)\n            let valStx \u2190 updateSource valStx\n            pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx }\n\n  private partial def addMissingFields (s : Struct) : TermElabM Struct := do\n    let env \u2190 getEnv\n    let fieldNames := getStructureFields env s.structName\n    let ref := s.ref.mkSynthetic\n    withRef ref do\n      let fields \u2190 fieldNames.foldlM (init := []) fun fields fieldName => do\n        match findField? s.fields fieldName with\n        | some field => return field::fields\n        | none       =>\n          let addField (val : FieldVal Struct) : TermElabM Fields := do\n            return { ref, lhs := [FieldLHS.fieldName ref fieldName], val := val } :: fields\n          match Lean.isSubobjectField? env s.structName fieldName with\n          | some substructName => do\n            let addSubstruct : TermElabM Fields := do\n              let substruct := Struct.mk ref substructName [] s.source\n              let substruct \u2190 expandStruct substruct\n              addField (FieldVal.nested substruct)\n            match s.source with\n            | Source.none             => addSubstruct\n            | Source.implicit _       => addSubstruct\n            | Source.explicit sources =>\n              -- If one of the sources has the subobject field, use it\n              if let some val \u2190 sources.findSomeM? fun source => mkProjStx? source.stx source.structName fieldName then\n                addField (FieldVal.term val)\n              else\n                addSubstruct\n          | none =>\n            match s.source with\n            | Source.none         => addField FieldVal.default\n            | Source.implicit _   => addField (FieldVal.term (mkHole ref))\n            | Source.explicit sources =>\n              if let some val \u2190 sources.findSomeM? fun source => mkProjStx? source.stx source.structName fieldName then\n                addField (FieldVal.term val)\n              else\n                addField FieldVal.default\n      return s.setFields fields.reverse\n\n  private partial def expandStruct (s : Struct) : TermElabM Struct := do\n    let s := expandCompositeFields s\n    let s \u2190 expandNumLitFields s\n    let s \u2190 expandParentFields s\n    let s \u2190 groupFields s\n    addMissingFields s\n\nend\n\nstructure CtorHeaderResult where\n  ctorFn     : Expr\n  ctorFnType : Expr\n  instMVars  : Array MVarId := #[]\n\nprivate def mkCtorHeaderAux : Nat \u2192 Expr \u2192 Expr \u2192 Array MVarId \u2192 TermElabM CtorHeaderResult\n  | 0,   type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars }\n  | n+1, type, ctorFn, instMVars => do\n    let type \u2190 whnfForall type\n    match type with\n    | Expr.forallE _ d b c =>\n      match c.binderInfo with\n      | BinderInfo.instImplicit =>\n        let a \u2190 mkFreshExprMVar d MetavarKind.synthetic\n        mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!)\n      | _ =>\n        let a \u2190 mkFreshExprMVar d\n        mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars\n    | _ => throwError \"unexpected constructor type\"\n\nprivate partial def getForallBody : Nat \u2192 Expr \u2192 Option Expr\n  | i+1, Expr.forallE _ _ b _ => getForallBody i b\n  | i+1, _                    => none\n  | 0,   type                 => type\n\nprivate def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit :=\n  match expectedType? with\n  | none              => pure ()\n  | some expectedType => do\n    match getForallBody numFields type with\n      | none           => pure ()\n      | some typeBody =>\n        unless typeBody.hasLooseBVars do\n          discard <| isDefEq expectedType typeBody\n\nprivate def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do\n  let us \u2190 mkFreshLevelMVars ctorVal.levelParams.length\n  let val  := Lean.mkConst ctorVal.name us\n  let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams us\n  let r \u2190 mkCtorHeaderAux ctorVal.numParams type val #[]\n  propagateExpectedType r.ctorFnType ctorVal.numFields expectedType?\n  synthesizeAppInstMVars r.instMVars r.ctorFn\n  pure r\n\ndef markDefaultMissing (e : Expr) : Expr :=\n  mkAnnotation `structInstDefault e\n\ndef defaultMissing? (e : Expr) : Option Expr :=\n  annotation? `structInstDefault e\n\ndef throwFailedToElabField {\u03b1} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM \u03b1 :=\n  throwError \"failed to elaborate field '{fieldName}' of '{structName}, {msgData}\"\n\ndef trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do\n  if !s.allDefault then\n    pure none\n  else\n    try synthInstance? expectedType catch _ => pure none\n\nprivate partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr \u00d7 Struct) := withRef s.ref do\n  let env \u2190 getEnv\n  let ctorVal := getStructureCtor env s.structName\n  let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } \u2190 mkCtorHeader ctorVal expectedType?\n  let (e, _, fields) \u2190 s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field =>\n    match field.lhs with\n    | [FieldLHS.fieldName ref fieldName] => do\n      let type \u2190 whnfForall type\n      trace[Elab.struct] \"elabStruct {field}, {type}\"\n      match type with\n      | Expr.forallE _ d b _ =>\n        let cont (val : Expr) (field : Field Struct) : TermElabM (Expr \u00d7 Expr \u00d7 Fields) := do\n          pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo {\n            projName := s.structName.append fieldName, fieldName, lctx := (\u2190 getLCtx), val, stx := ref }\n          let e     := mkApp e val\n          let type  := b.instantiate1 val\n          let field := { field with expr? := some val }\n          pure (e, type, field::fields)\n        match field.val with\n        | FieldVal.term stx => cont (\u2190 elabTermEnsuringType stx d) field\n        | FieldVal.nested s => do\n          -- if all fields of `s` are marked as `default`, then try to synthesize instance\n          match (\u2190 trySynthStructInstance? s d) with\n          | some val => cont val { field with val := FieldVal.term (mkHole field.ref) }\n          | none     => do let (val, sNew) \u2190 elabStruct s (some d); let val \u2190 ensureHasType d val; cont val { field with val := FieldVal.nested sNew }\n        | FieldVal.default  => do\n          match d.getAutoParamTactic? with\n          | some (Expr.const tacticDecl ..) =>\n            match evalSyntaxConstant env (\u2190 getOptions) tacticDecl with\n            | Except.error err       => throwError err\n            | Except.ok tacticSyntax =>\n              let stx \u2190 `(by $tacticSyntax)\n              cont (\u2190 elabTermEnsuringType stx (d.getArg! 0)) field\n          | _ =>\n            let val \u2190 withRef field.ref <| mkFreshExprMVar (some d)\n            cont (markDefaultMissing val) field\n      | _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!\"unexpected constructor type{indentExpr type}\"\n    | _ => throwErrorAt field.ref \"unexpected unexpanded structure field\"\n  pure (e, s.setFields fields.reverse)\n\nnamespace DefaultFields\n\nstructure Context where\n  -- We must search for default values overriden in derived structures\n  structs : Array Struct := #[]\n  allStructNames : Array Name := #[]\n  /--\n  Consider the following example:\n  ```\n  structure A where\n    x : Nat := 1\n\n  structure B extends A where\n    y : Nat := x + 1\n    x := y + 1\n\n  structure C extends B where\n    z : Nat := 2*y\n    x := z + 3\n  ```\n  And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`.\n  We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2.\n  The field `maxDistance` specifies the maximum distance considered in a round of Default field computation.\n  Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0.\n\n  The fixpoint for setting default values works in the following way.\n  - Keep computing default values using `maxDistance == 0`.\n  - We increase `maxDistance` whenever we failed to compute a new default value in a round.\n  - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value.\n    We use depth-first search.\n  - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above).\n  -/\n  maxDistance : Nat := 0\n\nstructure State where\n  progress : Bool := false\n\npartial def collectStructNames (struct : Struct) (names : Array Name) : Array Name :=\n  let names := names.push struct.structName\n  struct.fields.foldl (init := names) fun names field =>\n    match field.val with\n    | FieldVal.nested struct => collectStructNames struct names\n    | _ => names\n\npartial def getHierarchyDepth (struct : Struct) : Nat :=\n  struct.fields.foldl (init := 0) fun max field =>\n    match field.val with\n    | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1)\n    | _ => max\n\npartial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) :=\n  struct.fields.findSome? fun field =>\n   match field.val with\n   | FieldVal.nested struct => findDefaultMissing? mctx struct\n   | _ => match field.expr? with\n     | none      => unreachable!\n     | some expr => match defaultMissing? expr with\n       | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field\n       | _                         => none\n\ndef getFieldName (field : Field Struct) : Name :=\n  match field.lhs with\n  | [FieldLHS.fieldName _ fieldName] => fieldName\n  | _ => unreachable!\n\nabbrev M := ReaderT Context (StateRefT State TermElabM)\n\ndef isRoundDone : M Bool := do\n  return (\u2190 get).progress && (\u2190 read).maxDistance > 0\n\ndef getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr :=\n  struct.fields.findSome? fun field =>\n    if getFieldName field == fieldName then\n      field.expr?\n    else\n      none\n\npartial def mkDefaultValueAux? (struct : Struct) : Expr \u2192 TermElabM (Option Expr)\n  | Expr.lam n d b c => withRef struct.ref do\n    if c.binderInfo.isExplicit then\n      let fieldName := n\n      match getFieldValue? struct fieldName with\n      | none     => pure none\n      | some val =>\n        let valType \u2190 inferType val\n        if (\u2190 isDefEq valType d) then\n          mkDefaultValueAux? struct (b.instantiate1 val)\n        else\n          pure none\n    else\n      let arg \u2190 mkFreshExprMVar d\n      mkDefaultValueAux? struct (b.instantiate1 arg)\n  | e =>\n    if e.isAppOfArity ``id 2 then\n      pure (some e.appArg!)\n    else\n      pure (some e)\n\ndef mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) :=\n  withRef struct.ref do\n  let us \u2190 mkFreshLevelMVarsFor cinfo\n  mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us)\n\n/-- Reduce default value. It performs beta reduction and projections of the given structures. -/\npartial def reduce (structNames : Array Name) (e : Expr) : MetaM Expr := do\n  -- trace[Elab.struct] \"reduce {e}\"\n  match e with\n  | Expr.lam ..       => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (\u2190 reduce structNames b)\n  | Expr.forallE ..   => forallTelescope e fun xs b => do mkForallFVars xs (\u2190 reduce structNames b)\n  | Expr.letE ..      => lambdaLetTelescope e fun xs b => do mkLetFVars xs (\u2190 reduce structNames b)\n  | Expr.proj _ i b _ => do\n    match (\u2190 Meta.project? b i) with\n    | some r => reduce structNames r\n    | none   => return e.updateProj! (\u2190 reduce structNames b)\n  | Expr.app f .. => do\n    match (\u2190 reduceProjOf? e structNames.contains) with\n    | some r => reduce structNames r\n    | none   =>\n      let f := f.getAppFn\n      let f' \u2190 reduce structNames f\n      if f'.isLambda then\n        let revArgs := e.getAppRevArgs\n        reduce structNames (f'.betaRev revArgs)\n      else\n        let args \u2190 e.getAppArgs.mapM (reduce structNames)\n        return (mkAppN f' args)\n  | Expr.mdata _ b _ => do\n    let b \u2190 reduce structNames b\n    if (defaultMissing? e).isSome && !b.isMVar then\n      return b\n    else\n      return e.updateMData! b\n  | Expr.mvar mvarId _ => do\n    match (\u2190 getExprMVarAssignment? mvarId) with\n    | some val => if val.isMVar then pure val else reduce structNames val\n    | none     => return e\n  | e => return e\n\npartial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool :=\n  let rec loop (i : Nat) (dist : Nat) := do\n    if dist > maxDistance then\n      pure false\n    else if h : i < structs.size then do\n      let struct := structs.get \u27e8i, h\u27e9\n      match getDefaultFnForField? (\u2190 getEnv) struct.structName fieldName with\n      | some defFn =>\n        let cinfo \u2190 getConstInfo defFn\n        let mctx \u2190 getMCtx\n        let val? \u2190 mkDefaultValue? struct cinfo\n        match val? with\n        | none     => do setMCtx mctx; loop (i+1) (dist+1)\n        | some val => do\n          let val \u2190 reduce allStructNames val\n          match val.find? fun e => (defaultMissing? e).isSome with\n          | some _ => setMCtx mctx; loop (i+1) (dist+1)\n          | none   =>\n            let mvarDecl \u2190 getMVarDecl mvarId\n            let val \u2190 ensureHasType mvarDecl.type val\n            assignExprMVar mvarId val\n            pure true\n      | _ => loop (i+1) dist\n    else\n      pure false\n  loop 0 0\n\npartial def step (struct : Struct) : M Unit :=\n  unless (\u2190 isRoundDone) do\n    withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do\n      for field in struct.fields do\n        match field.val with\n        | FieldVal.nested struct => step struct\n        | _ => match field.expr? with\n          | none      => unreachable!\n          | some expr =>\n            match defaultMissing? expr with\n            | some (Expr.mvar mvarId _) =>\n              unless (\u2190 isExprMVarAssigned mvarId) do\n                let ctx \u2190 read\n                if (\u2190 withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then\n                  modify fun s => { s with progress := true }\n            | _ => pure ()\n\npartial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do\n  match findDefaultMissing? (\u2190 getMCtx) struct with\n  | none       => pure () -- Done\n  | some field =>\n    trace[Elab.struct] \"propagate [{d}] [field := {field}]: {struct}\"\n    if d > hierarchyDepth then\n      throwErrorAt field.ref \"field '{getFieldName field}' is missing\"\n    else withReader (fun ctx => { ctx with maxDistance := d }) do\n      modify fun s => { s with progress := false }\n      step struct\n      if (\u2190 get).progress then do\n        propagateLoop hierarchyDepth 0 struct\n      else\n        propagateLoop hierarchyDepth (d+1) struct\n\ndef propagate (struct : Struct) : TermElabM Unit :=\n  let hierarchyDepth := getHierarchyDepth struct\n  let structNames := collectStructNames struct #[]\n  (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {}\n\nend DefaultFields\n\nprivate def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do\n  let structName \u2190 getStructName stx expectedType? source\n  let struct \u2190 liftMacroM <| mkStructView stx structName source\n  let struct \u2190 expandStruct struct\n  trace[Elab.struct] \"{struct}\"\n  /- We try to synthesize pending problems with `withSynthesize` combinator before trying to use default values.\n     This is important in examples such as\n      ```\n      structure MyStruct where\n          {\u03b1 : Type u}\n          {\u03b2 : Type v}\n          a : \u03b1\n          b : \u03b2\n\n      #check { a := 10, b := true : MyStruct }\n      ```\n     were the `\u03b1` will remain \"unknown\" until the default instance for `OfNat` is used to ensure that `10` is a `Nat`.\n\n     TODO: investigate whether this design decision may have unintended side effects or produce confusing behavior.\n  -/\n  let (r, struct) \u2190 withSynthesize (mayPostpone := true) <| elabStruct struct expectedType?\n  trace[Elab.struct] \"before propagate {r}\"\n  DefaultFields.propagate struct\n  return r\n\n/-- Structure instance. `{ x := e, ... }` assigns `e` to field `x`, which may be\ninherited. If `e` is itself a variable called `x`, it can be elided:\n`fun y => { x := 1, y }`.\nA *structure update* of an existing value can be given via `with`:\n`{ point with x := 1 }`.\nThe structure type can be specified if not inferable:\n`{ x := 1, y := 2 : Point }`. -/\n@[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do\n  match (\u2190 expandNonAtomicExplicitSources stx) with\n  | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n  | none =>\n    let sourceView \u2190 getStructSource stx\n    match (\u2190 isModifyOp? stx), sourceView with\n    | some modifyOp, Source.explicit sources => elabModifyOp stx modifyOp sources expectedType?\n    | some _,        _                       => throwError \"invalid \\{...} notation, explicit source is required when using '[<index>] := <value>'\"\n    | _,             _                       => elabStructInstAux stx expectedType? sourceView\n\nbuiltin_initialize registerTraceClass `Elab.struct\n\nend Lean.Elab.Term.StructInst\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/Elab/StructInst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.177810865121124, "lm_q2_score": 0.04208772836618918, "lm_q1q2_score": 0.00748365539177497}}
{"text": "/-\nCopyright (c) 2020 Chris Hughes. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Chris Hughes\n\n! This file was ported from Lean 3 source module tactic.protected\n! leanprover-community/mathlib commit f36c98e877dd86af12606abbba5275513baa8a26\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## `protected` and `protect_proj` user attributes\n\n`protected` is an attribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj` attribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n# Examples\n\nIn this example all of `foo.bar`, `foo.baz` and `foo.qux` will be protected.\n```\n@[protect_proj] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n\nThe following code example define the structure `foo`, and the projections `foo.qux`\nwill be protected, but not `foo.baz` or `foo.bar`\n\n```\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\n\n\nnamespace Tactic\n\n/-- Attribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\nProtectedness is a built in parser feature that is independent of this attribute.\nA declaration may be protected even if it does not have the `@[protected]` attribute.\nThis provides a convenient way to protect many declarations at once.\n-/\n@[user_attribute]\nunsafe def protected_attr : user_attribute\n    where\n  Name := \"protected\"\n  descr :=\n    \"Attribute to protect a declaration\\n    If a declaration `foo.bar` is marked protected, then it must be referred to\\n    by its full name `foo.bar`, even when the `foo` namespace is open.\"\n  after_set := some fun n _ _ => mk_protected n\n#align tactic.protected_attr tactic.protected_attr\n\nadd_tactic_doc\n  { Name := \"protected\"\n    category := DocCategory.attr\n    declNames := [`tactic.protected_attr]\n    tags := [\"parsing\", \"environment\"] }\n\n/-- Tactic that is executed when a structure is marked with the `protect_proj` attribute -/\nunsafe def protect_proj_tac (n : Name) (l : List Name) : tactic Unit := do\n  let env \u2190 get_env\n  match env n with\n    | none => fail \"protect_proj failed: declaration is not a structure\"\n    | some fields => fields fun field => when (l fun m => not <| m Field) <| mk_protected Field\n#align tactic.protect_proj_tac tactic.protect_proj_tac\n\n/-- Attribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected, meaning they must always be referred to by\ntheir full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n```lean\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\n@[user_attribute]\nunsafe def protect_proj_attr : user_attribute Unit (List Name)\n    where\n  Name := \"protect_proj\"\n  descr :=\n    \"Attribute to protect the projections of a structure.\\n    If a structure `foo` is marked with the `protect_proj` user attribute, then\\n    all of the projections become protected, meaning they must always be referred to by\\n    their full name `foo.bar`, even when the `foo` namespace is open.\\n\\n    `protect_proj without bar baz` will protect all projections except for bar and baz\"\n  after_set :=\n    some fun n _ _ => do\n      let l \u2190 protect_proj_attr.get_param n\n      protect_proj_tac n l\n  parser := interactive.types.without_ident_list\n#align tactic.protect_proj_attr tactic.protect_proj_attr\n\nadd_tactic_doc\n  { Name := \"protect_proj\"\n    category := DocCategory.attr\n    declNames := [`tactic.protect_proj_attr]\n    tags := [\"parsing\", \"environment\", \"structures\"] }\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/Protected.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252320931407358, "lm_q2_score": 0.06097517702556992, "lm_q1q2_score": 0.007470874377666594}}
{"text": "import Lean\n\nimport GameServer.Utils\nimport GameServer.EnvExtensions\n\nopen Lean Meta\n\nset_option autoImplicit false\n\n/-! ## Easy metadata -/\n\nsection metadata\n\nopen Lean Meta Elab Command Term\n\n/-- Create a game with the given identifier as name. -/\nelab \"Game\" n:str : command => do\n  gameExt.set {name := n.getString}\n\n/-- Define the current level number. -/\nelab \"Level\" n:num : command => do\n  let idx := n.getNat\n  setCurLevelIdx idx\n  levelsExt.insert idx {index := idx}\n\n/-- Define the title of the current game or current level if some\nbuilding a level. -/\nelab \"Title\" t:str : command => do\n  let lvlIdx \u2190 getCurLevelIdx\n  if lvlIdx > 0 then\n    let some lvl := (\u2190 levelsExt.find? lvlIdx) | throwError \"Unable to find level\"\n    levelsExt.update lvlIdx {lvl with title := t.getString}\n  else\n    gameExt.set {\u2190 gameExt.get with title := t.getString}\n\n/-- Define the introduction of the current game or current level if some\nbuilding a level. -/\nelab \"Introduction\" t:str : command => do\n  let lvlIdx \u2190 getCurLevelIdx\n  if lvlIdx > 0 then\n    let some lvl := (\u2190 levelsExt.find? lvlIdx) | throwError \"Unable to find level\"\n    levelsExt.update lvlIdx {lvl with introduction := t.getString}\n  else\n    gameExt.set {\u2190 gameExt.get with introduction := t.getString}\n\n/-- Define the statement of the current level. -/\nelab \"Statement\" sig:declSig val:declVal : command => do\n  let lvlIdx \u2190 getCurLevelIdx\n  let declName : Name := (\u2190 gameExt.get).name ++ (\"level\" ++ toString lvlIdx : String)\n  elabCommand (\u2190 `(theorem $(mkIdent declName) $sig $val))\n  let (binders, _) := expandDeclSig sig\n  let mut nb : Nat := 0\n  for arg in binders.getArgs do\n    nb := nb + arg[1].getArgs.size\n  let some cInfo := (\u2190 getEnv).find? declName | throwError \"Declaration not found\"\n  levelsExt.update lvlIdx {\u2190 getCurLevel with goal := cInfo.type, intro_nb := nb}\n  \n/-- Define the conclusion of the current game or current level if some\nbuilding a level. -/\nelab \"Conclusion\" t:str : command => do\n  let lvlIdx \u2190 getCurLevelIdx\n  if lvlIdx > 0 then\n    let some lvl := (\u2190 levelsExt.find? lvlIdx) | throwError \"Unable to find level\"\n    levelsExt.update lvlIdx {lvl with conclusion := t.getString}\n  else\n    gameExt.set {\u2190 gameExt.get with conclusion := t.getString}\n\n/-- Print current game for debugging purposes. -/\nelab \"PrintCurGame\" : command => do\n  logInfo (repr (\u2190 gameExt.get))\n\n/-- Print current level for debugging purposes. -/\nelab \"PrintCurLevel\" : command => do\n  match \u2190 levelsExt.find? (\u2190 getCurLevelIdx) with\n  | some lvl => logInfo (repr lvl)\n  | none => logInfo \"Could not find level\"\n\n/-- Print levels for debugging purposes. -/\nelab \"PrintLevels\" : command => do\n  logInfo $ repr $ (levelsExt.getState (\u2190 getEnv)).toList.map (\u00b7.fst)\n\nend metadata\n\n/-! ## Messages -/\n\nopen Lean Meta Elab Command Term\n\ndeclare_syntax_cat mydecl\nsyntax \"(\" ident \":\" term \")\" : mydecl\n\ndef getIdent : TSyntax `mydecl \u2192 Ident\n| `(mydecl| ($n:ident : $_t:term)) => n\n| _ => default\n\ndef getType : TSyntax `mydecl \u2192 Term\n| `(mydecl| ($_n:ident : $t:term)) => t\n| _ => default\n\n/-- From a term `s` and a list of pairs `(i, t) ; Ident \u00d7 Term`, create the syntax\nwhere `s` is preceded with universal quantifiers `\u2200 i : t`. -/\ndef mkGoalSyntax (s : Term) : List (Ident \u00d7 Term) \u2192 MacroM Term \n| (n, t)::tail => do return (\u2190 `(\u2200 $n : $t, $(\u2190 mkGoalSyntax s tail)))\n| [] => return s\n\n/-- Declare a message. This version doesn't prevent the unused linter variable from running. -/\nlocal elab \"Message'\" decls:mydecl* \":\" goal:term \"=>\" msg:str : command => do\n  let g \u2190 liftMacroM $ mkGoalSyntax goal (decls.map (\u03bb decl => (getIdent decl, getType decl))).toList\n  let g \u2190 liftTermElabM do (return \u2190 instantiateMVars (\u2190 elabTerm g none))\n  let (ctx_size, normalized_goal) \u2190 liftTermElabM do\n    let msg_mvar \u2190 mkFreshExprMVar g MetavarKind.syntheticOpaque\n    msg_mvar.mvarId!.withContext do \n      let (_, msg_mvar) \u2190 msg_mvar.mvarId!.introNP decls.size\n      return ((\u2190 msg_mvar.getDecl).lctx.size,  (\u2190 normalizedRevertExpr msg_mvar))\n  let lvlIdx \u2190 getCurLevelIdx\n  let lvl \u2190 getCurLevel\n  levelsExt.update lvlIdx {lvl with messages := lvl.messages.push {\n    ctx_size := ctx_size,\n    normalized_goal := normalized_goal,\n    intro_nb := decls.size,\n    message := msg.getString }}\n\n/-- Declare a message in reaction to a given tactic state in the current level. -/\nmacro \"Message\" decls:mydecl* \":\" goal:term \"=>\" msg:str : command => do\n  `(set_option linter.unusedVariables false in Message' $decls* : $goal => $msg)\n\n\n/-! ## Tactics -/\n\n/-- Declare a documentation entry for some tactic.\nExpect an identifier and then a string literal. -/\nelab \"TacticDoc\" name:ident content:str : command => \n  modifyEnv (tacticDocExt.addEntry \u00b7 {\n    name := name.getId, \n    content := content.getString })\n\n/-- Declare a set of tactic documentation entries. \nExpect an identifier used as the set name then `:=` and a\nspace separated list of identifiers.\n-/\nelab \"TacticSet\" name:ident \":=\" args:ident* : command => do\n  let docs := tacticDocExt.getState (\u2190 getEnv)\n  let mut entries : Array TacticDocEntry := #[]\n  for arg in args do\n    let name := arg.getId\n    match docs.find? (\u00b7.name = name) with\n    | some doc => entries := entries.push doc\n    | none => throwError \"Documentation for tactic {name} wasn't found.\"\n  modifyEnv (tacticSetExt.addEntry \u00b7 {\n    name := name.getId, \n    tactics := entries })\n\ninstance : Quote TacticDocEntry `term :=\n\u27e8\u03bb entry => Syntax.mkCApp ``TacticDocEntry.mk #[quote entry.name, quote entry.content]\u27e9\n\n/-- Declare the list of tactics that will be displayed in the current level. \nExpects a space separated list of identifiers that refer to either a tactic doc\nentry or a tactic doc set. -/\nelab \"Tactics\" args:ident* : command => do\n  let env \u2190 getEnv\n  let docs := tacticDocExt.getState env\n  let sets := tacticSetExt.getState env\n  let mut tactics : Array TacticDocEntry := #[]\n  for arg in args do\n    let name := arg.getId\n    match docs.find? (\u00b7.name = name) with\n    | some entry => tactics := tactics.push entry\n    | none => match sets.find? (\u00b7.name = name) with\n              | some entry => tactics := tactics ++ entry.tactics\n              | none => throwError \"Tactic doc or tactic set {name} wasn't found.\"\n  let lvlIdx \u2190 getCurLevelIdx\n  if lvlIdx > 0 then\n    let some lvl := (\u2190 levelsExt.find? lvlIdx) | throwError \"Unable to find level\"\n    levelsExt.update lvlIdx {lvl with tactics := tactics}\n  else\n    throwError \"This command can be used only while building a level.\"\n\n/-! ## Lemmas -/\n\n/-- Declare a documentation entry for some lemma.\nExpect two identifiers and then a string literal. The first identifier is meant\nas the real name of the lemma while the second is the displayed name. Currently\nthe real name isn't used. -/\nelab \"LemmaDoc\" name:ident \"as\" userName:ident \"in\" category:str content:str : command => \n  modifyEnv (lemmaDocExt.addEntry \u00b7 {\n    name := name.getId, \n    userName := userName.getId,\n    category := category.getString,\n    content := content.getString })\n\n/-- Declare a set of lemma documentation entries. \nExpect an identifier used as the set name then `:=` and a\nspace separated list of identifiers. -/\nelab \"LemmaSet\" name:ident \":\" title:str \":=\" args:ident* : command => do\n  let docs := lemmaDocExt.getState (\u2190 getEnv)\n  let mut entries : Array LemmaDocEntry := #[]\n  for arg in args do\n    let name := arg.getId\n    match docs.find? (\u00b7.userName = name) with\n    | some doc => entries := entries.push doc\n    | none => throwError \"Lemma doc {name} wasn't found.\"\n  modifyEnv (lemmaSetExt.addEntry \u00b7 {\n    name := name.getId,\n    title := title.getString,\n    lemmas := entries })\n\ninstance : Quote LemmaDocEntry `term :=\n\u27e8\u03bb entry => Syntax.mkCApp ``LemmaDocEntry.mk #[quote entry.name, quote entry.userName, quote entry.category, quote entry.content]\u27e9\n\n/-- Declare the list of lemmas that will be displayed in the current level. \nExpects a space separated list of identifiers that refer to either a lemma doc\nentry or a lemma doc set. -/\nelab \"Lemmas\" args:ident* : command => do\n  let env \u2190 getEnv\n  let docs := lemmaDocExt.getState env\n  let sets := lemmaSetExt.getState env\n  let mut lemmas : Array LemmaDocEntry := #[]\n  for arg in args do\n    let name := arg.getId\n    match docs.find? (\u00b7.userName = name) with\n    | some entry => lemmas := lemmas.push entry\n    | none => match sets.find? (\u00b7.name = name) with\n              | some entry => lemmas := lemmas ++ entry.lemmas\n              | none => throwError \"Lemma doc or lemma set {name} wasn't found.\"\n  let lvlIdx \u2190 getCurLevelIdx\n  if lvlIdx > 0 then\n    let some lvl := (\u2190 levelsExt.find? lvlIdx) | throwError \"Unable to find level\"\n    levelsExt.update lvlIdx {lvl with lemmas := lemmas}\n  else\n    throwError \"This command can be used only while building a level.\"\n", "meta": {"author": "PatrickMassot", "repo": "lean4-game-server", "sha": "a193c37ca99386cdd4f01855c80b1a0fa0a4a3c9", "save_path": "github-repos/lean/PatrickMassot-lean4-game-server", "path": "github-repos/lean/PatrickMassot-lean4-game-server/lean4-game-server-a193c37ca99386cdd4f01855c80b1a0fa0a4a3c9/GameServer/Commands.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.03514484917990871, "lm_q1q2_score": 0.007453126144894035}}
{"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 \u2190\n  registerInternalExceptionId `congrHypothesisFailed\n\ndef throwCongrHypothesisFailed : MetaM \u03b1 :=\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\u2081 r\u2082 : Result) : MetaM Result := do\n  match r\u2081.proof? with\n  | none => return r\u2082\n  | some p\u2081 => match r\u2082.proof? with\n    | none    => return { r\u2082 with proof? := r\u2081.proof? }\n    | some p\u2082 => return { r\u2082 with proof? := (\u2190 Meta.mkEqTrans p\u2081 p\u2082) }\n\ndef 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? := (\u2190 Meta.mkCongrFun h a) }\n\ndef mkCongr (r\u2081 r\u2082 : Result) : MetaM Result :=\n  let e := mkApp r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | some h,  none    => return { expr := e, proof? := (\u2190 Meta.mkCongrFun h r\u2082.expr) }\n  | none,    some h  => return { expr := e, proof? := (\u2190 Meta.mkCongrArg r\u2081.expr h) }\n  | some h\u2081, some h\u2082 => return { expr := e, proof? := (\u2190 Meta.mkCongr h\u2081 h\u2082) }\n\nprivate def mkImpCongr (r\u2081 r\u2082 : Result) : MetaM Result := do\n  let e \u2190 mkArrow r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | _,        _      => return { expr := e, proof? := (\u2190 Meta.mkImpCongr (\u2190 r\u2081.getProof) (\u2190 r\u2082.getProof)) } -- TODO specialize if bootleneck\n\n/-- Return true if `e` is of the form `ofNat n` where `n` is a kernel Nat literal -/\ndef isOfNatNatLit (e : Expr) : Bool :=\n  e.isAppOfArity ``OfNat.ofNat 3 && e.appFn!.appArg!.isNatLit\n\nprivate def reduceProj (e : Expr) : MetaM Expr := do\n  match (\u2190 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 (\u2190 getProjectionFnInfo? cinfo.name) with\n    | none => return none\n    | some projInfo =>\n      if projInfo.fromClass then\n        if (\u2190 read).simpTheorems.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 (\u2190 unfoldDefinition? e) with\n        | none   => pure none\n        | some e =>\n          match (\u2190 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 (\u2190 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 (\u2190 isProjectionFn fName) then\n    return none -- should be reduced by `reduceProjFn?`\n  if (\u2190 read).simpTheorems.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 := (\u2190 read).config\n  if cfg.beta then\n    let e' := e.headBeta\n    if e' != e then\n      return (\u2190 reduce e')\n  -- TODO: eta reduction\n  if cfg.proj then\n    match (\u2190 reduceProjFn? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  if cfg.iota then\n    match (\u2190 reduceRecMatcher? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  match (\u2190 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 (\u2190 reduce e))\n\ninductive SimpLetCase where\n  | dep -- `let x := v; b` is not equivalent to `(fun x => b) v`\n  | nondepDepVar -- `let x := v; b` is equivalent to `(fun x => b) v`, but result type depends on `x`\n  | nondep -- `let x := v; b` is equivalent to `(fun x => b) v`, and result type does not depend on `x`\n\ndef getSimpLetCase (n : Name) (t : Expr) (v : Expr) (b : Expr) : MetaM SimpLetCase := do\n  withLocalDeclD n t fun x => do\n    let bx := b.instantiate1 x\n    /- The following step is potentially very expensive when we have many nested let-decls.\n       TODO: handle a block of nested let decls in a single pass if this becomes a performance problem. -/\n    if (\u2190 isTypeCorrect bx) then\n      let bxType \u2190 whnf (\u2190 inferType bx)\n      if (\u2190 dependsOn bxType x.fvarId!) then\n        return SimpLetCase.nondepDepVar\n      else\n        return SimpLetCase.nondep\n    else\n      return SimpLetCase.dep\n\npartial def simp (e : Expr) : M Result := withIncRecDepth do\n  checkMaxHeartbeats \"simp\"\n  let cfg \u2190 getConfig\n  if (\u2190 isProof e) then\n    return { expr := e }\n  if cfg.memoize then\n    if let some result := (\u2190 get).cache.find? e then\n      return result\n  simpLoop { expr := e }\n\nwhere\n  simpLoop (r : Result) : M Result := do\n    let cfg \u2190 getConfig\n    if (\u2190 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 (\u2190 pre r.expr) with\n      | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n      | Step.visit r' =>\n        let r \u2190 mkEqTrans r r'\n        let r \u2190 mkEqTrans r (\u2190 simpStep r.expr)\n        match (\u2190 post r.expr) with\n        | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n        | Step.visit r' =>\n          let r \u2190 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 m e _ => let r \u2190 simp e; return { r with expr := mkMData m r.expr }\n    | Expr.proj ..     => simpProj 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 ..     => return { expr := e }\n    | Expr.lit ..      => simpLit e\n    | Expr.mvar ..     => return { expr := (\u2190 instantiateMVars e) }\n    | Expr.fvar ..     => return { expr := (\u2190 reduceFVar (\u2190 getConfig) e) }\n\n  simpLit (e : Expr) : M Result := do\n    match e.natLit? with\n    | some n =>\n      /- If `OfNat.ofNat` is marked to be unfolded, we do not pack orphan nat literals as `OfNat.ofNat` applications\n         to avoid non-termination. See issue #788.  -/\n      if (\u2190 getSimpTheorems).isDeclToUnfold ``OfNat.ofNat then\n        return { expr := e }\n      else\n        return { expr := (\u2190 mkNumeral (mkConst ``Nat) n) }\n    | none   => return { expr := e }\n\n  simpProj (e : Expr) : M Result := do\n    match (\u2190 reduceProj? e) with\n    | some e => return { expr := e }\n    | none =>\n      let s := e.projExpr!\n      let motive? \u2190 withLocalDeclD `s (\u2190 inferType s) fun s => do\n        let p := e.updateProj! s\n        if (\u2190 dependsOn (\u2190 inferType p) s.fvarId!) then\n          return none\n        else\n          let motive \u2190 mkLambdaFVars #[s] (\u2190 mkEq e p)\n          if !(\u2190 isTypeCorrect motive) then\n            return none\n          else\n            return some motive\n      if let some motive := motive? then\n        let r \u2190 simp s\n        let eNew := e.updateProj! r.expr\n        match r.proof? with\n        | none => return { expr := eNew }\n        | some h =>\n          let hNew \u2190 mkEqNDRec motive (\u2190 mkEqRefl e) h\n          return { expr := eNew, proof? := some hNew }\n      else\n        return { expr := (\u2190 dsimp e) }\n\n  congrArgs (r : Result) (args : Array Expr) : M Result := do\n    if args.isEmpty then\n      return r\n    else\n      let infos := (\u2190 getFunInfoNArgs r.expr args.size).paramInfo\n      let mut r := r\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 \u2190 mkCongr r (\u2190 simp arg)\n        else if (\u2190 whnfD (\u2190 inferType r.expr)).isArrow then\n          r \u2190 mkCongr r (\u2190 simp arg)\n        else\n          r \u2190 mkCongrFun r (\u2190 dsimp arg)\n        i := i + 1\n      return r\n\n  congrDefault (e : Expr) : M Result :=\n    withParent e <| e.withApp fun f args => do\n      congrArgs (\u2190 simp f) args\n\n  /- Return true iff processing the given congruence theorem hypothesis produced a non-refl proof. -/\n  processCongrHypothesis (h : Expr) : M Bool := do\n    forallTelescopeReducing (\u2190 inferType h) fun xs hType => withNewLemmas xs do\n      let lhs \u2190 instantiateMVars hType.appFn!.appArg!\n      let r \u2190 simp lhs\n      let rhs := hType.appArg!\n      rhs.withApp fun m zs => do\n        let val \u2190 mkLambdaFVars zs r.expr\n        unless (\u2190 isDefEq m val) do\n          throwCongrHypothesisFailed\n        unless (\u2190 isDefEq h (\u2190 mkLambdaFVars xs (\u2190 r.getProof))) do\n          throwCongrHypothesisFailed\n        return r.proof?.isSome\n\n  /- Try to rewrite `e` children using the given congruence theorem -/\n  trySimpCongrTheorem? (c : SimpCongrTheorem) (e : Expr) : M (Option Result) := withNewMCtxDepth do\n    trace[Debug.Meta.Tactic.simp.congr] \"{c.theoremName}, {e}\"\n    let lemma \u2190 mkConstWithFreshMVarLevels c.theoremName\n    let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType lemma)\n    if c.hypothesesPos.any (\u00b7 \u2265 xs.size) then\n      return none\n    let lhs := type.appFn!.appArg!\n    let rhs := type.appArg!\n    let numArgs := lhs.getAppNumArgs\n    let mut e := e\n    let mut extraArgs := #[]\n    if e.getAppNumArgs > numArgs then\n      let args := e.getAppArgs\n      e := mkAppN e.getAppFn args[:numArgs]\n      extraArgs := args[numArgs:].toArray\n    if (\u2190 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 (\u2190 processCongrHypothesis x) then\n            modified := true\n        catch ex =>\n          trace[Meta.Tactic.simp.congr] \"processCongrHypothesis {c.theoremName} failed {\u2190 inferType x}\"\n          if ex.isMaxRecDepth then\n            -- Recall that `processCongrHypothesis` invokes `simp` recursively.\n            throw ex\n          else\n            return none\n      unless modified do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} not modified\"\n        return none\n      unless (\u2190 synthesizeArgs c.theoremName xs bis (\u2190 read).discharge?) do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} synthesizeArgs failed\"\n        return none\n      let eNew \u2190 instantiateMVars rhs\n      let proof \u2190 instantiateMVars (mkAppN lemma xs)\n      congrArgs { expr := eNew, proof? := proof } extraArgs\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 congrThms \u2190 getSimpCongrTheorems\n      let cs := congrThms.get f.constName!\n      for c in cs do\n        match (\u2190 trySimpCongrTheorem? 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 \u2190 reduce e\n    if !e.isApp then\n      simp e\n    else if isOfNatNatLit e then\n      -- Recall that we expand \"orphan\" kernel nat literals `n` into `ofNat n`\n      return { expr := e }\n    else\n      congr e\n\n  simpConst (e : Expr) : M Result :=\n    return { expr := (\u2190 reduce e) }\n\n  withNewLemmas {\u03b1} (xs : Array Expr) (f : M \u03b1) : M \u03b1 := do\n    if (\u2190 getConfig).contextual then\n      let mut s \u2190 getSimpTheorems\n      let mut updated := false\n      for x in xs do\n        if (\u2190 isProof x) then\n          s \u2190 s.add #[] x\n          updated := true\n      if updated then\n        withSimpTheorems 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 \u2190 simp e\n      let eNew \u2190 mkLambdaFVars xs r.expr\n      match r.proof? with\n      | none   => return { expr := eNew }\n      | some h =>\n        let p \u2190 xs.foldrM (init := h) fun x h => do\n          mkFunExt (\u2190 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 \u2190 simp p\n    trace[Debug.Meta.Tactic.simp] \"arrow [{(\u2190 getConfig).contextual}] {p} [{\u2190 isProp p}] -> {q} [{\u2190 isProp q}]\"\n    if (\u2190 pure (\u2190 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 \u2190 getSimpTheorems\n        let s \u2190 s.add #[] h\n        withSimpTheorems s do\n          let rq \u2190 simp q\n          match rq.proof? with\n          | none    => mkImpCongr rp rq\n          | some hq =>\n            let hq \u2190 mkLambdaFVars #[h] hq\n            return { expr := (\u2190 mkArrow rp.expr rq.expr), proof? := (\u2190 mkImpCongrCtx (\u2190 rp.getProof) hq) }\n    else\n      mkImpCongr rp (\u2190 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 (\u2190 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 \u2190 simp b\n        let eNew \u2190 mkForallFVars #[x] rb.expr\n        match rb.proof? with\n        | none   => return { expr := eNew }\n        | some h => return { expr := eNew, proof? := (\u2190 mkForallCongr (\u2190 mkLambdaFVars #[x] h)) }\n    else\n      return { expr := (\u2190 dsimp e) }\n\n  simpLet (e : Expr) : M Result := do\n    let Expr.letE n t v b _ := e | unreachable!\n    if (\u2190 getConfig).zeta then\n      return { expr := b.instantiate1 v }\n    else\n      match (\u2190 getSimpLetCase n t v b) with\n      | SimpLetCase.dep => return { expr := (\u2190 dsimp e) }\n      | SimpLetCase.nondep =>\n        let rv \u2190 simp v\n        withLocalDeclD n t fun x => do\n          let bx := b.instantiate1 x\n          let rbx \u2190 simp bx\n          let hb? \u2190 match rbx.proof? with\n            | none => pure none\n            | some h => pure (some (\u2190 mkLambdaFVars #[x] h))\n          let e' := mkLet n t rv.expr (\u2190 abstract rbx.expr #[x])\n          match rv.proof?, hb? with\n          | none,   none   => return { expr := e' }\n          | some h, none   => return { expr := e', proof? := some (\u2190 mkLetValCongr (\u2190 mkLambdaFVars #[x] rbx.expr) h) }\n          | _,      some h => return { expr := e', proof? := some (\u2190 mkLetCongr (\u2190 rv.getProof) h) }\n      | SimpLetCase.nondepDepVar =>\n        let v' \u2190 dsimp v\n        withLocalDeclD n t fun x => do\n          let bx := b.instantiate1 x\n          let rbx \u2190 simp bx\n          let e' := mkLet n t v' (\u2190 abstract rbx.expr #[x])\n          match rbx.proof? with\n          | none => return { expr := e' }\n          | some h =>\n            let h \u2190 mkLambdaFVars #[x] h\n            return { expr := e', proof? := some (\u2190 mkLetBodyCongr v' h) }\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 :=\n  withConfig (fun c => { c with etaStruct := ctx.config.etaStruct }) <| withReducible do\n    simp e methods ctx |>.run' {}\n\npartial def isEqnThmHypothesis (e : Expr) : Bool :=\n  e.isForall && go e\nwhere\n  go (e : Expr) : Bool :=\n    if e.isForall then\n      go e.bindingBody!\n    else\n      e.isConstOf ``False\n\nabbrev Discharge := Expr \u2192 SimpM (Option Expr)\n\ndef dischargeUsingAssumption (e : Expr) : SimpM (Option Expr) := do\n  (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n    if localDecl.isAuxDecl then\n      return none\n    else if (\u2190 isDefEq e localDecl.type) then\n      return some localDecl.toExpr\n    else\n      return none\n\nnamespace DefaultMethods\nmutual\n  partial def discharge? (e : Expr) : SimpM (Option Expr) := do\n    if isEqnThmHypothesis e then\n      let r \u2190 dischargeUsingAssumption e\n      if r.isSome then\n        return r\n    let ctx \u2190 read\n    trace[Meta.Tactic.simp.discharge] \">> discharge?: {e}\"\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 \u2190 simp e { pre := pre, post := post, discharge? := discharge? }\n        if r.expr.isConstOf ``True then\n          try\n            return some (\u2190 mkOfEqTrue (\u2190 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?\nend\n\ndef methods : Methods :=\n  { pre := pre, post := post, discharge? := discharge? }\n\nend DefaultMethods\n\nend Simp\n\ndef simp (e : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM Simp.Result := do profileitM Exception \"simp\" (\u2190 getOptions) do\n  match discharge? with\n  | none   => Simp.main e ctx (methods := Simp.DefaultMethods.methods)\n  | some d => Simp.main e ctx (methods := { pre := (Simp.preDefault . d), post := (Simp.postDefault . d), discharge? := d })\n\n/--\n  Auxiliary method.\n  Given the current `target` of `mvarId`, apply `r` which is a new target and proof that it is equaal to the current one.\n-/\ndef applySimpResultToTarget (mvarId : MVarId) (target : Expr) (r : Simp.Result) : MetaM MVarId := do\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/-- 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) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) := do\n  let target \u2190 instantiateMVars (\u2190 getMVarType mvarId)\n  let r \u2190 simp target ctx discharge?\n  if r.expr.isConstOf ``True then\n    match r.proof? with\n    | some proof => assignExprMVar mvarId  (\u2190 mkOfEqTrue proof)\n    | none => assignExprMVar mvarId (mkConst ``True.intro)\n    return none\n  else\n    applySimpResultToTarget mvarId target r\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) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) :=\n  withMVarContext mvarId do\n    checkNotAssigned mvarId `simp\n    simpTargetCore mvarId ctx discharge?\n\n/--\n  Apply the result `r` for `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 applySimpResultToProp (mvarId : MVarId) (proof : Expr) (prop : Expr) (r : Simp.Result) : MetaM (Option (Expr \u00d7 Expr)) := do\n  if r.expr.isConstOf ``False then\n    match r.proof? with\n    | some eqProof => assignExprMVar mvarId (\u2190 mkFalseElim (\u2190 getMVarType mvarId) (\u2190 mkEqMP eqProof proof))\n    | none => assignExprMVar mvarId (\u2190 mkFalseElim (\u2190 getMVarType mvarId) proof)\n    return none\n  else\n    match r.proof? with\n    | some eqProof => return some ((\u2190 mkEqMP eqProof proof), r.expr)\n    | none =>\n      if r.expr != prop then\n        return some ((\u2190 mkExpectedTypeHint proof r.expr), r.expr)\n      else\n        return some (proof, r.expr)\n\ndef applySimpResultToFVarId (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) : MetaM (Option (Expr \u00d7 Expr)) := do\n  let localDecl \u2190 getLocalDecl fvarId\n  applySimpResultToProp mvarId (mkFVar fvarId) localDecl.type r\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) (discharge? : Option Simp.Discharge := none) : MetaM (Option (Expr \u00d7 Expr)) := do\n  let r \u2190 simp prop ctx discharge?\n  applySimpResultToProp mvarId proof prop r\n\ndef applySimpResultToLocalDeclCore (mvarId : MVarId) (fvarId : FVarId) (r : Option (Expr \u00d7 Expr)) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  match r with\n  | none => return none\n  | some (value, type') =>\n    let localDecl \u2190 getLocalDecl fvarId\n    if localDecl.type != type' then\n      let mvarId \u2190 assert mvarId localDecl.userName type' value\n      let mvarId \u2190 tryClear mvarId localDecl.fvarId\n      let (fvarId, mvarId) \u2190 intro1P mvarId\n      return some (fvarId, mvarId)\n    else\n      return some (fvarId, mvarId)\n\n/--\n  Simplify `simp` result to the given local declaration. Return `none` if the goal was closed.\n  This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/\ndef applySimpResultToLocalDecl (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  applySimpResultToLocalDeclCore mvarId fvarId (\u2190 applySimpResultToFVarId mvarId fvarId r)\n\ndef simpLocalDecl (mvarId : MVarId) (fvarId : FVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  withMVarContext mvarId do\n    checkNotAssigned mvarId `simp\n    let localDecl \u2190 getLocalDecl fvarId\n    let type \u2190 instantiateMVars localDecl.type\n    applySimpResultToLocalDeclCore mvarId fvarId (\u2190 simpStep mvarId (mkFVar fvarId) type ctx discharge?)\n\nabbrev FVarIdToLemmaId := FVarIdMap Name\n\ndef simpGoal (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[]) (fvarIdToLemmaId : FVarIdToLemmaId := {}) : MetaM (Option (Array FVarId \u00d7 MVarId)) := do\n  withMVarContext mvarId do\n    checkNotAssigned mvarId `simp\n    let mut mvarId := mvarId\n    let mut toAssert : Array Hypothesis := #[]\n    for fvarId in fvarIdsToSimp do\n      let localDecl \u2190 getLocalDecl fvarId\n      let type \u2190 instantiateMVars localDecl.type\n      let ctx \u2190 match fvarIdToLemmaId.find? localDecl.fvarId with\n        | none => pure ctx\n        | some thmId => pure { ctx with simpTheorems := ctx.simpTheorems.eraseCore thmId }\n      match (\u2190 simpStep mvarId (mkFVar fvarId) type ctx discharge?) with\n      | none => return none\n      | some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value }\n    if simplifyTarget then\n      match (\u2190 simpTarget mvarId ctx discharge?) with\n      | none => return none\n      | some mvarIdNew => mvarId := mvarIdNew\n    let (fvarIdsNew, mvarIdNew) \u2190 assertHypotheses mvarId toAssert\n    let mvarIdNew \u2190 tryClearMany mvarIdNew fvarIdsToSimp\n    return (fvarIdsNew, mvarIdNew)\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/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815649166448126, "lm_q2_score": 0.03258974229958256, "lm_q1q2_score": 0.0074355612673223}}
{"text": "import Lean.Widget.InteractiveCode\nimport ProofWidgets.Compat\n\nnamespace ProofWidgets\n\n/-- A component is a widget module whose `default` export is a\n[React component](https://react.dev/learn/your-first-component). Every component definition must\nbe annotated with `@[widget_module]`. This makes it possible for the infoview to load the component.\n\n## Execution environment\n\nThe JS environment in which components execute provides a fixed set of libraries accessible via\ndirect `import`, notably\n[`@leanprover/infoview`](https://www.npmjs.com/package/@leanprover/infoview).\nAll [React contexts](https://react.dev/learn/passing-data-deeply-with-context) exported from\n`@leanprover/infoview` are usable from components.\n\n## Lean encoding of props\n\n`Props` is the Lean representation of the type `JsProps` of\n[React props](https://react.dev/learn/passing-props-to-a-component) that the component expects.\nThe `default` export of the module should then have type\n`(props: JsProps & { pos: DocumentPosition }): React.ReactNode` where `DocumentPosition` is\ndefined in `@leanprover/infoview`. `Props` is expected to have a `Lean.Server.RpcEncodable` instance\nspecifying how to encode props as JSON. -/\nstructure Component (Props : Type) extends Module\n\nopen Lean\n\nstructure InteractiveCodeProps where\n  fmt : Widget.CodeWithInfos\n\n#mkrpcenc InteractiveCodeProps\n\n/-- Present pretty-printed code as interactive text.\n\nThe most common use case is to instantiate this component from a `Lean.Expr`. To do so, you must\neagerly pretty-print the `Expr` using `Widget.ppExprTagged`. See also `InteractiveExpr`. -/\n@[widget_module]\ndef InteractiveCode : Component InteractiveCodeProps where\n  javascript := \"\n    import { InteractiveCode } from '@leanprover/infoview'\n    import * as React from 'react'\n    export default function(props) {\n      return React.createElement(InteractiveCode, props)\n    }\"\n\nstructure InteractiveExprProps where\n  expr : Server.WithRpcRef ExprWithCtx\n\n#mkrpcenc InteractiveExprProps\n\n@[server_rpc_method]\ndef ppExprTagged : InteractiveExprProps \u2192 Server.RequestM (Server.RequestTask Widget.CodeWithInfos)\n  | \u27e8\u27e8expr\u27e9\u27e9 => Server.RequestM.asTask <| expr.runMetaM Widget.ppExprTagged\n\n/-- Lazily pretty-print and present a `Lean.Expr` as interactive text.\n\nThis component is preferrable over `InteractiveCode` when the `Expr` will not necessarily be\ndisplayed in the UI (e.g. it may be hidden by default), in which case laziness saves some work.\nOn the other hand if the `Expr` will likely be shown and you are in a `MetaM` context, it is\npreferrable to use the eager `InteractiveCode` in order to avoid the extra client-server roundtrip\nneeded for the pretty-printing RPC call. -/\n@[widget_module]\ndef InteractiveExpr : Component InteractiveExprProps where\n  javascript := include_str \"..\" / \"..\" / \"build\" / \"js\" / \"interactiveExpr.js\"\n\n/-- These are the props passed to a panel widget. A panel widget is a component which can appear\nas a top-level panel in the infoview. For example, a goal state display. See also\n`savePanelWidgetInfo`.\n\nNote that to be a good citizen which doesn't mess up the infoview, a panel widget should be a block\nelement, and should provide some way to collapse it, for example by using `<details>` as the\ntop-level tag. -/\n-- TODO: This contains the fields described in `userWidget.tsx`\nstructure PanelWidgetProps where\n\nend ProofWidgets\n", "meta": {"author": "EdAyers", "repo": "ProofWidgets4", "sha": "c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e", "save_path": "github-repos/lean/EdAyers-ProofWidgets4", "path": "github-repos/lean/EdAyers-ProofWidgets4/ProofWidgets4-c57cc40fcc58ff1ac2a2b52cf34c39d90ba0b11e/ProofWidgets/Component/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.13296423332632276, "lm_q2_score": 0.055823145454283137, "lm_q1q2_score": 0.007422481737192557}}
{"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": "/-\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.ForEachExprWhere\nimport Lean.Util.ReplaceLevel\nimport Lean.Util.ReplaceExpr\nimport Lean.Util.CollectLevelParams\nimport Lean.Meta.Constructions\nimport Lean.Meta.CollectFVars\nimport Lean.Meta.SizeOf\nimport Lean.Meta.Injective\nimport Lean.Meta.IndPredBelow\nimport Lean.Elab.Command\nimport Lean.Elab.ComputedFields\nimport Lean.Elab.DefView\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.Deriving.Basic\n\nnamespace Lean.Elab.Command\nopen Meta\n\nbuiltin_initialize\n  registerTraceClass `Elab.inductive\n\ndef checkValidInductiveModifier [Monad m] [MonadError m] (modifiers : Modifiers) : m Unit := do\n  if modifiers.isNoncomputable then\n    throwError \"invalid use of 'noncomputable' in inductive declaration\"\n  if modifiers.isPartial then\n    throwError \"invalid use of 'partial' in inductive declaration\"\n\ndef checkValidCtorModifier [Monad m] [MonadError m] (modifiers : Modifiers) : m Unit := do\n  if modifiers.isNoncomputable then\n    throwError \"invalid use of 'noncomputable' in constructor declaration\"\n  if modifiers.isPartial then\n    throwError \"invalid use of 'partial' in constructor declaration\"\n  if modifiers.isUnsafe then\n    throwError \"invalid use of 'unsafe' in constructor declaration\"\n  if modifiers.attrs.size != 0 then\n    throwError \"invalid use of attributes in constructor declaration\"\n\nstructure CtorView where\n  ref       : Syntax\n  modifiers : Modifiers\n  declName  : Name\n  binders   : Syntax\n  type?     : Option Syntax\n  deriving Inhabited\n\nstructure ComputedFieldView where\n  ref       : Syntax\n  modifiers : Syntax\n  fieldId   : Name\n  type      : Syntax.Term\n  matchAlts : TSyntax ``Parser.Term.matchAlts\n\nstructure InductiveView where\n  ref             : Syntax\n  declId          : Syntax\n  modifiers       : Modifiers\n  shortDeclName   : Name\n  declName        : Name\n  levelNames      : List Name\n  binders         : Syntax\n  type?           : Option Syntax\n  ctors           : Array CtorView\n  derivingClasses : Array DerivingClassView\n  computedFields  : Array ComputedFieldView\n  deriving Inhabited\n\nstructure ElabHeaderResult where\n  view       : InductiveView\n  lctx       : LocalContext\n  localInsts : LocalInstances\n  params     : Array Expr\n  type       : Expr\n  deriving Inhabited\n\nprivate partial def elabHeaderAux (views : Array InductiveView) (i : Nat) (acc : Array ElabHeaderResult) : TermElabM (Array ElabHeaderResult) :=\n  Term.withAutoBoundImplicitForbiddenPred (fun n => views.any (\u00b7.shortDeclName == n)) do\n    if h : i < views.size then\n      let view := views.get \u27e8i, h\u27e9\n      let acc \u2190 Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do\n        match view.type? with\n        | none         =>\n          let u \u2190 mkFreshLevelMVar\n          let type := mkSort u\n          Term.synthesizeSyntheticMVarsNoPostponing\n          Term.addAutoBoundImplicits' params type fun params type => do\n            return acc.push { lctx := (\u2190 getLCtx), localInsts := (\u2190 getLocalInstances), params, type, view }\n        | some typeStx =>\n          let (type, _) \u2190 Term.withAutoBoundImplicit do\n            let type \u2190 Term.elabType typeStx\n            unless (\u2190 isTypeFormerType type) do\n              throwErrorAt typeStx \"invalid inductive type, resultant type is not a sort\"\n            Term.synthesizeSyntheticMVarsNoPostponing\n            let indices \u2190 Term.addAutoBoundImplicits #[]\n            return (\u2190 mkForallFVars indices type, indices.size)\n          Term.addAutoBoundImplicits' params type fun params type => do\n            trace[Elab.inductive] \"header params: {params}, type: {type}\"\n            return acc.push { lctx := (\u2190 getLCtx), localInsts := (\u2190 getLocalInstances), params, type, view }\n      elabHeaderAux views (i+1) acc\n    else\n      return acc\n\nprivate def checkNumParams (rs : Array ElabHeaderResult) : TermElabM Nat := do\n  let numParams := rs[0]!.params.size\n  for r in rs do\n    unless r.params.size == numParams do\n      throwErrorAt r.view.ref \"invalid inductive type, number of parameters mismatch in mutually inductive datatypes\"\n  return numParams\n\nprivate def checkUnsafe (rs : Array ElabHeaderResult) : TermElabM Unit := do\n  let isUnsafe := rs[0]!.view.modifiers.isUnsafe\n  for r in rs do\n    unless r.view.modifiers.isUnsafe == isUnsafe do\n      throwErrorAt r.view.ref \"invalid inductive type, cannot mix unsafe and safe declarations in a mutually inductive datatypes\"\n\nprivate def checkLevelNames (views : Array InductiveView) : TermElabM Unit := do\n  if views.size > 1 then\n    let levelNames := views[0]!.levelNames\n    for view in views do\n      unless view.levelNames == levelNames do\n        throwErrorAt view.ref \"invalid inductive type, universe parameters mismatch in mutually inductive datatypes\"\n\nprivate def mkTypeFor (r : ElabHeaderResult) : TermElabM Expr := do\n  withLCtx r.lctx r.localInsts do\n    mkForallFVars r.params r.type\n\nprivate def throwUnexpectedInductiveType : TermElabM \u03b1 :=\n  throwError \"unexpected inductive resulting type\"\n\nprivate def eqvFirstTypeResult (firstType type : Expr) : MetaM Bool :=\n  forallTelescopeReducing firstType fun _ firstTypeResult => isDefEq firstTypeResult type\n\n-- Auxiliary function for checking whether the types in mutually inductive declaration are compatible.\nprivate partial def checkParamsAndResultType (type firstType : Expr) (numParams : Nat) : TermElabM Unit := do\n  try\n    forallTelescopeCompatible type firstType numParams fun _ type firstType =>\n    forallTelescopeReducing type fun _ type =>\n    forallTelescopeReducing firstType fun _ firstType => do\n      let type \u2190 whnfD type\n      match type with\n      | .sort .. =>\n        unless (\u2190 isDefEq firstType type) do\n          throwError \"resulting universe mismatch, given{indentExpr type}\\nexpected type{indentExpr firstType}\"\n      | _ =>\n        throwError \"unexpected inductive resulting type\"\n  catch\n    | Exception.error ref msg => throw (Exception.error ref m!\"invalid mutually inductive types, {msg}\")\n    | ex => throw ex\n\n-- Auxiliary function for checking whether the types in mutually inductive declaration are compatible.\nprivate def checkHeader (r : ElabHeaderResult) (numParams : Nat) (firstType? : Option Expr) : TermElabM Expr := do\n  let type \u2190 mkTypeFor r\n  match firstType? with\n  | none           => return type\n  | some firstType =>\n    withRef r.view.ref <| checkParamsAndResultType type firstType numParams\n    return firstType\n\n-- Auxiliary function for checking whether the types in mutually inductive declaration are compatible.\nprivate partial def checkHeaders (rs : Array ElabHeaderResult) (numParams : Nat) (i : Nat) (firstType? : Option Expr) : TermElabM Unit := do\n  if i < rs.size then\n    let type \u2190 checkHeader rs[i]! numParams firstType?\n    checkHeaders rs numParams (i+1) type\n\nprivate def elabHeader (views : Array InductiveView) : TermElabM (Array ElabHeaderResult) := do\n  let rs \u2190 elabHeaderAux views 0 #[]\n  if rs.size > 1 then\n    checkUnsafe rs\n    let numParams \u2190 checkNumParams rs\n    checkHeaders rs numParams 0 none\n  return rs\n\n/-- Create a local declaration for each inductive type in `rs`, and execute `x params indFVars`, where `params` are the inductive type parameters and\n   `indFVars` are the new local declarations.\n   We use the local context/instances and parameters of rs[0].\n   Note that this method is executed after we executed `checkHeaders` and established all\n   parameters are compatible. -/\nprivate partial def withInductiveLocalDecls (rs : Array ElabHeaderResult) (x : Array Expr \u2192 Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let namesAndTypes \u2190 rs.mapM fun r => do\n    let type \u2190 mkTypeFor r\n    pure (r.view.declName, r.view.shortDeclName, type)\n  let r0     := rs[0]!\n  let params := r0.params\n  withLCtx r0.lctx r0.localInsts <| withRef r0.view.ref do\n    let rec loop (i : Nat) (indFVars : Array Expr) := do\n      if h : i < namesAndTypes.size then\n        let (declName, shortDeclName, type) := namesAndTypes.get \u27e8i, h\u27e9\n        Term.withAuxDecl shortDeclName type declName fun indFVar => loop (i+1) (indFVars.push indFVar)\n      else\n        x params indFVars\n    loop 0 #[]\n\nprivate def isInductiveFamily (numParams : Nat) (indFVar : Expr) : TermElabM Bool := do\n  let indFVarType \u2190 inferType indFVar\n  forallTelescopeReducing indFVarType fun xs _ =>\n    return xs.size > numParams\n\nprivate def getArrowBinderNames (type : Expr) : Array Name :=\n  go type #[]\nwhere\n  go (type : Expr) (acc : Array Name) : Array Name :=\n    match type with\n    | .forallE n _ b _ => go b (acc.push n)\n    | .mdata _ b       => go b acc\n    | _ => acc\n\n/--\n  Replace binder names in `type` with `newNames`.\n  Remark: we only replace the names for binder containing macroscopes.\n-/\nprivate def replaceArrowBinderNames (type : Expr) (newNames : Array Name) : Expr :=\n  go type 0\nwhere\n  go (type : Expr) (i : Nat) : Expr :=\n    if i < newNames.size then\n      match type with\n      | .forallE n d b bi =>\n        if n.hasMacroScopes then\n          mkForall newNames[i]! bi d (go b (i+1))\n        else\n          mkForall n bi d (go b (i+1))\n      | _ => type\n    else\n      type\n\n/--\n  Reorder contructor arguments to improve the effectiveness of the `fixedIndicesToParams` method.\n\n  The idea is quite simple. Given a constructor type of the form\n  ```\n  (a\u2081 : A\u2081) \u2192 ... \u2192 (a\u2099 : A\u2099) \u2192 C b\u2081 ... b\u2098\n  ```\n  We try to find the longest prefix `b\u2081 ... b\u1d62`, `i \u2264 m` s.t.\n  - each `b\u2096` is in `{a\u2081, ..., a\u2099}`\n  - each `b\u2096` only depends on variables in `{b\u2081, ..., b\u2096\u208b\u2081}`\n\n  Then, it moves this prefix `b\u2081 ... b\u1d62` to the front.\n\n  Remark: We only reorder implicit arguments that have macroscopes. See issue #1156.\n  The macroscope test is an approximation, we could have restricted ourselves to auto-implicit arguments.\n-/\nprivate def reorderCtorArgs (ctorType : Expr) : MetaM Expr := do\n  forallTelescopeReducing ctorType fun as type => do\n    /- `type` is of the form `C ...` where `C` is the inductive datatype being defined. -/\n    let bs := type.getAppArgs\n    let mut as  := as\n    let mut bsPrefix := #[]\n    for b in bs do\n      unless b.isFVar && as.contains b do\n        break\n      let localDecl \u2190 getFVarLocalDecl b\n      if localDecl.binderInfo.isExplicit then\n        break\n      unless localDecl.userName.hasMacroScopes do\n        break\n      if (\u2190 localDeclDependsOnPred localDecl fun fvarId => as.any fun p => p.fvarId! == fvarId) then\n        break\n      bsPrefix := bsPrefix.push b\n      as := as.erase b\n    if bsPrefix.isEmpty then\n      return ctorType\n    else\n      let r \u2190 mkForallFVars (bsPrefix ++ as) type\n      /- `r` already contains the resulting type.\n         To be able to produce more better error messages, we copy the first `bsPrefix.size` binder names from `C` to `r`.\n         This is important when some of contructor parameters were inferred using the auto-bound implicit feature.\n         For example, in the following declaration.\n         ```\n          inductive Member : \u03b1 \u2192 List \u03b1 \u2192 Type u\n            | head : Member a (a::as)\n            | tail : Member a bs \u2192 Member a (b::bs)\n         ```\n         if we do not copy the binder names\n         ```\n         #check @Member.head\n         ```\n         produces `@Member.head : {x : Type u_1} \u2192 {a : x} \u2192 {as : List x} \u2192 Member a (a :: as)`\n         which is correct, but a bit confusing. By copying the binder names, we obtain\n         `@Member.head : {\u03b1 : Type u_1} \u2192 {a : \u03b1} \u2192 {as : List \u03b1} \u2192 Member a (a :: as)`\n       -/\n      let C := type.getAppFn\n      let binderNames := getArrowBinderNames (\u2190 instantiateMVars (\u2190 inferType C))\n      return replaceArrowBinderNames r binderNames[:bsPrefix.size]\n\n/--\n  Execute `k` with updated binder information for `xs`. Any `x` that is explicit becomes implicit.\n-/\nprivate def withExplicitToImplicit (xs : Array Expr) (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let mut toImplicit := #[]\n  for x in xs do\n    if (\u2190 getFVarLocalDecl x).binderInfo.isExplicit then\n      toImplicit := toImplicit.push (x.fvarId!, BinderInfo.implicit)\n  withNewBinderInfos toImplicit k\n\n/--\n  Elaborate constructor types.\n\n  Remark: we check whether the resulting type is correct, and the parameter occurrences are consistent, but\n  we currently do not check for:\n  - Positivity (it is a rare failure, and the kernel already checks for it).\n  - Universe constraints (the kernel checks for it).\n-/\nprivate def elabCtors (indFVars : Array Expr) (indFVar : Expr) (params : Array Expr) (r : ElabHeaderResult) : TermElabM (List Constructor) := withRef r.view.ref do\n  let indFamily \u2190 isInductiveFamily params.size indFVar\n  r.view.ctors.toList.mapM fun ctorView =>\n    Term.withAutoBoundImplicit <| Term.elabBinders ctorView.binders.getArgs fun ctorParams =>\n      withRef ctorView.ref do\n        let rec elabCtorType (k : Expr \u2192 TermElabM Constructor) : TermElabM Constructor := do\n          match ctorView.type? with\n          | none          =>\n            if indFamily then\n              throwError \"constructor resulting type must be specified in inductive family declaration\"\n            k <| mkAppN indFVar params\n          | some ctorType =>\n            let type \u2190 Term.elabType ctorType\n            trace[Elab.inductive] \"elabType {ctorView.declName} : {type} \"\n            Term.synthesizeSyntheticMVars (mayPostpone := true)\n            let type \u2190 instantiateMVars type\n            let type \u2190 checkParamOccs type\n            forallTelescopeReducing type fun _ resultingType => do\n              unless resultingType.getAppFn == indFVar do\n                throwError \"unexpected constructor resulting type{indentExpr resultingType}\"\n              unless (\u2190 isType resultingType) do\n                throwError \"unexpected constructor resulting type, type expected{indentExpr resultingType}\"\n            k type\n        elabCtorType fun type => do\n          Term.synthesizeSyntheticMVarsNoPostponing\n          let ctorParams \u2190 Term.addAutoBoundImplicits ctorParams\n          let except (mvarId : MVarId) := ctorParams.any fun ctorParam => ctorParam.isMVar && ctorParam.mvarId! == mvarId\n          /-\n            We convert metavariables in the resulting type info extra parameters. Otherwise, we would not be able to elaborate\n            declarations such as\n            ```\n            inductive Palindrome : List \u03b1 \u2192 Prop where\n              | nil      : Palindrome [] -- We would get an error here saying \"failed to synthesize implicit argument\" at `@List.nil ?m`\n              | single   : (a : \u03b1) \u2192 Palindrome [a]\n              | sandwich : (a : \u03b1) \u2192 Palindrome as \u2192 Palindrome ([a] ++ as ++ [a])\n            ```\n            We used to also collect unassigned metavariables on `ctorParams`, but it produced counterintuitive behavior.\n            For example, the following declaration used to be accepted.\n            ```\n            inductive Foo\n            | bar (x)\n\n            #check Foo.bar\n            -- @Foo.bar : {x : Sort u_1} \u2192 x \u2192 Foo\n            ```\n            which is also inconsistent with the behavior of auto implicits in definitions. For example, the following example was never accepted.\n            ```\n            def bar (x) := 1\n            ```\n          -/\n          let extraCtorParams \u2190 Term.collectUnassignedMVars (\u2190 instantiateMVars type) #[] except\n          trace[Elab.inductive] \"extraCtorParams: {extraCtorParams}\"\n          /- We must abstract `extraCtorParams` and `ctorParams` simultaneously to make\n             sure we do not create auxiliary metavariables. -/\n          let type  \u2190 mkForallFVars (extraCtorParams ++ ctorParams) type\n          let type \u2190 reorderCtorArgs type\n          let type \u2190 mkForallFVars params type\n          trace[Elab.inductive] \"{ctorView.declName} : {type}\"\n          return { name := ctorView.declName, type }\nwhere\n  checkParamOccs (ctorType : Expr) : MetaM Expr :=\n    let visit (e : Expr) : MetaM TransformStep := do\n      let f := e.getAppFn\n      if indFVars.contains f then\n        let mut args := e.getAppArgs\n        unless args.size \u2265 params.size do\n          throwError \"unexpected inductive type occurrence{indentExpr e}\"\n        for i in [:params.size] do\n          let param := params[i]!\n          let arg := args[i]!\n          unless (\u2190 isDefEq param arg) do\n            throwError \"inductive datatype parameter mismatch{indentExpr arg}\\nexpected{indentExpr param}\"\n          args := args.set! i param\n        return TransformStep.done (mkAppN f args)\n      else\n        return .continue\n    transform ctorType (pre := visit)\n\nprivate def getResultingUniverse : List InductiveType \u2192 TermElabM Level\n  | []           => throwError \"unexpected empty inductive declaration\"\n  | indType :: _ => forallTelescopeReducing indType.type fun _ r => do\n    let r \u2190 whnfD r\n    match r with\n    | Expr.sort u => return u\n    | _           => throwError \"unexpected inductive type resulting type{indentExpr r}\"\n\n/--\n  Return `some ?m` if `u` is of the form `?m + k`.\n  Return none if `u` does not contain universe metavariables.\n  Throw exception otherwise. -/\ndef shouldInferResultUniverse (u : Level) : TermElabM (Option LMVarId) := do\n  let u \u2190 instantiateLevelMVars u\n  if u.hasMVar then\n    match u.getLevelOffset with\n    | Level.mvar mvarId => return some mvarId\n    | _ =>\n      throwError \"cannot infer resulting universe level of inductive datatype, given level contains metavariables {mkSort u}, provide universe explicitly\"\n  else\n    return none\n\n/--\n  Convert universe metavariables into new parameters. It skips `univToInfer?` (the inductive datatype resulting universe) because\n  it should be inferred later using `inferResultingUniverse`.\n-/\nprivate def levelMVarToParam (indTypes : List InductiveType) (univToInfer? : Option LMVarId) : TermElabM (List InductiveType) :=\n  indTypes.mapM fun indType => do\n    let type  \u2190 levelMVarToParam' indType.type\n    let ctors \u2190 indType.ctors.mapM fun ctor => do\n      let ctorType \u2190 levelMVarToParam' ctor.type\n      return { ctor with type := ctorType }\n    return { indType with ctors, type }\nwhere\n  levelMVarToParam' (type : Expr) : TermElabM Expr := do\n    Term.levelMVarToParam type (except := fun mvarId => univToInfer? == some mvarId)\n\ndef mkResultUniverse (us : Array Level) (rOffset : Nat) : Level :=\n  if us.isEmpty && rOffset == 0 then\n    levelOne\n  else\n    let r := Level.mkNaryMax us.toList\n    if rOffset == 0 && !r.isZero && !r.isNeverZero then\n      mkLevelMax r levelOne |>.normalize\n    else\n      r.normalize\n\n /--\n   Auxiliary function for `updateResultingUniverse`\n   `accLevel u r rOffset` add `u` to state if it is not already there and\n   it is different from the resulting universe level `r+rOffset`.\n\n\n   If `u` is a `max`, then its components are recursively processed.\n   If `u` is a `succ` and `rOffset > 0`, we process the `u`s child using `rOffset-1`.\n\n   This method is used to infer the resulting universe level of an inductive datatype.\n -/\ndef accLevel (u : Level) (r : Level) (rOffset : Nat) : OptionT (StateT (Array Level) Id) Unit := do\n  go u rOffset\nwhere\n  go (u : Level) (rOffset : Nat) : OptionT (StateT (Array Level) Id) Unit := do\n    match u, rOffset with\n    | .max u v,  rOffset   => go u rOffset; go v rOffset\n    | .imax u v, rOffset   => go u rOffset; go v rOffset\n    | .zero,     _         => return ()\n    | .succ u,   rOffset+1 => go u rOffset\n    | u,         rOffset   =>\n      if rOffset == 0 && u == r then\n        return ()\n      else if r.occurs u  then\n        failure\n      else if rOffset > 0 then\n        failure\n      else if (\u2190 get).contains u then\n        return ()\n      else\n        modify fun us => us.push u\n\n/--\n  Auxiliary function for `updateResultingUniverse`\n  `accLevelAtCtor ctor ctorParam r rOffset` add `u` (`ctorParam`'s universe) to state if it is not already there and\n  it is different from the resulting universe level `r+rOffset`.\n\n  See `accLevel`.\n-/\ndef accLevelAtCtor (ctor : Constructor) (ctorParam : Expr) (r : Level) (rOffset : Nat) : StateRefT (Array Level) TermElabM Unit := do\n  let type \u2190 inferType ctorParam\n  let u \u2190 instantiateLevelMVars (\u2190 getLevel type)\n  match (\u2190 modifyGet fun s => accLevel u r rOffset |>.run |>.run s) with\n  | some _ => pure ()\n  | none =>\n    let typeType \u2190 inferType type\n    let mut msg := m!\"failed to compute resulting universe level of inductive datatype, constructor '{ctor.name}' has type{indentExpr ctor.type}\\nparameter\"\n    let localDecl \u2190 getFVarLocalDecl ctorParam\n    unless localDecl.userName.hasMacroScopes do\n      msg := msg ++ m!\" '{ctorParam}'\"\n    msg := msg ++ m!\" has type{indentD m!\"{type} : {typeType}\"}\\ninductive type resulting type{indentExpr (mkSort (r.addOffset rOffset))}\"\n    if r.isMVar then\n      msg := msg ++ \"\\nrecall that Lean only infers the resulting universe level automatically when there is a unique solution for the universe level constraints, consider explicitly providing the inductive type resulting universe level\"\n    throwError msg\n\n/--\n  Execute `k` using the `Syntax` reference associated with constructor `ctorName`.\n-/\ndef withCtorRef [Monad m] [MonadRef m] (views : Array InductiveView) (ctorName : Name) (k : m \u03b1) : m \u03b1 := do\n  for view in views do\n    for ctorView in view.ctors do\n      if ctorView.declName == ctorName then\n        return (\u2190 withRef ctorView.ref k)\n  k\n\n/-- Auxiliary function for `updateResultingUniverse` -/\nprivate partial def collectUniverses (views : Array InductiveView) (r : Level) (rOffset : Nat) (numParams : Nat) (indTypes : List InductiveType) : TermElabM (Array Level) := do\n  let (_, us) \u2190 go |>.run #[]\n  return us\nwhere\n  go : StateRefT (Array Level) TermElabM Unit :=\n    indTypes.forM fun indType => indType.ctors.forM fun ctor =>\n      withCtorRef views ctor.name do\n        forallTelescopeReducing ctor.type fun ctorParams _ =>\n          for ctorParam in ctorParams[numParams:] do\n            accLevelAtCtor ctor ctorParam r rOffset\n\nprivate def updateResultingUniverse (views : Array InductiveView) (numParams : Nat) (indTypes : List InductiveType) : TermElabM (List InductiveType) := do\n  let r \u2190 getResultingUniverse indTypes\n  let rOffset : Nat   := r.getOffset\n  let r       : Level := r.getLevelOffset\n  unless r.isMVar do\n    throwError \"failed to compute resulting universe level of inductive datatype, provide universe explicitly: {r}\"\n  let us \u2190 collectUniverses views r rOffset numParams indTypes\n  trace[Elab.inductive] \"updateResultingUniverse us: {us}, r: {r}, rOffset: {rOffset}\"\n  let rNew := mkResultUniverse us rOffset\n  assignLevelMVar r.mvarId! rNew\n  indTypes.mapM fun indType => do\n    let type \u2190 instantiateMVars indType.type\n    let ctors \u2190 indType.ctors.mapM fun ctor => return { ctor with type := (\u2190 instantiateMVars ctor.type) }\n    return { indType with type, ctors }\n\nregister_builtin_option bootstrap.inductiveCheckResultingUniverse : Bool := {\n    defValue := true,\n    group    := \"bootstrap\",\n    descr    := \"by default the `inductive/structure commands report an error if the resulting universe is not zero, but may be zero for some universe parameters. Reason: unless this type is a subsingleton, it is hardly what the user wants since it can only eliminate into `Prop`. In the `Init` package, we define subsingletons, and we use this option to disable the check. This option may be deleted in the future after we improve the validator\"\n}\n\ndef checkResultingUniverse (u : Level) : TermElabM Unit := do\n  if bootstrap.inductiveCheckResultingUniverse.get (\u2190 getOptions) then\n    let u \u2190 instantiateLevelMVars u\n    if !u.isZero && !u.isNeverZero then\n      throwError \"invalid universe polymorphic type, the resultant universe is not Prop (i.e., 0), but it may be Prop for some parameter values (solution: use 'u+1' or 'max 1 u'{indentD u}\"\n\nprivate def checkResultingUniverses (views : Array InductiveView) (numParams : Nat) (indTypes : List InductiveType) : TermElabM Unit := do\n  let u := (\u2190 instantiateLevelMVars (\u2190 getResultingUniverse indTypes)).normalize\n  checkResultingUniverse u\n  unless u.isZero do\n    indTypes.forM fun indType => indType.ctors.forM fun ctor =>\n      forallTelescopeReducing ctor.type fun ctorArgs _ => do\n        for ctorArg in ctorArgs[numParams:] do\n          let type \u2190 inferType ctorArg\n          let v := (\u2190 instantiateLevelMVars (\u2190 getLevel type)).normalize\n          let rec check (v' : Level) (u' : Level) : TermElabM Unit :=\n            match v', u' with\n            | .succ v', .succ u' => check v' u'\n            | .mvar id, .param ..  =>\n              /- Special case:\n                 The constructor parameter `v` is at unverse level `?v+k` and\n                 the resulting inductive universe level is `u'+k`, where `u'` is a parameter (or zero).\n                 Thus, `?v := u'` is the only choice for satisfying the universe contraint `?v+k <= u'+k`.\n                 Note that, we still generate an error for cases where there is more than one of satisfying the constraint.\n                 Examples:\n                 -----------------------------------------------------------\n                 | ctor universe level | inductive datatype universe level |\n                 -----------------------------------------------------------\n                 |   ?v                | max u w                           |\n                 -----------------------------------------------------------\n                 |   ?v                | u + 1                             |\n                 -----------------------------------------------------------\n              -/\n              assignLevelMVar id u'\n            | .mvar id, .zero => assignLevelMVar id u' -- TODO: merge with previous case\n            | _, _ =>\n              unless u.geq v do\n                let mut msg := m!\"invalid universe level in constructor '{ctor.name}', parameter\"\n                let localDecl \u2190 getFVarLocalDecl ctorArg\n                unless localDecl.userName.hasMacroScopes do\n                  msg := msg ++ m!\" '{ctorArg}'\"\n                msg := msg ++ m!\" has type{indentExpr type}\"\n                msg := msg ++ m!\"\\nat universe level{indentD v}\"\n                msg := msg ++ m!\"\\nit must be smaller than or equal to the inductive datatype universe level{indentD u}\"\n                withCtorRef views ctor.name <| throwError msg\n          check v u\n\nprivate def collectUsed (indTypes : List InductiveType) : StateRefT CollectFVars.State MetaM Unit := do\n  indTypes.forM fun indType => do\n    indType.type.collectFVars\n    indType.ctors.forM fun ctor =>\n      ctor.type.collectFVars\n\nprivate def removeUnused (vars : Array Expr) (indTypes : List InductiveType) : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed indTypes).run {}\n  Meta.removeUnused vars used\n\nprivate def withUsed {\u03b1} (vars : Array Expr) (indTypes : List InductiveType) (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnused vars indTypes\n  withLCtx lctx localInsts <| k vars\n\nprivate def updateParams (vars : Array Expr) (indTypes : List InductiveType) : TermElabM (List InductiveType) :=\n  indTypes.mapM fun indType => do\n    let type \u2190 mkForallFVars vars indType.type\n    let ctors \u2190 indType.ctors.mapM fun ctor => do\n      let ctorType \u2190 withExplicitToImplicit vars (mkForallFVars vars ctor.type)\n      return { ctor with type := ctorType }\n    return { indType with type, ctors }\n\nprivate def collectLevelParamsInInductive (indTypes : List InductiveType) : Array Name := Id.run do\n  let mut usedParams : CollectLevelParams.State := {}\n  for indType in indTypes do\n    usedParams := collectLevelParams usedParams indType.type\n    for ctor in indType.ctors do\n      usedParams := collectLevelParams usedParams ctor.type\n  return usedParams.params\n\nprivate def mkIndFVar2Const (views : Array InductiveView) (indFVars : Array Expr) (levelNames : List Name) : ExprMap Expr := Id.run do\n  let levelParams := levelNames.map mkLevelParam;\n  let mut m : ExprMap Expr := {}\n  for i in [:views.size] do\n    let view    := views[i]!\n    let indFVar := indFVars[i]!\n    m := m.insert indFVar (mkConst view.declName levelParams)\n  return m\n\n/-- Remark: `numVars <= numParams`. `numVars` is the number of context `variables` used in the inductive declaration,\n   and `numParams` is `numVars` + number of explicit parameters provided in the declaration. -/\nprivate def replaceIndFVarsWithConsts (views : Array InductiveView) (indFVars : Array Expr) (levelNames : List Name)\n    (numVars : Nat) (numParams : Nat) (indTypes : List InductiveType) : TermElabM (List InductiveType) :=\n  let indFVar2Const := mkIndFVar2Const views indFVars levelNames\n  indTypes.mapM fun indType => do\n    let ctors \u2190 indType.ctors.mapM fun ctor => do\n      let type \u2190 forallBoundedTelescope ctor.type numParams fun params type => do\n        let type := type.replace fun e =>\n          if !e.isFVar then\n            none\n          else match indFVar2Const.find? e with\n            | none   => none\n            | some c => mkAppN c (params.extract 0 numVars)\n        instantiateMVars (\u2190 mkForallFVars params type)\n      return { ctor with type }\n    return { indType with ctors }\n\nprivate def mkAuxConstructions (views : Array InductiveView) : TermElabM Unit := do\n  let env \u2190 getEnv\n  let hasEq   := env.contains ``Eq\n  let hasHEq  := env.contains ``HEq\n  let hasUnit := env.contains ``PUnit\n  let hasProd := env.contains ``Prod\n  for view in views do\n    let n := view.declName\n    mkRecOn n\n    if hasUnit then mkCasesOn n\n    if hasUnit && hasEq && hasHEq then mkNoConfusion n\n    if hasUnit && hasProd then mkBelow n\n    if hasUnit && hasProd then mkIBelow n\n  for view in views do\n    let n := view.declName;\n    if hasUnit && hasProd then mkBRecOn n\n    if hasUnit && hasProd then mkBInductionOn n\n\nprivate def getArity (indType : InductiveType) : MetaM Nat :=\n  forallTelescopeReducing indType.type fun xs _ => return xs.size\n\nprivate def resetMaskAt (mask : Array Bool) (i : Nat) : Array Bool :=\n  if h : i < mask.size then\n    mask.set \u27e8i, h\u27e9 false\n  else\n    mask\n\n/--\n  Compute a bit-mask that for `indType`. The size of the resulting array `result` is the arity of `indType`.\n  The first `numParams` elements are `false` since they are parameters.\n  For `i \u2208 [numParams, arity)`, we have that `result[i]` if this index of the inductive family is fixed.\n-/\nprivate def computeFixedIndexBitMask (numParams : Nat) (indType : InductiveType) (indFVars : Array Expr) : MetaM (Array Bool) := do\n  let arity \u2190 getArity indType\n  if arity \u2264 numParams then\n    return mkArray arity false\n  else\n    let maskRef \u2190 IO.mkRef (mkArray numParams false ++ mkArray (arity - numParams) true)\n    let rec go (ctors : List Constructor) : MetaM (Array Bool) := do\n      match ctors with\n      | [] => maskRef.get\n      | ctor :: ctors =>\n        forallTelescopeReducing ctor.type fun xs type => do\n          let typeArgs := type.getAppArgs\n          for i in [numParams:arity] do\n            unless i < xs.size && xs[i]! == typeArgs[i]! do -- Remark: if we want to allow arguments to be rearranged, this test should be xs.contains typeArgs[i]\n              maskRef.modify fun mask => mask.set! i false\n          for x in xs[numParams:] do\n            let xType \u2190 inferType x\n            let cond (e : Expr) := indFVars.any (fun indFVar => e.getAppFn == indFVar) && e.getAppNumArgs > numParams\n            xType.forEachWhere cond fun e => do\n              let eArgs := e.getAppArgs\n              for i in [numParams:eArgs.size] do\n                if i >= typeArgs.size then\n                  maskRef.modify (resetMaskAt \u00b7 i)\n                else\n                  unless eArgs[i]! == typeArgs[i]! do\n                    maskRef.modify (resetMaskAt \u00b7 i)\n        go ctors\n    go indType.ctors\n\n/-- Return true iff `arrowType` is an arrow and its domain is defeq to `type` -/\nprivate def isDomainDefEq (arrowType : Expr) (type : Expr) : MetaM Bool := do\n  if !arrowType.isForall then\n    return false\n  else\n    /-\n      We used to use `withNewMCtxDepth` to make sure we do not assign universe metavariables,\n      but it was not satisfactory. For example, in declarations such as\n      ```\n      inductive Eq : \u03b1 \u2192 \u03b1 \u2192 Prop where\n      | refl (a : \u03b1) : Eq a a\n      ```\n      We want the first two indices to be promoted to parameters, and this will only\n      happen if we can assign universe metavariables.\n    -/\n    isDefEq arrowType.bindingDomain! type\n\n/--\n  Convert fixed indices to parameters.\n-/\nprivate partial def fixedIndicesToParams (numParams : Nat) (indTypes : Array InductiveType) (indFVars : Array Expr) : MetaM Nat := do\n  let masks \u2190 indTypes.mapM (computeFixedIndexBitMask numParams \u00b7 indFVars)\n  if masks.all fun mask => !mask.contains true then\n    return numParams\n  trace[Elab.inductive] \"masks: {masks}\"\n  -- We process just a non-fixed prefix of the indices for now. Reason: we don't want to change the order.\n  -- TODO: extend it in the future. For example, it should be reasonable to change\n  -- the order of indices generated by the auto implicit feature.\n  let mask := masks[0]!\n  forallBoundedTelescope indTypes[0]!.type numParams fun params type => do\n    let otherTypes \u2190 indTypes[1:].toArray.mapM fun indType => do whnfD (\u2190 instantiateForall indType.type params)\n    let ctorTypes \u2190 indTypes.toList.mapM fun indType => indType.ctors.mapM fun ctor => do whnfD (\u2190 instantiateForall ctor.type params)\n    let typesToCheck := otherTypes.toList ++ ctorTypes.join\n    let rec go (i : Nat) (type : Expr) (typesToCheck : List Expr) : MetaM Nat := do\n      if i < mask.size then\n        if !masks.all fun mask => i < mask.size && mask[i]! then\n           return i\n        if !type.isForall then\n          return i\n        let paramType := type.bindingDomain!\n        if !(\u2190 typesToCheck.allM fun type => isDomainDefEq type paramType) then\n          trace[Elab.inductive] \"domain not def eq: {i}, {type} =?= {paramType}\"\n          return i\n        withLocalDeclD `a paramType fun paramNew => do\n          let typesToCheck \u2190 typesToCheck.mapM fun type => whnfD (type.bindingBody!.instantiate1 paramNew)\n          go (i+1) (type.bindingBody!.instantiate1 paramNew) typesToCheck\n      else\n        return i\n    go numParams type typesToCheck\n\nprivate def mkInductiveDecl (vars : Array Expr) (views : Array InductiveView) : TermElabM Unit := Term.withoutSavingRecAppSyntax do\n  let view0 := views[0]!\n  let scopeLevelNames \u2190 Term.getLevelNames\n  checkLevelNames views\n  let allUserLevelNames := view0.levelNames\n  let isUnsafe          := view0.modifiers.isUnsafe\n  withRef view0.ref <| Term.withLevelNames allUserLevelNames do\n    let rs \u2190 elabHeader views\n    withInductiveLocalDecls rs fun params indFVars => do\n      trace[Elab.inductive] \"indFVars: {indFVars}\"\n      let mut indTypesArray := #[]\n      for i in [:views.size] do\n        let indFVar := indFVars[i]!\n        Term.addLocalVarInfo views[i]!.declId indFVar\n        let r       := rs[i]!\n        let type  \u2190 mkForallFVars params r.type\n        let ctors \u2190 withExplicitToImplicit params (elabCtors indFVars indFVar params r)\n        indTypesArray := indTypesArray.push { name := r.view.declName, type, ctors }\n      Term.synthesizeSyntheticMVarsNoPostponing\n      let numExplicitParams \u2190 fixedIndicesToParams params.size indTypesArray indFVars\n      trace[Elab.inductive] \"numExplicitParams: {numExplicitParams}\"\n      let indTypes := indTypesArray.toList\n      let u \u2190 getResultingUniverse indTypes\n      let univToInfer? \u2190 shouldInferResultUniverse u\n      withUsed vars indTypes fun vars => do\n        let numVars   := vars.size\n        let numParams := numVars + numExplicitParams\n        let indTypes \u2190 updateParams vars indTypes\n        let indTypes \u2190 if let some univToInfer := univToInfer? then\n          updateResultingUniverse views numParams (\u2190 levelMVarToParam indTypes univToInfer)\n        else\n          checkResultingUniverses views numParams indTypes\n          levelMVarToParam indTypes none\n        let usedLevelNames := collectLevelParamsInInductive indTypes\n        match sortDeclLevelParams scopeLevelNames allUserLevelNames usedLevelNames with\n        | .error msg      => throwError msg\n        | .ok levelParams => do\n          let indTypes \u2190 replaceIndFVarsWithConsts views indFVars levelParams numVars numParams indTypes\n          let decl := Declaration.inductDecl levelParams numParams indTypes isUnsafe\n          Term.ensureNoUnassignedMVars decl\n          addDecl decl\n          mkAuxConstructions views\n    withSaveInfoContext do  -- save new env\n      for view in views do\n        Term.addTermInfo' view.ref[1] (\u2190 mkConstWithLevelParams view.declName) (isBinder := true)\n        for ctor in view.ctors do\n          Term.addTermInfo' ctor.ref[3] (\u2190 mkConstWithLevelParams ctor.declName) (isBinder := true)\n        -- We need to invoke `applyAttributes` because `class` is implemented as an attribute.\n        Term.applyAttributesAt view.declName view.modifiers.attrs .afterTypeChecking\n\nprivate def applyDerivingHandlers (views : Array InductiveView) : CommandElabM Unit := do\n  let mut processed : NameSet := {}\n  for view in views do\n    for classView in view.derivingClasses do\n      let className := classView.className\n      unless processed.contains className do\n        processed := processed.insert className\n        let mut declNames := #[]\n        for view in views do\n          if view.derivingClasses.any fun classView => classView.className == className then\n            declNames := declNames.push view.declName\n        classView.applyHandlers declNames\n\nprivate def applyComputedFields (indViews : Array InductiveView) : CommandElabM Unit := do\n  if indViews.all (\u00b7.computedFields.isEmpty) then return\n\n  let mut computedFields := #[]\n  let mut computedFieldDefs := #[]\n  for indView@{declName, ..} in indViews do\n    for {ref, fieldId, type, matchAlts, modifiers, ..} in indView.computedFields do\n      computedFieldDefs := computedFieldDefs.push <| \u2190 do\n        let modifiers \u2190 match modifiers with\n          | `(Lean.Parser.Command.declModifiersT| $[$doc:docComment]? $[$attrs:attributes]? $[$vis]? $[noncomputable]?) =>\n            `(Lean.Parser.Command.declModifiersT| $[$doc]? $[$attrs]? $[$vis]? noncomputable)\n          | _ => do\n            withRef modifiers do logError \"unsupported modifiers for computed field\"\n            `(Parser.Command.declModifiersT| noncomputable)\n        `($(\u27e8modifiers\u27e9):declModifiers\n          def%$ref $(mkIdent <| `_root_ ++ declName ++ fieldId):ident : $type $matchAlts:matchAlts)\n    let computedFieldNames := indView.computedFields.map fun {fieldId, ..} => declName ++ fieldId\n    computedFields := computedFields.push (declName, computedFieldNames)\n  withScope (fun scope => { scope with\n      opts := scope.opts\n        |>.setBool `bootstrap.genMatcherCode false\n        |>.setBool `elaboratingComputedFields true}) <|\n    elabCommand <| \u2190 `(mutual $computedFieldDefs* end)\n\n  liftTermElabM do Term.withDeclName indViews[0]!.declName do\n    ComputedFields.setComputedFields computedFields\n\ndef elabInductiveViews (views : Array InductiveView) : CommandElabM Unit := do\n  let view0 := views[0]!\n  let ref := view0.ref\n  runTermElabM fun vars => Term.withDeclName view0.declName do withRef ref do\n    mkInductiveDecl vars views\n    mkSizeOfInstances view0.declName\n    Lean.Meta.IndPredBelow.mkBelow view0.declName\n    for view in views do\n      mkInjectiveTheorems view.declName\n  applyComputedFields views -- NOTE: any generated code before this line is invalid\n  applyDerivingHandlers views\n  runTermElabM fun _ => Term.withDeclName view0.declName do withRef ref do\n    for view in views do\n      Term.applyAttributesAt view.declName view.modifiers.attrs .afterCompilation\n\nend Lean.Elab.Command\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/Inductive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23091976292927185, "lm_q2_score": 0.03161876840929292, "lm_q1q2_score": 0.007301398505189471}}
{"text": "example : (p \u2228 p) \u2192 p := fun h => match\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/loopErrorRecovery.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19193279569159505, "lm_q2_score": 0.037892424320813946, "lm_q1q2_score": 0.0072727989354260105}}
{"text": "/-\nCopyright (c) 2020 Chris Hughes. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Chris Hughes\n-/\nimport tactic.core\n/-!\n## `protected` and `protect_proj` user attributes\n\n`protected` is an attribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj` attribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n# Examples\n\nIn this example all of `foo.bar`, `foo.baz` and `foo.qux` will be protected.\n```\n@[protect_proj] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n\nThe following code example define the structure `foo`, and the projections `foo.qux`\nwill be protected, but not `foo.baz` or `foo.bar`\n\n```\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\nnamespace tactic\n\n/--\nAttribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\nProtectedness is a built in parser feature that is independent of this attribute.\nA declaration may be protected even if it does not have the `@[protected]` attribute.\nThis provides a convenient way to protect many declarations at once.\n-/\n@[user_attribute] meta def protected_attr : user_attribute :=\n{ name := \"protected\",\n  descr := \"Attribute to protect a declaration\n    If a declaration `foo.bar` is marked protected, then it must be referred to\n    by its full name `foo.bar`, even when the `foo` namespace is open.\",\n  after_set := some (\u03bb n _ _, mk_protected n)  }\n\nadd_tactic_doc\n{ name        := \"protected\",\n  category    := doc_category.attr,\n  decl_names  := [`tactic.protected_attr],\n  tags        := [\"parsing\", \"environment\"] }\n\n/-- Tactic that is executed when a structure is marked with the `protect_proj` attribute -/\nmeta def protect_proj_tac (n : name) (l : list name) : tactic unit :=\ndo env \u2190 get_env,\nmatch env.structure_fields_full n with\n| none := fail \"protect_proj failed: declaration is not a structure\"\n| some fields := fields.mmap' $ \u03bb field,\n    when (l.all $ \u03bb m, bnot $ m.is_suffix_of field) $ mk_protected field\nend\n\n/--\nAttribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected, meaning they must always be referred to by\ntheir full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n```lean\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\n@[user_attribute] meta def protect_proj_attr : user_attribute unit (list name) :=\n{ name := \"protect_proj\",\n  descr := \"Attribute to protect the projections of a structure.\n    If a structure `foo` is marked with the `protect_proj` user attribute, then\n    all of the projections become protected, meaning they must always be referred to by\n    their full name `foo.bar`, even when the `foo` namespace is open.\n\n    `protect_proj without bar baz` will protect all projections except for bar and baz\",\n  after_set := some (\u03bb n _ _, do l \u2190 protect_proj_attr.get_param n,\n    protect_proj_tac n l),\n  parser := interactive.types.without_ident_list }\n\nadd_tactic_doc\n{ name        := \"protect_proj\",\n  category    := doc_category.attr,\n  decl_names  := [`tactic.protect_proj_attr],\n  tags        := [\"parsing\", \"environment\", \"structures\"] }\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/protected.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920293453832882, "lm_q2_score": 0.06097518555755886, "lm_q1q2_score": 0.007268421052480142}}
{"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 \u03b1} [monad m] [monad_fail m] : string \u2295 \u03b1 \u2192 m \u03b1\n| (sum.inl e) := monad_fail.fail $ \"\\n\" ++ e\n| (sum.inr e) := pure e\n\nmeta instance {\u03b1} : has_coe (string \u2295 \u03b1) (tactic \u03b1) := \u27e8 sum.coe \u27e9\ninstance sum.io_coe {\u03b1} : has_coe (string \u2295 \u03b1) (io \u03b1) := \u27e8 sum.coe \u27e9\n\nmeta instance int.reflect : has_reflect \u2124\n| x :=\nif x < 0 then cast undefined `(- %%(int.reflect x) : \u2124)\nelse if h\u2081 : x = 0 then cast (by rw h\u2081) `(0 : \u2124)\n       else if h\u2082 : x = 1 then cast (by rw h\u2082) `(1 : \u2124)\n       else if h\u2083 : x % 2 = 0 then cast undefined $ `(\u03bb x : \u2124, bit0 x).subst (int.reflect (x / 2))\n       else cast undefined `(bit1 %%(int.reflect (x / 2)) : \u2124)\n\nmeta def rat.has_reflect' : \u03a0 x : \u211a, \u03a3 y : \u211a, \u03a3' h : x = y, reflected y\n| \u27e8x,y,h,h'\u27e9 := \u27e8rat.mk_nat x y, by { rw [rat.num_denom',rat.mk_nat_eq] } , `(_)\u27e9\n\nmeta instance : has_reflect \u211a\n| x :=\nmatch rat.has_reflect' x with\n| \u27e8 ._, rfl, h \u27e9 := h\nend\n\nnamespace smt\n\ninductive atom\n| num (s : \u2124)\n| dec (s : \u211a)\n-- | str (s : string)\n| sym (s : string)\n-- | keyword (s : string)\n\nprotected meta def atom.to_string : atom \u2192 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\u27e8 atom.to_string \u27e9\n\ninductive sexpr\n| const : atom \u2192 sexpr\n| fapp : list sexpr \u2192 sexpr\n\nprotected meta def sexpr.to_string : sexpr \u2192 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\u27e8 sexpr.to_string \u27e9\n\ninductive type\n| int | real | array (idx rng : type)\n\nopen smt.type\n\ndef type.to_string : type \u2192 string\n| int := \"Int\"\n| real := \"Real\"\n| (array t\u2080 t\u2081) := \"(Array \" ++ t\u2080.to_string ++ \" \" ++ t\u2081.to_string ++ \")\"\n\ndef string.map (f : char \u2192 char) : string \u2192 string :=\nlist.as_string \u2218 list.map f \u2218 string.to_list\n\nprotected def name := string\nprotected def name.to_string : smt.name \u2192 string := id\n\ndef repl_prime : char \u2192 char\n| '\\'' := '@'\n| c := c\n\ndef to_smt_name : name \u2192 smt.name :=\nstring.map repl_prime \u2218 name.to_string_with_sep \"_\"\n\ninductive expr'\n| all : smt.name \u2192 type \u2192 expr' \u2192 expr'\n| exist : smt.name \u2192 type \u2192 expr' \u2192 expr'\n| var : \u2115 \u2192 expr'\n| lit : \u2115 \u2192 expr'\n| const : smt.name \u2192 expr'\n| app : smt.name \u2192 list expr' \u2192 expr'\n\nopen smt.expr'\n\nmutual inductive bounded, all_bounded\nwith bounded : expr' \u2192 \u2115 \u2192 Prop\n| all {n t e b} :\n  bounded e (b+1) \u2192\n  bounded (all n t e) b\n| exist {n t e b} :\n  bounded e (b+1) \u2192\n  bounded (exist n t e) b\n| var {n b} : n < b \u2192 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 \u2192\n  bounded (expr'.app fn args) b\nwith all_bounded : list expr' \u2192 \u2115 \u2192 Prop\n| nil {b} : all_bounded [] b\n| cons {x xs b} :\n  bounded x b \u2192\n  all_bounded xs b \u2192\n  all_bounded (x :: xs) b\n\ndef expr := { e // bounded e 0 }\n\nmeta def type.to_z3 : _root_.expr \u2192 string \u2295 type\n| `(\u2124) := sum.inr type.int\n| `(\u211d) := sum.inr type.real\n| `(%%a \u2192 %%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 (\u2115 \u00d7 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 \u2192 string \u2295 \u2115\n| `(bit0 %%e) := (*2) <$> mk_lit e\n| `(bit1 %%e) := (\u03bb 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 \u2192 string \u2295 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\u2080 e\u2081) :=\nlet fn := e\u2080.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 \u2192 bounded e (b+1)\n| (bounded.all h) := h\n\nlemma bounded.of_exist {n t e b} : bounded (exist n t e) b \u2192 bounded e (b+1)\n| (bounded.exist h) := h\n\nlemma bounded.of_var {n b} : bounded (var n) b \u2192 n < b\n| (bounded.var h) := h\n\nlemma bounded.of_app {fn args b} : bounded (expr'.app fn args) b \u2192 all_bounded args b\n| (bounded.app h) := h\n\nlemma all_bounded.head {x xs b} : all_bounded (x :: xs) b \u2192 bounded x b\n| (all_bounded.cons h _) := h\n\nlemma all_bounded.tail {x xs b} : all_bounded (x :: xs) b \u2192 all_bounded xs b\n| (all_bounded.cons _ h) := h\n\ndef decidable.map {p q : Prop} (f : p \u2192 q) (g : q \u2192 p) : decidable p \u2192 decidable q\n| (is_true p) := is_true $ f p\n| (is_false p) := is_false $ \u03bb 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 : \u03a0 e b, decidable (bounded e b)\n| (var v) := \u03bb 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) := \u03bb b, is_true $ bounded.const\n| (lit n) := \u03bb b, is_true $ bounded.lit\n| (all n t e) := \u03bb 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) := \u03bb b, decidable.map bounded.exist bounded.of_exist (bounded.decide e $ b+1)\n| (app fn args) := \u03bb b, decidable.map bounded.app bounded.of_app (all_bounded.decide args b)\nwith all_bounded.decide : \u03a0 es b, decidable (all_bounded es b)\n| [] := \u03bb b, is_true all_bounded.nil\n| (e :: es) := \u03bb 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 (\u03bb h'', h' h''.tail)\n  end\n| (is_false h) := is_false (\u03bb 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 : \u03a0 (e : expr') (vs : list smt.name), bounded e vs.length \u2192 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' : \u03a0 (e : list expr') (vs : list smt.name), all_bounded e vs.length \u2192 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 \u2192 string\n| \u27e8e,h\u27e9 := e.to_string_aux [] h\n\nmeta def to_z3 (e : _root_.expr) : string \u2295 expr :=\ndo e' \u2190 to_z3' e,\n   if h : bounded e' 0 then pure \u27e8e',h\u27e9\n                       else sum.inl \"wrong use of bound variables\"\n\nmeta def encode_local (v : _root_.expr) : tactic string :=\ndo t \u2190 tactic.infer_type v,\n   p \u2190 tactic.is_prop t,\n   if p then do\n     e' \u2190 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 \u2190 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 \u2218 list.as_string) <$> parser.many1 (sat char.is_alphanum <|> '_' <$ ch '_')\n\ndef is_printable (c : char) : Prop :=\n32 \u2264 c.val \u2227 c.val \u2264 126\n\ndef is_symbol (c : char) : Prop :=\nc \u2208 (\"~!@$%^&*_-+=<>.?/\").to_list\n\ninstance is_printable.decidable_pred : decidable_pred is_printable :=\n\u03bb c, (by apply_instance : decidable (32 \u2264 c.val \u2227 c.val \u2264 126))\n\ninstance is_symbol.decidable_pred : decidable_pred is_symbol :=\n\u03bb c, (by apply_instance : decidable (c \u2208 (\"~!@$%^&*_-+=<>.?/\").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 \u2192 \u2115 :=\nlist.foldl (\u03bb n c, 10 * n + c.val - '0'.val) 0\n\ndef nat.bin_of_char : list char \u2192 \u2115 :=\nlist.foldl (\u03bb n c, 2 * n + c.val - '0'.val) 0\n\ndef nat.hex_of_char : list char \u2192 \u2115 :=\nlet digit := \"0123456789abcdef\".to_list in\nlist.foldl (\u03bb n c, 16 * n + list.index_of c.to_lower digit) 0\n\ndef rat.of_char : list char \u2192 \u211a :=\nlist.foldl (\u03bb n (c : char), (n + \u2191(c.val - '0'.val)) / 10) 0 \u2218 list.reverse\n\ndef non_zero : parser char :=\nsat $ \u03bb d, char.is_digit d \u2227 d \u2260 '0'\n\ndef numerals : parser (list char) :=\n((::) <$> non_zero <*> many (sat char.is_digit)) <|>\n['0'] <$ ch '0'\n\ndef parse_nat : parser \u2115 :=\nnat.of_char <$> numerals\n\ndef decimal : parser atom :=\ndo x \u2190 numerals,\n   do { ch '.', many (ch '0'),\n        y \u2190 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 (\u2208 xs)\n\ndef hexa : parser atom :=\nstr \"#x\" *>\n(num \u2218 coe \u2218 nat.hex_of_char) <$> many1 (sat char.is_digit <|> any_of \"abcdefABCDEF\".to_list)\n\ndef bin : parser atom :=\nstr \"#b\" *>\n(num \u2218 coe \u2218 nat.bin_of_char) <$> many1 (any_of ['0','1'])\n\n-- def parse_string : parser atom :=\n-- ch '\\\"' *>\n-- (atom.str \u2218 list.as_string) <$> many\n--           ('\\\"' <$ str \"\\\"\\\"\" <|>\n--             sat (\u03bb c, is_printable c \u2227 c \u2260 '\\\"') <|>\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 $ \u03bb parser, (smt.sexpr.const <$> parse_atom) <|> (smt.sexpr.fapp <$> (ch '(' *> sep_by space parser <* ch ')') )\n\ndef brackets {\u03b1} (l r : string) (p : parser \u03b1) : parser \u03b1 :=\nstr l *> p <* str r\n\ndef base_name : name \u2192 string\n| (name.mk_string s _) := s\n| _ := \"\"\n\nopen smt.sexpr tactic\n\nmeta def mk_assoc (n : name) : list expr \u2192 tactic expr\n| [] := fail \"mk_assoc []\"\n-- | [x] := pure x\n| (x :: xs) :=\n  do mfoldl (\u03bb a b, mk_app n [a,b]) x xs\n\nmeta def expr.of_sexpr : sexpr \u2192 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 \u2192 expr\n| [] := `(true)\n| (x :: xs) := xs.foldl (\u03bb a b, (`(and) : expr) a b) x\n\nmeta def and_prj : \u2115 \u2192 expr \u2192 expr \u2192 tactic expr\n| 0 `(%%p \u2227 %%q) h :=\n     mk_mapp ``and.elim_left [p,q,h]\n| 0 p h := mk_app ``id [h]\n| (i+1) `(%%p \u2227 %%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  \u2190 revert_lst ls,\n   hs \u2190 local_context,\n   hs.reverse.mmap $ \u03bb 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 \u2192 tactic unit )\n\nmeta instance : hashable solver :=\n{ hash_with_salt := \u03bb \u27e8a,b,c,d,_,_,_\u27e9, 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": "/-\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.Tactic.Clear\nimport Lean.Meta.Tactic.Util\nimport Lean.Meta.Tactic.Simp.Main\n\nnamespace Lean.Meta\n\nnamespace SimpAll\n\nstructure Entry where\n  fvarId   : FVarId -- original fvarId\n  userName : Name\n  id       : Name   -- id of the lemma at `SimpLemmas`\n  type     : Expr\n  proof    : Expr\n  deriving Inhabited\n\nstructure State where\n  modified : Bool := false\n  mvarId   : MVarId\n  entries  : Array Entry := #[]\n  ctx      : Simp.Context\n\nabbrev M := StateRefT State MetaM\n\nprivate def initEntries : M Unit := do\n  let hs \u2190 getNondepPropHyps (\u2190 get).mvarId\n  let erased := (\u2190 get).ctx.simpLemmas.erased\n  for h in hs do\n    let localDecl \u2190 getLocalDecl h\n    unless erased.contains localDecl.userName do\n      let fvarId := localDecl.fvarId\n      let proof  := localDecl.toExpr\n      let id     \u2190 mkFreshUserName `h\n      let simpLemmas \u2190 (\u2190 get).ctx.simpLemmas.add #[] proof (name? := id)\n      let entry : Entry := { fvarId := fvarId, userName := localDecl.userName, id := id, type := (\u2190 instantiateMVars localDecl.type), proof := proof }\n      modify fun s => { s with entries := s.entries.push entry, ctx.simpLemmas := simpLemmas }\n\nprivate abbrev getSimpLemmas : M SimpLemmas :=\n  return (\u2190 get).ctx.simpLemmas\n\nprivate partial def loop : M Bool := do\n  modify fun s => { s with modified := false }\n  -- simplify entries\n  for i in [:(\u2190 get).entries.size] do\n    let entry := (\u2190 get).entries[i]\n    let ctx := (\u2190 get).ctx\n    -- We disable the current entry to prevent it to be simplified to `True`\n    let simpLemmasWithoutEntry \u2190 (\u2190 getSimpLemmas).eraseCore entry.id\n    let ctx := { ctx with simpLemmas := simpLemmasWithoutEntry }\n    match (\u2190 simpStep (\u2190 get).mvarId entry.proof entry.type ctx) with\n    | none => return true -- closed the goal\n    | some (proofNew, typeNew) =>\n      unless typeNew == entry.type do\n        let id \u2190 mkFreshUserName `h\n        let simpLemmasNew \u2190 (\u2190 getSimpLemmas).add #[] proofNew (name? := id)\n        modify fun s => { s with\n          modified       := true\n          ctx.simpLemmas := simpLemmasNew\n          entries[i]     := { entry with type := typeNew, proof := proofNew, id := id }\n        }\n  -- simplify target\n  let mvarId := (\u2190 get).mvarId\n  match (\u2190 simpTarget mvarId (\u2190 get).ctx) with\n  | none => return true\n  | some mvarIdNew =>\n    unless mvarId == mvarIdNew do\n      modify fun s => { s with\n        modified := true\n        mvarId   := mvarIdNew\n      }\n  if (\u2190 get).modified then\n    loop\n  else\n    return false\n\ndef main : M (Option MVarId) := do\n  initEntries\n  if (\u2190 loop) then\n    return none -- close the goal\n  else\n    let mvarId := (\u2190 get).mvarId\n    let entries := (\u2190 get).entries\n    let (_, mvarId) \u2190 assertHypotheses mvarId (entries.map fun e => { userName := e.userName, type := e.type, value := e.proof })\n    tryClearMany mvarId (entries.map fun e => e.fvarId)\n\nend SimpAll\n\ndef simpAll (mvarId : MVarId) (ctx : Simp.Context) : MetaM (Option MVarId) := do\n  withMVarContext mvarId do\n    SimpAll.main.run' { mvarId := mvarId, ctx := ctx }\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/SimpAll.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127980882971, "lm_q2_score": 0.028870906841840533, "lm_q1q2_score": 0.007244080019032768}}
{"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\n\nsection\nopen Lean Elab Command\n\nsyntax (name := timeCmd)  \"#time \" command : command\n\n/--\nTime the elaboration of a command, and print the result (in milliseconds).\n\nExample usage:\n```\nset_option maxRecDepth 100000 in\n#time example : (List.range 500).length = 500 := rfl\n```\n-/\n@[commandElab timeCmd] def timeCmdElab : CommandElab\n  | `(#time%$tk $stx:command) => do\n    let start \u2190 IO.monoMsNow\n    elabCommand stx\n    logInfoAt tk m!\"time: {(\u2190 IO.monoMsNow) - start}ms\"\n  | _ => throwUnsupportedSyntax\n\nend\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/Util/Time.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10669059962643358, "lm_q2_score": 0.06754668879328725, "lm_q1q2_score": 0.007206596730135918}}
{"text": "namespace Foo\n\nscoped macro \"foo!\" x:term:max : term => `($x + 1)\n\n#check foo! 10\n\ntheorem ex1 : foo! 10 = 11 := rfl\n\nend Foo\n\n#check foo! 10 -- Error\n\nopen Foo\n\n#check foo! 10 -- works\n\ntheorem ex2 : foo! 10 = 11 := rfl\n\nscoped macro \"bla!\" x:term:max : term => `($x * 2) -- Error scoped macros must be used inside namespaces\n\nsection\n\nlocal macro \"bla!\" x:term:max : term => `($x * 2)\n\ntheorem ex3 : bla! 10 = 20 := rfl\n\nend\n\n#check bla! 10 -- Error unknown identifier `bla!`\n\ndef bla! := 20 -- bla! is still a valid identifier\n\nsyntax \"bar!\" term:max : term\n\n -- Error scoped attributes must be used inside namespaces\nscoped macro_rules | `(bar! $x) => `($x + 10)\n\nsection\n\nlocal macro_rules | `(bar! $x) => `($x + 20)\n\n#check bar! 10\n\nend\n\n-- Error no elaboration function\n#check bar! 10\n\nnamespace Bar\n\nscoped macro_rules | `(bar! $x) => `($x + 10)\n\n#check bar! 10\n\nend Bar\n\n-- Error no elaboration function\n#check bar! 10\n\nopen Bar\n\n#check bar! 10\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/scopedMacros.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761019, "lm_q2_score": 0.025565215176111034, "lm_q1q2_score": 0.007194194597551681}}
{"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 justification \nimport Architectural.LACU input.lacu_contract\nimport Architectural.lang Architectural.proofObligations\nimport rpo_meta\nopen interactive LANG PORTS\n\nvariable {\u03b1 : Type}\n\nlocal infix `OR`:50 := LANG.disj \nlocal infix `&`:50 := LANG.conj \n\nset_option pp.structure_instances_qualifier true \n\ndef local_input_name : string := \"lacu_input\"\ndef local_strat_name : string := \"lacu_strat\"\ndef local_prf_name : string := \"lacu_strat_valid\"\n\ndef preamble : string := \"import justification Architectural.LACU input.lacu_contract rpo_meta \\n open LANG PORTS \\n\\n \nlocal infix `OR`:50 := LANG.disj \nlocal infix `&`:50 := LANG.conj \n\\n\\n \nvariables Is : Implementations LACU_ARCH_MODEL \nvariables Env : Env PORTS\"\n\nmeta def proof_template (p\u2081 p\u2082 : string) : string := \n\"\\n\\n\ntheorem \" ++ local_prf_name ++ \" : \" ++ p\u2081 ++ \" := \\nbegin \\n\" ++ p\u2082 ++ \"\\nend\" ++ \"\\n\\n\\n\" \n\nmeta def evidence_file_template (input_string tscript : string) : string := \npreamble \n++ \"\\n\\n @[reducible] def \" ++ local_input_name \n++ \" : ArchitectureWithContracts LANG LACU  := \"++ input_string\n++ \"\\n\\n @[reducible] def \"++ local_strat_name \n++ \" : Strategy (Trace PORTS) := Contract.strategy \" ++ local_input_name ++ \" Is Env \" \n++ proof_template (\"deductive (Trace PORTS) \" ++ \" (\" ++ local_strat_name ++ \" Is Env)\" ) (tscript)\n\nmeta def output (s : string) : io unit := do \n  of \u2190 io.mk_file_handle \"src/evidence.lean\" io.mode.write, \n  io.fs.write of s.to_char_buffer\n\ntheorem archMap \n{Var \u03a6 : Type} [fintype Var] [decidable_eq Var] [AssertionLang \u03a6 Var]\n{S : Component Var}\n{A : Architecture S}\n(Is :\n \u03a0 (S' : Component Var), S' \u2208 A.subs \u2192 Impl Var)\n(inpt : ArchitectureWithContracts \u03a6 S) \n(h : A = inpt.to_Architecture)\n: Implementations (inpt.to_Architecture) :=\nby {rw \u2190 h, exact Is,}\n\nmeta def Output (s : string) : io unit := do \n  of \u2190 io.mk_file_handle \"src/evidence.lean\" io.mode.write, \n  io.fs.write of s.to_char_buffer\n\nmeta def driver (input : pexpr) : tactic unit := \ndo \n  STRAT \u2190 tactic.to_expr input,\n  if STRAT.contains_sorry then tactic.trace \"ff\" else do  \n  match STRAT with \n  | `(ArchitectureWithContracts.mk %%A %%prnt %%map %%prf) := do \n      inpt \u2190 tactic.eval_expr (ArchitectureWithContracts LANG LACU) STRAT,\n      input_fmt \u2190 tactic_format_expr STRAT,\n      let envc : expr := `(@set.univ (Trace PORTS)),\n      let goal := `(deductive (Trace PORTS) (@Contract.mk_strategy LANG _ _ _ _ LACU (%%STRAT))),\n      set_goal goal,\n      `[apply via_rpo],\n      solve_rpo,\n      b \u2190 is_solved, \n      match b with \n      | tt := do tactic.trace \"tt\", \n         input_string \u2190 stringOfFormatExpr STRAT,\n          tactic.unsafe_run_io $ Output $ evidence_file_template input_string  \"apply via_rpo,\\n solve_rpo,\"\n      | ff := do tactic.trace \"ff\"\n      end \n  | _ := return ()\nend\n\n\n@[user_command]\nmeta def main\n(meta_info : decl_meta_info)\n(_ : parse (lean.parser.tk \"main\")) : lean.parser unit :=\ndo \n   F \u2190 read \"src/input/inputLACU.txt\" types.texpr,\n   lean.parser.of_tactic $ driver F\n. \n main\n", "meta": {"author": "loganrjmurphy", "repo": "ForeMoSt", "sha": "c7affc7c8971562520d2775ac48fe4f188f84b02", "save_path": "github-repos/lean/loganrjmurphy-ForeMoSt", "path": "github-repos/lean/loganrjmurphy-ForeMoSt/ForeMoSt-c7affc7c8971562520d2775ac48fe4f188f84b02/src/lacu_main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.01798620746174082, "lm_q1q2_score": 0.007123764207596173}}
{"text": "#reduce \"\".data\n\nexample : \"\".data = [] := rfl\n\ntheorem ex : \"\".data = [] := 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/strLitProj.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.15405756269148543, "lm_q2_score": 0.04603390174485914, "lm_q1q2_score": 0.007091870703992318}}
{"text": "example (r : \u03b1 \u2192 \u03b1 \u2192 Prop) (q : Quot r) : False := by\n  induction q using Quot.ind with\n  | mk x => 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/run/quotInd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.17553806499717958, "lm_q2_score": 0.04023794420614677, "lm_q1q2_score": 0.007063290865411478}}
{"text": "import Mt.Thread.Basic\nimport Mt.Utils\n\nnamespace Mt.Traced\n\nstructure TracedThread (spec : Spec) where\n  thread : Thread spec\n  reservation : spec.Reservation\n\nvariable {spec : Spec}\nlocal instance : IsReservation spec.Reservation :=spec.is_reservation\n\nnamespace TracedThread\n\ndef T (t : TracedThread spec) : Type :=t.thread.T\ndef block_until (t : TracedThread spec) : spec.State -> Bool :=t.thread.block_until\ndef task (t : TracedThread spec) : TaskM spec t.T :=t.thread.task\ndef iterate (t : TracedThread spec) : spec.State -> Thread.IterationResult spec :=t.thread.iterate\n\ndef valid (thread : TracedThread spec) : Prop :=\n  thread.thread.task.valid thread.reservation\n    thread.thread.block_until\n    (\u03bb _ r => r = IsReservation.empty)\n\ntheorem valid_elim {thread : TracedThread spec}\n  (is_valid : thread.valid)\n  : \u2200 env_r s,\n    thread.block_until s \u2192\n    spec.validate (env_r + thread.reservation) s \u2192 \u2203 r' : spec.Reservation,\n    match thread.iterate s with\n      | Thread.IterationResult.Done s' =>\n          spec.validate (env_r + r') s' \u2227\n          r' = IsReservation.empty\n      | Thread.IterationResult.Panic .. => False\n      | Thread.IterationResult.Running s' cont =>\n        (spec.validate (env_r + r') s') \u2227 TracedThread.valid \u27e8cont, r'\u27e9 :=by\n  simp only [] -- TODO: Remove\n  intro env_r s bu_true initial_valid\n  rw [valid, TaskM.valid] at is_valid\n  have :=is_valid env_r s bu_true initial_valid\n  cases this\n\n  clear is_valid ; rename_i r' is_valid\n  exists r'\n  simp only [iterate, Thread.iterate]\n  \n  cases h : TaskM.iterate thread.thread.task s\n  all_goals (\n    rw [h] at is_valid\n    exact is_valid\n  )\n\nend TracedThread\n\nend Mt.Traced", "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/Thread/Traced.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.017176706370975556, "lm_q1q2_score": 0.007061530438854028}}
{"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 \u2190 mkIdent <$> mkFreshId\n      evalTactic (\u2190 `(tactic| have $fname := $res'))\n      applyList ts fname\n\ndef mkAppList : List Term \u2192 Ident \u2192 Syntax\n| [], id => id\n| t::ts, id =>\n  let rest := mkAppList ts id\n  let rest := \u27e8rest\u27e9\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 := \u27e8innerProof\u27e9\n      `($innerProof)\n    else\n      let id' := mkIdent (Name.mkSimple \"w\")\n      let innerProof := mkAppList tactics id'\n      let innerProof: Term := \u27e8innerProof\u27e9\n      `(congOrRight (fun $id' => $innerProof) $id)\n  | (i' + 1) => do\n    let id' := mkIdent (Name.mkSimple \"w\")\n    let r \u2190 congTactics tactics i' id' last\n    let r: Term := \u27e8r\u27e9\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 := \u27e8hyp\u27e9\n    evalTactic (\u2190 `(tactic| have $id := $hyp))\n  else withMainContext do\n    let last := getLength type == j + 1\n    let step\u2081: Ident \u2190 \n      if last then pure \u27e8hyp\u27e9\n      else do\n        let v := List.take (j - i) $ getCongAssoc j `orAssocDir\n        let res: Term := \u27e8hyp\u27e9\n        let step\u2081: Term \u2190 applyList v res\n        let step\u2081: Ident := \u27e8step\u2081\u27e9 \n        pure step\u2081 \n\n    let step\u2082: Ident \u2190\n      if last then do\n        let tactics := List.take (j - 1 - i) $ getCongAssoc (j - 1) `orAssocDir\n        let step\u2082: Term \u2190 applyList tactics step\u2081\n        let step\u2082: Ident := \u27e8step\u2082\u27e9\n        pure step\u2082\n      else do\n        let tactics\u2082 := List.reverse $ getCongAssoc (j - i - 1) `orAssocDir\n        let wrappedTactics\u2082: Syntax \u2190 congTactics tactics\u2082 i step\u2081 last\n        let wrappedTactics\u2082: Term := \u27e8wrappedTactics\u2082\u27e9\n        let fname\u2082 \u2190 mkIdent <$> mkFreshId\n        evalTactic (\u2190 `(tactic| have $fname\u2082 := $wrappedTactics\u2082))\n        pure fname\u2082\n    \n    let orComm: Term := \u27e8mkIdent `orComm\u27e9\n    let wrappedTactics\u2083 \u2190 congTactics [orComm] i step\u2082 last\n    let wrappedTactics\u2083 := \u27e8wrappedTactics\u2083\u27e9\n    let step\u2083 \u2190 mkIdent <$> mkFreshId\n    evalTactic (\u2190 `(tactic| have $step\u2083 := $wrappedTactics\u2083))\n\n    let step\u2084: Ident \u2190\n      if last then pure step\u2083 \n      else do\n        let u := List.reverse $ List.take (j - i) $ getCongAssoc j `orAssocConv\n        let step\u2084: Term \u2190 applyList u step\u2083\n        let step\u2084: Ident := \u27e8step\u2084\u27e9\n        pure step\u2084\n\n    evalTactic (\u2190 `(tactic| have $id := $step\u2084))\n\nsyntax (name := pullToMiddle) \"pullToMiddle\" term \",\" term \",\" term \",\" ident : tactic\n\n@[tactic pullToMiddle] def evalPullToMiddle : Tactic := fun stx => withMainContext do\n  let i \u2190 stxToNat \u27e8stx[1]\u27e9 \n  let j \u2190 stxToNat \u27e8stx[3]\u27e9\n  let id: Ident := \u27e8stx[7]\u27e9\n  let e \u2190 elabTerm stx[5] none\n  let t \u2190 instantiateMVars (\u2190 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 (\u2190 `(tactic| have $id := $(\u27e8hypS\u27e9)))\n        else\n          let ctx \u2190 getLCtx\n          let hyp := (ctx.findFromUserName? hypS.getId).get!.toExpr\n          let fname \u2190 mkFreshId\n          groupOrPrefixCore hyp type sufIdx fname\n          evalTactic (\u2190 `(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 \u2190 elabTerm stx[1] none\n  let t \u2190 instantiateMVars (\u2190 Meta.inferType e)\n  let e\u2082 \u2190 elabTerm stx[3] none\n  pullCore e\u2082 t stx[1] \u27e8stx[5]\u27e9\n\n/- example : A \u2228 B \u2228 C \u2228 D \u2228 E \u2192 E \u2228 A \u2228 B \u2228 C \u2228 D := by -/\n/-   intro h -/\n/-   pull h, E, h\u2082 -/\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 Runtime.Time\nimport Runtime.Interface\nimport Runtime.Utilities\nimport Runtime.Reaction.Trigger\n\nnamespace ReactionT\n\n/--\nAn event `{ action, value, time }` indicates that the action identified by name `action` should be\nset to the value `value` at time `time`.\n-/\nstructure Event (\u03c3A : Interface.Scheme) where\n  action : \u03c3A.vars\n  value  : \u03c3A.type action\n  time   : Time\n\n/-- Cf. `EventType` -/\ninstance : EventType (Event \u03c3A) where\n  Id := \u03c3A.vars\n  id := Event.action\n  time := Event.time\n\n/--\nAn `Input` in the context of a `ReactionT`-based monad carries all of the information that should be\nreadable by a reaction. That is:\n* `ports`: source ports of the reaction\n* `actions`: source action of the reaction\n* `state`: state variables of the parent reactor\n* `params`: parameters of the parent reactor\n* `tag`: the logical tag at the time of the reaction's execution\n\nThe `physicalOffset` is not exposed directly by any monadic operation on `ReactionT` (below), but is\nrequired by `ReactionT.getPhysicalTime`. It is used to normalize physical be 0 at the start of\nexecution of the program.\n-/\nstructure Input (\u03c3PS \u03c3AS \u03c3S \u03c3P : Interface.Scheme) where\n  ports          : Interface? \u03c3PS\n  actions        : Interface? \u03c3AS\n  state          : Interface \u03c3S\n  params         : Interface \u03c3P\n  tag            : Tag\n  physicalOffset : Duration\n\n/-- The time of an input is the time component of its `tag`. -/\nabbrev Input.time (input : Input \u03c3PS \u03c3AS \u03c3S \u03c3P) := input.tag.time\n\n/--\nAn `Output` in the context of a `ReactionT`-based monad carries all of the information that should\nbe writable by a reaction. That is:\n* `ports`: effect ports of the reaction\n* `state`: state variables of the parent reactor\n* `events`: a list of `Event`s scheduled for effect actions of the reaction\n* `stopRequested`: an indicator for whether the reaction requested execution to stop\n\nThe `writtenPorts` field is a (temporary) implementation detail used to record when a given port was\nwritten to. This information is used for the implementation of connections with delays. If we didn't\nforce reaction bodies to be written in `do` notation, this field could be manipulated to break the\nsemantics of reactor execution, by marking a port as unwritten, even though it was written to. In\nthis case, the port's value would not be propagated along a delayed connection.\n-/\n-- TODO: If there's an implementation of a dependent hash map available, combine the fields `ports`\n--       and `writtenPorts` by using a dependent hash map.\nstructure Output (\u03c3PE \u03c3AE \u03c3S : Interface.Scheme) (min : Time) where\n  ports         : Interface? \u03c3PE        := Interface?.empty\n  state         : Interface \u03c3S\n  events        : Queue (Event \u03c3AE) min := \u00b0[]\n  stopRequested : Bool                  := false\n  writtenPorts  : Array \u03c3PE.vars        := #[]\n\n-- WIP: Try implementing issue #11 before continuing with this.\n-- structure Proofs (input : Input \u03c3PS \u03c3AS \u03c3S \u03c3P) (triggers : Array (Trigger \u03c3PS.vars \u03c3AS.vars Timer)) where\n--   a : triggers.all (\u00b7.valued) \u2192 \u00ac(input.ports.isEmpty \u2227 input.actions.isEmpty)\n--   b : triggers = #[.startup] \u2192 input.tag = \u27e80, 0\u27e9\n--   c : triggers = #[.timer t] \u2192 input.tag.microstep = 0\n\n/--\nThe `ReactionT` monad transformer adds readable `ReactionT.Input` and writable `ReactionT.Output` to\na given monad.\n-/\nabbrev _root_.ReactionT (\u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P : Interface.Scheme) (m : Type \u2192 Type) (\u03b1 : Type) :=\n  (input : Input \u03c3PS \u03c3AS \u03c3S \u03c3P) \u2192 m (Output \u03c3PE \u03c3AE \u03c3S input.time \u00d7 \u03b1)\n\n/--\nMerges outputs `o\u2081` and `o\u2082` assuming `o\u2082` was produced *after* `o\u2081`. This order is relevant for\n`ports`, `state` and `events`:\n* Writes to ports of `o\u2082` override those of `o\u2081`.\n* The state of `o\u2082` is considered to be the resulting state.\n* For a fixed action and time, events of `o\u2082` are queued *after* those of `o\u2081`.\n-/\ndef Output.merge (o\u2081 o\u2082 : Output \u03c3PE \u03c3AE \u03c3S time) : Output \u03c3PE \u03c3AE \u03c3S time where\n  ports         := o\u2081.ports.merge o\u2082.ports\n  state         := o\u2082.state\n  events        := o\u2081.events.merge o\u2082.events\n  stopRequested := o\u2081.stopRequested \u2228 o\u2082.stopRequested\n  writtenPorts  := o\u2081.writtenPorts ++ o\u2082.writtenPorts\n\n@[simp]\ntheorem Output.merge_ports : (Output.merge o\u2081 o\u2082).ports = o\u2081.ports.merge o\u2082.ports := rfl\n\n@[simp]\ntheorem Output.merge_state : (Output.merge o\u2081 o\u2082).state = o\u2082.state := rfl\n\n@[simp]\ntheorem Output.merge_events : (Output.merge o\u2081 o\u2082).events = o\u2081.events.merge o\u2082.events := rfl\n\n@[simp]\ntheorem Output.merge_stopRequested :\n  (Output.merge o\u2081 o\u2082).stopRequested = (o\u2081.stopRequested \u2228 o\u2082.stopRequested) := by simp [merge]\n\n@[simp]\ntheorem Output.merge_writtenPorts :\n  (Output.merge o\u2081 o\u2082).writtenPorts = o\u2081.writtenPorts ++ o\u2082.writtenPorts := rfl\n\n/--\nProduces the `Output` for a given `Input` that should be the result of performing no (monadic)\noperation. This amounts to simply propagating the state from input to output.\n-/\ndef Input.noop (input : Input \u03c3PS \u03c3AS \u03c3S \u03c3P) : Output \u03c3PE \u03c3AE \u03c3S input.time where\n  state := input.state\n\n@[simp]\ntheorem Input.noop_ports_isEmpty (input : Input \u03c3PS \u03c3AS \u03c3S \u03c3P) {\u03c3PE \u03c3AE} :\n  input.noop (\u03c3PE := \u03c3PE) (\u03c3AE := \u03c3AE) |>.ports.isEmpty := rfl\n\nvariable [Monad m]\n\ninstance : Monad (ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m) where\n  -- A pure value results in a noop `Output`.\n  pure a input := do\n    let output := input.noop\n    return (output, a)\n  -- Mapping a value retains the `Output`.\n  map f ma input := do\n    let (output, a) \u2190 ma input\n    return (output, f a)\n  -- Sequencing requires the `Input` of the second operation to receive the state from the `Output`\n  -- of the first operation.\n  seq mf ma input\u2081 := do\n    let (output\u2081, a) \u2190 ma () input\u2081\n    let input\u2082 := { input\u2081 with state := output\u2081.state }\n    let (output\u2082, f) \u2190 mf input\u2082\n    return (output\u2082, f a)\n  -- Binding requires the `Input` of the second operation to receive the state from the `Output` of\n  -- the first operation. Additionally the outputs need to be merged at the end.\n  bind ma f input\u2081 := do\n    let (output\u2081, a) \u2190 ma input\u2081\n    let input\u2082 := { input\u2081 with state := output\u2081.state }\n    let (output\u2082, b) \u2190 f a input\u2082\n    let output := output\u2081.merge output\u2082\n    return (output, b)\n\n/-- Any `IO` operation can be used in an impure (cf. `Reaction.Kind`) reaction. -/\n-- TODO: This doesn't work in reaction bodies.\ninstance : MonadLift IO (ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P IO) where\n  monadLift io input world :=\n    match io world with\n    | .error e world' => .error e world'\n    | .ok    a world' => .ok (input.noop, a) world'\n\n/--\nGets the value of a given input port. The return value is optional, as the port may be absent.\n-/\ndef getInput (port : \u03c3PS.vars) : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m (Option <| \u03c3PS.type port) :=\n  fun input => return (input.noop, input.ports port)\n\n/-- Gets the value of a given state variable. -/\ndef getState (stv : \u03c3S.vars) : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m (\u03c3S.type stv) :=\n  fun input => return (input.noop, input.state stv)\n\n/--\nGets the value of a given action as scheduled for the current tag (cf. `ReactionT.Input.tag` &\n`getTag`). The return value is optional, as there may be no event scheduled for the action at the\ncurrent tag.\n-/\ndef getAction (action : \u03c3AS.vars) : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m (Option <| \u03c3AS.type action) :=\n  fun input => return (input.noop, input.actions action)\n\n/-- Gets the value of a given parameter as set for the parent reactor (instance) of the reaction. -/\ndef getParam (param : \u03c3P.vars) : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m (\u03c3P.type param) :=\n  fun input => return (input.noop, input.params param)\n\n/-- Gets the current logical tag. -/\ndef getTag : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m Tag :=\n  fun input => return (input.noop, input.tag)\n\n/-- Gets the current logical time. -/\ndef getLogicalTime : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m Time := do\n  return (\u2190 getTag).time\n\n/--\nGets the current physical time, which is monotonically increasing and normalized to be 0 upon the\nstart of the program's execution.\n\nNote that this operation is only available in the context impure reactions (cf. `Reaction.Kind`).\n-/\ndef getPhysicalTime : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P IO Time :=\n  fun input => return (input.noop, (\u2190 Time.now) - input.physicalOffset)\n\n/-- Sets a given output port to a given value. -/\ndef setOutput (port : \u03c3PE.vars) (v : \u03c3PE.type port) : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m Unit :=\n  fun input =>\n    let ports := fun p => if h : p = port then some (h \u25b8 v) else none\n    let output := { ports := ports, writtenPorts := #[port], state := input.state }\n    return (output, ())\n\n/-- Sets a given state variable to a given value. -/\ndef setState (stv : \u03c3S.vars) (v : \u03c3S.type stv) : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m Unit :=\n  fun input =>\n    let state := fun s => if h : s = stv then h \u25b8 v else input.state s\n    let output := { state := state }\n    return (output, ())\n\n/--\nSchedules an event for a given action with a given value to occur after a given logical delay.\n\nIf `delay = 0`, the action is scheduled for the current time with a microstep delay of 1.\nIf `delay > 0`, the action is scheduled for the tag `\u27e8(\u2190 getLogicalTime) + delay, 0\u27e9`.\n-/\ndef schedule (action : \u03c3AE.vars) (delay : Duration) (v : \u03c3AE.type action) :\n  ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m Unit :=\n  fun input =>\n    let time := input.time + delay\n    let event : Event \u03c3AE := { action, time, value := v }\n    let output := {\n      state := input.state,\n      events := \u00b0[event]' (Nat.le_trans (Nat.le_refl _) (Nat.le_add_right ..))\n    }\n    return (output, ())\n\n/--\nCauses the program to enter shutdown mode. This results in the following steps: After invoking this\noperation, execution for the current logical tag will be completed as usual. Afterwards, execution\ncontinues at the immediate successor of the current tag (if the current tag is `\u27e8t, m\u27e9` the\nimmediate successor is `\u27e8t, m + 1\u27e9`). The execution of the immediate successor tag will be\naccompanied by the `shutdown` trigger being active. Upon completion of that tag, the program will\nterminate.\n-/\ndef requestStop : ReactionT \u03c3PS \u03c3PE \u03c3AS \u03c3AE \u03c3S \u03c3P m Unit :=\n  fun input =>\n    let output := { stopRequested := true, state := input.state }\n    return (output, ())\n\nend ReactionT\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/Reaction/Monad.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32082131381216084, "lm_q2_score": 0.021948253874805947, "lm_q1q2_score": 0.007041467643998094}}
{"text": "import Contractome.Interfaces\nimport Contractome.Instances.Map256\nimport Contractome.Instances\nimport Contractome.EVM\nimport Contractome.UInt256\nimport Std.Data.Stack\nimport Contractome.Utils.RBMap2\nimport Contractome.Utils\n\nimport Contractome.ABIEncoding\n\nopen EVM\n\nopen MStd (RBMap mkRBMap)\n\ndef C : Cfg := {\n  S := Std.Stack UInt256\n  BA := List UInt8\n  BAI := List UInt8\n\n  M := CondensedMap\n  AM := RBMap UInt256 UInt256 Ord.compare\n  BAM := RBMap UInt256 (List UInt8) Ord.compare\n  STM := RBMap UInt256 CondensedMap Ord.compare\n  RS := Std.Stack (UInt256 \u00d7 (List UInt8))\n  Tw := UInt256\n  Tb := UInt8\n}\n\nderiving instance Repr for Std.Stack\n\n-- instance : Repr ByteArray := \u27e8 fun a _ => byteArrayToHex a \u27e9 \n\n-- #eval UInt64\n\ninstance : Repr C.Tw := (inferInstance : Repr UInt256)\ninstance : Repr C.Tb := (inferInstance : Repr UInt8)\ninstance : Repr C.M := (inferInstance : Repr CondensedMap)\ninstance : Repr C.S := (inferInstance : Repr (Std.Stack UInt256))\ninstance : Repr C.BA := (inferInstance : Repr (List UInt8))\ninstance : Repr C.AM := (inferInstance : Repr (RBMap UInt256 UInt256 Ord.compare))\ninstance : Repr C.BAM := (inferInstance : Repr (RBMap UInt256 (List UInt8) Ord.compare))\ninstance : Repr C.STM := (inferInstance : Repr (RBMap UInt256 CondensedMap Ord.compare))\ninstance : Repr C.RS := (inferInstance : Repr (Std.Stack (UInt256 \u00d7 (List UInt8))))\n-- deriving instance Repr for TransactionContext\n\ninstance : DecidableEq C.Tw := (inferInstance : DecidableEq UInt256)\ninstance : \u2200 n, OfNat C.Tw n := (inferInstance : \u2200 n, OfNat UInt256 n)\ninstance : Element C.Tw := (inferInstance : Element UInt256)\n\ninstance : DecidableEq C.Tb := (inferInstance : DecidableEq UInt8)\ninstance : \u2200 n, OfNat C.Tb n := (inferInstance : \u2200 n, OfNat UInt8 n)\ninstance : Element C.Tb := (inferInstance : Element UInt8)\ninstance : TakeBytes C.BAI := (inferInstance : TakeBytes (List UInt8))\ninstance : SByteArray C.Tw C.Tb C.BA C.BAI := (inferInstance : SByteArray UInt256 UInt8 (List UInt8) (List UInt8))\n\ninstance : Zero C.M := (inferInstance : Zero CondensedMap)\ninstance : EVMStack C.Tw C.S := (inferInstance : EVMStack UInt256 (Std.Stack UInt256))\ninstance : EVMStack (C.Tw \u00d7 C.BA) C.RS := (inferInstance : EVMStack (UInt256 \u00d7 (List UInt8)) (Std.Stack (UInt256 \u00d7 (List UInt8))))\ninstance : EVMMapDefault C.Tw C.Tw C.AM := (inferInstance : EVMMapDefault UInt256 UInt256 (RBMap UInt256 UInt256 Ord.compare))\ninstance : EVMMapDefault C.Tw C.M C.STM := (inferInstance : EVMMapDefault UInt256 CondensedMap (RBMap UInt256 CondensedMap Ord.compare))\ninstance : EVMMapBasic C.Tw C.BA C.BAM := (inferInstance : EVMMapBasic UInt256 (List UInt8) (RBMap UInt256 (List UInt8) Ord.compare))\n\ninstance : EVMMapSeq C.Tw C.Tb C.M (BA := C.BA) (BAI := C.BAI) :=\n  (inferInstance : EVMMapSeq UInt256 UInt8 (List UInt8) (List UInt8) CondensedMap)\n\n-- variable [EVMStack C.Tw C.S] [EVMMap C.Tw C.Tw C.AM] [EVMMapSeq C.Tw C.Tb C.M (instBA := instBA)]\n-- variable [EVMMapBasic C.Tw C.BA C.BAM]\n\n#assert (hexToByteArray! \"604260005260206000F3\") == (hexToByteArray!' \"604260005260206000F3\")\n\ndef basicInput := hexToByteList!' \"604260005260206000F3\"\n\n\ndef emptySolcInput := hexToByteArray! \"6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220c852edbace7e3c9da7b9e566199d4b7f89d6c7c9e5d1029f0337839e993fa6fa64736f6c63430008070033\"\n\ndef basicSolcInput := hexToByteList!' \"6080604052348015600f57600080fd5b5060405160e338038060e38339818101604052810190602d9190604c565b80600081905550506097565b6000815190506046816083565b92915050565b600060208284031215605f57605e607e565b5b6000606b848285016039565b91505092915050565b6000819050919050565b600080fd5b608a816074565b8114609457600080fd5b50565b603f8060a46000396000f3fe6080604052600080fdfea26469706673582212209c130309b4505633bae9459145bea0f6138a99c38947f11384f39beca020bc9a64736f6c63430008070033\"\ndef basicSolcInputWithArg := [basicSolcInput, (ABIEncodable.abiEncode 123).data.toList].join\n\n-- #eval basicSolcInputWithArg\n\n-- #eval basicSolcInput.size\n\ndef initTC (bytecode : List UInt8) : TransactionContext (C:=C) := {\n  address := 0\n  origin := 0\n  caller := 0\n  callvalue := 0\n  balances := MStd.rbmapOf [ (0, 5) ] Ord.compare\n  calldata := []\n  returnData := Std.Stack.empty\n  codes := MStd.rbmapOf [ (0, bytecode) ] Ord.compare\n}\n\ndef initCC : ChainContext (C:=C) := {\n  gasprice := 0\n  blockhash := 0\n  coinbase := 0\n  timestamp := 0\n  number := 0\n  difficulty := 0\n  gaslimit := 0\n  chainid := 0\n  basefee := 0\n}\n\nabbrev runEvm (v: EVMM (C:=C) \u03b1) (txCtx : TransactionContext (C:=C)) (chCtx : ChainContext (C:=C)) := EVMM.run (C:=C) v txCtx chCtx\nabbrev runEvm' (v: EVMM (C:=C) \u03b1) (txCtx : TransactionContext (C:=C)) (chCtx : ChainContext (C:=C)) := EVMM.run' (C:=C) v txCtx chCtx\n\n-- #eval EVM.decode basicInput\n-- #eval basicInput\n-- #eval EVM.decode \u27e8 hexToByteArray! \"604260005260206000F3\", 123 \u27e9 \n\n-- #eval 0x103\n\ndef stepN (n : Nat) : EVMM (C:=C) Unit := match n with\n| 0 => pure ()\n| n+1 => do\n  if (\u2190 EVMM.isDone) then pure () else \n  EVMM.step; stepN n\n\n-- #eval UInt256.ofBytes! $ hexToByteArray! \"42\"\n-- #eval runEvm (EVMM.getNextInstr) initTC initCC\n\n-- #eval 0x2d\n\n#eval runEvm (stepN 116) (initTC basicSolcInputWithArg) initCC\n\n\n#reduce basicInput\n\n\nset_option maxRecDepth 5000\ndef m := mkRBMap UInt256 UInt256 Ord.compare\n\n-- set_option pp.all true\n-- #reduce' (5 : UInt256) + 2 + 1\n\n#reduce' EVMMapBasic.set (K:=UInt256) (V:=UInt8) m 1 0xff\n\n-- set_option maxRecDepth 5000\n-- #reduce runEvm (do\n--   EVMM.pushStack 0x40\n--   EVMM.pushStack 0x80\n--   EVMM.i52_mstore) (initTC basicInput) initCC\n\n-- set_option maxHeartbeats 200000\n-- #reduce runEvm' (do\n--   stepN 3\n--   let st \u2190 get\n--   return st.memory\n--   ) (initTC basicSolcInputWithArg) initCC\n-- TODO note: not work\n\n\n-- def hexToByteArray'(s: String): Option ByteArray := Id.run do\n--   if s.length % 2 != 0 then return none\n--   let mut res := ByteArray.mkEmpty $ s.length / 2\n--   for i in [:((s.length)/2)] do\n--     let v1 := hexChar (s[2*i])\n--     let v2 := hexChar (s[2*i+1])\n--     match (v1, v2) with \n--     | (some v1, some v2) => res := res.push $ \u27e8 (16 * v1) + v2, sorry \u27e9 \n--     | _ => return none\n--   return res\n-- set_option pp.all true\n\n-- def codeInlined : ByteArray := {}\n\n-- local instance : OfNat UInt8 n where\n--   -- ofNat := fofNat n\n--   ofNat := \u27e8 n % 256, sorry \u27e9\n\n-- -- #reduce basicInput\n-- set_option maxRecDepth 2000\n-- -- #reduce initTC basicInput\n\n\n-- -- set_option maxRecDepth 10000\n-- -- #redComp (1 : UInt256)\n\n-- -- set_option maxRecDepth 10000\n-- -- #reduce codeInlined\n\n-- -- local instance : OfNat UInt8 n where\n-- --   ofNat := \u27e8n % 256, sorry\u27e9\n\n-- set_option maxHeartbeats 500000\n-- -- #redComp emptySolcInput\n\n-- -- #reduce initTC emptySolcInput\n\n-- constant a : UInt8\n\n-- -- #eval b[1, 2]\n\n-- -- #reduce initTC b[a]\n\n-- -- theorem test1 (tC : TransactionContext) (cC : ChainContext) := \n\n-- #reduce runEvm (EVMM.getNextInstr) (initTC basicInput) initCC\n-- #eval runEvm (stepN 116) (initTC basicSolcInputWithArg) initCC", "meta": {"author": "zygi", "repo": "contractome", "sha": "d4d59ce817e47578d8764e26d77050ce72c18c18", "save_path": "github-repos/lean/zygi-contractome", "path": "github-repos/lean/zygi-contractome/contractome-d4d59ce817e47578d8764e26d77050ce72c18c18/Contractome/Concrete.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.022629201145338597, "lm_q1q2_score": 0.007030765981353806}}
{"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.Tactic.Clear\nimport Lean.Meta.Tactic.Util\nimport Lean.Meta.Tactic.Simp.Main\n\nnamespace Lean.Meta\n\nopen Simp (UsedSimps)\n\nnamespace SimpAll\n\nstructure Entry where\n  fvarId   : FVarId -- original fvarId\n  userName : Name\n  id       : Origin -- id of the theorem at `SimpTheorems`\n  type     : Expr\n  proof    : Expr\n  deriving Inhabited\n\nstructure State where\n  modified  : Bool := false\n  mvarId    : MVarId\n  entries   : Array Entry := #[]\n  ctx       : Simp.Context\n  usedSimps : UsedSimps := {}\n\nabbrev M := StateRefT State MetaM\n\nprivate def initEntries : M Unit := do\n  let hs \u2190  (\u2190 get).mvarId.withContext do getPropHyps\n  let hsNonDeps \u2190 (\u2190 get).mvarId.getNondepPropHyps\n  let mut simpThms := (\u2190 get).ctx.simpTheorems\n  for h in hs do\n    unless simpThms.isErased (.fvar h) do\n      let localDecl \u2190 h.getDecl\n      let proof  := localDecl.toExpr\n      simpThms \u2190 simpThms.addTheorem (.fvar h) proof\n      modify fun s => { s with ctx.simpTheorems := simpThms }\n      if hsNonDeps.contains h then\n        -- We only simplify nondependent hypotheses\n        let entry : Entry := { fvarId := h, userName := localDecl.userName, id := .fvar h, type := (\u2190 instantiateMVars localDecl.type), proof := proof }\n        modify fun s => { s with entries := s.entries.push entry }\n\nprivate abbrev getSimpTheorems : M SimpTheoremsArray :=\n  return (\u2190 get).ctx.simpTheorems\n\nprivate partial def loop : M Bool := do\n  modify fun s => { s with modified := false }\n  -- simplify entries\n  for i in [:(\u2190 get).entries.size] do\n    let entry := (\u2190 get).entries[i]!\n    let ctx := (\u2190 get).ctx\n    -- We disable the current entry to prevent it to be simplified to `True`\n    let simpThmsWithoutEntry := (\u2190 getSimpTheorems).eraseTheorem entry.id\n    let ctx := { ctx with simpTheorems := simpThmsWithoutEntry }\n    let (r, usedSimps) \u2190 simpStep (\u2190 get).mvarId entry.proof entry.type ctx (usedSimps := (\u2190 get).usedSimps)\n    modify fun s => { s with usedSimps }\n    match r with\n    | none => return true -- closed the goal\n    | some (proofNew, typeNew) =>\n      unless typeNew == entry.type do\n        /- We must erase the `id` for the simplified theorem. Otherwise,\n           the previous versions can be used to self-simplify the new version. For example, suppose we have\n           ```\n            x : Nat\n            h : x \u2260 0\n            \u22a2 Unit\n           ```\n           In the first round, `h : x \u2260 0` is simplified to `h : \u00ac x = 0`.\n\n           It is also important for avoiding identical hypotheses to simplify each other to `True`.\n           Example\n           ```\n           ...\n           h\u2081 : p a\n           h\u2082 : p a\n           \u22a2 q a\n           ```\n           `h\u2081` is first simplified to `True`. If we don't remove `h\u2081` from the set of simp theorems, it will\n           be used to simplify `h\u2082` to `True` and information is lost.\n\n           We must use `mkExpectedTypeHint` because `inferType proofNew` may not be equal to `typeNew` when\n           we have theorems marked with `rfl`.\n        -/\n        trace[Meta.Tactic.simp.all] \"entry.id: {\u2190 ppOrigin entry.id}, {entry.type} => {typeNew}\"\n        let mut simpThmsNew := (\u2190 getSimpTheorems).eraseTheorem (.fvar entry.fvarId)\n        let idNew \u2190 mkFreshId\n        simpThmsNew \u2190 simpThmsNew.addTheorem (.other idNew) (\u2190 mkExpectedTypeHint proofNew typeNew)\n        modify fun s => { s with\n          modified         := true\n          ctx.simpTheorems := simpThmsNew\n          entries[i]       := { entry with type := typeNew, proof := proofNew, id := .other idNew }\n        }\n  -- simplify target\n  let mvarId := (\u2190 get).mvarId\n  let (r, usedSimps) \u2190 simpTarget mvarId (\u2190 get).ctx (usedSimps := (\u2190 get).usedSimps)\n  modify fun s => { s with usedSimps }\n  match r with\n  | none => return true\n  | some mvarIdNew =>\n    unless mvarId == mvarIdNew do\n      modify fun s => { s with\n        modified := true\n        mvarId   := mvarIdNew\n      }\n  if (\u2190 get).modified then\n    loop\n  else\n    return false\n\ndef main : M (Option MVarId) := do\n  initEntries\n  if (\u2190 loop) then\n    return none -- close the goal\n  else\n    let mvarId := (\u2190 get).mvarId\n    let entries := (\u2190 get).entries\n    let (_, mvarId) \u2190 mvarId.assertHypotheses <| entries.filterMap fun e =>\n      -- Do not assert `True` hypotheses\n      if e.type.isConstOf ``True then none else some { userName := e.userName, type := e.type, value := e.proof }\n    mvarId.tryClearMany (entries.map fun e => e.fvarId)\n\nend SimpAll\n\ndef simpAll (mvarId : MVarId) (ctx : Simp.Context) (usedSimps : UsedSimps := {}) : MetaM (Option MVarId \u00d7 UsedSimps) := do\n  mvarId.withContext do\n    let (r, s) \u2190 SimpAll.main.run { mvarId, ctx, usedSimps }\n    return (r, s.usedSimps)\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/Simp/SimpAll.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2509127980882971, "lm_q2_score": 0.02800752080881603, "lm_q1q2_score": 0.007027445413656235}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Util.CollectLevelParams\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.DefView\nimport Lean.Elab.Inductive\nimport Lean.Elab.Structure\nimport Lean.Elab.MutualDef\nimport Lean.Elab.DeclarationRange\nnamespace Lean.Elab.Command\n\nopen Meta\n\nprivate def ensureValidNamespace (name : Name) : MacroM Unit := do\n  match name with\n  | .str p s =>\n    if s == \"_root_\" then\n      Macro.throwError s!\"invalid namespace '{name}', '_root_' is a reserved namespace\"\n    ensureValidNamespace p\n  | .num .. => Macro.throwError s!\"invalid namespace '{name}', it must not contain numeric parts\"\n  | .anonymous => return ()\n\nprivate def setDeclIdName (declId : Syntax) (nameNew : Name) : Syntax :=\n  let (id, _) := expandDeclIdCore declId\n  -- We should not update the name of `def _root_.` declarations\n  assert! !(`_root_).isPrefixOf id\n  let idStx := mkIdent nameNew |>.raw.setInfo declId.getHeadInfo\n  if declId.isIdent then\n    idStx\n  else\n    declId.setArg 0 idStx\n\n/-- Return `true` if `stx` is a `Command.declaration`, and it is a definition that always has a name. -/\nprivate def isNamedDef (stx : Syntax) : Bool :=\n  if !stx.isOfKind ``Lean.Parser.Command.declaration then\n    false\n  else\n    let decl := stx[1]\n    let k := decl.getKind\n    k == ``Lean.Parser.Command.abbrev ||\n    k == ``Lean.Parser.Command.def ||\n    k == ``Lean.Parser.Command.theorem ||\n    k == ``Lean.Parser.Command.opaque ||\n    k == ``Lean.Parser.Command.axiom ||\n    k == ``Lean.Parser.Command.inductive ||\n    k == ``Lean.Parser.Command.classInductive ||\n    k == ``Lean.Parser.Command.structure\n\n/-- Return `true` if `stx` is an `instance` declaration command -/\nprivate def isInstanceDef (stx : Syntax) : Bool :=\n  stx.isOfKind ``Lean.Parser.Command.declaration &&\n  stx[1].getKind == ``Lean.Parser.Command.instance\n\n/-- Return `some name` if `stx` is a definition named `name` -/\nprivate def getDefName? (stx : Syntax) : Option Name := do\n  if isNamedDef stx then\n    let (id, _) := expandDeclIdCore stx[1][1]\n    some id\n  else if isInstanceDef stx then\n    let optDeclId := stx[1][3]\n    if optDeclId.isNone then none\n    else\n      let (id, _) := expandDeclIdCore optDeclId[0]\n      some id\n  else\n    none\n\n/--\nUpdate the name of the given definition.\nThis function assumes `stx` is not a nameless instance.\n-/\nprivate def setDefName (stx : Syntax) (name : Name) : Syntax :=\n  if isNamedDef stx then\n    stx.setArg 1 <| stx[1].setArg 1 <| setDeclIdName stx[1][1] name\n  else if isInstanceDef stx then\n    -- We never set the name of nameless instance declarations\n    assert! !stx[1][3].isNone\n    stx.setArg 1 <| stx[1].setArg 3 <| stx[1][3].setArg 0 <| setDeclIdName stx[1][3][0] name\n  else\n    stx\n\n/--\n  Given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)`\n  Remark: if the id starts with `_root_`, we return `none`.\n-/\nprivate def expandDeclNamespace? (stx : Syntax) : MacroM (Option (Name \u00d7 Syntax)) := do\n  let some name := getDefName? stx | return none\n  if (`_root_).isPrefixOf name then\n    ensureValidNamespace (name.replacePrefix `_root_ Name.anonymous)\n    return none\n  let scpView := extractMacroScopes name\n  match scpView.name with\n  | .str .anonymous _ => return none\n  | .str pre shortName => return some (pre, setDefName stx { scpView with name := shortName }.review)\n  | _ => return none\n\ndef elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  -- leading_parser \"axiom \" >> declId >> declSig\n  let declId             := stx[1]\n  let (binders, typeStx) := expandDeclSig stx[2]\n  let scopeLevelNames \u2190 getLevelNames\n  let \u27e8_, declName, allUserLevelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName stx\n  runTermElabM fun vars =>\n    Term.withDeclName declName <| Term.withLevelNames allUserLevelNames <| Term.elabBinders binders.getArgs fun xs => do\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration\n      let type \u2190 Term.elabType typeStx\n      Term.synthesizeSyntheticMVarsNoPostponing\n      let type \u2190 instantiateMVars type\n      let type \u2190 mkForallFVars xs type\n      let type \u2190 mkForallFVars vars type (usedOnly := true)\n      let type \u2190 Term.levelMVarToParam type\n      let usedParams  := collectLevelParams {} type |>.params\n      match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with\n      | Except.error msg      => throwErrorAt stx msg\n      | Except.ok levelParams =>\n        let type \u2190 instantiateMVars type\n        let decl := Declaration.axiomDecl {\n          name        := declName,\n          levelParams := levelParams,\n          type        := type,\n          isUnsafe    := modifiers.isUnsafe\n        }\n        trace[Elab.axiom] \"{declName} : {type}\"\n        Term.ensureNoUnassignedMVars decl\n        addDecl decl\n        withSaveInfoContext do  -- save new env\n          Term.addTermInfo' declId (\u2190 mkConstWithLevelParams declName) (isBinder := true)\n        Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking\n        if isExtern (\u2190 getEnv) declName then\n          compileDecl decl\n        Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation\n\n/-\nleading_parser \"inductive \" >> declId >> optDeclSig >> optional \":=\" >> many ctor\nleading_parser atomic (group (\"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional \":=\" >> many ctor >> optDeriving\n-/\nprivate def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do\n  checkValidInductiveModifier modifiers\n  let (binders, type?) := expandOptDeclSig decl[2]\n  let declId           := decl[1]\n  let \u27e8name, declName, levelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName decl\n  let ctors      \u2190 decl[4].getArgs.mapM fun ctor => withRef ctor do\n    -- def ctor := leading_parser optional docComment >> \"\\n| \" >> declModifiers >> rawIdent >> optDeclSig\n    let mut ctorModifiers \u2190 elabModifiers ctor[2]\n    if let some leadingDocComment := ctor[0].getOptional? then\n      if ctorModifiers.docString?.isSome then\n        logErrorAt leadingDocComment \"duplicate doc string\"\n      ctorModifiers := { ctorModifiers with docString? := TSyntax.getDocString \u27e8leadingDocComment\u27e9 }\n    if ctorModifiers.isPrivate && modifiers.isPrivate then\n      throwError \"invalid 'private' constructor in a 'private' inductive datatype\"\n    if ctorModifiers.isProtected && modifiers.isPrivate then\n      throwError \"invalid 'protected' constructor in a 'private' inductive datatype\"\n    checkValidCtorModifier ctorModifiers\n    let ctorName := ctor.getIdAt 3\n    let ctorName := declName ++ ctorName\n    let ctorName \u2190 withRef ctor[3] <| applyVisibility ctorModifiers.visibility ctorName\n    let (binders, type?) := expandOptDeclSig ctor[4]\n    addDocString' ctorName ctorModifiers.docString?\n    addAuxDeclarationRanges ctorName ctor ctor[3]\n    return { ref := ctor, modifiers := ctorModifiers, declName := ctorName, binders := binders, type? := type? : CtorView }\n  let computedFields \u2190 (decl[5].getOptional?.map (\u00b7[1].getArgs) |>.getD #[]).mapM fun cf => withRef cf do\n    return { ref := cf, modifiers := cf[0], fieldId := cf[1].getId, type := \u27e8cf[3]\u27e9, matchAlts := \u27e8cf[4]\u27e9 }\n  let classes \u2190 getOptDerivingClasses decl[6]\n  return {\n    ref             := decl\n    shortDeclName   := name\n    derivingClasses := classes\n    declId, modifiers, declName, levelNames\n    binders, type?, ctors\n    computedFields\n  }\n\nprivate def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView :=\n  inductiveSyntaxToView modifiers decl\n\ndef elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let v \u2190 inductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\ndef elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let modifiers := modifiers.addAttribute { name := `class }\n  let v \u2190 classInductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\ndef getTerminationHints (stx : Syntax) : TerminationHints :=\n  let decl := stx[1]\n  let k := decl.getKind\n  if k == ``Parser.Command.def || k == ``Parser.Command.abbrev || k == ``Parser.Command.theorem || k == ``Parser.Command.instance then\n    let args := decl.getArgs\n    { terminationBy? := args[args.size - 2]!.getOptional?, decreasingBy? := args[args.size - 1]!.getOptional? }\n  else\n    {}\n\n@[builtin_command_elab declaration]\ndef elabDeclaration : CommandElab := fun stx => do\n  match (\u2190 liftMacroM <| expandDeclNamespace? stx) with\n  | some (ns, newStx) => do\n    let ns := mkIdentFrom stx ns\n    let newStx \u2190 `(namespace $ns $(\u27e8newStx\u27e9) end $ns)\n    withMacroExpansion stx newStx <| elabCommand newStx\n  | none => do\n    let decl     := stx[1]\n    let declKind := decl.getKind\n    if declKind == ``Lean.Parser.Command.\u00abaxiom\u00bb then\n      let modifiers \u2190 elabModifiers stx[0]\n      elabAxiom modifiers decl\n    else if declKind == ``Lean.Parser.Command.\u00abinductive\u00bb then\n      let modifiers \u2190 elabModifiers stx[0]\n      elabInductive modifiers decl\n    else if declKind == ``Lean.Parser.Command.classInductive then\n      let modifiers \u2190 elabModifiers stx[0]\n      elabClassInductive modifiers decl\n    else if declKind == ``Lean.Parser.Command.\u00abstructure\u00bb then\n      let modifiers \u2190 elabModifiers stx[0]\n      elabStructure modifiers decl\n    else if isDefLike decl then\n      elabMutualDef #[stx] (getTerminationHints stx)\n    else\n      throwError \"unexpected declaration\"\n\n/-- Return true if all elements of the mutual-block are inductive declarations. -/\nprivate def isMutualInductive (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl     := elem[1]\n    let declKind := decl.getKind\n    declKind == `Lean.Parser.Command.inductive\n\nprivate def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do\n  let views \u2190 elems.mapM fun stx => do\n     let modifiers \u2190 elabModifiers stx[0]\n     inductiveSyntaxToView modifiers stx[1]\n  elabInductiveViews views\n\n/-- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/\nprivate def isMutualDef (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl := elem[1]\n    isDefLike decl\n\nprivate def isMutualPreambleCommand (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  k == ``Lean.Parser.Command.variable ||\n  k == ``Lean.Parser.Command.universe ||\n  k == ``Lean.Parser.Command.check ||\n  k == ``Lean.Parser.Command.set_option ||\n  k == ``Lean.Parser.Command.open\n\nprivate partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax \u00d7 Array Syntax) :=\n  let rec loop (i : Nat) : Option (Array Syntax \u00d7 Array Syntax) :=\n    if h : i < elems.size then\n      let elem := elems.get \u27e8i, h\u27e9\n      if isMutualPreambleCommand elem then\n        loop (i+1)\n      else if i == 0 then\n        none -- `mutual` block does not contain any preamble commands\n      else\n        some (elems[0:i], elems[i:elems.size])\n    else\n      none -- a `mutual` block containing only preamble commands is not a valid `mutual` block\n  loop 0\n\n/--\nFind the common namespace for the given names.\nExample:\n```\nfindCommonPrefix [`Lean.Elab.eval, `Lean.mkConst, `Lean.Elab.Tactic.evalTactic]\n-- `Lean\n```\n-/\ndef findCommonPrefix (ns : List Name) : Name :=\n  match ns with\n  | [] => .anonymous\n  | n :: ns => go n ns\nwhere\n  go (n : Name) (ns : List Name) : Name :=\n    match n with\n    | .anonymous => .anonymous\n    | _ => match ns with\n      | [] => n\n      | n' :: ns => go (findCommon n.components n'.components) ns\n  findCommon (as bs : List Name) : Name :=\n    match as, bs with\n    | a :: as, b :: bs => if a == b then a ++ findCommon as bs else .anonymous\n    | _, _ => .anonymous\n\n\n@[builtin_macro Lean.Parser.Command.mutual]\ndef expandMutualNamespace : Macro := fun stx => do\n  let mut nss := #[]\n  for elem in stx[1].getArgs do\n    match (\u2190 expandDeclNamespace? elem) with\n    | none        => Macro.throwUnsupported\n    | some (n, _) => nss := nss.push n\n  let common := findCommonPrefix nss.toList\n  if common.isAnonymous then Macro.throwUnsupported\n  let elemsNew \u2190 stx[1].getArgs.mapM fun elem => do\n    let some name := getDefName? elem | unreachable!\n    let view := extractMacroScopes name\n    let nameNew := { view with name := view.name.replacePrefix common .anonymous }.review\n    return setDefName elem nameNew\n  let ns := mkIdentFrom stx common\n  let stxNew := stx.setArg 1 (mkNullNode elemsNew)\n  `(namespace $ns $(\u27e8stxNew\u27e9) end $ns)\n\n@[builtin_macro Lean.Parser.Command.mutual]\ndef expandMutualElement : Macro := fun stx => do\n  let mut elemsNew := #[]\n  let mut modified := false\n  for elem in stx[1].getArgs do\n    match (\u2190 expandMacro? elem) with\n    | some elemNew => elemsNew := elemsNew.push elemNew; modified := true\n    | none         => elemsNew := elemsNew.push elem\n  if modified then\n    return stx.setArg 1 (mkNullNode elemsNew)\n  else\n    Macro.throwUnsupported\n\n@[builtin_macro Lean.Parser.Command.mutual]\ndef expandMutualPreamble : Macro := fun stx =>\n  match splitMutualPreamble stx[1].getArgs with\n  | none => Macro.throwUnsupported\n  | some (preamble, rest) => do\n    let secCmd    \u2190 `(section)\n    let newMutual := stx.setArg 1 (mkNullNode rest)\n    let endCmd    \u2190 `(end)\n    return mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd])\n\n@[builtin_command_elab \u00abmutual\u00bb]\ndef elabMutual : CommandElab := fun stx => do\n  let hints := { terminationBy? := stx[3].getOptional?, decreasingBy? := stx[4].getOptional? }\n  if isMutualInductive stx then\n    if let some bad := hints.terminationBy? then\n      throwErrorAt bad \"invalid 'termination_by' in mutually inductive datatype declaration\"\n    if let some bad := hints.decreasingBy? then\n      throwErrorAt bad \"invalid 'decreasing_by' in mutually inductive datatype declaration\"\n    elabMutualInductive stx[1].getArgs\n  else if isMutualDef stx then\n    for arg in stx[1].getArgs do\n      let argHints := getTerminationHints arg\n      if let some bad := argHints.terminationBy? then\n        throwErrorAt bad \"invalid 'termination_by' in 'mutual' block, it must be used after the 'end' keyword\"\n      if let some bad := argHints.decreasingBy? then\n        throwErrorAt bad \"invalid 'decreasing_by' in 'mutual' block, it must be used after the 'end' keyword\"\n    elabMutualDef stx[1].getArgs hints\n  else\n    throwError \"invalid mutual block\"\n\n/- leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"]\" >> many1 ident -/\n@[builtin_command_elab \u00abattribute\u00bb] def elabAttr : CommandElab := fun stx => do\n  let mut attrInsts := #[]\n  let mut toErase := #[]\n  for attrKindStx in stx[2].getSepArgs do\n    if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then\n      let attrName := attrKindStx[1].getId.eraseMacroScopes\n      if isAttribute (\u2190 getEnv) attrName then\n        toErase := toErase.push attrName\n      else\n        logErrorAt attrKindStx m!\"unknown attribute [{attrName}]\"\n    else\n      attrInsts := attrInsts.push attrKindStx\n  let attrs \u2190 elabAttrs attrInsts\n  let idents := stx[4].getArgs\n  for ident in idents do withRef ident <| liftTermElabM do\n    let declName \u2190 resolveGlobalConstNoOverloadWithInfo ident\n    Term.applyAttributes declName attrs\n    for attrName in toErase do\n      Attribute.erase declName attrName\n\n@[builtin_macro Lean.Parser.Command.\u00abinitialize\u00bb] def expandInitialize : Macro\n  | stx@`($declModifiers:declModifiers $kw:initializeKeyword $[$id? : $type? \u2190]? $doSeq) => do\n    let attrId := mkIdentFrom stx <| if kw.raw[0].isToken \"initialize\" then `init else `builtin_init\n    if let (some id, some type) := (id?, type?) then\n      let `(Parser.Command.declModifiersT| $[$doc?:docComment]? $[@[$attrs?,*]]? $(vis?)? $[unsafe%$unsafe?]?) := stx[0]\n        | Macro.throwErrorAt declModifiers \"invalid initialization command, unexpected modifiers\"\n      `($[unsafe%$unsafe?]? def initFn : IO $type := with_decl_name% ?$id do $doSeq\n        $[$doc?:docComment]? @[$attrId:ident initFn, $(attrs?.getD \u2205),*] $(vis?)? opaque $id : $type)\n    else\n      let `(Parser.Command.declModifiersT| $[$doc?:docComment]? ) := declModifiers\n        | Macro.throwErrorAt declModifiers \"invalid initialization command, unexpected modifiers\"\n      `($[$doc?:docComment]? @[$attrId:ident] def initFn : IO Unit := do $doSeq)\n  | _ => Macro.throwUnsupported\n\nbuiltin_initialize\n  registerTraceClass `Elab.axiom\n\nend Lean.Elab.Command\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/Declaration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16885693959392695, "lm_q2_score": 0.04146227049058796, "lm_q1q2_score": 0.007001192103656271}}
{"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, Jannis Limperg\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.type_context\nimport Mathlib.Lean3Lib.init.meta.rewrite_tactic\nimport Mathlib.Lean3Lib.init.meta.simp_tactic\nimport Mathlib.Lean3Lib.init.meta.smt.congruence_closure\nimport Mathlib.Lean3Lib.init.control.combinators\nimport Mathlib.Lean3Lib.init.meta.interactive_base\nimport Mathlib.Lean3Lib.init.meta.derive\nimport Mathlib.Lean3Lib.init.meta.match_tactic\nimport Mathlib.Lean3Lib.init.meta.congr_tactic\nimport Mathlib.Lean3Lib.init.meta.case_tag\n \n\nuniverses l u v \n\nnamespace Mathlib\n\nnamespace tactic\n\n\n/- allows metavars -/\n\n/- allow metavars and no subgoals -/\n\n/- doesn't allows metavars -/\n\n/- Auxiliary version of i_to_expr for apply-like tactics.\n   This is a workaround for comment\n      https://github.com/leanprover/lean/issues/1342#issuecomment-307912291\n   at issue #1342.\n\n   In interactive mode, given a tactic\n\n        apply f\n\n   we want the apply tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n\n   Before we added `i_to_expr_for_apply`, the tactic\n\n       apply le_antisymm\n\n   would first elaborate `le_antisymm`, and create\n\n       @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4\n\n   The type class resolution problem\n        ?m_2 : weak_order ?m_1\n   by the elaborator since ?m_1 is not assigned yet, and the problem is\n   discarded.\n\n   Then, we would invoke `apply_core`, which would create two\n   new metavariables for the explicit arguments, and try to unify the resulting\n   type with the current target. After the unification,\n   the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost\n   the information about the pending type class resolution problem.\n\n   With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,\n   the apply_core tactic creates all metavariables, and solves the ones that\n   can be solved by type class resolution.\n\n   Another possible fix: we modify the elaborator to return pending\n   type class resolution problems, and store them in the tactic_state.\n-/\n\nnamespace interactive\n\n\n/--\nitactic: parse a nested \"interactive\" tactic. That is, parse\n  `{` tactic `}`\n-/\n/--\nIf the current goal is a Pi/forall `\u2200 x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.\n\nIf the goal is an arrow `t \u2192 u`, then it puts `h : t` in the local context and the new goal target is `u`.\n\nIf the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.\n-/\n/--\nSimilar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.\n\nThe variant `intros h\u2081 ... h\u2099` introduces `n` new hypotheses using the given identifiers to name them.\n-/\n/--\nThe tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.\n\nExamples:\n```\nexample : \u2200 a b : nat, a = b \u2192 b = a :=\nbegin\n  introv h,\n  exact h.symm\nend\n```\nThe state after `introv h` is\n```\na b : \u2115,\nh : a = b\n\u22a2 b = a\n```\n\n```\nexample : \u2200 a b : nat, a = b \u2192 \u2200 c, b = c \u2192 a = c :=\nbegin\n  introv h\u2081 h\u2082,\n  exact h\u2081.trans h\u2082\nend\n```\nThe state after `introv h\u2081 h\u2082` is\n```\na b : \u2115,\nh\u2081 : a = b,\nc : \u2115,\nh\u2082 : b = c\n\u22a2 a = c\n```\n-/\n/-- Parse a current name and new name for `rename`. -/\n/-- Parse the arguments of `rename`. -/\n/--\nRename one or more local hypotheses. The renamings are given as follows:\n\n```\nrename x y             -- rename x to y\nrename x \u2192 y           -- ditto\nrename [x y, a b]      -- rename x to y and a to b\nrename [x \u2192 y, a \u2192 b]  -- ditto\n```\n\nNote that if there are multiple hypotheses called `x` in the context, then\n`rename x y` will rename *all* of them. If you want to rename only one, use\n`dedup` first.\n-/\n/--\nThe `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\n/--\nSimilar to the `apply` tactic, but does not reorder goals.\n-/\n/--\nSimilar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution.\n-/\n/--\nSimilar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object.\n-/\n/--\nSimilar to the `apply` tactic, but uses matching instead of unification.\n`apply_match t` is equivalent to `apply_with t {unify := ff}`\n-/\n/--\nThis tactic tries to close the main goal `... \u22a2 t` by generating a term of type `t` using type class resolution.\n-/\n/--\nThis tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.\n\nNote that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat \u2192 Prop)`.\n-/\n/--\nThis tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.\n-/\n/-- Try to apply `assumption` to all goals. -/\n/--\n`change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.\n\n`change u at h` will change a local hypothesis to `u`.\n\n`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.\n-/\n/--\nThis tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.\n-/\n/--\nLike `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.\n-/\n/--\nA synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.\n-/\n/--\n`revert h\u2081 ... h\u2099` applies to any goal with hypotheses `h\u2081` ... `h\u2099`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.\n-/\n/- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.\n   This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.\n   Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.\n   Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/\n\n-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations\n\n/--\n`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`\u2190` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.\n\n`rewrite [e\u2081, ..., e\u2099]` applies the given rules sequentially.\n\n`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `\u22a2` or `|-` can also be used, to signify the target of the goal.\n-/\n/--\nAn abbreviation for `rewrite`.\n-/\n/--\n`rewrite` followed by `assumption`.\n-/\n/--\nA variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.\n-/\n/--\nAn abbreviation for `erewrite`.\n-/\n/--\nReturns the unique names of all hypotheses (local constants) in the context.\n-/\n/--\nReturns all hypotheses (local constants) from the context except those whose\nunique names are in `hyp_uids`.\n-/\n/--\nApply `t` to the main goal and revert any new hypothesis in the generated goals.\nIf `t` is a supported tactic or chain of supported tactics (e.g. `induction`,\n`cases`, `apply`, `constructor`), the generated goals are also tagged with case\ntags. You can then use `case` to focus such tagged goals.\n\nTwo typical uses of `with_cases`:\n\n1. Applying a custom eliminator:\n\n   ```\n   lemma my_nat_rec :\n     \u2200 n {P : \u2115 \u2192 Prop} (zero : P 0) (succ : \u2200 n, P n \u2192 P (n + 1)), P n := ...\n\n   example (n : \u2115) : n = n :=\n   begin\n     with_cases { apply my_nat_rec n },\n     case zero { refl },\n     case succ : m ih { refl }\n   end\n   ```\n\n2. Enabling the use of `case` after a chain of case-splitting tactics:\n\n   ```\n   example (n m : \u2115) : unit :=\n   begin\n     with_cases { cases n; induction m },\n     case nat.zero nat.zero { exact () },\n     case nat.zero nat.succ : k { exact () },\n     case nat.succ nat.zero : i { exact () },\n     case nat.succ nat.succ : k i ih_i { exact () }\n   end\n   ```\n-/\n/--\n`generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.\n\n`generalize h : e = x` in addition registers the hypothesis `h : e = x`.\n-/\n/--\n  Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag`\n  is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was\n  applied. `rs` should contain, for each subgoal, the constructor name\n  associated with that goal and the hypotheses that were introduced.\n-/\n/--\nAssuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih\u2081 : P a \u2192 Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih\u2081` ire chosen automatically.\n\n`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.\n\n`induction e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.\n\n`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables\n\n`induction e generalizing z\u2081 ... z\u2099`, where `z\u2081 ... z\u2099` are variables in the local context, generalizes over `z\u2081 ... z\u2099` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.\n\n`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.\n-/\n/--\nFocuses on a goal ('case') generated by `induction`, `cases` or `with_cases`.\n\nThe goal is selected by giving one or more names which must match exactly one\ngoal. A goal is matched if the given names are a suffix of its goal tag.\nAdditionally, each name in the sequence can be abbreviated to a suffix of the\ncorresponding name in the goal tag. Thus, a goal with tag\n```\nnat.zero, list.nil\n```\ncan be selected with any of these invocations (among others):\n```\ncase nat.zero list.nil {...}\ncase nat.zero nil      {...}\ncase zero     nil      {...}\ncase          nil      {...}\n```\n\nAdditionally, the form\n```\ncase C : N\u2080 ... N\u2099 {...}\n```\ncan be used to rename hypotheses introduced by the preceding\n`cases`/`induction`/`with_cases`, using the names `N\u1d62`. For example:\n```\nexample (xs : list \u2115) : xs = xs :=\nbegin\n  induction xs,\n  case nil { reflexivity },\n  case cons : x xs ih {\n    -- x : \u2115, xs : list \u2115, ih : xs = xs\n    reflexivity }\nend\n```\n\nNote that this renaming functionality only work reliably *directly after* an\n`induction`/`cases`/`with_cases`. If you need to perform additional work after\nan `induction` or `cases` (e.g. introduce hypotheses in all goals), use\n`with_cases`.\n-/\n/-\nTODO `case` could be generalised to work with zero names as well. The form\n\n  case : x y z { ... }\n\nwould select the first goal (or the first goal with a case tag), renaming\nhypotheses to `x, y, z`. The renaming functionality would be available only if\nthe goal has a case tag.\n-/\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 \u2192 Q n`, and one goal with target `\u2200 (a : \u2115), (\u03bb (w : \u2115), n = w \u2192 Q n) (nat.succ a)`. Here the name `a` is chosen automatically.\n-/\n/--\nAssuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.\n\n`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.\n\n`cases e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.\n\n`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.\n-/\n/--\n`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.\n`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.\n`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_matching* [_ \u2228 _, _ \u2227 _]\n```\n-/\n/-- Shorthand for `cases_matching` -/\n/--\n`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`\n`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`\n`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`\n`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_type* or and\n```\n-/\n/--\nTries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.\n-/\n/--\nCloses the main goal using `sorry`.\n-/\n/--\nCloses the main goal using `sorry`.\n-/\n/--\nThe contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.\n-/\n/--\n`iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.\n\n`iterate n { t }` applies `t` `n` times.\n-/\n/--\n`repeat { t }` applies `t` to each goal. If the application succeeds,\nthe tactic is applied recursively to all the generated subgoals until it eventually fails.\nThe recursion stops in a subgoal when the tactic has failed to make progress.\nThe tactic `repeat { t }` never fails.\n-/\n/--\n`try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.\n-/\n/--\nA do-nothing tactic that always succeeds.\n-/\n/--\n`solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.\n-/\n/--\n`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.\n-/\n/--\n`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.\n-/\n/--\n`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.\n-/\n/--\n`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.\n-/\n/--\nAssuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.\n\n`assume (h\u2081 : t\u2081) ... (h\u2099 : t\u2099)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.\n-/\n/--\n`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\n/--\n`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\n/--\n`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.\n-/\n/--\nThis tactic displays the current state in the tracing buffer.\n-/\n/--\n`trace a` displays `a` in the tracing buffer.\n-/\n/--\n`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.\n\n`existsi [e\u2081, ..., e\u2099]` iteratively does the same for each expression in the list.\n-/\n/--\nThis tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.\n-/\n/--\nSimilar to `constructor`, but only non-dependent premises are added as new goals.\n-/\n/--\nApplies the first constructor when the type of the target is an inductive data type with two constructors.\n-/\n/--\nApplies the second constructor when the type of the target is an inductive data type with two constructors.\n-/\n/--\nApplies the constructor when the type of the target is an inductive data type with one constructor.\n-/\n/--\nReplaces the target of the main goal by `false`.\n-/\n/--\nThe `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t\u2081)` and `(c t\u2082)` are two terms that are equal then  `t\u2081` and `t\u2082` are equal too.\n\nIf `q` is a proof of a statement of conclusion `t\u2081 = t\u2082`, then injection applies injectivity to derive the equality of all arguments of `t\u2081` and `t\u2082` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t\u2081` and `t\u2082` should be constructor applications of the same constructor.\n\nGiven `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h\u2081 h\u2082` uses the names `h\u2081` and `h\u2082` to name the new hypotheses.\n-/\n/--\n`injections with h\u2081 ... h\u2099` iteratively applies `injection` to hypotheses using the names `h\u2081 ... h\u2099`.\n-/\nend interactive\n\n\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`.\n  This version fails when an argument of the form `simp_arg_type.symm_expr`\n  is included, so that `simp`-like tactics that do not (yet) support backwards rewriting\n  should properly report an error but function normally on other inputs.\n-/\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is the newer version of `decode_simp_arg_list`,\n  and has a new name for backwards compatibility.\n  This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`.\n-/\nnamespace interactive\n\n\n/--\nThe `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.\n\n`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.\n\n`simp [h\u2081 h\u2082 ... h\u2099]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h\u1d62`'s, where the `h\u1d62`'s are expressions. If `h\u1d62` is preceded by left arrow (`\u2190` or `<-`), the simplification is performed in the reverse direction. If an `h\u1d62` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.\n\n`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.\n\n`simp *` is a shorthand for `simp [*]`.\n\n`simp only [h\u2081 h\u2082 ... h\u2099]` is like `simp [h\u2081 h\u2082 ... h\u2099]` but does not use `[simp]` lemmas\n\n`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id\u1d62`.\n\n`simp at h\u2081 h\u2082 ... h\u2099` simplifies the non-dependent hypotheses `h\u2081 : T\u2081` ... `h\u2099 : T\u2099`. The tactic fails if the target or another hypothesis depends on one of them. The token `\u22a2` or `|-` can be added to the list to include the target.\n\n`simp at *` simplifies all the hypotheses and the target.\n\n`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.\n\n`simp with attr\u2081 ... attr\u2099` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr\u2081]`, ..., `[attr\u2099]` or `[simp]`.\n-/\n/--\nJust construct the simp set and trace it. Used for debugging.\n-/\n/--\n`simp_intros h\u2081 h\u2082 ... h\u2099` is similar to `intros h\u2081 h\u2082 ... h\u2099` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.\n\nAs with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.\n-/\n/--\n`dsimp` is similar to `simp`, except that it only uses definitional equalities.\n-/\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.\n-/\n/--\nShorter name for the tactic `reflexivity`.\n-/\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.\n-/\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.\n\n`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.\n-/\n/--\nProves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.\n-/\n/--\nAn abbreviation for `ac_reflexivity`.\n-/\n/--\nTries to prove the main goal using congruence closure.\n-/\n/--\nGiven hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\n-/\n/--\nApply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.\n-/\n/--\n`clear h\u2081 ... h\u2099` tries to clear each hypothesis `h\u1d62` from the local context.\n-/\n/--\nSimilar to `unfold`, but only uses definitional equalities.\n-/\n/--\nSimilar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.\n-/\n/--\nThis tactic unfolds all structure projections.\n-/\nend interactive\n\n\nstructure unfold_config \nextends simp_config\nwhere\n\nnamespace interactive\n\n\n/--\nGiven defined constants `e\u2081 ... e\u2099`, `unfold e\u2081 ... e\u2099` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.\n\nAs with `simp`, the `at` modifier can be used to specify locations for the unfolding.\n-/\n/--\nSimilar to `unfold`, but does not iterate the unfolding.\n-/\n/--\nIf the target of the main goal is an `opt_param`, assigns the default value.\n-/\n/--\nIf the target of the main goal is an `auto_param`, executes the associated tactic.\n-/\n/--\nFails if the given tactic succeeds.\n-/\n/--\nSucceeds if the given tactic fails.\n-/\n/--\n`guard_target t` fails if the target of the main goal is not `t`.\nWe use this tactic for writing tests.\n-/\n/--\n`guard_hyp h : t` fails if the hypothesis `h` does not have type `t`.\nWe use this tactic for writing tests.\n-/\n/--\n`match_target t` fails if target does not match pattern `t`.\n-/\n/--\n`by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and\n`h : \u00ac p` in the second branch. You can specify the name of the new hypothesis using the syntax\n`by_cases h : p`.\n-/\n/--\nApply function extensionality and introduce new hypotheses.\nThe tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to\n```\n  |-  ((fun x, ...) = (fun x, ...))\n```\nThe variant `funext h\u2081 ... h\u2099` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.\n-/\n/--\nIf the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contradiction h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\n/--\nIf the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contra h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\n/--\nType check the given expression, and trace its type.\n-/\n/--\nFail if there are unsolved goals.\n-/\n/--\n`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.\n-/\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a\u2081` ... `a\u2099`. The tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099` and tries to clear the previous one.\n-/\nend interactive\n\n\nend tactic\n\n\n/- See add_interactive -/\n\n/--\nCopy a list of meta definitions in the current namespace to tactic.interactive.\n\nThis command is useful when we want to update tactic.interactive without closing the current namespace.\n-/\n/--\nRenames hypotheses with the same name.\n-/\nnamespace tactic\n\n\n/- Helper tactic for `mk_inj_eq -/\n\n/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.\n   These lemmas are automatically generated by the equation compiler.\n   Example:\n   ```\n   list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 \u2227 t1 = t2) :=\n   by mk_inj_eq\n   ```\n-/\n\nend tactic\n\n\n/- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/\n\ntheorem sum.inl.inj_eq {\u03b1 : Type u} (\u03b2 : Type v) (a\u2081 : \u03b1) (a\u2082 : \u03b1) : sum.inl a\u2081 = sum.inl a\u2082 = (a\u2081 = a\u2082) :=\n  propext\n    { mp := fun (h : sum.inl a\u2081 = sum.inl a\u2082) => sum.inl.inj h,\n      mpr := fun (\u1fb0 : a\u2081 = a\u2082) => (fun (val val_1 : \u03b1) (e_2 : val = val_1) => congr_arg sum.inl e_2) a\u2081 a\u2082 \u1fb0 }\n\ntheorem sum.inr.inj_eq (\u03b1 : Type u) {\u03b2 : Type v} (b\u2081 : \u03b2) (b\u2082 : \u03b2) : sum.inr b\u2081 = sum.inr b\u2082 = (b\u2081 = b\u2082) := sorry\n\ntheorem psum.inl.inj_eq {\u03b1 : Sort u} (\u03b2 : Sort v) (a\u2081 : \u03b1) (a\u2082 : \u03b1) : psum.inl a\u2081 = psum.inl a\u2082 = (a\u2081 = a\u2082) :=\n  propext\n    { mp := fun (h : psum.inl a\u2081 = psum.inl a\u2082) => psum.inl.inj h,\n      mpr := fun (\u1fb0 : a\u2081 = a\u2082) => (fun (val val_1 : \u03b1) (e_2 : val = val_1) => congr_arg psum.inl e_2) a\u2081 a\u2082 \u1fb0 }\n\ntheorem psum.inr.inj_eq (\u03b1 : Sort u) {\u03b2 : Sort v} (b\u2081 : \u03b2) (b\u2082 : \u03b2) : psum.inr b\u2081 = psum.inr b\u2082 = (b\u2081 = b\u2082) := sorry\n\ntheorem sigma.mk.inj_eq {\u03b1 : Type u} {\u03b2 : \u03b1 \u2192 Type v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) : sigma.mk a\u2081 b\u2081 = sigma.mk a\u2082 b\u2082 = (a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082) := sorry\n\ntheorem psigma.mk.inj_eq {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) : psigma.mk a\u2081 b\u2081 = psigma.mk a\u2082 b\u2082 = (a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082) := sorry\n\ntheorem subtype.mk.inj_eq {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} (a\u2081 : \u03b1) (h\u2081 : p a\u2081) (a\u2082 : \u03b1) (h\u2082 : p a\u2082) : { val := a\u2081, property := h\u2081 } = { val := a\u2082, property := h\u2082 } = (a\u2081 = a\u2082) := sorry\n\ntheorem option.some.inj_eq {\u03b1 : Type u} (a\u2081 : \u03b1) (a\u2082 : \u03b1) : some a\u2081 = some a\u2082 = (a\u2081 = a\u2082) :=\n  propext\n    { mp := fun (h : some a\u2081 = some a\u2082) => option.some.inj h,\n      mpr := fun (\u1fb0 : a\u2081 = a\u2082) => (fun (val val_1 : \u03b1) (e_1 : val = val_1) => congr_arg some e_1) a\u2081 a\u2082 \u1fb0 }\n\ntheorem list.cons.inj_eq {\u03b1 : Type u} (h\u2081 : \u03b1) (t\u2081 : List \u03b1) (h\u2082 : \u03b1) (t\u2082 : List \u03b1) : h\u2081 :: t\u2081 = h\u2082 :: t\u2082 = (h\u2081 = h\u2082 \u2227 t\u2081 = t\u2082) := sorry\n\ntheorem nat.succ.inj_eq (n\u2081 : \u2115) (n\u2082 : \u2115) : Nat.succ n\u2081 = Nat.succ n\u2082 = (n\u2081 = n\u2082) :=\n  propext\n    { mp := fun (h : Nat.succ n\u2081 = Nat.succ n\u2082) => nat.succ.inj h,\n      mpr := fun (\u1fb0 : n\u2081 = n\u2082) => (fun (n n_1 : \u2115) (e_1 : n = n_1) => congr_arg Nat.succ e_1) n\u2081 n\u2082 \u1fb0 }\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/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20181321745968234, "lm_q2_score": 0.03461884244969336, "lm_q1q2_score": 0.006986539979502449}}
{"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.CollectMVars\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Constructor\nimport Lean.Meta.Tactic.Assert\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.SyntheticMVars\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\n/- `elabTerm` for Tactics and basic tactics that use it. -/\n\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  /- We have disabled `Term.withoutErrToSorry` to improve error recovery.\n     When we were using it, any tactic using `elabTerm` would be interrupted at elaboration errors.\n     Tactics that do not want to proceed should check whether the result contains sythetic sorrys or\n     disable `errToSorry` before invoking `elabTerm` -/\n  withRef stx do -- <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx expectedType?\n    Term.synthesizeSyntheticMVars mayPostpone\n    instantiateMVars e\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  let e \u2190 elabTerm stx expectedType? mayPostpone\n  -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here.\n  match expectedType? with\n  | none => return e\n  | some expectedType =>\n    let eType \u2190 inferType e\n    -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really\n    -- part of the elaboration, but part of the tactic. See issue #492\n    unless (\u2190 withAssignableSyntheticOpaque do isDefEq eType expectedType) do\n      Term.throwTypeMismatchError none expectedType eType e\n    return e\n\n/- Try to close main goal using `x target`, where `target` is the type of the main goal.  -/\ndef closeMainGoalUsing (x : Expr \u2192 TacticM Expr) (checkUnassigned := true) : TacticM Unit :=\n  withMainContext do\n    closeMainGoal (checkUnassigned := checkUnassigned) (\u2190 x (\u2190 getMainTarget))\n\ndef logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do\n   if (\u2190 Term.logUnassignedUsingErrorInfos mvarIds) then\n     throwAbortTactic\n\ndef filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do\n  let mctx \u2190 getMCtx\n  return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved\n\n@[builtinTactic \u00abexact\u00bb] def evalExact : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do\n    let mvarCounterSaved := (\u2190 getMCtx).mvarCounter\n    let r \u2190 elabTermEnsuringType e type\n    logUnassignedAndAbort (\u2190 filterOldMVars (\u2190 getMVars r) mvarCounterSaved)\n    return r\n  | _ => throwUnsupportedSyntax\n\ndef elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr \u00d7 List MVarId) := do\n  let mvarCounterSaved := (\u2190 getMCtx).mvarCounter\n  let val \u2190 elabTermEnsuringType stx expectedType?\n  let newMVarIds \u2190 getMVarsNoDelayed val\n  /- ignore let-rec auxiliary variables, they are synthesized automatically later -/\n  let newMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 Term.isLetRecAuxMVar mvarId)\n  let newMVarIds \u2190\n    if allowNaturalHoles then\n      pure newMVarIds.toList\n    else\n      let naturalMVarIds \u2190 newMVarIds.filterM fun mvarId => return (\u2190 getMVarDecl mvarId).kind.isNatural\n      let syntheticMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 getMVarDecl mvarId).kind.isNatural\n      let naturalMVarIds \u2190 filterOldMVars naturalMVarIds mvarCounterSaved\n      logUnassignedAndAbort naturalMVarIds\n      pure syntheticMVarIds.toList\n  tagUntaggedGoals (\u2190 getMainTag) tagSuffix newMVarIds\n  pure (val, newMVarIds)\n\n/- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned \"natural\" metavariables.\n   Recall that \"natutal\" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be\n   filled by typing constraints.\n   \"Synthetic\" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/\ndef refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do\n  withMainContext do\n    let (val, mvarIds') \u2190 elabTermWithHoles stx (\u2190 getMainTarget) tagSuffix allowNaturalHoles\n    assignExprMVar (\u2190 getMainGoal) val\n    replaceMainGoal mvarIds'\n\n@[builtinTactic \u00abrefine\u00bb] def evalRefine : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false)\n  | _                    => throwUnsupportedSyntax\n\n@[builtinTactic \u00abrefine'\u00bb] def evalRefine' : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true)\n  | _                     => throwUnsupportedSyntax\n\n@[builtinTactic \u00abspecialize\u00bb] def evalSpecialize : Tactic := fun stx => withMainContext do\n  match stx with\n  | `(tactic| specialize $e:term) =>\n    let (e, mvarIds') \u2190 elabTermWithHoles e none `specialize (allowNaturalHoles := true)\n    let h := e.getAppFn\n    if h.isFVar then\n      let localDecl \u2190 getLocalDecl h.fvarId!\n      let mvarId \u2190 assert (\u2190 getMainGoal) localDecl.userName (\u2190 inferType e).headBeta e\n      let (_, mvarId) \u2190 intro1P mvarId\n      let mvarId \u2190 tryClear mvarId h.fvarId!\n      replaceMainGoal (mvarId :: mvarIds')\n    else\n      throwError \"'specialize' requires a term of the form `h x_1 .. x_n` where `h` appears in the local context\"\n  | _ => throwUnsupportedSyntax\n\n/--\n   Given a tactic\n   ```\n   apply f\n   ```\n   we want the `apply` tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n   A similar method is also used in Lean 3.\n   This method is useful when applying lemmas such as:\n   ```\n   theorem infLeRight {s t : Set \u03b1} : s \u2293 t \u2264 t\n   ```\n   where `s \u2264 t` here is defined as\n   ```\n   \u2200 {x : \u03b1}, x \u2208 s \u2192 x \u2208 t\n   ```\n-/\ndef elabTermForApply (stx : Syntax) : TacticM Expr := do\n  if stx.isIdent then\n    match (\u2190 Term.resolveId? stx (withInfo := true)) with\n    | some e => return e\n    | _      => pure ()\n  elabTerm stx none (mayPostpone := true)\n\ndef evalApplyLikeTactic (tac : MVarId \u2192 Expr \u2192 MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do\n  withMainContext do\n    let val  \u2190 elabTermForApply e\n    let mvarIds'  \u2190 tac (\u2190 getMainGoal) val\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx =>\n  match stx with\n  | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e\n  | _ => throwUnsupportedSyntax\n\n@[builtinTactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun stx =>\n  withMainContext do\n    let mvarIds'  \u2190 Meta.constructor (\u2190 getMainGoal)\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(\u2190 Meta.existsIntro mvarId e)]) e\n  | _ => throwUnsupportedSyntax\n\n@[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx =>\n  withReducible <| evalTactic stx[1]\n\n@[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx =>\n  withReducibleAndInstances <| evalTactic stx[1]\n\n/--\n  Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable.\n  Note that, the main goal is updated when `Meta.assert` is used in the second case. -/\ndef elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId :=\n  withMainContext do\n    let e \u2190 elabTerm stx none\n    match e with\n    | Expr.fvar fvarId _ => pure fvarId\n    | _ =>\n      let type \u2190 inferType e\n      let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do\n        let mvarId \u2190 getMainGoal\n        let (fvarId, mvarId) \u2190 liftMetaM do\n          let mvarId \u2190 Meta.assert mvarId userName type e\n          Meta.intro1Core mvarId preserveBinderNames\n        replaceMainGoal [mvarId]\n        return fvarId\n      match userName? with\n      | none          => intro `h false\n      | some userName => intro userName true\n\n@[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx =>\n  match stx with\n  | `(tactic| rename $typeStx:term => $h:ident) => do\n    withMainContext do\n      /- Remark: we must not use `withoutModifyingState` because we may miss errors message.\n         For example, suppose the following `elabTerm` logs an error during elaboration.\n         In this scenario, the term `type` contains a synthetic `sorry`, and the error\n         message `\"failed to find ...\"` is not logged by the outer loop.\n         By using `withoutModifyingStateWithInfoAndMessages`, we ensure that\n         the messages and the info trees are preserved while the rest of the\n         state is backtracked. -/\n      let fvarId \u2190 withoutModifyingStateWithInfoAndMessages <| withNewMCtxDepth do\n        let type \u2190 elabTerm typeStx none (mayPostpone := true)\n        let fvarId? \u2190 (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n          if (\u2190 isDefEq type localDecl.type) then return localDecl.fvarId else return none\n        match fvarId? with\n        | none => throwError \"failed to find a hypothesis with type{indentExpr type}\"\n        | some fvarId => return fvarId\n      let lctxNew := (\u2190 getLCtx).setUserName fvarId h.getId\n      let mvarNew \u2190 mkFreshExprMVarAt lctxNew (\u2190 getLocalInstances) (\u2190 getMainTarget) MetavarKind.syntheticOpaque (\u2190 getMainTag)\n      assignExprMVar (\u2190 getMainGoal) mvarNew\n      replaceMainGoal [mvarNew.mvarId!]\n  | _ => throwUnsupportedSyntax\n\n/--\n   Make sure `expectedType` does not contain free and metavariables.\n   It applies zeta-reduction to eliminate let-free-vars.\n-/\nprivate def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do\n  let mut expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasFVar then\n    expectedType \u2190 zetaReduce expectedType\n  if expectedType.hasFVar || expectedType.hasMVar then\n    throwError \"expected type must not contain free or meta variables{indentExpr expectedType}\"\n  return expectedType\n\n@[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun stx =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let d \u2190 instantiateMVars d\n    let r \u2190 withDefault <| whnf d\n    unless r.isConstOf ``true do\n      throwError \"failed to reduce to 'true'{indentExpr r}\"\n    let s := d.appArg! -- get instance from `d`\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf\n\nprivate def mkNativeAuxDecl (baseName : Name) (type val : Expr) : TermElabM Name := do\n  let auxName \u2190 Term.mkAuxName baseName\n  let decl := Declaration.defnDecl {\n    name := auxName, levelParams := [], type := type, value := val,\n    hints := ReducibilityHints.abbrev,\n    safety := DefinitionSafety.safe\n  }\n  addDecl decl\n  compileDecl decl\n  pure auxName\n\n@[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun stx =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let auxDeclName \u2190 mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    let s := d.appArg! -- get instance from `d`\n    return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf\n\nend Lean.Elab.Tactic\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/Elab/Tactic/ElabTerm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561049052975445, "lm_q2_score": 0.04468087138573504, "lm_q1q2_score": 0.0069749031962819345}}
{"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Arthur Paulino, Gabriel Ebner, Mario Carneiro\n-/\nimport Lean.Meta.Tactic.Assumption\nimport Lean.Elab.Tactic.Simp\nimport Lean.Linter.Util\nimport Std.Lean.Meta.LCtx\nimport Std.Lean.Parser\nimport Std.Tactic.OpenPrivate\n\n/--\nEnables the 'unnecessary `simpa`' linter. This will report if a use of\n`simpa` could be proven using `simp` or `simp at h` instead.\n-/\nregister_option linter.unnecessarySimpa : Bool := {\n  defValue := true\n  descr := \"enable the 'unnecessary simpa' linter\"\n}\n\nnamespace Std.Tactic.Simpa\n\nopen Lean Parser.Tactic Elab Meta Term Tactic Simp Linter\n\n/-- The arguments to the `simpa` family tactics. -/\nsyntax simpaArgsRest := (config)? (discharger)? &\" only \"? (simpArgs)? (\" using \" term)?\n\n/--\nThis is a \"finishing\" tactic modification of `simp`. It has two forms.\n\n* `simpa [rules, \u22ef] 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, \u22ef]` 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.\n\n#TODO: implement `?`\n-/\nsyntax (name := simpa) \"simpa\" \"?\"? \"!\"? simpaArgsRest : tactic\n@[inherit_doc simpa] macro \"simpa!\" rest:simpaArgsRest : tactic =>\n  `(tactic| simpa ! $rest:simpaArgsRest)\n@[inherit_doc simpa] macro \"simpa?\" rest:simpaArgsRest : tactic =>\n  `(tactic| simpa ? $rest:simpaArgsRest)\n@[inherit_doc simpa] macro \"simpa?!\" rest:simpaArgsRest : tactic =>\n  `(tactic| simpa ?! $rest:simpaArgsRest)\n\nopen private useImplicitLambda from Lean.Elab.Term\n\n-- FIXME: remove when lean4#1862 lands\nopen TSyntax.Compat in\n/--\nIf `stx` is the syntax of a `simp`, `simp_all` or `dsimp` tactic invocation, and\n`usedSimps` is the set of simp lemmas used by this invocation, then `mkSimpOnly`\ncreates the syntax of an equivalent `simp only`, `simp_all only` or `dsimp only`\ninvocation.\n-/\nprivate def mkSimpOnly (stx : Syntax) (usedSimps : UsedSimps) : MetaM Syntax.Tactic := do\n  let isSimpAll := stx[0].getAtomVal == \"simp_all\"\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 \u2190 getLCtx\n  let env \u2190 getEnv\n  for (thm, _) in usedSimps.toArray.qsort (\u00b7.2 < \u00b7.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 (\u2190 `(Parser.Tactic.simpLemma| $(mkIdent (\u2190 unresolveNameGlobal declName)):ident))\n    | .fvar fvarId => -- local hypotheses in the context\n      if isSimpAll then\n        continue\n        -- `simp_all` uses all hypotheses anyway, so we do not need to include\n        -- them in the arguments. In fact, it would be harmful to do so:\n        -- `simp_all only [h]`, where `h` is a hypothesis, simplifies `h` to\n        -- `True` and subsequenly removes it from the context, whereas\n        -- `simp_all` does not. So to get behavior equivalent to `simp_all`, we\n        -- must omit `h`.\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 ++ (\u2190 locals.mapM fun id => `(Parser.Tactic.simpLemma| $(mkIdent id):ident))\n  else\n    args := args.push (\u2190 `(Parser.Tactic.simpStar| *))\n  let argsStx := if args.isEmpty then #[] else #[mkAtom \"[\", (mkAtom \",\").mkSep args, mkAtom \"]\"]\n  return stx.setArg 4 (mkNullNode argsStx)\n\n/-- Gets the value of the `linter.unnecessarySimpa` option. -/\ndef getLinterUnnecessarySimpa (o : Options) : Bool :=\n  getLinterValue linter.unnecessarySimpa o\n\nderiving instance Repr for UseImplicitLambdaResult\n\nelab_rules : tactic\n| `(tactic| simpa $[?%$squeeze]? $[!%$unfold]? $(cfg)? $(disch)? $[only%$only]?\n      $[[$args,*]]? $[using $usingArg]?) => Elab.Tactic.focus do\n  let stx \u2190 `(tactic| simp $(cfg)? $(disch)? $[only%$only]? $[[$args,*]]?)\n  let { ctx, dischargeWrapper } \u2190 withMainContext <| mkSimpContext stx (eraseLocal := false)\n  let ctx := if unfold.isSome then { ctx with config.autoUnfold := true } else ctx\n  dischargeWrapper.with fun discharge? => do\n    let (some (_, g), usedSimps) \u2190\n        simpGoal (\u2190 getMainGoal) ctx (simplifyTarget := true) (discharge? := discharge?)\n      | if getLinterUnnecessarySimpa (\u2190 getOptions) then\n          logLint linter.unnecessarySimpa (\u2190 getRef) \"try 'simp' instead of 'simpa'\"\n    let usedSimps \u2190 if let some stx := usingArg then\n      setGoals [g]\n      g.withContext do\n      let e \u2190 Tactic.elabTerm stx none (mayPostpone := true)\n      let (h, g) \u2190 if let .fvar h \u2190 instantiateMVars e then\n        pure (h, g)\n      else\n        (\u2190 g.assert `h (\u2190 inferType e) e).intro1\n      let (result?, usedSimps) \u2190 simpGoal g ctx (fvarIdsToSimp := #[h])\n        (simplifyTarget := false) (usedSimps := usedSimps) (discharge? := discharge?)\n      match result? with\n      | some (xs, g) =>\n        let h := match xs with | #[h] | #[] => h | _ => unreachable!\n        let name \u2190 mkFreshBinderNameForTactic `h\n        let g \u2190 g.rename h name\n        g.assign <|\u2190 g.withContext do\n          Tactic.elabTermEnsuringType (mkIdent name) (\u2190 g.getType)\n      | none =>\n        if getLinterUnnecessarySimpa (\u2190 getOptions) then\n          if (\u2190 getLCtx).getRoundtrippingUserName? h |>.isSome then\n            logLint linter.unnecessarySimpa (\u2190 getRef)\n              m!\"try 'simp at {Expr.fvar h}' instead of 'simpa using {Expr.fvar h}'\"\n      pure usedSimps\n    else if let some ldecl := (\u2190 getLCtx).findFromUserName? `this then\n      if let (some (_, g), usedSimps) \u2190 simpGoal g ctx (fvarIdsToSimp := #[ldecl.fvarId])\n          (simplifyTarget := false) (usedSimps := usedSimps) (discharge? := discharge?) then\n        g.assumption; pure usedSimps\n      else\n        pure usedSimps\n    else\n      g.assumption; pure usedSimps\n    if tactic.simp.trace.get (\u2190 getOptions) || squeeze.isSome then\n      let stx \u2190 match \u2190 mkSimpOnly stx usedSimps with\n        | `(tactic| simp $(cfg)? $(disch)? $[only%$only]? $[[$args,*]]?) =>\n          if unfold.isSome then\n            `(tactic| simpa! $(cfg)? $(disch)? $[only%$only]? $[[$args,*]]? $[using $usingArg]?)\n          else\n            `(tactic| simpa $(cfg)? $(disch)? $[only%$only]? $[[$args,*]]? $[using $usingArg]?)\n        | _ => unreachable!\n      logInfoAt stx.raw[0] m!\"Try this: {stx}\"\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/Simpa.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608723589515565, "lm_q2_score": 0.04742587536541707, "lm_q1q2_score": 0.006928315042041935}}
{"text": "/-\nCopyright (c) E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: E.W.Ayers\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.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.mk_dec_eq_instance\nimport Mathlib.Lean3Lib.init.meta.json\n \n\nuniverses l \n\nnamespace Mathlib\n\n/-! A component is a piece of UI which may contain internal state. Use component.mk to build new components.\n\n## Using widgets.\n\nTo make a widget, you need to make a custom executor object and then instead of calling `save_info_thunk` you call `save_widget`.\n\nAdditionally, you will need a compatible build of the vscode extension or web app to use widgets in vscode.\n\n## How it works:\n\nThe design is inspired by React.\nIf you are familiar with using React or Elm or a similar functional UI framework then that's helpful for this.\nThe [React article on reconciliation](https://reactjs.org/docs/reconciliation.html) might be helpful.\n\nOne can imagine making a UI for a particular object as just being a function `f : \u03b1 \u2192 UI` where `UI` is some inductive datatype for buttons, textboxes, lists and so on.\nThe process of evaluating `f` is called __rendering__.\nSo for example `\u03b1` could be `tactic_state` and the function renders a goal view.\n\n## HTML\n\nFor our purposes, `UI` is an HTML tree and is written `html \u03b1 : Type`. I'm going to assume some familiarity with HTML for the purposes of this document.\nAn HTML tree is composed of elements and strings.\nEach element has a tag such as \"div\", \"span\", \"article\" and so on and a set of attributes and child html.\nUse the helper function `h : string \u2192 list (attr \u03b1) \u2192 list (html \u03b1) \u2192 html \u03b1` to build new pieces of `html`. So for example:\n\n```lean\nh \"ul\" [] [\n     h \"li\" [] [\"this is list item 1\"],\n     h \"li\" [style [(\"color\", \"blue\")]] [\"this is list item 2\"],\n     h \"hr\" [] [],\n     h \"li\" [] [\n          h \"span\" [] [\"there is a button here\"],\n          h \"button\" [on_click (\u03bb _, 3)] [\"click me!\"]\n     ]\n]\n```\nHas the type `html nat`.\nThe `nat` type is called the __action__ and whenever the user interacts with the UI, the html will emit an object of type `nat`.\nSo for example if the user clicks the button above, the html will 'emit' `3`.\nThe above example is compiled to the following piece of html:\n\n```html\n<ul>\n  <li>this is list item 1</li>\n  <li style=\"{ color: blue; }\">this is list item 2</li>\n  <hr/>\n  <li>\n     <span>There is a button here</span>\n     <button onClick=\"[handler]\">click me!</button>\n  </li>\n</ul>\n```\n\n## Components\n\nIn order for the UI to react to events, you need to be able to take these actions \u03b1 and alter some state.\nTo do this we use __components__. `component` takes two type arguments: `\u03c0` and `\u03b1`. `\u03b1` is called the 'action' and `\u03c0` are the 'props'.\nThe props can be thought of as a kind of wrapped function domain for `component`. So given `C : component nat \u03b1`, one can turn this into html with\n`html.of_component 4 C : html \u03b1`.\n\nThe base constructor for a component is `pure`:\n```lean\nmeta def Hello : component string \u03b1 := component.pure (\u03bb s, [\"hello, \", s, \", good day!\"])\n\n#html Hello \"lean\" -- renders \"hello, lean, good day!\"\n```\nSo here a pure component is just a simple function `\u03c0 \u2192 list (html \u03b1)`.\nHowever, one can augment components with __hooks__.\nThe hooks available for compoenents are listed in the inductive definition for component.\n\nHere we will just look at the `with_state` hook, which can be used to build components with inner state.\n\n```\nmeta inductive my_action\n| increment\n| decrement\nopen my_action\n\nmeta def Counter : component unit \u03b1 :=\ncomponent.with_state\n     my_action          -- the action of the inner component\n     int                -- the state\n     (\u03bb _, 0)           -- initialise the state\n     (\u03bb _ _ s, s)       -- update the state if the props change\n     (\u03bb _ s a,          -- update the state if an action was received\n          match a with\n          | increment := (s + 1, none) -- replace `none` with `some _` to emit an action\n          | decrement := (s - 1, none)\n          end\n     )\n$ component.pure (\u03bb \u27e8state, \u27e8\u27e9\u27e9, [\n     button \"+\" (\u03bb _, increment),\n     to_string state,\n     button \"-\" (\u03bb _, decrement)\n  ])\n\n#html Counter ()\n```\n\nYou can add many hooks to a component.\n\n- `filter_map_action` lets you filter or map actions that are emmitted by the component\n- `map_props` lets you map the props.\n- `with_should_update` will not re-render the child component if the given test returns false. This can be useful for efficiency.\n- `with_state` discussed above.`\n- `with_mouse` subscribes the component to the mouse state, for example whether or not the mouse is over the component. See the `tests/lean/widget/widget_mouse.lean` test for an example.\n\nGiven an active document, Lean (in server mode) maintains a set of __widgets__ for the document.\nA widget is a component `c`, some `p : Props` and an internal state-manager which manages the states\nof the component and subcomponents and also handles the routing of events from the UI.\n\n## Reconciliation\n\nIf a parent component's state changes, this can cause child components to change position or to appear and dissappear.\nHowever we want to preserve the state of these child components where we can.\nThe UI system will try to match up these child components through a process called __reconciliation__.\n\nReconciliation will make sure that the states are carried over correctly and will also not rerender subcomponents if they haven't changed their props or state.\nTo compute whether two components are the same, the system will perform a hash on their VM objects.\nNot all VM objects can be hashed, so it's important to make sure that any items that you expect to change over the lifetime of the component are fed through the 'Props' argument.\nThis is why we need the props argument on `component`.\nThe reconciliation engine uses the `props_eq` predicate passed to the component constructor to determine whether the props have changed and hence whether the component should be re-rendered.\n\n## Keys\n\nIf you have some list of components and the list changes according to some state, it is important to add keys to the components so\nthat if two components change order in the list their states are preserved.\nIf you don't provide keys or there are duplicate keys then you may get some strange behaviour in both the Lean widget engine and react.\n\nIt is possible to use incorrect HTML tags and attributes, there is (currently) no type checking that the result is a valid piece of HTML.\nSo for example, the client widget system will error if you add a `text_change_event` attribute to anything other than an element tagged with `input`.\n\n## Styles with Tachyons\n\nThe widget system assumes that a stylesheet called 'tachyons' is present.\nYou can find documentation for this stylesheet at [Tachyons.io](http://tachyons.io/).\nTachyons was chosen because it is very terse and allows arbitrary styling without using inline styles and without needing to dynamically load a stylesheet.\n\n## Further work (up for grabs!)\n\n- Add type checking for html.\n- Better error handling when the html tree is malformed.\n- Better error handling when keys are malformed.\n- Add a 'with_task' which lets long-running operations (eg running `simp`) not block the UI update.\n- Timers, animation (ambitious).\n- More event handlers\n- Drag and drop support.\n- The current perf bottleneck is sending the full UI across to the server for every update.\n  Instead, it should be possible to send a smaller [JSON Patch](http://jsonpatch.com).\n  Which is already supported by `json.hpp` and javascript ecosystem.\n\n-/\n\nnamespace widget\n\n\ninductive mouse_event_kind \nwhere\n| on_click : mouse_event_kind\n| on_mouse_enter : mouse_event_kind\n| on_mouse_leave : mouse_event_kind\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/widget/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079883920791, "lm_q2_score": 0.034618839212677624, "lm_q1q2_score": 0.006899811203947605}}
{"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 \u27f6 obj.as)\n  (s   : Y.as \u27f6 obj.as)\n  (qis : S s)\n\n-- Define the equivalence\n\ndef veq (X Y : left_calculus C M) (v\u2081 v\u2082 : valley X Y) : Prop :=\n  \u2203 v\u2083 : valley X Y, \u2203 u\u2081 : v\u2081.obj.as \u27f6 v\u2083.obj.as, \u2203 u\u2082 : v\u2082.obj.as \u27f6 v\u2083.obj.as, \n    (v\u2081.f \u226b u\u2081) = v\u2083.f \u2227 (v\u2081.s \u226b u\u2081) = v\u2083.s \u2227 \n    (v\u2082.f \u226b u\u2082) = v\u2083.f \u2227 (v\u2082.s \u226b u\u2082) = v\u2083.s\n\n@[simp]\nlemma valley_equiv_refl (X Y : left_calculus C M) : reflexive (veq X Y) :=\n  \u03bb v, \u27e8 v, \ud835\udfd9 v.obj.as, \ud835\udfd9 v.obj.as, by simp, by simp, by simp, by simp \u27e9\n\n@[simp]\nlemma valley_equiv_symm (X Y : left_calculus C M) : symmetric (veq X Y) :=\n\u03bb v w h, let \u27e8u, \u27e8 f, g, comm\u2081, comm\u2082, comm\u2083, comm\u2084 \u27e9 \u27e9 := h in\n  \u27e8 u, g, f, comm\u2083, comm\u2084, comm\u2081, comm\u2082 \u27e9\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\u2081 v\u2082 : valley X Y) : Prop :=\n  \u2203 a : v\u2081.obj.as \u27f6 v\u2082.obj.as, v\u2081.f \u226b a = v\u2082.f \u2227 v\u2081.s \u226b a = v\u2082.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  (\u2203 w : valley X Y, (u E w) \u2227 (v E w)) \u2194 veq X Y u v :=\nbegin\n  split,\n  { rintro \u27e8 w, h\u2081, h\u2082 \u27e9,\n    rcases h\u2081 with \u27e8 f, h\u2081' \u27e9,\n    rcases h\u2082 with \u27e8 g, h\u2082' \u27e9,\n    use w.obj.as, use w.f, use w.s, use w.qis, use f, use g,\n    exact \u27e8 h\u2081'.left, h\u2081'.right, h\u2082' \u27e9 },\n\n  { rintro \u27e8 w, f, g, h\u2081, h\u2082, h\u2083, h\u2084 \u27e9,\n    use w,\n    split,\n      exact \u27e8f, \u27e8h\u2081, h\u2082\u27e9\u27e9,\n      exact \u27e8g, \u27e8h\u2083, h\u2084\u27e9\u27e9 }\nend\n\n\nlemma triple_comp {W X Y Z : C} (M : left_mult_sys S) {f\u2081 : W \u27f6 X} {f\u2082 : X \u27f6 Y} {f\u2083 : Y \u27f6 Z} :\n  S f\u2081 \u2227 S f\u2082 \u2227 S f\u2083 \u2192 S (f\u2081 \u226b f\u2082 \u226b f\u2083) := \nbegin\n  rintro \u27e8 s\u2081, s\u2082, s\u2083 \u27e9,\n  have s\u2084 : S (f\u2082 \u226b f\u2083) := M.comp \u27e8s\u2082, s\u2083\u27e9,\n  exact M.comp \u27e8s\u2081, s\u2084\u27e9  \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  (\u2203 w : valley X Y, (w E u) \u2227 (w E v)) \u2192 veq X Y u v :=\nbegin\n  intro h,\n  rcases h with \u27e8 w, hwu, hwv \u27e9,\n  rcases hwu with \u27e8 a, ha \u27e9,\n  rcases hwv with \u27e8 b, hb \u27e9,\n  have hore : _, from M.ore v.s u.s u.qis,\n  rcases hore with \u27e8 Z\u2081, c\u2081, s\u2081, hc\u2081, hcomm\u2081 \u27e9,\n  \n  have hcancel : w.s \u226b b \u226b s\u2081 = w.s \u226b a \u226b c\u2081, by {\n    rw [\u2190hb.right, \u2190ha.right] at hcomm\u2081,\n    simp at hcomm\u2081,\n    exact hcomm\u2081 },\n  have ht : _ := M.cancel \u27e8w.qis, hcancel\u27e9,\n  rcases ht with \u27e8 Z\u2082, t, ht\u2081, ht\u2082 \u27e9,\n\n  use Z\u2082, use u.f \u226b c\u2081 \u226b t, use v.s \u226b s\u2081 \u226b t,\n  exact triple_comp M \u27e8v.qis, hc\u2081, ht\u2081\u27e9,\n\n  use c\u2081 \u226b t,\n  use s\u2081 \u226b t,\n  \n  split, { simp },\n  split,\n    { \n      suffices heq : u.s \u226b c\u2081 \u226b t = v.s \u226b s\u2081 \u226b t, from \n        begin\n          simp, exact heq,\n        end,\n      have heq' : (u.s \u226b c\u2081) \u226b t = (v.s \u226b s\u2081) \u226b t, by rw hcomm\u2081,\n      simp at heq', assumption,\n    },\n  split,\n    { \n      simp,\n      rw [\u2190hb.left, \u2190ha.left],\n      simp,\n      simp at ht\u2082,\n      rw ht\u2082\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 \u27e8v\u2081, \u27e8auv, a, i, j, k, l\u27e9\u27e9, \n  rintro \u27e8v\u2082, \u27e8b, avw, i', j', k', l'\u27e9\u27e9,\n  have elem' : \u2203 x, (x E v\u2081) \u2227 (x E v\u2082), from begin\n    use v,\n    have velem\u2081 : (v E v\u2081), from \u27e8 a, \u27e8 k, l \u27e9 \u27e9,\n    have velem\u2082 : (v E v\u2082), from \u27e8 b, \u27e8 i', j' \u27e9 \u27e9,\n    exact \u27e8 velem\u2081, velem\u2082 \u27e9,\n  end,\n  have equiv : veq X Y v\u2081 v\u2082, from (mut_dom_implies_equiv v\u2081 v\u2082) elem',\n  have equiv' : \u2203 x, (u E x) \u2227 (w E x), from \n    begin\n      rcases equiv with \u27e8 z, u\u2081, u\u2082, hequiv \u27e9,\n      use z,\n      split,\n      { rw [\u2190 i, \u2190 j ] at hequiv,\n        simp at hequiv,\n        rcases hequiv with \u27e8 ha, hb, _ \u27e9,\n        exact \u27e8auv \u226b u\u2081, \u27e8 ha, hb\u27e9 \u27e9 },\n      { rw [\u2190 k', \u2190 l'] at hequiv,\n        simp at hequiv,\n        rcases hequiv with \u27e8 _, _, ha, hb \u27e9,\n        exact \u27e8 avw \u226b u\u2082, \u27e8 ha, hb \u27e9\u27e9 }\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 := \u27e8 valley_equiv_refl X Y, valley_equiv_symm X Y, valley_equiv_trans X Y \u27e9\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": "import Lean.Elab\n\nstructure Bar where\n\nstructure Foo where\n  foo\u2081 : Nat\n  foo\u2082 : Nat\n  bar  : Bar\n\ndef mkFoo\u2081 : Foo := {\n--v textDocument/definition\n  foo\u2081 := 1\n    --^ textDocument/definition\n--v textDocument/declaration\n  foo\u2082 := 2\n--v textDocument/typeDefinition\n  bar := \u27e8\u27e9\n}\n\n         --v textDocument/definition\n#check (Bar)\n\nstructure HandWrittenStruct where\n  n : Nat\n\n-- def HandWrittenStruct.n := fun | mk n => n\n\n          --v textDocument/definition\ndef hws : HandWrittenStruct := {\n--v textDocument/definition\n  n := 3\n}\n\n            --v textDocument/declaration\ndef mkFoo\u2082 := mkFoo\u2081\n\nsyntax (name := elabTest) \"test\" : term\n\n@[term_elab elabTest] def elabElabTest : Lean.Elab.Term.TermElab := fun orig _ => do\n  let stx \u2190 `(2)\n  Lean.Elab.withMacroExpansionInfo orig stx $ Lean.Elab.Term.elabTerm stx none\n\n     --v textDocument/declaration\n#check test\n     --^ textDocument/definition\n\ndef Baz (\u03b1 : Type) := \u03b1\n\n#check fun (b : Baz Nat) => b\n                          --^ textDocument/typeDefinition\n\nexample : Nat :=\n  let a := 1\n--v textDocument/definition\n  a + b\n    --^ textDocument/definition\nwhere\n  b := 2\n\nmacro_rules | `(test) => `(3)\n#check test\n     --^ textDocument/definition\n\nclass Foo2 where\n  foo : Nat \u2192 Nat\n  foo' : Nat\n\nclass Foo3 [Foo2] where\n  foo : [Foo2] \u2192 Nat\n\nclass inductive Foo4 : Nat \u2192 Type where\n| mk : Nat \u2192 Foo4 0\n\ndef Foo4.foo : [Foo4 n] \u2192 Nat\n| .mk n => n\n\nclass Foo5 where\n  foo : Foo2\n\n\ninstance : Foo2 := .mk id 0\ninstance : Foo3 := .mk 0\ninstance : Foo4 0 := .mk 0\ninstance [foo2 : Foo2] : Foo5 := .mk foo2\n\n-- should go-to instance\n              --v textDocument/definition\n#check Foo2.foo  2\n          --^ textDocument/definition\n#check (Foo2.foo)\n           --^ textDocument/definition\n#check (Foo2.foo')\n           --^ textDocument/definition\n\n-- should go-to projection\n#check @Foo2.foo\n           --^ textDocument/definition\n\n-- test that the correct instance index is extracted\n#check (Foo3.foo)\n           --^ textDocument/definition\n\n-- non-projections should not go-to instance\n#check (Foo4.foo)\n           --^ textDocument/definition\n\nset_option pp.all true in\n-- test that multiple instances can be extracted\n#check (Foo5.foo)\n           --^ textDocument/definition\n\n-- duplicate definitions link to the original\ndef mkFoo\u2081 := 1\n     --^ textDocument/definition\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/goTo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.025178839140372777, "lm_q1q2_score": 0.006849262414228508}}
{"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 tactic.core\n\n/-!\n# list_unused_decls\n\n`#list_unused_decls` is a command used for theory development.\nWhen writing a new theory one often tries\nmultiple variations of the same definitions: `foo`, `foo'`, `foo\u2082`,\n`foo\u2083`, etc. Once the main definition or theorem has been written,\nit's time to clean up and the file can contain a lot of dead code.\nMark the main declarations with `@[main_declaration]` and\n`#list_unused_decls` will show the declarations in the file\nthat are not needed to define the main declarations.\n\nSome of the so-called \"unused\" declarations may turn out to be useful\nafter all. The oversight can be corrected by marking those as\n`@[main_declaration]`. `#list_unused_decls` will revise the list of\nunused declarations. By default, the list of unused declarations will\nnot include any dependency of the main declarations.\n\nThe `@[main_declaration]` attribute should be removed before submitting\ncode to mathlib as it is merely a tool for cleaning up a module.\n-/\n\nnamespace tactic\n\n/-- Attribute `main_declaration` is used to mark declarations that are featured\nin the current file.  Then, the `#list_unused_decls` command can be used to\nlist the declaration present in the file that are not used by the main\ndeclarations of the file. -/\n@[user_attribute]\nmeta def main_declaration_attr : user_attribute :=\n{ name := `main_declaration,\n  descr := \"tag essential declarations to help identify unused definitions\" }\n\n/-- `update_unsed_decls_list n m` removes from the map of unneeded declarations those\nreferenced by declaration named `n` which is considerred to be a\nmain declaration -/\nprivate meta def update_unsed_decls_list :\n  name \u2192 name_map declaration \u2192 tactic (name_map declaration)\n| n m :=\n  do d \u2190 get_decl n,\n     if m.contains n then do\n       let m := m.erase n,\n       let ns := d.value.list_constant.union d.type.list_constant,\n       ns.mfold m update_unsed_decls_list\n     else pure m\n\n/-- In the current file, list all the declaration that are not marked as `@[main_declaration]` and\nthat are not referenced by such declarations -/\nmeta def all_unused (fs : list (option string)) : tactic (name_map declaration) :=\ndo ds \u2190 get_decls_from fs,\n   ls \u2190 ds.keys.mfilter (succeeds \u2218 user_attribute.get_param_untyped main_declaration_attr),\n   ds \u2190 ls.mfoldl (flip update_unsed_decls_list) ds,\n   ds.mfilter $ \u03bb n d, do\n     e \u2190 get_env,\n     return $ !d.is_auto_or_internal e\n\n/-- expecting a string literal (e.g. `\"src/tactic/find_unused.lean\"`)\n-/\nmeta def parse_file_name (fn : pexpr) : tactic (option string) :=\nsome <$> (to_expr fn >>= eval_expr string) <|> fail \"expecting: \\\"src/dir/file-name\\\"\"\n\nsetup_tactic_parser\n\n/-- The command `#list_unused_decls` lists the declarations that that\nare not used the main features of the present file. The main features\nof a file are taken as the declaration tagged with\n`@[main_declaration]`.\n\nA list of files can be given to `#list_unused_decls` as follows:\n\n```lean\n#list_unused_decls [\"src/tactic/core.lean\",\"src/tactic/interactive.lean\"]\n```\n\nThey are given in a list that contains file names written as Lean\nstrings. With a list of files, the declarations from all those files\nin addition to the declarations above `#list_unused_decls` in the\ncurrent file will be considered and their interdependencies will be\nanalyzed to see which declarations are unused by declarations marked\nas `@[main_declaration]`. The files listed must be imported by the\ncurrent file. The path of the file names is expected to be relative to\nthe root of the project (i.e. the location of `leanpkg.toml` when it\nis present).\n\nNeither `#list_unused_decls` nor `@[main_declaration]` should appear\nin a finished mathlib development. -/\n@[user_command]\nmeta def unused_decls_cmd (_ : parse $ tk \"#list_unused_decls\") : lean.parser unit :=\ndo fs \u2190 pexpr_list,\n   show tactic unit, from\n   do fs \u2190 fs.mmap parse_file_name,\n      ds \u2190 all_unused $ none :: fs,\n      ds.to_list.mmap' $ \u03bb \u27e8n,_\u27e9, trace!\"#print {n}\"\n\nadd_tactic_doc\n{ name                     := \"#list_unused_decls\",\n  category                 := doc_category.cmd,\n  decl_names               := [`tactic.unused_decls_cmd],\n  tags                     := [\"debugging\"] }\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/find_unused.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08389038182979684, "lm_q2_score": 0.08151974816472271, "lm_q1q2_score": 0.006838722800207468}}
{"text": "/-\nCopyright (c) 2020 Chris Hughes. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Chris Hughes\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.core\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n## `protected` and `protect_proj` user attributes\n\n`protected` is an attribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj` attribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n# Examples\n\nIn this example all of `foo.bar`, `foo.baz` and `foo.qux` will be protected.\n```\n@[protect_proj] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n\nThe following code example define the structure `foo`, and the projections `foo.qux`\nwill be protected, but not `foo.baz` or `foo.bar`\n\n```\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\n```\n-/\n\nnamespace tactic\n\n\n/--\nAttribute to protect a declaration.\nIf a declaration `foo.bar` is marked protected, then it must be referred to\nby its full name `foo.bar`, even when the `foo` namespace is open.\n\nProtectedness is a built in parser feature that is independent of this attribute.\nA declaration may be protected even if it does not have the `@[protected]` attribute.\nThis provides a convenient way to protect many declarations at once.\n-/\n/-- Tactic that is executed when a structure is marked with the `protect_proj` attribute -/\n/--\nAttribute to protect the projections of a structure.\nIf a structure `foo` is marked with the `protect_proj` user attribute, then\nall of the projections become protected, meaning they must always be referred to by\ntheir full name `foo.bar`, even when the `foo` namespace is open.\n\n`protect_proj without bar baz` will protect all projections except for `bar` and `baz`.\n\n```lean\n@[protect_proj without baz bar] structure foo : Type :=\n(bar : unit) (baz : unit) (qux : unit)\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/protected_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804719803168948, "lm_q2_score": 0.046033906652718684, "lm_q1q2_score": 0.00681519089438735}}
{"text": "-- import .repeat_at_least_once\n-- import .recover\n\n-- open tactic\n\n-- variables {\u03b1 : Type} [has_to_format \u03b1]\n\n-- meta inductive synthetic_goal\n-- | none\n-- | goals (original synthetic type : expr) : synthetic_goal\n\n-- meta def synthetic_goal.new : tactic synthetic_goal :=\n-- (do g :: gs \u2190 get_goals,\n--    t \u2190 infer_type g,\n--    is_lemma \u2190 is_prop t,\n--    if is_lemma then\n--      return synthetic_goal.none\n--    else do\n--      m \u2190 mk_meta_var t,\n--      set_goals (m :: gs),\n--      return (synthetic_goal.goals g m t)) <|> return synthetic_goal.none\n\n-- meta def synthetic_goal.update : synthetic_goal \u2192 tactic synthetic_goal\n-- | synthetic_goal.none := synthetic_goal.new\n-- | (synthetic_goal.goals g g' t) :=\n--     do try_core (do {\n--       val \u2190 instantiate_mvars g',\n--       do {\n--         guard (val.metavariables = []),\n--         c  \u2190 new_aux_decl_name,\n--         gs \u2190 get_goals,\n--         set_goals [g],\n--         add_aux_decl c t val ff >>= unify g,\n--         set_goals gs } <|> unify g val }),\n--       synthetic_goal.new\n\n-- meta def luxembourg_chain_aux (tac : tactic \u03b1) : \u2115 \u2192 synthetic_goal \u2192 tactic (synthetic_goal \u00d7 list (\u2115 \u00d7 \u03b1))\n-- | b s := do (done >> return (s, [])) <|>\n--             (do a \u2190 tac,\n--                 (s, c) \u2190 luxembourg_chain_aux 0 s,\n--                 return (s, (b, a) :: c)) <|>\n--             (do s \u2190 s.update,\n--                 n \u2190 num_goals,\n--                 if b = (n-1) then return (s, []) else do\n--                 rotate_left 1,\n--                 luxembourg_chain_aux (b+1) s)\n\n-- /-- Returns a `list (\u2115 \u00d7 \u03b1)`, whose successive elements `(n, a)` represent\n--     a successful result of `rotate_left n >> tac`.\n\n--     (When `n = 0`, the `rotate_left` may of course be omitted.) -/\n-- meta def luxembourg_chain_core (tac : tactic \u03b1) : tactic (list (\u2115 \u00d7 \u03b1)) :=\n-- do b \u2190 num_goals,\n--    s \u2190 synthetic_goal.new,\n--    (s, r) \u2190 luxembourg_chain_aux tac 0 s,\n--    s.update,\n--    return r\n\n\n-- meta def luxembourg_chain (tactics : list (tactic \u03b1)) : tactic (list string) :=\n-- do results \u2190 luxembourg_chain_core (first tactics),\n--    return (results.map (\u03bb p, (if p.1 = 0 then \"\" else \"rotate_left \" ++ (to_string p.1) ++ \", \") ++ (format!\"{p.2}\").to_string))\n", "meta": {"author": "semorrison", "repo": "lean-tidy", "sha": "6c1d46de6cff05e1c2c4c9692af812bca3e13b6c", "save_path": "github-repos/lean/semorrison-lean-tidy", "path": "github-repos/lean/semorrison-lean-tidy/lean-tidy-6c1d46de6cff05e1c2c4c9692af812bca3e13b6c/src/tidy/scratch_1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761019, "lm_q2_score": 0.024053552938151736, "lm_q1q2_score": 0.006768804385471174}}
{"text": "import Lean\n\nmacro \"t\" t:interpolatedStr(term) : doElem =>\n  `(Macro.trace[Meta.debug] $t)\n\nmacro \"tstcmd\" : command => do\n  t \"hello\"\n  `(example : Nat := 1)\n\nset_option trace.Meta.debug true in\ntstcmd\n\nopen Lean Meta\n\nmacro \"r\" r:interpolatedStr(term) : doElem =>\n  `(trace[Meta.debug] $r)\n\nset_option trace.Meta.debug true in\n#eval show MetaM _ from do r \"world\"\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/traceClassScopes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.20946968133032529, "lm_q2_score": 0.032100705443805444, "lm_q1q2_score": 0.0067241245397925645}}
{"text": "import Lean\n\nmacro \"t\" t:interpolatedStr(term) : doElem =>\n  `(doElem| Macro.trace[Meta.debug] $t)\n\nmacro \"tstcmd\" : command => do\n  t \"hello\"\n  `(example : Nat := 1)\n\nset_option trace.Meta.debug true in\ntstcmd\n\nopen Lean Meta\n\nmacro \"r\" r:interpolatedStr(term) : doElem =>\n  `(doElem| trace[Meta.debug] $r)\n\nset_option trace.Meta.debug true in\n#eval show MetaM _ from do r \"world\"\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/traceClassScopes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.23934933647101647, "lm_q2_score": 0.02800752080881603, "lm_q1q2_score": 0.006703581521788303}}
{"text": "import ..data_util.util\nimport all\n\nsection main\n\nmeta def main_aux (names_file : string) (dest : string) : io unit := do {\n  nm_strs \u2190 (io.mk_file_handle names_file io.mode.read >>= \u03bb f,\n    (string.split (\u03bb c, c = '\\n') <$> buffer.to_string <$> io.fs.read_to_end f)),\n\n  let nm_strs := nm_strs.filter (\u03bb x : string, x.length > 0),\n  nms : list (name \u00d7 list name) \u2190 io.run_tactic' $ nm_strs.mmap parse_decl_nm_and_open_ns,\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n \n  io.run_tactic' $ do {\n    env \u2190 tactic.get_env,\n    for_ nms $ \u03bb \u27e8nm, open_ns\u27e9, tactic.try $ do {\n      decl \u2190 env.get nm,\n      if decl.is_theorem then do {\n        tactic.trace format! \"[filter_defs] KEEPING {nm.to_string}\",\n        tactic.unsafe_run_io $\n          io.fs.put_str_ln_flush\n            dest_handle\n              (nm.to_string ++ \" \" ++ (\" \".intercalate $ name.to_string <$> open_ns))\n      } else do {\n        tactic.trace format! \"[filter_defs] DISCARDING {nm.to_string}\",\n        pure ()\n      }\n    }\n  }\n}\n\nmeta def main : io unit := do {\n  io.put_str_ln' \"ENTERING\",\n  args \u2190 io.cmdline_args,\n  names_file \u2190 args.nth_except 0 \"names_file\",\n  dest \u2190 args.nth_except 1 \"dest\",\n  main_aux names_file dest\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/tools/filter_defs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.02931223361324235, "lm_q1q2_score": 0.006687776691721276}}
{"text": "import Lean\nimport Lean.Parser.Command\nimport Lean.Parser.Term\n\nnamespace NamedState\n\nopen Lean Elab Command Term Meta TSyntax\n\n\n--\n-- A monad to read/write from multiples state variables, using string lookup.\n-- As an example if your state is the struct { z : Nat, y : String } then you\n-- can (getNamed \"y\") or (putNamed \"z\" 3) in your do block.\n-- If using algebraic effects you would need something like [Sendable (NamedState \"z\" Nat) m]\n-- to getNamed/putNamed z.\n--\n\ninductive NamedState (n : String) (v : Type) : Type \u2192 Type where\n  | Get : NamedState n v v\n  | Put : v \u2192 NamedState n v Unit\n  \n/-\n A general monad to use as the target for a collapser.\n Usually when running algebraic effects, the monads you end up with are IO and\n some state. So you can build your collapser to produce a StateIO which handles both of these cases.\n\n Lets' say you have a sum type and freer monad or some equivalent construct. Here we make a freer monad with\n two effects, (NamedState \"z\" Nat \u03b1) and (IO \u03b1)\n\n > mkSumType ExampleCommand >| (NamedState \"z\" Nat), IO |<\n > mkFreer ExampleMonad ExampleCommand\n\n This has two sendable instances, IO and (NamedState \"z\" Nat).\n\n To interpret this we make a StateIO monad as the final target monad:\n\n > mkStateIO Blargh (z:Nat),(y:String) @@\n\n this makes a datatype of type \"StateIO Blarghstruct\" where Blarghstruct is a struct with fields { z:Nat, y:String }\n\n Then in the interpreter you can use \"collapseNamedState\" for example:\n\n > def interpreter1 := buildInterpreter ExampleCommand OneState (NamedState \"z\" Nat),IO\n >   [:\n >     collapseNamedState \"z\" Nat,\n >     collapseIO\n >   :]\n\n-/\n\n\ndef StateIO (sType : Type) (\u03b1 : Type) : Type := sType \u2192 IO (\u03b1 \u00d7 sType)\n\ninstance : Monad (StateIO s) where\n    pure := fun a s => pure \u27e8a, s\u27e9\n    bind := fun m f s => do let \u27e8a', s'\u27e9 \u2190 m s\n                            f a' s'\n\nclass StateOperator (stateContainer : Type) (name : String) (state : Type) where\n    putS : state \u2192 stateContainer \u2192 stateContainer\n    getS : stateContainer \u2192 state\n\n-- Normally a state monad has a single variable that you access using get/put.\n-- This builds a structure representing state, with several fields in it. Each field \"x\"\n-- is a single state that is accessed using putNamed \"x\"/getNamed \"x\".\nset_option hygiene false in\ndef elabSS (structid : TSyntax `Lean.Parser.Command.declId) (vals : Syntax.TSepArray `structfield \",\") : CommandElabM Unit := do\n    let valArray : Array (TSyntax `structfield) := vals\n    let valInstance : TSyntax `structfield \u2192 CommandElabM (TSyntax `Lean.Parser.Command.structExplicitBinder) :=\n      fun n => do\n        let id : Ident := TSyntax.mk <| n.raw.getArgs[1]!\n        let ftype : Term := TSyntax.mk <| n.raw.getArgs[3]!\n        let c \u2190 `(Lean.Parser.Command.structExplicitBinder | ($id : $ftype))\n        pure c\n    let fields \u2190 Array.sequenceMap valArray valInstance\n    let structDecl \u2190 `(structure $structid where $fields:structExplicitBinder*)\n    elabCommand structDecl\n\ndeclare_syntax_cat structfield\nsyntax \" ( \" ident \" : \" term \" ) \" : structfield\n\nelab \"mkStateIOStruct\" structid:ident vals:structfield,+ \" @@ \" : command => elabSS structid vals\n\n-- This makes instances of StateOperator for a particular state container (a structure) and a named\n-- field of that structure. There should be an instance generated for each field of the structure.\nset_option hygiene false in\ndef elabSI (structid :Term) (fields : Syntax.TSepArray `structfield \",\") : CommandElabM Unit := do\n  let fieldArray : Array (TSyntax `structfield) := fields\n  let fieldInstance : TSyntax `structfield \u2192 CommandElabM Unit :=\n    fun n => do\n      let id := TSyntax.mk n.raw.getArgs[1]!\n      let ftype : Term := TSyntax.mk n.raw.getArgs[3]!\n      let s := Syntax.mkStrLit id.getId.toString\n      let c \u2190 `(instance : StateOperator $structid $s $ftype where\n                  putS := fun v s => { s with $id:ident := v}\n                  getS := fun s => s.$id)\n      elabCommand c\n  Array.forM fieldInstance fieldArray\n\nelab \"mkStateInterfaces\" structid:term vals:structfield,+ \" @@ \" : command => elabSI structid vals\n\n-- Makes a complete set of definitions for a StateIO monad, including:\n--  A structure with fields to hold all the named states\n--  Instances of StateOperator to get/put state\n--  A Monad instance\n-- You provide the monad name and field names/types.  For a StateIO monad named \"x\" there is also\n-- a State structure named \"xstruct\" which you can use.\nelab \"mkStateIO\" stateIOname:ident vals:structfield,+ \" @@ \" : command => do\n    let structid : Ident := Lean.mkIdent <| Name.appendAfter stateIOname.getId \"struct\"\n    elabSS structid vals\n    elabSI structid vals\n    let siodef \u2190 `(def $stateIOname := StateIO $structid)\n    elabCommand siodef\n    let c \u2190\n        `(instance : Monad $stateIOname where\n              pure := fun a s => pure \u27e8a, s\u27e9\n              bind := fun m f s => do let \u27e8a', s'\u27e9 \u2190 m s\n                                      f a' s')\n    elabCommand c\n\n\n--mkStateIOStruct Blargh (z:Nat),(y:String) @@\n--mkStateInterfaces Blargh (z:Nat),(y:String) @@\n\n/-\nmkStateIO Blargh (z:Nat),(y:String) @@\n\ndef testStruct : Blarghstruct := { z := 3, y := \"argh\"}\n\n#check testStruct\ndef goP [StateOperator Blarghstruct \"z\" Nat] : Blarghstruct \u2192 Nat := fun b => StateOperator.getS \"z\" b\n#eval goP testStruct\n-/\n\n\n-- When running the interpreter for a Freer monad that has one or more named state, you typically collapse\n-- the monad into a StateIO monad.  For each effect that is a NamedState you can use collapseNamedState.\ndef collapseNamedState (n : String) (v : Type) [StateOperator s n v] {\u03b1 : Type} : NamedState n v \u03b1 \u2192 StateIO s \u03b1 :=\n  fun m =>\n    match m with\n    | .Get => fun s => pure \u27e8StateOperator.getS n s,s\u27e9\n    | .Put v' => fun s => pure \u27e8(), StateOperator.putS n v' s\u27e9\n\n-- When running the interpreter for a Freer monad that has one or more named state, you typically collapse\n-- the monad into a StateIO monad.  If you have an effect that represents arbitrary IO you can collapse it with collapseIO.\ndef collapseIO : IO \u03b1 \u2192 StateIO ss \u03b1 :=\n    fun o => fun s => Functor.map (fun x => \u27e8x,s\u27e9) o\n\nend NamedState\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/Data/NamedState.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825678173200435, "lm_q2_score": 0.023689471644012663, "lm_q1q2_score": 0.006591756140594538}}
{"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 \u03b1) : monadLift x = x :=\n  rfl\n\nclass LawfulFunctor (f : Type u \u2192 Type v) [Functor f] : Prop where\n  map_const          : (Functor.mapConst : \u03b1 \u2192 f \u03b2 \u2192 f \u03b1) = Functor.map \u2218 const \u03b2\n  id_map   (x : f \u03b1) : id <$> x = x\n  comp_map (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) (x : f \u03b1) : (h \u2218 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 \u03b1) : (fun a => a) <$> x = x :=\n  id_map x\n\nclass LawfulApplicative (f : Type u \u2192 Type v) [Applicative f] extends LawfulFunctor f : Prop where\n  seqLeft_eq  (x : f \u03b1) (y : f \u03b2)     : x <* y = const \u03b2 <$> x <*> y\n  seqRight_eq (x : f \u03b1) (y : f \u03b2)     : x *> y = const \u03b1 id <$> x <*> y\n  pure_seq    (g : \u03b1 \u2192 \u03b2) (x : f \u03b1)   : pure g <*> x = g <$> x\n  map_pure    (g : \u03b1 \u2192 \u03b2) (x : \u03b1)     : g <$> (pure x : f \u03b1) = pure (g x)\n  seq_pure    {\u03b1 \u03b2 : Type u} (g : f (\u03b1 \u2192 \u03b2)) (x : \u03b1) : g <*> pure x = (fun h => h x) <$> g\n  seq_assoc   {\u03b1 \u03b2 \u03b3 : Type u} (x : f \u03b1) (g : f (\u03b1 \u2192 \u03b2)) (h : f (\u03b2 \u2192 \u03b3)) : h <*> (g <*> x) = ((@comp \u03b1 \u03b2 \u03b3) <$> h) <*> g <*> x\n  comp_map g h x := (by\n    repeat rw [\u2190 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 \u03b1) : pure id <*> x = x := by\n  simp [pure_seq]\n\nclass LawfulMonad (m : Type u \u2192 Type v) [Monad m] extends LawfulApplicative m : Prop where\n  bind_pure_comp (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : x >>= pure \u2218 f = f <$> x\n  bind_map       {\u03b1 \u03b2 : Type u} (f : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : f >>= (. <$> x) = f <*> x\n  pure_bind      (x : \u03b1) (f : \u03b1 \u2192 m \u03b2) : pure x >>= f = f x\n  bind_assoc     (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) (g : \u03b2 \u2192 m \u03b3) : x >>= f >>= g = x >>= fun x => f x >>= g\n  map_pure g x    := (by rw [\u2190 bind_pure_comp, pure_bind])\n  seq_pure g x    := (by rw [\u2190 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 {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : f <$> x = x >>= pure \u2218 f := by\n      rw [bind_pure_comp]\n    let bind_map_symm {\u03b1 \u03b2 : Type u} (f : m (\u03b1 \u2192 (\u03b2 : Type u))) (x : m \u03b1) : 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 \u03b1) : x >>= pure = x := by\n  show x >>= pure \u2218 id = x\n  rw [bind_pure_comp, id_map]\n\ntheorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : f <$> x = x >>= fun a => pure (f a) := by\n  rw [\u2190 bind_pure_comp]\n\ntheorem seq_eq_bind_map {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (f : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : f <*> x = f >>= (. <$> x) := by\n  rw [\u2190 bind_map]\n\ntheorem bind_congr [Bind m] {x : m \u03b1} {f g : \u03b1 \u2192 m \u03b2} (h : \u2200 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 \u27e8\u27e9) = x := by\n  have : (x >>= fun _ => pure \u27e8\u27e9) = (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 \u03b1} {f g : \u03b1 \u2192 \u03b2} (h : \u2200 a, f a = g a) : (f <$> x : m \u03b2) = g <$> x := by\n  simp [funext h]\n\ntheorem seq_eq_bind {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (mf : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : mf <*> x = mf >>= fun f => f <$> x := by\n  rw [bind_map]\n\ntheorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m \u03b1) (y : m \u03b2) : 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 \u03b1) (y : m \u03b2) : 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 \u03b1) (f : \u03b1 \u2192 \u03b2) : f <$> x = f x := rfl\n@[simp] theorem bind_eq (x : Id \u03b1) (f : \u03b1 \u2192 id \u03b2) : x >>= f = f x := rfl\n@[simp] theorem pure_eq (a : \u03b1) : (pure a : Id \u03b1) = 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 \u03b5 m \u03b1} (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 \u03b5 m \u03b1) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift [Monad m] (x : m \u03b1) : run (ExceptT.lift x : ExceptT \u03b5 m \u03b1) = (Except.ok <$> x : m (Except \u03b5 \u03b1)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT \u03b5 m \u03b2) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : run (ExceptT.lift x >>= f : ExceptT \u03b5 m \u03b2) = 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 : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : (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 \u03b5 m \u03b1)\n        : run (x >>= f : ExceptT \u03b5 m \u03b2)\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 : \u03b1) : ExceptT.lift (pure a) = (pure a : ExceptT \u03b5 m \u03b1) := by\n  simp [ExceptT.lift, pure, ExceptT.pure]\n\n@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1)\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 {\u03b1 \u03b2 \u03b5 : Type u} [Monad m] (mf : ExceptT \u03b5 m (\u03b1 \u2192 \u03b2)) (x : ExceptT \u03b5 m \u03b1) : mf <*> x = mf >>= fun f => f <$> x :=\n  rfl\n\nprotected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1) : x >>= pure \u2218 f = f <$> x := by\n  intros; rfl\n\nprotected theorem seqLeft_eq {\u03b1 \u03b2 \u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m] [LawfulMonad m] (x : ExceptT \u03b5 m \u03b1) (y : ExceptT \u03b5 m \u03b2) : x <* y = const \u03b2 <$> x <*> y := by\n  show (x >>= fun a => y >>= fun _ => pure a) = (const (\u03b1 := \u03b1) \u03b2 <$> x) >>= fun f => f <$> y\n  rw [\u2190 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 \u03b5 m \u03b1) (y : ExceptT \u03b5 m \u03b2) : x *> y = const \u03b1 id <$> x <*> y := by\n  show (x >>= fun _ => y) = (const \u03b1 id <$> x) >>= fun f => f <$> y\n  rw [\u2190 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 \u03b5 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 \u03c1 m \u03b1} (h : \u2200 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 : \u03b1) (ctx : \u03c1) : (pure a : ReaderT \u03c1 m \u03b1).run ctx = pure a := rfl\n\n@[simp] theorem run_bind [Monad m] (x : ReaderT \u03c1 m \u03b1) (f : \u03b1 \u2192 ReaderT \u03c1 m \u03b2) (ctx : \u03c1)\n    : (x >>= f).run ctx = x.run ctx >>= \u03bb a => (f a).run ctx := rfl\n\n@[simp] theorem run_map [Monad m] (f : \u03b1 \u2192 \u03b2) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (f <$> x).run ctx = f <$> x.run ctx := rfl\n\n@[simp] theorem run_monadLift [MonadLiftT n m] (x : n \u03b1) (ctx : \u03c1)\n    : (monadLift x : ReaderT \u03c1 m \u03b1).run ctx = (monadLift x : m \u03b1) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {\u03b2 : Type u} \u2192 n \u03b2 \u2192 n \u03b2) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (monadMap @f x : ReaderT \u03c1 m \u03b1).run ctx = monadMap @f (x.run ctx) := rfl\n\n@[simp] theorem run_read [Monad m] (ctx : \u03c1) : (ReaderT.read : ReaderT \u03c1 m \u03c1).run ctx = pure ctx := rfl\n\n@[simp] theorem run_seq {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (f : ReaderT \u03c1 m (\u03b1 \u2192 \u03b2)) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1) : (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 \u03c1 m \u03b1) (y : ReaderT \u03c1 m \u03b2) (ctx : \u03c1) : (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 \u03c1 m \u03b1) (y : ReaderT \u03c1 m \u03b2) (ctx : \u03c1) : (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 \u03c1 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' \u03c9 \u03c3 m) :=\n  inferInstanceAs (LawfulMonad (ReaderT (ST.Ref \u03c9 \u03c3) m))\n\n/- StateT -/\n\nnamespace StateT\n\ntheorem ext {x y : StateT \u03c3 m \u03b1} (h : \u2200 s, x.run s = y.run s) : x = y :=\n  funext h\n\n@[simp] theorem run'_eq [Monad m] (x : StateT \u03c3 m \u03b1) (s : \u03c3) : run' x s = (\u00b7.1) <$> run x s :=\n  rfl\n\n@[simp] theorem run_pure [Monad m] (a : \u03b1) (s : \u03c3) : (pure a : StateT \u03c3 m \u03b1).run s = pure (a, s) := rfl\n\n@[simp] theorem run_bind [Monad m] (x : StateT \u03c3 m \u03b1) (f : \u03b1 \u2192 StateT \u03c3 m \u03b2) (s : \u03c3)\n    : (x >>= f).run s = x.run s >>= \u03bb 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 {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : StateT \u03c3 m \u03b1) (s : \u03c3) : (f <$> x).run s = (fun (p : \u03b1 \u00d7 \u03c3) => (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 : \u03c3)    : (get : StateT \u03c3 m \u03c3).run s = pure (s, s) := rfl\n\n@[simp] theorem run_set [Monad m] (s s' : \u03c3) : (set s' : StateT \u03c3 m PUnit).run s = pure (\u27e8\u27e9, s') := rfl\n\n@[simp] theorem run_modify [Monad m] (f : \u03c3 \u2192 \u03c3) (s : \u03c3) : (modify f : StateT \u03c3 m PUnit).run s = pure (\u27e8\u27e9, f s) := rfl\n\n@[simp] theorem run_modifyGet [Monad m] (f : \u03c3 \u2192 \u03b1 \u00d7 \u03c3) (s : \u03c3) : (modifyGet f : StateT \u03c3 m \u03b1).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 {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (s : \u03c3) : (StateT.lift x : StateT \u03c3 m \u03b1).run s = x >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_bind_lift {\u03b1 \u03c3 : Type u} [Monad m] [LawfulMonad m] (x : m \u03b1) (f : \u03b1 \u2192 StateT \u03c3 m \u03b2) (s : \u03c3) : (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 {\u03b1 \u03c3 : Type u} [Monad m] [MonadLiftT n m] (x : n \u03b1) (s : \u03c3) : (monadLift x : StateT \u03c3 m \u03b1).run s = (monadLift x : m \u03b1) >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {\u03b2 : Type u} \u2192 n \u03b2 \u2192 n \u03b2) (x : StateT \u03c3 m \u03b1) (s : \u03c3)\n    : (monadMap @f x : StateT \u03c3 m \u03b1).run s = monadMap @f (x.run s) := rfl\n\n@[simp] theorem run_seq {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (f : StateT \u03c3 m (\u03b1 \u2192 \u03b2)) (x : StateT \u03c3 m \u03b1) (s : \u03c3) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : \u03b1 \u00d7 \u03c3) => (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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) (s : \u03c3) : (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 {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (x : StateT \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) (s : \u03c3) : (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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) : x *> y = const \u03b1 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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) : x <* y = const \u03b2 <$> x <*> y := by\n  apply ext; intro s\n  simp [map_eq_pure_bind]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateT \u03c3 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 init.lean.message init.lean.parser.syntax init.lean.parser.trie init.lean.parser.basic init.lean.parser.stringliteral\nimport init.lean.parser.token\n\nnamespace Lean\nnamespace flatParser\nopen String\nopen Parser (Syntax Syntax.missing)\nopen Parser (Trie TokenMap)\n\nabbreviation pos := String.Pos\n\n/-- A precomputed cache for quickly mapping Char offsets to positions. -/\nstructure FileMap :=\n(offsets : Array Nat)\n(lines   : Array Nat)\n\nnamespace FileMap\nprivate def fromStringAux (s : String) : Nat \u2192 Nat \u2192 Nat \u2192 pos \u2192 Array Nat \u2192 Array Nat \u2192 FileMap\n| 0     offset line i offsets lines := \u27e8offsets.push offset, lines.push line\u27e9\n| (k+1) offset line i offsets lines :=\n  if s.atEnd i then \u27e8offsets.push offset, lines.push line\u27e9\n  else let c := s.get i in\n       let i := s.next i in\n       let offset := offset + 1 in\n       if c = '\\n'\n       then fromStringAux k offset (line+1) i (offsets.push offset) (lines.push (line+1))\n       else fromStringAux k offset line i offsets lines\n\ndef fromString (s : String) : FileMap :=\nfromStringAux s s.length 0 1 0 (Array.empty.push 0) (Array.empty.push 1)\n\n/- Remark: `offset is in [(offsets.get b), (offsets.get e)]` and `b < e` -/\nprivate def toPositionAux (offsets : Array Nat) (lines : Array Nat) (offset : Nat) : Nat \u2192 Nat \u2192 Nat \u2192 Position\n| 0     b e := \u27e8offset, 1\u27e9 -- unreachable\n| (k+1) b e :=\n  let offsetB := offsets.get b in\n  if e = b + 1 then \u27e8offset - offsetB, lines.get b\u27e9\n  else let m := (b + e) / 2 in\n       let offsetM := offsets.get m in\n       if offset = offsetM then \u27e80, lines.get m\u27e9\n       else if offset > offsetM then toPositionAux k m e\n       else toPositionAux k b m\n\ndef toPosition : FileMap \u2192 Nat \u2192 Position\n| \u27e8offsets, lines\u27e9 offset := toPositionAux offsets lines offset offsets.size 0 (offsets.size-1)\nend FileMap\n\nstructure TokenConfig :=\n(\u00abprefix\u00bb : String)\n(lbp : Nat := 0)\n\nstructure FrontendConfig :=\n(filename : String)\n(input    : String)\n(FileMap : FileMap)\n\n/- Remark: if we have a Node in the Trie with `some TokenConfig`, the String induced by the path is equal to the `TokenConfig.prefix`. -/\nstructure ParserConfig extends FrontendConfig :=\n(tokens : Trie TokenConfig)\n\n-- Backtrackable State\nstructure ParserState :=\n(messages : MessageLog)\n\nstructure TokenCacheEntry :=\n(startPos stopPos : pos)\n(tk : Syntax)\n\n-- Non-backtrackable State\nstructure ParserCache :=\n(tokenCache : Option TokenCacheEntry := none)\n\ninductive Result (\u03b1 : Type)\n| ok       (a : \u03b1)        (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result\n| error {} (msg : String) (i : pos) (cache : ParserCache) (stx : Syntax)         (eps : Bool) : Result\n\ninductive Result.IsOk {\u03b1 : Type} : Result \u03b1 \u2192 Prop\n| mk (a : \u03b1) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result.IsOk (Result.ok a i cache State eps)\n\ntheorem errorIsNotOk {\u03b1 : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool}\n                        (h : Result.IsOk (@Result.error \u03b1 msg i cache stx eps)) : False :=\nmatch h with end\n\n@[inline] def unreachableError {\u03b1 \u03b2 : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool}\n                                (h : Result.IsOk (@Result.error \u03b1 msg i cache stx eps)) : \u03b2 :=\nFalse.elim (errorIsNotOk h)\n\ndef resultOk := {r : Result Unit // r.IsOk}\n\n@[inline] def mkResultOk (i : pos) (cache : ParserCache) (State : ParserState) (eps := true) : resultOk :=\n\u27e8Result.ok () i cache State eps, Result.IsOk.mk _ _ _ _ _\u27e9\n\ndef parserCoreM (\u03b1 : Type) :=\nParserConfig \u2192 resultOk \u2192 Result \u03b1\nabbreviation parserCore := parserCoreM Syntax\n\nstructure recParsers :=\n(cmdParser  : parserCore)\n(termParser : Nat \u2192 parserCore)\n\ndef parserM (\u03b1 : Type) := recParsers \u2192 parserCoreM \u03b1\nabbreviation Parser := parserM Syntax\nabbreviation trailingParser := Syntax \u2192 Parser\n\n@[inline] def command.Parser : Parser := \u03bb ps, ps.cmdParser\n@[inline] def Term.Parser (rbp : Nat := 0) : Parser  := \u03bb ps, ps.termParser rbp\n\n@[inline] def parserM.pure {\u03b1 : Type} (a : \u03b1) : parserM \u03b1 :=\n\u03bb _ _ r,\n  match r with\n  | \u27e8Result.ok _ it c s _, h\u27e9   := Result.ok a it c s true\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline_if_reduce] def eagerOr  (b\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\n@[inline_if_reduce] def eagerAnd (b\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\n\n@[inline] def parserM.bind {\u03b1 \u03b2 : Type} (x : parserM \u03b1) (f : \u03b1 \u2192 parserM \u03b2) : parserM \u03b2 :=\n\u03bb ps cfg r,\n  match x ps cfg r with\n  | Result.ok a i c s e\u2081 :=\n    (match f a ps cfg (mkResultOk i c s) with\n     | Result.ok b i c s e\u2082        := Result.ok b i c s (eagerAnd e\u2081 e\u2082)\n     | Result.error msg i c stx e\u2082 := Result.error msg i c stx (eagerAnd e\u2081 e\u2082))\n  | Result.error msg i c stx e  := Result.error msg i c stx e\n\ninstance : Monad parserM :=\n{pure := @parserM.pure, bind := @parserM.bind}\n\n@[inline] protected def orelse {\u03b1 : Type} (p q : parserM \u03b1) : parserM \u03b1 :=\n\u03bb ps cfg r,\n  match r with\n  | \u27e8Result.ok _ i\u2081 _ s\u2081 _, _\u27e9 :=\n    (match p ps cfg r with\n     | Result.error msg\u2081 i\u2082 c\u2082 stx\u2081 true := q ps cfg (mkResultOk i\u2081 c\u2082 s\u2081)\n     | other                           := other)\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline] protected def failure {\u03b1 : Type} : parserM \u03b1 :=\n\u03bb _ _ r,\n  match r with\n  | \u27e8Result.ok _ i c s _, h\u27e9    := Result.error \"failure\" i c Syntax.missing true\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\ninstance : Alternative parserM :=\n{ orelse         := @flatParser.orelse,\n  failure        := @flatParser.failure,\n  ..flatParser.Monad }\n\ndef setSilentError {\u03b1 : Type} : Result \u03b1 \u2192 Result \u03b1\n| (Result.error i c msg stx _) := Result.error i c msg stx true\n| other                        := other\n\n/--\n`try p` behaves like `p`, but it pretends `p` hasn't\nconsumed any input when `p` fails.\n-/\n@[inline] def try {\u03b1 : Type} (p : parserM \u03b1) : parserM \u03b1 :=\n\u03bb ps cfg r, setSilentError (p ps cfg r)\n\n@[inline] def atEnd (cfg : ParserConfig) (i : pos) : Bool :=\ncfg.input.atEnd i\n\n@[inline] def curr (cfg : ParserConfig) (i : pos) : Char :=\ncfg.input.get i\n\n@[inline] def next (cfg : ParserConfig) (i : pos) : pos :=\ncfg.input.next i\n\n@[inline] def inputSize (cfg : ParserConfig) : Nat :=\ncfg.input.length\n\n@[inline] def currPos : resultOk \u2192 pos\n| \u27e8Result.ok _ i _ _ _, _\u27e9    := i\n| \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline] def currState : resultOk \u2192 ParserState\n| \u27e8Result.ok _ _ _ s _, _\u27e9    := s\n| \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\ndef mkError {\u03b1 : Type} (r : resultOk) (msg : String) (stx : Syntax := Syntax.missing) (eps := true) : Result \u03b1 :=\nmatch r with\n| \u27e8Result.ok _ i c s _, _\u27e9    := Result.error msg i c stx eps\n| \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline] def satisfy (p : Char \u2192 Bool) : parserM Char :=\n\u03bb _ cfg r,\n  match r with\n  | \u27e8Result.ok _ i ch st e, _\u27e9 :=\n    if atEnd cfg i then mkError r \"end of input\"\n    else let c := curr cfg i in\n         if p c then Result.ok c (next cfg i) ch st false\n         else mkError r \"unexpected character\"\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\ndef any : parserM Char :=\nsatisfy (\u03bb _, true)\n\n@[specialize] def takeUntilAux (p : Char \u2192 Bool) (cfg : ParserConfig) : Nat \u2192 resultOk \u2192 Result Unit\n| 0     r := r.val\n| (n+1) r :=\n  match r with\n  | \u27e8Result.ok _ i ch st e, _\u27e9 :=\n    if atEnd cfg i then r.val\n    else let c := curr cfg i in\n         if p c then r.val\n         else takeUntilAux n (mkResultOk (next cfg i) ch st true)\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[specialize] def takeUntil (p : Char \u2192 Bool) : parserM Unit :=\n\u03bb ps cfg r, takeUntilAux p cfg (inputSize cfg) r\n\ndef takeUntilNewLine : parserM Unit :=\ntakeUntil (= '\\n')\n\ndef whitespace : parserM Unit :=\ntakeUntil (\u03bb c, !c.isWhitespace)\n\n-- setOption Trace.Compiler.boxed True\n--- setOption pp.implicit True\n\ndef strAux (cfg : ParserConfig) (str : String) (error : String) : Nat \u2192 resultOk \u2192 pos \u2192 Result Unit\n| 0     r j := mkError r error\n| (n+1) r j :=\n  if str.atEnd j then r.val\n  else\n    match r with\n    | \u27e8Result.ok _ i ch st e, _\u27e9 :=\n      if atEnd cfg i then Result.error error i ch Syntax.missing true\n      else if curr cfg i = str.get j then strAux n (mkResultOk (next cfg i) ch st true) (str.next j)\n      else Result.error error i ch Syntax.missing true\n    | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n-- #exit\n\n@[inline] def str (s : String) : parserM Unit :=\n\u03bb ps cfg r, strAux cfg s (\"expected \" ++ repr s) (inputSize cfg) r 0\n\n@[specialize] def manyAux (p : parserM Unit) : Nat \u2192 Bool \u2192 parserM Unit\n| 0     fst := pure ()\n| (k+1) fst := \u03bb ps cfg r,\n  let i\u2080 := currPos r in\n  let s\u2080 := currState r in\n  match p ps cfg r with\n  | Result.ok a i c s _    := manyAux k false ps cfg (mkResultOk i c s)\n  | Result.error _ _ c _ _ := Result.ok () i\u2080 c s\u2080 fst\n\n@[inline] def many (p : parserM Unit) : parserM Unit  :=\n\u03bb ps cfg r, manyAux p (inputSize cfg) true ps cfg r\n\n@[inline] def many1 (p : parserM Unit) : parserM Unit  :=\np *> many p\n\ndef dummyParserCore : parserCore :=\n\u03bb cfg r, mkError r \"dummy\"\n\ndef testParser {\u03b1 : Type} (x : parserM \u03b1) (input : String) : String :=\nlet r :=\n  x { cmdParser := dummyParserCore, termParser := \u03bb _, dummyParserCore }\n    { filename := \"test\", input := input, FileMap := FileMap.fromString input, tokens := Lean.Parser.Trie.empty }\n    (mkResultOk 0 {} {messages := MessageLog.empty}) in\nmatch r with\n| Result.ok _ i _ _ _      := \"Ok at \" ++ toString i\n| Result.error msg i _ _ _ := \"Error at \" ++ toString i ++ \": \" ++ msg\n\n/-\nmutual def recCmd, recTerm (parseCmd : Parser) (parseTerm : Nat \u2192 Parser) (parseLvl : Nat \u2192 parserCore)\nwith recCmd  : Nat \u2192 parserCore\n| 0     cfg r := mkError r \"Parser: no progress\"\n| (n+1) cfg r := parseCmd \u27e8recCmd n, parseLvl, recTerm n\u27e9 cfg r\nwith recTerm : Nat \u2192 Nat \u2192 parserCore\n| 0     rbp cfg r := mkError r \"Parser: no progress\"\n| (n+1) rbp cfg r := parseTerm rbp \u27e8recCmd n, parseLvl, recTerm n\u27e9 cfg r\n-/\n\n/-\ndef runParser (x : Parser) (parseCmd : Parser) (parseLvl : Nat \u2192 Parser) (parseTerm : Nat \u2192 Parser)\n               (input : Iterator) (cfg : ParserConfig) : Result Syntax :=\nlet it := input in\nlet n  := it.remaining in\nlet r  := mkResultOk it {} {messages := MessageLog.Empty} in\nlet pl := recLvl (parseLvl) n in\nlet ps : recParsers := { cmdParser  := recCmd parseCmd parseTerm pl n,\n                          lvlParser  := pl,\n                          termParser := recTerm parseCmd parseTerm pl n } in\nx ps cfg r\n-/\n\nstructure parsingTables :=\n(leadingTermParsers : TokenMap Parser)\n(trailingTermParsers : TokenMap trailingParser)\n\nabbreviation CommandParserM (\u03b1 : Type) :=\nparsingTables \u2192 parserM \u03b1\n\nend flatParser\nend Lean\n\nsection\nopen Lean.flatParser\n\ndef flatP : parserM Unit :=\nmany1 (str \"++\" <|> str \"**\" <|>  (str \"--\" *> takeUntil (= '\\n') *> any *> pure ()))\n\nend\n\nsection\nopen Lean.Parser\nopen Lean.Parser.MonadParsec\n\n@[reducible] def Parser (\u03b1 : Type) : Type :=  ReaderT Lean.flatParser.recParsers (ReaderT Lean.flatParser.ParserConfig (ParsecT Syntax (StateT ParserCache Id))) \u03b1\n\ndef testParsec (p : Parser Unit) (input : String) : String :=\nlet ps : Lean.flatParser.recParsers := { cmdParser := Lean.flatParser.dummyParserCore, termParser := \u03bb _, Lean.flatParser.dummyParserCore } in\nlet cfg : Lean.flatParser.ParserConfig := { filename := \"test\", input := input, FileMap := Lean.flatParser.FileMap.fromString input, tokens := Lean.Parser.Trie.empty } in\nlet r := p ps cfg input.mkOldIterator {} in\nmatch r with\n| (Parsec.Result.ok _ it _, _)   := \"OK at \" ++ toString it.offset\n| (Parsec.Result.error msg _, _) := \"Error \" ++ msg.toString\n\n@[inline] def str' (s : String) : Parser Unit :=\nstr s *> pure ()\n\ndef parsecP : Parser Unit :=\nmany1' (str' \"++\" <|> str' \"**\" <|> (str \"--\" *> takeUntil (\u03bb c, c = '\\n') *> any *> pure ()))\n\ndef parsecP2 : Parser Unit :=\nmany1' ((parseStringLiteral *> whitespace *> pure ()) <|> (str \"--\" *> takeUntil (\u03bb c, c = '\\n') *> any *> pure ()))\n\nend\n\n\nnamespace BasicParser\nopen Lean.Parser\nopen Lean.Parser.MonadParsec\n\ndef testBasicParser (p : BasicParserM Unit) (input : String) : String :=\nlet cfg : Lean.Parser.ParserConfig := {\nfilename := \"test\", input := input, fileMap := { lines := {} }, tokens := Lean.Parser.Trie.empty } in\nlet r := p cfg input.mkOldIterator {} in\nmatch r with\n| (Parsec.Result.ok _ it _, _)   := \"OK at \" ++ toString it.offset\n| (Parsec.Result.error msg _, _) := \"Error \" ++ msg.toString\n\n@[inline] def str' (s : String) : BasicParserM Unit :=\nstr s *> pure ()\n\ndef parserP : BasicParserM Unit :=\nmany1' (str' \"++\" <|> str' \"**\" <|> (str \"--\" *> takeUntil (\u03bb c, c = '\\n') *> any *> pure ()))\n\ndef parser2 : BasicParserM Unit :=\nmany1' ((parseStringLiteral *> Lean.Parser.MonadParsec.whitespace *> pure ()) <|> (str \"--\" *> takeUntil (\u03bb c, c = '\\n') *> any *> pure ()))\n\ndef parser3 : BasicParserM Unit :=\nLean.Parser.whitespace\n\nend BasicParser\n\ndef mkBigString : Nat \u2192 String \u2192 String\n| 0     s := s\n| (n+1) s := mkBigString n (s ++ \"-- new comment\\n\")\n\ndef mkBigString2 : Nat \u2192 String \u2192 String\n| 0     s := s\n| (n+1) s := mkBigString2 n (s ++ \"\\\"hello\\\\nworld\\\"\\n-- comment\\n\")\n\ndef mkBigString3 : Nat \u2192 String \u2192 String\n| 0     s := s\n| (n+1) s := mkBigString3 n (s ++ \"/- /- comment 1 -/ -/ \\n -- comment 2 \\n \\t \\n \")\n\n@[noinline] def testFlatP (s : String) : IO Unit :=\nIO.println (Lean.flatParser.testParser flatP s)\n\n@[noinline] def testParsecP (p : Parser Unit) (s : String) : IO Unit :=\nIO.println (testParsec p s)\n\n@[noinline] def testBasicParser (p : Lean.Parser.BasicParserM Unit) (s : String) : IO Unit :=\nIO.println (BasicParser.testBasicParser p s)\n\n@[noinline] def prof {\u03b1 : Type} (msg : String) (p : IO \u03b1) : IO \u03b1 :=\nlet msg\u2081 := \"Time for '\" ++ msg ++ \"':\" in\nlet msg\u2082 := \"Memory usage for '\" ++ msg ++ \"':\" in\nallocprof msg\u2082 (timeit msg\u2081 p)\n\ndef main (xs : List String) : IO Unit :=\n-- let s\u2081 := mkBigString xs.head.toNat \"\" in\n-- let s\u2082 := s\u2081 ++ \"bad\" ++ mkBigString 20 \"\" in\n-- let s\u2083 := mkBigString2 xs.head.toNat \"\" in\nlet s\u2084 := mkBigString3 xs.head.toNat \"\" in\n-- prof \"flat Parser 1\" (testFlatP s\u2081) *>\n-- prof \"flat Parser 2\" (testFlatP s\u2082) *>\n-- prof \"Parsec 1\" (testParsecP parsecP s\u2081) *>\n-- prof \"Parsec 2\" (testParsecP parsecP s\u2082) *>\n-- prof \"Parsec 3\" (testParsecP parsecP2 s\u2083) *>\nprof \"Basic parser 1\" (testBasicParser BasicParser.parser3 s\u2084)\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/flat_parser.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237174, "lm_q2_score": 0.0267592824092946, "lm_q1q2_score": 0.006558299080694811}}
{"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.SCC\nimport Lean.Elab.PreDefinition.Basic\nimport Lean.Elab.PreDefinition.Structural\nimport Lean.Elab.PreDefinition.WF.Main\nimport Lean.Elab.PreDefinition.MkInhabitant\n\nnamespace Lean.Elab\nopen Meta\nopen Term\n\nstructure TerminationHints where\n  terminationBy? : Option Syntax := none\n  decreasingBy? : Option Syntax := none\n  deriving Inhabited\n\nprivate def addAndCompilePartial (preDefs : Array PreDefinition) (useSorry := false) : TermElabM Unit := do\n  for preDef in preDefs do\n    trace[Elab.definition] \"processing {preDef.declName}\"\n    let all := preDefs.toList.map (\u00b7.declName)\n    forallTelescope preDef.type fun xs type => do\n      let value \u2190 if useSorry then\n        mkLambdaFVars xs (\u2190 mkSorry type (synthetic := true))\n      else\n        liftM <| mkInhabitantFor preDef.declName xs type\n      addNonRec { preDef with\n        kind  := DefKind.\u00abopaque\u00bb\n        value\n      } (all := all)\n  addAndCompilePartialRec preDefs\n\nprivate def isNonRecursive (preDef : PreDefinition) : Bool :=\n  Option.isNone $ preDef.value.find? fun\n    | Expr.const declName _ => preDef.declName == declName\n    | _ => false\n\nprivate def partitionPreDefs (preDefs : Array PreDefinition) : Array (Array PreDefinition) :=\n  let getPreDef    := fun declName => (preDefs.find? fun preDef => preDef.declName == declName).get!\n  let vertices     := preDefs.toList.map (\u00b7.declName)\n  let successorsOf := fun declName => (getPreDef declName).value.foldConsts [] fun declName successors =>\n    if preDefs.any fun preDef => preDef.declName == declName then\n      declName :: successors\n    else\n      successors\n  let sccs := SCC.scc vertices successorsOf\n  sccs.toArray.map fun scc => scc.toArray.map getPreDef\n\nprivate def collectMVarsAtPreDef (preDef : PreDefinition) : StateRefT CollectMVars.State MetaM Unit := do\n  collectMVars preDef.value\n  collectMVars preDef.type\n\nprivate def getMVarsAtPreDef (preDef : PreDefinition) : MetaM (Array MVarId) := do\n  let (_, s) \u2190 (collectMVarsAtPreDef preDef).run {}\n  pure s.result\n\nprivate def ensureNoUnassignedMVarsAtPreDef (preDef : PreDefinition) : TermElabM PreDefinition := do\n  let pendingMVarIds \u2190 getMVarsAtPreDef preDef\n  if (\u2190 logUnassignedUsingErrorInfos pendingMVarIds) then\n    let preDef := { preDef with value := (\u2190 mkSorry preDef.type (synthetic := true)) }\n    if (\u2190 getMVarsAtPreDef preDef).isEmpty then\n      return preDef\n    else\n      throwAbortCommand\n  else\n    return preDef\n\n/--\n  Letrec declarations produce terms of the form `(fun .. => ..) d` where `d` is a (partial) application of an auxiliary declaration for a letrec declaration.\n  This method beta-reduces them to make sure they can be eliminated by the well-founded recursion module. -/\nprivate def betaReduceLetRecApps (preDefs : Array PreDefinition) : MetaM (Array PreDefinition) :=\n  preDefs.mapM fun preDef => do\n    let value \u2190 transform preDef.value fun e => do\n      if e.isApp && e.getAppFn.isLambda && e.getAppArgs.all fun arg => arg.getAppFn.isConst && preDefs.any fun preDef => preDef.declName == arg.getAppFn.constName! then\n        return .visit e.headBeta\n      else\n        return .continue\n    return { preDef with value }\n\nprivate def addAsAxioms (preDefs : Array PreDefinition) : TermElabM Unit := do\n  for preDef in preDefs do\n    let decl := Declaration.axiomDecl {\n      name        := preDef.declName,\n      levelParams := preDef.levelParams,\n      type        := preDef.type,\n      isUnsafe    := preDef.modifiers.isUnsafe\n    }\n    addDecl decl\n    withSaveInfoContext do  -- save new env\n      addTermInfo' preDef.ref (\u2190 mkConstWithLevelParams preDef.declName) (isBinder := true)\n    applyAttributesOf #[preDef] AttributeApplicationTime.afterTypeChecking\n    applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation\n\ndef addPreDefinitions (preDefs : Array PreDefinition) (hints : TerminationHints) : TermElabM Unit := withLCtx {} {} do\n  for preDef in preDefs do\n    trace[Elab.definition.body] \"{preDef.declName} : {preDef.type} :=\\n{preDef.value}\"\n  let preDefs \u2190 preDefs.mapM ensureNoUnassignedMVarsAtPreDef\n  let preDefs \u2190 betaReduceLetRecApps preDefs\n  let cliques := partitionPreDefs preDefs\n  let mut terminationBy \u2190 liftMacroM <| WF.expandTerminationBy hints.terminationBy? (cliques.map fun ds => ds.map (\u00b7.declName))\n  let mut decreasingBy  \u2190 liftMacroM <| WF.expandTerminationHint hints.decreasingBy? (cliques.map fun ds => ds.map (\u00b7.declName))\n  let mut hasErrors := false\n  for preDefs in cliques do\n    trace[Elab.definition.scc] \"{preDefs.map (\u00b7.declName)}\"\n    if preDefs.size == 1 && isNonRecursive preDefs[0]! then\n      let preDef := preDefs[0]!\n      if preDef.modifiers.isNoncomputable then\n        addNonRec preDef\n      else\n        addAndCompileNonRec preDef\n    else if preDefs.any (\u00b7.modifiers.isUnsafe) then\n      addAndCompileUnsafe preDefs\n    else if preDefs.any (\u00b7.modifiers.isPartial) then\n      for preDef in preDefs do\n        if preDef.modifiers.isPartial && !(\u2190 whnfD preDef.type).isForall then\n          withRef preDef.ref <| throwError \"invalid use of 'partial', '{preDef.declName}' is not a function{indentExpr preDef.type}\"\n      addAndCompilePartial preDefs\n    else\n      try\n        let mut wf? := none\n        let mut decrTactic? := none\n        if let some wf := terminationBy.find? (preDefs.map (\u00b7.declName)) then\n          wf? := some wf\n          terminationBy := terminationBy.markAsUsed (preDefs.map (\u00b7.declName))\n        if let some { ref, value := decrTactic } := decreasingBy.find? (preDefs.map (\u00b7.declName)) then\n          decrTactic? := some (\u2190 withRef ref `(by $(\u27e8decrTactic\u27e9)))\n          decreasingBy := decreasingBy.markAsUsed (preDefs.map (\u00b7.declName))\n        if wf?.isSome || decrTactic?.isSome then\n          wfRecursion preDefs wf? decrTactic?\n        else\n          withRef (preDefs[0]!.ref) <| mapError\n            (orelseMergeErrors\n              (structuralRecursion preDefs)\n              (wfRecursion preDefs none none))\n            (fun msg =>\n              let preDefMsgs := preDefs.toList.map (MessageData.ofExpr $ mkConst \u00b7.declName)\n              m!\"fail to show termination for{indentD (MessageData.joinSep preDefMsgs Format.line)}\\nwith errors\\n{msg}\")\n      catch ex =>\n        hasErrors := true\n        logException ex\n        let s \u2190 saveState\n        try\n          if preDefs.all fun preDef => preDef.kind == DefKind.def || preDefs.all fun preDef => preDef.kind == DefKind.abbrev then\n            -- try to add as partial definition\n            try\n              addAndCompilePartial preDefs (useSorry := true)\n            catch _ =>\n              -- Compilation failed try again just as axiom\n              s.restore\n              addAsAxioms preDefs\n          else if preDefs.all fun preDef => preDef.kind == DefKind.theorem then\n            addAsAxioms preDefs\n        catch _ => s.restore\n  unless hasErrors do\n    liftMacroM <| terminationBy.ensureAllUsed\n    liftMacroM <| decreasingBy.ensureAllUsed\n\nbuiltin_initialize\n  registerTraceClass `Elab.definition.body\n  registerTraceClass `Elab.definition.scc\n\nend Lean.Elab\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/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.0251788416091651, "lm_q1q2_score": 0.006542108584219883}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Util.CollectLevelParams\nimport Lean.Elab.DeclUtil\nimport Lean.Elab.DefView\nimport Lean.Elab.Inductive\nimport Lean.Elab.Structure\nimport Lean.Elab.MutualDef\nimport Lean.Elab.DeclarationRange\nnamespace Lean.Elab.Command\n\nopen Meta\n\nprivate def ensureValidNamespace (name : Name) : MacroM Unit := do\n  match name with\n  | Name.str p s _ =>\n    if s == \"_root_\" then\n      Macro.throwError s!\"invalid namespace '{name}', '_root_' is a reserved namespace\"\n    ensureValidNamespace p\n  | Name.num p .. => Macro.throwError s!\"invalid namespace '{name}', it must not contain numeric parts\"\n  | Name.anonymous => pure ()\n\n/- Auxiliary function for `expandDeclNamespace?` -/\nprivate def expandDeclIdNamespace? (declId : Syntax) : MacroM (Option (Name \u00d7 Syntax)) := do\n  let (id, optUnivDeclStx) := expandDeclIdCore declId\n  let scpView := extractMacroScopes id\n  match scpView.name with\n  | Name.str Name.anonymous s _ => return none\n  | Name.str pre s _            =>\n    ensureValidNamespace pre\n    let nameNew := { scpView with name := Name.mkSimple s }.review\n    -- preserve \"original\" info, if any, so that hover etc. on the namespaced\n    -- name access the info tree node of the declaration name\n    let id := mkIdent nameNew |>.setInfo declId.getHeadInfo\n    if declId.isIdent then\n      return some (pre, id)\n    else\n      return some (pre, declId.setArg 0 id)\n  | _ => return none\n\n/- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/\nprivate def expandDeclNamespace? (stx : Syntax) : MacroM (Option (Name \u00d7 Syntax)) := do\n  if !stx.isOfKind `Lean.Parser.Command.declaration then\n    return none\n  else\n    let decl := stx[1]\n    let k := decl.getKind\n    if k == ``Lean.Parser.Command.abbrev ||\n       k == ``Lean.Parser.Command.def ||\n       k == ``Lean.Parser.Command.theorem ||\n       k == ``Lean.Parser.Command.constant ||\n       k == ``Lean.Parser.Command.axiom ||\n       k == ``Lean.Parser.Command.inductive ||\n       k == ``Lean.Parser.Command.classInductive ||\n       k == ``Lean.Parser.Command.structure then\n      match (\u2190 expandDeclIdNamespace? decl[1]) with\n      | some (ns, declId) => return some (ns, stx.setArg 1 (decl.setArg 1 declId))\n      | none              => return none\n    else if k == ``Lean.Parser.Command.instance then\n      let optDeclId := decl[3]\n      if optDeclId.isNone then return none\n      else match (\u2190 expandDeclIdNamespace? optDeclId[0]) with\n        | some (ns, declId) => return some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId)))\n        | none              => return none\n    else\n      return none\n\ndef elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  -- leading_parser \"axiom \" >> declId >> declSig\n  let declId             := stx[1]\n  let (binders, typeStx) := expandDeclSig stx[2]\n  let scopeLevelNames \u2190 getLevelNames\n  let \u27e8name, declName, allUserLevelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName stx\n  runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do\n    Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration\n    let type \u2190 Term.elabType typeStx\n    Term.synthesizeSyntheticMVarsNoPostponing\n    let type \u2190 instantiateMVars type\n    let type \u2190 mkForallFVars xs type\n    let type \u2190 mkForallFVars vars type (usedOnly := true)\n    let (type, _) \u2190 Term.levelMVarToParam type\n    let usedParams  := collectLevelParams {} type |>.params\n    match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with\n    | Except.error msg      => throwErrorAt stx msg\n    | Except.ok levelParams =>\n      let decl := Declaration.axiomDecl {\n        name        := declName,\n        levelParams := levelParams,\n        type        := type,\n        isUnsafe    := modifiers.isUnsafe\n      }\n      Term.ensureNoUnassignedMVars decl\n      addDecl decl\n      withSaveInfoContext do  -- save new env\n        Term.addTermInfo declId (\u2190 mkConstWithLevelParams declName) (isBinder := true)\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking\n      if isExtern (\u2190 getEnv) declName then\n        compileDecl decl\n      Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation\n\n/-\nleading_parser \"inductive \" >> declId >> optDeclSig >> optional \":=\" >> many ctor\nleading_parser atomic (group (\"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional \":=\" >> many ctor >> optDeriving\n-/\nprivate def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do\n  checkValidInductiveModifier modifiers\n  let (binders, type?) := expandOptDeclSig decl[2]\n  let declId           := decl[1]\n  let \u27e8name, declName, levelNames\u27e9 \u2190 expandDeclId declId modifiers\n  addDeclarationRanges declName decl\n  let ctors      \u2190 decl[4].getArgs.mapM fun ctor => withRef ctor do\n    -- def ctor := leading_parser \" | \" >> declModifiers >> ident >> optional inferMod >> optDeclSig\n    let ctorModifiers \u2190 elabModifiers ctor[1]\n    if ctorModifiers.isPrivate && modifiers.isPrivate then\n      throwError \"invalid 'private' constructor in a 'private' inductive datatype\"\n    if ctorModifiers.isProtected && modifiers.isPrivate then\n      throwError \"invalid 'protected' constructor in a 'private' inductive datatype\"\n    checkValidCtorModifier ctorModifiers\n    let ctorName := ctor.getIdAt 2\n    let ctorName := declName ++ ctorName\n    let ctorName \u2190 withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName\n    let inferMod := !ctor[3].isNone\n    let (binders, type?) := expandOptDeclSig ctor[4]\n    addDocString' ctorName ctorModifiers.docString?\n    addAuxDeclarationRanges ctorName ctor ctor[2]\n    pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView }\n  let classes \u2190 getOptDerivingClasses decl[5]\n  pure {\n    ref             := decl\n    modifiers       := modifiers\n    shortDeclName   := name\n    declName        := declName\n    levelNames      := levelNames\n    binders         := binders\n    type?           := type?\n    ctors           := ctors\n    derivingClasses := classes\n  }\n\nprivate def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView :=\n  inductiveSyntaxToView modifiers decl\n\ndef elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let v \u2190 inductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\ndef elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do\n  let modifiers := modifiers.addAttribute { name := `class }\n  let v \u2190 classInductiveSyntaxToView modifiers stx\n  elabInductiveViews #[v]\n\ndef getTerminationHints (stx : Syntax) : TerminationHints :=\n  let decl := stx[1]\n  let k := decl.getKind\n  if k == ``Parser.Command.def || k == ``Parser.Command.theorem || k == ``Parser.Command.instance then\n    let args := decl.getArgs\n    { terminationBy? := args[args.size - 2].getOptional?, decreasingBy? := args[args.size - 1].getOptional? }\n  else\n    {}\n\n@[builtinCommandElab declaration]\ndef elabDeclaration : CommandElab := fun stx => do\n  match (\u2190 liftMacroM <| expandDeclNamespace? stx) with\n  | some (ns, newStx) => do\n    let ns := mkIdentFrom stx ns\n    let newStx \u2190 `(namespace $ns:ident $newStx end $ns:ident)\n    withMacroExpansion stx newStx $ elabCommand newStx\n  | none => do\n    let modifiers \u2190 elabModifiers stx[0]\n    let decl     := stx[1]\n    let declKind := decl.getKind\n    if declKind == ``Lean.Parser.Command.\u00abaxiom\u00bb then\n      elabAxiom modifiers decl\n    else if declKind == ``Lean.Parser.Command.\u00abinductive\u00bb then\n      elabInductive modifiers decl\n    else if declKind == ``Lean.Parser.Command.classInductive then\n      elabClassInductive modifiers decl\n    else if declKind == ``Lean.Parser.Command.\u00abstructure\u00bb then\n      elabStructure modifiers decl\n    else if isDefLike decl then\n      elabMutualDef #[stx] (getTerminationHints stx)\n    else\n      throwError \"unexpected declaration\"\n\n/- Return true if all elements of the mutual-block are inductive declarations. -/\nprivate def isMutualInductive (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl     := elem[1]\n    let declKind := decl.getKind\n    declKind == `Lean.Parser.Command.inductive\n\nprivate def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do\n  let views \u2190 elems.mapM fun stx => do\n     let modifiers \u2190 elabModifiers stx[0]\n     inductiveSyntaxToView modifiers stx[1]\n  elabInductiveViews views\n\n/- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/\nprivate def isMutualDef (stx : Syntax) : Bool :=\n  stx[1].getArgs.all fun elem =>\n    let decl := elem[1]\n    isDefLike decl\n\nprivate def isMutualPreambleCommand (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  k == ``Lean.Parser.Command.variable ||\n  k == ``Lean.Parser.Command.universe ||\n  k == ``Lean.Parser.Command.check ||\n  k == ``Lean.Parser.Command.set_option ||\n  k == ``Lean.Parser.Command.open\n\nprivate partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax \u00d7 Array Syntax) :=\n  let rec loop (i : Nat) : Option (Array Syntax \u00d7 Array Syntax) :=\n    if h : i < elems.size then\n      let elem := elems.get \u27e8i, h\u27e9\n      if isMutualPreambleCommand elem then\n        loop (i+1)\n      else if i == 0 then\n        none -- `mutual` block does not contain any preamble commands\n      else\n        some (elems[0:i], elems[i:elems.size])\n    else\n      none -- a `mutual` block containing only preamble commands is not a valid `mutual` block\n  loop 0\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualNamespace : Macro := fun stx => do\n  let mut ns?      := none\n  let mut elemsNew := #[]\n  for elem in stx[1].getArgs do\n    match ns?, (\u2190 expandDeclNamespace? elem) with\n    | _, none                         => elemsNew := elemsNew.push elem\n    | none, some (ns, elem)           => ns? := some ns; elemsNew := elemsNew.push elem\n    | some nsCurr, some (nsNew, elem) =>\n      if nsCurr == nsNew then\n        elemsNew := elemsNew.push elem\n      else\n        Macro.throwErrorAt elem s!\"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration\"\n  match ns? with\n  | some ns =>\n    let ns := mkIdentFrom stx ns\n    let stxNew := stx.setArg 1 (mkNullNode elemsNew)\n    `(namespace $ns:ident $stxNew end $ns:ident)\n  | none => Macro.throwUnsupported\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualElement : Macro := fun stx => do\n  let mut elemsNew := #[]\n  let mut modified := false\n  for elem in stx[1].getArgs do\n    match (\u2190 expandMacro? elem) with\n    | some elemNew => elemsNew := elemsNew.push elemNew; modified := true\n    | none         => elemsNew := elemsNew.push elem\n  if modified then\n    pure $ stx.setArg 1 (mkNullNode elemsNew)\n  else\n    Macro.throwUnsupported\n\n@[builtinMacro Lean.Parser.Command.mutual]\ndef expandMutualPreamble : Macro := fun stx =>\n  match splitMutualPreamble stx[1].getArgs with\n  | none => Macro.throwUnsupported\n  | some (preamble, rest) => do\n    let secCmd    \u2190 `(section)\n    let newMutual := stx.setArg 1 (mkNullNode rest)\n    let endCmd    \u2190 `(end)\n    pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd])\n\n@[builtinCommandElab \u00abmutual\u00bb]\ndef elabMutual : CommandElab := fun stx => do\n  let hints := { terminationBy? := stx[3].getOptional?, decreasingBy? := stx[4].getOptional? }\n  if isMutualInductive stx then\n    if let some bad := hints.terminationBy? then\n      throwErrorAt bad \"invalid 'termination_by' in mutually inductive datatype declaration\"\n    if let some bad := hints.decreasingBy? then\n      throwErrorAt bad \"invalid 'decreasing_by' in mutually inductive datatype declaration\"\n    elabMutualInductive stx[1].getArgs\n  else if isMutualDef stx then\n    for arg in stx[1].getArgs do\n      let argHints := getTerminationHints arg\n      if let some bad := argHints.terminationBy? then\n        throwErrorAt bad \"invalid 'termination_by' in 'mutual' block, it must be used after the 'end' keyword\"\n      if let some bad := argHints.decreasingBy? then\n        throwErrorAt bad \"invalid 'decreasing_by' in 'mutual' block, it must be used after the 'end' keyword\"\n    elabMutualDef stx[1].getArgs hints\n  else\n    throwError \"invalid mutual block\"\n\n/- leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"]\" >> many1 ident -/\n@[builtinCommandElab \u00abattribute\u00bb] def elabAttr : CommandElab := fun stx => do\n  let mut attrInsts := #[]\n  let mut toErase := #[]\n  for attrKindStx in stx[2].getSepArgs do\n    if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then\n      let attrName := attrKindStx[1].getId.eraseMacroScopes\n      unless isAttribute (\u2190 getEnv) attrName do\n        throwError \"unknown attribute [{attrName}]\"\n      toErase := toErase.push attrName\n    else\n      attrInsts := attrInsts.push attrKindStx\n  let attrs \u2190 elabAttrs attrInsts\n  let idents := stx[4].getArgs\n  for ident in idents do withRef ident <| liftTermElabM none do\n    let declName \u2190 resolveGlobalConstNoOverloadWithInfo ident\n    Term.applyAttributes declName attrs\n    for attrName in toErase do\n      Attribute.erase declName attrName\n\ndef expandInitCmd (builtin : Bool) : Macro := fun stx => do\n  let optVisibility := stx[0]\n  let optHeader     := stx[2]\n  let doSeq         := stx[3]\n  let attrId        := mkIdentFrom stx $ if builtin then `builtinInit else `init\n  if optHeader.isNone then\n    unless optVisibility.isNone do\n      Macro.throwError \"invalid initialization command, 'visibility' modifer is not allowed\"\n    `(@[$attrId:ident]def initFn : IO Unit := do $doSeq)\n  else\n    let id   := optHeader[0]\n    let type := optHeader[1][1]\n    if optVisibility.isNone then\n      `(def initFn : IO $type := do $doSeq\n        @[$attrId:ident initFn] constant $id : $type)\n    else if optVisibility[0].getKind == ``Parser.Command.private then\n      `(def initFn : IO $type := do $doSeq\n        @[$attrId:ident initFn] private constant $id : $type)\n    else if optVisibility[0].getKind == ``Parser.Command.protected then\n      `(def initFn : IO $type := do $doSeq\n        @[$attrId:ident initFn] protected constant $id : $type)\n    else\n      Macro.throwError \"unexpected visibility annotation\"\n\n@[builtinMacro Lean.Parser.Command.\u00abinitialize\u00bb] def expandInitialize : Macro :=\n  expandInitCmd (builtin := false)\n\n@[builtinMacro Lean.Parser.Command.\u00abbuiltin_initialize\u00bb] def expandBuiltinInitialize : Macro :=\n  expandInitCmd (builtin := true)\n\nend Lean.Elab.Command\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/Elab/Declaration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508501313237172, "lm_q2_score": 0.0263553506474639, "lm_q1q2_score": 0.006459301459541952}}
{"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.basic\nimport tactic.simpa\n\nsetup_tactic_parser\n\nprivate meta def loc.to_string_aux : option name \u2192 string\n| none := \"\u22a2\"\n| (some x) := to_string x\n\n/-- pretty print a `loc` -/\nmeta def loc.to_string : loc \u2192 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\n/-- shift `pos` `n` columns to the left -/\nmeta def pos.move_left (p : pos) (n : \u2115) : pos :=\n{ line := p.line, column := p.column - n }\n\nnamespace tactic\n\nopen list\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\nmeta def struct_inst : lean.parser pexpr :=\ndo tk \"{\",\n   ls \u2190 sep_by (skip_info (tk \",\"))\n     ( sum.inl <$> (tk \"..\" *> texpr) <|>\n       sum.inr <$> (prod.mk <$> ident <* tk \":=\" <*> texpr)),\n   tk \"}\",\n   let (srcs,fields) := partition_map id ls,\n   let (names,values) := unzip fields,\n   pure $ pexpr.mk_structure_instance\n     { field_names := names,\n       field_values := values,\n       sources := srcs }\n\n/-- pretty print structure instance -/\nmeta def struct.to_tactic_format (e : pexpr) : tactic format :=\ndo r \u2190 e.get_structure_instance_info,\n   fs \u2190 mzip_with (\u03bb n v,\n     do v \u2190 to_expr v >>= pp,\n        pure $ format!\"{n} := {v}\" )\n     r.field_names r.field_values,\n   let ss := r.sources.map (\u03bb s, format!\" .. {s}\"),\n   let x : format := format.join $ list.intersperse \", \" (fs ++ ss),\n   pure format!\" {{{x}}\"\n\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n@[user_attribute]\nprivate meta def squeeze_loc_attr :\n  user_attribute unit (option (list (pos \u00d7 string \u00d7 list simp_arg_type \u00d7 string))) :=\n{ name := `_squeeze_loc,\n  parser := fail \"this attribute should not be used\",\n  descr := \"table to accumulate multiple `squeeze_simp` suggestions\" }\n\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeeze_loc_attr_carrier := ()\n\nrun_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt\n\n/-- Format a list of arguments for use with `simp` and friends. This omits the\nlist entirely if it is empty. -/\nmeta def render_simp_arg_list : list simp_arg_type \u2192 tactic format\n| [] := pure \"\"\n| args := (++) \" \" <$> to_line_wrap_format <$> args.mmap pp\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. -/\nmeta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type)\n  (at_pos := ff) : tactic unit :=\ndo xs \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier,\n   match xs with\n   | none := do\n     args \u2190 render_simp_arg_list args,\n     if at_pos then\n       @scope_trace _ p.line p.column $\n         \u03bb _, _root_.trace sformat!\"{pre}{args}{post}\" (pure () : tactic unit)\n     else\n       trace sformat!\"{pre}{args}{post}\"\n   | some xs := do\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff\n   end\n\nlocal postfix `?`:9001 := optional\n\n/-- translate a `pexpr` into a `simp` configuration -/\nmeta def parse_config : option pexpr \u2192 tactic (simp_config_ext \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr simp_config_ext e\n             <*> struct.to_tactic_format cfg\n\n/-- translate a `pexpr` into a `dsimp` configuration -/\nmeta def parse_dsimp_config : option pexpr \u2192 tactic (dsimp_config \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr dsimp_config e\n             <*> struct.to_tactic_format cfg\n\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\nmeta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool :=\ndo s \u2190 get_proof_state_after tac,\n   pure $ some pr = s\n\nprivate meta def filter_simp_set_aux\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (args : list simp_arg_type) (pr : proof_state) :\n  list simp_arg_type \u2192 list simp_arg_type \u2192\n  list simp_arg_type \u2192 tactic (list simp_arg_type \u00d7 list simp_arg_type)\n| [] ys ds := pure (ys.reverse, ds.reverse)\n| (x :: xs) ys ds :=\n  do b \u2190 same_result pr (tac tt (args ++ xs ++ ys)),\n     if b\n       then filter_simp_set_aux xs ys (x:: ds)\n       else filter_simp_set_aux xs (x :: ys) ds\n\ndeclare_trace squeeze.deleted\n\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-/\nmeta def filter_simp_set\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) :=\ndo some s \u2190 get_proof_state_after (tac ff (user_args ++ simp_args)),\n   (simp_args', _)  \u2190 filter_simp_set_aux tac user_args s simp_args [] [],\n   (user_args', ds) \u2190 filter_simp_set_aux tac simp_args' s user_args [] [],\n   when (is_trace_enabled_for `squeeze.deleted = tt \u2227 \u00ac ds.empty)\n     trace!\"deleting provided arguments {ds}\",\n   pure (user_args' ++ simp_args')\n\n/-- make a `simp_arg_type` that references the name given as an argument -/\nmeta def name.to_simp_args (n : name) : tactic simp_arg_type :=\ndo e \u2190 resolve_name' n, pure $ simp_arg_type.expr e\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\n-/\nmeta def squeeze_simp_core\n  (slow no_dflt : bool) (args : list simp_arg_type)\n  (tac : \u03a0 (no_dflt : bool) (args : list simp_arg_type), tactic unit)\n  (mk_suggestion : list simp_arg_type \u2192 tactic unit) : tactic unit :=\ndo v \u2190 target >>= mk_meta_var,\n   args \u2190 if slow then do\n     simp_set \u2190 attribute.get_instances `simp,\n     simp_set \u2190 simp_set.mfilter $ has_attribute' `_refl_lemma,\n     simp_set \u2190 simp_set.mmap $ resolve_name' >=> pure \u2218 simp_arg_type.expr,\n     pure $ args ++ simp_set\n   else pure args,\n   g \u2190 retrieve $ do\n   { g \u2190 main_goal,\n     tac no_dflt args,\n     instantiate_mvars g },\n   let vs := g.list_constant,\n   vs \u2190 vs.mfilter is_simp_lemma,\n   vs \u2190 vs.mmap strip_prefix,\n   vs \u2190 vs.to_list.mmap name.to_simp_args,\n   with_local_goals' [v] (filter_simp_set tac args vs)\n     >>= mk_suggestion,\n   tac no_dflt args\n\nnamespace interactive\n\nattribute [derive decidable_eq] simp_arg_type\n\n/-- Turn a `simp_arg_type` into a string. -/\nmeta instance simp_arg_type.has_to_string : has_to_string simp_arg_type :=\n\u27e8\u03bb a, match a with\n| simp_arg_type.all_hyps := \"*\"\n| (simp_arg_type.except n) := \"-\" ++ to_string n\n| (simp_arg_type.expr e) := to_string e\n| (simp_arg_type.symm_expr e) := \"\u2190\" ++ to_string e\nend\u27e9\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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (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-/\nmeta def squeeze_scope (tac : itactic) : tactic unit :=\ndo none \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (),\n   squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff,\n   finally tac $ do\n     some xs \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail \"invalid state\",\n     let m := native.rb_lmap.of_list xs,\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff,\n     m.to_list.reverse.mmap' $ \u03bb \u27e8p,suggs\u27e9, do\n       { let \u27e8pre,_,post\u27e9 := suggs.head,\n         let suggs : list (list simp_arg_type) := suggs.map $ prod.fst \u2218 prod.snd,\n         mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () }\n\n/--\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-/\nmeta def squeeze_simp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\n/-- see `squeeze_simp` -/\nmeta def squeeze_simpa\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (tgt : parse (tk \"using\" *> texpr)?)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   tgt' \u2190 traverse (\u03bb t, do t \u2190 to_expr t >>= pp,\n                            pure format!\" using {t}\") tgt,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            tgt' := tgt'.get_or_else \"\" in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simpa{use_iota_eqn} only\"\n          sformat!\"{attrs}{tgt'}{c}\" args)\n\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 -/\nmeta def squeeze_dsimp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?)\n  (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_dsimp_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: dsimp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\nend interactive\nend tactic\n\nopen tactic.interactive\nadd_tactic_doc\n{ name       := \"squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope\",\n  category   := doc_category.tactic,\n  decl_names :=\n   [``squeeze_simp,\n    ``squeeze_dsimp,\n    ``squeeze_simpa,\n    ``squeeze_scope],\n  tags       := [\"simplification\", \"Try this\"],\n  inherit_description_from := ``squeeze_simp }\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/squeeze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19193279569159505, "lm_q2_score": 0.03358950274784212, "lm_q1q2_score": 0.006446927168283853}}
{"text": "/-\nCopyright (c) 2022 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Siddharth Bhat\n-/\n\nimport Lean.Data.HashMap\nimport Lean.Runtime\nimport Lean.Compiler.NameMangling\nimport Lean.Compiler.ExportAttr\nimport Lean.Compiler.InitAttr\nimport Lean.Compiler.IR.CompilerM\nimport Lean.Compiler.IR.EmitUtil\nimport Lean.Compiler.IR.NormIds\nimport Lean.Compiler.IR.SimpCase\nimport Lean.Compiler.IR.Boxing\nimport Lean.Compiler.IR.ResetReuse\nimport Lean.Compiler.IR.LLVMBindings\n\nopen Lean.IR.ExplicitBoxing (isBoxedName)\n\nnamespace Lean.IR\n\ndef leanMainFn := \"_lean_main\"\n\nnamespace LLVM\n-- TODO(bollu): instantiate target triple and find out what size_t is.\ndef size_tType (llvmctx : LLVM.Context) : IO (LLVM.LLVMType llvmctx) :=\n  LLVM.i64Type llvmctx\nend LLVM\n\nnamespace EmitLLVM\n\nstructure Context (llvmctx : LLVM.Context) where\n  env        : Environment\n  modName    : Name\n  jpMap      : JPParamsMap := {}\n  mainFn     : FunId := default\n  mainParams : Array Param := #[]\n  llvmmodule : LLVM.Module llvmctx\n\nstructure State (llvmctx : LLVM.Context) where\n  var2val : HashMap VarId (LLVM.LLVMType llvmctx \u00d7 LLVM.Value llvmctx)\n  jp2bb   : HashMap JoinPointId (LLVM.BasicBlock llvmctx)\n\nabbrev Error := String\n\nabbrev M (llvmctx : LLVM.Context) :=\n  StateRefT (State llvmctx) (ReaderT (Context llvmctx) (ExceptT Error IO))\n\ninstance : Inhabited (M llvmctx \u03b1) where\n  default := throw \"Error: inhabitant\"\n\ndef addVartoState (x : VarId) (v : LLVM.Value llvmctx) (ty : LLVM.LLVMType llvmctx) : M llvmctx Unit := do\n  modify (fun s => { s with var2val := s.var2val.insert x (ty, v) }) -- add new variable\n\ndef addJpTostate (jp : JoinPointId) (bb : LLVM.BasicBlock llvmctx) : M llvmctx Unit :=\n  modify (fun s => { s with jp2bb := s.jp2bb.insert jp bb })\n\ndef emitJp (jp : JoinPointId) : M llvmctx (LLVM.BasicBlock llvmctx) := do\n  let state \u2190 get\n  match state.jp2bb.find? jp with\n  | .some bb => return bb\n  | .none => throw s!\"unable to find join point {jp}\"\n\ndef getLLVMModule : M llvmctx (LLVM.Module llvmctx) := Context.llvmmodule <$> read\n\ndef getEnv : M llvmctx Environment := Context.env <$> read\n\ndef getModName : M llvmctx  Name := Context.modName <$> read\n\ndef getDecl (n : Name) : M llvmctx Decl := do\n  let env \u2190 getEnv\n  match findEnvDecl env n with\n  | some d => pure d\n  | none   => throw s!\"unknown declaration {n}\"\n\ndef constIntUnsigned (n : Nat) : M llvmctx (LLVM.Value llvmctx) :=  do\n    LLVM.constIntUnsigned llvmctx (UInt64.ofNat n)\n\ndef getOrCreateFunctionPrototype (mod : LLVM.Module llvmctx)\n    (retty : LLVM.LLVMType llvmctx) (name : String) (args : Array (LLVM.LLVMType llvmctx)) : M llvmctx  (LLVM.Value llvmctx) := do\n  LLVM.getOrAddFunction mod name $ \u2190 LLVM.functionType retty args (isVarArg := false)\n\ndef callLeanBox (builder : LLVM.Builder llvmctx)\n    (arg : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_box\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[ \u2190 LLVM.size_tType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn  #[arg] name\n\ndef callLeanMarkPersistentFn (builder : LLVM.Builder llvmctx) (arg : LLVM.Value llvmctx) : M llvmctx  Unit := do\n  let fnName :=  \"lean_mark_persistent\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190   LLVM.buildCall2 builder fnty fn  #[arg]\n\n-- `lean_{inc, dec}_{ref?}_{1,n}`\ninductive RefcountKind where\n  | inc | dec\n\ninstance : ToString RefcountKind where\n  toString\n    | .inc => \"inc\"\n    | .dec => \"dec\"\n\ndef callLeanRefcountFn (builder : LLVM.Builder llvmctx)\n    (kind : RefcountKind) (checkRef? : Bool) (arg : LLVM.Value llvmctx)\n    (delta : Option (LLVM.Value llvmctx) := Option.none) : M llvmctx Unit := do\n  let fnName :=  s!\"lean_{kind}{if checkRef? then \"\" else \"_ref\"}{if delta.isNone then \"\" else \"_n\"}\" \n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := if delta.isNone then #[\u2190 LLVM.voidPtrType llvmctx] else #[\u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys \n  match delta with\n  | .none => do\n    -- since refcount \u03b4 is 1, we only supply the pointer.\n    let _ \u2190 LLVM.buildCall2 builder fnty fn #[arg]\n  | .some n => do\n    let _ \u2190 LLVM.buildCall2 builder fnty fn #[arg, n]\n\n-- `decRef1`\n-- Do NOT attempt to merge this code with callLeanRefcountFn, because of the uber confusing\n-- semantics of 'ref?'. If 'ref?' is true, it calls the version that is lean_dec\ndef callLeanDecRef (builder : LLVM.Builder llvmctx) (res : LLVM.Value llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_dec_ref\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.i8PtrType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[res]\n\ndef callLeanUnsignedToNatFn (builder : LLVM.Builder llvmctx)\n    (n : Nat) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let mod \u2190 getLLVMModule\n  let argtys := #[\u2190 LLVM.i32Type llvmctx]\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let f \u2190   getOrCreateFunctionPrototype mod retty \"lean_unsigned_to_nat\"  argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let nv \u2190 LLVM.constInt32 llvmctx (UInt64.ofNat n)\n  LLVM.buildCall2 builder fnty f #[nv] name\n\ndef callLeanMkStringFromBytesFn (builder : LLVM.Builder llvmctx)\n    (strPtr nBytes : LLVM.Value llvmctx) (name : String) : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_mk_string_from_bytes\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys :=  #[\u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.i64Type llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[strPtr, nBytes] name\n\ndef callLeanMkString (builder : LLVM.Builder llvmctx)\n    (strPtr : LLVM.Value llvmctx) (name : String) : M llvmctx (LLVM.Value llvmctx) := do\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys :=  #[\u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190  getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty \"lean_mk_string\" argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[strPtr] name\n\ndef callLeanCStrToNatFn (builder : LLVM.Builder llvmctx)\n    (n : Nat) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_cstr_to_nat\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys :=  #[\u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let s \u2190 LLVM.buildGlobalString builder (value := toString n)\n  LLVM.buildCall2 builder fnty fn #[s] name\n\ndef callLeanIOMkWorld (builder : LLVM.Builder llvmctx) : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_io_mk_world\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys :=  #[]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[] \"mk_io_out\"\n\ndef callLeanIOResultIsError (builder : LLVM.Builder llvmctx)\n    (arg : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_io_result_is_error\"\n  let retty \u2190 LLVM.i1Type llvmctx\n  let argtys :=  #[\u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[arg] name\n\ndef callLeanAllocCtor (builder : LLVM.Builder llvmctx)\n    (tag num_objs scalar_sz : Nat) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_alloc_ctor\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let i32 \u2190 LLVM.i32Type llvmctx\n  let argtys :=  #[i32, i32, i32]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n\n  let tag \u2190 LLVM.constInt32 llvmctx (UInt64.ofNat tag)\n  let num_objs \u2190 LLVM.constInt32 llvmctx (UInt64.ofNat num_objs)\n  let scalar_sz \u2190 LLVM.constInt32 llvmctx (UInt64.ofNat scalar_sz)\n  LLVM.buildCall2 builder fnty fn #[tag, num_objs, scalar_sz] name\n\ndef callLeanCtorSet (builder : LLVM.Builder llvmctx)\n    (o i v : LLVM.Value llvmctx) : M llvmctx Unit := do\n  let fnName := \"lean_ctor_set\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let voidptr \u2190 LLVM.voidPtrType llvmctx\n  let unsigned \u2190 LLVM.size_tType llvmctx\n  let argtys :=  #[voidptr, unsigned, voidptr]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  _ <- LLVM.buildCall2 builder fnty fn  #[o, i, v]\n\ndef callLeanIOResultMKOk (builder : LLVM.Builder llvmctx)\n    (v : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_io_result_mk_ok\"\n  let voidptr \u2190 LLVM.voidPtrType llvmctx\n  let retty := voidptr\n  let argtys :=  #[voidptr]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[v] name\n\ndef callLeanAllocClosureFn (builder : LLVM.Builder llvmctx)\n    (f arity nys : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_alloc_closure\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn  #[f, arity, nys] retName\n\ndef callLeanClosureSetFn (builder : LLVM.Builder llvmctx)\n    (closure ix arg : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx Unit := do\n  let fnName :=  \"lean_closure_set\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx, \u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[closure, ix, arg] retName\n\ndef callLeanObjTag (builder : LLVM.Builder llvmctx)\n    (closure : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_obj_tag\"\n  let retty \u2190 LLVM.i32Type llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let out \u2190 LLVM.buildCall2 builder fnty fn  #[closure] retName\n  LLVM.buildSextOrTrunc builder out (\u2190 LLVM.i64Type llvmctx)\n\ndef callLeanIOResultGetValue (builder : LLVM.Builder llvmctx)\n    (v : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_io_result_get_value\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[v] name\n\ndef callLeanCtorRelease (builder : LLVM.Builder llvmctx)\n    (closure i : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx Unit := do\n  let fnName :=  \"lean_ctor_release\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[closure, i] retName\n\ndef callLeanCtorSetTag (builder : LLVM.Builder llvmctx)\n    (closure i : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx Unit := do\n  let fnName :=  \"lean_ctor_set_tag\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[closure, i] retName\n\ndef toLLVMType (t : IRType) : M llvmctx (LLVM.LLVMType llvmctx) := do\n  match t with\n  | IRType.float      => LLVM.doubleTypeInContext llvmctx\n  | IRType.uint8      => LLVM.intTypeInContext llvmctx 8\n  | IRType.uint16     => LLVM.intTypeInContext llvmctx 16\n  | IRType.uint32     => LLVM.intTypeInContext llvmctx 32\n  | IRType.uint64     => LLVM.intTypeInContext llvmctx 64\n  -- TODO: how to cleanly size_t in LLVM? We can do eg. instantiate the current target and query for size.\n  | IRType.usize      => LLVM.size_tType llvmctx\n  | IRType.object     => do LLVM.pointerType (\u2190 LLVM.i8Type llvmctx)\n  | IRType.tobject    => do LLVM.pointerType (\u2190 LLVM.i8Type llvmctx)\n  | IRType.irrelevant => do LLVM.pointerType (\u2190 LLVM.i8Type llvmctx)\n  | IRType.struct _ _ => panic! \"not implemented yet\"\n  | IRType.union _ _  => panic! \"not implemented yet\"\n\ndef throwInvalidExportName {\u03b1 : Type} (n : Name) : M llvmctx \u03b1 := do\n  throw s!\"invalid export name {n.toString}\"\n\ndef toCName (n : Name) : M llvmctx String := do\n  match getExportNameFor? (\u2190 getEnv) n with\n  | some (.str .anonymous s) => pure s\n  | some _                   => throwInvalidExportName n\n  | none                     => if n == `main then pure leanMainFn else pure n.mangle\n\ndef toCInitName (n : Name) : M llvmctx String := do\n  match getExportNameFor? (\u2190 getEnv) n with\n  | some (.str .anonymous s) => return \"_init_\" ++ s\n  | some _                   => throwInvalidExportName n\n  | none                     => pure (\"_init_\" ++ n.mangle)\n\n/--\n## LLVM Control flow Utilities\n-/\n\n-- Indicates whether the API for building the blocks for then/else should\n-- forward the control flow to the merge block.\ninductive ShouldForwardControlFlow where\n| yes | no\n\n-- Get the function we are currently inserting into.\ndef builderGetInsertionFn (builder : LLVM.Builder llvmctx) : M llvmctx (LLVM.Value llvmctx) := do\n  let builderBB \u2190 LLVM.getInsertBlock builder\n  LLVM.getBasicBlockParent builderBB\n\ndef builderAppendBasicBlock (builder : LLVM.Builder llvmctx) (name : String) : M llvmctx (LLVM.BasicBlock llvmctx) := do\n  let fn \u2190 builderGetInsertionFn builder\n  LLVM.appendBasicBlockInContext llvmctx fn name\n\ndef buildWhile_ (builder : LLVM.Builder llvmctx) (name : String)\n    (condcodegen : LLVM.Builder llvmctx \u2192 M llvmctx (LLVM.Value llvmctx))\n    (bodycodegen : LLVM.Builder llvmctx \u2192 M llvmctx Unit) : M llvmctx Unit := do\n  let fn \u2190 builderGetInsertionFn builder\n\n  let nameHeader := name ++ \"header\"\n  let nameBody := name ++ \"body\"\n  let nameMerge := name ++ \"merge\"\n\n  -- cur \u2192 header\n  let headerbb \u2190 LLVM.appendBasicBlockInContext llvmctx fn nameHeader\n  let _ \u2190 LLVM.buildBr builder headerbb\n\n  let bodybb \u2190 LLVM.appendBasicBlockInContext llvmctx fn nameBody\n  let mergebb \u2190 LLVM.appendBasicBlockInContext llvmctx fn nameMerge\n\n  -- header \u2192 {body, merge}\n  LLVM.positionBuilderAtEnd builder headerbb\n  let cond \u2190 condcodegen builder\n  let _ \u2190 LLVM.buildCondBr builder cond bodybb mergebb\n\n  -- body \u2192 header\n  LLVM.positionBuilderAtEnd builder bodybb\n  bodycodegen builder\n  let _ \u2190 LLVM.buildBr builder headerbb\n\n  -- merge\n  LLVM.positionBuilderAtEnd builder mergebb\n\n-- build an if, and position the builder at the merge basic block after execution.\n-- The '_' denotes that we return Unit on each branch.\ndef buildIfThen_ (builder : LLVM.Builder llvmctx) (name : String) (brval : LLVM.Value llvmctx)\n    (thencodegen : LLVM.Builder llvmctx \u2192 M llvmctx ShouldForwardControlFlow) : M llvmctx Unit := do\n  let fn \u2190 builderGetInsertionFn builder\n\n  let nameThen := name ++ \"Then\"\n  let nameElse := name ++ \"Else\"\n  let nameMerge := name ++ \"Merge\"\n\n  let thenbb \u2190 LLVM.appendBasicBlockInContext llvmctx fn nameThen\n  let elsebb \u2190 LLVM.appendBasicBlockInContext llvmctx fn nameElse\n  let mergebb \u2190 LLVM.appendBasicBlockInContext llvmctx fn nameMerge\n  let _ \u2190 LLVM.buildCondBr builder brval thenbb elsebb\n  -- then\n  LLVM.positionBuilderAtEnd builder thenbb\n  let fwd? \u2190 thencodegen builder\n  match fwd? with\n  | .yes => let _ \u2190 LLVM.buildBr builder mergebb\n  | .no => pure ()\n  -- else\n  LLVM.positionBuilderAtEnd builder elsebb\n  let _ \u2190 LLVM.buildBr builder mergebb\n  -- merge\n  LLVM.positionBuilderAtEnd builder mergebb\n\ndef buildIfThenElse_ (builder : LLVM.Builder llvmctx)  (name : String) (brval : LLVM.Value llvmctx)\n    (thencodegen : LLVM.Builder llvmctx \u2192 M llvmctx ShouldForwardControlFlow)\n    (elsecodegen : LLVM.Builder llvmctx \u2192 M llvmctx ShouldForwardControlFlow) : M llvmctx Unit := do\n  let fn \u2190 LLVM.getBasicBlockParent (\u2190 LLVM.getInsertBlock builder)\n  let thenbb \u2190 LLVM.appendBasicBlockInContext llvmctx fn (name ++ \"Then\")\n  let elsebb \u2190 LLVM.appendBasicBlockInContext llvmctx fn (name ++ \"Else\")\n  let mergebb \u2190 LLVM.appendBasicBlockInContext llvmctx fn (name ++ \"Merge\")\n  let _ \u2190 LLVM.buildCondBr builder brval thenbb elsebb\n  -- then\n  LLVM.positionBuilderAtEnd builder thenbb\n  let fwd? \u2190 thencodegen builder\n  match fwd? with\n  | .yes => let _ \u2190 LLVM.buildBr builder mergebb\n  | .no => pure ()\n  -- else\n  LLVM.positionBuilderAtEnd builder elsebb\n  let fwd? \u2190 elsecodegen builder\n  match fwd? with\n  | .yes => let _ \u2190 LLVM.buildBr builder mergebb\n  | .no => pure ()\n  -- merge\n  LLVM.positionBuilderAtEnd builder mergebb\n\n-- Recall that lean uses `i8` for booleans, not `i1`, so we need to compare with `true`.\ndef buildLeanBoolTrue? (builder : LLVM.Builder llvmctx)\n    (b : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  LLVM.buildICmp builder LLVM.IntPredicate.NE b (\u2190 LLVM.constInt8 llvmctx 0) name\n\ndef emitFnDeclAux (mod : LLVM.Module llvmctx)\n    (decl : Decl) (cppBaseName : String) (isExternal : Bool) : M llvmctx (LLVM.Value llvmctx) := do\n  let ps := decl.params\n  let env \u2190 getEnv\n  -- bollu: if we have a declaration with no parameters, then we emit it as a global pointer.\n  -- bollu: Otherwise, we emit it as a function\n  if ps.isEmpty then\n      let retty \u2190 (toLLVMType decl.resultType)\n      let global \u2190 LLVM.getOrAddGlobal mod cppBaseName retty\n      if !isExternal then\n        LLVM.setInitializer global (\u2190 LLVM.getUndef retty)\n      return global\n  else\n      let retty \u2190 (toLLVMType decl.resultType)\n      let mut argtys := #[]\n      for p in ps do\n        -- if it is extern, then we must not add irrelevant args\n        if !(isExternC env decl.name) || !p.ty.isIrrelevant then\n          argtys := argtys.push (\u2190 toLLVMType p.ty)\n      -- TODO (bollu): simplify this API, this code of `closureMaxArgs` is duplicated in multiple places.\n      if argtys.size > closureMaxArgs && isBoxedName decl.name then\n        argtys := #[\u2190 LLVM.pointerType (\u2190 LLVM.voidPtrType llvmctx)]\n      let fnty \u2190 LLVM.functionType retty argtys (isVarArg := false)\n      LLVM.getOrAddFunction mod cppBaseName fnty\n\ndef emitFnDecl (decl : Decl) (isExternal : Bool) : M llvmctx Unit := do\n  let cppBaseName \u2190 toCName decl.name\n  let _ \u2190 emitFnDeclAux (\u2190 getLLVMModule) decl cppBaseName isExternal\n\ndef emitExternDeclAux (decl : Decl) (cNameStr : String) : M llvmctx Unit := do\n  let env \u2190 getEnv\n  let extC := isExternC env decl.name\n  let _ \u2190 emitFnDeclAux (\u2190 getLLVMModule) decl cNameStr extC\n\ndef emitFnDecls : M llvmctx Unit := do\n  let env \u2190 getEnv\n  let decls := getDecls env\n  let modDecls  : NameSet := decls.foldl (fun s d => s.insert d.name) {}\n  let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {}\n  let usedDecls := usedDecls.toList\n  for n in usedDecls do\n    let decl \u2190 getDecl n\n    match getExternNameFor env `c decl.name with\n    | some cName => emitExternDeclAux decl cName\n    | none       => emitFnDecl decl (!modDecls.contains n)\n  return ()\n\ndef emitLhsSlot_ (x : VarId) : M llvmctx (LLVM.LLVMType llvmctx \u00d7 LLVM.Value llvmctx) := do\n  let state \u2190 get\n  match state.var2val.find? x with\n  | .some v => return v\n  | .none => throw s!\"unable to find variable {x}\"\n\ndef emitLhsVal (builder : LLVM.Builder llvmctx)\n    (x : VarId) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let (xty, xslot) \u2190 emitLhsSlot_ x\n  LLVM.buildLoad2 builder xty xslot name\n\ndef emitLhsSlotStore (builder : LLVM.Builder llvmctx)\n    (x : VarId) (v : LLVM.Value llvmctx) : M llvmctx Unit := do\n  let (_, slot) \u2190 emitLhsSlot_ x\n  LLVM.buildStore builder v slot\n\ndef emitArgSlot_ (builder : LLVM.Builder llvmctx)\n    (x : Arg) : M llvmctx (LLVM.LLVMType llvmctx \u00d7 LLVM.Value llvmctx) := do\n  match x with\n  | Arg.var x => emitLhsSlot_ x\n  | _ => do\n    let slotty \u2190 LLVM.voidPtrType llvmctx\n    let slot \u2190 LLVM.buildAlloca builder slotty \"irrelevant_slot\"\n    let v \u2190 callLeanBox builder (\u2190 LLVM.constIntUnsigned llvmctx 0) \"irrelevant_val\"\n    let _ \u2190 LLVM.buildStore builder v slot\n    return (slotty, slot)\n\ndef emitArgVal (builder : LLVM.Builder llvmctx)\n    (x : Arg) (name : String := \"\") : M llvmctx (LLVM.LLVMType llvmctx \u00d7 LLVM.Value llvmctx) := do\n  let (xty, xslot) \u2190 emitArgSlot_ builder x\n  let xval \u2190 LLVM.buildLoad2 builder xty xslot name\n  return (xty, xval)\n\ndef emitAllocCtor (builder : LLVM.Builder llvmctx)\n    (c : CtorInfo) : M llvmctx (LLVM.Value llvmctx) := do\n  -- TODO(bollu) : find the correct size, don't assume 'void*' size is 8\n  let hackSizeofVoidPtr := 8\n  let scalarSize := hackSizeofVoidPtr * c.usize + c.ssize\n  callLeanAllocCtor builder c.cidx c.size scalarSize \"lean_alloc_ctor_out\"\n\ndef emitCtorSetArgs (builder : LLVM.Builder llvmctx)\n    (z : VarId) (ys : Array Arg) : M llvmctx Unit := do\n  ys.size.forM fun i => do\n    let zv \u2190 emitLhsVal builder z\n    let (_yty, yv) \u2190 emitArgVal builder ys[i]!\n    let iv \u2190 LLVM.constIntUnsigned llvmctx (UInt64.ofNat i)\n    callLeanCtorSet builder zv iv yv\n    emitLhsSlotStore builder z zv\n    pure ()\n\ndef emitCtor (builder : LLVM.Builder llvmctx)\n    (z : VarId) (c : CtorInfo) (ys : Array Arg) : M llvmctx Unit := do\n  let (_llvmty, slot) \u2190 emitLhsSlot_ z\n  if c.size == 0 && c.usize == 0 && c.ssize == 0 then do\n    let v \u2190 callLeanBox builder (\u2190 constIntUnsigned c.cidx) \"lean_box_outv\"\n    let _ \u2190 LLVM.buildStore builder v slot\n  else do\n    let v \u2190 emitAllocCtor builder c\n    let _ \u2190 LLVM.buildStore builder v slot\n    emitCtorSetArgs builder z ys\n\ndef emitInc (builder : LLVM.Builder llvmctx)\n    (x : VarId) (n : Nat) (checkRef? : Bool) : M llvmctx Unit := do\n  let xv \u2190 emitLhsVal builder x\n  if n != 1\n  then do\n     let nv \u2190 LLVM.constIntUnsigned llvmctx (UInt64.ofNat n)\n     callLeanRefcountFn builder (kind := RefcountKind.inc) (checkRef? := checkRef?) (delta := nv) xv\n  else callLeanRefcountFn builder (kind := RefcountKind.inc) (checkRef? := checkRef?) xv\n\ndef emitDec (builder : LLVM.Builder llvmctx)\n    (x : VarId) (n : Nat) (checkRef? : Bool) : M llvmctx Unit := do\n  let xv \u2190 emitLhsVal builder x\n  if n != 1\n  then throw \"expected n = 1 for emitDec\"\n  else callLeanRefcountFn builder (kind := RefcountKind.dec) (checkRef? := checkRef?) xv\n\ndef emitNumLit (builder : LLVM.Builder llvmctx)\n    (t : IRType) (v : Nat) : M llvmctx (LLVM.Value llvmctx) := do\n  if t.isObj then\n    if v < UInt32.size then\n      callLeanUnsignedToNatFn builder v\n    else\n      callLeanCStrToNatFn builder v\n  else\n    LLVM.constInt (\u2190 toLLVMType t) (UInt64.ofNat v)\n\ndef toHexDigit (c : Nat) : String :=\n  String.singleton c.digitChar\n\n-- TODO(bollu) : Setup code sharing between 'EmitC' and 'EmitLLVM'\ndef quoteString (s : String) : String :=\n  let q := \"\\\"\";\n  let q := s.foldl\n    (fun q c => q ++\n      if c == '\\n' then \"\\\\n\"\n      else if c == '\\r' then \"\\\\r\"\n      else if c == '\\t' then \"\\\\t\"\n      else if c == '\\\\' then \"\\\\\\\\\"\n      else if c == '\\\"' then \"\\\\\\\"\"\n      else if c.toNat <= 31 then\n        \"\\\\x\" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16)\n      -- TODO(Leo) : we should use `\\unnnn` for escaping unicode characters.\n      else String.singleton c)\n    q;\n  q ++ \"\\\"\"\n\ndef emitSimpleExternalCall (builder : LLVM.Builder llvmctx)\n    (f : String)\n    (ps : Array Param)\n    (ys : Array Arg)\n    (retty : IRType)\n    (name : String) : M llvmctx (LLVM.Value llvmctx) := do\n  let mut args := #[]\n  let mut argTys := #[]\n  for (p, y) in ps.zip ys do\n    if !p.ty.isIrrelevant then\n      let (_yty, yv) \u2190 emitArgVal builder y \"\"\n      argTys := argTys.push (\u2190 toLLVMType p.ty)\n      args := args.push yv\n  let fnty \u2190 LLVM.functionType (\u2190 toLLVMType retty) argTys\n  let fn \u2190 LLVM.getOrAddFunction (\u2190 getLLVMModule) f fnty\n  LLVM.buildCall2 builder fnty fn args name\n\n-- TODO: if the external call is one that we cannot code generate, give up and\n-- generate fallback code.\ndef emitExternCall (builder : LLVM.Builder llvmctx)\n    (f : FunId)\n    (ps : Array Param)\n    (extData : ExternAttrData)\n    (ys : Array Arg) (retty : IRType)\n    (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) :=\n  match getExternEntryFor extData `c with\n  | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall builder extFn ps ys retty name\n  | some (ExternEntry.inline \"llvm\" _pat) => throw \"Unimplemented codegen of inline LLVM\"\n  | some (ExternEntry.inline _ pat) => throw s!\"Cannot codegen non-LLVM inline code '{pat}'.\"\n  | some (ExternEntry.foreign _ extFn)  => emitSimpleExternalCall builder extFn ps ys retty name\n  | _ => throw s!\"Failed to emit extern application '{f}'.\"\n\ndef getFunIdTy (f : FunId) : M llvmctx (LLVM.LLVMType llvmctx) := do\n  let decl \u2190 getDecl f\n  let retty \u2190 toLLVMType decl.resultType\n  let argtys \u2190 decl.params.mapM (fun p => do toLLVMType p.ty)\n  LLVM.functionType retty argtys\n\n/--\nCreate a function declaration and return a pointer to the function.\nIf the function actually takes arguments, then we must have a function pointer in scope.\nIf the function takes no arguments, then it is a top-level closed term, and its value will\nbe stored in a global pointer. So, we load from the global pointer. The type of the global is function pointer pointer.\nThis returns a *function pointer.*\n-/\ndef getOrAddFunIdValue (builder : LLVM.Builder llvmctx) (f : FunId) : M llvmctx (LLVM.Value llvmctx) := do\n  let decl \u2190 getDecl f\n  let fcname \u2190 toCName f\n  let retty \u2190 toLLVMType decl.resultType\n  if decl.params.isEmpty then\n     let gslot \u2190 LLVM.getOrAddGlobal (\u2190 getLLVMModule) fcname retty\n     LLVM.buildLoad2 builder retty gslot\n  else\n    let argtys \u2190 decl.params.mapM (fun p => do toLLVMType p.ty)\n    let fnty \u2190 LLVM.functionType retty argtys\n    LLVM.getOrAddFunction (\u2190 getLLVMModule) fcname fnty\n\ndef emitPartialApp (builder : LLVM.Builder llvmctx) (z : VarId) (f : FunId) (ys : Array Arg) : M llvmctx Unit := do\n  let decl \u2190 getDecl f\n  let fv \u2190 getOrAddFunIdValue builder f\n  let arity := decl.params.size\n  let (_zty, zslot) \u2190 emitLhsSlot_ z\n  let zval \u2190 callLeanAllocClosureFn builder fv\n                                    (\u2190 constIntUnsigned arity)\n                                    (\u2190 constIntUnsigned ys.size)\n  LLVM.buildStore builder zval zslot\n  ys.size.forM fun i => do\n    let (yty, yslot) \u2190 emitArgSlot_ builder ys[i]!\n    let yval \u2190 LLVM.buildLoad2 builder yty yslot\n    callLeanClosureSetFn builder zval (\u2190 constIntUnsigned i) yval\n\ndef emitApp (builder : LLVM.Builder llvmctx) (z : VarId) (f : VarId) (ys : Array Arg) : M llvmctx Unit := do\n  if ys.size > closureMaxArgs then do\n    let aargs \u2190 LLVM.buildAlloca builder (\u2190 LLVM.arrayType (\u2190 LLVM.voidPtrType llvmctx) (UInt64.ofNat ys.size)) \"aargs\"\n    for i in List.range ys.size do\n      let (yty, yv) \u2190 emitArgVal builder ys[i]!\n      let aslot \u2190 LLVM.buildInBoundsGEP2 builder yty aargs #[\u2190 constIntUnsigned 0, \u2190 constIntUnsigned i] s!\"param_{i}_slot\"\n      LLVM.buildStore builder yv aslot\n    let fnName :=  s!\"lean_apply_m\"\n    let retty \u2190 LLVM.voidPtrType llvmctx\n    let args := #[\u2190 emitLhsVal builder f, \u2190 constIntUnsigned ys.size, aargs]\n    -- '1 + ...'. '1' for the fn and 'args' for the arguments\n    let argtys := #[\u2190 LLVM.voidPtrType llvmctx]\n    let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n    let fnty \u2190 LLVM.functionType retty argtys\n    let zv \u2190 LLVM.buildCall2 builder fnty fn args\n    emitLhsSlotStore builder z zv\n  else do\n\n    let fnName :=  s!\"lean_apply_{ys.size}\"\n    let retty \u2190 LLVM.voidPtrType llvmctx\n    let args : Array (LLVM.Value llvmctx) := #[\u2190 emitLhsVal builder f] ++ (\u2190 ys.mapM (fun y => Prod.snd <$> (emitArgVal builder y)))\n    -- '1 + ...'. '1' for the fn and 'args' for the arguments\n    let argtys := (List.replicate (1 + ys.size) (\u2190 LLVM.voidPtrType llvmctx)).toArray\n    let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n    let fnty \u2190 LLVM.functionType retty argtys\n    let zv \u2190 LLVM.buildCall2 builder fnty fn args\n    emitLhsSlotStore builder z zv\n\ndef emitFullApp (builder : LLVM.Builder llvmctx)\n    (z : VarId) (f : FunId) (ys : Array Arg) : M llvmctx Unit := do\n  let (__zty, zslot) \u2190 emitLhsSlot_ z\n  let decl \u2190 getDecl f\n  match decl with\n  | Decl.extern _ ps retty extData =>\n     let zv \u2190 emitExternCall builder f ps extData ys retty\n     LLVM.buildStore builder zv zslot\n  | Decl.fdecl .. =>\n    if ys.size > 0 then\n        let fv \u2190 getOrAddFunIdValue builder f\n        let ys \u2190  ys.mapM (fun y => do\n            let (yty, yslot) \u2190 emitArgSlot_ builder y\n            let yv \u2190 LLVM.buildLoad2 builder yty yslot\n            return yv)\n        let zv \u2190 LLVM.buildCall2 builder (\u2190 getFunIdTy f) fv ys\n        LLVM.buildStore builder zv zslot\n    else\n       let zv \u2190 getOrAddFunIdValue builder f\n       LLVM.buildStore builder zv zslot\n\n-- Note that this returns a *slot*, just like `emitLhsSlot_`.\ndef emitLit (builder : LLVM.Builder llvmctx)\n    (z : VarId) (t : IRType) (v : LitVal) : M llvmctx (LLVM.Value llvmctx) := do\n  let llvmty \u2190 toLLVMType t\n  let zslot \u2190 LLVM.buildAlloca builder llvmty\n  addVartoState z zslot llvmty\n  let zv \u2190 match v with\n            | LitVal.num v => emitNumLit builder t v\n            | LitVal.str v =>\n                 let zero \u2190 LLVM.constIntUnsigned llvmctx 0\n                 let str_global \u2190 LLVM.buildGlobalString builder v\n                 -- access through the global, into the 0th index of the array\n                 let strPtr \u2190 LLVM.buildInBoundsGEP2 builder\n                                (\u2190 LLVM.opaquePointerTypeInContext llvmctx)\n                                str_global #[zero] \"\"\n                 let nbytes \u2190 LLVM.constIntUnsigned llvmctx (UInt64.ofNat (v.utf8ByteSize))\n                 callLeanMkStringFromBytesFn builder strPtr nbytes \"\"\n  LLVM.buildStore builder zv zslot\n  return zslot\n\ndef callLeanCtorGet (builder : LLVM.Builder llvmctx)\n    (x i : LLVM.Value llvmctx) (retName : String) : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_ctor_get\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.i32Type llvmctx]\n  let fnty \u2190 LLVM.functionType retty argtys\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let i \u2190 LLVM.buildSextOrTrunc builder i (\u2190 LLVM.i32Type llvmctx)\n  LLVM.buildCall2 builder fnty fn  #[x, i] retName\n\ndef emitProj (builder : LLVM.Builder llvmctx) (z : VarId) (i : Nat) (x : VarId) : M llvmctx Unit := do\n  let xval \u2190 emitLhsVal builder x\n  let zval \u2190 callLeanCtorGet builder xval (\u2190 constIntUnsigned i) \"\"\n  emitLhsSlotStore builder z zval\n\ndef callLeanCtorGetUsize (builder : LLVM.Builder llvmctx)\n    (x i : LLVM.Value llvmctx) (retName : String) : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_ctor_get_usize\"\n  let retty \u2190 LLVM.size_tType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fnty \u2190 LLVM.functionType retty argtys\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  LLVM.buildCall2 builder fnty fn  #[x, i] retName\n\ndef emitUProj (builder : LLVM.Builder llvmctx) (z : VarId) (i : Nat) (x : VarId) : M llvmctx Unit := do\n  let xval \u2190 emitLhsVal builder x\n  let zval \u2190 callLeanCtorGetUsize builder xval (\u2190 constIntUnsigned i) \"\"\n  emitLhsSlotStore builder z zval\n\ndef emitOffset (builder : LLVM.Builder llvmctx)\n    (n : Nat) (offset : Nat) : M llvmctx (LLVM.Value llvmctx) := do\n   -- TODO(bollu) : replace 8 with sizeof(void*)\n   let out \u2190 constIntUnsigned 8\n   let out \u2190 LLVM.buildMul builder out (\u2190 constIntUnsigned n) \"\" -- sizeof(void*)*n\n   LLVM.buildAdd builder out (\u2190 constIntUnsigned offset) \"\" -- sizeof(void*)*n+offset\n\ndef emitSProj (builder : LLVM.Builder llvmctx)\n    (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M llvmctx Unit := do\n  let (fnName, retty) \u2190\n    match t with\n    | IRType.float  => pure (\"lean_ctor_get_float\", \u2190 LLVM.doubleTypeInContext llvmctx)\n    | IRType.uint8  => pure (\"lean_ctor_get_uint8\", \u2190 LLVM.i8Type llvmctx)\n    | IRType.uint16 => pure (\"lean_ctor_get_uint16\", \u2190  LLVM.i16Type llvmctx)\n    | IRType.uint32 => pure (\"lean_ctor_get_uint32\", \u2190 LLVM.i32Type llvmctx)\n    | IRType.uint64 => pure (\"lean_ctor_get_uint64\", \u2190 LLVM.i64Type llvmctx)\n    | _             => throw s!\"Invalid type for lean_ctor_get: '{t}'\"\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let xval \u2190 emitLhsVal builder x\n  let offset \u2190 emitOffset builder n offset\n  let fnty \u2190 LLVM.functionType retty argtys\n  let zval \u2190 LLVM.buildCall2 builder fnty fn  #[xval, offset]\n  emitLhsSlotStore builder z zval\n\ndef callLeanIsExclusive (builder : LLVM.Builder llvmctx)\n    (closure : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_is_exclusive\"\n  let retty \u2190 LLVM.i1Type llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let out \u2190 LLVM.buildCall2 builder fnty fn  #[closure] retName\n  LLVM.buildSextOrTrunc builder out (\u2190 LLVM.i8Type llvmctx)\n\ndef callLeanIsScalar (builder : LLVM.Builder llvmctx)\n    (closure : LLVM.Value llvmctx) (retName : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_is_scalar\"\n  let retty \u2190 LLVM.i8Type llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn  #[closure] retName\n\ndef emitIsShared (builder : LLVM.Builder llvmctx) (z : VarId) (x : VarId) : M llvmctx Unit := do\n    let xv \u2190 emitLhsVal builder x\n    let exclusive? \u2190 callLeanIsExclusive builder xv\n    let exclusive? \u2190 LLVM.buildSextOrTrunc builder exclusive? (\u2190 LLVM.i1Type llvmctx)\n    let shared? \u2190 LLVM.buildNot builder exclusive?\n    let shared? \u2190 LLVM.buildSext builder shared? (\u2190 LLVM.i8Type llvmctx)\n    emitLhsSlotStore builder z shared?\n\ndef emitBox (builder : LLVM.Builder llvmctx) (z : VarId) (x : VarId) (xType : IRType) : M llvmctx Unit := do\n  let xv \u2190 emitLhsVal builder x\n  let (fnName, argTy, xv) \u2190\n    match xType with\n    | IRType.usize  => pure (\"lean_box_usize\", \u2190 LLVM.size_tType llvmctx, xv)\n    | IRType.uint32 => pure (\"lean_box_uint32\", \u2190 LLVM.i32Type llvmctx, xv)\n    | IRType.uint64 => pure (\"lean_box_uint64\", \u2190 LLVM.size_tType llvmctx, xv)\n    | IRType.float  => pure (\"lean_box_float\", \u2190 LLVM.doubleTypeInContext llvmctx, xv)\n    | _             => do\n         -- sign extend smaller values into i64\n         let xv \u2190 LLVM.buildSext builder xv (\u2190 LLVM.size_tType llvmctx)\n         pure (\"lean_box\", \u2190 LLVM.size_tType llvmctx, xv)\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[argTy]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let zv \u2190 LLVM.buildCall2 builder fnty fn  #[xv]\n  emitLhsSlotStore builder z zv\n\ndef IRType.isIntegerType (t : IRType) : Bool :=\n  match t with\n  | .uint8 => true\n  | .uint16 => true\n  | .uint32 => true\n  | .uint64 => true\n  | .usize => true\n  | _ => false\n\ndef callUnboxForType (builder : LLVM.Builder llvmctx)\n    (t : IRType)\n    (v : LLVM.Value llvmctx)\n    (retName : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let (fnName, retty) \u2190\n     match t with\n     | IRType.usize  => pure (\"lean_unbox_usize\", \u2190 toLLVMType t)\n     | IRType.uint32 => pure (\"lean_unbox_uint32\", \u2190 toLLVMType t)\n     | IRType.uint64 => pure (\"lean_unbox_uint64\", \u2190 toLLVMType t)\n     | IRType.float  => pure (\"lean_unbox_float\", \u2190 toLLVMType t)\n     | _             => pure (\"lean_unbox\", \u2190 LLVM.size_tType llvmctx)\n  let argtys := #[\u2190 LLVM.voidPtrType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[v] retName\n\n\n\ndef emitUnbox (builder : LLVM.Builder llvmctx)\n    (z : VarId) (t : IRType) (x : VarId) (retName : String := \"\") : M llvmctx Unit := do\n  let zval \u2190 callUnboxForType builder t (\u2190 emitLhsVal builder x) retName\n  -- NOTE(bollu) : note that lean_unbox only returns an i64, but we may need to truncate to\n  -- smaller widths. see `phashmap` for an example of this occurring at calls to `lean_unbox`\n  let zval \u2190\n    if IRType.isIntegerType t\n    then LLVM.buildSextOrTrunc builder zval (\u2190 toLLVMType t)\n    else pure zval\n  emitLhsSlotStore builder z zval\n\ndef emitReset (builder : LLVM.Builder llvmctx) (z : VarId) (n : Nat) (x : VarId) : M llvmctx Unit := do\n  let xv \u2190 emitLhsVal builder x\n  let isExclusive \u2190 callLeanIsExclusive builder xv\n  let isExclusive \u2190 buildLeanBoolTrue? builder isExclusive\n  buildIfThenElse_ builder \"isExclusive\" isExclusive\n   (fun builder => do\n     let xv \u2190 emitLhsVal builder x\n     n.forM fun i => do\n         callLeanCtorRelease builder xv (\u2190 constIntUnsigned i)\n     emitLhsSlotStore builder z xv\n     return ShouldForwardControlFlow.yes\n   )\n   (fun builder => do\n      let xv \u2190 emitLhsVal builder x\n      callLeanDecRef builder xv\n      let box0 \u2190 callLeanBox builder (\u2190 constIntUnsigned 0) \"box0\"\n      emitLhsSlotStore builder z box0\n      return ShouldForwardControlFlow.yes\n   )\n\ndef emitReuse (builder : LLVM.Builder llvmctx)\n    (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M llvmctx Unit := do\n  let xv \u2190 emitLhsVal builder x\n  let isScalar \u2190 callLeanIsScalar builder xv\n  let isScalar \u2190 buildLeanBoolTrue? builder isScalar\n  buildIfThenElse_ builder  \"isScalar\" isScalar\n    (fun builder => do\n      let cv \u2190 emitAllocCtor builder c\n      emitLhsSlotStore builder z cv\n      return ShouldForwardControlFlow.yes\n   )\n   (fun builder => do\n       let xv \u2190 emitLhsVal builder x\n       emitLhsSlotStore builder z xv\n       if updtHeader then\n          let zv \u2190 emitLhsVal builder z\n          callLeanCtorSetTag builder zv (\u2190 constIntUnsigned c.cidx)\n       return ShouldForwardControlFlow.yes\n   )\n  emitCtorSetArgs builder z ys\n\ndef emitVDecl (builder : LLVM.Builder llvmctx) (z : VarId) (t : IRType) (v : Expr) : M llvmctx Unit := do\n  match v with\n  | Expr.ctor c ys      => emitCtor builder z c ys\n  | Expr.reset n x      => emitReset builder z n x\n  | Expr.reuse x c u ys => emitReuse builder z x c u ys\n  | Expr.proj i x       => emitProj builder z i x\n  | Expr.uproj i x      => emitUProj builder z i x\n  | Expr.sproj n o x    => emitSProj builder z t n o x\n  | Expr.fap c ys       => emitFullApp builder z c ys\n  | Expr.pap c ys       => emitPartialApp builder z c ys\n  | Expr.ap x ys        => emitApp builder z x ys\n  | Expr.box t x        => emitBox builder z x t\n  | Expr.unbox x        => emitUnbox builder z t x\n  | Expr.isShared x     => emitIsShared builder z x\n  | Expr.lit v          => let _ \u2190 emitLit builder z t v\n\ndef declareVar (builder : LLVM.Builder llvmctx) (x : VarId) (t : IRType) : M llvmctx Unit := do\n  let llvmty \u2190 toLLVMType t\n  let alloca \u2190 LLVM.buildAlloca builder llvmty \"varx\"\n  addVartoState x alloca llvmty\n\npartial def declareVars (builder : LLVM.Builder llvmctx) (f : FnBody) : M llvmctx Unit := do\n  match f with\n  | FnBody.vdecl x t _ b => do\n      declareVar builder x t\n      declareVars builder b\n  | FnBody.jdecl _ xs _ b => do\n      for param in xs do declareVar builder param.x param.ty\n      declareVars builder b\n  | e => do\n      if e.isTerminal then pure () else declareVars builder e.body\n\ndef emitTag (builder : LLVM.Builder llvmctx) (x : VarId) (xType : IRType) : M llvmctx (LLVM.Value llvmctx) := do\n  if xType.isObj then do\n    let xval \u2190 emitLhsVal builder x\n    callLeanObjTag builder xval\n  else if xType.isScalar then do\n    emitLhsVal builder x\n  else\n    throw \"Do not know how to `emitTag` in general.\"\n\ndef emitSet (builder : LLVM.Builder llvmctx) (x : VarId) (i : Nat) (y : Arg) : M llvmctx Unit := do\n  let fnName :=  \"lean_ctor_set\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx, \u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[\u2190 emitLhsVal builder x, \u2190 constIntUnsigned i, (\u2190 emitArgVal builder y).2]\n\ndef emitUSet (builder : LLVM.Builder llvmctx) (x : VarId) (i : Nat) (y : VarId) : M llvmctx Unit := do\n  let fnName :=  \"lean_ctor_set_usize\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[\u2190 emitLhsVal builder x, \u2190 constIntUnsigned i, (\u2190 emitLhsVal builder y)]\n\ndef emitTailCall (builder : LLVM.Builder llvmctx) (f : FunId) (v : Expr) : M llvmctx Unit := do\n   match v with\n  | Expr.fap _ ys => do\n    let llvmctx \u2190 read\n    let ps := llvmctx.mainParams\n    unless ps.size == ys.size do throw s!\"Invalid tail call. f:'{f}' v:'{v}'\"\n    let args \u2190 ys.mapM (fun y => Prod.snd <$> emitArgVal builder y)\n    let fn \u2190 builderGetInsertionFn builder\n    let call \u2190 LLVM.buildCall2 builder (\u2190 getFunIdTy f) fn args\n    -- TODO (bollu) : add 'musttail' attribute using the C API.\n    LLVM.setTailCall call true -- mark as tail call\n    let _ \u2190 LLVM.buildRet builder call\n  | _ => throw s!\"EmitTailCall expects function application, found '{v}'\"\n\ndef emitJmp (builder : LLVM.Builder llvmctx) (jp : JoinPointId) (xs : Array Arg) : M llvmctx Unit := do\n let llvmctx \u2190 read\n  let ps \u2190 match llvmctx.jpMap.find? jp with\n  | some ps => pure ps\n  | none    => throw s!\"Unknown join point {jp}\"\n  unless xs.size == ps.size do throw s!\"Invalid goto, mismatched sizes between arguments, formal parameters.\"\n  for (p, x)  in ps.zip xs do\n    let (_xty, xv) \u2190 emitArgVal builder x\n    emitLhsSlotStore builder p.x xv\n  let _ \u2190 LLVM.buildBr builder (\u2190 emitJp jp)\n\ndef emitSSet (builder : LLVM.Builder llvmctx) (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M llvmctx Unit := do\n  let (fnName, setty) \u2190\n  match t with\n  | IRType.float  => pure (\"lean_ctor_set_float\", \u2190 LLVM.doubleTypeInContext llvmctx)\n  | IRType.uint8  => pure (\"lean_ctor_set_uint8\", \u2190 LLVM.i8Type llvmctx)\n  | IRType.uint16 => pure (\"lean_ctor_set_uint16\", \u2190 LLVM.i16Type llvmctx)\n  | IRType.uint32 => pure (\"lean_ctor_set_uint32\", \u2190 LLVM.i32Type llvmctx)\n  | IRType.uint64 => pure (\"lean_ctor_set_uint64\", \u2190 LLVM.i64Type llvmctx)\n  | _             => throw s!\"invalid type for 'lean_ctor_set': '{t}'\"\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx, setty]\n  let retty  \u2190 LLVM.voidType llvmctx\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let xv \u2190 emitLhsVal builder x\n  let offset \u2190 emitOffset builder n offset\n  let yv \u2190 emitLhsVal builder y\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[xv, offset, yv]\n\ndef emitDel (builder : LLVM.Builder llvmctx) (x : VarId) : M llvmctx Unit := do\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx]\n  let retty  \u2190 LLVM.voidType llvmctx\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty \"lean_free_object\" argtys\n  let xv \u2190 emitLhsVal builder x\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[xv]\n\ndef emitSetTag (builder : LLVM.Builder llvmctx) (x : VarId) (i : Nat) : M llvmctx Unit := do\n  let argtys := #[\u2190 LLVM.voidPtrType llvmctx, \u2190 LLVM.size_tType llvmctx]\n  let retty  \u2190 LLVM.voidType llvmctx\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty \"lean_ctor_set_tag\" argtys\n  let xv \u2190 emitLhsVal builder x\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn  #[xv, \u2190 constIntUnsigned i]\n\ndef ensureHasDefault' (alts : Array Alt) : Array Alt :=\n  if alts.any Alt.isDefault then alts\n  else\n    let last := alts.back\n    let alts := alts.pop\n    alts.push (Alt.default last.body)\n\nmutual\npartial def emitCase (builder : LLVM.Builder llvmctx)\n    (x : VarId) (xType : IRType) (alts : Array Alt) : M llvmctx Unit := do\n  let oldBB \u2190 LLVM.getInsertBlock builder\n  -- NOTE: In this context, 'Zext' versus 'Sext' have a meaninful semantic difference.\n  --       We perform a zero extend so that one-bit tags of `0/-1` actually extend to `0/1`\n  --       in 64-bit space.\n  let tag \u2190 emitTag builder x xType\n  let tag \u2190 LLVM.buildZext builder tag (\u2190 LLVM.i64Type llvmctx)\n  let alts := ensureHasDefault' alts\n  let defaultBB \u2190 builderAppendBasicBlock builder s!\"case_{xType}_default\"\n  let numCasesHint := alts.size\n  let switch \u2190 LLVM.buildSwitch builder tag defaultBB (UInt64.ofNat numCasesHint)\n  alts.forM fun alt => do\n    match alt with\n    | Alt.ctor c b  =>\n       let destbb \u2190 builderAppendBasicBlock builder s!\"case_{xType}_{c.name}_{c.cidx}\"\n       LLVM.addCase switch (\u2190 constIntUnsigned c.cidx) destbb\n       LLVM.positionBuilderAtEnd builder destbb\n       emitFnBody builder b\n    | Alt.default b =>\n       LLVM.positionBuilderAtEnd builder defaultBB\n       emitFnBody builder b\n  LLVM.clearInsertionPosition builder\n  LLVM.positionBuilderAtEnd builder oldBB -- reset state to previous insertion point.\n\n-- NOTE:  emitJP promises to keep the builder context untouched.\npartial def emitJDecl (builder : LLVM.Builder llvmctx)\n    (jp : JoinPointId) (_ps : Array Param) (b : FnBody) : M llvmctx Unit := do\n  let oldBB \u2190 LLVM.getInsertBlock builder\n  let jpbb \u2190 builderAppendBasicBlock builder s!\"jp_{jp.idx}\"\n  addJpTostate jp jpbb\n  LLVM.positionBuilderAtEnd builder jpbb\n  -- NOTE(bollu) : Note that we declare the slots for the variables that are inside\n  --              the join point body before emitting the join point body.\n  --              This ensures reachability via dominance.\n  -- TODO(bollu) : Eliminate the need entirely for 'alloca'/slots by generating SSA phi nodes\n  --              directly as discussed with digamma(Mario Carneiro <di.gama@gmail.com>)\n  declareVars builder b\n  emitBlock builder b\n  LLVM.positionBuilderAtEnd builder oldBB -- reset state\n\npartial def emitUnreachable (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[]\n  let fn \u2190 getOrCreateFunctionPrototype  (\u2190 getLLVMModule) retty \"lean_internal_panic_unreachable\" argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn #[]\n  let _ \u2190 LLVM.buildUnreachable builder\n\npartial def emitBlock (builder : LLVM.Builder llvmctx) (b : FnBody) : M llvmctx Unit := do\n  match b with\n  | FnBody.jdecl j xs  v b      =>\n       emitJDecl builder j xs v\n       emitBlock builder b\n  | d@(FnBody.vdecl x t v b)   => do\n    let llvmctx \u2190 read\n    if isTailCallTo llvmctx.mainFn d then\n      emitTailCall builder llvmctx.mainFn v\n    else\n      emitVDecl builder x t v\n      emitBlock builder b\n  | FnBody.inc x n c p b       =>\n    unless p do emitInc builder x n c\n    emitBlock builder b\n  | FnBody.dec x n c p b       =>\n    unless p do emitDec builder x n c\n    emitBlock builder b\n  | FnBody.del x b             =>  emitDel builder x; emitBlock builder b\n  | FnBody.setTag x i b        =>  emitSetTag builder x i; emitBlock builder b\n  | FnBody.set x i y b         => emitSet builder x i y; emitBlock builder b\n  | FnBody.uset x i y b        => emitUSet builder x i y; emitBlock builder b\n  | FnBody.sset x i o y t b    => emitSSet builder x i o y t; emitBlock builder b\n  | FnBody.mdata _ b           => emitBlock builder b\n  | FnBody.ret x               => do\n      let (_xty, xv) \u2190 emitArgVal builder x \"ret_val\"\n      let _ \u2190 LLVM.buildRet builder xv\n  | FnBody.case _ x xType alts =>\n     emitCase builder x xType alts\n  | FnBody.jmp j xs            =>\n     emitJmp builder j xs\n  | FnBody.unreachable         => emitUnreachable builder\n\npartial def emitFnBody  (builder : LLVM.Builder llvmctx)  (b : FnBody) : M llvmctx Unit := do\n  declareVars builder b\n  emitBlock builder b\n\nend\n\ndef emitFnArgs (builder : LLVM.Builder llvmctx)\n    (needsPackedArgs? : Bool)  (llvmfn : LLVM.Value llvmctx) (params : Array Param) : M llvmctx Unit := do\n  if needsPackedArgs? then do\n      let argsp \u2190 LLVM.getParam llvmfn 0 -- lean_object **args\n      for i in List.range params.size do\n          let param := params[i]!\n          -- argsi := (args + i)\n          let argsi \u2190 LLVM.buildGEP2 builder (\u2190 LLVM.voidPtrType llvmctx) argsp #[\u2190 constIntUnsigned i] s!\"packed_arg_{i}_slot\"\n          let llvmty \u2190 toLLVMType param.ty\n          -- pv := *(argsi) = *(args + i)\n          let pv \u2190 LLVM.buildLoad2 builder llvmty argsi\n          -- slot for arg[i] which is always void* ? \n          let alloca \u2190 LLVM.buildAlloca builder llvmty s!\"arg_{i}\"\n          LLVM.buildStore builder pv alloca\n          addVartoState params[i]!.x alloca llvmty\n  else\n      let n := LLVM.countParams llvmfn\n      for i in (List.range n.toNat) do\n        let llvmty \u2190 toLLVMType params[i]!.ty\n        let alloca \u2190 LLVM.buildAlloca builder  llvmty s!\"arg_{i}\"\n        let arg \u2190 LLVM.getParam llvmfn (UInt64.ofNat i)\n        let _ \u2190 LLVM.buildStore builder arg alloca\n        addVartoState params[i]!.x alloca llvmty\n\ndef emitDeclAux (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) (d : Decl) : M llvmctx Unit := do\n  let env \u2190 getEnv\n  let (_, jpMap) := mkVarJPMaps d\n  withReader (fun llvmctx => { llvmctx with jpMap := jpMap }) do\n  unless hasInitAttr env d.name do\n    match d with\n    | .fdecl (f := f) (xs := xs) (type := t) (body := b) .. =>\n      let baseName \u2190 toCName f\n      let name := if xs.size > 0 then baseName else \"_init_\" ++ baseName\n      let retty \u2190 toLLVMType t\n      let mut argtys := #[]\n      let needsPackedArgs? := xs.size > closureMaxArgs && isBoxedName d.name\n      if needsPackedArgs? then\n          argtys := #[\u2190 LLVM.pointerType (\u2190 LLVM.voidPtrType llvmctx)]\n      else\n        for x in xs do\n          argtys := argtys.push (\u2190 toLLVMType x.ty)\n      let fnty \u2190 LLVM.functionType retty argtys (isVarArg := false)\n      let llvmfn \u2190 LLVM.getOrAddFunction mod name fnty\n      withReader (fun llvmctx => { llvmctx with mainFn := f, mainParams := xs }) do\n        set { var2val := default, jp2bb := default : EmitLLVM.State llvmctx } -- flush variable map\n        let bb \u2190 LLVM.appendBasicBlockInContext llvmctx llvmfn \"entry\"\n        LLVM.positionBuilderAtEnd builder bb\n        emitFnArgs builder needsPackedArgs? llvmfn xs\n        emitFnBody builder b\n      pure ()\n    | _ => pure ()\n\ndef emitDecl (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) (d : Decl) : M llvmctx Unit := do\n  let d := d.normalizeIds -- ensure we don't have gaps in the variable indices\n  try\n    emitDeclAux mod builder d\n    return ()\n  catch err =>\n    throw (s!\"emitDecl:\\ncompiling:\\n{d}\\nerr:\\n{err}\\n\")\n\ndef emitFns (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let env \u2190 getEnv\n  let decls := getDecls env\n  decls.reverse.forM (emitDecl mod builder)\n\ndef callIODeclInitFn (builder : LLVM.Builder llvmctx) \n    (initFnName : String)\n    (world : LLVM.Value llvmctx): M llvmctx (LLVM.Value llvmctx) := do\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[\u2190 LLVM.voidPtrType llvmctx]\n  let fn \u2190 getOrCreateFunctionPrototype  (\u2190 getLLVMModule) retty initFnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[world]\n\ndef callPureDeclInitFn (builder : LLVM.Builder llvmctx)\n    (initFnName : String)\n    (retty : LLVM.LLVMType llvmctx): M llvmctx (LLVM.Value llvmctx) := do\n  let argtys := #[]\n  let fn \u2190 getOrCreateFunctionPrototype  (\u2190 getLLVMModule) retty initFnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[]\n\ndef emitDeclInit (builder : LLVM.Builder llvmctx)\n    (parentFn : LLVM.Value llvmctx) (d : Decl) : M llvmctx Unit := do\n  let env \u2190 getEnv\n  if isIOUnitInitFn env d.name then do\n    let world \u2190 callLeanIOMkWorld builder\n    let resv \u2190 callIODeclInitFn builder (\u2190 toCName d.name) world \n    let err? \u2190 callLeanIOResultIsError builder resv \"is_error\"\n    buildIfThen_ builder s!\"init_{d.name}_isError\" err?\n      (fun builder => do\n        let _ \u2190 LLVM.buildRet builder resv\n        pure ShouldForwardControlFlow.no)\n    -- TODO (bollu) : emit lean_dec_ref. For now, it does not matter.\n  else if d.params.size == 0 then\n    match getInitFnNameFor? env d.name with\n    | some initFn =>\n      let llvmty \u2190 toLLVMType d.resultType\n      let dslot \u2190  LLVM.getOrAddGlobal (\u2190 getLLVMModule) (\u2190 toCName d.name) llvmty\n      LLVM.setInitializer dslot (\u2190 LLVM.getUndef llvmty)\n      let initBB \u2190 builderAppendBasicBlock builder s!\"do_{d.name}_init\"\n      let restBB \u2190 builderAppendBasicBlock builder s!\"post_{d.name}_init\"\n      let checkBuiltin? := getBuiltinInitFnNameFor? env d.name |>.isSome\n      if checkBuiltin? then\n        -- `builtin` is set to true if the initializer is part of the executable,\n        -- and not loaded dynamically.\n        let builtinParam \u2190 LLVM.getParam parentFn 0 \n        let cond \u2190 buildLeanBoolTrue? builder builtinParam \"is_builtin_true\"\n        let _ \u2190 LLVM.buildCondBr builder cond initBB restBB\n       else\n        let _ \u2190 LLVM.buildBr builder initBB\n      LLVM.positionBuilderAtEnd builder initBB\n      let world \u2190 callLeanIOMkWorld builder\n      let resv \u2190 callIODeclInitFn builder (\u2190 toCName initFn) world\n      let err? \u2190 callLeanIOResultIsError builder resv s!\"{d.name}_is_error\"\n      buildIfThen_ builder s!\"init_{d.name}_isError\" err?\n        (fun builder => do\n          let _ \u2190 LLVM.buildRet builder resv\n          pure ShouldForwardControlFlow.no)\n      if d.resultType.isScalar then\n        let dval \u2190 callLeanIOResultGetValue builder resv s!\"{d.name}_res\"\n        let dval \u2190 callUnboxForType builder d.resultType dval\n        LLVM.buildStore builder dval dslot\n      else\n         let dval \u2190 callLeanIOResultGetValue builder resv s!\"{d.name}_res\"\n         LLVM.buildStore builder dval dslot\n         callLeanMarkPersistentFn builder dval\n      let _ \u2190 LLVM.buildBr builder restBB\n      LLVM.positionBuilderAtEnd builder restBB\n    | none => do \n      let llvmty \u2190 toLLVMType d.resultType\n      let dslot \u2190  LLVM.getOrAddGlobal (\u2190 getLLVMModule) (\u2190 toCName d.name) llvmty\n      LLVM.setInitializer dslot (\u2190 LLVM.getUndef llvmty)\n      let dval \u2190 callPureDeclInitFn builder (\u2190 toCInitName d.name) (\u2190 toLLVMType d.resultType)\n      LLVM.buildStore builder dval dslot\n      if d.resultType.isObj then\n         callLeanMarkPersistentFn builder dval\n\ndef callModInitFn (builder : LLVM.Builder llvmctx)\n    (modName : Name) (input world : LLVM.Value llvmctx) (retName : String): M llvmctx (LLVM.Value llvmctx) := do\n  let fnName := mkModuleInitializationFunctionName modName\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[ (\u2190 LLVM.i8Type llvmctx), (\u2190 LLVM.voidPtrType llvmctx)]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[input, world] retName\n\ndef emitInitFn (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let env \u2190 getEnv\n  let modName \u2190 getModName\n\n  let initFnTy \u2190 LLVM.functionType (\u2190 LLVM.voidPtrType llvmctx) #[ (\u2190 LLVM.i8Type llvmctx), (\u2190 LLVM.voidPtrType llvmctx)] (isVarArg := false)\n  let initFn \u2190 LLVM.getOrAddFunction mod (mkModuleInitializationFunctionName modName) initFnTy\n  let entryBB \u2190 LLVM.appendBasicBlockInContext llvmctx initFn \"entry\"\n  LLVM.positionBuilderAtEnd builder entryBB\n  let ginit?ty := \u2190 LLVM.i1Type llvmctx\n  let ginit?slot \u2190 LLVM.getOrAddGlobal mod (modName.mangle ++ \"_G_initialized\") ginit?ty\n  LLVM.setInitializer ginit?slot (\u2190 LLVM.constFalse llvmctx)\n  let ginit?v \u2190 LLVM.buildLoad2 builder ginit?ty ginit?slot \"init_v\"\n  buildIfThen_ builder \"isGInitialized\" ginit?v\n    (fun builder => do\n      let box0 \u2190 callLeanBox builder (\u2190 LLVM.constIntUnsigned llvmctx 0) \"box0\"\n      let out \u2190 callLeanIOResultMKOk builder box0 \"retval\"\n      let _ \u2190 LLVM.buildRet builder out\n      pure ShouldForwardControlFlow.no)\n  LLVM.buildStore builder (\u2190 LLVM.constTrue llvmctx) ginit?slot\n\n  env.imports.forM fun import_ => do\n    let builtin \u2190 LLVM.getParam initFn 0\n    let world \u2190 callLeanIOMkWorld builder\n    let res \u2190 callModInitFn builder import_.module builtin world (\"res_\" ++ import_.module.mangle)\n    let err? \u2190 callLeanIOResultIsError builder res (\"res_is_error_\"  ++ import_.module.mangle)\n    buildIfThen_ builder (\"IsError\" ++ import_.module.mangle) err?\n      (fun builder => do\n        let _ \u2190 LLVM.buildRet builder res\n        pure ShouldForwardControlFlow.no)\n    callLeanDecRef builder res\n  let decls := getDecls env\n  decls.reverse.forM (emitDeclInit builder initFn)\n  let box0 \u2190 callLeanBox builder (\u2190 LLVM.constIntUnsigned llvmctx 0) \"box0\"\n  let out \u2190 callLeanIOResultMKOk builder box0 \"retval\"\n  let _ \u2190 LLVM.buildRet builder out\n\ndef callLeanInitialize (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_initialize\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[]\n  let fnty \u2190 LLVM.functionType retty argtys\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn #[]\n\ndef callLeanInitializeRuntimeModule (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_initialize_runtime_module\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[]\n  let fnty \u2190 LLVM.functionType retty argtys\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn #[]\n\ndef callLeanSetPanicMessages (builder : LLVM.Builder llvmctx)\n    (enable? : LLVM.Value llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_set_panic_messages\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.i1Type llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn #[enable?] \n\ndef callLeanIOMarkEndInitialization (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_io_mark_end_initialization\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn #[]\n\ndef callLeanIOResultIsOk (builder : LLVM.Builder llvmctx)\n    (arg : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_io_result_is_ok\"\n  let retty \u2190 LLVM.i1Type llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn #[arg] name\n\ndef callLeanInitTaskManager (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_init_task_manager\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n   let _ \u2190 LLVM.buildCall2 builder fnty fn #[]\n\ndef callLeanFinalizeTaskManager (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let fnName :=  \"lean_finalize_task_manager\"\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let argtys := #[]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n   let _ \u2190 LLVM.buildCall2 builder fnty fn #[]\n\ndef callLeanUnboxUint32 (builder : LLVM.Builder llvmctx)\n    (v : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx (LLVM.Value llvmctx) := do\n  let fnName :=  \"lean_unbox_uint32\"\n  let retty \u2190 LLVM.i32Type llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  LLVM.buildCall2 builder fnty fn  #[v] name\n\ndef callLeanIOResultShowError (builder : LLVM.Builder llvmctx)\n    (v : LLVM.Value llvmctx) (name : String := \"\") : M llvmctx Unit := do\n  let fnName :=  \"lean_io_result_show_error\"\n  let retty \u2190 LLVM.voidType llvmctx\n  let argtys := #[ \u2190 LLVM.voidPtrType llvmctx ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty fnName argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let _ \u2190 LLVM.buildCall2 builder fnty fn #[v] name\n\ndef callLeanMainFn (builder : LLVM.Builder llvmctx) \n    (argv? : Option (LLVM.Value llvmctx))\n    (world : LLVM.Value llvmctx)\n    (name : String) : M llvmctx (LLVM.Value llvmctx) := do\n  let retty \u2190 LLVM.voidPtrType llvmctx\n  let voidptr \u2190 LLVM.voidPtrType llvmctx\n  let argtys := if argv?.isSome then #[ voidptr, voidptr ] else #[ voidptr ]\n  let fn \u2190 getOrCreateFunctionPrototype (\u2190 getLLVMModule) retty leanMainFn argtys\n  let fnty \u2190 LLVM.functionType retty argtys\n  let args := match argv? with \n              | .some argv => #[argv, world]\n              | .none => #[world]\n  LLVM.buildCall2 builder fnty fn args name\n\ndef emitMainFn (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  let d \u2190 getDecl `main\n  let xs \u2190 match d with\n   | .fdecl (xs := xs) .. => pure xs\n   | _ =>  throw \"Function declaration expected for 'main'\"\n\n  unless xs.size == 2 || xs.size == 1 do throw s!\"Invalid main function, main expected to have '2' or '1' arguments, found '{xs.size}' arguments\"\n  let env \u2190 getEnv\n  let usesLeanAPI := usesModuleFrom env `Lean\n  let mainTy \u2190 LLVM.functionType (\u2190 LLVM.i64Type llvmctx)\n      #[(\u2190 LLVM.i64Type llvmctx), (\u2190 LLVM.pointerType (\u2190 LLVM.voidPtrType llvmctx))]\n  let main \u2190 LLVM.getOrAddFunction mod \"main\" mainTy\n  let entry \u2190 LLVM.appendBasicBlockInContext llvmctx main \"entry\"\n  LLVM.positionBuilderAtEnd builder entry\n  /-\n  #if defined(WIN32) || defined(_WIN32)\n  SetErrorMode(SEM_FAILCRITICALERRORS);\n  #endif\n  -/\n  let inty \u2190 LLVM.voidPtrType llvmctx\n  let inslot \u2190 LLVM.buildAlloca builder (\u2190 LLVM.pointerType inty) \"in\"\n  let resty \u2190 LLVM.voidPtrType llvmctx\n  let res \u2190 LLVM.buildAlloca builder (\u2190 LLVM.pointerType resty) \"res\"\n  if usesLeanAPI then callLeanInitialize builder else callLeanInitializeRuntimeModule builder\n    /- We disable panic messages because they do not mesh well with extracted closed terms.\n        See issue #534. We can remove this workaround after we implement issue #467. -/\n  callLeanSetPanicMessages builder (\u2190 LLVM.constFalse llvmctx)\n  let world \u2190 callLeanIOMkWorld builder\n  let resv \u2190 callModInitFn builder (\u2190 getModName) (\u2190 LLVM.constInt8 llvmctx 1) world ((\u2190 getModName).toString ++ \"_init_out\")\n  let _ \u2190 LLVM.buildStore builder resv res\n\n  callLeanSetPanicMessages builder (\u2190 LLVM.constTrue llvmctx)\n  callLeanIOMarkEndInitialization builder\n\n  let resv \u2190 LLVM.buildLoad2 builder resty res \"resv\"\n  let res_is_ok \u2190 callLeanIOResultIsOk builder resv \"res_is_ok\"\n  buildIfThen_ builder \"resIsOkBranches\"  res_is_ok\n    (fun builder => do -- then clause of the builder)\n      callLeanDecRef builder resv\n      callLeanInitTaskManager builder\n      if xs.size == 2 then\n        let inv \u2190 callLeanBox builder (\u2190 LLVM.constInt (\u2190 LLVM.size_tType llvmctx) 0) \"inv\"\n        let _ \u2190 LLVM.buildStore builder inv inslot\n        let ity \u2190 LLVM.size_tType llvmctx\n        let islot \u2190 LLVM.buildAlloca builder ity \"islot\"\n        let argcval \u2190 LLVM.getParam main 0\n        let argvval \u2190 LLVM.getParam main 1\n        LLVM.buildStore builder argcval islot\n        buildWhile_ builder \"argv\"\n          (condcodegen := fun builder => do\n            let iv \u2190 LLVM.buildLoad2 builder ity islot \"iv\"\n            let i_gt_1 \u2190 LLVM.buildICmp builder LLVM.IntPredicate.UGT iv (\u2190 constIntUnsigned 1) \"i_gt_1\"\n            return i_gt_1)\n          (bodycodegen := fun builder => do\n            let iv \u2190 LLVM.buildLoad2 builder ity islot \"iv\"\n            let iv_next \u2190 LLVM.buildSub builder iv (\u2190 constIntUnsigned 1) \"iv.next\"\n            LLVM.buildStore builder iv_next islot\n            let nv \u2190 callLeanAllocCtor builder 1 2 0 \"nv\"\n            let argv_i_next_slot \u2190 LLVM.buildGEP2 builder (\u2190 LLVM.voidPtrType llvmctx) argvval #[iv_next] \"argv.i.next.slot\"\n            let argv_i_next_val \u2190 LLVM.buildLoad2 builder (\u2190 LLVM.voidPtrType llvmctx) argv_i_next_slot \"argv.i.next.val\"\n            let argv_i_next_val_str \u2190 callLeanMkString builder argv_i_next_val \"arg.i.next.val.str\"\n            callLeanCtorSet builder nv (\u2190 constIntUnsigned 0) argv_i_next_val_str\n            let inv \u2190 LLVM.buildLoad2 builder inty inslot \"inv\"\n            callLeanCtorSet builder nv (\u2190 constIntUnsigned 1) inv\n            LLVM.buildStore builder nv inslot)\n        let world \u2190 callLeanIOMkWorld builder\n        let inv \u2190 LLVM.buildLoad2 builder inty inslot \"inv\"\n        let resv \u2190 callLeanMainFn builder (argv? := .some inv) (world := world) \"resv\"\n        let _ \u2190 LLVM.buildStore builder resv res\n        pure ShouldForwardControlFlow.yes\n      else\n          let world \u2190 callLeanIOMkWorld builder\n          let resv \u2190 callLeanMainFn builder (argv? := .none) (world := world) \"resv\"\n          let _ \u2190 LLVM.buildStore builder resv res\n          pure ShouldForwardControlFlow.yes\n  )\n\n  -- `IO _`\n  let retTy := env.find? `main |>.get! |>.type |>.getForallBody\n  -- either `UInt32` or `(P)Unit`\n  let retTy := retTy.appArg!\n  -- finalize at least the task manager to avoid leak sanitizer false positives\n  -- from tasks outliving the main thread\n  callLeanFinalizeTaskManager builder\n  let resv \u2190 LLVM.buildLoad2 builder resty res \"resv\"\n  let res_is_ok \u2190 callLeanIOResultIsOk builder resv \"res_is_ok\"\n  buildIfThenElse_ builder \"res.is.ok\" res_is_ok\n    (fun builder => -- then builder\n      if retTy.constName? == some ``UInt32 then do\n        let resv \u2190 LLVM.buildLoad2 builder resty res \"resv\"\n        let retv \u2190 callLeanUnboxUint32 builder (\u2190 callLeanIOResultGetValue builder resv \"io_val\") \"retv\"\n        let retv \u2190 LLVM.buildSext builder retv (\u2190 LLVM.i64Type llvmctx) \"retv_sext\"\n        callLeanDecRef builder resv\n        let _ \u2190 LLVM.buildRet builder retv\n        pure ShouldForwardControlFlow.no\n      else do\n        callLeanDecRef builder resv\n        let _ \u2190 LLVM.buildRet builder (\u2190 LLVM.constInt64 llvmctx 0)\n        pure ShouldForwardControlFlow.no\n\n    )\n    (fun builder => do -- else builder\n        let resv \u2190 LLVM.buildLoad2 builder resty res \"resv\"\n        callLeanIOResultShowError builder resv\n        callLeanDecRef builder resv\n        let _ \u2190 LLVM.buildRet builder (\u2190 LLVM.constInt64 llvmctx 1)\n        pure ShouldForwardControlFlow.no)\n  -- at the merge\n  let _ \u2190 LLVM.buildUnreachable builder\n\ndef hasMainFn : M llvmctx Bool := do\n  let env \u2190 getEnv\n  let decls := getDecls env\n  return decls.any (fun d => d.name == `main)\n\ndef emitMainFnIfNeeded (mod : LLVM.Module llvmctx) (builder : LLVM.Builder llvmctx) : M llvmctx Unit := do\n  if (\u2190 hasMainFn) then emitMainFn mod builder\n\ndef main : M llvmctx Unit := do\n  emitFnDecls\n  let builder \u2190 LLVM.createBuilderInContext llvmctx\n  emitFns (\u2190 getLLVMModule) builder\n  emitInitFn (\u2190 getLLVMModule) builder\n  emitMainFnIfNeeded (\u2190 getLLVMModule) builder\nend EmitLLVM\n\ndef getLeanHBcPath : IO System.FilePath := do\n  return (\u2190 getLibDir (\u2190 getBuildDir)) / \"lean.h.bc\"\n\ndef optimizeLLVMModule (mod : LLVM.Module ctx) : IO Unit := do\n  let pm  \u2190 LLVM.createPassManager\n  let pmb \u2190 LLVM.createPassManagerBuilder\n  pmb.setOptLevel 3\n  pmb.populateModulePassManager pm\n  LLVM.runPassManager pm mod\n  LLVM.disposePassManager pm\n  LLVM.disposePassManagerBuilder pmb\n\n/--\n`emitLLVM` is the entrypoint for the lean shell to code generate LLVM.\n-/\n@[export lean_ir_emit_llvm]\ndef emitLLVM (env : Environment) (modName : Name) (filepath : String) (tripleStr? : Option String) : IO Unit := do\n  LLVM.llvmInitializeTargetInfo\n  let llvmctx \u2190 LLVM.createContext\n  let module \u2190 LLVM.createModule llvmctx modName.toString\n  let emitLLVMCtx : EmitLLVM.Context llvmctx := {env := env, modName := modName, llvmmodule := module}\n  let initState := { var2val := default, jp2bb := default : EmitLLVM.State llvmctx}\n  let out? \u2190 ((EmitLLVM.main (llvmctx := llvmctx)).run initState).run emitLLVMCtx\n  match out? with\n  | .ok _ => do\n         let membuf \u2190 LLVM.createMemoryBufferWithContentsOfFile (\u2190 getLeanHBcPath).toString\n         let modruntime \u2190 LLVM.parseBitcode llvmctx membuf\n         LLVM.linkModules (dest := emitLLVMCtx.llvmmodule) (src := modruntime)\n         optimizeLLVMModule emitLLVMCtx.llvmmodule\n         LLVM.writeBitcodeToFile emitLLVMCtx.llvmmodule filepath\n         let tripleStr := tripleStr?.getD (\u2190 LLVM.getDefaultTargetTriple)\n         let target \u2190 LLVM.getTargetFromTriple tripleStr\n         let cpu := \"generic\"\n         let features := \"\"\n         let targetMachine \u2190 LLVM.createTargetMachine target tripleStr cpu features\n         let codegenType := LLVM.CodegenFileType.ObjectFile\n         LLVM.targetMachineEmitToFile targetMachine emitLLVMCtx.llvmmodule (filepath ++ \".o\") codegenType\n         LLVM.disposeModule emitLLVMCtx.llvmmodule\n         LLVM.disposeTargetMachine targetMachine\n  | .error err => throw (IO.Error.userError err)\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/EmitLLVM.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1460872321774425, "lm_q2_score": 0.04401865487939376, "lm_q1q2_score": 0.006430563455504707}}
{"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 \u00d7 name) := do \n  x \u2190 tactic.get_unused_name `x,\n  H \u2190 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 \u27e8x, H\u27e9\n\n\ndef theList := [armPosition,LAAP,armController].pw_filter (ne)\n\n\nmeta def foo : tactic unit := \ndo \n  v \u2190 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  \u27e8x, H\u27e9 \u2190 preprocess_rpo_fst,\n  `[rcases H with \u27e8H1,H2,H3\u27e9],\n  tactic.repeat `[rw Map.find_val at H1 H2 H3],\n  `[have  distinct1 : armPosition \u2260 LAAP, by {dec_trivial,},\n  have  distinct2 : armPosition \u2260 armController, by {dec_trivial},\n  have  distinct3 : armController \u2260 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 \u2208 AssertionLang.sem ((atom fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg).always \u2192 x \u2208 ((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 \u2208 AssertionLang.sem ((atom fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg).always) \u2192 stream.drop i x \u2208 (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 \u00d7 expr)) := \n-- do \n\n-- meta def get_comp_names : tactic (list (expr \u00d7 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 \u2260 LAAP, by {dec_trivial,},\n  have  distinct2 : armPosition \u2260 armController, by {dec_trivial},\n  have  distinct3 : armController \u2260 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 \u2260 LAAP, by {dec_trivial,},\n  have  distinct2 : armPosition \u2260 armController, by {dec_trivial},\n  have  distinct3 : armController \u2260 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 \u2260 LAAP, by {dec_trivial,},\n  have  distinct2 : armPosition \u2260 armController, by {dec_trivial},\n  have  distinct3 : armController \u2260 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 \u2260 LAAP, by {dec_trivial,},\n  have  distinct2 : armPosition \u2260 armController, by {dec_trivial},\n  have  distinct3 : armController \u2260 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 \u2260 LAAP, by {dec_trivial,},\n  have  distinct2 : armPosition \u2260 armController, by {dec_trivial},\n  have  distinct3 : armController \u2260 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 \u2208 AssertionLang.sem ((atom  fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg ).always) \u2192 stream.drop i s \u2208 (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 \u2208 AssertionLang.sem ((atom  fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg ).always) \u2192 stream.drop i s \u2208 (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 data.finset.basic\nimport data.fintype.basic\n\n/-\nHigh-level model of Soong build system (very incomplete)\n\n Concrete examples of libraries:\n\n /system/bin/cameraserver\n - soong world: no options specified (meaning, 'local to system')\n\n /vendor/bin/vndservicemanager\n - soong world: \"vendor: true\" (meaning, 'local to vendor')\n\n libgui\n - soong world: \"vendor_available: false, vndk: { enabled: true, },\"\n - \"vndk-private\"\n\n libcamerahelper\n - soong world: \"vendor_available: true, vndk: { enabled: true, },\"\n - soong world: \"libcamerahelper loads libgui\" -- not important to model, this\n                actually the relationship between vndk and vndk-private\n - \"vndk\"\n\n libbinder_ndk\n - soong world: \"vendor_available: true, isLlNdk() true\"\n - ll-ndk\n -/\n\n--------------------------------------------------------------------------------\n/-\n - Core data structures of Soong model\n -/\n\n/-\n - Different kinds of libraries which have regular behavior in some sense\n - This does not correspond to any particular abstraction in the codebase but\n - is very useful for clarifying a mental model of how things work (lots of\n - behavior can be defined purely in virtue of what library classes a library\n - inhabits, without having to look at details of the library itself).\n -/\n@[derive decidable_eq]\ninductive Library_class\n | system_local: Library_class\n | system_ext: Library_class\n | vendor_local: Library_class\n | llndk: Library_class\n | vndk: Library_class\n | vndk_sp: Library_class\n | vndk_ext: Library_class\n | vndk_private: Library_class\n | product: Library_class\n | recovery: Library_class\n\nopen Library_class\n\n/-\n - Being assigned some subset of these variants is a property of a given library\n - Which are assigned ends up dictating the build environment to a large degree.\n -/\n@[derive decidable_eq]\ninductive Variant\n | core: Variant\n | vendor_platform : Variant\n | product_platform : Variant\n | product_product : Variant\n | ramdisk : Variant\n | recovery : Variant\n\n/-\n - Specified by a user in a Soong input file.\n -/\n@[derive decidable_eq]\nstructure Library :=\n (name: string)\n\n (vendor_available: option bool)\n\n (vendor: option bool)\n -- declared as a VNDK or VNDK-SP module. The vendor variant\n    -- will be installed in /system instead of /vendor partition.\n    -- if true, then vendor_available must be explicitly set to either \u22a4 or \u22a5\n (vndk_enabled: option bool)\n -- declared as a VNDK-SP module, which is a subset of VNDK (need vndk_enabled).\n    -- All these modules are allowed to link to VNDK-SP or LL-NDK\n    -- modules only. Other dependency will cause link-type errors.\n    -- none/false means lib is VNDK-core\n    -- can link to other VNDK-core ,VNDK-SP or LL-NDK modules only.\n    -- Warning: sometimes erroneously referred to as support_same_process\n (vndk_support_system_process: option bool)\n -- Whether m.linker(*llndkStubDecorator) returns true or not\n -- Assume that llndkHeadersDecorator has same value\n -- Modeled as a boolean field for simplicity\n (llndk_stub: bool)\n\n (device_specific: bool)\n (product_specific: bool)\n (is_vndk: bool)\n (is_vndkext: bool)\n -- Dependencies on other libraries by name\n (deps: finset string)\n\n/-\n - Based on Jiyong's summary\n - The \"none\" corresponds to the very first check of ImageMutatorBegin, where\n - it fails because having both of these options set doesn't make sense\n - TODO consider all four booleans together,\n -   vndk-private is when vendor_available is false but vndk_enabled is true\n -   vndk_sp_private is the same as above but also has\n -     vndk_support_system_process true\n -/\ndef assign_library_classes (lib: Library): option (finset Library_class) :=\n (option.lift_or_get finset.has_union.1)\n\n (match lib.vendor, lib.vendor_available  with\n  | (some _),      (some _)  := none\n  | (some vendor), _         := some [vendor_local].to_finset\n  | _,             (some tt) := some [vendor_local, system_local].to_finset\n  | _,             (some ff) := some [system_local].to_finset -- TODO CHECK THIS\n  | none,          none      := some [system_local].to_finset\n  end)\n  $  (option.lift_or_get finset.has_union.1)\n\n  (match lib.vndk_enabled, lib.vndk_support_system_process with\n    | (some tt), (some tt) := some [vndk_sp].to_finset\n    | (some tt), _         := some [vndk].to_finset\n    | _,         (some _)  := none\n    | _,          _        := some \u2205\n   end)\n\n  (some $ if lib.llndk_stub then [llndk].to_finset else \u2205)\n\n/-\n - Based on the implemenation at ~3122 of cc.go\n - Relies on assign_library_classes\n -/\n open Variant\n def libaryclass_to_variants: Library_class \u2192 finset Variant\n | system_local:= [core].to_finset\n | system_ext:= [core].to_finset\n | vendor_local:= [].to_finset -- aka vendorSpecific (ignore kernelHeadersDecorator) and ignore vendor board (it's experimental) only look at line 255\n | llndk:= [].to_finset -- variants from lines 187-197\n | vndk:= [core].to_finset -- AND whatever is in vendor_local\n | vndk_sp:= [].to_finset -- SAME as vndk\n | vndk_ext:= [].to_finset -- same as vendor_local\n | vndk_private:= [].to_finset -- same as vendor_local\n | product:= [core].to_finset\n | recovery:= [Variant.recovery].to_finset\n\n\n\n\n/-\n - Map over and union\n - That we can do this is the justification of library_class' existance.\n - All members of a library class share variants.\n -/\ndef libary_to_variant (libc: Library): option (finset Variant):=\n  assign_library_classes libc >>= \u03bb lcs, some $\n    (libclasses.1.map library_class_to_variants).fold (\u222a) \u2205\n\n--------------------------------------------------------------------------------\n/-\n - Transitive relationship of reachability in a graph\n -/\ninductive depends: finset Library \u2192 Library \u2192 Library \u2192 Prop\n | edge: \u2200 (ctx: finset Library) (src tar: Library),\n    src \u2208 ctx \u2192 tar \u2208 ctx\n        \u2192 tar.name \u2208 src.deps\n            \u2192 depends ctx src tar\n | trans: \u2200 (ctx: finset Library) (src mid tar: Library),\n    src \u2208 ctx \u2192 tar \u2208 ctx\n        \u2192 depends ctx src mid\n            \u2192 depends ctx mid tar\n                \u2192 depends ctx src tar\n\n\n--------------------------------------------------------------------------------\n/-\n - Concrete library examples\n -/\n-- def cameraserver: Library := \u27e8\"cameraserver\", none, none, none, \u2205\u27e9\n-- def libcamerahelper: Library := \u27e8\"libcamerahelper\", some tt, none, none, \u2205\u27e9\n-- def vndservicemanager: Library := \u27e8\"vndservicemanager\", ff, none, none, \u2205\u27e9\n-- def libgui: Library := \u27e8\"libgui\", some ff, none, none, \u2205\u27e9\n-- def libutils: Library := \u27e8\"libutils\", some tt, none, none, \u2205\u27e9\n--------------------------------------------------------------------------------\n/-\n - Proofs about the model\n -/\n\ntheorem assign_library_classes_nonempty:\n  forall lib: Library, \u00ac (assign_library_classes lib) = some \u2205\n := sorry\n\n-- theorem double_loadable:\n--   forall llndklib vndklib: LibraryWithClass, llndklib <= vndklib\n--     \u2192 vndklib.double_loadable\n--  := sorry\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/soong_model/soong_model.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.023689473065645436, "lm_q1q2_score": 0.006371080557780899}}
{"text": "import Yatima.Datatypes.Const\nimport Lurk.LDON\n\nopen Lurk\n\ninstance : Coe Nat LDON where\n  coe := .num \u2218 .ofNat\n\ninstance : OfNat LDON n where\n  ofNat := .num (.ofNat n)\n\ninstance : Coe Bool LDON where coe\n  | false => 0\n  | true  => 1\n\ninstance : Coe String LDON where\n  coe := .str\n\ninstance : Coe F LDON where\n  coe := .num\n\ninstance : Coe (List LDON) LDON where\n  coe xs := xs.foldr (init := .nil) .cons\n\ninstance : Coe Lean.Literal LDON where coe  \n  | .natVal n => ([0, n] : List LDON)\n  | .strVal s => ([1, s] : List LDON)\n\nnamespace Yatima.IR\n\ndef Univ.toLDON : Univ \u2192 LDON\n  | .zero     => ([0] : List LDON)\n  | .succ u   => ([1, u.toLDON] : List LDON)\n  | .max u v  => ([2, u.toLDON, v.toLDON] : List LDON)\n  | .imax u v => ([3, u.toLDON, v.toLDON] : List LDON)\n  | .var n    => ([4, n] : List LDON)\n\ninstance : Coe Univ LDON where\n  coe := Univ.toLDON\n\ndef Expr.toLDON : Expr \u2192 LDON\n  | .var n lvls     => ([0, n, lvls.map IR.Univ.toLDON] : List LDON)\n  | .sort u         => ([1, u] : List LDON)\n  | .const ptr lvls => ([2, ptr, lvls.map IR.Univ.toLDON] : List LDON)\n  | .app fn arg     => ([3, fn.toLDON, arg.toLDON] : List LDON)\n  | .lam name body  => ([4, name.toLDON, body.toLDON] : List LDON)\n  | .pi x y         => ([5, x.toLDON, y.toLDON] : List LDON)\n  | .letE x y z     => ([6, x.toLDON, y.toLDON, z.toLDON] : List LDON)\n  | .lit l          => ([7, l] : List LDON)\n  | .proj n e       => ([8, n, e.toLDON] : List LDON)\n\ninstance : Coe Expr LDON where\n  coe := Expr.toLDON\n\ndef Axiom.toLDON : Axiom \u2192 LDON\n  | \u27e8lvls, type\u27e9 => ([0, lvls, type] : List LDON)\n\ninstance : Coe Axiom LDON where\n  coe := Axiom.toLDON\n\ndef Theorem.toLDON : Theorem \u2192 LDON\n  | \u27e8lvls, type, value\u27e9 => ([0, lvls, type, value] : List LDON)\n\ninstance : Coe Theorem LDON where\n  coe := Theorem.toLDON\n\ndef Opaque.toLDON : Opaque \u2192 LDON\n  | \u27e8lvls, type, value\u27e9 => ([0, lvls, type, value] : List LDON)\n\ninstance : Coe Opaque LDON where\n  coe := Opaque.toLDON\n\ninstance : Coe Lean.QuotKind LDON where coe\n  | .type => ([0] : List LDON)\n  | .ctor => ([1] : List LDON)\n  | .lift => ([2] : List LDON)\n  | .ind  => ([3] : List LDON)\n\ndef Quotient.toLDON : Quotient \u2192 LDON\n  | \u27e8lvls, type, kind\u27e9 => ([0, lvls, type, kind] : List LDON)\n\ninstance : Coe Quotient LDON where\n  coe := Quotient.toLDON\n\ninstance : Coe Lean.DefinitionSafety LDON where coe\n  | .unsafe  => ([0] : List LDON)\n  | .safe    => ([1] : List LDON)\n  | .partial => ([2] : List LDON)\n\ndef Definition.toLDON : Definition \u2192 LDON\n  | \u27e8lvls, type, value, part\u27e9 =>\n    ([0, lvls, type, value, part] : List LDON)\n\ninstance : Coe Definition LDON where\n  coe := Definition.toLDON\n\ndef Constructor.toLDON : Constructor \u2192 LDON\n  | \u27e8lvls, type, idx, params, fields\u27e9 => ([0, lvls, type, idx, params, fields] : List LDON)\n\ninstance : Coe Constructor LDON where\n  coe := Constructor.toLDON\n\ndef RecursorRule.toLDON : RecursorRule \u2192 LDON\n  | \u27e8fields, rhs\u27e9 => ([0, fields, rhs] : List LDON)\n\ninstance : Coe RecursorRule LDON where\n  coe := RecursorRule.toLDON\n\ndef Recursor.toLDON : Recursor \u2192 LDON\n  | \u27e8lvls, type, params, indices, motives, minors, rules, isK, internal\u27e9 =>\n    ([0, lvls, type, params, indices, motives, minors, rules.map RecursorRule.toLDON, isK, internal] : List LDON)\n\ninstance : Coe Recursor LDON where\n  coe := Recursor.toLDON\n\ndef Inductive.toLDON : Inductive \u2192 LDON\n  | \u27e8lvls, type, params, indices, ctors, recrs, recr, refl, struct, unit\u27e9 =>\n    ([0, lvls, type, params, indices, ctors.map Constructor.toLDON, recrs.map Recursor.toLDON, recr, refl, struct, unit] : List LDON)\n\ninstance : Coe Inductive LDON where\n  coe := Inductive.toLDON\n\ndef InductiveProj.toLDON : InductiveProj \u2192 LDON\n  | \u27e8block, idx\u27e9 => ([0, block, idx] : List LDON)\n\ninstance : Coe InductiveProj LDON where\n  coe := InductiveProj.toLDON\n\ndef ConstructorProj.toLDON : ConstructorProj \u2192 LDON\n  | \u27e8block, idx, cidx\u27e9 => ([0, block, idx, cidx] : List LDON)\n\ninstance : Coe ConstructorProj LDON where\n  coe := ConstructorProj.toLDON\n\ndef RecursorProj.toLDON : RecursorProj \u2192 LDON\n  | \u27e8block, idx, ridx\u27e9 => ([0, block, idx, ridx] : List LDON)\n\ninstance : Coe RecursorProj LDON where\n  coe := RecursorProj.toLDON\n\ndef DefinitionProj.toLDON : DefinitionProj \u2192 LDON\n  | \u27e8block, idx\u27e9 => ([0, block, idx] : List LDON)\n\ninstance : Coe DefinitionProj LDON where\n  coe := DefinitionProj.toLDON\n\ndef Const.toLDON : Const \u2192 LDON\n  | .axiom x           => ([0, x] : List LDON)\n  | .theorem x         => ([1, x] : List LDON)\n  | .opaque x          => ([2, x] : List LDON)\n  | .definition x      => ([3, x] : List LDON)\n  | .quotient x        => ([4, x] : List LDON)\n  | .inductiveProj x   => ([5, x] : List LDON)\n  | .constructorProj x => ([6, x] : List LDON)\n  | .recursorProj x    => ([7, x] : List LDON)\n  | .definitionProj x  => ([8, x] : List LDON)\n  | .mutDefBlock x     => ([9, x.map Definition.toLDON] : List LDON)\n  | .mutIndBlock x     => ([10, x.map Inductive.toLDON] : List LDON)\n\nend Yatima.IR\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/Yatima/Common/ToLDON.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2173375210470625, "lm_q2_score": 0.02931223223529719, "lm_q1q2_score": 0.006370647890375287}}
{"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* := \u2115\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\u27e8\u03bb _ _, by { unfold foo, exact 37 }\u27e9\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 \u27e8\u03bb _ _, 37\u27e9\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 \u27e8\u03bb _ _, 37\u27e9\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": "import ..flocq\n\n/- Indeterminate architecture -/\n\nnamespace archi\nopen flocq\n\ndef ptr64 : bool := sorry\n\ndef big_endian : bool := sorry\n\ndef align_int64 : \u2115 := sorry\ndef align_float64 : \u2115 := sorry\n\ndef splitlong : bool := sorry\n\nlemma splitlong_ptr32 : splitlong = tt \u2192 ptr64 = ff := sorry\n\ndef default_pl_64 : bool \u00d7 nan_pl 53 := sorry\n\ndef choose_binop_pl_64 (s1 : bool) (pl1 : nan_pl 53) (s2 : bool) (pl2 : nan_pl 53) : bool := sorry\n\ndef default_pl_32 : bool \u00d7 nan_pl 24 := sorry\n\ndef choose_binop_pl_32 (s1 : bool) (pl1 : nan_pl 24) (s2 : bool) (pl2 : nan_pl 24) : bool := sorry\n\ndef float_of_single_preserves_sNaN : bool := sorry\n\nend archi", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/archi/sorry.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32082128783705344, "lm_q2_score": 0.0197191264510955, "lm_q1q2_score": 0.006326315543062164}}
{"text": "/-\nCopyright (c) 2021 OpenAI. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Stanislas Polu, Jesse Michael Han\n\nREPL implementation to interact with Lean through stdio at a specific\ndeclaration.\n-/\nimport tactic\nimport data.string.basic\nimport all\nimport util.io\nimport util.tactic\nimport basic.table\nimport tools.shrink_proof\nimport tools.try_finish\n\nsection main\n\nsetup_tactic_parser\n\n\nmeta structure LeanREPLRequest : Type :=\n(cmd : string)\n(sid: string)\n(tsid: string)\n(tac: string)\n(name: string)\n(open_ns: string)\n(term: string)\n\nmeta structure LeanREPLResponse : Type :=\n(sid : option string)\n(tsid : option string)\n(tactic_state : option string)\n(error: option string)\n(proof_steps : list (string \u00d7 string))\n\n\nmeta structure parent : Type :=\n(tsid : string)\n(action : string)\n\nmeta structure LeanREPLState : Type :=\n(state : dict string (dict string (tactic_state \u00d7 option parent)))\n(next_sid : \u2115)\n\nnamespace LeanREPLState\n\nmeta def insert_ts (\u03c3 : LeanREPLState) (sid) (tsid) (ts) (parent : option parent): LeanREPLState :=\n  \u27e8dict.insert sid (dict.insert tsid (ts, parent) (\u03c3.1.get_default (dict.empty) sid)) \u03c3.1, \u03c3.2\u27e9\n\nmeta def get_ts_parents (\u03c3 : LeanREPLState) (sid) (tsid) : option (tactic_state \u00d7 option parent) :=\n  (\u03c3.1.get_default (dict.empty) sid).get tsid\n\nmeta def get_ts (\u03c3 : LeanREPLState) (sid) (tsid) : option tactic_state :=\n  option.map prod.fst $ \u03c3.get_ts_parents sid tsid\n\nmeta def get_next_tsid (\u03c3 : LeanREPLState) (sid) : string := (format! \"{(\u03c3.1.get_default (dict.empty) sid).size}\").to_string\n\nmeta def erase_search (\u03c3 : LeanREPLState) (sid) : LeanREPLState := \u27e8\u03c3.1.erase sid, \u03c3.2\u27e9\n\nmeta def get_next_sid (\u03c3 : LeanREPLState) : string := (format! \"{\u03c3.2}\").to_string\n\nmeta def incr_next_sid (\u03c3 : LeanREPLState) : LeanREPLState := \u27e8\u03c3.1, \u03c3.2+1\u27e9\n\nend LeanREPLState\n\nmeta instance : has_from_json LeanREPLRequest := \u27e8\u03bb msg, match msg with\n  | (json.array [json.of_string cmd, json.array args]) := match cmd with\n    | \"run_tac\" := match json.array args with\n      | (json.array [json.of_string sid, json.of_string tsid, json.of_string tac]) := pure \u27e8cmd, sid, tsid, tac, \"\", \"\", \"\"\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | \"conjecture_set\" := match json.array args with\n      | (json.array [json.of_string sid, json.of_string tsid, json.of_string term]) := pure \u27e8cmd, sid, tsid, \"\", \"\", \"\", term\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | \"conjecture_assume\" := match json.array args with\n      | (json.array [json.of_string sid, json.of_string tsid, json.of_string term]) := pure \u27e8cmd, sid, tsid, \"\", \"\", \"\", term\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | \"init_search\" := match json.array args with\n      | (json.array [json.of_string name, json.of_string open_ns]) := pure \u27e8cmd, \"\", \"\", \"\", name, open_ns, \"\"\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | \"clear_search\" := match json.array args with\n      | (json.array [json.of_string sid]) := pure \u27e8cmd, sid, \"\" , \"\", \"\", \"\", \"\"\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | \"shrink_proof\" := match json.array args with\n      | (json.array [json.of_string sid, json.of_string tsid]) := do\n        pure \u27e8cmd, sid, tsid , \"\", \"\", \"\", \"\"\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | \"try_finish\" := match json.array args with\n      | (json.array [json.of_string sid, json.of_string tsid]) := do\n        pure \u27e8cmd, sid, tsid , \"\", \"\", \"\", \"\"\u27e9\n      | exc := tactic.fail format!\"request_parsing_error: cmd={cmd} data={exc}\"\n      end\n    | exc := tactic.fail format!\"request_parsing_error: data={exc}\"\n    end\n  | exc := tactic.fail format!\"request_parsing_error: data={exc}\"\n  end\n\u27e9\n\n\n@[reducible]\nmeta def LeanREPL := state_t LeanREPLState io\n\nmeta def LeanREPL.forever (x : LeanREPL unit) : LeanREPL unit := do\n  \u03c3\u2080 \u2190 get,\n  state_t.lift $ io.iterate \u03c3\u2080 $ \u03bb \u03c3, do {\n    (_, \u03c3') \u2190 x.run \u03c3,\n    return (some \u03c3')\n  },\n  state_t.lift $ io.fail' $ format! \"[LeanREPL.forever] unreachable code\"\n\nmeta def record_ts {m} [monad m] (sid: string) (ts : tactic_state) (parent : option parent) : (state_t LeanREPLState m) string := do {\n  \u03c3 \u2190 get,\n  let tsid := \u03c3.get_next_tsid sid,\n  modify $ \u03bb \u03c3, \u03c3.insert_ts sid tsid ts parent,\n  pure tsid\n}\n\nmeta def LeanREPLResponse.to_json: LeanREPLResponse \u2192 json\n| \u27e8sid, tsid, ts, err, steps\u27e9 :=\n    json.object [\n      \u27e8\"search_id\", match sid with\n        | none := json.null\n        | some sid := json.of_string sid\n        end\u27e9,\n      \u27e8\"tactic_state_id\", match tsid with\n        | none := json.null\n        | some tsid := json.of_string tsid\n        end\u27e9,\n      \u27e8\"tactic_state\", match ts with\n        | none := json.null\n        | some ts := json.of_string ts\n        end\u27e9,\n      \u27e8\"error\", match err with\n        | none := json.null\n        | some err := json.of_string err\n        end\u27e9,\n      \u27e8\"proof_steps\", json.array (steps.map $ \u03bb \u27e8ts_str, action\u27e9, json.array [json.of_string ts_str, json.of_string action])\u27e9\n    ]\n\nmeta instance : has_to_format LeanREPLResponse :=\n\u27e8has_to_format.to_format \u2218 LeanREPLResponse.to_json\u27e9\n\n\nmeta def parse_theorem_name (nm: string) : tactic name :=\ndo lean.parser.run_with_input ident nm\n\n\nmeta def parse_open_namespace (open_ns: string) : tactic (list name) :=\ndo lean.parser.run_with_input (many ident) open_ns\n\n\nmeta def handle_init_search\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n   \u03c3 \u2190 get,\n   -- Parse declaration name.\n   decl_name \u2190 state_t.lift $ io.run_tactic'' $ do {\n     parse_theorem_name req.name\n   },\n   -- Parse open namespaces.\n   decl_open_ns \u2190 state_t.lift $ io.run_tactic'' $ do {\n     parse_open_namespace req.open_ns\n   },\n   -- Check that the declaration is a theorem.\n   is_theorem \u2190 state_t.lift $ io.run_tactic'' $ do {\n     tactic.is_theorem decl_name\n   } <|> pure ff,\n   match is_theorem with\n   -- The declaration is not a theorem, return an error.\n   | ff := do {\n     let err := format! \"not_a_theorem: name={req.name} open_ns={req.open_ns}\",\n     pure \u27e8none, none, none, some err.to_string, []\u27e9\n   }\n   -- The declaration is a theorem, set the env with open namespaces to it and\n   -- generate a new tactic state.\n   | tt := do {\n     ts \u2190 state_t.lift $ io.run_tactic'' $ do {\n       env \u2190 tactic.get_env,\n       decl \u2190 env.get decl_name,\n       let g := decl.type,\n       tactic.set_goal_to g,\n       lean_file \u2190 env.decl_olean decl_name,\n       tactic.set_env_core $ environment.for_decl_of_imported_module lean_file decl_name,\n       add_open_namespaces decl_open_ns,\n       tactic.read\n     },\n     let sid := \u03c3.get_next_sid,\n     modify $ \u03bb \u03c3, \u03c3.incr_next_sid,\n     tsid \u2190 record_ts sid ts none,\n     ts_str \u2190 (state_t.lift \u2218 io.run_tactic'') $ postprocess_tactic_state ts,\n     pure $ \u27e8sid, tsid, ts_str, none, []\u27e9\n   }\n   end\n}\n\n\nmeta def handle_clear_search\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n   -- Simply remove the table associated with the provided search id from the state.\n   modify $ \u03bb \u03c3, \u03c3.erase_search req.sid,\n   pure $ \u27e8req.sid, none, none, none, []\u27e9\n}\n\n\nmeta def finalize_proof\n  (req : LeanREPLRequest)\n  (ts': tactic_state) : LeanREPL LeanREPLResponse := do {\n  \u03c3 \u2190 get,\n  -- Retrieve the tactic state at index 0 to extract the top-level goal metavariable.\n  match \u03c3.get_ts req.sid \"0\" with\n  | none := do {\n    let err := format! \"unexpected_unknown_tsid_0: search_id={req.sid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n  | (some ts\u2080) := do {\n    result \u2190 (state_t.lift \u2218 io.run_tactic'') $ do {\n      -- Set to tactic state index 0 to retrieve the meta-variable for the top goal.\n      tactic.write ts\u2080,\n      [g] \u2190 tactic.get_goals,\n      tgt \u2190 tactic.infer_type g,\n      tactic.write ts',\n      pf \u2190 tactic.get_assignment g >>= tactic.instantiate_mvars,\n      tactic.capture' (validate_proof tgt pf)\n    },\n    match result with\n    | (interaction_monad.result.success r s') := do {\n      tsid \u2190 record_ts req.sid ts' (some \u27e8req.tsid, req.tac\u27e9),\n      ts_str \u2190 (state_t.lift \u2218 io.run_tactic'') $ postprocess_tactic_state ts',\n      pure $ \u27e8req.sid, tsid, ts_str, none, []\u27e9\n    }\n    | (interaction_monad.result.exception f p s') := do {\n      let msg := (f.get_or_else (\u03bb _, format.of_string \"n/a\")) (),\n      let err := format! \"proof_validation_failed: msg={msg}\",\n      pure \u27e8none, none, none, some err.to_string, []\u27e9\n    }\n    end\n  }\n  end\n}\n\nmeta def handle_conjecture\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n  \u03c3 \u2190 get,\n  match (\u03c3.get_ts req.sid req.tsid) with\n  | none := do {\n    let err := format! \"unknown_id: search_id={req.sid} tactic_state_id={req.tsid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n  | (some ts) := do {\n    let conj_str := req.term,\n    -- Use `have` to introduce the new assumption\n    result_with_string \u2190 state_t.lift $ io.run_tactic'' $ do {\n      tactic.write ts,\n      conj_name \u2190 tactic.get_unused_name \"h\",\n      let tac_str := format! \"have {conj_name} : {conj_str}\",\n      get_tac_and_capture_result tac_str.to_string 5000 <|> do {\n          let msg : format := format!\"parse_itactic failed on `{req.tac}`\",\n          interaction_monad.mk_exception msg none <$> tactic.read\n      }\n    },\n    match result_with_string with\n    -- `have` was successful.\n    | interaction_monad.result.success _ ts' := do {\n        -- Narrow the tactic state to the assumption only\n        ts_narrowed \u2190 (state_t.lift \u2218 io.run_tactic'') $ do {\n          tactic.write ts',\n          g \u2190 list.head <$> tactic.get_goals,\n          tactic.set_goals [g],\n          -- We need to revert all hypotheses, otherwise proof finalization will complain with\n          -- unknown variables.\n          tactic.revert_all,\n          tactic.read\n        },\n        -- Create a new search id, this is required so that the final check are only run on the\n        -- \"narrowed\" tactic state (tactic state of the conjecture only).\n        let sid := \u03c3.get_next_sid,\n        modify $ \u03bb \u03c3, \u03c3.incr_next_sid,\n\n        tsid \u2190 record_ts sid ts_narrowed none,\n        ts_str \u2190 (state_t.lift \u2218 io.run_tactic'') $ postprocess_tactic_state ts_narrowed,\n        pure $ \u27e8sid, tsid, ts_str, none, []\u27e9\n    }\n    | interaction_monad.result.exception fn pos ts' := do {\n      state_t.lift $ do {\n        let msg := (fn.get_or_else (\u03bb _, format.of_string \"n/a\")) (),\n        let err := format! \"conjecture_set_have_failed: pos={pos} msg={msg}\",\n        pure \u27e8none, none, none, some err.to_string, []\u27e9\n      }\n    }\n    end\n  }\n  end\n}\n\nmeta def collect_proof_steps_aux (\u03c3 : LeanREPLState) (sid : string) : \u03a0 (tsid : string), io (list (tactic_state \u00d7 string \u00d7 tactic_state))\n| tsid2 := do\n  match \u03c3.get_ts_parents sid tsid2 with\n  | none := io.fail \"collect_proof_steps: invalid tsid\"\n  | (some \u27e8ts2, parent\u27e9) :=\n    match parent with\n    | none := if tsid2 = \"0\" then pure [] else io.fail \"no parent\"\n    | (some \u27e8tsid1, action\u27e9) :=\n      match \u03c3.get_ts sid tsid1 with\n      | none := io.fail \"parent doesn't exist\"\n      | (some ts1) := do {\n        rest \u2190 collect_proof_steps_aux tsid1,\n        pure (\u27e8ts1, action, ts2\u27e9 :: rest)\n      }\n      end\n    end\n  end\n\nmeta def collect_proof_steps (\u03c3 : LeanREPLState) (sid tsid : string) : io (list (tactic_state \u00d7 string \u00d7 tactic_state)) := do\n  rev_steps \u2190 collect_proof_steps_aux \u03c3 sid tsid,\n  pure $ list.reverse rev_steps\n\nmeta def handle_shrink_proof\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n  \u03c3 \u2190 get,\n  match (\u03c3.get_ts req.sid req.tsid) with\n  | none := do {\n    let err := format! \"unknown_id: search_id={req.sid} tactic_state_id={req.tsid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n  | (some ts_final) := do {\n    ts_str \u2190 state_t.lift $ io.run_tactic'' $ postprocess_tactic_state ts_final,\n    state_t.lift $ io.run_tac ts_final tactic.done,\n    steps \u2190 state_t.lift $ collect_proof_steps \u03c3 req.sid req.tsid,\n    new_steps \u2190 state_t.lift (shrink_proof steps),\n    new_steps \u2190 state_t.lift $ new_steps.mmap $ \u03bb \u27e8ts1, action, _\u27e9, do {\n      ts1_str \u2190 io.run_tactic'' $ postprocess_tactic_state ts1,\n      pure (ts1_str, action)\n    },\n    pure \u27e8req.sid, req.tsid, ts_str, none, new_steps\u27e9\n  }\n  end\n  }\n\nmeta def handle_try_finish\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n  \u03c3 \u2190 get,\n  match (\u03c3.get_ts req.sid req.tsid) with\n  | none := do {\n    let err := format! \"unknown_id: search_id={req.sid} tactic_state_id={req.tsid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n  | (some ts) := do {\n    possible_action \u2190 state_t.lift $ try_finish ts,\n    match possible_action with\n    | none := do {\n      let err := format! \"try_finish_failed: search_id={req.sid} tactic_state_id={req.tsid}\",\n      pure \u27e8none, none, none, some err.to_string, []\u27e9\n    }\n    | some (action, ts') := do {\n      -- TODO: refactor so that finalizing a proof is a separate top-level call\n      goals \u2190 state_t.lift $ io.run_tac ts' tactic.get_goals,\n      if goals.empty then do {\n        r \u2190 finalize_proof { req with tac := action } ts',\n        match r.error with\n        | none := do {\n          ts_str \u2190 state_t.lift $ io.run_tactic'' $ postprocess_tactic_state ts',\n          pure { r with proof_steps := [(action, ts_str)] }\n        }\n        | some err := pure r\n        end\n      } else do {\n      tsid \u2190 record_ts req.sid ts' (some \u27e8req.tsid, action\u27e9),\n      ts_str \u2190 (state_t.lift \u2218 io.run_tactic'') $ postprocess_tactic_state ts',\n      pure $ \u27e8req.sid, tsid, ts_str, none, [(action, ts_str)]\u27e9\n    }\n    }\n    end\n  }\n  end\n}\n\nmeta def handle_assume\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n  \u03c3 \u2190 get,\n  match (\u03c3.get_ts req.sid req.tsid) with\n  | none := do {\n    let err := format! \"unknown_id: search_id={req.sid} tactic_state_id={req.tsid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n  | (some ts) := do {\n    let conj_str := req.term,\n    -- Use `have` to introduce the new assumption\n    result_with_string \u2190 state_t.lift $ io.run_tactic'' $ do {\n      tactic.write ts,\n      conj_name \u2190 tactic.get_unused_name \"h\",\n      let tac_str := format! \"have {conj_name} : {conj_str}\",\n      get_tac_and_capture_result tac_str.to_string 5000 <|> do {\n          let msg : format := format!\"parse_itactic failed on `{req.tac}`\",\n          interaction_monad.mk_exception msg none <$> tactic.read\n      }\n    },\n    match result_with_string with\n    -- `have` was successful.\n    | interaction_monad.result.success _ ts' := do {\n        -- Narrow the tactic state to the initial goal with assumption.\n        ts_assumed \u2190 (state_t.lift \u2218 io.run_tactic'') $ do {\n          tactic.write ts',\n          (g1 :: gs) \u2190 tactic.get_goals,\n          tactic.set_goals gs,\n          -- We need to revert all hypotheses, otherwise proof finalization will complain with\n          -- unknown variables.\n          tactic.revert_all,\n          tactic.read\n        },\n        -- Create a new search id, this is required so that the final check are only run on the\n        -- \"assumed\" tactic state (tactic state with additional assumption only).\n        let sid := \u03c3.get_next_sid,\n        modify $ \u03bb \u03c3, \u03c3.incr_next_sid,\n\n        tsid \u2190 record_ts sid ts_assumed (some \u27e8req.tsid, req.tac\u27e9),\n        ts_str \u2190 (state_t.lift \u2218 io.run_tactic'') $ postprocess_tactic_state ts_assumed,\n        pure $ \u27e8sid, tsid, ts_str, none, []\u27e9\n    }\n    | interaction_monad.result.exception fn pos ts' := do {\n      state_t.lift $ do {\n        let msg := (fn.get_or_else (\u03bb _, format.of_string \"n/a\")) (),\n        let err := format! \"conjecture_assume_have_failed: pos={pos} msg={msg}\",\n        pure \u27e8none, none, none, some err.to_string, []\u27e9\n      }\n    }\n    end\n  }\n  end\n}\n\nmeta def handle_parse_failed\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n    -- A little hack that use `req` to pass error message\n    let err := format! \"parse_failed: data={req.sid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n\nmeta def handle_run_tac\n  (req : LeanREPLRequest)\n  : LeanREPL LeanREPLResponse := do {\n  \u03c3 \u2190 get,\n  match (\u03c3.get_ts req.sid req.tsid) with\n  -- Received an unknown search id, return an error.\n  | none := do {\n    let err := format! \"unknown_id: search_id={req.sid} tactic_state_id={req.tsid}\",\n    pure \u27e8none, none, none, some err.to_string, []\u27e9\n  }\n  -- The tactic state was retrieved from the state.\n  | (some ts) := do {\n    -- Set the tactic state and try to apply the tactic.\n    result_with_string \u2190 state_t.lift $ io.run_tactic'' $ do {\n      tactic.write ts,\n      get_tac_and_capture_result req.tac 5000 <|> do {\n          let msg : format := format!\"parse_itactic failed on `{req.tac}`\",\n          interaction_monad.mk_exception msg none <$> tactic.read\n      }\n    },\n    match result_with_string with\n    -- The tactic application was successful.\n    | interaction_monad.result.success _ ts' := do {\n        n \u2190 (state_t.lift \u2218 io.run_tactic'') $ do {\n          tactic.write ts',\n          tactic.num_goals\n        },\n        -- monad_lift $ io.run_tactic'' $ tactic.trace format! \"REMAINING SUBGOALS: {n}\",\n        match n with\n        -- There is no more subgoals, check that the produced proof is valid.\n        | 0 := do {\n          finalize_proof req ts'\n        }\n        -- There are remaining subgoals, return the updated tactic state.\n        | n := do {\n          tsid \u2190 record_ts req.sid ts' (some \u27e8req.tsid, req.tac\u27e9),\n          ts_str \u2190 (state_t.lift \u2218 io.run_tactic'') $ postprocess_tactic_state ts',\n          pure $ \u27e8req.sid, tsid, ts_str, none, []\u27e9\n        }\n        end\n      }\n    -- The tactic application failed, potentially return an error with the failure message.\n    | interaction_monad.result.exception fn pos ts' := do {\n        -- Some tactics such as linarith fail but result in a tactic state with no goals. Check if\n        -- that's the case and finalize the proof, otherwise error.\n        n \u2190 (state_t.lift \u2218 io.run_tactic'') $ do {\n          tactic.write ts',\n          tactic.num_goals\n        },\n        -- monad_lift $ io.run_tactic'' $ tactic.trace format! \"REMAINING SUBGOALS: {n}\",\n        match n with\n        -- There is no more subgoals, check that the produced proof is valid.\n        | 0 := do {\n          finalize_proof req ts'\n        }\n        -- There are remaining subgoals, return the error.\n        | _ := do {\n          state_t.lift $ do {\n            let msg := (fn.get_or_else (\u03bb _, format.of_string \"n/a\")) (),\n            let err := format! \"gen_tac_and_capture_res_failed: pos={pos} msg={msg}\",\n            pure \u27e8none, none, none, some err.to_string, []\u27e9\n          }\n        }\n        end\n      }\n    end\n  }\n  end\n}\n\n\nmeta def handle_request (req : LeanREPLRequest) : LeanREPL LeanREPLResponse :=\nmatch req.cmd with\n| \"run_tac\" := handle_run_tac req\n| \"init_search\" := handle_init_search req\n| \"clear_search\" := handle_clear_search req\n| \"conjecture_set\" := handle_conjecture req\n| \"conjecture_assume\" := handle_assume req\n| \"shrink_proof\" := handle_shrink_proof req\n| \"try_finish\" := handle_try_finish req\n| \"parse_failed\" := handle_parse_failed req\n| exc := state_t.lift $ io.fail' format! \"[fatal] unknown_command: cmd={exc}\"\nend\n\n\nmeta def parse_request (msg : string) : io LeanREPLRequest := do {\n  match json.parse msg with\n  | (some json_msg) := io.run_tactic'' $ has_from_json.from_json json_msg\n  | none := pure \u27e8\"parse_failed\", msg, \"\", \"\", \"\", \"\", \"\"\u27e9\n  end\n}\n\n\nmeta def loop : LeanREPL unit := do {\n  req \u2190 (state_t.lift $ io.get_line >>= parse_request),\n  res \u2190 handle_request req,\n  state_t.lift $ io.put_str_ln' $ format! \"{(json.unparse \u2218 LeanREPLResponse.to_json) res}\"\n}\n\nmeta def main : io unit := do {\n  state_t.run loop.forever \u27e8dict.empty, 0\u27e9 $> ()\n}\n\nend main\n", "meta": {"author": "openai", "repo": "lean-gym", "sha": "1585ac4d2e56a1ceb72243ce859645b9d0069d34", "save_path": "github-repos/lean/openai-lean-gym", "path": "github-repos/lean/openai-lean-gym/lean-gym-1585ac4d2e56a1ceb72243ce859645b9d0069d34/src/repl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.023689470997815976, "lm_q1q2_score": 0.0062985677563837045}}
{"text": "example : Nat := Id.run do\n  for _ in [1:10] do\n    assert! true\n    if false then return 0\n  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/1420.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.12765262532179067, "lm_q2_score": 0.04885778139204432, "lm_q1q2_score": 0.006236824062092589}}
{"text": "import tactic.replacer\n\nopen tactic\n\ndef_replacer sneaky\n\nexample : true :=\nbegin\n  success_if_fail { sneaky },\n  trivial\nend\n\n@[sneaky] meta def sneaky' : tactic unit := `[skip]\n\nexample : true :=\nbegin\n  sneaky,\n  guard_target true,\n  trivial\nend\n\n@[sneaky] meta def sneaky'' := `[trivial]\n\nexample : true :=\nbegin\n  sneaky\nend\n\n@[sneaky] meta def sneaky''' (old : tactic unit) := old >> `[trivial]\n\nexample : true \u2227 true :=\nbegin\n  split,\n  sneaky\nend\n\ndef_replacer transform : \u2115 \u2192 tactic \u2115\n\nrun_cmd success_if_fail (transform 1)\n\n@[transform] meta def transform' (n : \u2115) : tactic \u2115 :=\nreturn (n+1)\n\nrun_cmd do n \u2190 transform 2, guard (n = 3)\n\n@[transform] meta def transform'' (n : \u2115) : tactic \u2115 :=\nreturn (n * n)\n\nrun_cmd do n \u2190 transform 2, guard (n = 4)\n\n@[transform] meta def transform''' (n : \u2115) (old : tactic \u2115) : tactic \u2115 :=\ndo n' \u2190 old, return (n' * n')\n\nrun_cmd do n \u2190 transform 2, guard (n = 16)\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/replacer.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262224883771, "lm_q2_score": 0.03161876612799809, "lm_q1q2_score": 0.006223402296717314}}
{"text": "structure Foo where\n  foo : Nat\n\nexample (f : Foo) : f\n                   --^ insert: .\n                    --^ textDocument/completion\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/editCompletion.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296424019782926, "lm_q2_score": 0.04672495763050702, "lm_q1q2_score": 0.00621274848961613}}
{"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, Jannis Limperg\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.type_context\nimport Mathlib.Lean3Lib.init.meta.rewrite_tactic\nimport Mathlib.Lean3Lib.init.meta.simp_tactic\nimport Mathlib.Lean3Lib.init.meta.smt.congruence_closure\nimport Mathlib.Lean3Lib.init.control.combinators\nimport Mathlib.Lean3Lib.init.meta.interactive_base\nimport Mathlib.Lean3Lib.init.meta.derive\nimport Mathlib.Lean3Lib.init.meta.match_tactic\nimport Mathlib.Lean3Lib.init.meta.congr_tactic\nimport Mathlib.Lean3Lib.init.meta.case_tag\n\nuniverses l u v \n\nnamespace Mathlib\n\nnamespace tactic\n\n\n/- allows metavars -/\n\n/- allow metavars and no subgoals -/\n\n/- doesn't allows metavars -/\n\n/- Auxiliary version of i_to_expr for apply-like tactics.\n   This is a workaround for comment\n      https://github.com/leanprover/lean/issues/1342#issuecomment-307912291\n   at issue #1342.\n\n   In interactive mode, given a tactic\n\n        apply f\n\n   we want the apply tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n\n   Before we added `i_to_expr_for_apply`, the tactic\n\n       apply le_antisymm\n\n   would first elaborate `le_antisymm`, and create\n\n       @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4\n\n   The type class resolution problem\n        ?m_2 : weak_order ?m_1\n   by the elaborator since ?m_1 is not assigned yet, and the problem is\n   discarded.\n\n   Then, we would invoke `apply_core`, which would create two\n   new metavariables for the explicit arguments, and try to unify the resulting\n   type with the current target. After the unification,\n   the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost\n   the information about the pending type class resolution problem.\n\n   With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,\n   the apply_core tactic creates all metavariables, and solves the ones that\n   can be solved by type class resolution.\n\n   Another possible fix: we modify the elaborator to return pending\n   type class resolution problems, and store them in the tactic_state.\n-/\n\nnamespace interactive\n\n\n/--\nitactic: parse a nested \"interactive\" tactic. That is, parse\n  `{` tactic `}`\n-/\n/--\nIf the current goal is a Pi/forall `\u2200 x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.\n\nIf the goal is an arrow `t \u2192 u`, then it puts `h : t` in the local context and the new goal target is `u`.\n\nIf the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.\n-/\n/--\nSimilar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.\n\nThe variant `intros h\u2081 ... h\u2099` introduces `n` new hypotheses using the given identifiers to name them.\n-/\n/--\nThe tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.\n\nExamples:\n```\nexample : \u2200 a b : nat, a = b \u2192 b = a :=\nbegin\n  introv h,\n  exact h.symm\nend\n```\nThe state after `introv h` is\n```\na b : \u2115,\nh : a = b\n\u22a2 b = a\n```\n\n```\nexample : \u2200 a b : nat, a = b \u2192 \u2200 c, b = c \u2192 a = c :=\nbegin\n  introv h\u2081 h\u2082,\n  exact h\u2081.trans h\u2082\nend\n```\nThe state after `introv h\u2081 h\u2082` is\n```\na b : \u2115,\nh\u2081 : a = b,\nc : \u2115,\nh\u2082 : b = c\n\u22a2 a = c\n```\n-/\n/-- Parse a current name and new name for `rename`. -/\n/-- Parse the arguments of `rename`. -/\n/--\nRename one or more local hypotheses. The renamings are given as follows:\n\n```\nrename x y             -- rename x to y\nrename x \u2192 y           -- ditto\nrename [x y, a b]      -- rename x to y and a to b\nrename [x \u2192 y, a \u2192 b]  -- ditto\n```\n\nNote that if there are multiple hypotheses called `x` in the context, then\n`rename x y` will rename *all* of them. If you want to rename only one, use\n`dedup` first.\n-/\n/--\nThe `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.\n\nThe `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.\n-/\n/--\nSimilar to the `apply` tactic, but does not reorder goals.\n-/\n/--\nSimilar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution.\n-/\n/--\nSimilar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object.\n-/\n/--\nSimilar to the `apply` tactic, but uses matching instead of unification.\n`apply_match t` is equivalent to `apply_with t {unify := ff}`\n-/\n/--\nThis tactic tries to close the main goal `... \u22a2 t` by generating a term of type `t` using type class resolution.\n-/\n/--\nThis tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.\n\nNote that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat \u2192 Prop)`.\n-/\n/--\nThis tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.\n-/\n/-- Try to apply `assumption` to all goals. -/\n/--\n`change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.\n\n`change u at h` will change a local hypothesis to `u`.\n\n`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.\n-/\n/--\nThis tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.\n-/\n/--\nLike `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.\n-/\n/--\nA synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.\n-/\n/--\n`revert h\u2081 ... h\u2099` applies to any goal with hypotheses `h\u2081` ... `h\u2099`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.\n-/\n/- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.\n   This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.\n   Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.\n   Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/\n\n-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations\n\n/--\n`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`\u2190` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.\n\n`rewrite [e\u2081, ..., e\u2099]` applies the given rules sequentially.\n\n`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `\u22a2` or `|-` can also be used, to signify the target of the goal.\n-/\n/--\nAn abbreviation for `rewrite`.\n-/\n/--\n`rewrite` followed by `assumption`.\n-/\n/--\nA variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.\n-/\n/--\nAn abbreviation for `erewrite`.\n-/\n/--\nReturns the unique names of all hypotheses (local constants) in the context.\n-/\n/--\nReturns all hypotheses (local constants) from the context except those whose\nunique names are in `hyp_uids`.\n-/\n/--\nApply `t` to the main goal and revert any new hypothesis in the generated goals.\nIf `t` is a supported tactic or chain of supported tactics (e.g. `induction`,\n`cases`, `apply`, `constructor`), the generated goals are also tagged with case\ntags. You can then use `case` to focus such tagged goals.\n\nTwo typical uses of `with_cases`:\n\n1. Applying a custom eliminator:\n\n   ```\n   lemma my_nat_rec :\n     \u2200 n {P : \u2115 \u2192 Prop} (zero : P 0) (succ : \u2200 n, P n \u2192 P (n + 1)), P n := ...\n\n   example (n : \u2115) : n = n :=\n   begin\n     with_cases { apply my_nat_rec n },\n     case zero { refl },\n     case succ : m ih { refl }\n   end\n   ```\n\n2. Enabling the use of `case` after a chain of case-splitting tactics:\n\n   ```\n   example (n m : \u2115) : unit :=\n   begin\n     with_cases { cases n; induction m },\n     case nat.zero nat.zero { exact () },\n     case nat.zero nat.succ : k { exact () },\n     case nat.succ nat.zero : i { exact () },\n     case nat.succ nat.succ : k i ih_i { exact () }\n   end\n   ```\n-/\n/--\n`generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.\n\n`generalize h : e = x` in addition registers the hypothesis `h : e = x`.\n-/\n/--\n  Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag`\n  is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was\n  applied. `rs` should contain, for each subgoal, the constructor name\n  associated with that goal and the hypotheses that were introduced.\n-/\n/--\nAssuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih\u2081 : P a \u2192 Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih\u2081` ire chosen automatically.\n\n`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.\n\n`induction e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.\n\n`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables\n\n`induction e generalizing z\u2081 ... z\u2099`, where `z\u2081 ... z\u2099` are variables in the local context, generalizes over `z\u2081 ... z\u2099` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.\n\n`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.\n-/\n/--\nFocuses on a goal ('case') generated by `induction`, `cases` or `with_cases`.\n\nThe goal is selected by giving one or more names which must match exactly one\ngoal. A goal is matched if the given names are a suffix of its goal tag.\nAdditionally, each name in the sequence can be abbreviated to a suffix of the\ncorresponding name in the goal tag. Thus, a goal with tag\n```\nnat.zero, list.nil\n```\ncan be selected with any of these invocations (among others):\n```\ncase nat.zero list.nil {...}\ncase nat.zero nil      {...}\ncase zero     nil      {...}\ncase          nil      {...}\n```\n\nAdditionally, the form\n```\ncase C : N\u2080 ... N\u2099 {...}\n```\ncan be used to rename hypotheses introduced by the preceding\n`cases`/`induction`/`with_cases`, using the names `N\u1d62`. For example:\n```\nexample (xs : list \u2115) : xs = xs :=\nbegin\n  induction xs,\n  case nil { reflexivity },\n  case cons : x xs ih {\n    -- x : \u2115, xs : list \u2115, ih : xs = xs\n    reflexivity }\nend\n```\n\nNote that this renaming functionality only work reliably *directly after* an\n`induction`/`cases`/`with_cases`. If you need to perform additional work after\nan `induction` or `cases` (e.g. introduce hypotheses in all goals), use\n`with_cases`.\n-/\n/-\nTODO `case` could be generalised to work with zero names as well. The form\n\n  case : x y z { ... }\n\nwould select the first goal (or the first goal with a case tag), renaming\nhypotheses to `x, y, z`. The renaming functionality would be available only if\nthe goal has a case tag.\n-/\n\n/--\nAssuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 \u2192 Q n`, and one goal with target `\u2200 (a : \u2115), (\u03bb (w : \u2115), n = w \u2192 Q n) (nat.succ a)`. Here the name `a` is chosen automatically.\n-/\n/--\nAssuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.\n\nFor example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.\n\n`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.\n\n`cases e with y\u2081 ... y\u2099`, where `e` is a variable or an expression, specifies that the sequence of names `y\u2081 ... y\u2099` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.\n\n`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.\n-/\n/--\n`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.\n`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.\n`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_matching* [_ \u2228 _, _ \u2227 _]\n```\n-/\n/-- Shorthand for `cases_matching` -/\n/--\n`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`\n`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`\n`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`\n`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.\n\nExample: The following tactic destructs all conjunctions and disjunctions in the current goal.\n```\ncases_type* or and\n```\n-/\n/--\nTries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.\n-/\n/--\nCloses the main goal using `sorry`.\n-/\n/--\nCloses the main goal using `sorry`.\n-/\n/--\nThe contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.\n-/\n/--\n`iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.\n\n`iterate n { t }` applies `t` `n` times.\n-/\n/--\n`repeat { t }` applies `t` to each goal. If the application succeeds,\nthe tactic is applied recursively to all the generated subgoals until it eventually fails.\nThe recursion stops in a subgoal when the tactic has failed to make progress.\nThe tactic `repeat { t }` never fails.\n-/\n/--\n`try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.\n-/\n/--\nA do-nothing tactic that always succeeds.\n-/\n/--\n`solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.\n-/\n/--\n`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.\n-/\n/--\n`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.\n-/\n/--\n`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.\n-/\n/--\n`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.\n-/\n/--\nAssuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.\n\n`assume (h\u2081 : t\u2081) ... (h\u2099 : t\u2099)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.\n-/\n/--\n`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\n/--\n`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.\n\n`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.\n\nIf `h` is omitted, the name `this` is used.\n-/\n/--\n`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.\n-/\n/--\nThis tactic displays the current state in the tracing buffer.\n-/\n/--\n`trace a` displays `a` in the tracing buffer.\n-/\n/--\n`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.\n\n`existsi [e\u2081, ..., e\u2099]` iteratively does the same for each expression in the list.\n-/\n/--\nThis tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.\n-/\n/--\nSimilar to `constructor`, but only non-dependent premises are added as new goals.\n-/\n/--\nApplies the first constructor when the type of the target is an inductive data type with two constructors.\n-/\n/--\nApplies the second constructor when the type of the target is an inductive data type with two constructors.\n-/\n/--\nApplies the constructor when the type of the target is an inductive data type with one constructor.\n-/\n/--\nReplaces the target of the main goal by `false`.\n-/\n/--\nThe `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t\u2081)` and `(c t\u2082)` are two terms that are equal then  `t\u2081` and `t\u2082` are equal too.\n\nIf `q` is a proof of a statement of conclusion `t\u2081 = t\u2082`, then injection applies injectivity to derive the equality of all arguments of `t\u2081` and `t\u2082` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t\u2081` and `t\u2082` should be constructor applications of the same constructor.\n\nGiven `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h\u2081 h\u2082` uses the names `h\u2081` and `h\u2082` to name the new hypotheses.\n-/\n/--\n`injections with h\u2081 ... h\u2099` iteratively applies `injection` to hypotheses using the names `h\u2081 ... h\u2099`.\n-/\nend interactive\n\n\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`.\n  This version fails when an argument of the form `simp_arg_type.symm_expr`\n  is included, so that `simp`-like tactics that do not (yet) support backwards rewriting\n  should properly report an error but function normally on other inputs.\n-/\n/-- Decode a list of `simp_arg_type` into lists for each type.\n\n  This is the newer version of `decode_simp_arg_list`,\n  and has a new name for backwards compatibility.\n  This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`.\n-/\nnamespace interactive\n\n\n/--\nThe `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.\n\n`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.\n\n`simp [h\u2081 h\u2082 ... h\u2099]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h\u1d62`'s, where the `h\u1d62`'s are expressions. If `h\u1d62` is preceded by left arrow (`\u2190` or `<-`), the simplification is performed in the reverse direction. If an `h\u1d62` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.\n\n`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.\n\n`simp *` is a shorthand for `simp [*]`.\n\n`simp only [h\u2081 h\u2082 ... h\u2099]` is like `simp [h\u2081 h\u2082 ... h\u2099]` but does not use `[simp]` lemmas\n\n`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id\u1d62`.\n\n`simp at h\u2081 h\u2082 ... h\u2099` simplifies the non-dependent hypotheses `h\u2081 : T\u2081` ... `h\u2099 : T\u2099`. The tactic fails if the target or another hypothesis depends on one of them. The token `\u22a2` or `|-` can be added to the list to include the target.\n\n`simp at *` simplifies all the hypotheses and the target.\n\n`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.\n\n`simp with attr\u2081 ... attr\u2099` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr\u2081]`, ..., `[attr\u2099]` or `[simp]`.\n-/\n/--\nJust construct the simp set and trace it. Used for debugging.\n-/\n/--\n`simp_intros h\u2081 h\u2082 ... h\u2099` is similar to `intros h\u2081 h\u2082 ... h\u2099` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.\n\nAs with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.\n-/\n/--\n`dsimp` is similar to `simp`, except that it only uses definitional equalities.\n-/\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.\n-/\n/--\nShorter name for the tactic `reflexivity`.\n-/\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.\n-/\n/--\nThis tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.\n\n`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.\n-/\n/--\nProves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.\n-/\n/--\nAn abbreviation for `ac_reflexivity`.\n-/\n/--\nTries to prove the main goal using congruence closure.\n-/\n/--\nGiven hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.\n-/\n/--\nApply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.\n-/\n/--\n`clear h\u2081 ... h\u2099` tries to clear each hypothesis `h\u1d62` from the local context.\n-/\n/--\nSimilar to `unfold`, but only uses definitional equalities.\n-/\n/--\nSimilar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.\n-/\n/--\nThis tactic unfolds all structure projections.\n-/\nend interactive\n\n\nstructure unfold_config extends simp_config where\n\nnamespace interactive\n\n\n/--\nGiven defined constants `e\u2081 ... e\u2099`, `unfold e\u2081 ... e\u2099` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.\n\nAs with `simp`, the `at` modifier can be used to specify locations for the unfolding.\n-/\n/--\nSimilar to `unfold`, but does not iterate the unfolding.\n-/\n/--\nIf the target of the main goal is an `opt_param`, assigns the default value.\n-/\n/--\nIf the target of the main goal is an `auto_param`, executes the associated tactic.\n-/\n/--\nFails if the given tactic succeeds.\n-/\n/--\nSucceeds if the given tactic fails.\n-/\n/--\n`guard_target t` fails if the target of the main goal is not `t`.\nWe use this tactic for writing tests.\n-/\n/--\n`guard_hyp h : t` fails if the hypothesis `h` does not have type `t`.\nWe use this tactic for writing tests.\n-/\n/--\n`match_target t` fails if target does not match pattern `t`.\n-/\n/--\n`by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and\n`h : \u00ac p` in the second branch. You can specify the name of the new hypothesis using the syntax\n`by_cases h : p`.\n-/\n/--\nApply function extensionality and introduce new hypotheses.\nThe tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to\n```\n  |-  ((fun x, ...) = (fun x, ...))\n```\nThe variant `funext h\u2081 ... h\u2099` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.\n-/\n/--\nIf the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contradiction h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\n/--\nIf the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : \u00ac p`. `by_contra h` can be used to name the hypothesis `h : \u00ac p`.\n\nThis tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.\n-/\n/--\nType check the given expression, and trace its type.\n-/\n/--\nFail if there are unsolved goals.\n-/\n/--\n`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.\n-/\n/--\nThe tactic `specialize h a\u2081 ... a\u2099` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a\u2081` ... `a\u2099`. The tactic adds a new hypothesis with the same name `h := h a\u2081 ... a\u2099` and tries to clear the previous one.\n-/\nend interactive\n\n\nend tactic\n\n\n/- See add_interactive -/\n\n/--\nCopy a list of meta definitions in the current namespace to tactic.interactive.\n\nThis command is useful when we want to update tactic.interactive without closing the current namespace.\n-/\n/--\nRenames hypotheses with the same name.\n-/\nnamespace tactic\n\n\n/- Helper tactic for `mk_inj_eq -/\n\n/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.\n   These lemmas are automatically generated by the equation compiler.\n   Example:\n   ```\n   list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 \u2227 t1 = t2) :=\n   by mk_inj_eq\n   ```\n-/\n\nend tactic\n\n\n/- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/\n\ntheorem sum.inl.inj_eq {\u03b1 : Type u} (\u03b2 : Type v) (a\u2081 : \u03b1) (a\u2082 : \u03b1) :\n    sum.inl a\u2081 = sum.inl a\u2082 = (a\u2081 = a\u2082) :=\n  propext\n    { mp := fun (h : sum.inl a\u2081 = sum.inl a\u2082) => sum.inl.inj h,\n      mpr :=\n        fun (\u1fb0 : a\u2081 = a\u2082) =>\n          (fun (val val_1 : \u03b1) (e_2 : val = val_1) => congr_arg sum.inl e_2) a\u2081 a\u2082 \u1fb0 }\n\ntheorem sum.inr.inj_eq (\u03b1 : Type u) {\u03b2 : Type v} (b\u2081 : \u03b2) (b\u2082 : \u03b2) :\n    sum.inr b\u2081 = sum.inr b\u2082 = (b\u2081 = b\u2082) :=\n  sorry\n\ntheorem psum.inl.inj_eq {\u03b1 : Sort u} (\u03b2 : Sort v) (a\u2081 : \u03b1) (a\u2082 : \u03b1) :\n    psum.inl a\u2081 = psum.inl a\u2082 = (a\u2081 = a\u2082) :=\n  propext\n    { mp := fun (h : psum.inl a\u2081 = psum.inl a\u2082) => psum.inl.inj h,\n      mpr :=\n        fun (\u1fb0 : a\u2081 = a\u2082) =>\n          (fun (val val_1 : \u03b1) (e_2 : val = val_1) => congr_arg psum.inl e_2) a\u2081 a\u2082 \u1fb0 }\n\ntheorem psum.inr.inj_eq (\u03b1 : Sort u) {\u03b2 : Sort v} (b\u2081 : \u03b2) (b\u2082 : \u03b2) :\n    psum.inr b\u2081 = psum.inr b\u2082 = (b\u2081 = b\u2082) :=\n  sorry\n\ntheorem sigma.mk.inj_eq {\u03b1 : Type u} {\u03b2 : \u03b1 \u2192 Type v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) :\n    sigma.mk a\u2081 b\u2081 = sigma.mk a\u2082 b\u2082 = (a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082) :=\n  sorry\n\ntheorem psigma.mk.inj_eq {\u03b1 : Sort u} {\u03b2 : \u03b1 \u2192 Sort v} (a\u2081 : \u03b1) (b\u2081 : \u03b2 a\u2081) (a\u2082 : \u03b1) (b\u2082 : \u03b2 a\u2082) :\n    psigma.mk a\u2081 b\u2081 = psigma.mk a\u2082 b\u2082 = (a\u2081 = a\u2082 \u2227 b\u2081 == b\u2082) :=\n  sorry\n\ntheorem subtype.mk.inj_eq {\u03b1 : Sort u} {p : \u03b1 \u2192 Prop} (a\u2081 : \u03b1) (h\u2081 : p a\u2081) (a\u2082 : \u03b1) (h\u2082 : p a\u2082) :\n    { val := a\u2081, property := h\u2081 } = { val := a\u2082, property := h\u2082 } = (a\u2081 = a\u2082) :=\n  sorry\n\ntheorem option.some.inj_eq {\u03b1 : Type u} (a\u2081 : \u03b1) (a\u2082 : \u03b1) : some a\u2081 = some a\u2082 = (a\u2081 = a\u2082) :=\n  propext\n    { mp := fun (h : some a\u2081 = some a\u2082) => option.some.inj h,\n      mpr :=\n        fun (\u1fb0 : a\u2081 = a\u2082) =>\n          (fun (val val_1 : \u03b1) (e_1 : val = val_1) => congr_arg some e_1) a\u2081 a\u2082 \u1fb0 }\n\ntheorem list.cons.inj_eq {\u03b1 : Type u} (h\u2081 : \u03b1) (t\u2081 : List \u03b1) (h\u2082 : \u03b1) (t\u2082 : List \u03b1) :\n    h\u2081 :: t\u2081 = h\u2082 :: t\u2082 = (h\u2081 = h\u2082 \u2227 t\u2081 = t\u2082) :=\n  sorry\n\ntheorem nat.succ.inj_eq (n\u2081 : \u2115) (n\u2082 : \u2115) : Nat.succ n\u2081 = Nat.succ n\u2082 = (n\u2081 = n\u2082) :=\n  propext\n    { mp := fun (h : Nat.succ n\u2081 = Nat.succ n\u2082) => nat.succ.inj h,\n      mpr :=\n        fun (\u1fb0 : n\u2081 = n\u2082) => (fun (n n_1 : \u2115) (e_1 : n = n_1) => congr_arg Nat.succ e_1) n\u2081 n\u2082 \u1fb0 }\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/interactive_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713267309572335, "lm_q2_score": 0.03308598136812591, "lm_q1q2_score": 0.0061914681354127}}
{"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 {\u03b5 : Type u}\n\n@[always_inline, inline]\nprotected def pure (a : \u03b1) : Except \u03b5 \u03b1 :=\n  Except.ok a\n\n@[always_inline, inline]\nprotected def map (f : \u03b1 \u2192 \u03b2) : Except \u03b5 \u03b1 \u2192 Except \u03b5 \u03b2\n  | Except.error err => Except.error err\n  | Except.ok v => Except.ok <| f v\n\n@[simp] theorem map_id : Except.map (\u03b5 := \u03b5) (\u03b1 := \u03b1) (\u03b2 := \u03b1) 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 : \u03b5 \u2192 \u03b5') : Except \u03b5 \u03b1 \u2192 Except \u03b5' \u03b1\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 \u03b5 \u03b1) (f : \u03b1 \u2192 Except \u03b5 \u03b2) : Except \u03b5 \u03b2 :=\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 \u03b5 \u03b1 \u2192 Bool\n  | Except.ok _    => true\n  | Except.error _ => false\n\nabbrev isOk : Except \u03b5 \u03b1 \u2192 Bool := Except.toBool\n\n@[always_inline, inline]\nprotected def toOption : Except \u03b5 \u03b1 \u2192 Option \u03b1\n  | Except.ok a    => some a\n  | Except.error _ => none\n\n@[always_inline, inline]\nprotected def tryCatch (ma : Except \u03b5 \u03b1) (handle : \u03b5 \u2192 Except \u03b5 \u03b1) : Except \u03b5 \u03b1 :=\n  match ma with\n  | Except.ok a    => Except.ok a\n  | Except.error e => handle e\n\ndef orElseLazy (x : Except \u03b5 \u03b1) (y : Unit \u2192 Except \u03b5 \u03b1) : Except \u03b5 \u03b1 :=\n  match x with\n  | Except.ok a    => Except.ok a\n  | Except.error _ => y ()\n\n@[always_inline]\ninstance : Monad (Except \u03b5) where\n  pure := Except.pure\n  bind := Except.bind\n  map  := Except.map\n\nend Except\n\ndef ExceptT (\u03b5 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) : Type v :=\n  m (Except \u03b5 \u03b1)\n\n@[always_inline, inline]\ndef ExceptT.mk {\u03b5 : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type u} (x : m (Except \u03b5 \u03b1)) : ExceptT \u03b5 m \u03b1 := x\n\n@[always_inline, inline]\ndef ExceptT.run {\u03b5 : Type u} {m : Type u \u2192 Type v} {\u03b1 : Type u} (x : ExceptT \u03b5 m \u03b1) : m (Except \u03b5 \u03b1) := x\n\nnamespace ExceptT\n\nvariable {\u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m]\n\n@[always_inline, inline]\nprotected def pure {\u03b1 : Type u} (a : \u03b1) : ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk <| pure (Except.ok a)\n\n@[always_inline, inline]\nprotected def bindCont {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : Except \u03b5 \u03b1 \u2192 m (Except \u03b5 \u03b2)\n  | Except.ok a    => f a\n  | Except.error e => pure (Except.error e)\n\n@[always_inline, inline]\nprotected def bind {\u03b1 \u03b2 : Type u} (ma : ExceptT \u03b5 m \u03b1) (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : ExceptT \u03b5 m \u03b2 :=\n  ExceptT.mk <| ma >>= ExceptT.bindCont f\n\n@[always_inline, inline]\nprotected def map {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1) : ExceptT \u03b5 m \u03b2 :=\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 {\u03b1 : Type u} (t : m \u03b1) : ExceptT \u03b5 m \u03b1 :=\n  ExceptT.mk <| Except.ok <$> t\n\n@[always_inline]\ninstance : MonadLift (Except \u03b5) (ExceptT \u03b5 m) := \u27e8fun e => ExceptT.mk <| pure e\u27e9\ninstance : MonadLift m (ExceptT \u03b5 m) := \u27e8ExceptT.lift\u27e9\n\n@[always_inline, inline]\nprotected def tryCatch {\u03b1 : Type u} (ma : ExceptT \u03b5 m \u03b1) (handle : \u03b5 \u2192 ExceptT \u03b5 m \u03b1) : ExceptT \u03b5 m \u03b1 :=\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 \u03b5 m) := \u27e8fun f x => f x\u27e9\n\n@[always_inline]\ninstance : Monad (ExceptT \u03b5 m) where\n  pure := ExceptT.pure\n  bind := ExceptT.bind\n  map  := ExceptT.map\n\n@[always_inline, inline]\nprotected def adapt {\u03b5' \u03b1 : Type u} (f : \u03b5 \u2192 \u03b5') : ExceptT \u03b5 m \u03b1 \u2192 ExceptT \u03b5' m \u03b1 := fun x =>\n  ExceptT.mk <| Except.mapError f <$> x\n\nend ExceptT\n\n@[always_inline]\ninstance (m : Type u \u2192 Type v) (\u03b5\u2081 : Type u) (\u03b5\u2082 : Type u) [Monad m] [MonadExceptOf \u03b5\u2081 m] : MonadExceptOf \u03b5\u2081 (ExceptT \u03b5\u2082 m) where\n  throw e := ExceptT.mk <| throwThe \u03b5\u2081 e\n  tryCatch x handle := ExceptT.mk <| tryCatchThe \u03b5\u2081 x handle\n\n@[always_inline]\ninstance (m : Type u \u2192 Type v) (\u03b5 : Type u) [Monad m] : MonadExceptOf \u03b5 (ExceptT \u03b5 m) where\n  throw e := ExceptT.mk <| pure (Except.error e)\n  tryCatch := ExceptT.tryCatch\n\ninstance [Monad m] [Inhabited \u03b5] : Inhabited (ExceptT \u03b5 m \u03b1) where\n  default := throw default\n\ninstance (\u03b5) : MonadExceptOf \u03b5 (Except \u03b5) where\n  throw    := Except.error\n  tryCatch := Except.tryCatch\n\nnamespace MonadExcept\nvariable {\u03b5 : Type u} {m : Type v \u2192 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 \u03b5 m] {\u03b1 : Type v} (t\u2081 t\u2082 : m \u03b1) (useFirstEx := true) : m \u03b1 :=\n  tryCatch t\u2081 fun e\u2081 => tryCatch t\u2082 fun e\u2082 => throw (if useFirstEx then e\u2081 else e\u2082)\n\nend MonadExcept\n\n@[always_inline, inline]\ndef observing {\u03b5 \u03b1 : Type u} {m : Type u \u2192 Type v} [Monad m] [MonadExcept \u03b5 m] (x : m \u03b1) : m (Except \u03b5 \u03b1) :=\n  tryCatch (do let a \u2190 x; pure (Except.ok a)) (fun ex => pure (Except.error ex))\n\ndef liftExcept [MonadExceptOf \u03b5 m] [Pure m] : Except \u03b5 \u03b1 \u2192 m \u03b1\n  | Except.ok a    => pure a\n  | Except.error e => throw e\n\ninstance (\u03b5 : Type u) (m : Type u \u2192 Type v) [Monad m] : MonadControl m (ExceptT \u03b5 m) where\n  stM        := Except \u03b5\n  liftWith f := liftM <| f fun x => x.run\n  restoreM x := x\n\nclass MonadFinally (m : Type u \u2192 Type v) where\n  /-- `tryFinally' x f` runs `x` and then the \"finally\" computation `f`.\n  When `x` succeeds with `a : \u03b1`, `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' {\u03b1 \u03b2} : m \u03b1 \u2192 (Option \u03b1 \u2192 m \u03b2) \u2192 m (\u03b1 \u00d7 \u03b2)\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 \u2192 Type v} {\u03b1 \u03b2 : Type u} [MonadFinally m] [Functor m] (x : m \u03b1) (finalizer : m \u03b2) : m \u03b1 :=\n  let y := tryFinally' x (fun _ => finalizer)\n  (\u00b7.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 \u2192 Type v} {\u03b5 : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT \u03b5 m) where\n  tryFinally' := fun x h => ExceptT.mk do\n    let r \u2190 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": "/-\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.basic\nimport tactic.simpa\n\nopen interactive interactive.types lean.parser\n\nprivate meta def loc.to_string_aux : option name \u2192 string\n| none := \"\u22a2\"\n| (some x) := to_string x\n\n/-- pretty print a `loc` -/\nmeta def loc.to_string : loc \u2192 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\n/-- shift `pos` `n` columns to the left -/\nmeta def pos.move_left (p : pos) (n : \u2115) : pos :=\n{ line := p.line, column := p.column - n }\n\nnamespace tactic\n\nopen list\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\nmeta def struct_inst : lean.parser pexpr :=\ndo tk \"{\",\n   ls \u2190 sep_by (skip_info (tk \",\"))\n     ( sum.inl <$> (tk \"..\" *> texpr) <|>\n       sum.inr <$> (prod.mk <$> ident <* tk \":=\" <*> texpr)),\n   tk \"}\",\n   let (srcs,fields) := partition_map id ls,\n   let (names,values) := unzip fields,\n   pure $ pexpr.mk_structure_instance\n     { field_names := names,\n       field_values := values,\n       sources := srcs }\n\n/-- pretty print structure instance -/\nmeta def struct.to_tactic_format (e : pexpr) : tactic format :=\ndo r \u2190 e.get_structure_instance_info,\n   fs \u2190 mzip_with (\u03bb n v,\n     do v \u2190 to_expr v >>= pp,\n        pure $ format!\"{n} := {v}\" )\n     r.field_names r.field_values,\n   let ss := r.sources.map (\u03bb s, format!\" .. {s}\"),\n   let x : format := format.join $ list.intersperse \", \" (fs ++ ss),\n   pure format!\" {{{x}}\"\n\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n@[user_attribute]\nprivate meta def squeeze_loc_attr :\n  user_attribute unit (option (list (pos \u00d7 string \u00d7 list simp_arg_type \u00d7 string))) :=\n{ name := `_squeeze_loc,\n  parser := fail \"this attribute should not be used\",\n  descr := \"table to accumulate multiple `squeeze_simp` suggestions\" }\n\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeeze_loc_attr_carrier := ()\n\nrun_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt\n\n/-- Format a list of arguments for use with `simp` and friends. This omits the\nlist entirely if it is empty. -/\nmeta def render_simp_arg_list : list simp_arg_type \u2192 tactic format\n| [] := pure \"\"\n| args := (++) \" \" <$> to_line_wrap_format <$> args.mmap pp\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. -/\nmeta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type)\n  (at_pos := ff) : tactic unit :=\ndo xs \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier,\n   match xs with\n   | none := do\n     args \u2190 render_simp_arg_list args,\n     if at_pos then\n       @scope_trace _ p.line p.column $\n         \u03bb _, _root_.trace sformat!\"{pre}{args}{post}\" (pure () : tactic unit)\n     else\n       trace sformat!\"{pre}{args}{post}\"\n   | some xs := do\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff\n   end\n\nlocal postfix `?`:9001 := optional\n\n/-- translate a `pexpr` into a `simp` configuration -/\nmeta def parse_config : option pexpr \u2192 tactic (simp_config_ext \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr simp_config_ext e\n             <*> struct.to_tactic_format cfg\n\n/-- translate a `pexpr` into a `dsimp` configuration -/\nmeta def parse_dsimp_config : option pexpr \u2192 tactic (dsimp_config \u00d7 format)\n| none := pure ({}, \"\")\n| (some cfg) :=\n  do e \u2190 to_expr ``(%%cfg : simp_config_ext),\n     fmt \u2190 has_to_tactic_format.to_tactic_format cfg,\n     prod.mk <$> eval_expr dsimp_config e\n             <*> struct.to_tactic_format cfg\n\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\nmeta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool :=\ndo s \u2190 get_proof_state_after tac,\n   pure $ some pr = s\n\nprivate meta def filter_simp_set_aux\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (args : list simp_arg_type) (pr : proof_state) :\n  list simp_arg_type \u2192 list simp_arg_type \u2192\n  list simp_arg_type \u2192 tactic (list simp_arg_type \u00d7 list simp_arg_type)\n| [] ys ds := pure (ys.reverse, ds.reverse)\n| (x :: xs) ys ds :=\n  do b \u2190 same_result pr (tac tt (args ++ xs ++ ys)),\n     if b\n       then filter_simp_set_aux xs ys (x:: ds)\n       else filter_simp_set_aux xs (x :: ys) ds\n\ndeclare_trace squeeze.deleted\n\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-/\nmeta def filter_simp_set\n  (tac : bool \u2192 list simp_arg_type \u2192 tactic unit)\n  (user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) :=\ndo some s \u2190 get_proof_state_after (tac ff (user_args ++ simp_args)),\n   (simp_args', _)  \u2190 filter_simp_set_aux tac user_args s simp_args [] [],\n   (user_args', ds) \u2190 filter_simp_set_aux tac simp_args' s user_args [] [],\n   when (is_trace_enabled_for `squeeze.deleted = tt \u2227 \u00ac ds.empty)\n     trace!\"deleting provided arguments {ds}\",\n   pure (user_args' ++ simp_args')\n\n/-- make a `simp_arg_type` that references the name given as an argument -/\nmeta def name.to_simp_args (n : name) : tactic simp_arg_type :=\ndo e \u2190 resolve_name' n, pure $ simp_arg_type.expr e\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\n-/\nmeta def squeeze_simp_core\n  (slow no_dflt : bool) (args : list simp_arg_type)\n  (tac : \u03a0 (no_dflt : bool) (args : list simp_arg_type), tactic unit)\n  (mk_suggestion : list simp_arg_type \u2192 tactic unit) : tactic unit :=\ndo v \u2190 target >>= mk_meta_var,\n   args \u2190 if slow then do\n     simp_set \u2190 attribute.get_instances `simp,\n     simp_set \u2190 simp_set.mfilter $ has_attribute' `_refl_lemma,\n     simp_set \u2190 simp_set.mmap $ resolve_name' >=> pure \u2218 simp_arg_type.expr,\n     pure $ args ++ simp_set\n   else pure args,\n   g \u2190 retrieve $ do\n   { g \u2190 main_goal,\n     tac no_dflt args,\n     instantiate_mvars g },\n   let vs := g.list_constant,\n   vs \u2190 vs.mfilter is_simp_lemma,\n   vs \u2190 vs.mmap strip_prefix,\n   vs \u2190 vs.to_list.mmap name.to_simp_args,\n   with_local_goals' [v] (filter_simp_set tac args vs)\n     >>= mk_suggestion,\n   tac no_dflt args\n\nnamespace interactive\n\nattribute [derive decidable_eq] simp_arg_type\n\n/-- Turn a `simp_arg_type` into a string. -/\nmeta instance simp_arg_type.has_to_string : has_to_string simp_arg_type :=\n\u27e8\u03bb a, match a with\n| simp_arg_type.all_hyps := \"*\"\n| (simp_arg_type.except n) := \"-\" ++ to_string n\n| (simp_arg_type.expr e) := to_string e\n| (simp_arg_type.symm_expr e) := \"\u2190\" ++ to_string e\nend\u27e9\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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (xs.tail.map f).length = xs.length :=\nbegin\n  have : xs = ys, admit,\n  squeeze_scope\n  { split; squeeze_simp, -- `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]  -- `squeeze_simp` is run only once\n                         -- prints:\n                         -- > Try this: simp only [this]\n },\nend\n```\n\n-/\nmeta def squeeze_scope (tac : itactic) : tactic unit :=\ndo none \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (),\n   squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff,\n   finally tac $ do\n     some xs \u2190 squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail \"invalid state\",\n     let m := native.rb_lmap.of_list xs,\n     squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff,\n     m.to_list.reverse.mmap' $ \u03bb \u27e8p,suggs\u27e9, do\n       { let \u27e8pre,_,post\u27e9 := suggs.head,\n         let suggs : list (list simp_arg_type) := suggs.map $ prod.fst \u2218 prod.snd,\n         mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () }\n\n/--\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-/\nmeta def squeeze_simp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\n/-- see `squeeze_simp` -/\nmeta def squeeze_simpa\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (tgt : parse (tk \"using\" *> texpr)?)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_config cfg,\n   tgt' \u2190 traverse (\u03bb t, do t \u2190 to_expr t >>= pp,\n                            pure format!\" using {t}\") tgt,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            tgt' := tgt'.get_or_else \"\" in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: simpa{use_iota_eqn} only\"\n          sformat!\"{attrs}{tgt'}{c}\" args)\n\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 -/\nmeta def squeeze_dsimp\n  (key : parse cur_pos)\n  (slow_and_accurate : parse (tk \"?\")?)\n  (use_iota_eqn : parse (tk \"!\")?)\n  (no_dflt : parse only_flag) (hs : parse simp_arg_list)\n  (attr_names : parse with_ident_list) (locat : parse location)\n  (cfg : parse struct_inst?) : tactic unit :=\ndo (cfg',c) \u2190 parse_dsimp_config cfg,\n   squeeze_simp_core slow_and_accurate.is_some no_dflt hs\n     (\u03bb l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg')\n     (\u03bb args,\n        let use_iota_eqn := if use_iota_eqn.is_some then \"!\" else \"\",\n            attrs := if attr_names.empty then \"\"\n                     else string.join (list.intersperse \" \" (\" with\" :: attr_names.map to_string)),\n            loc := loc.to_string locat in\n        mk_suggestion (key.move_left 1)\n          sformat!\"Try this: dsimp{use_iota_eqn} only\"\n          sformat!\"{attrs}{loc}{c}\" args)\n\nend interactive\nend tactic\n\nopen tactic.interactive\nadd_tactic_doc\n{ name       := \"squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope\",\n  category   := doc_category.tactic,\n  decl_names :=\n   [``squeeze_simp,\n    ``squeeze_dsimp,\n    ``squeeze_simpa,\n    ``squeeze_scope],\n  tags       := [\"simplification\", \"Try this\"],\n  inherit_description_from := ``squeeze_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/tactic/squeeze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238003666671086, "lm_q2_score": 0.03732688466686841, "lm_q1q2_score": 0.00606114090086018}}
{"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\n\n/-!\n# Defines `#time` command.\n\nTime the elaboration of a command, and print the result (in milliseconds).\n-/\n\nsection\nopen Lean Elab Command\n\nsyntax (name := timeCmd)  \"#time \" command : command\n\n/--\nTime the elaboration of a command, and print the result (in milliseconds).\n\nExample usage:\n```\nset_option maxRecDepth 100000 in\n#time example : (List.range 500).length = 500 := rfl\n```\n-/\n@[command_elab timeCmd] def timeCmdElab : CommandElab\n  | `(#time%$tk $stx:command) => do\n    let start \u2190 IO.monoMsNow\n    elabCommand stx\n    logInfoAt tk m!\"time: {(\u2190 IO.monoMsNow) - start}ms\"\n  | _ => throwUnsupportedSyntax\n\nend\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/Util/Time.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.11124121534690626, "lm_q2_score": 0.05419873478822258, "lm_q1q2_score": 0.006029133128106528}}
{"text": "import LeanForeign.S\nimport Lean\ndef main : IO Unit := do\n  IO.println (mkS 10 20 \"hello\").addXY\n  IO.println (mkS 10 20 \"hello\").string\n  appendToGlobalS \"foo\"\n  appendToGlobalS \"bla\"\n  getGlobalString >>= IO.println\n  updateGlobalS (mkS 0 0 \"world\")\n  getGlobalString >>= IO.println\n  pure ()\n\nopen Lean Elab Command Term Meta\n\n-- syntax (name := mc1) \"#mc1\" : command\n-- @[commandElab mc1]\n-- def mc1Impl : CommandElab\n\nelab \"#findCElab \" c:command : command => do\n  let macroRes \u2190 liftMacroM <| expandMacroImpl? (\u2190getEnv) c\n  -- because of MonadLift, IO monad also available\n  let _c \u2190 (pure: _ \u2192 IO _) Lean.Syntax.missing\n  let _a \u2190 liftIO do\n      IO.println \"a\"\n      let _b := 12\n      (pure: _) Lean.Syntax.missing\n  match macroRes with\n  | some (name, _) => logInfo s!\"Next step is a macro: {name.toString}\"\n  | none =>\n    let kind := c.raw.getKind\n    let elabs := commandElabAttribute.getEntries (\u2190getEnv) kind\n    match elabs with\n    | [] => logInfo s!\"There is no elaborators for your syntax, lools like its bad\"\n    | _ => logInfo s!\"your syntx may be elaborated by: {elabs.map (fun el => el.declName.toString)}\"\n\n#findCElab def lala := 12\n#findCElab example : 1 = 1 := rfl\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#eval divide 8 0\n\ndef lt (x : Except String Float):\n  StateT Nat (Except String) Float := (monadLift : _) x\n\n#print lt\n\nsyntax (name := myterm1) \"myterm 1\" : term\n\ndef mytermValues := [1,3]\n\n@[termElab myterm1]\ndef myTerm1Impl : TermElab := fun stx type? =>\n  mkAppM ``List.get! #[mkConst ``mytermValues, mkNatLit 0]\n#eval myterm 1\n\ndef sss := \"\u2200a b, a \u2192 b \u2192 a \u2227 b\"\nelab \"myterm 2\" : term => do\n  let env \u2190 getEnv\n  let _a \u2190 (pure:_ \u2192 IO _) \"a\"\n  let parsedSyntax \u2190 match Lean.Parser.runParserCategory env `term sss with\n                      | Except.ok stx => pure stx\n                      | Except.error errmsg => throwError errmsg\n  logInfo s!\"{parsedSyntax}\"\n  let prop \u2190 elabTerm parsedSyntax none-- (mkConst `Lean.Prop)\n  logInfo s!\"hi:{prop}\"\n  pure prop\n  -- logInfo s!\"{prop}\"\n  -- mkAppM ``List.get! #[mkConst ``mytermValues, mkNatLit 1]\n\ndef hahna: myterm 2 := fun {a b : Prop}(ha:a) (hb:b) => And.intro ha hb -- (\u27e8ha,hb\u27e9:a\u2227b)\n", "meta": {"author": "denjiry", "repo": "leanforeign", "sha": "0128b7f11f442c3bf49513bb1b849d517b137378", "save_path": "github-repos/lean/denjiry-leanforeign", "path": "github-repos/lean/denjiry-leanforeign/leanforeign-0128b7f11f442c3bf49513bb1b849d517b137378/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782568056728001, "lm_q2_score": 0.021615332486907682, "lm_q1q2_score": 0.006014613371362433}}
{"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 : \u03a0 \u2983i j : C \u00d7 D\u2984 (f : i \u27f6 j), Prop}\n  (comp : \u2200 {i j k : C \u00d7 D} (f : i \u27f6 j) (g : j \u27f6 k), motive f \u2192 motive g \u2192 motive (f \u226b g))\n  (H1 : \u2200 (i : C) {j k : D} (f : j \u2264 k), @motive (i,j) (i,k) (hom_of_le $ \u27e8le_rfl, f\u27e9))\n  (H2 : \u2200 {i j : C} (k : D) (f : i \u2264 j), @motive (i,k) (j,k) (hom_of_le $ \u27e8f, le_rfl\u27e9))\n  \u2983i j : C \u00d7 D\u2984 (f : i \u27f6 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 : \u03a0 \u2983i j : C \u00d7 D\u2984 (f : i \u27f6 j), Prop}\n  (comp : \u2200 {i j k : C \u00d7 D} (f : i \u27f6 j) (g : j \u27f6 k), motive f \u2192 motive g \u2192 motive (f \u226b g))\n  (H1 : \u2200 (i : C) {j k : D} (f : j \u27f6 k), @motive (i,j) (i,k) (\ud835\udfd9 i, f))\n  (H2 : \u2200 {i j : C} (k : D) (f : i \u27f6 j), @motive (i,k) (j,k) (f, \ud835\udfd9 k))\n  \u2983i j : C \u00d7 D\u2984 (f : i \u27f6 j) : motive f :=\nbegin\n  let f1 : (i.1, i.2) \u27f6 (i.1, j.2) := (\ud835\udfd9 i.1, f.2),\n  let f2 : (i.1, j.2) \u27f6 (j.1, j.2) := (f.1, \ud835\udfd9 j.2),\n  have hf : f = f1 \u226b 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 : \u2115)\n  {motive : \u03a0 \u2983i j : fin (n+1)\u2984 (f : i \u2264 j), Prop}\n  (id : \u2200 i, motive (le_refl i))\n  (comp : \u2200 {i j k : fin (n+1)} (f : i \u2264 j) (g : j \u2264 k), motive f \u2192 motive g \u2192 motive (f.trans g : i \u2264 k))\n  (Hsucc : \u2200 (i : fin n), @motive i.cast_succ i.succ (le_of_lt $ by { rw fin.cast_succ_lt_iff_succ_le }))\n  \u2983i j : fin (n+1)\u2984 (f : i \u2264 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 \u2190 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 \ud835\udcd0 : Type*} [category C] [category \ud835\udcd0] [abelian \ud835\udcd0]\n\nnamespace homological_complex\n\nvariables {\u03b9 : Type*} {c : complex_shape \u03b9}\n\nlocal notation x `\u27f6[`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 \u27f6 succ_horizontal i j := snake_diagram.hom _ _\ndef to_succ_vertical ( i : fin 3) (j : fin 3) :\n  cast_vertical i j \u27f6 succ_vertical i j := snake_diagram.hom _ _\n\nlemma snake_diagram_induction\n  {motive : \u03a0 \u2983i j : snake_diagram\u2984 (f : i \u27f6 j), Prop}\n  (id : \u2200 i : snake_diagram, motive (\ud835\udfd9 i))\n  (comp : \u2200 (i j k : snake_diagram) (f : i \u27f6 j) (g : j \u27f6 k),\n    motive f \u2192 motive g \u2192 motive (f \u226b g))\n  (succ_horizontal : \u2200 (i : fin 4) (j : fin 2),\n    motive (to_succ_horizontal i j))\n  (succ_vertical : \u2200 (i : fin 3) (j : fin 3),\n    motive (to_succ_vertical i j)) \u2983i j : snake_diagram\u2984 (f : i \u27f6 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      (\u03bb j k f, motive (hom_of_le $ (\u27e8le_refl i, f\u27e9 : (i,j) \u2264 (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      (\u03bb i j f, motive (hom_of_le $ (\u27e8f, le_refl k\u27e9 : (i,k) \u2264 (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 \u2964 homological_complex \ud835\udcd0 c} (f : X \u27f6 Y) (g : Y \u27f6 Z)\n  (H : \u2200 c i, short_exact ((f.app c).f i) ((g.app c).f i))\n  {c\u2081 c\u2082 : C} (\u03c6 : c\u2081 \u27f6 c\u2082) (i j : \u03b9) (hij : c.rel i j)\n\ndef mk_snake_diagram_nat_trans_app : \u03a0 (e : snake_diagram),\n  (snake (f.app c\u2081) (g.app c\u2081) (H _) i j hij).snake_diagram.obj e \u27f6\n  (snake (f.app c\u2082) (g.app c\u2082) (H _) i j hij).snake_diagram.obj e\n| \u27e8\u27e80,_\u27e9,\u27e80,_\u27e9\u27e9 := (homology_functor _ _ i).map (X.map \u03c6)\n| \u27e8\u27e80,_\u27e9,\u27e81,_\u27e9\u27e9 := (homology_functor _ _ i).map (Y.map \u03c6)\n| \u27e8\u27e80,_\u27e9,\u27e82,_\u27e9\u27e9 := (homology_functor _ _ i).map (Z.map \u03c6)\n| \u27e8\u27e81,_\u27e9,\u27e80,_\u27e9\u27e9 := (mod_boundaries_functor _).map (X.map \u03c6)\n| \u27e8\u27e81,_\u27e9,\u27e81,_\u27e9\u27e9 := (mod_boundaries_functor _).map (Y.map \u03c6)\n| \u27e8\u27e81,_\u27e9,\u27e82,_\u27e9\u27e9 := (mod_boundaries_functor _).map (Z.map \u03c6)\n| \u27e8\u27e82,_\u27e9,\u27e80,_\u27e9\u27e9 := (cycles_functor _ _ _).map (X.map \u03c6)\n| \u27e8\u27e82,_\u27e9,\u27e81,_\u27e9\u27e9 := (cycles_functor _ _ _).map (Y.map \u03c6)\n| \u27e8\u27e82,_\u27e9,\u27e82,_\u27e9\u27e9 := (cycles_functor _ _ _).map (Z.map \u03c6)\n| \u27e8\u27e83,_\u27e9,\u27e80,_\u27e9\u27e9 := (homology_functor _ _ j).map (X.map \u03c6)\n| \u27e8\u27e83,_\u27e9,\u27e81,_\u27e9\u27e9 := (homology_functor _ _ j).map (Y.map \u03c6)\n| \u27e8\u27e83,_\u27e9,\u27e82,_\u27e9\u27e9 := (homology_functor _ _ j).map (Z.map \u03c6)\n| _ := 0 -- impossible case\n.\n\ndef mk_snake_diagram_nat_trans_hor :\n  \u2200 (a : fin 4) (b : fin 2),\n  (snake (f.app c\u2081) (g.app c\u2081) (H _) i j hij).snake_diagram.map (to_succ_horizontal a b) \u226b\n    mk_snake_diagram_nat_trans_app f g H \u03c6 i j hij (succ_horizontal a b) =\n    mk_snake_diagram_nat_trans_app f g H \u03c6 i j hij (cast_horizontal a b) \u226b\n    (snake (f.app c\u2082) (g.app c\u2082) (H _) i j hij).snake_diagram.map (to_succ_horizontal a b)\n| \u27e80,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_f0, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e80,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_g0, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e80,_\u27e9 \u27e8n+2,h\u27e9 := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| \u27e81,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_f1, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e81,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_g1, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e81,_\u27e9 \u27e8n+2,h\u27e9 := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| \u27e82,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_f2, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e82,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_g2, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e82,_\u27e9 \u27e8n+2,h\u27e9 := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| \u27e83,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_f3, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e83,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_g3, \u2190 category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| \u27e83,_\u27e9 \u27e8n+2,h\u27e9 := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| \u27e8n+4,h\u27e9 _   := 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  \u2200 (a b : fin 3),\n  (snake (f.app c\u2081) (g.app c\u2081) (H _) i j hij).snake_diagram.map (to_succ_vertical a b) \u226b\n    mk_snake_diagram_nat_trans_app f g H \u03c6 i j hij (succ_vertical a b) =\n    mk_snake_diagram_nat_trans_app f g H \u03c6 i j hij (cast_vertical a b) \u226b\n    (snake (f.app c\u2082) (g.app c\u2082) (H _) i j hij).snake_diagram.map (to_succ_vertical a b)\n| \u27e80,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_a0] }, erw nat_trans.naturality, refl }\n| \u27e80,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_b0] }, erw nat_trans.naturality, refl }\n| \u27e80,_\u27e9 \u27e82,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_c0] }, erw nat_trans.naturality, refl }\n| \u27e80,_\u27e9 \u27e8n+3,h\u27e9 := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n| \u27e81,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_a1] }, erw nat_trans.naturality, refl }\n| \u27e81,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_b1] }, erw nat_trans.naturality, refl }\n| \u27e81,_\u27e9 \u27e82,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_c1] }, erw nat_trans.naturality, refl }\n| \u27e81,_\u27e9 \u27e8n+3,h\u27e9 := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n| \u27e82,_\u27e9 \u27e80,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_a2] }, erw nat_trans.naturality, refl }\n| \u27e82,_\u27e9 \u27e81,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_b2] }, erw nat_trans.naturality, refl }\n| \u27e82,_\u27e9 \u27e82,_\u27e9 := by { repeat { erw [snake_diagram.mk_functor_map_c2] }, erw nat_trans.naturality, refl }\n| \u27e82,_\u27e9 \u27e8n+3,h\u27e9 := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n| \u27e8n+3,h\u27e9 _   := 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\u2081) (g.app c\u2081) (H _) i j hij).snake_diagram \u27f6\n  (snake (f.app c\u2082) (g.app c\u2082) (H _) i j hij).snake_diagram :=\n{ app := \u03bb e, mk_snake_diagram_nat_trans_app f g H \u03c6 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 \u03c6 i j hij },\n    { exact mk_snake_diagram_nat_trans_ver f g H \u03c6 i j hij },\n  end }\n\nlemma \u03b4_natural :\n  \u03b4 (f.app c\u2081) (g.app c\u2081) (H _) i j hij \u226b (homology_functor _ _ j).map (X.map \u03c6) =\n    (homology_functor _ _ i).map (Z.map \u03c6) \u226b \u03b4 (f.app c\u2082) (g.app c\u2082) (H _) i j hij :=\nbegin\n  let \u03b7 := mk_snake_diagram_nat_trans f g H \u03c6 i j hij,\n  apply (snake_lemma.\u03b4_natural \u03b7 _ _).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 Lean.Elab\n\nstructure Bar where\n\nstructure Foo where\n  foo\u2081 : Nat\n  foo\u2082 : Nat\n  bar  : Bar\n\ndef mkFoo\u2081 : Foo := {\n--v textDocument/definition\n  foo\u2081 := 1\n--v textDocument/declaration\n  foo\u2082 := 2\n--v textDocument/typeDefinition\n  bar := \u27e8\u27e9\n}\n\nstructure HandWrittenStruct where\n  n : Nat\n\n-- def HandWrittenStruct.n := fun | mk n => n\n\n          --v textDocument/definition\ndef hws : HandWrittenStruct := {\n--v textDocument/definition\n  n := 3\n}\n\n            --v textDocument/declaration\ndef mkFoo\u2082 := mkFoo\u2081\n\nsyntax (name := elabTest) \"test\" : term\n\n@[termElab elabTest] def elabElabTest : Lean.Elab.Term.TermElab := fun _ _ => do\n  let stx \u2190 `(2)\n  Lean.Elab.Term.elabTerm stx none\n\n     --v textDocument/declaration\n#check test\n     --^ textDocument/definition\n\ndef Baz (\u03b1 : Type) := \u03b1\n\n#check fun (b : Baz Nat) => b\n                          --^ textDocument/typeDefinition\n\nexample : Nat :=\n  let a := 1\n--v textDocument/definition\n  a + b\n    --^ textDocument/definition\nwhere\n  b := 2\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/goTo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968261942204597, "lm_q2_score": 0.030214588595594973, "lm_q1q2_score": 0.005947022483207862}}
{"text": "\nimport Lib.Meta\nimport Lib.Tactic\n\nnamespace Lean.Elab.Tactic\n\nopen Lean.Elab.Tactic\nopen Lean Lean.Meta\nopen Lean.Elab\nopen Lean.Elab.Term\nopen Lean.PrettyPrinter.Delaborator.TopDownAnalyze\nopen Lean.Elab.Tactic\n\n-- initialize registerTrace\ninitialize registerTraceClass `select.match.failure\ninitialize registerTraceClass `select.match.attempt\ninitialize registerTraceClass `select.match.success\ninitialize registerTraceClass `select.skipped\n\ninductive Selector where\n  | hyp (name : Name) (pattern : Expr)\n  | goal (pattern : Expr)\n\ndef headZeta1 : Expr \u2192 Expr\n| .mdata _ e _ => headZeta1 e\n| .letE v t e e' _ => instantiateBVar [e] e'\n| e => e\n\ndef clearLDecl (l : LocalDecl) : TacticM (Array Name) :=\nwithMainContext do\n  -- println!\"before\"\n  -- print_vars![mainGoal]\n  let some l' \u2190 tryTactic? <| liftMetaTactic1' (revert . #[l.fvarId])\n    | pure #[]\n  -- println!\"reverted\"\n  let tgt \u2190 getMainTarget\n  -- println!\"main target\"\n  liftMetaTactic1 (change . <| headZeta1 tgt)\n  let l' := l'[1:].toArray\n  -- println!\"after\"\n  l'.mapM (\u03bb v => do return (\u2190 getLocalDecl v).userName)\n\nopen Lean (Meta.ppExpr)\nopen Lean.Meta (ppExpr)\n\ndef elabHypSelector : Selector \u2192 SearchTacticM \u03b4 (Option (LocalDecl \u00d7 LocalDecl))\n| .hyp tag pat => do\n  let lctx \u2190 getLCtx\n  let ls := \u03bb _ : Unit =>\n    lctx.decls.toList.filterMap <| Option.map (\u00b7.userName)\n  let some h := (\u2190 SearchT.pick lctx.decls.toList) | failure\n  trace[select.match.attempt]\" trying {h.userName} with {\u2190 Meta.ppExpr pat}\"\n  unless \u00ac h.isAuxDecl do\n    trace[select.skipped]\"skipping {h.userName} ({h.fvarId.name}) \"\n    failure\n  let t := h.type\n  unless (\u2190 liftM <| isDefEqAssigning t pat) do\n    trace[select.match.failure]\" tried {h.userName} with {\u2190 Meta.ppExpr pat}\"\n    failure\n  trace[select.match.success]\" tried {h.userName} with {\u2190 Meta.ppExpr pat}\"\n  liftMetaTactic1 (define . tag h.type <| mkFVar h.fvarId)\n  let var \u2190 liftMetaTactic1' (intro . tag)\n  let var \u2190 withMainContext (getLocalDecl var)\n  return some (var, h)\n| .goal pat => do\n  let g \u2190 getMainTarget\n  unless (\u2190 liftM <| isDefEqAssigning g pat) do\n    trace[select.match.failure]\" tried goal with {\u2190 Meta.ppExpr pat}\"\n    failure\n  return none\n\n-- #exit\n\ndef elabHypSelectors (sel : Array Selector) (tac : Option Syntax) :\n  SearchTacticM \u03b4 (Array (LocalDecl \u00d7 LocalDecl)) := do\nlet mappings \u2190 sel.filterMapM elabHypSelector\nmatch tac with\n| none => pure ()\n| some tac => evalTactic tac\nreturn mappings\n\ndef elabSelectors (sel : Array Selector) (tac : Option Syntax) :\n  TacticM (Array (LocalDecl \u00d7 LocalDecl)) := do\nelabHypSelectors sel tac |>.run\n\n\ndeclare_syntax_cat asm_select\ndeclare_syntax_cat asm_selectors\n\nsyntax (name := hyp_selector)\n  colGt withPosition(\"hyp \" ident \" : \" colGt term) ppLine : asm_select\nsyntax (name := goal_selector)\n  colGt withPosition(\"goal \" \" : \" colGt term) ppLine : asm_select\nsyntax (name := many_selectors) (asm_select)+ : asm_selectors\nsyntax (name := one_selector) group(ident \" : \" colGt term) : asm_selectors\n\nsyntax withPosition(\"select \" asm_selectors (colGt tacticSeq)?) : tactic\n\nelab \"have! \" d:haveDecl : tactic => do\n  let Hid := d[0][0][0].getId\n  let decl \u2190 getLocalDeclFromUserName Hid\n  evalTactic (\u2190 `(tactic| have $d:haveDecl))\n  liftMetaTactic1 (clear . decl.fvarId)\n\nelab \"have? \" d:haveDecl : tactic => do\n  evalTactic (\u2190 `(tactic| have $d:haveDecl))\n  let Hid := d[0][0][0].getId\n  withMainContext do\n  let ldecl \u2190 getLocalDeclFromUserName Hid\n  for h in \u2190 getLCtx do\n    if h.fvarId != ldecl.fvarId && (\u2190 isDefEq h.type ldecl.type) then\n      throwError \"Local decl {h.userName} already has type {ldecl.type}\"\n\ndef parseSelector (xs : Syntax) : TacticM (Array Selector) := do\nif xs.getKind == ``one_selector then\n  let xs := xs[0]\n  let tag := xs[0].getId\n  let colon := xs[1]\n  let term := xs[2]\n  let pat \u2190 Term.elabTerm term none\n  return #[ Selector.hyp tag pat ]\nelse\n  let mut r := #[]\n  for x in xs[0].getArgs do\n    if x.getKind == ``goal_selector then\n      let kw    := x[0]\n      let colon := x[1]\n      let term  := x[2]\n      let pat \u2190 Term.elabTerm term none\n      r := r.push <| Selector.goal pat\n    else\n      let kw    := x[0]\n      let tag   := x[1].getId\n      let colon := x[2]\n      let term  := x[3]\n      let pat \u2190 Term.elabTerm term none\n      r := r.push <| Selector.hyp tag pat\n  return r\n\nelab_rules : tactic\n| `(tactic| select $xs $[$tac:tacticSeq]?) =>\nLean.MonadQuotation.withFreshMacroScope do\nwithMainContext do\n    let sels \u2190 parseSelector xs\n    let hs \u2190 elabSelectors sels tac\n    if tac.isSome then\n      withMainContext do\n      let mut vs := #[]\n      for (v, _) in hs.reverse do\n        let vs' \u2190 clearLDecl v\n        vs := vs ++ vs'.reverse\n      withMainContext do\n      for v in vs.reverse do\n        discard <| liftMetaTactic1' (intro . v)\n\n\nexample (a b c x y z : Nat)\n  (a\u2080 : a \u2264 b)\n  (a\u2081 : b \u2264 c)\n  (h\u2081 : y \u2264 z)\n  (h\u2082 : x \u2264 z)\n  (h\u2080 : x \u2264 y)\n  -- (hh : x \u2264 w)\n  (h\u2083 : z \u2264 w)\n : x \u2264 w := by\n-- repeat\nrepeat\n  select\n    hyp h : ?x \u2264 ?y\n    hyp h' : ?y \u2264 ?z\n    -- goal : ?x \u2264 ?z\n    have? h\u2083 := Nat.le_trans h h'\nskip\nadmit\n-- have : h = h := rfl\n-- have : h' = h' := rfl\n  -- clear h\n  -- revert h'\n  -- have? h\u2084 := rfl\n-- intro\n-- select h'' : _ \u2264 ?x\n\n-- skip\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/Tactic/Select.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23934934732271165, "lm_q2_score": 0.024798161366748964, "lm_q1q2_score": 0.005935423737934648}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Parser.Term\nimport Lean.Parser.Do\n\nnamespace Lean\nnamespace Parser\n\n/--\n  Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like\n  `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead.\n  Multiple command will be put in a `` `null `` node, but a single command will not (so that you can directly\n  match against a quotation in a command kind's elaborator). -/\n-- TODO: use two separate quotation parsers with parser priorities instead\n@[builtinTermParser] def Term.quot := leading_parser \"`(\" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> \")\"\n@[builtinTermParser] def Term.precheckedQuot := leading_parser \"`\" >> Term.quot\n\nnamespace Command\n\ndef terminationBy := leading_parser \"termination_by \" >> sepBy1 termParser \", \"\n\n@[builtinCommandParser]\ndef moduleDoc := leading_parser ppDedent $ \"/-!\" >> commentBody >> ppLine\n\ndef namedPrio := leading_parser (atomic (\"(\" >> nonReservedSymbol \"priority\") >> \" := \" >> priorityParser >> \")\")\ndef optNamedPrio := optional namedPrio\n\ndef \u00abprivate\u00bb        := leading_parser \"private \"\ndef \u00abprotected\u00bb      := leading_parser \"protected \"\ndef visibility       := \u00abprivate\u00bb <|> \u00abprotected\u00bb\ndef \u00abnoncomputable\u00bb  := leading_parser \"noncomputable \"\ndef \u00abunsafe\u00bb         := leading_parser \"unsafe \"\ndef \u00abpartial\u00bb        := leading_parser \"partial \"\ndef \u00abnonrec\u00bb         := leading_parser \"nonrec \"\ndef declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.\u00abattributes\u00bb >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional \u00abnoncomputable\u00bb >> optional \u00abunsafe\u00bb >> optional (\u00abpartial\u00bb <|> \u00abnonrec\u00bb)\ndef declId           := leading_parser ident >> optional (\".{\" >> sepBy1 ident \", \" >> \"}\")\ndef declSig          := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec\ndef optDeclSig       := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType\ndef declValSimple    := leading_parser \" :=\\n\" >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef declVal          := declValSimple <|> declValEqns <|> Term.whereDecls\ndef \u00ababbrev\u00bb         := leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\ndef optDefDeriving   := optional (atomic (\"deriving \" >> notSymbol \"instance\") >> sepBy1 ident \", \")\ndef \u00abdef\u00bb            := leading_parser \"def \" >> declId >> optDeclSig >> declVal >> optDefDeriving >> optional terminationBy\ndef \u00abtheorem\u00bb        := leading_parser \"theorem \" >> declId >> declSig >> declVal >> optional terminationBy\ndef \u00abconstant\u00bb       := leading_parser \"constant \" >> declId >> declSig >> optional declValSimple\ndef \u00abinstance\u00bb       := leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal >> optional terminationBy\ndef \u00abaxiom\u00bb          := leading_parser \"axiom \" >> declId >> declSig\ndef \u00abexample\u00bb        := leading_parser \"example \" >> declSig >> declVal\ndef inferMod         := leading_parser atomic (symbol \"{\" >> \"}\")\ndef ctor             := leading_parser \"\\n| \" >> declModifiers true >> ident >> optional inferMod >> optDeclSig\ndef derivingClasses  := sepBy1 (group (ident >> optional (\" with \" >> Term.structInst))) \", \"\ndef optDeriving      := leading_parser optional (atomic (\"deriving \" >> notSymbol \"instance\") >> derivingClasses)\ndef \u00abinductive\u00bb      := leading_parser \"inductive \" >> declId >> optDeclSig >> optional (symbol \":=\" <|> \"where\") >> many ctor >> optDeriving\ndef classInductive   := leading_parser atomic (group (symbol \"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional (symbol \":=\" <|> \"where\") >> many ctor >> optDeriving\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> optional inferMod >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> optional inferMod >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder))\ndef structCtor           := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> \" :: \")\ndef structureTk          := leading_parser \"structure \"\ndef classTk              := leading_parser \"class \"\ndef \u00abextends\u00bb            := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef \u00abstructure\u00bb          := leading_parser\n    (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType\n    >> optional ((symbol \" := \" <|> \" where \") >> optional structCtor >> structFields)\n    >> optDeriving\n@[builtinCommandParser] def declaration := leading_parser\ndeclModifiers false >> (\u00ababbrev\u00bb <|> \u00abdef\u00bb <|> \u00abtheorem\u00bb <|> \u00abconstant\u00bb <|> \u00abinstance\u00bb <|> \u00abaxiom\u00bb <|> \u00abexample\u00bb <|> \u00abinductive\u00bb <|> classInductive <|> \u00abstructure\u00bb)\n@[builtinCommandParser] def \u00abderiving\u00bb     := leading_parser \"deriving \" >> \"instance \" >> derivingClasses >> \" for \" >> sepBy1 ident \", \"\n@[builtinCommandParser] def \u00absection\u00bb      := leading_parser \"section \" >> optional ident\n@[builtinCommandParser] def \u00abnamespace\u00bb    := leading_parser \"namespace \" >> ident\n@[builtinCommandParser] def \u00abend\u00bb          := leading_parser \"end \" >> optional ident\n@[builtinCommandParser] def \u00abvariable\u00bb     := leading_parser \"variable\" >> many1 Term.bracketedBinder\n@[builtinCommandParser] def \u00abuniverse\u00bb     := leading_parser \"universe \" >> many1 ident\n@[builtinCommandParser] def check          := leading_parser \"#check \" >> termParser\n@[builtinCommandParser] def check_failure  := leading_parser \"#check_failure \" >> termParser -- Like `#check`, but succeeds only if term does not type check\n@[builtinCommandParser] def reduce         := leading_parser \"#reduce \" >> termParser\n@[builtinCommandParser] def eval           := leading_parser \"#eval \" >> termParser\n@[builtinCommandParser] def synth          := leading_parser \"#synth \" >> termParser\n@[builtinCommandParser] def exit           := leading_parser \"#exit\"\n@[builtinCommandParser] def print          := leading_parser \"#print \" >> (ident <|> strLit)\n@[builtinCommandParser] def printAxioms    := leading_parser \"#print \" >> nonReservedSymbol \"axioms \" >> ident\n@[builtinCommandParser] def \u00abresolve_name\u00bb := leading_parser \"#resolve_name \" >> ident\n@[builtinCommandParser] def \u00abinit_quot\u00bb    := leading_parser \"init_quot\"\ndef optionValue := nonReservedSymbol \"true\" <|> nonReservedSymbol \"false\" <|> strLit <|> numLit\n@[builtinCommandParser] def \u00abset_option\u00bb   := leading_parser \"set_option \" >> ident >> ppSpace >> optionValue\ndef eraseAttr := leading_parser \"-\" >> rawIdent\n@[builtinCommandParser] def \u00abattribute\u00bb    := leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"] \" >> many1 ident\n@[builtinCommandParser] def \u00abexport\u00bb       := leading_parser \"export \" >> ident >> \"(\" >> many1 ident >> \")\"\ndef openHiding       := leading_parser atomic (ident >> \"hiding\") >> many1 (checkColGt >> ident)\ndef openRenamingItem := leading_parser ident >> unicodeSymbol \"\u2192\" \"->\" >> checkColGt >> ident\ndef openRenaming     := leading_parser atomic (ident >> \"renaming\") >> sepBy1 openRenamingItem \", \"\ndef openOnly         := leading_parser atomic (ident >> \"(\") >> many1 ident >> \")\"\ndef openSimple       := leading_parser many1 (checkColGt >> ident)\ndef openScoped       := leading_parser \"scoped \" >> many1 (checkColGt >> ident)\ndef openDecl         := openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped\n@[builtinCommandParser] def \u00abopen\u00bb    := leading_parser withPosition (\"open \" >> openDecl)\n\n@[builtinCommandParser] def \u00abmutual\u00bb := leading_parser \"mutual \" >> many1 (ppLine >> notSymbol \"end\" >> commandParser) >> ppDedent (ppLine >> \"end\") >> optional terminationBy\n@[builtinCommandParser] def \u00abinitialize\u00bb := leading_parser optional visibility >> \"initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n@[builtinCommandParser] def \u00abbuiltin_initialize\u00bb := leading_parser optional visibility >> \"builtin_initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n\n@[builtinCommandParser] def \u00abin\u00bb  := trailing_parser withOpen (\" in \" >> commandParser)\n\n/-\n  This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`.\n  It is meant for bootstrapping purposes only. -/\n@[builtinCommandParser] def genInjectiveTheorems := leading_parser \"gen_injective_theorems% \" >> ident\n\n@[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false\n@[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true\n\nbuiltin_initialize\n  register_parser_alias \"declModifiers\"       declModifiersF\n  register_parser_alias \"nestedDeclModifiers\" declModifiersT\n  register_parser_alias                       declId\n  register_parser_alias                       declSig\n  register_parser_alias                       declVal\n  register_parser_alias                       optDeclSig\n  register_parser_alias                       openDecl\n\nend Command\n\nnamespace Term\n@[builtinTermParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> termParser)\n@[builtinTermParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> termParser\nend Term\n\nnamespace Tactic\n@[builtinTacticParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> tacticSeq)\n@[builtinTacticParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> tacticSeq\nend Tactic\n\nend Parser\nend Lean\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/Parser/Command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1993079979040456, "lm_q2_score": 0.029760092655176606, "lm_q1q2_score": 0.005931424484542142}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Parser.Term\nimport Lean.Parser.Do\n\nnamespace Lean\nnamespace Parser\n\n/--\n  Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like\n  `($x $y) will be parsed as an application, not two commands. Use `($x:command $y:command) instead.\n  Multiple command will be put in a `null node, but a single command will not (so that you can directly\n  match against a quotation in a command kind's elaborator). -/\n-- TODO: use two separate quotation parsers with parser priorities instead\n@[builtinTermParser] def Term.quot := leading_parser \"`(\" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> \")\"\n@[builtinTermParser] def Term.precheckedQuot := leading_parser \"`\" >> Term.quot\n\nnamespace Command\n\ndef namedPrio := leading_parser (atomic (\"(\" >> nonReservedSymbol \"priority\") >> \" := \" >> priorityParser >> \")\")\ndef optNamedPrio := optional namedPrio\n\ndef \u00abprivate\u00bb        := leading_parser \"private \"\ndef \u00abprotected\u00bb      := leading_parser \"protected \"\ndef visibility       := \u00abprivate\u00bb <|> \u00abprotected\u00bb\ndef \u00abnoncomputable\u00bb  := leading_parser \"noncomputable \"\ndef \u00abunsafe\u00bb         := leading_parser \"unsafe \"\ndef \u00abpartial\u00bb        := leading_parser \"partial \"\ndef declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.\u00abattributes\u00bb >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional \u00abnoncomputable\u00bb >> optional \u00abunsafe\u00bb >> optional \u00abpartial\u00bb\ndef declId           := leading_parser ident >> optional (\".{\" >> sepBy1 ident \", \" >> \"}\")\ndef declSig          := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec\ndef optDeclSig       := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType\ndef declValSimple    := leading_parser \" :=\\n\" >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef declVal          := declValSimple <|> declValEqns <|> Term.whereDecls\ndef \u00ababbrev\u00bb         := leading_parser \"abbrev \" >> declId >> optDeclSig >> declVal\ndef \u00abdef\u00bb            := leading_parser \"def \" >> declId >> optDeclSig >> declVal\ndef \u00abtheorem\u00bb        := leading_parser \"theorem \" >> declId >> declSig >> declVal\ndef \u00abconstant\u00bb       := leading_parser \"constant \" >> declId >> declSig >> optional declValSimple\ndef \u00abinstance\u00bb       := leading_parser Term.attrKind >> \"instance \" >> optNamedPrio >> optional declId >> declSig >> declVal\ndef \u00abaxiom\u00bb          := leading_parser \"axiom \" >> declId >> declSig\ndef \u00abexample\u00bb        := leading_parser \"example \" >> declSig >> declVal\ndef inferMod         := leading_parser atomic (symbol \"{\" >> \"}\")\ndef ctor             := leading_parser \"\\n| \" >> declModifiers true >> ident >> optional inferMod >> optDeclSig\ndef optDeriving      := leading_parser optional (atomic (\"deriving \" >> notSymbol \"instance\") >> sepBy1 ident \", \")\ndef \u00abinductive\u00bb      := leading_parser \"inductive \" >> declId >> optDeclSig >> optional (symbol \":=\" <|> \"where\") >> many ctor >> optDeriving\ndef classInductive   := leading_parser atomic (group (symbol \"class \" >> \"inductive \")) >> declId >> optDeclSig >> optional (symbol \":=\" <|> \"where\") >> many ctor >> optDeriving\ndef structExplicitBinder := leading_parser atomic (declModifiers true >> \"(\") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> \")\"\ndef structImplicitBinder := leading_parser atomic (declModifiers true >> \"{\") >> many1 ident >> optional inferMod >> declSig >> \"}\"\ndef structInstBinder     := leading_parser atomic (declModifiers true >> \"[\") >> many1 ident >> optional inferMod >> declSig >> \"]\"\ndef structSimpleBinder   := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault\ndef structFields         := leading_parser manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder))\ndef structCtor           := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> \" :: \")\ndef structureTk          := leading_parser \"structure \"\ndef classTk              := leading_parser \"class \"\ndef \u00abextends\u00bb            := leading_parser \" extends \" >> sepBy1 termParser \", \"\ndef \u00abstructure\u00bb          := leading_parser\n    (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional \u00abextends\u00bb >> Term.optType\n    >> optional ((symbol \" := \" <|> \" where \") >> optional structCtor >> structFields)\n    >> optDeriving\n@[builtinCommandParser] def declaration := leading_parser\ndeclModifiers false >> (\u00ababbrev\u00bb <|> \u00abdef\u00bb <|> \u00abtheorem\u00bb <|> \u00abconstant\u00bb <|> \u00abinstance\u00bb <|> \u00abaxiom\u00bb <|> \u00abexample\u00bb <|> \u00abinductive\u00bb <|> classInductive <|> \u00abstructure\u00bb)\n@[builtinCommandParser] def \u00abderiving\u00bb     := leading_parser \"deriving \" >> \"instance \" >> sepBy1 ident \", \" >> \" for \" >> sepBy1 ident \", \"\n@[builtinCommandParser] def \u00absection\u00bb      := leading_parser \"section \" >> optional ident\n@[builtinCommandParser] def \u00abnamespace\u00bb    := leading_parser \"namespace \" >> ident\n@[builtinCommandParser] def \u00abend\u00bb          := leading_parser \"end \" >> optional ident\n@[builtinCommandParser] def \u00abvariable\u00bb     := leading_parser \"variable\" >> many1 Term.bracketedBinder\n@[builtinCommandParser] def \u00abuniverse\u00bb     := leading_parser \"universe \" >> ident\n@[builtinCommandParser] def \u00abuniverses\u00bb    := leading_parser \"universes \" >> many1 ident\n@[builtinCommandParser] def check          := leading_parser \"#check \" >> termParser\n@[builtinCommandParser] def check_failure  := leading_parser \"#check_failure \" >> termParser -- Like `#check`, but succeeds only if term does not type check\n@[builtinCommandParser] def reduce         := leading_parser \"#reduce \" >> termParser\n@[builtinCommandParser] def eval           := leading_parser \"#eval \" >> termParser\n@[builtinCommandParser] def synth          := leading_parser \"#synth \" >> termParser\n@[builtinCommandParser] def exit           := leading_parser \"#exit\"\n@[builtinCommandParser] def print          := leading_parser \"#print \" >> (ident <|> strLit)\n@[builtinCommandParser] def printAxioms    := leading_parser \"#print \" >> nonReservedSymbol \"axioms \" >> ident\n@[builtinCommandParser] def \u00abresolve_name\u00bb := leading_parser \"#resolve_name \" >> ident\n@[builtinCommandParser] def \u00abinit_quot\u00bb    := leading_parser \"init_quot\"\ndef optionValue := nonReservedSymbol \"true\" <|> nonReservedSymbol \"false\" <|> strLit <|> numLit\n@[builtinCommandParser] def \u00abset_option\u00bb   := leading_parser \"set_option \" >> ident >> ppSpace >> optionValue\ndef eraseAttr := leading_parser \"-\" >> ident\n@[builtinCommandParser] def \u00abattribute\u00bb    := leading_parser \"attribute \" >> \"[\" >> sepBy1 (eraseAttr <|> Term.attrInstance) \", \" >> \"] \" >> many1 ident\n@[builtinCommandParser] def \u00abexport\u00bb       := leading_parser \"export \" >> ident >> \"(\" >> many1 ident >> \")\"\ndef openHiding       := leading_parser atomic (ident >> \"hiding\") >> many1 ident\ndef openRenamingItem := leading_parser ident >> unicodeSymbol \"\u2192\" \"->\" >> ident\ndef openRenaming     := leading_parser atomic (ident >> \"renaming\") >> sepBy1 openRenamingItem \", \"\ndef openOnly         := leading_parser atomic (ident >> \"(\") >> many1 ident >> \")\"\ndef openSimple       := leading_parser many1 ident\ndef openDecl         := openHiding <|> openRenaming <|> openOnly <|> openSimple\n@[builtinCommandParser] def \u00abopen\u00bb    := leading_parser \"open \" >> openDecl\n\n@[builtinCommandParser] def \u00abmutual\u00bb := leading_parser \"mutual \" >> many1 (ppLine >> notSymbol \"end\" >> commandParser) >> ppDedent (ppLine >> \"end\")\n@[builtinCommandParser] def \u00abinitialize\u00bb := leading_parser \"initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n@[builtinCommandParser] def \u00abbuiltin_initialize\u00bb := leading_parser \"builtin_initialize \" >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n\n@[builtinCommandParser] def \u00abin\u00bb  := trailing_parser \" in \" >> commandParser\n\n/-\n  This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`.\n  It is meant for bootstrapping purposes only. -/\n@[builtinCommandParser] def genInjectiveTheorems := leading_parser \"gen_injective_theorems% \" >> ident\n\n@[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false\n@[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true\n\nbuiltin_initialize\n  register_parser_alias \"declModifiers\"       declModifiersF\n  register_parser_alias \"nestedDeclModifiers\" declModifiersT\n  register_parser_alias \"declId\"              declId\n  register_parser_alias \"declSig\"             declSig\n  register_parser_alias \"declVal\"             declVal\n  register_parser_alias \"optDeclSig\"          optDeclSig\n  register_parser_alias \"openDecl\"            openDecl\n\nend Command\n\nnamespace Term\n@[builtinTermParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> \" in \" >> termParser\n@[builtinTermParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> termParser\nend Term\n\nnamespace Tactic\n@[builtinTacticParser] def \u00abopen\u00bb := leading_parser:leadPrec \"open \" >> Command.openDecl >> \" in \" >> tacticSeq\n@[builtinTacticParser] def \u00abset_option\u00bb := leading_parser:leadPrec \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> tacticSeq\nend Tactic\n\nend Parser\nend Lean\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/Parser/Command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1847675016698433, "lm_q2_score": 0.03210070961065096, "lm_q1q2_score": 0.005931167916589105}}
{"text": "import Lean.Elab\n\nstructure Bar where\n\nstructure Foo where\n  foo\u2081 : Nat\n  foo\u2082 : Nat\n  bar  : Bar\n\ndef mkFoo\u2081 : Foo := {\n--v textDocument/definition\n  foo\u2081 := 1\n--v textDocument/declaration\n  foo\u2082 := 2\n--v textDocument/typeDefinition\n  bar := \u27e8\u27e9\n}\n\nstructure HandWrittenStruct where\n  n : Nat\n\n-- def HandWrittenStruct.n := fun | mk n => n\n\n          --v textDocument/definition\ndef hws : HandWrittenStruct := {\n--v textDocument/definition\n  n := 3\n}\n\n            --v textDocument/declaration\ndef mkFoo\u2082 := mkFoo\u2081\n\nsyntax (name := elabTest) \"test\" : term\n\n@[termElab elabTest] def elabElabTest : Lean.Elab.Term.TermElab := fun _ _ => do\n  let stx \u2190 `(2)\n  Lean.Elab.Term.elabTerm stx none\n\n     --v textDocument/declaration\n#check test\n     --^ textDocument/definition\n\ndef Baz (\u03b1 : Type) := \u03b1\n\n#check fun (b : Baz Nat) => b\n                          --^ textDocument/typeDefinition\n\nexample : Nat :=\n  let a := 1\n--v textDocument/definition\n  a + b\n    --^ textDocument/definition\nwhere\n  b := 2\n\nmacro_rules | `(test) => `(3)\n#check test\n     --^ textDocument/definition\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/interactive/goTo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2018132126589859, "lm_q2_score": 0.029312228101462088, "lm_q1q2_score": 0.005915594923349071}}
{"text": "import Lean.Elab.Do\nimport Lean.Util.CollectLevelParams\n\n/-\n## HBind definition\n-/\n\nclass HBind (m : Type u1 \u2192 Type v1) (n : Type u2 \u2192 Type v2) where\n  hBind {\u03b1 : Type u1} {\u03b2 : Type u2} : m \u03b1 \u2192 (\u03b1 \u2192 n \u03b2) \u2192 n \u03b2\n\n@[defaultInstance] instance [Bind m] : HBind m m := \u27e8bind\u27e9\n\ninstance: HBind Id.{u} Id.{v} where\n  hBind {\u03b1: Type u} {\u03b2: Type v} (x: Id \u03b1) (f: \u03b1 \u2192 Id \u03b2): Id \u03b2 := f x\n\n/-\n## `hdo` notation: parsing\n-/\n\nsyntax (name := hdo) \"hdo\" doSeq: term\n\n-- Variation where we specify the type of the monad (to avoid inferring it as\n-- [Type \u2192 Type])\nsyntax (name := hdo_2) \"hdo \" atomic(\"(\" &\"monad\" \" := \" term \")\") doSeq: term\n\n/-\n## `hdo` notation: elaboration\n\nMost of this is copied from src/Lean/Elab/Do.lean. Look for \"HDO:\" to find the\ndifferences with the implementation of \"do\".\n-/\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Lean.Elab.Term\nopen Meta\n\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Meta\n\nprivate def getDoSeqElems (doSeq : Syntax) : List Syntax :=\n  if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then\n    doSeq[1].getArgs.toList.map fun arg => arg[0]\n  else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then\n    doSeq[0].getArgs.toList.map fun arg => arg[0]\n  else\n    []\n\nprivate def getDoSeq (doStx : Syntax) : Syntax :=\n  doStx[1]\n\n@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>\n  throwErrorAt stx \"invalid use of `(<- ...)`, must be nested inside a 'do' expression\"\n\n/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/\nprivate def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=\n  k == ``Lean.Parser.Term.do ||\n  k == ``Lean.Parser.Term.doSeqIndent ||\n  k == ``Lean.Parser.Term.doSeqBracketed ||\n  k == ``Lean.Parser.Term.termReturn ||\n  k == ``Lean.Parser.Term.termUnless ||\n  k == ``Lean.Parser.Term.termTry ||\n  k == ``Lean.Parser.Term.termFor\n\n/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/\nprivate def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=\n  let k := letDeclArg.getKind\n  if k == ``Lean.Parser.Term.letPatDecl then\n    false\n  else if k == ``Lean.Parser.Term.letEqnsDecl then\n    true\n  else if k == ``Lean.Parser.Term.letIdDecl then\n    -- letIdLhs := ident >> checkWsBefore \"expected space before binders\" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType\n    let binders := letDeclArg[1]\n    binders.getNumArgs > 0\n  else\n    false\n\n/-- Return `true` if the given `letDecl` contains binders. -/\nprivate def letDeclHasBinders (letDecl : Syntax) : Bool :=\n  letDeclArgHasBinders letDecl[0]\n\n/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/\nprivate def liftMethodForbiddenBinder (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||\n     k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec  then\n     -- It is never ok to lift over this kind of binder\n    true\n  -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not\n  else if k == ``Lean.Parser.Term.let then\n    letDeclHasBinders stx[1]\n  else if k == ``Lean.Parser.Term.doLet then\n    letDeclHasBinders stx[2]\n  else if k == ``Lean.Parser.Term.doLetArrow then\n    letDeclArgHasBinders stx[2]\n  else\n    false\n\nprivate partial def hasLiftMethod : Syntax \u2192 Bool\n  | Syntax.node _ k args =>\n    if liftMethodDelimiter k then false\n    -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a\n    -- bit slower\n    else if k == ``Lean.Parser.Term.liftMethod then true\n    else args.any hasLiftMethod\n  | _ => false\n\nstructure ExtractMonadResult where\n  m            : Expr\n  \u03b1            : Expr\n  expectedType : Expr\n\nprivate partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do\n  match expectedType? with\n  | none => throwError \"invalid 'do' notation, expected type is not available\"\n  | some expectedType =>\n    let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match type with\n      | Expr.app m \u03b1 _ =>\n        try\n          let bindInstType \u2190 mkAppM ``Bind #[m]\n          let _  \u2190 Meta.synthInstance bindInstType\n          return some { m := m, \u03b1 := \u03b1, expectedType := expectedType }\n        catch _ =>\n          return none\n      | _ =>\n        return none\n    let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match (\u2190 extractStep? type) with\n      | some r => return r\n      | none =>\n        let typeNew \u2190 whnfCore type\n        if typeNew != type then\n          extract? typeNew\n        else\n          if typeNew.getAppFn.isMVar then throwError \"invalid 'do' notation, expected type is not available\"\n          match (\u2190 unfoldDefinition? typeNew) with\n          | some typeNew => extract? typeNew\n          | none => return none\n    match (\u2190 extract? expectedType) with\n    | some r => return r\n    | none   => throwError \"invalid 'do' notation, expected type is not a monad application{indentExpr expectedType}\\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad.\"\n\nnamespace HDo\n\nabbrev Var := Syntax  -- TODO: should be `TSyntax identKind`\n\n/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/\nstructure Alt (\u03c3 : Type) where\n  ref : Syntax\n  vars : Array Var\n  patterns : Syntax\n  rhs : \u03c3\n  deriving Inhabited\n\n/-\n  Auxiliary datastructure for representing a `do` code block, and compiling \"reassignments\" (e.g., `x := x + 1`).\n  We convert `Code` into a `Syntax` term representing the:\n  - `do`-block, or\n  - the visitor argument for the `forIn` combinator.\n\n  We say the following constructors are terminals:\n  - `break`:    for interrupting a `for x in s`\n  - `continue`: for interrupting the current iteration of a `for x in s`\n  - `return e`: for returning `e` as the result for the whole `do` computation block\n  - `action a`: for executing action `a` as a terminal\n  - `ite`:      if-then-else\n  - `match`:    pattern matching\n  - `jmp`       a goto to a join-point\n\n  We say the terminals `break`, `continue`, `action`, and `return` are \"exit points\"\n\n  Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x == 0 then\n     return ()\n  IO.println \"hello\"\n  ```\n  Executing `#eval f 0` will not print \"hello\". Now, consider\n  ```\n  def g (x : Nat) : IO Unit := do\n  if x == 0 then\n     pure ()\n  IO.println \"hello\"\n  ```\n  The `if` statement is essentially a noop, and \"hello\" is printed when we execute `g 0`.\n\n  - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).\n    The field `stx` is the actual `doElem`,\n    `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.\n    `vars` is an array since we have declarations such as `let (a, b) := s`.\n\n  - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).\n\n  - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.\n\n  - `seq a k` executes action `a`, ignores its result, and then executes `k`.\n    We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.\n\n  A code block `C` is well-formed if\n  - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and\n    `ps.size == as.size` -/\ninductive Code where\n  | decl         (xs : Array Var) (doElem : Syntax) (k : Code)\n  | reassign     (xs : Array Var) (doElem : Syntax) (k : Code)\n  /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/\n  | joinpoint    (name : Name) (params : Array (Var \u00d7 Bool)) (body : Code) (k : Code)\n  | seq          (action : Syntax) (k : Code)\n  | action       (action : Syntax)\n  | \u00abbreak\u00bb      (ref : Syntax)\n  | \u00abcontinue\u00bb   (ref : Syntax)\n  | \u00abreturn\u00bb     (ref : Syntax) (val : Syntax)\n  /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/\n  | ite          (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)\n  | \u00abmatch\u00bb      (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code))\n  | jmp          (ref : Syntax) (jpName : Name) (args : Array Syntax)\n  deriving Inhabited\n\nabbrev VarSet := Std.RBMap Name Syntax Name.cmp\n\n/- A code block, and the collection of variables updated by it. -/\nstructure CodeBlock where\n  code  : Code\n  uvars : VarSet := {} -- set of variables updated by `code`\n\nprivate def varSetToArray (s : VarSet) : Array Var :=\n  s.fold (fun xs _ x => xs.push x) #[]\n\nprivate def varsToMessageData (vars : Array Var) : MessageData :=\n  MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) \" \"\n\npartial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=\n  let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax\n  let rec loop : Code \u2192 MessageData\n    | Code.decl xs _ k            => m!\"let {varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.reassign xs _ k        => m!\"{varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.joinpoint n ps body k  => m!\"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\\n{loop k}\"\n    | Code.seq e k                => m!\"{e}\\n{loop k}\"\n    | Code.action e               => e\n    | Code.ite _ _ _ c t e        => m!\"if {c} then {indentD (loop t)}\\nelse{loop e}\"\n    | Code.jmp _ j xs             => m!\"jmp {j.simpMacroScopes} {xs.toList}\"\n    | Code.\u00abbreak\u00bb _              => m!\"break {us}\"\n    | Code.\u00abcontinue\u00bb _           => m!\"continue {us}\"\n    | Code.\u00abreturn\u00bb _ v           => m!\"return {v} {us}\"\n    | Code.\u00abmatch\u00bb _ _ ds t alts  =>\n      m!\"match {ds} with\"\n      ++ alts.foldl (init := m!\"\") fun acc alt => acc ++ m!\"\\n| {alt.patterns} => {loop alt.rhs}\"\n  loop codeBlock.code\n\n/- Return true if the give code contains an exit point that satisfies `p` -/\npartial def hasExitPointPred (c : Code) (p : Code \u2192 Bool) : Bool :=\n  let rec loop : Code \u2192 Bool\n    | Code.decl _ _ k           => loop k\n    | Code.reassign _ _ k       => loop k\n    | Code.joinpoint _ _ b k    => loop b || loop k\n    | Code.seq _ k              => loop k\n    | Code.ite _ _ _ _ t e      => loop t || loop e\n    | Code.\u00abmatch\u00bb _ _ _ _ alts => alts.any (loop \u00b7.rhs)\n    | Code.jmp _ _ _            => false\n    | c                         => p c\n  loop c\n\ndef hasExitPoint (c : Code) : Bool :=\n  hasExitPointPred c fun c => true\n\ndef hasReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef hasTerminalAction (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abaction\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinue (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinueReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax \u2192 m Code) : m Code := withRef e <| withFreshMacroScope do\n  let y \u2190 `(y)\n  let doElem \u2190 `(doElem| let y \u2190 $e:term)\n  -- Add elaboration hint for producing sane error message\n  let y \u2190 `(ensure_expected_type% \"type mismatch, result value\" $y)\n  let k \u2190 mkCont y\n  return Code.decl #[y] doElem k\n\n/- Convert `action _ e` instructions in `c` into `let y \u2190 e; jmp _ jp (xs y)`. -/\npartial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code :=\n  let rec loop : Code \u2192 MacroM Code\n    | Code.decl xs stx k           => return Code.decl xs stx (\u2190 loop k)\n    | Code.reassign xs stx k       => return Code.reassign xs stx (\u2190 loop k)\n    | Code.joinpoint n ps b k      => return Code.joinpoint n ps (\u2190 loop b) (\u2190 loop k)\n    | Code.seq e k                 => return Code.seq e (\u2190 loop k)\n    | Code.ite ref x? h c t e      => return Code.ite ref x? h c (\u2190 loop t) (\u2190 loop e)\n    | Code.\u00abmatch\u00bb ref g ds t alts => return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 loop alt.rhs) })\n    | Code.action e                => mkAuxDeclFor e fun y =>\n      let ref := e\n      -- We jump to `jp` with xs **and** y\n      let jmpArgs := xs.push y\n      return Code.jmp ref jp jmpArgs\n    | c                            => return c\n  loop code\n\nstructure JPDecl where\n  name : Name\n  params : Array (Var \u00d7 Bool)\n  body : Code\n\ndef attachJP (jpDecl : JPDecl) (k : Code) : Code :=\n  Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k\n\ndef attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=\n  jpDecls.foldr attachJP k\n\ndef mkFreshJP (ps : Array (Var \u00d7 Bool)) (body : Code) : TermElabM JPDecl := do\n  let ps \u2190\n    if ps.isEmpty then\n      let y \u2190 `(y)\n      pure #[(y, false)]\n    else\n      pure ps\n  -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by\n  -- the \"do\" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`\n  -- We will remove this hack when we re-implement the compiler frontend in Lean.\n  let name \u2190 mkFreshUserName `_do_jp\n  pure { name := name, params := ps, body := body }\n\ndef addFreshJP (ps : Array (Var \u00d7 Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do\n  let jp \u2190 mkFreshJP ps body\n  modify fun (jps : Array JPDecl) => jps.push jp\n  pure jp.name\n\ndef insertVars (rs : VarSet) (xs : Array Var) : VarSet :=\n  xs.foldl (fun rs x => rs.insert x.getId x) rs\n\ndef eraseVars (rs : VarSet) (xs : Array Var) : VarSet :=\n  xs.foldl (\u00b7.erase \u00b7.getId) rs\n\ndef eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet :=\n  match x? with\n  | none   => rs\n  | some x => rs.insert x.getId x\n\n/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/\ndef mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := varSetToArray rs\n  let jp \u2190 addFreshJP (xs.map fun x => (x, true)) c\n  if xs.isEmpty then\n    let unit \u2190 ``(Unit.unit)\n    return Code.jmp ref jp #[unit]\n  else\n    return Code.jmp ref jp xs\n\n/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.\n   The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`\n   is a fresh variable created by this method. -/\ndef mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax \u2192 MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := varSetToArray rs\n  let args := xs.push val\n  let yFresh \u2190 withRef ref `(y)\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (yFresh, false)\n  let jpBody \u2190 liftMacroM <| mkJPBody yFresh\n  let jp \u2190 addFreshJP ps jpBody\n  return Code.jmp ref jp args\n\n/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path.  -/\npartial def pullExitPointsAux : VarSet \u2192 Code \u2192 StateRefT (Array JPDecl) TermElabM Code\n  | rs, Code.decl xs stx k           => return Code.decl xs stx (\u2190 pullExitPointsAux (eraseVars rs xs) k)\n  | rs, Code.reassign xs stx k       => return Code.reassign xs stx (\u2190 pullExitPointsAux (insertVars rs xs) k)\n  | rs, Code.joinpoint j ps b k      => return Code.joinpoint j ps (\u2190 pullExitPointsAux rs b) (\u2190 pullExitPointsAux rs k)\n  | rs, Code.seq e k                 => return Code.seq e (\u2190 pullExitPointsAux rs k)\n  | rs, Code.ite ref x? o c t e      => return Code.ite ref x? o c (\u2190 pullExitPointsAux (eraseOptVar rs x?) t) (\u2190 pullExitPointsAux (eraseOptVar rs x?) e)\n  | rs, Code.\u00abmatch\u00bb ref g ds t alts => return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })\n  | rs, c@(Code.jmp _ _ _)           => return  c\n  | rs, Code.\u00abbreak\u00bb ref             => mkSimpleJmp ref rs (Code.\u00abbreak\u00bb ref)\n  | rs, Code.\u00abcontinue\u00bb ref          => mkSimpleJmp ref rs (Code.\u00abcontinue\u00bb ref)\n  | rs, Code.\u00abreturn\u00bb ref val        => mkJmp ref rs val (fun y => return Code.\u00abreturn\u00bb ref y)\n  | rs, Code.action e                =>\n    -- We use `mkAuxDeclFor` because `e` is not pure.\n    mkAuxDeclFor e fun y =>\n      let ref := e\n      mkJmp ref rs y (fun yFresh => return Code.action (\u2190 ``(Pure.pure $yFresh)))\n\n/-\nAuxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.\nWhen a new variable is not already in the collection, but is shadowed by some declaration in `c`,\nwe create auxiliary join points to make sure we preserve the semantics of the code block.\nExample: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it\nwith the reassignment `x := x + 1`. We first use `pullExitPoints` to create\n```\nlet jp (x!1) :=  return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nand then we add the reassignment\n```\nx := x + 1\nlet jp (x!1) := return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nNote that we created a fresh variable `x!1` to avoid accidental name capture.\nAs another example, consider\n```\nprint x;\nlet x := 10\ny := y + 1;\nreturn x;\n```\nWe transform it into\n```\nlet jp (y x!1) := return x!1;\nprint x;\nlet x := 10\ny := y + 1;\njmp jp y x\n```\nand then we add the reassignment as in the previous example.\nWe need to include `y` in the jump, because each exit point is implicitly returning the set of\nupdate variables.\n\nWe implement the method as follows. Let `us` be `c.uvars`, then\n1- for each `return _ y` in `c`, we create a join point\n  `let j (us y!1) := return y!1`\n   and replace the `return _ y` with `jmp us y`\n2- for each `break`, we create a join point\n  `let j (us) := break`\n   and replace the `break` with `jmp us`.\n3- Same as 2 for `continue`.\n-/\ndef pullExitPoints (c : Code) : TermElabM Code := do\n  if hasExitPoint c then\n    let (c, jpDecls) \u2190 (pullExitPointsAux {} c).run #[]\n    return attachJPs jpDecls c\n  else\n    return c\n\npartial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code :=\n  let rec update : Code \u2192 TermElabM Code\n    | Code.joinpoint j ps b k          => return Code.joinpoint j ps (\u2190 update b) (\u2190 update k)\n    | Code.seq e k                     => return Code.seq e (\u2190 update k)\n    | c@(Code.\u00abmatch\u00bb ref g ds t alts) => do\n      if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then\n        -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 update alt.rhs) })\n    | Code.ite ref none o c t e => return Code.ite ref none o c (\u2190 update t) (\u2190 update e)\n    | c@(Code.ite ref (some h) o cond t e) => do\n      if ws.contains h.getId then\n        -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.ite ref (some h) o cond (\u2190 update t) (\u2190 update e)\n    | Code.reassign xs stx k => return Code.reassign xs stx (\u2190 update k)\n    | c@(Code.decl xs stx k) => do\n      if xs.any fun x => ws.contains x.getId then\n        -- One the declared variables is shadowing a variable in `ws`\n        pullExitPoints c\n      else\n        return Code.decl xs stx (\u2190 update k)\n    | c => return  c\n  update c\n\n/-\nExtend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.\nWe **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.\nSee discussion at `pullExitPoints`.\n-/\npartial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do\n  if ws.any fun x _ => !c.uvars.contains x then\n    -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)\n    pure { code := (\u2190 extendUpdatedVarsAux c.code ws), uvars := ws }\n  else\n    pure { c with uvars := ws }\n\nprivate def union (s\u2081 s\u2082 : VarSet) : VarSet :=\n  s\u2081.fold (\u00b7.insert \u00b7) s\u2082\n\n/-\nGiven two code blocks `c\u2081` and `c\u2082`, make sure they have the same set of updated variables.\nLet `ws` the union of the updated variables in `c\u2081\u2035 and \u2035c\u2082`.\nWe use `extendUpdatedVars c\u2081 ws` and `extendUpdatedVars c\u2082 ws`\n-/\ndef homogenize (c\u2081 c\u2082 : CodeBlock) : TermElabM (CodeBlock \u00d7 CodeBlock) := do\n  let ws := union c\u2081.uvars c\u2082.uvars\n  let c\u2081 \u2190 extendUpdatedVars c\u2081 ws\n  let c\u2082 \u2190 extendUpdatedVars c\u2082 ws\n  pure (c\u2081, c\u2082)\n\n/-\nExtending code blocks with variable declarations: `let x : t := v` and `let x : t \u2190 v`.\nWe remove `x` from the collection of updated varibles.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `let (x, y) := t`\n-/\ndef mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := {\n  code := Code.decl xs stx c.code,\n  uvars := eraseVars c.uvars xs\n}\n\n/-\nExtending code blocks with reassignments: `x : t := v` and `x : t \u2190 v`.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `(x, y) \u2190 t`\n-/\ndef mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do\n  let us := c.uvars\n  let ws := insertVars us xs\n  -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.\n  -- See discussion at `pullExitPoints`\n  let code \u2190 if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code\n  pure { code := Code.reassign xs stx code, uvars := ws }\n\ndef mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=\n  { c with code := Code.seq action c.code }\n\ndef mkTerminalAction (action : Syntax) : CodeBlock :=\n  { code := Code.action action }\n\ndef mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=\n  { code := Code.\u00abreturn\u00bb ref val }\n\ndef mkBreak (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abbreak\u00bb ref }\n\ndef mkContinue (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abcontinue\u00bb ref }\n\ndef mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do\n  let x? := optIdent.getOptional?\n  let (thenBranch, elseBranch) \u2190 homogenize thenBranch elseBranch\n  pure {\n    code  := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,\n    uvars := thenBranch.uvars,\n  }\n\nprivate def mkUnit : MacroM Syntax :=\n  ``((\u27e8\u27e9 : PUnit))\n\nprivate def mkPureUnit : MacroM Syntax :=\n  ``(pure PUnit.unit)\n\ndef mkPureUnitAction : MacroM CodeBlock := do\n  return mkTerminalAction (\u2190 mkPureUnit)\n\ndef mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do\n  let thenBranch \u2190 mkPureUnitAction\n  pure { c with code := Code.ite (\u2190 getRef) none mkNullNode cond thenBranch.code c.code }\n\ndef mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do\n  -- nary version of homogenize\n  let ws := alts.foldl (union \u00b7 \u00b7.rhs.uvars) {}\n  let alts \u2190 alts.mapM fun alt => do\n    let rhs \u2190 extendUpdatedVars alt.rhs ws\n    return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }\n  return { code := Code.\u00abmatch\u00bb ref genParam discrs optMotive alts, uvars := ws }\n\n/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.\n   This method assumes `terminal` is a terminal -/\ndef concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do\n  unless hasTerminalAction terminal.code do\n    throwErrorAt kRef \"'do' element is unreachable\"\n  let (terminal, k) \u2190 homogenize terminal k\n  let xs := varSetToArray k.uvars\n  let y \u2190 match y? with | some y => pure y | none => `(y)\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (y, false)\n  let jpDecl \u2190 mkFreshJP ps k.code\n  let jp := jpDecl.name\n  let terminal \u2190 liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs\n  return { code  := attachJP jpDecl terminal, uvars := k.uvars }\n\ndef getLetIdDeclVar (letIdDecl : Syntax) : Var :=\n  letIdDecl[0]\n\n-- support both regular and syntax match\ndef getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) :=\n  getPatternVars pattern <|>\n  Quotation.getPatternVars pattern\n\ndef getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) :=\n  getPatternsVars patterns <|>\n  Quotation.getPatternsVars patterns\n\ndef getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do\n  let pattern := letPatDecl[0]\n  getPatternVarsEx pattern\n\ndef getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var :=\n  letEqnsDecl[0]\n\ndef getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do\n  let arg := letDecl[0]\n  if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n    return #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then\n    return #[getLetEqnsDeclVar arg]\n  else\n    throwError \"unexpected kind of let declaration\"\n\ndef getDoLetVars (doLet : Syntax) : TermElabM (Array Var) :=\n  -- leading_parser \"let \" >> optional \"mut \" >> letDecl\n  getLetDeclVars doLet[2]\n\ndef getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var :=\n  if optIdent.isNone then\n    `(this)\n  else\n    pure optIdent[0]\n\ndef getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do\n  -- doHave := leading_parser \"have \" >> Term.haveDecl\n  -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl\n  let arg := doHave[1][0]\n  if arg.getKind == ``Lean.Parser.Term.haveIdDecl then\n    -- haveIdDecl := leading_parser atomic (haveIdLhs >> \" := \") >> termParser\n    -- haveIdLhs := optional (ident >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder))) >> optType\n    return #[\u2190 getHaveIdLhsVar arg[0]]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Lean.Parser.Term.haveEqnsDecl then\n    -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts\n    return #[\u2190 getHaveIdLhsVar arg[0]]\n  else\n    throwError \"unexpected kind of have declaration\"\n\ndef getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do\n  -- letRecDecls is an array of `(group (optional attributes >> letDecl))`\n  let letRecDecls := doLetRec[1][0].getSepArgs\n  let letDecls := letRecDecls.map fun p => p[2]\n  let mut allVars := #[]\n  for letDecl in letDecls do\n    let vars \u2190 getLetDeclVars letDecl\n    allVars := allVars ++ vars\n  return allVars\n\n-- ident >> optType >> leftArrow >> termParser\ndef getDoIdDeclVar (doIdDecl : Syntax) : Var :=\n  doIdDecl[0]\n\n-- termParser >> leftArrow >> termParser >> optional (\" | \" >> termParser)\ndef getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do\n  let pattern := doPatDecl[0]\n  getPatternVarsEx pattern\n\n-- leading_parser \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\ndef getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do\n  let decl := doLetArrow[2]\n  if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n    return #[getDoIdDeclVar decl]\n  else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n    getDoPatDeclVars decl\n  else\n    throwError \"unexpected kind of 'do' declaration\"\n\ndef getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do\n  let arg := doReassign[0]\n  if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n    return #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else\n    throwError \"unexpected kind of reassignment\"\n\ndef mkDoSeq (doElems : Array Syntax) : Syntax :=\n  mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]\n\ndef mkSingletonDoSeq (doElem : Syntax) : Syntax :=\n  mkDoSeq #[doElem]\n\n/-\n  If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s.  -/\nprivate def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with\n  | `(doElem|if $p:doIfProp then $t else $e) => pure none\n  | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do\n    let mut e      := e?.getD (\u2190 `(doSeq|pure PUnit.unit))\n    let mut eIsSeq := true\n    for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do\n      e \u2190 if eIsSeq then pure e else `(doSeq|$e:doElem)\n      e \u2190 withRef cond <| match cond with\n        | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)\n        | `(doIfCond|let $pat \u2190 $d)  => `(doElem| match%$i \u2190 $d    with | $pat:term => $t | _ => $e)\n        | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)\n        | _                          => `(doElem| if%$i $(Syntax.missing) then $t else $e)\n      eIsSeq := false\n    return some e\n  | _ => pure none\n\nstructure DoIfView where\n  ref        : Syntax\n  optIdent   : Syntax\n  cond       : Syntax\n  thenBranch : Syntax\n  elseBranch : Syntax\n\n/- This method assumes `expandDoIf?` is not applicable. -/\nprivate def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do\n  pure {\n    ref        := doIf,\n    optIdent   := doIf[1][0],\n    cond       := doIf[1][1],\n    thenBranch := doIf[3],\n    elseBranch := doIf[5][1]\n  }\n\n/-\nHDO: We use `Prod` instead of `MProd` for exactly the opposite reason\n-/\nprivate def mkTuple (elems : Array Syntax) : MacroM Syntax := do\n  if elems.size == 0 then\n    mkUnit\n  else if elems.size == 1 then\n    return elems[0]\n  else\n    elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple =>\n      ``(Prod.mk $elem $tuple)\n\n/- Return `some action` if `doElem` is a `doExpr <action>`-/\ndef isDoExpr? (doElem : Syntax) : Option Syntax :=\n  if doElem.getKind == ``Lean.Parser.Term.doExpr then\n    some doElem[0]\n  else\n    none\n\n/--\n  Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term\n  ```\n  let a_1     := x.1\n  let x       := x.2\n  let a_2     := x.1\n  let x       := x.2\n  ...\n  let a_n     := x.1\n  let a_{n+1} := x.2\n  body\n  ```\n  Special cases\n  - `uvars := #[]` => `body`\n  - `uvars := #[a]` => `let a := x; body`\n\n\n  We use this method when expanding the `for-in` notation.\n-/\nprivate def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n  if uvars.size == 0 then\n    return body\n  else if uvars.size == 1 then\n    `(let $(uvars[0]):ident := $x; $body)\n  else\n    destruct uvars.toList x body\nwhere\n  destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n    match as with\n      | [a, b]  => `(let $a:ident := $x.1; let $b:ident := $x.2; $body)\n      | a :: as => withFreshMacroScope do\n        let rest \u2190 destruct as (\u2190 `(x)) body\n        `(let $a:ident := $x.1; let x := $x.2; $rest)\n      | _ => unreachable!\n\n/-\nThe procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.\nWe use this method to convert\n1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of\n   `CodeBlock` never contains `break` nor `continue`. Moreover, the collection\n   of updated variables is not packed into the result.\n   Thus, we have two kinds of exit points\n     - `Code.action e` which is converted into `e`\n     - `Code.return _ e` which is converted into `pure e`\n\n   We use `Kind.regular` for this case.\n\n2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate\n   a `Syntax` term representing a function for the `xs.forIn` combinator.\n\n   a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term\n      has type `m (ForInStep (Option \u03b1 \u00d7 \u03c3))`, where `a : \u03b1`, and the `\u03c3` is the type\n      of the tuple of variables reassigned by `b`.\n      We use `Kind.forInWithReturn` for this case\n\n   b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated\n      `Syntax` term has type `m (ForInStep \u03c3)`.\n      We use `Kind.forIn` for this case.\n\n3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).\n\n   The generated `Syntax` term for `c` must inform whether `c` \"exited\" using `Code.action`, `Code.return`,\n   `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.\n   For example, the auxiliary type `DoResultPBC \u03b1 \u03c3` is used for a code block that exits with `Code.action`,\n   **and** `Code.break`/`Code.continue`, `\u03b1` is the type of values produced by the exit `action`, and\n   `\u03c3` is the type of the tuple of reassigned variables.\n   The type `DoResult \u03b1 \u03b2 \u03c3` is usedf for code blocks that exit with\n   `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `\u03b2` is the type of the returned values.\n   We don't use `DoResult \u03b1 \u03b2 \u03c3` for all cases because:\n\n      a) The elaborator would not be able to infer all type parameters without extra annotations. For example,\n         if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `\u03b2`.\n\n      b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),\n         but we don't want to consider \"unreachable\" cases.\n\n   We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.\n\n   When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,\n   and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.\n\n   - `a`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n\n   - `r`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n           Note that the code that pattern matches on the result will behave differently in this case.\n           It produces `return a` for this case, and `pure a` for the previous one.\n\n   - `b/c`: `Kind.nestedBC`, type `m (DoResultBC \u03c3)`\n\n   - `a` and `r`:   `Kind.nestedPR`, type `m (DoResultPR \u03b1 \u03b2 \u03c3)`\n\n   - `a` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n\n   - `r` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n         Again the code that pattern matches on the result will behave differently in this case and\n         the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for\n         this case, and `pure a` for the previous case.\n\n   - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC \u03b1 \u03b2 \u03c3)`\n\nHere is the recipe for adding new combinators with nested `do`s.\nExample: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m \u03b1 \u2192 m \u03b1`\n1- Convert `doSeq` into `codeBlock : CodeBlock`\n2- Create term `term` using `mkNestedTerm code m uvars a r bc` where\n   `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,\n   `m` is a `Syntax` representing the Monad, and\n   `a` is true if `code` contains `Code.action _`,\n   `r` is true if `code` contains `Code.return _ _`,\n   `bc` is true if `code` contains `Code.break _` or `Code.continue _`.\n\n   Remark: for combinators such as `repeat` that take a single `doSeq`, all\n   arguments, but `m`, are extracted from `codeBlock`.\n3- Create the term `repeat $term`\n4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`\n\n-/\nnamespace ToTerm\n\ninductive Kind where\n  | regular\n  | forIn\n  | forInWithReturn\n  | nestedBC\n  | nestedPR\n  | nestedSBC\n  | nestedPRBC\n\ninstance : Inhabited Kind := \u27e8Kind.regular\u27e9\n\ndef Kind.isRegular : Kind \u2192 Bool\n  | Kind.regular => true\n  | _            => false\n\nstructure Context where\n  m     : Syntax -- Syntax to reference the monad associated with the do notation.\n  uvars : Array Var\n  kind  : Kind\n\nabbrev M := ReaderT Context MacroM\n\ndef mkUVarTuple : M Syntax := do\n  let ctx \u2190 read\n  mkTuple ctx.uvars\n\ndef returnToTerm (val : Syntax) : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (Prod.mk $val $u)) -- HDO: Prod\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (Prod.mk (some $val) $u))) -- HDO: Prod\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Pure.pure (DoResultPR.\u00abreturn\u00bb $val $u))\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abpureReturn\u00bb $val $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abreturn\u00bb $val $u))\n\ndef continueToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (Prod.mk none $u))) -- HDO: Prod\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abcontinue\u00bb $u))\n\ndef breakToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (Prod.mk none $u))) -- HDO: Prod\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abbreak\u00bb $u))\n\ndef actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then pure action else ``(HBind.hBind $action fun y => Pure.pure (Prod.mk y $u)) -- HDO: Prod, HBind\n  | Kind.forIn           => ``(HBind.hBind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) -- HDO: HBind\n  | Kind.forInWithReturn => ``(HBind.hBind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (Prod.mk none $u))) -- HDO: Prod, HBind\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(HBind.hBind $action fun y => (Pure.pure (DoResultPR.\u00abpure\u00bb y $u))) -- HDO: HBind\n  | Kind.nestedSBC       => ``(HBind.hBind $action fun y => (Pure.pure (DoResultSBC.\u00abpureReturn\u00bb y $u))) -- HDO: HBind\n  | Kind.nestedPRBC      => ``(HBind.hBind $action fun y => (Pure.pure (DoResultPRBC.\u00abpure\u00bb y $u))) -- HDO: HBind\n\ndef seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  if action.getKind == ``Lean.Parser.Term.doDbgTrace then\n    let msg := action[1]\n    `(dbg_trace $msg; $k)\n  else if action.getKind == ``Lean.Parser.Term.doAssert then\n    let cond := action[1]\n    `(assert! $cond; $k)\n  else\n    let action \u2190 withRef action ``(($action : $((\u2190read).m) PUnit))\n    ``(HBind.hBind $action (fun (_ : PUnit) => $k)) -- HDO: HBind\n\ndef declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do\n  let kind := decl.getKind\n  if kind == ``Lean.Parser.Term.doLet then\n    let letDecl := decl[2]\n    `(let $letDecl:letDecl; $k)\n  else if kind == ``Lean.Parser.Term.doLetRec then\n    let letRecToken := decl[0]\n    let letRecDecls := decl[1]\n    return mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]\n  else if kind == ``Lean.Parser.Term.doLetArrow then\n    let arg := decl[2]\n    let ref := arg\n    if arg.getKind == ``Lean.Parser.Term.doIdDecl then\n      let id     := arg[0]\n      let type   := expandOptType id arg[1]\n      let doElem := arg[3]\n      -- `doElem` must be a `doExpr action`. See `doLetArrowToCode`\n      match isDoExpr? doElem with\n      | some action =>\n        let action \u2190 withRef action `(($action : $((\u2190 read).m) $type))\n        ``(HBind.hBind $action (fun ($id:ident : $type) => $k))\n      | none        => Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n    else\n      Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n  else if kind == ``Lean.Parser.Term.doHave then\n    -- The `have` term is of the form  `\"have \" >> haveDecl >> optSemicolon termParser`\n    let args := decl.getArgs\n    let args := args ++ #[mkNullNode /- optional ';' -/, k]\n    return mkNode `Lean.Parser.Term.\u00abhave\u00bb args\n  else\n    Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n\ndef reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do\n  let kind := reassign.getKind\n  if kind == ``Lean.Parser.Term.doReassign then\n    -- doReassign := leading_parser (letIdDecl <|> letPatDecl)\n    let arg := reassign[0]\n    if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n      -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >>  \" := \" >> termParser\n      let x   := arg[0]\n      let val := arg[4]\n      let newVal \u2190 `(ensure_type_of% $x $(quote \"invalid reassignment, value\") $val)\n      let arg := arg.setArg 4 newVal\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n    else\n      -- TODO: ensure the types did not change\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n  else\n    -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode\n    Macro.throwErrorAt reassign \"unexpected kind of 'do' reassignment\"\n\ndef mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do\n  if optIdent.isNone then\n    ``(if $cond then $thenBranch else $elseBranch)\n  else\n    let h := optIdent[0]\n    ``(if $h:ident : $cond then $thenBranch else $elseBranch)\n\ndef mkJoinPoint (j : Name) (ps : Array (Syntax \u00d7 Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do\n  let pTypes \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => do if useTypeOf then `(type_of% $id) else `(_)\n  let ps     := ps.map (\u00b7.1)\n  /-\n  We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.\n  By elaborating `$k` first, we \"learn\" more about `$body`'s type.\n  For example, consider the following example `do` expression\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x > 0 then\n    IO.println \"x is not zero\" -- Error is here\n  IO.mkRef true\n  ```\n  it is expanded into\n  ```\n  def f (x : Nat) : IO Unit := do\n  let jp (u : Unit) : IO _ :=\n    IO.mkRef true;\n  if x > 0 then\n    IO.println \"not zero\"\n    jp ()\n  else\n    jp ()\n  ```\n  If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit \u2192 IO (IO.Ref Bool)`.\n  Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit \u2192 IO Unit`.\n  Then, we get the expected type mismatch error at `IO.mkRef true`. -/\n  `(let_delayed $(\u2190 mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((\u2190 read).m) _ := $body; $k)\n\ndef mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=\n  Syntax.mkApp (mkIdentFrom ref j) args\n\npartial def toTerm (c : Code) : M Syntax := do\n  match c with\n  | Code.return ref val     => withRef ref <| returnToTerm val\n  | Code.continue ref       => withRef ref continueToTerm\n  | Code.break ref          => withRef ref breakToTerm\n  | Code.action e           => actionTerminalToTerm e\n  | Code.joinpoint j ps b k => mkJoinPoint j ps (\u2190 toTerm b) (\u2190 toTerm k)\n  | Code.jmp ref j args     => return mkJmp ref j args\n  | Code.decl _ stx k       => declToTerm stx (\u2190 toTerm k)\n  | Code.reassign _ stx k   => reassignToTerm stx (\u2190 toTerm k)\n  | Code.seq stx k          => seqToTerm stx (\u2190 toTerm k)\n  | Code.ite ref _ o c t e  => withRef ref <| do mkIte o c (\u2190 toTerm t) (\u2190 toTerm e)\n  | Code.\u00abmatch\u00bb ref genParam discrs optMotive alts =>\n    let mut termAlts := #[]\n    for alt in alts do\n      let rhs \u2190 toTerm alt.rhs\n      let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref \"|\", mkNullNode #[alt.patterns], mkAtomFrom alt.ref \"=>\", rhs]\n      termAlts := termAlts.push termAlt\n    let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]\n    return mkNode `Lean.Parser.Term.\u00abmatch\u00bb #[mkAtomFrom ref \"match\", genParam, optMotive, discrs, mkAtomFrom ref \"with\", termMatchAlts]\n\ndef run (code : Code) (m : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax :=\n  toTerm code { m := m, kind := kind, uvars := uvars }\n\n/- Given\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   generate Kind. See comment at the beginning of the `ToTerm` namespace. -/\ndef mkNestedKind (a r bc : Bool) : Kind :=\n  match a, r, bc with\n  | true,  false, false => .regular\n  | false, true,  false => .regular\n  | false, false, true  => .nestedBC\n  | true,  true,  false => .nestedPR\n  | true,  false, true  => .nestedSBC\n  | false, true,  true  => .nestedSBC\n  | true,  true,  true  => .nestedPRBC\n  | false, false, false => unreachable!\n\ndef mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do\n  ToTerm.run code m uvars (mkNestedKind a r bc)\n\n/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.\n   See comment at the beginning of the `ToTerm` namespace.\n\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   The result is a sequence of `doElem` -/\ndef matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do\n  let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)\n  let u \u2190 mkTuple uvars\n  match a, r, bc with\n  | true, false, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do $term:term))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; pure r.1))\n  | false, true, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; return r))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; return r.1))\n  | false, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, false => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPR.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPR.\u00abreturn\u00bb b u => $u:term := u; return b)\n  | true, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; pure a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; return a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPRBC.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPRBC.\u00abreturn\u00bb a u => $u:term := u; return a\n         | DoResultPRBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultPRBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, false, false => unreachable!\n\nend ToTerm\n\ndef isMutableLet (doElem : Syntax) : Bool :=\n  let kind := doElem.getKind\n  (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)\n  &&\n  !doElem[1].isNone\n\nnamespace ToCodeBlock\n\nstructure Context where\n  ref         : Syntax\n  m           : Syntax -- Syntax representing the monad associated with the do notation.\n  mutableVars : VarSet := {}\n  insideFor   : Bool := false\n\nabbrev M := ReaderT Context TermElabM\n\ndef withNewMutableVars {\u03b1} (newVars : Array Var) (mutable : Bool) (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x\n\ndef checkReassignable (xs : Array Var) : M Unit := do\n  let throwInvalidReassignment (x : Name) : M Unit :=\n    throwError \"'{x.simpMacroScopes}' cannot be reassigned\"\n  let ctx \u2190 read\n  for x in xs do\n    unless ctx.mutableVars.contains x.getId do\n      throwInvalidReassignment x.getId\n\ndef checkNotShadowingMutable (xs : Array Var) : M Unit := do\n  let throwInvalidShadowing (x : Name) : M Unit :=\n    throwError \"mutable variable '{x.simpMacroScopes}' cannot be shadowed\"\n  let ctx \u2190 read\n  for x in xs do\n    if ctx.mutableVars.contains x.getId then\n      throwInvalidShadowing x.getId\n\ndef withFor {\u03b1} (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => { ctx with insideFor := true }) x\n\nstructure ToForInTermResult where\n  uvars      : Array Var\n  term       : Syntax\n\ndef mkForInBody  (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do\n  let ctx \u2190 read\n  let uvars := forInBody.uvars\n  let uvars := varSetToArray uvars\n  let term \u2190 liftMacroM <| ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)\n  return \u27e8uvars, term\u27e9\n\ndef ensureInsideFor : M Unit :=\n  unless (\u2190 read).insideFor do\n    throwError \"invalid 'do' element, it must be inside 'for'\"\n\ndef ensureEOS (doElems : List Syntax) : M Unit :=\n  unless doElems.isEmpty do\n    throwError \"must be last element in a 'do' sequence\"\n\nprivate partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax \u2192 StateT (List Syntax) M Syntax\n  | stx@(Syntax.node i k args) =>\n    if liftMethodDelimiter k then\n      return stx\n    else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do\n      if inBinder then\n        throwErrorAt stx \"cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`\"\n      let term := args[1]\n      let term \u2190 expandLiftMethodAux inQuot inBinder term\n      let auxDoElem \u2190 `(doElem| let a \u2190 $term:term)\n      modify fun s => s ++ [auxDoElem]\n      `(a)\n    else do\n      let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot\n      let inBinder   := inBinder || (!inQuot && liftMethodForbiddenBinder stx)\n      let args \u2190 args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)\n      return Syntax.node i k args\n  | stx => return stx\n\ndef expandLiftMethod (doElem : Syntax) : M (List Syntax \u00d7 Syntax) := do\n  if !hasLiftMethod doElem then\n    return ([], doElem)\n  else\n    let (doElem, doElemsNew) \u2190 (expandLiftMethodAux false false doElem).run []\n    return (doElemsNew, doElem)\n\ndef checkLetArrowRHS (doElem : Syntax) : M Unit := do\n  let kind := doElem.getKind\n  if kind == ``Lean.Parser.Term.doLetArrow ||\n     kind == ``Lean.Parser.Term.doLet ||\n     kind == ``Lean.Parser.Term.doLetRec ||\n     kind == ``Lean.Parser.Term.doHave ||\n     kind == ``Lean.Parser.Term.doReassign ||\n     kind == ``Lean.Parser.Term.doReassignArrow then\n    throwErrorAt doElem \"invalid kind of value '{kind}' in an assignment\"\n\n/- Generate `CodeBlock` for `doReturn` which is of the form\n   ```\n   \"return \" >> optional termParser\n   ```\n   `doElems` is only used for sanity checking. -/\ndef doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do\n  ensureEOS doElems\n  let argOpt := doReturn[1]\n  let arg \u2190 if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]\n  return mkReturn (\u2190 getRef) arg\n\nstructure Catch where\n  x         : Syntax\n  optType   : Syntax\n  codeBlock : CodeBlock\n\ndef getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet :=\n  let ws := tryCode.uvars\n  let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws\n  let ws := match finallyCode? with\n    | none   => ws\n    | some c => union c.uvars ws\n  ws\n\ndef tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code \u2192 Bool) : Bool :=\n  p tryCode.code ||\n  catches.any (fun \u00abcatch\u00bb => p \u00abcatch\u00bb.codeBlock.code) ||\n  match finallyCode? with\n  | none => false\n  | some finallyCode => p finallyCode.code\n\nmutual\n  /- \"Concatenate\" `c` with `doSeqToCode doElems` -/\n  partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=\n    match doElems with\n    | [] => pure c\n    | nextDoElem :: _  => do\n      let k \u2190 doSeqToCode doElems\n      let ref := nextDoElem\n      concat c ref none k\n\n  /- Generate `CodeBlock` for `doLetArrow; doElems`\n     `doLetArrow` is of the form\n     ```\n     \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\n     ```\n     where\n     ```\n     def doIdDecl   := leading_parser ident >> optType >> leftArrow >> doElemParser\n     def doPatDecl  := leading_parser termParser >> leftArrow >> doElemParser >> optional (\" | \" >> doElemParser)\n     ```\n  -/\n  partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref     := doLetArrow\n    let decl    := doLetArrow[2]\n    if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n      let y := decl[0]\n      checkNotShadowingMutable #[y]\n      let doElem := decl[3]\n      let k \u2190 withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)\n      match isDoExpr? doElem with\n      | some action => return mkVarDeclCore #[y] doLetArrow k\n      | none =>\n        checkLetArrowRHS doElem\n        let c \u2190 doSeqToCode [doElem]\n        match doElems with\n        | []       => pure c\n        | kRef::_  => concat c kRef y k\n    else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190\n          if isMutableLet doLetArrow then\n            `(do let discr \u2190 $doElem; let mut $pattern:term := discr)\n          else\n            `(do let discr \u2190 $doElem; let $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        if isMutableLet doLetArrow then\n          throwError \"'mut' is currently not supported in let-decls with 'else' case\"\n        let contSeq := mkDoSeq doElems.toArray\n        let elseSeq := mkSingletonDoSeq optElse[1]\n        let auxDo \u2190 `(do let discr \u2190 $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n    else\n      throwError \"unexpected kind of 'do' declaration\"\n\n  partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    -- \"let \" >> termParser >> \" := \" >> termParser >> checkColGt >> \" | \" >> doElemParser\n    let pattern := doLetElse[1]\n    let val     := doLetElse[3]\n    let elseSeq := mkSingletonDoSeq doLetElse[5]\n    let contSeq := mkDoSeq doElems.toArray\n    let auxDo \u2190 `(do let discr := $val; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n    doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n\n  /- Generate `CodeBlock` for `doReassignArrow; doElems`\n     `doReassignArrow` is of the form\n     ```\n     (doIdDecl <|> doPatDecl)\n     ```\n  -/\n  partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref  := doReassignArrow\n    let decl := doReassignArrow[0]\n    if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n      let doElem := decl[3]\n      let y      := decl[0]\n      let auxDo \u2190 `(do let r \u2190 $doElem; $y:ident := r)\n      doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n    else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 `(do let discr \u2190 $doElem; $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        throwError \"reassignment with `|` (i.e., \\\"else clause\\\") is not currently supported\"\n    else\n      throwError \"unexpected kind of 'do' reassignment\"\n\n  /- Generate `CodeBlock` for `doIf; doElems`\n     `doIf` is of the form\n     ```\n     \"if \" >> optIdent >> termParser >> \" then \" >> doSeq\n      >> many (group (try (group (\" else \" >> \" if \")) >> optIdent >> termParser >> \" then \" >> doSeq))\n      >> optional (\" else \" >> doSeq)\n     ```  -/\n  partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let view \u2190 liftMacroM $ mkDoIfView doIf\n    let thenBranch \u2190 doSeqToCode (getDoSeqElems view.thenBranch)\n    let elseBranch \u2190 doSeqToCode (getDoSeqElems view.elseBranch)\n    let ite \u2190 mkIte view.ref view.optIdent view.cond thenBranch elseBranch\n    concatWith ite doElems\n\n  /- Generate `CodeBlock` for `doUnless; doElems`\n     `doUnless` is of the form\n     ```\n     \"unless \" >> termParser >> \"do \" >> doSeq\n     ```  -/\n  partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do\n    let ref   := doUnless\n    let cond  := doUnless[1]\n    let doSeq := doUnless[3]\n    let body \u2190 doSeqToCode (getDoSeqElems doSeq)\n    let unlessCode \u2190 liftMacroM <| mkUnless cond body\n    concatWith unlessCode doElems\n\n  /- Generate `CodeBlock` for `doFor; doElems`\n     `doFor` is of the form\n     ```\n     def doForDecl := leading_parser termParser >> \" in \" >> withForbidden \"do\" termParser\n     def doFor := leading_parser \"for \" >> sepBy1 doForDecl \", \" >> \"do \" >> doSeq\n     ```\n  -/\n  partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let doForDecls := doFor[1].getSepArgs\n    if doForDecls.size > 1 then\n      /-\n        Expand\n        ```\n        for x in xs, y in ys do\n          body\n        ```\n        into\n        ```\n        let s := toStream ys\n        for x in xs do\n          match Stream.next? s with\n          | none => break\n          | some (y, s') =>\n            s := s'\n            body\n        ```\n      -/\n      -- Extract second element\n      let doForDecl := doForDecls[1]\n      unless doForDecl[0].isNone do\n        throwErrorAt doForDecl[0] \"the proof annotation here has not been implemented yet\"\n      let y  := doForDecl[1]\n      let ys := doForDecl[3]\n      let doForDecls := doForDecls.eraseIdx 1\n      let body := doFor[3]\n      withFreshMacroScope do\n        let toStreamFn \u2190 withRef ys ``(toStream)\n        let auxDo \u2190\n          `(do let mut s := $toStreamFn:ident $ys\n               for $doForDecls:doForDecl,* do\n                 match Stream.next? s with\n                 | none => break\n                 | some ($y, s') =>\n                   s := s'\n                   do $body)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n    else withRef doFor do\n      let h?        := if doForDecls[0][0].isNone then none else some doForDecls[0][0][0]\n      let x         := doForDecls[0][1]\n      withRef x <| checkNotShadowingMutable (\u2190 getPatternVarsEx x)\n      let xs        := doForDecls[0][3]\n      let forElems  := getDoSeqElems doFor[3]\n      let forInBodyCodeBlock \u2190 withFor (doSeqToCode forElems)\n      let \u27e8uvars, forInBody\u27e9 \u2190 mkForInBody x forInBodyCodeBlock\n      let ctx \u2190 read\n      -- semantic no-op that replaces the `uvars`' position information (which all point inside the loop)\n      -- with that of the respective mutable declarations outside the loop, which allows the language\n      -- server to identify them as conceptually identical variables\n      let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v\n      let uvarsTuple \u2190 liftMacroM do mkTuple uvars\n      if hasReturn forInBodyCodeBlock.code then\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190\n          if let some h := h? then\n            `(for_in'% $(xs) (Prod.mk none $uvarsTuple) fun $x $h r => let r := r.2; $forInBody) -- HDO: Prod\n          else\n            `(for_in% $(xs) (Prod.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) -- HDO: Prod\n        let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                         $uvarsTuple:term := r.2;\n                         match r.1 with\n                         | none => Pure.pure (ensure_expected_type% \"type mismatch, 'for'\" PUnit.unit)\n                         | some a => return ensure_expected_type% \"type mismatch, 'for'\" a)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n      else\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190\n          if let some h := h? then\n            `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody)\n          else\n            `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)\n        if doElems.isEmpty then\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                           $uvarsTuple:term := r;\n                           Pure.pure (ensure_expected_type% \"type mismatch, 'for'\" PUnit.unit))\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n        else\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term; $uvarsTuple:term := r)\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n\n  /-- Generate `CodeBlock` for `doMatch; doElems` -/\n  partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref       := doMatch\n    let genParam  := doMatch[1]\n    let optMotive := doMatch[2]\n    let discrs    := doMatch[3]\n    let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`\n    let matchAlts \u2190 matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (\u2190 liftMacroM <| expandMatchAlt matchAlt)\n    let alts \u2190  matchAlts.mapM fun matchAlt => do\n      let patterns := matchAlt[1][0]\n      let vars \u2190 getPatternsVarsEx patterns.getSepArgs\n      withRef patterns <| checkNotShadowingMutable vars\n      let rhs  := matchAlt[3]\n      let rhs \u2190 doSeqToCode (getDoSeqElems rhs)\n      pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }\n    let matchCode \u2190 mkMatch ref genParam discrs optMotive alts\n    concatWith matchCode doElems\n\n  /--\n    Generate `CodeBlock` for `doTry; doElems`\n    ```\n    def doTry := leading_parser \"try \" >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally\n    def doCatch      := leading_parser \"catch \" >> binderIdent >> optional (\":\" >> termParser) >> darrow >> doSeq\n    def doCatchMatch := leading_parser \"catch \" >> doMatchAlts\n    def doFinally    := leading_parser \"finally \" >> doSeq\n    ```\n  -/\n  partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref := doTry\n    let tryCode \u2190 doSeqToCode (getDoSeqElems doTry[1])\n    let optFinally := doTry[3]\n    let catches \u2190 doTry[2].getArgs.mapM fun catchStx => do\n      if catchStx.getKind == ``Lean.Parser.Term.doCatch then\n        let x       := catchStx[1]\n        if x.isIdent then\n          withRef x <| checkNotShadowingMutable #[x]\n        let optType := catchStx[2]\n        let c \u2190 doSeqToCode (getDoSeqElems catchStx[4])\n        return { x := x, optType := optType, codeBlock := c : Catch }\n      else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then\n        let matchAlts := catchStx[1]\n        let x \u2190 `(ex)\n        let auxDo \u2190 `(do match ex with $matchAlts)\n        let c \u2190 doSeqToCode (getDoSeqElems (getDoSeq auxDo))\n        return { x := x, codeBlock := c, optType := mkNullNode : Catch }\n      else\n        throwError \"unexpected kind of 'catch'\"\n    let finallyCode? \u2190 if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])\n    if catches.isEmpty && finallyCode?.isNone then\n      throwError \"invalid 'try', it must have a 'catch' or 'finally'\"\n    let ctx \u2190 read\n    let ws    := getTryCatchUpdatedVars tryCode catches finallyCode?\n    let uvars := varSetToArray ws\n    let a     := tryCatchPred tryCode catches finallyCode? hasTerminalAction\n    let r     := tryCatchPred tryCode catches finallyCode? hasReturn\n    let bc    := tryCatchPred tryCode catches finallyCode? hasBreakContinue\n    let toTerm (codeBlock : CodeBlock) : M Syntax := do\n      let codeBlock \u2190 liftM $ extendUpdatedVars codeBlock ws\n      liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc\n    let term \u2190 toTerm tryCode\n    let term \u2190 catches.foldlM (init := term) fun term \u00abcatch\u00bb => do\n      let catchTerm \u2190 toTerm \u00abcatch\u00bb.codeBlock\n      if catch.optType.isNone then\n        ``(MonadExcept.tryCatch $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n      else\n        let type := \u00abcatch\u00bb.optType[1]\n        ``(tryCatchThe $type $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n    let term \u2190 match finallyCode? with\n      | none             => pure term\n      | some finallyCode => withRef optFinally do\n        unless finallyCode.uvars.isEmpty do\n          throwError \"'finally' currently does not support reassignments\"\n        if hasBreakContinueReturn finallyCode.code then\n          throwError \"'finally' currently does 'return', 'break', nor 'continue'\"\n        let finallyTerm \u2190 liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular\n        ``(tryFinally $term $finallyTerm)\n    let doElemsNew \u2190 liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc\n    doSeqToCode (doElemsNew ++ doElems)\n\n  partial def doSeqToCode : List Syntax \u2192 M CodeBlock\n    | [] => do liftMacroM mkPureUnitAction\n    | doElem::doElems => withIncRecDepth <| withRef doElem do\n      checkMaxHeartbeats \"'do'-expander\"\n      match (\u2190 liftMacroM <| expandMacro? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n      match (\u2190 liftMacroM <| expandDoIf? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n        let (liftedDoElems, doElem) \u2190 expandLiftMethod doElem\n        if !liftedDoElems.isEmpty then\n          doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)\n        else\n          let ref := doElem\n          let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems\n          let k := doElem.getKind\n          if k == ``Lean.Parser.Term.doLet then\n            let vars \u2190 getDoLetVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doHave then\n            let vars \u2190 getDoHaveVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doLetRec then\n            let vars \u2190 getDoLetRecVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doReassign then\n            let vars \u2190 getDoReassignVars doElem\n            checkReassignable vars\n            let k \u2190 doSeqToCode doElems\n            mkReassignCore vars doElem k\n          else if k == ``Lean.Parser.Term.doLetArrow then\n            doLetArrowToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doLetElse then\n            doLetElseToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doReassignArrow then\n            doReassignArrowToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doIf then\n            doIfToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doUnless then\n            doUnlessToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do\n            doForToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doMatch then\n            doMatchToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doTry then\n            doTryToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doBreak then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkBreak ref\n          else if k == ``Lean.Parser.Term.doContinue then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkContinue ref\n          else if k == ``Lean.Parser.Term.doReturn then\n            doReturnToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doDbgTrace then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doAssert then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doNested then\n            let nestedDoSeq := doElem[1]\n            doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)\n          else if k == ``Lean.Parser.Term.doExpr then\n            let term := doElem[0]\n            if doElems.isEmpty then\n              return mkTerminalAction term\n            else\n              return mkSeq term (\u2190 doSeqToCode doElems)\n          else\n            throwError \"unexpected do-element of kind {doElem.getKind}:\\n{doElem}\"\nend\n\ndef run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=\n  (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m }\n\nend ToCodeBlock\n\n/- Create a synthetic metavariable `?m` and assign `m` to it.\n   We use `?m` to refer to `m` when expanding the `do` notation. -/\n\n-- HDO: Metavariables can't be universe polymorphic, so we instead hack and\n-- create a quantified external definition, then return the name of that\n-- definition as Syntax instead of ?m\nprivate def mkMonadAlias (m : Expr) : TermElabM Syntax := do\n  let levelParams := collectLevelParams {} m |>.params\n  let mType \u2190 inferType m\n  let name \u2190 mkFreshUserName `_hdo\n  let decl := Declaration.defnDecl {\n      name := name, levelParams := levelParams.toList, type := mType,\n      value := m, hints := ReducibilityHints.opaque,\n      safety := DefinitionSafety.unsafe\n  }\n  ensureNoUnassignedMVars decl\n  dbg_trace m\n  addAndCompile decl\n  return mkIdent name\n\n-- HDO: This elaborates like the normal do command (but with Prod/HBind)\n@[termElab \u00abhdo\u00bb] def elabHDo : TermElab := fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  let bindInfo \u2190 extractBind expectedType?\n  let m \u2190 mkMonadAlias bindInfo.m\n  let codeBlock \u2190 ToCodeBlock.run stx m\n  let stxNew \u2190 liftMacroM <| ToTerm.run codeBlock.code m\n  trace[Elab.do] stxNew\n  withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType\n\n-- HDO: Variation with additional information for testing\n@[termElab \u00abhdo_2\u00bb] def elabHDo2 : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(hdo (monad := $stx_monad:term) $stx_seq) =>\n      let stx \u2190 `(hdo $stx_seq)\n\n      -- We get an expression for the universe polymorphic monad as parameter\n      let monad \u2190 elabTerm stx_monad none\n      dbg_trace \"Monad:\"\n      dbg_trace monad\n      dbg_trace \"Inferred monad type:\"\n      dbg_trace (\u2190 inferType monad)\n\n      tryPostponeIfNoneOrMVar expectedType?\n      let bindInfo \u2190 extractBind expectedType?\n      let m \u2190 mkMonadAlias monad\n      let codeBlock \u2190 ToCodeBlock.run stx m\n      let stxNew \u2190 liftMacroM <| ToTerm.run codeBlock.code m\n      trace[Elab.do] stxNew\n      withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType\n\n  | _ => throwError \"unrecognized syntax for hdo_2\"\n\nend HDo\n\nbuiltin_initialize registerTraceClass `Elab.do\n\nprivate def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do\n  let stx := stx.setKind newKind\n  withRef stx `(do $stx:doElem)\n\n@[builtinMacro Lean.Parser.Term.termFor]\ndef expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor\n\n@[builtinMacro Lean.Parser.Term.termTry]\ndef expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry\n\n@[builtinMacro Lean.Parser.Term.termUnless]\ndef expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless\n\n@[builtinMacro Lean.Parser.Term.termReturn]\ndef expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn\n\nend Lean.Elab.Term\n\n/-\n## Tests\n-/\n\nset_option trace.Elab.do true\n\n-- Elaborating with `hdo` gives us a term absed on `hBind`\ndef test_IO: IO Unit := hdo\n  IO.println \"Lean4\"\n  IO.println \"hBind\"\n  return ()\n#print test_IO\n\ndef get_0: Id Nat :=\n  pure 0\ndef get_1: Id ((\u03b1: Type) \u2192 \u03b1 \u2192 \u03b1) :=\n  pure @id\ndef get_any: Id PUnit.{u+1} :=\n  pure .unit\n\nexample: Id Unit :=\n  HBind.hBind get_0 fun n =>\n  HBind.hBind get_1 fun f => -- Heterogeneous bind succeeds\n  pure ()\n\n-- If we specify the monad as a polymorphic one, elaboration succeeds\n-- We hacked the universe name so we have to define it\nuniverse u in\nexample: Id Unit := hdo (monad := Id.{u})\n  let _ \u2190 get_0\n  let _ \u2190 get_1\n  let _ \u2190 get_any.{2}\n  get_any.{0}\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/Util/HBind.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20434189993684584, "lm_q2_score": 0.028870907468524762, "lm_q1q2_score": 0.005899536085019222}}
{"text": "import data.cpi.species\n\nnamespace cpi\n\nvariables {\u210d : Type} {\u03c9 : context}\n\n/-- A function to look up names within the environment. -/\n@[nolint has_inhabited_instance]\ndef lookup (\u210d : Type) (\u03c9 \u0393 : context) := \u2200 n, reference n \u03c9 \u2192 species.choices \u210d \u03c9 (context.extend n \u0393)\n\n/-- Rename a lookup function, embedding the returned species into another\n    context.-/\ndef lookup.rename {\u0393 \u0394} (\u03c1 : name \u0393 \u2192 name \u0394) : lookup \u210d \u03c9 \u0393 \u2192 lookup \u210d \u03c9 \u0394\n| f n r := species.rename (name.ext \u03c1) (f n r)\n\n/-- Rewrite lemma for when lookups get expanded incorrectly. -/\nlemma lookup.rename.def {\u0393 \u0394} (\u03c1 : name \u0393 \u2192 name \u0394) (\u2113 : lookup \u210d \u03c9 \u0393)\n  : (\u03bb n r, species.rename (name.ext \u03c1) (\u2113 n r)) = lookup.rename \u03c1 \u2113\n  := rfl\n\nlemma lookup.rename.inj {\u0393 \u0394} {\u03c1 : name \u0393 \u2192 name \u0394} (inj : function.injective \u03c1)\n  : function.injective (@lookup.rename \u210d \u03c9 \u0393 \u0394 \u03c1)\n| x y eq := funext $ \u03bb n, funext $ \u03bb r, begin\n  have : species.rename (name.ext \u03c1) (x n r) = species.rename (name.ext \u03c1) (y n r)\n    := congr_fun (congr_fun eq n) r,\n  from species.rename.inj (name.ext.inj inj) this,\nend\n\nlemma lookup.rename_compose {\u0393 \u0394 \u03b7} (\u03c1 : name \u0393 \u2192 name \u0394) (\u03c3 : name \u0394 \u2192 name \u03b7)\n  : \u2200 (\u2113 : lookup \u210d \u03c9 \u0393)\n  , lookup.rename \u03c3 (lookup.rename \u03c1 \u2113) = lookup.rename (\u03c3 \u2218 \u03c1) \u2113\n| f := funext $ \u03bb n, funext $ \u03bb r, begin\n  simp only [lookup.rename, function.comp],\n  rw [species.rename_compose (name.ext \u03c1) (name.ext \u03c3) (f n r), name.ext_comp],\nend\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/transition/lookup.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.017442482278175485, "lm_q1q2_score": 0.00589690424664301}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Daniel Selsam\n-/\nimport Mathport.Util.Misc\n\ndef Lean.BinderInfo.bracket (paren : Bool) : BinderInfo \u2192 Format \u2192 Format\n  | BinderInfo.default,        f => if paren then f.paren else f.group\n  | BinderInfo.implicit,       f => f.bracket \"{\" \"}\"\n  | BinderInfo.strictImplicit, f => f.bracket \"{{\" \"}}\"\n  | BinderInfo.instImplicit,   f => f.sbracket\n\nnamespace Mathport\n\nopen Lean (Position Name BinderInfo)\nopen Std (Format)\n\nnamespace Lean3\n\ninductive Proj\n  | nat : Nat \u2192 Proj\n  | ident : Name \u2192 Proj\n  deriving Inhabited\n\ninstance : Repr Proj where\n  reprPrec\n  | Proj.nat n, _ => repr n\n  | Proj.ident n, _ => n.toString\n\nopen Lean (Level)\n\ninductive Annotation\n  | no_univ\n  | do_failure_eq\n  | infix_fn\n  | begin_hole\n  | end_hole\n  | anonymous_constructor\n  | \u00abcalc\u00bb\n  | no_info\n  | frozen_name\n  | \u00abhave\u00bb\n  | \u00abshow\u00bb\n  | \u00absuffices\u00bb\n  | checkpoint\n  | \u00ab@\u00bb\n  | \u00ab@@\u00bb\n  | as_atomic\n  | as_is\n  | antiquote\n  | expr_quote_pre\n  | comp_irrel\n  | inaccessible\n  | \u00abby\u00bb\n  | pattern_hint\n  | th_proof\n  deriving Repr\n\nstructure EquationsHeader :=\n  (num_fns : Nat) (fn_names fn_actual_names : Array Name)\n  (is_private is_noncomputable is_meta is_lemma gen_code aux_lemmas : Bool)\n  deriving Repr\n\ninstance : Repr Level.Data := \u27e8fun _ _ => \"\u00b7\"\u27e9\nderiving instance Repr for Level\n\nmutual\n\n  inductive Expr where\n    | var : Nat \u2192 Expr\n    | sort : Level \u2192 Expr\n    | const : Name \u2192 Array Level \u2192 Expr\n    | mvar (name pp : Name) (type : Expr)\n    | \u00ablocal\u00bb (name pp : Name) (bi : BinderInfo) (type : Expr)\n    | app : Expr \u2192 Expr \u2192 Expr\n    | lam (name : Name) (bi : BinderInfo) (dom body : Expr)\n    | Pi (name : Name) (bi : BinderInfo) (dom body : Expr)\n    | \u00ablet\u00bb (name : Name) (type value body : Expr)\n    | annotation : Annotation \u2192 Expr \u2192 Expr\n    | field : Expr \u2192 Proj \u2192 Expr\n    | typed_expr (ty val : Expr)\n    | structinst (struct : Name) (catchall : Bool) (fields : Array (Name \u00d7 Expr)) (sources : Array Expr)\n    | prenum (value : Nat)\n    | nat (value : Nat)\n    | quote (value : Expr) (expr : Bool)\n    | choice (args : Array Expr)\n    | string (value : String)\n    | no_equation\n    | equation (lhs rhs : Expr) (ignore_if_unused : Bool)\n    | equations (h : EquationsHeader) (eqns : Array LambdaEquation) (wf : Option Expr)\n    | equations_result (args : Array Expr)\n    | as_pattern (lhs rhs : Expr)\n    | delayed_abstraction : Expr \u2192 Array (Name \u00d7 Expr) \u2192 Expr\n    | \u00absorry\u00bb (synthetic : Bool) (ty : Expr)\n    | rec_fn (name : Name) (ty : Expr)\n    | proj (I constr proj : Name) (idx : Nat) (params : Array Name) (ty val arg : Expr)\n    | ac_app (args : Array Expr) (op : Expr)\n    | perm_ac (assoc comm e1 e2 : Expr)\n    | cc_proof (e1 e2 : Expr)\n    deriving Inhabited, Repr\n\n  inductive LambdaEquation where\n    | no_equation\n    | equation (lhs rhs : Expr) (ignore_if_unused : Bool)\n    | lam (name : Name) (bi : BinderInfo) (dom : Expr) : LambdaEquation \u2192 LambdaEquation\n    deriving Inhabited, Repr\n\nend\n\npartial def Expr.toLambdaEqn : Expr \u2192 Option LambdaEquation\n  | Expr.no_equation => LambdaEquation.no_equation\n  | Expr.equation lhs rhs iu => LambdaEquation.equation lhs rhs iu\n  | Expr.lam n pp bi e => LambdaEquation.lam n pp bi <$> e.toLambdaEqn\n  | _ => none\n\nend Lean3\n\nstructure Meta where\n  id : Nat\n  start : Position\n  end_ : Position\n  deriving Inhabited\n\nstructure Spanned (\u03b1 : Type u) where\n  meta : Option Meta\n  kind : \u03b1\n  deriving Inhabited\n\ninstance [Repr \u03b1] : Repr (Spanned \u03b1) := \u27e8fun n p => reprPrec n.kind p\u27e9\n\ndef Spanned.map (f : \u03b1 \u2192 \u03b2) : Spanned \u03b1 \u2192 Spanned \u03b2\n  | \u27e8m, a\u27e9 => \u27e8m, f a\u27e9\n\ndef Spanned.dummy (a : \u03b1) : Spanned \u03b1 := \u27e8none, a\u27e9\n\nlocal prefix:max \"#\" => Spanned\n\nnamespace AST3\n\nopen Lean3 (Proj)\n\ninductive BinderName\n  | ident : Name \u2192 BinderName\n  | \u00ab_\u00bb : BinderName\n\ninstance : Repr BinderName where\n  reprPrec\n  | BinderName.ident n, _ => n.toString\n  | BinderName.\u00ab_\u00bb, _ => \"_\"\n\ninductive VariableKind | \u00abvariable\u00bb | \u00abparameter\u00bb\n  deriving Inhabited\n\ninstance : Repr VariableKind where\n  reprPrec\n  | VariableKind.\u00abvariable\u00bb, _ => \"variable\"\n  | VariableKind.\u00abparameter\u00bb, _ => \"parameter\"\n\ninductive AxiomKind | \u00abaxiom\u00bb | \u00abconstant\u00bb\n  deriving Inhabited\n\ninstance : Repr AxiomKind where\n  reprPrec\n  | AxiomKind.\u00abaxiom\u00bb, _ => \"axiom\"\n  | AxiomKind.\u00abconstant\u00bb, _ => \"constant\"\n\ninductive DeclKind | \u00abdef\u00bb | \u00abtheorem\u00bb | \u00ababbrev\u00bb | \u00abexample\u00bb | \u00abinstance\u00bb\n  deriving Inhabited\n\ninstance : Repr DeclKind where\n  reprPrec\n  | DeclKind.def, _ => \"def\"\n  | DeclKind.theorem, _ => \"theorem\"\n  | DeclKind.abbrev, _ => \"abbreviation\"\n  | DeclKind.example, _ => \"example\"\n  | DeclKind.instance, _ => \"instance\"\n\ndef LocalReserve := Bool \u00d7 Bool\n\ninstance : Repr LocalReserve := \u27e8fun \u27e8loc, res\u27e9 _ =>\n  ((if loc then \"local \" else \"\") ++ (if res then \"reserve \" else \"\") : String)\u27e9\n\ninductive MixfixKind | \u00abinfix\u00bb | \u00abinfixl\u00bb | \u00abinfixr\u00bb | \u00abpostfix\u00bb | \u00abprefix\u00bb\n  deriving Inhabited, BEq, Hashable\n\ninstance : Repr MixfixKind where\n  reprPrec\n  | MixfixKind.infix, _ => \"infix\"\n  | MixfixKind.infixl, _ => \"infixl\"\n  | MixfixKind.infixr, _ => \"infixr\"\n  | MixfixKind.postfix, _ => \"postfix\"\n  | MixfixKind.prefix, _ => \"prefix\"\n\ninstance : ToString MixfixKind where\n  toString m := toString (repr m)\n\ninductive InferKind | implicit | relaxedImplicit | none\n\ninstance : Inhabited InferKind := \u27e8InferKind.relaxedImplicit\u27e9\n\ninstance : ToString InferKind where\n  toString\n  | InferKind.implicit => \"[]\"\n  | InferKind.relaxedImplicit => \"{}\"\n  | InferKind.none => \"( )\"\n\ninstance : Repr InferKind where\n  reprPrec ik _ := toString ik\n\ndef InferKind.optRepr : Option InferKind \u2192 Format\n  | Option.none => \"\"\n  | some ik => \" \" ++ repr ik\n\ninductive Symbol\n  | quoted : String \u2192 Symbol\n  | ident : String \u2192 Symbol\n  deriving Inhabited\n\ninstance : Repr Symbol where\n  reprPrec\n  | Symbol.quoted s, _ => (\"`\" ++ s ++ \"`\" : String)\n  | Symbol.ident n, _ => n\n\ndef Symbol.trim : Symbol \u2192 String\n  | Symbol.ident s => s\n  | Symbol.quoted s => s.trim\n\ndef Symbol.toString : Symbol \u2192 String\n  | Symbol.ident s => s\n  | Symbol.quoted s => s\n\ninductive Choice\n  | one : Name \u2192 Choice\n  | many : Array Name \u2192 Choice\n  deriving Inhabited\n\ndef Choice.name : Choice \u2192 Name\n  | Choice.one n => n\n  | Choice.many #[n] => n\n  | _ => default\n\ninstance : Repr Choice where\n  reprPrec\n  | Choice.one n, _ => n.toString\n  | Choice.many ns, _ => (Format.joinSep (ns.toList.map (\u00b7.toString)) \"/\").sbracket\n\ninductive OptionVal\n  | bool : Bool \u2192 OptionVal\n  | str : String \u2192 OptionVal\n  | nat : Nat \u2192 OptionVal\n  | decimal : Nat \u2192 Nat \u2192 OptionVal\n\ninstance : Repr OptionVal where\n  reprPrec\n  | OptionVal.bool n, _ => repr n\n  | OptionVal.nat n, _ => repr n\n  | OptionVal.str n, _ => repr n\n  | OptionVal.decimal n d, _ => repr n ++ \"/\" ++ repr d\n\ninductive Level\n  | \u00ab_\u00bb : Level\n  | nat : Nat \u2192 Level\n  | add : #Level \u2192 #Nat \u2192 Level\n  | max : Array #Level \u2192 Level\n  | imax : Array #Level \u2192 Level\n  | param : Name \u2192 Level\n  | paren : #Level \u2192 Level\n  deriving Inhabited\n\ndef Levels := Option (Array #Level)\ndef LevelDecl := Option (Array #Name)\ninstance : Inhabited Levels := \u27e8none\u27e9\ninstance : Inhabited LevelDecl := \u27e8none\u27e9\n\n-- These are used to break up the huge mutual recursion below\nabbrev NotationId := Nat\nabbrev CommandId := Nat\n\nsection\nset_option hygiene false\nlocal notation \"Binders\" => Array #Binder\n\nmutual\n\n  inductive Default\n    | \u00ab:=\u00bb : #Expr \u2192 Default\n    | \u00ab.\u00bb : #Name \u2192 Default\n\n  inductive Binder\n    | \u00abnotation\u00bb : NotationId \u2192 Binder\n    | binder : BinderInfo \u2192 Option (Array #BinderName) \u2192\n      Binders \u2192 Option #Expr \u2192 Option Default \u2192 Binder\n    | collection : BinderInfo \u2192 Array #BinderName \u2192\n      (nota : Name) \u2192 (rhs : #Expr) \u2192 Binder\n    deriving Inhabited\n\n  inductive LambdaBinder\n    | reg : Binder \u2192 LambdaBinder\n    | \u00ab\u27e8\u27e9\u00bb : Array #Expr \u2192 LambdaBinder\n    deriving Inhabited\n\n  inductive LetDecl\n    | \u00abnotation\u00bb : NotationId \u2192 LetDecl\n    | var : #BinderName \u2192 Binders \u2192 Option #Expr \u2192 #Expr \u2192 LetDecl\n    | pat : #Expr \u2192 #Expr \u2192 LetDecl\n    deriving Inhabited\n\n  inductive Arg\n    | expr : Expr \u2192 Arg\n    | exprs : Array #Expr \u2192 Arg\n    | binder : Binder \u2192 Arg\n    | binders : Binders \u2192 Arg\n    deriving Inhabited\n\n  inductive Expr\n    | \u00ab...\u00bb : Expr\n    | \u00absorry\u00bb : Expr\n    | \u00ab_\u00bb : Expr\n    | \u00ab()\u00bb : Expr\n    | \u00ab{}\u00bb : Expr\n    | ident : Name \u2192 Expr\n    | const : #Name \u2192 Levels \u2192 Array Name \u2192 Expr\n    | nat : Nat \u2192 Expr\n    | decimal : Nat \u2192 Nat \u2192 Expr\n    | string : String \u2192 Expr\n    | char : Char \u2192 Expr\n    | paren : #Expr \u2192 Expr\n    | sort (isType isStar : Bool) : Option #Level \u2192 Expr\n    | app : #Expr \u2192 #Expr \u2192 Expr\n    | \u00abfun\u00bb (isAssume : Bool) : Array #LambdaBinder \u2192 #Expr \u2192 Expr\n    | \u00ab\u2192\u00bb : #Expr \u2192 #Expr \u2192 Expr\n    | Pi : Binders \u2192 #Expr \u2192 Expr\n    | \u00abshow\u00bb : #Expr \u2192 #Proof \u2192 Expr\n    | \u00abhave\u00bb (suff : Bool) : Option #Name \u2192 #Expr \u2192 #Proof \u2192 #Expr \u2192 Expr\n    | \u00ab.\u00bb (compact : Bool) : #Expr \u2192 #Proj \u2192 Expr\n    | \u00abif\u00bb : Option #Name \u2192 #Expr \u2192 #Expr \u2192 #Expr \u2192 Expr\n    | \u00abcalc\u00bb : Array (#Expr \u00d7 #Expr) \u2192 Expr\n    | \u00ab@\u00bb (\u00abpartial\u00bb : Bool) : #Expr \u2192 Expr\n    | pattern : #Expr \u2192 Expr\n    | \u00ab`()\u00bb (lazy expr : Bool) : #Expr \u2192 Expr\n    | \u00ab%%\u00bb : #Expr \u2192 Expr\n    | \u00ab`[]\u00bb : Array #Tactic \u2192 Expr\n    | \u00ab`\u00bb (resolve : Bool) : Name \u2192 Expr\n    | \u00ab\u27e8\u27e9\u00bb : Array #Expr \u2192 Expr\n    | infix_fn : Choice \u2192 Option #Expr \u2192 Expr\n    | \u00ab(,)\u00bb : Array #Expr \u2192 Expr\n    | \u00ab:\u00bb : #Expr \u2192 #Expr \u2192 Expr\n    | hole : Array #Expr \u2192 Expr\n    | \u00ab#[]\u00bb : Array #Expr \u2192 Expr\n    | \u00abby\u00bb : #Tactic \u2192 Expr\n    | begin : Block \u2192 Expr\n    | \u00ablet\u00bb : Array #LetDecl \u2192 #Expr \u2192 Expr\n    | \u00abmatch\u00bb : Array #Expr \u2192 Option #Expr \u2192 Array Arm \u2192 Expr\n    | \u00abdo\u00bb (braces : Bool) : Array #DoElem \u2192 Expr\n    | \u00ab{,}\u00bb : Array #Expr \u2192 Expr\n    | subtype (setOf : Bool) : #Name \u2192 Option #Expr \u2192 #Expr \u2192 Expr\n    | sep : #Name \u2192 #Expr \u2192 #Expr \u2192 Expr\n    | setReplacement : #Expr \u2192 Binders \u2192 Expr\n    | structInst (ty : Option #Name) (src : Option #Expr)\n      (fields : Array (#Name \u00d7 #Expr)) (srcs : Array #Expr) (catchall : Bool) : Expr\n    | atPat : #Name \u2192 #Expr \u2192 Expr\n    | \u00ab.()\u00bb : #Expr \u2192 Expr\n    | \u00abnotation\u00bb (n : Choice) : Array #Arg \u2192 Expr\n    | userNotation (n : Name) : Array #Param \u2192 Expr\n    deriving Inhabited\n\n  inductive Arm\n    | mk (lhs : Array #Expr) (rhs : #Expr) : Arm\n    deriving Inhabited\n\n  inductive DoElem\n    | \u00ablet\u00bb : #LetDecl \u2192 DoElem\n    | \u00ab\u2190\u00bb : #Expr \u2192 Option #Expr \u2192 #Expr \u2192 Option #Expr \u2192 DoElem\n    | eval : #Expr \u2192 DoElem\n    deriving Inhabited\n\n  inductive Proof\n    | \u00abfrom\u00bb (\u00ab:=\u00bb : Bool) : #Expr \u2192 Proof\n    | block : Block \u2192 Proof\n    | \u00abby\u00bb : #Tactic \u2192 Proof\n    deriving Inhabited\n\n  inductive Tactic\n    | \u00ab;\u00bb : Array #Tactic \u2192 Tactic\n    | \u00ab<|>\u00bb : Array #Tactic \u2192 Tactic\n    | \u00ab[]\u00bb : Array #Tactic \u2192 Tactic\n    | block : Block \u2192 Tactic\n    | \u00abby\u00bb : #Tactic \u2192 Tactic\n    | exact_shortcut : #Expr \u2192 Tactic\n    | expr : #Expr \u2192 Tactic\n    | interactive (n : Name) : Array #Param \u2192 Tactic\n    deriving Inhabited\n\n  inductive Block\n    | mk (curly : Bool) (tacClass : Option #Name)\n        (cfg : Option #Expr) (tacs : Array #Tactic) : Block\n    deriving Inhabited\n\n  inductive Param\n    | parse : Lean3.Expr \u2192 Array #VMCall \u2192 Param\n    | expr : #Expr \u2192 Param\n    | block : Block \u2192 Param\n    deriving Inhabited\n\n  inductive VMCall\n    | ident : Name \u2192 VMCall\n    | nat : Nat \u2192 VMCall\n    | token : String \u2192 VMCall\n    | pat : Expr \u2192 VMCall\n    | expr : Expr \u2192 VMCall\n    | binders : Binders \u2192 VMCall\n    | block : Block \u2192 VMCall\n    | \u00abinductive\u00bb : CommandId \u2192 VMCall\n    | command : Option CommandId \u2192 VMCall\n    | withInput : Array #VMCall \u2192 (bytesParsed : Nat) \u2192 VMCall\n    deriving Inhabited\n\nend\nend\n\ndef Binders := Array #Binder\ninstance : Inhabited Binders := \u27e8#[]\u27e9\n\npartial def Expr.unparen : Expr \u2192 Expr\n  | Expr.paren e => e.kind.unparen\n  | e => e\n\ninductive AttrArg\n  | eager : AttrArg\n  | indices : Array #Nat \u2192 AttrArg\n  | keyValue : #String \u2192 #String \u2192 AttrArg\n  | vmOverride : #Name \u2192 Option #Name \u2192 AttrArg\n  | user : Lean3.Expr \u2192 Array #VMCall \u2192 AttrArg\n  deriving Inhabited\n\ninductive Attribute\n  | priority : #Expr \u2192 Attribute\n  | del (name : Name) : Attribute\n  | add (name : Name) (arg : Option #AttrArg) : Attribute\n  deriving Inhabited\n\ndef Attributes := Array #Attribute\ninstance : Inhabited Attributes := \u27e8#[]\u27e9\n\ninductive Precedence\n  | nat : Nat \u2192 Precedence\n  | expr : #Expr \u2192 Precedence\n  deriving Inhabited\n\ndef PrecSymbol := #Symbol \u00d7 Option #Precedence\ninstance : Inhabited PrecSymbol := inferInstanceAs (Inhabited (_\u00d7_))\n\ninductive Action\n  | prec : Precedence \u2192 Action\n  | prev : Action\n  | \u00abscoped\u00bb : Option #Precedence \u2192 Option (#Name \u00d7 #Expr) \u2192 Action\n  | fold (right : Bool)\n      (prec : Option #Precedence) (sep : PrecSymbol)\n      (\u00abrec\u00bb : #Name \u00d7 #Name \u00d7 #Expr) (ini : Option #Expr)\n      (term : Option PrecSymbol) : Action\n  deriving Inhabited\n\ninductive Literal\n  | nat : Nat \u2192 Literal\n  | var : #Name \u2192 Option #Action \u2192 Literal\n  | sym : PrecSymbol \u2192 Literal\n  | binder : Option #Precedence \u2192 Literal\n  | binders : Option #Precedence \u2192 Literal\n  deriving Inhabited\n\ninductive Notation\n  | \u00abnotation\u00bb : Option #Name \u2192 Array #Literal \u2192 Option #Expr \u2192 Notation\n  | mixfix : MixfixKind \u2192 Option #Name \u2192 PrecSymbol \u2192 Option #Expr \u2192 Notation\n  deriving Inhabited\n\ninductive Modifier\n  | \u00abprivate\u00bb : Modifier\n  | \u00abprotected\u00bb : Modifier\n  | \u00abnoncomputable\u00bb : Modifier\n  | meta : Modifier\n  | \u00abmutual\u00bb : Modifier\n  | doc : String \u2192 Modifier\n  | attr (\u00ablocal\u00bb compact : Bool) : Attributes \u2192 Modifier\n  deriving Inhabited\n\ndef Modifiers := Array #Modifier\ninstance : Inhabited Modifiers := \u27e8#[]\u27e9\n\ninductive DeclVal\n  | expr : Expr \u2192 DeclVal\n  | eqns : Array Arm \u2192 DeclVal\n  deriving Inhabited\n\nstructure Mutual (\u03b1 : Type) := (attrs : Attributes) (name : #Name) (ty : #Expr) (vals : Array \u03b1)\n  deriving Inhabited\n\nstructure MutualHeader (\u03b1 : Type) where\n  (mods : Modifiers) (lvls : LevelDecl) (bis : Binders) (vals : Array (Mutual \u03b1))\n  deriving Inhabited\n\nstructure Intro where\n  (doc : Option String) (name : #Name) (ik : Option InferKind) (bis : Binders) (ty : Option #Expr)\n\nstructure Rename := (\u00abfrom\u00bb to : #Name)\n\nstructure Parent where\n  (\u00abprivate\u00bb : Bool) (name : Option #Name) (expr : #Expr) (renames : Array Rename)\n\nstructure Mk := (name : #Name) (ik : Option InferKind)\n\ninductive Field\n  | binder : BinderInfo \u2192 Array #Name \u2192 Option InferKind \u2192\n    Binders \u2192 Option #Expr \u2192 Option Default \u2192 Field\n  | \u00abnotation\u00bb : Notation \u2192 Field\n\ninductive OpenClause\n  | explicit : Array #Name \u2192 OpenClause\n  | \u00abrenaming\u00bb : Array Rename \u2192 OpenClause\n  | \u00abhiding\u00bb : Array #Name \u2192 OpenClause\n\nstructure Open :=\n  (tgt : #Name) (as : Option #Name) (clauses : Array #OpenClause)\n\ninductive HelpCmd\n  | options : HelpCmd\n  | commands : HelpCmd\n\ninductive PrintAttrCmd\n  | recursor : PrintAttrCmd\n  | unify : PrintAttrCmd\n  | simp : PrintAttrCmd\n  | congr : PrintAttrCmd\n  | attr : Name \u2192 PrintAttrCmd\n\ndef PrintAttrCmd.toName : PrintAttrCmd \u2192 Name\n  | recursor => `recursor\n  | unify => `unify\n  | simp => `simp\n  | congr => `congr\n  | attr n => n\n\ninductive PrintCmd\n  | str : String \u2192 PrintCmd\n  | raw : #Expr \u2192 PrintCmd\n  | options : PrintCmd\n  | trust : PrintCmd\n  | keyEquivalences : PrintCmd\n  | \u00abdef\u00bb : #Name \u2192 PrintCmd\n  | instances : #Name \u2192 PrintCmd\n  | classes : PrintCmd\n  | attributes : PrintCmd\n  | \u00abprefix\u00bb : #Name \u2192 PrintCmd\n  | aliases : PrintCmd\n  | \u00abaxioms\u00bb : Option #Name \u2192 PrintCmd\n  | fields : #Name \u2192 PrintCmd\n  | \u00abnotation\u00bb : Array #Name \u2192 PrintCmd\n  | \u00abinductive\u00bb : #Name \u2192 PrintCmd\n  | attr : #PrintAttrCmd \u2192 PrintCmd\n  | token : #Name \u2192 PrintCmd\n  | ident : #Name \u2192 PrintCmd\n\ninductive InductiveCmd\n  | reg (\u00abclass\u00bb : Bool) : Modifiers \u2192 #Name \u2192 LevelDecl \u2192 Binders \u2192\n    (ty : Option #Expr) \u2192 Option Notation \u2192 Array #Intro \u2192 InductiveCmd\n  | \u00abmutual\u00bb (\u00abclass\u00bb : Bool) : Modifiers \u2192 LevelDecl \u2192 Binders \u2192\n    Option Notation \u2192 Array (Mutual #Intro) \u2192 InductiveCmd\n\ninductive Command\n  | initQuotient : Command\n  | mdoc : String \u2192 Command\n  | \u00abuniverse\u00bb (var plural : Bool) : Array #Name \u2192 Command\n  | \u00abnamespace\u00bb : #Name \u2192 Command\n  | \u00absection\u00bb : Option #Name \u2192 Command\n  | \u00abend\u00bb : Option #Name \u2192 Command\n  | \u00abvariable\u00bb : VariableKind \u2192 (plural : Bool) \u2192 Modifiers \u2192 Binders \u2192 Command\n  | \u00abaxiom\u00bb : AxiomKind \u2192 Modifiers \u2192 #Name \u2192 LevelDecl \u2192 Binders \u2192 #Expr \u2192 Command\n  | \u00abaxioms\u00bb : AxiomKind \u2192 Modifiers \u2192 Binders \u2192 Command\n  | decl : DeclKind \u2192 Modifiers \u2192 Option #Name \u2192\n    LevelDecl \u2192 Binders \u2192 (ty : Option #Expr) \u2192 #DeclVal \u2192 (uwf : Option #Expr) \u2192 Command\n  | mutualDecl : DeclKind \u2192 Modifiers \u2192 LevelDecl \u2192 Binders \u2192 Array (Mutual Arm) \u2192\n    (uwf : Option #Expr) \u2192 Command\n  | \u00abinductive\u00bb : InductiveCmd \u2192 Command\n  | \u00abstructure\u00bb (\u00abclass\u00bb : Bool) :\n    Modifiers \u2192 #Name \u2192 LevelDecl \u2192 Binders \u2192 Array #Parent \u2192 (ty : Option #Expr) \u2192\n    Option #Mk \u2192 Array #Field \u2192 Command\n  | \u00abattribute\u00bb (\u00ablocal\u00bb : Bool) : Modifiers \u2192 Attributes \u2192 Array #Name \u2192 Command\n  | \u00abprecedence\u00bb : #Symbol \u2192 #Precedence \u2192 Command\n  | \u00abnotation\u00bb : LocalReserve \u2192 Attributes \u2192 Notation \u2192 Command\n  | \u00abopen\u00bb (\u00abexport\u00bb : Bool) : Array Open \u2192 Command\n  | \u00abinclude\u00bb (pos : Bool) : Array #Name \u2192 Command\n  | \u00abhide\u00bb : Array #Name \u2192 Command\n  | \u00abtheory\u00bb : Modifiers \u2192 Command\n  | setOption : #Name \u2192 #OptionVal \u2192 Command\n  | declareTrace : #Name \u2192 Command\n  | addKeyEquivalence : #Name \u2192 #Name \u2192 Command\n  | runCmd : #Expr \u2192 Command\n  | check : #Expr \u2192 Command\n  | reduce (whnf : Bool) : #Expr \u2192 Command\n  | eval : #Expr \u2192 Command\n  | unify : #Expr \u2192 #Expr \u2192 Command\n  | compile : #Name \u2192 Command\n  | help : HelpCmd \u2192 Command\n  | print : PrintCmd \u2192 Command\n  | userCommand (n : Name) : Modifiers \u2192 Array #Param \u2192 Command\n  deriving Inhabited\n\ndef spaced (f : \u03b1 \u2192 Format) (mods : Array \u03b1) : Format :=\n  (Format.joinSep (mods.toList.map f) Format.line).fill\n\ndef spacedBefore (f : \u03b1 \u2192 Format) (mods : Array \u03b1) : Format :=\n  (Format.join (mods.toList.map fun m => Format.line ++ f m)).fill\n\ndef spacedAfter (f : \u03b1 \u2192 Format) (mods : Array \u03b1) : Format :=\n  (Format.join (mods.toList.map fun m => f m ++ Format.line)).fill\n\ndef suffix (pl : Bool) := if pl then \"s \" else \" \"\n\npartial def Level_repr : Level \u2192 (prec : _ := 0) \u2192 Format\n  | Level.\u00ab_\u00bb, _ => \"_\"\n  | Level.nat n, _ => repr n\n  | Level.add l n, p => Format.parenPrec 10 p $\n    Level_repr l.kind 10 ++ \"+\" ++ repr n\n  | Level.imax ls, p => Format.parenPrec max_prec p $\n    \"imax\" ++ Format.join (ls.toList.map fun l => \" \" ++ Level_repr l.kind max_prec)\n  | Level.max ls, p => Format.parenPrec max_prec p $\n    \"max\" ++ Format.join (ls.toList.map fun l => \" \" ++ Level_repr l.kind max_prec)\n  | Level.param u, _ => u.toString\n  | Level.paren l, _ => Level_repr l.kind\n\ninstance : Repr Level := \u27e8@Level_repr\u27e9\n\ninstance : Repr Levels where\n  reprPrec\n  | none, _ => \"\"\n  | some us, _ => (Format.joinSep (us.toList.map repr) \", \").bracket \".{\" \"}\"\n\ninstance : Repr LevelDecl where\n  reprPrec\n  | none, _ => \"\"\n  | some us, _ => (Format.joinSep (us.toList.map fun u => u.kind.toString) \", \").bracket \".{\" \"}\"\n\nmutual\n\n  partial def Precedence_repr : Precedence \u2192 Format\n    | Precedence.nat n => repr n\n    | Precedence.expr e => Expr_repr e.kind max_prec\n\n  partial def optTy : Option #Expr \u2192 Format\n    | none => \"\"\n    | some e => \" :\" ++ Format.line ++ Expr_repr e.kind\n\n  partial def Default_repr : Option Default \u2192 Format\n    | none => \"\"\n    | some (Default.\u00ab:=\u00bb e) => \" :=\" ++ Format.line ++ Expr_repr e.kind\n    | some (Default.\u00ab.\u00bb n) => \" .\" ++ Format.line ++ (n.kind.toString : Format)\n\n  partial def Binder_repr : Binder \u2192 (paren :_:= true) \u2192 Format\n    | Binder.binder bi none _ e dflt, paren => bi.bracket paren $\n      (match e with | none => \"\u2b1d\" | some e => Expr_repr e.kind) ++\n      Default_repr dflt\n    | Binder.binder bi (some vars) bis ty dflt, paren => bi.bracket paren $\n      spaced repr vars ++ Binders_repr bis ++ optTy ty ++ Default_repr dflt\n    | Binder.collection bi vars n rhs, paren => bi.bracket paren $\n      spaced repr vars ++ \" \" ++ n.toString ++ \" \" ++ Expr_repr rhs.kind\n    | Binder.notation n, _ => Format.paren s!\"notation <{show Nat from n}>\"\n\n  partial def Binders_repr (bis : Binders) (paren := true) : Format :=\n    let paren := paren || bis.size \u2260 1\n    spacedBefore (fun m => Binder_repr m.kind paren) bis\n\n  partial def LambdaBinder_repr : LambdaBinder \u2192 (paren :_:= true) \u2192 Format\n    | LambdaBinder.reg bi, paren => Binder_repr bi paren\n    | LambdaBinder.\u00ab\u27e8\u27e9\u00bb args, _ =>\n      (Format.joinSep (args.toList.map fun e => Expr_repr e.kind) \", \").bracket \"\u27e8\" \"\u27e9\"\n\n  partial def LambdaBinders_repr (bis : Array #LambdaBinder) (paren := true) : Format :=\n    let paren := paren || bis.size \u2260 1\n    spacedBefore (fun m => LambdaBinder_repr m.kind paren) bis\n\n  partial def LetDecl_repr : LetDecl \u2192 Format\n    | LetDecl.var v bis ty val =>\n      repr v ++ Binders_repr bis ++ optTy ty ++ \" := \" ++ Expr_repr val.kind\n    | LetDecl.pat pat val => Expr_repr pat.kind ++ \" := \" ++ Expr_repr val.kind\n    | LetDecl.notation n => s!\"notation <{show Nat from n}>\"\n\n  partial def Expr_repr : Expr \u2192 (prec : _ := 0) \u2192 Format\n    | Expr.\u00ab...\u00bb, _ => \"...\"\n    | Expr.sorry, _ => \"sorry\"\n    | Expr.\u00ab_\u00bb, _ => \"_\"\n    | Expr.\u00ab()\u00bb, _ => \"()\"\n    | Expr.\u00ab{}\u00bb, _ => \"{}\"\n    | Expr.ident n, _ => n.toString\n    | Expr.const n l cs, _ => n.kind.toString ++ cs.toList.toString ++ repr l\n    | Expr.nat n, _ => repr n\n    | Expr.decimal n d, _ => repr n ++ \"/\" ++ repr d\n    | Expr.string s, _ => repr s\n    | Expr.char c, _ => repr c\n    | Expr.paren e, p => Expr_repr e.kind p\n    | Expr.sort ty st u, p => Format.parenPrec max_prec p $\n      (if ty then \"Type\" else \"Sort\") ++\n      if st then (\"*\" : Format) else match u with | none => \"\" | some u => \" \" ++ Level_repr u.kind max_prec\n    | Expr.\u00ab\u2192\u00bb lhs rhs, p => Format.parenPrec 25 p $\n      Expr_repr lhs.kind 25 ++ \" \u2192 \" ++ Expr_repr rhs.kind 24\n    | Expr.fun as bis e, p => Format.parenPrec max_prec p $\n      ((if as then \"assume\" else \"\u03bb\" : Format) ++\n      (match as, bis with\n        | true, #[\u27e8_, .reg (.binder _ none _ (some ty) _)\u27e9] => \": \" ++ Expr_repr ty.kind\n        | _, _ => LambdaBinders_repr bis false) ++\n      \",\").group ++ Format.line ++ Expr_repr e.kind\n    | Expr.Pi bis e, p => Format.parenPrec max_prec p $ (\"\u2200\" ++\n      Binders_repr bis false ++ \",\").group ++ Format.line ++ Expr_repr e.kind\n    | Expr.app f x, p => Format.parenPrec max_prec p $\n      (Expr_repr f.kind 1023 ++ Format.line ++ Expr_repr x.kind max_prec).fill\n    | Expr.show t pr, p => Format.parenPrec 1000 p $\n      \"show \" ++ Expr_repr t.kind ++ Proof_repr' pr.kind\n    | Expr.have suff h t pr e, p => Format.parenPrec 1000 p $\n      (if suff then \"suffices \" else \"have \") ++\n      (match h with | none => \"\" | some h => h.kind.toString ++ \" : \") ++\n      Expr_repr t.kind ++ Proof_repr' pr.kind ++\n      \",\" ++ Format.line ++ Expr_repr e.kind\n    | Expr.\u00ab.\u00bb compact e pr, _ =>\n      Expr_repr e.kind max_prec ++ (if compact then \".\" else \"^.\") ++ repr pr.kind\n    | Expr.if h c t e, p => Format.parenPrec 1000 p $ \"if \" ++\n      (match h with | none => \"\" | some h => h.kind.toString ++ \" : \") ++\n      Expr_repr c.kind ++ \" then \" ++ Expr_repr t.kind ++ \" else \" ++ Expr_repr e.kind\n    | Expr.calc args, p => Format.parenPrec 1000 p $ \"calc\" ++\n      (Format.join $ args.toList.map fun (lhs, rhs) =>\n        Format.line ++ Expr_repr lhs.kind ++ \" : \" ++ Expr_repr rhs.kind).nest 2\n    | Expr.\u00ab@\u00bb part e, _ => (if part then \"@@\" else \"@\") ++ Expr_repr e.kind max_prec\n    | Expr.pattern e, p => Format.parenPrec 1000 p $ \"(: \" ++ Expr_repr e.kind ++ \" :)\"\n    | Expr.\u00ab`()\u00bb lazy expr e, p => Format.parenPrec 1000 p $\n      (if expr then \"`(\" else if lazy then \"```(\" else \"``(\") ++\n      (match e.kind with\n      | Expr.\u00ab:\u00bb e ty => Expr_repr e.kind ++ \" : \" ++ Expr_repr ty.kind\n      | _ => Expr_repr e.kind : Format) ++ \")\"\n    | Expr.\u00ab%%\u00bb e, p => Format.parenPrec 1000 p $ \"%%\" ++ Expr_repr e.kind\n    | Expr.\u00ab`[]\u00bb tacs, p => Format.parenPrec 1000 p $\n      (Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) \", \").bracket \"`[\" \"]\"\n    | Expr.\u00ab`\u00bb res n, p => Format.parenPrec 1000 p $\n      (if res then \"``\" else \"`\" : Format) ++ n.toString\n    | Expr.\u00ab\u27e8\u27e9\u00bb es, _ =>\n      (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) \", \").bracket \"\u27e8\" \"\u27e9\"\n    | Expr.infix_fn c e, p => Format.parenPrec 1000 p $\n      \"(\" ++ repr c ++ (match e with | none => \"\" | some e => \" \" ++ Expr_repr e.kind) ++ \")\"\n    | Expr.\u00ab(,)\u00bb es, _ =>\n      (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) \", \").paren\n    | Expr.\u00ab.()\u00bb e, _ => \".\" ++ Expr_repr e.kind max_prec\n    | Expr.\u00ab:\u00bb e ty, _ => \"(\" ++ Expr_repr e.kind ++ \" : \" ++ Expr_repr ty.kind ++ \")\"\n    | Expr.hole es, p => Format.parenPrec 1000 p $\n      (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) \", \").bracket \"{! \" \" !}\"\n    | Expr.\u00ab#[]\u00bb es, p => Format.parenPrec 1000 p $\n      (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) \", \").bracket \"#[\" \"]\"\n    | Expr.by tac, p => Format.parenPrec 1000 p $ \"by \" ++ Tactic_repr tac.kind\n    | Expr.begin tacs, p => Format.parenPrec 1000 p $ Block_repr tacs\n    | Expr.let bis e, p => Format.parenPrec 1000 p $\n      (\"let \" ++ ((\",\" ++ Format.line).joinSep\n        (bis.toList.map fun bi => LetDecl_repr bi.kind)).nest 4 ++ \" in\").group ++\n      Format.line ++ Expr_repr e.kind\n    | Expr.match xs ty eqns, _ => \"match \" ++\n      Format.joinSep (xs.toList.map fun x => Expr_repr x.kind) \", \" ++ optTy ty ++ \" with\" ++\n      (if eqns.isEmpty then \" end\" else Arms_repr eqns ++ Format.line ++ \"end\" : Format)\n    | Expr.do braces els, p => Format.parenPrec 1000 p $\n      let s := Format.line ++ ((\",\" ++ Format.line).joinSep\n        (els.toList.map fun el => DoElem_repr el.kind)).nest 2\n      if braces then \"do\" ++ s else \"do {\" ++ s ++ \" }\"\n    | Expr.\u00ab{,}\u00bb es, _ => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) \", \").bracket \"{\" \"}\"\n    | Expr.subtype setOf x ty p, _ =>\n      \"{\" ++ x.kind.toString ++ optTy ty ++\n      (if setOf then \" | \" else \" // \") ++ Expr_repr p.kind ++ \"}\"\n    | Expr.sep x ty p, _ =>\n      \"{\" ++ x.kind.toString ++ \" \u2208 \" ++ Expr_repr ty.kind ++ \" | \" ++ Expr_repr p.kind ++ \"}\"\n    | Expr.setReplacement e bis, _ =>\n      \"{(\" ++ Expr_repr e.kind ++ \") |\" ++ Binders_repr bis false ++ \"}\"\n    | Expr.structInst S src flds srcs catchall, _ => Format.nest 2 $ Format.group $ \"{ \" ++\n      (match S with | none => \"\" | some S => S.kind.toString ++ \" .\" ++ Format.line : Format) ++\n      (match src with | none => \"\" | some s => Expr_repr s.kind ++ \" with\" ++ Format.line : Format) ++\n      ((\",\" ++ Format.line).joinSep $\n        flds.toList.map (fun (i, s) => i.kind.toString ++ \" := \" ++ Expr_repr s.kind) ++\n        srcs.toList.map (fun s => \"..\" ++ Expr_repr s.kind) ++\n        if catchall then [(\"..\" : Format)] else []) ++ \" }\"\n    | Expr.atPat lhs rhs, p => Format.parenPrec 1000 p $\n      lhs.kind.toString ++ \"@\" ++ Expr_repr rhs.kind max_prec\n    | Expr.notation n args, _ => repr n ++\n      (Format.joinSep (args.toList.map fun e => Arg_repr e.kind) (\",\" ++ Format.line)).paren\n    | Expr.userNotation n args, p => Format.parenPrec 1000 p $ n.toString ++\n      Format.join (args.toList.map fun a => \" \" ++ Param_repr a.kind)\n\n  partial def Arg_repr : Arg \u2192 Format\n    | Arg.expr e => Expr_repr e\n    | Arg.exprs es => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) \", \").sbracket\n    | Arg.binder bi => Binder_repr bi\n    | Arg.binders bis => spaced (fun m => Binder_repr m.kind) bis\n\n  partial def Arm_repr : Arm \u2192 Format\n    | \u27e8lhs, rhs\u27e9 =>\n      \"\\n| \" ++ Format.joinSep (lhs.toList.map fun e => Expr_repr e.kind) \", \" ++\n      \" := \" ++ Expr_repr rhs.kind\n\n  partial def DoElem_repr : DoElem \u2192 Format\n    | DoElem.let bi => \"let \" ++ LetDecl_repr bi.kind\n    | DoElem.\u00ab\u2190\u00bb lhs ty rhs els =>\n      Expr_repr lhs.kind ++ optTy ty ++ \" \u2190 \" ++ Expr_repr rhs.kind ++\n      match els with | none => \"\" | some e => \" | \" ++ Expr_repr e.kind\n    | DoElem.eval e => Expr_repr e.kind\n\n  partial def Arms_repr (arms : Array Arm) : Format :=\n    if arms.isEmpty then \".\" else Format.join $ arms.toList.map Arm_repr\n\n  partial def Proof_repr' : Proof \u2192 Format\n    | Proof.from true e => \" := \" ++ Expr_repr e.kind\n    | p => \", \" ++ Proof_repr p\n\n  partial def Proof_repr : Proof \u2192 Format\n    | Proof.from _ e => \"from \" ++ Expr_repr e.kind\n    | Proof.block tacs => Block_repr tacs\n    | Proof.by tac => \"by \" ++ Tactic_repr tac.kind\n\n  partial def Tactic_repr : Tactic \u2192 Format\n    | Tactic.\u00ab;\u00bb tacs =>\n      Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) \"; \"\n    | Tactic.\u00ab<|>\u00bb tacs =>\n      Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) \" <|> \"\n    | Tactic.\u00ab[]\u00bb tacs =>\n      (Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) \", \").sbracket\n    | Tactic.block tacs => Block_repr tacs\n    | Tactic.by tac => \"by \" ++ Tactic_repr tac.kind\n    | Tactic.exact_shortcut e => Expr_repr e.kind\n    | Tactic.expr tac => Expr_repr tac.kind\n    | Tactic.interactive n args => n.toString ++\n      Format.join (args.toList.map fun a => \" \" ++ Param_repr a.kind)\n\n  partial def Block_repr : Block \u2192 Format\n    | \u27e8curly, cl, cfg, tacs\u27e9 =>\n      let s\u2081 := match cl with | none => \"\" | some cl => \" [\" ++ cl.kind.toString ++ \"]\"\n      let s\u2082 : Format := match cfg with | none => \"\" | some e => \" with \" ++ Expr_repr e.kind ++ \",\"\n      let s\u2083 := (\",\" ++ Format.line).joinSep (tacs.toList.map fun t => Tactic_repr t.kind)\n      if curly then\n        (\"{\" ++ s\u2081 ++ s\u2082 ++ (if cl.isSome || cfg.isSome then Format.line else \" \") ++ s\u2083 ++ \" }\").nest 2\n      else\n        (\"begin\" ++ s\u2081 ++ s\u2082 ++ Format.line ++ s\u2083).nest 2 ++ Format.line ++ \"end\"\n\n  partial def Param_repr : Param \u2192 Format\n    | Param.parse _ calls => Format.sbracket $\n      (\", \":Format).joinSep $ calls.toList.map fun c => VMCall_repr c.kind\n    | Param.expr e => Expr_repr e.kind\n    | Param.block e => Block_repr e\n\n  partial def VMCall_repr : VMCall \u2192 Format\n    | VMCall.ident n => \"ident \" ++ (n.toString:Format)\n    | VMCall.nat n => repr n\n    | VMCall.token tk => repr tk\n    | VMCall.pat e => \"pat \" ++ Expr_repr e\n    | VMCall.expr e => \"expr \" ++ Expr_repr e\n    | VMCall.binders bis => \"binders\" ++ Binders_repr bis\n    | VMCall.block bl => Block_repr bl\n    | VMCall.inductive c => s!\"inductive <{show Nat from c}>\"\n    | VMCall.command c => s!\"command <{repr $ show Option Nat from c}>\"\n    | VMCall.withInput calls _ => Format.sbracket $\n      (\", \":Format).joinSep $ calls.toList.map fun c => VMCall_repr c.kind\n\n  partial def optPrec_repr : Option #Precedence \u2192 Format\n    | none => \"\"\n    | some p => \":\" ++ Precedence_repr p.kind\n\n  partial def PrecSymbol_repr : PrecSymbol \u2192 Format\n    | (sym, prec) => repr sym ++ optPrec_repr prec\n\n  partial def Action_repr : Action \u2192 Format\n    | Action.prec p => Precedence_repr p\n    | Action.prev => \"prev\"\n    | Action.scoped p none => \"scoped\" ++ optPrec_repr p\n    | Action.scoped p (some (x, e)) =>\n      \"(scoped\" ++ optPrec_repr p ++ \" \" ++ x.kind.toString ++ \", \" ++ Expr_repr e.kind ++ \")\"\n    | Action.fold r p sep (x, y, \u00abrec\u00bb) ini term =>\n      \"(fold\" ++ (if r then \"r\" else \"l\") ++ optPrec_repr p ++ \" \" ++\n      PrecSymbol_repr sep ++\n      \" (\" ++ x.kind.toString ++ \" \" ++ y.kind.toString ++ \", \" ++ Expr_repr rec.kind ++ \")\" ++\n      (match ini with | none => \"\" | some ini => \" \" ++ Expr_repr ini.kind) ++\n      (match term with | none => \"\" | some term => \" \" ++ PrecSymbol_repr term) ++ \")\"\n\n  partial def Literal_repr : Literal \u2192 Format\n    | Literal.nat n => repr n\n    | Literal.sym sym => PrecSymbol_repr sym\n    | Literal.binder prec => \"binder\" ++ optPrec_repr prec\n    | Literal.binders prec => \"binders\" ++ optPrec_repr prec\n    | Literal.var v a => (v.kind.toString : Format) ++\n      match a with | none => \"\" | some a => \":\" ++ Action_repr a.kind\n\nend\n\ninstance : Repr Precedence := \u27e8fun n _ => Precedence_repr n\u27e9\ninstance : Repr Binder := \u27e8fun n _ => Binder_repr n\u27e9\ninstance : Repr Binders := \u27e8fun n _ => Binders_repr n\u27e9\ninstance : Repr Expr := \u27e8fun n _ => Expr_repr n\u27e9\ninstance : Repr Arg := \u27e8fun n _ => Arg_repr n\u27e9\ninstance : Repr Arm := \u27e8fun n _ => Arm_repr n\u27e9\ninstance : Repr DoElem := \u27e8fun n _ => DoElem_repr n\u27e9\ninstance : Repr Proof := \u27e8fun n _ => Proof_repr n\u27e9\ninstance : Repr Tactic := \u27e8fun n _ => Tactic_repr n\u27e9\ninstance : Repr Block := \u27e8fun n _ => Block_repr n\u27e9\ninstance : Repr Param := \u27e8fun n _ => Param_repr n\u27e9\ninstance : Repr VMCall := \u27e8fun n _ => VMCall_repr n\u27e9\ninstance : Repr PrecSymbol := \u27e8fun n _ => PrecSymbol_repr n\u27e9\ninstance : Repr Action := \u27e8fun n _ => Action_repr n\u27e9\ninstance : Repr Literal := \u27e8fun n _ => Literal_repr n\u27e9\n\ninstance : Repr AttrArg where reprPrec\n  | AttrArg.eager, _ => \"!\"\n  | AttrArg.indices ns, _ => spacedBefore repr ns\n  | AttrArg.keyValue a b, _ => \" \" ++ repr a ++ \" \" ++ repr b\n  | AttrArg.vmOverride a b, _ => \" \" ++ repr a ++\n    (match b with | none => \"\" | some b => \" \" ++ repr b : Format)\n  | AttrArg.user _ e, _ => repr e\n\ninstance : Repr Attribute where reprPrec\n  | Attribute.priority e, _ => \"priority \" ++ Expr_repr e.kind\n  | Attribute.del n, _ => (\"-\":Format) ++ n.toString\n  | Attribute.add n arg, _ => n.toString ++\n    (match arg with | none => \"\" | some arg => \" \" ++ repr arg : Format)\n\ninstance : Repr Attributes :=\n  \u27e8fun attrs _ =>  (Format.joinSep (attrs.toList.map repr) \", \").sbracket\u27e9\n\ndef Notation_repr : Notation \u2192 (attrs : Attributes := #[]) \u2192 Format\n  | Notation.mixfix mk name sym val, attrs => repr mk ++\n    (if attrs.isEmpty then \"\" else \" \" ++ repr attrs : Format) ++\n    (match name with | none => \"\" | some n => f!\" (name := {repr n})\") ++\n    \" \" ++ PrecSymbol_repr sym ++\n    (match val with | none => \"\" | some e => \" := \" ++ Expr_repr e.kind)\n  | Notation.notation name lits val, attrs => \"notation\" ++\n    (if attrs.isEmpty then \"\" else \" \" ++ repr attrs : Format) ++\n    (match name with | none => \"\" | some n => f!\" (name := {repr n})\") ++\n    spacedBefore (fun n => Literal_repr n.kind) lits ++\n    (match val with | none => \"\" | some e => \" := \" ++ Expr_repr e.kind)\n\ninstance : Repr Notation := \u27e8fun n _ => Notation_repr n\u27e9\n\ninstance : Repr DeclVal where reprPrec\n  | DeclVal.expr n, _ => \" :=\" ++ Format.line ++ repr n\n  | DeclVal.eqns arms, _ => Format.join (arms.toList.map repr)\n\ninstance : Repr Modifier where reprPrec\n  | Modifier.private, _ => \"private\"\n  | Modifier.protected, _ => \"protected\"\n  | Modifier.noncomputable, _ => \"noncomputable\"\n  | Modifier.meta, _ => \"meta\"\n  | Modifier.mutual, _ => \"mutual\"\n  | Modifier.doc s, _ => (\"/--\" ++ s ++ \"-/\" : String)\n  | Modifier.attr l c attrs, _ =>\n    (if l then \"local \" else \"\") ++ (if c then \"@\" else \"attribute \") ++ repr attrs\n\ndef Modifiers_repr : Modifiers \u2192 Format := spacedAfter repr\ninstance : Repr Modifiers := \u27e8fun n _ => Modifiers_repr n\u27e9\n\ninstance : Repr Intro where reprPrec\n  | \u27e8doc, name, ik, bis, ty\u27e9, _ =>\n    (match doc with | none => \"\" | some doc => \"\\n/--\" ++ doc ++ \"-/\") ++\n    \"\\n| \" ++ name.kind.toString ++ InferKind.optRepr ik ++ repr bis ++ optTy ty\n\ndef Intros_repr (arms : Array #Intro) : Format :=\n  Format.join $ arms.toList.map repr\n\ndef Mutual_repr (f : Array \u03b1 \u2192 Format) : Mutual \u03b1 \u2192 Format\n  | \u27e8attr, n, ty, vals\u27e9 =>\n    \"with \" ++ repr attr ++ \" \" ++ n.kind.toString ++ \" : \" ++\n    Expr_repr ty.kind ++ f vals\n\ninstance : Repr Mk where reprPrec\n  | \u27e8mk, ik\u27e9, _ => mk.kind.toString ++ InferKind.optRepr ik\n\ninstance : Repr Rename where reprPrec\n  | \u27e8\u00abfrom\u00bb, to\u27e9, _ => (\u00abfrom\u00bb.kind.toString ++ \"\u2192\" ++ to.kind.toString : String)\n\ninstance : Repr Parent where reprPrec\n  | \u27e8priv, n, ty, rens\u27e9, _ =>\n    (if priv then \"private \" else \"\") ++\n    (match n with | none => \"\" | some n => n.kind.toString ++ \" : \") ++ repr ty ++\n    if rens.isEmpty then (\"\":Format) else \"renaming\" ++ spacedBefore repr rens\n\ninstance : Repr Field where reprPrec\n  | Field.binder bi vars ik bis ty dflt, _ => bi.bracket true $\n    spaced (fun v => v.kind.toString) vars ++ InferKind.optRepr ik ++\n    Binders_repr bis ++ optTy ty ++ Default_repr dflt\n  | Field.notation n, _ => (repr n).paren\n\ninstance : Repr OpenClause where reprPrec\n  | OpenClause.explicit ns, _ => spaced (fun n => n.kind.toString) ns\n  | OpenClause.renaming rens, _ => \"renaming\" ++ spacedBefore repr rens\n  | OpenClause.hiding ns, _ => \"hiding\" ++ spacedBefore (fun n => n.kind.toString) ns\n\ninstance : Repr Open where reprPrec\n  | \u27e8tgt, as, cls\u27e9, _ => tgt.kind.toString ++\n    (match as with | none => \"\" | some as => \" as \" ++ as.kind.toString) ++\n    spacedBefore (fun i => (repr i).paren) cls\n\ninstance : Repr HelpCmd where\n  reprPrec\n  | HelpCmd.options, _ => \"options\"\n  | HelpCmd.commands, _ => \"commands\"\n\ninstance : Repr PrintCmd where reprPrec c _ := match c with\n  | PrintCmd.str n => repr n\n  | PrintCmd.raw e => \"raw \" ++ (repr e).nest 2\n  | PrintCmd.options => \"options\"\n  | PrintCmd.trust => \"trust\"\n  | PrintCmd.keyEquivalences => \"key_equivalences\"\n  | PrintCmd.def n => \"def \" ++ repr n\n  | PrintCmd.instances n => (\"instances \" : Format) ++ n.kind.toString\n  | PrintCmd.classes => \"classes\"\n  | PrintCmd.attributes => \"attributes\"\n  | PrintCmd.prefix n => (\"prefix \" : Format) ++ n.kind.toString\n  | PrintCmd.aliases => \"aliases\"\n  | PrintCmd.axioms n => (\"axioms\" : Format) ++\n    (match n with | none => \"\" | some n => \" \" ++ n.kind.toString : String)\n  | PrintCmd.fields n => (\"fields \" : Format) ++ n.kind.toString\n  | PrintCmd.notation ns => (\"notation\" : Format) ++ spacedBefore (fun n => n.kind.toString) ns\n  | PrintCmd.inductive n => (\"inductive \" : Format) ++ n.kind.toString\n  | PrintCmd.attr n => (n.kind.toName.toString : Format).sbracket\n  | PrintCmd.token n => n.kind.toString\n  | PrintCmd.ident n => n.kind.toString\n\ninstance : Repr InductiveCmd where reprPrec c _ := match c with\n  | InductiveCmd.reg cl mods n us bis ty nota intros =>\n    repr mods ++ (if cl then \"class \" else \"\") ++ \"inductive \" ++\n    n.kind.toString ++ repr us ++ repr bis ++ optTy ty ++\n    (match nota with | none => \"\" | some n => \"\\n\" ++ repr n) ++\n    Intros_repr intros\n  | InductiveCmd.mutual cl mods us bis nota inds =>\n    repr mods ++ (if cl then \"class \" else \"\") ++ \"inductive \" ++ repr us ++\n    Format.joinSep (inds.toList.map fun m => m.name.kind.toString) \", \" ++ repr bis ++\n    (match nota with | none => \"\" | some n => \"\\n\" ++ repr n) ++\n    Format.join (inds.toList.map (Mutual_repr Intros_repr))\n\ninstance : Repr Command where reprPrec c _ := match c with\n  | Command.initQuotient => \"init_quotient\"\n  | Command.mdoc s => (\"/-!\" ++ s ++ \"-/\" : String)\n  | Command.\u00abuniverse\u00bb var pl ns =>\n    \"universe\" ++ (if var then \" variable\" else \"\") ++ suffix pl ++\n    Format.joinSep (ns.toList.map fun a => a.kind.toString) \" \"\n  | Command.\u00abnamespace\u00bb n => (\"namespace \":Format) ++ n.kind.toString\n  | Command.\u00absection\u00bb (some n) => (\"section \":Format) ++ n.kind.toString\n  | Command.\u00absection\u00bb none => \"section\"\n  | Command.\u00abend\u00bb (some n) => (\"end \":Format) ++ n.kind.toString\n  | Command.\u00abend\u00bb none => \"end\"\n  | Command.\u00abvariable\u00bb vk plural mods bis =>\n    repr mods ++ repr vk ++ (if plural then \"s\" else \"\") ++ Binders_repr bis plural\n  | Command.axiom ak mods n us bis ty =>\n    repr mods ++ repr ak ++ \" \" ++ n.kind.toString ++\n    repr us ++ repr bis ++ optTy ty\n  | Command.axioms ak mods bis => repr mods ++ repr ak ++ \"s\" ++ repr bis\n  | Command.decl dk mods n us bis ty val uwf =>\n    repr mods ++ (repr dk ++\n    (match n with | none => \"\" | some n => \" \" ++ n.kind.toString : String) ++\n    repr us ++ repr bis ++ optTy ty).group.nest 2 ++ repr val.kind ++\n    (match uwf with | none => \"\" | some e => \"\\nusing_well_founded \" ++ (repr e).nest 2)\n  | Command.mutualDecl dk mods us bis arms uwf =>\n    repr mods ++ repr dk ++ \" \" ++ repr us ++\n    Format.joinSep (arms.toList.map fun m => m.name.kind.toString) \", \" ++\n    repr bis ++ Format.join (arms.toList.map (Mutual_repr Arms_repr)) ++\n    (match uwf with | none => \"\" | some e => \"\\nusing_well_founded \" ++ (repr e).nest 2)\n  | Command.inductive ind => repr ind\n  | Command.structure cl mods n us bis exts ty mk flds =>\n    repr mods ++ (if cl then \"class \" else \"structure \") ++\n    n.kind.toString ++ repr us ++ repr bis ++\n    (if exts.isEmpty then (\"\":Format) else \"extends \" ++\n      ((\", \":Format).joinSep $ exts.toList.map repr)) ++ optTy ty ++\n    if mk.isNone && flds.isEmpty then (\"\":Format) else \" :=\" ++\n    (match mk with | none => \"\" | some mk => \" \" ++ repr mk ++\n      if flds.isEmpty then \"\" else \" ::\" : Format) ++\n    ((Format.join $ flds.toList.map fun f => Format.line ++ repr f).group).nest 2\n  | Command.attribute loc mods attrs ns =>\n    repr mods ++ (if loc then \"local \" else \"\") ++ \"attribute\" ++\n    (if attrs.isEmpty then \"\" else \" \" ++ repr attrs : Format) ++ spacedBefore (fun n => n.kind.toString) ns\n  | Command.precedence sym prec => \"precedence \" ++ repr sym ++ \":\" ++ repr prec\n  | Command.notation loc attrs n => repr loc ++ Notation_repr n attrs\n  | Command.open exp ops => (if exp then \"export\" else \"open\") ++ spacedBefore repr ops\n  | Command.include pos ops => (if pos then \"include\" else \"omit\") ++\n    spacedBefore (fun n => n.kind.toString) ops\n  | Command.hide ops => \"hide\" ++ spacedBefore (fun n => n.kind.toString) ops\n  | Command.theory mods => repr mods ++ \"theory\"\n  | Command.setOption n val => \"set_option \" ++ n.kind.toString ++ \" \" ++ repr val\n  | Command.declareTrace n => (\"declare_trace \" : Format) ++ n.kind.toString\n  | Command.addKeyEquivalence a b => (\"add_key_equivalence \" : Format) ++\n    a.kind.toString ++ \" \" ++ b.kind.toString\n  | Command.runCmd e => \"run_cmd \" ++ (repr e).nest 2\n  | Command.check e => \"#check \" ++ (repr e).nest 2\n  | Command.reduce whnf e => \"#reduce \" ++ (if whnf then \"[whnf] \" else \"\") ++ (repr e).nest 2\n  | Command.eval e => \"#eval \" ++ (repr e).nest 2\n  | Command.unify e\u2081 e\u2082 => \"#unify \" ++ (repr e\u2081 ++ \", \" ++ repr e\u2082).nest 2\n  | Command.compile n => (\"#compile \":Format) ++ n.kind.toString\n  | Command.help n => \"#help \" ++ repr n\n  | Command.print n => \"#print \" ++ repr n\n  | Command.userCommand n mods args => repr mods ++ n.toString ++\n    Format.join (args.toList.map fun a => \" \" ++ Param_repr a.kind)\n\ndef Notation.name (sp : Char) (f : PrecSymbol \u2192 String) (withTerm : Bool) (start : String) :\n  Notation \u2192 Name\n| Notation.notation (some name) .. | Notation.mixfix _ (some name) .. => name.kind\n| Notation.notation none lits _ => Id.run do\n  let mut s := start\n  for \u27e8_, lit\u27e9 in lits do\n    match lit with\n    | Literal.nat n => s := s ++ toString n\n    | Literal.sym tk => s := s ++ f tk\n    | Literal.var _ none => s := s.push sp\n    | Literal.var _ (some \u27e8_, Action.prec _\u27e9) => s := s.push sp\n    | Literal.var _ (some \u27e8_, Action.prev\u27e9) => s := s.push sp\n    | Literal.var _ (some \u27e8_, Action.scoped _ _\u27e9) => s := s.push sp\n    | Literal.var _ (some \u27e8_, Action.fold _ _ sep _ _ term\u27e9) =>\n      s := s.push sp ++ f sep\n      if withTerm then if let some term := term then s := s ++ f term\n    | Literal.binder _ => s := s.push sp\n    | Literal.binders _ => s := s.push sp\n  Name.mkSimple s\n| Notation.mixfix mk none tk _ =>\n  Name.mkSimple <| match mk with\n  | MixfixKind.infix => start.push sp ++ (f tk).push sp\n  | MixfixKind.infixl => start.push sp ++ (f tk).push sp\n  | MixfixKind.infixr => start.push sp ++ (f tk).push sp\n  | MixfixKind.postfix => start.push sp ++ f tk\n  | MixfixKind.prefix => start ++ (f tk).push sp\n\ndef Notation.name3 := Notation.name ' ' (\u00b7.1.kind.trim) true \"expr\"\ndef Notation.name4 := Notation.name '_' (\u00b7.1.kind.trim) false \"term\"\n\ndef Attributes.hasToAdditive (attrs : Attributes) : Bool :=\n  attrs.any (\u00b7 matches \u27e8_, .add `to_additive _\u27e9)\n\ndef Modifiers.hasToAdditive (mods : Modifiers) : Bool :=\n  mods.any fun\n    | \u27e8_, .attr _ _ attrs\u27e9 => attrs.hasToAdditive\n    | _ => false\n\nstructure Hyp where\n  name : Name\n  pp : Name\n  type : Lean3.Expr\n  value : Option Lean3.Expr\n\ninstance : Repr Hyp where reprPrec\n  | \u27e8_, pp, t, v\u27e9, _ =>\n    pp.toString ++ \" : \" ++ repr t ++\n    match v with | none => (\"\":Format) | some v => repr v\n\nstructure Goal where\n  hyps : Array Hyp\n  target : Lean3.Expr\n\ninstance : Repr Goal where reprPrec\n  | \u27e8hyps, target\u27e9, _ =>\n    Format.join (hyps.toList.map fun hyp => repr hyp ++ \"\\n\") ++\n    \"\u22a2 \" ++ repr target\n\ndef Goals_repr (gs : Array Goal) : Format :=\n  Format.join (gs.toList.map fun g => repr g ++ \"\\n\")\n\nstructure TacticInvocation where\n  declName : Name\n  ast      : Option #Tactic\n  start    : Array Goal\n  \u00abend\u00bb    : Array Goal\n  success  : Bool\n\ninstance : Repr TacticInvocation where reprPrec\n  | \u27e8declName, tac, start, end_, success\u27e9, _ =>\n    \"in declaration \" ++ toString declName ++ \" \" ++\n    \"invoking \" ++ repr tac ++ \":\\n\" ++\n    \"before:\\n\" ++ Goals_repr start ++\n    (if success then \"success\" else \"failed\") ++ \", after:\\n\" ++ Goals_repr end_\n\nstructure Comment where\n  start : Position\n  \u00abend\u00bb : Position\n  text : String\n  deriving Repr, Inhabited\n\nend AST3\n\nstructure AST3 where\n  \u00abprelude\u00bb : Option #Unit\n  \u00abimport\u00bb : Array (Array #Name)\n  commands : Array (Spanned AST3.Command)\n  indexed_nota : Array AST3.Notation\n  indexed_cmds : Array AST3.Command\n  comments : Array AST3.Comment\n\ninstance : Repr AST3 where reprPrec\n  | \u27e8prel, imps, cmds, _, _, _\u27e9, _ =>\n    (match prel with | none => \"\" | some _ => \"prelude\\n\") ++\n    Format.join (imps.toList.map fun ns =>\n      \"import \" ++ Format.joinSep (ns.toList.map fun a => a.kind.toString) \" \" ++ \"\\n\") ++\n    \"\\n\" ++ Format.join (cmds.toList.map fun c => repr c ++ \"\\n\\n\")\n\npartial def Spanned.unparen : #AST3.Expr \u2192 #AST3.Expr\n  | \u27e8_, AST3.Expr.paren e\u27e9 => e.unparen\n  | e => e\n\nend Mathport\n", "meta": {"author": "leanprover-community", "repo": "mathport", "sha": "b5459df41774820ca21861417fafd8ff7a662fc5", "save_path": "github-repos/lean/leanprover-community-mathport", "path": "github-repos/lean/leanprover-community-mathport/mathport-b5459df41774820ca21861417fafd8ff7a662fc5/Mathport/Syntax/AST3.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713267309572335, "lm_q2_score": 0.03114383323253478, "lm_q1q2_score": 0.005828028763251655}}
{"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\u2081 : type_of (sig.val var) = t) (h\u2082 : ((sig.val var).type).dim = dim) : op\n| compute_list (computes : list (memory (parlang_mcl_tlocal sig) \u2192 memory (parlang_mcl_tlocal sig))) : op\n\ndef ts_updates {sig : signature} : list (op sig) \u2192 thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) \u2192 thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)\n| [] ts := ts\n| (op.store var idx h\u2081 h\u2082 :: ops) ts := ts_updates ops $ thread_state.tlocal_to_shared var idx h\u2081 h\u2082 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 \u2218 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] \u2218 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) \u2192 thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) : \nts_updates [] \u2218 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\u2081 : type_of (sig.val var) = t} {h\u2082} {updates} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) \u2192 thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) : \nts_updates updates \u2218 thread_state.tlocal_to_shared var idx h\u2081 h\u2082 \u2218 f = ts_updates (op.store var idx h\u2081 h\u2082 :: updates) \u2218 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) \u2192 thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) : \nts_updates updates \u2218 compute g \u2218 f = ts_updates (op.compute_list [g] :: updates) \u2218 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) \u2192 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 \u2190map_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 \u2190map_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 \u2190map_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": "/-\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.Tactic.Clear\nimport Lean.Meta.Tactic.Util\nimport Lean.Meta.Tactic.Simp.Main\n\nnamespace Lean.Meta\n\nnamespace SimpAll\n\nstructure Entry where\n  fvarId   : FVarId -- original fvarId\n  userName : Name\n  id       : Name   -- id of the theorem at `SimpTheorems`\n  type     : Expr\n  proof    : Expr\n  deriving Inhabited\n\nstructure State where\n  modified : Bool := false\n  mvarId   : MVarId\n  entries  : Array Entry := #[]\n  ctx      : Simp.Context\n\nabbrev M := StateRefT State MetaM\n\nprivate def initEntries : M Unit := do\n  let hs \u2190 getNondepPropHyps (\u2190 get).mvarId\n  let erased := (\u2190 get).ctx.simpTheorems.erased\n  for h in hs do\n    let localDecl \u2190 getLocalDecl h\n    unless erased.contains localDecl.userName do\n      let fvarId := localDecl.fvarId\n      let proof  := localDecl.toExpr\n      let id     \u2190 mkFreshUserName `h\n      let simpThms \u2190 (\u2190 get).ctx.simpTheorems.add #[] proof (name? := id)\n      let entry : Entry := { fvarId := fvarId, userName := localDecl.userName, id := id, type := (\u2190 instantiateMVars localDecl.type), proof := proof }\n      modify fun s => { s with entries := s.entries.push entry, ctx.simpTheorems := simpThms }\n\nprivate abbrev getSimpTheorems : M SimpTheorems :=\n  return (\u2190 get).ctx.simpTheorems\n\nprivate partial def loop : M Bool := do\n  modify fun s => { s with modified := false }\n  -- simplify entries\n  for i in [:(\u2190 get).entries.size] do\n    let entry := (\u2190 get).entries[i]\n    let ctx := (\u2190 get).ctx\n    -- We disable the current entry to prevent it to be simplified to `True`\n    let simpThmsWithoutEntry := (\u2190 getSimpTheorems).eraseCore entry.id\n    let ctx := { ctx with simpTheorems := simpThmsWithoutEntry }\n    match (\u2190 simpStep (\u2190 get).mvarId entry.proof entry.type ctx) with\n    | none => return true -- closed the goal\n    | some (proofNew, typeNew) =>\n      unless typeNew == entry.type do\n        let id \u2190 mkFreshUserName `h\n        let simpThmsNew \u2190 (\u2190 getSimpTheorems).add #[] proofNew (name? := id)\n        modify fun s => { s with\n          modified         := true\n          ctx.simpTheorems := simpThmsNew\n          entries[i]       := { entry with type := typeNew, proof := proofNew, id := id }\n        }\n  -- simplify target\n  let mvarId := (\u2190 get).mvarId\n  match (\u2190 simpTarget mvarId (\u2190 get).ctx) with\n  | none => return true\n  | some mvarIdNew =>\n    unless mvarId == mvarIdNew do\n      modify fun s => { s with\n        modified := true\n        mvarId   := mvarIdNew\n      }\n  if (\u2190 get).modified then\n    loop\n  else\n    return false\n\ndef main : M (Option MVarId) := do\n  initEntries\n  if (\u2190 loop) then\n    return none -- close the goal\n  else\n    let mvarId := (\u2190 get).mvarId\n    let entries := (\u2190 get).entries\n    let (_, mvarId) \u2190 assertHypotheses mvarId (entries.map fun e => { userName := e.userName, type := e.type, value := e.proof })\n    tryClearMany mvarId (entries.map fun e => e.fvarId)\n\nend SimpAll\n\ndef simpAll (mvarId : MVarId) (ctx : Simp.Context) : MetaM (Option MVarId) := do\n  withMVarContext mvarId do\n    SimpAll.main.run' { mvarId := mvarId, ctx := ctx }\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/SimpAll.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20689405859634893, "lm_q2_score": 0.02758528252657529, "lm_q1q2_score": 0.005707231059450108}}
{"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 \u2293 A \u2192 V) :\n    A \u2192 A \u2192 V :=\n  \u03bb 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 \u2192 A \u2192 V) :\n    A \u2293 A \u2192 V :=\n  \u03bb 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 \u2192 A \u2192 V) :=\n  A \u2293 A \u27ff[propMap r] V\n  notation:20 A:21 \" \u2910[\" 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 \u2293 A \u27f6 \u230aV\u230b\n  infixr:20 \" \u2910 \" => HasRelations.Relation\n\n  variable {V : Universe} [HasRelations U V] {A : U}\n\n  instance coeRel : CoeFun (A \u2910 V) (\u03bb _ => A \u2192 A \u2192 V) := \u27e8\u03bb \u03b8 => relMap \u03b8.p\u27e9\n\n  def defExtractABFun : (A \u2293 A) \u2293 A \u27f6{\u03bb P => intro (fst (fst P)) (snd (fst P))} A \u2293 A :=\n  fstFun (A \u2293 A) A\n  \u25c4 \u03bb _ => by simp\n\n  def defExtractBCFun : (A \u2293 A) \u2293 A \u27f6{\u03bb P => intro (snd (fst P)) (snd P)} A \u2293 A :=\n  elim\u2083LFun (HasSubLinearFunOp.constFun A (introFunFun A A))\n  \u25c4 \u03bb _ => by simp [elim\u2083LFun]\n\n  def defExtractACFun : (A \u2293 A) \u2293 A \u27f6{\u03bb P => intro (fst (fst P)) (snd P)} A \u2293 A :=\n  elim\u2083LFun (HasLinearFunOp.swapFunFun (HasSubLinearFunOp.constFun A (introFunFun A A)))\n  \u25c4 \u03bb _ => by simp [elim\u2083LFun]\n\n  @[reducible] def extractABFun' : (A \u2293 A) \u2293 A \u27f6' A \u2293 A := HasFunctoriality.fromDefFun defExtractABFun\n  @[reducible] def extractBCFun' : (A \u2293 A) \u2293 A \u27f6' A \u2293 A := HasFunctoriality.fromDefFun defExtractBCFun\n  @[reducible] def extractACFun' : (A \u2293 A) \u2293 A \u27f6' A \u2293 A := HasFunctoriality.fromDefFun defExtractACFun\n\n  variable [HasCompFunProp' U U V] (\u03b8 : A \u2910 V)\n\n  class HasRefl where\n  (reflPi : \u03a0 compProp (dupIntroFun' A) \u03b8)\n\n  def HasRefl.refl [HasRefl \u03b8] (a : A) : \u03b8 a a := reflPi a\n\n  variable [HasInternalFunctors V] [HasFunProp U V V V]\n\n  class HasTrans where\n  (transPi : \u03a0 {compProp extractABFun' \u03b8 \u27f6 {compProp extractBCFun' \u03b8 \u27f6 compProp extractACFun' \u03b8}})\n\n  @[simp] theorem simp_extractAB (a b c : A) :\n    let P := intro\u2083L a b c;\n    \u03b8 (fst (fst P)) (snd (fst P)) = \u03b8 a b :=\n  by simp\n\n  @[simp] theorem simp_extractBC (a b c : A) :\n    let P := intro\u2083L a b c;\n    \u03b8 (snd (fst P)) (snd P) = \u03b8 b c :=\n  by simp\n\n  @[simp] theorem simp_extractAC (a b c : A) :\n    let P := intro\u2083L a b c;\n    \u03b8 (fst (fst P)) (snd P) = \u03b8 a c :=\n  by simp\n\n  def HasTrans.trans [HasTrans \u03b8] (a b c : A) : \u03b8 a b \u27f6 \u03b8 b c \u27f6 \u03b8 a c :=\n  simp_extractAB \u03b8 a b c \u25b8 simp_extractBC \u03b8 a b c \u25b8 simp_extractAC \u03b8 a b c \u25b8 transPi (intro\u2083L a b c)\n\n  class IsPreorder extends HasRefl \u03b8, HasTrans \u03b8\n\n  variable [HasInternalProducts V] [HasInternalEquivalences V] [HasEquivProp U V V]\n\n  class HasSymm where\n  (symmPi : \u03a0 {\u03b8 \u27f6 compProp (commFun' A A) \u03b8})\n\n  @[simp] theorem simp_swap (a b : A) :\n    let P := intro a b;\n    \u03b8 (snd P) (fst P) = \u03b8 b a :=\n  by simp\n\n  def HasSymm.symm [HasSymm \u03b8] (a b : A) : \u03b8 a b \u27f6 \u03b8 b a :=\n  simp_swap \u03b8 a b \u25b8 symmPi (intro a b)\n\n  class HasTransEquiv [HasTrans \u03b8] [HasSymm \u03b8] where\n  (defTransEquiv    {a b : A} (f : \u03b8 a b) (c : A) :\n      \u03b8 b c \u27f7{HasTrans.trans \u03b8 a b c f, HasTrans.trans \u03b8 b a c (HasSymm.symm \u03b8 a b f)} \u03b8 a c)\n  (defTransEquivFun (a b c : A)                   :\n      \u03b8 a b \u27f6{\u03bb f => HasEquivalences.fromDefEquiv (defTransEquiv f c)} (\u03b8 b c \u27f7 \u03b8 a c))\n\n  class HasSymmEquiv [HasSymm \u03b8] where\n  (defSymmEquiv (a b : A) : \u03b8 a b \u27f7{HasSymm.symm \u03b8 a b, HasSymm.symm \u03b8 b a} \u03b8 b a)\n\n  class IsEquivalence extends IsPreorder \u03b8, HasSymm \u03b8, HasTransEquiv \u03b8\n\n  def substRel (\u03c6 : A \u27f6 \u230aV\u230b) : A \u2910 V :=\n  {compProp (fstFun' A A) \u03c6 \u27f7 compProp (sndFun' A A) \u03c6}\n\n  @[simp] theorem simp_subst_refl (\u03c6 : A \u27f6 \u230aV\u230b) :\n    compProp (dupIntroFun' A) (substRel \u03c6) = {\u03c6 \u27f7 \u03c6} :=\n  sorry\n\n  class HasIdEquivPi (\u03c6 : A \u27f6 \u230aV\u230b) where\n  [hasIdFun   : HasIdFun V]\n  [hasIdEquiv : HasIdEquiv V V]\n  (F          : \u03a0{\u03bb a => HasIdEquiv.idEquiv (\u03c6 a)} {\u03c6 \u27f7 \u03c6})\n\n  instance substRel.hasRefl (\u03c6 : A \u27f6 \u230aV\u230b) [h : HasIdEquivPi \u03c6] :\n    HasRefl (substRel \u03c6) :=\n  \u27e8simp_subst_refl \u03c6 \u25b8 h.F\u27e9\n\n  class IsSubstitution extends HasRefl \u03b8 where\n  (substPi (\u03c6 : A \u27f6 \u230aV\u230b) [HasIdEquivPi \u03c6] : \u03a0 {\u03b8 \u27f6 substRel \u03c6})\n\n  @[simp] theorem simp_apply_fst (\u03c6 : A \u27f6 \u230aV\u230b) (a b : A) :\n    \u03c6 (fst (intro a b)) = \u03c6 a :=\n  by simp\n\n  @[simp] theorem simp_apply_snd (\u03c6 : A \u27f6 \u230aV\u230b) (a b : A) :\n    \u03c6 (snd (intro a b)) = \u03c6 b :=\n  by simp\n\n  def IsSubstitution.subst [IsSubstitution \u03b8] (\u03c6 : A \u27f6 \u230aV\u230b) [HasIdEquivPi \u03c6] (a b : A) :\n    \u03b8 a b \u27f6 (\u03c6 a \u27f7 \u03c6 b) :=\n  simp_apply_fst \u03c6 a b \u25b8 simp_apply_snd \u03c6 a b \u25b8 substPi \u03c6 (intro a b)\n\n  class IsIdentity extends HasRefl \u03b8 where\n  (elimPi (\u03be : A \u2910 V) [HasRefl \u03be] : \u03a0 {\u03b8 \u27f6 \u03be})\n\n  namespace IsIdentity\n\n    variable [IsIdentity \u03b8]\n\n    def elim (\u03be : A \u2910 V) [HasRefl \u03be] (a b : A) : \u03b8 a b \u27f6 \u03be a b :=\n    elimPi \u03be (HasProducts.intro a b)\n\n    instance isSubstitution : IsSubstitution \u03b8 :=\n    { substPi := \u03bb \u03c6 => elimPi (substRel \u03c6) }\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": "example (a : \u03b1) : \u00ac some (some a) = some none := 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/run/simpLoopBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968261942204597, "lm_q2_score": 0.028870904230656375, "lm_q1q2_score": 0.005682550203423463}}
{"text": "import mcl.defs\nimport mcl.rhl\nimport parlang.defs\nimport syncablep\nimport mcl.compute_list\nimport mcl.ts_updates\n\nopen mcl\nopen mcl.mclk\nopen mcl.rhl\n\nnamespace assign_mcl\n\nopen parlang\nopen parlang.state\nopen parlang.thread_state\n\n/- not in use -/\n-- lemma store_access_elim_name {sig : signature} {n n_idx} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {var} {idx : vector (expression sig type.int) n_idx} \n-- {t h\u2084} {h\u2083 : type_of (sig.val var) = t } {f} {t : fin n} {i} {ac\u2081 : vector bool n} {updates}\n-- (h\u2081 : i \u2209 accesses (vector.nth ((map_active_threads ac\u2081 (f \u2218 compute_list updates) s).threads) t)) \n-- (h\u2082 : i.1 \u2260 var) :\n-- i \u2209 accesses (vector.nth ((map_active_threads ac\u2081 (f \u2218 (thread_state.tlocal_to_shared var idx h\u2083 h\u2084) \u2218 compute_list updates) s).threads) t) := begin\n--     sorry,\n-- end\n\n-- lemma store_no_stores_name {sig : signature} {dim} {idx : vector (expression sig type.int) dim} {var t} {h\u2081 : type_of (sig.val var) = t} {h\u2082} {computes : list (memory (parlang_mcl_tlocal sig) \u2192 memory (parlang_mcl_tlocal sig))}\n-- {ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {i : mcl_address sig}\n-- {n} {s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {m : memory (parlang_mcl_shared sig)} {tid}\n-- {f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) \u2192 thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} : \n-- syncable ((f \u2218 compute_list computes) s) m \u2192\n-- i.fst \u2260 var \u2192\n-- i \u2209 ((f \u2218 compute_list computes) (s.threads.nth tid)).stores \u2192\n-- i \u2209 ((f \u2218 thread_state.tlocal_to_shared var idx h\u2081 h\u2082 \u2218 compute_list computes) (s.threads.nth tid)).stores := begin\n--     intros syncable i_not_var i_not_in_f,\n--     unfold parlang.state.syncable at syncable,\n--     specialize syncable i,\n--     cases ts,\n--     induction computes,\n--     {\n--         simp [compute_list, thread_state.tlocal_to_shared, store],\n--     }, {\n\n--     }\n-- end\n\nend assign_mcl", "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/use_cases/assign_mcl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3040416875789104, "lm_q2_score": 0.018264281524716788, "lm_q1q2_score": 0.005553102977191207}}
{"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, Sebastian Ullrich\n-/\nimport Lean.ResolveName\nimport Lean.Util.Sorry\nimport Lean.Util.ReplaceExpr\nimport Lean.Structure\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.CollectMVars\nimport Lean.Meta.Coe\nimport Lean.Hygiene\nimport Lean.Util.RecDepth\n\nimport Lean.Elab.Log\nimport Lean.Elab.Config\nimport Lean.Elab.Level\nimport Lean.Elab.Attributes\nimport Lean.Elab.AutoBound\nimport Lean.Elab.InfoTree\nimport Lean.Elab.Open\nimport Lean.Elab.SetOption\nimport Lean.Elab.DeclModifiers\n\nnamespace Lean.Elab.Term\nstructure Context where\n  fileName        : String\n  fileMap         : FileMap\n  declName?       : Option Name     := none\n  macroStack      : MacroStack      := []\n  currMacroScope  : MacroScope      := firstFrontendMacroScope\n  /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.\n     The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in\n     the list of pending synthetic metavariables, and returns `?m`. -/\n  mayPostpone     : Bool            := true\n  /- When `errToSorry` is set to true, the method `elabTerm` catches\n     exceptions and converts them into synthetic `sorry`s.\n     The implementation of choice nodes and overloaded symbols rely on the fact\n     that when `errToSorry` is set to false for an elaboration function `F`, then\n     `errToSorry` remains `false` for all elaboration functions invoked by `F`.\n     That is, it is safe to transition `errToSorry` from `true` to `false`, but\n     we must not set `errToSorry` to `true` when it is currently set to `false`. -/\n  errToSorry      : Bool            := true\n  /- When `autoBoundImplicit` is set to true, instead of producing\n     an \"unknown identifier\" error for unbound variables, we generate an\n     internal exception. This exception is caught at `elabBinders` and\n     `elabTypeWithUnboldImplicit`. Both methods add implicit declarations\n     for the unbound variable and try again. -/\n  autoBoundImplicit  : Bool            := false\n  autoBoundImplicits : Std.PArray Expr := {}\n  /-- Map from user name to internal unique name -/\n  sectionVars        : NameMap Name    := {}\n  /-- Map from internal name to fvar -/\n  sectionFVars       : NameMap Expr    := {}\n  /-- Enable/disable implicit lambdas feature. -/\n  implicitLambda     : Bool            := true\n  /-- noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for  -/\n  isNoncomputableSection : Bool        := false\n  /-- when `true` we skip TC failures. We use this option when processing patterns -/\n  ignoreTCFailures : Bool := false\n\n/-- Saved context for postponed terms and tactics to be executed. -/\nstructure SavedContext where\n  declName?  : Option Name\n  options    : Options\n  openDecls  : List OpenDecl\n  macroStack : MacroStack\n  errToSorry : Bool\n\n/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/\ninductive SyntheticMVarKind where\n  -- typeclass instance search\n  | typeClass\n  /- Similar to typeClass, but error messages are different.\n     if `f?` is `some f`, we produce an application type mismatch error message.\n     Otherwise, if `header?` is `some header`, we generate the error `(header ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)`\n     Otherwise, we generate the error `(\"type mismatch\" ++ e ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)` -/\n  | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)\n  -- tactic block execution\n  | tactic (tacticCode : Syntax) (ctx : SavedContext)\n  -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)\n  | postponed (ctx : SavedContext)\n\ninstance : ToString SyntheticMVarKind where\n  toString\n    | SyntheticMVarKind.typeClass    => \"typeclass\"\n    | SyntheticMVarKind.coe ..       => \"coe\"\n    | SyntheticMVarKind.tactic ..    => \"tactic\"\n    | SyntheticMVarKind.postponed .. => \"postponed\"\n\nstructure SyntheticMVarDecl where\n  mvarId : MVarId\n  stx : Syntax\n  kind : SyntheticMVarKind\n\ninductive MVarErrorKind where\n  | implicitArg (ctx : Expr)\n  | hole\n  | custom (msgData : MessageData)\n  deriving Inhabited\n\ninstance : ToString MVarErrorKind where\n  toString\n    | MVarErrorKind.implicitArg ctx => \"implicitArg\"\n    | MVarErrorKind.hole            => \"hole\"\n    | MVarErrorKind.custom msg      => \"custom\"\n\nstructure MVarErrorInfo where\n  mvarId    : MVarId\n  ref       : Syntax\n  kind      : MVarErrorKind\n  argName?  : Option Name := none\n  deriving Inhabited\n\nstructure LetRecToLift where\n  ref            : Syntax\n  fvarId         : FVarId\n  attrs          : Array Attribute\n  shortDeclName  : Name\n  declName       : Name\n  lctx           : LocalContext\n  localInstances : LocalInstances\n  type           : Expr\n  val            : Expr\n  mvarId         : MVarId\n\nstructure State where\n  levelNames        : List Name       := []\n  syntheticMVars    : List SyntheticMVarDecl := []\n  mvarErrorInfos    : MVarIdMap MVarErrorInfo := {}\n  messages          : MessageLog := {}\n  letRecsToLift     : List LetRecToLift := []\n  infoState         : InfoState := {}\n  deriving Inhabited\n\nabbrev TermElabM := ReaderT Context $ StateRefT State MetaM\nabbrev TermElab  := Syntax \u2192 Option Expr \u2192 TermElabM Expr\n\n-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the\n-- whole monad stack at every use site. May eventually be covered by `deriving`.\ninstance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind }\n\nopen Meta\n\ninstance : Inhabited (TermElabM \u03b1) where\n  default := throw default\n\nstructure SavedState where\n  meta   : Meta.SavedState\n  \u00abelab\u00bb : State\n  deriving Inhabited\n\nprotected def saveState : TermElabM SavedState := do\n  pure { meta := (\u2190 Meta.saveState), \u00abelab\u00bb := (\u2190 get) }\n\ndef SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do\n  let traceState \u2190 getTraceState -- We never backtrack trace message\n  let infoState := (\u2190 get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false`\n  s.meta.restore\n  set s.elab\n  setTraceState traceState\n  unless restoreInfo do\n    modify fun s => { s with infoState := infoState }\n\ninstance : MonadBacktrack SavedState TermElabM where\n  saveState      := Term.saveState\n  restoreState b := b.restore\n\nabbrev TermElabResult (\u03b1 : Type) := EStateM.Result Exception SavedState \u03b1\n\ninstance [Inhabited \u03b1] : Inhabited (TermElabResult \u03b1) where\n  default := EStateM.Result.ok default default\n\ndef setMessageLog (messages : MessageLog) : TermElabM Unit :=\n  modify fun s => { s with messages := messages }\n\ndef resetMessageLog : TermElabM Unit :=\n  setMessageLog {}\n\ndef getMessageLog : TermElabM MessageLog :=\n  return (\u2190 get).messages\n\n/--\n  Execute `x`, save resulting expression and new state.\n  We remove any `Info` created by `x`.\n  The info nodes are committed when we execute `applyResult`.\n  We use `observing` to implement overloaded notation and decls.\n  We want to save `Info` nodes for the chosen alternative.\n-/\ndef observing (x : TermElabM \u03b1) : TermElabM (TermElabResult \u03b1) := do\n  let s \u2190 saveState\n  try\n    let e \u2190 x\n    let sNew \u2190 saveState\n    s.restore (restoreInfo := true)\n    pure (EStateM.Result.ok e sNew)\n  catch\n    | ex@(Exception.error _ _) =>\n      let sNew \u2190 saveState\n      s.restore (restoreInfo := true)\n      pure (EStateM.Result.error ex sNew)\n    | ex@(Exception.internal id _) =>\n      if id == postponeExceptionId then\n        s.restore (restoreInfo := true)\n      throw ex\n\n/--\n  Apply the result/exception and state captured with `observing`.\n  We use this method to implement overloaded notation and symbols. -/\ndef applyResult (result : TermElabResult \u03b1) : TermElabM \u03b1 :=\n  match result with\n  | EStateM.Result.ok a r     => do r.restore (restoreInfo := true); pure a\n  | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex\n\n/--\n  Execute `x`, but keep state modifications only if `x` did not postpone.\n  This method is useful to implement elaboration functions that cannot decide whether\n  they need to postpone or not without updating the state. -/\ndef commitIfDidNotPostpone (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  -- We just reuse the implementation of `observing` and `applyResult`.\n  let r \u2190 observing x\n  applyResult r\n\ndef getLevelNames : TermElabM (List Name) :=\n  return (\u2190 get).levelNames\n\ndef getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do\n  match (\u2190 getLCtx).find? fvar.fvarId! with\n  | some d => pure d\n  | none   => unreachable!\n\ninstance : AddErrorMessageContext TermElabM where\n  add ref msg := do\n    let ctx \u2190 read\n    let ref := getBetterRef ref ctx.macroStack\n    let msg \u2190 addMessageContext msg\n    let msg \u2190 addMacroStack msg ctx.macroStack\n    pure (ref, msg)\n\ninstance : MonadLog TermElabM where\n  getRef      := getRef\n  getFileMap  := return (\u2190 read).fileMap\n  getFileName := return (\u2190 read).fileName\n  logMessage msg := do\n    let ctx \u2190 readThe Core.Context\n    let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };\n    modify fun s => { s with messages := s.messages.add msg }\n\nprotected def getCurrMacroScope : TermElabM MacroScope := do pure (\u2190 read).currMacroScope\nprotected def getMainModule     : TermElabM Name := do pure (\u2190 getEnv).mainModule\n\nprotected def withFreshMacroScope (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let fresh \u2190 modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))\n  withReader (fun ctx => { ctx with currMacroScope := fresh }) x\n\ninstance : MonadQuotation TermElabM where\n  getCurrMacroScope   := Term.getCurrMacroScope\n  getMainModule       := Term.getMainModule\n  withFreshMacroScope := Term.withFreshMacroScope\n\ninstance : MonadInfoTree TermElabM where\n  getInfoState      := return (\u2190 get).infoState\n  modifyInfoState f := modify fun s => { s with infoState := f s.infoState }\n\n/--\n  Execute `x` but discard changes performed at `Term.State` and `Meta.State`.\n  Recall that the environment is at `Core.State`. Thus, any updates to it will\n  be preserved. This method is useful for performing computations where all\n  metavariable must be resolved or discarded.\n  The info trees are not discarded, however, and wrapped in `InfoTree.Context`\n  to store their metavariable context. -/\ndef withoutModifyingElabMetaStateWithInfo (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let s \u2190 get\n  let sMeta \u2190 getThe Meta.State\n  try\n     withSaveInfoContext x\n  finally\n    modify ({ s with infoState := \u00b7.infoState })\n    set sMeta\n\n/--\n  Execute `x` bud discard changes performed to the state.\n  However, the info trees and messages are not discarded. -/\nprivate def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let saved \u2190 saveState\n  try\n    x\n  finally\n    let s \u2190 get\n    let saved := { saved with elab.infoState := s.infoState, elab.messages := s.messages }\n    restoreState saved\n\nunsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=\n  mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab \"term\"\n\n@[implementedBy mkTermElabAttributeUnsafe]\nconstant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)\n\nbuiltin_initialize termElabAttribute : KeyedDeclsAttribute TermElab \u2190 mkTermElabAttribute\n\n/--\n  Auxiliary datatatype for presenting a Lean lvalue modifier.\n  We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.\n  Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list\n  `[LVal.fieldName \"foo\", LVal.getOp i, LVal.fieldIdx 1]`.\n  Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/\ninductive LVal where\n  | fieldIdx  (ref : Syntax) (i : Nat)\n    /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name.\n       `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/\n  | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)\n  | getOp     (ref : Syntax) (idx : Syntax)\n\ndef LVal.getRef : LVal \u2192 Syntax\n  | LVal.fieldIdx ref _    => ref\n  | LVal.fieldName ref ..  => ref\n  | LVal.getOp ref _       => ref\n\ndef LVal.isFieldName : LVal \u2192 Bool\n  | LVal.fieldName .. => true\n  | _ => false\n\ninstance : ToString LVal where\n  toString\n    | LVal.fieldIdx _ i     => toString i\n    | LVal.fieldName _ n .. => n\n    | LVal.getOp _ idx      => \"[\" ++ toString idx ++ \"]\"\n\ndef getDeclName? : TermElabM (Option Name) := return (\u2190 read).declName?\ndef getLetRecsToLift : TermElabM (List LetRecToLift) := return (\u2190 get).letRecsToLift\ndef isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (\u2190 getMCtx).isExprAssigned mvarId\ndef getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (\u2190 getMCtx).getDecl mvarId\ndef assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }\n\ndef withDeclName (name : Name) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with declName? := name }) x\n\ndef setLevelNames (levelNames : List Name) : TermElabM Unit :=\n  modify fun s => { s with levelNames := levelNames }\n\ndef withLevelNames (levelNames : List Name) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let levelNamesSaved \u2190 getLevelNames\n  setLevelNames levelNames\n  try x finally setLevelNames levelNamesSaved\n\ndef withoutErrToSorry (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with errToSorry := false }) x\n\n/-- For testing `TermElabM` methods. The #eval command will sign the error. -/\ndef throwErrorIfErrors : TermElabM Unit := do\n  if (\u2190 get).messages.hasErrors then\n    throwError \"Error(s)\"\n\ndef traceAtCmdPos (cls : Name) (msg : Unit \u2192 MessageData) : TermElabM Unit :=\n  withRef Syntax.missing $ trace cls msg\n\ndef ppGoal (mvarId : MVarId) : TermElabM Format :=\n  Meta.ppGoal mvarId\n\nopen Level (LevelElabM)\n\ndef liftLevelM (x : LevelElabM \u03b1) : TermElabM \u03b1 := do\n  let ctx \u2190 read\n  let mctx \u2190 getMCtx\n  let ngen \u2190 getNGen\n  let lvlCtx : Level.Context := { options := (\u2190 getOptions), ref := (\u2190 getRef), autoBoundImplicit := ctx.autoBoundImplicit }\n  match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (\u2190 getLevelNames) } with\n  | EStateM.Result.ok a newS  => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a\n  | EStateM.Result.error ex _ => throw ex\n\ndef elabLevel (stx : Syntax) : TermElabM Level :=\n  liftLevelM $ Level.elabLevel stx\n\n/- Elaborate `x` with `stx` on the macro stack -/\ndef withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withMacroExpansionInfo beforeStx afterStx do\n    withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x\n\n/-\n  Add the given metavariable to the list of pending synthetic metavariables.\n  The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/\ndef registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }\n\ndef registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  registerSyntheticMVar (\u2190 getRef) mvarId kind\n\ndef registerMVarErrorInfo (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit :=\n  modify fun s => { s with mvarErrorInfos := s.mvarErrorInfos.insert mvarErrorInfo.mvarId mvarErrorInfo }\n\ndef registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit :=\n  registerMVarErrorInfo { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole }\n\ndef registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do\n  registerMVarErrorInfo { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app }\n\ndef registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do\n  registerMVarErrorInfo { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData }\n\ndef getMVarErrorInfo? (mvarId : MVarId) : TermElabM (Option MVarErrorInfo) := do\n  return (\u2190 get).mvarErrorInfos.find? mvarId\n\ndef registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=\n  match e.getAppFn with\n  | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData\n  | _ => pure ()\n\n/-\n  Auxiliary method for reporting errors of the form \"... contains metavariables ...\".\n  This kind of error is thrown, for example, at `Match.lean` where elaboration\n  cannot continue if there are metavariables in patterns.\n  We only want to log it if we haven't logged any error so far. -/\ndef throwMVarError (m : MessageData) : TermElabM \u03b1 := do\n  if (\u2190 get).messages.hasErrors then\n    throwAbortTerm\n  else\n    throwError m\n\ndef MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do\n  match mvarErrorInfo.kind with\n  | MVarErrorKind.implicitArg app => do\n    let app \u2190 instantiateMVars app\n    let msg := addArgName \"don't know how to synthesize implicit argument\"\n    let msg := msg ++ m!\"{indentExpr app.setAppPPExplicitForExposingMVars}\" ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\n  | MVarErrorKind.hole => do\n    let msg := addArgName \"don't know how to synthesize placeholder\" \" for argument\"\n    let msg := msg ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)\n  | MVarErrorKind.custom msg =>\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\nwhere\n  /-- Append `mvarErrorInfo` argument name (if available) to the message.\n      Remark: if the argument name contains macro scopes we do not append it. -/\n  addArgName (msg : MessageData) (extra : String := \"\") : MessageData :=\n    match mvarErrorInfo.argName? with\n    | none => msg\n    | some argName => if argName.hasMacroScopes then msg else msg ++ extra ++ m!\" '{argName}'\"\n\n  appendExtra (msg : MessageData) : MessageData :=\n    match extraMsg? with\n    | none => msg\n    | some extraMsg => msg ++ extraMsg\n\n/--\n  Try to log errors for the unassigned metavariables `pendingMVarIds`.\n\n  Return `true` if there were \"unfilled holes\", and we should \"abort\" declaration.\n  TODO: try to fill \"all\" holes using synthetic \"sorry's\"\n\n  Remark: We only log the \"unfilled holes\" as new errors if no error has been logged so far. -/\ndef logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do\n  let s \u2190 get\n  let hasOtherErrors := s.messages.hasErrors\n  let mut hasNewErrors := false\n  let mut alreadyVisited : MVarIdSet := {}\n  let mut errors : Array MVarErrorInfo := #[]\n  for (_, mvarErrorInfo) in s.mvarErrorInfos do\n    let mvarId := mvarErrorInfo.mvarId\n    unless alreadyVisited.contains mvarId do\n      alreadyVisited := alreadyVisited.insert mvarId\n      /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or\n         delayed assigned to another metavariable that is unassigned. -/\n      let mvarDeps \u2190 getMVars (mkMVar mvarId)\n      if mvarDeps.any pendingMVarIds.contains then do\n        unless hasOtherErrors do\n          errors := errors.push mvarErrorInfo\n        hasNewErrors := true\n  -- To sort the errors by position use\n  -- let sortedErrors := errors.qsort fun e\u2081 e\u2082 => e\u2081.ref.getPos?.getD 0 < e\u2082.ref.getPos?.getD 0\n  for error in errors do\n    withMVarContext error.mvarId do\n      error.logError extraMsg?\n  return hasNewErrors\n\n/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/\ndef ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do\n  let pendingMVarIds \u2190 getMVarsAtDecl decl\n  if (\u2190 logUnassignedUsingErrorInfos pendingMVarIds) then\n    throwAbortCommand\n\n/-\n  Execute `x` without allowing it to postpone elaboration tasks.\n  That is, `tryPostpone` is a noop. -/\ndef withoutPostponing (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with mayPostpone := false }) x\n\n/-- Creates syntax for `(` <ident> `:` <type> `)` -/\ndef mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=\n  mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom \"(\", mkNullNode #[ident], mkNullNode #[mkAtom \":\", type], mkNullNode, mkAtom \")\"]\n\n/--\n  Convert unassigned universe level metavariables into parameters.\n  The new parameter names are of the form `u_i` where `i >= nextParamIdx`.\n  The method returns the updated expression and new `nextParamIdx`.\n\n  Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/\ndef levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr \u00d7 Nat) := do\n  let mctx \u2190 getMCtx\n  let levelNames \u2190 getLevelNames\n  let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx\n  setMCtx r.mctx\n  pure (r.expr, r.nextParamIdx)\n\n/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/\ndef levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do\n  let nextParamIdx \u2190 get\n  let (e, nextParamIdx) \u2190 levelMVarToParam e nextParamIdx\n  set nextParamIdx\n  pure e\n\n/--\n  Auxiliary method for creating fresh binder names.\n  Do not confuse with the method for creating fresh free/meta variable ids. -/\ndef mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=\n  withFreshMacroScope $ MonadQuotation.addMacroScope `x\n\n/--\n  Auxiliary method for creating a `Syntax.ident` containing\n  a fresh name. This method is intended for creating fresh binder names.\n  It is just a thin layer on top of `mkFreshUserName`. -/\ndef mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax :=\n  return mkIdentFrom ref (\u2190 mkFreshBinderName)\n\nprivate def applyAttributesCore\n    (declName : Name) (attrs : Array Attribute)\n    (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=\n  for attr in attrs do\n    let env \u2190 getEnv\n    match getAttributeImpl env attr.name with\n    | Except.error errMsg => throwError errMsg\n    | Except.ok attrImpl  =>\n      match applicationTime? with\n      | none => attrImpl.add declName attr.stx attr.kind\n      | some applicationTime =>\n        if applicationTime == attrImpl.applicationTime then\n          attrImpl.add declName attr.stx attr.kind\n\n/-- Apply given attributes **at** a given application time -/\ndef applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=\n  applyAttributesCore declName attrs applicationTime\n\ndef applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=\n  applyAttributesCore declName attrs none\n\ndef mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do\n  let header : MessageData := match header? with\n    | some header => m!\"{header} \"\n    | none        => m!\"type mismatch{indentExpr e}\\n\"\n  return m!\"{header}{\u2190 mkHasTypeButIsExpectedMsg eType expectedType}\"\n\ndef throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM \u03b1 := do\n  /-\n    We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was\n    always of the form:\n    ```\n    failed to synthesize instance\n      CoeT <eType> <e> <expectedType>\n    ```\n    We should revisit this decision in the future and decide whether it may contain useful information\n    or not. -/\n  let extraMsg := Format.nil\n  /-\n  let extraMsg : MessageData := match extraMsg? with\n    | none          => Format.nil\n    | some extraMsg => Format.line ++ extraMsg;\n  -/\n  match f? with\n  | none   => throwError \"{\u2190 mkTypeMismatchError header? e eType expectedType}{extraMsg}\"\n  | some f => Meta.throwAppTypeMismatch f e extraMsg\n\ndef withoutMacroStackAtErr (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x\n\nnamespace ContainsPendingMVar\n\nabbrev M := MonadCacheT Expr Unit (OptionT TermElabM)\n\n/-- See `containsPostponedTerm` -/\npartial def visit (e : Expr) : M Unit := do\n  checkCache e fun _ => do\n    match e with\n    | Expr.forallE _ d b _   => visit d; visit b\n    | Expr.lam _ d b _       => visit d; visit b\n    | Expr.letE _ t v b _    => visit t; visit v; visit b\n    | Expr.app f a _         => visit f; visit a\n    | Expr.mdata _ b _       => visit b\n    | Expr.proj _ _ b _      => visit b\n    | Expr.fvar fvarId ..    =>\n      match (\u2190 getLocalDecl fvarId) with\n      | LocalDecl.cdecl .. => return ()\n      | LocalDecl.ldecl (value := v) .. => visit v\n    | Expr.mvar mvarId ..    =>\n      let e' \u2190 instantiateMVars e\n      if e' != e then\n        visit e'\n      else\n        match (\u2190 getDelayedAssignment? mvarId) with\n        | some d => visit d.val\n        | none   => failure\n    | _ => return ()\n\nend ContainsPendingMVar\n\n/-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/\ndef containsPendingMVar (e : Expr) : TermElabM Bool := do\n  match (\u2190 ContainsPendingMVar.visit e |>.run.run) with\n  | some _ => return false\n  | none   => return true\n\n/- Try to synthesize metavariable using type class resolution.\n   This method assumes the local context and local instances of `instMVar` coincide\n   with the current local context and local instances.\n   Return `true` if the instance was synthesized successfully, and `false` if\n   the instance contains unassigned metavariables that are blocking the type class\n   resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/\ndef synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do\n  let instMVarDecl \u2190 getMVarDecl instMVar\n  let type := instMVarDecl.type\n  let type \u2190 instantiateMVars type\n  let result \u2190 trySynthInstance type maxResultSize?\n  match result with\n  | LOption.some val =>\n    if (\u2190 isExprMVarAssigned instMVar) then\n      let oldVal \u2190 instantiateMVars (mkMVar instMVar)\n      unless (\u2190 isDefEq oldVal val) do\n        if (\u2190 containsPendingMVar oldVal <||> containsPendingMVar val) then\n          /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration),\n             we return `false` to indicate we should try again later. This is very course grain since\n             the metavariable may not be responsible for the failure. We should refine the test in the future if needed.\n             This check has been added to address dependencies between postponed metavariables. The following\n             example demonstrates the issue fixed by this test.\n             ```\n               structure Point where\n                 x : Nat\n                 y : Nat\n\n               def Point.compute (p : Point) : Point :=\n                 let p := { p with x := 1 }\n                 let p := { p with y := 0 }\n                 if (p.x - p.y) > p.x then p else p\n             ```\n             The `isDefEq` test above fails for `Decidable (p.x - p.y \u2264 p.x)` when the structure instance assigned to\n             `p` has not been elaborated yet.\n           -/\n          return false -- we will try again later\n        let oldValType \u2190 inferType oldVal\n        let valType \u2190 inferType val\n        unless (\u2190 isDefEq oldValType valType) do\n          throwError \"synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\\nhas type{indentExpr valType}\\nexpected{indentExpr oldValType}\"\n        throwError \"synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\\ninferred{indentExpr oldVal}\"\n    else\n      unless (\u2190 isDefEq (mkMVar instMVar) val) do\n        throwError \"failed to assign synthesized type class instance{indentExpr val}\"\n    pure true\n  | LOption.undef    => return false -- we will try later\n  | LOption.none     =>\n    if (\u2190 read).ignoreTCFailures then\n      return false\n    else\n      throwError \"failed to synthesize instance{indentExpr type}\"\n\nregister_builtin_option autoLift : Bool := {\n  defValue := true\n  descr    := \"insert monadic lifts (i.e., `liftM` and coercions) when needed\"\n}\n\nregister_builtin_option maxCoeSize : Nat := {\n  defValue := 16\n  descr    := \"maximum number of instances used to construct an automatic coercion\"\n}\n\ndef synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do\n  synthesizeInstMVarCore instMVar (some (maxCoeSize.get (\u2190 getOptions)))\n\n/-\nThe coercion from `\u03b1` to `Thunk \u03b1` cannot be implemented using an instance because it would\neagerly evaluate `e` -/\ndef tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do\n  match expectedType with\n  | Expr.app (Expr.const ``Thunk u _) arg _ =>\n    if (\u2190 isDefEq eType arg) then\n      pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e)))\n    else\n      pure none\n  | _ =>\n    pure none\n\ndef mkCoe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  let u \u2190 getLevel eType\n  let v \u2190 getLevel expectedType\n  let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType]\n  let mvar \u2190 mkFreshExprMVar coeTInstType MetavarKind.synthetic\n  let eNew := mkAppN (mkConst ``CoeT.coe [u, v]) #[eType, e, expectedType, mvar]\n  let mvarId := mvar.mvarId!\n  try\n    withoutMacroStackAtErr do\n      if (\u2190 synthesizeCoeInstMVarCore mvarId) then\n        expandCoe eNew\n      else\n        -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe`\n        -- after we syntheze `mvar`\n        let mvarAux \u2190 mkFreshExprMVar expectedType MetavarKind.syntheticOpaque\n        registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?)\n        return mvarAux\n  catch\n    | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg\n    | _                     => throwTypeMismatchError errorMsgHeader? expectedType eType e f?\n\n/--\n  Try to apply coercion to make sure `e` has type `expectedType`.\n  Relevant definitions:\n  ```\n  class CoeT (\u03b1 : Sort u) (a : \u03b1) (\u03b2 : Sort v)\n  abbrev coe {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeT \u03b1 a \u03b2] : \u03b2\n  ```\n-/\nprivate def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do\n  if (\u2190 isDefEq expectedType eType) then\n    return e\n  else match (\u2190 tryCoeThunk? expectedType eType e) with\n    | some r => return r\n    | none   => mkCoe expectedType eType e f? errorMsgHeader?\n\ndef isTypeApp? (type : Expr) : TermElabM (Option (Expr \u00d7 Expr)) := do\n  let type \u2190 withReducible $ whnf type\n  match type with\n  | Expr.app m \u03b1 _ => pure (some ((\u2190 instantiateMVars m), (\u2190 instantiateMVars \u03b1)))\n  | _              => pure none\n\ndef synthesizeInst (type : Expr) : TermElabM Expr := do\n  let type \u2190 instantiateMVars type\n  match (\u2190 trySynthInstance type) with\n  | LOption.some val => pure val\n  -- Note that `ignoreTCFailures` is not checked here since it must return a result.\n  | LOption.undef    => throwError \"failed to synthesize instance{indentExpr type}\"\n  | LOption.none     => throwError \"failed to synthesize instance{indentExpr type}\"\n\ndef isMonadApp (type : Expr) : TermElabM Bool := do\n  let some (m, _) \u2190 isTypeApp? type | pure false\n  return (\u2190 isMonad? m) |>.isSome\n\n/-\nTry coercions and monad lifts to make sure `e` has type `expectedType`.\n\nIf `expectedType` is of the form `n \u03b2`, we try monad lifts and other extensions.\nOtherwise, we just use the basic `tryCoe`.\n\nExtensions for monads.\n\n1- Try to unify `n` and `m`. If it succeeds, then we use\n   ```\n   coeM {m : Type u \u2192 Type v} {\u03b1 \u03b2 : Type u} [\u2200 a, CoeT \u03b1 a \u03b2] [Monad m] (x : m \u03b1) : m \u03b2\n   ```\n   `n` must be a `Monad` to use this one.\n\n2- If there is monad lift from `m` to `n` and we can unify `\u03b1` and `\u03b2`, we use\n  ```\n  liftM : \u2200 {m : Type u_1 \u2192 Type u_2} {n : Type u_1 \u2192 Type u_3} [self : MonadLiftT m n] {\u03b1 : Type u_1}, m \u03b1 \u2192 n \u03b1\n  ```\n  Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as\n  ```\n  def g (x : Nat) : IO Nat := do\n    IO.println x\n    pure x\n\n  def f {m} [MonadLiftT IO m] : m Nat :=\n    g 10\n\n  ```\n\n3- If there is a monad lif from `m` to `n` and a coercion from `\u03b1` to `\u03b2`, we use\n  ```\n  liftCoeM {m : Type u \u2192 Type v} {n : Type u \u2192 Type w} {\u03b1 \u03b2 : Type u} [MonadLiftT m n] [\u2200 a, CoeT \u03b1 a \u03b2] [Monad n] (x : m \u03b1) : n \u03b2\n  ```\n\nNote that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `\u03b1` to `\u03b2` for all values in `\u03b1`.\nThis is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and\nwe only have a coercion from decidable propositions.  Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`\nusing the instance `pureCoeDepProp`.\n\nNote that, approach 2 is more powerful than `tryCoe`.\nRecall that type class resolution never assigns metavariables created by other modules.\nNow, consider the following scenario\n```lean\ndef g (x : Nat) : IO Nat := ...\ndeg h (x : Nat) : StateT Nat IO Nat := do\nv \u2190 g x;\nIO.Println v;\n...\n```\nLet's assume there is no other occurrence of `v` in `h`.\nThus, we have that the expected of `g x` is `StateT Nat IO ?\u03b1`,\nand the given type is `IO Nat`. So, even if we add a coercion.\n```\ninstance {\u03b1 m n} [MonadLiftT m n] {\u03b1} : Coe (m \u03b1) (n \u03b1) := ...\n```\nIt is not applicable because TC would have to assign `?\u03b1 := Nat`.\nOn the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`\nsince this goal does not contain any metavariables. And then, we\nconvert `g x` into `liftM $ g x`.\n-/\nprivate def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 instantiateMVars expectedType\n  let eType \u2190 instantiateMVars eType\n  let throwMismatch {\u03b1} : TermElabM \u03b1 := throwTypeMismatchError errorMsgHeader? expectedType eType e f?\n  let tryCoeSimple : TermElabM Expr :=\n    tryCoe errorMsgHeader? expectedType eType e f?\n  let some (n, \u03b2) \u2190 isTypeApp? expectedType | tryCoeSimple\n  let some (m, \u03b1) \u2190 isTypeApp? eType | tryCoeSimple\n  if (\u2190 isDefEq m n) then\n    let some monadInst \u2190 isMonad? n | tryCoeSimple\n    try expandCoe (\u2190 mkAppOptM ``Lean.Internal.coeM #[m, \u03b1, \u03b2, none, monadInst, e]) catch _ => throwMismatch\n  else if autoLift.get (\u2190 getOptions) then\n    try\n      -- Construct lift from `m` to `n`\n      let monadLiftType \u2190 mkAppM ``MonadLiftT #[m, n]\n      let monadLiftVal  \u2190 synthesizeInst monadLiftType\n      let u_1 \u2190 getDecLevel \u03b1\n      let u_2 \u2190 getDecLevel eType\n      let u_3 \u2190 getDecLevel expectedType\n      let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, \u03b1, e]\n      let eNewType \u2190 inferType eNew\n      if (\u2190 isDefEq expectedType eNewType) then\n        return eNew -- approach 2 worked\n      else\n        let some monadInst \u2190 isMonad? n | tryCoeSimple\n        let u \u2190 getLevel \u03b1\n        let v \u2190 getLevel \u03b2\n        let coeTInstType := Lean.mkForall `a BinderInfo.default \u03b1 $ mkAppN (mkConst ``CoeT [u, v]) #[\u03b1, mkBVar 0, \u03b2]\n        let coeTInstVal \u2190 synthesizeInst coeTInstType\n        let eNew \u2190 expandCoe (mkAppN (Lean.mkConst ``Lean.Internal.liftCoeM [u_1, u_2, u_3]) #[m, n, \u03b1, \u03b2, monadLiftVal, coeTInstVal, monadInst, e])\n        let eNewType \u2190 inferType eNew\n        unless (\u2190 isDefEq expectedType eNewType) do throwMismatch\n        return eNew -- approach 3 worked\n    catch _ =>\n      /- If `m` is not a monad, then we try to use `tryCoe?`. -/\n      tryCoeSimple\n  else\n    tryCoeSimple\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.\n  If they are not, then try coercions.\n\n  Argument `f?` is used only for generating error messages. -/\ndef ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  match expectedType? with\n  | none              => pure e\n  | some expectedType =>\n    if (\u2190 isDefEq eType expectedType) then\n      pure e\n    else\n      tryLiftAndCoe errorMsgHeader? expectedType eType e f?\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.\n  If they are not, then try coercions. -/\ndef ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=\n  match expectedType? with\n  | none => pure e\n  | _    => do\n    let eType \u2190 inferType e\n    ensureHasTypeAux expectedType? eType e none errorMsgHeader?\n\nprivate def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 match expectedType? with\n    | none              => mkFreshTypeMVar\n    | some expectedType => pure expectedType\n  mkSyntheticSorry expectedType\n\nprivate def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do\n  let syntheticSorry \u2190 mkSyntheticSorryFor expectedType?\n  logException ex\n  pure syntheticSorry\n\n/-- If `mayPostpone == true`, throw `Expection.postpone`. -/\ndef tryPostpone : TermElabM Unit := do\n  if (\u2190 read).mayPostpone then\n    throwPostpone\n\n/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/\ndef tryPostponeIfMVar (e : Expr) : TermElabM Unit := do\n  let e \u2190 whnfR e\n  if e.getAppFn.isMVar then\n    tryPostpone\n\ndef tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=\n  match e? with\n  | some e => tryPostponeIfMVar e\n  | none   => tryPostpone\n\ndef tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let some expectedType \u2190 pure expectedType? |\n    throwError \"{msg}, expected type must be known\"\n  let expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasExprMVar then\n    tryPostpone\n    throwError \"{msg}, expected type contains metavariables{indentExpr expectedType}\"\n  pure expectedType\n\ndef saveContext : TermElabM SavedContext :=\n  return {\n    macroStack := (\u2190 read).macroStack\n    declName?  := (\u2190 read).declName?\n    options    := (\u2190 getOptions)\n    openDecls  := (\u2190 getOpenDecls)\n    errToSorry := (\u2190 read).errToSorry\n  }\n\ndef withSavedContext (savedCtx : SavedContext) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|\n    withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls })\n      x\n\nprivate def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  trace[Elab.postpone] \"{stx} : {expectedType?}\"\n  let mvar \u2190 mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque\n  let ctx \u2190 read\n  registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (\u2190 saveContext))\n  pure mvar\n\ndef getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=\n  return (\u2190 get).syntheticMVars.find? fun d => d.mvarId == mvarId\n\n/--\n  Create an auxiliary annotation to make sure we create a `Info` even if `e` is a metavariable.\n  See `mkTermInfo`.\n\n  We use this functions because some elaboration functions elaborate subterms that may not be immediately\n  part of the resulting term. Example:\n  ```\n  let_mvar% ?m := b; wait_if_type_mvar% ?m; body\n  ```\n  If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just return a fresh\n  metavariable `?n`. The elaborator for\n  ```\n  let_mvar% ?m := b; wait_if_type_mvar% ?m; body\n  ```\n  returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are \"saved\".\n  This is a bit hackish, but elaborators like `let_mvar%` are rare.\n-/\ndef mkSaveInfoAnnotation (e : Expr) : Expr :=\n  if e.isMVar then\n    mkAnnotation `save_info e\n  else\n    e\n\ndef isSaveInfoAnnotation? (e : Expr) : Option Expr :=\n  annotation? `save_info e\n\npartial def removeSaveInfoAnnotation (e : Expr) : Expr :=\n  match isSaveInfoAnnotation? e with\n  | some e => removeSaveInfoAnnotation e\n  | _ => e\n\ndef mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do\n  let isHole? : TermElabM (Option MVarId) := do\n    match e with\n    | Expr.mvar mvarId _ =>\n      match (\u2190 getSyntheticMVarDecl? mvarId) with\n      | some { kind := SyntheticMVarKind.tactic .., .. }    => return mvarId\n      | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId\n      | _                                                   => return none\n    | _ => pure none\n  match (\u2190 isHole?) with\n  | some mvarId => return Sum.inr mvarId\n  | none =>\n    let e := removeSaveInfoAnnotation e\n    return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (\u2190 getLCtx), expr := e, stx, expectedType?, isBinder }\n\ndef addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do\n  withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard\n\n/-\n  Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or\n  an error is found. -/\nprivate def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)\n    : List (KeyedDeclsAttribute.AttributeEntry TermElab) \u2192 TermElabM Expr\n  | []                => do throwError \"unexpected syntax{indentD stx}\"\n  | (elabFn::elabFns) =>\n    try\n      -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`)\n      withInfoContext' (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx)\n        (try\n          elabFn.value stx expectedType?\n        catch ex => match ex with\n          | Exception.error ref msg =>\n            if (\u2190 read).errToSorry then\n              exceptionToSorry ex expectedType?\n            else\n              throw ex\n          | Exception.internal id _ =>\n            if (\u2190 read).errToSorry && id == abortTermExceptionId then\n              exceptionToSorry ex expectedType?\n            else if id == unsupportedSyntaxExceptionId then\n              throw ex  -- to outer try\n            else if catchExPostpone && id == postponeExceptionId then\n              /- If `elab` threw `Exception.postpone`, we reset any state modifications.\n                For example, we want to make sure pending synthetic metavariables created by `elab` before\n                it threw `Exception.postpone` are discarded.\n                Note that we are also discarding the messages created by `elab`.\n\n                For example, consider the expression.\n                `((f.x a1).x a2).x a3`\n                Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.\n                Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`\n                because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and\n                finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would\n                keep \"dead\" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is\n                wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch\n                and new metavariables are created for the nested functions. -/\n              s.restore\n              postponeElabTerm stx expectedType?\n            else\n              throw ex)\n    catch ex => match ex with\n      | Exception.internal id _ =>\n        if id == unsupportedSyntaxExceptionId then\n          s.restore  -- also removes the info tree created above\n          elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n        else\n          throw ex\n      | _ => throw ex\n\nprivate def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do\n  let s \u2190 saveState\n  let k := stx.getKind\n  match termElabAttribute.getEntries (\u2190 getEnv) k with\n  | []      => throwError \"elaboration function for '{k}' has not been implemented{indentD stx}\"\n  | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n\ninstance : MonadMacroAdapter TermElabM where\n  getCurrMacroScope := getCurrMacroScope\n  getNextMacroScope := return (\u2190 getThe Core.State).nextMacroScope\n  setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }\n\nprivate def isExplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(@$f) => true\n  | _      => false\n\nprivate def isExplicitApp (stx : Syntax) : Bool :=\n  stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]\n\n/--\n  Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.\n  Example: `fun {\u03b1} (a : \u03b1) => a` -/\nprivate def isLambdaWithImplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder\n  | _                         => false\n\nprivate partial def dropTermParens : Syntax \u2192 Syntax := fun stx =>\n  match stx with\n  | `(($stx)) => dropTermParens stx\n  | _         => stx\n\nprivate def isHole (stx : Syntax) : Bool :=\n  match stx with\n  | `(_)          => true\n  | `(? _)        => true\n  | `(? $x:ident) => true\n  | _             => false\n\nprivate def isTacticBlock (stx : Syntax) : Bool :=\n  match stx with\n  | `(by $x:tacticSeq) => true\n  | _ => false\n\nprivate def isNoImplicitLambda (stx : Syntax) : Bool :=\n  match stx with\n  | `(no_implicit_lambda% $x:term) => true\n  | _ => false\n\nprivate def isTypeAscription (stx : Syntax) : Bool :=\n  match stx with\n  | `(($e : $type)) => true\n  | _               => false\n\ndef mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=\n  mkAnnotation `noImplicitLambda type\n\ndef hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=\n  annotation? `noImplicitLambda type |>.isSome\n\n/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/\ndef blockImplicitLambda (stx : Syntax) : Bool :=\n  let stx := dropTermParens stx\n  -- TODO: make it extensible\n  isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||\n  isNoImplicitLambda stx || isTypeAscription stx\n\n/--\n  Return normalized expected type if it is of the form `{a : \u03b1} \u2192 \u03b2` or `[a : \u03b1] \u2192 \u03b2` and\n  `blockImplicitLambda stx` is not true, else return `none`.\n\n  Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : \u03b1}} \u2192 \u03b2`\n-/\nprivate def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=\n  if blockImplicitLambda stx then\n    return none\n  else match expectedType? with\n    | some expectedType => do\n      if hasNoImplicitLambdaAnnotation expectedType then\n        return none\n      else\n        let expectedType \u2190 whnfForall expectedType\n        match expectedType with\n        | Expr.forallE _ _ _ c =>\n          if c.binderInfo.isImplicit || c.binderInfo.isInstImplicit then\n            return some expectedType\n          else\n            return none\n        | _ => return none\n    | _ => return none\n\nprivate def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do\n  match ex with\n  | Exception.error ref msg =>\n    if impFVars.isEmpty then\n      return Exception.error ref msg\n    else\n      let mut msg := m!\"{msg}\\nthe following variables have been introduced by the implicit lamda feature\"\n      for impFVar in impFVars do\n        let auxMsg := m!\"{impFVar} : {\u2190 inferType impFVar}\"\n        let auxMsg \u2190 addMessageContext auxMsg\n        msg := m!\"{msg}{indentD auxMsg}\"\n      msg := m!\"{msg}\\nyou can disable implict lambdas using `@` or writing a lambda expression with `\\{}` or `[]` binder annotations.\"\n      return Exception.error ref msg\n  | _ => return ex\n\nprivate def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do\n  let body \u2190 elabUsingElabFns stx expectedType catchExPostpone\n  try\n    let body \u2190 ensureHasType expectedType body\n    let r \u2190 mkLambdaFVars impFVars body\n    trace[Elab.implicitForall] r\n    pure r\n  catch ex =>\n    throw (\u2190 decorateErrorMessageWithLambdaImplicitVars ex impFVars)\n\nprivate partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=\n  loop type #[]\nwhere\n  loop\n    | type@(Expr.forallE n d b c), fvars =>\n      if c.binderInfo.isExplicit then\n        elabImplicitLambdaAux stx catchExPostpone type fvars\n      else withFreshMacroScope do\n        let n \u2190 MonadQuotation.addMacroScope n\n        withLocalDecl n c.binderInfo d fun fvar => do\n          let type \u2190 whnfForall (b.instantiate1 fvar)\n          loop type (fvars.push fvar)\n    | type, fvars =>\n      elabImplicitLambdaAux stx catchExPostpone type fvars\n\n/- Main loop for `elabTerm` -/\nprivate partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax \u2192 TermElabM Expr\n  | Syntax.missing => mkSyntheticSorryFor expectedType?\n  | stx => withFreshMacroScope <| withIncRecDepth do\n    trace[Elab.step] \"expected type: {expectedType?}, term\\n{stx}\"\n    checkMaxHeartbeats \"elaborator\"\n    withNestedTraces do\n    let env \u2190 getEnv\n    match (\u2190 liftMacroM (expandMacroImpl? env stx)) with\n    | some (decl, stxNew?) =>\n      let stxNew \u2190 liftMacroM <| liftExcept stxNew?\n      withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <|\n        withMacroExpansion stx stxNew <|\n          withRef stxNew <|\n            elabTermAux expectedType? catchExPostpone implicitLambda stxNew\n    | _ =>\n      let implicit? \u2190 if implicitLambda && (\u2190 read).implicitLambda then useImplicitLambda? stx expectedType? else pure none\n      match implicit? with\n      | some expectedType => elabImplicitLambda stx catchExPostpone expectedType\n      | none              => elabUsingElabFns stx expectedType? catchExPostpone\n\n/-- Store in the `InfoTree` that `e` is a \"dot\"-completion target. -/\ndef addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do\n  addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (\u2190 getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?)\n\n/--\n  Main function for elaborating terms.\n  It extracts the elaboration methods from the environment using the node kind.\n  Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.\n  It creates a fresh macro scope for executing the elaboration method.\n  All unlogged trace messages produced by the elaboration method are logged using\n  the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,\n  the error is logged and a synthetic sorry expression is returned.\n  If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,\n  a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,\n  and returned.\n  The option `catchExPostpone == false` is used to implement `resumeElabTerm`\n  to prevent the creation of another synthetic metavariable when resuming the elaboration.\n\n  If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.\n  We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.\n  -/\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=\n  withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  let e \u2190 elabTerm stx expectedType? catchExPostpone implicitLambda\n  withRef stx <| ensureHasType expectedType? e errorMsgHeader?\n\n/--\n  Execute `x` and then restore `syntheticMVars`, `levelNames`, `mvarErrorInfos`, and `letRecsToLift`.\n  We use this combinator when we don't want the pending problems created by `x` to persist after its execution. -/\ndef withoutPending (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let saved \u2190 get\n  try\n    x\n  finally\n    modify fun s => { s with syntheticMVars := saved.syntheticMVars, levelNames := saved.levelNames,\n                             letRecsToLift := saved.letRecsToLift, mvarErrorInfos := saved.mvarErrorInfos }\n\n/-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/\ndef commitIfNoErrors? (x : TermElabM \u03b1) : TermElabM (Option \u03b1) := do\n  let saved \u2190 saveState\n  modify fun s => { s with messages := {} }\n  try\n    let a \u2190 x\n    if (\u2190 get).messages.hasErrors then\n      restoreState saved\n      return none\n    else\n      modify fun s => { s with messages := saved.elab.messages ++ s.messages }\n      return a\n  catch _ =>\n    restoreState saved\n    return none\n\n/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/\ndef adaptExpander (exp : Syntax \u2192 TermElabM Syntax) : TermElab := fun stx expectedType? => do\n  let stx' \u2190 exp stx\n  withMacroExpansion stx stx' $ elabTerm stx' expectedType?\n\ndef mkInstMVar (type : Expr) : TermElabM Expr := do\n  let mvar \u2190 mkFreshExprMVar type MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  unless (\u2190 synthesizeInstMVarCore mvarId) do\n    registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass\n  pure mvar\n\n/-\n  Relevant definitions:\n  ```\n  class CoeSort (\u03b1 : Sort u) (\u03b2 : outParam (Sort v))\n  ```\n  -/\nprivate def tryCoeSort (\u03b1 : Expr) (a : Expr) : TermElabM Expr := do\n  let \u03b2 \u2190 mkFreshTypeMVar\n  let u \u2190 getLevel \u03b1\n  let v \u2190 getLevel \u03b2\n  let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[\u03b1, \u03b2]\n  let mvar \u2190 mkFreshExprMVar coeSortInstType MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  try\n    withoutMacroStackAtErr do\n      if (\u2190 synthesizeCoeInstMVarCore mvarId) then\n        let result \u2190 expandCoe <| mkAppN (Lean.mkConst ``CoeSort.coe [u, v]) #[\u03b1, \u03b2, mvar, a]\n        unless (\u2190 isType result) do\n          throwError \"failed to coerse{indentExpr a}\\nto a type, after applying `CoeSort.coe`, result is still not a type{indentExpr result}\\nthis is often due to incorrect `CoeSort` instances, the synthesized value for{indentExpr coeSortInstType}\\nwas{indentExpr mvar}\"\n        return result\n      else\n        throwError \"type expected\"\n  catch\n    | Exception.error _ msg => throwError \"type expected\\n{msg}\"\n    | _                     => throwError \"type expected\"\n\n/--\n  Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`\n  or is unifiable with `Expr.sort`, or can be coerced into one. -/\ndef ensureType (e : Expr) : TermElabM Expr := do\n  if (\u2190 isType e) then\n    pure e\n  else\n    let eType \u2190 inferType e\n    let u \u2190 mkFreshLevelMVar\n    if (\u2190 isDefEq eType (mkSort u)) then\n      pure e\n    else\n      tryCoeSort eType e\n\n/-- Elaborate `stx` and ensure result is a type. -/\ndef elabType (stx : Syntax) : TermElabM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  let type \u2190 elabTerm stx (mkSort u)\n  withRef stx $ ensureType type\n\n/--\n  Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,\n  a new local declaration is created, registered, and `k` is tried to be executed again. -/\npartial def withAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let flag := autoBoundImplicitLocal.get (\u2190 getOptions)\n  if flag then\n    withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do\n      let rec loop (s : SavedState) : TermElabM \u03b1 := do\n        try\n          k\n        catch\n          | ex => match isAutoBoundImplicitLocalException? ex with\n            | some n =>\n              -- Restore state, declare `n`, and try again\n              s.restore\n              withLocalDecl n BinderInfo.implicit (\u2190 mkFreshTypeMVar) fun x =>\n                withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do\n                  loop (\u2190 saveState)\n            | none   => throw ex\n      loop (\u2190 saveState)\n  else\n    k\n\ndef withoutAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k\n\n/--\n  Return `autoBoundImplicits ++ xs.\n  This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/\ndef addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do\n  let autoBoundImplicits := (\u2190 read).autoBoundImplicits\n  for auto in autoBoundImplicits do\n    let localDecl \u2190 getLocalDecl auto.fvarId!\n    for x in xs do\n      if (\u2190 getMCtx).localDeclDependsOn localDecl x.fvarId! then\n        throwError \"invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'\"\n  return autoBoundImplicits.toArray ++ xs\n\ndef mkAuxName (suffix : Name) : TermElabM Name := do\n  match (\u2190 read).declName? with\n  | none          => throwError \"auxiliary declaration cannot be created when declaration name is not available\"\n  | some declName => Lean.mkAuxName (declName ++ suffix) 1\n\nbuiltin_initialize registerTraceClass `Elab.letrec\n\n/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it\n   is delayed assigned to one. -/\ndef isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do\n  trace[Elab.letrec] \"mvarId: {mkMVar mvarId} letrecMVars: {(\u2190 get).letRecsToLift.map (mkMVar $ \u00b7.mvarId)}\"\n  let mvarId := (\u2190 getMCtx).getDelayedRoot mvarId\n  trace[Elab.letrec] \"mvarId root: {mkMVar mvarId}\"\n  return (\u2190 get).letRecsToLift.any (\u00b7.mvarId == mvarId)\n\ndef resolveLocalName (n : Name) : TermElabM (Option (Expr \u00d7 List String)) := do\n  let lctx \u2190 getLCtx\n  let view := extractMacroScopes n\n  let rec loop (n : Name) (projs : List String) :=\n    match lctx.findFromUserName? { view with name := n }.review with\n    | some decl =>\n      if decl.isAuxDecl && !projs.isEmpty then\n        /- We do not consider dot notation for local decls corresponding to recursive functions being defined.\n           The following example would not be elaborated correctly without this case.\n           ```\n            def foo.aux := 1\n            def foo : Nat \u2192 Nat\n              | n => foo.aux -- should not be interpreted as `(foo).bar`\n           ```\n         -/\n        none\n      else\n        some (decl.toExpr, projs)\n    | none      => match n with\n      | Name.str pre s _ => loop pre (s::projs)\n      | _                => none\n  return loop view.name []\n\n/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/\ndef isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val _ => do\n    let r? \u2190 resolveLocalName val\n    match r? with\n    | some (fvar, []) => pure (some fvar)\n    | _               => pure none\n  | _ => pure none\n\n/--\n  Create an `Expr.const` using the given name and explicit levels.\n  Remark: fresh universe metavariables are created if the constant has more universe\n  parameters than `explicitLevels`. -/\ndef mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do\n  let cinfo \u2190 getConstInfo constName\n  if explicitLevels.length > cinfo.levelParams.length then\n    throwError \"too many explicit universe levels for '{constName}'\"\n  else\n    let numMissingLevels := cinfo.levelParams.length - explicitLevels.length\n    let us \u2190 mkFreshLevelMVars numMissingLevels\n    return Lean.mkConst constName (explicitLevels ++ us)\n\nprivate def mkConsts (candidates : List (Name \u00d7 List String)) (explicitLevels : List Level) : TermElabM (List (Expr \u00d7 List String)) := do\n  candidates.foldlM (init := []) fun result (constName, projs) => do\n    -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.\n   let const \u2190 mkConst constName explicitLevels\n   return (const, projs) :: result\n\ndef resolveName (stx : Syntax) (n : Name) (preresolved : List (Name \u00d7 List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 List String)) := do\n  try\n    if let some (e, projs) \u2190 resolveLocalName n then\n      unless explicitLevels.isEmpty do\n        throwError \"invalid use of explicit universe parameters, '{e}' is a local\"\n      return [(e, projs)]\n    -- check for section variable capture by a quotation\n    let ctx \u2190 read\n    if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (\u00b7, projs) then\n      return [(e, projs)]  -- section variables should shadow global decls\n    if preresolved.isEmpty then\n      process (\u2190 resolveGlobalName n)\n    else\n      process preresolved\n  catch ex =>\n    if preresolved.isEmpty && explicitLevels.isEmpty then\n      addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n    throw ex\nwhere process (candidates : List (Name \u00d7 List String)) : TermElabM (List (Expr \u00d7 List String)) := do\n  if candidates.isEmpty then\n    if (\u2190 read).autoBoundImplicit && isValidAutoBoundImplicitName n then\n      throwAutoBoundImplicitLocal n\n    else\n      throwError \"unknown identifier '{Lean.mkConst n}'\"\n  if preresolved.isEmpty && explicitLevels.isEmpty then\n    addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n  mkConsts candidates explicitLevels\n\n/--\n  Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.\n  Example: Assume resolveName `v.head.bla.boo` produces `(v.head, [\"bla\", \"boo\"])`, then this method produces\n  `(v.head, id, [f\u2081, f\u2082])` where `id` is an identifier for `v.head`, and `f\u2081` and `f\u2082` are identifiers for fields `\"bla\"` and `\"boo\"`. -/\ndef resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 Syntax \u00d7 List Syntax)) := do\n  match ident with\n  | Syntax.ident info rawStr n preresolved =>\n    let r \u2190 resolveName ident n preresolved explicitLevels expectedType?\n    r.mapM fun (c, fields) => do\n      let ids := ident.identComponents (nFields? := fields.length)\n      return (c, ids.head!, ids.tail!)\n  | _ => throwError \"identifier expected\"\n\ndef resolveId? (stx : Syntax) (kind := \"term\") (withInfo := false) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val preresolved => do\n    let rs \u2190 try resolveName stx val preresolved [] catch _ => pure []\n    let rs := rs.filter fun \u27e8f, projs\u27e9 => projs.isEmpty\n    let fs := rs.map fun (f, _) => f\n    match fs with\n    | []  => pure none\n    | [f] =>\n      if withInfo then\n        addTermInfo stx f\n      pure (some f)\n    | _   => throwError \"ambiguous {kind}, use fully qualified name, possible interpretations {fs}\"\n  | _ => throwError \"identifier expected\"\n\nprivate def mkSomeContext : Context := {\n  fileName      := \"<TermElabM>\"\n  fileMap       := default\n}\n\ndef TermElabM.run (x : TermElabM \u03b1) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (\u03b1 \u00d7 State) :=\n  withConfig setElabConfig (x ctx |>.run s)\n\n@[inline] def TermElabM.run' (x : TermElabM \u03b1) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM \u03b1 :=\n  (\u00b7.1) <$> x.run ctx s\n\ndef TermElabM.toIO (x : TermElabM \u03b1)\n    (ctxCore : Core.Context) (sCore : Core.State)\n    (ctxMeta : Meta.Context) (sMeta : Meta.State)\n    (ctx : Context) (s : State) : IO (\u03b1 \u00d7 Core.State \u00d7 Meta.State \u00d7 State) := do\n  let ((a, s), sCore, sMeta) \u2190 (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta\n  pure (a, sCore, sMeta, s)\n\ninstance [MetaEval \u03b1] : MetaEval (TermElabM \u03b1) where\n  eval env opts x _ :=\n    let x : TermElabM \u03b1 := do\n      try x finally\n        let s \u2190 get\n        s.messages.forM fun msg => do IO.println (\u2190 msg.toString)\n    MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext\n\nunsafe def evalExpr (\u03b1) (typeName : Name) (value : Expr) : TermElabM \u03b1 :=\n  withoutModifyingEnv do\n    let name \u2190 mkFreshUserName `_tmp\n    let type \u2190 inferType value\n    let type \u2190 whnfD type\n    unless type.isConstOf typeName do\n      throwError \"unexpected type at evalExpr{indentExpr type}\"\n    let decl := Declaration.defnDecl {\n       name := name, levelParams := [], type := type,\n       value := value, hints := ReducibilityHints.opaque,\n       safety := DefinitionSafety.unsafe\n    }\n    ensureNoUnassignedMVars decl\n    addAndCompile decl\n    evalConst \u03b1 name\n\nprivate def throwStuckAtUniverseCnstr : TermElabM Unit := do\n  -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property\n  let entries \u2190 getPostponed\n  let mut found : Std.HashSet (Level \u00d7 Level) := {}\n  let mut uniqueEntries := #[]\n  for entry in entries do\n    let mut lhs := entry.lhs\n    let mut rhs := entry.rhs\n    if Level.normLt rhs lhs then\n      (lhs, rhs) := (rhs, lhs)\n    unless found.contains (lhs, rhs) do\n      found := found.insert (lhs, rhs)\n      uniqueEntries := uniqueEntries.push entry\n  for i in [1:uniqueEntries.size] do\n    logErrorAt uniqueEntries[i].ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[i])\n  throwErrorAt uniqueEntries[0].ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[0])\n\ndef withoutPostponingUniverseConstraints (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let postponed \u2190 getResetPostponed\n  try\n    let a \u2190 x\n    unless (\u2190 processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do\n      throwStuckAtUniverseCnstr\n    setPostponed postponed\n    return a\n  catch ex =>\n    setPostponed postponed\n    throw ex\n\ndef expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : TermElabM ExpandDeclIdResult := do\n  let r \u2190 Elab.expandDeclId currNamespace currLevelNames declId modifiers\n  if (\u2190 read).sectionVars.contains r.shortName then\n    throwError \"invalid declaration name '{r.shortName}', there is a section variable with the same name\"\n  return r\n\nend Term\n\nopen Term in\ndef withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m \u03b1) : m \u03b1 := do\n  controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x\n\nbuiltin_initialize\n  registerTraceClass `Elab.postpone\n  registerTraceClass `Elab.coe\n  registerTraceClass `Elab.debug\n\nexport Term (TermElabM)\n\nend Lean.Elab\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/Elab/Term.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436781101874467, "lm_q2_score": 0.028007522938509034, "lm_q1q2_score": 0.00544376092561528}}
{"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.UnifyEq\nimport Lean.Meta.Tactic.Simp.Rewrite\n\nnamespace Lean.Meta\nnamespace Simp\n\nbuiltin_initialize congrHypothesisExceptionId : InternalExceptionId \u2190\n  registerInternalExceptionId `congrHypothesisFailed\n\ndef throwCongrHypothesisFailed : MetaM \u03b1 :=\n  throw <| Exception.internal congrHypothesisExceptionId\n\n/--\n  Helper method for bootstrapping purposes. It disables `arith` if support theorems have not been defined yet.\n-/\ndef Config.updateArith (c : Config) : CoreM Config := do\n  if c.arith then\n    if (\u2190 getEnv).contains ``Nat.Linear.ExprCnstr.eq_of_toNormPoly_eq then\n      return c\n    else\n      return { c with arith := false }\n  else\n    return c\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\n/--\n  Similar to `Result.getProof`, but adds a `mkExpectedTypeHint` if `proof?` is `none`\n  (i.e., result is definitionally equal to input), but we cannot establish that\n  `source` and `r.expr` are definitionally when using `TransparencyMode.reducible`. -/\ndef Result.getProof' (source : Expr) (r : Result) : MetaM Expr := do\n  match r.proof? with\n  | some p => return p\n  | none   =>\n    if (\u2190 isDefEq source r.expr) then\n      mkEqRefl r.expr\n    else\n      /- `source` and `r.expr` must be definitionally equal, but\n         are not definitionally equal at `TransparencyMode.reducible` -/\n      mkExpectedTypeHint (\u2190 mkEqRefl r.expr) (\u2190 mkEq source r.expr)\n\ndef 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? := (\u2190 Meta.mkCongrFun h a) }\n\ndef mkCongr (r\u2081 r\u2082 : Result) : MetaM Result :=\n  let e := mkApp r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | some h,  none    => return { expr := e, proof? := (\u2190 Meta.mkCongrFun h r\u2082.expr) }\n  | none,    some h  => return { expr := e, proof? := (\u2190 Meta.mkCongrArg r\u2081.expr h) }\n  | some h\u2081, some h\u2082 => return { expr := e, proof? := (\u2190 Meta.mkCongr h\u2081 h\u2082) }\n\nprivate def mkImpCongr (src : Expr) (r\u2081 r\u2082 : Result) : MetaM Result := do\n  let e := src.updateForallE! r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | _,        _      => return { expr := e, proof? := (\u2190 Meta.mkImpCongr (\u2190 r\u2081.getProof) (\u2190 r\u2082.getProof)) } -- TODO specialize if bootleneck\n\n/-- Return true if `e` is of the form `ofNat n` where `n` is a kernel Nat literal -/\ndef isOfNatNatLit (e : Expr) : Bool :=\n  e.isAppOfArity ``OfNat.ofNat 3 && e.appFn!.appArg!.isNatLit\n\nprivate def reduceProj (e : Expr) : MetaM Expr := do\n  match (\u2190 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 (\u2190 getProjectionFnInfo? cinfo.name) with\n    | none => return none\n    | some projInfo =>\n      /- Helper function for applying `reduceProj?` to the result of `unfoldDefinition?` -/\n      let reduceProjCont? (e? : Option Expr) : SimpM (Option Expr) := do\n        match e? with\n        | none   => pure none\n        | some e =>\n          match (\u2190 reduceProj? e.getAppFn) with\n          | some f => return some (mkAppN f e.getAppArgs)\n          | none   => return none\n      if projInfo.fromClass then\n        -- `class` projection\n        if (\u2190 read).isDeclToUnfold cinfo.name then\n          /-\n          If user requested `class` projection to be unfolded, we set transparency mode to `.instances`,\n          and invoke `unfoldDefinition?`.\n          Recall that `unfoldDefinition?` has support for unfolding this kind of projection when transparency mode is `.instances`.\n          -/\n          withReducibleAndInstances <| unfoldDefinition? e\n        else\n          /-\n          Recall that class projections are **not** marked with `[reducible]` because we want them to be\n          in \"reducible canonical form\". However, if we have a class projection of the form `Class.projFn (Class.mk ...)`,\n          we want to reduce it. See issue #1869 for an example where this is important.\n          -/\n          unless e.getAppNumArgs > projInfo.numParams do\n            return none\n          let major := e.getArg! projInfo.numParams\n          unless major.isConstructorApp (\u2190 getEnv) do\n            return none\n          reduceProjCont? (\u2190 withDefault <| unfoldDefinition? e)\n      else\n        -- `structure` projections\n        reduceProjCont? (\u2190 unfoldDefinition? e)\n\nprivate def reduceFVar (cfg : Config) (e : Expr) : MetaM Expr := do\n  if cfg.zeta then\n    match (\u2190 getFVarLocalDecl e).value? with\n    | some v => return v\n    | none   => return e\n  else\n    return e\n\n/--\n  Return true if `declName` is the name of a definition of the form\n  ```\n  def declName ... :=\n    match ... with\n    | ...\n  ```\n-/\nprivate partial def isMatchDef (declName : Name) : CoreM Bool := do\n  let .defnInfo info \u2190 getConstInfo declName | return false\n  return go (\u2190 getEnv) info.value\nwhere\n  go (env : Environment) (e : Expr) : Bool :=\n    if e.isLambda then\n      go env e.bindingBody!\n    else\n      let f := e.getAppFn\n      f.isConst && isMatcherCore env f.constName!\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 (\u2190 isProjectionFn fName) then\n    return none -- should be reduced by `reduceProjFn?`\n  let ctx \u2190 read\n  if ctx.config.autoUnfold then\n    if ctx.simpTheorems.isErased (.decl fName) then\n      return none\n    else if hasSmartUnfoldingDecl (\u2190 getEnv) fName then\n      withDefault <| unfoldDefinition? e\n    else if (\u2190 isMatchDef fName) then\n      let some value \u2190 withDefault <| unfoldDefinition? e | return none\n      let .reduced value \u2190 reduceMatcher? value | return none\n      return some value\n    else\n      return none\n  else if ctx.isDeclToUnfold fName then\n    withDefault <| unfoldDefinition? e\n  else\n    return none\n\nprivate partial def reduce (e : Expr) : SimpM Expr := withIncRecDepth do\n  let cfg := (\u2190 read).config\n  if e.getAppFn.isMVar then\n    let e' \u2190 instantiateMVars e\n    if e' != e then\n      return (\u2190 reduce e')\n  if cfg.beta then\n    let e' := e.headBeta\n    if e' != e then\n      return (\u2190 reduce e')\n  -- TODO: eta reduction\n  if cfg.proj then\n    match (\u2190 reduceProjFn? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  if cfg.iota then\n    match (\u2190 reduceRecMatcher? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  match (\u2190 unfold? e) with\n  | some e' =>\n    trace[Meta.Tactic.simp.rewrite] \"unfold {mkConst e.getAppFn.constName!}, {e} ==> {e'}\"\n    recordSimpTheorem (.decl e.getAppFn.constName!)\n    reduce e'\n  | none => return e\n\nprivate partial def dsimp (e : Expr) : M Expr := do\n  let cfg \u2190 getConfig\n  unless cfg.dsimp do\n    return e\n  let pre (e : Expr) : M TransformStep := do\n    if let Step.visit r \u2190 rewritePre e (fun _ => pure none) (rflOnly := true) then\n      if r.expr != e then\n        return .visit r.expr\n    return .continue\n  let post (e : Expr) : M TransformStep := do\n    if let Step.visit r \u2190 rewritePost e (fun _ => pure none) (rflOnly := true) then\n      if r.expr != e then\n        return .visit r.expr\n    let mut eNew \u2190 reduce e\n    if cfg.zeta && eNew.isFVar then\n      eNew \u2190 reduceFVar cfg eNew\n    if eNew != e then return .visit eNew else return .done e\n  transform (usedLetOnly := cfg.zeta) e (pre := pre) (post := post)\n\ninstance : Inhabited (M \u03b1) where\n  default := fun _ _ _ => default\n\npartial def lambdaTelescopeDSimp (e : Expr) (k : Array Expr \u2192 Expr \u2192 M \u03b1) : M \u03b1 := do\n  go #[] e\nwhere\n  go (xs : Array Expr) (e : Expr) : M \u03b1 := do\n    match e with\n    | .lam n d b c => withLocalDecl n c (\u2190 dsimp d) fun x => go (xs.push x) (b.instantiate1 x)\n    | e => k xs e\n\ninductive SimpLetCase where\n  | dep -- `let x := v; b` is not equivalent to `(fun x => b) v`\n  | nondepDepVar -- `let x := v; b` is equivalent to `(fun x => b) v`, but result type depends on `x`\n  | nondep -- `let x := v; b` is equivalent to `(fun x => b) v`, and result type does not depend on `x`\n\ndef getSimpLetCase (n : Name) (t : Expr) (b : Expr) : MetaM SimpLetCase := do\n  withLocalDeclD n t fun x => do\n    let bx := b.instantiate1 x\n    /- The following step is potentially very expensive when we have many nested let-decls.\n       TODO: handle a block of nested let decls in a single pass if this becomes a performance problem. -/\n    if (\u2190 isTypeCorrect bx) then\n      let bxType \u2190 whnf (\u2190 inferType bx)\n      if (\u2190 dependsOn bxType x.fvarId!) then\n        return SimpLetCase.nondepDepVar\n      else\n        return SimpLetCase.nondep\n    else\n      return SimpLetCase.dep\n\n/-- Given the application `e`, remove unnecessary casts of the form `Eq.rec a rfl` and `Eq.ndrec a rfl`. -/\npartial def removeUnnecessaryCasts (e : Expr) : MetaM Expr := do\n  let mut args := e.getAppArgs\n  let mut modified := false\n  for i in [:args.size] do\n    let arg := args[i]!\n    if isDummyEqRec arg then\n      args := args.set! i (elimDummyEqRec arg)\n      modified := true\n  if modified then\n    return mkAppN e.getAppFn args\n  else\n    return e\nwhere\n  isDummyEqRec (e : Expr) : Bool :=\n    (e.isAppOfArity ``Eq.rec 6 || e.isAppOfArity ``Eq.ndrec 6) && e.appArg!.isAppOf ``Eq.refl\n\n  elimDummyEqRec (e : Expr) : Expr :=\n    if isDummyEqRec e then\n      elimDummyEqRec e.appFn!.appFn!.appArg!\n    else\n      e\n\npartial def simp (e : Expr) : M Result := withIncRecDepth do\n  checkMaxHeartbeats \"simp\"\n  let cfg \u2190 getConfig\n  if (\u2190 isProof e) then\n    return { expr := e }\n  if cfg.memoize then\n    if let some result := (\u2190 get).cache.find? e then\n      /-\n         If the result was cached at a dischargeDepth > the current one, it may not be valid.\n         See issue #1234\n      -/\n      if result.dischargeDepth \u2264 (\u2190 readThe Simp.Context).dischargeDepth then\n        return result\n  trace[Meta.Tactic.simp.heads] \"{repr e.toHeadIndex}\"\n  simpLoop { expr := e }\n\nwhere\n  simpLoop (r : Result) : M Result := do\n    let cfg \u2190 getConfig\n    if (\u2190 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 (\u2190 pre r.expr) with\n      | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n      | Step.visit r' =>\n        let r \u2190 mkEqTrans r r'\n        let r \u2190 mkEqTrans r (\u2190 simpStep r.expr)\n        match (\u2190 post r.expr) with\n        | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n        | Step.visit r' =>\n          let r \u2190 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 m e   => let r \u2190 simp e; return { r with expr := mkMData m r.expr }\n    | Expr.proj ..     => simpProj 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 ..     => return { expr := e }\n    | Expr.lit ..      => simpLit e\n    | Expr.mvar ..     => return { expr := (\u2190 instantiateMVars e) }\n    | Expr.fvar ..     => return { expr := (\u2190 reduceFVar (\u2190 getConfig) e) }\n\n  simpLit (e : Expr) : M Result := do\n    match e.natLit? with\n    | some n =>\n      /- If `OfNat.ofNat` is marked to be unfolded, we do not pack orphan nat literals as `OfNat.ofNat` applications\n         to avoid non-termination. See issue #788.  -/\n      if (\u2190 readThe Simp.Context).isDeclToUnfold ``OfNat.ofNat then\n        return { expr := e }\n      else\n        return { expr := (\u2190 mkNumeral (mkConst ``Nat) n) }\n    | none   => return { expr := e }\n\n  simpProj (e : Expr) : M Result := do\n    match (\u2190 reduceProj? e) with\n    | some e => return { expr := e }\n    | none =>\n      let s := e.projExpr!\n      let motive? \u2190 withLocalDeclD `s (\u2190 inferType s) fun s => do\n        let p := e.updateProj! s\n        if (\u2190 dependsOn (\u2190 inferType p) s.fvarId!) then\n          return none\n        else\n          let motive \u2190 mkLambdaFVars #[s] (\u2190 mkEq e p)\n          if !(\u2190 isTypeCorrect motive) then\n            return none\n          else\n            return some motive\n      if let some motive := motive? then\n        let r \u2190 simp s\n        let eNew := e.updateProj! r.expr\n        match r.proof? with\n        | none => return { expr := eNew }\n        | some h =>\n          let hNew \u2190 mkEqNDRec motive (\u2190 mkEqRefl e) h\n          return { expr := eNew, proof? := some hNew }\n      else\n        return { expr := (\u2190 dsimp e) }\n\n  congrArgs (r : Result) (args : Array Expr) : M Result := do\n    if args.isEmpty then\n      return r\n    else\n      let infos := (\u2190 getFunInfoNArgs r.expr args.size).paramInfo\n      let mut r := r\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 \u2190 mkCongr r (\u2190 simp arg)\n        else if (\u2190 whnfD (\u2190 inferType r.expr)).isArrow then\n          r \u2190 mkCongr r (\u2190 simp arg)\n        else\n          r \u2190 mkCongrFun r (\u2190 dsimp arg)\n        i := i + 1\n      return r\n\n  visitFn (e : Expr) : M Result := do\n    let f := e.getAppFn\n    let fNew \u2190 simp f\n    if fNew.expr == f then\n      return { expr := e }\n    else\n      let args := e.getAppArgs\n      let eNew := mkAppN fNew.expr args\n      if fNew.proof?.isNone then return { expr := eNew }\n      let mut proof \u2190 fNew.getProof\n      for arg in args do\n        proof \u2190 Meta.mkCongrFun proof arg\n      return { expr := eNew, proof? := proof }\n\n  mkCongrSimp? (f : Expr) : M (Option CongrTheorem) := do\n    if f.isConst then if (\u2190 isMatcher f.constName!) then\n      -- We always use simple congruence theorems for auxiliary match applications\n      return none\n    let info \u2190 getFunInfo f\n    let kinds \u2190 getCongrSimpKinds f info\n    if kinds.all fun k => match k with | CongrArgKind.fixed => true | CongrArgKind.eq => true | _ => false then\n      /- If all argument kinds are `fixed` or `eq`, then using\n         simple congruence theorems `congr`, `congrArg`, and `congrFun` produces a more compact proof -/\n      return none\n    match (\u2190 get).congrCache.find? f with\n    | some thm? => return thm?\n    | none =>\n      let thm? \u2190 mkCongrSimpCore? f info kinds\n      modify fun s => { s with congrCache := s.congrCache.insert f thm? }\n      return thm?\n\n  /-- Try to use automatically generated congruence theorems. See `mkCongrSimp?`. -/\n  tryAutoCongrTheorem? (e : Expr) : M (Option Result) := do\n    let f := e.getAppFn\n    -- TODO: cache\n    let some cgrThm \u2190 mkCongrSimp? f | return none\n    if cgrThm.argKinds.size != e.getAppNumArgs then return none\n    let mut simplified := false\n    let mut hasProof   := false\n    let mut hasCast    := false\n    let mut argsNew    := #[]\n    let mut argResults := #[]\n    let args := e.getAppArgs\n    for arg in args, kind in cgrThm.argKinds do\n      match kind with\n      | CongrArgKind.fixed => argsNew := argsNew.push (\u2190 dsimp arg)\n      | CongrArgKind.cast  => hasCast := true; argsNew := argsNew.push arg\n      | CongrArgKind.subsingletonInst => argsNew := argsNew.push arg\n      | CongrArgKind.eq =>\n        let argResult \u2190 simp arg\n        argResults := argResults.push argResult\n        argsNew    := argsNew.push argResult.expr\n        if argResult.proof?.isSome then hasProof := true\n        if arg != argResult.expr then simplified := true\n      | _ => unreachable!\n    if !simplified then return some { expr := e }\n    /-\n      If `hasProof` is false, we used to return `mkAppN f argsNew` with `proof? := none`.\n      However, this created a regression when we started using `proof? := none` for `rfl` theorems.\n      Consider the following goal\n      ```\n      m n : Nat\n      a : Fin n\n      h\u2081 : m < n\n      h\u2082 : Nat.pred (Nat.succ m) < n\n      \u22a2 Fin.succ (Fin.mk m h\u2081) = Fin.succ (Fin.mk m.succ.pred h\u2082)\n      ```\n      The term `m.succ.pred` is simplified to `m` using a `Nat.pred_succ` which is a `rfl` theorem.\n      The auto generated theorem for `Fin.mk` has casts and if used here at `Fin.mk m.succ.pred h\u2082`,\n      it produces the term `Fin.mk m (id (Eq.refl m) \u25b8 h\u2082)`. The key property here is that the\n      proof `(id (Eq.refl m) \u25b8 h\u2082)` has type `m < n`. If we had just returned `mkAppN f argsNew`,\n      the resulting term would be `Fin.mk m h\u2082` which is type correct, but later we would not be\n      able to apply `eq_self` to\n      ```lean\n      Fin.succ (Fin.mk m h\u2081) = Fin.succ (Fin.mk m h\u2082)\n      ```\n      because we would not be able to establish that `m < n` and `Nat.pred (Nat.succ m) < n` are definitionally\n      equal using `TransparencyMode.reducible` (`Nat.pred` is not reducible).\n      Thus, we decided to return here only if the auto generated congruence theorem does not introduce casts.\n    -/\n    if !hasProof && !hasCast then return some { expr := mkAppN f argsNew }\n    let mut proof := cgrThm.proof\n    let mut type  := cgrThm.type\n    let mut j := 0 -- index at argResults\n    let mut subst := #[]\n    for arg in args, kind in cgrThm.argKinds do\n      proof := mkApp proof arg\n      subst := subst.push arg\n      type := type.bindingBody!\n      match kind with\n      | CongrArgKind.fixed => pure ()\n      | CongrArgKind.cast  => pure ()\n      | CongrArgKind.subsingletonInst =>\n        let clsNew := type.bindingDomain!.instantiateRev subst\n        let instNew \u2190 if (\u2190 isDefEq (\u2190 inferType arg) clsNew) then\n          pure arg\n        else\n          match (\u2190 trySynthInstance clsNew) with\n          | LOption.some val => pure val\n          | _ =>\n            trace[Meta.Tactic.simp.congr] \"failed to synthesize instance{indentExpr clsNew}\"\n            return none\n        proof := mkApp proof instNew\n        subst := subst.push instNew\n        type := type.bindingBody!\n      | CongrArgKind.eq =>\n        let argResult := argResults[j]!\n        let argProof \u2190 argResult.getProof' arg\n        j := j + 1\n        proof := mkApp2 proof argResult.expr argProof\n        subst := subst.push argResult.expr |>.push argProof\n        type := type.bindingBody!.bindingBody!\n      | _ => unreachable!\n    let some (_, _, rhs) := type.instantiateRev subst |>.eq? | unreachable!\n    let rhs \u2190 if hasCast then removeUnnecessaryCasts rhs else pure rhs\n    if hasProof then\n      return some { expr := rhs, proof? := proof }\n    else\n      /- See comment above. This is reachable if `hasCast == true`. The `rhs` is not structurally equal to `mkAppN f argsNew` -/\n      return some { expr := rhs }\n\n  congrDefault (e : Expr) : M Result := do\n    if let some result \u2190 tryAutoCongrTheorem? e then\n      mkEqTrans result (\u2190 visitFn result.expr)\n    else\n      withParent e <| e.withApp fun f args => do\n        congrArgs (\u2190 simp f) args\n\n  /-- Process the given congruence theorem hypothesis. Return true if it made \"progress\". -/\n  processCongrHypothesis (h : Expr) : M Bool := do\n    forallTelescopeReducing (\u2190 inferType h) fun xs hType => withNewLemmas xs do\n      let lhs \u2190 instantiateMVars hType.appFn!.appArg!\n      let r \u2190 simp lhs\n      let rhs := hType.appArg!\n      rhs.withApp fun m zs => do\n        let val \u2190 mkLambdaFVars zs r.expr\n        unless (\u2190 isDefEq m val) do\n          throwCongrHypothesisFailed\n        let mut proof \u2190 r.getProof\n        if hType.isAppOf ``Iff then\n          try proof \u2190 mkIffOfEq proof\n          catch _ => throwCongrHypothesisFailed\n        unless (\u2190 isDefEq h (\u2190 mkLambdaFVars xs proof)) do\n          throwCongrHypothesisFailed\n        /- We used to return `false` if `r.proof? = none` (i.e., an implicit `rfl` proof) because we\n           assumed `dsimp` would also be able to simplify the term, but this is not true\n           for non-trivial user-provided theorems.\n           Example:\n           ```\n           @[congr] theorem image_congr {f g : \u03b1 \u2192 \u03b2} {s : Set \u03b1} (h : \u2200 a, mem a s \u2192 f a = g a) : image f s = image g s :=\n           ...\n\n           example {\u0393: Set Nat}: (image (Nat.succ \u2218 Nat.succ) \u0393) = (image (fun a => a.succ.succ) \u0393) := by\n             simp only [Function.comp_apply]\n           ```\n           `Function.comp_apply` is a `rfl` theorem, but `dsimp` will not apply it because the composition\n           is not fully applied. See comment at issue #1113\n\n           Thus, we have an extra check now if `xs.size > 0`. TODO: refine this test.\n        -/\n        return r.proof?.isSome || (xs.size > 0 && lhs != r.expr)\n\n  /-- Try to rewrite `e` children using the given congruence theorem -/\n  trySimpCongrTheorem? (c : SimpCongrTheorem) (e : Expr) : M (Option Result) := withNewMCtxDepth do\n    trace[Debug.Meta.Tactic.simp.congr] \"{c.theoremName}, {e}\"\n    let thm \u2190 mkConstWithFreshMVarLevels c.theoremName\n    let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType thm)\n    if c.hypothesesPos.any (\u00b7 \u2265 xs.size) then\n      return none\n    let isIff := type.isAppOf ``Iff\n    let lhs := type.appFn!.appArg!\n    let rhs := type.appArg!\n    let numArgs := lhs.getAppNumArgs\n    let mut e := e\n    let mut extraArgs := #[]\n    if e.getAppNumArgs > numArgs then\n      let args := e.getAppArgs\n      e := mkAppN e.getAppFn args[:numArgs]\n      extraArgs := args[numArgs:].toArray\n    if (\u2190 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 (\u2190 processCongrHypothesis x) then\n            modified := true\n        catch ex =>\n          trace[Meta.Tactic.simp.congr] \"processCongrHypothesis {c.theoremName} failed {\u2190 inferType x}\"\n          if ex.isMaxRecDepth then\n            -- Recall that `processCongrHypothesis` invokes `simp` recursively.\n            throw ex\n          else\n            return none\n      unless modified do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} not modified\"\n        return none\n      unless (\u2190 synthesizeArgs (.decl c.theoremName) xs bis (\u2190 read).discharge?) do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} synthesizeArgs failed\"\n        return none\n      let eNew \u2190 instantiateMVars rhs\n      let mut proof \u2190 instantiateMVars (mkAppN thm xs)\n      if isIff then\n        try proof \u2190 mkAppM ``propext #[proof]\n        catch _ => return none\n      if (\u2190 hasAssignableMVar proof <||> hasAssignableMVar eNew) then\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} has unassigned metavariables\"\n        return none\n      congrArgs { expr := eNew, proof? := proof } extraArgs\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 congrThms \u2190 getSimpCongrTheorems\n      let cs := congrThms.get f.constName!\n      for c in cs do\n        match (\u2190 trySimpCongrTheorem? 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 \u2190 reduce e\n    if !e.isApp then\n      simp e\n    else if isOfNatNatLit e then\n      -- Recall that we expand \"orphan\" kernel nat literals `n` into `ofNat n`\n      return { expr := e }\n    else\n      congr e\n\n  simpConst (e : Expr) : M Result :=\n    return { expr := (\u2190 reduce e) }\n\n  withNewLemmas {\u03b1} (xs : Array Expr) (f : M \u03b1) : M \u03b1 := do\n    if (\u2190 getConfig).contextual then\n      let mut s \u2190 getSimpTheorems\n      let mut updated := false\n      for x in xs do\n        if (\u2190 isProof x) then\n          s \u2190 s.addTheorem (.fvar x.fvarId!) x\n          updated := true\n      if updated then\n        withSimpTheorems s f\n      else\n        f\n    else\n      f\n\n  simpLambda (e : Expr) : M Result :=\n    withParent e <| lambdaTelescopeDSimp e fun xs e => withNewLemmas xs do\n      let r \u2190 simp e\n      let eNew \u2190 mkLambdaFVars xs r.expr\n      match r.proof? with\n      | none   => return { expr := eNew }\n      | some h =>\n        let p \u2190 xs.foldrM (init := h) fun x h => do\n          mkFunExt (\u2190 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 \u2190 simp p\n    trace[Debug.Meta.Tactic.simp] \"arrow [{(\u2190 getConfig).contextual}] {p} [{\u2190 isProp p}] -> {q} [{\u2190 isProp q}]\"\n    if (\u2190 pure (\u2190 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 \u2190 getSimpTheorems\n        let s \u2190 s.addTheorem (.fvar h.fvarId!) h\n        withSimpTheorems s do\n          let rq \u2190 simp q\n          match rq.proof? with\n          | none    => mkImpCongr e rp rq\n          | some hq =>\n            let hq \u2190 mkLambdaFVars #[h] hq\n            /-\n              We use the default reducibility setting at `mkImpDepCongrCtx` and `mkImpCongrCtx` because they use the theorems\n              ```lean\n              @implies_dep_congr_ctx : \u2200 {p\u2081 p\u2082 q\u2081 : Prop}, p\u2081 = p\u2082 \u2192 \u2200 {q\u2082 : p\u2082 \u2192 Prop}, (\u2200 (h : p\u2082), q\u2081 = q\u2082 h) \u2192 (p\u2081 \u2192 q\u2081) = \u2200 (h : p\u2082), q\u2082 h\n              @implies_congr_ctx : \u2200 {p\u2081 p\u2082 q\u2081 q\u2082 : Prop}, p\u2081 = p\u2082 \u2192 (p\u2082 \u2192 q\u2081 = q\u2082) \u2192 (p\u2081 \u2192 q\u2081) = (p\u2082 \u2192 q\u2082)\n              ```\n              And the proofs may be from `rfl` theorems which are now omitted. Moreover, we cannot establish that the two\n              terms are definitionally equal using `withReducible`.\n              TODO (better solution): provide the problematic implicit arguments explicitly. It is more efficient and avoids this\n              problem.\n             -/\n            if rq.expr.containsFVar h.fvarId! then\n              return { expr := (\u2190 mkForallFVars #[h] rq.expr), proof? := (\u2190 withDefault <| mkImpDepCongrCtx (\u2190 rp.getProof) hq) }\n            else\n              return { expr := e.updateForallE! rp.expr rq.expr, proof? := (\u2190 withDefault <| mkImpCongrCtx (\u2190 rp.getProof) hq) }\n    else\n      mkImpCongr e rp (\u2190 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 (\u2190 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 \u2190 simp b\n        let eNew \u2190 mkForallFVars #[x] rb.expr\n        match rb.proof? with\n        | none   => return { expr := eNew }\n        | some h => return { expr := eNew, proof? := (\u2190 mkForallCongr (\u2190 mkLambdaFVars #[x] h)) }\n    else\n      return { expr := (\u2190 dsimp e) }\n\n  simpLet (e : Expr) : M Result := do\n    let Expr.letE n t v b _ := e | unreachable!\n    if (\u2190 getConfig).zeta then\n      return { expr := b.instantiate1 v }\n    else\n      match (\u2190 getSimpLetCase n t b) with\n      | SimpLetCase.dep => return { expr := (\u2190 dsimp e) }\n      | SimpLetCase.nondep =>\n        let rv \u2190 simp v\n        withLocalDeclD n t fun x => do\n          let bx := b.instantiate1 x\n          let rbx \u2190 simp bx\n          let hb? \u2190 match rbx.proof? with\n            | none => pure none\n            | some h => pure (some (\u2190 mkLambdaFVars #[x] h))\n          let e' := mkLet n t rv.expr (\u2190 rbx.expr.abstractM #[x])\n          match rv.proof?, hb? with\n          | none,   none   => return { expr := e' }\n          | some h, none   => return { expr := e', proof? := some (\u2190 mkLetValCongr (\u2190 mkLambdaFVars #[x] rbx.expr) h) }\n          | _,      some h => return { expr := e', proof? := some (\u2190 mkLetCongr (\u2190 rv.getProof) h) }\n      | SimpLetCase.nondepDepVar =>\n        let v' \u2190 dsimp v\n        withLocalDeclD n t fun x => do\n          let bx := b.instantiate1 x\n          let rbx \u2190 simp bx\n          let e' := mkLet n t v' (\u2190 rbx.expr.abstractM #[x])\n          match rbx.proof? with\n          | none => return { expr := e' }\n          | some h =>\n            let h \u2190 mkLambdaFVars #[x] h\n            return { expr := e', proof? := some (\u2190 mkLetBodyCongr v' h) }\n\n  cacheResult (cfg : Config) (r : Result) : M Result := do\n    if cfg.memoize then\n      let dischargeDepth := (\u2190 readThe Simp.Context).dischargeDepth\n      modify fun s => { s with cache := s.cache.insert e { r with dischargeDepth } }\n    return r\n\n@[inline] def withSimpConfig (ctx : Context) (x : MetaM \u03b1) : MetaM \u03b1 :=\n  withConfig (fun c => { c with etaStruct := ctx.config.etaStruct }) <| withReducible x\n\ndef main (e : Expr) (ctx : Context) (usedSimps : UsedSimps := {}) (methods : Methods := {}) : MetaM (Result \u00d7 UsedSimps) := do\n  let ctx := { ctx with config := (\u2190 ctx.config.updateArith) }\n  withSimpConfig ctx do\n    try\n      let (r, s) \u2190 simp e methods ctx |>.run { usedTheorems := usedSimps }\n      trace[Meta.Tactic.simp.numSteps] \"{s.numSteps}\"\n      return (r, s.usedTheorems)\n    catch ex =>\n      if ex.isMaxHeartbeat then throwNestedTacticEx `simp ex else throw ex\n\ndef dsimpMain (e : Expr) (ctx : Context) (usedSimps : UsedSimps := {}) (methods : Methods := {}) : MetaM (Expr \u00d7 UsedSimps) := do\n  withSimpConfig ctx do\n    try\n      let (r, s) \u2190 dsimp e methods ctx |>.run { usedTheorems := usedSimps }\n      pure (r, s.usedTheorems)\n    catch ex =>\n      if ex.isMaxHeartbeat then throwNestedTacticEx `dsimp ex else throw ex\n\n/--\n  Return true if `e` is of the form `(x : \u03b1) \u2192 ... \u2192 s = t \u2192 ... \u2192 False`\n\n  Recall that this kind of proposition is generated by Lean when creating equations for\n  functions and match-expressions with overlapping cases.\n  Example: the following `match`-expression has overlapping cases.\n  ```\n  def f (x y : Nat) :=\n    match x, y with\n    | Nat.succ n, Nat.succ m => ...\n    | _, _ => 0\n  ```\n  The second equation is of the form\n  ```\n  (x y : Nat) \u2192 ((n m : Nat) \u2192 x = Nat.succ n \u2192 y = Nat.succ m \u2192 False) \u2192 f x y = 0\n  ```\n  The hypothesis `(n m : Nat) \u2192 x = Nat.succ n \u2192 y = Nat.succ m \u2192 False` is essentially\n  saying the first case is not applicable.\n-/\npartial def isEqnThmHypothesis (e : Expr) : Bool :=\n  e.isForall && go e\nwhere\n  go (e : Expr) : Bool :=\n    match e with\n    | .forallE _ d b _ => (d.isEq || d.isHEq || b.hasLooseBVar 0) && go b\n    | _ => e.isConstOf ``False\n\nabbrev Discharge := Expr \u2192 SimpM (Option Expr)\n\ndef dischargeUsingAssumption? (e : Expr) : SimpM (Option Expr) := do\n  (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n    if localDecl.isImplementationDetail then\n      return none\n    else if (\u2190 isDefEq e localDecl.type) then\n      return some localDecl.toExpr\n    else\n      return none\n\n/--\n  Tries to solve `e` using `unifyEq?`.\n  It assumes that `isEqnThmHypothesis e` is `true`.\n-/\npartial def dischargeEqnThmHypothesis? (e : Expr) : MetaM (Option Expr) := do\n  assert! isEqnThmHypothesis e\n  let mvar \u2190 mkFreshExprSyntheticOpaqueMVar e\n  withReader (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher }) do\n    if let .none \u2190 go? mvar.mvarId! then\n      instantiateMVars mvar\n    else\n      return none\nwhere\n  go? (mvarId : MVarId) : MetaM (Option MVarId) :=\n    try\n      let (fvarId, mvarId) \u2190 mvarId.intro1\n      mvarId.withContext do\n        let localDecl \u2190 fvarId.getDecl\n        if localDecl.type.isEq || localDecl.type.isHEq then\n          if let some { mvarId, .. } \u2190 unifyEq? mvarId fvarId {} then\n            go? mvarId\n          else\n            return none\n        else\n          go? mvarId\n    catch _  =>\n      return some mvarId\n\nnamespace DefaultMethods\nmutual\n  partial def discharge? (e : Expr) : SimpM (Option Expr) := do\n    if isEqnThmHypothesis e then\n      if let some r \u2190 dischargeUsingAssumption? e then\n        return some r\n      if let some r \u2190 dischargeEqnThmHypothesis? e then\n        return some r\n    let ctx \u2190 read\n    trace[Meta.Tactic.simp.discharge] \">> discharge?: {e}\"\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 \u2190 simp e { pre := pre, post := post, discharge? := discharge? }\n        if r.expr.isConstOf ``True then\n          try\n            return some (\u2190 mkOfEqTrue (\u2190 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?\nend\n\ndef methods : Methods :=\n  { pre := pre, post := post, discharge? := discharge? }\n\nend DefaultMethods\n\nend Simp\nopen Simp (UsedSimps)\n\ndef simp (e : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none)\n    (usedSimps : UsedSimps := {}) : MetaM (Simp.Result \u00d7 UsedSimps) := do profileitM Exception \"simp\" (\u2190 getOptions) do\n  match discharge? with\n  | none   => Simp.main e ctx usedSimps (methods := Simp.DefaultMethods.methods)\n  | some d => Simp.main e ctx usedSimps (methods := { pre := (Simp.preDefault \u00b7 d), post := (Simp.postDefault \u00b7 d), discharge? := d })\n\ndef dsimp (e : Expr) (ctx : Simp.Context)\n    (usedSimps : UsedSimps := {}) : MetaM (Expr \u00d7 UsedSimps) := do profileitM Exception \"dsimp\" (\u2190 getOptions) do\n  Simp.dsimpMain e ctx usedSimps (methods := Simp.DefaultMethods.methods)\n\n/--\n  Auxiliary method.\n  Given the current `target` of `mvarId`, apply `r` which is a new target and proof that it is equal to the current one.\n-/\ndef applySimpResultToTarget (mvarId : MVarId) (target : Expr) (r : Simp.Result) : MetaM MVarId := do\n  match r.proof? with\n  | some proof => mvarId.replaceTargetEq r.expr proof\n  | none =>\n    if target != r.expr then\n      mvarId.replaceTargetDefEq r.expr\n    else\n      return mvarId\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) (discharge? : Option Simp.Discharge := none)\n    (mayCloseGoal := true) (usedSimps : UsedSimps := {}) : MetaM (Option MVarId \u00d7 UsedSimps) := do\n  let target \u2190 instantiateMVars (\u2190 mvarId.getType)\n  let (r, usedSimps) \u2190 simp target ctx discharge? usedSimps\n  if mayCloseGoal && r.expr.isConstOf ``True then\n    match r.proof? with\n    | some proof => mvarId.assign (\u2190 mkOfEqTrue proof)\n    | none => mvarId.assign (mkConst ``True.intro)\n    return (none, usedSimps)\n  else\n    return (\u2190 applySimpResultToTarget mvarId target r, usedSimps)\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) (discharge? : Option Simp.Discharge := none)\n    (mayCloseGoal := true) (usedSimps : UsedSimps := {}) : MetaM (Option MVarId \u00d7 UsedSimps) :=\n  mvarId.withContext do\n    mvarId.checkNotAssigned `simp\n    simpTargetCore mvarId ctx discharge? mayCloseGoal usedSimps\n\n/--\n  Apply the result `r` for `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 applySimpResultToProp (mvarId : MVarId) (proof : Expr) (prop : Expr) (r : Simp.Result) (mayCloseGoal := true) : MetaM (Option (Expr \u00d7 Expr)) := do\n  if mayCloseGoal && r.expr.isConstOf ``False then\n    match r.proof? with\n    | some eqProof => mvarId.assign (\u2190 mkFalseElim (\u2190 mvarId.getType) (\u2190 mkEqMP eqProof proof))\n    | none => mvarId.assign (\u2190 mkFalseElim (\u2190 mvarId.getType) proof)\n    return none\n  else\n    match r.proof? with\n    | some eqProof => return some ((\u2190 mkEqMP eqProof proof), r.expr)\n    | none =>\n      if r.expr != prop then\n        return some ((\u2190 mkExpectedTypeHint proof r.expr), r.expr)\n      else\n        return some (proof, r.expr)\n\ndef applySimpResultToFVarId (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) (mayCloseGoal : Bool) : MetaM (Option (Expr \u00d7 Expr)) := do\n  let localDecl \u2190 fvarId.getDecl\n  applySimpResultToProp mvarId (mkFVar fvarId) localDecl.type r mayCloseGoal\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) (discharge? : Option Simp.Discharge := none)\n    (mayCloseGoal := true) (usedSimps : UsedSimps := {}) : MetaM (Option (Expr \u00d7 Expr) \u00d7 UsedSimps) := do\n  let (r, usedSimps) \u2190 simp prop ctx discharge? usedSimps\n  return (\u2190 applySimpResultToProp mvarId proof prop r (mayCloseGoal := mayCloseGoal), usedSimps)\n\ndef applySimpResultToLocalDeclCore (mvarId : MVarId) (fvarId : FVarId) (r : Option (Expr \u00d7 Expr)) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  match r with\n  | none => return none\n  | some (value, type') =>\n    let localDecl \u2190 fvarId.getDecl\n    if localDecl.type != type' then\n      let mvarId \u2190 mvarId.assert localDecl.userName type' value\n      let mvarId \u2190 mvarId.tryClear localDecl.fvarId\n      let (fvarId, mvarId) \u2190 mvarId.intro1P\n      return some (fvarId, mvarId)\n    else\n      return some (fvarId, mvarId)\n\n/--\n  Simplify `simp` result to the given local declaration. Return `none` if the goal was closed.\n  This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/\ndef applySimpResultToLocalDecl (mvarId : MVarId) (fvarId : FVarId) (r : Simp.Result) (mayCloseGoal : Bool) : MetaM (Option (FVarId \u00d7 MVarId)) := do\n  if r.proof?.isNone then\n    -- New result is definitionally equal to input. Thus, we can avoid creating a new variable if there are dependencies\n    let mvarId \u2190 mvarId.replaceLocalDeclDefEq fvarId r.expr\n    if mayCloseGoal && r.expr.isConstOf ``False then\n      mvarId.assign (\u2190 mkFalseElim (\u2190 mvarId.getType) (mkFVar fvarId))\n      return none\n    else\n      return some (fvarId, mvarId)\n  else\n    applySimpResultToLocalDeclCore mvarId fvarId (\u2190 applySimpResultToFVarId mvarId fvarId r mayCloseGoal)\n\ndef simpLocalDecl (mvarId : MVarId) (fvarId : FVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none)\n    (mayCloseGoal := true) (usedSimps : UsedSimps := {}) : MetaM (Option (FVarId \u00d7 MVarId) \u00d7 UsedSimps) := do\n  mvarId.withContext do\n    mvarId.checkNotAssigned `simp\n    let type \u2190 instantiateMVars (\u2190 fvarId.getType)\n    let (r, usedSimps) \u2190 simpStep mvarId (mkFVar fvarId) type ctx discharge? mayCloseGoal usedSimps\n    return (\u2190 applySimpResultToLocalDeclCore mvarId fvarId r, usedSimps)\n\ndef simpGoal (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none)\n    (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[])\n    (usedSimps : UsedSimps := {}) : MetaM (Option (Array FVarId \u00d7 MVarId) \u00d7 UsedSimps) := do\n  mvarId.withContext do\n    mvarId.checkNotAssigned `simp\n    let mut mvarId := mvarId\n    let mut toAssert := #[]\n    let mut replaced := #[]\n    let mut usedSimps := usedSimps\n    for fvarId in fvarIdsToSimp do\n      let localDecl \u2190 fvarId.getDecl\n      let type \u2190 instantiateMVars localDecl.type\n      let ctx := { ctx with simpTheorems := ctx.simpTheorems.eraseTheorem (.fvar localDecl.fvarId) }\n      let (r, usedSimps') \u2190 simp type ctx discharge? usedSimps\n      usedSimps := usedSimps'\n      match r.proof? with\n      | some _ => match (\u2190 applySimpResultToProp mvarId (mkFVar fvarId) type r) with\n        | none => return (none, usedSimps)\n        | some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value }\n      | none =>\n        if r.expr.isConstOf ``False then\n          mvarId.assign (\u2190 mkFalseElim (\u2190 mvarId.getType) (mkFVar fvarId))\n          return (none, usedSimps)\n        -- TODO: if there are no forwards dependencies we may consider using the same approach we used when `r.proof?` is a `some ...`\n        -- Reason: it introduces a `mkExpectedTypeHint`\n        mvarId \u2190 mvarId.replaceLocalDeclDefEq fvarId r.expr\n        replaced := replaced.push fvarId\n    if simplifyTarget then\n      match (\u2190 simpTarget mvarId ctx discharge?) with\n      | (none, usedSimps') => return (none, usedSimps')\n      | (some mvarIdNew, usedSimps') => mvarId := mvarIdNew; usedSimps := usedSimps'\n    let (fvarIdsNew, mvarIdNew) \u2190 mvarId.assertHypotheses toAssert\n    let toClear := fvarIdsToSimp.filter fun fvarId => !replaced.contains fvarId\n    let mvarIdNew \u2190 mvarIdNew.tryClearMany toClear\n    return (some (fvarIdsNew, mvarIdNew), usedSimps)\n\ndef simpTargetStar (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none)\n    (usedSimps : UsedSimps := {}) : MetaM (TacticResultCNM \u00d7 UsedSimps) := mvarId.withContext do\n  let mut ctx := ctx\n  for h in (\u2190 getPropHyps) do\n    let localDecl \u2190 h.getDecl\n    let proof  := localDecl.toExpr\n    let simpTheorems \u2190 ctx.simpTheorems.addTheorem (.fvar h) proof\n    ctx := { ctx with simpTheorems }\n  match (\u2190 simpTarget mvarId ctx discharge? (usedSimps := usedSimps)) with\n  | (none, usedSimps) => return (TacticResultCNM.closed, usedSimps)\n  | (some mvarId', usedSimps') =>\n    if (\u2190 mvarId.getType) == (\u2190 mvarId'.getType) then\n      return (TacticResultCNM.noChange, usedSimps)\n    else\n      return (TacticResultCNM.modified mvarId', usedSimps')\n\ndef dsimpGoal (mvarId : MVarId) (ctx : Simp.Context) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[])\n    (usedSimps : UsedSimps := {}) : MetaM (Option MVarId \u00d7 UsedSimps) := do\n   mvarId.withContext do\n    mvarId.checkNotAssigned `simp\n    let mut mvarId := mvarId\n    let mut usedSimps : UsedSimps := usedSimps\n    for fvarId in fvarIdsToSimp do\n      let type \u2190 instantiateMVars (\u2190 fvarId.getType)\n      let (typeNew, usedSimps') \u2190 dsimp type ctx\n      usedSimps := usedSimps'\n      if typeNew.isConstOf ``False then\n        mvarId.assign (\u2190 mkFalseElim (\u2190 mvarId.getType) (mkFVar fvarId))\n        return (none, usedSimps)\n      if typeNew != type then\n        mvarId \u2190 mvarId.replaceLocalDeclDefEq fvarId typeNew\n    if simplifyTarget then\n      let target \u2190 mvarId.getType\n      let (targetNew, usedSimps') \u2190 dsimp target ctx usedSimps\n      usedSimps := usedSimps'\n      if targetNew.isConstOf ``True then\n        mvarId.assign (mkConst ``True.intro)\n        return (none, usedSimps)\n      if let some (_, lhs, rhs) := targetNew.eq? then\n        if (\u2190 withReducible <| isDefEq lhs rhs) then\n          mvarId.assign (\u2190 mkEqRefl lhs)\n          return (none, usedSimps)\n      if target != targetNew then\n        mvarId \u2190 mvarId.replaceTargetDefEq targetNew\n      pure () -- FIXME: bug in do notation if this is removed?\n    return (some mvarId, usedSimps)\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/Simp/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1968262036430985, "lm_q2_score": 0.027585280727863537, "lm_q1q2_score": 0.005429506082094509}}
{"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 \u00d7 String)\n\ndef WriterT.run (wm: WriterT m a ): m (a \u00d7 String) := wm\n\ndef WriterT.mk (x: m (a \u00d7 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: \u03b1 \u2192 WriterT m \u03b2) (x: \u03b1 \u00d7 String):\n    WriterT m \u03b2 := WriterT.mk do\n  let y \u2190 k x.fst\n  return (y.fst, x.snd ++ y.snd)\n\ndef WriterT.bind [Bind m] [Pure m] (wma: WriterT m \u03b1) (a2wmb: \u03b1 \u2192 WriterT m \u03b2):\n    WriterT m \u03b2 :=\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] {\u03b1 : Type u} (ma: m \u03b1): WriterT m \u03b1 :=\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 \u2192 Type u) (F: Type \u2192 Type v) :=\n  \u2200 T, E T \u2192 F T\nabbrev sum1 (E F: Type \u2192 Type) :=\n  fun T => E T \u2295 F T\ninductive Void1: Type \u2192 Type :=\n\ninfixr:40 \" ~> \" => to1\ninfixr:60 \" +' \" => sum1\n\nclass Member (E: Type \u2192 Type) (F: Type \u2192 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 \u2218 Member.inject T\n\ninstance MemberSumR {E F G} [Member E G]: Member E (F +' G) where\n  inject T := Sum.inr \u2218 Member.inject T\n\ndef Sum.cases {\u03b1 \u03b2 \u03b3} (f\u03b1: \u03b1 \u2192 \u03b3) (f\u03b2: \u03b2 \u2192 \u03b3): (\u03b1 \u2295 \u03b2) \u2192 \u03b3\n  | .inl a => f\u03b1 a\n  | .inr b => f\u03b2 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 \u2192 Type) (R: Type) where\n  | Ret (r: R): Fitree E R\n  | Vis {T: Type} (e: E T) (k: T \u2192 Fitree E R): Fitree E R\n\ndef Fitree.ret {E R}: R \u2192 Fitree E R :=\n  Fitree.Ret\n\ndef Fitree.trigger {E: Type \u2192 Type} {F: Type \u2192 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 \u2192 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 \u2192 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 \u2192 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\u2081: E ~> G) (h\u2082: F ~> G): E +' F ~> G :=\n  fun R ef => match ef with\n  | Sum.inl e => h\u2081 R e\n  | Sum.inr f => h\u2082 R f\n\n@[simp] theorem Fitree.case_left:\n  Fitree.case h\u2081 h\u2082 _ (Sum.inl e) = h\u2081 _ e := rfl\n@[simp] theorem Fitree.case_right:\n  Fitree.case h\u2081 h\u2082 _ (Sum.inr e) = h\u2082 _ e := rfl\n\n/-\n### Monadic interpretation\n-/\n\ndef Fitree.interp {M} [Monad M] {E} (h: E ~> M) {R}: Fitree E R \u2192 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 \u2192 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 \u2192 WriterT M R :=\n  interp h\n\ndef Fitree.interpOption {M} [Monad M] {E} (h: E ~> OptionT M):\n    forall {R}, Fitree E R \u2192 OptionT M R :=\n  interp h\n\ndef Fitree.interpExcept {M \u03b5} [Monad M] {E} (h: E ~> ExceptT \u03b5 M) {R}:\n    Fitree E R \u2192 ExceptT \u03b5 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 \u2192 S \u2192 Fitree E (R \u00d7 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 \u2192 Fitree E (R \u00d7 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 \u2192 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 \u2192 Fitree E (Except \u03b5 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 \u03b5 (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 \u03b5} [Monad M] (h: E ~> ExceptT \u03b5 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 \u2192 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 \u00d7 String) := by\n  simp [WriterT]\n\ntheorem Fitree.interpWriter_bind (h: E ~> WriterT (Fitree F))\n  (t: Fitree E T) (k: T \u2192 Fitree E R):\n    Fitree.interpWriter h (Fitree.bind t k) =\n    Fitree.bind (Fitree.interpWriter h t) fun (x,s\u2081) =>\n      Fitree.bind (Fitree.interpWriter h (k x)) fun (y,s\u2082) =>\n        Fitree.ret (y,s\u2081++s\u2082) := by\n  induction t with\n  | Ret _ =>\n      simp [bind, interpWriter]\n      have h\u2081: forall x, \"\" ++ x = x := by\n        simp [HAppend.hAppend, Append.append, String.append]\n        simp [List.nil_append]\n      simp [h\u2081]\n      have h\u2082: forall (\u03b1 \u03b2: Type) (x: \u03b1 \u00d7 \u03b2), (x.fst, x.snd) = x := by simp\n      simp [h\u2082]\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 \u2192 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) \u2192 match (bind) theorem to rewrite, so...\n      have fequal2 \u03b1 \u03b2 (f g: \u03b1 \u2192 \u03b2) x y: f = g \u2192 x = y \u2192 f x = g y :=\n        fun h\u2081 h\u2082 => by simp [h\u2081, h\u2082]\n      apply fequal2; rfl; funext x\n      cases x <;> simp [ih]\n\ntheorem Fitree.interpExcept_bind (h: E ~> ExceptT \u03b5 (Fitree F))\n  (t: Fitree E T) (k: T \u2192 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 \u03b5 => Fitree.ret (.error \u03b5)\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 \u03b1 \u03b2 (f g: \u03b1 \u2192 \u03b2) x y: f = g \u2192 x = y \u2192 f x = g y :=\n        fun h\u2081 h\u2082 => by simp [h\u2081, h\u2082]\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 \u2192 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 \u2192 Prop :=\n  | Ret r: noEventL (Ret r)\n  | Vis f k: (\u2200 t, noEventL (k t)) \u2192 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 \u00d7 i) -> (BBRef i' \u00d7 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 \u00d7 i) -> (BBRef i' \u00d7 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 <input-type> <interprocedural-out-type>\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 (\u03a3 (i: Type), BBRef i) -> Type _ -> Type _ -> Type _ where\n| lbl: ((ref: BBRef i) ->\n   RegionBuilder O T (\u27e8 i, ref \u27e9::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 (\u27e8i,ref\u27e9::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 \u00d7 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 \u27e8exitbb, inew\u27e9, \u27e8loopbb, (inew, knew)\u27e9)))))\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' \u00d7 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: \u2200 (n: Nat), factorial (Int.ofNat (Nat.succ n))\naxiom factorial_rec: \u2200 (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": "import lean_gym.server\n\n-- set up server\nmeta def  json_config : json_server lean_server_request lean_server_response := {\n  read_write := io_streams.stdin_stdout_streams,\n  get_json := json_server.get_custom_json,   -- use custom format since faster\n  put_json := json_server.put_standard_json, -- use standard format  \n}\n\nmeta def my_tactic : tactic unit := do\nchild \u2190 tactic.unsafe_run_io $ io.proc.spawn {\n  cmd := \"python3\",\n  args := [\"lean_gym/gym/example_app.py\", \"--app\"],\n  stdout := io.process.stdio.piped,\n  stdin := io.process.stdio.piped,\n},\nlet json_config : json_server lean_server_request lean_server_response := {\n  read_write := io_streams.child_process_streams child,\n  get_json := json_server.get_custom_json,   -- use custom format since faster\n  put_json := json_server.put_standard_json, -- use standard format  \n},\nout <- lean_gym.run_server_from_tactic json_config,\nmatch out with\n| except.error e := tactic.trace \"There was an error\"\n| except.ok (some s) := tactic.trace s\n| except.ok none := return ()\nend,\nreturn ()\n\nexample : (\u2200 p q : Prop, q \u2192 p \u2192 q) := \nbegin\n--my_tactic,\nintro, intro, intro, intro, apply a\nend", "meta": {"author": "jasonrute", "repo": "lean_gym_prototype", "sha": "ab29624d14e4e069e15afe0b1d90248b5b394b86", "save_path": "github-repos/lean/jasonrute-lean_gym_prototype", "path": "github-repos/lean/jasonrute-lean_gym_prototype/lean_gym_prototype-ab29624d14e4e069e15afe0b1d90248b5b394b86/src/examples/tactic_calls_process.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.16885696050685436, "lm_q2_score": 0.031618767724904455, "lm_q1q2_score": 0.005339049012999593}}
{"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.ematch\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.Smt.CongruenceClosure\nimport Leanbin.Init.Meta.Attribute\nimport Leanbin.Init.Meta.SimpTactic\nimport Leanbin.Init.Meta.InteractiveBase\nimport Leanbin.Init.Meta.Derive\n\nopen Tactic\n\n/-- Heuristic instantiation lemma -/\nunsafe axiom hinst_lemma : Type\n#align hinst_lemma hinst_lemma\n\nunsafe axiom hinst_lemmas : Type\n#align hinst_lemmas hinst_lemmas\n\n/-- `mk_core m e as_simp`, m is used to decide which definitions will be unfolded in patterns.\n   If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion\n   as a pattern. -/\nunsafe axiom hinst_lemma.mk_core : Transparency \u2192 expr \u2192 Bool \u2192 tactic hinst_lemma\n#align hinst_lemma.mk_core hinst_lemma.mk_core\n\nunsafe axiom hinst_lemma.mk_from_decl_core : Transparency \u2192 Name \u2192 Bool \u2192 tactic hinst_lemma\n#align hinst_lemma.mk_from_decl_core hinst_lemma.mk_from_decl_core\n\nunsafe axiom hinst_lemma.pp : hinst_lemma \u2192 tactic format\n#align hinst_lemma.pp hinst_lemma.pp\n\nunsafe axiom hinst_lemma.id : hinst_lemma \u2192 Name\n#align hinst_lemma.id hinst_lemma.id\n\nunsafe instance : has_to_tactic_format hinst_lemma :=\n  \u27e8hinst_lemma.pp\u27e9\n\nunsafe def hinst_lemma.mk (h : expr) : tactic hinst_lemma :=\n  hinst_lemma.mk_core reducible h false\n#align hinst_lemma.mk hinst_lemma.mk\n\nunsafe def hinst_lemma.mk_from_decl (h : Name) : tactic hinst_lemma :=\n  hinst_lemma.mk_from_decl_core reducible h false\n#align hinst_lemma.mk_from_decl hinst_lemma.mk_from_decl\n\nunsafe axiom hinst_lemmas.mk : hinst_lemmas\n#align hinst_lemmas.mk hinst_lemmas.mk\n\nunsafe axiom hinst_lemmas.add : hinst_lemmas \u2192 hinst_lemma \u2192 hinst_lemmas\n#align hinst_lemmas.add hinst_lemmas.add\n\nunsafe axiom hinst_lemmas.fold {\u03b1 : Type} : hinst_lemmas \u2192 \u03b1 \u2192 (hinst_lemma \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1\n#align hinst_lemmas.fold hinst_lemmas.fold\n\nunsafe axiom hinst_lemmas.merge : hinst_lemmas \u2192 hinst_lemmas \u2192 hinst_lemmas\n#align hinst_lemmas.merge hinst_lemmas.merge\n\nunsafe def mk_hinst_singleton : hinst_lemma \u2192 hinst_lemmas :=\n  hinst_lemmas.add hinst_lemmas.mk\n#align mk_hinst_singleton mk_hinst_singleton\n\nunsafe def hinst_lemmas.pp (s : hinst_lemmas) : tactic format :=\n  let tac :=\n    s.fold (return format.nil) fun h tac => do\n      let hpp \u2190 h.pp\n      let r \u2190 tac\n      if r then return hpp\n        else\n          return\n            f! \"{r },\n              {hpp}\"\n  do\n  let r \u2190 tac\n  return <| format.cbrace (format.group r)\n#align hinst_lemmas.pp hinst_lemmas.pp\n\nunsafe instance : has_to_tactic_format hinst_lemmas :=\n  \u27e8hinst_lemmas.pp\u27e9\n\nopen Tactic\n\nprivate unsafe def add_lemma (m : Transparency) (as_simp : Bool) (h : Name) (hs : hinst_lemmas) :\n    tactic hinst_lemmas := do\n  let h \u2190 hinst_lemma.mk_from_decl_core m h as_simp\n  return <| hs h\n#align add_lemma add_lemma\n\nunsafe def to_hinst_lemmas_core (m : Transparency) :\n    Bool \u2192 List Name \u2192 hinst_lemmas \u2192 tactic hinst_lemmas\n  | as_simp, [], hs => return hs\n  | as_simp, n :: ns, hs =>\n    let add (n) := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns\n    do\n    let eqns\n      \u2190-- First check if n is the name of a function with equational lemmas associated with it\n          tactic.get_eqn_lemmas_for\n          true n\n    match eqns with\n      | [] => do\n        -- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma\n            add\n            n\n      | _ => do\n        let p \u2190 is_prop_decl n\n        if p then add n\n          else-- n is a proposition\n          do\n            let new_hs\n              \u2190-- Add equational lemmas to resulting hinst_lemmas\n                  to_hinst_lemmas_core\n                  tt eqns hs\n            to_hinst_lemmas_core as_simp ns new_hs\n#align to_hinst_lemmas_core to_hinst_lemmas_core\n\nunsafe def mk_hinst_lemma_attr_core (attr_name : Name) (as_simp : Bool) : Tactic := do\n  let t := q(user_attribute hinst_lemmas)\n  let v :=\n    q(({  Name := attr_name\n          descr := \"hinst_lemma attribute\"\n          after_set :=\n            some fun n _ _ =>\n              to_hinst_lemmas_core reducible as_simp [n] hinst_lemmas.mk >> skip <|>\n                fail f! \"invalid ematch lemma '{n}'\"\n          -- allow unsetting\n          before_unset := some fun _ _ => skip\n          cache_cfg :=\n            { mk_cache := fun ns => to_hinst_lemmas_core reducible as_simp ns hinst_lemmas.mk\n              dependencies := [`reducibility] } } :\n        user_attribute hinst_lemmas))\n  add_decl (declaration.defn attr_name [] t v ReducibilityHints.abbrev ff)\n  attribute.register attr_name\n#align mk_hinst_lemma_attr_core mk_hinst_lemma_attr_core\n\nunsafe def mk_hinst_lemma_attrs_core (as_simp : Bool) : List Name \u2192 Tactic\n  | [] => skip\n  | n :: ns =>\n    mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns <|> do\n      let type \u2190 infer_type (expr.const n [])\n      let expected := q(user_attribute)\n      is_def_eq type expected <|>\n          fail\n            f! \"failed to create hinst_lemma attribute '{n}', declaration already exists and has different type.\"\n      mk_hinst_lemma_attrs_core ns\n#align mk_hinst_lemma_attrs_core mk_hinst_lemma_attrs_core\n\nunsafe def merge_hinst_lemma_attrs (m : Transparency) (as_simp : Bool) :\n    List Name \u2192 hinst_lemmas \u2192 tactic hinst_lemmas\n  | [], hs => return hs\n  | attr :: attrs, hs => do\n    let ns \u2190 attribute.get_instances attr\n    let new_hs \u2190 to_hinst_lemmas_core m as_simp ns hs\n    merge_hinst_lemma_attrs attrs new_hs\n#align merge_hinst_lemma_attrs merge_hinst_lemma_attrs\n\n/-- Create a new \"cached\" attribute (attr_name : user_attribute hinst_lemmas).\nIt also creates \"cached\" attributes for each attr_names and simp_attr_names if they have not been defined\nyet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with\n    attr_name, attrs_name, and simp_attr_names.\nFor the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern.\n-/\nunsafe def mk_hinst_lemma_attr_set (attr_name : Name) (attr_names : List Name)\n    (simp_attr_names : List Name) : Tactic := do\n  mk_hinst_lemma_attrs_core ff attr_names\n  mk_hinst_lemma_attrs_core tt simp_attr_names\n  let t := q(user_attribute hinst_lemmas)\n  let v :=\n    q(({  Name := attr_name\n          descr := \"hinst_lemma attribute set\"\n          after_set :=\n            some fun n _ _ =>\n              to_hinst_lemmas_core reducible false [n] hinst_lemmas.mk >> skip <|>\n                fail f! \"invalid ematch lemma '{n}'\"\n          -- allow unsetting\n          before_unset := some fun _ _ => skip\n          cache_cfg :=\n            { mk_cache := fun ns => do\n                let hs\u2081 \u2190 to_hinst_lemmas_core reducible false ns hinst_lemmas.mk\n                let hs\u2082 \u2190 merge_hinst_lemma_attrs reducible false attr_names hs\u2081\n                merge_hinst_lemma_attrs reducible tt simp_attr_names hs\u2082\n              dependencies := [`reducibility] ++ attr_names ++ simp_attr_names } } :\n        user_attribute hinst_lemmas))\n  add_decl (declaration.defn attr_name [] t v ReducibilityHints.abbrev ff)\n  attribute.register attr_name\n#align mk_hinst_lemma_attr_set mk_hinst_lemma_attr_set\n\nunsafe def get_hinst_lemmas_for_attr (attr_name : Name) : tactic hinst_lemmas :=\n  get_attribute_cache_dyn attr_name\n#align get_hinst_lemmas_for_attr get_hinst_lemmas_for_attr\n\nstructure EmatchConfig where\n  maxInstances : Nat := 10000\n  maxGeneration : Nat := 10\n#align ematch_config EmatchConfig\n\n/-! Ematching -/\n\n\nunsafe axiom ematch_state : Type\n#align ematch_state ematch_state\n\nunsafe axiom ematch_state.mk : EmatchConfig \u2192 ematch_state\n#align ematch_state.mk ematch_state.mk\n\nunsafe axiom ematch_state.internalize : ematch_state \u2192 expr \u2192 tactic ematch_state\n#align ematch_state.internalize ematch_state.internalize\n\nnamespace Tactic\n\nunsafe axiom ematch_core :\n    Transparency \u2192\n      cc_state \u2192\n        ematch_state \u2192 hinst_lemma \u2192 expr \u2192 tactic (List (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state)\n#align tactic.ematch_core tactic.ematch_core\n\nunsafe axiom ematch_all_core :\n    Transparency \u2192\n      cc_state \u2192\n        ematch_state \u2192 hinst_lemma \u2192 Bool \u2192 tactic (List (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state)\n#align tactic.ematch_all_core tactic.ematch_all_core\n\nunsafe def ematch :\n    cc_state \u2192\n      ematch_state \u2192 hinst_lemma \u2192 expr \u2192 tactic (List (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state) :=\n  ematch_core reducible\n#align tactic.ematch tactic.ematch\n\nunsafe def ematch_all :\n    cc_state \u2192\n      ematch_state \u2192 hinst_lemma \u2192 Bool \u2192 tactic (List (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state) :=\n  ematch_all_core reducible\n#align tactic.ematch_all tactic.ematch_all\n\nend Tactic\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/Ematch.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.19930799790404563, "lm_q2_score": 0.02675928182718321, "lm_q1q2_score": 0.005333338886325998}}
{"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.CollectMVars\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Constructor\nimport Lean.Meta.Tactic.Assert\nimport Lean.Meta.Tactic.Rename\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.SyntheticMVars\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\n/- `elabTerm` for Tactics and basic tactics that use it. -/\n\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  /- We have disabled `Term.withoutErrToSorry` to improve error recovery.\n     When we were using it, any tactic using `elabTerm` would be interrupted at elaboration errors.\n     Tactics that do not want to proceed should check whether the result contains sythetic sorrys or\n     disable `errToSorry` before invoking `elabTerm` -/\n  withRef stx do -- <| Term.withoutErrToSorry do\n    let e \u2190 Term.elabTerm stx expectedType?\n    Term.synthesizeSyntheticMVars mayPostpone\n    instantiateMVars e\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  let e \u2190 elabTerm stx expectedType? mayPostpone\n  -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here.\n  match expectedType? with\n  | none => return e\n  | some expectedType =>\n    let eType \u2190 inferType e\n    -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really\n    -- part of the elaboration, but part of the tactic. See issue #492\n    unless (\u2190 withAssignableSyntheticOpaque do isDefEq eType expectedType) do\n      Term.throwTypeMismatchError none expectedType eType e\n    return e\n\n/- Try to close main goal using `x target`, where `target` is the type of the main goal.  -/\ndef closeMainGoalUsing (x : Expr \u2192 TacticM Expr) (checkUnassigned := true) : TacticM Unit :=\n  withMainContext do\n    closeMainGoal (checkUnassigned := checkUnassigned) (\u2190 x (\u2190 getMainTarget))\n\ndef logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do\n   if (\u2190 Term.logUnassignedUsingErrorInfos mvarIds) then\n     throwAbortTactic\n\ndef filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do\n  let mctx \u2190 getMCtx\n  return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved\n\n@[builtinTactic \u00abexact\u00bb] def evalExact : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do\n    let mvarCounterSaved := (\u2190 getMCtx).mvarCounter\n    let r \u2190 elabTermEnsuringType e type\n    logUnassignedAndAbort (\u2190 filterOldMVars (\u2190 getMVars r) mvarCounterSaved)\n    return r\n  | _ => throwUnsupportedSyntax\n\ndef elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr \u00d7 List MVarId) := do\n  let mvarCounterSaved := (\u2190 getMCtx).mvarCounter\n  let val \u2190 elabTermEnsuringType stx expectedType?\n  let newMVarIds \u2190 getMVarsNoDelayed val\n  /- ignore let-rec auxiliary variables, they are synthesized automatically later -/\n  let newMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 Term.isLetRecAuxMVar mvarId)\n  let newMVarIds \u2190\n    if allowNaturalHoles then\n      pure newMVarIds.toList\n    else\n      let naturalMVarIds \u2190 newMVarIds.filterM fun mvarId => return (\u2190 getMVarDecl mvarId).kind.isNatural\n      let syntheticMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 getMVarDecl mvarId).kind.isNatural\n      let naturalMVarIds \u2190 filterOldMVars naturalMVarIds mvarCounterSaved\n      logUnassignedAndAbort naturalMVarIds\n      pure syntheticMVarIds.toList\n  tagUntaggedGoals (\u2190 getMainTag) tagSuffix newMVarIds\n  pure (val, newMVarIds)\n\n/- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned \"natural\" metavariables.\n   Recall that \"natutal\" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be\n   filled by typing constraints.\n   \"Synthetic\" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/\ndef refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do\n  withMainContext do\n    let (val, mvarIds') \u2190 elabTermWithHoles stx (\u2190 getMainTarget) tagSuffix allowNaturalHoles\n    assignExprMVar (\u2190 getMainGoal) val\n    replaceMainGoal mvarIds'\n\n@[builtinTactic \u00abrefine\u00bb] def evalRefine : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false)\n  | _                    => throwUnsupportedSyntax\n\n@[builtinTactic \u00abrefine'\u00bb] def evalRefine' : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true)\n  | _                     => throwUnsupportedSyntax\n\n@[builtinTactic \u00abspecialize\u00bb] def evalSpecialize : Tactic := fun stx => withMainContext do\n  match stx with\n  | `(tactic| specialize $e:term) =>\n    let (e, mvarIds') \u2190 elabTermWithHoles e none `specialize (allowNaturalHoles := true)\n    let h := e.getAppFn\n    if h.isFVar then\n      let localDecl \u2190 getLocalDecl h.fvarId!\n      let mvarId \u2190 assert (\u2190 getMainGoal) localDecl.userName (\u2190 inferType e).headBeta e\n      let (_, mvarId) \u2190 intro1P mvarId\n      let mvarId \u2190 tryClear mvarId h.fvarId!\n      replaceMainGoal (mvarId :: mvarIds')\n    else\n      throwError \"'specialize' requires a term of the form `h x_1 .. x_n` where `h` appears in the local context\"\n  | _ => throwUnsupportedSyntax\n\n/--\n   Given a tactic\n   ```\n   apply f\n   ```\n   we want the `apply` tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n   A similar method is also used in Lean 3.\n   This method is useful when applying lemmas such as:\n   ```\n   theorem infLeRight {s t : Set \u03b1} : s \u2293 t \u2264 t\n   ```\n   where `s \u2264 t` here is defined as\n   ```\n   \u2200 {x : \u03b1}, x \u2208 s \u2192 x \u2208 t\n   ```\n-/\ndef elabTermForApply (stx : Syntax) (mayPostpone := true) : TacticM Expr := do\n  if stx.isIdent then\n    match (\u2190 Term.resolveId? stx (withInfo := true)) with\n    | some e => return e\n    | _      => pure ()\n  elabTerm stx none mayPostpone\n\ndef evalApplyLikeTactic (tac : MVarId \u2192 Expr \u2192 MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do\n  withMainContext do\n    let val  \u2190 elabTermForApply e\n    let mvarIds'  \u2190 tac (\u2190 getMainGoal) val\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\ndef getFVarId (id : Syntax) : TacticM FVarId := withRef id do\n  -- use apply-like elaboration to suppress insertion of implicit arguments\n  let e \u2190 withMainContext do\n    elabTermForApply id (mayPostpone := false)\n  match e with\n  | Expr.fvar fvarId _ => return fvarId\n  | _                  => throwError \"unexpected term '{e}'; expected single reference to variable\"\n\ndef getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do\n  withMainContext do ids.mapM getFVarId\n\n@[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx =>\n  match stx with\n  | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e\n  | _ => throwUnsupportedSyntax\n\n@[builtinTactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun stx =>\n  withMainContext do\n    let mvarIds'  \u2190 Meta.constructor (\u2190 getMainGoal)\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(\u2190 Meta.existsIntro mvarId e)]) e\n  | _ => throwUnsupportedSyntax\n\n@[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx =>\n  withReducible <| evalTactic stx[1]\n\n@[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx =>\n  withReducibleAndInstances <| evalTactic stx[1]\n\n/--\n  Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable.\n  Note that, the main goal is updated when `Meta.assert` is used in the second case. -/\ndef elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId :=\n  withMainContext do\n    let e \u2190 elabTerm stx none\n    match e with\n    | Expr.fvar fvarId _ => pure fvarId\n    | _ =>\n      let type \u2190 inferType e\n      let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do\n        let mvarId \u2190 getMainGoal\n        let (fvarId, mvarId) \u2190 liftMetaM do\n          let mvarId \u2190 Meta.assert mvarId userName type e\n          Meta.intro1Core mvarId preserveBinderNames\n        replaceMainGoal [mvarId]\n        return fvarId\n      match userName? with\n      | none          => intro `h false\n      | some userName => intro userName true\n\n@[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx =>\n  match stx with\n  | `(tactic| rename $typeStx:term => $h:ident) => do\n    withMainContext do\n      /- Remark: we must not use `withoutModifyingState` because we may miss errors message.\n         For example, suppose the following `elabTerm` logs an error during elaboration.\n         In this scenario, the term `type` contains a synthetic `sorry`, and the error\n         message `\"failed to find ...\"` is not logged by the outer loop.\n         By using `withoutModifyingStateWithInfoAndMessages`, we ensure that\n         the messages and the info trees are preserved while the rest of the\n         state is backtracked. -/\n      let fvarId \u2190 withoutModifyingStateWithInfoAndMessages <| withNewMCtxDepth do\n        let type \u2190 elabTerm typeStx none (mayPostpone := true)\n        let fvarId? \u2190 (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n          if (\u2190 isDefEq type localDecl.type) then return localDecl.fvarId else return none\n        match fvarId? with\n        | none => throwError \"failed to find a hypothesis with type{indentExpr type}\"\n        | some fvarId => return fvarId\n      replaceMainGoal [\u2190 rename (\u2190 getMainGoal) fvarId h.getId]\n  | _ => throwUnsupportedSyntax\n\n/--\n   Make sure `expectedType` does not contain free and metavariables.\n   It applies zeta-reduction to eliminate let-free-vars.\n-/\nprivate def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do\n  let mut expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasFVar then\n    expectedType \u2190 zetaReduce expectedType\n  if expectedType.hasFVar || expectedType.hasMVar then\n    throwError \"expected type must not contain free or meta variables{indentExpr expectedType}\"\n  return expectedType\n\n@[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun stx =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let d \u2190 instantiateMVars d\n    let r \u2190 withDefault <| whnf d\n    unless r.isConstOf ``true do\n      throwError \"failed to reduce to 'true'{indentExpr r}\"\n    let s := d.appArg! -- get instance from `d`\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf\n\nprivate def mkNativeAuxDecl (baseName : Name) (type val : Expr) : TermElabM Name := do\n  let auxName \u2190 Term.mkAuxName baseName\n  let decl := Declaration.defnDecl {\n    name := auxName, levelParams := [], type := type, value := val,\n    hints := ReducibilityHints.abbrev,\n    safety := DefinitionSafety.safe\n  }\n  addDecl decl\n  compileDecl decl\n  pure auxName\n\n@[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun stx =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let auxDeclName \u2190 mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    let s := d.appArg! -- get instance from `d`\n    return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf\n\nend Lean.Elab.Tactic\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/Elab/Tactic/ElabTerm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561048817412842, "lm_q2_score": 0.034100423135568096, "lm_q1q2_score": 0.005323242520905609}}
{"text": "/-\nCopyright (c) 2022 Henrik B\u00f6ving. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Henrik B\u00f6ving\n-/\nimport Lean.Compiler.LCNF.CompilerM\nimport Lean.Compiler.LCNF.PassManager\nimport Lean.Compiler.LCNF.PullFunDecls\nimport Lean.Compiler.LCNF.FVarUtil\nimport Lean.Compiler.LCNF.ScopeM\nimport Lean.Compiler.LCNF.InferType\n\nnamespace Lean.Compiler.LCNF\n\nnamespace JoinPointFinder\n\nopen ScopeM\n\n/--\nInfo about a join point candidate (a `fun` declaration) during the find phase.\n-/\nstructure CandidateInfo where\n  /--\n  The arity of the candidate\n  -/\n  arity : Nat\n  /--\n  The set of candidates that rely on this candidate to be a join point.\n  For a more detailed explanation see the documentation of `find`\n  -/\n  associated : HashSet FVarId\n  deriving Inhabited\n\n/--\nThe state for the join point candidate finder.\n-/\nstructure FindState where\n  /--\n  All current join point candidates accessible by their `FVarId`.\n  -/\n  candidates : HashMap FVarId CandidateInfo := .empty\n  /--\n  The `FVarId`s of all `fun` declarations that were declared within the\n  current `fun`.\n  -/\n  scope : HashSet FVarId := .empty\n\nabbrev ReplaceCtx := HashMap FVarId Name\n\nabbrev FindM := ReaderT (Option FVarId) StateRefT FindState ScopeM\nabbrev ReplaceM := ReaderT ReplaceCtx CompilerM\n\n/--\nAttempt to find a join point candidate by its `FVarId`.\n-/\nprivate def findCandidate? (fvarId : FVarId) : FindM (Option CandidateInfo) := do\n  return (\u2190 get).candidates.find? fvarId\n\n/--\nErase a join point candidate as well as all the ones that depend on it\nby its `FVarId`, no error is thrown is the candidate does not exist.\n-/\nprivate partial def eraseCandidate (fvarId : FVarId) : FindM Unit := do\n  if let some info \u2190 findCandidate? fvarId then\n    modify (fun state => { state with candidates := state.candidates.erase fvarId })\n    info.associated.forM eraseCandidate\n\n/--\nCombinator for modifying the candidates in `FindM`.\n-/\nprivate def modifyCandidates (f : HashMap FVarId CandidateInfo \u2192 HashMap FVarId CandidateInfo) : FindM Unit :=\n  modify (fun state => {state with candidates := f state.candidates })\n\n/--\nRemove all join point candidates contained in `a`.\n-/\nprivate partial def removeCandidatesInArg (a : Arg) : FindM Unit := do\n  forFVarM eraseCandidate a\n\n/--\nRemove all join point candidates contained in `a`.\n-/\nprivate partial def removeCandidatesInLetValue (e : LetValue) : FindM Unit := do\n  forFVarM eraseCandidate e\n\n/--\nAdd a new join point candidate to the state.\n-/\nprivate def addCandidate (fvarId : FVarId) (arity : Nat) : FindM Unit := do\n  let cinfo := { arity, associated := .empty }\n  modifyCandidates (fun cs => cs.insert fvarId cinfo )\n\n/--\nAdd a new join point dependency from `src` to `dst`.\n-/\nprivate def addDependency (src : FVarId) (target : FVarId) : FindM Unit := do\n  if let some targetInfo \u2190 findCandidate? target then\n    modifyCandidates (fun cs => cs.insert target { targetInfo with associated := targetInfo.associated.insert src })\n  else\n    eraseCandidate src\n\n/--\nFind all `fun` declarations that qualify as a join point, that is:\n- are always fully applied\n- are always called in tail position\n\nWhere a `fun` `f` is in tail position iff it is called as follows:\n```\nlet res := f arg\nres\n```\nThe majority (if not all) tail calls will be brought into this form\nby the simplifier pass.\n\nFurthermore a `fun` disqualifies as a join point if turning it into a join\npoint would turn a call to it into an out of scope join point.\nThis can happen if we have something like:\n```\ndef test (b : Bool) (x y : Nat) : Nat :=\n  fun myjp x => Nat.add x (Nat.add x x)\n  fun f y =>\n    let x := Nat.add y y\n    myjp x\n  fun f y =>\n    let x := Nat.mul y y\n    myjp x\n  cases b (f x) (g y)\n```\n`f` and `g` can be detected as a join point right away, however\n`myjp` can only ever be detected as a join point after we have established\nthis. This is because otherwise the calls to `myjp` in `f` and `g` would\nproduce out of scope join point jumps.\n-/\npartial def find (decl : Decl) : CompilerM FindState := do\n  let (_, candidates) \u2190 go decl.value |>.run none |>.run {} |>.run' {}\n  return candidates\nwhere\n  go : Code \u2192 FindM Unit\n  | .let decl k => do\n    match k, decl.value with\n    | .return valId, .fvar fvarId args =>\n      args.forM removeCandidatesInArg\n      if let some candidateInfo \u2190 findCandidate? fvarId then\n        -- Erase candidate that are not fully applied or applied outside of tail position\n        if valId != decl.fvarId || args.size != candidateInfo.arity then\n          eraseCandidate fvarId\n        -- Out of scope join point candidate handling\n        else if let some upperCandidate \u2190 read then\n          if !(\u2190 isInScope fvarId) then\n            addDependency fvarId upperCandidate\n      else\n        eraseCandidate fvarId\n    | _, _ =>\n      removeCandidatesInLetValue decl.value\n      go k\n  | .fun decl k => do\n    withReader (fun _ => some decl.fvarId) do\n      withNewScope do\n        go decl.value\n    addCandidate decl.fvarId decl.getArity\n    addToScope decl.fvarId\n    go k\n  | .jp decl k => do\n    go decl.value\n    go k\n  | .jmp _ args => args.forM removeCandidatesInArg\n  | .return val => eraseCandidate val\n  | .cases c => do\n    eraseCandidate c.discr\n    c.alts.forM (\u00b7.forCodeM go)\n  | .unreach .. => return ()\n\n/--\nReplace all join point candidate `fun` declarations with `jp` ones\nand all calls to them with `jmp`s.\n-/\npartial def replace (decl : Decl) (state : FindState) : CompilerM Decl := do\n  let mapper := fun acc cname _ => do return acc.insert cname (\u2190 mkFreshJpName)\n  let replaceCtx : ReplaceCtx \u2190 state.candidates.foldM (init := .empty) mapper\n  let newValue \u2190 go decl.value |>.run replaceCtx\n  return { decl with value := newValue }\nwhere\n  go (code : Code) : ReplaceM Code := do\n    match code with\n    | .let decl k =>\n      match k, decl.value with\n      | .return valId, .fvar fvarId args =>\n        if valId == decl.fvarId then\n          if (\u2190 read).contains fvarId then\n            eraseLetDecl decl\n            return .jmp fvarId args\n          else\n            return code\n        else\n          return code\n      | _, _ => return Code.updateLet! code decl (\u2190 go k)\n    | .fun decl k =>\n      if let some replacement := (\u2190 read).find? decl.fvarId then\n        let newDecl := { decl with\n          binderName := replacement,\n          value := (\u2190 go decl.value)\n        }\n        modifyLCtx fun lctx => lctx.addFunDecl newDecl\n        return .jp newDecl (\u2190 go k)\n      else\n        let newDecl \u2190 decl.updateValue (\u2190 go decl.value)\n        return Code.updateFun! code newDecl (\u2190 go k)\n    | .jp decl k =>\n       let newDecl \u2190 decl.updateValue (\u2190 go decl.value)\n       return Code.updateFun! code newDecl (\u2190 go k)\n    | .cases cs =>\n      return Code.updateCases! code cs.resultType cs.discr (\u2190 cs.alts.mapM (\u00b7.mapCodeM go))\n    | .jmp .. | .return .. | .unreach .. =>\n      return code\n\nend JoinPointFinder\n\nnamespace JoinPointContextExtender\n\nopen ScopeM\n\n/--\nThe context managed by `ExtendM`.\n-/\nstructure ExtendContext where\n  /--\n  The `FVarId` of the current join point if we are currently inside one.\n  -/\n  currentJp? : Option FVarId := none\n  /--\n  The list of valid candidates for extending the context. This will be\n  all `let` and `fun` declarations as well as all `jp` parameters up\n  until the last `fun` declaration in the tree.\n  -/\n  candidates : FVarIdSet := {}\n\n/--\nThe state managed by `ExtendM`.\n-/\nstructure ExtendState where\n  /--\n  A map from join point `FVarId`s to a respective map from free variables\n  to `Param`s. The free variables in this map are the once that the context\n  of said join point will be extended by by passing in the respective parameter.\n  -/\n  fvarMap : HashMap FVarId (HashMap FVarId Param) := {}\n\n/--\nThe monad for the `extendJoinPointContext` pass.\n-/\nabbrev ExtendM := ReaderT ExtendContext StateRefT ExtendState ScopeM\n\n/--\nReplace a free variable if necessary, that is:\n- It is in the list of candidates\n- We are currently within a join point (if we are within a function there\n  cannot be a need to replace them since we dont extend their context)\n- Said join point actually has a replacement parameter registered.\notherwise just return `fvar`.\n-/\ndef replaceFVar (fvar : FVarId) : ExtendM FVarId := do\n  if (\u2190 read).candidates.contains fvar then\n    if let some currentJp := (\u2190 read).currentJp? then\n      if let some replacement := (\u2190 get).fvarMap.find! currentJp |>.find? fvar then\n        return replacement.fvarId\n  return fvar\n\n/--\nAdd a new candidate to the current scope + to the list of candidates\nif we are currently within a join point. Then execute `x`.\n-/\ndef withNewCandidate (fvar : FVarId) (x : ExtendM \u03b1) : ExtendM \u03b1 := do\n  addToScope fvar\n  if (\u2190 read).currentJp?.isSome then\n    withReader (fun ctx => { ctx with candidates := ctx.candidates.insert fvar }) do\n      x\n  else\n    x\n\n/--\nSame as `withNewCandidate` but with multiple `FVarId`s.\n-/\ndef withNewCandidates (fvars : Array FVarId) (x : ExtendM \u03b1) : ExtendM \u03b1 := do\n  if (\u2190 read).currentJp?.isSome then\n    let candidates := (\u2190 read).candidates\n    let folder (acc : FVarIdSet) (val : FVarId) := do\n      addToScope val\n      return acc.insert val\n    let newCandidates \u2190 fvars.foldlM (init := candidates) folder\n    withReader (fun ctx => { ctx with candidates := newCandidates }) do\n      x\n  else\n    x\n\n/--\nExtend the context of the current join point (if we are within one)\nby `fvar` if necessary.\nThis is necessary if:\n- `fvar` is not in scope (that is, was declared outside of the current jp)\n- we have not already extended the context by `fvar`\n- the list of candidates contains `fvar`. This is because if we have something\n  like:\n  ```\n  let x := ..\n  fun f a =>\n    jp j b =>\n      let y := x\n      y\n  ```\n  There is no point in extending the context of `j` by `x` because we\n  cannot lift a join point outside of a local function declaration.\n-/\ndef extendByIfNecessary (fvar : FVarId) : ExtendM Unit := do\n  if let some currentJp := (\u2190 read).currentJp? then\n    let mut translator := (\u2190 get).fvarMap.find! currentJp\n    let candidates := (\u2190 read).candidates\n    if !(\u2190 isInScope fvar) && !translator.contains fvar && candidates.contains fvar then\n      let typ \u2190 getType fvar\n      let newParam \u2190 mkAuxParam typ\n      translator := translator.insert fvar newParam\n      modify fun s => { s with fvarMap := s.fvarMap.insert currentJp translator }\n\n/--\nMerge the extended context of two join points if necessary. That is\nif we have a structure such as:\n```\njp j.1 ... =>\n  jp j.2 .. =>\n    ...\n  ...\n```\nAnd we are just done visiting `j.2` we want to extend the context of\n`j.1` by all free variables that the context of `j.2` was extended by\nas well because we need to drag these variables through at the call sites\nof `j.2` in `j.1`.\n-/\ndef mergeJpContextIfNecessary (jp : FVarId) : ExtendM Unit := do\n  if (\u2190 read).currentJp?.isSome then\n    let additionalArgs := (\u2190 get).fvarMap.find! jp |>.toArray\n    for (fvar, _) in additionalArgs do\n      extendByIfNecessary fvar\n\n/--\nWe call this whenever we enter a new local function. It clears both the\ncurrent join point and the list of candidates since we cant lift join\npoints outside of functions as explained in `mergeJpContextIfNecessary`.\n-/\ndef withNewFunScope (decl : FunDecl) (x : ExtendM \u03b1): ExtendM \u03b1 := do\n  withReader (fun ctx => { ctx with currentJp? := none, candidates := {} }) do\n    withNewScope do\n      x\n\n/--\nWe call this whenever we enter a new join point. It will set the current\njoin point and extend the list of candidates by all of the parameters of\nthe join point. This is so in the case of nested join points that refer\nto parameters of the current one we extend the context of the nested\njoin points by said parameters.\n-/\ndef withNewJpScope (decl : FunDecl) (x : ExtendM \u03b1): ExtendM \u03b1 := do\n  withReader (fun ctx => { ctx with currentJp? := some decl.fvarId }) do\n    modify fun s => { s with fvarMap := s.fvarMap.insert decl.fvarId {} }\n    withNewScope do\n      withNewCandidates (decl.params.map (\u00b7.fvarId)) do\n        x\n\n/--\nWe call this whenever we visit a new arm of a cases statement.\nIt will back up the current scope (since we are doing a case split\nand want to continue with other arms afterwards) and add all of the\nparameters of the match arm to the list of candidates.\n-/\ndef withNewAltScope (alt : Alt) (x : ExtendM \u03b1) : ExtendM \u03b1 := do\n  withBackTrackingScope do\n    withNewCandidates (alt.getParams.map (\u00b7.fvarId)) do\n      x\n\n/--\nUse all of the above functions to find free variables declared outside\nof join points that said join points can be reasonaly extended by. Reasonable\nmeaning that in case the current join point is nested within a function\ndeclaration we will not extend it by free variables declared before the\nfunction declaration because we cannot lift join points outside of function\ndeclarations.\n\nAll of this is done to eliminate dependencies of join points onto their\nposition within the code so we can pull them out as far as possible, hopefully\nenabling new inlining possibilities in the next simplifier run.\n-/\npartial def extend (decl : Decl) : CompilerM Decl := do\n  let newValue \u2190 go decl.value |>.run {} |>.run' {} |>.run' {}\n  let decl := { decl with value := newValue }\n  decl.pullFunDecls\nwhere\n  goFVar (fvar : FVarId) : ExtendM FVarId := do\n    extendByIfNecessary fvar\n    replaceFVar fvar\n  go (code : Code) : ExtendM Code := do\n    match code with\n    | .let decl k =>\n      let decl \u2190 decl.updateValue (\u2190 mapFVarM goFVar decl.value)\n      withNewCandidate decl.fvarId do\n        return Code.updateLet! code decl (\u2190 go k)\n    | .jp decl k =>\n      let decl \u2190 withNewJpScope decl do\n        let value \u2190 go decl.value\n        let additionalParams := (\u2190 get).fvarMap.find! decl.fvarId |>.toArray |>.map Prod.snd\n        let newType := additionalParams.foldr (init := decl.type) (fun val acc => .forallE val.binderName val.type acc .default)\n        decl.update newType (additionalParams ++ decl.params) value\n      mergeJpContextIfNecessary decl.fvarId\n      withNewCandidate decl.fvarId do\n        return Code.updateFun! code decl (\u2190 go k)\n    | .fun decl k =>\n      let decl \u2190 withNewFunScope decl do\n        decl.updateValue (\u2190 go decl.value)\n      withNewCandidate decl.fvarId do\n        return Code.updateFun! code decl (\u2190 go k)\n    | .cases cs =>\n      extendByIfNecessary cs.discr\n      let discr \u2190 replaceFVar cs.discr\n      let visitor := fun alt => do\n        withNewAltScope alt do\n          alt.mapCodeM go\n      let alts \u2190 cs.alts.mapM visitor\n      return Code.updateCases! code cs.resultType discr alts\n    | .jmp fn args =>\n      let mut newArgs \u2190 args.mapM (mapFVarM goFVar)\n      let additionalArgs := (\u2190 get).fvarMap.find! fn |>.toArray |>.map Prod.fst\n      if let some _currentJp := (\u2190 read).currentJp? then\n        let f := fun arg => do\n          return .fvar (\u2190 goFVar arg)\n        newArgs := (\u2190additionalArgs.mapM f) ++ newArgs\n      else\n        newArgs := (additionalArgs.map .fvar) ++ newArgs\n      return Code.updateJmp! code fn newArgs\n    | .return var =>\n      extendByIfNecessary var\n      return Code.updateReturn! code (\u2190 replaceFVar var)\n    | .unreach .. => return code\n\nend JoinPointContextExtender\n\nnamespace JoinPointCommonArgs\n\n/--\nContext for `ReduceAnalysisM`.\n-/\nstructure AnalysisCtx where\n  /--\n  The variables that are in scope at the time of the definition of\n  the join point.\n  -/\n  jpScopes : FVarIdMap FVarIdSet := {}\n\n/--\nState for `ReduceAnalysisM`.\n-/\nstructure AnalysisState where\n  /--\n  A map, that for each join point id contains a map from all (so far)\n  duplicated argument ids to the respective duplicate value\n  -/\n  jpJmpArgs : FVarIdMap FVarSubst := {}\n\nabbrev ReduceAnalysisM := ReaderT AnalysisCtx StateRefT AnalysisState ScopeM\nabbrev ReduceActionM := ReaderT AnalysisState CompilerM\n\ndef isInJpScope (jp : FVarId) (var : FVarId) : ReduceAnalysisM Bool := do\n  return (\u2190 read).jpScopes.find! jp |>.contains var\n\nopen ScopeM\n\n/--\nTake a look at each join point and each of their call sites. If all\ncall sites of a join point have one or more arguments in common, for example:\n```\njp _jp.1 a b c => ...\n...\ncases foo\n| n1 => jmp _jp.1 d e f\n| n2 => jmp _jp.1 g e h\n```\nWe can get rid of the common argument in favour of inlining it directly\ninto the join point (in this case the `e`). This reduces the amount of\narguments we have to pass around drastically for example in `ReaderT` based\nmonad stacks.\n\nNote 1: This transformation can in certain niche cases obtain better results.\nFor example:\n```\njp foo a b => ..\nlet x := ...\ncases discr\n| n1 => jmp foo x y\n| n2 => jmp foo x z\n```\nHere we will not collapse the `x` since it is defined after the join point `foo`\nand thus not accessible for substitution yet. We could however reorder the code in\nsuch a way that this is possible, this is currently not done since we observe\nthan in praxis most of the applications of this transformation can occur naturally\nwithout reordering.\n\nNote 2: This transformation is kind of the opposite of `JoinPointContextExtender`.\nHowever we still benefit from the extender because in the `simp` run after it\nwe might be able to pull join point declarations further up in the hierarchy\nof nested functions/join points which in turn might enable additional optimizations.\nAfter we have performed all of these optimizations we can take away the\n(remaining) common arguments and end up with nicely floated and optimized\ncode that has as little arguments as possible in the join points.\n-/\npartial def reduce (decl : Decl) : CompilerM Decl := do\n  let (_, analysis) \u2190 goAnalyze decl.value |>.run {} |>.run {} |>.run' {}\n  let newValue \u2190 goReduce decl.value |>.run analysis\n  return { decl with value := newValue }\nwhere\n  goAnalyzeFunDecl (fn : FunDecl) : ReduceAnalysisM Unit := do\n    withNewScope do\n      fn.params.forM (addToScope \u00b7.fvarId)\n      goAnalyze fn.value\n\n  goAnalyze (code : Code) : ReduceAnalysisM Unit := do\n    match code with\n    | .let decl k =>\n      addToScope decl.fvarId\n      goAnalyze k\n    | .jp decl k =>\n      goAnalyzeFunDecl decl\n      let scope \u2190 getScope\n      withReader (fun ctx => { ctx with jpScopes := ctx.jpScopes.insert decl.fvarId scope }) do\n        addToScope decl.fvarId\n        goAnalyze k\n    | .fun decl k =>\n      goAnalyzeFunDecl decl\n      addToScope decl.fvarId\n      goAnalyze k\n    | .cases cs =>\n      let visitor alt := do\n        withNewScope do\n          alt.getParams.forM (addToScope \u00b7.fvarId)\n          goAnalyze alt.getCode\n      cs.alts.forM visitor\n    | .jmp fn args =>\n      let decl \u2190 getFunDecl fn\n      if let some knownArgs := (\u2190 get).jpJmpArgs.find? fn then\n        let mut newArgs := knownArgs\n        for (param, arg) in decl.params.zip args do\n          if let some knownVal := newArgs.find? param.fvarId then\n            if arg.toExpr != knownVal then\n              newArgs := newArgs.erase param.fvarId\n        modify fun s => { s with jpJmpArgs := s.jpJmpArgs.insert fn newArgs }\n      else\n        let folder := fun acc (param, arg) => do\n          if (\u2190 allFVarM (isInJpScope fn) arg) then\n            return acc.insert param.fvarId arg.toExpr\n          else\n            return acc\n        let interestingArgs \u2190 decl.params.zip args |>.foldlM (init := {}) folder\n        modify fun s => { s with jpJmpArgs := s.jpJmpArgs.insert fn interestingArgs }\n    | .return .. | .unreach .. => return ()\n\n  goReduce (code : Code) : ReduceActionM Code := do\n    match code with\n    | .jp decl k =>\n      if let some reducibleArgs := (\u2190 read).jpJmpArgs.find? decl.fvarId then\n        let filter param := do\n          let erasable := reducibleArgs.contains param.fvarId\n          if erasable then\n            eraseParam param\n          return !erasable\n        let newParams \u2190 decl.params.filterM filter\n        let mut newValue \u2190 goReduce decl.value\n        newValue \u2190 replaceFVars newValue reducibleArgs false\n        let newType \u2190\n          if newParams.size != decl.params.size then\n            mkForallParams newParams (\u2190 newValue.inferType)\n          else\n            pure decl.type\n        let k \u2190 goReduce k\n        let decl \u2190 decl.update newType newParams newValue\n        return Code.updateFun! code decl k\n      else\n        return Code.updateFun! code decl (\u2190 goReduce k)\n    | .jmp fn args =>\n      let reducibleArgs := (\u2190 read).jpJmpArgs.find! fn\n      let decl \u2190 getFunDecl fn\n      let newParams := decl.params.zip args\n        |>.filter (!reducibleArgs.contains \u00b7.fst.fvarId)\n        |>.map Prod.snd\n      return Code.updateJmp! code fn newParams\n    | .let decl k =>\n      return Code.updateLet! code decl (\u2190 goReduce k)\n    | .fun decl k =>\n      let decl \u2190 decl.updateValue (\u2190 goReduce decl.value)\n      return Code.updateFun! code decl (\u2190 goReduce k)\n    | .cases cs =>\n      let alts \u2190 cs.alts.mapM (\u00b7.mapCodeM goReduce)\n      return Code.updateCases! code cs.resultType cs.discr alts\n    | .return .. | .unreach .. => return code\n\nend JoinPointCommonArgs\n\n/--\nFind all `fun` declarations in `decl` that qualify as join points then replace\ntheir definitions and call sites with `jp`/`jmp`.\n-/\ndef Decl.findJoinPoints (decl : Decl) : CompilerM Decl := do\n  let findResult \u2190 JoinPointFinder.find decl\n  trace[Compiler.findJoinPoints] \"Found: {findResult.candidates.size} jp candidates\"\n  JoinPointFinder.replace decl findResult\n\ndef findJoinPoints : Pass :=\n  .mkPerDeclaration `findJoinPoints Decl.findJoinPoints .base\n\nbuiltin_initialize\n  registerTraceClass `Compiler.findJoinPoints (inherited := true)\n\ndef Decl.extendJoinPointContext (decl : Decl) : CompilerM Decl := do\n  JoinPointContextExtender.extend decl\n\ndef extendJoinPointContext (occurrence : Nat := 0) (phase := Phase.mono) (_h : phase \u2260 .base := by simp): Pass :=\n  .mkPerDeclaration `extendJoinPointContext Decl.extendJoinPointContext phase (occurrence := occurrence)\n\nbuiltin_initialize\n  registerTraceClass `Compiler.extendJoinPointContext (inherited := true)\n\ndef Decl.commonJoinPointArgs (decl : Decl) : CompilerM Decl := do\n  JoinPointCommonArgs.reduce decl\n\ndef commonJoinPointArgs : Pass :=\n  .mkPerDeclaration `commonJoinPointArgs Decl.commonJoinPointArgs .mono\n\nbuiltin_initialize\n  registerTraceClass `Compiler.commonJoinPointArgs (inherited := true)\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/JoinPoints.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15203223778010538, "lm_q2_score": 0.03461883946167883, "lm_q1q2_score": 0.005263179632709252}}
{"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, Sebastian Ullrich\n-/\nimport Lean.ResolveName\nimport Lean.Util.Sorry\nimport Lean.Util.ReplaceExpr\nimport Lean.Structure\nimport Lean.Meta.ExprDefEq\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.SynthInstance\nimport Lean.Meta.CollectMVars\nimport Lean.Meta.Coe\nimport Lean.Meta.Tactic.Util\nimport Lean.Hygiene\nimport Lean.Util.RecDepth\nimport Lean.Elab.Log\nimport Lean.Elab.Level\nimport Lean.Elab.Attributes\nimport Lean.Elab.AutoBound\nimport Lean.Elab.InfoTree\nimport Lean.Elab.Open\nimport Lean.Elab.SetOption\n\nnamespace Lean.Elab.Term\n/-\n  Set isDefEq configuration for the elaborator.\n  Note that we enable all approximations but `quasiPatternApprox`\n\n  In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.\n  The example:\n  ```\n  def ex : StateT \u03b4 (StateT \u03c3 Id) \u03c3 :=\n  monadLift (get : StateT \u03c3 Id \u03c3)\n  ```\n  demonstrates why it produces counterintuitive behavior.\n  We have the `Monad-lift` application:\n  ```\n  @monadLift ?m ?n ?c ?\u03b1 (get : StateT \u03c3 id \u03c3) : ?n ?\u03b1\n  ```\n  It produces the following unification problem when we process the expected type:\n  ```\n  ?n ?\u03b1 =?= StateT \u03b4 (StateT \u03c3 id) \u03c3\n  ==> (approximate using first-order unification)\n  ?n := StateT \u03b4 (StateT \u03c3 id)\n  ?\u03b1 := \u03c3\n  ```\n  Then, we need to solve:\n  ```\n  ?m ?\u03b1 =?= StateT \u03c3 id \u03c3\n  ==> instantiate metavars\n  ?m \u03c3 =?= StateT \u03c3 id \u03c3\n  ==> (approximate since it is a quasi-pattern unification constraint)\n  ?m := fun \u03c3 => StateT \u03c3 id \u03c3\n  ```\n  Note that the constraint is not a Milner pattern because \u03c3 is in\n  the local context of `?m`. We are ignoring the other possible solutions:\n  ```\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3' id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3'\n  ```\n\n  We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).\n\n  If we had use first-order unification, then we would have produced\n  the right answer: `?m := StateT \u03c3 id`\n\n  Haskell would work on this example since it always uses\n  first-order unification.\n-/\ndef setElabConfig (cfg : Meta.Config) : Meta.Config :=\n  { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }\n\nstructure Context where\n  fileName        : String\n  fileMap         : FileMap\n  declName?       : Option Name     := none\n  macroStack      : MacroStack      := []\n  currMacroScope  : MacroScope      := firstFrontendMacroScope\n  /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.\n     The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in\n     the list of pending synthetic metavariables, and returns `?m`. -/\n  mayPostpone     : Bool            := true\n  /- When `errToSorry` is set to true, the method `elabTerm` catches\n     exceptions and converts them into synthetic `sorry`s.\n     The implementation of choice nodes and overloaded symbols rely on the fact\n     that when `errToSorry` is set to false for an elaboration function `F`, then\n     `errToSorry` remains `false` for all elaboration functions invoked by `F`.\n     That is, it is safe to transition `errToSorry` from `true` to `false`, but\n     we must not set `errToSorry` to `true` when it is currently set to `false`. -/\n  errToSorry      : Bool            := true\n  /- When `autoBoundImplicit` is set to true, instead of producing\n     an \"unknown identifier\" error for unbound variables, we generate an\n     internal exception. This exception is caught at `elabBinders` and\n     `elabTypeWithUnboldImplicit`. Both methods add implicit declarations\n     for the unbound variable and try again. -/\n  autoBoundImplicit  : Bool            := false\n  autoBoundImplicits : Std.PArray Expr := {}\n  /-- Map from user name to internal unique name -/\n  sectionVars        : NameMap Name    := {}\n  /-- Map from internal name to fvar -/\n  sectionFVars       : NameMap Expr    := {}\n  /-- Enable/disable implicit lambdas feature. -/\n  implicitLambda     : Bool            := true\n\n/-- Saved context for postponed terms and tactics to be executed. -/\nstructure SavedContext where\n  declName?  : Option Name\n  options    : Options\n  openDecls  : List OpenDecl\n  macroStack : MacroStack\n  errToSorry : Bool\n\n/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/\ninductive SyntheticMVarKind where\n  -- typeclass instance search\n  | typeClass\n  /- Similar to typeClass, but error messages are different.\n     if `f?` is `some f`, we produce an application type mismatch error message.\n     Otherwise, if `header?` is `some header`, we generate the error `(header ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)`\n     Otherwise, we generate the error `(\"type mismatch\" ++ e ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)` -/\n  | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)\n  -- tactic block execution\n  | tactic (tacticCode : Syntax) (ctx : SavedContext)\n  -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)\n  | postponed (ctx : SavedContext)\n\ninstance : ToString SyntheticMVarKind where\n  toString\n    | SyntheticMVarKind.typeClass    => \"typeclass\"\n    | SyntheticMVarKind.coe ..       => \"coe\"\n    | SyntheticMVarKind.tactic ..    => \"tactic\"\n    | SyntheticMVarKind.postponed .. => \"postponed\"\n\nstructure SyntheticMVarDecl where\n  mvarId : MVarId\n  stx : Syntax\n  kind : SyntheticMVarKind\n\ninductive MVarErrorKind where\n  | implicitArg (ctx : Expr)\n  | hole\n  | custom (msgData : MessageData)\n\ninstance : ToString MVarErrorKind where\n  toString\n    | MVarErrorKind.implicitArg ctx => \"implicitArg\"\n    | MVarErrorKind.hole            => \"hole\"\n    | MVarErrorKind.custom msg      => \"custom\"\n\nstructure MVarErrorInfo where\n  mvarId    : MVarId\n  ref       : Syntax\n  kind      : MVarErrorKind\n\nstructure LetRecToLift where\n  ref            : Syntax\n  fvarId         : FVarId\n  attrs          : Array Attribute\n  shortDeclName  : Name\n  declName       : Name\n  lctx           : LocalContext\n  localInstances : LocalInstances\n  type           : Expr\n  val            : Expr\n  mvarId         : MVarId\n\nstructure State where\n  levelNames        : List Name       := []\n  syntheticMVars    : List SyntheticMVarDecl := []\n  mvarErrorInfos    : List MVarErrorInfo := []\n  messages          : MessageLog := {}\n  letRecsToLift     : List LetRecToLift := []\n  infoState         : InfoState := {}\n  deriving Inhabited\n\nabbrev TermElabM := ReaderT Context $ StateRefT State MetaM\nabbrev TermElab  := Syntax \u2192 Option Expr \u2192 TermElabM Expr\n\n-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the\n-- whole monad stack at every use site. May eventually be covered by `deriving`.\ninstance : Monad TermElabM := { inferInstanceAs (Monad TermElabM) with }\n\nopen Meta\n\ninstance : Inhabited (TermElabM \u03b1) where\n  default := throw arbitrary\n\nstructure SavedState where\n  meta   : Meta.SavedState\n  \u00abelab\u00bb : State\n  deriving Inhabited\n\nprotected def saveState : TermElabM SavedState := do\n  pure { meta := (\u2190 Meta.saveState), \u00abelab\u00bb := (\u2190 get) }\n\ndef SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do\n  let traceState \u2190 getTraceState -- We never backtrack trace message\n  let infoState := (\u2190 get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false`\n  s.meta.restore\n  set s.elab\n  setTraceState traceState\n  unless restoreInfo do\n    modify fun s => { s with infoState := infoState }\n\ninstance : MonadBacktrack SavedState TermElabM where\n  saveState      := Term.saveState\n  restoreState b := b.restore\n\nabbrev TermElabResult (\u03b1 : Type) := EStateM.Result Exception SavedState \u03b1\n\ninstance [Inhabited \u03b1] : Inhabited (TermElabResult \u03b1) where\n  default := EStateM.Result.ok arbitrary arbitrary\n\ndef setMessageLog (messages : MessageLog) : TermElabM Unit :=\n  modify fun s => { s with messages := messages }\n\ndef resetMessageLog : TermElabM Unit :=\n  setMessageLog {}\n\ndef getMessageLog : TermElabM MessageLog :=\n  return (\u2190 get).messages\n\n/--\n  Execute `x`, save resulting expression and new state.\n  We remove any `Info` created by `x`.\n  The info nodes are committed when we execute `applyResult`.\n  We use `observing` to implement overloaded notation and decls.\n  We want to save `Info` nodes for the chosen alternative.\n-/\ndef observing (x : TermElabM \u03b1) : TermElabM (TermElabResult \u03b1) := do\n  let s \u2190 saveState\n  try\n    let e \u2190 x\n    let sNew \u2190 saveState\n    s.restore (restoreInfo := true)\n    pure (EStateM.Result.ok e sNew)\n  catch\n    | ex@(Exception.error _ _) =>\n      let sNew \u2190 saveState\n      s.restore (restoreInfo := true)\n      pure (EStateM.Result.error ex sNew)\n    | ex@(Exception.internal id _) =>\n      if id == postponeExceptionId then\n        s.restore (restoreInfo := true)\n      throw ex\n\n/--\n  Apply the result/exception and state captured with `observing`.\n  We use this method to implement overloaded notation and symbols. -/\ndef applyResult (result : TermElabResult \u03b1) : TermElabM \u03b1 :=\n  match result with\n  | EStateM.Result.ok a r     => do r.restore (restoreInfo := true); pure a\n  | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex\n\n/--\n  Execute `x`, but keep state modifications only if `x` did not postpone.\n  This method is useful to implement elaboration functions that cannot decide whether\n  they need to postpone or not without updating the state. -/\ndef commitIfDidNotPostpone (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  -- We just reuse the implementation of `observing` and `applyResult`.\n  let r \u2190 observing x\n  applyResult r\n\ndef getLevelNames : TermElabM (List Name) :=\n  return (\u2190 get).levelNames\n\ndef getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do\n  match (\u2190 getLCtx).find? fvar.fvarId! with\n  | some d => pure d\n  | none   => unreachable!\n\ninstance : AddErrorMessageContext TermElabM where\n  add ref msg := do\n    let ctx \u2190 read\n    let ref := getBetterRef ref ctx.macroStack\n    let msg \u2190 addMessageContext msg\n    let msg \u2190 addMacroStack msg ctx.macroStack\n    pure (ref, msg)\n\ninstance : MonadLog TermElabM where\n  getRef      := getRef\n  getFileMap  := return (\u2190 read).fileMap\n  getFileName := return (\u2190 read).fileName\n  logMessage msg := do\n    let ctx \u2190 readThe Core.Context\n    let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };\n    modify fun s => { s with messages := s.messages.add msg }\n\nprotected def getCurrMacroScope : TermElabM MacroScope := do pure (\u2190 read).currMacroScope\nprotected def getMainModule     : TermElabM Name := do pure (\u2190 getEnv).mainModule\n\nprotected def withFreshMacroScope (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let fresh \u2190 modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))\n  withReader (fun ctx => { ctx with currMacroScope := fresh }) x\n\ninstance : MonadQuotation TermElabM where\n  getCurrMacroScope   := Term.getCurrMacroScope\n  getMainModule       := Term.getMainModule\n  withFreshMacroScope := Term.withFreshMacroScope\n\ninstance : MonadInfoTree TermElabM where\n  getInfoState      := return (\u2190 get).infoState\n  modifyInfoState f := modify fun s => { s with infoState := f s.infoState }\n\n/--\n  Execute `x` but discard changes performed at `Term.State` and `Meta.State`.\n  Recall that the environment is at `Core.State`. Thus, any updates to it will\n  be preserved. This method is useful for performing computations where all\n  metavariable must be resolved or discarded.\n  The info trees are not discarded, however, and wrapped in `InfoTree.Context`\n  to store their metavariable context. -/\ndef withoutModifyingElabMetaStateWithInfo (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let s \u2190 get\n  let sMeta \u2190 getThe Meta.State\n  try\n     withSaveInfoContext x\n  finally\n    modify ({ s with infoState := \u00b7.infoState })\n    set sMeta\n\nunsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=\n  mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab \"term\"\n\n@[implementedBy mkTermElabAttributeUnsafe]\nconstant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)\n\nbuiltin_initialize termElabAttribute : KeyedDeclsAttribute TermElab \u2190 mkTermElabAttribute\n\n/--\n  Auxiliary datatatype for presenting a Lean lvalue modifier.\n  We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.\n  Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list\n  `[LVal.fieldName \"foo\", LVal.getOp i, LVal.fieldIdx 1]`.\n  Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/\ninductive LVal where\n  | fieldIdx  (ref : Syntax) (i : Nat)\n    /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name.\n       `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/\n  | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)\n  | getOp     (ref : Syntax) (idx : Syntax)\n\ndef LVal.getRef : LVal \u2192 Syntax\n  | LVal.fieldIdx ref _    => ref\n  | LVal.fieldName ref ..  => ref\n  | LVal.getOp ref _       => ref\n\ndef LVal.isFieldName : LVal \u2192 Bool\n  | LVal.fieldName .. => true\n  | _ => false\n\ninstance : ToString LVal where\n  toString\n    | LVal.fieldIdx _ i     => toString i\n    | LVal.fieldName _ n .. => n\n    | LVal.getOp _ idx      => \"[\" ++ toString idx ++ \"]\"\n\ndef getDeclName? : TermElabM (Option Name) := return (\u2190 read).declName?\ndef getLetRecsToLift : TermElabM (List LetRecToLift) := return (\u2190 get).letRecsToLift\ndef isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (\u2190 getMCtx).isExprAssigned mvarId\ndef getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (\u2190 getMCtx).getDecl mvarId\ndef assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }\n\ndef withDeclName (name : Name) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with declName? := name }) x\n\ndef setLevelNames (levelNames : List Name) : TermElabM Unit :=\n  modify fun s => { s with levelNames := levelNames }\n\ndef withLevelNames (levelNames : List Name) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let levelNamesSaved \u2190 getLevelNames\n  setLevelNames levelNames\n  try x finally setLevelNames levelNamesSaved\n\ndef withoutErrToSorry (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with errToSorry := false }) x\n\n/-- For testing `TermElabM` methods. The #eval command will sign the error. -/\ndef throwErrorIfErrors : TermElabM Unit := do\n  if (\u2190 get).messages.hasErrors then\n    throwError \"Error(s)\"\n\ndef traceAtCmdPos (cls : Name) (msg : Unit \u2192 MessageData) : TermElabM Unit :=\n  withRef Syntax.missing $ trace cls msg\n\ndef ppGoal (mvarId : MVarId) : TermElabM Format :=\n  Meta.ppGoal mvarId\n\nopen Level (LevelElabM)\n\ndef liftLevelM (x : LevelElabM \u03b1) : TermElabM \u03b1 := do\n  let ctx \u2190 read\n  let mctx \u2190 getMCtx\n  let ngen \u2190 getNGen\n  let lvlCtx : Level.Context := { options := (\u2190 getOptions), ref := (\u2190 getRef), autoBoundImplicit := ctx.autoBoundImplicit }\n  match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (\u2190 getLevelNames) } with\n  | EStateM.Result.ok a newS  => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a\n  | EStateM.Result.error ex _ => throw ex\n\ndef elabLevel (stx : Syntax) : TermElabM Level :=\n  liftLevelM $ Level.elabLevel stx\n\n/- Elaborate `x` with `stx` on the macro stack -/\ndef withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withMacroExpansionInfo beforeStx afterStx do\n    withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x\n\n/-\n  Add the given metavariable to the list of pending synthetic metavariables.\n  The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/\ndef registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }\n\ndef registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  registerSyntheticMVar (\u2190 getRef) mvarId kind\n\ndef registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do\n  modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos }\n\ndef registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do\n  modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos }\n\ndef registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do\n  modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos }\n\ndef registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=\n  match e.getAppFn with\n  | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData\n  | _ => pure ()\n\n/-\n  Auxiliary method for reporting errors of the form \"... contains metavariables ...\".\n  This kind of error is thrown, for example, at `Match.lean` where elaboration\n  cannot continue if there are metavariables in patterns.\n  We only want to log it if we haven't logged any error so far. -/\ndef throwMVarError (m : MessageData) : TermElabM \u03b1 := do\n  if (\u2190 get).messages.hasErrors then\n    throwAbortTerm\n  else\n    throwError m\n\ndef MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do\n  match mvarErrorInfo.kind with\n  | MVarErrorKind.implicitArg app => do\n    let app \u2190 instantiateMVars app\n    let msg : MessageData := m!\"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}\"\n    let msg := msg ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\n  | MVarErrorKind.hole => do\n    let msg : MessageData := \"don't know how to synthesize placeholder\"\n    let msg := msg ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)\n  | MVarErrorKind.custom msg =>\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\nwhere\n  appendExtra (msg : MessageData) : MessageData :=\n    match extraMsg? with\n    | none => msg\n    | some extraMsg => msg ++ extraMsg\n\n/--\n  Try to log errors for the unassigned metavariables `pendingMVarIds`.\n\n  Return `true` if there were \"unfilled holes\", and we should \"abort\" declaration.\n  TODO: try to fill \"all\" holes using synthetic \"sorry's\"\n\n  Remark: We only log the \"unfilled holes\" as new errors if no error has been logged so far. -/\ndef logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do\n  let s \u2190 get\n  let hasOtherErrors := s.messages.hasErrors\n  let mut hasNewErrors := false\n  let mut alreadyVisited : NameSet := {}\n  for mvarErrorInfo in s.mvarErrorInfos do\n    let mvarId := mvarErrorInfo.mvarId\n    unless alreadyVisited.contains mvarId do\n      alreadyVisited := alreadyVisited.insert mvarId\n      let foundError \u2190 withMVarContext mvarId do\n        /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or\n           delayed assigned to another metavariable that is unassigned. -/\n        let mvarDeps \u2190 getMVars (mkMVar mvarId)\n        if mvarDeps.any pendingMVarIds.contains then do\n          unless hasOtherErrors do\n            mvarErrorInfo.logError extraMsg?\n          pure true\n        else\n          pure false\n      if foundError then\n        hasNewErrors := true\n  return hasNewErrors\n\n/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/\ndef ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do\n  let pendingMVarIds \u2190 getMVarsAtDecl decl\n  if (\u2190 logUnassignedUsingErrorInfos pendingMVarIds) then\n    throwAbortCommand\n\n/-\n  Execute `x` without allowing it to postpone elaboration tasks.\n  That is, `tryPostpone` is a noop. -/\ndef withoutPostponing (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with mayPostpone := false }) x\n\n/-- Creates syntax for `(` <ident> `:` <type> `)` -/\ndef mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=\n  mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom \"(\", mkNullNode #[ident], mkNullNode #[mkAtom \":\", type], mkNullNode, mkAtom \")\"]\n\n/--\n  Convert unassigned universe level metavariables into parameters.\n  The new parameter names are of the form `u_i` where `i >= nextParamIdx`.\n  The method returns the updated expression and new `nextParamIdx`.\n\n  Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/\ndef levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr \u00d7 Nat) := do\n  let mctx \u2190 getMCtx\n  let levelNames \u2190 getLevelNames\n  let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx\n  setMCtx r.mctx\n  pure (r.expr, r.nextParamIdx)\n\n/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/\ndef levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do\n  let nextParamIdx \u2190 get\n  let (e, nextParamIdx) \u2190 levelMVarToParam e nextParamIdx\n  set nextParamIdx\n  pure e\n\n/--\n  Auxiliary method for creating fresh binder names.\n  Do not confuse with the method for creating fresh free/meta variable ids. -/\ndef mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=\n  withFreshMacroScope $ MonadQuotation.addMacroScope `x\n\n/--\n  Auxiliary method for creating a `Syntax.ident` containing\n  a fresh name. This method is intended for creating fresh binder names.\n  It is just a thin layer on top of `mkFreshUserName`. -/\ndef mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax :=\n  return mkIdentFrom ref (\u2190 mkFreshBinderName)\n\nprivate def applyAttributesCore\n    (declName : Name) (attrs : Array Attribute)\n    (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=\n  for attr in attrs do\n    let env \u2190 getEnv\n    match getAttributeImpl env attr.name with\n    | Except.error errMsg => throwError errMsg\n    | Except.ok attrImpl  =>\n      match applicationTime? with\n      | none => attrImpl.add declName attr.stx attr.kind\n      | some applicationTime =>\n        if applicationTime == attrImpl.applicationTime then\n          attrImpl.add declName attr.stx attr.kind\n\n/-- Apply given attributes **at** a given application time -/\ndef applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=\n  applyAttributesCore declName attrs applicationTime\n\ndef applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=\n  applyAttributesCore declName attrs none\n\ndef mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do\n  let header : MessageData := match header? with\n    | some header => m!\"{header} \"\n    | none        => m!\"type mismatch{indentExpr e}\\n\"\n  return m!\"{header}{\u2190 mkHasTypeButIsExpectedMsg eType expectedType}\"\n\ndef throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM \u03b1 := do\n  /-\n    We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was\n    always of the form:\n    ```\n    failed to synthesize instance\n      CoeT <eType> <e> <expectedType>\n    ```\n    We should revisit this decision in the future and decide whether it may contain useful information\n    or not. -/\n  let extraMsg := Format.nil\n  /-\n  let extraMsg : MessageData := match extraMsg? with\n    | none          => Format.nil\n    | some extraMsg => Format.line ++ extraMsg;\n  -/\n  match f? with\n  | none   => throwError \"{\u2190 mkTypeMismatchError header? e eType expectedType}{extraMsg}\"\n  | some f => Meta.throwAppTypeMismatch f e extraMsg\n\ndef withoutMacroStackAtErr (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x\n\n/- Try to synthesize metavariable using type class resolution.\n   This method assumes the local context and local instances of `instMVar` coincide\n   with the current local context and local instances.\n   Return `true` if the instance was synthesized successfully, and `false` if\n   the instance contains unassigned metavariables that are blocking the type class\n   resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/\ndef synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do\n  let instMVarDecl \u2190 getMVarDecl instMVar\n  let type := instMVarDecl.type\n  let type \u2190 instantiateMVars type\n  let result \u2190 trySynthInstance type maxResultSize?\n  match result with\n  | LOption.some val =>\n    if (\u2190 isExprMVarAssigned instMVar) then\n      let oldVal \u2190 instantiateMVars (mkMVar instMVar)\n      unless (\u2190 isDefEq oldVal val) do\n        let oldValType \u2190 inferType oldVal\n        let valType \u2190 inferType val\n        unless (\u2190 isDefEq oldValType valType) do\n          throwError \"synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\\nhas type{indentExpr valType}\\nexpected{indentExpr oldValType}\"\n        throwError \"synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\\ninferred{indentExpr oldVal}\"\n    else\n      unless (\u2190 isDefEq (mkMVar instMVar) val) do\n        throwError \"failed to assign synthesized type class instance{indentExpr val}\"\n    pure true\n  | LOption.undef    => pure false -- we will try later\n  | LOption.none     => throwError \"failed to synthesize instance{indentExpr type}\"\n\nregister_builtin_option autoLift : Bool := {\n  defValue := true\n  descr    := \"insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed\"\n}\n\nregister_builtin_option maxCoeSize : Nat := {\n  defValue := 16\n  descr    := \"maximum number of instances used to construct an automatic coercion\"\n}\n\ndef synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do\n  synthesizeInstMVarCore instMVar (some (maxCoeSize.get (\u2190 getOptions)))\n\n/-\nThe coercion from `\u03b1` to `Thunk \u03b1` cannot be implemented using an instance because it would\neagerly evaluate `e` -/\ndef tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do\n  match expectedType with\n  | Expr.app (Expr.const ``Thunk u _) arg _ =>\n    if (\u2190 isDefEq eType arg) then\n      pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e)))\n    else\n      pure none\n  | _ =>\n    pure none\n\n/--\n  Try to apply coercion to make sure `e` has type `expectedType`.\n  Relevant definitions:\n  ```\n  class CoeT (\u03b1 : Sort u) (a : \u03b1) (\u03b2 : Sort v)\n  abbrev coe {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeT \u03b1 a \u03b2] : \u03b2\n  ```\n-/\nprivate def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do\n  if (\u2190 isDefEq expectedType eType) then\n    return e\n  else match (\u2190 tryCoeThunk? expectedType eType e) with\n    | some r => return r\n    | none   =>\n      let u \u2190 getLevel eType\n      let v \u2190 getLevel expectedType\n      let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType]\n      let mvar \u2190 mkFreshExprMVar coeTInstType MetavarKind.synthetic\n      let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar]\n      let mvarId := mvar.mvarId!\n      try\n        withoutMacroStackAtErr do\n          if (\u2190 synthesizeCoeInstMVarCore mvarId) then\n            expandCoe eNew\n          else\n            -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe`\n            -- after we syntheze `mvar`\n            let mvarAux \u2190 mkFreshExprMVar expectedType MetavarKind.syntheticOpaque\n            registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?)\n            return mvarAux\n      catch\n        | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg\n        | _                     => throwTypeMismatchError errorMsgHeader? expectedType eType e f?\n\ndef isTypeApp? (type : Expr) : TermElabM (Option (Expr \u00d7 Expr)) := do\n  let type \u2190 withReducible $ whnf type\n  match type with\n  | Expr.app m \u03b1 _ => pure (some ((\u2190 instantiateMVars m), (\u2190 instantiateMVars \u03b1)))\n  | _              => pure none\n\ndef synthesizeInst (type : Expr) : TermElabM Expr := do\n  let type \u2190 instantiateMVars type\n  match (\u2190 trySynthInstance type) with\n  | LOption.some val => pure val\n  | LOption.undef    => throwError \"failed to synthesize instance{indentExpr type}\"\n  | LOption.none     => throwError \"failed to synthesize instance{indentExpr type}\"\n\ndef isMonadApp (type : Expr) : TermElabM Bool := do\n  let some (m, _) \u2190 isTypeApp? type | pure false\n  return (\u2190 isMonad? m) |>.isSome\n\n/--\n  Try to coerce `a : \u03b1` into `m \u03b2` by first coercing `a : \u03b1` into \u2035\u03b2`, and then using `pure`.\n  The method is only applied if `\u03b1` is not monadic (e.g., `Nat \u2192 IO Unit`), and the head symbol\n  of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool \u2192 ?m Nat`).\n\n  The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism\n  do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y`\n  since none of them is polymorphic\n  ```\n  def f (x : Bool) : IO Bool := do\n  let y \u2190 if x == 0 then IO.println \"hello\"; true else false;\n  !y\n  ```\n  On the other hand, the following fails since `+` is polymorphic\n  ```\n  def f (x : Bool) : IO Nat := do\n  IO.prinln x\n  x + x  -- Error: failed to synthesize `Add (IO Nat)`\n  ```\n-/\nprivate def tryPureCoe? (errorMsgHeader? : Option String) (m \u03b2 \u03b1 a : Expr) : TermElabM (Option Expr) :=\n  commitWhenSome? do\n    let doIt : TermElabM (Option Expr) := do\n      try\n        let aNew \u2190 tryCoe errorMsgHeader? \u03b2 \u03b1 a none\n        let aNew \u2190 mkPure m aNew\n        pure (some aNew)\n      catch _ =>\n        pure none\n    forallTelescope \u03b1 fun _ \u03b1 => do\n      if (\u2190 isMonadApp \u03b1) then\n        pure none\n      else if !\u03b1.getAppFn.isMVar  then\n        doIt\n      else\n        pure none\n\n/-\nTry coercions and monad lifts to make sure `e` has type `expectedType`.\n\nIf `expectedType` is of the form `n \u03b2`, we try monad lifts and other extensions.\nOtherwise, we just use the basic `tryCoe`.\n\nExtensions for monads.\n\nGiven an expected type of the form `n \u03b2`, if `eType` is of the form `\u03b1`, but not `m \u03b1`\n\n1 - Try to coerce \u2035\u03b1` into \u2035\u03b2`, and use `pure` to lift it to `n \u03b1`.\n    It only works if `n` implements `Pure`\n\nIf `eType` is of the form `m \u03b1`. We use the following approaches.\n\n1- Try to unify `n` and `m`. If it succeeds, then we use\n   ```\n   coeM {m : Type u \u2192 Type v} {\u03b1 \u03b2 : Type u} [\u2200 a, CoeT \u03b1 a \u03b2] [Monad m] (x : m \u03b1) : m \u03b2\n   ```\n   `n` must be a `Monad` to use this one.\n\n2- If there is monad lift from `m` to `n` and we can unify `\u03b1` and `\u03b2`, we use\n  ```\n  liftM : \u2200 {m : Type u_1 \u2192 Type u_2} {n : Type u_1 \u2192 Type u_3} [self : MonadLiftT m n] {\u03b1 : Type u_1}, m \u03b1 \u2192 n \u03b1\n  ```\n  Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as\n  ```\n  def g (x : Nat) : IO Nat := do\n    IO.println x\n    pure x\n\n  def f {m} [MonadLiftT IO m] : m Nat :=\n    g 10\n\n  ```\n\n3- If there is a monad lif from `m` to `n` and a coercion from `\u03b1` to `\u03b2`, we use\n  ```\n  liftCoeM {m : Type u \u2192 Type v} {n : Type u \u2192 Type w} {\u03b1 \u03b2 : Type u} [MonadLiftT m n] [\u2200 a, CoeT \u03b1 a \u03b2] [Monad n] (x : m \u03b1) : n \u03b2\n  ```\n\nNote that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `\u03b1` to `\u03b2` for all values in `\u03b1`.\nThis is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and\nwe only have a coercion from decidable propositions.  Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`\nusing the instance `pureCoeDepProp`.\n\nNote that, approach 2 is more powerful than `tryCoe`.\nRecall that type class resolution never assigns metavariables created by other modules.\nNow, consider the following scenario\n```lean\ndef g (x : Nat) : IO Nat := ...\ndeg h (x : Nat) : StateT Nat IO Nat := do\nv \u2190 g x;\nIO.Println v;\n...\n```\nLet's assume there is no other occurrence of `v` in `h`.\nThus, we have that the expected of `g x` is `StateT Nat IO ?\u03b1`,\nand the given type is `IO Nat`. So, even if we add a coercion.\n```\ninstance {\u03b1 m n} [MonadLiftT m n] {\u03b1} : Coe (m \u03b1) (n \u03b1) := ...\n```\nIt is not applicable because TC would have to assign `?\u03b1 := Nat`.\nOn the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`\nsince this goal does not contain any metavariables. And then, we\nconvert `g x` into `liftM $ g x`.\n-/\nprivate def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 instantiateMVars expectedType\n  let eType \u2190 instantiateMVars eType\n  let throwMismatch {\u03b1} : TermElabM \u03b1 := throwTypeMismatchError errorMsgHeader? expectedType eType e f?\n  let tryCoeSimple : TermElabM Expr :=\n    tryCoe errorMsgHeader? expectedType eType e f?\n  let some (n, \u03b2) \u2190 isTypeApp? expectedType | tryCoeSimple\n  let tryPureCoeAndSimple : TermElabM Expr := do\n    if autoLift.get (\u2190 getOptions) then\n      match (\u2190 tryPureCoe? errorMsgHeader? n \u03b2 eType e) with\n      | some eNew => pure eNew\n      | none      => tryCoeSimple\n    else\n      tryCoeSimple\n  let some (m, \u03b1) \u2190 isTypeApp? eType | tryPureCoeAndSimple\n  if (\u2190 isDefEq m n) then\n    let some monadInst \u2190 isMonad? n | tryCoeSimple\n    try expandCoe (\u2190 mkAppOptM ``coeM #[m, \u03b1, \u03b2, none, monadInst, e]) catch _ => throwMismatch\n  else if autoLift.get (\u2190 getOptions) then\n    try\n      -- Construct lift from `m` to `n`\n      let monadLiftType \u2190 mkAppM ``MonadLiftT #[m, n]\n      let monadLiftVal  \u2190 synthesizeInst monadLiftType\n      let u_1 \u2190 getDecLevel \u03b1\n      let u_2 \u2190 getDecLevel eType\n      let u_3 \u2190 getDecLevel expectedType\n      let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, \u03b1, e]\n      let eNewType \u2190 inferType eNew\n      if (\u2190 isDefEq expectedType eNewType) then\n        return eNew -- approach 2 worked\n      else\n        let some monadInst \u2190 isMonad? n | tryCoeSimple\n        let u \u2190 getLevel \u03b1\n        let v \u2190 getLevel \u03b2\n        let coeTInstType := Lean.mkForall `a BinderInfo.default \u03b1 $ mkAppN (mkConst ``CoeT [u, v]) #[\u03b1, mkBVar 0, \u03b2]\n        let coeTInstVal \u2190 synthesizeInst coeTInstType\n        let eNew \u2190 expandCoe (\u2190 mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, \u03b1, \u03b2, monadLiftVal, coeTInstVal, monadInst, e])\n        let eNewType \u2190 inferType eNew\n        unless (\u2190 isDefEq expectedType eNewType) do throwMismatch\n        return eNew -- approach 3 worked\n    catch _ =>\n      /-\n        If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`.\n        Otherwise, we just try `tryCoe?`.\n      -/\n      match (\u2190 isMonad? m) with\n      | none   => tryPureCoeAndSimple\n      | some _ => tryCoeSimple\n  else\n    tryCoeSimple\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.\n  If they are not, then try coercions.\n\n  Argument `f?` is used only for generating error messages. -/\ndef ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  match expectedType? with\n  | none              => pure e\n  | some expectedType =>\n    if (\u2190 isDefEq eType expectedType) then\n      pure e\n    else\n      tryLiftAndCoe errorMsgHeader? expectedType eType e f?\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.\n  If they are not, then try coercions. -/\ndef ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=\n  match expectedType? with\n  | none => pure e\n  | _    => do\n    let eType \u2190 inferType e\n    ensureHasTypeAux expectedType? eType e none errorMsgHeader?\n\nprivate def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 match expectedType? with\n    | none              => mkFreshTypeMVar\n    | some expectedType => pure expectedType\n  mkSyntheticSorry expectedType\n\nprivate def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do\n  let syntheticSorry \u2190 mkSyntheticSorryFor expectedType?\n  logException ex\n  pure syntheticSorry\n\n/-- If `mayPostpone == true`, throw `Expection.postpone`. -/\ndef tryPostpone : TermElabM Unit := do\n  if (\u2190 read).mayPostpone then\n    throwPostpone\n\n/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/\ndef tryPostponeIfMVar (e : Expr) : TermElabM Unit := do\n  if e.getAppFn.isMVar then\n    let e \u2190 instantiateMVars e\n    if e.getAppFn.isMVar then\n      tryPostpone\n\ndef tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=\n  match e? with\n  | some e => tryPostponeIfMVar e\n  | none   => tryPostpone\n\ndef tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let some expectedType \u2190 pure expectedType? |\n    throwError \"{msg}, expected type must be known\"\n  let expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasExprMVar then\n    tryPostpone\n    throwError \"{msg}, expected type contains metavariables{indentExpr expectedType}\"\n  pure expectedType\n\ndef saveContext : TermElabM SavedContext :=\n  return {\n    macroStack := (\u2190 read).macroStack\n    declName?  := (\u2190 read).declName?\n    options    := (\u2190 getOptions)\n    openDecls  := (\u2190 getOpenDecls)\n    errToSorry := (\u2190 read).errToSorry\n  }\n\ndef withSavedContext (savedCtx : SavedContext) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|\n    withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls })\n      x\n\nprivate def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  trace[Elab.postpone] \"{stx} : {expectedType?}\"\n  let mvar \u2190 mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque\n  let ctx \u2190 read\n  registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (\u2190 saveContext))\n  pure mvar\n\ndef getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=\n  return (\u2190 get).syntheticMVars.find? fun d => d.mvarId == mvarId\n\ndef mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) : TermElabM (Sum Info MVarId) := do\n  let isHole? : TermElabM (Option MVarId) := do\n    match e with\n    | Expr.mvar mvarId _ =>\n      match (\u2190 getSyntheticMVarDecl? mvarId) with\n      | some { kind := SyntheticMVarKind.tactic .., .. }    => return mvarId\n      | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId\n      | _                                                   => return none\n    | _ => pure none\n  match (\u2190 isHole?) with\n  | none        => return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (\u2190 getLCtx), expr := e, stx, expectedType? }\n  | some mvarId => return Sum.inr mvarId\n\ndef addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) : TermElabM Unit := do\n  withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx?) |> discard\n\n/-\n  Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or\n  an error is found. -/\nprivate def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)\n    : List (KeyedDeclsAttribute.AttributeEntry TermElab) \u2192 TermElabM Expr\n  | []                => do throwError \"unexpected syntax{indentD stx}\"\n  | (elabFn::elabFns) =>\n    try\n      -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`)\n      withInfoContext' (mkInfo := mkTermInfo elabFn.decl (expectedType? := expectedType?) stx)\n        (try\n          elabFn.value stx expectedType?\n        catch ex => match ex with\n          | Exception.error ref msg =>\n            if (\u2190 read).errToSorry then\n              exceptionToSorry ex expectedType?\n            else\n              throw ex\n          | Exception.internal id _ =>\n            if (\u2190 read).errToSorry && id == abortTermExceptionId then\n              exceptionToSorry ex expectedType?\n            else if id == unsupportedSyntaxExceptionId then\n              throw ex  -- to outer try\n            else if catchExPostpone && id == postponeExceptionId then\n              /- If `elab` threw `Exception.postpone`, we reset any state modifications.\n                For example, we want to make sure pending synthetic metavariables created by `elab` before\n                it threw `Exception.postpone` are discarded.\n                Note that we are also discarding the messages created by `elab`.\n\n                For example, consider the expression.\n                `((f.x a1).x a2).x a3`\n                Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.\n                Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`\n                because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and\n                finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would\n                keep \"dead\" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is\n                wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch\n                and new metavariables are created for the nested functions. -/\n              s.restore\n              postponeElabTerm stx expectedType?\n            else\n              throw ex)\n    catch ex => match ex with\n      | Exception.internal id _ =>\n        if id == unsupportedSyntaxExceptionId then\n          s.restore  -- also removes the info tree created above\n          elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n        else\n          throw ex\n      | _ => throw ex\n\nprivate def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do\n  let s \u2190 saveState\n  let k := stx.getKind\n  match termElabAttribute.getEntries (\u2190 getEnv) k with\n  | []      => throwError \"elaboration function for '{k}' has not been implemented{indentD stx}\"\n  | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n\ninstance : MonadMacroAdapter TermElabM where\n  getCurrMacroScope := getCurrMacroScope\n  getNextMacroScope := return (\u2190 getThe Core.State).nextMacroScope\n  setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }\n\nprivate def isExplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(@$f) => true\n  | _      => false\n\nprivate def isExplicitApp (stx : Syntax) : Bool :=\n  stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]\n\n/--\n  Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.\n  Example: `fun {\u03b1} (a : \u03b1) => a` -/\nprivate def isLambdaWithImplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder\n  | _                         => false\n\nprivate partial def dropTermParens : Syntax \u2192 Syntax := fun stx =>\n  match stx with\n  | `(($stx)) => dropTermParens stx\n  | _         => stx\n\nprivate def isHole (stx : Syntax) : Bool :=\n  match stx with\n  | `(_)          => true\n  | `(? _)        => true\n  | `(? $x:ident) => true\n  | _             => false\n\nprivate def isTacticBlock (stx : Syntax) : Bool :=\n  match stx with\n  | `(by $x:tacticSeq) => true\n  | _ => false\n\nprivate def isNoImplicitLambda (stx : Syntax) : Bool :=\n  match stx with\n  | `(noImplicitLambda% $x:term) => true\n  | _ => false\n\nprivate def isTypeAscription (stx : Syntax) : Bool :=\n  match stx with\n  | `(($e : $type)) => true\n  | _               => false\n\ndef mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=\n  mkAnnotation `noImplicitLambda type\n\ndef hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=\n  annotation? `noImplicitLambda type |>.isSome\n\n/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/\ndef blockImplicitLambda (stx : Syntax) : Bool :=\n  let stx := dropTermParens stx\n  -- TODO: make it extensible\n  isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||\n  isNoImplicitLambda stx || isTypeAscription stx\n\n/--\n  Return normalized expected type if it is of the form `{a : \u03b1} \u2192 \u03b2` or `[a : \u03b1] \u2192 \u03b2` and\n  `blockImplicitLambda stx` is not true, else return `none`. -/\nprivate def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=\n  if blockImplicitLambda stx then\n    pure none\n  else match expectedType? with\n    | some expectedType => do\n      if hasNoImplicitLambdaAnnotation expectedType then\n        pure none\n      else\n        let expectedType \u2190 whnfForall expectedType\n        match expectedType with\n        | Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType\n        | _                    => pure none\n    | _         => pure none\n\nprivate def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do\n  match ex with\n  | Exception.error ref msg =>\n    if impFVars.isEmpty then\n      return Exception.error ref msg\n    else\n      let mut msg := m!\"{msg}\\nthe following variables have been introduced by the implicit lamda feature\"\n      for impFVar in impFVars do\n        let auxMsg := m!\"{impFVar} : {\u2190 inferType impFVar}\"\n        let auxMsg \u2190 addMessageContext auxMsg\n        msg := m!\"{msg}{indentD auxMsg}\"\n      msg := m!\"{msg}\\nyou can disable implict lambdas using `@` or writing a lambda expression with `\\{}` or `[]` binder annotations.\"\n      return Exception.error ref msg\n  | _ => return ex\n\nprivate def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do\n  let body \u2190 elabUsingElabFns stx expectedType catchExPostpone\n  try\n    let body \u2190 ensureHasType expectedType body\n    let r \u2190 mkLambdaFVars impFVars body\n    trace[Elab.implicitForall] r\n    pure r\n  catch ex =>\n    throw (\u2190 decorateErrorMessageWithLambdaImplicitVars ex impFVars)\n\nprivate partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=\n  loop type #[]\nwhere\n  loop\n    | type@(Expr.forallE n d b c), fvars =>\n      if c.binderInfo.isExplicit then\n        elabImplicitLambdaAux stx catchExPostpone type fvars\n      else withFreshMacroScope do\n        let n \u2190 MonadQuotation.addMacroScope n\n        withLocalDecl n c.binderInfo d fun fvar => do\n          let type \u2190 whnfForall (b.instantiate1 fvar)\n          loop type (fvars.push fvar)\n    | type, fvars =>\n      elabImplicitLambdaAux stx catchExPostpone type fvars\n\n/- Main loop for `elabTerm` -/\nprivate partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax \u2192 TermElabM Expr\n  | Syntax.missing => mkSyntheticSorryFor expectedType?\n  | stx => withFreshMacroScope <| withIncRecDepth do\n    trace[Elab.step] \"expected type: {expectedType?}, term\\n{stx}\"\n    checkMaxHeartbeats \"elaborator\"\n    withNestedTraces do\n    let env \u2190 getEnv\n    match (\u2190 liftMacroM (expandMacroImpl? env stx)) with\n    | some (decl, stxNew) =>\n      withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <|\n        withMacroExpansion stx stxNew <|\n          withRef stxNew <|\n            elabTermAux expectedType? catchExPostpone implicitLambda stxNew\n    | _ =>\n      let implicit? \u2190 if implicitLambda && (\u2190 read).implicitLambda then useImplicitLambda? stx expectedType? else pure none\n      match implicit? with\n      | some expectedType => elabImplicitLambda stx catchExPostpone expectedType\n      | none              => elabUsingElabFns stx expectedType? catchExPostpone\n\n/-- Store in the `InfoTree` that `e` is a \"dot\"-completion target. -/\ndef addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do\n  addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (\u2190 getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?)\n\n/--\n  Main function for elaborating terms.\n  It extracts the elaboration methods from the environment using the node kind.\n  Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.\n  It creates a fresh macro scope for executing the elaboration method.\n  All unlogged trace messages produced by the elaboration method are logged using\n  the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,\n  the error is logged and a synthetic sorry expression is returned.\n  If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,\n  a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,\n  and returned.\n  The option `catchExPostpone == false` is used to implement `resumeElabTerm`\n  to prevent the creation of another synthetic metavariable when resuming the elaboration.\n\n  If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.\n  We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.\n  -/\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=\n  withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  let e \u2190 elabTerm stx expectedType? catchExPostpone implicitLambda\n  withRef stx <| ensureHasType expectedType? e errorMsgHeader?\n\n/-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/\ndef commitIfNoErrors? (x : TermElabM \u03b1) : TermElabM (Option \u03b1) := do\n  let saved \u2190 saveState\n  modify fun s => { s with messages := {} }\n  try\n    let a \u2190 x\n    if (\u2190 get).messages.hasErrors then\n      restoreState saved\n      return none\n    else\n      modify fun s => { s with messages := saved.elab.messages ++ s.messages }\n      return a\n  catch _ =>\n    restoreState saved\n    return none\n\n/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/\ndef adaptExpander (exp : Syntax \u2192 TermElabM Syntax) : TermElab := fun stx expectedType? => do\n  let stx' \u2190 exp stx\n  withMacroExpansion stx stx' $ elabTerm stx' expectedType?\n\ndef mkInstMVar (type : Expr) : TermElabM Expr := do\n  let mvar \u2190 mkFreshExprMVar type MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  unless (\u2190 synthesizeInstMVarCore mvarId) do\n    registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass\n  pure mvar\n\n/-\n  Relevant definitions:\n  ```\n  class CoeSort (\u03b1 : Sort u) (\u03b2 : outParam (Sort v))\n  abbrev coeSort {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeSort \u03b1 \u03b2] : \u03b2\n  ```\n  -/\nprivate def tryCoeSort (\u03b1 : Expr) (a : Expr) : TermElabM Expr := do\n  let \u03b2 \u2190 mkFreshTypeMVar\n  let u \u2190 getLevel \u03b1\n  let v \u2190 getLevel \u03b2\n  let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[\u03b1, \u03b2]\n  let mvar \u2190 mkFreshExprMVar coeSortInstType MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  try\n    withoutMacroStackAtErr do\n      if (\u2190 synthesizeCoeInstMVarCore mvarId) then\n        expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[\u03b1, \u03b2, a, mvar]\n      else\n        throwError \"type expected\"\n  catch\n    | Exception.error _ msg => throwError \"type expected\\n{msg}\"\n    | _                     => throwError \"type expected\"\n\n/--\n  Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`\n  or is unifiable with `Expr.sort`, or can be coerced into one. -/\ndef ensureType (e : Expr) : TermElabM Expr := do\n  if (\u2190 isType e) then\n    pure e\n  else\n    let eType \u2190 inferType e\n    let u \u2190 mkFreshLevelMVar\n    if (\u2190 isDefEq eType (mkSort u)) then\n      pure e\n    else\n      tryCoeSort eType e\n\n/-- Elaborate `stx` and ensure result is a type. -/\ndef elabType (stx : Syntax) : TermElabM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  let type \u2190 elabTerm stx (mkSort u)\n  withRef stx $ ensureType type\n\n/--\n  Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,\n  a new local declaration is created, registered, and `k` is tried to be executed again. -/\npartial def withAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let flag := autoBoundImplicitLocal.get (\u2190 getOptions)\n  if flag then\n    withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do\n      let rec loop (s : SavedState) : TermElabM \u03b1 := do\n        try\n          k\n        catch\n          | ex => match isAutoBoundImplicitLocalException? ex with\n            | some n =>\n              -- Restore state, declare `n`, and try again\n              s.restore\n              withLocalDecl n BinderInfo.implicit (\u2190 mkFreshTypeMVar) fun x =>\n                withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do\n                  loop (\u2190 saveState)\n            | none   => throw ex\n      loop (\u2190 saveState)\n  else\n    k\n\ndef withoutAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k\n\n/--\n  Return `autoBoundImplicits ++ xs.\n  This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/\ndef addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do\n  let autoBoundImplicits := (\u2190 read).autoBoundImplicits\n  for auto in autoBoundImplicits do\n    let localDecl \u2190 getLocalDecl auto.fvarId!\n    for x in xs do\n      if (\u2190 getMCtx).localDeclDependsOn localDecl x.fvarId! then\n        throwError \"invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'\"\n  return autoBoundImplicits.toArray ++ xs\n\ndef mkAuxName (suffix : Name) : TermElabM Name := do\n  match (\u2190 read).declName? with\n  | none          => throwError \"auxiliary declaration cannot be created when declaration name is not available\"\n  | some declName => Lean.mkAuxName (declName ++ suffix) 1\n\nbuiltin_initialize registerTraceClass `Elab.letrec\n\n/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it\n   is delayed assigned to one. -/\ndef isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do\n  trace[Elab.letrec] \"mvarId: {mkMVar mvarId} letrecMVars: {(\u2190 get).letRecsToLift.map (mkMVar $ \u00b7.mvarId)}\"\n  let mvarId := (\u2190 getMCtx).getDelayedRoot mvarId\n  trace[Elab.letrec] \"mvarId root: {mkMVar mvarId}\"\n  return (\u2190 get).letRecsToLift.any (\u00b7.mvarId == mvarId)\n\ndef resolveLocalName (n : Name) : TermElabM (Option (Expr \u00d7 List String)) := do\n  let lctx \u2190 getLCtx\n  let view := extractMacroScopes n\n  let rec loop (n : Name) (projs : List String) :=\n    match lctx.findFromUserName? { view with name := n }.review with\n    | some decl => some (decl.toExpr, projs)\n    | none      => match n with\n      | Name.str pre s _ => loop pre (s::projs)\n      | _                => none\n  return loop view.name []\n\n/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/\ndef isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val _ => do\n    let r? \u2190 resolveLocalName val\n    match r? with\n    | some (fvar, []) => pure (some fvar)\n    | _               => pure none\n  | _ => pure none\n\n/--\n  Create an `Expr.const` using the given name and explicit levels.\n  Remark: fresh universe metavariables are created if the constant has more universe\n  parameters than `explicitLevels`. -/\ndef mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do\n  let cinfo \u2190 getConstInfo constName\n  if explicitLevels.length > cinfo.levelParams.length then\n    throwError \"too many explicit universe levels\"\n  else\n    let numMissingLevels := cinfo.levelParams.length - explicitLevels.length\n    let us \u2190 mkFreshLevelMVars numMissingLevels\n    pure $ Lean.mkConst constName (explicitLevels ++ us)\n\nprivate def mkConsts (candidates : List (Name \u00d7 List String)) (explicitLevels : List Level) : TermElabM (List (Expr \u00d7 List String)) := do\n  candidates.foldlM (init := []) fun result (constName, projs) => do\n    -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.\n   let const \u2190 mkConst constName explicitLevels\n   return (const, projs) :: result\n\ndef resolveName (stx : Syntax) (n : Name) (preresolved : List (Name \u00d7 List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 List String)) := do\n  try\n    if let some (e, projs) \u2190 resolveLocalName n then\n      unless explicitLevels.isEmpty do\n        throwError \"invalid use of explicit universe parameters, '{e}' is a local\"\n      return [(e, projs)]\n    -- check for section variable capture by a quotation\n    let ctx \u2190 read\n    if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (\u00b7, projs) then\n      return [(e, projs)]  -- section variables should shadow global decls\n    if preresolved.isEmpty then\n      process (\u2190 resolveGlobalName n)\n    else\n      process preresolved\n  catch ex =>\n    if preresolved.isEmpty && explicitLevels.isEmpty then\n      addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n    throw ex\nwhere process (candidates : List (Name \u00d7 List String)) : TermElabM (List (Expr \u00d7 List String)) := do\n  if candidates.isEmpty then\n    if (\u2190 read).autoBoundImplicit && isValidAutoBoundImplicitName n then\n      throwAutoBoundImplicitLocal n\n    else\n      throwError \"unknown identifier '{Lean.mkConst n}'\"\n  if preresolved.isEmpty && explicitLevels.isEmpty then\n    addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n  mkConsts candidates explicitLevels\n\n/--\n  Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.\n  Example: Assume resolveName `v.head.bla.boo` produces `(v.head, [\"bla\", \"boo\"])`, then this method produces\n  `(v.head, id, [f\u2081, f\u2082])` where `id` is an identifier for `v.head`, and `f\u2081` and `f\u2082` are identifiers for fields `\"bla\"` and `\"boo\"`. -/\ndef resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 Syntax \u00d7 List Syntax)) := do\n  match ident with\n  | Syntax.ident info rawStr n preresolved =>\n    let r \u2190 resolveName ident n preresolved explicitLevels expectedType?\n    r.mapM fun (c, fields) => do\n      let (cSstr, fields) := fields.foldr (init := (rawStr, [])) fun field (restSstr, fs) =>\n        let fieldSstr := restSstr.takeRightWhile (\u00b7 \u2260 '.')\n        ({ restSstr with stopPos := restSstr.stopPos - (fieldSstr.bsize + 1) }, (field, fieldSstr) :: fs)\n      let mkIdentFromPos pos rawVal val :=\n        let info := match info with\n        | SourceInfo.original .. => SourceInfo.original \"\".toSubstring pos \"\".toSubstring (pos + rawVal.bsize)\n        | _                      => SourceInfo.synthetic pos (pos + rawVal.bsize)\n        Syntax.ident info rawVal val []\n      let id := match c with\n        | Expr.const id _ _ => id\n        | Expr.fvar id _    => id\n        | _                 => unreachable!\n      let id := mkIdentFromPos (ident.getPos?.getD 0) cSstr id\n      match info.getPos? with\n      | none =>\n        return (c, id, fields.map fun (field, _) => mkIdentFrom ident (Name.mkSimple field))\n      | some pos =>\n        let mut pos := pos + cSstr.bsize + 1\n        let mut newFields := #[]\n        for (field, fieldSstr) in fields do\n          newFields := newFields.push <| mkIdentFromPos pos fieldSstr (Name.mkSimple field)\n          pos := pos + fieldSstr.bsize + 1\n        return (c, id, newFields.toList)\n  | _ => throwError \"identifier expected\"\n\ndef resolveId? (stx : Syntax) (kind := \"term\") (withInfo := false) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val preresolved => do\n    let rs \u2190 try resolveName stx val preresolved [] catch _ => pure []\n    let rs := rs.filter fun \u27e8f, projs\u27e9 => projs.isEmpty\n    let fs := rs.map fun (f, _) => f\n    match fs with\n    | []  => pure none\n    | [f] =>\n      if withInfo then\n        addTermInfo stx f\n      pure (some f)\n    | _   => throwError \"ambiguous {kind}, use fully qualified name, possible interpretations {fs}\"\n  | _ => throwError \"identifier expected\"\n\nprivate def mkSomeContext : Context := {\n  fileName      := \"<TermElabM>\"\n  fileMap       := arbitrary\n}\n\ndef TermElabM.run (x : TermElabM \u03b1) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (\u03b1 \u00d7 State) :=\n  withConfig setElabConfig (x ctx |>.run s)\n\n@[inline] def TermElabM.run' (x : TermElabM \u03b1) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM \u03b1 :=\n  (\u00b7.1) <$> x.run ctx s\n\ndef TermElabM.toIO (x : TermElabM \u03b1)\n    (ctxCore : Core.Context) (sCore : Core.State)\n    (ctxMeta : Meta.Context) (sMeta : Meta.State)\n    (ctx : Context) (s : State) : IO (\u03b1 \u00d7 Core.State \u00d7 Meta.State \u00d7 State) := do\n  let ((a, s), sCore, sMeta) \u2190 (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta\n  pure (a, sCore, sMeta, s)\n\ninstance [MetaEval \u03b1] : MetaEval (TermElabM \u03b1) where\n  eval env opts x _ :=\n    let x : TermElabM \u03b1 := do\n      try x finally\n        let s \u2190 get\n        s.messages.forM fun msg => do IO.println (\u2190 msg.toString)\n    MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext\n\nunsafe def evalExpr (\u03b1) (typeName : Name) (value : Expr) : TermElabM \u03b1 :=\n  withoutModifyingEnv do\n    let name \u2190 mkFreshUserName `_tmp\n    let type \u2190 inferType value\n    let type \u2190 whnfD type\n    unless type.isConstOf typeName do\n      throwError \"unexpected type at evalExpr{indentExpr type}\"\n    let decl := Declaration.defnDecl {\n       name := name, levelParams := [], type := type,\n       value := value, hints := ReducibilityHints.opaque,\n       safety := DefinitionSafety.unsafe\n    }\n    ensureNoUnassignedMVars decl\n    addAndCompile decl\n    evalConst \u03b1 name\n\nprivate def throwStuckAtUniverseCnstr : TermElabM Unit := do\n  -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property\n  let entries \u2190 getPostponed\n  let mut found : Std.HashSet (Level \u00d7 Level) := {}\n  let mut uniqueEntries := #[]\n  for entry in entries do\n    let mut lhs := entry.lhs\n    let mut rhs := entry.rhs\n    if Level.normLt rhs lhs then\n      (lhs, rhs) := (rhs, lhs)\n    unless found.contains (lhs, rhs) do\n      found := found.insert (lhs, rhs)\n      uniqueEntries := uniqueEntries.push entry\n  for i in [1:uniqueEntries.size] do\n    logErrorAt uniqueEntries[i].ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[i])\n  throwErrorAt uniqueEntries[0].ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[0])\n\ndef withoutPostponingUniverseConstraints (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let postponed \u2190 getResetPostponed\n  try\n    let a \u2190 x\n    unless (\u2190 processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do\n      throwStuckAtUniverseCnstr\n    setPostponed postponed\n    return a\n  catch ex =>\n    setPostponed postponed\n    throw ex\n\nend Term\n\nbuiltin_initialize\n  registerTraceClass `Elab.postpone\n  registerTraceClass `Elab.coe\n  registerTraceClass `Elab.debug\n\nexport Term (TermElabM)\n\nend Lean.Elab\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Elab/Term.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.02479816150188319, "lm_q1q2_score": 0.005258916459958768}}
{"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.BorrowedAnnotation\nimport Lean.Meta.KAbstract\nimport Lean.Meta.MatchUtil\nimport Lean.Elab.SyntheticMVars\n\nnamespace Lean.Elab.Term\nopen Meta\n\n@[builtin_term_elab coeNotation] def elabCoe : TermElab := fun stx expectedType? => do\n  let stx := stx[1]\n  tryPostponeIfNoneOrMVar expectedType?\n  let e \u2190 elabTerm stx none\n  if expectedType?.isNone then\n    throwError \"invalid coercion notation, expected type is not known\"\n  ensureHasType expectedType? e\n\n@[builtin_term_elab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? =>\n  match stx with\n  | `(\u27e8$args,*\u27e9) => do\n    tryPostponeIfNoneOrMVar expectedType?\n    match expectedType? with\n    | some expectedType =>\n      let expectedType \u2190 whnf expectedType\n      matchConstInduct expectedType.getAppFn\n        (fun _ => throwError \"invalid constructor \u27e8...\u27e9, expected type must be an inductive type {indentExpr expectedType}\")\n        (fun ival _ => do\n          match ival.ctors with\n          | [ctor] =>\n            if isPrivateNameFromImportedModule (\u2190 getEnv) ctor then\n              throwError \"invalid \u27e8...\u27e9 notation, constructor for `{ival.name}` is marked as private\"\n            let cinfo \u2190 getConstInfoCtor ctor\n            let numExplicitFields \u2190 forallTelescopeReducing cinfo.type fun xs _ => do\n              let mut n := 0\n              for i in [cinfo.numParams:xs.size] do\n                if (\u2190 getFVarLocalDecl xs[i]!).binderInfo.isExplicit then\n                  n := n + 1\n              return n\n            let args := args.getElems\n            if args.size < numExplicitFields then\n              throwError \"invalid constructor \u27e8...\u27e9, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided\"\n            let newStx \u2190 if args.size == numExplicitFields then\n              `($(mkCIdentFrom stx ctor (canonical := true)) $(args)*)\n            else if numExplicitFields == 0 then\n              throwError \"invalid constructor \u27e8...\u27e9, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided\"\n            else\n              let extra := args[numExplicitFields-1:args.size]\n              let newLast \u2190 `(\u27e8$[$extra],*\u27e9)\n              let newArgs := args[0:numExplicitFields-1].toArray.push newLast\n              `($(mkCIdentFrom stx ctor (canonical := true)) $(newArgs)*)\n            withMacroExpansion stx newStx $ elabTerm newStx expectedType?\n          | _ => throwError \"invalid constructor \u27e8...\u27e9, expected type must be an inductive type with only one constructor {indentExpr expectedType}\")\n    | none => throwError \"invalid constructor \u27e8...\u27e9, expected type must be known\"\n  | _ => throwUnsupportedSyntax\n\n@[builtin_term_elab borrowed] def elabBorrowed : TermElab := fun stx expectedType? =>\n  match stx with\n  | `(@& $e) => return markBorrowed (\u2190 elabTerm e expectedType?)\n  | _ => throwUnsupportedSyntax\n\n@[builtin_macro Lean.Parser.Term.show] def expandShow : Macro := fun stx =>\n  match stx with\n  | `(show $type by%$b $tac) => `(show $type from by%$b $tac)\n  | _                        => Macro.throwUnsupported\n\n@[builtin_term_elab Lean.Parser.Term.show] def elabShow : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(show $type from $val)  =>\n    /-\n    We first elaborate the type and try to unify it with the expected type if available.\n    Note that, we should not throw an error if the types do not unify. Recall that we have coercions and\n    the following is supported in Lean 3 and 4.\n    ```\n    example : Int :=\n      show Nat from 0\n    ```\n    -/\n    let type \u2190 withSynthesize (mayPostpone := true) do\n      let type \u2190 elabType type\n      if let some expectedType := expectedType? then\n        -- Recall that a similiar approach is used when elaborating applications\n        discard <| isDefEq expectedType type\n      return type\n    /-\n    Recall that we do not use the same approach used to elaborate type ascriptions.\n    For the `($val : $type)` notation, we just elaborate `val` using `type` and\n    ensure it has type `type`. This approach only ensure the type resulting expression\n    is definitionally equal to `type`. For the `show` notation we use `let_fun` to ensure the type\n    of the resulting expression is *structurally equal* `type`. Structural equality is important,\n    for example, if the resulting expression is a `simp`/`rw` parameter. Here is an example:\n    ```\n    example (x : Nat) : (x + 0) + y = x + y := by\n      rw [show x + 0 = x from rfl]\n    ```\n    -/\n    let thisId := mkIdentFrom stx `this\n    let valNew \u2190 `(let_fun $thisId : $(\u2190 exprToSyntax type) := $val; $thisId)\n    elabTerm valNew expectedType?\n  | _ => throwUnsupportedSyntax\n\n@[builtin_macro Lean.Parser.Term.have] def expandHave : Macro := fun stx =>\n  match stx with\n  | `(have $x $bs* $[: $type]? := $val; $body)            => `(let_fun $x $bs* $[: $type]? := $val; $body)\n  | `(have%$tk $[: $type]? := $val; $body)                => `(have $(mkIdentFrom tk `this (canonical := true)) $[: $type]? := $val; $body)\n  | `(have $x $bs* $[: $type]? $alts; $body)              => `(let_fun $x $bs* $[: $type]? $alts; $body)\n  | `(have%$tk $[: $type]? $alts:matchAlts; $body)        => `(have $(mkIdentFrom tk `this (canonical := true)) $[: $type]? $alts:matchAlts; $body)\n  | `(have $pattern:term $[: $type]? := $val:term; $body) => `(let_fun $pattern:term $[: $type]? := $val:term ; $body)\n  | _                                                     => Macro.throwUnsupported\n\n@[builtin_macro Lean.Parser.Term.suffices] def expandSuffices : Macro\n  | `(suffices%$tk $[$x :]? $type from $val; $body)            => `(have%$tk $[$x]? : $type := $body; $val)\n  | `(suffices%$tk $[$x :]? $type by%$b $tac:tacticSeq; $body) => `(have%$tk $[$x]? : $type := $body; by%$b $tac)\n  | _                                                          => Macro.throwUnsupported\n\nopen Lean.Parser in\nprivate def elabParserMacroAux (prec e : Term) (withAnonymousAntiquot : Bool) : TermElabM Syntax := do\n  let (some declName) \u2190 getDeclName?\n    | throwError \"invalid `leading_parser` macro, it must be used in definitions\"\n  match extractMacroScopes declName with\n  | { name := .str _ s, .. } =>\n    let kind := quote declName\n    let mut p \u2190 ``(withAntiquot\n      (mkAntiquot $(quote s) $kind $(quote withAnonymousAntiquot))\n      (leadingNode $kind $prec $e))\n    -- cache only unparameterized parsers\n    if (\u2190 getLCtx).all (\u00b7.isAuxDecl) then\n      p \u2190 ``(withCache $kind $p)\n    return p\n  | _  => throwError \"invalid `leading_parser` macro, unexpected declaration name\"\n\n@[builtin_term_elab \u00ableading_parser\u00bb] def elabLeadingParserMacro : TermElab :=\n  adaptExpander fun\n    | `(leading_parser $[: $prec?]? $[(withAnonymousAntiquot := $anon?)]? $e) =>\n        elabParserMacroAux (prec?.getD (quote Parser.maxPrec)) e (anon?.all (\u00b7.raw.isOfKind ``Parser.Term.trueVal))\n    | _ => throwUnsupportedSyntax\n\nprivate def elabTParserMacroAux (prec lhsPrec e : Term) : TermElabM Syntax := do\n  let declName? \u2190 getDeclName?\n  match declName? with\n  | some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e)\n  | none          => throwError \"invalid `trailing_parser` macro, it must be used in definitions\"\n\n@[builtin_term_elab \u00abtrailing_parser\u00bb] def elabTrailingParserMacro : TermElab :=\n  adaptExpander fun stx => match stx with\n  | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) =>\n    elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e\n  | _ => throwUnsupportedSyntax\n\n@[builtin_term_elab Lean.Parser.Term.panic] def elabPanic : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(panic! $arg) =>\n    let pos \u2190 getRefPosition\n    let env \u2190 getEnv\n    let stxNew \u2190 match (\u2190 getDeclName?) with\n    | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg)\n    | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg)\n    withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?\n  | _ => throwUnsupportedSyntax\n\n@[builtin_macro Lean.Parser.Term.unreachable]  def expandUnreachable : Macro := fun _ =>\n  `(panic! \"unreachable code has been reached\")\n\n@[builtin_macro Lean.Parser.Term.assert]  def expandAssert : Macro\n  | `(assert! $cond; $body) =>\n    -- TODO: support for disabling runtime assertions\n    match cond.raw.reprint with\n    | some code => `(if $cond then $body else panic! (\"assertion violation: \" ++ $(quote code)))\n    | none => `(if $cond then $body else panic! (\"assertion violation\"))\n  | _ => Macro.throwUnsupported\n\n@[builtin_macro Lean.Parser.Term.dbgTrace]  def expandDbgTrace : Macro\n  | `(dbg_trace $arg:interpolatedStr; $body) => `(dbgTrace (s! $arg) fun _ => $body)\n  | `(dbg_trace $arg:term; $body)            => `(dbgTrace (toString $arg) fun _ => $body)\n  | _                                        => Macro.throwUnsupported\n\n@[builtin_term_elab \u00absorry\u00bb] def elabSorry : TermElab := fun stx expectedType? => do\n  let stxNew \u2190 `(sorryAx _ false)\n  withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?\n\n/-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/\npartial def mkPairs (elems : Array Term) : MacroM Term :=\n  let rec loop (i : Nat) (acc : Term) := do\n    if i > 0 then\n      let i    := i - 1\n      let elem := elems[i]!\n      let acc \u2190 `(Prod.mk $elem $acc)\n      loop i acc\n    else\n      pure acc\n  loop (elems.size - 1) elems.back\n\nopen Parser in\npartial def hasCDot : Syntax \u2192 Bool\n  | Syntax.node _ k args =>\n    if k == ``Term.paren || k == ``Term.typeAscription || k == ``Term.tuple then false\n    else if k == ``Term.cdot then true\n    else args.any hasCDot\n  | _ => false\n\n/--\n  Return `some` if succeeded expanding `\u00b7` notation occurring in\n  the given syntax. Otherwise, return `none`.\n  Examples:\n  - `\u00b7 + 1` => `fun _a_1 => _a_1 + 1`\n  - `f \u00b7 \u00b7 b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/\npartial def expandCDot? (stx : Term) : MacroM (Option Term) := do\n  if hasCDot stx then\n    let (newStx, binders) \u2190 (go stx).run #[]\n    `(fun $binders* => $(\u27e8newStx\u27e9))\n  else\n    pure none\nwhere\n  /--\n    Auxiliary function for expanding the `\u00b7` notation.\n    The extra state `Array Syntax` contains the new binder names.\n    If `stx` is a `\u00b7`, we create a fresh identifier, store in the\n    extra state, and return it. Otherwise, we just return `stx`. -/\n  go : Syntax \u2192 StateT (Array Ident) MacroM Syntax\n    | stx@`(($(_))) => pure stx\n    | stx@`(\u00b7) => withFreshMacroScope do\n      let id \u2190 mkFreshIdent stx (canonical := true)\n      modify (\u00b7.push id)\n      pure id\n    | stx => match stx with\n      | .node _ k args => do\n        let args \u2190 args.mapM go\n        return .node (.fromRef stx (canonical := true)) k args\n      | _ => pure stx\n\n/--\n  Helper method for elaborating terms such as `(.+.)` where a constant name is expected.\n  This method is usually used to implement tactics that function names as arguments (e.g., `simp`).\n-/\ndef elabCDotFunctionAlias? (stx : Term) : TermElabM (Option Expr) := do\n  let some stx \u2190 liftMacroM <| expandCDotArg? stx | pure none\n  let stx \u2190 liftMacroM <| expandMacros stx\n  match stx with\n  | `(fun $binders* => $f $args*) =>\n    if binders == args then\n      try Term.resolveId? f catch _ => return none\n    else\n      return none\n  | `(fun $binders* => binop% $f $a $b) =>\n    if binders == #[a, b] then\n      try Term.resolveId? f catch _ => return none\n    else\n      return none\n  | _ => return none\nwhere\n  expandCDotArg? (stx : Term) : MacroM (Option Term) :=\n    match stx with\n    | `(($e)) => Term.expandCDot? e\n    | _ => Term.expandCDot? stx\n\n@[builtin_macro Lean.Parser.Term.paren] def expandParen : Macro\n  | `(($e)) => return (\u2190 expandCDot? e).getD e\n  | _       => Macro.throwUnsupported\n\n@[builtin_macro Lean.Parser.Term.tuple] def expandTuple : Macro\n  | `(()) => ``(Unit.unit)\n  | `(($e, $es,*)) => do\n    let pairs \u2190 mkPairs (#[e] ++ es)\n    return (\u2190 expandCDot? pairs).getD pairs\n  | _ => Macro.throwUnsupported\n\n@[builtin_macro Lean.Parser.Term.typeAscription] def expandTypeAscription : Macro\n  | `(($e : $(type)?)) => do\n    match (\u2190 expandCDot? e) with\n    | some e => `(($e : $(type)?))\n    | none   => Macro.throwUnsupported\n  | _ => Macro.throwUnsupported\n\n@[builtin_term_elab typeAscription] def elabTypeAscription : TermElab\n  | `(($e : $type)), _ => do\n    let type \u2190 withSynthesize (mayPostpone := true) <| elabType type\n    let e \u2190 elabTerm e type\n    ensureHasType type e\n  | `(($e :)), expectedType? => do\n    let e \u2190 withSynthesize (mayPostpone := false) <| elabTerm e none\n    ensureHasType expectedType? e\n  | _, _ => throwUnsupportedSyntax\n\n/-- Return `true` if `lhs` is a free variable and `rhs` does not depend on it. -/\nprivate def isSubstCandidate (lhs rhs : Expr) : MetaM Bool :=\n  if lhs.isFVar then\n    return !(\u2190 dependsOn rhs lhs.fvarId!)\n  else\n    return false\n\n/--\n  Given an expression `e` that is the elaboration of `stx`, if `e` is a free variable, then return `k stx`.\n  Otherwise, return `(fun x => k x) e`\n-/\nprivate def withLocalIdentFor (stx : Term) (e : Expr) (k : Term \u2192 TermElabM Expr) : TermElabM Expr := do\n  if e.isFVar then\n    k stx\n  else\n    let id \u2190 mkFreshUserName `h\n    let aux \u2190 withLocalDeclD id (\u2190 inferType e) fun x => do mkLambdaFVars #[x] (\u2190 k (mkIdentFrom stx id))\n    return mkApp aux e\n\n@[builtin_term_elab subst] def elabSubst : TermElab := fun stx expectedType? => do\n  let expectedType? \u2190 tryPostponeIfHasMVars? expectedType?\n  match stx with\n  | `($heqStx \u25b8 $hStx) => do\n     synthesizeSyntheticMVars\n     let mut heq \u2190 withSynthesize <| elabTerm heqStx none\n     let heqType \u2190 inferType heq\n     let heqType \u2190 instantiateMVars heqType\n     match (\u2190 Meta.matchEq? heqType) with\n     | none => throwError \"invalid `\u25b8` notation, argument{indentExpr heq}\\nhas type{indentExpr heqType}\\nequality expected\"\n     | some (\u03b1, lhs, rhs) =>\n       let mut lhs := lhs\n       let mut rhs := rhs\n       let mkMotive (lhs typeWithLooseBVar : Expr) := do\n         withLocalDeclD (\u2190 mkFreshUserName `x) \u03b1 fun x => do\n           withLocalDeclD (\u2190 mkFreshUserName `h) (\u2190 mkEq lhs x) fun h => do\n             mkLambdaFVars #[x, h] $ typeWithLooseBVar.instantiate1 x\n       match expectedType? with\n       | some expectedType =>\n         let mut expectedAbst \u2190 kabstract expectedType rhs\n         unless expectedAbst.hasLooseBVars do\n           expectedAbst \u2190 kabstract expectedType lhs\n           unless expectedAbst.hasLooseBVars do\n             throwError \"invalid `\u25b8` notation, expected result type of cast is {indentExpr expectedType}\\nhowever, the equality {indentExpr heq}\\nof type {indentExpr heqType}\\ndoes not contain the expected result type on either the left or the right hand side\"\n           heq \u2190 mkEqSymm heq\n           (lhs, rhs) := (rhs, lhs)\n         let hExpectedType := expectedAbst.instantiate1 lhs\n         let (h, badMotive?) \u2190 withRef hStx do\n           let h \u2190 elabTerm hStx hExpectedType\n           try\n             return (\u2190 ensureHasType hExpectedType h, none)\n           catch ex =>\n             -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too\n             let hType \u2190 inferType h\n             let hTypeAbst \u2190 kabstract hType rhs\n             unless hTypeAbst.hasLooseBVars do\n               throw ex\n             let hTypeNew := hTypeAbst.instantiate1 lhs\n             unless (\u2190 isDefEq hExpectedType hTypeNew) do\n               throw ex\n             let motive \u2190 mkMotive rhs hTypeAbst\n             if !(\u2190 isTypeCorrect motive) then\n               return (h, some motive)\n             else\n               return (\u2190 mkEqRec motive h (\u2190 mkEqSymm heq), none)\n         let motive \u2190 mkMotive lhs expectedAbst\n         if badMotive?.isSome || !(\u2190 isTypeCorrect motive) then\n           -- Before failing try tos use `subst`\n           if \u2190 (isSubstCandidate lhs rhs <||> isSubstCandidate rhs lhs) then\n             withLocalIdentFor heqStx heq fun heqStx => do\n               let h \u2190 instantiateMVars h\n               if h.hasMVar then\n                 -- If `h` has metavariables, we try to elaborate `hStx` again after we substitute `heqStx`\n                 -- Remark: re-elaborating `hStx` may be problematic if `hStx` contains the `lhs` of `heqStx` which will be eliminated by `subst`\n                 let stxNew \u2190 `(by subst $heqStx; exact $hStx)\n                 withMacroExpansion stx stxNew (elabTerm stxNew expectedType)\n               else\n                 withLocalIdentFor hStx h fun hStx => do\n                   let stxNew \u2190 `(by subst $heqStx; exact $hStx)\n                   withMacroExpansion stx stxNew (elabTerm stxNew expectedType)\n           else\n             throwError \"invalid `\u25b8` notation, failed to compute motive for the substitution\"\n         else\n           mkEqRec motive h heq\n       | none =>\n         let h \u2190 elabTerm hStx none\n         let hType \u2190 inferType h\n         let hTypeAbst \u2190 kabstract hType lhs\n         let motive \u2190 mkMotive lhs hTypeAbst\n         unless (\u2190 isTypeCorrect motive) do\n           throwError \"invalid `\u25b8` notation, failed to compute motive for the substitution\"\n         mkEqRec motive h heq\n  | _ => throwUnsupportedSyntax\n\n@[builtin_term_elab stateRefT] def elabStateRefT : TermElab := fun stx _ => do\n  let \u03c3 \u2190 elabType stx[1]\n  let mut mStx := stx[2]\n  if mStx.getKind == ``Lean.Parser.Term.macroDollarArg then\n    mStx := mStx[1]\n  let m \u2190 elabTerm mStx (\u2190 mkArrow (mkSort levelOne) (mkSort levelOne))\n  let \u03c9 \u2190 mkFreshExprMVar (mkSort levelOne)\n  let stWorld \u2190 mkAppM ``STWorld #[\u03c9, m]\n  discard <| mkInstMVar stWorld\n  mkAppM ``StateRefT' #[\u03c9, \u03c3, m]\n\n@[builtin_term_elab noindex] def elabNoindex : TermElab := fun stx expectedType? => do\n  let e \u2190 elabTerm stx[1] expectedType?\n  return DiscrTree.mkNoindexAnnotation e\n\nend Lean.Elab.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/Lean/Elab/BuiltinNotation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.14804719427274568, "lm_q2_score": 0.03514484892726185, "lm_q1q2_score": 0.005203096276820632}}
{"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 \u03b1) : monadLift x = x :=\n  rfl\n\nclass LawfulFunctor (f : Type u \u2192 Type v) [Functor f] : Prop where\n  map_const          : (Functor.mapConst : \u03b1 \u2192 f \u03b2 \u2192 f \u03b1) = Functor.map \u2218 const \u03b2\n  id_map   (x : f \u03b1) : id <$> x = x\n  comp_map (g : \u03b1 \u2192 \u03b2) (h : \u03b2 \u2192 \u03b3) (x : f \u03b1) : (h \u2218 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 \u03b1) : (fun a => a) <$> x = x :=\n  id_map x\n\nclass LawfulApplicative (f : Type u \u2192 Type v) [Applicative f] extends LawfulFunctor f : Prop where\n  seqLeft_eq  (x : f \u03b1) (y : f \u03b2)     : x <* y = const \u03b2 <$> x <*> y\n  seqRight_eq (x : f \u03b1) (y : f \u03b2)     : x *> y = const \u03b1 id <$> x <*> y\n  pure_seq    (g : \u03b1 \u2192 \u03b2) (x : f \u03b1)   : pure g <*> x = g <$> x\n  map_pure    (g : \u03b1 \u2192 \u03b2) (x : \u03b1)     : g <$> (pure x : f \u03b1) = pure (g x)\n  seq_pure    {\u03b1 \u03b2 : Type u} (g : f (\u03b1 \u2192 \u03b2)) (x : \u03b1) : g <*> pure x = (fun h => h x) <$> g\n  seq_assoc   {\u03b1 \u03b2 \u03b3 : Type u} (x : f \u03b1) (g : f (\u03b1 \u2192 \u03b2)) (h : f (\u03b2 \u2192 \u03b3)) : h <*> (g <*> x) = ((@comp \u03b1 \u03b2 \u03b3) <$> h) <*> g <*> x\n  comp_map g h x := by\n    repeat rw [\u2190 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 \u03b1) : pure id <*> x = x := by\n  simp [pure_seq]\n\nclass LawfulMonad (m : Type u \u2192 Type v) [Monad m] extends LawfulApplicative m : Prop where\n  bind_pure_comp (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : x >>= pure \u2218 f = f <$> x\n  bind_map       {\u03b1 \u03b2 : Type u} (f : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : f >>= (. <$> x) = f <*> x\n  pure_bind      (x : \u03b1) (f : \u03b1 \u2192 m \u03b2) : pure x >>= f = f x\n  bind_assoc     (x : m \u03b1) (f : \u03b1 \u2192 m \u03b2) (g : \u03b2 \u2192 m \u03b3) : x >>= f >>= g = x >>= fun x => f x >>= g\n  map_pure g x    := by rw [\u2190 bind_pure_comp, pure_bind]\n  seq_pure g x    := by rw [\u2190 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 {\u03b1 \u03b2 : Type u} (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : f <$> x = x >>= pure \u2218 f := by\n      rw [bind_pure_comp]\n    let bind_map_symm {\u03b1 \u03b2 : Type u} (f : m (\u03b1 \u2192 (\u03b2 : Type u))) (x : m \u03b1) : 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 \u03b1) : x >>= pure = x := by\n  show x >>= pure \u2218 id = x\n  rw [bind_pure_comp, id_map]\n\ntheorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : m \u03b1) : f <$> x = x >>= fun a => pure (f a) := by\n  rw [\u2190 bind_pure_comp]\n\ntheorem seq_eq_bind_map {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (f : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : f <*> x = f >>= (. <$> x) := by\n  rw [\u2190 bind_map]\n\ntheorem bind_congr [Bind m] {x : m \u03b1} {f g : \u03b1 \u2192 m \u03b2} (h : \u2200 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 \u27e8\u27e9) = x := by\n  have : (x >>= fun _ => pure \u27e8\u27e9) = (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 \u03b1} {f g : \u03b1 \u2192 \u03b2} (h : \u2200 a, f a = g a) : (f <$> x : m \u03b2) = g <$> x := by\n  simp [funext h]\n\ntheorem seq_eq_bind {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (mf : m (\u03b1 \u2192 \u03b2)) (x : m \u03b1) : mf <*> x = mf >>= fun f => f <$> x := by\n  rw [bind_map]\n\ntheorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m \u03b1) (y : m \u03b2) : 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 \u03b1) (y : m \u03b2) : 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 \u03b1) (f : \u03b1 \u2192 \u03b2) : f <$> x = f x := rfl\n@[simp] theorem bind_eq (x : Id \u03b1) (f : \u03b1 \u2192 id \u03b2) : x >>= f = f x := rfl\n@[simp] theorem pure_eq (a : \u03b1) : (pure a : Id \u03b1) = 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 \u03b5 m \u03b1} (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 \u03b5 m \u03b1) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift [Monad m] (x : m \u03b1) : run (ExceptT.lift x : ExceptT \u03b5 m \u03b1) = (Except.ok <$> x : m (Except \u03b5 \u03b1)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT \u03b5 m \u03b2) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : run (ExceptT.lift x >>= f : ExceptT \u03b5 m \u03b2) = 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 : \u03b1 \u2192 ExceptT \u03b5 m \u03b2) : (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 \u03b5 m \u03b1)\n        : run (x >>= f : ExceptT \u03b5 m \u03b2)\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 : \u03b1) : ExceptT.lift (pure a) = (pure a : ExceptT \u03b5 m \u03b1) := by\n  simp [ExceptT.lift, pure, ExceptT.pure]\n\n@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1)\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 {\u03b1 \u03b2 \u03b5 : Type u} [Monad m] (mf : ExceptT \u03b5 m (\u03b1 \u2192 \u03b2)) (x : ExceptT \u03b5 m \u03b1) : mf <*> x = mf >>= fun f => f <$> x :=\n  rfl\n\nprotected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : ExceptT \u03b5 m \u03b1) : x >>= pure \u2218 f = f <$> x := by\n  intros; rfl\n\nprotected theorem seqLeft_eq {\u03b1 \u03b2 \u03b5 : Type u} {m : Type u \u2192 Type v} [Monad m] [LawfulMonad m] (x : ExceptT \u03b5 m \u03b1) (y : ExceptT \u03b5 m \u03b2) : x <* y = const \u03b2 <$> x <*> y := by\n  show (x >>= fun a => y >>= fun _ => pure a) = (const (\u03b1 := \u03b1) \u03b2 <$> x) >>= fun f => f <$> y\n  rw [\u2190 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 \u03b5 m \u03b1) (y : ExceptT \u03b5 m \u03b2) : x *> y = const \u03b1 id <$> x <*> y := by\n  show (x >>= fun _ => y) = (const \u03b1 id <$> x) >>= fun f => f <$> y\n  rw [\u2190 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 \u03b5 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 \u03c1 m \u03b1} (h : \u2200 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 : \u03b1) (ctx : \u03c1) : (pure a : ReaderT \u03c1 m \u03b1).run ctx = pure a := rfl\n\n@[simp] theorem run_bind [Monad m] (x : ReaderT \u03c1 m \u03b1) (f : \u03b1 \u2192 ReaderT \u03c1 m \u03b2) (ctx : \u03c1)\n    : (x >>= f).run ctx = x.run ctx >>= \u03bb a => (f a).run ctx := rfl\n\n@[simp] theorem run_map [Monad m] (f : \u03b1 \u2192 \u03b2) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (f <$> x).run ctx = f <$> x.run ctx := rfl\n\n@[simp] theorem run_monadLift [MonadLiftT n m] (x : n \u03b1) (ctx : \u03c1)\n    : (monadLift x : ReaderT \u03c1 m \u03b1).run ctx = (monadLift x : m \u03b1) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {\u03b2 : Type u} \u2192 n \u03b2 \u2192 n \u03b2) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1)\n    : (monadMap @f x : ReaderT \u03c1 m \u03b1).run ctx = monadMap @f (x.run ctx) := rfl\n\n@[simp] theorem run_read [Monad m] (ctx : \u03c1) : (ReaderT.read : ReaderT \u03c1 m \u03c1).run ctx = pure ctx := rfl\n\n@[simp] theorem run_seq {\u03b1 \u03b2 : Type u} [Monad m] [LawfulMonad m] (f : ReaderT \u03c1 m (\u03b1 \u2192 \u03b2)) (x : ReaderT \u03c1 m \u03b1) (ctx : \u03c1) : (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 \u03c1 m \u03b1) (y : ReaderT \u03c1 m \u03b2) (ctx : \u03c1) : (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 \u03c1 m \u03b1) (y : ReaderT \u03c1 m \u03b2) (ctx : \u03c1) : (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 \u03c1 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' \u03c9 \u03c3 m) :=\n  inferInstanceAs (LawfulMonad (ReaderT (ST.Ref \u03c9 \u03c3) m))\n\n/- StateT -/\n\nnamespace StateT\n\ntheorem ext {x y : StateT \u03c3 m \u03b1} (h : \u2200 s, x.run s = y.run s) : x = y :=\n  funext h\n\n@[simp] theorem run'_eq [Monad m] (x : StateT \u03c3 m \u03b1) (s : \u03c3) : run' x s = (\u00b7.1) <$> run x s :=\n  rfl\n\n@[simp] theorem run_pure [Monad m] (a : \u03b1) (s : \u03c3) : (pure a : StateT \u03c3 m \u03b1).run s = pure (a, s) := rfl\n\n@[simp] theorem run_bind [Monad m] (x : StateT \u03c3 m \u03b1) (f : \u03b1 \u2192 StateT \u03c3 m \u03b2) (s : \u03c3)\n    : (x >>= f).run s = x.run s >>= \u03bb 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 {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (f : \u03b1 \u2192 \u03b2) (x : StateT \u03c3 m \u03b1) (s : \u03c3) : (f <$> x).run s = (fun (p : \u03b1 \u00d7 \u03c3) => (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 : \u03c3)    : (get : StateT \u03c3 m \u03c3).run s = pure (s, s) := rfl\n\n@[simp] theorem run_set [Monad m] (s s' : \u03c3) : (set s' : StateT \u03c3 m PUnit).run s = pure (\u27e8\u27e9, s') := rfl\n\n@[simp] theorem run_modify [Monad m] (f : \u03c3 \u2192 \u03c3) (s : \u03c3) : (modify f : StateT \u03c3 m PUnit).run s = pure (\u27e8\u27e9, f s) := rfl\n\n@[simp] theorem run_modifyGet [Monad m] (f : \u03c3 \u2192 \u03b1 \u00d7 \u03c3) (s : \u03c3) : (modifyGet f : StateT \u03c3 m \u03b1).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 {\u03b1 \u03c3 : Type u} [Monad m] (x : m \u03b1) (s : \u03c3) : (StateT.lift x : StateT \u03c3 m \u03b1).run s = x >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_bind_lift {\u03b1 \u03c3 : Type u} [Monad m] [LawfulMonad m] (x : m \u03b1) (f : \u03b1 \u2192 StateT \u03c3 m \u03b2) (s : \u03c3) : (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 {\u03b1 \u03c3 : Type u} [Monad m] [MonadLiftT n m] (x : n \u03b1) (s : \u03c3) : (monadLift x : StateT \u03c3 m \u03b1).run s = (monadLift x : m \u03b1) >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {\u03b2 : Type u} \u2192 n \u03b2 \u2192 n \u03b2) (x : StateT \u03c3 m \u03b1) (s : \u03c3)\n    : (monadMap @f x : StateT \u03c3 m \u03b1).run s = monadMap @f (x.run s) := rfl\n\n@[simp] theorem run_seq {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (f : StateT \u03c3 m (\u03b1 \u2192 \u03b2)) (x : StateT \u03c3 m \u03b1) (s : \u03c3) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : \u03b1 \u00d7 \u03c3) => (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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) (s : \u03c3) : (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 {\u03b1 \u03b2 \u03c3 : Type u} [Monad m] [LawfulMonad m] (x : StateT \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) (s : \u03c3) : (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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) : x *> y = const \u03b1 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 \u03c3 m \u03b1) (y : StateT \u03c3 m \u03b2) : x <* y = const \u03b2 <$> x <*> y := by\n  apply ext; intro s\n  simp [map_eq_pure_bind]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateT \u03c3 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 \u2190\n  registerInternalExceptionId `congrHypothesisFailed\n\ndef throwCongrHypothesisFailed : MetaM \u03b1 :=\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\u2081 r\u2082 : Result) : MetaM Result := do\n  match r\u2081.proof? with\n  | none => return r\u2082\n  | some p\u2081 => match r\u2082.proof? with\n    | none    => return { r\u2082 with proof? := r\u2081.proof? }\n    | some p\u2082 => return { r\u2082 with proof? := (\u2190 Meta.mkEqTrans p\u2081 p\u2082) }\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? := (\u2190 Meta.mkCongrFun h a) }\n\nprivate def mkCongr (r\u2081 r\u2082 : Result) : MetaM Result :=\n  let e := mkApp r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | some h,  none    => return { expr := e, proof? := (\u2190 Meta.mkCongrFun h r\u2082.expr) }\n  | none,    some h  => return { expr := e, proof? := (\u2190 Meta.mkCongrArg r\u2081.expr h) }\n  | some h\u2081, some h\u2082 => return { expr := e, proof? := (\u2190 Meta.mkCongr h\u2081 h\u2082) }\n\nprivate def mkImpCongr (r\u2081 r\u2082 : Result) : MetaM Result := do\n  let e \u2190 mkArrow r\u2081.expr r\u2082.expr\n  match r\u2081.proof?, r\u2082.proof? with\n  | none,     none   => return { expr := e, proof? := none }\n  | _,        _      => return { expr := e, proof? := (\u2190 Meta.mkImpCongr (\u2190 r\u2081.getProof) (\u2190 r\u2082.getProof)) } -- TODO specialize if bootleneck\n\nprivate def reduceProj (e : Expr) : MetaM Expr := do\n  match (\u2190 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 (\u2190 getProjectionFnInfo? cinfo.name) with\n    | none => return none\n    | some projInfo =>\n      if projInfo.fromClass then\n        if (\u2190 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 (\u2190 unfoldDefinition? e) with\n        | none   => pure none\n        | some e =>\n          match (\u2190 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 (\u2190 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 (\u2190 isProjectionFn fName) then\n    return none -- should be reduced by `reduceProjFn?`\n  if (\u2190 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 := (\u2190 read).config\n  if cfg.beta then\n    let e' := e.headBeta\n    if e' != e then\n      return (\u2190 reduce e')\n  -- TODO: eta reduction\n  if cfg.proj then\n    match (\u2190 reduceProjFn? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  if cfg.iota then\n    match (\u2190 reduceRecMatcher? e) with\n    | some e => return (\u2190 reduce e)\n    | none   => pure ()\n  match (\u2190 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 (\u2190 reduce e))\n\npartial def simp (e : Expr) : M Result := withIncRecDepth do\n  let cfg \u2190 getConfig\n  if (\u2190 isProof e) then\n    return { expr := e }\n  if cfg.memoize then\n    if let some result := (\u2190 get).cache.find? e then\n      return result\n  simpLoop { expr := e }\n\nwhere\n  simpLoop (r : Result) : M Result := do\n    let cfg \u2190 getConfig\n    if (\u2190 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 (\u2190 pre r.expr) with\n      | Step.done r   => cacheResult cfg r\n      | Step.visit r' =>\n        let r \u2190 mkEqTrans r r'\n        let r \u2190 mkEqTrans r (\u2190 simpStep r.expr)\n        match (\u2190 post r.expr) with\n        | Step.done r'  => cacheResult cfg (\u2190 mkEqTrans r r')\n        | Step.visit r' =>\n          let r \u2190 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 := (\u2190 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 := (\u2190 instantiateMVars e) }\n    | Expr.fvar ..     => pure { expr := (\u2190 reduceFVar (\u2190 getConfig) e) }\n\n  congrDefault (e : Expr) : M Result :=\n    withParent e <| e.withApp fun f args => do\n      let infos := (\u2190 getFunInfoNArgs f args.size).paramInfo\n      let mut r \u2190 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 \u2190 mkCongr r (\u2190 simp arg)\n        else if (\u2190 whnfD (\u2190 inferType r.expr)).isArrow then\n          r \u2190 mkCongr r (\u2190 simp arg)\n        else\n          r \u2190 mkCongrFun r (\u2190 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 (\u2190 inferType h) fun xs hType => withNewLemmas xs do\n      let lhs \u2190 instantiateMVars hType.appFn!.appArg!\n      let r \u2190 simp lhs\n      let rhs := hType.appArg!\n      rhs.withApp fun m zs => do\n        let val \u2190 mkLambdaFVars zs r.expr\n        unless (\u2190 isDefEq m val) do\n          throwCongrHypothesisFailed\n        unless (\u2190 isDefEq h (\u2190 mkLambdaFVars xs (\u2190 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 \u2190 mkConstWithFreshMVarLevels c.theoremName\n    let (xs, bis, type) \u2190 forallMetaTelescopeReducing (\u2190 inferType lemma)\n    if c.hypothesesPos.any (\u00b7 \u2265 xs.size) then\n      return none\n    let lhs := type.appFn!.appArg!\n    let rhs := type.appArg!\n    if (\u2190 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 (\u2190 processCongrHypothesis x) then\n            modified := true\n        catch _ =>\n          trace[Meta.Tactic.simp.congr] \"processCongrHypothesis {c.theoremName} failed {\u2190 inferType x}\"\n          return none\n      unless modified do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} not modified\"\n        return none\n      unless (\u2190 synthesizeArgs c.theoremName xs bis (\u2190 read).discharge?) do\n        trace[Meta.Tactic.simp.congr] \"{c.theoremName} synthesizeArgs failed\"\n        return none\n      let eNew \u2190 instantiateMVars rhs\n      let proof \u2190 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 \u2190 getCongrLemmas\n      let cs := congrLemmas.get f.constName!\n      for c in cs do\n        match (\u2190 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 \u2190 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 := (\u2190 reduce e) }\n\n  withNewLemmas {\u03b1} (xs : Array Expr) (f : M \u03b1) : M \u03b1 := do\n    if (\u2190 getConfig).contextual then\n      let mut s \u2190 getSimpLemmas\n      let mut updated := false\n      for x in xs do\n        if (\u2190 isProof x) then\n          s \u2190 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 \u2190 simp e\n      let eNew \u2190 mkLambdaFVars xs r.expr\n      match r.proof? with\n      | none   => return { expr := eNew }\n      | some h =>\n        let p \u2190 xs.foldrM (init := h) fun x h => do\n          mkFunExt (\u2190 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 \u2190 simp p\n    trace[Debug.Meta.Tactic.simp] \"arrow [{(\u2190 getConfig).contextual}] {p} [{\u2190 isProp p}] -> {q} [{\u2190 isProp q}]\"\n    if (\u2190 (\u2190 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 \u2190 getSimpLemmas\n        let s \u2190 s.add #[] h\n        withSimpLemmas s do\n          let rq \u2190 simp q\n          match rq.proof? with\n          | none    => mkImpCongr rp rq\n          | some hq =>\n            let hq \u2190 mkLambdaFVars #[h] hq\n            return { expr := (\u2190 mkArrow rp.expr rq.expr), proof? := (\u2190 mkImpCongrCtx (\u2190 rp.getProof) hq) }\n    else\n      mkImpCongr rp (\u2190 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 (\u2190 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 \u2190 simp b\n        let eNew \u2190 mkForallFVars #[x] rb.expr\n        match rb.proof? with\n        | none   => return { expr := eNew }\n        | some h => return { expr := eNew, proof? := (\u2190 mkForallCongr (\u2190 mkLambdaFVars #[x] h)) }\n    else\n      return { expr := (\u2190 dsimp e) }\n\n  simpLet (e : Expr) : M Result := do\n    if (\u2190 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 := (\u2190 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 \u2190 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 \u2190 simp e methods\n        if r.expr.isConstOf ``True then\n          try\n            return some (\u2190 mkOfEqTrue (\u2190 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\" (\u2190 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 \u2190 instantiateMVars (\u2190 getMVarType mvarId)\n  let r \u2190 simp target ctx\n  if r.expr.isConstOf ``True then\n    match r.proof? with\n    | some proof => assignExprMVar mvarId  (\u2190 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 \u00d7 Expr)) := do\n  let r \u2190 simp prop ctx\n  if r.expr.isConstOf ``False then\n    match r.proof? with\n    | some eqProof => assignExprMVar mvarId (\u2190 mkFalseElim (\u2190 getMVarType mvarId) (\u2190 mkEqMP eqProof proof))\n    | none => assignExprMVar mvarId (\u2190 mkFalseElim (\u2190 getMVarType mvarId) proof)\n    return none\n  else\n    match r.proof? with\n    | some eqProof => return some ((\u2190 mkEqMP eqProof proof), r.expr)\n    | none =>\n      if r.expr != prop then\n        return some ((\u2190 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 Aesop\n\nexample : True := by\n  aesop (rule_sets [Nonexistent])\n", "meta": {"author": "JLimperg", "repo": "aesop", "sha": "c68fb1d5a9172498230d81d95c61f6461bea6722", "save_path": "github-repos/lean/JLimperg-aesop", "path": "github-repos/lean/JLimperg-aesop/aesop-c68fb1d5a9172498230d81d95c61f6461bea6722/tests/golden/41.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.18713267309572335, "lm_q2_score": 0.026759281245071823, "lm_q1q2_score": 0.005007535829510547}}
{"text": "import .util\n\nmeta def unwrap_lm_response (ident : option string) : json \u2192 tactic (list string)\n| (json.array $ tactic_strings) := do\n    result \u2190 tactic_strings.mmap $ lift_option \u2218 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 \u2192 option json\n| (json.array xs) := json.of_float <$> xs.mfoldr (\u03bb 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 \u2192 tactic (list $ string \u00d7 native.float)\n| (json.array $ [(json.array predictions), (json.array scores)]) := do {\n  decoded_strings \u2190 predictions.mmap $ lift_option \u2218 json.get_string,\n  decoded_scores \u2190 scores.mmap $ lift_option \u2218 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 : \u03a0 (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  (\u03bb \u27e8\u27e8k\u2081, v\u2081\u27e9, \u27e8k\u2082, v\u2082\u27e9\u27e9 acc,\n  json.compare k\u2081 k\u2082 && json.compare v\u2081 v\u2082 && acc) tt\n| (json.array args) (json.array args') := (list.zip args args').foldr\n  (\u03bb \u27e8j\u2081, j\u2082\u27e9 acc, acc && json.compare j\u2081 j\u2082) tt\n| _ _ := ff\n\nmeta def json.to_raw_fmt : json \u2192 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 \u00d7 json \u2192 format :=\n  (\u03bb \u27e8k,v\u27e9, 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 \u2192 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 \u2218 unsigned.to_nat $ u), has_to_tactic_json_name_aux nm])]\n\nmeta def has_to_tactic_json_name_aux : name \u2192 json\n| anonymous := json.array \u2218 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 \u2218 unsigned.to_nat $ u), has_to_tactic_json_name_aux nm])]\n\nmeta instance : has_to_tactic_json name :=\n\u27e8pure \u2218 has_to_tactic_json_name_aux\u27e9\n\nend has_to_tactic_json_name\n\nsection has_from_json_name\n\n-- meta def has_from_json_name_aux : json \u2192 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) \u2190 (do {\n--       [json.of_string str, nm_json] \u2190 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) \u2190 (do {\n--       [json.of_int u, nm_json] \u2190 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 \u2218 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 \u2192 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) \u2190 (do {\n      [json.of_string str, nm_json] \u2190 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) \u2190 (do {\n      [json.of_int u, nm_json] \u2190 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 \u2218 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\u27e8has_from_json_name_aux\u27e9\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 \u2190 local_context,\n  (x::_) \u2190 tactic.intro_lst [`arg],\n  et \u2190 infer_type x,\n  xs \u2190 tactic.induction x,\n  xs.mmap' $ \u03bb \u27e8c, args, _\u27e9, do\n    (args', rec_call) \u2190 args.mpartition $ \u03bb e, do {e' \u2190 tactic.to_expr ``(tactic json), bnot <$> e'.occurs <$> tactic.infer_type e},\n    args'' \u2190 args'.mmap (\u03bb a, flip prod.mk a <$> (et.occurs <$> tactic.infer_type a)),\n    let fn : list (bool \u00d7 expr) \u2192 state_t (list expr) tactic (list expr) := \u03bb args'', do {\n      let pop : state_t (list expr) tactic (option expr) := do {\n        xs \u2190 get,\n        match xs with\n        | (a::as) := modify (\u03bb _, as) *> pure (some a)\n        | [] := pure none\n        end\n      },\n      args''.mmap (\u03bb \u27e8b, a\u27e9, if b then do (some x) \u2190 pop, pure x else state_t.lift $ do\n      a_tp \u2190 infer_type a,\n      _inst \u2190 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''' \u2190 prod.fst <$> (fn args'').run rec_call,\n\n\n    c \u2190 tactic.resolve_constant c,\n    refine ``((\u03bb (ys : list $ tactic json),\n      (\u03bb x, json.array [has_to_tactic_json_name_aux %%c,\n        json.array x]) <$>  ys.mmap id) _), -- lol\n    args'''.mmap (\u03bb 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 \u2190 local_context,\n  `(has_to_tactic_json %%f) \u2190 target,\n  env \u2190 get_env,\n  let n := f.get_app_fn.const_name,\n  d \u2190 get_decl n,\n  refine ``( { to_tactic_json := _ } ),\n  tgt \u2190 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 \u00d7 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 : \u03a0 (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 \u2190 (json_to_expr nm_json) >>= eval_expr name,\n--   constr \u2190 mk_const c_nm,\n--   if args.length = 0 then do {\n--   tp \u2190 tactic.infer_type constr,\n--   e_id \u2190 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 \u2190 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 \u2190 get_env,\n-- --   nm \u2190 (has_from_json_name_aux nm_json),\n-- --   -- d \u2190 env.get nm,\n-- --   ty_reflected \u2190 declaration.type <$> get_decl nm,\n\n-- --   _inst \u2190 to_expr ``(has_from_json %%nm) >>= mk_instance,\n-- --   _inst2 \u2190 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 : \u03a0 (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 \u2190 (has_from_json_name_aux nm_json),\n  constr \u2190 mk_const c_nm,\n  if args.length = 0 then do {\n  tp \u2190 tactic.infer_type constr,\n  e_id \u2190 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 \u2190 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 \u2190 get_env,\n--   nm \u2190 (has_from_json_name_aux nm_json),\n--   -- d \u2190 env.get nm,\n--   ty_reflected \u2190 declaration.type <$> get_decl nm,\n\n--   _inst \u2190 to_expr ``(has_from_json %%nm) >>= mk_instance,\n--   _inst2 \u2190 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::_) \u2190 tactic.intro_lst [`_arg],\n  real_tgt@`(tactic %%tgt) \u2190 target,\n  y \u2190 to_expr ``(json_to_expr %%x),\n  -- let real_tgt := ``(reflected $ tactic %%tgt),\n\n  -- _ \u2190 to_expr ``(do %%y >>= eval_expr unit),\n  -- tactic.read >>= \u03bb ts, tactic.trace format!\"TACTIC STATE AFTER EVAL: {ts}\",\n  -- pure ()\n  -- tac \u2190 eval_expr (tactic unit) y,\n  -- tac\n  -- `(tactic %%tgt) \u2190 target,\n  -- -- y \u2190 to_expr ``(@id (tactic %%tgt)) >>= (\u03bb 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 \u2190 to_expr ``(do %%y >>= eval_expr %%tgt),\n  gs \u2190 tactic.get_goals,\n\n  -- m \u2190 tactic.mk_meta_var real_tgt,\n  -- let m' := `([m]).to_expr,\n\n  -- result \u2190 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 \u2190 to_expr ``(do %%y) >>= eval_expr expr,\n\n  result \u2190 to_expr ``(do try trivial, m \u2190 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::_) \u2190 tactic.intro_lst [`_arg],\n--   let rec := `(pure () : tactic unit).to_expr,\n--   f \u2190 to_expr ``(match (get_constr_and_args %%x) with\n--   | (some \u27e8constr, args\u27e9) := %%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 \u2190 local_context,\n  `(has_from_json %%f) \u2190 target,\n  env \u2190 get_env,\n  let n := f.get_app_fn.const_name,\n  d \u2190 get_decl n,\n  refine ``( { from_json := _ } ),\n  tgt \u2190 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 : \u03b1)` -/\n-- | foo : DUH'\n-- /- `{x : \u03b1}` -/\n| bar : my_nat'\n| baz : my_nat' \u2192 my_nat'\n-- /- `\u2983x:\u03b1\u2984` -/\n-- | strict_implicit : DUH'\n-- /- `[x : \u03b1]`. 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 \u2192 tactic my_nat) >>= tactic.trace)\n\n-- meta instance : has_to_format my_nat :=\n-- \u27e8\u03bb x, match x with | my_nat.zero := \"my_nat.zero\" | (my_nat.succ x) := \"my_nat.succ \" ++ (by exact _match x) end\u27e9\n\n-- meta instance : has_from_json my_nat :=\n-- \u27e8\u03bb k,\n-- -- match k with\n-- -- | (json.object $ [(\"constr\", c), (\"args\", (json.array args))]) := do\n-- --   nm \u2190 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-- \u27e9\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 \u2192 tactic my_nat) >>= tactic.trace)\n\n@[derive [has_to_tactic_json, has_from_json]]\ninductive my_tree : Type\n| leaf : my_nat \u2192 my_tree\n| node : my_tree \u2192 my_tree \u2192 my_nat \u2192 my_tree\n\nmeta instance : has_to_format my_tree :=\n\u27e8\u03bb t, match t with\n| (my_tree.leaf k) := format!\"(leaf {k})\"\n| (my_tree.node t\u2081 t\u2082 k) := by exact format!\"(node {_match t\u2081} {_match t\u2082} {k})\"\nend\n\u27e9\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 \u2192 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-- \u27e8has_to_tactic_json.to_tactic_json \u2218 int.of_nat\u27e9\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\u27e8pure \u2218 json.of_int \u2218 int.of_nat\u27e9\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--  \u03bb x, tactic.trace x *> ((has_from_json.from_json : json \u2192 tactic \u2115) x >>= tactic.trace))\n\n-- meta instance : has_from_json nat :=\n-- \u27e8\u03bb 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-- \u27e9\n\n-- meta instance : has_to_tactic_json unsigned :=\n-- \u27e8has_to_tactic_json.to_tactic_json \u2218 unsigned.to_nat\u27e9\n\nmeta instance : has_from_json unsigned :=\n\u27e8\u03bb 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\u27e9\n\nmeta instance has_to_tactic_json_list {\u03b1} [h : has_to_tactic_json \u03b1] : has_to_tactic_json (list \u03b1) :=\n\u27e8by mk_to_tactic_json name.anonymous\u27e9\nuniverse u\n-- meta instance has_from_json_list {\u03b1 : Type u} [reflected \u03b1] [h : has_from_json \u03b1] : has_from_json (list \u03b1) :=\n-- \u27e8by mk_from_json name.anonymous\u27e9\n-- set_option formatter.hide_full_terms false\n-- run_cmd (has_to_tactic_json.to_tactic_json [1,2] >>= \u03bb x, tactic.trace x *> (has_from_json.from_json : json \u2192 tactic (list \u2115)) x)\n\nmeta instance has_from_json_list {\u03b1} [H : has_from_json \u03b1] : has_from_json (list \u03b1) :=\n\u27e8\u03bb msg, do\nlet \u27e8fn\u27e9 := H in\nmatch msg with\n| (json.array $ [c, json.array args]) := do\n  c_nm \u2190 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 \u2190 (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\u27e9\n\n-- run_cmd (has_to_tactic_json.to_tactic_json 2 >>= (has_from_json.from_json : json \u2192 tactic \u2115) >>= tactic.trace)\n\n-- run_cmd (has_to_tactic_json.to_tactic_json [1,2] >>= \u03bb x, tactic.trace x *> (has_from_json_list.from_json : json \u2192 tactic (list \u2115)) x >>= tactic.trace)\n\nmeta instance has_to_tactic_json_option {\u03b1} [has_to_tactic_json \u03b1] : has_to_tactic_json (option \u03b1) :=\n\u27e8by mk_to_tactic_json name.anonymous\u27e9\n\nmeta instance has_from_json_option {\u03b1} [H : has_from_json \u03b1] : has_from_json (option \u03b1) :=\n\u27e8\u03bb msg, do\nlet \u27e8fn\u27e9 := H in\nmatch msg with\n| (json.array $ [c, json.array args]) := do\n  c_nm \u2190 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\u27e9\n\n-- run_cmd (has_to_tactic_json.to_tactic_json (some [1,2]) >>= \u03bb x, tactic.trace x *> (has_from_json.from_json : json \u2192 tactic (option $ list \u2115)) x >>= tactic.trace) -- sweet\n\nmeta instance has_to_tactic_json_prod {\u03b1 \u03b2} [has_to_tactic_json \u03b1] [has_to_tactic_json \u03b2] : has_to_tactic_json (\u03b1 \u00d7 \u03b2) :=\n\u27e8by mk_to_tactic_json name.anonymous\u27e9\n\nmeta instance has_from_json_prod {\u03b1 \u03b2 : Type} [H : has_from_json \u03b1] [H' : has_from_json \u03b2] : has_from_json (prod \u03b1 \u03b2) :=\n\u27e8\u03bb msg, do\nlet \u27e8fn\u2081\u27e9 := H in\nlet \u27e8fn\u2082\u27e9 := H' in\nmatch msg with\n| (json.array $ [c, json.array args]) := do\n  (c_nm : name) \u2190 has_from_json_name_aux c,\n  if c_nm = `prod.mk then prod.mk <$> (args.nth 0 >>= fn\u2081) <*> (args.nth 1 >>= fn\u2082) else\n  tactic.fail format!\"[has_from_json_prod] unexpected {msg}\"\n| exc := tactic.fail \"[has_from_json_prod] unexpected {exc}\"\nend\n\u27e9\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 \u2192 expr'\n| sort        : level \u2192 expr'\n| const       : name \u2192 list level \u2192 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' \u2192 expr' \u2192 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' \u2192 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\u2081 e\u2082) := (expr.app (expr'.to_expr e\u2081) (expr'.to_expr e\u2082))\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' \u2192 tactic expr := \u03bb x, tactic.trace \"CONVERTING TO EXPR\" *> (x.to_expr)\n\nmeta def expr.to_expr' : expr \u2192 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\u2081 e\u2082) := (expr'.app <$> (expr.to_expr' e\u2081) <*> (expr.to_expr' e\u2082))\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-- \u27e8\u03bb msg, match msg with\n--   | (json.object $ [(\"constr\", c), (\"args\", json.array args)]) := do\n--     (c_nm : name) \u2190 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] \u2190 pure args, result \u2190 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-- \u27e9\n\nend expr'\n\nmeta instance : has_to_tactic_json expr :=\n\u27e8\u03bb e, e.erase_annotations.to_expr' >>= has_to_tactic_json.to_tactic_json\u27e9\n\nmeta instance : has_from_json expr :=\n\u27e8\u03bb msg, expr'.to_expr <$> (has_from_json.from_json : json \u2192 tactic expr') msg\u27e9\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 >>= (\u03bb x, tactic.trace x *> ((has_from_json.from_json : json \u2192 tactic name) x >>= tactic.trace)))\n\n-- private theorem foo {p q : Prop} : p \u2192 q \u2192 \u2200 r, (p \u2227 q) \u2228 r :=\n-- \u03bb h\u2081 h\u2082 h\u2083, or.inl (and.intro \u2039_\u203a \u2039_\u203a)\n\nmeta instance : has_to_tactic_json bool := \u27e8\u03bb b, pure \u2191b\u27e9\nmeta instance : has_from_json bool := \u27e8\u03bb msg, match msg with\n| (json.of_bool b) := pure b\n| exc := tactic.fail format!\"[has_from_json_bool] unexpected: {exc}\"\nend\n\u27e9\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 Cat\n\ndef main : IO Unit :=\n  IO.println s!\"lif sux\"\n\ntheorem easy : True := by\n  have nested (n : Nat) : True := by\n    \n", "meta": {"author": "AdrienChampion", "repo": "experimentalean4", "sha": "5071a8b007029f61b2e996d9ac89d90999603fcc", "save_path": "github-repos/lean/AdrienChampion-experimentalean4", "path": "github-repos/lean/AdrienChampion-experimentalean4/experimentalean4-5071a8b007029f61b2e996d9ac89d90999603fcc/cat/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.1500288243424251, "lm_q2_score": 0.033085981248949035, "lm_q1q2_score": 0.004963850868995345}}
{"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.ResolveName\nimport Lean.Util.Sorry\nimport Lean.Util.ReplaceExpr\nimport Lean.Structure\nimport Lean.Meta.ExprDefEq\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.SynthInstance\nimport Lean.Meta.CollectMVars\nimport Lean.Meta.Coe\nimport Lean.Meta.Tactic.Util\nimport Lean.Hygiene\nimport Lean.Util.RecDepth\nimport Lean.Elab.Log\nimport Lean.Elab.Level\nimport Lean.Elab.Attributes\nimport Lean.Elab.AutoBound\nimport Lean.Elab.InfoTree\nimport Lean.Elab.Open\nimport Lean.Elab.SetOption\n\nnamespace Lean.Elab.Term\n/-\n  Set isDefEq configuration for the elaborator.\n  Note that we enable all approximations but `quasiPatternApprox`\n\n  In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.\n  The example:\n  ```\n  def ex : StateT \u03b4 (StateT \u03c3 Id) \u03c3 :=\n  monadLift (get : StateT \u03c3 Id \u03c3)\n  ```\n  demonstrates why it produces counterintuitive behavior.\n  We have the `Monad-lift` application:\n  ```\n  @monadLift ?m ?n ?c ?\u03b1 (get : StateT \u03c3 id \u03c3) : ?n ?\u03b1\n  ```\n  It produces the following unification problem when we process the expected type:\n  ```\n  ?n ?\u03b1 =?= StateT \u03b4 (StateT \u03c3 id) \u03c3\n  ==> (approximate using first-order unification)\n  ?n := StateT \u03b4 (StateT \u03c3 id)\n  ?\u03b1 := \u03c3\n  ```\n  Then, we need to solve:\n  ```\n  ?m ?\u03b1 =?= StateT \u03c3 id \u03c3\n  ==> instantiate metavars\n  ?m \u03c3 =?= StateT \u03c3 id \u03c3\n  ==> (approximate since it is a quasi-pattern unification constraint)\n  ?m := fun \u03c3 => StateT \u03c3 id \u03c3\n  ```\n  Note that the constraint is not a Milner pattern because \u03c3 is in\n  the local context of `?m`. We are ignoring the other possible solutions:\n  ```\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3' id \u03c3\n  ?m := fun \u03c3' => StateT \u03c3 id \u03c3'\n  ```\n\n  We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).\n\n  If we had use first-order unification, then we would have produced\n  the right answer: `?m := StateT \u03c3 id`\n\n  Haskell would work on this example since it always uses\n  first-order unification.\n-/\ndef setElabConfig (cfg : Meta.Config) : Meta.Config :=\n  { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }\n\nstructure Context where\n  fileName        : String\n  fileMap         : FileMap\n  declName?       : Option Name     := none\n  macroStack      : MacroStack      := []\n  currMacroScope  : MacroScope      := firstFrontendMacroScope\n  /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.\n     The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in\n     the list of pending synthetic metavariables, and returns `?m`. -/\n  mayPostpone     : Bool            := true\n  /- When `errToSorry` is set to true, the method `elabTerm` catches\n     exceptions and converts them into synthetic `sorry`s.\n     The implementation of choice nodes and overloaded symbols rely on the fact\n     that when `errToSorry` is set to false for an elaboration function `F`, then\n     `errToSorry` remains `false` for all elaboration functions invoked by `F`.\n     That is, it is safe to transition `errToSorry` from `true` to `false`, but\n     we must not set `errToSorry` to `true` when it is currently set to `false`. -/\n  errToSorry      : Bool            := true\n  /- When `autoBoundImplicit` is set to true, instead of producing\n     an \"unknown identifier\" error for unbound variables, we generate an\n     internal exception. This exception is caught at `elabBinders` and\n     `elabTypeWithUnboldImplicit`. Both methods add implicit declarations\n     for the unbound variable and try again. -/\n  autoBoundImplicit  : Bool            := false\n  autoBoundImplicits : Std.PArray Expr := {}\n  /-- Map from user name to internal unique name -/\n  sectionVars        : NameMap Name    := {}\n  /-- Map from internal name to fvar -/\n  sectionFVars       : NameMap Expr    := {}\n  /-- Enable/disable implicit lambdas feature. -/\n  implicitLambda     : Bool            := true\n\n/-- Saved context for postponed terms and tactics to be executed. -/\nstructure SavedContext where\n  declName?  : Option Name\n  options    : Options\n  openDecls  : List OpenDecl\n  macroStack : MacroStack\n  errToSorry : Bool\n\n/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/\ninductive SyntheticMVarKind where\n  -- typeclass instance search\n  | typeClass\n  /- Similar to typeClass, but error messages are different.\n     if `f?` is `some f`, we produce an application type mismatch error message.\n     Otherwise, if `header?` is `some header`, we generate the error `(header ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)`\n     Otherwise, we generate the error `(\"type mismatch\" ++ e ++ \"has type\" ++ eType ++ \"but it is expected to have type\" ++ expectedType)` -/\n  | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)\n  -- tactic block execution\n  | tactic (tacticCode : Syntax) (ctx : SavedContext)\n  -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)\n  | postponed (ctx : SavedContext)\n\ninstance : ToString SyntheticMVarKind where\n  toString\n    | SyntheticMVarKind.typeClass    => \"typeclass\"\n    | SyntheticMVarKind.coe ..       => \"coe\"\n    | SyntheticMVarKind.tactic ..    => \"tactic\"\n    | SyntheticMVarKind.postponed .. => \"postponed\"\n\nstructure SyntheticMVarDecl where\n  mvarId : MVarId\n  stx : Syntax\n  kind : SyntheticMVarKind\n\ninductive MVarErrorKind where\n  | implicitArg (ctx : Expr)\n  | hole\n  | custom (msgData : MessageData)\n\ninstance : ToString MVarErrorKind where\n  toString\n    | MVarErrorKind.implicitArg ctx => \"implicitArg\"\n    | MVarErrorKind.hole            => \"hole\"\n    | MVarErrorKind.custom msg      => \"custom\"\n\nstructure MVarErrorInfo where\n  mvarId    : MVarId\n  ref       : Syntax\n  kind      : MVarErrorKind\n\nstructure LetRecToLift where\n  ref            : Syntax\n  fvarId         : FVarId\n  attrs          : Array Attribute\n  shortDeclName  : Name\n  declName       : Name\n  lctx           : LocalContext\n  localInstances : LocalInstances\n  type           : Expr\n  val            : Expr\n  mvarId         : MVarId\n\nstructure State where\n  levelNames        : List Name       := []\n  syntheticMVars    : List SyntheticMVarDecl := []\n  mvarErrorInfos    : List MVarErrorInfo := []\n  messages          : MessageLog := {}\n  letRecsToLift     : List LetRecToLift := []\n  infoState         : InfoState := {}\n  deriving Inhabited\n\nabbrev TermElabM := ReaderT Context $ StateRefT State MetaM\nabbrev TermElab  := Syntax \u2192 Option Expr \u2192 TermElabM Expr\n\nopen Meta\n\ninstance : Inhabited (TermElabM \u03b1) where\n  default := throw arbitrary\n\nstructure SavedState where\n  meta   : Meta.SavedState\n  \u00abelab\u00bb : State\n  deriving Inhabited\n\nprotected def saveState : TermElabM SavedState := do\n  pure { meta := (\u2190 Meta.saveState), \u00abelab\u00bb := (\u2190 get) }\n\ndef SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do\n  let traceState \u2190 getTraceState -- We never backtrack trace message\n  let infoState := (\u2190 get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false`\n  s.meta.restore\n  set s.elab\n  setTraceState traceState\n  unless restoreInfo do\n    modify fun s => { s with infoState := infoState }\n\ninstance : MonadBacktrack SavedState TermElabM where\n  saveState      := Term.saveState\n  restoreState b := b.restore\n\nabbrev TermElabResult (\u03b1 : Type) := EStateM.Result Exception SavedState \u03b1\n\ninstance [Inhabited \u03b1] : Inhabited (TermElabResult \u03b1) where\n  default := EStateM.Result.ok arbitrary arbitrary\n\ndef setMessageLog (messages : MessageLog) : TermElabM Unit :=\n  modify fun s => { s with messages := messages }\n\ndef resetMessageLog : TermElabM Unit :=\n  setMessageLog {}\n\ndef getMessageLog : TermElabM MessageLog :=\n  return (\u2190 get).messages\n\n/--\n  Execute `x`, save resulting expression and new state.\n  We remove any `Info` created by `x`.\n  The info nodes are committed when we execute `applyResult`.\n  We use `observing` to implement overloaded notation and decls.\n  We want to save `Info` nodes for the chosen alternative.\n-/\n@[inline] def observing (x : TermElabM \u03b1) : TermElabM (TermElabResult \u03b1) := do\n  let s \u2190 saveState\n  try\n    let e \u2190 x\n    let sNew \u2190 saveState\n    s.restore (restoreInfo := true)\n    pure (EStateM.Result.ok e sNew)\n  catch\n    | ex@(Exception.error _ _) =>\n      let sNew \u2190 saveState\n      s.restore (restoreInfo := true)\n      pure (EStateM.Result.error ex sNew)\n    | ex@(Exception.internal id _) =>\n      if id == postponeExceptionId then\n        s.restore (restoreInfo := true)\n      throw ex\n\n/--\n  Apply the result/exception and state captured with `observing`.\n  We use this method to implement overloaded notation and symbols. -/\n@[inline] def applyResult (result : TermElabResult \u03b1) : TermElabM \u03b1 :=\n  match result with\n  | EStateM.Result.ok a r     => do r.restore (restoreInfo := true); pure a\n  | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex\n\n/--\n  Execute `x`, but keep state modifications only if `x` did not postpone.\n  This method is useful to implement elaboration functions that cannot decide whether\n  they need to postpone or not without updating the state. -/\ndef commitIfDidNotPostpone (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  -- We just reuse the implementation of `observing` and `applyResult`.\n  let r \u2190 observing x\n  applyResult r\n\n/--\n  Execute `x` but discard changes performed at `Term.State` and `Meta.State`.\n  Recall that the environment is at `Core.State`. Thus, any updates to it will\n  be preserved. This method is useful for performing computations where all\n  metavariable must be resolved or discarded. -/\ndef withoutModifyingElabMetaState (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let s \u2190 get\n  let sMeta \u2190 getThe Meta.State\n  try\n    x\n  finally\n    set s\n    set sMeta\n\ndef getLevelNames : TermElabM (List Name) :=\n  return (\u2190 get).levelNames\n\ndef getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do\n  match (\u2190 getLCtx).find? fvar.fvarId! with\n  | some d => pure d\n  | none   => unreachable!\n\ninstance : AddErrorMessageContext TermElabM where\n  add ref msg := do\n    let ctx \u2190 read\n    let ref := getBetterRef ref ctx.macroStack\n    let msg \u2190 addMessageContext msg\n    let msg \u2190 addMacroStack msg ctx.macroStack\n    pure (ref, msg)\n\ninstance : MonadLog TermElabM where\n  getRef      := getRef\n  getFileMap  := return (\u2190 read).fileMap\n  getFileName := return (\u2190 read).fileName\n  logMessage msg := do\n    let ctx \u2190 readThe Core.Context\n    let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };\n    modify fun s => { s with messages := s.messages.add msg }\n\nprotected def getCurrMacroScope : TermElabM MacroScope := do pure (\u2190 read).currMacroScope\nprotected def getMainModule     : TermElabM Name := do pure (\u2190 getEnv).mainModule\n\n@[inline] protected def withFreshMacroScope (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let fresh \u2190 modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))\n  withReader (fun ctx => { ctx with currMacroScope := fresh }) x\n\ninstance : MonadQuotation TermElabM where\n  getCurrMacroScope   := Term.getCurrMacroScope\n  getMainModule       := Term.getMainModule\n  withFreshMacroScope := Term.withFreshMacroScope\n\ninstance : MonadInfoTree TermElabM where\n  getInfoState      := return (\u2190 get).infoState\n  modifyInfoState f := modify fun s => { s with infoState := f s.infoState }\n\nunsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=\n  mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab \"term\"\n\n@[implementedBy mkTermElabAttributeUnsafe]\nconstant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)\n\nbuiltin_initialize termElabAttribute : KeyedDeclsAttribute TermElab \u2190 mkTermElabAttribute\n\n/--\n  Auxiliary datatatype for presenting a Lean lvalue modifier.\n  We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.\n  Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list\n  `[LVal.fieldName \"foo\", LVal.getOp i, LVal.fieldIdx 1]`.\n  Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/\ninductive LVal where\n  | fieldIdx  (ref : Syntax) (i : Nat)\n    /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name.\n       `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/\n  | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)\n  | getOp     (ref : Syntax) (idx : Syntax)\n\ndef LVal.getRef : LVal \u2192 Syntax\n  | LVal.fieldIdx ref _    => ref\n  | LVal.fieldName ref ..  => ref\n  | LVal.getOp ref _       => ref\n\ndef LVal.isFieldName : LVal \u2192 Bool\n  | LVal.fieldName .. => true\n  | _ => false\n\ninstance : ToString LVal where\n  toString\n    | LVal.fieldIdx _ i     => toString i\n    | LVal.fieldName _ n .. => n\n    | LVal.getOp _ idx      => \"[\" ++ toString idx ++ \"]\"\n\ndef getDeclName? : TermElabM (Option Name) := return (\u2190 read).declName?\ndef getLetRecsToLift : TermElabM (List LetRecToLift) := return (\u2190 get).letRecsToLift\ndef isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (\u2190 getMCtx).isExprAssigned mvarId\ndef getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (\u2190 getMCtx).getDecl mvarId\ndef assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }\n\ndef withDeclName (name : Name) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with declName? := name }) x\n\ndef setLevelNames (levelNames : List Name) : TermElabM Unit :=\n  modify fun s => { s with levelNames := levelNames }\n\ndef withLevelNames (levelNames : List Name) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let levelNamesSaved \u2190 getLevelNames\n  setLevelNames levelNames\n  try x finally setLevelNames levelNamesSaved\n\ndef withoutErrToSorry (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with errToSorry := false }) x\n\n/-- For testing `TermElabM` methods. The #eval command will sign the error. -/\ndef throwErrorIfErrors : TermElabM Unit := do\n  if (\u2190 get).messages.hasErrors then\n    throwError \"Error(s)\"\n\n@[inline] def traceAtCmdPos (cls : Name) (msg : Unit \u2192 MessageData) : TermElabM Unit :=\nwithRef Syntax.missing $ trace cls msg\n\ndef ppGoal (mvarId : MVarId) : TermElabM Format :=\n  Meta.ppGoal mvarId\n\nopen Level (LevelElabM)\n\ndef liftLevelM (x : LevelElabM \u03b1) : TermElabM \u03b1 := do\n  let ctx \u2190 read\n  let ref \u2190 getRef\n  let mctx \u2190 getMCtx\n  let ngen \u2190 getNGen\n  let lvlCtx : Level.Context := { options := (\u2190 getOptions), ref := ref, autoBoundImplicit := ctx.autoBoundImplicit }\n  match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (\u2190 getLevelNames) } with\n  | EStateM.Result.ok a newS  => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a\n  | EStateM.Result.error ex _ => throw ex\n\ndef elabLevel (stx : Syntax) : TermElabM Level :=\n  liftLevelM $ Level.elabLevel stx\n\n/- Elaborate `x` with `stx` on the macro stack -/\n@[inline] def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withMacroExpansionInfo beforeStx afterStx do\n    withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x\n\n/-\n  Add the given metavariable to the list of pending synthetic metavariables.\n  The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/\ndef registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }\n\ndef registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do\n  registerSyntheticMVar (\u2190 getRef) mvarId kind\n\ndef registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do\n  modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos }\n\ndef registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do\n  modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos }\n\ndef registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do\n  modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos }\n\ndef registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=\n  match e.getAppFn with\n  | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData\n  | _ => pure ()\n\n/-\n  Auxiliary method for reporting errors of the form \"... contains metavariables ...\".\n  This kind of error is thrown, for example, at `Match.lean` where elaboration\n  cannot continue if there are metavariables in patterns.\n  We only want to log it if we haven't logged any error so far. -/\ndef throwMVarError (m : MessageData) : TermElabM \u03b1 := do\n  if (\u2190 get).messages.hasErrors then\n    throwAbortTerm\n  else\n    throwError m\n\ndef MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do\n  match mvarErrorInfo.kind with\n  | MVarErrorKind.implicitArg app => do\n    let app \u2190 instantiateMVars app\n    let msg : MessageData := m!\"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}\"\n    let msg := msg ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\n  | MVarErrorKind.hole => do\n    let msg : MessageData := \"don't know how to synthesize placeholder\"\n    let msg := msg ++ Format.line ++ \"context:\" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId\n    logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)\n  | MVarErrorKind.custom msg =>\n    logErrorAt mvarErrorInfo.ref (appendExtra msg)\nwhere\n  appendExtra (msg : MessageData) : MessageData :=\n    match extraMsg? with\n    | none => msg\n    | some extraMsg => msg ++ extraMsg\n\n/--\n  Try to log errors for the unassigned metavariables `pendingMVarIds`.\n\n  Return `true` if there were \"unfilled holes\", and we should \"abort\" declaration.\n  TODO: try to fill \"all\" holes using synthetic \"sorry's\"\n\n  Remark: We only log the \"unfilled holes\" as new errors if no error has been logged so far. -/\ndef logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do\n  let s \u2190 get\n  let hasOtherErrors := s.messages.hasErrors\n  let mut hasNewErrors := false\n  let mut alreadyVisited : NameSet := {}\n  for mvarErrorInfo in s.mvarErrorInfos do\n    let mvarId := mvarErrorInfo.mvarId\n    unless alreadyVisited.contains mvarId do\n      alreadyVisited := alreadyVisited.insert mvarId\n      let foundError \u2190 withMVarContext mvarId do\n        /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or\n           delayed assigned to another metavariable that is unassigned. -/\n        let mvarDeps \u2190 getMVars (mkMVar mvarId)\n        if mvarDeps.any pendingMVarIds.contains then do\n          unless hasOtherErrors do\n            mvarErrorInfo.logError extraMsg?\n          pure true\n        else\n          pure false\n      if foundError then\n        hasNewErrors := true\n  return hasNewErrors\n\n/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/\ndef ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do\n  let pendingMVarIds \u2190 getMVarsAtDecl decl\n  if (\u2190 logUnassignedUsingErrorInfos pendingMVarIds) then\n    throwAbortCommand\n\n/-\n  Execute `x` without allowing it to postpone elaboration tasks.\n  That is, `tryPostpone` is a noop. -/\n@[inline] def withoutPostponing (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withReader (fun ctx => { ctx with mayPostpone := false }) x\n\n/-- Creates syntax for `(` <ident> `:` <type> `)` -/\ndef mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=\n  mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom \"(\", mkNullNode #[ident], mkNullNode #[mkAtom \":\", type], mkNullNode, mkAtom \")\"]\n\n/--\n  Convert unassigned universe level metavariables into parameters.\n  The new parameter names are of the form `u_i` where `i >= nextParamIdx`.\n  The method returns the updated expression and new `nextParamIdx`.\n\n  Remark: we make sure the generated parameter names do not clash with the universes at `ctx.levelNames`. -/\ndef levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr \u00d7 Nat) := do\n  let mctx \u2190 getMCtx\n  let levelNames \u2190 getLevelNames\n  let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx\n  setMCtx r.mctx\n  pure (r.expr, r.nextParamIdx)\n\n/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/\ndef levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do\n  let nextParamIdx \u2190 get\n  let (e, nextParamIdx) \u2190 levelMVarToParam e nextParamIdx\n  set nextParamIdx\n  pure e\n\n/--\n  Auxiliary method for creating fresh binder names.\n  Do not confuse with the method for creating fresh free/meta variable ids. -/\ndef mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=\n  withFreshMacroScope $ MonadQuotation.addMacroScope `x\n\n/--\n  Auxiliary method for creating a `Syntax.ident` containing\n  a fresh name. This method is intended for creating fresh binder names.\n  It is just a thin layer on top of `mkFreshUserName`. -/\ndef mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax :=\n  return mkIdentFrom ref (\u2190 mkFreshBinderName)\n\nprivate def applyAttributesCore\n    (declName : Name) (attrs : Array Attribute)\n    (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=\n  for attr in attrs do\n    let env \u2190 getEnv\n    match getAttributeImpl env attr.name with\n    | Except.error errMsg => throwError errMsg\n    | Except.ok attrImpl  =>\n      match applicationTime? with\n      | none => attrImpl.add declName attr.stx attr.kind\n      | some applicationTime =>\n        if applicationTime == attrImpl.applicationTime then\n          attrImpl.add declName attr.stx attr.kind\n\n/-- Apply given attributes **at** a given application time -/\ndef applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=\n  applyAttributesCore declName attrs applicationTime\n\ndef applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=\n  applyAttributesCore declName attrs none\n\ndef mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do\n  let header : MessageData := match header? with\n    | some header => m!\"{header} \"\n    | none        => m!\"type mismatch{indentExpr e}\\n\"\n  return m!\"{header}{\u2190 mkHasTypeButIsExpectedMsg eType expectedType}\"\n\ndef throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM \u03b1 := do\n  /-\n    We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was\n    always of the form:\n    ```\n    failed to synthesize instance\n      CoeT <eType> <e> <expectedType>\n    ```\n    We should revisit this decision in the future and decide whether it may contain useful information\n    or not. -/\n  let extraMsg := Format.nil\n  /-\n  let extraMsg : MessageData := match extraMsg? with\n    | none          => Format.nil\n    | some extraMsg => Format.line ++ extraMsg;\n  -/\n  match f? with\n  | none   => throwError \"{\u2190 mkTypeMismatchError header? e eType expectedType}{extraMsg}\"\n  | some f => Meta.throwAppTypeMismatch f e extraMsg\n\n@[inline] def withoutMacroStackAtErr (x : TermElabM \u03b1) : TermElabM \u03b1 :=\n  withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x\n\n/- Try to synthesize metavariable using type class resolution.\n   This method assumes the local context and local instances of `instMVar` coincide\n   with the current local context and local instances.\n   Return `true` if the instance was synthesized successfully, and `false` if\n   the instance contains unassigned metavariables that are blocking the type class\n   resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/\ndef synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do\n  let instMVarDecl \u2190 getMVarDecl instMVar\n  let type := instMVarDecl.type\n  let type \u2190 instantiateMVars type\n  let result \u2190 trySynthInstance type maxResultSize?\n  match result with\n  | LOption.some val =>\n    if (\u2190 isExprMVarAssigned instMVar) then\n      let oldVal \u2190 instantiateMVars (mkMVar instMVar)\n      unless (\u2190 isDefEq oldVal val) do\n        let oldValType \u2190 inferType oldVal\n        let valType \u2190 inferType val\n        unless (\u2190 isDefEq oldValType valType) do\n          throwError \"synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\\nhas type{indentExpr valType}\\nexpected{indentExpr oldValType}\"\n        throwError \"synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\\ninferred{indentExpr oldVal}\"\n    else\n      unless (\u2190 isDefEq (mkMVar instMVar) val) do\n        throwError \"failed to assign synthesized type class instance{indentExpr val}\"\n    pure true\n  | LOption.undef    => pure false -- we will try later\n  | LOption.none     => throwError \"failed to synthesize instance{indentExpr type}\"\n\nregister_builtin_option autoLift : Bool := {\n  defValue := true\n  descr    := \"insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed\"\n}\n\nregister_builtin_option maxCoeSize : Nat := {\n  defValue := 16\n  descr    := \"maximum number of instances used to construct an automatic coercion\"\n}\n\ndef synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do\n  synthesizeInstMVarCore instMVar (some (maxCoeSize.get (\u2190 getOptions)))\n\n/-\nThe coercion from `\u03b1` to `Thunk \u03b1` cannot be implemented using an instance because it would\neagerly evaluate `e` -/\ndef tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do\n  match expectedType with\n  | Expr.app (Expr.const ``Thunk u _) arg _ =>\n    if (\u2190 isDefEq eType arg) then\n      pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e)))\n    else\n      pure none\n  | _ =>\n    pure none\n\n/--\n  Try to apply coercion to make sure `e` has type `expectedType`.\n  Relevant definitions:\n  ```\n  class CoeT (\u03b1 : Sort u) (a : \u03b1) (\u03b2 : Sort v)\n  abbrev coe {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeT \u03b1 a \u03b2] : \u03b2\n  ```\n-/\nprivate def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do\n  if (\u2190 isDefEq expectedType eType) then\n    return e\n  else match (\u2190 tryCoeThunk? expectedType eType e) with\n    | some r => return r\n    | none   =>\n      let u \u2190 getLevel eType\n      let v \u2190 getLevel expectedType\n      let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType]\n      let mvar \u2190 mkFreshExprMVar coeTInstType MetavarKind.synthetic\n      let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar]\n      let mvarId := mvar.mvarId!\n      try\n        withoutMacroStackAtErr do\n          if (\u2190 synthesizeCoeInstMVarCore mvarId) then\n            expandCoe eNew\n          else\n            -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe`\n            -- after we syntheze `mvar`\n            let mvarAux \u2190 mkFreshExprMVar expectedType MetavarKind.syntheticOpaque\n            registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?)\n            return mvarAux\n      catch\n        | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg\n        | _                     => throwTypeMismatchError errorMsgHeader? expectedType eType e f?\n\ndef isTypeApp? (type : Expr) : TermElabM (Option (Expr \u00d7 Expr)) := do\n  let type \u2190 withReducible $ whnf type\n  match type with\n  | Expr.app m \u03b1 _ => pure (some ((\u2190 instantiateMVars m), (\u2190 instantiateMVars \u03b1)))\n  | _              => pure none\n\ndef synthesizeInst (type : Expr) : TermElabM Expr := do\n  let type \u2190 instantiateMVars type\n  match (\u2190 trySynthInstance type) with\n  | LOption.some val => pure val\n  | LOption.undef    => throwError \"failed to synthesize instance{indentExpr type}\"\n  | LOption.none     => throwError \"failed to synthesize instance{indentExpr type}\"\n\ndef isMonadApp (type : Expr) : TermElabM Bool := do\n  let some (m, _) \u2190 isTypeApp? type | pure false\n  return (\u2190 isMonad? m) |>.isSome\n\n/--\n  Try to coerce `a : \u03b1` into `m \u03b2` by first coercing `a : \u03b1` into \u2035\u03b2`, and then using `pure`.\n  The method is only applied if `\u03b1` is not monadic (e.g., `Nat \u2192 IO Unit`), and the head symbol\n  of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool \u2192 ?m Nat`).\n\n  The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism\n  do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y`\n  since none of them is polymorphic\n  ```\n  def f (x : Bool) : IO Bool := do\n  let y \u2190 if x == 0 then IO.println \"hello\"; true else false;\n  !y\n  ```\n  On the other hand, the following fails since `+` is polymorphic\n  ```\n  def f (x : Bool) : IO Nat := do\n  IO.prinln x\n  x + x  -- Error: failed to synthesize `Add (IO Nat)`\n  ```\n-/\nprivate def tryPureCoe? (errorMsgHeader? : Option String) (m \u03b2 \u03b1 a : Expr) : TermElabM (Option Expr) :=\n  commitWhenSome? do\n    let doIt : TermElabM (Option Expr) := do\n      try\n        let aNew \u2190 tryCoe errorMsgHeader? \u03b2 \u03b1 a none\n        let aNew \u2190 mkPure m aNew\n        pure (some aNew)\n      catch _ =>\n        pure none\n    forallTelescope \u03b1 fun _ \u03b1 => do\n      if (\u2190 isMonadApp \u03b1) then\n        pure none\n      else if !\u03b1.getAppFn.isMVar  then\n        doIt\n      else\n        pure none\n\n/-\nTry coercions and monad lifts to make sure `e` has type `expectedType`.\n\nIf `expectedType` is of the form `n \u03b2`, we try monad lifts and other extensions.\nOtherwise, we just use the basic `tryCoe`.\n\nExtensions for monads.\n\nGiven an expected type of the form `n \u03b2`, if `eType` is of the form `\u03b1`, but not `m \u03b1`\n\n1 - Try to coerce \u2035\u03b1` into \u2035\u03b2`, and use `pure` to lift it to `n \u03b1`.\n    It only works if `n` implements `Pure`\n\nIf `eType` is of the form `m \u03b1`. We use the following approaches.\n\n1- Try to unify `n` and `m`. If it succeeds, then we use\n   ```\n   coeM {m : Type u \u2192 Type v} {\u03b1 \u03b2 : Type u} [\u2200 a, CoeT \u03b1 a \u03b2] [Monad m] (x : m \u03b1) : m \u03b2\n   ```\n   `n` must be a `Monad` to use this one.\n\n2- If there is monad lift from `m` to `n` and we can unify `\u03b1` and `\u03b2`, we use\n  ```\n  liftM : \u2200 {m : Type u_1 \u2192 Type u_2} {n : Type u_1 \u2192 Type u_3} [self : MonadLiftT m n] {\u03b1 : Type u_1}, m \u03b1 \u2192 n \u03b1\n  ```\n  Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as\n  ```\n  def g (x : Nat) : IO Nat := do\n    IO.println x\n    pure x\n\n  def f {m} [MonadLiftT IO m] : m Nat :=\n    g 10\n\n  ```\n\n3- If there is a monad lif from `m` to `n` and a coercion from `\u03b1` to `\u03b2`, we use\n  ```\n  liftCoeM {m : Type u \u2192 Type v} {n : Type u \u2192 Type w} {\u03b1 \u03b2 : Type u} [MonadLiftT m n] [\u2200 a, CoeT \u03b1 a \u03b2] [Monad n] (x : m \u03b1) : n \u03b2\n  ```\n\nNote that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `\u03b1` to `\u03b2` for all values in `\u03b1`.\nThis is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and\nwe only have a coercion from decidable propositions.  Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`\nusing the instance `pureCoeDepProp`.\n\nNote that, approach 2 is more powerful than `tryCoe`.\nRecall that type class resolution never assigns metavariables created by other modules.\nNow, consider the following scenario\n```lean\ndef g (x : Nat) : IO Nat := ...\ndeg h (x : Nat) : StateT Nat IO Nat := do\nv \u2190 g x;\nIO.Println v;\n...\n```\nLet's assume there is no other occurrence of `v` in `h`.\nThus, we have that the expected of `g x` is `StateT Nat IO ?\u03b1`,\nand the given type is `IO Nat`. So, even if we add a coercion.\n```\ninstance {\u03b1 m n} [MonadLiftT m n] {\u03b1} : Coe (m \u03b1) (n \u03b1) := ...\n```\nIt is not applicable because TC would have to assign `?\u03b1 := Nat`.\nOn the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`\nsince this goal does not contain any metavariables. And then, we\nconvert `g x` into `liftM $ g x`.\n-/\nprivate def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 instantiateMVars expectedType\n  let eType \u2190 instantiateMVars eType\n  let throwMismatch {\u03b1} : TermElabM \u03b1 := throwTypeMismatchError errorMsgHeader? expectedType eType e f?\n  let tryCoeSimple : TermElabM Expr :=\n    tryCoe errorMsgHeader? expectedType eType e f?\n  let some (n, \u03b2) \u2190 isTypeApp? expectedType | tryCoeSimple\n  let tryPureCoeAndSimple : TermElabM Expr := do\n    if autoLift.get (\u2190 getOptions) then\n      match (\u2190 tryPureCoe? errorMsgHeader? n \u03b2 eType e) with\n      | some eNew => pure eNew\n      | none      => tryCoeSimple\n    else\n      tryCoeSimple\n  let some (m, \u03b1) \u2190 isTypeApp? eType | tryPureCoeAndSimple\n  if (\u2190 isDefEq m n) then\n    let some monadInst \u2190 isMonad? n | tryCoeSimple\n    try expandCoe (\u2190 mkAppOptM ``coeM #[m, \u03b1, \u03b2, none, monadInst, e]) catch _ => throwMismatch\n  else if autoLift.get (\u2190 getOptions) then\n    try\n      -- Construct lift from `m` to `n`\n      let monadLiftType \u2190 mkAppM ``MonadLiftT #[m, n]\n      let monadLiftVal  \u2190 synthesizeInst monadLiftType\n      let u_1 \u2190 getDecLevel \u03b1\n      let u_2 \u2190 getDecLevel eType\n      let u_3 \u2190 getDecLevel expectedType\n      let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, \u03b1, e]\n      let eNewType \u2190 inferType eNew\n      if (\u2190 isDefEq expectedType eNewType) then\n        return eNew -- approach 2 worked\n      else\n        let some monadInst \u2190 isMonad? n | tryCoeSimple\n        let u \u2190 getLevel \u03b1\n        let v \u2190 getLevel \u03b2\n        let coeTInstType := Lean.mkForall `a BinderInfo.default \u03b1 $ mkAppN (mkConst ``CoeT [u, v]) #[\u03b1, mkBVar 0, \u03b2]\n        let coeTInstVal \u2190 synthesizeInst coeTInstType\n        let eNew \u2190 expandCoe (\u2190 mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, \u03b1, \u03b2, monadLiftVal, coeTInstVal, monadInst, e])\n        let eNewType \u2190 inferType eNew\n        unless (\u2190 isDefEq expectedType eNewType) do throwMismatch\n        return eNew -- approach 3 worked\n    catch _ =>\n      /-\n        If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`.\n        Otherwise, we just try `tryCoe?`.\n      -/\n      match (\u2190 isMonad? m) with\n      | none   => tryPureCoeAndSimple\n      | some _ => tryCoeSimple\n  else\n    tryCoeSimple\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.\n  If they are not, then try coercions.\n\n  Argument `f?` is used only for generating error messages. -/\ndef ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)\n    (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  match expectedType? with\n  | none              => pure e\n  | some expectedType =>\n    if (\u2190 isDefEq eType expectedType) then\n      pure e\n    else\n      tryLiftAndCoe errorMsgHeader? expectedType eType e f?\n\n/--\n  If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.\n  If they are not, then try coercions. -/\ndef ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=\n  match expectedType? with\n  | none => pure e\n  | _    => do\n    let eType \u2190 inferType e\n    ensureHasTypeAux expectedType? eType e none errorMsgHeader?\n\nprivate def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do\n  let expectedType \u2190 match expectedType? with\n    | none              => mkFreshTypeMVar\n    | some expectedType => pure expectedType\n  mkSyntheticSorry expectedType\n\nprivate def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do\n  let syntheticSorry \u2190 mkSyntheticSorryFor expectedType?\n  logException ex\n  pure syntheticSorry\n\n/-- If `mayPostpone == true`, throw `Expection.postpone`. -/\ndef tryPostpone : TermElabM Unit := do\n  if (\u2190 read).mayPostpone then\n    throwPostpone\n\n/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/\ndef tryPostponeIfMVar (e : Expr) : TermElabM Unit := do\n  if e.getAppFn.isMVar then\n    let e \u2190 instantiateMVars e\n    if e.getAppFn.isMVar then\n      tryPostpone\n\ndef tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=\n  match e? with\n  | some e => tryPostponeIfMVar e\n  | none   => tryPostpone\n\ndef tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do\n  tryPostponeIfNoneOrMVar expectedType?\n  let some expectedType \u2190 pure expectedType? |\n    throwError \"{msg}, expected type must be known\"\n  let expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasExprMVar then\n    tryPostpone\n    throwError \"{msg}, expected type contains metavariables{indentExpr expectedType}\"\n  pure expectedType\n\nprivate def saveContext : TermElabM SavedContext :=\n  return {\n    macroStack := (\u2190 read).macroStack\n    declName?  := (\u2190 read).declName?\n    options    := (\u2190 getOptions)\n    openDecls  := (\u2190 getOpenDecls)\n    errToSorry := (\u2190 read).errToSorry\n  }\n\ndef withSavedContext (savedCtx : SavedContext) (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|\n    withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls })\n      x\n\nprivate def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do\n  trace[Elab.postpone] \"{stx} : {expectedType?}\"\n  let mvar \u2190 mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque\n  let ctx \u2190 read\n  registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (\u2190 saveContext))\n  pure mvar\n\n/-\n  Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or\n  an error is found. -/\nprivate def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)\n    : List TermElab \u2192 TermElabM Expr\n  | []                => do throwError \"unexpected syntax{indentD stx}\"\n  | (elabFn::elabFns) => do\n    try\n      elabFn stx expectedType?\n    catch ex => match ex with\n      | Exception.error ref msg =>\n        if (\u2190 read).errToSorry then\n          exceptionToSorry ex expectedType?\n        else\n          throw ex\n      | Exception.internal id _ =>\n        if (\u2190 read).errToSorry && id == abortTermExceptionId then\n          exceptionToSorry ex expectedType?\n        else if id == unsupportedSyntaxExceptionId then\n          s.restore\n          elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n        else if catchExPostpone && id == postponeExceptionId then\n          /- If `elab` threw `Exception.postpone`, we reset any state modifications.\n             For example, we want to make sure pending synthetic metavariables created by `elab` before\n             it threw `Exception.postpone` are discarded.\n             Note that we are also discarding the messages created by `elab`.\n\n             For example, consider the expression.\n             `((f.x a1).x a2).x a3`\n             Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.\n             Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`\n             because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and\n            finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would\n            keep \"dead\" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is\n            wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch\n            and new metavariables are created for the nested functions. -/\n            s.restore\n            postponeElabTerm stx expectedType?\n          else\n            throw ex\n\nprivate def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do\n  let s \u2190 saveState\n  let table := termElabAttribute.ext.getState (\u2190 getEnv) |>.table\n  let k := stx.getKind\n  match table.find? k with\n  | some elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns\n  | none         => throwError \"elaboration function for '{k}' has not been implemented{indentD stx}\"\n\ninstance : MonadMacroAdapter TermElabM where\n  getCurrMacroScope := getCurrMacroScope\n  getNextMacroScope := return (\u2190 getThe Core.State).nextMacroScope\n  setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }\n\nprivate def isExplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(@$f) => true\n  | _      => false\n\nprivate def isExplicitApp (stx : Syntax) : Bool :=\n  stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]\n\n/--\n  Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.\n  Example: `fun {\u03b1} (a : \u03b1) => a` -/\nprivate def isLambdaWithImplicit (stx : Syntax) : Bool :=\n  match stx with\n  | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder\n  | _                         => false\n\nprivate partial def dropTermParens : Syntax \u2192 Syntax := fun stx =>\n  match stx with\n  | `(($stx)) => dropTermParens stx\n  | _         => stx\n\nprivate def isHole (stx : Syntax) : Bool :=\n  match stx with\n  | `(_)          => true\n  | `(? _)        => true\n  | `(? $x:ident) => true\n  | _             => false\n\nprivate def isTacticBlock (stx : Syntax) : Bool :=\n  match stx with\n  | `(by $x:tacticSeq) => true\n  | _ => false\n\nprivate def isNoImplicitLambda (stx : Syntax) : Bool :=\n  match stx with\n  | `(noImplicitLambda% $x:term) => true\n  | _ => false\n\nprivate def isTypeAscription (stx : Syntax) : Bool :=\n  match stx with\n  | `(($e : $type)) => true\n  | _               => false\n\ndef mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=\n  mkAnnotation `noImplicitLambda type\n\ndef hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=\n  annotation? `noImplicitLambda type |>.isSome\n\n/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/\ndef blockImplicitLambda (stx : Syntax) : Bool :=\n  let stx := dropTermParens stx\n  -- TODO: make it extensible\n  isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||\n  isNoImplicitLambda stx || isTypeAscription stx\n\n/--\n  Return normalized expected type if it is of the form `{a : \u03b1} \u2192 \u03b2` or `[a : \u03b1] \u2192 \u03b2` and\n  `blockImplicitLambda stx` is not true, else return `none`. -/\nprivate def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=\n  if blockImplicitLambda stx then\n    pure none\n  else match expectedType? with\n    | some expectedType => do\n      if hasNoImplicitLambdaAnnotation expectedType then\n        pure none\n      else\n        let expectedType \u2190 whnfForall expectedType\n        match expectedType with\n        | Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType\n        | _                    => pure none\n    | _         => pure none\n\nprivate def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do\n  match ex with\n  | Exception.error ref msg =>\n    if impFVars.isEmpty then\n      return Exception.error ref msg\n    else\n      let mut msg := m!\"{msg}\\nthe following variables have been introduced by the implicit lamda feature\"\n      for impFVar in impFVars do\n        let auxMsg := m!\"{impFVar} : {\u2190 inferType impFVar}\"\n        let auxMsg \u2190 addMessageContext auxMsg\n        msg := m!\"{msg}{indentD auxMsg}\"\n      msg := m!\"{msg}\\nyou can disable implict lambdas using `@` or writing a lambda expression with `\\{}` or `[]` binder annotations.\"\n      return Exception.error ref msg\n  | _ => return ex\n\nprivate def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do\n  let body \u2190 elabUsingElabFns stx expectedType catchExPostpone\n  try\n    let body \u2190 ensureHasType expectedType body\n    let r \u2190 mkLambdaFVars impFVars body\n    trace[Elab.implicitForall] r\n    pure r\n  catch ex =>\n    throw (\u2190 decorateErrorMessageWithLambdaImplicitVars ex impFVars)\n\nprivate partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=\n  loop type #[]\nwhere\n  loop\n    | type@(Expr.forallE n d b c), fvars =>\n      if c.binderInfo.isExplicit then\n        elabImplicitLambdaAux stx catchExPostpone type fvars\n      else withFreshMacroScope do\n        let n \u2190 MonadQuotation.addMacroScope n\n        withLocalDecl n c.binderInfo d fun fvar => do\n          let type \u2190 whnfForall (b.instantiate1 fvar)\n          loop type (fvars.push fvar)\n    | type, fvars =>\n      elabImplicitLambdaAux stx catchExPostpone type fvars\n\n/- Main loop for `elabTerm` -/\nprivate partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax \u2192 TermElabM Expr\n  | Syntax.missing => mkSyntheticSorryFor expectedType?\n  | stx => withFreshMacroScope <| withIncRecDepth do\n    trace[Elab.step] \"expected type: {expectedType?}, term\\n{stx}\"\n    checkMaxHeartbeats \"elaborator\"\n    withNestedTraces do\n    let env \u2190 getEnv\n    let stxNew? \u2190 catchInternalId unsupportedSyntaxExceptionId\n      (do let newStx \u2190 adaptMacro (getMacros env) stx; pure (some newStx))\n      (fun _ => pure none)\n    match stxNew? with\n    | some stxNew => withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew\n    | _ =>\n      let implicit? \u2190 if implicitLambda && (\u2190 read).implicitLambda then useImplicitLambda? stx expectedType? else pure none\n      match implicit? with\n      | some expectedType => elabImplicitLambda stx catchExPostpone expectedType\n      | none              => elabUsingElabFns stx expectedType? catchExPostpone\n\ndef addTermInfo (stx : Syntax) (e : Expr) : TermElabM Unit := do\n  if (\u2190 getInfoState).enabled then\n    pushInfoLeaf <| Info.ofTermInfo { lctx := (\u2190 getLCtx), expr := e, stx := stx }\n\ndef getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=\n  return (\u2190 get).syntheticMVars.find? fun d => d.mvarId == mvarId\n\ndef mkTermInfo (stx : Syntax) (e : Expr) : TermElabM (Sum Info MVarId) := do\n  let isHole? : TermElabM (Option MVarId) := do\n    match e with\n    | Expr.mvar mvarId _ =>\n      match (\u2190 getSyntheticMVarDecl? mvarId) with\n      | some { kind := SyntheticMVarKind.tactic .., .. }    => return mvarId\n      | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId\n      | _                                                   => return none\n    | _ => pure none\n  match (\u2190 isHole?) with\n  | none        => return Sum.inl <| Info.ofTermInfo { lctx := (\u2190 getLCtx), expr := e, stx := stx }\n  | some mvarId => return Sum.inr mvarId\n\n/-- Store in the `InfoTree` that `e` is a \"dot\"-completion target. -/\ndef addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do\n  addCompletionInfo <| CompletionInfo.dot { expr := e, stx := stx, lctx := (\u2190 getLCtx) } (field? := field?) (expectedType? := expectedType?)\n\n/--\n  Main function for elaborating terms.\n  It extracts the elaboration methods from the environment using the node kind.\n  Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.\n  It creates a fresh macro scope for executing the elaboration method.\n  All unlogged trace messages produced by the elaboration method are logged using\n  the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,\n  the error is logged and a synthetic sorry expression is returned.\n  If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,\n  a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,\n  and returned.\n  The option `catchExPostpone == false` is used to implement `resumeElabTerm`\n  to prevent the creation of another synthetic metavariable when resuming the elaboration.\n\n  If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.\n  We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.\n  -/\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=\n  withInfoContext' (withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx) (mkTermInfo stx)\n\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do\n  let e \u2190 elabTerm stx expectedType? catchExPostpone implicitLambda\n  withRef stx <| ensureHasType expectedType? e errorMsgHeader?\n\n/-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/\ndef commitIfNoErrors? (x : TermElabM \u03b1) : TermElabM (Option \u03b1) := do\n  let saved \u2190 saveState\n  modify fun s => { s with messages := {} }\n  try\n    let a \u2190 x\n    if (\u2190 get).messages.hasErrors then\n      restoreState saved\n      return none\n    else\n      modify fun s => { s with messages := saved.elab.messages ++ s.messages }\n      return a\n  catch _ =>\n    restoreState saved\n    return none\n\n/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/\ndef adaptExpander (exp : Syntax \u2192 TermElabM Syntax) : TermElab := fun stx expectedType? => do\n  let stx' \u2190 exp stx\n  withMacroExpansion stx stx' $ elabTerm stx' expectedType?\n\ndef mkInstMVar (type : Expr) : TermElabM Expr := do\n  let mvar \u2190 mkFreshExprMVar type MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  unless (\u2190 synthesizeInstMVarCore mvarId) do\n    registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass\n  pure mvar\n\n/-\n  Relevant definitions:\n  ```\n  class CoeSort (\u03b1 : Sort u) (\u03b2 : outParam (Sort v))\n  abbrev coeSort {\u03b1 : Sort u} {\u03b2 : Sort v} (a : \u03b1) [CoeSort \u03b1 \u03b2] : \u03b2\n  ```\n  -/\nprivate def tryCoeSort (\u03b1 : Expr) (a : Expr) : TermElabM Expr := do\n  let \u03b2 \u2190 mkFreshTypeMVar\n  let u \u2190 getLevel \u03b1\n  let v \u2190 getLevel \u03b2\n  let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[\u03b1, \u03b2]\n  let mvar \u2190 mkFreshExprMVar coeSortInstType MetavarKind.synthetic\n  let mvarId := mvar.mvarId!\n  try\n    withoutMacroStackAtErr do\n      if (\u2190 synthesizeCoeInstMVarCore mvarId) then\n        expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[\u03b1, \u03b2, a, mvar]\n      else\n        throwError \"type expected\"\n  catch\n    | Exception.error _ msg => throwError \"type expected\\n{msg}\"\n    | _                     => throwError \"type expected\"\n\n/--\n  Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`\n  or is unifiable with `Expr.sort`, or can be coerced into one. -/\ndef ensureType (e : Expr) : TermElabM Expr := do\n  if (\u2190 isType e) then\n    pure e\n  else\n    let eType \u2190 inferType e\n    let u \u2190 mkFreshLevelMVar\n    if (\u2190 isDefEq eType (mkSort u)) then\n      pure e\n    else\n      tryCoeSort eType e\n\n/-- Elaborate `stx` and ensure result is a type. -/\ndef elabType (stx : Syntax) : TermElabM Expr := do\n  let u \u2190 mkFreshLevelMVar\n  let type \u2190 elabTerm stx (mkSort u)\n  withRef stx $ ensureType type\n\n/--\n  Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,\n  a new local declaration is created, registered, and `k` is tried to be executed again. -/\npartial def withAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let flag := autoBoundImplicitLocal.get (\u2190 getOptions)\n  if flag then\n    withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do\n      let rec loop (s : SavedState) : TermElabM \u03b1 := do\n        try\n          k\n        catch\n          | ex => match isAutoBoundImplicitLocalException? ex with\n            | some n =>\n              -- Restore state, declare `n`, and try again\n              s.restore\n              withLocalDecl n BinderInfo.implicit (\u2190 mkFreshTypeMVar) fun x =>\n                withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do\n                  loop (\u2190 saveState)\n            | none   => throw ex\n      loop (\u2190 saveState)\n  else\n    k\n\ndef withoutAutoBoundImplicit (k : TermElabM \u03b1) : TermElabM \u03b1 := do\n  withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k\n\n/--\n  Return `autoBoundImplicits ++ xs.\n  This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/\ndef addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do\n  let autoBoundImplicits := (\u2190 read).autoBoundImplicits\n  for auto in autoBoundImplicits do\n    let localDecl \u2190 getLocalDecl auto.fvarId!\n    for x in xs do\n      if (\u2190 getMCtx).localDeclDependsOn localDecl x.fvarId! then\n        throwError \"invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'\"\n  return autoBoundImplicits.toArray ++ xs\n\ndef mkAuxName (suffix : Name) : TermElabM Name := do\n  match (\u2190 read).declName? with\n  | none          => throwError \"auxiliary declaration cannot be created when declaration name is not available\"\n  | some declName => Lean.mkAuxName (declName ++ suffix) 1\n\nbuiltin_initialize registerTraceClass `Elab.letrec\n\n/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it\n   is delayed assigned to one. -/\ndef isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do\n  trace[Elab.letrec] \"mvarId: {mkMVar mvarId} letrecMVars: {(\u2190 get).letRecsToLift.map (mkMVar $ \u00b7.mvarId)}\"\n  let mvarId := (\u2190 getMCtx).getDelayedRoot mvarId\n  trace[Elab.letrec] \"mvarId root: {mkMVar mvarId}\"\n  return (\u2190 get).letRecsToLift.any (\u00b7.mvarId == mvarId)\n\n/- =======================================\n       Builtin elaboration functions\n   ======================================= -/\n\n@[builtinTermElab \u00abprop\u00bb] def elabProp : TermElab := fun _ _ =>\n  return mkSort levelZero\n\nprivate def elabOptLevel (stx : Syntax) : TermElabM Level :=\n  if stx.isNone then\n    pure levelZero\n  else\n    elabLevel stx[0]\n\n@[builtinTermElab \u00absort\u00bb] def elabSort : TermElab := fun stx _ =>\n  return mkSort (\u2190 elabOptLevel stx[1])\n\n@[builtinTermElab \u00abtype\u00bb] def elabTypeStx : TermElab := fun stx _ =>\n  return mkSort (mkLevelSucc (\u2190 elabOptLevel stx[1]))\n\n/-\n the method `resolveName` adds a completion point for it using the given\n    expected type. Thus, we propagate the expected type if `stx[0]` is an identifier.\n    It doesn't \"hurt\" if the identifier can be resolved because the expected type is not used in this case.\n    Recall that if the name resolution fails a synthetic sorry is returned.-/\n\n@[builtinTermElab \u00abpipeCompletion\u00bb] def elabPipeCompletion : TermElab := fun stx expectedType? => do\n  let e \u2190 elabTerm stx[0] none\n  unless e.isSorry do\n    addDotCompletionInfo stx e expectedType?\n  throwErrorAt stx[1] \"invalid field notation, identifier or numeral expected\"\n\n@[builtinTermElab \u00abcompletion\u00bb] def elabCompletion : TermElab := fun stx expectedType? => do\n  /- `ident.` is ambiguous in Lean, we may try to be completing a declaration name or access a \"field\". -/\n  if stx[0].isIdent then\n    /- If we can elaborate the identifier successfully, we assume it a dot-completion. Otherwise, we treat it as\n       identifier completion with a dangling `.`.\n       Recall that the server falls back to identifier completion when dot-completion fails. -/\n    let s \u2190 saveState\n    try\n      let e \u2190 elabTerm stx[0] none\n      addDotCompletionInfo stx e expectedType?\n    catch _ =>\n      s.restore\n      addCompletionInfo <| CompletionInfo.id stx stx[0].getId (danglingDot := true) (\u2190 getLCtx) expectedType?\n    throwErrorAt stx[1] \"invalid field notation, identifier or numeral expected\"\n  else\n    elabPipeCompletion stx expectedType?\n\n@[builtinTermElab \u00abhole\u00bb] def elabHole : TermElab := fun stx expectedType? => do\n  let mvar \u2190 mkFreshExprMVar expectedType?\n  registerMVarErrorHoleInfo mvar.mvarId! stx\n  pure mvar\n\n@[builtinTermElab \u00absyntheticHole\u00bb] def elabSyntheticHole : TermElab := fun stx expectedType? => do\n  let arg  := stx[1]\n  let userName := if arg.isIdent then arg.getId else Name.anonymous\n  let mkNewHole : Unit \u2192 TermElabM Expr := fun _ => do\n    let mvar \u2190 mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque userName\n    registerMVarErrorHoleInfo mvar.mvarId! stx\n    pure mvar\n  if userName.isAnonymous then\n    mkNewHole ()\n  else\n    let mctx \u2190 getMCtx\n    match mctx.findUserName? userName with\n    | none => mkNewHole ()\n    | some mvarId =>\n      let mvar := mkMVar mvarId\n      let mvarDecl \u2190 getMVarDecl mvarId\n      let lctx \u2190 getLCtx\n      if mvarDecl.lctx.isSubPrefixOf lctx then\n        pure mvar\n      else match mctx.getExprAssignment? mvarId with\n      | some val =>\n        let val \u2190 instantiateMVars val\n        if mctx.isWellFormed lctx val then\n          pure val\n        else\n          withLCtx mvarDecl.lctx mvarDecl.localInstances do\n            throwError \"synthetic hole has already been defined and assigned to value incompatible with the current context{indentExpr val}\"\n      | none =>\n        if mctx.isDelayedAssigned mvarId then\n          -- We can try to improve this case if needed.\n          throwError \"synthetic hole has already beend defined and delayed assigned with an incompatible local context\"\n        else if lctx.isSubPrefixOf mvarDecl.lctx then\n          let mvarNew \u2190 mkNewHole ()\n          modifyMCtx fun mctx => mctx.assignExpr mvarId mvarNew\n          pure mvarNew\n        else\n          throwError \"synthetic hole has already been defined with an incompatible local context\"\n\nprivate def mkTacticMVar (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do\n  let mvar \u2190 mkFreshExprMVar type MetavarKind.syntheticOpaque\n  let mvarId := mvar.mvarId!\n  let ref \u2190 getRef\n  let declName? \u2190 getDeclName?\n  registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic tacticCode (\u2190 saveContext)\n  return mvar\n\n@[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? =>\n  match expectedType? with\n  | some expectedType => mkTacticMVar expectedType stx\n  | none => throwError (\"invalid 'by' tactic, expected type has not been provided\")\n\n@[builtinTermElab noImplicitLambda] def elabNoImplicitLambda : TermElab := fun stx expectedType? =>\n  elabTerm stx[1] (mkNoImplicitLambdaAnnotation <$> expectedType?)\n\ndef resolveLocalName (n : Name) : TermElabM (Option (Expr \u00d7 List String)) := do\n  let lctx \u2190 getLCtx\n  let view := extractMacroScopes n\n  let rec loop (n : Name) (projs : List String) :=\n    match lctx.findFromUserName? { view with name := n }.review with\n    | some decl => some (decl.toExpr, projs)\n    | none      => match n with\n      | Name.str pre s _ => loop pre (s::projs)\n      | _                => none\n  return loop view.name []\n\n/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/\ndef isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val _ => do\n    let r? \u2190 resolveLocalName val\n    match r? with\n    | some (fvar, []) => pure (some fvar)\n    | _               => pure none\n  | _ => pure none\n\n/--\n  Create an `Expr.const` using the given name and explicit levels.\n  Remark: fresh universe metavariables are created if the constant has more universe\n  parameters than `explicitLevels`. -/\ndef mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do\n  let cinfo \u2190 getConstInfo constName\n  if explicitLevels.length > cinfo.levelParams.length then\n    throwError \"too many explicit universe levels\"\n  else\n    let numMissingLevels := cinfo.levelParams.length - explicitLevels.length\n    let us \u2190 mkFreshLevelMVars numMissingLevels\n    pure $ Lean.mkConst constName (explicitLevels ++ us)\n\nprivate def mkConsts (candidates : List (Name \u00d7 List String)) (explicitLevels : List Level) : TermElabM (List (Expr \u00d7 List String)) := do\n  candidates.foldlM (init := []) fun result (constName, projs) => do\n    -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.\n   let const \u2190 mkConst constName explicitLevels\n   return (const, projs) :: result\n\ndef resolveName (stx : Syntax) (n : Name) (preresolved : List (Name \u00d7 List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 List String)) := do\n  try\n    if let some (e, projs) \u2190 resolveLocalName n then\n      unless explicitLevels.isEmpty do\n        throwError \"invalid use of explicit universe parameters, '{e}' is a local\"\n      return [(e, projs)]\n    -- check for section variable capture by a quotation\n    let ctx \u2190 read\n    if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (\u00b7, projs) then\n      return [(e, projs)]  -- section variables should shadow global decls\n    if preresolved.isEmpty then\n      process (\u2190 resolveGlobalName n)\n    else\n      process preresolved\n  catch ex =>\n    if preresolved.isEmpty && explicitLevels.isEmpty then\n      addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n    throw ex\nwhere process (candidates : List (Name \u00d7 List String)) : TermElabM (List (Expr \u00d7 List String)) := do\n  if candidates.isEmpty then\n    if (\u2190 read).autoBoundImplicit && isValidAutoBoundImplicitName n then\n      throwAutoBoundImplicitLocal n\n    else\n      throwError \"unknown identifier '{Lean.mkConst n}'\"\n  if preresolved.isEmpty && explicitLevels.isEmpty then\n    addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (\u2190 getLCtx) expectedType?\n  mkConsts candidates explicitLevels\n\n/--\n  Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.\n  Example: Assume resolveName `v.head.bla.boo` produces `(v.head, [\"bla\", \"boo\"])`, then this method produces\n  `(v.head, id, [f\u2081, f\u2082])` where `id` is an identifier for `v.head`, and `f\u2081` and `f\u2082` are identifiers for fields `\"bla\"` and `\"boo\"`. -/\ndef resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr \u00d7 Syntax \u00d7 List Syntax)) := do\n  match ident with\n  | Syntax.ident info rawStr n preresolved =>\n    let r \u2190 resolveName ident n preresolved explicitLevels expectedType?\n    r.mapM fun (c, fields) => do\n      let (cSstr, fields) := fields.foldr (init := (rawStr, [])) fun field (restSstr, fs) =>\n        let fieldSstr := restSstr.takeRightWhile (\u00b7 \u2260 '.')\n        ({ restSstr with stopPos := restSstr.stopPos - (fieldSstr.bsize + 1) }, (field, fieldSstr) :: fs)\n      let mkIdentFromPos pos rawVal val :=\n        let info := match info with\n        | SourceInfo.original .. => SourceInfo.original \"\".toSubstring pos \"\".toSubstring (pos + rawVal.bsize)\n        | _                      => SourceInfo.synthetic pos (pos + rawVal.bsize)\n        Syntax.ident info rawVal val []\n      let id := match c with\n        | Expr.const id _ _ => id\n        | Expr.fvar id _    => id\n        | _                 => unreachable!\n      let id := mkIdentFromPos (ident.getPos?.getD 0) cSstr id\n      match info.getPos? with\n      | none =>\n        return (c, id, fields.map fun (field, _) => mkIdentFrom ident (Name.mkSimple field))\n      | some pos =>\n        let mut pos := pos + cSstr.bsize + 1\n        let mut newFields := #[]\n        for (field, fieldSstr) in fields do\n          newFields := newFields.push <| mkIdentFromPos pos fieldSstr (Name.mkSimple field)\n          pos := pos + fieldSstr.bsize + 1\n        return (c, id, newFields.toList)\n  | _ => throwError \"identifier expected\"\n\ndef resolveId? (stx : Syntax) (kind := \"term\") (withInfo := false) : TermElabM (Option Expr) :=\n  match stx with\n  | Syntax.ident _ _ val preresolved => do\n    let rs \u2190 try resolveName stx val preresolved [] catch _ => pure []\n    let rs := rs.filter fun \u27e8f, projs\u27e9 => projs.isEmpty\n    let fs := rs.map fun (f, _) => f\n    match fs with\n    | []  => pure none\n    | [f] =>\n      if withInfo then\n        addTermInfo stx f\n      pure (some f)\n    | _   => throwError \"ambiguous {kind}, use fully qualified name, possible interpretations {fs}\"\n  | _ => throwError \"identifier expected\"\n\n@[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ =>\n  throwError \"invalid occurrence of `\u00b7` notation, it must be surrounded by parentheses (e.g. `(\u00b7 + 1)`)\"\n\n@[builtinTermElab strLit] def elabStrLit : TermElab := fun stx _ => do\n  match stx.isStrLit? with\n  | some val => pure $ mkStrLit val\n  | none     => throwIllFormedSyntax\n\nprivate def mkFreshTypeMVarFor (expectedType? : Option Expr) : TermElabM Expr := do\n  let typeMVar \u2190 mkFreshTypeMVar MetavarKind.synthetic\n  match expectedType? with\n  | some expectedType => discard <| isDefEq expectedType typeMVar\n  | _                 => pure ()\n  return typeMVar\n\n@[builtinTermElab numLit] def elabNumLit : TermElab := fun stx expectedType? => do\n  let val \u2190 match stx.isNatLit? with\n    | some val => pure val\n    | none     => throwIllFormedSyntax\n  let typeMVar \u2190 mkFreshTypeMVarFor expectedType?\n  let u \u2190 getDecLevel typeMVar\n  let mvar \u2190 mkInstMVar (mkApp2 (Lean.mkConst ``OfNat [u]) typeMVar (mkNatLit val))\n  let r := mkApp3 (Lean.mkConst ``OfNat.ofNat [u]) typeMVar (mkNatLit val) mvar\n  registerMVarErrorImplicitArgInfo mvar.mvarId! stx r\n  return r\n\n@[builtinTermElab rawNatLit] def elabRawNatLit : TermElab :=  fun stx expectedType? => do\n  match stx[1].isNatLit? with\n  | some val => return mkNatLit val\n  | none     => throwIllFormedSyntax\n\n@[builtinTermElab scientificLit]\ndef elabScientificLit : TermElab := fun stx expectedType? => do\n  match stx.isScientificLit? with\n  | none        => throwIllFormedSyntax\n  | some (m, sign, e) =>\n    let typeMVar \u2190 mkFreshTypeMVarFor expectedType?\n    let u \u2190 getDecLevel typeMVar\n    let mvar \u2190 mkInstMVar (mkApp (Lean.mkConst ``OfScientific [u]) typeMVar)\n    return mkApp5 (Lean.mkConst ``OfScientific.ofScientific [u]) typeMVar mvar (mkNatLit m) (toExpr sign) (mkNatLit e)\n\n@[builtinTermElab charLit] def elabCharLit : TermElab := fun stx _ => do\n  match stx.isCharLit? with\n  | some val => return mkApp (Lean.mkConst ``Char.ofNat) (mkNatLit val.toNat)\n  | none     => throwIllFormedSyntax\n\n@[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ =>\n  match stx[0].isNameLit? with\n  | some val => pure $ toExpr val\n  | none     => throwIllFormedSyntax\n\n@[builtinTermElab doubleQuotedName] def elabDoubleQuotedName : TermElab := fun stx _ => do\n  match stx[1].isNameLit? with\n  | some val => toExpr (\u2190 resolveGlobalConstNoOverloadWithInfo stx[1] val)\n  | none     => throwIllFormedSyntax\n\n@[builtinTermElab typeOf] def elabTypeOf : TermElab := fun stx _ => do\n  inferType (\u2190 elabTerm stx[1] none)\n\n@[builtinTermElab ensureTypeOf] def elabEnsureTypeOf : TermElab := fun stx expectedType? =>\n  match stx[2].isStrLit? with\n  | none     => throwIllFormedSyntax\n  | some msg => do\n    let refTerm \u2190 elabTerm stx[1] none\n    let refTermType \u2190 inferType refTerm\n    elabTermEnsuringType stx[3] refTermType (errorMsgHeader? := msg)\n\n@[builtinTermElab ensureExpectedType] def elabEnsureExpectedType : TermElab := fun stx expectedType? =>\n  match stx[1].isStrLit? with\n  | none     => throwIllFormedSyntax\n  | some msg => elabTermEnsuringType stx[2] expectedType? (errorMsgHeader? := msg)\n\n@[builtinTermElab \u00abopen\u00bb] def elabOpen : TermElab := fun stx expectedType? => do\n  try\n    pushScope\n    let openDecls \u2190 elabOpenDecl stx[1]\n    withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do\n      elabTerm stx[3] expectedType?\n  finally\n    popScope\n\n@[builtinTermElab \u00abset_option\u00bb] def elabSetOption : TermElab := fun stx expectedType? => do\n  let options \u2190 Elab.elabSetOption stx[1] stx[2]\n  withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do\n    elabTerm stx[4] expectedType?\n\nprivate def mkSomeContext : Context := {\n  fileName      := \"<TermElabM>\"\n  fileMap       := arbitrary\n}\n\n@[inline] def TermElabM.run (x : TermElabM \u03b1) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (\u03b1 \u00d7 State) :=\n  withConfig setElabConfig (x ctx |>.run s)\n\n@[inline] def TermElabM.run' (x : TermElabM \u03b1) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM \u03b1 :=\n  (\u00b7.1) <$> x.run ctx s\n\n@[inline] def TermElabM.toIO (x : TermElabM \u03b1)\n    (ctxCore : Core.Context) (sCore : Core.State)\n    (ctxMeta : Meta.Context) (sMeta : Meta.State)\n    (ctx : Context) (s : State) : IO (\u03b1 \u00d7 Core.State \u00d7 Meta.State \u00d7 State) := do\n  let ((a, s), sCore, sMeta) \u2190 (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta\n  pure (a, sCore, sMeta, s)\n\ninstance [MetaEval \u03b1] : MetaEval (TermElabM \u03b1) where\n  eval env opts x _ :=\n    let x : TermElabM \u03b1 := do\n      try x finally\n        let s \u2190 get\n        s.messages.forM fun msg => do IO.println (\u2190 msg.toString)\n    MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext\n\nunsafe def evalExpr (\u03b1) (typeName : Name) (value : Expr) : TermElabM \u03b1 :=\n  withoutModifyingEnv do\n    let name \u2190 mkFreshUserName `_tmp\n    let type \u2190 inferType value\n    let type \u2190 whnfD type\n    unless type.isConstOf typeName do\n      throwError \"unexpected type at evalExpr{indentExpr type}\"\n    let decl := Declaration.defnDecl {\n       name := name, levelParams := [], type := type,\n       value := value, hints := ReducibilityHints.opaque,\n       safety := DefinitionSafety.unsafe\n    }\n    ensureNoUnassignedMVars decl\n    addAndCompile decl\n    evalConst \u03b1 name\n\nprivate def throwStuckAtUniverseCnstr : TermElabM Unit := do\n  -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property\n  let entries \u2190 getPostponed\n  let mut found : Std.HashSet (Level \u00d7 Level) := {}\n  let mut uniqueEntries := #[]\n  for entry in entries do\n    let mut lhs := entry.lhs\n    let mut rhs := entry.rhs\n    if Level.normLt rhs lhs then\n      (lhs, rhs) := (rhs, lhs)\n    unless found.contains (lhs, rhs) do\n      found := found.insert (lhs, rhs)\n      uniqueEntries := uniqueEntries.push entry\n  for i in [1:uniqueEntries.size] do\n    logErrorAt uniqueEntries[i].ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[i])\n  throwErrorAt uniqueEntries[0].ref (\u2190 mkLevelStuckErrorMessage uniqueEntries[0])\n\n@[specialize] def withoutPostponingUniverseConstraints (x : TermElabM \u03b1) : TermElabM \u03b1 := do\n  let postponed \u2190 getResetPostponed\n  try\n    let a \u2190 x\n    unless (\u2190 processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do\n      throwStuckAtUniverseCnstr\n    setPostponed postponed\n    return a\n  catch ex =>\n    setPostponed postponed\n    throw ex\n\nend Term\n\nbuiltin_initialize\n  registerTraceClass `Elab.postpone\n  registerTraceClass `Elab.coe\n  registerTraceClass `Elab.debug\n\nexport Term (TermElabM)\n\nend Lean.Elab\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/Elab/Term.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682620364309847, "lm_q2_score": 0.024798160961346273, "lm_q1q2_score": 0.004880927879352276}}
{"text": "/-\nCopyright (c) 2018 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Sebastian Ullrich\n\nParser for the Lean language\n-/\nprelude\nimport init.lean.parser.parsec init.lean.parser.syntax init.lean.parser.rec\nimport init.lean.parser.trie\nimport init.lean.parser.identifier init.data.rbmap init.lean.message\n\nnamespace Lean\nnamespace Parser\n\n/- Maximum standard precedence. This is the precedence of Function application.\n   In the standard Lean language, only the token `.` has a left-binding power greater\n   than `maxPrec` (so that field accesses like `g (h x).f` are parsed as `g ((h x).f)`,\n   not `(g (h x)).f`). -/\ndef maxPrec : Nat := 1024\n\nstructure TokenConfig :=\n(\u00abprefix\u00bb : String)\n/- Left-binding power used by the Term Parser. The Term Parser operates in the context\n   of a right-binding power between 0 (used by parentheses and on the top-Level) and\n   (usually) `maxPrec` (used by Function application). After parsing an initial Term,\n   it continues parsing and expanding that Term only when the left-binding power of\n   the next token is greater than the current right-binding power. For example, it\n   never continues parsing an argument after the initial parse, unless a token with\n   lbp > maxPrec is encountered. Conversely, the Term Parser will always continue\n   parsing inside parentheses until it finds a token with lbp 0 (such as `)`). -/\n(lbp : Nat := 0)\n-- reading a token should not need any State\n/- An optional Parser that is activated after matching `prefix`.\n   It should return a Syntax tree with a \"hole\" for the\n   `SourceInfo` surrounding the token, which will be supplied\n   by the `token` Parser.\n\n   Remark: `suffixParser` has many applications for example for parsing\n   hexdecimal numbers, `prefix` is `0x` and `suffixParser` is the Parser `digit*`.\n   We also use it to parse String literals: here `prefix` is just `\"`.\n-/\n(suffixParser : Option (Parsec' (SourceInfo \u2192 Syntax)) := none)\n\n-- Backtrackable State\nstructure ParserState :=\n(messages : MessageLog)\n\nstructure TokenCacheEntry :=\n(startIt stopIt : String.OldIterator)\n(tk : Syntax)\n\n-- Non-backtrackable State\nstructure ParserCache :=\n(tokenCache : Option TokenCacheEntry := none)\n-- for profiling\n(hit miss : Nat := 0)\n\nstructure FrontendConfig :=\n(filename : String)\n(input    : String)\n(fileMap  : FileMap)\n\n/- Remark: if we have a Node in the Trie with `some TokenConfig`, the String induced by the path is equal to the `TokenConfig.prefix`. -/\nstructure ParserConfig extends FrontendConfig :=\n(tokens : Trie TokenConfig)\n\ninstance parserConfigCoe : HasCoe ParserConfig FrontendConfig :=\n\u27e8ParserConfig.toFrontendConfig\u27e9\n\n@[derive Monad Alternative MonadParsec MonadExcept]\ndef parserCoreT (m : Type \u2192 Type) [Monad m] :=\nParsecT Syntax $ StateT ParserCache $ m\n\n@[derive Monad Alternative MonadReader MonadParsec MonadExcept]\ndef ParserT (\u03c1 : Type) (m : Type \u2192 Type) [Monad m] := ReaderT \u03c1 $ parserCoreT m\n@[derive Monad Alternative MonadReader MonadParsec MonadExcept]\ndef BasicParserM := ParserT ParserConfig Id\nabbrev basicParser := BasicParserM Syntax\nabbrev monadBasicParser := HasMonadLiftT BasicParserM\n\nsection\nlocal attribute [reducible] BasicParserM ParserT parserCoreT\n@[inline] def getCache : BasicParserM ParserCache :=\nmonadLift (get : StateT ParserCache Id _)\n\n@[inline] def putCache : ParserCache \u2192 BasicParserM PUnit :=\n\u03bb c, monadLift (set c : StateT ParserCache Id _)\nend\n\n -- an arbitrary `Parser` Type; parsers are usually some Monad stack based on `BasicParserM` returning `Syntax`\nvariable {\u03c1 : Type}\n\nclass HasTokens (r : \u03c1) := mk {} ::\n(tokens : List TokenConfig)\n\n@[noinline, nospecialize] def tokens (r : \u03c1) [HasTokens r] :=\nHasTokens.tokens r\n\ninstance HasTokens.Inhabited (r : \u03c1) : Inhabited (HasTokens r) :=\n\u27e8\u27e8[]\u27e9\u27e9\n\ninstance List.nil.tokens : Parser.HasTokens ([] : List \u03c1) :=\ndefault _\n\ninstance List.cons.tokens (r : \u03c1) (rs : List \u03c1) [Parser.HasTokens r] [Parser.HasTokens rs] :\n  Parser.HasTokens (r::rs) :=\n\u27e8tokens r ++ tokens rs\u27e9\n\nclass HasView (\u03b1 : outParam Type) (r : \u03c1) :=\n(view : Syntax \u2192 \u03b1)\n(review : \u03b1 \u2192 Syntax)\n\nexport HasView (view review)\n\ndef tryView {\u03b1 : Type} (k : SyntaxNodeKind) [HasView \u03b1 k] (stx : Syntax) : Option \u03b1 :=\nif stx.isOfKind k then some (HasView.view k stx) else none\n\ninstance HasView.default (r : \u03c1) : Inhabited (Parser.HasView Syntax r) :=\n\u27e8{ view := id, review := id }\u27e9\n\nclass HasViewDefault (r : \u03c1) (\u03b1 : outParam Type) [HasView \u03b1 r] (default : \u03b1) := mk {}\n\ndef messageOfParsecMessage {\u03bc : Type} (cfg : FrontendConfig) (msg : Parsec.Message \u03bc) : Message :=\n{filename := cfg.filename, pos := cfg.fileMap.toPosition msg.it.offset, text := msg.text}\n\n/-- Run Parser stack, returning a partial Syntax tree in case of a fatal error -/\nprotected def run {m : Type \u2192 Type} {\u03b1 \u03c1 : Type} [Monad m] [HasCoeT \u03c1 FrontendConfig] (cfg : \u03c1) (s : String) (r : StateT ParserState (ParserT \u03c1 m) \u03b1) :\nm (Sum \u03b1 Syntax \u00d7 MessageLog) :=\ndo (r, _) \u2190 (((r.run {messages:=MessageLog.empty}).run cfg).parse s).run {},\npure $ match r with\n| Except.ok (a, st) := (Sum.inl a, st.messages)\n| Except.error msg  := (Sum.inr msg.custom.get, MessageLog.empty.add (messageOfParsecMessage cfg msg))\n\nopen MonadParsec\nopen Parser.HasView\nvariables {\u03b1 : Type} {m : Type \u2192 Type}\nlocal notation `Parser` := m Syntax\n\ndef logMessage {\u03bc : Type} [Monad m] [MonadReader \u03c1 m] [HasLiftT \u03c1 FrontendConfig] [MonadState ParserState m]\n  (msg : Parsec.Message \u03bc) : m Unit :=\ndo cfg \u2190 read,\n   modify (\u03bb st, {st with messages := st.messages.add (messageOfParsecMessage \u2191cfg msg)})\n\ndef mkTokenTrie (tokens : List TokenConfig) : Except String (Trie TokenConfig) :=\ndo -- the only hardcoded tokens, because they are never directly mentioned by a `Parser`\n   let builtinTokens : List TokenConfig := [{\u00abprefix\u00bb := \"/-\"}, {\u00abprefix\u00bb := \"--\"}],\n   t \u2190 (builtinTokens ++ tokens).mfoldl (\u03bb (t : Trie TokenConfig) tk,\n     match t.find tk.prefix with\n     | some tk' := match tk.lbp, tk'.lbp with\n       | l, 0  := pure $ t.insert tk.prefix tk\n       | 0, _  := pure t\n       | l, l' := if l = l' then pure t else throw $\n         \"invalid token '\" ++ tk.prefix ++ \"', has been defined with precedences \" ++\n         toString l ++ \" and \" ++ toString l'\n     | none := pure $ t.insert tk.prefix tk)\n     Trie.empty,\n   pure t\n\n\n/- Monad stacks used in multiple files -/\n\n/- NOTE: We move `RecT` under `ParserT`'s `ReaderT` so that `termParser`, which does not\n   have access to `commandParser`'s \u03c1 (=`CommandParserConfig`) can still recurse into it\n   (for command quotations). This means that the `CommandParserConfig` will be reset\n   on a recursive call to `command.Parser`, i.e. it forgets about locally registered parsers,\n   but that's not an issue for our intended uses of it. -/\n@[derive Monad Alternative MonadReader MonadParsec MonadExcept MonadRec]\ndef CommandParserM (\u03c1 : Type) := ReaderT \u03c1 $ RecT Unit Syntax $ parserCoreT Id\n\nsection\nlocal attribute [reducible] ParserT CommandParserM\ninstance CommandParserM.MonadReaderAdapter (\u03c1 \u03c1' : Type) :\n  MonadReaderAdapter \u03c1 \u03c1' (CommandParserM \u03c1) (CommandParserM \u03c1') :=\ninferInstance\ninstance CommandParserM.basicParser (\u03c1 : Type) [HasLiftT \u03c1 ParserConfig] : monadBasicParser (CommandParserM \u03c1) :=\n\u27e8\u03bb _ x cfg rec, x.run \u2191cfg\u27e9\nend\n\n/- The `Nat` at `RecT` is the lbp` -/\n@[derive Monad Alternative MonadReader MonadParsec MonadExcept MonadRec monadBasicParser]\ndef TermParserM := RecT Nat Syntax $ CommandParserM ParserConfig\nabbrev termParser := TermParserM Syntax\n\n/-- A Term Parser for a suffix or infix notation that accepts a preceding Term. -/\n@[derive Monad Alternative MonadReader MonadParsec MonadExcept MonadRec monadBasicParser]\ndef TrailingTermParserM := ReaderT Syntax TermParserM\nabbrev trailingTermParser := TrailingTermParserM Syntax\n\ninstance trailingTermParserCoe : HasCoe termParser trailingTermParser :=\n\u27e8\u03bb x _, x\u27e9\n\n/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/\ndef TokenMap (\u03b1 : Type) := RBMap Name (List \u03b1) Name.quickLt\n\ndef TokenMap.insert {\u03b1 : Type} (map : TokenMap \u03b1) (k : Name) (v : \u03b1) : TokenMap \u03b1 :=\nmatch map.find k with\n| none    := map.insert k [v]\n| some vs := map.insert k (v::vs)\n\ndef TokenMap.ofList {\u03b1 : Type} : List (Name \u00d7 \u03b1) \u2192 TokenMap \u03b1\n| []          := mkRBMap _ _ _\n| (\u27e8k,v\u27e9::xs) := (TokenMap.ofList xs).insert k v\n\ninstance tokenMapNil.tokens : Parser.HasTokens $ @TokenMap.ofList \u03c1 [] :=\ndefault _\n\ninstance tokenMapCons.tokens (k : Name) (r : \u03c1) (rs : List (Name \u00d7 \u03c1)) [Parser.HasTokens r] [Parser.HasTokens $ TokenMap.ofList rs] :\n  Parser.HasTokens $ TokenMap.ofList ((k,r)::rs) :=\n\u27e8tokens r ++ tokens (TokenMap.ofList rs)\u27e9\n\n-- This needs to be a separate structure since `termParser`s cannot contain themselves in their config\nstructure CommandParserConfig extends ParserConfig :=\n(leadingTermParsers : TokenMap termParser)\n(trailingTermParsers : TokenMap trailingTermParser)\n-- local Term parsers (such as from `local notation`) hide previous parsers instead of overloading them\n(localLeadingTermParsers : TokenMap termParser := mkRBMap _ _ _)\n(localTrailingTermParsers : TokenMap trailingTermParser := mkRBMap _ _ _)\n\ninstance commandParserConfigCoeParserConfig : HasCoe CommandParserConfig ParserConfig :=\n\u27e8CommandParserConfig.toParserConfig\u27e9\n\nabbrev commandParser := CommandParserM CommandParserConfig Syntax\n\nend \u00abParser\u00bb\nend Lean\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/tmp/new-frontend/parser/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1276526286405008, "lm_q2_score": 0.03789242296270021, "lm_q1q2_score": 0.004837067396746356}}
{"text": "/-\nTODO:\n  - opaque struct\n  - opaque inductive\n  - equation tags\n  - constructor / recursor tags?\n    - use them in pattern matching\n    - use them in `induction` / `cases` / `match`\n\n  opaque namespace:\n  - including normal namespace\n  - including normal section\n  - including opaque def\n\n\n-/\nimport Lean.Elab.Declaration\nimport Lean.Elab.Command\nimport Lean.Elab.BuiltinCommand\n\nimport Lib.Meta\nimport Lib.Meta.TransportFacts\n\n\nnamespace Lean.Syntax\n\ndef mkEndNode (ident : Option Name) : Syntax :=\nmkNode ``Lean.Parser.Command.end\n  #[mkAtom \"end\", mkOptionalNode <| ident.map mkIdent]\n\ndef mkEndNodeFrom (stx : Syntax) (ident : Option Name) : Syntax :=\nSyntax.node stx.getHeadInfo ``Lean.Parser.Command.end\n  #[mkAtom \"end\", mkOptionalNode <| ident.map mkIdent]\n\nvariable [Monad m] [MonadRef m]\n\ndef mkEndNodeFromRef (ident : Option Name) : m Syntax :=\ndo return mkEndNodeFrom (\u2190 getRef) ident\n\nend Lean.Syntax\n\nnamespace Lean.Name\n\ndef revConcat : List String \u2192 Name :=\nList.foldl mkStr anonymous\n\n@[specialize]\ndef withoutPrivatePrefixAux (ns : List String) (f : Name \u2192 Name) : Name \u2192 Name\n| anonymous => f <| revConcat ns\n| str p s .. => withoutPrivatePrefixAux (s :: ns) f p\n| n@(num p s ..) => n ++ f (revConcat ns)\n\n@[specialize]\ndef withoutPrivatePrefix (f : Name \u2192 Name) : Name \u2192 Name :=\nwithoutPrivatePrefixAux [] f\n\ndef replacePrefix' (n p newP : Name) : Name :=\nwithoutPrivatePrefix (replacePrefix . p newP) n\n\nend Lean.Name\n\nstructure Locked {\u03b1 : Sort u} (x : \u03b1) where\n  val : \u03b1\n  val_eq : val = x\n\nnamespace Lean\n\nnamespace Meta\n\ndef addDef' (us : List Name) (n : Name) (t : Expr) (d : Expr) : MetaM Name := do\ntrace[opaque.decls]\"def {n} : {t}\"\naddDef us n t d\n\ndef addThm' (us : List Name) (n : Name) (t : Expr) (d : Expr) : MetaM Name := do\ntrace[opaque.decls]\"theorem {n} : {t}\"\naddThm us n t d\n\ndef addConst' (us : List Name) (n : Name) (t : Expr) (d : Expr) : MetaM Name := do\ntrace[opaque.decls]\"constant {n} : {t}\"\naddConst us n t d\n\nend Meta\n\nnamespace Parser\nnamespace OpaqueExt\n\nopen Lean.Elab.Tactic\n\nstructure OpaqueDef where\n  declName : Name\n  intlName : Name\n  eqvProof : Name\n  lockedConst : Name\n  unfoldEqn : Option Name := none\n  eqns : Array Name := #[]\n  deriving Inhabited\n\nstructure OpaqueDefIdx where\n  intlToDecl : NameMap OpaqueDef := {}\n  decls : NameMap OpaqueDef := {}\n  simpLemmas : Lean.Meta.SimpTheorems := {}\n  newLemmas : List Name := []\n  deriving Inhabited\n\nnamespace OpaqueDefIdx\n\ndef insert (o : OpaqueDefIdx) (decl : OpaqueDef) : OpaqueDefIdx where\n  intlToDecl := o.intlToDecl.insert decl.intlName decl\n  decls := o.intlToDecl.insert decl.declName decl\n  simpLemmas := o.simpLemmas\n  newLemmas := decl.eqvProof :: o.newLemmas\n\ndef erase (o : OpaqueDefIdx) (decl : Name) : OpaqueDefIdx := Id.run do\nlet some d := o.decls.find? decl\n  | return o\nreturn {\n  decls := o.decls.erase decl\n  intlToDecl := o.intlToDecl.erase d.intlName\n  simpLemmas := o.simpLemmas.eraseCore d.eqvProof\n  newLemmas := o.newLemmas.erase d.eqvProof\n  }\n\nend OpaqueDefIdx\n\nabbrev OpaqueExtension :=\nSimpleScopedEnvExtension OpaqueDef OpaqueDefIdx\n\ndef mkOpaqueExt (extName : Name) : IO OpaqueExtension :=\n  registerSimpleScopedEnvExtension {\n    name     := extName\n    initial  := {}\n    addEntry := fun d decl => d.insert decl\n  }\n\ndef getOpaqueExtension (ext : OpaqueExtension) : MetaM OpaqueDefIdx := do\nreturn ext.getState (\u2190 getEnv)\n\ndef getEqnsForOpaqueDef (ext : OpaqueExtension) (n : Name) : MetaM (Option (Array Name)) := do\nreturn (\u2190 getOpaqueExtension ext)\n  |>.decls\n  |>.find? n\n  |>.map (\u00b7.eqns)\n\ndef getUnfoldEqnsForOpaqueDef (ext : OpaqueExtension) (n : Name) : MetaM (Option Name) := do\nreturn (\u2190 getOpaqueExtension ext)\n  |>.decls\n  |>.find? n\n  |>.bind (\u00b7.unfoldEqn)\n\ndef registerOpaqueAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter \"Ext\") : IO OpaqueExtension := do\n  let ext \u2190 mkOpaqueExt extName\n  Lean.Meta.registerGetEqnsFn <| getEqnsForOpaqueDef ext\n  Lean.Meta.registerGetUnfoldEqnFn <| getUnfoldEqnsForOpaqueDef ext\n  return ext\n\nend OpaqueExt\n\ninitialize opaqueExtension : OpaqueExt.OpaqueExtension \u2190\n  OpaqueExt.registerOpaqueAttr `opaque \"opaque definitions\"\n\ndef getOpaqueExtension :=\nOpaqueExt.getOpaqueExtension opaqueExtension\n\ndef setOpaqueExtension (idx : OpaqueExt.OpaqueDefIdx) : MetaM Unit :=\nmodifyEnv \u03bb env => opaqueExtension.modifyState env \u03bb _ => idx\n\ndef registerOpaqueDef (decl : OpaqueExt.OpaqueDef) : MetaM Unit :=\nmodifyEnv (opaqueExtension.addEntry . decl)\n\n\ndef getSimpLemmas : MetaM Meta.SimpTheorems := do\nlet ext \u2190 getOpaqueExtension\nlet mut simpLemmas := ext.simpLemmas\nfor eqn in ext.newLemmas do\n  simpLemmas \u2190 simpLemmas.addConst (inv := true) eqn\nsetOpaqueExtension <| { ext with\n  newLemmas := []\n  simpLemmas := simpLemmas }\nreturn simpLemmas\n\nnamespace Command\n\nopen Elab Elab.Command\nopen Meta\n\nsyntax (name := opaqueDef)\n   declModifiers \"opaque \" \u00abdef\u00bb : command\n\ninitialize registerTraceClass `opaque\ninitialize registerTraceClass `opaque.decls\ninitialize registerTraceClass `opaque.parser\ninitialize registerTraceClass `opaque.debug\ninitialize registerTraceClass `opaque.proof.state\n\ndef proveNewEqn (t\u2080 : Expr) (eqnN name name' defN : Name) : MetaM Name := do\nlet eqn \u2190 mkConstWithLevelParams eqnN\nlet ls := (\u2190 getConstInfo eqnN).levelParams\nforallTelescope t\u2080 \u03bb vs t => do\n  let proof := (\u2190 mkFreshExprMVar t) |>.mvarId!\n  let r \u2190 rewrite proof t (\u2190 mkConstWithFreshMVarLevels defN)\n  let rule \u2190 mkAppOptM ``Eq.mpr #[none, none, r.eqProof]\n  let [v] \u2190 apply proof rule\n    | throwError \"too many goals\"\n  let [] \u2190 apply v (\u2190 mkConstWithFreshMVarLevels eqnN)\n    | throwError \"too many goals\"\n  let proof \u2190 mkLambdaFVars vs (mkMVar proof)\n  let newEqnName := eqnN.replacePrefix' name' name\n  addThm' ls newEqnName t\u2080 proof\n\ndef rewriteEqn (eqn name name' eqThm : Name) : MetaM Name := do\nlet eqnE \u2190 mkConstWithLevelParams eqn\nlet t \u2190 inferType eqnE\nlet c \u2190 mkConstWithLevelParams name\nlet c' \u2190 mkConstWithLevelParams name'\nlet t := t.replace \u03bb e => if e == c' then some c else none\nproveNewEqn t eqn name name' eqThm\n\ndef constantWrapper (declName intlName : Name) : MetaM Unit := do\n  let ls := (\u2190 getConstInfo intlName).levelParams\n  let ls' := ls.map mkLevelParam\n  let e \u2190 mkConstWithLevelParams intlName\n\n  let t \u2190 inferType e\n  let t' \u2190 mkAppOptM ``Locked #[none, e]\n  let eqPr \u2190 mkAppOptM ``rfl #[none, e]\n  let locked \u2190 mkAppOptM ``Locked.mk #[none, e, e, eqPr]\n  let lockedName \u2190 addConst' ls (declName ++ `_locked) t' locked\n\n  let locked_e \u2190 mkConstWithLevelParams lockedName\n  let e' \u2190 mkAppOptM ``Locked.val #[none, none, locked_e]\n  discard <| addDef' ls declName t e'\n\n  let e_def \u2190 mkConstWithLevelParams declName\n  let pr \u2190 mkAppOptM ``Locked.val_eq #[none, none, locked_e]\n  let eqStmt \u2190 mkAppOptM ``Eq #[none, e_def, e]\n  let eqThmName := declName ++ `_unlock\n  let eqThm \u2190 addThm' ls eqThmName eqStmt pr\n  let eqns := (\u2190 getEqnsFor? intlName) |>.getD #[]\n  let uEqns : Option Name \u2190 getUnfoldEqnFor? intlName\n  let newEqns  \u2190 eqns.mapM (rewriteEqn . declName intlName eqThm)\n  let newUEqns \u2190 uEqns.mapM (rewriteEqn . declName intlName eqThm)\n  let t \u2190 mkAppOptM ``Transport.EqvTerm\n    #[none, none, mkConst declName ls', mkConst intlName ls']\n  let eqC := mkConst eqThm ls'\n  let eqvInst \u2190 mkAppOptM ``Transport.EqvTerm.ofEq #[none, none, none, eqC]\n  let inst \u2190 addDef' ls (declName ++ `instEqvTerm) t eqvInst\n  addInstance inst AttributeKind.\u00abglobal\u00bb 0\n\n  let opDef : OpaqueExt.OpaqueDef :=\n    { declName := declName,\n      intlName := intlName,\n      eqvProof := eqThm,\n      lockedConst := lockedName,\n      eqns := newEqns,\n      unfoldEqn := newUEqns }\n  registerOpaqueDef opDef\n  pure ()\n\ndef replaceName (n n' : Name) (s : Syntax) := Id.run <|\ns.replaceM \u03bb s =>\n  if s.isIdent && s.getId == n then\n    return mkIdentFrom s n'\n  else return none\n\nsection Name\nopen Name\n\ndef mkImplName : Name \u2192 Name\n| str p s _ => p ++ mkSimple s ++ `_impl ++ mkSimple s\n| n => n\n\nend Name\n\n@[commandElab opaqueDef]\ndef elabOpaqueDef : CommandElab := \u03bb stx => do\n  let mods := stx[0]\n  let kw := stx[1]\n  let \u00abdef\u00bb := stx[2]\n  let declName  := \u00abdef\u00bb[1][0].getId\n  let ns \u2190 getCurrNamespace\n  let insideName := mkImplName declName\n  trace[opaque.decls]\"impl name: {insideName}\"\n  let id    := \u00abdef\u00bb[1].setArg 0 <| Lean.mkIdent insideName\n  let \u00abdef\u00bb := \u00abdef\u00bb.setArg 1 id\n  let stx   := mkNode ``Lean.Parser.Command.declaration #[mods, \u00abdef\u00bb]\n  trace[opaque.decls]\"declNamespace: {ns}\"\n  Lean.Elab.Command.elabDeclaration stx\n  let declName   := ns ++ declName\n  let insideName := ns ++ insideName\n  liftTermElabM none <| constantWrapper declName insideName\n\nend Command\nnamespace Transport\n\nopen OpaqueExt\n\ndef transportType (e : Expr) : MetaM Expr := do\nlet idx \u2190 getOpaqueExtension\nreturn e.replace \u03bb\n  | (Expr.const n ls _) =>\n    match idx.intlToDecl.find? n with\n    | some d => mkConst d.declName ls\n    | none => none\n  | _ => none\n\nopen Lean.Meta\nopen Transport\nopen Lean.Elab\nopen Lean.Parser.Tactic\nopen Lean.Elab.Tactic\nopen Lean.Elab.Term\n\ndef showProofState : TacticM MessageData := do\nlet gs \u2190 getGoals\nlet mut res : Format := s!\"Goals ({gs.length})\"\nfor g in gs do\n  let g \u2190 Meta.ppGoal g\n  res := res ++ \"\\n\\n\" ++ g\nreturn res\n\ndef proveTransport (g : Expr) : TermElabM Expr := do\nlet g \u2190 mkFreshExprMVar g\ndiscard <| Tactic.run g.mvarId! do\n  trace[opaque.proof.state]\"begin proof\"\n  repeat do\n    traceM `opaque.proof.state showProofState\n    discard (liftMetaTactic1' (intro . `_))  <|>\n      liftMetaTactic1 (do Meta.assumption .; pure none) <|>\n      liftMetaTactic (Meta.applyc . ``Transport.refl) <|>\n      liftMetaTactic (Meta.applyc . ``Transport.EqvTypes_arrow) <|>\n      liftMetaTactic (Meta.applyc . ``Transport.EqvTypes_forall') <|>\n      liftMetaTactic (Meta.applyc . ``Transport.EqvTypes_forall) <|>\n      liftMetaTactic (Meta.applyc . ``Transport.EqvTerm_app) <|>\n      liftMetaTactic (Meta.applyc . ``Transport.EqvTerm_app') <|>\n      liftMetaTactic (Meta.applyc . ``Transport.EqvTypes_of_EqvTerm) <|>\n      liftMetaTactic (Meta.applyc . ``inferInstance)\n  until (\u2190 getGoals).isEmpty\n  let gs \u2190 getUnsolvedGoals\n  done\n  trace[opaque.proof.state]\"end proof\"\nreturn g\n\ndef transportDecl (declName intlName : Name) (isThm : Bool) : MetaM Unit := do\n  trace[opaque.debug]\"begin {declName} ({intlName})\"\n  let c  \u2190 mkConstWithLevelParams intlName\n  let t  \u2190 inferType c\n  let t' \u2190 transportType t\n  let e \u2190 mkAppOptM ``Transport.mkLockedType #[t',none,c]\n  let argT := (\u2190 inferType e).bindingDomain!\n  trace[opaque.debug]\"begin transport proof\"\n  let transPr \u2190 proveTransport argT |>.run'\n  trace[opaque.debug]\"end transport proof\"\n  let pr := mkApp e transPr\n  let ls  := (\u2190 getConstInfo intlName) |>.levelParams\n  let ls' := ls.map mkLevelParam\n  let prT \u2190 inferType pr\n  let pr' \u2190 instantiateMVars pr\n  let lockedDecl \u2190 addConst' ls (declName ++ `_locked)\n      (\u2190 inferType pr) pr\n  let lockedC := mkConst lockedDecl ls'\n  let e \u2190 mkAppOptM ``LockedType.val\n    #[none, none, none, lockedC]\n  if isThm\n    then discard <| addThm' ls declName t' e\n    else discard <| addDef' ls declName t' e\n\n  let declC := mkConst declName ls'\n  let intlC := mkConst intlName ls'\n  let e \u2190 mkAppOptM ``LockedType.val_eqv #[none, none, none, lockedC]\n  let heq \u2190 mkAppOptM ``HEq #[none, declC, none, intlC]\n  let unlock \u2190 addThm' ls (declName ++ `_unlock) heq e\n\n  let instT \u2190 mkAppOptM ``Transport.EqvTerm\n    #[none,none,declC,intlC]\n  let heqPr := mkConst unlock ls'\n  let instPr \u2190 mkAppOptM ``Transport.EqvTerm.ofHEq\n    #[none,none,none,none,heqPr]\n  let inst \u2190 addThm' ls (declName ++ `instEqvTerm) instT instPr\n  addInstance inst AttributeKind.\u00abglobal\u00bb 0\n\n  let opDef : OpaqueExt.OpaqueDef :=\n    { declName := declName,\n      intlName := intlName,\n      eqvProof := unlock,\n      lockedConst := lockedDecl,\n      eqns := #[],\n      unfoldEqn := none }\n  registerOpaqueDef opDef\n  trace[opaque.debug]\"end {declName} ({intlName})\"\n\nopen Lean.Elab.Command\n\nprivate def removeImpl : Name \u2192 Name\n| Name.str p s _ =>\n  if s == \"_impl\" then p\n  else removeImpl p\n| n => n\n\ndef elabAndTransport (_ : Name) (d : Syntax) : CommandElabM Unit := do\nlet ns \u2190 getCurrNamespace\nlet \u00abdef\u00bb := d.getArgs[1]\nlet kind := \u00abdef\u00bb.getKind\nlet rawName := \u00abdef\u00bb[1][0].getId\nlet intlName := ns ++ rawName\nlet declName := removeImpl ns ++ rawName\ntrace[opaque.parser]\"decl kind:   {d.getKind}\"\ntrace[opaque.parser]\"inside kind: {\u00abdef\u00bb.getKind}\"\nelabDeclaration d\nlet fullName \u2190 resolveGlobalConstNoOverload <| Lean.mkIdent intlName\nif isPrivateName fullName then\n  pure ()\nelse if kind == `Lean.Parser.Command.def then\n  liftCoreM <| transportDecl declName intlName false |>.run'\nelse if kind == `Lean.Parser.Command.theorem then\n  liftCoreM <| transportDecl declName intlName true |>.run'\nelse\n  throwError \"not supported\"\n\nopen Lean.Syntax\ndef myElabEnd (n : Name) : CommandElabM Unit := do\nelabEnd (\u2190 mkEndNodeFromRef <| some <| n ++ `_impl ++ n  )\n\nmacro \"opaque \" \"namespace \" id:ident : command => do\n  let idImplName := Lean.mkIdent <| id.getId ++ `_impl\n  let defName := Lean.mkIdent <| id.getId ++ `_impl ++ id.getId\n  let implName := Lean.mkIdent `_impl\n  let idStr := Lean.Syntax.mkStrLit id.getId.toString\n  let command := Lean.mkIdent `command\n  let declaration := Lean.mkIdent ``Lean.Parser.Command.declaration\n  let idLit := Lean.Syntax.mkNameLit <| toString id\n  let implNLit := Lean.Syntax.mkNameLit \"_impl\"\n  `(\n    #quiet check $defName:ident\n\n    namespace $idImplName:ident\n    namespace $(Lean.mkIdent id.getId):ident\n\n    local elab d:($declaration:ident) : $command =>\n      elabAndTransport $idLit:name d\n\n    -- local elab_rules : $command\n    -- | `($$d:declaration) => elabAndTransport $idLit:nameLit\n\n    local elab \"end\" id:ident : $command:ident => myElabEnd id.getId\n\n    -- local elab_rules : $command\n    -- | `(end $$id:ident) => myElabEnd id.getId\n\n    local elab \"section\" id:(ident)? : $command =>\n      throwError \"section and namespaces not supported in opaque namespaces\"\n\n    local elab \"namespace\" id:(ident)? : $command =>\n      throwError \"section and namespaces not supported in opaque namespaces\"\n\n    -- local elab_rules : $command\n    -- | `(section $$id) =>\n    --   throwError \"section and namespaces not supported in opaque namespaces\"\n\n    -- local elab_rules : $command\n    -- | `(namespace $$id) =>\n    --   throwError \"section and namespaces not supported in opaque namespaces\"\n\n  )\n\nend Transport\nend Parser\nend Lean\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/Meta/Opaque.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18010665528475028, "lm_q2_score": 0.02675928134209039, "lm_q1q2_score": 0.004819524660347524}}
{"text": "/-!\n#  Errors\n\nError handling is done with the `Except \u03b5 \u03b1` datatype. An `Except` is either `ok : \u03b1` or `error : \u03b5`.\nErrors of type `\u03b5` are added to monads with `EStateM \u03b5` or `ExceptT \u03b5`. Here are some common choices of `\u03b5` that are used throughout Lean:\n\n- `Exception` is either an\n  - `error (ref : Syntax) (msg : MessageData)` is for errors that a user should try to correct, (eg a tactic is not applicable). The ref syntax is used by the language server to figure out where to draw the red squiggly. MessageData is the message, but with support for interactivity in the Infoview (so you can see the types of terms etc.)\n  - `internal (id : InternalExceptionId) (extra : KVMap)` is used for when lean crashes.\n- `IO.Error` is specialised for errors that can happen during IO operations (rather than lean-specific errors).\n  There is an error type for all of the errors that you might get from the OS while doing syscalls.\n  There is also a `userError (msg : String)` for when you want to bundle a user error.\n- `Empty` is used when you don't want to throw errors.\n\nThere are also a load of monad classes which are used to talk about errors\n\n- `MonadExcept \u03b5 M` means that you have `tryCatch : M \u03b1 \u2192 (\u03b5 \u2192 M \u03b1) \u2192 M \u03b1` and `throw : \u03b5 \u2192 M \u03b1` available.\n  This in turn is used to drive the `throw`/`try`/`catch` syntax.\n- `MonadError M` means that you can throw and catch `Exceptions` and make the `Exceptions` properly where it is aware of the context of the error, so that you can draw red squigglies in the right place and render messages interactively.\n  - `MonadExcept Exception M`: it can throw and catch `Exception`s.\n  - `MonadRef M` is to do with managing syntax hygiene. It looks like `MonadReader Syntax M`, but slightly different.\n  - `AddErrorMessageContext M`. Which means that you can take some `MessageData` and add context information to it. For example if you had a message which had to render an mvar, in order for the infoview to show this properly you would need to tell the message what metavariable context to use.\n\n## Alternative\n\nThere is also a class `Alternative M`, this is `\u2200 \u03b1, OrElse (M \u03b1)` and a `failure : \u2200 \u03b1, M \u03b1`.\nNote that in general `ExceptT\n\n## Syntax for error handling\n\nThere are a few different mechanisms you can use for throwing stuff.\n\n- `throwError \"...\"` uses `MonadError` and throws an Exception in your monad. The \"...\" is a MessageData string comprehension so you can do `\" ... {e} ...\"` where `e : Expr` and it will correctly render that in an interactive way which is nice.\n  `throwErrorAt ref \"...\"` is similar, but you can specify which piece of syntax the squigglie should appear at.\n- `throw` uses `MonadExcept`, so it doesn't do all the fancy message stuff that `throwError` does. A variant is `throwThe \u03b5 e` where you just make the instance of the `MonadError \u03b5 M` that you want explicit; this is useful if you have multiple instances of `MonadError _ M` flying around.\n- `try/catch` syntax can be much nicer than manually handling the error cases with match blocks:\n  ```lean\n  try\n    x\n  catch\n    | p\u2081 => asdf\n    | p\u2082 => qwerty\n  ```\n- This is not strictly error handling, but is good to know about: if you are in a `do` block, you can pattern match the let expressions and have a 'failover' case\n  ```\n  do\n    let head :: tail \u2190 getGoals | e\n  ```\n  the `e : M \u03b1` is run if the pattern matching on the lhs of the `let` assignment fails.\n- `guard p` will test `p` and then throw an error\n\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/temp/errors.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1520322377801054, "lm_q2_score": 0.03161876829522817, "lm_q1q2_score": 0.004807072099774187}}
{"text": "example : True := by\n  rewrite []\n--^ textDocument/hover\n  trivial\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/1403.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846179056896438, "lm_q2_score": 0.034618837220668094, "lm_q1q2_score": 0.004793386188989214}}
{"text": "import Runtime.Execution.Next\nimport Runtime.Execution.Apply\nimport Runtime.Execution.Propagate\nimport Runtime.Execution.Triggers\n\nnamespace Execution.Executable\nopen Network Graph Class\n\ndef fire (exec : Executable net) {reactor : ReactorId net} (reaction : Reaction reactor.class) :=\n  reaction.val.run {\n    ports          := exec.reactionInputs reactor     |>.restrict\n    actions        := exec.interface reactor .actions |>.restrict\n    state          := reaction.eqState  \u25b8 exec.interface reactor .state\n    params         := reaction.eqParams \u25b8 exec.interface reactor .params\n    tag            := exec.tag\n    physicalOffset := exec.physicalOffset\n  }\n\ndef fireToIO (exec : Executable net) {reactor : ReactorId net} (reaction : Reaction reactor.class) :=\n  toIO <| exec.fire reaction\nwhere\n  toIO {\u03b1} {kind : Reaction.Kind} : (kind.monad \u03b1) \u2192 IO \u03b1 :=\n    match kind with | .pure => pure | .impure => id\n\n-- Advances the given executable to the state given by `next`.\n-- This includes:\n-- * advancing the tag\n-- * dequeueing events for that tag\n-- * clearing all ports\n-- * setting actions' values for the given tag\ndef advance (exec : Executable net) (next : Next net) : Executable net := { exec with\n  tag := next.tag\n  queue := next.queue\n  toPropagate := #[]\n  reactors := fun id => { exec.reactors id with\n    timer := next.timers exec id\n    interface := fun\n      | .inputs  => next.inputs id\n      | .actions => next.actions id\n      | .outputs => Interface?.empty\n      | _        => exec.interface id _\n  }\n}\n\ntheorem advance_tag_strictly_increasing (exec : Executable net) :\n  (Next.for exec = some next) \u2192 exec.tag < (exec.advance next).tag :=\n  Next.for_tag_strictly_monotonic exec\n\ndef shutdown (exec : Executable net) (h : exec.state = .shutdownPending) : Executable net :=\n  match hn : Next.for exec  with\n  | some next => { exec.advance next with state := .shuttingDown }\n  | none => by have h' := Next.for_isSome_if_shutdownPending h; simp [hn] at h'\n\n-- TODO: Once Lean has universe polymorphic IO:\n-- * factor out a `runInst` function for the instantaneous execution\n-- * factor out a `runTimed` function for everything currently happening in the `none` branch\n-- Then you can actually prove theorems about these functions.\npartial def run (exec : Executable net) (topo : Array (ReactionId net)) (reactionIdx : Nat) : IO Unit := do\n  match topo[reactionIdx]? with\n  -- This branch is entered whenever we've completed an instantaneous execution.\n  | none =>\n    match h : exec.state with\n    -- The instantaneous execution where the `.shutdown` trigger is active\n    -- has already been executed, so we terminate execution.\n    | .shuttingDown => return\n    -- The last instantaneous execution contained a shutdown request,\n    -- so the next instantaneous execution performs shutdown.\n    | .shutdownPending => exec.shutdown h |>.run topo 0\n    -- Case 1:\n    -- We've reached starvation (there are no more events to be processed),\n    -- so the next instantaneous execution performs shutdown.\n    -- Case 2:\n    -- Execution continues normally at the tag of the next event.\n    | .executing =>\n      match Next.for exec with\n      | none =>\n        let exec := { exec with state := .shutdownPending }\n        exec.shutdown rfl |>.run topo 0\n      | some next =>\n        let exec := exec.advance next\n        IO.sleepUntil exec.absoluteTime\n        exec.run topo 0\n  -- This branch is entered whenever we're within an instantaneous execution.\n  | some reactionId =>\n    let reaction := reactionId.reaction\n    let mut exec := exec\n    if Triggers exec reaction then\n      exec := (\u2190 exec.fireToIO reaction)\n        |> ReactionOutput.fromRaw\n        |> exec.apply\n        |>.propagate reactionId\n    exec.run topo (reactionIdx + 1)\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/Execution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804730998169, "lm_q2_score": 0.017986213877115107, "lm_q1q2_score": 0.004782183054921857}}
{"text": "import util.tactic\nimport util.io\nimport all\n\nsection main\n\nsection\n\nnamespace io\nnamespace fs\n\ndef put_str_ln_flush (h : handle) (s : string) : io unit :=\nput_str h s *> put_str h \"\\n\" *> flush h\n\nend fs\nend io\n\nsetup_tactic_parser\n\n-- Expected file format:\n-- <decl>, <import> ... <import>, <open> ... <open>\n\nmeta def parse_decl_and_metadata (input : string) : tactic (name \u00d7 list name \u00d7 list name) := do\n flip lean.parser.run_with_input input $ do\n  name \u2190 ident,\n  tk \",\",\n  imports \u2190 many ident,\n  tk \",\",\n  opens \u2190 many ident,\n  pure (name, imports, opens)\n\nend\n\ndef for_ {m \u03b1 \u03b2} [monad m] (xs : list \u03b1) (body : \u03b1 \u2192 m \u03b2) := list.mmap' body xs\n\nmeta def main_aux (names_file : string) (dest : string) : io unit := do {\n  nm_strs \u2190 (io.mk_file_handle names_file io.mode.read >>= \u03bb f,\n    (string.split (\u03bb c, c = '\\n') <$> buffer.to_string <$> io.fs.read_to_end f)),\n\n  let nm_strs := nm_strs.filter (\u03bb x : string, x.length > 0),\n  nms : list (name \u00d7 list name \u00d7 list name) \u2190 io.run_tactic'' $ nm_strs.mmap parse_decl_and_metadata,\n  dest_handle \u2190 io.mk_file_handle dest io.mode.write,\n\n  io.run_tactic'' $ do {\n    env \u2190 tactic.get_env,\n    for_ (nm_strs.zip nms) $ \u03bb \u27e8nm_str, \u27e8nm, imports, open_ns\u27e9\u27e9, tactic.try $ do {\n      decl \u2190 env.get nm,\n      if decl.is_theorem then do {\n        tactic.trace format! \"[filter_defs] KEEPING {nm.to_string}\",\n        tactic.unsafe_run_io $ io.fs.put_str_ln_flush dest_handle nm_str\n      } else do {\n        tactic.trace format! \"[filter_defs] DISCARDING {nm.to_string}\",\n        pure ()\n      }\n    }\n  }\n}\n\nmeta def main : io unit := do {\n  io.put_str_ln' \"ENTERING\",\n  args \u2190 io.cmdline_args,\n  names_file \u2190 args.nth_except 0 \"names_file\",\n  dest \u2190 args.nth_except 1 \"dest\",\n  main_aux names_file dest\n}\n\nend main\n", "meta": {"author": "openai", "repo": "lean-gym", "sha": "1585ac4d2e56a1ceb72243ce859645b9d0069d34", "save_path": "github-repos/lean/openai-lean-gym", "path": "github-repos/lean/openai-lean-gym/lean-gym-1585ac4d2e56a1ceb72243ce859645b9d0069d34/src/tools/filter_decls.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1581743527484317, "lm_q2_score": 0.03021458641245071, "lm_q1q2_score": 0.00477917264935095}}
{"text": "example : True := by\n  skip\n    skip --< should complain about misleading indentation\n  trivial\n\nmacro \"frobnicate\" : tactic => `(tactic| skip)\n\nexample : True := by\n  conv =>\n    skip\n    frobnicate --< should not parse frobnicate as a tactic\n  trivial\n\n-- check error message without default handler for conv tactics\ndeclare_syntax_cat item\nsyntax \"valid_item\" : item\nmacro \"block\" \"=>\" sepByIndentSemicolon(item) : tactic => `(tactic| skip)\n\nexample : True := by\n  block =>\n    valid_item\n    frobnicate --< should not parse frobnicate as a tactic\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/1606.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.028870905797366845, "lm_q1q2_score": 0.0047497393024026726}}
{"text": "import theology.natural.god\nopen set topological_space classical\nset_option pp.generalized_field_notation true\nlocal attribute [instance] prop_decidable\n\nnamespace ontology\n\nvariables {\u03c9 : ontology} (c : \u03c9.cause)\n\nlemma eps_stronger : c.eps \u21d2 c.epcs \u2229 c.epsc :=\n  begin\n    intros w hw,\n    constructor,\n      rintro \u27e8e, he\u2081, he\u2082\u27e9,\n      refine \u27e8e.exists, e.existential, he\u2082, _\u27e9,\n      refine \u27e8_,hw e he\u2081 he\u2082\u27e9,\n      simp [nbe] at he\u2081,\n      exact \u27e8e.possible, he\u2081\u27e9,\n    intros h\u2081 e h\u2082 su h\u2083 h\u2084 h\u2085 h\u2086,\n    apply h\u2082; try{assumption},\n    refine \u27e8h\u2084,_\u27e9,\n    let s : \u03c9.entity := \u27e8su, h\u2085, nonempty_of_mem h\u2086\u27e9,\n    apply hw s,\n      simp [nbe],\n      exact h\u2084.2,\n    simpa [su],\n  end\n\n\ntheorem aquinas_second (h' : c.entitative) : c.epcs \u2229 c.epsc \u2229 c.epc \u2229 (c.epp (\u03bbe, c.csubstratum e)) \u21d2 c.first_cause \u03c9.nbe :=\n  begin\n    rintro w \u27e8\u27e8\u27e8h\u2081, h\u2082\u27e9, pc\u27e9, pp\u27e9,\n    by_cases h : \u2203 e : \u03c9.entity, e.contingent \u2227 e.exists w, swap,\n      exact c.first_cause_of_nocontingent h,\n    specialize h\u2081 h, clear h,\n    specialize h\u2082 h\u2081 univ, clear h\u2081,\n    suffices c\u2080 : \u2200 (su : event \u03c9), cause.csubstratum c su \u2192\n                 su \u2260 univ \u2192 event.existential su \u2192\n                 event.occurs su w \u2192 cause.causes c univ su w,\n      specialize h\u2082 c\u2080,\n      simp [cause.first_cause, nbe],\n      refine \u27e8by simp [univ],_\u27e9,\n      unfold_coes, simp,\n      intros e h\u2083 h\u2084,\n      replace h\u2084 := ne.symm h\u2084,\n      apply h\u2082; try{assumption},\n        exact \u27e8e.possible, h\u2084\u27e9,\n      exact e.existential,\n    clear h\u2082,\n    intros ee h\u2083 h\u2084 h\u2085 h\u2086,\n    let e : \u03c9.entity := \u27e8ee, h\u2085, nonempty_of_mem h\u2086\u27e9,\n    have c\u2081 := pc e (by simpa [nbe]) h\u2086,\n    have c\u2082 := pp e h\u2083 c\u2081,\n    obtain \u27e8ge, hg, cg\u27e9 := c\u2082,\n    replace h\u2083 := h\u2083.2,\n    specialize h\u2083 ge cg,\n    convert cg,\n    replace cg := h' (nonempty_of_mem \u27e8ee, cg\u27e9),\n    symmetry,\n    by_contradiction h,\n    let g : \u03c9.entity := \u27e8ge, cg, nonempty_of_mem h\u2083\u27e9,\n    specialize pc g (by simpa [nbe]) h\u2083,\n    unfold_coes at pc, simp [g] at pc,\n    contradiction,\n  end\n\ntheorem leibniz_second : (c.epcs (@entity.contingent \u03c9) univ) \u2229 (c.epsc univ) \u2229 c.epsr \u2229 (c.epp' (\u03bbe, c.csubstratum e)) \u21d2 c.first_cause \u03c9.nbe :=\n  begin\n    rintro w \u27e8\u27e8\u27e8h\u2081, h\u2082\u27e9, psr\u27e9, pp\u27e9,\n    by_cases h : \u2203 e : \u03c9.entity, e.contingent \u2227 e.exists w, swap,\n      exact c.first_cause_of_nocontingent h,\n    specialize h\u2081 h, clear h,\n    specialize h\u2082 h\u2081 univ, clear h\u2081,\n    suffices c\u2080 : \u2200 (su : event \u03c9), cause.csubstratum c su \u2192\n                 su \u2260 univ \u2192 univ su \u2192\n                 event.occurs su w \u2192 cause.causes c univ su w,\n      specialize h\u2082 c\u2080,\n      simp [cause.first_cause, nbe],\n      refine \u27e8by simp [univ],_\u27e9,\n      unfold_coes, simp,\n      intros e h\u2083 h\u2084,\n      replace h\u2084 := ne.symm h\u2084,\n      apply h\u2082; try{assumption},\n        exact \u27e8e.possible, h\u2084\u27e9,\n      trivial,\n    clear h\u2082,\n    intros ee h\u2083 h\u2084 h\u2085 h\u2086,\n    have c\u2081 := psr ee \u27e8nonempty_of_mem h\u2086,h\u2084\u27e9 h\u2086,\n    have c\u2082 := pp ee h\u2083 c\u2081,\n    obtain \u27e8g, hg, cg\u27e9 := c\u2082,\n    replace h\u2083 := h\u2083.2,\n    specialize h\u2083 g cg,\n    convert cg,\n    symmetry,\n    by_contradiction h,\n    specialize psr g \u27e8nonempty_of_mem h\u2083,h\u27e9 h\u2083,\n    obtain \u27e8absurdity, insanity\u27e9 := psr,\n    replace insanity := c.caused_causes insanity,\n    contradiction,\n  end\n\n-- And of course we can get `dscotus` out of these proofs:\ntheorem scotus_second (h' : c.entitative) : \u22c4(c.epcs \u2229 c.epsc \u2229 c.epc \u2229 (c.epp (\u03bbe, c.csubstratum e))) \u2192 c.dscotus :=\n  c.scotus_theorem $ aquinas_second c @h'\n\ntheorem scotus_second_psr : \u22c4((c.epcs (@entity.contingent \u03c9) univ) \u2229 (c.epsc univ) \u2229 c.epsr \u2229 (c.epp' (\u03bbe, c.csubstratum e))) \u2192 c.dscotus :=\n  c.scotus_theorem $ leibniz_second c\n\n\n-- theorem material_substratum : \u2200 {c' : \u03c9.cause} (mc : c'.mcause), c.pcem mc \u2229 mc.pis c \u21d2 c.epcs (@entity.contingent \u03c9) univ :=\n--   begin\n--     rintros c' mc w \u27e8hw\u2081,hw\u2082\u27e9 \u27e8e,he\u2081,he\u2082\u27e9,\n--     by_cases h : mc.immaterial e w,\n--       specialize hw\u2082 e h,\n--       refine \u27e8e, by trivial, _\u27e9,\n--       refine \u27e8he\u2082, _, hw\u2082\u27e9,\n--       unfold_coes,\n--       simp [nbe] at he\u2081,\n--       exact \u27e8e.possible, he\u2081\u27e9,\n--     simp [cause.mcause.immaterial] at h,\n--     replace h : \u00acc'.uncaused e.exists w,\n--       by_contradiction h\u2080,\n--       apply h,\n--       exact \u27e8he\u2082,h\u2080\u27e9,\n--     simp [cause.uncaused, cause.caused] at h,\n--     simp [has_neg.neg, compl, set_of, has_mem.mem, set.mem] at h,\n--     obtain \u27e8m, hm\u27e9 := h,\n--     replace hm := c'.caused_causes hm,\n--     specialize hw\u2081 e hm,\n--     obtain \u27e8f, hf\u2081, hf\u2082, h\u27e9 := hw\u2081,\n    \n    -- use f.continues,\n    -- push_neg at h,\n      \n    -- unfold_coes at h,\n    -- simp [set_of] at h,\n    \n  -- end\n\ntheorem leibniz_BCCF (h : c.conjunctive\u2081') : c.epsr \u2229 c.epss \u21d2 c.first_cause \u03c9.nbe :=\n  begin\n    rintros w \u27e8psr, pss\u27e9,\n    by_cases c\u2080 : \u2200 w', w' = w,\n      exact c.first_cause_of_parmenides c\u2080,\n    push_neg at c\u2080,\n    replace c\u2080 : ({w} : \u03c9.event).contingent,\n      simp [ext_iff], exact c\u2080,\n    have c\u2081 := psr {w} c\u2080 (by simp),\n    obtain \u27e8g, hg\u27e9 := c\u2081,\n    specialize pss g hg,\n    have c\u2082 : c.causes univ {w} w,\n      convert hg,\n      symmetry,\n      by_contradiction cg,\n      have c\u2083 : {w} = g \u2229 {w},\n        ext w', simp,\n        exact \u27e8\u03bbh, \u27e8by convert pss, h\u27e9, and.right\u27e9,\n      rw c\u2083 at hg,\n      have c\u2084 := h g g {w} \u27e8nonempty_of_mem pss,cg\u27e9 c\u2080 hg,\n      replace c\u2084 := nonempty_of_mem c\u2084.1,\n      have c\u2085 := c.irreflexive g,\n      contradiction,\n    clear psr pss hg g,\n    simp [cause.first_cause, nbe],\n    refine \u27e8by simp [univ],_\u27e9,\n    unfold_coes, simp,\n    intros e h\u2083 h\u2084,\n    replace h\u2084 := ne.symm h\u2084,\n    specialize h univ e {w} \u27e8nonempty_of_mem h\u2083,h\u2084\u27e9 c\u2080,\n    unfold_coes at h,\n    specialize @h w _, swap,\n      have c\u2083 : {w} = e.exists \u2229 {w},\n        ext w', simp,\n        exact \u27e8\u03bbh, \u27e8by convert h\u2083, h\u27e9, and.right\u27e9,\n      rw \u2190c\u2083,\n      exact c\u2082,\n    exact h.1,\n  end\n\ntheorem scotus_leibniz_BCCF (h : c.conjunctive\u2081') : \u22c4(c.epsr \u2229 c.epss) \u2192 c.dscotus :=\n  c.scotus_theorem $ leibniz_BCCF c h\n\n\ntheorem atheological_hylemorphism : (\u2203 c : \u03c9.cause, \u22c4(c.uhylemorphism \u2229 \u03c9.nonparmenidean)) \u2192 \u03c9.atheism :=\n  begin\n    rintros \u27e8c, \u27e8w, \u27e8\u27e8hc,hw\u27e9, nparm\u27e9\u27e9\u27e9,\n    obtain \u27e8e, \u27e8he\u2081,he\u2082\u27e9\u27e9 := nparm,\n    have c\u2080 : (\u2203 s : \u03c9.substance, s.contingent \u2227 s.exists w) \u2228 \u03c9.atheism,\n      by_cases h\u2080 : e.perfect, swap,\n        let a : \u03c9.accident := \u27e8e, h\u2080\u27e9,\n        by_cases h\u2081 : a.owner.necessary,\n          right,\n          simp [accident.owner, nb] at h\u2081,\n          intro theism,\n          simp [ontology.theism, ext_iff] at theism,\n          apply theism,\n          refine \u27e8a, _\u27e9,\n          simp [accident.inheres, entity.subsists, nb],\n          exact h\u2081,\n        left,\n        use a.owner,\n        refine \u27e8h\u2081,_\u27e9,\n        have c\u2080 := a.inh_owner,\n        replace c\u2080 := entails_of_inheres c\u2080,\n        exact c\u2080 he\u2082,\n      left,\n      refine \u27e8\u27e8e,h\u2080\u27e9,_,he\u2082\u27e9,\n      simp [nb, -entity_ext_iff],\n      exact he\u2081,\n    cases c\u2080, swap, assumption,\n    obtain \u27e8s, h\u2081, h\u2082\u27e9 := c\u2080,\n    have c\u2081 := hw s \u27e8s.perfect,_\u27e9 h\u2082, swap,\n      simp [nb] at h\u2081,\n      unfold_coes, intro h,\n      specialize h\u2081 _,swap,\n        apply substance_ext,\n        simp at h, exact h,\n      contradiction,\n    have c\u2082 := hc.axiom\u2088,\n    simp [cause.pp, ext_iff] at c\u2082,\n    replace c\u2081 := @c\u2082 w s (by trivial) c\u2081,\n    clear c\u2082,\n    obtain \u27e8m, h\u2083, h\u2084\u27e9 := c\u2081,\n    have c\u2081 := hc.axiom\u2080 \u27e8w, nonempty_of_mem h\u2084\u27e9,\n    let es : \u03c9.entity := \u27e8m, c\u2081.1.1, c\u2081.1.2\u27e9,\n    let ms : \u03c9.substance := \u27e8es,c\u2081.2\u27e9,\n    have c\u2082 : ms.necessary,\n      by_contradiction contra,\n      simp [nb, ms, -entity_ext_iff] at contra,\n      specialize hw es \u27e8ms.perfect, contra\u27e9,\n      unfold_coes at hw,\n      simp [es] at hw,\n      suffices : c.caused m w,\n        contradiction,\n      apply hw,\n      exact hc.axiom\u2083 \u27e8s, h\u2084\u27e9,\n    simp [ms,nb] at c\u2082,\n    rw c\u2082 at h\u2084,\n    replace h\u2084 : w \u2208 c.is_cause \u03c9.nbe.exists := \u27e8s, h\u2084\u27e9,\n    replace h\u2084 := nonempty_of_mem h\u2084,\n    replace h\u2084 := hc.axiom\u2085 \u03c9.nbe h\u2084,\n    simp [atheism, theism, nb, ext_iff, accident.inheres],\n    simp [-entity_ext_iff] at h\u2084,\n    obtain \u27e8e, h\u2084, h\u2085\u27e9 := h\u2084,\n    let a : \u03c9.accident, refine \u27e8e, _\u27e9,\n      exact imperfect_of_subsists_other h\u2084 h\u2085,\n    exact \u27e8a, h\u2084\u27e9,\n  end\n\ntheorem theological_hylemorphism : \u2200 (c' : \u03c9.cause) (mc : c'.mcause), -c'.uhylemorphism \u2229 mc.pis c \u21d2 c.epcs :=\n  begin\n    rintros c' mc w \u27e8h\u2081, h\u2082\u27e9,\n    simp [cause.uhylemorphism, mc, cause.epc] at h\u2081,\n    simp [set_of, has_mem.mem, set.mem] at h\u2081,\n    obtain \u27e8e, h\u2081, h\u2083, h\u2084, h\u2085\u27e9 := h\u2081,\n    have c : mc.immaterial e w := \u27e8h\u2084, h\u2085\u27e9,\n    specialize h\u2082 e c,\n    intro aux, clear aux,\n    refine \u27e8e.exists, e.existential, h\u2084, \u27e8_,h\u2082\u27e9\u27e9,\n    simp [nbe] at h\u2083,\n    exact \u27e8e.possible, h\u2083\u27e9,\n  end\n\n\n-- The argument from consubstantial causation.\ntheorem consub_cosmo : c.consubstantial \u2192 \u22c4(c.epsr \u2229 c.uncaused \u03c9.nbe) \u2192 \u03c9.theism :=\n  begin\n    simp [set.nonempty, cause.epsr],\n    intros h w psr unc,\n    dunfold theism substance.simple entity.simple,\n    -- suppose God had an accident\n    simp [substance.accidents, ext_iff, set.nonempty],\n    intro a,\n    by_contradiction contra,\n    -- then He should also have an accident 'a' \n    -- in the world w in which psr is valid\n    have : \u03c9.nb.composite := \u27e8a, contra\u27e9,\n    clear contra a,\n    obtain \u27e8a, contra, h\u2081\u27e9 := nb_acc_actual this w, clear this,\n    simp [substance.accidents] at contra,\n    -- this accident has a cause in w, call it 's'.\n    have : a.exists.contingent,\n      refine \u27e8a.possible, _\u27e9,\n      have := a.contingent,\n      simp [entity.contingent, nbe] at this,\n      simpa [event.necessary],\n    obtain \u27e8s, hs\u27e9 := psr a this h\u2081, clear this,\n    -- But this cause would in a sense have to be a\n    -- cause of something that is going on in the necessary\n    -- being.\n    have c\u2081 : c.causes s \u03c9.nbe.exists w,\n        refine h s a hs \u03c9.nbe _ (by simp [nbe]),\n        simp [has_equiv.equiv, entity.cosubstantial],\n        exact \u27e8\u03c9.nbe, self_subsist.mp \u03c9.nb.perfect, contra\u27e9,\n    -- However the necessary being admits no causes.\n    simp [cause.uncaused, cause.caused] at unc,\n    apply unc s, assumption,\n    -- Therefore the necessary being \n    -- is what we call God (E.Q.D.D.).\n  end\n\nvariable (\u03c9)\n\n\n/-- \"It is contingent that there contingent things. \"-/\ndef contingency_contingent : Prop := (\u2203 e : \u03c9.entity, e.contingent) \u2227 (Sup $ @entity.contingent \u03c9).contingent\n\n/-- It is it enough for it it to be contingent that there are\n    contingent entities for we to get full blown classical theism\n    without any extra auxiliary assumptions. -/\ntheorem ctheism_of_contingency : \u03c9.contingency_contingent \u2192 \u03c9.ctheism :=\n  begin\n    rintros \u27e8h\u2081, h\u2082\u27e9,\n    have c : set.nonempty entity.contingent := h\u2081,\n    simp [Sup, c, entity_Sup, nbe, ext_iff] at h\u2082,\n    -- clear c h\u2081,\n    obtain \u27e8w, hw\u27e9 := h\u2082,\n    replace hw : \u2200 e : \u03c9.entity, e.exists w \u2192 e.necessary,\n      intro e,\n      simp [has_Sup.Sup, c, entity_Sup] at hw,\n      specialize hw e,\n      contrapose,\n      exact hw,\n    use w, intros e\u2081 e\u2082 h\u2083 h\u2084,\n    have c\u2081 := hw e\u2081 h\u2083,\n    have c\u2082 := hw e\u2082 h\u2084,\n    clear hw h\u2083 h\u2084,\n    simp [entity.necessary] at *,\n    rw c\u2081, rw c\u2082,\n  end\n\n/-! # Aquinas's fourth way.\n    \n    The following proof is the best interpretation I could give of Aquinas's fourth way.\n    However, admittedly, two additional assumptions, \n    though probably acceptable to Saint Thomas, \n    were not present in the original argument.\n    The first could probably be replaced by any other premisse from which it \n    were possible to prove that if the necessary being's degree of perfection does \n    not vary across possible worlds then it can possibly exist alone or,\n    for a weaker `\u03c9.theism` argument, that it is simple.\n    This premisse seemed intuitive enough for its intended application.\n    The second might be even harder to replace, but it is even more\n    intuitive. Please verify the formal definitions of all referenced\n    concepts and lemmas before proposing an objection.\n\n    The original text of the Summa Theologica reads:\n\n      \"**Quarta via** sumitur ex gradibus qui in rebus inveniuntur.\n       Invenitur enim in rebus aliquid magis et minus bonum,\n       et verum, et nobile, et sic de aliis huiusmodi.\n       Sed magis et minus dicuntur de diversis secundum \n       quod appropinquant diversimode ad aliquid quod maxime est,\n       sicut magis calidum est, quod magis appropinquat maxime calido.\n       Est igitur aliquid quod est verissimum, et optimum, et nobilissimum,\n       et per consequens maxime ens, nam quae sunt maxime vera, sunt maxime entia,\n       ut dicitur II Metaphys. Quod autem dicitur maxime tale in aliquo genere, \n       est causa omnium quae sunt illius generis, sicut ignis, qui est maxime \n       calidus, est causa omnium calidorum, ut in eodem libro dicitur. \n       Ergo est aliquid quod omnibus entibus est causa esse, et bonitatis, \n       et cuiuslibet perfectionis, et hoc dicimus Deum.\"\n\n       Reference: (https://www.corpusthomisticum.org/sth1002.html)\n                  accessed in Jan 9, 2021.\n\n    A translation reads:\n\n      \"The **fourth way** is taken from the gradation to be found in things.\n      Among beings [rebus] there are some more and some less good, true, noble and the like.\n      But \"more\" and \"less\" are predicated of different things, according as they \n      resemble in their different ways something which is the maximum, as a thing is \n      said to be hotter according as it more nearly resembles that which is hottest; \n      so that there is something which is truest, something best, something noblest and,\n      consequently, something which is uttermost being; for those things that are greatest\n      in truth are greatest in being, as it is written in Metaph. ii.\n      Now the maximum in any genus is the cause of all in that genus; \n      as fire, which is the maximum heat, is the cause of all hot things. \n      Therefore there must also be something which is to all beings the cause of their being, goodness,\n      and every other perfection; and this we call God.\" \n        \n      Reference: (https://www.newadvent.org/summa/1002.htm#article3)\n                 accessed in Jan 9, 2021.\n    \n    My formalization depends on the following\n    assumptions and lemmas:\n    \n    0. (Analytical Premisse) There is a necessary being (`\u03c9.nbe`), though it might in principle be a mere abstraction\n        of the collection or multitude of all possible things/contingent things, i.e. the universe/cosmos.\n\n        0.1. Notice that the conclusion `\u03c9.ctheism` is incompatible with it being a mere \n            abstraction, and with it being the universe. See god.lean for details.\n        0.2. Indeed, to say that God exists (`\u03c9.theism`) is to say that the necessary being cannot be construed\n            as a well-behaved materialistic universe, as the material universe has accidents. While\n            to say that God has the attributes classically ascribed to Him (`\u03c9.ctheism`) is to \n            say that the necessary being cannot *in any way* be construed as the universe,\n            or as any collection of things, and that it cannot be taken to be a mere abstraction,\n            *no matter one's underlying intensional position on which entities are real*, provide only it is a consistent\n            position.\n        0.3. The necessary being is unique up to existential equivalence (i.e. *qua* extensional entity)\n            (`nbe_unique`).\n\n    1. (Premisse) There are degrees of perfection, or greatness of being, in things (`b : \u03c9.being`).\n\n    2. (Premisse) If `e\u2081 \u21d2 e\u2082` but not `e\u2082 \u21d2 e\u2081`, \n        then `e\u2082` is strictly more perfect than `e\u2081` (`b.axiom\u2082`).\n\n    3. (Minor Syllogistic Premisse) Some possible entity possibly attains the greatest\n        conceivable degree of perfection (`b.ecaused`).\n\n        3.1. We believe that in the original argument the notion of an **exemplary cause** is used\n             to justify this premisse. Refer to the section \"*The Intuition behind exemplary causes*\" \n             in essence.lean for details.\n        3.2. Supposing it were false, the necessary being could get arbitrarily close to the greatest\n            conceivable degree of perfection, but never be able to reach it (`nbe_mperfectible`, `b.axiom\u2083`).\n            This would be very strange, for at some possible world the difference between attaining and not\n            attaining the greatest possible perfection would be negligible; e.g. there would\n            be a possible world in which the necessary being would be 99.999999% perfect, but it\n            would never be 100%.\n        3.3. Alternatively we could also prove this premisse using `ecaused_of_phappy_and_wholesome` from:\n            3.3.1. It is possible for some possible entity to attain the \n                    greatest degree of perfection **that it can have** (`b.wholesome`).\n            3.3.2. No entity which attains the greatest degree of perfection that it can have, in a world `w`,\n                    can entail the existence (`\u21d2`) of an entity which does not attain the greatest degree \n                    of perfection that it can have, at `w` (`b.phappy`).\n        \n    4. (Theorem) If **(3)** and **(2)**, then the necessary being can possibly attain \n        the greatest conceivable degree of perfection (`exemplar_nbe_of_ecaused`).\n\n        4.1.1. For mere convenience we don't use `exemplar_nbe_of_ecaused` directly\n              in our proof, but both `abs_exemplary_intro` and `nbe_eq1_of_abs_exemplary` instead.\n        4.1.2. These lemmas have a dependency on `exemplar_nbe_of_ecaused`.\n        4.1.3. `nbe_eq1_of_abs_exemplary` also depends on `b.axiom\u2083`, but this axiom is a mere\n              convenience (allowing us to hardcode the number `1` in the proof)\n              and could be completely removed without prejudice to the proof.\n    \n    5. (Major Syllogistic Premisse) It is *de re* necessary, (or essential) for an entity \n        to attain the greatest conceivable degree of perfection (if it is possible for it to do so). \n        I.e. \"x attains the greatest conceivable degree of perfection\" \n        is a *de re* necessary predicate (`b.eexemplary`).\n\n    6. (Theorem) If **(5)**, then the necessary being necessarily attains the \n        greatest conceivable degree of perfection (`b.absolutely_exemplary`).\n\n    Given **(6)** we can already conclude that the necessary being is maximally perfect (`entity.mperfect`),\n    and that is probably the only conclusion that the original 4th way of Aquinas could manage to extract\n    on its own without further assumptions. However, in order to prove the stronger result `\u03c9.ctheism`, \n    which is what Aquinas would ultimately have wanted to prove, further premisses are needed. In\n    a sense, the proof of `\u03c9.ctheism` from **(6)** via additional premisses is a way to resolve\n    the so called \"gap problem\" of proving the classical properties of God from the god-like entity\n    obtained at the end of a typical proof of the existence of God. In Aquina's Summa Theologica,\n    this is done along the 26 first questions of the *prima pars*. For the purpose of solving this\n    problem, we then further introduce the following 2 assumptions:\n\n    7. (Premisse) The multitude, collection, or whole of things (substances) of a given \n       kind varies in perfection across possible worlds in proportion to the number of \n       entities of that kind which exists in each respective world (`b.composable`).\n\n       7.1. Strictly larger sets are strictly more perfect than the strictly smaller sets.\n       7.2. Collections are strictly more perfect than their proper parts, \n            though it may or may not be the case that they are more perfect \n            than the *sum* of the perfections of their parts. \n            We are not here committed to either.\n\n    8. (Premisse) Given any possible world `w`,\n        there must be some world `w'` which is either strictly\"larger\" (`>`) than `w`, \n        or strictly \"smaller\" (`<`) than `w` (`\u03c9.viable`).\n\n        8.1. What `w < w'` means is that every entity which exists at `w` also exists at `w'`, but not vice-versa.\n        8.2. See the definition of `\u03c9.viable`, as well as the definitions of `specialization_order`\n             and `specialization` (currently defined) at alexandroff.lean for further\n             details on what \"larger\" and \"smaller\" mean.\n\n    Since premisses **(1)**, **(3)**, **(5)** and **(7)** depend on an instance of `\u03c9.being`,\n    we pack them all together into the `\u03c9.participated : Prop` definition. It turns\n    out that it suffices to assume that it is logically consistent for there to be\n    a `b : \u03c9.being` with the aforementioned properties to prove `\u03c9.ctheism`.\n    The definition `\u03c9.participated` can then reduce to our 4 premisses as the\n    following example shows:\n    \n    example : \u03c9.participated = \u2203 b : \u03c9.being, b.composable \u2227 b.ecaused \u2227 b.eexemplary := \n      by simp [participated, being.participated]\n\n    Finally, we allow the proof to explain itself:\n\n-/\n\n-- WORK IN PROGRESS. ALMOST DONE.\n-- MOST OF IT TYPE CHECKS AND CAN BE PROFITABLY READ.\n-- INCOMPLETE PARTS ARE EXPLICIT. \n-- UNCOMMENT `\u03c9.participated` IN `god.lean` AND THIS TO FOLLOW THE ARGUMENT.\n-- /-- Aquinas's fourth way. -/\n-- theorem aquinas_fourth : \u03c9.participated \u2192 \u03c9.viable \u2192 \u03c9.ctheism :=\n--   begin\n--     intros participated viable,\n--     obtain \u27e8b, comp, h\u2081, h\u2082\u27e9 := participated,\n--     obtain \u27e8viable\u27e9 := viable,\n--     -- the following step already concludes the proof that\n--     -- the necessary being is maximally perfect (`entity.absolutely_exemplary`)\n--     -- which is what the original\n--     -- argument probably sough to show.\n--     -- check the lemma for the proof.\n--     have he := abs_exemplary_intro h\u2081 h\u2082,\n--     clear h\u2081 h\u2082,\n--     -- for simplicity, we ditch the \"absolutely examplary/maximally perfect\" conclusion\n--     -- and work with the hardcoded number `1`.\n--     replace he := nbe_eq1_of_abs_exemplary he,\n--     dunfold ctheism,\n--     -- suppose the classical theistic God doesn't exist.\n--     by_contradiction c,\n--     push_neg at c,\n--     -- then in any possible world there must be\n--     -- something contingent\n--     replace c : \u2200 w, \u2203 e : \u03c9.entity, e.contingent \u2227 e.exists w,\n--       intro w,\n--       specialize c w,\n--       obtain \u27e8e\u2081,e\u2082,he\u2081,he\u2082,neq\u27e9 := c,\n--       dunfold entity.contingent,\n--       simp [nbe],\n--       by_cases h : e\u2081.necessary;\n--       simp [nbe] at h, swap,\n--         exact \u27e8e\u2081,h, he\u2081\u27e9,\n--       rw \u2190h,\n--       replace neq := ne.symm neq,\n--       simp [entity_ext_iff] at neq,\n--       exact \u27e8e\u2082, neq, he\u2082\u27e9,\n--     -- it then also follows that the necessary being \n--     -- can be expressed as the supremum of the set of all\n--     -- contingent things. I.e. the necessary being's\n--     -- existence is logically equivalent to \"there exists something contingent\",\n--     -- so it can be thought of as the collection\n--     -- of contingent things, or \"the universe\".\n--     replace c : \u03c9.nbe = Sup entity.contingent := sorry,\n--     -- we can then specialize the compositionality of being\n--     -- to the set of contingent entities and to the necessary being:\n--     specialize comp (set_of $ @entity.contingent \u03c9) \u03c9.nbe,\n--     -- We derive an auxiliary result before proceeding,\n--     -- this was needed for purely bureocratic reasons.\n--     have c' : \u03c9.nbe \u2209 (set_of $ @entity.contingent \u03c9),\n--       simp [set_of, has_mem.mem, set.mem],\n--     -- We analyse the consequences of this for a single\n--     -- possible world `w`:\n--     obtain \u27e8w\u27e9 := \u03c9.wne,\n--     -- because the ontology is viable, this world could be\n--     -- made larger or smaller by some world `w'`.\n--     -- This generates 2 proof goals for us corresponding to the\n--     -- \"larger\" and \"smaller\" cases, respectively:\n--     specialize viable w,\n--     obtain \u27e8w', \u27e8hw'\u2081, hw'\u2082\u27e9|\u27e8hw'\u2081, hw'\u2082\u27e9\u27e9 := viable;\n--     push_neg at hw'\u2082; simp [specialization] at hw'\u2082;\n--     obtain \u27e8s, open_s, hs\u2081, hs\u2082\u27e9 := hw'\u2082,\n--     -- we then seek to prove that the degree of perfection of the\n--     -- necessary being varies across worlds.\n--     -- for the case w < w':\n--       specialize comp w w',\n--       swap,\n--     -- for the case w' < w:\n--     specialize comp w' w,\n--     all_goals {\n--       specialize comp c' c,\n--       specialize comp _, swap,\n--         constructor,\n--           rintros e \u27e8he\u2081,he\u2082\u27e9,\n--           simp [world.entities] at he\u2081,\n--           specialize hw'\u2081 e.exists e.existential he\u2081,\n--           exact \u27e8hw'\u2081, he\u2082\u27e9,\n--         simp [world.entities, has_subset.subset, set.subset],\n--         have ps : \u22c4s, \n--           simp [has_diamond.diamond],\n--           exact nonempty_of_mem hs\u2081,\n--         let es : \u03c9.entity := \u27e8s, open_s, ps\u27e9,\n--         use es,\n--         constructor, simp [es, hs\u2081],\n--         constructor, swap, simp [es, hs\u2082],\n--         simp [ontology.nbe, es],\n--         intro h, simp [ext_iff] at h,\n--     },\n--     specialize h w', contradiction,\n--     swap,\n--     specialize h w, contradiction,\n--     -- finished specializing comp.\n--     -- We have shown roughly that the perfection\n--     -- of the necessary being varies across worlds,\n--     -- now we need to show that, because the necessary\n--     -- being is maximally perfect, this is impossible\n--     all_goals {\n--       have h := he w,\n--       have h' := he w',\n--       clear he,\n--       rw h at comp,\n--       rw h' at comp,\n--       norm_num at comp,\n--     },\n--   end\n\n-- WORK IN PROGRESS\n-- /-- Using `being.axiom\u2084` we can also show \n--     composability + viability \u2192 nogap\u2082.\n--     meaning classical theism follows from these assumptions under\n--     the further assumption of theism. -/\n-- theorem aquinas_fourth_nogap\u2082 : \u03c9.composable \u2192 \u03c9.viable \u2192 \u03c9.nogap\u2082 := sorry\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/theology/natural/proofs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.014957083299985045, "lm_q1q2_score": 0.004747771289159048}}
{"text": "import GameServer.HashMapExtension\nimport GameServer.SingleValPersistentEnvExtension\n\n/-! # Environment extensions\n\nThe game framework stores almost all its game building data in environment extensions\ndefined in this file. MAyn of them are `SimplePersistentEnvExtension` but we also\nuse `HashMapExtension` and `SingleValPersistentEnvExtension`\n-/\n\n\nopen Lean\n\n/-! ## Messages -/\n\nstructure GoalMessageEntry where\n  ctx_size : Nat\n  normalized_goal : Expr\n  intro_nb : Nat \n  message : String\n  deriving Repr\n\n/-! ## Tactic documentation -/\n\nstructure TacticDocEntry where\n  name : Name\n  content : String\n  deriving ToJson, Repr\n\n/-- Environment extension for tactic documentation. -/\ninitialize tacticDocExt : SimplePersistentEnvExtension TacticDocEntry (Array TacticDocEntry) \u2190\n  registerSimplePersistentEnvExtension {\n    name := `tactic_doc\n    addEntryFn := Array.push\n    addImportedFn := Array.concatMap id\n  }\n\nopen Elab Command in\n/-- Print a registered tactic doc for debugging purposes. -/\nelab \"#print_tactic_doc\" : command => do \n  for entry in tacticDocExt.getState (\u2190 getEnv) do\n    dbg_trace \"{entry.name} : {entry.content}\"\n\nstructure TacticSetEntry where\n  name : Name\n  tactics : Array TacticDocEntry\n  deriving ToJson, Repr\n\n/-- Environment extension for tactic sets. -/\ninitialize tacticSetExt : SimplePersistentEnvExtension TacticSetEntry (Array TacticSetEntry) \u2190\n  registerSimplePersistentEnvExtension {\n    name := `tactic_set\n    addEntryFn := Array.push\n    addImportedFn := Array.concatMap id\n  }\n\nopen Elab Command in\n/-- Print all registered tactic sets for debugging purposes. -/\nelab \"#print_tactic_set\" : command => do \n  for entry in tacticSetExt.getState (\u2190 getEnv) do\n    dbg_trace \"{entry.name} : {entry.tactics.map TacticDocEntry.name}\"\n\n/-! ## Lemma documentation -/\n\nstructure LemmaDocEntry where\n  name : Name\n  userName : Name\n  category : String\n  content : String\n  deriving ToJson, Repr\n\n/-- Environment extension for lemma documentation. -/\ninitialize lemmaDocExt : SimplePersistentEnvExtension LemmaDocEntry (Array LemmaDocEntry) \u2190\n  registerSimplePersistentEnvExtension {\n    name := `lemma_doc\n    addEntryFn := Array.push\n    addImportedFn := Array.concatMap id\n  }\n\nopen Elab Command in\n/-- Print a lemma doc for debugging purposes. -/\nelab \"#print_lemma_doc\" : command => do \n  for entry in lemmaDocExt.getState (\u2190 getEnv) do\n    dbg_trace \"{entry.userName} ({entry.name}) in {entry.category}: {entry.content}\"\n\nstructure LemmaSetEntry where\n  name : Name\n  title : String\n  lemmas : Array LemmaDocEntry\n  deriving ToJson, Repr\n\n/-- Environment extension for lemma sets. -/\ninitialize lemmaSetExt : SimplePersistentEnvExtension LemmaSetEntry (Array LemmaSetEntry) \u2190\n  registerSimplePersistentEnvExtension {\n    name := `lemma_set\n    addEntryFn := Array.push\n    addImportedFn := Array.concatMap id\n  }\n\nopen Elab Command in\n/-- Print all registered lemma sets for debugging purposes. -/\nelab \"#print_lemma_set\" : command => do \n  for entry in lemmaSetExt.getState (\u2190 getEnv) do\n    dbg_trace \"{entry.name} : {entry.lemmas.map LemmaDocEntry.name}\"\n\n/-! ## Game -/\n\nstructure Game where\n  name : Name\n  title : String := \"\"\n  introduction : String := \"\"\n  conclusion : String := \"\"\n  authors : List String := []\n  nb_levels : Nat := 0\n  deriving Repr, Inhabited, ToJson\n\ninitialize gameExt : SingleValPersistentEnvExtension Game \u2190 registerSingleValPersistentEnvExtension `gameExt Game\n\n/-! ## Levels -/\n\n/- Register a (non-persistent) environment extension to hold the current level number. -/\ninitialize curLevelExt : EnvExtension Nat \u2190 registerEnvExtension (pure 0)\n\nvariable {m: Type \u2192 Type} [Monad m] [MonadEnv m]\n\ndef setCurLevelIdx (lvl : Nat) :  m Unit := \n  modifyEnv (curLevelExt.setState \u00b7 lvl)\n\ndef getCurLevelIdx :  m Nat := do\n  return curLevelExt.getState (\u2190 getEnv)\n\nstructure GameLevel where\n  index: Nat\n  title: String := default\n  introduction: String := default\n  conclusion: String := default\n  tactics: Array TacticDocEntry := default\n  lemmas: Array LemmaDocEntry := default\n  messages: Array GoalMessageEntry := default\n  goal : Expr := default\n  intro_nb : Nat := default\n  deriving Inhabited, Repr\n\ninitialize levelsExt : HashMapExtension Nat GameLevel \u2190 mkHashMapExtension `levels Nat GameLevel\n\ndef getCurLevel [MonadError m] :  m GameLevel := do\n  let idx \u2190 getCurLevelIdx\n  match (\u2190 levelsExt.find? idx) with\n  | some level => return level\n  | none => throwError \"Couldn't find level {idx}\"\n\n", "meta": {"author": "PatrickMassot", "repo": "lean4-game-server", "sha": "a193c37ca99386cdd4f01855c80b1a0fa0a4a3c9", "save_path": "github-repos/lean/PatrickMassot-lean4-game-server", "path": "github-repos/lean/PatrickMassot-lean4-game-server/lean4-game-server-a193c37ca99386cdd4f01855c80b1a0fa0a4a3c9/GameServer/EnvExtensions.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421300186801369, "lm_q2_score": 0.03789242608636187, "lm_q1q2_score": 0.004706731992248837}}
{"text": "example : True := by rw (config := non / sense) []\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/1576.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.22541661583507672, "lm_q2_score": 0.020645928554817804, "lm_q1q2_score": 0.004653935345599805}}
{"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\nopen Lean Parser.Term Macro\n\n/-\nThis adds support for structure instance spread syntax.\n\n```lean\ninstance : Foo \u03b1 where\n  __ := instSomething -- include fields from `instSomething`\n\nexample : Foo \u03b1 := {\n  __ := instSomething -- include fields from `instSomething`\n}\n```\n-/\n\nmacro_rules\n| `({ $[$srcs,* with]? $[$fields $[,]?]* $[: $ty?]? }) => do\n    let mut spreads := #[]\n    let mut newFields := #[]\n\n    for field in fields do\n      match field with\n        | `(structInstField| $name:ident := $arg) =>\n          if name.getId.eraseMacroScopes == `__ then do\n            spreads := spreads.push arg\n          else\n            newFields := newFields.push field\n        | `(structInstFieldAbbrev| $name:ident) =>\n          newFields := newFields.push field\n        | _ =>\n          throwUnsupported\n\n    if spreads.isEmpty then throwUnsupported\n\n    let srcs := (srcs.map (\u00b7.1)).getD #[] ++ spreads\n    `({ $srcs,* with $[$newFields,]* $[: $ty?]? })\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/Spread.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846180123433285, "lm_q2_score": 0.03308597731611235, "lm_q1q2_score": 0.004581144014787194}}
{"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 \u2192 bool := \u03bb n, n \u2264 10000 in\nlet validate_float_frac : native.float \u2192 bool := \u03bb k, 0 \u2264 k \u2227 k \u2264 1 in\nlet validate_and_return {\u03b1} (pred : \u03b1 \u2192 bool) : \u03b1 \u2192 tactic \u03b1 := \u03bb a, ((guard $ pred a) *> pure a <|> tactic.fail \"VALIDATE_AND_RETURN FAILED\") in\nlet validate_optional_and_return {\u03b1} (pred : \u03b1 \u2192 bool) : option \u03b1 \u2192 tactic (option \u03b1) := \u03bb 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 \u2192 tactic json := \u03bb req, match req with\n| \u27e8prompt, max_tokens, temperature, nbest, beam\u27e9 := do\n  max_tokens \u2190 validate_and_return validate_max_tokens max_tokens,\n  temperature \u2190 validate_and_return validate_float_frac temperature,\n  nbest \u2190 validate_and_return (\u03bb x, 0 \u2264 x \u2227 x \u2264 (50 : int)) /- don't go overboard with the candidates -/ nbest,\n  beam \u2190 validate_and_return (\u03bb x, 0 \u2264 x \u2227 x \u2264 (50 : int)) /- don't go overboard with the candidates -/ beam,\n\n  let pre_kvs : list (string \u00d7 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 (\u03bb \u27e8k,mv\u27e9, prod.mk k <$> mv)\nend\nin \u27e8fn\u27e9\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 \u2192 io (io.process.spawn_args)\n| req@\u27e8prompt, max_tokens, temperature, nbest, beam\u27e9 := do\nserialized_req \u2190 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 \u2192 tactic CompletionRequest := \u03bb ts, do {\n  ts_str \u2190 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) \u2190 response_msg.lookup \"choices\" | none,\n      /- `choices` is a list of {text: ..., index: ..., logprobs: ..., finish_reason: ...}-/\n      texts \u2190 choices.mmap (\u03bb choice, choice.lookup \"text\"),\n      pure texts\n  }) in\n\nlet fn : CompletionRequest \u2192 io json := \u03bb req, do {\n  proc_cmds \u2190 req.to_cmd entry_pt model_path data_path,\n  response_raw \u2190 io.cmd proc_cmds,\n  io.put_str_ln' format!\"RAW RESPONSE: {response_raw}\",\n  response_msg \u2190 (lift_option $ json.parse response_raw) | io.fail' format!\"[fairseq_api] JSON PARSE FAILED {response_raw}\",\n  (do predictions \u2190 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 \u27e8fn\u27e9\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      (\u03bb  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      (\u03bb  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 : \u2115) (m : \u2115) : 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 \u2192 String\n  | none => \"\u22a2\"\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 \u2192 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 : \u2115) : 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  \u27e8fun 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 => \"\u2190\" ++ toString e\u27e9\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 \u2190\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 \u2190 e.get_structure_instance_info\n  let fs \u2190\n    zipWithM\n        (fun n v => do\n          let v \u2190 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 \u00d7 String \u00d7 List simp_arg_type \u00d7 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 \u2192 format\n  | [] => \"\"\n  | args => (\u00b7 ++ \u00b7) \" \" <| 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 \u2190 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 \u2192 tactic (simp_config_ext \u00d7 format)\n  | none => pure ({ }, \"\")\n  | some cfg => do\n    let e \u2190 to_expr ``(($(cfg) : simp_config_ext))\n    let fmt \u2190 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 \u2192 tactic (DsimpConfig \u00d7 format)\n  | none => pure ({ }, \"\")\n  | some cfg => do\n    let e \u2190 to_expr ``(($(cfg) : simp_config_ext))\n    let fmt \u2190 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 \u2190 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 \u2192 List simp_arg_type \u2192 tactic Unit)\n    (args : List simp_arg_type) (pr : proof_state) :\n    List simp_arg_type \u2192\n      List simp_arg_type \u2192 List simp_arg_type \u2192 tactic (List simp_arg_type \u00d7 List simp_arg_type)\n  | [], ys, ds => pure (ys, ds)\n  | x :: xs, ys, ds => do\n    let b \u2190 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 \u2192 List simp_arg_type \u2192 tactic Unit)\n    (user_args simp_args : List simp_arg_type) : tactic (List simp_arg_type) := do\n  let some s \u2190 get_proof_state_after (tac false (user_args ++ simp_args))\n  let (simp_args', _) \u2190 filter_simp_set_aux tac user_args s simp_args [] []\n  let (user_args', ds) \u2190 filter_simp_set_aux tac simp_args' s user_args [] []\n  when (is_trace_enabled_for `squeeze.deleted = tt \u2227 \u00acds)\n      (\u2190 do\n        dbg_trace \"deleting provided arguments {\u2190 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 \u2190 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 : \u2200 (no_dflt : Bool) (args : List simp_arg_type), tactic Unit)\n    (mk_suggestion : List simp_arg_type \u2192 tactic Unit) : tactic Unit := do\n  let v \u2190 target >>= mk_meta_var\n  let args \u2190\n    if slow then do\n        let simp_set \u2190 attribute.get_instances `simp\n        let simp_set \u2190 simp_set.filterM <| has_attribute' `_refl_lemma\n        let simp_set \u2190 simp_set.mapM <| resolve_name' >=> pure \u2218 simp_arg_type.expr\n        pure <| args ++ simp_set\n      else pure args\n  let g \u2190\n    retrieve do\n        let g \u2190 main_goal\n        tac no_dflt args\n        instantiate_mvars g\n  let vs := g.list_constant'\n  let vs \u2190 vs.filterM is_simp_lemma\n  let vs \u2190 vs.mapM strip_prefix\n  let vs \u2190 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 {\u03b1 \u03b2} (xs ys : list \u03b1) (f : \u03b1 \u2192 \u03b2) :\n  (xs ++ ys.tail).map f = xs.map f \u2227 (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 \u2190 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 \u2190 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 \u27e8p, suggs\u27e9 => do\n          let \u27e8pre, _, post\u27e9 := suggs\n          let suggs : List (List simp_arg_type) := suggs <| Prod.fst \u2218 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) \u2190 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) \u2190 parse_config cfg\n  let tgt' \u2190\n    traverse\n        (fun t => do\n          let t \u2190 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) \u2190 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": "/-\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# Macro for spread syntax (`__ := instSomething`) in structures.\n-/\n\nopen Lean Parser.Term Macro\n\n/-\nThis adds support for structure instance spread syntax.\n\n```lean\ninstance : Foo \u03b1 where\n  __ := instSomething -- include fields from `instSomething`\n\nexample : Foo \u03b1 := {\n  __ := instSomething -- include fields from `instSomething`\n}\n```\n-/\n\nmacro_rules\n| `({ $[$srcs,* with]? $[$fields],* $[: $ty?]? }) => do\n    let mut spreads := #[]\n    let mut newFields := #[]\n\n    for field in fields do\n      match field.1 with\n        | `(structInstField| $name:ident := $arg) =>\n          if name.getId.eraseMacroScopes == `__ then do\n            spreads := spreads.push arg\n          else\n            newFields := newFields.push field\n        | `(structInstFieldAbbrev| $_:ident) =>\n          newFields := newFields.push field\n        | _ =>\n          throwUnsupported\n\n    if spreads.isEmpty then throwUnsupported\n\n    let srcs := (srcs.map (\u00b7.getElems)).getD {} ++ spreads\n    `({ $srcs,* with $[$newFields],* $[: $ty?]? })\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/Spread.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1127953943533099, "lm_q2_score": 0.039638843213543364, "lm_q1q2_score": 0.004471078951980646}}
{"text": "import Std\nimport LeanSAT\n\ndef IO.asTaskTimeout (time : Nat) (t : IO \u03b1) : IO (Except Unit \u03b1) :=\n  show IO _ from do\n  let task : Task (Except IO.Error (Except Unit \u03b1)) \u2190\n    IO.asTask (do\n      let a \u2190 t\n      return .ok a)\n  let sleep : Task (Except IO.Error (Except Unit \u03b1)) \u2190\n    IO.asTask (do\n      IO.sleep time.toUInt32\n      return .error ())\n  let res \u2190 IO.waitAny [task, sleep]\n  let res \u2190 IO.ofExcept res\n  return res\n\n \ndef Log (m) [Monad m] [MonadLiftT IO m] (\u03b1) := IO.FS.Handle \u2192 m \u03b1\n\nnamespace Log\nvariable {m} [Monad m] [MonadLiftT IO m]\n\ninstance : Monad (Log m) where\n  pure a := fun _ => pure a\n  bind la f := fun logfile =>\n    bind (la logfile) (fun a => f a logfile)\n\ninstance : MonadLift m (Log m) where\n  monadLift ma := fun _ => ma\n\nprivate def write (type : String) (s : String) : Log m Unit :=\n  fun logfile => do\n  let time \u2190 (IO.monoMsNow : IO _)\n  let ms := toString <| time % 1000\n  logfile.putStrLn s!\"[{time / 1000}.{\"\".pushn '0' (3-ms.length) ++ ms}] {type}: {s}\"\n  logfile.flush\n\ndef info : String \u2192 Log m Unit := write \"INFO\"\ndef warn : String \u2192 Log m Unit := write \"WARN\"\ndef error : String \u2192 Log m Unit := write \"ERROR\"\n\ndef run (logfile : IO.FS.Handle) (la : Log m \u03b1) : m \u03b1 := la logfile\ndef getHandle : Log m IO.FS.Handle := \u03bb path => pure path\n\ninstance [Monad m] [Monad n] [MonadLift m n] : MonadLift (Log m) (Log n) where\n  monadLift mla := fun handle => liftM <| Log.run handle mla\n\ninstance [Monad m] [ForIn m \u03c1 \u03b1] : ForIn (Log m) \u03c1 \u03b1 where\n  forIn r acc f := fun handle => ForIn.forIn r acc (f \u00b7 \u00b7 handle)\n\nend Log\n\n\ndef LeanSAT.Encode.EncCNF.State.cleanup : State \u2192 State \u00d7 (Var \u2192 Var)\n| {nextVar, clauses, names, varCtx} =>\n  let usedVars :=\n    clauses.foldl\n      (fun set clause =>\n        clause.lits.foldl\n          (fun set lit =>\n            set.insert lit.var ())\n          set)\n      (Std.HashMap.empty)\n\n  let (varRemap, namesRemap, nextVarRemap) := Id.run do\n    let mut varRemap : Std.HashMap Var Var := .empty\n    let mut namesRemap : Std.HashMap Var String := .empty\n    let mut nextVarRemap := 0\n    for i in [0:nextVar] do\n      if usedVars.contains i then\n        varRemap := varRemap.insert i nextVarRemap\n        if names.contains i then\n          namesRemap := namesRemap.insert nextVarRemap (names.find! i)\n        nextVarRemap := nextVarRemap.succ\n    return (varRemap, namesRemap, nextVarRemap)\n\n  let clausesRemap := clauses.map (\u27e8\u00b7.lits.map (fun\n    | .pos v => .pos <| varRemap.find! v\n    | .neg v => .neg <| varRemap.find! v\n    )\u27e9)\n\n  ( { nextVar := nextVarRemap\n      names := namesRemap\n      clauses := clausesRemap\n      varCtx := varCtx}\n  , varRemap.find! )\n\ndef List.pmap {p : \u03b1 \u2192 Prop} (f : \u2200 a, p a \u2192 \u03b2) : \u2200 l : List \u03b1, (\u2200 a \u2208 l, p a) \u2192 List \u03b2\n  | [], _ => []\n  | a :: l, H => f a (H a (List.Mem.head _)) :: pmap f l (fun a h => H a (List.Mem.tail _ h))\n\ndef List.attach (l : List \u03b1) : List { x // x \u2208 l } :=\n  pmap Subtype.mk l fun _ => id\n\n@[simp] theorem List.length_pmap : List.length (List.pmap f L h) = List.length L := by\n  induction L with\n  | nil => simp [pmap]\n  | cons x xs ih => simp [pmap, ih]\n\ndef RandomM (\u03c4) := \u2200 g, RandomGen g \u2192 StateM g \u03c4\n\nnamespace RandomM\n\ninstance [RandomGen g] : Monad RandomM where\n  pure a    := \u03bb _ _ => pure a\n  bind r f  := \u03bb G R => bind (r G R) (fun a => f a G R)\n\ndef run [R : RandomGen G] (g : G) (r : RandomM \u03c4) : \u03c4 \u00d7 G :=\n  StateT.run (r G R) g\n\ninstance : MonadLift RandomM IO where\n  monadLift r := do\n    let gen \u2190 IO.stdGenRef.get\n    let (res, seed) := run gen r\n    IO.stdGenRef.set seed\n    return res\n\n@[inline]\ndef randIndep (p1 : RandomM \u03b1) : RandomM \u03b1 :=\n  \u03bb _ R r => let (r1,r2) := RandomGen.split r\n             let (a,_) := p1 _ R r1\n             (a,r2)\n\n@[inline]\ndef randFin (n : Nat) (hn : n > 0 := by trivial) : RandomM (Fin n) :=\n  \u03bb G R g =>\n    let (res, g) := @randNat G R g 0 n.pred\n    if h : res < n then\n      (\u27e8res, h\u27e9, g)\n    else\n      have : Inhabited (Fin n \u00d7 G) := \u27e8\u27e8\u27e80,hn\u27e9, g\u27e9\u27e9\n      panic! s!\"randFin wrong: n={n}, res={res}\"\n\n/- Generate a random permutation of the list.\nImplementation is quadratic in length of L. -/\ndef randPerm (L : List \u03b1) : RandomM (List \u03b1) :=\n  randPermTR L [] 0\nwhere randPermTR (L acc n) := do\n  match L with\n  | [] => return acc\n  | x::xs =>\n    let idx \u2190 RandomM.randFin (n+1) (Nat.zero_lt_succ _)\n    let acc' := acc.insertNth idx x\n    randPermTR xs acc' (n+1)\n\nend RandomM\n\ndef List.parMap (jobs : List \u03b1) (f : \u03b1 \u2192 IO \u03b2) : IO (List \u03b2) := do\n  let tasks \u2190 jobs.mapM (IO.asTask <| f \u00b7)\n  let res \u2190 IO.mapTasks (\u00b7.mapM IO.ofExcept) tasks\n  return \u2190 IO.ofExcept res.get\n\ndef List.removeOne : List \u03b1 \u2192 List (\u03b1 \u00d7 List \u03b1)\n| [] => []\n| x::xs => (x,xs) :: (xs.removeOne.map (fun (x',xs') => (x', x::xs')))\n\ndef List.removeOne' : (L : List \u03b1) \u2192 List (\u03b1 \u00d7 { L' : List \u03b1 // L'.length < L.length })\n| [] => []\n| x::xs => (x,\u27e8xs, by simp\u27e9) :: (xs.removeOne'.map (fun (x',\u27e8xs',h\u27e9) => (x', \u27e8x::xs', Nat.succ_lt_succ h\u27e9)))\n\ndef List.minBy [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] (f : \u03b1 \u2192 \u03b2) (L : List \u03b1) : Option \u03b1 :=\n  L.foldl (fun o a =>\n    let b := f a\n    match o with\n    | none => some (a, f a)\n    | some (a',b') =>\n      if b < b' then\n        some (a,b)\n      else\n        some (a',b')) none\n  |>.map (\u00b7.1)\n\ndef List.maxBy [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] (f : \u03b1 \u2192 \u03b2) (L : List \u03b1) : Option \u03b1 :=\n  L.foldl (fun o a =>\n    let b := f a\n    match o with\n    | none => some (a, b)\n    | some (a',b') =>\n      if b < b' then\n        some (a',b')\n      else\n        some (a,b)) none\n  |>.map (\u00b7.1)\n\n@[simp]\ntheorem List.maxBy_eq_none [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] : List.maxBy (\u03b2 := \u03b2) f L = none \u2194 L = [] := by\n  simp [List.maxBy]\n  cases L <;> simp\n  next hd tl =>\n  induction tl generalizing hd\n  . simp\n  . simp; split <;> simp [*]\n\ndef List.maxByMap [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] (f : \u03b1 \u2192 \u03b1' \u00d7 \u03b2) (L : List \u03b1) : Option (\u03b1 \u00d7 \u03b1') :=\n  L.foldl (fun o a =>\n    let b := f a\n    match o with\n    | none => some (a, b)\n    | some (a',b') =>\n      if b.2 < b'.2 then\n        some (a',b')\n      else\n        some (a,b)) none\n  |>.map (fun (a,a',_) => (a,a'))\n\n@[simp]\ntheorem List.maxByMap_eq_none [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] : List.maxByMap (\u03b2 := \u03b2) f L = none \u2194 L = [] := by\n  simp [List.maxByMap]\n  cases L <;> simp\n  next hd tl =>\n  induction tl generalizing hd\n  . simp\n  . simp; split <;> simp [*]\n\n@[simp]\ntheorem List.maxByMap_nil [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] : List.maxByMap (\u03b2 := \u03b2) f [] = none := by\n  simp [List.maxByMap]\n\n\n@[simp]\ntheorem List.isSome_maxByMap [LT \u03b2] [DecidableRel (@LT.lt \u03b2 _)] : Option.isSome (List.maxByMap (\u03b2 := \u03b2) f L) = !L.isEmpty := by\n  apply Eq.symm; unfold Option.isSome\n  split <;> cases L <;> simp [isEmpty] at *\n\n\ntheorem List.fins.finsAux_eq_append : List.fins.finsAux n i h acc = List.fins.finsAux n i h [] ++ acc := by\n  induction i generalizing acc with\n  | zero => unfold finsAux; simp\n  | succ i ih =>\n    unfold finsAux; rw [ih]; conv => rhs; rw [ih]\n    simp\n\n\ntheorem List.fins_succ (n : Nat) : List.fins n.succ = 0 :: (List.fins n |>.map (\u00b7.succ)) := by\n  unfold fins\n  suffices \u2200 i (h : i \u2264 n),\n    fins.finsAux (Nat.succ n) (Nat.succ i) (Nat.succ_le_succ h) []\n    = 0 :: (fins.finsAux n i h [] |>.map (\u00b7.succ))\n    from this n (Nat.le_refl _)\n  intro i h\n  induction i with\n  | zero =>\n    unfold fins.finsAux; unfold fins.finsAux; rfl\n  | succ i ih =>\n    conv => lhs; unfold fins.finsAux; rw [fins.finsAux_eq_append]\n    conv => rhs; unfold fins.finsAux; rw [fins.finsAux_eq_append]\n    rw [ih]\n    simp [Fin.succ]\n    apply Nat.le_of_lt h\n", "meta": {"author": "JamesGallicchio", "repo": "eternity2", "sha": "dad53d56336aea60b0a1151c3a91676efc4e51ad", "save_path": "github-repos/lean/JamesGallicchio-eternity2", "path": "github-repos/lean/JamesGallicchio-eternity2/eternity2-dad53d56336aea60b0a1151c3a91676efc4e51ad/lean/Eternity2/AuxDefs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13296422989056966, "lm_q2_score": 0.03358950323155241, "lm_q1q2_score": 0.004466202429590167}}
{"text": "import ..flocq\n\n/- Architecture-dependent parameters for x86 in 32-bit mode -/\n\nnamespace archi\nopen flocq\n\ndef ptr64 : bool := ff\n\ndef big_endian : bool := ff\n\ndef align_int64 := 4\ndef align_float64 := 4\n\ndef splitlong := bnot ptr64\n\nlemma splitlong_ptr32 : splitlong = tt \u2192 ptr64 = ff := \u03bb_, rfl\n\ndef default_pl_64 : bool \u00d7 nan_pl 53 :=\n(ff, word.repr (2^51))\n  \ndef choose_binop_pl_64 (s1 : bool) (pl1 : nan_pl 53) (s2 : bool) (pl2 : nan_pl 53) : bool :=\nff /- always choose first NaN -/\n\ndef default_pl_32 : bool \u00d7 nan_pl 24 :=\n(ff,  word.repr (2^22))\n  \ndef choose_binop_pl_32 (s1 : bool) (pl1 : nan_pl 24) (s2 : bool) (pl2 : nan_pl 24) : bool :=\nff /- always choose first NaN -/\n   \ndef float_of_single_preserves_sNaN := ff\n\nend archi", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/archi/x86_32.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2450850241603249, "lm_q2_score": 0.01798621335072534, "lm_q1q2_score": 0.004408151533615278}}
{"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.Parser.Term\nimport Lean.Meta.Closure\nimport Lean.Meta.Check\nimport Lean.Meta.Transform\nimport Lean.PrettyPrinter.Delaborator.Options\nimport Lean.Elab.Command\nimport Lean.Elab.Match\nimport Lean.Elab.DefView\nimport Lean.Elab.Deriving.Basic\nimport Lean.Elab.PreDefinition.Main\nimport Lean.Elab.DeclarationRange\n\nnamespace Lean.Elab\nopen Lean.Parser.Term\n\n/-- `DefView` after elaborating the header. -/\nstructure DefViewElabHeader where\n  ref           : Syntax\n  modifiers     : Modifiers\n  /-- Stores whether this is the header of a definition, theorem, ... -/\n  kind          : DefKind\n  /--\n    Short name. Recall that all declarations in Lean 4 are potentially recursive. We use `shortDeclName` to refer\n    to them at `valueStx`, and other declarations in the same mutual block. -/\n  shortDeclName : Name\n  /-- Full name for this declaration. This is the name that will be added to the `Environment`. -/\n  declName      : Name\n  /-- Universe level parameter names explicitly provided by the user. -/\n  levelNames    : List Name\n  /-- Syntax objects for the binders occurring befor `:`, we use them to populate the `InfoTree` when elaborating `valueStx`. -/\n  binderIds     : Array Syntax\n  /-- Number of parameters before `:`, it also includes auto-implicit parameters automatically added by Lean. -/\n  numParams     : Nat\n  /-- Type including parameters. -/\n  type          : Expr\n  /-- `Syntax` object the body/value of the definition. -/\n  valueStx      : Syntax\n  deriving Inhabited\n\nnamespace Term\nopen Meta\n\nprivate def checkModifiers (m\u2081 m\u2082 : Modifiers) : TermElabM Unit := do\n  unless m\u2081.isUnsafe == m\u2082.isUnsafe do\n    throwError \"cannot mix unsafe and safe definitions\"\n  unless m\u2081.isNoncomputable == m\u2082.isNoncomputable do\n    throwError \"cannot mix computable and non-computable definitions\"\n  unless m\u2081.isPartial == m\u2082.isPartial do\n    throwError \"cannot mix partial and non-partial definitions\"\n\nprivate def checkKinds (k\u2081 k\u2082 : DefKind) : TermElabM Unit := do\n  unless k\u2081.isExample == k\u2082.isExample do\n    throwError \"cannot mix examples and definitions\" -- Reason: we should discard examples\n  unless k\u2081.isTheorem == k\u2082.isTheorem do\n    throwError \"cannot mix theorems and definitions\" -- Reason: we will eventually elaborate theorems in `Task`s.\n\nprivate def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do\n  if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then\n    throwError \"'unsafe' theorems are not allowed\"\n  if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then\n    throwError \"'partial' theorems are not allowed, 'partial' is a code generation directive\"\n  if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then\n    throwError \"'theorem' subsumes 'noncomputable', code is not generated for theorems\"\n  if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then\n    throwError \"'noncomputable unsafe' is not allowed\"\n  if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then\n    throwError \"'noncomputable partial' is not allowed\"\n  if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then\n    throwError \"'unsafe' subsumes 'partial'\"\n  if h : 0 < prevHeaders.size then\n    let firstHeader := prevHeaders.get \u27e80, h\u27e9\n    try\n      unless newHeader.levelNames == firstHeader.levelNames do\n        throwError \"universe parameters mismatch\"\n      checkModifiers newHeader.modifiers firstHeader.modifiers\n      checkKinds newHeader.kind firstHeader.kind\n    catch\n       | .error ref msg => throw (.error ref m!\"invalid mutually recursive definitions, {msg}\")\n       | ex => throw ex\n  else\n    pure ()\n\nprivate def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit :=\n  registerCustomErrorIfMVar type ref \"failed to infer definition type\"\n\n/--\n  Return `some [b, c]` if the given `views` are representing a declaration of the form\n  ```\n  opaque a b c : Nat\n  ```  -/\nprivate def isMultiConstant? (views : Array DefView) : Option (List Name) :=\n  if views.size == 1 &&\n     views[0]!.kind == .opaque &&\n     views[0]!.binders.getArgs.size > 0 &&\n     views[0]!.binders.getArgs.all (\u00b7.isIdent) then\n    some (views[0]!.binders.getArgs.toList.map (\u00b7.getId))\n  else\n    none\n\nprivate def getPendindMVarErrorMessage (views : Array DefView) : String :=\n  match isMultiConstant? views with\n  | some ids =>\n    let idsStr := \", \".intercalate <| ids.map fun id => s!\"`{id}`\"\n    let paramsStr := \", \".intercalate <| ids.map fun id => s!\"`({id} : _)`\"\n    s!\"\\nrecall that you cannot declare multiple constants in a single declaration. The identifier(s) {idsStr} are being interpreted as parameters {paramsStr}\"\n  | none =>\n    \"\\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed\"\n\n/--\nConvert terms of the form `OfNat <type> (OfNat.ofNat Nat <num> ..)` into `OfNat <type> <num>`.\nWe use this method on instance declaration types.\nThe motivation is to address a recurrent mistake when users forget to use `nat_lit` when declaring `OfNat` instances.\nSee issues #1389 and #875\n-/\nprivate def cleanupOfNat (type : Expr) : MetaM Expr := do\n  Meta.transform type fun e => do\n    if !e.isAppOfArity ``OfNat 2 then return .continue\n    let arg \u2190 instantiateMVars e.appArg!\n    if !arg.isAppOfArity ``OfNat.ofNat 3 then return .continue\n    let argArgs := arg.getAppArgs\n    if !argArgs[0]!.isConstOf ``Nat then return .continue\n    let eNew := mkApp e.appFn! argArgs[1]!\n    return .done eNew\n\n/-- Elaborate only the declaration headers. We have to elaborate the headers first because we support mutually recursive declarations in Lean 4. -/\nprivate def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do\n  let expandedDeclIds \u2190 views.mapM fun view => withRef view.ref do\n    Term.expandDeclId (\u2190 getCurrNamespace) (\u2190 getLevelNames) view.declId view.modifiers\n  withAutoBoundImplicitForbiddenPred (fun n => expandedDeclIds.any (\u00b7.shortName == n)) do\n    let mut headers := #[]\n    for view in views, \u27e8shortDeclName, declName, levelNames\u27e9 in expandedDeclIds do\n      let newHeader \u2190 withRef view.ref do\n        addDeclarationRanges declName view.ref\n        applyAttributesAt declName view.modifiers.attrs .beforeElaboration\n        withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <|\n          elabBindersEx view.binders.getArgs fun xs => do\n            let refForElabFunType := view.value\n            let mut type \u2190 match view.type? with\n              | some typeStx =>\n                let type \u2190 elabType typeStx\n                registerFailedToInferDefTypeInfo type typeStx\n                pure type\n              | none =>\n                let hole := mkHole refForElabFunType\n                let type \u2190 elabType hole\n                trace[Elab.definition] \">> type: {type}\\n{type.mvarId!}\"\n                registerFailedToInferDefTypeInfo type refForElabFunType\n                pure type\n            Term.synthesizeSyntheticMVarsNoPostponing\n            if view.isInstance then\n              type \u2190 cleanupOfNat type\n            let (binderIds, xs) := xs.unzip\n            -- TODO: add forbidden predicate using `shortDeclName` from `views`\n            let xs \u2190 addAutoBoundImplicits xs\n            type \u2190 mkForallFVars' xs type\n            type \u2190 instantiateMVars type\n            let levelNames \u2190 getLevelNames\n            if view.type?.isSome then\n              let pendingMVarIds \u2190 getMVars type\n              discard <| logUnassignedUsingErrorInfos pendingMVarIds <|\n                getPendindMVarErrorMessage views\n            let newHeader := {\n              ref           := view.ref\n              modifiers     := view.modifiers\n              kind          := view.kind\n              shortDeclName := shortDeclName\n              declName, type, levelNames, binderIds\n              numParams     := xs.size\n              valueStx      := view.value : DefViewElabHeader }\n            check headers newHeader\n            return newHeader\n      headers := headers.push newHeader\n    return headers\n\n/--\n  Create auxiliary local declarations `fs` for the given hearders using their `shortDeclName` and `type`, given hearders, and execute `k fs`.\n  The new free variables are tagged as `auxDecl`.\n  Remark: `fs.size = headers.size`.\n-/\nprivate partial def withFunLocalDecls {\u03b1} (headers : Array DefViewElabHeader) (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 :=\n  let rec loop (i : Nat) (fvars : Array Expr) := do\n    if h : i < headers.size then\n      let header := headers.get \u27e8i, h\u27e9\n      if header.modifiers.isNonrec then\n        loop (i+1) fvars\n      else\n        withAuxDecl header.shortDeclName header.type header.declName fun fvar => loop (i+1) (fvars.push fvar)\n    else\n      k fvars\n  loop 0 #[]\n\nprivate def expandWhereStructInst : Macro\n  | `(Parser.Command.whereStructInst|where $[$decls:letDecl];* $[$whereDecls?:whereDecls]?) => do\n    let letIdDecls \u2190 decls.mapM fun stx => match stx with\n      | `(letDecl|$_decl:letPatDecl) => Macro.throwErrorAt stx \"patterns are not allowed here\"\n      | `(letDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl (useExplicit := false)\n      | `(letDecl|$decl:letIdDecl)   => pure decl\n      | _                            => Macro.throwUnsupported\n    let structInstFields \u2190 letIdDecls.mapM fun\n      | stx@`(letIdDecl|$id:ident $binders* $[: $ty?]? := $val) => withRef stx do\n        let mut val := val\n        if let some ty := ty? then\n          val \u2190 `(($val : $ty))\n        -- HACK: this produces invalid syntax, but the fun elaborator supports letIdBinders as well\n        have : Coe (TSyntax ``letIdBinder) (TSyntax ``funBinder) := \u27e8(\u27e8\u00b7\u27e9)\u27e9\n        val \u2190 if binders.size > 0 then `(fun $binders* => $val) else pure val\n        `(structInstField|$id:ident := $val)\n      | _ => Macro.throwUnsupported\n    let body \u2190 `({ $structInstFields,* })\n    match whereDecls? with\n    | some whereDecls => expandWhereDecls whereDecls body\n    | none => return body\n  | _ => Macro.throwUnsupported\n\n/-\nRecall that\n```\ndef declValSimple    := leading_parser \" :=\\n\" >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser Term.matchAltsWhereDecls\ndef declVal          := declValSimple <|> declValEqns <|> Term.whereDecls\n```\n-/\nprivate def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do\n  if declVal.isOfKind ``Parser.Command.declValSimple then\n    expandWhereDeclsOpt declVal[2] declVal[1]\n  else if declVal.isOfKind ``Parser.Command.declValEqns then\n    expandMatchAltsWhereDecls declVal[0]\n  else if declVal.isOfKind ``Parser.Command.whereStructInst then\n    expandWhereStructInst declVal\n  else if declVal.isMissing then\n    Macro.throwErrorAt declVal \"declaration body is missing\"\n  else\n    Macro.throwErrorAt declVal \"unexpected declaration body\"\n\nprivate def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) :=\n  headers.mapM fun header => withDeclName header.declName <| withLevelNames header.levelNames do\n    let valStx \u2190 liftMacroM <| declValToTerm header.valueStx\n    forallBoundedTelescope header.type header.numParams fun xs type => do\n      -- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location.\n      for i in [0:header.binderIds.size] do\n        -- skip auto-bound prefix in `xs`\n        addLocalVarInfo header.binderIds[i]! xs[header.numParams - header.binderIds.size + i]!\n      let val \u2190 elabTermEnsuringType valStx type\n      mkLambdaFVars xs val\n\nprivate def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    : StateRefT CollectFVars.State MetaM Unit := do\n  headers.forM fun header => header.type.collectFVars\n  values.forM fun val => val.collectFVars\n  toLift.forM fun letRecToLift => do\n    letRecToLift.type.collectFVars\n    letRecToLift.val.collectFVars\n\nprivate def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    : TermElabM (LocalContext \u00d7 LocalInstances \u00d7 Array Expr) := do\n  let (_, used) \u2190 (collectUsed headers values toLift).run {}\n  removeUnused vars used\n\nprivate def withUsed {\u03b1} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift)\n    (k : Array Expr \u2192 TermElabM \u03b1) : TermElabM \u03b1 := do\n  let (lctx, localInsts, vars) \u2190 removeUnusedVars vars headers values toLift\n  withLCtx lctx localInsts <| k vars\n\nprivate def isExample (views : Array DefView) : Bool :=\n  views.any (\u00b7.kind.isExample)\n\nprivate def isTheorem (views : Array DefView) : Bool :=\n  views.any (\u00b7.kind.isTheorem)\n\nprivate def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do\n  let type \u2190 instantiateMVars header.type\n  pure { header with type := type }\n\nprivate def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do\n  let type \u2190 instantiateMVars toLift.type\n  let val \u2190 instantiateMVars toLift.val\n  pure { toLift with type, val }\n\nprivate def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId :=\n  let occ? := type.find? fun e => match e with\n    | Expr.fvar fvarId => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId\n    | _ => false\n  match occ? with\n  | some (Expr.fvar fvarId) => some fvarId\n  | _ => none\n\nprivate def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do\n  match (\u2190 fvarId.findDecl?) with\n  | some decl => return decl.userName\n  | none =>\n    /- Recall that the FVarId of nested let-recs are not in the current local context. -/\n    match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with\n    | none   => throwError \"unknown function\"\n    | some n => return n\n\n/--\nEnsures that the of let-rec definition types do not contain functions being defined.\nIn principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components.\nHowever, this extra complication doesn't seem worth it.\n-/\nprivate def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit :=\n  letRecsToLift.forM fun toLift =>\n    match typeHasRecFun toLift.type funVars letRecsToLift with\n    | none        => pure ()\n    | some fvarId => do\n      let fnName \u2190 getFunName fvarId letRecsToLift\n      throwErrorAt toLift.ref \"invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously\"\n\nnamespace MutualClosure\n\n/-- A mapping from FVarId to Set of FVarIds. -/\nabbrev UsedFVarsMap := FVarIdMap FVarIdSet\n\n/--\nCreate the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of\nfree variables in its definition.\n\nFor `mainFVars`, this is just the set of section variables `sectionVars` used.\nFor nested let-rec functions, we collect their free variables.\n\nRecall that a `let rec` expressions are encoded as follows in the elaborator.\n```lean\nlet rec\n  f : A := t,\n  g : B := s;\nbody\n```\nis encoded as\n```lean\nlet f : A := ?m\u2081;\nlet g : B := ?m\u2082;\nbody\n```\nwhere `?m\u2081` and `?m\u2082` are synthetic opaque metavariables. That are assigned by this module.\nWe may have nested `let rec`s.\n```lean\nlet rec f : A :=\n    let rec g : B := t;\n    s;\nbody\n```\nis encoded as\n```lean\nlet f : A := ?m\u2081;\nbody\n```\nand the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above,\nwe would have a `LetRecToLift` containing:\n```\n{\n  mvarId := m\u2081,\n  val    := `(let g : B := ?m\u2082; body)\n  ...\n}\n```\nNote that `g` is not a free variable at `(let g : B := ?m\u2082; body)`. We recover the fact that\n`f` depends on `g` because it contains `m\u2082`\n-/\nprivate def mkInitialUsedFVarsMap [Monad m] [MonadMCtx m] (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift)\n    : m UsedFVarsMap := do\n  let mut sectionVarSet := {}\n  for var in sectionVars do\n    sectionVarSet := sectionVarSet.insert var.fvarId!\n  let mut usedFVarMap := {}\n  for mainFVarId in mainFVarIds do\n    usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet\n  for toLift in letRecsToLift do\n    let state := Lean.collectFVars {} toLift.val\n    let state := Lean.collectFVars state toLift.type\n    let mut set := state.fvarSet\n    /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId\n       for the associated let-rec because we need this information to compute the fixpoint later. -/\n    let mvarIds := (toLift.val.collectMVars {}).result\n    for mvarId in mvarIds do\n      match (\u2190 letRecsToLift.findSomeM? fun (toLift : LetRecToLift) => return if toLift.mvarId == (\u2190 getDelayedMVarRoot mvarId) then some toLift.fvarId else none) with\n      | some fvarId => set := set.insert fvarId\n      | none        => pure ()\n    usedFVarMap := usedFVarMap.insert toLift.fvarId set\n  return usedFVarMap\n\n/-!\nThe let-recs may invoke each other. Example:\n```\nlet rec\n  f (x : Nat) := g x + y\n  g : Nat \u2192 Nat\n    | 0   => 1\n    | x+1 => f x + z\n```\n`y` is free variable in `f`, and `z` is a free variable in `g`.\nTo close `f` and `g`, `y` and `z` must be in the closure of both.\nThat is, we need to generate the top-level definitions.\n```\ndef f (y z x : Nat) := g y z x + y\ndef g (y z : Nat) : Nat \u2192 Nat\n  | 0 => 1\n  | x+1 => f y z x + z\n```\n-/\nnamespace FixPoint\n\nstructure State where\n  usedFVarsMap : UsedFVarsMap := {}\n  modified     : Bool         := false\n\nabbrev M := ReaderT (Array FVarId) $ StateM State\n\nprivate def isModified : M Bool := do pure (\u2190 get).modified\nprivate def resetModified : M Unit := modify fun s => { s with modified := false }\nprivate def markModified : M Unit := modify fun s => { s with modified := true }\nprivate def getUsedFVarsMap : M UsedFVarsMap := do pure (\u2190 get).usedFVarsMap\nprivate def modifyUsedFVars (f : UsedFVarsMap \u2192 UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap }\n\n-- merge s\u2082 into s\u2081\nprivate def merge (s\u2081 s\u2082 : FVarIdSet) : M FVarIdSet :=\n  s\u2082.foldM (init := s\u2081) fun s\u2081 k => do\n    if s\u2081.contains k then\n      return s\u2081\n    else\n      markModified\n      return s\u2081.insert k\n\nprivate def updateUsedVarsOf (fvarId : FVarId) : M Unit := do\n  let usedFVarsMap \u2190 getUsedFVarsMap\n  match usedFVarsMap.find? fvarId with\n  | none         => return ()\n  | some fvarIds =>\n    let fvarIdsNew \u2190 fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => do\n      if fvarId == fvarId' then\n        return fvarIdsNew\n      else\n        match usedFVarsMap.find? fvarId' with\n        | none => return fvarIdsNew\n          /- We are being sloppy here `otherFVarIds` may contain free variables that are\n             not in the context of the let-rec associated with fvarId.\n             We filter these out-of-context free variables later. -/\n        | some otherFVarIds => merge fvarIdsNew otherFVarIds\n    modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew\n\nprivate partial def fixpoint : Unit \u2192 M Unit\n  | _ => do\n    resetModified\n    let letRecFVarIds \u2190 read\n    letRecFVarIds.forM updateUsedVarsOf\n    if (\u2190 isModified) then\n      fixpoint ()\n\ndef run (letRecFVarIds : Array FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap :=\n  let (_, s) := fixpoint () |>.run letRecFVarIds |>.run { usedFVarsMap := usedFVarsMap }\n  s.usedFVarsMap\n\nend FixPoint\n\nabbrev FreeVarMap := FVarIdMap (Array FVarId)\n\nprivate def mkFreeVarMap [Monad m] [MonadMCtx m]\n    (sectionVars : Array Expr) (mainFVarIds : Array FVarId)\n    (recFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : m FreeVarMap := do\n  let usedFVarsMap   \u2190 mkInitialUsedFVarsMap sectionVars mainFVarIds letRecsToLift\n  let letRecFVarIds  := letRecsToLift.map fun toLift => toLift.fvarId\n  let usedFVarsMap   := FixPoint.run letRecFVarIds usedFVarsMap\n  let mut freeVarMap := {}\n  for toLift in letRecsToLift do\n    let lctx       := toLift.lctx\n    let fvarIdsSet := usedFVarsMap.find? toLift.fvarId |>.get!\n    let fvarIds    := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId =>\n      if lctx.contains fvarId && !recFVarIds.contains fvarId then\n        fvarIds.push fvarId\n      else\n        fvarIds\n    freeVarMap := freeVarMap.insert toLift.fvarId fvarIds\n  return freeVarMap\n\nstructure ClosureState where\n  newLocalDecls : Array LocalDecl := #[]\n  localDecls    : Array LocalDecl := #[]\n  newLetDecls   : Array LocalDecl := #[]\n  exprArgs      : Array Expr      := #[]\n\nprivate def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId :=\n  fvarIds.getMax? fun fvarId\u2081 fvarId\u2082 => (lctx.get! fvarId\u2081).index < (lctx.get! fvarId\u2082).index\n\nprivate def preprocess (e : Expr) : TermElabM Expr := do\n  let e \u2190 instantiateMVars e\n  -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.\n  Meta.check e\n  pure e\n\n/-- Push free variables in `s` to `toProcess` if they are not already there. -/\nprivate def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId :=\n  s.fvarSet.fold (init := toProcess) fun toProcess fvarId =>\n    if toProcess.contains fvarId then toProcess else toProcess.push fvarId\n\nprivate def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) (kind : LocalDeclKind)\n    : StateRefT ClosureState TermElabM (Array FVarId) := do\n  let type \u2190 preprocess type\n  modify fun s => { s with\n    newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl default fvarId userName type bi kind\n    exprArgs      := s.exprArgs.push (mkFVar fvarId)\n  }\n  return pushNewVars toProcess (collectFVars {} type)\n\nprivate partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do\n  let lctx \u2190 getLCtx\n  match pickMaxFVar? lctx toProcess with\n  | none        => return ()\n  | some fvarId =>\n    trace[Elab.definition.mkClosure] \"toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}\"\n    let toProcess := toProcess.erase fvarId\n    let localDecl \u2190 fvarId.getDecl\n    match localDecl with\n    | .cdecl _ _ userName type bi k =>\n      let toProcess \u2190 pushLocalDecl toProcess fvarId userName type bi k\n      mkClosureForAux toProcess\n    | .ldecl _ _ userName type val _ k =>\n      let zetaFVarIds \u2190 getZetaFVarIds\n      if !zetaFVarIds.contains fvarId then\n        /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/\n        let toProcess \u2190 pushLocalDecl toProcess fvarId userName type .default k\n        mkClosureForAux toProcess\n      else\n        /- Dependent let-decl. -/\n        let type \u2190 preprocess type\n        let val  \u2190 preprocess val\n        modify fun s => { s with\n          newLetDecls   := s.newLetDecls.push <| .ldecl default fvarId userName type val false k,\n          /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId\n             at `newLocalDecls` and `localDecls` -/\n          newLocalDecls := s.newLocalDecls.map (\u00b7.replaceFVarId fvarId val)\n          localDecls := s.localDecls.map (\u00b7.replaceFVarId fvarId val)\n        }\n        mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val))\n\nprivate partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do\n  let (_, s) \u2190 mkClosureForAux freeVars |>.run { localDecls := localDecls }\n  return { s with\n    newLocalDecls := s.newLocalDecls.reverse\n    newLetDecls   := s.newLetDecls.reverse\n    exprArgs      := s.exprArgs.reverse\n  }\n\nstructure LetRecClosure where\n  ref        : Syntax\n  localDecls : Array LocalDecl\n  /-- Expression used to replace occurrences of the let-rec `FVarId`. -/\n  closed     : Expr\n  toLift     : LetRecToLift\n\nprivate def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do\n  let lctx := toLift.lctx\n  withLCtx lctx toLift.localInstances do\n  lambdaTelescope toLift.val fun xs val => do\n    /-\n      Recall that `toLift.type` and `toLift.value` may have different binder annotations.\n      See issue #1377 for an example.\n    -/\n    let userNameAndBinderInfos \u2190 forallBoundedTelescope toLift.type xs.size fun xs _ =>\n      xs.mapM fun x => do\n        let localDecl \u2190 x.fvarId!.getDecl\n        return (localDecl.userName, localDecl.binderInfo)\n    /- Auxiliary map for preserving binder user-facing names and `BinderInfo` for types. -/\n    let mut userNameBinderInfoMap : FVarIdMap (Name \u00d7 BinderInfo) := {}\n    for x in xs, (userName, bi) in userNameAndBinderInfos do\n      userNameBinderInfoMap := userNameBinderInfoMap.insert x.fvarId! (userName, bi)\n    let type \u2190 instantiateForall toLift.type xs\n    let lctx \u2190 getLCtx\n    let s \u2190 mkClosureFor freeVars <| xs.map fun x => lctx.get! x.fvarId!\n    /- Apply original type binder info and user-facing names to local declarations. -/\n    let typeLocalDecls := s.localDecls.map fun localDecl =>\n      if let some (userName, bi) := userNameBinderInfoMap.find? localDecl.fvarId then\n        localDecl.setBinderInfo bi |>.setUserName userName\n      else\n        localDecl\n    let type := Closure.mkForall typeLocalDecls <| Closure.mkForall s.newLetDecls type\n    let val  := Closure.mkLambda s.localDecls <| Closure.mkLambda s.newLetDecls val\n    let c    := mkAppN (Lean.mkConst toLift.declName) s.exprArgs\n    toLift.mvarId.assign c\n    return {\n      ref        := toLift.ref\n      localDecls := s.newLocalDecls\n      closed     := c\n      toLift     := { toLift with val, type }\n    }\n\nprivate def mkLetRecClosures (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : TermElabM (List LetRecClosure) := do\n  -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec.\n  let mut letRecsToLift := letRecsToLift\n  let mut freeVarMap    \u2190 mkFreeVarMap sectionVars mainFVarIds recFVarIds letRecsToLift\n  let mut result := #[]\n  for i in [:letRecsToLift.size] do\n    if letRecsToLift[i]!.val.hasExprMVar then\n      -- This can happen when this particular let-rec has nested let-rec that have been resolved in previous iterations.\n      -- This code relies on the fact that nested let-recs occur before the outer most let-recs at `letRecsToLift`.\n      -- Unresolved nested let-recs appear as metavariables before they are resolved. See `assignExprMVar` at `mkLetRecClosureFor`\n      let valNew \u2190 instantiateMVars letRecsToLift[i]!.val\n      letRecsToLift := letRecsToLift.modify i fun t => { t with val := valNew }\n      -- We have to recompute the `freeVarMap` in this case. This overhead should not be an issue in practice.\n      freeVarMap \u2190 mkFreeVarMap sectionVars mainFVarIds recFVarIds letRecsToLift\n    let toLift := letRecsToLift[i]!\n    result := result.push (\u2190 mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get!)\n  return result.toList\n\n/-- Mapping from FVarId of mutually recursive functions being defined to \"closure\" expression. -/\nabbrev Replacement := FVarIdMap Expr\n\ndef insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement :=\n  mainFVars.size.fold (init := r) fun i r =>\n    r.insert mainFVars[i]!.fvarId! (mkAppN (Lean.mkConst mainHeaders[i]!.declName) sectionVars)\n\n\ndef insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement :=\n  letRecClosures.foldl (init := r) fun r c =>\n    r.insert c.toLift.fvarId c.closed\n\ndef Replacement.apply (r : Replacement) (e : Expr) : Expr :=\n  e.replace fun e => match e with\n    | .fvar fvarId => match r.find? fvarId with\n      | some c => some c\n      | _      => none\n    | _ => none\n\ndef pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr)\n    : TermElabM (Array PreDefinition) :=\n  mainHeaders.size.foldM (init := preDefs) fun i preDefs => do\n    let header := mainHeaders[i]!\n    let value \u2190 mkLambdaFVars sectionVars mainVals[i]!\n    let type \u2190 mkForallFVars sectionVars header.type\n    return preDefs.push {\n      ref         := getDeclarationSelectionRef header.ref\n      kind        := header.kind\n      declName    := header.declName\n      levelParams := [], -- we set it later\n      modifiers   := header.modifiers\n      type, value\n    }\n\ndef pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : MetaM (Array PreDefinition) :=\n  letRecClosures.foldlM (init := preDefs) fun preDefs c => do\n    let type  := Closure.mkForall c.localDecls c.toLift.type\n    let value := Closure.mkLambda c.localDecls c.toLift.val\n    -- Convert any proof let recs inside a `def` to `theorem` kind\n    let kind \u2190 if kind.isDefOrAbbrevOrOpaque then\n      withLCtx c.toLift.lctx c.toLift.localInstances do\n        return if (\u2190 inferType c.toLift.type).isProp then .theorem else kind\n    else\n      pure kind\n    return preDefs.push {\n      ref         := c.ref\n      declName    := c.toLift.declName\n      levelParams := [] -- we set it later\n      modifiers   := { modifiers with attrs := c.toLift.attrs }\n      kind, type, value\n    }\n\ndef getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind :=\n  if mainHeaders.any fun h => h.kind.isTheorem then DefKind.\u00abtheorem\u00bb\n  else DefKind.\u00abdef\u00bb\n\ndef getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := {\n  isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable\n  recKind         := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default\n  isUnsafe        := mainHeaders.any fun h => h.modifiers.isUnsafe\n}\n\n/--\n- `sectionVars`:   The section variables used in the `mutual` block.\n- `mainHeaders`:   The elaborated header of the top-level definitions being defined by the mutual block.\n- `mainFVars`:     The auxiliary variables used to represent the top-level definitions being defined by the mutual block.\n- `mainVals`:      The elaborated value for the top-level definitions\n- `letRecsToLift`: The let-rec's definitions that need to be lifted\n-/\ndef main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift)\n    : TermElabM (Array PreDefinition) := do\n  -- Store in recFVarIds the fvarId of every function being defined by the mutual block.\n  let letRecsToLift := letRecsToLift.toArray\n  let mainFVarIds := mainFVars.map Expr.fvarId!\n  let recFVarIds  := (letRecsToLift.map fun toLift => toLift.fvarId) ++ mainFVarIds\n  resetZetaFVarIds\n  withTrackingZeta do\n    -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`.\n    let letRecsToLift \u2190 letRecsToLift.mapM fun toLift => withLCtx toLift.lctx toLift.localInstances do\n      Meta.check toLift.type\n      Meta.check toLift.val\n      return { toLift with val := (\u2190 instantiateMVars toLift.val), type := (\u2190 instantiateMVars toLift.type) }\n    let letRecClosures \u2190 mkLetRecClosures sectionVars mainFVarIds recFVarIds letRecsToLift\n    -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations.\n    let mainVals    \u2190 mainVals.mapM (instantiateMVars \u00b7)\n    let mainHeaders \u2190 mainHeaders.mapM instantiateMVarsAtHeader\n    let letRecClosures \u2190 letRecClosures.mapM fun closure => do pure { closure with toLift := (\u2190 instantiateMVarsAtLetRecToLift closure.toLift) }\n    -- Replace fvarIds for functions being defined with closed terms\n    let r              := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars\n    let r              := insertReplacementForLetRecs r letRecClosures\n    let mainVals       := mainVals.map r.apply\n    let mainHeaders    := mainHeaders.map fun h => { h with type := r.apply h.type }\n    let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } }\n    let letRecKind     := getKindForLetRecs mainHeaders\n    let letRecMods     := getModifiersForLetRecs mainHeaders\n    pushMain (\u2190 pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals\n\nend MutualClosure\n\nprivate def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name :=\n  if h : 0 < headers.size then\n    -- Recall that all top-level functions must have the same levels. See `check` method above\n    (headers.get \u27e80, h\u27e9).levelNames\n  else\n    []\n\n/-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/\nprivate def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do\n  let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do\n    let mut newHeaders := #[]\n    for view in views, header in headers do\n      if view.kind.isTheorem then\n        newHeaders \u2190\n          withLevelNames header.levelNames do\n            return newHeaders.push { header with type := (\u2190 levelMVarToParam header.type), levelNames := (\u2190 getLevelNames) }\n      else\n        newHeaders := newHeaders.push header\n    return newHeaders\n  let newHeaders \u2190 (process).run' 1\n  newHeaders.mapM fun header => return { header with type := (\u2190 instantiateMVars header.type) }\n\npartial def checkForHiddenUnivLevels (allUserLevelNames : List Name) (preDefs : Array PreDefinition) : TermElabM Unit :=\n  unless (\u2190 MonadLog.hasErrors) do\n    -- We do not report this kind of error if the declaration already contains errors\n    let mut sTypes : CollectLevelParams.State := {}\n    let mut sValues : CollectLevelParams.State := {}\n    for preDef in preDefs do\n      sTypes  := collectLevelParams sTypes preDef.type\n      sValues := collectLevelParams sValues preDef.value\n    if sValues.params.all fun u => sTypes.params.contains u || allUserLevelNames.contains u then\n      -- If all universe level occurring in values also occur in types or explicitly provided universes, then everything is fine\n      -- and we just return\n      return ()\n    let checkPreDef (preDef : PreDefinition) : TermElabM Unit :=\n      -- Otherwise, we try to produce an error message containing the expression with the offending universe\n      let rec visitLevel (u : Level) : ReaderT Expr TermElabM Unit := do\n        match u with\n        | .succ u => visitLevel u\n        | .imax u v | .max u v => visitLevel u; visitLevel v\n        | .param n =>\n          unless sTypes.visitedLevel.contains u || allUserLevelNames.contains n do\n            let parent \u2190 withOptions (fun o => pp.universes.set o true) do addMessageContext m!\"{indentExpr (\u2190 read)}\"\n            let body \u2190 withOptions (fun o => pp.letVarTypes.setIfNotSet (pp.funBinderTypes.setIfNotSet o true) true) do addMessageContext m!\"{indentExpr preDef.value}\"\n            throwError \"invalid occurrence of universe level '{u}' at '{preDef.declName}', it does not occur at the declaration type, nor it is explicit universe level provided by the user, occurring at expression{parent}\\nat declaration body{body}\"\n        | _ => pure ()\n      let rec visit (e : Expr) : ReaderT Expr (MonadCacheT ExprStructEq Unit TermElabM) Unit := do\n        checkCache { val := e : ExprStructEq } fun _ => do\n          match e with\n          | .forallE n d b c | .lam n d b c => visit d e; withLocalDecl n c d fun x => visit (b.instantiate1 x) e\n          | .letE n t v b _  => visit t e; visit v e; withLetDecl n t v fun x => visit (b.instantiate1 x) e\n          | .app ..        => e.withApp fun f args => do visit f e; args.forM fun arg => visit arg e\n          | .mdata _ b     => visit b e\n          | .proj _ _ b    => visit b e\n          | .sort u        => visitLevel u (\u2190 read)\n          | .const _ us    => us.forM (visitLevel \u00b7 (\u2190 read))\n          | _              => pure ()\n      visit preDef.value preDef.value |>.run {}\n    for preDef in preDefs do\n      checkPreDef preDef\n\ndef elabMutualDef (vars : Array Expr) (views : Array DefView) (hints : TerminationHints) : TermElabM Unit :=\n  if isExample views then\n    withoutModifyingEnv do\n      -- save correct environment in info tree\n      withSaveInfoContext do\n        go\n  else\n    go\nwhere\n  go := do\n    let scopeLevelNames \u2190 getLevelNames\n    let headers \u2190 elabHeaders views\n    let headers \u2190 levelMVarToParamHeaders views headers\n    let allUserLevelNames := getAllUserLevelNames headers\n    withFunLocalDecls headers fun funFVars => do\n      for view in views, funFVar in funFVars do\n        addLocalVarInfo view.declId funFVar\n      let values \u2190\n        try\n          let values \u2190 elabFunValues headers\n          Term.synthesizeSyntheticMVarsNoPostponing\n          values.mapM (instantiateMVars \u00b7)\n        catch ex =>\n          logException ex\n          headers.mapM fun header => mkSorry header.type (synthetic := true)\n      let headers \u2190 headers.mapM instantiateMVarsAtHeader\n      let letRecsToLift \u2190 getLetRecsToLift\n      let letRecsToLift \u2190 letRecsToLift.mapM instantiateMVarsAtLetRecToLift\n      checkLetRecsToLiftTypes funFVars letRecsToLift\n      withUsed vars headers values letRecsToLift fun vars => do\n        let preDefs \u2190 MutualClosure.main vars headers funFVars values letRecsToLift\n        for preDef in preDefs do\n          trace[Elab.definition] \"{preDef.declName} : {preDef.type} :=\\n{preDef.value}\"\n        let preDefs \u2190 withLevelNames allUserLevelNames <| levelMVarToParamPreDecls preDefs\n        let preDefs \u2190 instantiateMVarsAtPreDecls preDefs\n        let preDefs \u2190 fixLevelParams preDefs scopeLevelNames allUserLevelNames\n        for preDef in preDefs do\n          trace[Elab.definition] \"after eraseAuxDiscr, {preDef.declName} : {preDef.type} :=\\n{preDef.value}\"\n        checkForHiddenUnivLevels allUserLevelNames preDefs\n        addPreDefinitions preDefs hints\n        processDeriving headers\n\n  processDeriving (headers : Array DefViewElabHeader) := do\n    for header in headers, view in views do\n      if let some classNamesStx := view.deriving? then\n        for classNameStx in classNamesStx do\n          let className \u2190 resolveGlobalConstNoOverload classNameStx\n          withRef classNameStx do\n            unless (\u2190 processDefDeriving className header.declName) do\n              throwError \"failed to synthesize instance '{className}' for '{header.declName}'\"\n\nend Term\nnamespace Command\n\ndef elabMutualDef (ds : Array Syntax) (hints : TerminationHints) : CommandElabM Unit := do\n  let views \u2190 ds.mapM fun d => do\n    let modifiers \u2190 elabModifiers d[0]\n    if ds.size > 1 && modifiers.isNonrec then\n      throwErrorAt d \"invalid use of 'nonrec' modifier in 'mutual' block\"\n    mkDefView modifiers d[1]\n  runTermElabM fun vars => Term.elabMutualDef vars views hints\n\nend Command\nend Lean.Elab\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/MutualDef.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421300186801369, "lm_q2_score": 0.03514484804299783, "lm_q1q2_score": 0.004365447075615946}}
{"text": "import UserWidget.ToHtml.Widget\n\ndef codefn (s : String) := s!\"\n  import * as React from 'react';\n  export default function (props) \\{\n    return React.createElement('p', \\{}, `This is {s} with props $\\{JSON.stringify(props)}`)\n  }\"\n\nopen Lean.Widget in\n@[widget]\ndef widget1 : UserWidgetDefinition where\n  name := \"Hello widget1\"\n  javascript := codefn \"widget1\"\n\nsyntax (name := widget) \"widget!\" ident : tactic\nopen Lean Elab Tactic in\n@[tactic widget]\ndef widgetTac : Tactic\n  | stx@`(tactic| widget! $n) => do\n    if let some pos := stx.getPos? then\n      let id := n.getId\n      if \u00ac Lean.Widget.userWidgetRegistry.contains (\u2190 getEnv) id then \n        throwError \"No widget present named '{id}'\"\n      let props := Json.mkObj [(\"pos\", pos.byteIdx)]\n      Lean.Widget.saveWidgetInfo id props stx\n  | _ => throwUnsupportedSyntax\n\ntheorem asdf : True := by\n  widget! widget1\n  trivial\n\nopen scoped Lean.Widget.Jsx in\ntheorem ghjk : True := by\n  html! <b>What, HTML in Lean?! </b>\n  html! <i>And another!</i>\n  trivial\n\n", "meta": {"author": "Vtec234", "repo": "npm-widget", "sha": "b7ba6a7cdc3e66e0614a16225e3bd1aee009e371", "save_path": "github-repos/lean/Vtec234-npm-widget", "path": "github-repos/lean/Vtec234-npm-widget/npm-widget-b7ba6a7cdc3e66e0614a16225e3bd1aee009e371/UserWidget/Demos/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.12252322213041655, "lm_q2_score": 0.03514485006417277, "lm_q1q2_score": 0.004306060271152825}}
{"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.Elab.Term\nimport Lean.Elab.BindersUtil\nimport Lean.Elab.PatternVar\nimport Lean.Elab.Quotation.Util\nimport Lean.Parser.Do\n\n-- HACK: avoid code explosion until heuristics are improved\nset_option compiler.reuse false\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Meta\nopen TSyntax.Compat\n\nprivate def getDoSeqElems (doSeq : Syntax) : List Syntax :=\n  if doSeq.getKind == ``Parser.Term.doSeqBracketed then\n    doSeq[1].getArgs.toList.map fun arg => arg[0]\n  else if doSeq.getKind == ``Parser.Term.doSeqIndent then\n    doSeq[0].getArgs.toList.map fun arg => arg[0]\n  else\n    []\n\nprivate def getDoSeq (doStx : Syntax) : Syntax :=\n  doStx[1]\n\n@[builtin_term_elab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>\n  throwErrorAt stx \"invalid use of `(<- ...)`, must be nested inside a 'do' expression\"\n\n/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/\nprivate def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=\n  k == ``Parser.Term.do ||\n  k == ``Parser.Term.doSeqIndent ||\n  k == ``Parser.Term.doSeqBracketed ||\n  k == ``Parser.Term.termReturn ||\n  k == ``Parser.Term.termUnless ||\n  k == ``Parser.Term.termTry ||\n  k == ``Parser.Term.termFor\n\n/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/\nprivate def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=\n  let k := letDeclArg.getKind\n  if k == ``Parser.Term.letPatDecl then\n    false\n  else if k == ``Parser.Term.letEqnsDecl then\n    true\n  else if k == ``Parser.Term.letIdDecl then\n    -- letIdLhs := ident >> checkWsBefore \"expected space before binders\" >> many (ppSpace >> letIdBinder)) >> optType\n    let binders := letDeclArg[1]\n    binders.getNumArgs > 0\n  else\n    false\n\n/-- Return `true` if the given `letDecl` contains binders. -/\nprivate def letDeclHasBinders (letDecl : Syntax) : Bool :=\n  letDeclArgHasBinders letDecl[0]\n\n/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/\nprivate def liftMethodForbiddenBinder (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  if k == ``Parser.Term.fun || k == ``Parser.Term.matchAlts ||\n     k == ``Parser.Term.doLetRec || k == ``Parser.Term.letrec  then\n     -- It is never ok to lift over this kind of binder\n    true\n  -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not\n  else if k == ``Parser.Term.let then\n    letDeclHasBinders stx[1]\n  else if k == ``Parser.Term.doLet then\n    letDeclHasBinders stx[2]\n  else if k == ``Parser.Term.doLetArrow then\n    letDeclArgHasBinders stx[2]\n  else\n    false\n\nprivate partial def hasLiftMethod : Syntax \u2192 Bool\n  | Syntax.node _ k args =>\n    if liftMethodDelimiter k then false\n    -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a\n    -- bit slower\n    else if k == ``Parser.Term.liftMethod then true\n    else args.any hasLiftMethod\n  | _ => false\n\nstructure ExtractMonadResult where\n  m            : Expr\n  returnType   : Expr\n  expectedType : Expr\n\nprivate def mkUnknownMonadResult : MetaM ExtractMonadResult := do\n  let u \u2190 mkFreshLevelMVar\n  let v \u2190 mkFreshLevelMVar\n  let m \u2190 mkFreshExprMVar (\u2190 mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v)))\n  let returnType \u2190 mkFreshExprMVar (mkSort (mkLevelSucc u))\n  return { m, returnType, expectedType := mkApp m returnType }\n\nprivate partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do\n  let some expectedType := expectedType? | mkUnknownMonadResult\n  let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n    let .app m returnType := type | return none\n    try\n      let bindInstType \u2190 mkAppM ``Bind #[m]\n      discard <| Meta.synthInstance bindInstType\n      return some { m, returnType, expectedType }\n    catch _ =>\n      return none\n  let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n    match (\u2190 extractStep? type) with\n    | some r => return r\n    | none =>\n      let typeNew \u2190 whnfCore type\n      if typeNew != type then\n        extract? typeNew\n      else\n        if typeNew.getAppFn.isMVar then\n          mkUnknownMonadResult\n        else match (\u2190 unfoldDefinition? typeNew) with\n          | some typeNew => extract? typeNew\n          | none => return none\n  match (\u2190 extract? expectedType) with\n  | some r => return r\n  | none   => throwError \"invalid `do` notation, expected type is not a monad application{indentExpr expectedType}\\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad.\"\n\nnamespace Do\n\nabbrev Var := Syntax  -- TODO: should be `Ident`\n\n/-- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/\nstructure Alt (\u03c3 : Type) where\n  ref : Syntax\n  vars : Array Var\n  patterns : Syntax\n  rhs : \u03c3\n  deriving Inhabited\n\n/--\n  Auxiliary datastructure for representing a `do` code block, and compiling \"reassignments\" (e.g., `x := x + 1`).\n  We convert `Code` into a `Syntax` term representing the:\n  - `do`-block, or\n  - the visitor argument for the `forIn` combinator.\n\n  We say the following constructors are terminals:\n  - `break`:    for interrupting a `for x in s`\n  - `continue`: for interrupting the current iteration of a `for x in s`\n  - `return e`: for returning `e` as the result for the whole `do` computation block\n  - `action a`: for executing action `a` as a terminal\n  - `ite`:      if-then-else\n  - `match`:    pattern matching\n  - `jmp`       a goto to a join-point\n\n  We say the terminals `break`, `continue`, `action`, and `return` are \"exit points\"\n\n  Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x == 0 then\n     return ()\n  IO.println \"hello\"\n  ```\n  Executing `#eval f 0` will not print \"hello\". Now, consider\n  ```\n  def g (x : Nat) : IO Unit := do\n  if x == 0 then\n     pure ()\n  IO.println \"hello\"\n  ```\n  The `if` statement is essentially a noop, and \"hello\" is printed when we execute `g 0`.\n\n  - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).\n    The field `stx` is the actual `doElem`,\n    `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.\n    `vars` is an array since we have declarations such as `let (a, b) := s`.\n\n  - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).\n\n  - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.\n\n  - `seq a k` executes action `a`, ignores its result, and then executes `k`.\n    We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.\n\n  A code block `C` is well-formed if\n  - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and\n    `ps.size == as.size` -/\ninductive Code where\n  | decl         (xs : Array Var) (doElem : Syntax) (k : Code)\n  | reassign     (xs : Array Var) (doElem : Syntax) (k : Code)\n  /-- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/\n  | joinpoint    (name : Name) (params : Array (Var \u00d7 Bool)) (body : Code) (k : Code)\n  | seq          (action : Syntax) (k : Code)\n  | action       (action : Syntax)\n  | break        (ref : Syntax)\n  | continue     (ref : Syntax)\n  | return       (ref : Syntax) (val : Syntax)\n  /-- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/\n  | ite          (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)\n  | match        (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code))\n  | jmp          (ref : Syntax) (jpName : Name) (args : Array Syntax)\n  deriving Inhabited\n\ndef Code.getRef? : Code \u2192 Option Syntax\n  | .decl _ doElem _     => doElem\n  | .reassign _ doElem _ => doElem\n  | .joinpoint ..        => none\n  | .seq a _             => a\n  | .action a            => a\n  | .break ref           => ref\n  | .continue ref        => ref\n  | .return ref _        => ref\n  | .ite ref ..          => ref\n  | .match ref ..        => ref\n  | .jmp ref ..          => ref\n\nabbrev VarSet := RBMap Name Syntax Name.cmp\n\n/-- A code block, and the collection of variables updated by it. -/\nstructure CodeBlock where\n  code  : Code\n  uvars : VarSet := {} -- set of variables updated by `code`\n\nprivate def varSetToArray (s : VarSet) : Array Var :=\n  s.fold (fun xs _ x => xs.push x) #[]\n\nprivate def varsToMessageData (vars : Array Var) : MessageData :=\n  MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) \" \"\n\npartial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=\n  let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax\n  let rec loop : Code \u2192 MessageData\n    | .decl xs _ k           => m!\"let {varsToMessageData xs} := ...\\n{loop k}\"\n    | .reassign xs _ k       => m!\"{varsToMessageData xs} := ...\\n{loop k}\"\n    | .joinpoint n ps body k => m!\"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\\n{loop k}\"\n    | .seq e k               => m!\"{e}\\n{loop k}\"\n    | .action e              => e\n    | .ite _ _ _ c t e       => m!\"if {c} then {indentD (loop t)}\\nelse{loop e}\"\n    | .jmp _ j xs            => m!\"jmp {j.simpMacroScopes} {xs.toList}\"\n    | .break _               => m!\"break {us}\"\n    | .continue _            => m!\"continue {us}\"\n    | .return _ v            => m!\"return {v} {us}\"\n    | .match _ _ ds _ alts   =>\n      m!\"match {ds} with\"\n      ++ alts.foldl (init := m!\"\") fun acc alt => acc ++ m!\"\\n| {alt.patterns} => {loop alt.rhs}\"\n  loop codeBlock.code\n\n/-- Return true if the give code contains an exit point that satisfies `p` -/\npartial def hasExitPointPred (c : Code) (p : Code \u2192 Bool) : Bool :=\n  let rec loop : Code \u2192 Bool\n    | .decl _ _ k         => loop k\n    | .reassign _ _ k     => loop k\n    | .joinpoint _ _ b k  => loop b || loop k\n    | .seq _ k            => loop k\n    | .ite _ _ _ _ t e    => loop t || loop e\n    | .match _ _ _ _ alts => alts.any (loop \u00b7.rhs)\n    | .jmp ..             => false\n    | c                   => p c\n  loop c\n\ndef hasExitPoint (c : Code) : Bool :=\n  hasExitPointPred c fun _ => true\n\ndef hasReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | .return .. => true\n    | _ => false\n\ndef hasTerminalAction (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | .action _ => true\n    | _ => false\n\ndef hasBreakContinue (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | .break _    => true\n    | .continue _ => true\n    | _ => false\n\ndef hasBreakContinueReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | .break _    => true\n    | .continue _ => true\n    | .return _ _ => true\n    | _ => false\n\ndef mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax \u2192 m Code) : m Code := withRef e <| withFreshMacroScope do\n  let y \u2190 `(y)\n  let doElem \u2190 `(doElem| let y \u2190 $e:term)\n  -- Add elaboration hint for producing sane error message\n  let y \u2190 `(ensure_expected_type% \"type mismatch, result value\" $y)\n  let k \u2190 mkCont y\n  return .decl #[y] doElem k\n\n/-- Convert `action _ e` instructions in `c` into `let y \u2190 e; jmp _ jp (xs y)`. -/\npartial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code :=\n  let rec loop : Code \u2192 MacroM Code\n    | .decl xs stx k         => return .decl xs stx (\u2190 loop k)\n    | .reassign xs stx k     => return .reassign xs stx (\u2190 loop k)\n    | .joinpoint n ps b k    => return .joinpoint n ps (\u2190 loop b) (\u2190 loop k)\n    | .seq e k               => return .seq e (\u2190 loop k)\n    | .ite ref x? h c t e    => return .ite ref x? h c (\u2190 loop t) (\u2190 loop e)\n    | .match ref g ds t alts => return .match ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 loop alt.rhs) })\n    | .action e              => mkAuxDeclFor e fun y =>\n      let ref := e\n      -- We jump to `jp` with xs **and** y\n      let jmpArgs := xs.push y\n      return Code.jmp ref jp jmpArgs\n    | c                            => return c\n  loop code\n\nstructure JPDecl where\n  name : Name\n  params : Array (Var \u00d7 Bool)\n  body : Code\n\ndef attachJP (jpDecl : JPDecl) (k : Code) : Code :=\n  Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k\n\ndef attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=\n  jpDecls.foldr attachJP k\n\ndef mkFreshJP (ps : Array (Var \u00d7 Bool)) (body : Code) : TermElabM JPDecl := do\n  let ps \u2190 if ps.isEmpty then\n    let y \u2190 `(y)\n    pure #[(y.raw, false)]\n  else\n    pure ps\n  -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by\n  -- the \"do\" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`\n  -- We will remove this hack when we re-implement the compiler frontend in Lean.\n  let name \u2190 mkFreshUserName `__do_jp\n  pure { name := name, params := ps, body := body }\n\ndef addFreshJP (ps : Array (Var \u00d7 Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do\n  let jp \u2190 mkFreshJP ps body\n  modify fun (jps : Array JPDecl) => jps.push jp\n  pure jp.name\n\ndef insertVars (rs : VarSet) (xs : Array Var) : VarSet :=\n  xs.foldl (fun rs x => rs.insert x.getId x) rs\n\ndef eraseVars (rs : VarSet) (xs : Array Var) : VarSet :=\n  xs.foldl (\u00b7.erase \u00b7.getId) rs\n\ndef eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet :=\n  match x? with\n  | none   => rs\n  | some x => rs.insert x.getId x\n\n/-- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/\ndef mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := varSetToArray rs\n  let jp \u2190 addFreshJP (xs.map fun x => (x, true)) c\n  if xs.isEmpty then\n    let unit \u2190 ``(Unit.unit)\n    return Code.jmp ref jp #[unit]\n  else\n    return Code.jmp ref jp xs\n\n/-- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.\n   The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`\n   is a fresh variable created by this method. -/\ndef mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax \u2192 MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := varSetToArray rs\n  let args := xs.push val\n  let yFresh \u2190 withRef ref `(y)\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (yFresh, false)\n  let jpBody \u2190 liftMacroM <| mkJPBody yFresh\n  let jp \u2190 addFreshJP ps jpBody\n  return Code.jmp ref jp args\n\n/-- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path.  -/\npartial def pullExitPointsAux (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code :=\n  match c with\n  | .decl xs stx k         => return .decl xs stx (\u2190 pullExitPointsAux (eraseVars rs xs) k)\n  | .reassign xs stx k     => return .reassign xs stx (\u2190 pullExitPointsAux (insertVars rs xs) k)\n  | .joinpoint j ps b k    => return .joinpoint j ps (\u2190 pullExitPointsAux rs b) (\u2190 pullExitPointsAux rs k)\n  | .seq e k               => return .seq e (\u2190 pullExitPointsAux rs k)\n  | .ite ref x? o c t e    => return .ite ref x? o c (\u2190 pullExitPointsAux (eraseOptVar rs x?) t) (\u2190 pullExitPointsAux (eraseOptVar rs x?) e)\n  | .match ref g ds t alts => return .match ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })\n  | .jmp ..                => return  c\n  | .break ref             => mkSimpleJmp ref rs (.break ref)\n  | .continue ref          => mkSimpleJmp ref rs (.continue ref)\n  | .return ref val        => mkJmp ref rs val (fun y => return .return ref y)\n  | .action e              =>\n    -- We use `mkAuxDeclFor` because `e` is not pure.\n    mkAuxDeclFor e fun y =>\n      let ref := e\n      mkJmp ref rs y (fun yFresh => return .action (\u2190 ``(Pure.pure $yFresh)))\n\n/--\nAuxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.\nWhen a new variable is not already in the collection, but is shadowed by some declaration in `c`,\nwe create auxiliary join points to make sure we preserve the semantics of the code block.\nExample: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it\nwith the reassignment `x := x + 1`. We first use `pullExitPoints` to create\n```\nlet jp (x!1) :=  return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nand then we add the reassignment\n```\nx := x + 1\nlet jp (x!1) := return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nNote that we created a fresh variable `x!1` to avoid accidental name capture.\nAs another example, consider\n```\nprint x;\nlet x := 10\ny := y + 1;\nreturn x;\n```\nWe transform it into\n```\nlet jp (y x!1) := return x!1;\nprint x;\nlet x := 10\ny := y + 1;\njmp jp y x\n```\nand then we add the reassignment as in the previous example.\nWe need to include `y` in the jump, because each exit point is implicitly returning the set of\nupdate variables.\n\nWe implement the method as follows. Let `us` be `c.uvars`, then\n1- for each `return _ y` in `c`, we create a join point\n  `let j (us y!1) := return y!1`\n   and replace the `return _ y` with `jmp us y`\n2- for each `break`, we create a join point\n  `let j (us) := break`\n   and replace the `break` with `jmp us`.\n3- Same as 2 for `continue`.\n-/\ndef pullExitPoints (c : Code) : TermElabM Code := do\n  if hasExitPoint c then\n    let (c, jpDecls) \u2190 (pullExitPointsAux {} c).run #[]\n    return attachJPs jpDecls c\n  else\n    return c\n\npartial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code :=\n  let rec update (c : Code) : TermElabM Code := do\n    match c with\n    | .joinpoint j ps b k    => return .joinpoint j ps (\u2190 update b) (\u2190 update k)\n    | .seq e k               => return .seq e (\u2190 update k)\n    | .match ref g ds t alts =>\n      if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then\n        -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return .match ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 update alt.rhs) })\n    | .ite ref none o c t e => return .ite ref none o c (\u2190 update t) (\u2190 update e)\n    | .ite ref (some h) o cond t e =>\n      if ws.contains h.getId then\n        -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.ite ref (some h) o cond (\u2190 update t) (\u2190 update e)\n    | .reassign xs stx k => return .reassign xs stx (\u2190 update k)\n    | .decl xs stx k => do\n      if xs.any fun x => ws.contains x.getId then\n        -- One the declared variables is shadowing a variable in `ws`\n        pullExitPoints c\n      else\n        return .decl xs stx (\u2190 update k)\n    | c => return  c\n  update c\n\n/--\nExtend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.\nWe **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.\nSee discussion at `pullExitPoints`.\n-/\npartial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do\n  if ws.any fun x _ => !c.uvars.contains x then\n    -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)\n    pure { code := (\u2190 extendUpdatedVarsAux c.code ws), uvars := ws }\n  else\n    pure { c with uvars := ws }\n\nprivate def union (s\u2081 s\u2082 : VarSet) : VarSet :=\n  s\u2081.fold (\u00b7.insert \u00b7) s\u2082\n\n/--\nGiven two code blocks `c\u2081` and `c\u2082`, make sure they have the same set of updated variables.\nLet `ws` the union of the updated variables in `c\u2081\u2035 and \u2035c\u2082`.\nWe use `extendUpdatedVars c\u2081 ws` and `extendUpdatedVars c\u2082 ws`\n-/\ndef homogenize (c\u2081 c\u2082 : CodeBlock) : TermElabM (CodeBlock \u00d7 CodeBlock) := do\n  let ws := union c\u2081.uvars c\u2082.uvars\n  let c\u2081 \u2190 extendUpdatedVars c\u2081 ws\n  let c\u2082 \u2190 extendUpdatedVars c\u2082 ws\n  pure (c\u2081, c\u2082)\n\n/--\nExtending code blocks with variable declarations: `let x : t := v` and `let x : t \u2190 v`.\nWe remove `x` from the collection of updated varibles.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `let (x, y) := t`\n-/\ndef mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := {\n  code := Code.decl xs stx c.code,\n  uvars := eraseVars c.uvars xs\n}\n\n/--\nExtending code blocks with reassignments: `x : t := v` and `x : t \u2190 v`.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `(x, y) \u2190 t`\n-/\ndef mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do\n  let us := c.uvars\n  let ws := insertVars us xs\n  -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.\n  -- See discussion at `pullExitPoints`\n  let code \u2190 if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code\n  pure { code := .reassign xs stx code, uvars := ws }\n\ndef mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=\n  { c with code := .seq action c.code }\n\ndef mkTerminalAction (action : Syntax) : CodeBlock :=\n  { code := .action action }\n\ndef mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=\n  { code := .return ref val }\n\ndef mkBreak (ref : Syntax) : CodeBlock :=\n  { code := .break ref }\n\ndef mkContinue (ref : Syntax) : CodeBlock :=\n  { code := .continue ref }\n\ndef mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do\n  let x? := optIdent.getOptional?\n  let (thenBranch, elseBranch) \u2190 homogenize thenBranch elseBranch\n  return {\n    code  := .ite ref x? optIdent cond thenBranch.code elseBranch.code,\n    uvars := thenBranch.uvars,\n  }\n\nprivate def mkUnit : MacroM Syntax :=\n  ``((\u27e8\u27e9 : PUnit))\n\nprivate def mkPureUnit : MacroM Syntax :=\n  ``(pure PUnit.unit)\n\ndef mkPureUnitAction : MacroM CodeBlock := do\n  return mkTerminalAction (\u2190 mkPureUnit)\n\ndef mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do\n  let thenBranch \u2190 mkPureUnitAction\n  return { c with code := .ite (\u2190 getRef) none mkNullNode cond thenBranch.code c.code }\n\ndef mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do\n  -- nary version of homogenize\n  let ws := alts.foldl (union \u00b7 \u00b7.rhs.uvars) {}\n  let alts \u2190 alts.mapM fun alt => do\n    let rhs \u2190 extendUpdatedVars alt.rhs ws\n    return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }\n  return { code := .match ref genParam discrs optMotive alts, uvars := ws }\n\n/-- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.\n   This method assumes `terminal` is a terminal -/\ndef concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do\n  unless hasTerminalAction terminal.code do\n    throwErrorAt kRef \"`do` element is unreachable\"\n  let (terminal, k) \u2190 homogenize terminal k\n  let xs := varSetToArray k.uvars\n  let y \u2190 match y? with | some y => pure y | none => `(y)\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (y, false)\n  let jpDecl \u2190 mkFreshJP ps k.code\n  let jp := jpDecl.name\n  let terminal \u2190 liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs\n  return { code  := attachJP jpDecl terminal, uvars := k.uvars }\n\ndef getLetIdDeclVar (letIdDecl : Syntax) : Var :=\n  letIdDecl[0]\n\n-- support both regular and syntax match\ndef getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) :=\n  getPatternVars pattern <|>\n  Quotation.getPatternVars pattern\n\ndef getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) :=\n  getPatternsVars patterns <|>\n  Quotation.getPatternsVars patterns\n\ndef getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do\n  let pattern := letPatDecl[0]\n  getPatternVarsEx pattern\n\ndef getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var :=\n  letEqnsDecl[0]\n\ndef getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do\n  let arg := letDecl[0]\n  if arg.getKind == ``Parser.Term.letIdDecl then\n    return #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Parser.Term.letEqnsDecl then\n    return #[getLetEqnsDeclVar arg]\n  else\n    throwError \"unexpected kind of let declaration\"\n\ndef getDoLetVars (doLet : Syntax) : TermElabM (Array Var) :=\n  -- leading_parser \"let \" >> optional \"mut \" >> letDecl\n  getLetDeclVars doLet[2]\n\ndef getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var :=\n  if optIdent.isNone then\n    `(this)\n  else\n    pure optIdent[0]\n\ndef getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do\n  -- doHave := leading_parser \"have \" >> Term.haveDecl\n  -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl\n  let arg := doHave[1][0]\n  if arg.getKind == ``Parser.Term.haveIdDecl then\n    -- haveIdDecl := leading_parser atomic (haveIdLhs >> \" := \") >> termParser\n    -- haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType\n    return #[\u2190 getHaveIdLhsVar arg[0]]\n  else if arg.getKind == ``Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Parser.Term.haveEqnsDecl then\n    -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts\n    return #[\u2190 getHaveIdLhsVar arg[0]]\n  else\n    throwError \"unexpected kind of have declaration\"\n\ndef getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do\n  -- letRecDecls is an array of `(group (optional attributes >> letDecl))`\n  let letRecDecls := doLetRec[1][0].getSepArgs\n  let letDecls := letRecDecls.map fun p => p[2]\n  let mut allVars := #[]\n  for letDecl in letDecls do\n    let vars \u2190 getLetDeclVars letDecl\n    allVars := allVars ++ vars\n  return allVars\n\n-- ident >> optType >> leftArrow >> termParser\ndef getDoIdDeclVar (doIdDecl : Syntax) : Var :=\n  doIdDecl[0]\n\n-- termParser >> leftArrow >> termParser >> optional (\" | \" >> termParser)\ndef getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do\n  let pattern := doPatDecl[0]\n  getPatternVarsEx pattern\n\n-- leading_parser \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\ndef getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do\n  let decl := doLetArrow[2]\n  if decl.getKind == ``Parser.Term.doIdDecl then\n    return #[getDoIdDeclVar decl]\n  else if decl.getKind == ``Parser.Term.doPatDecl then\n    getDoPatDeclVars decl\n  else\n    throwError \"unexpected kind of `do` declaration\"\n\ndef getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do\n  let arg := doReassign[0]\n  if arg.getKind == ``Parser.Term.letIdDecl then\n    return #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else\n    throwError \"unexpected kind of reassignment\"\n\ndef mkDoSeq (doElems : Array Syntax) : Syntax :=\n  mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]\n\n/--\n  If the given syntax is a `doIf`, return an equivalent `doIf` that has an `else` but no `else if`s or `if let`s.  -/\nprivate def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with\n  | `(doElem|if $_:doIfProp then $_ else $_) => pure none\n  | `(doElem|if $cond:doIfCond then $t $[else if $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do\n    let mut e      := e?.getD (\u2190 `(doSeq|pure PUnit.unit))\n    let mut eIsSeq := true\n    for (cond, t) in Array.zip (conds.reverse.push cond) (ts.reverse.push t) do\n      e \u2190 if eIsSeq then pure e else `(doSeq|$e:doElem)\n      e \u2190 match cond with\n        | `(doIfCond|let $pat := $d) => `(doElem| match $d:term with | $pat:term => $t | _ => $e)\n        | `(doIfCond|let $pat \u2190 $d)  => `(doElem| match \u2190 $d    with | $pat:term => $t | _ => $e)\n        | `(doIfCond|$cond:doIfProp) => `(doElem| if $cond:doIfProp then $t else $e)\n        | _                          => `(doElem| if $(Syntax.missing) then $t else $e)\n      eIsSeq := false\n    return some e\n  | _ => pure none\n\nstructure DoIfView where\n  ref        : Syntax\n  optIdent   : Syntax\n  cond       : Syntax\n  thenBranch : Syntax\n  elseBranch : Syntax\n\n/-- This method assumes `expandDoIf?` is not applicable. -/\nprivate def mkDoIfView (doIf : Syntax) : DoIfView := {\n  ref        := doIf\n  optIdent   := doIf[1][0]\n  cond       := doIf[1][1]\n  thenBranch := doIf[3]\n  elseBranch := doIf[5][1]\n}\n\n/--\nWe use `MProd` instead of `Prod` to group values when expanding the\n`do` notation. `MProd` is a universe monomorphic product.\nThe motivation is to generate simpler universe constraints in code\nthat was not written by the user.\nNote that we are not restricting the macro power since the\n`Bind.bind` combinator already forces values computed by monadic\nactions to be in the same universe.\n-/\nprivate def mkTuple (elems : Array Syntax) : MacroM Syntax := do\n  if elems.size == 0 then\n    mkUnit\n  else if elems.size == 1 then\n    return elems[0]!\n  else\n    elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple =>\n      ``(MProd.mk $elem $tuple)\n\n/-- Return `some action` if `doElem` is a `doExpr <action>`-/\ndef isDoExpr? (doElem : Syntax) : Option Syntax :=\n  if doElem.getKind == ``Parser.Term.doExpr then\n    some doElem[0]\n  else\n    none\n\n/--\n  Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term\n  ```\n  let a_1     := x.1\n  let x       := x.2\n  let a_2     := x.1\n  let x       := x.2\n  ...\n  let a_n     := x.1\n  let a_{n+1} := x.2\n  body\n  ```\n  Special cases\n  - `uvars := #[]` => `body`\n  - `uvars := #[a]` => `let a := x; body`\n\n\n  We use this method when expanding the `for-in` notation.\n-/\nprivate def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n  if uvars.size == 0 then\n    return body\n  else if uvars.size == 1 then\n    `(let $(uvars[0]!):ident := $x; $body)\n  else\n    destruct uvars.toList x body\nwhere\n  destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n    match as with\n      | [a, b]  => `(let $a:ident := $x.1; let $b:ident := $x.2; $body)\n      | a :: as => withFreshMacroScope do\n        let rest \u2190 destruct as (\u2190 `(x)) body\n        `(let $a:ident := $x.1; let x := $x.2; $rest)\n      | _ => unreachable!\n\n/-!\nThe procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.\nWe use this method to convert\n1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of\n   `CodeBlock` never contains `break` nor `continue`. Moreover, the collection\n   of updated variables is not packed into the result.\n   Thus, we have two kinds of exit points\n     - `Code.action e` which is converted into `e`\n     - `Code.return _ e` which is converted into `pure e`\n\n   We use `Kind.regular` for this case.\n\n2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate\n   a `Syntax` term representing a function for the `xs.forIn` combinator.\n\n   a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term\n      has type `m (ForInStep (Option \u03b1 \u00d7 \u03c3))`, where `a : \u03b1`, and the `\u03c3` is the type\n      of the tuple of variables reassigned by `b`.\n      We use `Kind.forInWithReturn` for this case\n\n   b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated\n      `Syntax` term has type `m (ForInStep \u03c3)`.\n      We use `Kind.forIn` for this case.\n\n3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).\n\n   The generated `Syntax` term for `c` must inform whether `c` \"exited\" using `Code.action`, `Code.return`,\n   `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.\n   For example, the auxiliary type `DoResultPBC \u03b1 \u03c3` is used for a code block that exits with `Code.action`,\n   **and** `Code.break`/`Code.continue`, `\u03b1` is the type of values produced by the exit `action`, and\n   `\u03c3` is the type of the tuple of reassigned variables.\n   The type `DoResult \u03b1 \u03b2 \u03c3` is usedf for code blocks that exit with\n   `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `\u03b2` is the type of the returned values.\n   We don't use `DoResult \u03b1 \u03b2 \u03c3` for all cases because:\n\n      a) The elaborator would not be able to infer all type parameters without extra annotations. For example,\n         if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `\u03b2`.\n\n      b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),\n         but we don't want to consider \"unreachable\" cases.\n\n   We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.\n\n   When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,\n   and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.\n\n   - `a`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n\n   - `r`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n           Note that the code that pattern matches on the result will behave differently in this case.\n           It produces `return a` for this case, and `pure a` for the previous one.\n\n   - `b/c`: `Kind.nestedBC`, type `m (DoResultBC \u03c3)`\n\n   - `a` and `r`:   `Kind.nestedPR`, type `m (DoResultPR \u03b1 \u03b2 \u03c3)`\n\n   - `a` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n\n   - `r` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n         Again the code that pattern matches on the result will behave differently in this case and\n         the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for\n         this case, and `pure a` for the previous case.\n\n   - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC \u03b1 \u03b2 \u03c3)`\n\nHere is the recipe for adding new combinators with nested `do`s.\nExample: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m \u03b1 \u2192 m \u03b1`\n1- Convert `doSeq` into `codeBlock : CodeBlock`\n2- Create term `term` using `mkNestedTerm code m uvars a r bc` where\n   `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,\n   `m` is a `Syntax` representing the Monad, and\n   `a` is true if `code` contains `Code.action _`,\n   `r` is true if `code` contains `Code.return _ _`,\n   `bc` is true if `code` contains `Code.break _` or `Code.continue _`.\n\n   Remark: for combinators such as `repeat` that take a single `doSeq`, all\n   arguments, but `m`, are extracted from `codeBlock`.\n3- Create the term `repeat $term`\n4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`\n\n-/\n\n/--\nHelper method for annotating `term` with the raw syntax `ref`.\nWe use this method to implement finer-grained term infos for `do`-blocks.\n\nWe use `withRef term` to make sure the synthetic position for the `with_annotate_term` is equal\nto the one for `term`. This is important for producing error messages when there is a type mismatch.\nConsider the following example:\n```\nopaque f : IO Nat\n\ndef g : IO String := do\n  f\n```\nThere is at type mismatch at `f`, but it is detected when elaborating the expanded term\ncontaining the `with_annotate_term .. f`. The current `getRef` when this `annotate` is invoked\nis not necessarily `f`. Actually, it is the whole `do`-block. By using `withRef` we ensure\nthe synthetic position for the `with_annotate_term ..` is equal to `term`.\nRecall that synthetic positions are used when generating error messages.\n-/\ndef annotate [Monad m] [MonadRef m] [MonadQuotation m] (ref : Syntax) (term : Syntax) : m Syntax :=\n  withRef term <| `(with_annotate_term $ref $term)\n\nnamespace ToTerm\n\ninductive Kind where\n  | regular\n  | forIn\n  | forInWithReturn\n  | nestedBC\n  | nestedPR\n  | nestedSBC\n  | nestedPRBC\n\ninstance : Inhabited Kind := \u27e8Kind.regular\u27e9\n\ndef Kind.isRegular : Kind \u2192 Bool\n  | .regular => true\n  | _        => false\n\nstructure Context where\n  /-- Syntax to reference the monad associated with the do notation. -/\n  m          : Syntax\n  /-- Syntax to reference the result of the monadic computation performed by the do notation. -/\n  returnType : Syntax\n  uvars      : Array Var\n  kind       : Kind\n\nabbrev M := ReaderT Context MacroM\n\ndef mkUVarTuple : M Syntax := do\n  let ctx \u2190 read\n  mkTuple ctx.uvars\n\ndef returnToTerm (val : Syntax) : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | .regular         => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))\n  | .forIn           => ``(Pure.pure (ForInStep.done $u))\n  | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))\n  | .nestedBC        => unreachable!\n  | .nestedPR        => ``(Pure.pure (DoResultPR.\u00abreturn\u00bb $val $u))\n  | .nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abpureReturn\u00bb $val $u))\n  | .nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abreturn\u00bb $val $u))\n\ndef continueToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | .regular         => unreachable!\n  | .forIn           => ``(Pure.pure (ForInStep.yield $u))\n  | .forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | .nestedBC        => ``(Pure.pure (DoResultBC.\u00abcontinue\u00bb $u))\n  | .nestedPR        => unreachable!\n  | .nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abcontinue\u00bb $u))\n  | .nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abcontinue\u00bb $u))\n\ndef breakToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | .regular         => unreachable!\n  | .forIn           => ``(Pure.pure (ForInStep.done $u))\n  | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))\n  | .nestedBC        => ``(Pure.pure (DoResultBC.\u00abbreak\u00bb $u))\n  | .nestedPR        => unreachable!\n  | .nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abbreak\u00bb $u))\n  | .nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abbreak\u00bb $u))\n\ndef actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | .regular         => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))\n  | .forIn           => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))\n  | .forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | .nestedBC        => unreachable!\n  | .nestedPR        => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.\u00abpure\u00bb y $u)))\n  | .nestedSBC       => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.\u00abpureReturn\u00bb y $u)))\n  | .nestedPRBC      => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.\u00abpure\u00bb y $u)))\n\ndef seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  if action.getKind == ``Parser.Term.doDbgTrace then\n    let msg := action[1]\n    `(dbg_trace $msg; $k)\n  else if action.getKind == ``Parser.Term.doAssert then\n    let cond := action[1]\n    `(assert! $cond; $k)\n  else\n    let action \u2190 withRef action ``(($action : $((\u2190read).m) PUnit))\n    ``(Bind.bind $action (fun (_ : PUnit) => $k))\n\ndef declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do\n  let kind := decl.getKind\n  if kind == ``Parser.Term.doLet then\n    let letDecl := decl[2]\n    `(let $letDecl:letDecl; $k)\n  else if kind == ``Parser.Term.doLetRec then\n    let letRecToken := decl[0]\n    let letRecDecls := decl[1]\n    return mkNode ``Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]\n  else if kind == ``Parser.Term.doLetArrow then\n    let arg := decl[2]\n    if arg.getKind == ``Parser.Term.doIdDecl then\n      let id     := arg[0]\n      let type   := expandOptType id arg[1]\n      let doElem := arg[3]\n      -- `doElem` must be a `doExpr action`. See `doLetArrowToCode`\n      match isDoExpr? doElem with\n      | some action =>\n        let action \u2190 withRef action `(($action : $((\u2190 read).m) $type))\n        ``(Bind.bind $action (fun ($id:ident : $type) => $k))\n      | none        => Macro.throwErrorAt decl \"unexpected kind of `do` declaration\"\n    else\n      Macro.throwErrorAt decl \"unexpected kind of `do` declaration\"\n  else if kind == ``Parser.Term.doHave then\n    -- The `have` term is of the form  `\"have \" >> haveDecl >> optSemicolon termParser`\n    let args := decl.getArgs\n    let args := args ++ #[mkNullNode /- optional ';' -/, k]\n    return mkNode `Lean.Parser.Term.\u00abhave\u00bb args\n  else\n    Macro.throwErrorAt decl \"unexpected kind of `do` declaration\"\n\ndef reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do\n  match reassign with\n  | `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote \"invalid reassignment, value\") $rhs; $k)\n  | `(doElem| $e:term  := $rhs) => `(let $e:term  := ensure_type_of% $e $(quote \"invalid reassignment, value\") $rhs; $k)\n  | _ =>\n    -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode\n    Macro.throwErrorAt reassign \"unexpected kind of `do` reassignment\"\n\ndef mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do\n  if optIdent.isNone then\n    ``(if $cond then $thenBranch else $elseBranch)\n  else\n    let h := optIdent[0]\n    ``(if $h:ident : $cond then $thenBranch else $elseBranch)\n\ndef mkJoinPoint (j : Name) (ps : Array (Syntax \u00d7 Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do\n  let pTypes \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => do if useTypeOf then `(type_of% $id) else `(_)\n  let ps     := ps.map (\u00b7.1)\n  /-\n  We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.\n  By elaborating `$k` first, we \"learn\" more about `$body`'s type.\n  For example, consider the following example `do` expression\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x > 0 then\n    IO.println \"x is not zero\" -- Error is here\n  IO.mkRef true\n  ```\n  it is expanded into\n  ```\n  def f (x : Nat) : IO Unit := do\n  let jp (u : Unit) : IO _ :=\n    IO.mkRef true;\n  if x > 0 then\n    IO.println \"not zero\"\n    jp ()\n  else\n    jp ()\n  ```\n  If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit \u2192 IO (IO.Ref Bool)`.\n  Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit \u2192 IO Unit`.\n  Then, we get the expected type mismatch error at `IO.mkRef true`. -/\n  `(let_delayed $(\u2190 mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((\u2190 read).m) _ := $body; $k)\n\ndef mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=\n  Syntax.mkApp (mkIdentFrom ref j) args\n\npartial def toTerm (c : Code) : M Syntax := do\n  let term \u2190 go c\n  if let some ref := c.getRef? then\n    annotate ref term\n  else\n    return term\nwhere\n  go (c : Code) : M Syntax := do\n    match c with\n    | .return ref val     => withRef ref <| returnToTerm val\n    | .continue ref       => withRef ref continueToTerm\n    | .break ref          => withRef ref breakToTerm\n    | .action e           => actionTerminalToTerm e\n    | .joinpoint j ps b k => mkJoinPoint j ps (\u2190 toTerm b) (\u2190 toTerm k)\n    | .jmp ref j args     => return mkJmp ref j args\n    | .decl _ stx k       => declToTerm stx (\u2190 toTerm k)\n    | .reassign _ stx k   => reassignToTerm stx (\u2190 toTerm k)\n    | .seq stx k          => seqToTerm stx (\u2190 toTerm k)\n    | .ite ref _ o c t e  => withRef ref <| do mkIte o c (\u2190 toTerm t) (\u2190 toTerm e)\n    | .match ref genParam discrs optMotive alts =>\n      let mut termAlts := #[]\n      for alt in alts do\n        let rhs \u2190 toTerm alt.rhs\n        let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref \"|\", mkNullNode #[alt.patterns], mkAtomFrom alt.ref \"=>\", rhs]\n        termAlts := termAlts.push termAlt\n      let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]\n      return mkNode `Lean.Parser.Term.\u00abmatch\u00bb #[mkAtomFrom ref \"match\", genParam, optMotive, discrs, mkAtomFrom ref \"with\", termMatchAlts]\n\ndef run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax :=\n  toTerm code { m, returnType, kind, uvars }\n\n/-- Given\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   generate Kind. See comment at the beginning of the `ToTerm` namespace. -/\ndef mkNestedKind (a r bc : Bool) : Kind :=\n  match a, r, bc with\n  | true,  false, false => .regular\n  | false, true,  false => .regular\n  | false, false, true  => .nestedBC\n  | true,  true,  false => .nestedPR\n  | true,  false, true  => .nestedSBC\n  | false, true,  true  => .nestedSBC\n  | true,  true,  true  => .nestedPRBC\n  | false, false, false => unreachable!\n\ndef mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do\n  ToTerm.run code m returnType uvars (mkNestedKind a r bc)\n\n/-- Given a term `term` produced by `ToTerm.run`, pattern match on its result.\n   See comment at the beginning of the `ToTerm` namespace.\n\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   The result is a sequence of `doElem` -/\ndef matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do\n  let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)\n  let u \u2190 mkTuple uvars\n  match a, r, bc with\n  | true, false, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do $term:term))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; pure r.1))\n  | false, true, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; return r))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; return r.1))\n  | false, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | .break u => $u:term := u; break\n         | .continue u => $u:term := u; continue)\n  | true, true, false => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | .pure a u => $u:term := u; pure a\n         | .return b u => $u:term := u; return b)\n  | true, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | .pureReturn a u => $u:term := u; pure a\n         | .break u => $u:term := u; break\n         | .continue u => $u:term := u; continue)\n  | false, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | .pureReturn a u => $u:term := u; return a\n         | .break u => $u:term := u; break\n         | .continue u => $u:term := u; continue)\n  | true, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | .pure a u => $u:term := u; pure a\n         | .return a u => $u:term := u; return a\n         | .break u => $u:term := u; break\n         | .continue u => $u:term := u; continue)\n  | false, false, false => unreachable!\n\nend ToTerm\n\ndef isMutableLet (doElem : Syntax) : Bool :=\n  let kind := doElem.getKind\n  (kind == ``doLetArrow || kind == ``doLet || kind == ``doLetElse)\n  &&\n  !doElem[1].isNone\n\nnamespace ToCodeBlock\n\nstructure Context where\n  ref         : Syntax\n  /-- Syntax representing the monad associated with the do notation. -/\n  m           : Syntax\n  /-- Syntax to reference the result of the monadic computation performed by the do notation. -/\n  returnType  : Syntax\n  mutableVars : VarSet := {}\n  insideFor   : Bool := false\n\nabbrev M := ReaderT Context TermElabM\n\ndef withNewMutableVars {\u03b1} (newVars : Array Var) (mutable : Bool) (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x\n\ndef checkReassignable (xs : Array Var) : M Unit := do\n  let throwInvalidReassignment (x : Name) : M Unit :=\n    throwError \"`{x.simpMacroScopes}` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intent to mutate but define `{x.simpMacroScopes}`, consider using `let {x.simpMacroScopes}` instead\"\n  let ctx \u2190 read\n  for x in xs do\n    unless ctx.mutableVars.contains x.getId do\n      throwInvalidReassignment x.getId\n\ndef checkNotShadowingMutable (xs : Array Var) : M Unit := do\n  let throwInvalidShadowing (x : Name) : M Unit :=\n    throwError \"mutable variable `{x.simpMacroScopes}` cannot be shadowed\"\n  let ctx \u2190 read\n  for x in xs do\n    if ctx.mutableVars.contains x.getId then\n      withRef x <| throwInvalidShadowing x.getId\n\ndef withFor {\u03b1} (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => { ctx with insideFor := true }) x\n\nstructure ToForInTermResult where\n  uvars      : Array Var\n  term       : Syntax\n\ndef mkForInBody  (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do\n  let ctx \u2190 read\n  let uvars := forInBody.uvars\n  let uvars := varSetToArray uvars\n  let term \u2190 liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)\n  return \u27e8uvars, term\u27e9\n\ndef ensureInsideFor : M Unit :=\n  unless (\u2190 read).insideFor do\n    throwError \"invalid `do` element, it must be inside `for`\"\n\ndef ensureEOS (doElems : List Syntax) : M Unit :=\n  unless doElems.isEmpty do\n    throwError \"must be last element in a `do` sequence\"\n\nvariable (baseId : Name) in\nprivate partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax \u2192 StateT (List Syntax) M Syntax\n  | stx@(Syntax.node i k args) =>\n    if k == choiceKind then do\n      -- choice node: check that lifts are consistent\n      let alts \u2190 stx.getArgs.mapM (expandLiftMethodAux inQuot inBinder \u00b7 |>.run [])\n      let (_, lifts) := alts[0]!\n      unless alts.all (\u00b7.2 == lifts) do\n        throwErrorAt stx \"cannot lift `(<- ...)` over inconsistent syntax variants, consider lifting out the binding manually\"\n      modify (\u00b7 ++ lifts)\n      return .node i k (alts.map (\u00b7.1))\n    else if liftMethodDelimiter k then\n      return stx\n    else if k == ``Parser.Term.liftMethod && !inQuot then withFreshMacroScope do\n      if inBinder then\n        throwErrorAt stx \"cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`\"\n      let term := args[1]!\n      let term \u2190 expandLiftMethodAux inQuot inBinder term\n      -- keep name deterministic across choice branches\n      let id \u2190 mkIdentFromRef (.num baseId (\u2190 get).length)\n      let auxDoElem : Syntax \u2190 `(doElem| let $id:ident \u2190 $term:term)\n      modify fun s => s ++ [auxDoElem]\n      return id\n    else do\n      let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot\n      let inBinder   := inBinder || (!inQuot && liftMethodForbiddenBinder stx)\n      let args \u2190 args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)\n      return Syntax.node i k args\n  | stx => return stx\n\ndef expandLiftMethod (doElem : Syntax) : M (List Syntax \u00d7 Syntax) := do\n  if !hasLiftMethod doElem then\n    return ([], doElem)\n  else\n    let baseId \u2190 withFreshMacroScope (MonadQuotation.addMacroScope `__do_lift)\n    let (doElem, doElemsNew) \u2190 (expandLiftMethodAux baseId false false doElem).run []\n    return (doElemsNew, doElem)\n\ndef checkLetArrowRHS (doElem : Syntax) : M Unit := do\n  let kind := doElem.getKind\n  if kind == ``Parser.Term.doLetArrow ||\n     kind == ``Parser.Term.doLet ||\n     kind == ``Parser.Term.doLetRec ||\n     kind == ``Parser.Term.doHave ||\n     kind == ``Parser.Term.doReassign ||\n     kind == ``Parser.Term.doReassignArrow then\n    throwErrorAt doElem \"invalid kind of value `{kind}` in an assignment\"\n\n/-- Generate `CodeBlock` for `doReturn` which is of the form\n   ```\n   \"return \" >> optional termParser\n   ```\n   `doElems` is only used for sanity checking. -/\ndef doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do\n  ensureEOS doElems\n  let argOpt := doReturn[1]\n  let arg \u2190 if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]\n  return mkReturn (\u2190 getRef) arg\n\nstructure Catch where\n  x         : Syntax\n  optType   : Syntax\n  codeBlock : CodeBlock\n\ndef getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet :=\n  let ws := tryCode.uvars\n  let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws\n  let ws := match finallyCode? with\n    | none   => ws\n    | some c => union c.uvars ws\n  ws\n\ndef tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code \u2192 Bool) : Bool :=\n  p tryCode.code ||\n  catches.any (fun \u00abcatch\u00bb => p \u00abcatch\u00bb.codeBlock.code) ||\n  match finallyCode? with\n  | none => false\n  | some finallyCode => p finallyCode.code\n\nmutual\n  /-- \"Concatenate\" `c` with `doSeqToCode doElems` -/\n  partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=\n    match doElems with\n    | [] => pure c\n    | nextDoElem :: _  => do\n      let k \u2190 doSeqToCode doElems\n      let ref := nextDoElem\n      concat c ref none k\n\n  /-- Generate `CodeBlock` for `doLetArrow; doElems`\n     `doLetArrow` is of the form\n     ```\n     \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\n     ```\n     where\n     ```\n     def doIdDecl   := leading_parser ident >> optType >> leftArrow >> doElemParser\n     def doPatDecl  := leading_parser termParser >> leftArrow >> doElemParser >> optional (\" | \" >> doSeq)\n     ```\n  -/\n  partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let decl    := doLetArrow[2]\n    if decl.getKind == ``Parser.Term.doIdDecl then\n      let y := decl[0]\n      checkNotShadowingMutable #[y]\n      let doElem := decl[3]\n      let k \u2190 withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)\n      match isDoExpr? doElem with\n      | some _      => return mkVarDeclCore #[y] doLetArrow k\n      | none =>\n        checkLetArrowRHS doElem\n        let c \u2190 doSeqToCode [doElem]\n        match doElems with\n        | []       => pure c\n        | kRef::_  => concat c kRef y k\n    else if decl.getKind == ``Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 if isMutableLet doLetArrow then\n          `(do let%$doLetArrow __discr \u2190 $doElem; let%$doLetArrow mut $pattern:term := __discr)\n        else\n          `(do let%$doLetArrow __discr \u2190 $doElem; let%$doLetArrow $pattern:term := __discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        let contSeq \u2190 if isMutableLet doLetArrow then\n          let vars \u2190 (\u2190 getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var)\n          pure (vars ++ doElems.toArray)\n        else\n          pure doElems.toArray\n        let contSeq := mkDoSeq contSeq\n        let elseSeq := optElse[1]\n        let auxDo \u2190 `(do let%$doLetArrow __discr \u2190 $doElem; match%$doLetArrow __discr with | $pattern:term => $contSeq | _ => $elseSeq)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n    else\n      throwError \"unexpected kind of `do` declaration\"\n\n  partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    -- \"let \" >> optional \"mut \" >> termParser >> \" := \" >> termParser >> checkColGt >> \" | \" >> doSeq\n    let pattern := doLetElse[2]\n    let val     := doLetElse[4]\n    let elseSeq := doLetElse[6]\n    let contSeq \u2190 if isMutableLet doLetElse then\n      let vars \u2190 (\u2190 getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var)\n      pure (vars ++ doElems.toArray)\n    else\n      pure doElems.toArray\n    let contSeq := mkDoSeq contSeq\n    let auxDo \u2190 `(do let __discr := $val; match __discr with | $pattern:term => $contSeq | _ => $elseSeq)\n    doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n\n  /-- Generate `CodeBlock` for `doReassignArrow; doElems`\n     `doReassignArrow` is of the form\n     ```\n     (doIdDecl <|> doPatDecl)\n     ```\n  -/\n  partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let decl := doReassignArrow[0]\n    if decl.getKind == ``Parser.Term.doIdDecl then\n      let doElem := decl[3]\n      let y      := decl[0]\n      let auxDo \u2190 `(do let r \u2190 $doElem; $y:ident := r)\n      doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n    else if decl.getKind == ``Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 `(do let __discr \u2190 $doElem; $pattern:term := __discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        throwError \"reassignment with `|` (i.e., \\\"else clause\\\") is not currently supported\"\n    else\n      throwError \"unexpected kind of `do` reassignment\"\n\n  /-- Generate `CodeBlock` for `doIf; doElems`\n     `doIf` is of the form\n     ```\n     \"if \" >> optIdent >> termParser >> \" then \" >> doSeq\n      >> many (group (try (group (\" else \" >> \" if \")) >> optIdent >> termParser >> \" then \" >> doSeq))\n      >> optional (\" else \" >> doSeq)\n     ```  -/\n  partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let view := mkDoIfView doIf\n    let thenBranch \u2190 doSeqToCode (getDoSeqElems view.thenBranch)\n    let elseBranch \u2190 doSeqToCode (getDoSeqElems view.elseBranch)\n    let ite \u2190 mkIte view.ref view.optIdent view.cond thenBranch elseBranch\n    concatWith ite doElems\n\n  /-- Generate `CodeBlock` for `doUnless; doElems`\n     `doUnless` is of the form\n     ```\n     \"unless \" >> termParser >> \"do \" >> doSeq\n     ```  -/\n  partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do\n    let cond  := doUnless[1]\n    let doSeq := doUnless[3]\n    let body \u2190 doSeqToCode (getDoSeqElems doSeq)\n    let unlessCode \u2190 liftMacroM <| mkUnless cond body\n    concatWith unlessCode doElems\n\n  /-- Generate `CodeBlock` for `doFor; doElems`\n     `doFor` is of the form\n     ```\n     def doForDecl := leading_parser termParser >> \" in \" >> withForbidden \"do\" termParser\n     def doFor := leading_parser \"for \" >> sepBy1 doForDecl \", \" >> \"do \" >> doSeq\n     ```\n  -/\n  partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let doForDecls := doFor[1].getSepArgs\n    if doForDecls.size > 1 then\n      /-\n        Expand\n        ```\n        for x in xs, y in ys do\n          body\n        ```\n        into\n        ```\n        let s := toStream ys\n        for x in xs do\n          match Stream.next? s with\n          | none => break\n          | some (y, s') =>\n            s := s'\n            body\n        ```\n      -/\n      -- Extract second element\n      let doForDecl := doForDecls[1]!\n      unless doForDecl[0].isNone do\n        throwErrorAt doForDecl[0] \"the proof annotation here has not been implemented yet\"\n      let y  := doForDecl[1]\n      let ys := doForDecl[3]\n      let doForDecls := doForDecls.eraseIdx 1\n      let body := doFor[3]\n      withFreshMacroScope do\n        /- Recall that `@` (explicit) disables `coeAtOutParam`.\n           We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/\n        let toStreamApp \u2190 withRef ys `(@toStream _ _ _ $ys)\n        let auxDo \u2190\n          `(do let mut s := $toStreamApp:term\n               for $doForDecls:doForDecl,* do\n                 match @Stream.next? _ _ _ s with\n                 | none => break\n                 | some ($y, s') =>\n                   s := s'\n                   do $body)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n    else withRef doFor do\n      let h?        := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0]\n      let x         := doForDecls[0]![1]\n      withRef x <| checkNotShadowingMutable (\u2190 getPatternVarsEx x)\n      let xs        := doForDecls[0]![3]\n      let forElems  := getDoSeqElems doFor[3]\n      let forInBodyCodeBlock \u2190 withFor (doSeqToCode forElems)\n      let \u27e8uvars, forInBody\u27e9 \u2190 mkForInBody x forInBodyCodeBlock\n      let ctx \u2190 read\n      -- semantic no-op that replaces the `uvars`' position information (which all point inside the loop)\n      -- with that of the respective mutable declarations outside the loop, which allows the language\n      -- server to identify them as conceptually identical variables\n      let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v\n      let uvarsTuple \u2190 liftMacroM do mkTuple uvars\n      if hasReturn forInBodyCodeBlock.code then\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let optType \u2190 `(Option $((\u2190 read).returnType))\n        let forInTerm \u2190 if let some h := h? then\n          annotate doFor\n            (\u2190 `(for_in'% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody))\n        else\n          annotate doFor\n            (\u2190 `(for_in% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => let r := r.2; $forInBody))\n        let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                         $uvarsTuple:term := r.2;\n                         match r.1 with\n                         | none => Pure.pure (ensure_expected_type% \"type mismatch, `for`\" PUnit.unit)\n                         | some a => return ensure_expected_type% \"type mismatch, `for`\" a)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n      else\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 if let some h := h? then\n          annotate doFor (\u2190 `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody))\n        else\n          annotate doFor (\u2190 `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody))\n        if doElems.isEmpty then\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                           $uvarsTuple:term := r;\n                           Pure.pure (ensure_expected_type% \"type mismatch, `for`\" PUnit.unit))\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n        else\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term; $uvarsTuple:term := r)\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n\n  /-- Generate `CodeBlock` for `doMatch; doElems` -/\n  partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref       := doMatch\n    let genParam  := doMatch[1]\n    let optMotive := doMatch[2]\n    let discrs    := doMatch[3]\n    let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`\n    let matchAlts \u2190 matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (\u2190 liftMacroM <| expandMatchAlt matchAlt)\n    let alts \u2190  matchAlts.mapM fun matchAlt => do\n      let patterns := matchAlt[1][0]\n      let vars \u2190 getPatternsVarsEx patterns.getSepArgs\n      withRef patterns <| checkNotShadowingMutable vars\n      let rhs  := matchAlt[3]\n      let rhs \u2190 doSeqToCode (getDoSeqElems rhs)\n      pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }\n    let matchCode \u2190 mkMatch ref genParam discrs optMotive alts\n    concatWith matchCode doElems\n\n  /--\n    Generate `CodeBlock` for `doTry; doElems`\n    ```\n    def doTry := leading_parser \"try \" >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally\n    def doCatch      := leading_parser \"catch \" >> binderIdent >> optional (\":\" >> termParser) >> darrow >> doSeq\n    def doCatchMatch := leading_parser \"catch \" >> doMatchAlts\n    def doFinally    := leading_parser \"finally \" >> doSeq\n    ```\n  -/\n  partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let tryCode \u2190 doSeqToCode (getDoSeqElems doTry[1])\n    let optFinally := doTry[3]\n    let catches \u2190 doTry[2].getArgs.mapM fun catchStx : Syntax => do\n      if catchStx.getKind == ``Parser.Term.doCatch then\n        let x       := catchStx[1]\n        if x.isIdent then\n          withRef x <| checkNotShadowingMutable #[x]\n        let optType := catchStx[2]\n        let c \u2190 doSeqToCode (getDoSeqElems catchStx[4])\n        return { x := x, optType := optType, codeBlock := c : Catch }\n      else if catchStx.getKind == ``Parser.Term.doCatchMatch then\n        let matchAlts := catchStx[1]\n        let x \u2190 `(ex)\n        let auxDo \u2190 `(do match ex with $matchAlts)\n        let c \u2190 doSeqToCode (getDoSeqElems (getDoSeq auxDo))\n        return { x := x, codeBlock := c, optType := mkNullNode : Catch }\n      else\n        throwError \"unexpected kind of `catch`\"\n    let finallyCode? \u2190 if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])\n    if catches.isEmpty && finallyCode?.isNone then\n      throwError \"invalid `try`, it must have a `catch` or `finally`\"\n    let ctx \u2190 read\n    let ws    := getTryCatchUpdatedVars tryCode catches finallyCode?\n    let uvars := varSetToArray ws\n    let a     := tryCatchPred tryCode catches finallyCode? hasTerminalAction\n    let r     := tryCatchPred tryCode catches finallyCode? hasReturn\n    let bc    := tryCatchPred tryCode catches finallyCode? hasBreakContinue\n    let toTerm (codeBlock : CodeBlock) : M Syntax := do\n      let codeBlock \u2190 liftM $ extendUpdatedVars codeBlock ws\n      liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m ctx.returnType uvars a r bc\n    let term \u2190 toTerm tryCode\n    let term \u2190 catches.foldlM (init := term) fun term \u00abcatch\u00bb => do\n      let catchTerm \u2190 toTerm \u00abcatch\u00bb.codeBlock\n      if catch.optType.isNone then\n        annotate doTry (\u2190 ``(MonadExcept.tryCatch $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm)))\n      else\n        let type := \u00abcatch\u00bb.optType[1]\n        annotate doTry (\u2190 ``(tryCatchThe $type $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm)))\n    let term \u2190 match finallyCode? with\n      | none             => pure term\n      | some finallyCode => withRef optFinally do\n        unless finallyCode.uvars.isEmpty do\n          throwError \"`finally` currently does not support reassignments\"\n        if hasBreakContinueReturn finallyCode.code then\n          throwError \"`finally` currently does `return`, `break`, nor `continue`\"\n        let finallyTerm \u2190 liftMacroM <| ToTerm.run finallyCode.code ctx.m ctx.returnType {} ToTerm.Kind.regular\n        annotate doTry (\u2190 ``(tryFinally $term $finallyTerm))\n    let doElemsNew \u2190 liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc\n    doSeqToCode (doElemsNew ++ doElems)\n\n  partial def doSeqToCode : List Syntax \u2192 M CodeBlock\n    | [] => do liftMacroM mkPureUnitAction\n    | doElem::doElems => withIncRecDepth <| withRef doElem do\n      checkMaxHeartbeats \"`do`-expander\"\n      match (\u2190 liftMacroM <| expandMacro? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n      match (\u2190 liftMacroM <| expandDoIf? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n        let (liftedDoElems, doElem) \u2190 expandLiftMethod doElem\n        if !liftedDoElems.isEmpty then\n          doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)\n        else\n          let ref := doElem\n          let k := doElem.getKind\n          if k == ``Parser.Term.doLet then\n            let vars \u2190 getDoLetVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)\n          else if k == ``Parser.Term.doHave then\n            let vars \u2190 getDoHaveVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Parser.Term.doLetRec then\n            let vars \u2190 getDoLetRecVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Parser.Term.doReassign then\n            let vars \u2190 getDoReassignVars doElem\n            checkReassignable vars\n            let k \u2190 doSeqToCode doElems\n            mkReassignCore vars doElem k\n          else if k == ``Parser.Term.doLetArrow then\n            doLetArrowToCode doElem doElems\n          else if k == ``Parser.Term.doLetElse then\n            doLetElseToCode doElem doElems\n          else if k == ``Parser.Term.doReassignArrow then\n            doReassignArrowToCode doElem doElems\n          else if k == ``Parser.Term.doIf then\n            doIfToCode doElem doElems\n          else if k == ``Parser.Term.doUnless then\n            doUnlessToCode doElem doElems\n          else if k == ``Parser.Term.doFor then withFreshMacroScope do\n            doForToCode doElem doElems\n          else if k == ``Parser.Term.doMatch then\n            doMatchToCode doElem doElems\n          else if k == ``Parser.Term.doTry then\n            doTryToCode doElem doElems\n          else if k == ``Parser.Term.doBreak then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkBreak ref\n          else if k == ``Parser.Term.doContinue then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkContinue ref\n          else if k == ``Parser.Term.doReturn then\n            doReturnToCode doElem doElems\n          else if k == ``Parser.Term.doDbgTrace then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Parser.Term.doAssert then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Parser.Term.doNested then\n            let nestedDoSeq := doElem[1]\n            doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)\n          else if k == ``Parser.Term.doExpr then\n            let term := doElem[0]\n            if doElems.isEmpty then\n              return mkTerminalAction term\n            else\n              return mkSeq term (\u2190 doSeqToCode doElems)\n          else\n            throwError \"unexpected do-element of kind {doElem.getKind}:\\n{doElem}\"\nend\n\ndef run (doStx : Syntax) (m : Syntax) (returnType : Syntax) : TermElabM CodeBlock :=\n  (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType }\n\nend ToCodeBlock\n\n@[builtin_term_elab \u00abdo\u00bb] def elabDo : TermElab := fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  let bindInfo \u2190 extractBind expectedType?\n  let m \u2190 Term.exprToSyntax bindInfo.m\n  let returnType \u2190 Term.exprToSyntax bindInfo.returnType\n  let codeBlock \u2190 ToCodeBlock.run stx m returnType\n  let stxNew \u2190 liftMacroM <| ToTerm.run codeBlock.code m returnType\n  trace[Elab.do] stxNew\n  withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType\n\nend Do\n\nbuiltin_initialize registerTraceClass `Elab.do\n\nprivate def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do\n  let stx := stx.setKind newKind\n  withRef stx `(do $stx:doElem)\n\n@[builtin_macro Lean.Parser.Term.termFor]\ndef expandTermFor : Macro := toDoElem ``Parser.Term.doFor\n\n@[builtin_macro Lean.Parser.Term.termTry]\ndef expandTermTry : Macro := toDoElem ``Parser.Term.doTry\n\n@[builtin_macro Lean.Parser.Term.termUnless]\ndef expandTermUnless : Macro := toDoElem ``Parser.Term.doUnless\n\n@[builtin_macro Lean.Parser.Term.termReturn]\ndef expandTermReturn : Macro := toDoElem ``Parser.Term.doReturn\n\nend Lean.Elab.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/Lean/Elab/Do.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434084342705, "lm_q2_score": 0.027169230058730273, "lm_q1q2_score": 0.004297475055763085}}
{"text": "/-\nCopyright (c) 2020 Wojciech Nawrocki. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki, Leonardo de Moura, Sebastian Ullrich\n-/\nimport Lean.Data.Position\nimport Lean.Data.OpenDecl\nimport Lean.MetavarContext\nimport Lean.Environment\nimport Lean.Data.Json\n\nnamespace Lean.Elab\n\n/-- Context after executing `liftTermElabM`.\n   Note that the term information collected during elaboration may contain metavariables, and their\n   assignments are stored at `mctx`. -/\nstructure ContextInfo where\n  env           : Environment\n  fileMap       : FileMap\n  mctx          : MetavarContext := {}\n  options       : Options        := {}\n  currNamespace : Name           := Name.anonymous\n  openDecls     : List OpenDecl  := []\n  ngen          : NameGenerator -- We must save the name generator to implement `ContextInfo.runMetaM` and making we not create `MVarId`s used in `mctx`.\n\n/-- Base structure for `TermInfo`, `CommandInfo` and `TacticInfo`. -/\nstructure ElabInfo where\n  /-- The name of the elaborator that created this info. -/\n  elaborator : Name\n  /-- The piece of syntax that the elaborator created this info for.\n  Note that this also implicitly stores the code position in the syntax's SourceInfo. -/\n  stx : Syntax\n  deriving Inhabited\n\nstructure TermInfo extends ElabInfo where\n  lctx : LocalContext -- The local context when the term was elaborated.\n  expectedType? : Option Expr\n  expr : Expr\n  isBinder : Bool := false\n  deriving Inhabited\n\nstructure CommandInfo extends ElabInfo where\n  deriving Inhabited\n\n/-- A completion is an item that appears in the [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense)\nbox that appears as you type. -/\ninductive CompletionInfo where\n  | dot (termInfo : TermInfo) (field? : Option Syntax) (expectedType? : Option Expr)\n  | id (stx : Syntax) (id : Name) (danglingDot : Bool) (lctx : LocalContext) (expectedType? : Option Expr)\n  | dotId (stx : Syntax) (id : Name) (lctx : LocalContext) (expectedType? : Option Expr)\n  | fieldId (stx : Syntax) (id : Name) (lctx : LocalContext) (structName : Name)\n  | namespaceId (stx : Syntax)\n  | option (stx : Syntax)\n  | endSection (stx : Syntax) (scopeNames : List String)\n  | tactic (stx : Syntax) (goals : List MVarId)\n  -- TODO `import`\n\n/-- Info for an option reference (e.g. in `set_option`). -/\nstructure OptionInfo where\n  stx : Syntax\n  optionName : Name\n  declName : Name\n\nstructure FieldInfo where\n  /-- Name of the projection. -/\n  projName  : Name\n  /-- Name of the field as written. -/\n  fieldName : Name\n  lctx      : LocalContext\n  val       : Expr\n  stx       : Syntax\n  deriving Inhabited\n\n/-- The information needed to render the tactic state in the infoview.\n\n    We store the list of goals before and after the execution of a tactic.\n    We also store the metavariable context at each time since we want metavariables\n    unassigned at tactic execution time to be displayed as `?m...`. -/\nstructure TacticInfo extends ElabInfo where\n  mctxBefore  : MetavarContext\n  goalsBefore : List MVarId\n  mctxAfter   : MetavarContext\n  goalsAfter  : List MVarId\n  deriving Inhabited\n\nstructure MacroExpansionInfo where\n  lctx   : LocalContext -- The local context when the macro was expanded.\n  stx    : Syntax\n  output : Syntax\n  deriving Inhabited\n\n/-- Dynamic info for custom use cases. -/\nstructure CustomInfo where\n  stx : Syntax\n  value : Dynamic\n\n/-- An info that represents a user-widget.\nUser-widgets are custom pieces of code that run on the editor client.\nYou can learn about user widgets at `src/Lean/Widget/UserWidget`\n-/\nstructure UserWidgetInfo where\n  stx : Syntax\n  /-- Id of `WidgetSource` object to use. -/\n  widgetId : Name\n  /-- Json representing the props to be loaded in to the component. -/\n  props : Json\n  deriving Inhabited\n\n/--\nSpecifies that the given free variables should be considered semantically identical.\nThe free variable `baseId` might not be in the current local context\nbecause it has been cleared.\nUsed for e.g. connecting variables before and after `match` generalization.\n-/\nstructure FVarAliasInfo where\n  userName : Name\n  id     : FVarId\n  baseId : FVarId\n\n/--\nContains the syntax of an identifier which is part of a field redeclaration, like:\n```\nstructure Foo := x : Nat\nstructure Bar extends Foo :=\n  x := 0\n--^ here\n```\n-/\nstructure FieldRedeclInfo where\n  stx : Syntax\n\n/-- Header information for a node in `InfoTree`. -/\ninductive Info where\n  | ofTacticInfo (i : TacticInfo)\n  | ofTermInfo (i : TermInfo)\n  | ofCommandInfo (i : CommandInfo)\n  | ofMacroExpansionInfo (i : MacroExpansionInfo)\n  | ofOptionInfo (i : OptionInfo)\n  | ofFieldInfo (i : FieldInfo)\n  | ofCompletionInfo (i : CompletionInfo)\n  | ofUserWidgetInfo (i : UserWidgetInfo)\n  | ofCustomInfo (i : CustomInfo)\n  | ofFVarAliasInfo (i : FVarAliasInfo)\n  | ofFieldRedeclInfo (i : FieldRedeclInfo)\n  deriving Inhabited\n\n/-- The InfoTree is a structure that is generated during elaboration and used\n    by the language server to look up information about objects at particular points\n    in the Lean document. For example, tactic information and expected type information in\n    the infoview and information about completions.\n\n    The infotree consists of nodes which may have child nodes. Each node\n    has an `Info` object that contains details about what kind of information\n    is present. Each `Info` object also contains a `Syntax` instance, this is used to\n    map positions in the Lean document to particular info objects.\n\n    An example of a function that extracts information from an infotree for a given\n    position is `InfoTree.goalsAt?` which finds `TacticInfo`.\n\n    Information concerning expressions requires that a context also be saved.\n    `context` nodes store a local context that is used to process expressions\n    in nodes below.\n\n    Because the info tree is generated during elaboration, some parts of the infotree\n    for a particular piece of syntax may not be ready yet. Hence InfoTree supports metavariable-like\n    `hole`s which are filled in later in the same way that unassigned metavariables are.\n-/\ninductive InfoTree where\n  /-- The context object is created by `liftTermElabM` at `Command.lean` -/\n  | context (i : ContextInfo) (t : InfoTree)\n  /-- The children contain information for nested term elaboration and tactic evaluation -/\n  | node (i : Info) (children : PersistentArray InfoTree)\n  /-- The elaborator creates holes (aka metavariables) for tactics and postponed terms -/\n  | hole (mvarId : MVarId)\n  deriving Inhabited\n\n/-- This structure is the state that is being used to build an InfoTree object.\nDuring elaboration, some parts of the info tree may be `holes` which need to be filled later.\nThe `assignments` field is used to assign these holes.\nThe `trees` field is a list of pending child trees for the infotree node currently being built.\n\nYou should not need to use `InfoState` directly, instead infotrees should be built with the help of the methods here\nsuch as `pushInfoLeaf` to create leaf nodes and `withInfoContext` to create a nested child node.\n\nTo see how `trees` is used, look at the function body of `withInfoContext'`.\n-/\nstructure InfoState where\n  /-- Whether info trees should be recorded. -/\n  enabled    : Bool := true\n  /-- Map from holes in the infotree to child infotrees. -/\n  assignment : PersistentHashMap MVarId InfoTree := {}\n  /-- Pending child trees of a node. -/\n  trees      : PersistentArray InfoTree := {}\n  deriving Inhabited\n\nclass MonadInfoTree (m : Type \u2192 Type)  where\n  getInfoState    : m InfoState\n  modifyInfoState : (InfoState \u2192 InfoState) \u2192 m Unit\n\nexport MonadInfoTree (getInfoState modifyInfoState)\n\ninstance [MonadLift m n] [MonadInfoTree m] : MonadInfoTree n where\n  getInfoState      := liftM (getInfoState : m _)\n  modifyInfoState f := liftM (modifyInfoState f : m _)\n\ndef setInfoState [MonadInfoTree m] (s : InfoState) : m Unit :=\n  modifyInfoState fun _ => s\n\nend Lean.Elab\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/InfoTree/Types.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1259227582746744, "lm_q2_score": 0.03358950698030741, "lm_q1q2_score": 0.004229683368046738}}
{"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.meta.smt.congruence_closure\nimport init.meta.attribute init.meta.simp_tactic\nimport init.meta.interactive_base init.meta.derive\nopen tactic\n\n/-- Heuristic instantiation lemma -/\nmeta constant hinst_lemma : Type\n\nmeta constant hinst_lemmas : Type\n\n/-- `mk_core m e as_simp`, m is used to decide which definitions will be unfolded in patterns.\n   If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion\n   as a pattern. -/\nmeta constant hinst_lemma.mk_core           : transparency \u2192 expr \u2192 bool \u2192 tactic hinst_lemma\nmeta constant hinst_lemma.mk_from_decl_core : transparency \u2192 name \u2192 bool \u2192 tactic hinst_lemma\nmeta constant hinst_lemma.pp                : hinst_lemma \u2192 tactic format\nmeta constant hinst_lemma.id                : hinst_lemma \u2192 name\n\nmeta instance : has_to_tactic_format hinst_lemma :=\n\u27e8hinst_lemma.pp\u27e9\n\nmeta def hinst_lemma.mk (h : expr) : tactic hinst_lemma :=\nhinst_lemma.mk_core reducible h ff\n\nmeta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma :=\nhinst_lemma.mk_from_decl_core reducible h ff\n\nmeta constant hinst_lemmas.mk              : hinst_lemmas\nmeta constant hinst_lemmas.add             : hinst_lemmas \u2192 hinst_lemma \u2192 hinst_lemmas\nmeta constant hinst_lemmas.fold {\u03b1 : Type} : hinst_lemmas \u2192 \u03b1 \u2192 (hinst_lemma \u2192 \u03b1 \u2192 \u03b1) \u2192 \u03b1\nmeta constant hinst_lemmas.merge           : hinst_lemmas \u2192 hinst_lemmas \u2192 hinst_lemmas\n\nmeta def mk_hinst_singleton : hinst_lemma \u2192 hinst_lemmas :=\nhinst_lemmas.add hinst_lemmas.mk\n\nmeta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format :=\nlet tac := s.fold (return format.nil)\n    (\u03bb h tac, do\n      hpp \u2190 h.pp,\n      r   \u2190 tac,\n      if r.is_nil then return hpp\n      else return format!\"{r},\\n{hpp}\")\nin do\n  r \u2190 tac,\n  return $ format.cbrace (format.group r)\n\nmeta instance : has_to_tactic_format hinst_lemmas :=\n\u27e8hinst_lemmas.pp\u27e9\n\nopen tactic\n\nprivate meta def add_lemma (m : transparency) (as_simp : bool) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas :=\ndo h \u2190 hinst_lemma.mk_from_decl_core m h as_simp, return $ hs.add h\n\nmeta def to_hinst_lemmas_core (m : transparency) : bool \u2192 list name \u2192 hinst_lemmas \u2192 tactic hinst_lemmas\n| as_simp []      hs := return hs\n| as_simp (n::ns) hs :=\n  let add n := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns\n  in do\n  /- First check if n is the name of a function with equational lemmas associated with it -/\n  eqns   \u2190 tactic.get_eqn_lemmas_for tt n,\n  match eqns with\n  | []  := do\n    /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/\n    add n\n  | _   := do\n    p \u2190 is_prop_decl n,\n    if p then add n /- n is a proposition -/\n    else do\n      /- Add equational lemmas to resulting hinst_lemmas -/\n      new_hs \u2190 to_hinst_lemmas_core tt eqns hs,\n      to_hinst_lemmas_core as_simp ns new_hs\n  end\n\nmeta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command :=\ndo let t := `(user_attribute hinst_lemmas),\n   let v := `({name     := attr_name,\n               descr    := \"hinst_lemma attribute\",\n               after_set := some $ \u03bb n _ _,\n                 to_hinst_lemmas_core reducible as_simp [n] hinst_lemmas.mk >> skip <|>\n                 fail format!\"invalid ematch lemma '{n}'\",\n               -- allow unsetting\n               before_unset := some $ \u03bb _ _, skip,\n               cache_cfg := {\n                 mk_cache := \u03bb ns, to_hinst_lemmas_core reducible as_simp ns hinst_lemmas.mk,\n                 dependencies := [`reducibility]}} : user_attribute hinst_lemmas),\n   add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff),\n   attribute.register attr_name\n\nmeta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name \u2192 command\n| []      := skip\n| (n::ns) :=\n  (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns)\n  <|>\n  (do type \u2190 infer_type (expr.const n []),\n      let expected := `(user_attribute),\n      (is_def_eq type expected\n       <|> fail format!\"failed to create hinst_lemma attribute '{n}', declaration already exists and has different type.\"),\n      mk_hinst_lemma_attrs_core ns)\n\nmeta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name \u2192 hinst_lemmas \u2192 tactic hinst_lemmas\n| []            hs := return hs\n| (attr::attrs) hs := do\n  ns     \u2190 attribute.get_instances attr,\n  new_hs \u2190 to_hinst_lemmas_core m as_simp ns hs,\n  merge_hinst_lemma_attrs attrs new_hs\n\n/--\nCreate a new \"cached\" attribute (attr_name : user_attribute hinst_lemmas).\nIt also creates \"cached\" attributes for each attr_names and simp_attr_names if they have not been defined\nyet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with\n    attr_name, attrs_name, and simp_attr_names.\nFor the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern.\n-/\nmeta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command :=\ndo mk_hinst_lemma_attrs_core ff attr_names,\n   mk_hinst_lemma_attrs_core tt simp_attr_names,\n   let t  := `(user_attribute hinst_lemmas),\n   let v  := `({name     := attr_name,\n                descr    := \"hinst_lemma attribute set\",\n                after_set := some $ \u03bb n _ _,\n                  to_hinst_lemmas_core reducible ff [n] hinst_lemmas.mk >> skip <|>\n                  fail format!\"invalid ematch lemma '{n}'\",\n                -- allow unsetting\n                before_unset := some $ \u03bb _ _, skip,\n                cache_cfg := {\n                  mk_cache := \u03bb ns, do {\n                    hs\u2081 \u2190 to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk,\n                    hs\u2082 \u2190 merge_hinst_lemma_attrs reducible ff attr_names hs\u2081,\n                    merge_hinst_lemma_attrs reducible tt simp_attr_names hs\u2082},\n                  dependencies := [`reducibility] ++ attr_names ++ simp_attr_names}} : user_attribute hinst_lemmas),\n   add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff),\n   attribute.register attr_name\n\nmeta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas :=\nget_attribute_cache_dyn attr_name\n\nstructure ematch_config :=\n(max_instances  : nat := 10000)\n(max_generation : nat := 10)\n\n/- Ematching -/\nmeta constant ematch_state             : Type\nmeta constant ematch_state.mk          : ematch_config \u2192 ematch_state\nmeta constant ematch_state.internalize : ematch_state \u2192 expr \u2192 tactic ematch_state\n\nnamespace tactic\nmeta constant ematch_core       : transparency \u2192 cc_state \u2192 ematch_state \u2192 hinst_lemma \u2192 expr \u2192 tactic (list (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state)\nmeta constant ematch_all_core   : transparency \u2192 cc_state \u2192 ematch_state \u2192 hinst_lemma \u2192 bool \u2192 tactic (list (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state)\n\nmeta def ematch : cc_state \u2192 ematch_state \u2192 hinst_lemma \u2192 expr \u2192 tactic (list (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state) :=\nematch_core reducible\n\nmeta def ematch_all : cc_state \u2192 ematch_state \u2192 hinst_lemma \u2192 bool \u2192 tactic (list (expr \u00d7 expr) \u00d7 cc_state \u00d7 ematch_state) :=\nematch_all_core reducible\nend tactic\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/ematch.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646699291614, "lm_q2_score": 0.02556521545452025, "lm_q1q2_score": 0.00420589892449037}}
{"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Sebastian Ullrich, Leonardo de Moura\n-/\nimport Lean.Data.Name\nimport Lean.Data.Format\n\nnamespace Lean\n\ndef SourceInfo.updateTrailing (trailing : Substring) : SourceInfo \u2192 SourceInfo\n  | SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos\n  | info                                     => info\n\n/- Syntax AST -/\n\ninductive IsNode : Syntax \u2192 Prop where\n  | mk (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node info kind args)\n\ndef SyntaxNode : Type := {s : Syntax // IsNode s }\n\ndef unreachIsNodeMissing {\u03b2} (h : IsNode Syntax.missing) : \u03b2 := False.elim (nomatch h)\ndef unreachIsNodeAtom {\u03b2} {info val} (h : IsNode (Syntax.atom info val)) : \u03b2 := False.elim (nomatch h)\ndef unreachIsNodeIdent {\u03b2 info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : \u03b2 := False.elim (nomatch h)\n\ndef isLitKind (k : SyntaxNodeKind) : Bool :=\n  k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind\n\nnamespace SyntaxNode\n\n@[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind :=\n  match n with\n  | \u27e8Syntax.node _ k _, _\u27e9  => k\n  | \u27e8Syntax.missing, h\u27e9     => unreachIsNodeMissing h\n  | \u27e8Syntax.atom .., h\u27e9     => unreachIsNodeAtom h\n  | \u27e8Syntax.ident .., h\u27e9    => unreachIsNodeIdent h\n\n@[inline] def withArgs {\u03b2} (n : SyntaxNode) (fn : Array Syntax \u2192 \u03b2) : \u03b2 :=\n  match n with\n  | \u27e8Syntax.node _ _ args, _\u27e9   => fn args\n  | \u27e8Syntax.missing, h\u27e9       => unreachIsNodeMissing h\n  | \u27e8Syntax.atom _ _, h\u27e9      => unreachIsNodeAtom h\n  | \u27e8Syntax.ident _ _ _ _, h\u27e9 => unreachIsNodeIdent h\n\n@[inline] def getNumArgs (n : SyntaxNode) : Nat :=\n  withArgs n fun args => args.size\n\n@[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax :=\n  withArgs n fun args => args.get! i\n\n@[inline] def getArgs (n : SyntaxNode) : Array Syntax :=\n  withArgs n fun args => args\n\n@[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax \u2192 Array Syntax) : Syntax :=\n  match n with\n  | \u27e8Syntax.node i k args, _\u27e9  => Syntax.node i k (fn args)\n  | \u27e8Syntax.missing, h\u27e9        => unreachIsNodeMissing h\n  | \u27e8Syntax.atom _ _, h\u27e9       => unreachIsNodeAtom h\n  | \u27e8Syntax.ident _ _ _ _,  h\u27e9 => unreachIsNodeIdent h\n\nend SyntaxNode\n\nnamespace Syntax\n\ndef getAtomVal! : Syntax \u2192 String\n  | atom _ val => val\n  | _          => panic! \"getAtomVal!: not an atom\"\n\ndef setAtomVal : Syntax \u2192 String \u2192 Syntax\n  | atom info _, v => (atom info v)\n  | stx,         _ => stx\n\n@[inline] def ifNode {\u03b2} (stx : Syntax) (hyes : SyntaxNode \u2192 \u03b2) (hno : Unit \u2192 \u03b2) : \u03b2 :=\n  match stx with\n  | Syntax.node i k args => hyes \u27e8Syntax.node i k args, IsNode.mk i k args\u27e9\n  | _                    => hno ()\n\n@[inline] def ifNodeKind {\u03b2} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode \u2192 \u03b2) (hno : Unit \u2192 \u03b2) : \u03b2 :=\n  match stx with\n  | Syntax.node i k args => if k == kind then hyes \u27e8Syntax.node i k args, IsNode.mk i k args\u27e9 else hno ()\n  | _                    => hno ()\n\ndef asNode : Syntax \u2192 SyntaxNode\n  | Syntax.node info kind args => \u27e8Syntax.node info kind args, IsNode.mk info kind args\u27e9\n  | _                          => \u27e8mkNullNode, IsNode.mk _ _ _\u27e9\n\ndef getIdAt (stx : Syntax) (i : Nat) : Name :=\n  (stx.getArg i).getId\n\n@[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax \u2192 Array Syntax) : Syntax :=\n  match stx with\n  | node i k args => node i k (fn args)\n  | stx           => stx\n\n@[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax \u2192 Syntax) : Syntax :=\n  match stx with\n  | node info k args => node info k (args.modify i fn)\n  | stx              => stx\n\n@[specialize] partial def replaceM {m : Type \u2192 Type} [Monad m] (fn : Syntax \u2192 m (Option Syntax)) : Syntax \u2192 m (Syntax)\n  | stx@(node info kind args) => do\n    match (\u2190 fn stx) with\n    | some stx => return stx\n    | none     => return node info kind (\u2190 args.mapM (replaceM fn))\n  | stx => do\n    let o \u2190 fn stx\n    return o.getD stx\n\n@[specialize] partial def rewriteBottomUpM {m : Type \u2192 Type} [Monad m] (fn : Syntax \u2192 m (Syntax)) : Syntax \u2192 m (Syntax)\n  | node info kind args   => do\n    let args \u2190 args.mapM (rewriteBottomUpM fn)\n    fn (node info kind args)\n  | stx => fn stx\n\n@[inline] def rewriteBottomUp (fn : Syntax \u2192 Syntax) (stx : Syntax) : Syntax :=\n  Id.run <| stx.rewriteBottomUpM fn\n\nprivate def updateInfo : SourceInfo \u2192 String.Pos \u2192 String.Pos \u2192 SourceInfo\n  | SourceInfo.original lead pos trail endPos, leadStart, trailStop =>\n    SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos\n  | info, _, _ => info\n\nprivate def chooseNiceTrailStop (trail : Substring) : String.Pos :=\ntrail.startPos + trail.posOf '\\n'\n\n/- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token,\n   or the beginning of the String. -/\n@[inline]\nprivate def updateLeadingAux : Syntax \u2192 StateM String.Pos (Option Syntax)\n  | atom info@(SourceInfo.original lead _ trail _) val => do\n    let trailStop := chooseNiceTrailStop trail\n    let newInfo := updateInfo info (\u2190 get) trailStop\n    set trailStop\n    return some (atom newInfo val)\n  | ident info@(SourceInfo.original lead _ trail _) rawVal val pre => do\n    let trailStop := chooseNiceTrailStop trail\n    let newInfo := updateInfo info (\u2190 get) trailStop\n    set trailStop\n    return some (ident newInfo rawVal val pre)\n  | _ => pure none\n\n/-- Set `SourceInfo.leading` according to the trailing stop of the preceding token.\n    The result is a round-tripping syntax tree IF, in the input syntax tree,\n    * all leading stops, atom contents, and trailing starts are correct\n    * trailing stops are between the trailing start and the next leading stop.\n\n    Remark: after parsing, all `SourceInfo.leading` fields are empty.\n    The `Syntax` argument is the output produced by the parser for `source`.\n    This function \"fixes\" the `source.leading` field.\n\n    Additionally, we try to choose \"nicer\" splits between leading and trailing stops\n    according to some heuristics so that e.g. comments are associated to the (intuitively)\n    correct token.\n\n    Note that the `SourceInfo.trailing` fields must be correct.\n    The implementation of this Function relies on this property. -/\ndef updateLeading : Syntax \u2192 Syntax :=\n  fun stx => (replaceM updateLeadingAux stx).run' 0\n\npartial def updateTrailing (trailing : Substring) : Syntax \u2192 Syntax\n  | Syntax.atom info val               => Syntax.atom (info.updateTrailing trailing) val\n  | Syntax.ident info rawVal val pre   => Syntax.ident (info.updateTrailing trailing) rawVal val pre\n  | n@(Syntax.node info k args)        =>\n    if args.size == 0 then n\n    else\n     let i    := args.size - 1\n     let last := updateTrailing trailing args[i]\n     let args := args.set! i last;\n     Syntax.node info k args\n  | s => s\n\npartial def getTailWithPos : Syntax \u2192 Option Syntax\n  | stx@(atom info _)   => info.getPos?.map fun _ => stx\n  | stx@(ident info ..) => info.getPos?.map fun _ => stx\n  | node SourceInfo.none _ args => args.findSomeRev? getTailWithPos\n  | stx@(node info _ _) => stx\n  | _                   => none\n\nopen SourceInfo in\n/-- Split an `ident` into its dot-separated components while preserving source info.\nMacro scopes are first erased.  For example, `` `foo.bla.boo._@._hyg.4 `` \u21a6 `` [`foo, `bla, `boo] ``.\nIf `nFields` is set, we take that many fields from the end and keep the remaining components\nas one name. For example, `` `foo.bla.boo `` with `(nFields := 1)` \u21a6 `` [`foo.bla, `boo] ``. -/\ndef identComponents (stx : Syntax) (nFields? : Option Nat := none) : List Syntax :=\n  match stx with\n  | ident (SourceInfo.original lead pos trail _) rawStr val _ =>\n    let val := val.eraseMacroScopes\n    -- With original info, we assume that `rawStr` represents `val`.\n    let nameComps := nameComps val nFields?\n    let rawComps := splitNameLit rawStr\n    let rawComps :=\n      if let some nFields := nFields? then\n        let nPrefix := rawComps.length - nFields\n        let prefixSz := rawComps.take nPrefix |>.foldl (init := 0) fun acc (ss : Substring) => acc + ss.bsize + 1\n        let prefixSz := prefixSz - 1 -- The last component has no dot\n        rawStr.extract 0 prefixSz :: rawComps.drop nPrefix\n      else\n        rawComps\n    assert! nameComps.length == rawComps.length\n    nameComps.zip rawComps |>.map fun (id, ss) =>\n      let off := ss.startPos - rawStr.startPos\n      let lead := if off == 0 then lead else \"\".toSubstring\n      let trail := if ss.stopPos == rawStr.stopPos then trail else \"\".toSubstring\n      let info := original lead (pos + off) trail (pos + off + ss.bsize)\n      ident info ss id []\n  | ident si _ val _ =>\n    let val := val.eraseMacroScopes\n    /- With non-original info:\n     - `rawStr` can take all kinds of forms so we only use `val`.\n     - there is no source extent to offset, so we pass it as-is. -/\n    nameComps val nFields? |>.map fun n => ident si n.toString.toSubstring n []\n  | _ => unreachable!\n  where\n    nameComps (n : Name) (nFields? : Option Nat) : List Name :=\n      if let some nFields := nFields? then\n        let nameComps := n.components\n        let nPrefix := nameComps.length - nFields\n        let namePrefix := nameComps.take nPrefix |>.foldl (init := Name.anonymous) fun acc n => acc ++ n\n        namePrefix :: nameComps.drop nPrefix\n      else\n        n.components\n\nstructure TopDown where\n  firstChoiceOnly : Bool\n  stx : Syntax\n\n/--\n`for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right.\nIf `firstChoiceOnly` is `true`, only visit the first argument of each choice node.\n-/\ndef topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := \u27e8firstChoiceOnly, stx\u27e9\n\npartial instance : ForIn m TopDown Syntax where\n  forIn := fun \u27e8firstChoiceOnly, stx\u27e9 init f => do\n    let rec @[specialize] loop stx b [Inhabited (type_of% b)] := do\n      match (\u2190 f stx b) with\n      | ForInStep.yield b' =>\n        let mut b := b'\n        if let Syntax.node i k args := stx then\n          if firstChoiceOnly && k == choiceKind then\n            return \u2190 loop args[0] b\n          else\n            for arg in args do\n              match (\u2190 loop arg b) with\n              | ForInStep.yield b' => b := b'\n              | ForInStep.done b'  => return ForInStep.done b'\n        return ForInStep.yield b\n      | ForInStep.done b => return ForInStep.done b\n    match (\u2190 @loop stx init \u27e8init\u27e9) with\n    | ForInStep.yield b => return b\n    | ForInStep.done b  => return b\n\npartial def reprint (stx : Syntax) : Option String :=\n  OptionM.run do\n    let mut s := \"\"\n    for stx in stx.topDown (firstChoiceOnly := true) do\n      match stx with\n      | atom info val           => s := s ++ reprintLeaf info val\n      | ident info rawVal _ _   => s := s ++ reprintLeaf info rawVal.toString\n      | node info kind args     =>\n        if kind == choiceKind then\n          -- this visit the first arg twice, but that should hardly be a problem\n          -- given that choice nodes are quite rare and small\n          let s0 \u2190 reprint args[0]\n          for arg in args[1:] do\n            let s' \u2190 reprint arg\n            guard (s0 == s')\n      | _ => pure ()\n    return s\nwhere\n  reprintLeaf (info : SourceInfo) (val : String) : String :=\n    match info with\n    | SourceInfo.original lead _ trail _ => s!\"{lead}{val}{trail}\"\n    -- no source info => add gracious amounts of whitespace to definitely separate tokens\n    -- Note that the proper pretty printer does not use this function.\n    -- The parser as well always produces source info, so round-tripping is still\n    -- guaranteed.\n    | _                                => s!\" {val} \"\n\ndef hasMissing (stx : Syntax) : Bool := Id.run <| do\n  for stx in stx.topDown do\n    if stx.isMissing then\n      return true\n  return false\n\n/--\nRepresents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right.\nIndices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`.\nIf the `Traverser` is used linearly, updates are linear in the `Syntax` object as well.\n-/\nstructure Traverser where\n  cur     : Syntax\n  parents : Array Syntax\n  idxs    : Array Nat\n\nnamespace Traverser\n\ndef fromSyntax (stx : Syntax) : Traverser :=\n  \u27e8stx, #[], #[]\u27e9\n\ndef setCur (t : Traverser) (stx : Syntax) : Traverser :=\n  { t with cur := stx }\n\n/-- Advance to the `idx`-th child of the current node. -/\ndef down (t : Traverser) (idx : Nat) : Traverser :=\n  if idx < t.cur.getNumArgs then\n    { cur := t.cur.getArg idx, parents := t.parents.push <| t.cur.setArg idx default, idxs := t.idxs.push idx }\n  else\n    { cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx }\n\n/-- Advance to the parent of the current node, if any. -/\ndef up (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back\n    { cur := cur, parents := t.parents.pop, idxs := t.idxs.pop }\n  else\n    t\n\n/-- Advance to the left sibling of the current node, if any. -/\ndef left (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    t.up.down (t.idxs.back - 1)\n  else\n    t\n\n/-- Advance to the right sibling of the current node, if any. -/\ndef right (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    t.up.down (t.idxs.back + 1)\n  else\n    t\n\nend Traverser\n\n/-- Monad class that gives read/write access to a `Traverser`. -/\nclass MonadTraverser (m : Type \u2192 Type) where\n  st : MonadState Traverser m\n\nnamespace MonadTraverser\n\nvariable {m : Type \u2192 Type} [Monad m] [t : MonadTraverser m]\n\ndef getCur : m Syntax := Traverser.cur <$> t.st.get\ndef setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx)\ndef goDown (idx : Nat)    : m Unit := @modify _ _ t.st (fun t => t.down idx)\ndef goUp                  : m Unit := @modify _ _ t.st (fun t => t.up)\ndef goLeft                : m Unit := @modify _ _ t.st (fun t => t.left)\ndef goRight               : m Unit := @modify _ _ t.st (fun t => t.right)\n\ndef getIdx : m Nat := do\n  let st \u2190 t.st.get\n  return st.idxs.back?.getD 0\n\nend MonadTraverser\nend Syntax\n\nnamespace SyntaxNode\n\n@[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name :=\n  (n.getArg i).getId\n\nend SyntaxNode\n\ndef mkListNode (args : Array Syntax) : Syntax :=\n  mkNullNode args\n\nnamespace Syntax\n\n-- quotation node kinds are formed from a unique quotation name plus \"quot\"\ndef isQuot : Syntax \u2192 Bool\n  | Syntax.node _ (Name.str _ \"quot\" _)         _ => true\n  | Syntax.node _ `Lean.Parser.Term.dynamicQuot _ => true\n  | _                                             => false\n\ndef getQuotContent (stx : Syntax) : Syntax :=\n  if stx.isOfKind `Lean.Parser.Term.dynamicQuot then\n    stx[3]\n  else\n    stx[1]\n\n-- antiquotation node kinds are formed from the original node kind (if any) plus \"antiquot\"\ndef isAntiquot : Syntax \u2192 Bool\n  | Syntax.node _ (Name.str _ \"antiquot\" _) _ => true\n  | _                                         => false\n\ndef mkAntiquotNode (term : Syntax) (nesting := 0) (name : Option String := none) (kind := Name.anonymous) : Syntax :=\n  let nesting := mkNullNode (mkArray nesting (mkAtom \"$\"))\n  let term := match term.isIdent with\n    | true  => term\n    | false => mkNode `antiquotNestedExpr #[mkAtom \"(\", term, mkAtom \")\"]\n  let name := match name with\n    | some name => mkNode `antiquotName #[mkAtom \":\", mkAtom name]\n    | none      => mkNullNode\n  mkNode (kind ++ `antiquot) #[mkAtom \"$\", nesting, term, name]\n\n-- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices.\ndef isEscapedAntiquot (stx : Syntax) : Bool :=\n  !stx[1].getArgs.isEmpty\n\n-- Also works for antiquotation splices.\ndef unescapeAntiquot (stx : Syntax) : Syntax :=\n  if isAntiquot stx then\n    stx.setArg 1 <| mkNullNode stx[1].getArgs.pop\n  else\n    stx\n\n-- Also works for token antiquotations.\ndef getAntiquotTerm (stx : Syntax) : Syntax :=\n  let e := if stx.isAntiquot then stx[2] else stx[3]\n  if e.isIdent then e\n  else\n    -- `e` is from `\"(\" >> termParser >> \")\"`\n    e[1]\n\ndef antiquotKind? : Syntax \u2192 Option SyntaxNodeKind\n  | Syntax.node _ (Name.str k \"antiquot\" _) args =>\n    if args[3].isOfKind `antiquotName then some k\n    else\n      -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`)\n      some Name.anonymous\n  | _                                          => none\n\n-- An \"antiquotation splice\" is something like `$[...]?` or `$[...]*`.\ndef antiquotSpliceKind? : Syntax \u2192 Option SyntaxNodeKind\n  | Syntax.node _ (Name.str k \"antiquot_scope\" _) args => some k\n  | _                                                  => none\n\ndef isAntiquotSplice (stx : Syntax) : Bool :=\n  antiquotSpliceKind? stx |>.isSome\n\ndef getAntiquotSpliceContents (stx : Syntax) : Array Syntax :=\n  stx[3].getArgs\n\n-- `$[..],*` or `$x,*` ~> `,*`\ndef getAntiquotSpliceSuffix (stx : Syntax) : Syntax :=\n  if stx.isAntiquotSplice then\n    stx[5]\n  else\n    stx[1]\n\ndef mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax :=\n  let nesting := mkNullNode (mkArray nesting (mkAtom \"$\"))\n  mkNode (kind ++ `antiquot_splice) #[mkAtom \"$\", nesting, mkAtom \"[\", mkNullNode contents, mkAtom \"]\", mkAtom suffix]\n\n-- `$x,*` etc.\ndef antiquotSuffixSplice? : Syntax \u2192 Option SyntaxNodeKind\n  | Syntax.node _ (Name.str k \"antiquot_suffix_splice\" _) args => some k\n  | _                                                          => none\n\ndef isAntiquotSuffixSplice (stx : Syntax) : Bool :=\n  antiquotSuffixSplice? stx |>.isSome\n\n-- `$x` in the example above\ndef getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax :=\n  stx[0]\n\ndef mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax :=\n  mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix]\n\ndef isTokenAntiquot (stx : Syntax) : Bool :=\n  stx.isOfKind `token_antiquot\n\ndef isAnyAntiquot (stx : Syntax) : Bool :=\n  stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot\n\nend Syntax\nend Lean\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/Syntax.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920292202211755, "lm_q2_score": 0.035144842863737535, "lm_q1q2_score": 0.00418936796336568}}
{"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Sebastian Ullrich, Leonardo de Moura\n-/\nimport Lean.Data.Name\nimport Lean.Data.Format\n\nnamespace Lean\n\ndef SourceInfo.updateTrailing (trailing : Substring) : SourceInfo \u2192 SourceInfo\n  | SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos\n  | info                                     => info\n\n/- Syntax AST -/\n\ninductive IsNode : Syntax \u2192 Prop where\n  | mk (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node kind args)\n\ndef SyntaxNode : Type := {s : Syntax // IsNode s }\n\ndef unreachIsNodeMissing {\u03b2} (h : IsNode Syntax.missing) : \u03b2 := False.elim (nomatch h)\ndef unreachIsNodeAtom {\u03b2} {info val} (h : IsNode (Syntax.atom info val)) : \u03b2 := False.elim (nomatch h)\ndef unreachIsNodeIdent {\u03b2 info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : \u03b2 := False.elim (nomatch h)\n\nnamespace SyntaxNode\n\n@[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind :=\n  match n with\n  | \u27e8Syntax.node k args, _\u27e9 => k\n  | \u27e8Syntax.missing, h\u27e9     => unreachIsNodeMissing h\n  | \u27e8Syntax.atom .., h\u27e9     => unreachIsNodeAtom h\n  | \u27e8Syntax.ident .., h\u27e9    => unreachIsNodeIdent h\n\n@[inline] def withArgs {\u03b2} (n : SyntaxNode) (fn : Array Syntax \u2192 \u03b2) : \u03b2 :=\n  match n with\n  | \u27e8Syntax.node _ args, _\u27e9   => fn args\n  | \u27e8Syntax.missing, h\u27e9       => unreachIsNodeMissing h\n  | \u27e8Syntax.atom _ _, h\u27e9      => unreachIsNodeAtom h\n  | \u27e8Syntax.ident _ _ _ _, h\u27e9 => unreachIsNodeIdent h\n\n@[inline] def getNumArgs (n : SyntaxNode) : Nat :=\n  withArgs n $ fun args => args.size\n\n@[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax :=\n  withArgs n $ fun args => args.get! i\n\n@[inline] def getArgs (n : SyntaxNode) : Array Syntax :=\n  withArgs n $ fun args => args\n\n@[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax \u2192 Array Syntax) : Syntax :=\n  match n with\n  | \u27e8Syntax.node kind args, _\u27e9 => Syntax.node kind (fn args)\n  | \u27e8Syntax.missing, h\u27e9        => unreachIsNodeMissing h\n  | \u27e8Syntax.atom _ _, h\u27e9       => unreachIsNodeAtom h\n  | \u27e8Syntax.ident _ _ _ _,  h\u27e9 => unreachIsNodeIdent h\n\nend SyntaxNode\n\nnamespace Syntax\n\ndef getAtomVal! : Syntax \u2192 String\n  | atom _ val => val\n  | _          => panic! \"getAtomVal!: not an atom\"\n\ndef setAtomVal : Syntax \u2192 String \u2192 Syntax\n  | atom info _, v => (atom info v)\n  | stx,         _ => stx\n\n@[inline] def ifNode {\u03b2} (stx : Syntax) (hyes : SyntaxNode \u2192 \u03b2) (hno : Unit \u2192 \u03b2) : \u03b2 :=\n  match stx with\n  | Syntax.node k args => hyes \u27e8Syntax.node k args, IsNode.mk k args\u27e9\n  | _                  => hno ()\n\n@[inline] def ifNodeKind {\u03b2} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode \u2192 \u03b2) (hno : Unit \u2192 \u03b2) : \u03b2 :=\n  match stx with\n  | Syntax.node k args => if k == kind then hyes \u27e8Syntax.node k args, IsNode.mk k args\u27e9 else hno ()\n  | _                  => hno ()\n\ndef asNode : Syntax \u2192 SyntaxNode\n  | Syntax.node kind args => \u27e8Syntax.node kind args, IsNode.mk kind args\u27e9\n  | _                     => \u27e8Syntax.node nullKind #[], IsNode.mk nullKind #[]\u27e9\n\ndef getIdAt (stx : Syntax) (i : Nat) : Name :=\n  (stx.getArg i).getId\n\n@[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax \u2192 Array Syntax) : Syntax :=\n  match stx with\n  | node k args => node k (fn args)\n  | stx         => stx\n\n@[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax \u2192 Syntax) : Syntax :=\n  match stx with\n  | node k args => node k (args.modify i fn)\n  | stx         => stx\n\n@[specialize] partial def replaceM {m : Type \u2192 Type} [Monad m] (fn : Syntax \u2192 m (Option Syntax)) : Syntax \u2192 m (Syntax)\n  | stx@(node kind args) => do\n    match (\u2190 fn stx) with\n    | some stx => return stx\n    | none     => return node kind (\u2190 args.mapM (replaceM fn))\n  | stx => do\n    let o \u2190 fn stx\n    return o.getD stx\n\n@[specialize] partial def rewriteBottomUpM {m : Type \u2192 Type} [Monad m] (fn : Syntax \u2192 m (Syntax)) : Syntax \u2192 m (Syntax)\n  | node kind args   => do\n    let args \u2190 args.mapM (rewriteBottomUpM fn)\n    fn (node kind args)\n  | stx => fn stx\n\n@[inline] def rewriteBottomUp (fn : Syntax \u2192 Syntax) (stx : Syntax) : Syntax :=\n  Id.run $ stx.rewriteBottomUpM fn\n\nprivate def updateInfo : SourceInfo \u2192 String.Pos \u2192 String.Pos \u2192 SourceInfo\n  | SourceInfo.original lead pos trail endPos, leadStart, trailStop =>\n    SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos\n  | info, _, _ => info\n\nprivate def chooseNiceTrailStop (trail : Substring) : String.Pos :=\ntrail.startPos + trail.posOf '\\n'\n\n/- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token,\n   or the beginning of the String. -/\n@[inline]\nprivate def updateLeadingAux : Syntax \u2192 StateM String.Pos (Option Syntax)\n  | atom info@(SourceInfo.original lead _ trail _) val => do\n    let trailStop := chooseNiceTrailStop trail\n    let newInfo := updateInfo info (\u2190 get) trailStop\n    set trailStop\n    pure $ some (atom newInfo val)\n  | ident info@(SourceInfo.original lead _ trail _) rawVal val pre => do\n    let trailStop := chooseNiceTrailStop trail\n    let newInfo := updateInfo info (\u2190 get) trailStop\n    set trailStop\n    pure $ some (ident newInfo rawVal val pre)\n  | _ => pure none\n\n/-- Set `SourceInfo.leading` according to the trailing stop of the preceding token.\n    The result is a round-tripping syntax tree IF, in the input syntax tree,\n    * all leading stops, atom contents, and trailing starts are correct\n    * trailing stops are between the trailing start and the next leading stop.\n\n    Remark: after parsing, all `SourceInfo.leading` fields are empty.\n    The `Syntax` argument is the output produced by the parser for `source`.\n    This function \"fixes\" the `source.leading` field.\n\n    Additionally, we try to choose \"nicer\" splits between leading and trailing stops\n    according to some heuristics so that e.g. comments are associated to the (intuitively)\n    correct token.\n\n    Note that the `SourceInfo.trailing` fields must be correct.\n    The implementation of this Function relies on this property. -/\ndef updateLeading : Syntax \u2192 Syntax :=\n  fun stx => (replaceM updateLeadingAux stx).run' 0\n\npartial def updateTrailing (trailing : Substring) : Syntax \u2192 Syntax\n  | Syntax.atom info val               => Syntax.atom (info.updateTrailing trailing) val\n  | Syntax.ident info rawVal val pre   => Syntax.ident (info.updateTrailing trailing) rawVal val pre\n  | n@(Syntax.node k args)             =>\n    if args.size == 0 then n\n    else\n     let i    := args.size - 1\n     let last := updateTrailing trailing args[i]\n     let args := args.set! i last;\n     Syntax.node k args\n  | s => s\n\npartial def getTailWithPos : Syntax \u2192 Option Syntax\n  | stx@(atom info _)   => info.getPos?.map fun _ => stx\n  | stx@(ident info ..) => info.getPos?.map fun _ => stx\n  | node _ args         => args.findSomeRev? getTailWithPos\n  | _                   => none\n\nstructure TopDown where\n  firstChoiceOnly : Bool\n  stx : Syntax\n\n/--\n`for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right.\nIf `firstChoiceOnly` is `true`, only visit the first argument of each choice node.\n-/\ndef topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := \u27e8firstChoiceOnly, stx\u27e9\n\npartial instance : ForIn m TopDown Syntax where\n  forIn := fun \u27e8firstChoiceOnly, stx\u27e9 init f => do\n    let rec @[specialize] loop stx b [Inhabited (typeOf% b)] := do\n      match \u2190 f stx b with\n      | ForInStep.yield b' =>\n        let mut b := b'\n        if let Syntax.node k args := stx then\n          if firstChoiceOnly && k == choiceKind then\n            return \u2190 loop args[0] b\n          else\n            for arg in args do\n              match \u2190 loop arg b with\n              | ForInStep.yield b' => b := b'\n              | ForInStep.done b'  => return ForInStep.done b'\n        return ForInStep.yield b\n      | ForInStep.done b => return ForInStep.done b\n    match \u2190 @loop stx init \u27e8init\u27e9 with\n    | ForInStep.yield b => return b\n    | ForInStep.done b  => return b\n\npartial def reprint (stx : Syntax) : Option String :=\n  OptionM.run do\n    let mut s := \"\"\n    for stx in stx.topDown (firstChoiceOnly := true) do\n      match stx with\n      | atom info val           => s := s ++ reprintLeaf info val\n      | ident info rawVal _ _   => s := s ++ reprintLeaf info rawVal.toString\n      | node kind args          =>\n        if kind == choiceKind then\n          -- this visit the first arg twice, but that should hardly be a problem\n          -- given that choice nodes are quite rare and small\n          let s0 \u2190 reprint args[0]\n          for arg in args[1:] do\n            let s' \u2190 reprint stx\n            guard (s0 == s')\n      | _ => pure ()\n    return s\nwhere\n  reprintLeaf (info : SourceInfo) (val : String) : String :=\n    match info with\n    | SourceInfo.original lead _ trail _ => s!\"{lead}{val}{trail}\"\n    -- no source info => add gracious amounts of whitespace to definitely separate tokens\n    -- Note that the proper pretty printer does not use this function.\n    -- The parser as well always produces source info, so round-tripping is still\n    -- guaranteed.\n    | _                                => s!\" {val} \"\n\ndef hasMissing (stx : Syntax) : Bool := do\n  for stx in stx.topDown do\n    if stx.isMissing then\n      return true\n  return false\n\n/--\nRepresents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right.\nIndices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`.\nIf the `Traverser` is used linearly, updates are linear in the `Syntax` object as well.\n-/\nstructure Traverser where\n  cur     : Syntax\n  parents : Array Syntax\n  idxs    : Array Nat\n\nnamespace Traverser\n\ndef fromSyntax (stx : Syntax) : Traverser :=\n  \u27e8stx, #[], #[]\u27e9\n\ndef setCur (t : Traverser) (stx : Syntax) : Traverser :=\n  { t with cur := stx }\n\n/-- Advance to the `idx`-th child of the current node. -/\ndef down (t : Traverser) (idx : Nat) : Traverser :=\n  if idx < t.cur.getNumArgs then\n    { cur := t.cur.getArg idx, parents := t.parents.push $ t.cur.setArg idx arbitrary, idxs := t.idxs.push idx }\n  else\n    { cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx }\n\n/-- Advance to the parent of the current node, if any. -/\ndef up (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back\n    { cur := cur, parents := t.parents.pop, idxs := t.idxs.pop }\n  else\n    t\n\n/-- Advance to the left sibling of the current node, if any. -/\ndef left (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    t.up.down (t.idxs.back - 1)\n  else\n    t\n\n/-- Advance to the right sibling of the current node, if any. -/\ndef right (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    t.up.down (t.idxs.back + 1)\n  else\n    t\n\nend Traverser\n\n/-- Monad class that gives read/write access to a `Traverser`. -/\nclass MonadTraverser (m : Type \u2192 Type) where\n  st : MonadState Traverser m\n\nnamespace MonadTraverser\n\nvariable {m : Type \u2192 Type} [Monad m] [t : MonadTraverser m]\n\ndef getCur : m Syntax := Traverser.cur <$> t.st.get\ndef setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx)\ndef goDown (idx : Nat)    : m Unit := @modify _ _ t.st (fun t => t.down idx)\ndef goUp                  : m Unit := @modify _ _ t.st (fun t => t.up)\ndef goLeft                : m Unit := @modify _ _ t.st (fun t => t.left)\ndef goRight               : m Unit := @modify _ _ t.st (fun t => t.right)\n\ndef getIdx : m Nat := do\n  let st \u2190 t.st.get\n  st.idxs.back?.getD 0\n\nend MonadTraverser\nend Syntax\n\nnamespace SyntaxNode\n\n@[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name :=\n  (n.getArg i).getId\n\nend SyntaxNode\n\ndef mkListNode (args : Array Syntax) : Syntax :=\n  Syntax.node nullKind args\n\nnamespace Syntax\n\n-- quotation node kinds are formed from a unique quotation name plus \"quot\"\ndef isQuot : Syntax \u2192 Bool\n  | Syntax.node (Name.str _ \"quot\" _)         _ => true\n  | Syntax.node `Lean.Parser.Term.dynamicQuot _ => true\n  | _                                           => false\n\ndef getQuotContent (stx : Syntax) : Syntax :=\n  if stx.isOfKind `Lean.Parser.Term.dynamicQuot then\n    stx[3]\n  else\n    stx[1]\n\n-- antiquotation node kinds are formed from the original node kind (if any) plus \"antiquot\"\ndef isAntiquot : Syntax \u2192 Bool\n  | Syntax.node (Name.str _ \"antiquot\" _) _ => true\n  | _                                       => false\n\ndef mkAntiquotNode (term : Syntax) (nesting := 0) (name : Option String := none) (kind := Name.anonymous) : Syntax :=\n  let nesting := mkNullNode (mkArray nesting (mkAtom \"$\"))\n  let term := match term.isIdent with\n    | true  => term\n    | false => mkNode `antiquotNestedExpr #[mkAtom \"(\", term, mkAtom \")\"]\n  let name := match name with\n    | some name => mkNode `antiquotName #[mkAtom \":\", mkAtom name]\n    | none      => mkNullNode\n  mkNode (kind ++ `antiquot) #[mkAtom \"$\", nesting, term, name]\n\n-- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices.\ndef isEscapedAntiquot (stx : Syntax) : Bool :=\n  !stx[1].getArgs.isEmpty\n\n-- Also works for antiquotation splices.\ndef unescapeAntiquot (stx : Syntax) : Syntax :=\n  if isAntiquot stx then\n    stx.setArg 1 $ mkNullNode stx[1].getArgs.pop\n  else\n    stx\n\n-- Also works for token antiquotations.\ndef getAntiquotTerm (stx : Syntax) : Syntax :=\n  let e := if stx.isAntiquot then stx[2] else stx[3]\n  if e.isIdent then e\n  else\n    -- `e` is from `\"(\" >> termParser >> \")\"`\n    e[1]\n\ndef antiquotKind? : Syntax \u2192 Option SyntaxNodeKind\n  | Syntax.node (Name.str k \"antiquot\" _) args =>\n    if args[3].isOfKind `antiquotName then some k\n    else\n      -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`)\n      some Name.anonymous\n  | _                                          => none\n\n-- An \"antiquotation splice\" is something like `$[...]?` or `$[...]*`.\ndef antiquotSpliceKind? : Syntax \u2192 Option SyntaxNodeKind\n  | Syntax.node (Name.str k \"antiquot_scope\" _) args => some k\n  | _                                                => none\n\ndef isAntiquotSplice (stx : Syntax) : Bool :=\n  antiquotSpliceKind? stx |>.isSome\n\ndef getAntiquotSpliceContents (stx : Syntax) : Array Syntax :=\n  stx[3].getArgs\n\n-- `$[..],*` or `$x,*` ~> `,*`\ndef getAntiquotSpliceSuffix (stx : Syntax) : Syntax :=\n  if stx.isAntiquotSplice then\n    stx[5]\n  else\n    stx[1]\n\ndef mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax :=\n  let nesting := mkNullNode (mkArray nesting (mkAtom \"$\"))\n  mkNode (kind ++ `antiquot_splice) #[mkAtom \"$\", nesting, mkAtom \"[\", mkNullNode contents, mkAtom \"]\", mkAtom suffix]\n\n-- `$x,*` etc.\ndef antiquotSuffixSplice? : Syntax \u2192 Option SyntaxNodeKind\n  | Syntax.node (Name.str k \"antiquot_suffix_splice\" _) args => some k\n  | _                                                        => none\n\ndef isAntiquotSuffixSplice (stx : Syntax) : Bool :=\n  antiquotSuffixSplice? stx |>.isSome\n\n-- `$x` in the example above\ndef getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax :=\n  stx[0]\n\ndef mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax :=\n  mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix]\n\ndef isTokenAntiquot (stx : Syntax) : Bool :=\n  stx.isOfKind `token_antiquot\n\ndef isAnyAntiquot (stx : Syntax) : Bool :=\n  stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot\n\nend Syntax\nend Lean\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/Syntax.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970578261038684, "lm_q2_score": 0.037892424320813946, "lm_q1q2_score": 0.00415701806511975}}
{"text": "open tactic\n\nlemma a1 : true :=\nbegin\n  sleep 20000,\n  trivial\nend\n\nlemma a2 : true :=\nbegin\n  sleep 10000,\n  trivial\nend\n", "meta": {"author": "alexjbest", "repo": "pole-test", "sha": "a8458dea5dfa337d85bf50c4698eae668759a487", "save_path": "github-repos/lean/alexjbest-pole-test", "path": "github-repos/lean/alexjbest-pole-test/pole-test-a8458dea5dfa337d85bf50c4698eae668759a487/src/a.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.11279540628289321, "lm_q2_score": 0.036769468318585026, "lm_q1q2_score": 0.004147427117800769}}
{"text": "def String.isInfixOf (p : String) (s : String) : Bool := do\n  if s.length < p.length then false\n  else do\n    for i in [0:(s.length-p.length)] do\n      if s.extract i (i+p.length) == p then\n        return true\n    return false\n\nnamespace Terminal\n\nclass Command (\u03b1 : Type u) where\n  writeAnsi : \u03b1 \u2192 IO.FS.Stream \u2192 IO Unit\n\ndef csi (s : String) : String := \"\\x1B[\" ++ s\n\n/--\n  A command that moves the terminal cursor to the given position (column, row).\n\n  # Notes\n\n  * Top left cell is represented as `0,0`.\n  * Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveTo := (c r : UInt16)\n\ninstance : Command MoveTo where\n  writeAnsi self f := f.putStr <| csi s!\"{self.r + 1};{self.c + 1}H\"\n\n/--\n  A command that moves the terminal cursor down the given number of lines, \n  and moves it to the first column.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveToNextLine := (n : UInt16)\n\ninstance : Command MoveToNextLine where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}E\"\n\n/--\n  A command that moves the terminal cursor up the given number of lines,\n  and moves it to the first column.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveToPreviousLine := (n : UInt16)\n\ninstance : Command MoveToPreviousLine where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}F\"\n\n/--\n  A command that moves the terminal cursor to the given column on the current row.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveToColumn := (c : UInt16)\n\ninstance : Command MoveToColumn where\n  writeAnsi self f := f.putStr <| csi s!\"{self.c}G\"\n\n/--\n  A command that moves the terminal cursor to the given row on the current column.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveToRow := (r : UInt16)\n\ninstance : Command MoveToRow where\n  writeAnsi self f := f.putStr <| csi s!\"{self.r}d\"\n\n/--\n  A command that moves the terminal cursor a given number of rows up.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveUp := (n : UInt16)\n\ninstance : Command MoveUp where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}A\"\n\n/--\n  A command that moves the terminal cursor a given number of columns to the right.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveRight := (n : UInt16)\n\ninstance : Command MoveRight where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}C\"\n\n/--\n  A command that moves the terminal cursor a given number of rows down.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveDown := (n : UInt16)\n\ninstance : Command MoveDown where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}B\"\n\n/--\n  A command that moves the terminal cursor a given number of columns to the left.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure MoveLeft := (n : UInt16)\n\ninstance : Command MoveLeft where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}D\"\n\n/--\n  A command that saves the current terminal cursor position.\n\n  See the `RestorePosition` command.\n\n  # Notes\n\n  - The cursor position is stored globally.\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SavePosition\n\ninstance : Command SavePosition where\n  writeAnsi self f := f.putStr <| csi \"s\"\n\n/--\n  A command that saves the current terminal cursor position.\n\n  See the `SavePosition` command.\n\n  # Notes\n\n  - The cursor position is stored globally.\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure RestorePosition\n\ninstance : Command RestorePosition where\n  writeAnsi self f := f.putStr <| csi \"u\"\n\n/--\n  A command that hides the terminal cursor.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure Hide\n\ninstance : Command Hide where\n  writeAnsi self f := f.putStr <| csi \"?25l\"\n\n/--\n  A command that shows the terminal cursor.\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure Show\n\ninstance : Command Show where\n  writeAnsi self f := f.putStr <| csi \"?25h\"\n\n/--\n  A command that enables blinking of the terminal cursor.\n\n  # Notes\n\n  - Windows versions lower than Windows 10 do not support this functionality.\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure EnableBlinking\n\ninstance : Command EnableBlinking where\n  writeAnsi self f := f.putStr <| csi \"?12h\"\n\n/--\n  A command that disables blinking of the terminal cursor.\n\n  # Notes\n\n  - Windows versions lower than Windows 10 do not support this functionality.\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure DisableBlinking\n\ninstance : Command DisableBlinking where\n  writeAnsi self f := f.putStr <| csi \"?12l\"\n\ninductive CursorShape\n  | underScore\n  | line\n  | block\n\n/--\n  A command that sets the shape of the cursor\n\n  # Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SetCursorShape := (s : CursorShape)\n\ninstance : Command SetCursorShape where\n  writeAnsi self f := f.putStr <| csi <|\n    match self.s with\n    | CursorShape.underScore  => \"3 q\"\n    | CursorShape.line        => \"5 q\"\n    | CursorShape.block       => \"2 q\"\n\n-- /--\n--   Returns the cursor position (column, row).\n\n--   The top left cell is represented `0,0`.\n-- -/\n-- def position : IO (UInt16 \u00d7 UInt16) := sorry\n\ninductive KeyCode where\n  | /-- Backspace key. -/\n    backspace\n  | /-- Enter key. -/\n    enter\n  | /-- Left arrow key. -/\n    left\n  | /-- Right arrow key. -/\n    right\n  | /-- Up arrow key. -/\n    up\n  | /-- Down arrow key. -/\n    down\n  | /-- Home key. -/\n    home\n  | /-- End key. -/\n    \u00abend\u00bb \n  | /-- Page up key. -/\n    pageUp\n  | /-- Page dow key. -/\n    pageDown\n  | /-- Tab key.-/\n    tab\n  | /-- Shift + Tab key. -/\n    backtab\n  | /-- Delete key. -/\n    delete\n  | /-- Insert key. -/\n    insert\n  | /-- \n      F key.\n      `KeyCode.f 1` represents F1 key, etc. \n    -/ \n    f : UInt8 \u2192 KeyCode\n  | /--\n      A character. \n      KeyCode::Char('c') represents c character, etc.\n    -/\n    char : Char \u2192 KeyCode\n  | /-- Null. -/\n    null\n  | /-- Escape key. -/\n    esc\n\n-- TODO: something like bitflags.\n/-- Represents key modifiers (shift, control, alt). -/\nstructure KeyModifiers\n\n/-- Represents a key event. -/\nstructure KeyEvent where\n  /-- The key itself. -/\n  code      : KeyCode\n  /-- Additional key modifiers. -/\n  modifiers : KeyModifiers\n\n/-- Represents a mouse button. -/\ninductive MouseButton\n  | left\n  | right\n  | middle\n\n/-- \n  A mouse event kind. \n\n  # Platform-specific Notes\n\n  ## Mouse Buttons\n\n  Some platforms/terminals do not report mouse button for the\n  `MouseEventKind.up` and `MouseEventKind.drag` events. `MouseButton.left`\n  is returned if we don't know which button was used.\n-/\ninductive MouseEventKind\n  | /-- Pressed mouse button. Contains the button that was pressed. -/\n    down : MouseButton \u2192 MouseEventKind\n  | /-- Released mouse button. Contains the button that was released. -/\n    up   : MouseButton \u2192 MouseEventKind\n  | /-- Moved the mouse cursor while pressing the contained mouse button. -/\n    drag : MouseButton \u2192 MouseEventKind\n  |/-- Moved the mouse cursor while not pressing a mouse button. -/ \n    moved\n  | /-- Scrolled mouse wheel downwards (towards the user). -/\n    scrollDown\n  | /-- Scrolled mouse wheel upwards (away from the user). -/\n    scrollUp\n\n/--\n  Represents a mouse event.\n\n  # Platform-specific Notes\n\n  ## Mouse Buttons\n\n  Some platforms/terminals do not report mouse button for the\n  `MouseEventKind.up` and `MouseEventKind.drag` events. `MouseButton.left`\n  is returned if we don't know which button was used.\n\n  ## Key Modifiers\n\n  Some platforms/terminals does not report all key modifiers\n  combinations for all mouse event types. For example - macOS reports\n  `Ctrl` + left mouse button click as a right mouse button click.\n-/\nstructure MouseEvent where\n  /-- The kind of mouse event that was caused. -/\n  kind      : MouseEventKind\n  /-- The column that the event occurred on. -/\n  column    : UInt16\n  /-- The row that the event occurred on. -/\n  row       : UInt16\n  /-- The key modifiers active when the event occurred. -/\n  modifiers : KeyModifiers\n\n/-- Represents an event. -/\ninductive Event\n  | /-- A single key event with additional pressed modifiers. -/\n    key     : KeyEvent \u2192 Event\n  | /-- A single mouse event with additional pressed modifiers. -/\n    mouse   : MouseEvent \u2192 Event\n  | /--\n      An resize event with new dimensions after resize (columns, rows).\n      **Note** that resize events can be occur in batches.\n    -/\n    resize  : UInt16 \u00d7 UInt16 \u2192 Event\n\n-- TODO: add poll\n\n-- /--\n--   Reads a single `Event`\n\n--   This function blocks until an `Event` is available. Combine it with the\n--   `poll` function to get non-blocking reads.\n\n-- -/\n-- def read : IO Event := sorry\n\n/--\n  A command that enables mouse event capturing.\n\n  Mouse events can be captured with `read`/`poll`.\n-/\nstructure EnableMouseCapture\n\ninstance : Command EnableMouseCapture where\n  writeAnsi self f := f.putStr <| \n    -- Normal tracking: Send mouse X & Y on button press and release\n    csi \"?1000h\" ++\n    -- Button-event tracking: Report button motion events (dragging)\n    csi \"?1002h\" ++\n    -- Any-event tracking: Report all motion events\n    csi \"?1003h\" ++\n    -- RXVT mouse mode: Allows mouse coordinates of >223\n    csi \"?1005h\" ++\n    -- SGR mouse mode: Allows mouse coordinates of >223, preferred over RXVT mode\n    csi \"?1006h\"\n\n/--\n  A command that disables mouse event capturing.\n\n  Mouse events can be captured with `read`/`poll`.\n-/\nstructure DisableMouseCapture\n\ninstance : Command DisableMouseCapture where\n  writeAnsi self f := f.putStr <| \n    -- The inverse commands of EnableMouseCapture, in reverse order.\n    csi \"?1006l\" ++\n    csi \"?1015l\" ++\n    csi \"?1003l\" ++\n    csi \"?1002l\" ++\n    csi \"?1001l\"\n\n/--\n  Represents an attribute.\n         \n  # Platform-specific Notes\n  \n  * Only UNIX and Windows 10 terminals do support text attributes.\n  * Keep in mind that not all terminals support all attributes.\n  * lean4-terminal implements almost all attributes listed in the\n    [SGR parameters](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters).\n  \n  | Attribute | Windows | UNIX | Notes |\n  | :-- | :--: | :--: | :-- |\n  | `reset` | \u2713 | \u2713 | |\n  | `bold` | \u2713 | \u2713 | |\n  | `dim` | \u2713 | \u2713 | |\n  | `italic` | ? | ? | Not widely supported, sometimes treated as inverse. |\n  | `underlined` | \u2713 | \u2713 | |\n  | `slowBlink` | ? | ? | Not widely supported, sometimes treated as inverse. |\n  | `rapidBlink` | ? | ? | Not widely supported. MS-DOS ANSI.SYS; 150+ per minute. |\n  | `reverse` | \u2713 | \u2713 | |\n  | `hidden` | \u2713 | \u2713 | Also known as Conceal. |\n  | `fraktur` | \u2717 | \u2713 | Legible characters, but marked for deletion. |\n  | `defaultForegroundColor` | ? | ? | Implementation specific (according to standard). |\n  | `defaultBackgroundColor` | ? | ? | Implementation specific (according to standard). |\n  | `framed` | ? | ? | Not widely supported. |\n  | `encircled` | ? | ? | This should turn on the encircled attribute. |\n  | `overLined` | ? | ? | This should draw a line at the top of the text. |\n-/\ninductive Attribute where\n  | /-- Resets all the attributes. -/\n    reset\n  | /-- Increases the text intensity. -/\n    bold\n  | /-- Decreases the text intensity. -/\n    dim\n  | /-- Emphasises the text. -/\n    italic\n  | /-- Underlines the text. -/\n    underlined\n  | /-- Makes the text blinking (< 150 per minute). -/\n    slowBlink\n  | /-- Makes the text blinking (>= 150 per minute). -/\n    rapidBlink\n  | /-- Swaps foreground and background colors. -/\n    reverse\n  | /-- Hides the text (also known as Conceal). -/\n    hidden\n  | /-- Crosses the text. -/\n    crossedOut\n  | /-- \n      Sets the [Fraktur](https://en.wikipedia.org/wiki/Fraktur) typeface.\n\n      Mostly used for [mathematical alphanumeric symbols](https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols).\n    -/\n    fraktur\n  | /-- Turns off the `bold` attribute. - Inconsistent - Prefer to use normalIntensity -/\n    noBold\n  | /-- Switches the text back to normal intensity (no bold, italic). -/\n    normalIntensity\n  | /-- Turns off the `Italic` attribute. -/\n    noItalic\n  | /-- Turns off the `Underlined` attribute. -/\n    noUnderline\n  | /-- Turns off the text blinking (`SlowBlink` or `RapidBlink`). -/\n    noBlink\n  | /-- Turns off the `Reverse` attribute. -/\n    noReverse\n  | /-- Turns off the `Hidden` attribute. -/\n    noHidden\n  | /-- Turns off the `CrossedOut` attribute. -/\n    notCrossedOut\n  | /-- Makes the text framed. -/\n    framed\n  | /-- Makes the text encircled. -/\n    encircled\n  | /--  Draws a line at the top of the text.. -/\n    overLined\n  | /-- Turns off the `Frame` and `Encircled` attributes. -/\n    notFramedOrEncircled\n  | /-- Turns off the `OverLined` attribute. -/\n    notOverLined\n\n/--\n  Returns the SGR attribute value.\n\n  See <https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters>\n-/\ndef Attribute.sgr : Attribute \u2192 UInt16\n  | Attribute.reset                 =>  0\n  | Attribute.bold                  =>  1\n  | Attribute.dim                   =>  2\n  | Attribute.italic                =>  3\n  | Attribute.underlined            =>  4\n  | Attribute.slowBlink             =>  5\n  | Attribute.rapidBlink            =>  6\n  | Attribute.reverse               =>  7\n  | Attribute.hidden                =>  8\n  | Attribute.crossedOut            =>  9\n  | Attribute.fraktur               => 20\n  | Attribute.noBold                => 21\n  | Attribute.normalIntensity       => 22\n  | Attribute.noItalic              => 23\n  | Attribute.noUnderline           => 24\n  | Attribute.noBlink               => 25\n  | Attribute.noReverse             => 27\n  | Attribute.noHidden              => 28\n  | Attribute.notCrossedOut         => 29\n  | Attribute.framed                => 51\n  | Attribute.encircled             => 52\n  | Attribute.overLined             => 53\n  | Attribute.notFramedOrEncircled  => 54\n  | Attribute.notOverLined          => 55\n\n/--\n  Represents a color.\n \n  # Platform-specific Notes\n \n  The following list of 16 base colors are available for almost all terminals (Windows 7 and 8 included).\n \n  | Light | dark |\n  | :--| :--   |\n  | `darkGrey` | `black` |\n  | `red` | `darkRed` |\n  | `green` | `darkGreen` |\n  | `yellow` | `darkYellow` |\n  | `blue` | `darkBlue` |\n  | `magenta` | `darkMagenta` |\n  | `cyan` | `darkCyan` |\n  | `white` | `grey` |\n \n  Most UNIX terminals and Windows 10 consoles support additional colors.\n  See `Color.rgb` or `Color.ansiValue` for more info.\n-/\ninductive Color where\n  | /-- Resets the terminal color. -/\n    reset\n  | /-- Black color. -/\n    black\n  | /-- Dark grey color. -/\n    darkGrey\n  | /-- Light red color. -/\n    red\n  | /-- Dark red color. -/\n    darkRed\n  | /-- Light green color. -/\n    green\n  | /-- Dark green color. -/\n    darkGreen\n  | /-- Light yellow color. -/\n    yellow\n  | /-- Dark yellow color. -/\n    darkYellow\n  | /-- Light blue color. -/\n    blue\n  | /-- Dark blue color. -/\n    darkBlue\n  | /-- Light magenta color. -/\n    magenta\n  | /-- Dark magenta color. -/\n    darkMagenta\n  | /-- Light cyan color. -/\n    cyan\n  | /-- Dark cyan color. -/\n    darkCyan\n  | /-- White color. -/\n    white\n  | /-- Grey color. -/\n    grey\n  | /-- \n      An RGB color. See [RGB color model](https://en.wikipedia.org/wiki/RGB_color_model) for more info.\n\n      Most UNIX terminals and Windows 10 supported only.\n      See Platform-specific notes for more info.\n      -/\n    rgb (r g b : UInt8) : Color\n  | /-- \n      An ANSI color. See [256 colors - cheat sheet](https://jonasjacek.github.io/colors/) for more info.\n\n      Most UNIX terminals and Windows 10 supported only.\n      See Platform-specific notes for more info. -/\n  ansiValue : UInt8 \u2192 Color\n\n/--\n  Represents a foreground or background color.\n-/\ninductive Colored\n  | /-- A foreground color. -/\n    foregroundColor : Color \u2192 Colored\n  | /-- A background color. -/\n    backgroundColor : Color \u2192 Colored\n\ndef Colored.toString (colored : Colored) : String := \n  match colored with\n  | Colored.foregroundColor c => \n    match c with\n    | Color.reset => \"39\"\n    | Color.black => fg \"5;0\"\n    | Color.darkGrey => fg \"5;8\"\n    | Color.red => fg \"5;9\"\n    | Color.darkRed => fg \"5;1\"\n    | Color.green => fg \"5;10\"\n    | Color.darkGreen => fg \"5;2\"\n    | Color.yellow => fg \"5;11\"\n    | Color.darkYellow => fg \"5;3\"\n    | Color.blue => fg \"5;12\"\n    | Color.darkBlue => fg \"5;4\"\n    | Color.magenta => fg \"5;13\"\n    | Color.darkMagenta => fg \"5;5\"\n    | Color.cyan => fg \"5;14\"\n    | Color.darkCyan => fg \"5;6\"\n    | Color.white => fg \"5;15\"\n    | Color.grey => fg \"5;7\"\n    | Color.rgb r g b => fg s!\"2;{r};{g};{b}\"\n    | Color.ansiValue v => fg s!\"5;{v}\"\n  | Colored.backgroundColor c => \n    match c with\n    | Color.reset => \"49\"\n    | Color.black => bg \"5;0\"\n    | Color.darkGrey => bg \"5;8\"\n    | Color.red => bg \"5;9\"\n    | Color.darkRed => bg \"5;1\"\n    | Color.green => bg \"5;10\"\n    | Color.darkGreen => bg \"5;2\"\n    | Color.yellow => bg \"5;11\"\n    | Color.darkYellow => bg \"5;3\"\n    | Color.blue => bg \"5;12\"\n    | Color.darkBlue => bg \"5;4\"\n    | Color.magenta => bg \"5;13\"\n    | Color.darkMagenta => bg \"5;5\"\n    | Color.cyan => bg \"5;14\"\n    | Color.darkCyan => bg \"5;6\"\n    | Color.white => bg \"5;15\"\n    | Color.grey => bg \"5;7\"\n    | Color.rgb r g b => bg s!\"2;{r};{g};{b}\"\n    | Color.ansiValue v => bg s!\"5;{v}\"\n  where\n    fg s := \"38;\" ++ s\n    bg s := \"48;\" ++ s\n\ninstance : ToString Colored := \u27e8 Colored.toString \u27e9 \n\n/--\n  Returns available color count.\n\n  # Notes\n\n  - This does not always provide a good result.\n-/\ndef availableColorCount : IO UInt16 := do\n  let term \u2190 IO.getEnv \"TERM\"\n  return match term with\n  | some x => if \"256color\".isInfixOf x then 256 else 8\n  | _      => 8\n\n/--\n  A command that sets the the foreground color.\n  See `Color` for more info.\n \n  # Notes\n \n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SetForegroundColor := (c : Color)\n\ninstance : Command SetForegroundColor where\n  writeAnsi self f := f.putStr <| csi s!\"{Colored.foregroundColor self.c}m\"\n\n/--\n  A command that sets the the background color.\n\n  See `Color` for more info.\n \n  # Notes\n \n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SetBackgroundColor := (c : Color)\n\ninstance : Command SetBackgroundColor where\n  writeAnsi self f := f.putStr <| csi s!\"{Colored.backgroundColor self.c}m\"\n\n/--\n  A command that prints the given displayable type.\n\n  ## Notes\n\n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure Print (\u03b1 : Type u) [ToString \u03b1] := (s : \u03b1)\n\ninstance [inst: ToString \u03b1] : Command (Print \u03b1) where\n  writeAnsi self f := f.putStr <| ToString.toString self.s\n\n/--\n  A command that resets the colors back to default.\n \n  # Notes\n \n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure ResetColor\n\ninstance : Command ResetColor where\n  writeAnsi self f := f.putStr <| csi \"0m\"\n\n/--\n  A command that sets an attribute.\n \n  See `Attribute` for more info.\n \n  # Notes\n \n  - Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SetAttribute := (a : Attribute)\n\ninstance : Command SetAttribute where\n  writeAnsi self f := f.putStr <| csi s!\"{self.a.sgr}m\"\n\n/-- Different ways to clear the terminal buffer. -/\ninductive ClearType\n  | /-- All cells. -/\n    all \n  | /-- All plus history. -/\n    purge\n  | /-- All cells from the cursor position downwards. -/\n    fromCursorDown\n  | /-- All cells from the cursor position upwards. -/\n    fromCursorUp\n  | /-- All cells at the cursor row. -/\n    currentLine\n  | /-- All cells from the cursor position until the new line. -/\n    untilNewLine\n\n/--\n  A command that clears the terminal screen buffer.\n \n  See the `ClearType` enum.\n \n  # Notes\n \n  Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure Clear := (t : ClearType)\n\ninstance : Command Clear where\n  writeAnsi self f := f.putStr <| csi <|\n    match self.t with\n    | ClearType.all             => \"2J\"\n    | ClearType.purge           => \"3J\"\n    | ClearType.fromCursorDown  => \"J\"\n    | ClearType.fromCursorUp    => \"1J\"\n    | ClearType.currentLine     => \"2K\"\n    | ClearType.untilNewLine    => \"K\"\n\n/-- Disables line wrapping. -/\nstructure DisableLineWrap\n\ninstance : Command DisableLineWrap where\n  writeAnsi self f := f.putStr <| csi \"?7l\"\n\n/-- Enable line wrapping. -/\nstructure EnableLineWrap\n\ninstance : Command EnableLineWrap where\n  writeAnsi self f := f.putStr <| csi \"?7h\"\n\n/--\n  A command that switches to alternate screen.\n \n  # Notes\n \n  * Commands must be executed/queued for execution otherwise they do nothing.\n  * Use `LeaveAlternateScreen` command to leave the entered alternate screen.\n-/\nstructure EnterAlternateScreen\n\ninstance : Command EnterAlternateScreen where\n  writeAnsi self f := f.putStr <| csi \"?1049h\"\n\n/--\n  A command that switches back to the main screen.\n \n  # Notes\n \n  * Commands must be executed/queued for execution otherwise they do nothing.\n  * Use `EnterAlternateScreen` to enter the alternate screen.\n \n-/\nstructure LeaveAlternateScreen\n\ninstance : Command LeaveAlternateScreen where\n  writeAnsi self f := f.putStr <| csi \"?1049l\"\n\n/--\n  A command that scrolls the terminal screen a given number of rows down.\n \n  # Notes\n \n  Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure ScrollDown := (n : UInt16)\n\ninstance : Command ScrollDown where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}T\"\n\n/--\n  A command that scrolls the terminal screen a given number of rows up.\n \n  # Notes\n \n  Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure ScrollUp := (n : UInt16)\n\ninstance : Command ScrollUp where\n  writeAnsi self f := f.putStr <| csi s!\"{self.n}S\"\n\n/--\n  A command that sets the terminal size `(columns, rows)`.\n \n  # Notes\n \n  Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SetSize := (c r : UInt16)\n\ninstance : Command SetSize where\n  writeAnsi self f := f.putStr <| csi s!\"8;{self.r};{self.c}t\"\n\n/--\n  A command that sets the terminal title\n \n  # Notes\n \n  Commands must be executed/queued for execution otherwise they do nothing.\n-/\nstructure SetTitle (\u03b1 : Type u) [ToString \u03b1] := (s : \u03b1)\n\ninstance [inst: ToString \u03b1] : Command (SetTitle \u03b1) where\n  writeAnsi self f := f.putStr <| csi s!\"\\x1B]0;{ToString.toString self.s}\\x07\"\n\n@[extern \"lean_disable_raw_mode\"]\nconstant disableRawMode.prim : Unit \u2192 IO Unit\n\n/-- Disables raw mode. -/\ndef disableRawMode : IO Unit := disableRawMode.prim ()\n\n@[extern \"lean_enable_raw_mode\"]\nconstant enableRawMode.prim : Unit \u2192 IO Unit\n\n/-- Enables raw mode. -/\ndef enableRawMode : IO Unit := enableRawMode.prim ()\n\n@[extern \"lean_is_raw_mode_enabled\"]\nconstant isRawModeEnabled.prim : Unit \u2192 IO Bool\n\n/-- Tells whether the raw mode is enabled. -/\ndef isRawModeEnabled : IO Bool := isRawModeEnabled.prim ()\n\n@[extern \"lean_get_is_tty\"]\nprivate constant isTty.prim : Unit \u2192 IO Bool\n\n/--\n  Returns true when we are in a terminal, otherwise false.\n-/\ndef isTty : IO Bool := isTty.prim ()\n\n@[extern \"lean_get_size\"]\nprivate constant size.prim : Unit \u2192 IO (UInt16 \u00d7 UInt16)\n\n/--\n  Returns the terminal size `(columns, rows)`.\n-/\ndef size : IO (UInt16 \u00d7 UInt16) := size.prim ()\n\n/-- Queues the given command for further execution. -/\ndef queue [Terminal.Command \u03b1] (cs : Array \u03b1) : IO Unit := do\n  cs.forM (Terminal.Command.writeAnsi \u00b7 (\u2190 IO.getStdout))\n\n/-- Executes the given command directly. -/\ndef execute [Terminal.Command \u03b1] (cs : Array \u03b1) : IO Unit := do\n  let out \u2190 IO.getStdout\n  cs.forM (Terminal.Command.writeAnsi \u00b7 out)\n  out.flush\n\nend Terminal", "meta": {"author": "xubaiw", "repo": "lean4-terminal", "sha": "0166c1715aa903200464fc11f89c591bbd8530b6", "save_path": "github-repos/lean/xubaiw-lean4-terminal", "path": "github-repos/lean/xubaiw-lean4-terminal/lean4-terminal-0166c1715aa903200464fc11f89c591bbd8530b6/Terminal.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1561049013715009, "lm_q2_score": 0.026355353802057137, "lm_q1q2_score": 0.004114199905881141}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Parser.Term\nimport Lean.Parser.Do\n\nnamespace Lean\nnamespace Parser\n\n/-- Syntax quotation for terms. -/\n@[builtin_term_parser] def Term.quot := leading_parser\n  \"`(\" >> withoutPosition (incQuotDepth termParser) >> \")\"\n@[builtin_term_parser] def Term.precheckedQuot := leading_parser\n  \"`\" >> Term.quot\n\nnamespace Command\n\n/--\nSyntax quotation for (sequences of) commands.\nThe identical syntax for term quotations takes priority,\nso ambiguous quotations like `` `($x $y) `` will be parsed as an application,\nnot two commands. Use `` `($x:command $y:command) `` instead.\nMultiple commands will be put in a `` `null `` node,\nbut a single command will not (so that you can directly\nmatch against a quotation in a command kind's elaborator). -/\n@[builtin_term_parser low] def quot := leading_parser\n  \"`(\" >> withoutPosition (incQuotDepth (many1Unbox commandParser)) >> \")\"\n\n/-\nA mutual block may be broken in different cliques,\nwe identify them using an `ident` (an element of the clique).\nWe provide two kinds of hints to the termination checker:\n1- A wellfounded relation (`p` is `termParser`)\n2- A tactic for proving the recursive applications are \"decreasing\" (`p` is `tacticSeq`)\n-/\ndef terminationHintMany (p : Parser) := leading_parser\n  atomic (lookahead (ident >> \" => \")) >>\n  many1Indent (group (ppLine >> ident >> \" => \" >> p >> optional \";\"))\ndef terminationHint1 (p : Parser) := leading_parser p\ndef terminationHint (p : Parser) := terminationHintMany p <|> terminationHint1 p\n\ndef terminationByCore := leading_parser\n  \"termination_by' \" >> terminationHint termParser\ndef decreasingBy := leading_parser\n  \"decreasing_by \" >> terminationHint Tactic.tacticSeq\n\ndef terminationByElement   := leading_parser\n  ppLine >> (ident <|> Term.hole) >> many (ident <|> Term.hole) >>\n  \" => \" >> termParser >> optional \";\"\ndef terminationBy          := leading_parser\n  ppLine >> \"termination_by \" >> many1Indent terminationByElement\n\ndef terminationSuffix :=\n  optional (terminationBy <|> terminationByCore) >> optional decreasingBy\n\n@[builtin_command_parser]\ndef moduleDoc := leading_parser ppDedent <|\n  \"/-!\" >> commentBody >> ppLine\n\ndef namedPrio := leading_parser\n  atomic (\"(\" >> nonReservedSymbol \"priority\") >> \" := \" >> withoutPosition priorityParser >> \")\"\ndef optNamedPrio := optional (ppSpace >> namedPrio)\n\ndef \u00abprivate\u00bb        := leading_parser \"private \"\ndef \u00abprotected\u00bb      := leading_parser \"protected \"\ndef visibility       := \u00abprivate\u00bb <|> \u00abprotected\u00bb\ndef \u00abnoncomputable\u00bb  := leading_parser \"noncomputable \"\ndef \u00abunsafe\u00bb         := leading_parser \"unsafe \"\ndef \u00abpartial\u00bb        := leading_parser \"partial \"\ndef \u00abnonrec\u00bb         := leading_parser \"nonrec \"\ndef declModifiers (inline : Bool) := leading_parser\n  optional docComment >>\n  optional (Term.\u00abattributes\u00bb >> if inline then skip else ppDedent ppLine) >>\n  optional visibility >>\n  optional \u00abnoncomputable\u00bb >>\n  optional \u00abunsafe\u00bb >>\n  optional (\u00abpartial\u00bb <|> \u00abnonrec\u00bb)\ndef declId           := leading_parser\n  ident >> optional (\".{\" >> sepBy1 ident \", \" >> \"}\")\ndef declSig          := leading_parser\n  many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.typeSpec\ndef optDeclSig       := leading_parser\n  many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.optType\ndef declValSimple    := leading_parser\n  \" :=\" >> ppHardLineUnlessUngrouped >> termParser >> optional Term.whereDecls\ndef declValEqns      := leading_parser\n  Term.matchAltsWhereDecls\ndef whereStructField := leading_parser\n  Term.letDecl\ndef whereStructInst  := leading_parser\n  ppIndent ppSpace >> \"where\" >> sepByIndent (ppGroup whereStructField) \"; \" (allowTrailingSep := true) >>\n  optional Term.whereDecls\n/-\n  Remark: we should not use `Term.whereDecls` at `declVal`\n  because `Term.whereDecls` is defined using `Term.letRecDecl` which may contain attributes.\n  Issue #753 showns an example that fails to be parsed when we used `Term.whereDecls`.\n-/\ndef declVal          :=\n  withAntiquot (mkAntiquot \"declVal\" `Lean.Parser.Command.declVal (isPseudoKind := true)) <|\n    declValSimple <|> declValEqns <|> whereStructInst\ndef \u00ababbrev\u00bb         := leading_parser\n  \"abbrev \" >> declId >> ppIndent optDeclSig >> declVal >> terminationSuffix\ndef optDefDeriving   :=\n  optional (atomic (\"deriving \" >> notSymbol \"instance\") >> sepBy1 ident \", \")\ndef \u00abdef\u00bb            := leading_parser\n  \"def \" >> declId >> ppIndent optDeclSig >> declVal >> optDefDeriving >> terminationSuffix\ndef \u00abtheorem\u00bb        := leading_parser\n  \"theorem \" >> declId >> ppIndent declSig >> declVal >> terminationSuffix\ndef \u00abopaque\u00bb         := leading_parser\n  \"opaque \" >> declId >> ppIndent declSig >> optional declValSimple\n/- As `declSig` starts with a space, \"instance\" does not need a trailing space\n  if we put `ppSpace` in the optional fragments. -/\ndef \u00abinstance\u00bb       := leading_parser\n  Term.attrKind >> \"instance\" >> optNamedPrio >>\n  optional (ppSpace >> declId) >> ppIndent declSig >> declVal >> terminationSuffix\ndef \u00abaxiom\u00bb          := leading_parser\n  \"axiom \" >> declId >> ppIndent declSig\n/- As `declSig` starts with a space, \"example\" does not need a trailing space. -/\ndef \u00abexample\u00bb        := leading_parser\n  \"example\" >> ppIndent optDeclSig >> declVal\ndef ctor             := leading_parser\n  atomic (optional docComment >> \"\\n| \") >>\n  ppGroup (declModifiers true >> rawIdent >> optDeclSig)\ndef derivingClasses  := sepBy1 (group (ident >> optional (\" with \" >> Term.structInst))) \", \"\ndef optDeriving      := leading_parser\n  optional (ppLine >> atomic (\"deriving \" >> notSymbol \"instance\") >> derivingClasses)\ndef computedField    := leading_parser\n  declModifiers true >> ident >> \" : \" >> termParser >> Term.matchAlts\ndef computedFields   := leading_parser\n  \"with\" >> manyIndent (ppLine >> ppGroup computedField)\n/--\nIn Lean, every concrete type other than the universes\nand every type constructor other than dependent arrows\nis an instance of a general family of type constructions known as inductive types.\nIt is remarkable that it is possible to construct a substantial edifice of mathematics\nbased on nothing more than the type universes, dependent arrow types, and inductive types;\neverything else follows from those.\nIntuitively, an inductive type is built up from a specified list of constructor.\nFor example, `List \u03b1` is the list of elements of type `\u03b1`, and is defined as follows:\n```\ninductive List (\u03b1 : Type u) where\n| nil\n| cons (head : \u03b1) (tail : List \u03b1)\n```\nA list of elements of type `\u03b1` is either the empty list, `nil`,\nor an element `head : \u03b1` followed by a list `tail : List \u03b1`.\nFor more information about [inductive types](https://leanprover.github.io/theorem_proving_in_lean4/inductive_types.html).\n-/\ndef \u00abinductive\u00bb      := leading_parser\n  \"inductive \" >> declId >> optDeclSig >> optional (symbol \" :=\" <|> \" where\") >>\n  many ctor >> optional (ppDedent ppLine >> computedFields) >> optDeriving\ndef classInductive   := leading_parser\n  atomic (group (symbol \"class \" >> \"inductive \")) >>\n  declId >> ppIndent optDeclSig >>\n  optional (symbol \" :=\" <|> \" where\") >> many ctor >> optDeriving\ndef structExplicitBinder := leading_parser\n  atomic (declModifiers true >> \"(\") >>\n  withoutPosition (many1 ident >> ppIndent optDeclSig >>\n    optional (Term.binderTactic <|> Term.binderDefault)) >> \")\"\ndef structImplicitBinder := leading_parser\n  atomic (declModifiers true >> \"{\") >> withoutPosition (many1 ident >> declSig) >> \"}\"\ndef structInstBinder     := leading_parser\n  atomic (declModifiers true >> \"[\") >> withoutPosition (many1 ident >> declSig) >> \"]\"\ndef structSimpleBinder   := leading_parser\n  atomic (declModifiers true >> ident) >> optDeclSig >>\n  optional (Term.binderTactic <|> Term.binderDefault)\ndef structFields         := leading_parser\n  manyIndent <|\n    ppLine >> checkColGe >> ppGroup (\n      structExplicitBinder <|> structImplicitBinder <|>\n      structInstBinder <|> structSimpleBinder)\ndef structCtor           := leading_parser\n  atomic (declModifiers true >> ident >> \" :: \")\ndef structureTk          := leading_parser\n  \"structure \"\ndef classTk              := leading_parser\n  \"class \"\ndef \u00abextends\u00bb            := leading_parser\n  \" extends \" >> sepBy1 termParser \", \"\ndef \u00abstructure\u00bb          := leading_parser\n    (structureTk <|> classTk) >>\n    declId >> many (ppSpace >> Term.bracketedBinder) >>\n    optional \u00abextends\u00bb >> Term.optType >>\n    optional ((symbol \" := \" <|> \" where \") >> optional structCtor >> structFields) >>\n    optDeriving\n@[builtin_command_parser] def declaration := leading_parser\n  declModifiers false >>\n  (\u00ababbrev\u00bb <|> \u00abdef\u00bb <|> \u00abtheorem\u00bb <|> \u00abopaque\u00bb <|> \u00abinstance\u00bb <|> \u00abaxiom\u00bb <|> \u00abexample\u00bb <|>\n   \u00abinductive\u00bb <|> classInductive <|> \u00abstructure\u00bb)\n@[builtin_command_parser] def \u00abderiving\u00bb     := leading_parser\n  \"deriving \" >> \"instance \" >> derivingClasses >> \" for \" >> sepBy1 ident \", \"\n@[builtin_command_parser] def noncomputableSection := leading_parser\n  \"noncomputable \" >> \"section \" >> optional ident\n@[builtin_command_parser] def \u00absection\u00bb      := leading_parser\n  \"section \" >> optional ident\n@[builtin_command_parser] def \u00abnamespace\u00bb    := leading_parser\n  \"namespace \" >> ident\n@[builtin_command_parser] def \u00abend\u00bb          := leading_parser\n  \"end \" >> optional ident\n@[builtin_command_parser] def \u00abvariable\u00bb     := leading_parser\n  \"variable\" >> many1 (ppSpace >> Term.bracketedBinder)\n@[builtin_command_parser] def \u00abuniverse\u00bb     := leading_parser\n  \"universe \" >> many1 ident\n@[builtin_command_parser] def check          := leading_parser\n  \"#check \" >> termParser\n@[builtin_command_parser] def check_failure  := leading_parser\n  \"#check_failure \" >> termParser -- Like `#check`, but succeeds only if term does not type check\n@[builtin_command_parser] def reduce         := leading_parser\n  \"#reduce \" >> termParser\n@[builtin_command_parser] def eval           := leading_parser\n  \"#eval \" >> termParser\n@[builtin_command_parser] def synth          := leading_parser\n  \"#synth \" >> termParser\n@[builtin_command_parser] def exit           := leading_parser\n  \"#exit\"\n@[builtin_command_parser] def print          := leading_parser\n  \"#print \" >> (ident <|> strLit)\n@[builtin_command_parser] def printAxioms    := leading_parser\n  \"#print \" >> nonReservedSymbol \"axioms \" >> ident\n@[builtin_command_parser] def \u00abinit_quot\u00bb    := leading_parser\n  \"init_quot\"\ndef optionValue := nonReservedSymbol \"true\" <|> nonReservedSymbol \"false\" <|> strLit <|> numLit\n@[builtin_command_parser] def \u00abset_option\u00bb   := leading_parser\n  \"set_option \" >> ident >> ppSpace >> optionValue\ndef eraseAttr := leading_parser\n  \"-\" >> rawIdent\n@[builtin_command_parser] def \u00abattribute\u00bb    := leading_parser\n  \"attribute \" >> \"[\" >>\n    withoutPosition (sepBy1 (eraseAttr <|> Term.attrInstance) \", \") >>\n  \"] \" >> many1 ident\n@[builtin_command_parser] def \u00abexport\u00bb       := leading_parser\n  \"export \" >> ident >> \" (\" >> many1 ident >> \")\"\n@[builtin_command_parser] def \u00abimport\u00bb       := leading_parser\n  \"import\" -- not a real command, only for error messages\ndef openHiding       := leading_parser\n  atomic (ident >> \"hiding\") >> many1 (checkColGt >> ident)\ndef openRenamingItem := leading_parser\n  ident >> unicodeSymbol \" \u2192 \" \" -> \" >> checkColGt >> ident\ndef openRenaming     := leading_parser\n  atomic (ident >> \"renaming\") >> sepBy1 openRenamingItem \", \"\ndef openOnly         := leading_parser\n  atomic (ident >> \" (\") >> many1 ident >> \")\"\ndef openSimple       := leading_parser\n  many1 (checkColGt >> ident)\ndef openScoped       := leading_parser\n  \"scoped \" >> many1 (checkColGt >> ident)\ndef openDecl         :=\n  withAntiquot (mkAntiquot \"openDecl\" `Lean.Parser.Command.openDecl (isPseudoKind := true)) <|\n    openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped\n@[builtin_command_parser] def \u00abopen\u00bb    := leading_parser\n  withPosition (\"open \" >> openDecl)\n\n@[builtin_command_parser] def \u00abmutual\u00bb := leading_parser\n  \"mutual \" >> many1 (ppLine >> notSymbol \"end\" >> commandParser) >>\n  ppDedent (ppLine >> \"end\") >> terminationSuffix\ndef initializeKeyword := leading_parser\n  \"initialize \" <|> \"builtin_initialize \"\n@[builtin_command_parser] def \u00abinitialize\u00bb := leading_parser\n  declModifiers false >> initializeKeyword >>\n  optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq\n\n@[builtin_command_parser] def \u00abin\u00bb  := trailing_parser withOpen (\" in \" >> commandParser)\n\n@[builtin_command_parser] def addDocString := leading_parser\n  docComment >> \"add_decl_doc\" >> ident\n\n/--\n  This is an auxiliary command for generation constructor injectivity theorems for\n  inductive types defined at `Prelude.lean`.\n  It is meant for bootstrapping purposes only. -/\n@[builtin_command_parser] def genInjectiveTheorems := leading_parser\n  \"gen_injective_theorems% \" >> ident\n\n/-- No-op parser used as syntax kind for attaching remaining whitespace to at the end of the input. -/\n@[run_builtin_parser_attribute_hooks] def eoi : Parser := leading_parser \"\"\n\nbuiltin_initialize\n  registerBuiltinNodeKind ``eoi\n\n@[run_builtin_parser_attribute_hooks] abbrev declModifiersF := declModifiers false\n@[run_builtin_parser_attribute_hooks] abbrev declModifiersT := declModifiers true\n\nbuiltin_initialize\n  register_parser_alias (kind := ``declModifiers) \"declModifiers\"       declModifiersF\n  register_parser_alias (kind := ``declModifiers) \"nestedDeclModifiers\" declModifiersT\n  register_parser_alias                                                 declId\n  register_parser_alias                                                 declSig\n  register_parser_alias                                                 declVal\n  register_parser_alias                                                 optDeclSig\n  register_parser_alias                                                 openDecl\n  register_parser_alias                                                 docComment\n\nend Command\n\nnamespace Term\n/--\n`open Foo in e` is like `open Foo` but scoped to a single term.\nIt makes the given namespaces available in the term `e`.\n-/\n@[builtin_term_parser] def \u00abopen\u00bb := leading_parser:leadPrec\n  \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> termParser)\n\n/--\n`set_option opt val in e` is like `set_option opt val` but scoped to a single term.\nIt sets the option `opt` to the value `val` in the term `e`.\n-/\n@[builtin_term_parser] def \u00abset_option\u00bb := leading_parser:leadPrec\n  \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> termParser\nend Term\n\nnamespace Tactic\n/-- `open Foo in tacs` (the tactic) acts like `open Foo` at command level,\nbut it opens a namespace only within the tactics `tacs`. -/\n@[builtin_tactic_parser] def \u00abopen\u00bb := leading_parser:leadPrec\n  \"open \" >> Command.openDecl >> withOpenDecl (\" in \" >> tacticSeq)\n\n/-- `set_option opt val in tacs` (the tactic) acts like `set_option opt val` at the command level,\nbut it sets the option only within the tactics `tacs`. -/\n@[builtin_tactic_parser] def \u00abset_option\u00bb := leading_parser:leadPrec\n  \"set_option \" >> ident >> ppSpace >> Command.optionValue >> \" in \" >> tacticSeq\nend Tactic\n\nend Parser\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/Parser/Command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940273159163906, "lm_q2_score": 0.031618765557674414, "lm_q1q2_score": 0.004091554632718704}}
{"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.Tactic.Constructor\nimport Lean.Meta.Tactic.Assert\nimport Lean.Meta.Tactic.Clear\nimport Lean.Meta.Tactic.Rename\nimport Lean.Elab.Tactic.Basic\nimport Lean.Elab.SyntheticMVars\n\nnamespace Lean.Elab.Tactic\nopen Meta\n\n/-! # `elabTerm` for Tactics and basic tactics that use it. -/\n\n/--\nRuns a term elaborator inside a tactic.\n\nThis function ensures that term elaboration fails when backtracking,\ni.e., in `first| tac term | other`.\n-/\ndef runTermElab (k : TermElabM \u03b1) (mayPostpone := false) : TacticM \u03b1 := do\n  /- If error recovery is disabled, we disable `Term.withoutErrToSorry` -/\n  if (\u2190 read).recover then\n    go\n  else\n    Term.withoutErrToSorry go\nwhere\n  go := k <* Term.synthesizeSyntheticMVars (mayPostpone := mayPostpone)\n\n/-- Elaborate `stx` in the current `MVarContext`. If given, the `expectedType` will be used to help\nelaboration but not enforced (use `elabTermEnsuringType` to enforce an expected type). -/\ndef elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr :=\n  withRef stx do instantiateMVars <| \u2190 runTermElab (mayPostpone := mayPostpone) do\n    Term.elabTerm stx expectedType?\n\n/-- Elaborate `stx` in the current `MVarContext`. If given, the `expectedType` will be used to help\nelaboration and then a `TypeMismatchError` will be thrown if the elaborated type doesn't match.  -/\ndef elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do\n  let e \u2190 elabTerm stx expectedType? mayPostpone\n  -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here.\n  match expectedType? with\n  | none => return e\n  | some expectedType =>\n    let eType \u2190 inferType e\n    -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really\n    -- part of the elaboration, but part of the tactic. See issue #492\n    unless (\u2190 withAssignableSyntheticOpaque <| isDefEq eType expectedType) do\n      Term.throwTypeMismatchError none expectedType eType e\n    return e\n\n/-- Try to close main goal using `x target`, where `target` is the type of the main goal.  -/\ndef closeMainGoalUsing (x : Expr \u2192 TacticM Expr) (checkUnassigned := true) : TacticM Unit :=\n  withMainContext do\n    closeMainGoal (checkUnassigned := checkUnassigned) (\u2190 x (\u2190 getMainTarget))\n\ndef logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do\n   if (\u2190 Term.logUnassignedUsingErrorInfos mvarIds) then\n     throwAbortTactic\n\ndef filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do\n  let mctx \u2190 getMCtx\n  return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved\n\n@[builtin_tactic \u00abexact\u00bb] def evalExact : Tactic := fun stx =>\n  match stx with\n  | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do\n    let mvarCounterSaved := (\u2190 getMCtx).mvarCounter\n    let r \u2190 elabTermEnsuringType e type\n    logUnassignedAndAbort (\u2190 filterOldMVars (\u2190 getMVars r) mvarCounterSaved)\n    return r\n  | _ => throwUnsupportedSyntax\n\ndef sortMVarIdArrayByIndex [MonadMCtx m] [Monad m] (mvarIds : Array MVarId) : m (Array MVarId) := do\n  let mctx \u2190 getMCtx\n  return mvarIds.qsort fun mvarId\u2081 mvarId\u2082 =>\n    let decl\u2081 := mctx.getDecl mvarId\u2081\n    let decl\u2082 := mctx.getDecl mvarId\u2082\n    if decl\u2081.index != decl\u2082.index then\n      decl\u2081.index < decl\u2082.index\n    else\n      Name.quickLt mvarId\u2081.name mvarId\u2082.name\n\ndef sortMVarIdsByIndex [MonadMCtx m] [Monad m] (mvarIds : List MVarId) : m (List MVarId) :=\n  return (\u2190 sortMVarIdArrayByIndex mvarIds.toArray).toList\n\n/--\n  Execute `k`, and collect new \"holes\" in the resulting expression.\n-/\ndef withCollectingNewGoalsFrom (k : TacticM Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr \u00d7 List MVarId) :=\n  /-\n  When `allowNaturalHoles = true`, unassigned holes should become new metavariables, including `_`s.\n  Thus, we set `holesAsSynthethicOpaque` to true if it is not already set to `true`.\n  See issue #1681. We have the tactic\n  ```\n  `refine' (fun x => _)\n  ```\n  If we create a natural metavariable `?m` for `_` with type `Nat`, then when we try to abstract `x`,\n  a new metavariable `?n` with type `Nat -> Nat` is created, and we assign `?m := ?n x`,\n  and the resulting term is `fun x => ?n x`. Then, `getMVarsNoDelayed` would return `?n` as a new goal\n  which would be confusing since it has type `Nat -> Nat`.\n  -/\n  if allowNaturalHoles then\n    withTheReader Term.Context (fun ctx => { ctx with holesAsSyntheticOpaque := ctx.holesAsSyntheticOpaque || allowNaturalHoles }) do\n      /-\n      We also enable the assignment of synthetic metavariables, otherwise we will fail to\n      elaborate terms such as `f _ x` where `f : (\u03b1 : Type) \u2192 \u03b1 \u2192 \u03b1` and `x : A`.\n\n      IMPORTANT: This is not a perfect solution. For example, `isDefEq` will be able assign metavariables associated with `by ...`.\n      This should not be an immediate problem since this feature is only used to implement `refine'`. If it becomes\n      an issue in practice, we should add a new kind of opaque metavariable for `refine'`, and mark the holes created using `_`\n      with it, and have a flag that allows us to assign this kind of metavariable, but prevents us from assigning metavariables\n      created by the `by ...` notation.\n      -/\n      withAssignableSyntheticOpaque go\n  else\n    go\nwhere\n  go := do\n    let mvarCounterSaved := (\u2190 getMCtx).mvarCounter\n    let val \u2190 k\n    let newMVarIds \u2190 getMVarsNoDelayed val\n    /- ignore let-rec auxiliary variables, they are synthesized automatically later -/\n    let newMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 Term.isLetRecAuxMVar mvarId)\n    let newMVarIds \u2190 if allowNaturalHoles then\n      pure newMVarIds.toList\n    else\n      let naturalMVarIds \u2190 newMVarIds.filterM fun mvarId => return (\u2190 mvarId.getKind).isNatural\n      let syntheticMVarIds \u2190 newMVarIds.filterM fun mvarId => return !(\u2190 mvarId.getKind).isNatural\n      let naturalMVarIds \u2190 filterOldMVars naturalMVarIds mvarCounterSaved\n      logUnassignedAndAbort naturalMVarIds\n      pure syntheticMVarIds.toList\n    /-\n    We sort the new metavariable ids by index to ensure the new goals are ordered using the order the metavariables have been created.\n    See issue #1682.\n    Potential problem: if elaboration of subterms is delayed the order the new metavariables are created may not match the order they\n    appear in the `.lean` file. We should tell users to prefer tagged goals.\n    -/\n    let newMVarIds \u2190 sortMVarIdsByIndex newMVarIds\n    tagUntaggedGoals (\u2190 getMainTag) tagSuffix newMVarIds\n    return (val, newMVarIds)\n\ndef elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr \u00d7 List MVarId) := do\n  withCollectingNewGoalsFrom (elabTermEnsuringType stx expectedType?) tagSuffix allowNaturalHoles\n\n/-- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned \"natural\" metavariables.\n   Recall that \"natutal\" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be\n   filled by typing constraints.\n   \"Synthetic\" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/\ndef refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do\n  withMainContext do\n    let (val, mvarIds') \u2190 elabTermWithHoles stx (\u2190 getMainTarget) tagSuffix allowNaturalHoles\n    let mvarId \u2190 getMainGoal\n    let val \u2190 instantiateMVars val\n    unless val == mkMVar mvarId do\n      if val.findMVar? (\u00b7 == mvarId) matches some _ then\n        throwError \"'refine' tactic failed, value{indentExpr val}\\ndepends on the main goal metavariable '{mkMVar mvarId}'\"\n      mvarId.assign val\n    replaceMainGoal mvarIds'\n\n@[builtin_tactic \u00abrefine\u00bb] def evalRefine : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false)\n  | _                    => throwUnsupportedSyntax\n\n@[builtin_tactic \u00abrefine'\u00bb] def evalRefine' : Tactic := fun stx =>\n  match stx with\n  | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true)\n  | _                     => throwUnsupportedSyntax\n\n@[builtin_tactic \u00abspecialize\u00bb] def evalSpecialize : Tactic := fun stx => withMainContext do\n  match stx with\n  | `(tactic| specialize $e:term) =>\n    let (e, mvarIds') \u2190 elabTermWithHoles e none `specialize (allowNaturalHoles := true)\n    let h := e.getAppFn\n    if h.isFVar then\n      let localDecl \u2190 h.fvarId!.getDecl\n      let mvarId \u2190 (\u2190 getMainGoal).assert localDecl.userName (\u2190 inferType e).headBeta e\n      let (_, mvarId) \u2190 mvarId.intro1P\n      let mvarId \u2190 mvarId.tryClear h.fvarId!\n      replaceMainGoal (mvarIds' ++ [mvarId])\n    else\n      throwError \"'specialize' requires a term of the form `h x_1 .. x_n` where `h` appears in the local context\"\n  | _ => throwUnsupportedSyntax\n\n/--\n   Given a tactic\n   ```\n   apply f\n   ```\n   we want the `apply` tactic to create all metavariables. The following\n   definition will return `@f` for `f`. That is, it will **not** create\n   metavariables for implicit arguments.\n   A similar method is also used in Lean 3.\n   This method is useful when applying lemmas such as:\n   ```\n   theorem infLeRight {s t : Set \u03b1} : s \u2293 t \u2264 t\n   ```\n   where `s \u2264 t` here is defined as\n   ```\n   \u2200 {x : \u03b1}, x \u2208 s \u2192 x \u2208 t\n   ```\n-/\ndef elabTermForApply (stx : Syntax) (mayPostpone := true) : TacticM Expr := do\n  if stx.isIdent then\n    match (\u2190 Term.resolveId? stx (withInfo := true)) with\n    | some e => return e\n    | _      => pure ()\n  /-\n    By disabling the \"error recovery\" (and consequently \"error to sorry\") feature,\n    we make sure an `apply e` fails without logging an error message.\n    The motivation is that `apply` is frequently used when writing tactic such as\n    ```\n    cases h <;> intro h' <;> first | apply t[h'] | ....\n    ```\n    Here the type of `h'` may be different in each case, and the term `t[h']` containing `h'` may even fail to\n    be elaborated in some cases. When this happens we want the tactic to fail without reporting any error to the user,\n    and the next tactic is tried.\n\n    A drawback of disabling \"error to sorry\" is that there is no error recovery after the error is thrown, and features such\n    as auto-completion are affected.\n\n    By disabling \"error to sorry\", we also limit ourselves to at most one error at `t[h']`.\n\n    By disabling \"error to sorry\", we also miss the opportunity to catch mistakes is tactic code such as\n      `first | apply nonsensical-term | assumption`\n\n    This should not be a big problem for the `apply` tactic since we usually provide small terms there.\n\n    Note that we do not disable \"error to sorry\" at `exact` and `refine` since they are often used to elaborate big terms,\n    and we do want error recovery there, and we want to see the error messages.\n\n    We should probably provide options for allowing users to control this behavior.\n\n    see issue #1037\n\n    More complex solution:\n      - We do not disable \"error to sorry\"\n      - We elaborate term and check whether errors were produced\n      - If there are other tactic braches and there are errors, we remove the errors from the log, and throw a new error to force the tactic to backtrack.\n  -/\n  withoutRecover <| elabTerm stx none mayPostpone\n\ndef getFVarId (id : Syntax) : TacticM FVarId := withRef id do\n  -- use apply-like elaboration to suppress insertion of implicit arguments\n  let e \u2190 withMainContext do\n    elabTermForApply id (mayPostpone := false)\n  match e with\n  | Expr.fvar fvarId => return fvarId\n  | _                => throwError \"unexpected term '{e}'; expected single reference to variable\"\n\ndef getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do\n  withMainContext do ids.mapM getFVarId\n\ndef evalApplyLikeTactic (tac : MVarId \u2192 Expr \u2192 MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do\n  withMainContext do\n    let mut val \u2190 instantiateMVars (\u2190 elabTermForApply e)\n    if val.isMVar then\n      /-\n      If `val` is a metavariable, we force the elaboration of postponed terms.\n      This is useful for producing a more useful error message in examples such as\n      ```\n      example (h : P) : P \u2228 Q := by\n        apply .inl\n      ```\n      Recall that `apply` elaborates terms without using the expected type,\n      and the notation `.inl` requires the expected type to be available.\n      -/\n      Term.synthesizeSyntheticMVarsNoPostponing\n      val \u2190 instantiateMVars val\n    let mvarIds' \u2190 tac (\u2190 getMainGoal) val\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtin_tactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx =>\n  match stx with\n  | `(tactic| apply $e) => evalApplyLikeTactic (\u00b7.apply) e\n  | _ => throwUnsupportedSyntax\n\n@[builtin_tactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun _ =>\n  withMainContext do\n    let mvarIds' \u2190 (\u2190 getMainGoal).constructor\n    Term.synthesizeSyntheticMVarsNoPostponing\n    replaceMainGoal mvarIds'\n\n@[builtin_tactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx =>\n  withReducible <| evalTactic stx[1]\n\n@[builtin_tactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx =>\n  withReducibleAndInstances <| evalTactic stx[1]\n\n@[builtin_tactic Lean.Parser.Tactic.withUnfoldingAll] def evalWithUnfoldingAll : Tactic := fun stx =>\n  withTransparency TransparencyMode.all <| evalTactic stx[1]\n\n/--\n  Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable.\n  Note that, the main goal is updated when `Meta.assert` is used in the second case. -/\ndef elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId :=\n  withMainContext do\n    let e \u2190 elabTerm stx none\n    match e with\n    | .fvar fvarId => pure fvarId\n    | _ =>\n      let type \u2190 inferType e\n      let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do\n        let mvarId \u2190 getMainGoal\n        let (fvarId, mvarId) \u2190 liftMetaM do\n          let mvarId \u2190 mvarId.assert userName type e\n          Meta.intro1Core mvarId preserveBinderNames\n        replaceMainGoal [mvarId]\n        return fvarId\n      match userName? with\n      | none          => intro `h false\n      | some userName => intro userName true\n\n@[builtin_tactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx =>\n  match stx with\n  | `(tactic| rename $typeStx:term => $h:ident) => do\n    withMainContext do\n      /- Remark: we also use `withoutRecover` to make sure `elabTerm` does not succeed\n         using `sorryAx`, and we get `\"failed to find ...\"` which will not be logged because\n         it contains synthetic sorry's -/\n      let fvarId \u2190 withoutModifyingState <| withNewMCtxDepth <| withoutRecover do\n        let type \u2190 elabTerm typeStx none (mayPostpone := true)\n        let fvarId? \u2190 (\u2190 getLCtx).findDeclRevM? fun localDecl => do\n          if (\u2190 isDefEq type localDecl.type) then return localDecl.fvarId else return none\n        match fvarId? with\n        | none => throwError \"failed to find a hypothesis with type{indentExpr type}\"\n        | some fvarId => return fvarId\n      replaceMainGoal [\u2190 (\u2190 getMainGoal).rename fvarId h.getId]\n  | _ => throwUnsupportedSyntax\n\n/--\n   Make sure `expectedType` does not contain free and metavariables.\n   It applies zeta-reduction to eliminate let-free-vars.\n-/\nprivate def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do\n  let mut expectedType \u2190 instantiateMVars expectedType\n  if expectedType.hasFVar then\n    expectedType \u2190 zetaReduce expectedType\n  if expectedType.hasFVar || expectedType.hasMVar then\n    throwError \"expected type must not contain free or meta variables{indentExpr expectedType}\"\n  return expectedType\n\n@[builtin_tactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun _ =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let d \u2190 instantiateMVars d\n    let r \u2190 withDefault <| whnf d\n    unless r.isConstOf ``true do\n      throwError \"failed to reduce to 'true'{indentExpr r}\"\n    let s := d.appArg! -- get instance from `d`\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf\n\nprivate def mkNativeAuxDecl (baseName : Name) (type value : Expr) : TermElabM Name := do\n  let auxName \u2190 Term.mkAuxName baseName\n  let decl := Declaration.defnDecl {\n    name := auxName, levelParams := [], type, value\n    hints := .abbrev\n    safety := .safe\n  }\n  addDecl decl\n  compileDecl decl\n  pure auxName\n\n@[builtin_tactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun _ =>\n  closeMainGoalUsing fun expectedType => do\n    let expectedType \u2190 preprocessPropToDecide expectedType\n    let d \u2190 mkDecide expectedType\n    let auxDeclName \u2190 mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d\n    let rflPrf \u2190 mkEqRefl (toExpr true)\n    let s := d.appArg! -- get instance from `d`\n    return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf\n\nend Lean.Elab.Tactic\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/Tactic/ElabTerm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09670578548608505, "lm_q2_score": 0.04146227641277931, "lm_q1q2_score": 0.004009642008539}}
{"text": "import tactic.local_cache\n\nopen tactic\n\nsection example_tactic\n\ndef TEST_NS : name := `my_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace \"cache regenerating\",\n   return [1, 2, 3, 4]\n\nmeta def my_tactic : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS generate_some_data,\n   -- Do some stuff with `my_cached_data`\n   skip\n\nend example_tactic\n\n\n\nsection example_usage\n\n-- Note only a single cache regeneration (only a single trace message),\n-- even upon descent to a sub-tactic-block.\nlemma my_lemma : true := begin\n    my_tactic,\n    my_tactic,\n    my_tactic,\n\n    have h : true,\n    { my_tactic,\n      trivial },\n\n    trivial\nend\n\nend example_usage\n\nsection test\n\nmeta def fail_if_cache_miss : tactic unit :=\ndo p \u2190 local_cache.present TEST_NS,\n   if p then skip else fail \"cache miss\"\n\nmeta def clear_cache : tactic unit := local_cache.clear TEST_NS\n\nlemma my_test : true := begin\n    success_if_fail { fail_if_cache_miss },\n\n    my_tactic,\n\n    fail_if_cache_miss,\n    fail_if_cache_miss,\n\n    have h : true,\n    { fail_if_cache_miss,\n      trivial },\n\n    clear_cache,\n    success_if_fail { fail_if_cache_miss },\n\n    trivial\nend\n\nend test\n", "meta": {"author": "khoek", "repo": "lean-local-cache", "sha": "4cd64e20628be2a33d138a31dcc5b64ec57d13b7", "save_path": "github-repos/lean/khoek-lean-local-cache", "path": "github-repos/lean/khoek-lean-local-cache/lean-local-cache-4cd64e20628be2a33d138a31dcc5b64ec57d13b7/src/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920293453832885, "lm_q2_score": 0.033589507464017766, "lm_q1q2_score": 0.0040039678594080185}}
{"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.Elab.Term\nimport Lean.Elab.BindersUtil\nimport Lean.Elab.PatternVar\nimport Lean.Elab.Quotation.Util\nimport Lean.Parser.Do\n\n-- HACK: avoid code explosion until heuristics are improved\nset_option compiler.reuse false\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Meta\n\nprivate def getDoSeqElems (doSeq : Syntax) : List Syntax :=\n  if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then\n    doSeq[1].getArgs.toList.map fun arg => arg[0]\n  else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then\n    doSeq[0].getArgs.toList.map fun arg => arg[0]\n  else\n    []\n\nprivate def getDoSeq (doStx : Syntax) : Syntax :=\n  doStx[1]\n\n@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>\n  throwErrorAt stx \"invalid use of `(<- ...)`, must be nested inside a 'do' expression\"\n\n/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/\nprivate def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=\n  k == ``Lean.Parser.Term.do ||\n  k == ``Lean.Parser.Term.doSeqIndent ||\n  k == ``Lean.Parser.Term.doSeqBracketed ||\n  k == ``Lean.Parser.Term.termReturn ||\n  k == ``Lean.Parser.Term.termUnless ||\n  k == ``Lean.Parser.Term.termTry ||\n  k == ``Lean.Parser.Term.termFor\n\n/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/\nprivate def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=\n  let k := letDeclArg.getKind\n  if k == ``Lean.Parser.Term.letPatDecl then\n    false\n  else if k == ``Lean.Parser.Term.letEqnsDecl then\n    true\n  else if k == ``Lean.Parser.Term.letIdDecl then\n    -- letIdLhs := ident >> checkWsBefore \"expected space before binders\" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType\n    let binders := letDeclArg[1]\n    binders.getNumArgs > 0\n  else\n    false\n\n/-- Return `true` if the given `letDecl` contains binders. -/\nprivate def letDeclHasBinders (letDecl : Syntax) : Bool :=\n  letDeclArgHasBinders letDecl[0]\n\n/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/\nprivate def liftMethodForbiddenBinder (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||\n     k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec  then\n     -- It is never ok to lift over this kind of binder\n    true\n  -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not\n  else if k == ``Lean.Parser.Term.let then\n    letDeclHasBinders stx[1]\n  else if k == ``Lean.Parser.Term.doLet then\n    letDeclHasBinders stx[2]\n  else if k == ``Lean.Parser.Term.doLetArrow then\n    letDeclArgHasBinders stx[2]\n  else\n    false\n\nprivate partial def hasLiftMethod : Syntax \u2192 Bool\n  | Syntax.node k args =>\n    if liftMethodDelimiter k then false\n    -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a\n    -- bit slower\n    else if k == `Lean.Parser.Term.liftMethod then true\n    else args.any hasLiftMethod\n  | _ => false\n\nstructure ExtractMonadResult where\n  m            : Expr\n  \u03b1            : Expr\n  hasBindInst  : Expr\n  expectedType : Expr\n\nprivate def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do\n  let u \u2190 getDecLevel type\n  let id        := Lean.mkConst `Id [u]\n  let idBindVal := Lean.mkConst `Id.hasBind [u]\n  pure { m := id, hasBindInst := idBindVal, \u03b1 := type, expectedType := mkApp id type }\n\nprivate partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do\n  match expectedType? with\n  | none => throwError \"invalid 'do' notation, expected type is not available\"\n  | some expectedType =>\n    let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match type with\n      | Expr.app m \u03b1 _ =>\n        try\n          let bindInstType \u2190 mkAppM `Bind #[m]\n          let bindInstVal  \u2190 Meta.synthInstance bindInstType\n          return some { m := m, hasBindInst := bindInstVal, \u03b1 := \u03b1, expectedType := expectedType }\n        catch _ =>\n          return none\n      | _ =>\n        return none\n    let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match (\u2190 extractStep? type) with\n      | some r => return r\n      | none =>\n        let typeNew \u2190 whnfCore type\n        if typeNew != type then\n          extract? typeNew\n        else\n          if typeNew.getAppFn.isMVar then throwError \"invalid 'do' notation, expected type is not available\"\n          match (\u2190 unfoldDefinition? typeNew) with\n          | some typeNew => extract? typeNew\n          | none => return none\n    match (\u2190 extract? expectedType) with\n    | some r => return r\n    | none   => mkIdBindFor expectedType\n\nnamespace Do\n\n/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/\nstructure Alt (\u03c3 : Type) where\n  ref : Syntax\n  vars : Array Name\n  patterns : Syntax\n  rhs : \u03c3\n  deriving Inhabited\n\n/-\n  Auxiliary datastructure for representing a `do` code block, and compiling \"reassignments\" (e.g., `x := x + 1`).\n  We convert `Code` into a `Syntax` term representing the:\n  - `do`-block, or\n  - the visitor argument for the `forIn` combinator.\n\n  We say the following constructors are terminals:\n  - `break`:    for interrupting a `for x in s`\n  - `continue`: for interrupting the current iteration of a `for x in s`\n  - `return e`: for returning `e` as the result for the whole `do` computation block\n  - `action a`: for executing action `a` as a terminal\n  - `ite`:      if-then-else\n  - `match`:    pattern matching\n  - `jmp`       a goto to a join-point\n\n  We say the terminals `break`, `continue`, `action`, and `return` are \"exit points\"\n\n  Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x == 0 then\n     return ()\n  IO.println \"hello\"\n  ```\n  Executing `#eval f 0` will not print \"hello\". Now, consider\n  ```\n  def g (x : Nat) : IO Unit := do\n  if x == 0 then\n     pure ()\n  IO.println \"hello\"\n  ```\n  The `if` statement is essentially a noop, and \"hello\" is printed when we execute `g 0`.\n\n  - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).\n    The field `stx` is the actual `doElem`,\n    `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.\n    `vars` is an array since we have declarations such as `let (a, b) := s`.\n\n  - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).\n\n  - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.\n\n  - `seq a k` executes action `a`, ignores its result, and then executes `k`.\n    We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.\n\n  A code block `C` is well-formed if\n  - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and\n    `ps.size == as.size` -/\ninductive Code where\n  | decl         (xs : Array Name) (doElem : Syntax) (k : Code)\n  | reassign     (xs : Array Name) (doElem : Syntax) (k : Code)\n  /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/\n  | joinpoint    (name : Name) (params : Array (Name \u00d7 Bool)) (body : Code) (k : Code)\n  | seq          (action : Syntax) (k : Code)\n  | action       (action : Syntax)\n  | \u00abbreak\u00bb      (ref : Syntax)\n  | \u00abcontinue\u00bb   (ref : Syntax)\n  | \u00abreturn\u00bb     (ref : Syntax) (val : Syntax)\n  /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/\n  | ite          (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)\n  | \u00abmatch\u00bb      (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))\n  | jmp          (ref : Syntax) (jpName : Name) (args : Array Syntax)\n  deriving Inhabited\n\n/- A code block, and the collection of variables updated by it. -/\nstructure CodeBlock where\n  code  : Code\n  uvars : NameSet := {} -- set of variables updated by `code`\n\nprivate def nameSetToArray (s : NameSet) : Array Name :=\n  s.fold (fun (xs : Array Name) x => xs.push x) #[]\n\nprivate def varsToMessageData (vars : Array Name) : MessageData :=\n  MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) \" \"\n\npartial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=\n  let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName\n  let rec loop : Code \u2192 MessageData\n    | Code.decl xs _ k            => m!\"let {varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.reassign xs _ k        => m!\"{varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.joinpoint n ps body k  => m!\"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\\n{loop k}\"\n    | Code.seq e k                => m!\"{e}\\n{loop k}\"\n    | Code.action e               => e\n    | Code.ite _ _ _ c t e        => m!\"if {c} then {indentD (loop t)}\\nelse{loop e}\"\n    | Code.jmp _ j xs             => m!\"jmp {j.simpMacroScopes} {xs.toList}\"\n    | Code.\u00abbreak\u00bb _              => m!\"break {us}\"\n    | Code.\u00abcontinue\u00bb _           => m!\"continue {us}\"\n    | Code.\u00abreturn\u00bb _ v           => m!\"return {v} {us}\"\n    | Code.\u00abmatch\u00bb _ _ ds t alts  =>\n      m!\"match {ds} with\"\n      ++ alts.foldl (init := m!\"\") fun acc alt => acc ++ m!\"\\n| {alt.patterns} => {loop alt.rhs}\"\n  loop codeBlock.code\n\n/- Return true if the give code contains an exit point that satisfies `p` -/\npartial def hasExitPointPred (c : Code) (p : Code \u2192 Bool) : Bool :=\n  let rec loop : Code \u2192 Bool\n    | Code.decl _ _ k           => loop k\n    | Code.reassign _ _ k       => loop k\n    | Code.joinpoint _ _ b k    => loop b || loop k\n    | Code.seq _ k              => loop k\n    | Code.ite _ _ _ _ t e      => loop t || loop e\n    | Code.\u00abmatch\u00bb _ _ _ _ alts => alts.any (loop \u00b7.rhs)\n    | Code.jmp _ _ _            => false\n    | c                         => p c\n  loop c\n\ndef hasExitPoint (c : Code) : Bool :=\n  hasExitPointPred c fun c => true\n\ndef hasReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef hasTerminalAction (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abaction\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinue (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinueReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax \u2192 m Code) : m Code := withRef e <| withFreshMacroScope do\n  let y \u2190 `(y)\n  let yName := y.getId\n  let doElem \u2190 `(doElem| let y \u2190 $e:term)\n  -- Add elaboration hint for producing sane error message\n  let y \u2190 `(ensureExpectedType% \"type mismatch, result value\" $y)\n  let k \u2190 mkCont y\n  pure $ Code.decl #[yName] doElem k\n\n/- Convert `action _ e` instructions in `c` into `let y \u2190 e; jmp _ jp (xs y)`. -/\npartial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=\n  let rec loop : Code \u2192 MacroM Code\n    | Code.decl xs stx k           => do Code.decl xs stx (\u2190 loop k)\n    | Code.reassign xs stx k       => do Code.reassign xs stx (\u2190 loop k)\n    | Code.joinpoint n ps b k      => do Code.joinpoint n ps (\u2190 loop b) (\u2190 loop k)\n    | Code.seq e k                 => do Code.seq e (\u2190 loop k)\n    | Code.ite ref x? h c t e      => do Code.ite ref x? h c (\u2190 loop t) (\u2190 loop e)\n    | Code.\u00abmatch\u00bb ref g ds t alts => do Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 loop alt.rhs) })\n    | Code.action e                => mkAuxDeclFor e fun y =>\n      let ref := e\n      -- We jump to `jp` with xs **and** y\n      let jmpArgs := xs.map $ mkIdentFrom ref\n      let jmpArgs := jmpArgs.push y\n      pure $ Code.jmp ref jp jmpArgs\n    | c                            => pure c\n  loop code\n\nstructure JPDecl where\n  name : Name\n  params : Array (Name \u00d7 Bool)\n  body : Code\n\ndef attachJP (jpDecl : JPDecl) (k : Code) : Code :=\n  Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k\n\ndef attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=\n  jpDecls.foldr attachJP k\n\ndef mkFreshJP (ps : Array (Name \u00d7 Bool)) (body : Code) : TermElabM JPDecl := do\n  let ps \u2190\n    if ps.isEmpty then\n      let y \u2190 mkFreshUserName `y\n      pure #[(y, false)]\n    else\n      pure ps\n  -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by\n  -- the \"do\" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`\n  -- We will remove this hack when we re-implement the compiler frontend in Lean.\n  let name \u2190 mkFreshUserName `_do_jp\n  pure { name := name, params := ps, body := body }\n\ndef mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=\n  mkFreshJP (xs.map fun x => (x, true)) body\n\ndef addFreshJP (ps : Array (Name \u00d7 Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do\n  let jp \u2190 mkFreshJP ps body\n  modify fun (jps : Array JPDecl) => jps.push jp\n  pure jp.name\n\ndef insertVars (rs : NameSet) (xs : Array Name) : NameSet :=\n  xs.foldl (\u00b7.insert \u00b7) rs\n\ndef eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=\n  xs.foldl (\u00b7.erase \u00b7) rs\n\ndef eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=\n  match x? with\n  | none   => rs\n  | some x => rs.insert x\n\n/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/\ndef mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := nameSetToArray rs\n  let jp \u2190 addFreshJP (xs.map fun x => (x, true)) c\n  if xs.isEmpty then\n    let unit \u2190 ``(Unit.unit)\n    return Code.jmp ref jp #[unit]\n  else\n    return Code.jmp ref jp (xs.map $ mkIdentFrom ref)\n\n/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.\n   The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`\n   is a fresh variable created by this method. -/\ndef mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax \u2192 MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := nameSetToArray rs\n  let args := xs.map $ mkIdentFrom ref\n  let args := args.push val\n  let yFresh \u2190 mkFreshUserName `y\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (yFresh, false)\n  let jpBody \u2190 liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)\n  let jp \u2190 addFreshJP ps jpBody\n  pure $ Code.jmp ref jp args\n\n/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path.  -/\npartial def pullExitPointsAux : NameSet \u2192 Code \u2192 StateRefT (Array JPDecl) TermElabM Code\n  | rs, Code.decl xs stx k           => do Code.decl xs stx (\u2190 pullExitPointsAux (eraseVars rs xs) k)\n  | rs, Code.reassign xs stx k       => do Code.reassign xs stx (\u2190 pullExitPointsAux (insertVars rs xs) k)\n  | rs, Code.joinpoint j ps b k      => do Code.joinpoint j ps (\u2190 pullExitPointsAux rs b) (\u2190 pullExitPointsAux rs k)\n  | rs, Code.seq e k                 => do Code.seq e (\u2190 pullExitPointsAux rs k)\n  | rs, Code.ite ref x? o c t e      => do Code.ite ref x? o c (\u2190 pullExitPointsAux (eraseOptVar rs x?) t) (\u2190 pullExitPointsAux (eraseOptVar rs x?) e)\n  | rs, Code.\u00abmatch\u00bb ref g ds t alts => do\n    Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })\n  | rs, c@(Code.jmp _ _ _)           => pure c\n  | rs, Code.\u00abbreak\u00bb ref             => mkSimpleJmp ref rs (Code.\u00abbreak\u00bb ref)\n  | rs, Code.\u00abcontinue\u00bb ref          => mkSimpleJmp ref rs (Code.\u00abcontinue\u00bb ref)\n  | rs, Code.\u00abreturn\u00bb ref val        => mkJmp ref rs val (fun y => pure $ Code.\u00abreturn\u00bb ref y)\n  | rs, Code.action e                =>\n    -- We use `mkAuxDeclFor` because `e` is not pure.\n    mkAuxDeclFor e fun y =>\n      let ref := e\n      mkJmp ref rs y (fun yFresh => do pure $ Code.action (\u2190 ``(Pure.pure $yFresh)))\n\n/-\nAuxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.\nWhen a new variable is not already in the collection, but is shadowed by some declaration in `c`,\nwe create auxiliary join points to make sure we preserve the semantics of the code block.\nExample: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it\nwith the reassignment `x := x + 1`. We first use `pullExitPoints` to create\n```\nlet jp (x!1) :=  return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nand then we add the reassignment\n```\nx := x + 1\nlet jp (x!1) := return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nNote that we created a fresh variable `x!1` to avoid accidental name capture.\nAs another example, consider\n```\nprint x;\nlet x := 10\ny := y + 1;\nreturn x;\n```\nWe transform it into\n```\nlet jp (y x!1) := return x!1;\nprint x;\nlet x := 10\ny := y + 1;\njmp jp y x\n```\nand then we add the reassignment as in the previous example.\nWe need to include `y` in the jump, because each exit point is implicitly returning the set of\nupdate variables.\n\nWe implement the method as follows. Let `us` be `c.uvars`, then\n1- for each `return _ y` in `c`, we create a join point\n  `let j (us y!1) := return y!1`\n   and replace the `return _ y` with `jmp us y`\n2- for each `break`, we create a join point\n  `let j (us) := break`\n   and replace the `break` with `jmp us`.\n3- Same as 2 for `continue`.\n-/\ndef pullExitPoints (c : Code) : TermElabM Code := do\n  if hasExitPoint c then\n    let (c, jpDecls) \u2190 (pullExitPointsAux {} c).run #[]\n    pure $ attachJPs jpDecls c\n  else\n    pure c\n\npartial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=\n  let rec update : Code \u2192 TermElabM Code\n    | Code.joinpoint j ps b k          => do Code.joinpoint j ps (\u2190 update b) (\u2190 update k)\n    | Code.seq e k                     => do Code.seq e (\u2190 update k)\n    | c@(Code.\u00abmatch\u00bb ref g ds t alts) => do\n      if alts.any fun alt => alt.vars.any fun x => ws.contains x then\n        -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`\n        pullExitPoints c\n      else\n        Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 update alt.rhs) })\n    | Code.ite ref none o c t e => do Code.ite ref none o c (\u2190 update t) (\u2190 update e)\n    | c@(Code.ite ref (some h) o cond t e) => do\n      if ws.contains h then\n        -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`\n        pullExitPoints c\n      else\n        Code.ite ref (some h) o cond (\u2190 update t) (\u2190 update e)\n    | Code.reassign xs stx k => do Code.reassign xs stx (\u2190 update k)\n    | c@(Code.decl xs stx k) => do\n      if xs.any fun x => ws.contains x then\n        -- One the declared variables is shadowing a variable in `ws`\n        pullExitPoints c\n      else\n        Code.decl xs stx (\u2190 update k)\n    | c => pure c\n  update c\n\n/-\nExtend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.\nWe **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.\nSee discussion at `pullExitPoints`.\n-/\npartial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do\n  if ws.any fun x => !c.uvars.contains x then\n    -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)\n    pure { code := (\u2190 extendUpdatedVarsAux c.code ws), uvars := ws }\n  else\n    pure { c with uvars := ws }\n\nprivate def union (s\u2081 s\u2082 : NameSet) : NameSet :=\n  s\u2081.fold (\u00b7.insert \u00b7) s\u2082\n\n/-\nGiven two code blocks `c\u2081` and `c\u2082`, make sure they have the same set of updated variables.\nLet `ws` the union of the updated variables in `c\u2081\u2035 and \u2035c\u2082`.\nWe use `extendUpdatedVars c\u2081 ws` and `extendUpdatedVars c\u2082 ws`\n-/\ndef homogenize (c\u2081 c\u2082 : CodeBlock) : TermElabM (CodeBlock \u00d7 CodeBlock) := do\n  let ws := union c\u2081.uvars c\u2082.uvars\n  let c\u2081 \u2190 extendUpdatedVars c\u2081 ws\n  let c\u2082 \u2190 extendUpdatedVars c\u2082 ws\n  pure (c\u2081, c\u2082)\n\n/-\nExtending code blocks with variable declarations: `let x : t := v` and `let x : t \u2190 v`.\nWe remove `x` from the collection of updated varibles.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `let (x, y) := t`\n-/\ndef mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {\n  code := Code.decl xs stx c.code,\n  uvars := eraseVars c.uvars xs\n}\n\n/-\nExtending code blocks with reassignments: `x : t := v` and `x : t \u2190 v`.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `(x, y) \u2190 t`\n-/\ndef mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do\n  let us := c.uvars\n  let ws := insertVars us xs\n  -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.\n  -- See discussion at `pullExitPoints`\n  let code \u2190 if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code\n  pure { code := Code.reassign xs stx code, uvars := ws }\n\ndef mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=\n  { c with code := Code.seq action c.code }\n\ndef mkTerminalAction (action : Syntax) : CodeBlock :=\n  { code := Code.action action }\n\ndef mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=\n  { code := Code.\u00abreturn\u00bb ref val }\n\ndef mkBreak (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abbreak\u00bb ref }\n\ndef mkContinue (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abcontinue\u00bb ref }\n\ndef mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do\n  let x? := if optIdent.isNone then none else some optIdent[0].getId\n  let (thenBranch, elseBranch) \u2190 homogenize thenBranch elseBranch\n  pure {\n    code  := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,\n    uvars := thenBranch.uvars,\n  }\n\nprivate def mkUnit : MacroM Syntax :=\n  ``((\u27e8\u27e9 : PUnit))\n\nprivate def mkPureUnit : MacroM Syntax :=\n  ``(pure PUnit.unit)\n\ndef mkPureUnitAction : MacroM CodeBlock := do\n  mkTerminalAction (\u2190 mkPureUnit)\n\ndef mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do\n  let thenBranch \u2190 mkPureUnitAction\n  pure { c with code := Code.ite (\u2190 getRef) none mkNullNode cond thenBranch.code c.code }\n\ndef mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do\n  -- nary version of homogenize\n  let ws := alts.foldl (union \u00b7 \u00b7.rhs.uvars) {}\n  let alts \u2190 alts.mapM fun alt => do\n    let rhs \u2190 extendUpdatedVars alt.rhs ws\n    pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }\n  pure { code := Code.\u00abmatch\u00bb ref genParam discrs optType alts, uvars := ws }\n\n/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.\n   This method assumes `terminal` is a terminal -/\ndef concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do\n  unless hasTerminalAction terminal.code do\n    throwErrorAt kRef \"'do' element is unreachable\"\n  let (terminal, k) \u2190 homogenize terminal k\n  let xs := nameSetToArray k.uvars\n  let y \u2190 match y? with | some y => pure y | none => mkFreshUserName `y\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (y, false)\n  let jpDecl \u2190 mkFreshJP ps k.code\n  let jp := jpDecl.name\n  let terminal \u2190 liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs\n  pure { code  := attachJP jpDecl terminal, uvars := k.uvars }\n\ndef getLetIdDeclVar (letIdDecl : Syntax) : Name :=\n  letIdDecl[0].getId\n\n-- support both regular and syntax match\ndef getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=\n  getPatternVarNames <$> getPatternVars pattern <|>\n  Array.map Syntax.getId <$> Quotation.getPatternVars pattern\n\ndef getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=\n  getPatternVarNames <$> getPatternsVars patterns <|>\n  Array.map Syntax.getId <$> Quotation.getPatternsVars patterns\n\ndef getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do\n  let pattern := letPatDecl[0]\n  getPatternVarsEx pattern\n\ndef getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=\n  letEqnsDecl[0].getId\n\ndef getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do\n  let arg := letDecl[0]\n  if arg.getKind == `Lean.Parser.Term.letIdDecl then\n    pure #[getLetIdDeclVar arg]\n  else if arg.getKind == `Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then\n    pure #[getLetEqnsDeclVar arg]\n  else\n    throwError \"unexpected kind of let declaration\"\n\ndef getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=\n  -- leading_parser \"let \" >> optional \"mut \" >> letDecl\n  getLetDeclVars doLet[2]\n\ndef getDoHaveVar (doHave : Syntax) : Name :=\n  /-\n    `leading_parser \"have \" >> Term.haveDecl`\n    where\n    ```\n    haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)\n    optIdent := optional (try (ident >> \" : \"))\n\n    ```\n  -/\n  let optIdent := doHave[1][0]\n  if optIdent.isNone then\n    `this\n  else\n    optIdent[0].getId\n\ndef getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do\n  -- letRecDecls is an array of `(group (optional attributes >> letDecl))`\n  let letRecDecls := doLetRec[1][0].getSepArgs\n  let letDecls := letRecDecls.map fun p => p[2]\n  let mut allVars := #[]\n  for letDecl in letDecls do\n    let vars \u2190 getLetDeclVars letDecl\n    allVars := allVars ++ vars\n  pure allVars\n\n-- ident >> optType >> leftArrow >> termParser\ndef getDoIdDeclVar (doIdDecl : Syntax) : Name :=\n  doIdDecl[0].getId\n\n-- termParser >> leftArrow >> termParser >> optional (\" | \" >> termParser)\ndef getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do\n  let pattern := doPatDecl[0]\n  getPatternVarsEx pattern\n\n-- leading_parser \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\ndef getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do\n  let decl := doLetArrow[2]\n  if decl.getKind == `Lean.Parser.Term.doIdDecl then\n    pure #[getDoIdDeclVar decl]\n  else if decl.getKind == `Lean.Parser.Term.doPatDecl then\n    getDoPatDeclVars decl\n  else\n    throwError \"unexpected kind of 'do' declaration\"\n\ndef getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do\n  let arg := doReassign[0]\n  if arg.getKind == `Lean.Parser.Term.letIdDecl then\n    pure #[getLetIdDeclVar arg]\n  else if arg.getKind == `Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else\n    throwError \"unexpected kind of reassignment\"\n\ndef mkDoSeq (doElems : Array Syntax) : Syntax :=\n  mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]\n\ndef mkSingletonDoSeq (doElem : Syntax) : Syntax :=\n  mkDoSeq #[doElem]\n\n/-\n  If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s.  -/\nprivate def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with\n  | `(doElem|if $p:doIfProp then $t else $e) => pure none\n  | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do\n    let mut e      := e?.getD (\u2190 `(doSeq|pure PUnit.unit))\n    let mut eIsSeq := true\n    for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do\n      e \u2190 if eIsSeq then e else `(doSeq|$e:doElem)\n      e \u2190 withRef cond <| match cond with\n        | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)\n        | `(doIfCond|let $pat \u2190 $d)  => `(doElem| match%$i \u2190 $d    with | $pat:term => $t | _ => $e)\n        | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)\n        | _                          => `(doElem| if%$i $(Syntax.missing) then $t else $e)\n      eIsSeq := false\n    return some e\n  | _ => pure none\n\nstructure DoIfView where\n  ref        : Syntax\n  optIdent   : Syntax\n  cond       : Syntax\n  thenBranch : Syntax\n  elseBranch : Syntax\n\n/- This method assumes `expandDoIf?` is not applicable. -/\nprivate def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do\n  pure {\n    ref        := doIf,\n    optIdent   := doIf[1][0],\n    cond       := doIf[1][1],\n    thenBranch := doIf[3],\n    elseBranch := doIf[5][1]\n  }\n\n/-\nWe use `MProd` instead of `Prod` to group values when expanding the\n`do` notation. `MProd` is a universe monomorphic product.\nThe motivation is to generate simpler universe constraints in code\nthat was not written by the user.\nNote that we are not restricting the macro power since the\n`Bind.bind` combinator already forces values computed by monadic\nactions to be in the same universe.\n-/\nprivate def mkTuple (elems : Array Syntax) : MacroM Syntax := do\n  if elems.size == 0 then\n    mkUnit\n  else if elems.size == 1 then\n    pure elems[0]\n  else\n    (elems.extract 0 (elems.size - 1)).foldrM\n      (fun elem tuple => ``(MProd.mk $elem $tuple))\n      (elems.back)\n\n/- Return `some action` if `doElem` is a `doExpr <action>`-/\ndef isDoExpr? (doElem : Syntax) : Option Syntax :=\n  if doElem.getKind == `Lean.Parser.Term.doExpr then\n    some doElem[0]\n  else\n    none\n\n/--\n  Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term\n  ```\n  let a_1     := x.1\n  let x       := x.2\n  let a_2     := x.1\n  let x       := x.2\n  ...\n  let a_n     := x.1\n  let a_{n+1} := x.2\n  body\n  ```\n  Special cases\n  - `uvars := #[]` => `body`\n  - `uvars := #[a]` => `let a := x; body`\n\n\n  We use this method when expanding the `for-in` notation.\n-/\nprivate def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n  if uvars.size == 0 then\n    return body\n  else if uvars.size == 1 then\n    `(let $(\u2190 mkIdentFromRef uvars[0]):ident := $x; $body)\n  else\n    destruct uvars.toList x body\nwhere\n  destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n    match as with\n      | [a, b]  => `(let $(\u2190 mkIdentFromRef a):ident := $x.1; let $(\u2190 mkIdentFromRef b):ident := $x.2; $body)\n      | a :: as => withFreshMacroScope do\n        let rest \u2190 destruct as (\u2190 `(x)) body\n        `(let $(\u2190 mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)\n      | _ => unreachable!\n\n/-\nThe procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.\nWe use this method to convert\n1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of\n   `CodeBlock` never contains `break` nor `continue`. Moreover, the collection\n   of updated variables is not packed into the result.\n   Thus, we have two kinds of exit points\n     - `Code.action e` which is converted into `e`\n     - `Code.return _ e` which is converted into `pure e`\n\n   We use `Kind.regular` for this case.\n\n2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate\n   a `Syntax` term representing a function for the `xs.forIn` combinator.\n\n   a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term\n      has type `m (ForInStep (Option \u03b1 \u00d7 \u03c3))`, where `a : \u03b1`, and the `\u03c3` is the type\n      of the tuple of variables reassigned by `b`.\n      We use `Kind.forInWithReturn` for this case\n\n   b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated\n      `Syntax` term has type `m (ForInStep \u03c3)`.\n      We use `Kind.forIn` for this case.\n\n3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).\n\n   The generated `Syntax` term for `c` must inform whether `c` \"exited\" using `Code.action`, `Code.return`,\n   `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.\n   For example, the auxiliary type `DoResultPBC \u03b1 \u03c3` is used for a code block that exits with `Code.action`,\n   **and** `Code.break`/`Code.continue`, `\u03b1` is the type of values produced by the exit `action`, and\n   `\u03c3` is the type of the tuple of reassigned variables.\n   The type `DoResult \u03b1 \u03b2 \u03c3` is usedf for code blocks that exit with\n   `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `\u03b2` is the type of the returned values.\n   We don't use `DoResult \u03b1 \u03b2 \u03c3` for all cases because:\n\n      a) The elaborator would not be able to infer all type parameters without extra annotations. For example,\n         if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `\u03b2`.\n\n      b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),\n         but we don't want to consider \"unreachable\" cases.\n\n   We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.\n\n   When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,\n   and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.\n\n   - `a`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n\n   - `r`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n           Note that the code that pattern matches on the result will behave differently in this case.\n           It produces `return a` for this case, and `pure a` for the previous one.\n\n   - `b/c`: `Kind.nestedBC`, type `m (DoResultBC \u03c3)`\n\n   - `a` and `r`:   `Kind.nestedPR`, type `m (DoResultPR \u03b1 \u03b2 \u03c3)`\n\n   - `a` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n\n   - `r` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n         Again the code that pattern matches on the result will behave differently in this case and\n         the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for\n         this case, and `pure a` for the previous case.\n\n   - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC \u03b1 \u03b2 \u03c3)`\n\nHere is the recipe for adding new combinators with nested `do`s.\nExample: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m \u03b1 \u2192 m \u03b1`\n1- Convert `doSeq` into `codeBlock : CodeBlock`\n2- Create term `term` using `mkNestedTerm code m uvars a r bc` where\n   `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,\n   `m` is a `Syntax` representing the Monad, and\n   `a` is true if `code` contains `Code.action _`,\n   `r` is true if `code` contains `Code.return _ _`,\n   `bc` is true if `code` contains `Code.break _` or `Code.continue _`.\n\n   Remark: for combinators such as `repeat` that take a single `doSeq`, all\n   arguments, but `m`, are extracted from `codeBlock`.\n3- Create the term `repeat $term`\n4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`\n\n-/\nnamespace ToTerm\n\ninductive Kind where\n  | regular\n  | forIn\n  | forInWithReturn\n  | nestedBC\n  | nestedPR\n  | nestedSBC\n  | nestedPRBC\n\ninstance : Inhabited Kind := \u27e8Kind.regular\u27e9\n\ndef Kind.isRegular : Kind \u2192 Bool\n  | Kind.regular => true\n  | _            => false\n\nstructure Context where\n  m     : Syntax -- Syntax to reference the monad associated with the do notation.\n  uvars : Array Name\n  kind  : Kind\n\nabbrev M := ReaderT Context MacroM\n\ndef mkUVarTuple : M Syntax := do\n  let ctx \u2190 read\n  let uvarIdents \u2190 ctx.uvars.mapM mkIdentFromRef\n  mkTuple uvarIdents\n\ndef returnToTerm (val : Syntax) : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Pure.pure (DoResultPR.\u00abreturn\u00bb $val $u))\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abpureReturn\u00bb $val $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abreturn\u00bb $val $u))\n\ndef continueToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abcontinue\u00bb $u))\n\ndef breakToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abbreak\u00bb $u))\n\ndef actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))\n  | Kind.forIn           => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.\u00abpure\u00bb y $u)))\n  | Kind.nestedSBC       => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.\u00abpureReturn\u00bb y $u)))\n  | Kind.nestedPRBC      => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.\u00abpure\u00bb y $u)))\n\ndef seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  if action.getKind == `Lean.Parser.Term.doDbgTrace then\n    let msg := action[1]\n    `(dbg_trace $msg; $k)\n  else if action.getKind == `Lean.Parser.Term.doAssert then\n    let cond := action[1]\n    `(assert! $cond; $k)\n  else\n    let action \u2190 withRef action ``(($action : $((\u2190read).m) PUnit))\n    ``(Bind.bind $action (fun (_ : PUnit) => $k))\n\ndef declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do\n  let kind := decl.getKind\n  if kind == `Lean.Parser.Term.doLet then\n    let letDecl := decl[2]\n    `(let $letDecl:letDecl; $k)\n  else if kind == `Lean.Parser.Term.doLetRec then\n    let letRecToken := decl[0]\n    let letRecDecls := decl[1]\n    pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]\n  else if kind == `Lean.Parser.Term.doLetArrow then\n    let arg := decl[2]\n    let ref := arg\n    if arg.getKind == `Lean.Parser.Term.doIdDecl then\n      let id     := arg[0]\n      let type   := expandOptType ref arg[1]\n      let doElem := arg[3]\n      -- `doElem` must be a `doExpr action`. See `doLetArrowToCode`\n      match isDoExpr? doElem with\n      | some action =>\n        let action \u2190 withRef action `(($action : $((\u2190 read).m) $type))\n        ``(Bind.bind $action (fun ($id:ident : $type) => $k))\n      | none        => Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n    else\n      Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n  else if kind == `Lean.Parser.Term.doHave then\n    -- The `have` term is of the form  `\"have \" >> haveDecl >> optSemicolon termParser`\n    let args := decl.getArgs\n    let args := args ++ #[mkNullNode /- optional ';' -/, k]\n    pure $ mkNode `Lean.Parser.Term.\u00abhave\u00bb args\n  else\n    Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n\ndef reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do\n  let kind := reassign.getKind\n  if kind == `Lean.Parser.Term.doReassign then\n    -- doReassign := leading_parser (letIdDecl <|> letPatDecl)\n    let arg := reassign[0]\n    if arg.getKind == `Lean.Parser.Term.letIdDecl then\n      -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >>  \" := \" >> termParser\n      let x   := arg[0]\n      let val := arg[4]\n      let newVal \u2190 `(ensureTypeOf% $x $(quote \"invalid reassignment, value\") $val)\n      let arg := arg.setArg 4 newVal\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n    else\n      -- TODO: ensure the types did not change\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n  else\n    -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode\n    Macro.throwErrorAt reassign \"unexpected kind of 'do' reassignment\"\n\ndef mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do\n  if optIdent.isNone then\n    ``(ite $cond $thenBranch $elseBranch)\n  else\n    let h := optIdent[0]\n    ``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch))\n\ndef mkJoinPoint (j : Name) (ps : Array (Name \u00d7 Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do\n  let pTypes \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => do if useTypeOf then `(typeOf% $(\u2190 mkIdentFromRef id)) else `(_)\n  let ps     \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => mkIdentFromRef id\n  /-\n  We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.\n  By elaborating `$k` first, we \"learn\" more about `$body`'s type.\n  For example, consider the following example `do` expression\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x > 0 then\n    IO.println \"x is not zero\" -- Error is here\n  IO.mkRef true\n  ```\n  it is expanded into\n  ```\n  def f (x : Nat) : IO Unit := do\n  let jp (u : Unit) : IO _ :=\n    IO.mkRef true;\n  if x > 0 then\n    IO.println \"not zero\"\n    jp ()\n  else\n    jp ()\n  ```\n  If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit \u2192 IO (IO.Ref Bool)`.\n  Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit \u2192 IO Unit`.\n  Then, we get the expected type mismatch error at `IO.mkRef true`. -/\n  `(let_delayed $(\u2190 mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((\u2190 read).m) _ := $body; $k)\n\ndef mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=\n  Syntax.mkApp (mkIdentFrom ref j) args\n\npartial def toTerm : Code \u2192 M Syntax\n  | Code.\u00abreturn\u00bb ref val   => withRef ref <| returnToTerm val\n  | Code.\u00abcontinue\u00bb ref     => withRef ref continueToTerm\n  | Code.\u00abbreak\u00bb ref        => withRef ref breakToTerm\n  | Code.action e           => actionTerminalToTerm e\n  | Code.joinpoint j ps b k => do mkJoinPoint j ps (\u2190 toTerm b) (\u2190 toTerm k)\n  | Code.jmp ref j args     => pure $ mkJmp ref j args\n  | Code.decl _ stx k       => do declToTerm stx (\u2190 toTerm k)\n  | Code.reassign _ stx k   => do reassignToTerm stx (\u2190 toTerm k)\n  | Code.seq stx k          => do seqToTerm stx (\u2190 toTerm k)\n  | Code.ite ref _ o c t e  => withRef ref <| do mkIte o c (\u2190 toTerm t) (\u2190 toTerm e)\n  | Code.\u00abmatch\u00bb ref genParam discrs optType alts => do\n    let mut termAlts := #[]\n    for alt in alts do\n      let rhs \u2190 toTerm alt.rhs\n      let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref \"|\", alt.patterns, mkAtomFrom alt.ref \"=>\", rhs]\n      termAlts := termAlts.push termAlt\n    let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]\n    pure $ mkNode `Lean.Parser.Term.\u00abmatch\u00bb #[mkAtomFrom ref \"match\", genParam, discrs, optType, mkAtomFrom ref \"with\", termMatchAlts]\n\ndef run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do\n  let term \u2190 toTerm code { m := m, kind := kind, uvars := uvars }\n  pure term\n\n/- Given\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   generate Kind. See comment at the beginning of the `ToTerm` namespace. -/\ndef mkNestedKind (a r bc : Bool) : Kind :=\n  match a, r, bc with\n  | true,  false, false => Kind.regular\n  | false, true,  false => Kind.regular\n  | false, false, true  => Kind.nestedBC\n  | true,  true,  false => Kind.nestedPR\n  | true,  false, true  => Kind.nestedSBC\n  | false, true,  true  => Kind.nestedSBC\n  | true,  true,  true  => Kind.nestedPRBC\n  | false, false, false => unreachable!\n\ndef mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do\n  ToTerm.run code m uvars (mkNestedKind a r bc)\n\n/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.\n   See comment at the beginning of the `ToTerm` namespace.\n\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   The result is a sequence of `doElem` -/\ndef matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do\n  let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)\n  let u \u2190 mkTuple (\u2190 uvars.mapM mkIdentFromRef)\n  match a, r, bc with\n  | true, false, false =>\n    if uvars.isEmpty then\n      toDoElems (\u2190 `(do $term:term))\n    else\n      toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; pure r.1))\n  | false, true, false =>\n    if uvars.isEmpty then\n      toDoElems (\u2190 `(do let r \u2190 $term:term; return r))\n    else\n      toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; return r.1))\n  | false, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, false => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPR.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPR.\u00abreturn\u00bb b u => $u:term := u; return b)\n  | true, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; pure a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; return a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPRBC.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPRBC.\u00abreturn\u00bb a u => $u:term := u; return a\n         | DoResultPRBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultPRBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, false, false => unreachable!\n\nend ToTerm\n\ndef isMutableLet (doElem : Syntax) : Bool :=\n  let kind := doElem.getKind\n  (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)\n  &&\n  !doElem[1].isNone\n\nnamespace ToCodeBlock\n\nstructure Context where\n  ref         : Syntax\n  m           : Syntax -- Syntax representing the monad associated with the do notation.\n  mutableVars : NameSet := {}\n  insideFor   : Bool := false\n\nabbrev M := ReaderT Context TermElabM\n\ndef withNewMutableVars {\u03b1} (newVars : Array Name) (mutable : Bool) (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x\n\ndef checkReassignable (xs : Array Name) : M Unit := do\n  let throwInvalidReassignment (x : Name) : M Unit :=\n    throwError \"'{x.simpMacroScopes}' cannot be reassigned\"\n  let ctx \u2190 read\n  for x in xs do\n    unless ctx.mutableVars.contains x do\n      throwInvalidReassignment x\n\ndef checkNotShadowingMutable (xs : Array Name) : M Unit := do\n  let throwInvalidShadowing (x : Name) : M Unit :=\n    throwError \"mutable variable '{x.simpMacroScopes}' cannot be shadowed\"\n  let ctx \u2190 read\n  for x in xs do\n    if ctx.mutableVars.contains x then\n      throwInvalidShadowing x\n\ndef withFor {\u03b1} (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => { ctx with insideFor := true }) x\n\nstructure ToForInTermResult where\n  uvars      : Array Name\n  term       : Syntax\n\ndef mkForInBody  (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do\n  let ctx \u2190 read\n  let uvars := forInBody.uvars\n  let uvars := nameSetToArray uvars\n  let term \u2190 liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)\n  pure \u27e8uvars, term\u27e9\n\ndef ensureInsideFor : M Unit :=\n  unless (\u2190 read).insideFor do\n    throwError \"invalid 'do' element, it must be inside 'for'\"\n\ndef ensureEOS (doElems : List Syntax) : M Unit :=\n  unless doElems.isEmpty do\n    throwError \"must be last element in a 'do' sequence\"\n\nprivate partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax \u2192 StateT (List Syntax) MacroM Syntax\n  | stx@(Syntax.node k args) =>\n    if liftMethodDelimiter k then\n      return stx\n    else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do\n      if inBinder then\n        Macro.throwErrorAt stx \"cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`\"\n      let term := args[1]\n      let term \u2190 expandLiftMethodAux inQuot inBinder term\n      let auxDoElem \u2190 `(doElem| let a \u2190 $term:term)\n      modify fun s => s ++ [auxDoElem]\n      `(a)\n    else do\n      let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot\n      let inBinder   := inBinder || (!inQuot && liftMethodForbiddenBinder stx)\n      let args \u2190 args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)\n      return Syntax.node k args\n  | stx => pure stx\n\ndef expandLiftMethod (doElem : Syntax) : MacroM (List Syntax \u00d7 Syntax) := do\n  if !hasLiftMethod doElem then\n    pure ([], doElem)\n  else\n    let (doElem, doElemsNew) \u2190 (expandLiftMethodAux false false doElem).run []\n    pure (doElemsNew, doElem)\n\ndef checkLetArrowRHS (doElem : Syntax) : M Unit := do\n  let kind := doElem.getKind\n  if kind == `Lean.Parser.Term.doLetArrow ||\n     kind == `Lean.Parser.Term.doLet ||\n     kind == `Lean.Parser.Term.doLetRec ||\n     kind == `Lean.Parser.Term.doHave ||\n     kind == `Lean.Parser.Term.doReassign ||\n     kind == `Lean.Parser.Term.doReassignArrow then\n    throwErrorAt doElem \"invalid kind of value '{kind}' in an assignment\"\n\n/- Generate `CodeBlock` for `doReturn` which is of the form\n   ```\n   \"return \" >> optional termParser\n   ```\n   `doElems` is only used for sanity checking. -/\ndef doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do\n  ensureEOS doElems\n  let argOpt := doReturn[1]\n  let arg \u2190 if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]\n  return mkReturn (\u2190 getRef) arg\n\nstructure Catch where\n  x         : Syntax\n  optType   : Syntax\n  codeBlock : CodeBlock\n\ndef getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=\n  let ws := tryCode.uvars\n  let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws\n  let ws := match finallyCode? with\n    | none   => ws\n    | some c => union c.uvars ws\n  ws\n\ndef tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code \u2192 Bool) : Bool :=\n  p tryCode.code ||\n  catches.any (fun \u00abcatch\u00bb => p \u00abcatch\u00bb.codeBlock.code) ||\n  match finallyCode? with\n  | none => false\n  | some finallyCode => p finallyCode.code\n\nmutual\n  /- \"Concatenate\" `c` with `doSeqToCode doElems` -/\n  partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=\n    match doElems with\n    | [] => pure c\n    | nextDoElem :: _  => do\n      let k \u2190 doSeqToCode doElems\n      let ref := nextDoElem\n      concat c ref none k\n\n  /- Generate `CodeBlock` for `doLetArrow; doElems`\n     `doLetArrow` is of the form\n     ```\n     \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\n     ```\n     where\n     ```\n     def doIdDecl   := leading_parser ident >> optType >> leftArrow >> doElemParser\n     def doPatDecl  := leading_parser termParser >> leftArrow >> doElemParser >> optional (\" | \" >> doElemParser)\n     ```\n  -/\n  partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref     := doLetArrow\n    let decl    := doLetArrow[2]\n    if decl.getKind == `Lean.Parser.Term.doIdDecl then\n      let y := decl[0].getId\n      checkNotShadowingMutable #[y]\n      let doElem := decl[3]\n      let k \u2190 withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)\n      match isDoExpr? doElem with\n      | some action => pure $ mkVarDeclCore #[y] doLetArrow k\n      | none =>\n        checkLetArrowRHS doElem\n        let c \u2190 doSeqToCode [doElem]\n        match doElems with\n        | []       => pure c\n        | kRef::_  => concat c kRef y k\n    else if decl.getKind == `Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190\n          if isMutableLet doLetArrow then\n            `(do let discr \u2190 $doElem; let mut $pattern:term := discr)\n          else\n            `(do let discr \u2190 $doElem; let $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        if isMutableLet doLetArrow then\n          throwError \"'mut' is currently not supported in let-decls with 'else' case\"\n        let contSeq := mkDoSeq doElems.toArray\n        let elseSeq := mkSingletonDoSeq optElse[1]\n        let auxDo \u2190 `(do let discr \u2190 $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n    else\n      throwError \"unexpected kind of 'do' declaration\"\n\n\n  /- Generate `CodeBlock` for `doReassignArrow; doElems`\n     `doReassignArrow` is of the form\n     ```\n     (doIdDecl <|> doPatDecl)\n     ```\n  -/\n  partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref  := doReassignArrow\n    let decl := doReassignArrow[0]\n    if decl.getKind == `Lean.Parser.Term.doIdDecl then\n      let doElem := decl[3]\n      let y      := decl[0]\n      let auxDo \u2190 `(do let r \u2190 $doElem; $y:ident := r)\n      doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n    else if decl.getKind == `Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 `(do let discr \u2190 $doElem; $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        throwError \"reassignment with `|` (i.e., \\\"else clause\\\") is not currently supported\"\n    else\n      throwError \"unexpected kind of 'do' reassignment\"\n\n  /- Generate `CodeBlock` for `doIf; doElems`\n     `doIf` is of the form\n     ```\n     \"if \" >> optIdent >> termParser >> \" then \" >> doSeq\n      >> many (group (try (group (\" else \" >> \" if \")) >> optIdent >> termParser >> \" then \" >> doSeq))\n      >> optional (\" else \" >> doSeq)\n     ```  -/\n  partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let view \u2190 liftMacroM $ mkDoIfView doIf\n    let thenBranch \u2190 doSeqToCode (getDoSeqElems view.thenBranch)\n    let elseBranch \u2190 doSeqToCode (getDoSeqElems view.elseBranch)\n    let ite \u2190 mkIte view.ref view.optIdent view.cond thenBranch elseBranch\n    concatWith ite doElems\n\n  /- Generate `CodeBlock` for `doUnless; doElems`\n     `doUnless` is of the form\n     ```\n     \"unless \" >> termParser >> \"do \" >> doSeq\n     ```  -/\n  partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do\n    let ref   := doUnless\n    let cond  := doUnless[1]\n    let doSeq := doUnless[3]\n    let body \u2190 doSeqToCode (getDoSeqElems doSeq)\n    let unlessCode \u2190 liftMacroM <| mkUnless cond body\n    concatWith unlessCode doElems\n\n  /- Generate `CodeBlock` for `doFor; doElems`\n     `doFor` is of the form\n     ```\n     def doForDecl := leading_parser termParser >> \" in \" >> withForbidden \"do\" termParser\n     def doFor := leading_parser \"for \" >> sepBy1 doForDecl \", \" >> \"do \" >> doSeq\n     ```\n  -/\n  partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let doForDecls := doFor[1].getSepArgs\n    if doForDecls.size > 1 then\n      /-\n        Expand\n        ```\n        for x in xs, y in ys do\n          body\n        ```\n        into\n        ```\n        let s := toStream ys\n        for x in xs do\n          match Stream.next? s with\n          | none => break\n          | some (y, s') =>\n            s := s'\n            body\n        ```\n      -/\n      -- Extract second element\n      let doForDecl := doForDecls[1]\n      let y  := doForDecl[0]\n      let ys := doForDecl[2]\n      let doForDecls := doForDecls.eraseIdx 1\n      let body := doFor[3]\n      withFreshMacroScope do\n        let toStreamFn \u2190 withRef ys ``(toStream)\n        let auxDo \u2190\n          `(do let mut s := $toStreamFn:ident $ys\n               for $doForDecls:doForDecl,* do\n                 match Stream.next? s with\n                 | none => break\n                 | some ($y, s') =>\n                   s := s'\n                   do $body)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n    else withRef doFor do\n      let x         := doForDecls[0][0]\n      withRef x <| checkNotShadowingMutable (\u2190 getPatternVarsEx x)\n      let xs        := doForDecls[0][2]\n      let forElems  := getDoSeqElems doFor[3]\n      let forInBodyCodeBlock \u2190 withFor (doSeqToCode forElems)\n      let \u27e8uvars, forInBody\u27e9 \u2190 mkForInBody x forInBodyCodeBlock\n      let uvarsTuple \u2190 liftMacroM do mkTuple (\u2190 uvars.mapM mkIdentFromRef)\n      if hasReturn forInBodyCodeBlock.code then\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)\n        let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                         $uvarsTuple:term := r.2;\n                         match r.1 with\n                         | none => Pure.pure (ensureExpectedType% \"type mismatch, 'for'\" PUnit.unit)\n                         | some a => return ensureExpectedType% \"type mismatch, 'for'\" a)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n      else\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody)\n        if doElems.isEmpty then\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                           $uvarsTuple:term := r;\n                           Pure.pure (ensureExpectedType% \"type mismatch, 'for'\" PUnit.unit))\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n        else\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term; $uvarsTuple:term := r)\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n\n  /-- Generate `CodeBlock` for `doMatch; doElems` -/\n  partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref       := doMatch\n    let genParam  := doMatch[1]\n    let discrs    := doMatch[2]\n    let optType   := doMatch[3]\n    let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`\n    let alts \u2190  matchAlts.mapM fun matchAlt => do\n      let patterns := matchAlt[1]\n      let vars \u2190 getPatternsVarsEx patterns.getSepArgs\n      withRef patterns <| checkNotShadowingMutable vars\n      let rhs  := matchAlt[3]\n      let rhs \u2190 doSeqToCode (getDoSeqElems rhs)\n      pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }\n    let matchCode \u2190 mkMatch ref genParam discrs optType alts\n    concatWith matchCode doElems\n\n  /--\n    Generate `CodeBlock` for `doTry; doElems`\n    ```\n    def doTry := leading_parser \"try \" >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally\n    def doCatch      := leading_parser \"catch \" >> binderIdent >> optional (\":\" >> termParser) >> darrow >> doSeq\n    def doCatchMatch := leading_parser \"catch \" >> doMatchAlts\n    def doFinally    := leading_parser \"finally \" >> doSeq\n    ```\n  -/\n  partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref := doTry\n    let tryCode \u2190 doSeqToCode (getDoSeqElems doTry[1])\n    let optFinally := doTry[3]\n    let catches \u2190 doTry[2].getArgs.mapM fun catchStx => do\n      if catchStx.getKind == `Lean.Parser.Term.doCatch then\n        let x       := catchStx[1]\n        if x.isIdent then\n          withRef x <| checkNotShadowingMutable #[x.getId]\n        let optType := catchStx[2]\n        let c \u2190 doSeqToCode (getDoSeqElems catchStx[4])\n        pure { x := x, optType := optType, codeBlock := c : Catch }\n      else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then\n        let matchAlts := catchStx[1]\n        let x \u2190 `(ex)\n        let auxDo \u2190 `(do match ex with $matchAlts)\n        let c \u2190 doSeqToCode (getDoSeqElems (getDoSeq auxDo))\n        pure { x := x, codeBlock := c, optType := mkNullNode : Catch }\n      else\n        throwError \"unexpected kind of 'catch'\"\n    let finallyCode? \u2190 if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])\n    if catches.isEmpty && finallyCode?.isNone then\n      throwError \"invalid 'try', it must have a 'catch' or 'finally'\"\n    let ctx \u2190 read\n    let ws    := getTryCatchUpdatedVars tryCode catches finallyCode?\n    let uvars := nameSetToArray ws\n    let a     := tryCatchPred tryCode catches finallyCode? hasTerminalAction\n    let r     := tryCatchPred tryCode catches finallyCode? hasReturn\n    let bc    := tryCatchPred tryCode catches finallyCode? hasBreakContinue\n    let toTerm (codeBlock : CodeBlock) : M Syntax := do\n      let codeBlock \u2190 liftM $ extendUpdatedVars codeBlock ws\n      liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc\n    let term \u2190 toTerm tryCode\n    let term \u2190 catches.foldlM\n      (fun term \u00abcatch\u00bb => do\n        let catchTerm \u2190 toTerm \u00abcatch\u00bb.codeBlock\n        if catch.optType.isNone then\n          ``(MonadExcept.tryCatch $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n        else\n          let type := \u00abcatch\u00bb.optType[1]\n          ``(tryCatchThe $type $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm)))\n      term\n    let term \u2190 match finallyCode? with\n      | none             => pure term\n      | some finallyCode => withRef optFinally do\n        unless finallyCode.uvars.isEmpty do\n          throwError \"'finally' currently does not support reassignments\"\n        if hasBreakContinueReturn finallyCode.code then\n          throwError \"'finally' currently does 'return', 'break', nor 'continue'\"\n        let finallyTerm \u2190 liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular\n        ``(tryFinally $term $finallyTerm)\n    let doElemsNew \u2190 liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc\n    doSeqToCode (doElemsNew ++ doElems)\n\n  partial def doSeqToCode : List Syntax \u2192 M CodeBlock\n    | [] => do liftMacroM mkPureUnitAction\n    | doElem::doElems => withIncRecDepth <| withRef doElem do\n      checkMaxHeartbeats \"'do'-expander\"\n      match (\u2190 liftMacroM <| expandMacro? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n      match (\u2190 liftMacroM <| expandDoIf? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n        let (liftedDoElems, doElem) \u2190 liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _)\n        if !liftedDoElems.isEmpty then\n          doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)\n        else\n          let ref := doElem\n          let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems\n          let k := doElem.getKind\n          if k == `Lean.Parser.Term.doLet then\n            let vars \u2190 getDoLetVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doHave then\n            let var := getDoHaveVar doElem\n            checkNotShadowingMutable #[var]\n            mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doLetRec then\n            let vars \u2190 getDoLetRecVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doReassign then\n            let vars \u2190 getDoReassignVars doElem\n            checkReassignable vars\n            let k \u2190 doSeqToCode doElems\n            mkReassignCore vars doElem k\n          else if k == `Lean.Parser.Term.doLetArrow then\n            doLetArrowToCode doElem doElems\n          else if k == `Lean.Parser.Term.doReassignArrow then\n            doReassignArrowToCode doElem doElems\n          else if k == `Lean.Parser.Term.doIf then\n            doIfToCode doElem doElems\n          else if k == `Lean.Parser.Term.doUnless then\n            doUnlessToCode doElem doElems\n          else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do\n            doForToCode doElem doElems\n          else if k == `Lean.Parser.Term.doMatch then\n            doMatchToCode doElem doElems\n          else if k == `Lean.Parser.Term.doTry then\n            doTryToCode doElem doElems\n          else if k == `Lean.Parser.Term.doBreak then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkBreak ref\n          else if k == `Lean.Parser.Term.doContinue then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkContinue ref\n          else if k == `Lean.Parser.Term.doReturn then\n            doReturnToCode doElem doElems\n          else if k == `Lean.Parser.Term.doDbgTrace then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doAssert then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doNested then\n            let nestedDoSeq := doElem[1]\n            doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)\n          else if k == `Lean.Parser.Term.doExpr then\n            let term := doElem[0]\n            if doElems.isEmpty then\n              return mkTerminalAction term\n            else\n              return mkSeq term (\u2190 doSeqToCode doElems)\n          else\n            throwError \"unexpected do-element of kind {doElem.getKind}:\\n{doElem}\"\nend\n\ndef run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=\n  (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m }\n\nend ToCodeBlock\n\n/- Create a synthetic metavariable `?m` and assign `m` to it.\n   We use `?m` to refer to `m` when expanding the `do` notation. -/\nprivate def mkMonadAlias (m : Expr) : TermElabM Syntax := do\n  let result \u2190 `(?m)\n  let mType \u2190 inferType m\n  let mvar \u2190 elabTerm result mType\n  assignExprMVar mvar.mvarId! m\n  pure result\n\n@[builtinTermElab \u00abdo\u00bb]\ndef elabDo : TermElab := fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  let bindInfo \u2190 extractBind expectedType?\n  let m \u2190 mkMonadAlias bindInfo.m\n  let codeBlock \u2190 ToCodeBlock.run stx m\n  let stxNew \u2190 liftMacroM $ ToTerm.run codeBlock.code m\n  trace[Elab.do] stxNew\n  withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType\n\nend Do\n\nbuiltin_initialize registerTraceClass `Elab.do\n\nprivate def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do\n  let stx := stx.setKind newKind\n  withRef stx `(do $stx:doElem)\n\n@[builtinMacro Lean.Parser.Term.termFor]\ndef expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor\n\n@[builtinMacro Lean.Parser.Term.termTry]\ndef expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry\n\n@[builtinMacro Lean.Parser.Term.termUnless]\ndef expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless\n\n@[builtinMacro Lean.Parser.Term.termReturn]\ndef expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn\n\nend Lean.Elab.Term\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Elab/Do.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14033624949008322, "lm_q2_score": 0.027585279928436127, "lm_q1q2_score": 0.0038712147262907975}}
{"text": "/-\nCopyright (c) 2020 Marc Huisinga. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Marc Huisinga, Wojciech Nawrocki\n-/\nimport Lean.Data.Json\nimport Lean.Data.JsonRpc\n\n/-! Defines most of the 'Basic Structures' in the LSP specification\n(https://microsoft.github.io/language-server-protocol/specifications/specification-current/),\nas well as some utilities.\n\nSince LSP is Json-based, Ints/Nats are represented by Floats on the wire. -/\n\nnamespace Lean\nnamespace Lsp\n\nopen Json\n\nstructure CancelParams where\n  id : JsonRpc.RequestID\n  deriving Inhabited, BEq, ToJson, FromJson\n\nabbrev DocumentUri := String\n\n/-- We adopt the convention that zero-based UTF-16 positions as sent by LSP clients\nare represented by `Lsp.Position` while internally we mostly use `String.Pos` UTF-8\noffsets. For diagnostics, one-based `Lean.Position`s are used internally.\n`character` is accepted liberally: actual character := min(line length, character) -/\nstructure Position where\n  line : Nat\n  character : Nat\n  deriving Inhabited, BEq, Ord, Hashable, ToJson, FromJson\n\ninstance : ToString Position := \u27e8fun p =>\n  \"(\" ++ toString p.line ++ \", \" ++ toString p.character ++ \")\"\u27e9\n\ninstance : LT Position := ltOfOrd\ninstance : LE Position := leOfOrd\n\nstructure Range where\n  start : Position\n  \u00abend\u00bb : Position\n  deriving Inhabited, BEq, Hashable, ToJson, FromJson, Ord\n\ninstance : LT Range := ltOfOrd\ninstance : LE Range := leOfOrd\n\n/-- A `Location` is a `DocumentUri` and a `Range`. -/\nstructure Location where\n  uri : DocumentUri\n  range : Range\n  deriving Inhabited, BEq, ToJson, FromJson\n\nstructure LocationLink where\n  originSelectionRange? : Option Range\n  targetUri : DocumentUri\n  targetRange : Range\n  targetSelectionRange : Range\n  deriving ToJson, FromJson\n\n-- NOTE: Diagnostic defined in Diagnostics.lean\n\n/-- Represents a reference to a client editor command.\n\nNOTE: No specific commands are specified by LSP, hence\npossible commands need to be announced as capabilities.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#command)\n-/\nstructure Command where\n  /-- Title of the command, like `save`. -/\n  title : String\n  /-- The identifier of the actual command handler. -/\n  command : String\n  /-- Arguments that the command handler should be invoked with. -/\n  arguments? : Option (Array Json) := none\n  deriving ToJson, FromJson\n\n/-- A textual edit applicable to a text document.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textEdit) -/\nstructure TextEdit where\n  /--  The range of the text document to be manipulated.\n    To insert text into a document create a range where `start = end`. -/\n  range : Range\n  /-- The string to be inserted. For delete operations use an empty string. -/\n  newText : String\n  /-- Identifier for annotated edit.\n\n    `WorkspaceEdit` has a `changeAnnotations` field that maps these identifiers to a `ChangeAnnotation`.\n    By annotating an edit you can add a description of what the edit will do and also control whether the\n    user is presented with a prompt before applying the edit.\n    [reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textEdit).\n  -/\n  annotationId? : Option String := none\n  deriving ToJson, FromJson\n\n/-- An array of `TextEdit`s to be performed in sequence. -/\ndef TextEditBatch := Array TextEdit\n\ninstance : FromJson TextEditBatch :=\n  \u27e8@fromJson? (Array TextEdit) _\u27e9\n\ninstance : ToJson TextEditBatch :=\n  \u27e8@toJson (Array TextEdit) _\u27e9\n\ninstance : EmptyCollection TextEditBatch := \u27e8#[]\u27e9\n\ninstance : Append TextEditBatch :=\n  inferInstanceAs (Append (Array _))\n\ninstance : Coe TextEdit TextEditBatch where\n  coe te := #[te]\n\nstructure TextDocumentIdentifier where\n  uri : DocumentUri\n  deriving ToJson, FromJson\n\nstructure VersionedTextDocumentIdentifier where\n  uri : DocumentUri\n  version? : Option Nat := none\n  deriving ToJson, FromJson\n\n/-- A batch of `TextEdit`s to perform on a versioned text document.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentEdit) -/\nstructure TextDocumentEdit where\n  textDocument : VersionedTextDocumentIdentifier\n  edits : TextEditBatch\n  deriving ToJson, FromJson\n\n/-- Additional information that describes document changes.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textEdit) -/\nstructure ChangeAnnotation where\n  /-- A human-readable string describing the actual change.\n  The string is rendered prominent in the user interface. -/\n  label             : String\n  /-- A flag which indicates that user confirmation is needed before applying the change. -/\n  needsConfirmation : Bool := false\n  /-- A human-readable string which is rendered less prominent in the user interface. -/\n  description?      : Option String := none\n  deriving ToJson, FromJson\n\n/-- Options for `CreateFile` and `RenameFile`. -/\nstructure CreateFile.Options where\n  overwrite      : Bool := false\n  ignoreIfExists : Bool := false\n  deriving ToJson, FromJson\n\n/-- Options for `DeleteFile`. -/\nstructure DeleteFile.Options where\n  recursive : Bool := false\n  ignoreIfNotExists := false\n  deriving ToJson, FromJson\n\nstructure CreateFile where\n  uri           : DocumentUri\n  options?      : Option CreateFile.Options := none\n  annotationId? : Option String := none\n  deriving ToJson, FromJson\n\nstructure RenameFile where\n  oldUri        : DocumentUri\n  newUri        : DocumentUri\n  options?      : Option CreateFile.Options := none\n  annotationId? : Option String := none\n  deriving ToJson, FromJson\n\nstructure DeleteFile where\n  uri           : DocumentUri\n  options?      : Option DeleteFile.Options := none\n  annotationId? : Option String := none\n  deriving ToJson, FromJson\n\n/-- A change to a file resource.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#resourceChanges) -/\ninductive DocumentChange where\n  | create : CreateFile       \u2192 DocumentChange\n  | rename : RenameFile       \u2192 DocumentChange\n  | delete : DeleteFile       \u2192 DocumentChange\n  | edit   : TextDocumentEdit \u2192 DocumentChange\n\ninstance : ToJson DocumentChange := \u27e8fun\n  | .create x => Json.setObjVal! (toJson x) \"kind\" \"create\"\n  | .rename x => Json.setObjVal! (toJson x) \"kind\" \"rename\"\n  | .delete x => Json.setObjVal! (toJson x) \"kind\" \"delete\"\n  | .edit   x => toJson x\n\u27e9\n\ninstance : FromJson DocumentChange where\n  fromJson? j := (do\n    let kind \u2190 j.getObjVal? \"kind\"\n    match kind with\n      | \"create\" => return DocumentChange.create <|\u2190 fromJson? j\n      | \"rename\" => return DocumentChange.rename <|\u2190 fromJson? j\n      | \"delete\" => return DocumentChange.delete <|\u2190 fromJson? j\n      | kind => throw s!\"Unrecognized kind: {kind}\")\n    <|> (DocumentChange.edit <$> fromJson? j)\n\n/-- A workspace edit represents changes to many resources managed in the workspace.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspaceEdit) -/\nstructure WorkspaceEdit where\n  /-- Changes to existing resources. -/\n  changes : RBMap DocumentUri TextEditBatch compare := \u2205\n  /-- Depending on the client capability\n    `workspace.workspaceEdit.resourceOperations` document changes are either\n    an array of `TextDocumentEdit`s to express changes to n different text\n    documents where each text document edit addresses a specific version of\n    a text document. Or it can contain above `TextDocumentEdit`s mixed with\n    create, rename and delete file / folder operations.\n\n    Whether a client supports versioned document edits is expressed via\n    `workspace.workspaceEdit.documentChanges` client capability.\n\n    If a client neither supports `documentChanges` nor\n    `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s\n    using the `changes` property are supported. -/\n  documentChanges : Array DocumentChange := \u2205\n  /-- A map of change annotations that can be referenced in\n      `AnnotatedTextEdit`s or create, rename and delete file / folder\n      operations.\n\n      Whether clients honor this property depends on the client capability\n      `workspace.changeAnnotationSupport`. -/\n  changeAnnotations : RBMap String ChangeAnnotation compare := \u2205\n  deriving ToJson, FromJson\n\nnamespace WorkspaceEdit\n\ninstance : EmptyCollection WorkspaceEdit := \u27e8{}\u27e9\n\ninstance : Append WorkspaceEdit where\n  append x y := {\n    changes           := x.changes.mergeBy (fun _ v\u2081 v\u2082 => v\u2081 ++ v\u2082) y.changes\n    documentChanges   := x.documentChanges ++ y.documentChanges\n    changeAnnotations := x.changeAnnotations.mergeBy (fun _ _v\u2081 v\u2082 => v\u2082) y.changeAnnotations\n  }\n\ndef ofTextDocumentEdit (e : TextDocumentEdit) : WorkspaceEdit :=\n  { documentChanges := #[DocumentChange.edit e]}\n\ndef ofTextEdit (uri : DocumentUri) (te : TextEdit) : WorkspaceEdit :=\n  /- [note], there is a bug in vscode where not including the version will cause an error,\n  even though the version field is not used to validate the change.\n\n  References:\n  - [a fix in the wild](https://github.com/stylelint/vscode-stylelint/pull/330/files).\n    Note that the version field needs to be present, even if the value is `undefined`.\n  - [angry comment](https://github.com/tsqllint/tsqllint-vscode-extension/blob/727026fce9f8c6a33d113373666d0776f8f6c23c/server/src/server.ts#L70)\n  -/\n  let doc := {uri, version? := some 0}\n  ofTextDocumentEdit { textDocument := doc, edits := #[te]}\n\nend WorkspaceEdit\n\n/-- The `workspace/applyEdit` request is sent from the server to the client to modify resource on the client side.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#applyWorkspaceEditParams) -/\nstructure ApplyWorkspaceEditParams where\n  /-- An optional label of the workspace edit. This label is\n  presented in the user interface for example on an undo\n  stack to undo the workspace edit. -/\n  label? : Option String := none\n  /-- The edits to apply. -/\n  edit : WorkspaceEdit\n  deriving ToJson, FromJson\n\n/-- An item to transfer a text document from the client to the server.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem)\n-/\nstructure TextDocumentItem where\n  /-- The text document's URI. -/\n  uri : DocumentUri\n  /-- The text document's language identifier. -/\n  languageId : String\n  /-- The version number of this document (it will increase after each change, including undo/redo). -/\n  version : Nat\n  /-- The content of the opened text document. -/\n  text : String\n  deriving ToJson, FromJson\n\nstructure TextDocumentPositionParams where\n  textDocument : TextDocumentIdentifier\n  position : Position\n  deriving ToJson, FromJson\n\ninstance : ToString TextDocumentPositionParams where\n  toString p := s!\"{p.textDocument.uri}:{p.position.line}:{p.position.character}\"\n\nstructure DocumentFilter where\n  language? : Option String := none\n  scheme?   : Option String := none\n  pattern?  : Option String := none\n  deriving ToJson, FromJson\n\ndef DocumentSelector := Array DocumentFilter\n\ninstance : FromJson DocumentSelector :=\n  \u27e8@fromJson? (Array DocumentFilter) _\u27e9\n\ninstance : ToJson DocumentSelector :=\n  \u27e8@toJson (Array DocumentFilter) _\u27e9\n\nstructure StaticRegistrationOptions where\n  id? : Option String := none\n  deriving ToJson, FromJson\n\nstructure TextDocumentRegistrationOptions where\n  documentSelector? : Option DocumentSelector := none\n  deriving ToJson, FromJson\n\ninductive MarkupKind where\n  | plaintext | markdown\n\ninstance : FromJson MarkupKind := \u27e8fun\n  | str \"plaintext\" => Except.ok MarkupKind.plaintext\n  | str \"markdown\"  => Except.ok MarkupKind.markdown\n  | _               => throw \"unknown MarkupKind\"\u27e9\n\ninstance : ToJson MarkupKind := \u27e8fun\n  | MarkupKind.plaintext => str \"plaintext\"\n  | MarkupKind.markdown  => str \"markdown\"\u27e9\n\nstructure MarkupContent where\n  kind  : MarkupKind\n  value : String\n  deriving ToJson, FromJson\n\n/-- Reference to the progress of some in-flight piece of work.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#progress)\n-/\nabbrev ProgressToken := String -- do we need integers?\n\n/-- Params for JSON-RPC method `$/progress` request.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#progress) -/\nstructure ProgressParams (\u03b1 : Type) where\n  token : ProgressToken\n  value : \u03b1\n  deriving ToJson\n\nstructure WorkDoneProgressReport where\n  kind := \"report\"\n  /-- More detailed associated progress message. -/\n  message? : Option String := none\n  /-- Controls if a cancel button should show to allow the user to cancel the operation. -/\n  cancellable := false\n  /-- Optional progress percentage to display (value 100 is considered 100%).\n      If not provided infinite progress is assumed. -/\n  percentage? : Option Nat := none\n  deriving ToJson\n\n/-- Notification to signal the start of progress reporting. -/\nstructure WorkDoneProgressBegin extends WorkDoneProgressReport where\n  kind := \"begin\"\n  title : String\n  deriving ToJson\n\n/-- Signals the end of progress reporting. -/\nstructure WorkDoneProgressEnd where\n  kind := \"end\"\n  message? : Option String := none\n  deriving ToJson\n\nstructure WorkDoneProgressParams where\n  workDoneToken? : Option ProgressToken := none\n  deriving ToJson, FromJson\n\nstructure PartialResultParams where\n  partialResultToken? : Option ProgressToken := none\n  deriving ToJson, FromJson\n\n/-- [reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workDoneProgressOptions) -/\nstructure WorkDoneProgressOptions where\n  workDoneProgress := false\n  deriving ToJson, FromJson\n\nend Lsp\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/Data/Lsp/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970577387797076, "lm_q2_score": 0.03514485044314308, "lm_q1q2_score": 0.0038555930156905557}}
{"text": "import ..flocq\n\n/- Architecture-dependent parameters for x86 in 64-bit mode -/\n\nnamespace archi\nopen flocq\n\ndef ptr64 : bool := tt\n\ndef big_endian : bool := ff\n\ndef align_int64 := 4\ndef align_float64 := 4\n\ndef splitlong := bnot ptr64\n\nlemma splitlong_ptr32 : splitlong = tt \u2192 ptr64 = ff := \u03bbh, bool.no_confusion h\n\ndef default_pl_64 : bool \u00d7 nan_pl 53 :=\n(ff, word.repr (2^51))\n  \ndef choose_binop_pl_64 (s1 : bool) (pl1 : nan_pl 53) (s2 : bool) (pl2 : nan_pl 53) : bool :=\nff /- always choose first NaN -/\n\ndef default_pl_32 : bool \u00d7 nan_pl 24 :=\n(ff,  word.repr (2^22))\n  \ndef choose_binop_pl_32 (s1 : bool) (pl1 : nan_pl 24) (s2 : bool) (pl2 : nan_pl 24) : bool :=\nff /- always choose first NaN -/\n   \ndef float_of_single_preserves_sNaN := ff\n\nend archi", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/archi/x86_64.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21733752104706244, "lm_q2_score": 0.01771229581915593, "lm_q1q2_score": 0.003849546465387598}}
{"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.Elab.Term\nimport Lean.Elab.BindersUtil\nimport Lean.Elab.PatternVar\nimport Lean.Elab.Quotation.Util\nimport Lean.Parser.Do\nimport Lean.Elab.Do\nimport Lean.Util.CollectLevelParams\nimport HBind.HBind\n\n/-\n`hdo (monad := IDENT)`\nThe identifier should be universe polymorphic.\n-/\nsyntax (name := hdo) \"hdo\" doSeq: term\nsyntax (name := hdo_2) \"hdo \" atomic(\"(\" &\"monad\" \" := \" term \")\") doSeq: term\n\n-- HACK: avoid code explosion until heuristics are improved\nset_option compiler.reuse false\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Meta\nopen TSyntax.Compat\n\nprivate def getDoSeqElems (doSeq : Syntax) : List Syntax :=\n  if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then\n    doSeq[1].getArgs.toList.map fun arg => arg[0]\n  else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then\n    doSeq[0].getArgs.toList.map fun arg => arg[0]\n  else\n    []\n\nprivate def getDoSeq (doStx : Syntax) : Syntax :=\n  doStx[1]\n\n/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/\nprivate def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=\n  k == ``Lean.Parser.Term.do ||\n  k == ``Lean.Parser.Term.doSeqIndent ||\n  k == ``Lean.Parser.Term.doSeqBracketed ||\n  k == ``Lean.Parser.Term.termReturn ||\n  k == ``Lean.Parser.Term.termUnless ||\n  k == ``Lean.Parser.Term.termTry ||\n  k == ``Lean.Parser.Term.termFor\n\n/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/\nprivate def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=\n  let k := letDeclArg.getKind\n  if k == ``Lean.Parser.Term.letPatDecl then\n    false\n  else if k == ``Lean.Parser.Term.letEqnsDecl then\n    true\n  else if k == ``Lean.Parser.Term.letIdDecl then\n    -- letIdLhs := ident >> checkWsBefore \"expected space before binders\" >> many (ppSpace >> letIdBinder)) >> optType\n    let binders := letDeclArg[1]\n    binders.getNumArgs > 0\n  else\n    false\n\n/-- Return `true` if the given `letDecl` contains binders. -/\nprivate def letDeclHasBinders (letDecl : Syntax) : Bool :=\n  letDeclArgHasBinders letDecl[0]\n\n/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/\nprivate def liftMethodForbiddenBinder (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||\n     k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec  then\n     -- It is never ok to lift over this kind of binder\n    true\n  -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not\n  else if k == ``Lean.Parser.Term.let then\n    letDeclHasBinders stx[1]\n  else if k == ``Lean.Parser.Term.doLet then\n    letDeclHasBinders stx[2]\n  else if k == ``Lean.Parser.Term.doLetArrow then\n    letDeclArgHasBinders stx[2]\n  else\n    false\n\nprivate partial def hasLiftMethod : Syntax \u2192 Bool\n  | Syntax.node _ k args =>\n    if liftMethodDelimiter k then false\n    -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a\n    -- bit slower\n    else if k == ``Lean.Parser.Term.liftMethod then true\n    else args.any hasLiftMethod\n  | _ => false\n\nprivate def mkUnknownMonadResult : MetaM ExtractMonadResult := do\n  let u \u2190 mkFreshLevelMVar\n  let v \u2190 mkFreshLevelMVar\n  let m \u2190 mkFreshExprMVar (\u2190 mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v)))\n  let returnType \u2190 mkFreshExprMVar (mkSort (mkLevelSucc u))\n  return { m, returnType, expectedType := mkApp m returnType }\n\nprivate partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do\n  let some expectedType := expectedType? | mkUnknownMonadResult\n  let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n    let .app m returnType := type | return none\n    try\n      let bindInstType \u2190 mkAppM ``Bind #[m]\n      discard <| Meta.synthInstance bindInstType\n      return some { m, returnType, expectedType }\n    catch _ =>\n      return none\n  let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n    match (\u2190 extractStep? type) with\n    | some r => return r\n    | none =>\n      let typeNew \u2190 whnfCore type\n      if typeNew != type then\n        extract? typeNew\n      else\n        if typeNew.getAppFn.isMVar then\n          mkUnknownMonadResult\n        else match (\u2190 unfoldDefinition? typeNew) with\n          | some typeNew => extract? typeNew\n          | none => return none\n  match (\u2190 extract? expectedType) with\n  | some r => return r\n  | none   => throwError \"invalid 'do' notation, expected type is not a monad application{indentExpr expectedType}\\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad.\"\n\nprivate def generalizeBindUniverse (bindInfo: ExtractMonadResult): TermElabM ExtractMonadResult := do\n  let rec genAppliedConst: Expr \u2192 TermElabM Expr\n    | .const name levels => do\n      trace[Elab.do] s!\"Found monad constant {name} with levels {levels}\"\n      let gm \u2190 mkConstWithLevelParams name\n      trace[Elab.do] s!\"Generalizing {name} into {gm}\"\n      return gm\n    | .app func arg => do\n      -- TODO: Simply erasing the universe levels of the argument is fragile\n      let arg: TermElabM Expr :=\n        match arg with\n        | .const name _ => do\n          let e \u2190 mkConstWithFreshMVarLevels name\n          trace[Elab.do] s!\"Generalizing {arg} into {e}\"\n          return e\n        | e => do\n          return e\n      mkAppM' (\u2190 genAppliedConst func) #[\u2190 arg]\n    | e => do\n      trace[Elab.do] s!\"Failed to generalize levels for monad: {bindInfo.m}\"\n      return e\n  let m \u2190 genAppliedConst bindInfo.m\n  trace[Elab.do] s!\"Final monad: {m}\"\n  return { bindInfo with m := m }\n\nnamespace HDo\n\nabbrev Var := Syntax  -- TODO: should be `Ident`\n\n/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/\nstructure Alt (\u03c3 : Type) where\n  ref : Syntax\n  vars : Array Var\n  patterns : Syntax\n  rhs : \u03c3\n  deriving Inhabited\n\n/-\n  Auxiliary datastructure for representing a `do` code block, and compiling \"reassignments\" (e.g., `x := x + 1`).\n  We convert `Code` into a `Syntax` term representing the:\n  - `do`-block, or\n  - the visitor argument for the `forIn` combinator.\n\n  We say the following constructors are terminals:\n  - `break`:    for interrupting a `for x in s`\n  - `continue`: for interrupting the current iteration of a `for x in s`\n  - `return e`: for returning `e` as the result for the whole `do` computation block\n  - `action a`: for executing action `a` as a terminal\n  - `ite`:      if-then-else\n  - `match`:    pattern matching\n  - `jmp`       a goto to a join-point\n\n  We say the terminals `break`, `continue`, `action`, and `return` are \"exit points\"\n\n  Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x == 0 then\n     return ()\n  IO.println \"hello\"\n  ```\n  Executing `#eval f 0` will not print \"hello\". Now, consider\n  ```\n  def g (x : Nat) : IO Unit := do\n  if x == 0 then\n     pure ()\n  IO.println \"hello\"\n  ```\n  The `if` statement is essentially a noop, and \"hello\" is printed when we execute `g 0`.\n\n  - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).\n    The field `stx` is the actual `doElem`,\n    `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.\n    `vars` is an array since we have declarations such as `let (a, b) := s`.\n\n  - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).\n\n  - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.\n\n  - `seq a k` executes action `a`, ignores its result, and then executes `k`.\n    We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.\n\n  A code block `C` is well-formed if\n  - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and\n    `ps.size == as.size` -/\ninductive Code where\n  | decl         (xs : Array Var) (doElem : Syntax) (k : Code)\n  | reassign     (xs : Array Var) (doElem : Syntax) (k : Code)\n  /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/\n  | joinpoint    (name : Name) (params : Array (Var \u00d7 Bool)) (body : Code) (k : Code)\n  | seq          (action : Syntax) (k : Code)\n  | action       (action : Syntax)\n  | \u00abbreak\u00bb      (ref : Syntax)\n  | \u00abcontinue\u00bb   (ref : Syntax)\n  | \u00abreturn\u00bb     (ref : Syntax) (val : Syntax)\n  /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/\n  | ite          (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)\n  | \u00abmatch\u00bb      (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code))\n  | jmp          (ref : Syntax) (jpName : Name) (args : Array Syntax)\n  deriving Inhabited\n\nabbrev VarSet := Std.RBMap Name Syntax Name.cmp\n\n/- A code block, and the collection of variables updated by it. -/\nstructure CodeBlock where\n  code  : Code\n  uvars : VarSet := {} -- set of variables updated by `code`\n\nprivate def varSetToArray (s : VarSet) : Array Var :=\n  s.fold (fun xs _ x => xs.push x) #[]\n\nprivate def varsToMessageData (vars : Array Var) : MessageData :=\n  MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) \" \"\n\npartial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=\n  let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax\n  let rec loop : Code \u2192 MessageData\n    | Code.decl xs _ k            => m!\"let {varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.reassign xs _ k        => m!\"{varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.joinpoint n ps body k  => m!\"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\\n{loop k}\"\n    | Code.seq e k                => m!\"{e}\\n{loop k}\"\n    | Code.action e               => e\n    | Code.ite _ _ _ c t e        => m!\"if {c} then {indentD (loop t)}\\nelse{loop e}\"\n    | Code.jmp _ j xs             => m!\"jmp {j.simpMacroScopes} {xs.toList}\"\n    | Code.\u00abbreak\u00bb _              => m!\"break {us}\"\n    | Code.\u00abcontinue\u00bb _           => m!\"continue {us}\"\n    | Code.\u00abreturn\u00bb _ v           => m!\"return {v} {us}\"\n    | Code.\u00abmatch\u00bb _ _ ds _ alts  =>\n      m!\"match {ds} with\"\n      ++ alts.foldl (init := m!\"\") fun acc alt => acc ++ m!\"\\n| {alt.patterns} => {loop alt.rhs}\"\n  loop codeBlock.code\n\n/- Return true if the give code contains an exit point that satisfies `p` -/\npartial def hasExitPointPred (c : Code) (p : Code \u2192 Bool) : Bool :=\n  let rec loop : Code \u2192 Bool\n    | Code.decl _ _ k           => loop k\n    | Code.reassign _ _ k       => loop k\n    | Code.joinpoint _ _ b k    => loop b || loop k\n    | Code.seq _ k              => loop k\n    | Code.ite _ _ _ _ t e      => loop t || loop e\n    | Code.\u00abmatch\u00bb _ _ _ _ alts => alts.any (loop \u00b7.rhs)\n    | Code.jmp _ _ _            => false\n    | c                         => p c\n  loop c\n\ndef hasExitPoint (c : Code) : Bool :=\n  hasExitPointPred c fun _ => true\n\ndef hasReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef hasTerminalAction (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abaction\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinue (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinueReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax \u2192 m Code) : m Code := withRef e <| withFreshMacroScope do\n  let y \u2190 `(y)\n  let doElem \u2190 `(doElem| let y \u2190 $e:term)\n  -- Add elaboration hint for producing sane error message\n  let y \u2190 `(ensure_expected_type% \"type mismatch, result value\" $y)\n  let k \u2190 mkCont y\n  return Code.decl #[y] doElem k\n\n/- Convert `action _ e` instructions in `c` into `let y \u2190 e; jmp _ jp (xs y)`. -/\npartial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code :=\n  let rec loop : Code \u2192 MacroM Code\n    | Code.decl xs stx k           => return Code.decl xs stx (\u2190 loop k)\n    | Code.reassign xs stx k       => return Code.reassign xs stx (\u2190 loop k)\n    | Code.joinpoint n ps b k      => return Code.joinpoint n ps (\u2190 loop b) (\u2190 loop k)\n    | Code.seq e k                 => return Code.seq e (\u2190 loop k)\n    | Code.ite ref x? h c t e      => return Code.ite ref x? h c (\u2190 loop t) (\u2190 loop e)\n    | Code.\u00abmatch\u00bb ref g ds t alts => return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 loop alt.rhs) })\n    | Code.action e                => mkAuxDeclFor e fun y =>\n      let ref := e\n      -- We jump to `jp` with xs **and** y\n      let jmpArgs := xs.push y\n      return Code.jmp ref jp jmpArgs\n    | c                            => return c\n  loop code\n\nstructure JPDecl where\n  name : Name\n  params : Array (Var \u00d7 Bool)\n  body : Code\n\ndef attachJP (jpDecl : JPDecl) (k : Code) : Code :=\n  Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k\n\ndef attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=\n  jpDecls.foldr attachJP k\n\ndef mkFreshJP (ps : Array (Var \u00d7 Bool)) (body : Code) : TermElabM JPDecl := do\n  let ps \u2190 if ps.isEmpty then\n    let y \u2190 `(y)\n    pure #[(y.raw, false)]\n  else\n    pure ps\n  -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by\n  -- the \"do\" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`\n  -- We will remove this hack when we re-implement the compiler frontend in Lean.\n  let name \u2190 mkFreshUserName `_do_jp\n  pure { name := name, params := ps, body := body }\n\ndef addFreshJP (ps : Array (Var \u00d7 Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do\n  let jp \u2190 mkFreshJP ps body\n  modify fun (jps : Array JPDecl) => jps.push jp\n  pure jp.name\n\ndef insertVars (rs : VarSet) (xs : Array Var) : VarSet :=\n  xs.foldl (fun rs x => rs.insert x.getId x) rs\n\ndef eraseVars (rs : VarSet) (xs : Array Var) : VarSet :=\n  xs.foldl (\u00b7.erase \u00b7.getId) rs\n\ndef eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet :=\n  match x? with\n  | none   => rs\n  | some x => rs.insert x.getId x\n\n/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/\ndef mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := varSetToArray rs\n  let jp \u2190 addFreshJP (xs.map fun x => (x, true)) c\n  if xs.isEmpty then\n    let unit \u2190 ``(Unit.unit)\n    return Code.jmp ref jp #[unit]\n  else\n    return Code.jmp ref jp xs\n\n/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.\n   The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`\n   is a fresh variable created by this method. -/\ndef mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax \u2192 MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := varSetToArray rs\n  let args := xs.push val\n  let yFresh \u2190 withRef ref `(y)\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (yFresh, false)\n  let jpBody \u2190 liftMacroM <| mkJPBody yFresh\n  let jp \u2190 addFreshJP ps jpBody\n  return Code.jmp ref jp args\n\n/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path.  -/\npartial def pullExitPointsAux : VarSet \u2192 Code \u2192 StateRefT (Array JPDecl) TermElabM Code\n  | rs, Code.decl xs stx k           => return Code.decl xs stx (\u2190 pullExitPointsAux (eraseVars rs xs) k)\n  | rs, Code.reassign xs stx k       => return Code.reassign xs stx (\u2190 pullExitPointsAux (insertVars rs xs) k)\n  | rs, Code.joinpoint j ps b k      => return Code.joinpoint j ps (\u2190 pullExitPointsAux rs b) (\u2190 pullExitPointsAux rs k)\n  | rs, Code.seq e k                 => return Code.seq e (\u2190 pullExitPointsAux rs k)\n  | rs, Code.ite ref x? o c t e      => return Code.ite ref x? o c (\u2190 pullExitPointsAux (eraseOptVar rs x?) t) (\u2190 pullExitPointsAux (eraseOptVar rs x?) e)\n  | rs, Code.\u00abmatch\u00bb ref g ds t alts => return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })\n  | _,  c@(Code.jmp _ _ _)           => return  c\n  | rs, Code.\u00abbreak\u00bb ref             => mkSimpleJmp ref rs (Code.\u00abbreak\u00bb ref)\n  | rs, Code.\u00abcontinue\u00bb ref          => mkSimpleJmp ref rs (Code.\u00abcontinue\u00bb ref)\n  | rs, Code.\u00abreturn\u00bb ref val        => mkJmp ref rs val (fun y => return Code.\u00abreturn\u00bb ref y)\n  | rs, Code.action e                =>\n    -- We use `mkAuxDeclFor` because `e` is not pure.\n    mkAuxDeclFor e fun y =>\n      let ref := e\n      mkJmp ref rs y (fun yFresh => return Code.action (\u2190 ``(Pure.pure $yFresh)))\n\n/-\nAuxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.\nWhen a new variable is not already in the collection, but is shadowed by some declaration in `c`,\nwe create auxiliary join points to make sure we preserve the semantics of the code block.\nExample: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it\nwith the reassignment `x := x + 1`. We first use `pullExitPoints` to create\n```\nlet jp (x!1) :=  return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nand then we add the reassignment\n```\nx := x + 1\nlet jp (x!1) := return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nNote that we created a fresh variable `x!1` to avoid accidental name capture.\nAs another example, consider\n```\nprint x;\nlet x := 10\ny := y + 1;\nreturn x;\n```\nWe transform it into\n```\nlet jp (y x!1) := return x!1;\nprint x;\nlet x := 10\ny := y + 1;\njmp jp y x\n```\nand then we add the reassignment as in the previous example.\nWe need to include `y` in the jump, because each exit point is implicitly returning the set of\nupdate variables.\n\nWe implement the method as follows. Let `us` be `c.uvars`, then\n1- for each `return _ y` in `c`, we create a join point\n  `let j (us y!1) := return y!1`\n   and replace the `return _ y` with `jmp us y`\n2- for each `break`, we create a join point\n  `let j (us) := break`\n   and replace the `break` with `jmp us`.\n3- Same as 2 for `continue`.\n-/\ndef pullExitPoints (c : Code) : TermElabM Code := do\n  if hasExitPoint c then\n    let (c, jpDecls) \u2190 (pullExitPointsAux {} c).run #[]\n    return attachJPs jpDecls c\n  else\n    return c\n\npartial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code :=\n  let rec update : Code \u2192 TermElabM Code\n    | Code.joinpoint j ps b k          => return Code.joinpoint j ps (\u2190 update b) (\u2190 update k)\n    | Code.seq e k                     => return Code.seq e (\u2190 update k)\n    | c@(Code.\u00abmatch\u00bb ref g ds t alts) => do\n      if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then\n        -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 update alt.rhs) })\n    | Code.ite ref none o c t e => return Code.ite ref none o c (\u2190 update t) (\u2190 update e)\n    | c@(Code.ite ref (some h) o cond t e) => do\n      if ws.contains h.getId then\n        -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.ite ref (some h) o cond (\u2190 update t) (\u2190 update e)\n    | Code.reassign xs stx k => return Code.reassign xs stx (\u2190 update k)\n    | c@(Code.decl xs stx k) => do\n      if xs.any fun x => ws.contains x.getId then\n        -- One the declared variables is shadowing a variable in `ws`\n        pullExitPoints c\n      else\n        return Code.decl xs stx (\u2190 update k)\n    | c => return  c\n  update c\n\n/-\nExtend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.\nWe **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.\nSee discussion at `pullExitPoints`.\n-/\npartial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do\n  if ws.any fun x _ => !c.uvars.contains x then\n    -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)\n    pure { code := (\u2190 extendUpdatedVarsAux c.code ws), uvars := ws }\n  else\n    pure { c with uvars := ws }\n\nprivate def union (s\u2081 s\u2082 : VarSet) : VarSet :=\n  s\u2081.fold (\u00b7.insert \u00b7) s\u2082\n\n/-\nGiven two code blocks `c\u2081` and `c\u2082`, make sure they have the same set of updated variables.\nLet `ws` the union of the updated variables in `c\u2081\u2035 and \u2035c\u2082`.\nWe use `extendUpdatedVars c\u2081 ws` and `extendUpdatedVars c\u2082 ws`\n-/\ndef homogenize (c\u2081 c\u2082 : CodeBlock) : TermElabM (CodeBlock \u00d7 CodeBlock) := do\n  let ws := union c\u2081.uvars c\u2082.uvars\n  let c\u2081 \u2190 extendUpdatedVars c\u2081 ws\n  let c\u2082 \u2190 extendUpdatedVars c\u2082 ws\n  pure (c\u2081, c\u2082)\n\n/-\nExtending code blocks with variable declarations: `let x : t := v` and `let x : t \u2190 v`.\nWe remove `x` from the collection of updated varibles.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `let (x, y) := t`\n-/\ndef mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := {\n  code := Code.decl xs stx c.code,\n  uvars := eraseVars c.uvars xs\n}\n\n/-\nExtending code blocks with reassignments: `x : t := v` and `x : t \u2190 v`.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `(x, y) \u2190 t`\n-/\ndef mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do\n  let us := c.uvars\n  let ws := insertVars us xs\n  -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.\n  -- See discussion at `pullExitPoints`\n  let code \u2190 if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code\n  pure { code := Code.reassign xs stx code, uvars := ws }\n\ndef mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=\n  { c with code := Code.seq action c.code }\n\ndef mkTerminalAction (action : Syntax) : CodeBlock :=\n  { code := Code.action action }\n\ndef mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=\n  { code := Code.\u00abreturn\u00bb ref val }\n\ndef mkBreak (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abbreak\u00bb ref }\n\ndef mkContinue (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abcontinue\u00bb ref }\n\ndef mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do\n  let x? := optIdent.getOptional?\n  let (thenBranch, elseBranch) \u2190 homogenize thenBranch elseBranch\n  pure {\n    code  := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,\n    uvars := thenBranch.uvars,\n  }\n\nprivate def mkUnit : MacroM Syntax :=\n  ``((\u27e8\u27e9 : PUnit))\n\nprivate def mkPureUnit : MacroM Syntax :=\n  ``(pure PUnit.unit)\n\ndef mkPureUnitAction : MacroM CodeBlock := do\n  return mkTerminalAction (\u2190 mkPureUnit)\n\ndef mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do\n  let thenBranch \u2190 mkPureUnitAction\n  pure { c with code := Code.ite (\u2190 getRef) none mkNullNode cond thenBranch.code c.code }\n\ndef mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do\n  -- nary version of homogenize\n  let ws := alts.foldl (union \u00b7 \u00b7.rhs.uvars) {}\n  let alts \u2190 alts.mapM fun alt => do\n    let rhs \u2190 extendUpdatedVars alt.rhs ws\n    return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }\n  return { code := Code.\u00abmatch\u00bb ref genParam discrs optMotive alts, uvars := ws }\n\n/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.\n   This method assumes `terminal` is a terminal -/\ndef concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do\n  unless hasTerminalAction terminal.code do\n    throwErrorAt kRef \"'do' element is unreachable\"\n  let (terminal, k) \u2190 homogenize terminal k\n  let xs := varSetToArray k.uvars\n  let y \u2190 match y? with | some y => pure y | none => `(y)\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (y, false)\n  let jpDecl \u2190 mkFreshJP ps k.code\n  let jp := jpDecl.name\n  let terminal \u2190 liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs\n  return { code  := attachJP jpDecl terminal, uvars := k.uvars }\n\ndef getLetIdDeclVar (letIdDecl : Syntax) : Var :=\n  letIdDecl[0]\n\n-- support both regular and syntax match\ndef getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) :=\n  getPatternVars pattern <|>\n  Quotation.getPatternVars pattern\n\ndef getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) :=\n  getPatternsVars patterns <|>\n  Quotation.getPatternsVars patterns\n\ndef getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do\n  let pattern := letPatDecl[0]\n  getPatternVarsEx pattern\n\ndef getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var :=\n  letEqnsDecl[0]\n\ndef getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do\n  let arg := letDecl[0]\n  if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n    return #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then\n    return #[getLetEqnsDeclVar arg]\n  else\n    throwError \"unexpected kind of let declaration\"\n\ndef getDoLetVars (doLet : Syntax) : TermElabM (Array Var) :=\n  -- leading_parser \"let \" >> optional \"mut \" >> letDecl\n  getLetDeclVars doLet[2]\n\ndef getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var :=\n  if optIdent.isNone then\n    `(this)\n  else\n    pure optIdent[0]\n\ndef getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do\n  -- doHave := leading_parser \"have \" >> Term.haveDecl\n  -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl\n  let arg := doHave[1][0]\n  if arg.getKind == ``Lean.Parser.Term.haveIdDecl then\n    -- haveIdDecl := leading_parser atomic (haveIdLhs >> \" := \") >> termParser\n    -- haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType\n    return #[\u2190 getHaveIdLhsVar arg[0]]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Lean.Parser.Term.haveEqnsDecl then\n    -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts\n    return #[\u2190 getHaveIdLhsVar arg[0]]\n  else\n    throwError \"unexpected kind of have declaration\"\n\ndef getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do\n  -- letRecDecls is an array of `(group (optional attributes >> letDecl))`\n  let letRecDecls := doLetRec[1][0].getSepArgs\n  let letDecls := letRecDecls.map fun p => p[2]\n  let mut allVars := #[]\n  for letDecl in letDecls do\n    let vars \u2190 getLetDeclVars letDecl\n    allVars := allVars ++ vars\n  return allVars\n\n-- ident >> optType >> leftArrow >> termParser\ndef getDoIdDeclVar (doIdDecl : Syntax) : Var :=\n  doIdDecl[0]\n\n-- termParser >> leftArrow >> termParser >> optional (\" | \" >> termParser)\ndef getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do\n  let pattern := doPatDecl[0]\n  getPatternVarsEx pattern\n\n-- leading_parser \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\ndef getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do\n  let decl := doLetArrow[2]\n  if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n    return #[getDoIdDeclVar decl]\n  else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n    getDoPatDeclVars decl\n  else\n    throwError \"unexpected kind of 'do' declaration\"\n\ndef getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do\n  let arg := doReassign[0]\n  if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n    return #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else\n    throwError \"unexpected kind of reassignment\"\n\ndef mkDoSeq (doElems : Array Syntax) : Syntax :=\n  mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]\n\ndef mkSingletonDoSeq (doElem : Syntax) : Syntax :=\n  mkDoSeq #[doElem]\n\n/-\n  If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s.  -/\nprivate def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with\n  | `(doElem|if $_:doIfProp then $_ else $_) => pure none\n  | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do\n    let mut e      := e?.getD (\u2190 `(doSeq|pure PUnit.unit))\n    let mut eIsSeq := true\n    for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do\n      e \u2190 if eIsSeq then pure e else `(doSeq|$e:doElem)\n      e \u2190 withRef cond <| match cond with\n        | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)\n        | `(doIfCond|let $pat \u2190 $d)  => `(doElem| match%$i \u2190 $d    with | $pat:term => $t | _ => $e)\n        | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)\n        | _                          => `(doElem| if%$i $(Syntax.missing) then $t else $e)\n      eIsSeq := false\n    return some e\n  | _ => pure none\n\nstructure DoIfView where\n  ref        : Syntax\n  optIdent   : Syntax\n  cond       : Syntax\n  thenBranch : Syntax\n  elseBranch : Syntax\n\n/- This method assumes `expandDoIf?` is not applicable. -/\nprivate def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do\n  pure {\n    ref        := doIf,\n    optIdent   := doIf[1][0],\n    cond       := doIf[1][1],\n    thenBranch := doIf[3],\n    elseBranch := doIf[5][1]\n  }\n\nprivate def mkTuple (elems : Array Syntax) : MacroM Syntax := do\n  if elems.size == 0 then\n    mkUnit\n  else if elems.size == 1 then\n    return elems[0]!\n  else\n    elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple =>\n      ``(Prod.mk $elem $tuple)\n\n/- Return `some action` if `doElem` is a `doExpr <action>`-/\ndef isDoExpr? (doElem : Syntax) : Option Syntax :=\n  if doElem.getKind == ``Lean.Parser.Term.doExpr then\n    some doElem[0]\n  else\n    none\n\n/--\n  Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term\n  ```\n  let a_1     := x.1\n  let x       := x.2\n  let a_2     := x.1\n  let x       := x.2\n  ...\n  let a_n     := x.1\n  let a_{n+1} := x.2\n  body\n  ```\n  Special cases\n  - `uvars := #[]` => `body`\n  - `uvars := #[a]` => `let a := x; body`\n\n\n  We use this method when expanding the `for-in` notation.\n-/\nprivate def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n  if uvars.size == 0 then\n    return body\n  else if uvars.size == 1 then\n    `(let $(uvars[0]!):ident := $x; $body)\n  else\n    destruct uvars.toList x body\nwhere\n  destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n    match as with\n      | [a, b]  => `(let $a:ident := $x.1; let $b:ident := $x.2; $body)\n      | a :: as => withFreshMacroScope do\n        let rest \u2190 destruct as (\u2190 `(x)) body\n        `(let $a:ident := $x.1; let x := $x.2; $rest)\n      | _ => unreachable!\n\n/-\nThe procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.\nWe use this method to convert\n1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of\n   `CodeBlock` never contains `break` nor `continue`. Moreover, the collection\n   of updated variables is not packed into the result.\n   Thus, we have two kinds of exit points\n     - `Code.action e` which is converted into `e`\n     - `Code.return _ e` which is converted into `pure e`\n\n   We use `Kind.regular` for this case.\n\n2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate\n   a `Syntax` term representing a function for the `xs.forIn` combinator.\n\n   a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term\n      has type `m (ForInStep (Option \u03b1 \u00d7 \u03c3))`, where `a : \u03b1`, and the `\u03c3` is the type\n      of the tuple of variables reassigned by `b`.\n      We use `Kind.forInWithReturn` for this case\n\n   b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated\n      `Syntax` term has type `m (ForInStep \u03c3)`.\n      We use `Kind.forIn` for this case.\n\n3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).\n\n   The generated `Syntax` term for `c` must inform whether `c` \"exited\" using `Code.action`, `Code.return`,\n   `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.\n   For example, the auxiliary type `DoResultPBC \u03b1 \u03c3` is used for a code block that exits with `Code.action`,\n   **and** `Code.break`/`Code.continue`, `\u03b1` is the type of values produced by the exit `action`, and\n   `\u03c3` is the type of the tuple of reassigned variables.\n   The type `DoResult \u03b1 \u03b2 \u03c3` is usedf for code blocks that exit with\n   `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `\u03b2` is the type of the returned values.\n   We don't use `DoResult \u03b1 \u03b2 \u03c3` for all cases because:\n\n      a) The elaborator would not be able to infer all type parameters without extra annotations. For example,\n         if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `\u03b2`.\n\n      b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),\n         but we don't want to consider \"unreachable\" cases.\n\n   We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.\n\n   When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,\n   and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.\n\n   - `a`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n\n   - `r`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n           Note that the code that pattern matches on the result will behave differently in this case.\n           It produces `return a` for this case, and `pure a` for the previous one.\n\n   - `b/c`: `Kind.nestedBC`, type `m (DoResultBC \u03c3)`\n\n   - `a` and `r`:   `Kind.nestedPR`, type `m (DoResultPR \u03b1 \u03b2 \u03c3)`\n\n   - `a` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n\n   - `r` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n         Again the code that pattern matches on the result will behave differently in this case and\n         the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for\n         this case, and `pure a` for the previous case.\n\n   - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC \u03b1 \u03b2 \u03c3)`\n\nHere is the recipe for adding new combinators with nested `do`s.\nExample: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m \u03b1 \u2192 m \u03b1`\n1- Convert `doSeq` into `codeBlock : CodeBlock`\n2- Create term `term` using `mkNestedTerm code m uvars a r bc` where\n   `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,\n   `m` is a `Syntax` representing the Monad, and\n   `a` is true if `code` contains `Code.action _`,\n   `r` is true if `code` contains `Code.return _ _`,\n   `bc` is true if `code` contains `Code.break _` or `Code.continue _`.\n\n   Remark: for combinators such as `repeat` that take a single `doSeq`, all\n   arguments, but `m`, are extracted from `codeBlock`.\n3- Create the term `repeat $term`\n4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`\n\n-/\nnamespace ToTerm\n\ninductive Kind where\n  | regular\n  | forIn\n  | forInWithReturn\n  | nestedBC\n  | nestedPR\n  | nestedSBC\n  | nestedPRBC\n\ninstance : Inhabited Kind := \u27e8Kind.regular\u27e9\n\ndef Kind.isRegular : Kind \u2192 Bool\n  | Kind.regular => true\n  | _            => false\n\nstructure Context where\n  /-- Syntax to reference the monad associated with the do notation. -/\n  m          : Syntax\n  /-- Syntax to reference the result of the monadic computation performed by the do notation. -/\n  returnType : Syntax\n  uvars      : Array Var\n  kind       : Kind\n\nabbrev M := ReaderT Context MacroM\n\ndef mkUVarTuple : M Syntax := do\n  let ctx \u2190 read\n  mkTuple ctx.uvars\n\ndef returnToTerm (val : Syntax) : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (Prod.mk $val $u))\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (Prod.mk (some $val) $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Pure.pure (DoResultPR.\u00abreturn\u00bb $val $u))\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abpureReturn\u00bb $val $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abreturn\u00bb $val $u))\n\ndef continueToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (Prod.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abcontinue\u00bb $u))\n\ndef breakToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (Prod.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abbreak\u00bb $u))\n\ndef actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  let m := ctx.m\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then pure action else ``(HBind.hBind (m := $m) (n := $m) $action fun y => Pure.pure (Prod.mk y $u))\n  | Kind.forIn           => ``(HBind.hBind (m := $m) (n := $m) $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(HBind.hBind (m := $m) (n := $m) $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (Prod.mk none $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(HBind.hBind (m := $m) (n := $m) $action fun y => (Pure.pure (DoResultPR.\u00abpure\u00bb y $u)))\n  | Kind.nestedSBC       => ``(HBind.hBind (m := $m) (n := $m) $action fun y => (Pure.pure (DoResultSBC.\u00abpureReturn\u00bb y $u)))\n  | Kind.nestedPRBC      => ``(HBind.hBind (m := $m) (n := $m) $action fun y => (Pure.pure (DoResultPRBC.\u00abpure\u00bb y $u)))\n\ndef seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  if action.getKind == ``Lean.Parser.Term.doDbgTrace then\n    let msg := action[1]\n    `(dbg_trace $msg; $k)\n  else if action.getKind == ``Lean.Parser.Term.doAssert then\n    let cond := action[1]\n    `(assert! $cond; $k)\n  else\n    let m := (\u2190read).m\n    let action \u2190 withRef action ``(($action : $m PUnit))\n    ``(HBind.hBind (m := $m) (n := $m) $action (fun (_ : PUnit) => $k))\n\ndef declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do\n  let kind := decl.getKind\n  if kind == ``Lean.Parser.Term.doLet then\n    let letDecl := decl[2]\n    `(let $letDecl:letDecl; $k)\n  else if kind == ``Lean.Parser.Term.doLetRec then\n    let letRecToken := decl[0]\n    let letRecDecls := decl[1]\n    return mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]\n  else if kind == ``Lean.Parser.Term.doLetArrow then\n    let arg := decl[2]\n    if arg.getKind == ``Lean.Parser.Term.doIdDecl then\n      let id     := arg[0]\n      let type   := expandOptType id arg[1]\n      let doElem := arg[3]\n      -- `doElem` must be a `doExpr action`. See `doLetArrowToCode`\n      match isDoExpr? doElem with\n      | some action =>\n        let m := (\u2190read).m\n        let action \u2190 withRef action `(($action : $m $type))\n        ``(HBind.hBind (m := $m) (n := $m) $action (fun ($id:ident : $type) => $k))\n      | none        => Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n    else\n      Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n  else if kind == ``Lean.Parser.Term.doHave then\n    -- The `have` term is of the form  `\"have \" >> haveDecl >> optSemicolon termParser`\n    let args := decl.getArgs\n    let args := args ++ #[mkNullNode /- optional ';' -/, k]\n    return mkNode `Lean.Parser.Term.\u00abhave\u00bb args\n  else\n    Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n\ndef reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do\n  match reassign with\n  | `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote \"invalid reassignment, value\") $rhs; $k)\n  | `(doElem| $e:term  := $rhs) => `(let $e:term  := ensure_type_of% $e $(quote \"invalid reassignment, value\") $rhs; $k)\n  | _ =>\n    -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode\n    Macro.throwErrorAt reassign \"unexpected kind of 'do' reassignment\"\n\ndef mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do\n  if optIdent.isNone then\n    ``(if $cond then $thenBranch else $elseBranch)\n  else\n    let h := optIdent[0]\n    ``(if $h:ident : $cond then $thenBranch else $elseBranch)\n\ndef mkJoinPoint (j : Name) (ps : Array (Syntax \u00d7 Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do\n  let pTypes \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => do if useTypeOf then `(type_of% $id) else `(_)\n  let ps     := ps.map (\u00b7.1)\n  /-\n  We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.\n  By elaborating `$k` first, we \"learn\" more about `$body`'s type.\n  For example, consider the following example `do` expression\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x > 0 then\n    IO.println \"x is not zero\" -- Error is here\n  IO.mkRef true\n  ```\n  it is expanded into\n  ```\n  def f (x : Nat) : IO Unit := do\n  let jp (u : Unit) : IO _ :=\n    IO.mkRef true;\n  if x > 0 then\n    IO.println \"not zero\"\n    jp ()\n  else\n    jp ()\n  ```\n  If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit \u2192 IO (IO.Ref Bool)`.\n  Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit \u2192 IO Unit`.\n  Then, we get the expected type mismatch error at `IO.mkRef true`. -/\n  `(let_delayed $(\u2190 mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((\u2190 read).m) _ := $body; $k)\n\ndef mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=\n  Syntax.mkApp (mkIdentFrom ref j) args\n\npartial def toTerm (c : Code) : M Syntax := do\n  match c with\n  | Code.return ref val     => withRef ref <| returnToTerm val\n  | Code.continue ref       => withRef ref continueToTerm\n  | Code.break ref          => withRef ref breakToTerm\n  | Code.action e           => actionTerminalToTerm e\n  | Code.joinpoint j ps b k => mkJoinPoint j ps (\u2190 toTerm b) (\u2190 toTerm k)\n  | Code.jmp ref j args     => return mkJmp ref j args\n  | Code.decl _ stx k       => declToTerm stx (\u2190 toTerm k)\n  | Code.reassign _ stx k   => reassignToTerm stx (\u2190 toTerm k)\n  | Code.seq stx k          => seqToTerm stx (\u2190 toTerm k)\n  | Code.ite ref _ o c t e  => withRef ref <| do mkIte o c (\u2190 toTerm t) (\u2190 toTerm e)\n  | Code.\u00abmatch\u00bb ref genParam discrs optMotive alts =>\n    let mut termAlts := #[]\n    for alt in alts do\n      let rhs \u2190 toTerm alt.rhs\n      let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref \"|\", mkNullNode #[alt.patterns], mkAtomFrom alt.ref \"=>\", rhs]\n      termAlts := termAlts.push termAlt\n    let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]\n    return mkNode `Lean.Parser.Term.\u00abmatch\u00bb #[mkAtomFrom ref \"match\", genParam, optMotive, discrs, mkAtomFrom ref \"with\", termMatchAlts]\n\ndef run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax :=\n  toTerm code { m, returnType, kind, uvars }\n\n/- Given\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   generate Kind. See comment at the beginning of the `ToTerm` namespace. -/\ndef mkNestedKind (a r bc : Bool) : Kind :=\n  match a, r, bc with\n  | true,  false, false => .regular\n  | false, true,  false => .regular\n  | false, false, true  => .nestedBC\n  | true,  true,  false => .nestedPR\n  | true,  false, true  => .nestedSBC\n  | false, true,  true  => .nestedSBC\n  | true,  true,  true  => .nestedPRBC\n  | false, false, false => unreachable!\n\ndef mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do\n  ToTerm.run code m returnType uvars (mkNestedKind a r bc)\n\n/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.\n   See comment at the beginning of the `ToTerm` namespace.\n\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   The result is a sequence of `doElem` -/\ndef matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do\n  let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)\n  let u \u2190 mkTuple uvars\n  match a, r, bc with\n  | true, false, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do $term:term))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; pure r.1))\n  | false, true, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; return r))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; return r.1))\n  | false, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, false => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPR.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPR.\u00abreturn\u00bb b u => $u:term := u; return b)\n  | true, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; pure a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; return a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPRBC.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPRBC.\u00abreturn\u00bb a u => $u:term := u; return a\n         | DoResultPRBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultPRBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, false, false => unreachable!\n\nend ToTerm\n\ndef isMutableLet (doElem : Syntax) : Bool :=\n  let kind := doElem.getKind\n  (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)\n  &&\n  !doElem[1].isNone\n\nnamespace ToCodeBlock\n\nstructure Context where\n  ref         : Syntax\n  /-- Syntax representing the monad associated with the do notation. -/\n  m           : Syntax\n  /-- Syntax to reference the result of the monadic computation performed by the do notation. -/\n  returnType  : Syntax\n  mutableVars : VarSet := {}\n  insideFor   : Bool := false\n\nabbrev M := ReaderT Context TermElabM\n\ndef withNewMutableVars {\u03b1} (newVars : Array Var) (mutable : Bool) (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x\n\ndef checkReassignable (xs : Array Var) : M Unit := do\n  let throwInvalidReassignment (x : Name) : M Unit :=\n    throwError \"'{x.simpMacroScopes}' cannot be reassigned\"\n  let ctx \u2190 read\n  for x in xs do\n    unless ctx.mutableVars.contains x.getId do\n      throwInvalidReassignment x.getId\n\ndef checkNotShadowingMutable (xs : Array Var) : M Unit := do\n  let throwInvalidShadowing (x : Name) : M Unit :=\n    throwError \"mutable variable '{x.simpMacroScopes}' cannot be shadowed\"\n  let ctx \u2190 read\n  for x in xs do\n    if ctx.mutableVars.contains x.getId then\n      throwInvalidShadowing x.getId\n\ndef withFor {\u03b1} (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => { ctx with insideFor := true }) x\n\nstructure ToForInTermResult where\n  uvars      : Array Var\n  term       : Syntax\n\ndef mkForInBody  (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do\n  let ctx \u2190 read\n  let uvars := forInBody.uvars\n  let uvars := varSetToArray uvars\n  let term \u2190 liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)\n  return \u27e8uvars, term\u27e9\n\ndef ensureInsideFor : M Unit :=\n  unless (\u2190 read).insideFor do\n    throwError \"invalid 'do' element, it must be inside 'for'\"\n\ndef ensureEOS (doElems : List Syntax) : M Unit :=\n  unless doElems.isEmpty do\n    throwError \"must be last element in a 'do' sequence\"\n\nprivate partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax \u2192 StateT (List Syntax) M Syntax\n  | stx@(Syntax.node i k args) =>\n    if liftMethodDelimiter k then\n      return stx\n    else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do\n      if inBinder then\n        throwErrorAt stx \"cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`\"\n      let term := args[1]!\n      let term \u2190 expandLiftMethodAux inQuot inBinder term\n      let auxDoElem : Syntax \u2190 `(doElem| let a \u2190 $term:term)\n      modify fun s => s ++ [auxDoElem]\n      `(a)\n    else do\n      let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot\n      let inBinder   := inBinder || (!inQuot && liftMethodForbiddenBinder stx)\n      let args \u2190 args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)\n      return Syntax.node i k args\n  | stx => return stx\n\ndef expandLiftMethod (doElem : Syntax) : M (List Syntax \u00d7 Syntax) := do\n  if !hasLiftMethod doElem then\n    return ([], doElem)\n  else\n    let (doElem, doElemsNew) \u2190 (expandLiftMethodAux false false doElem).run []\n    return (doElemsNew, doElem)\n\ndef checkLetArrowRHS (doElem : Syntax) : M Unit := do\n  let kind := doElem.getKind\n  if kind == ``Lean.Parser.Term.doLetArrow ||\n     kind == ``Lean.Parser.Term.doLet ||\n     kind == ``Lean.Parser.Term.doLetRec ||\n     kind == ``Lean.Parser.Term.doHave ||\n     kind == ``Lean.Parser.Term.doReassign ||\n     kind == ``Lean.Parser.Term.doReassignArrow then\n    throwErrorAt doElem \"invalid kind of value '{kind}' in an assignment\"\n\n/- Generate `CodeBlock` for `doReturn` which is of the form\n   ```\n   \"return \" >> optional termParser\n   ```\n   `doElems` is only used for sanity checking. -/\ndef doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do\n  ensureEOS doElems\n  let argOpt := doReturn[1]\n  let arg \u2190 if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]\n  return mkReturn (\u2190 getRef) arg\n\nstructure Catch where\n  x         : Syntax\n  optType   : Syntax\n  codeBlock : CodeBlock\n\ndef getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet :=\n  let ws := tryCode.uvars\n  let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws\n  let ws := match finallyCode? with\n    | none   => ws\n    | some c => union c.uvars ws\n  ws\n\ndef tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code \u2192 Bool) : Bool :=\n  p tryCode.code ||\n  catches.any (fun \u00abcatch\u00bb => p \u00abcatch\u00bb.codeBlock.code) ||\n  match finallyCode? with\n  | none => false\n  | some finallyCode => p finallyCode.code\n\nmutual\n  /- \"Concatenate\" `c` with `doSeqToCode doElems` -/\n  partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=\n    match doElems with\n    | [] => pure c\n    | nextDoElem :: _  => do\n      let k \u2190 doSeqToCode doElems\n      let ref := nextDoElem\n      concat c ref none k\n\n  /- Generate `CodeBlock` for `doLetArrow; doElems`\n     `doLetArrow` is of the form\n     ```\n     \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\n     ```\n     where\n     ```\n     def doIdDecl   := leading_parser ident >> optType >> leftArrow >> doElemParser\n     def doPatDecl  := leading_parser termParser >> leftArrow >> doElemParser >> optional (\" | \" >> doElemParser)\n     ```\n  -/\n  partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let decl    := doLetArrow[2]\n    if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n      let y := decl[0]\n      checkNotShadowingMutable #[y]\n      let doElem := decl[3]\n      let k \u2190 withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)\n      match isDoExpr? doElem with\n      | some _      => return mkVarDeclCore #[y] doLetArrow k\n      | none =>\n        checkLetArrowRHS doElem\n        let c \u2190 doSeqToCode [doElem]\n        match doElems with\n        | []       => pure c\n        | kRef::_  => concat c kRef y k\n    else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 if isMutableLet doLetArrow then\n          `(do let discr \u2190 $doElem; let mut $pattern:term := discr)\n        else\n          `(do let discr \u2190 $doElem; let $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        if isMutableLet doLetArrow then\n          throwError \"'mut' is currently not supported in let-decls with 'else' case\"\n        let contSeq := mkDoSeq doElems.toArray\n        let elseSeq := mkSingletonDoSeq optElse[1]\n        let auxDo \u2190 `(do let discr \u2190 $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n    else\n      throwError \"unexpected kind of 'do' declaration\"\n\n  partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    -- \"let \" >> termParser >> \" := \" >> termParser >> checkColGt >> \" | \" >> doElemParser\n    let pattern := doLetElse[1]\n    let val     := doLetElse[3]\n    let elseSeq := mkSingletonDoSeq doLetElse[5]\n    let contSeq := mkDoSeq doElems.toArray\n    let auxDo \u2190 `(do let discr := $val; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n    doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n\n  /- Generate `CodeBlock` for `doReassignArrow; doElems`\n     `doReassignArrow` is of the form\n     ```\n     (doIdDecl <|> doPatDecl)\n     ```\n  -/\n  partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let decl := doReassignArrow[0]\n    if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n      let doElem := decl[3]\n      let y      := decl[0]\n      let auxDo \u2190 `(do let r \u2190 $doElem; $y:ident := r)\n      doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n    else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 `(do let discr \u2190 $doElem; $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        throwError \"reassignment with `|` (i.e., \\\"else clause\\\") is not currently supported\"\n    else\n      throwError \"unexpected kind of 'do' reassignment\"\n\n  /- Generate `CodeBlock` for `doIf; doElems`\n     `doIf` is of the form\n     ```\n     \"if \" >> optIdent >> termParser >> \" then \" >> doSeq\n      >> many (group (try (group (\" else \" >> \" if \")) >> optIdent >> termParser >> \" then \" >> doSeq))\n      >> optional (\" else \" >> doSeq)\n     ```  -/\n  partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let view \u2190 liftMacroM $ mkDoIfView doIf\n    let thenBranch \u2190 doSeqToCode (getDoSeqElems view.thenBranch)\n    let elseBranch \u2190 doSeqToCode (getDoSeqElems view.elseBranch)\n    let ite \u2190 mkIte view.ref view.optIdent view.cond thenBranch elseBranch\n    concatWith ite doElems\n\n  /- Generate `CodeBlock` for `doUnless; doElems`\n     `doUnless` is of the form\n     ```\n     \"unless \" >> termParser >> \"do \" >> doSeq\n     ```  -/\n  partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do\n    let cond  := doUnless[1]\n    let doSeq := doUnless[3]\n    let body \u2190 doSeqToCode (getDoSeqElems doSeq)\n    let unlessCode \u2190 liftMacroM <| mkUnless cond body\n    concatWith unlessCode doElems\n\n  /- Generate `CodeBlock` for `doFor; doElems`\n     `doFor` is of the form\n     ```\n     def doForDecl := leading_parser termParser >> \" in \" >> withForbidden \"do\" termParser\n     def doFor := leading_parser \"for \" >> sepBy1 doForDecl \", \" >> \"do \" >> doSeq\n     ```\n  -/\n  partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let doForDecls := doFor[1].getSepArgs\n    if doForDecls.size > 1 then\n      /-\n        Expand\n        ```\n        for x in xs, y in ys do\n          body\n        ```\n        into\n        ```\n        let s := toStream ys\n        for x in xs do\n          match Stream.next? s with\n          | none => break\n          | some (y, s') =>\n            s := s'\n            body\n        ```\n      -/\n      -- Extract second element\n      let doForDecl := doForDecls[1]!\n      unless doForDecl[0].isNone do\n        throwErrorAt doForDecl[0] \"the proof annotation here has not been implemented yet\"\n      let y  := doForDecl[1]\n      let ys := doForDecl[3]\n      let doForDecls := doForDecls.eraseIdx 1\n      let body := doFor[3]\n      withFreshMacroScope do\n        /- Recall that `@` (explicit) disables `coeAtOutParam`.\n           We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/\n        let toStreamApp \u2190 withRef ys `(@toStream _ _ _ $ys)\n        let auxDo \u2190\n          `(do let mut s := $toStreamApp:term\n               for $doForDecls:doForDecl,* do\n                 match @Stream.next? _ _ _ s with\n                 | none => break\n                 | some ($y, s') =>\n                   s := s'\n                   do $body)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n    else withRef doFor do\n      let h?        := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0]\n      let x         := doForDecls[0]![1]\n      withRef x <| checkNotShadowingMutable (\u2190 getPatternVarsEx x)\n      let xs        := doForDecls[0]![3]\n      let forElems  := getDoSeqElems doFor[3]\n      let forInBodyCodeBlock \u2190 withFor (doSeqToCode forElems)\n      let \u27e8uvars, forInBody\u27e9 \u2190 mkForInBody x forInBodyCodeBlock\n      let ctx \u2190 read\n      -- semantic no-op that replaces the `uvars`' position information (which all point inside the loop)\n      -- with that of the respective mutable declarations outside the loop, which allows the language\n      -- server to identify them as conceptually identical variables\n      let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v\n      let uvarsTuple \u2190 liftMacroM do mkTuple uvars\n      if hasReturn forInBodyCodeBlock.code then\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let optType \u2190 `(Option $((\u2190 read).returnType))\n        let forInTerm \u2190 if let some h := h? then\n          `(for_in'% $(xs) (Prod.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody)\n        else\n          `(for_in% $(xs) (Prod.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => let r := r.2; $forInBody)\n        let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                         $uvarsTuple:term := r.2;\n                         match r.1 with\n                         | none => Pure.pure (ensure_expected_type% \"type mismatch, 'for'\" PUnit.unit)\n                         | some a => return ensure_expected_type% \"type mismatch, 'for'\" a)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n      else\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 if let some h := h? then\n          `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody)\n        else\n          `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)\n        if doElems.isEmpty then\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                           $uvarsTuple:term := r;\n                           Pure.pure (ensure_expected_type% \"type mismatch, 'for'\" PUnit.unit))\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n        else\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term; $uvarsTuple:term := r)\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n\n  /-- Generate `CodeBlock` for `doMatch; doElems` -/\n  partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref       := doMatch\n    let genParam  := doMatch[1]\n    let optMotive := doMatch[2]\n    let discrs    := doMatch[3]\n    let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`\n    let matchAlts \u2190 matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (\u2190 liftMacroM <| expandMatchAlt matchAlt)\n    let alts \u2190  matchAlts.mapM fun matchAlt => do\n      let patterns := matchAlt[1][0]\n      let vars \u2190 getPatternsVarsEx patterns.getSepArgs\n      withRef patterns <| checkNotShadowingMutable vars\n      let rhs  := matchAlt[3]\n      let rhs \u2190 doSeqToCode (getDoSeqElems rhs)\n      pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }\n    let matchCode \u2190 mkMatch ref genParam discrs optMotive alts\n    concatWith matchCode doElems\n\n  /--\n    Generate `CodeBlock` for `doTry; doElems`\n    ```\n    def doTry := leading_parser \"try \" >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally\n    def doCatch      := leading_parser \"catch \" >> binderIdent >> optional (\":\" >> termParser) >> darrow >> doSeq\n    def doCatchMatch := leading_parser \"catch \" >> doMatchAlts\n    def doFinally    := leading_parser \"finally \" >> doSeq\n    ```\n  -/\n  partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let tryCode \u2190 doSeqToCode (getDoSeqElems doTry[1])\n    let optFinally := doTry[3]\n    let catches \u2190 doTry[2].getArgs.mapM fun catchStx : Syntax => do\n      if catchStx.getKind == ``Lean.Parser.Term.doCatch then\n        let x       := catchStx[1]\n        if x.isIdent then\n          withRef x <| checkNotShadowingMutable #[x]\n        let optType := catchStx[2]\n        let c \u2190 doSeqToCode (getDoSeqElems catchStx[4])\n        return { x := x, optType := optType, codeBlock := c : Catch }\n      else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then\n        let matchAlts := catchStx[1]\n        let x \u2190 `(ex)\n        let auxDo \u2190 `(do match ex with $matchAlts)\n        let c \u2190 doSeqToCode (getDoSeqElems (getDoSeq auxDo))\n        return { x := x, codeBlock := c, optType := mkNullNode : Catch }\n      else\n        throwError \"unexpected kind of 'catch'\"\n    let finallyCode? \u2190 if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])\n    if catches.isEmpty && finallyCode?.isNone then\n      throwError \"invalid 'try', it must have a 'catch' or 'finally'\"\n    let ctx \u2190 read\n    let ws    := getTryCatchUpdatedVars tryCode catches finallyCode?\n    let uvars := varSetToArray ws\n    let a     := tryCatchPred tryCode catches finallyCode? hasTerminalAction\n    let r     := tryCatchPred tryCode catches finallyCode? hasReturn\n    let bc    := tryCatchPred tryCode catches finallyCode? hasBreakContinue\n    let toTerm (codeBlock : CodeBlock) : M Syntax := do\n      let codeBlock \u2190 liftM $ extendUpdatedVars codeBlock ws\n      liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m ctx.returnType uvars a r bc\n    let term \u2190 toTerm tryCode\n    let term \u2190 catches.foldlM (init := term) fun term \u00abcatch\u00bb => do\n      let catchTerm \u2190 toTerm \u00abcatch\u00bb.codeBlock\n      if catch.optType.isNone then\n        ``(MonadExcept.tryCatch $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n      else\n        let type := \u00abcatch\u00bb.optType[1]\n        ``(tryCatchThe $type $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n    let term \u2190 match finallyCode? with\n      | none             => pure term\n      | some finallyCode => withRef optFinally do\n        unless finallyCode.uvars.isEmpty do\n          throwError \"'finally' currently does not support reassignments\"\n        if hasBreakContinueReturn finallyCode.code then\n          throwError \"'finally' currently does 'return', 'break', nor 'continue'\"\n        let finallyTerm \u2190 liftMacroM <| ToTerm.run finallyCode.code ctx.m ctx.returnType {} ToTerm.Kind.regular\n        ``(tryFinally $term $finallyTerm)\n    let doElemsNew \u2190 liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc\n    doSeqToCode (doElemsNew ++ doElems)\n\n  partial def doSeqToCode : List Syntax \u2192 M CodeBlock\n    | [] => do liftMacroM mkPureUnitAction\n    | doElem::doElems => withIncRecDepth <| withRef doElem do\n      checkMaxHeartbeats \"'do'-expander\"\n      match (\u2190 liftMacroM <| expandMacro? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n      match (\u2190 liftMacroM <| expandDoIf? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n        let (liftedDoElems, doElem) \u2190 expandLiftMethod doElem\n        if !liftedDoElems.isEmpty then\n          doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)\n        else\n          let ref := doElem\n          let k := doElem.getKind\n          if k == ``Lean.Parser.Term.doLet then\n            let vars \u2190 getDoLetVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doHave then\n            let vars \u2190 getDoHaveVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doLetRec then\n            let vars \u2190 getDoLetRecVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doReassign then\n            let vars \u2190 getDoReassignVars doElem\n            checkReassignable vars\n            let k \u2190 doSeqToCode doElems\n            mkReassignCore vars doElem k\n          else if k == ``Lean.Parser.Term.doLetArrow then\n            doLetArrowToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doLetElse then\n            doLetElseToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doReassignArrow then\n            doReassignArrowToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doIf then\n            doIfToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doUnless then\n            doUnlessToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do\n            doForToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doMatch then\n            doMatchToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doTry then\n            doTryToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doBreak then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkBreak ref\n          else if k == ``Lean.Parser.Term.doContinue then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkContinue ref\n          else if k == ``Lean.Parser.Term.doReturn then\n            doReturnToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doDbgTrace then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doAssert then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doNested then\n            let nestedDoSeq := doElem[1]\n            doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)\n          else if k == ``Lean.Parser.Term.doExpr then\n            let term := doElem[0]\n            if doElems.isEmpty then\n              return mkTerminalAction term\n            else\n              return mkSeq term (\u2190 doSeqToCode doElems)\n          else\n            throwError \"unexpected do-element of kind {doElem.getKind}:\\n{doElem}\"\nend\n\ndef run (doStx : Syntax) (m : Syntax) (returnType : Syntax) : TermElabM CodeBlock :=\n  (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType }\n\nend ToCodeBlock\n\n/- HBind: The elaborator for `do` aliases the monad through a metavariable to\n   embed its `Term` into `Syntax`. But metavariables can't be universe\n   polymorphic, so we instead hack and create a quantified external definition,\n   then return the name of that definition. -/\nprivate def mkMonadAlias (m : Expr) : TermElabM Syntax := do\n  let levelParams := collectLevelParams {} m |>.params\n  let mType \u2190 inferType m\n  let name \u2190 mkFreshUserName `hdoMonadAlias\n  let decl := Declaration.defnDecl {\n      name := name, levelParams := levelParams.toList, type := mType,\n      value := m, hints := ReducibilityHints.abbrev,\n      safety := DefinitionSafety.safe\n  }\n  ensureNoUnassignedMVars decl\n  addAndCompile decl\n  Term.applyAttributes name #[{ name := `inline }, { name := `reducible }]\n  return mkIdent name\n\n-- HDO: This elaborates like the normal do command (but with Prod/HBind)\n@[termElab \u00abhdo\u00bb] def elabHDo : TermElab := fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  let bindInfo \u2190 extractBind expectedType?\n  let bindInfo \u2190 generalizeBindUniverse bindInfo\n  let m \u2190 mkMonadAlias bindInfo.m\n  let returnType \u2190 Term.exprToSyntax bindInfo.returnType\n  let codeBlock \u2190 ToCodeBlock.run stx m returnType\n  let stxNew \u2190 liftMacroM <| ToTerm.run codeBlock.code m returnType\n  trace[Elab.do] stxNew\n  withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType\n\n-- HDO: Variation with additional information for testing\n@[termElab \u00abhdo_2\u00bb] def elabHDo2 : TermElab := fun stx expectedType? => do\n  match stx with\n  | `(hdo (monad := $stx_monad:term) $stx_seq) =>\n      let stx \u2190 `(hdo $stx_seq)\n\n      let monad \u2190 elabTerm stx_monad none\n      trace[Elab.do] s!\"Manually-specified monad: {monad}: {\u2190 inferType monad}\"\n\n      tryPostponeIfNoneOrMVar expectedType?\n      let bindInfo \u2190 extractBind expectedType?\n      let m \u2190 mkMonadAlias monad\n      let returnType \u2190 Term.exprToSyntax bindInfo.returnType\n      let codeBlock \u2190 ToCodeBlock.run stx m returnType\n      let stxNew \u2190 liftMacroM <| ToTerm.run codeBlock.code m returnType\n      trace[Elab.do] stxNew\n      withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType\n\n  | _ => throwError \"unrecognized syntax for hdo_2\"\n\nend HDo\n\nend Lean.Elab.Term\n", "meta": {"author": "lephe", "repo": "lean4-hbind", "sha": "47fe6a8bdda94021d6a9820597190ed6163347b3", "save_path": "github-repos/lean/lephe-lean4-hbind", "path": "github-repos/lean/lephe-lean4-hbind/lean4-hbind-47fe6a8bdda94021d6a9820597190ed6163347b3/HBind/ElabHdo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451645470385745, "lm_q2_score": 0.0229773696591339, "lm_q1q2_score": 0.003780155394740691}}
{"text": "import Lean.Data.HashMap\nimport Lean.Data.HashSet\n\ninstance [BEq \u03b1] [Hashable \u03b1] [Repr \u03b1]: Repr (Lean.HashSet \u03b1) where\n  reprPrec h n := h.toList.repr n\n\ninstance [BEq \u03b1] [Hashable \u03b1] [Repr (\u03b1 \u00d7 \u03b2)]: Repr (Lean.HashMap \u03b1 \u03b2) where\n  reprPrec h n := h.toList.repr n\n\nnamespace MWE1\n\ninductive \u00abEntity\u00bb where\n  | aspect\n    (name: String)\n    (\u00abspecializations\u00bb: List String := List.nil)\n  | concept\n    (name: String)\n    (\u00abspecializations\u00bb: List String := List.nil)\n  deriving Repr\n\ndef \u00abEntity\u00bb.name (e: \u00abEntity\u00bb): String :=\n  match e with\n  | .aspect n _ => n\n  | .concept n _ => n\n\ndef \u00abEntity\u00bb.\u00abspecializations\u00bb (e: \u00abEntity\u00bb): List String :=\n  match e with\n  | .aspect _ s => s\n  | .concept _ s => s\n\nclass \u00abVocabulary\u00bbwhere\n  \u00abownedStatements\u00bb: List \u00abEntity\u00bb\n  deriving Repr\n\ndef v : \u00abVocabulary\u00bb := {\n  ownedStatements := [\n    \u00abEntity\u00bb.aspect \"base:Container\",\n    \u00abEntity\u00bb.concept \"mission:Component\" [ \"base:Container\" ]\n  ]\n}\n\ninductive RDeclarationKind where\n  | rAspect\n  | rConcept\n  deriving BEq, Repr\n\ndef \u00abEntity\u00bb.toKind (e: \u00abEntity\u00bb): 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 \u00abVocabulary\u00bb := .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 \u03b1): 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 \u2192 Name2NamesMap)\n  (update: State \u2192 String \u2192 Names \u2192 State)\n  : M Unit := do\n  let s \u2190 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: \u00abEntity\u00bb): M Unit := do\n  let s \u2190 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 (\u2190 read).vocabularies do\n    for e in v.ownedStatements do\n      validateStatementDeclaration e\n\ndef validateVocabularySpecialization (e: \u00abEntity\u00bb): M Unit := do\n  let s \u2190 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 (\u2190 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  \u2200 a: String, s.aspectSpecializations.contains a \u2192 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  \u2200 (a: String) (sup : String), (s.aspectSpecializations.findD a .empty).contains sup \u2192 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  \u2200 a: String, s.conceptSpecializations.contains a \u2192 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  \u2200 (a: String) (sup : String), (s.conceptSpecializations.findD a .empty).contains sup \u2192 \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 tactic.iconfig\n\nopen tactic\n\nmeta structure a_config :=\n(max_iterations  : \u2115 := 500)\n(max_discovers   : \u2115 := 0)\n(suggest         : list pexpr := [])\n(optimal         : bool := tt)\n(exhaustive      : bool := ff)\n(inflate_rws     : bool := ff)\n(trace           : bool := ff)\n(trace_summary   : bool := ff)\n(trace_rules     : bool := ff)\n(ssss   : string := \"dd\")\n\nrun_cmd (do\n  iconfig.is_valid_config `a_config >>= trace\n)\n\nrun_cmd (do\n  e \u2190 get_env,\n  let n := `a_config,\n  e.structure_fields n >>= list.mmap (iconfig.resolve_field e n),\n\n  skip\n)\n\nmeta instance : has_to_tactic_format a_config := \u27e8\u03bb b, return format!\"{b.max_iterations} : {b.max_discovers}\"\u27e9\n\nsection\n\niconfig_mk my_tac\n\niconfig_add_struct my_tac a_config\n\nend\n\nnamespace tactic\nnamespace interactive\n\nmeta def cfgdump (c : iconfig my_tac) : tactic unit := do\n  r \u2190 iconfig.read c,\n  r.struct `a_config a_config >>= tactic.trace,\n  return ()\n\nend interactive\nend tactic\n\nexample : tt := begin\n  cfgdump {\n    max_iterations := 113,\n    max_discovers := 112\n  },\n\n  simp\nend\n", "meta": {"author": "khoek", "repo": "libiconfig", "sha": "6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5", "save_path": "github-repos/lean/khoek-libiconfig", "path": "github-repos/lean/khoek-libiconfig/libiconfig-6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5/test/struct.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15002881674163046, "lm_q2_score": 0.024798159294690838, "lm_q1q2_score": 0.003720438496352932}}
{"text": "import Contractome.Interfaces\nimport Contractome.Instances\nimport Contractome.EVM\nimport Contractome.UInt256\nimport Std.Data.Stack\nimport Std.Data.RBMap\nimport Contractome.Utils\n\nimport Contractome.ABIEncoding\n\nopen EVM\n\ndef C : Cfg := {\n  S := Std.Stack UInt256\n  BA := ByteArray\n  BAI := ByteArray.Iterator\n\n  M := Std.RBMap UInt256 UInt8 Ord.compare\n  AM := Std.RBMap UInt256 UInt256 Ord.compare\n  BAM := Std.RBMap UInt256 ByteArray Ord.compare\n  STM := Std.RBMap UInt256 (Std.RBMap UInt256 UInt8 Ord.compare) Ord.compare\n  RS := Std.Stack (UInt256 \u00d7 ByteArray)\n  Tw := UInt256\n  Tb := UInt8\n}\n\nderiving instance Repr for Std.Stack\n\n-- instance : Repr ByteArray := \u27e8 fun a _ => byteArrayToHex a \u27e9 \n\n-- #eval UInt64\n\ninstance : Repr C.Tw := (inferInstance : Repr UInt256)\ninstance : Repr C.Tb := (inferInstance : Repr UInt8)\ninstance : Repr C.M := (inferInstance : Repr (Std.RBMap UInt256 UInt8 Ord.compare))\ninstance : Repr C.S := (inferInstance : Repr (Std.Stack UInt256))\ninstance : Repr C.BA := (inferInstance : Repr (ByteArray))\ninstance : Repr C.AM := (inferInstance : Repr (Std.RBMap UInt256 UInt256 Ord.compare))\ninstance : Repr C.BAM := (inferInstance : Repr (Std.RBMap UInt256 ByteArray Ord.compare))\ninstance : Repr C.STM := (inferInstance : Repr (Std.RBMap UInt256 (Std.RBMap UInt256 UInt8 Ord.compare) Ord.compare))\ninstance : Repr C.RS := (inferInstance : Repr (Std.Stack (UInt256 \u00d7 ByteArray)))\n-- deriving instance Repr for TransactionContext\n\ninstance : DecidableEq C.Tw := (inferInstance : DecidableEq UInt256)\ninstance : \u2200 n, OfNat C.Tw n := (inferInstance : \u2200 n, OfNat UInt256 n)\ninstance : Element C.Tw := (inferInstance : Element UInt256)\n\ninstance : DecidableEq C.Tb := (inferInstance : DecidableEq UInt8)\ninstance : \u2200 n, OfNat C.Tb n := (inferInstance : \u2200 n, OfNat UInt8 n)\ninstance : Element C.Tb := (inferInstance : Element UInt8)\ninstance : TakeBytes C.BAI := (inferInstance : TakeBytes ByteArray.Iterator)\ninstance : SByteArray C.Tw C.Tb C.BA C.BAI := (inferInstance : SByteArray UInt256 UInt8 ByteArray ByteArray.Iterator)\n\ninstance : Zero C.M := (inferInstance : Zero (Std.RBMap UInt256 UInt8 Ord.compare))\ninstance : EVMStack C.Tw C.S := (inferInstance : EVMStack UInt256 (Std.Stack UInt256))\ninstance : EVMStack (C.Tw \u00d7 C.BA) C.RS := (inferInstance : EVMStack (UInt256 \u00d7 ByteArray) (Std.Stack (UInt256 \u00d7 ByteArray)))\ninstance : EVMMapDefault C.Tw C.Tw C.AM := (inferInstance : EVMMapDefault UInt256 UInt256 (Std.RBMap UInt256 UInt256 Ord.compare))\ninstance : EVMMapDefault C.Tw C.M C.STM := (inferInstance : EVMMapDefault UInt256 (Std.RBMap UInt256 UInt8 Ord.compare) (Std.RBMap UInt256 (Std.RBMap UInt256 UInt8 Ord.compare) Ord.compare))\ninstance : EVMMapBasic C.Tw C.BA C.BAM := (inferInstance : EVMMapBasic UInt256 ByteArray (Std.RBMap UInt256 ByteArray Ord.compare))\n\ninstance : EVMMapSeq C.Tw C.Tb C.M (BA := C.BA) (BAI := C.BAI) :=\n  (inferInstance : EVMMapSeq UInt256 UInt8 ByteArray ByteArray.Iterator (Std.RBMap UInt256 UInt8 Ord.compare))\n\n-- variable [EVMStack C.Tw C.S] [EVMMap C.Tw C.Tw C.AM] [EVMMapSeq C.Tw C.Tb C.M (instBA := instBA)]\n-- variable [EVMMapBasic C.Tw C.BA C.BAM]\n\n#assert (hexToByteArray! \"604260005260206000F3\") == (hexToByteArray!' \"604260005260206000F3\")\n\ndef basicInput := hexToByteArray!' \"604260005260206000F3\"\n\n\ndef emptySolcInput := hexToByteArray! \"6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220c852edbace7e3c9da7b9e566199d4b7f89d6c7c9e5d1029f0337839e993fa6fa64736f6c63430008070033\"\n\ndef basicSolcInput := hexToByteArray! \"6080604052348015600f57600080fd5b5060405160e338038060e38339818101604052810190602d9190604c565b80600081905550506097565b6000815190506046816083565b92915050565b600060208284031215605f57605e607e565b5b6000606b848285016039565b91505092915050565b6000819050919050565b600080fd5b608a816074565b8114609457600080fd5b50565b603f8060a46000396000f3fe6080604052600080fdfea26469706673582212209c130309b4505633bae9459145bea0f6138a99c38947f11384f39beca020bc9a64736f6c63430008070033\"\ndef basicSolcInputWithArg := basicSolcInput ++ ABIEncodable.abiEncode 123\n\n-- #eval basicSolcInput\n\n#eval basicSolcInput.size\n\ndef initTC (bytecode : ByteArray) : TransactionContext (C:=C) := {\n  address := 0\n  origin := 0\n  caller := 0\n  callvalue := 0\n  balances := Std.rbmapOf [ (0, 5) ] _\n  calldata := ByteArray.empty\n  returnData := Std.Stack.empty\n  codes := Std.rbmapOf [ (0, bytecode) ] _\n}\n\ndef initCC : ChainContext (C:=C) := {\n  gasprice := 0\n  blockhash := 0\n  coinbase := 0\n  timestamp := 0\n  number := 0\n  difficulty := 0\n  gaslimit := 0\n  chainid := 0\n  basefee := 0\n}\n\nabbrev runEvm (v: EVMM (C:=C) \u03b1) (txCtx : TransactionContext (C:=C)) (chCtx : ChainContext (C:=C)) := EVMM.run' (C:=C) v txCtx chCtx\n\n-- #eval EVM.decode basicInput\n-- #eval basicInput\n#eval EVM.decode \u27e8 hexToByteArray! \"604260005260206000F3\", 123 \u27e9 \n\n-- #eval 0x103\n\ndef stepN (n : Nat) : EVMM (C:=C) Unit := match n with\n| 0 => pure ()\n| n+1 => do\n  if (\u2190 EVMM.isDone) then pure () else \n  EVMM.step; stepN n\n\n#eval UInt256.ofBytes! $ hexToByteArray! \"42\"\n-- #eval runEvm (EVMM.getNextInstr) initTC initCC\n\n-- #eval 0x2d\n\n#eval 0x7b\n\n-- TODO note: not work\n\n\n-- def hexToByteArray'(s: String): Option ByteArray := Id.run do\n--   if s.length % 2 != 0 then return none\n--   let mut res := ByteArray.mkEmpty $ s.length / 2\n--   for i in [:((s.length)/2)] do\n--     let v1 := hexChar (s[2*i])\n--     let v2 := hexChar (s[2*i+1])\n--     match (v1, v2) with \n--     | (some v1, some v2) => res := res.push $ \u27e8 (16 * v1) + v2, sorry \u27e9 \n--     | _ => return none\n--   return res\n-- set_option pp.all true\n\n-- def codeInlined : ByteArray := {}\n\nlocal instance : OfNat UInt8 n where\n  -- ofNat := fofNat n\n  ofNat := \u27e8 n % 256, sorry \u27e9\n\n-- #reduce basicInput\nset_option maxRecDepth 2000\n-- #reduce initTC basicInput\n\n\n-- set_option maxRecDepth 10000\n-- #redComp (1 : UInt256)\n\n-- set_option maxRecDepth 10000\n-- #reduce codeInlined\n\n-- local instance : OfNat UInt8 n where\n--   ofNat := \u27e8n % 256, sorry\u27e9\n\nset_option maxHeartbeats 500000\n-- #redComp emptySolcInput\n\n-- #reduce initTC emptySolcInput\n\nconstant a : UInt8\n\n-- #eval b[1, 2]\n\n-- #reduce initTC b[a]\n\n-- theorem test1 (tC : TransactionContext) (cC : ChainContext) := \n\n#reduce runEvm (EVMM.getNextInstr) (initTC basicInput) initCC\n-- #eval runEvm (stepN 116) (initTC basicSolcInputWithArg) initCC", "meta": {"author": "zygi", "repo": "contractome", "sha": "d4d59ce817e47578d8764e26d77050ce72c18c18", "save_path": "github-repos/lean/zygi-contractome", "path": "github-repos/lean/zygi-contractome/contractome-d4d59ce817e47578d8764e26d77050ce72c18c18/Contractome/Concrete2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19682618479782124, "lm_q2_score": 0.018833128754614906, "lm_q1q2_score": 0.0037068528805769946}}
{"text": "import tactic.local_cache\n\nopen tactic\n\ndef do_trace : bool := ff\n\nmeta def trace_cache_regenerating : tactic unit :=\nif do_trace then trace \"(test/local_cache): cache regenerating\" else skip\n\nnamespace block_local\n\nsection example_tactic\n\ndef TEST_NS_1 : name := `my_tactic\ndef TEST_NS_2 : name := `my_other_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace_cache_regenerating,\n   return [1, 2, 3, 4]\n\nmeta def my_tactic : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS_1 generate_some_data,\n   -- Do some stuff with `my_cached_data`\n   skip\n\nmeta def my_other_tactic : tactic unit :=\nrun_once TEST_NS_2 (return [10, 20, 30, 40]) >> skip\n\nend example_tactic\n\n\n\nsection example_usage\n\n-- Note only a single cache regeneration (only a single trace message),\n-- even upon descent to a sub-tactic-block.\nlemma my_lemma : true := begin\n    my_tactic,\n    my_tactic,\n    my_tactic,\n\n    have h : true,\n    { my_tactic,\n      trivial },\n\n    trivial\nend\n\nend example_usage\n\nsection test\n\nmeta def fail_if_cache_miss (ns : name) : tactic unit :=\ndo p \u2190 local_cache.present ns,\n   if p then skip else fail \"cache miss\"\n\nmeta def fail_if_cache_miss_1 : tactic unit :=\nfail_if_cache_miss TEST_NS_1\n\nmeta def fail_if_cache_miss_2 : tactic unit :=\nfail_if_cache_miss TEST_NS_2\n\nend test\n\n-- Test: the cache persists only within a single tactic block\nsection test_scope\n\nstructure dummy :=\n(a b : \u2115)\n\ndef my_definition : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\ndef my_definition' : dummy :=\n \u27e8 begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\nlemma my_lemma' : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\nend test_scope\n\n-- Test: the cache is reliably persistent, decends to sub-blocks,\n-- the api to inspect whether a cache entry is present works, and\n-- the cache can be manually cleared.\nsection test_persistence\n\nlemma my_test_ps : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n\n  my_tactic,\n\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  have h : true,\n  { fail_if_cache_miss_1,\n    trivial },\n\n  -- Manually clear cache\n  local_cache.clear TEST_NS_1,\n  success_if_fail { fail_if_cache_miss_1 },\n\n  trivial\nend\n\nend test_persistence\n\n-- Test: caching under different namespaces doesn't share the\n-- cached state.\nsection test_ns_collison\n\nlemma my_test_ns : true := begin\n  my_tactic,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  my_other_tactic,\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_2,\n\n  local_cache.clear TEST_NS_1,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  my_other_tactic,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  trivial\nend\n\nend test_ns_collison\n\n-- Test: cached results don't leak between `def`s or `lemma`s.\nsection test_locality\n\ndef my_def_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\ndef my_def_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nend test_locality\n\n-- Test: the `local_cache.get` function.\nsection test_get\n\nmeta def assert_equal {\u03b1 : Type} [decidable_eq \u03b1] (a : \u03b1) (ta : tactic \u03b1) : tactic unit :=\ndo a' \u2190 ta,\n   if a = a' then skip\n             else fail \"not equal!\"\n\nlemma my_lemma_3 : true := begin\n  assert_equal none (local_cache.get TEST_NS_1 (list \u2115)),\n\n  my_tactic,\n  my_other_tactic,\n  assert_equal (some [1,2,3,4]) (local_cache.get TEST_NS_1 (list \u2115)),\n  assert_equal (some [10, 20, 30, 40]) (local_cache.get TEST_NS_2 (list \u2115)),\n\n  trivial\nend\n\nend test_get\n\nend block_local\n\n\n\n---------------------------\n-- Now test again with the `def_local` scope.\n---------------------------\n\n\nnamespace def_local\n\nopen tactic.local_cache.cache_scope\n\nsection example_tactic\n\ndef TEST_NS_1 : name := `my_tactic\ndef TEST_NS_2 : name := `my_other_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace_cache_regenerating,\n   return [1, 2, 3, 4]\n\nmeta def my_tactic : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS_1 generate_some_data def_local,\n   -- Do some stuff with `my_cached_data`\n   skip\n\nmeta def my_other_tactic : tactic unit :=\nrun_once TEST_NS_2 (return [10, 20, 30, 40]) def_local >> skip\n\nend example_tactic\n\n\n\nsection example_usage\n\n-- Note only a single cache regeneration (only a single trace message),\n-- even upon descent to a sub-tactic-block.\nlemma my_lemma : true := begin\n    my_tactic,\n    my_tactic,\n    my_tactic,\n\n    have h : true,\n    { my_tactic,\n      trivial },\n\n    trivial\nend\n\nend example_usage\n\nsection test\n\nmeta def fail_if_cache_miss (ns : name) : tactic unit :=\ndo p \u2190 local_cache.present ns def_local,\n   if p then skip else fail \"cache miss\"\n\nmeta def fail_if_cache_miss_1 : tactic unit :=\nfail_if_cache_miss TEST_NS_1\n\nmeta def fail_if_cache_miss_2 : tactic unit :=\nfail_if_cache_miss TEST_NS_2\n\nend test\n\n-- Test: the cache really does persist over a whole definition\nsection test_scope\n\nstructure dummy :=\n(a b : \u2115)\n\ndef my_definition : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     fail_if_cache_miss_1,\n     exact 1\n   end, \u27e9\n\ndef my_definition' : dummy :=\n \u27e8 begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\nlemma my_lemma' : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     fail_if_cache_miss_1,\n     exact 1\n   end, \u27e9\n\nend test_scope\n\n-- Test: the cache is reliably persistent, decends to sub-blocks,\n-- the api to inspect whether a cache entry is present works, and\n-- the cache can be manually cleared.\nsection test_persistence\n\nlemma my_test_ps : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n\n  my_tactic,\n  my_tactic,\n\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  have h : true,\n  { fail_if_cache_miss_1,\n    trivial },\n\n  -- Manually clear cache\n  local_cache.clear TEST_NS_1 def_local,\n  success_if_fail { fail_if_cache_miss_1 },\n\n  trivial\nend\n\nend test_persistence\n\n-- Test: caching under different namespaces doesn't share the\n-- cached state.\nsection test_ns_collison\n\nlemma my_test_ns : true := begin\n  my_tactic,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  my_other_tactic,\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_2,\n\n  local_cache.clear TEST_NS_1 def_local,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  my_other_tactic,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  trivial\nend\n\nend test_ns_collison\n\n-- Test: cached results don't leak between `def`s or `lemma`s.\nsection test_locality\n\ndef my_def_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\ndef my_def_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nend test_locality\n\n-- Test: the `local_cache.get` function.\nsection test_get\n\nmeta def assert_equal {\u03b1 : Type} [decidable_eq \u03b1] (a : \u03b1) (ta : tactic \u03b1) : tactic unit :=\ndo a' \u2190 ta,\n   if a = a' then skip\n             else fail \"not equal!\"\n\nlemma my_lemma_3 : true := begin\n  assert_equal none (local_cache.get TEST_NS_1 (list \u2115)),\n\n  my_tactic,\n  my_other_tactic,\n  assert_equal (some [1,2,3,4]) (local_cache.get TEST_NS_1 (list \u2115) def_local),\n  assert_equal (some [10, 20, 30, 40]) (local_cache.get TEST_NS_2 (list \u2115) def_local),\n\n  trivial\nend\n\nend test_get\n\nend def_local\n\n-- Test: finally, make sure the `block_local` and `def_local` caches\n-- don't collide.\n\nnamespace collision\n\nopen tactic.local_cache.cache_scope\n\ndef TEST_NS : name := `my_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace_cache_regenerating,\n   return [1, 2, 3, 4]\n\nmeta def tac_block : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS generate_some_data block_local,\n   skip\n\nmeta def tac_def : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS generate_some_data def_local,\n   skip\n\nmeta def fail_if_cache_miss_def : tactic unit :=\ndo p \u2190 local_cache.present TEST_NS def_local,\n   if p then skip else fail \"cache miss\"\n\nmeta def fail_if_cache_miss_block : tactic unit :=\ndo p \u2190 local_cache.present TEST_NS block_local,\n   if p then skip else fail \"cache miss\"\n\nlemma my_lemma_1 : true := begin\n  tac_block,\n  fail_if_cache_miss_block,\n  success_if_fail { fail_if_cache_miss_def },\n\n  trivial\nend\n\nlemma my_lemma_2 : true := begin\n  tac_def,\n  fail_if_cache_miss_def,\n  success_if_fail { fail_if_cache_miss_block },\n\n  trivial\nend\n\nlemma my_lemma_3 : true := begin\n  tac_block,\n  tac_def,\n\n  local_cache.clear TEST_NS block_local,\n  fail_if_cache_miss_def,\n  success_if_fail { fail_if_cache_miss_block },\n\n  trivial\nend\n\nlemma my_lemma_4 : true := begin\n  tac_block,\n  tac_def,\n\n  local_cache.clear TEST_NS def_local,\n  fail_if_cache_miss_block,\n  success_if_fail { fail_if_cache_miss_def },\n\n  trivial\nend\n\nend collision\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/test/local_cache.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12765261868437058, "lm_q2_score": 0.028436030780608815, "lm_q1q2_score": 0.003629933794134082}}
{"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.Elab.Command\nimport Lean.Linter.Util\nimport Std.Tactic.Unreachable\n\nnamespace Std.Linter\nopen Lean Elab Command Linter\n\n/--\nEnables the 'unreachable tactic' linter. This will warn on any tactics that are never executed.\nFor example, in `example : True := by trivial <;> done`, the tactic `done` is never executed\nbecause `trivial` produces no subgoals; you could put `sorry` or `apply I_don't_exist`\nor anything else there and no error would result.\n\nA common source of such things is `simp <;> tac` in the case that `simp` improves and\ncloses a subgoal that was previously being closed by `tac`.\n-/\nregister_option linter.unreachableTactic : Bool := {\n  defValue := true\n  descr := \"enable the 'unreachable tactic' linter\"\n}\n\nnamespace UnreachableTactic\n/-- Gets the value of the `linter.unreachableTactic` option. -/\ndef getLinterUnreachableTactic (o : Options) : Bool := getLinterValue linter.unreachableTactic o\n\n/-- The monad for collecting used tactic syntaxes. -/\nabbrev M := StateRefT (HashMap String.Range Syntax) IO\n\n/--\nA list of blacklisted syntax kinds, which are expected to have subterms that contain\nunevaluated tactics.\n-/\ninitialize ignoreTacticKindsRef : IO.Ref NameHashSet \u2190\n  IO.mkRef <| HashSet.empty\n    |>.insert ``Parser.Term.binderTactic\n    |>.insert ``Lean.Parser.Term.dynamicQuot\n    |>.insert ``Lean.Parser.Tactic.quotSeq\n    |>.insert ``Lean.Parser.Tactic.tacticStop_\n\n/-- Is this a syntax kind that contains intentionally unevaluated tactic subterms? -/\ndef isIgnoreTacticKind (ignoreTacticKinds : NameHashSet) (k : SyntaxNodeKind) : Bool :=\n  match k with\n  | .str _ \"quot\" => true\n  | _ => ignoreTacticKinds.contains k\n\n/--\nAdds a new syntax kind whose children will be ignored by the `unreachableTactic` linter.\nThis should be called from an `initialize` block.\n-/\ndef addIgnoreTacticKind (kind : SyntaxNodeKind) : IO Unit :=\n  ignoreTacticKindsRef.modify (\u00b7.insert kind)\n\nvariable (ignoreTacticKinds : NameHashSet) (isTacKind : SyntaxNodeKind \u2192 Bool) in\n/-- Accumulates the set of tactic syntaxes that should be evaluated at least once. -/\n@[specialize] partial def getTactics (stx : Syntax) : M Unit := do\n  if let .node _ k args := stx then\n    if !isIgnoreTacticKind ignoreTacticKinds k then\n      args.forM getTactics\n    if isTacKind k then\n      if let some r := stx.getRange? true then\n        modify fun m => m.insert r stx\n\nmutual\nvariable (isTacKind : SyntaxNodeKind \u2192 Bool)\n/-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/\npartial def eraseUsedTacticsList (trees : PersistentArray InfoTree) : M Unit :=\n  trees.forM eraseUsedTactics\n\n/-- Search for tactic executions in the info tree and remove executed tactic syntaxes. -/\npartial def eraseUsedTactics : InfoTree \u2192 M Unit\n  | .node i c => do\n    if let .ofTacticInfo i := i then\n      if let some r := i.stx.getRange? true then\n        modify (\u00b7.erase r)\n    eraseUsedTacticsList c\n  | .context _ t => eraseUsedTactics t\n  | .hole _ => pure ()\n\nend\n\n/-- The main entry point to the unreachable tactic linter. -/\npartial def unreachableTacticLinter : Linter := fun stx => do\n  unless getLinterUnreachableTactic (\u2190 getOptions) && (\u2190 getInfoState).enabled do\n    return\n  if (\u2190 get).messages.hasErrors then\n    return\n  let cats := (Parser.parserExtension.getState (\u2190 getEnv)).categories\n  let tactics := cats.find! `tactic |>.kinds\n  let convs := cats.find! `conv |>.kinds\n  let trees \u2190 getInfoTrees\n  let go : M Unit := do\n    getTactics (\u2190 ignoreTacticKindsRef.get) (fun k => tactics.contains k || convs.contains k) stx\n    eraseUsedTacticsList trees\n  let (_, map) \u2190 go.run {}\n  let unreachable := map.toArray\n  let key (r : String.Range) := (r.start.byteIdx, (-r.stop.byteIdx : Int))\n  let mut last : String.Range := \u27e80, 0\u27e9\n  for (r, stx) in let _ := @lexOrd; let _ := @ltOfOrd.{0}; unreachable.qsort (key \u00b7.1 < key \u00b7.1) do\n    if stx.getKind \u2208 [``Std.Tactic.unreachable, ``Std.Tactic.unreachableConv] then continue\n    if last.start \u2264 r.start && r.stop \u2264 last.stop then continue\n    logLint linter.unreachableTactic stx \"this tactic is never executed\"\n    last := r\n\ninitialize addLinter unreachableTacticLinter\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Linter/UnreachableTactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10087861191752102, "lm_q2_score": 0.03567855023687644, "lm_q1q2_score": 0.003599202623125636}}
{"text": "import tactic.local_cache\n\nopen tactic\n\ndef do_trace : bool := ff\n\nmeta def trace_cache_regenerating : tactic unit :=\nif do_trace then trace \"(test/local_cache): cache regenerating\" else skip\n\nnamespace block_local\n\nsection example_tactic\n\ndef TEST_NS_1 : name := `my_tactic\ndef TEST_NS_2 : name := `my_other_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace_cache_regenerating,\n   return [1, 2, 3, 4]\n\nmeta def my_tactic : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS_1 generate_some_data,\n   -- Do some stuff with `my_cached_data`\n   skip\n\nmeta def my_other_tactic : tactic unit :=\nrun_once TEST_NS_2 (return [10, 20, 30, 40]) >> skip\n\nend example_tactic\n\n\n\nsection example_usage\n\n-- Note only a single cache regeneration (only a single trace message),\n-- even upon descent to a sub-tactic-block.\nlemma my_lemma : true := begin\n    my_tactic,\n    my_tactic,\n    my_tactic,\n\n    have h : true,\n    { my_tactic,\n      trivial },\n\n    trivial\nend\n\nend example_usage\n\nsection test\n\nmeta def fail_if_cache_miss (ns : name) : tactic unit :=\ndo p \u2190 local_cache.present ns,\n   if p then skip else fail \"cache miss\"\n\nmeta def fail_if_cache_miss_1 : tactic unit :=\nfail_if_cache_miss TEST_NS_1\n\nmeta def fail_if_cache_miss_2 : tactic unit :=\nfail_if_cache_miss TEST_NS_2\n\nend test\n\n-- Test: the cache persists only within a single tactic block\nsection test_scope\n\nstructure dummy :=\n(a b : \u2115)\n\ndef my_definition : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\ndef my_definition' : dummy :=\n \u27e8 begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\nnoncomputable\nlemma my_lemma' : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\nend test_scope\n\n-- Test: the cache is reliably persistent, decends to sub-blocks,\n-- the api to inspect whether a cache entry is present works, and\n-- the cache can be manually cleared.\nsection test_persistence\n\nlemma my_test_ps : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n\n  my_tactic,\n\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  have h : true,\n  { fail_if_cache_miss_1,\n    trivial },\n\n  -- Manually clear cache\n  local_cache.clear TEST_NS_1,\n  success_if_fail { fail_if_cache_miss_1 },\n\n  trivial\nend\n\nend test_persistence\n\n-- Test: caching under different namespaces doesn't share the\n-- cached state.\nsection test_ns_collison\n\nlemma my_test_ns : true := begin\n  my_tactic,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  my_other_tactic,\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_2,\n\n  local_cache.clear TEST_NS_1,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  my_other_tactic,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  trivial\nend\n\nend test_ns_collison\n\n-- Test: cached results don't leak between `def`s or `lemma`s.\nsection test_locality\n\ndef my_def_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\ndef my_def_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nend test_locality\n\n-- Test: the `local_cache.get` function.\nsection test_get\n\nmeta def assert_equal {\u03b1 : Type} [decidable_eq \u03b1] (a : \u03b1) (ta : tactic \u03b1) : tactic unit :=\ndo a' \u2190 ta,\n   if a = a' then skip\n             else fail \"not equal!\"\n\nlemma my_lemma_3 : true := begin\n  assert_equal none (local_cache.get TEST_NS_1 (list \u2115)),\n\n  my_tactic,\n  my_other_tactic,\n  assert_equal (some [1,2,3,4]) (local_cache.get TEST_NS_1 (list \u2115)),\n  assert_equal (some [10, 20, 30, 40]) (local_cache.get TEST_NS_2 (list \u2115)),\n\n  trivial\nend\n\nend test_get\n\nend block_local\n\n\n\n---------------------------\n-- Now test again with the `def_local` scope.\n---------------------------\n\n\nnamespace def_local\n\nopen tactic.local_cache.cache_scope\n\nsection example_tactic\n\ndef TEST_NS_1 : name := `my_tactic\ndef TEST_NS_2 : name := `my_other_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace_cache_regenerating,\n   return [1, 2, 3, 4]\n\nmeta def my_tactic : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS_1 generate_some_data def_local,\n   -- Do some stuff with `my_cached_data`\n   skip\n\nmeta def my_other_tactic : tactic unit :=\nrun_once TEST_NS_2 (return [10, 20, 30, 40]) def_local >> skip\n\nend example_tactic\n\n\n\nsection example_usage\n\n-- Note only a single cache regeneration (only a single trace message),\n-- even upon descent to a sub-tactic-block.\nlemma my_lemma : true := begin\n    my_tactic,\n    my_tactic,\n    my_tactic,\n\n    have h : true,\n    { my_tactic,\n      trivial },\n\n    trivial\nend\n\nend example_usage\n\nsection test\n\nmeta def fail_if_cache_miss (ns : name) : tactic unit :=\ndo p \u2190 local_cache.present ns def_local,\n   if p then skip else fail \"cache miss\"\n\nmeta def fail_if_cache_miss_1 : tactic unit :=\nfail_if_cache_miss TEST_NS_1\n\nmeta def fail_if_cache_miss_2 : tactic unit :=\nfail_if_cache_miss TEST_NS_2\n\nend test\n\n-- Test: the cache really does persist over a whole definition\nsection test_scope\n\nstructure dummy :=\n(a b : \u2115)\n\ndef my_definition : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     fail_if_cache_miss_1,\n     exact 1\n   end, \u27e9\n\ndef my_definition' : dummy :=\n \u27e8 begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end,\n   begin\n     success_if_fail { fail_if_cache_miss_1 },\n     exact 1\n   end, \u27e9\n\nnoncomputable\nlemma my_lemma' : dummy :=\n \u27e8 begin\n     my_tactic,\n     fail_if_cache_miss_1,\n     exact 1\n   end,\n   begin\n     fail_if_cache_miss_1,\n     exact 1\n   end, \u27e9\n\nend test_scope\n\n-- Test: the cache is reliably persistent, decends to sub-blocks,\n-- the api to inspect whether a cache entry is present works, and\n-- the cache can be manually cleared.\nsection test_persistence\n\nlemma my_test_ps : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n\n  my_tactic,\n  my_tactic,\n\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  have h : true,\n  { fail_if_cache_miss_1,\n    trivial },\n\n  -- Manually clear cache\n  local_cache.clear TEST_NS_1 def_local,\n  success_if_fail { fail_if_cache_miss_1 },\n\n  trivial\nend\n\nend test_persistence\n\n-- Test: caching under different namespaces doesn't share the\n-- cached state.\nsection test_ns_collison\n\nlemma my_test_ns : true := begin\n  my_tactic,\n  fail_if_cache_miss_1,\n  success_if_fail { fail_if_cache_miss_2 },\n\n  my_other_tactic,\n  fail_if_cache_miss_1,\n  fail_if_cache_miss_2,\n\n  local_cache.clear TEST_NS_1 def_local,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  my_other_tactic,\n  success_if_fail { fail_if_cache_miss_1 },\n  fail_if_cache_miss_2,\n\n  trivial\nend\n\nend test_ns_collison\n\n-- Test: cached results don't leak between `def`s or `lemma`s.\nsection test_locality\n\ndef my_def_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\ndef my_def_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_1 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nlemma my_lemma_2 : true := begin\n  success_if_fail { fail_if_cache_miss_1 },\n  my_tactic,\n  fail_if_cache_miss_1,\n\n  trivial\nend\n\nend test_locality\n\n-- Test: the `local_cache.get` function.\nsection test_get\n\nmeta def assert_equal {\u03b1 : Type} [decidable_eq \u03b1] (a : \u03b1) (ta : tactic \u03b1) : tactic unit :=\ndo a' \u2190 ta,\n   if a = a' then skip\n             else fail \"not equal!\"\n\nlemma my_lemma_3 : true := begin\n  assert_equal none (local_cache.get TEST_NS_1 (list \u2115)),\n\n  my_tactic,\n  my_other_tactic,\n  assert_equal (some [1,2,3,4]) (local_cache.get TEST_NS_1 (list \u2115) def_local),\n  assert_equal (some [10, 20, 30, 40]) (local_cache.get TEST_NS_2 (list \u2115) def_local),\n\n  trivial\nend\n\nend test_get\n\nend def_local\n\n-- Test: finally, make sure the `block_local` and `def_local` caches\n-- don't collide.\n\nnamespace collision\n\nopen tactic.local_cache.cache_scope\n\ndef TEST_NS : name := `my_tactic\n\n-- Example \"expensive\" function\nmeta def generate_some_data : tactic (list \u2115) :=\ndo trace_cache_regenerating,\n   return [1, 2, 3, 4]\n\nmeta def tac_block : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS generate_some_data block_local,\n   skip\n\nmeta def tac_def : tactic unit :=\ndo my_cached_data \u2190 run_once TEST_NS generate_some_data def_local,\n   skip\n\nmeta def fail_if_cache_miss_def : tactic unit :=\ndo p \u2190 local_cache.present TEST_NS def_local,\n   if p then skip else fail \"cache miss\"\n\nmeta def fail_if_cache_miss_block : tactic unit :=\ndo p \u2190 local_cache.present TEST_NS block_local,\n   if p then skip else fail \"cache miss\"\n\nlemma my_lemma_1 : true := begin\n  tac_block,\n  fail_if_cache_miss_block,\n  success_if_fail { fail_if_cache_miss_def },\n\n  trivial\nend\n\nlemma my_lemma_2 : true := begin\n  tac_def,\n  fail_if_cache_miss_def,\n  success_if_fail { fail_if_cache_miss_block },\n\n  trivial\nend\n\nlemma my_lemma_3 : true := begin\n  tac_block,\n  tac_def,\n\n  local_cache.clear TEST_NS block_local,\n  fail_if_cache_miss_def,\n  success_if_fail { fail_if_cache_miss_block },\n\n  trivial\nend\n\nlemma my_lemma_4 : true := begin\n  tac_block,\n  tac_def,\n\n  local_cache.clear TEST_NS def_local,\n  fail_if_cache_miss_block,\n  success_if_fail { fail_if_cache_miss_def },\n\n  trivial\nend\n\nend collision\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/local_cache.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1259227582746744, "lm_q2_score": 0.02843603602953799, "lm_q1q2_score": 0.003580744091237444}}
{"text": "import system.io\n\ndef io.buffer_cmd (args : io.process.spawn_args) : io char_buffer :=\ndo child \u2190 io.proc.spawn { args with stdout := io.process.stdio.piped },\n  buf \u2190 io.fs.read_to_end child.stdout,\n  exitv \u2190 io.proc.wait child,\n  when (exitv \u2260 0) $ io.fail $ \"process exited with status \" ++ to_string exitv,\n  return buf\n\ndef PYTHON_SCRIPT := \"/cvxopt/opt.py\"\n\nmeta def blah := do\n  b <- tactic.unsafe_run_io $ io.buffer_cmd { cmd := \"python3\", args := [PYTHON_SCRIPT] },\n  trace b.to_string\n  return b.to_string\n\n\nexample : false :=\nbegin\n-- blah,\nend", "meta": {"author": "skbaek", "repo": "cvx", "sha": "c50c790c9116f9fac8dfe742903a62bdd7292c15", "save_path": "github-repos/lean/skbaek-cvx", "path": "github-repos/lean/skbaek-cvx/cvx-c50c790c9116f9fac8dfe742903a62bdd7292c15/src/alex_playground/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.14414886773958663, "lm_q2_score": 0.02479815906946714, "lm_q1q2_score": 0.0035746265518898494}}
{"text": "import evaluation\nimport utils\n\n-- TODO(jesse): code duplication >:(\n\nnamespace openai\n\nsection openai_api\n\nmeta structure CompletionRequest : Type :=\n(prompt : string)\n(max_tokens : int := 16)\n(temperature : native.float := 1.0)\n(top_p : native.float := 1)\n(n : int := 1)\n(best_of : option int := none)\n(stream : option bool := none)\n(logprobs : int := 0)\n(echo : option bool := none)\n(stop : option string := none) -- TODO(jesse): list string\n(presence_penalty : option native.float := none)\n(frequency_penalty : option native.float := none)\n(show_trace : bool := ff)\n(prompt_token := \"PROOFSTEP\")\n-- don't support logit_bias for now\n\n-- TODO(jesse): write a derive handler for this kind of structure serialization\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 \u2192 bool := \u03bb n, n \u2264 2048 in\nlet validate_float_frac : native.float \u2192 bool := \u03bb k, 0 \u2264 k \u2227 k \u2264 1 in\nlet validate_and_return {\u03b1} [has_to_format \u03b1] (pred : \u03b1 \u2192 bool) : \u03b1 \u2192 tactic \u03b1 :=\n  \u03bb a, ((guard $ pred a) *> pure a <|> by {tactic.unfreeze_local_instances, exact (tactic.fail format!\"[openai.CompletionRequest.to_tactic_json] VALIDATION FAILED FOR {a}\")}) in\nlet validate_optional_and_return {\u03b1} [has_to_format \u03b1] (pred : \u03b1 \u2192 bool) : option \u03b1 \u2192 tactic (option \u03b1) := \u03bb x, do {\n  match x with\n  | (some val) := some <$> by {tactic.unfreeze_local_instances, exact (validate_and_return pred val)}\n  | none := pure none\n  end\n} in\nlet MAX_N : int := 100000 in\nlet fn : CompletionRequest \u2192 tactic json := \u03bb req, match req with\n| \u27e8prompt, max_tokens, temperature, top_p, n, best_of,\n  stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _, _\u27e9 := do\n  -- TODO(jesse): ensure validation does not fail silently\n  max_tokens \u2190 validate_and_return validate_max_tokens max_tokens,\n  -- temperature \u2190 validate_and_return validate_float_frac temperature,\n  top_p \u2190 validate_and_return validate_float_frac top_p,\n  n \u2190 validate_and_return (\u03bb x, 0 \u2264 x \u2227 x \u2264 MAX_N) /- go wild with the candidates -/ n,\n  best_of \u2190 validate_optional_and_return (\u03bb x, n \u2264 x \u2227 x \u2264 MAX_N) best_of,\n  presence_penalty \u2190 validate_optional_and_return validate_float_frac presence_penalty,\n  frequency_penalty \u2190 validate_optional_and_return validate_float_frac frequency_penalty,\n\n  eval_trace $ \"[openai.CompletionRequest.to_tactic_json] VALIDATION PASSED\",\n\n  let pre_kvs : list (string \u00d7 option json) := [\n    (\"prompt\", json.of_string prompt),\n    (\"max_tokens\", json.of_int max_tokens),\n    (\"temperature\", json.of_float temperature),\n    (\"top_p\", json.of_float top_p),\n    (\"n\", json.of_int n),\n    (\"best_of\", json.of_int <$> best_of),\n    (\"stream\", json.of_bool <$> stream),\n    (\"logprobs\", some $ json.of_int logprobs),\n    (\"echo\", json.of_bool <$> echo),\n    (\"stop\", json.of_string <$> stop),\n    (\"presence_penalty\", json.of_float <$> presence_penalty),\n    (\"frequency_penalty\", json.of_float <$> frequency_penalty)\n  ],\n\n  pure $ json.object $ pre_kvs.filter_map (\u03bb \u27e8k,mv\u27e9, prod.mk k <$> mv)\nend\nin \u27e8fn\u27e9\n\n/-\nexample from API docs:\ncurl https://api.openai.com/v1/engines/davinci/completions \\\n  -H 'Content-Type: application/json' \\\n  -H 'Authorization: Bearer $OPENAI_API_KEY' \\\n  -d '{\n  \"prompt\": \"Once upon a time\",\n  \"max_tokens\": 5\n}'\n-/\nmeta def dummy_cr : CompletionRequest :=\n{prompt := \"Once upon a time\", max_tokens := 5, temperature := 1.0, top_p := 1.0, n := 3}\n\nmeta def CompletionRequest.to_cmd (engine_id : string) (api_key : string) : CompletionRequest \u2192 io (io.process.spawn_args)\n| req@\u27e8prompt, max_tokens, temperature, top_p, n, best_of,\n  stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _, _\u27e9 := do\nwhen EVAL_TRACE $ io.put_str_ln' format!\"[openai.CompletionRequest.to_cmd] ENTERING\",\nserialized_req \u2190 io.run_tactic' $ has_to_tactic_json.to_tactic_json req,\nwhen EVAL_TRACE $ io.put_str_ln' format!\"[openai.CompletionRequest.to_cmd] SERIALIZED\",\npure {\n  cmd := \"curl\",\n  args := [\n         \"-u\"\n      , format.to_string $ format!\":{api_key}\"\n      ,  \"-X\"\n      , \"POST\"\n--      ,  format.to_string format!\"http://router.api.svc.owl.sci.openai.org:5004/v1/engines/{engine_id}/completions\"\n      ,  format.to_string format!\"https://api.openai.com/v1/engines/{engine_id}/completions\"\n      , \"-H\", \"OpenAI-Organization: org-kuQ09yewcuHU5GN5YYEUp2hh\"\n      , \"-H\", \"Content-Type: application/json\"\n      , \"-d\"\n      , json.unparse serialized_req\n    ]\n}\n\nsetup_tactic_parser\n\n-- nice, it works\n-- example {p q} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   apply and.intro, do {tactic.read >>= postprocess_tactic_state >>= eval_trace}\n-- end\n\nmeta def serialize_ts\n  (req : CompletionRequest)\n  : tactic_state \u2192 tactic CompletionRequest := \u03bb ts, do {\n  ts_str \u2190 ts.fully_qualified >>= postprocess_tactic_state,\n  let prompt : string :=\n    \"[LN] GOAL \" ++ ts_str ++ (format! \" {req.prompt_token} \").to_string,\n  eval_trace format!\"\\n \\n \\n PROMPT: {prompt} \\n \\n \\n \",\n  pure {\n    prompt := prompt,\n    ..req}\n}\n\nsetup_tactic_parser\n\nprivate meta def decode_response_msg : json \u2192 io (json \u00d7 json) := \u03bb response_msg, do {\n  (json.array choices) \u2190 lift_option $ response_msg.lookup \"choices\" | io.fail' format!\"can't find choices in {response_msg}\",\n  prod.mk <$> (json.array <$> choices.mmap (\u03bb choice, lift_option $ json.lookup choice \"text\")) <*> do {\n    logprobss \u2190 choices.mmap (\u03bb msg, lift_option $ msg.lookup \"logprobs\"),\n    scoress \u2190 logprobss.mmap (\u03bb logprobs, lift_option $ logprobs.lookup \"token_logprobs\"),\n    result \u2190 json.array <$> scoress.mmap (lift_option \u2218 json_float_array_sum),\n    pure result\n  }\n}\n\nmeta def openai_api (engine_id : string) (api_key : string) : ModelAPI CompletionRequest :=\nlet fn : CompletionRequest \u2192 io json := \u03bb req, do {\n  proc_cmds \u2190 req.to_cmd engine_id api_key,\n  -- when req.show_trace $ io.put_str_ln' format!\"[openai_api] PROC_CMDS: {proc_cmds}\",\n  response_raw \u2190 io.cmd proc_cmds,\n  when req.show_trace $ io.put_str_ln' format!\"[openai_api] RAW RESPONSE: {response_raw}\",\n\n  response_msg \u2190 (lift_option $ json.parse response_raw) | io.fail' format!\"[openai_api] JSON PARSE FAILED {response_raw}\",\n    \n  when req.show_trace $ io.put_str_ln' format!\"GOT RESPONSE_MSG\",\n\n  -- predictions \u2190 (lift_option $ do {\n  --   (json.array choices) \u2190 response_msg.lookup \"choices\" | none,\n  --   /- `choices` is a list of {text: ..., index: ..., logprobs: ..., finish_reason: ...}-/\n  --   texts \u2190 choices.mmap (\u03bb choice, choice.lookup \"text\"),\n  --   (scoress : list json) \u2190 choices.mmap (\u03bb msg, msg.lookup \"logprobs\" >>= \u03bb x, x.lookup \"token_logprobs\"),\n  --   -- scores \u2190 scoress.mmap (\u03bb xs, xs.map (\u03bb msg,\n  --   scores \u2190 scoress.mmap json_float_array_sum,\n  --   pure $ prod.mk texts scores\n  --  }) \n\n  do {\n    predictions \u2190 decode_response_msg response_msg | io.fail' format!\"[openai_api] UNEXPECTED RESPONSE MSG: {response_msg}\",\n    when req.show_trace $ io.put_str_ln' format!\"PREDICTIONS: {predictions}\",\n    pure (json.array [predictions.fst, predictions.snd])\n  } <|> pure (json.array $ [json.of_string $ format.to_string $ format!\"ERROR {response_msg}\"]) -- catch API errors here\n} in \u27e8fn\u27e9\n\nend openai_api\n\nsection openai_proof_search\n\nmeta def read_first_line : string \u2192 io string := \u03bb path, do\n  buffer.to_string <$> (io.mk_file_handle path io.mode.read >>= io.fs.get_line)\n\n-- in entry point, API key is read from command line and then set as an environment variable for the execution\n-- of the command\n\n@[inline, reducible]meta def tab : char := '\\t'\n\n@[inline, reducible]meta def newline : char := '\\n'\n\nmeta def default_partial_req : openai.CompletionRequest :=\n{\n  prompt := \"\",\n  max_tokens := 128,\n  temperature := (0.7 : native.float),\n  top_p := 1,\n  n := 1,\n  best_of := none,\n  stream := none,\n  logprobs := 0,\n  echo := none,\n  stop := none, -- TODO(jesse): list string,\n  presence_penalty := none,\n  frequency_penalty := none,\n  show_trace := EVAL_TRACE\n}\n\n/- this is the entry point for the evalution harness -/\nmeta def openai_bfs_proof_search_core\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  : state_t BFSState tactic unit := do\nmonad_lift $ set_show_eval_trace partial_req.show_trace,\nbfs_core\n  (openai_api engine_id api_key)\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[openai_greedy_proof_search_core]\") msg n)\n        (fuel)\n\n/- for testing API failure handling.\n   replace `openai.openai_bfs_proof_search_core` with\n   `openai.dummy_openai_bfs_proof_search_core` in\n   `evaluation/bfs/gptf.lean` and confirm that the\n   produced `.json` files show `api_failures = 1`\n-/\nmeta def dummy_openai_bfs_proof_search_core\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  : state_t BFSState tactic unit := do\nmonad_lift $ set_show_eval_trace partial_req.show_trace,\nbfs_core\n    dummy_api\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[openai_greedy_proof_search_core]\") msg n)\n        (fuel)\n\n/- meant for interactive use -/\nmeta def openai_bfs_proof_search\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  (verbose := ff)\n  (max_width : \u2115 := 25)\n  (max_depth : \u2115 := 50)\n  : tactic unit := do\nset_show_eval_trace partial_req.show_trace,\nbfs\n  (openai_api engine_id api_key)\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[openai_greedy_proof_search]\") msg n)\n        (fuel) (verbose) (max_width) (max_depth)\n\nend openai_proof_search\n\nsection playground\n\nexample : true :=\nbegin\n  trivial\n  -- openai_bfs_proof_search default_partial_req \"formal-large-lean-webmath-1230-v1-c4\" API_KEY\nend\n\n-- example : true :=\n-- begin\n--   openai_greedy_proof_search\n--     default_partial_req\n--       \"formal-large-lean-webmath-1230-v1-c4\"\n--         API_KEY\n-- end\n\n-- example (n : \u2115) (m : \u2115) : nat.succ (n + m) < (nat.succ n + m) + 1  :=\n-- begin\n--   -- openai_greedy_proof_search\n--   --   {n := 10, temperature := 0.7, ..default_partial_req}\n--   --     \"formal-large-lean-webmath-1230-v1-c4\"\n--   --       API_KEY 10 tt,\n-- sorry\n-- -- rw succ_add,  exact nat.lt_succ_self _\n-- end\n\n-- theorem t2 (p q r : Prop) (h\u2081 : p) (h\u2082 : q) : (q \u2227 p) \u2228 r :=\n\n-- lemma peirce_identity {P Q :Prop} : ((P \u2192 Q) \u2192 P) \u2192 P :=\n-- begin\n--   openai_greedy_proof_search\n--     {n := 25, temperature := 0.7, ..default_partial_req}\n--       \"formal-large-lean-webmath-1230-v1-c4\"\n--         API_KEY 10,\n-- end\n\n-- --   openai_greedy_proof_search\n-- --     default_partial_req\n-- --       \"formal-large-lean-webmath-1230-v1-c4\"\n-- --         API_KEY\n-- -- -- simp [or_assoc, or_comm, or_left_comm]\n\n-- end\n\nend playground\n\nend openai\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/bfs/openai.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12421301807811348, "lm_q2_score": 0.028436035720777426, "lm_q1q2_score": 0.003532125819054807}}
{"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.Elab.Syntax\nimport Lean.Elab.AuxDef\nimport Lean.Elab.BuiltinNotation\n\nnamespace Lean.Elab.Command\nopen Lean.Syntax\nopen Lean.Parser.Term hiding macroArg\nopen Lean.Parser.Command\n\n/-- Wrap all occurrences of the given `ident` nodes in antiquotations -/\nprivate partial def antiquote (vars : Array Syntax) : Syntax \u2192 Syntax\n  | stx => match stx with\n  | `($id:ident) =>\n    if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then\n      mkAntiquotNode id (kind := `term) (isPseudoKind := true)\n    else\n      stx\n  | _ => match stx with\n    | Syntax.node i k args => Syntax.node i k (args.map (antiquote vars))\n    | stx => stx\n\n def addInheritDocDefault (rhs : Term) (attrs? : Option (TSepArray ``attrInstance \",\")) :\n    Option (TSepArray ``attrInstance \",\") :=\n  attrs?.map fun attrs =>\n    match rhs with\n    | `($f:ident $_args*) | `($f:ident) =>\n      attrs.getElems.map fun stx => Unhygienic.run do\n        if let `(attrInstance| $attr:ident) := stx then\n          if attr.getId.eraseMacroScopes == `inherit_doc then\n            return \u2190 `(attrInstance| $attr:ident $f:ident)\n        pure \u27e8stx\u27e9\n    | _ => attrs\n\n/-- Convert `notation` command lhs item into a `syntax` command item -/\ndef expandNotationItemIntoSyntaxItem : TSyntax ``notationItem \u2192 MacroM (TSyntax `stx)\n  | `(notationItem| $_:ident$[:$prec?]?) => `(stx| term $[:$prec?]?)\n  | `(notationItem| $s:str)              => `(stx| $s:str)\n  | _                                    => Macro.throwUnsupported\n\n/-- Convert `notation` command lhs item into a pattern element -/\ndef expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax :=\n  let k := stx.getKind\n  if k == `Lean.Parser.Command.identPrec then\n    return mkAntiquotNode stx[0] (kind := `term) (isPseudoKind := true)\n  else if k == strLitKind then\n    strLitToPattern stx\n  else\n    Macro.throwUnsupported\n\ndef removeParenthesesAux (parens body : Syntax) : Syntax :=\n  match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with\n  | .original lead _ _ _, .original _ pos trail pos',\n    .original endLead endPos _ endPos', .original _ _ endTrail _ =>\n      body.setHeadInfo (.original lead pos trail pos') |>.setTailInfo (.original endLead endPos endTrail endPos')\n  | _, _, _, _ => body\n\npartial def removeParentheses (stx : Syntax) : MacroM Syntax := do\n  match stx with\n  | `(($e)) => pure $ removeParenthesesAux stx (\u2190removeParentheses $ (\u2190Term.expandCDot? e).getD e)\n  | _ =>\n    match stx with\n    | .node info kind args => pure $ .node info kind (\u2190args.mapM removeParentheses)\n    | _ => pure stx\n\npartial def hasDuplicateAntiquot (stxs : Array Syntax) : Bool := Id.run do\n  let mut seen := NameSet.empty\n  for stx in stxs do\n    for node in Syntax.topDown stx true do\n      if node.isAntiquot then\n        let ident := node.getAntiquotTerm.getId\n        if seen.contains ident then\n          return true\n        else\n          seen := seen.insert ident\n  pure false\n\n/-- Try to derive an unexpander from a notation.\n    The notation must be of the form `notation ... => c body`\n    where `c` is a declaration in the current scope and `body` any syntax\n    that contains each variable from the LHS at most once. -/\ndef mkUnexpander (attrKind : TSyntax ``attrKind) (pat qrhs : Term) : OptionT MacroM Syntax := do\n  let (c, args) \u2190 match qrhs with\n    | `($c:ident $args*) => pure (c, args)\n    | `($c:ident)        => pure (c, #[])\n    | _                  => failure\n  let [(c, [])] \u2190 Macro.resolveGlobalName c.getId | failure\n  /-\n  Try to remove all non semantic parenthesis. Since the parenthesizer\n  runs after appUnexpanders we should not match on parenthesis that the user\n  syntax inserted here for example the right hand side of:\n  notation \"{\" x \"|\" p \"}\" => setOf (fun x => p)\n  Should be matched as: setOf fun x => p\n  -/\n  let args \u2190 liftM <| args.mapM removeParentheses\n  /-\n  The user could mention the same antiquotation from the lhs multiple\n  times on the rhs, this heuristic does not support this.\n  -/\n  guard !hasDuplicateAntiquot args\n  -- replace head constant with antiquotation so we're not dependent on the exact pretty printing of the head\n  -- The reference is attached to the syntactic representation of the called function itself, not the entire function application\n  let lhs \u2190 `($$f:ident)\n  let lhs := Syntax.mkApp lhs (.mk args)\n  -- allow over-application, avoiding nested `app` nodes\n  let lhsWithMoreArgs := flattenApp (\u2190 `($lhs $$moreArgs*))\n  let patWithMoreArgs := flattenApp (\u2190 `($pat $$moreArgs*))\n  `(@[$attrKind app_unexpander $(mkIdent c)]\n    aux_def unexpand $(mkIdent c) : Lean.PrettyPrinter.Unexpander := fun\n      | `($lhs)             => withRef f `($pat)\n      -- must be a separate case as the LHS and RHS above might not be `app` nodes\n      | `($lhsWithMoreArgs) => withRef f `($patWithMoreArgs)\n      | _                   => throw ())\nwhere\n  -- NOTE: we consider only one nesting level here\n  flattenApp : Term \u2192 Term\n    | stx@`($f $xs*) => match f with\n      | `($f' $xs'*) => Syntax.mkApp f' (xs' ++ xs)\n      | _            => stx\n    | stx            => stx\n\nprivate def expandNotationAux (ref : Syntax) (currNamespace : Name)\n    (doc? : Option (TSyntax ``docComment))\n    (attrs? : Option (TSepArray ``attrInstance \",\"))\n    (attrKind : TSyntax ``attrKind)\n    (prec? : Option Prec) (name? : Option Ident) (prio? : Option Prio)\n    (items : Array (TSyntax ``notationItem)) (rhs : Term) : MacroM Syntax := do\n  let prio \u2190 evalOptPrio prio?\n  -- build parser\n  let syntaxParts \u2190 items.mapM expandNotationItemIntoSyntaxItem\n  let cat := mkIdentFrom ref `term\n  let name \u2190\n    match name? with\n    | some name => pure name.getId\n    | none => addMacroScopeIfLocal (\u2190 mkNameFromParserSyntax `term (mkNullNode syntaxParts)) attrKind\n  -- build macro rules\n  let vars := items.filter fun item => item.raw.getKind == ``identPrec\n  let vars := vars.map fun var => var.raw[0]\n  let qrhs := \u27e8antiquote vars rhs\u27e9\n  let attrs? := addInheritDocDefault rhs attrs?\n  let patArgs \u2190 items.mapM expandNotationItemIntoPattern\n  /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.\n     So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/\n  let fullName := currNamespace ++ name\n  let pat : Term := \u27e8mkNode fullName patArgs\u27e9\n  let stxDecl \u2190 `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind\n    syntax $[: $prec?]? (name := $(name?.getD (mkIdent name))) (priority := $(quote prio)) $[$syntaxParts]* : $cat)\n  let macroDecl \u2190 `(macro_rules | `($pat) => ``($qrhs))\n  let macroDecls \u2190\n    if isLocalAttrKind attrKind then\n      -- Make sure the quotation pre-checker takes section variables into account for local notation.\n      `(section set_option quotPrecheck.allowSectionVars true $macroDecl end)\n    else\n      pure \u27e8mkNullNode #[macroDecl]\u27e9\n  match (\u2190 mkUnexpander attrKind pat qrhs |>.run) with\n  | some delabDecl => return mkNullNode #[stxDecl, macroDecls, delabDecl]\n  | none           => return mkNullNode #[stxDecl, macroDecls]\n\n@[builtin_macro Lean.Parser.Command.notation] def expandNotation : Macro\n  | stx@`($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind\n      notation $[: $prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => do\n    -- trigger scoped checks early and only once\n    let _ \u2190 toAttributeKind attrKind\n    expandNotationAux stx (\u2190 Macro.getCurrNamespace) doc? attrs? attrKind prec? name? prio? items rhs\n  | _ => Macro.throwUnsupported\n\nend Lean.Elab.Command\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/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15405755880753266, "lm_q2_score": 0.02262919797322009, "lm_q1q2_score": 0.003486198997526653}}
{"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 <Tab> 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 := \u27e8fun n => Syntax.mkNumLit <| n.repr\u27e9\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<int> or f<int>, 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 \u2192 builtin\nexample : MLIRType builtin := [mlir_type| i32]\n\n-- Uses dialect coercion empty \u2192 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 \"\u00d7\")* 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.\u00abmlir_dimension_list_\u00d7_\u00bb\n--  [\n--    [(MLIR.EDSL.mlir_dimension_ (numLit \"3\")) \"\u00d7\"]\n--    [(MLIR.EDSL.mlir_dimension_ (numLit \"3\")) \"\u00d7\"]]\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 \u00d7 TSyntax `term) := do\n\n  let ty <- `([mlir_type|  $(\u27e8k.getArgs.back\u27e9)])\n  let dimensions := (k.getArg 0)\n  let dimensions <- dimensions.getArgs.toList.mapM (fun x =>\n    `([mlir_dimension| $(\u27e8x.getArg 0\u27e9)]))\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, \"\u00d7\", \"\u00d7\" notFollowedBy(mlir_type <|> \"[\")) : static_dim_list\n\n\nsyntax \"[static_dim_list|\" static_dim_list \"]\" : term\nmacro_rules\n| `([static_dim_list| $[ $ns:num ]\u00d7* ]) => do\n      quoteMList (ns.toList.map (\u27e8\u00b7.raw\u27e9)) (<- `(Nat))\n\n-- vector-dim-list := (static-dim-list `x`)? (`[` static-dim-list `]` `x`)?\ndeclare_syntax_cat vector_dim_list\nsyntax (static_dim_list \"\u00d7\" (\"[\" static_dim_list \"]\" \"\u00d7\")? )? : 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 \u00d7 $[ [ $scaled?:static_dim_list ] \u00d7 ]? ]? $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 \u00d7 2]\n#reduce staticDimList1\n\n\n\ndef vectorTy0 := [mlir_type| vector<i32>]\n#print vectorTy0\n\ndef vectorTy1 := [mlir_type| vector<2 \u00d7 i32>]\n#print vectorTy1\n\ndef vectorTy2 := [mlir_type| vector<2 \u00d7 3 \u00d7 [ 4 ] \u00d7 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\" \"<\"  \"*\" \"\u00d7\" mlir_type \">\"  : mlir_type\nsyntax \"tensor\" \"<*\" \"\u00d7\" mlir_type \">\"  : mlir_type\nsyntax \"tensor\" \"<*\u00d7\" mlir_type \">\"  : mlir_type\n\nmacro_rules\n| `([mlir_type| tensor < *\u00d7 $ty:mlir_type >]) => do\n    `(builtin.tensor_unranked [mlir_type| $ty])\n\nmacro_rules\n| `([mlir_type| tensor < * \u00d7 $ty:mlir_type >]) => do\n    `(builtin.tensor_unranked [mlir_type| $ty])\n\nmacro_rules\n| `([mlir_type| tensor <* \u00d7 $ty:mlir_type >]) => do\n    `(builtin.tensor_unranked [mlir_type| $ty])\n\nmacro_rules\n| `([mlir_type| tensor <*\u00d7$ty:mlir_type >]) => do\n    `(builtin.tensor_unranked [mlir_type| $ty])\n\n-- Automatically inferred as MLIRType builtin\ndef tensorTy0 := [mlir_type| tensor<3\u00d73\u00d7i32>]\n#print tensorTy0\n\ndef tensorTy1 := [mlir_type| tensor< * \u00d7 i32>]\n#print tensorTy1\n\ndef tensorTy2 := [mlir_type| tensor< * \u00d7 f32>]\n#print tensorTy2\n\ndef tensorTy3 := [mlir_type| tensor<*\u00d7 f32>]\n#print tensorTy3\n\ndef tensorTy4 := [mlir_type| tensor<* \u00d7 f32>]\n#print tensorTy4\n\n-- Basic coercion builtin \u2192 builtin + empty\nexample : MLIRType (builtin + Dialect.empty) := [mlir_type| tensor<* \u00d7 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 \u2190 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 \u00d7 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 $(\u27e8x\u27e9))\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 $(\u27e8t\u27e9))\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 \u2192 builtin\nexample : AttrValue builtin := [mlir_attr_val| \"foo\"]\n-- Uses dialect coercion: empty \u2192 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 $(\u27e8x\u27e9) (MLIRType.float 64))\n| `([mlir_attr_val| $x:scientific : $t:mlir_type]) => `(AttrValue.float $(\u27e8x\u27e9) [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 \u00d7 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 \u2194 resType=.unit`\n        let res \u2190 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 \u2190 quoteMList (\u2190 operands.mapM id) (\u2190 `(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 \u2190   `([([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 \u2190 quoteMList (\u2190 operands.mapM id) (\u2190 `(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 \u00d7 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 \u2190 args.getElems.mapM (fun x => `([mlir_bb_operand| $x]))\n     let bbargs \u2190 quoteMList bbargs.toList (\u2190 `(MLIR.AST.SSAVal \u00d7 MLIR.AST.MLIRType _))\n     -- Make the entry block (the only block)\n     let rgn \u2190 `(Region.mk \"entry\" $bbargs [mlir_ops| $ops])\n\n     -- Make the function signature\n     let argTypes \u2190 args.getElems.mapM (fun x => `(Prod.snd [mlir_bb_operand| $x]))\n     let argTypes \u2190 quoteMList argTypes.toList (\u2190 `(MLIR.AST.MLIRType _))\n     let retType \u2190 match ret with\n       | none => `(MLIRType.tuple [])\n       | some \u03c4 => `([mlir_type| $\u03c4])\n     let signature \u2190 `(MLIRType.fn (MLIRType.tuple $argTypes) $retType)\n\n     -- Make the entire operation\n     let attrs \u2190 `(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\u00d73\u00d7i32>]\n#print memrefTy0\n\ndef memrefTy1 := [mlir_type| memref<i32>]\n#print memrefTy1\n\ndef memrefTy2 := [mlir_type| memref<2 \u00d7 4 \u00d7 i8, #map1>]\n#print memrefTy2\n\ndef memrefTy3 := [mlir_type| memref<2 \u00d7 4 \u00d7 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\" \"<\"  \"*\" \"\u00d7\" mlir_type (\",\" mlir_attr_val)?  \">\"  : mlir_type\nsyntax \"memref\" \"<*\" \"\u00d7\" mlir_type (\",\" mlir_attr_val)?  \">\"  : mlir_type\nmacro_rules\n| `([mlir_type| memref < * \u00d7 $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 <* \u00d7 $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<* \u00d7 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 evaluation\nimport utils\n\nnamespace openai\n\nsection openai_api\n\nmeta structure CompletionRequest : Type :=\n(prompt : string)\n(max_tokens : int := 16)\n(temperature : native.float := 1.0)\n(top_p : native.float := 1)\n(n : int := 1)\n(best_of : option int := none)\n(stream : option bool := none)\n(logprobs : option int := none)\n(echo : option bool := none)\n(stop : option string := none) -- TODO(jesse): list string\n(presence_penalty : option native.float := none)\n(frequency_penalty : option native.float := none)\n(show_trace : bool := ff)\n-- don't support logit_bias for now\n\n-- TODO(jesse): write a derive handler for this kind of structure serialization\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 \u2192 bool := \u03bb n, n \u2264 2048 in\nlet validate_float_frac : native.float \u2192 bool := \u03bb k, 0 \u2264 k \u2227 k \u2264 1 in\nlet validate_and_return {\u03b1} (pred : \u03b1 \u2192 bool) : \u03b1 \u2192 tactic \u03b1 :=\n  \u03bb a, ((guard $ pred a) *> pure a <|> tactic.fail \"[openai.CompletionRequest.to_tactic_json] VALIDATION FAILED\") in\nlet validate_optional_and_return {\u03b1} (pred : \u03b1 \u2192 bool) : option \u03b1 \u2192 tactic (option \u03b1) := \u03bb x, do {\n  match x with\n  | (some val) := some <$> validate_and_return pred val\n  | none := pure none\n  end\n} in\nlet MAX_N : int := 100000 in\nlet fn : CompletionRequest \u2192 tactic json := \u03bb req, match req with\n| \u27e8prompt, max_tokens, temperature, top_p, n, best_of,\n  stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _\u27e9 := do\n\n-- TODO(jesse): ensure validation does not fail silently\n  max_tokens \u2190 validate_and_return validate_max_tokens max_tokens,\n  -- temperature \u2190 validate_and_return validate_float_frac temperature,\n  top_p \u2190 validate_and_return validate_float_frac top_p,\n  n \u2190 validate_and_return (\u03bb x, 0 \u2264 x \u2227 x \u2264 MAX_N) /- go wild with the candidates -/ n,\n  best_of \u2190 validate_optional_and_return (\u03bb x, n \u2264 x \u2227 x \u2264 MAX_N) best_of,\n  presence_penalty \u2190 validate_optional_and_return validate_float_frac presence_penalty,\n  frequency_penalty \u2190 validate_optional_and_return validate_float_frac frequency_penalty,\n\n  let pre_kvs : list (string \u00d7 option json) := [\n    (\"prompt\", json.of_string prompt),\n    (\"max_tokens\", json.of_int max_tokens),\n    (\"temperature\", json.of_float temperature),\n    (\"top_p\", json.of_float top_p),\n    (\"n\", json.of_int n),\n    (\"best_of\", json.of_int <$> best_of),\n    (\"stream\", json.of_bool <$> stream),\n    (\"logprobs\", json.of_int <$> logprobs),\n    (\"echo\", json.of_bool <$> echo),\n    (\"stop\", json.of_string <$> stop),\n    (\"presence_penalty\", json.of_float <$> presence_penalty),\n    (\"frequency_penalty\", json.of_float <$> frequency_penalty)\n  ],\n\n  pure $ json.object $ pre_kvs.filter_map (\u03bb \u27e8k,mv\u27e9, prod.mk k <$> mv)\nend\nin \u27e8fn\u27e9\n\n/-\nexample from API docs:\ncurl https://api.openai.com/v1/engines/davinci/completions \\\n  -H 'Content-Type: application/json' \\\n  -H 'Authorization: Bearer $OPENAI_API_KEY' \\\n  -d '{\n  \"prompt\": \"Once upon a time\",\n  \"max_tokens\": 5\n}'\n-/\nmeta def dummy_cr : CompletionRequest :=\n{prompt := \"Once upon a time\", max_tokens := 5, temperature := 1.0, top_p := 1.0, n := 3}\n\nmeta def CompletionRequest.to_cmd (engine_id : string) (api_key : string) : CompletionRequest \u2192 io (io.process.spawn_args)\n| req@\u27e8prompt, max_tokens, temperature, top_p, n, best_of,\n  stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _\u27e9 := do\nwhen EVAL_TRACE $ io.put_str_ln' format!\"[openai.CompletionRequest.to_cmd] ENTERING\",\nserialized_req \u2190 io.run_tactic' $ has_to_tactic_json.to_tactic_json req,\nwhen EVAL_TRACE $ io.put_str_ln' format!\"[openai.CompletionRequest.to_cmd] SERIALIZED\",\npure {\n  cmd := \"curl\",\n  args := [\n         \"-u\"\n      , format.to_string $ format!\":{api_key}\"\n      ,  \"-X\"\n      , \"POST\"\n--      ,  format.to_string format!\"http://router.api.svc.owl.sci.openai.org:5004/v1/engines/{engine_id}/completions\"\n      ,  format.to_string format!\"https://api.openai.com/v1/engines/{engine_id}/completions\"\n      , \"-H\", \"OpenAI-Organization: org-kuQ09yewcuHU5GN5YYEUp2hh\"\n      , \"-H\", \"Content-Type: application/json\"\n      , \"-d\"\n      , json.unparse serialized_req\n    ]\n}\n\nsetup_tactic_parser\n\n-- nice, it works\n-- example {p q} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   apply and.intro, do {tactic.read >>= postprocess_tactic_state >>= eval_trace}\n-- end\n\nmeta def serialize_ts\n  (req : CompletionRequest)\n  : tactic_state \u2192 tactic CompletionRequest := \u03bb ts, do {\n  ts_str \u2190 postprocess_tactic_state ts,\n  let prompt : string :=\n    \"[LN] GOAL \" ++ ts_str ++ \" PROOFSTEP\",\n  eval_trace format!\"\\n \\n \\n PROMPT: {prompt} \\n \\n \\n \",\n  pure {\n    prompt := prompt,\n    ..req}\n}\n\nsetup_tactic_parser\n\nmeta def openai_api (engine_id : string) (api_key : string) : ModelAPI CompletionRequest :=\nlet fn : CompletionRequest \u2192 io json := \u03bb req, do {\n  proc_cmds \u2190 req.to_cmd engine_id api_key,\n  -- when req.show_trace $ io.put_str_ln' format!\"[openai_api] PROC_CMDS: {proc_cmds}\",\n  response_raw \u2190 io.cmd proc_cmds,\n  when req.show_trace $ io.put_str_ln' format!\"[openai_api] RAW RESPONSE: {response_raw}\",\n\n  response_msg \u2190 (lift_option $ json.parse response_raw) | io.fail' format!\"[openai_api] JSON PARSE FAILED {response_raw}\",\n  (do predictions \u2190 (lift_option $ do\n    { (json.array choices) \u2190 response_msg.lookup \"choices\" | none,\n      /- `choices` is a list of {text: ..., index: ..., logprobs: ..., finish_reason: ...}-/\n      texts \u2190 choices.mmap (\u03bb choice, choice.lookup \"text\"),\n      pure texts\n  }) | io.fail' format!\"[openai_api] UNEXPECTED RESPONSE MSG: {response_msg}\",\n  when req.show_trace $ 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 \u27e8fn\u27e9\n\nend openai_api\n\nsection openai_proof_search\n\nmeta def read_first_line : string \u2192 io string := \u03bb path, do\n  buffer.to_string <$> (io.mk_file_handle path io.mode.read >>= io.fs.get_line)\n\n-- in entry point, API key is read from command line and then set as an environment variable for the execution\n-- of the command\n\n@[inline, reducible]meta def tab : char := '\\t'\n\n@[inline, reducible]meta def newline : char := '\\n'\n\nmeta def default_partial_req : openai.CompletionRequest :=\n{\n  prompt := \"\",\n  max_tokens := 128,\n  temperature := (0.7 : native.float),\n  top_p := 1,\n  n := 1,\n  best_of := none,\n  stream := none,\n  logprobs := none,\n  echo := none,\n  stop := none, -- TODO(jesse): list string,\n  presence_penalty := none,\n  frequency_penalty := none,\n  show_trace := EVAL_TRACE\n}\n\n/- this is the entry point for the evalution harness -/\nmeta def openai_greedy_proof_search_core\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  : state_t GreedyProofSearchState tactic unit := do\nmonad_lift $ set_show_eval_trace partial_req.show_trace,\ngreedy_proof_search_core\n  (openai_api engine_id api_key)\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_best_beam_candidate (unwrap_lm_response $ some \"[openai_greedy_proof_search_core]\") msg n)\n        (fuel)\n\n/- meant for interactive use -/\nmeta def openai_greedy_proof_search\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  (verbose := ff)\n  : tactic unit := do\nset_show_eval_trace partial_req.show_trace,\ngreedy_proof_search\n  (openai_api engine_id api_key)\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_best_beam_candidate (unwrap_lm_response $ some \"[openai_greedy_proof_search]\") msg n)\n        (fuel)\n          (verbose)\n\nend openai_proof_search\n\nsection playground\n\n-- example : true :=\n-- begin\n--   openai_greedy_proof_search\n--     default_partial_req\n--       \"formal-large-lean-webmath-1230-v1-c4\"\n--         API_KEY\n-- end\n\n-- example (n : \u2115) (m : \u2115) : nat.succ (n + m) < (nat.succ n + m) + 1  :=\n-- begin\n--   -- openai_greedy_proof_search\n--   --   {n := 10, temperature := 0.7, ..default_partial_req}\n--   --     \"formal-large-lean-webmath-1230-v1-c4\"\n--   --       API_KEY 10 tt,\n-- sorry\n-- -- rw succ_add,  exact nat.lt_succ_self _\n-- end\n\n-- theorem t2 (p q r : Prop) (h\u2081 : p) (h\u2082 : q) : (q \u2227 p) \u2228 r :=\n\n-- lemma peirce_identity {P Q :Prop} : ((P \u2192 Q) \u2192 P) \u2192 P :=\n-- begin\n--   openai_greedy_proof_search\n--     {n := 25, temperature := 0.7, ..default_partial_req}\n--       \"formal-large-lean-webmath-1230-v1-c4\"\n--         API_KEY 10,\n-- end\n\n-- --   openai_greedy_proof_search\n-- --     default_partial_req\n-- --       \"formal-large-lean-webmath-1230-v1-c4\"\n-- --         API_KEY\n-- -- -- simp [or_assoc, or_comm, or_left_comm]\n\n-- end\n\nend playground\n\nend openai\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/openai.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.1347759243735362, "lm_q2_score": 0.025565212531223618, "lm_q1q2_score": 0.0034455751507015742}}
{"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 and Sebastian Ullrich\n\nAdditional goodies for writing macros\n-/\nprelude\nimport Init.Data.Array.Basic\nimport Init.Data.Option.BasicAux\n\nnamespace Lean\n\n@[extern c inline \"lean_box(LEAN_VERSION_MAJOR)\"]\nprivate opaque version.getMajor (u : Unit) : Nat\ndef version.major : Nat := version.getMajor ()\n\n@[extern c inline \"lean_box(LEAN_VERSION_MINOR)\"]\nprivate opaque version.getMinor (u : Unit) : Nat\ndef version.minor : Nat := version.getMinor ()\n\n@[extern c inline \"lean_box(LEAN_VERSION_PATCH)\"]\nprivate opaque version.getPatch (u : Unit) : Nat\ndef version.patch : Nat := version.getPatch ()\n\n@[extern \"lean_get_githash\"]\nopaque getGithash (u : Unit) : String\ndef githash : String := getGithash ()\n\n@[extern c inline \"LEAN_VERSION_IS_RELEASE\"]\nopaque version.getIsRelease (u : Unit) : Bool\ndef version.isRelease : Bool := version.getIsRelease ()\n\n/-- Additional version description like \"nightly-2018-03-11\" -/\n@[extern c inline \"lean_mk_string(LEAN_SPECIAL_VERSION_DESC)\"]\nopaque version.getSpecialDesc (u : Unit) : String\ndef version.specialDesc : String := version.getSpecialDesc ()\n\ndef versionStringCore :=\n  toString version.major ++ \".\" ++ toString version.minor ++ \".\" ++ toString version.patch\n\ndef versionString :=\n  if version.specialDesc \u2260 \"\" then\n    versionStringCore ++ \"-\" ++ version.specialDesc\n  else if version.isRelease then\n    versionStringCore\n  else\n    versionStringCore ++ \", commit \" ++ githash\n\ndef origin :=\n  \"leanprover/lean4\"\n\ndef toolchain :=\n  if version.specialDesc \u2260 \"\"  then\n    if version.isRelease then\n      origin ++ \":\" ++ versionStringCore ++ \"-\" ++ version.specialDesc\n    else\n      origin ++ \":\" ++ version.specialDesc\n  else if version.isRelease then\n    origin ++ \":\" ++ versionStringCore\n  else\n    \"\"\n\n@[extern c inline \"LEAN_IS_STAGE0\"]\nopaque Internal.isStage0 (u : Unit) : Bool\n\n/-- Valid identifier names -/\ndef isGreek (c : Char) : Bool :=\n  0x391 \u2264 c.val && c.val \u2264 0x3dd\n\ndef isLetterLike (c : Char) : Bool :=\n  (0x3b1  \u2264 c.val && c.val \u2264 0x3c9 && c.val \u2260 0x3bb) ||                  -- Lower greek, but lambda\n  (0x391  \u2264 c.val && c.val \u2264 0x3A9 && c.val \u2260 0x3A0 && c.val \u2260 0x3A3) || -- Upper greek, but Pi and Sigma\n  (0x3ca  \u2264 c.val && c.val \u2264 0x3fb) ||                                   -- Coptic letters\n  (0x1f00 \u2264 c.val && c.val \u2264 0x1ffe) ||                                  -- Polytonic Greek Extended Character Set\n  (0x2100 \u2264 c.val && c.val \u2264 0x214f) ||                                  -- Letter like block\n  (0x1d49c \u2264 c.val && c.val \u2264 0x1d59f)                                   -- Latin letters, Script, Double-struck, Fractur\n\ndef isNumericSubscript (c : Char) : Bool :=\n  0x2080 \u2264 c.val && c.val \u2264 0x2089\n\ndef isSubScriptAlnum (c : Char) : Bool :=\n  isNumericSubscript c ||\n  (0x2090 \u2264 c.val && c.val \u2264 0x209c) ||\n  (0x1d62 \u2264 c.val && c.val \u2264 0x1d6a)\n\ndef isIdFirst (c : Char) : Bool :=\n  c.isAlpha || c = '_' || isLetterLike c\n\ndef isIdRest (c : Char) : Bool :=\n  c.isAlphanum || c = '_' || c = '\\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c\n\ndef idBeginEscape := '\u00ab'\ndef idEndEscape   := '\u00bb'\ndef isIdBeginEscape (c : Char) : Bool := c = idBeginEscape\ndef isIdEndEscape (c : Char) : Bool := c = idEndEscape\n\nnamespace Name\n\ndef getRoot : Name \u2192 Name\n  | anonymous             => anonymous\n  | n@(str anonymous _) => n\n  | n@(num anonymous _) => n\n  | str n _             => getRoot n\n  | num n _             => getRoot n\n\n@[export lean_is_inaccessible_user_name]\ndef isInaccessibleUserName : Name \u2192 Bool\n  | Name.str _ s   => s.contains '\u271d' || s == \"_inaccessible\"\n  | Name.num p _   => isInaccessibleUserName p\n  | _              => false\n\ndef escapePart (s : String) : Option String :=\n  if s.length > 0 && isIdFirst (s.get 0) && (s.toSubstring.drop 1).all isIdRest then s\n  else if s.any isIdEndEscape then none\n  else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString\n\n-- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape`\nvariable (sep : String) (escape : Bool)\ndef toStringWithSep : Name \u2192 String\n  | anonymous       => \"[anonymous]\"\n  | str anonymous s => maybeEscape s\n  | num anonymous v => toString v\n  | str n s         => toStringWithSep n ++ sep ++ maybeEscape s\n  | num n v         => toStringWithSep n ++ sep ++ Nat.repr v\nwhere\n  maybeEscape s := if escape then escapePart s |>.getD s else s\n\nprotected def toString (n : Name) (escape := true) : String :=\n  -- never escape \"prettified\" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator\n  toStringWithSep \".\" (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n\nwhere\n  maybePseudoSyntax :=\n    if let .str _ s := n.getRoot then\n      -- could be pseudo-syntax for loose bvar or universe mvar, output as is\n      \"#\".isPrefixOf s || \"?\".isPrefixOf s\n    else\n      false\n\ninstance : ToString Name where\n  toString n := n.toString\n\nprivate def hasNum : Name \u2192 Bool\n  | anonymous => false\n  | num ..    => true\n  | str p ..  => hasNum p\n\nprotected def reprPrec (n : Name) (prec : Nat) : Std.Format :=\n  match n with\n  | anonymous => Std.Format.text \"Lean.Name.anonymous\"\n  | num p i => Repr.addAppParen (\"Lean.Name.mkNum \" ++ Name.reprPrec p max_prec ++ \" \" ++ repr i) prec\n  | str p s =>\n    if p.hasNum then\n      Repr.addAppParen (\"Lean.Name.mkStr \" ++ Name.reprPrec p max_prec ++ \" \" ++ repr s) prec\n    else\n      Std.Format.text \"`\" ++ n.toString\n\ninstance : Repr Name where\n  reprPrec := Name.reprPrec\n\ndef capitalize : Name \u2192 Name\n  | .str p s => .str p s.capitalize\n  | n        => n\n\ndef replacePrefix : Name \u2192 Name \u2192 Name \u2192 Name\n  | anonymous,   anonymous, newP => newP\n  | anonymous,   _,         _    => anonymous\n  | n@(str p s), queryP,    newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s\n  | n@(num p s), queryP,    newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s\n\n/--\n  `eraseSuffix? n s` return `n'` if `n` is of the form `n == n' ++ s`.\n-/\ndef eraseSuffix? : Name \u2192 Name \u2192 Option Name\n  | n,       anonymous => some n\n  | str p s, str p' s' => if s == s' then eraseSuffix? p p' else none\n  | num p s, num p' s' => if s == s' then eraseSuffix? p p' else none\n  | _,       _         => none\n\n/-- Remove macros scopes, apply `f`, and put them back -/\n@[inline] def modifyBase (n : Name) (f : Name \u2192 Name) : Name :=\n  if n.hasMacroScopes then\n    let view := extractMacroScopes n\n    { view with name := f view.name }.review\n  else\n    f n\n\n@[export lean_name_append_after]\ndef appendAfter (n : Name) (suffix : String) : Name :=\n  n.modifyBase fun\n    | str p s => Name.mkStr p (s ++ suffix)\n    | n       => Name.mkStr n suffix\n\n@[export lean_name_append_index_after]\ndef appendIndexAfter (n : Name) (idx : Nat) : Name :=\n  n.modifyBase fun\n    | str p s => Name.mkStr p (s ++ \"_\" ++ toString idx)\n    | n       => Name.mkStr n (\"_\" ++ toString idx)\n\n@[export lean_name_append_before]\ndef appendBefore (n : Name) (pre : String) : Name :=\n  n.modifyBase fun\n    | anonymous => Name.mkStr anonymous pre\n    | str p s => Name.mkStr p (pre ++ s)\n    | num p n => Name.mkNum (Name.mkStr p pre) n\n\nprotected theorem beq_iff_eq {m n : Name} : m == n \u2194 m = n := by\n  show m.beq n \u2194 _\n  induction m generalizing n <;> cases n <;> simp_all [Name.beq, And.comm]\n\ninstance : LawfulBEq Name where\n  eq_of_beq := Name.beq_iff_eq.1\n  rfl := Name.beq_iff_eq.2 rfl\n\ninstance : DecidableEq Name :=\n  fun a b => if h : a == b then .isTrue (by simp_all) else .isFalse (by simp_all)\n\nend Name\n\nstructure NameGenerator where\n  namePrefix : Name := `_uniq\n  idx        : Nat  := 1\n  deriving Inhabited\n\nnamespace NameGenerator\n\n@[inline] def curr (g : NameGenerator) : Name :=\n  Name.mkNum g.namePrefix g.idx\n\n@[inline] def next (g : NameGenerator) : NameGenerator :=\n  { g with idx := g.idx + 1 }\n\n@[inline] def mkChild (g : NameGenerator) : NameGenerator \u00d7 NameGenerator :=\n  ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 },\n   { g with idx := g.idx + 1 })\n\nend NameGenerator\n\nclass MonadNameGenerator (m : Type \u2192 Type) where\n  getNGen : m NameGenerator\n  setNGen : NameGenerator \u2192 m Unit\n\nexport MonadNameGenerator (getNGen setNGen)\n\ndef mkFreshId {m : Type \u2192 Type} [Monad m] [MonadNameGenerator m] : m Name := do\n  let ngen \u2190 getNGen\n  let r := ngen.curr\n  setNGen ngen.next\n  pure r\n\ninstance monadNameGeneratorLift (m n : Type \u2192 Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := {\n  getNGen := liftM (getNGen : m _),\n  setNGen := fun ngen => liftM (setNGen ngen : m _)\n}\n\nnamespace Syntax\n\nderiving instance Repr for Syntax.Preresolved\nderiving instance Repr for Syntax\nderiving instance Repr for TSyntax\n\nabbrev Term := TSyntax `term\nabbrev Command := TSyntax `command\nprotected abbrev Level := TSyntax `level\nprotected abbrev Tactic := TSyntax `tactic\nabbrev Prec := TSyntax `prec\nabbrev Prio := TSyntax `prio\nabbrev Ident := TSyntax identKind\nabbrev StrLit := TSyntax strLitKind\nabbrev CharLit := TSyntax charLitKind\nabbrev NameLit := TSyntax nameLitKind\nabbrev ScientificLit := TSyntax scientificLitKind\nabbrev NumLit := TSyntax numLitKind\n\nend Syntax\n\nexport Syntax (Term Command Prec Prio Ident StrLit CharLit NameLit ScientificLit NumLit)\n\nnamespace TSyntax\n\ninstance : Coe (TSyntax [k]) (TSyntax (k :: ks)) where\n  coe stx := \u27e8stx\u27e9\n\ninstance : Coe (TSyntax ks) (TSyntax (k' :: ks)) where\n  coe stx := \u27e8stx\u27e9\n\ninstance : Coe Ident Term where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : CoeDep Term \u27e8Syntax.ident info ss n res\u27e9 Ident where\n  coe := \u27e8Syntax.ident info ss n res\u27e9\n\ninstance : Coe StrLit Term where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe NameLit Term where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe ScientificLit Term where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe NumLit Term where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe CharLit Term where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe Ident Syntax.Level where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe NumLit Prio where\n  coe s := \u27e8s.raw\u27e9\n\ninstance : Coe NumLit Prec where\n  coe s := \u27e8s.raw\u27e9\n\nnamespace Compat\n\nscoped instance : CoeTail Syntax (TSyntax k) where\n  coe s := \u27e8s\u27e9\n\nscoped instance : CoeTail (Array Syntax) (TSyntaxArray k) where\n  coe := .mk\n\nend Compat\n\nend TSyntax\n\nnamespace Syntax\n\nderiving instance BEq for Syntax.Preresolved\n\n/-- Compare syntax structures modulo source info. -/\npartial def structEq : Syntax \u2192 Syntax \u2192 Bool\n  | Syntax.missing, Syntax.missing => true\n  | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq\n  | Syntax.atom _ val, Syntax.atom _ val' => val == val'\n  | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved'\n  | _, _ => false\n\ninstance : BEq Lean.Syntax := \u27e8structEq\u27e9\ninstance : BEq (Lean.TSyntax k) := \u27e8(\u00b7.raw == \u00b7.raw)\u27e9\n\npartial def getTailInfo? : Syntax \u2192 Option SourceInfo\n  | atom info _   => info\n  | ident info .. => info\n  | node SourceInfo.none _ args =>\n      args.findSomeRev? getTailInfo?\n  | node info _ _    => info\n  | _             => none\n\ndef getTailInfo (stx : Syntax) : SourceInfo :=\n  stx.getTailInfo?.getD SourceInfo.none\n\ndef getTrailingSize (stx : Syntax) : Nat :=\n  match stx.getTailInfo? with\n  | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize\n  | _ => 0\n\n/--\n  Return substring of original input covering `stx`.\n  Result is meaningful only if all involved `SourceInfo.original`s refer to the same string (as is the case after parsing). -/\ndef getSubstring? (stx : Syntax) (withLeading := true) (withTrailing := true) : Option Substring :=\n  match stx.getHeadInfo, stx.getTailInfo with\n  | SourceInfo.original lead startPos _ _, SourceInfo.original _ _ trail stopPos =>\n    some {\n      str      := lead.str\n      startPos := if withLeading then lead.startPos else startPos\n      stopPos  := if withTrailing then trail.stopPos else stopPos\n    }\n  | _, _ => none\n\n@[specialize] private partial def updateLast {\u03b1} [Inhabited \u03b1] (a : Array \u03b1) (f : \u03b1 \u2192 Option \u03b1) (i : Nat) : Option (Array \u03b1) :=\n  if i == 0 then\n    none\n  else\n    let i := i - 1\n    let v := a[i]!\n    match f v with\n    | some v => some <| a.set! i v\n    | none   => updateLast a f i\n\npartial def setTailInfoAux (info : SourceInfo) : Syntax \u2192 Option Syntax\n  | atom _ val             => some <| atom info val\n  | ident _ rawVal val pre => some <| ident info rawVal val pre\n  | node info k args       =>\n    match updateLast args (setTailInfoAux info) args.size with\n    | some args => some <| node info k args\n    | none      => none\n  | _                      => none\n\ndef setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax :=\n  match setTailInfoAux info stx with\n  | some stx => stx\n  | none     => stx\n\ndef unsetTrailing (stx : Syntax) : Syntax :=\n  match stx.getTailInfo with\n  | SourceInfo.original lead pos _ endPos => stx.setTailInfo (SourceInfo.original lead pos \"\".toSubstring endPos)\n  | _                                     => stx\n\n@[specialize] private partial def updateFirst {\u03b1} [Inhabited \u03b1] (a : Array \u03b1) (f : \u03b1 \u2192 Option \u03b1) (i : Nat) : Option (Array \u03b1) :=\n  if h : i < a.size then\n    let v := a[i]\n    match f v with\n    | some v => some <| a.set \u27e8i, h\u27e9 v\n    | none   => updateFirst a f (i+1)\n  else\n    none\n\npartial def setHeadInfoAux (info : SourceInfo) : Syntax \u2192 Option Syntax\n  | atom _ val             => some <| atom info val\n  | ident _ rawVal val pre => some <| ident info rawVal val pre\n  | node i k args          =>\n    match updateFirst args (setHeadInfoAux info) 0 with\n    | some args => some <| node i k args\n    | _         => none\n  | _                      => none\n\ndef setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax :=\n  match setHeadInfoAux info stx with\n  | some stx => stx\n  | none     => stx\n\ndef setInfo (info : SourceInfo) : Syntax \u2192 Syntax\n  | atom _ val             => atom info val\n  | ident _ rawVal val pre => ident info rawVal val pre\n  | node _ kind args       => node info kind args\n  | missing                => missing\n\n/-- Return the first atom/identifier that has position information -/\npartial def getHead? : Syntax \u2192 Option Syntax\n  | stx@(atom info ..)  => info.getPos?.map fun _ => stx\n  | stx@(ident info ..) => info.getPos?.map fun _ => stx\n  | node SourceInfo.none _ args => args.findSome? getHead?\n  | stx@(node ..) => stx\n  | _ => none\n\ndef copyHeadTailInfoFrom (target source : Syntax) : Syntax :=\n  target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo\n\n/-- Ensure head position is synthetic. The server regards syntax as \"original\" only if both head and tail info are `original`. -/\ndef mkSynthetic (stx : Syntax) : Syntax :=\n  stx.setHeadInfo (SourceInfo.fromRef stx)\n\nend Syntax\n\n/-- Use the head atom/identifier of the current `ref` as the `ref` -/\n@[inline] def withHeadRefOnly {m : Type \u2192 Type} [Monad m] [MonadRef m] {\u03b1} (x : m \u03b1) : m \u03b1 := do\n  match (\u2190 getRef).getHead? with\n  | none => x\n  | some ref => withRef ref x\n\n/-- Syntax objects for a Lean module. -/\nstructure Module where\n  header   : Syntax\n  commands : Array Syntax\n\n/--\n  Expand macros in the given syntax.\n  A node with kind `k` is visited only if `p k` is true.\n\n  Note that the default value for `p` returns false for `by ...` nodes.\n  This is a \"hack\". The tactic framework abuses the macro system to implement extensible tactics.\n  For example, one can define\n  ```lean\n  syntax \"my_trivial\" : tactic -- extensible tactic\n\n  macro_rules | `(tactic| my_trivial) => `(tactic| decide)\n  macro_rules | `(tactic| my_trivial) => `(tactic| assumption)\n  ```\n  When the tactic evaluator finds the tactic `my_trivial`, it tries to evaluate the `macro_rule` expansions\n  until one \"works\", i.e., the macro expansion is evaluated without producing an exception.\n  We say this solution is a bit hackish because the term elaborator may invoke `expandMacros` with `(p := fun _ => true)`,\n  and expand the tactic macros as just macros. In the example above, `my_trivial` would be replaced with `assumption`,\n  `decide` would not be tried if `assumption` fails at tactic evaluation time.\n\n  We are considering two possible solutions for this issue:\n  1- A proper extensible tactic feature that does not rely on the macro system.\n\n  2- Typed macros that know the syntax categories they're working in. Then, we would be able to select which\n     syntatic categories are expanded by `expandMacros`.\n-/\npartial def expandMacros (stx : Syntax) (p : SyntaxNodeKind \u2192 Bool := fun k => k != `Lean.Parser.Term.byTactic) : MacroM Syntax :=\n  withRef stx do\n    match stx with\n    | .node info k args => do\n      if p k then\n        match (\u2190 expandMacro? stx) with\n        | some stxNew => expandMacros stxNew\n        | none        => do\n          let args \u2190 Macro.withIncRecDepth stx <| args.mapM expandMacros\n          return .node info k args\n      else\n        return stx\n    | stx => return stx\n\n/-! # Helper functions for processing Syntax programmatically -/\n\n/--\n  Create an identifier copying the position from `src`.\n  To refer to a specific constant, use `mkCIdentFrom` instead. -/\ndef mkIdentFrom (src : Syntax) (val : Name) (canonical := false) : Ident :=\n  \u27e8Syntax.ident (SourceInfo.fromRef src canonical) (toString val).toSubstring val []\u27e9\n\ndef mkIdentFromRef [Monad m] [MonadRef m] (val : Name) (canonical := false) : m Ident := do\n  return mkIdentFrom (\u2190 getRef) val canonical\n\n/--\n  Create an identifier referring to a constant `c` copying the position from `src`.\n  This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally\n  be captured. -/\ndef mkCIdentFrom (src : Syntax) (c : Name) (canonical := false) : Ident :=\n  -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend\n  let id   := addMacroScope `_internal c reservedMacroScope\n  \u27e8Syntax.ident (SourceInfo.fromRef src canonical) (toString id).toSubstring id [.decl c []]\u27e9\n\ndef mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) (canonical := false) : m Syntax := do\n  return mkCIdentFrom (\u2190 getRef) c canonical\n\ndef mkCIdent (c : Name) : Ident :=\n  mkCIdentFrom Syntax.missing c\n\n@[export lean_mk_syntax_ident]\ndef mkIdent (val : Name) : Ident :=\n  \u27e8Syntax.ident SourceInfo.none (toString val).toSubstring val []\u27e9\n\n@[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax :=\n  mkNode groupKind args\n\ndef mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := Id.run do\n  let mut i := 0\n  let mut r := #[]\n  for a in as do\n    if i > 0 then\n      r := r.push sep |>.push a\n    else\n      r := r.push a\n    i := i + 1\n  return r\n\ndef mkOptionalNode (arg : Option Syntax) : Syntax :=\n  match arg with\n  | some arg => mkNullNode #[arg]\n  | none     => mkNullNode #[]\n\ndef mkHole (ref : Syntax) (canonical := false) : Syntax :=\n  mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref \"_\" canonical]\n\nnamespace Syntax\n\ndef mkSep (a : Array Syntax) (sep : Syntax) : Syntax :=\n  mkNullNode <| mkSepArray a sep\n\ndef SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep :=\n\u27e8mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtom sep)\u27e9\n\ndef SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do\n  let ref \u2190 getRef;\n  return \u27e8mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtomFrom ref sep)\u27e9\n\ninstance : Coe (Array Syntax) (SepArray sep) where\n  coe := SepArray.ofElems\n\ninstance : Coe (TSyntaxArray k) (TSepArray k sep) where\n  coe a := \u27e8mkSepArray a.raw (mkAtom sep)\u27e9\n\n/-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/\ndef mkApp (fn : Term) : (args : TSyntaxArray `term) \u2192 Term\n  | #[]  => fn\n  | args => \u27e8mkNode `Lean.Parser.Term.app #[fn, mkNullNode args.raw]\u27e9\n\ndef mkCApp (fn : Name) (args : TSyntaxArray `term) : Term :=\n  mkApp (mkCIdent fn) args\n\ndef mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : TSyntax kind :=\n  let atom : Syntax := Syntax.atom info val\n  mkNode kind #[atom]\n\ndef mkStrLit (val : String) (info := SourceInfo.none) : StrLit :=\n  mkLit strLitKind (String.quote val) info\n\ndef mkNumLit (val : String) (info := SourceInfo.none) : NumLit :=\n  mkLit numLitKind val info\n\ndef mkScientificLit (val : String) (info := SourceInfo.none) : TSyntax scientificLitKind :=\n  mkLit scientificLitKind val info\n\ndef mkNameLit (val : String) (info := SourceInfo.none) : NameLit :=\n  mkLit nameLitKind val info\n\n/-! Recall that we don't have special Syntax constructors for storing numeric and string atoms.\n   The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or\n   different ways of representing them. So, our atoms contain just the parsed string.\n   The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded\n   in binary, octal, decimal and hexadecimal format. `isNatLit` implements a \"decoder\"\n   for Syntax objects representing these numerals. -/\n\nprivate partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat :=\n  if s.atEnd i then some val\n  else\n    let c := s.get i\n    if c == '0' then decodeBinLitAux s (s.next i) (2*val)\n    else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1)\n    else none\n\nprivate partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat :=\n  if s.atEnd i then some val\n  else\n    let c := s.get i\n    if '0' \u2264 c && c \u2264 '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat)\n    else none\n\nprivate def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat \u00d7 String.Pos) :=\n  let c := s.get i\n  let i := s.next i\n  if '0' \u2264 c && c \u2264 '9' then some (c.toNat - '0'.toNat, i)\n  else if 'a' \u2264 c && c \u2264 'f' then some (10 + c.toNat - 'a'.toNat, i)\n  else if 'A' \u2264 c && c \u2264 'F' then some (10 + c.toNat - 'A'.toNat, i)\n  else none\n\nprivate partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat :=\n  if s.atEnd i then some val\n  else match decodeHexDigit s i with\n    | some (d, i) => decodeHexLitAux s i (16*val + d)\n    | none        => none\n\nprivate partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat :=\n  if s.atEnd i then some val\n  else\n    let c := s.get i\n    if '0' \u2264 c && c \u2264 '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat)\n    else none\n\ndef decodeNatLitVal? (s : String) : Option Nat :=\n  let len := s.length\n  if len == 0 then none\n  else\n    let c := s.get 0\n    if c == '0' then\n      if len == 1 then some 0\n      else\n        let c := s.get \u27e81\u27e9\n        if c == 'x' || c == 'X' then decodeHexLitAux s \u27e82\u27e9 0\n        else if c == 'b' || c == 'B' then decodeBinLitAux s \u27e82\u27e9 0\n        else if c == 'o' || c == 'O' then decodeOctalLitAux s \u27e82\u27e9 0\n        else if c.isDigit then decodeDecimalLitAux s 0 0\n        else none\n    else if c.isDigit then decodeDecimalLitAux s 0 0\n    else none\n\ndef isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String :=\n  match stx with\n  | Syntax.node _ k args =>\n    if k == litKind && args.size == 1 then\n      match args.get! 0 with\n      | (Syntax.atom _ val) => some val\n      | _ => none\n    else\n      none\n  | _ => none\n\nprivate def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat :=\n  match isLit? litKind stx with\n  | some val => decodeNatLitVal? val\n  | _        => none\n\ndef isNatLit? (s : Syntax) : Option Nat :=\n  isNatLitAux numLitKind s\n\ndef isFieldIdx? (s : Syntax) : Option Nat :=\n  isNatLitAux fieldIdxKind s\n\n/-- Decodes a 'scientific number' string which is consumed by the `OfScientific` class.\n  Takes as input a string such as `123`, `123.456e7` and returns a triple `(n, sign, e)` with value given by\n  `n * 10^-e` if `sign` else `n * 10^e`.\n-/\npartial def decodeScientificLitVal? (s : String) : Option (Nat \u00d7 Bool \u00d7 Nat) :=\n  let len := s.length\n  if len == 0 then none\n  else\n    let c := s.get 0\n    if c.isDigit then\n      decode 0 0\n    else none\nwhere\n  decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat \u00d7 Bool \u00d7 Nat) :=\n    if s.atEnd i then\n      if sign then\n        some (val, sign, exp + e)\n      else if exp >= e then\n        some (val, sign, exp - e)\n      else\n        some (val, true, e - exp)\n    else\n      let c := s.get i\n      if '0' \u2264 c && c \u2264 '9' then\n        decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat)\n      else\n        none\n\n  decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat \u00d7 Bool \u00d7 Nat) :=\n    if s.atEnd i then none else\n    let c := s.get i\n    if c == '-' then\n       decodeAfterExp (s.next i) val e true 0\n    else if c == '+' then\n       decodeAfterExp (s.next i) val e false 0\n    else\n       decodeAfterExp i val e false 0\n\n  decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat \u00d7 Bool \u00d7 Nat) :=\n    if s.atEnd i then\n      some (val, true, e)\n    else\n      let c := s.get i\n      if '0' \u2264 c && c \u2264 '9' then\n        decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1)\n      else if c == 'e' || c == 'E' then\n        decodeExp (s.next i) val e\n      else\n        none\n\n  decode (i : String.Pos) (val : Nat) : Option (Nat \u00d7 Bool \u00d7 Nat) :=\n    if s.atEnd i then\n      none\n    else\n      let c := s.get i\n      if '0' \u2264 c && c \u2264 '9' then\n        decode (s.next i) (10*val + c.toNat - '0'.toNat)\n      else if c == '.' then\n        decodeAfterDot (s.next i) val 0\n      else if c == 'e' || c == 'E' then\n        decodeExp (s.next i) val 0\n      else\n        none\n\ndef isScientificLit? (stx : Syntax) : Option (Nat \u00d7 Bool \u00d7 Nat) :=\n  match isLit? scientificLitKind stx with\n  | some val => decodeScientificLitVal? val\n  | _        => none\n\ndef isIdOrAtom? : Syntax \u2192 Option String\n  | Syntax.atom _ val           => some val\n  | Syntax.ident _ rawVal _ _   => some rawVal.toString\n  | _ => none\n\ndef toNat (stx : Syntax) : Nat :=\n  match stx.isNatLit? with\n  | some val => val\n  | none     => 0\n\ndef decodeQuotedChar (s : String) (i : String.Pos) : Option (Char \u00d7 String.Pos) := do\n  let c := s.get i\n  let i := s.next i\n  if c == '\\\\' then pure ('\\\\', i)\n  else if c = '\\\"' then pure ('\\\"', i)\n  else if c = '\\'' then pure ('\\'', i)\n  else if c = 'r'  then pure ('\\r', i)\n  else if c = 'n'  then pure ('\\n', i)\n  else if c = 't'  then pure ('\\t', i)\n  else if c = 'x'  then\n    let (d\u2081, i) \u2190 decodeHexDigit s i\n    let (d\u2082, i) \u2190 decodeHexDigit s i\n    pure (Char.ofNat (16*d\u2081 + d\u2082), i)\n  else if c = 'u'  then do\n    let (d\u2081, i) \u2190 decodeHexDigit s i\n    let (d\u2082, i) \u2190 decodeHexDigit s i\n    let (d\u2083, i) \u2190 decodeHexDigit s i\n    let (d\u2084, i) \u2190 decodeHexDigit s i\n    pure (Char.ofNat (16*(16*(16*d\u2081 + d\u2082) + d\u2083) + d\u2084), i)\n  else\n    none\n\npartial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := do\n  let c := s.get i\n  let i := s.next i\n  if c == '\\\"' then\n    pure acc\n  else if s.atEnd i then\n    none\n  else if c == '\\\\' then do\n    let (c, i) \u2190 decodeQuotedChar s i\n    decodeStrLitAux s i (acc.push c)\n  else\n    decodeStrLitAux s i (acc.push c)\n\ndef decodeStrLit (s : String) : Option String :=\n  decodeStrLitAux s \u27e81\u27e9 \"\"\n\ndef isStrLit? (stx : Syntax) : Option String :=\n  match isLit? strLitKind stx with\n  | some val => decodeStrLit val\n  | _        => none\n\ndef decodeCharLit (s : String) : Option Char := do\n  let c := s.get \u27e81\u27e9\n  if c == '\\\\' then do\n    let (c, _) \u2190 decodeQuotedChar s \u27e82\u27e9\n    pure c\n  else\n    pure c\n\ndef isCharLit? (stx : Syntax) : Option Char :=\n  match isLit? charLitKind stx with\n  | some val => decodeCharLit val\n  | _        => none\n\nprivate partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring :=\n  let splitRest (ss : Substring) (acc : List Substring) : List Substring :=\n    if ss.front == '.' then\n      splitNameLitAux (ss.drop 1) acc\n    else if ss.isEmpty then\n      acc\n    else\n      []\n  if ss.isEmpty then []\n  else\n    let curr := ss.front\n    if isIdBeginEscape curr then\n      let escapedPart := ss.takeWhile (!isIdEndEscape \u00b7)\n      let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) }\n      if !isIdEndEscape (escapedPart.get <| escapedPart.prev \u27e8escapedPart.bsize\u27e9) then []\n      else splitRest (ss.extract \u27e8escapedPart.bsize\u27e9 \u27e8ss.bsize\u27e9) (escapedPart :: acc)\n    else if isIdFirst curr then\n      let idPart := ss.takeWhile isIdRest\n      splitRest (ss.extract \u27e8idPart.bsize\u27e9 \u27e8ss.bsize\u27e9) (idPart :: acc)\n    else if curr.isDigit then\n      let idPart := ss.takeWhile Char.isDigit\n      splitRest (ss.extract \u27e8idPart.bsize\u27e9 \u27e8ss.bsize\u27e9) (idPart :: acc)\n    else\n      []\n\n/-- Split a name literal (without the backtick) into its dot-separated components. For example,\n`foo.bla.\u00abbo.o\u00bb` \u21a6 `[\"foo\", \"bla\", \"\u00abbo.o\u00bb\"]`. If the literal cannot be parsed, return `[]`. -/\ndef splitNameLit (ss : Substring) : List Substring :=\n  splitNameLitAux ss [] |>.reverse\n\ndef decodeNameLit (s : String) : Option Name :=\n  if s.get 0 == '`' then\n    match splitNameLitAux (s.toSubstring.drop 1) [] with\n    | [] => none\n    | comps => some <| comps.foldr (init := Name.anonymous)\n      fun comp n =>\n        let comp := comp.toString\n        if isIdBeginEscape comp.front then\n          Name.mkStr n (comp.drop 1 |>.dropRight 1)\n        else if comp.front.isDigit then\n          if let some k := decodeNatLitVal? comp then\n            Name.mkNum n k\n          else\n            unreachable!\n        else\n          Name.mkStr n comp\n  else\n    none\n\ndef isNameLit? (stx : Syntax) : Option Name :=\n  match isLit? nameLitKind stx with\n  | some val => decodeNameLit val\n  | _        => none\n\ndef hasArgs : Syntax \u2192 Bool\n  | Syntax.node _ _ args => args.size > 0\n  | _                    => false\n\ndef isAtom : Syntax \u2192 Bool\n  | atom _ _ => true\n  | _        => false\n\ndef isToken (token : String) : Syntax \u2192 Bool\n  | atom _ val => val.trim == token.trim\n  | _          => false\n\ndef isNone (stx : Syntax) : Bool :=\n  match stx with\n  | Syntax.node _ k args => k == nullKind && args.size == 0\n  -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none`\n  | Syntax.missing     => true\n  | _                  => false\n\ndef getOptionalIdent? (stx : Syntax) : Option Name :=\n  match stx.getOptional? with\n  | some stx => some stx.getId\n  | none     => none\n\npartial def findAux (p : Syntax \u2192 Bool) : Syntax \u2192 Option Syntax\n  | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p)\n  | stx                        => if p stx then some stx else none\n\ndef find? (stx : Syntax) (p : Syntax \u2192 Bool) : Option Syntax :=\n  findAux p stx\n\nend Syntax\n\nnamespace TSyntax\n\ndef getNat (s : NumLit) : Nat :=\n  s.raw.isNatLit?.getD 0\n\ndef getId (s : Ident) : Name :=\n  s.raw.getId\n\ndef getScientific (s : ScientificLit) : Nat \u00d7 Bool \u00d7 Nat :=\n  s.raw.isScientificLit?.getD (0, false, 0)\n\ndef getString (s : StrLit) : String :=\n  s.raw.isStrLit?.getD \"\"\n\ndef getChar (s : CharLit) : Char :=\n  s.raw.isCharLit?.getD default\n\ndef getName (s : NameLit) : Name :=\n  s.raw.isNameLit?.getD .anonymous\n\nnamespace Compat\n\nscoped instance : CoeTail (Array Syntax) (Syntax.TSepArray k sep) where\n  coe a := (a : TSyntaxArray k)\n\nend Compat\n\nend TSyntax\n\n/-- Reflect a runtime datum back to surface syntax (best-effort). -/\nclass Quote (\u03b1 : Type) (k : SyntaxNodeKind := `term) where\n  quote : \u03b1 \u2192 TSyntax k\n\nexport Quote (quote)\n\ninstance [Quote \u03b1 k] [CoeHTCT (TSyntax k) (TSyntax [k'])] : Quote \u03b1 k' := \u27e8fun a => quote (k := k) a\u27e9\n\ninstance : Quote Term := \u27e8id\u27e9\ninstance : Quote Bool := \u27e8fun | true => mkCIdent ``Bool.true | false => mkCIdent ``Bool.false\u27e9\ninstance : Quote String strLitKind := \u27e8Syntax.mkStrLit\u27e9\ninstance : Quote Nat numLitKind := \u27e8fun n => Syntax.mkNumLit <| toString n\u27e9\ninstance : Quote Substring := \u27e8fun s => Syntax.mkCApp ``String.toSubstring' #[quote s.toString]\u27e9\n\n-- in contrast to `Name.toString`, we can, and want to be, precise here\nprivate def getEscapedNameParts? (acc : List String) : Name \u2192 Option (List String)\n  | Name.anonymous => if acc.isEmpty then none else some acc\n  | Name.str n s => do\n    let s \u2190 Name.escapePart s\n    getEscapedNameParts? (s::acc) n\n  | Name.num _ _ => none\n\ndef quoteNameMk : Name \u2192 Term\n  | .anonymous => mkCIdent ``Name.anonymous\n  | .str n s => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s]\n  | .num n i => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i]\n\ninstance : Quote Name `term where\n  quote n := match getEscapedNameParts? [] n with\n    | some ss => \u27e8mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit (\"`\" ++ \".\".intercalate ss)]\u27e9\n    | none    => \u27e8quoteNameMk n\u27e9\n\ninstance [Quote \u03b1 `term] [Quote \u03b2 `term] : Quote (\u03b1 \u00d7 \u03b2) `term where\n  quote\n    | \u27e8a, b\u27e9 => Syntax.mkCApp ``Prod.mk #[quote a, quote b]\n\nprivate def quoteList [Quote \u03b1 `term] : List \u03b1 \u2192 Term\n  | []      => mkCIdent ``List.nil\n  | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs]\n\ninstance [Quote \u03b1 `term] : Quote (List \u03b1) `term where\n  quote := quoteList\n\nprivate def quoteArray [Quote \u03b1 `term] (xs : Array \u03b1) : Term :=\n  if xs.size <= 8 then\n    go 0 #[]\n  else\n    Syntax.mkCApp ``List.toArray #[quote xs.toList]\nwhere\n  go (i : Nat) (args : Array Term) : Term :=\n    if h : i < xs.size then\n      go (i+1) (args.push (quote xs[i]))\n    else\n      Syntax.mkCApp (Name.mkStr2 \"Array\" (\"mkArray\" ++ toString xs.size)) args\ntermination_by go i _ => xs.size - i\n\ninstance [Quote \u03b1 `term] : Quote (Array \u03b1) `term where\n  quote := quoteArray\n\ninstance Option.hasQuote {\u03b1 : Type} [Quote \u03b1 `term] : Quote (Option \u03b1) `term where\n  quote\n    | none     => mkIdent ``none\n    | (some x) => Syntax.mkCApp ``some #[quote x]\n\n\n/-- Evaluator for `prec` DSL -/\ndef evalPrec (stx : Syntax) : MacroM Nat :=\n  Macro.withIncRecDepth stx do\n    let stx \u2190 expandMacros stx\n    match stx with\n    | `(prec| $num:num) => return num.getNat\n    | _ => Macro.throwErrorAt stx \"unexpected precedence\"\n\nmacro_rules\n  | `(prec| $a + $b) => do `(prec| $(quote <| (\u2190 evalPrec a) + (\u2190 evalPrec b)):num)\n\nmacro_rules\n  | `(prec| $a - $b) => do `(prec| $(quote <| (\u2190 evalPrec a) - (\u2190 evalPrec b)):num)\n\nmacro \"eval_prec \" p:prec:max : term => return quote (k := `term) (\u2190 evalPrec p)\n\n/-- Evaluator for `prio` DSL -/\ndef evalPrio (stx : Syntax) : MacroM Nat :=\n  Macro.withIncRecDepth stx do\n    let stx \u2190 expandMacros stx\n    match stx with\n    | `(prio| $num:num) => return num.getNat\n    | _ => Macro.throwErrorAt stx \"unexpected priority\"\n\nmacro_rules\n  | `(prio| $a + $b) => do `(prio| $(quote <| (\u2190 evalPrio a) + (\u2190 evalPrio b)):num)\n\nmacro_rules\n  | `(prio| $a - $b) => do `(prio| $(quote <| (\u2190 evalPrio a) - (\u2190 evalPrio b)):num)\n\nmacro \"eval_prio \" p:prio:max : term => return quote (k := `term) (\u2190 evalPrio p)\n\ndef evalOptPrio : Option (TSyntax `prio) \u2192 MacroM Nat\n  | some prio => evalPrio prio\n  | none      => return 1000 -- TODO: FIX back eval_prio default\n\nend Lean\n\nnamespace Array\n\nabbrev getSepElems := @getEvenElems\n\nopen Lean\n\nprivate partial def filterSepElemsMAux {m : Type \u2192 Type} [Monad m] (a : Array Syntax) (p : Syntax \u2192 m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do\n  if h : i < a.size then\n    let stx := a[i]\n    if (\u2190 p stx) then\n      if acc.isEmpty then\n        filterSepElemsMAux a p (i+2) (acc.push stx)\n      else if hz : i \u2260 0 then\n        have : i.pred < i := Nat.pred_lt hz\n        have : i.pred < a.size := Nat.lt_trans this h\n        let sepStx := a[i.pred]\n        filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx)\n      else\n        filterSepElemsMAux a p (i+2) (acc.push stx)\n    else\n      filterSepElemsMAux a p (i+2) acc\n  else\n    pure acc\n\ndef filterSepElemsM {m : Type \u2192 Type} [Monad m] (a : Array Syntax) (p : Syntax \u2192 m Bool) : m (Array Syntax) :=\n  filterSepElemsMAux a p 0 #[]\n\ndef filterSepElems (a : Array Syntax) (p : Syntax \u2192 Bool) : Array Syntax :=\n  Id.run <| a.filterSepElemsM p\n\nprivate partial def mapSepElemsMAux {m : Type \u2192 Type} [Monad m] (a : Array Syntax) (f : Syntax \u2192 m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do\n  if h : i < a.size then\n    let stx := a[i]\n    if i % 2 == 0 then do\n      let stx \u2190 f stx\n      mapSepElemsMAux a f (i+1) (acc.push stx)\n    else\n      mapSepElemsMAux a f (i+1) (acc.push stx)\n  else\n    pure acc\n\ndef mapSepElemsM {m : Type \u2192 Type} [Monad m] (a : Array Syntax) (f : Syntax \u2192 m Syntax) : m (Array Syntax) :=\n  mapSepElemsMAux a f 0 #[]\n\ndef mapSepElems (a : Array Syntax) (f : Syntax \u2192 Syntax) : Array Syntax :=\n  Id.run <| a.mapSepElemsM f\n\nend Array\n\nnamespace Lean.Syntax\n\ndef SepArray.getElems (sa : SepArray sep) : Array Syntax :=\n  sa.elemsAndSeps.getSepElems\n\ndef TSepArray.getElems (sa : TSepArray k sep) : TSyntaxArray k :=\n  .mk sa.elemsAndSeps.getSepElems\n\ndef TSepArray.push (sa : TSepArray k sep) (e : TSyntax k) : TSepArray k sep :=\n  if sa.elemsAndSeps.isEmpty then\n    { elemsAndSeps := #[e] }\n  else\n    { elemsAndSeps := sa.elemsAndSeps.push (mkAtom sep) |>.push e }\n\ninstance : EmptyCollection (SepArray sep) where\n  emptyCollection := \u27e8\u2205\u27e9\n\ninstance : EmptyCollection (TSepArray sep k) where\n  emptyCollection := \u27e8\u2205\u27e9\n\ninstance : CoeOut (SepArray sep) (Array Syntax) where\n  coe := SepArray.getElems\n\ninstance : CoeOut (TSepArray k sep) (TSyntaxArray k) where\n  coe := TSepArray.getElems\n\ninstance [Coe (TSyntax k) (TSyntax k')] : Coe (TSyntaxArray k) (TSyntaxArray k') where\n  coe a := a.map Coe.coe\n\ninstance : CoeOut (TSyntaxArray k) (Array Syntax) where\n  coe a := a.raw\n\ninstance : Coe Ident (TSyntax `Lean.Parser.Command.declId) where\n  coe id := mkNode _ #[id, mkNullNode #[]]\n\ninstance : Coe (Lean.Term) (Lean.TSyntax `Lean.Parser.Term.funBinder) where\n  coe stx := \u27e8stx\u27e9\n\nend Lean.Syntax\n\nset_option linter.unusedVariables.funArgs false in\n/--\n  Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses\n  the given tactic.\n  Like `optParam`, this gadget only affects elaboration.\n  For example, the tactic will *not* be invoked during type class resolution. -/\nabbrev autoParam.{u} (\u03b1 : Sort u) (tactic : Lean.Syntax) : Sort u := \u03b1\n\n/-! # Helper functions for manipulating interpolated strings -/\n\nnamespace Lean.Syntax\n\nprivate def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char \u00d7 String.Pos) := do\n  match decodeQuotedChar s i with\n  | some r => some r\n  | none   =>\n    let c := s.get i\n    let i := s.next i\n    if c == '{' then pure ('{', i)\n    else none\n\nprivate partial def decodeInterpStrLit (s : String) : Option String :=\n  let rec loop (i : String.Pos) (acc : String) : Option String :=\n    let c := s.get i\n    let i := s.next i\n    if c == '\\\"' || c == '{' then\n      pure acc\n    else if s.atEnd i then\n      none\n    else if c == '\\\\' then do\n      let (c, i) \u2190 decodeInterpStrQuotedChar s i\n      loop i (acc.push c)\n    else\n      loop i (acc.push c)\n  loop \u27e81\u27e9 \"\"\n\npartial def isInterpolatedStrLit? (stx : Syntax) : Option String :=\n  match isLit? interpolatedStrLitKind stx with\n  | none     => none\n  | some val => decodeInterpStrLit val\n\ndef getSepArgs (stx : Syntax) : Array Syntax :=\n  stx.getArgs.getSepElems\n\nend Syntax\n\nnamespace TSyntax\n\ndef expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax \u2192 Syntax \u2192 MacroM Syntax) (mkElem : Syntax \u2192 MacroM Syntax) : MacroM Syntax := do\n  let mut i := 0\n  let mut result := Syntax.missing\n  for elem in chunks do\n    let elem \u2190 match elem.isInterpolatedStrLit? with\n      | none     => mkElem elem\n      | some str => mkElem (Syntax.mkStrLit str)\n    if i == 0 then\n      result := elem\n    else\n      result \u2190 mkAppend result elem\n    i := i+1\n  return result\n\nopen TSyntax.Compat in\ndef expandInterpolatedStr (interpStr : TSyntax interpolatedStrKind) (type : Term) (toTypeFn : Term) : MacroM Term := do\n  let r \u2190 expandInterpolatedStrChunks interpStr.raw.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a))\n  `(($r : $type))\n\nend TSyntax\n\nnamespace Meta\n\ninductive TransparencyMode where\n  | all | default | reducible | instances\n  deriving Inhabited, BEq, Repr\n\ninductive EtaStructMode where\n  /-- Enable eta for structure and classes. -/\n  | all\n  /-- Enable eta only for structures that are not classes. -/\n  | notClasses\n  /-- Disable eta for structures and classes. -/\n  | none\n  deriving Inhabited, BEq, Repr\n\nnamespace DSimp\n\nstructure Config where\n  zeta              : Bool := true\n  beta              : Bool := true\n  eta               : Bool := true\n  etaStruct         : EtaStructMode := .all\n  iota              : Bool := true\n  proj              : Bool := true\n  decide            : Bool := false\n  autoUnfold        : Bool := false\n  deriving Inhabited, BEq, Repr\n\nend DSimp\n\nnamespace Simp\n\ndef defaultMaxSteps := 100000\n\nstructure Config where\n  maxSteps          : Nat  := defaultMaxSteps\n  maxDischargeDepth : Nat  := 2\n  contextual        : Bool := false\n  memoize           : Bool := true\n  singlePass        : Bool := false\n  zeta              : Bool := true\n  beta              : Bool := true\n  eta               : Bool := true\n  etaStruct         : EtaStructMode := .all\n  iota              : Bool := true\n  proj              : Bool := true\n  decide            : Bool := true\n  arith             : Bool := false\n  autoUnfold        : Bool := false\n  /--\n    If `dsimp := true`, then switches to `dsimp` on dependent arguments where there is no congruence theorem that allows\n    `simp` to visit them. If `dsimp := false`, then argument is not visited.\n  -/\n  dsimp             : Bool := true\n  deriving Inhabited, BEq, Repr\n\n-- Configuration object for `simp_all`\nstructure ConfigCtx extends Config where\n  contextual := true\n\ndef neutralConfig : Simp.Config := {\n  zeta              := false\n  beta              := false\n  eta               := false\n  iota              := false\n  proj              := false\n  decide            := false\n  arith             := false\n  autoUnfold        := false\n}\n\nend Simp\n\nnamespace Rewrite\n\nstructure Config where\n  transparency : TransparencyMode := TransparencyMode.reducible\n  offsetCnstrs : Bool := true\n\nend Rewrite\n\nend Meta\n\nnamespace Parser.Tactic\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 loc:(location)? : tactic =>\n  `(tactic| rw (config := { transparency := .default }) $s $(loc)?)\n\nsyntax simpAllKind := atomic(\"(\" &\"all\") \" := \" &\"true\" \")\"\nsyntax dsimpKind   := atomic(\"(\" &\"dsimp\") \" := \" &\"true\" \")\"\n\nmacro (name := declareSimpLikeTactic) doc?:(docComment)? \"declare_simp_like_tactic\" opt:((simpAllKind <|> dsimpKind)?) tacName:ident tacToken:str updateCfg:term : command => do\n  let (kind, tkn, stx) \u2190\n    if opt.raw.isNone then\n      pure (\u2190 `(``simp), \u2190 `(\"simp\"), \u2190 `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&\" only\")? (\" [\" (simpStar <|> simpErase <|> simpLemma),* \"]\")? (location)? : tactic))\n    else if opt.raw[0].getKind == ``simpAllKind then\n      pure (\u2190 `(``simpAll), \u2190 `(\"simp_all\"), \u2190 `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&\" only\")? (\" [\" (simpErase <|> simpLemma),* \"]\")? : tactic))\n    else\n      pure (\u2190 `(``dsimp), \u2190 `(\"dsimp\"), \u2190 `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&\" only\")? (\" [\" (simpErase <|> simpLemma),* \"]\")? (location)? : tactic))\n  `($stx:command\n    @[macro $tacName] def expandSimp : Macro := fun s => do\n      let c \u2190 match s[1][0] with\n        | `(config| (config := $$c)) => `(config| (config := $updateCfg $$c))\n        | _ => `(config| (config := $updateCfg {}))\n      let s := s.setKind $kind\n      let s := s.setArg 0 (mkAtomFrom s[0] $tkn (canonical := true))\n      let r := s.setArg 1 (mkNullNode #[c])\n      return r)\n\n/-- `simp!` is shorthand for `simp` with `autoUnfold := true`.\nThis will rewrite with all equation lemmas, which can be used to\npartially evaluate many definitions. -/\ndeclare_simp_like_tactic simpAutoUnfold \"simp! \" fun (c : Lean.Meta.Simp.Config) => { c with autoUnfold := true }\n\n/-- `simp_arith` is shorthand for `simp` with `arith := true`.\nThis enables the use of normalization by linear arithmetic. -/\ndeclare_simp_like_tactic simpArith \"simp_arith \" fun (c : Lean.Meta.Simp.Config) => { c with arith := true }\n\n/-- `simp_arith!` is shorthand for `simp_arith` with `autoUnfold := true`.\nThis will rewrite with all equation lemmas, which can be used to\npartially evaluate many definitions. -/\ndeclare_simp_like_tactic simpArithAutoUnfold \"simp_arith! \" fun (c : Lean.Meta.Simp.Config) => { c with arith := true, autoUnfold := true }\n\n/-- `simp_all!` is shorthand for `simp_all` with `autoUnfold := true`.\nThis will rewrite with all equation lemmas, which can be used to\npartially evaluate many definitions. -/\ndeclare_simp_like_tactic (all := true) simpAllAutoUnfold \"simp_all! \" fun (c : Lean.Meta.Simp.ConfigCtx) => { c with autoUnfold := true }\n\n/-- `simp_all_arith` combines the effects of `simp_all` and `simp_arith`. -/\ndeclare_simp_like_tactic (all := true) simpAllArith \"simp_all_arith \" fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true }\n\n/-- `simp_all_arith!` combines the effects of `simp_all`, `simp_arith` and `simp!`. -/\ndeclare_simp_like_tactic (all := true) simpAllArithAutoUnfold \"simp_all_arith! \" fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true, autoUnfold := true }\n\n/-- `dsimp!` is shorthand for `dsimp` with `autoUnfold := true`.\nThis will rewrite with all equation lemmas, which can be used to\npartially evaluate many definitions. -/\ndeclare_simp_like_tactic (dsimp := true) dsimpAutoUnfold \"dsimp! \" fun (c : Lean.Meta.DSimp.Config) => { c with autoUnfold := true }\n\nend Parser.Tactic\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/Meta.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0875638323797629, "lm_q2_score": 0.0390482941240866, "lm_q1q2_score": 0.0034192182813971993}}
{"text": "-- TODO:\n-- * Derive handler\n-- * test\n-- * cleanup code\n-- * add argument type to usage string\n\nimport Lean.Elab.AuxDef\nimport Lean.Elab.BindersUtil\nimport Lean.Elab.Deriving.Basic\nimport Lean.Elab.Deriving.Util\nimport Lean.Elab.MacroArgUtil\nimport Lean.Elab.Quotation.Precheck\nimport Lean.Elab.Term\n\nimport Lean.Parser.Term\nimport Lean.PrettyPrinter.Delaborator.Basic\n\nimport Lean.Parser.Term\nimport Lean.Meta.Closure\nimport Lean.Meta.Check\nimport Lean.Elab.Command\nimport Lean.Elab.DefView\nimport Lean.Elab.PreDefinition\nimport Lean.Elab.DeclarationRange\n\nimport Std.Data.HashMap\n\nimport CLI.Format\n\nopen Lean Lean.Meta\n\nclass CLIArg (\u03b1 : Type u) where\n  typeName : String\n  parse : String \u2192 Option \u03b1\n\ndef parseArg (\u03b1) [CLIArg \u03b1] : String \u2192 Option \u03b1 :=\nCLIArg.parse\n\ninstance : CLIArg String where\n  typeName := \"STRING\"\n  parse := some\n\ninstance : CLIArg Nat where\n  typeName := \"NAT\"\n  parse := String.toNat?\n\ninductive StreamReader (\u03b1 : Type u) (\u03b2 : Type v) where\n  | read (f : \u03b1 \u2192 StreamReader \u03b1 \u03b2) : StreamReader \u03b1 \u03b2\n  | pure : \u03b2 \u2192 StreamReader \u03b1 \u03b2\n  | error : String \u2192 StreamReader \u03b1 \u03b2\n\nclass CLIArgRecord (\u03b1 : Type u) where\n  init : \u03b1\n  parse : String \u2192 \u03b1 \u2192 Option (StreamReader String \u03b1)\n  usageString : String\n\n@[simp]\ntheorem measure_foo (f : \u03b1 \u2192 Nat) :\n  (measure f).1 x y \u2194 f x < f y := Iff.rfl\n\n@[simp]\ntheorem dec_double (x k : Nat) :\n  x < x + k \u2194 0 < k := sorry\n\n@[simp]\ntheorem dec_double''' (i j : Nat) :\n  x + i.succ + j = x + i + j.succ := sorry\n\n@[simp]\ntheorem dec_double'' (i j : Nat) :\n  x + i < x + j \u2194 i < j := sorry\n\n@[simp]\ntheorem dec_double' (x y : Nat) :\n  x * y.succ = x*y + x := sorry\n\nmutual\n\nvariable (\u03b1 : Type) [CLIArgRecord \u03b1]\nvariable (interspersedArgs : Bool)\n\n@[inline]\ndef parseArgsFeed (acc : List String)\n    (args : List String)\n     : StreamReader String \u03b1 \u2192\n       Except String (\u03b1 \u00d7 Array String)\n| StreamReader.pure x' => parseArgsAux acc x' args\n| StreamReader.error msg => Except.error msg\n| StreamReader.read f =>\n  match args with\n  | [] => Except.error \"expecting more arguments\"\n  | y::ys => parseArgsFeed acc ys (f y)\n\n@[inline]\ndef parseArgsAux (acc : List String) (x : \u03b1)\n     : List String \u2192\n  Except String (\u03b1 \u00d7 Array String)\n| [] => pure (x, acc.reverse.toArray)\n| y :: ys =>\n  match CLIArgRecord.parse y x with\n  | none =>\n    if interspersedArgs\n    then parseArgsAux (y :: acc) x ys\n    else pure (x, (acc.reverse ++ y :: ys).toArray)\n  | some r =>\n    parseArgsFeed acc ys r\n\nend\n\ntermination_by\n  parseArgsFeed x _ => (2 * x.length) + 1\n  parseArgsAux x => 2 * x.length\ndecreasing_by simp [InvImage, WellFoundedRelation.rel, sizeOf]\n\n\n@[specialize]\ndef parseArgs (\u03b1 : Type) [CLIArgRecord \u03b1]\n    (args : Array String) (interspersedArgs : Bool) :\n  Except String (\u03b1 \u00d7 Array String) :=\nparseArgsAux \u03b1\n  interspersedArgs [] CLIArgRecord.init args.toList\n\ndef LeftOvers (\u03b1 : Type) (allowed : Bool) :=\n  cond allowed (\u03b1 \u00d7 Array String) \u03b1\n\ninstance [Repr \u03b1] {allowed} : Repr (LeftOvers \u03b1 allowed) :=\nmatch allowed with\n| true => inferInstanceAs (Repr (\u03b1 \u00d7 Array String))\n| false => inferInstanceAs (Repr \u03b1)\n\ndef processCmdLine  (\u03b1 : Type) [CLIArgRecord \u03b1]\n    (args : Array String)\n    (interspersedArgs := false)\n    (allowLeftOvers := false) :\n  IO (LeftOvers \u03b1 allowLeftOvers) := do\nlet (r, ar) \u2190\n  match parseArgs \u03b1 args interspersedArgs with\n  | Except.error msg =>\n    throw <| IO.userError\n      <| s!\"{msg}\\n\\n{CLIArgRecord.usageString \u03b1}\"\n  | Except.ok (r, ar) => pure (r, ar)\nmatch allowLeftOvers with\n| true => return (r, ar)\n| false =>\n  if ar.isEmpty then return r\n  else throw\n      <| IO.userError\n      <| s!\"Excess arguments: {ar}\\n\\n{CLIArgRecord.usageString \u03b1}\"\n\nabbrev CmdLineFlag (short : String) (long : Option String) (descr : String) := Bool\n\nabbrev CmdLineOpt (short : String) (long : Option String) (t : Type) [CLIArg t]\n  (descr : String) := Option t\n\nstructure Flags where\n  traceCmd :\n    CmdLineFlag \"-c\" (some \"--cmd\")\n    \"tracing: print command\"\n  traceSubst :\n    CmdLineFlag \"-s\" none\n    \"tracing: print module renaming\"\n  traceRoot :\n    CmdLineFlag \"-r\" none\n    \"tracing: print command\"\n  optValue :\n    CmdLineOpt \"-t\" none Nat\n    \"tracing: test option parsing\"\n  dryRun :\n    CmdLineFlag \"-d\" none\n    \"dry run: calculate parameters but perform no action\"\n  forward : Array String := #[]\n                           -- array of -f, -i, -n, -v, -k\n  deriving Repr, Inhabited\n\nnamespace CLI\nopen Lean\n\ndef instantiateBVarAux (i : Nat) (vs : List Expr) (e : Expr) :\n  Expr :=\nif e.looseBVarRange > 0 then e else\n  match e with\n  | Expr.forallE n d b data =>\n    Expr.forallE n\n      (instantiateBVarAux i vs d)\n      (instantiateBVarAux (i+1) vs b) data\n  | Expr.lam n d b data     =>\n    Expr.lam n\n      (instantiateBVarAux i vs d)\n      (instantiateBVarAux (i+1) vs b) data\n  | Expr.mdata m e d        =>\n    Expr.mdata m (instantiateBVarAux i vs e) d\n  | Expr.letE n t v b data  =>\n    Expr.letE n\n      (instantiateBVarAux i vs t)\n      (instantiateBVarAux i vs v)\n      (instantiateBVarAux (i+1) vs b) data\n  | Expr.app f a data       =>\n    Expr.app\n      (instantiateBVarAux i vs f)\n      (instantiateBVarAux i vs a)\n      data\n  | Expr.proj r j e data    =>\n    Expr.proj r j (instantiateBVarAux i vs e) data\n  | e@(Expr.bvar j _)  => vs.getD (j - i) e\n  | e                       => e\n\ndef instantiateBVar (vs : List Expr) (e : Expr) : Expr :=\ninstantiateBVarAux 0 vs e\n\ndef mkFieldTypeAux (vs : List Expr) (s' : Name) :\n  Expr \u2192 MetaM (List Expr \u00d7 Expr)\n| Expr.forallE n d b _  =>\n  Lean.Meta.withLocalDeclD n d \u03bb v =>\n    if d.isConstOf s'\n    then return (v :: vs, instantiateBVar (v :: vs) b)\n    else mkFieldTypeAux (v :: vs) s' b\n| e => return (vs, e)\n\ndef mkFieldType : Name \u2192 Expr \u2192 MetaM (List Expr \u00d7 Expr) :=\nmkFieldTypeAux []\n\ndef typeOfField' (s field : Name) : OptionT MetaM Expr := do\nlet env \u2190 getEnv\nlet s' \u2190 liftOption <| findField? env s field\nlet info \u2190 liftOption <| getFieldInfo? env s' field\nlet d \u2190 liftOption <| env.find? info.projFn\nlet t := d.type\nProd.snd <$> mkFieldType s' t\n\ndef typeOfField (s field : Name) : MetaM Expr := do\nlet some a \u2190 typeOfField' s field |>.run\n    | throwError \"cannot infer field type of {s}.{field}\"\nreturn a\n\ndef getFieldInfo' (s field : Name) : OptionT MetaM StructureFieldInfo := do\nlet env \u2190 getEnv\nlet s' \u2190 liftOption <| findField? env s field\nliftOption <| getFieldInfo? env s' field\n\ndef getFieldInfo! (s field : Name) : MetaM StructureFieldInfo := do\nlet some a \u2190 getFieldInfo' s field |>.run\n    | throwError \"cannot find field info for {s}.{field}\"\nreturn a\n\nstructure FlagDescr where\n  field : Name\n  projection : Name\n  shortOpt : String\n  longOpt : Option String\n  optType : Option Syntax\n  description : String\n  deriving Repr, Inhabited\n\ndef parseStringLit [Monad m] [MonadError m] (s : Syntax) :\n  m String := do\n  let some x := Syntax.isStrLit? s\n    | throwError \"expecting string literal {s}\"\n  return x\n\ndef parseShortOpt [Monad m] [MonadError m]\n    (s : Syntax) : m String := do\n  let x \u2190 parseStringLit s\n  unless (\"-\".isPrefixOf x \u2227 x.length = 2) do\n    throwError \"invalid short option '{x}'\"\n  return x\n\ndef parseLongOpt [Monad m] [MonadError m] :\n  Syntax \u2192 m (Option String)\n| `(none) => pure none\n| `(some $x) => do\n  let x \u2190 parseStringLit x\n  unless (\"--\".isPrefixOf x \u2227 x.length > 2) do\n    throwError \"invalid long option '{x}'\"\n  return some x\n| e => throwError \"Expecting a literal string: {e}\"\n\nopen Lean.Elab.Term\n\ndef mkFlagDescr (struct field : Name) :\n  TermElabM (Option FlagDescr) := do\nlet t \u2190 typeOfField struct field\nlet proj := (\u2190 getFieldInfo! struct field).projFn\nlet s \u2190 Lean.PrettyPrinter.delab t\nmatch s with\n| `(CmdLineFlag $x $y $descr) =>\n  return some {\n    field := field,\n    projection := proj,\n    shortOpt := \u2190 parseShortOpt x,\n    longOpt := \u2190 parseLongOpt y,\n    optType := none,\n    description := \u2190 parseStringLit descr : FlagDescr }\n| `(CmdLineOpt $x $y $t $descr) =>\n  return some {\n    field := field,\n    projection := proj,\n    shortOpt := \u2190 parseShortOpt x,\n    longOpt := \u2190 parseLongOpt y,\n    optType := some t,\n    description := \u2190 parseStringLit descr : FlagDescr }\n| _ => return none\n\nsection\n\nopen Lean.Meta\nopen Lean Parser Term Elab Term\n\ndef optionParsingFailure (x : String) :\n  Option (StreamReader String \u03b1) :=\nif \"-\".isPrefixOf x then\n  some <| StreamReader.error s!\"Invalid option: {x}\"\nelse\n  none\n\ndef mkOptParser (arg\u2080 obj : Syntax)\n                (flag : FlagDescr) :\n    TermElabM Syntax :=\nwithFreshMacroScope do\n  let field := mkIdent flag.field\n  let proj := mkIdent flag.projection\n  let flagString :=\n    match flag.longOpt with\n    | some opt =>  opt\n    | none =>  flag.shortOpt\n  let parsingErrorMsg :=\n    s!\"Flag {flagString} requires an argument of type \"\n  let parsingErrorMsg := Syntax.mkStrLit parsingErrorMsg\n  let redundantOptMsg :=\n    s!\"Flag {flagString} should be provided only once\"\n  let redundantOptMsg := Syntax.mkStrLit redundantOptMsg\n  if let some type := flag.optType then\n    let successCode \u2190 `(StreamReader.pure\n           { $obj with $field:ident := some val } )\n    let errorCode \u2190 `(StreamReader.error <|\n        $parsingErrorMsg ++ CLIArg.typeName $type)\n    let redundantOpt \u2190 `(StreamReader.error <| $redundantOptMsg)\n    let br1 \u2190 `(matchAltExpr| | none => $errorCode)\n    let br2 \u2190 `(matchAltExpr| | some val => $successCode)\n    let brs := #[br1, br2]\n    let discr \u2190 `(parseArg $type arg\u2081)\n    let body \u2190 `(match $discr:term with $brs:matchAlt*)\n    let parseArg \u2190 `(StreamReader.read \u03bb arg\u2081 => $body)\n    `(some <| if ($proj $obj).isNone\n              then $parseArg\n              else $redundantOpt )\n  else\n    `(some <| StreamReader.pure\n        { $obj with $field:ident := true } )\n\n\nend\n\n/--\nGenerate a function\n\ndef MyStruct.parseArg (s : String) (x : MyStruct) : Option MyStruct := ...\n\nNote: this is broken because I don't know how to create\nand elaborate a syntax object of the form `{x with foo := 7}`\n-/\ndef mkArgParserAux\n  -- [Monad m] [MonadRef m] [MonadQuotation m]\n  (type : Name) (arg obj : Syntax) :\n  List FlagDescr \u2192 TermElabM Syntax\n| [] => `(optionParsingFailure $arg)\n| flag :: fs => do\n  let code \u2190 mkArgParserAux type arg obj fs\n  let field := mkIdent flag.field\n  let thenBr \u2190 mkOptParser arg obj flag\n  let elseBr \u2190\n    if let some longOpt := flag.longOpt then\n      `(if $arg = $(Syntax.mkStrLit longOpt)\n        then $thenBr\n        else $code )\n    else pure code\n  `(if $arg = $(Syntax.mkStrLit flag.shortOpt)\n    then $thenBr\n    else $elseBr)\n\ndef addDef (n : Name) (t : Expr) (d : Expr) : MetaM Name := do\nlet t \u2190 instantiateMVars t\nlet d \u2190 instantiateMVars d\naddAndCompile\n  <| Declaration.defnDecl\n  <| DefinitionVal.mk\n    (ConstantVal.mk n [] t) d\n    (ReducibilityHints.regular 10)\n    DefinitionSafety.safe\nreturn n\n\ndef mkArgParser (type : Name)\n  (flags : List FlagDescr) : TermElabM Name :=\nlet n := type.mkStr \"parseArg\"\nwithDeclName n do\nwithFreshMacroScope do\n  let arg \u2190 `(arg)\n  let obj \u2190 `(obj)\n  let b \u2190 mkArgParserAux type arg obj flags\n  let type' := mkIdent type\n  let t \u2190 Elab.Term.elabTerm\n      (\u2190 `(String \u2192 $type' \u2192\n           Option (StreamReader String $type'))) none\n  let d \u2190 withDeclName n <| Elab.Term.elabTerm\n    (\u2190 `(\u03bb ($arg : String)\n           ($obj : $type') => $b))\n    (some t)\n  addDef n t d\n\nopen Lean.Parser.Term\nopen Lean.Elab Term Meta\n\ndef mkInitAux (type : Name)\n  (flags : List FlagDescr) : TermElabM Syntax := do\nlet fieldInits := flags.toArray\nlet fieldInits \u2190 fieldInits.mapM \u03bb fl => do\n  let field := mkIdent fl.field\n  let val \u2190\n    if fl.optType.isSome then `(none)\n    else `(false)\n  `(structInstField| $field:ident := $val )\n`({ $[$fieldInits,]* : $(mkIdent type) })\n\ndef mkInitialization (type : Name)\n  (flags : List FlagDescr) : TermElabM Name :=\nlet n := type.mkStr \"init\"\nwithDeclName n do\nwithFreshMacroScope do\n  let t := Lean.mkConst type\n  let d \u2190 withDeclName n <| Elab.Term.elabTerm\n    (\u2190 mkInitAux type flags)\n    (some t)\n  addDef n t d\n\n-- #check ConstantInfo\nopen Std\n\nsection UsageString\n\nopen Document.Table\nopen Document.Paragraph\n\ndef mkUsageString' (flags : List FlagDescr) : String :=\nlet t := flags.map \u03bb fl =>\n  (#[rightAlign fl.shortOpt,\n     leftAlign <| fl.longOpt.getD \"\"],\n   fl.description)\nlet descrWidth := 60\nlet t := t.map <| Prod.map id <| wrapParagraph descrWidth\nlet empty := leftAlign \"\"\nlet t := t.bind \u03bb\n  | (a,[]) => [a.push <| empty]\n  | (a,l::ls) =>\n    a.push (leftAlign l) ::\n    ls.map (#[empty,empty].push \u2218 leftAlign)\nlet t :=\n  #[leftAlign \"Flags\", empty, leftAlign \"Description\"] ::\n  t\nrenderTable t\n\ndef mkUsageString (struct : Name)\n    (flags : List FlagDescr) : MetaM Name := do\nlet usage := mkUsageString' flags\nlet n := struct.mkStr \"usageString\"\nlet t \u2190 mkConstWithLevelParams ``String\nlet e := mkStrLit usage\nprintln!\"name: {n}\"\naddDef n t e\n\nend UsageString\n\ndef elabCLIArgRecordInst (struct : Name)\n    (init parser usage : Syntax) :\n  TermElabM (Expr \u00d7 Expr) := do\nlet t \u2190 elabTerm (\u2190 `(CLIArgRecord $(mkIdent struct))) none\nlet e \u2190 elabTerm\n  (\u2190 `( { init := $init,\n          parse := $parser,\n          usageString := $usage } ))\n  (some t)\nreturn (t, e)\n\n\ndef mkCLIArgRecordInst' (struct : Name)\n    (flags : List FlagDescr) : TermElabM Name := do\nlet usage := mkIdent (\u2190 mkUsageString struct flags)\nlet parser := mkIdent (\u2190 mkArgParser struct flags)\nlet init := mkIdent (\u2190 mkInitialization struct flags)\nlet (t, e) \u2190 elabCLIArgRecordInst struct init parser usage\nlet n := struct.mkStr \"instCLIArgRecord\"\naddDef n t e\n\ndef mkCLIArgRecordInst (struct : Name) : TermElabM Name :=\nwithDeclName struct do\nlet env \u2190 getEnv\nlet fields := getStructureFieldsFlattened env struct\nlet flags \u2190 fields.toList.filterMapM <| mkFlagDescr struct\nlet inst \u2190 mkCLIArgRecordInst' struct flags\naddInstance inst AttributeKind.\u00abglobal\u00bb 0\nreturn inst\n\ndef test : MetaM Unit := do\nlet env \u2190 getEnv\nlet struct := ``Flags\nIO.println <| (\u2190 mkCLIArgRecordInst struct |>.run')\nIO.println <| repr struct\n\n-- #eval mkCLIArgRecordInst ``Flags\n#eval test\n\n-- #check Flags.usageString\n-- #check Flags.parseArg\n\n-- instance : CLIArgRecord Flags where\n--   init := {}\n--   parse := Flags.parseArg\n--   usageString :=  Flags.usageString\nnamespace Derive\nopen Lean.Elab.Command\n\ndef mkCLIArgRecordInstanceHandler' : Array Name \u2192 CommandElabM Bool\n| #[t] => do\n  -- println! \"foo\"\n  -- liftTermElabM none <| discard <| mkCLIArgRecordInst t\n  return true\n| _ => do\n  -- throwError \"Mutually inductive types not supported\"\n  return false\n\n\ndef mkCLIArgRecordInstanceHandler : Array Name \u2192 CommandElabM Bool\n| #[t] => do\n  return true\n| _ => do\n  return true\n\nbuiltin_initialize\n  Lean.Elab.registerBuiltinDerivingHandler `CLIArgRecord\n    mkCLIArgRecordInstanceHandler\n\n-- structure Foo where\n--   field1 := false\n--   deriving CLIArgRecord\n\nend Derive\n\n#eval parseArgs Flags #[\"-d\", \"a\", \"-r\", \"-t\", \"3\", \"z\"] false\n\n#eval processCmdLine Flags #[\"-d\", \"a\", \"-r\", \"-t\", \"3\"] true true\n-- #eval parseArgsUnordered Flags #[\"--cmd\", \"a\", \"-r\"]\n\nend CLI\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/cmd-line-args/CLI/Args.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16451646289656316, "lm_q2_score": 0.020332353194251022, "lm_q1q2_score": 0.003345006829881816}}
{"text": "-- Trying to reproduce a bug with $(..) within a large syntax object\nimport Lean.Parser\nimport Lean.Parser.Extra\n\nopen Lean\nopen Lean.Parser\n\n-- | TODO: factor Symbol out from AttrVal\ninductive AttrVal : Type where\n| str : String -> AttrVal\n\ninductive AttrEntry : Type where\n  | mk: (key: String) \n      -> (value: AttrVal)\n      -> AttrEntry\n\ndeclare_syntax_cat mlir_attr_val\nsyntax str: mlir_attr_val\nsyntax \"[mlir_attr_val|\" incQuotDepth(mlir_attr_val) \"]\" : term\n\nmacro_rules\n| `([mlir_attr_val| $$($x) ]) => `($x)\n| `([mlir_attr_val| $s:strLit]) => `(AttrVal.str $s)\n\n-- Attribute Entries\ndeclare_syntax_cat mlir_attr_entry\n\nsyntax strLit \"=\" mlir_attr_val : mlir_attr_entry\nsyntax \"[mlir_attr_entry|\" incQuotDepth(mlir_attr_entry) \"]\" : term\n\nmacro_rules \n  | `([mlir_attr_entry| $name:strLit  = $v:mlir_attr_val]) => \n     `(AttrEntry.mk $name [mlir_attr_val| $v])\n\ndef attrVal0Str : AttrVal := [mlir_attr_val| \"add\"]\n#reduce attrVal0Str\n\ndef attrVal1Escape : AttrVal := [mlir_attr_val| $(attrVal0Str)]\n#reduce attrVal1Escape\n\ndef AttrEntry0Str : AttrEntry := [mlir_attr_entry| \"sym_name\" = \"add\"]\n#reduce AttrEntry0Str\n\n\n-- vv example SHOULD NOT FAIL?\ndef AttrEntry1Escape : AttrEntry := [mlir_attr_entry| \"sym_name\" = $(attrVal0Str)]\n#reduce AttrEntry1Escape\n\n\n\ndeclare_syntax_cat inner\ndeclare_syntax_cat outer\n\nsyntax \"<[\" inner \"]>\" : outer\n\nsyntax \"[inner|\" incQuotDepth(inner) \"]\" : term\nmacro_rules\n| `([inner| $$($s)]) => return s\n\nsyntax \"[outer|\" outer \"]\" : term\nmacro_rules\n| `([outer| <[ $k:inner ]> ]) => `([inner| $k])\n\nsyntax \"[outerIncQuotDepth|\" incQuotDepth(outer) \"]\" : term\nmacro_rules\n| `([outerIncQuotDepth|  <[ $k:inner ]> ]) => `([inner| $k])\n\n\ndef g := \"global string\"\n\ndef innerQuot := [inner| $(g) ]\ndef outerIncQuotDepth := [outerIncQuotDepth| <[ $(g) ]> ]\n-- I would expect `outerDoesNotWork` to work, because the quoting comes from inner, not outer!\ndef outerDoesNotWork := [outer| <[ $(g) ]> ] \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/playground/escape.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1500288205420277, "lm_q2_score": 0.02194825187557982, "lm_q1q2_score": 0.0032928703418525877}}
{"text": "import Lean\nimport Lean.Meta\nimport LeanCodePrompts.CheckParse\nimport LeanCodePrompts.ParseJson\nimport Mathlib.Mathport.Rename\n\nopen Lean Meta Elab\n\npartial def camelSplitAux (s : String)(accum: List String) : List String :=\n  if s.length == 0 then accum\n  else \n    let head := s.decapitalize.takeWhile (fun c => 'a' \u2264 c)\n    if head.length = 0 then accum ++ [s]\n    else\n      let tail := s.drop (head.length)\n      camelSplitAux tail (accum ++ [head])\n\ndef camelSplit(s : String) : List String :=\n  camelSplitAux s []\n\n-- #eval camelSplit \"CamelCaseWord\"\n\ndef fullSplit (s : String) : List String :=\n  let parts := s.splitOn \"_\"\n  parts.bind (fun s => camelSplit s)\n\n-- #eval fullSplit \"CamelCaseWord\"\n-- #eval fullSplit \"snake_caseBut_wordWithCamel\"\n\ninitialize caseNameCache : IO.Ref (HashMap String String) \n  \u2190 IO.mkRef (HashMap.empty)\n\n-- initialize xNameCache : IO.Ref (HashMap String String) \n--   \u2190 IO.mkRef (HashMap.empty)\n\n-- initialize xxNameCache : IO.Ref (HashMap String String) \n--   \u2190 IO.mkRef (HashMap.empty)\n\ninitialize dotNameCache : IO.Ref (HashMap String String) \n  \u2190 IO.mkRef (HashMap.empty)\n\n\ninitialize binNamesCache : IO.Ref (Array String) \u2190 IO.mkRef (#[])\n\ninitialize binNameMapCache : IO.Ref (HashMap (List String) String) \n  \u2190 IO.mkRef (HashMap.empty)\n\ninitialize binNameNoIsMapCache : IO.Ref (HashMap (List String) String) \n  \u2190 IO.mkRef (HashMap.empty)\n\ninitialize elabPromptsCache : IO.Ref (HashSet String) \u2190 IO.mkRef (HashSet.empty)\n\ndef caseNames : MetaM (HashMap String String) := do\n  let cache \u2190 caseNameCache.get\n  if cache.isEmpty then \n      let jsBlob \u2190 \n        IO.FS.readFile (\u2190 reroutePath <| System.mkFilePath [\"data\", \"case_dictionary.json\"])\n      let json \u2190 readJson jsBlob\n      match json.getArr? with\n      | Except.error e => throwError e\n      | Except.ok arr => do\n        let mut m : HashMap String String := HashMap.empty\n        for js in arr do\n          let snakeCase? := \n            (js.getObjVal? \"snakecase\").toOption.bind (fun s => \n                s.getStr?.toOption)\n          let camelCase? :=\n            (js.getObjVal? \"camelcase\").toOption.bind (fun s => \n                s.getStr?.toOption)\n          m := match (snakeCase?, camelCase?) with\n            | (some sc, some cc) =>  m.insert sc cc\n            | _ =>  m\n        caseNameCache.set m\n        return m\n  else return cache\n\n-- def xNames : MetaM (HashMap String String) := do\n--   let cache \u2190 xNameCache.get\n--   if cache.isEmpty then \n--       let lines \u2190 \n--         IO.FS.lines (\u2190 reroutePath <| System.mkFilePath [\"data\", \"x_names.txt\"])\n--       let mut m : HashMap String String := HashMap.empty\n--       for xname in lines do\n--         m := m.insert (xname.dropRight 1) xname\n--       xNameCache.set m\n--       return m\n--   else return cache\n\n-- def xxNames : MetaM (HashMap String String) := do\n--   let cache \u2190 xxNameCache.get\n--   if cache.isEmpty then \n--       let lines \u2190 \n--         IO.FS.lines (\u2190 reroutePath <| System.mkFilePath [\"data\", \"xx_names.txt\"])\n--       let mut m : HashMap String String := HashMap.empty\n--       for xxname in lines do\n--         m := m.insert (xxname.dropRight 2) xxname\n--       xxNameCache.set m\n--       return m\n--   else return cache\n\ndef dotNames : MetaM (HashMap String String) := do\n  let cache \u2190 dotNameCache.get\n  if cache.isEmpty then \n      let lines \u2190 \n        IO.FS.lines (\u2190 reroutePath <| System.mkFilePath [\"data\", \"simple_dot_names.txt\"])\n      let mut m : HashMap String String := HashMap.empty\n      for name in lines do\n        m := m.insert (name.toLower) name\n      dotNameCache.set m\n      return m\n  else return cache\n\ndef caseName?(s: String) : MetaM (Option String) := do\n  let cache \u2190 caseNames\n  return cache.find? s\n\n-- def xName?(s: String) : MetaM (Option String) := do\n--   let cache \u2190 xNames\n--   return cache.find? s\n\n-- def xxName?(s: String) : MetaM (Option String) := do\n--   let cache \u2190 xxNames\n--   return cache.find? s\n\ndef dotName?(s: String) : MetaM (Option String) := do\nmatch s.splitOn \".\" with\n| [head, field] =>\n  if head.length \u2264 2 then\n    let cache \u2190 dotNames\n    return cache.find? field |>.map (fun s => head ++ \".\" ++ s)\n  else return none\n| _ => return none\n\ndef binNames : IO (Array String) := do \n  let cacheStr \u2190 binNamesCache.get\n  if cacheStr.size > 0 then \n    return cacheStr\n  else \n    let all \u2190 \n      IO.FS.lines (\u2190 reroutePath <| System.mkFilePath [\"data\", \"binport_names.txt\"])\n    let filtered := all.filter (fun s => s.length > 0)\n    let filtered := filtered.toList\n    binNamesCache.set filtered.toArray\n    return all.filter (fun s => !(s.contains  '.'))\n\ndef binNameMap : IO (HashMap (List String) String) := do\n  let cacheMap \u2190 binNameMapCache.get\n  if cacheMap.isEmpty then \n    let names \u2190 binNames\n    let res := names.foldl \n      (fun m s => m.insert (fullSplit s) s) (HashMap.empty)\n    binNameMapCache.set res\n    return res\n  else\n    return cacheMap\n\ndef elabPrompts : IO (HashSet String) := do \n  let cacheStr \u2190 elabPromptsCache.get\n  if !cacheStr.isEmpty then \n    return cacheStr\n  else \n    let arr \u2190 \n      IO.FS.lines (\u2190 \n       reroutePath <| System.mkFilePath [\"data\", \"elab_thms.txt\"])\n    return arr.foldl (fun acc n => acc.insert n) HashSet.empty\n\ndef isElabPrompt(s: String) : IO Bool := do\n  let prompts \u2190 elabPrompts\n  return prompts.contains s\n\n\ndef withoutIs? : List String \u2192 Option (List String)\n| x :: ys => \n  if x = \"is\" || x = \"has\" then some ys else none\n| [] => none\n\ndef binNameNoIsMap : IO (HashMap (List String) String) := do\n  let cacheMap \u2190 binNameNoIsMapCache.get\n  if cacheMap.isEmpty then \n    let names \u2190 binNames\n    let res := names.foldl \n      (fun m s => \n        match withoutIs? (fullSplit s) with\n        | some ys => m.insert ys s\n        | none => m\n          ) (HashMap.empty)\n    binNameNoIsMapCache.set res\n    return res\n  else\n    return cacheMap\n\ndef binName?(s : String) : MetaM <| Option String := do\n  let map \u2190 binNameMap\n  let mapNoIs \u2190 binNameNoIsMap\n  let split := fullSplit s\n  let splitNoIs? := withoutIs? split\n  let res := ((map.find? split).orElse \n              (fun _ => mapNoIs.find? split)).orElse \n              (fun _ => splitNoIs?.bind (\n                  fun splitNoIs => map.find? splitNoIs))\n  return res\n\ndef lean4Name?(s: String) : MetaM (Option String) := do\n  let m := Mathlib.Prelude.Rename.getRenameMap (\u2190 getEnv)\n  return m.find? s |>.map (fun (_, name) => name.toString)\n\n\ndef caseOrBinName?(s : String) : MetaM (Option String) := do\n  match \u2190 lean4Name? s with\n  | some name => return some name\n  | none => do\n    let res \u2190 caseName? s\n    if res.isNone then do\n      let res \u2190 binName? s\n      return res\n    else return res\n\n-- #eval lean4Name? \"has_abs\"\n\n\ndef identErr (err: String) : Option String :=\n  let head := \"unknown identifier '\"\n  let tail := \"' (during elaboration)\"\n  if err.startsWith head && err.endsWith tail then\n    some <| (err.drop (head.length)).dropRight (tail.length)\n  else\n    none\n\n\ndef identCorrection(s err: String) : MetaM (Option String) := do\n  match identErr err with\n  | none => return none \n  | some id => match \u2190  binName? id with\n    | none => return none\n    | some name => return some (s.replace id name)\n\n/-- identifier substrings -/\npartial def identSubs : Syntax \u2192 List Substring\n| Syntax.ident _ s .. => [s]\n| Syntax.node _ _ ss => ss.toList.bind identSubs\n| _ => []\n\npartial def extractByteAux (s: String) (start stop : String.Pos) (accum: String) \n    := if start \u2265  stop then accum else\n        let h := s.get start\n        extractByteAux s (s.next start) stop (accum ++ h.toString)\n\ndef extractBytes (s: String) (start stop : String.Pos) := \n      extractByteAux s start stop \"\"\n\ndef interleaveAux (full: Substring)(cursor: String.Pos)\n  (accum: List (Substring \u00d7 Substring))(idents: List Substring) :\n      (List (Substring \u00d7 Substring)) \u00d7 Substring :=\n  match idents with\n  | [] => (accum, full.extract cursor full.stopPos)\n  | h :: ts => \n      let pred := full.extract cursor h.startPos\n      interleaveAux full (h.stopPos) \n          (accum ++ [(pred, h)]) ts\n      \ndef interLeave(full: Substring)(idents: List Substring) :\n      (List (Substring \u00d7 Substring)) \u00d7 Substring := \n          interleaveAux full 0 [] idents\n\n/-- given a string expected to be a *theorem statement* such as `{A: Type} (a : A) : P a`, transforms to one of the type `{A: Type} \u2192 (a : A) \u2192 P a`, parses this as a term and returns segments and a tail, with each segment a pair with the second part an identifier and the first an identifier-free part preceding it. -/\ndef identThmSegments (s : String)(opens: List String := [])\n  : MetaM <| Except String ((Array (String \u00d7 String)) \u00d7 String) := do\n  let env \u2190 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        identsAux type args\n      | `(thmStat|$vars:argument* $_: docComment theorem $args:argument* : $type:term) =>\n        identsAux type (vars ++ args)\n      | `(thmStat|theorem $_ $args:argument* : $type:term) =>\n        identsAux type args\n      | `(thmStat|def $_ $args:argument* : $type:term) =>\n        identsAux type args\n      | `(thmStat|$args:argument* : $type:term) =>\n        identsAux type args\n      | _ => return Except.error \"not a theorem statement\"\n  | Except.error _  => return Except.error \"not a theorem statement\"\n  where identsAux (type: Syntax)(args: Array Syntax) : \n        MetaM <| Except String ((Array (String \u00d7 String)) \u00d7 String) := 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 funTypeStr := s!\"{header}{argS}{showSyntax type}\"\n        \n        match Lean.Parser.runParserCategory (\u2190 getEnv) `term funTypeStr with\n        | Except.ok termStx => \n              let mut fullString := funTypeStr \n              let mut segments : Array (String \u00d7 String) := #[]\n              let mut cursor : String.Pos := 0\n              let res := identSubs termStx\n              for ss in res do \n                fullString := ss.str\n                let pred := fullString.extract cursor ss.startPos\n                segments := segments.push (pred, ss.toString)\n                cursor := ss.stopPos\n              let tail := fullString.extract cursor fullString.endPos\n              return Except.ok (segments, tail)\n        | Except.error e => return Except.error e\n\ndef transformBuild (segs: (Array (String \u00d7 String)) \u00d7 String)\n        (transf : String \u2192 MetaM (Option String)) : MetaM (String) := do\n        let (pairs, tail) := segs\n        let res : Array (String \u00d7 String) \u2190  \n          pairs.mapM (fun (pred, ident) => do\n            let ident'? \u2190 transf ident \n            let ident' := ident'?.getD ident\n            return (pred, ident'))\n        let out : String := \n          res.foldr (fun (init, ident) acc => (init ++ ident ++ acc)) tail\n        return out\n\n/-- given a string like `{A: Type} \u2192 (a : A) \u2192 P a` broken up into identifiers and intermediate segments, transforms this by translating identifiers using a given one-one and a given one-many transformation and returns corresponding lists of segments -/\ndef polyTransform (pairs: (List (String \u00d7 String)))\n        (transf : String \u2192 MetaM (Option String))\n        (extraTransf : List (String \u2192 MetaM (Option String))) : \n            MetaM (List (List (String \u00d7 String))) := do\n        match pairs with\n        | [] => return [[]]\n        | h :: ts =>\n          let (pred, ident) := h\n          let ident' :=  (\u2190 transf ident).getD ident\n          let extraIdents \u2190 \n              extraTransf.filterMapM (fun f => f ident')\n          let h' := (ident' :: extraIdents).map ((pred, .))\n          let prev \u2190 polyTransform ts  transf extraTransf\n          return h'.bind (fun x => prev.map (x :: .))\n\n/-- given a string like `{A: Type} \u2192 (a : A) \u2192 P a` broken up into identifiers and intermediate segments, transforms this by translating identifiers using a given one-one and a given one-many transformation and builds strings from the results -/\ndef polyTransformBuild (segs: (Array (String \u00d7 String)) \u00d7 String)\n        (transf : String \u2192 MetaM (Option String))\n        (extraTransf : List (String \u2192 MetaM (Option String))) (limit : Option Nat := none) : \n        MetaM (List String) := do\n        let (pairs, tail) := segs\n        if (pairs.size \u2265  limit.getD (pairs.size + 1)) then return []\n        else \n        -- IO.println s!\"building {pairs.size} segments\"\n        let transformed \u2190 polyTransform pairs.toList transf extraTransf\n        -- IO.println s!\"transformed to {transformed.length} pieces\"\n        let strings := \n          transformed.map (fun res => \n            res.foldr (fun (init, ident) acc => (init ++ ident ++ acc)) tail)\n        -- IO.println \"built strings\"\n        return strings.eraseDups\n\n\ndef identMappedFunStx (s: String)\n    (transf : String \u2192 MetaM (Option String) := binName?)(opens: List String := [])  : MetaM (Except String String) := do\n    let corr?  \u2190 identThmSegments s opens\n    match corr? with\n    | Except.ok corr => do\n          let t \u2190 transformBuild corr transf\n          return Except.ok t\n    | Except.error e => return Except.error e\n\n/-- transforms a string expected to be of a form like `{A: Type} \u2192 (a : A) \u2192 P a` by translating identifiers using a given one-one and a given one-many transformation  -/\ndef polyIdentMappedFunStx (s: String)\n    (transf : String \u2192 MetaM (Option String) := caseOrBinName?)\n    (extraTransf : List (String \u2192 MetaM (Option String)) \n        := [])\n    (opens: List String := [])(limit : Option Nat := none)  : MetaM (Except String (List String)) := do\n    let corr?  \u2190 identThmSegments s opens\n    match corr? with\n    | Except.ok corr => do\n          let t \u2190 polyTransformBuild corr transf extraTransf limit\n          return Except.ok t\n    | Except.error e => return Except.error e\n\n-- #eval identThmSegments \"{K : Type u} [Field K] : is_ring K\"\n\n/-- attempts to elaborate a string expected to be of a form like  `{A: Type} \u2192 (a : A) \u2192 P a` via parsing to a term; in principle any term is parsed -/\ndef elabFuncTyp (funTypeStr : String) (levelNames : List Lean.Name := levelNames) : TermElabM (Except String <| Syntax \u00d7  Expr) := do\n    -- IO.println s!\"matching syntax {funTypeStr}\"\n    match Lean.Parser.runParserCategory (\u2190 getEnv) `term funTypeStr with\n        | Except.ok termStx => Term.withLevelNames levelNames <|\n          try \n            -- IO.println \"elaborating\"\n            let expr \u2190 Term.withoutErrToSorry <| \n                Term.elabTerm termStx none\n            return Except.ok (termStx, expr)\n          catch e => \n            return Except.error s!\"{\u2190 e.toMessageData.toString} for {termStx.reprint} (during elaboration)\"\n        | Except.error e => \n            return Except.error s!\"parsed func-type to {funTypeStr}; error while parsing as theorem: {e}\" \n\n/-- elaborates the string with translations and auto-corrections, including the one-to-many compatibility transformations and (optionally) returns a list of translations and translated strings -/\ndef polyElabThmTrans (s : String)(limit : Option Nat := none)\n  (transf : String \u2192 MetaM (Option String) := caseOrBinName?)\n  (extraTransf : List (String \u2192 MetaM (Option String))\n        := [])\n  (opens: List String := []) \n  (levelNames : List Lean.Name := levelNames)\n  : TermElabM <| Except String (List (Expr \u00d7 Syntax \u00d7 String)) := do\n  match \u2190 polyIdentMappedFunStx s transf extraTransf opens limit with\n  | Except.ok funTypeStrList => do\n    -- IO.println s!\"elaborating {funTypeStrList.length} strings\"\n    let pairs: List (Expr \u00d7 Syntax \u00d7 String) \u2190 \n      funTypeStrList.filterMapM (fun funTypeStr => do      \n        let expE? \u2190 elabFuncTyp funTypeStr levelNames\n        let exp? := expE?.toOption\n        return exp?.map <| fun (stx, expr) => (expr, stx , funTypeStr))\n    return Except.ok pairs\n  | Except.error e => return Except.error e\n\n/-- elaborates the string with translations and auto-corrections, including the one-to-many compatibility transformations and (optionally) returns a  translation and translated string -/\ndef elabThmTrans? (s : String)(limit : Option Nat := none)\n  (transf : String \u2192 MetaM (Option String) := caseOrBinName?)\n  (extraTransf : List (String \u2192 MetaM (Option String))\n        := [])\n  (opens: List String := []) \n  (levelNames : List Lean.Name := levelNames)\n  : TermElabM <| (Option (Expr \u00d7 Syntax \u00d7 String)) := do\n  match \u2190 polyIdentMappedFunStx s transf extraTransf opens limit with\n  | Except.ok funTypeStrList => do\n    -- IO.println s!\"elaborating {funTypeStrList.length} strings\"\n    funTypeStrList.findSomeM? (fun funTypeStr => do      \n        let expE? \u2190 elabFuncTyp funTypeStr levelNames\n        let exp? := expE?.toOption\n        return exp?.map <| fun (stx, expr) => (expr, stx , funTypeStr))\n  | Except.error _ => return none\n\ndef polyStrThmTrans (s : String)\n  (transf : String \u2192 MetaM (Option String) := caseOrBinName?)\n  (extraTransf : List (String \u2192 MetaM (Option String))\n        := [])\n  (opens: List String := []) \n  : TermElabM (List String) := do\n  match \u2190 polyIdentMappedFunStx s transf extraTransf opens with\n  | Except.ok funTypeStrList => do\n    return funTypeStrList\n  | Except.error _ => return [s]\n\ndef elabThmTrans (s : String)\n  (transf : String \u2192 MetaM (Option String) := caseOrBinName?)\n  (opens: List String := []) \n  (levelNames : List Lean.Name := levelNames)\n  : TermElabM <| Except String (Expr \u00d7 String) := do\n  match \u2190 identMappedFunStx s transf opens with\n  | Except.ok funTypeStr => do\n    match (\u2190 elabFuncTyp funTypeStr levelNames) with\n    | Except.ok (_, expr) => return Except.ok (expr, funTypeStr)\n    | Except.error e => return Except.error e\n  | Except.error e => return Except.error e\n\ndef compareFuncStrs(s\u2081 s\u2082 : String) \n  (levelNames : List Lean.Name := levelNames)\n  : TermElabM <| Except String Bool := do\n  let e\u2081 \u2190 elabFuncTyp s\u2081  levelNames\n  let e\u2082 \u2190 elabFuncTyp s\u2082 levelNames\n  match e\u2081 with\n  | Except.ok (_, e\u2081) => match e\u2082 with\n    | Except.ok (_, e\u2082) => \n        let p := (\u2190 provedEqual e\u2081 e\u2082) || \n          (\u2190 provedEquiv e\u2081 e\u2082)\n        return Except.ok p\n    | Except.error e\u2082 => return Except.error e\u2082\n  | Except.error e\u2081 => return Except.error e\u2081\n\ndef equalFuncStrs(s\u2081 s\u2082 : String) \n  (levelNames : List Lean.Name := levelNames): TermElabM Bool := do\n  match \u2190 compareFuncStrs s\u2081 s\u2082  levelNames with\n  | Except.ok p => return p\n  | Except.error _ => return Bool.false\n\n\ndef groupFuncStrs(ss: Array 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 \u2190 groups.findIdxM? (fun g => \n          equalFuncStrs s g[0]!  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 elabCorrected(depth: Nat)(ss : Array String) : \n  TermElabM (Array String) := do\n  let mut elabs : Array String := #[]\n  let mut corrected : Array String := #[]\n  for s  in ss do\n    match \u2190 elabThm s with\n    | Except.ok _ => elabs := elabs.push s\n    | Except.error err => do\n      logInfo m!\"s: {s}, err: {err}\"\n      match \u2190 identCorrection s err with\n      | none => pure ()\n      | some s' => corrected := corrected.push s'\n  if elabs.isEmpty then \n    match depth with \n    | 0 => return #[]\n    | d + 1 => if corrected.isEmpty then return #[] else do\n      elabCorrected d corrected\n  else return elabs\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/Autocorrect.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13660840057146195, "lm_q2_score": 0.023330768553822136, "lm_q1q2_score": 0.0031871789762406024}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Daniel Selsam\n-/\nimport Std.Data.RBMap\nimport Lean.Meta.SynthInstance\nimport Lean.Util.FindMVar\nimport Lean.Util.FindLevelMVar\nimport Lean.Util.CollectLevelParams\nimport Lean.Util.ReplaceLevel\nimport Lean.PrettyPrinter.Delaborator.Options\nimport Lean.PrettyPrinter.Delaborator.SubExpr\nimport Lean.Elab.Config\n\n/-!\nThe top-down analyzer is an optional preprocessor to the delaborator that aims\nto determine the minimal annotations necessary to ensure that the delaborated\nexpression can be re-elaborated correctly. Currently, the top-down analyzer\nis neither sound nor complete: there may be edge-cases in which the expression\ncan still not be re-elaborated correctly, and it may also add many annotations\nthat are not strictly necessary.\n-/\n\nnamespace Lean\n\nopen Lean.Meta\nopen Std (RBMap)\n\nregister_builtin_option pp.analyze : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) determine annotations sufficient to ensure round-tripping\"\n}\n\nregister_builtin_option pp.analyze.checkInstances : Bool := {\n  -- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not\n  -- include the `LocalInstances`, so this will be very over-aggressive in inserting instances\n  -- that would otherwise be easy to synthesize. We may consider threading the instances in the future,\n  -- or at least tracking a bool for whether the instances have been lost.\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) confirm that instances can be re-synthesized\"\n}\n\nregister_builtin_option pp.analyze.typeAscriptions : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) add type ascriptions when deemed necessary\"\n}\n\nregister_builtin_option pp.analyze.trustSubst : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' applications that can delab to \u25b8 are 'regular'\"\n}\n\nregister_builtin_option pp.analyze.trustOfNat : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up\"\n}\n\nregister_builtin_option pp.analyze.trustOfScientific : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up\"\n}\n\nregister_builtin_option pp.analyze.trustCoe : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always assume a coercion can be correctly inserted\"\n}\n\n-- TODO: this is an arbitrary special case of a more general principle.\nregister_builtin_option pp.analyze.trustSubtypeMk : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) assume the implicit arguments of Subtype.mk can be inferred\"\n}\n\nregister_builtin_option pp.analyze.trustId : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred\"\n}\n\nregister_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type\"\n}\n\nregister_builtin_option pp.analyze.omitMax : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)\"\n}\n\nregister_builtin_option pp.analyze.knowsType : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) assume the type of the original expression is known\"\n}\n\nregister_builtin_option pp.analyze.explicitHoles : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) use `_` for explicit arguments that can be inferred\"\n}\n\ndef getPPAnalyze                            (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue\ndef getPPAnalyzeCheckInstances              (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue\ndef getPPAnalyzeTypeAscriptions             (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue\ndef getPPAnalyzeTrustSubst                  (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue\ndef getPPAnalyzeTrustOfNat                  (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue\ndef getPPAnalyzeTrustOfScientific           (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue\ndef getPPAnalyzeTrustId                     (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue\ndef getPPAnalyzeTrustCoe                    (o : Options) : Bool := o.get pp.analyze.trustCoe.name pp.analyze.trustCoe.defValue\ndef getPPAnalyzeTrustSubtypeMk              (o : Options) : Bool := o.get pp.analyze.trustSubtypeMk.name pp.analyze.trustSubtypeMk.defValue\ndef getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue\ndef getPPAnalyzeOmitMax                     (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue\ndef getPPAnalyzeKnowsType                   (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue\ndef getPPAnalyzeExplicitHoles               (o : Options) : Bool := o.get pp.analyze.explicitHoles.name pp.analyze.explicitHoles.defValue\n\ndef getPPAnalysisSkip            (o : Options) : Bool := o.get `pp.analysis.skip false\ndef getPPAnalysisHole            (o : Options) : Bool := o.get `pp.analysis.hole false\ndef getPPAnalysisNamedArg        (o : Options) : Bool := o.get `pp.analysis.namedArg false\ndef getPPAnalysisLetVarType      (o : Options) : Bool := o.get `pp.analysis.letVarType false\ndef getPPAnalysisNeedsType       (o : Options) : Bool := o.get `pp.analysis.needsType false\ndef getPPAnalysisBlockImplicit   (o : Options) : Bool := o.get `pp.analysis.blockImplicit false\n\nnamespace PrettyPrinter.Delaborator\n\ndef returnsPi (motive : Expr) : MetaM Bool := do\n  lambdaTelescope motive fun xs b => return b.isForall\n\ndef isNonConstFun (motive : Expr) : MetaM Bool := do\n  match motive with\n  | Expr.lam name d b _ => isNonConstFun b\n  | _ => return motive.hasLooseBVars\n\ndef isSimpleHOFun (motive : Expr) : MetaM Bool :=\n  return not (\u2190 returnsPi motive) && not (\u2190 isNonConstFun motive)\n\ndef isType2Type (motive : Expr) : MetaM Bool := do\n  match \u2190 inferType motive with\n  | Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => return true\n  | _ => return false\n\ndef isFOLike (motive : Expr) : MetaM Bool := do\n  let f := motive.getAppFn\n  return f.isFVar || f.isConst\n\ndef isIdLike (arg : Expr) : Bool :=\n  -- TODO: allow `id` constant as well?\n  match arg with\n  | Expr.lam _ _ (Expr.bvar ..) .. => true\n  | _ => false\n\ndef isCoe (e : Expr) : Bool :=\n  -- TODO: `coeSort? Builtins doesn't seem to render them anyway\n  -- TODO: should we delete this function, we want to eagerly expand all coercions\n  e.isAppOfArity ``CoeT.coe 4\n  || (e.isAppOf ``CoeFun.coe && e.getAppNumArgs >= 4)\n  || e.isAppOfArity ``CoeSort.coe 4\n\ndef isStructureInstance (e : Expr) : MetaM Bool := do\n  match e.isConstructorApp? (\u2190 getEnv) with\n  | some s => return isStructure (\u2190 getEnv) s.induct\n  | none   => return false\n\nnamespace TopDownAnalyze\n\npartial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  return Option.isSome <| e.findMVar? fun mvarId =>\n    match mctx.findDecl? mvarId with\n    | some mdecl => mdecl.depth == mctx.depth\n    | _ => false\n\npartial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  return Option.isSome <| e.findLevelMVar? fun mvarId =>\n    mctx.findLevelDepth? mvarId == some mctx.depth\n\nprivate def valUnknown (e : Expr) : MetaM Bool := do\n  hasMVarAtCurrDepth (\u2190 instantiateMVars e)\n\nprivate def typeUnknown (e : Expr) : MetaM Bool := do\n  valUnknown (\u2190 inferType e)\n\ndef isHBinOp (e : Expr) : Bool := Id.run <| do\n  -- TODO: instead of tracking these explicitly,\n  -- consider a more general solution that checks for defaultInstances\n  if e.getAppNumArgs != 6 then return false\n  let f := e.getAppFn\n  if !f.isConst then return false\n\n  -- Note: we leave out `HPow.hPow because we expect its homogeneous\n  -- version will change soon\n  let ops := #[\n    `HOr.hOr, `HXor.hXor, `HAnd.hAnd,\n    `HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen,\n    `HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod,\n    `HShiftLeft.hShiftLeft, `HShiftRight]\n  ops.any fun op => op == f.constName!\n\ndef replaceLPsWithVars (e : Expr) : MetaM Expr := do\n  if !e.hasLevelParam then return e\n  let lps := collectLevelParams {} e |>.params\n  let mut replaceMap : Std.HashMap Name Level := {}\n  for lp in lps do replaceMap := replaceMap.insert lp (\u2190 mkFreshLevelMVar)\n  return e.replaceLevel fun\n    | Level.param n .. => replaceMap.find! n\n    | l => if !l.hasParam then some l else none\n\ndef isDefEqAssigning (t s : Expr) : MetaM Bool := do\n  withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $\n    Meta.isDefEq t s\n\ndef checkpointDefEq (t s : Expr) : MetaM Bool := do\n  Meta.checkpointDefEq (mayPostpone := false) do\n    isDefEqAssigning t s\n\ndef isHigherOrder (type : Expr) : MetaM Bool := do\n  forallTelescopeReducing type fun xs b => return xs.size > 0 && b.isSort\n\ndef isFunLike (e : Expr) : MetaM Bool := do\n  forallTelescopeReducing (\u2190 inferType e) fun xs b => return xs.size > 0\n\ndef isSubstLike (e : Expr) : Bool :=\n  e.isAppOfArity `Eq.ndrec 6 || e.isAppOfArity `Eq.rec 6\n\ndef nameNotRoundtrippable (n : Name) : Bool :=\n  n.hasMacroScopes || isPrivateName n || containsNum n\nwhere\n  containsNum\n    | Name.str p .. => containsNum p\n    | Name.num ..   => true\n    | Name.anonymous => false\n\ndef mvarName (mvar : Expr) : MetaM Name :=\n  return (\u2190 getMVarDecl mvar.mvarId!).userName\n\ndef containsBadMax : Level \u2192 Bool\n  | Level.succ u ..   => containsBadMax u\n  | Level.max u v ..  => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v\n  | Level.imax u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v\n  | _                 => false\n\nopen SubExpr\n\nstructure Context where\n  knowsType   : Bool\n  knowsLevel  : Bool -- only constants look at this\n  inBottomUp  : Bool := false\n  parentIsApp : Bool := false\n  subExpr     : SubExpr\n  deriving Inhabited\n\nstructure State where\n  annotations : RBMap Pos Options compare := {}\n  postponed   : Array (Expr \u00d7 Expr) := #[] -- not currently used\n\nabbrev AnalyzeM := ReaderT Context (StateRefT State MetaM)\n\ninstance (priority := low) : MonadReaderOf SubExpr AnalyzeM where\n  read := Context.subExpr <$> read\n\ninstance (priority := low) : MonadWithReaderOf SubExpr AnalyzeM where\n  withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr }\n\ndef tryUnify (e\u2081 e\u2082 : Expr) : AnalyzeM Unit := do\n  try\n    let r \u2190 isDefEqAssigning e\u2081 e\u2082\n    if !r then modify fun s => { s with postponed := s.postponed.push (e\u2081, e\u2082) }\n    pure ()\n  catch ex =>\n    modify fun s => { s with postponed := s.postponed.push (e\u2081, e\u2082) }\n\npartial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do\n  let argType  \u2190 inferType arg -- HAdd \u03b1 \u03b1 \u03b1\n  let mvarType \u2190 inferType mvar\n  let fType \u2190 inferType argType.getAppFn -- Type \u2192 Type \u2192 outParam Type\n  let mType \u2190 inferType mvarType.getAppFn\n  inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs\nwhere\n  inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do\n    let fType \u2190 whnf fType\n    let mType \u2190 whnf mType\n    if not (i < args.size) then return ()\n    match fType, mType with\n    | Expr.forallE _ fd fb _, Expr.forallE _ md mb _ => do\n      -- TODO: do I need to check (\u2190 okBottomUp? args[i] mvars[i] fuel).isSafe here?\n      -- if so, I'll need to take a callback\n      if isOutParam fd then\n        tryUnify (args[i]) (mvars[i])\n      inspectAux (fb.instantiate1 args[i]) (mb.instantiate1 mvars[i]) (i+1) args mvars\n    | _, _ => return ()\n\npartial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do\n  let opts \u2190 getOptions\n  return e.isFVar\n         || e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort\n         || (getPPAnalyzeTrustOfNat opts && e.isAppOfArity `OfNat.ofNat 3)\n         || (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity `OfScientific.ofScientific 5)\n\npartial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do\n  -- Here we check if `e` can be safely elaborated without its expected type.\n  -- These are incomplete (and possibly unsound) heuristics.\n  -- TODO: do I need to snapshot the state before calling this?\n  match fuel with\n  | 0 => return false\n  | fuel + 1 =>\n    if \u2190 isTrivialBottomUp e then return true\n    let f := e.getAppFn\n    if !f.isConst && !f.isFVar then return false\n    let args := e.getAppArgs\n    let fType \u2190 replaceLPsWithVars (\u2190 inferType e.getAppFn)\n    let (mvars, bInfos, resultType) \u2190 forallMetaBoundedTelescope fType e.getAppArgs.size\n    for i in [:mvars.size] do\n      if bInfos[i] == BinderInfo.instImplicit then\n        inspectOutParams args[i] mvars[i]\n      else if bInfos[i] == BinderInfo.default then\n        if \u2190 isTrivialBottomUp args[i] then tryUnify args[i] mvars[i]\n        else if \u2190 typeUnknown mvars[i] <&&> canBottomUp args[i] mvars[i] fuel then tryUnify args[i] mvars[i]\n    if \u2190 (pure (isHBinOp e) <&&> (valUnknown mvars[0] <||> valUnknown mvars[1])) then tryUnify mvars[0] mvars[1]\n    if mvar?.isSome then tryUnify resultType (\u2190 inferType mvar?.get!)\n    return !(\u2190 valUnknown resultType)\n\ndef withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM \u03b1) : AnalyzeM \u03b1 := do\n  withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x\n\nbuiltin_initialize analyzeFailureId : InternalExceptionId \u2190 registerInternalExceptionId `analyzeFailure\n\ndef checkKnowsType : AnalyzeM Unit := do\n  if not (\u2190 read).knowsType then\n    throw $ Exception.internal analyzeFailureId\n\ndef annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do\n  let opts := (\u2190 get).annotations.findD pos {} |>.setBool n true\n  trace[pp.analyze.annotate] \"{pos} {n}\"\n  modify fun s => { s with annotations := s.annotations.insert pos opts }\n\ndef annotateBool (n : Name) : AnalyzeM Unit := do\n  annotateBoolAt n (\u2190 getPos)\n\nstructure App.Context where\n  f               : Expr\n  fType           : Expr\n  args            : Array Expr\n  mvars           : Array Expr\n  bInfos          : Array BinderInfo\n  forceRegularApp : Bool\n\nstructure App.State where\n  bottomUps       : Array Bool\n  higherOrders    : Array Bool\n  funBinders      : Array Bool\n  provideds       : Array Bool\n  namedArgs       : Array Name := #[]\n\nabbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM)\n\nmutual\n\n  partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do\n    checkMaxHeartbeats \"Delaborator.topDownAnalyze\"\n    trace[pp.analyze] \"{(\u2190 read).knowsType}.{(\u2190 read).knowsLevel}\"\n    let e \u2190 getExpr\n    let opts \u2190 getOptions\n    if \u2190 (pure !e.isAtomic) <&&> pure !(getPPProofs opts) <&&> (try Meta.isProof e catch ex => pure false) then\n      if getPPProofsWithType opts then\n        withType $ withKnowing true true $ analyze\n      return ()\n    else\n      withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do\n        match (\u2190 getExpr) with\n        | Expr.app ..     => analyzeApp\n        | Expr.forallE .. => analyzePi\n        | Expr.lam ..     => analyzeLam\n        | Expr.const ..   => analyzeConst\n        | Expr.sort ..    => analyzeSort\n        | Expr.proj ..    => analyzeProj\n        | Expr.fvar ..    => analyzeFVar\n        | Expr.mdata ..   => analyzeMData\n        | Expr.letE ..    => analyzeLet\n        | Expr.lit ..     => pure ()\n        | Expr.mvar ..    => pure ()\n        | Expr.bvar ..    => pure ()\n  where\n    analyzeApp := do\n      let mut willKnowType := (\u2190 read).knowsType\n      if !(\u2190 read).knowsType && !(\u2190 canBottomUp (\u2190 getExpr)) then\n        annotateBool `pp.analysis.needsType\n        withType $ withKnowing true false $ analyze\n        willKnowType := true\n\n      else if \u2190 (pure !(\u2190 read).knowsType <||> pure (\u2190 read).inBottomUp) <&&> isStructureInstance (\u2190 getExpr) then\n        withType do\n          annotateBool `pp.structureInstanceTypes\n          withKnowing true false $ analyze\n        willKnowType := true\n\n      withKnowing willKnowType true $ analyzeAppStaged (\u2190 getExpr).getAppFn (\u2190 getExpr).getAppArgs\n\n    analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do\n      let fType \u2190 replaceLPsWithVars (\u2190 inferType f)\n      let (mvars, bInfos, resultType) \u2190 forallMetaBoundedTelescope fType args.size\n      let rest := args.extract mvars.size args.size\n      let args := args.shrink mvars.size\n\n      -- Unify with the expected type\n      if (\u2190 read).knowsType then tryUnify (\u2190 inferType (mkAppN f args)) resultType\n\n      let forceRegularApp : Bool :=\n        (getPPAnalyzeTrustSubst (\u2190 getOptions) && isSubstLike (\u2190 getExpr))\n        || (getPPAnalyzeTrustCoe (\u2190 getOptions) && isCoe (\u2190 getExpr))\n        || (getPPAnalyzeTrustSubtypeMk (\u2190 getOptions) && (\u2190 getExpr).isAppOfArity `Subtype.mk 4)\n\n      analyzeAppStagedCore { f, fType, args, mvars, bInfos, forceRegularApp } |>.run' {\n        bottomUps    := mkArray args.size false,\n        higherOrders := mkArray args.size false,\n        provideds    := mkArray args.size false,\n        funBinders   := mkArray args.size false\n      }\n\n      if not rest.isEmpty then\n        -- Note: this shouldn't happen for type-correct terms\n        if !args.isEmpty then\n          analyzeAppStaged (mkAppN f args) rest\n\n    maybeAddBlockImplicit : AnalyzeM Unit := do\n      -- See `MonadLift.noConfusion for an example where this is necessary.\n      if !(\u2190 read).parentIsApp then\n        let type \u2190 inferType (\u2190 getExpr)\n        if type.isForall && type.bindingInfo! == BinderInfo.implicit then\n          annotateBool `pp.analysis.blockImplicit\n\n    analyzeConst : AnalyzeM Unit := do\n      let Expr.const n ls .. \u2190 getExpr | unreachable!\n      if !(\u2190 read).knowsLevel && !ls.isEmpty then\n        -- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590\n        unless getPPAnalyzeOmitMax (\u2190 getOptions) && ls.any containsBadMax do\n        annotateBool `pp.universes\n      maybeAddBlockImplicit\n\n    analyzePi : AnalyzeM Unit := do\n      withBindingDomain $ withKnowing true false analyze\n      withBindingBody Name.anonymous analyze\n\n    analyzeLam : AnalyzeM Unit := do\n      if !(\u2190 read).knowsType then annotateBool `pp.funBinderTypes\n      withBindingDomain $ withKnowing true false analyze\n      withBindingBody Name.anonymous analyze\n\n    analyzeLet : AnalyzeM Unit := do\n      let Expr.letE n t v body .. \u2190 getExpr | unreachable!\n      if !(\u2190 canBottomUp v) then\n        annotateBool `pp.analysis.letVarType\n        withLetVarType $ withKnowing true false analyze\n        withLetValue $ withKnowing true true analyze\n      else\n        withReader (fun ctx => { ctx with inBottomUp := true }) do\n          withLetValue $ withKnowing true true analyze\n\n      withLetBody analyze\n\n    analyzeSort  : AnalyzeM Unit := pure ()\n    analyzeProj  : AnalyzeM Unit := withProj analyze\n    analyzeFVar  : AnalyzeM Unit := maybeAddBlockImplicit\n    analyzeMData : AnalyzeM Unit := withMDataExpr analyze\n\n  partial def analyzeAppStagedCore : AnalyzeAppM Unit := do\n    collectBottomUps\n    checkOutParams\n    collectHigherOrders\n    hBinOpHeuristic\n    collectTrivialBottomUps\n    discard <| processPostponed (mayPostpone := true)\n    applyFunBinderHeuristic\n    analyzeFn\n    for i in [:(\u2190 read).args.size] do analyzeArg i\n    maybeSetExplicit\n\n  where\n    collectBottomUps := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for target in [fun _ => none, fun i => some mvars[i]] do\n        for i in [:args.size] do\n          if bInfos[i] == BinderInfo.default then\n            if \u2190 typeUnknown mvars[i] <&&> canBottomUp args[i] (target i) then\n              tryUnify args[i] mvars[i]\n              modify fun s => { s with bottomUps := s.bottomUps.set! i true }\n\n    checkOutParams := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if bInfos[i] == BinderInfo.instImplicit then inspectOutParams args[i] mvars[i]\n\n    collectHigherOrders := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if not (bInfos[i] == BinderInfo.implicit || bInfos[i] == BinderInfo.strictImplicit) then continue\n        if not (\u2190 isHigherOrder (\u2190 inferType args[i])) then continue\n        if getPPAnalyzeTrustId (\u2190 getOptions) && isIdLike args[i] then continue\n\n        if getPPAnalyzeTrustKnownFOType2TypeHOFuns (\u2190 getOptions) && not (\u2190 valUnknown mvars[i])\n          && (\u2190 isType2Type (args[i])) && (\u2190 isFOLike (args[i])) then continue\n\n        tryUnify args[i] mvars[i]\n        modify fun s => { s with higherOrders := s.higherOrders.set! i true }\n\n    hBinOpHeuristic := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      if \u2190 (pure (isHBinOp (\u2190 getExpr)) <&&> (valUnknown mvars[0] <||> valUnknown mvars[1])) then\n        tryUnify mvars[0] mvars[1]\n\n    collectTrivialBottomUps := do\n      -- motivation: prevent levels from printing in\n      -- Boo.mk : {\u03b1 : Type u_1} \u2192 {\u03b2 : Type u_2} \u2192 \u03b1 \u2192 \u03b2 \u2192 Boo.{u_1, u_2} \u03b1 \u03b2\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if bInfos[i] == BinderInfo.default then\n          if \u2190 valUnknown mvars[i] <&&> isTrivialBottomUp args[i] then\n            tryUnify args[i] mvars[i]\n            modify fun s => { s with bottomUps := s.bottomUps.set! i true }\n\n    applyFunBinderHeuristic := do\n      let { f, args, mvars, bInfos, .. } \u2190 read\n\n      let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do\n        match \u2190 getExpr, mvarType with\n        | Expr.lam .., Expr.forallE n t b .. =>\n          let mut annotated := false\n          for i in [:argIdx] do\n            if \u2190 pure (bInfos[i] == BinderInfo.implicit) <&&> valUnknown mvars[i] <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]) then\n              annotateBool `pp.funBinderTypes\n              tryUnify args[i] mvars[i]\n              -- Note: currently we always analyze the lambda binding domains in `analyzeLam`\n              -- (so we don't need to analyze it again here)\n              annotated := true\n              break\n          let annotatedBody \u2190 withBindingBody Name.anonymous (core argIdx b)\n          return annotated || annotatedBody\n\n        | _, _ => return false\n\n      for i in [:args.size] do\n        if bInfos[i] == BinderInfo.default then\n          let b \u2190 withNaryArg i (core i (\u2190 inferType mvars[i]))\n          if b then modify fun s => { s with funBinders := s.funBinders.set! i true }\n\n    analyzeFn := do\n      -- Now, if this is the first staging, analyze the n-ary function without expected type\n      let {f, fType, forceRegularApp ..} \u2190 read\n      if !f.isApp then withKnowing false (forceRegularApp || !(\u2190 hasLevelMVarAtCurrDepth (\u2190 instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true))\n\n    annotateNamedArg (n : Name) : AnalyzeAppM Unit := do\n      annotateBool `pp.analysis.namedArg\n      modify fun s => { s with namedArgs := s.namedArgs.push n }\n\n    analyzeArg (i : Nat) := do\n      let { f, args, mvars, bInfos, forceRegularApp ..} \u2190 read\n      let { bottomUps, higherOrders, funBinders, ..} \u2190 get\n      let arg := args[i]\n      let argType \u2190 inferType arg\n\n      let processNaturalImplicit : AnalyzeAppM Unit := do\n        if (\u2190 valUnknown mvars[i] <||> pure higherOrders[i]) && !forceRegularApp then\n          annotateNamedArg (\u2190 mvarName mvars[i])\n          modify fun s => { s with provideds := s.provideds.set! i true }\n        else\n          annotateBool `pp.analysis.skip\n\n      withNaryArg (f.getAppNumArgs + i) do\n        withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i] }) do\n\n          match bInfos[i] with\n          | BinderInfo.default =>\n            if \u2190 pure (getPPAnalyzeExplicitHoles (\u2190 getOptions)) <&&> pure !(\u2190 valUnknown mvars[i]) <&&> pure !(\u2190 readThe Context).inBottomUp <&&> pure !(\u2190 isFunLike arg) <&&> pure !funBinders[i] <&&> checkpointDefEq mvars[i] arg then\n              annotateBool `pp.analysis.hole\n            else\n              modify fun s => { s with provideds := s.provideds.set! i true }\n\n          | BinderInfo.implicit => processNaturalImplicit\n          | BinderInfo.strictImplicit => processNaturalImplicit\n\n          | BinderInfo.instImplicit =>\n            -- Note: apparently checking valUnknown here is not sound, because the elaborator\n            -- will not happily assign instImplicits that it cannot synthesize\n            let mut provided := true\n            if !getPPInstances (\u2190 getOptions) then\n              annotateBool `pp.analysis.skip\n              provided := false\n            else if getPPAnalyzeCheckInstances (\u2190 getOptions) then\n              let instResult \u2190 try trySynthInstance argType catch _ => pure LOption.undef\n              match instResult with\n              | LOption.some inst =>\n                if \u2190 checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false\n                else annotateNamedArg (\u2190 mvarName mvars[i])\n              | _                 => annotateNamedArg (\u2190 mvarName mvars[i])\n            else annotateBool `pp.analysis.skip; provided := false\n            modify fun s => { s with provideds := s.provideds.set! i provided }\n          | BinderInfo.auxDecl => pure ()\n          if (\u2190 get).provideds[i] then withKnowing (not (\u2190 typeUnknown mvars[i])) true analyze\n          tryUnify mvars[i] args[i]\n\n    maybeSetExplicit := do\n      let { f, args, mvars, bInfos, forceRegularApp, ..} \u2190 read\n      if (\u2190 get).namedArgs.any nameNotRoundtrippable then\n        annotateBool `pp.explicit\n        for i in [:args.size] do\n          if !(\u2190 get).provideds[i] then\n            withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole\n          if bInfos[i] == BinderInfo.instImplicit && getPPInstanceTypes (\u2190 getOptions) then\n            withType (withKnowing true false analyze)\n\nend\n\nend TopDownAnalyze\n\nopen TopDownAnalyze SubExpr\n\ndef topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do\n  let s\u2080 \u2190 get\n  traceCtx `pp.analyze do\n    withReader (fun ctx => { ctx with config := Elab.Term.setElabConfig ctx.config }) do\n      let \u03d5 : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; pure (\u2190 get).annotations\n      try\n        let knowsType := getPPAnalyzeKnowsType (\u2190 getOptions)\n        \u03d5 { knowsType := knowsType, knowsLevel := knowsType, subExpr := mkRoot e }\n          |>.run' { : TopDownAnalyze.State }\n      catch ex =>\n        trace[pp.analyze.error] \"failed\"\n        pure {}\n      finally set s\u2080\n\nbuiltin_initialize\n  registerTraceClass `pp.analyze\n  registerTraceClass `pp.analyze.annotate\n  registerTraceClass `pp.analyze.tryUnify\n  registerTraceClass `pp.analyze.error\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/TopDownAnalyze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10521053109182897, "lm_q2_score": 0.030214585866664676, "lm_q1q2_score": 0.00317889262575146}}
{"text": "import LeanInk.Annotation.Basic\nimport LeanInk.Logger\nimport LeanInk.Analysis.DataTypes\nimport LeanInk.Annotation.Util\nimport LeanInk.FileHelper\n\nimport Lean.Data.Json\nimport Lean.Data.Json.FromToJson\nimport Lean.Data.Lsp\n\nnamespace LeanInk.Annotation.Alectryon\n\nopen Lean\nopen LeanInk.Analysis\n\nstructure TypeInfo where\n  _type : String := \"typeinfo\"\n  name : String\n  type : String\n  deriving ToJson\n\nstructure Token where\n  _type : String := \"token\"\n  raw : String\n  typeinfo : Option TypeInfo := Option.none\n  link : Option String := Option.none\n  docstring : Option String := Option.none\n  semanticType : Option String :=  Option.none\n  deriving ToJson\n\n/--\n  Support type for experimental --experimental-type-tokens feature\n  If flag not set please only use the string case.\n-/\ninductive Contents where\n  | string (value : String)\n  | experimentalTokens (value : Array Token)\n\ninstance : ToJson Contents where\n  toJson\n    | Contents.string v => toJson v\n    | Contents.experimentalTokens v => toJson v\n\nstructure Hypothesis where\n  _type : String := \"hypothesis\"\n  names : List String\n  body : String\n  type : String\n  deriving ToJson\n\nstructure Goal where\n  _type : String := \"goal\"\n  name : String\n  conclusion : String\n  hypotheses : Array Hypothesis\n  deriving ToJson\n\nstructure Message where\n  _type : String := \"message\"  \n  contents : String\n  deriving ToJson\n\nstructure Sentence where\n  _type : String := \"sentence\"\n  contents : Contents\n  messages : Array Message\n  goals : Array Goal\n  deriving ToJson\n\nstructure Text where\n  _type : String := \"text\"\n  contents : Contents\n  deriving ToJson\n\n/-- \nWe need a custom ToJson implementation for Alectryons fragments.\n\nFor example we have following fragment:\n```\nFragment.text { contents := \"Test\" }\n```\n\nWe want to serialize this to:\n```\n[{\"contents\": \"Test\", \"_type\": \"text\"}]\n```\n\ninstead of:\n```\n[{\"text\": {\"contents\": \"Test\", \"_type\": \"text\"}}]\n```\n\nThis is because of the way Alectryon decodes the json files. It uses the _type field to\ndetermine the namedTuple type with Alectryon.\n-/\ninductive Fragment where\n  | text (value : Text)\n  | sentence (value : Sentence)\n\ninstance : ToJson Fragment where\n  toJson\n    | Fragment.text v => toJson v\n    | Fragment.sentence v => toJson v\n\n/- \n  Token Generation\n-/\n\ndef genTypeInfo? (getContents : String.Pos -> String.Pos -> Option String) (token : Analysis.TypeTokenInfo) : AnalysisM (Option TypeInfo) := do\n  match token.type with\n  | some type => do\n    let headPos := Positional.headPos token\n    let tailPos := Positional.tailPos token\n    match getContents headPos tailPos with \n    | none => pure none\n    | \"\" => pure none\n    | some x => return some { name := x, type := type }\n  | none => pure none\n\ndef genSemanticTokenValue : Option SemanticTokenInfo -> AnalysisM (Option String)\n  | none => pure none\n  | some info =>\n    match info.semanticType with\n    | SemanticTokenType.property => pure (some \"Name.Attribute\")\n    | SemanticTokenType.keyword => pure (some \"Keyword\")\n    | SemanticTokenType.variable => pure (some \"Name.Variable\")\n    | default => pure none\n\ndef genToken (token : Compound Analysis.Token) (contents : Option String) (getContents : String.Pos -> String.Pos -> Option String) : AnalysisM (Option Token) := do\n  match contents with\n  | none => return none\n  | \"\" => return none\n  | some contents => do\n    let typeTokens := token.getFragments.filterMap (\u03bb x => x.toTypeTokenInfo?)\n    let semanticTokens := token.getFragments.filterMap (\u03bb x => x.toSemanticTokenInfo?)\n    let semanticToken := Positional.smallest? semanticTokens\n    let semanticTokenType \u2190 genSemanticTokenValue semanticToken\n    match (Positional.smallest? typeTokens) with\n    | none => do \n      return some { raw := contents, semanticType := semanticTokenType }\n    | some token => do \n      return some { raw := contents, typeinfo := \u2190 genTypeInfo? getContents token, link := none, docstring := token.docString, semanticType := semanticTokenType }\n\ndef extractContents (offset : String.Pos) (contents : String) (head tail: String.Pos) : Option String := \n  if head >= tail then\n    none\n  else\n    contents.extract (head - offset) (tail - offset)\n\ndef minPos (x y : String.Pos) := if x < y then x else y\ndef maxPos (x y : String.Pos) := if x > y then x else y\n\npartial def genTokens (contents : String) (head : String.Pos) (offset : String.Pos) (l : List Token)  (compounds : List (Compound Analysis.Token)) : AnalysisM (List Token) := do\n  let textTail := \u27e8contents.utf8ByteSize\u27e9 + offset\n  let mut head : String.Pos := head\n  let mut tokens : List Token := []\n  for x in compounds do\n    let extract := extractContents offset contents\n    let tail := x.tailPos.getD textTail\n    if x.headPos <= head then\n      let text := extract head tail\n      head := tail\n      logInfo s!\"Text-B1: {text}\"\n      match (\u2190 genToken x text extract) with\n      | none => logInfo s!\"Empty 1 {text} {x.headPos} {tail}\"\n      | some fragment => tokens := fragment::tokens\n    else\n      let text := extract head x.headPos\n      head := x.headPos\n      logInfo s!\"Text-B2: {text}\"\n      match text with\n      | none => logInfo s!\"Empty 1 {text} {x.headPos} {tail}\"\n      | some text => tokens := { raw := text }::tokens\n  match extractContents offset contents head (\u27e8contents.utf8ByteSize\u27e9 + offset) with\n  | none => return tokens.reverse\n  | some x => return ({ raw := x }::tokens).reverse\n  \n/- \n  Fragment Generation\n-/\n\ndef genHypothesis (hypothesis : Analysis.Hypothesis) : Hypothesis := {\n  names := hypothesis.names\n  body := hypothesis.body\n  type := hypothesis.type\n}\n\ndef genGoal (goal : Analysis.Goal) : Goal := {\n  name := goal.name\n  conclusion := goal.conclusion\n  hypotheses := (goal.hypotheses.map genHypothesis).toArray\n}\n\ndef genGoals (beforeNode: Bool) (tactic : Analysis.Tactic) : List Goal := \n  if beforeNode then \n    tactic.goalsBefore.map (\u03bb g => genGoal g)\n  else\n    tactic.goalsAfter.map (\u03bb g => genGoal g)\n\ndef genMessages (message : Analysis.Message) : Message := { contents := message.msg }\n\ndef genFragment (annotation : Annotation) (globalTailPos : String.Pos) (contents : String) : AnalysisM Alectryon.Fragment := do\n  let config \u2190 read\n  if annotation.sentence.fragments.isEmpty then\n    if config.experimentalTypeInfo \u2228 config.experimentalDocString then\n      let headPos := annotation.sentence.headPos\n      let tokens \u2190 genTokens contents headPos headPos [] annotation.tokens\n      return Fragment.text { contents := Contents.experimentalTokens tokens.toArray }\n    else\n      return Fragment.text { contents := Contents.string contents }\n  else\n    let tactics : List Analysis.Tactic := annotation.sentence.getFragments.filterMap (\u03bb f => f.asTactic?)\n    let messages : List Analysis.Message := annotation.sentence.getFragments.filterMap (\u03bb f => f.asMessage?)\n    let mut goals : List Goal := []\n    if let (some tactic) := Positional.smallest? tactics then\n      let useBefore : Bool := tactic.tailPos > globalTailPos\n      goals := genGoals useBefore tactic\n    let mut fragmentContents : Contents := Contents.string contents\n    if config.experimentalTypeInfo \u2228 config.experimentalDocString then\n      let headPos := annotation.sentence.headPos\n      let tokens \u2190 genTokens contents headPos headPos [] annotation.tokens\n      fragmentContents := Contents.experimentalTokens tokens.toArray\n    return Fragment.sentence { \n      contents := fragmentContents\n      goals := goals.toArray\n      messages := (messages.map genMessages).toArray\n    }\n\n/-\nExpects a list of sorted CompoundFragments (sorted by headPos).\nGenerates AlectryonFragments for the given CompoundFragments and input file content.\n-/\ndef annotateFileWithCompounds (l : List Alectryon.Fragment) (contents : String) : List Annotation -> AnalysisM (List Fragment)\n| [] => pure l\n| x::[] => do\n  let fragment \u2190 genFragment x \u27e8contents.utf8ByteSize\u27e9 (contents.extract x.sentence.headPos \u27e8contents.utf8ByteSize\u27e9)\n  return l.append [fragment]\n| x::y::ys => do\n  let fragment \u2190 genFragment x y.sentence.headPos (contents.extract x.sentence.headPos (y.sentence.headPos))\n  return (\u2190 annotateFileWithCompounds (l.append [fragment]) contents (y::ys))\n\ndef genOutput (annotation : List Annotation) : AnalysisM UInt32 := do\n  let config := (\u2190 read)\n  let fragments \u2190 annotateFileWithCompounds [] config.inputFileContents annotation\n  let rawContents \u2190 generateOutput fragments.toArray\n  createOutputFile (\u2190 IO.currentDir) config.inputFileName rawContents\n  return 0\n", "meta": {"author": "leanprover", "repo": "LeanInk", "sha": "499cf46f571562bebee0c8c193a7f9dcf5a30187", "save_path": "github-repos/lean/leanprover-LeanInk", "path": "github-repos/lean/leanprover-LeanInk/LeanInk-499cf46f571562bebee0c8c193a7f9dcf5a30187/LeanInk/Annotation/Alectryon.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.13846178701384174, "lm_q2_score": 0.02262919908552134, "lm_q1q2_score": 0.0031332793440732778}}
{"text": "import .hp hp.writeup basic\nuniverses u\n\nopen widget\nopen tactic.unsafe\nopen tactic\n\nnamespace hp\n\nmeta def rc (\u03c0 \u03b1) := interaction_component hp_state \u03c0 \u03b1\n\nmeta instance : has_should_update hp_state :=\n{su := \u03bb rs\u2081 rs\u2082, (rs\u2081.b \u2260 rs\u2082.b)}\n\nvariables {\u03c0 \u03b1 : Type} [has_should_update \u03c0]\n\n-- meta instance tc_coe_rc: has_coe (tc \u03c0 \u03b1) (rc \u03c0 \u03b1) :=\n-- \u27e8\u03bb c, interaction_component.bind_props (\u03bb p, do ts \u2190 hp_state.ts <$> get, pure (ts,p)) $ interaction_component.of_component c\u27e9\n\nmeta def rc.to_component : rc \u03c0 \u03b1 \u2192 component (hp_state \u00d7 \u03c0) \u03b1\n| r := interaction_component.to_component r\n\nmeta instance rc_fun : has_coe_to_fun (rc \u03c0 \u03b1) :=\n\u27e8 \u03bb c, \u03c0 \u2192 hp (html \u03b1)\n, \u03bb c p, do rs \u2190 get, pure $ html.of_component (rs, p) c.to_component\n\u27e9\n\nmeta def rc.stateless {\u03c0 \u03b1} [has_should_update \u03c0] (view : \u03c0 \u2192 hp (list (html \u03b1))): rc \u03c0 \u03b1 :=\ninteraction_component.stateless (\u03bb p, view p)\n\n/-- An rc for rendering as a secondary tactic type.\nThe main example being subtasks. -/\nmeta def inner_component := html (hp_state)\n\nmeta inductive rc.action : Type\n| new_state (rs : hp_state)\n| interactive_inner_tactic (rc : inner_component)\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/tactic/hp_component.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.16238002045272698, "lm_q2_score": 0.019124036750888904, "lm_q1q2_score": 0.0031053614787480426}}
{"text": "/-\nCopyright (c) 2021 Henrik B\u00f6ving. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Henrik B\u00f6ving\n-/\nimport DocGen4.Process\nimport DocGen4.Output.ToHtmlFormat\n\nnamespace DocGen4.Output\n\nopen scoped DocGen4.Jsx\nopen Lean System Widget Elab Process\n\ndef basePath := FilePath.mk \".\" / \"build\" / \"doc\"\ndef srcBasePath := basePath / \"src\"\ndef declarationsBasePath := basePath / \"declarations\"\n\n/--\nThe context used in the `BaseHtmlM` monad for HTML templating.\n-/\nstructure SiteBaseContext where\n\n  /--\n  The module hierarchy as a tree structure.\n  -/\n  hierarchy : Hierarchy\n  /--\n  How far away we are from the page root, used for relative links to the root.\n  -/\n  depthToRoot: Nat\n  /--\n  The name of the current module if there is one, there exist a few\n  pages that don't have a module name.\n  -/\n  currentName : Option Name\n  /--\n  The Github URL of the project that we are building docs for.\n  -/\n  projectGithubUrl : String\n  /--\n  The commit of the project that we are building docs for.\n  -/\n  projectCommit : String\n\n/--\nThe context used in the `HtmlM` monad for HTML templating.\n-/\nstructure SiteContext where\n  /--\n  The full analysis result from the Process module.\n  -/\n  result : AnalyzerResult\n  /--\n  A function to link declaration names to their source URLs, usually Github ones.\n  -/\n  sourceLinker : Name \u2192 Option DeclarationRange \u2192 String\n  /--\n  Whether LeanInk is enabled\n  -/\n  leanInkEnabled : Bool\n\ndef setCurrentName (name : Name) (ctx : SiteBaseContext) := {ctx with currentName := some name}\n\nabbrev BaseHtmlT := ReaderT SiteBaseContext\nabbrev BaseHtmlM := BaseHtmlT Id\n\nabbrev HtmlT (m) := ReaderT SiteContext (BaseHtmlT m)\nabbrev HtmlM := HtmlT Id\n\ndef HtmlT.run (x : HtmlT m \u03b1) (ctx : SiteContext) (baseCtx : SiteBaseContext) : m \u03b1 :=\n  ReaderT.run x ctx |>.run baseCtx\n\ndef HtmlM.run (x : HtmlM \u03b1) (ctx : SiteContext) (baseCtx : SiteBaseContext) : \u03b1 :=\n  ReaderT.run x ctx |>.run baseCtx |>.run\n\ninstance [Monad m] : MonadLift HtmlM (HtmlT m) where\n  monadLift x := do return x.run (\u2190 readThe SiteContext) (\u2190 readThe SiteBaseContext)\n\ninstance [Monad m] : MonadLift BaseHtmlM (BaseHtmlT m) where\n  monadLift x := do return x.run (\u2190 readThe SiteBaseContext)\n\n/--\nObtains the root URL as a relative one to the current depth.\n-/\ndef getRoot : BaseHtmlM String := do\n  let rec go: Nat -> String\n  | 0 => \"./\"\n  | Nat.succ n' => \"../\" ++ go n'\n  let d <- SiteBaseContext.depthToRoot <$> read\n  return (go d)\n\ndef getHierarchy : BaseHtmlM Hierarchy := do return (\u2190 read).hierarchy\ndef getCurrentName : BaseHtmlM (Option Name) := do return (\u2190 read).currentName\ndef getResult : HtmlM AnalyzerResult := do return (\u2190 read).result\ndef getSourceUrl (module : Name) (range : Option DeclarationRange): HtmlM String := do return (\u2190 read).sourceLinker module range\ndef leanInkEnabled? : HtmlM Bool := do return (\u2190 read).leanInkEnabled\ndef getProjectGithubUrl : BaseHtmlM String := do return (\u2190 read).projectGithubUrl\ndef getProjectCommit : BaseHtmlM String := do return (\u2190 read).projectCommit\n\n/--\nIf a template is meant to be extended because it for example only provides the\nheader but no real content this is the way to fill the template with content.\nThis is untyped so HtmlM and BaseHtmlM can be mixed.\n-/\ndef templateExtends {\u03b1 \u03b2} {m} [Bind m] (base : \u03b1 \u2192 m \u03b2) (new : m \u03b1) : m \u03b2 :=\n  new >>= base\n\ndef templateLiftExtends {\u03b1 \u03b2} {m n} [Bind m] [MonadLift n m] (base : \u03b1 \u2192 n \u03b2) (new : m \u03b1) : m \u03b2 :=\n  new >>= (monadLift \u2218 base)\n/--\nReturns the doc-gen4 link to a module name.\n-/\ndef moduleNameToLink (n : Name) : BaseHtmlM String := do\n  let parts := n.components.map Name.toString\n  return (\u2190 getRoot) ++ (parts.intersperse \"/\").foldl (\u00b7 ++ \u00b7) \"\" ++ \".html\"\n\n/--\nReturns the HTML doc-gen4 link to a module name.\n-/\ndef moduleToHtmlLink (module : Name) : BaseHtmlM Html := do\n  return <a href={\u2190 moduleNameToLink module}>{module.toString}</a>\n\n/--\nReturns the LeanInk link to a module name.\n-/\ndef moduleNameToInkLink (n : Name) : BaseHtmlM String := do\n  let parts := \"src\" :: n.components.map Name.toString\n  return (\u2190 getRoot) ++ (parts.intersperse \"/\").foldl (\u00b7 ++ \u00b7) \"\" ++ \".html\"\n\n/--\nReturns the path to the HTML file that contains information about a module.\n-/\ndef moduleNameToFile (basePath : FilePath) (n : Name) : FilePath :=\n  let parts := n.components.map Name.toString\n  FilePath.withExtension (basePath / parts.foldl (\u00b7 / \u00b7) (FilePath.mk \".\")) \"html\"\n\n/--\nReturns the directory of the HTML file that contains information about a module.\n-/\ndef moduleNameToDirectory (basePath : FilePath) (n : Name) : FilePath :=\n  let parts := n.components.dropLast.map Name.toString\n  basePath / parts.foldl (\u00b7 / \u00b7) (FilePath.mk \".\")\n\nsection Static\n/-!\nThe following section contains all the statically included files that\nare used in documentation generation, notably JS and CSS ones.\n-/\n  def styleCss : String := include_str \"../../static/style.css\"\n  def declarationDataCenterJs : String := include_str \"../../static/declaration-data.js\"\n  def navJs : String := include_str \"../../static/nav.js\"\n  def howAboutJs : String := include_str \"../../static/how-about.js\"\n  def searchJs : String := include_str \"../../static/search.js\"\n  def instancesJs : String := include_str \"../../static/instances.js\"\n  def importedByJs : String := include_str \"../../static/importedBy.js\"\n  def findJs : String := include_str \"../../static/find/find.js\"\n  def mathjaxConfigJs : String := include_str \"../../static/mathjax-config.js\"\n  \n  def alectryonCss : String := include_str \"../../static/alectryon/alectryon.css\"\n  def alectryonJs : String := include_str \"../../static/alectryon/alectryon.js\"\n  def docUtilsCss : String  := include_str \"../../static/alectryon/docutils_basic.css\"\n  def pygmentsCss : String  := include_str \"../../static/alectryon/pygments.css\"\nend Static\n\n/--\nReturns the doc-gen4 link to a declaration name.\n-/\ndef declNameToLink (name : Name) : HtmlM String := do\n  let res \u2190 getResult\n  let module := res.moduleNames[res.name2ModIdx.find! name |>.toNat]!\n  return (\u2190 moduleNameToLink module) ++ \"#\" ++ name.toString\n\n/--\nReturns the HTML doc-gen4 link to a declaration name.\n-/\ndef declNameToHtmlLink (name : Name) : HtmlM Html := do\n  return <a href={\u2190 declNameToLink name}>{name.toString}</a>\n\n/--\nReturns the LeanInk link to a declaration name.\n-/\ndef declNameToInkLink (name : Name) : HtmlM String := do\n  let res \u2190 getResult\n  let module := res.moduleNames[res.name2ModIdx.find! name |>.toNat]!\n  return (\u2190 moduleNameToInkLink module) ++ \"#\" ++ name.toString\n\n/--\nReturns a name splitted into parts.\nTogether with \"break_within\" CSS class this helps browser to break a name\nnicely.\n-/\ndef breakWithin (name: String) : (Array Html) :=\n  name.splitOn \".\"\n    |> .map (fun (s: String) => <span class=\"name\">{s}</span>)\n    |> .intersperse \".\"\n    |> List.toArray\n\n/--\nReturns the HTML doc-gen4 link to a declaration name with \"break_within\"\nset as class.\n-/\ndef declNameToHtmlBreakWithinLink (name : Name) : HtmlM Html := do\n  return <a class=\"break_within\" href={\u2190 declNameToLink name}>\n      [breakWithin name.toString]\n    </a>\n\n/--\nIn Lean syntax declarations the following pattern is quite common:\n```\nsyntax term \" + \" term : term\n```\nthat is, we place spaces around the operator in the middle. When the\n`InfoTree` framework provides us with information about what source token\ncorresponds to which identifier it will thus say that `\" + \"` corresponds to\n`HAdd.hadd`. This is however not the way we want this to be linked, in the HTML\nonly `+` should be linked, taking care of this is what this function is\nresponsible for.\n-/\ndef splitWhitespaces (s : String) : (String \u00d7 String \u00d7 String) := Id.run do\n  let front := \"\".pushn ' ' <| s.offsetOfPos (s.find (!Char.isWhitespace \u00b7))\n  let mut s := s.trimLeft\n  let back := \"\".pushn ' ' (s.length - s.offsetOfPos (s.find Char.isWhitespace))\n  s := s.trimRight\n  (front, s, back)\n\n/--\nTurns a `CodeWithInfos` object, that is basically a Lean syntax tree with\ninformation about what the identifiers mean, into an HTML object that links\nto as much information as possible.\n-/\npartial def infoFormatToHtml (i : CodeWithInfos) : HtmlM (Array Html) := do\n  match i with\n  | .text t => return #[Html.escape t]\n  | .append tt => tt.foldlM (fun acc t => do return acc ++ (\u2190 infoFormatToHtml t)) #[]\n  | .tag a t =>\n    match a.info.val.info with\n    | Info.ofTermInfo i =>\n      let cleanExpr :=  i.expr.consumeMData\n      match cleanExpr with\n      | .const name _ =>\n        -- TODO: this is some very primitive blacklisting but real Blacklisting needs MetaM\n        -- find a better solution\n        if (\u2190 getResult).name2ModIdx.contains name then\n          match t with\n          | .text t =>\n            let (front, t, back) := splitWhitespaces <| Html.escape t\n            let elem := <a href={\u2190 declNameToLink name}>{t}</a>\n            return #[Html.text front, elem, Html.text back]\n          | _ =>\n            return #[<a href={\u2190 declNameToLink name}>[\u2190 infoFormatToHtml t]</a>]\n        else\n         return #[<span class=\"fn\">[\u2190 infoFormatToHtml t]</span>]\n      | .sort _ =>\n        match t with\n        | .text t =>\n          let mut sortPrefix :: rest := t.splitOn \" \" | unreachable!\n          let sortLink := <a href={s!\"{\u2190 getRoot}foundational_types.html\"}>{sortPrefix}</a>\n          if rest != [] then\n            rest := \" \" :: rest\n          return #[sortLink, Html.text <| String.join rest]\n        | _ =>\n          return #[<a href={s!\"{\u2190 getRoot}foundational_types.html\"}>[\u2190 infoFormatToHtml t]</a>]\n      | _ =>\n         return #[<span class=\"fn\">[\u2190 infoFormatToHtml t]</span>]\n    | _ => return #[<span class=\"fn\">[\u2190 infoFormatToHtml t]</span>]\n\ndef baseHtmlHeadDeclarations : BaseHtmlM (Array Html) := do\n  return #[\n    <meta charset=\"UTF-8\"/>,\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>,\n    <link rel=\"stylesheet\" href={s!\"{\u2190 getRoot}style.css\"}/>,\n    <link rel=\"stylesheet\" href={s!\"{\u2190 getRoot}src/pygments.css\"}/>,\n    <link rel=\"shortcut icon\" href={s!\"{\u2190 getRoot}favicon.ico\"}/>,\n    <link rel=\"prefetch\" href={s!\"{\u2190 getRoot}/declarations/declaration-data.bmp\"} as=\"image\"/>\n  ]\n\nend DocGen4.Output\n", "meta": {"author": "leanprover", "repo": "doc-gen4", "sha": "b9421b9a12b148d9279a881cce227affdb09ed08", "save_path": "github-repos/lean/leanprover-doc-gen4", "path": "github-repos/lean/leanprover-doc-gen4/doc-gen4-b9421b9a12b148d9279a881cce227affdb09ed08/DocGen4/Output/Base.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921033280367934, "lm_q2_score": 0.039048295521946844, "lm_q1q2_score": 0.003093028483709831}}
{"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.Elab.Term\nimport Lean.Elab.Binders\nimport Lean.Elab.Match\nimport Lean.Elab.Quotation.Util\nimport Lean.Parser.Do\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Meta\n\nprivate def getDoSeqElems (doSeq : Syntax) : List Syntax :=\n  if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then\n    doSeq[1].getArgs.toList.map fun arg => arg[0]\n  else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then\n    doSeq[0].getArgs.toList.map fun arg => arg[0]\n  else\n    []\n\nprivate def getDoSeq (doStx : Syntax) : Syntax :=\n  doStx[1]\n\n@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>\n  throwErrorAt stx \"invalid use of `(<- ...)`, must be nested inside a 'do' expression\"\n\n/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/\nprivate def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=\n  k == ``Lean.Parser.Term.do ||\n  k == ``Lean.Parser.Term.doSeqIndent ||\n  k == ``Lean.Parser.Term.doSeqBracketed ||\n  k == ``Lean.Parser.Term.termReturn ||\n  k == ``Lean.Parser.Term.termUnless ||\n  k == ``Lean.Parser.Term.termTry ||\n  k == ``Lean.Parser.Term.termFor\n\n/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/\nprivate def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=\n  let k := letDeclArg.getKind\n  if k == ``Lean.Parser.Term.letPatDecl then\n    false\n  else if k == ``Lean.Parser.Term.letEqnsDecl then\n    true\n  else if k == ``Lean.Parser.Term.letIdDecl then\n    -- letIdLhs := ident >> checkWsBefore \"expected space before binders\" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType\n    let binders := letDeclArg[1]\n    binders.getNumArgs > 0\n  else\n    false\n\n/-- Return `true` if the given `letDecl` contains binders. -/\nprivate def letDeclHasBinders (letDecl : Syntax) : Bool :=\n  letDeclArgHasBinders letDecl[0]\n\n/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/\nprivate def liftMethodForbiddenBinder (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||\n     k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec  then\n     -- It is never ok to lift over this kind of binder\n    true\n  -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not\n  else if k == ``Lean.Parser.Term.let then\n    letDeclHasBinders stx[1]\n  else if k == ``Lean.Parser.Term.doLet then\n    letDeclHasBinders stx[2]\n  else if k == ``Lean.Parser.Term.doLetArrow then\n    letDeclArgHasBinders stx[2]\n  else\n    false\n\nprivate partial def hasLiftMethod : Syntax \u2192 Bool\n  | Syntax.node k args =>\n    if liftMethodDelimiter k then false\n    -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a\n    -- bit slower\n    else if k == `Lean.Parser.Term.liftMethod then true\n    else args.any hasLiftMethod\n  | _ => false\n\nstructure ExtractMonadResult where\n  m            : Expr\n  \u03b1            : Expr\n  hasBindInst  : Expr\n  expectedType : Expr\n\nprivate def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do\n  let u \u2190 getDecLevel type\n  let id        := Lean.mkConst `Id [u]\n  let idBindVal := Lean.mkConst `Id.hasBind [u]\n  pure { m := id, hasBindInst := idBindVal, \u03b1 := type, expectedType := mkApp id type }\n\nprivate partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do\n  match expectedType? with\n  | none => throwError \"invalid 'do' notation, expected type is not available\"\n  | some expectedType =>\n    let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match type with\n      | Expr.app m \u03b1 _ =>\n        try\n          let bindInstType \u2190 mkAppM `Bind #[m]\n          let bindInstVal  \u2190 Meta.synthInstance bindInstType\n          return some { m := m, hasBindInst := bindInstVal, \u03b1 := \u03b1, expectedType := expectedType }\n        catch _ =>\n          return none\n      | _ =>\n        return none\n    let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match (\u2190 extractStep? type) with\n      | some r => return r\n      | none =>\n        let typeNew \u2190 whnfCore type\n        if typeNew != type then\n          extract? typeNew\n        else\n          if typeNew.getAppFn.isMVar then throwError \"invalid 'do' notation, expected type is not available\"\n          match (\u2190 unfoldDefinition? typeNew) with\n          | some typeNew => extract? typeNew\n          | none => return none\n    match (\u2190 extract? expectedType) with\n    | some r => return r\n    | none   => mkIdBindFor expectedType\n\nnamespace Do\n\n/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/\nstructure Alt (\u03c3 : Type) where\n  ref : Syntax\n  vars : Array Name\n  patterns : Syntax\n  rhs : \u03c3\n  deriving Inhabited\n\n/-\n  Auxiliary datastructure for representing a `do` code block, and compiling \"reassignments\" (e.g., `x := x + 1`).\n  We convert `Code` into a `Syntax` term representing the:\n  - `do`-block, or\n  - the visitor argument for the `forIn` combinator.\n\n  We say the following constructors are terminals:\n  - `break`:    for interrupting a `for x in s`\n  - `continue`: for interrupting the current iteration of a `for x in s`\n  - `return e`: for returning `e` as the result for the whole `do` computation block\n  - `action a`: for executing action `a` as a terminal\n  - `ite`:      if-then-else\n  - `match`:    pattern matching\n  - `jmp`       a goto to a join-point\n\n  We say the terminals `break`, `continue`, `action`, and `return` are \"exit points\"\n\n  Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x == 0 then\n     return ()\n  IO.println \"hello\"\n  ```\n  Executing `#eval f 0` will not print \"hello\". Now, consider\n  ```\n  def g (x : Nat) : IO Unit := do\n  if x == 0 then\n     pure ()\n  IO.println \"hello\"\n  ```\n  The `if` statement is essentially a noop, and \"hello\" is printed when we execute `g 0`.\n\n  - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).\n    The field `stx` is the actual `doElem`,\n    `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.\n    `vars` is an array since we have declarations such as `let (a, b) := s`.\n\n  - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).\n\n  - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.\n\n  - `seq a k` executes action `a`, ignores its result, and then executes `k`.\n    We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.\n\n  A code block `C` is well-formed if\n  - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and\n    `ps.size == as.size` -/\ninductive Code where\n  | decl         (xs : Array Name) (doElem : Syntax) (k : Code)\n  | reassign     (xs : Array Name) (doElem : Syntax) (k : Code)\n  /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/\n  | joinpoint    (name : Name) (params : Array (Name \u00d7 Bool)) (body : Code) (k : Code)\n  | seq          (action : Syntax) (k : Code)\n  | action       (action : Syntax)\n  | \u00abbreak\u00bb      (ref : Syntax)\n  | \u00abcontinue\u00bb   (ref : Syntax)\n  | \u00abreturn\u00bb     (ref : Syntax) (val : Syntax)\n  /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/\n  | ite          (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)\n  | \u00abmatch\u00bb      (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))\n  | jmp          (ref : Syntax) (jpName : Name) (args : Array Syntax)\n  deriving Inhabited\n\n/- A code block, and the collection of variables updated by it. -/\nstructure CodeBlock where\n  code  : Code\n  uvars : NameSet := {} -- set of variables updated by `code`\n\nprivate def nameSetToArray (s : NameSet) : Array Name :=\n  s.fold (fun (xs : Array Name) x => xs.push x) #[]\n\nprivate def varsToMessageData (vars : Array Name) : MessageData :=\n  MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) \" \"\n\npartial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=\n  let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName\n  let rec loop : Code \u2192 MessageData\n    | Code.decl xs _ k            => m!\"let {varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.reassign xs _ k        => m!\"{varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.joinpoint n ps body k  => m!\"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\\n{loop k}\"\n    | Code.seq e k                => m!\"{e}\\n{loop k}\"\n    | Code.action e               => e\n    | Code.ite _ _ _ c t e        => m!\"if {c} then {indentD (loop t)}\\nelse{loop e}\"\n    | Code.jmp _ j xs             => m!\"jmp {j.simpMacroScopes} {xs.toList}\"\n    | Code.\u00abbreak\u00bb _              => m!\"break {us}\"\n    | Code.\u00abcontinue\u00bb _           => m!\"continue {us}\"\n    | Code.\u00abreturn\u00bb _ v           => m!\"return {v} {us}\"\n    | Code.\u00abmatch\u00bb _ _ ds t alts  =>\n      m!\"match {ds} with\"\n      ++ alts.foldl (init := m!\"\") fun acc alt => acc ++ m!\"\\n| {alt.patterns} => {loop alt.rhs}\"\n  loop codeBlock.code\n\n/- Return true if the give code contains an exit point that satisfies `p` -/\n@[inline] partial def hasExitPointPred (c : Code) (p : Code \u2192 Bool) : Bool :=\n  let rec @[specialize] loop : Code \u2192 Bool\n    | Code.decl _ _ k           => loop k\n    | Code.reassign _ _ k       => loop k\n    | Code.joinpoint _ _ b k    => loop b || loop k\n    | Code.seq _ k              => loop k\n    | Code.ite _ _ _ _ t e      => loop t || loop e\n    | Code.\u00abmatch\u00bb _ _ _ _ alts => alts.any (loop \u00b7.rhs)\n    | Code.jmp _ _ _            => false\n    | c                         => p c\n  loop c\n\ndef hasExitPoint (c : Code) : Bool :=\n  hasExitPointPred c fun c => true\n\ndef hasReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef hasTerminalAction (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abaction\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinue (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinueReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax \u2192 m Code) : m Code := withRef e <| withFreshMacroScope do\n  let y \u2190 `(y)\n  let yName := y.getId\n  let doElem \u2190 `(doElem| let y \u2190 $e:term)\n  -- Add elaboration hint for producing sane error message\n  let y \u2190 `(ensureExpectedType% \"type mismatch, result value\" $y)\n  let k \u2190 mkCont y\n  pure $ Code.decl #[yName] doElem k\n\n/- Convert `action _ e` instructions in `c` into `let y \u2190 e; jmp _ jp (xs y)`. -/\npartial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=\n  let rec loop : Code \u2192 MacroM Code\n    | Code.decl xs stx k           => do Code.decl xs stx (\u2190 loop k)\n    | Code.reassign xs stx k       => do Code.reassign xs stx (\u2190 loop k)\n    | Code.joinpoint n ps b k      => do Code.joinpoint n ps (\u2190 loop b) (\u2190 loop k)\n    | Code.seq e k                 => do Code.seq e (\u2190 loop k)\n    | Code.ite ref x? h c t e      => do Code.ite ref x? h c (\u2190 loop t) (\u2190 loop e)\n    | Code.\u00abmatch\u00bb ref g ds t alts => do Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 loop alt.rhs) })\n    | Code.action e                => mkAuxDeclFor e fun y =>\n      let ref := e\n      -- We jump to `jp` with xs **and** y\n      let jmpArgs := xs.map $ mkIdentFrom ref\n      let jmpArgs := jmpArgs.push y\n      pure $ Code.jmp ref jp jmpArgs\n    | c                            => pure c\n  loop code\n\nstructure JPDecl where\n  name : Name\n  params : Array (Name \u00d7 Bool)\n  body : Code\n\ndef attachJP (jpDecl : JPDecl) (k : Code) : Code :=\n  Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k\n\ndef attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=\n  jpDecls.foldr attachJP k\n\ndef mkFreshJP (ps : Array (Name \u00d7 Bool)) (body : Code) : TermElabM JPDecl := do\n  let ps \u2190\n    if ps.isEmpty then\n      let y \u2190 mkFreshUserName `y\n      pure #[(y, false)]\n    else\n      pure ps\n  -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by\n  -- the \"do\" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`\n  -- We will remove this hack when we re-implement the compiler frontend in Lean.\n  let name \u2190 mkFreshUserName `_do_jp\n  pure { name := name, params := ps, body := body }\n\ndef mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=\n  mkFreshJP (xs.map fun x => (x, true)) body\n\ndef addFreshJP (ps : Array (Name \u00d7 Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do\n  let jp \u2190 mkFreshJP ps body\n  modify fun (jps : Array JPDecl) => jps.push jp\n  pure jp.name\n\ndef insertVars (rs : NameSet) (xs : Array Name) : NameSet :=\n  xs.foldl (\u00b7.insert \u00b7) rs\n\ndef eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=\n  xs.foldl (\u00b7.erase \u00b7) rs\n\ndef eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=\n  match x? with\n  | none   => rs\n  | some x => rs.insert x\n\n/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/\ndef mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := nameSetToArray rs\n  let jp \u2190 addFreshJP (xs.map fun x => (x, true)) c\n  if xs.isEmpty then\n    let unit \u2190 ``(Unit.unit)\n    return Code.jmp ref jp #[unit]\n  else\n    return Code.jmp ref jp (xs.map $ mkIdentFrom ref)\n\n/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.\n   The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`\n   is a fresh variable created by this method. -/\ndef mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax \u2192 MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := nameSetToArray rs\n  let args := xs.map $ mkIdentFrom ref\n  let args := args.push val\n  let yFresh \u2190 mkFreshUserName `y\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (yFresh, false)\n  let jpBody \u2190 liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)\n  let jp \u2190 addFreshJP ps jpBody\n  pure $ Code.jmp ref jp args\n\n/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path.  -/\npartial def pullExitPointsAux : NameSet \u2192 Code \u2192 StateRefT (Array JPDecl) TermElabM Code\n  | rs, Code.decl xs stx k           => do Code.decl xs stx (\u2190 pullExitPointsAux (eraseVars rs xs) k)\n  | rs, Code.reassign xs stx k       => do Code.reassign xs stx (\u2190 pullExitPointsAux (insertVars rs xs) k)\n  | rs, Code.joinpoint j ps b k      => do Code.joinpoint j ps (\u2190 pullExitPointsAux rs b) (\u2190 pullExitPointsAux rs k)\n  | rs, Code.seq e k                 => do Code.seq e (\u2190 pullExitPointsAux rs k)\n  | rs, Code.ite ref x? o c t e      => do Code.ite ref x? o c (\u2190 pullExitPointsAux (eraseOptVar rs x?) t) (\u2190 pullExitPointsAux (eraseOptVar rs x?) e)\n  | rs, Code.\u00abmatch\u00bb ref g ds t alts => do\n    Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })\n  | rs, c@(Code.jmp _ _ _)           => pure c\n  | rs, Code.\u00abbreak\u00bb ref             => mkSimpleJmp ref rs (Code.\u00abbreak\u00bb ref)\n  | rs, Code.\u00abcontinue\u00bb ref          => mkSimpleJmp ref rs (Code.\u00abcontinue\u00bb ref)\n  | rs, Code.\u00abreturn\u00bb ref val        => mkJmp ref rs val (fun y => pure $ Code.\u00abreturn\u00bb ref y)\n  | rs, Code.action e                =>\n    -- We use `mkAuxDeclFor` because `e` is not pure.\n    mkAuxDeclFor e fun y =>\n      let ref := e\n      mkJmp ref rs y (fun yFresh => do pure $ Code.action (\u2190 ``(Pure.pure $yFresh)))\n\n/-\nAuxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.\nWhen a new variable is not already in the collection, but is shadowed by some declaration in `c`,\nwe create auxiliary join points to make sure we preserve the semantics of the code block.\nExample: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it\nwith the reassignment `x := x + 1`. We first use `pullExitPoints` to create\n```\nlet jp (x!1) :=  return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nand then we add the reassignment\n```\nx := x + 1\nlet jp (x!1) := return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nNote that we created a fresh variable `x!1` to avoid accidental name capture.\nAs another example, consider\n```\nprint x;\nlet x := 10\ny := y + 1;\nreturn x;\n```\nWe transform it into\n```\nlet jp (y x!1) := return x!1;\nprint x;\nlet x := 10\ny := y + 1;\njmp jp y x\n```\nand then we add the reassignment as in the previous example.\nWe need to include `y` in the jump, because each exit point is implicitly returning the set of\nupdate variables.\n\nWe implement the method as follows. Let `us` be `c.uvars`, then\n1- for each `return _ y` in `c`, we create a join point\n  `let j (us y!1) := return y!1`\n   and replace the `return _ y` with `jmp us y`\n2- for each `break`, we create a join point\n  `let j (us) := break`\n   and replace the `break` with `jmp us`.\n3- Same as 2 for `continue`.\n-/\ndef pullExitPoints (c : Code) : TermElabM Code := do\n  if hasExitPoint c then\n    let (c, jpDecls) \u2190 (pullExitPointsAux {} c).run #[]\n    pure $ attachJPs jpDecls c\n  else\n    pure c\n\npartial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=\n  let rec update : Code \u2192 TermElabM Code\n    | Code.joinpoint j ps b k          => do Code.joinpoint j ps (\u2190 update b) (\u2190 update k)\n    | Code.seq e k                     => do Code.seq e (\u2190 update k)\n    | c@(Code.\u00abmatch\u00bb ref g ds t alts) => do\n      if alts.any fun alt => alt.vars.any fun x => ws.contains x then\n        -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`\n        pullExitPoints c\n      else\n        Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 update alt.rhs) })\n    | Code.ite ref none o c t e => do Code.ite ref none o c (\u2190 update t) (\u2190 update e)\n    | c@(Code.ite ref (some h) o cond t e) => do\n      if ws.contains h then\n        -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`\n        pullExitPoints c\n      else\n        Code.ite ref (some h) o cond (\u2190 update t) (\u2190 update e)\n    | Code.reassign xs stx k => do Code.reassign xs stx (\u2190 update k)\n    | c@(Code.decl xs stx k) => do\n      if xs.any fun x => ws.contains x then\n        -- One the declared variables is shadowing a variable in `ws`\n        pullExitPoints c\n      else\n        Code.decl xs stx (\u2190 update k)\n    | c => pure c\n  update c\n\n/-\nExtend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.\nWe **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.\nSee discussion at `pullExitPoints`.\n-/\npartial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do\n  if ws.any fun x => !c.uvars.contains x then\n    -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)\n    pure { code := (\u2190 extendUpdatedVarsAux c.code ws), uvars := ws }\n  else\n    pure { c with uvars := ws }\n\nprivate def union (s\u2081 s\u2082 : NameSet) : NameSet :=\n  s\u2081.fold (\u00b7.insert \u00b7) s\u2082\n\n/-\nGiven two code blocks `c\u2081` and `c\u2082`, make sure they have the same set of updated variables.\nLet `ws` the union of the updated variables in `c\u2081\u2035 and \u2035c\u2082`.\nWe use `extendUpdatedVars c\u2081 ws` and `extendUpdatedVars c\u2082 ws`\n-/\ndef homogenize (c\u2081 c\u2082 : CodeBlock) : TermElabM (CodeBlock \u00d7 CodeBlock) := do\n  let ws := union c\u2081.uvars c\u2082.uvars\n  let c\u2081 \u2190 extendUpdatedVars c\u2081 ws\n  let c\u2082 \u2190 extendUpdatedVars c\u2082 ws\n  pure (c\u2081, c\u2082)\n\n/-\nExtending code blocks with variable declarations: `let x : t := v` and `let x : t \u2190 v`.\nWe remove `x` from the collection of updated varibles.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `let (x, y) := t`\n-/\ndef mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {\n  code := Code.decl xs stx c.code,\n  uvars := eraseVars c.uvars xs\n}\n\n/-\nExtending code blocks with reassignments: `x : t := v` and `x : t \u2190 v`.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `(x, y) \u2190 t`\n-/\ndef mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do\n  let us := c.uvars\n  let ws := insertVars us xs\n  -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.\n  -- See discussion at `pullExitPoints`\n  let code \u2190 if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code\n  pure { code := Code.reassign xs stx code, uvars := ws }\n\ndef mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=\n  { c with code := Code.seq action c.code }\n\ndef mkTerminalAction (action : Syntax) : CodeBlock :=\n  { code := Code.action action }\n\ndef mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=\n  { code := Code.\u00abreturn\u00bb ref val }\n\ndef mkBreak (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abbreak\u00bb ref }\n\ndef mkContinue (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abcontinue\u00bb ref }\n\ndef mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do\n  let x? := if optIdent.isNone then none else some optIdent[0].getId\n  let (thenBranch, elseBranch) \u2190 homogenize thenBranch elseBranch\n  pure {\n    code  := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,\n    uvars := thenBranch.uvars,\n  }\n\nprivate def mkUnit : MacroM Syntax :=\n  ``((\u27e8\u27e9 : PUnit))\n\nprivate def mkPureUnit : MacroM Syntax :=\n  ``(pure PUnit.unit)\n\ndef mkPureUnitAction : MacroM CodeBlock := do\n  mkTerminalAction (\u2190 mkPureUnit)\n\ndef mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do\n  let thenBranch \u2190 mkPureUnitAction\n  pure { c with code := Code.ite (\u2190 getRef) none mkNullNode cond thenBranch.code c.code }\n\ndef mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do\n  -- nary version of homogenize\n  let ws := alts.foldl (union \u00b7 \u00b7.rhs.uvars) {}\n  let alts \u2190 alts.mapM fun alt => do\n    let rhs \u2190 extendUpdatedVars alt.rhs ws\n    pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }\n  pure { code := Code.\u00abmatch\u00bb ref genParam discrs optType alts, uvars := ws }\n\n/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.\n   This method assumes `terminal` is a terminal -/\ndef concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do\n  unless hasTerminalAction terminal.code do\n    throwErrorAt kRef \"'do' element is unreachable\"\n  let (terminal, k) \u2190 homogenize terminal k\n  let xs := nameSetToArray k.uvars\n  let y \u2190 match y? with | some y => pure y | none => mkFreshUserName `y\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (y, false)\n  let jpDecl \u2190 mkFreshJP ps k.code\n  let jp := jpDecl.name\n  let terminal \u2190 liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs\n  pure { code  := attachJP jpDecl terminal, uvars := k.uvars }\n\ndef getLetIdDeclVar (letIdDecl : Syntax) : Name :=\n  letIdDecl[0].getId\n\n-- support both regular and syntax match\ndef getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=\n  getPatternVarNames <$> getPatternVars pattern <|>\n  Array.map Syntax.getId <$> Quotation.getPatternVars pattern\n\ndef getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=\n  getPatternVarNames <$> getPatternsVars patterns <|>\n  Array.map Syntax.getId <$> Quotation.getPatternsVars patterns\n\ndef getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do\n  let pattern := letPatDecl[0]\n  getPatternVarsEx pattern\n\ndef getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=\n  letEqnsDecl[0].getId\n\ndef getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do\n  let arg := letDecl[0]\n  if arg.getKind == `Lean.Parser.Term.letIdDecl then\n    pure #[getLetIdDeclVar arg]\n  else if arg.getKind == `Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then\n    pure #[getLetEqnsDeclVar arg]\n  else\n    throwError \"unexpected kind of let declaration\"\n\ndef getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=\n  -- leading_parser \"let \" >> optional \"mut \" >> letDecl\n  getLetDeclVars doLet[2]\n\ndef getDoHaveVar (doHave : Syntax) : Name :=\n  /-\n    `leading_parser \"have \" >> Term.haveDecl`\n    where\n    ```\n    haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)\n    optIdent := optional (try (ident >> \" : \"))\n\n    ```\n  -/\n  let optIdent := doHave[1][0]\n  if optIdent.isNone then\n    `this\n  else\n    optIdent[0].getId\n\ndef getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do\n  -- letRecDecls is an array of `(group (optional attributes >> letDecl))`\n  let letRecDecls := doLetRec[1][0].getSepArgs\n  let letDecls := letRecDecls.map fun p => p[2]\n  let mut allVars := #[]\n  for letDecl in letDecls do\n    let vars \u2190 getLetDeclVars letDecl\n    allVars := allVars ++ vars\n  pure allVars\n\n-- ident >> optType >> leftArrow >> termParser\ndef getDoIdDeclVar (doIdDecl : Syntax) : Name :=\n  doIdDecl[0].getId\n\n-- termParser >> leftArrow >> termParser >> optional (\" | \" >> termParser)\ndef getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do\n  let pattern := doPatDecl[0]\n  getPatternVarsEx pattern\n\n-- leading_parser \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\ndef getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do\n  let decl := doLetArrow[2]\n  if decl.getKind == `Lean.Parser.Term.doIdDecl then\n    pure #[getDoIdDeclVar decl]\n  else if decl.getKind == `Lean.Parser.Term.doPatDecl then\n    getDoPatDeclVars decl\n  else\n    throwError \"unexpected kind of 'do' declaration\"\n\ndef getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do\n  let arg := doReassign[0]\n  if arg.getKind == `Lean.Parser.Term.letIdDecl then\n    pure #[getLetIdDeclVar arg]\n  else if arg.getKind == `Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else\n    throwError \"unexpected kind of reassignment\"\n\ndef mkDoSeq (doElems : Array Syntax) : Syntax :=\n  mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]\n\ndef mkSingletonDoSeq (doElem : Syntax) : Syntax :=\n  mkDoSeq #[doElem]\n\n/-\n  If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s.  -/\nprivate def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with\n  | `(doElem|if $p:doIfProp then $t else $e) => pure none\n  | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do\n    let mut e      := e?.getD (\u2190 `(doSeq|pure PUnit.unit))\n    let mut eIsSeq := true\n    for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do\n      e \u2190 if eIsSeq then e else `(doSeq|$e:doElem)\n      e \u2190 withRef cond <| match cond with\n        | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)\n        | `(doIfCond|let $pat \u2190 $d)  => `(doElem| match%$i \u2190 $d    with | $pat:term => $t | _ => $e)\n        | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)\n        | _                          => `(doElem| if%$i $(Syntax.missing) then $t else $e)\n      eIsSeq := false\n    return some e\n  | _ => pure none\n\nstructure DoIfView where\n  ref        : Syntax\n  optIdent   : Syntax\n  cond       : Syntax\n  thenBranch : Syntax\n  elseBranch : Syntax\n\n/- This method assumes `expandDoIf?` is not applicable. -/\nprivate def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do\n  pure {\n    ref        := doIf,\n    optIdent   := doIf[1][0],\n    cond       := doIf[1][1],\n    thenBranch := doIf[3],\n    elseBranch := doIf[5][1]\n  }\n\n/-\nWe use `MProd` instead of `Prod` to group values when expanding the\n`do` notation. `MProd` is a universe monomorphic product.\nThe motivation is to generate simpler universe constraints in code\nthat was not written by the user.\nNote that we are not restricting the macro power since the\n`Bind.bind` combinator already forces values computed by monadic\nactions to be in the same universe.\n-/\nprivate def mkTuple (elems : Array Syntax) : MacroM Syntax := do\n  if elems.size == 0 then\n    mkUnit\n  else if elems.size == 1 then\n    pure elems[0]\n  else\n    (elems.extract 0 (elems.size - 1)).foldrM\n      (fun elem tuple => ``(MProd.mk $elem $tuple))\n      (elems.back)\n\n/- Return `some action` if `doElem` is a `doExpr <action>`-/\ndef isDoExpr? (doElem : Syntax) : Option Syntax :=\n  if doElem.getKind == `Lean.Parser.Term.doExpr then\n    some doElem[0]\n  else\n    none\n\n/--\n  Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term\n  ```\n  let a_1     := x.1\n  let x       := x.2\n  let a_2     := x.1\n  let x       := x.2\n  ...\n  let a_n     := x.1\n  let a_{n+1} := x.2\n  body\n  ```\n  Special cases\n  - `uvars := #[]` => `body`\n  - `uvars := #[a]` => `let a := x; body`\n\n\n  We use this method when expanding the `for-in` notation.\n-/\nprivate def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n  if uvars.size == 0 then\n    return body\n  else if uvars.size == 1 then\n    `(let $(\u2190 mkIdentFromRef uvars[0]):ident := $x; $body)\n  else\n    destruct uvars.toList x body\nwhere\n  destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n    match as with\n      | [a, b]  => `(let $(\u2190 mkIdentFromRef a):ident := $x.1; let $(\u2190 mkIdentFromRef b):ident := $x.2; $body)\n      | a :: as => withFreshMacroScope do\n        let rest \u2190 destruct as (\u2190 `(x)) body\n        `(let $(\u2190 mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)\n      | _ => unreachable!\n\n/-\nThe procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.\nWe use this method to convert\n1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of\n   `CodeBlock` never contains `break` nor `continue`. Moreover, the collection\n   of updated variables is not packed into the result.\n   Thus, we have two kinds of exit points\n     - `Code.action e` which is converted into `e`\n     - `Code.return _ e` which is converted into `pure e`\n\n   We use `Kind.regular` for this case.\n\n2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate\n   a `Syntax` term representing a function for the `xs.forIn` combinator.\n\n   a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term\n      has type `m (ForInStep (Option \u03b1 \u00d7 \u03c3))`, where `a : \u03b1`, and the `\u03c3` is the type\n      of the tuple of variables reassigned by `b`.\n      We use `Kind.forInWithReturn` for this case\n\n   b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated\n      `Syntax` term has type `m (ForInStep \u03c3)`.\n      We use `Kind.forIn` for this case.\n\n3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).\n\n   The generated `Syntax` term for `c` must inform whether `c` \"exited\" using `Code.action`, `Code.return`,\n   `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.\n   For example, the auxiliary type `DoResultPBC \u03b1 \u03c3` is used for a code block that exits with `Code.action`,\n   **and** `Code.break`/`Code.continue`, `\u03b1` is the type of values produced by the exit `action`, and\n   `\u03c3` is the type of the tuple of reassigned variables.\n   The type `DoResult \u03b1 \u03b2 \u03c3` is usedf for code blocks that exit with\n   `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `\u03b2` is the type of the returned values.\n   We don't use `DoResult \u03b1 \u03b2 \u03c3` for all cases because:\n\n      a) The elaborator would not be able to infer all type parameters without extra annotations. For example,\n         if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `\u03b2`.\n\n      b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),\n         but we don't want to consider \"unreachable\" cases.\n\n   We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.\n\n   When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,\n   and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.\n\n   - `a`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n\n   - `r`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n           Note that the code that pattern matches on the result will behave differently in this case.\n           It produces `return a` for this case, and `pure a` for the previous one.\n\n   - `b/c`: `Kind.nestedBC`, type `m (DoResultBC \u03c3)`\n\n   - `a` and `r`:   `Kind.nestedPR`, type `m (DoResultPR \u03b1 \u03b2 \u03c3)`\n\n   - `a` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n\n   - `r` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n         Again the code that pattern matches on the result will behave differently in this case and\n         the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for\n         this case, and `pure a` for the previous case.\n\n   - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC \u03b1 \u03b2 \u03c3)`\n\nHere is the recipe for adding new combinators with nested `do`s.\nExample: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m \u03b1 \u2192 m \u03b1`\n1- Convert `doSeq` into `codeBlock : CodeBlock`\n2- Create term `term` using `mkNestedTerm code m uvars a r bc` where\n   `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,\n   `m` is a `Syntax` representing the Monad, and\n   `a` is true if `code` contains `Code.action _`,\n   `r` is true if `code` contains `Code.return _ _`,\n   `bc` is true if `code` contains `Code.break _` or `Code.continue _`.\n\n   Remark: for combinators such as `repeat` that take a single `doSeq`, all\n   arguments, but `m`, are extracted from `codeBlock`.\n3- Create the term `repeat $term`\n4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`\n\n-/\nnamespace ToTerm\n\ninductive Kind where\n  | regular\n  | forIn\n  | forInWithReturn\n  | nestedBC\n  | nestedPR\n  | nestedSBC\n  | nestedPRBC\n\ninstance : Inhabited Kind := \u27e8Kind.regular\u27e9\n\ndef Kind.isRegular : Kind \u2192 Bool\n  | Kind.regular => true\n  | _            => false\n\nstructure Context where\n  m     : Syntax -- Syntax to reference the monad associated with the do notation.\n  uvars : Array Name\n  kind  : Kind\n\nabbrev M := ReaderT Context MacroM\n\ndef mkUVarTuple : M Syntax := do\n  let ctx \u2190 read\n  let uvarIdents \u2190 ctx.uvars.mapM mkIdentFromRef\n  mkTuple uvarIdents\n\ndef returnToTerm (val : Syntax) : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Pure.pure (DoResultPR.\u00abreturn\u00bb $val $u))\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abpureReturn\u00bb $val $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abreturn\u00bb $val $u))\n\ndef continueToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abcontinue\u00bb $u))\n\ndef breakToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abbreak\u00bb $u))\n\ndef actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))\n  | Kind.forIn           => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.\u00abpure\u00bb y $u)))\n  | Kind.nestedSBC       => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.\u00abpureReturn\u00bb y $u)))\n  | Kind.nestedPRBC      => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.\u00abpure\u00bb y $u)))\n\ndef seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  if action.getKind == `Lean.Parser.Term.doDbgTrace then\n    let msg := action[1]\n    `(dbg_trace $msg; $k)\n  else if action.getKind == `Lean.Parser.Term.doAssert then\n    let cond := action[1]\n    `(assert! $cond; $k)\n  else\n    let action \u2190 withRef action ``(($action : $((\u2190read).m) PUnit))\n    ``(Bind.bind $action (fun (_ : PUnit) => $k))\n\ndef declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do\n  let kind := decl.getKind\n  if kind == `Lean.Parser.Term.doLet then\n    let letDecl := decl[2]\n    `(let $letDecl:letDecl; $k)\n  else if kind == `Lean.Parser.Term.doLetRec then\n    let letRecToken := decl[0]\n    let letRecDecls := decl[1]\n    pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]\n  else if kind == `Lean.Parser.Term.doLetArrow then\n    let arg := decl[2]\n    let ref := arg\n    if arg.getKind == `Lean.Parser.Term.doIdDecl then\n      let id     := arg[0]\n      let type   := expandOptType ref arg[1]\n      let doElem := arg[3]\n      -- `doElem` must be a `doExpr action`. See `doLetArrowToCode`\n      match isDoExpr? doElem with\n      | some action =>\n        let action \u2190 withRef action `(($action : $((\u2190 read).m) $type))\n        ``(Bind.bind $action (fun ($id:ident : $type) => $k))\n      | none        => Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n    else\n      Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n  else if kind == `Lean.Parser.Term.doHave then\n    -- The `have` term is of the form  `\"have \" >> haveDecl >> optSemicolon termParser`\n    let args := decl.getArgs\n    let args := args ++ #[mkNullNode /- optional ';' -/, k]\n    pure $ mkNode `Lean.Parser.Term.\u00abhave\u00bb args\n  else\n    Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n\ndef reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do\n  let kind := reassign.getKind\n  if kind == `Lean.Parser.Term.doReassign then\n    -- doReassign := leading_parser (letIdDecl <|> letPatDecl)\n    let arg := reassign[0]\n    if arg.getKind == `Lean.Parser.Term.letIdDecl then\n      -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >>  \" := \" >> termParser\n      let x   := arg[0]\n      let val := arg[4]\n      let newVal \u2190 `(ensureTypeOf% $x $(quote \"invalid reassignment, value\") $val)\n      let arg := arg.setArg 4 newVal\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n    else\n      -- TODO: ensure the types did not change\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n  else\n    -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode\n    Macro.throwErrorAt reassign \"unexpected kind of 'do' reassignment\"\n\ndef mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do\n  if optIdent.isNone then\n    ``(ite $cond $thenBranch $elseBranch)\n  else\n    let h := optIdent[0]\n    ``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch))\n\ndef mkJoinPoint (j : Name) (ps : Array (Name \u00d7 Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do\n  let pTypes \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => do if useTypeOf then `(typeOf% $(\u2190 mkIdentFromRef id)) else `(_)\n  let ps     \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => mkIdentFromRef id\n  /-\n  We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.\n  By elaborating `$k` first, we \"learn\" more about `$body`'s type.\n  For example, consider the following example `do` expression\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x > 0 then\n    IO.println \"x is not zero\" -- Error is here\n  IO.mkRef true\n  ```\n  it is expanded into\n  ```\n  def f (x : Nat) : IO Unit := do\n  let jp (u : Unit) : IO _ :=\n    IO.mkRef true;\n  if x > 0 then\n    IO.println \"not zero\"\n    jp ()\n  else\n    jp ()\n  ```\n  If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit \u2192 IO (IO.Ref Bool)`.\n  Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit \u2192 IO Unit`.\n  Then, we get the expected type mismatch error at `IO.mkRef true`. -/\n  `(let_delayed $(\u2190 mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((\u2190 read).m) _ := $body; $k)\n\ndef mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=\n  Syntax.mkApp (mkIdentFrom ref j) args\n\npartial def toTerm : Code \u2192 M Syntax\n  | Code.\u00abreturn\u00bb ref val   => withRef ref <| returnToTerm val\n  | Code.\u00abcontinue\u00bb ref     => withRef ref continueToTerm\n  | Code.\u00abbreak\u00bb ref        => withRef ref breakToTerm\n  | Code.action e           => actionTerminalToTerm e\n  | Code.joinpoint j ps b k => do mkJoinPoint j ps (\u2190 toTerm b) (\u2190 toTerm k)\n  | Code.jmp ref j args     => pure $ mkJmp ref j args\n  | Code.decl _ stx k       => do declToTerm stx (\u2190 toTerm k)\n  | Code.reassign _ stx k   => do reassignToTerm stx (\u2190 toTerm k)\n  | Code.seq stx k          => do seqToTerm stx (\u2190 toTerm k)\n  | Code.ite ref _ o c t e  => withRef ref <| do mkIte o c (\u2190 toTerm t) (\u2190 toTerm e)\n  | Code.\u00abmatch\u00bb ref genParam discrs optType alts => do\n    let mut termAlts := #[]\n    for alt in alts do\n      let rhs \u2190 toTerm alt.rhs\n      let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref \"|\", alt.patterns, mkAtomFrom alt.ref \"=>\", rhs]\n      termAlts := termAlts.push termAlt\n    let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]\n    pure $ mkNode `Lean.Parser.Term.\u00abmatch\u00bb #[mkAtomFrom ref \"match\", genParam, discrs, optType, mkAtomFrom ref \"with\", termMatchAlts]\n\ndef run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do\n  let term \u2190 toTerm code { m := m, kind := kind, uvars := uvars }\n  pure term\n\n/- Given\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   generate Kind. See comment at the beginning of the `ToTerm` namespace. -/\ndef mkNestedKind (a r bc : Bool) : Kind :=\n  match a, r, bc with\n  | true,  false, false => Kind.regular\n  | false, true,  false => Kind.regular\n  | false, false, true  => Kind.nestedBC\n  | true,  true,  false => Kind.nestedPR\n  | true,  false, true  => Kind.nestedSBC\n  | false, true,  true  => Kind.nestedSBC\n  | true,  true,  true  => Kind.nestedPRBC\n  | false, false, false => unreachable!\n\ndef mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do\n  ToTerm.run code m uvars (mkNestedKind a r bc)\n\n/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.\n   See comment at the beginning of the `ToTerm` namespace.\n\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   The result is a sequence of `doElem` -/\ndef matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do\n  let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)\n  let u \u2190 mkTuple (\u2190 uvars.mapM mkIdentFromRef)\n  match a, r, bc with\n  | true, false, false =>\n    if uvars.isEmpty then\n      toDoElems (\u2190 `(do $term:term))\n    else\n      toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; pure r.1))\n  | false, true, false =>\n    if uvars.isEmpty then\n      toDoElems (\u2190 `(do let r \u2190 $term:term; return r))\n    else\n      toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; return r.1))\n  | false, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, false => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPR.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPR.\u00abreturn\u00bb b u => $u:term := u; return b)\n  | true, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; pure a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; return a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPRBC.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPRBC.\u00abreturn\u00bb a u => $u:term := u; return a\n         | DoResultPRBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultPRBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, false, false => unreachable!\n\nend ToTerm\n\ndef isMutableLet (doElem : Syntax) : Bool :=\n  let kind := doElem.getKind\n  (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)\n  &&\n  !doElem[1].isNone\n\nnamespace ToCodeBlock\n\nstructure Context where\n  ref         : Syntax\n  m           : Syntax -- Syntax representing the monad associated with the do notation.\n  mutableVars : NameSet := {}\n  insideFor   : Bool := false\n\nabbrev M := ReaderT Context TermElabM\n\n@[inline] def withNewMutableVars {\u03b1} (newVars : Array Name) (mutable : Bool) (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x\n\ndef checkReassignable (xs : Array Name) : M Unit := do\n  let throwInvalidReassignment (x : Name) : M Unit :=\n    throwError \"'{x.simpMacroScopes}' cannot be reassigned\"\n  let ctx \u2190 read\n  for x in xs do\n    unless ctx.mutableVars.contains x do\n      throwInvalidReassignment x\n\ndef checkNotShadowingMutable (xs : Array Name) : M Unit := do\n  let throwInvalidShadowing (x : Name) : M Unit :=\n    throwError \"mutable variable '{x.simpMacroScopes}' cannot be shadowed\"\n  let ctx \u2190 read\n  for x in xs do\n    if ctx.mutableVars.contains x then\n      throwInvalidShadowing x\n\n@[inline] def withFor {\u03b1} (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => { ctx with insideFor := true }) x\n\nstructure ToForInTermResult where\n  uvars      : Array Name\n  term       : Syntax\n\ndef mkForInBody  (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do\n  let ctx \u2190 read\n  let uvars := forInBody.uvars\n  let uvars := nameSetToArray uvars\n  let term \u2190 liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)\n  pure \u27e8uvars, term\u27e9\n\ndef ensureInsideFor : M Unit :=\n  unless (\u2190 read).insideFor do\n    throwError \"invalid 'do' element, it must be inside 'for'\"\n\ndef ensureEOS (doElems : List Syntax) : M Unit :=\n  unless doElems.isEmpty do\n    throwError \"must be last element in a 'do' sequence\"\n\nprivate partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax \u2192 StateT (List Syntax) MacroM Syntax\n  | stx@(Syntax.node k args) =>\n    if liftMethodDelimiter k then\n      return stx\n    else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do\n      if inBinder then\n        Macro.throwErrorAt stx \"cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`\"\n      let term := args[1]\n      let term \u2190 expandLiftMethodAux inQuot inBinder term\n      let auxDoElem \u2190 `(doElem| let a \u2190 $term:term)\n      modify fun s => s ++ [auxDoElem]\n      `(a)\n    else do\n      let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot\n      let inBinder   := inBinder || (!inQuot && liftMethodForbiddenBinder stx)\n      let args \u2190 args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)\n      return Syntax.node k args\n  | stx => pure stx\n\ndef expandLiftMethod (doElem : Syntax) : MacroM (List Syntax \u00d7 Syntax) := do\n  if !hasLiftMethod doElem then\n    pure ([], doElem)\n  else\n    let (doElem, doElemsNew) \u2190 (expandLiftMethodAux false false doElem).run []\n    pure (doElemsNew, doElem)\n\ndef checkLetArrowRHS (doElem : Syntax) : M Unit := do\n  let kind := doElem.getKind\n  if kind == `Lean.Parser.Term.doLetArrow ||\n     kind == `Lean.Parser.Term.doLet ||\n     kind == `Lean.Parser.Term.doLetRec ||\n     kind == `Lean.Parser.Term.doHave ||\n     kind == `Lean.Parser.Term.doReassign ||\n     kind == `Lean.Parser.Term.doReassignArrow then\n    throwErrorAt doElem \"invalid kind of value '{kind}' in an assignment\"\n\n/- Generate `CodeBlock` for `doReturn` which is of the form\n   ```\n   \"return \" >> optional termParser\n   ```\n   `doElems` is only used for sanity checking. -/\ndef doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do\n  ensureEOS doElems\n  let argOpt := doReturn[1]\n  let arg \u2190 if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]\n  return mkReturn (\u2190 getRef) arg\n\nstructure Catch where\n  x         : Syntax\n  optType   : Syntax\n  codeBlock : CodeBlock\n\ndef getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=\n  let ws := tryCode.uvars\n  let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws\n  let ws := match finallyCode? with\n    | none   => ws\n    | some c => union c.uvars ws\n  ws\n\ndef tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code \u2192 Bool) : Bool :=\n  p tryCode.code ||\n  catches.any (fun \u00abcatch\u00bb => p \u00abcatch\u00bb.codeBlock.code) ||\n  match finallyCode? with\n  | none => false\n  | some finallyCode => p finallyCode.code\n\nmutual\n  /- \"Concatenate\" `c` with `doSeqToCode doElems` -/\n  partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=\n    match doElems with\n    | [] => pure c\n    | nextDoElem :: _  => do\n      let k \u2190 doSeqToCode doElems\n      let ref := nextDoElem\n      concat c ref none k\n\n  /- Generate `CodeBlock` for `doLetArrow; doElems`\n     `doLetArrow` is of the form\n     ```\n     \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\n     ```\n     where\n     ```\n     def doIdDecl   := leading_parser ident >> optType >> leftArrow >> doElemParser\n     def doPatDecl  := leading_parser termParser >> leftArrow >> doElemParser >> optional (\" | \" >> doElemParser)\n     ```\n  -/\n  partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref     := doLetArrow\n    let decl    := doLetArrow[2]\n    if decl.getKind == `Lean.Parser.Term.doIdDecl then\n      let y := decl[0].getId\n      checkNotShadowingMutable #[y]\n      let doElem := decl[3]\n      let k \u2190 withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)\n      match isDoExpr? doElem with\n      | some action => pure $ mkVarDeclCore #[y] doLetArrow k\n      | none =>\n        checkLetArrowRHS doElem\n        let c \u2190 doSeqToCode [doElem]\n        match doElems with\n        | []       => pure c\n        | kRef::_  => concat c kRef y k\n    else if decl.getKind == `Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190\n          if isMutableLet doLetArrow then\n            `(do let discr \u2190 $doElem; let mut $pattern:term := discr)\n          else\n            `(do let discr \u2190 $doElem; let $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        if isMutableLet doLetArrow then\n          throwError \"'mut' is currently not supported in let-decls with 'else' case\"\n        let contSeq := mkDoSeq doElems.toArray\n        let elseSeq := mkSingletonDoSeq optElse[1]\n        let auxDo \u2190 `(do let discr \u2190 $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n    else\n      throwError \"unexpected kind of 'do' declaration\"\n\n\n  /- Generate `CodeBlock` for `doReassignArrow; doElems`\n     `doReassignArrow` is of the form\n     ```\n     (doIdDecl <|> doPatDecl)\n     ```\n  -/\n  partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref  := doReassignArrow\n    let decl := doReassignArrow[0]\n    if decl.getKind == `Lean.Parser.Term.doIdDecl then\n      let doElem := decl[3]\n      let y      := decl[0]\n      let auxDo \u2190 `(do let r \u2190 $doElem; $y:ident := r)\n      doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n    else if decl.getKind == `Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 `(do let discr \u2190 $doElem; $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        throwError \"reassignment with `|` (i.e., \\\"else clause\\\") is not currently supported\"\n    else\n      throwError \"unexpected kind of 'do' reassignment\"\n\n  /- Generate `CodeBlock` for `doIf; doElems`\n     `doIf` is of the form\n     ```\n     \"if \" >> optIdent >> termParser >> \" then \" >> doSeq\n      >> many (group (try (group (\" else \" >> \" if \")) >> optIdent >> termParser >> \" then \" >> doSeq))\n      >> optional (\" else \" >> doSeq)\n     ```  -/\n  partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let view \u2190 liftMacroM $ mkDoIfView doIf\n    let thenBranch \u2190 doSeqToCode (getDoSeqElems view.thenBranch)\n    let elseBranch \u2190 doSeqToCode (getDoSeqElems view.elseBranch)\n    let ite \u2190 mkIte view.ref view.optIdent view.cond thenBranch elseBranch\n    concatWith ite doElems\n\n  /- Generate `CodeBlock` for `doUnless; doElems`\n     `doUnless` is of the form\n     ```\n     \"unless \" >> termParser >> \"do \" >> doSeq\n     ```  -/\n  partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do\n    let ref   := doUnless\n    let cond  := doUnless[1]\n    let doSeq := doUnless[3]\n    let body \u2190 doSeqToCode (getDoSeqElems doSeq)\n    let unlessCode \u2190 liftMacroM <| mkUnless cond body\n    concatWith unlessCode doElems\n\n  /- Generate `CodeBlock` for `doFor; doElems`\n     `doFor` is of the form\n     ```\n     def doForDecl := leading_parser termParser >> \" in \" >> withForbidden \"do\" termParser\n     def doFor := leading_parser \"for \" >> sepBy1 doForDecl \", \" >> \"do \" >> doSeq\n     ```\n  -/\n  partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let doForDecls := doFor[1].getSepArgs\n    if doForDecls.size > 1 then\n      /-\n        Expand\n        ```\n        for x in xs, y in ys do\n          body\n        ```\n        into\n        ```\n        let s := toStream ys\n        for x in xs do\n          match Stream.next? s with\n          | none => break\n          | some (y, s') =>\n            s := s'\n            body\n        ```\n      -/\n      -- Extract second element\n      let doForDecl := doForDecls[1]\n      let y  := doForDecl[0]\n      let ys := doForDecl[2]\n      let doForDecls := doForDecls.eraseIdx 1\n      let body := doFor[3]\n      withFreshMacroScope do\n        let toStreamFn \u2190 withRef ys ``(toStream)\n        let auxDo \u2190\n          `(do let mut s := $toStreamFn:ident $ys\n               for $doForDecls:doForDecl,* do\n                 match Stream.next? s with\n                 | none => break\n                 | some ($y, s') =>\n                   s := s'\n                   do $body)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n    else withRef doFor do\n      let x         := doForDecls[0][0]\n      withRef x <| checkNotShadowingMutable (\u2190 getPatternVarsEx x)\n      let xs        := doForDecls[0][2]\n      let forElems  := getDoSeqElems doFor[3]\n      let forInBodyCodeBlock \u2190 withFor (doSeqToCode forElems)\n      let \u27e8uvars, forInBody\u27e9 \u2190 mkForInBody x forInBodyCodeBlock\n      let uvarsTuple \u2190 liftMacroM do mkTuple (\u2190 uvars.mapM mkIdentFromRef)\n      if hasReturn forInBodyCodeBlock.code then\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)\n        let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                         $uvarsTuple:term := r.2;\n                         match r.1 with\n                         | none => Pure.pure (ensureExpectedType% \"type mismatch, 'for'\" PUnit.unit)\n                         | some a => return ensureExpectedType% \"type mismatch, 'for'\" a)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n      else\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody)\n        if doElems.isEmpty then\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                           $uvarsTuple:term := r;\n                           Pure.pure (ensureExpectedType% \"type mismatch, 'for'\" PUnit.unit))\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n        else\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term; $uvarsTuple:term := r)\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n\n  /-- Generate `CodeBlock` for `doMatch; doElems` -/\n  partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref       := doMatch\n    let genParam  := doMatch[1]\n    let discrs    := doMatch[2]\n    let optType   := doMatch[3]\n    let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`\n    let alts \u2190  matchAlts.mapM fun matchAlt => do\n      let patterns := matchAlt[1]\n      let vars \u2190 getPatternsVarsEx patterns.getSepArgs\n      withRef patterns <| checkNotShadowingMutable vars\n      let rhs  := matchAlt[3]\n      let rhs \u2190 doSeqToCode (getDoSeqElems rhs)\n      pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }\n    let matchCode \u2190 mkMatch ref genParam discrs optType alts\n    concatWith matchCode doElems\n\n  /--\n    Generate `CodeBlock` for `doTry; doElems`\n    ```\n    def doTry := leading_parser \"try \" >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally\n    def doCatch      := leading_parser \"catch \" >> binderIdent >> optional (\":\" >> termParser) >> darrow >> doSeq\n    def doCatchMatch := leading_parser \"catch \" >> doMatchAlts\n    def doFinally    := leading_parser \"finally \" >> doSeq\n    ```\n  -/\n  partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref := doTry\n    let tryCode \u2190 doSeqToCode (getDoSeqElems doTry[1])\n    let optFinally := doTry[3]\n    let catches \u2190 doTry[2].getArgs.mapM fun catchStx => do\n      if catchStx.getKind == `Lean.Parser.Term.doCatch then\n        let x       := catchStx[1]\n        if x.isIdent then\n          withRef x <| checkNotShadowingMutable #[x.getId]\n        let optType := catchStx[2]\n        let c \u2190 doSeqToCode (getDoSeqElems catchStx[4])\n        pure { x := x, optType := optType, codeBlock := c : Catch }\n      else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then\n        let matchAlts := catchStx[1]\n        let x \u2190 `(ex)\n        let auxDo \u2190 `(do match ex with $matchAlts)\n        let c \u2190 doSeqToCode (getDoSeqElems (getDoSeq auxDo))\n        pure { x := x, codeBlock := c, optType := mkNullNode : Catch }\n      else\n        throwError \"unexpected kind of 'catch'\"\n    let finallyCode? \u2190 if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])\n    if catches.isEmpty && finallyCode?.isNone then\n      throwError \"invalid 'try', it must have a 'catch' or 'finally'\"\n    let ctx \u2190 read\n    let ws    := getTryCatchUpdatedVars tryCode catches finallyCode?\n    let uvars := nameSetToArray ws\n    let a     := tryCatchPred tryCode catches finallyCode? hasTerminalAction\n    let r     := tryCatchPred tryCode catches finallyCode? hasReturn\n    let bc    := tryCatchPred tryCode catches finallyCode? hasBreakContinue\n    let toTerm (codeBlock : CodeBlock) : M Syntax := do\n      let codeBlock \u2190 liftM $ extendUpdatedVars codeBlock ws\n      liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc\n    let term \u2190 toTerm tryCode\n    let term \u2190 catches.foldlM\n      (fun term \u00abcatch\u00bb => do\n        let catchTerm \u2190 toTerm \u00abcatch\u00bb.codeBlock\n        if catch.optType.isNone then\n          ``(MonadExcept.tryCatch $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n        else\n          let type := \u00abcatch\u00bb.optType[1]\n          ``(tryCatchThe $type $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm)))\n      term\n    let term \u2190 match finallyCode? with\n      | none             => pure term\n      | some finallyCode => withRef optFinally do\n        unless finallyCode.uvars.isEmpty do\n          throwError \"'finally' currently does not support reassignments\"\n        if hasBreakContinueReturn finallyCode.code then\n          throwError \"'finally' currently does 'return', 'break', nor 'continue'\"\n        let finallyTerm \u2190 liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular\n        ``(tryFinally $term $finallyTerm)\n    let doElemsNew \u2190 liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc\n    doSeqToCode (doElemsNew ++ doElems)\n\n  partial def doSeqToCode : List Syntax \u2192 M CodeBlock\n    | [] => do liftMacroM mkPureUnitAction\n    | doElem::doElems => withIncRecDepth <| withRef doElem do\n      checkMaxHeartbeats \"'do'-expander\"\n      match (\u2190 liftMacroM <| expandMacro? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n      match (\u2190 liftMacroM <| expandDoIf? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n        let (liftedDoElems, doElem) \u2190 liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _)\n        if !liftedDoElems.isEmpty then\n          doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)\n        else\n          let ref := doElem\n          let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems\n          let k := doElem.getKind\n          if k == `Lean.Parser.Term.doLet then\n            let vars \u2190 getDoLetVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doHave then\n            let var := getDoHaveVar doElem\n            checkNotShadowingMutable #[var]\n            mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doLetRec then\n            let vars \u2190 getDoLetRecVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doReassign then\n            let vars \u2190 getDoReassignVars doElem\n            checkReassignable vars\n            let k \u2190 doSeqToCode doElems\n            mkReassignCore vars doElem k\n          else if k == `Lean.Parser.Term.doLetArrow then\n            doLetArrowToCode doElem doElems\n          else if k == `Lean.Parser.Term.doReassignArrow then\n            doReassignArrowToCode doElem doElems\n          else if k == `Lean.Parser.Term.doIf then\n            doIfToCode doElem doElems\n          else if k == `Lean.Parser.Term.doUnless then\n            doUnlessToCode doElem doElems\n          else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do\n            doForToCode doElem doElems\n          else if k == `Lean.Parser.Term.doMatch then\n            doMatchToCode doElem doElems\n          else if k == `Lean.Parser.Term.doTry then\n            doTryToCode doElem doElems\n          else if k == `Lean.Parser.Term.doBreak then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkBreak ref\n          else if k == `Lean.Parser.Term.doContinue then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkContinue ref\n          else if k == `Lean.Parser.Term.doReturn then\n            doReturnToCode doElem doElems\n          else if k == `Lean.Parser.Term.doDbgTrace then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doAssert then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == `Lean.Parser.Term.doNested then\n            let nestedDoSeq := doElem[1]\n            doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)\n          else if k == `Lean.Parser.Term.doExpr then\n            let term := doElem[0]\n            if doElems.isEmpty then\n              return mkTerminalAction term\n            else\n              return mkSeq term (\u2190 doSeqToCode doElems)\n          else\n            throwError \"unexpected do-element\\n{doElem}\"\nend\n\ndef run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=\n  (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m }\n\nend ToCodeBlock\n\n/- Create a synthetic metavariable `?m` and assign `m` to it.\n   We use `?m` to refer to `m` when expanding the `do` notation. -/\nprivate def mkMonadAlias (m : Expr) : TermElabM Syntax := do\n  let result \u2190 `(?m)\n  let mType \u2190 inferType m\n  let mvar \u2190 elabTerm result mType\n  assignExprMVar mvar.mvarId! m\n  pure result\n\n@[builtinTermElab \u00abdo\u00bb]\ndef elabDo : TermElab := fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  let bindInfo \u2190 extractBind expectedType?\n  let m \u2190 mkMonadAlias bindInfo.m\n  let codeBlock \u2190 ToCodeBlock.run stx m\n  let stxNew \u2190 liftMacroM $ ToTerm.run codeBlock.code m\n  trace[Elab.do] stxNew\n  withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType\n\nend Do\n\nbuiltin_initialize registerTraceClass `Elab.do\n\nprivate def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do\n  let stx := stx.setKind newKind\n  withRef stx `(do $stx:doElem)\n\n@[builtinMacro Lean.Parser.Term.termFor]\ndef expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor\n\n@[builtinMacro Lean.Parser.Term.termTry]\ndef expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry\n\n@[builtinMacro Lean.Parser.Term.termUnless]\ndef expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless\n\n@[builtinMacro Lean.Parser.Term.termReturn]\ndef expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn\n\nend Lean.Elab.Term\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/Elab/Do.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12940273159163906, "lm_q2_score": 0.023689470093140645, "lm_q1q2_score": 0.0030654821400108397}}
{"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.Elab.Term\nimport Lean.Elab.BindersUtil\nimport Lean.Elab.PatternVar\nimport Lean.Elab.Quotation.Util\nimport Lean.Parser.Do\n\n-- HACK: avoid code explosion until heuristics are improved\nset_option compiler.reuse false\n\nnamespace Lean.Elab.Term\nopen Lean.Parser.Term\nopen Meta\n\nprivate def getDoSeqElems (doSeq : Syntax) : List Syntax :=\n  if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then\n    doSeq[1].getArgs.toList.map fun arg => arg[0]\n  else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then\n    doSeq[0].getArgs.toList.map fun arg => arg[0]\n  else\n    []\n\nprivate def getDoSeq (doStx : Syntax) : Syntax :=\n  doStx[1]\n\n@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>\n  throwErrorAt stx \"invalid use of `(<- ...)`, must be nested inside a 'do' expression\"\n\n/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/\nprivate def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=\n  k == ``Lean.Parser.Term.do ||\n  k == ``Lean.Parser.Term.doSeqIndent ||\n  k == ``Lean.Parser.Term.doSeqBracketed ||\n  k == ``Lean.Parser.Term.termReturn ||\n  k == ``Lean.Parser.Term.termUnless ||\n  k == ``Lean.Parser.Term.termTry ||\n  k == ``Lean.Parser.Term.termFor\n\n/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/\nprivate def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=\n  let k := letDeclArg.getKind\n  if k == ``Lean.Parser.Term.letPatDecl then\n    false\n  else if k == ``Lean.Parser.Term.letEqnsDecl then\n    true\n  else if k == ``Lean.Parser.Term.letIdDecl then\n    -- letIdLhs := ident >> checkWsBefore \"expected space before binders\" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType\n    let binders := letDeclArg[1]\n    binders.getNumArgs > 0\n  else\n    false\n\n/-- Return `true` if the given `letDecl` contains binders. -/\nprivate def letDeclHasBinders (letDecl : Syntax) : Bool :=\n  letDeclArgHasBinders letDecl[0]\n\n/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/\nprivate def liftMethodForbiddenBinder (stx : Syntax) : Bool :=\n  let k := stx.getKind\n  if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||\n     k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec  then\n     -- It is never ok to lift over this kind of binder\n    true\n  -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not\n  else if k == ``Lean.Parser.Term.let then\n    letDeclHasBinders stx[1]\n  else if k == ``Lean.Parser.Term.doLet then\n    letDeclHasBinders stx[2]\n  else if k == ``Lean.Parser.Term.doLetArrow then\n    letDeclArgHasBinders stx[2]\n  else\n    false\n\nprivate partial def hasLiftMethod : Syntax \u2192 Bool\n  | Syntax.node _ k args =>\n    if liftMethodDelimiter k then false\n    -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a\n    -- bit slower\n    else if k == ``Lean.Parser.Term.liftMethod then true\n    else args.any hasLiftMethod\n  | _ => false\n\nstructure ExtractMonadResult where\n  m            : Expr\n  \u03b1            : Expr\n  expectedType : Expr\n\nprivate partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do\n  match expectedType? with\n  | none => throwError \"invalid 'do' notation, expected type is not available\"\n  | some expectedType =>\n    let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match type with\n      | Expr.app m \u03b1 _ =>\n        try\n          let bindInstType \u2190 mkAppM ``Bind #[m]\n          let _  \u2190 Meta.synthInstance bindInstType\n          return some { m := m, \u03b1 := \u03b1, expectedType := expectedType }\n        catch _ =>\n          return none\n      | _ =>\n        return none\n    let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do\n      match (\u2190 extractStep? type) with\n      | some r => return r\n      | none =>\n        let typeNew \u2190 whnfCore type\n        if typeNew != type then\n          extract? typeNew\n        else\n          if typeNew.getAppFn.isMVar then throwError \"invalid 'do' notation, expected type is not available\"\n          match (\u2190 unfoldDefinition? typeNew) with\n          | some typeNew => extract? typeNew\n          | none => return none\n    match (\u2190 extract? expectedType) with\n    | some r => return r\n    | none   => throwError \"invalid 'do' notation, expected type is not a monad application{indentExpr expectedType}\\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad.\"\n\nnamespace Do\n\n/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/\nstructure Alt (\u03c3 : Type) where\n  ref : Syntax\n  vars : Array Name\n  patterns : Syntax\n  rhs : \u03c3\n  deriving Inhabited\n\n/-\n  Auxiliary datastructure for representing a `do` code block, and compiling \"reassignments\" (e.g., `x := x + 1`).\n  We convert `Code` into a `Syntax` term representing the:\n  - `do`-block, or\n  - the visitor argument for the `forIn` combinator.\n\n  We say the following constructors are terminals:\n  - `break`:    for interrupting a `for x in s`\n  - `continue`: for interrupting the current iteration of a `for x in s`\n  - `return e`: for returning `e` as the result for the whole `do` computation block\n  - `action a`: for executing action `a` as a terminal\n  - `ite`:      if-then-else\n  - `match`:    pattern matching\n  - `jmp`       a goto to a join-point\n\n  We say the terminals `break`, `continue`, `action`, and `return` are \"exit points\"\n\n  Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x == 0 then\n     return ()\n  IO.println \"hello\"\n  ```\n  Executing `#eval f 0` will not print \"hello\". Now, consider\n  ```\n  def g (x : Nat) : IO Unit := do\n  if x == 0 then\n     pure ()\n  IO.println \"hello\"\n  ```\n  The `if` statement is essentially a noop, and \"hello\" is printed when we execute `g 0`.\n\n  - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).\n    The field `stx` is the actual `doElem`,\n    `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.\n    `vars` is an array since we have declarations such as `let (a, b) := s`.\n\n  - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).\n\n  - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.\n\n  - `seq a k` executes action `a`, ignores its result, and then executes `k`.\n    We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.\n\n  A code block `C` is well-formed if\n  - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and\n    `ps.size == as.size` -/\ninductive Code where\n  | decl         (xs : Array Name) (doElem : Syntax) (k : Code)\n  | reassign     (xs : Array Name) (doElem : Syntax) (k : Code)\n  /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/\n  | joinpoint    (name : Name) (params : Array (Name \u00d7 Bool)) (body : Code) (k : Code)\n  | seq          (action : Syntax) (k : Code)\n  | action       (action : Syntax)\n  | \u00abbreak\u00bb      (ref : Syntax)\n  | \u00abcontinue\u00bb   (ref : Syntax)\n  | \u00abreturn\u00bb     (ref : Syntax) (val : Syntax)\n  /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/\n  | ite          (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)\n  | \u00abmatch\u00bb      (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))\n  | jmp          (ref : Syntax) (jpName : Name) (args : Array Syntax)\n  deriving Inhabited\n\n/- A code block, and the collection of variables updated by it. -/\nstructure CodeBlock where\n  code  : Code\n  uvars : NameSet := {} -- set of variables updated by `code`\n\nprivate def nameSetToArray (s : NameSet) : Array Name :=\n  s.fold (fun (xs : Array Name) x => xs.push x) #[]\n\nprivate def varsToMessageData (vars : Array Name) : MessageData :=\n  MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) \" \"\n\npartial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=\n  let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName\n  let rec loop : Code \u2192 MessageData\n    | Code.decl xs _ k            => m!\"let {varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.reassign xs _ k        => m!\"{varsToMessageData xs} := ...\\n{loop k}\"\n    | Code.joinpoint n ps body k  => m!\"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\\n{loop k}\"\n    | Code.seq e k                => m!\"{e}\\n{loop k}\"\n    | Code.action e               => e\n    | Code.ite _ _ _ c t e        => m!\"if {c} then {indentD (loop t)}\\nelse{loop e}\"\n    | Code.jmp _ j xs             => m!\"jmp {j.simpMacroScopes} {xs.toList}\"\n    | Code.\u00abbreak\u00bb _              => m!\"break {us}\"\n    | Code.\u00abcontinue\u00bb _           => m!\"continue {us}\"\n    | Code.\u00abreturn\u00bb _ v           => m!\"return {v} {us}\"\n    | Code.\u00abmatch\u00bb _ _ ds t alts  =>\n      m!\"match {ds} with\"\n      ++ alts.foldl (init := m!\"\") fun acc alt => acc ++ m!\"\\n| {alt.patterns} => {loop alt.rhs}\"\n  loop codeBlock.code\n\n/- Return true if the give code contains an exit point that satisfies `p` -/\npartial def hasExitPointPred (c : Code) (p : Code \u2192 Bool) : Bool :=\n  let rec loop : Code \u2192 Bool\n    | Code.decl _ _ k           => loop k\n    | Code.reassign _ _ k       => loop k\n    | Code.joinpoint _ _ b k    => loop b || loop k\n    | Code.seq _ k              => loop k\n    | Code.ite _ _ _ _ t e      => loop t || loop e\n    | Code.\u00abmatch\u00bb _ _ _ _ alts => alts.any (loop \u00b7.rhs)\n    | Code.jmp _ _ _            => false\n    | c                         => p c\n  loop c\n\ndef hasExitPoint (c : Code) : Bool :=\n  hasExitPointPred c fun c => true\n\ndef hasReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef hasTerminalAction (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abaction\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinue (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | _ => false\n\ndef hasBreakContinueReturn (c : Code) : Bool :=\n  hasExitPointPred c fun\n    | Code.\u00abbreak\u00bb _    => true\n    | Code.\u00abcontinue\u00bb _ => true\n    | Code.\u00abreturn\u00bb _ _ => true\n    | _ => false\n\ndef mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax \u2192 m Code) : m Code := withRef e <| withFreshMacroScope do\n  let y \u2190 `(y)\n  let yName := y.getId\n  let doElem \u2190 `(doElem| let y \u2190 $e:term)\n  -- Add elaboration hint for producing sane error message\n  let y \u2190 `(ensure_expected_type% \"type mismatch, result value\" $y)\n  let k \u2190 mkCont y\n  pure $ Code.decl #[yName] doElem k\n\n/- Convert `action _ e` instructions in `c` into `let y \u2190 e; jmp _ jp (xs y)`. -/\npartial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=\n  let rec loop : Code \u2192 MacroM Code\n    | Code.decl xs stx k           => return Code.decl xs stx (\u2190 loop k)\n    | Code.reassign xs stx k       => return Code.reassign xs stx (\u2190 loop k)\n    | Code.joinpoint n ps b k      => return Code.joinpoint n ps (\u2190 loop b) (\u2190 loop k)\n    | Code.seq e k                 => return Code.seq e (\u2190 loop k)\n    | Code.ite ref x? h c t e      => return Code.ite ref x? h c (\u2190 loop t) (\u2190 loop e)\n    | Code.\u00abmatch\u00bb ref g ds t alts => return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 loop alt.rhs) })\n    | Code.action e                => mkAuxDeclFor e fun y =>\n      let ref := e\n      -- We jump to `jp` with xs **and** y\n      let jmpArgs := xs.map $ mkIdentFrom ref\n      let jmpArgs := jmpArgs.push y\n      return Code.jmp ref jp jmpArgs\n    | c                            => return c\n  loop code\n\nstructure JPDecl where\n  name : Name\n  params : Array (Name \u00d7 Bool)\n  body : Code\n\ndef attachJP (jpDecl : JPDecl) (k : Code) : Code :=\n  Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k\n\ndef attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=\n  jpDecls.foldr attachJP k\n\ndef mkFreshJP (ps : Array (Name \u00d7 Bool)) (body : Code) : TermElabM JPDecl := do\n  let ps \u2190\n    if ps.isEmpty then\n      let y \u2190 mkFreshUserName `y\n      pure #[(y, false)]\n    else\n      pure ps\n  -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by\n  -- the \"do\" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`\n  -- We will remove this hack when we re-implement the compiler frontend in Lean.\n  let name \u2190 mkFreshUserName `_do_jp\n  pure { name := name, params := ps, body := body }\n\ndef mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=\n  mkFreshJP (xs.map fun x => (x, true)) body\n\ndef addFreshJP (ps : Array (Name \u00d7 Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do\n  let jp \u2190 mkFreshJP ps body\n  modify fun (jps : Array JPDecl) => jps.push jp\n  pure jp.name\n\ndef insertVars (rs : NameSet) (xs : Array Name) : NameSet :=\n  xs.foldl (\u00b7.insert \u00b7) rs\n\ndef eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=\n  xs.foldl (\u00b7.erase \u00b7) rs\n\ndef eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=\n  match x? with\n  | none   => rs\n  | some x => rs.insert x\n\n/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/\ndef mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := nameSetToArray rs\n  let jp \u2190 addFreshJP (xs.map fun x => (x, true)) c\n  if xs.isEmpty then\n    let unit \u2190 ``(Unit.unit)\n    return Code.jmp ref jp #[unit]\n  else\n    return Code.jmp ref jp (xs.map $ mkIdentFrom ref)\n\n/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.\n   The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`\n   is a fresh variable created by this method. -/\ndef mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax \u2192 MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do\n  let xs := nameSetToArray rs\n  let args := xs.map $ mkIdentFrom ref\n  let args := args.push val\n  let yFresh \u2190 mkFreshUserName `y\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (yFresh, false)\n  let jpBody \u2190 liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)\n  let jp \u2190 addFreshJP ps jpBody\n  pure $ Code.jmp ref jp args\n\n/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path.  -/\npartial def pullExitPointsAux : NameSet \u2192 Code \u2192 StateRefT (Array JPDecl) TermElabM Code\n  | rs, Code.decl xs stx k           => return Code.decl xs stx (\u2190 pullExitPointsAux (eraseVars rs xs) k)\n  | rs, Code.reassign xs stx k       => return Code.reassign xs stx (\u2190 pullExitPointsAux (insertVars rs xs) k)\n  | rs, Code.joinpoint j ps b k      => return Code.joinpoint j ps (\u2190 pullExitPointsAux rs b) (\u2190 pullExitPointsAux rs k)\n  | rs, Code.seq e k                 => return Code.seq e (\u2190 pullExitPointsAux rs k)\n  | rs, Code.ite ref x? o c t e      => return Code.ite ref x? o c (\u2190 pullExitPointsAux (eraseOptVar rs x?) t) (\u2190 pullExitPointsAux (eraseOptVar rs x?) e)\n  | rs, Code.\u00abmatch\u00bb ref g ds t alts => return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })\n  | rs, c@(Code.jmp _ _ _)           => return  c\n  | rs, Code.\u00abbreak\u00bb ref             => mkSimpleJmp ref rs (Code.\u00abbreak\u00bb ref)\n  | rs, Code.\u00abcontinue\u00bb ref          => mkSimpleJmp ref rs (Code.\u00abcontinue\u00bb ref)\n  | rs, Code.\u00abreturn\u00bb ref val        => mkJmp ref rs val (fun y => pure $ Code.\u00abreturn\u00bb ref y)\n  | rs, Code.action e                =>\n    -- We use `mkAuxDeclFor` because `e` is not pure.\n    mkAuxDeclFor e fun y =>\n      let ref := e\n      mkJmp ref rs y (fun yFresh => do pure $ Code.action (\u2190 ``(Pure.pure $yFresh)))\n\n/-\nAuxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.\nWhen a new variable is not already in the collection, but is shadowed by some declaration in `c`,\nwe create auxiliary join points to make sure we preserve the semantics of the code block.\nExample: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it\nwith the reassignment `x := x + 1`. We first use `pullExitPoints` to create\n```\nlet jp (x!1) :=  return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nand then we add the reassignment\n```\nx := x + 1\nlet jp (x!1) := return x!1;\nprint x;\nlet x := 10;\njmp jp x\n```\nNote that we created a fresh variable `x!1` to avoid accidental name capture.\nAs another example, consider\n```\nprint x;\nlet x := 10\ny := y + 1;\nreturn x;\n```\nWe transform it into\n```\nlet jp (y x!1) := return x!1;\nprint x;\nlet x := 10\ny := y + 1;\njmp jp y x\n```\nand then we add the reassignment as in the previous example.\nWe need to include `y` in the jump, because each exit point is implicitly returning the set of\nupdate variables.\n\nWe implement the method as follows. Let `us` be `c.uvars`, then\n1- for each `return _ y` in `c`, we create a join point\n  `let j (us y!1) := return y!1`\n   and replace the `return _ y` with `jmp us y`\n2- for each `break`, we create a join point\n  `let j (us) := break`\n   and replace the `break` with `jmp us`.\n3- Same as 2 for `continue`.\n-/\ndef pullExitPoints (c : Code) : TermElabM Code := do\n  if hasExitPoint c then\n    let (c, jpDecls) \u2190 (pullExitPointsAux {} c).run #[]\n    pure $ attachJPs jpDecls c\n  else\n    pure c\n\npartial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=\n  let rec update : Code \u2192 TermElabM Code\n    | Code.joinpoint j ps b k          => return Code.joinpoint j ps (\u2190 update b) (\u2190 update k)\n    | Code.seq e k                     => return Code.seq e (\u2190 update k)\n    | c@(Code.\u00abmatch\u00bb ref g ds t alts) => do\n      if alts.any fun alt => alt.vars.any fun x => ws.contains x then\n        -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.\u00abmatch\u00bb ref g ds t (\u2190 alts.mapM fun alt => do pure { alt with rhs := (\u2190 update alt.rhs) })\n    | Code.ite ref none o c t e => return Code.ite ref none o c (\u2190 update t) (\u2190 update e)\n    | c@(Code.ite ref (some h) o cond t e) => do\n      if ws.contains h then\n        -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`\n        pullExitPoints c\n      else\n        return Code.ite ref (some h) o cond (\u2190 update t) (\u2190 update e)\n    | Code.reassign xs stx k => return Code.reassign xs stx (\u2190 update k)\n    | c@(Code.decl xs stx k) => do\n      if xs.any fun x => ws.contains x then\n        -- One the declared variables is shadowing a variable in `ws`\n        pullExitPoints c\n      else\n        return Code.decl xs stx (\u2190 update k)\n    | c => return  c\n  update c\n\n/-\nExtend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.\nWe **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.\nSee discussion at `pullExitPoints`.\n-/\npartial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do\n  if ws.any fun x => !c.uvars.contains x then\n    -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)\n    pure { code := (\u2190 extendUpdatedVarsAux c.code ws), uvars := ws }\n  else\n    pure { c with uvars := ws }\n\nprivate def union (s\u2081 s\u2082 : NameSet) : NameSet :=\n  s\u2081.fold (\u00b7.insert \u00b7) s\u2082\n\n/-\nGiven two code blocks `c\u2081` and `c\u2082`, make sure they have the same set of updated variables.\nLet `ws` the union of the updated variables in `c\u2081\u2035 and \u2035c\u2082`.\nWe use `extendUpdatedVars c\u2081 ws` and `extendUpdatedVars c\u2082 ws`\n-/\ndef homogenize (c\u2081 c\u2082 : CodeBlock) : TermElabM (CodeBlock \u00d7 CodeBlock) := do\n  let ws := union c\u2081.uvars c\u2082.uvars\n  let c\u2081 \u2190 extendUpdatedVars c\u2081 ws\n  let c\u2082 \u2190 extendUpdatedVars c\u2082 ws\n  pure (c\u2081, c\u2082)\n\n/-\nExtending code blocks with variable declarations: `let x : t := v` and `let x : t \u2190 v`.\nWe remove `x` from the collection of updated varibles.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `let (x, y) := t`\n-/\ndef mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {\n  code := Code.decl xs stx c.code,\n  uvars := eraseVars c.uvars xs\n}\n\n/-\nExtending code blocks with reassignments: `x : t := v` and `x : t \u2190 v`.\nRemark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables\ndeclared by it. It is an array because we have let-declarations that declare multiple variables.\nExample: `(x, y) \u2190 t`\n-/\ndef mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do\n  let us := c.uvars\n  let ws := insertVars us xs\n  -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.\n  -- See discussion at `pullExitPoints`\n  let code \u2190 if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code\n  pure { code := Code.reassign xs stx code, uvars := ws }\n\ndef mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=\n  { c with code := Code.seq action c.code }\n\ndef mkTerminalAction (action : Syntax) : CodeBlock :=\n  { code := Code.action action }\n\ndef mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=\n  { code := Code.\u00abreturn\u00bb ref val }\n\ndef mkBreak (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abbreak\u00bb ref }\n\ndef mkContinue (ref : Syntax) : CodeBlock :=\n  { code := Code.\u00abcontinue\u00bb ref }\n\ndef mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do\n  let x? := if optIdent.isNone then none else some optIdent[0].getId\n  let (thenBranch, elseBranch) \u2190 homogenize thenBranch elseBranch\n  pure {\n    code  := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,\n    uvars := thenBranch.uvars,\n  }\n\nprivate def mkUnit : MacroM Syntax :=\n  ``((\u27e8\u27e9 : PUnit))\n\nprivate def mkPureUnit : MacroM Syntax :=\n  ``(pure PUnit.unit)\n\ndef mkPureUnitAction : MacroM CodeBlock := do\n  return mkTerminalAction (\u2190 mkPureUnit)\n\ndef mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do\n  let thenBranch \u2190 mkPureUnitAction\n  pure { c with code := Code.ite (\u2190 getRef) none mkNullNode cond thenBranch.code c.code }\n\ndef mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do\n  -- nary version of homogenize\n  let ws := alts.foldl (union \u00b7 \u00b7.rhs.uvars) {}\n  let alts \u2190 alts.mapM fun alt => do\n    let rhs \u2190 extendUpdatedVars alt.rhs ws\n    pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }\n  pure { code := Code.\u00abmatch\u00bb ref genParam discrs optType alts, uvars := ws }\n\n/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.\n   This method assumes `terminal` is a terminal -/\ndef concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do\n  unless hasTerminalAction terminal.code do\n    throwErrorAt kRef \"'do' element is unreachable\"\n  let (terminal, k) \u2190 homogenize terminal k\n  let xs := nameSetToArray k.uvars\n  let y \u2190 match y? with | some y => pure y | none => mkFreshUserName `y\n  let ps := xs.map fun x => (x, true)\n  let ps := ps.push (y, false)\n  let jpDecl \u2190 mkFreshJP ps k.code\n  let jp := jpDecl.name\n  let terminal \u2190 liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs\n  pure { code  := attachJP jpDecl terminal, uvars := k.uvars }\n\ndef getLetIdDeclVar (letIdDecl : Syntax) : Name :=\n  letIdDecl[0].getId\n\n-- support both regular and syntax match\ndef getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=\n  getPatternVarNames <$> getPatternVars pattern <|>\n  Array.map Syntax.getId <$> Quotation.getPatternVars pattern\n\ndef getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=\n  getPatternVarNames <$> getPatternsVars patterns <|>\n  Array.map Syntax.getId <$> Quotation.getPatternsVars patterns\n\ndef getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do\n  let pattern := letPatDecl[0]\n  getPatternVarsEx pattern\n\ndef getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=\n  letEqnsDecl[0].getId\n\ndef getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do\n  let arg := letDecl[0]\n  if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n    pure #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then\n    pure #[getLetEqnsDeclVar arg]\n  else\n    throwError \"unexpected kind of let declaration\"\n\ndef getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=\n  -- leading_parser \"let \" >> optional \"mut \" >> letDecl\n  getLetDeclVars doLet[2]\n\ndef getHaveIdLhsVar (optIdent : Syntax) : Name :=\n  if optIdent.isNone then\n    `this\n  else\n    optIdent[0].getId\n\ndef getDoHaveVars (doHave : Syntax) : TermElabM (Array Name) :=\n  -- doHave := leading_parser \"have \" >> Term.haveDecl\n  -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl\n  let arg := doHave[1][0]\n  if arg.getKind == ``Lean.Parser.Term.haveIdDecl then\n    -- haveIdDecl := leading_parser atomic (haveIdLhs >> \" := \") >> termParser\n    -- haveIdLhs := optional (ident >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder))) >> optType\n    pure #[getHaveIdLhsVar arg[0]]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else if arg.getKind == ``Lean.Parser.Term.haveEqnsDecl then\n    -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts\n    pure #[getHaveIdLhsVar arg[0]]\n  else\n    throwError \"unexpected kind of have declaration\"\n\ndef getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do\n  -- letRecDecls is an array of `(group (optional attributes >> letDecl))`\n  let letRecDecls := doLetRec[1][0].getSepArgs\n  let letDecls := letRecDecls.map fun p => p[2]\n  let mut allVars := #[]\n  for letDecl in letDecls do\n    let vars \u2190 getLetDeclVars letDecl\n    allVars := allVars ++ vars\n  pure allVars\n\n-- ident >> optType >> leftArrow >> termParser\ndef getDoIdDeclVar (doIdDecl : Syntax) : Name :=\n  doIdDecl[0].getId\n\n-- termParser >> leftArrow >> termParser >> optional (\" | \" >> termParser)\ndef getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do\n  let pattern := doPatDecl[0]\n  getPatternVarsEx pattern\n\n-- leading_parser \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\ndef getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do\n  let decl := doLetArrow[2]\n  if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n    pure #[getDoIdDeclVar decl]\n  else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n    getDoPatDeclVars decl\n  else\n    throwError \"unexpected kind of 'do' declaration\"\n\ndef getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do\n  let arg := doReassign[0]\n  if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n    pure #[getLetIdDeclVar arg]\n  else if arg.getKind == ``Lean.Parser.Term.letPatDecl then\n    getLetPatDeclVars arg\n  else\n    throwError \"unexpected kind of reassignment\"\n\ndef mkDoSeq (doElems : Array Syntax) : Syntax :=\n  mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]\n\ndef mkSingletonDoSeq (doElem : Syntax) : Syntax :=\n  mkDoSeq #[doElem]\n\n/-\n  If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s.  -/\nprivate def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with\n  | `(doElem|if $p:doIfProp then $t else $e) => pure none\n  | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do\n    let mut e      := e?.getD (\u2190 `(doSeq|pure PUnit.unit))\n    let mut eIsSeq := true\n    for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do\n      e \u2190 if eIsSeq then pure e else `(doSeq|$e:doElem)\n      e \u2190 withRef cond <| match cond with\n        | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)\n        | `(doIfCond|let $pat \u2190 $d)  => `(doElem| match%$i \u2190 $d    with | $pat:term => $t | _ => $e)\n        | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)\n        | _                          => `(doElem| if%$i $(Syntax.missing) then $t else $e)\n      eIsSeq := false\n    return some e\n  | _ => pure none\n\nstructure DoIfView where\n  ref        : Syntax\n  optIdent   : Syntax\n  cond       : Syntax\n  thenBranch : Syntax\n  elseBranch : Syntax\n\n/- This method assumes `expandDoIf?` is not applicable. -/\nprivate def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do\n  pure {\n    ref        := doIf,\n    optIdent   := doIf[1][0],\n    cond       := doIf[1][1],\n    thenBranch := doIf[3],\n    elseBranch := doIf[5][1]\n  }\n\n/-\nWe use `MProd` instead of `Prod` to group values when expanding the\n`do` notation. `MProd` is a universe monomorphic product.\nThe motivation is to generate simpler universe constraints in code\nthat was not written by the user.\nNote that we are not restricting the macro power since the\n`Bind.bind` combinator already forces values computed by monadic\nactions to be in the same universe.\n-/\nprivate def mkTuple (elems : Array Syntax) : MacroM Syntax := do\n  if elems.size == 0 then\n    mkUnit\n  else if elems.size == 1 then\n    pure elems[0]\n  else\n    (elems.extract 0 (elems.size - 1)).foldrM\n      (fun elem tuple => ``(MProd.mk $elem $tuple))\n      (elems.back)\n\n/- Return `some action` if `doElem` is a `doExpr <action>`-/\ndef isDoExpr? (doElem : Syntax) : Option Syntax :=\n  if doElem.getKind == ``Lean.Parser.Term.doExpr then\n    some doElem[0]\n  else\n    none\n\n/--\n  Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term\n  ```\n  let a_1     := x.1\n  let x       := x.2\n  let a_2     := x.1\n  let x       := x.2\n  ...\n  let a_n     := x.1\n  let a_{n+1} := x.2\n  body\n  ```\n  Special cases\n  - `uvars := #[]` => `body`\n  - `uvars := #[a]` => `let a := x; body`\n\n\n  We use this method when expanding the `for-in` notation.\n-/\nprivate def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n  if uvars.size == 0 then\n    return body\n  else if uvars.size == 1 then\n    `(let $(\u2190 mkIdentFromRef uvars[0]):ident := $x; $body)\n  else\n    destruct uvars.toList x body\nwhere\n  destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do\n    match as with\n      | [a, b]  => `(let $(\u2190 mkIdentFromRef a):ident := $x.1; let $(\u2190 mkIdentFromRef b):ident := $x.2; $body)\n      | a :: as => withFreshMacroScope do\n        let rest \u2190 destruct as (\u2190 `(x)) body\n        `(let $(\u2190 mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)\n      | _ => unreachable!\n\n/-\nThe procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.\nWe use this method to convert\n1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of\n   `CodeBlock` never contains `break` nor `continue`. Moreover, the collection\n   of updated variables is not packed into the result.\n   Thus, we have two kinds of exit points\n     - `Code.action e` which is converted into `e`\n     - `Code.return _ e` which is converted into `pure e`\n\n   We use `Kind.regular` for this case.\n\n2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate\n   a `Syntax` term representing a function for the `xs.forIn` combinator.\n\n   a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term\n      has type `m (ForInStep (Option \u03b1 \u00d7 \u03c3))`, where `a : \u03b1`, and the `\u03c3` is the type\n      of the tuple of variables reassigned by `b`.\n      We use `Kind.forInWithReturn` for this case\n\n   b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated\n      `Syntax` term has type `m (ForInStep \u03c3)`.\n      We use `Kind.forIn` for this case.\n\n3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).\n\n   The generated `Syntax` term for `c` must inform whether `c` \"exited\" using `Code.action`, `Code.return`,\n   `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.\n   For example, the auxiliary type `DoResultPBC \u03b1 \u03c3` is used for a code block that exits with `Code.action`,\n   **and** `Code.break`/`Code.continue`, `\u03b1` is the type of values produced by the exit `action`, and\n   `\u03c3` is the type of the tuple of reassigned variables.\n   The type `DoResult \u03b1 \u03b2 \u03c3` is usedf for code blocks that exit with\n   `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `\u03b2` is the type of the returned values.\n   We don't use `DoResult \u03b1 \u03b2 \u03c3` for all cases because:\n\n      a) The elaborator would not be able to infer all type parameters without extra annotations. For example,\n         if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `\u03b2`.\n\n      b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),\n         but we don't want to consider \"unreachable\" cases.\n\n   We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.\n\n   When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,\n   and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.\n\n   - `a`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n\n   - `r`: `Kind.regular`, type `m (\u03b1 \u00d7 \u03c3)`\n           Note that the code that pattern matches on the result will behave differently in this case.\n           It produces `return a` for this case, and `pure a` for the previous one.\n\n   - `b/c`: `Kind.nestedBC`, type `m (DoResultBC \u03c3)`\n\n   - `a` and `r`:   `Kind.nestedPR`, type `m (DoResultPR \u03b1 \u03b2 \u03c3)`\n\n   - `a` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n\n   - `r` and `bc`:  `Kind.nestedSBC`, type `m (DoResultSBC \u03b1 \u03c3)`\n         Again the code that pattern matches on the result will behave differently in this case and\n         the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for\n         this case, and `pure a` for the previous case.\n\n   - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC \u03b1 \u03b2 \u03c3)`\n\nHere is the recipe for adding new combinators with nested `do`s.\nExample: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m \u03b1 \u2192 m \u03b1`\n1- Convert `doSeq` into `codeBlock : CodeBlock`\n2- Create term `term` using `mkNestedTerm code m uvars a r bc` where\n   `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,\n   `m` is a `Syntax` representing the Monad, and\n   `a` is true if `code` contains `Code.action _`,\n   `r` is true if `code` contains `Code.return _ _`,\n   `bc` is true if `code` contains `Code.break _` or `Code.continue _`.\n\n   Remark: for combinators such as `repeat` that take a single `doSeq`, all\n   arguments, but `m`, are extracted from `codeBlock`.\n3- Create the term `repeat $term`\n4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`\n\n-/\nnamespace ToTerm\n\ninductive Kind where\n  | regular\n  | forIn\n  | forInWithReturn\n  | nestedBC\n  | nestedPR\n  | nestedSBC\n  | nestedPRBC\n\ninstance : Inhabited Kind := \u27e8Kind.regular\u27e9\n\ndef Kind.isRegular : Kind \u2192 Bool\n  | Kind.regular => true\n  | _            => false\n\nstructure Context where\n  m     : Syntax -- Syntax to reference the monad associated with the do notation.\n  uvars : Array Name\n  kind  : Kind\n\nabbrev M := ReaderT Context MacroM\n\ndef mkUVarTuple : M Syntax := do\n  let ctx \u2190 read\n  let uvarIdents \u2190 ctx.uvars.mapM mkIdentFromRef\n  mkTuple uvarIdents\n\ndef returnToTerm (val : Syntax) : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Pure.pure (DoResultPR.\u00abreturn\u00bb $val $u))\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abpureReturn\u00bb $val $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abreturn\u00bb $val $u))\n\ndef continueToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abcontinue\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abcontinue\u00bb $u))\n\ndef breakToTerm : M Syntax := do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => unreachable!\n  | Kind.forIn           => ``(Pure.pure (ForInStep.done $u))\n  | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))\n  | Kind.nestedBC        => ``(Pure.pure (DoResultBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPR        => unreachable!\n  | Kind.nestedSBC       => ``(Pure.pure (DoResultSBC.\u00abbreak\u00bb $u))\n  | Kind.nestedPRBC      => ``(Pure.pure (DoResultPRBC.\u00abbreak\u00bb $u))\n\ndef actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  let ctx \u2190 read\n  let u \u2190 mkUVarTuple\n  match ctx.kind with\n  | Kind.regular         => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))\n  | Kind.forIn           => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))\n  | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))\n  | Kind.nestedBC        => unreachable!\n  | Kind.nestedPR        => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.\u00abpure\u00bb y $u)))\n  | Kind.nestedSBC       => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.\u00abpureReturn\u00bb y $u)))\n  | Kind.nestedPRBC      => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.\u00abpure\u00bb y $u)))\n\ndef seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do\n  if action.getKind == ``Lean.Parser.Term.doDbgTrace then\n    let msg := action[1]\n    `(dbg_trace $msg; $k)\n  else if action.getKind == ``Lean.Parser.Term.doAssert then\n    let cond := action[1]\n    `(assert! $cond; $k)\n  else\n    let action \u2190 withRef action ``(($action : $((\u2190read).m) PUnit))\n    ``(Bind.bind $action (fun (_ : PUnit) => $k))\n\ndef declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do\n  let kind := decl.getKind\n  if kind == ``Lean.Parser.Term.doLet then\n    let letDecl := decl[2]\n    `(let $letDecl:letDecl; $k)\n  else if kind == ``Lean.Parser.Term.doLetRec then\n    let letRecToken := decl[0]\n    let letRecDecls := decl[1]\n    pure $ mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]\n  else if kind == ``Lean.Parser.Term.doLetArrow then\n    let arg := decl[2]\n    let ref := arg\n    if arg.getKind == ``Lean.Parser.Term.doIdDecl then\n      let id     := arg[0]\n      let type   := expandOptType id arg[1]\n      let doElem := arg[3]\n      -- `doElem` must be a `doExpr action`. See `doLetArrowToCode`\n      match isDoExpr? doElem with\n      | some action =>\n        let action \u2190 withRef action `(($action : $((\u2190 read).m) $type))\n        ``(Bind.bind $action (fun ($id:ident : $type) => $k))\n      | none        => Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n    else\n      Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n  else if kind == ``Lean.Parser.Term.doHave then\n    -- The `have` term is of the form  `\"have \" >> haveDecl >> optSemicolon termParser`\n    let args := decl.getArgs\n    let args := args ++ #[mkNullNode /- optional ';' -/, k]\n    pure $ mkNode `Lean.Parser.Term.\u00abhave\u00bb args\n  else\n    Macro.throwErrorAt decl \"unexpected kind of 'do' declaration\"\n\ndef reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do\n  let kind := reassign.getKind\n  if kind == ``Lean.Parser.Term.doReassign then\n    -- doReassign := leading_parser (letIdDecl <|> letPatDecl)\n    let arg := reassign[0]\n    if arg.getKind == ``Lean.Parser.Term.letIdDecl then\n      -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >>  \" := \" >> termParser\n      let x   := arg[0]\n      let val := arg[4]\n      let newVal \u2190 `(ensure_type_of% $x $(quote \"invalid reassignment, value\") $val)\n      let arg := arg.setArg 4 newVal\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n    else\n      -- TODO: ensure the types did not change\n      let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]\n      `(let $letDecl:letDecl; $k)\n  else\n    -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode\n    Macro.throwErrorAt reassign \"unexpected kind of 'do' reassignment\"\n\ndef mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do\n  if optIdent.isNone then\n    ``(if $cond then $thenBranch else $elseBranch)\n  else\n    let h := optIdent[0]\n    ``(if $h:ident : $cond then $thenBranch else $elseBranch)\n\ndef mkJoinPoint (j : Name) (ps : Array (Name \u00d7 Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do\n  let pTypes \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => do if useTypeOf then `(type_of% $(\u2190 mkIdentFromRef id)) else `(_)\n  let ps     \u2190 ps.mapM fun \u27e8id, useTypeOf\u27e9 => mkIdentFromRef id\n  /-\n  We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.\n  By elaborating `$k` first, we \"learn\" more about `$body`'s type.\n  For example, consider the following example `do` expression\n  ```\n  def f (x : Nat) : IO Unit := do\n  if x > 0 then\n    IO.println \"x is not zero\" -- Error is here\n  IO.mkRef true\n  ```\n  it is expanded into\n  ```\n  def f (x : Nat) : IO Unit := do\n  let jp (u : Unit) : IO _ :=\n    IO.mkRef true;\n  if x > 0 then\n    IO.println \"not zero\"\n    jp ()\n  else\n    jp ()\n  ```\n  If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit \u2192 IO (IO.Ref Bool)`.\n  Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit \u2192 IO Unit`.\n  Then, we get the expected type mismatch error at `IO.mkRef true`. -/\n  `(let_delayed $(\u2190 mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((\u2190 read).m) _ := $body; $k)\n\ndef mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=\n  Syntax.mkApp (mkIdentFrom ref j) args\n\npartial def toTerm : Code \u2192 M Syntax\n  | Code.\u00abreturn\u00bb ref val   => withRef ref <| returnToTerm val\n  | Code.\u00abcontinue\u00bb ref     => withRef ref continueToTerm\n  | Code.\u00abbreak\u00bb ref        => withRef ref breakToTerm\n  | Code.action e           => actionTerminalToTerm e\n  | Code.joinpoint j ps b k => do mkJoinPoint j ps (\u2190 toTerm b) (\u2190 toTerm k)\n  | Code.jmp ref j args     => pure $ mkJmp ref j args\n  | Code.decl _ stx k       => do declToTerm stx (\u2190 toTerm k)\n  | Code.reassign _ stx k   => do reassignToTerm stx (\u2190 toTerm k)\n  | Code.seq stx k          => do seqToTerm stx (\u2190 toTerm k)\n  | Code.ite ref _ o c t e  => withRef ref <| do mkIte o c (\u2190 toTerm t) (\u2190 toTerm e)\n  | Code.\u00abmatch\u00bb ref genParam discrs optType alts => do\n    let mut termAlts := #[]\n    for alt in alts do\n      let rhs \u2190 toTerm alt.rhs\n      let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref \"|\", alt.patterns, mkAtomFrom alt.ref \"=>\", rhs]\n      termAlts := termAlts.push termAlt\n    let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]\n    pure $ mkNode `Lean.Parser.Term.\u00abmatch\u00bb #[mkAtomFrom ref \"match\", genParam, discrs, optType, mkAtomFrom ref \"with\", termMatchAlts]\n\ndef run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do\n  let term \u2190 toTerm code { m := m, kind := kind, uvars := uvars }\n  pure term\n\n/- Given\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   generate Kind. See comment at the beginning of the `ToTerm` namespace. -/\ndef mkNestedKind (a r bc : Bool) : Kind :=\n  match a, r, bc with\n  | true,  false, false => Kind.regular\n  | false, true,  false => Kind.regular\n  | false, false, true  => Kind.nestedBC\n  | true,  true,  false => Kind.nestedPR\n  | true,  false, true  => Kind.nestedSBC\n  | false, true,  true  => Kind.nestedSBC\n  | true,  true,  true  => Kind.nestedPRBC\n  | false, false, false => unreachable!\n\ndef mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do\n  ToTerm.run code m uvars (mkNestedKind a r bc)\n\n/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.\n   See comment at the beginning of the `ToTerm` namespace.\n\n   - `a` is true if the code block has a `Code.action _` exit point\n   - `r` is true if the code block has a `Code.return _ _` exit point\n   - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point\n\n   The result is a sequence of `doElem` -/\ndef matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do\n  let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)\n  let u \u2190 mkTuple (\u2190 uvars.mapM mkIdentFromRef)\n  match a, r, bc with\n  | true, false, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do $term:term))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; pure r.1))\n  | false, true, false =>\n    if uvars.isEmpty then\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; return r))\n    else\n      return toDoElems (\u2190 `(do let r \u2190 $term:term; $u:term := r.2; return r.1))\n  | false, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, false => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPR.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPR.\u00abreturn\u00bb b u => $u:term := u; return b)\n  | true, false, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; pure a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultSBC.\u00abpureReturn\u00bb a u => $u:term := u; return a\n         | DoResultSBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultSBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | true, true, true => toDoElems <$>\n    `(do let r \u2190 $term:term;\n         match r with\n         | DoResultPRBC.\u00abpure\u00bb a u => $u:term := u; pure a\n         | DoResultPRBC.\u00abreturn\u00bb a u => $u:term := u; return a\n         | DoResultPRBC.\u00abbreak\u00bb u => $u:term := u; break\n         | DoResultPRBC.\u00abcontinue\u00bb u => $u:term := u; continue)\n  | false, false, false => unreachable!\n\nend ToTerm\n\ndef isMutableLet (doElem : Syntax) : Bool :=\n  let kind := doElem.getKind\n  (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)\n  &&\n  !doElem[1].isNone\n\nnamespace ToCodeBlock\n\nstructure Context where\n  ref         : Syntax\n  m           : Syntax -- Syntax representing the monad associated with the do notation.\n  mutableVars : NameSet := {}\n  insideFor   : Bool := false\n\nabbrev M := ReaderT Context TermElabM\n\ndef withNewMutableVars {\u03b1} (newVars : Array Name) (mutable : Bool) (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x\n\ndef checkReassignable (xs : Array Name) : M Unit := do\n  let throwInvalidReassignment (x : Name) : M Unit :=\n    throwError \"'{x.simpMacroScopes}' cannot be reassigned\"\n  let ctx \u2190 read\n  for x in xs do\n    unless ctx.mutableVars.contains x do\n      throwInvalidReassignment x\n\ndef checkNotShadowingMutable (xs : Array Name) : M Unit := do\n  let throwInvalidShadowing (x : Name) : M Unit :=\n    throwError \"mutable variable '{x.simpMacroScopes}' cannot be shadowed\"\n  let ctx \u2190 read\n  for x in xs do\n    if ctx.mutableVars.contains x then\n      throwInvalidShadowing x\n\ndef withFor {\u03b1} (x : M \u03b1) : M \u03b1 :=\n  withReader (fun ctx => { ctx with insideFor := true }) x\n\nstructure ToForInTermResult where\n  uvars      : Array Name\n  term       : Syntax\n\ndef mkForInBody  (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do\n  let ctx \u2190 read\n  let uvars := forInBody.uvars\n  let uvars := nameSetToArray uvars\n  let term \u2190 liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)\n  pure \u27e8uvars, term\u27e9\n\ndef ensureInsideFor : M Unit :=\n  unless (\u2190 read).insideFor do\n    throwError \"invalid 'do' element, it must be inside 'for'\"\n\ndef ensureEOS (doElems : List Syntax) : M Unit :=\n  unless doElems.isEmpty do\n    throwError \"must be last element in a 'do' sequence\"\n\nprivate partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax \u2192 StateT (List Syntax) M Syntax\n  | stx@(Syntax.node i k args) =>\n    if liftMethodDelimiter k then\n      return stx\n    else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do\n      if inBinder then\n        throwErrorAt stx \"cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`\"\n      let term := args[1]\n      let term \u2190 expandLiftMethodAux inQuot inBinder term\n      let auxDoElem \u2190 `(doElem| let a \u2190 $term:term)\n      modify fun s => s ++ [auxDoElem]\n      `(a)\n    else do\n      let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot\n      let inBinder   := inBinder || (!inQuot && liftMethodForbiddenBinder stx)\n      let args \u2190 args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)\n      return Syntax.node i k args\n  | stx => pure stx\n\ndef expandLiftMethod (doElem : Syntax) : M (List Syntax \u00d7 Syntax) := do\n  if !hasLiftMethod doElem then\n    pure ([], doElem)\n  else\n    let (doElem, doElemsNew) \u2190 (expandLiftMethodAux false false doElem).run []\n    pure (doElemsNew, doElem)\n\ndef checkLetArrowRHS (doElem : Syntax) : M Unit := do\n  let kind := doElem.getKind\n  if kind == ``Lean.Parser.Term.doLetArrow ||\n     kind == ``Lean.Parser.Term.doLet ||\n     kind == ``Lean.Parser.Term.doLetRec ||\n     kind == ``Lean.Parser.Term.doHave ||\n     kind == ``Lean.Parser.Term.doReassign ||\n     kind == ``Lean.Parser.Term.doReassignArrow then\n    throwErrorAt doElem \"invalid kind of value '{kind}' in an assignment\"\n\n/- Generate `CodeBlock` for `doReturn` which is of the form\n   ```\n   \"return \" >> optional termParser\n   ```\n   `doElems` is only used for sanity checking. -/\ndef doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do\n  ensureEOS doElems\n  let argOpt := doReturn[1]\n  let arg \u2190 if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]\n  return mkReturn (\u2190 getRef) arg\n\nstructure Catch where\n  x         : Syntax\n  optType   : Syntax\n  codeBlock : CodeBlock\n\ndef getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=\n  let ws := tryCode.uvars\n  let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws\n  let ws := match finallyCode? with\n    | none   => ws\n    | some c => union c.uvars ws\n  ws\n\ndef tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code \u2192 Bool) : Bool :=\n  p tryCode.code ||\n  catches.any (fun \u00abcatch\u00bb => p \u00abcatch\u00bb.codeBlock.code) ||\n  match finallyCode? with\n  | none => false\n  | some finallyCode => p finallyCode.code\n\nmutual\n  /- \"Concatenate\" `c` with `doSeqToCode doElems` -/\n  partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=\n    match doElems with\n    | [] => pure c\n    | nextDoElem :: _  => do\n      let k \u2190 doSeqToCode doElems\n      let ref := nextDoElem\n      concat c ref none k\n\n  /- Generate `CodeBlock` for `doLetArrow; doElems`\n     `doLetArrow` is of the form\n     ```\n     \"let \" >> optional \"mut \" >> (doIdDecl <|> doPatDecl)\n     ```\n     where\n     ```\n     def doIdDecl   := leading_parser ident >> optType >> leftArrow >> doElemParser\n     def doPatDecl  := leading_parser termParser >> leftArrow >> doElemParser >> optional (\" | \" >> doElemParser)\n     ```\n  -/\n  partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref     := doLetArrow\n    let decl    := doLetArrow[2]\n    if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n      let y := decl[0].getId\n      checkNotShadowingMutable #[y]\n      let doElem := decl[3]\n      let k \u2190 withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)\n      match isDoExpr? doElem with\n      | some action => pure $ mkVarDeclCore #[y] doLetArrow k\n      | none =>\n        checkLetArrowRHS doElem\n        let c \u2190 doSeqToCode [doElem]\n        match doElems with\n        | []       => pure c\n        | kRef::_  => concat c kRef y k\n    else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190\n          if isMutableLet doLetArrow then\n            `(do let discr \u2190 $doElem; let mut $pattern:term := discr)\n          else\n            `(do let discr \u2190 $doElem; let $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        if isMutableLet doLetArrow then\n          throwError \"'mut' is currently not supported in let-decls with 'else' case\"\n        let contSeq := mkDoSeq doElems.toArray\n        let elseSeq := mkSingletonDoSeq optElse[1]\n        let auxDo \u2190 `(do let discr \u2190 $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n    else\n      throwError \"unexpected kind of 'do' declaration\"\n\n  partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    -- \"let \" >> termParser >> \" := \" >> termParser >> checkColGt >> \" | \" >> doElemParser\n    let pattern := doLetElse[1]\n    let val     := doLetElse[3]\n    let elseSeq := mkSingletonDoSeq doLetElse[5]\n    let contSeq := mkDoSeq doElems.toArray\n    let auxDo \u2190 `(do let discr := $val; match discr with | $pattern:term => $contSeq | _ => $elseSeq)\n    doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n\n  /- Generate `CodeBlock` for `doReassignArrow; doElems`\n     `doReassignArrow` is of the form\n     ```\n     (doIdDecl <|> doPatDecl)\n     ```\n  -/\n  partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let ref  := doReassignArrow\n    let decl := doReassignArrow[0]\n    if decl.getKind == ``Lean.Parser.Term.doIdDecl then\n      let doElem := decl[3]\n      let y      := decl[0]\n      let auxDo \u2190 `(do let r \u2190 $doElem; $y:ident := r)\n      doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n    else if decl.getKind == ``Lean.Parser.Term.doPatDecl then\n      let pattern := decl[0]\n      let doElem  := decl[2]\n      let optElse := decl[3]\n      if optElse.isNone then withFreshMacroScope do\n        let auxDo \u2190 `(do let discr \u2190 $doElem; $pattern:term := discr)\n        doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n      else\n        throwError \"reassignment with `|` (i.e., \\\"else clause\\\") is not currently supported\"\n    else\n      throwError \"unexpected kind of 'do' reassignment\"\n\n  /- Generate `CodeBlock` for `doIf; doElems`\n     `doIf` is of the form\n     ```\n     \"if \" >> optIdent >> termParser >> \" then \" >> doSeq\n      >> many (group (try (group (\" else \" >> \" if \")) >> optIdent >> termParser >> \" then \" >> doSeq))\n      >> optional (\" else \" >> doSeq)\n     ```  -/\n  partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let view \u2190 liftMacroM $ mkDoIfView doIf\n    let thenBranch \u2190 doSeqToCode (getDoSeqElems view.thenBranch)\n    let elseBranch \u2190 doSeqToCode (getDoSeqElems view.elseBranch)\n    let ite \u2190 mkIte view.ref view.optIdent view.cond thenBranch elseBranch\n    concatWith ite doElems\n\n  /- Generate `CodeBlock` for `doUnless; doElems`\n     `doUnless` is of the form\n     ```\n     \"unless \" >> termParser >> \"do \" >> doSeq\n     ```  -/\n  partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do\n    let ref   := doUnless\n    let cond  := doUnless[1]\n    let doSeq := doUnless[3]\n    let body \u2190 doSeqToCode (getDoSeqElems doSeq)\n    let unlessCode \u2190 liftMacroM <| mkUnless cond body\n    concatWith unlessCode doElems\n\n  /- Generate `CodeBlock` for `doFor; doElems`\n     `doFor` is of the form\n     ```\n     def doForDecl := leading_parser termParser >> \" in \" >> withForbidden \"do\" termParser\n     def doFor := leading_parser \"for \" >> sepBy1 doForDecl \", \" >> \"do \" >> doSeq\n     ```\n  -/\n  partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do\n    let doForDecls := doFor[1].getSepArgs\n    if doForDecls.size > 1 then\n      /-\n        Expand\n        ```\n        for x in xs, y in ys do\n          body\n        ```\n        into\n        ```\n        let s := toStream ys\n        for x in xs do\n          match Stream.next? s with\n          | none => break\n          | some (y, s') =>\n            s := s'\n            body\n        ```\n      -/\n      -- Extract second element\n      let doForDecl := doForDecls[1]\n      let y  := doForDecl[0]\n      let ys := doForDecl[2]\n      let doForDecls := doForDecls.eraseIdx 1\n      let body := doFor[3]\n      withFreshMacroScope do\n        let toStreamFn \u2190 withRef ys ``(toStream)\n        let auxDo \u2190\n          `(do let mut s := $toStreamFn:ident $ys\n               for $doForDecls:doForDecl,* do\n                 match Stream.next? s with\n                 | none => break\n                 | some ($y, s') =>\n                   s := s'\n                   do $body)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n    else withRef doFor do\n      let x         := doForDecls[0][0]\n      withRef x <| checkNotShadowingMutable (\u2190 getPatternVarsEx x)\n      let xs        := doForDecls[0][2]\n      let forElems  := getDoSeqElems doFor[3]\n      let forInBodyCodeBlock \u2190 withFor (doSeqToCode forElems)\n      let \u27e8uvars, forInBody\u27e9 \u2190 mkForInBody x forInBodyCodeBlock\n      let uvarsTuple \u2190 liftMacroM do mkTuple (\u2190 uvars.mapM mkIdentFromRef)\n      if hasReturn forInBodyCodeBlock.code then\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 `(for_in% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)\n        let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                         $uvarsTuple:term := r.2;\n                         match r.1 with\n                         | none => Pure.pure (ensure_expected_type% \"type mismatch, 'for'\" PUnit.unit)\n                         | some a => return ensure_expected_type% \"type mismatch, 'for'\" a)\n        doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)\n      else\n        let forInBody \u2190 liftMacroM <| destructTuple uvars (\u2190 `(r)) forInBody\n        let forInTerm \u2190 `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)\n        if doElems.isEmpty then\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term;\n                           $uvarsTuple:term := r;\n                           Pure.pure (ensure_expected_type% \"type mismatch, 'for'\" PUnit.unit))\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo)\n        else\n          let auxDo \u2190 `(do let r \u2190 $forInTerm:term; $uvarsTuple:term := r)\n          doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems\n\n  /-- Generate `CodeBlock` for `doMatch; doElems` -/\n  partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref       := doMatch\n    let genParam  := doMatch[1]\n    let discrs    := doMatch[2]\n    let optType   := doMatch[3]\n    let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`\n    let alts \u2190  matchAlts.mapM fun matchAlt => do\n      let patterns := matchAlt[1]\n      let vars \u2190 getPatternsVarsEx patterns.getSepArgs\n      withRef patterns <| checkNotShadowingMutable vars\n      let rhs  := matchAlt[3]\n      let rhs \u2190 doSeqToCode (getDoSeqElems rhs)\n      pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }\n    let matchCode \u2190 mkMatch ref genParam discrs optType alts\n    concatWith matchCode doElems\n\n  /--\n    Generate `CodeBlock` for `doTry; doElems`\n    ```\n    def doTry := leading_parser \"try \" >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally\n    def doCatch      := leading_parser \"catch \" >> binderIdent >> optional (\":\" >> termParser) >> darrow >> doSeq\n    def doCatchMatch := leading_parser \"catch \" >> doMatchAlts\n    def doFinally    := leading_parser \"finally \" >> doSeq\n    ```\n  -/\n  partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do\n    let ref := doTry\n    let tryCode \u2190 doSeqToCode (getDoSeqElems doTry[1])\n    let optFinally := doTry[3]\n    let catches \u2190 doTry[2].getArgs.mapM fun catchStx => do\n      if catchStx.getKind == ``Lean.Parser.Term.doCatch then\n        let x       := catchStx[1]\n        if x.isIdent then\n          withRef x <| checkNotShadowingMutable #[x.getId]\n        let optType := catchStx[2]\n        let c \u2190 doSeqToCode (getDoSeqElems catchStx[4])\n        pure { x := x, optType := optType, codeBlock := c : Catch }\n      else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then\n        let matchAlts := catchStx[1]\n        let x \u2190 `(ex)\n        let auxDo \u2190 `(do match ex with $matchAlts)\n        let c \u2190 doSeqToCode (getDoSeqElems (getDoSeq auxDo))\n        pure { x := x, codeBlock := c, optType := mkNullNode : Catch }\n      else\n        throwError \"unexpected kind of 'catch'\"\n    let finallyCode? \u2190 if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])\n    if catches.isEmpty && finallyCode?.isNone then\n      throwError \"invalid 'try', it must have a 'catch' or 'finally'\"\n    let ctx \u2190 read\n    let ws    := getTryCatchUpdatedVars tryCode catches finallyCode?\n    let uvars := nameSetToArray ws\n    let a     := tryCatchPred tryCode catches finallyCode? hasTerminalAction\n    let r     := tryCatchPred tryCode catches finallyCode? hasReturn\n    let bc    := tryCatchPred tryCode catches finallyCode? hasBreakContinue\n    let toTerm (codeBlock : CodeBlock) : M Syntax := do\n      let codeBlock \u2190 liftM $ extendUpdatedVars codeBlock ws\n      liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc\n    let term \u2190 toTerm tryCode\n    let term \u2190 catches.foldlM\n      (fun term \u00abcatch\u00bb => do\n        let catchTerm \u2190 toTerm \u00abcatch\u00bb.codeBlock\n        if catch.optType.isNone then\n          ``(MonadExcept.tryCatch $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm))\n        else\n          let type := \u00abcatch\u00bb.optType[1]\n          ``(tryCatchThe $type $term (fun $(\u00abcatch\u00bb.x):ident => $catchTerm)))\n      term\n    let term \u2190 match finallyCode? with\n      | none             => pure term\n      | some finallyCode => withRef optFinally do\n        unless finallyCode.uvars.isEmpty do\n          throwError \"'finally' currently does not support reassignments\"\n        if hasBreakContinueReturn finallyCode.code then\n          throwError \"'finally' currently does 'return', 'break', nor 'continue'\"\n        let finallyTerm \u2190 liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular\n        ``(tryFinally $term $finallyTerm)\n    let doElemsNew \u2190 liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc\n    doSeqToCode (doElemsNew ++ doElems)\n\n  partial def doSeqToCode : List Syntax \u2192 M CodeBlock\n    | [] => do liftMacroM mkPureUnitAction\n    | doElem::doElems => withIncRecDepth <| withRef doElem do\n      checkMaxHeartbeats \"'do'-expander\"\n      match (\u2190 liftMacroM <| expandMacro? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n      match (\u2190 liftMacroM <| expandDoIf? doElem) with\n      | some doElem => doSeqToCode (doElem::doElems)\n      | none =>\n        let (liftedDoElems, doElem) \u2190 expandLiftMethod doElem\n        if !liftedDoElems.isEmpty then\n          doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)\n        else\n          let ref := doElem\n          let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems\n          let k := doElem.getKind\n          if k == ``Lean.Parser.Term.doLet then\n            let vars \u2190 getDoLetVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doHave then\n            let vars \u2190 getDoHaveVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doLetRec then\n            let vars \u2190 getDoLetRecVars doElem\n            checkNotShadowingMutable vars\n            mkVarDeclCore vars doElem <$> (doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doReassign then\n            let vars \u2190 getDoReassignVars doElem\n            checkReassignable vars\n            let k \u2190 doSeqToCode doElems\n            mkReassignCore vars doElem k\n          else if k == ``Lean.Parser.Term.doLetArrow then\n            doLetArrowToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doLetElse then\n            doLetElseToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doReassignArrow then\n            doReassignArrowToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doIf then\n            doIfToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doUnless then\n            doUnlessToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do\n            doForToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doMatch then\n            doMatchToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doTry then\n            doTryToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doBreak then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkBreak ref\n          else if k == ``Lean.Parser.Term.doContinue then\n            ensureInsideFor\n            ensureEOS doElems\n            return mkContinue ref\n          else if k == ``Lean.Parser.Term.doReturn then\n            doReturnToCode doElem doElems\n          else if k == ``Lean.Parser.Term.doDbgTrace then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doAssert then\n            return mkSeq doElem (\u2190 doSeqToCode doElems)\n          else if k == ``Lean.Parser.Term.doNested then\n            let nestedDoSeq := doElem[1]\n            doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)\n          else if k == ``Lean.Parser.Term.doExpr then\n            let term := doElem[0]\n            if doElems.isEmpty then\n              return mkTerminalAction term\n            else\n              return mkSeq term (\u2190 doSeqToCode doElems)\n          else\n            throwError \"unexpected do-element of kind {doElem.getKind}:\\n{doElem}\"\nend\n\ndef run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=\n  (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m }\n\nend ToCodeBlock\n\n/- Create a synthetic metavariable `?m` and assign `m` to it.\n   We use `?m` to refer to `m` when expanding the `do` notation. -/\nprivate def mkMonadAlias (m : Expr) : TermElabM Syntax := do\n  let result \u2190 `(?m)\n  let mType \u2190 inferType m\n  let mvar \u2190 elabTerm result mType\n  assignExprMVar mvar.mvarId! m\n  pure result\n\n@[builtinTermElab \u00abdo\u00bb] def elabDo : TermElab := fun stx expectedType? => do\n  tryPostponeIfNoneOrMVar expectedType?\n  let bindInfo \u2190 extractBind expectedType?\n  let m \u2190 mkMonadAlias bindInfo.m\n  let codeBlock \u2190 ToCodeBlock.run stx m\n  let stxNew \u2190 liftMacroM $ ToTerm.run codeBlock.code m\n  trace[Elab.do] stxNew\n  withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType\n\nend Do\n\nbuiltin_initialize registerTraceClass `Elab.do\n\nprivate def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do\n  let stx := stx.setKind newKind\n  withRef stx `(do $stx:doElem)\n\n@[builtinMacro Lean.Parser.Term.termFor]\ndef expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor\n\n@[builtinMacro Lean.Parser.Term.termTry]\ndef expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry\n\n@[builtinMacro Lean.Parser.Term.termUnless]\ndef expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless\n\n@[builtinMacro Lean.Parser.Term.termReturn]\ndef expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn\n\nend Lean.Elab.Term\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/Elab/Do.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.11920293140927592, "lm_q2_score": 0.024798159024422405, "lm_q1q2_score": 0.0029560132492645404}}
{"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 Exception monad transformer using CPS style.\n-/\n\ndef ExceptCpsT (\u03b5 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) := (\u03b2 : Type u) \u2192 (\u03b1 \u2192 m \u03b2) \u2192 (\u03b5 \u2192 m \u03b2) \u2192 m \u03b2\n\nnamespace ExceptCpsT\n\n@[inline] def run {\u03b5 \u03b1 : Type u} [Monad m] (x : ExceptCpsT \u03b5 m \u03b1) : m (Except \u03b5 \u03b1) :=\n  x _ (fun a => pure (Except.ok a)) (fun e => pure (Except.error e))\n\n@[inline] def runK {\u03b5 \u03b1 : Type u} (x : ExceptCpsT \u03b5 m \u03b1) (s : \u03b5) (ok : \u03b1 \u2192 m \u03b2) (error : \u03b5 \u2192 m \u03b2) : m \u03b2 :=\n  x _ ok error\n\n@[inline] def runCatch [Monad m] (x : ExceptCpsT \u03b1 m \u03b1) : m \u03b1 :=\n  x \u03b1 pure pure\n\ninstance : Monad (ExceptCpsT \u03b5 m) where\n  map f x  := fun _ k\u2081 k\u2082 => x _ (fun a => k\u2081 (f a)) k\u2082\n  pure a   := fun _ k _ => k a\n  bind x f := fun _ k\u2081 k\u2082 => x _ (fun a => f a _ k\u2081 k\u2082) k\u2082\n\ninstance : LawfulMonad (ExceptCpsT \u03c3 m) := by\n  refine' { .. } <;> intros <;> rfl\n\ninstance : MonadExceptOf \u03b5 (ExceptCpsT \u03b5 m) where\n  throw e  := fun _ _ k => k e\n  tryCatch x handle := fun _ k\u2081 k\u2082 => x _ k\u2081 (fun e => handle e _ k\u2081 k\u2082)\n\n@[inline] def lift [Monad m] (x : m \u03b1) : ExceptCpsT \u03b5 m \u03b1 :=\n  fun _ k _ => x >>= k\n\ninstance [Monad m] : MonadLift m (ExceptCpsT \u03c3 m) where\n  monadLift := ExceptCpsT.lift\n\ninstance [Inhabited \u03b5] : Inhabited (ExceptCpsT \u03b5 m \u03b1) where\n  default := fun _ k\u2081 k\u2082 => k\u2082 arbitrary\n\n@[simp] theorem run_pure [Monad m] : run (pure x : ExceptCpsT \u03b5 m \u03b1) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift {\u03b1 \u03b5 : Type u} [Monad m] (x : m \u03b1) : run (ExceptCpsT.lift x : ExceptCpsT \u03b5 m \u03b1) = (x >>= fun a => pure (Except.ok a) : m (Except \u03b5 \u03b1)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptCpsT \u03b5 m \u03b2) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptCpsT \u03b5 m \u03b2) : run (ExceptCpsT.lift x >>= f : ExceptCpsT \u03b5 m \u03b2) = x >>= fun a => run (f a) := rfl\n\n@[simp] theorem run_bind_throw [Monad m] (e : \u03b5) (f : \u03b1 \u2192 ExceptCpsT \u03b5 m \u03b2) : run (throw e >>= f : ExceptCpsT \u03b5 m \u03b2) = run (throw e) := rfl\n\n@[simp] theorem runCatch_pure [Monad m] : runCatch (pure x : ExceptCpsT \u03b1 m \u03b1) = pure x := rfl\n\n@[simp] theorem runCatch_lift {\u03b1 : Type u} [Monad m] [LawfulMonad m] (x : m \u03b1) : runCatch (ExceptCpsT.lift x : ExceptCpsT \u03b1 m \u03b1) = x := by\n  simp [runCatch, lift]\n\n@[simp] theorem runCatch_throw [Monad m] : runCatch (throw a : ExceptCpsT \u03b1 m \u03b1) = pure a := rfl\n\n@[simp] theorem runCatch_bind_lift [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptCpsT \u03b2 m \u03b2) : runCatch (ExceptCpsT.lift x >>= f : ExceptCpsT \u03b2 m \u03b2) = x >>= fun a => runCatch (f a) := rfl\n\n@[simp] theorem runCatch_bind_throw [Monad m] (e : \u03b2) (f : \u03b1 \u2192 ExceptCpsT \u03b2 m \u03b2) : runCatch (throw e >>= f : ExceptCpsT \u03b2 m \u03b2) = pure e := rfl\n\nend ExceptCpsT\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/ExceptCps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1480472055495773, "lm_q2_score": 0.019419347579476793, "lm_q1q2_score": 0.002874980142737487}}
{"text": "open Lean\nsyntax \"foo\" (ident ident)? : term\n\nvariable (x y : Option (TSyntax identKind))\nexample : MacroM Syntax := `(foo $[$x:ident $y:ident]?)\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/1124.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10230470789265303, "lm_q2_score": 0.027585284125430275, "lm_q1q2_score": 0.002822104434587983}}
{"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 Exception monad transformer using CPS style.\n-/\n\ndef ExceptCpsT (\u03b5 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) := (\u03b2 : Type u) \u2192 (\u03b1 \u2192 m \u03b2) \u2192 (\u03b5 \u2192 m \u03b2) \u2192 m \u03b2\n\nnamespace ExceptCpsT\n\n@[inline] def run {\u03b5 \u03b1 : Type u} [Monad m] (x : ExceptCpsT \u03b5 m \u03b1) : m (Except \u03b5 \u03b1) :=\n  x _ (fun a => pure (Except.ok a)) (fun e => pure (Except.error e))\n\n@[inline] def runK {\u03b5 \u03b1 : Type u} (x : ExceptCpsT \u03b5 m \u03b1) (s : \u03b5) (ok : \u03b1 \u2192 m \u03b2) (error : \u03b5 \u2192 m \u03b2) : m \u03b2 :=\n  x _ ok error\n\n@[inline] def runCatch [Monad m] (x : ExceptCpsT \u03b1 m \u03b1) : m \u03b1 :=\n  x \u03b1 pure pure\n\ninstance : Monad (ExceptCpsT \u03b5 m) where\n  map f x  := fun _ k\u2081 k\u2082 => x _ (fun a => k\u2081 (f a)) k\u2082\n  pure a   := fun _ k _ => k a\n  bind x f := fun _ k\u2081 k\u2082 => x _ (fun a => f a _ k\u2081 k\u2082) k\u2082\n\ninstance : LawfulMonad (ExceptCpsT \u03c3 m) := by\n  refine' { .. } <;> intros <;> rfl\n\ninstance : MonadExceptOf \u03b5 (ExceptCpsT \u03b5 m) where\n  throw e  := fun _ _ k => k e\n  tryCatch x handle := fun _ k\u2081 k\u2082 => x _ k\u2081 (fun e => handle e _ k\u2081 k\u2082)\n\n@[inline] def lift [Monad m] (x : m \u03b1) : ExceptCpsT \u03b5 m \u03b1 :=\n  fun _ k _ => x >>= k\n\ninstance [Monad m] : MonadLift m (ExceptCpsT \u03c3 m) where\n  monadLift := ExceptCpsT.lift\n\ninstance [Inhabited \u03b5] : Inhabited (ExceptCpsT \u03b5 m \u03b1) where\n  default := fun _ k\u2081 k\u2082 => k\u2082 default\n\n@[simp] theorem run_pure [Monad m] : run (pure x : ExceptCpsT \u03b5 m \u03b1) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift {\u03b1 \u03b5 : Type u} [Monad m] (x : m \u03b1) : run (ExceptCpsT.lift x : ExceptCpsT \u03b5 m \u03b1) = (x >>= fun a => pure (Except.ok a) : m (Except \u03b5 \u03b1)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptCpsT \u03b5 m \u03b2) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptCpsT \u03b5 m \u03b2) : run (ExceptCpsT.lift x >>= f : ExceptCpsT \u03b5 m \u03b2) = x >>= fun a => run (f a) := rfl\n\n@[simp] theorem run_bind_throw [Monad m] (e : \u03b5) (f : \u03b1 \u2192 ExceptCpsT \u03b5 m \u03b2) : run (throw e >>= f : ExceptCpsT \u03b5 m \u03b2) = run (throw e) := rfl\n\n@[simp] theorem runCatch_pure [Monad m] : runCatch (pure x : ExceptCpsT \u03b1 m \u03b1) = pure x := rfl\n\n@[simp] theorem runCatch_lift {\u03b1 : Type u} [Monad m] [LawfulMonad m] (x : m \u03b1) : runCatch (ExceptCpsT.lift x : ExceptCpsT \u03b1 m \u03b1) = x := by\n  simp [runCatch, lift]\n\n@[simp] theorem runCatch_throw [Monad m] : runCatch (throw a : ExceptCpsT \u03b1 m \u03b1) = pure a := rfl\n\n@[simp] theorem runCatch_bind_lift [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptCpsT \u03b2 m \u03b2) : runCatch (ExceptCpsT.lift x >>= f : ExceptCpsT \u03b2 m \u03b2) = x >>= fun a => runCatch (f a) := rfl\n\n@[simp] theorem runCatch_bind_throw [Monad m] (e : \u03b2) (f : \u03b1 \u2192 ExceptCpsT \u03b2 m \u03b2) : runCatch (throw e >>= f : ExceptCpsT \u03b2 m \u03b2) = pure e := rfl\n\nend ExceptCpsT\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/Control/ExceptCps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1460872396128689, "lm_q2_score": 0.019124037868971218, "lm_q1q2_score": 0.0027937779025299773}}
{"text": "example (id : Lean.Syntax.Ident) : Lean.Name := id.\n                                                 --^ textDocument/completion\nexample (id : Lean.TSyntax `ident) : Lean.Name := id.\n                                                   --^ textDocument/completion\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/1265.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816085449158, "lm_q2_score": 0.03567854767346022, "lm_q1q2_score": 0.0027857153843030735}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Daniel Selsam\n-/\nimport Lean.Data.RBMap\nimport Lean.Meta.SynthInstance\nimport Lean.Util.FindMVar\nimport Lean.Util.FindLevelMVar\nimport Lean.Util.CollectLevelParams\nimport Lean.Util.ReplaceLevel\nimport Lean.PrettyPrinter.Delaborator.Options\nimport Lean.PrettyPrinter.Delaborator.SubExpr\nimport Lean.Elab.Config\n\n/-!\nThe top-down analyzer is an optional preprocessor to the delaborator that aims\nto determine the minimal annotations necessary to ensure that the delaborated\nexpression can be re-elaborated correctly. Currently, the top-down analyzer\nis neither sound nor complete: there may be edge-cases in which the expression\ncan still not be re-elaborated correctly, and it may also add many annotations\nthat are not strictly necessary.\n-/\n\nnamespace Lean\nopen Meta SubExpr\n\nregister_builtin_option pp.analyze : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) determine annotations sufficient to ensure round-tripping\"\n}\n\nregister_builtin_option pp.analyze.checkInstances : Bool := {\n  -- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not\n  -- include the `LocalInstances`, so this will be very over-aggressive in inserting instances\n  -- that would otherwise be easy to synthesize. We may consider threading the instances in the future,\n  -- or at least tracking a bool for whether the instances have been lost.\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) confirm that instances can be re-synthesized\"\n}\n\nregister_builtin_option pp.analyze.typeAscriptions : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) add type ascriptions when deemed necessary\"\n}\n\nregister_builtin_option pp.analyze.trustSubst : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' applications that can delab to \u25b8 are 'regular'\"\n}\n\nregister_builtin_option pp.analyze.trustOfNat : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up\"\n}\n\nregister_builtin_option pp.analyze.trustOfScientific : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up\"\n}\n\n-- TODO: this is an arbitrary special case of a more general principle.\nregister_builtin_option pp.analyze.trustSubtypeMk : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) assume the implicit arguments of Subtype.mk can be inferred\"\n}\n\nregister_builtin_option pp.analyze.trustId : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred\"\n}\n\nregister_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type\"\n}\n\nregister_builtin_option pp.analyze.omitMax : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)\"\n}\n\nregister_builtin_option pp.analyze.knowsType : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) assume the type of the original expression is known\"\n}\n\nregister_builtin_option pp.analyze.explicitHoles : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) use `_` for explicit arguments that can be inferred\"\n}\n\ndef getPPAnalyze                            (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue\ndef getPPAnalyzeCheckInstances              (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue\ndef getPPAnalyzeTypeAscriptions             (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue\ndef getPPAnalyzeTrustSubst                  (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue\ndef getPPAnalyzeTrustOfNat                  (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue\ndef getPPAnalyzeTrustOfScientific           (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue\ndef getPPAnalyzeTrustId                     (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue\ndef getPPAnalyzeTrustSubtypeMk              (o : Options) : Bool := o.get pp.analyze.trustSubtypeMk.name pp.analyze.trustSubtypeMk.defValue\ndef getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue\ndef getPPAnalyzeOmitMax                     (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue\ndef getPPAnalyzeKnowsType                   (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue\ndef getPPAnalyzeExplicitHoles               (o : Options) : Bool := o.get pp.analyze.explicitHoles.name pp.analyze.explicitHoles.defValue\n\ndef getPPAnalysisSkip            (o : Options) : Bool := o.get `pp.analysis.skip false\ndef getPPAnalysisHole            (o : Options) : Bool := o.get `pp.analysis.hole false\ndef getPPAnalysisNamedArg        (o : Options) : Bool := o.get `pp.analysis.namedArg false\ndef getPPAnalysisLetVarType      (o : Options) : Bool := o.get `pp.analysis.letVarType false\ndef getPPAnalysisNeedsType       (o : Options) : Bool := o.get `pp.analysis.needsType false\ndef getPPAnalysisBlockImplicit   (o : Options) : Bool := o.get `pp.analysis.blockImplicit false\n\nnamespace PrettyPrinter.Delaborator\n\ndef returnsPi (motive : Expr) : MetaM Bool := do\n  lambdaTelescope motive fun _ b => return b.isForall\n\ndef isNonConstFun (motive : Expr) : MetaM Bool := do\n  match motive with\n  | Expr.lam _    _ b _ => isNonConstFun b\n  | _ => return motive.hasLooseBVars\n\ndef isSimpleHOFun (motive : Expr) : MetaM Bool :=\n  return not (\u2190 returnsPi motive) && not (\u2190 isNonConstFun motive)\n\ndef isType2Type (motive : Expr) : MetaM Bool := do\n  match \u2190 inferType motive with\n  | Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => return true\n  | _ => return false\n\ndef isFOLike (motive : Expr) : MetaM Bool := do\n  let f := motive.getAppFn\n  return f.isFVar || f.isConst\n\ndef isIdLike (arg : Expr) : Bool :=\n  -- TODO: allow `id` constant as well?\n  match arg with\n  | Expr.lam _ _ (Expr.bvar ..) .. => true\n  | _ => false\n\ndef isStructureInstance (e : Expr) : MetaM Bool := do\n  match e.isConstructorApp? (\u2190 getEnv) with\n  | some s => return isStructure (\u2190 getEnv) s.induct\n  | none   => return false\n\nnamespace TopDownAnalyze\n\npartial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  return Option.isSome <| e.findMVar? fun mvarId =>\n    match mctx.findDecl? mvarId with\n    | some mdecl => mdecl.depth == mctx.depth\n    | _ => false\n\npartial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  return Option.isSome <| e.findLevelMVar? fun mvarId =>\n    mctx.findLevelDepth? mvarId == some mctx.depth\n\nprivate def valUnknown (e : Expr) : MetaM Bool := do\n  hasMVarAtCurrDepth (\u2190 instantiateMVars e)\n\nprivate def typeUnknown (e : Expr) : MetaM Bool := do\n  valUnknown (\u2190 inferType e)\n\ndef isHBinOp (e : Expr) : Bool := Id.run do\n  -- TODO: instead of tracking these explicitly,\n  -- consider a more general solution that checks for defaultInstances\n  if e.getAppNumArgs != 6 then return false\n  let f := e.getAppFn\n  if !f.isConst then return false\n\n  -- Note: we leave out `HPow.hPow because we expect its homogeneous\n  -- version will change soon\n  let ops := #[\n    `HOr.hOr, `HXor.hXor, `HAnd.hAnd,\n    `HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen,\n    `HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod,\n    `HShiftLeft.hShiftLeft, `HShiftRight]\n  ops.any fun op => op == f.constName!\n\ndef replaceLPsWithVars (e : Expr) : MetaM Expr := do\n  if !e.hasLevelParam then return e\n  let lps := collectLevelParams {} e |>.params\n  let mut replaceMap : HashMap Name Level := {}\n  for lp in lps do replaceMap := replaceMap.insert lp (\u2190 mkFreshLevelMVar)\n  return e.replaceLevel fun\n    | Level.param n .. => replaceMap.find! n\n    | l => if !l.hasParam then some l else none\n\ndef isDefEqAssigning (t s : Expr) : MetaM Bool := do\n  withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $\n    Meta.isDefEq t s\n\ndef checkpointDefEq (t s : Expr) : MetaM Bool := do\n  Meta.checkpointDefEq (mayPostpone := false) do\n    isDefEqAssigning t s\n\ndef isHigherOrder (type : Expr) : MetaM Bool := do\n  forallTelescopeReducing type fun xs b => return xs.size > 0 && b.isSort\n\ndef isFunLike (e : Expr) : MetaM Bool := do\n  forallTelescopeReducing (\u2190 inferType e) fun xs _ => return xs.size > 0\n\ndef isSubstLike (e : Expr) : Bool :=\n  e.isAppOfArity ``Eq.ndrec 6 || e.isAppOfArity ``Eq.rec 6\n\ndef nameNotRoundtrippable (n : Name) : Bool :=\n  n.hasMacroScopes || isPrivateName n || containsNum n\nwhere\n  containsNum\n    | Name.str p .. => containsNum p\n    | Name.num ..   => true\n    | Name.anonymous => false\n\ndef mvarName (mvar : Expr) : MetaM Name :=\n  return (\u2190  mvar.mvarId!.getDecl).userName\n\ndef containsBadMax : Level \u2192 Bool\n  | Level.succ u ..   => containsBadMax u\n  | Level.max u v ..  => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v\n  | Level.imax u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v\n  | _                 => false\n\nopen SubExpr\n\nstructure Context where\n  knowsType   : Bool\n  knowsLevel  : Bool -- only constants look at this\n  inBottomUp  : Bool := false\n  parentIsApp : Bool := false\n  subExpr     : SubExpr\n  deriving Inhabited\n\nstructure State where\n  annotations : OptionsPerPos := {}\n  postponed   : Array (Expr \u00d7 Expr) := #[] -- not currently used\n\nabbrev AnalyzeM := ReaderT Context (StateRefT State MetaM)\n\ninstance (priority := low) : MonadReaderOf SubExpr AnalyzeM where\n  read := Context.subExpr <$> read\n\ninstance (priority := low) : MonadWithReaderOf SubExpr AnalyzeM where\n  withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr }\n\ndef tryUnify (e\u2081 e\u2082 : Expr) : AnalyzeM Unit := do\n  try\n    let r \u2190 isDefEqAssigning e\u2081 e\u2082\n    if !r then modify fun s => { s with postponed := s.postponed.push (e\u2081, e\u2082) }\n    pure ()\n  catch _ =>\n    modify fun s => { s with postponed := s.postponed.push (e\u2081, e\u2082) }\n\npartial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do\n  let argType  \u2190 inferType arg -- HAdd \u03b1 \u03b1 \u03b1\n  let mvarType \u2190 inferType mvar\n  let fType \u2190 inferType argType.getAppFn -- Type \u2192 Type \u2192 outParam Type\n  let mType \u2190 inferType mvarType.getAppFn\n  inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs\nwhere\n  inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do\n    let fType \u2190 whnf fType\n    let mType \u2190 whnf mType\n    if not (i < args.size) then return ()\n    match fType, mType with\n    | Expr.forallE _ fd fb _, Expr.forallE _ _  mb _ => do\n      -- TODO: do I need to check (\u2190 okBottomUp? args[i] mvars[i] fuel).isSafe here?\n      -- if so, I'll need to take a callback\n      if fd.isOutParam then\n        tryUnify (args[i]!) (mvars[i]!)\n      inspectAux (fb.instantiate1 args[i]!) (mb.instantiate1 mvars[i]!) (i+1) args mvars\n    | _, _ => return ()\n\npartial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do\n  let opts \u2190 getOptions\n  return e.isFVar\n         || e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort\n         || (getPPAnalyzeTrustOfNat opts && e.isAppOfArity ``OfNat.ofNat 3)\n         || (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity ``OfScientific.ofScientific 5)\n\npartial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do\n  -- Here we check if `e` can be safely elaborated without its expected type.\n  -- These are incomplete (and possibly unsound) heuristics.\n  -- TODO: do I need to snapshot the state before calling this?\n  match fuel with\n  | 0 => return false\n  | fuel + 1 =>\n    if \u2190 isTrivialBottomUp e then return true\n    let f := e.getAppFn\n    if !f.isConst && !f.isFVar then return false\n    let args := e.getAppArgs\n    let fType \u2190 replaceLPsWithVars (\u2190 inferType e.getAppFn)\n    let (mvars, bInfos, resultType) \u2190 forallMetaBoundedTelescope fType e.getAppArgs.size\n    for i in [:mvars.size] do\n      if bInfos[i]! == BinderInfo.instImplicit then\n        inspectOutParams args[i]! mvars[i]!\n      else if bInfos[i]! == BinderInfo.default then\n        if \u2190 isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]!\n        else if \u2190 typeUnknown mvars[i]! <&&> canBottomUp args[i]! (some mvars[i]!) fuel then tryUnify args[i]! mvars[i]!\n    if \u2190 (pure (isHBinOp e) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]!\n    if mvar?.isSome then tryUnify resultType (\u2190 inferType mvar?.get!)\n    return !(\u2190 valUnknown resultType)\n\ndef withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM \u03b1) : AnalyzeM \u03b1 := do\n  withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x\n\nbuiltin_initialize analyzeFailureId : InternalExceptionId \u2190 registerInternalExceptionId `analyzeFailure\n\ndef checkKnowsType : AnalyzeM Unit := do\n  if not (\u2190 read).knowsType then\n    throw $ Exception.internal analyzeFailureId\n\ndef annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do\n  let opts := (\u2190 get).annotations.findD pos {} |>.setBool n true\n  trace[pp.analyze.annotate] \"{pos} {n}\"\n  modify fun s => { s with annotations := s.annotations.insert pos opts }\n\ndef annotateBool (n : Name) : AnalyzeM Unit := do\n  annotateBoolAt n (\u2190 getPos)\n\nstructure App.Context where\n  f               : Expr\n  fType           : Expr\n  args            : Array Expr\n  mvars           : Array Expr\n  bInfos          : Array BinderInfo\n  forceRegularApp : Bool\n\nstructure App.State where\n  bottomUps       : Array Bool\n  higherOrders    : Array Bool\n  funBinders      : Array Bool\n  provideds       : Array Bool\n  namedArgs       : Array Name := #[]\n\nabbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM)\n\nmutual\n\n  partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do\n    checkMaxHeartbeats \"Delaborator.topDownAnalyze\"\n    trace[pp.analyze] \"{(\u2190 read).knowsType}.{(\u2190 read).knowsLevel}\"\n    let e \u2190 getExpr\n    let opts \u2190 getOptions\n    if \u2190 (pure !e.isAtomic) <&&> pure !(getPPProofs opts) <&&> (try Meta.isProof e catch _ => pure false) then\n      if getPPProofsWithType opts then\n        withType $ withKnowing true true $ analyze\n      return ()\n    else\n      withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do\n        match (\u2190 getExpr) with\n        | Expr.app ..     => analyzeApp\n        | Expr.forallE .. => analyzePi\n        | Expr.lam ..     => analyzeLam\n        | Expr.const ..   => analyzeConst\n        | Expr.sort ..    => analyzeSort\n        | Expr.proj ..    => analyzeProj\n        | Expr.fvar ..    => analyzeFVar\n        | Expr.mdata ..   => analyzeMData\n        | Expr.letE ..    => analyzeLet\n        | Expr.lit ..     => pure ()\n        | Expr.mvar ..    => pure ()\n        | Expr.bvar ..    => pure ()\n  where\n    analyzeApp := do\n      let mut willKnowType := (\u2190 read).knowsType\n      if !(\u2190 read).knowsType && !(\u2190 canBottomUp (\u2190 getExpr)) then\n        annotateBool `pp.analysis.needsType\n        withType $ withKnowing true false $ analyze\n        willKnowType := true\n\n      else if \u2190 (pure !(\u2190 read).knowsType <||> pure (\u2190 read).inBottomUp) <&&> isStructureInstance (\u2190 getExpr) then\n        withType do\n          annotateBool `pp.structureInstanceTypes\n          withKnowing true false $ analyze\n        willKnowType := true\n\n      withKnowing willKnowType true $ analyzeAppStaged (\u2190 getExpr).getAppFn (\u2190 getExpr).getAppArgs\n\n    analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do\n      let fType \u2190 replaceLPsWithVars (\u2190 inferType f)\n      let (mvars, bInfos, resultType) \u2190 forallMetaBoundedTelescope fType args.size\n      let rest := args.extract mvars.size args.size\n      let args := args.shrink mvars.size\n\n      -- Unify with the expected type\n      if (\u2190 read).knowsType then tryUnify (\u2190 inferType (mkAppN f args)) resultType\n\n      let forceRegularApp : Bool :=\n        (getPPAnalyzeTrustSubst (\u2190 getOptions) && isSubstLike (\u2190 getExpr))\n        || (getPPAnalyzeTrustSubtypeMk (\u2190 getOptions) && (\u2190 getExpr).isAppOfArity ``Subtype.mk 4)\n\n      analyzeAppStagedCore { f, fType, args, mvars, bInfos, forceRegularApp } |>.run' {\n        bottomUps    := mkArray args.size false,\n        higherOrders := mkArray args.size false,\n        provideds    := mkArray args.size false,\n        funBinders   := mkArray args.size false\n      }\n\n      if not rest.isEmpty then\n        -- Note: this shouldn't happen for type-correct terms\n        if !args.isEmpty then\n          analyzeAppStaged (mkAppN f args) rest\n\n    maybeAddBlockImplicit : AnalyzeM Unit := do\n      -- See `MonadLift.noConfusion for an example where this is necessary.\n      if !(\u2190 read).parentIsApp then\n        let type \u2190 inferType (\u2190 getExpr)\n        if type.isForall && type.bindingInfo! == BinderInfo.implicit then\n          annotateBool `pp.analysis.blockImplicit\n\n    analyzeConst : AnalyzeM Unit := do\n      let Expr.const _ ls .. \u2190 getExpr | unreachable!\n      if !(\u2190 read).knowsLevel && !ls.isEmpty then\n        -- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590\n        unless getPPAnalyzeOmitMax (\u2190 getOptions) && ls.any containsBadMax do\n        annotateBool `pp.universes\n      maybeAddBlockImplicit\n\n    analyzePi : AnalyzeM Unit := do\n      withBindingDomain $ withKnowing true false analyze\n      withBindingBody Name.anonymous analyze\n\n    analyzeLam : AnalyzeM Unit := do\n      if !(\u2190 read).knowsType then annotateBool `pp.funBinderTypes\n      withBindingDomain $ withKnowing true false analyze\n      withBindingBody Name.anonymous analyze\n\n    analyzeLet : AnalyzeM Unit := do\n      let Expr.letE _ _ v _    .. \u2190 getExpr | unreachable!\n      if !(\u2190 canBottomUp v) then\n        annotateBool `pp.analysis.letVarType\n        withLetVarType $ withKnowing true false analyze\n        withLetValue $ withKnowing true true analyze\n      else\n        withReader (fun ctx => { ctx with inBottomUp := true }) do\n          withLetValue $ withKnowing true true analyze\n\n      withLetBody analyze\n\n    analyzeSort  : AnalyzeM Unit := pure ()\n    analyzeProj  : AnalyzeM Unit := withProj analyze\n    analyzeFVar  : AnalyzeM Unit := maybeAddBlockImplicit\n    analyzeMData : AnalyzeM Unit := withMDataExpr analyze\n\n  partial def analyzeAppStagedCore : AnalyzeAppM Unit := do\n    collectBottomUps\n    checkOutParams\n    collectHigherOrders\n    hBinOpHeuristic\n    collectTrivialBottomUps\n    discard <| processPostponed (mayPostpone := true)\n    applyFunBinderHeuristic\n    analyzeFn\n    for i in [:(\u2190 read).args.size] do analyzeArg i\n    maybeSetExplicit\n\n  where\n    collectBottomUps := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for target in [fun _ => none, fun i => some mvars[i]!] do\n        for i in [:args.size] do\n          if bInfos[i]! == BinderInfo.default then\n            if \u2190 typeUnknown mvars[i]! <&&> canBottomUp args[i]! (target i) then\n              tryUnify args[i]! mvars[i]!\n              modify fun s => { s with bottomUps := s.bottomUps.set! i true }\n\n    checkOutParams := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]!\n\n    collectHigherOrders := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if not (bInfos[i]! == BinderInfo.implicit || bInfos[i]! == BinderInfo.strictImplicit) then continue\n        if not (\u2190 isHigherOrder (\u2190 inferType args[i]!)) then continue\n        if getPPAnalyzeTrustId (\u2190 getOptions) && isIdLike args[i]! then continue\n\n        if getPPAnalyzeTrustKnownFOType2TypeHOFuns (\u2190 getOptions) && not (\u2190 valUnknown mvars[i]!)\n          && (\u2190 isType2Type (args[i]!)) && (\u2190 isFOLike (args[i]!)) then continue\n\n        tryUnify args[i]! mvars[i]!\n        modify fun s => { s with higherOrders := s.higherOrders.set! i true }\n\n    hBinOpHeuristic := do\n      let { mvars, ..} \u2190 read\n      if \u2190 (pure (isHBinOp (\u2190 getExpr)) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then\n        tryUnify mvars[0]! mvars[1]!\n\n    collectTrivialBottomUps := do\n      -- motivation: prevent levels from printing in\n      -- Boo.mk : {\u03b1 : Type u_1} \u2192 {\u03b2 : Type u_2} \u2192 \u03b1 \u2192 \u03b2 \u2192 Boo.{u_1, u_2} \u03b1 \u03b2\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if bInfos[i]! == BinderInfo.default then\n          if \u2190 valUnknown mvars[i]! <&&> isTrivialBottomUp args[i]! then\n            tryUnify args[i]! mvars[i]!\n            modify fun s => { s with bottomUps := s.bottomUps.set! i true }\n\n    applyFunBinderHeuristic := do\n      let { args, mvars, bInfos, .. } \u2190 read\n\n      let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do\n        match \u2190 getExpr, mvarType with\n        | Expr.lam .., Expr.forallE _ t b .. =>\n          let mut annotated := false\n          for i in [:argIdx] do\n            if \u2190 pure (bInfos[i]! == BinderInfo.implicit) <&&> valUnknown mvars[i]! <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]!) then\n              annotateBool `pp.funBinderTypes\n              tryUnify args[i]! mvars[i]!\n              -- Note: currently we always analyze the lambda binding domains in `analyzeLam`\n              -- (so we don't need to analyze it again here)\n              annotated := true\n              break\n          let annotatedBody \u2190 withBindingBody Name.anonymous (core argIdx b)\n          return annotated || annotatedBody\n\n        | _, _ => return false\n\n      for i in [:args.size] do\n        if bInfos[i]! == BinderInfo.default then\n          let b \u2190 withNaryArg i (core i (\u2190 inferType mvars[i]!))\n          if b then modify fun s => { s with funBinders := s.funBinders.set! i true }\n\n    analyzeFn := do\n      -- Now, if this is the first staging, analyze the n-ary function without expected type\n      let {f, fType, forceRegularApp ..} \u2190 read\n      if !f.isApp then withKnowing false (forceRegularApp || !(\u2190 hasLevelMVarAtCurrDepth (\u2190 instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true))\n\n    annotateNamedArg (n : Name) : AnalyzeAppM Unit := do\n      annotateBool `pp.analysis.namedArg\n      modify fun s => { s with namedArgs := s.namedArgs.push n }\n\n    analyzeArg (i : Nat) := do\n      let { f, args, mvars, bInfos, forceRegularApp ..} \u2190 read\n      let { bottomUps, higherOrders, funBinders, ..} \u2190 get\n      let arg := args[i]!\n      let argType \u2190 inferType arg\n\n      let processNaturalImplicit : AnalyzeAppM Unit := do\n        if (\u2190 valUnknown mvars[i]! <||> pure higherOrders[i]!) && !forceRegularApp then\n          annotateNamedArg (\u2190 mvarName mvars[i]!)\n          modify fun s => { s with provideds := s.provideds.set! i true }\n        else\n          annotateBool `pp.analysis.skip\n\n      withNaryArg (f.getAppNumArgs + i) do\n        withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i]! }) do\n\n          match bInfos[i]! with\n          | BinderInfo.default =>\n            if \u2190 pure (getPPAnalyzeExplicitHoles (\u2190 getOptions)) <&&> pure !(\u2190 valUnknown mvars[i]!) <&&> pure !(\u2190 readThe Context).inBottomUp <&&> pure !(\u2190 isFunLike arg) <&&> pure !funBinders[i]! <&&> checkpointDefEq mvars[i]! arg then\n              annotateBool `pp.analysis.hole\n            else\n              modify fun s => { s with provideds := s.provideds.set! i true }\n\n          | BinderInfo.implicit => processNaturalImplicit\n          | BinderInfo.strictImplicit => processNaturalImplicit\n\n          | BinderInfo.instImplicit =>\n            -- Note: apparently checking valUnknown here is not sound, because the elaborator\n            -- will not happily assign instImplicits that it cannot synthesize\n            let mut provided := true\n            if !getPPInstances (\u2190 getOptions) then\n              annotateBool `pp.analysis.skip\n              provided := false\n            else if getPPAnalyzeCheckInstances (\u2190 getOptions) then\n              let instResult \u2190 try trySynthInstance argType catch _ => pure LOption.undef\n              match instResult with\n              | LOption.some inst =>\n                if \u2190 checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false\n                else annotateNamedArg (\u2190 mvarName mvars[i]!)\n              | _                 => annotateNamedArg (\u2190 mvarName mvars[i]!)\n            else annotateBool `pp.analysis.skip; provided := false\n            modify fun s => { s with provideds := s.provideds.set! i provided }\n          if (\u2190 get).provideds[i]! then withKnowing (not (\u2190 typeUnknown mvars[i]!)) true analyze\n          tryUnify mvars[i]! args[i]!\n\n    maybeSetExplicit := do\n      let { f, args, bInfos, ..} \u2190 read\n      if (\u2190 get).namedArgs.any nameNotRoundtrippable then\n        annotateBool `pp.explicit\n        for i in [:args.size] do\n          if !(\u2190 get).provideds[i]! then\n            withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole\n          if bInfos[i]! == BinderInfo.instImplicit && getPPInstanceTypes (\u2190 getOptions) then\n            withType (withKnowing true false analyze)\n\nend\n\nend TopDownAnalyze\n\nopen TopDownAnalyze SubExpr\n\ndef topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do\n  let s\u2080 \u2190 get\n  withTraceNode `pp.analyze (fun _ => return e) do\n    withReader (fun ctx => { ctx with config := Elab.Term.setElabConfig ctx.config }) do\n      let \u03d5 : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; pure (\u2190 get).annotations\n      try\n        let knowsType := getPPAnalyzeKnowsType (\u2190 getOptions)\n        \u03d5 { knowsType := knowsType, knowsLevel := knowsType, subExpr := mkRoot e }\n          |>.run' { : TopDownAnalyze.State }\n      catch e =>\n        trace[pp.analyze.error] \"failed {e.toMessageData}\"\n        pure {}\n      finally set s\u2080\n\nbuiltin_initialize\n  registerTraceClass `pp.analyze\n  registerTraceClass `pp.analyze.annotate (inherited := true)\n  registerTraceClass `pp.analyze.tryUnify (inherited := true)\n  registerTraceClass `pp.analyze.error (inherited := true)\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/TopDownAnalyze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0888202996359354, "lm_q2_score": 0.031143830085152435, "lm_q1q2_score": 0.002766204319973899}}
{"text": "/-\nCopyright (c) 2018 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Sebastian Ullrich\n\nElaborator for the Lean language: takes commands and produces side effects\n-/\nprelude\nimport init.lean.parser.module\nimport init.lean.expander\nimport init.lean.expr\nimport init.lean.options\nimport init.lean.environment\n\nnamespace Lean\n-- deprecated Constructor\n@[extern \"lean_expr_local\"]\nconstant Expr.local (n : Name) (pp : Name) (ty : Expr) (bi : BinderInfo) : Expr := default Expr\n\nnamespace Elaborator\n-- TODO(Sebastian): move\n-- TODO(Sebastian): should be its own Monad?\nstructure NameGenerator :=\n(\u00abprefix\u00bb : Name)\n(nextIdx : UInt32)\n\nstructure SectionVar :=\n(uniqName : Name)\n(BinderInfo : BinderInfo)\n(type : Expr)\n\n/-- Simplified State of the Lean 3 Parser. Maps are replaced with lists for easier interop. -/\nstructure OldElaboratorState :=\n(env : Environment)\n(ngen : NameGenerator)\n(univs : List (Name \u00d7 Level))\n(vars : List (Name \u00d7 SectionVar))\n(includeVars : List Name)\n(Options : Options)\n(nextInstIdx : Nat)\n(ns : Name)\n\n@[extern \"lean_elaborator_elaborate_command\"]\nconstant elaborateCommand (filename : @& String) (e : Expr) (s : @& OldElaboratorState) : Option OldElaboratorState \u00d7 MessageLog := (none, \u27e8[]\u27e9)\n\nopen Parser\nopen Parser.Combinators\nopen Parser.Term\nopen Parser.command\nopen Parser.command.NotationSpec\nopen Expander\n\n-- TODO(Sebastian): move\n/-- An RBMap that remembers the insertion order. -/\nstructure OrderedRBMap (\u03b1 \u03b2 : Type) (lt : \u03b1 \u2192 \u03b1 \u2192 Bool) :=\n(entries : List (\u03b1 \u00d7 \u03b2))\n(map : RBMap \u03b1 (Nat \u00d7 \u03b2) lt)\n(size : Nat)\n\nnamespace OrderedRBMap\nvariables {\u03b1 \u03b2 : Type} {lt : \u03b1 \u2192 \u03b1 \u2192 Bool} (m : OrderedRBMap \u03b1 \u03b2 lt)\n\ndef empty : OrderedRBMap \u03b1 \u03b2 lt := {entries := [], map := mkRBMap _ _ _, size := 0}\n\ndef insert (k : \u03b1) (v : \u03b2) : OrderedRBMap \u03b1 \u03b2 lt :=\n{entries := (k, v)::m.entries, map := m.map.insert k (m.size, v), size := m.size + 1}\n\ndef find (a : \u03b1) : Option (Nat \u00d7 \u03b2) :=\nm.map.find a\n\ndef ofList (l : List (\u03b1 \u00d7 \u03b2)) : OrderedRBMap \u03b1 \u03b2 lt :=\nl.foldl (\u03bb m p, OrderedRBMap.insert m (Prod.fst p) (Prod.snd p)) OrderedRBMap.empty\nend OrderedRBMap\n\nstructure ElaboratorConfig extends FrontendConfig :=\n(initialParserCfg : ModuleParserConfig)\n\ninstance elaboratorConfigCoeFrontendConfig : HasCoe ElaboratorConfig FrontendConfig :=\n\u27e8ElaboratorConfig.toFrontendConfig\u27e9\n\n/-- Elaborator State that will be reverted at the end of a section or namespace. -/\nstructure Scope :=\n-- \"section\" or \"namespace\" (or \"MODULE\"), currently\n(cmd : String)\n-- Scope header, should match identifier after `end`. Can be `Name.anonymous` for sections.\n(header : Name)\n(notations : List NotationMacro := [])\n/- The set of local universe variables.\n   We remember their insertion order so that we can keep the order when copying them to declarations. -/\n(univs : OrderedRBMap Name Level Name.quickLt := OrderedRBMap.empty)\n/- The set of local variables. -/\n(vars : OrderedRBMap Name SectionVar Name.quickLt := OrderedRBMap.empty)\n/- The subset of `vars` that is tagged as always included. -/\n(includeVars : RBTree Name Name.quickLt := mkRBTree _ _)\n/- The stack of nested active `namespace` commands. -/\n(nsStack : List Name := [])\n/- The set of active `open` declarations. -/\n(openDecls : List openSpec.View := [])\n(Options : Options := {})\n\n/-- An `export` command together with the namespace it was declared in. Opening the namespace activates\n    the export. -/\nstructure ScopedExportDecl :=\n(inNs : Name)\n(spec : openSpec.View)\n\nstructure ElaboratorState :=\n-- TODO(Sebastian): retrieve from environment\n(reservedNotations : List reserveNotation.View := [])\n(notations : List NotationMacro := [])\n(notationCounter := 0)\n/- The current set of `export` declarations (active or inactive). -/\n(exportDecls : List ScopedExportDecl := [])\n\n-- Stack of current scopes. The bottom-most Scope is the Module Scope.\n(scopes : List Scope)\n(messages : MessageLog := MessageLog.empty)\n(parserCfg : ModuleParserConfig)\n(expanderCfg : Expander.ExpanderConfig)\n(env : Environment)\n(ngen : NameGenerator)\n(nextInstIdx : Nat := 0)\n\n@[derive Monad MonadRec MonadReader MonadState MonadExcept]\ndef ElaboratorM := RecT Syntax Unit $ ReaderT ElaboratorConfig $ StateT ElaboratorState $ ExceptT Message Id\nabbrev Elaborator := Syntax \u2192 ElaboratorM Unit\n\ninstance elaboratorInh (\u03b1 : Type) : Inhabited (ElaboratorM \u03b1) :=\n\u27e8\u03bb _ _ _, Except.error (default _)\u27e9\n\n/-- Recursively elaborate any command. -/\ndef command.elaborate : Elaborator := recurse\n\ndef currentScope : ElaboratorM Scope := do\n  st \u2190 get,\n  match st.scopes with\n  | [] := error none \"currentScope: unreachable\"\n  | sc::_ := pure sc\n\ndef modifyCurrentScope (f : Scope \u2192 Scope) : ElaboratorM Unit := do\n  st \u2190 get,\n  match st.scopes with\n  | [] := error none \"modifyCurrentScope: unreachable\"\n  | sc::scs := set {st with scopes := f sc::scs}\n\ndef mangleIdent (id : SyntaxIdent) : Name :=\nid.scopes.foldl Name.mkNumeral id.val\n\npartial def levelGetAppArgs : Syntax \u2192 ElaboratorM (Syntax \u00d7 List Syntax)\n| stx := do\n  match stx.kind with\n  | some Level.leading := pure (stx, [])\n  | some Level.trailing := match view Level.trailing stx with\n    | Level.trailing.View.app lta := do\n      (fn, args) \u2190 levelGetAppArgs lta.fn,\n      pure (fn, lta.Arg :: args)\n    | Level.trailing.View.addLit _ := pure (stx, [])\n  | _ := error stx $ \"levelGetAppArgs: unexpected input: \" ++ toString stx\n\ndef levelAdd : Level \u2192 Nat \u2192 Level\n| l 0     := l\n| l (n+1) := (levelAdd l n).succ\n\npartial def toLevel : Syntax \u2192 ElaboratorM Level\n| stx := do\n  (fn, args) \u2190 levelGetAppArgs stx,\n  sc \u2190 currentScope,\n  match fn.kind with\n  | some Level.leading := match view Level.leading fn, args with\n    | Level.leading.View.hole _, [] := pure $ Level.mvar Name.anonymous\n    | Level.leading.View.lit lit, [] := pure $ Level.ofNat lit.toNat\n    | Level.leading.View.var id, [] := let id := mangleIdent id in match sc.univs.find id with\n      | some _ := pure $ Level.Param id\n      | none   := error stx $ \"unknown universe variable '\" ++ toString id ++ \"'\"\n    | Level.leading.View.max _, (Arg::args) := List.foldr Level.max <$> toLevel Arg <*> args.mmap toLevel\n    | Level.leading.View.imax _, (Arg::args) := List.foldr Level.imax <$> toLevel Arg <*> args.mmap toLevel\n    | _, _ := error stx \"ill-formed universe Level\"\n  | some Level.trailing := match view Level.trailing fn, args with\n    | Level.trailing.View.addLit lta, [] := do\n      l \u2190 toLevel lta.lhs,\n      pure $ levelAdd l lta.rhs.toNat\n    | _, _ := error stx \"ill-formed universe Level\"\n  | _ := error stx $ \"toLevel: unexpected input: \" ++ toString stx\n\ndef Expr.mkAnnotation (ann : Name) (e : Expr) :=\nExpr.mdata (MData.empty.setName `annotation ann) e\n\ndef dummy : Expr := Expr.const `Prop []\n\ndef mkEqns (type : Expr) (eqns : List (Name \u00d7 List Expr \u00d7 Expr)): Expr :=\n  let eqns := eqns.map $ \u03bb \u27e8fn, lhs, rhs\u27e9, do {\n    let fn := Expr.local fn fn type BinderInfo.auxDecl,\n    let lhs := Expr.mkApp (Expr.mkAnnotation `@ fn) lhs,\n    Expr.app lhs rhs\n  } in\n  Expr.mkAnnotation `preEquations $ Expr.mkCapp `_ eqns\n\npartial def toPexpr : Syntax \u2192 ElaboratorM Expr\n| stx@(Syntax.rawNode {kind := k, args := args}) := do\n  e \u2190 match k with\n  | @identUnivs := do\n    let v := view identUnivs stx,\n    e \u2190 match v with\n    | {id := id, univs := some univs} := Expr.const (mangleIdent id) <$> univs.levels.mmap toLevel\n    | {id := id, univs := none}       := pure $ Expr.const (mangleIdent id) [],\n    let m := MData.empty.setName `annotation `preresolved,\n    let m := v.id.preresolved.enum.foldl (\u03bb (m : MData) \u27e8i, n\u27e9, m.setName (Name.anonymous.mkNumeral i) n) m,\n    pure $ Expr.mdata m e\n  | @app   := let v := view app stx in\n    Expr.app <$> toPexpr v.fn <*> toPexpr v.Arg\n  | @lambda := do\n    let lam := view lambda stx,\n    binders.View.simple bnder \u2190 pure lam.binders\n      | error stx \"ill-formed lambda\",\n    (bi, id, type) \u2190 pure bnder.toBinderInfo,\n    Expr.lam (mangleIdent id) bi <$> toPexpr type <*> toPexpr lam.body\n  | @pi := do\n    let v := view pi stx,\n    binders.View.simple bnder \u2190 pure v.binders\n      | error stx \"ill-formed pi\",\n    (bi, id, type) \u2190 pure bnder.toBinderInfo,\n    Expr.pi (mangleIdent id) bi <$> toPexpr type <*> toPexpr v.range\n  | @sort := match view sort stx with\n    | sort.View.Sort _ := pure $ Expr.sort Level.zero\n    | sort.View.Type _ := pure $ Expr.sort $ Level.succ Level.zero\n  | @sortApp := do\n    let v := view sortApp stx,\n    match view sort v.fn with\n    | sort.View.Sort _ := Expr.sort <$> toLevel v.Arg\n    | sort.View.Type _ := (Expr.sort \u2218 Level.succ) <$> toLevel v.Arg\n  | @anonymousConstructor := do\n    let v := view anonymousConstructor stx,\n    p \u2190 toPexpr $ mkApp (review hole {}) (v.args.map SepBy.Elem.View.item),\n    pure $ Expr.mkAnnotation `anonymousConstructor p\n  | @hole := pure $ Expr.mvar Name.anonymous dummy\n  | @\u00abhave\u00bb := do\n    let v := view \u00abhave\u00bb stx,\n    let id := (mangleIdent <$> optIdent.View.id <$> v.id).getOrElse `this,\n    let proof := match v.proof with\n    | haveProof.View.Term hpt := hpt.Term\n    | haveProof.View.from hpf := hpf.from.proof,\n    lam \u2190 Expr.lam id BinderInfo.default <$> toPexpr v.prop <*> toPexpr v.body,\n    Expr.app (Expr.mkAnnotation `have lam) <$> toPexpr proof\n  | @\u00abshow\u00bb := do\n    let v := view \u00abshow\u00bb stx,\n    prop \u2190 toPexpr v.prop,\n    proof \u2190 toPexpr v.from.proof,\n    pure $ Expr.mkAnnotation `show $ Expr.app (Expr.lam `this BinderInfo.default prop $ Expr.bvar 0) proof\n  | @\u00ablet\u00bb := do\n    let v := view \u00ablet\u00bb stx,\n    letLhs.View.id {id := id, binders := [], type := some ty} \u2190 pure v.lhs\n      | error stx \"ill-formed let\",\n    Expr.elet (mangleIdent id) <$> toPexpr ty.type <*> toPexpr v.value <*> toPexpr v.body\n  | @projection := do\n    let v := view projection stx,\n    let val := match v.proj with\n    | projectionSpec.View.id id := DataValue.ofName id.val\n    | projectionSpec.View.num n := DataValue.ofNat n.toNat,\n    Expr.mdata (MData.empty.insert `fieldNotation val) <$> toPexpr v.Term\n  | @explicit := do\n    let v := view explicit stx,\n    let ann := match v.mod with\n    | explicitModifier.View.explicit _         := `@\n    | explicitModifier.View.partialExplicit _ := `@@,\n    Expr.mkAnnotation ann <$> toPexpr (review identUnivs v.id)\n  | @inaccessible := do\n    let v := view inaccessible stx,\n    Expr.mkAnnotation `innaccessible <$> toPexpr v.Term  -- sic\n  | @borrowed := do\n    let v := view borrowed stx,\n    Expr.mkAnnotation `borrowed <$> toPexpr v.Term\n  | @number := do\n    let v := view number stx,\n    pure $ Expr.lit $ Literal.natVal v.toNat\n  | @stringLit := do\n    let v := view stringLit stx,\n    pure $ Expr.lit $ Literal.strVal (v.value.getOrElse \"NOTAString\")\n  | @choice := do\n    last::rev \u2190 List.reverse <$> args.mmap (\u03bb a, toPexpr a)\n      | error stx \"ill-formed choice\",\n    pure $ Expr.mdata (MData.empty.setNat `choice args.length) $\n      rev.reverse.foldr Expr.app last\n  | @structInst := do\n    let v := view structInst stx,\n    -- order should be: fields*, sources*, catchall?\n    let (fields, other) := v.items.span (\u03bb it, \u2191match SepBy.Elem.View.item it with\n      | structInstItem.View.field _ := true\n      | _ := false),\n    let (sources, catchall) := other.span (\u03bb it, \u2191match SepBy.Elem.View.item it with\n      | structInstItem.View.source {source := some _} := true\n      | _ := false),\n    catchall \u2190 match catchall with\n    | [] := pure false\n    | [{item := structInstItem.View.source _}] := pure true\n    | {item := it}::_ := error (review structInstItem it) $ \"unexpected item in structure instance notation\",\n\n    fields \u2190 fields.mmap (\u03bb f, match SepBy.Elem.View.item f with\n      | structInstItem.View.field f :=\n        Expr.mdata (MData.empty.setName `field $ mangleIdent f.id) <$> toPexpr f.val\n      | _ := error stx \"toPexpr: unreachable\"),\n    sources \u2190 sources.mmap (\u03bb src, match SepBy.Elem.View.item src with\n      | structInstItem.View.source {source := some src} := toPexpr src\n      | _ := error stx \"toPexpr: unreachable\"),\n    sources \u2190 match v.with with\n    | none     := pure sources\n    | some src := do { src \u2190 toPexpr src.source, pure $ sources ++ [src]},\n\n    let m := MData.empty.setNat \"structure instance\" fields.length,\n    let m := m.setBool `catchall catchall,\n    let m := m.setName `struct $\n      (mangleIdent <$> structInstType.View.id <$> v.type).getOrElse Name.anonymous,\n    let dummy := Expr.sort Level.zero,\n    pure $ Expr.mdata m $ (fields ++ sources).foldr Expr.app dummy\n  | @\u00abmatch\u00bb := do\n    let v := view \u00abmatch\u00bb stx,\n    eqns \u2190 (v.equations.map SepBy.Elem.View.item).mmap $ \u03bb (eqn : matchEquation.View), do {\n      lhs \u2190 eqn.lhs.mmap $ \u03bb l, toPexpr l.item,\n      rhs \u2190 toPexpr eqn.rhs,\n      pure (`_matchFn, lhs, rhs)\n    },\n    type \u2190 toPexpr $ getOptType v.type,\n    let eqns := mkEqns type eqns,\n    Expr.mdata mdata e \u2190 pure eqns\n      | error stx \"toPexpr: unreachable\",\n    let eqns := Expr.mdata (mdata.setBool `match true) e,\n    Expr.mkApp eqns <$> v.scrutinees.mmap (\u03bb scr, toPexpr scr.item)\n  | _ := error stx $ \"toPexpr: unexpected Node: \" ++ toString k.name,\n  match k with\n  | @app := pure e -- no Position\n  | _ := do\n    cfg \u2190 read,\n    match stx.getPos with\n    | some pos :=\n      let pos := cfg.fileMap.toPosition pos in\n      pure $ Expr.mdata ((MData.empty.setNat `column pos.column).setNat `row pos.line) e\n    | none := pure e\n| stx := error stx $ \"toPexpr: unexpected: \" ++ toString stx\n\n/-- Returns the active namespace, that is, the concatenation of all active `namespace` commands. -/\ndef getNamespace : ElaboratorM Name := do\n  sc \u2190 currentScope,\n  pure $ match sc.nsStack with\n  | ns::_ := ns\n  | _     := Name.anonymous\n\ndef oldElabCommand (stx : Syntax) (cmd : Expr) : ElaboratorM Unit :=\ndo cfg \u2190 read,\n   let pos := cfg.fileMap.toPosition $ stx.getPos.getOrElse (default _),\n   let cmd := match cmd with\n   | Expr.mdata m e := Expr.mdata ((m.setNat `column pos.column).setNat `row pos.line) e\n   | e := e,\n   st \u2190 get,\n   sc \u2190 currentScope,\n   ns \u2190 getNamespace,\n   let (st', msgs) := elaborateCommand cfg.filename cmd {\n     ns := ns,\n     univs := sc.univs.entries.reverse,\n     vars := sc.vars.entries.reverse,\n     includeVars := sc.includeVars.toList,\n     Options := sc.Options,\n     ..st},\n   match st' with\n   | some st' := do modifyCurrentScope $ \u03bb sc, {sc with\n       univs := OrderedRBMap.ofList st'.univs,\n       vars := OrderedRBMap.ofList st'.vars,\n       includeVars := RBTree.ofList st'.includeVars,\n       Options := st'.Options,\n     },\n     modify $ \u03bb st, {..st', ..st}\n   | none := pure (),  -- error\n   modify $ \u03bb st, {st with messages := st.messages ++ msgs}\n\ndef namesToPexpr (ns : List Name) : Expr :=\nExpr.mkCapp `_ $ ns.map (\u03bb n, Expr.const n [])\n\ndef attrsToPexpr (attrs : List (SepBy.Elem.View attrInstance.View (Option SyntaxAtom))) : ElaboratorM Expr :=\nExpr.mkCapp `_ <$> attrs.mmap (\u03bb attr,\n  Expr.mkCapp attr.item.Name.val <$> attr.item.args.mmap toPexpr)\n\ndef declModifiersToPexpr (mods : declModifiers.View) : ElaboratorM Expr := do\n  let mdata : MData := {},\n  let mdata := match mods.docComment with\n    | some {doc := some doc, ..} := mdata.setString `docString doc.val\n    | _ := mdata,\n  let mdata := match mods.visibility with\n    | some (visibility.View.private _) := mdata.setBool `private true\n    | some (visibility.View.protected _) := mdata.setBool `protected true\n    | _ := mdata,\n  let mdata := mdata.setBool `noncomputable mods.noncomputable.isSome,\n  let mdata := mdata.setBool `unsafe mods.unsafe.isSome,\n  Expr.mdata mdata <$> attrsToPexpr (match mods.attrs with\n    | some attrs := attrs.attrs\n    | none       := [])\n\ndef identUnivParamsToPexpr (id : identUnivParams.View) : Expr :=\nExpr.const (mangleIdent id.id) $ match id.univParams with\n  | some params := params.params.map (Level.Param \u2218 mangleIdent)\n  | none        := []\n\n/-- Execute `elab` and reset local Scope (universes, ...) after it has finished. -/\ndef locally (elab : ElaboratorM Unit) :\n  ElaboratorM Unit := do\n  sc \u2190 currentScope,\n  elab,\n  modifyCurrentScope $ \u03bb _, sc\n\ndef simpleBindersToPexpr (bindrs : List simpleBinder.View) : ElaboratorM Expr :=\nExpr.mkCapp `_ <$> bindrs.mmap (\u03bb b, do\n  let (bi, id, type) := b.toBinderInfo,\n  let id := mangleIdent id,\n  type \u2190 toPexpr type,\n  pure $ Expr.local id id type bi)\n\ndef elabDefLike (stx : Syntax) (mods : declModifiers.View) (dl : defLike.View) (kind : Nat) : ElaboratorM Unit :=\nmatch dl with\n| {sig := {params := bracketedBinders.View.simple bbs}, ..} := do\n  let mdata := MData.empty.setName `command `defs,\n  mods \u2190 declModifiersToPexpr mods,\n  let kind := Expr.lit $ Literal.natVal kind,\n  match dl.oldUnivParams with\n  | some uparams :=\n    modifyCurrentScope $ \u03bb sc, {sc with univs :=\n      (uparams.ids.map mangleIdent).foldl (\u03bb m id, OrderedRBMap.insert m id (Level.Param id)) sc.univs}\n  | none := pure (),\n  -- do we actually need this??\n  let uparams := namesToPexpr $ match dl.oldUnivParams with\n  | some uparams := uparams.ids.map mangleIdent\n  | none := [],\n  let id := mangleIdent dl.Name.id,\n  let type := getOptType dl.sig.type,\n  type \u2190 toPexpr type,\n  let fns := Expr.mkCapp `_ [Expr.local id id type BinderInfo.auxDecl],\n  val \u2190 match dl.val with\n  | declVal.View.simple val  := toPexpr val.body\n  | declVal.View.emptyMatch _ := pure $ mkEqns type []\n  | declVal.View.match eqns  := do {\n    eqns \u2190 eqns.mmap (\u03bb (eqn : equation.View), do\n      lhs \u2190 eqn.lhs.mmap toPexpr,\n      rhs \u2190 toPexpr eqn.rhs,\n      pure (id, lhs, rhs)\n    ),\n    pure $ mkEqns type eqns\n  },\n  params \u2190 simpleBindersToPexpr bbs,\n  oldElabCommand stx $ Expr.mdata mdata $ Expr.mkCapp `_ [mods, kind, uparams, fns, params, val]\n| _ := error stx \"elabDefLike: unexpected input\"\n\ndef inferModToPexpr (mod : Option inferModifier.View) : Expr :=\nExpr.lit $ Literal.natVal $ match mod with\n| none := 0\n| some $ inferModifier.View.relaxed _ := 1\n| some $ inferModifier.View.strict _  := 2\n\ndef declaration.elaborate : Elaborator :=\n\u03bb stx, locally $ do\n  let decl := view \u00abdeclaration\u00bb stx,\n  match decl.inner with\n  | declaration.inner.View.\u00abaxiom\u00bb c@{sig := {params := bracketedBinders.View.simple [], type := type}, ..} := do\n    let mdata := MData.empty.setName `command `\u00abaxiom\u00bb, -- CommentTo(Kha): It was `constant` here\n    mods \u2190 declModifiersToPexpr decl.modifiers,\n    let id := identUnivParamsToPexpr c.Name,\n    type \u2190 toPexpr type.type,\n    oldElabCommand stx $ Expr.mdata mdata $ Expr.mkCapp `_ [mods, id, type]\n  | declaration.inner.View.defLike dl := do\n      -- The numeric literals below should reflect the enum values\n      -- enum class declCmdKind { Theorem, Definition, OpaqueConst, Example, Instance, Var, Abbreviation };\n      let kind := match dl.kind with\n      | defLike.kind.View.theorem _ := 0\n      | defLike.kind.View.def _ := 1\n      | defLike.kind.View.\u00abconstant\u00bb _ := 2\n      | defLike.kind.View.abbreviation _ := 6\n      | defLike.kind.View.\u00ababbrev\u00bb _ := 6,\n      elabDefLike stx decl.modifiers dl kind\n\n  -- these are almost macros for `def`, Except the Elaborator handles them specially at a few places\n  -- based on the kind\n  | declaration.inner.View.example ex :=\n    elabDefLike stx decl.modifiers {\n      kind := defLike.kind.View.def,\n      Name := {id := Name.anonymous},\n      sig := {..ex.sig},\n      ..ex} 3\n  | declaration.inner.View.instance i :=\n    elabDefLike stx decl.modifiers {\n      kind := defLike.kind.View.def,\n      Name := i.Name.getOrElse {id := Name.anonymous},\n      sig := {..i.sig},\n      ..i} 4\n\n  | declaration.inner.View.inductive ind@{\u00abclass\u00bb := none, sig := {params := bracketedBinders.View.simple bbs}, ..} := do\n    let mdata := MData.empty.setName `command `inductives,\n    mods \u2190 declModifiersToPexpr decl.modifiers,\n    attrs \u2190 attrsToPexpr (match decl.modifiers.attrs with\n      | some attrs := attrs.attrs\n      | none       := []),\n    let mutAttrs := Expr.mkCapp `_ [attrs],\n    match ind.oldUnivParams with\n    | some uparams :=\n      modifyCurrentScope $ \u03bb sc, {sc with univs :=\n        (uparams.ids.map mangleIdent).foldl (\u03bb m id, OrderedRBMap.insert m id (Level.Param id)) sc.univs}\n    | none := pure (),\n    let uparams := namesToPexpr $ match ind.oldUnivParams with\n    | some uparams := uparams.ids.map mangleIdent\n    | none := [],\n    let id := mangleIdent ind.Name.id,\n    let type := getOptType ind.sig.type,\n    type \u2190 toPexpr type,\n    let indL := Expr.local id id type BinderInfo.default,\n    let inds := Expr.mkCapp `_ [indL],\n    params \u2190 simpleBindersToPexpr bbs,\n    introRules \u2190 ind.introRules.mmap (\u03bb (r : introRule.View), do\n      ({params := bracketedBinders.View.simple [], type := some ty}) \u2190 pure r.sig\n        | error stx \"declaration.elaborate: unexpected input\",\n      type \u2190 toPexpr ty.type,\n      let Name := mangleIdent r.Name,\n      pure $ Expr.local Name Name type BinderInfo.default),\n    let introRules := Expr.mkCapp `_ introRules,\n    let introRules := Expr.mkCapp `_ [introRules],\n    let inferKinds := ind.introRules.map $ \u03bb (r : introRule.View), inferModToPexpr r.inferMod,\n    let inferKinds := Expr.mkCapp `_ inferKinds,\n    let inferKinds := Expr.mkCapp `_ [inferKinds],\n    oldElabCommand stx $ Expr.mdata mdata $\n      Expr.mkCapp `_ [mods, mutAttrs, uparams, inds, params, introRules, inferKinds]\n\n  | declaration.inner.View.structure s@{keyword := structureKw.View.structure _, sig := {params := bracketedBinders.View.simple bbs}, ..} := do\n    let mdata := MData.empty.setName `command `structure,\n    mods \u2190 declModifiersToPexpr decl.modifiers,\n    match s.oldUnivParams with\n    | some uparams :=\n      modifyCurrentScope $ \u03bb sc, {sc with univs :=\n        (uparams.ids.map mangleIdent).foldl (\u03bb m id, OrderedRBMap.insert m id (Level.Param id)) sc.univs}\n    | none := pure (),\n    let uparams := namesToPexpr $ match s.oldUnivParams with\n    | some uparams := uparams.ids.map mangleIdent\n    | none := [],\n    let Name := mangleIdent s.Name.id,\n    let Name := Expr.local Name Name dummy BinderInfo.default,\n    let type := getOptType s.sig.type,\n    type \u2190 toPexpr type,\n    params \u2190 simpleBindersToPexpr bbs,\n    let parents := match s.extends with\n    | some ex := ex.parents\n    | none    := [],\n    parents \u2190 parents.mmap (toPexpr \u2218 SepBy.Elem.View.item),\n    let parents := Expr.mkCapp `_ parents,\n    let mk := match s.ctor with\n    | some ctor := mangleIdent ctor.Name\n    | none      := `mk,\n    let mk := Expr.local mk mk dummy BinderInfo.default,\n    let infer := inferModToPexpr (s.ctor >>= structureCtor.View.inferMod),\n    fieldBlocks \u2190 s.fieldBlocks.mmap (\u03bb bl, do\n      (bi, content) \u2190 match bl with\n        | structureFieldBlock.View.explicit {content := structExplicitBinderContent.View.notation _} :=\n          error stx \"declaration.elaborate: unexpected input\"\n        | structureFieldBlock.View.explicit {content := structExplicitBinderContent.View.other c} :=\n          pure (BinderInfo.default, c)\n        | structureFieldBlock.View.implicit {content := c} := pure (BinderInfo.implicit, c)\n        | structureFieldBlock.View.strictImplicit {content := c} := pure (BinderInfo.strictImplicit, c)\n        | structureFieldBlock.View.instImplicit {content := c} := pure (BinderInfo.instImplicit, c),\n      let bi := Expr.local `_ `_ dummy bi,\n      let ids := namesToPexpr $ content.ids.map mangleIdent,\n      let kind := inferModToPexpr content.inferMod,\n      let type := getOptType content.sig.type,\n      type \u2190 toPexpr type,\n      pure $ Expr.mkCapp `_ [bi, ids, kind, type]),\n    let fieldBlocks := Expr.mkCapp `_ fieldBlocks,\n    oldElabCommand stx $ Expr.mdata mdata $\n      Expr.mkCapp `_ [mods, uparams, Name, params, parents, type, mk, infer, fieldBlocks]\n  | _ :=\n    error stx \"declaration.elaborate: unexpected input\"\n\ndef variables.elaborate : Elaborator :=\n\u03bb stx, do\n  let mdata := MData.empty.setName `command `variables,\n  let v := view \u00abvariables\u00bb stx,\n  vars \u2190 match v.binders with\n  | bracketedBinders.View.simple bbs := bbs.mfilter $ \u03bb b, do\n    let (bi, id, type) := b.toBinderInfo,\n    if type.isOfKind bindingAnnotationUpdate then do\n      sc \u2190 currentScope,\n      let id := mangleIdent id,\n      match sc.vars.find id with\n      | some (_, v) :=\n        modifyCurrentScope $ \u03bb sc, {sc with vars :=\n          sc.vars.insert id {v with BinderInfo := bi}}\n      | none := error (Syntax.ident id) \"\",\n      pure false\n    else pure true\n  | _ := error stx \"variables.elaborate: unexpected input\",\n  vars \u2190 simpleBindersToPexpr vars,\n  oldElabCommand stx $ Expr.mdata mdata vars\n\ndef include.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := view \u00abinclude\u00bb stx,\n  -- TODO(Sebastian): error checking\n  modifyCurrentScope $ \u03bb sc, {sc with includeVars :=\n    v.ids.foldl (\u03bb vars v, vars.insert $ mangleIdent v) sc.includeVars}\n\n-- TODO: RBMap.remove\n/-\ndef omit.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := View \u00abomit\u00bb stx,\n  modify $ \u03bb st, {st with localState := {sc with includeVars :=\n    v.ids.foldl (\u03bb vars v, vars.remove $ mangleIdent v) sc.includeVars}}\n-/\n\ndef Module.header.elaborate : Elaborator :=\n\u03bb stx, do\n  let header := view Module.header stx,\n  match header with\n  | {\u00abprelude\u00bb := some _, imports := []} := pure ()\n  | _ := error stx \"not implemented: imports\"\n\ndef precToNat : Option precedence.View \u2192 Nat\n| (some prec) := prec.Term.toNat\n| none        := 0\n\n-- TODO(Sebastian): Command parsers like `structure` will need access to these\ndef CommandParserConfig.registerNotationTokens (spec : NotationSpec.View) (cfg : CommandParserConfig) :\n  Except String CommandParserConfig :=\ndo spec.rules.mfoldl (\u03bb (cfg : CommandParserConfig) r, match r.symbol with\n   | notationSymbol.View.quoted {symbol := some a, prec := prec, ..} :=\n     pure {cfg with tokens := cfg.tokens.insert a.val.trim {\u00abprefix\u00bb := a.val.trim, lbp := precToNat prec}}\n   | _ := throw \"registerNotationTokens: unreachable\") cfg\n\ndef CommandParserConfig.registerNotationParser (k : SyntaxNodeKind) (nota : notation.View)\n  (cfg : CommandParserConfig) : Except String CommandParserConfig :=\ndo -- build and register Parser\n   ps \u2190 nota.spec.rules.mmap (\u03bb r : rule.View, do\n     psym \u2190 match r.symbol with\n     | notationSymbol.View.quoted {symbol := some a ..} :=\n       pure (symbol a.val : termParser)\n     | _ := throw \"registerNotationParser: unreachable\",\n     ptrans \u2190 match r.transition with\n     | some (transition.View.binder b) :=\n       pure $ some $ Term.binderIdent.Parser\n     | some (transition.View.binders b) :=\n       pure $ some $ Term.binders.Parser\n     | some (transition.View.Arg {action := none, ..}) :=\n       pure $ some Term.Parser\n     | some (transition.View.Arg {action := some {kind := actionKind.View.prec prec}, ..}) :=\n       pure $ some $ Term.Parser prec.toNat\n     | some (transition.View.Arg {action := some {kind := actionKind.View.scoped sc}, ..}) :=\n       pure $ some $ Term.Parser $ precToNat sc.prec\n     | none := pure $ none\n     | _ := throw \"registerNotationParser: unimplemented\",\n     pure $ psym::ptrans.toMonad\n   ),\n   firstRule::_ \u2190 pure nota.spec.rules | throw \"registerNotationParser: unreachable\",\n   firstTk \u2190 match firstRule.symbol with\n   | notationSymbol.View.quoted {symbol := some a ..} :=\n     pure a.val.trim\n   | _ := throw \"registerNotationParser: unreachable\",\n   let ps := ps.bind id,\n   cfg \u2190 match nota.local, nota.spec.prefixArg with\n   | none,   none   := pure {cfg with leadingTermParsers :=\n     cfg.leadingTermParsers.insert firstTk $ Parser.Combinators.node k ps}\n   | some _, none   := pure {cfg with localLeadingTermParsers :=\n     cfg.localLeadingTermParsers.insert firstTk $ Parser.Combinators.node k ps}\n   | none,   some _ := pure {cfg with trailingTermParsers :=\n     cfg.trailingTermParsers.insert firstTk $ Parser.Combinators.node k (getLeading::ps.map coe)}\n   | some _, some _ := pure {cfg with localTrailingTermParsers :=\n     cfg.localTrailingTermParsers.insert firstTk $ Parser.Combinators.node k (getLeading::ps.map coe)},\n   pure cfg\n\n/-- Recreate `ElaboratorState.parserCfg` from the Elaborator State and the initial config,\n    effectively treating it as a cache. -/\ndef updateParserConfig : ElaboratorM Unit :=\ndo st \u2190 get,\n   sc \u2190 currentScope,\n   cfg \u2190 read,\n   let ccfg := cfg.initialParserCfg.toCommandParserConfig,\n   ccfg \u2190 st.reservedNotations.mfoldl (\u03bb ccfg rnota,\n     match CommandParserConfig.registerNotationTokens rnota.spec ccfg with\n     | Except.ok ccfg := pure ccfg\n     | Except.error e := error (review reserveNotation rnota) e) ccfg,\n   ccfg \u2190 (st.notations ++ sc.notations).mfoldl (\u03bb ccfg nota,\n     match CommandParserConfig.registerNotationTokens nota.nota.spec ccfg >>=\n               CommandParserConfig.registerNotationParser nota.kind nota.nota with\n     | Except.ok ccfg := pure ccfg\n     | Except.error e := error (review \u00abnotation\u00bb nota.nota) e) ccfg,\n   set {st with parserCfg := {cfg.initialParserCfg with toCommandParserConfig := ccfg}}\n\ndef postprocessNotationSpec (spec : NotationSpec.View) : NotationSpec.View :=\n-- default leading tokens to `max`\n-- NOTE: should happen after copying precedences from reserved notation\nmatch spec with\n| {prefixArg := none, rules := r@{symbol := notationSymbol.View.quoted sym@{prec := none, ..}, ..}::rs} :=\n  {spec with rules := {r with symbol := notationSymbol.View.quoted {sym with prec := some\n    {Term := precedenceTerm.View.lit $ precedenceLit.View.num $ number.View.ofNat maxPrec}\n  }}::rs}\n| _ := spec\n\ndef reserveNotation.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := view reserveNotation stx,\n  let v := {v with spec := postprocessNotationSpec v.spec},\n  -- TODO: sanity checks?\n  modify $ \u03bb st, {st with reservedNotations := v::st.reservedNotations},\n  updateParserConfig\n\ndef matchPrecedence : Option precedence.View \u2192 Option precedence.View \u2192 Bool\n| none      (some rp) := true\n| (some sp) (some rp) := sp.Term.toNat = rp.Term.toNat\n| _         _         := false\n\n/-- Check if a notation is compatible with a reserved notation, and if so, copy missing\n    precedences in the notation from the reserved notation. -/\ndef matchSpec (spec reserved : NotationSpec.View) : Option NotationSpec.View :=\ndo guard $ spec.prefixArg.isSome = reserved.prefixArg.isSome,\n   rules \u2190 (spec.rules.zip reserved.rules).mmap $ \u03bb \u27e8sr, rr\u27e9, do {\n     notationSymbol.View.quoted sq@{symbol := some sa, ..} \u2190 pure sr.symbol\n       | failure,\n     notationSymbol.View.quoted rq@{symbol := some ra, ..} \u2190 pure rr.symbol\n       | failure,\n     guard $ sa.val.trim = ra.val.trim,\n     guard $ matchPrecedence sq.prec rq.prec,\n     st \u2190 match sr.transition, rr.transition with\n     | some (transition.View.binder sb), some (transition.View.binder rb) :=\n       guard (matchPrecedence sb.prec rb.prec) *> pure rr.transition\n     | some (transition.View.binders sb), some (transition.View.binders rb) :=\n       guard (matchPrecedence sb.prec rb.prec) *> pure rr.transition\n     | some (transition.View.Arg sarg), some (transition.View.Arg rarg) := do\n       sact \u2190 match action.View.kind <$> sarg.action, action.View.kind <$> rarg.action with\n       | some (actionKind.View.prec sp), some (actionKind.View.prec rp) :=\n         guard (sp.toNat = rp.toNat) *> pure sarg.action\n       | none,                            some (actionKind.View.prec rp) :=\n         pure rarg.action\n       | _, _ := failure,\n       pure $ some $ transition.View.Arg {sarg with action := sact}\n     | none,    none    := pure none\n     | _,       _       := failure,\n     pure $ {rule.View .\n       symbol := notationSymbol.View.quoted rq,\n       transition := st}\n   },\n   pure $ {spec with rules := rules}\n\ndef notation.elaborateAux : notation.View \u2192 ElaboratorM notation.View :=\n\u03bb nota, do\n  st \u2190 get,\n  -- check reserved notations\n  matched \u2190 pure $ st.reservedNotations.filterMap $\n    \u03bb rnota, matchSpec nota.spec rnota.spec,\n  nota \u2190 match matched with\n  | [matched] := pure {nota with spec := matched}\n  | []        := pure nota\n  | _         := error (review \u00abnotation\u00bb nota) \"invalid notation, matches multiple reserved notations\",\n  -- TODO: sanity checks\n  pure {nota with spec := postprocessNotationSpec nota.spec}\n\n-- TODO(Sebastian): better kind names, Module prefix?\ndef mkNotationKind : ElaboratorM SyntaxNodeKind :=\ndo st \u2190 get,\n   set {st with notationCounter := st.notationCounter + 1},\n   pure {name := (`_notation).mkNumeral st.notationCounter}\n\n/-- Register a notation in the Expander. Unlike with notation parsers, there is no harm in\n    keeping local notation macros registered after closing a section. -/\ndef registerNotationMacro (nota : notation.View) : ElaboratorM NotationMacro :=\ndo k \u2190 mkNotationKind,\n   let m : NotationMacro := \u27e8k, nota\u27e9,\n   let transf := mkNotationTransformer m,\n   modify $ \u03bb st, {st with expanderCfg := {st.expanderCfg with transformers := st.expanderCfg.transformers.insert k.name transf}},\n   pure m\n\ndef notation.elaborate : Elaborator :=\n\u03bb stx, do\n  let nota := view \u00abnotation\u00bb stx,\n  -- HACK: ignore List Literal notation using :fold\n  let usesFold := nota.spec.rules.any $ \u03bb r, match r.transition with\n    | some (transition.View.Arg {action := some {kind := actionKind.View.fold _, ..}, ..}) := true\n    | _ := false,\n  if usesFold then do {\n    cfg \u2190 read,\n    modify $ \u03bb st, {st with messages := st.messages.add {filename := cfg.filename, pos := \u27e81,0\u27e9,\n      severity := MessageSeverity.warning, text := \"ignoring notation using 'fold' action\"}}\n  } else do {\n    nota \u2190 notation.elaborateAux nota,\n    m \u2190 registerNotationMacro nota,\n    match nota.local with\n      | some _ := modifyCurrentScope $ \u03bb sc, {sc with notations := m::sc.notations}\n      | none   := modify $ \u03bb st, {st with notations := m::st.notations},\n    updateParserConfig\n  }\n\ndef universe.elaborate : Elaborator :=\n\u03bb stx, do\n  let univ := view \u00abuniverse\u00bb stx,\n  let id := mangleIdent univ.id,\n  sc \u2190 currentScope,\n  match sc.univs.find id with\n  | none   := modifyCurrentScope $ \u03bb sc, {sc with univs := sc.univs.insert id (Level.Param id)}\n  | some _ := error stx $ \"a universe named '\" ++ toString id ++ \"' has already been declared in this Scope\"\n\ndef attribute.elaborate : Elaborator :=\n\u03bb stx, do\n  let attr := view \u00abattribute\u00bb stx,\n  let mdata := MData.empty.setName `command `attribute,\n  let mdata := mdata.setBool `local $ attr.local.isSome,\n  attrs \u2190 attrsToPexpr attr.attrs,\n  ids \u2190 attr.ids.mmap (\u03bb id, match id.preresolved with\n    | []  := error (Syntax.ident id) $ \"unknown identifier '\" ++ toString id.val ++ \"'\"\n    | [c] := pure $ Expr.const c []\n    | _   := error (Syntax.ident id) \"invalid 'attribute' command, identifier is ambiguous\"),\n  let ids := Expr.mkCapp `_ ids,\n  oldElabCommand stx $ Expr.mdata mdata $ Expr.app attrs ids\n\ndef check.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := view check stx,\n  let mdata := MData.empty.setName `command `#check,\n  e \u2190 toPexpr v.Term,\n  oldElabCommand stx $ Expr.mdata mdata e\n\ndef open.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := view \u00abopen\u00bb stx,\n  -- TODO: do eager sanity checks (namespace does not exist, etc.)\n  modifyCurrentScope $ \u03bb sc, {sc with openDecls := sc.openDecls ++ v.spec}\n\ndef export.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := view \u00abexport\u00bb stx,\n  ns \u2190 getNamespace,\n  -- TODO: do eager sanity checks (namespace does not exist, etc.)\n  modify $ \u03bb st, {st with exportDecls := st.exportDecls ++ v.spec.map (\u03bb spec, \u27e8ns, spec\u27e9)}\n\ndef initQuot.elaborate : Elaborator :=\n\u03bb stx, oldElabCommand stx $ Expr.mdata (MData.empty.setName `command `initQuot) dummy\n\ndef setOption.elaborate : Elaborator :=\n\u03bb stx, do\n  let v := view \u00absetOption\u00bb stx,\n  let opt := v.opt.val,\n  sc \u2190 currentScope,\n  let opts := sc.Options,\n  -- TODO(Sebastian): check registered Options\n  let opts := match v.val with\n  | optionValue.View.Bool b := opts.setBool opt (match b with boolOptionValue.View.True _ := true | _ := false)\n  | optionValue.View.String lit := match lit.value with\n    | some s := opts.setString opt s\n    | none   := opts  -- Parser already failed\n  | optionValue.View.num lit := opts.setNat opt lit.toNat,\n  modifyCurrentScope $ \u03bb sc, {sc with Options := opts}\n\n/-- List of commands: recursively elaborate each command. -/\ndef noKind.elaborate : Elaborator := \u03bb stx, do\n  some n \u2190 pure stx.asNode\n    | error stx \"noKind.elaborate: unreachable\",\n  n.args.mfor command.elaborate\n\ndef end.elaborate : Elaborator :=\n\u03bb cmd, do\n  let v := view \u00abend\u00bb cmd,\n  st \u2190 get,\n  -- NOTE: bottom-most (Module) Scope cannot be closed\n  sc::sc'::scps \u2190 pure st.scopes\n    | error cmd \"invalid 'end', there is no open Scope to end\",\n  let endName := mangleIdent $ v.Name.getOrElse Name.anonymous,\n  when (endName \u2260 sc.header) $\n    error cmd $ \"invalid end of \" ++ sc.cmd ++ \", expected Name '\" ++\n      toString sc.header ++ \"'\",\n  set {st with scopes := sc'::scps},\n  -- local notations may have vanished\n  updateParserConfig\n\ndef section.elaborate : Elaborator :=\n\u03bb cmd, do\n  let sec := view \u00absection\u00bb cmd,\n  let header := mangleIdent $ sec.Name.getOrElse Name.anonymous,\n  sc \u2190 currentScope,\n  modify $ \u03bb st, {st with scopes := {sc with cmd := \"section\", header := header}::st.scopes}\n\ndef namespace.elaborate : Elaborator :=\n\u03bb cmd, do\n  let v := view \u00abnamespace\u00bb cmd,\n  let header := mangleIdent v.Name,\n  sc \u2190 currentScope,\n  ns \u2190 getNamespace,\n  let sc' := {sc with cmd := \"namespace\", header := header, nsStack := (ns ++ header)::sc.nsStack},\n  modify $ \u03bb st, {st with scopes := sc'::st.scopes}\n\ndef eoi.elaborate : Elaborator :=\n\u03bb cmd, do\n  st \u2190 get,\n  when (st.scopes.length > 1) $\n    error cmd \"invalid end of input, expected 'end'\"\n\n-- TODO(Sebastian): replace with attribute\ndef elaborators : RBMap Name Elaborator Name.quickLt := RBMap.fromList [\n  (Module.header.name, Module.header.elaborate),\n  (notation.name, notation.elaborate),\n  (reserveNotation.name, reserveNotation.elaborate),\n  (universe.name, universe.elaborate),\n  (noKind.name, noKind.elaborate),\n  (end.name, end.elaborate),\n  (section.name, section.elaborate),\n  (namespace.name, namespace.elaborate),\n  (variables.name, variables.elaborate),\n  (include.name, include.elaborate),\n  --(omit.name, omit.elaborate),\n  (declaration.name, declaration.elaborate),\n  (attribute.name, attribute.elaborate),\n  (open.name, open.elaborate),\n  (export.name, export.elaborate),\n  (check.name, check.elaborate),\n  (initQuot.name, initQuot.elaborate),\n  (setOption.name, setOption.elaborate),\n  (Module.eoi.name, eoi.elaborate)\n] _\n\n-- TODO: optimize\ndef isOpenNamespace (sc : Scope) : Name \u2192 Bool\n| Name.anonymous := true\n| ns :=\n  -- check surrounding namespaces\n  ns \u2208 sc.nsStack \u2228\n  -- check opened namespaces\n  sc.openDecls.any (\u03bb od, od.id.val = ns) \u2228\n  -- TODO: check active exports\n  false\n\n-- TODO: `hiding`, `as`, `renaming`\ndef matchOpenSpec (n : Name) (spec : openSpec.View) : Option Name :=\nlet matchesOnly := match spec.only with\n| none := true\n| some only := n = only.id.val \u2228 only.ids.any (\u03bb id, n = id.val) in\nif matchesOnly then some (spec.id.val ++ n) else none\n\ndef resolveContext : Name \u2192 ElaboratorM (List Name)\n| n := do\n  st \u2190 get,\n  sc \u2190 currentScope, pure $\n\n  -- TODO(Sebastian): check the interaction betwen preresolution and section variables\n  match sc.vars.find n with\n  | some (_, v) := [v.uniqName]\n  | _ :=\n\n  -- global resolution\n\n  -- check surrounding namespaces first\n  -- TODO: check for `protected`\n  match sc.nsStack.filter (\u03bb ns, st.env.contains (ns ++ n)) with\n  | ns::_ := [ns ++ n] -- prefer innermost namespace\n  | _ :=\n\n  -- check environment directly\n  (let unrooted := n.replacePrefix `_root_ Name.anonymous in\n   match st.env.contains unrooted with\n   | true := [unrooted]\n   | _ := [])\n  ++\n  -- check opened namespaces\n  (let ns' := sc.openDecls.filterMap (matchOpenSpec n) in\n   ns'.filter (\u03bb n', st.env.contains n'))\n  ++\n  -- check active exports\n  -- TODO: optimize\n  -- TODO: Lean 3 activates an export in `foo` even on `open foo (specificThing)`, but does that make sense?\n  (let eds' := st.exportDecls.filter (\u03bb ed, isOpenNamespace sc ed.inNs) in\n   let ns' := eds'.filterMap (\u03bb ed, matchOpenSpec n ed.spec) in\n   ns'.filter (\u03bb n', st.env.contains n'))\n\n  -- TODO: projection notation\n\npartial def preresolve : Syntax \u2192 ElaboratorM Syntax\n| (Syntax.ident id) := do\n  let n := mangleIdent id,\n  ns \u2190 resolveContext n,\n  pure $ Syntax.ident {id with preresolved := ns ++ id.preresolved}\n| (Syntax.rawNode n) := do\n  args \u2190 n.args.mmap preresolve,\n  pure $ Syntax.rawNode {n with args := args}\n| stx := pure stx\n\ndef mkState (cfg : ElaboratorConfig) (env : Environment) (opts : Options) : ElaboratorState := {\n  parserCfg := cfg.initialParserCfg,\n  expanderCfg := {transformers := Expander.builtinTransformers, ..cfg},\n  env := env,\n  ngen := \u27e8`_ngen.fixme, 0\u27e9,\n  scopes := [{cmd := \"MODULE\", header := `MODULE, Options := opts}]}\n\ndef processCommand (cfg : ElaboratorConfig) (st : ElaboratorState) (cmd : Syntax) : ElaboratorState :=\nlet st := {st with messages := MessageLog.empty} in\nlet r := @ExceptT.run _ Id _ $ flip StateT.run st $ flip ReaderT.run cfg $ RecT.run\n  (command.elaborate cmd)\n  (\u03bb _, error cmd \"Elaborator.run: recursion depth exceeded\")\n  (\u03bb cmd, do\n    some n \u2190 pure cmd.asNode |\n      error cmd $ \"not a command: \" ++ toString cmd,\n    some elab \u2190 pure $ elaborators.find n.kind.name |\n      error cmd $ \"unknown command: \" ++ toString n.kind.name,\n    cmd' \u2190 preresolve cmd,\n    elab cmd') in\nmatch r with\n| Except.ok ((), st) := st\n| Except.error e     := {st with messages := st.messages.add e}\n\nend Elaborator\nend Lean\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/tmp/new-frontend/elaborator.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434481176187, "lm_q2_score": 0.01744248543849965, "lm_q1q2_score": 0.002758953706123379}}
{"text": "/-\nCopyright (c) 2021 Wojciech Nawrocki. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki, Marc Huisinga\n-/\nimport Lean.DeclarationRange\n\nimport Lean.Data.Json\nimport Lean.Data.Lsp\nimport Lean.Elab.Command\n\nimport Lean.Server.FileSource\nimport Lean.Server.FileWorker.Utils\n\nimport Lean.Server.Rpc.Basic\n\nnamespace Lean.Server\n\nstructure RequestError where\n  code    : JsonRpc.ErrorCode\n  message : String\n  deriving Inhabited\n\nnamespace RequestError\nopen JsonRpc\n\ndef fileChanged : RequestError :=\n  { code := ErrorCode.contentModified\n    message := \"File changed.\" }\n\ndef methodNotFound (method : String) : RequestError :=\n  { code := ErrorCode.methodNotFound\n    message := s!\"No request handler found for '{method}'\" }\n\ndef invalidParams (message : String) : RequestError :=\n  {code := ErrorCode.invalidParams, message}\n\ndef internalError (message : String) : RequestError :=\n  { code := ErrorCode.internalError, message }\n\ndef ofException (e : Lean.Exception) : IO RequestError :=\n  return internalError (\u2190 e.toMessageData.toString)\n\ndef ofIoError (e : IO.Error) : RequestError :=\n  internalError (toString e)\n\ndef toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=\n  { id := id\n    code := e.code\n    message := e.message }\n\nend RequestError\n\ndef parseRequestParams (paramType : Type) [FromJson paramType] (params : Json)\n    : Except RequestError paramType :=\n  fromJson? params |>.mapError fun inner =>\n    { code := JsonRpc.ErrorCode.parseError\n      message := s!\"Cannot parse request params: {params.compress}\\n{inner}\" }\n\nstructure RequestContext where\n  rpcSessions   : RBMap UInt64 (IO.Ref FileWorker.RpcSession) compare\n  srcSearchPath : SearchPath\n  doc           : FileWorker.EditableDocument\n  hLog          : IO.FS.Stream\n  hOut          : IO.FS.Stream\n  initParams    : Lsp.InitializeParams\n\nabbrev RequestTask \u03b1 := Task (Except RequestError \u03b1)\nabbrev RequestT m := ReaderT RequestContext <| ExceptT RequestError m\n/-- Workers execute request handlers in this monad. -/\nabbrev RequestM := ReaderT RequestContext <| EIO RequestError\n\nabbrev RequestTask.pure (a : \u03b1) : RequestTask \u03b1 := .pure (.ok a)\n\ninstance : MonadLift IO RequestM where\n  monadLift x := do\n    match \u2190  x.toBaseIO with\n    | .error e => throw <| RequestError.ofIoError e\n    | .ok v => return v\n\ninstance : MonadLift (EIO Exception) RequestM where\n  monadLift x := do\n    match \u2190  x.toBaseIO with\n    | .error e => throw <| \u2190 RequestError.ofException e\n    | .ok v => return v\n\nnamespace RequestM\nopen FileWorker\nopen Snapshots\n\ndef readDoc [Monad m] [MonadReaderOf RequestContext m] : m EditableDocument := do\n  let rc \u2190 readThe RequestContext\n  return rc.doc\n\ndef asTask (t : RequestM \u03b1) : RequestM (RequestTask \u03b1) := do\n  let rc \u2190 readThe RequestContext\n  let t \u2190 EIO.asTask <| t.run rc\n  return t.map liftExcept\n\ndef mapTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM \u03b2) : RequestM (RequestTask \u03b2) := do\n  let rc \u2190 readThe RequestContext\n  let t \u2190 EIO.mapTask (f \u00b7 rc) t\n  return t.map liftExcept\n\ndef bindTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM (RequestTask \u03b2)) : RequestM (RequestTask \u03b2) := do\n  let rc \u2190 readThe RequestContext\n  EIO.bindTask t (f \u00b7 rc)\n\ndef waitFindSnapAux (notFoundX abortedX : RequestM \u03b1) (x : Snapshot \u2192 RequestM \u03b1)\n    : Except ElabTaskError (Option Snapshot) \u2192 RequestM \u03b1\n  /- The elaboration task that we're waiting for may be aborted if the file contents change.\n  In that case, we reply with the `fileChanged` error by default. Thanks to this, the server doesn't\n  get bogged down in requests for an old state of the document. -/\n  | Except.error FileWorker.ElabTaskError.aborted => abortedX\n  | Except.error (FileWorker.ElabTaskError.ioError e) =>\n    throw (RequestError.ofIoError e)\n  | Except.ok none => notFoundX\n  | Except.ok (some snap) => x snap\n\n/-- Create a task which waits for the first snapshot matching `p`, handles various errors,\nand if a matching snapshot was found executes `x` with it. If not found, the task executes\n`notFoundX`. -/\ndef withWaitFindSnap (doc : EditableDocument) (p : Snapshot \u2192 Bool)\n    (notFoundX : RequestM \u03b2)\n    (x : Snapshot \u2192 RequestM \u03b2)\n    (abortedX : RequestM \u03b2 := throwThe RequestError .fileChanged)\n    : RequestM (RequestTask \u03b2) := do\n  let findTask := doc.cmdSnaps.waitFind? p\n  mapTask findTask <| waitFindSnapAux notFoundX abortedX x\n\n/-- See `withWaitFindSnap`. -/\ndef bindWaitFindSnap (doc : EditableDocument) (p : Snapshot \u2192 Bool)\n    (notFoundX : RequestM (RequestTask \u03b2))\n    (x : Snapshot \u2192 RequestM (RequestTask \u03b2))\n    (abortedX : RequestM (RequestTask \u03b2) := throwThe RequestError .fileChanged)\n    : RequestM (RequestTask \u03b2) := do\n  let findTask := doc.cmdSnaps.waitFind? p\n  bindTask findTask <| waitFindSnapAux notFoundX abortedX x\n\n/-- Create a task which waits for the snapshot containing `lspPos` and executes `f` with it.\nIf no such snapshot exists, the request fails with an error. -/\ndef withWaitFindSnapAtPos\n    (lspPos : Lsp.Position)\n    (f : Snapshots.Snapshot \u2192 RequestM \u03b1)\n    : RequestM (RequestTask \u03b1) := do\n  let doc \u2190 readDoc\n  let pos := doc.meta.text.lspPosToUtf8Pos lspPos\n  withWaitFindSnap doc (fun s => s.endPos >= pos)\n    (notFoundX := throw \u27e8.invalidParams, s!\"no snapshot found at {lspPos}\"\u27e9)\n    (x := f)\n\nopen Elab.Command in\ndef runCommandElabM (snap : Snapshot) (c : RequestT CommandElabM \u03b1) : RequestM \u03b1 := do\n  let rc \u2190 readThe RequestContext\n  match \u2190 snap.runCommandElabM rc.doc.meta (c.run rc) with\n  | .ok v => return v\n  | .error e => throw e\n\ndef runCoreM (snap : Snapshot) (c : RequestT CoreM \u03b1) : RequestM \u03b1 := do\n  let rc \u2190 readThe RequestContext\n  match \u2190 snap.runCoreM rc.doc.meta (c.run rc) with\n  | .ok v => return v\n  | .error e => throw e\n\nopen Elab.Term in\ndef runTermElabM (snap : Snapshot) (c : RequestT TermElabM \u03b1) : RequestM \u03b1 := do\n  let rc \u2190 readThe RequestContext\n  match \u2190 snap.runTermElabM rc.doc.meta (c.run rc) with\n  | .ok v => return v\n  | .error e => throw e\n\nend RequestM\n\n/-! # The global request handlers table\n\nWe maintain a global map of LSP request handlers. This allows user code such as plugins\nto register its own handlers, for example to support ITP functionality such as goal state\nvisualization.\n\nFor details of how to register one, see `registerLspRequestHandler`. -/\nsection HandlerTable\nopen Lsp\n\nstructure RequestHandler where\n  fileSource : Json \u2192 Except RequestError Lsp.DocumentUri\n  handle : Json \u2192 RequestM (RequestTask Json)\n\nbuiltin_initialize requestHandlers : IO.Ref (PersistentHashMap String RequestHandler) \u2190\n  IO.mkRef {}\n\n/-- NB: This method may only be called in `initialize` blocks (user or builtin).\n\nA registration consists of:\n- a type of JSON-parsable request data `paramType`\n- a `FileSource` instance for it so the system knows where to route requests\n- a type of JSON-serializable response data `respType`\n- an actual `handler` which runs in the `RequestM` monad and is expected\n  to produce an asynchronous `RequestTask` which does any waiting/computation\n\nA handler task may be cancelled at any time, so it should check the cancellation token when possible\nto handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client\nas LSP error responses. -/\ndef registerLspRequestHandler (method : String)\n    paramType [FromJson paramType] [FileSource paramType]\n    respType [ToJson respType]\n    (handler : paramType \u2192 RequestM (RequestTask respType)) : IO Unit := do\n  if !(\u2190 Lean.initializing) then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': only possible during initialization\"\n  if (\u2190 requestHandlers.get).contains method then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': already registered\"\n  let fileSource := fun j =>\n    parseRequestParams paramType j |>.map Lsp.fileSource\n  let handle := fun j => do\n    let params \u2190 liftExcept <| parseRequestParams paramType j\n    let t \u2190 handler params\n    pure <| t.map <| Except.map ToJson.toJson\n\n  requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }\n\ndef lookupLspRequestHandler (method : String) : IO (Option RequestHandler) :=\n  return (\u2190 requestHandlers.get).find? method\n\n/-- NB: This method may only be called in `initialize` blocks (user or builtin).\n\nRegister another handler to invoke after the last one registered for a method.\nAt least one handler for the method must have already been registered to perform\nchaining.\n\nFor more details on the registration of a handler, see `registerLspRequestHandler`. -/\ndef chainLspRequestHandler (method : String)\n    paramType [FromJson paramType]\n    respType [FromJson respType] [ToJson respType]\n    (handler : paramType \u2192 RequestTask respType \u2192 RequestM (RequestTask respType)) : IO Unit := do\n  if !(\u2190 Lean.initializing) then\n    throw <| IO.userError s!\"Failed to chain LSP request handler for '{method}': only possible during initialization\"\n  if let some oldHandler \u2190 lookupLspRequestHandler method then\n    let handle := fun j => do\n      let t \u2190 oldHandler.handle j\n      let t := t.map fun x => x.bind fun j => FromJson.fromJson? j |>.mapError fun e =>\n        .internalError s!\"Failed to parse original LSP response for `{method}` when chaining: {e}\"\n      let params \u2190 liftExcept <| parseRequestParams paramType j\n      let t \u2190 handler params t\n      pure <| t.map <| Except.map ToJson.toJson\n\n    requestHandlers.modify fun rhs => rhs.insert method {oldHandler with handle}\n  else\n    throw <| IO.userError s!\"Failed to chain LSP request handler for '{method}': no initial handler registered\"\n\ndef routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => return Except.error <| RequestError.methodNotFound method\n  | some rh => return rh.fileSource params\n\ndef handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none =>\n    throw <| .internalError\n      s!\"request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?\"\n  | some rh => rh.handle params\n\nend HandlerTable\nend Lean.Server\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/Server/Requests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07921031976169719, "lm_q2_score": 0.03461883522865867, "lm_q1q2_score": 0.0027421690082395605}}
{"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 Exception monad transformer using CPS style.\n-/\n\ndef ExceptCpsT (\u03b5 : Type u) (m : Type u \u2192 Type v) (\u03b1 : Type u) := (\u03b2 : Type u) \u2192 (\u03b1 \u2192 m \u03b2) \u2192 (\u03b5 \u2192 m \u03b2) \u2192 m \u03b2\n\nnamespace ExceptCpsT\n\n@[always_inline, inline]\ndef run {\u03b5 \u03b1 : Type u} [Monad m] (x : ExceptCpsT \u03b5 m \u03b1) : m (Except \u03b5 \u03b1) :=\n  x _ (fun a => pure (Except.ok a)) (fun e => pure (Except.error e))\n\n@[always_inline, inline]\ndef runK {\u03b5 \u03b1 : Type u} (x : ExceptCpsT \u03b5 m \u03b1) (s : \u03b5) (ok : \u03b1 \u2192 m \u03b2) (error : \u03b5 \u2192 m \u03b2) : m \u03b2 :=\n  x _ ok error\n\n@[always_inline, inline]\ndef runCatch [Monad m] (x : ExceptCpsT \u03b1 m \u03b1) : m \u03b1 :=\n  x \u03b1 pure pure\n\n@[always_inline]\ninstance : Monad (ExceptCpsT \u03b5 m) where\n  map f x  := fun _ k\u2081 k\u2082 => x _ (fun a => k\u2081 (f a)) k\u2082\n  pure a   := fun _ k _ => k a\n  bind x f := fun _ k\u2081 k\u2082 => x _ (fun a => f a _ k\u2081 k\u2082) k\u2082\n\ninstance : LawfulMonad (ExceptCpsT \u03c3 m) := by\n  refine' { .. } <;> intros <;> rfl\n\ninstance : MonadExceptOf \u03b5 (ExceptCpsT \u03b5 m) where\n  throw e  := fun _ _ k => k e\n  tryCatch x handle := fun _ k\u2081 k\u2082 => x _ k\u2081 (fun e => handle e _ k\u2081 k\u2082)\n\n@[always_inline, inline]\ndef lift [Monad m] (x : m \u03b1) : ExceptCpsT \u03b5 m \u03b1 :=\n  fun _ k _ => x >>= k\n\ninstance [Monad m] : MonadLift m (ExceptCpsT \u03c3 m) where\n  monadLift := ExceptCpsT.lift\n\ninstance [Inhabited \u03b5] : Inhabited (ExceptCpsT \u03b5 m \u03b1) where\n  default := fun _ _ k\u2082 => k\u2082 default\n\n@[simp] theorem run_pure [Monad m] : run (pure x : ExceptCpsT \u03b5 m \u03b1) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift {\u03b1 \u03b5 : Type u} [Monad m] (x : m \u03b1) : run (ExceptCpsT.lift x : ExceptCpsT \u03b5 m \u03b1) = (x >>= fun a => pure (Except.ok a) : m (Except \u03b5 \u03b1)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptCpsT \u03b5 m \u03b2) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptCpsT \u03b5 m \u03b2) : run (ExceptCpsT.lift x >>= f : ExceptCpsT \u03b5 m \u03b2) = x >>= fun a => run (f a) := rfl\n\n@[simp] theorem run_bind_throw [Monad m] (e : \u03b5) (f : \u03b1 \u2192 ExceptCpsT \u03b5 m \u03b2) : run (throw e >>= f : ExceptCpsT \u03b5 m \u03b2) = run (throw e) := rfl\n\n@[simp] theorem runCatch_pure [Monad m] : runCatch (pure x : ExceptCpsT \u03b1 m \u03b1) = pure x := rfl\n\n@[simp] theorem runCatch_lift {\u03b1 : Type u} [Monad m] [LawfulMonad m] (x : m \u03b1) : runCatch (ExceptCpsT.lift x : ExceptCpsT \u03b1 m \u03b1) = x := by\n  simp [runCatch, lift]\n\n@[simp] theorem runCatch_throw [Monad m] : runCatch (throw a : ExceptCpsT \u03b1 m \u03b1) = pure a := rfl\n\n@[simp] theorem runCatch_bind_lift [Monad m] (x : m \u03b1) (f : \u03b1 \u2192 ExceptCpsT \u03b2 m \u03b2) : runCatch (ExceptCpsT.lift x >>= f : ExceptCpsT \u03b2 m \u03b2) = x >>= fun a => runCatch (f a) := rfl\n\n@[simp] theorem runCatch_bind_throw [Monad m] (e : \u03b2) (f : \u03b1 \u2192 ExceptCpsT \u03b2 m \u03b2) : runCatch (throw e >>= f : ExceptCpsT \u03b2 m \u03b2) = pure e := rfl\n\nend ExceptCpsT\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/ExceptCps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817434878009673, "lm_q2_score": 0.017176711056214933, "lm_q1q2_score": 0.0027169150855006845}}
{"text": "import Std.Tactic.Lint\n\n-- internal names should be ignored\ntheorem Foo.Foo._bar : True := trivial\n\n#lint- only dupNamespace\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/test/lint_dupNamespace.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734719655746, "lm_q2_score": 0.03210070671700818, "lm_q1q2_score": 0.00265464328863129}}
{"text": "/-\n# Elaboration\n\nThe elaborator is the component in charge of turning the user facing\n`Syntax` into something with which the rest of the compiler can work.\nMost of the time, this means translating `Syntax` into `Expr`s but\nthere are also other use cases such as `#check` or `#eval`. Hence the\nelaborator is quite a large piece of code, it lives\n[here](https://github.com/leanprover/lean4/blob/master/src/Lean/Elab).\n\n## Command elaboration\nA command is the highest level of `Syntax`, a Lean file is made\nup of a list of commands. The most commonly used commands are declarations,\nfor example:\n- `def`\n- `inductive`\n- `structure`\n\nbut there are also other ones, most notably `#check`, `#eval` and friends.\nAll commands live in the `command` syntax category so in order to declare\ncustom commands, their syntax has to be registered in that category.\n\n### Giving meaning to commands\nThe next step is giving some semantics to the syntax. With commands, this\nis done by registering a so called command elaborator.\n\nCommand elaborators have type `CommandElab` which is an alias for:\n`Syntax \u2192 CommandElabM Unit`. What they do, is take the `Syntax` that\nrepresents whatever the user wants to call the command and produce some\nsort of side effect on the `CommandElabM` monad, after all the return\nvalue is always `Unit`. The `CommandElabM` monad has 4 main kinds of\nside effects:\n1. Logging messages to the user via the `Monad` extensions\n   `MonadLog` and `AddMessageContext`, like `#check`. This is done via\n   functions that can be found in `Lean.Elab.Log`, the most notable ones\n   being: `logInfo`, `logWarning` and `logError`.\n2. Interacting with the `Environment` via the `Monad` extension `MonadEnv`.\n   This is the place where all of the relevant information for the compiler\n   is stored, all known declarations, their types, doc-strings, values etc.\n   The current environment can be obtained via `getEnv` and set via `setEnv`\n   once it has been modified. Note that quite often wrappers around `setEnv`\n   like `addDecl` are the correct way to add information to the `Environment`.\n3. Performing `IO`, `CommandElabM` is capable of running any `IO` operation.\n   For example reading from files and based on their contents perform\n   declarations.\n4. Throwing errors, since it can run any kind of `IO`, it is only natural\n   that it can throw errors via `throwError`.\n\nFurthermore there are a bunch of other `Monad` extensions that are supported\nby `CommandElabM`:\n- `MonadRef` and `MonadQuotation` for `Syntax` quotations like in macros\n- `MonadOptions` to interact with the options framework\n- `MonadTrace` for debug trace information\n- TODO: There are a few others though I'm not sure whether they are relevant,\n  see the instance in `Lean.Elab.Command`\n\n### Command elaboration\nNow that we understand the type of command elaborators let's take a brief\nlook at how the elaboration process actually works:\n1. Check whether any macros can be applied to the current `Syntax`.\n   If there is a macro that does apply and does not throw an error\n   the resulting `Syntax` is recursively elaborated as a command again.\n2. If no macro can be applied, we search for all `CommandElab`s that have been\n   registered for the `SyntaxKind` of the `Syntax` we are elaborating,\n   using the `command_elab` attribute.\n3. All of these `CommandElab` are then tried in order until one of them does not throw an\n   `unsupportedSyntaxException`, Lean's way of indicating that the elaborator\n   \"feels responsible\"\n   for this specific `Syntax` construct. Note that it can still throw a regular\n   error to indicate to the user that something is wrong. If no responsible\n   elaborator is found, then the command elaboration is aborted with an `unexpected syntax`\n   error message.\n\nAs you can see the general idea behind the procedure is quite similar to ordinary macro expansion.\n\n### Making our own\nNow that we know both what a `CommandElab` is and how they are used, we can\nstart looking into writing our own. The steps for this, as we learned above, are:\n1. Declaring the syntax\n2. Declaring the elaborator\n3. Registering the elaborator as responsible for the syntax via the `command_elab`\n   attribute.\n\nLet's see how this is done:\n-/\n\nimport Lean\n\nopen Lean Elab Command Term Meta\n\nsyntax (name := mycommand1) \"#mycommand1\" : command -- declare the syntax\n\n@[command_elab mycommand1]\ndef mycommand1Impl : CommandElab := fun stx => do -- declare and register the elaborator\n  logInfo \"Hello World\"\n\n#mycommand1 -- Hello World\n\n/-!\nYou might think that this is a little boiler-platey and it turns out the Lean\ndevs did as well so they added a macro for this!\n-/\nelab \"#mycommand2\" : command =>\n  logInfo \"Hello World\"\n\n#mycommand2 -- Hello World\n\n/-!\nNote that, due to the fact that command elaboration supports multiple\nregistered elaborators for the same syntax, we can in fact overload\nsyntax, if we want to.\n-/\n@[command_elab mycommand1]\ndef myNewImpl : CommandElab := fun stx => do\n  logInfo \"new!\"\n\n#mycommand1 -- new!\n\n/-!\nFurthermore it is also possible to only overload parts of syntax by\nthrowing an `unsupportedSyntaxException` in the cases we want the default\nhandler to deal with it or just letting the `elab` command handle it.\n-/\n\n/-\nIn the following example, we are not extending the original `#check` syntax,\nbut adding a new `SyntaxKind` for this specific syntax construct.\nHowever, from the point of view of the user, the effect is basically the same.\n-/\nelab \"#check\" \"mycheck\" : command => do\n  logInfo \"Got ya!\"\n\n/-\nThis is actually extending the original `#check`\n-/\n@[command_elab Lean.Parser.Command.check] def mySpecialCheck : CommandElab := fun stx => do\n  if let some str := stx[1].isStrLit? then\n    logInfo s!\"Specially elaborated string literal!: {str} : String\"\n  else\n    throwUnsupportedSyntax\n\n#check mycheck -- Got ya!\n#check \"Hello\" -- Specially elaborated string literal!: Hello : String\n#check Nat.add -- Nat.add : Nat \u2192 Nat \u2192 Nat\n\n/-!\n### Mini project\nAs a final mini project for this section let's build a command elaborator\nthat is actually useful. It will take a command and use the same mechanisms\nas `elabCommand` (the entry point for command elaboration) to tell us\nwhich macros or elaborators are relevant to the command we gave it.\n\nWe will not go through the effort of actually reimplementing `elabCommand` though\n-/\nelab \"#findCElab \" c:command : command => do\n  let macroRes \u2190 liftMacroM <| expandMacroImpl? (\u2190getEnv) c\n  match macroRes with\n  | some (name, _) => logInfo s!\"Next step is a macro: {name.toString}\"\n  | none =>\n    let kind := c.raw.getKind\n    let elabs := commandElabAttribute.getEntries (\u2190getEnv) kind\n    match elabs with\n    | [] => logInfo s!\"There is no elaborators for your syntax, looks like its bad :(\"\n    | _ => logInfo s!\"Your syntax may be elaborated by: {elabs.map (fun el => el.declName.toString)}\"\n\n#findCElab def lala := 12 -- Your syntax may be elaborated by: [Lean.Elab.Command.elabDeclaration]\n#findCElab abbrev lolo := 12 -- Your syntax may be elaborated by: [Lean.Elab.Command.elabDeclaration]\n#findCElab #check foo -- even our own syntax!: Your syntax may be elaborated by: [mySpecialCheck, Lean.Elab.Command.elabCheck]\n#findCElab open Hi -- Your syntax may be elaborated by: [Lean.Elab.Command.elabOpen]\n#findCElab namespace Foo -- Your syntax may be elaborated by: [Lean.Elab.Command.elabNamespace]\n#findCElab #findCElab open Bar -- even itself!: Your syntax may be elaborated by: [\u00ab_aux_lean_elaboration___elabRules_command#findCElab__1\u00bb]\n\n/-!\nTODO: Maybe we should also add a mini project that demonstrates a\nnon # style command aka a declaration, although nothing comes to mind right now.\nTODO:  Define a `conjecture` declaration, similar to `lemma/theorem`, except that \nit is automatically sorried.  The `sorry` could be a custom one, to reflect that\nthe \"conjecture\" might be expected to be true.\n-/\n\n/-!\n## Term elaboration\nA term is a `Syntax` object that represents some sort of `Expr`.\nTerm elaborators are the ones that do the work for most of the code we write.\nMost notably they elaborate all the values of things like definitions,\ntypes (since these are also just `Expr`) etc.\n\nAll terms live in the `term` syntax category (which we have seen in action\nin the macro chapter already). So, in order to declare custom terms, their\nsyntax needs to be registered in that category.\n\n### Giving meaning to terms\nAs with command elaboration, the next step is giving some semantics to the syntax.\nWith terms, this is done by registering a so called term elaborator.\n\nTerm elaborators have type `TermElab` which is an alias for:\n`Syntax \u2192 Option Expr \u2192 TermElabM Expr`. This type is already\nquite different from command elaboration:\n- As with command elaboration the `Syntax` is whatever the user used\n  to create this term\n- The `Option Expr` is the expected type of the term, since this cannot\n  always be known it is only an `Option` argument\n- Unlike command elaboration, term elaboration is not only executed\n  because of its side effects -- the `TermElabM Expr` return value does\n  actually contain something of interest, namely, the `Expr` that represents\n  the `Syntax` object.\n\n`TermElabM` is basically an upgrade of `CommandElabM` in every regard:\nit supports all the capabilities we mentioned above, plus two more.\nThe first one is quite simple: On top of running `IO` code it is also\ncapable of running `MetaM` code, so `Expr`s can be constructed nicely.\nThe second one is very specific to the term elaboration loop.\n\n### Term elaboration\nThe basic idea of term elaboration is the same as command elaboration:\nexpand macros and recurse or run term elaborators that have been registered\nfor the `Syntax` via the `term_elab` attribute (they might in turn run term elaboration)\nuntil we are done. There is, however, one special action that a term elaborator\ncan do during its execution.\n\nA term elaborator may throw `Except.postpone`. This indicates that\nthe term elaborator requires more\ninformation to continue its work. In order to represent this missing information,\nLean uses so called synthetic metavariables. As you know from before, metavariables\nare holes in `Expr`s that are waiting to be filled in. Synthetic metavariables are\ndifferent in that they have special methods that are used to solve them,\nregistered in `SyntheticMVarKind`. Right now, there are four of these:\n- `typeClass`, the metavariable should be solved with typeclass synthesis\n- `coe`, the metavariable should be solved via coercion (a special case of typeclass)\n- `tactic`, the metavariable is a tactic term that should be solved by running a tactic\n- `postponed`, the ones that are created at `Except.postpone`\n\nOnce such a synthetic metavariable is created, the next higher level term elaborator will continue.\nAt some point, execution of postponed metavariables will be resumed by the term elaborator,\nin hopes that it can now complete its execution. We can try to see this in\naction with the following example:\n-/\n#check set_option trace.Elab.postpone true in List.foldr .add 0 [1,2,3] -- [Elab.postpone] .add : ?m.5695 \u2192 ?m.5696 \u2192 ?m.5696\n\n/-!\nWhat happened here is that the elaborator for function applications started\nat `List.foldr` which is a generic function so it created metavariables\nfor the implicit type parameters. Then, it attempted to elaborate the first argument `.add`.\n\nIn case you don't know how `.name` works, the basic idea is that quite\noften (like in this case) Lean should be able to infer the output type (in this case `Nat`)\nof a function (in this case `Nat.add`).  In such cases, the `.name` feature will then simply\nsearch for a function named `name` in the namespace `Nat`. This is especially\nuseful when you want to use constructors of a type without referring to its\nnamespace or opening it, but can also be used like above.\n\nNow back to our example, while Lean does at this point already know that `.add`\nneeds to have type: `?m1 \u2192 ?m2 \u2192 ?m2` (where `?x` is notation for a metavariable)\nthe elaborator for `.add` does need to know the actual value of `?m2` so the\nterm elaborator postpones execution (by internally creating a synthetic metavariable\nin place of `.add`), the elaboration of the other two arguments then yields the fact that\n`?m2` has to be `Nat` so once the `.add` elaborator is continued it can work with\nthis information to complete elaboration.\n\nWe can also easily provoke cases where this does not work out. For example:\n-/\n\n#check set_option trace.Elab.postpone true in List.foldr .add\n-- [Elab.postpone] .add : ?m.5808 \u2192 ?m.5809 \u2192 ?m.5809\n-- invalid dotted identifier notation, expected type is not of the form (... \u2192 C ...) where C is a constant\n  -- ?m.5808 \u2192 ?m.5809 \u2192 ?m.5809\n\n/-!\nIn this case `.add` first postponed its execution, then got called again\nbut didn't have enough information to finish elaboration and thus failed.\n\n### Making our own\nAdding new term elaborators works basically the same way as adding new\ncommand elaborators so we'll only take a very brief look:\n-/\n\nsyntax (name := myterm1) \"myterm 1\" : term\n\ndef mytermValues := [1, 2]\n\n@[term_elab myterm1]\ndef myTerm1Impl : TermElab := fun stx type? =>\n  mkAppM ``List.get! #[.const ``mytermValues [], mkNatLit 0] -- `MetaM` code\n\n#eval myterm 1 -- 1\n\n-- Also works with `elab`\nelab \"myterm 2\" : term => do\n  mkAppM ``List.get! #[.const ``mytermValues [], mkNatLit 1] -- `MetaM` code\n\n#eval myterm 2 -- 2\n\n/-!\n### Mini project\nAs a final mini project for this chapter we will recreate one of the most\ncommonly used Lean syntax sugars, the `\u27e8a,b,c\u27e9` notation as a short hand\nfor single constructor types:\n-/\n\n-- slightly different notation so no ambiguity happens\nsyntax (name := myanon) \"\u27e8\u27e8\" term,* \"\u27e9\u27e9\" : term\n\ndef getCtors (typ : Name) : MetaM (List Name) := do\n  let env \u2190 getEnv\n  match env.find? typ with\n  | some (ConstantInfo.inductInfo val) =>\n    pure val.ctors\n  | _ => pure []\n\n@[term_elab myanon]\ndef myanonImpl : TermElab := fun stx typ? => do\n  -- Attempt to postpone execution if the type is not known or is a metavariable.\n  -- Metavariables are used by things like the function elaborator to fill\n  -- out the values of implicit parameters when they haven't gained enough\n  -- information to figure them out yet.\n  -- Term elaborators can only postpone execution once, so the elaborator\n  -- doesn't end up in an infinite loop. Hence, we only try to postpone it,\n  -- otherwise we may cause an error.\n  tryPostponeIfNoneOrMVar typ? \n  -- If we haven't found the type after postponing just error\n  let some typ := typ? | throwError \"expected type must be known\"\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] \u2190 getCtors base | throwError \"type doesn't have exactly one constructor\"\n  let args := TSyntaxArray.mk stx[1].getSepArgs\n  let stx \u2190 `($(mkIdent ctor) $args*) -- syntax quotations\n  elabTerm stx typ -- call term elaboration recursively\n\n#check (\u27e8\u27e81, sorry\u27e9\u27e9 : Fin 12) -- { val := 1, isLt := (_ : 1 < 12) } : Fin 12\n#check \u27e8\u27e81, sorry\u27e9\u27e9 -- expected type must be known\n#check (\u27e8\u27e80\u27e9\u27e9 : Nat) -- type doesn't have exactly one constructor\n#check (\u27e8\u27e8\u27e9\u27e9 : Nat \u2192 Nat) -- type is not of the expected form: Nat -> Nat\n\n/-!\nAs a final note, we can shorten the postponing act by using an additional\nsyntax sugar of the `elab` syntax instead:\n-/\n\n-- This `t` syntax will effectively perform the first two lines of `myanonImpl`\nelab \"\u27e8\u27e8\" args:term,* \"\u27e9\u27e9\" : term <= t => do \n  sorry\n\n\n/-!\n\n## Exercises\n\n1. Consider the following code. Rewrite `syntax` + `@[term_elab hi]... : TermElab` combination using just `elab`.\n\n```\nsyntax (name := hi) term \" \u2665 \" \" \u2665 \"? \" \u2665 \"? : term\n\n@[term_elab hi]\ndef heartElab : TermElab := fun stx tp =>\n  match stx with\n    | `($l:term \u2665) => do\n      let nExpr \u2190 elabTermEnsuringType l (mkConst `Nat)\n      return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 1)\n    | `($l:term \u2665\u2665) => do\n      let nExpr \u2190 elabTermEnsuringType l (mkConst `Nat)\n      return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 2)\n    | `($l:term \u2665\u2665\u2665) => do\n      let nExpr \u2190 elabTermEnsuringType l (mkConst `Nat)\n      return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 3)\n    | _ =>\n      throwUnsupportedSyntax\n```\n\n2. Here is some syntax taken from a real mathlib command `alias`.\n\n```\nsyntax (name := our_alias) (docComment)? \"our_alias \" ident \" \u2190 \" ident* : command\n```\n\nWe want `alias hi \u2190 hello yes` to print out the identifiers after `\u2190` - that is, \"hello\" and \"yes\".\n\nPlease add these semantics:\n\n**a)** using `syntax` + `@[command_elab alias] def elabOurAlias : CommandElab`.  \n**b)** using `syntax` + `elab_rules`.  \n**c)** using `elab`.\n\n3. Here is some syntax taken from a real mathlib tactic `nth_rewrite`.\n\n```\nopen Parser.Tactic\nsyntax (name := nthRewriteSeq) \"nth_rewrite \" (config)? num rwRuleSeq (ppSpace location)? : tactic\n```\n\nWe want `nth_rewrite 5 [\u2190add_zero a] at h` to print out `\"rewrite location!\"` if the user provided location, and `\"rewrite target!\"` if the user didn't provide location.\n\nPlease add these semantics:\n\n**a)** using `syntax` + `@[tactic nthRewrite] def elabNthRewrite : Lean.Elab.Tactic.Tactic`.  \n**b)** using `syntax` + `elab_rules`.  \n**c)** using `elab`.\n\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/elaboration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06187598831856144, "lm_q2_score": 0.04272219510883879, "lm_q1q2_score": 0.0026434780454978116}}
{"text": "inductive Foo where\n  | foo\nexample : Foo :=\n  let c := Foo.foo\n  c\n--^ textDocument/typeDefinition\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/interactive/definition.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09009298418962222, "lm_q2_score": 0.029312227889470563, "lm_q1q2_score": 0.002640826083808675}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Parser.Extension\n-- necessary for auto-generation\nimport Lean.PrettyPrinter.Parenthesizer\nimport Lean.PrettyPrinter.Formatter\n\nnamespace Lean\nnamespace Parser\n\n-- synthesize pretty printers for parsers declared prior to `Lean.PrettyPrinter`\n-- (because `Parser.Extension` depends on them)\nattribute [run_builtin_parser_attribute_hooks]\n  leadingNode termParser commandParser mkAntiquot nodeWithAntiquot sepBy sepBy1\n  unicodeSymbol nonReservedSymbol\n  withCache withResetCache withPosition withPositionAfterLinebreak withoutPosition withForbidden withoutForbidden setExpected\n  incQuotDepth decQuotDepth suppressInsideQuot evalInsideQuot\n  withOpen withOpenDecl\n  dbgTraceState\n\n@[run_builtin_parser_attribute_hooks] def optional (p : Parser) : Parser :=\n  optionalNoAntiquot (withAntiquotSpliceAndSuffix `optional p (symbol \"?\"))\n\n@[run_builtin_parser_attribute_hooks] def many (p : Parser) : Parser :=\n  manyNoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol \"*\"))\n\n@[run_builtin_parser_attribute_hooks] def many1 (p : Parser) : Parser :=\n  many1NoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol \"*\"))\n\n@[run_builtin_parser_attribute_hooks] def ident : Parser :=\n  withAntiquot (mkAntiquot \"ident\" identKind) identNoAntiquot\n\n-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name\n@[run_builtin_parser_attribute_hooks] def rawIdent : Parser :=\n  withAntiquot (mkAntiquot \"ident\" identKind) rawIdentNoAntiquot\n\n@[run_builtin_parser_attribute_hooks] def numLit : Parser :=\n  withAntiquot (mkAntiquot \"num\" numLitKind) numLitNoAntiquot\n\n@[run_builtin_parser_attribute_hooks] def scientificLit : Parser :=\n  withAntiquot (mkAntiquot \"scientific\" scientificLitKind) scientificLitNoAntiquot\n\n@[run_builtin_parser_attribute_hooks] def strLit : Parser :=\n  withAntiquot (mkAntiquot \"str\" strLitKind) strLitNoAntiquot\n\n@[run_builtin_parser_attribute_hooks] def charLit : Parser :=\n  withAntiquot (mkAntiquot \"char\" charLitKind) charLitNoAntiquot\n\n@[run_builtin_parser_attribute_hooks] def nameLit : Parser :=\n  withAntiquot (mkAntiquot \"name\" nameLitKind) nameLitNoAntiquot\n\n@[run_builtin_parser_attribute_hooks, inline] def group (p : Parser) : Parser :=\n  node groupKind p\n\n@[run_builtin_parser_attribute_hooks, inline] def many1Indent (p : Parser) : Parser :=\n  withPosition $ many1 (checkColGe \"irrelevant\" >> p)\n\n@[run_builtin_parser_attribute_hooks, inline] def manyIndent (p : Parser) : Parser :=\n  withPosition $ many (checkColGe \"irrelevant\" >> p)\n\n@[inline] def sepByIndent (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser :=\n  let p := withAntiquotSpliceAndSuffix `sepBy p (symbol \"*\")\n  withPosition $ sepBy (checkColGe \"irrelevant\" >> p) sep (psep <|> checkColEq \"irrelevant\" >> checkLinebreakBefore >> pushNone) allowTrailingSep\n\n@[inline] def sepBy1Indent (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser :=\n  let p := withAntiquotSpliceAndSuffix `sepBy p (symbol \"*\")\n  withPosition $ sepBy1 (checkColGe \"irrelevant\" >> p) sep (psep <|> checkColEq \"irrelevant\" >> checkLinebreakBefore >> pushNone) allowTrailingSep\n\nopen PrettyPrinter Syntax.MonadTraverser Formatter in\n@[combinator_formatter sepByIndent]\ndef sepByIndent.formatter (p : Formatter) (_sep : String) (pSep : Formatter) : Formatter := do\n  let stx \u2190 getCur\n  let hasNewlineSep := stx.getArgs.mapIdx (fun \u27e8i, _\u27e9 n =>\n    i % 2 == 1 && n.matchesNull 0 && i != stx.getArgs.size - 1) |>.any id\n  visitArgs do\n    for i in (List.range stx.getArgs.size).reverse do\n      if i % 2 == 0 then p else pSep <|>\n        -- If the final separator is a newline, skip it.\n        ((if i == stx.getArgs.size - 1 then pure () else pushWhitespace \"\\n\") *> goLeft)\n  -- If there is any newline separator, then we add an `align` at the start\n  -- so that `withPosition` will pick up the right column.\n  if hasNewlineSep then\n    pushAlign (force := true)\n\n@[combinator_formatter sepBy1Indent] def sepBy1Indent.formatter := sepByIndent.formatter\n\nattribute [run_builtin_parser_attribute_hooks] sepByIndent sepBy1Indent\n\n@[run_builtin_parser_attribute_hooks] abbrev notSymbol (s : String) : Parser :=\n  notFollowedBy (symbol s) s\n\n/-- No-op parser combinator that annotates subtrees to be ignored in syntax patterns. -/\n@[inline, run_builtin_parser_attribute_hooks] def patternIgnore : Parser \u2192 Parser := node `patternIgnore\n\n/-- No-op parser that advises the pretty printer to emit a non-breaking space. -/\n@[inline] def ppHardSpace : Parser := skip\n/-- No-op parser that advises the pretty printer to emit a space/soft line break. -/\n@[inline] def ppSpace : Parser := skip\n/-- No-op parser that advises the pretty printer to emit a hard line break. -/\n@[inline] def ppLine : Parser := skip\n/-- No-op parser combinator that advises the pretty printer to emit a `Format.fill` node. -/\n@[inline] def ppRealFill : Parser \u2192 Parser := id\n/-- No-op parser combinator that advises the pretty printer to emit a `Format.group` node. -/\n@[inline] def ppRealGroup : Parser \u2192 Parser := id\n/-- No-op parser combinator that advises the pretty printer to indent the given syntax without grouping it. -/\n@[inline] def ppIndent : Parser \u2192 Parser := id\n/--\n  No-op parser combinator that advises the pretty printer to group and indent the given syntax.\n  By default, only syntax categories are grouped. -/\n@[inline] def ppGroup (p : Parser) : Parser := ppRealFill (ppIndent p)\n/--\n  No-op parser combinator that advises the pretty printer to dedent the given syntax.\n  Dedenting can in particular be used to counteract automatic indentation. -/\n@[inline] def ppDedent : Parser \u2192 Parser := id\n\n/--\n  No-op parser combinator that allows the pretty printer to omit the group and\n  indent operation in the enclosing category parser.\n  ```\n  syntax ppAllowUngrouped \"by \" tacticSeq : term\n  -- allows a `by` after `:=` without linebreak in between:\n  theorem foo : True := by\n    trivial\n  ```\n-/\n@[inline] def ppAllowUngrouped : Parser := skip\n\n/--\n  No-op parser combinator that advises the pretty printer to dedent the given syntax,\n  if it was grouped by the category parser.\n  Dedenting can in particular be used to counteract automatic indentation. -/\n@[inline] def ppDedentIfGrouped : Parser \u2192 Parser := id\n\n/--\n  No-op parser combinator that prints a line break.\n  The line break is soft if the combinator is followed\n  by an ungrouped parser (see ppAllowUngrouped), otherwise hard. -/\n@[inline] def ppHardLineUnlessUngrouped : Parser := skip\n\nend Parser\n\nsection\nopen PrettyPrinter Parser\n\n@[combinator_formatter ppHardSpace] def ppHardSpace.formatter : Formatter := Formatter.pushWhitespace \" \"\n@[combinator_formatter ppSpace] def ppSpace.formatter : Formatter := Formatter.pushLine\n@[combinator_formatter ppLine] def ppLine.formatter : Formatter := Formatter.pushWhitespace \"\\n\"\n@[combinator_formatter ppRealFill] def ppRealFill.formatter (p : Formatter) : Formatter := Formatter.fill p\n@[combinator_formatter ppRealGroup] def ppRealGroup.formatter (p : Formatter) : Formatter := Formatter.group p\n@[combinator_formatter ppIndent] def ppIndent.formatter (p : Formatter) : Formatter := Formatter.indent p\n@[combinator_formatter ppDedent] def ppDedent.formatter (p : Formatter) : Formatter := do\n  let opts \u2190 getOptions\n  Formatter.indent p (some ((0:Int) - Std.Format.getIndent opts))\n\n@[combinator_formatter ppAllowUngrouped] def ppAllowUngrouped.formatter : Formatter := do\n  modify ({ \u00b7 with mustBeGrouped := false })\n@[combinator_formatter ppDedentIfGrouped] def ppDedentIfGrouped.formatter (p : Formatter) : Formatter := do\n  Formatter.concat p\n  let indent := Std.Format.getIndent (\u2190 getOptions)\n  unless (\u2190 get).isUngrouped do\n    modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (\u00b7.nest (0 - indent)) }\n@[combinator_formatter ppHardLineUnlessUngrouped] def ppHardLineUnlessUngrouped.formatter : Formatter := do\n  if (\u2190 get).isUngrouped then\n    Formatter.pushLine\n  else\n    ppLine.formatter\n\nend\n\nnamespace Parser\n\n-- now synthesize parenthesizers\nattribute [run_builtin_parser_attribute_hooks]\n  ppHardSpace ppSpace ppLine ppGroup ppRealGroup ppRealFill ppIndent ppDedent\n  ppAllowUngrouped ppDedentIfGrouped ppHardLineUnlessUngrouped\n\nsyntax \"register_parser_alias\" group(\"(\" &\"kind\" \" := \" term \")\")? (strLit)? ident (colGt term)? : term\nmacro_rules\n  | `(register_parser_alias $[(kind := $kind?)]? $(aliasName?)? $declName $(info?)?) => do\n    let [(fullDeclName, [])] \u2190 Macro.resolveGlobalName declName.getId |\n      Macro.throwError \"expected non-overloaded constant name\"\n    let aliasName := aliasName?.getD (Syntax.mkStrLit declName.getId.toString)\n    `(do Parser.registerAlias $aliasName ``$declName $declName $(info?.getD (Unhygienic.run `({}))) (kind? := some $(kind?.getD (quote fullDeclName)))\n         PrettyPrinter.Formatter.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `formatter))\n         PrettyPrinter.Parenthesizer.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `parenthesizer)))\n\nbuiltin_initialize\n  register_parser_alias patternIgnore { autoGroupArgs := false }\n\n  register_parser_alias group { autoGroupArgs := false }\n  register_parser_alias ppHardSpace { stackSz? := some 0 }\n  register_parser_alias ppSpace { stackSz? := some 0 }\n  register_parser_alias ppLine { stackSz? := some 0 }\n  register_parser_alias ppGroup { stackSz? := none }\n  register_parser_alias ppRealGroup { stackSz? := none }\n  register_parser_alias ppRealFill { stackSz? := none }\n  register_parser_alias ppIndent { stackSz? := none }\n  register_parser_alias ppDedent { stackSz? := none }\n  register_parser_alias ppDedentIfGrouped { stackSz? := none }\n  register_parser_alias ppAllowUngrouped { stackSz? := some 0 }\n  register_parser_alias ppHardLineUnlessUngrouped { stackSz? := some 0 }\n\nend Parser\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/Parser/Extra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08269734493579811, "lm_q2_score": 0.031143830759591477, "lm_q1q2_score": 0.0025755121149480557}}
{"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Sebastian Ullrich, Leonardo de Moura\n-/\nimport Lean.Data.Name\nimport Lean.Data.Format\n\n/--\nA position range inside a string. This type is mostly in combination with syntax trees,\nas there might not be a single underlying string in this case that could be used for a `Substring`.\n-/\nprotected structure String.Range where\n  start : String.Pos\n  stop  : String.Pos\n  deriving Inhabited, Repr, BEq, Hashable\n\ndef String.Range.contains (r : String.Range) (pos : String.Pos) (includeStop := false) : Bool :=\n  r.start <= pos && (if includeStop then pos <= r.stop else pos < r.stop)\n\ndef String.Range.includes (super sub : String.Range) : Bool :=\n  super.start <= sub.start && super.stop >= sub.stop\n\nnamespace Lean\n\ndef SourceInfo.updateTrailing (trailing : Substring) : SourceInfo \u2192 SourceInfo\n  | SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos\n  | info                                     => info\n\n/-! # Syntax AST -/\n\ninductive IsNode : Syntax \u2192 Prop where\n  | mk (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node info kind args)\n\ndef SyntaxNode : Type := {s : Syntax // IsNode s }\n\ndef unreachIsNodeMissing {\u03b2} (h : IsNode Syntax.missing) : \u03b2 := False.elim (nomatch h)\ndef unreachIsNodeAtom {\u03b2} {info val} (h : IsNode (Syntax.atom info val)) : \u03b2 := False.elim (nomatch h)\ndef unreachIsNodeIdent {\u03b2 info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : \u03b2 := False.elim (nomatch h)\n\ndef isLitKind (k : SyntaxNodeKind) : Bool :=\n  k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind\n\nnamespace SyntaxNode\n\n@[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind :=\n  match n with\n  | \u27e8Syntax.node _ k _, _\u27e9  => k\n  | \u27e8Syntax.missing, h\u27e9     => unreachIsNodeMissing h\n  | \u27e8Syntax.atom .., h\u27e9     => unreachIsNodeAtom h\n  | \u27e8Syntax.ident .., h\u27e9    => unreachIsNodeIdent h\n\n@[inline] def withArgs {\u03b2} (n : SyntaxNode) (fn : Array Syntax \u2192 \u03b2) : \u03b2 :=\n  match n with\n  | \u27e8Syntax.node _ _ args, _\u27e9   => fn args\n  | \u27e8Syntax.missing, h\u27e9       => unreachIsNodeMissing h\n  | \u27e8Syntax.atom _ _, h\u27e9      => unreachIsNodeAtom h\n  | \u27e8Syntax.ident _ _ _ _, h\u27e9 => unreachIsNodeIdent h\n\n@[inline] def getNumArgs (n : SyntaxNode) : Nat :=\n  withArgs n fun args => args.size\n\n@[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax :=\n  withArgs n fun args => args.get! i\n\n@[inline] def getArgs (n : SyntaxNode) : Array Syntax :=\n  withArgs n fun args => args\n\n@[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax \u2192 Array Syntax) : Syntax :=\n  match n with\n  | \u27e8Syntax.node i k args, _\u27e9  => Syntax.node i k (fn args)\n  | \u27e8Syntax.missing, h\u27e9        => unreachIsNodeMissing h\n  | \u27e8Syntax.atom _ _, h\u27e9       => unreachIsNodeAtom h\n  | \u27e8Syntax.ident _ _ _ _,  h\u27e9 => unreachIsNodeIdent h\n\nend SyntaxNode\n\nnamespace Syntax\n\ndef getAtomVal : Syntax \u2192 String\n  | atom _ val => val\n  | _          => \"\"\n\ndef setAtomVal : Syntax \u2192 String \u2192 Syntax\n  | atom info _, v => (atom info v)\n  | stx,         _ => stx\n\n@[inline] def ifNode {\u03b2} (stx : Syntax) (hyes : SyntaxNode \u2192 \u03b2) (hno : Unit \u2192 \u03b2) : \u03b2 :=\n  match stx with\n  | Syntax.node i k args => hyes \u27e8Syntax.node i k args, IsNode.mk i k args\u27e9\n  | _                    => hno ()\n\n@[inline] def ifNodeKind {\u03b2} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode \u2192 \u03b2) (hno : Unit \u2192 \u03b2) : \u03b2 :=\n  match stx with\n  | Syntax.node i k args => if k == kind then hyes \u27e8Syntax.node i k args, IsNode.mk i k args\u27e9 else hno ()\n  | _                    => hno ()\n\ndef asNode : Syntax \u2192 SyntaxNode\n  | Syntax.node info kind args => \u27e8Syntax.node info kind args, IsNode.mk info kind args\u27e9\n  | _                          => \u27e8mkNullNode, IsNode.mk _ _ _\u27e9\n\ndef getIdAt (stx : Syntax) (i : Nat) : Name :=\n  (stx.getArg i).getId\n\n@[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax \u2192 Array Syntax) : Syntax :=\n  match stx with\n  | node i k args => node i k (fn args)\n  | stx           => stx\n\n@[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax \u2192 Syntax) : Syntax :=\n  match stx with\n  | node info k args => node info k (args.modify i fn)\n  | stx              => stx\n\n@[specialize] partial def replaceM {m : Type \u2192 Type} [Monad m] (fn : Syntax \u2192 m (Option Syntax)) : Syntax \u2192 m (Syntax)\n  | stx@(node info kind args) => do\n    match (\u2190 fn stx) with\n    | some stx => return stx\n    | none     => return node info kind (\u2190 args.mapM (replaceM fn))\n  | stx => do\n    let o \u2190 fn stx\n    return o.getD stx\n\n@[specialize] partial def rewriteBottomUpM {m : Type \u2192 Type} [Monad m] (fn : Syntax \u2192 m (Syntax)) : Syntax \u2192 m (Syntax)\n  | node info kind args   => do\n    let args \u2190 args.mapM (rewriteBottomUpM fn)\n    fn (node info kind args)\n  | stx => fn stx\n\n@[inline] def rewriteBottomUp (fn : Syntax \u2192 Syntax) (stx : Syntax) : Syntax :=\n  Id.run <| stx.rewriteBottomUpM fn\n\nprivate def updateInfo : SourceInfo \u2192 String.Pos \u2192 String.Pos \u2192 SourceInfo\n  | SourceInfo.original lead pos trail endPos, leadStart, trailStop =>\n    SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos\n  | info, _, _ => info\n\nprivate def chooseNiceTrailStop (trail : Substring) : String.Pos :=\ntrail.startPos + trail.posOf '\\n'\n\n/-- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token,\n   or the beginning of the String. -/\n@[inline]\nprivate def updateLeadingAux : Syntax \u2192 StateM String.Pos (Option Syntax)\n  | atom info@(SourceInfo.original _ _ trail _) val => do\n    let trailStop := chooseNiceTrailStop trail\n    let newInfo := updateInfo info (\u2190 get) trailStop\n    set trailStop\n    return some (atom newInfo val)\n  | ident info@(SourceInfo.original _ _ trail _) rawVal val pre => do\n    let trailStop := chooseNiceTrailStop trail\n    let newInfo := updateInfo info (\u2190 get) trailStop\n    set trailStop\n    return some (ident newInfo rawVal val pre)\n  | _ => pure none\n\n/-- Set `SourceInfo.leading` according to the trailing stop of the preceding token.\n    The result is a round-tripping syntax tree IF, in the input syntax tree,\n    * all leading stops, atom contents, and trailing starts are correct\n    * trailing stops are between the trailing start and the next leading stop.\n\n    Remark: after parsing, all `SourceInfo.leading` fields are empty.\n    The `Syntax` argument is the output produced by the parser for `source`.\n    This function \"fixes\" the `source.leading` field.\n\n    Additionally, we try to choose \"nicer\" splits between leading and trailing stops\n    according to some heuristics so that e.g. comments are associated to the (intuitively)\n    correct token.\n\n    Note that the `SourceInfo.trailing` fields must be correct.\n    The implementation of this Function relies on this property. -/\ndef updateLeading : Syntax \u2192 Syntax :=\n  fun stx => (replaceM updateLeadingAux stx).run' 0\n\npartial def updateTrailing (trailing : Substring) : Syntax \u2192 Syntax\n  | Syntax.atom info val               => Syntax.atom (info.updateTrailing trailing) val\n  | Syntax.ident info rawVal val pre   => Syntax.ident (info.updateTrailing trailing) rawVal val pre\n  | n@(Syntax.node info k args)        =>\n    if args.size == 0 then n\n    else\n     let i    := args.size - 1\n     let last := updateTrailing trailing args[i]!\n     let args := args.set! i last;\n     Syntax.node info k args\n  | s => s\n\npartial def getTailWithPos : Syntax \u2192 Option Syntax\n  | stx@(atom info _)   => info.getPos?.map fun _ => stx\n  | stx@(ident info ..) => info.getPos?.map fun _ => stx\n  | node SourceInfo.none _ args => args.findSomeRev? getTailWithPos\n  | stx@(node ..) => stx\n  | _ => none\n\nopen SourceInfo in\n/-- Split an `ident` into its dot-separated components while preserving source info.\nMacro scopes are first erased.  For example, `` `foo.bla.boo._@._hyg.4 `` \u21a6 `` [`foo, `bla, `boo] ``.\nIf `nFields` is set, we take that many fields from the end and keep the remaining components\nas one name. For example, `` `foo.bla.boo `` with `(nFields := 1)` \u21a6 `` [`foo.bla, `boo] ``. -/\ndef identComponents (stx : Syntax) (nFields? : Option Nat := none) : List Syntax :=\n  match stx with\n  | ident (SourceInfo.original lead pos trail _) rawStr val _ =>\n    let val := val.eraseMacroScopes\n    -- With original info, we assume that `rawStr` represents `val`.\n    let nameComps := nameComps val nFields?\n    let rawComps := splitNameLit rawStr\n    let rawComps :=\n      if let some nFields := nFields? then\n        let nPrefix := rawComps.length - nFields\n        let prefixSz := rawComps.take nPrefix |>.foldl (init := 0) fun acc (ss : Substring) => acc + ss.bsize + 1\n        let prefixSz := prefixSz - 1 -- The last component has no dot\n        rawStr.extract 0 \u27e8prefixSz\u27e9 :: rawComps.drop nPrefix\n      else\n        rawComps\n    assert! nameComps.length == rawComps.length\n    nameComps.zip rawComps |>.map fun (id, ss) =>\n      let off := ss.startPos - rawStr.startPos\n      let lead := if off == 0 then lead else \"\".toSubstring\n      let trail := if ss.stopPos == rawStr.stopPos then trail else \"\".toSubstring\n      let info := original lead (pos + off) trail (pos + off + \u27e8ss.bsize\u27e9)\n      ident info ss id []\n  | ident si _ val _ =>\n    let val := val.eraseMacroScopes\n    /- With non-original info:\n     - `rawStr` can take all kinds of forms so we only use `val`.\n     - there is no source extent to offset, so we pass it as-is. -/\n    nameComps val nFields? |>.map fun n => ident si n.toString.toSubstring n []\n  | _ => unreachable!\n  where\n    nameComps (n : Name) (nFields? : Option Nat) : List Name :=\n      if let some nFields := nFields? then\n        let nameComps := n.components\n        let nPrefix := nameComps.length - nFields\n        let namePrefix := nameComps.take nPrefix |>.foldl (init := Name.anonymous) fun acc n => acc ++ n\n        namePrefix :: nameComps.drop nPrefix\n      else\n        n.components\n\nstructure TopDown where\n  firstChoiceOnly : Bool\n  stx : Syntax\n\n/--\n`for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right.\nIf `firstChoiceOnly` is `true`, only visit the first argument of each choice node.\n-/\ndef topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := \u27e8firstChoiceOnly, stx\u27e9\n\npartial instance : ForIn m TopDown Syntax where\n  forIn := fun \u27e8firstChoiceOnly, stx\u27e9 init f => do\n    let rec @[specialize] loop stx b [Inhabited (type_of% b)] := do\n      match (\u2190 f stx b) with\n      | ForInStep.yield b' =>\n        let mut b := b'\n        if let Syntax.node _ k args := stx then\n          if firstChoiceOnly && k == choiceKind then\n            return \u2190 loop args[0]! b\n          else\n            for arg in args do\n              match (\u2190 loop arg b) with\n              | ForInStep.yield b' => b := b'\n              | ForInStep.done b'  => return ForInStep.done b'\n        return ForInStep.yield b\n      | ForInStep.done b => return ForInStep.done b\n    match (\u2190 @loop stx init \u27e8init\u27e9) with\n    | ForInStep.yield b => return b\n    | ForInStep.done b  => return b\n\npartial def reprint (stx : Syntax) : Option String := do\n  let mut s := \"\"\n  for stx in stx.topDown (firstChoiceOnly := true) do\n    match stx with\n    | atom info val           => s := s ++ reprintLeaf info val\n    | ident info rawVal _ _   => s := s ++ reprintLeaf info rawVal.toString\n    | node _    kind args     =>\n      if kind == choiceKind then\n        -- this visit the first arg twice, but that should hardly be a problem\n        -- given that choice nodes are quite rare and small\n        let s0 \u2190 reprint args[0]!\n        for arg in args[1:] do\n          let s' \u2190 reprint arg\n          guard (s0 == s')\n    | _ => pure ()\n  return s\nwhere\n  reprintLeaf (info : SourceInfo) (val : String) : String :=\n    match info with\n    | SourceInfo.original lead _ trail _ => s!\"{lead}{val}{trail}\"\n    -- no source info => add gracious amounts of whitespace to definitely separate tokens\n    -- Note that the proper pretty printer does not use this function.\n    -- The parser as well always produces source info, so round-tripping is still\n    -- guaranteed.\n    | _                                => s!\" {val} \"\n\ndef hasMissing (stx : Syntax) : Bool := Id.run do\n  for stx in stx.topDown do\n    if stx.isMissing then\n      return true\n  return false\n\ndef getRange? (stx : Syntax) (canonicalOnly := false) : Option String.Range :=\n  match stx.getPos? canonicalOnly, stx.getTailPos? canonicalOnly with\n  | some start, some stop => some { start, stop }\n  | _,          _         => none\n\n/--\nRepresents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right.\nIndices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`.\nIf the `Traverser` is used linearly, updates are linear in the `Syntax` object as well.\n-/\nstructure Traverser where\n  cur     : Syntax\n  parents : Array Syntax\n  idxs    : Array Nat\n\nnamespace Traverser\n\ndef fromSyntax (stx : Syntax) : Traverser :=\n  \u27e8stx, #[], #[]\u27e9\n\ndef setCur (t : Traverser) (stx : Syntax) : Traverser :=\n  { t with cur := stx }\n\n/-- Advance to the `idx`-th child of the current node. -/\ndef down (t : Traverser) (idx : Nat) : Traverser :=\n  if idx < t.cur.getNumArgs then\n    { cur := t.cur.getArg idx, parents := t.parents.push <| t.cur.setArg idx default, idxs := t.idxs.push idx }\n  else\n    { cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx }\n\n/-- Advance to the parent of the current node, if any. -/\ndef up (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back\n    { cur := cur, parents := t.parents.pop, idxs := t.idxs.pop }\n  else\n    t\n\n/-- Advance to the left sibling of the current node, if any. -/\ndef left (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    t.up.down (t.idxs.back - 1)\n  else\n    t\n\n/-- Advance to the right sibling of the current node, if any. -/\ndef right (t : Traverser) : Traverser :=\n  if t.parents.size > 0 then\n    t.up.down (t.idxs.back + 1)\n  else\n    t\n\nend Traverser\n\n/-- Monad class that gives read/write access to a `Traverser`. -/\nclass MonadTraverser (m : Type \u2192 Type) where\n  st : MonadState Traverser m\n\nnamespace MonadTraverser\n\nvariable {m : Type \u2192 Type} [Monad m] [t : MonadTraverser m]\n\ndef getCur : m Syntax := Traverser.cur <$> t.st.get\ndef setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx)\ndef goDown (idx : Nat)    : m Unit := @modify _ _ t.st (fun t => t.down idx)\ndef goUp                  : m Unit := @modify _ _ t.st (fun t => t.up)\ndef goLeft                : m Unit := @modify _ _ t.st (fun t => t.left)\ndef goRight               : m Unit := @modify _ _ t.st (fun t => t.right)\n\ndef getIdx : m Nat := do\n  let st \u2190 t.st.get\n  return st.idxs.back?.getD 0\n\nend MonadTraverser\nend Syntax\n\nnamespace SyntaxNode\n\n@[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name :=\n  (n.getArg i).getId\n\nend SyntaxNode\n\ndef mkListNode (args : Array Syntax) : Syntax :=\n  mkNullNode args\n\nnamespace Syntax\n\n-- quotation node kinds are formed from a unique quotation name plus \"quot\"\ndef isQuot : Syntax \u2192 Bool\n  | Syntax.node _ (Name.str _ \"quot\")           _ => true\n  | Syntax.node _ `Lean.Parser.Term.dynamicQuot _ => true\n  | _                                             => false\n\ndef getQuotContent (stx : Syntax) : Syntax :=\n  let stx := if stx.getNumArgs == 1 then stx[0] else stx\n  if stx.isOfKind `Lean.Parser.Term.dynamicQuot then\n    stx[3]\n  else\n    stx[1]\n\n-- antiquotation node kinds are formed from the original node kind (if any) plus \"antiquot\"\ndef isAntiquot : Syntax \u2192 Bool\n  | .node _ (.str _ \"antiquot\") _ => true\n  | _                             => false\n\ndef isAntiquots (stx : Syntax) : Bool :=\n  stx.isAntiquot || (stx.isOfKind choiceKind && stx.getNumArgs > 0 && stx.getArgs.all isAntiquot)\n\ndef getCanonicalAntiquot (stx : Syntax) : Syntax :=\n  if stx.isOfKind choiceKind then\n    stx[0]\n  else\n    stx\n\ndef mkAntiquotNode (kind : Name) (term : Syntax) (nesting := 0) (name : Option String := none) (isPseudoKind := false) : Syntax :=\n  let nesting := mkNullNode (mkArray nesting (mkAtom \"$\"))\n  let term :=\n    if term.isIdent then term\n    else if term.isOfKind `Lean.Parser.Term.hole then term[0]\n    else mkNode `antiquotNestedExpr #[mkAtom \"(\", term, mkAtom \")\"]\n  let name := match name with\n    | some name => mkNode `antiquotName #[mkAtom \":\", mkAtom name]\n    | none      => mkNullNode\n  mkNode (kind ++ (if isPseudoKind then `pseudo else Name.anonymous) ++ `antiquot) #[mkAtom \"$\", nesting, term, name]\n\n-- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices.\ndef isEscapedAntiquot (stx : Syntax) : Bool :=\n  !stx[1].getArgs.isEmpty\n\n-- Also works for antiquotation splices.\ndef unescapeAntiquot (stx : Syntax) : Syntax :=\n  if isAntiquot stx then\n    stx.setArg 1 <| mkNullNode stx[1].getArgs.pop\n  else\n    stx\n\n-- Also works for token antiquotations.\ndef getAntiquotTerm (stx : Syntax) : Syntax :=\n  let e := if stx.isAntiquot then stx[2] else stx[3]\n  if e.isIdent then e\n  else if e.isAtom then mkNode `Lean.Parser.Term.hole #[e]\n  else\n    -- `e` is from `\"(\" >> termParser >> \")\"`\n    e[1]\n\n/-- Return kind of parser expected at this antiquotation, and whether it is a \"pseudo\" kind (see `mkAntiquot`). -/\ndef antiquotKind? : Syntax \u2192 Option (SyntaxNodeKind \u00d7 Bool)\n  | .node _ (.str (.str k \"pseudo\") \"antiquot\") _ => (k, true)\n  | .node _ (.str k                 \"antiquot\") _ => (k, false)\n  | _                                             => none\n\ndef antiquotKinds (stx : Syntax) : List (SyntaxNodeKind \u00d7 Bool) :=\n  if stx.isOfKind choiceKind then\n    stx.getArgs.filterMap antiquotKind? |>.toList\n  else\n    match antiquotKind? stx with\n    | some stx => [stx]\n    | none     => []\n\n-- An \"antiquotation splice\" is something like `$[...]?` or `$[...]*`.\ndef antiquotSpliceKind? : Syntax \u2192 Option SyntaxNodeKind\n  | .node _ (.str k \"antiquot_scope\") _ => some k\n  | _ => none\n\ndef isAntiquotSplice (stx : Syntax) : Bool :=\n  antiquotSpliceKind? stx |>.isSome\n\ndef getAntiquotSpliceContents (stx : Syntax) : Array Syntax :=\n  stx[3].getArgs\n\n-- `$[..],*` or `$x,*` ~> `,*`\ndef getAntiquotSpliceSuffix (stx : Syntax) : Syntax :=\n  if stx.isAntiquotSplice then\n    stx[5]\n  else\n    stx[1]\n\ndef mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax :=\n  let nesting := mkNullNode (mkArray nesting (mkAtom \"$\"))\n  mkNode (kind ++ `antiquot_splice) #[mkAtom \"$\", nesting, mkAtom \"[\", mkNullNode contents, mkAtom \"]\", mkAtom suffix]\n\n-- `$x,*` etc.\ndef antiquotSuffixSplice? : Syntax \u2192 Option SyntaxNodeKind\n  | .node _ (.str k \"antiquot_suffix_splice\") _ => some k\n  | _ => none\n\ndef isAntiquotSuffixSplice (stx : Syntax) : Bool :=\n  antiquotSuffixSplice? stx |>.isSome\n\n-- `$x` in the example above\ndef getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax :=\n  stx[0]\n\ndef mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax :=\n  mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix]\n\ndef isTokenAntiquot (stx : Syntax) : Bool :=\n  stx.isOfKind `token_antiquot\n\ndef isAnyAntiquot (stx : Syntax) : Bool :=\n  stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot\n\n/-- List of `Syntax` nodes in which each succeeding element is the parent of\nthe current. The associated index is the index of the preceding element in the\nlist of children of the current element. -/\nprotected abbrev Stack := List (Syntax \u00d7 Nat)\n\n/-- Return stack of syntax nodes satisfying `visit`, starting with such a node that also fulfills `accept` (default \"is leaf\"), and ending with the root. -/\npartial def findStack? (root : Syntax) (visit : Syntax \u2192 Bool) (accept : Syntax \u2192 Bool := fun stx => !stx.hasArgs) : Option Syntax.Stack :=\n  if visit root then go [] root else none\nwhere\n  go (stack : Syntax.Stack) (stx : Syntax) : Option Syntax.Stack := Id.run do\n    if accept stx then\n      return (stx, 0) :: stack  -- the first index is arbitrary as there is no preceding element\n    for i in [0:stx.getNumArgs] do\n      if visit stx[i] then\n        if let some stack := go ((stx, i) :: stack) stx[i] then\n          return stack\n    return none\n\n/-- Compare the `SyntaxNodeKind`s in `pattern` to those of the `Syntax`\nelements in `stack`. Return `false` if `stack` is shorter than `pattern`. -/\ndef Stack.matches (stack : Syntax.Stack) (pattern : List $ Option SyntaxNodeKind) : Bool :=\n  stack.length >= pattern.length &&\n  (stack\n    |>.zipWith (fun (s, _) p => p |>.map (s.isOfKind \u00b7) |>.getD true) pattern\n    |>.all id)\n\nend Syntax\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/Syntax.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.095349472611171, "lm_q2_score": 0.026759281245071827, "lm_q1q2_score": 0.0025514833541715977}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki\n-/\nimport Lean.Linter.UnusedVariables\nimport Lean.Server.Utils\nimport Lean.Widget.InteractiveGoal\n\nnamespace Lean.Widget\nopen Lsp Server\n\ninductive StrictOrLazy (\u03b1 \u03b2 : Type) : Type\n  | strict : \u03b1 \u2192 StrictOrLazy \u03b1 \u03b2\n  | lazy : \u03b2 \u2192 StrictOrLazy \u03b1 \u03b2\n  deriving Inhabited, RpcEncodable\n\nstructure LazyTraceChildren where\n  indent : Nat\n  children : Array (WithRpcRef MessageData)\n  deriving TypeName\n\ninductive MsgEmbed where\n  /-- A piece of Lean code with elaboration/typing data.\n  Note: does not necessarily correspond to an `Expr`, the name is for RPC API compatibility. -/\n  | expr : CodeWithInfos \u2192 MsgEmbed\n  /-- An interactive goal display. -/\n  | goal : InteractiveGoal \u2192 MsgEmbed\n  /-- Some messages (in particular, traces) are too costly to print eagerly. Instead, we allow\n  the user to expand sub-traces interactively. -/\n  | trace (indent : Nat) (cls : Name) (msg : TaggedText MsgEmbed) (collapsed : Bool)\n      (children : StrictOrLazy (Array (TaggedText MsgEmbed)) (WithRpcRef LazyTraceChildren))\n  deriving Inhabited, RpcEncodable\n\n/-- The `message` field is the text of a message possibly containing interactive *embeds* of type\n`MsgEmbed`. We maintain the invariant that embeds are stored in `.tag`s with empty `.text` subtrees,\ni.e. `.tag embed (.text \"\")`, because a `MsgEmbed` display involve more than just text. -/\nabbrev InteractiveDiagnostic := Lsp.DiagnosticWith (TaggedText MsgEmbed)\n\nderiving instance RpcEncodable for Lsp.DiagnosticWith\n\nnamespace InteractiveDiagnostic\nopen MsgEmbed\n\ndef toDiagnostic (diag : InteractiveDiagnostic) : Lsp.Diagnostic :=\n  { diag with message := prettyTt diag.message }\nwhere\n  prettyTt (tt : TaggedText MsgEmbed) : String :=\n    let tt : TaggedText MsgEmbed := tt.rewrite fun\n      | .expr tt,  _ => .text tt.stripTags\n      | .goal g,   _ => .text (toString g.pretty)\n      | .trace .., _ => .text \"(trace)\"\n    tt.stripTags\n\nend InteractiveDiagnostic\n\nprivate def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := {\n  env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts,\n  currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls\n}\n\n/-! The `msgToInteractive` algorithm turns a `MessageData` into `TaggedText MsgEmbed` in two stages.\n\nFirst, in `msgToInteractiveAux` we produce a `Format` object whose `.tag` nodes refer to `EmbedFmt`\nobjects stored in an auxiliary array. Only the most shallow `.tag` in every branch through the\n`Format` corresponds to an `EmbedFmt`. The kind of this tag determines how the nested `Format`\nobject (possibly including further `.tag`s), is processed. For example, if the output is\n`.tag (.expr ctx infos) fmt` then tags in the nested `fmt` object refer to elements of `infos`.\n\nIn the second stage, we recursively transform such a `Format` into `TaggedText MsgEmbed` according\nto the rule above by first pretty-printing it and then grabbing data referenced by the tags from\nall the nested arrays (such as the `infos` array in the example above).\n\nWe cannot easily do the translation in a single `MessageData \u2192 TaggedText MsgEmbed` step because\nthat would effectively require reimplementing the (stateful, to keep track of indentation)\n`Format.prettyM` algorithm.\n-/\n\nprivate inductive EmbedFmt\n  /-- Nested tags denote `Info` objects in `infos`. -/\n  | code (ctx : Elab.ContextInfo) (infos : RBMap Nat Elab.Info compare)\n  /-- Nested text is ignored. -/\n  | goal (ctx : Elab.ContextInfo) (lctx : LocalContext) (g : MVarId)\n  /-- Nested text is ignored. -/\n  | trace (cls : Name) (msg : Format) (collapsed : Bool)\n    (children : StrictOrLazy (Array Format) (Array MessageData))\n  /-- Nested tags are ignored, show nested text as-is. -/\n  | ignoreTags\n  deriving Inhabited\n\nprivate abbrev MsgFmtM := StateT (Array EmbedFmt) IO\n\nopen MessageData in\nprivate partial def msgToInteractiveAux (msgData : MessageData) : IO (Format \u00d7 Array EmbedFmt) :=\n  go { currNamespace := Name.anonymous, openDecls := [] } none msgData #[]\nwhere\n  pushEmbed (e : EmbedFmt) : MsgFmtM Nat :=\n    modifyGet fun es => (es.size, es.push e)\n\n  withIgnoreTags (fmt : Format) : MsgFmtM Format := do\n    let t \u2190 pushEmbed EmbedFmt.ignoreTags\n    return Format.tag t fmt\n\n  mkContextInfo (nCtx : NamingContext) (ctx : MessageDataContext) : Elab.ContextInfo := {\n    env           := ctx.env\n    mctx          := ctx.mctx\n    fileMap       := default\n    options       := ctx.opts\n    currNamespace := nCtx.currNamespace\n    openDecls     := nCtx.openDecls\n    -- Hack: to make sure unique ids created at `ppExprWithInfos` do not collide with ones in `ctx.mctx`\n    ngen          := { namePrefix := `_diag }\n  }\n\n  go (nCtx : NamingContext) : Option MessageDataContext \u2192 MessageData \u2192 MsgFmtM Format\n  | _,         ofFormat fmt             => withIgnoreTags fmt\n  | none,      ofPPFormat fmt           => (\u00b7.fmt) <$> fmt.pp none\n  | some ctx,  ofPPFormat fmt           => do\n    let \u27e8fmt, infos\u27e9 \u2190 fmt.pp (mkPPContext nCtx ctx)\n    let t \u2190 pushEmbed <| EmbedFmt.code (mkContextInfo nCtx ctx) infos\n    return Format.tag t fmt\n  | none,      ofGoal mvarId            => pure $ \"goal \" ++ format (mkMVar mvarId)\n  | some ctx,  ofGoal mvarId            =>\n    return .tag (\u2190 pushEmbed (.goal (mkContextInfo nCtx ctx) ctx.lctx mvarId)) \"\\n\"\n  | _,         withContext ctx d        => go nCtx ctx d\n  | ctx,       withNamingContext nCtx d => go nCtx ctx d\n  | ctx,       tagged _ d               => go nCtx ctx d\n  | ctx,       nest n d                 => Format.nest n <$> go nCtx ctx d\n  | ctx,       compose d\u2081 d\u2082            => do let d\u2081 \u2190 go nCtx ctx d\u2081; let d\u2082 \u2190 go nCtx ctx d\u2082; pure $ d\u2081 ++ d\u2082\n  | ctx,       group d                  => Format.group <$> go nCtx ctx d\n  | ctx,       .trace cls header children collapsed => do\n    let header := (\u2190 go nCtx ctx header).nest 4\n    let nodes \u2190\n      if collapsed && !children.isEmpty then\n        let children := children.map fun child =>\n          MessageData.withNamingContext nCtx <|\n            match ctx with\n            | some ctx => MessageData.withContext ctx child\n            | none     => child\n        pure (.lazy children)\n      else\n        pure (.strict (\u2190 children.mapM (go nCtx ctx)))\n    let e := .trace cls header collapsed nodes\n    return .tag (\u2190 pushEmbed e) \".\\n\"\n\npartial def msgToInteractive (msgData : MessageData) (hasWidgets : Bool) (indent : Nat := 0) : IO (TaggedText MsgEmbed) := do\n  if !hasWidgets then\n    return (TaggedText.prettyTagged (\u2190 msgData.format)).rewrite fun _ tt => .text tt.stripTags\n  let (fmt, embeds) \u2190 msgToInteractiveAux msgData\n  let rec fmtToTT (fmt : Format) (indent : Nat) : IO (TaggedText MsgEmbed) :=\n    (TaggedText.prettyTagged fmt indent).rewriteM fun (n, col) tt =>\n      match embeds[n]! with\n        | .code ctx infos =>\n          return .tag (.expr (tagCodeInfos ctx infos tt)) default\n        | .goal ctx lctx g =>\n          ctx.runMetaM lctx do\n            return .tag (.goal (\u2190 goalToInteractive g)) default\n        | .trace cls msg collapsed children => do\n          let col := col + tt.stripTags.length - 2\n          let children \u2190\n            match children with\n              | .lazy children => pure <| .lazy \u27e8{indent := col+2, children := children.map .mk}\u27e9\n              | .strict children => pure <| .strict (\u2190 children.mapM (fmtToTT \u00b7 (col+2)))\n          return .tag (.trace indent cls (\u2190 fmtToTT msg col) collapsed children) default\n        | .ignoreTags => return .text tt.stripTags\n  fmtToTT fmt indent\n\n/-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/\ndef msgToInteractiveDiagnostic (text : FileMap) (m : Message) (hasWidgets : Bool) : IO InteractiveDiagnostic := do\n  let low : Lsp.Position := text.leanPosToLspPos m.pos\n  let fullHigh := text.leanPosToLspPos <| m.endPos.getD m.pos\n  let high : Lsp.Position := match m.endPos with\n    | some endPos =>\n      /-\n        Truncate messages that are more than one line long.\n        This is a workaround to avoid big blocks of \"red squiggly lines\" on VS Code.\n        TODO: should it be a parameter?\n      -/\n      let endPos := if endPos.line > m.pos.line then { line := m.pos.line + 1, column := 0 } else endPos\n      text.leanPosToLspPos endPos\n    | none        => low\n  let range : Range := \u27e8low, high\u27e9\n  let fullRange : Range := \u27e8low, fullHigh\u27e9\n  let severity? := some <| match m.severity with\n    | .information => .information\n    | .warning     => .warning\n    | .error       => .error\n  let source? := some \"Lean 4\"\n  let tags? :=\n    if m.data.isDeprecationWarning then some #[.deprecated]\n    else if m.data.isUnusedVariableWarning then some #[.unnecessary]\n    else none\n  let message \u2190 try\n      msgToInteractive m.data hasWidgets\n    catch ex =>\n      pure <| TaggedText.text s!\"[error when printing message: {ex.toString}]\"\n  pure { range, fullRange? := some fullRange, severity?, source?, message, tags? }\n\nend Lean.Widget\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/Widget/InteractiveDiagnostic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09268778365193332, "lm_q2_score": 0.027169229369486597, "lm_q1q2_score": 0.0025182556537887263}}
{"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\u00a0devDiagnostic`. 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\u00a0reset`, then proceed with 2.\n  - CreateMigration -> proceed with 2.\n2. Call `RPC\u00a0applyMigrations`\n3. If we have no migration name, prompt for it.\n4. Check for the `--create-only` flag\n  - If it was passed, call `RPC\u00a0evaluateDataLoss`, show the warnings,\n    `RPC\u00a0createMigration`. Done.\n  - Otherwise, call `RPC\u00a0evaluateDataLoss`, potentially ask for confirmation,\n    `RPC\u00a0createMigration`, `RPC\u00a0applyMigrations`. 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 { \u03b1 : 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 \u2192 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 \u2192 option ResetReason :=\n\u03bb projectState,\nif (\n  \u00acprojectState.failedMigrationNames.is_nil ||\n  \u00acprojectState.editedMigrationNames.is_nil\n) then\n  some ResetReason.Unspecified\nelse if \u00acprojectState.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 \u2192 option string :=\n\u03bb o,\nmatch (o.drift, o.errorInUnappliedMigrations) with\n| \u27e8some (DriftDiagnostic.MigrationFailedToApply name), _\u27e9 := some name\n| \u27e8_, some name\u27e9 := some name\n| _ := none\nend\n\nexample : monad id := by apply_instance\n\n/-- Machinery to define early returns. -/\ndef devState : Type \u2192 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 \u2192 devState punit :=\n\u03bb 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 \u2192 devState punit :=\n\u03bb 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 \u2192 DiagnoseMigrationHistoryOutput \u2192 devState DevOutput :=\n\u03bb 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 \u2192 DiagnoseMigrationHistoryOutput \u2192 DevOutput :=\n\u03bb 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  \u2200 (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput),\n  projectState.brokenMigration = none \u2192\n  projectState.resetReason.is_some \u2192\n  \u2203 r, runDev input projectState = Reset r :=\nbegin\n  intros input projectState hBroken hReset,\n  delta runDev dev checkBrokenMigration checkReset,\n  obtain \u27e8r, hSome\u27e9 : \u2203 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  \u2200 (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput),\n  projectState.resetReason = none \u2192\n  projectState.brokenMigration = none \u2192\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  \u2200 (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput) (brokenMigrationName : string),\n  projectState.brokenMigration = some brokenMigrationName \u2192\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": "namespace Lean\nsyntax \"foo \" binderIdent : term\nexample : Syntax \u2192 MacroM Syntax\n  | `(foo _) => `(_)\n  | `(foo $x:ident) => `($x:ident)\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/lean/run/1411.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.08151975151186386, "lm_q2_score": 0.028870908304103757, "lm_q1q2_score": 0.002353549270872345}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Daniel Selsam\n-/\nimport Lean.Meta\nimport Lean.Util.FindMVar\nimport Lean.Util.FindLevelMVar\nimport Lean.Util.CollectLevelParams\nimport Lean.Util.ReplaceLevel\nimport Lean.PrettyPrinter.Delaborator.Options\nimport Lean.PrettyPrinter.Delaborator.SubExpr\nimport Std.Data.RBMap\n\n/-!\nThe top-down analyzer is an optional preprocessor to the delaborator that aims\nto determine the minimal annotations necessary to ensure that the delaborated\nexpression can be re-elaborated correctly. Currently, the top-down analyzer\nis neither sound nor complete: there may be edge-cases in which the expression\ncan still not be re-elaborated correctly, and it may also add many annotations\nthat are not strictly necessary.\n-/\n\nnamespace Lean\n\nopen Lean.Meta\nopen Std (RBMap)\n\nregister_builtin_option pp.analyze : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) determine annotations sufficient to ensure round-tripping\"\n}\n\nregister_builtin_option pp.analyze.checkInstances : Bool := {\n  -- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not\n  -- include the `LocalInstances`, so this will be very over-aggressive in inserting instances\n  -- that would otherwise be easy to synthesize. We may consider threading the instances in the future,\n  -- or at least tracking a bool for whether the instances have been lost.\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) confirm that instances can be re-synthesized\"\n}\n\nregister_builtin_option pp.analyze.typeAscriptions : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) add type ascriptions when deemed necessary\"\n}\n\nregister_builtin_option pp.analyze.trustSubst : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' applications that can delab to \u25b8 are 'regular'\"\n}\n\nregister_builtin_option pp.analyze.trustOfNat : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up\"\n}\n\nregister_builtin_option pp.analyze.trustOfScientific : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up\"\n}\n\nregister_builtin_option pp.analyze.trustCoe : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always assume a coercion can be correctly inserted\"\n}\n\n-- TODO: this is an arbitrary special case of a more general principle.\nregister_builtin_option pp.analyze.trustSubtypeMk : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) assume the implicit arguments of Subtype.mk can be inferred\"\n}\n\nregister_builtin_option pp.analyze.trustId : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred\"\n}\n\nregister_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type\"\n}\n\nregister_builtin_option pp.analyze.omitMax : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)\"\n}\n\nregister_builtin_option pp.analyze.knowsType : Bool := {\n  defValue := true\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) assume the type of the original expression is known\"\n}\n\nregister_builtin_option pp.analyze.explicitHoles : Bool := {\n  defValue := false\n  group    := \"pp.analyze\"\n  descr    := \"(pretty printer analyzer) use `_` for explicit arguments that can be inferred\"\n}\n\ndef getPPAnalyze                            (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue\ndef getPPAnalyzeCheckInstances              (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue\ndef getPPAnalyzeTypeAscriptions             (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue\ndef getPPAnalyzeTrustSubst                  (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue\ndef getPPAnalyzeTrustOfNat                  (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue\ndef getPPAnalyzeTrustOfScientific           (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue\ndef getPPAnalyzeTrustId                     (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue\ndef getPPAnalyzeTrustCoe                    (o : Options) : Bool := o.get pp.analyze.trustCoe.name pp.analyze.trustCoe.defValue\ndef getPPAnalyzeTrustSubtypeMk              (o : Options) : Bool := o.get pp.analyze.trustSubtypeMk.name pp.analyze.trustSubtypeMk.defValue\ndef getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue\ndef getPPAnalyzeOmitMax                     (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue\ndef getPPAnalyzeKnowsType                   (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue\ndef getPPAnalyzeExplicitHoles               (o : Options) : Bool := o.get pp.analyze.explicitHoles.name pp.analyze.explicitHoles.defValue\n\ndef getPPAnalysisSkip            (o : Options) : Bool := o.get `pp.analysis.skip false\ndef getPPAnalysisHole            (o : Options) : Bool := o.get `pp.analysis.hole false\ndef getPPAnalysisNamedArg        (o : Options) : Bool := o.get `pp.analysis.namedArg false\ndef getPPAnalysisLetVarType      (o : Options) : Bool := o.get `pp.analysis.letVarType false\ndef getPPAnalysisNeedsType       (o : Options) : Bool := o.get `pp.analysis.needsType false\ndef getPPAnalysisBlockImplicit   (o : Options) : Bool := o.get `pp.analysis.blockImplicit false\n\nnamespace PrettyPrinter.Delaborator\n\ndef returnsPi (motive : Expr) : MetaM Bool := do\n  lambdaTelescope motive fun xs b => b.isForall\n\ndef isNonConstFun (motive : Expr) : MetaM Bool := do\n  match motive with\n  | Expr.lam name d b _ => isNonConstFun b\n  | _ => motive.hasLooseBVars\n\ndef isSimpleHOFun (motive : Expr) : MetaM Bool := do\n  not (\u2190 returnsPi motive) && not (\u2190 isNonConstFun motive)\n\ndef isType2Type (motive : Expr) : MetaM Bool := do\n  match \u2190 inferType motive with\n  | Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => true\n  | _ => false\n\ndef isFOLike (motive : Expr) : MetaM Bool := do\n  let f := motive.getAppFn\n  f.isFVar || f.isConst\n\ndef isIdLike (arg : Expr) : Bool := do\n  -- TODO: allow `id` constant as well?\n  match arg with\n  | Expr.lam _ _ (Expr.bvar ..) .. => true\n  | _ => false\n\ndef isCoe (e : Expr) : Bool :=\n  -- TODO: `coeSort? Builtins doesn't seem to render them anyway\n  e.isAppOfArity `coe 4\n  || (e.isAppOf `coeFun && e.getAppNumArgs >= 4)\n  || e.isAppOfArity `coeSort 4\n\ndef isStructureInstance (e : Expr) : MetaM Bool := do\n  match e.isConstructorApp? (\u2190 getEnv) with\n  | some s => isStructure (\u2190 getEnv) s.induct\n  | none   => false\n\nnamespace TopDownAnalyze\n\npartial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  Option.isSome $ e.findMVar? fun mvarId =>\n    match mctx.findDecl? mvarId with\n    | some mdecl => mdecl.depth == mctx.depth\n    | _ => false\n\npartial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do\n  let mctx \u2190 getMCtx\n  Option.isSome $ e.findLevelMVar? fun mvarId =>\n    mctx.findLevelDepth? mvarId == some mctx.depth\n\nprivate def valUnknown (e : Expr) : MetaM Bool := do\n  hasMVarAtCurrDepth (\u2190 instantiateMVars e)\n\nprivate def typeUnknown (e : Expr) : MetaM Bool := do\n  valUnknown (\u2190 inferType e)\n\ndef isHBinOp (e : Expr) : Bool := do\n  -- TODO: instead of tracking these explicitly,\n  -- consider a more general solution that checks for defaultInstances\n  if e.getAppNumArgs != 6 then return false\n  let f := e.getAppFn\n  if !f.isConst then return false\n\n  -- Note: we leave out `HPow.hPow because we expect its homogeneous\n  -- version will change soon\n  let ops := #[\n    `HOr.hOr, `HXor.hXor, `HAnd.hAnd,\n    `HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen,\n    `HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod,\n    `HShiftLeft.hShiftLeft, `HShiftRight]\n  ops.any fun op => op == f.constName!\n\ndef replaceLPsWithVars (e : Expr) : MetaM Expr := do\n  if !e.hasLevelParam then return e\n  let lps := collectLevelParams {} e |>.params\n  let mut replaceMap : Std.HashMap Name Level := {}\n  for lp in lps do replaceMap := replaceMap.insert lp (\u2190 mkFreshLevelMVar)\n  return e.replaceLevel fun\n    | Level.param n .. => replaceMap.find! n\n    | l => if !l.hasParam then some l else none\n\ndef isDefEqAssigning (t s : Expr) : MetaM Bool := do\n  withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $\n    Meta.isDefEq t s\n\ndef checkpointDefEq (t s : Expr) : MetaM Bool := do\n  Meta.checkpointDefEq (mayPostpone := false) do\n    isDefEqAssigning t s\n\ndef isHigherOrder (type : Expr) : MetaM Bool := do\n  forallTelescopeReducing type fun xs b => xs.size > 0 && b.isSort\n\ndef isFunLike (e : Expr) : MetaM Bool := do\n  forallTelescopeReducing (\u2190 inferType e) fun xs b => xs.size > 0\n\ndef isSubstLike (e : Expr) : Bool :=\n  e.isAppOfArity `Eq.ndrec 6 || e.isAppOfArity `Eq.rec 6\n\ndef nameNotRoundtrippable (n : Name) : Bool :=\n  n.hasMacroScopes || isPrivateName n || containsNum n\nwhere\n  containsNum\n    | Name.str p .. => containsNum p\n    | Name.num ..   => true\n    | Name.anonymous => false\n\ndef mvarName (mvar : Expr) : MetaM Name := do\n  (\u2190 getMVarDecl mvar.mvarId!).userName\n\ndef containsBadMax : Level \u2192 Bool\n  | Level.succ u ..   => containsBadMax u\n  | Level.max u v ..  => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v\n  | Level.imax u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v\n  | _                 => false\n\nopen SubExpr\n\nstructure Context where\n  knowsType   : Bool\n  knowsLevel  : Bool -- only constants look at this\n  inBottomUp  : Bool := false\n  parentIsApp : Bool := false\n  subExpr     : SubExpr\n  deriving Inhabited\n\nstructure State where\n  annotations : RBMap Pos Options compare := {}\n  postponed   : Array (Expr \u00d7 Expr) := #[] -- not currently used\n\nabbrev AnalyzeM := ReaderT Context (StateRefT State MetaM)\n\ninstance (priority := low) : MonadReaderOf SubExpr AnalyzeM where\n  read := Context.subExpr <$> read\n\ninstance (priority := low) : MonadWithReaderOf SubExpr AnalyzeM where\n  withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr }\n\ndef tryUnify (e\u2081 e\u2082 : Expr) : AnalyzeM Unit := do\n  try\n    let r \u2190 isDefEqAssigning e\u2081 e\u2082\n    if !r then modify fun s => { s with postponed := s.postponed.push (e\u2081, e\u2082) }\n    pure ()\n  catch ex =>\n    modify fun s => { s with postponed := s.postponed.push (e\u2081, e\u2082) }\n\npartial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do\n  let argType  \u2190 inferType arg -- HAdd \u03b1 \u03b1 \u03b1\n  let mvarType \u2190 inferType mvar\n  let fType \u2190 inferType argType.getAppFn -- Type \u2192 Type \u2192 outParam Type\n  let mType \u2190 inferType mvarType.getAppFn\n  inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs\nwhere\n  inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do\n    let fType \u2190 whnf fType\n    let mType \u2190 whnf mType\n    if not (i < args.size) then return ()\n    match fType, mType with\n    | Expr.forallE _ fd fb _, Expr.forallE _ md mb _ => do\n      -- TODO: do I need to check (\u2190 okBottomUp? args[i] mvars[i] fuel).isSafe here?\n      -- if so, I'll need to take a callback\n      if isOutParam fd then\n        tryUnify (args[i]) (mvars[i])\n      inspectAux (fb.instantiate1 args[i]) (mb.instantiate1 mvars[i]) (i+1) args mvars\n    | _, _ => return ()\n\npartial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do\n  let opts \u2190 getOptions\n  return e.isFVar\n         || e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort\n         || (getPPAnalyzeTrustOfNat opts && e.isAppOfArity `OfNat.ofNat 3)\n         || (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity `OfScientific.ofScientific 5)\n\npartial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do\n  -- Here we check if `e` can be safely elaborated without its expected type.\n  -- These are incomplete (and possibly unsound) heuristics.\n  -- TODO: do I need to snapshot the state before calling this?\n  match fuel with\n  | 0 => false\n  | fuel + 1 =>\n    if \u2190 isTrivialBottomUp e then return true\n    let f := e.getAppFn\n    if !f.isConst && !f.isFVar then return false\n    let args := e.getAppArgs\n    let fType \u2190 replaceLPsWithVars (\u2190 inferType e.getAppFn)\n    let (mvars, bInfos, resultType) \u2190 forallMetaBoundedTelescope fType e.getAppArgs.size\n    for i in [:mvars.size] do\n      if bInfos[i] == BinderInfo.instImplicit then\n        inspectOutParams args[i] mvars[i]\n      else if \u2190 bInfos[i] == BinderInfo.default then\n        if \u2190 isTrivialBottomUp args[i] then tryUnify args[i] mvars[i]\n        else if \u2190 typeUnknown mvars[i] <&&> canBottomUp args[i] mvars[i] fuel then tryUnify args[i] mvars[i]\n    if \u2190 (isHBinOp e <&&> (valUnknown mvars[0] <||> valUnknown mvars[1])) then tryUnify mvars[0] mvars[1]\n    if mvar?.isSome then tryUnify resultType (\u2190 inferType mvar?.get!)\n    return !(\u2190 valUnknown resultType)\n\ndef withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM \u03b1) : AnalyzeM \u03b1 := do\n  withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x\n\nbuiltin_initialize analyzeFailureId : InternalExceptionId \u2190 registerInternalExceptionId `analyzeFailure\n\ndef checkKnowsType : AnalyzeM Unit := do\n  if not (\u2190 read).knowsType then\n    throw $ Exception.internal analyzeFailureId\n\ndef annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do\n  let opts := (\u2190 get).annotations.findD pos {} |>.setBool n true\n  trace[pp.analyze.annotate] \"{pos} {n}\"\n  modify fun s => { s with annotations := s.annotations.insert pos opts }\n\ndef annotateBool (n : Name) : AnalyzeM Unit := do\n  annotateBoolAt n (\u2190 getPos)\n\nstructure App.Context where\n  f               : Expr\n  fType           : Expr\n  args            : Array Expr\n  mvars           : Array Expr\n  bInfos          : Array BinderInfo\n  forceRegularApp : Bool\n\nstructure App.State where\n  bottomUps       : Array Bool\n  higherOrders    : Array Bool\n  funBinders      : Array Bool\n  provideds       : Array Bool\n  namedArgs       : Array Name := #[]\n\nabbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM)\n\nmutual\n\n  partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do\n    checkMaxHeartbeats \"Delaborator.topDownAnalyze\"\n    trace[pp.analyze] \"{(\u2190 read).knowsType}.{(\u2190 read).knowsLevel}\"\n    let e \u2190 getExpr\n    let opts \u2190 getOptions\n    if \u2190 !e.isAtomic <&&> !(getPPProofs opts) <&&> (try Meta.isProof e catch ex => false) then\n      if getPPProofsWithType opts then\n        withType $ withKnowing true true $ analyze\n      return ()\n    else\n      withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do\n        match (\u2190 getExpr) with\n        | Expr.app ..     => analyzeApp\n        | Expr.forallE .. => analyzePi\n        | Expr.lam ..     => analyzeLam\n        | Expr.const ..   => analyzeConst\n        | Expr.sort ..    => analyzeSort\n        | Expr.proj ..    => analyzeProj\n        | Expr.fvar ..    => analyzeFVar\n        | Expr.mdata ..   => analyzeMData\n        | Expr.letE ..    => analyzeLet\n        | Expr.lit ..     => pure ()\n        | Expr.mvar ..    => pure ()\n        | Expr.bvar ..    => pure ()\n  where\n    analyzeApp := do\n      let mut willKnowType := (\u2190 read).knowsType\n      if !(\u2190 read).knowsType && !(\u2190 canBottomUp (\u2190 getExpr)) then\n        annotateBool `pp.analysis.needsType\n        withType $ withKnowing true false $ analyze\n        willKnowType := true\n\n      else if \u2190 (!(\u2190 read).knowsType <||> (\u2190 read).inBottomUp) <&&> isStructureInstance (\u2190 getExpr) then\n        withType do\n          annotateBool `pp.structureInstanceTypes\n          withKnowing true false $ analyze\n        willKnowType := true\n\n      withKnowing willKnowType true $ analyzeAppStaged (\u2190 getExpr).getAppFn (\u2190 getExpr).getAppArgs\n\n    analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do\n      let fType \u2190 replaceLPsWithVars (\u2190 inferType f)\n      let (mvars, bInfos, resultType) \u2190 forallMetaBoundedTelescope fType args.size\n      let rest := args.extract mvars.size args.size\n      let args := args.shrink mvars.size\n\n      -- Unify with the expected type\n      if (\u2190 read).knowsType then tryUnify (\u2190 inferType (mkAppN f args)) resultType\n\n      let forceRegularApp : Bool :=\n        (getPPAnalyzeTrustSubst (\u2190 getOptions) && isSubstLike (\u2190 getExpr))\n        || (getPPAnalyzeTrustCoe (\u2190 getOptions) && isCoe (\u2190 getExpr))\n        || (getPPAnalyzeTrustSubtypeMk (\u2190 getOptions) && (\u2190 getExpr).isAppOfArity `Subtype.mk 4)\n\n      analyzeAppStagedCore { f, fType, args, mvars, bInfos, forceRegularApp } |>.run' {\n        bottomUps    := mkArray args.size false,\n        higherOrders := mkArray args.size false,\n        provideds    := mkArray args.size false,\n        funBinders   := mkArray args.size false\n      }\n\n      if not rest.isEmpty then\n        -- Note: this shouldn't happen for type-correct terms\n        if !args.isEmpty then\n          analyzeAppStaged (mkAppN f args) rest\n\n    maybeAddBlockImplicit : AnalyzeM Unit := do\n      -- See `MonadLift.noConfusion for an example where this is necessary.\n      if !(\u2190 read).parentIsApp then\n        let type \u2190 inferType (\u2190 getExpr)\n        if type.isForall && type.bindingInfo! == BinderInfo.implicit then\n          annotateBool `pp.analysis.blockImplicit\n\n    analyzeConst : AnalyzeM Unit := do\n      let Expr.const n ls .. \u2190 getExpr | unreachable!\n      if !(\u2190 read).knowsLevel && !ls.isEmpty then\n        -- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590\n        unless getPPAnalyzeOmitMax (\u2190 getOptions) && ls.any containsBadMax do\n        annotateBool `pp.universes\n      maybeAddBlockImplicit\n\n    analyzePi : AnalyzeM Unit := do\n      withBindingDomain $ withKnowing true false analyze\n      withBindingBody Name.anonymous analyze\n\n    analyzeLam : AnalyzeM Unit := do\n      if !(\u2190 read).knowsType then annotateBool `pp.funBinderTypes\n      withBindingDomain $ withKnowing true false analyze\n      withBindingBody Name.anonymous analyze\n\n    analyzeLet : AnalyzeM Unit := do\n      let Expr.letE n t v body .. \u2190 getExpr | unreachable!\n      if !(\u2190 canBottomUp v) then\n        annotateBool `pp.analysis.letVarType\n        withLetVarType $ withKnowing true false analyze\n        withLetValue $ withKnowing true true analyze\n      else\n        withReader (fun ctx => { ctx with inBottomUp := true }) do\n          withLetValue $ withKnowing true true analyze\n\n      withLetBody analyze\n\n    analyzeSort  : AnalyzeM Unit := pure ()\n    analyzeProj  : AnalyzeM Unit := withProj analyze\n    analyzeFVar  : AnalyzeM Unit := maybeAddBlockImplicit\n    analyzeMData : AnalyzeM Unit := withMDataExpr analyze\n\n  partial def analyzeAppStagedCore : AnalyzeAppM Unit := do\n    collectBottomUps\n    checkOutParams\n    collectHigherOrders\n    hBinOpHeuristic\n    collectTrivialBottomUps\n    discard <| processPostponed (mayPostpone := true)\n    applyFunBinderHeuristic\n    analyzeFn\n    for i in [:(\u2190 read).args.size] do analyzeArg i\n    maybeSetExplicit\n\n  where\n    collectBottomUps := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for target in [fun _ => none, fun i => some mvars[i]] do\n        for i in [:args.size] do\n          if bInfos[i] == BinderInfo.default then\n            if \u2190 typeUnknown mvars[i] <&&> canBottomUp args[i] (target i) then\n              tryUnify args[i] mvars[i]\n              modify fun s => { s with bottomUps := s.bottomUps.set! i true }\n\n    checkOutParams := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if bInfos[i] == BinderInfo.instImplicit then inspectOutParams args[i] mvars[i]\n\n    collectHigherOrders := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if not (bInfos[i] == BinderInfo.implicit || bInfos[i] == BinderInfo.strictImplicit) then continue\n        if not (\u2190 isHigherOrder (\u2190 inferType args[i])) then continue\n        if getPPAnalyzeTrustId (\u2190 getOptions) && isIdLike args[i] then continue\n\n        if getPPAnalyzeTrustKnownFOType2TypeHOFuns (\u2190 getOptions) && not (\u2190 valUnknown mvars[i])\n          && (\u2190 isType2Type (args[i])) && (\u2190 isFOLike (args[i])) then continue\n\n        tryUnify args[i] mvars[i]\n        modify fun s => { s with higherOrders := s.higherOrders.set! i true }\n\n    hBinOpHeuristic := do\n      let { args, mvars, bInfos, ..} \u2190 read\n      if \u2190 (isHBinOp (\u2190 getExpr) <&&> (valUnknown mvars[0] <||> valUnknown mvars[1])) then\n        tryUnify mvars[0] mvars[1]\n\n    collectTrivialBottomUps := do\n      -- motivation: prevent levels from printing in\n      -- Boo.mk : {\u03b1 : Type u_1} \u2192 {\u03b2 : Type u_2} \u2192 \u03b1 \u2192 \u03b2 \u2192 Boo.{u_1, u_2} \u03b1 \u03b2\n      let { args, mvars, bInfos, ..} \u2190 read\n      for i in [:args.size] do\n        if bInfos[i] == BinderInfo.default then\n          if \u2190 valUnknown mvars[i] <&&> isTrivialBottomUp args[i] then\n            tryUnify args[i] mvars[i]\n            modify fun s => { s with bottomUps := s.bottomUps.set! i true }\n\n    applyFunBinderHeuristic := do\n      let { f, args, mvars, bInfos, .. } \u2190 read\n\n      let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do\n        match \u2190 getExpr, mvarType with\n        | Expr.lam .., Expr.forallE n t b .. =>\n          let mut annotated := false\n          for i in [:argIdx] do\n            if \u2190 bInfos[i] == BinderInfo.implicit <&&> valUnknown mvars[i] <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]) then\n              annotateBool `pp.funBinderTypes\n              tryUnify args[i] mvars[i]\n              -- Note: currently we always analyze the lambda binding domains in `analyzeLam`\n              -- (so we don't need to analyze it again here)\n              annotated := true\n              break\n          let annotatedBody \u2190 withBindingBody Name.anonymous (core argIdx b)\n          return annotated || annotatedBody\n\n        | _, _ => return false\n\n      for i in [:args.size] do\n        if \u2190 bInfos[i] == BinderInfo.default then\n          let b \u2190 withNaryArg i (core i (\u2190 inferType mvars[i]))\n          if b then modify fun s => { s with funBinders := s.funBinders.set! i true }\n\n    analyzeFn := do\n      -- Now, if this is the first staging, analyze the n-ary function without expected type\n      let {f, fType, forceRegularApp ..} \u2190 read\n      if !f.isApp then withKnowing false (forceRegularApp || !(\u2190 hasLevelMVarAtCurrDepth (\u2190 instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true))\n\n    annotateNamedArg (n : Name) : AnalyzeAppM Unit := do\n      annotateBool `pp.analysis.namedArg\n      modify fun s => { s with namedArgs := s.namedArgs.push n }\n\n    analyzeArg (i : Nat) := do\n      let { f, args, mvars, bInfos, forceRegularApp ..} \u2190 read\n      let { bottomUps, higherOrders, funBinders, ..} \u2190 get\n      let arg := args[i]\n      let argType \u2190 inferType arg\n\n      let processNaturalImplicit : AnalyzeAppM Unit := do\n        if (\u2190 valUnknown mvars[i] <||> higherOrders[i]) && !forceRegularApp then\n          annotateNamedArg (\u2190 mvarName mvars[i])\n          modify fun s => { s with provideds := s.provideds.set! i true }\n        else\n          annotateBool `pp.analysis.skip\n\n      withNaryArg (f.getAppNumArgs + i) do\n        withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i] }) do\n\n          match bInfos[i] with\n          | BinderInfo.default =>\n            if \u2190 getPPAnalyzeExplicitHoles (\u2190 getOptions) <&&> !(\u2190 valUnknown mvars[i]) <&&> !(\u2190 readThe Context).inBottomUp <&&> !(\u2190 isFunLike arg) <&&> !funBinders[i] <&&> checkpointDefEq mvars[i] arg then\n              annotateBool `pp.analysis.hole\n            else\n              modify fun s => { s with provideds := s.provideds.set! i true }\n\n          | BinderInfo.implicit => processNaturalImplicit\n          | BinderInfo.strictImplicit => processNaturalImplicit\n\n          | BinderInfo.instImplicit =>\n            -- Note: apparently checking valUnknown here is not sound, because the elaborator\n            -- will not happily assign instImplicits that it cannot synthesize\n            let mut provided := true\n            if !getPPInstances (\u2190 getOptions) then\n              annotateBool `pp.analysis.skip\n              provided := false\n            else if getPPAnalyzeCheckInstances (\u2190 getOptions) then\n              let instResult \u2190 try trySynthInstance argType catch _ => LOption.undef\n              match instResult with\n              | LOption.some inst =>\n                if \u2190 checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false\n                else annotateNamedArg (\u2190 mvarName mvars[i])\n              | _                 => annotateNamedArg (\u2190 mvarName mvars[i])\n            else annotateBool `pp.analysis.skip; provided := false\n            modify fun s => { s with provideds := s.provideds.set! i provided }\n          | BinderInfo.auxDecl => pure ()\n          if (\u2190 get).provideds[i] then withKnowing (not (\u2190 typeUnknown mvars[i])) true analyze\n          tryUnify mvars[i] args[i]\n\n    maybeSetExplicit := do\n      let { f, args, mvars, bInfos, forceRegularApp, ..} \u2190 read\n      if (\u2190 get).namedArgs.any nameNotRoundtrippable then\n        annotateBool `pp.explicit\n        for i in [:args.size] do\n          if !(\u2190 get).provideds[i] then\n            withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole\n          if bInfos[i] == BinderInfo.instImplicit && getPPInstanceTypes (\u2190 getOptions) then\n            withType (withKnowing true false analyze)\n\nend\n\nend TopDownAnalyze\n\nopen TopDownAnalyze SubExpr\n\ndef topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do\n  let s\u2080 \u2190 get\n  traceCtx `pp.analyze do\n    withReader (fun ctx => { ctx with config := Lean.Elab.Term.setElabConfig ctx.config }) do\n      let \u03d5 : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; (\u2190 get).annotations\n      try\n        let knowsType := getPPAnalyzeKnowsType (\u2190 getOptions)\n        \u03d5 { knowsType := knowsType, knowsLevel := knowsType, subExpr := mkRoot e }\n          |>.run' { : TopDownAnalyze.State }\n      catch ex =>\n        trace[pp.analyze.error] \"failed\"\n        pure {}\n      finally set s\u2080\n\nbuiltin_initialize\n  registerTraceClass `pp.analyze\n  registerTraceClass `pp.analyze.annotate\n  registerTraceClass `pp.analyze.tryUnify\n  registerTraceClass `pp.analyze.error\n\nend Lean.PrettyPrinter.Delaborator\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/PrettyPrinter/Delaborator/TopDownAnalyze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07807816514495095, "lm_q2_score": 0.029760093730832948, "lm_q1q2_score": 0.002323613513045194}}
{"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Daniel Selsam\n-/\nimport Mathport.Syntax.Translate.Basic\n\nnamespace Mathport.Translate\n\nopen Lean hiding Expr Expr.app Expr.const Expr.sort Level Level.imax Level.max Level.param Command\nopen Lean.Elab (Visibility)\nopen Lean.Elab.Command (CommandElabM liftCoreM)\nopen Parser.Command AST3\n\ndef elabCommand (stx : Syntax.Command) : CommandElabM Unit := do\n  -- try dbg_trace \"warning: elaborating:\\n{\u2190 liftCoreM $\n  --   Lean.PrettyPrinter.parenthesizeCommand stx >>= Lean.PrettyPrinter.formatCommand}\"\n  -- catch e => dbg_trace \"warning: failed to format: {\u2190 e.toMessageData.toString}\\nin: {stx}\"\n  Elab.Command.elabCommand stx\n\ndef pushElab (stx : Syntax.Command) : M Unit := elabCommand stx *> push stx\n\ndef modifyScope (f : Scope \u2192 Scope) : M Unit :=\n  modify fun s => { s with current := f s.current }\n\ndef pushScope : M Unit :=\n  modify fun s => { s with scopes := s.scopes.push s.current }\n\ndef popScope : M Unit :=\n  modify fun s => match s.scopes.back? with\n  | none => s\n  | some c => { s with current := c, scopes := s.scopes.pop }\n\ndef registerNotationEntry (loc : Bool) (d : NotationData) : M Unit :=\n  if loc then modifyScope fun sc => { sc with localNotations := sc.localNotations.insert d }\n  else registerGlobalNotationEntry d\n\ndef trDerive (e : Spanned AST3.Expr) : M Name :=\n  match e.kind.unparen with\n  | Expr.ident n => renameIdent n\n  | Expr.const \u27e8_, n\u27e9 _ choices => renameIdent n choices\n  | e => warn! \"unsupported derive handler {repr e}\"\n\ninductive TrAttr\n  | del : TSyntax ``eraseAttr \u2192 TrAttr\n  | add : Syntax.Attr \u2192 TrAttr\n  | prio : Expr \u2192 TrAttr\n  | parsingOnly : TrAttr\n  | irreducible : TrAttr\n  | derive : Array Name \u2192 TrAttr\n\ndef trAttr (_prio : Option Expr) : Attribute \u2192 M (Option TrAttr)\n  | Attribute.priority n => pure $ TrAttr.prio n.kind\n  | Attribute.del n => do\n    let n \u2190 match n with\n    | `instance => pure `instance\n    | `simp => pure `simp\n    | `congr => pure `congr\n    | `inline => pure `inline\n    | `pattern => pure `match_pattern\n    | _ => warn! \"warning: unsupported attr -{n}\"; return none\n    pure $ some $ TrAttr.del (\u2190 `(eraseAttr| -$(\u2190 mkIdentI n)))\n  | AST3.Attribute.add `parsing_only none => pure TrAttr.parsingOnly\n  | AST3.Attribute.add `irreducible none => pure TrAttr.irreducible\n  | AST3.Attribute.add n arg => do\n    let attr \u2190 match n, arg with\n    | `class,              none => `(attr| class)\n    | `instance,           none => `(attr| instance)\n    | `simp,               none => `(attr| simp)\n    | `recursor,           some \u27e8_, AttrArg.indices #[]\u27e9 => warn! \"unsupported: @[recursor]\"\n    | `recursor,           some \u27e8_, AttrArg.indices #[\u27e8_, n\u27e9]\u27e9 =>\n      `(attr| recursor $(Quote.quote n):num)\n    | `intro,              none => `(attr| intro)\n    | `intro,              some \u27e8_, AttrArg.eager\u27e9 => `(attr| intro!)\n    | `refl,               none => pure $ mkSimpleAttr `refl\n    | `symm,               none => pure $ mkSimpleAttr `symm\n    | `trans,              none => pure $ mkSimpleAttr `trans\n    | `subst,              none => pure $ mkSimpleAttr `subst\n    | `congr,              none => pure $ mkSimpleAttr `congr\n    | `inline,             none => pure $ mkSimpleAttr `inline\n    | `pattern,            none => pure $ mkSimpleAttr `match_pattern\n    | `reducible,          none => pure $ mkSimpleAttr `reducible\n    | `semireducible,      none => pure $ mkSimpleAttr `semireducible\n    | `irreducible,        none => pure $ mkSimpleAttr `irreducible\n    | `elab_simple,        none => pure $ mkSimpleAttr `elab_without_expected_type\n    | `elab_as_eliminator, none => pure $ mkSimpleAttr `elab_as_elim\n    | `vm_override,        some \u27e8_, AttrArg.vmOverride n none\u27e9 =>\n      pure $ mkSimpleAttr `implemented_by #[\u2190 mkIdentI n.kind]\n    | `derive,             some \u27e8_, AttrArg.user _ args\u27e9 =>\n      return TrAttr.derive $ \u2190 (\u2190 Parser.pExprListOrTExpr.run' args).mapM trDerive\n    | `algebra,            _ => return none -- this attribute is no longer needed\n    | _, none => mkSimpleAttr <$> renameAttr n\n    | _, some \u27e8_, AttrArg.user e args\u27e9 =>\n      match (\u2190 get).userAttrs.find? n, args with\n      | some f, _ =>\n        let attr \u2190 try f #[Spanned.dummy (AST3.Param.parse e args)]\n        catch e => warn! \"in {n}: {\u2190 e.toMessageData.toString}\"\n        if attr.raw.isMissing then return none\n        pure attr\n      | none, #[] => mkSimpleAttr <$> renameAttr n\n      | none, _ => warn! \"unsupported user attr {n}\"\n    | _, _ =>\n      warn! \"warning: suppressing unknown attr {n}\"\n      return none\n    pure $ TrAttr.add attr\n\ndef trAttrKind : AttributeKind \u2192 M (TSyntax ``Parser.Term.attrKind)\n  | .global => `(Parser.Term.attrKind|)\n  | .scoped => `(Parser.Term.attrKind| scoped)\n  | .local => `(Parser.Term.attrKind| local)\n\nstructure SpecialAttrs where\n  prio : Option AST3.Expr := none\n  parsingOnly := false\n  irreducible := false\n  derive : Array Name := #[]\n\ndef AttrState := SpecialAttrs \u00d7 Array Syntax.EraseOrAttrInstance\n\ndef trAttrInstance (attr : Attribute) (allowDel := false)\n  (kind : AttributeKind := .global) : StateT AttrState M Unit := do\n  match \u2190 trAttr (\u2190 get).1.prio attr with\n  | some (TrAttr.del stx) => do\n    unless allowDel do warn! \"unsupported (impossible)\"\n    modify fun s => { s with 2 := s.2.push stx }\n  | some (TrAttr.add stx) => do\n    let stx \u2190 `(Parser.Term.attrInstance| $(\u2190 trAttrKind kind) $stx)\n    modify fun s => { s with 2 := s.2.push stx }\n  | some (TrAttr.prio prio) => modify fun s => { s with 1.prio := prio }\n  | some TrAttr.parsingOnly => modify fun s => { s with 1.parsingOnly := true }\n  | some TrAttr.irreducible => modify fun s => { s with 1.irreducible := true }\n  | some (TrAttr.derive ns) => modify fun s => { s with 1.derive := s.1.derive ++ ns }\n  | none => pure ()\n\ndef trAttributes (attrs : Attributes) (allowDel := false)\n  (kind : AttributeKind := .global) : StateT AttrState M Unit :=\n  attrs.forM fun attr => trAttrInstance attr.kind allowDel kind\n\nstructure Modifiers4 where\n  docComment : Option String := none\n  attrs : AttrState := ({}, #[])\n  vis : Visibility := Visibility.regular\n  \u00abnoncomputable\u00bb : Option Unit := none\n  safety : DefinitionSafety := DefinitionSafety.safe\n\ndef trModifiers (mods : Modifiers) (more : Attributes := #[]) :\n    M (SpecialAttrs \u00d7 TSyntax ``declModifiers) :=\n  mods.foldlM trModifier {} >>= trAttrs more >>= toSyntax\nwhere\n  trAttrs (attrs : Attributes) (kind : AttributeKind := .global)\n    (s : Modifiers4) : M Modifiers4 := do\n    pure { s with attrs := (\u2190 trAttributes attrs false kind s.attrs).2 }\n\n  trModifier (s : Modifiers4) (m : Spanned Modifier) : M Modifiers4 :=\n    match m.kind with\n    | .private => match s.vis with\n      | .regular => pure { s with vis := .private }\n      | _ => throw! \"unsupported (impossible)\"\n    | .protected => match s.vis with\n      | .regular => pure { s with vis := .protected }\n      | _ => throw! \"unsupported (impossible)\"\n    | .noncomputable => match s.noncomputable with\n      | none => pure { s with \u00abnoncomputable\u00bb := some () }\n      | _ => throw! \"unsupported (impossible)\"\n    | .meta => match s.safety with\n      | .safe => pure { s with safety := .unsafe }\n      | _ => throw! \"unsupported (impossible)\"\n    | .mutual => pure s -- mutual is duplicated elsewhere in the grammar\n    | .attr loc _ attrs => trAttrs attrs (if loc then .local else .global) s\n    | .doc doc => match s.docComment with\n      | none => pure { s with docComment := some doc }\n      | _ => throw! \"unsupported (impossible)\"\n  toSyntax : Modifiers4 \u2192 M (SpecialAttrs \u00d7 TSyntax ``declModifiers)\n  | \u27e8doc, (s, attrs), vis, nc, safety\u27e9 => do\n    let doc := doc.map trDocComment\n    let attrs : Array (TSyntax ``Parser.Term.attrInstance) :=\n      attrs.map fun s => \u27e8s\u27e9 -- HACK HACK HACK ignores @[-attr]\n    let attrs \u2190 attrs.asNonempty.mapM fun attrs => `(Parser.Term.attributes| @[$[$attrs],*])\n    let vis \u2190 show M (Option (TSyntax [``\u00abprivate\u00bb, ``\u00abprotected\u00bb])) from match vis with\n      | .regular => pure none\n      | .private => `(\u00abprivate\u00bb| private)\n      | .protected => `(\u00abprotected\u00bb| protected)\n    let nc \u2190 nc.mapM fun () => `(\u00abnoncomputable\u00bb| noncomputable)\n    let part \u2190 match safety with\n      | .partial => some <$> `(\u00abpartial\u00bb| partial)\n      | _ => pure none\n    let uns \u2190 match safety with\n      | .unsafe => some <$> `(\u00abunsafe\u00bb| unsafe)\n      | _ => pure none\n    return (s, \u2190 `(declModifiersF| $(doc)? $(attrs)? $(vis)? $(nc)? $(uns)? $(part)?))\n\ndef trOpenCmd (ops : Array Open) : M Unit := do\n  let mut simple := #[]\n  let pushSimple (s : Array Ident) :=\n    unless s.isEmpty do pushElab $ \u2190 `(command| open $[$s]*)\n  for o in ops do\n    match o with\n    | \u27e8tgt, none, clauses\u27e9 =>\n      if clauses.isEmpty then\n        simple := simple.push (\u2190 mkIdentN tgt.kind)\n      else\n        pushSimple simple; simple := #[]\n        let mut explicit := #[]\n        let mut renames := #[]\n        let mut hides := #[]\n        for c in clauses do\n          match c.kind with\n          | .explicit ns => explicit := explicit ++ ns\n          | .renaming ns => renames := renames ++ ns\n          | .hiding ns => hides := hides ++ ns\n        match explicit.isEmpty, renames.isEmpty, hides.isEmpty with\n        | true, true, true => pure ()\n        | false, true, true =>\n          let ns \u2190 explicit.mapM fun n => mkIdentF n.kind\n          pushElab $ \u2190 `(command| open $(\u2190 mkIdentN tgt.kind):ident ($ns*))\n        | true, false, true =>\n          let rs \u2190 renames.mapM fun \u27e8a, b\u27e9 => do\n            `(openRenamingItem| $(\u2190 mkIdentF a.kind):ident \u2192 $(\u2190 mkIdentF b.kind):ident)\n          pushElab $ \u2190 `(command| open $(\u2190 mkIdentN tgt.kind):ident renaming $rs,*)\n        | true, true, false =>\n          let ns \u2190 hides.mapM fun n => mkIdentF n.kind\n          pushElab $ \u2190 `(command| open $(\u2190 mkIdentN tgt.kind):ident hiding $ns*)\n        | _, _, _ => warn! \"unsupported: advanced open style\"\n    | _ => warn! \"unsupported: unusual advanced open style\"\n  pushSimple simple\n\ndef trExportCmd : Open \u2192 M Unit\n  | \u27e8tgt, none, clauses\u27e9 => do\n    let mut args := #[]\n    for c in clauses do\n      match c.kind with\n      | .explicit ns =>\n        for n in ns do args := args.push (\u2190 mkIdentF n.kind)\n      | _ => warn! \"unsupported: advanced export style\"\n    pushElab $ \u2190 `(export $(\u2190 mkIdentN tgt.kind):ident ($args*))\n  | _ => warn! \"unsupported: advanced export style\"\n\ndef trDeclId (n : Name) (us : LevelDecl) (translateToAdditive : Bool) :\n    M (Option Name \u00d7 TSyntax ``declId) := do\n  let us := us.map $ Array.map fun u => mkIdent u.kind\n  let orig := Elab.Command.resolveNamespace (\u2190 get).current.curNamespace n\n  let ((dubious, n4), id) \u2190 renameIdentCore n #[orig]\n  if (\u2190 read).config.redundantAlign then\n    pushAlign orig n4\n    if translateToAdditive then\n      if let some add4 := ToAdditive.findTranslation? (\u2190 getEnv) n4 then\n        if let some (add3, _) :=\n            (Mathlib.Prelude.Rename.getRenameMap (\u2190 getEnv)).toLean3.find? add4 then\n          pushAlign add3 add4\n  let (n3, _) := Rename.getClashes (\u2190 getEnv) n4\n  let mut msg := Format.nil\n  let mut found := none\n  if dubious.isEmpty && (\u2190 getEnv).contains n4 && !binportTag.hasTag (\u2190 getEnv) n4 then\n    found := n4 -- if the definition already exists, abort the current command\n  if orig != n3 then\n    if dubious.isEmpty then\n      found := n4 -- if the clash is authoritative, abort the current command\n    msg := msg ++ f!\"warning: {orig} clashes with {n3} -> {n4}\\n\"\n  if !dubious.isEmpty then\n    msg := msg ++ f!\"warning: {orig} -> {n4} is a dubious translation:\\n{dubious}\\n\"\n  if !msg.isEmpty then\n    logComment f!\"{msg}Case conversion may be inaccurate. Consider using '#align {orig} {n4}\u2093'.\"\n  return (found, \u2190 `(declId| $(\u2190 mkIdentR id):ident $[.{$us,*}]?))\n\ndef trDeclSig (bis : Binders) (ty : Option (Spanned Expr)) : M (TSyntax ``declSig) := do\n  let bis \u2190 trBinders {} bis\n  let ty \u2190 trExpr (ty.getD <| Spanned.dummy Expr.\u00ab_\u00bb)\n  `(declSig| $[$bis]* : $ty)\n\ndef trOptDeclSig (bis : Binders) (ty : Option (Spanned Expr)) : M (TSyntax ``optDeclSig) := do\n  let bis \u2190 trBinders {} bis\n  `(optDeclSig| $[$bis]* $[: $(\u2190 ty.mapM trExpr)]?)\n\ndef trAxiom (mods : Modifiers) (n : Name)\n    (us : LevelDecl) (bis : Binders) (ty : Option (Spanned Expr)) : M Unit := do\n  let toAdd := mods.hasToAdditive\n  let (s, mods) \u2190 trModifiers mods\n  unless s.derive.isEmpty do warn! \"unsupported: @[derive] axiom\"\n  let (found, id) \u2190 trDeclId n us toAdd\n  withReplacement found do\n    pushM `(command| $mods:declModifiers axiom $id $(\u2190 trDeclSig bis ty))\n\ndef trUWF : Option (Spanned Expr) \u2192\n    M (Option (TSyntax ``terminationByCore) \u00d7 Option (TSyntax ``decreasingBy))\n  | none | some \u27e8_, AST3.Expr.\u00ab{}\u00bb\u27e9 => pure (none, none)\n  | some \u27e8_, AST3.Expr.structInst _ none flds #[] false\u27e9 => do\n    let mut tm := none; let mut dc := none\n    for (\u27e8_, n\u27e9, \u27e8s, e\u27e9) in flds do\n      match n with\n      | `rel_tac =>\n        let .fun _ _ \u27e8_, .\u00ab`[]\u00bb #[\u27e8_, .interactive `exact #[\u27e8_, .parse _ #[\u27e8s, .expr e\u27e9]\u27e9]\u27e9]\u27e9 := e\n          | warn! \"warning: unsupported using_well_founded rel_tac: {repr e}\"\n        tm := some (\u2190 `(terminationByCore| termination_by' $(\u2190 trExpr \u27e8s, e\u27e9):term))\n      | `dec_tac =>\n        dc := some (\u2190 `(decreasingBy| decreasing_by $(\u2190 trTactic (.dummy <| .expr \u27e8s, e\u27e9)):tactic))\n      | _ => warn! \"warning: unsupported using_well_founded config option: {n}\"\n    if let some dc' := dc then\n      -- this is a little optimistic, but let's hope that lean 4 doesn't need\n      -- `decreasing_by assumption` as much as lean 3 did\n      if dc' matches `(decreasingBy| decreasing_by assumption) then dc := none\n    pure (tm, dc)\n  | some _ => warn! \"warning: unsupported using_well_founded config syntax\" | pure (none, none)\n\ndef trDecl (dk : DeclKind) (mods : Modifiers) (attrs : Attributes)\n    (n : Option (Spanned Name)) (us : LevelDecl) (bis : Binders) (ty : Option (Spanned Expr))\n    (val : DeclVal) (uwf : Option (Spanned Expr)) : M (Option Name \u00d7 Syntax.Command) := do\n  let toAdd := mods.hasToAdditive || attrs.hasToAdditive\n  let (s, mods) \u2190 trModifiers mods attrs\n  let id \u2190 n.mapM fun n => trDeclId n.kind us toAdd\n  (id >>= (\u00b7.1), \u00b7) <$> do\n  let id := (\u00b7.2) <$> id\n  let val \u2190 match val with\n    | DeclVal.expr e => `(declVal| := $(\u2190 trExprUnspanned e))\n    | DeclVal.eqns #[] => `(declVal| := fun.)\n    | DeclVal.eqns arms => `(declVal| $[$(\u2190 arms.mapM trArm):matchAlt]*)\n  if s.irreducible then\n    unless dk matches DeclKind.def do warn! \"unsupported irreducible non-definition\"\n    unless s.derive.isEmpty do warn! \"unsupported: @[derive, irreducible] def\"\n    unless uwf.isNone do warn! \"unsupported: @[irreducible] def + using_well_founded\"\n    return \u2190 `($mods:declModifiers irreducible_def $id.get! $(\u2190 trOptDeclSig bis ty) $val:declVal)\n  match dk with\n  | DeclKind.abbrev => do\n    unless s.derive.isEmpty do warn! \"unsupported: @[derive] abbrev\"\n    unless uwf.isNone do warn! \"unsupported: abbrev + using_well_founded\"\n    `($mods:declModifiers abbrev $id.get! $(\u2190 trOptDeclSig bis ty):optDeclSig $val)\n  | DeclKind.def => do\n    let ds := s.derive.map mkIdent |>.asNonempty\n    let (tm, dc) \u2190 trUWF uwf\n    `($mods:declModifiers\n      def $id.get! $(\u2190 trOptDeclSig bis ty) $val:declVal $[deriving $ds,*]? $(tm)? $(dc)?)\n  | DeclKind.example => do\n    unless s.derive.isEmpty do warn! \"unsupported: @[derive] example\"\n    unless uwf.isNone do warn! \"unsupported: example + using_well_founded\"\n    `($mods:declModifiers example $(\u2190 trOptDeclSig bis ty):optDeclSig $val)\n  | DeclKind.theorem => do\n    unless s.derive.isEmpty do warn! \"unsupported: @[derive] theorem\"\n    let (tm, dc) \u2190 trUWF uwf\n    `($mods:declModifiers\n      theorem $id.get! $(\u2190 trDeclSig bis ty) $val:declVal $(tm)? $(dc)?)\n  | DeclKind.instance => do\n    unless s.derive.isEmpty do warn! \"unsupported: @[derive] instance\"\n    let prio \u2190 s.prio.mapM fun prio => do\n      `(namedPrio| (priority := $(\u2190 trPrio prio)))\n    let sig \u2190 trDeclSig bis ty\n    let (tm, dc) \u2190 trUWF uwf\n    `($mods:declModifiers\n      instance $[$prio:namedPrio]? $[$id:declId]? $sig $val:declVal $(tm)? $(dc)?)\n\ndef trOptDeriving : Array Name \u2192 M (TSyntax ``optDeriving)\n  | #[] => `(optDeriving|)\n  | ds => `(optDeriving| deriving $[$(ds.map mkIdent):ident],*)\n\nset_option linter.unusedVariables false in -- FIXME(Mario): spurious warning on let ctors \u2190 ...\ndef trInductive (cl : Bool) (mods : Modifiers) (attrs : Attributes)\n  (n : Spanned Name) (us : LevelDecl) (bis : Binders) (ty : Option (Spanned Expr))\n  (nota : Option Notation) (intros : Array (Spanned Intro)) : M (Option Name \u00d7 Syntax.Command) := do\n  let toAdd := mods.hasToAdditive || attrs.hasToAdditive\n  let (s, mods) \u2190 trModifiers mods attrs\n  let (found, id) \u2190 trDeclId n.kind us toAdd\n  (found, \u00b7) <$> do\n  let sig \u2190 trOptDeclSig bis ty\n  unless nota.isNone do warn! \"unsupported: (notation) in inductive\"\n  let ctors \u2190 intros.mapM fun \u27e8m, \u27e8doc, name, ik, bis, ty\u27e9\u27e9 => withSpanS m do\n    if let some ik := ik then warn! \"infer kinds are unsupported in Lean 4: {name.2} {ik}\"\n    `(ctor| $[$(doc.map trDocComment):docComment]?\n      | $(\u2190 mkIdentI name.kind):ident $(\u2190 trOptDeclSig bis ty):optDeclSig)\n  let ds \u2190 trOptDeriving s.derive\n  match cl with\n  | true => `($mods:declModifiers class inductive\n    $id:declId $sig:optDeclSig $[$ctors:ctor]* $ds:optDeriving)\n  | false => `($mods:declModifiers inductive\n    $id:declId $sig:optDeclSig $[$ctors:ctor]* $ds:optDeriving)\n\ndef trMutual (decls : Array (Mutual \u03b1)) (uwf : Option (Spanned Expr))\n    (f : Mutual \u03b1 \u2192 M (Option Name \u00d7 Syntax.Command)) : M Unit := do\n  let mut found := none\n  let mut cmds := #[]\n  for decl in decls do\n    let (found', cmd) \u2190 f decl\n    found := found <|> found'\n    cmds := cmds.push cmd\n  let (tm, dc) \u2190 trUWF uwf\n  withReplacement found do pushM `(mutual $cmds* end $(tm)? $(dc)?)\n\ndef trField : Spanned Field \u2192 M (Array Syntax) := spanning fun\n  | Field.binder bi ns ik bis ty dflt => do\n    let ns \u2190 ns.mapM fun n => mkIdentF n.kind\n    if let some ik := ik then warn! \"infer kinds are unsupported in Lean 4: {ns} {ik}\"\n    (#[\u00b7]) <$> match bi with\n    | BinderInfo.implicit => do\n      `(structImplicitBinder| {$ns* $(\u2190 trDeclSig bis ty):declSig})\n    | BinderInfo.instImplicit => do\n      `(structInstBinder| [$ns* $(\u2190 trDeclSig bis ty):declSig])\n    | _ => do\n      let sig \u2190 trOptDeclSig bis ty\n      let dflt \u2190 dflt.mapM trBinderDefault\n      if let #[n] := ns then\n        `(structSimpleBinder| $n:ident $sig:optDeclSig $[$dflt]?)\n      else\n        `(structExplicitBinder| ($ns* $sig:optDeclSig $[$dflt]?))\n  | Field.notation _ => warn! \"unsupported: (notation) in structure\"\n\ndef trFields (flds : Array (Spanned Field)) : M (TSyntax ``structFields) := do\n  let flds \u2190 flds.concatMapM trField\n  pure $ mkNode ``structFields #[mkNullNode flds]\n\ndef trStructure (cl : Bool) (mods : Modifiers) (n : Spanned Name) (us : LevelDecl)\n  (bis : Binders) (exts : Array (Spanned Parent)) (ty : Option (Spanned Expr))\n  (mk : Option (Spanned Mk)) (flds : Array (Spanned Field)) : M Unit := do\n  let toAdd := mods.hasToAdditive\n  let (s, mods) \u2190 trModifiers mods\n  let (found, id) \u2190 trDeclId n.kind us toAdd\n  withReplacement found do\n  let bis \u2190 trBracketedBinders {} bis\n  let exts \u2190 exts.mapM fun\n    | \u27e8_, false, none, ty, #[]\u27e9 => trExpr ty\n    | _ => warn! \"unsupported: advanced extends in structure\"\n  let exts \u2190 exts.asNonempty.mapM fun exts => `(\u00abextends\u00bb| extends $[$exts],*)\n  let ty \u2190 trOptType ty\n  let (ctor, flds) \u2190 match mk, flds with\n    | none, #[] => pure (none, none)\n    | mk, flds => do\n      let mk \u2190 mk.mapM fun \u27e8_, n, ik\u27e9 => do\n        if let some ik := ik then warn! \"infer kinds are unsupported in Lean 4: {n.2} {ik}\"\n        `(structCtor| $(\u2190 mkIdentF n.kind):ident ::)\n      pure (some mk, some (\u2190 trFields flds))\n  let deriv \u2190 trOptDeriving s.derive\n  let decl \u2190\n    if cl then\n      `(\u00abstructure\u00bb|\n        class $id:declId $[$bis]* $[$exts]? $[$ty]? $[where $[$ctor]? $flds]? $deriv)\n    else\n      `(\u00abstructure\u00bb|\n        structure $id:declId $[$bis]* $[$exts]? $[$ty]? $[where $[$ctor]? $flds]? $deriv)\n  pushM `(command| $mods:declModifiers $decl:structure)\n\npartial def mkUnusedName [Monad m] [MonadResolveName m] [MonadEnv m]\n  (baseName : Name) : m Name := do\n  let ns \u2190 getCurrNamespace\n  let env \u2190 getEnv\n  return if env.contains (ns ++ baseName) then\n    let rec loop (idx : Nat) :=\n      let name := baseName.appendIndexAfter idx\n      if env.contains (ns ++ name) then loop (idx+1) else name\n    loop 1\n  else baseName\n\nsection\n\nprivate def mkNAry (lits : Array (Spanned AST3.Literal)) : Option (Array Literal) := do\n  let mut i := 0\n  let mut out := #[]\n  for lit in lits do\n    match lit with\n    | \u27e8_, AST3.Literal.sym tk\u27e9 => out := out.push (Literal.tk tk.1.kind.toString)\n    | \u27e8_, AST3.Literal.var _ _\u27e9 => out := out.push (Literal.arg i); i := i + 1\n    | \u27e8_, AST3.Literal.binder _\u27e9 => out := out.push (Literal.arg i); i := i + 1\n    | \u27e8_, AST3.Literal.binders _\u27e9 => out := out.push (Literal.arg i); i := i + 1\n    | _ => none\n  pure out\n\npartial def trPrecExpr : Expr \u2192 M Precedence\n  | Expr.nat n => pure $ Precedence.nat n\n  | Expr.paren e => trPrecExpr e.kind -- do `(prec| ($(\u2190 trPrecExpr e.kind)))\n  | Expr.const \u27e8_, `max\u27e9 _ _ => pure Precedence.max\n  | Expr.const \u27e8_, `std.prec.max_plus\u27e9 _ _ => pure Precedence.maxPlus\n  | Expr.notation (Choice.one `\u00abexpr + \u00bb) #[\n      \u27e8_, Arg.expr (Expr.ident `max)\u27e9,\n      \u27e8_, Arg.expr (Expr.nat 1)\u27e9\n    ] => pure Precedence.maxPlus\n  | e => warn! \"unsupported: advanced prec syntax {repr e}\" | pure $ Precedence.nat 999\n\ndef trPrec : AST3.Precedence \u2192 M Precedence\n  | AST3.Precedence.nat n => pure $ Precedence.nat n\n  | AST3.Precedence.expr e => trPrecExpr e.kind\n\nprivate def isIdentPrec : AST3.Literal \u2192 Bool\n  | AST3.Literal.sym _ => true\n  | AST3.Literal.var _ none => true\n  | AST3.Literal.var _ (some \u27e8_, Action.prec _\u27e9) => true\n  | _ => false\n\nprivate def truncatePrec (prec : Precedence) : Precedence := Id.run do\n  -- https://github.com/leanprover-community/mathport/issues/114#issuecomment-1046582957\n  if let Precedence.nat n := prec then\n    if n > 1024 then\n      return Precedence.nat 1024\n  return prec\n\nprivate def trMixfix (kind : TSyntax ``Parser.Term.attrKind) (prio : Option (TSyntax ``namedPrio))\n    (m : AST3.MixfixKind) (tk : String) (prec : Option (Spanned AST3.Precedence)) :\n    M (NotationDesc \u00d7 (Option (TSyntax ``namedName) \u2192 Term \u2192 Id Syntax.Command)) := do\n  let p \u2190 match prec with\n  | some p => trPrec p.kind\n  | none => pure $ (\u2190 getPrecedence? tk m).getD (Precedence.nat 0)\n  let p := truncatePrec p\n  let p := p.toSyntax\n  let s := Syntax.mkStrLit tk\n  pure $ match m with\n  | MixfixKind.infix | MixfixKind.infixl =>\n    (NotationDesc.infix tk, fun n e =>\n      `($kind:attrKind infixl:$p $[$n:namedName]? $[$prio:namedPrio]? $s => $e))\n  | MixfixKind.infixr =>\n    (NotationDesc.infix tk, fun n e =>\n      `($kind:attrKind infixr:$p $[$n:namedName]? $[$prio:namedPrio]? $s => $e))\n  | MixfixKind.prefix =>\n    (NotationDesc.prefix tk, fun n e =>\n      `($kind:attrKind prefix:$p $[$n:namedName]? $[$prio:namedPrio]? $s => $e))\n  | MixfixKind.postfix =>\n    (NotationDesc.postfix tk, fun n e =>\n      `($kind:attrKind postfix:$p $[$n:namedName]? $[$prio:namedPrio]? $s => $e))\n\nprivate def trNotation4 (kind : TSyntax ``Parser.Term.attrKind)\n    (prio : Option (TSyntax ``namedPrio)) (p : Option Prec) (lits : Array (Spanned AST3.Literal)) :\n    M (Option (TSyntax ``namedName) \u2192 Term \u2192 Id Syntax.Command) := do\n  let lits \u2190 lits.mapM fun\n  | \u27e8_, AST3.Literal.sym tk\u27e9 => `(notationItem| $(Syntax.mkStrLit tk.1.kind.toString):str)\n  | \u27e8_, AST3.Literal.var x none\u27e9 => `(notationItem| $(mkIdent x.kind):ident)\n  | \u27e8_, AST3.Literal.var x (some \u27e8_, Action.prec p\u27e9)\u27e9 => do\n    `(notationItem| $(mkIdent x.kind):ident : $((\u2190 trPrec p).toSyntax))\n  | _ => warn! \"unsupported (impossible)\"\n  pure fun n e =>\n    `($kind:attrKind notation$[:$p]? $[$n:namedName]? $[$prio:namedPrio]? $lits* => $e)\n\nopen Lean.Parser.Command in\nprivate def trNotation3Item : (lit : AST3.Literal) \u2192 M (Array (TSyntax ``notation3Item))\n  | .sym tk => pure #[sym tk]\n  | .binder .. | .binders .. => return #[\u2190 `(notation3Item| (...))]\n  | .var x none\n  | .var x (some \u27e8_, .prec _\u27e9)\n  | .var x (some \u27e8_, .prev\u27e9) => pure #[var x]\n  | .var x (some \u27e8_, .scoped _ sc\u27e9) => return #[\u2190 scope x sc]\n  | .var x (some \u27e8_, .fold r _ sep \u00abrec\u00bb (some ini) term\u27e9) => do\n    let f \u2190 fold x r sep \u00abrec\u00bb ini\n    pure $ match term.map sym with | none => #[f] | some a => #[f, a]\n  | lit => warn! \"unsupported: advanced notation ({repr lit})\"\nwhere\n  sym tk := Id.run `(notation3Item| $(Syntax.mkStrLit tk.1.kind.toString):str)\n  var x := Id.run `(notation3Item| $(mkIdent x.kind):ident)\n  scope x sc := do\n    let (p, e) := match sc with\n      | none => (`x, Spanned.dummy $ Expr.ident `x)\n      | some (p, e) => (p.kind, e)\n    `(notation3Item| $(mkIdent x.kind):ident : (scoped $(mkIdent p) => $(\u2190 trExpr e)))\n  fold x r sep | (y, z, \u00abrec\u00bb), ini => do\n    let kind \u2190 if r then `(foldKind| foldr) else `(foldKind| foldl)\n    `(notation3Item| ($(mkIdent x.kind) $(Syntax.mkStrLit sep.1.kind.toString)* =>\n        $kind ($(mkIdent y.kind) $(mkIdent z.kind) => $(\u2190 trExpr rec)) $(\u2190 trExpr ini)))\n\nprivate def addSpaceBeforeBinders (lits : Array AST3.Literal) : Array AST3.Literal := Id.run do\n  let mut lits := lits\n  for i in [1:lits.size] do\n    if lits[i]! matches AST3.Literal.binder .. || lits[i]! matches AST3.Literal.binders .. then\n      if let AST3.Literal.sym (\u27e8s, Symbol.quoted tk\u27e9, prec) := lits[i-1]! then\n        if !tk.endsWith \" \" then\n          lits := lits.set! (i-1) <| AST3.Literal.sym (\u27e8s, Symbol.quoted (tk ++ \" \")\u27e9, prec)\n  lits\n\nprivate def trNotation3 (kind : TSyntax ``Parser.Term.attrKind)\n    (prio : Option (TSyntax ``namedPrio)) (p : Option Prec) (lits : Array (Spanned AST3.Literal)) :\n    M (Option (TSyntax ``namedName) \u2192 Term \u2192 Id Syntax.Command) := do\n  let lits := addSpaceBeforeBinders <| lits.map (\u00b7.kind)\n  let lits \u2190 lits.concatMapM trNotation3Item\n  pure fun n e =>\n    `($kind:attrKind notation3$[:$p]? $[$n:namedName]? $[$prio:namedPrio]? $lits* => $e)\n\ndef trNotationCmd (kind : AttributeKind) (res : Bool) (attrs : Attributes) (nota : Notation)\n  (ns : Option Name := none) : M Unit := do\n  let (s, attrs) := (\u2190 trAttributes attrs false .global |>.run ({}, #[])).2\n  unless s.derive.isEmpty do warn! \"unsupported: @[derive] notation\"\n  unless attrs.isEmpty do warn! \"unsupported (impossible)\"\n  if res then\n    match nota with\n    | Notation.mixfix m _ (tk, some prec) _ =>\n      registerPrecedenceEntry tk.kind.toString m (\u2190 trPrec prec.kind)\n    | _ => warn! \"warning: suppressing unsupported reserve notation\"\n    return\n  let n := nota.name3\n  let skip : Bool := match \u2190 getNotationEntry? n with\n  | some \u27e8_, _, _, skip\u27e9 => skip\n  | none => false\n  if skip && kind != .local then return\n  let prio \u2190 s.prio.mapM fun prio => do `(namedPrio| (priority := $(\u2190 trPrio prio)))\n  let kindStx \u2190 trAttrKind kind\n  let (e, desc, cmd) \u2190 match nota with\n  | Notation.mixfix m _ (tk, prec) (some e) =>\n    pure (e, \u2190 trMixfix kindStx prio m tk.kind.toString prec)\n  | Notation.notation _ lits (some e) =>\n    let p := match lits.get? 0 with\n    | some \u27e8_, AST3.Literal.sym tk\u27e9 => tk.2\n    | some \u27e8_, AST3.Literal.var _ _\u27e9 => match lits.get? 1 with\n      | some \u27e8_, AST3.Literal.sym tk\u27e9 => tk.2\n      | _ => none\n    | _ => none\n    let p \u2190 p.mapM fun p => return (\u2190 trPrec p.kind).toSyntax\n    let desc := match lits with\n    | #[\u27e8_, AST3.Literal.sym tk\u27e9] => NotationDesc.const tk.1.kind.trim\n    | #[\u27e8_, AST3.Literal.sym left\u27e9,\n        \u27e8_, AST3.Literal.var _ (some \u27e8_, Action.fold _ _ sep _ _ (some term)\u27e9)\u27e9] =>\n      NotationDesc.exprs left.1.kind.trim sep.1.kind.trim term.1.kind.trim\n    | _ => match mkNAry lits with\n      | some lits => NotationDesc.nary lits\n      | none => NotationDesc.fail\n    let cmd \u2190 match lits.all fun lit => isIdentPrec lit.kind with\n    | true => trNotation4 kindStx prio p lits\n    | false => trNotation3 kindStx prio p lits\n    pure (e, desc, cmd)\n  | _ => warn! \"unsupported (impossible)\" | default\n  let e \u2190 trExpr e\n  let ns' := match ns with\n  | none => .anonymous\n  | some ns => rootNamespace ++ ns\n  let n4 \u2190 Elab.Command.withWeakNamespace (ns' ++ (\u2190 getEnv).mainModule) $ do\n    let n4 \u2190 mkUnusedName nota.name4\n    let nn \u2190 `(namedName| (name := $(mkIdent n4)))\n    try elabCommand (cmd (some nn) e)\n    catch e => dbg_trace \"warning: failed to add syntax {repr n4}: {\u2190 e.toMessageData.toString}\"\n    pure $ (\u2190 getCurrNamespace) ++ n4\n  printOutput s!\"-- mathport name: {n}\\n\"\n  if let some ns := ns then\n    pushM `(command| scoped[$(\u2190 mkIdentR ns)] $(cmd none e))\n  else push (cmd none e)\n  registerNotationEntry (kind == .local) \u27e8n, n4, desc\u27e9\n\nend\n\ndef trInductiveCmd : InductiveCmd \u2192 M Unit\n  | InductiveCmd.reg cl mods n us bis ty nota intros => do\n    let (found, cmd) \u2190 trInductive cl mods #[] n us bis ty nota intros\n    withReplacement found (push cmd)\n  | InductiveCmd.mutual cl mods us bis nota inds =>\n    trMutual inds none fun \u27e8attrs, n, ty, intros\u27e9 => do\n      trInductive cl mods attrs n us bis ty nota intros\n\ndef trAttributeCmd (kind : AttributeKind) (attrs : Attributes) (ns : Array (Spanned Name))\n    (f : Syntax.Command \u2192 Syntax.Command) : M Unit := do\n  if ns.isEmpty then return ()\n  let (s, attrs) := (\u2190 trAttributes attrs true kind |>.run ({}, #[])).2\n  let ns \u2190 ns.mapM fun n => mkIdentI n.kind\n  unless s.derive.isEmpty do\n    push $ f $ \u2190 `(deriving instance $[$(s.derive.map mkIdent):ident],* for $ns,*)\n  unless attrs.isEmpty do\n    push $ f $ \u2190 `(attribute [$attrs,*] $ns*)\n\ndef trCommand' : Command \u2192 M Unit\n  | Command.initQuotient => pushM `(init_quot)\n  | Command.mdoc doc =>\n    push \u27e8mkNode ``moduleDoc #[mkAtom \"/-!\", mkAtom (doc ++ \"-/\")]\u27e9\n  | Command.\u00abuniverse\u00bb _ _ ns =>\n    pushM `(universe $(ns.map fun n => mkIdent n.kind)*)\n  | Command.\u00abnamespace\u00bb n => do\n    pushScope; modifyScope fun s => { s with curNamespace := s.curNamespace ++ n.kind }\n    pushElab $ \u2190 `(namespace $(\u2190 mkIdentN n.kind))\n  | Command.\u00absection\u00bb n => do\n    pushScope; pushElab $ \u2190 `(section $(\u2190 n.mapM fun n => mkIdentN n.kind)?)\n  | Command.\u00abend\u00bb n => do\n    popScope; pushElab $ \u2190 `(end $(\u2190 n.mapM fun n => mkIdentN n.kind)?)\n  | Command.\u00abvariable\u00bb vk _ _ bis =>\n    unless bis.isEmpty do\n      let bis \u2190 trBracketedBinders {} bis\n      match vk with\n      | VariableKind.variable => pushM `(variable $bis*)\n      | VariableKind.parameter => pushM `(parameter $bis*)\n  | Command.axiom _ mods n us bis ty => trAxiom mods n.kind us bis ty\n  | Command.axioms _ mods bis => bis.forM fun\n    | \u27e8_, Binder.binder _ (some ns) bis (some ty) none\u27e9 => ns.forM fun\n      | \u27e8_, BinderName.ident n\u27e9 => trAxiom mods n none bis ty\n      | _ => warn! \"unsupported (impossible)\"\n    | _ => warn! \"unsupported (impossible)\"\n  | Command.decl dk mods n us bis ty val uwf => do\n    let (found, cmd) \u2190 trDecl dk mods #[] n us bis ty val.kind uwf\n    withReplacement found (push cmd)\n  | Command.mutualDecl dk mods us bis arms uwf =>\n    trMutual arms uwf fun \u27e8attrs, n, ty, vals\u27e9 =>\n      trDecl dk mods attrs n us bis ty (DeclVal.eqns vals) none\n  | Command.inductive ind => trInductiveCmd ind\n  | Command.structure cl mods n us bis exts ty m flds =>\n    trStructure cl mods n us bis exts ty m flds\n  | Command.attribute loc _ attrs ns =>\n    trAttributeCmd (if loc then .local else .global) attrs ns id\n  | Command.precedence .. => warn! \"warning: unsupported: precedence command\"\n  | Command.notation (loc, res) attrs n =>\n    trNotationCmd (if loc then .local else .global) res attrs n\n  | Command.open true ops => ops.forM trExportCmd\n  | Command.open false ops => trOpenCmd ops\n  | Command.include true ops => unless ops.isEmpty do\n      pushM `(include $(ops.map fun n => mkIdent n.kind)*)\n  | Command.include false ops => unless ops.isEmpty do\n      pushM `(omit $(ops.map fun n => mkIdent n.kind)*)\n  | Command.hide ops => unless ops.isEmpty do\n      warn! \"unsupported: hide command\"\n      -- pushM `(hide $(ops.map fun n => mkIdent n.kind)*)\n  | Command.theory #[\u27e8_, Modifier.noncomputable\u27e9] =>\n    pushM `(command| noncomputable section)\n  | Command.theory #[\u27e8_, Modifier.doc doc\u27e9, \u27e8_, Modifier.noncomputable\u27e9] => do\n    printOutput s!\"/-!{doc}-/\\n\"\n    pushM `(command| noncomputable section)\n  | Command.theory _ => warn! \"unsupported (impossible)\"\n  | Command.setOption o val => match o.kind, val.kind with\n    | `old_structure_cmd, OptionVal.bool b =>\n      modifyScope fun s => { s with oldStructureCmd := b }\n    | o, OptionVal.bool true => do\n      pushM `(command| set_option $(\u2190 mkIdentO o) true)\n    | o, OptionVal.bool false => do\n      pushM `(command| set_option $(\u2190 mkIdentO o) false)\n    | o, OptionVal.str s => do\n      pushM `(command| set_option $(\u2190 mkIdentO o) $(Syntax.mkStrLit s):str)\n    | o, OptionVal.nat n => do\n      pushM `(command| set_option $(\u2190 mkIdentO o) $(Quote.quote n):num)\n    | _, OptionVal.decimal .. => warn! \"unsupported: float-valued option\"\n  | Command.declareTrace n => do\n    let n \u2190 renameIdent n.kind\n    pushM `(command| initialize registerTraceClass $(Quote.quote n))\n  | Command.addKeyEquivalence .. => warn! \"unsupported: add_key_equivalence\"\n  | Command.runCmd e => do let e \u2190 trExpr e; pushM `(run_cmd $e:term)\n  | Command.check e => do pushM `(#check $(\u2190 trExpr e))\n  | Command.reduce _ e => do pushM `(#reduce $(\u2190 trExpr e))\n  | Command.eval e => do pushM `(#eval $(\u2190 trExpr e))\n  | Command.unify .. => warn! \"unsupported: #unify\"\n  | Command.compile .. => warn! \"unsupported: #compile\"\n  | Command.help .. => warn! \"unsupported: #help\"\n  | Command.print (PrintCmd.str s) => pushM `(#print $(Syntax.mkStrLit s))\n  | Command.print (PrintCmd.ident n) => do pushM `(#print $(\u2190 mkIdentI n.kind))\n  | Command.print (PrintCmd.axioms (some n)) => do pushM `(#print axioms $(\u2190 mkIdentI n.kind))\n  | Command.print _ => warn! \"unsupported: advanced #print\"\n  | Command.userCommand n mods args => do\n    match (\u2190 get).userCmds.find? n with\n    | some f => try f mods args catch e => warn! \"in {n} {repr args}: {\u2190 e.toMessageData.toString}\"\n    | none => warn! \"unsupported user command {n}\"\n", "meta": {"author": "leanprover-community", "repo": "mathport", "sha": "b5459df41774820ca21861417fafd8ff7a662fc5", "save_path": "github-repos/lean/leanprover-community-mathport", "path": "github-repos/lean/leanprover-community-mathport/mathport-b5459df41774820ca21861417fafd8ff7a662fc5/Mathport/Syntax/Translate/Command.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09947020587339866, "lm_q2_score": 0.022977369993656183, "lm_q1q2_score": 0.0022855637236982333}}
{"text": "import evaluation_modified\nimport utils\n\n-- TODO(jesse): code duplication >:(\n\nnamespace openai\n\nsection openai_api\n\nmeta structure CompletionRequest : Type :=\n(prompt : string)\n(max_tokens : int := 16)\n(temperature : native.float := 1.0)\n(top_p : native.float := 1)\n(n : int := 1)\n(best_of : option int := none)\n(stream : option bool := none)\n(logprobs : int := 0)\n(echo : option bool := none)\n(stop : option string := none) -- TODO(jesse): list string\n(presence_penalty : option native.float := none)\n(frequency_penalty : option native.float := none)\n(show_trace : bool := ff)\n(prompt_token := \"PROOFSTEP\")\n-- don't support logit_bias for now\n\n-- TODO(jesse): write a derive handler for this kind of structure serialization\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 \u2192 bool := \u03bb n, n \u2264 2048 in\nlet validate_float_frac : native.float \u2192 bool := \u03bb k, 0 \u2264 k \u2227 k \u2264 1 in\nlet validate_and_return {\u03b1} [has_to_format \u03b1] (pred : \u03b1 \u2192 bool) : \u03b1 \u2192 tactic \u03b1 :=\n  \u03bb a, ((guard $ pred a) *> pure a <|> by {tactic.unfreeze_local_instances, exact (tactic.fail format!\"[openai.CompletionRequest.to_tactic_json] VALIDATION FAILED FOR {a}\")}) in\nlet validate_optional_and_return {\u03b1} [has_to_format \u03b1] (pred : \u03b1 \u2192 bool) : option \u03b1 \u2192 tactic (option \u03b1) := \u03bb x, do {\n  match x with\n  | (some val) := some <$> by {tactic.unfreeze_local_instances, exact (validate_and_return pred val)}\n  | none := pure none\n  end\n} in\nlet MAX_N : int := 100000 in\nlet fn : CompletionRequest \u2192 tactic json := \u03bb req, match req with\n| \u27e8prompt, max_tokens, temperature, top_p, n, best_of,\n  stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _, _\u27e9 := do\n  -- TODO(jesse): ensure validation does not fail silently\n  max_tokens \u2190 validate_and_return validate_max_tokens max_tokens,\n  -- temperature \u2190 validate_and_return validate_float_frac temperature,\n  top_p \u2190 validate_and_return validate_float_frac top_p,\n  n \u2190 validate_and_return (\u03bb x, 0 \u2264 x \u2227 x \u2264 MAX_N) /- go wild with the candidates -/ n,\n  best_of \u2190 validate_optional_and_return (\u03bb x, n \u2264 x \u2227 x \u2264 MAX_N) best_of,\n  presence_penalty \u2190 validate_optional_and_return validate_float_frac presence_penalty,\n  frequency_penalty \u2190 validate_optional_and_return validate_float_frac frequency_penalty,\n\n  eval_trace $ \"[openai.CompletionRequest.to_tactic_json] VALIDATION PASSED\",\n\n  let pre_kvs : list (string \u00d7 option json) := [\n    (\"prompt\", json.of_string prompt),\n    (\"max_tokens\", json.of_int max_tokens),\n    (\"temperature\", json.of_float temperature),\n    (\"top_p\", json.of_float top_p),\n    (\"n\", json.of_int n),\n    (\"best_of\", json.of_int <$> best_of),\n    (\"stream\", json.of_bool <$> stream),\n    (\"logprobs\", some $ json.of_int logprobs),\n    (\"echo\", json.of_bool <$> echo),\n    (\"stop\", json.of_string <$> stop),\n    (\"presence_penalty\", json.of_float <$> presence_penalty),\n    (\"frequency_penalty\", json.of_float <$> frequency_penalty)\n  ],\n\n  pure $ json.object $ pre_kvs.filter_map (\u03bb \u27e8k,mv\u27e9, prod.mk k <$> mv)\nend\nin \u27e8fn\u27e9\n\n/-\nexample from API docs:\ncurl https://api.openai.com/v1/engines/davinci/completions \\\n  -H 'Content-Type: application/json' \\\n  -H 'Authorization: Bearer $OPENAI_API_KEY' \\\n  -d '{\n  \"prompt\": \"Once upon a time\",\n  \"max_tokens\": 5\n}'\n-/\nmeta def dummy_cr : CompletionRequest :=\n{prompt := \"Once upon a time\", max_tokens := 5, temperature := 1.0, top_p := 1.0, n := 3}\n\nmeta def CompletionRequest.to_cmd (engine_id : string) (api_key : string) : CompletionRequest \u2192 io (io.process.spawn_args)\n| req@\u27e8prompt, max_tokens, temperature, top_p, n, best_of,\n  stream, logprobs, echo, stop, presence_penalty, frequency_penalty, _, _\u27e9 := do\nwhen EVAL_TRACE $ io.put_str_ln' format!\"[openai.CompletionRequest.to_cmd] ENTERING\",\nserialized_req \u2190 io.run_tactic' $ has_to_tactic_json.to_tactic_json req,\nwhen EVAL_TRACE $ io.put_str_ln' format!\"[openai.CompletionRequest.to_cmd] SERIALIZED\",\npure {\n--  cmd := \"sh\",\n--  args := [\n--      \"./echo.sh\"\n--  ]\n  cmd := \"python3\",\n  args := [\n      format.to_string $ format!\"src/gptf_8epoch.py\"\n      , json.unparse serialized_req\n    ]\n}\n\nsetup_tactic_parser\n\n-- nice, it works\n-- example {p q} (h\u2081 : p) (h\u2082 : q) : p \u2227 q :=\n-- begin\n--   apply and.intro, do {tactic.read >>= postprocess_tactic_state >>= eval_trace}\n-- end\n\nmeta def serialize_ts\n  (req : CompletionRequest)\n  : tactic_state \u2192 tactic CompletionRequest := \u03bb ts, do {\n  ts_str \u2190 ts.fully_qualified >>= postprocess_tactic_state,\n  let prompt : string :=\n    \"[LN] GOAL \" ++ ts_str ++ (format! \" {req.prompt_token} \").to_string,\n  eval_trace format!\"\\n \\n \\n PROMPT: {prompt} \\n \\n \\n \",\n  pure {\n    prompt := prompt,\n    ..req}\n}\n\nsetup_tactic_parser\n\nprivate meta def decode_response_msg : json \u2192 io (json \u00d7 json) := \u03bb response_msg, do {\n  (json.array choices) \u2190 lift_option $ response_msg.lookup \"choices\" | io.fail' format!\"can't find choices in {response_msg}\",\n  prod.mk <$> (json.array <$> choices.mmap (\u03bb choice, lift_option $ json.lookup choice \"text\")) <*> do {\n    logprobss \u2190 choices.mmap (\u03bb msg, lift_option $ msg.lookup \"logprobs\"),\n    scoress \u2190 logprobss.mmap (\u03bb logprobs, lift_option $ logprobs.lookup \"token_logprobs\"),\n    result \u2190 json.array <$> scoress.mmap (lift_option \u2218 json_float_array_sum),\n    pure result\n  }\n}\n\nmeta def openai_api (engine_id : string) (api_key : string) : ModelAPI CompletionRequest :=\nlet fn : CompletionRequest \u2192 io json := \u03bb req, do {\n  proc_cmds \u2190 req.to_cmd engine_id api_key,\n  -- when req.show_trace $ io.put_str_ln' format!\"[openai_api] PROC_CMDS: {proc_cmds}\",\n  response_raw \u2190 io.cmd proc_cmds,\n  when req.show_trace $ io.put_str_ln' format!\"[openai_api] RAW RESPONSE: {response_raw}\",\n\n  response_msg \u2190 (lift_option $ json.parse response_raw) | io.fail' format!\"[openai_api] JSON PARSE FAILED {response_raw}\",\n    \n  when req.show_trace $ io.put_str_ln' format!\"GOT RESPONSE_MSG\",\n\n  -- predictions \u2190 (lift_option $ do {\n  --   (json.array choices) \u2190 response_msg.lookup \"choices\" | none,\n  --   /- `choices` is a list of {text: ..., index: ..., logprobs: ..., finish_reason: ...}-/\n  --   texts \u2190 choices.mmap (\u03bb choice, choice.lookup \"text\"),\n  --   (scoress : list json) \u2190 choices.mmap (\u03bb msg, msg.lookup \"logprobs\" >>= \u03bb x, x.lookup \"token_logprobs\"),\n  --   -- scores \u2190 scoress.mmap (\u03bb xs, xs.map (\u03bb msg,\n  --   scores \u2190 scoress.mmap json_float_array_sum,\n  --   pure $ prod.mk texts scores\n  --  }) \n\n  do {\n    predictions \u2190 decode_response_msg response_msg | io.fail' format!\"[openai_api] UNEXPECTED RESPONSE MSG: {response_msg}\",\n    when req.show_trace $ io.put_str_ln' format!\"PREDICTIONS: {predictions}\",\n    pure (json.array [predictions.fst, predictions.snd])\n  } <|> pure (json.array $ [json.of_string $ format.to_string $ format!\"ERROR {response_msg}\"]) -- catch API errors here\n} in \u27e8fn\u27e9\n\nend openai_api\n\nsection openai_proof_search\n\nmeta def read_first_line : string \u2192 io string := \u03bb path, do\n  buffer.to_string <$> (io.mk_file_handle path io.mode.read >>= io.fs.get_line)\n\n-- in entry point, API key is read from command line and then set as an environment variable for the execution\n-- of the command\n\n@[inline, reducible]meta def tab : char := '\\t'\n\n@[inline, reducible]meta def newline : char := '\\n'\n\nmeta def default_partial_req : openai.CompletionRequest :=\n{\n  prompt := \"\",\n  max_tokens := 128,\n  temperature := (0.7 : native.float),\n  top_p := 1,\n  n := 1,\n  best_of := none,\n  stream := none,\n  logprobs := 0,\n  echo := none,\n  stop := none, -- TODO(jesse): list string,\n  presence_penalty := none,\n  frequency_penalty := none,\n  show_trace := EVAL_TRACE\n}\n\n/- this is the entry point for the evalution harness -/\nmeta def openai_bfs_proof_search_core\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  : state_t BFSState tactic unit := do\nmonad_lift $ set_show_eval_trace partial_req.show_trace,\nbfs_core\n  (openai_api engine_id api_key)\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[openai_greedy_proof_search_core]\") msg n)\n        (fuel)\n\n/- for testing API failure handling.\n   replace `openai.openai_bfs_proof_search_core` with\n   `openai.dummy_openai_bfs_proof_search_core` in\n   `evaluation/bfs/gptf.lean` and confirm that the\n   produced `.json` files show `api_failures = 1`\n-/\nmeta def dummy_openai_bfs_proof_search_core\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  : state_t BFSState tactic unit := do\nmonad_lift $ set_show_eval_trace partial_req.show_trace,\nbfs_core\n    dummy_api\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[openai_greedy_proof_search_core]\") msg n)\n        (fuel)\n\n/- meant for interactive use -/\nmeta def openai_bfs_proof_search\n  (partial_req : openai.CompletionRequest)\n  (engine_id : string)\n  (api_key : string)\n  (fuel := 5)\n  (verbose := ff)\n  (max_width : \u2115 := 25)\n  (max_depth : \u2115 := 50)\n  : tactic unit := do\nset_show_eval_trace partial_req.show_trace,\nbfs\n  (openai_api engine_id api_key)\n    (openai.serialize_ts partial_req)\n      (\u03bb msg n, run_all_beam_candidates (unwrap_lm_response_logprobs $ some \"[openai_greedy_proof_search]\") msg n)\n        (fuel) (verbose) (max_width) (max_depth)\n\nend openai_proof_search\n\nsection playground\n\nexample : true :=\nbegin\n  trivial\n  -- openai_bfs_proof_search default_partial_req \"formal-large-lean-webmath-1230-v1-c4\" API_KEY\nend\n\n-- example : true :=\n-- begin\n--   openai_greedy_proof_search\n--     default_partial_req\n--       \"formal-large-lean-webmath-1230-v1-c4\"\n--         API_KEY\n-- end\n\n-- example (n : \u2115) (m : \u2115) : nat.succ (n + m) < (nat.succ n + m) + 1  :=\n-- begin\n--   -- openai_greedy_proof_search\n--   --   {n := 10, temperature := 0.7, ..default_partial_req}\n--   --     \"formal-large-lean-webmath-1230-v1-c4\"\n--   --       API_KEY 10 tt,\n-- sorry\n-- -- rw succ_add,  exact nat.lt_succ_self _\n-- end\n\n-- theorem t2 (p q r : Prop) (h\u2081 : p) (h\u2082 : q) : (q \u2227 p) \u2228 r :=\n\n-- lemma peirce_identity {P Q :Prop} : ((P \u2192 Q) \u2192 P) \u2192 P :=\n-- begin\n--   openai_greedy_proof_search\n--     {n := 25, temperature := 0.7, ..default_partial_req}\n--       \"formal-large-lean-webmath-1230-v1-c4\"\n--         API_KEY 10,\n-- end\n\n-- --   openai_greedy_proof_search\n-- --     default_partial_req\n-- --       \"formal-large-lean-webmath-1230-v1-c4\"\n-- --         API_KEY\n-- -- -- simp [or_assoc, or_comm, or_left_comm]\n\n-- end\n\nend playground\n\nend openai\n", "meta": {"author": "toontran", "repo": "pact-lean-low-resource", "sha": "e24af1935b7f518f4d3ce5fe55e0a8fd1d541b82", "save_path": "github-repos/lean/toontran-pact-lean-low-resource", "path": "github-repos/lean/toontran-pact-lean-low-resource/pact-lean-low-resource-e24af1935b7f518f4d3ce5fe55e0a8fd1d541b82/src/backends/bfs/gptf_8epoch.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970576514555529, "lm_q2_score": 0.02064593284829514, "lm_q1q2_score": 0.0022649778602659722}}
{"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, Sebastian Ullrich\n-/\nimport Lean.Parser.Extension\n-- necessary for auto-generation\nimport Lean.PrettyPrinter.Parenthesizer\nimport Lean.PrettyPrinter.Formatter\n\nnamespace Lean\nnamespace Parser\n\n-- synthesize pretty printers for parsers declared prior to `Lean.PrettyPrinter`\n-- (because `Parser.Extension` depends on them)\nattribute [runBuiltinParserAttributeHooks]\n  leadingNode termParser commandParser mkAntiquot nodeWithAntiquot sepBy sepBy1\n  unicodeSymbol nonReservedSymbol\n\n@[runBuiltinParserAttributeHooks] def optional (p : Parser) : Parser :=\n  optionalNoAntiquot (withAntiquotSpliceAndSuffix `optional p (symbol \"?\"))\n\n@[runBuiltinParserAttributeHooks] def many (p : Parser) : Parser :=\n  manyNoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol \"*\"))\n\n@[runBuiltinParserAttributeHooks] def many1 (p : Parser) : Parser :=\n  many1NoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol \"*\"))\n\n@[runBuiltinParserAttributeHooks] def ident : Parser :=\n  withAntiquot (mkAntiquot \"ident\" identKind) identNoAntiquot\n\n-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name\n@[runBuiltinParserAttributeHooks] def rawIdent : Parser :=\n  withAntiquot (mkAntiquot \"ident\" identKind) rawIdentNoAntiquot\n\n@[runBuiltinParserAttributeHooks] def numLit : Parser :=\n  withAntiquot (mkAntiquot \"numLit\" numLitKind) numLitNoAntiquot\n\n@[runBuiltinParserAttributeHooks] def scientificLit : Parser :=\n  withAntiquot (mkAntiquot \"scientificLit\" scientificLitKind) scientificLitNoAntiquot\n\n@[runBuiltinParserAttributeHooks] def strLit : Parser :=\n  withAntiquot (mkAntiquot \"strLit\" strLitKind) strLitNoAntiquot\n\n@[runBuiltinParserAttributeHooks] def charLit : Parser :=\n  withAntiquot (mkAntiquot \"charLit\" charLitKind) charLitNoAntiquot\n\n@[runBuiltinParserAttributeHooks] def nameLit : Parser :=\n  withAntiquot (mkAntiquot \"nameLit\" nameLitKind) nameLitNoAntiquot\n\n@[runBuiltinParserAttributeHooks, inline] def group (p : Parser) : Parser :=\n  node groupKind p\n\n@[runBuiltinParserAttributeHooks, inline] def many1Indent (p : Parser) : Parser :=\n  withPosition $ many1 (checkColGe \"irrelevant\" >> p)\n\n@[runBuiltinParserAttributeHooks, inline] def manyIndent (p : Parser) : Parser :=\n  withPosition $ many (checkColGe \"irrelevant\" >> p)\n\n@[runBuiltinParserAttributeHooks] abbrev notSymbol (s : String) : Parser :=\n  notFollowedBy (symbol s) s\n\n/-- No-op parser that advises the pretty printer to emit a non-breaking space. -/\n@[inline] def ppHardSpace : Parser := skip\n/-- No-op parser that advises the pretty printer to emit a space/soft line break. -/\n@[inline] def ppSpace : Parser := skip\n/-- No-op parser that advises the pretty printer to emit a hard line break. -/\n@[inline] def ppLine : Parser := skip\n/-- No-op parser combinator that advises the pretty printer to emit a `Format.fill` node. -/\n@[inline] def ppRealFill : Parser \u2192 Parser := id\n/-- No-op parser combinator that advises the pretty printer to emit a `Format.group` node. -/\n@[inline] def ppRealGroup : Parser \u2192 Parser := id\n/-- No-op parser combinator that advises the pretty printer to indent the given syntax without grouping it. -/\n@[inline] def ppIndent : Parser \u2192 Parser := id\n/--\n  No-op parser combinator that advises the pretty printer to group and indent the given syntax.\n  By default, only syntax categories are grouped. -/\n@[inline] def ppGroup (p : Parser) : Parser := ppRealFill (ppIndent p)\n/--\n  No-op parser combinator that advises the pretty printer to dedent the given syntax.\n  Dedenting can in particular be used to counteract automatic indentation. -/\n@[inline] def ppDedent : Parser \u2192 Parser := id\n\n/--\n  No-op parser combinator that allows the pretty printer to omit the group and\n  indent operation in the enclosing category parser.\n  ```\n  syntax ppAllowUngrouped \"by \" tacticSeq : term\n  -- allows a `by` after `:=` without linebreak in between:\n  theorem foo : True := by\n    trivial\n  ```\n-/\n@[inline] def ppAllowUngrouped : Parser := skip\n\n/--\n  No-op parser combinator that advises the pretty printer to dedent the given syntax,\n  if it was grouped by the category parser.\n  Dedenting can in particular be used to counteract automatic indentation. -/\n@[inline] def ppDedentIfGrouped : Parser \u2192 Parser := id\n\n/--\n  No-op parser combinator that prints a line break.\n  The line break is soft if the combinator is followed\n  by an ungrouped parser (see ppAllowUngrouped), otherwise hard. -/\n@[inline] def ppHardLineUnlessUngrouped : Parser := skip\n\nend Parser\n\nsection\nopen PrettyPrinter\n\n@[combinatorFormatter Lean.Parser.ppHardSpace] def ppHardSpace.formatter : Formatter := Formatter.pushWhitespace \" \"\n@[combinatorFormatter Lean.Parser.ppSpace] def ppSpace.formatter : Formatter := Formatter.pushLine\n@[combinatorFormatter Lean.Parser.ppLine] def ppLine.formatter : Formatter := Formatter.pushWhitespace \"\\n\"\n@[combinatorFormatter Lean.Parser.ppRealFill] def ppRealFill.formatter (p : Formatter) : Formatter := Formatter.fill p\n@[combinatorFormatter Lean.Parser.ppRealGroup] def ppRealGroup.formatter (p : Formatter) : Formatter := Formatter.group p\n@[combinatorFormatter Lean.Parser.ppIndent] def ppIndent.formatter (p : Formatter) : Formatter := Formatter.indent p\n@[combinatorFormatter Lean.Parser.ppDedent] def ppDedent.formatter (p : Formatter) : Formatter := do\n  let opts \u2190 getOptions\n  Formatter.indent p (some ((0:Int) - Std.Format.getIndent opts))\n\n@[combinatorFormatter Lean.Parser.ppAllowUngrouped] def ppAllowUngrouped.formatter : Formatter := do\n  modify ({ \u00b7 with mustBeGrouped := false })\n@[combinatorFormatter Lean.Parser.ppDedentIfGrouped] def ppDedentIfGrouped.formatter (p : Formatter) : Formatter := do\n  Formatter.concat p\n  let indent := Std.Format.getIndent (\u2190 getOptions)\n  unless (\u2190 get).isUngrouped do\n    modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (\u00b7.nest (0 - indent)) }\n@[combinatorFormatter Lean.Parser.ppHardLineUnlessUngrouped] def ppHardLineUnlessUngrouped.formatter : Formatter := do\n  if (\u2190 get).isUngrouped then\n    Formatter.pushLine\n  else\n    ppLine.formatter\n\nend\n\nnamespace Parser\n\n-- now synthesize parenthesizers\nattribute [runBuiltinParserAttributeHooks]\n  ppHardSpace ppSpace ppLine ppGroup ppRealGroup ppRealFill ppIndent ppDedent\n  ppAllowUngrouped ppDedentIfGrouped ppHardLineUnlessUngrouped\n\nmacro \"register_parser_alias\" aliasName?:optional(strLit) declName:ident : term =>\n  let aliasName := aliasName?.getD (Syntax.mkStrLit declName.getId.toString)\n  `(do Parser.registerAlias $aliasName $declName\n       PrettyPrinter.Formatter.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `formatter))\n       PrettyPrinter.Parenthesizer.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `parenthesizer)))\n\nbuiltin_initialize\n  register_parser_alias group\n  register_parser_alias ppHardSpace\n  register_parser_alias ppSpace\n  register_parser_alias ppLine\n  register_parser_alias ppGroup\n  register_parser_alias ppRealGroup\n  register_parser_alias ppRealFill\n  register_parser_alias ppIndent\n  register_parser_alias ppDedent\n  register_parser_alias ppAllowUngrouped\n  register_parser_alias ppDedentIfGrouped\n  register_parser_alias ppHardLineUnlessUngrouped\n\nend Parser\n\nend Lean\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/Parser/Extra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07263671238329551, "lm_q2_score": 0.030675799052176208, "lm_q1q2_score": 0.002228189192880692}}
{"text": "/-\nCopyright (c) 2020 Wojciech Nawrocki. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki\n-/\nimport Lean.Data.Json\nimport Lean.Data.Lsp.Basic\n\nnamespace Lean\nnamespace Lsp\n\nopen Json\n\nstructure CompletionOptions where\n  triggerCharacters?   : Option (Array String) := none\n  allCommitCharacters? : Option (Array String) := none\n  resolveProvider      : Bool := false\n  deriving FromJson, ToJson\n\ninductive CompletionItemKind where\n  | text | method | function | constructor | field\n  | variable | class | interface | module | property\n  | unit | value | enum | keyword | snippet\n  | color | file | reference | folder | enumMember\n  | constant | struct | event | operator | typeParameter\n  deriving Inhabited, DecidableEq, Repr\n\ninstance : ToJson CompletionItemKind where\n  toJson a := toJson (a.toCtorIdx + 1)\n\ninstance : FromJson CompletionItemKind where\n  fromJson? v := do\n    let i : Nat \u2190 fromJson? v\n    return CompletionItemKind.ofNat (i-1)\n\nstructure InsertReplaceEdit where\n  newText : String\n  insert : Range\n  replace : Range\n  deriving FromJson, ToJson\n\nstructure CompletionItem where\n  label : String\n  detail? : Option String := none\n  documentation? : Option MarkupContent := none\n  kind? : Option CompletionItemKind := none\n  textEdit? : Option InsertReplaceEdit := none\n  /-\n  tags? : CompletionItemTag[]\n  deprecated? : boolean\n  preselect? : boolean\n  sortText? : string\n  filterText? : string\n  insertText? : string\n  insertTextFormat? : InsertTextFormat\n  insertTextMode? : InsertTextMode\n  additionalTextEdits? : TextEdit[]\n  commitCharacters? : string[]\n  command? : Command\n  data? : any -/\n  deriving FromJson, ToJson, Inhabited\n\nstructure CompletionList where\n  isIncomplete : Bool\n  items : Array CompletionItem\n  deriving FromJson, ToJson\n\nstructure CompletionParams extends TextDocumentPositionParams where\n  -- context? : CompletionContext\n  deriving FromJson, ToJson\n\nstructure Hover where\n  /- NOTE we should also accept MarkedString/MarkedString[] here\n  but they are deprecated, so maybe can get away without. -/\n  contents : MarkupContent\n  range? : Option Range := none\n  deriving ToJson, FromJson\n\nstructure HoverParams extends TextDocumentPositionParams\n  deriving FromJson, ToJson\n\nstructure DeclarationParams extends TextDocumentPositionParams\n  deriving FromJson, ToJson\n\nstructure DefinitionParams extends TextDocumentPositionParams\n  deriving FromJson, ToJson\n\nstructure TypeDefinitionParams extends TextDocumentPositionParams\n  deriving FromJson, ToJson\n\nstructure ReferenceContext where\n  includeDeclaration : Bool\n  deriving FromJson, ToJson\n\nstructure ReferenceParams extends TextDocumentPositionParams where\n  context : ReferenceContext\n  deriving FromJson, ToJson\n\nstructure WorkspaceSymbolParams where\n  query : String\n  deriving FromJson, ToJson\n\nstructure DocumentHighlightParams extends TextDocumentPositionParams\n  deriving FromJson, ToJson\n\ninductive DocumentHighlightKind where\n  | text\n  | read\n  | write\n\ninstance : ToJson DocumentHighlightKind where\n toJson\n   | DocumentHighlightKind.text => 1\n   | DocumentHighlightKind.read => 2\n   | DocumentHighlightKind.write => 3\n\nstructure DocumentHighlight where\n  range : Range\n  kind? : Option DocumentHighlightKind := none\n  deriving ToJson\n\nabbrev DocumentHighlightResult := Array DocumentHighlight\n\nstructure DocumentSymbolParams where\n  textDocument : TextDocumentIdentifier\n  deriving FromJson, ToJson\n\ninductive SymbolKind where\n  | file\n  | module\n  | namespace\n  | package\n  | class\n  | method\n  | property\n  | field\n  | constructor\n  | enum\n  | interface\n  | function\n  | variable\n  | constant\n  | string\n  | number\n  | boolean\n  | array\n  | object\n  | key\n  | null\n  | enumMember\n  | struct\n  | event\n  | operator\n  | typeParameter\n\ninstance : ToJson SymbolKind where\n toJson\n   | SymbolKind.file => 1\n   | SymbolKind.module => 2\n   | SymbolKind.namespace => 3\n   | SymbolKind.package => 4\n   | SymbolKind.class => 5\n   | SymbolKind.method => 6\n   | SymbolKind.property => 7\n   | SymbolKind.field => 8\n   | SymbolKind.constructor => 9\n   | SymbolKind.enum => 10\n   | SymbolKind.interface => 11\n   | SymbolKind.function => 12\n   | SymbolKind.variable => 13\n   | SymbolKind.constant => 14\n   | SymbolKind.string => 15\n   | SymbolKind.number => 16\n   | SymbolKind.boolean => 17\n   | SymbolKind.array => 18\n   | SymbolKind.object => 19\n   | SymbolKind.key => 20\n   | SymbolKind.null => 21\n   | SymbolKind.enumMember => 22\n   | SymbolKind.struct => 23\n   | SymbolKind.event => 24\n   | SymbolKind.operator => 25\n   | SymbolKind.typeParameter => 26\n\nstructure DocumentSymbolAux (Self : Type) where\n  name : String\n  detail? : Option String := none\n  kind : SymbolKind\n  -- tags? : Array SymbolTag\n  range : Range\n  selectionRange : Range\n  children? : Option (Array Self) := none\n  deriving ToJson\n\ninductive DocumentSymbol where\n  | mk (sym : DocumentSymbolAux DocumentSymbol)\n\npartial instance : ToJson DocumentSymbol where\n  toJson :=\n    let rec go\n      | DocumentSymbol.mk sym =>\n        have : ToJson DocumentSymbol := \u27e8go\u27e9\n        toJson sym\n    go\n\nstructure DocumentSymbolResult where\n  syms : Array DocumentSymbol\n\ninstance : ToJson DocumentSymbolResult where\n  toJson dsr := toJson dsr.syms\n\ninductive SymbolTag where\n  | deprecated\n\ninstance : ToJson SymbolTag where\n toJson\n   | SymbolTag.deprecated => 1\n\nstructure SymbolInformation where\n  name : String\n  kind : SymbolKind\n  tags : Array SymbolTag := #[]\n  location : Location\n  containerName? : Option String := none\n  deriving ToJson\n\ninductive SemanticTokenType where\n  -- Used by Lean\n  | keyword\n  | variable\n  | property\n  | function\n  /- Other types included by default in the LSP specification.\n  Not used by the Lean core, but useful to users extending the Lean server. -/\n  | namespace\n  | type\n  | class\n  | enum\n  | interface\n  | struct\n  | typeParameter\n  | parameter\n  | enumMember\n  | event\n  | method\n  | macro\n  | modifier\n  | comment\n  | string\n  | number\n  | regexp\n  | operator\n  | decorator\n  -- Extensions\n  | leanSorryLike\n  deriving ToJson, FromJson\n\n-- must be in the same order as the constructors\ndef SemanticTokenType.names : Array String :=\n  #[\"keyword\", \"variable\", \"property\", \"function\", \"namespace\", \"type\", \"class\",\n    \"enum\", \"interface\", \"struct\", \"typeParameter\", \"parameter\", \"enumMember\",\n    \"event\", \"method\", \"macro\", \"modifier\", \"comment\", \"string\", \"number\",\n    \"regexp\", \"operator\", \"decorator\", \"leanSorryLike\"]\n\ndef SemanticTokenType.toNat (type : SemanticTokenType) : Nat :=\n  type.toCtorIdx\n\n-- sanity check\n-- TODO: restore after update-stage0\n--example {v : SemanticTokenType} : open SemanticTokenType in\n--    names[v.toNat]?.map (toString <| toJson \u00b7) = some (toString <| toJson v) := by\n--  cases v <;> native_decide\n\n/--\nThe semantic token modifiers included by default in the LSP specification.\nNot used by the Lean core, but implementing them here allows them to be\nutilized by users extending the Lean server.\n-/\ninductive SemanticTokenModifier where\n  | declaration\n  | definition\n  | readonly\n  | static\n  | deprecated\n  | abstract\n  | async\n  | modification\n  | documentation\n  | defaultLibrary\n  deriving ToJson, FromJson\n\n-- must be in the same order as the constructors\ndef SemanticTokenModifier.names : Array String :=\n  #[\"declaration\", \"definition\", \"readonly\", \"static\", \"deprecated\", \"abstract\",\n    \"async\", \"modification\", \"documentation\", \"defaultLibrary\"]\n\ndef SemanticTokenModifier.toNat (modifier : SemanticTokenModifier) : Nat :=\n  modifier.toCtorIdx\n\n-- sanity check\nexample {v : SemanticTokenModifier} : open SemanticTokenModifier in\n    names[v.toNat]?.map (toString <| toJson \u00b7) = some (toString <| toJson v) := by\n  cases v <;> native_decide\n\nstructure SemanticTokensLegend where\n  tokenTypes : Array String\n  tokenModifiers : Array String\n  deriving FromJson, ToJson\n\nstructure SemanticTokensOptions where\n  legend : SemanticTokensLegend\n  range : Bool\n  full : Bool /- | {\n    delta?: boolean;\n  } -/\n  deriving FromJson, ToJson\n\nstructure SemanticTokensParams where\n  textDocument : TextDocumentIdentifier\n  deriving FromJson, ToJson\n\nstructure SemanticTokensRangeParams where\n  textDocument : TextDocumentIdentifier\n  range : Range\n  deriving FromJson, ToJson\n\nstructure SemanticTokens where\n  resultId? : Option String := none\n  data : Array Nat\n  deriving FromJson, ToJson\n\nstructure FoldingRangeParams where\n  textDocument : TextDocumentIdentifier\n  deriving FromJson, ToJson\n\ninductive FoldingRangeKind where\n  | comment\n  | imports\n  | region\n\ninstance : ToJson FoldingRangeKind where\n  toJson\n    | FoldingRangeKind.comment => \"comment\"\n    | FoldingRangeKind.imports => \"imports\"\n    | FoldingRangeKind.region => \"region\"\n\nstructure FoldingRange where\n  startLine : Nat\n  endLine : Nat\n  kind? : Option FoldingRangeKind := none\n  deriving ToJson\n\nend Lsp\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/Data/Lsp/LanguageFeatures.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.10970578261038683, "lm_q2_score": 0.019719127423242864, "lm_q1q2_score": 0.002163302306360799}}
{"text": "import Cli\n\nopen Cli\n\ndef doNothing (p : Parsed) : IO UInt32 :=\n  return 0\n\ndef runExampleCmd (p : Parsed) : IO UInt32 := do\n  let input   : String       := p.positionalArg! \"input\" |>.as! String\n  let outputs : Array String := p.variableArgsAs! String\n  IO.println <| \"Input: \" ++ input\n  IO.println <| \"Outputs: \" ++ toString outputs\n\n  if p.hasFlag \"verbose\" then\n    IO.println \"Flag `--verbose` was set.\"\n  if p.hasFlag \"invert\" then\n    IO.println \"Flag `--invert` was set.\"\n  if p.hasFlag \"optimize\" then\n    IO.println \"Flag `--optimize` was set.\"\n\n  let priority : Nat := p.flag! \"priority\" |>.as! Nat\n  IO.println <| \"Flag `--priority` always has at least a default value: \" ++ toString priority\n\n  if let some setPathsFlag := p.flag? \"set-paths\" then\n    IO.println <| toString <| setPathsFlag.as! (Array String)\n  return 0\n\ndef installCmd := `[Cli|\n  installCmd VIA doNothing; [\"0.0.1\"]\n  \"installCmd provides an example for a subcommand without flags or arguments.\"\n]\n\ndef testCmd := `[Cli|\n  testCmd VIA doNothing; [\"0.0.1\"]\n  \"testCmd provides another example for a subcommand without flags or arguments.\"\n]\n\ndef exampleCmd : Cmd := `[Cli|\n  exampleCmd VIA runExampleCmd; [\"0.0.1\"]\n  \"This string denotes the description of `exampleCmd`.\"\n\n  FLAGS:\n    verbose;                    \"Declares a flag `--verbose`. This is the description of the flag.\"\n    i, invert;                  \"Declares a flag `--invert` with an associated short alias `-i`.\"\n    o, optimize;                \"Declares a flag `--optimize` with an associated short alias `-o`.\"\n    p, priority : Nat;          \"Declares a flag `--priority` with an associated short alias `-p` \" ++\n                                \"that takes an argument of type `Nat`.\"\n    \"set-paths\" : Array String; \"Declares a flag `--set-paths` \" ++\n                                \"that takes an argument of type `Array Nat`. \" ++\n                                \"Quotation marks allow the use of hyphens.\"\n\n  ARGS:\n    input : String;      \"Declares a positional argument <input> \" ++\n                         \"that takes an argument of type `String`.\"\n    ...outputs : String; \"Declares a variable argument <output>... \" ++\n                         \"that takes an arbitrary amount of arguments of type `String`.\"\n\n  SUBCOMMANDS:\n    installCmd;\n    testCmd\n\n  -- The EXTENSIONS section denotes features that\n  -- were added as an external extension to the library.\n  -- `./Cli/Extensions.lean` provides some commonly useful examples.\n  EXTENSIONS:\n    author \"mhuisi\";\n    defaultValues! #[(\"priority\", \"0\")]\n]\n\ndef main (args : List String) : IO UInt32 :=\n  exampleCmd.validate args\n\n#eval main <| \"-i -o -p 1 --set-paths=path1,path2,path3 input output1 output2\".splitOn \" \"\n/-\nYields:\n  Input: input\n  Outputs: #[output1, output2]\n  Flag `--invert` was set.\n  Flag `--optimize` was set.\n  Flag `--priority` always has at least a default value: 1\n  #[path1, path2, path3]\n-/\n\n-- Short parameterless flags can be grouped,\n-- short flags with parameters do not need to be separated from\n-- the corresponding value.\n#eval main <| \"-io -p1 input\".splitOn \" \"\n/-\nYields:\n  Input: input\n  Outputs: #[]\n  Flag `--invert` was set.\n  Flag `--optimize` was set.\n  Flag `--priority` always has at least a default value: 1\n-/\n\n#eval main <| \"--version\".splitOn \" \"\n/-\nYields:\n  0.0.1\n-/\n\n\n#eval main <| \"-h\".splitOn \" \"\n/-\nYields:\n  exampleCmd [0.0.1]\n  mhuisi\n  This string denotes the description of `exampleCmd`.\n\n  USAGE:\n      exampleCmd [SUBCOMMAND] [FLAGS] <input> <outputs>...\n\n  FLAGS:\n      -h, --help                  Prints this message.\n      --version                   Prints the version.\n      --verbose                   Declares a flag `--verbose`. This is the\n                                  description of the flag.\n      -i, --invert                Declares a flag `--invert` with an associated\n                                  short alias `-i`.\n      -o, --optimize              Declares a flag `--optimize` with an associated\n                                  short alias `-o`.\n      -p, --priority : Nat        Declares a flag `--priority` with an associated\n                                  short alias `-p` that takes an argument of type\n                                  `Nat`. [Default: `0`]\n      --set-paths : Array String  Declares a flag `--set-paths` that takes an\n                                  argument of type `Array Nat`. Quotation marks\n                                  allow the use of hyphens.\n\n  ARGS:\n      input : String    Declares a positional argument <input> that takes an\n                        argument of type `String`.\n      outputs : String  Declares a variable argument <output>... that takes an\n                        arbitrary amount of arguments of type `String`.\n\n  SUBCOMMANDS:\n      installCmd  installCmd provides an example for a subcommand without flags or\n                  arguments.\n      testCmd     testCmd provides another example for a subcommand without flags\n                  or arguments.\n-/", "meta": {"author": "mhuisi", "repo": "lean4-cli-docker-test", "sha": "6b3881eaa22596f6f430654f61fc03719ee18c62", "save_path": "github-repos/lean/mhuisi-lean4-cli-docker-test", "path": "github-repos/lean/mhuisi-lean4-cli-docker-test/lean4-cli-docker-test-6b3881eaa22596f6f430654f61fc03719ee18c62/Cli/Example.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07369626563712976, "lm_q2_score": 0.027169229418718292, "lm_q1q2_score": 0.0020022707483979838}}
{"text": "import Cli\n\nopen Cli\n\ndef runExampleCmd (p : Parsed) : IO UInt32 := do\n  let input   : String       := p.positionalArg! \"input\" |>.as! String\n  let outputs : Array String := p.variableArgsAs! String\n  IO.println <| \"Input: \" ++ input\n  IO.println <| \"Outputs: \" ++ toString outputs\n\n  if p.hasFlag \"verbose\" then\n    IO.println \"Flag `--verbose` was set.\"\n  if p.hasFlag \"invert\" then\n    IO.println \"Flag `--invert` was set.\"\n  if p.hasFlag \"optimize\" then\n    IO.println \"Flag `--optimize` was set.\"\n\n  let priority : Nat := p.flag! \"priority\" |>.as! Nat\n  IO.println <| \"Flag `--priority` always has at least a default value: \" ++ toString priority\n\n  if let some setPathsFlag := p.flag? \"set-paths\" then\n    IO.println <| toString <| setPathsFlag.as! (Array String)\n  return 0\n\ndef installCmd := `[Cli|\n  installCmd NOOP;\n  \"installCmd provides an example for a subcommand without flags or arguments that does nothing. \" ++\n  \"Versions can be omitted.\"\n]\n\ndef testCmd := `[Cli|\n  testCmd NOOP;\n  \"testCmd provides another example for a subcommand without flags or arguments that does nothing.\"\n]\n\ndef exampleCmd : Cmd := `[Cli|\n  exampleCmd VIA runExampleCmd; [\"0.0.1\"]\n  \"This string denotes the description of `exampleCmd`.\"\n\n  FLAGS:\n    verbose;                    \"Declares a flag `--verbose`. This is the description of the flag.\"\n    i, invert;                  \"Declares a flag `--invert` with an associated short alias `-i`.\"\n    o, optimize;                \"Declares a flag `--optimize` with an associated short alias `-o`.\"\n    p, priority : Nat;          \"Declares a flag `--priority` with an associated short alias `-p` \" ++\n                                \"that takes an argument of type `Nat`.\"\n    \"set-paths\" : Array String; \"Declares a flag `--set-paths` \" ++\n                                \"that takes an argument of type `Array Nat`. \" ++\n                                \"Quotation marks allow the use of hyphens.\"\n\n  ARGS:\n    input : String;      \"Declares a positional argument <input> \" ++\n                         \"that takes an argument of type `String`.\"\n    ...outputs : String; \"Declares a variable argument <output>... \" ++\n                         \"that takes an arbitrary amount of arguments of type `String`.\"\n\n  SUBCOMMANDS:\n    installCmd;\n    testCmd\n\n  -- The EXTENSIONS section denotes features that\n  -- were added as an external extension to the library.\n  -- `./Cli/Extensions.lean` provides some commonly useful examples.\n  EXTENSIONS:\n    author \"mhuisi\";\n    defaultValues! #[(\"priority\", \"0\")]\n]\n\ndef main (args : List String) : IO UInt32 :=\n  exampleCmd.validate args\n\n#eval main <| \"-i -o -p 1 --set-paths=path1,path2,path3 input output1 output2\".splitOn \" \"\n/-\nYields:\n  Input: input\n  Outputs: #[output1, output2]\n  Flag `--invert` was set.\n  Flag `--optimize` was set.\n  Flag `--priority` always has at least a default value: 1\n  #[path1, path2, path3]\n-/\n\n-- Short parameterless flags can be grouped,\n-- short flags with parameters do not need to be separated from\n-- the corresponding value.\n#eval main <| \"-io -p1 input\".splitOn \" \"\n/-\nYields:\n  Input: input\n  Outputs: #[]\n  Flag `--invert` was set.\n  Flag `--optimize` was set.\n  Flag `--priority` always has at least a default value: 1\n-/\n\n#eval main <| \"--version\".splitOn \" \"\n/-\nYields:\n  0.0.1\n-/\n\n\n#eval main <| \"-h\".splitOn \" \"\n/-\nYields:\n  exampleCmd [0.0.1]\n  mhuisi\n  This string denotes the description of `exampleCmd`.\n\n  USAGE:\n      exampleCmd [SUBCOMMAND] [FLAGS] <input> <outputs>...\n\n  FLAGS:\n      -h, --help                  Prints this message.\n      --version                   Prints the version.\n      --verbose                   Declares a flag `--verbose`. This is the\n                                  description of the flag.\n      -i, --invert                Declares a flag `--invert` with an associated\n                                  short alias `-i`.\n      -o, --optimize              Declares a flag `--optimize` with an associated\n                                  short alias `-o`.\n      -p, --priority : Nat        Declares a flag `--priority` with an associated\n                                  short alias `-p` that takes an argument of type\n                                  `Nat`. [Default: `0`]\n      --set-paths : Array String  Declares a flag `--set-paths` that takes an\n                                  argument of type `Array Nat`. Quotation marks\n                                  allow the use of hyphens.\n\n  ARGS:\n      input : String    Declares a positional argument <input> that takes an\n                        argument of type `String`.\n      outputs : String  Declares a variable argument <output>... that takes an\n                        arbitrary amount of arguments of type `String`.\n\n  SUBCOMMANDS:\n      installCmd  installCmd provides an example for a subcommand without flags or\n                  arguments that does nothing. Versions can be omitted.\n      testCmd     testCmd provides another example for a subcommand without flags\n                  or arguments that does nothing.\n-/", "meta": {"author": "mhuisi", "repo": "lean4-cli", "sha": "634cd9bffa4cccf2c4bfa4d2fa476c5e4177e9cf", "save_path": "github-repos/lean/mhuisi-lean4-cli", "path": "github-repos/lean/mhuisi-lean4-cli/lean4-cli-634cd9bffa4cccf2c4bfa4d2fa476c5e4177e9cf/Cli/Example.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06754669301670264, "lm_q2_score": 0.026759284252647432, "lm_q1q2_score": 0.0018075011587602614}}
{"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.Elab.ElabRules\n\nnamespace Std.Tactic\n\n/--\nThis tactic causes a panic when run (at compile time).\n(This is distinct from `exact unreachable!`, which inserts code which will panic at run time.)\n\nIt is intended for tests to assert that a tactic will never be executed, which is otherwise an\nunusual thing to do (and the `unreachableTactic` linter will give a warning if you do).\n\nThe `unreachableTactic` linter has a special exception for uses of `unreachable!`.\n```\nexample : True := by trivial <;> unreachable!\n```\n-/\nelab (name := unreachable) \"unreachable!\" : tactic => do\n  panic! \"unreachable tactic has been reached\"\n  -- Note that `panic!` does not actually halt execution or early exit,\n  -- so we still have to throw an error after panicking.\n  throwError \"unreachable tactic has been reached\"\n\n@[inherit_doc unreachable] macro (name := unreachableConv) \"unreachable!\" : conv =>\n  `(conv| tactic' => unreachable!)\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/Unreachable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.0656048392859768, "lm_q2_score": 0.02716923124029089, "lm_q1q2_score": 0.0017824330490428238}}
{"text": "/-\nCopyright (c) 2022 E.W.Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: E.W.Ayers\n-/\nimport Lean.Data.Json\nimport Lean.Data.Lsp.Basic\nimport Lean.Data.Lsp.Diagnostics\n\nnamespace Lean.Lsp\n\nopen Json\n\n/-- The kind of a code action.\n\nKinds are a hierarchical list of identifiers separated by `.`,\ne.g. `\"refactor.extract.function\"`.\n\nThe set of kinds is open and client needs to announce the kinds it supports\nto the server during initialization.\nYou can make your own code action kinds, the ones supported by LSP are:\n- `quickfix`\n- `refactor`\n  - `refactor.extract`\n  - `refactor.inline`\n  - `refactor.rewrite`\n- `source` Source code actions apply to the entire file. Eg fixing all issues or organising imports.\n  - `source.organizeImports`\n  - `source.fixAll`\n-/\nabbrev CodeActionKind := String\n\ninductive CodeActionTriggerKind\n  /-- Code actions were explicitly requested by the user or by an extension. -/\n  | invoked\n  /-- Code actions were requested automatically.\n\n    This typically happens when current selection in a file changes, but can\n    also be triggered when file content changes. -/\n  | automatic\n\ninstance : ToJson CodeActionTriggerKind := \u27e8fun\n  | .invoked => 1\n  | .automatic => 2\n\u27e9\n\ninstance : FromJson CodeActionTriggerKind := \u27e8fun j => do\n  let n \u2190 j.getNat?\n  match n with\n    | 1 => return CodeActionTriggerKind.invoked\n    | 2 => return CodeActionTriggerKind.automatic\n    | n => throw s!\"Unexpected CodeActionTriggerKind {n}\"\n\u27e9\n\n/-- Contains additional diagnostic information about the context in which a code action is run.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#codeActionContext) -/\nstructure CodeActionContext where\n  /--\n    An array of diagnostics known on the client side overlapping the range\n    provided to the `textDocument/codeAction` request. They are provided so\n    that the server knows which errors are currently presented to the user\n    for the given range. There is no guarantee that these accurately reflect\n    the error state of the resource. The primary parameter\n    to compute code actions is the provided range.\n  -/\n  diagnostics : Array Diagnostic := #[]\n  /-- Requested kind of actions to return.\n\n    Actions not of this kind are filtered out by the client before being\n    shown. So servers can omit computing them.\n  -/\n  only? : Option (Array CodeActionKind) := none\n  /-- The reason why code actions were requested. -/\n  triggerKind? : Option CodeActionTriggerKind := none\n  deriving FromJson, ToJson\n\n/-- Parameters for a [CodeActionRequest](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_codeAction). -/\nstructure CodeActionParams extends WorkDoneProgressParams, PartialResultParams where\n  textDocument : TextDocumentIdentifier\n  range        : Range\n  context      : CodeActionContext := {}\n  deriving FromJson, ToJson\n\n/-- If the code action is disabled, this type gives the reson why. -/\nstructure CodeActionDisabled where\n  reason : String\n  deriving FromJson, ToJson\n\n/-- Capabilities of the server for handling code actions. -/\nstructure CodeActionOptions extends WorkDoneProgressOptions where\n  /-- CodeActionKinds that this server may return.\n\n  The list of kinds may be generic, such as `\"refactor\"`, or the server may list out every specific kind they provide. -/\n  codeActionKinds? : Option (Array CodeActionKind) := none\n  /-- The server provides support to resolve additional information for a code action. -/\n  resolveProvider? : Option Bool := none\n  deriving ToJson, FromJson\n\n/--  A code action represents a change that can be performed in code, e.g. to fix a problem or to refactor code.\n\nA CodeAction should set either `edit` and/or a `command`.\nIf both are supplied, the `edit` is applied first, then the `command` is executed.\nIf none are supplied, the client makes a `codeAction/resolve` JSON-RPC request to compute the edit.\n\n[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#codeAction) -/\nstructure CodeAction extends WorkDoneProgressParams, PartialResultParams where\n  /-- A short, human-readable, title for this code action. -/\n  title        : String\n  /-- The kind of the code action. -/\n  kind?        : Option CodeActionKind := none\n  /-- The diagnostics that this code action resolves. -/\n  diagnostics? : Option (Array Diagnostic) := none\n  /-- Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted by keybindings. -/\n  isPreferred? : Option Bool := none\n  /-- Marks that the code action cannot currently be applied. -/\n  disabled?    : Option CodeActionDisabled := none\n  /-- The workspace edit this code action performs. -/\n  edit?        : Option WorkspaceEdit := none\n  /-- A command this code action executes.\n\n  If a code action provides an edit and a command, first the edit is executed and then the command. -/\n  command?     : Option Command := none\n  /-- A data entry field that is preserved on a code action between a `textDocument/codeAction` and a `codeAction/resolve` request.\n  In particular, for Lean-created commands we expect `data` to have a `uri : DocumentUri` field so that `FileSource` can be implemented.\n   -/\n  data?        : Option Json := none\n  deriving ToJson, FromJson\n\nstructure ResolveSupport where\n  properties : Array String\n  deriving FromJson, ToJson\n\nstructure CodeActionLiteralSupportValueSet where\n  /-- The code action kind values the client supports. When this\n    property exists the client also guarantees that it will\n    handle values outside its set gracefully and falls back\n    to a default value when unknown.\n  -/\n  valueSet : Array CodeActionKind\n  deriving FromJson, ToJson\n\nstructure CodeActionLiteralSupport where\n  /-- The code action kind is supported with the following value set. -/\n  codeActionKind : CodeActionLiteralSupportValueSet\n  deriving FromJson, ToJson\n\n/-- [Reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#codeActionClientCapabilities) -/\nstructure CodeActionClientCapabilities where\n  /-- Whether we can [register capabilities dynamically](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#client_registerCapability). -/\n  dynamicRegistration?      : Option Bool := false\n  /-- Whether the code action supports the `isPreferred` property. -/\n  isPreferredSupport?       : Option Bool := false\n  /-- Whether the code action supports the `disabled` property. -/\n  disabledSupport?          : Option Bool := false\n  /-- Weather code action supports the `data` property which is preserved between a `textDocument/codeAction` and a `codeAction/resolve` request. -/\n  dataSupport?              : Option Bool := false\n  /-- Whether the client honors the change annotations in\n    text edits and resource operations returned via the\n    `CodeAction#edit` property by for example presenting\n    the workspace edit in the user interface and asking\n    for confirmation. -/\n  honorsChangeAnnotations?  : Option Bool := false\n  /-- The client supports code action literals as a valid response of the `textDocument/codeAction` request. -/\n  codeActionLiteralSupport? : Option CodeActionLiteralSupport := none\n  /-- Whether the client supports resolving additional code action properties via a separate `codeAction/resolve` request. -/\n  resolveSupport?           : Option ResolveSupport           := none\n  deriving FromJson, ToJson\n\n\nend Lean.Lsp\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/Data/Lsp/CodeActions.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.05834583406213189, "lm_q2_score": 0.028870909870814438, "lm_q1q2_score": 0.0016844973165453048}}
{"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.Lsp.Capabilities\n\nopen Lean Lsp\n\nnamespace Alloy\n\nstructure EmptyObject deriving ToJson, FromJson\ninstance : EmptyCollection EmptyObject := \u27e8.mk\u27e9\n\ndef Union := Sum\n\ndef Union.inl (a : \u03b1) : Union \u03b1 \u03b2 := Sum.inl a\ndef Union.inr (b : \u03b2) : Union \u03b1 \u03b2 := Sum.inr b\n\ninstance : Coe \u03b1 (Union \u03b1 \u03b2) := \u27e8.inl\u27e9\ninstance : Coe \u03b2 (Union \u03b1 \u03b2) := \u27e8.inr\u27e9\n\ninstance [ToJson \u03b1] [ToJson \u03b2] : ToJson (Union \u03b1 \u03b2) where\n  toJson | .inl a => toJson a | .inr b => toJson b\n\ninstance [FromJson \u03b1] [FromJson \u03b2] : FromJson (Union \u03b1 \u03b2) where\n  fromJson? v :=\n    match fromJson? v with\n    | .ok a => .ok <| .inl a\n    | .error _ => .inr <$> fromJson? v\n\nabbrev BUnion (\u03b1) := Union Bool \u03b1\nabbrev BOption (\u03b1) := Option (BUnion \u03b1)\n\nstructure WorkDoneProgressOptions where\n  workDoneProgress? : Option Bool := none\n\nderiving instance DecidableEq for SymbolKind\n\ninstance : FromJson SymbolKind where\n fromJson? v := do\n    let i : Nat \u2190 fromJson? v\n    return SymbolKind.ofNat (i-1)\n\nderiving instance DecidableEq for SymbolTag\n\ninstance : FromJson SymbolTag where\n  fromJson? v := return .ofNat ((\u2190 fromJson? v)-1)\n\ninductive CompletionItemTag where\n| deprecated\nderiving Inhabited, DecidableEq, Repr\n\ninstance : ToJson CompletionItemTag where\n  toJson a := toJson <| a.toCtorIdx + 1\n\ninstance : FromJson CompletionItemTag where\n  fromJson? v := return .ofNat ((\u2190 fromJson? v)-1)\n\ninductive InsertTextMode where\n| asIs | adjustIndentation\nderiving Inhabited, DecidableEq, Repr\n\ninstance : ToJson InsertTextMode where\n  toJson a := toJson <| a.toCtorIdx + 1\n\ninstance : FromJson InsertTextMode where\n  fromJson? v := return .ofNat ((\u2190 fromJson? v)-1)\n\ninductive PrepareSupportDefaultBehavior  where\n| identifier\nderiving Inhabited, DecidableEq, Repr\n\ninstance : ToJson PrepareSupportDefaultBehavior where\n  toJson a := toJson <| a.toCtorIdx + 1\n\ninstance : FromJson PrepareSupportDefaultBehavior where\n  fromJson? v := return .ofNat ((\u2190 fromJson? v)-1)\n\ninductive DiagnosticTag  where\n| unnecessary | deprecated\nderiving Inhabited, DecidableEq, Repr\n\ninstance : ToJson DiagnosticTag where\n  toJson a := toJson <| a.toCtorIdx + 1\n\ninstance : FromJson DiagnosticTag where\n  fromJson? v := return .ofNat ((\u2190 fromJson? v)-1)\n\nderiving instance FromJson for FoldingRangeKind\n\n---\n\ninductive ResourceOperationKind\n| create | rename | delete\nderiving ToJson, FromJson\n\ninductive FailureHandlingKind\n| abort | transactional | undo | textOnlyTransactional\nderiving ToJson, FromJson\n\nstructure ChangeAnnotationSupportClientCapabilities where\n  groupsOnLabel? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure WorkspaceEditClientCapabilities where\n  documentChanges? : Option Bool := none\n  resourceOperations? : Option (Array ResourceOperationKind) := none\n  failureHandling? : Option FailureHandlingKind := none\n  normalizeLineEndings? : Option Bool := none\n  changeAnnotationSupport? : Option ChangeAnnotationSupportClientCapabilities := none\n  deriving ToJson, FromJson\n\nstructure DidChangeConfigurationClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DidChangeWatchedFilesClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  relativePatternSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure SymbolKindCapabilities where\n  valueSet? : Option (Array SymbolKind) := none\n  deriving ToJson, FromJson\n\nstructure SymbolTagSupportCapabilities where\n  valueSet : Array SymbolTag\n  deriving ToJson, FromJson\n\nstructure ResolveSupportCapabilities where\n  properties : Array String\n  deriving ToJson, FromJson\n\nstructure WorkspaceSymbolClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  symbolKind? : Option SymbolKindCapabilities := none\n  tagSupport? : Option SymbolTagSupportCapabilities := none\n  resolveSupport? : Option ResolveSupportCapabilities := none\n  deriving ToJson, FromJson\n\nstructure ExecuteCommandClientCapabilities extends WorkDoneProgressOptions where\n  commands : Array String\n  deriving ToJson, FromJson\n\nstructure SemanticTokensWorkspaceClientCapabilities where\n  refreshSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure CodeLensWorkspaceClientCapabilities where\n  refreshSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure FileOperationsCapabilities where\n  dynamicRegistration? : Option Bool := none\n  didCreate? : Option Bool := none\n  willCreate? : Option Bool := none\n  didRename? : Option Bool := none\n  willRename? : Option Bool := none\n  didDelete? : Option Bool := none\n  willDelete? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure InlineValueWorkspaceClientCapabilities where\n  refreshSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure InlayHintWorkspaceClientCapabilities where\n  refreshSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DiagnosticWorkspaceClientCapabilities where\n  refreshSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure WorkspaceClientCapabilities where\n  applyEdit? : Option Bool := none\n  workspaceEdit? : Option WorkspaceEditClientCapabilities := none\n  didChangeConfiguration? : Option DidChangeConfigurationClientCapabilities := none\n  didChangeWatchedFiles? : Option DidChangeWatchedFilesClientCapabilities := none\n  symbol? : Option WorkspaceSymbolClientCapabilities := none\n  executeCommand? : Option ExecuteCommandClientCapabilities := none\n  workspaceFolders? : Option Bool := none\n  configuration? : Option Bool := none\n  semanticTokens? : Option SemanticTokensWorkspaceClientCapabilities := none\n  codeLens? : Option CodeLensWorkspaceClientCapabilities := none\n  fileOperations? : Option FileOperationsCapabilities := none\n  inlineValue? : Option InlineValueWorkspaceClientCapabilities := none\n  inlayHint? : Option InlayHintWorkspaceClientCapabilities := none\n  diagnostics? : Option DiagnosticWorkspaceClientCapabilities := none\n  deriving ToJson, FromJson\n\nstructure TextDocumentSyncClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  willSave? : Option Bool := none\n  willSaveWaitUntil? : Option Bool := none\n  didSave? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure CompletionItemTagSupportCapabilities where\n  valueSet : Array CompletionItemTag\n  deriving ToJson, FromJson\n\nstructure InsertTextModeSupportCapabilities where\n  valueSet : Array InsertTextMode\n  deriving ToJson, FromJson\n\nstructure CompletionItemCapabilities where\n  snippetSupport? : Option Bool := none\n  commitCharactersSupport? : Option Bool := none\n  documentationFormat? : Option (Array MarkupKind) := none\n  deprecatedSupport? : Option Bool := none\n  preselectSupport? : Option Bool := none\n  tagSupport? : Option CompletionItemTagSupportCapabilities := none\n  insertReplaceSupport? : Option Bool := none\n  insertTextModeSupport? : Option InsertTextModeSupportCapabilities := none\n  resolveSupport? : Option ResolveSupportCapabilities := none\n  labelDetailsSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure CompletionItemKindCapabilities where\n  valueSet? : Option (Array CompletionItemKind) := none\n  deriving ToJson, FromJson\n\nstructure CompletionListCapabilities where\n  itemDefaults? : Option (Array String) := none\n  deriving ToJson, FromJson\n\nstructure CompletionClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  completionItem? : Option CompletionItemCapabilities := none\n  completionItemKind? : Option CompletionItemKindCapabilities := none\n  contextSupport? : Option Bool := none\n  insertTextMode? : Option InsertTextMode := none\n  completionList? : Option CompletionListCapabilities := none\n  deriving ToJson, FromJson\n\nstructure HoverClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  contentFormat? : Option (Array MarkupKind) := none\n  deriving ToJson, FromJson\n\nstructure ParameterInformationCapabilities where\n  labelOffsetSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure SignatureInformationCapabilities where\n  documentationFormat? : Option (Array MarkupKind) := none\n  parameterInformation? : Option ParameterInformationCapabilities := none\n  activeParameterSupport : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure SignatureHelpClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  signatureInformation? : Option SignatureInformationCapabilities := none\n  contentSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DeclarationClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  linkSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DefinitionClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  linkSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure TypeDefinitionClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  linkSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure ImplementationClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  linkSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure ReferenceClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentHighlightClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentSymbolClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  symbolKind? : Option SymbolKindCapabilities := none\n  hierarchicalDocumentSymbolSupport? : Option Bool := none\n  tagSupport? : Option SymbolTagSupportCapabilities := none\n  labelSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\ndef CodeActionKind := Name\n\nnamespace CodeActionKind\n\ndef empty := Name.anonymous\ndef quickfix := `quickfix\ndef refactor := `refactor\ndef refactorExtract := `refactor.extract\ndef refactorInline := `refactor.inline\ndef refactorRewrite := `refactor.inline\ndef source := `refactor.inline\ndef sourceOrganizeImports := `source.organizeImports\ndef sourceFixAll := `source.fixAll\n\ninstance : ToJson CodeActionKind where\n  toJson a := if a.isAnonymous then \"\" else a.toString false\n\ninstance : FromJson CodeActionKind where\n  fromJson? v := v.getStr? <&> fun v => if v.isEmpty then empty else v.toName\n\nend CodeActionKind\n\nstructure CodeActionKindCapabilities where\n  valueSet : Array CodeActionKind\n  deriving ToJson, FromJson\n\nstructure CodeActionLiteralSupportCapabilities where\n  codeActionKind : CodeActionKindCapabilities\n  deriving ToJson, FromJson\n\nstructure CodeActionClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  codeActionLiteralSupport? : Option CodeActionLiteralSupportCapabilities := none\n  isPreferredSupport? : Option Bool := none\n  disabledSupport? : Option Bool := none\n  dataSupport? : Option Bool := none\n  resolveSupport? : Option ResolveSupportCapabilities := none\n  honorsChangeAnnotations? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure CodeLensClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentLinkClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  tooltipSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentColorClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentFormattingClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentRangeFormattingClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DocumentOnTypeFormattingClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure RenameClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  prepareSupport? : Option Bool := none\n  prepareSupportDefaultBehavior? : Option PrepareSupportDefaultBehavior := none\n  honorsChangeAnnotations? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure DiagnosticTagSupportCapabilities where\n  valueSet : Array DiagnosticTag\n  deriving ToJson, FromJson\n\nstructure PublishDiagnosticsClientCapabilities where\n  relatedInformation? : Option Bool := none\n  tagSupport? : Option DiagnosticTagSupportCapabilities := none\n  versionSupport? : Option PrepareSupportDefaultBehavior := none\n  codeDescriptionSupport? : Option Bool := none\n  dataSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure FoldingRangeKindCapabilities where\n  valueSet? : Option (Array FoldingRangeKind) := none\n  deriving ToJson, FromJson\n\nstructure FoldingRangeCapabilities where\n  collapsedText? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure FoldingRangeClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  rangeLimit? : Option Nat := none\n  lineFoldingOnly? : Option Bool := none\n  foldingRangeKind? : Option FoldingRangeKindCapabilities := none\n  foldingRange? : Option FoldingRangeCapabilities := none\n  deriving ToJson, FromJson\n\nstructure SelectionRangeClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure LinkedEditingRangeClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure CallHierarchyClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure SemanticTokensFullCapabilities where\n  delta? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure SemanticTokensRequestsCapabilities where\n  range? : BOption EmptyObject := none\n  full? : BOption SemanticTokensFullCapabilities := none\n  deriving ToJson, FromJson\n\ninductive TokenFormat\n| relative\nderiving ToJson, FromJson\n\nstructure SemanticTokensClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  requests : SemanticTokensRequestsCapabilities\n  tokenTypes : Array String\n  tokenModifiers : Array String\n  formats : Array TokenFormat\n  overlappingTokenSupport? : Option Bool := none\n  multilineTokenSupport? : Option Bool := none\n  serverCancelSupport? : Option Bool := none\n  augmentsSyntaxTokens : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure MonikerClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure TypeHierarchyClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure InlineValueClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure InlayHintClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  resolveSupport? : Option ResolveSupportCapabilities := none\n  deriving ToJson, FromJson\n\nstructure DiagnosticClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  relatedDocumentSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure TextDocumentClientCapabilities where\n  synchronization? : Option TextDocumentSyncClientCapabilities := none\n  completion? : Option CompletionClientCapabilities := none\n  hover? : Option HoverClientCapabilities := none\n  signatureHelp? : Option SignatureHelpClientCapabilities := none\n  declaration? : Option DeclarationClientCapabilities := none\n  definition? : Option DefinitionClientCapabilities := none\n  typeDefinition? : Option TypeDefinitionClientCapabilities := none\n  implementation? : Option ImplementationClientCapabilities := none\n  references? : Option ReferenceClientCapabilities := none\n  documentHighlight? : Option DocumentHighlightClientCapabilities := none\n  documentSymbol? : Option DocumentSymbolClientCapabilities := none\n  codeAction? : Option CodeActionClientCapabilities := none\n  codeLens? : Option CodeLensClientCapabilities := none\n  documentLink? : Option DocumentLinkClientCapabilities := none\n  colorProvider? : Option DocumentColorClientCapabilities := none\n  formatting? : Option DocumentFormattingClientCapabilities := none\n  rangeFormatting? : Option DocumentRangeFormattingClientCapabilities := none\n  onTypeFormatting? : Option DocumentOnTypeFormattingClientCapabilities := none\n  rename? : Option RenameClientCapabilities := none\n  publishDiagnostics? : Option PublishDiagnosticsClientCapabilities := none\n  foldingRange? : Option FoldingRangeClientCapabilities := none\n  selectionRange? : Option SelectionRangeClientCapabilities := none\n  linkedEditingRange? : Option LinkedEditingRangeClientCapabilities := none\n  callHierarchy? : Option CallHierarchyClientCapabilities := none\n  semanticTokens? : Option SemanticTokensClientCapabilities := none\n  moniker? : Option MonikerClientCapabilities := none\n  typeHierarchy? : Option TypeHierarchyClientCapabilities := none\n  inlineValue? : Option InlineValueClientCapabilities := none\n  inlayHint? : Option InlayHintClientCapabilities := none\n  diagnostic? : Option DiagnosticClientCapabilities := none\n  deriving ToJson, FromJson\n\nstructure NotebookDocumentSyncClientCapabilities where\n  dynamicRegistration? : Option Bool := none\n  executionSummarySupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure NotebookDocumentClientCapabilities where\n  synchronization : NotebookDocumentSyncClientCapabilities\n  deriving ToJson, FromJson\n\nstructure MessageActionItemCapabilities where\n  additionalPropertiesSupport? : Option Bool := none\n  deriving ToJson, FromJson\n\nstructure ShowMessageRequestClientCapabilities where\n  messageActionItem? : Option MessageActionItemCapabilities := none\n  deriving ToJson, FromJson\n\nstructure WindowClientCapabilities where\n  workDoneProgress? : Option Bool := none\n  showMessage? : Option ShowMessageRequestClientCapabilities := none\n  showDocument? : Option ShowDocumentClientCapabilities := none\n  deriving ToJson, FromJson\n\nstructure StaleRequestSupportCapabilities where\n  cancel : Bool\n  retryOnContentModified : Array String\n  deriving ToJson, FromJson\n\nstructure RegularExpressionsClientCapabilities where\n  engine : String\n  version? : Option String := none\n  deriving ToJson, FromJson\n\nstructure MarkdownClientCapabilities where\n  parser : String\n  version? : Option String := none\n  allowedTags? : Option (Array String) := none\n  deriving ToJson, FromJson\n\nabbrev PositionEncodingKind := String\nnamespace PositionEncodingKind\ndef utf8 := \"utf-8\"\ndef utf16 := \"utf-16\"\ndef utf32 := \"utf-32\"\nend PositionEncodingKind\n\nstructure GeneralClientCapabilities where\n  staleRequestSupport? : Option StaleRequestSupportCapabilities := none\n  regularExpressions? : Option RegularExpressionsClientCapabilities := none\n  markdown? : Option MarkdownClientCapabilities := none\n  positionEncodings? : Option (Array PositionEncodingKind) := none\n  deriving ToJson, FromJson\n\nstructure ClientCapabilities (Experimental := Json) where\n  workspace? : Option WorkspaceClientCapabilities := none\n  textDocument? : Option TextDocumentClientCapabilities := none\n  notebookDocument? : Option NotebookDocumentClientCapabilities := none\n  window? : Option WindowClientCapabilities := none\n  general? : Option GeneralClientCapabilities := none\n  experimental? : Option Experimental := none\n  deriving Inhabited, ToJson, FromJson\n\ninstance [ToJson Exp] : Coe (ClientCapabilities Exp) ClientCapabilities where\n  coe caps := {caps with experimental? := caps.experimental?.map toJson}\n\n---\n\nstructure TextDocumentSyncOptions where\n  openClose? : Option Bool := none\n  change? : Option TextDocumentSyncKind := none\n  deriving ToJson, FromJson\n\n/--\nPermits parsing a `TextDocumentSyncOptions`\nfrom a plain `TextDocumentSyncKind` (i.e., a number).\n-/\ninstance : FromJson TextDocumentSyncOptions where\n  fromJson? v := try return {change? := some <| \u2190 fromJson? v} catch _ => fromJson? v\n\nstructure StaticRegistrationOptions where\n  id? : Option String := none\n\nstructure TextDocumentRegistrationOptions where\n  documentSelector : Option DocumentSelector := none\n\nabbrev NotebookDocumentSyncRegistrationOptions := Json\nabbrev CompletionOptions := Json\nabbrev HoverOptions := Json\nabbrev SignatureHelpOptions := Json\nabbrev DeclarationRegistrationOptions := Json\nabbrev DefinitionOptions := Json\nabbrev TypeDefinitionRegistrationOptions := Json\nabbrev ImplementationRegistrationOptions := Json\nabbrev ReferenceOptions := Json\nabbrev DocumentHighlightOptions := Json\nabbrev DocumentSymbolOptions := Json\nabbrev CodeActionOptions := Json\nabbrev CodeLensOptions := Json\nabbrev DocumentLinkOptions := Json\nabbrev DocumentColorRegistrationOptions := Json\nabbrev DocumentFormattingOptions := Json\nabbrev DocumentRangeFormattingOptions := Json\nabbrev DocumentOnTypeFormattingOptions := Json\nabbrev RenameOptions := Json\nabbrev FoldingRangeRegistrationOptions := Json\nabbrev ExecuteCommandOptions := Json\nabbrev SelectionRangeRegistrationOptions := Json\nabbrev LinkedEditingRangeRegistrationOption := Json\nabbrev CallHierarchyRegistrationOptions := Json\n\nexample : ToJson (BOption EmptyObject) := inferInstance\nexample : ToJson (BOption SemanticTokensFullCapabilities) := inferInstance\n\nstructure SemanticTokensOptions extends WorkDoneProgressOptions where\n  legend : SemanticTokensLegend\n  range? : BOption EmptyObject := none\n  full? : BOption SemanticTokensFullCapabilities := none\n  deriving ToJson, FromJson\n\nstructure SemanticTokensRegistrationOptions extends\n  SemanticTokensOptions, TextDocumentRegistrationOptions, StaticRegistrationOptions\n  deriving ToJson, FromJson\n\nabbrev MonikerRegistrationOptions := Json\nabbrev TypeHierarchyRegistrationOptions := Json\nabbrev InlineValueRegistrationOptions := Json\nabbrev InlayHintRegistrationOptions := Json\nabbrev DiagnosticRegistrationOptions := Json\nabbrev WorkspaceSymbolOptions := Json\nabbrev WorkspaceServerCapabilities := Json\n\nstructure ServerCapabilities (Experimental := Json) where\n  positionEncoding? : Option PositionEncodingKind := none\n  textDocumentSync? : Option TextDocumentSyncOptions := none\n  notebookDocumentSync? : Option NotebookDocumentSyncRegistrationOptions := none\n  completionProvider? : Option CompletionOptions := none\n  hoverProvider? : BOption HoverOptions := none\n  signatureHelpProvider? : Option SignatureHelpOptions := none\n  declarationProvider? : BOption DeclarationRegistrationOptions := none\n  definitionProvider? : BOption DefinitionOptions := none\n  typeDefinitionProvider? : BOption TypeDefinitionRegistrationOptions := none\n  implementationProvider? : BOption ImplementationRegistrationOptions := none\n  referencesProvider? : BOption ReferenceOptions := none\n  documentHighlightProvider? : BOption DocumentHighlightOptions := none\n  documentSymbolProvider? : BOption DocumentSymbolOptions := none\n  codeActionProvider? : BOption CodeActionOptions := none\n  codeLensProvider? : Option CodeLensOptions := none\n  documentLinkProver? : Option DocumentLinkOptions := none\n  colorProvider? : BOption DocumentColorRegistrationOptions := none\n  documentFormattingProvider? : BOption DocumentFormattingOptions := none\n  documentRangeFormattingProvider? : BOption DocumentRangeFormattingOptions := none\n  documentOnTypeFormattingProvider? : Option DocumentOnTypeFormattingOptions := none\n  renameProvider? : BOption RenameOptions := none\n  foldingRangeProvider? : BOption FoldingRangeRegistrationOptions := none\n  executeCommandProvider? : Option ExecuteCommandOptions := none\n  selectionRangeProvider? : BOption SelectionRangeRegistrationOptions := none\n  linkedEditingRangeProvider? : BOption LinkedEditingRangeRegistrationOption := none\n  callHierarchyProvider? : BOption CallHierarchyRegistrationOptions := none\n  semanticTokensProvider? : Option SemanticTokensRegistrationOptions := none\n  monikerProvider? : BOption MonikerRegistrationOptions := none\n  typeHierarchyProvider? : BOption TypeHierarchyRegistrationOptions := none\n  inlineValueProvider? : BOption InlineValueRegistrationOptions := none\n  inlayHintProvider? : BOption InlayHintRegistrationOptions := none\n  diagnosticProvider? : Option DiagnosticRegistrationOptions := none\n  workspaceSymbolProvider? : BOption WorkspaceSymbolOptions := none\n  workspace? : Option WorkspaceServerCapabilities := none\n  experimental? : Option Experimental := none\n  deriving Inhabited, ToJson, FromJson\n\ninstance [ToJson Exp] : Coe (ServerCapabilities Exp) ServerCapabilities where\n  coe caps := {caps with experimental? := caps.experimental?.map toJson}\n", "meta": {"author": "tydeu", "repo": "lean4-alloy", "sha": "334407dc09c10c84549242dc73f9d364886267d1", "save_path": "github-repos/lean/tydeu-lean4-alloy", "path": "github-repos/lean/tydeu-lean4-alloy/lean4-alloy-334407dc09c10c84549242dc73f9d364886267d1/Alloy/Util/Server/Capabilities.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1081889459357195, "lm_q2_score": 0.01518904652329336, "lm_q1q2_score": 0.0016432869331237134}}
{"text": "import init.Lean.Message init.Lean.Parser.Syntax init.Lean.Parser.Trie init.Lean.Parser.basic\nimport init.Lean.Parser.token\n\nnamespace Lean\nnamespace flatParser\nopen String\nopen Parser (Syntax Syntax.missing Syntax.atom Syntax.ident Syntax.rawNode number stringLit)\nopen Parser (Trie TokenMap)\ndef maxPrec : Nat := 1024\n\nabbrev pos := String.utf8Pos\n\n/-- A precomputed cache for quickly mapping Char offsets to positions. -/\nstructure FileMap :=\n(offsets : Array Nat)\n(lines   : Array Nat)\n\nnamespace FileMap\nprivate def fromStringAux (s : String) : Nat \u2192 Nat \u2192 Nat \u2192 pos \u2192 Array Nat \u2192 Array Nat \u2192 FileMap\n| 0     offset line i offsets lines := \u27e8offsets.push offset, lines.push line\u27e9\n| (k+1) offset line i offsets lines :=\n  if s.utf8AtEnd i then \u27e8offsets.push offset, lines.push line\u27e9\n  else let c := s.utf8Get i in\n       let i := s.utf8Next i in\n       let offset := offset + 1 in\n       if c = '\\n'\n       then fromStringAux k offset (line+1) i (offsets.push offset) (lines.push (line+1))\n       else fromStringAux k offset line i offsets lines\n\ndef fromString (s : String) : FileMap :=\nfromStringAux s s.length 0 1 0 (Array.nil.push 0) (Array.nil.push 1)\n\n/- Remark: `offset is in [(offsets.get b), (offsets.get e)]` and `b < e` -/\nprivate def toPositionAux (offsets : Array Nat) (lines : Array Nat) (offset : Nat) : Nat \u2192 Nat \u2192 Nat \u2192 Position\n| 0     b e := \u27e8offset, 1\u27e9 -- unreachable\n| (k+1) b e :=\n  let offsetB := offsets.read' b in\n  if e = b + 1 then \u27e8offset - offsetB, lines.read' b\u27e9\n  else let m := (b + e) / 2 in\n       let offsetM := offsets.read' m in\n       if offset = offsetM then \u27e80, lines.read' m\u27e9\n       else if offset > offsetM then toPositionAux k m e\n       else toPositionAux k b m\n\ndef toPosition : FileMap \u2192 Nat \u2192 Position\n| \u27e8offsets, lines\u27e9 offset := toPositionAux offsets lines offset offsets.size 0 (offsets.size-1)\nend FileMap\n\nstructure TokenConfig :=\n(\u00abprefix\u00bb : String)\n(lbp : Nat := 0)\n\nstructure FrontendConfig :=\n(filename : String)\n(input    : String)\n(FileMap : FileMap)\n\n/- Remark: if we have a Node in the Trie with `some TokenConfig`, the String induced by the path is equal to the `TokenConfig.prefix`. -/\nstructure ParserConfig extends FrontendConfig :=\n(tokens      : Trie TokenConfig)\n\n-- Backtrackable State\nstructure ParserState :=\n(messages : MessageLog)\n\nstructure TokenCacheEntry :=\n(startPos stopPos : pos)\n(tk : Syntax)\n\n-- Non-backtrackable State\nstructure ParserCache :=\n(tokenCache : Option TokenCacheEntry := none)\n\ninductive Result (\u03b1 : Type)\n| ok       (a : \u03b1)        (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result\n| error {} (msg : String) (i : pos) (cache : ParserCache) (stx : Syntax)         (eps : Bool) : Result\n\ninductive Result.IsOk {\u03b1 : Type} : Result \u03b1 \u2192 Prop\n| mk (a : \u03b1) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result.IsOk (Result.ok a i cache State eps)\n\ntheorem errorIsNotOk {\u03b1 : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool}\n                        (h : Result.IsOk (@Result.error \u03b1 msg i cache stx eps)) : False :=\nmatch h with end\n\n@[inline] def unreachableError {\u03b1 \u03b2 : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool}\n                                (h : Result.IsOk (@Result.error \u03b1 msg i cache stx eps)) : \u03b2 :=\nFalse.elim (errorIsNotOk h)\n\ndef resultOk := {r : Result Unit // r.IsOk}\n\n@[inline] def mkResultOk (i : pos) (cache : ParserCache) (State : ParserState) (eps := tt) : resultOk :=\n\u27e8Result.ok () i cache State eps, Result.IsOk.mk _ _ _ _ _\u27e9\n\ndef mkError {\u03b1 : Type} (r : resultOk) (msg : String) (stx : Syntax := Syntax.missing) (eps := tt) : Result \u03b1 :=\nmatch r with\n| \u27e8Result.ok _ i c s _, _\u27e9    := Result.error msg i c stx eps\n| \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\ndef parserCoreM (\u03b1 : Type) :=\nresultOk \u2192 Result \u03b1\nabbrev parserCore := parserCoreM Syntax\n\n@[inline] def parserCoreM.pure {\u03b1 : Type} (a : \u03b1) : parserCoreM \u03b1 :=\n\u03bb r,\n  match r with\n  | \u27e8Result.ok _ it c s _, h\u27e9   := Result.ok a it c s tt\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline_if_reduce] def strictOr  (b\u2081 b\u2082 : Bool) := b\u2081 || b\u2082\n@[inline_if_reduce] def strictAnd (b\u2081 b\u2082 : Bool) := b\u2081 && b\u2082\n\n@[inline] def parserCoreM.bind {\u03b1 \u03b2 : Type} (x : parserCoreM \u03b1) (f : \u03b1 \u2192 parserCoreM \u03b2) : parserCoreM \u03b2 :=\n\u03bb r,\n  match x r with\n  | Result.ok a i c s e\u2081 :=\n    (match f a (mkResultOk i c s) with\n     | Result.ok b i c s e\u2082        := Result.ok b i c s (strictAnd e\u2081 e\u2082)\n     | Result.error msg i c stx e\u2082 := Result.error msg i c stx (strictAnd e\u2081 e\u2082))\n  | Result.error msg i c stx e  := Result.error msg i c stx e\n\ninstance : Monad parserCoreM :=\n{bind := @parserCoreM.bind, pure := @parserCoreM.pure}\n\ninstance : Inhabited parserCore :=\n\u27e8\u03bb r, mkError r \"error\"\u27e9\n\n@[inline] def parserCoreM.error {\u03b1 : Type} (msg : String) : parserCoreM \u03b1 :=\n\u03bb r, mkError r msg\n\n@[inline] def error {\u03b1 : Type} {m : Type \u2192 Type} [HasMonadLiftT parserCoreM m] (msg : String) : m \u03b1 :=\nmonadLift $ parserCoreM.error msg\n\nabbrev BasicParserM : Type \u2192 Type              := ReaderT ParserConfig parserCoreM\nabbrev basicParser : Type                       := BasicParserM Syntax\nabbrev CommandParserM (\u03c1 : Type) : Type \u2192 Type := ReaderT \u03c1 (ReaderT parserCore parserCoreM)\nabbrev TermParserM : Type \u2192 Type               := ReaderT (Nat \u2192 parserCore) (CommandParserM ParserConfig)\nabbrev termParser : Type                        := TermParserM Syntax\nabbrev trailingTermParser : Type               := Syntax \u2192 termParser\n\nstructure CommandParserConfig extends ParserConfig :=\n(leadingTermParsers  : TokenMap termParser)\n(trailingTermParsers : TokenMap trailingTermParser)\n\nabbrev commandParser : Type      := CommandParserM CommandParserConfig Syntax\nabbrev commandParserCore : Type := CommandParserM ParserConfig Syntax\n\n@[inline] def termParserOfBasicParser {\u03b1 : Type} (p : BasicParserM \u03b1) : TermParserM \u03b1 :=\n\u03bb _ cfg _, p cfg\n\n@[inline] def commandParserOfBasicParser {\u03b1 : Type} (p : BasicParserM \u03b1) : CommandParserM CommandParserConfig \u03b1 :=\n\u03bb cfg _, p cfg.toParserConfig\n\ninstance basic2termP    : HasMonadLift BasicParserM TermParserM                            := \u27e8@termParserOfBasicParser\u27e9\ninstance basic2commandP : HasMonadLift BasicParserM (CommandParserM CommandParserConfig) := \u27e8@commandParserOfBasicParser\u27e9\n\n@[inline] def Term.Parser (rbp := 0) : termParser := \u03bb p _ _, p rbp\n@[inline] def command.Parser : commandParser      := \u03bb _ p, p\n\n@[inline] def readCfg : TermParserM ParserConfig :=\n\u03bb _ cfg _, pure cfg\n\ndef peekToken : BasicParserM Syntax :=\nerror \"TODO\"\n\ndef currLbp : TermParserM Nat :=\ndo tk \u2190 monadLift peekToken,\n   match tk with\n   | Syntax.atom \u27e8_, sym\u27e9 := do\n     cfg \u2190 readCfg,\n     (match cfg.tokens.matchPrefix sym.mkIterator with\n      | some \u27e8_, tkCfg\u27e9 := pure tkCfg.lbp\n      | _                := error \"currLbp: unreachable\")\n   | Syntax.rawNode {kind := @number, ..}     := pure maxPrec\n   | Syntax.rawNode {kind := @stringLit, ..} := pure maxPrec\n   | Syntax.ident _                            := pure maxPrec\n   | _                                         := error \"currLbp: unknown token kind\"\n\n\n\n#exit\n\n   match tk with\n   | Syntax.atom \u27e8_, sym\u27e9 := do\n     cfg \u2190 read,\n     -- some \u27e8_, tkCfg\u27e9 \u2190 pure (cfg.tokens.matchPrefix sym.mkIterator) | error \"currLbp: unreachable\",\n     pure 0\n   | Syntax.ident _ := pure maxPrec\n   | Syntax.rawNode {kind := @number, ..} := pure maxPrec\n   | Syntax.rawNode {kind := @stringLit, ..} := pure maxPrec\n   | _ := error \"currLbp: unknown token kind\"\n\n\n\n\n\nprivate def trailing (cfg : CommandParserConfig) : trailingTermParser :=\n\u03bb _ p _ _ r, p 0 r -- TODO(Leo)\n\nprivate def leading (cfg : CommandParserConfig) : termParser :=\n\u03bb p _ _ r, p 0 r -- TODO(Leo)\n\ndef dummy : Nat \u2192 parserCore :=\n\u03bb _ r, mkError r \"dummy\"\n\ndef pratt (leadingP : termParser) (trailingP : trailingTermParser) (p : termParser) : commandParserCore :=\np dummy\n\ndef commandParserOfTermParser (p : termParser) : commandParser :=\n\u03bb cfg rec r,\n  let leadingP  : termParser          := leading cfg in\n  let trailingP : trailingTermParser := trailing cfg in\n  let cfg        : ParserConfig        := cfg.toParserConfig in\n  let p          : commandParserCore  := pratt leadingP trailingP p in\n  p cfg rec r\n\n#exit\n\ndef prattParser (cfg : CommandParserConfig) : termParser :=\nleading\n\n\n\n@[inline] def toParserCore (termP : Nat \u2192 Parser) (cmdP : parserCore) : Nat \u2192 parserCore :=\nfix (\u03bb recF rbp cfg r, termP rbp cmdP recF cfg r)\n\n@[inline] def Parser.run (x : Parser) (termP : Nat \u2192 Parser) (cmdP : parserCore) : parserCore :=\nx cmdP (toParserCore termP cmdP)\n\n\n\n\n-- STOPPED HERE\n#exit\n\ndef parserCore.run (cmdP : parserCore) (termP : parserCore) : parserCore :=\n\n\n\ndef aux (f : Nat \u2192 parserCore) : Nat \u2192 parserCore\n\nstructure CommandParserConfig extends recParserConfig :=\n(leadingTermParsers  : TokenMap Parser)\n(trailingTermParsers : TokenMap trailingParser)\n\nabbrev CommandParserM (\u03b1 : Type) : Type := parserCoreM CommandParserConfig \u03b1\nabbrev commandParser := CommandParserM Syntax\n\n\n\n\n\n#exit\n-- abbrev\n\n\n-- def parserM (\u03b1 : Type) := recParsers \u2192 parserCoreM \u03b1\nabbreviation Parser := parserM Syntax\nabbreviation trailingParser := Syntax \u2192 Parser\n\n@[inline] def command.Parser : Parser := \u03bb cfg, cfg.cmdParser cfg\n\n@[inline] def Term.Parser (rbp : Nat := 0) : Parser  := \u03bb ps, ps.termParser rbp\n\n\ninstance : Monad parserM :=\n{pure := @parserM.pure, bind := @parserM.bind}\n\n@[inline] protected def orelse {\u03b1 : Type} (p q : parserM \u03b1) : parserM \u03b1 :=\n\u03bb ps cfg r,\n  match r with\n  | \u27e8Result.ok _ i\u2081 _ s\u2081 _, _\u27e9 :=\n    (match p ps cfg r with\n     | Result.error msg\u2081 i\u2082 c\u2082 stx\u2081 tt := q ps cfg (mkResultOk i\u2081 c\u2082 s\u2081)\n     | other                           := other)\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline] protected def failure {\u03b1 : Type} : parserM \u03b1 :=\n\u03bb _ _ r,\n  match r with\n  | \u27e8Result.ok _ i c s _, h\u27e9    := Result.error \"failure\" i c Syntax.missing tt\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\ninstance : Alternative parserM :=\n{ orelse         := @flatParser.orelse,\n  failure        := @flatParser.failure,\n  ..flatParser.Monad }\n\ndef setSilentError {\u03b1 : Type} : Result \u03b1 \u2192 Result \u03b1\n| (Result.error i c msg stx _) := Result.error i c msg stx tt\n| other                        := other\n\n/--\n`try p` behaves like `p`, but it pretends `p` hasn't\nconsumed any input when `p` fails.\n-/\n@[inline] def try {\u03b1 : Type} (p : parserM \u03b1) : parserM \u03b1 :=\n\u03bb ps cfg r, setSilentError (p ps cfg r)\n\n@[inline] def atEnd (cfg : ParserConfig) (i : pos) : Bool :=\ncfg.input.utf8AtEnd i\n\n@[inline] def curr (cfg : ParserConfig) (i : pos) : Char :=\ncfg.input.utf8Get i\n\n@[inline] def next (cfg : ParserConfig) (i : pos) : pos :=\ncfg.input.utf8Next i\n\n@[inline] def inputSize (cfg : ParserConfig) : Nat :=\ncfg.input.length\n\n@[inline] def currPos : resultOk \u2192 pos\n| \u27e8Result.ok _ i _ _ _, _\u27e9    := i\n| \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline] def currState : resultOk \u2192 ParserState\n| \u27e8Result.ok _ _ _ s _, _\u27e9    := s\n| \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[inline] def satisfy (p : Char \u2192 Bool) : parserM Char :=\n\u03bb _ cfg r,\n  match r with\n  | \u27e8Result.ok _ i ch st e, _\u27e9 :=\n    if atEnd cfg i then mkError r \"end of input\"\n    else let c := curr cfg i in\n         if p c then Result.ok c (next cfg i) ch st ff\n         else mkError r \"unexpected character\"\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\ndef any : parserM Char :=\nsatisfy (\u03bb _, tt)\n\n@[specialize] def takeUntilAux (p : Char \u2192 Bool) (cfg : ParserConfig) : Nat \u2192 resultOk \u2192 Result Unit\n| 0     r := r.val\n| (n+1) r :=\n  match r with\n  | \u27e8Result.ok _ i ch st e, _\u27e9 :=\n    if atEnd cfg i then r.val\n    else let c := curr cfg i in\n         if p c then r.val\n         else takeUntilAux n (mkResultOk (next cfg i) ch st tt)\n  | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n@[specialize] def takeUntil (p : Char \u2192 Bool) : parserM Unit :=\n\u03bb ps cfg r, takeUntilAux p cfg (inputSize cfg) r\n\ndef takeUntilNewLine : parserM Unit :=\ntakeUntil (= '\\n')\n\ndef whitespace : parserM Unit :=\ntakeUntil (\u03bb c, !c.isWhitespace)\n\n-- setOption Trace.Compiler.boxed True\n--- setOption pp.implicit True\n\ndef strAux (cfg : ParserConfig) (str : String) (error : String) : Nat \u2192 resultOk \u2192 pos \u2192 Result Unit\n| 0     r j := mkError r error\n| (n+1) r j :=\n  if str.utf8AtEnd j then r.val\n  else\n    match r with\n    | \u27e8Result.ok _ i ch st e, _\u27e9 :=\n      if atEnd cfg i then Result.error error i ch Syntax.missing tt\n      else if curr cfg i = str.utf8Get j then strAux n (mkResultOk (next cfg i) ch st tt) (str.utf8Next j)\n      else Result.error error i ch Syntax.missing tt\n    | \u27e8Result.error _ _ _ _ _, h\u27e9 := unreachableError h\n\n-- #exit\n\n@[inline] def str (s : String) : parserM Unit :=\n\u03bb ps cfg r, strAux cfg s (\"expected \" ++ repr s) (inputSize cfg) r 0\n\n@[specialize] def manyAux (p : parserM Unit) : Nat \u2192 Bool \u2192 parserM Unit\n| 0     fst := pure ()\n| (k+1) fst := \u03bb ps cfg r,\n  let i\u2080 := currPos r in\n  let s\u2080 := currState r in\n  match p ps cfg r with\n  | Result.ok a i c s _    := manyAux k ff ps cfg (mkResultOk i c s)\n  | Result.error _ _ c _ _ := Result.ok () i\u2080 c s\u2080 fst\n\n@[inline] def many (p : parserM Unit) : parserM Unit  :=\n\u03bb ps cfg r, manyAux p (inputSize cfg) tt ps cfg r\n\n@[inline] def many1 (p : parserM Unit) : parserM Unit  :=\np *> many p\n\ndef dummyParserCore : parserCore :=\n\u03bb cfg r, mkError r \"dummy\"\n\ndef testParser {\u03b1 : Type} (x : parserM \u03b1) (input : String) : String :=\nlet r :=\n  x { cmdParser := dummyParserCore, termParser := \u03bb _, dummyParserCore }\n    { filename := \"test\", input := input, FileMap := FileMap.fromString input, tokens := Lean.Parser.Trie.mk }\n    (mkResultOk 0 {} {messages := MessageLog.Empty}) in\nmatch r with\n| Result.ok _ i _ _ _      := \"Ok at \" ++ toString i\n| Result.error msg i _ _ _ := \"Error at \" ++ toString i ++ \": \" ++ msg\n\n/-\nmutual def recCmd, recTerm (parseCmd : Parser) (parseTerm : Nat \u2192 Parser) (parseLvl : Nat \u2192 parserCore)\nwith recCmd  : Nat \u2192 parserCore\n| 0     cfg r := mkError r \"Parser: no progress\"\n| (n+1) cfg r := parseCmd \u27e8recCmd n, parseLvl, recTerm n\u27e9 cfg r\nwith recTerm : Nat \u2192 Nat \u2192 parserCore\n| 0     rbp cfg r := mkError r \"Parser: no progress\"\n| (n+1) rbp cfg r := parseTerm rbp \u27e8recCmd n, parseLvl, recTerm n\u27e9 cfg r\n-/\n\n/-\ndef runParser (x : Parser) (parseCmd : Parser) (parseLvl : Nat \u2192 Parser) (parseTerm : Nat \u2192 Parser)\n               (input : Iterator) (cfg : ParserConfig) : Result Syntax :=\nlet it := input in\nlet n  := it.remaining in\nlet r  := mkResultOk it {} {messages := MessageLog.Empty} in\nlet pl := recLvl (parseLvl) n in\nlet ps : recParsers := { cmdParser  := recCmd parseCmd parseTerm pl n,\n                          lvlParser  := pl,\n                          termParser := recTerm parseCmd parseTerm pl n } in\nx ps cfg r\n-/\n\nstructure parsingTables :=\n(leadingTermParsers : TokenMap Parser)\n(trailingTermParsers : TokenMap trailingParser)\n\nabbreviation CommandParserM (\u03b1 : Type) :=\nparsingTables \u2192 parserM \u03b1\n\nend flatParser\nend Lean\n\ndef mkBigString : Nat \u2192 String \u2192 String\n| 0     s := s\n| (n+1) s := mkBigString n (s ++ \"-- new comment\\n\")\n\nsection\nopen Lean.flatParser\n\ndef flatP : parserM Unit :=\nmany1 (str \"--\" *> takeUntil (= '\\n') *> any *> pure ())\n\nend\n\nsection\nopen Lean.Parser\nopen Lean.Parser.MonadParsec\n\n@[reducible] def Parser (\u03b1 : Type) : Type :=  ReaderT Lean.flatParser.recParsers (ReaderT Lean.flatParser.ParserConfig (ParsecT Syntax (StateT ParserCache id))) \u03b1\n\ndef testParsec (p : Parser Unit) (input : String) : String :=\nlet ps : Lean.flatParser.recParsers := { cmdParser := Lean.flatParser.dummyParserCore, termParser := \u03bb _, Lean.flatParser.dummyParserCore } in\nlet cfg : Lean.flatParser.ParserConfig := { filename := \"test\", input := input, FileMap := Lean.flatParser.FileMap.fromString input, tokens := Lean.Parser.Trie.mk } in\nlet r := p ps cfg input.mkIterator {} in\nmatch r with\n| (Parsec.Result.ok _ it _, _)   := \"OK at \" ++ toString it.offset\n| (Parsec.Result.error msg _, _) := \"Error \" ++ msg.toString\n\ndef parsecP : Parser Unit :=\nmany1' (str \"--\" *> takeUntil (\u03bb c, c = '\\n') *> any *> pure ())\nend\n\n@[noinline] def testFlatP (s : String) : IO Unit :=\nIO.println (Lean.flatParser.testParser flatP s)\n\n@[noinline] def testParsecP (s : String) : IO Unit :=\nIO.println (testParsec parsecP s)\n\ndef prof {\u03b1 : Type} (msg : String) (p : IO \u03b1) : IO \u03b1 :=\nlet msg\u2081 := \"Time for '\" ++ msg ++ \"':\" in\nlet msg\u2082 := \"Memory usage for '\" ++ msg ++ \"':\" in\nallocprof msg\u2082 (timeit msg\u2081 p)\n\ndef main (xs : List String) : IO UInt32 :=\nlet s\u2081 := mkBigString xs.head.toNat \"\" in\nlet s\u2082 := s\u2081 ++ \"bad\" ++ mkBigString 20 \"\" in\nprof \"flat Parser 1\" (testFlatP s\u2081) *>\nprof \"flat Parser 2\" (testFlatP s\u2082) *>\n-- prof \"Parsec 1\" (testParsecP s\u2081) *>\n-- prof \"Parsec 2\" (testParsecP s\u2082) *>\npure 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/playground/flat_parser2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1112412182933608, "lm_q2_score": 0.014281936468669088, "lm_q1q2_score": 0.0015887400123631285}}
{"text": "/-\nCopyright (c) 2020 Sebastian Ullrich. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\nimport Lean.InternalExceptionId\nimport Lean.KeyedDeclsAttribute\n\nnamespace Lean\nnamespace PrettyPrinter\n\n/- Auxiliary internal exception for backtracking the pretty printer.\n   See `orelse.parenthesizer` for example -/\nbuiltin_initialize backtrackExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `backtrackFormatter\n\nunsafe def runForNodeKind {\u03b1} (attr : KeyedDeclsAttribute \u03b1) (k : SyntaxNodeKind) (interp : ParserDescr \u2192 CoreM \u03b1) : CoreM \u03b1 := do\n  match attr.getValues (\u2190 getEnv) k with\n  | p::_ => pure p\n  | _ =>\n    -- assume `k` is from a `ParserDescr`, in which case we assume it's also the declaration name\n    let info \u2190 getConstInfo k\n    if info.type.isConstOf ``ParserDescr || info.type.isConstOf ``TrailingParserDescr then\n      let d \u2190 evalConst ParserDescr k\n      interp d\n    else\n      throwError \"no declaration of attribute [{attr.defn.name}] found for '{k}'\"\n\nend PrettyPrinter\nend Lean\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/PrettyPrinter/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.06371499602983463, "lm_q2_score": 0.02405355123285508, "lm_q1q2_score": 0.0015325719213047852}}
{"text": "import Lean.Elab.Tactic\n\nopen Lean Elab Tactic in\nelab \"print!\" : tactic => do\n  logInfo \"foo\"\n  throwError \"error\"\n\nexample : True := by\n  print!\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/1358.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.06278920158197557, "lm_q2_score": 0.02368946979158221, "lm_q1q2_score": 0.0014874428941137761}}
{"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 {\u03c9 : 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 : \u03c9.cause` is the correct notion of causality for the ontology `\u03c9`, \n   he can do this by using the `inhabited` type:\n\n   ```instance correct_notion_of_causality : inhabited \u03c9.cause := \u27e8X\u27e9```\n\n   If a philosopher uses this library to formalize his theory of causality\n   as the instance `X` of the `\u03c9.cause` type, and then adds the line above to his code,\n   he will be able to refer to `X` by the expression `default \u03c9.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 \u03c9.cause` had previously been defined by another philosopher, `default \u03c9.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 \u03c9.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 \u03c9.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 \u03c9.cause`. And anything else that we did\n       say about causality which did not make reference to `default \u03c9.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 \u03c9.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 `\u03c9.efficient_cause` as an extension\n   of the `\u03c9.cause` structure which we define below with further axioms which characterize\n   efficient causes, and then define an instance of `inhabited \u03c9.efficient_cause`. \n   This would also not pose problems if we wanted to keep an already existing \n   definition of `inhabited \u03c9.cause` because\n   if we properly partition `\u03c9.cause` into subtypes then `default \u03c9.cause` would have to \"belong\"\n   to one of these subtypes, say `\u03c9.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 `\u03c9.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 \u03c9.cause` even in the context\n   of there being subtypes of `\u03c9.cause` with their own `default`s, we need not remove the `inhabited \u03c9.cause` \n   instance definition from Lean just because we introduced a new subtype of `\u03c9.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 (\u03c9 : ontology) :=\n  (explains : \u03c9.event \u2192 \u03c9.event \u2192 \u03c9.event)\n  (nontrivial : \u2203 e\u2081 e\u2082, \u22c4explains e\u2081 e\u2082)\n  (transitive : \u2200 e\u2081 e\u2082 e\u2083, explains e\u2081 e\u2082 \u2229 explains e\u2082 e\u2083 \u21d2 explains e\u2081 e\u2083)\n  (axiom\u2080 : \u2200 {e w}, (\u2203 e', explains e' e w) \u2192 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\u2080\n\nnamespace explanation \n\n  variable (\u03b5 : \u03c9.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 := \u2200 {e w}, (\u2203 e', \u03b5.explains e e' w) \u2192 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 : \u03c9 .event) := \u2200 e', \u03b5.explains e' e \u21d2 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\u2080` \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\u2081 e\u2082 : \u03c9.event) : \u03c9.event := \u03b5.explains e\u2081 e\u2082 \u2229 {w | \u03b5.explains e\u2081 e\u2082 \u21d2 e\u2081}\n\n  -- Note that in the right of the `\u2229` in the previous definition we are just lifting a `Prop` to an\n  -- `\u03c9.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 \u03c9) : \u03c9.event := \n    {w : \u03c9.world | \u2200 (e : \u03c9.event), kind e \u2192 e.occurs w \u2192 \u2203 e', \u03b5.explains e' e w}\n\n  /-- The (explanatory) **Weak Principle of Sufficient Reason**, as an event. -/\n  def ewpsr (kind := @event.contingent \u03c9) : \u03c9.event := \n    {w : \u03c9.world | \u2200 (e : \u03c9.event), kind e \u2192 e.occurs w \u2192 \u2203 e', \u22c4\u03b5.explains e' e}\n\n  /-- The (explanatory) **Principle of Sufficient Reason**. -/\n  def psr (kind := @event.contingent \u03c9) : Prop := \u25a1\u03b5.epsr kind\n\n  -- Note: by introducing the default argument in the definition, \n  -- we get that calling `\u03b5.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 : \u03c9.event := \u03b5.epsr univ \n\n  /-- A **stronger** version of the (explanatory) **Principle of Sufficient Reason**. -/\n  def spsr : Prop := \u25a1\u03b5.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 (\u03c9 : ontology) extends explanation \u03c9 :=\n  (irreflexive : \u2200 e, \u00ac\u22c4explains e e)\n\nnamespace cause\n\n  variable (c : \u03c9.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 := \u2200 {e w}, (\u2203 e', c.causes e e' w) \u2192 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 : \u03c9 .event) := \u2200 (e'), c.causes e' e \u21d2 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 : \u03c9 .event) : \u03c9.event := {w | \u2200 (e'), c.causes e' e w \u2192 e'.occurs w}\n\n  /-- An event `e\u2081` **simultaneously causes** another event `e\u2082` if `e\u2081` causes `e\u2082` and \n      `e\u2081` needs to be simultaneous with `e\u2082` in order to cause it. -/\n  def simcauses (e\u2081 e\u2082 : \u03c9.event) : \u03c9.event := c.causes e\u2081 e\u2082 \u2229 {w | c.causes e\u2081 e\u2082 \u21d2 e\u2081}\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 \u03c9) : \u03c9.event := {w | \u2200 e, kind e \u2192 e.occurs w \u2192 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 \u03c9) : Prop := \u25a1c.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 \u03c9) : \u03c9.event := {w | \u2200 e, kind e \u2192 e.exists w \u2192 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 \u03c9) : Prop := \u25a1c.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 : \u03c9.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 := \u25a1c.epss\n\n  def caused (e : \u03c9.event) : \u03c9.event := {w | \u2203 e', c.causes e' e w}\n  def simcaused (e : \u03c9.event) : \u03c9.event := {w | \u2203 e', c.simcauses e' e w}\n  def is_cause (e : \u03c9.event) : \u03c9.event := {w | \u2203 e', c.causes e e' w}\n  def uncaused (e : \u03c9.event) : \u03c9.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 : \u03c9.event) (e\u2081 : \u03c9.entity) : \u03c9.event := \n    {w | \u2200 e\u2082 : \u03c9.entity, e\u2082 \u2248 e\u2081 \u2192 e\u2082.exists w \u2192 c.causes e e\u2082 w}\n\n  /-- **External cause**. -/\n  def excauses (e : \u03c9.event) (e\u2081 : \u03c9.entity) : \u03c9.event := \n    c.causes e e\u2081 \u2229 {w | \u00ac \u2203 e\u2082 : \u03c9.entity, e\u2082.exists = e \u2227 e\u2081 \u2248 e\u2082}\n\n  def ppc\u2080 : Prop := \u2200 (e : \u03c9.event) (e\u2081 : \u03c9.entity), c.simcauses e e\u2081 \u21d2 c.excauses e e\u2081\n  \n  /-- **Strictly Existential cause**. -/\n  def secauses (e : \u03c9.event) (e\u2081 : \u03c9.entity) : \u03c9.event := \n    c.causes e e\u2081 \u2229 {w | \u00ac \u2203 e\u2082 : \u03c9.entity, e\u2082 \u2260 e\u2081 \u2227 e\u2081 \u2248 e\u2082 \u2227 c.causes e e\u2082 w}\n\n  /-- **Existential cause**. -/ -- needs some work, appears trivial.\n  def ecauses (e : \u03c9.event) (e\u2081 : \u03c9.entity) : \u03c9.event := c.secauses e e\u2081 \u222a c.exacts e e\u2081\n\n  def entitative : Prop := \u2200 {e}, \u22c4c.is_cause e \u2192 e.existential\n  def effentitative : Prop := \u2200 {e}, \u22c4c.caused e \u2192 e.existential\n  def substantive : Prop := \u2200 {e}, \u22c4c.is_cause e \u2192 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 (\u03a9 : \u03c9.iontology) : Prop := \u2200 (e\u2081 e\u2082 : \u03c9.entity), e\u2082.real \u03a9 \u2192 \u22c4c.causes e\u2081 e\u2082 \u2192 e\u2081.real \u03a9\n  \n  def consubstantial : Prop := \u2200 e (e\u2081 : \u03c9.entity), c.causes e e\u2081 \u21d2 c.exacts e e\u2081\n  \n  section conjunctive\n    def conjunctive : Prop := \u2200 e e\u2081 e\u2082, c.causes e (e\u2081 \u2229 e\u2082) = c.causes e e\u2081 \u2229 c.causes e e\u2082\n    def conjunctive\u2081 : Prop := \u2200 e e\u2081 e\u2082, c.causes e (e\u2081 \u2229 e\u2082) \u21d2 c.causes e e\u2081 \u2229 c.causes e e\u2082\n    def conjunctive\u2082 : Prop := \u2200 e e\u2081 e\u2082, c.causes e e\u2081 \u2229 c.causes e e\u2082 \u21d2 c.causes e (e\u2081 \u2229 e\u2082)\n\n    def conjunctive' : Prop := \n      \u2200 e e\u2081 e\u2082 : \u03c9.event,\n      e\u2081.contingent \u2192 e\u2082.contingent \u2192 c.causes e (e\u2081 \u2229 e\u2082) = c.causes e e\u2081 \u2229 c.causes e e\u2082\n    def conjunctive\u2081' : Prop := \n      \u2200 e e\u2081 e\u2082 : \u03c9.event, \n      e\u2081.contingent \u2192 e\u2082.contingent \u2192 c.causes e (e\u2081 \u2229 e\u2082) \u21d2 c.causes e e\u2081 \u2229 c.causes e e\u2082\n    \n    def conjunctive\u2082' : Prop := \n      \u2200 e e\u2081 e\u2082 : \u03c9.event, \n      e\u2081.contingent \u2192 e\u2082.contingent \u2192 c.causes e e\u2081 \u2229 c.causes e e\u2082 \u21d2 c.causes e (e\u2081 \u2229 e\u2082)\n\n    def conjunctive\u2081'' : Prop := \n      \u2200 e e\u2081 e\u2082 : \u03c9.event, e\u2081 \u2262 e\u2082 \u2192 c.causes e (e\u2081 \u2229 e\u2082) \u21d2 c.causes e e\u2081 \u2229 c.causes e e\u2082\n    \n    def econjunctive\u2081'' : Prop := \n      \u2200 e e\u2081 e\u2082 : \u03c9.event, e\u2081.entitative \u2192 e\u2081 \u2262 e\u2082 \u2192 c.causes e (e\u2081 \u2229 e\u2082) \u21d2 c.causes e e\u2081\n      \n  \n  end conjunctive\n\n  def disjunctive : Prop := \u2200 e e\u2081 e\u2082, c.causes e (e\u2081 \u222a e\u2082) = c.causes e e\u2081 \u222a c.causes e e\u2082\n  def subadditive : Prop := \u2200 e e\u2081 e\u2082, c.causes e (e\u2081 \u222a e\u2082) \u21d2 c.causes e e\u2081 \u222a c.causes e e\u2082\n  def superadditive : Prop := \u2200 e e\u2081 e\u2082, c.causes e e\u2081 \u222a c.causes e e\u2082 \u21d2 c.causes e (e\u2081 \u222a e\u2082)\n\n  /-- Causal monotonicity -/\n  def monotone : Prop := \u2200 e e\u2081 e\u2082 : \u03c9.event, e\u2081 \u21d2 e\u2082 \u2192 c.causes e e\u2081 \u21d2 c.causes e e\u2082\n\n  /-- Contingent causal monotonicity -/\n  def cmonotone : Prop := \n    \u2200 e e\u2081 e\u2082 : \u03c9.event, e\u2081.contingent \u2192 e\u2082.contingent \u2192 \n    e\u2081 \u21d2 e\u2082 \u2192 c.causes e e\u2081 \u21d2 c.causes e e\u2082\n  \n  def K : Prop := \u2200 e e\u2081 e\u2082, c.causes e (e\u2081 \u27f6 e\u2082) \u21d2 ((c.causes e e\u2081) \u27f6 c.causes e e\u2082)\n  def axiom\u2084\u2080 : Prop := \u2200 e\u2081 e\u2082, c.causes e\u2081 e\u2082 \u21d2 c.causes e\u2081 (c.causes e\u2081 e\u2082)\n  def axiom\u2084\u2081 : Prop := \u2200 e, c.caused e \u21d2 c.caused (c.caused e)\n  def axiom\u2084\u2082 : Prop := \u2200 e\u2081 e\u2082, c.causes e\u2081 e\u2082 = c.causes e\u2081 (c.caused e\u2082)\n  lemma T : \u2200 {e}, c.caused e \u21d2 e := by\n    rintros e w \u27e8e\u2082, h\u27e9; exact c.axiom\u2080 \u27e8e\u2082, h\u27e9\n\n  @[simp]\n  lemma caused_causes : \u2200 {e\u2081 e\u2082}, c.causes e\u2081 e\u2082 \u21d2 c.caused e\u2082 := \n    assume e\u2081 _ _ h, \u27e8e\u2081,h\u27e9\n\n  @[simp]\n  lemma occured_causes : \u2200 {e\u2081 e\u2082}, c.causes e\u2081 e\u2082 \u21d2 e\u2082 := by\n    intros e\u2081 e\u2082 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\u2081' \u2192 \u2200 {w e}, c.causes e {w} w \u2192\n                                       \u2200 e' : \u03c9.event, e'.contingent \u2192 e'.occurs w \u2192 c.causes e e' w\n                                       := begin\n    intros h\u2081 w e h\u2082 e' h\u2083 h\u2084,\n    by_cases h\u2085 : ({w} : \u03c9.event).contingent, swap,\n      simp [nbe, ext_iff] at h\u2083,\n      replace h\u2083 := h\u2083.2,\n      obtain \u27e8w', hw'\u27e9 := h\u2083,\n      simp [nbe, ext_iff] at h\u2085,\n      specialize h\u2085 w',\n      rw h\u2085 at hw',\n      contradiction,\n    replace h\u2081 := h\u2081 e {w} e',\n    suffices c\u2083 : {w} = {w} \u2229 e',\n      rw \u2190c\u2083 at h\u2081,\n      specialize h\u2081 h\u2085 h\u2083 h\u2082,\n      exact h\u2081.2,\n    ext w', simp,\n    refine \u27e8\u03bbh, \u27e8h,_\u27e9, and.left\u27e9,\n    cases h,\n    exact h\u2084,\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 : \u03c9.substance) (e : \u03c9.event) : \u03c9.event := \n    { w | c.simcauses s e w \u2227 \u2200 (context : \u03c9.event), \n      c.simcauses s e \u21d2 context \u2192 c.simcauses s e \u2260 context \u2192\n      \u2203 w', w' \u2260 w \u2227 s.state w' = s.state w \u2227 context.occurs w' \u2227\n      \u00acc.simcauses s e w'\n    }\n  \n  def has_will (s : \u03c9.substance) : Prop := \u2203 e, \u22c4c.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 : \u03c9.substance) : \u03c9.event := \n    { w | s.exists w \u2227 \u2203 e, \u22c4(c.fcauses s e \u2229 s.equiv w) \u2227\n      w \u2208 \u2726(c.fcauses s e) \u2227 \u00ac\u2203 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 : \u03c9.substance) : Prop := s \u21d2 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 \u03c9) : \u03c9.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 \u03c9) : \u03c9.event := c.up.ewpsr kind\n\n  /-- The causal version of the **Principle of Sufficient Reason**. -/\n  def psr (kind := @event.contingent \u03c9) : Prop := \u25a1c.epsr kind\n\n  /-- The **Principle of Causality**, as an event. This is the `psr` restricted to entities. -/\n  def epc (kind := @entity.contingent \u03c9) : \u03c9.event := \n    {w : \u03c9.world | \u2200 (e : \u03c9.entity), kind e \u2192 e.exists w \u2192 c.caused e w}\n  /-- The **Principle of Causality**. This is the `psr` restricted to entities. -/\n  def pc (kind := @entity.contingent \u03c9) : Prop := \u25a1c.epc kind\n\n\n  theorem Gale_Pruss : c.conjunctive\u2081' \u2192 c.ewpsr \u21d2 c.epsr :=\n    begin\n      intros h\u2080 w h\u2081,\n      specialize h\u2081 {w}, simp [ext_iff] at h\u2081,\n      by_cases hyp : \u2203 w', w' \u2260 w,\n        obtain \u27e8w', hw'\u27e9 := hyp,\n        specialize h\u2081 w' hw', clear hw' w',\n        obtain \u27e8C, w', h\u27e9 := h\u2081,\n        have c\u2081 := c.axiom\u2080 \u27e8C, h\u27e9, \n        simp at c\u2081, cases c\u2081, clear c\u2081,\n        have c\u2081 := c.cause_all_of_cause_singleton h\u2080 h,\n        intros e he\u2081 he\u2082, use C, apply c\u2081; assumption,\n      clear h\u2080 h\u2081,\n      intros e he, exfalso,\n      simp [entity.contingent, ext_iff] at he,\n      obtain \u27e8\u27e8w', hw'\u27e9, w'', hw''\u27e9 := he,\n      push_neg at hyp,\n      have c\u2081 := hyp w',\n      have c\u2082 := hyp w'', \n      cases c\u2081, cases c\u2082, clear hyp c\u2081 c\u2082,\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 := \u03bbe:\u03c9.event,true) : \u03c9.event := \n    {w | \u2200 e, kind e \u2192 c.caused e w \u2192 \u2203 e', w \u2208 c.uncaused e' \u2229 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 := \u03bbe:\u03c9.event,true) : Prop := \u25a1c.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 := \u03bbe:\u03c9.entity,true) : \u03c9.event := \n    {w | \u2200 (e : \u03c9.entity), kind e \u2192 c.caused e w \u2192 \u2203 e', w \u2208 c.uncaused e' \u2229 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 := \u03bbe:\u03c9.entity,true) : Prop := \u25a1c.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 : \u03c9.entity) : \u03c9.event := \n    {w | e.exists w \u2227 \u2200 e' : \u03c9.event, e'.occurs w \u2192 e.exists \u2260 e' \u2192 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 : \u03c9.entity) : \u03c9.event := \n    {w | e.exists w \u2227 \u2200 e' \u2208 w, e \u2260 e' \u2192 c.causes e e' w}\n  \n  def omnipotent (e : \u03c9.entity) : Prop := \u25a1c.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 := \u22c4c.first_cause \u03c9.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 : \u2200 {argument : \u03c9.event}, argument \u21d2 c.first_cause \u03c9.nbe \u2192 \u22c4argument \u2192 c.dscotus :=\n    by rintros arg h\u2081 \u27e8w, hw\u27e9; use w; exact h\u2081 hw\n\n  lemma first_cause_of_nocontingent : \u2200 {w}, (\u00ac\u2203 e : \u03c9.entity, e.contingent \u2227 e.exists w) \u2192 c.first_cause \u03c9.nbe w :=\n    begin\n      intros w h,\n      push_neg at h,\n      simp [cause.first_cause, nbe],\n      refine \u27e8by simp [univ],_\u27e9,\n      unfold_coes, simp,\n      intros e h\u2083 h\u2084,\n      replace h\u2084 := ne.symm h\u2084,\n      specialize h e,\n      simp [nbe, h\u2084] at h,\n      contradiction,\n    end\n  \n  lemma first_cause_of_parmenides : \u2200 {w}, (\u2200 w', w' = w) \u2192 c.first_cause \u03c9.nbe w :=\n    begin\n      intros w h,\n      apply c.first_cause_of_nocontingent,\n      rintro \u27e8e, h\u2081, h\u2082\u27e9,\n      suffices c : \u25a1e, 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 : \u03c9.event) : Prop := e.contingent \u2227 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 := \u03bbe:\u03c9.event,true) : \u03c9.event := \n    {w | \u2203 su, kind su \u2227 su.occurs w \u2227 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\u2081 := @entity.contingent \u03c9)  (kind\u2082 := @event.existential \u03c9) : \u03c9.event := \n    {w | (\u2203 e, kind\u2081 e \u2227 e.exists w) \u2192 c.kcsubstrata kind\u2082 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\u2081 := @entity.contingent \u03c9)  (kind\u2082 := @event.existential \u03c9) := \u25a1c.epcs kind\u2081 kind\u2082\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 \u03c9) : \u03c9.event := \n    {w | c.kcsubstrata kind w \u2192 \u2200 e,\n         (\u2200 su, c.csubstratum su \u2192 su \u2260 e \u2192 kind su \u2192 su.occurs w \u2192 c.causes e su w) \u2192\n         (\u2200 su, su \u2260 e \u2192 su.contingent \u2192 kind su \u2192 su.occurs w \u2192 c.causes e su w)\n    }\n  \n  def ultimate_substratum (e : \u03c9.event) : Prop := \n    c.csubstratum e \u2227 \u2200 e' : \u03c9.entity, c.causes e' e \u21d2 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 := \u03bbe:\u03c9.event,true) : \u03c9.event := \n    {w | \u2203 u, water u \u2227 u.occurs w \u2227 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 \u03c9)  (water := \u03bbe:\u03c9.event,true) : \u03c9.event := \n    {w | (\u2203 e, kind e \u2227 e.exists w) \u2192 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 \u03c9)  (water := \u03bbe:\u03c9.event,true) := \u25a1c.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 : \u03c9.event) : \u03c9.event := {w | \u2203 e' : \u03c9.event, e'.occurs w \u2227 \u22c4c.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' : \u03c9.event := {w | \u2200 e : \u03c9.event, \u22c4e \u2192 e.occurs w \u2228 c.cground e w}\n  -- Notice the converse of the (`\u2192`) 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 : \u03c9.event := {w | \u2200 e : \u03c9.event, e.npnegative \u2192 e.occurs w \u2228 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 : \u03c9.event := {w | \u2200 (e : \u03c9.entity), e.exists w \u2228 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\u2081 : Prop := \u2200 (w : \u03c9.world), c.acam' w \u2192 (\u2200 w', w' \u2260 w \u2192 c.epsr.occurs w') \u2192 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\u2081`. -/\n  def prussian_principle\u2082 : Prop := \u2200 (w : \u03c9.world), c.acam w \u2192 (\u2200 w', (\u2203 e \u2208 w', e \u2209 w) \u2192 c.epc.occurs w') \u2192 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 : \u25a1c.acam' \u2192 \u2200 e : \u03c9.event, e.contingent \u2192 e \u2262 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 \u27e8he, \u27e8w, hw\u27e9\u27e9 := 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 \u27e8C, h\u2081, \u27e8w', hw'\u27e9\u27e9 := h,\n        have c\u2080 := c.axiom\u2080 \u27e8C, hw'\u27e9,\n        specialize absurd c\u2080,\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\u2080 : c.uncaused e w,\n        specialize absurd c\u2080, 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\u2080 \u27e8C, absurd\u27e9,\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    \u2200 e C : \u03c9.event, e.contingent \u2192 \n    c.causes C (e \u2229 c.uncaused e) \u21d2 c.causes C e\n\n  theorem pruss_nature_of_modality_argument\u2080 : c.conjunctive\u2081'' \u2192 \u25a1c.acam' \u2192 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 \u27e8E, h\u2081, w', h\u2082, \u27e8h\u2083, h\u2084\u27e9\u27e9 := contra,\n      let \u00abE*\u00bb := c.uncaused E \u2229 E,\n      simp [cause.acam', ext_iff] at h,\n      have c\u2080 : w \u2208 \u00abE*\u00bb,\n        refine \u27e8_, h\u2083\u27e9,\n        simpa [cause.uncaused, cause.caused],\n      specialize h w' \u00abE*\u00bb \u27e8w, c\u2080\u27e9,\n      simp [h\u2082, cause.cground, set_of] at h,\n      obtain \u27e8C, h\u2085, \u27e8w'', h\u2086\u27e9\u27e9 := h,\n      simp [\u00abE*\u00bb] at h\u2086,\n      specialize conj C E (c.uncaused E) _, swap,\n        apply (indep E), \n        simp [event.contingent, event.necessary, ext_iff],\n        exact \u27e8\u27e8w, h\u2083\u27e9,\u27e8w', h\u2082\u27e9\u27e9,\n      simp only [inter_comm] at h\u2086,\n      specialize conj h\u2086, clear h\u2086,\n      obtain \u27e8h\u2086, h\u2087\u27e9 := conj,\n      replace h\u2087 := c.axiom\u2080 \u27e8C, h\u2087\u27e9,\n      simp [cause.uncaused, cause.caused] at h\u2087,\n      specialize h\u2087 C,\n      contradiction,\n    end\n\n  theorem pruss_nature_of_modality_argument\u2080' : c.prussian_minimal_extra_assumption \u2192 \u25a1c.acam' \u2192 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 \u27e8E, h\u2081, w', h\u2082, \u27e8h\u2083, h\u2084\u27e9\u27e9 := contra,\n      let \u00abE*\u00bb := c.uncaused E \u2229 E,\n      simp [cause.acam', ext_iff] at h,\n      have c\u2080 : w \u2208 \u00abE*\u00bb,\n        refine \u27e8_, h\u2083\u27e9,\n        simpa [cause.uncaused, cause.caused],\n      specialize h w' \u00abE*\u00bb \u27e8w, c\u2080\u27e9,\n      simp [h\u2082, cause.cground, set_of] at h,\n      obtain \u27e8C, h\u2085, \u27e8w'', h\u2086\u27e9\u27e9 := h,\n      simp [\u00abE*\u00bb] at h\u2086,\n      specialize min E C _, swap,\n        simp [event.contingent, event.necessary, ext_iff],\n        exact \u27e8\u27e8w, h\u2083\u27e9,\u27e8w', h\u2082\u27e9\u27e9,\n      simp only [inter_comm] at h\u2086,\n      specialize min h\u2086, \n      replace h\u2086 := c.axiom\u2080 \u27e8C, h\u2086\u27e9,\n      simp [cause.uncaused, cause.caused] at h\u2086,\n      replace h\u2086 := h\u2086.2 C,\n      contradiction,\n    end  \n\n  theorem pruss_nature_of_modality_argument\u2081 : c.conjunctive\u2081'' \u2192 \n    c.prussian_minimal_extra_assumption \u2192 c.prussian_principle\u2081 \n    \u2192 \u22c4c.acam' \u2192 c.psr :=\n    begin\n      intros conj min pruss h,\n      obtain \u27e8actual_world, ha\u27e9 := h,\n      suffices c\u2080 : \u2200 w', w' \u2260 actual_world \u2192 c.epsr.occurs w',\n        have c\u2081 := pruss actual_world ha c\u2080,\n        simp [cause.psr, ext_iff], intro w,\n        by_cases h : w = actual_world,\n          rw h, exact c\u2081,\n        exact c\u2080 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 \u27e8E, h\u2080, h\u2081, h\u2082, h\u2083\u27e9 := contra,\n      by_cases h : E.occurs actual_world,\n        let nonactuality : \u03c9.event := -{actual_world},\n        let F := E \u2229 nonactuality,\n        let \u00abF*\u00bb := F \u2229 c.uncaused F,\n        have c\u2080 : w \u2208 F,\n          refine \u27e8h\u2082, _\u27e9,\n          simp [nonactuality, hw],\n        have c\u2081 : E \u2262 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 \u27e8world, hworld\u27e9 := h\u2081,\n          by_cases aux : world = actual_world,\n            cases aux, contradiction,\n          have : world \u2208 nonactuality,\n            simp [nonactuality, aux],\n          specialize absurd this,\n          contradiction,\n        have c\u2082 : \u2200 (C : \u03c9.event), \u00acc.causes C F w,\n          intros C absurd,\n          have c' := conj C E nonactuality c\u2081 absurd,\n          replace c' := c'.1,\n          specialize h\u2083 C,\n          contradiction,\n        have c\u2083 : \u22c4\u00abF*\u00bb,\n          refine \u27e8w, c\u2080, _\u27e9,\n          simpa [cause.uncaused, cause.caused],\n        have c\u2084 : actual_world \u2209 \u00abF*\u00bb,\n          intro absurd, simp [\u00abF*\u00bb, F] at absurd,\n          contradiction,\n        clear c\u2081 c\u2082,\n        simp [cause.acam'] at ha,\n        specialize ha \u00abF*\u00bb c\u2083, clear c\u2083,\n        simp [c\u2084, cause.cground, set_of] at ha, clear c\u2084,\n        obtain \u27e8C, actual_C, w', hw'\u27e9 := ha,\n        specialize min F C _, swap,\n          simp [event.contingent, event.necessary, ext_iff],\n          refine \u27e8\u27e8w, c\u2080\u27e9, actual_world, _\u27e9, simp [h],\n        specialize min hw',\n        replace hw' := c.axiom\u2080 \u27e8C, hw'\u27e9,\n        replace hw' := hw'.2,\n        simp [cause.uncaused, cause.caused] at hw',\n        specialize hw' C, contradiction,\n      -- second case\n      let \u00abF*\u00bb := E \u2229 c.uncaused E,\n      have c\u2083 : \u22c4\u00abF*\u00bb,\n          refine \u27e8w, h\u2082, _\u27e9,\n          simpa [cause.uncaused, cause.caused],\n      have c\u2084 : actual_world \u2209 \u00abF*\u00bb,\n        intro absurd, simp [\u00abF*\u00bb] at absurd,\n        replace absurd := absurd.1, \n        contradiction,\n      simp [cause.acam'] at ha,\n      specialize ha \u00abF*\u00bb c\u2083, clear c\u2083,\n      simp [c\u2084, cause.cground, set_of] at ha, clear c\u2084,\n      cases ha, replace ha := ha.1,\n        contradiction,\n      obtain \u27e8C, actual_C, w', hw'\u27e9 := ha,\n      specialize min E C _, swap,\n        simp [event.contingent, event.necessary, ext_iff],\n        exact \u27e8\u27e8w, h\u2082\u27e9, actual_world, h\u27e9,\n      specialize min hw',\n      replace hw' := c.axiom\u2080 \u27e8C, hw'\u27e9,\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\u2081' : c.conjunctive\u2081' \u2192 c.prussian_principle\u2081 \u2192 \u22c4c.acam' \u2192 c.psr :=\n    begin\n      intros conj pruss h,\n      obtain \u27e8actual_world, ha\u27e9 := h,\n      suffices c\u2080 : \u2200 w', w' \u2260 actual_world \u2192 c.epsr.occurs w',\n        have c\u2081 := pruss actual_world ha c\u2080,\n        simp [cause.psr, ext_iff], intro w,\n        by_cases h : w = actual_world,\n          rw h, exact c\u2081,\n        exact c\u2080 w h,\n      intros w hw,\n      simp [explanation.epsr],\n      intros e pe ce he, clear pe,\n      have c\u2081 : \u00acc.epsr.occurs w \u2192 \u2203 F : \u03c9.event, \u22c4F \u2227 \u00acF.occurs actual_world \u2227 \u00ac\u22c4c.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 \u27e8w', \u27e8e',he', h'\u27e9\u27e9 := contra,\n          obtain \u27e8w'', hw''\u27e9 := h',\n          have c\u2081 := c.occured_causes hw'',\n          simp at c\u2081,\n          rw c\u2081 at hw'', clear c\u2081 w'', rename hw'' c\u2081,\n          simp [cause.epsr, explanation.epsr] at brute,\n          obtain \u27e8ev, h\u2081, \u27e8h\u2082, h\u2083,h\u2084\u27e9\u27e9 := brute,\n          specialize h\u2084 e',\n          replace c\u2081 := c.cause_all_of_cause_singleton conj c\u2081,\n          specialize c\u2081 ev \u27e8h\u2081,h\u2082\u27e9 h\u2083,\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\u2081 := c\u2081 h,\n      obtain \u27e8F, pF, naF, hF\u27e9 := c\u2081,\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 : \u25a1c.nnacam \u2192 \u2200 e : \u03c9.event, e.contingent \u2192 e.npnegative \u2192 e \u2262 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 \u27e8he, \u27e8w, hw\u27e9\u27e9 := 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 \u27e8C, h\u2081, \u27e8w', hw'\u27e9\u27e9 := h,\n          have c\u2080 := c.axiom\u2080 \u27e8C, hw'\u27e9,\n          specialize absurd c\u2080,\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\u2080 : c.uncaused e w,\n          specialize absurd c\u2080, 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\u2080 \u27e8C, absurd\u27e9,\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 := \u2200 (e : \u03c9.entity), (\u2191e \u2229 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\u2081'' \u2192 c.pnnue \u2192 \u25a1c.nnacam \u2192 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 \u27e8E, w', h\u2082, \u27e8h\u2083, h\u2084\u27e9\u27e9 := contra,\n          let \u00abE*\u00bb := \u2191E \u2229 (c.uncaused E),\n          simp [cause.nnacam, ext_iff] at h,\n          have c\u2080 : \u00abE*\u00bb.npnegative, \n            simp [\u00abE*\u00bb],\n            exact pnnue E,\n          specialize h w' \u00abE*\u00bb c\u2080,\n          cases h, replace h := h.1, contradiction,\n          simp [cause.cground, set_of] at h,\n          obtain \u27e8C, h\u2085, \u27e8w'', h\u2086\u27e9\u27e9 := h,\n          simp [\u00abE*\u00bb] at h\u2086,\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 \u27e8\u27e8w, h\u2083\u27e9,\u27e8w', h\u2082\u27e9\u27e9,\n              by_contradiction contra,\n              push_neg at contra,\n              apply contra.2,\n              exact \u27e8E.existential, contra.1\u27e9,\n          specialize conj h\u2086, \n          replace h\u2086 := c.axiom\u2080 \u27e8C, h\u2086\u27e9,\n          simp [cause.uncaused, cause.caused] at h\u2086,\n          replace h\u2086 := h\u2086.2,\n          specialize h\u2086 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\u2081''` 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 (\u03c9)\n\n  /- A **Counterfactual Theory of (Hierarchical) Causality** is one which, beginning from\n      a theory of counterfactuals, defines hierarchical causality as \"If `e\u2082` is removed, then `e\u2081` is removed\",\n      i.e. there is strong counterfactual dependence between `e\u2081` and `e\u2082`. -/\n  -- def ctc (c : \u03c9.cfr := default \u03c9.cfr) : \u03c9.cause := begin\n  --   refine \u27e8\u27e8c.sdepends, _, _\u27e9, _\u27e9,\n  --    intros,\n  --    simp [cfr.sdepends, cfr.depends],\n  --    unfold_coes,\n  -- end\n  \n  -- TODO: Another interpretation of \"If `e\u2081` is removed, then `e\u2082` 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 {\u03c9}\n  \n  structure cause.mcause (c : \u03c9.cause) : Prop :=\n    (axiom\u2080 : c.substantive)\n    (axiom\u2081 : c.consubstantial)\n    (axiom\u2082 : c.effentitative)\n    (axiom\u2083 : c.simultaneous)\n    (axiom\u2084 : \u00ac\u2203 s, c.has_will s)\n    (axiom\u2085 : \u2200 (e : \u03c9.entity), \u22c4c.is_cause e \u2192 e.composite)\n    (axiom\u2086 : \u2200 (s : \u03c9.substance), \u22c4c.caused s \u2192 s.composite)\n    (axiom\u2087 : c.conjunctive\u2082')\n    (axiom\u2088 : c.pp)\n    (axiom\u2089 : \u2200 (s\u2081 s\u2082 : \u03c9.substance) w, c.causes s\u2081 s\u2082 w \u2192 s\u2082.equiv w \u2264 s\u2081.equiv w)\n    (axiom\u2081\u2080 : \u2200 s\u2081 s\u2082 : \u03c9.substance, \u22c4(-c.causes s\u2081 s\u2082 \u2229 s\u2081 \u2229 s\u2082))\n\n  def cause.uhylemorphism (c : \u03c9.cause) : \u03c9.event := { w | c.mcause \u2227 c.epc (\u03bbe, e.perfect \u2227 e.contingent) w}\n\n  variables {c : \u03c9.cause}\n  \n  def cause.mcause.atom (mc : c.mcause) (s : \u03c9.substance) := \u22c4c.is_cause s \u2227 \u00ac\u22c4c.caused s\n  def cause.mcause.immaterial (mc : c.mcause) (e : \u03c9.entity) := e.exists \u2229 c.uncaused e\n  \n  /-- **Principle of Immaterial Substratum** -/\n  def cause.mcause.pis (mc : c.mcause) (ec : \u03c9.cause) : \u03c9.event := \n    {w | \u2200 (e : \u03c9.entity), mc.immaterial e w \u2192 ec.substratum e}\n  \n  def cause.mcause.base (ec : c.mcause) (s : \u03c9.substance) : \u03c9.event := \n    {w | \u2200 e, c.caused e w \u2192 c.causes s e w}\n\n  \n  structure cause.mcause.ecompatible (mc : c.mcause) (ec : \u03c9.cause) : Prop :=\n    (axiom\u2081 : \u2200 (s : \u03c9.substance), \u22c4c.is_cause s \u2192 \u00acec.has_will s)\n    (axiom\u2082 : \u25a1 mc.pis ec)\n    \n  class cause.effcause (c : \u03c9.cause) : Prop :=\n    (axiom\u2080 : c.substantive)\n    (axiom\u2081 : c.conjunctive\u2081'')\n    -- (axiom\u2082 : c.pp' (\u03bbe, c.substratum e))\n    -- (axiom\u2083 : c.psr)\n    (axiom\u2084 : \u25a1c.acam')\n    \n\n  -- def ecause.aristotelian : Prop := \n    \n\n  --   variables (s : \u03c9.substance) (e : \u03c9.entity)\n\n  --   -- integral parthood\n  --   def substance.part_of (s\u2081 s\u2082 : \u03c9.substance) : \u03c9.event := sorry\n\n  --   -- efficient vertical causation\n  --   def substance.ecauses : \u03c9.event := \n  --     s.causes e.exists \u2229\n  --     -s.part_of e.substance \u2229\n  --     -e.substance.part_of s\n\n\n  --   -- compositional causation (we say s \"compositionally causes\" e)\n  --   def substance.ccauses : \u03c9.event := \n  --     s.causes e.exists \u2229\n  --     s.part_of e.substance \u2229\n  --     -e.substance.part_of s\n\n  --   -- formal causation\n  --   def substance.forcauses : \u03c9.event := \n  --     s.ccauses e \u2229\n  --     s.causes e.substance.exists\n\n  --   -- material causation\n  --   def substance.mcauses : \u03c9.event := \n  --     s.ccauses e \u2229\n  --     -s.causes e.substance.exists\n\n  --   -- final causation\n  --   def substance.fincauses : \u03c9.event := \n  --     s.causes e.exists \u2229\n  --     -s.part_of e.substance \u2229\n  --     e.substance.part_of s\n\nend four_causes\n\nsection principles\n\n  variable (\u03c9)\n\n  -- -- the thomistic principle of sufficent reason/causality\n  -- def tpsr : Prop := \n  --   \u2200 (s : \u03c9.substance) (p : \u03c9.predicate) (h\u2081 : p.proper) (h\u2082 : \u00ac p.dere_of s.up) (w \u2208 p s.up), \n  --   \u2203 c : \u03c9.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  --   \u2200 (s : \u03c9.substance) (p : \u03c9.predicate) (h\u2081 : p.proper) (h\u2082 : \u00ac p.dere_of s.up) (w \u2208 p s.up),\n  --   -- p s.up cast to an entity\n  --   let r := (entity.mk (p s.up) \n  --           (by apply h\u2081.axiom\u2082; exact e) \n  --           (by use w; assumption))\n  --   in \u2203 c : \u03c9.substance, c.ecauses r w\n\nend principles\n\nsection time\n\n  variables {\u03c9} (c : \u03c9.cause)\n\n  structure event.factor (e : \u03c9.event) :=\n    (begins : \u03c9.event)\n    (continues : \u03c9.event)\n    (disjoint : begins \u2229 continues = \u2205)\n    (factor : begins \u222a continues = e)\n    (nontrivial\u2081 : \u22c4begins)\n    (nontrivial\u2082 : \u22c4continues)\n\n  def cause.dircauses (e\u2081 : \u03c9.event) {e\u2082 : \u03c9.event} (f : e\u2082.factor) := c.simcauses e\u2081 f.begins\n\n  def event.factor.direct {e\u2082 : \u03c9.event} (f : e\u2082.factor) (c : \u03c9.cause) := c.substratum f.begins\n\n  def cause.indcauses (e\u2081 : \u03c9.event) {e\u2082 : \u03c9.event} (f : e\u2082.factor) := \n    (c.causes e\u2081 f.begins) \u2229 -(c.simcauses e\u2081 f.begins)\n\n  def cause.sindcauses (e\u2081 : \u03c9.event) {e\u2082 : \u03c9.event} (f : e\u2082.factor) := \n    { w | c.causes e\u2081 f.continues w \u2227 \u00ac c.simcauses e\u2081 f.continues w \u2227 \u22c4c.indcauses e\u2081 f }\n\n  def cause.wnoninertial (c : \u03c9.cause) {e : \u03c9.event} (f : e.factor) : Prop := c.substratum f.continues\n\n  def cause.noninertial (c : \u03c9.cause) {e : \u03c9.event} (f : e.factor) : Prop := \n    c.substratum f.continues \u2227 f.continues \u21d2 c.caused f.continues\n\n  def cause.inertial (c : \u03c9.cause) {e : \u03c9.event} (f : e.factor) : Prop := \u00ac c.noninertial f\n\n  structure cause.tfactor (c : \u03c9.cause) {e : \u03c9.event} (f : e.factor) : Prop:=\n    (axiom\u2081 : \u2200 ca, f.begins \u21d2 c.causes ca f.begins \u27f7 c.causes ca e)\n    (axiom\u2082 : \u2200 ca, f.continues \u21d2 c.causes ca f.continues \u27f7 c.causes ca e)\n\n  def cause.pind\u2081 {e : \u03c9.event} (f : e.factor) : Prop := \n    c.tfactor f \u2227\n    \u2200 (ca : \u03c9.event), c.causes ca e \u2229 -ca \u21d2 c.sindcauses ca f \u222a c.indcauses ca f\n\n  -- def cause.pind\u2082 : Prop := \n\n  def cause.pcem (c : \u03c9.cause) {c' : \u03c9.cause} (mc : c'.mcause) : \u03c9.event :=\n    {w | \u2200 e : \u03c9.entity, c'.caused e w \u2192 \u2203 f : e.exists.factor, c.tfactor f \u2227 f.direct c \u2227\n      \u2200 ca mca, c.causes ca f.continues \u21d2 c'.causes mca e \u27f6 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 : \u03c9.cause) (e : \u03c9.event) := \u2203 f : e.factor, f.direct c \u2227 c.tfactor f \u2227 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 : \u03c9.cause) (e : \u03c9.event) := \u2203 f : e.factor, f.direct c \u2227 c.tfactor f \u2227 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 : \u03c9.cause) (e : \u03c9.event) := \u2203 f : e.factor, f.direct c \u2227 c.tfactor f\n\n  def cause.direct' : \u03c9.event :=\n    {w | \u2200 e : \u03c9.event, e.occurs w \u2192 c.dtf e}\n\n  def cause.direct : \u03c9.event :=\n    {w | \u2200 e : \u03c9.entity, e.exists w \u2192 c.dtf e}\n\n  def cause.nidirect : \u03c9.event :=\n    {w | \u2200 e : \u03c9.entity, e.exists w \u2192 c.dnitf e}\n\n  def cause.wdnidirect : \u03c9.event :=\n    {w | \u2200 e : \u03c9.entity, e.exists w \u2192 c.wdnitf e}\n\n\n  -- lemma wdnitf_lemma : c.ps (\u03bbe, c.wnitf e) :=\n  --   begin\n\n  --   end\n\n  -- lemma quasi_simultaneity_of_wnidirect : \u25a1c.wdnidirect \u2192 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\u2081 e\u2081 aux h\u2081 e\u2082 w\u2082 h\u2082,\n  --     clear aux h\u2081 w\u2081,\n  --     have c\u2080 := c.occured_causes h\u2082,\n  --     specialize h w\u2082 e\u2081 c\u2080,\n  --     obtain \u27e8f, hf\u2081, hf\u2082\u27e9 := h,\n  --     unfold_coes at h\u2082,\n  --     by_cases h : f.begins w\u2082,\n  --       have c := hf\u2081.axiom\u2082 e\u2082 h,\n  --       replace c := c.2,\n  --       unfold_coes at c,\n  --       simp [h\u2082] at c,\n  --       replace c := hf\u2081.axiom\u2081 e\u2082 c,\n  --       exact c,\n  --     rw \u2190f.factor at c\u2080,\n  --     simp at c\u2080,\n  --     cases c\u2080, contradiction,\n  --     clear h,\n  --     replace c\u2080 := hf\u2081.axiom\u2083 e\u2082 c\u2080,\n  --     replace c\u2080 := c\u2080.2,\n  --     unfold_coes at c\u2080,\n  --     simp [h\u2082] at c\u2080,\n  --     replace hf\u2082 := hf\u2082 e\u2082 c\u2080,\n  --     exact hf\u2082,\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}}
{"text": "def sentences : Array String := #[ \n  \"lean theorem prover\",\n  \"programming is fun\",\n  \"go get an apple\",\n  \"hello there\",\n  \"here is a sentence\",\n  \"haha you will lose at hangman\"\n]", "meta": {"author": "crabbo-rave", "repo": "lean4-Hangman", "sha": "84704881bb1c8c2b647556d2042dfd7acd537880", "save_path": "github-repos/lean/crabbo-rave-lean4-Hangman", "path": "github-repos/lean/crabbo-rave-lean4-Hangman/lean4-Hangman-84704881bb1c8c2b647556d2042dfd7acd537880/sentences.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.06656918156310716, "lm_q2_score": 0.020023442057000226, "lm_q1q2_score": 0.0013329441498108041}}
{"text": "/-\nCopyright (c) 2020 Marc Huisinga. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Marc Huisinga, Wojciech Nawrocki\n-/\nimport Init.System.IO\nimport Init.Data.ByteArray\nimport Std.Data.RBMap\n\nimport Lean.Elab.Import\n\nimport Lean.Data.Lsp\nimport Lean.Server.Utils\nimport Lean.Server.Requests\n\n/-!\nFor general server architecture, see `README.md`. This module implements the watchdog process.\n\n## Watchdog state\n\nMost LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted\nworkers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes\nto the header and thus restart the corresponding worker, freeing its imports.\n\nTODO(WN):\nWe may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker\ncrashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed\n(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,\nusers may be confused about why the server seemingly stopped working for a single file.\n\n## Watchdog <-> worker communication\n\nThe watchdog process and its file worker processes communicate via LSP. If the necessity arises,\nwe might add non-standard commands similarly based on JSON-RPC. Most requests and notifications\nare forwarded to the corresponding file worker process, with the exception of these notifications:\n\n- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to\n                        asynchronously receive LSP packets from the worker (e.g. request responses).\n- textDocument/didChange: Update the local file state. If the header was mutated,\n                          signal a shutdown to the file worker by closing the I/O channels.\n                          Then restart the file worker. Otherwise, forward the `didChange` notification.\n- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.\n\nMoreover, we don't implement the full protocol at this level:\n\n- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server\n  capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.\n- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of\n  the file. No additional `didOpen` notifications will be forwarded to the worker process.\n- `$/cancelRequest` notifications are forwarded to all file workers.\n- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.\n  Similarly, they never receive a `didClose` notification.\n\n## Watchdog <-> client communication\n\nThe watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add\nnon-standard extensions in case they're needed, for example to communicate tactic state.\n-/\n\nnamespace Lean.Server.Watchdog\n\nopen IO\nopen Std (RBMap RBMap.empty)\nopen Lsp\nopen JsonRpc\n\nsection Utils\n  structure OpenDocument where\n    meta      : DocumentMeta\n    headerAst : Syntax\n\n  def workerCfg : Process.StdioConfig := {\n    stdin  := Process.Stdio.piped\n    stdout := Process.Stdio.piped\n    -- We pass workers' stderr through to the editor.\n    stderr := Process.Stdio.inherit\n  }\n\n  /-- Events that worker-specific tasks signal to the main thread. -/\n  inductive WorkerEvent where\n    /- A synthetic event signalling that the grouped edits should be processed. -/\n    | processGroupedEdits\n    | terminated\n    | crashed (e : IO.Error)\n    | ioError (e : IO.Error)\n\n  inductive WorkerState where\n    /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker\n       and when reading a request reply.\n       In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.\n       Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.\n       Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded\n       to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file\n       worker arrives. -/\n    | crashed (queuedMsgs : Array JsonRpc.Message)\n    | running\n\n  abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare\n\n  private def parseHeaderAst (input : String) : IO Syntax := do\n    let inputCtx   := Parser.mkInputContext input \"<input>\"\n    let (stx, _, _) \u2190 Parser.parseHeader inputCtx\n    return stx\nend Utils\n\nsection FileWorker\n  /-- A group of edits which will be processed at a future instant. -/\n  structure GroupedEdits where\n    /-- When to process the edits. -/\n    applyTime  : Nat\n    params     : DidChangeTextDocumentParams\n    /-- Signals when `applyTime` has been reached. -/\n    signalTask : Task WorkerEvent\n    /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/\n    queuedMsgs : Array JsonRpc.Message\n\n  structure FileWorker where\n    doc                : OpenDocument\n    proc               : Process.Child workerCfg\n    commTask           : Task WorkerEvent\n    state              : WorkerState\n    -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state\n    /-- The pending requests map contains all requests\n    that have been received from the LSP client, but were not answered yet.\n    This includes the queued messages in the grouped edits. -/\n    pendingRequestsRef : IO.Ref PendingRequestMap\n    groupedEditsRef    : IO.Ref (Option GroupedEdits)\n\n  namespace FileWorker\n\n  def stdin (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdin\n\n  def stdout (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdout\n\n  def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit :=\n    fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id\n\n  def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do\n    let pendingRequests \u2190 fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))\n    for \u27e8id, _\u27e9 in pendingRequests do\n      hError.writeLspResponseError { id := id, code := code, message := msg }\n\n  partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do\n    -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification\n    let rec loopAction : IO WorkerEvent := do\n      let now \u2190 monoMsNow\n      let some ge \u2190 fw.groupedEditsRef.get\n        | throwServerError \"Internal error: empty grouped edits reference in signal task\"\n      if ge.applyTime \u2264 now then\n        return WorkerEvent.processGroupedEdits\n      else\n        IO.sleep <| UInt32.ofNat <| ge.applyTime - now\n        loopAction\n\n    let t \u2190 IO.asTask loopAction\n    return t.map fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  end FileWorker\nend FileWorker\n\nsection ServerM\n  abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare\n\n  structure ServerContext where\n    hIn            : FS.Stream\n    hOut           : FS.Stream\n    hLog           : FS.Stream\n    /-- Command line arguments. -/\n    args           : List String\n    fileWorkersRef : IO.Ref FileWorkerMap\n    /-- We store these to pass them to workers. -/\n    initParams     : InitializeParams\n    editDelay      : Nat\n    workerPath     : System.FilePath\n\n  abbrev ServerM := ReaderT ServerContext IO\n\n  def updateFileWorkers (val : FileWorker) : ServerM Unit := do\n    (\u2190read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val)\n\n  def findFileWorker (uri : DocumentUri) : ServerM FileWorker := do\n    match (\u2190(\u2190read).fileWorkersRef.get).find? uri with\n    | some fw => fw\n    | none    => throwServerError s!\"Got unknown document URI ({uri})\"\n\n  def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do\n    (\u2190read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)\n\n  def log (msg : String) : ServerM Unit := do\n    let st \u2190 read\n    st.hLog.putStrLn msg\n    st.hLog.flush\n\n  /-- Creates a Task which forwards a worker's messages into the output stream until an event\n  which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/\n  private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do\n    let o := (\u2190read).hOut\n    let rec loop : ServerM WorkerEvent := do\n      try\n        let msg \u2190 fw.stdout.readLspMessage\n        if let Message.response id _ := msg then\n          fw.erasePendingRequest id\n        if let Message.responseError id _ _ _ := msg then\n          fw.erasePendingRequest id\n        -- Writes to Lean I/O channels are atomic, so these won't trample on each other.\n        o.writeLspMessage msg\n      catch err =>\n        -- If writeLspMessage from above errors we will block here, but the main task will\n        -- quit eventually anyways if that happens\n        let exitCode \u2190 fw.proc.wait\n        if exitCode = 0 then\n          -- Worker was terminated\n          fw.errorPendingRequests o ErrorCode.contentModified\n            (\"The file worker has been terminated. Either the header has changed,\"\n            ++ \" or the file was closed, or the server is shutting down.\")\n          return WorkerEvent.terminated\n        else\n          -- Worker crashed\n          fw.errorPendingRequests o ErrorCode.internalError\n            s!\"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then \"see stderr for exception\" else \"likely due to a stack overflow in user code\"}.\"\n          return WorkerEvent.crashed err\n      loop\n    let task \u2190 IO.asTask (loop $ \u2190read) Task.Priority.dedicated\n    task.map $ fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  def startFileWorker (m : DocumentMeta) : ServerM Unit := do\n    publishProgressAtPos m 0 (\u2190 read).hOut\n    let st \u2190 read\n    let headerAst \u2190 parseHeaderAst m.text.source\n    let workerProc \u2190 Process.spawn {\n      toStdioConfig := workerCfg\n      cmd           := st.workerPath.toString\n      args          := #[\"--worker\"] ++ st.args.toArray\n    }\n    let pendingRequestsRef \u2190 IO.mkRef (RBMap.empty : PendingRequestMap)\n    -- The task will never access itself, so this is fine\n    let fw : FileWorker := {\n      doc                := \u27e8m, headerAst\u27e9\n      proc               := workerProc\n      commTask           := Task.pure WorkerEvent.terminated\n      state              := WorkerState.running\n      pendingRequestsRef := pendingRequestsRef\n      groupedEditsRef    := \u2190 IO.mkRef none\n    }\n    let commTask \u2190 forwardMessages fw\n    let fw : FileWorker := { fw with commTask := commTask }\n    fw.stdin.writeLspRequest \u27e80, \"initialize\", st.initParams\u27e9\n    fw.stdin.writeLspNotification {\n      method := \"textDocument/didOpen\"\n      param  := {\n        textDocument := {\n          uri        := m.uri\n          languageId := \"lean\"\n          version    := m.version\n          text       := m.text.source\n        } : DidOpenTextDocumentParams\n      }\n    }\n    updateFileWorkers fw\n\n  def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do\n    /- The file worker must have crashed just when we were about to terminate it!\n       That's fine - just forget about it then.\n       (on didClose we won't need the crashed file worker anymore,\n       when the header changed we'll start a new one right after\n       anyways and when we're shutting down the server\n       it's over either way.) -/\n    try (\u2190findFileWorker uri).stdin.writeLspMessage (Message.notification \"exit\" none)\n    catch err => ()\n    eraseFileWorker uri\n\n  def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do\n    updateFileWorkers { \u2190findFileWorker uri with state := WorkerState.crashed queuedMsgs }\n\n  /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed\n      and restarts the file worker if the `crashed` flag was already set.\n      Messages that couldn't be sent can be queued up via the queueFailedMessage flag and\n      will be discharged after the FileWorker is restarted. -/\n  def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :\n      ServerM Unit := do\n    let fw \u2190 findFileWorker uri\n    let pendingEdit \u2190 fw.groupedEditsRef.modifyGet fun\n      | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg })\n      | none    => (false, none)\n    if pendingEdit then\n      return\n    match fw.state with\n    | WorkerState.crashed queuedMsgs =>\n      let mut queuedMsgs := queuedMsgs\n      if queueFailedMessage then\n        queuedMsgs := queuedMsgs.push msg\n      if !restartCrashedWorker then\n        return\n      -- restart the crashed FileWorker\n      eraseFileWorker uri\n      startFileWorker fw.doc.meta\n      let newFw \u2190 findFileWorker uri\n      let mut crashedMsgs := #[]\n      -- try to discharge all queued msgs, tracking the ones that we can't discharge\n      for msg in queuedMsgs do\n        try\n          newFw.stdin.writeLspMessage msg\n        catch _ =>\n          crashedMsgs := crashedMsgs.push msg\n      if \u00ac crashedMsgs.isEmpty then\n        handleCrash uri crashedMsgs\n    | WorkerState.running =>\n      let initialQueuedMsgs :=\n        if queueFailedMessage then\n          #[msg]\n        else\n          #[]\n      try\n        fw.stdin.writeLspMessage msg\n      catch _ =>\n        handleCrash uri initialQueuedMsgs\nend ServerM\n\nsection NotificationHandling\n  def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=\n    let doc := p.textDocument\n    /- NOTE(WN): `toFileMap` marks line beginnings as immediately following\n       \"\\n\", which should be enough to handle both LF and CRLF correctly.\n       This is because LSP always refers to characters by (line, column),\n       so if we get the line number correct it shouldn't matter that there\n       is a CR there. -/\n    startFileWorker \u27e8doc.uri, doc.version, doc.text.toFileMap\u27e9\n\n  def handleEdits (fw : FileWorker) : ServerM Unit := do\n    let some ge \u2190 fw.groupedEditsRef.modifyGet (\u00b7, none)\n      | throwServerError \"Internal error: empty grouped edits reference\"\n    let doc := ge.params.textDocument\n    let changes := ge.params.contentChanges\n    let oldDoc := fw.doc\n    let some newVersion \u2190 pure doc.version?\n      | throwServerError \"Expected version number\"\n    if newVersion <= oldDoc.meta.version then\n      throwServerError \"Got outdated version number\"\n    if changes.isEmpty then\n      return\n    let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text\n    let newMeta : DocumentMeta := \u27e8doc.uri, newVersion, newDocText\u27e9\n    let newHeaderAst \u2190 parseHeaderAst newDocText.source\n    if newHeaderAst != oldDoc.headerAst then\n      terminateFileWorker doc.uri\n      startFileWorker newMeta\n    else\n      let newDoc : OpenDocument := \u27e8newMeta, oldDoc.headerAst\u27e9\n      updateFileWorkers { fw with doc := newDoc }\n      tryWriteMessage doc.uri (Notification.mk \"textDocument/didChange\" ge.params) (restartCrashedWorker := true)\n      for msg in ge.queuedMsgs do\n        tryWriteMessage doc.uri msg\n\n  def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=\n    terminateFileWorker p.textDocument.uri\n\n  def handleCancelRequest (p : CancelParams) : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, fw\u27e9 in fileWorkers do\n      -- Cancelled requests still require a response, so they can't be removed\n      -- from the pending requests map.\n      if (\u2190 fw.pendingRequestsRef.get).contains p.id then\n        tryWriteMessage uri (Notification.mk \"$/cancelRequest\" p) (queueFailedMessage := false)\nend NotificationHandling\n\nsection MessageHandling\n  def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=\n      match fromJson? params with\n      | Except.ok parsed => pure parsed\n      | Except.error inner => throwServerError s!\"Got param with wrong structure: {params.compress}\\n{inner}\"\n\n  def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do\n    match (\u2190 Requests.routeLspRequest method params) with\n      | Except.error e => \n        (\u2190read).hOut.writeLspResponseError <| e.toLspResponseError id\n      | Except.ok uri =>\n        let fw \u2190 try\n          findFileWorker uri\n        catch _ =>\n          -- VS Code sometimes sends us requests just after closing a file?\n          -- This is permitted by the spec, but seems pointless, and there's not much we can do,\n          -- so we return an error instead.\n          (\u2190read).hOut.writeLspResponseError\n            { id      := id\n              code    := ErrorCode.contentModified\n              message := s!\"Cannot process request to closed file '{uri}'\" }\n          return\n        let r := Request.mk id method params\n        fw.pendingRequestsRef.modify (\u00b7.insert id r)\n        tryWriteMessage uri r\n\n  def handleNotification (method : String) (params : Json) : ServerM Unit := do\n    let handle := (fun \u03b1 [FromJson \u03b1] (handler : \u03b1 \u2192 ServerM Unit) => parseParams \u03b1 params >>= handler)\n    match method with\n    | \"textDocument/didOpen\"   => handle DidOpenTextDocumentParams handleDidOpen\n    /- NOTE: textDocument/didChange is handled in the main loop. -/\n    | \"textDocument/didClose\"  => handle DidCloseTextDocumentParams handleDidClose\n    | \"$/cancelRequest\"        => handle CancelParams handleCancelRequest\n    | _                        =>\n      if !\"$/\".isPrefixOf method then  -- implementation-dependent notifications can be safely ignored\n        (\u2190read).hLog.putStrLn s!\"Got unsupported notification: {method}\"\nend MessageHandling\n\nsection MainLoop\n  def shutdown : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, _\u27e9 in fileWorkers do\n      terminateFileWorker uri\n    for \u27e8_, fw\u27e9 in fileWorkers do\n      discard <| IO.wait fw.commTask\n\n  inductive ServerEvent where\n    | workerEvent (fw : FileWorker) (ev : WorkerEvent)\n    | clientMsg (msg : JsonRpc.Message)\n    | clientError (e : IO.Error)\n\n  def runClientTask : ServerM (Task ServerEvent) := do\n    let st \u2190 read\n    let readMsgAction : IO ServerEvent := do\n      /- Runs asynchronously. -/\n      let msg \u2190 st.hIn.readLspMessage\n      ServerEvent.clientMsg msg\n    let clientTask := (\u2190IO.asTask readMsgAction).map $ fun\n      | Except.ok ev   => ev\n      | Except.error e => ServerEvent.clientError e\n    return clientTask\n\n  partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do\n    let st \u2190 read\n    let workers \u2190 st.fileWorkersRef.get\n    let mut workerTasks := #[]\n    for (_, fw) in workers do\n      if let WorkerState.running := fw.state then\n        workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)\n        if let some ge \u2190 fw.groupedEditsRef.get then\n          workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw)\n\n    let ev \u2190 IO.waitAny (workerTasks.push clientTask |>.toList)\n    match ev with\n    | ServerEvent.clientMsg msg =>\n      match msg with\n      | Message.request id \"shutdown\" _ =>\n        shutdown\n        st.hOut.writeLspResponse \u27e8id, Json.null\u27e9\n      | Message.request id method (some params) =>\n        handleRequest id method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | Message.notification \"textDocument/didChange\" (some params) =>\n        let p \u2190 parseParams DidChangeTextDocumentParams (toJson params)\n        let fw \u2190 findFileWorker p.textDocument.uri\n        let now \u2190 monoMsNow\n        /- We wait `editDelay`ms since last edit before applying the changes. -/\n        let applyTime := now + st.editDelay\n        let queuedMsgs? \u2190 fw.groupedEditsRef.modifyGet fun\n          | some ge => (some ge.queuedMsgs, some { ge with\n            applyTime := applyTime\n            params.textDocument := p.textDocument\n            params.contentChanges := ge.params.contentChanges ++ p.contentChanges\n            -- drain now-outdated messages and respond with `contentModified` below\n            queuedMsgs := #[] })\n          | none    => (none, some {\n            applyTime := applyTime\n            params := p\n            /- This is overwritten just below. -/\n            signalTask := Task.pure WorkerEvent.processGroupedEdits\n            queuedMsgs := #[] })\n        match queuedMsgs? with\n        | some queuedMsgs =>\n          for msg in queuedMsgs do\n            match msg with\n            | JsonRpc.Message.request id _ _ =>\n              fw.erasePendingRequest id\n              (\u2190 read).hOut.writeLspResponseError {\n                id := id\n                code := ErrorCode.contentModified\n                message := \"File changed.\"\n              }\n            | _ => () -- notifications do not need to be cancelled\n        | _ =>\n          let t \u2190 fw.runEditsSignalTask\n          fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } )\n        mainLoop (\u2190runClientTask)\n      | Message.notification method (some params) =>\n        handleNotification method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | _ => throwServerError \"Got invalid JSON-RPC message\"\n    | ServerEvent.clientError e => throw e\n    | ServerEvent.workerEvent fw ev =>\n      match ev with\n      | WorkerEvent.processGroupedEdits =>\n        handleEdits fw\n        mainLoop clientTask\n      | WorkerEvent.ioError e =>\n        throwServerError s!\"IO error while processing events for {fw.doc.meta.uri}: {e}\"\n      | WorkerEvent.crashed e =>\n        handleCrash fw.doc.meta.uri #[]\n        mainLoop clientTask\n      | WorkerEvent.terminated =>\n        throwServerError \"Internal server error: got termination event for worker that should have been removed\"\nend MainLoop\n\ndef mkLeanServerCapabilities : ServerCapabilities := {\n  textDocumentSync? := some {\n    openClose         := true\n    change            := TextDocumentSyncKind.incremental\n    willSave          := false\n    willSaveWaitUntil := false\n    save?             := none\n  }\n  -- refine\n  completionProvider? := some {\n    triggerCharacters? := some #[\".\"]\n  }\n  hoverProvider := true\n  declarationProvider := true\n  definitionProvider := true\n  typeDefinitionProvider := true\n  documentHighlightProvider := true\n  documentSymbolProvider := true\n  semanticTokensProvider? := some {\n    legend := {\n      tokenTypes     := SemanticTokenType.names\n      tokenModifiers := #[]\n    }\n    full  := true\n    range := true\n  }\n}\n\ndef initAndRunWatchdogAux : ServerM Unit := do\n  let st \u2190 read\n  try\n    discard $ st.hIn.readLspNotificationAs \"initialized\" InitializedParams\n    let clientTask \u2190 runClientTask\n    mainLoop clientTask\n    let Message.notification \"exit\" none \u2190 st.hIn.readLspMessage\n      | throwServerError \"Expected an exit notification\"\n  catch err =>\n    shutdown\n    throw err\n\ndef initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do\n  let mut workerPath \u2190 IO.appPath\n  if let some path := (\u2190IO.getEnv \"LEAN_SYSROOT\") then\n    workerPath := System.FilePath.mk path / \"bin\" / \"lean\" |>.withExtension System.FilePath.exeExtension\n  if let some path := (\u2190IO.getEnv \"LEAN_WORKER_PATH\") then\n    workerPath := System.FilePath.mk path\n  let fileWorkersRef \u2190 IO.mkRef (RBMap.empty : FileWorkerMap)\n  let i \u2190 maybeTee \"wdIn.txt\" false i\n  let o \u2190 maybeTee \"wdOut.txt\" true o\n  let e \u2190 maybeTee \"wdErr.txt\" true e\n  let initRequest \u2190 i.readLspRequestAs \"initialize\" InitializeParams\n  o.writeLspResponse {\n    id     := initRequest.id\n    result := {\n      capabilities := mkLeanServerCapabilities\n      serverInfo?  := some {\n        name     := \"Lean 4 server\"\n        version? := \"0.0.1\"\n      }\n      : InitializeResult\n    }\n  }\n  ReaderT.run initAndRunWatchdogAux {\n    hIn            := i\n    hOut           := o\n    hLog           := e\n    args           := args\n    fileWorkersRef := fileWorkersRef\n    initParams     := initRequest.param\n    editDelay      := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200\n    workerPath     := workerPath\n    : ServerContext\n  }\n\n@[export lean_server_watchdog_main]\ndef watchdogMain (args : List String) : IO UInt32 := do\n  let i \u2190 IO.getStdin\n  let o \u2190 IO.getStdout\n  let e \u2190 IO.getStderr\n  try\n    initAndRunWatchdog args i o e\n    return 0\n  catch err =>\n    e.putStrLn s!\"Watchdog error: {err}\"\n    return 1\n\nend Lean.Server.Watchdog\n", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Server/Watchdog.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.09401018469323504, "lm_q2_score": 0.013848610622569719, "lm_q1q2_score": 0.001301910442372476}}
{"text": "/-\nCopyright (c) 2020 Sebastian Ullrich. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich\n-/\nimport Lean.KeyedDeclsAttribute\n\nnamespace Lean\nnamespace PrettyPrinter\n\n/- Auxiliary internal exception for backtracking the pretty printer.\n   See `orelse.parenthesizer` for example -/\nbuiltin_initialize backtrackExceptionId : InternalExceptionId \u2190 registerInternalExceptionId `backtrackFormatter\n\nunsafe def runForNodeKind {\u03b1} (attr : KeyedDeclsAttribute \u03b1) (k : SyntaxNodeKind) (interp : ParserDescr \u2192 CoreM \u03b1) : CoreM \u03b1 := do\n  match attr.getValues (\u2190 getEnv) k with\n  | p::_ => pure p\n  | _ =>\n    -- assume `k` is from a `ParserDescr`, in which case we assume it's also the declaration name\n    let info \u2190 getConstInfo k\n    if info.type.isConstOf ``ParserDescr || info.type.isConstOf ``TrailingParserDescr then\n      let d \u2190 evalConst ParserDescr k\n      interp d\n    else\n      throwError \"no declaration of attribute [{attr.defn.name}] found for '{k}'\"\n\nend PrettyPrinter\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/PrettyPrinter/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.057493273955619005, "lm_q2_score": 0.02161533347169331, "lm_q1q2_score": 0.0012427362889301248}}
{"text": "/-\nCopyright (c) 2020 Marc Huisinga. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Marc Huisinga, Wojciech Nawrocki\n-/\nimport Init.System.IO\nimport Init.Data.ByteArray\nimport Lean.Data.RBMap\n\nimport Lean.Util.Paths\n\nimport Lean.Data.FuzzyMatching\nimport Lean.Data.Json\nimport Lean.Data.Lsp\nimport Lean.Server.Utils\nimport Lean.Server.Requests\nimport Lean.Server.References\n\n/-!\nFor general server architecture, see `README.md`. This module implements the watchdog process.\n\n## Watchdog state\n\nMost LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted\nworkers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes\nto the header and thus restart the corresponding worker, freeing its imports.\n\nTODO(WN):\nWe may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker\ncrashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed\n(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,\nusers may be confused about why the server seemingly stopped working for a single file.\n\n## Watchdog <-> worker communication\n\nThe watchdog process and its file worker processes communicate via LSP. If the necessity arises,\nwe might add non-standard commands similarly based on JSON-RPC. Most requests and notifications\nare forwarded to the corresponding file worker process, with the exception of these notifications:\n\n- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to\n                        asynchronously receive LSP packets from the worker (e.g. request responses).\n- textDocument/didChange: Update the local file state so that it can be resent to restarted workers.\n                          Then forward the `didChange` notification.\n- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.\n\nMoreover, we don't implement the full protocol at this level:\n\n- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server\n  capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.\n- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of\n  the file. No additional `didOpen` notifications will be forwarded to the worker process.\n- `$/cancelRequest` notifications are forwarded to all file workers.\n- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.\n  Similarly, they never receive a `didClose` notification.\n\n## Watchdog <-> client communication\n\nThe watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add\nnon-standard extensions in case they're needed, for example to communicate tactic state.\n-/\n\nnamespace Lean.Server.Watchdog\n\nopen IO\nopen Lsp\nopen JsonRpc\nopen System.Uri\n\nsection Utils\n  def workerCfg : Process.StdioConfig := {\n    stdin  := Process.Stdio.piped\n    stdout := Process.Stdio.piped\n    -- We pass workers' stderr through to the editor.\n    stderr := Process.Stdio.inherit\n  }\n\n  /-- Events that worker-specific tasks signal to the main thread. -/\n  inductive WorkerEvent where\n    | terminated\n    | importsChanged\n    | crashed (e : IO.Error)\n    | ioError (e : IO.Error)\n\n  inductive WorkerState where\n    /-- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker\n    and when reading a request reply.\n    In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.\n    Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.\n    Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded\n    to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file\n    worker arrives. -/\n    | crashed (queuedMsgs : Array JsonRpc.Message)\n    | running\n\n  abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare\nend Utils\n\nsection FileWorker\n  structure FileWorker where\n    doc                : DocumentMeta\n    proc               : Process.Child workerCfg\n    commTask           : Task WorkerEvent\n    state              : WorkerState\n    -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state\n    /-- The pending requests map contains all requests\n    that have been received from the LSP client, but were not answered yet.\n    We need them for forwaring cancellation requests to the correct worker as well as cleanly aborting\n    requests on worker crashes. -/\n    pendingRequestsRef : IO.Ref PendingRequestMap\n\n  namespace FileWorker\n\n  def stdin (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdin\n\n  def stdout (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdout\n\n  def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit :=\n    fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id\n\n  def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do\n    let pendingRequests \u2190 fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))\n    for \u27e8id, _\u27e9 in pendingRequests do\n      hError.writeLspResponseError { id := id, code := code, message := msg }\n\n  end FileWorker\nend FileWorker\n\nsection ServerM\n  abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare\n\n  structure ServerContext where\n    hIn            : FS.Stream\n    hOut           : FS.Stream\n    hLog           : FS.Stream\n    /-- Command line arguments. -/\n    args           : List String\n    fileWorkersRef : IO.Ref FileWorkerMap\n    /-- We store these to pass them to workers. -/\n    initParams     : InitializeParams\n    workerPath     : System.FilePath\n    srcSearchPath  : System.SearchPath\n    references     : IO.Ref References\n\n  abbrev ServerM := ReaderT ServerContext IO\n\n  def updateFileWorkers (val : FileWorker) : ServerM Unit := do\n    (\u2190read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.uri val)\n\n  def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) :=\n    return (\u2190 (\u2190read).fileWorkersRef.get).find? uri\n\n  def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do\n    let some fw \u2190 findFileWorker? uri\n      | throwServerError s!\"cannot find open document '{uri}'\"\n    return fw\n\n  def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do\n    let s \u2190 read\n    s.fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)\n    if let some path := fileUriToPath? uri then\n      if let some module \u2190 searchModuleNameOfFileName path s.srcSearchPath then\n        s.references.modify fun refs => refs.removeWorkerRefs module\n\n  def log (msg : String) : ServerM Unit := do\n    let st \u2190 read\n    st.hLog.putStrLn msg\n    st.hLog.flush\n\n  def handleIleanInfoUpdate (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do\n    let s \u2190 read\n    if let some path := fileUriToPath? fw.doc.uri then\n      if let some module \u2190 searchModuleNameOfFileName path s.srcSearchPath then\n        s.references.modify fun refs => refs.updateWorkerRefs module params.version params.references\n\n  def handleIleanInfoFinal (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do\n    let s \u2190 read\n    if let some path := fileUriToPath? fw.doc.uri then\n      if let some module \u2190 searchModuleNameOfFileName path s.srcSearchPath then\n        s.references.modify fun refs => refs.finalizeWorkerRefs module params.version params.references\n\n  /-- Creates a Task which forwards a worker's messages into the output stream until an event\n  which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/\n  private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do\n    let o := (\u2190read).hOut\n    let rec loop : ServerM WorkerEvent := do\n      try\n        let msg \u2190 fw.stdout.readLspMessage\n        -- Re. `o.writeLspMessage msg`:\n        -- Writes to Lean I/O channels are atomic, so these won't trample on each other.\n        match msg with\n          | Message.response id _ => do\n            fw.erasePendingRequest id\n            o.writeLspMessage msg\n          | Message.responseError id _ _ _ => do\n            fw.erasePendingRequest id\n            o.writeLspMessage msg\n          | Message.notification \"$/lean/ileanInfoUpdate\" params =>\n            if let some params := params then\n              if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then\n                handleIleanInfoUpdate fw params\n          | Message.notification \"$/lean/ileanInfoFinal\" params =>\n            if let some params := params then\n              if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then\n                handleIleanInfoFinal fw params\n          | _ => o.writeLspMessage msg\n      catch err =>\n        -- If writeLspMessage from above errors we will block here, but the main task will\n        -- quit eventually anyways if that happens\n        let exitCode \u2190 fw.proc.wait\n        match exitCode with\n        | 0 =>\n          -- Worker was terminated\n          fw.errorPendingRequests o ErrorCode.contentModified\n            (s!\"The file worker for {fw.doc.uri} has been terminated. Either the header has changed,\"\n            ++ \" or the file was closed, or the server is shutting down.\")\n          -- one last message to clear the diagnostics for this file so that stale errors\n          -- do not remain in the editor forever.\n          publishDiagnostics fw.doc #[] o\n          return WorkerEvent.terminated\n        | 2 =>\n          return .importsChanged\n        | _ =>\n          -- Worker crashed\n          fw.errorPendingRequests o (if exitCode = 1 then ErrorCode.workerExited else ErrorCode.workerCrashed)\n            s!\"Server process for {fw.doc.uri} crashed, {if exitCode = 1 then \"see stderr for exception\" else \"likely due to a stack overflow or a bug\"}.\"\n          publishProgressAtPos fw.doc 0 o (kind := LeanFileProgressKind.fatalError)\n          return WorkerEvent.crashed err\n      loop\n    let task \u2190 IO.asTask (loop $ \u2190read) Task.Priority.dedicated\n    return task.map fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  def startFileWorker (m : DocumentMeta) : ServerM Unit := do\n    publishProgressAtPos m 0 (\u2190 read).hOut\n    let st \u2190 read\n    let workerProc \u2190 Process.spawn {\n      toStdioConfig := workerCfg\n      cmd           := st.workerPath.toString\n      args          := #[\"--worker\"] ++ st.args.toArray ++ #[m.uri]\n    }\n    let pendingRequestsRef \u2190 IO.mkRef (RBMap.empty : PendingRequestMap)\n    -- The task will never access itself, so this is fine\n    let fw : FileWorker := {\n      doc                := m\n      proc               := workerProc\n      commTask           := Task.pure WorkerEvent.terminated\n      state              := WorkerState.running\n      pendingRequestsRef := pendingRequestsRef\n    }\n    let commTask \u2190 forwardMessages fw\n    let fw : FileWorker := { fw with commTask := commTask }\n    fw.stdin.writeLspRequest \u27e80, \"initialize\", st.initParams\u27e9\n    fw.stdin.writeLspNotification {\n      method := \"textDocument/didOpen\"\n      param  := {\n        textDocument := {\n          uri        := m.uri\n          languageId := \"lean\"\n          version    := m.version\n          text       := m.text.source\n        } : DidOpenTextDocumentParams\n      }\n    }\n    updateFileWorkers fw\n\n  def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do\n    let fw \u2190 findFileWorker! uri\n    try\n      fw.stdin.writeLspMessage (Message.notification \"exit\" none)\n    catch _ =>\n      /- The file worker must have crashed just when we were about to terminate it!\n        That's fine - just forget about it then.\n        (on didClose we won't need the crashed file worker anymore,\n        when the header changed we'll start a new one right after\n        anyways and when we're shutting down the server\n        it's over either way.) -/\n      return\n    eraseFileWorker uri\n\n  def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do\n    updateFileWorkers { \u2190findFileWorker! uri with state := WorkerState.crashed queuedMsgs }\n\n  /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed\n      and restarts the file worker if the `crashed` flag was already set. Just logs an error if there\n      is no FileWorker at this `uri`.\n      Messages that couldn't be sent can be queued up via the queueFailedMessage flag and\n      will be discharged after the FileWorker is restarted. -/\n  def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :\n      ServerM Unit := do\n    let some fw \u2190 findFileWorker? uri\n      | do\n        (\u2190read).hLog.putStrLn s!\"Cannot send message to unknown document '{uri}':\\n{(toJson msg).compress}\"\n        return\n    match fw.state with\n    | WorkerState.crashed queuedMsgs =>\n      let mut queuedMsgs := queuedMsgs\n      if queueFailedMessage then\n        queuedMsgs := queuedMsgs.push msg\n      if !restartCrashedWorker then\n        return\n      -- restart the crashed FileWorker\n      eraseFileWorker uri\n      startFileWorker fw.doc\n      let newFw \u2190 findFileWorker! uri\n      let mut crashedMsgs := #[]\n      -- try to discharge all queued msgs, tracking the ones that we can't discharge\n      for msg in queuedMsgs do\n        try\n          newFw.stdin.writeLspMessage msg\n        catch _ =>\n          crashedMsgs := crashedMsgs.push msg\n      if \u00ac crashedMsgs.isEmpty then\n        handleCrash uri crashedMsgs\n    | WorkerState.running =>\n      let initialQueuedMsgs :=\n        if queueFailedMessage then\n          #[msg]\n        else\n          #[]\n      try\n        fw.stdin.writeLspMessage msg\n      catch _ =>\n        handleCrash uri initialQueuedMsgs\nend ServerM\n\nsection RequestHandling\n\nopen FuzzyMatching\n\ndef findDefinitions (p : TextDocumentPositionParams) : ServerM <| Array Location := do\n  let mut definitions := #[]\n  if let some path := fileUriToPath? p.textDocument.uri then\n    let srcSearchPath := (\u2190 read).srcSearchPath\n    if let some module \u2190 searchModuleNameOfFileName path srcSearchPath then\n      let references \u2190 (\u2190 read).references.get\n      for ident in references.findAt module p.position do\n        if let some definition \u2190 references.definitionOf? ident srcSearchPath then\n          definitions := definitions.push definition\n  return definitions\n\ndef handleReference (p : ReferenceParams) : ServerM (Array Location) := do\n  let mut result := #[]\n  if let some path := fileUriToPath? p.textDocument.uri then\n    let srcSearchPath := (\u2190 read).srcSearchPath\n    if let some module \u2190 searchModuleNameOfFileName path srcSearchPath then\n      let references \u2190 (\u2190 read).references.get\n      for ident in references.findAt module p.position do\n        let identRefs \u2190 references.referringTo module ident srcSearchPath p.context.includeDeclaration\n        result := result.append identRefs\n  return result\n\ndef handleWorkspaceSymbol (p : WorkspaceSymbolParams) : ServerM (Array SymbolInformation) := do\n  if p.query.isEmpty then\n    return #[]\n  let references \u2190 (\u2190 read).references.get\n  let srcSearchPath := (\u2190 read).srcSearchPath\n  let symbols \u2190 references.definitionsMatching srcSearchPath (maxAmount? := none)\n    fun name =>\n      let name := privateToUserName? name |>.getD name\n      if let some score := fuzzyMatchScoreWithThreshold? p.query name.toString then\n        some (name.toString, score)\n      else\n        none\n  return symbols\n    |>.qsort (fun ((_, s1), _) ((_, s2), _) => s1 > s2)\n    |>.extract 0 100 -- max amount\n    |>.map fun ((name, _), location) =>\n      { name, kind := SymbolKind.constant, location }\n\nend RequestHandling\n\nsection NotificationHandling\n  def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=\n    let doc := p.textDocument\n    /- NOTE(WN): `toFileMap` marks line beginnings as immediately following\n       \"\\n\", which should be enough to handle both LF and CRLF correctly.\n       This is because LSP always refers to characters by (line, column),\n       so if we get the line number correct it shouldn't matter that there\n       is a CR there. -/\n    startFileWorker \u27e8doc.uri, doc.version, doc.text.toFileMap\u27e9\n\n  def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do\n    let doc := p.textDocument\n    let changes := p.contentChanges\n    let fw \u2190 findFileWorker! p.textDocument.uri\n    let oldDoc := fw.doc\n    let newVersion := doc.version?.getD 0\n    if changes.isEmpty then\n      return\n    let newDocText := foldDocumentChanges changes oldDoc.text\n    let newDoc : DocumentMeta := \u27e8doc.uri, newVersion, newDocText\u27e9\n    updateFileWorkers { fw with doc := newDoc }\n    tryWriteMessage doc.uri (Notification.mk \"textDocument/didChange\" p) (restartCrashedWorker := true)\n\n  def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=\n    terminateFileWorker p.textDocument.uri\n\n  def handleDidChangeWatchedFiles (p : DidChangeWatchedFilesParams) : ServerM Unit := do\n    let references := (\u2190 read).references\n    let oleanSearchPath \u2190 Lean.searchPathRef.get\n    let ileans \u2190 oleanSearchPath.findAllWithExt \"ilean\"\n    for change in p.changes do\n      if let some path := fileUriToPath? change.uri then\n      if let FileChangeType.Deleted := change.type then\n        references.modify (fun r => r.removeIlean path)\n      else if ileans.contains path then\n        try\n          let ilean \u2190 Ilean.load path\n          if let FileChangeType.Changed := change.type then\n            references.modify (fun r => r.removeIlean path |>.addIlean path ilean)\n          else\n            references.modify (fun r => r.addIlean path ilean)\n        catch\n          -- ilean vanished, ignore error\n          | .noFileOrDirectory .. => references.modify (\u00b7.removeIlean path)\n          | e => throw e\n\n  def handleCancelRequest (p : CancelParams) : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, fw\u27e9 in fileWorkers do\n      -- Cancelled requests still require a response, so they can't be removed\n      -- from the pending requests map.\n      if (\u2190 fw.pendingRequestsRef.get).contains p.id then\n        tryWriteMessage uri (Notification.mk \"$/cancelRequest\" p) (queueFailedMessage := false)\n\n  def forwardNotification {\u03b1 : Type} [ToJson \u03b1] [FileSource \u03b1] (method : String) (params : \u03b1) : ServerM Unit :=\n    tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true)\nend NotificationHandling\n\nsection MessageHandling\n  def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=\n    match fromJson? params with\n    | Except.ok parsed => pure parsed\n    | Except.error inner => throwServerError s!\"Got param with wrong structure: {params.compress}\\n{inner}\"\n\n  def forwardRequestToWorker (id : RequestID) (method : String) (params : Json) : ServerM Unit := do\n    let uri: DocumentUri \u2190\n      -- This request is handled specially.\n      if method == \"$/lean/rpc/connect\" then\n        let ps \u2190 parseParams Lsp.RpcConnectParams params\n        pure <| fileSource ps\n      else match (\u2190 routeLspRequest method params) with\n      | Except.error e =>\n        (\u2190read).hOut.writeLspResponseError <| e.toLspResponseError id\n        return\n      | Except.ok uri => pure uri\n    let some fw \u2190 findFileWorker? uri\n      /- Clients may send requests to closed files, which we respond to with an error.\n      For example, VSCode sometimes sends requests just after closing a file,\n      and RPC clients may also do so, e.g. due to remaining timers. -/\n      | do\n        (\u2190read).hOut.writeLspResponseError\n          { id      := id\n            /- Some clients (VSCode) also send requests *before* opening a file. We reply\n            with `contentModified` as that does not display a \"request failed\" popup. -/\n            code    := ErrorCode.contentModified\n            message := s!\"Cannot process request to closed file '{uri}'\" }\n        return\n    let r := Request.mk id method params\n    fw.pendingRequestsRef.modify (\u00b7.insert id r)\n    tryWriteMessage uri r\n\n  def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do\n    let handle \u03b1 \u03b2 [FromJson \u03b1] [ToJson \u03b2] (handler : \u03b1 \u2192 ServerM \u03b2) : ServerM Unit := do\n      let hOut := (\u2190 read).hOut\n      try\n        let params \u2190 parseParams \u03b1 params\n        let result \u2190 handler params\n        hOut.writeLspResponse \u27e8id, result\u27e9\n      catch\n        -- TODO Do fancier error handling, like in file worker?\n        | e => hOut.writeLspResponseError {\n          id := id\n          code := ErrorCode.internalError\n          message := s!\"Failed to process request {id}: {e}\"\n        }\n    -- If a definition is in a different, modified file, the ilean data should\n    -- have the correct location while the olean still has outdated info from\n    -- the last compilation. This is easier than catching the client's reply and\n    -- fixing the definition's location afterwards, but it doesn't work for\n    -- go-to-type-definition.\n    if method == \"textDocument/definition\" || method == \"textDocument/declaration\" then\n      let params \u2190 parseParams TextDocumentPositionParams params\n      let definitions \u2190 findDefinitions params\n      if !definitions.isEmpty then\n        (\u2190 read).hOut.writeLspResponse \u27e8id, definitions\u27e9\n        return\n    match method with\n      | \"textDocument/references\" => handle ReferenceParams (Array Location) handleReference\n      | \"workspace/symbol\" => handle WorkspaceSymbolParams (Array SymbolInformation) handleWorkspaceSymbol\n      | _ => forwardRequestToWorker id method params\n\n  def handleNotification (method : String) (params : Json) : ServerM Unit := do\n    let handle := (fun \u03b1 [FromJson \u03b1] (handler : \u03b1 \u2192 ServerM Unit) => parseParams \u03b1 params >>= handler)\n    match method with\n    | \"textDocument/didOpen\"            => handle _ handleDidOpen\n    | \"textDocument/didChange\"          => handle DidChangeTextDocumentParams handleDidChange\n    | \"textDocument/didClose\"           => handle DidCloseTextDocumentParams handleDidClose\n    | \"workspace/didChangeWatchedFiles\" => handle DidChangeWatchedFilesParams handleDidChangeWatchedFiles\n    | \"$/cancelRequest\"                 => handle CancelParams handleCancelRequest\n    | \"$/lean/rpc/connect\"              => handle RpcConnectParams (forwardNotification method)\n    | \"$/lean/rpc/release\"              => handle RpcReleaseParams (forwardNotification method)\n    | \"$/lean/rpc/keepAlive\"            => handle RpcKeepAliveParams (forwardNotification method)\n    | _                                 =>\n      if !\"$/\".isPrefixOf method then  -- implementation-dependent notifications can be safely ignored\n        (\u2190read).hLog.putStrLn s!\"Got unsupported notification: {method}\"\nend MessageHandling\n\nsection MainLoop\n  def shutdown : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, _\u27e9 in fileWorkers do\n      terminateFileWorker uri\n    for \u27e8_, fw\u27e9 in fileWorkers do\n      discard <| IO.wait fw.commTask\n\n  inductive ServerEvent where\n    | workerEvent (fw : FileWorker) (ev : WorkerEvent)\n    | clientMsg (msg : JsonRpc.Message)\n    | clientError (e : IO.Error)\n\n  def runClientTask : ServerM (Task ServerEvent) := do\n    let st \u2190 read\n    let readMsgAction : IO ServerEvent := do\n      /- Runs asynchronously. -/\n      let msg \u2190 st.hIn.readLspMessage\n      pure <| ServerEvent.clientMsg msg\n    let clientTask := (\u2190 IO.asTask readMsgAction).map fun\n      | Except.ok ev   => ev\n      | Except.error e => ServerEvent.clientError e\n    return clientTask\n\n  partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do\n    let st \u2190 read\n    let workers \u2190 st.fileWorkersRef.get\n    let mut workerTasks := #[]\n    for (_, fw) in workers do\n      if let WorkerState.running := fw.state then\n        workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)\n\n    let ev \u2190 IO.waitAny (clientTask :: workerTasks.toList)\n    match ev with\n    | ServerEvent.clientMsg msg =>\n      match msg with\n      | Message.request id \"shutdown\" _ =>\n        shutdown\n        st.hOut.writeLspResponse \u27e8id, Json.null\u27e9\n      | Message.request id method (some params) =>\n        handleRequest id method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | Message.response .. =>\n        -- TODO: handle client responses\n        mainLoop (\u2190runClientTask)\n      | Message.responseError _ _ e .. =>\n        throwServerError s!\"Unhandled response error: {e}\"\n      | Message.notification method (some params) =>\n        handleNotification method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | _ => throwServerError \"Got invalid JSON-RPC message\"\n    | ServerEvent.clientError e => throw e\n    | ServerEvent.workerEvent fw ev =>\n      match ev with\n      | WorkerEvent.ioError e =>\n        throwServerError s!\"IO error while processing events for {fw.doc.uri}: {e}\"\n      | WorkerEvent.crashed _ =>\n        handleCrash fw.doc.uri #[]\n        mainLoop clientTask\n      | WorkerEvent.terminated =>\n        throwServerError \"Internal server error: got termination event for worker that should have been removed\"\n      | .importsChanged =>\n        startFileWorker fw.doc\n        mainLoop clientTask\nend MainLoop\n\ndef mkLeanServerCapabilities : ServerCapabilities := {\n  textDocumentSync? := some {\n    openClose         := true\n    change            := TextDocumentSyncKind.incremental\n    willSave          := false\n    willSaveWaitUntil := false\n    save?             := none\n  }\n  -- refine\n  completionProvider? := some {\n    triggerCharacters? := some #[\".\"]\n  }\n  hoverProvider := true\n  declarationProvider := true\n  definitionProvider := true\n  typeDefinitionProvider := true\n  referencesProvider := true\n  workspaceSymbolProvider := true\n  documentHighlightProvider := true\n  documentSymbolProvider := true\n  foldingRangeProvider := true\n  semanticTokensProvider? := some {\n    legend := {\n      tokenTypes     := SemanticTokenType.names\n      tokenModifiers := SemanticTokenModifier.names\n    }\n    full  := true\n    range := true\n  }\n  codeActionProvider? := some {\n    resolveProvider? := true,\n    codeActionKinds? := some #[\"quickfix\", \"refactor\"]\n  }\n}\n\ndef initAndRunWatchdogAux : ServerM Unit := do\n  let st \u2190 read\n  try\n    discard $ st.hIn.readLspNotificationAs \"initialized\" InitializedParams\n    let clientTask \u2190 runClientTask\n    mainLoop clientTask\n  catch err =>\n    shutdown\n    throw err\n  /- NOTE(WN): It looks like instead of sending the `exit` notification,\n  VSCode just closes the stream. In that case, pretend we got an `exit`. -/\n  let Message.notification \"exit\" none \u2190\n    try st.hIn.readLspMessage\n    catch _ => pure (Message.notification \"exit\" none)\n    | throwServerError \"Got `shutdown` request, expected an `exit` notification\"\n\ndef findWorkerPath : IO System.FilePath := do\n  let mut workerPath \u2190 IO.appPath\n  if let some path := (\u2190IO.getEnv \"LEAN_SYSROOT\") then\n    workerPath := System.FilePath.mk path / \"bin\" / \"lean\" |>.withExtension System.FilePath.exeExtension\n  if let some path := (\u2190IO.getEnv \"LEAN_WORKER_PATH\") then\n    workerPath := System.FilePath.mk path\n  return workerPath\n\ndef loadReferences : IO References := do\n  let oleanSearchPath \u2190 Lean.searchPathRef.get\n  let mut refs := References.empty\n  for path in \u2190 oleanSearchPath.findAllWithExt \"ilean\" do\n    try\n      refs := refs.addIlean path (\u2190 Ilean.load path)\n    catch _ =>\n      -- could be a race with the build system, for example\n      -- ilean load errors should not be fatal, but we *should* log them\n      -- when we add logging to the server\n      pure ()\n  return refs\n\ndef initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do\n  let workerPath \u2190 findWorkerPath\n  let srcSearchPath \u2190 initSrcSearchPath (\u2190 getBuildDir)\n  let references \u2190 IO.mkRef (\u2190 loadReferences)\n  let fileWorkersRef \u2190 IO.mkRef (RBMap.empty : FileWorkerMap)\n  let i \u2190 maybeTee \"wdIn.txt\" false i\n  let o \u2190 maybeTee \"wdOut.txt\" true o\n  let e \u2190 maybeTee \"wdErr.txt\" true e\n  let initRequest \u2190 i.readLspRequestAs \"initialize\" InitializeParams\n  o.writeLspResponse {\n    id     := initRequest.id\n    result := {\n      capabilities := mkLeanServerCapabilities\n      serverInfo?  := some {\n        name     := \"Lean 4 Server\"\n        version? := \"0.1.2\"\n      }\n      : InitializeResult\n    }\n  }\n  o.writeLspRequest {\n    id := RequestID.str \"register_ilean_watcher\"\n    method := \"client/registerCapability\"\n    param := some {\n      registrations := #[ {\n        id := \"ilean_watcher\"\n        method := \"workspace/didChangeWatchedFiles\"\n        registerOptions := some <| toJson {\n          watchers := #[ { globPattern := \"**/*.ilean\" } ]\n        : DidChangeWatchedFilesRegistrationOptions }\n      } ]\n    : RegistrationParams }\n  }\n  ReaderT.run initAndRunWatchdogAux {\n    hIn            := i\n    hOut           := o\n    hLog           := e\n    args           := args\n    fileWorkersRef := fileWorkersRef\n    initParams     := initRequest.param\n    workerPath\n    srcSearchPath\n    references\n    : ServerContext\n  }\n\n@[export lean_server_watchdog_main]\ndef watchdogMain (args : List String) : IO UInt32 := do\n  let i \u2190 IO.getStdin\n  let o \u2190 IO.getStdout\n  let e \u2190 IO.getStderr\n  try\n    initAndRunWatchdog args i o e\n    return 0\n  catch err =>\n    e.putStrLn s!\"Watchdog error: {err}\"\n    return 1\n\nend Lean.Server.Watchdog\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/Server/Watchdog.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.08151975820614656, "lm_q2_score": 0.013636836233489566, "lm_q1q2_score": 0.0011116715924508877}}
{"text": "import system.io\n\nmeta def demo : tactic unit := do\n  tactic.trace \"running\",\n\n  tactic.unsafe_run_io $ do {\n    h \u2190 io.mk_file_handle \"test2.dat\" io.mode.read ff,\n    c \u2190 io.fs.read h (24000 * 1024),\n    c \u2190 io.fs.read h (24000 * 1024),\n    io.print_ln c.size\n  },\n\n  tactic.trace \"done\"\n\nexample : true := begin\ndemo,\n\ntrivial\nend\n\n", "meta": {"author": "khoek", "repo": "leandemo-for-sebastian", "sha": "4842276a5a2565f5362137d9f8d855d710fc1261", "save_path": "github-repos/lean/khoek-leandemo-for-sebastian", "path": "github-repos/lean/khoek-leandemo-for-sebastian/leandemo-for-sebastian-4842276a5a2565f5362137d9f8d855d710fc1261/test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.061875985723642724, "lm_q2_score": 0.016657039154967256, "lm_q1q2_score": 0.0010306707169509119}}
{"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.Util.Path\nimport Lean.Data.LOption\nimport Alloy.C.Server.Clangd\nimport Alloy.Util.Server.Worker\n\n/-!\n# C Language Server Worker\n\nThe language server can be in one of three states:\n* `none`: Failed to start and is therefore unsupported\n* `some`: Initialized and is running\n* `undef`: Not yet started, waiting for the first `getLs?` to attempt start\n\nWe use the limbo state of `undef` to ensure we do not try to start the\nlanguage server when unnecessary (e.g., during compilation, where elaboration\nis non-interactive).\n-/\n\nopen Lean\n\nnamespace Alloy.C\n\ninitialize serverMux : IO.Mutex (LOption LsWorker) \u2190 IO.Mutex.new .undef\n\ndef initLs? : BaseIO (Option LsWorker) :=\n  let act := some <$> do\n    /- NOTE: We follow Lean's example and do not limit completion results. -/\n    let args := #[\"--log=error\", \"--limit-results=0\", \"--header-insertion=never\"]\n    LsWorker.init \"clangd\" args {\n      capabilities := {\n        textDocument? := some {\n          hover? := some {\n            contentFormat? := some #[.markdown, .plaintext]\n          },\n          declaration? := some {\n            linkSupport? := true\n          }\n          completion? := some {\n            completionItem? := some {\n              documentationFormat? := some #[.markdown, .plaintext]\n              insertReplaceSupport? := true\n            }\n            completionItemKind? := some {\n              valueSet? := some #[\n                .text, .method, .function, .constructor, .field, .variable,\n                .class,  .interface, .module, .property, .unit, .value, .enum,\n                .keyword, .snippet,  .color, .file, .reference, .folder, .enumMember,\n                .constant, .struct, .event,  .operator, .typeParameter\n              ]\n            }\n          }\n        }\n      }\n      initializationOptions? := some <| toJson (\u03b1 := Clangd.InitializationOptions) {\n        -- Add Lean's include directory to `clangd`'s include path\n        fallbackFlags? := some #[\"-I\", (\u2190 Lean.getBuildDir) / \"include\" |>.toString]\n        clangdFileStatus? := true\n      }\n    }\n  act.catchExceptions fun e => do\n    IO.eprintln s!\"Failed to initialize Alloy C language server: {e}\"\n      |>.catchExceptions (fun _ => pure ())\n    return none\n\ndef getLs? : BaseIO (Option LsWorker) :=\n  serverMux.atomically fun ref => ref.get >>= fun\n    | .none => return none\n    | .some ls => return some ls\n    | .undef => do\n      let ls? \u2190 initLs?\n      ref.set ls?.toLOption\n      return ls?\n", "meta": {"author": "tydeu", "repo": "lean4-alloy", "sha": "334407dc09c10c84549242dc73f9d364886267d1", "save_path": "github-repos/lean/tydeu-lean4-alloy", "path": "github-repos/lean/tydeu-lean4-alloy/lean4-alloy-334407dc09c10c84549242dc73f9d364886267d1/Alloy/C/Server/Worker.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04742587317756678, "lm_q2_score": 0.021615331974819175, "lm_q1q2_score": 0.0010251259929287783}}
{"text": "/-\nCopyright (c) 2020 Marc Huisinga. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Marc Huisinga, Wojciech Nawrocki\n-/\nimport Init.System.IO\nimport Init.Data.ByteArray\nimport Std.Data.RBMap\n\nimport Lean.Elab.Import\nimport Lean.Util.Paths\n\nimport Lean.Data.Json\nimport Lean.Data.Lsp\nimport Lean.Server.Utils\nimport Lean.Server.Requests\nimport Lean.Server.References\n\n/-!\nFor general server architecture, see `README.md`. This module implements the watchdog process.\n\n## Watchdog state\n\nMost LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted\nworkers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes\nto the header and thus restart the corresponding worker, freeing its imports.\n\nTODO(WN):\nWe may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker\ncrashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed\n(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,\nusers may be confused about why the server seemingly stopped working for a single file.\n\n## Watchdog <-> worker communication\n\nThe watchdog process and its file worker processes communicate via LSP. If the necessity arises,\nwe might add non-standard commands similarly based on JSON-RPC. Most requests and notifications\nare forwarded to the corresponding file worker process, with the exception of these notifications:\n\n- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to\n                        asynchronously receive LSP packets from the worker (e.g. request responses).\n- textDocument/didChange: Update the local file state. If the header was mutated,\n                          signal a shutdown to the file worker by closing the I/O channels.\n                          Then restart the file worker. Otherwise, forward the `didChange` notification.\n- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.\n\nMoreover, we don't implement the full protocol at this level:\n\n- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server\n  capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.\n- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of\n  the file. No additional `didOpen` notifications will be forwarded to the worker process.\n- `$/cancelRequest` notifications are forwarded to all file workers.\n- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.\n  Similarly, they never receive a `didClose` notification.\n\n## Watchdog <-> client communication\n\nThe watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add\nnon-standard extensions in case they're needed, for example to communicate tactic state.\n-/\n\nnamespace Lean.Server.Watchdog\n\nopen IO\nopen Std (RBMap RBMap.empty)\nopen Lsp\nopen JsonRpc\n\nsection Utils\n  structure OpenDocument where\n    meta      : DocumentMeta\n    headerAst : Syntax\n\n  def workerCfg : Process.StdioConfig := {\n    stdin  := Process.Stdio.piped\n    stdout := Process.Stdio.piped\n    -- We pass workers' stderr through to the editor.\n    stderr := Process.Stdio.inherit\n  }\n\n  /-- Events that worker-specific tasks signal to the main thread. -/\n  inductive WorkerEvent where\n    /- A synthetic event signalling that the grouped edits should be processed. -/\n    | processGroupedEdits\n    | terminated\n    | crashed (e : IO.Error)\n    | ioError (e : IO.Error)\n\n  inductive WorkerState where\n    /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker\n       and when reading a request reply.\n       In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.\n       Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.\n       Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded\n       to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file\n       worker arrives. -/\n    | crashed (queuedMsgs : Array JsonRpc.Message)\n    | running\n\n  abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare\n\n  private def parseHeaderAst (input : String) : IO Syntax := do\n    let inputCtx   := Parser.mkInputContext input \"<input>\"\n    let (stx, _, _) \u2190 Parser.parseHeader inputCtx\n    return stx\nend Utils\n\nsection FileWorker\n  /-- A group of edits which will be processed at a future instant. -/\n  structure GroupedEdits where\n    /-- When to process the edits. -/\n    applyTime  : Nat\n    params     : DidChangeTextDocumentParams\n    /-- Signals when `applyTime` has been reached. -/\n    signalTask : Task WorkerEvent\n    /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/\n    queuedMsgs : Array JsonRpc.Message\n\n  structure FileWorker where\n    doc                : OpenDocument\n    proc               : Process.Child workerCfg\n    commTask           : Task WorkerEvent\n    state              : WorkerState\n    -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state\n    /-- The pending requests map contains all requests\n    that have been received from the LSP client, but were not answered yet.\n    This includes the queued messages in the grouped edits. -/\n    pendingRequestsRef : IO.Ref PendingRequestMap\n    groupedEditsRef    : IO.Ref (Option GroupedEdits)\n\n  namespace FileWorker\n\n  def stdin (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdin\n\n  def stdout (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdout\n\n  def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit :=\n    fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id\n\n  def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do\n    let pendingRequests \u2190 fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))\n    for \u27e8id, _\u27e9 in pendingRequests do\n      hError.writeLspResponseError { id := id, code := code, message := msg }\n\n  partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do\n    -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification\n    let rec loopAction : IO WorkerEvent := do\n      let now \u2190 monoMsNow\n      let some ge \u2190 fw.groupedEditsRef.get\n        | throwServerError \"Internal error: empty grouped edits reference in signal task\"\n      if ge.applyTime \u2264 now then\n        return WorkerEvent.processGroupedEdits\n      else\n        IO.sleep <| UInt32.ofNat <| ge.applyTime - now\n        loopAction\n\n    let t \u2190 IO.asTask loopAction\n    return t.map fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  end FileWorker\nend FileWorker\n\nsection ServerM\n  abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare\n\n  structure ServerContext where\n    hIn            : FS.Stream\n    hOut           : FS.Stream\n    hLog           : FS.Stream\n    /-- Command line arguments. -/\n    args           : List String\n    fileWorkersRef : IO.Ref FileWorkerMap\n    /-- We store these to pass them to workers. -/\n    initParams     : InitializeParams\n    editDelay      : Nat\n    workerPath     : System.FilePath\n    srcSearchPath  : System.SearchPath\n    references     : IO.Ref References\n\n  abbrev ServerM := ReaderT ServerContext IO\n\n  def updateFileWorkers (val : FileWorker) : ServerM Unit := do\n    (\u2190read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val)\n\n  def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) :=\n    return (\u2190 (\u2190read).fileWorkersRef.get).find? uri\n\n  def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do\n    let some fw \u2190 findFileWorker? uri\n      | throwServerError s!\"cannot find open document '{uri}'\"\n    return fw\n\n  def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do\n    let s \u2190 read\n    s.fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)\n    if let some path := uri.toPath? then\n      if let some module \u2190 searchModuleNameOfFileName path s.srcSearchPath then\n        s.references.modify fun refs => refs.removeWorkerRefs module\n\n  def log (msg : String) : ServerM Unit := do\n    let st \u2190 read\n    st.hLog.putStrLn msg\n    st.hLog.flush\n\n  def handleIleanInfoUpdate (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do\n    let s \u2190 read\n    if let some path := fw.doc.meta.uri.toPath? then\n      if let some module \u2190 searchModuleNameOfFileName path s.srcSearchPath then\n        s.references.modify fun refs => refs.updateWorkerRefs module params.version params.references\n\n  def handleIleanInfoFinal (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do\n    let s \u2190 read\n    if let some path := fw.doc.meta.uri.toPath? then\n      if let some module \u2190 searchModuleNameOfFileName path s.srcSearchPath then\n        s.references.modify fun refs => refs.finalizeWorkerRefs module params.version params.references\n\n  /-- Creates a Task which forwards a worker's messages into the output stream until an event\n  which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/\n  private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do\n    let o := (\u2190read).hOut\n    let rec loop : ServerM WorkerEvent := do\n      try\n        let msg \u2190 fw.stdout.readLspMessage\n        -- Re. `o.writeLspMessage msg`:\n        -- Writes to Lean I/O channels are atomic, so these won't trample on each other.\n        match msg with\n          | Message.response id _ => do\n            fw.erasePendingRequest id\n            o.writeLspMessage msg\n          | Message.responseError id _ _ _ => do\n            fw.erasePendingRequest id\n            o.writeLspMessage msg\n          | Message.notification \"$/lean/ileanInfoUpdate\" params =>\n            if let some params := params then\n              if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then\n                handleIleanInfoUpdate fw params\n          | Message.notification \"$/lean/ileanInfoFinal\" params =>\n            if let some params := params then\n              if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then\n                handleIleanInfoFinal fw params\n          | _ => o.writeLspMessage msg\n      catch err =>\n        -- If writeLspMessage from above errors we will block here, but the main task will\n        -- quit eventually anyways if that happens\n        let exitCode \u2190 fw.proc.wait\n        if exitCode = 0 then\n          -- Worker was terminated\n          fw.errorPendingRequests o ErrorCode.contentModified\n            (\"The file worker has been terminated. Either the header has changed,\"\n            ++ \" or the file was closed, or the server is shutting down.\")\n          return WorkerEvent.terminated\n        else\n          -- Worker crashed\n          fw.errorPendingRequests o ErrorCode.internalError\n            s!\"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then \"see stderr for exception\" else \"likely due to a stack overflow in user code\"}.\"\n          return WorkerEvent.crashed err\n      loop\n    let task \u2190 IO.asTask (loop $ \u2190read) Task.Priority.dedicated\n    return task.map fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  def startFileWorker (m : DocumentMeta) : ServerM Unit := do\n    publishProgressAtPos m 0 (\u2190 read).hOut\n    let st \u2190 read\n    let headerAst \u2190 parseHeaderAst m.text.source\n    let workerProc \u2190 Process.spawn {\n      toStdioConfig := workerCfg\n      cmd           := st.workerPath.toString\n      args          := #[\"--worker\"] ++ st.args.toArray ++ #[m.uri]\n    }\n    let pendingRequestsRef \u2190 IO.mkRef (RBMap.empty : PendingRequestMap)\n    -- The task will never access itself, so this is fine\n    let fw : FileWorker := {\n      doc                := \u27e8m, headerAst\u27e9\n      proc               := workerProc\n      commTask           := Task.pure WorkerEvent.terminated\n      state              := WorkerState.running\n      pendingRequestsRef := pendingRequestsRef\n      groupedEditsRef    := \u2190 IO.mkRef none\n    }\n    let commTask \u2190 forwardMessages fw\n    let fw : FileWorker := { fw with commTask := commTask }\n    fw.stdin.writeLspRequest \u27e80, \"initialize\", st.initParams\u27e9\n    fw.stdin.writeLspNotification {\n      method := \"textDocument/didOpen\"\n      param  := {\n        textDocument := {\n          uri        := m.uri\n          languageId := \"lean\"\n          version    := m.version\n          text       := m.text.source\n        } : DidOpenTextDocumentParams\n      }\n    }\n    updateFileWorkers fw\n\n  def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do\n    let fw \u2190 findFileWorker! uri\n    try\n      fw.stdin.writeLspMessage (Message.notification \"exit\" none)\n    catch _ =>\n      /- The file worker must have crashed just when we were about to terminate it!\n        That's fine - just forget about it then.\n        (on didClose we won't need the crashed file worker anymore,\n        when the header changed we'll start a new one right after\n        anyways and when we're shutting down the server\n        it's over either way.) -/\n      return\n    eraseFileWorker uri\n\n  def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do\n    updateFileWorkers { \u2190findFileWorker! uri with state := WorkerState.crashed queuedMsgs }\n\n  /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed\n      and restarts the file worker if the `crashed` flag was already set. Just logs an error if there\n      is no FileWorker at this `uri`.\n      Messages that couldn't be sent can be queued up via the queueFailedMessage flag and\n      will be discharged after the FileWorker is restarted. -/\n  def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :\n      ServerM Unit := do\n    let some fw \u2190 findFileWorker? uri\n      | do\n        (\u2190read).hLog.putStrLn s!\"Cannot send message to unknown document '{uri}':\\n{(toJson msg).compress}\"\n        return\n    let pendingEdit \u2190 fw.groupedEditsRef.modifyGet fun\n      | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg })\n      | none    => (false, none)\n    if pendingEdit then\n      return\n    match fw.state with\n    | WorkerState.crashed queuedMsgs =>\n      let mut queuedMsgs := queuedMsgs\n      if queueFailedMessage then\n        queuedMsgs := queuedMsgs.push msg\n      if !restartCrashedWorker then\n        return\n      -- restart the crashed FileWorker\n      eraseFileWorker uri\n      startFileWorker fw.doc.meta\n      let newFw \u2190 findFileWorker! uri\n      let mut crashedMsgs := #[]\n      -- try to discharge all queued msgs, tracking the ones that we can't discharge\n      for msg in queuedMsgs do\n        try\n          newFw.stdin.writeLspMessage msg\n        catch _ =>\n          crashedMsgs := crashedMsgs.push msg\n      if \u00ac crashedMsgs.isEmpty then\n        handleCrash uri crashedMsgs\n    | WorkerState.running =>\n      let initialQueuedMsgs :=\n        if queueFailedMessage then\n          #[msg]\n        else\n          #[]\n      try\n        fw.stdin.writeLspMessage msg\n      catch _ =>\n        handleCrash uri initialQueuedMsgs\nend ServerM\n\nsection RequestHandling\n\ndef findDefinitions (p : TextDocumentPositionParams) : ServerM <| Array Location := do\n  let mut definitions := #[]\n  if let some path := p.textDocument.uri.toPath? then\n    let srcSearchPath := (\u2190 read).srcSearchPath\n    if let some module \u2190 searchModuleNameOfFileName path srcSearchPath then\n      let references \u2190 (\u2190 read).references.get\n      for ident in references.findAt module p.position do\n        if let some definition \u2190 references.definitionOf? ident srcSearchPath then\n          definitions := definitions.push definition\n  return definitions\n\ndef handleReference (p : ReferenceParams) : ServerM (Array Location) := do\n  let mut result := #[]\n  if let some path := p.textDocument.uri.toPath? then\n    let srcSearchPath := (\u2190 read).srcSearchPath\n    if let some module \u2190 searchModuleNameOfFileName path srcSearchPath then\n      let references \u2190 (\u2190 read).references.get\n      for ident in references.findAt module p.position do\n        let identRefs \u2190 references.referringTo ident srcSearchPath p.context.includeDeclaration\n        result := result.append identRefs\n  return result\n\n-- TODO Better matching https://github.com/leanprover/lean4/issues/960\ndef handleWorkspaceSymbol (p : WorkspaceSymbolParams) : ServerM (Array SymbolInformation) := do\n  let references \u2190 (\u2190 read).references.get\n  let srcSearchPath := (\u2190 read).srcSearchPath\n  let symbols \u2190 references.definitionsMatching srcSearchPath (maxAmount? := some 100)\n    fun name =>\n      let name := privateToUserName? name |>.getD name\n      if containsCaseInsensitive p.query name.toString then\n        some name.toString\n      else\n        none\n  -- TODO Sort symbols by some useful metric?\n  return symbols.map fun (name, location) =>\n    { name, kind := SymbolKind.constant, location }\nwhere\n  containsCaseInsensitive (value : String) : String \u2192 Bool :=\n    if value.any (\u00b7.isUpper) then\n      containsInOrder value\n    else\n      -- ignore case if query is all lower-case\n      let value := value.toLower\n      fun target => containsInOrder value target.toLower\n\n  containsInOrder (value : String) (target : String) : Bool := Id.run do\n    if value.length == 0 then\n      return true\n    let mut valueIt := value.mkIterator\n    let mut targetIt := target.mkIterator\n    for _ in [:target.bsize] do\n      if valueIt.curr == targetIt.curr then\n        valueIt := valueIt.next\n        if !valueIt.hasNext then\n          return true\n      targetIt := targetIt.next\n    return false\n\nend RequestHandling\n\nsection NotificationHandling\n  def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=\n    let doc := p.textDocument\n    /- NOTE(WN): `toFileMap` marks line beginnings as immediately following\n       \"\\n\", which should be enough to handle both LF and CRLF correctly.\n       This is because LSP always refers to characters by (line, column),\n       so if we get the line number correct it shouldn't matter that there\n       is a CR there. -/\n    startFileWorker \u27e8doc.uri, doc.version, doc.text.toFileMap\u27e9\n\n  def handleEdits (fw : FileWorker) : ServerM Unit := do\n    let some ge \u2190 fw.groupedEditsRef.modifyGet (\u00b7, none)\n      | throwServerError \"Internal error: empty grouped edits reference\"\n    let doc := ge.params.textDocument\n    let changes := ge.params.contentChanges\n    let oldDoc := fw.doc\n    let some newVersion \u2190 pure doc.version?\n      | throwServerError \"Expected version number\"\n    if newVersion <= oldDoc.meta.version then\n      throwServerError \"Got outdated version number\"\n    if changes.isEmpty then\n      return\n    let newDocText := foldDocumentChanges changes oldDoc.meta.text\n    let newMeta : DocumentMeta := \u27e8doc.uri, newVersion, newDocText\u27e9\n    let newHeaderAst \u2190 parseHeaderAst newDocText.source\n    if newHeaderAst != oldDoc.headerAst then\n      terminateFileWorker doc.uri\n      startFileWorker newMeta\n    else\n      let newDoc : OpenDocument := \u27e8newMeta, oldDoc.headerAst\u27e9\n      updateFileWorkers { fw with doc := newDoc }\n      tryWriteMessage doc.uri (Notification.mk \"textDocument/didChange\" ge.params) (restartCrashedWorker := true)\n      for msg in ge.queuedMsgs do\n        tryWriteMessage doc.uri msg\n\n  def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=\n    terminateFileWorker p.textDocument.uri\n\n  def handleDidChangeWatchedFiles (p : DidChangeWatchedFilesParams) : ServerM Unit := do\n    let references := (\u2190 read).references\n    let oleanSearchPath \u2190 Lean.searchPathRef.get\n    let ileans \u2190 oleanSearchPath.findAllWithExt \"ilean\"\n    for change in p.changes do\n      if let some path := change.uri.toPath? then\n      if let FileChangeType.Deleted := change.type then\n        references.modify (fun r => r.removeIlean path)\n      else if ileans.contains path then\n        let ilean \u2190 Ilean.load path\n        if let FileChangeType.Changed := change.type then\n          references.modify (fun r => r.removeIlean path |>.addIlean path ilean)\n        else\n          references.modify (fun r => r.addIlean path ilean)\n\n  def handleCancelRequest (p : CancelParams) : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, fw\u27e9 in fileWorkers do\n      -- Cancelled requests still require a response, so they can't be removed\n      -- from the pending requests map.\n      if (\u2190 fw.pendingRequestsRef.get).contains p.id then\n        tryWriteMessage uri (Notification.mk \"$/cancelRequest\" p) (queueFailedMessage := false)\n\n  def forwardNotification {\u03b1 : Type} [ToJson \u03b1] [FileSource \u03b1] (method : String) (params : \u03b1) : ServerM Unit :=\n    tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true)\nend NotificationHandling\n\nsection MessageHandling\n  def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=\n    match fromJson? params with\n    | Except.ok parsed => pure parsed\n    | Except.error inner => throwServerError s!\"Got param with wrong structure: {params.compress}\\n{inner}\"\n\n  def forwardRequestToWorker (id : RequestID) (method : String) (params : Json) : ServerM Unit := do\n    let uri: DocumentUri \u2190\n      -- This request is handled specially.\n      if method == \"$/lean/rpc/connect\" then\n        let ps \u2190 parseParams Lsp.RpcConnectParams params\n        pure <| fileSource ps\n      else match (\u2190 routeLspRequest method params) with\n      | Except.error e =>\n        (\u2190read).hOut.writeLspResponseError <| e.toLspResponseError id\n        return\n      | Except.ok uri => pure uri\n    let some fw \u2190 findFileWorker? uri\n      /- Clients may send requests to closed files, which we respond to with an error.\n      For example, VSCode sometimes sends requests just after closing a file,\n      and RPC clients may also do so, e.g. due to remaining timers. -/\n      | do\n        (\u2190read).hOut.writeLspResponseError\n          { id      := id\n            /- Some clients (VSCode) also send requests *before* opening a file. We reply\n            with `contentModified` as that does not display a \"request failed\" popup. -/\n            code    := ErrorCode.contentModified\n            message := s!\"Cannot process request to closed file '{uri}'\" }\n        return\n    let r := Request.mk id method params\n    fw.pendingRequestsRef.modify (\u00b7.insert id r)\n    tryWriteMessage uri r\n\n  def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do\n    let handle \u03b1 \u03b2 [FromJson \u03b1] [ToJson \u03b2] (handler : \u03b1 \u2192 ServerM \u03b2) : ServerM Unit := do\n      let hOut := (\u2190 read).hOut\n      try\n        let params \u2190 parseParams \u03b1 params\n        let result \u2190 handler params\n        hOut.writeLspResponse \u27e8id, result\u27e9\n      catch\n        -- TODO Do fancier error handling, like in file worker?\n        | e => hOut.writeLspResponseError {\n          id := id\n          code := ErrorCode.internalError\n          message := s!\"Failed to process request {id}: {e}\"\n        }\n    -- If a definition is in a different, modified file, the ilean data should\n    -- have the correct location while the olean still has outdated info from\n    -- the last compilation. This is easier than catching the client's reply and\n    -- fixing the definition's location afterwards, but it doesn't work for\n    -- go-to-type-definition.\n    if method == \"textDocument/definition\" || method == \"textDocument/declaration\" then\n      let params \u2190 parseParams TextDocumentPositionParams params\n      let definitions \u2190 findDefinitions params\n      if !definitions.isEmpty then\n        (\u2190 read).hOut.writeLspResponse \u27e8id, definitions\u27e9\n        return\n    match method with\n      | \"textDocument/references\" => handle ReferenceParams (Array Location) handleReference\n      | \"workspace/symbol\" => handle WorkspaceSymbolParams (Array SymbolInformation) handleWorkspaceSymbol\n      | _ => forwardRequestToWorker id method params\n\n  def handleNotification (method : String) (params : Json) : ServerM Unit := do\n    let handle := (fun \u03b1 [FromJson \u03b1] (handler : \u03b1 \u2192 ServerM Unit) => parseParams \u03b1 params >>= handler)\n    match method with\n    | \"textDocument/didOpen\"            => handle DidOpenTextDocumentParams handleDidOpen\n    /- NOTE: textDocument/didChange is handled in the main loop. -/\n    | \"textDocument/didClose\"           => handle DidCloseTextDocumentParams handleDidClose\n    | \"workspace/didChangeWatchedFiles\" => handle DidChangeWatchedFilesParams handleDidChangeWatchedFiles\n    | \"$/cancelRequest\"                 => handle CancelParams handleCancelRequest\n    | \"$/lean/rpc/connect\"              => handle RpcConnectParams (forwardNotification method)\n    | \"$/lean/rpc/release\"              => handle RpcReleaseParams (forwardNotification method)\n    | \"$/lean/rpc/keepAlive\"            => handle RpcKeepAliveParams (forwardNotification method)\n    | _                                 =>\n      if !\"$/\".isPrefixOf method then  -- implementation-dependent notifications can be safely ignored\n        (\u2190read).hLog.putStrLn s!\"Got unsupported notification: {method}\"\nend MessageHandling\n\nsection MainLoop\n  def shutdown : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, _\u27e9 in fileWorkers do\n      terminateFileWorker uri\n    for \u27e8_, fw\u27e9 in fileWorkers do\n      discard <| IO.wait fw.commTask\n\n  inductive ServerEvent where\n    | workerEvent (fw : FileWorker) (ev : WorkerEvent)\n    | clientMsg (msg : JsonRpc.Message)\n    | clientError (e : IO.Error)\n\n  def runClientTask : ServerM (Task ServerEvent) := do\n    let st \u2190 read\n    let readMsgAction : IO ServerEvent := do\n      /- Runs asynchronously. -/\n      let msg \u2190 st.hIn.readLspMessage\n      pure <| ServerEvent.clientMsg msg\n    let clientTask := (\u2190 IO.asTask readMsgAction).map fun\n      | Except.ok ev   => ev\n      | Except.error e => ServerEvent.clientError e\n    return clientTask\n\n  partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do\n    let st \u2190 read\n    let workers \u2190 st.fileWorkersRef.get\n    let mut workerTasks := #[]\n    for (_, fw) in workers do\n      if let WorkerState.running := fw.state then\n        workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)\n        if let some ge \u2190 fw.groupedEditsRef.get then\n          workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw)\n\n    let ev \u2190 IO.waitAny (workerTasks.push clientTask |>.toList)\n    match ev with\n    | ServerEvent.clientMsg msg =>\n      match msg with\n      | Message.request id \"shutdown\" _ =>\n        shutdown\n        st.hOut.writeLspResponse \u27e8id, Json.null\u27e9\n      | Message.request id method (some params) =>\n        handleRequest id method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | Message.notification \"textDocument/didChange\" (some params) =>\n        let p \u2190 parseParams DidChangeTextDocumentParams (toJson params)\n        let fw \u2190 findFileWorker! p.textDocument.uri\n        let now \u2190 monoMsNow\n        /- We wait `editDelay`ms since last edit before applying the changes. -/\n        let applyTime := now + st.editDelay\n        let queuedMsgs? \u2190 fw.groupedEditsRef.modifyGet fun\n          | some ge => (some ge.queuedMsgs, some { ge with\n            applyTime := applyTime\n            params.textDocument := p.textDocument\n            params.contentChanges := ge.params.contentChanges ++ p.contentChanges\n            -- drain now-outdated messages and respond with `contentModified` below\n            queuedMsgs := #[] })\n          | none    => (none, some {\n            applyTime := applyTime\n            params := p\n            /- This is overwritten just below. -/\n            signalTask := Task.pure WorkerEvent.processGroupedEdits\n            queuedMsgs := #[] })\n        match queuedMsgs? with\n        | some queuedMsgs =>\n          for msg in queuedMsgs do\n            match msg with\n            | JsonRpc.Message.request id _ _ =>\n              fw.erasePendingRequest id\n              (\u2190 read).hOut.writeLspResponseError {\n                id := id\n                code := ErrorCode.contentModified\n                message := \"File changed.\"\n              }\n            | _ => pure () -- notifications do not need to be cancelled\n        | _ =>\n          let t \u2190 fw.runEditsSignalTask\n          fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } )\n        mainLoop (\u2190runClientTask)\n      | Message.notification method (some params) =>\n        handleNotification method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | Message.response \"register_ilean_watcher\" result =>\n        mainLoop (\u2190runClientTask)\n      | _ => throwServerError \"Got invalid JSON-RPC message\"\n    | ServerEvent.clientError e => throw e\n    | ServerEvent.workerEvent fw ev =>\n      match ev with\n      | WorkerEvent.processGroupedEdits =>\n        handleEdits fw\n        mainLoop clientTask\n      | WorkerEvent.ioError e =>\n        throwServerError s!\"IO error while processing events for {fw.doc.meta.uri}: {e}\"\n      | WorkerEvent.crashed e =>\n        handleCrash fw.doc.meta.uri #[]\n        mainLoop clientTask\n      | WorkerEvent.terminated =>\n        throwServerError \"Internal server error: got termination event for worker that should have been removed\"\nend MainLoop\n\ndef mkLeanServerCapabilities : ServerCapabilities := {\n  textDocumentSync? := some {\n    openClose         := true\n    change            := TextDocumentSyncKind.incremental\n    willSave          := false\n    willSaveWaitUntil := false\n    save?             := none\n  }\n  -- refine\n  completionProvider? := some {\n    triggerCharacters? := some #[\".\"]\n  }\n  hoverProvider := true\n  declarationProvider := true\n  definitionProvider := true\n  typeDefinitionProvider := true\n  referencesProvider := true\n  workspaceSymbolProvider := true\n  documentHighlightProvider := true\n  documentSymbolProvider := true\n  semanticTokensProvider? := some {\n    legend := {\n      tokenTypes     := SemanticTokenType.names\n      tokenModifiers := #[]\n    }\n    full  := true\n    range := true\n  }\n}\n\ndef initAndRunWatchdogAux : ServerM Unit := do\n  let st \u2190 read\n  try\n    discard $ st.hIn.readLspNotificationAs \"initialized\" InitializedParams\n    let clientTask \u2190 runClientTask\n    mainLoop clientTask\n  catch err =>\n    shutdown\n    throw err\n  /- NOTE(WN): It looks like instead of sending the `exit` notification,\n  VSCode just closes the stream. In that case, pretend we got an `exit`. -/\n  let Message.notification \"exit\" none \u2190\n    try st.hIn.readLspMessage\n    catch _ => pure (Message.notification \"exit\" none)\n    | throwServerError \"Got `shutdown` request, expected an `exit` notification\"\n\ndef findWorkerPath : IO System.FilePath := do\n  let mut workerPath \u2190 IO.appPath\n  if let some path := (\u2190IO.getEnv \"LEAN_SYSROOT\") then\n    workerPath := System.FilePath.mk path / \"bin\" / \"lean\" |>.withExtension System.FilePath.exeExtension\n  if let some path := (\u2190IO.getEnv \"LEAN_WORKER_PATH\") then\n    workerPath := System.FilePath.mk path\n  return workerPath\n\ndef loadReferences : IO References := do\n  let oleanSearchPath \u2190 Lean.searchPathRef.get\n  let mut refs := References.empty\n  for path in \u2190 oleanSearchPath.findAllWithExt \"ilean\" do\n    try\n      refs := refs.addIlean path (\u2190 Ilean.load path)\n    catch _ =>\n      -- could be a race with the build system, for example\n      -- ilean load errors should not be fatal, but we *should* log them\n      -- when we add logging to the server\n      pure ()\n  return refs\n\ndef initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do\n  let workerPath \u2190 findWorkerPath\n  let srcSearchPath \u2190 initSrcSearchPath (\u2190 getBuildDir)\n  let references \u2190 IO.mkRef (\u2190 loadReferences)\n  let fileWorkersRef \u2190 IO.mkRef (RBMap.empty : FileWorkerMap)\n  let i \u2190 maybeTee \"wdIn.txt\" false i\n  let o \u2190 maybeTee \"wdOut.txt\" true o\n  let e \u2190 maybeTee \"wdErr.txt\" true e\n  let initRequest \u2190 i.readLspRequestAs \"initialize\" InitializeParams\n  o.writeLspResponse {\n    id     := initRequest.id\n    result := {\n      capabilities := mkLeanServerCapabilities\n      serverInfo?  := some {\n        name     := \"Lean 4 Server\"\n        version? := \"0.1.1\"\n      }\n      : InitializeResult\n    }\n  }\n  o.writeLspRequest {\n    id := RequestID.str \"register_ilean_watcher\"\n    method := \"client/registerCapability\"\n    param := some {\n      registrations := #[ {\n        id := \"ilean_watcher\"\n        method := \"workspace/didChangeWatchedFiles\"\n        registerOptions := some <| toJson {\n          watchers := #[ { globPattern := \"**/*.ilean\" } ]\n        : DidChangeWatchedFilesRegistrationOptions }\n      } ]\n    : RegistrationParams }\n  }\n  ReaderT.run initAndRunWatchdogAux {\n    hIn            := i\n    hOut           := o\n    hLog           := e\n    args           := args\n    fileWorkersRef := fileWorkersRef\n    initParams     := initRequest.param\n    editDelay      := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200\n    workerPath\n    srcSearchPath\n    references\n    : ServerContext\n  }\n\n@[export lean_server_watchdog_main]\ndef watchdogMain (args : List String) : IO UInt32 := do\n  let i \u2190 IO.getStdin\n  let o \u2190 IO.getStdout\n  let e \u2190 IO.getStderr\n  try\n    initAndRunWatchdog args i o e\n    return 0\n  catch err =>\n    e.putStrLn s!\"Watchdog error: {err}\"\n    return 1\n\nend Lean.Server.Watchdog\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/Server/Watchdog.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07696083569602614, "lm_q2_score": 0.013020488366458539, "lm_q1q2_score": 0.0010020676658530354}}
{"text": "/-\nCopyright (c) 2020 Marc Huisinga. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Marc Huisinga, Wojciech Nawrocki\n-/\nimport Init.System.IO\nimport Init.Data.ByteArray\nimport Std.Data.RBMap\n\nimport Lean.Elab.Import\n\nimport Lean.Data.Lsp\nimport Lean.Server.FileSource\nimport Lean.Server.Utils\n\n/-!\nFor general server architecture, see `README.md`. This module implements the watchdog process.\n\n## Watchdog state\n\nMost LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted\nworkers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes\nto the header and thus restart the corresponding worker, freeing its imports.\n\nTODO(WN):\nWe may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker\ncrashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed\n(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,\nusers may be confused about why the server seemingly stopped working for a single file.\n\n## Watchdog <-> worker communication\n\nThe watchdog process and its file worker processes communicate via LSP. If the necessity arises,\nwe might add non-standard commands similarly based on JSON-RPC. Most requests and notifications\nare forwarded to the corresponding file worker process, with the exception of these notifications:\n\n- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to\n                        asynchronously receive LSP packets from the worker (e.g. request responses).\n- textDocument/didChange: Update the local file state. If the header was mutated,\n                          signal a shutdown to the file worker by closing the I/O channels.\n                          Then restart the file worker. Otherwise, forward the `didChange` notification.\n- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.\n\nMoreover, we don't implement the full protocol at this level:\n\n- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server\n  capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.\n- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of\n  the file. No additional `didOpen` notifications will be forwarded to the worker process.\n- `$/cancelRequest` notifications are forwarded to all file workers.\n- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.\n  Similarly, they never receive a `didClose` notification.\n\n## Watchdog <-> client communication\n\nThe watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add\nnon-standard extensions in case they're needed, for example to communicate tactic state.\n-/\n\nnamespace Lean.Server.Watchdog\n\nopen IO\nopen Std (RBMap RBMap.empty)\nopen Lsp\nopen JsonRpc\n\nsection Utils\n  structure OpenDocument where\n    meta      : DocumentMeta\n    headerAst : Syntax\n\n  def workerCfg : Process.StdioConfig := {\n    stdin  := Process.Stdio.piped\n    stdout := Process.Stdio.piped\n    -- We pass workers' stderr through to the editor.\n    stderr := Process.Stdio.inherit\n  }\n\n  /-- Events that worker-specific tasks signal to the main thread. -/\n  inductive WorkerEvent where\n    /- A synthetic event signalling that the grouped edits should be processed. -/\n    | processGroupedEdits\n    | terminated\n    | crashed (e : IO.Error)\n    | ioError (e : IO.Error)\n\n  inductive WorkerState where\n    /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker\n       and when reading a request reply.\n       In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.\n       Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.\n       Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded\n       to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file\n       worker arrives. -/\n    | crashed (queuedMsgs : Array JsonRpc.Message)\n    | running\n\n  abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare\n\n  private def parseHeaderAst (input : String) : IO Syntax := do\n    let inputCtx   := Parser.mkInputContext input \"<input>\"\n    let (stx, _, _) \u2190 Parser.parseHeader inputCtx\n    return stx\nend Utils\n\nsection FileWorker\n  /-- A group of edits which will be processed at a future instant. -/\n  structure GroupedEdits where\n    /-- When to process the edits. -/\n    applyTime  : Nat\n    params     : DidChangeTextDocumentParams\n    /-- Signals when `applyTime` has been reached. -/\n    signalTask : Task WorkerEvent\n    /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/\n    queuedMsgs : Array JsonRpc.Message\n\n  structure FileWorker where\n    doc                : OpenDocument\n    proc               : Process.Child workerCfg\n    commTask           : Task WorkerEvent\n    state              : WorkerState\n    -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state\n    pendingRequestsRef : IO.Ref PendingRequestMap\n    groupedEditsRef    : IO.Ref (Option GroupedEdits)\n\n  namespace FileWorker\n\n  def stdin (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdin\n\n  def stdout (fw : FileWorker) : FS.Stream :=\n    FS.Stream.ofHandle fw.proc.stdout\n\n  def readMessage (fw : FileWorker) : IO JsonRpc.Message := do\n    let msg \u2190 fw.stdout.readLspMessage\n    if let Message.response id _ := msg then\n      fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id)\n    if let Message.responseError id _ _ _ := msg then\n      fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id)\n    return msg\n\n  def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do\n    let pendingRequests \u2190 fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))\n    for \u27e8id, _\u27e9 in pendingRequests do\n      hError.writeLspResponseError { id := id, code := code, message := msg }\n\n  partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do\n    -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification\n    let rec loopAction : IO WorkerEvent := do\n      let now \u2190 monoMsNow\n      let some ge \u2190 fw.groupedEditsRef.get\n        | throwServerError \"Internal error: empty grouped edits reference in signal task\"\n      if ge.applyTime \u2264 now then\n        return WorkerEvent.processGroupedEdits\n      else\n        IO.sleep <| UInt32.ofNat <| ge.applyTime - now\n        loopAction\n\n    let t \u2190 IO.asTask loopAction\n    return t.map fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  end FileWorker\nend FileWorker\n\nsection ServerM\n  abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare\n\n  structure ServerContext where\n    hIn            : FS.Stream\n    hOut           : FS.Stream\n    hLog           : FS.Stream\n    /-- Command line arguments. -/\n    args           : List String\n    fileWorkersRef : IO.Ref FileWorkerMap\n    /-- We store these to pass them to workers. -/\n    initParams     : InitializeParams\n    editDelay      : Nat\n    workerPath     : String\n\n  abbrev ServerM := ReaderT ServerContext IO\n\n  def updateFileWorkers (val : FileWorker) : ServerM Unit := do\n    (\u2190read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val)\n\n  def findFileWorker (uri : DocumentUri) : ServerM FileWorker := do\n    match (\u2190(\u2190read).fileWorkersRef.get).find? uri with\n    | some fw => fw\n    | none    => throwServerError s!\"Got unknown document URI ({uri})\"\n\n  def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do\n    (\u2190read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)\n\n  def log (msg : String) : ServerM Unit := do\n    let st \u2190 read\n    st.hLog.putStrLn msg\n    st.hLog.flush\n\n  /-- Creates a Task which forwards a worker's messages into the output stream until an event\n  which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/\n  private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do\n    let o := (\u2190read).hOut\n    let rec loop : ServerM WorkerEvent := do\n      try\n        let msg \u2190 fw.readMessage\n        -- Writes to Lean I/O channels are atomic, so these won't trample on each other.\n        o.writeLspMessage msg\n      catch err =>\n        -- If writeLspMessage from above errors we will block here, but the main task will\n        -- quit eventually anyways if that happens\n        let exitCode \u2190 fw.proc.wait\n        if exitCode = 0 then\n          -- Worker was terminated\n          fw.errorPendingRequests o ErrorCode.contentModified\n            (\"The file worker has been terminated. Either the header has changed,\"\n            ++ \" or the file was closed, or the server is shutting down.\")\n          return WorkerEvent.terminated\n        else\n          -- Worker crashed\n          fw.errorPendingRequests o ErrorCode.internalError\n            s!\"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then \"see stderr for exception\" else \"likely due to a stack overflow in user code\"}.\"\n          return WorkerEvent.crashed err\n      loop\n    let task \u2190 IO.asTask (loop $ \u2190read) Task.Priority.dedicated\n    task.map $ fun\n      | Except.ok ev   => ev\n      | Except.error e => WorkerEvent.ioError e\n\n  def startFileWorker (m : DocumentMeta) : ServerM Unit := do\n    publishDiagnostics m #[{ range := \u27e8\u27e80, 0\u27e9, \u27e80, 0\u27e9\u27e9, severity? := DiagnosticSeverity.information, message := \"starting new server for file...\" }] (\u2190 read).hOut\n    let st \u2190 read\n    let headerAst \u2190 parseHeaderAst m.text.source\n    let workerProc \u2190 Process.spawn {\n      toStdioConfig := workerCfg\n      cmd           := st.workerPath\n      args          := #[\"--worker\"] ++ st.args.toArray\n    }\n    let pendingRequestsRef \u2190 IO.mkRef (RBMap.empty : PendingRequestMap)\n    -- The task will never access itself, so this is fine\n    let fw : FileWorker := {\n      doc                := \u27e8m, headerAst\u27e9\n      proc               := workerProc\n      commTask           := Task.pure WorkerEvent.terminated\n      state              := WorkerState.running\n      pendingRequestsRef := pendingRequestsRef\n      groupedEditsRef    := \u2190 IO.mkRef none\n    }\n    let commTask \u2190 forwardMessages fw\n    let fw : FileWorker := { fw with commTask := commTask }\n    fw.stdin.writeLspRequest \u27e80, \"initialize\", st.initParams\u27e9\n    fw.stdin.writeLspNotification {\n      method := \"textDocument/didOpen\"\n      param  := {\n        textDocument := {\n          uri        := m.uri\n          languageId := \"lean\"\n          version    := m.version\n          text       := m.text.source\n        } : DidOpenTextDocumentParams\n      }\n    }\n    updateFileWorkers fw\n\n  def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do\n    /- The file worker must have crashed just when we were about to terminate it!\n       That's fine - just forget about it then.\n       (on didClose we won't need the crashed file worker anymore,\n       when the header changed we'll start a new one right after\n       anyways and when we're shutting down the server\n       it's over either way.) -/\n    try (\u2190findFileWorker uri).stdin.writeLspMessage (Message.notification \"exit\" none)\n    catch err => ()\n    eraseFileWorker uri\n\n  def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do\n    updateFileWorkers { \u2190findFileWorker uri with state := WorkerState.crashed queuedMsgs }\n\n  /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed\n      and restarts the file worker if the `crashed` flag was already set.\n      Messages that couldn't be sent can be queued up via the queueFailedMessage flag and\n      will be discharged after the FileWorker is restarted. -/\n  def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :\n      ServerM Unit := do\n    let fw \u2190 findFileWorker uri\n    let pendingEdit \u2190 fw.groupedEditsRef.modifyGet fun\n      | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg })\n      | none    => (false, none)\n    if pendingEdit then\n      return\n    match fw.state with\n    | WorkerState.crashed queuedMsgs =>\n      let mut queuedMsgs := queuedMsgs\n      if queueFailedMessage then\n        queuedMsgs := queuedMsgs.push msg\n      if !restartCrashedWorker then\n        return\n      -- restart the crashed FileWorker\n      eraseFileWorker uri\n      startFileWorker fw.doc.meta\n      let newFw \u2190 findFileWorker uri\n      let mut crashedMsgs := #[]\n      -- try to discharge all queued msgs, tracking the ones that we can't discharge\n      for msg in queuedMsgs do\n        try\n          newFw.stdin.writeLspMessage msg\n        catch _ =>\n          crashedMsgs := crashedMsgs.push msg\n      if \u00ac crashedMsgs.isEmpty then\n        handleCrash uri crashedMsgs\n    | WorkerState.running =>\n      let initialQueuedMsgs :=\n        if queueFailedMessage then\n          #[msg]\n        else\n          #[]\n      try\n        fw.stdin.writeLspMessage msg\n      catch _ =>\n        handleCrash uri initialQueuedMsgs\nend ServerM\n\nsection NotificationHandling\n  def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=\n    let doc := p.textDocument\n    /- NOTE(WN): `toFileMap` marks line beginnings as immediately following\n       \"\\n\", which should be enough to handle both LF and CRLF correctly.\n       This is because LSP always refers to characters by (line, column),\n       so if we get the line number correct it shouldn't matter that there\n       is a CR there. -/\n    startFileWorker \u27e8doc.uri, doc.version, doc.text.toFileMap\u27e9\n\n  def handleEdits (fw : FileWorker) : ServerM Unit := do\n    let some ge \u2190 fw.groupedEditsRef.modifyGet (\u00b7, none)\n      | throwServerError \"Internal error: empty grouped edits reference\"\n    let doc := ge.params.textDocument\n    let changes := ge.params.contentChanges\n    let oldDoc := fw.doc\n    let some newVersion \u2190 pure doc.version?\n      | throwServerError \"Expected version number\"\n    if newVersion <= oldDoc.meta.version then\n      throwServerError \"Got outdated version number\"\n    if changes.isEmpty then\n      return\n    let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text\n    let newMeta : DocumentMeta := \u27e8doc.uri, newVersion, newDocText\u27e9\n    let newHeaderAst \u2190 parseHeaderAst newDocText.source\n    if newHeaderAst != oldDoc.headerAst then\n      terminateFileWorker doc.uri\n      startFileWorker newMeta\n    else\n      let newDoc : OpenDocument := \u27e8newMeta, oldDoc.headerAst\u27e9\n      updateFileWorkers { fw with doc := newDoc }\n      tryWriteMessage doc.uri (Notification.mk \"textDocument/didChange\" ge.params) (restartCrashedWorker := true)\n      for msg in ge.queuedMsgs do\n        tryWriteMessage doc.uri msg\n\n  def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=\n    terminateFileWorker p.textDocument.uri\n\n  def handleCancelRequest (p : CancelParams) : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, fw\u27e9 in fileWorkers do\n      let req? \u2190 fw.pendingRequestsRef.modifyGet (fun pendingRequests =>\n        (pendingRequests.find? p.id, pendingRequests.erase p.id))\n      if let some req := req? then\n        tryWriteMessage uri (Notification.mk \"$/cancelRequest\" p) (queueFailedMessage := false)\nend NotificationHandling\n\nsection MessageHandling\n  def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=\n      match fromJson? params with\n      | some parsed => pure parsed\n      | none        => throwServerError s!\"Got param with wrong structure: {params.compress}\"\n\n  def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do\n    let handle := fun \u03b1 [FromJson \u03b1] [ToJson \u03b1] [FileSource \u03b1] => do\n      let parsedParams \u2190 parseParams \u03b1 params\n      let uri := fileSource parsedParams\n      let fw \u2190 try\n        findFileWorker uri\n      catch _ =>\n        -- VS Code sometimes sends us requests just after closing a file?\n        -- This is permitted by the spec, but seems pointless, and there's not much we can do,\n        -- so we return an error instead.\n        (\u2190read).hOut.writeLspResponseError\n          { id      := id\n            code    := ErrorCode.contentModified\n            message := s!\"Cannot process request to closed file '{uri}'\" }\n        return\n      let r := Request.mk id method params\n      fw.pendingRequestsRef.modify (\u00b7.insert id r)\n      tryWriteMessage uri r\n    match method with\n    | \"textDocument/waitForDiagnostics\"   => handle WaitForDiagnosticsParams\n    | \"textDocument/completion\"           => handle CompletionParams\n    | \"textDocument/hover\"                => handle HoverParams\n    | \"textDocument/declaration\"          => handle DeclarationParams\n    | \"textDocument/definition\"           => handle DefinitionParams\n    | \"textDocument/typeDefinition\"       => handle TypeDefinitionParams\n    | \"textDocument/documentHighlight\"    => handle DocumentHighlightParams\n    | \"textDocument/documentSymbol\"       => handle DocumentSymbolParams\n    | \"textDocument/semanticTokens/range\" => handle SemanticTokensRangeParams\n    | \"textDocument/semanticTokens/full\"  => handle SemanticTokensParams\n    | \"$/lean/plainGoal\"                  => handle PlainGoalParams\n    | _                                   =>\n      (\u2190read).hOut.writeLspResponseError\n        { id      := id\n          code    := ErrorCode.methodNotFound\n          message := s!\"Unsupported request method: {method}\" }\n\n  def handleNotification (method : String) (params : Json) : ServerM Unit := do\n    let handle := (fun \u03b1 [FromJson \u03b1] (handler : \u03b1 \u2192 ServerM Unit) => parseParams \u03b1 params >>= handler)\n    match method with\n    | \"textDocument/didOpen\"   => handle DidOpenTextDocumentParams handleDidOpen\n    /- NOTE: textDocument/didChange is handled in the main loop. -/\n    | \"textDocument/didClose\"  => handle DidCloseTextDocumentParams handleDidClose\n    | \"$/cancelRequest\"        => handle CancelParams handleCancelRequest\n    | _                        =>\n      if !\"$/\".isPrefixOf method then  -- implementation-dependent notifications can be safely ignored\n        (\u2190read).hLog.putStrLn s!\"Got unsupported notification: {method}\"\nend MessageHandling\n\nsection MainLoop\n  def shutdown : ServerM Unit := do\n    let fileWorkers \u2190 (\u2190read).fileWorkersRef.get\n    for \u27e8uri, _\u27e9 in fileWorkers do\n      terminateFileWorker uri\n    for \u27e8_, fw\u27e9 in fileWorkers do\n      discard <| IO.wait fw.commTask\n\n  inductive ServerEvent where\n    | workerEvent (fw : FileWorker) (ev : WorkerEvent)\n    | clientMsg (msg : JsonRpc.Message)\n    | clientError (e : IO.Error)\n\n  def runClientTask : ServerM (Task ServerEvent) := do\n    let st \u2190 read\n    let readMsgAction : IO ServerEvent := do\n      /- Runs asynchronously. -/\n      let msg \u2190 st.hIn.readLspMessage\n      ServerEvent.clientMsg msg\n    let clientTask := (\u2190IO.asTask readMsgAction).map $ fun\n      | Except.ok ev   => ev\n      | Except.error e => ServerEvent.clientError e\n    return clientTask\n\n  partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do\n    let st \u2190 read\n    let workers \u2190 st.fileWorkersRef.get\n    let mut workerTasks := #[]\n    for (_, fw) in workers do\n      if let WorkerState.running := fw.state then\n        workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)\n        if let some ge \u2190 fw.groupedEditsRef.get then\n          workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw)\n\n    let ev \u2190 IO.waitAny (workerTasks.push clientTask |>.toList)\n    match ev with\n    | ServerEvent.clientMsg msg =>\n      match msg with\n      | Message.request id \"shutdown\" _ =>\n        shutdown\n        st.hOut.writeLspResponse \u27e8id, Json.null\u27e9\n      | Message.request id method (some params) =>\n        handleRequest id method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | Message.notification \"textDocument/didChange\" (some params) =>\n        let p \u2190 parseParams DidChangeTextDocumentParams (toJson params)\n        let fw \u2190 findFileWorker p.textDocument.uri\n        let now \u2190 monoMsNow\n        /- We wait `editDelay`ms since last edit before applying the changes. -/\n        let applyTime := now + st.editDelay\n        let pendingEdit \u2190 fw.groupedEditsRef.modifyGet fun\n          | some ge => (true, some { ge with\n            applyTime := applyTime\n            params.textDocument := p.textDocument\n            params.contentChanges := ge.params.contentChanges ++ p.contentChanges\n            -- drain now-outdated messages and respond with `contentModified` below\n            queuedMsgs := #[] })\n          | none    => (false, some {\n            applyTime := applyTime\n            params := p\n            /- This is overwritten just below. -/\n            signalTask := Task.pure WorkerEvent.processGroupedEdits\n            queuedMsgs := #[] })\n        if pendingEdit then\n          fw.errorPendingRequests (\u2190read).hOut ErrorCode.contentModified \"File changed.\"\n        else\n          let t \u2190 fw.runEditsSignalTask\n          fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } )\n        mainLoop (\u2190runClientTask)\n      | Message.notification method (some params) =>\n        handleNotification method (toJson params)\n        mainLoop (\u2190runClientTask)\n      | _ => throwServerError \"Got invalid JSON-RPC message\"\n    | ServerEvent.clientError e => throw e\n    | ServerEvent.workerEvent fw ev =>\n      match ev with\n      | WorkerEvent.processGroupedEdits =>\n        handleEdits fw\n        mainLoop clientTask\n      | WorkerEvent.ioError e =>\n        throwServerError s!\"IO error while processing events for {fw.doc.meta.uri}: {e}\"\n      | WorkerEvent.crashed e =>\n        handleCrash fw.doc.meta.uri #[]\n        mainLoop clientTask\n      | WorkerEvent.terminated =>\n        throwServerError \"Internal server error: got termination event for worker that should have been removed\"\nend MainLoop\n\ndef mkLeanServerCapabilities : ServerCapabilities := {\n  textDocumentSync? := some {\n    openClose         := true\n    change            := TextDocumentSyncKind.incremental\n    willSave          := false\n    willSaveWaitUntil := false\n    save?             := none\n  }\n  -- refine\n  completionProvider? := some {\n    triggerCharacters? := some #[\".\"]\n  }\n  hoverProvider := true\n  declarationProvider := true\n  definitionProvider := true\n  typeDefinitionProvider := true\n  documentHighlightProvider := true\n  documentSymbolProvider := true\n  semanticTokensProvider? := some {\n    legend := {\n      tokenTypes     := SemanticTokenType.names\n      tokenModifiers := #[]\n    }\n    full  := true\n    range := true\n  }\n}\n\ndef initAndRunWatchdogAux : ServerM Unit := do\n  let st \u2190 read\n  try\n    discard $ st.hIn.readLspNotificationAs \"initialized\" InitializedParams\n    let clientTask \u2190 runClientTask\n    mainLoop clientTask\n    let Message.notification \"exit\" none \u2190 st.hIn.readLspMessage\n      | throwServerError \"Expected an exit notification\"\n  catch err =>\n    shutdown\n    throw err\n\ndef initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do\n  let mut workerPath \u2190 IO.appPath\n  if let some path := (\u2190IO.getEnv \"LEAN_SYSROOT\") then\n    workerPath := s!\"{path}/bin/lean{System.FilePath.exeSuffix}\"\n  if let some path := (\u2190IO.getEnv \"LEAN_WORKER_PATH\") then\n    workerPath := path\n  let fileWorkersRef \u2190 IO.mkRef (RBMap.empty : FileWorkerMap)\n  let i \u2190 maybeTee \"wdIn.txt\" false i\n  let o \u2190 maybeTee \"wdOut.txt\" true o\n  let e \u2190 maybeTee \"wdErr.txt\" true e\n  let initRequest \u2190 i.readLspRequestAs \"initialize\" InitializeParams\n  o.writeLspResponse {\n    id     := initRequest.id\n    result := {\n      capabilities := mkLeanServerCapabilities\n      serverInfo?  := some {\n        name     := \"Lean 4 server\"\n        version? := \"0.0.1\"\n      }\n      : InitializeResult\n    }\n  }\n  ReaderT.run initAndRunWatchdogAux {\n    hIn            := i\n    hOut           := o\n    hLog           := e\n    args           := args\n    fileWorkersRef := fileWorkersRef\n    initParams     := initRequest.param\n    editDelay      := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200\n    workerPath     := workerPath\n    : ServerContext\n  }\n\n@[export lean_server_watchdog_main]\ndef watchdogMain (args : List String) : IO UInt32 := do\n  let i \u2190 IO.getStdin\n  let o \u2190 IO.getStdout\n  let e \u2190 IO.getStderr\n  try\n    initAndRunWatchdog args i o e\n    return 0\n  catch err =>\n    e.putStrLn s!\"Watchdog error: {err}\"\n    return 1\n\nend Lean.Server.Watchdog\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/Server/Watchdog.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.07159120736790556, "lm_q2_score": 0.013020492483583527, "lm_q1q2_score": 0.000932152777424484}}
{"text": "/-\nCopyright (c) 2021 Wojciech Nawrocki. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki, Marc Huisinga\n-/\nimport Lean.DeclarationRange\n\nimport Lean.Data.Json\nimport Lean.Data.Lsp\n\nimport Lean.Server.FileSource\nimport Lean.Server.FileWorker.Utils\n\n/-! We maintain a global map of LSP request handlers. This allows user code such as plugins\nto register its own handlers, for example to support ITP functionality such as goal state\nvisualization.\n\nFor details of how to register one, see `registerLspRequestHandler`. -/\n\nnamespace Lean.Server.Requests\n\nstructure RequestError where\n  code    : JsonRpc.ErrorCode\n  message : String\n\nnamespace RequestError\nopen JsonRpc\n\ndef fileChanged : RequestError :=\n  { code := ErrorCode.contentModified\n    message := \"File changed.\" }\n\ndef methodNotFound (method : String) : RequestError :=\n  { code := ErrorCode.methodNotFound\n    message := s!\"No request handler found for '{method}'\" }\n\ninstance : Coe IO.Error RequestError where\n  coe e := { code := ErrorCode.internalError\n             message := toString e }\n\ndef toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=\n  { id := id\n    code := e.code\n    message := e.message }\n\nend RequestError\n\nstructure RequestContext where\n  srcSearchPath : SearchPath\n  docRef        : IO.Ref FileWorker.EditableDocument\n  hLog          : IO.FS.Stream\n\nabbrev RequestTask \u03b1 := Task (Except RequestError \u03b1)\n/-- Workers execute request handlers in this monad. -/\nabbrev RequestM := ReaderT RequestContext <| ExceptT RequestError IO\n\nnamespace RequestM\nopen FileWorker\nopen Snapshots\n\ndef readDoc : RequestM EditableDocument := fun rc =>\n  rc.docRef.get\n\ndef asTask (t : RequestM \u03b1) : RequestM (RequestTask \u03b1) := fun rc => do\n  let t \u2190 IO.asTask <| t rc\n  return t.map fun\n    | Except.error e => throwThe RequestError e\n    | Except.ok v    => v\n\ndef mapTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM \u03b2) : RequestM (RequestTask \u03b2) := fun rc => do\n  let t \u2190 (IO.mapTask \u00b7 t) fun a => f a rc\n  return t.map fun\n    | Except.error e => throwThe RequestError e\n    | Except.ok v    => v\n\ndef bindTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM (RequestTask \u03b2)) : RequestM (RequestTask \u03b2) := fun rc => do\n  let t \u2190 IO.bindTask t fun a => do\n    match (\u2190 f a rc) with\n    | Except.error e => return Task.pure <| Except.ok <| Except.error e\n    | Except.ok t    => return t.map Except.ok\n  return t.map fun\n    | Except.error e => throwThe RequestError e\n    | Except.ok v    => v\n\n/-- Create a task which waits for a snapshot matching `p`, handles various errors,\nand if a matching snapshot was found executes `x` with it. If not found, the task\nexecutes `notFoundX`. -/\ndef withWaitFindSnap (doc : EditableDocument) (p : Snapshot \u2192 Bool)\n  (notFoundX : RequestM \u03b2)\n  (x : Snapshot \u2192 RequestM \u03b2)\n    : RequestM (RequestTask \u03b2) := do\n  let findTask \u2190 doc.cmdSnaps.waitFind? p\n  mapTask findTask fun\n    /- The elaboration task that we're waiting for may be aborted if the file contents change.\n    In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't\n    get bogged down in requests for an old state of the document. -/\n    | Except.error FileWorker.ElabTaskError.aborted =>\n      throwThe RequestError RequestError.fileChanged\n    | Except.error (FileWorker.ElabTaskError.ioError e) =>\n      throwThe IO.Error e\n    | Except.error FileWorker.ElabTaskError.eof => notFoundX\n    | Except.ok none => notFoundX\n    | Except.ok (some snap) => x snap\n\nend RequestM\n\n/- The global request handlers table. -/\nsection HandlerTable\nopen Lsp\n\nprivate structure RequestHandler where\n  fileSource : Json \u2192 Except RequestError Lsp.DocumentUri\n  handle : Json \u2192 RequestM (RequestTask Json)\n\nbuiltin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) \u2190\n  IO.mkRef {}\n\nprivate def parseParams (paramType : Type) [FromJson paramType] (params : Json) : Except RequestError paramType :=\n  fromJson? params |>.mapError fun inner =>\n    { code := JsonRpc.ErrorCode.parseError\n      message := s!\"Cannot parse request params: {params.compress}\\n{inner}\" }\n\n/-- NB: This method may only be called in `initialize`/`builtin_initialize` blocks.\n\nA registration consists of:\n- a type of JSON-parsable request data `paramType`\n- a `FileSource` instance for it so the system knows where to route requests\n- a type of JSON-serializable response data `respType`\n- an actual `handler` which runs in the `RequestM` monad and is expected\n  to produce an asynchronous `RequestTask` which does any waiting/computation\n\nA handler task may be cancelled at any time, so it should check the cancellation token when possible\nto handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client\nas LSP error responses. -/\ndef registerLspRequestHandler (method : String)\n    paramType [FromJson paramType] [FileSource paramType]\n    respType [ToJson respType]\n    (handler : paramType \u2192 RequestM (RequestTask respType)) : IO Unit := do\n  if !(\u2190 IO.initializing) then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': only possible during initialization\"\n  if (\u2190requestHandlers.get).contains method then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': already registered\"\n  let fileSource := fun j =>\n    parseParams paramType j |>.map fun p =>\n      Lsp.fileSource p\n  let handle := fun j => do\n    let params \u2190 parseParams paramType j\n    let t \u2190 handler params\n    t.map <| Except.map ToJson.toJson\n\n  requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }\n\nprivate def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) := do\n  (\u2190 requestHandlers.get).find? method\n\ndef routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => return Except.error <| RequestError.methodNotFound method\n  | some rh => return rh.fileSource params\n\ndef handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => throwThe IO.Error <| IO.userError s!\"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?\"\n  | some rh => rh.handle params\n\nend HandlerTable\nend Lean.Server.Requests", "meta": {"author": "JLimperg", "repo": "lean4-aesop", "sha": "5c4b9a3e05c32f69a4357c3047c274f4b94f9c71", "save_path": "github-repos/lean/JLimperg-lean4-aesop", "path": "github-repos/lean/JLimperg-lean4-aesop/lean4-aesop-5c4b9a3e05c32f69a4357c3047c274f4b94f9c71/stage0/src/Lean/Server/Requests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.04208773031866069, "lm_q2_score": 0.021615333865607576, "lm_q1q2_score": 0.0009097403424835051}}
{"text": "/-\nCopyright (c) 2021 Wojciech Nawrocki. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki, Marc Huisinga\n-/\nimport Lean.DeclarationRange\n\nimport Lean.Data.Json\nimport Lean.Data.Lsp\n\nimport Lean.Server.FileSource\nimport Lean.Server.FileWorker.Utils\n\nimport Lean.Server.Rpc.Basic\n\n/-! We maintain a global map of LSP request handlers. This allows user code such as plugins\nto register its own handlers, for example to support ITP functionality such as goal state\nvisualization.\n\nFor details of how to register one, see `registerLspRequestHandler`. -/\n\nnamespace Lean.Server\n\nstructure RequestError where\n  code    : JsonRpc.ErrorCode\n  message : String\n\nnamespace RequestError\nopen JsonRpc\n\ndef fileChanged : RequestError :=\n  { code := ErrorCode.contentModified\n    message := \"File changed.\" }\n\ndef methodNotFound (method : String) : RequestError :=\n  { code := ErrorCode.methodNotFound\n    message := s!\"No request handler found for '{method}'\" }\n\ninstance : Coe IO.Error RequestError where\n  coe e := { code := ErrorCode.internalError\n             message := toString e }\n\ndef toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=\n  { id := id\n    code := e.code\n    message := e.message }\n\nend RequestError\n\ndef parseRequestParams (paramType : Type) [FromJson paramType] (params : Json)\n    : Except RequestError paramType :=\n  fromJson? params |>.mapError fun inner =>\n    { code := JsonRpc.ErrorCode.parseError\n      message := s!\"Cannot parse request params: {params.compress}\\n{inner}\" }\n\nstructure RequestContext where\n  rpcSessions   : Std.RBMap UInt64 (IO.Ref FileWorker.RpcSession) compare\n  srcSearchPath : SearchPath\n  doc           : FileWorker.EditableDocument\n  hLog          : IO.FS.Stream\n  initParams    : Lsp.InitializeParams\n\nabbrev RequestTask \u03b1 := Task (Except RequestError \u03b1)\n/-- Workers execute request handlers in this monad. -/\nabbrev RequestM := ReaderT RequestContext <| EIO RequestError\n\ninstance : Inhabited (RequestM \u03b1) :=\n  \u27e8throw (\"executing Inhabited instance?!\" : RequestError)\u27e9\n\ninstance : MonadLift IO RequestM where\n  monadLift x := x.toEIO fun e => (e : RequestError)\n\nnamespace RequestM\nopen FileWorker\nopen Snapshots\n\ndef readDoc : RequestM EditableDocument := fun rc =>\n  return rc.doc\n\ndef asTask (t : RequestM \u03b1) : RequestM (RequestTask \u03b1) := fun rc => do\n  let t \u2190 EIO.asTask <| t rc\n  return t.map liftExcept\n\ndef mapTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM \u03b2) : RequestM (RequestTask \u03b2) := fun rc => do\n  let t \u2190 EIO.mapTask (f \u00b7 rc) t\n  return t.map liftExcept\n\ndef bindTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM (RequestTask \u03b2)) : RequestM (RequestTask \u03b2) := fun rc => do\n  EIO.bindTask t (f \u00b7 rc)\n\n/-- Create a task which waits for the first snapshot matching `p`, handles various errors,\nand if a matching snapshot was found executes `x` with it. If not found, the task executes\n`notFoundX`. -/\ndef withWaitFindSnap (doc : EditableDocument) (p : Snapshot \u2192 Bool)\n  (notFoundX : RequestM \u03b2)\n  (x : Snapshot \u2192 RequestM \u03b2)\n    : RequestM (RequestTask \u03b2) := do\n  let findTask \u2190 doc.allSnaps.waitFind? p\n  mapTask findTask fun\n    /- The elaboration task that we're waiting for may be aborted if the file contents change.\n    In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't\n    get bogged down in requests for an old state of the document. -/\n    | Except.error FileWorker.ElabTaskError.aborted =>\n      throwThe RequestError RequestError.fileChanged\n    | Except.error (FileWorker.ElabTaskError.ioError e) =>\n      throw (e : RequestError)\n    | Except.ok none => notFoundX\n    | Except.ok (some snap) => x snap\n\nend RequestM\n\n/- The global request handlers table. -/\nsection HandlerTable\nopen Lsp\n\nstructure RequestHandler where\n  fileSource : Json \u2192 Except RequestError Lsp.DocumentUri\n  handle : Json \u2192 RequestM (RequestTask Json)\n\nbuiltin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) \u2190\n  IO.mkRef {}\n\n/-- NB: This method may only be called in `builtin_initialize` blocks.\n\nA registration consists of:\n- a type of JSON-parsable request data `paramType`\n- a `FileSource` instance for it so the system knows where to route requests\n- a type of JSON-serializable response data `respType`\n- an actual `handler` which runs in the `RequestM` monad and is expected\n  to produce an asynchronous `RequestTask` which does any waiting/computation\n\nA handler task may be cancelled at any time, so it should check the cancellation token when possible\nto handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client\nas LSP error responses. -/\ndef registerLspRequestHandler (method : String)\n    paramType [FromJson paramType] [FileSource paramType]\n    respType [ToJson respType]\n    (handler : paramType \u2192 RequestM (RequestTask respType)) : IO Unit := do\n  if !(\u2190 IO.initializing) then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': only possible during initialization\"\n  if (\u2190 requestHandlers.get).contains method then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': already registered\"\n  let fileSource := fun j =>\n    parseRequestParams paramType j |>.map Lsp.fileSource\n  let handle := fun j => do\n    let params \u2190 liftExcept <| parseRequestParams paramType j\n    let t \u2190 handler params\n    pure <| t.map <| Except.map ToJson.toJson\n\n  requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }\n\ndef lookupLspRequestHandler (method : String) : IO (Option RequestHandler) :=\n  return (\u2190 requestHandlers.get).find? method\n\n/-- NB: This method may only be called in `builtin_initialize` blocks.\n\nRegister another handler to invoke after the last one registered for a method.\nAt least one handler for the method must have already been registered to perform\nchaining.\n\nFor more details on the registration of a handler, see `registerLspRequestHandler`. -/\ndef chainLspRequestHandler (method : String)\n    paramType [FromJson paramType]\n    respType [FromJson respType] [ToJson respType]\n    (handler : paramType \u2192 RequestTask respType \u2192 RequestM (RequestTask respType)) : IO Unit := do\n  if !(\u2190 IO.initializing) then\n    throw <| IO.userError s!\"Failed to chain LSP request handler for '{method}': only possible during initialization\"\n  if let some oldHandler \u2190 lookupLspRequestHandler method then\n    let handle := fun j => do\n      let t \u2190 oldHandler.handle j\n      let t := t.map fun x => x.bind fun j => FromJson.fromJson? j |>.mapError fun e =>\n        IO.userError s!\"Failed to parse original LSP response for `{method}` when chaining: {e}\"\n      let params \u2190 liftExcept <| parseRequestParams paramType j\n      let t \u2190 handler params t\n      pure <| t.map <| Except.map ToJson.toJson\n\n    requestHandlers.modify fun rhs => rhs.insert method {oldHandler with handle}\n  else\n    throw <| IO.userError s!\"Failed to chain LSP request handler for '{method}': no initial handler registered\"\n\ndef routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => return Except.error <| RequestError.methodNotFound method\n  | some rh => return rh.fileSource params\n\ndef handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => throw (s!\"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?\" : RequestError)\n  | some rh => rh.handle params\n\nend HandlerTable\nend Lean.Server\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/Server/Requests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03567855087773052, "lm_q2_score": 0.02333076957245557, "lm_q1q2_score": 0.0008324080492074632}}
{"text": "/-\nCopyright (c) 2021 Wojciech Nawrocki. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthors: Wojciech Nawrocki, Marc Huisinga\n-/\nimport Lean.DeclarationRange\n\nimport Lean.Data.Json\nimport Lean.Data.Lsp\n\nimport Lean.Server.FileSource\nimport Lean.Server.FileWorker.Utils\n\nimport Lean.Server.Rpc.Basic\n\n/-! We maintain a global map of LSP request handlers. This allows user code such as plugins\nto register its own handlers, for example to support ITP functionality such as goal state\nvisualization.\n\nFor details of how to register one, see `registerLspRequestHandler`. -/\n\nnamespace Lean.Server\n\nstructure RequestError where\n  code    : JsonRpc.ErrorCode\n  message : String\n\nnamespace RequestError\nopen JsonRpc\n\ndef fileChanged : RequestError :=\n  { code := ErrorCode.contentModified\n    message := \"File changed.\" }\n\ndef methodNotFound (method : String) : RequestError :=\n  { code := ErrorCode.methodNotFound\n    message := s!\"No request handler found for '{method}'\" }\n\ninstance : Coe IO.Error RequestError where\n  coe e := { code := ErrorCode.internalError\n             message := toString e }\n\ndef toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=\n  { id := id\n    code := e.code\n    message := e.message }\n\nend RequestError\n\ndef parseRequestParams (paramType : Type) [FromJson paramType] (params : Json)\n    : Except RequestError paramType :=\n  fromJson? params |>.mapError fun inner =>\n    { code := JsonRpc.ErrorCode.parseError\n      message := s!\"Cannot parse request params: {params.compress}\\n{inner}\" }\n\nstructure RequestContext where\n  rpcSessions   : Std.RBMap UInt64 (IO.Ref FileWorker.RpcSession) compare\n  srcSearchPath : SearchPath\n  doc           : FileWorker.EditableDocument\n  hLog          : IO.FS.Stream\n\nabbrev RequestTask \u03b1 := Task (Except RequestError \u03b1)\n/-- Workers execute request handlers in this monad. -/\nabbrev RequestM := ReaderT RequestContext <| ExceptT RequestError IO\n\ninstance : Inhabited (RequestM \u03b1) :=\n  \u27e8throwThe IO.Error \"executing Inhabited instance?!\"\u27e9\n\nnamespace RequestM\nopen FileWorker\nopen Snapshots\n\ndef readDoc : RequestM EditableDocument := fun rc =>\n  rc.doc\n\ndef asTask (t : RequestM \u03b1) : RequestM (RequestTask \u03b1) := fun rc => do\n  let t \u2190 IO.asTask <| t rc\n  return t.map fun\n    | Except.error e => throwThe RequestError e\n    | Except.ok v    => v\n\ndef mapTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM \u03b2) : RequestM (RequestTask \u03b2) := fun rc => do\n  let t \u2190 (IO.mapTask \u00b7 t) fun a => f a rc\n  return t.map fun\n    | Except.error e => throwThe RequestError e\n    | Except.ok v    => v\n\ndef bindTask (t : Task \u03b1) (f : \u03b1 \u2192 RequestM (RequestTask \u03b2)) : RequestM (RequestTask \u03b2) := fun rc => do\n  let t \u2190 IO.bindTask t fun a => do\n    match (\u2190 f a rc) with\n    | Except.error e => return Task.pure <| Except.ok <| Except.error e\n    | Except.ok t    => return t.map Except.ok\n  return t.map fun\n    | Except.error e => throwThe RequestError e\n    | Except.ok v    => v\n\n/-- Create a task which waits for a snapshot matching `p`, handles various errors,\nand if a matching snapshot was found executes `x` with it. If not found, the task\nexecutes `notFoundX`. -/\ndef withWaitFindSnap (doc : EditableDocument) (p : Snapshot \u2192 Bool)\n  (notFoundX : RequestM \u03b2)\n  (x : Snapshot \u2192 RequestM \u03b2)\n    : RequestM (RequestTask \u03b2) := do\n  let findTask \u2190 doc.cmdSnaps.waitFind? p\n  mapTask findTask fun\n    /- The elaboration task that we're waiting for may be aborted if the file contents change.\n    In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't\n    get bogged down in requests for an old state of the document. -/\n    | Except.error FileWorker.ElabTaskError.aborted =>\n      throwThe RequestError RequestError.fileChanged\n    | Except.error (FileWorker.ElabTaskError.ioError e) =>\n      throwThe IO.Error e\n    | Except.error FileWorker.ElabTaskError.eof => notFoundX\n    | Except.ok none => notFoundX\n    | Except.ok (some snap) => x snap\n\nend RequestM\n\n/- The global request handlers table. -/\nsection HandlerTable\nopen Lsp\n\nprivate structure RequestHandler where\n  fileSource : Json \u2192 Except RequestError Lsp.DocumentUri\n  handle : Json \u2192 RequestM (RequestTask Json)\n\nbuiltin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) \u2190\n  IO.mkRef {}\n\n/-- NB: This method may only be called in `builtin_initialize` blocks.\n\nA registration consists of:\n- a type of JSON-parsable request data `paramType`\n- a `FileSource` instance for it so the system knows where to route requests\n- a type of JSON-serializable response data `respType`\n- an actual `handler` which runs in the `RequestM` monad and is expected\n  to produce an asynchronous `RequestTask` which does any waiting/computation\n\nA handler task may be cancelled at any time, so it should check the cancellation token when possible\nto handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client\nas LSP error responses. -/\ndef registerLspRequestHandler (method : String)\n    paramType [FromJson paramType] [FileSource paramType]\n    respType [ToJson respType]\n    (handler : paramType \u2192 RequestM (RequestTask respType)) : IO Unit := do\n  if !(\u2190 IO.initializing) then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': only possible during initialization\"\n  if (\u2190requestHandlers.get).contains method then\n    throw <| IO.userError s!\"Failed to register LSP request handler for '{method}': already registered\"\n  let fileSource := fun j =>\n    parseRequestParams paramType j |>.map Lsp.fileSource\n  let handle := fun j => do\n    let params \u2190 parseRequestParams paramType j\n    let t \u2190 handler params\n    t.map <| Except.map ToJson.toJson\n\n  requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }\n\nprivate def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) := do\n  (\u2190 requestHandlers.get).find? method\n\ndef routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => return Except.error <| RequestError.methodNotFound method\n  | some rh => return rh.fileSource params\n\ndef handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do\n  match (\u2190 lookupLspRequestHandler method) with\n  | none => throwThe IO.Error <| IO.userError s!\"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?\"\n  | some rh => rh.handle params\n\nend HandlerTable\nend Lean.Server\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/Server/Requests.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.03358950468268333, "lm_q2_score": 0.02128735307407293, "lm_q1q2_score": 0.0007150316457635061}}
{"text": "inductive Foo where\n  | a | b | c\n\ndef f : Foo \u2192 Nat\n  | Foo.a => 10\n  | Foo.b => 20\n  | Foo.c => 35\n\ninductive CXCursorKind where\n  | CXCursor_UnexposedDecl\n  | CXCursor_StructDecl\n  | CXCursor_UnionDecl\n  | CXCursor_ClassDecl\n  | CXCursor_EnumDecl\n  | CXCursor_FieldDecl\n  | CXCursor_EnumConstantDecl\n  | CXCursor_FunctionDecl\n  | CXCursor_VarDecl\n  | CXCursor_ParmDecl\n  | CXCursor_ObjCInterfaceDecl\n  | CXCursor_ObjCCategoryDecl\n  | CXCursor_ObjCProtocolDecl\n  | CXCursor_ObjCPropertyDecl\n  | CXCursor_ObjCIvarDecl\n  | CXCursor_ObjCInstanceMethodDecl\n  | CXCursor_ObjCClassMethodDecl\n  | CXCursor_ObjCImplementationDecl\n  | CXCursor_ObjCCategoryImplDecl\n  | CXCursor_TypedefDecl\n  | CXCursor_CXXMethod\n  | CXCursor_Namespace\n  | CXCursor_LinkageSpec\n  | CXCursor_Constructor\n  | CXCursor_Destructor\n  | CXCursor_ConversionFunction\n  | CXCursor_TemplateTypeParameter\n  | CXCursor_NonTypeTemplateParameter\n  | CXCursor_TemplateTemplateParameter\n  | CXCursor_FunctionTemplate\n  | CXCursor_ClassTemplate\n  | CXCursor_ClassTemplatePartialSpecialization\n  | CXCursor_NamespaceAlias\n  | CXCursor_UsingDirective\n  | CXCursor_UsingDeclaration\n  | CXCursor_TypeAliasDecl\n  | CXCursor_ObjCSynthesizeDecl\n  | CXCursor_ObjCDynamicDecl\n  | CXCursor_CXXAccessSpecifier\n  | CXCursor_FirstDecl\n  | CXCursor_LastDecl\n  | CXCursor_FirstRef\n  | CXCursor_ObjCSuperClassRef\n  | CXCursor_ObjCProtocolRef\n  | CXCursor_ObjCClassRef\n  | CXCursor_TypeRef\n  | CXCursor_CXXBaseSpecifier\n  | CXCursor_TemplateRef\n  | CXCursor_NamespaceRef\n  | CXCursor_MemberRef\n  | CXCursor_LabelRef\n  | CXCursor_OverloadedDeclRef\n  | CXCursor_VariableRef\n  | CXCursor_LastRef\n  | CXCursor_FirstInvalid\n  | CXCursor_InvalidFile\n  | CXCursor_NoDeclFound\n  | CXCursor_NotImplemented\n  | CXCursor_InvalidCode\n  | CXCursor_LastInvalid\n  | CXCursor_FirstExpr\n  | CXCursor_UnexposedExpr\n  | CXCursor_DeclRefExpr\n  | CXCursor_MemberRefExpr\n  | CXCursor_CallExpr\n  | CXCursor_ObjCMessageExpr\n  | CXCursor_BlockExpr\n  | CXCursor_IntegerLiteral\n  | CXCursor_FloatingLiteral\n  | CXCursor_ImaginaryLiteral\n  | CXCursor_StringLiteral\n  | CXCursor_CharacterLiteral\n  | CXCursor_ParenExpr\n  | CXCursor_UnaryOperator\n  | CXCursor_ArraySubscriptExpr\n  | CXCursor_BinaryOperator\n  | CXCursor_CompoundAssignOperator\n  | CXCursor_ConditionalOperator\n  | CXCursor_CStyleCastExpr\n  | CXCursor_CompoundLiteralExpr\n  | CXCursor_InitListExpr\n  | CXCursor_AddrLabelExpr\n  | CXCursor_StmtExpr\n  | CXCursor_GenericSelectionExpr\n  | CXCursor_GNUNullExpr\n  | CXCursor_CXXStaticCastExpr\n  | CXCursor_CXXDynamicCastExpr\n  | CXCursor_CXXReinterpretCastExpr\n  | CXCursor_CXXConstCastExpr\n  | CXCursor_CXXFunctionalCastExpr\n  | CXCursor_CXXTypeidExpr\n  | CXCursor_CXXBoolLiteralExpr\n  | CXCursor_CXXNullPtrLiteralExpr\n  | CXCursor_CXXThisExpr\n  | CXCursor_CXXThrowExpr\n  | CXCursor_CXXNewExpr\n  | CXCursor_CXXDeleteExpr\n  | CXCursor_UnaryExpr\n  | CXCursor_ObjCStringLiteral\n  | CXCursor_ObjCEncodeExpr\n  | CXCursor_ObjCSelectorExpr\n  | CXCursor_ObjCProtocolExpr\n  | CXCursor_ObjCBridgedCastExpr\n  | CXCursor_PackExpansionExpr\n  | CXCursor_SizeOfPackExpr\n  | CXCursor_LambdaExpr\n  | CXCursor_ObjCBoolLiteralExpr\n  | CXCursor_ObjCSelfExpr\n  | CXCursor_OMPArraySectionExpr\n  | CXCursor_ObjCAvailabilityCheckExpr\n  | CXCursor_FixedPointLiteral\n  | CXCursor_OMPArrayShapingExpr\n  | CXCursor_OMPIteratorExpr\n  | CXCursor_CXXAddrspaceCastExpr\n  | CXCursor_LastExpr\n  | CXCursor_FirstStmt\n  | CXCursor_UnexposedStmt\n  | CXCursor_LabelStmt\n  | CXCursor_CompoundStmt\n  | CXCursor_CaseStmt\n  | CXCursor_DefaultStmt\n  | CXCursor_IfStmt\n  | CXCursor_SwitchStmt\n  | CXCursor_WhileStmt\n  | CXCursor_DoStmt\n  | CXCursor_ForStmt\n  | CXCursor_GotoStmt\n  | CXCursor_IndirectGotoStmt\n  | CXCursor_ContinueStmt\n  | CXCursor_BreakStmt\n  | CXCursor_ReturnStmt\n  | CXCursor_GCCAsmStmt\n  | CXCursor_AsmStmt\n  | CXCursor_ObjCAtTryStmt\n  | CXCursor_ObjCAtCatchStmt\n  | CXCursor_ObjCAtFinallyStmt\n  | CXCursor_ObjCAtThrowStmt\n  | CXCursor_ObjCAtSynchronizedStmt\n  | CXCursor_ObjCAutoreleasePoolStmt\n  | CXCursor_ObjCForCollectionStmt\n  | CXCursor_CXXCatchStmt\n  | CXCursor_CXXTryStmt\n  | CXCursor_CXXForRangeStmt\n  | CXCursor_SEHTryStmt\n  | CXCursor_SEHExceptStmt\n  | CXCursor_SEHFinallyStmt\n  | CXCursor_MSAsmStmt\n  | CXCursor_NullStmt\n  | CXCursor_DeclStmt\n  | CXCursor_OMPParallelDirective\n  | CXCursor_OMPSimdDirective\n  | CXCursor_OMPForDirective\n  | CXCursor_OMPSectionsDirective\n  | CXCursor_OMPSectionDirective\n  | CXCursor_OMPSingleDirective\n  | CXCursor_OMPParallelForDirective\n  | CXCursor_OMPParallelSectionsDirective\n  | CXCursor_OMPTaskDirective\n  | CXCursor_OMPMasterDirective\n  | CXCursor_OMPCriticalDirective\n  | CXCursor_OMPTaskyieldDirective\n  | CXCursor_OMPBarrierDirective\n  | CXCursor_OMPTaskwaitDirective\n  | CXCursor_OMPFlushDirective\n  | CXCursor_SEHLeaveStmt\n  | CXCursor_OMPOrderedDirective\n  | CXCursor_OMPAtomicDirective\n  | CXCursor_OMPForSimdDirective\n  | CXCursor_OMPParallelForSimdDirective\n  | CXCursor_OMPTargetDirective\n  | CXCursor_OMPTeamsDirective\n  | CXCursor_OMPTaskgroupDirective\n  | CXCursor_OMPCancellationPointDirective\n  | CXCursor_OMPCancelDirective\n  | CXCursor_OMPTargetDataDirective\n  | CXCursor_OMPTaskLoopDirective\n  | CXCursor_OMPTaskLoopSimdDirective\n  | CXCursor_OMPDistributeDirective\n  | CXCursor_OMPTargetEnterDataDirective\n  | CXCursor_OMPTargetExitDataDirective\n  | CXCursor_OMPTargetParallelDirective\n  | CXCursor_OMPTargetParallelForDirective\n  | CXCursor_OMPTargetUpdateDirective\n  | CXCursor_OMPDistributeParallelForDirective\n  | CXCursor_OMPDistributeParallelForSimdDirective\n  | CXCursor_OMPDistributeSimdDirective\n  | CXCursor_OMPTargetParallelForSimdDirective\n  | CXCursor_OMPTargetSimdDirective\n  | CXCursor_OMPTeamsDistributeDirective\n  | CXCursor_OMPTeamsDistributeSimdDirective\n  | CXCursor_OMPTeamsDistributeParallelForSimdDirective\n  | CXCursor_OMPTeamsDistributeParallelForDirective\n  | CXCursor_OMPTargetTeamsDirective\n  | CXCursor_OMPTargetTeamsDistributeDirective\n  | CXCursor_OMPTargetTeamsDistributeParallelForDirective\n  | CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective\n  | CXCursor_OMPTargetTeamsDistributeSimdDirective\n  | CXCursor_BuiltinBitCastExpr\n  | CXCursor_OMPMasterTaskLoopDirective\n  | CXCursor_OMPParallelMasterTaskLoopDirective\n  | CXCursor_OMPMasterTaskLoopSimdDirective\n  | CXCursor_OMPParallelMasterTaskLoopSimdDirective\n  | CXCursor_OMPParallelMasterDirective\n  | CXCursor_OMPDepobjDirective\n  | CXCursor_OMPScanDirective\n  | CXCursor_OMPTileDirective\n  | CXCursor_OMPCanonicalLoop\n  | CXCursor_OMPInteropDirective\n  | CXCursor_OMPDispatchDirective\n  | CXCursor_OMPMaskedDirective\n  | CXCursor_OMPUnrollDirective\n  | CXCursor_LastStmt\n  | CXCursor_TranslationUnit\n  | CXCursor_FirstAttr\n  | CXCursor_UnexposedAttr\n  | CXCursor_IBActionAttr\n  | CXCursor_IBOutletAttr\n  | CXCursor_IBOutletCollectionAttr\n  | CXCursor_CXXFinalAttr\n  | CXCursor_CXXOverrideAttr\n  | CXCursor_AnnotateAttr\n  | CXCursor_AsmLabelAttr\n  | CXCursor_PackedAttr\n  | CXCursor_PureAttr\n  | CXCursor_ConstAttr\n  | CXCursor_NoDuplicateAttr\n  | CXCursor_CUDAConstantAttr\n  | CXCursor_CUDADeviceAttr\n  | CXCursor_CUDAGlobalAttr\n  | CXCursor_CUDAHostAttr\n  | CXCursor_CUDASharedAttr\n  | CXCursor_VisibilityAttr\n  | CXCursor_DLLExport\n  | CXCursor_DLLImport\n  | CXCursor_NSReturnsRetained\n  | CXCursor_NSReturnsNotRetained\n  | CXCursor_NSReturnsAutoreleased\n  | CXCursor_NSConsumesSelf\n  | CXCursor_NSConsumed\n  | CXCursor_ObjCException\n  | CXCursor_ObjCNSObject\n  | CXCursor_ObjCIndependentClass\n  | CXCursor_ObjCPreciseLifetime\n  | CXCursor_ObjCReturnsInnerPointer\n  | CXCursor_ObjCRequiresSuper\n  | CXCursor_ObjCRootClass\n  | CXCursor_ObjCSubclassingRestricted\n  | CXCursor_ObjCExplicitProtocolImpl\n  | CXCursor_ObjCDesignatedInitializer\n  | CXCursor_ObjCRuntimeVisible\n  | CXCursor_ObjCBoxable\n  | CXCursor_FlagEnum\n  | CXCursor_ConvergentAttr\n  | CXCursor_WarnUnusedAttr\n  | CXCursor_WarnUnusedResultAttr\n  | CXCursor_AlignedAttr\n  | CXCursor_LastAttr\n  | CXCursor_PreprocessingDirective\n  | CXCursor_MacroDefinition\n  | CXCursor_MacroExpansion\n  | CXCursor_MacroInstantiation\n  | CXCursor_InclusionDirective\n  | CXCursor_FirstPreprocessing\n  | CXCursor_LastPreprocessing\n  | CXCursor_ModuleImportDecl\n  | CXCursor_TypeAliasTemplateDecl\n  | CXCursor_StaticAssert\n  | CXCursor_FriendDecl\n  | CXCursor_FirstExtraDecl\n  | CXCursor_LastExtraDecl\n  | CXCursor_OverloadCandidate\n  deriving BEq, DecidableEq\n\nopen CXCursorKind\n\nexample (h : CXCursor_CUDAGlobalAttr = CXCursor_CUDAHostAttr) : False := by\n  contradiction\n\n#eval CXCursor_CUDAGlobalAttr == CXCursor_CUDAHostAttr\n\n#eval decide (CXCursor_CUDAGlobalAttr = CXCursor_CUDAHostAttr)\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/654.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.0656048392859768, "lm_q2_score": 0.00970847506675134, "lm_q1q2_score": 0.0006369229464661345}}
{"text": "# 2021-10-10 ssr plus, passwall\n# Automatically generated file; DO NOT EDIT.\n# OpenWrt Configuration\n#\nCONFIG_MODULES=y\nCONFIG_HAVE_DOT_CONFIG=y\n# CONFIG_TARGET_sunxi is not set\n# CONFIG_TARGET_apm821xx is not set\n# CONFIG_TARGET_ath25 is not set\n# CONFIG_TARGET_ath79 is not set\n# CONFIG_TARGET_bcm27xx is not set\n# CONFIG_TARGET_bcm53xx is not set\n# CONFIG_TARGET_bcm47xx is not set\n# CONFIG_TARGET_bcm4908 is not set\n# CONFIG_TARGET_bcm63xx is not set\n# CONFIG_TARGET_bmips is not set\n# CONFIG_TARGET_octeon is not set\n# CONFIG_TARGET_gemini is not set\n# CONFIG_TARGET_mpc85xx is not set\n# CONFIG_TARGET_mxs is not set\n# CONFIG_TARGET_lantiq is not set\n# CONFIG_TARGET_malta is not set\n# CONFIG_TARGET_pistachio is not set\n# CONFIG_TARGET_mvebu is not set\n# CONFIG_TARGET_kirkwood is not set\n# CONFIG_TARGET_mediatek is not set\nCONFIG_TARGET_ramips=y\n# CONFIG_TARGET_at91 is not set\n# CONFIG_TARGET_tegra is not set\n# CONFIG_TARGET_layerscape is not set\n# CONFIG_TARGET_imx6 is not set\n# CONFIG_TARGET_octeontx is not set\n# CONFIG_TARGET_oxnas is not set\n# CONFIG_TARGET_armvirt is not set\n# CONFIG_TARGET_ipq40xx is not set\n# CONFIG_TARGET_ipq806x is not set\n# CONFIG_TARGET_ipq807x is not set\n# CONFIG_TARGET_realtek is not set\n# CONFIG_TARGET_rockchip is not set\n# CONFIG_TARGET_arc770 is not set\n# CONFIG_TARGET_archs38 is not set\n# CONFIG_TARGET_omap is not set\n# CONFIG_TARGET_uml is not set\n# CONFIG_TARGET_zynq is not set\n# CONFIG_TARGET_x86 is not set\n# CONFIG_TARGET_ramips_mt7620 is not set\nCONFIG_TARGET_ramips_mt7621=y\n# CONFIG_TARGET_ramips_mt76x8 is not set\n# CONFIG_TARGET_ramips_rt288x is not set\n# CONFIG_TARGET_ramips_rt305x is not set\n# CONFIG_TARGET_ramips_rt3883 is not set\n# CONFIG_TARGET_MULTI_PROFILE is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_adslr_g7 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_afoundry_ew1200 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_alfa-network_quad-e4g is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_ampedwireless_ally-r1900k is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_ampedwireless_ally-00x19k is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_asiarf_ap7621-001 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_asiarf_ap7621-nv1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_asus_rt-ac57u is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_asus_rt-ac65p is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_asus_rt-ac85p is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_asus_rt-n56u-b1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_buffalo_wsr-1166dhp is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_buffalo_wsr-2533dhpl is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_buffalo_wsr-600dhp is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_cudy_wr1300 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_cudy_wr2100 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-1960-a1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-2640-a1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-2660-a1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-853-a3 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-853-r1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-860l-b1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-867-a1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-878-a1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-882-a1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_dlink_dir-882-r1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_d-team_newifi-d2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_d-team_pbr-m1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_edimax_ra21s is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_edimax_re23s is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_edimax_rg21s is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1167ghbk2-s is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1167gs2-b is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1167gst2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1750gs is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1750gst2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1750gsv is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-1900gst is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-2533ghbk-i is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-2533gst is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_elecom_wrc-2533gst2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_firefly_firewrt is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_gehua_ghl-r-001 is not set\nCONFIG_TARGET_ramips_mt7621_DEVICE_glinet_gl-mt1300=y\n# CONFIG_TARGET_ramips_mt7621_DEVICE_gnubee_gb-pc1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_gnubee_gb-pc2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_hiwifi_hc5962 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wn-ax1167gr is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wn-ax1167gr2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wn-ax2033gr is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wn-dx1167r is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wn-dx1200gr is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wn-gx300gr is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iodata_wnpr2600g is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iptime_a6ns-m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_iptime_a8004t is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_jcg_jhr-ac876m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_jcg_q20 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_jcg_y2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_lenovo_newifi-d1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_e5600 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_ea7300-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_ea7300-v2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_ea7500-v2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_ea8100-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_ea8100-v2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_linksys_re6500 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mediatek_ap-mt7621a-v60 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mediatek_mt7621-eval-board is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mikrotik_routerboard-750gr3 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mikrotik_routerboard-760igs is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mikrotik_routerboard-m11g is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mikrotik_routerboard-m33g is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mqmaker_witi is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_mtc_wr1201 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_ex6150 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_r6220 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_r6260 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_r6350 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_r6700-v2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_r6800 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_r6850 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_wac104 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_wac124 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netgear_wndr3700-v5 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_netis_wf2881 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_phicomm_k2p is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_planex_vr500 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_samknows_whitebox-v8 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_sercomm_na502 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_storylink_sap-g3200u3 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_telco-electronics_x1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tenbay_t-mb5eu-v01 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_thunder_timecloud is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_totolink_a7000r is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_totolink_x5000r is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_archer-a6-v3 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_archer-c6-v3 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_archer-c6u-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_eap235-wall-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_re350-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_re500-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_tplink_re650-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_ubnt_edgerouter-x is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_ubnt_edgerouter-x-sfp is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_ubnt_unifi-6-lite is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_ubnt_unifi-nanohd is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_unielec_u7621-01-16m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_unielec_u7621-06-16m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_unielec_u7621-06-64m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_wavlink_wl-wn531a6 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_wevo_11acnas is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_wevo_w2914ns-v2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_winstars_ws-wn583a6 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-3g is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-3g-v2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-3-pro is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-4 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-4a-gigabit is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-ac2100 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_mi-router-cr660x is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaomi_redmi-router-ac2100 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xiaoyu_xy-c5 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_xzwifi_creativebox-v1 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_youhua_wr1200js is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_youku_yk-l2 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zbtlink_zbt-we1326 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zbtlink_zbt-we3526 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zbtlink_zbt-wg2626 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zbtlink_zbt-wg3526-16m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zbtlink_zbt-wg3526-32m is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zio_freezio is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zyxel_nr7101 is not set\n# CONFIG_TARGET_ramips_mt7621_DEVICE_zyxel_wap6805 is not set\nCONFIG_HAS_SUBTARGETS=y\nCONFIG_HAS_DEVICES=y\nCONFIG_TARGET_BOARD=\"ramips\"\nCONFIG_TARGET_SUBTARGET=\"mt7621\"\nCONFIG_TARGET_PROFILE=\"DEVICE_glinet_gl-mt1300\"\nCONFIG_TARGET_ARCH_PACKAGES=\"mipsel_24kc\"\nCONFIG_DEFAULT_TARGET_OPTIMIZATION=\"-Os -pipe -mno-branch-likely -mips32r2 -mtune=24kc\"\nCONFIG_CPU_TYPE=\"24kc\"\nCONFIG_LINUX_5_4=y\nCONFIG_DEFAULT_base-files=y\nCONFIG_DEFAULT_block-mount=y\nCONFIG_DEFAULT_busybox=y\nCONFIG_DEFAULT_coremark=y\nCONFIG_DEFAULT_ddns-scripts_aliyun=y\nCONFIG_DEFAULT_ddns-scripts_dnspod=y\nCONFIG_DEFAULT_default-settings=y\nCONFIG_DEFAULT_dnsmasq-full=y\nCONFIG_DEFAULT_dropbear=y\nCONFIG_DEFAULT_firewall=y\nCONFIG_DEFAULT_fstools=y\nCONFIG_DEFAULT_iptables=y\nCONFIG_DEFAULT_iwinfo=y\nCONFIG_DEFAULT_kmod-crypto-hw-eip93=y\nCONFIG_DEFAULT_kmod-gpio-button-hotplug=y\nCONFIG_DEFAULT_kmod-ipt-raw=y\nCONFIG_DEFAULT_kmod-leds-gpio=y\nCONFIG_DEFAULT_kmod-mt7615d_dbdc=y\nCONFIG_DEFAULT_kmod-nf-nathelper=y\nCONFIG_DEFAULT_kmod-nf-nathelper-extra=y\nCONFIG_DEFAULT_kmod-usb3=y\nCONFIG_DEFAULT_libc=y\nCONFIG_DEFAULT_libgcc=y\nCONFIG_DEFAULT_libustream-openssl=y\nCONFIG_DEFAULT_logd=y\nCONFIG_DEFAULT_luci=y\nCONFIG_DEFAULT_luci-app-accesscontrol=y\nCONFIG_DEFAULT_luci-app-arpbind=y\nCONFIG_DEFAULT_luci-app-autoreboot=y\nCONFIG_DEFAULT_luci-app-ddns=y\nCONFIG_DEFAULT_luci-app-filetransfer=y\nCONFIG_DEFAULT_luci-app-nlbwmon=y\nCONFIG_DEFAULT_luci-app-ramfree=y\nCONFIG_DEFAULT_luci-app-ssr-plus=y\nCONFIG_DEFAULT_luci-app-turboacc=y\nCONFIG_DEFAULT_luci-app-unblockmusic=y\nCONFIG_DEFAULT_luci-app-upnp=y\nCONFIG_DEFAULT_luci-app-vlmcsd=y\nCONFIG_DEFAULT_luci-app-vsftpd=y\nCONFIG_DEFAULT_luci-app-wol=y\nCONFIG_DEFAULT_mtd=y\nCONFIG_DEFAULT_netifd=y\nCONFIG_DEFAULT_opkg=y\nCONFIG_DEFAULT_ppp=y\nCONFIG_DEFAULT_ppp-mod-pppoe=y\nCONFIG_DEFAULT_procd=y\nCONFIG_DEFAULT_swconfig=y\nCONFIG_DEFAULT_uci=y\nCONFIG_DEFAULT_uclient-fetch=y\nCONFIG_DEFAULT_urandom-seed=y\nCONFIG_HAS_TESTING_KERNEL=y\nCONFIG_AUDIO_SUPPORT=y\nCONFIG_GPIO_SUPPORT=y\nCONFIG_PCI_SUPPORT=y\nCONFIG_USB_SUPPORT=y\nCONFIG_RTC_SUPPORT=y\nCONFIG_USES_DEVICETREE=y\nCONFIG_USES_INITRAMFS=y\nCONFIG_USES_SQUASHFS=y\nCONFIG_USES_MINOR=y\nCONFIG_HAS_MIPS16=y\nCONFIG_NAND_SUPPORT=y\nCONFIG_mipsel=y\nCONFIG_ARCH=\"mipsel\"\n\n#\n# Target Images\n#\nCONFIG_TARGET_ROOTFS_INITRAMFS=y\n# CONFIG_TARGET_INITRAMFS_COMPRESSION_NONE is not set\n# CONFIG_TARGET_INITRAMFS_COMPRESSION_GZIP is not set\n# CONFIG_TARGET_INITRAMFS_COMPRESSION_BZIP2 is not set\nCONFIG_TARGET_INITRAMFS_COMPRESSION_LZMA=y\n# CONFIG_TARGET_INITRAMFS_COMPRESSION_LZO is not set\n# CONFIG_TARGET_INITRAMFS_COMPRESSION_LZ4 is not set\n# CONFIG_TARGET_INITRAMFS_COMPRESSION_XZ is not set\nCONFIG_EXTERNAL_CPIO=\"\"\n# CONFIG_TARGET_INITRAMFS_FORCE is not set\n\n#\n# Root filesystem archives\n#\n# CONFIG_TARGET_ROOTFS_CPIOGZ is not set\n# CONFIG_TARGET_ROOTFS_TARGZ is not set\n\n#\n# Root filesystem images\n#\n# CONFIG_TARGET_ROOTFS_EXT4FS is not set\nCONFIG_TARGET_ROOTFS_SQUASHFS=y\nCONFIG_TARGET_SQUASHFS_BLOCK_SIZE=1024\nCONFIG_TARGET_UBIFS_FREE_SPACE_FIXUP=y\nCONFIG_TARGET_UBIFS_JOURNAL_SIZE=\"\"\n\n#\n# Image Options\n#\n# end of Target Images\n\n# CONFIG_EXPERIMENTAL is not set\n\n#\n# Global build settings\n#\n# CONFIG_JSON_OVERVIEW_IMAGE_INFO is not set\n# CONFIG_ALL_NONSHARED is not set\n# CONFIG_ALL_KMODS is not set\n# CONFIG_ALL is not set\n# CONFIG_BUILDBOT is not set\nCONFIG_SIGNED_PACKAGES=y\nCONFIG_SIGNATURE_CHECK=y\n\n#\n# General build options\n#\n# CONFIG_TESTING_KERNEL is not set\n# CONFIG_DISPLAY_SUPPORT is not set\n# CONFIG_BUILD_PATENTED is not set\n# CONFIG_BUILD_NLS is not set\nCONFIG_SHADOW_PASSWORDS=y\n# CONFIG_CLEAN_IPKG is not set\n# CONFIG_IPK_FILES_CHECKSUMS is not set\n# CONFIG_INCLUDE_CONFIG is not set\n# CONFIG_REPRODUCIBLE_DEBUG_INFO is not set\n# CONFIG_COLLECT_KERNEL_DEBUG is not set\n\n#\n# Kernel build options\n#\nCONFIG_KERNEL_BUILD_USER=\"\"\nCONFIG_KERNEL_BUILD_DOMAIN=\"\"\nCONFIG_KERNEL_PRINTK=y\nCONFIG_KERNEL_CRASHLOG=y\nCONFIG_KERNEL_SWAP=y\n# CONFIG_KERNEL_PROC_STRIPPED is not set\nCONFIG_KERNEL_DEBUG_FS=y\nCONFIG_KERNEL_MIPS_FP_SUPPORT=y\n# CONFIG_KERNEL_PERF_EVENTS is not set\n# CONFIG_KERNEL_PROFILING is not set\n# CONFIG_KERNEL_UBSAN is not set\n# CONFIG_KERNEL_KCOV is not set\n# CONFIG_KERNEL_TASKSTATS is not set\nCONFIG_KERNEL_KALLSYMS=y\n# CONFIG_KERNEL_FTRACE is not set\nCONFIG_KERNEL_DEBUG_KERNEL=y\nCONFIG_KERNEL_DEBUG_INFO=y\n# CONFIG_KERNEL_DYNAMIC_DEBUG is not set\n# CONFIG_KERNEL_KPROBES is not set\nCONFIG_KERNEL_AIO=y\nCONFIG_KERNEL_IO_URING=y\nCONFIG_KERNEL_FHANDLE=y\nCONFIG_KERNEL_FANOTIFY=y\n# CONFIG_KERNEL_BLK_DEV_BSG is not set\n# CONFIG_KERNEL_HUGETLB_PAGE is not set\nCONFIG_KERNEL_MAGIC_SYSRQ=y\n# CONFIG_KERNEL_DEBUG_PINCTRL is not set\n# CONFIG_KERNEL_DEBUG_GPIO is not set\nCONFIG_KERNEL_COREDUMP=y\nCONFIG_KERNEL_ELF_CORE=y\n# CONFIG_KERNEL_PROVE_LOCKING is not set\n# CONFIG_KERNEL_LOCKUP_DETECTOR is not set\n# CONFIG_KERNEL_DETECT_HUNG_TASK is not set\n# CONFIG_KERNEL_WQ_WATCHDOG is not set\n# CONFIG_KERNEL_DEBUG_ATOMIC_SLEEP is not set\n# CONFIG_KERNEL_DEBUG_VM is not set\nCONFIG_KERNEL_PRINTK_TIME=y\n# CONFIG_KERNEL_SLABINFO is not set\n# CONFIG_KERNEL_PROC_PAGE_MONITOR is not set\n# CONFIG_KERNEL_KEXEC is not set\n# CONFIG_USE_RFKILL is not set\n# CONFIG_USE_SPARSE is not set\n# CONFIG_KERNEL_DEVTMPFS is not set\nCONFIG_KERNEL_KEYS=y\n# CONFIG_KERNEL_PERSISTENT_KEYRINGS is not set\n# CONFIG_KERNEL_KEYS_REQUEST_CACHE is not set\n# CONFIG_KERNEL_BIG_KEYS is not set\nCONFIG_KERNEL_CGROUPS=y\n# CONFIG_KERNEL_CGROUP_DEBUG is not set\nCONFIG_KERNEL_FREEZER=y\n# CONFIG_KERNEL_CGROUP_FREEZER is not set\n# CONFIG_KERNEL_CGROUP_DEVICE is not set\n# CONFIG_KERNEL_CGROUP_HUGETLB is not set\nCONFIG_KERNEL_CGROUP_PIDS=y\nCONFIG_KERNEL_CGROUP_RDMA=y\nCONFIG_KERNEL_CGROUP_BPF=y\nCONFIG_KERNEL_CPUSETS=y\n# CONFIG_KERNEL_PROC_PID_CPUSET is not set\nCONFIG_KERNEL_CGROUP_CPUACCT=y\nCONFIG_KERNEL_RESOURCE_COUNTERS=y\nCONFIG_KERNEL_MM_OWNER=y\nCONFIG_KERNEL_MEMCG=y\nCONFIG_KERNEL_MEMCG_SWAP=y\n# CONFIG_KERNEL_MEMCG_SWAP_ENABLED is not set\nCONFIG_KERNEL_MEMCG_KMEM=y\n# CONFIG_KERNEL_CGROUP_PERF is not set\nCONFIG_KERNEL_CGROUP_SCHED=y\nCONFIG_KERNEL_FAIR_GROUP_SCHED=y\nCONFIG_KERNEL_CFS_BANDWIDTH=y\nCONFIG_KERNEL_RT_GROUP_SCHED=y\nCONFIG_KERNEL_BLK_CGROUP=y\n# CONFIG_KERNEL_CFQ_GROUP_IOSCHED is not set\nCONFIG_KERNEL_BLK_DEV_THROTTLING=y\n# CONFIG_KERNEL_BLK_DEV_THROTTLING_LOW is not set\n# CONFIG_KERNEL_DEBUG_BLK_CGROUP is not set\n# CONFIG_KERNEL_NET_CLS_CGROUP is not set\n# CONFIG_KERNEL_CGROUP_NET_CLASSID is not set\n# CONFIG_KERNEL_CGROUP_NET_PRIO is not set\nCONFIG_KERNEL_NAMESPACES=y\nCONFIG_KERNEL_UTS_NS=y\nCONFIG_KERNEL_IPC_NS=y\nCONFIG_KERNEL_USER_NS=y\nCONFIG_KERNEL_PID_NS=y\nCONFIG_KERNEL_NET_NS=y\nCONFIG_KERNEL_DEVPTS_MULTIPLE_INSTANCES=y\nCONFIG_KERNEL_POSIX_MQUEUE=y\nCONFIG_KERNEL_SECCOMP_FILTER=y\nCONFIG_KERNEL_SECCOMP=y\nCONFIG_KERNEL_IP_MROUTE=y\nCONFIG_KERNEL_IPV6=y\nCONFIG_KERNEL_IPV6_MULTIPLE_TABLES=y\nCONFIG_KERNEL_IPV6_SUBTREES=y\nCONFIG_KERNEL_IPV6_MROUTE=y\n# CONFIG_KERNEL_IPV6_PIMSM_V2 is not set\nCONFIG_KERNEL_IPV6_SEG6_LWTUNNEL=y\n# CONFIG_KERNEL_LWTUNNEL_BPF is not set\n# CONFIG_KERNEL_IP_PNP is not set\n\n#\n# Filesystem ACL and attr support options\n#\n# CONFIG_USE_FS_ACL_ATTR is not set\n# CONFIG_KERNEL_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_BTRFS_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_EXT4_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_F2FS_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_JFFS2_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_TMPFS_POSIX_ACL is not set\n# CONFIG_KERNEL_CIFS_ACL is not set\n# CONFIG_KERNEL_HFS_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_HFSPLUS_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_NFS_ACL_SUPPORT is not set\n# CONFIG_KERNEL_NFS_V3_ACL_SUPPORT is not set\n# CONFIG_KERNEL_NFSD_V2_ACL_SUPPORT is not set\n# CONFIG_KERNEL_NFSD_V3_ACL_SUPPORT is not set\n# CONFIG_KERNEL_REISER_FS_POSIX_ACL is not set\n# CONFIG_KERNEL_XFS_POSIX_ACL is not set\n# CONFIG_KERNEL_JFS_POSIX_ACL is not set\n# end of Filesystem ACL and attr support options\n\n# CONFIG_KERNEL_DEVMEM is not set\n# CONFIG_KERNEL_DEVKMEM is not set\nCONFIG_KERNEL_SQUASHFS_FRAGMENT_CACHE_SIZE=3\n# CONFIG_KERNEL_SQUASHFS_XATTR is not set\nCONFIG_KERNEL_CC_OPTIMIZE_FOR_PERFORMANCE=y\n# CONFIG_KERNEL_CC_OPTIMIZE_FOR_SIZE is not set\n# CONFIG_KERNEL_AUDIT is not set\n# CONFIG_KERNEL_SECURITY is not set\n# CONFIG_KERNEL_SECURITY_NETWORK is not set\n# CONFIG_KERNEL_SECURITY_SELINUX is not set\n# CONFIG_KERNEL_EXT4_FS_SECURITY is not set\n# CONFIG_KERNEL_F2FS_FS_SECURITY is not set\n# CONFIG_KERNEL_UBIFS_FS_SECURITY is not set\n# CONFIG_KERNEL_JFFS2_FS_SECURITY is not set\n# end of Kernel build options\n\n#\n# Package build options\n#\n# CONFIG_DEBUG is not set\nCONFIG_IPV6=y\n\n#\n# Stripping options\n#\n# CONFIG_NO_STRIP is not set\n# CONFIG_USE_STRIP is not set\nCONFIG_USE_SSTRIP=y\nCONFIG_SSTRIP_ARGS=\"-z\"\n# CONFIG_STRIP_KERNEL_EXPORTS is not set\n# CONFIG_USE_MKLIBS is not set\nCONFIG_USE_UCLIBCXX=y\n# CONFIG_USE_LIBSTDCXX is not set\n\n#\n# Hardening build options\n#\nCONFIG_PKG_CHECK_FORMAT_SECURITY=y\n# CONFIG_PKG_ASLR_PIE_NONE is not set\nCONFIG_PKG_ASLR_PIE_REGULAR=y\n# CONFIG_PKG_ASLR_PIE_ALL is not set\n# CONFIG_PKG_CC_STACKPROTECTOR_NONE is not set\nCONFIG_PKG_CC_STACKPROTECTOR_REGULAR=y\n# CONFIG_PKG_CC_STACKPROTECTOR_STRONG is not set\n# CONFIG_KERNEL_CC_STACKPROTECTOR_NONE is not set\nCONFIG_KERNEL_CC_STACKPROTECTOR_REGULAR=y\n# CONFIG_KERNEL_CC_STACKPROTECTOR_STRONG is not set\nCONFIG_KERNEL_STACKPROTECTOR=y\n# CONFIG_KERNEL_STACKPROTECTOR_STRONG is not set\n# CONFIG_PKG_FORTIFY_SOURCE_NONE is not set\nCONFIG_PKG_FORTIFY_SOURCE_1=y\n# CONFIG_PKG_FORTIFY_SOURCE_2 is not set\n# CONFIG_PKG_RELRO_NONE is not set\n# CONFIG_PKG_RELRO_PARTIAL is not set\nCONFIG_PKG_RELRO_FULL=y\n# CONFIG_SELINUX is not set\n# end of Global build settings\n\n# CONFIG_DEVEL is not set\n# CONFIG_BROKEN is not set\nCONFIG_BINARY_FOLDER=\"\"\nCONFIG_DOWNLOAD_FOLDER=\"\"\nCONFIG_LOCALMIRROR=\"\"\nCONFIG_AUTOREBUILD=y\n# CONFIG_AUTOREMOVE is not set\nCONFIG_BUILD_SUFFIX=\"\"\nCONFIG_TARGET_ROOTFS_DIR=\"\"\n# CONFIG_CCACHE is not set\nCONFIG_CCACHE_DIR=\"\"\nCONFIG_EXTERNAL_KERNEL_TREE=\"\"\nCONFIG_KERNEL_GIT_CLONE_URI=\"\"\nCONFIG_BUILD_LOG_DIR=\"\"\nCONFIG_EXTRA_OPTIMIZATION=\"-fno-caller-saves -fno-plt\"\nCONFIG_TARGET_OPTIMIZATION=\"-Os -pipe -mno-branch-likely -mips32r2 -mtune=24kc\"\nCONFIG_SOFT_FLOAT=y\nCONFIG_USE_MIPS16=y\n# CONFIG_EXTRA_TARGET_ARCH is not set\nCONFIG_EXTRA_BINUTILS_CONFIG_OPTIONS=\"\"\nCONFIG_EXTRA_GCC_CONFIG_OPTIONS=\"\"\n# CONFIG_GCC_DEFAULT_PIE is not set\n# CONFIG_GCC_DEFAULT_SSP is not set\n# CONFIG_SJLJ_EXCEPTIONS is not set\n# CONFIG_INSTALL_GFORTRAN is not set\nCONFIG_GDB=y\n# CONFIG_GDB_PYTHON is not set\nCONFIG_USE_MUSL=y\nCONFIG_SSP_SUPPORT=y\nCONFIG_BINUTILS_VERSION_2_34=y\nCONFIG_BINUTILS_VERSION=\"2.34\"\nCONFIG_GCC_VERSION=\"8.4.0\"\n# CONFIG_GCC_USE_IREMAP is not set\nCONFIG_LIBC=\"musl\"\nCONFIG_TARGET_SUFFIX=\"musl\"\n# CONFIG_IB is not set\n# CONFIG_SDK is not set\n# CONFIG_MAKE_TOOLCHAIN is not set\n# CONFIG_IMAGEOPT is not set\n# CONFIG_PREINITOPT is not set\nCONFIG_TARGET_PREINIT_SUPPRESS_STDERR=y\n# CONFIG_TARGET_PREINIT_DISABLE_FAILSAFE is not set\nCONFIG_TARGET_PREINIT_TIMEOUT=2\n# CONFIG_TARGET_PREINIT_SHOW_NETMSG is not set\n# CONFIG_TARGET_PREINIT_SUPPRESS_FAILSAFE_NETMSG is not set\nCONFIG_TARGET_PREINIT_IFNAME=\"\"\nCONFIG_TARGET_PREINIT_IP=\"192.168.1.1\"\nCONFIG_TARGET_PREINIT_NETMASK=\"255.255.255.0\"\nCONFIG_TARGET_PREINIT_BROADCAST=\"192.168.1.255\"\n# CONFIG_INITOPT is not set\nCONFIG_TARGET_INIT_PATH=\"/usr/sbin:/usr/bin:/sbin:/bin\"\nCONFIG_TARGET_INIT_ENV=\"\"\nCONFIG_TARGET_INIT_CMD=\"/sbin/init\"\nCONFIG_TARGET_INIT_SUPPRESS_STDERR=y\n# CONFIG_VERSIONOPT is not set\nCONFIG_PER_FEED_REPO=y\nCONFIG_FEED_packages=y\nCONFIG_FEED_luci=y\nCONFIG_FEED_routing=y\nCONFIG_FEED_telephony=y\n\n#\n# Base system\n#\n# CONFIG_PACKAGE_attendedsysupgrade-common is not set\n# CONFIG_PACKAGE_auc is not set\nCONFIG_PACKAGE_base-files=y\nCONFIG_PACKAGE_block-mount=y\n# CONFIG_PACKAGE_blockd is not set\n# CONFIG_PACKAGE_bridge is not set\nCONFIG_PACKAGE_busybox=y\n# CONFIG_BUSYBOX_CUSTOM is not set\nCONFIG_BUSYBOX_DEFAULT_HAVE_DOT_CONFIG=y\n# CONFIG_BUSYBOX_DEFAULT_DESKTOP is not set\n# CONFIG_BUSYBOX_DEFAULT_EXTRA_COMPAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEDORA_COMPAT is not set\nCONFIG_BUSYBOX_DEFAULT_INCLUDE_SUSv2=y\nCONFIG_BUSYBOX_DEFAULT_LONG_OPTS=y\nCONFIG_BUSYBOX_DEFAULT_SHOW_USAGE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VERBOSE_USAGE=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_COMPRESS_USAGE is not set\nCONFIG_BUSYBOX_DEFAULT_LFS=y\n# CONFIG_BUSYBOX_DEFAULT_PAM is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DEVPTS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UTMP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WTMP is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_PIDFILE=y\nCONFIG_BUSYBOX_DEFAULT_PID_FILE_PATH=\"/var/run\"\n# CONFIG_BUSYBOX_DEFAULT_BUSYBOX is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SHOW_SCRIPT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSTALLER is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_NO_USR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SUID is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SUID_CONFIG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SUID_CONFIG_QUIET is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_PREFER_APPLETS=y\nCONFIG_BUSYBOX_DEFAULT_BUSYBOX_EXEC_PATH=\"/proc/self/exe\"\n# CONFIG_BUSYBOX_DEFAULT_SELINUX is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CLEAN_UP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SYSLOG_INFO is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SYSLOG=y\n# CONFIG_BUSYBOX_DEFAULT_STATIC is not set\n# CONFIG_BUSYBOX_DEFAULT_PIE is not set\n# CONFIG_BUSYBOX_DEFAULT_NOMMU is not set\n# CONFIG_BUSYBOX_DEFAULT_BUILD_LIBBUSYBOX is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LIBBUSYBOX_STATIC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INDIVIDUAL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SHARED_BUSYBOX is not set\nCONFIG_BUSYBOX_DEFAULT_CROSS_COMPILER_PREFIX=\"\"\nCONFIG_BUSYBOX_DEFAULT_SYSROOT=\"\"\nCONFIG_BUSYBOX_DEFAULT_EXTRA_CFLAGS=\"\"\nCONFIG_BUSYBOX_DEFAULT_EXTRA_LDFLAGS=\"\"\nCONFIG_BUSYBOX_DEFAULT_EXTRA_LDLIBS=\"\"\n# CONFIG_BUSYBOX_DEFAULT_USE_PORTABLE_CODE is not set\n# CONFIG_BUSYBOX_DEFAULT_STACK_OPTIMIZATION_386 is not set\n# CONFIG_BUSYBOX_DEFAULT_STATIC_LIBGCC is not set\nCONFIG_BUSYBOX_DEFAULT_INSTALL_APPLET_SYMLINKS=y\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_APPLET_HARDLINKS is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_APPLET_SCRIPT_WRAPPERS is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_APPLET_DONT is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_SH_APPLET_SYMLINK is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_SH_APPLET_HARDLINK is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL_SH_APPLET_SCRIPT_WRAPPER is not set\nCONFIG_BUSYBOX_DEFAULT_PREFIX=\"./_install\"\n# CONFIG_BUSYBOX_DEFAULT_DEBUG is not set\n# CONFIG_BUSYBOX_DEFAULT_DEBUG_PESSIMIZE is not set\n# CONFIG_BUSYBOX_DEFAULT_DEBUG_SANITIZE is not set\n# CONFIG_BUSYBOX_DEFAULT_UNIT_TEST is not set\n# CONFIG_BUSYBOX_DEFAULT_WERROR is not set\n# CONFIG_BUSYBOX_DEFAULT_WARN_SIMPLE_MSG is not set\nCONFIG_BUSYBOX_DEFAULT_NO_DEBUG_LIB=y\n# CONFIG_BUSYBOX_DEFAULT_DMALLOC is not set\n# CONFIG_BUSYBOX_DEFAULT_EFENCE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_USE_BSS_TAIL is not set\n# CONFIG_BUSYBOX_DEFAULT_FLOAT_DURATION is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_RTMINMAX is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_RTMINMAX_USE_LIBC_DEFINITIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BUFFERS_USE_MALLOC is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_BUFFERS_GO_ON_STACK=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BUFFERS_GO_IN_BSS is not set\nCONFIG_BUSYBOX_DEFAULT_PASSWORD_MINLEN=6\nCONFIG_BUSYBOX_DEFAULT_MD5_SMALL=1\nCONFIG_BUSYBOX_DEFAULT_SHA3_SMALL=1\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FAST_TOP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_ETC_NETWORKS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_ETC_SERVICES is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_MAX_LEN=512\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_VI is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_HISTORY=256\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_SAVEHISTORY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_SAVE_ON_EXIT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_REVERSE_SEARCH is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TAB_COMPLETION=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_USERNAME_COMPLETION is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_FANCY_PROMPT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_WINCH is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_EDITING_ASK_TERMINAL is not set\n# CONFIG_BUSYBOX_DEFAULT_LOCALE_SUPPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_SUPPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_USING_LOCALE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHECK_UNICODE_IN_ENV is not set\nCONFIG_BUSYBOX_DEFAULT_SUBST_WCHAR=0\nCONFIG_BUSYBOX_DEFAULT_LAST_SUPPORTED_WCHAR=0\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_COMBINING_WCHARS is not set\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_WIDE_WCHARS is not set\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_BIDI_SUPPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_NEUTRAL_TABLE is not set\n# CONFIG_BUSYBOX_DEFAULT_UNICODE_PRESERVE_BROKEN is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_NON_POSIX_CP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VERBOSE_CP_MESSAGE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_USE_SENDFILE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_COPYBUF_KB=4\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SKIP_ROOTFS is not set\nCONFIG_BUSYBOX_DEFAULT_MONOTONIC_SYSCALL=y\nCONFIG_BUSYBOX_DEFAULT_IOCTL_HEX2STR_ERROR=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HWIB is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SEAMLESS_XZ is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SEAMLESS_LZMA is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SEAMLESS_BZ2 is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SEAMLESS_GZ=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SEAMLESS_Z is not set\n# CONFIG_BUSYBOX_DEFAULT_AR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_AR_LONG_FILENAMES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_AR_CREATE is not set\n# CONFIG_BUSYBOX_DEFAULT_UNCOMPRESS is not set\nCONFIG_BUSYBOX_DEFAULT_GUNZIP=y\nCONFIG_BUSYBOX_DEFAULT_ZCAT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_GUNZIP_LONG_OPTIONS is not set\nCONFIG_BUSYBOX_DEFAULT_BUNZIP2=y\nCONFIG_BUSYBOX_DEFAULT_BZCAT=y\n# CONFIG_BUSYBOX_DEFAULT_UNLZMA is not set\n# CONFIG_BUSYBOX_DEFAULT_LZCAT is not set\n# CONFIG_BUSYBOX_DEFAULT_LZMA is not set\n# CONFIG_BUSYBOX_DEFAULT_UNXZ is not set\n# CONFIG_BUSYBOX_DEFAULT_XZCAT is not set\n# CONFIG_BUSYBOX_DEFAULT_XZ is not set\n# CONFIG_BUSYBOX_DEFAULT_BZIP2 is not set\nCONFIG_BUSYBOX_DEFAULT_BZIP2_SMALL=0\nCONFIG_BUSYBOX_DEFAULT_FEATURE_BZIP2_DECOMPRESS=y\n# CONFIG_BUSYBOX_DEFAULT_CPIO is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CPIO_O is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CPIO_P is not set\n# CONFIG_BUSYBOX_DEFAULT_DPKG is not set\n# CONFIG_BUSYBOX_DEFAULT_DPKG_DEB is not set\nCONFIG_BUSYBOX_DEFAULT_GZIP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_GZIP_LONG_OPTIONS is not set\nCONFIG_BUSYBOX_DEFAULT_GZIP_FAST=0\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_GZIP_LEVELS is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_GZIP_DECOMPRESS=y\n# CONFIG_BUSYBOX_DEFAULT_LZOP is not set\n# CONFIG_BUSYBOX_DEFAULT_UNLZOP is not set\n# CONFIG_BUSYBOX_DEFAULT_LZOPCAT is not set\n# CONFIG_BUSYBOX_DEFAULT_LZOP_COMPR_HIGH is not set\n# CONFIG_BUSYBOX_DEFAULT_RPM is not set\n# CONFIG_BUSYBOX_DEFAULT_RPM2CPIO is not set\nCONFIG_BUSYBOX_DEFAULT_TAR=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_LONG_OPTIONS is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_CREATE=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_AUTODETECT is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_FROM=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_OLDGNU_COMPATIBILITY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_OLDSUN_COMPATIBILITY is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_GNU_EXTENSIONS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_TO_COMMAND is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_UNAME_GNAME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_NOPRESERVE_TIME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TAR_SELINUX is not set\n# CONFIG_BUSYBOX_DEFAULT_UNZIP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UNZIP_CDF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UNZIP_BZIP2 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UNZIP_LZMA is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UNZIP_XZ is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LZMA_FAST is not set\nCONFIG_BUSYBOX_DEFAULT_BASENAME=y\nCONFIG_BUSYBOX_DEFAULT_CAT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CATN is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CATV is not set\nCONFIG_BUSYBOX_DEFAULT_CHGRP=y\nCONFIG_BUSYBOX_DEFAULT_CHMOD=y\nCONFIG_BUSYBOX_DEFAULT_CHOWN=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHOWN_LONG_OPTIONS is not set\nCONFIG_BUSYBOX_DEFAULT_CHROOT=y\n# CONFIG_BUSYBOX_DEFAULT_CKSUM is not set\n# CONFIG_BUSYBOX_DEFAULT_COMM is not set\nCONFIG_BUSYBOX_DEFAULT_CP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CP_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CP_REFLINK is not set\nCONFIG_BUSYBOX_DEFAULT_CUT=y\nCONFIG_BUSYBOX_DEFAULT_DATE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DATE_ISOFMT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DATE_NANO is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DATE_COMPAT is not set\nCONFIG_BUSYBOX_DEFAULT_DD=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DD_SIGNAL_HANDLING=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DD_THIRD_STATUS_LINE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DD_IBS_OBS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DD_STATUS is not set\nCONFIG_BUSYBOX_DEFAULT_DF=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DF_FANCY is not set\nCONFIG_BUSYBOX_DEFAULT_DIRNAME=y\n# CONFIG_BUSYBOX_DEFAULT_DOS2UNIX is not set\n# CONFIG_BUSYBOX_DEFAULT_UNIX2DOS is not set\nCONFIG_BUSYBOX_DEFAULT_DU=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DU_DEFAULT_BLOCKSIZE_1K=y\nCONFIG_BUSYBOX_DEFAULT_ECHO=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FANCY_ECHO=y\nCONFIG_BUSYBOX_DEFAULT_ENV=y\n# CONFIG_BUSYBOX_DEFAULT_EXPAND is not set\n# CONFIG_BUSYBOX_DEFAULT_UNEXPAND is not set\nCONFIG_BUSYBOX_DEFAULT_EXPR=y\nCONFIG_BUSYBOX_DEFAULT_EXPR_MATH_SUPPORT_64=y\n# CONFIG_BUSYBOX_DEFAULT_FACTOR is not set\nCONFIG_BUSYBOX_DEFAULT_FALSE=y\n# CONFIG_BUSYBOX_DEFAULT_FOLD is not set\nCONFIG_BUSYBOX_DEFAULT_HEAD=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FANCY_HEAD=y\n# CONFIG_BUSYBOX_DEFAULT_HOSTID is not set\nCONFIG_BUSYBOX_DEFAULT_ID=y\n# CONFIG_BUSYBOX_DEFAULT_GROUPS is not set\n# CONFIG_BUSYBOX_DEFAULT_INSTALL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSTALL_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_LINK is not set\nCONFIG_BUSYBOX_DEFAULT_LN=y\n# CONFIG_BUSYBOX_DEFAULT_LOGNAME is not set\nCONFIG_BUSYBOX_DEFAULT_LS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_FILETYPES=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_FOLLOWLINKS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_RECURSIVE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_WIDTH=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_SORTFILES=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_TIMESTAMPS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_USERNAME=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_COLOR=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LS_COLOR_IS_DEFAULT=y\nCONFIG_BUSYBOX_DEFAULT_MD5SUM=y\n# CONFIG_BUSYBOX_DEFAULT_SHA1SUM is not set\nCONFIG_BUSYBOX_DEFAULT_SHA256SUM=y\n# CONFIG_BUSYBOX_DEFAULT_SHA512SUM is not set\n# CONFIG_BUSYBOX_DEFAULT_SHA3SUM is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MD5_SHA1_SUM_CHECK=y\nCONFIG_BUSYBOX_DEFAULT_MKDIR=y\nCONFIG_BUSYBOX_DEFAULT_MKFIFO=y\nCONFIG_BUSYBOX_DEFAULT_MKNOD=y\nCONFIG_BUSYBOX_DEFAULT_MKTEMP=y\nCONFIG_BUSYBOX_DEFAULT_MV=y\nCONFIG_BUSYBOX_DEFAULT_NICE=y\n# CONFIG_BUSYBOX_DEFAULT_NL is not set\n# CONFIG_BUSYBOX_DEFAULT_NOHUP is not set\n# CONFIG_BUSYBOX_DEFAULT_NPROC is not set\n# CONFIG_BUSYBOX_DEFAULT_OD is not set\n# CONFIG_BUSYBOX_DEFAULT_PASTE is not set\n# CONFIG_BUSYBOX_DEFAULT_PRINTENV is not set\nCONFIG_BUSYBOX_DEFAULT_PRINTF=y\nCONFIG_BUSYBOX_DEFAULT_PWD=y\nCONFIG_BUSYBOX_DEFAULT_READLINK=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_READLINK_FOLLOW=y\n# CONFIG_BUSYBOX_DEFAULT_REALPATH is not set\nCONFIG_BUSYBOX_DEFAULT_RM=y\nCONFIG_BUSYBOX_DEFAULT_RMDIR=y\nCONFIG_BUSYBOX_DEFAULT_SEQ=y\n# CONFIG_BUSYBOX_DEFAULT_SHRED is not set\n# CONFIG_BUSYBOX_DEFAULT_SHUF is not set\nCONFIG_BUSYBOX_DEFAULT_SLEEP=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FANCY_SLEEP=y\nCONFIG_BUSYBOX_DEFAULT_SORT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SORT_BIG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SORT_OPTIMIZE_MEMORY is not set\n# CONFIG_BUSYBOX_DEFAULT_SPLIT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SPLIT_FANCY is not set\n# CONFIG_BUSYBOX_DEFAULT_STAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_STAT_FORMAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_STAT_FILESYSTEM is not set\n# CONFIG_BUSYBOX_DEFAULT_STTY is not set\n# CONFIG_BUSYBOX_DEFAULT_SUM is not set\nCONFIG_BUSYBOX_DEFAULT_SYNC=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SYNC_FANCY is not set\nCONFIG_BUSYBOX_DEFAULT_FSYNC=y\n# CONFIG_BUSYBOX_DEFAULT_TAC is not set\nCONFIG_BUSYBOX_DEFAULT_TAIL=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FANCY_TAIL=y\nCONFIG_BUSYBOX_DEFAULT_TEE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TEE_USE_BLOCK_IO=y\nCONFIG_BUSYBOX_DEFAULT_TEST=y\nCONFIG_BUSYBOX_DEFAULT_TEST1=y\nCONFIG_BUSYBOX_DEFAULT_TEST2=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TEST_64=y\n# CONFIG_BUSYBOX_DEFAULT_TIMEOUT is not set\nCONFIG_BUSYBOX_DEFAULT_TOUCH=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TOUCH_NODEREF is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TOUCH_SUSV3=y\nCONFIG_BUSYBOX_DEFAULT_TR=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TR_CLASSES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TR_EQUIV is not set\nCONFIG_BUSYBOX_DEFAULT_TRUE=y\n# CONFIG_BUSYBOX_DEFAULT_TRUNCATE is not set\n# CONFIG_BUSYBOX_DEFAULT_TTY is not set\nCONFIG_BUSYBOX_DEFAULT_UNAME=y\nCONFIG_BUSYBOX_DEFAULT_UNAME_OSNAME=\"GNU/Linux\"\n# CONFIG_BUSYBOX_DEFAULT_BB_ARCH is not set\nCONFIG_BUSYBOX_DEFAULT_UNIQ=y\n# CONFIG_BUSYBOX_DEFAULT_UNLINK is not set\n# CONFIG_BUSYBOX_DEFAULT_USLEEP is not set\n# CONFIG_BUSYBOX_DEFAULT_UUDECODE is not set\n# CONFIG_BUSYBOX_DEFAULT_BASE32 is not set\n# CONFIG_BUSYBOX_DEFAULT_BASE64 is not set\n# CONFIG_BUSYBOX_DEFAULT_UUENCODE is not set\nCONFIG_BUSYBOX_DEFAULT_WC=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WC_LARGE is not set\n# CONFIG_BUSYBOX_DEFAULT_WHO is not set\n# CONFIG_BUSYBOX_DEFAULT_W is not set\n# CONFIG_BUSYBOX_DEFAULT_USERS is not set\n# CONFIG_BUSYBOX_DEFAULT_WHOAMI is not set\nCONFIG_BUSYBOX_DEFAULT_YES=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VERBOSE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_PRESERVE_HARDLINKS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_HUMAN_READABLE=y\n# CONFIG_BUSYBOX_DEFAULT_CHVT is not set\nCONFIG_BUSYBOX_DEFAULT_CLEAR=y\n# CONFIG_BUSYBOX_DEFAULT_DEALLOCVT is not set\n# CONFIG_BUSYBOX_DEFAULT_DUMPKMAP is not set\n# CONFIG_BUSYBOX_DEFAULT_FGCONSOLE is not set\n# CONFIG_BUSYBOX_DEFAULT_KBD_MODE is not set\n# CONFIG_BUSYBOX_DEFAULT_LOADFONT is not set\n# CONFIG_BUSYBOX_DEFAULT_SETFONT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SETFONT_TEXTUAL_MAP is not set\nCONFIG_BUSYBOX_DEFAULT_DEFAULT_SETFONT_DIR=\"\"\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LOADFONT_PSF2 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LOADFONT_RAW is not set\n# CONFIG_BUSYBOX_DEFAULT_LOADKMAP is not set\n# CONFIG_BUSYBOX_DEFAULT_OPENVT is not set\nCONFIG_BUSYBOX_DEFAULT_RESET=y\n# CONFIG_BUSYBOX_DEFAULT_RESIZE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_RESIZE_PRINT is not set\n# CONFIG_BUSYBOX_DEFAULT_SETCONSOLE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SETCONSOLE_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_SETKEYCODES is not set\n# CONFIG_BUSYBOX_DEFAULT_SETLOGCONS is not set\n# CONFIG_BUSYBOX_DEFAULT_SHOWKEY is not set\n# CONFIG_BUSYBOX_DEFAULT_PIPE_PROGRESS is not set\n# CONFIG_BUSYBOX_DEFAULT_RUN_PARTS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_RUN_PARTS_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_RUN_PARTS_FANCY is not set\nCONFIG_BUSYBOX_DEFAULT_START_STOP_DAEMON=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_START_STOP_DAEMON_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_START_STOP_DAEMON_FANCY is not set\nCONFIG_BUSYBOX_DEFAULT_WHICH=y\n# CONFIG_BUSYBOX_DEFAULT_MINIPS is not set\n# CONFIG_BUSYBOX_DEFAULT_NUKE is not set\n# CONFIG_BUSYBOX_DEFAULT_RESUME is not set\n# CONFIG_BUSYBOX_DEFAULT_RUN_INIT is not set\nCONFIG_BUSYBOX_DEFAULT_AWK=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_AWK_LIBM=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_AWK_GNU_EXTENSIONS=y\nCONFIG_BUSYBOX_DEFAULT_CMP=y\n# CONFIG_BUSYBOX_DEFAULT_DIFF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DIFF_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DIFF_DIR is not set\n# CONFIG_BUSYBOX_DEFAULT_ED is not set\n# CONFIG_BUSYBOX_DEFAULT_PATCH is not set\nCONFIG_BUSYBOX_DEFAULT_SED=y\nCONFIG_BUSYBOX_DEFAULT_VI=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_MAX_LEN=1024\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VI_8BIT is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_COLON=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_YANKMARK=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_SEARCH=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VI_REGEX_SEARCH is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_USE_SIGNALS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_DOT_CMD=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_READONLY=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_SETOPTS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_SET=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_WIN_RESIZE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_ASK_TERMINAL=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VI_UNDO is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VI_UNDO_QUEUE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_VI_UNDO_QUEUE_MAX=0\nCONFIG_BUSYBOX_DEFAULT_FEATURE_ALLOW_EXEC=y\nCONFIG_BUSYBOX_DEFAULT_FIND=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_PRINT0=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_MTIME=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_MMIN=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_PERM=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_TYPE=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_EXECUTABLE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_XDEV=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_MAXDEPTH=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_NEWER=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_INUM is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_EXEC=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_EXEC_PLUS is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_USER=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_GROUP=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_NOT=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_DEPTH=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_PAREN=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_SIZE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_PRUNE=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_QUIT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_DELETE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_EMPTY is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_PATH=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_REGEX=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_CONTEXT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FIND_LINKS is not set\nCONFIG_BUSYBOX_DEFAULT_GREP=y\nCONFIG_BUSYBOX_DEFAULT_EGREP=y\nCONFIG_BUSYBOX_DEFAULT_FGREP=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_GREP_CONTEXT=y\nCONFIG_BUSYBOX_DEFAULT_XARGS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_CONFIRMATION=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_QUOTES=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_TERMOPT=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_ZERO_TERM=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_REPL_STR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_PARALLEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_XARGS_SUPPORT_ARGS_FILE is not set\n# CONFIG_BUSYBOX_DEFAULT_BOOTCHARTD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BOOTCHARTD_BLOATED_HEADER is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BOOTCHARTD_CONFIG_FILE is not set\nCONFIG_BUSYBOX_DEFAULT_HALT=y\nCONFIG_BUSYBOX_DEFAULT_POWEROFF=y\nCONFIG_BUSYBOX_DEFAULT_REBOOT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WAIT_FOR_INIT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CALL_TELINIT is not set\nCONFIG_BUSYBOX_DEFAULT_TELINIT_PATH=\"\"\n# CONFIG_BUSYBOX_DEFAULT_INIT is not set\n# CONFIG_BUSYBOX_DEFAULT_LINUXRC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_USE_INITTAB is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_KILL_REMOVED is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_KILL_DELAY=0\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INIT_SCTTY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INIT_SYSLOG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INIT_QUIET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INIT_COREDUMPS is not set\nCONFIG_BUSYBOX_DEFAULT_INIT_TERMINAL_TYPE=\"\"\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INIT_MODIFY_CMDLINE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SHADOWPASSWDS=y\n# CONFIG_BUSYBOX_DEFAULT_USE_BB_PWD_GRP is not set\n# CONFIG_BUSYBOX_DEFAULT_USE_BB_SHADOW is not set\n# CONFIG_BUSYBOX_DEFAULT_USE_BB_CRYPT is not set\n# CONFIG_BUSYBOX_DEFAULT_USE_BB_CRYPT_SHA is not set\n# CONFIG_BUSYBOX_DEFAULT_ADD_SHELL is not set\n# CONFIG_BUSYBOX_DEFAULT_REMOVE_SHELL is not set\n# CONFIG_BUSYBOX_DEFAULT_ADDGROUP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_ADDUSER_TO_GROUP is not set\n# CONFIG_BUSYBOX_DEFAULT_ADDUSER is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHECK_NAMES is not set\nCONFIG_BUSYBOX_DEFAULT_LAST_ID=0\nCONFIG_BUSYBOX_DEFAULT_FIRST_SYSTEM_ID=0\nCONFIG_BUSYBOX_DEFAULT_LAST_SYSTEM_ID=0\n# CONFIG_BUSYBOX_DEFAULT_CHPASSWD is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DEFAULT_PASSWD_ALGO=\"md5\"\n# CONFIG_BUSYBOX_DEFAULT_CRYPTPW is not set\n# CONFIG_BUSYBOX_DEFAULT_MKPASSWD is not set\n# CONFIG_BUSYBOX_DEFAULT_DELUSER is not set\n# CONFIG_BUSYBOX_DEFAULT_DELGROUP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DEL_USER_FROM_GROUP is not set\n# CONFIG_BUSYBOX_DEFAULT_GETTY is not set\nCONFIG_BUSYBOX_DEFAULT_LOGIN=y\nCONFIG_BUSYBOX_DEFAULT_LOGIN_SESSION_AS_CHILD=y\n# CONFIG_BUSYBOX_DEFAULT_LOGIN_SCRIPTS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_NOLOGIN is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SECURETTY is not set\nCONFIG_BUSYBOX_DEFAULT_PASSWD=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_PASSWD_WEAK_CHECK=y\n# CONFIG_BUSYBOX_DEFAULT_SU is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SU_SYSLOG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SU_CHECKS_SHELLS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SU_BLANK_PW_NEEDS_SECURE_TTY is not set\n# CONFIG_BUSYBOX_DEFAULT_SULOGIN is not set\n# CONFIG_BUSYBOX_DEFAULT_VLOCK is not set\n# CONFIG_BUSYBOX_DEFAULT_CHATTR is not set\n# CONFIG_BUSYBOX_DEFAULT_FSCK is not set\n# CONFIG_BUSYBOX_DEFAULT_LSATTR is not set\n# CONFIG_BUSYBOX_DEFAULT_TUNE2FS is not set\n# CONFIG_BUSYBOX_DEFAULT_MODPROBE_SMALL is not set\n# CONFIG_BUSYBOX_DEFAULT_DEPMOD is not set\n# CONFIG_BUSYBOX_DEFAULT_INSMOD is not set\n# CONFIG_BUSYBOX_DEFAULT_LSMOD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LSMOD_PRETTY_2_6_OUTPUT is not set\n# CONFIG_BUSYBOX_DEFAULT_MODINFO is not set\n# CONFIG_BUSYBOX_DEFAULT_MODPROBE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MODPROBE_BLACKLIST is not set\n# CONFIG_BUSYBOX_DEFAULT_RMMOD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CMDLINE_MODULE_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_2_4_MODULES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSMOD_VERSION_CHECKING is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSMOD_KSYMOOPS_SYMBOLS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSMOD_LOADINKMEM is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSMOD_LOAD_MAP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSMOD_LOAD_MAP_FULL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHECK_TAINTED_MODULE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INSMOD_TRY_MMAP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MODUTILS_ALIAS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MODUTILS_SYMBOLS is not set\nCONFIG_BUSYBOX_DEFAULT_DEFAULT_MODULES_DIR=\"\"\nCONFIG_BUSYBOX_DEFAULT_DEFAULT_DEPMOD_FILE=\"\"\n# CONFIG_BUSYBOX_DEFAULT_ACPID is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_ACPID_COMPAT is not set\n# CONFIG_BUSYBOX_DEFAULT_BLKDISCARD is not set\n# CONFIG_BUSYBOX_DEFAULT_BLKID is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BLKID_TYPE is not set\n# CONFIG_BUSYBOX_DEFAULT_BLOCKDEV is not set\n# CONFIG_BUSYBOX_DEFAULT_CAL is not set\n# CONFIG_BUSYBOX_DEFAULT_CHRT is not set\nCONFIG_BUSYBOX_DEFAULT_DMESG=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_DMESG_PRETTY=y\n# CONFIG_BUSYBOX_DEFAULT_EJECT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_EJECT_SCSI is not set\n# CONFIG_BUSYBOX_DEFAULT_FALLOCATE is not set\n# CONFIG_BUSYBOX_DEFAULT_FATATTR is not set\n# CONFIG_BUSYBOX_DEFAULT_FBSET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FBSET_FANCY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FBSET_READMODE is not set\n# CONFIG_BUSYBOX_DEFAULT_FDFORMAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FDISK is not set\n# CONFIG_BUSYBOX_DEFAULT_FDISK_SUPPORT_LARGE_DISKS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FDISK_WRITABLE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_AIX_LABEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SGI_LABEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SUN_LABEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_OSF_LABEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_GPT_LABEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FDISK_ADVANCED is not set\n# CONFIG_BUSYBOX_DEFAULT_FINDFS is not set\nCONFIG_BUSYBOX_DEFAULT_FLOCK=y\n# CONFIG_BUSYBOX_DEFAULT_FDFLUSH is not set\n# CONFIG_BUSYBOX_DEFAULT_FREERAMDISK is not set\n# CONFIG_BUSYBOX_DEFAULT_FSCK_MINIX is not set\n# CONFIG_BUSYBOX_DEFAULT_FSFREEZE is not set\n# CONFIG_BUSYBOX_DEFAULT_FSTRIM is not set\n# CONFIG_BUSYBOX_DEFAULT_GETOPT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_GETOPT_LONG is not set\nCONFIG_BUSYBOX_DEFAULT_HEXDUMP=y\n# CONFIG_BUSYBOX_DEFAULT_HD is not set\n# CONFIG_BUSYBOX_DEFAULT_XXD is not set\nCONFIG_BUSYBOX_DEFAULT_HWCLOCK=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HWCLOCK_ADJTIME_FHS is not set\n# CONFIG_BUSYBOX_DEFAULT_IONICE is not set\n# CONFIG_BUSYBOX_DEFAULT_IPCRM is not set\n# CONFIG_BUSYBOX_DEFAULT_IPCS is not set\n# CONFIG_BUSYBOX_DEFAULT_LAST is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LAST_FANCY is not set\n# CONFIG_BUSYBOX_DEFAULT_LOSETUP is not set\n# CONFIG_BUSYBOX_DEFAULT_LSPCI is not set\n# CONFIG_BUSYBOX_DEFAULT_LSUSB is not set\n# CONFIG_BUSYBOX_DEFAULT_MDEV is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MDEV_CONF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MDEV_RENAME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MDEV_RENAME_REGEXP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MDEV_EXEC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MDEV_LOAD_FIRMWARE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MDEV_DAEMON is not set\n# CONFIG_BUSYBOX_DEFAULT_MESG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MESG_ENABLE_ONLY_GROUP is not set\n# CONFIG_BUSYBOX_DEFAULT_MKE2FS is not set\n# CONFIG_BUSYBOX_DEFAULT_MKFS_EXT2 is not set\n# CONFIG_BUSYBOX_DEFAULT_MKFS_MINIX is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MINIX2 is not set\n# CONFIG_BUSYBOX_DEFAULT_MKFS_REISER is not set\n# CONFIG_BUSYBOX_DEFAULT_MKDOSFS is not set\n# CONFIG_BUSYBOX_DEFAULT_MKFS_VFAT is not set\nCONFIG_BUSYBOX_DEFAULT_MKSWAP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MKSWAP_UUID is not set\n# CONFIG_BUSYBOX_DEFAULT_MORE is not set\nCONFIG_BUSYBOX_DEFAULT_MOUNT=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_FAKE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_VERBOSE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_HELPERS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_LABEL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_NFS is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_CIFS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_FLAGS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_FSTAB=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_OTHERTAB is not set\n# CONFIG_BUSYBOX_DEFAULT_MOUNTPOINT is not set\n# CONFIG_BUSYBOX_DEFAULT_NOLOGIN is not set\n# CONFIG_BUSYBOX_DEFAULT_NOLOGIN_DEPENDENCIES is not set\n# CONFIG_BUSYBOX_DEFAULT_NSENTER is not set\nCONFIG_BUSYBOX_DEFAULT_PIVOT_ROOT=y\n# CONFIG_BUSYBOX_DEFAULT_RDATE is not set\n# CONFIG_BUSYBOX_DEFAULT_RDEV is not set\n# CONFIG_BUSYBOX_DEFAULT_READPROFILE is not set\n# CONFIG_BUSYBOX_DEFAULT_RENICE is not set\n# CONFIG_BUSYBOX_DEFAULT_REV is not set\n# CONFIG_BUSYBOX_DEFAULT_RTCWAKE is not set\n# CONFIG_BUSYBOX_DEFAULT_SCRIPT is not set\n# CONFIG_BUSYBOX_DEFAULT_SCRIPTREPLAY is not set\n# CONFIG_BUSYBOX_DEFAULT_SETARCH is not set\n# CONFIG_BUSYBOX_DEFAULT_LINUX32 is not set\n# CONFIG_BUSYBOX_DEFAULT_LINUX64 is not set\n# CONFIG_BUSYBOX_DEFAULT_SETPRIV is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SETPRIV_DUMP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SETPRIV_CAPABILITIES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SETPRIV_CAPABILITY_NAMES is not set\n# CONFIG_BUSYBOX_DEFAULT_SETSID is not set\nCONFIG_BUSYBOX_DEFAULT_SWAPON=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SWAPON_DISCARD=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SWAPON_PRI=y\nCONFIG_BUSYBOX_DEFAULT_SWAPOFF=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SWAPONOFF_LABEL is not set\nCONFIG_BUSYBOX_DEFAULT_SWITCH_ROOT=y\n# CONFIG_BUSYBOX_DEFAULT_TASKSET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TASKSET_FANCY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TASKSET_CPULIST is not set\n# CONFIG_BUSYBOX_DEFAULT_UEVENT is not set\nCONFIG_BUSYBOX_DEFAULT_UMOUNT=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_UMOUNT_ALL=y\n# CONFIG_BUSYBOX_DEFAULT_UNSHARE is not set\n# CONFIG_BUSYBOX_DEFAULT_WALL is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_LOOP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MOUNT_LOOP_CREATE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MTAB_SUPPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_VOLUMEID is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_BCACHE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_BTRFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_CRAMFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_EROFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_EXFAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_EXT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_F2FS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_FAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_HFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_ISO9660 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_JFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_LFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_LINUXRAID is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_LINUXSWAP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_LUKS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_MINIX is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_NILFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_NTFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_OCFS2 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_REISERFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_ROMFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_SQUASHFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_SYSV is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_UBIFS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_UDF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_VOLUMEID_XFS is not set\n# CONFIG_BUSYBOX_DEFAULT_ADJTIMEX is not set\n# CONFIG_BUSYBOX_DEFAULT_BBCONFIG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_COMPRESS_BBCONFIG is not set\n# CONFIG_BUSYBOX_DEFAULT_BC is not set\n# CONFIG_BUSYBOX_DEFAULT_DC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DC_BIG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DC_LIBM is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BC_INTERACTIVE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_BC_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_BEEP is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_BEEP_FREQ=0\nCONFIG_BUSYBOX_DEFAULT_FEATURE_BEEP_LENGTH_MS=0\n# CONFIG_BUSYBOX_DEFAULT_CHAT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_NOFAIL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_TTY_HIFI is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_IMPLICIT_CR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_SWALLOW_OPTS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_SEND_ESCAPES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_VAR_ABORT_LEN is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CHAT_CLR_ABORT is not set\n# CONFIG_BUSYBOX_DEFAULT_CONSPY is not set\nCONFIG_BUSYBOX_DEFAULT_CROND=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CROND_D is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CROND_CALL_SENDMAIL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_CROND_SPECIAL_TIMES is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_CROND_DIR=\"/etc\"\nCONFIG_BUSYBOX_DEFAULT_CRONTAB=y\n# CONFIG_BUSYBOX_DEFAULT_DEVFSD is not set\n# CONFIG_BUSYBOX_DEFAULT_DEVFSD_MODLOAD is not set\n# CONFIG_BUSYBOX_DEFAULT_DEVFSD_FG_NP is not set\n# CONFIG_BUSYBOX_DEFAULT_DEVFSD_VERBOSE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_DEVFS is not set\n# CONFIG_BUSYBOX_DEFAULT_DEVMEM is not set\n# CONFIG_BUSYBOX_DEFAULT_FBSPLASH is not set\n# CONFIG_BUSYBOX_DEFAULT_FLASH_ERASEALL is not set\n# CONFIG_BUSYBOX_DEFAULT_FLASH_LOCK is not set\n# CONFIG_BUSYBOX_DEFAULT_FLASH_UNLOCK is not set\n# CONFIG_BUSYBOX_DEFAULT_FLASHCP is not set\n# CONFIG_BUSYBOX_DEFAULT_HDPARM is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HDPARM_GET_IDENTITY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HDPARM_HDIO_SCAN_HWIF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HDPARM_HDIO_UNREGISTER_HWIF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HDPARM_HDIO_DRIVE_RESET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HDPARM_HDIO_TRISTATE_HWIF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HDPARM_HDIO_GETSET_DMA is not set\n# CONFIG_BUSYBOX_DEFAULT_HEXEDIT is not set\n# CONFIG_BUSYBOX_DEFAULT_I2CGET is not set\n# CONFIG_BUSYBOX_DEFAULT_I2CSET is not set\n# CONFIG_BUSYBOX_DEFAULT_I2CDUMP is not set\n# CONFIG_BUSYBOX_DEFAULT_I2CDETECT is not set\n# CONFIG_BUSYBOX_DEFAULT_I2CTRANSFER is not set\n# CONFIG_BUSYBOX_DEFAULT_INOTIFYD is not set\nCONFIG_BUSYBOX_DEFAULT_LESS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_MAXLINES=9999999\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_BRACKETS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_FLAGS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_TRUNCATE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_MARKS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_REGEXP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_WINCH is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_ASK_TERMINAL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_DASHCMD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_LINENUMS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_RAW is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LESS_ENV is not set\nCONFIG_BUSYBOX_DEFAULT_LOCK=y\n# CONFIG_BUSYBOX_DEFAULT_LSSCSI is not set\n# CONFIG_BUSYBOX_DEFAULT_MAKEDEVS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MAKEDEVS_LEAF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_MAKEDEVS_TABLE is not set\n# CONFIG_BUSYBOX_DEFAULT_MAN is not set\n# CONFIG_BUSYBOX_DEFAULT_MICROCOM is not set\n# CONFIG_BUSYBOX_DEFAULT_MIM is not set\n# CONFIG_BUSYBOX_DEFAULT_MT is not set\n# CONFIG_BUSYBOX_DEFAULT_NANDWRITE is not set\n# CONFIG_BUSYBOX_DEFAULT_NANDDUMP is not set\n# CONFIG_BUSYBOX_DEFAULT_PARTPROBE is not set\n# CONFIG_BUSYBOX_DEFAULT_RAIDAUTORUN is not set\n# CONFIG_BUSYBOX_DEFAULT_READAHEAD is not set\n# CONFIG_BUSYBOX_DEFAULT_RFKILL is not set\n# CONFIG_BUSYBOX_DEFAULT_RUNLEVEL is not set\n# CONFIG_BUSYBOX_DEFAULT_RX is not set\n# CONFIG_BUSYBOX_DEFAULT_SETFATTR is not set\n# CONFIG_BUSYBOX_DEFAULT_SETSERIAL is not set\nCONFIG_BUSYBOX_DEFAULT_STRINGS=y\nCONFIG_BUSYBOX_DEFAULT_TIME=y\n# CONFIG_BUSYBOX_DEFAULT_TS is not set\n# CONFIG_BUSYBOX_DEFAULT_TTYSIZE is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIATTACH is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIDETACH is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIMKVOL is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIRMVOL is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIRSVOL is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIUPDATEVOL is not set\n# CONFIG_BUSYBOX_DEFAULT_UBIRENAME is not set\n# CONFIG_BUSYBOX_DEFAULT_VOLNAME is not set\n# CONFIG_BUSYBOX_DEFAULT_WATCHDOG is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IPV6=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UNIX_LOCAL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PREFER_IPV4_ADDRESS is not set\nCONFIG_BUSYBOX_DEFAULT_VERBOSE_RESOLUTION_ERRORS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TLS_SHA1 is not set\n# CONFIG_BUSYBOX_DEFAULT_ARP is not set\n# CONFIG_BUSYBOX_DEFAULT_ARPING is not set\nCONFIG_BUSYBOX_DEFAULT_BRCTL=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_BRCTL_FANCY=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_BRCTL_SHOW=y\n# CONFIG_BUSYBOX_DEFAULT_DNSD is not set\n# CONFIG_BUSYBOX_DEFAULT_ETHER_WAKE is not set\n# CONFIG_BUSYBOX_DEFAULT_FTPD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FTPD_WRITE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FTPD_ACCEPT_BROKEN_LIST is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FTPD_AUTHENTICATION is not set\n# CONFIG_BUSYBOX_DEFAULT_FTPGET is not set\n# CONFIG_BUSYBOX_DEFAULT_FTPPUT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_FTPGETPUT_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_HOSTNAME is not set\n# CONFIG_BUSYBOX_DEFAULT_DNSDOMAINNAME is not set\n# CONFIG_BUSYBOX_DEFAULT_HTTPD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_RANGES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_SETUID is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_BASIC_AUTH is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_AUTH_MD5 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_CGI is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_ENCODE_URL_STR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_ERROR_PAGES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_PROXY is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_GZIP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_ETAG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_LAST_MODIFIED is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_DATE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_HTTPD_ACL_IP is not set\nCONFIG_BUSYBOX_DEFAULT_IFCONFIG=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IFCONFIG_STATUS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFCONFIG_SLIP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFCONFIG_MEMSTART_IOADDR_IRQ is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IFCONFIG_HW=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IFCONFIG_BROADCAST_PLUS=y\n# CONFIG_BUSYBOX_DEFAULT_IFENSLAVE is not set\n# CONFIG_BUSYBOX_DEFAULT_IFPLUGD is not set\n# CONFIG_BUSYBOX_DEFAULT_IFUP is not set\n# CONFIG_BUSYBOX_DEFAULT_IFDOWN is not set\nCONFIG_BUSYBOX_DEFAULT_IFUPDOWN_IFSTATE_PATH=\"\"\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFUPDOWN_IP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFUPDOWN_IPV4 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFUPDOWN_IPV6 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFUPDOWN_MAPPING is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IFUPDOWN_EXTERNAL_DHCP is not set\n# CONFIG_BUSYBOX_DEFAULT_INETD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INETD_SUPPORT_BUILTIN_ECHO is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INETD_SUPPORT_BUILTIN_TIME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_INETD_RPC is not set\nCONFIG_BUSYBOX_DEFAULT_IP=y\n# CONFIG_BUSYBOX_DEFAULT_IPADDR is not set\n# CONFIG_BUSYBOX_DEFAULT_IPLINK is not set\n# CONFIG_BUSYBOX_DEFAULT_IPROUTE is not set\n# CONFIG_BUSYBOX_DEFAULT_IPTUNNEL is not set\n# CONFIG_BUSYBOX_DEFAULT_IPRULE is not set\n# CONFIG_BUSYBOX_DEFAULT_IPNEIGH is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IP_ADDRESS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IP_LINK=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IP_ROUTE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IP_ROUTE_DIR=\"/etc/iproute2\"\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IP_TUNNEL is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IP_RULE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IP_NEIGH=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IP_RARE_PROTOCOLS is not set\n# CONFIG_BUSYBOX_DEFAULT_IPCALC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IPCALC_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IPCALC_FANCY is not set\n# CONFIG_BUSYBOX_DEFAULT_FAKEIDENTD is not set\n# CONFIG_BUSYBOX_DEFAULT_NAMEIF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_NAMEIF_EXTENDED is not set\n# CONFIG_BUSYBOX_DEFAULT_NBDCLIENT is not set\nCONFIG_BUSYBOX_DEFAULT_NC=y\n# CONFIG_BUSYBOX_DEFAULT_NETCAT is not set\n# CONFIG_BUSYBOX_DEFAULT_NC_SERVER is not set\n# CONFIG_BUSYBOX_DEFAULT_NC_EXTRA is not set\n# CONFIG_BUSYBOX_DEFAULT_NC_110_COMPAT is not set\nCONFIG_BUSYBOX_DEFAULT_NETMSG=y\nCONFIG_BUSYBOX_DEFAULT_NETSTAT=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_NETSTAT_WIDE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_NETSTAT_PRG=y\nCONFIG_BUSYBOX_DEFAULT_NSLOOKUP=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_NSLOOKUP_BIG=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_NSLOOKUP_LONG_OPTIONS is not set\nCONFIG_BUSYBOX_DEFAULT_NTPD=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_NTPD_SERVER=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_NTPD_CONF is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_NTP_AUTH is not set\nCONFIG_BUSYBOX_DEFAULT_PING=y\nCONFIG_BUSYBOX_DEFAULT_PING6=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_FANCY_PING=y\n# CONFIG_BUSYBOX_DEFAULT_PSCAN is not set\nCONFIG_BUSYBOX_DEFAULT_ROUTE=y\n# CONFIG_BUSYBOX_DEFAULT_SLATTACH is not set\n# CONFIG_BUSYBOX_DEFAULT_SSL_CLIENT is not set\n# CONFIG_BUSYBOX_DEFAULT_TC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TC_INGRESS is not set\n# CONFIG_BUSYBOX_DEFAULT_TCPSVD is not set\n# CONFIG_BUSYBOX_DEFAULT_UDPSVD is not set\n# CONFIG_BUSYBOX_DEFAULT_TELNET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TELNET_TTYPE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TELNET_AUTOLOGIN is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TELNET_WIDTH is not set\n# CONFIG_BUSYBOX_DEFAULT_TELNETD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TELNETD_STANDALONE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TELNETD_INETD_WAIT is not set\n# CONFIG_BUSYBOX_DEFAULT_TFTP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TFTP_PROGRESS_BAR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TFTP_HPA_COMPAT is not set\n# CONFIG_BUSYBOX_DEFAULT_TFTPD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TFTP_GET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TFTP_PUT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TFTP_BLOCKSIZE is not set\n# CONFIG_BUSYBOX_DEFAULT_TFTP_DEBUG is not set\n# CONFIG_BUSYBOX_DEFAULT_TLS is not set\nCONFIG_BUSYBOX_DEFAULT_TRACEROUTE=y\nCONFIG_BUSYBOX_DEFAULT_TRACEROUTE6=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TRACEROUTE_VERBOSE=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TRACEROUTE_USE_ICMP is not set\n# CONFIG_BUSYBOX_DEFAULT_TUNCTL is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TUNCTL_UG is not set\n# CONFIG_BUSYBOX_DEFAULT_VCONFIG is not set\n# CONFIG_BUSYBOX_DEFAULT_WGET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WGET_LONG_OPTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WGET_STATUSBAR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WGET_AUTHENTICATION is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WGET_TIMEOUT is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WGET_HTTPS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_WGET_OPENSSL is not set\n# CONFIG_BUSYBOX_DEFAULT_WHOIS is not set\n# CONFIG_BUSYBOX_DEFAULT_ZCIP is not set\n# CONFIG_BUSYBOX_DEFAULT_UDHCPD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPD_BASE_IP_ON_MAC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPD_WRITE_LEASES_EARLY is not set\nCONFIG_BUSYBOX_DEFAULT_DHCPD_LEASES_FILE=\"\"\n# CONFIG_BUSYBOX_DEFAULT_DUMPLEASES is not set\n# CONFIG_BUSYBOX_DEFAULT_DHCPRELAY is not set\nCONFIG_BUSYBOX_DEFAULT_UDHCPC=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPC_ARPING is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPC_SANITIZEOPT is not set\nCONFIG_BUSYBOX_DEFAULT_UDHCPC_DEFAULT_SCRIPT=\"/usr/share/udhcpc/default.script\"\n# CONFIG_BUSYBOX_DEFAULT_UDHCPC6 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPC6_RFC3646 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPC6_RFC4704 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPC6_RFC4833 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCPC6_RFC5970 is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCP_PORT is not set\nCONFIG_BUSYBOX_DEFAULT_UDHCP_DEBUG=0\nCONFIG_BUSYBOX_DEFAULT_UDHCPC_SLACK_FOR_BUGGY_SERVERS=80\nCONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCP_RFC3397=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UDHCP_8021Q is not set\nCONFIG_BUSYBOX_DEFAULT_IFUPDOWN_UDHCPC_CMD_OPTIONS=\"\"\n# CONFIG_BUSYBOX_DEFAULT_LPD is not set\n# CONFIG_BUSYBOX_DEFAULT_LPR is not set\n# CONFIG_BUSYBOX_DEFAULT_LPQ is not set\n# CONFIG_BUSYBOX_DEFAULT_MAKEMIME is not set\n# CONFIG_BUSYBOX_DEFAULT_POPMAILDIR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_POPMAILDIR_DELIVERY is not set\n# CONFIG_BUSYBOX_DEFAULT_REFORMIME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_REFORMIME_COMPAT is not set\n# CONFIG_BUSYBOX_DEFAULT_SENDMAIL is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_MIME_CHARSET=\"\"\nCONFIG_BUSYBOX_DEFAULT_FREE=y\n# CONFIG_BUSYBOX_DEFAULT_FUSER is not set\n# CONFIG_BUSYBOX_DEFAULT_IOSTAT is not set\nCONFIG_BUSYBOX_DEFAULT_KILL=y\nCONFIG_BUSYBOX_DEFAULT_KILLALL=y\n# CONFIG_BUSYBOX_DEFAULT_KILLALL5 is not set\n# CONFIG_BUSYBOX_DEFAULT_LSOF is not set\n# CONFIG_BUSYBOX_DEFAULT_MPSTAT is not set\n# CONFIG_BUSYBOX_DEFAULT_NMETER is not set\nCONFIG_BUSYBOX_DEFAULT_PGREP=y\n# CONFIG_BUSYBOX_DEFAULT_PKILL is not set\nCONFIG_BUSYBOX_DEFAULT_PIDOF=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PIDOF_SINGLE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PIDOF_OMIT is not set\n# CONFIG_BUSYBOX_DEFAULT_PMAP is not set\n# CONFIG_BUSYBOX_DEFAULT_POWERTOP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_POWERTOP_INTERACTIVE is not set\nCONFIG_BUSYBOX_DEFAULT_PS=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_PS_WIDE=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PS_LONG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PS_TIME is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PS_UNUSUAL_SYSTEMS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_PS_ADDITIONAL_COLUMNS is not set\n# CONFIG_BUSYBOX_DEFAULT_PSTREE is not set\n# CONFIG_BUSYBOX_DEFAULT_PWDX is not set\n# CONFIG_BUSYBOX_DEFAULT_SMEMCAP is not set\nCONFIG_BUSYBOX_DEFAULT_BB_SYSCTL=y\nCONFIG_BUSYBOX_DEFAULT_TOP=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TOP_INTERACTIVE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TOP_CPU_USAGE_PERCENTAGE=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_TOP_CPU_GLOBAL_PERCENTS=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TOP_SMP_CPU is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TOP_DECIMALS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TOP_SMP_PROCESS is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_TOPMEM is not set\nCONFIG_BUSYBOX_DEFAULT_UPTIME=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_UPTIME_UTMP_SUPPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_WATCH is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SHOW_THREADS is not set\n# CONFIG_BUSYBOX_DEFAULT_CHPST is not set\n# CONFIG_BUSYBOX_DEFAULT_SETUIDGID is not set\n# CONFIG_BUSYBOX_DEFAULT_ENVUIDGID is not set\n# CONFIG_BUSYBOX_DEFAULT_ENVDIR is not set\n# CONFIG_BUSYBOX_DEFAULT_SOFTLIMIT is not set\n# CONFIG_BUSYBOX_DEFAULT_RUNSV is not set\n# CONFIG_BUSYBOX_DEFAULT_RUNSVDIR is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_RUNSVDIR_LOG is not set\n# CONFIG_BUSYBOX_DEFAULT_SV is not set\nCONFIG_BUSYBOX_DEFAULT_SV_DEFAULT_SERVICE_DIR=\"\"\n# CONFIG_BUSYBOX_DEFAULT_SVC is not set\n# CONFIG_BUSYBOX_DEFAULT_SVOK is not set\n# CONFIG_BUSYBOX_DEFAULT_SVLOGD is not set\n# CONFIG_BUSYBOX_DEFAULT_CHCON is not set\n# CONFIG_BUSYBOX_DEFAULT_GETENFORCE is not set\n# CONFIG_BUSYBOX_DEFAULT_GETSEBOOL is not set\n# CONFIG_BUSYBOX_DEFAULT_LOAD_POLICY is not set\n# CONFIG_BUSYBOX_DEFAULT_MATCHPATHCON is not set\n# CONFIG_BUSYBOX_DEFAULT_RUNCON is not set\n# CONFIG_BUSYBOX_DEFAULT_SELINUXENABLED is not set\n# CONFIG_BUSYBOX_DEFAULT_SESTATUS is not set\n# CONFIG_BUSYBOX_DEFAULT_SETENFORCE is not set\n# CONFIG_BUSYBOX_DEFAULT_SETFILES is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SETFILES_CHECK_OPTION is not set\n# CONFIG_BUSYBOX_DEFAULT_RESTORECON is not set\n# CONFIG_BUSYBOX_DEFAULT_SETSEBOOL is not set\nCONFIG_BUSYBOX_DEFAULT_SH_IS_ASH=y\n# CONFIG_BUSYBOX_DEFAULT_SH_IS_HUSH is not set\n# CONFIG_BUSYBOX_DEFAULT_SH_IS_NONE is not set\n# CONFIG_BUSYBOX_DEFAULT_BASH_IS_ASH is not set\n# CONFIG_BUSYBOX_DEFAULT_BASH_IS_HUSH is not set\nCONFIG_BUSYBOX_DEFAULT_BASH_IS_NONE=y\nCONFIG_BUSYBOX_DEFAULT_SHELL_ASH=y\nCONFIG_BUSYBOX_DEFAULT_ASH=y\n# CONFIG_BUSYBOX_DEFAULT_ASH_OPTIMIZE_FOR_SIZE is not set\nCONFIG_BUSYBOX_DEFAULT_ASH_INTERNAL_GLOB=y\nCONFIG_BUSYBOX_DEFAULT_ASH_BASH_COMPAT=y\n# CONFIG_BUSYBOX_DEFAULT_ASH_BASH_SOURCE_CURDIR is not set\n# CONFIG_BUSYBOX_DEFAULT_ASH_BASH_NOT_FOUND_HOOK is not set\nCONFIG_BUSYBOX_DEFAULT_ASH_JOB_CONTROL=y\nCONFIG_BUSYBOX_DEFAULT_ASH_ALIAS=y\n# CONFIG_BUSYBOX_DEFAULT_ASH_RANDOM_SUPPORT is not set\nCONFIG_BUSYBOX_DEFAULT_ASH_EXPAND_PRMT=y\n# CONFIG_BUSYBOX_DEFAULT_ASH_IDLE_TIMEOUT is not set\n# CONFIG_BUSYBOX_DEFAULT_ASH_MAIL is not set\nCONFIG_BUSYBOX_DEFAULT_ASH_ECHO=y\nCONFIG_BUSYBOX_DEFAULT_ASH_PRINTF=y\nCONFIG_BUSYBOX_DEFAULT_ASH_TEST=y\n# CONFIG_BUSYBOX_DEFAULT_ASH_HELP is not set\nCONFIG_BUSYBOX_DEFAULT_ASH_GETOPTS=y\nCONFIG_BUSYBOX_DEFAULT_ASH_CMDCMD=y\n# CONFIG_BUSYBOX_DEFAULT_CTTYHACK is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH is not set\n# CONFIG_BUSYBOX_DEFAULT_SHELL_HUSH is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_BASH_COMPAT is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_BRACE_EXPANSION is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_LINENO_VAR is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_BASH_SOURCE_CURDIR is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_INTERACTIVE is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_SAVEHISTORY is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_JOB is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_TICK is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_IF is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_LOOPS is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_CASE is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_FUNCTIONS is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_LOCAL is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_RANDOM_SUPPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_MODE_X is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_ECHO is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_PRINTF is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_TEST is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_HELP is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_EXPORT is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_EXPORT_N is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_READONLY is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_KILL is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_WAIT is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_COMMAND is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_TRAP is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_TYPE is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_TIMES is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_READ is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_SET is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_UNSET is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_ULIMIT is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_UMASK is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_GETOPTS is not set\n# CONFIG_BUSYBOX_DEFAULT_HUSH_MEMLEAK is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SH_MATH=y\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SH_MATH_64=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SH_MATH_BASE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SH_EXTRA_QUIET is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SH_STANDALONE is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SH_NOFORK=y\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SH_READ_FRAC is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SH_HISTFILESIZE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SH_EMBEDDED_SCRIPTS is not set\n# CONFIG_BUSYBOX_DEFAULT_KLOGD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_KLOGD_KLOGCTL is not set\nCONFIG_BUSYBOX_DEFAULT_LOGGER=y\n# CONFIG_BUSYBOX_DEFAULT_LOGREAD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_LOGREAD_REDUCED_LOCKING is not set\n# CONFIG_BUSYBOX_DEFAULT_SYSLOGD is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_ROTATE_LOGFILE is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_REMOTE_LOG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SYSLOGD_DUP is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SYSLOGD_CFG is not set\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_SYSLOGD_PRECISE_TIMESTAMPS is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_SYSLOGD_READ_BUFFER_SIZE=0\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_IPC_SYSLOG is not set\nCONFIG_BUSYBOX_DEFAULT_FEATURE_IPC_SYSLOG_BUFFER_SIZE=0\n# CONFIG_BUSYBOX_DEFAULT_FEATURE_KMSG_SYSLOG is not set\n# CONFIG_PACKAGE_busybox-selinux is not set\nCONFIG_PACKAGE_ca-bundle=y\n# CONFIG_PACKAGE_ca-certificates is not set\n# CONFIG_PACKAGE_dnsmasq is not set\n# CONFIG_PACKAGE_dnsmasq-dhcpv6 is not set\nCONFIG_PACKAGE_dnsmasq-full=y\nCONFIG_PACKAGE_dnsmasq_full_dhcp=y\n# CONFIG_PACKAGE_dnsmasq_full_dhcpv6 is not set\n# CONFIG_PACKAGE_dnsmasq_full_dnssec is not set\n# CONFIG_PACKAGE_dnsmasq_full_auth is not set\nCONFIG_PACKAGE_dnsmasq_full_ipset=y\n# CONFIG_PACKAGE_dnsmasq_full_conntrack is not set\n# CONFIG_PACKAGE_dnsmasq_full_noid is not set\n# CONFIG_PACKAGE_dnsmasq_full_broken_rtc is not set\nCONFIG_PACKAGE_dnsmasq_full_tftp=y\nCONFIG_PACKAGE_dropbear=y\n\n#\n# Configuration\n#\nCONFIG_DROPBEAR_CURVE25519=y\n# CONFIG_DROPBEAR_ECC is not set\nCONFIG_DROPBEAR_ED25519=y\nCONFIG_DROPBEAR_CHACHA20POLY1305=y\n# CONFIG_DROPBEAR_ZLIB is not set\nCONFIG_DROPBEAR_DBCLIENT=y\nCONFIG_DROPBEAR_SCP=y\n# CONFIG_DROPBEAR_ASKPASS is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_ead is not set\nCONFIG_PACKAGE_firewall=y\n# CONFIG_PACKAGE_firewall4 is not set\nCONFIG_PACKAGE_fstools=y\n# CONFIG_FSTOOLS_UBIFS_EXTROOT is not set\n# CONFIG_FSTOOLS_OVL_MOUNT_FULL_ACCESS_TIME is not set\n# CONFIG_FSTOOLS_OVL_MOUNT_COMPRESS_ZLIB is not set\nCONFIG_PACKAGE_fwtool=y\nCONFIG_PACKAGE_getrandom=y\nCONFIG_PACKAGE_jsonfilter=y\n# CONFIG_PACKAGE_libatomic is not set\nCONFIG_PACKAGE_libc=y\nCONFIG_PACKAGE_libgcc=y\n# CONFIG_PACKAGE_libgomp is not set\nCONFIG_PACKAGE_libpthread=y\nCONFIG_PACKAGE_librt=y\nCONFIG_PACKAGE_libstdcpp=y\nCONFIG_PACKAGE_logd=y\nCONFIG_PACKAGE_mtd=y\nCONFIG_PACKAGE_netifd=y\n# CONFIG_PACKAGE_nft-qos is not set\n# CONFIG_PACKAGE_om-watchdog is not set\nCONFIG_PACKAGE_openwrt-keyring=y\nCONFIG_PACKAGE_opkg=y\nCONFIG_PACKAGE_procd=y\n\n#\n# Configuration\n#\n# CONFIG_PROCD_SHOW_BOOT is not set\n# CONFIG_PROCD_ZRAM_TMPFS is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_procd-seccomp is not set\n# CONFIG_PACKAGE_procd-selinux is not set\n# CONFIG_PACKAGE_procd-ujail is not set\n# CONFIG_PACKAGE_procd-ujail-console is not set\n# CONFIG_PACKAGE_qos-scripts is not set\n# CONFIG_PACKAGE_refpolicy is not set\nCONFIG_PACKAGE_resolveip=y\nCONFIG_PACKAGE_rpcd=y\n# CONFIG_PACKAGE_rpcd-mod-file is not set\n# CONFIG_PACKAGE_rpcd-mod-iwinfo is not set\n# CONFIG_PACKAGE_rpcd-mod-rpcsys is not set\n# CONFIG_PACKAGE_selinux-policy is not set\n# CONFIG_PACKAGE_snapshot-tool is not set\n# CONFIG_PACKAGE_sqm-scripts is not set\n# CONFIG_PACKAGE_sqm-scripts-extra is not set\nCONFIG_PACKAGE_swconfig=y\nCONFIG_PACKAGE_ubox=y\nCONFIG_PACKAGE_ubus=y\nCONFIG_PACKAGE_ubusd=y\n# CONFIG_PACKAGE_ucert is not set\n# CONFIG_PACKAGE_ucert-full is not set\nCONFIG_PACKAGE_uci=y\nCONFIG_PACKAGE_urandom-seed=y\n# CONFIG_PACKAGE_urngd is not set\nCONFIG_PACKAGE_usign=y\n# CONFIG_PACKAGE_uxc is not set\n# CONFIG_PACKAGE_wireless-tools is not set\n# CONFIG_PACKAGE_zram-swap is not set\n# end of Base system\n\n#\n# Administration\n#\n\n#\n# Zabbix\n#\n# CONFIG_PACKAGE_zabbix-agentd is not set\n\n#\n# SSL support\n#\n# CONFIG_ZABBIX_OPENSSL is not set\n# CONFIG_ZABBIX_GNUTLS is not set\nCONFIG_ZABBIX_NOSSL=y\n# CONFIG_PACKAGE_zabbix-extra-network is not set\n# CONFIG_PACKAGE_zabbix-extra-wifi is not set\n# CONFIG_PACKAGE_zabbix-get is not set\n# CONFIG_PACKAGE_zabbix-proxy is not set\n# CONFIG_PACKAGE_zabbix-sender is not set\n# CONFIG_PACKAGE_zabbix-server is not set\n\n#\n# Database Software\n#\n# CONFIG_ZABBIX_MYSQL is not set\nCONFIG_ZABBIX_POSTGRESQL=y\n# CONFIG_PACKAGE_zabbix-server-frontend is not set\n# end of Zabbix\n\n#\n# openwisp\n#\n# CONFIG_PACKAGE_openwisp-config-mbedtls is not set\n# CONFIG_PACKAGE_openwisp-config-nossl is not set\n# CONFIG_PACKAGE_openwisp-config-openssl is not set\n# CONFIG_PACKAGE_openwisp-config-wolfssl is not set\n# end of openwisp\n\n# CONFIG_PACKAGE_atop is not set\n# CONFIG_PACKAGE_backuppc is not set\n# CONFIG_PACKAGE_debian-archive-keyring is not set\n# CONFIG_PACKAGE_debootstrap is not set\n# CONFIG_PACKAGE_gkrellmd is not set\nCONFIG_PACKAGE_htop=y\n# CONFIG_PACKAGE_ipmitool is not set\n# CONFIG_PACKAGE_monit is not set\n# CONFIG_PACKAGE_monit-nossl is not set\n# CONFIG_PACKAGE_muninlite is not set\n# CONFIG_PACKAGE_netatop is not set\nCONFIG_PACKAGE_netdata=y\n# CONFIG_PACKAGE_nyx is not set\n# CONFIG_PACKAGE_schroot is not set\n\n#\n# Configuration\n#\n# CONFIG_SCHROOT_BTRFS is not set\n# CONFIG_SCHROOT_LOOPBACK is not set\n# CONFIG_SCHROOT_LVM is not set\n# CONFIG_SCHROOT_UUID is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_sudo is not set\n# CONFIG_PACKAGE_syslog-ng is not set\n# end of Administration\n\n#\n# Boot Loaders\n#\n# end of Boot Loaders\n\n#\n# Development\n#\n\n#\n# Libraries\n#\n# CONFIG_PACKAGE_libncurses-dev is not set\n# CONFIG_PACKAGE_libxml2-dev is not set\n# CONFIG_PACKAGE_zlib-dev is not set\n# end of Libraries\n\n# CONFIG_PACKAGE_ar is not set\n# CONFIG_PACKAGE_autoconf is not set\n# CONFIG_PACKAGE_automake is not set\n# CONFIG_PACKAGE_binutils is not set\n# CONFIG_PACKAGE_diffutils is not set\n# CONFIG_PACKAGE_gcc is not set\n# CONFIG_PACKAGE_gdb is not set\n# CONFIG_PACKAGE_gdbserver is not set\n# CONFIG_PACKAGE_gitlab-runner is not set\n# CONFIG_PACKAGE_libtool-bin is not set\n# CONFIG_PACKAGE_lpc21isp is not set\n# CONFIG_PACKAGE_lttng-tools is not set\n# CONFIG_PACKAGE_m4 is not set\n# CONFIG_PACKAGE_make is not set\n# CONFIG_PACKAGE_meson is not set\n# CONFIG_PACKAGE_ninja is not set\n# CONFIG_PACKAGE_objdump is not set\n# CONFIG_PACKAGE_packr is not set\n# CONFIG_PACKAGE_patch is not set\n# CONFIG_PACKAGE_pkg-config is not set\n# CONFIG_PACKAGE_pkgconf is not set\n# CONFIG_PACKAGE_trace-cmd is not set\n# CONFIG_PACKAGE_trace-cmd-extra is not set\n# CONFIG_PACKAGE_valgrind is not set\n# end of Development\n\n#\n# Extra packages\n#\n# CONFIG_PACKAGE_automount is not set\n# CONFIG_PACKAGE_autosamba is not set\n# CONFIG_PACKAGE_ipv6helper is not set\n# CONFIG_PACKAGE_jose is not set\n# CONFIG_PACKAGE_k3wifi is not set\n# CONFIG_PACKAGE_libjose is not set\n# CONFIG_PACKAGE_nginx is not set\n# CONFIG_PACKAGE_nginx-mod-luci-ssl is not set\n# CONFIG_PACKAGE_nginx-util is not set\n# CONFIG_PACKAGE_tang is not set\n# end of Extra packages\n\n#\n# Firmware\n#\n\n#\n# ath10k Board-Specific Overrides\n#\n# end of ath10k Board-Specific Overrides\n\n# CONFIG_PACKAGE_aircard-pcmcia-firmware is not set\n# CONFIG_PACKAGE_amdgpu-firmware is not set\n# CONFIG_PACKAGE_ar3k-firmware is not set\n# CONFIG_PACKAGE_ath10k-board-qca4019 is not set\n# CONFIG_PACKAGE_ath10k-board-qca9377 is not set\n# CONFIG_PACKAGE_ath10k-board-qca9887 is not set\n# CONFIG_PACKAGE_ath10k-board-qca9888 is not set\n# CONFIG_PACKAGE_ath10k-board-qca988x is not set\n# CONFIG_PACKAGE_ath10k-board-qca9984 is not set\n# CONFIG_PACKAGE_ath10k-board-qca99x0 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca4019 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca4019-ct is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca4019-ct-full-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca4019-ct-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca6174 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9377 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9887 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9887-ct is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9887-ct-full-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9888 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9888-ct is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9888-ct-full-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9888-ct-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca988x is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca988x-ct is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca988x-ct-full-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9984 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9984-ct is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9984-ct-full-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca9984-ct-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca99x0 is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca99x0-ct is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca99x0-ct-full-htt is not set\n# CONFIG_PACKAGE_ath10k-firmware-qca99x0-ct-htt is not set\n# CONFIG_PACKAGE_ath11k-firmware-ipq6018 is not set\n# CONFIG_PACKAGE_ath11k-firmware-ipq8074 is not set\n# CONFIG_PACKAGE_ath11k-firmware-qca6390 is not set\n# CONFIG_PACKAGE_ath11k-firmware-qcn9074 is not set\n# CONFIG_PACKAGE_ath6k-firmware is not set\n# CONFIG_PACKAGE_ath9k-htc-firmware is not set\n# CONFIG_PACKAGE_b43legacy-firmware is not set\n# CONFIG_PACKAGE_bnx2-firmware is not set\n# CONFIG_PACKAGE_bnx2x-firmware is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-4329-sdio is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-43430-sdio-rpi-3b is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-43430-sdio-rpi-zero-w is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-43430a0-sdio is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-43455-sdio-rpi-3b-plus is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-43455-sdio-rpi-4b is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-43602a1-pcie is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-4366b1-pcie is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-4366c0-pcie is not set\n# CONFIG_PACKAGE_brcmfmac-firmware-usb is not set\n# CONFIG_PACKAGE_brcmsmac-firmware is not set\n# CONFIG_PACKAGE_carl9170-firmware is not set\n# CONFIG_PACKAGE_cypress-firmware-43012-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-43340-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-43362-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-4339-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-43430-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-43455-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-4354-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-4356-pcie is not set\n# CONFIG_PACKAGE_cypress-firmware-4356-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-43570-pcie is not set\n# CONFIG_PACKAGE_cypress-firmware-4359-pcie is not set\n# CONFIG_PACKAGE_cypress-firmware-4359-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-4373-sdio is not set\n# CONFIG_PACKAGE_cypress-firmware-4373-usb is not set\n# CONFIG_PACKAGE_cypress-firmware-54591-pcie is not set\n# CONFIG_PACKAGE_cypress-firmware-89459-pcie is not set\n# CONFIG_PACKAGE_e100-firmware is not set\n# CONFIG_PACKAGE_edgeport-firmware is not set\n# CONFIG_PACKAGE_eip197-mini-firmware is not set\n# CONFIG_PACKAGE_ibt-firmware is not set\n# CONFIG_PACKAGE_iwl3945-firmware is not set\n# CONFIG_PACKAGE_iwl4965-firmware is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl100 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl1000 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl105 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl135 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl2000 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl2030 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl3160 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl3168 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl5000 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl5150 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl6000g2 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl6000g2a is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl6000g2b is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl6050 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl7260 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl7265 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl7265d is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl8260c is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl8265 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl9000 is not set\n# CONFIG_PACKAGE_iwlwifi-firmware-iwl9260 is not set\n# CONFIG_PACKAGE_jboot-tools is not set\n# CONFIG_PACKAGE_libertas-sdio-firmware is not set\n# CONFIG_PACKAGE_libertas-spi-firmware is not set\n# CONFIG_PACKAGE_libertas-usb-firmware is not set\n# CONFIG_PACKAGE_mt7601u-firmware is not set\n# CONFIG_PACKAGE_mt7622bt-firmware is not set\n# CONFIG_PACKAGE_mwifiex-pcie-firmware is not set\n# CONFIG_PACKAGE_mwifiex-sdio-firmware is not set\n# CONFIG_PACKAGE_mwl8k-firmware is not set\n# CONFIG_PACKAGE_p54-pci-firmware is not set\n# CONFIG_PACKAGE_p54-spi-firmware is not set\n# CONFIG_PACKAGE_p54-usb-firmware is not set\n# CONFIG_PACKAGE_prism54-firmware is not set\n# CONFIG_PACKAGE_qtn-firmware is not set\n# CONFIG_PACKAGE_qtn-proto is not set\n# CONFIG_PACKAGE_qtn-utils is not set\n# CONFIG_PACKAGE_r8169-firmware is not set\n# CONFIG_PACKAGE_radeon-firmware is not set\n# CONFIG_PACKAGE_rs9113-firmware is not set\n# CONFIG_PACKAGE_rt2800-pci-firmware is not set\n# CONFIG_PACKAGE_rt2800-usb-firmware is not set\n# CONFIG_PACKAGE_rt61-pci-firmware is not set\n# CONFIG_PACKAGE_rt73-usb-firmware is not set\n# CONFIG_PACKAGE_rtl8188eu-firmware is not set\n# CONFIG_PACKAGE_rtl8192ce-firmware is not set\n# CONFIG_PACKAGE_rtl8192cu-firmware is not set\n# CONFIG_PACKAGE_rtl8192de-firmware is not set\n# CONFIG_PACKAGE_rtl8192eu-firmware is not set\n# CONFIG_PACKAGE_rtl8192se-firmware is not set\n# CONFIG_PACKAGE_rtl8192su-firmware is not set\n# CONFIG_PACKAGE_rtl8723au-firmware is not set\n# CONFIG_PACKAGE_rtl8723bs-firmware is not set\n# CONFIG_PACKAGE_rtl8723bu-firmware is not set\n# CONFIG_PACKAGE_rtl8821ae-firmware is not set\n# CONFIG_PACKAGE_rtl8822be-firmware is not set\n# CONFIG_PACKAGE_rtl8822ce-firmware is not set\n# CONFIG_PACKAGE_ti-3410-firmware is not set\n# CONFIG_PACKAGE_ti-5052-firmware is not set\n# CONFIG_PACKAGE_wil6210-firmware is not set\n# CONFIG_PACKAGE_wireless-regdb is not set\n# CONFIG_PACKAGE_wl12xx-firmware is not set\n# CONFIG_PACKAGE_wl18xx-firmware is not set\n# end of Firmware\n\n#\n# Fonts\n#\n\n#\n# DejaVu\n#\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuMathTeXGyre is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSans is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSans-Bold is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSans-BoldOblique is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSans-ExtraLight is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSans-Oblique is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansCondensed is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansCondensed-Bold is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansCondensed-BoldOblique is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansCondensed-Oblique is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansMono is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansMono-Bold is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansMono-BoldOblique is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSansMono-Oblique is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerif is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerif-Bold is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerif-BoldItalic is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerif-Italic is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerifCondensed is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerifCondensed-Bold is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerifCondensed-BoldItalic is not set\n# CONFIG_PACKAGE_dejavu-fonts-ttf-DejaVuSerifCondensed-Italic is not set\n# end of DejaVu\n# end of Fonts\n\n#\n# Kernel modules\n#\n\n#\n# Block Devices\n#\n# CONFIG_PACKAGE_kmod-aoe is not set\n# CONFIG_PACKAGE_kmod-ata-ahci is not set\n# CONFIG_PACKAGE_kmod-ata-artop is not set\n# CONFIG_PACKAGE_kmod-ata-core is not set\n# CONFIG_PACKAGE_kmod-ata-marvell-sata is not set\n# CONFIG_PACKAGE_kmod-ata-nvidia-sata is not set\n# CONFIG_PACKAGE_kmod-ata-pdc202xx-old is not set\n# CONFIG_PACKAGE_kmod-ata-piix is not set\n# CONFIG_PACKAGE_kmod-ata-sil is not set\n# CONFIG_PACKAGE_kmod-ata-sil24 is not set\n# CONFIG_PACKAGE_kmod-ata-via-sata is not set\n# CONFIG_PACKAGE_kmod-block2mtd is not set\n# CONFIG_PACKAGE_kmod-dax is not set\n# CONFIG_PACKAGE_kmod-dm is not set\n# CONFIG_PACKAGE_kmod-dm-raid is not set\n# CONFIG_PACKAGE_kmod-iosched-bfq is not set\n# CONFIG_PACKAGE_kmod-iscsi-initiator is not set\n# CONFIG_PACKAGE_kmod-loop is not set\n# CONFIG_PACKAGE_kmod-md-mod is not set\n# CONFIG_PACKAGE_kmod-nbd is not set\n# CONFIG_PACKAGE_kmod-scsi-cdrom is not set\nCONFIG_PACKAGE_kmod-scsi-core=y\n# CONFIG_PACKAGE_kmod-scsi-generic is not set\n# CONFIG_PACKAGE_kmod-scsi-tape is not set\n# end of Block Devices\n\n#\n# CAN Support\n#\n# CONFIG_PACKAGE_kmod-can is not set\n# end of CAN Support\n\n#\n# Cryptographic API modules\n#\nCONFIG_PACKAGE_kmod-crypto-acompress=y\nCONFIG_PACKAGE_kmod-crypto-aead=y\nCONFIG_PACKAGE_kmod-crypto-arc4=y\nCONFIG_PACKAGE_kmod-crypto-authenc=y\n# CONFIG_PACKAGE_kmod-crypto-cbc is not set\nCONFIG_PACKAGE_kmod-crypto-ccm=y\nCONFIG_PACKAGE_kmod-crypto-cmac=y\nCONFIG_PACKAGE_kmod-crypto-crc32c=y\nCONFIG_PACKAGE_kmod-crypto-ctr=y\n# CONFIG_PACKAGE_kmod-crypto-cts is not set\n# CONFIG_PACKAGE_kmod-crypto-deflate is not set\nCONFIG_PACKAGE_kmod-crypto-des=y\nCONFIG_PACKAGE_kmod-crypto-ecb=y\n# CONFIG_PACKAGE_kmod-crypto-ecdh is not set\n# CONFIG_PACKAGE_kmod-crypto-echainiv is not set\n# CONFIG_PACKAGE_kmod-crypto-fcrypt is not set\n# CONFIG_PACKAGE_kmod-crypto-gcm is not set\n# CONFIG_PACKAGE_kmod-crypto-gf128 is not set\n# CONFIG_PACKAGE_kmod-crypto-ghash is not set\nCONFIG_PACKAGE_kmod-crypto-hash=y\nCONFIG_PACKAGE_kmod-crypto-hmac=y\nCONFIG_PACKAGE_kmod-crypto-hw-eip93=y\n# CONFIG_PACKAGE_kmod-crypto-hw-hifn-795x is not set\n# CONFIG_PACKAGE_kmod-crypto-hw-padlock is not set\n# CONFIG_PACKAGE_kmod-crypto-kpp is not set\nCONFIG_PACKAGE_kmod-crypto-manager=y\nCONFIG_PACKAGE_kmod-crypto-md4=y\nCONFIG_PACKAGE_kmod-crypto-md5=y\n# CONFIG_PACKAGE_kmod-crypto-michael-mic is not set\n# CONFIG_PACKAGE_kmod-crypto-misc is not set\nCONFIG_PACKAGE_kmod-crypto-null=y\n# CONFIG_PACKAGE_kmod-crypto-pcbc is not set\n# CONFIG_PACKAGE_kmod-crypto-rmd160 is not set\nCONFIG_PACKAGE_kmod-crypto-rng=y\nCONFIG_PACKAGE_kmod-crypto-seqiv=y\nCONFIG_PACKAGE_kmod-crypto-sha1=y\nCONFIG_PACKAGE_kmod-crypto-sha256=y\nCONFIG_PACKAGE_kmod-crypto-sha512=y\n# CONFIG_PACKAGE_kmod-crypto-test is not set\nCONFIG_PACKAGE_kmod-crypto-user=y\n# CONFIG_PACKAGE_kmod-crypto-xcbc is not set\n# CONFIG_PACKAGE_kmod-crypto-xts is not set\nCONFIG_PACKAGE_kmod-cryptodev=y\n# end of Cryptographic API modules\n\n#\n# Filesystems\n#\n# CONFIG_PACKAGE_kmod-fs-afs is not set\n# CONFIG_PACKAGE_kmod-fs-antfs is not set\n# CONFIG_PACKAGE_kmod-fs-autofs4 is not set\nCONFIG_PACKAGE_kmod-fs-btrfs=y\nCONFIG_PACKAGE_kmod-fs-cifs=y\n# CONFIG_PACKAGE_kmod-fs-configfs is not set\n# CONFIG_PACKAGE_kmod-fs-cramfs is not set\nCONFIG_PACKAGE_kmod-fs-exfat=y\n# CONFIG_PACKAGE_kmod-fs-exportfs is not set\nCONFIG_PACKAGE_kmod-fs-ext4=y\n# CONFIG_PACKAGE_kmod-fs-f2fs is not set\n# CONFIG_PACKAGE_kmod-fs-fscache is not set\n# CONFIG_PACKAGE_kmod-fs-hfs is not set\n# CONFIG_PACKAGE_kmod-fs-hfsplus is not set\n# CONFIG_PACKAGE_kmod-fs-isofs is not set\n# CONFIG_PACKAGE_kmod-fs-jfs is not set\n# CONFIG_PACKAGE_kmod-fs-ksmbd is not set\n# CONFIG_PACKAGE_kmod-fs-minix is not set\n# CONFIG_PACKAGE_kmod-fs-msdos is not set\n# CONFIG_PACKAGE_kmod-fs-nfs is not set\n# CONFIG_PACKAGE_kmod-fs-nfs-common is not set\n# CONFIG_PACKAGE_kmod-fs-nfs-common-rpcsec is not set\n# CONFIG_PACKAGE_kmod-fs-nfs-v3 is not set\n# CONFIG_PACKAGE_kmod-fs-nfs-v4 is not set\n# CONFIG_PACKAGE_kmod-fs-nfsd is not set\nCONFIG_PACKAGE_kmod-fs-ntfs=y\n# CONFIG_PACKAGE_kmod-fs-ntfs3 is not set\n# CONFIG_PACKAGE_kmod-fs-reiserfs is not set\n# CONFIG_PACKAGE_kmod-fs-squashfs is not set\n# CONFIG_PACKAGE_kmod-fs-udf is not set\n# CONFIG_PACKAGE_kmod-fs-vfat is not set\n# CONFIG_PACKAGE_kmod-fs-xfs is not set\n# CONFIG_PACKAGE_kmod-fuse is not set\n# end of Filesystems\n\n#\n# FireWire support\n#\n# CONFIG_PACKAGE_kmod-firewire is not set\n# end of FireWire support\n\n#\n# Hardware Monitoring Support\n#\n# CONFIG_PACKAGE_kmod-gl-mifi-mcu is not set\n# CONFIG_PACKAGE_kmod-hwmon-ad7418 is not set\n# CONFIG_PACKAGE_kmod-hwmon-adcxx is not set\n# CONFIG_PACKAGE_kmod-hwmon-ads1015 is not set\n# CONFIG_PACKAGE_kmod-hwmon-adt7410 is not set\n# CONFIG_PACKAGE_kmod-hwmon-adt7475 is not set\n# CONFIG_PACKAGE_kmod-hwmon-core is not set\n# CONFIG_PACKAGE_kmod-hwmon-dme1737 is not set\n# CONFIG_PACKAGE_kmod-hwmon-drivetemp is not set\n# CONFIG_PACKAGE_kmod-hwmon-emc2305 is not set\n# CONFIG_PACKAGE_kmod-hwmon-gpiofan is not set\n# CONFIG_PACKAGE_kmod-hwmon-ina209 is not set\n# CONFIG_PACKAGE_kmod-hwmon-ina2xx is not set\n# CONFIG_PACKAGE_kmod-hwmon-it87 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm63 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm75 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm77 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm85 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm90 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm92 is not set\n# CONFIG_PACKAGE_kmod-hwmon-lm95241 is not set\n# CONFIG_PACKAGE_kmod-hwmon-ltc4151 is not set\n# CONFIG_PACKAGE_kmod-hwmon-mcp3021 is not set\n# CONFIG_PACKAGE_kmod-hwmon-pwmfan is not set\n# CONFIG_PACKAGE_kmod-hwmon-sch5627 is not set\n# CONFIG_PACKAGE_kmod-hwmon-sht21 is not set\n# CONFIG_PACKAGE_kmod-hwmon-tmp102 is not set\n# CONFIG_PACKAGE_kmod-hwmon-tmp103 is not set\n# CONFIG_PACKAGE_kmod-hwmon-tmp421 is not set\n# CONFIG_PACKAGE_kmod-hwmon-vid is not set\n# CONFIG_PACKAGE_kmod-hwmon-w83793 is not set\n# CONFIG_PACKAGE_kmod-pmbus-core is not set\n# CONFIG_PACKAGE_kmod-pmbus-zl6100 is not set\n# end of Hardware Monitoring Support\n\n#\n# I2C support\n#\n# CONFIG_PACKAGE_kmod-i2c-algo-bit is not set\n# CONFIG_PACKAGE_kmod-i2c-algo-pca is not set\n# CONFIG_PACKAGE_kmod-i2c-algo-pcf is not set\n# CONFIG_PACKAGE_kmod-i2c-core is not set\n# CONFIG_PACKAGE_kmod-i2c-designware-pci is not set\n# CONFIG_PACKAGE_kmod-i2c-gpio is not set\n# CONFIG_PACKAGE_kmod-i2c-mux is not set\n# CONFIG_PACKAGE_kmod-i2c-mux-gpio is not set\n# CONFIG_PACKAGE_kmod-i2c-mux-pca9541 is not set\n# CONFIG_PACKAGE_kmod-i2c-mux-pca954x is not set\n# CONFIG_PACKAGE_kmod-i2c-pxa is not set\n# CONFIG_PACKAGE_kmod-i2c-smbus is not set\n# CONFIG_PACKAGE_kmod-i2c-tiny-usb is not set\n# end of I2C support\n\n#\n# Industrial I/O Modules\n#\n# CONFIG_PACKAGE_kmod-iio-ad799x is not set\n# CONFIG_PACKAGE_kmod-iio-am2315 is not set\n# CONFIG_PACKAGE_kmod-iio-bh1750 is not set\n# CONFIG_PACKAGE_kmod-iio-bme680 is not set\n# CONFIG_PACKAGE_kmod-iio-bme680-i2c is not set\n# CONFIG_PACKAGE_kmod-iio-bme680-spi is not set\n# CONFIG_PACKAGE_kmod-iio-bmp280 is not set\n# CONFIG_PACKAGE_kmod-iio-bmp280-i2c is not set\n# CONFIG_PACKAGE_kmod-iio-bmp280-spi is not set\n# CONFIG_PACKAGE_kmod-iio-ccs811 is not set\n# CONFIG_PACKAGE_kmod-iio-core is not set\n# CONFIG_PACKAGE_kmod-iio-dht11 is not set\n# CONFIG_PACKAGE_kmod-iio-fxas21002c is not set\n# CONFIG_PACKAGE_kmod-iio-fxas21002c-i2c is not set\n# CONFIG_PACKAGE_kmod-iio-fxas21002c-spi is not set\n# CONFIG_PACKAGE_kmod-iio-fxos8700 is not set\n# CONFIG_PACKAGE_kmod-iio-fxos8700-i2c is not set\n# CONFIG_PACKAGE_kmod-iio-fxos8700-spi is not set\n# CONFIG_PACKAGE_kmod-iio-hmc5843 is not set\n# CONFIG_PACKAGE_kmod-iio-htu21 is not set\n# CONFIG_PACKAGE_kmod-iio-kfifo-buf is not set\n# CONFIG_PACKAGE_kmod-iio-lsm6dsx is not set\n# CONFIG_PACKAGE_kmod-iio-lsm6dsx-i2c is not set\n# CONFIG_PACKAGE_kmod-iio-lsm6dsx-spi is not set\n# CONFIG_PACKAGE_kmod-iio-si7020 is not set\n# CONFIG_PACKAGE_kmod-iio-sps30 is not set\n# CONFIG_PACKAGE_kmod-iio-st_accel is not set\n# CONFIG_PACKAGE_kmod-iio-st_accel-i2c is not set\n# CONFIG_PACKAGE_kmod-iio-st_accel-spi is not set\n# CONFIG_PACKAGE_kmod-iio-tsl4531 is not set\n# CONFIG_PACKAGE_kmod-industrialio-triggered-buffer is not set\n# end of Industrial I/O Modules\n\n#\n# Input modules\n#\n# CONFIG_PACKAGE_kmod-hid is not set\n# CONFIG_PACKAGE_kmod-hid-generic is not set\n# CONFIG_PACKAGE_kmod-input-core is not set\n# CONFIG_PACKAGE_kmod-input-evdev is not set\n# CONFIG_PACKAGE_kmod-input-gpio-encoder is not set\n# CONFIG_PACKAGE_kmod-input-gpio-keys is not set\n# CONFIG_PACKAGE_kmod-input-gpio-keys-polled is not set\n# CONFIG_PACKAGE_kmod-input-joydev is not set\n# CONFIG_PACKAGE_kmod-input-matrixkmap is not set\n# CONFIG_PACKAGE_kmod-input-polldev is not set\n# CONFIG_PACKAGE_kmod-input-touchscreen-ads7846 is not set\n# CONFIG_PACKAGE_kmod-input-uinput is not set\n# end of Input modules\n\n#\n# LED modules\n#\n# CONFIG_PACKAGE_kmod-input-leds is not set\nCONFIG_PACKAGE_kmod-leds-gpio=y\n# CONFIG_PACKAGE_kmod-leds-pca963x is not set\n# CONFIG_PACKAGE_kmod-leds-uleds is not set\n# CONFIG_PACKAGE_kmod-ledtrig-activity is not set\n# CONFIG_PACKAGE_kmod-ledtrig-audio is not set\n# CONFIG_PACKAGE_kmod-ledtrig-gpio is not set\n# CONFIG_PACKAGE_kmod-ledtrig-oneshot is not set\n# CONFIG_PACKAGE_kmod-ledtrig-transient is not set\n# end of LED modules\n\n#\n# Libraries\n#\nCONFIG_PACKAGE_kmod-asn1-decoder=y\n# CONFIG_PACKAGE_kmod-lib-cordic is not set\nCONFIG_PACKAGE_kmod-lib-crc-ccitt=y\n# CONFIG_PACKAGE_kmod-lib-crc-itu-t is not set\nCONFIG_PACKAGE_kmod-lib-crc16=y\nCONFIG_PACKAGE_kmod-lib-crc32c=y\n# CONFIG_PACKAGE_kmod-lib-crc7 is not set\n# CONFIG_PACKAGE_kmod-lib-crc8 is not set\n# CONFIG_PACKAGE_kmod-lib-lz4 is not set\nCONFIG_PACKAGE_kmod-lib-lzo=y\nCONFIG_PACKAGE_kmod-lib-raid6=y\nCONFIG_PACKAGE_kmod-lib-textsearch=y\nCONFIG_PACKAGE_kmod-lib-xor=y\nCONFIG_PACKAGE_kmod-lib-zlib-deflate=y\nCONFIG_PACKAGE_kmod-lib-zlib-inflate=y\nCONFIG_PACKAGE_kmod-lib-zstd=y\n# end of Libraries\n\n#\n# Native Language Support\n#\nCONFIG_PACKAGE_kmod-nls-base=y\n# CONFIG_PACKAGE_kmod-nls-cp1250 is not set\n# CONFIG_PACKAGE_kmod-nls-cp1251 is not set\n# CONFIG_PACKAGE_kmod-nls-cp437 is not set\n# CONFIG_PACKAGE_kmod-nls-cp775 is not set\n# CONFIG_PACKAGE_kmod-nls-cp850 is not set\n# CONFIG_PACKAGE_kmod-nls-cp852 is not set\n# CONFIG_PACKAGE_kmod-nls-cp862 is not set\n# CONFIG_PACKAGE_kmod-nls-cp864 is not set\n# CONFIG_PACKAGE_kmod-nls-cp866 is not set\n# CONFIG_PACKAGE_kmod-nls-cp932 is not set\n# CONFIG_PACKAGE_kmod-nls-cp936 is not set\n# CONFIG_PACKAGE_kmod-nls-cp950 is not set\n# CONFIG_PACKAGE_kmod-nls-iso8859-1 is not set\n# CONFIG_PACKAGE_kmod-nls-iso8859-13 is not set\n# CONFIG_PACKAGE_kmod-nls-iso8859-15 is not set\n# CONFIG_PACKAGE_kmod-nls-iso8859-2 is not set\n# CONFIG_PACKAGE_kmod-nls-iso8859-6 is not set\n# CONFIG_PACKAGE_kmod-nls-iso8859-8 is not set\n# CONFIG_PACKAGE_kmod-nls-koi8r is not set\nCONFIG_PACKAGE_kmod-nls-utf8=y\n# end of Native Language Support\n\n#\n# Netfilter Extensions\n#\n# CONFIG_PACKAGE_kmod-arptables is not set\n# CONFIG_PACKAGE_kmod-br-netfilter is not set\n# CONFIG_PACKAGE_kmod-ebtables is not set\n# CONFIG_PACKAGE_kmod-ebtables-ipv4 is not set\n# CONFIG_PACKAGE_kmod-ebtables-ipv6 is not set\n# CONFIG_PACKAGE_kmod-ebtables-watchers is not set\nCONFIG_PACKAGE_kmod-ip6tables=y\n# CONFIG_PACKAGE_kmod-ip6tables-extra is not set\n# CONFIG_PACKAGE_kmod-ipt-account is not set\n# CONFIG_PACKAGE_kmod-ipt-chaos is not set\n# CONFIG_PACKAGE_kmod-ipt-checksum is not set\n# CONFIG_PACKAGE_kmod-ipt-cluster is not set\n# CONFIG_PACKAGE_kmod-ipt-clusterip is not set\n# CONFIG_PACKAGE_kmod-ipt-compat-xtables is not set\n# CONFIG_PACKAGE_kmod-ipt-condition is not set\nCONFIG_PACKAGE_kmod-ipt-conntrack=y\n# CONFIG_PACKAGE_kmod-ipt-conntrack-extra is not set\n# CONFIG_PACKAGE_kmod-ipt-conntrack-label is not set\nCONFIG_PACKAGE_kmod-ipt-core=y\n# CONFIG_PACKAGE_kmod-ipt-debug is not set\n# CONFIG_PACKAGE_kmod-ipt-delude is not set\n# CONFIG_PACKAGE_kmod-ipt-dhcpmac is not set\n# CONFIG_PACKAGE_kmod-ipt-dnetmap is not set\n# CONFIG_PACKAGE_kmod-ipt-extra is not set\n# CONFIG_PACKAGE_kmod-ipt-filter is not set\nCONFIG_PACKAGE_kmod-ipt-fullconenat=y\n# CONFIG_PACKAGE_kmod-ipt-fuzzy is not set\n# CONFIG_PACKAGE_kmod-ipt-geoip is not set\n# CONFIG_PACKAGE_kmod-ipt-hashlimit is not set\n# CONFIG_PACKAGE_kmod-ipt-iface is not set\n# CONFIG_PACKAGE_kmod-ipt-ipmark is not set\n# CONFIG_PACKAGE_kmod-ipt-ipopt is not set\n# CONFIG_PACKAGE_kmod-ipt-ipp2p is not set\n# CONFIG_PACKAGE_kmod-ipt-iprange is not set\n# CONFIG_PACKAGE_kmod-ipt-ipsec is not set\nCONFIG_PACKAGE_kmod-ipt-ipset=y\n# CONFIG_PACKAGE_kmod-ipt-ipv4options is not set\n# CONFIG_PACKAGE_kmod-ipt-led is not set\n# CONFIG_PACKAGE_kmod-ipt-length2 is not set\n# CONFIG_PACKAGE_kmod-ipt-logmark is not set\n# CONFIG_PACKAGE_kmod-ipt-lscan is not set\n# CONFIG_PACKAGE_kmod-ipt-lua is not set\nCONFIG_PACKAGE_kmod-ipt-nat=y\n# CONFIG_PACKAGE_kmod-ipt-nat-extra is not set\n# CONFIG_PACKAGE_kmod-ipt-nat6 is not set\n# CONFIG_PACKAGE_kmod-ipt-nathelper-rtsp is not set\n# CONFIG_PACKAGE_kmod-ipt-nflog is not set\n# CONFIG_PACKAGE_kmod-ipt-nfqueue is not set\nCONFIG_PACKAGE_kmod-ipt-offload=y\n# CONFIG_PACKAGE_kmod-ipt-physdev is not set\n# CONFIG_PACKAGE_kmod-ipt-proto is not set\n# CONFIG_PACKAGE_kmod-ipt-psd is not set\n# CONFIG_PACKAGE_kmod-ipt-quota2 is not set\nCONFIG_PACKAGE_kmod-ipt-raw=y\n# CONFIG_PACKAGE_kmod-ipt-raw6 is not set\n# CONFIG_PACKAGE_kmod-ipt-rpfilter is not set\n# CONFIG_PACKAGE_kmod-ipt-rtpengine is not set\n# CONFIG_PACKAGE_kmod-ipt-sysrq is not set\n# CONFIG_PACKAGE_kmod-ipt-tarpit is not set\n# CONFIG_PACKAGE_kmod-ipt-tee is not set\nCONFIG_PACKAGE_kmod-ipt-tproxy=y\n# CONFIG_PACKAGE_kmod-ipt-u32 is not set\n# CONFIG_PACKAGE_kmod-ipt-ulog is not set\n# CONFIG_PACKAGE_kmod-netatop is not set\nCONFIG_PACKAGE_kmod-nf-conntrack=y\n# CONFIG_PACKAGE_kmod-nf-conntrack-netlink is not set\nCONFIG_PACKAGE_kmod-nf-conntrack6=y\nCONFIG_PACKAGE_kmod-nf-flow=y\nCONFIG_PACKAGE_kmod-nf-ipt=y\nCONFIG_PACKAGE_kmod-nf-ipt6=y\n# CONFIG_PACKAGE_kmod-nf-ipvs is not set\nCONFIG_PACKAGE_kmod-nf-nat=y\n# CONFIG_PACKAGE_kmod-nf-nat6 is not set\nCONFIG_PACKAGE_kmod-nf-nathelper=y\nCONFIG_PACKAGE_kmod-nf-nathelper-extra=y\nCONFIG_PACKAGE_kmod-nf-reject=y\nCONFIG_PACKAGE_kmod-nf-reject6=y\nCONFIG_PACKAGE_kmod-nfnetlink=y\n# CONFIG_PACKAGE_kmod-nfnetlink-log is not set\n# CONFIG_PACKAGE_kmod-nfnetlink-queue is not set\n# CONFIG_PACKAGE_kmod-nft-arp is not set\n# CONFIG_PACKAGE_kmod-nft-bridge is not set\n# CONFIG_PACKAGE_kmod-nft-core is not set\n# CONFIG_PACKAGE_kmod-nft-fib is not set\n# CONFIG_PACKAGE_kmod-nft-nat is not set\n# CONFIG_PACKAGE_kmod-nft-nat6 is not set\n# CONFIG_PACKAGE_kmod-nft-netdev is not set\n# CONFIG_PACKAGE_kmod-nft-offload is not set\n# CONFIG_PACKAGE_kmod-nft-queue is not set\n# end of Netfilter Extensions\n\n#\n# Network Devices\n#\n# CONFIG_PACKAGE_kmod-3c59x is not set\n# CONFIG_PACKAGE_kmod-8139cp is not set\n# CONFIG_PACKAGE_kmod-8139too is not set\n# CONFIG_PACKAGE_kmod-alx is not set\n# CONFIG_PACKAGE_kmod-atl1 is not set\n# CONFIG_PACKAGE_kmod-atl1c is not set\n# CONFIG_PACKAGE_kmod-atl1e is not set\n# CONFIG_PACKAGE_kmod-atl2 is not set\n# CONFIG_PACKAGE_kmod-b44 is not set\n# CONFIG_PACKAGE_kmod-be2net is not set\n# CONFIG_PACKAGE_kmod-bnx2 is not set\n# CONFIG_PACKAGE_kmod-bnx2x is not set\n# CONFIG_PACKAGE_kmod-dm9000 is not set\n# CONFIG_PACKAGE_kmod-dummy is not set\n# CONFIG_PACKAGE_kmod-e100 is not set\n# CONFIG_PACKAGE_kmod-e1000 is not set\n# CONFIG_PACKAGE_kmod-et131x is not set\n# CONFIG_PACKAGE_kmod-ethoc is not set\n# CONFIG_PACKAGE_kmod-forcedeth is not set\n# CONFIG_PACKAGE_kmod-hfcmulti is not set\n# CONFIG_PACKAGE_kmod-hfcpci is not set\n# CONFIG_PACKAGE_kmod-i40e is not set\n# CONFIG_PACKAGE_kmod-iavf is not set\n# CONFIG_PACKAGE_kmod-ifb is not set\n# CONFIG_PACKAGE_kmod-igb is not set\n# CONFIG_PACKAGE_kmod-igc is not set\n# CONFIG_PACKAGE_kmod-ipvlan is not set\n# CONFIG_PACKAGE_kmod-ixgbe is not set\n# CONFIG_PACKAGE_kmod-ixgbevf is not set\n# CONFIG_PACKAGE_kmod-libphy is not set\nCONFIG_PACKAGE_kmod-macvlan=y\n# CONFIG_PACKAGE_kmod-mdio-gpio is not set\n# CONFIG_PACKAGE_kmod-mii is not set\n# CONFIG_PACKAGE_kmod-mlx4-core is not set\n# CONFIG_PACKAGE_kmod-mlx5-core is not set\n# CONFIG_PACKAGE_kmod-natsemi is not set\n# CONFIG_PACKAGE_kmod-ne2k-pci is not set\n# CONFIG_PACKAGE_kmod-niu is not set\n# CONFIG_PACKAGE_kmod-of-mdio is not set\n# CONFIG_PACKAGE_kmod-pcnet32 is not set\n# CONFIG_PACKAGE_kmod-phy-bcm84881 is not set\n# CONFIG_PACKAGE_kmod-phy-broadcom is not set\n# CONFIG_PACKAGE_kmod-phy-realtek is not set\n# CONFIG_PACKAGE_kmod-phylink is not set\n# CONFIG_PACKAGE_kmod-qlcnic is not set\n# CONFIG_PACKAGE_kmod-r6040 is not set\n# CONFIG_PACKAGE_kmod-r8125 is not set\n# CONFIG_PACKAGE_kmod-r8168 is not set\n# CONFIG_PACKAGE_kmod-r8169 is not set\n# CONFIG_PACKAGE_kmod-sfc is not set\n# CONFIG_PACKAGE_kmod-sfc-falcon is not set\n# CONFIG_PACKAGE_kmod-sfp is not set\n# CONFIG_PACKAGE_kmod-siit is not set\n# CONFIG_PACKAGE_kmod-sis190 is not set\n# CONFIG_PACKAGE_kmod-sis900 is not set\n# CONFIG_PACKAGE_kmod-skge is not set\n# CONFIG_PACKAGE_kmod-sky2 is not set\n# CONFIG_PACKAGE_kmod-solos-pci is not set\n# CONFIG_PACKAGE_kmod-spi-ks8995 is not set\n# CONFIG_PACKAGE_kmod-swconfig is not set\n# CONFIG_PACKAGE_kmod-switch-bcm53xx is not set\n# CONFIG_PACKAGE_kmod-switch-bcm53xx-mdio is not set\n# CONFIG_PACKAGE_kmod-switch-ip17xx is not set\n# CONFIG_PACKAGE_kmod-switch-rtl8306 is not set\n# CONFIG_PACKAGE_kmod-switch-rtl8366-smi is not set\n# CONFIG_PACKAGE_kmod-switch-rtl8366rb is not set\n# CONFIG_PACKAGE_kmod-switch-rtl8366s is not set\n# CONFIG_PACKAGE_kmod-switch-rtl8367b is not set\n# CONFIG_PACKAGE_kmod-tg3 is not set\n# CONFIG_PACKAGE_kmod-tulip is not set\n# CONFIG_PACKAGE_kmod-via-rhine is not set\n# CONFIG_PACKAGE_kmod-via-velocity is not set\n# CONFIG_PACKAGE_kmod-vmxnet3 is not set\n# end of Network Devices\n\n#\n# Network Support\n#\n# CONFIG_PACKAGE_kmod-atm is not set\n# CONFIG_PACKAGE_kmod-ax25 is not set\n# CONFIG_PACKAGE_kmod-batman-adv is not set\n# CONFIG_PACKAGE_kmod-bonding is not set\n# CONFIG_PACKAGE_kmod-bpf-test is not set\n# CONFIG_PACKAGE_kmod-dnsresolver is not set\n# CONFIG_PACKAGE_kmod-fast-classifier is not set\n# CONFIG_PACKAGE_kmod-fast-classifier-noload is not set\n# CONFIG_PACKAGE_kmod-fou is not set\n# CONFIG_PACKAGE_kmod-fou6 is not set\n# CONFIG_PACKAGE_kmod-geneve is not set\n# CONFIG_PACKAGE_kmod-gre is not set\n# CONFIG_PACKAGE_kmod-gre6 is not set\n# CONFIG_PACKAGE_kmod-ip6-tunnel is not set\n# CONFIG_PACKAGE_kmod-ipip is not set\n# CONFIG_PACKAGE_kmod-ipsec is not set\n# CONFIG_PACKAGE_kmod-iptunnel6 is not set\n# CONFIG_PACKAGE_kmod-isdn4linux is not set\n# CONFIG_PACKAGE_kmod-jool is not set\n# CONFIG_PACKAGE_kmod-l2tp is not set\n# CONFIG_PACKAGE_kmod-l2tp-eth is not set\n# CONFIG_PACKAGE_kmod-l2tp-ip is not set\n# CONFIG_PACKAGE_kmod-macremapper is not set\n# CONFIG_PACKAGE_kmod-macsec is not set\n# CONFIG_PACKAGE_kmod-misdn is not set\n# CONFIG_PACKAGE_kmod-mpls is not set\n# CONFIG_PACKAGE_kmod-nat46 is not set\n# CONFIG_PACKAGE_kmod-netem is not set\n# CONFIG_PACKAGE_kmod-netlink-diag is not set\n# CONFIG_PACKAGE_kmod-nlmon is not set\n# CONFIG_PACKAGE_kmod-nsh is not set\n# CONFIG_PACKAGE_kmod-openvswitch is not set\n# CONFIG_PACKAGE_kmod-openvswitch-geneve is not set\n# CONFIG_PACKAGE_kmod-openvswitch-gre is not set\n# CONFIG_PACKAGE_kmod-openvswitch-vxlan is not set\n# CONFIG_PACKAGE_kmod-pf-ring is not set\n# CONFIG_PACKAGE_kmod-pktgen is not set\nCONFIG_PACKAGE_kmod-ppp=y\nCONFIG_PACKAGE_kmod-mppe=y\n# CONFIG_PACKAGE_kmod-ppp-synctty is not set\n# CONFIG_PACKAGE_kmod-pppoa is not set\nCONFIG_PACKAGE_kmod-pppoe=y\n# CONFIG_PACKAGE_kmod-pppol2tp is not set\nCONFIG_PACKAGE_kmod-pppox=y\n# CONFIG_PACKAGE_kmod-pptp is not set\n# CONFIG_PACKAGE_kmod-qca-nss-ecm-noload is not set\n# CONFIG_PACKAGE_kmod-qca-nss-ecm-premium is not set\n# CONFIG_PACKAGE_kmod-qca-nss-ecm-premium-noload is not set\n# CONFIG_PACKAGE_kmod-qca-nss-ecm-standard is not set\n# CONFIG_PACKAGE_kmod-sched is not set\n# CONFIG_PACKAGE_kmod-sched-act-vlan is not set\n# CONFIG_PACKAGE_kmod-sched-bpf is not set\n# CONFIG_PACKAGE_kmod-sched-cake is not set\n# CONFIG_PACKAGE_kmod-sched-connmark is not set\n# CONFIG_PACKAGE_kmod-sched-core is not set\n# CONFIG_PACKAGE_kmod-sched-ctinfo is not set\n# CONFIG_PACKAGE_kmod-sched-flower is not set\n# CONFIG_PACKAGE_kmod-sched-ipset is not set\n# CONFIG_PACKAGE_kmod-sched-mqprio is not set\n# CONFIG_PACKAGE_kmod-sctp is not set\n# CONFIG_PACKAGE_kmod-shortcut-fe is not set\n# CONFIG_PACKAGE_kmod-shortcut-fe-cm is not set\n# CONFIG_PACKAGE_kmod-sit is not set\nCONFIG_PACKAGE_kmod-slhc=y\n# CONFIG_PACKAGE_kmod-slip is not set\nCONFIG_PACKAGE_kmod-tcp-bbr=y\n# CONFIG_PACKAGE_kmod-tcp-hybla is not set\n# CONFIG_PACKAGE_kmod-trelay is not set\nCONFIG_PACKAGE_kmod-tun=y\n# CONFIG_PACKAGE_kmod-veth is not set\n# CONFIG_PACKAGE_kmod-vxlan is not set\n# CONFIG_PACKAGE_kmod-wireguard is not set\n# end of Network Support\n\n#\n# Other modules\n#\n# CONFIG_PACKAGE_kmod-6lowpan is not set\n# CONFIG_PACKAGE_kmod-ath3k is not set\n# CONFIG_PACKAGE_kmod-bcma is not set\n# CONFIG_PACKAGE_kmod-bluetooth is not set\n# CONFIG_PACKAGE_kmod-bluetooth-6lowpan is not set\n# CONFIG_PACKAGE_kmod-btmrvl is not set\n# CONFIG_PACKAGE_kmod-button-hotplug is not set\n# CONFIG_PACKAGE_kmod-dma-ralink is not set\n# CONFIG_PACKAGE_kmod-echo is not set\n# CONFIG_PACKAGE_kmod-eeprom-93cx6 is not set\n# CONFIG_PACKAGE_kmod-eeprom-at24 is not set\n# CONFIG_PACKAGE_kmod-eeprom-at25 is not set\n# CONFIG_PACKAGE_kmod-gpio-beeper is not set\nCONFIG_PACKAGE_kmod-gpio-button-hotplug=y\n# CONFIG_PACKAGE_kmod-gpio-dev is not set\n# CONFIG_PACKAGE_kmod-gpio-mcp23s08 is not set\n# CONFIG_PACKAGE_kmod-gpio-nxp-74hc164 is not set\n# CONFIG_PACKAGE_kmod-gpio-pca953x is not set\n# CONFIG_PACKAGE_kmod-gpio-pcf857x is not set\n# CONFIG_PACKAGE_kmod-hsdma-mtk is not set\n# CONFIG_PACKAGE_kmod-ikconfig is not set\n# CONFIG_PACKAGE_kmod-it87-wdt is not set\n# CONFIG_PACKAGE_kmod-itco-wdt is not set\n# CONFIG_PACKAGE_kmod-keys-encrypted is not set\n# CONFIG_PACKAGE_kmod-keys-trusted is not set\n# CONFIG_PACKAGE_kmod-lp is not set\n# CONFIG_PACKAGE_kmod-mmc is not set\n# CONFIG_PACKAGE_kmod-mtd-rw is not set\n# CONFIG_PACKAGE_kmod-mtdoops is not set\n# CONFIG_PACKAGE_kmod-mtdram is not set\n# CONFIG_PACKAGE_kmod-mtdtests is not set\n# CONFIG_PACKAGE_kmod-parport-pc is not set\n# CONFIG_PACKAGE_kmod-ppdev is not set\n# CONFIG_PACKAGE_kmod-pps is not set\n# CONFIG_PACKAGE_kmod-pps-gpio is not set\n# CONFIG_PACKAGE_kmod-pps-ldisc is not set\n# CONFIG_PACKAGE_kmod-ptp is not set\n# CONFIG_PACKAGE_kmod-random-core is not set\n# CONFIG_PACKAGE_kmod-rtc-ds1307 is not set\n# CONFIG_PACKAGE_kmod-rtc-ds1374 is not set\n# CONFIG_PACKAGE_kmod-rtc-ds1672 is not set\n# CONFIG_PACKAGE_kmod-rtc-em3027 is not set\n# CONFIG_PACKAGE_kmod-rtc-isl1208 is not set\n# CONFIG_PACKAGE_kmod-rtc-pcf2123 is not set\n# CONFIG_PACKAGE_kmod-rtc-pcf2127 is not set\n# CONFIG_PACKAGE_kmod-rtc-pcf8563 is not set\n# CONFIG_PACKAGE_kmod-rtc-pt7c4338 is not set\n# CONFIG_PACKAGE_kmod-rtc-rs5c372a is not set\n# CONFIG_PACKAGE_kmod-rtc-rx8025 is not set\n# CONFIG_PACKAGE_kmod-rtc-s35390a is not set\n# CONFIG_PACKAGE_kmod-sdhci is not set\n# CONFIG_PACKAGE_kmod-sdhci-mt7620 is not set\n# CONFIG_PACKAGE_kmod-serial-8250 is not set\n# CONFIG_PACKAGE_kmod-serial-8250-exar is not set\n# CONFIG_PACKAGE_kmod-softdog is not set\n# CONFIG_PACKAGE_kmod-ssb is not set\n# CONFIG_PACKAGE_kmod-tpm is not set\n# CONFIG_PACKAGE_kmod-tpm-i2c-atmel is not set\n# CONFIG_PACKAGE_kmod-tpm-i2c-infineon is not set\n# CONFIG_PACKAGE_kmod-w83627hf-wdt is not set\n# CONFIG_PACKAGE_kmod-zram is not set\n# end of Other modules\n\n#\n# PCMCIA support\n#\n# end of PCMCIA support\n\n#\n# SPI Support\n#\n# CONFIG_PACKAGE_kmod-mmc-spi is not set\n# CONFIG_PACKAGE_kmod-spi-bitbang is not set\n# CONFIG_PACKAGE_kmod-spi-dev is not set\n# CONFIG_PACKAGE_kmod-spi-gpio is not set\n# end of SPI Support\n\n#\n# Sound Support\n#\n# CONFIG_PACKAGE_kmod-sound-core is not set\n# end of Sound Support\n\n#\n# USB Support\n#\n# CONFIG_PACKAGE_kmod-chaoskey is not set\n# CONFIG_PACKAGE_kmod-usb-acm is not set\n# CONFIG_PACKAGE_kmod-usb-atm is not set\n# CONFIG_PACKAGE_kmod-usb-cm109 is not set\nCONFIG_PACKAGE_kmod-usb-core=y\n# CONFIG_PACKAGE_kmod-usb-dwc2 is not set\n# CONFIG_PACKAGE_kmod-usb-dwc3 is not set\nCONFIG_PACKAGE_kmod-usb-ehci=y\n# CONFIG_PACKAGE_kmod-usb-hid is not set\n# CONFIG_PACKAGE_kmod-usb-hid-cp2112 is not set\n# CONFIG_PACKAGE_kmod-usb-ledtrig-usbport is not set\n# CONFIG_PACKAGE_kmod-usb-net is not set\n# CONFIG_PACKAGE_kmod-usb-net-aqc111 is not set\n# CONFIG_PACKAGE_kmod-usb-net-asix is not set\n# CONFIG_PACKAGE_kmod-usb-net-asix-ax88179 is not set\n# CONFIG_PACKAGE_kmod-usb-net-cdc-eem is not set\n# CONFIG_PACKAGE_kmod-usb-net-cdc-ether is not set\n# CONFIG_PACKAGE_kmod-usb-net-cdc-mbim is not set\n# CONFIG_PACKAGE_kmod-usb-net-cdc-ncm is not set\n# CONFIG_PACKAGE_kmod-usb-net-cdc-subset is not set\n# CONFIG_PACKAGE_kmod-usb-net-dm9601-ether is not set\n# CONFIG_PACKAGE_kmod-usb-net-hso is not set\n# CONFIG_PACKAGE_kmod-usb-net-huawei-cdc-ncm is not set\n# CONFIG_PACKAGE_kmod-usb-net-ipheth is not set\n# CONFIG_PACKAGE_kmod-usb-net-kalmia is not set\n# CONFIG_PACKAGE_kmod-usb-net-kaweth is not set\n# CONFIG_PACKAGE_kmod-usb-net-mcs7830 is not set\n# CONFIG_PACKAGE_kmod-usb-net-pegasus is not set\n# CONFIG_PACKAGE_kmod-usb-net-pl is not set\n# CONFIG_PACKAGE_kmod-usb-net-qmi-wwan is not set\n# CONFIG_PACKAGE_kmod-usb-net-rndis is not set\n# CONFIG_PACKAGE_kmod-usb-net-rtl8150 is not set\n# CONFIG_PACKAGE_kmod-usb-net-rtl8152 is not set\n# CONFIG_PACKAGE_kmod-usb-net-rtl8152-vendor is not set\n# CONFIG_PACKAGE_kmod-usb-net-sierrawireless is not set\n# CONFIG_PACKAGE_kmod-usb-net-smsc95xx is not set\n# CONFIG_PACKAGE_kmod-usb-net-sr9700 is not set\n# CONFIG_PACKAGE_kmod-usb-ohci is not set\n# CONFIG_PACKAGE_kmod-usb-ohci-pci is not set\n# CONFIG_PACKAGE_kmod-usb-printer is not set\n# CONFIG_PACKAGE_kmod-usb-serial is not set\n# CONFIG_PACKAGE_kmod-usb-serial-ark3116 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-belkin is not set\n# CONFIG_PACKAGE_kmod-usb-serial-ch341 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-cp210x is not set\n# CONFIG_PACKAGE_kmod-usb-serial-cypress-m8 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-edgeport is not set\n# CONFIG_PACKAGE_kmod-usb-serial-ftdi is not set\n# CONFIG_PACKAGE_kmod-usb-serial-garmin is not set\n# CONFIG_PACKAGE_kmod-usb-serial-ipw is not set\n# CONFIG_PACKAGE_kmod-usb-serial-keyspan is not set\n# CONFIG_PACKAGE_kmod-usb-serial-mct is not set\n# CONFIG_PACKAGE_kmod-usb-serial-mos7720 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-mos7840 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-option is not set\n# CONFIG_PACKAGE_kmod-usb-serial-oti6858 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-pl2303 is not set\n# CONFIG_PACKAGE_kmod-usb-serial-qualcomm is not set\n# CONFIG_PACKAGE_kmod-usb-serial-sierrawireless is not set\n# CONFIG_PACKAGE_kmod-usb-serial-simple is not set\n# CONFIG_PACKAGE_kmod-usb-serial-ti-usb is not set\n# CONFIG_PACKAGE_kmod-usb-serial-visor is not set\nCONFIG_PACKAGE_kmod-usb-storage=y\nCONFIG_PACKAGE_kmod-usb-storage-extras=y\n# CONFIG_PACKAGE_kmod-usb-storage-uas is not set\n# CONFIG_PACKAGE_kmod-usb-uhci is not set\n# CONFIG_PACKAGE_kmod-usb-wdm is not set\nCONFIG_PACKAGE_kmod-usb-xhci-hcd=y\nCONFIG_PACKAGE_kmod-usb-xhci-mtk=y\n# CONFIG_PACKAGE_kmod-usb-yealink is not set\nCONFIG_PACKAGE_kmod-usb2=y\n# CONFIG_PACKAGE_kmod-usb2-pci is not set\nCONFIG_PACKAGE_kmod-usb3=y\n# CONFIG_PACKAGE_kmod-usbip is not set\n# CONFIG_PACKAGE_kmod-usbip-client is not set\n# CONFIG_PACKAGE_kmod-usbip-server is not set\n# CONFIG_PACKAGE_kmod-usbmon is not set\n# end of USB Support\n\n#\n# Video Support\n#\n# CONFIG_PACKAGE_kmod-multimedia-input is not set\n# CONFIG_PACKAGE_kmod-video-core is not set\n# end of Video Support\n\n#\n# Virtualization\n#\n# end of Virtualization\n\n#\n# Voice over IP\n#\n# CONFIG_PACKAGE_kmod-dahdi is not set\n# end of Voice over IP\n\n#\n# W1 support\n#\n# CONFIG_PACKAGE_kmod-w1 is not set\n# end of W1 support\n\n#\n# WPAN 802.15.4 Support\n#\n# CONFIG_PACKAGE_kmod-at86rf230 is not set\n# CONFIG_PACKAGE_kmod-atusb is not set\n# CONFIG_PACKAGE_kmod-ca8210 is not set\n# CONFIG_PACKAGE_kmod-cc2520 is not set\n# CONFIG_PACKAGE_kmod-fakelb is not set\n# CONFIG_PACKAGE_kmod-ieee802154 is not set\n# CONFIG_PACKAGE_kmod-ieee802154-6lowpan is not set\n# CONFIG_PACKAGE_kmod-mac802154 is not set\n# CONFIG_PACKAGE_kmod-mrf24j40 is not set\n# end of WPAN 802.15.4 Support\n\n#\n# Wireless Drivers\n#\n# CONFIG_PACKAGE_kmod-acx-mac80211 is not set\n# CONFIG_PACKAGE_kmod-adm8211 is not set\n# CONFIG_PACKAGE_kmod-ar5523 is not set\n# CONFIG_PACKAGE_kmod-ath is not set\n# CONFIG_PACKAGE_kmod-ath10k is not set\n# CONFIG_PACKAGE_kmod-ath10k-ct is not set\n# CONFIG_PACKAGE_kmod-ath10k-ct-smallbuffers is not set\n# CONFIG_PACKAGE_kmod-ath11k is not set\n# CONFIG_PACKAGE_kmod-ath5k is not set\n# CONFIG_PACKAGE_kmod-ath6kl-sdio is not set\n# CONFIG_PACKAGE_kmod-ath6kl-usb is not set\n# CONFIG_PACKAGE_kmod-ath9k is not set\n# CONFIG_PACKAGE_kmod-ath9k-htc is not set\n# CONFIG_PACKAGE_kmod-b43 is not set\n# CONFIG_PACKAGE_kmod-b43legacy is not set\n# CONFIG_PACKAGE_kmod-brcmfmac is not set\n# CONFIG_PACKAGE_kmod-brcmsmac is not set\n# CONFIG_PACKAGE_kmod-brcmutil is not set\n# CONFIG_PACKAGE_kmod-carl9170 is not set\n# CONFIG_PACKAGE_kmod-cfg80211 is not set\n# CONFIG_PACKAGE_kmod-hermes is not set\n# CONFIG_PACKAGE_kmod-hermes-pci is not set\n# CONFIG_PACKAGE_kmod-hermes-plx is not set\n# CONFIG_PACKAGE_kmod-ipw2100 is not set\n# CONFIG_PACKAGE_kmod-ipw2200 is not set\n# CONFIG_PACKAGE_kmod-iwl-legacy is not set\n# CONFIG_PACKAGE_kmod-iwl3945 is not set\n# CONFIG_PACKAGE_kmod-iwl4965 is not set\n# CONFIG_PACKAGE_kmod-iwlwifi is not set\n# CONFIG_PACKAGE_kmod-lib80211 is not set\n# CONFIG_PACKAGE_kmod-libertas-sdio is not set\n# CONFIG_PACKAGE_kmod-libertas-spi is not set\n# CONFIG_PACKAGE_kmod-libertas-usb is not set\n# CONFIG_PACKAGE_kmod-libipw is not set\n# CONFIG_PACKAGE_kmod-mac80211 is not set\n# CONFIG_PACKAGE_kmod-mac80211-hwsim is not set\n# CONFIG_PACKAGE_kmod-mt76 is not set\n# CONFIG_PACKAGE_kmod-mt7601u is not set\n# CONFIG_PACKAGE_kmod-mt7603 is not set\n# CONFIG_PACKAGE_kmod-mt7603e is not set\n# CONFIG_PACKAGE_kmod-mt7615-firmware is not set\nCONFIG_PACKAGE_kmod-mt7615d=y\nCONFIG_MTK_SUPPORT_OPENWRT=y\nCONFIG_MTK_WIFI_DRIVER=y\nCONFIG_MTK_FIRST_IF_MT7615E=y\n# CONFIG_MTK_FIRST_IF_MT7622 is not set\n# CONFIG_MTK_FIRST_IF_MT7626 is not set\n# CONFIG_MTK_FIRST_IF_NONE is not set\n# CONFIG_MTK_SECOND_IF_NONE is not set\nCONFIG_MTK_SECOND_IF_MT7615E=y\nCONFIG_MTK_THIRD_IF_NONE=y\n# CONFIG_MTK_THIRD_IF_MT7615E is not set\nCONFIG_MTK_RT_FIRST_CARD=7615\nCONFIG_MTK_RT_SECOND_CARD=7615\nCONFIG_MTK_RT_FIRST_IF_RF_OFFSET=0xc0000\nCONFIG_MTK_RT_SECOND_IF_RF_OFFSET=0xc8000\nCONFIG_MTK_MT_WIFI=y\nCONFIG_MTK_MT_WIFI_PATH=\"mt_wifi\"\n\n#\n# WiFi Generic Feature Options\n#\nCONFIG_MTK_FIRST_IF_EEPROM_FLASH=y\n# CONFIG_MTK_FIRST_IF_EEPROM_PROM is not set\n# CONFIG_MTK_FIRST_IF_EEPROM_EFUSE is not set\nCONFIG_MTK_RT_FIRST_CARD_EEPROM=\"flash\"\nCONFIG_MTK_SECOND_IF_EEPROM_FLASH=y\n# CONFIG_MTK_SECOND_IF_EEPROM_PROM is not set\n# CONFIG_MTK_SECOND_IF_EEPROM_EFUSE is not set\nCONFIG_MTK_RT_SECOND_CARD_EEPROM=\"flash\"\nCONFIG_MTK_MULTI_INF_SUPPORT=y\nCONFIG_MTK_WIFI_BASIC_FUNC=y\nCONFIG_MTK_DOT11_N_SUPPORT=y\nCONFIG_MTK_DOT11_VHT_AC=y\nCONFIG_MTK_G_BAND_256QAM_SUPPORT=y\nCONFIG_MTK_BRCM_256QAM_SUPPORT=y\nCONFIG_MTK_VHT_TXBF_2G_EPIGRAM_IE_SUPPORT=y\nCONFIG_MTK_TPC_SUPPORT=y\nCONFIG_MTK_ICAP_SUPPORT=y\nCONFIG_MTK_SPECTRUM_SUPPORT=y\nCONFIG_MTK_BACKGROUND_SCAN_SUPPORT=y\nCONFIG_MTK_SMART_CARRIER_SENSE_SUPPORT=y\nCONFIG_MTK_MT_DFS_SUPPORT=y\nCONFIG_MTK_HDR_TRANS_TX_SUPPORT=y\nCONFIG_MTK_HDR_TRANS_RX_SUPPORT=y\nCONFIG_MTK_DBDC_MODE=y\nCONFIG_MTK_MULTI_PROFILE_SUPPORT=y\nCONFIG_MTK_WSC_INCLUDED=y\nCONFIG_MTK_WSC_V2_SUPPORT=y\nCONFIG_MTK_DOT11W_PMF_SUPPORT=y\nCONFIG_MTK_TXBF_SUPPORT=y\n# CONFIG_MTK_FAST_NAT_SUPPORT is not set\n# CONFIG_MTK_FTM_SUPPORT is not set\nCONFIG_MTK_IGMP_SNOOP_SUPPORT=y\nCONFIG_MTK_RTMP_FLASH_SUPPORT=y\nCONFIG_MTK_PRE_CAL_TRX_SET1_SUPPORT=y\nCONFIG_MTK_RLM_CAL_CACHE_SUPPORT=y\nCONFIG_MTK_PRE_CAL_TRX_SET2_SUPPORT=y\n# CONFIG_MTK_RF_LOCKDOWN_SUPPORT is not set\n# CONFIG_MTK_LINK_TEST_SUPPORT is not set\nCONFIG_MTK_ATE_SUPPORT=y\n# CONFIG_MTK_PASSPOINT_R2 is not set\n# CONFIG_MTK_MBO_SUPPORT is not set\nCONFIG_MTK_UAPSD=y\nCONFIG_MTK_TCP_RACK_SUPPORT=y\nCONFIG_MTK_RED_SUPPORT=y\n# CONFIG_MTK_FDB_SUPPORT is not set\nCONFIG_MTK_FIRST_IF_IPAILNA=y\n# CONFIG_MTK_FIRST_IF_IPAELNA is not set\n# CONFIG_MTK_FIRST_IF_EPAELNA is not set\nCONFIG_MTK_SECOND_IF_IPAILNA=y\n# CONFIG_MTK_SECOND_IF_IPAELNA is not set\n# CONFIG_MTK_SECOND_IF_EPAELNA is not set\n# CONFIG_MTK_RLT_MAC is not set\n# CONFIG_MTK_RTMP_MAC is not set\n# end of WiFi Generic Feature Options\n\n#\n# WiFi Operation Modes\n#\nCONFIG_MTK_WIFI_MODE_AP=y\n# CONFIG_MTK_WIFI_MODE_STA is not set\n# CONFIG_MTK_WIFI_MODE_BOTH is not set\nCONFIG_MTK_MT_AP_SUPPORT=y\nCONFIG_MTK_WDS_SUPPORT=y\nCONFIG_MTK_MBSS_SUPPORT=y\nCONFIG_MTK_APCLI_SUPPORT=y\n# CONFIG_MTK_APCLI_CERT_SUPPORT is not set\nCONFIG_MTK_MAC_REPEATER_SUPPORT=y\n# CONFIG_MTK_MWDS is not set\nCONFIG_MTK_MUMIMO_SUPPORT=y\nCONFIG_MTK_MU_RA_SUPPORT=y\n# CONFIG_MTK_DOT11R_FT_SUPPORT is not set\n# CONFIG_MTK_DOT11K_RRM_SUPPORT is not set\n# CONFIG_MTK_CFG80211_SUPPORT is not set\n# CONFIG_MTK_DSCP_PRI_SUPPORT is not set\n# CONFIG_MTK_CON_WPS_SUPPORT is not set\nCONFIG_MTK_MCAST_RATE_SPECIFIC=y\nCONFIG_MTK_VOW_SUPPORT=y\nCONFIG_MTK_BAND_STEERING=y\nCONFIG_MTK_LED_CONTROL_SUPPORT=y\n# CONFIG_MTK_WLAN_HOOK is not set\n# CONFIG_MTK_RADIUS_ACCOUNTING_SUPPORT is not set\n# CONFIG_MTK_GREENAP_SUPPORT is not set\nCONFIG_MTK_PCIE_ASPM_DYM_CTRL_SUPPORT=y\n# CONFIG_MTK_COEX_SUPPORT is not set\n# CONFIG_MTK_EASY_SETUP_SUPPORT is not set\n# CONFIG_MTK_EVENT_NOTIFIER_SUPPORT is not set\n# CONFIG_MTK_AIR_MONITOR is not set\n# CONFIG_MTK_WNM_SUPPORT is not set\n# CONFIG_MTK_INTERWORKING is not set\nCONFIG_MTK_LINUX_NET_TXQ_SUPPORT=y\n# end of WiFi Operation Modes\n\nCONFIG_MTK_WIFI_MT_MAC=y\nCONFIG_MTK_MT_MAC=y\n# CONFIG_MTK_CHIP_MT7603E is not set\nCONFIG_MTK_CHIP_MT7615E=y\n# CONFIG_MTK_CHIP_MT7622 is not set\n# CONFIG_MTK_CHIP_MT7663E is not set\n# CONFIG_MTK_CHIP_MT7626 is not set\nCONFIG_PACKAGE_kmod-mt7615d_dbdc=y\n# CONFIG_PACKAGE_kmod-mt7615e is not set\n# CONFIG_PACKAGE_kmod-mt7663-firmware-ap is not set\n# CONFIG_PACKAGE_kmod-mt7663-firmware-sta is not set\n# CONFIG_PACKAGE_kmod-mt7663s is not set\n# CONFIG_PACKAGE_kmod-mt7663u is not set\n# CONFIG_PACKAGE_kmod-mt76x0e is not set\n# CONFIG_PACKAGE_kmod-mt76x0u is not set\n# CONFIG_PACKAGE_kmod-mt76x2 is not set\n# CONFIG_PACKAGE_kmod-mt76x2e is not set\n# CONFIG_PACKAGE_kmod-mt76x2u is not set\n# CONFIG_PACKAGE_kmod-mt7915e is not set\n# CONFIG_PACKAGE_kmod-mt7921e is not set\n# CONFIG_PACKAGE_kmod-mwifiex-pcie is not set\n# CONFIG_PACKAGE_kmod-mwifiex-sdio is not set\n# CONFIG_PACKAGE_kmod-mwl8k is not set\n# CONFIG_PACKAGE_kmod-net-prism54 is not set\n# CONFIG_PACKAGE_kmod-net-rtl8192su is not set\n# CONFIG_PACKAGE_kmod-owl-loader is not set\n# CONFIG_PACKAGE_kmod-p54-common is not set\n# CONFIG_PACKAGE_kmod-p54-pci is not set\n# CONFIG_PACKAGE_kmod-p54-usb is not set\n# CONFIG_PACKAGE_kmod-qtn-pcie2 is not set\n# CONFIG_PACKAGE_kmod-rsi91x is not set\n# CONFIG_PACKAGE_kmod-rsi91x-sdio is not set\n# CONFIG_PACKAGE_kmod-rsi91x-usb is not set\n# CONFIG_PACKAGE_kmod-rt2400-pci is not set\n# CONFIG_PACKAGE_kmod-rt2500-pci is not set\n# CONFIG_PACKAGE_kmod-rt2500-usb is not set\n# CONFIG_PACKAGE_kmod-rt2800-pci is not set\n# CONFIG_PACKAGE_kmod-rt2800-usb is not set\n# CONFIG_PACKAGE_kmod-rt2x00-lib is not set\n# CONFIG_PACKAGE_kmod-rt61-pci is not set\n# CONFIG_PACKAGE_kmod-rt73-usb is not set\n# CONFIG_PACKAGE_kmod-rtl8180 is not set\n# CONFIG_PACKAGE_kmod-rtl8187 is not set\n# CONFIG_PACKAGE_kmod-rtl8192ce is not set\n# CONFIG_PACKAGE_kmod-rtl8192cu is not set\n# CONFIG_PACKAGE_kmod-rtl8192de is not set\n# CONFIG_PACKAGE_kmod-rtl8192se is not set\n# CONFIG_PACKAGE_kmod-rtl8723bs is not set\n# CONFIG_PACKAGE_kmod-rtl8812au-ct is not set\n# CONFIG_PACKAGE_kmod-rtl8821ae is not set\n# CONFIG_PACKAGE_kmod-rtl8xxxu is not set\n# CONFIG_PACKAGE_kmod-rtw88 is not set\n# CONFIG_PACKAGE_kmod-wil6210 is not set\n# CONFIG_PACKAGE_kmod-wl12xx is not set\n# CONFIG_PACKAGE_kmod-wl18xx is not set\n# CONFIG_PACKAGE_kmod-wlcore is not set\n# CONFIG_PACKAGE_kmod-zd1211rw is not set\n# end of Wireless Drivers\n# end of Kernel modules\n\n#\n# Languages\n#\n\n#\n# Erlang\n#\n# CONFIG_PACKAGE_erlang is not set\n# CONFIG_PACKAGE_erlang-asn1 is not set\n# CONFIG_PACKAGE_erlang-compiler is not set\n# CONFIG_PACKAGE_erlang-crypto is not set\n# CONFIG_PACKAGE_erlang-erl-interface is not set\n# CONFIG_PACKAGE_erlang-hipe is not set\n# CONFIG_PACKAGE_erlang-inets is not set\n# CONFIG_PACKAGE_erlang-mnesia is not set\n# CONFIG_PACKAGE_erlang-os_mon is not set\n# CONFIG_PACKAGE_erlang-public-key is not set\n# CONFIG_PACKAGE_erlang-reltool is not set\n# CONFIG_PACKAGE_erlang-runtime-tools is not set\n# CONFIG_PACKAGE_erlang-snmp is not set\n# CONFIG_PACKAGE_erlang-ssh is not set\n# CONFIG_PACKAGE_erlang-ssl is not set\n# CONFIG_PACKAGE_erlang-syntax-tools is not set\n# CONFIG_PACKAGE_erlang-tools is not set\n# CONFIG_PACKAGE_erlang-xmerl is not set\n# end of Erlang\n\n#\n# Go\n#\n# CONFIG_PACKAGE_golang is not set\n\n#\n# Configuration\n#\nCONFIG_GOLANG_EXTERNAL_BOOTSTRAP_ROOT=\"\"\nCONFIG_GOLANG_BUILD_CACHE_DIR=\"\"\n# CONFIG_GOLANG_MOD_CACHE_WORLD_READABLE is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_golang-doc is not set\n# CONFIG_PACKAGE_golang-github-jedisct1-dnscrypt-proxy2-dev is not set\n# CONFIG_PACKAGE_golang-github-nextdns-nextdns-dev is not set\n# CONFIG_PACKAGE_golang-gitlab-yawning-obfs4-dev is not set\n# CONFIG_PACKAGE_golang-src is not set\n# CONFIG_PACKAGE_golang-torproject-tor-fw-helper-dev is not set\n# end of Go\n\n#\n# Lua\n#\n# CONFIG_PACKAGE_dkjson is not set\n# CONFIG_PACKAGE_json4lua is not set\n# CONFIG_PACKAGE_ldbus is not set\nCONFIG_PACKAGE_libiwinfo-lua=y\n# CONFIG_PACKAGE_linotify is not set\n# CONFIG_PACKAGE_lpeg is not set\n# CONFIG_PACKAGE_lsqlite3 is not set\nCONFIG_PACKAGE_lua=y\n# CONFIG_PACKAGE_lua-argparse is not set\n# CONFIG_PACKAGE_lua-bencode is not set\n# CONFIG_PACKAGE_lua-bit32 is not set\n# CONFIG_PACKAGE_lua-cjson is not set\n# CONFIG_PACKAGE_lua-copas is not set\n# CONFIG_PACKAGE_lua-coxpcall is not set\n# CONFIG_PACKAGE_lua-ev is not set\n# CONFIG_PACKAGE_lua-examples is not set\n# CONFIG_PACKAGE_lua-libmodbus is not set\n# CONFIG_PACKAGE_lua-lzlib is not set\n# CONFIG_PACKAGE_lua-md5 is not set\n# CONFIG_PACKAGE_lua-mobdebug is not set\n# CONFIG_PACKAGE_lua-mosquitto is not set\n# CONFIG_PACKAGE_lua-openssl is not set\n# CONFIG_PACKAGE_lua-penlight is not set\n# CONFIG_PACKAGE_lua-rings is not set\n# CONFIG_PACKAGE_lua-rs232 is not set\n# CONFIG_PACKAGE_lua-sha2 is not set\n# CONFIG_PACKAGE_lua-wsapi-base is not set\n# CONFIG_PACKAGE_lua-wsapi-xavante is not set\n# CONFIG_PACKAGE_lua-xavante is not set\n# CONFIG_PACKAGE_lua5.3 is not set\n# CONFIG_PACKAGE_luabitop is not set\n# CONFIG_PACKAGE_luac is not set\n# CONFIG_PACKAGE_luac5.3 is not set\n# CONFIG_PACKAGE_luaexpat is not set\n# CONFIG_PACKAGE_luafilesystem is not set\n# CONFIG_PACKAGE_luajit is not set\n# CONFIG_PACKAGE_lualanes is not set\n# CONFIG_PACKAGE_luaposix is not set\n# CONFIG_PACKAGE_luarocks is not set\n# CONFIG_PACKAGE_luasec is not set\n# CONFIG_PACKAGE_luasoap is not set\n# CONFIG_PACKAGE_luasocket is not set\n# CONFIG_PACKAGE_luasocket5.3 is not set\n# CONFIG_PACKAGE_luasql-mysql is not set\n# CONFIG_PACKAGE_luasql-pgsql is not set\n# CONFIG_PACKAGE_luasql-sqlite3 is not set\n# CONFIG_PACKAGE_luasrcdiet is not set\n# CONFIG_PACKAGE_luci-lib-fs is not set\n# CONFIG_PACKAGE_luv is not set\n# CONFIG_PACKAGE_lyaml is not set\n# CONFIG_PACKAGE_lzmq is not set\n# CONFIG_PACKAGE_uuid is not set\n# end of Lua\n\n#\n# Node.js\n#\n# CONFIG_PACKAGE_node is not set\n# CONFIG_PACKAGE_node-arduino-firmata is not set\n# CONFIG_PACKAGE_node-cylon is not set\n# CONFIG_PACKAGE_node-cylon-firmata is not set\n# CONFIG_PACKAGE_node-cylon-gpio is not set\n# CONFIG_PACKAGE_node-cylon-i2c is not set\n# CONFIG_PACKAGE_node-hid is not set\n# CONFIG_PACKAGE_node-homebridge is not set\n# CONFIG_PACKAGE_node-javascript-obfuscator is not set\n# CONFIG_PACKAGE_node-npm is not set\n# CONFIG_PACKAGE_node-serialport is not set\n# CONFIG_PACKAGE_node-serialport-bindings is not set\n# end of Node.js\n\n#\n# PHP7\n#\n# CONFIG_PACKAGE_php7 is not set\n# end of PHP7\n\n#\n# PHP8\n#\n# CONFIG_PACKAGE_php8 is not set\n# end of PHP8\n\n#\n# Perl\n#\n# CONFIG_PACKAGE_perl is not set\n# end of Perl\n\n#\n# Python\n#\n# CONFIG_PACKAGE_libpython3 is not set\n# CONFIG_PACKAGE_micropython is not set\n# CONFIG_PACKAGE_micropython-lib is not set\n# CONFIG_PACKAGE_python-pip-conf is not set\n# CONFIG_PACKAGE_python3 is not set\n# CONFIG_PACKAGE_python3-aiohttp is not set\n# CONFIG_PACKAGE_python3-aiohttp-cors is not set\n# CONFIG_PACKAGE_python3-apipkg is not set\n# CONFIG_PACKAGE_python3-apparmor is not set\n# CONFIG_PACKAGE_python3-appdirs is not set\n# CONFIG_PACKAGE_python3-asgiref is not set\n# CONFIG_PACKAGE_python3-asn1crypto is not set\n# CONFIG_PACKAGE_python3-astral is not set\n# CONFIG_PACKAGE_python3-async-timeout is not set\n# CONFIG_PACKAGE_python3-asyncio is not set\n# CONFIG_PACKAGE_python3-atomicwrites is not set\n# CONFIG_PACKAGE_python3-attrs is not set\n# CONFIG_PACKAGE_python3-augeas is not set\n# CONFIG_PACKAGE_python3-automat is not set\n# CONFIG_PACKAGE_python3-awscli is not set\n# CONFIG_PACKAGE_python3-babel is not set\n# CONFIG_PACKAGE_python3-base is not set\n# CONFIG_PACKAGE_python3-bcrypt is not set\n# CONFIG_PACKAGE_python3-bidict is not set\n# CONFIG_PACKAGE_python3-boto3 is not set\n# CONFIG_PACKAGE_python3-botocore is not set\n# CONFIG_PACKAGE_python3-bottle is not set\n# CONFIG_PACKAGE_python3-cached-property is not set\n# CONFIG_PACKAGE_python3-cachelib is not set\n# CONFIG_PACKAGE_python3-cachetools is not set\n# CONFIG_PACKAGE_python3-certifi is not set\n# CONFIG_PACKAGE_python3-cffi is not set\n# CONFIG_PACKAGE_python3-cgi is not set\n# CONFIG_PACKAGE_python3-cgitb is not set\n# CONFIG_PACKAGE_python3-chardet is not set\n# CONFIG_PACKAGE_python3-ciso8601 is not set\n# CONFIG_PACKAGE_python3-click is not set\n# CONFIG_PACKAGE_python3-click-log is not set\n# CONFIG_PACKAGE_python3-codecs is not set\n# CONFIG_PACKAGE_python3-colorama is not set\n# CONFIG_PACKAGE_python3-constantly is not set\n# CONFIG_PACKAGE_python3-contextlib2 is not set\n# CONFIG_PACKAGE_python3-cryptodome is not set\n# CONFIG_PACKAGE_python3-cryptodomex is not set\n# CONFIG_PACKAGE_python3-cryptography is not set\n# CONFIG_PACKAGE_python3-ctypes is not set\n# CONFIG_PACKAGE_python3-curl is not set\n# CONFIG_PACKAGE_python3-dateutil is not set\n# CONFIG_PACKAGE_python3-dbm is not set\n# CONFIG_PACKAGE_python3-decimal is not set\n# CONFIG_PACKAGE_python3-decorator is not set\n# CONFIG_PACKAGE_python3-defusedxml is not set\n# CONFIG_PACKAGE_python3-dev is not set\n# CONFIG_PACKAGE_python3-distro is not set\n# CONFIG_PACKAGE_python3-distutils is not set\n# CONFIG_PACKAGE_python3-django is not set\n# CONFIG_PACKAGE_python3-django-appconf is not set\n# CONFIG_PACKAGE_python3-django-compressor is not set\n# CONFIG_PACKAGE_python3-django-cors-headers is not set\n# CONFIG_PACKAGE_python3-django-etesync-journal is not set\n# CONFIG_PACKAGE_python3-django-formtools is not set\n# CONFIG_PACKAGE_python3-django-jsonfield is not set\n# CONFIG_PACKAGE_python3-django-jsonfield2 is not set\n# CONFIG_PACKAGE_python3-django-picklefield is not set\n# CONFIG_PACKAGE_python3-django-postoffice is not set\n# CONFIG_PACKAGE_python3-django-ranged-response is not set\n# CONFIG_PACKAGE_python3-django-restframework is not set\n# CONFIG_PACKAGE_python3-django-restframework39 is not set\n# CONFIG_PACKAGE_python3-django-simple-captcha is not set\n# CONFIG_PACKAGE_python3-django-statici18n is not set\n# CONFIG_PACKAGE_python3-django-webpack-loader is not set\n# CONFIG_PACKAGE_python3-django1 is not set\n# CONFIG_PACKAGE_python3-dns is not set\n# CONFIG_PACKAGE_python3-docker is not set\n# CONFIG_PACKAGE_python3-dockerpty is not set\n# CONFIG_PACKAGE_python3-docopt is not set\n# CONFIG_PACKAGE_python3-docutils is not set\n# CONFIG_PACKAGE_python3-dotenv is not set\n# CONFIG_PACKAGE_python3-drf-nested-routers is not set\n# CONFIG_PACKAGE_python3-email is not set\n# CONFIG_PACKAGE_python3-engineio is not set\n# CONFIG_PACKAGE_python3-et_xmlfile is not set\n# CONFIG_PACKAGE_python3-evdev is not set\n# CONFIG_PACKAGE_python3-eventlet is not set\n# CONFIG_PACKAGE_python3-execnet is not set\n# CONFIG_PACKAGE_python3-flask is not set\n# CONFIG_PACKAGE_python3-flask-babel is not set\n# CONFIG_PACKAGE_python3-flask-httpauth is not set\n# CONFIG_PACKAGE_python3-flask-login is not set\n# CONFIG_PACKAGE_python3-flask-seasurf is not set\n# CONFIG_PACKAGE_python3-flask-session is not set\n# CONFIG_PACKAGE_python3-flask-socketio is not set\n# CONFIG_PACKAGE_python3-flup is not set\n# CONFIG_PACKAGE_python3-gdbm is not set\n# CONFIG_PACKAGE_python3-gmpy2 is not set\n# CONFIG_PACKAGE_python3-gnupg is not set\n# CONFIG_PACKAGE_python3-gpiod is not set\n# CONFIG_PACKAGE_python3-greenlet is not set\n# CONFIG_PACKAGE_python3-hyperlink is not set\n# CONFIG_PACKAGE_python3-idna is not set\n# CONFIG_PACKAGE_python3-ifaddr is not set\n# CONFIG_PACKAGE_python3-incremental is not set\n# CONFIG_PACKAGE_python3-influxdb is not set\n# CONFIG_PACKAGE_python3-iniconfig is not set\n# CONFIG_PACKAGE_python3-intelhex is not set\n# CONFIG_PACKAGE_python3-itsdangerous is not set\n# CONFIG_PACKAGE_python3-jdcal is not set\n# CONFIG_PACKAGE_python3-jinja2 is not set\n# CONFIG_PACKAGE_python3-jmespath is not set\n# CONFIG_PACKAGE_python3-jsonpath-ng is not set\n# CONFIG_PACKAGE_python3-jsonschema is not set\n# CONFIG_PACKAGE_python3-lib2to3 is not set\n# CONFIG_PACKAGE_python3-libmodbus is not set\n# CONFIG_PACKAGE_python3-libselinux is not set\n# CONFIG_PACKAGE_python3-libsemanage is not set\n# CONFIG_PACKAGE_python3-light is not set\n\n#\n# Configuration\n#\n# CONFIG_PYTHON3_BLUETOOTH_SUPPORT is not set\n# CONFIG_PYTHON3_HOST_PIP_CACHE_WORLD_READABLE is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_python3-logging is not set\n# CONFIG_PACKAGE_python3-lxml is not set\n# CONFIG_PACKAGE_python3-lzma is not set\n# CONFIG_PACKAGE_python3-markdown is not set\n# CONFIG_PACKAGE_python3-markupsafe is not set\n# CONFIG_PACKAGE_python3-maxminddb is not set\n# CONFIG_PACKAGE_python3-more-itertools is not set\n# CONFIG_PACKAGE_python3-msgpack is not set\n# CONFIG_PACKAGE_python3-multidict is not set\n# CONFIG_PACKAGE_python3-multiprocessing is not set\n# CONFIG_PACKAGE_python3-ncurses is not set\n# CONFIG_PACKAGE_python3-netdisco is not set\n# CONFIG_PACKAGE_python3-netifaces is not set\n# CONFIG_PACKAGE_python3-networkx is not set\n# CONFIG_PACKAGE_python3-newt is not set\n# CONFIG_PACKAGE_python3-oauthlib is not set\n# CONFIG_PACKAGE_python3-openpyxl is not set\n# CONFIG_PACKAGE_python3-openssl is not set\n# CONFIG_PACKAGE_python3-packaging is not set\n# CONFIG_PACKAGE_python3-paho-mqtt is not set\n# CONFIG_PACKAGE_python3-paramiko is not set\n# CONFIG_PACKAGE_python3-parsley is not set\n# CONFIG_PACKAGE_python3-passlib is not set\n# CONFIG_PACKAGE_python3-pillow is not set\n# CONFIG_PACKAGE_python3-pip is not set\n# CONFIG_PACKAGE_python3-pkg-resources is not set\n# CONFIG_PACKAGE_python3-pluggy is not set\n# CONFIG_PACKAGE_python3-ply is not set\n# CONFIG_PACKAGE_python3-psutil is not set\n# CONFIG_PACKAGE_python3-psycopg2 is not set\n# CONFIG_PACKAGE_python3-py is not set\n# CONFIG_PACKAGE_python3-pyasn1 is not set\n# CONFIG_PACKAGE_python3-pyasn1-modules is not set\n# CONFIG_PACKAGE_python3-pycparser is not set\n# CONFIG_PACKAGE_python3-pydoc is not set\n# CONFIG_PACKAGE_python3-pyjwt is not set\n# CONFIG_PACKAGE_python3-pymysql is not set\n# CONFIG_PACKAGE_python3-pynacl is not set\n# CONFIG_PACKAGE_python3-pyodbc is not set\n# CONFIG_PACKAGE_python3-pyopenssl is not set\n# CONFIG_PACKAGE_python3-pyotp is not set\n# CONFIG_PACKAGE_python3-pyparsing is not set\n# CONFIG_PACKAGE_python3-pyroute2 is not set\n# CONFIG_PACKAGE_python3-pyrsistent is not set\n# CONFIG_PACKAGE_python3-pyserial is not set\n# CONFIG_PACKAGE_python3-pysocks is not set\n# CONFIG_PACKAGE_python3-pytest is not set\n# CONFIG_PACKAGE_python3-pytest-forked is not set\n# CONFIG_PACKAGE_python3-pytest-xdist is not set\n# CONFIG_PACKAGE_python3-pytz is not set\n# CONFIG_PACKAGE_python3-qrcode is not set\n# CONFIG_PACKAGE_python3-rcssmin is not set\n# CONFIG_PACKAGE_python3-readline is not set\n# CONFIG_PACKAGE_python3-requests is not set\n# CONFIG_PACKAGE_python3-requests-oauthlib is not set\n# CONFIG_PACKAGE_python3-rsa is not set\n# CONFIG_PACKAGE_python3-ruamel-yaml is not set\n# CONFIG_PACKAGE_python3-s3transfer is not set\n# CONFIG_PACKAGE_python3-schedule is not set\n# CONFIG_PACKAGE_python3-schema is not set\n# CONFIG_PACKAGE_python3-seafile-ccnet is not set\n# CONFIG_PACKAGE_python3-seafile-server is not set\n# CONFIG_PACKAGE_python3-searpc is not set\n# CONFIG_PACKAGE_python3-sentry-sdk is not set\n# CONFIG_PACKAGE_python3-sepolgen is not set\n# CONFIG_PACKAGE_python3-sepolicy is not set\n# CONFIG_PACKAGE_python3-service-identity is not set\n# CONFIG_PACKAGE_python3-setuptools is not set\n# CONFIG_PACKAGE_python3-simplejson is not set\n# CONFIG_PACKAGE_python3-six is not set\n# CONFIG_PACKAGE_python3-slugify is not set\n# CONFIG_PACKAGE_python3-smbus is not set\n# CONFIG_PACKAGE_python3-socketio is not set\n# CONFIG_PACKAGE_python3-speedtest-cli is not set\n# CONFIG_PACKAGE_python3-sqlalchemy is not set\n# CONFIG_PACKAGE_python3-sqlite3 is not set\n# CONFIG_PACKAGE_python3-sqlparse is not set\n# CONFIG_PACKAGE_python3-stem is not set\n# CONFIG_PACKAGE_python3-sysrepo is not set\n# CONFIG_PACKAGE_python3-text-unidecode is not set\n# CONFIG_PACKAGE_python3-texttable is not set\n# CONFIG_PACKAGE_python3-toml is not set\n# CONFIG_PACKAGE_python3-tornado is not set\n# CONFIG_PACKAGE_python3-twisted is not set\n# CONFIG_PACKAGE_python3-typing-extensions is not set\n# CONFIG_PACKAGE_python3-ubus is not set\n# CONFIG_PACKAGE_python3-uci is not set\n# CONFIG_PACKAGE_python3-unidecode is not set\n# CONFIG_PACKAGE_python3-unittest is not set\n# CONFIG_PACKAGE_python3-urllib is not set\n# CONFIG_PACKAGE_python3-urllib3 is not set\n# CONFIG_PACKAGE_python3-vobject is not set\n# CONFIG_PACKAGE_python3-voluptuous is not set\n# CONFIG_PACKAGE_python3-voluptuous-serialize is not set\n# CONFIG_PACKAGE_python3-wcwidth is not set\n# CONFIG_PACKAGE_python3-websocket-client is not set\n# CONFIG_PACKAGE_python3-werkzeug is not set\n# CONFIG_PACKAGE_python3-xml is not set\n# CONFIG_PACKAGE_python3-xmltodict is not set\n# CONFIG_PACKAGE_python3-yaml is not set\n# CONFIG_PACKAGE_python3-yarl is not set\n# CONFIG_PACKAGE_python3-zeroconf is not set\n# CONFIG_PACKAGE_python3-zipp is not set\n# CONFIG_PACKAGE_python3-zope-interface is not set\n# end of Python\n\n#\n# Ruby\n#\n# CONFIG_PACKAGE_ruby is not set\n# end of Ruby\n\n#\n# Tcl\n#\n# CONFIG_PACKAGE_tcl is not set\n# end of Tcl\n\n# CONFIG_PACKAGE_chicken-scheme-full is not set\n# CONFIG_PACKAGE_chicken-scheme-interpreter is not set\n# CONFIG_PACKAGE_slsh is not set\n# end of Languages\n\n#\n# Libraries\n#\n\n#\n# Compression\n#\n# CONFIG_PACKAGE_libbz2 is not set\n# CONFIG_PACKAGE_liblz4 is not set\n# CONFIG_PACKAGE_liblzma is not set\n# CONFIG_PACKAGE_libunrar is not set\n# CONFIG_PACKAGE_libzip-gnutls is not set\n# CONFIG_PACKAGE_libzip-mbedtls is not set\n# CONFIG_PACKAGE_libzip-nossl is not set\n# CONFIG_PACKAGE_libzip-openssl is not set\n# CONFIG_PACKAGE_libzstd is not set\n# end of Compression\n\n#\n# Database\n#\n# CONFIG_PACKAGE_libmariadb is not set\n# CONFIG_PACKAGE_libpq is not set\n# CONFIG_PACKAGE_libpqxx is not set\n# CONFIG_PACKAGE_libsqlite3 is not set\n# CONFIG_PACKAGE_pgsqlodbc is not set\n# CONFIG_PACKAGE_psqlodbca is not set\n# CONFIG_PACKAGE_psqlodbcw is not set\n# CONFIG_PACKAGE_redis-cli is not set\n# CONFIG_PACKAGE_redis-server is not set\n# CONFIG_PACKAGE_redis-utils is not set\n# CONFIG_PACKAGE_tdb is not set\n# CONFIG_PACKAGE_unixodbc is not set\n# end of Database\n\n#\n# Filesystem\n#\n# CONFIG_PACKAGE_libacl is not set\nCONFIG_PACKAGE_libattr=y\n# CONFIG_PACKAGE_libfuse is not set\n# CONFIG_PACKAGE_libfuse3 is not set\n# CONFIG_PACKAGE_libow is not set\n# CONFIG_PACKAGE_libow-capi is not set\n# CONFIG_PACKAGE_libsysfs is not set\n# end of Filesystem\n\n#\n# Firewall\n#\n# CONFIG_PACKAGE_libfko is not set\nCONFIG_PACKAGE_libip4tc=y\nCONFIG_PACKAGE_libip6tc=y\nCONFIG_PACKAGE_libxtables=y\n# CONFIG_PACKAGE_libxtables-nft is not set\n# end of Firewall\n\n#\n# Instant Messaging\n#\n# CONFIG_PACKAGE_quasselc is not set\n# end of Instant Messaging\n\n#\n# IoT\n#\n# CONFIG_PACKAGE_libmraa is not set\n# CONFIG_PACKAGE_libmraa-python3 is not set\n# CONFIG_PACKAGE_libupm is not set\n# CONFIG_PACKAGE_libupm-a110x is not set\n# CONFIG_PACKAGE_libupm-a110x-python3 is not set\n# CONFIG_PACKAGE_libupm-abp is not set\n# CONFIG_PACKAGE_libupm-abp-python3 is not set\n# CONFIG_PACKAGE_libupm-ad8232 is not set\n# CONFIG_PACKAGE_libupm-ad8232-python3 is not set\n# CONFIG_PACKAGE_libupm-adafruitms1438 is not set\n# CONFIG_PACKAGE_libupm-adafruitms1438-python3 is not set\n# CONFIG_PACKAGE_libupm-adafruitss is not set\n# CONFIG_PACKAGE_libupm-adafruitss-python3 is not set\n# CONFIG_PACKAGE_libupm-adc121c021 is not set\n# CONFIG_PACKAGE_libupm-adc121c021-python3 is not set\n# CONFIG_PACKAGE_libupm-adis16448 is not set\n# CONFIG_PACKAGE_libupm-adis16448-python3 is not set\n# CONFIG_PACKAGE_libupm-ads1x15 is not set\n# CONFIG_PACKAGE_libupm-ads1x15-python3 is not set\n# CONFIG_PACKAGE_libupm-adxl335 is not set\n# CONFIG_PACKAGE_libupm-adxl335-python3 is not set\n# CONFIG_PACKAGE_libupm-adxl345 is not set\n# CONFIG_PACKAGE_libupm-adxl345-python3 is not set\n# CONFIG_PACKAGE_libupm-adxrs610 is not set\n# CONFIG_PACKAGE_libupm-adxrs610-python3 is not set\n# CONFIG_PACKAGE_libupm-am2315 is not set\n# CONFIG_PACKAGE_libupm-am2315-python3 is not set\n# CONFIG_PACKAGE_libupm-apa102 is not set\n# CONFIG_PACKAGE_libupm-apa102-python3 is not set\n# CONFIG_PACKAGE_libupm-apds9002 is not set\n# CONFIG_PACKAGE_libupm-apds9002-python3 is not set\n# CONFIG_PACKAGE_libupm-apds9930 is not set\n# CONFIG_PACKAGE_libupm-apds9930-python3 is not set\n# CONFIG_PACKAGE_libupm-at42qt1070 is not set\n# CONFIG_PACKAGE_libupm-at42qt1070-python3 is not set\n# CONFIG_PACKAGE_libupm-bh1749 is not set\n# CONFIG_PACKAGE_libupm-bh1749-python3 is not set\n# CONFIG_PACKAGE_libupm-bh1750 is not set\n# CONFIG_PACKAGE_libupm-bh1750-python3 is not set\n# CONFIG_PACKAGE_libupm-bh1792 is not set\n# CONFIG_PACKAGE_libupm-bh1792-python3 is not set\n# CONFIG_PACKAGE_libupm-biss0001 is not set\n# CONFIG_PACKAGE_libupm-biss0001-python3 is not set\n# CONFIG_PACKAGE_libupm-bma220 is not set\n# CONFIG_PACKAGE_libupm-bma220-python3 is not set\n# CONFIG_PACKAGE_libupm-bma250e is not set\n# CONFIG_PACKAGE_libupm-bma250e-python3 is not set\n# CONFIG_PACKAGE_libupm-bmg160 is not set\n# CONFIG_PACKAGE_libupm-bmg160-python3 is not set\n# CONFIG_PACKAGE_libupm-bmi160 is not set\n# CONFIG_PACKAGE_libupm-bmi160-python3 is not set\n# CONFIG_PACKAGE_libupm-bmm150 is not set\n# CONFIG_PACKAGE_libupm-bmm150-python3 is not set\n# CONFIG_PACKAGE_libupm-bmp280 is not set\n# CONFIG_PACKAGE_libupm-bmp280-python3 is not set\n# CONFIG_PACKAGE_libupm-bmpx8x is not set\n# CONFIG_PACKAGE_libupm-bmpx8x-python3 is not set\n# CONFIG_PACKAGE_libupm-bmx055 is not set\n# CONFIG_PACKAGE_libupm-bmx055-python3 is not set\n# CONFIG_PACKAGE_libupm-bno055 is not set\n# CONFIG_PACKAGE_libupm-bno055-python3 is not set\n# CONFIG_PACKAGE_libupm-button is not set\n# CONFIG_PACKAGE_libupm-button-python3 is not set\n# CONFIG_PACKAGE_libupm-buzzer is not set\n# CONFIG_PACKAGE_libupm-buzzer-python3 is not set\n# CONFIG_PACKAGE_libupm-cjq4435 is not set\n# CONFIG_PACKAGE_libupm-cjq4435-python3 is not set\n# CONFIG_PACKAGE_libupm-collision is not set\n# CONFIG_PACKAGE_libupm-collision-python3 is not set\n# CONFIG_PACKAGE_libupm-curieimu is not set\n# CONFIG_PACKAGE_libupm-curieimu-python3 is not set\n# CONFIG_PACKAGE_libupm-cwlsxxa is not set\n# CONFIG_PACKAGE_libupm-cwlsxxa-python3 is not set\n# CONFIG_PACKAGE_libupm-dfrec is not set\n# CONFIG_PACKAGE_libupm-dfrec-python3 is not set\n# CONFIG_PACKAGE_libupm-dfrorp is not set\n# CONFIG_PACKAGE_libupm-dfrorp-python3 is not set\n# CONFIG_PACKAGE_libupm-dfrph is not set\n# CONFIG_PACKAGE_libupm-dfrph-python3 is not set\n# CONFIG_PACKAGE_libupm-ds1307 is not set\n# CONFIG_PACKAGE_libupm-ds1307-python3 is not set\n# CONFIG_PACKAGE_libupm-ds1808lc is not set\n# CONFIG_PACKAGE_libupm-ds1808lc-python3 is not set\n# CONFIG_PACKAGE_libupm-ds18b20 is not set\n# CONFIG_PACKAGE_libupm-ds18b20-python3 is not set\n# CONFIG_PACKAGE_libupm-ds2413 is not set\n# CONFIG_PACKAGE_libupm-ds2413-python3 is not set\n# CONFIG_PACKAGE_libupm-ecezo is not set\n# CONFIG_PACKAGE_libupm-ecezo-python3 is not set\n# CONFIG_PACKAGE_libupm-ecs1030 is not set\n# CONFIG_PACKAGE_libupm-ecs1030-python3 is not set\n# CONFIG_PACKAGE_libupm-ehr is not set\n# CONFIG_PACKAGE_libupm-ehr-python3 is not set\n# CONFIG_PACKAGE_libupm-eldriver is not set\n# CONFIG_PACKAGE_libupm-eldriver-python3 is not set\n# CONFIG_PACKAGE_libupm-electromagnet is not set\n# CONFIG_PACKAGE_libupm-electromagnet-python3 is not set\n# CONFIG_PACKAGE_libupm-emg is not set\n# CONFIG_PACKAGE_libupm-emg-python3 is not set\n# CONFIG_PACKAGE_libupm-enc03r is not set\n# CONFIG_PACKAGE_libupm-enc03r-python3 is not set\n# CONFIG_PACKAGE_libupm-flex is not set\n# CONFIG_PACKAGE_libupm-flex-python3 is not set\n# CONFIG_PACKAGE_libupm-gas is not set\n# CONFIG_PACKAGE_libupm-gas-python3 is not set\n# CONFIG_PACKAGE_libupm-gp2y0a is not set\n# CONFIG_PACKAGE_libupm-gp2y0a-python3 is not set\n# CONFIG_PACKAGE_libupm-gprs is not set\n# CONFIG_PACKAGE_libupm-gprs-python3 is not set\n# CONFIG_PACKAGE_libupm-gsr is not set\n# CONFIG_PACKAGE_libupm-gsr-python3 is not set\n# CONFIG_PACKAGE_libupm-guvas12d is not set\n# CONFIG_PACKAGE_libupm-guvas12d-python3 is not set\n# CONFIG_PACKAGE_libupm-h3lis331dl is not set\n# CONFIG_PACKAGE_libupm-h3lis331dl-python3 is not set\n# CONFIG_PACKAGE_libupm-h803x is not set\n# CONFIG_PACKAGE_libupm-h803x-python3 is not set\n# CONFIG_PACKAGE_libupm-hcsr04 is not set\n# CONFIG_PACKAGE_libupm-hcsr04-python3 is not set\n# CONFIG_PACKAGE_libupm-hdc1000 is not set\n# CONFIG_PACKAGE_libupm-hdc1000-python3 is not set\n# CONFIG_PACKAGE_libupm-hdxxvxta is not set\n# CONFIG_PACKAGE_libupm-hdxxvxta-python3 is not set\n# CONFIG_PACKAGE_libupm-hka5 is not set\n# CONFIG_PACKAGE_libupm-hka5-python3 is not set\n# CONFIG_PACKAGE_libupm-hlg150h is not set\n# CONFIG_PACKAGE_libupm-hlg150h-python3 is not set\n# CONFIG_PACKAGE_libupm-hm11 is not set\n# CONFIG_PACKAGE_libupm-hm11-python3 is not set\n# CONFIG_PACKAGE_libupm-hmc5883l is not set\n# CONFIG_PACKAGE_libupm-hmc5883l-python3 is not set\n# CONFIG_PACKAGE_libupm-hmtrp is not set\n# CONFIG_PACKAGE_libupm-hmtrp-python3 is not set\n# CONFIG_PACKAGE_libupm-hp20x is not set\n# CONFIG_PACKAGE_libupm-hp20x-python3 is not set\n# CONFIG_PACKAGE_libupm-ht9170 is not set\n# CONFIG_PACKAGE_libupm-ht9170-python3 is not set\n# CONFIG_PACKAGE_libupm-htu21d is not set\n# CONFIG_PACKAGE_libupm-htu21d-python3 is not set\n# CONFIG_PACKAGE_libupm-hwxpxx is not set\n# CONFIG_PACKAGE_libupm-hwxpxx-python3 is not set\n# CONFIG_PACKAGE_libupm-hx711 is not set\n# CONFIG_PACKAGE_libupm-hx711-python3 is not set\n# CONFIG_PACKAGE_libupm-ili9341 is not set\n# CONFIG_PACKAGE_libupm-ili9341-python3 is not set\n# CONFIG_PACKAGE_libupm-ims is not set\n# CONFIG_PACKAGE_libupm-ims-python3 is not set\n# CONFIG_PACKAGE_libupm-ina132 is not set\n# CONFIG_PACKAGE_libupm-ina132-python3 is not set\n# CONFIG_PACKAGE_libupm-interfaces is not set\n# CONFIG_PACKAGE_libupm-interfaces-python3 is not set\n# CONFIG_PACKAGE_libupm-isd1820 is not set\n# CONFIG_PACKAGE_libupm-isd1820-python3 is not set\n# CONFIG_PACKAGE_libupm-itg3200 is not set\n# CONFIG_PACKAGE_libupm-itg3200-python3 is not set\n# CONFIG_PACKAGE_libupm-jhd1313m1 is not set\n# CONFIG_PACKAGE_libupm-jhd1313m1-python3 is not set\n# CONFIG_PACKAGE_libupm-joystick12 is not set\n# CONFIG_PACKAGE_libupm-joystick12-python3 is not set\n# CONFIG_PACKAGE_libupm-kx122 is not set\n# CONFIG_PACKAGE_libupm-kx122-python3 is not set\n# CONFIG_PACKAGE_libupm-kxcjk1013 is not set\n# CONFIG_PACKAGE_libupm-kxcjk1013-python3 is not set\n# CONFIG_PACKAGE_libupm-kxtj3 is not set\n# CONFIG_PACKAGE_libupm-kxtj3-python3 is not set\n# CONFIG_PACKAGE_libupm-l298 is not set\n# CONFIG_PACKAGE_libupm-l298-python3 is not set\n# CONFIG_PACKAGE_libupm-l3gd20 is not set\n# CONFIG_PACKAGE_libupm-l3gd20-python3 is not set\n# CONFIG_PACKAGE_libupm-lcd is not set\n# CONFIG_PACKAGE_libupm-lcd-python3 is not set\n# CONFIG_PACKAGE_libupm-lcdks is not set\n# CONFIG_PACKAGE_libupm-lcdks-python3 is not set\n# CONFIG_PACKAGE_libupm-lcm1602 is not set\n# CONFIG_PACKAGE_libupm-lcm1602-python3 is not set\n# CONFIG_PACKAGE_libupm-ldt0028 is not set\n# CONFIG_PACKAGE_libupm-ldt0028-python3 is not set\n# CONFIG_PACKAGE_libupm-led is not set\n# CONFIG_PACKAGE_libupm-led-python3 is not set\n# CONFIG_PACKAGE_libupm-lidarlitev3 is not set\n# CONFIG_PACKAGE_libupm-lidarlitev3-python3 is not set\n# CONFIG_PACKAGE_libupm-light is not set\n# CONFIG_PACKAGE_libupm-light-python3 is not set\n# CONFIG_PACKAGE_libupm-linefinder is not set\n# CONFIG_PACKAGE_libupm-linefinder-python3 is not set\n# CONFIG_PACKAGE_libupm-lis2ds12 is not set\n# CONFIG_PACKAGE_libupm-lis2ds12-python3 is not set\n# CONFIG_PACKAGE_libupm-lis3dh is not set\n# CONFIG_PACKAGE_libupm-lis3dh-python3 is not set\n# CONFIG_PACKAGE_libupm-lm35 is not set\n# CONFIG_PACKAGE_libupm-lm35-python3 is not set\n# CONFIG_PACKAGE_libupm-lol is not set\n# CONFIG_PACKAGE_libupm-lol-python3 is not set\n# CONFIG_PACKAGE_libupm-loudness is not set\n# CONFIG_PACKAGE_libupm-loudness-python3 is not set\n# CONFIG_PACKAGE_libupm-lp8860 is not set\n# CONFIG_PACKAGE_libupm-lp8860-python3 is not set\n# CONFIG_PACKAGE_libupm-lpd8806 is not set\n# CONFIG_PACKAGE_libupm-lpd8806-python3 is not set\n# CONFIG_PACKAGE_libupm-lsm303agr is not set\n# CONFIG_PACKAGE_libupm-lsm303agr-python3 is not set\n# CONFIG_PACKAGE_libupm-lsm303d is not set\n# CONFIG_PACKAGE_libupm-lsm303d-python3 is not set\n# CONFIG_PACKAGE_libupm-lsm303dlh is not set\n# CONFIG_PACKAGE_libupm-lsm303dlh-python3 is not set\n# CONFIG_PACKAGE_libupm-lsm6ds3h is not set\n# CONFIG_PACKAGE_libupm-lsm6ds3h-python3 is not set\n# CONFIG_PACKAGE_libupm-lsm6dsl is not set\n# CONFIG_PACKAGE_libupm-lsm6dsl-python3 is not set\n# CONFIG_PACKAGE_libupm-lsm9ds0 is not set\n# CONFIG_PACKAGE_libupm-lsm9ds0-python3 is not set\n# CONFIG_PACKAGE_libupm-m24lr64e is not set\n# CONFIG_PACKAGE_libupm-m24lr64e-python3 is not set\n# CONFIG_PACKAGE_libupm-mag3110 is not set\n# CONFIG_PACKAGE_libupm-mag3110-python3 is not set\n# CONFIG_PACKAGE_libupm-max30100 is not set\n# CONFIG_PACKAGE_libupm-max30100-python3 is not set\n# CONFIG_PACKAGE_libupm-max31723 is not set\n# CONFIG_PACKAGE_libupm-max31723-python3 is not set\n# CONFIG_PACKAGE_libupm-max31855 is not set\n# CONFIG_PACKAGE_libupm-max31855-python3 is not set\n# CONFIG_PACKAGE_libupm-max44000 is not set\n# CONFIG_PACKAGE_libupm-max44000-python3 is not set\n# CONFIG_PACKAGE_libupm-max44009 is not set\n# CONFIG_PACKAGE_libupm-max44009-python3 is not set\n# CONFIG_PACKAGE_libupm-max5487 is not set\n# CONFIG_PACKAGE_libupm-max5487-python3 is not set\n# CONFIG_PACKAGE_libupm-maxds3231m is not set\n# CONFIG_PACKAGE_libupm-maxds3231m-python3 is not set\n# CONFIG_PACKAGE_libupm-maxsonarez is not set\n# CONFIG_PACKAGE_libupm-maxsonarez-python3 is not set\n# CONFIG_PACKAGE_libupm-mb704x is not set\n# CONFIG_PACKAGE_libupm-mb704x-python3 is not set\n# CONFIG_PACKAGE_libupm-mcp2515 is not set\n# CONFIG_PACKAGE_libupm-mcp2515-python3 is not set\n# CONFIG_PACKAGE_libupm-mcp9808 is not set\n# CONFIG_PACKAGE_libupm-mcp9808-python3 is not set\n# CONFIG_PACKAGE_libupm-md is not set\n# CONFIG_PACKAGE_libupm-md-python3 is not set\n# CONFIG_PACKAGE_libupm-mg811 is not set\n# CONFIG_PACKAGE_libupm-mg811-python3 is not set\n# CONFIG_PACKAGE_libupm-mhz16 is not set\n# CONFIG_PACKAGE_libupm-mhz16-python3 is not set\n# CONFIG_PACKAGE_libupm-mic is not set\n# CONFIG_PACKAGE_libupm-mic-python3 is not set\n# CONFIG_PACKAGE_libupm-micsv89 is not set\n# CONFIG_PACKAGE_libupm-micsv89-python3 is not set\n# CONFIG_PACKAGE_libupm-mlx90614 is not set\n# CONFIG_PACKAGE_libupm-mlx90614-python3 is not set\n# CONFIG_PACKAGE_libupm-mma7361 is not set\n# CONFIG_PACKAGE_libupm-mma7361-python3 is not set\n# CONFIG_PACKAGE_libupm-mma7455 is not set\n# CONFIG_PACKAGE_libupm-mma7455-python3 is not set\n# CONFIG_PACKAGE_libupm-mma7660 is not set\n# CONFIG_PACKAGE_libupm-mma7660-python3 is not set\n# CONFIG_PACKAGE_libupm-mma8x5x is not set\n# CONFIG_PACKAGE_libupm-mma8x5x-python3 is not set\n# CONFIG_PACKAGE_libupm-mmc35240 is not set\n# CONFIG_PACKAGE_libupm-mmc35240-python3 is not set\n# CONFIG_PACKAGE_libupm-moisture is not set\n# CONFIG_PACKAGE_libupm-moisture-python3 is not set\n# CONFIG_PACKAGE_libupm-mpl3115a2 is not set\n# CONFIG_PACKAGE_libupm-mpl3115a2-python3 is not set\n# CONFIG_PACKAGE_libupm-mpr121 is not set\n# CONFIG_PACKAGE_libupm-mpr121-python3 is not set\n# CONFIG_PACKAGE_libupm-mpu9150 is not set\n# CONFIG_PACKAGE_libupm-mpu9150-python3 is not set\n# CONFIG_PACKAGE_libupm-mq303a is not set\n# CONFIG_PACKAGE_libupm-mq303a-python3 is not set\n# CONFIG_PACKAGE_libupm-ms5611 is not set\n# CONFIG_PACKAGE_libupm-ms5611-python3 is not set\n# CONFIG_PACKAGE_libupm-ms5803 is not set\n# CONFIG_PACKAGE_libupm-ms5803-python3 is not set\n# CONFIG_PACKAGE_libupm-my9221 is not set\n# CONFIG_PACKAGE_libupm-my9221-python3 is not set\n# CONFIG_PACKAGE_libupm-nlgpio16 is not set\n# CONFIG_PACKAGE_libupm-nlgpio16-python3 is not set\n# CONFIG_PACKAGE_libupm-nmea_gps is not set\n# CONFIG_PACKAGE_libupm-nmea_gps-python3 is not set\n# CONFIG_PACKAGE_libupm-nrf24l01 is not set\n# CONFIG_PACKAGE_libupm-nrf24l01-python3 is not set\n# CONFIG_PACKAGE_libupm-nrf8001 is not set\n# CONFIG_PACKAGE_libupm-nrf8001-python3 is not set\n# CONFIG_PACKAGE_libupm-nunchuck is not set\n# CONFIG_PACKAGE_libupm-nunchuck-python3 is not set\n# CONFIG_PACKAGE_libupm-o2 is not set\n# CONFIG_PACKAGE_libupm-o2-python3 is not set\n# CONFIG_PACKAGE_libupm-otp538u is not set\n# CONFIG_PACKAGE_libupm-otp538u-python3 is not set\n# CONFIG_PACKAGE_libupm-ozw is not set\n# CONFIG_PACKAGE_libupm-ozw-python3 is not set\n# CONFIG_PACKAGE_libupm-p9813 is not set\n# CONFIG_PACKAGE_libupm-p9813-python3 is not set\n# CONFIG_PACKAGE_libupm-pca9685 is not set\n# CONFIG_PACKAGE_libupm-pca9685-python3 is not set\n# CONFIG_PACKAGE_libupm-pn532 is not set\n# CONFIG_PACKAGE_libupm-pn532-python3 is not set\n# CONFIG_PACKAGE_libupm-ppd42ns is not set\n# CONFIG_PACKAGE_libupm-ppd42ns-python3 is not set\n# CONFIG_PACKAGE_libupm-pulsensor is not set\n# CONFIG_PACKAGE_libupm-pulsensor-python3 is not set\n# CONFIG_PACKAGE_libupm-relay is not set\n# CONFIG_PACKAGE_libupm-relay-python3 is not set\n# CONFIG_PACKAGE_libupm-rf22 is not set\n# CONFIG_PACKAGE_libupm-rf22-python3 is not set\n# CONFIG_PACKAGE_libupm-rfr359f is not set\n# CONFIG_PACKAGE_libupm-rfr359f-python3 is not set\n# CONFIG_PACKAGE_libupm-rgbringcoder is not set\n# CONFIG_PACKAGE_libupm-rgbringcoder-python3 is not set\n# CONFIG_PACKAGE_libupm-rhusb is not set\n# CONFIG_PACKAGE_libupm-rhusb-python3 is not set\n# CONFIG_PACKAGE_libupm-rn2903 is not set\n# CONFIG_PACKAGE_libupm-rn2903-python3 is not set\n# CONFIG_PACKAGE_libupm-rotary is not set\n# CONFIG_PACKAGE_libupm-rotary-python3 is not set\n# CONFIG_PACKAGE_libupm-rotaryencoder is not set\n# CONFIG_PACKAGE_libupm-rotaryencoder-python3 is not set\n# CONFIG_PACKAGE_libupm-rpr220 is not set\n# CONFIG_PACKAGE_libupm-rpr220-python3 is not set\n# CONFIG_PACKAGE_libupm-rsc is not set\n# CONFIG_PACKAGE_libupm-rsc-python3 is not set\n# CONFIG_PACKAGE_libupm-scam is not set\n# CONFIG_PACKAGE_libupm-scam-python3 is not set\n# CONFIG_PACKAGE_libupm-sensortemplate is not set\n# CONFIG_PACKAGE_libupm-sensortemplate-python3 is not set\n# CONFIG_PACKAGE_libupm-servo is not set\n# CONFIG_PACKAGE_libupm-servo-python3 is not set\n# CONFIG_PACKAGE_libupm-sht1x is not set\n# CONFIG_PACKAGE_libupm-sht1x-python3 is not set\n# CONFIG_PACKAGE_libupm-si1132 is not set\n# CONFIG_PACKAGE_libupm-si1132-python3 is not set\n# CONFIG_PACKAGE_libupm-si114x is not set\n# CONFIG_PACKAGE_libupm-si114x-python3 is not set\n# CONFIG_PACKAGE_libupm-si7005 is not set\n# CONFIG_PACKAGE_libupm-si7005-python3 is not set\n# CONFIG_PACKAGE_libupm-slide is not set\n# CONFIG_PACKAGE_libupm-slide-python3 is not set\n# CONFIG_PACKAGE_libupm-sm130 is not set\n# CONFIG_PACKAGE_libupm-sm130-python3 is not set\n# CONFIG_PACKAGE_libupm-smartdrive is not set\n# CONFIG_PACKAGE_libupm-smartdrive-python3 is not set\n# CONFIG_PACKAGE_libupm-speaker is not set\n# CONFIG_PACKAGE_libupm-speaker-python3 is not set\n# CONFIG_PACKAGE_libupm-ssd1351 is not set\n# CONFIG_PACKAGE_libupm-ssd1351-python3 is not set\n# CONFIG_PACKAGE_libupm-st7735 is not set\n# CONFIG_PACKAGE_libupm-st7735-python3 is not set\n# CONFIG_PACKAGE_libupm-stepmotor is not set\n# CONFIG_PACKAGE_libupm-stepmotor-python3 is not set\n# CONFIG_PACKAGE_libupm-sx1276 is not set\n# CONFIG_PACKAGE_libupm-sx1276-python3 is not set\n# CONFIG_PACKAGE_libupm-sx6119 is not set\n# CONFIG_PACKAGE_libupm-sx6119-python3 is not set\n# CONFIG_PACKAGE_libupm-t3311 is not set\n# CONFIG_PACKAGE_libupm-t3311-python3 is not set\n# CONFIG_PACKAGE_libupm-t6713 is not set\n# CONFIG_PACKAGE_libupm-t6713-python3 is not set\n# CONFIG_PACKAGE_libupm-ta12200 is not set\n# CONFIG_PACKAGE_libupm-ta12200-python3 is not set\n# CONFIG_PACKAGE_libupm-tca9548a is not set\n# CONFIG_PACKAGE_libupm-tca9548a-python3 is not set\n# CONFIG_PACKAGE_libupm-tcs3414cs is not set\n# CONFIG_PACKAGE_libupm-tcs3414cs-python3 is not set\n# CONFIG_PACKAGE_libupm-tcs37727 is not set\n# CONFIG_PACKAGE_libupm-tcs37727-python3 is not set\n# CONFIG_PACKAGE_libupm-teams is not set\n# CONFIG_PACKAGE_libupm-teams-python3 is not set\n# CONFIG_PACKAGE_libupm-temperature is not set\n# CONFIG_PACKAGE_libupm-temperature-python3 is not set\n# CONFIG_PACKAGE_libupm-tex00 is not set\n# CONFIG_PACKAGE_libupm-tex00-python3 is not set\n# CONFIG_PACKAGE_libupm-th02 is not set\n# CONFIG_PACKAGE_libupm-th02-python3 is not set\n# CONFIG_PACKAGE_libupm-tm1637 is not set\n# CONFIG_PACKAGE_libupm-tm1637-python3 is not set\n# CONFIG_PACKAGE_libupm-tmp006 is not set\n# CONFIG_PACKAGE_libupm-tmp006-python3 is not set\n# CONFIG_PACKAGE_libupm-tsl2561 is not set\n# CONFIG_PACKAGE_libupm-tsl2561-python3 is not set\n# CONFIG_PACKAGE_libupm-ttp223 is not set\n# CONFIG_PACKAGE_libupm-ttp223-python3 is not set\n# CONFIG_PACKAGE_libupm-uartat is not set\n# CONFIG_PACKAGE_libupm-uartat-python3 is not set\n# CONFIG_PACKAGE_libupm-uln200xa is not set\n# CONFIG_PACKAGE_libupm-uln200xa-python3 is not set\n# CONFIG_PACKAGE_libupm-ultrasonic is not set\n# CONFIG_PACKAGE_libupm-ultrasonic-python3 is not set\n# CONFIG_PACKAGE_libupm-urm37 is not set\n# CONFIG_PACKAGE_libupm-urm37-python3 is not set\n# CONFIG_PACKAGE_libupm-utilities is not set\n# CONFIG_PACKAGE_libupm-utilities-python3 is not set\n# CONFIG_PACKAGE_libupm-vcap is not set\n# CONFIG_PACKAGE_libupm-vcap-python3 is not set\n# CONFIG_PACKAGE_libupm-vdiv is not set\n# CONFIG_PACKAGE_libupm-vdiv-python3 is not set\n# CONFIG_PACKAGE_libupm-veml6070 is not set\n# CONFIG_PACKAGE_libupm-veml6070-python3 is not set\n# CONFIG_PACKAGE_libupm-water is not set\n# CONFIG_PACKAGE_libupm-water-python3 is not set\n# CONFIG_PACKAGE_libupm-waterlevel is not set\n# CONFIG_PACKAGE_libupm-waterlevel-python3 is not set\n# CONFIG_PACKAGE_libupm-wfs is not set\n# CONFIG_PACKAGE_libupm-wfs-python3 is not set\n# CONFIG_PACKAGE_libupm-wheelencoder is not set\n# CONFIG_PACKAGE_libupm-wheelencoder-python3 is not set\n# CONFIG_PACKAGE_libupm-wt5001 is not set\n# CONFIG_PACKAGE_libupm-wt5001-python3 is not set\n# CONFIG_PACKAGE_libupm-xbee is not set\n# CONFIG_PACKAGE_libupm-xbee-python3 is not set\n# CONFIG_PACKAGE_libupm-yg1006 is not set\n# CONFIG_PACKAGE_libupm-yg1006-python3 is not set\n# CONFIG_PACKAGE_libupm-zfm20 is not set\n# CONFIG_PACKAGE_libupm-zfm20-python3 is not set\n# end of IoT\n\n#\n# Languages\n#\n# CONFIG_PACKAGE_libyaml is not set\n# end of Languages\n\n#\n# LibElektra\n#\n# CONFIG_PACKAGE_libelektra-boost is not set\n# CONFIG_PACKAGE_libelektra-core is not set\n# CONFIG_PACKAGE_libelektra-cpp is not set\n# CONFIG_PACKAGE_libelektra-crypto is not set\n# CONFIG_PACKAGE_libelektra-curlget is not set\n# CONFIG_PACKAGE_libelektra-dbus is not set\n# CONFIG_PACKAGE_libelektra-extra is not set\n# CONFIG_PACKAGE_libelektra-lua is not set\n# CONFIG_PACKAGE_libelektra-plugins is not set\n# CONFIG_PACKAGE_libelektra-python3 is not set\n# CONFIG_PACKAGE_libelektra-resolvers is not set\n# CONFIG_PACKAGE_libelektra-xerces is not set\n# CONFIG_PACKAGE_libelektra-xml is not set\n# CONFIG_PACKAGE_libelektra-yajl is not set\n# CONFIG_PACKAGE_libelektra-yamlcpp is not set\n# CONFIG_PACKAGE_libelektra-zmq is not set\n# end of LibElektra\n\n#\n# Networking\n#\n# CONFIG_PACKAGE_libdcwproto is not set\n# CONFIG_PACKAGE_libdcwsocket is not set\n# CONFIG_PACKAGE_libsctp is not set\n# CONFIG_PACKAGE_libuhttpd-mbedtls is not set\n# CONFIG_PACKAGE_libuhttpd-nossl is not set\n# CONFIG_PACKAGE_libuhttpd-openssl is not set\n# CONFIG_PACKAGE_libuhttpd-wolfssl is not set\n# CONFIG_PACKAGE_libulfius-gnutls is not set\n# CONFIG_PACKAGE_libulfius-nossl is not set\n# CONFIG_PACKAGE_libunbound is not set\n# CONFIG_PACKAGE_libuwsc-mbedtls is not set\n# CONFIG_PACKAGE_libuwsc-nossl is not set\n# CONFIG_PACKAGE_libuwsc-openssl is not set\n# CONFIG_PACKAGE_libuwsc-wolfssl is not set\n# end of Networking\n\n#\n# Qt5\n#\n# CONFIG_PACKAGE_qt5-core is not set\n# CONFIG_PACKAGE_qt5-network is not set\n# CONFIG_PACKAGE_qt5-sql is not set\n# CONFIG_PACKAGE_qt5-xml is not set\n# CONFIG_PACKAGE_qtbase is not set\nCONFIG_QT5_INCLUDE_ATOMIC=y\n\n#\n# Select Qtbase Libraries\n#\n\n#\n# Qtbase Libraries\n#\n# end of Select Qtbase Libraries\n# end of Qt5\n\n#\n# SSL\n#\n# CONFIG_PACKAGE_libgnutls is not set\n# CONFIG_PACKAGE_libgnutls-dane is not set\nCONFIG_PACKAGE_libmbedtls=y\n# CONFIG_LIBMBEDTLS_DEBUG_C is not set\n# CONFIG_LIBMBEDTLS_HKDF_C is not set\n# CONFIG_PACKAGE_libnss is not set\nCONFIG_PACKAGE_libopenssl=y\n\n#\n# Build Options\n#\nCONFIG_OPENSSL_OPTIMIZE_SPEED=y\nCONFIG_OPENSSL_WITH_ASM=y\nCONFIG_OPENSSL_WITH_DEPRECATED=y\n# CONFIG_OPENSSL_NO_DEPRECATED is not set\nCONFIG_OPENSSL_WITH_ERROR_MESSAGES=y\n\n#\n# Protocol Support\n#\nCONFIG_OPENSSL_WITH_TLS13=y\n# CONFIG_OPENSSL_WITH_DTLS is not set\n# CONFIG_OPENSSL_WITH_NPN is not set\nCONFIG_OPENSSL_WITH_SRP=y\nCONFIG_OPENSSL_WITH_CMS=y\n\n#\n# Algorithm Selection\n#\n# CONFIG_OPENSSL_WITH_EC2M is not set\nCONFIG_OPENSSL_WITH_CHACHA_POLY1305=y\nCONFIG_OPENSSL_PREFER_CHACHA_OVER_GCM=y\nCONFIG_OPENSSL_WITH_PSK=y\n\n#\n# Less commonly used build options\n#\n# CONFIG_OPENSSL_WITH_ARIA is not set\n# CONFIG_OPENSSL_WITH_CAMELLIA is not set\n# CONFIG_OPENSSL_WITH_IDEA is not set\n# CONFIG_OPENSSL_WITH_SEED is not set\n# CONFIG_OPENSSL_WITH_SM234 is not set\n# CONFIG_OPENSSL_WITH_BLAKE2 is not set\n# CONFIG_OPENSSL_WITH_MDC2 is not set\n# CONFIG_OPENSSL_WITH_WHIRLPOOL is not set\n# CONFIG_OPENSSL_WITH_COMPRESSION is not set\n# CONFIG_OPENSSL_WITH_RFC3779 is not set\n\n#\n# Engine/Hardware Support\n#\nCONFIG_OPENSSL_ENGINE=y\nCONFIG_OPENSSL_ENGINE_BUILTIN=y\nCONFIG_OPENSSL_ENGINE_BUILTIN_AFALG=y\nCONFIG_OPENSSL_ENGINE_BUILTIN_DEVCRYPTO=y\nCONFIG_PACKAGE_libopenssl-conf=y\n# CONFIG_PACKAGE_libopenssl-devcrypto is not set\n# CONFIG_PACKAGE_libopenssl-gost_engine is not set\n# CONFIG_PACKAGE_libpolarssl is not set\n# CONFIG_PACKAGE_libwolfssl is not set\n# end of SSL\n\n#\n# Sound\n#\n# CONFIG_PACKAGE_alsa-ucm-conf is not set\n# CONFIG_PACKAGE_liblo is not set\n# end of Sound\n\n#\n# Telephony\n#\n# CONFIG_PACKAGE_bcg729 is not set\n# CONFIG_PACKAGE_dahdi-tools-libtonezone is not set\n# CONFIG_PACKAGE_gsmlib is not set\n# CONFIG_PACKAGE_libctb is not set\n# CONFIG_PACKAGE_libfreetdm is not set\n# CONFIG_PACKAGE_libiksemel is not set\n# CONFIG_PACKAGE_libks is not set\n# CONFIG_PACKAGE_libosip2 is not set\n# CONFIG_PACKAGE_libpj is not set\n# CONFIG_PACKAGE_libpjlib-util is not set\n# CONFIG_PACKAGE_libpjmedia is not set\n# CONFIG_PACKAGE_libpjnath is not set\n# CONFIG_PACKAGE_libpjsip is not set\n# CONFIG_PACKAGE_libpjsip-simple is not set\n# CONFIG_PACKAGE_libpjsip-ua is not set\n# CONFIG_PACKAGE_libpjsua is not set\n# CONFIG_PACKAGE_libpjsua2 is not set\n# CONFIG_PACKAGE_libre is not set\n# CONFIG_PACKAGE_librem is not set\n# CONFIG_PACKAGE_libspandsp is not set\n# CONFIG_PACKAGE_libspandsp3 is not set\n# CONFIG_PACKAGE_libsrtp2 is not set\n# CONFIG_PACKAGE_signalwire-client-c is not set\n# CONFIG_PACKAGE_sofia-sip is not set\n# end of Telephony\n\n#\n# libimobiledevice\n#\n# CONFIG_PACKAGE_libimobiledevice is not set\n# CONFIG_PACKAGE_libirecovery is not set\n# CONFIG_PACKAGE_libplist is not set\n# CONFIG_PACKAGE_libusbmuxd is not set\n# end of libimobiledevice\n\n# CONFIG_PACKAGE_acsccid is not set\n# CONFIG_PACKAGE_alsa-lib is not set\n# CONFIG_PACKAGE_argp-standalone is not set\n# CONFIG_PACKAGE_bind-libs is not set\n# CONFIG_PACKAGE_bluez-libs is not set\nCONFIG_PACKAGE_boost=y\n# CONFIG_boost-context-exclude is not set\n# CONFIG_boost-coroutine-exclude is not set\n# CONFIG_boost-fiber-exclude is not set\n\n#\n# Select Boost Options\n#\n\n#\n# Boost compilation options.\n#\n# CONFIG_boost-compile-visibility-global is not set\n# CONFIG_boost-compile-visibility-protected is not set\nCONFIG_boost-compile-visibility-hidden=y\n# CONFIG_boost-shared-libs is not set\n# CONFIG_boost-static-libs is not set\nCONFIG_boost-static-and-shared-libs=y\nCONFIG_boost-runtime-shared=y\nCONFIG_boost-variant-release=y\n# CONFIG_boost-variant-debug is not set\n# CONFIG_boost-variant-profile is not set\n# CONFIG_boost-use-name-tags is not set\n# end of Select Boost Options\n\n#\n# Select Boost libraries\n#\n\n#\n# Libraries\n#\n# CONFIG_boost-libs-all is not set\n# CONFIG_boost-test-pkg is not set\n# CONFIG_boost-graph-parallel is not set\n# CONFIG_PACKAGE_boost-atomic is not set\n# CONFIG_PACKAGE_boost-chrono is not set\n# CONFIG_PACKAGE_boost-container is not set\n# CONFIG_PACKAGE_boost-context is not set\n# CONFIG_PACKAGE_boost-contract is not set\n# CONFIG_PACKAGE_boost-coroutine is not set\n# CONFIG_PACKAGE_boost-date_time is not set\n# CONFIG_PACKAGE_boost-fiber is not set\n# CONFIG_PACKAGE_boost-filesystem is not set\n# CONFIG_PACKAGE_boost-graph is not set\n# CONFIG_PACKAGE_boost-iostreams is not set\n# CONFIG_PACKAGE_boost-json is not set\n# CONFIG_PACKAGE_boost-locale is not set\n# CONFIG_PACKAGE_boost-log is not set\n# CONFIG_PACKAGE_boost-math is not set\n# CONFIG_PACKAGE_boost-nowide is not set\nCONFIG_PACKAGE_boost-program_options=y\n# CONFIG_PACKAGE_boost-python3 is not set\n# CONFIG_PACKAGE_boost-random is not set\n# CONFIG_PACKAGE_boost-regex is not set\n# CONFIG_PACKAGE_boost-serialization is not set\n# CONFIG_PACKAGE_boost-wserialization is not set\n# CONFIG_PACKAGE_boost-stacktrace is not set\nCONFIG_PACKAGE_boost-system=y\n# CONFIG_PACKAGE_boost-thread is not set\n# CONFIG_PACKAGE_boost-timer is not set\n# CONFIG_PACKAGE_boost-type_erasure is not set\n# CONFIG_PACKAGE_boost-wave is not set\n# end of Select Boost libraries\n\n# CONFIG_PACKAGE_cJSON is not set\n# CONFIG_PACKAGE_ccid is not set\n# CONFIG_PACKAGE_check is not set\n# CONFIG_PACKAGE_confuse is not set\n# CONFIG_PACKAGE_czmq is not set\n# CONFIG_PACKAGE_dtndht is not set\n# CONFIG_PACKAGE_getdns is not set\n# CONFIG_PACKAGE_giflib is not set\n# CONFIG_PACKAGE_glib2 is not set\n# CONFIG_PACKAGE_google-authenticator-libpam is not set\n# CONFIG_PACKAGE_hidapi is not set\n# CONFIG_PACKAGE_ibrcommon is not set\n# CONFIG_PACKAGE_ibrdtn is not set\n# CONFIG_PACKAGE_icu is not set\n# CONFIG_PACKAGE_icu-data-tools is not set\n# CONFIG_PACKAGE_icu-full-data is not set\n# CONFIG_PACKAGE_jansson is not set\n# CONFIG_PACKAGE_json-glib is not set\n# CONFIG_PACKAGE_jsoncpp is not set\n# CONFIG_PACKAGE_knot-libs is not set\n# CONFIG_PACKAGE_knot-libzscanner is not set\n# CONFIG_PACKAGE_libaio is not set\n# CONFIG_PACKAGE_libantlr3c is not set\n# CONFIG_PACKAGE_libao is not set\n# CONFIG_PACKAGE_libapparmor is not set\n# CONFIG_PACKAGE_libapr is not set\n# CONFIG_PACKAGE_libaprutil is not set\n# CONFIG_PACKAGE_libarchive is not set\n# CONFIG_PACKAGE_libarchive-noopenssl is not set\n# CONFIG_PACKAGE_libasm is not set\n# CONFIG_PACKAGE_libassuan is not set\n# CONFIG_PACKAGE_libatasmart is not set\n# CONFIG_PACKAGE_libaudit is not set\n# CONFIG_PACKAGE_libauparse is not set\n# CONFIG_PACKAGE_libavahi-client is not set\n# CONFIG_PACKAGE_libavahi-compat-libdnssd is not set\n# CONFIG_PACKAGE_libavahi-dbus-support is not set\n# CONFIG_PACKAGE_libavahi-nodbus-support is not set\n# CONFIG_PACKAGE_libbfd is not set\nCONFIG_PACKAGE_libblkid=y\nCONFIG_PACKAGE_libblobmsg-json=y\nCONFIG_PACKAGE_libbpf=y\n# CONFIG_PACKAGE_libbsd is not set\nCONFIG_PACKAGE_libcap=y\n# CONFIG_PACKAGE_libcap-bin is not set\n# CONFIG_PACKAGE_libcap-ng is not set\n# CONFIG_PACKAGE_libcares is not set\n# CONFIG_PACKAGE_libcbor is not set\n# CONFIG_PACKAGE_libcgroup is not set\n# CONFIG_PACKAGE_libcharset is not set\n# CONFIG_PACKAGE_libcoap is not set\nCONFIG_PACKAGE_libcomerr=y\n# CONFIG_PACKAGE_libconfig is not set\n# CONFIG_PACKAGE_libcryptopp is not set\n# CONFIG_PACKAGE_libctf is not set\nCONFIG_PACKAGE_libcurl=y\n\n#\n# SSL support\n#\n# CONFIG_LIBCURL_MBEDTLS is not set\n# CONFIG_LIBCURL_WOLFSSL is not set\nCONFIG_LIBCURL_OPENSSL=y\n# CONFIG_LIBCURL_GNUTLS is not set\n# CONFIG_LIBCURL_NOSSL is not set\n\n#\n# Supported protocols\n#\n# CONFIG_LIBCURL_DICT is not set\nCONFIG_LIBCURL_FILE=y\nCONFIG_LIBCURL_FTP=y\n# CONFIG_LIBCURL_GOPHER is not set\nCONFIG_LIBCURL_HTTP=y\nCONFIG_LIBCURL_COOKIES=y\n# CONFIG_LIBCURL_IMAP is not set\n# CONFIG_LIBCURL_LDAP is not set\n# CONFIG_LIBCURL_POP3 is not set\n# CONFIG_LIBCURL_RTSP is not set\n# CONFIG_LIBCURL_SSH2 is not set\nCONFIG_LIBCURL_NO_SMB=\"!\"\n# CONFIG_LIBCURL_SMTP is not set\n# CONFIG_LIBCURL_TELNET is not set\n# CONFIG_LIBCURL_TFTP is not set\n# CONFIG_LIBCURL_NGHTTP2 is not set\n\n#\n# Miscellaneous\n#\nCONFIG_LIBCURL_PROXY=y\n# CONFIG_LIBCURL_CRYPTO_AUTH is not set\n# CONFIG_LIBCURL_TLS_SRP is not set\n# CONFIG_LIBCURL_LIBIDN2 is not set\n# CONFIG_LIBCURL_THREADED_RESOLVER is not set\n# CONFIG_LIBCURL_ZLIB is not set\n# CONFIG_LIBCURL_ZSTD is not set\n# CONFIG_LIBCURL_UNIX_SOCKETS is not set\n# CONFIG_LIBCURL_LIBCURL_OPTION is not set\n# CONFIG_LIBCURL_VERBOSE is not set\n# CONFIG_PACKAGE_libdaemon is not set\n# CONFIG_PACKAGE_libdaq is not set\n# CONFIG_PACKAGE_libdaq3 is not set\n# CONFIG_PACKAGE_libdb47 is not set\n# CONFIG_PACKAGE_libdb47xx is not set\n# CONFIG_PACKAGE_libdbi is not set\n# CONFIG_PACKAGE_libdbus is not set\n# CONFIG_PACKAGE_libdevmapper is not set\n# CONFIG_PACKAGE_libdevmapper-selinux is not set\n# CONFIG_PACKAGE_libdmapsharing is not set\n# CONFIG_PACKAGE_libdnet is not set\n# CONFIG_PACKAGE_libdouble-conversion is not set\n# CONFIG_PACKAGE_libdrm is not set\n# CONFIG_PACKAGE_libdw is not set\n# CONFIG_PACKAGE_libecdsautil is not set\n# CONFIG_PACKAGE_libedit is not set\nCONFIG_PACKAGE_libelf=y\n# CONFIG_PACKAGE_libesmtp is not set\n# CONFIG_PACKAGE_libestr is not set\nCONFIG_PACKAGE_libev=y\nCONFIG_PACKAGE_libevdev=y\n# CONFIG_PACKAGE_libevent2 is not set\n# CONFIG_PACKAGE_libevent2-core is not set\n# CONFIG_PACKAGE_libevent2-extra is not set\n# CONFIG_PACKAGE_libevent2-openssl is not set\n# CONFIG_PACKAGE_libevent2-pthreads is not set\n# CONFIG_PACKAGE_libexif is not set\n# CONFIG_PACKAGE_libexpat is not set\n# CONFIG_PACKAGE_libexslt is not set\nCONFIG_PACKAGE_libext2fs=y\n# CONFIG_PACKAGE_libextractor is not set\n# CONFIG_PACKAGE_libf2fs is not set\n# CONFIG_PACKAGE_libf2fs-selinux is not set\n# CONFIG_PACKAGE_libfaad2 is not set\n# CONFIG_PACKAGE_libfastjson is not set\n# CONFIG_PACKAGE_libfdisk is not set\n# CONFIG_PACKAGE_libfdt is not set\n# CONFIG_PACKAGE_libffi is not set\n# CONFIG_PACKAGE_libffmpeg-audio-dec is not set\n# CONFIG_PACKAGE_libffmpeg-custom is not set\n# CONFIG_PACKAGE_libffmpeg-full is not set\n# CONFIG_PACKAGE_libffmpeg-mini is not set\n# CONFIG_PACKAGE_libfido2 is not set\n# CONFIG_PACKAGE_libflac is not set\n# CONFIG_PACKAGE_libfmt is not set\n# CONFIG_PACKAGE_libfreetype is not set\n# CONFIG_PACKAGE_libfstrm is not set\n# CONFIG_PACKAGE_libftdi is not set\n# CONFIG_PACKAGE_libftdi1 is not set\n# CONFIG_PACKAGE_libgabe is not set\n# CONFIG_PACKAGE_libgcrypt is not set\n# CONFIG_PACKAGE_libgd is not set\n# CONFIG_PACKAGE_libgd-full is not set\n# CONFIG_PACKAGE_libgdbm is not set\n# CONFIG_PACKAGE_libgee is not set\n# CONFIG_PACKAGE_libgmp is not set\n# CONFIG_PACKAGE_libgnurl is not set\n# CONFIG_PACKAGE_libgpg-error is not set\n# CONFIG_PACKAGE_libgpgme is not set\n# CONFIG_PACKAGE_libgpgmepp is not set\n# CONFIG_PACKAGE_libgphoto2 is not set\n# CONFIG_PACKAGE_libgpiod is not set\n# CONFIG_PACKAGE_libgps is not set\n# CONFIG_PACKAGE_libh2o is not set\n# CONFIG_PACKAGE_libh2o-evloop is not set\n# CONFIG_PACKAGE_libhamlib is not set\n# CONFIG_PACKAGE_libhavege is not set\n# CONFIG_PACKAGE_libhiredis is not set\n# CONFIG_PACKAGE_libhttp-parser is not set\n# CONFIG_PACKAGE_libhwloc is not set\n# CONFIG_PACKAGE_libi2c is not set\n# CONFIG_PACKAGE_libical is not set\n# CONFIG_PACKAGE_libiconv is not set\n# CONFIG_PACKAGE_libiconv-full is not set\n# CONFIG_PACKAGE_libid3tag is not set\n# CONFIG_PACKAGE_libidn is not set\n# CONFIG_PACKAGE_libidn2 is not set\n# CONFIG_PACKAGE_libiio is not set\n# CONFIG_PACKAGE_libinotifytools is not set\n# CONFIG_PACKAGE_libinput is not set\n# CONFIG_PACKAGE_libintl is not set\n# CONFIG_PACKAGE_libintl-full is not set\n# CONFIG_PACKAGE_libipfs-http-client is not set\n# CONFIG_PACKAGE_libiw is not set\nCONFIG_PACKAGE_libiwinfo=y\n# CONFIG_PACKAGE_libjpeg-turbo is not set\nCONFIG_PACKAGE_libjson-c=y\n# CONFIG_PACKAGE_libkeyutils is not set\n# CONFIG_PACKAGE_libkmod is not set\n# CONFIG_PACKAGE_libksba is not set\n# CONFIG_PACKAGE_libldns is not set\n# CONFIG_PACKAGE_libleptonica is not set\n# CONFIG_PACKAGE_libloragw is not set\n# CONFIG_PACKAGE_libltdl is not set\nCONFIG_PACKAGE_liblua=y\n# CONFIG_PACKAGE_liblua5.3 is not set\nCONFIG_PACKAGE_liblzo=y\n# CONFIG_PACKAGE_libmad is not set\n# CONFIG_PACKAGE_libmagic is not set\n# CONFIG_PACKAGE_libmaxminddb is not set\n# CONFIG_PACKAGE_libmbim is not set\n# CONFIG_PACKAGE_libmcrypt is not set\n# CONFIG_PACKAGE_libmicrohttpd-no-ssl is not set\n# CONFIG_PACKAGE_libmicrohttpd-ssl is not set\n# CONFIG_PACKAGE_libmilter-sendmail is not set\nCONFIG_PACKAGE_libminiupnpc=y\n# CONFIG_PACKAGE_libmms is not set\nCONFIG_PACKAGE_libmnl=y\n# CONFIG_PACKAGE_libmodbus is not set\n# CONFIG_PACKAGE_libmosquitto-nossl is not set\n# CONFIG_PACKAGE_libmosquitto-ssl is not set\nCONFIG_PACKAGE_libmount=y\n# CONFIG_PACKAGE_libmpdclient is not set\n# CONFIG_PACKAGE_libmpeg2 is not set\n# CONFIG_PACKAGE_libmpg123 is not set\nCONFIG_PACKAGE_libnatpmp=y\nCONFIG_PACKAGE_libncurses=y\n# CONFIG_PACKAGE_libndpi is not set\n# CONFIG_PACKAGE_libneon is not set\n# CONFIG_PACKAGE_libnet-1.2.x is not set\n# CONFIG_PACKAGE_libnetconf2 is not set\n# CONFIG_PACKAGE_libnetfilter-acct is not set\n# CONFIG_PACKAGE_libnetfilter-conntrack is not set\n# CONFIG_PACKAGE_libnetfilter-cthelper is not set\n# CONFIG_PACKAGE_libnetfilter-cttimeout is not set\n# CONFIG_PACKAGE_libnetfilter-log is not set\n# CONFIG_PACKAGE_libnetfilter-queue is not set\n# CONFIG_PACKAGE_libnetsnmp is not set\n# CONFIG_PACKAGE_libnettle is not set\n# CONFIG_PACKAGE_libnewt is not set\n# CONFIG_PACKAGE_libnfnetlink is not set\n# CONFIG_PACKAGE_libnftnl is not set\n# CONFIG_PACKAGE_libnghttp2 is not set\n# CONFIG_PACKAGE_libnl is not set\n# CONFIG_PACKAGE_libnl-core is not set\n# CONFIG_PACKAGE_libnl-genl is not set\n# CONFIG_PACKAGE_libnl-nf is not set\n# CONFIG_PACKAGE_libnl-route is not set\nCONFIG_PACKAGE_libnl-tiny=y\n# CONFIG_PACKAGE_libnopoll is not set\n# CONFIG_PACKAGE_libnpth is not set\n# CONFIG_PACKAGE_libnpupnp is not set\n# CONFIG_PACKAGE_libogg is not set\n# CONFIG_PACKAGE_liboil is not set\n# CONFIG_PACKAGE_libopcodes is not set\n# CONFIG_PACKAGE_libopendkim is not set\n# CONFIG_PACKAGE_libopenobex is not set\n# CONFIG_PACKAGE_libopensc is not set\n# CONFIG_PACKAGE_libopenzwave is not set\n# CONFIG_PACKAGE_liboping is not set\n# CONFIG_PACKAGE_libopus is not set\n# CONFIG_PACKAGE_libopusenc is not set\n# CONFIG_PACKAGE_libopusfile is not set\n# CONFIG_PACKAGE_liborcania is not set\n# CONFIG_PACKAGE_libout123 is not set\n# CONFIG_PACKAGE_libowipcalc is not set\n# CONFIG_PACKAGE_libp11 is not set\n# CONFIG_PACKAGE_libpagekite is not set\n# CONFIG_PACKAGE_libpam is not set\n# CONFIG_PACKAGE_libpbc is not set\n# CONFIG_PACKAGE_libpcap is not set\n# CONFIG_PACKAGE_libpci is not set\n# CONFIG_PACKAGE_libpciaccess is not set\nCONFIG_PACKAGE_libpcre=y\n# CONFIG_PCRE_JIT_ENABLED is not set\n# CONFIG_PACKAGE_libpcre16 is not set\n# CONFIG_PACKAGE_libpcre2 is not set\n# CONFIG_PACKAGE_libpcre2-16 is not set\n# CONFIG_PACKAGE_libpcre2-32 is not set\n# CONFIG_PACKAGE_libpcre32 is not set\n# CONFIG_PACKAGE_libpcsclite is not set\n# CONFIG_PACKAGE_libpfring is not set\n# CONFIG_PACKAGE_libpkcs11-spy is not set\n# CONFIG_PACKAGE_libpkgconf is not set\n# CONFIG_PACKAGE_libpng is not set\n# CONFIG_PACKAGE_libpopt is not set\n# CONFIG_PACKAGE_libpri is not set\n# CONFIG_PACKAGE_libprotobuf-c is not set\n# CONFIG_PACKAGE_libpsl is not set\n# CONFIG_PACKAGE_libqmi is not set\n# CONFIG_PACKAGE_libqrencode is not set\n# CONFIG_PACKAGE_libqrtr-glib is not set\n# CONFIG_PACKAGE_libradcli is not set\n# CONFIG_PACKAGE_libradiotap is not set\nCONFIG_PACKAGE_libreadline=y\n# CONFIG_PACKAGE_libredblack is not set\n# CONFIG_PACKAGE_librouteros is not set\n# CONFIG_PACKAGE_libroxml is not set\n# CONFIG_PACKAGE_librrd1 is not set\n# CONFIG_PACKAGE_librtlsdr is not set\n# CONFIG_PACKAGE_libruby is not set\n# CONFIG_PACKAGE_libsamplerate is not set\n# CONFIG_PACKAGE_libsane is not set\n# CONFIG_PACKAGE_libsasl2 is not set\n# CONFIG_PACKAGE_libsearpc is not set\n# CONFIG_PACKAGE_libseccomp is not set\n# CONFIG_PACKAGE_libselinux is not set\n# CONFIG_PACKAGE_libsemanage is not set\n# CONFIG_PACKAGE_libsensors is not set\n# CONFIG_PACKAGE_libsepol is not set\n# CONFIG_PACKAGE_libshout is not set\n# CONFIG_PACKAGE_libshout-full is not set\n# CONFIG_PACKAGE_libshout-nossl is not set\n# CONFIG_PACKAGE_libsispmctl is not set\n# CONFIG_PACKAGE_libslang2 is not set\n# CONFIG_PACKAGE_libslang2-mod-base64 is not set\n# CONFIG_PACKAGE_libslang2-mod-chksum is not set\n# CONFIG_PACKAGE_libslang2-mod-csv is not set\n# CONFIG_PACKAGE_libslang2-mod-fcntl is not set\n# CONFIG_PACKAGE_libslang2-mod-fork is not set\n# CONFIG_PACKAGE_libslang2-mod-histogram is not set\n# CONFIG_PACKAGE_libslang2-mod-iconv is not set\n# CONFIG_PACKAGE_libslang2-mod-json is not set\n# CONFIG_PACKAGE_libslang2-mod-onig is not set\n# CONFIG_PACKAGE_libslang2-mod-pcre is not set\n# CONFIG_PACKAGE_libslang2-mod-png is not set\n# CONFIG_PACKAGE_libslang2-mod-rand is not set\n# CONFIG_PACKAGE_libslang2-mod-select is not set\n# CONFIG_PACKAGE_libslang2-mod-slsmg is not set\n# CONFIG_PACKAGE_libslang2-mod-socket is not set\n# CONFIG_PACKAGE_libslang2-mod-stats is not set\n# CONFIG_PACKAGE_libslang2-mod-sysconf is not set\n# CONFIG_PACKAGE_libslang2-mod-termios is not set\n# CONFIG_PACKAGE_libslang2-mod-varray is not set\n# CONFIG_PACKAGE_libslang2-mod-zlib is not set\n# CONFIG_PACKAGE_libslang2-modules is not set\nCONFIG_PACKAGE_libsmartcols=y\n# CONFIG_PACKAGE_libsndfile is not set\n# CONFIG_PACKAGE_libsoc is not set\n# CONFIG_PACKAGE_libsocks is not set\nCONFIG_PACKAGE_libsodium=y\n\n#\n# Configuration\n#\nCONFIG_LIBSODIUM_MINIMAL=y\n# end of Configuration\n\n# CONFIG_PACKAGE_libsoup is not set\n# CONFIG_PACKAGE_libsoxr is not set\n# CONFIG_PACKAGE_libspeex is not set\n# CONFIG_PACKAGE_libspeexdsp is not set\n# CONFIG_PACKAGE_libspice-server is not set\nCONFIG_PACKAGE_libss=y\n# CONFIG_PACKAGE_libssh is not set\n# CONFIG_PACKAGE_libssh2 is not set\n# CONFIG_PACKAGE_libstoken is not set\n# CONFIG_PACKAGE_libstrophe is not set\n# CONFIG_PACKAGE_libsyn123 is not set\n# CONFIG_PACKAGE_libsysrepo is not set\n# CONFIG_PACKAGE_libtalloc is not set\n# CONFIG_PACKAGE_libtasn1 is not set\n# CONFIG_PACKAGE_libtheora is not set\n# CONFIG_PACKAGE_libtiff is not set\n# CONFIG_PACKAGE_libtins is not set\nCONFIG_PACKAGE_libtirpc=y\n# CONFIG_PACKAGE_libtorrent-rasterbar is not set\nCONFIG_PACKAGE_libubox=y\n# CONFIG_PACKAGE_libubox-lua is not set\nCONFIG_PACKAGE_libubus=y\nCONFIG_PACKAGE_libubus-lua=y\nCONFIG_PACKAGE_libuci=y\nCONFIG_PACKAGE_libuci-lua=y\n# CONFIG_PACKAGE_libuci2 is not set\nCONFIG_PACKAGE_libuclient=y\nCONFIG_PACKAGE_libudev-zero=y\nCONFIG_PACKAGE_libudns=y\n# CONFIG_PACKAGE_libuecc is not set\n# CONFIG_PACKAGE_libugpio is not set\n# CONFIG_PACKAGE_libunistring is not set\n# CONFIG_PACKAGE_libunwind is not set\n# CONFIG_PACKAGE_libupnp is not set\n# CONFIG_PACKAGE_libupnpp is not set\n# CONFIG_PACKAGE_liburcu is not set\n# CONFIG_PACKAGE_liburing is not set\nCONFIG_PACKAGE_libusb-1.0=y\n# CONFIG_PACKAGE_libusb-compat is not set\n# CONFIG_PACKAGE_libustream-mbedtls is not set\nCONFIG_PACKAGE_libustream-openssl=y\n# CONFIG_PACKAGE_libustream-wolfssl is not set\nCONFIG_PACKAGE_libuuid=y\nCONFIG_PACKAGE_libuv=y\n# CONFIG_PACKAGE_libuwifi is not set\n# CONFIG_PACKAGE_libv4l is not set\n# CONFIG_PACKAGE_libvorbis is not set\n# CONFIG_PACKAGE_libvorbisidec is not set\n# CONFIG_PACKAGE_libvpx is not set\n# CONFIG_PACKAGE_libwebp is not set\nCONFIG_PACKAGE_libwebsockets-full=y\n# CONFIG_PACKAGE_libwebsockets-mbedtls is not set\n# CONFIG_PACKAGE_libwebsockets-openssl is not set\n# CONFIG_PACKAGE_libwrap is not set\n# CONFIG_PACKAGE_libwxbase is not set\n# CONFIG_PACKAGE_libxerces-c is not set\n# CONFIG_PACKAGE_libxerces-c-samples is not set\n# CONFIG_PACKAGE_libxml2 is not set\n# CONFIG_PACKAGE_libxslt is not set\n# CONFIG_PACKAGE_libyaml-cpp is not set\n# CONFIG_PACKAGE_libyang is not set\n# CONFIG_PACKAGE_libyang-cpp is not set\n# CONFIG_PACKAGE_libyubikey is not set\n# CONFIG_PACKAGE_libzmq-curve is not set\n# CONFIG_PACKAGE_libzmq-nc is not set\n# CONFIG_PACKAGE_linux-atm is not set\n# CONFIG_PACKAGE_lmdb is not set\n# CONFIG_PACKAGE_log4cplus is not set\n# CONFIG_PACKAGE_loudmouth is not set\n# CONFIG_PACKAGE_lttng-ust is not set\n# CONFIG_PACKAGE_minizip is not set\n# CONFIG_PACKAGE_msgpack-c is not set\n# CONFIG_PACKAGE_mtdev is not set\n# CONFIG_PACKAGE_musl-fts is not set\n# CONFIG_PACKAGE_mxml is not set\n# CONFIG_PACKAGE_nspr is not set\n# CONFIG_PACKAGE_oniguruma is not set\n# CONFIG_PACKAGE_open-isns is not set\n# CONFIG_PACKAGE_openpgm is not set\n# CONFIG_PACKAGE_p11-kit is not set\n# CONFIG_PACKAGE_pixman is not set\n# CONFIG_PACKAGE_poco is not set\n# CONFIG_PACKAGE_poco-all is not set\n# CONFIG_PACKAGE_protobuf is not set\n# CONFIG_PACKAGE_protobuf-lite is not set\n# CONFIG_PACKAGE_pthsem is not set\n# CONFIG_PACKAGE_rblibtorrent is not set\n# CONFIG_PACKAGE_re2 is not set\nCONFIG_PACKAGE_rpcd-mod-rrdns=y\n# CONFIG_PACKAGE_sbc is not set\n# CONFIG_PACKAGE_serdisplib is not set\n# CONFIG_PACKAGE_taglib is not set\nCONFIG_PACKAGE_terminfo=y\n# CONFIG_PACKAGE_tinycdb is not set\n# CONFIG_PACKAGE_uclibcxx is not set\n# CONFIG_PACKAGE_uw-imap is not set\n# CONFIG_PACKAGE_xmlrpc-c is not set\n# CONFIG_PACKAGE_xmlrpc-c-client is not set\n# CONFIG_PACKAGE_xmlrpc-c-server is not set\n# CONFIG_PACKAGE_yajl is not set\n# CONFIG_PACKAGE_yubico-pam is not set\nCONFIG_PACKAGE_zlib=y\n\n#\n# Configuration\n#\nCONFIG_ZLIB_OPTIMIZE_SPEED=y\n# end of Configuration\n# end of Libraries\n\n#\n# LuCI\n#\n\n#\n# 1. Collections\n#\nCONFIG_PACKAGE_luci=y\n# CONFIG_PACKAGE_luci-nginx is not set\n# CONFIG_PACKAGE_luci-ssl-nginx is not set\n# CONFIG_PACKAGE_luci-ssl-openssl is not set\n# end of 1. Collections\n\n#\n# 2. Modules\n#\nCONFIG_PACKAGE_luci-base=y\n# CONFIG_LUCI_SRCDIET is not set\n\n#\n# Translations\n#\n# CONFIG_LUCI_LANG_hu is not set\n# CONFIG_LUCI_LANG_pt is not set\n# CONFIG_LUCI_LANG_no is not set\n# CONFIG_LUCI_LANG_sk is not set\n# CONFIG_LUCI_LANG_el is not set\n# CONFIG_LUCI_LANG_uk is not set\n# CONFIG_LUCI_LANG_ru is not set\n# CONFIG_LUCI_LANG_vi is not set\n# CONFIG_LUCI_LANG_de is not set\n# CONFIG_LUCI_LANG_ro is not set\n# CONFIG_LUCI_LANG_ms is not set\n# CONFIG_LUCI_LANG_pl is not set\nCONFIG_LUCI_LANG_zh-cn=y\n# CONFIG_LUCI_LANG_ko is not set\n# CONFIG_LUCI_LANG_he is not set\n# CONFIG_LUCI_LANG_zh-tw is not set\n# CONFIG_LUCI_LANG_tr is not set\n# CONFIG_LUCI_LANG_sv is not set\n# CONFIG_LUCI_LANG_ja is not set\n# CONFIG_LUCI_LANG_pt-br is not set\n# CONFIG_LUCI_LANG_ca is not set\n# CONFIG_LUCI_LANG_en is not set\n# CONFIG_LUCI_LANG_es is not set\n# CONFIG_LUCI_LANG_cs is not set\n# CONFIG_LUCI_LANG_fr is not set\n# CONFIG_LUCI_LANG_it is not set\n# end of Translations\n\nCONFIG_PACKAGE_luci-compat=y\nCONFIG_PACKAGE_luci-mod-admin-full=y\n# CONFIG_PACKAGE_luci-mod-failsafe is not set\n# CONFIG_PACKAGE_luci-mod-rpc is not set\n# CONFIG_PACKAGE_luci-newapi is not set\n# end of 2. Modules\n\n#\n# 3. Applications\n#\nCONFIG_PACKAGE_luci-app-accesscontrol=y\n# CONFIG_PACKAGE_luci-app-adblock is not set\nCONFIG_PACKAGE_luci-app-adbyby-plus=y\n# CONFIG_PACKAGE_luci-app-advanced-reboot is not set\n# CONFIG_PACKAGE_luci-app-ahcp is not set\n# CONFIG_PACKAGE_luci-app-airplay2 is not set\n# CONFIG_PACKAGE_luci-app-amule is not set\n# CONFIG_PACKAGE_luci-app-aria2 is not set\n# CONFIG_PACKAGE_luci-app-arpbind is not set\n# CONFIG_PACKAGE_luci-app-asterisk is not set\n# CONFIG_PACKAGE_luci-app-attendedsysupgrade is not set\nCONFIG_PACKAGE_luci-app-autoreboot=y\n# CONFIG_PACKAGE_luci-app-baidupcs-web is not set\n# CONFIG_PACKAGE_luci-app-bcp38 is not set\n# CONFIG_PACKAGE_luci-app-bird1-ipv4 is not set\n# CONFIG_PACKAGE_luci-app-bird1-ipv6 is not set\n# CONFIG_PACKAGE_luci-app-bmx6 is not set\nCONFIG_PACKAGE_luci-app-cifs-mount=y\n# CONFIG_PACKAGE_luci-app-cifsd is not set\n# CONFIG_PACKAGE_luci-app-cjdns is not set\n# CONFIG_PACKAGE_luci-app-clamav is not set\n# CONFIG_PACKAGE_luci-app-commands is not set\n# CONFIG_PACKAGE_luci-app-control-timewol is not set\n# CONFIG_PACKAGE_luci-app-control-webrestriction is not set\n# CONFIG_PACKAGE_luci-app-control-weburl is not set\n# CONFIG_PACKAGE_luci-app-cshark is not set\nCONFIG_PACKAGE_luci-app-ddns=y\n# CONFIG_PACKAGE_luci-app-diag-core is not set\nCONFIG_PACKAGE_luci-app-diskman=y\nCONFIG_PACKAGE_luci-app-diskman_INCLUDE_btrfs_progs=y\nCONFIG_PACKAGE_luci-app-diskman_INCLUDE_lsblk=y\n# CONFIG_PACKAGE_luci-app-diskman_INCLUDE_mdadm is not set\n# CONFIG_PACKAGE_luci-app-dnscrypt-proxy is not set\n# CONFIG_PACKAGE_luci-app-dnsforwarder is not set\n# CONFIG_PACKAGE_luci-app-docker is not set\n# CONFIG_PACKAGE_luci-app-dump1090 is not set\n# CONFIG_PACKAGE_luci-app-dynapoint is not set\n# CONFIG_PACKAGE_luci-app-e2guardian is not set\n# CONFIG_PACKAGE_luci-app-easymesh is not set\n# CONFIG_PACKAGE_luci-app-familycloud is not set\n# CONFIG_PACKAGE_luci-app-fileassistant is not set\n# CONFIG_PACKAGE_luci-app-filebrowser is not set\n# CONFIG_PACKAGE_luci-app-filetransfer is not set\nCONFIG_PACKAGE_luci-app-firewall=y\n# CONFIG_PACKAGE_luci-app-frpc is not set\n# CONFIG_PACKAGE_luci-app-frps is not set\n# CONFIG_PACKAGE_luci-app-fwknopd is not set\n# CONFIG_PACKAGE_luci-app-guest-wifi is not set\n# CONFIG_PACKAGE_luci-app-haproxy-tcp is not set\n# CONFIG_PACKAGE_luci-app-hd-idle is not set\n# CONFIG_PACKAGE_luci-app-hnet is not set\n# CONFIG_PACKAGE_luci-app-https-dns-proxy is not set\n# CONFIG_PACKAGE_luci-app-ipsec-server is not set\n# CONFIG_PACKAGE_luci-app-ipsec-vpnd is not set\n# CONFIG_PACKAGE_luci-app-jd-dailybonus is not set\n# CONFIG_PACKAGE_luci-app-kodexplorer is not set\n# CONFIG_PACKAGE_luci-app-lxc is not set\n# CONFIG_PACKAGE_luci-app-minidlna is not set\n# CONFIG_PACKAGE_luci-app-mjpg-streamer is not set\n# CONFIG_PACKAGE_luci-app-music-remote-center is not set\n# CONFIG_PACKAGE_luci-app-mwan3 is not set\n# CONFIG_PACKAGE_luci-app-mwan3helper is not set\n# CONFIG_PACKAGE_luci-app-n2n_v2 is not set\nCONFIG_PACKAGE_luci-app-netdata=y\n# CONFIG_PACKAGE_luci-app-nfs is not set\n# CONFIG_PACKAGE_luci-app-nft-qos is not set\n# CONFIG_PACKAGE_luci-app-nginx-pingos is not set\n# CONFIG_PACKAGE_luci-app-nlbwmon is not set\n# CONFIG_PACKAGE_luci-app-noddos is not set\n# CONFIG_PACKAGE_luci-app-nps is not set\n# CONFIG_PACKAGE_luci-app-ntpc is not set\n# CONFIG_PACKAGE_luci-app-ocserv is not set\n# CONFIG_PACKAGE_luci-app-olsr is not set\n# CONFIG_PACKAGE_luci-app-olsr-services is not set\n# CONFIG_PACKAGE_luci-app-olsr-viz is not set\n# CONFIG_PACKAGE_luci-app-openclash is not set\n# CONFIG_PACKAGE_luci-app-openvpn is not set\n# CONFIG_PACKAGE_luci-app-openvpn-server is not set\n# CONFIG_PACKAGE_luci-app-p910nd is not set\n# CONFIG_PACKAGE_luci-app-pagekitec is not set\nCONFIG_PACKAGE_luci-app-passwall=y\n\n#\n# Configuration\n#\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Brook is not set\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_ChinaDNS_NG=y\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_Dns2socks=y\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Haproxy is not set\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Hysteria is not set\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Kcptun is not set\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_NaiveProxy is not set\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_PDNSD=y\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_Shadowsocks_Libev_Client=y\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Shadowsocks_Libev_Server is not set\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Shadowsocks_Rust_Client is not set\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_ShadowsocksR_Libev_Client=y\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_ShadowsocksR_Libev_Server is not set\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_Simple_Obfs=y\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Trojan_GO is not set\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_Trojan_Plus=y\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_V2ray is not set\n# CONFIG_PACKAGE_luci-app-passwall_INCLUDE_V2ray_Plugin is not set\nCONFIG_PACKAGE_luci-app-passwall_INCLUDE_Xray=y\n# end of Configuration\n\n# CONFIG_PACKAGE_luci-app-polipo is not set\n# CONFIG_PACKAGE_luci-app-pppoe-relay is not set\n# CONFIG_PACKAGE_luci-app-pppoe-server is not set\n# CONFIG_PACKAGE_luci-app-pptp-server is not set\n# CONFIG_PACKAGE_luci-app-privoxy is not set\n# CONFIG_PACKAGE_luci-app-ps3netsrv is not set\n# CONFIG_PACKAGE_luci-app-pushbot is not set\n# CONFIG_PACKAGE_luci-app-qbittorrent is not set\nCONFIG_PACKAGE_luci-app-qbittorrent_dynamic=y\n# CONFIG_PACKAGE_luci-app-qos is not set\n# CONFIG_PACKAGE_luci-app-radicale is not set\nCONFIG_PACKAGE_luci-app-ramfree=y\n# CONFIG_PACKAGE_luci-app-rclone is not set\n# CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-webui is not set\n# CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-ng is not set\n# CONFIG_PACKAGE_luci-app-rclone_INCLUDE_fuse-utils is not set\n# CONFIG_PACKAGE_luci-app-rp-pppoe-server is not set\nCONFIG_PACKAGE_luci-app-samba=y\n# CONFIG_PACKAGE_luci-app-samba4 is not set\n# CONFIG_PACKAGE_luci-app-shadowsocks-libev is not set\n# CONFIG_PACKAGE_luci-app-shairplay is not set\n# CONFIG_PACKAGE_luci-app-siitwizard is not set\n# CONFIG_PACKAGE_luci-app-simple-adblock is not set\n# CONFIG_PACKAGE_luci-app-socat is not set\n# CONFIG_PACKAGE_luci-app-softethervpn is not set\n# CONFIG_PACKAGE_luci-app-splash is not set\n# CONFIG_PACKAGE_luci-app-sqm is not set\n# CONFIG_PACKAGE_luci-app-squid is not set\n# CONFIG_PACKAGE_luci-app-ssr-mudb-server is not set\nCONFIG_PACKAGE_luci-app-ssr-plus=y\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Kcptun is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_NaiveProxy is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Redsocks2 is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Libev_Client is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Libev_Server is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Rust_Client is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Rust_Server is not set\nCONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_ShadowsocksR_Libev_Client=y\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_ShadowsocksR_Libev_Server is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Simple_Obfs is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Trojan is not set\n# CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_V2ray_Plugin is not set\nCONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Xray=y\n# CONFIG_PACKAGE_luci-app-ssrserver-python is not set\n# CONFIG_PACKAGE_luci-app-statistics is not set\n# CONFIG_PACKAGE_luci-app-syncdial is not set\n# CONFIG_PACKAGE_luci-app-syncthing is not set\n# CONFIG_PACKAGE_luci-app-timecontrol is not set\n# CONFIG_PACKAGE_luci-app-tinyproxy is not set\n# CONFIG_PACKAGE_luci-app-transmission is not set\n# CONFIG_PACKAGE_luci-app-travelmate is not set\nCONFIG_PACKAGE_luci-app-ttyd=y\nCONFIG_PACKAGE_luci-app-turboacc=y\nCONFIG_PACKAGE_TURBOACC_INCLUDE_OFFLOADING=y\n# CONFIG_PACKAGE_TURBOACC_INCLUDE_SHORTCUT_FE is not set\nCONFIG_PACKAGE_TURBOACC_INCLUDE_BBR_CCA=y\n# CONFIG_PACKAGE_TURBOACC_INCLUDE_DNSFORWARDER is not set\n# CONFIG_PACKAGE_TURBOACC_INCLUDE_DNSPROXY is not set\n# CONFIG_PACKAGE_luci-app-udpxy is not set\n# CONFIG_PACKAGE_luci-app-uhttpd is not set\n# CONFIG_PACKAGE_luci-app-unblockmusic is not set\n# CONFIG_PACKAGE_luci-app-unblockmusic_INCLUDE_UnblockNeteaseMusic_Go is not set\n# CONFIG_PACKAGE_luci-app-unblockmusic_INCLUDE_UnblockNeteaseMusic_NodeJS is not set\n# CONFIG_PACKAGE_luci-app-unbound is not set\nCONFIG_PACKAGE_luci-app-upnp=y\n# CONFIG_PACKAGE_luci-app-usb-printer is not set\n# CONFIG_PACKAGE_luci-app-uugamebooster is not set\n# CONFIG_PACKAGE_luci-app-v2ray-server is not set\n# CONFIG_PACKAGE_luci-app-verysync is not set\nCONFIG_PACKAGE_luci-app-vlmcsd=y\n# CONFIG_PACKAGE_luci-app-vnstat is not set\n# CONFIG_PACKAGE_luci-app-vpnbypass is not set\n# CONFIG_PACKAGE_luci-app-vsftpd is not set\n# CONFIG_PACKAGE_luci-app-watchcat is not set\n# CONFIG_PACKAGE_luci-app-webadmin is not set\n# CONFIG_PACKAGE_luci-app-wifischedule is not set\n# CONFIG_PACKAGE_luci-app-wireguard is not set\n# CONFIG_PACKAGE_luci-app-wol is not set\n# CONFIG_PACKAGE_luci-app-wrtbwmon is not set\n# CONFIG_PACKAGE_luci-app-xlnetacc is not set\nCONFIG_PACKAGE_luci-app-zerotier=y\n# end of 3. Applications\n\n#\n# 4. Themes\n#\n# CONFIG_PACKAGE_luci-theme-argon is not set\nCONFIG_PACKAGE_luci-theme-bootstrap=y\n# CONFIG_PACKAGE_luci-theme-material is not set\n# CONFIG_PACKAGE_luci-theme-netgear is not set\n# end of 4. Themes\n\n#\n# 5. Protocols\n#\n# CONFIG_PACKAGE_luci-proto-3g is not set\n# CONFIG_PACKAGE_luci-proto-bonding is not set\n# CONFIG_PACKAGE_luci-proto-ipip is not set\n# CONFIG_PACKAGE_luci-proto-ipv6 is not set\n# CONFIG_PACKAGE_luci-proto-ncm is not set\n# CONFIG_PACKAGE_luci-proto-openconnect is not set\nCONFIG_PACKAGE_luci-proto-ppp=y\n# CONFIG_PACKAGE_luci-proto-qmi is not set\n# CONFIG_PACKAGE_luci-proto-relay is not set\n# CONFIG_PACKAGE_luci-proto-vpnc is not set\n# CONFIG_PACKAGE_luci-proto-wireguard is not set\n# end of 5. Protocols\n\n#\n# 6. Libraries\n#\n# CONFIG_PACKAGE_luci-lib-dracula is not set\n# CONFIG_PACKAGE_luci-lib-httpclient is not set\n# CONFIG_PACKAGE_luci-lib-httpprotoutils is not set\nCONFIG_PACKAGE_luci-lib-ip=y\n# CONFIG_PACKAGE_luci-lib-iptparser is not set\n# CONFIG_PACKAGE_luci-lib-jquery-1-4 is not set\n# CONFIG_PACKAGE_luci-lib-json is not set\nCONFIG_PACKAGE_luci-lib-jsonc=y\n# CONFIG_PACKAGE_luci-lib-luaneightbl is not set\nCONFIG_PACKAGE_luci-lib-nixio=y\n# CONFIG_PACKAGE_luci-lib-nixio_notls is not set\n# CONFIG_PACKAGE_luci-lib-nixio_axtls is not set\n# CONFIG_PACKAGE_luci-lib-nixio_cyassl is not set\nCONFIG_PACKAGE_luci-lib-nixio_openssl=y\n# CONFIG_PACKAGE_luci-lib-px5g is not set\n# end of 6. Libraries\n\nCONFIG_PACKAGE_default-settings=y\nCONFIG_PACKAGE_luci-i18n-accesscontrol-zh-cn=y\nCONFIG_PACKAGE_luci-i18n-adbyby-plus-zh-cn=y\nCONFIG_PACKAGE_luci-i18n-autoreboot-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-base-ca is not set\n# CONFIG_PACKAGE_luci-i18n-base-cs is not set\n# CONFIG_PACKAGE_luci-i18n-base-de is not set\n# CONFIG_PACKAGE_luci-i18n-base-el is not set\n# CONFIG_PACKAGE_luci-i18n-base-en is not set\n# CONFIG_PACKAGE_luci-i18n-base-es is not set\n# CONFIG_PACKAGE_luci-i18n-base-fr is not set\n# CONFIG_PACKAGE_luci-i18n-base-he is not set\n# CONFIG_PACKAGE_luci-i18n-base-hu is not set\n# CONFIG_PACKAGE_luci-i18n-base-it is not set\n# CONFIG_PACKAGE_luci-i18n-base-ja is not set\n# CONFIG_PACKAGE_luci-i18n-base-ko is not set\n# CONFIG_PACKAGE_luci-i18n-base-ms is not set\n# CONFIG_PACKAGE_luci-i18n-base-no is not set\n# CONFIG_PACKAGE_luci-i18n-base-pl is not set\n# CONFIG_PACKAGE_luci-i18n-base-pt is not set\n# CONFIG_PACKAGE_luci-i18n-base-pt-br is not set\n# CONFIG_PACKAGE_luci-i18n-base-ro is not set\n# CONFIG_PACKAGE_luci-i18n-base-ru is not set\n# CONFIG_PACKAGE_luci-i18n-base-sk is not set\n# CONFIG_PACKAGE_luci-i18n-base-sv is not set\n# CONFIG_PACKAGE_luci-i18n-base-tr is not set\n# CONFIG_PACKAGE_luci-i18n-base-uk is not set\n# CONFIG_PACKAGE_luci-i18n-base-vi is not set\nCONFIG_PACKAGE_luci-i18n-base-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-base-zh-tw is not set\nCONFIG_PACKAGE_luci-i18n-cifs-mount-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-ddns-bg is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-ca is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-cs is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-de is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-el is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-en is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-es is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-fr is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-he is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-hi is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-hu is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-it is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-ja is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-ko is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-mr is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-ms is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-no is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-pl is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-pt is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-pt-br is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-ro is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-ru is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-sk is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-sv is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-tr is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-uk is not set\n# CONFIG_PACKAGE_luci-i18n-ddns-vi is not set\nCONFIG_PACKAGE_luci-i18n-ddns-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-ddns-zh-tw is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-ca is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-cs is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-de is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-el is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-en is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-es is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-fr is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-he is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-hu is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-it is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-ja is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-ko is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-ms is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-no is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-pl is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-pt is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-pt-br is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-ro is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-ru is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-sk is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-sv is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-tr is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-uk is not set\n# CONFIG_PACKAGE_luci-i18n-firewall-vi is not set\nCONFIG_PACKAGE_luci-i18n-firewall-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-firewall-zh-tw is not set\nCONFIG_PACKAGE_luci-i18n-netdata-zh-cn=y\nCONFIG_PACKAGE_luci-i18n-passwall-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-passwall-zh_Hans is not set\nCONFIG_PACKAGE_luci-i18n-ramfree-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-samba-ca is not set\n# CONFIG_PACKAGE_luci-i18n-samba-cs is not set\n# CONFIG_PACKAGE_luci-i18n-samba-de is not set\n# CONFIG_PACKAGE_luci-i18n-samba-el is not set\n# CONFIG_PACKAGE_luci-i18n-samba-en is not set\n# CONFIG_PACKAGE_luci-i18n-samba-es is not set\n# CONFIG_PACKAGE_luci-i18n-samba-fr is not set\n# CONFIG_PACKAGE_luci-i18n-samba-he is not set\n# CONFIG_PACKAGE_luci-i18n-samba-hu is not set\n# CONFIG_PACKAGE_luci-i18n-samba-it is not set\n# CONFIG_PACKAGE_luci-i18n-samba-ja is not set\n# CONFIG_PACKAGE_luci-i18n-samba-ms is not set\n# CONFIG_PACKAGE_luci-i18n-samba-no is not set\n# CONFIG_PACKAGE_luci-i18n-samba-pl is not set\n# CONFIG_PACKAGE_luci-i18n-samba-pt is not set\n# CONFIG_PACKAGE_luci-i18n-samba-pt-br is not set\n# CONFIG_PACKAGE_luci-i18n-samba-ro is not set\n# CONFIG_PACKAGE_luci-i18n-samba-ru is not set\n# CONFIG_PACKAGE_luci-i18n-samba-sk is not set\n# CONFIG_PACKAGE_luci-i18n-samba-sv is not set\n# CONFIG_PACKAGE_luci-i18n-samba-tr is not set\n# CONFIG_PACKAGE_luci-i18n-samba-uk is not set\n# CONFIG_PACKAGE_luci-i18n-samba-vi is not set\nCONFIG_PACKAGE_luci-i18n-samba-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-samba-zh-tw is not set\nCONFIG_PACKAGE_luci-i18n-ssr-plus-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-ssr-plus-zh_Hans is not set\nCONFIG_PACKAGE_luci-i18n-ttyd-zh-cn=y\nCONFIG_PACKAGE_luci-i18n-turboacc-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-upnp-ca is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-cs is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-de is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-el is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-en is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-es is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-fr is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-he is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-hu is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-it is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-ja is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-ms is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-no is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-pl is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-pt is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-pt-br is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-ro is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-ru is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-sk is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-sv is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-tr is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-uk is not set\n# CONFIG_PACKAGE_luci-i18n-upnp-vi is not set\nCONFIG_PACKAGE_luci-i18n-upnp-zh-cn=y\n# CONFIG_PACKAGE_luci-i18n-upnp-zh-tw is not set\nCONFIG_PACKAGE_luci-i18n-vlmcsd-zh-cn=y\nCONFIG_PACKAGE_luci-i18n-zerotier-zh-cn=y\n# end of LuCI\n\n#\n# Mail\n#\n# CONFIG_PACKAGE_alpine is not set\n# CONFIG_PACKAGE_bogofilter is not set\n# CONFIG_PACKAGE_dovecot is not set\n# CONFIG_PACKAGE_dovecot-pigeonhole is not set\n# CONFIG_PACKAGE_dovecot-utils is not set\n# CONFIG_PACKAGE_emailrelay is not set\n# CONFIG_PACKAGE_exim is not set\n# CONFIG_PACKAGE_exim-gnutls is not set\n# CONFIG_PACKAGE_exim-ldap is not set\n# CONFIG_PACKAGE_exim-openssl is not set\n# CONFIG_PACKAGE_fdm is not set\n# CONFIG_PACKAGE_greyfix is not set\n# CONFIG_PACKAGE_mailsend is not set\n# CONFIG_PACKAGE_mailsend-nossl is not set\n# CONFIG_PACKAGE_msmtp is not set\n# CONFIG_PACKAGE_msmtp-mta is not set\n# CONFIG_PACKAGE_msmtp-nossl is not set\n# CONFIG_PACKAGE_msmtp-queue is not set\n# CONFIG_PACKAGE_mutt is not set\n# CONFIG_PACKAGE_nail is not set\n# CONFIG_PACKAGE_opendkim is not set\n# CONFIG_PACKAGE_opendkim-tools is not set\n# CONFIG_PACKAGE_postfix is not set\n\n#\n# Select postfix build options\n#\nCONFIG_POSTFIX_TLS=y\nCONFIG_POSTFIX_SASL=y\nCONFIG_POSTFIX_LDAP=y\n# CONFIG_POSTFIX_DB is not set\nCONFIG_POSTFIX_CDB=y\nCONFIG_POSTFIX_SQLITE=y\n# CONFIG_POSTFIX_MYSQL is not set\n# CONFIG_POSTFIX_PGSQL is not set\nCONFIG_POSTFIX_PCRE=y\n# CONFIG_POSTFIX_EAI is not set\n# end of Select postfix build options\n\n# CONFIG_PACKAGE_spamc is not set\n# CONFIG_PACKAGE_spamc-ssl is not set\n# end of Mail\n\n#\n# Multimedia\n#\n\n#\n# Streaming\n#\n# CONFIG_PACKAGE_oggfwd is not set\n# end of Streaming\n\n# CONFIG_PACKAGE_UnblockNeteaseMusic is not set\n# CONFIG_PACKAGE_UnblockNeteaseMusic-Go is not set\n# CONFIG_UNBLOCKNETEASEMUSIC_GO_COMPRESS_GOPROXY is not set\nCONFIG_UNBLOCKNETEASEMUSIC_GO_COMPRESS_UPX=y\n# CONFIG_PACKAGE_ffmpeg is not set\n# CONFIG_PACKAGE_ffprobe is not set\n# CONFIG_PACKAGE_fswebcam is not set\n# CONFIG_PACKAGE_gerbera is not set\n# CONFIG_PACKAGE_gmediarender is not set\n# CONFIG_PACKAGE_gphoto2 is not set\n# CONFIG_PACKAGE_graphicsmagick is not set\n# CONFIG_PACKAGE_grilo is not set\n# CONFIG_PACKAGE_grilo-plugins is not set\n# CONFIG_PACKAGE_gst1-libav is not set\n# CONFIG_PACKAGE_gstreamer1-libs is not set\n# CONFIG_PACKAGE_gstreamer1-plugins-bad is not set\n# CONFIG_PACKAGE_gstreamer1-plugins-base is not set\n# CONFIG_PACKAGE_gstreamer1-plugins-good is not set\n# CONFIG_PACKAGE_gstreamer1-plugins-ugly is not set\n# CONFIG_PACKAGE_gstreamer1-utils is not set\n# CONFIG_PACKAGE_icecast is not set\n# CONFIG_PACKAGE_imagemagick is not set\n# CONFIG_PACKAGE_lcdgrilo is not set\n# CONFIG_PACKAGE_minidlna is not set\n# CONFIG_PACKAGE_minisatip is not set\n# CONFIG_PACKAGE_mjpg-streamer is not set\n# CONFIG_PACKAGE_motion is not set\n# CONFIG_PACKAGE_tvheadend is not set\n# CONFIG_PACKAGE_v4l2rtspserver is not set\n# CONFIG_PACKAGE_vips is not set\n# CONFIG_PACKAGE_xupnpd is not set\n# CONFIG_PACKAGE_youtube-dl is not set\n# end of Multimedia\n\n#\n# Network\n#\n\n#\n# BitTorrent\n#\n# CONFIG_PACKAGE_mktorrent is not set\n# CONFIG_PACKAGE_opentracker is not set\n# CONFIG_PACKAGE_opentracker6 is not set\n# CONFIG_PACKAGE_qbittorrent is not set\n# CONFIG_PACKAGE_rtorrent is not set\n# CONFIG_PACKAGE_rtorrent-rpc is not set\n# CONFIG_PACKAGE_transmission-cli-openssl is not set\n# CONFIG_PACKAGE_transmission-daemon-openssl is not set\n# CONFIG_PACKAGE_transmission-remote-openssl is not set\n# CONFIG_PACKAGE_transmission-web is not set\n# CONFIG_PACKAGE_transmission-web-control is not set\n# end of BitTorrent\n\n#\n# Captive Portals\n#\n# CONFIG_PACKAGE_apfree-wifidog is not set\n# CONFIG_PACKAGE_coova-chilli is not set\n# CONFIG_PACKAGE_nodogsplash is not set\n# CONFIG_PACKAGE_opennds is not set\n# CONFIG_PACKAGE_wifidog is not set\n# CONFIG_PACKAGE_wifidog-tls is not set\n# end of Captive Portals\n\n#\n# Cloud Manager\n#\n# CONFIG_PACKAGE_rclone-ng is not set\n# CONFIG_PACKAGE_rclone-webui-react is not set\n# end of Cloud Manager\n\n#\n# Dial-in/up\n#\n# CONFIG_PACKAGE_rp-pppoe-common is not set\n# CONFIG_PACKAGE_rp-pppoe-relay is not set\n# CONFIG_PACKAGE_rp-pppoe-server is not set\n# end of Dial-in/up\n\n#\n# Download Manager\n#\n# CONFIG_PACKAGE_ariang is not set\n# CONFIG_PACKAGE_ariang-nginx is not set\n# CONFIG_PACKAGE_leech is not set\n# CONFIG_PACKAGE_webui-aria2 is not set\n# end of Download Manager\n\n#\n# File Transfer\n#\n# CONFIG_PACKAGE_aria2 is not set\n# CONFIG_PACKAGE_atftp is not set\n# CONFIG_PACKAGE_atftpd is not set\nCONFIG_PACKAGE_curl=y\n# CONFIG_PACKAGE_gnurl is not set\n# CONFIG_PACKAGE_lftp is not set\n# CONFIG_PACKAGE_ps3netsrv is not set\n# CONFIG_PACKAGE_rosy-file-server is not set\n# CONFIG_PACKAGE_rsync is not set\n# CONFIG_PACKAGE_rsyncd is not set\n# CONFIG_PACKAGE_vsftpd is not set\n# CONFIG_PACKAGE_vsftpd-alt is not set\n# CONFIG_PACKAGE_vsftpd-tls is not set\n# CONFIG_PACKAGE_wget-nossl is not set\nCONFIG_PACKAGE_wget-ssl=y\n# end of File Transfer\n\n#\n# Filesystem\n#\n# CONFIG_PACKAGE_davfs2 is not set\n# CONFIG_PACKAGE_ksmbd-avahi-service is not set\n# CONFIG_PACKAGE_ksmbd-server is not set\n# CONFIG_PACKAGE_ksmbd-utils is not set\n# CONFIG_PACKAGE_netatalk is not set\n# CONFIG_PACKAGE_nfs-kernel-server is not set\n# CONFIG_PACKAGE_owftpd is not set\n# CONFIG_PACKAGE_owhttpd is not set\n# CONFIG_PACKAGE_owserver is not set\n# CONFIG_PACKAGE_sshfs is not set\n# end of Filesystem\n\n#\n# Firewall\n#\n# CONFIG_PACKAGE_arptables is not set\n# CONFIG_PACKAGE_conntrack is not set\n# CONFIG_PACKAGE_conntrackd is not set\n# CONFIG_PACKAGE_ebtables is not set\n# CONFIG_PACKAGE_fwknop is not set\n# CONFIG_PACKAGE_fwknopd is not set\n# CONFIG_PACKAGE_ip6tables is not set\nCONFIG_PACKAGE_iptables=y\n# CONFIG_IPTABLES_CONNLABEL is not set\n# CONFIG_IPTABLES_NFTABLES is not set\n# CONFIG_PACKAGE_iptables-mod-account is not set\n# CONFIG_PACKAGE_iptables-mod-chaos is not set\n# CONFIG_PACKAGE_iptables-mod-checksum is not set\n# CONFIG_PACKAGE_iptables-mod-cluster is not set\n# CONFIG_PACKAGE_iptables-mod-clusterip is not set\n# CONFIG_PACKAGE_iptables-mod-condition is not set\n# CONFIG_PACKAGE_iptables-mod-conntrack-extra is not set\n# CONFIG_PACKAGE_iptables-mod-delude is not set\n# CONFIG_PACKAGE_iptables-mod-dhcpmac is not set\n# CONFIG_PACKAGE_iptables-mod-dnetmap is not set\n# CONFIG_PACKAGE_iptables-mod-extra is not set\n# CONFIG_PACKAGE_iptables-mod-filter is not set\nCONFIG_PACKAGE_iptables-mod-fullconenat=y\n# CONFIG_PACKAGE_iptables-mod-fuzzy is not set\n# CONFIG_PACKAGE_iptables-mod-geoip is not set\n# CONFIG_PACKAGE_iptables-mod-hashlimit is not set\n# CONFIG_PACKAGE_iptables-mod-iface is not set\n# CONFIG_PACKAGE_iptables-mod-ipmark is not set\n# CONFIG_PACKAGE_iptables-mod-ipopt is not set\n# CONFIG_PACKAGE_iptables-mod-ipp2p is not set\n# CONFIG_PACKAGE_iptables-mod-iprange is not set\n# CONFIG_PACKAGE_iptables-mod-ipsec is not set\n# CONFIG_PACKAGE_iptables-mod-ipv4options is not set\n# CONFIG_PACKAGE_iptables-mod-led is not set\n# CONFIG_PACKAGE_iptables-mod-length2 is not set\n# CONFIG_PACKAGE_iptables-mod-logmark is not set\n# CONFIG_PACKAGE_iptables-mod-lscan is not set\n# CONFIG_PACKAGE_iptables-mod-lua is not set\n# CONFIG_PACKAGE_iptables-mod-nat-extra is not set\n# CONFIG_PACKAGE_iptables-mod-nflog is not set\n# CONFIG_PACKAGE_iptables-mod-nfqueue is not set\n# CONFIG_PACKAGE_iptables-mod-physdev is not set\n# CONFIG_PACKAGE_iptables-mod-proto is not set\n# CONFIG_PACKAGE_iptables-mod-psd is not set\n# CONFIG_PACKAGE_iptables-mod-quota2 is not set\n# CONFIG_PACKAGE_iptables-mod-rpfilter is not set\n# CONFIG_PACKAGE_iptables-mod-rtpengine is not set\n# CONFIG_PACKAGE_iptables-mod-sysrq is not set\n# CONFIG_PACKAGE_iptables-mod-tarpit is not set\n# CONFIG_PACKAGE_iptables-mod-tee is not set\nCONFIG_PACKAGE_iptables-mod-tproxy=y\n# CONFIG_PACKAGE_iptables-mod-trace is not set\n# CONFIG_PACKAGE_iptables-mod-u32 is not set\n# CONFIG_PACKAGE_iptables-mod-ulog is not set\n# CONFIG_PACKAGE_iptaccount is not set\n# CONFIG_PACKAGE_iptgeoip is not set\n\n#\n# Select iptgeoip options\n#\n# CONFIG_IPTGEOIP_PRESERVE is not set\n# end of Select iptgeoip options\n\n# CONFIG_PACKAGE_miniupnpc is not set\nCONFIG_PACKAGE_miniupnpd=y\n# CONFIG_MINIUPNPD_IGDv2 is not set\n# CONFIG_PACKAGE_natpmpc is not set\n# CONFIG_PACKAGE_nftables-json is not set\n# CONFIG_PACKAGE_nftables-nojson is not set\n# CONFIG_PACKAGE_shorewall is not set\n# CONFIG_PACKAGE_shorewall-core is not set\n# CONFIG_PACKAGE_shorewall-lite is not set\n# CONFIG_PACKAGE_shorewall6 is not set\n# CONFIG_PACKAGE_shorewall6-lite is not set\n# CONFIG_PACKAGE_snort is not set\n# CONFIG_PACKAGE_snort3 is not set\n# end of Firewall\n\n#\n# Firewall Tunnel\n#\n# CONFIG_PACKAGE_iodine is not set\n# CONFIG_PACKAGE_iodined is not set\n# end of Firewall Tunnel\n\n#\n# FreeRADIUS (version 3)\n#\n# CONFIG_PACKAGE_freeradius3 is not set\n# CONFIG_PACKAGE_freeradius3-common is not set\n# CONFIG_PACKAGE_freeradius3-utils is not set\n# end of FreeRADIUS (version 3)\n\n#\n# IP Addresses and Names\n#\n# CONFIG_PACKAGE_aggregate is not set\n# CONFIG_PACKAGE_announce is not set\n# CONFIG_PACKAGE_avahi-autoipd is not set\n# CONFIG_PACKAGE_avahi-daemon-service-http is not set\n# CONFIG_PACKAGE_avahi-daemon-service-ssh is not set\n# CONFIG_PACKAGE_avahi-dbus-daemon is not set\n# CONFIG_PACKAGE_avahi-dnsconfd is not set\n# CONFIG_PACKAGE_avahi-nodbus-daemon is not set\n# CONFIG_PACKAGE_avahi-utils is not set\n# CONFIG_PACKAGE_bind-check is not set\n# CONFIG_PACKAGE_bind-client is not set\n# CONFIG_PACKAGE_bind-dig is not set\n# CONFIG_PACKAGE_bind-dnssec is not set\n# CONFIG_PACKAGE_bind-host is not set\n# CONFIG_PACKAGE_bind-nslookup is not set\n# CONFIG_PACKAGE_bind-rndc is not set\n# CONFIG_PACKAGE_bind-server is not set\n# CONFIG_PACKAGE_bind-tools is not set\nCONFIG_PACKAGE_ddns-scripts=y\nCONFIG_PACKAGE_ddns-scripts_aliyun=y\n# CONFIG_PACKAGE_ddns-scripts_cloudflare.com-v4 is not set\nCONFIG_PACKAGE_ddns-scripts_dnspod=y\n# CONFIG_PACKAGE_ddns-scripts_freedns_42_pl is not set\n# CONFIG_PACKAGE_ddns-scripts_godaddy.com-v1 is not set\n# CONFIG_PACKAGE_ddns-scripts_no-ip_com is not set\n# CONFIG_PACKAGE_ddns-scripts_nsupdate is not set\n# CONFIG_PACKAGE_ddns-scripts_route53-v1 is not set\n# CONFIG_PACKAGE_dhcp-forwarder is not set\nCONFIG_PACKAGE_dns2socks=y\n# CONFIG_PACKAGE_dnscrypt-proxy is not set\n# CONFIG_PACKAGE_dnscrypt-proxy-resolvers is not set\n# CONFIG_PACKAGE_dnsdist is not set\n# CONFIG_PACKAGE_dnsproxy is not set\n# CONFIG_DNSPROXY_COMPRESS_GOPROXY is not set\nCONFIG_DNSPROXY_COMPRESS_UPX=y\n# CONFIG_PACKAGE_drill is not set\n# CONFIG_PACKAGE_hostip is not set\n# CONFIG_PACKAGE_idn is not set\n# CONFIG_PACKAGE_idn2 is not set\n# CONFIG_PACKAGE_inadyn is not set\n# CONFIG_PACKAGE_isc-dhcp-client-ipv4 is not set\n# CONFIG_PACKAGE_isc-dhcp-client-ipv6 is not set\n# CONFIG_PACKAGE_isc-dhcp-omshell-ipv4 is not set\n# CONFIG_PACKAGE_isc-dhcp-omshell-ipv6 is not set\n# CONFIG_PACKAGE_isc-dhcp-relay-ipv4 is not set\n# CONFIG_PACKAGE_isc-dhcp-relay-ipv6 is not set\n# CONFIG_PACKAGE_isc-dhcp-server-ipv4 is not set\n# CONFIG_PACKAGE_isc-dhcp-server-ipv6 is not set\n# CONFIG_PACKAGE_kadnode is not set\n# CONFIG_PACKAGE_kea-admin is not set\n# CONFIG_PACKAGE_kea-ctrl is not set\n# CONFIG_PACKAGE_kea-dhcp-ddns is not set\n# CONFIG_PACKAGE_kea-dhcp4 is not set\n# CONFIG_PACKAGE_kea-dhcp6 is not set\n# CONFIG_PACKAGE_kea-lfc is not set\n# CONFIG_PACKAGE_kea-libs is not set\n# CONFIG_PACKAGE_kea-perfdhcp is not set\n# CONFIG_PACKAGE_kea-shell is not set\n# CONFIG_PACKAGE_knot is not set\n# CONFIG_PACKAGE_knot-dig is not set\n# CONFIG_PACKAGE_knot-host is not set\n# CONFIG_PACKAGE_knot-keymgr is not set\n# CONFIG_PACKAGE_knot-nsupdate is not set\n# CONFIG_PACKAGE_knot-resolver is not set\n\n#\n# Configuration\n#\n# CONFIG_PACKAGE_knot-resolver_dnstap is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_knot-tests is not set\n# CONFIG_PACKAGE_knot-zonecheck is not set\n# CONFIG_PACKAGE_ldns-examples is not set\n# CONFIG_PACKAGE_mdns-utils is not set\n# CONFIG_PACKAGE_mdnsd is not set\n# CONFIG_PACKAGE_mdnsresponder is not set\n# CONFIG_PACKAGE_nsd is not set\n# CONFIG_PACKAGE_nsd-control is not set\n# CONFIG_PACKAGE_nsd-control-setup is not set\n# CONFIG_PACKAGE_nsd-nossl is not set\n# CONFIG_PACKAGE_ohybridproxy is not set\n# CONFIG_PACKAGE_overture is not set\n# CONFIG_PACKAGE_pdns is not set\n# CONFIG_PACKAGE_pdns-ixfrdist is not set\n# CONFIG_PACKAGE_pdns-recursor is not set\n# CONFIG_PACKAGE_pdns-tools is not set\n# CONFIG_PACKAGE_stubby is not set\n# CONFIG_PACKAGE_tor-hs is not set\n# CONFIG_PACKAGE_torsocks is not set\n# CONFIG_PACKAGE_unbound-anchor is not set\n# CONFIG_PACKAGE_unbound-checkconf is not set\n# CONFIG_PACKAGE_unbound-control is not set\n# CONFIG_PACKAGE_unbound-control-setup is not set\n# CONFIG_PACKAGE_unbound-daemon is not set\n# CONFIG_PACKAGE_unbound-host is not set\n# CONFIG_PACKAGE_wsdd2 is not set\n# CONFIG_PACKAGE_zonestitcher is not set\n# end of IP Addresses and Names\n\n#\n# Instant Messaging\n#\n# CONFIG_PACKAGE_bitlbee is not set\n# CONFIG_PACKAGE_irssi is not set\n# CONFIG_PACKAGE_ngircd is not set\n# CONFIG_PACKAGE_ngircd-nossl is not set\n# CONFIG_PACKAGE_prosody is not set\n# CONFIG_PACKAGE_quassel-irssi is not set\n# CONFIG_PACKAGE_umurmur-mbedtls is not set\n# CONFIG_PACKAGE_umurmur-openssl is not set\n# CONFIG_PACKAGE_znc is not set\n# end of Instant Messaging\n\n#\n# Linux ATM tools\n#\n# CONFIG_PACKAGE_atm-aread is not set\n# CONFIG_PACKAGE_atm-atmaddr is not set\n# CONFIG_PACKAGE_atm-atmdiag is not set\n# CONFIG_PACKAGE_atm-atmdump is not set\n# CONFIG_PACKAGE_atm-atmloop is not set\n# CONFIG_PACKAGE_atm-atmsigd is not set\n# CONFIG_PACKAGE_atm-atmswitch is not set\n# CONFIG_PACKAGE_atm-atmtcp is not set\n# CONFIG_PACKAGE_atm-awrite is not set\n# CONFIG_PACKAGE_atm-bus is not set\n# CONFIG_PACKAGE_atm-debug-tools is not set\n# CONFIG_PACKAGE_atm-diagnostics is not set\n# CONFIG_PACKAGE_atm-esi is not set\n# CONFIG_PACKAGE_atm-ilmid is not set\n# CONFIG_PACKAGE_atm-ilmidiag is not set\n# CONFIG_PACKAGE_atm-lecs is not set\n# CONFIG_PACKAGE_atm-les is not set\n# CONFIG_PACKAGE_atm-mpcd is not set\n# CONFIG_PACKAGE_atm-saaldump is not set\n# CONFIG_PACKAGE_atm-sonetdiag is not set\n# CONFIG_PACKAGE_atm-svc_recv is not set\n# CONFIG_PACKAGE_atm-svc_send is not set\n# CONFIG_PACKAGE_atm-tools is not set\n# CONFIG_PACKAGE_atm-ttcp_atm is not set\n# CONFIG_PACKAGE_atm-zeppelin is not set\n# CONFIG_PACKAGE_br2684ctl is not set\n# end of Linux ATM tools\n\n#\n# LoRaWAN\n#\n# CONFIG_PACKAGE_libloragw-tests is not set\n# CONFIG_PACKAGE_libloragw-utils is not set\n# end of LoRaWAN\n\n#\n# NMAP Suite\n#\n# CONFIG_PACKAGE_ncat is not set\n# CONFIG_PACKAGE_ncat-full is not set\n# CONFIG_PACKAGE_ncat-ssl is not set\n# CONFIG_PACKAGE_ndiff is not set\n# CONFIG_PACKAGE_nmap is not set\n# CONFIG_PACKAGE_nmap-full is not set\n# CONFIG_PACKAGE_nmap-ssl is not set\n# CONFIG_PACKAGE_nping is not set\n# CONFIG_PACKAGE_nping-ssl is not set\n# end of NMAP Suite\n\n#\n# NTRIP\n#\n# CONFIG_PACKAGE_ntripcaster is not set\n# CONFIG_PACKAGE_ntripclient is not set\n# CONFIG_PACKAGE_ntripserver is not set\n# end of NTRIP\n\n#\n# OLSR.org network framework\n#\n# CONFIG_PACKAGE_oonf-dlep-proxy is not set\n# CONFIG_PACKAGE_oonf-dlep-radio is not set\n# CONFIG_PACKAGE_oonf-init-scripts is not set\n# CONFIG_PACKAGE_oonf-olsrd2 is not set\n# end of OLSR.org network framework\n\n#\n# Open vSwitch\n#\n# CONFIG_PACKAGE_openvswitch is not set\n# CONFIG_PACKAGE_openvswitch-ovn-host is not set\n# CONFIG_PACKAGE_openvswitch-ovn-north is not set\n# CONFIG_PACKAGE_openvswitch-python3 is not set\n# CONFIG_PACKAGE_ovsd is not set\n# end of Open vSwitch\n\n#\n# OpenLDAP\n#\n# CONFIG_PACKAGE_libopenldap is not set\nCONFIG_OPENLDAP_DEBUG=y\n# CONFIG_OPENLDAP_CRYPT is not set\n# CONFIG_OPENLDAP_MONITOR is not set\n# CONFIG_OPENLDAP_DB47 is not set\n# CONFIG_OPENLDAP_ICU is not set\n# CONFIG_PACKAGE_openldap-server is not set\n# CONFIG_PACKAGE_openldap-utils is not set\n# end of OpenLDAP\n\n#\n# P2P\n#\n# CONFIG_PACKAGE_amule is not set\n# CONFIG_AMULE_CRYPTOPP_STATIC_LINKING is not set\n# CONFIG_PACKAGE_antileech is not set\n# end of P2P\n\n#\n# Printing\n#\n# CONFIG_PACKAGE_p910nd is not set\n# end of Printing\n\n#\n# Project V\n#\n# CONFIG_PACKAGE_v2ray-plugin is not set\n# CONFIG_v2ray-plugin_INCLUDE_GOPROXY is not set\n# end of Project V\n\n#\n# Routing and Redirection\n#\n# CONFIG_PACKAGE_babel-pinger is not set\n# CONFIG_PACKAGE_babeld is not set\n# CONFIG_PACKAGE_batmand is not set\n# CONFIG_PACKAGE_bcp38 is not set\n# CONFIG_PACKAGE_bfdd is not set\n# CONFIG_PACKAGE_bird1-ipv4 is not set\n# CONFIG_PACKAGE_bird1-ipv4-uci is not set\n# CONFIG_PACKAGE_bird1-ipv6 is not set\n# CONFIG_PACKAGE_bird1-ipv6-uci is not set\n# CONFIG_PACKAGE_bird1c-ipv4 is not set\n# CONFIG_PACKAGE_bird1c-ipv6 is not set\n# CONFIG_PACKAGE_bird1cl-ipv4 is not set\n# CONFIG_PACKAGE_bird1cl-ipv6 is not set\n# CONFIG_PACKAGE_bird2 is not set\n# CONFIG_PACKAGE_bird2c is not set\n# CONFIG_PACKAGE_bird2cl is not set\n# CONFIG_PACKAGE_bmx6 is not set\n# CONFIG_PACKAGE_bmx7 is not set\n# CONFIG_PACKAGE_cjdns is not set\n# CONFIG_PACKAGE_cjdns-tests is not set\n# CONFIG_PACKAGE_dcstad is not set\n# CONFIG_PACKAGE_dcwapd is not set\n# CONFIG_PACKAGE_devlink is not set\n# CONFIG_PACKAGE_frr is not set\n# CONFIG_PACKAGE_genl is not set\n# CONFIG_PACKAGE_igmpproxy is not set\n# CONFIG_PACKAGE_ip-bridge is not set\nCONFIG_PACKAGE_ip-full=y\n# CONFIG_PACKAGE_ip-tiny is not set\n# CONFIG_PACKAGE_lldpd is not set\n# CONFIG_PACKAGE_mcproxy is not set\n# CONFIG_PACKAGE_mrmctl is not set\n# CONFIG_PACKAGE_mwan3 is not set\n# CONFIG_PACKAGE_nstat is not set\n# CONFIG_PACKAGE_olsrd is not set\n# CONFIG_PACKAGE_prince is not set\n# CONFIG_PACKAGE_quagga is not set\n# CONFIG_PACKAGE_rdma is not set\n# CONFIG_PACKAGE_relayd is not set\n# CONFIG_PACKAGE_smcroute is not set\n# CONFIG_PACKAGE_ss is not set\n# CONFIG_PACKAGE_sslh is not set\n# CONFIG_PACKAGE_tc-full is not set\n# CONFIG_PACKAGE_tc-mod-iptables is not set\n# CONFIG_PACKAGE_tc-tiny is not set\n# CONFIG_PACKAGE_tcpproxy is not set\n# CONFIG_PACKAGE_udp-broadcast-relay-redux is not set\n# CONFIG_PACKAGE_vis is not set\n# CONFIG_PACKAGE_yggdrasil is not set\n# end of Routing and Redirection\n\n#\n# SSH\n#\n# CONFIG_PACKAGE_autossh is not set\n# CONFIG_PACKAGE_openssh-client is not set\n# CONFIG_PACKAGE_openssh-client-utils is not set\n# CONFIG_PACKAGE_openssh-keygen is not set\n# CONFIG_PACKAGE_openssh-moduli is not set\n# CONFIG_PACKAGE_openssh-server is not set\n# CONFIG_PACKAGE_openssh-server-pam is not set\n# CONFIG_PACKAGE_openssh-sftp-avahi-service is not set\n# CONFIG_PACKAGE_openssh-sftp-client is not set\n# CONFIG_PACKAGE_openssh-sftp-server is not set\n# CONFIG_PACKAGE_sshtunnel is not set\n# CONFIG_PACKAGE_tmate is not set\n# end of SSH\n\n#\n# THC-IPv6 attack and analyzing toolkit\n#\n# CONFIG_PACKAGE_thc-ipv6-address6 is not set\n# CONFIG_PACKAGE_thc-ipv6-alive6 is not set\n# CONFIG_PACKAGE_thc-ipv6-covert-send6 is not set\n# CONFIG_PACKAGE_thc-ipv6-covert-send6d is not set\n# CONFIG_PACKAGE_thc-ipv6-denial6 is not set\n# CONFIG_PACKAGE_thc-ipv6-detect-new-ip6 is not set\n# CONFIG_PACKAGE_thc-ipv6-detect-sniffer6 is not set\n# CONFIG_PACKAGE_thc-ipv6-dnsdict6 is not set\n# CONFIG_PACKAGE_thc-ipv6-dnsrevenum6 is not set\n# CONFIG_PACKAGE_thc-ipv6-dos-new-ip6 is not set\n# CONFIG_PACKAGE_thc-ipv6-dump-router6 is not set\n# CONFIG_PACKAGE_thc-ipv6-exploit6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-advertise6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-dhcps6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-dns6d is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-dnsupdate6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-mipv6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-mld26 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-mld6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-mldrouter6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-router26 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-router6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fake-solicitate6 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-advertise6 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-dhcpc6 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-mld26 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-mld6 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-mldrouter6 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-router26 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-router6 is not set\n# CONFIG_PACKAGE_thc-ipv6-flood-solicitate6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fragmentation6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fuzz-dhcpc6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fuzz-dhcps6 is not set\n# CONFIG_PACKAGE_thc-ipv6-fuzz-ip6 is not set\n# CONFIG_PACKAGE_thc-ipv6-implementation6 is not set\n# CONFIG_PACKAGE_thc-ipv6-implementation6d is not set\n# CONFIG_PACKAGE_thc-ipv6-inverse-lookup6 is not set\n# CONFIG_PACKAGE_thc-ipv6-kill-router6 is not set\n# CONFIG_PACKAGE_thc-ipv6-ndpexhaust6 is not set\n# CONFIG_PACKAGE_thc-ipv6-node-query6 is not set\n# CONFIG_PACKAGE_thc-ipv6-parasite6 is not set\n# CONFIG_PACKAGE_thc-ipv6-passive-discovery6 is not set\n# CONFIG_PACKAGE_thc-ipv6-randicmp6 is not set\n# CONFIG_PACKAGE_thc-ipv6-redir6 is not set\n# CONFIG_PACKAGE_thc-ipv6-rsmurf6 is not set\n# CONFIG_PACKAGE_thc-ipv6-sendpees6 is not set\n# CONFIG_PACKAGE_thc-ipv6-sendpeesmp6 is not set\n# CONFIG_PACKAGE_thc-ipv6-smurf6 is not set\n# CONFIG_PACKAGE_thc-ipv6-thcping6 is not set\n# CONFIG_PACKAGE_thc-ipv6-toobig6 is not set\n# CONFIG_PACKAGE_thc-ipv6-trace6 is not set\n# end of THC-IPv6 attack and analyzing toolkit\n\n#\n# Tcpreplay\n#\n# CONFIG_PACKAGE_tcpbridge is not set\n# CONFIG_PACKAGE_tcpcapinfo is not set\n# CONFIG_PACKAGE_tcpliveplay is not set\n# CONFIG_PACKAGE_tcpprep is not set\n# CONFIG_PACKAGE_tcpreplay is not set\n# CONFIG_PACKAGE_tcpreplay-all is not set\n# CONFIG_PACKAGE_tcpreplay-edit is not set\n# CONFIG_PACKAGE_tcprewrite is not set\n# end of Tcpreplay\n\n#\n# Telephony\n#\n# CONFIG_PACKAGE_asterisk is not set\n# CONFIG_PACKAGE_baresip is not set\n# CONFIG_PACKAGE_freeswitch is not set\n# CONFIG_PACKAGE_kamailio is not set\n# CONFIG_PACKAGE_miax is not set\n# CONFIG_PACKAGE_pcapsipdump is not set\n# CONFIG_PACKAGE_restund is not set\n# CONFIG_PACKAGE_rtpengine is not set\n# CONFIG_PACKAGE_rtpengine-no-transcode is not set\n# CONFIG_PACKAGE_rtpengine-recording is not set\n# CONFIG_PACKAGE_rtpproxy is not set\n# CONFIG_PACKAGE_sipp is not set\n# CONFIG_PACKAGE_siproxd is not set\n# CONFIG_PACKAGE_yate is not set\n# end of Telephony\n\n#\n# Telephony Lantiq\n#\n# end of Telephony Lantiq\n\n#\n# Time Synchronization\n#\n# CONFIG_PACKAGE_chrony is not set\n# CONFIG_PACKAGE_chrony-nts is not set\n# CONFIG_PACKAGE_htpdate is not set\n# CONFIG_PACKAGE_linuxptp is not set\n# CONFIG_PACKAGE_ntp-keygen is not set\n# CONFIG_PACKAGE_ntp-utils is not set\n# CONFIG_PACKAGE_ntpclient is not set\n# CONFIG_PACKAGE_ntpd is not set\n# CONFIG_PACKAGE_ntpdate is not set\n# end of Time Synchronization\n\n#\n# VPN\n#\n# CONFIG_PACKAGE_chaosvpn is not set\n# CONFIG_PACKAGE_eoip is not set\n# CONFIG_PACKAGE_fastd is not set\n# CONFIG_PACKAGE_libreswan is not set\n# CONFIG_PACKAGE_n2n-edge is not set\n# CONFIG_PACKAGE_n2n-supernode is not set\n# CONFIG_PACKAGE_ocserv is not set\n# CONFIG_PACKAGE_openconnect is not set\n# CONFIG_PACKAGE_openfortivpn is not set\n# CONFIG_PACKAGE_openvpn-easy-rsa is not set\n# CONFIG_PACKAGE_openvpn-mbedtls is not set\n# CONFIG_PACKAGE_openvpn-openssl is not set\n# CONFIG_PACKAGE_openvpn-wolfssl is not set\n# CONFIG_PACKAGE_pptpd is not set\n# CONFIG_PACKAGE_softethervpn-base is not set\n# CONFIG_PACKAGE_softethervpn-bridge is not set\n# CONFIG_PACKAGE_softethervpn-client is not set\n# CONFIG_PACKAGE_softethervpn-server is not set\n# CONFIG_PACKAGE_softethervpn5-bridge is not set\n# CONFIG_PACKAGE_softethervpn5-client is not set\n# CONFIG_PACKAGE_softethervpn5-server is not set\n# CONFIG_PACKAGE_sstp-client is not set\n# CONFIG_PACKAGE_strongswan is not set\n# CONFIG_PACKAGE_tailscale is not set\n# CONFIG_PACKAGE_tailscaled is not set\n# CONFIG_PACKAGE_tinc is not set\n# CONFIG_PACKAGE_uanytun is not set\n# CONFIG_PACKAGE_uanytun-nettle is not set\n# CONFIG_PACKAGE_uanytun-nocrypt is not set\n# CONFIG_PACKAGE_uanytun-sslcrypt is not set\n# CONFIG_PACKAGE_vpnc is not set\n# CONFIG_PACKAGE_vpnc-scripts is not set\n# CONFIG_PACKAGE_wireguard-tools is not set\n# CONFIG_PACKAGE_xl2tpd is not set\nCONFIG_PACKAGE_zerotier=y\n\n#\n# Configuration\n#\n# CONFIG_ZEROTIER_ENABLE_DEBUG is not set\n# CONFIG_ZEROTIER_ENABLE_SELFTEST is not set\n# end of Configuration\n# end of VPN\n\n#\n# Version Control Systems\n#\n# CONFIG_PACKAGE_git is not set\n# CONFIG_PACKAGE_git-http is not set\n# CONFIG_PACKAGE_subversion-client is not set\n# CONFIG_PACKAGE_subversion-libs is not set\n# CONFIG_PACKAGE_subversion-server is not set\n# end of Version Control Systems\n\n#\n# WWAN\n#\n# CONFIG_PACKAGE_adb-enablemodem is not set\n# CONFIG_PACKAGE_comgt is not set\n# CONFIG_PACKAGE_comgt-directip is not set\n# CONFIG_PACKAGE_comgt-ncm is not set\n# CONFIG_PACKAGE_umbim is not set\n# CONFIG_PACKAGE_uqmi is not set\n# end of WWAN\n\n#\n# Web Servers/Proxies\n#\n# CONFIG_PACKAGE_apache is not set\n# CONFIG_PACKAGE_brook is not set\n# CONFIG_BROOK_COMPRESS_GOPROXY is not set\nCONFIG_BROOK_COMPRESS_UPX=y\n# CONFIG_PACKAGE_cgi-io is not set\n# CONFIG_PACKAGE_clamav is not set\n# CONFIG_PACKAGE_e2guardian is not set\n# CONFIG_PACKAGE_etebase is not set\n# CONFIG_PACKAGE_freshclam is not set\n# CONFIG_PACKAGE_frpc is not set\n# CONFIG_PACKAGE_frps is not set\n# CONFIG_PACKAGE_gateway-go is not set\n# CONFIG_PACKAGE_gunicorn3 is not set\n# CONFIG_PACKAGE_haproxy is not set\n# CONFIG_PACKAGE_haproxy-nossl is not set\n# CONFIG_PACKAGE_hysteria is not set\n# CONFIG_PACKAGE_kcptun-client is not set\n# CONFIG_PACKAGE_kcptun-config is not set\n# CONFIG_PACKAGE_kcptun-server is not set\n# CONFIG_PACKAGE_lighttpd is not set\nCONFIG_PACKAGE_microsocks=y\n# CONFIG_PACKAGE_naiveproxy is not set\n# CONFIG_PACKAGE_nginx-all-module is not set\n# CONFIG_PACKAGE_nginx-mod-luci is not set\n# CONFIG_PACKAGE_nginx-ssl is not set\n# CONFIG_PACKAGE_nginx-ssl-util is not set\n# CONFIG_PACKAGE_nginx-ssl-util-nopcre is not set\nCONFIG_PACKAGE_pdnsd-alt=y\n# CONFIG_PACKAGE_polipo is not set\n# CONFIG_PACKAGE_privoxy is not set\n# CONFIG_PACKAGE_python3-gunicorn is not set\n# CONFIG_PACKAGE_radicale is not set\n# CONFIG_PACKAGE_radicale2 is not set\n# CONFIG_PACKAGE_radicale2-examples is not set\n# CONFIG_PACKAGE_redsocks2 is not set\n# CONFIG_PACKAGE_shadowsocks-libev-config is not set\nCONFIG_PACKAGE_shadowsocks-libev-ss-local=y\nCONFIG_PACKAGE_shadowsocks-libev-ss-redir=y\n# CONFIG_PACKAGE_shadowsocks-libev-ss-rules is not set\n# CONFIG_PACKAGE_shadowsocks-libev-ss-server is not set\n# CONFIG_PACKAGE_shadowsocks-libev-ss-tunnel is not set\n# CONFIG_PACKAGE_shadowsocks-rust-sslocal is not set\n# CONFIG_PACKAGE_shadowsocks-rust-ssmanager is not set\n# CONFIG_PACKAGE_shadowsocks-rust-ssserver is not set\n# CONFIG_PACKAGE_shadowsocks-rust-ssurl is not set\nCONFIG_PACKAGE_shadowsocksr-libev-ssr-check=y\nCONFIG_PACKAGE_shadowsocksr-libev-ssr-local=y\n# CONFIG_PACKAGE_shadowsocksr-libev-ssr-nat is not set\nCONFIG_PACKAGE_shadowsocksr-libev-ssr-redir=y\n# CONFIG_PACKAGE_shadowsocksr-libev-ssr-server is not set\n# CONFIG_PACKAGE_sockd is not set\n# CONFIG_PACKAGE_socksify is not set\n# CONFIG_PACKAGE_spawn-fcgi is not set\n# CONFIG_PACKAGE_squid is not set\n# CONFIG_PACKAGE_srelay is not set\n# CONFIG_PACKAGE_tinyproxy is not set\n# CONFIG_PACKAGE_trojan-go is not set\nCONFIG_PACKAGE_uhttpd=y\n# CONFIG_PACKAGE_uhttpd-mod-lua is not set\nCONFIG_PACKAGE_uhttpd-mod-ubus=y\n# CONFIG_PACKAGE_uwsgi is not set\n# end of Web Servers/Proxies\n\n#\n# Wireless\n#\n# CONFIG_PACKAGE_aircrack-ng is not set\n# CONFIG_PACKAGE_airmon-ng is not set\n# CONFIG_PACKAGE_dynapoint is not set\n# CONFIG_PACKAGE_hcxdumptool is not set\n# CONFIG_PACKAGE_hcxtools is not set\n# CONFIG_PACKAGE_horst is not set\n# CONFIG_PACKAGE_mt_wifi is not set\n# CONFIG_PACKAGE_pixiewps is not set\n# CONFIG_PACKAGE_reaver is not set\n# CONFIG_PACKAGE_wavemon is not set\n# CONFIG_PACKAGE_wifischedule is not set\n# end of Wireless\n\n#\n# WirelessAPD\n#\n# CONFIG_PACKAGE_eapol-test is not set\n# CONFIG_PACKAGE_eapol-test-openssl is not set\n# CONFIG_PACKAGE_eapol-test-wolfssl is not set\n# CONFIG_PACKAGE_hostapd is not set\n# CONFIG_PACKAGE_hostapd-basic is not set\n# CONFIG_PACKAGE_hostapd-basic-openssl is not set\n# CONFIG_PACKAGE_hostapd-basic-wolfssl is not set\n# CONFIG_PACKAGE_hostapd-common is not set\n# CONFIG_PACKAGE_hostapd-mini is not set\n# CONFIG_PACKAGE_hostapd-openssl is not set\n# CONFIG_PACKAGE_hostapd-wolfssl is not set\n# CONFIG_PACKAGE_hs20-client is not set\n# CONFIG_PACKAGE_hs20-common is not set\n# CONFIG_PACKAGE_hs20-server is not set\n# CONFIG_PACKAGE_wpa-supplicant is not set\n# CONFIG_WPA_WOLFSSL is not set\n# CONFIG_DRIVER_WEXT_SUPPORT is not set\nCONFIG_DRIVER_11N_SUPPORT=y\nCONFIG_DRIVER_11AC_SUPPORT=y\n# CONFIG_DRIVER_11AX_SUPPORT is not set\n# CONFIG_WPA_ENABLE_WEP is not set\n# CONFIG_PACKAGE_wpa-supplicant-basic is not set\n# CONFIG_PACKAGE_wpa-supplicant-mini is not set\n# CONFIG_PACKAGE_wpa-supplicant-openssl is not set\n# CONFIG_PACKAGE_wpa-supplicant-wolfssl is not set\n# CONFIG_PACKAGE_wpad is not set\n# CONFIG_PACKAGE_wpad-basic is not set\n# CONFIG_PACKAGE_wpad-basic-openssl is not set\n# CONFIG_PACKAGE_wpad-basic-wolfssl is not set\n# CONFIG_PACKAGE_wpad-mini is not set\n# CONFIG_PACKAGE_wpad-openssl is not set\n# CONFIG_PACKAGE_wpad-wolfssl is not set\n# end of WirelessAPD\n\n#\n# arp-scan\n#\n# CONFIG_PACKAGE_arp-scan is not set\n# CONFIG_PACKAGE_arp-scan-database is not set\n# end of arp-scan\n\n# CONFIG_PACKAGE_464xlat is not set\n# CONFIG_PACKAGE_6in4 is not set\n# CONFIG_PACKAGE_6rd is not set\n# CONFIG_PACKAGE_6to4 is not set\n# CONFIG_PACKAGE_UDPspeeder is not set\n# CONFIG_PACKAGE_acme is not set\n# CONFIG_PACKAGE_acme-dnsapi is not set\n# CONFIG_PACKAGE_adblock is not set\nCONFIG_PACKAGE_adbyby=y\n# CONFIG_PACKAGE_addrwatch is not set\n# CONFIG_PACKAGE_adguardhome is not set\n# CONFIG_PACKAGE_ahcpd is not set\n# CONFIG_PACKAGE_alfred is not set\n# CONFIG_PACKAGE_apcupsd is not set\n# CONFIG_PACKAGE_apcupsd-cgi is not set\n# CONFIG_PACKAGE_apinger is not set\n# CONFIG_PACKAGE_atlas-probe is not set\n# CONFIG_PACKAGE_atlas-sw-probe is not set\n# CONFIG_PACKAGE_atlas-sw-probe-rpc is not set\n# CONFIG_PACKAGE_baidupcs-web is not set\n# CONFIG_BAIDUPCS_WEB_COMPRESS_GOPROXY is not set\nCONFIG_BAIDUPCS_WEB_COMPRESS_UPX=y\n# CONFIG_PACKAGE_banip is not set\n# CONFIG_PACKAGE_batctl-default is not set\n# CONFIG_PACKAGE_batctl-full is not set\n# CONFIG_PACKAGE_batctl-tiny is not set\n# CONFIG_PACKAGE_beanstalkd is not set\n# CONFIG_PACKAGE_bmon is not set\n# CONFIG_PACKAGE_boinc is not set\n# CONFIG_PACKAGE_bpftool-full is not set\n# CONFIG_PACKAGE_bpftool-minimal is not set\n# CONFIG_PACKAGE_bwm-ng is not set\n# CONFIG_PACKAGE_bwping is not set\n# CONFIG_PACKAGE_chat is not set\nCONFIG_PACKAGE_chinadns-ng=y\n# CONFIG_PACKAGE_cifsmount is not set\n# CONFIG_PACKAGE_coap-server is not set\n# CONFIG_PACKAGE_conserver is not set\n# CONFIG_PACKAGE_cshark is not set\n# CONFIG_PACKAGE_daemonlogger is not set\n# CONFIG_PACKAGE_darkstat is not set\n# CONFIG_PACKAGE_dawn is not set\n# CONFIG_PACKAGE_dhcpcd is not set\n# CONFIG_PACKAGE_dmapd is not set\n# CONFIG_PACKAGE_dnscrypt-proxy2 is not set\n# CONFIG_PACKAGE_dnsforwarder is not set\n# CONFIG_PACKAGE_dnstap is not set\n# CONFIG_PACKAGE_dnstop is not set\n# CONFIG_PACKAGE_ds-lite is not set\n# CONFIG_PACKAGE_dsmboot is not set\n# CONFIG_PACKAGE_esniper is not set\n# CONFIG_PACKAGE_etherwake is not set\n# CONFIG_PACKAGE_etherwake-nfqueue is not set\n# CONFIG_PACKAGE_ethtool is not set\n# CONFIG_PACKAGE_ethtool-full is not set\n# CONFIG_PACKAGE_fakeidentd is not set\n# CONFIG_PACKAGE_fakepop is not set\n# CONFIG_PACKAGE_family-dns is not set\n# CONFIG_PACKAGE_foolsm is not set\n# CONFIG_PACKAGE_fping is not set\n# CONFIG_PACKAGE_generate-ipv6-address is not set\n# CONFIG_PACKAGE_geth is not set\n# CONFIG_PACKAGE_git-lfs is not set\n# CONFIG_PACKAGE_gnunet is not set\n# CONFIG_PACKAGE_gre is not set\n# CONFIG_PACKAGE_hnet-full is not set\n# CONFIG_PACKAGE_hnet-full-l2tp is not set\n# CONFIG_PACKAGE_hnet-full-secure is not set\n# CONFIG_PACKAGE_hnetd-nossl is not set\n# CONFIG_PACKAGE_hnetd-openssl is not set\n# CONFIG_PACKAGE_httping is not set\n# CONFIG_PACKAGE_httping-nossl is not set\n# CONFIG_PACKAGE_https-dns-proxy is not set\n# CONFIG_PACKAGE_i2pd is not set\n# CONFIG_PACKAGE_ibrdtn-tools is not set\n# CONFIG_PACKAGE_ibrdtnd is not set\n# CONFIG_PACKAGE_ifstat is not set\n# CONFIG_PACKAGE_iftop is not set\n# CONFIG_PACKAGE_iiod is not set\n# CONFIG_PACKAGE_iperf is not set\n# CONFIG_PACKAGE_iperf3 is not set\n# CONFIG_PACKAGE_iperf3-ssl is not set\n# CONFIG_PACKAGE_ipip is not set\nCONFIG_PACKAGE_ipset=y\n# CONFIG_PACKAGE_ipset-dns is not set\nCONFIG_PACKAGE_ipt2socks=y\n# CONFIG_PACKAGE_iptraf-ng is not set\n# CONFIG_PACKAGE_iputils-arping is not set\n# CONFIG_PACKAGE_iputils-clockdiff is not set\n# CONFIG_PACKAGE_iputils-ping is not set\n# CONFIG_PACKAGE_iputils-tftpd is not set\n# CONFIG_PACKAGE_iputils-tracepath is not set\n# CONFIG_PACKAGE_ipvsadm is not set\n# CONFIG_PACKAGE_irtt is not set\n# CONFIG_PACKAGE_iw is not set\n# CONFIG_PACKAGE_iw-full is not set\n# CONFIG_PACKAGE_jool-tools is not set\n# CONFIG_PACKAGE_keepalived is not set\n# CONFIG_PACKAGE_knxd is not set\n# CONFIG_PACKAGE_kplex is not set\n# CONFIG_PACKAGE_krb5-client is not set\n# CONFIG_PACKAGE_krb5-libs is not set\n# CONFIG_PACKAGE_krb5-server is not set\n# CONFIG_PACKAGE_krb5-server-extras is not set\nCONFIG_PACKAGE_libipset=y\n# CONFIG_PACKAGE_libndp is not set\n# CONFIG_PACKAGE_linknx is not set\n# CONFIG_PACKAGE_lynx is not set\n# CONFIG_PACKAGE_mac-telnet-client is not set\n# CONFIG_PACKAGE_mac-telnet-discover is not set\n# CONFIG_PACKAGE_mac-telnet-ping is not set\n# CONFIG_PACKAGE_mac-telnet-server is not set\n# CONFIG_PACKAGE_map is not set\n# CONFIG_PACKAGE_mbusd is not set\n# CONFIG_PACKAGE_memcached is not set\n# CONFIG_PACKAGE_mentohust is not set\n# CONFIG_PACKAGE_mii-tool is not set\n# CONFIG_PACKAGE_mikrotik-btest is not set\n# CONFIG_PACKAGE_mini_snmpd is not set\n# CONFIG_PACKAGE_minimalist-pcproxy is not set\n# CONFIG_PACKAGE_miredo is not set\n# CONFIG_PACKAGE_modemmanager is not set\n# CONFIG_PACKAGE_mosquitto-client-nossl is not set\n# CONFIG_PACKAGE_mosquitto-client-ssl is not set\n# CONFIG_PACKAGE_mosquitto-nossl is not set\n# CONFIG_PACKAGE_mosquitto-ssl is not set\n# CONFIG_PACKAGE_mrd6 is not set\n# CONFIG_PACKAGE_mstpd is not set\n# CONFIG_PACKAGE_mtk_apcli is not set\n# CONFIG_PACKAGE_mtr is not set\n# CONFIG_PACKAGE_nbd is not set\n# CONFIG_PACKAGE_nbd-server is not set\n# CONFIG_PACKAGE_ncp is not set\n# CONFIG_PACKAGE_ndppd is not set\n# CONFIG_PACKAGE_ndptool is not set\n# CONFIG_PACKAGE_nebula is not set\n# CONFIG_PACKAGE_nebula-cert is not set\n# CONFIG_PACKAGE_net-tools-route is not set\n# CONFIG_PACKAGE_netcat is not set\n# CONFIG_PACKAGE_netdiscover is not set\n# CONFIG_PACKAGE_netifyd is not set\n# CONFIG_PACKAGE_netperf is not set\n# CONFIG_PACKAGE_netsniff-ng is not set\n# CONFIG_PACKAGE_netstinky is not set\n# CONFIG_PACKAGE_nextdns is not set\n# CONFIG_PACKAGE_nfdump is not set\n# CONFIG_PACKAGE_nlbwmon is not set\n# CONFIG_PACKAGE_noddos is not set\n# CONFIG_PACKAGE_noping is not set\n# CONFIG_PACKAGE_npc is not set\n# CONFIG_PACKAGE_nut is not set\n# CONFIG_PACKAGE_obfs4proxy is not set\n# CONFIG_PACKAGE_odhcp6c is not set\n# CONFIG_PACKAGE_odhcpd is not set\n# CONFIG_PACKAGE_odhcpd-ipv6only is not set\n# CONFIG_PACKAGE_ola is not set\n# CONFIG_PACKAGE_omcproxy is not set\n# CONFIG_PACKAGE_onionshare-cli is not set\n# CONFIG_PACKAGE_ooniprobe is not set\n# CONFIG_PACKAGE_oor is not set\n# CONFIG_PACKAGE_open-iscsi is not set\n# CONFIG_PACKAGE_oping is not set\n# CONFIG_PACKAGE_ostiary is not set\n# CONFIG_PACKAGE_pagekitec is not set\n# CONFIG_PACKAGE_pen is not set\n# CONFIG_PACKAGE_phantap is not set\n# CONFIG_PACKAGE_pimbd is not set\n# CONFIG_PACKAGE_pingcheck is not set\n# CONFIG_PACKAGE_port-mirroring is not set\nCONFIG_PACKAGE_ppp=y\n# CONFIG_PACKAGE_ppp-mod-passwordfd is not set\n# CONFIG_PACKAGE_ppp-mod-pppoa is not set\nCONFIG_PACKAGE_ppp-mod-pppoe=y\n# CONFIG_PACKAGE_ppp-mod-pppol2tp is not set\n# CONFIG_PACKAGE_ppp-mod-pptp is not set\n# CONFIG_PACKAGE_ppp-mod-radius is not set\n# CONFIG_PACKAGE_ppp-multilink is not set\n# CONFIG_PACKAGE_pppdump is not set\n# CONFIG_PACKAGE_pppoe-discovery is not set\n# CONFIG_PACKAGE_pppossh is not set\n# CONFIG_PACKAGE_pppstats is not set\n# CONFIG_PACKAGE_proto-bonding is not set\n# CONFIG_PACKAGE_proxychains-ng is not set\n# CONFIG_PACKAGE_ptunnel-ng is not set\n# CONFIG_PACKAGE_radsecproxy is not set\n# CONFIG_PACKAGE_ratched is not set\n# CONFIG_PACKAGE_ratechecker is not set\n# CONFIG_PACKAGE_redsocks is not set\n# CONFIG_PACKAGE_remserial is not set\n# CONFIG_PACKAGE_restic-rest-server is not set\n# CONFIG_PACKAGE_rpcapd is not set\n# CONFIG_PACKAGE_rpcbind is not set\n# CONFIG_PACKAGE_rssileds is not set\n# CONFIG_PACKAGE_rsyslog is not set\n# CONFIG_PACKAGE_safe-search is not set\n# CONFIG_PACKAGE_samba36-client is not set\n# CONFIG_PACKAGE_samba36-net is not set\nCONFIG_PACKAGE_samba36-server=y\nCONFIG_PACKAGE_SAMBA_MAX_DEBUG_LEVEL=-1\n# CONFIG_PACKAGE_samba4-admin is not set\n# CONFIG_PACKAGE_samba4-client is not set\n# CONFIG_PACKAGE_samba4-libs is not set\n# CONFIG_PACKAGE_samba4-server is not set\n# CONFIG_PACKAGE_samba4-utils is not set\n# CONFIG_PACKAGE_samplicator is not set\n# CONFIG_PACKAGE_scapy is not set\n# CONFIG_PACKAGE_sctp-tools is not set\n# CONFIG_PACKAGE_seafile-ccnet is not set\n# CONFIG_PACKAGE_seafile-seahub is not set\n# CONFIG_PACKAGE_seafile-server is not set\n# CONFIG_PACKAGE_seafile-server-fuse is not set\n# CONFIG_PACKAGE_ser2net is not set\n# CONFIG_PACKAGE_simple-adblock is not set\nCONFIG_PACKAGE_simple-obfs=y\n# CONFIG_PACKAGE_simple-obfs-server is not set\n\n#\n# Simple-obfs Compile Configuration\n#\n# CONFIG_SIMPLE_OBFS_STATIC_LINK is not set\n# end of Simple-obfs Compile Configuration\n\n# CONFIG_PACKAGE_smartdns is not set\n# CONFIG_PACKAGE_smbinfo is not set\n# CONFIG_PACKAGE_snmp-mibs is not set\n# CONFIG_PACKAGE_snmp-utils is not set\n# CONFIG_PACKAGE_snmpd is not set\n# CONFIG_PACKAGE_snmptrapd is not set\n# CONFIG_PACKAGE_socat is not set\n# CONFIG_PACKAGE_softflowd is not set\n# CONFIG_PACKAGE_soloscli is not set\n# CONFIG_PACKAGE_speedtest-netperf is not set\n# CONFIG_PACKAGE_spoofer is not set\n# CONFIG_PACKAGE_ssocks is not set\n# CONFIG_PACKAGE_ssocksd is not set\n# CONFIG_PACKAGE_static-neighbor-reports is not set\n# CONFIG_PACKAGE_stunnel is not set\n# CONFIG_PACKAGE_switchdev-poller is not set\n# CONFIG_PACKAGE_tac_plus is not set\n# CONFIG_PACKAGE_tac_plus-pam is not set\n# CONFIG_PACKAGE_tayga is not set\n# CONFIG_PACKAGE_tcpdump is not set\n# CONFIG_PACKAGE_tcpdump-mini is not set\nCONFIG_PACKAGE_tcping=y\n# CONFIG_PACKAGE_tcpping is not set\n# CONFIG_PACKAGE_tgt is not set\n# CONFIG_PACKAGE_tmate-ssh-server is not set\n# CONFIG_PACKAGE_tor is not set\n# CONFIG_PACKAGE_tor-basic is not set\n# CONFIG_PACKAGE_tor-fw-helper is not set\n# CONFIG_PACKAGE_trafficshaper is not set\n# CONFIG_PACKAGE_travelmate is not set\n# CONFIG_PACKAGE_trojan is not set\nCONFIG_PACKAGE_trojan-plus=y\n# CONFIG_PACKAGE_u2pnpd is not set\n# CONFIG_PACKAGE_uacme is not set\nCONFIG_PACKAGE_uclient-fetch=y\n# CONFIG_PACKAGE_udptunnel is not set\n# CONFIG_PACKAGE_udpxy is not set\n# CONFIG_PACKAGE_ulogd is not set\n# CONFIG_PACKAGE_umdns is not set\n# CONFIG_PACKAGE_usbip is not set\n# CONFIG_PACKAGE_uugamebooster is not set\n# CONFIG_PACKAGE_v2ray-core is not set\n# CONFIG_PACKAGE_vallumd is not set\n# CONFIG_PACKAGE_verysync is not set\nCONFIG_PACKAGE_vlmcsd=y\n# CONFIG_PACKAGE_vncrepeater is not set\n# CONFIG_PACKAGE_vnstat is not set\n# CONFIG_PACKAGE_vnstat2 is not set\n# CONFIG_PACKAGE_vpn-policy-routing is not set\n# CONFIG_PACKAGE_vpnbypass is not set\n# CONFIG_PACKAGE_vti is not set\n# CONFIG_PACKAGE_vxlan is not set\n# CONFIG_PACKAGE_wakeonlan is not set\n# CONFIG_PACKAGE_wg-installer-client is not set\n# CONFIG_PACKAGE_wg-installer-server is not set\n# CONFIG_PACKAGE_wol is not set\n# CONFIG_PACKAGE_wpan-tools is not set\n# CONFIG_PACKAGE_wwan is not set\n# CONFIG_PACKAGE_xinetd is not set\nCONFIG_PACKAGE_xray-core=y\n\n#\n# Xray-core Configuration\n#\n# CONFIG_XRAY_CORE_COMPRESS_GOPROXY is not set\nCONFIG_XRAY_CORE_COMPRESS_UPX=y\n# end of Xray-core Configuration\n\n# CONFIG_PACKAGE_xray-example is not set\n# CONFIG_PACKAGE_xray-geodata is not set\n# CONFIG_PACKAGE_xray-plugin is not set\n# CONFIG_XRAY_PLUGIN_PROVIDE_V2RAY_PLUGIN is not set\n# CONFIG_XRAY_PLUGIN_COMPRESS_GOPROXY is not set\nCONFIG_XRAY_PLUGIN_COMPRESS_UPX=y\n# end of Network\n\n#\n# Sound\n#\n# CONFIG_PACKAGE_alsa-utils is not set\n# CONFIG_PACKAGE_alsa-utils-seq is not set\n# CONFIG_PACKAGE_alsa-utils-tests is not set\n# CONFIG_PACKAGE_aserver is not set\n# CONFIG_PACKAGE_espeak is not set\n# CONFIG_PACKAGE_faad2 is not set\n# CONFIG_PACKAGE_fdk-aac is not set\n# CONFIG_PACKAGE_forked-daapd is not set\n# CONFIG_PACKAGE_ices is not set\n# CONFIG_PACKAGE_lame is not set\n# CONFIG_PACKAGE_lame-lib is not set\n# CONFIG_PACKAGE_liblo-utils is not set\n# CONFIG_PACKAGE_madplay is not set\n# CONFIG_PACKAGE_moc is not set\n# CONFIG_PACKAGE_mpc is not set\n# CONFIG_PACKAGE_mpd-avahi-service is not set\n# CONFIG_PACKAGE_mpd-full is not set\n# CONFIG_PACKAGE_mpd-mini is not set\n# CONFIG_PACKAGE_mpg123 is not set\n# CONFIG_PACKAGE_opus-tools is not set\n# CONFIG_PACKAGE_pianod is not set\n# CONFIG_PACKAGE_pianod-client is not set\n# CONFIG_PACKAGE_portaudio is not set\n# CONFIG_PACKAGE_pulseaudio-daemon is not set\n# CONFIG_PACKAGE_pulseaudio-daemon-avahi is not set\n# CONFIG_PACKAGE_shairplay is not set\n# CONFIG_PACKAGE_shairport-sync-mbedtls is not set\n# CONFIG_PACKAGE_shairport-sync-mini is not set\n# CONFIG_PACKAGE_shairport-sync-openssl is not set\n# CONFIG_PACKAGE_shine is not set\n# CONFIG_PACKAGE_sox is not set\n# CONFIG_PACKAGE_squeezelite-full is not set\n# CONFIG_PACKAGE_squeezelite-mini is not set\n# CONFIG_PACKAGE_svox is not set\n# CONFIG_PACKAGE_upmpdcli is not set\n# end of Sound\n\n#\n# Utilities\n#\n\n#\n# AppArmor\n#\n# CONFIG_PACKAGE_apparmor-profiles is not set\n# CONFIG_PACKAGE_apparmor-utils is not set\n# end of AppArmor\n\n#\n# BigClown\n#\n# CONFIG_PACKAGE_bigclown-control-tool is not set\n# CONFIG_PACKAGE_bigclown-firmware-tool is not set\n# CONFIG_PACKAGE_bigclown-gateway is not set\n# CONFIG_PACKAGE_bigclown-mqtt2influxdb is not set\n# end of BigClown\n\n#\n# Boot Loaders\n#\n# CONFIG_PACKAGE_fconfig is not set\n# CONFIG_PACKAGE_uboot-envtools is not set\n# end of Boot Loaders\n\n#\n# Compression\n#\n# CONFIG_PACKAGE_bsdtar is not set\n# CONFIG_PACKAGE_bsdtar-noopenssl is not set\n# CONFIG_PACKAGE_bzip2 is not set\n# CONFIG_PACKAGE_gzip is not set\n# CONFIG_PACKAGE_lz4 is not set\n# CONFIG_PACKAGE_pigz is not set\n# CONFIG_PACKAGE_unrar is not set\nCONFIG_PACKAGE_unzip=y\n# CONFIG_PACKAGE_xz-utils is not set\n# CONFIG_PACKAGE_zipcmp is not set\n# CONFIG_PACKAGE_zipmerge is not set\n# CONFIG_PACKAGE_ziptool is not set\n# CONFIG_PACKAGE_zstd is not set\n# end of Compression\n\n#\n# Database\n#\n# CONFIG_PACKAGE_mariadb-common is not set\n# CONFIG_PACKAGE_pgsql-cli is not set\n# CONFIG_PACKAGE_pgsql-cli-extra is not set\n# CONFIG_PACKAGE_pgsql-server is not set\n# CONFIG_PACKAGE_rrdcgi1 is not set\n# CONFIG_PACKAGE_rrdtool1 is not set\n# CONFIG_PACKAGE_sqlite3-cli is not set\n# CONFIG_PACKAGE_unixodbc-tools is not set\n# end of Database\n\n#\n# Disc\n#\n# CONFIG_PACKAGE_autopart is not set\n# CONFIG_PACKAGE_blkdiscard is not set\nCONFIG_PACKAGE_blkid=y\n# CONFIG_PACKAGE_blockdev is not set\n# CONFIG_PACKAGE_cfdisk is not set\n# CONFIG_PACKAGE_cgdisk is not set\n# CONFIG_PACKAGE_eject is not set\n# CONFIG_PACKAGE_fdisk is not set\n# CONFIG_PACKAGE_findfs is not set\n# CONFIG_PACKAGE_fio is not set\n# CONFIG_PACKAGE_fixparts is not set\n# CONFIG_PACKAGE_gdisk is not set\n# CONFIG_PACKAGE_hd-idle is not set\n# CONFIG_PACKAGE_hdparm is not set\nCONFIG_PACKAGE_lsblk=y\n# CONFIG_PACKAGE_lvm2 is not set\n# CONFIG_PACKAGE_lvm2-selinux is not set\n# CONFIG_PACKAGE_mdadm is not set\n# CONFIG_PACKAGE_mtools is not set\nCONFIG_PACKAGE_parted=y\n\n#\n# Configuration\n#\nCONFIG_PARTED_READLINE=y\n# CONFIG_PARTED_LVM2 is not set\n# end of Configuration\n\n# CONFIG_PACKAGE_partx-utils is not set\n# CONFIG_PACKAGE_sfdisk is not set\n# CONFIG_PACKAGE_sgdisk is not set\n# CONFIG_PACKAGE_uvol is not set\n# CONFIG_PACKAGE_wipefs is not set\n# end of Disc\n\n#\n# Editors\n#\n# CONFIG_PACKAGE_joe is not set\n# CONFIG_PACKAGE_joe-extras is not set\n# CONFIG_PACKAGE_jupp is not set\n# CONFIG_PACKAGE_mg is not set\n# CONFIG_PACKAGE_nano is not set\n# CONFIG_PACKAGE_vim is not set\n# CONFIG_PACKAGE_vim-full is not set\n# CONFIG_PACKAGE_vim-fuller is not set\n# CONFIG_PACKAGE_vim-help is not set\n# CONFIG_PACKAGE_vim-runtime is not set\n# CONFIG_PACKAGE_zile is not set\n# end of Editors\n\n#\n# Encryption\n#\n# CONFIG_PACKAGE_ccrypt is not set\n# CONFIG_PACKAGE_certtool is not set\n# CONFIG_PACKAGE_cryptsetup is not set\n# CONFIG_PACKAGE_gnupg is not set\n# CONFIG_PACKAGE_gnupg2 is not set\n# CONFIG_PACKAGE_gnupg2-dirmngr is not set\n# CONFIG_PACKAGE_gnutls-utils is not set\n# CONFIG_PACKAGE_gpgv is not set\n# CONFIG_PACKAGE_gpgv2 is not set\n# CONFIG_PACKAGE_keyctl is not set\n# CONFIG_PACKAGE_keyutils is not set\n# CONFIG_PACKAGE_px5g-mbedtls is not set\n# CONFIG_PACKAGE_px5g-standalone is not set\n# CONFIG_PACKAGE_px5g-wolfssl is not set\n# CONFIG_PACKAGE_stoken is not set\n# end of Encryption\n\n#\n# Filesystem\n#\n# CONFIG_PACKAGE_acl is not set\n# CONFIG_PACKAGE_antfs-mount is not set\n# CONFIG_PACKAGE_attr is not set\n# CONFIG_PACKAGE_badblocks is not set\nCONFIG_PACKAGE_btrfs-progs=y\n# CONFIG_BTRFS_PROGS_ZSTD is not set\n# CONFIG_PACKAGE_chattr is not set\n# CONFIG_PACKAGE_debugfs is not set\n# CONFIG_PACKAGE_dosfstools is not set\n# CONFIG_PACKAGE_dumpe2fs is not set\n# CONFIG_PACKAGE_e2freefrag is not set\nCONFIG_PACKAGE_e2fsprogs=y\n# CONFIG_PACKAGE_e4crypt is not set\n# CONFIG_PACKAGE_exfat-fsck is not set\n# CONFIG_PACKAGE_exfat-mkfs is not set\n# CONFIG_PACKAGE_f2fs-tools is not set\n# CONFIG_PACKAGE_f2fs-tools-selinux is not set\n# CONFIG_PACKAGE_f2fsck is not set\n# CONFIG_PACKAGE_f2fsck-selinux is not set\n# CONFIG_PACKAGE_filefrag is not set\n# CONFIG_PACKAGE_fstrim is not set\n# CONFIG_PACKAGE_fuse-utils is not set\n# CONFIG_PACKAGE_fuse3-utils is not set\n# CONFIG_PACKAGE_hfsfsck is not set\n# CONFIG_PACKAGE_lsattr is not set\n# CONFIG_PACKAGE_mkf2fs is not set\n# CONFIG_PACKAGE_mkf2fs-selinux is not set\n# CONFIG_PACKAGE_mkhfs is not set\n# CONFIG_PACKAGE_ncdu is not set\n# CONFIG_PACKAGE_nfs-utils is not set\n# CONFIG_PACKAGE_nfs-utils-libs is not set\n# CONFIG_PACKAGE_ntfs-3g is not set\n# CONFIG_PACKAGE_ntfs-3g-low is not set\n# CONFIG_PACKAGE_ntfs-3g-utils is not set\n# CONFIG_PACKAGE_ntfs3-mount is not set\n# CONFIG_PACKAGE_owfs is not set\n# CONFIG_PACKAGE_owshell is not set\n# CONFIG_PACKAGE_resize2fs is not set\n# CONFIG_PACKAGE_squashfs-tools-mksquashfs is not set\n# CONFIG_PACKAGE_squashfs-tools-unsquashfs is not set\n# CONFIG_PACKAGE_swap-utils is not set\n# CONFIG_PACKAGE_sysfsutils is not set\n# CONFIG_PACKAGE_tune2fs is not set\n# CONFIG_PACKAGE_xfs-admin is not set\n# CONFIG_PACKAGE_xfs-fsck is not set\n# CONFIG_PACKAGE_xfs-growfs is not set\n# CONFIG_PACKAGE_xfs-mkfs is not set\n# end of Filesystem\n\n#\n# Image Manipulation\n#\n# CONFIG_PACKAGE_libjpeg-turbo-utils is not set\n# CONFIG_PACKAGE_tiff-utils is not set\n# end of Image Manipulation\n\n#\n# Microcontroller programming\n#\n# CONFIG_PACKAGE_avrdude is not set\n# CONFIG_PACKAGE_dfu-programmer is not set\n# CONFIG_PACKAGE_stm32flash is not set\n# end of Microcontroller programming\n\n#\n# RTKLIB Suite\n#\n# CONFIG_PACKAGE_convbin is not set\n# CONFIG_PACKAGE_pos2kml is not set\n# CONFIG_PACKAGE_rnx2rtkp is not set\n# CONFIG_PACKAGE_rtkrcv is not set\n# CONFIG_PACKAGE_str2str is not set\n# end of RTKLIB Suite\n\n#\n# Shells\n#\n# CONFIG_PACKAGE_bash is not set\n# CONFIG_PACKAGE_fish is not set\n# CONFIG_PACKAGE_klish is not set\n# CONFIG_PACKAGE_mksh is not set\n# CONFIG_PACKAGE_tcsh is not set\n# CONFIG_PACKAGE_zsh is not set\n# end of Shells\n\n#\n# Telephony\n#\n# CONFIG_PACKAGE_dahdi-cfg is not set\n# CONFIG_PACKAGE_dahdi-monitor is not set\n# CONFIG_PACKAGE_gsm-utils is not set\n# CONFIG_PACKAGE_sipgrep is not set\n# CONFIG_PACKAGE_sngrep is not set\n# end of Telephony\n\n#\n# Terminal\n#\n# CONFIG_PACKAGE_agetty is not set\n# CONFIG_PACKAGE_dvtm is not set\n# CONFIG_PACKAGE_minicom is not set\n# CONFIG_PACKAGE_picocom is not set\n# CONFIG_PACKAGE_rtty-mbedtls is not set\n# CONFIG_PACKAGE_rtty-nossl is not set\n# CONFIG_PACKAGE_rtty-openssl is not set\n# CONFIG_PACKAGE_rtty-wolfssl is not set\n# CONFIG_PACKAGE_screen is not set\n# CONFIG_PACKAGE_script-utils is not set\n# CONFIG_PACKAGE_serialconsole is not set\n# CONFIG_PACKAGE_setterm is not set\n# CONFIG_PACKAGE_tio is not set\n# CONFIG_PACKAGE_tmux is not set\nCONFIG_PACKAGE_ttyd=y\n# CONFIG_PACKAGE_wall is not set\n# end of Terminal\n\n#\n# Virtualization\n#\n# end of Virtualization\n\n#\n# Zoneinfo\n#\n# CONFIG_PACKAGE_zoneinfo-africa is not set\n# CONFIG_PACKAGE_zoneinfo-all is not set\n# CONFIG_PACKAGE_zoneinfo-asia is not set\n# CONFIG_PACKAGE_zoneinfo-atlantic is not set\n# CONFIG_PACKAGE_zoneinfo-australia-nz is not set\n# CONFIG_PACKAGE_zoneinfo-core is not set\n# CONFIG_PACKAGE_zoneinfo-europe is not set\n# CONFIG_PACKAGE_zoneinfo-india is not set\n# CONFIG_PACKAGE_zoneinfo-northamerica is not set\n# CONFIG_PACKAGE_zoneinfo-pacific is not set\n# CONFIG_PACKAGE_zoneinfo-poles is not set\n# CONFIG_PACKAGE_zoneinfo-simple is not set\n# CONFIG_PACKAGE_zoneinfo-southamerica is not set\n# end of Zoneinfo\n\n#\n# libimobiledevice\n#\n# CONFIG_PACKAGE_idevicerestore is not set\n# CONFIG_PACKAGE_irecovery is not set\n# CONFIG_PACKAGE_libimobiledevice-utils is not set\n# CONFIG_PACKAGE_libusbmuxd-utils is not set\n# CONFIG_PACKAGE_plistutil is not set\n# CONFIG_PACKAGE_usbmuxd is not set\n# end of libimobiledevice\n\n#\n# libselinux tools\n#\n# CONFIG_PACKAGE_libselinux-avcstat is not set\n# CONFIG_PACKAGE_libselinux-compute_av is not set\n# CONFIG_PACKAGE_libselinux-compute_create is not set\n# CONFIG_PACKAGE_libselinux-compute_member is not set\n# CONFIG_PACKAGE_libselinux-compute_relabel is not set\n# CONFIG_PACKAGE_libselinux-getconlist is not set\n# CONFIG_PACKAGE_libselinux-getdefaultcon is not set\n# CONFIG_PACKAGE_libselinux-getenforce is not set\n# CONFIG_PACKAGE_libselinux-getfilecon is not set\n# CONFIG_PACKAGE_libselinux-getpidcon is not set\n# CONFIG_PACKAGE_libselinux-getsebool is not set\n# CONFIG_PACKAGE_libselinux-getseuser is not set\n# CONFIG_PACKAGE_libselinux-matchpathcon is not set\n# CONFIG_PACKAGE_libselinux-policyvers is not set\n# CONFIG_PACKAGE_libselinux-sefcontext_compile is not set\n# CONFIG_PACKAGE_libselinux-selabel_digest is not set\n# CONFIG_PACKAGE_libselinux-selabel_get_digests_all_partial_matches is not set\n# CONFIG_PACKAGE_libselinux-selabel_lookup is not set\n# CONFIG_PACKAGE_libselinux-selabel_lookup_best_match is not set\n# CONFIG_PACKAGE_libselinux-selabel_partial_match is not set\n# CONFIG_PACKAGE_libselinux-selinux_check_access is not set\n# CONFIG_PACKAGE_libselinux-selinux_check_securetty_context is not set\n# CONFIG_PACKAGE_libselinux-selinuxenabled is not set\n# CONFIG_PACKAGE_libselinux-selinuxexeccon is not set\n# CONFIG_PACKAGE_libselinux-setenforce is not set\n# CONFIG_PACKAGE_libselinux-setfilecon is not set\n# CONFIG_PACKAGE_libselinux-togglesebool is not set\n# CONFIG_PACKAGE_libselinux-validatetrans is not set\n# end of libselinux tools\n\n# CONFIG_PACKAGE_ack is not set\n# CONFIG_PACKAGE_acpid is not set\n# CONFIG_PACKAGE_adb is not set\n# CONFIG_PACKAGE_ap51-flash is not set\n# CONFIG_PACKAGE_apk is not set\n# CONFIG_PACKAGE_at is not set\n# CONFIG_PACKAGE_atheepmgr is not set\n# CONFIG_PACKAGE_audit is not set\n# CONFIG_PACKAGE_audit-utils is not set\n# CONFIG_PACKAGE_augeas is not set\n# CONFIG_PACKAGE_augeas-lenses is not set\n# CONFIG_PACKAGE_augeas-lenses-tests is not set\n# CONFIG_PACKAGE_bandwidthd is not set\n# CONFIG_PACKAGE_bandwidthd-pgsql is not set\n# CONFIG_PACKAGE_bandwidthd-php is not set\n# CONFIG_PACKAGE_bandwidthd-sqlite is not set\n# CONFIG_PACKAGE_banhostlist is not set\n# CONFIG_PACKAGE_bc is not set\n# CONFIG_PACKAGE_bluelog is not set\n# CONFIG_PACKAGE_bluez-daemon is not set\n# CONFIG_PACKAGE_bluez-utils is not set\n# CONFIG_PACKAGE_bluez-utils-extra is not set\n# CONFIG_PACKAGE_bluld is not set\n# CONFIG_PACKAGE_bonniexx is not set\n# CONFIG_PACKAGE_bottlerocket is not set\n# CONFIG_PACKAGE_bsdiff is not set\n# CONFIG_PACKAGE_bspatch is not set\n# CONFIG_PACKAGE_byobu is not set\n# CONFIG_PACKAGE_byobu-utils is not set\n# CONFIG_PACKAGE_cache-domains-mbedtls is not set\n# CONFIG_PACKAGE_cache-domains-openssl is not set\n# CONFIG_PACKAGE_cache-domains-wolfssl is not set\n# CONFIG_PACKAGE_cal is not set\n# CONFIG_PACKAGE_canutils is not set\n# CONFIG_PACKAGE_cgroup-tools is not set\n# CONFIG_PACKAGE_cgroupfs-mount is not set\n# CONFIG_PACKAGE_checkpolicy is not set\n# CONFIG_PACKAGE_checksec is not set\n# CONFIG_PACKAGE_checksec_automator is not set\n# CONFIG_PACKAGE_chkcon is not set\n# CONFIG_PACKAGE_cmdpad is not set\n# CONFIG_PACKAGE_cni is not set\n# CONFIG_PACKAGE_cni-plugins is not set\n# CONFIG_PACKAGE_cni-plugins-nft is not set\n# CONFIG_PACKAGE_coap-client is not set\n# CONFIG_PACKAGE_collectd is not set\n# CONFIG_PACKAGE_conmon is not set\n# CONFIG_PACKAGE_containerd is not set\nCONFIG_PACKAGE_coremark=y\nCONFIG_COREMARK_OPTIMIZE_O3=y\nCONFIG_COREMARK_ENABLE_MULTITHREADING=y\nCONFIG_COREMARK_NUMBER_OF_THREADS=16\nCONFIG_PACKAGE_coreutils=y\n# CONFIG_PACKAGE_coreutils-b2sum is not set\n# CONFIG_PACKAGE_coreutils-base32 is not set\nCONFIG_PACKAGE_coreutils-base64=y\n# CONFIG_PACKAGE_coreutils-basename is not set\n# CONFIG_PACKAGE_coreutils-basenc is not set\n# CONFIG_PACKAGE_coreutils-cat is not set\n# CONFIG_PACKAGE_coreutils-chcon is not set\n# CONFIG_PACKAGE_coreutils-chgrp is not set\n# CONFIG_PACKAGE_coreutils-chmod is not set\n# CONFIG_PACKAGE_coreutils-chown is not set\n# CONFIG_PACKAGE_coreutils-chroot is not set\n# CONFIG_PACKAGE_coreutils-cksum is not set\n# CONFIG_PACKAGE_coreutils-comm is not set\n# CONFIG_PACKAGE_coreutils-cp is not set\n# CONFIG_PACKAGE_coreutils-csplit is not set\n# CONFIG_PACKAGE_coreutils-cut is not set\n# CONFIG_PACKAGE_coreutils-date is not set\n# CONFIG_PACKAGE_coreutils-dd is not set\n# CONFIG_PACKAGE_coreutils-df is not set\n# CONFIG_PACKAGE_coreutils-dir is not set\n# CONFIG_PACKAGE_coreutils-dircolors is not set\n# CONFIG_PACKAGE_coreutils-dirname is not set\n# CONFIG_PACKAGE_coreutils-du is not set\n# CONFIG_PACKAGE_coreutils-echo is not set\n# CONFIG_PACKAGE_coreutils-env is not set\n# CONFIG_PACKAGE_coreutils-expand is not set\n# CONFIG_PACKAGE_coreutils-expr is not set\n# CONFIG_PACKAGE_coreutils-factor is not set\n# CONFIG_PACKAGE_coreutils-false is not set\n# CONFIG_PACKAGE_coreutils-fmt is not set\n# CONFIG_PACKAGE_coreutils-fold is not set\n# CONFIG_PACKAGE_coreutils-groups is not set\n# CONFIG_PACKAGE_coreutils-head is not set\n# CONFIG_PACKAGE_coreutils-hostid is not set\n# CONFIG_PACKAGE_coreutils-id is not set\n# CONFIG_PACKAGE_coreutils-install is not set\n# CONFIG_PACKAGE_coreutils-join is not set\n# CONFIG_PACKAGE_coreutils-kill is not set\n# CONFIG_PACKAGE_coreutils-link is not set\n# CONFIG_PACKAGE_coreutils-ln is not set\n# CONFIG_PACKAGE_coreutils-logname is not set\n# CONFIG_PACKAGE_coreutils-ls is not set\n# CONFIG_PACKAGE_coreutils-md5sum is not set\n# CONFIG_PACKAGE_coreutils-mkdir is not set\n# CONFIG_PACKAGE_coreutils-mkfifo is not set\n# CONFIG_PACKAGE_coreutils-mknod is not set\n# CONFIG_PACKAGE_coreutils-mktemp is not set\n# CONFIG_PACKAGE_coreutils-mv is not set\n# CONFIG_PACKAGE_coreutils-nice is not set\n# CONFIG_PACKAGE_coreutils-nl is not set\nCONFIG_PACKAGE_coreutils-nohup=y\n# CONFIG_PACKAGE_coreutils-nproc is not set\n# CONFIG_PACKAGE_coreutils-numfmt is not set\n# CONFIG_PACKAGE_coreutils-od is not set\n# CONFIG_PACKAGE_coreutils-paste is not set\n# CONFIG_PACKAGE_coreutils-pathchk is not set\n# CONFIG_PACKAGE_coreutils-pinky is not set\n# CONFIG_PACKAGE_coreutils-pr is not set\n# CONFIG_PACKAGE_coreutils-printenv is not set\n# CONFIG_PACKAGE_coreutils-printf is not set\n# CONFIG_PACKAGE_coreutils-ptx is not set\n# CONFIG_PACKAGE_coreutils-pwd is not set\n# CONFIG_PACKAGE_coreutils-readlink is not set\n# CONFIG_PACKAGE_coreutils-realpath is not set\n# CONFIG_PACKAGE_coreutils-rm is not set\n# CONFIG_PACKAGE_coreutils-rmdir is not set\n# CONFIG_PACKAGE_coreutils-runcon is not set\n# CONFIG_PACKAGE_coreutils-seq is not set\n# CONFIG_PACKAGE_coreutils-sha1sum is not set\n# CONFIG_PACKAGE_coreutils-sha224sum is not set\n# CONFIG_PACKAGE_coreutils-sha256sum is not set\n# CONFIG_PACKAGE_coreutils-sha384sum is not set\n# CONFIG_PACKAGE_coreutils-sha512sum is not set\n# CONFIG_PACKAGE_coreutils-shred is not set\n# CONFIG_PACKAGE_coreutils-shuf is not set\n# CONFIG_PACKAGE_coreutils-sleep is not set\n# CONFIG_PACKAGE_coreutils-sort is not set\n# CONFIG_PACKAGE_coreutils-split is not set\n# CONFIG_PACKAGE_coreutils-stat is not set\n# CONFIG_PACKAGE_coreutils-stdbuf is not set\n# CONFIG_PACKAGE_coreutils-stty is not set\n# CONFIG_PACKAGE_coreutils-sum is not set\n# CONFIG_PACKAGE_coreutils-sync is not set\n# CONFIG_PACKAGE_coreutils-tac is not set\n# CONFIG_PACKAGE_coreutils-tail is not set\n# CONFIG_PACKAGE_coreutils-tee is not set\n# CONFIG_PACKAGE_coreutils-test is not set\n# CONFIG_PACKAGE_coreutils-timeout is not set\n# CONFIG_PACKAGE_coreutils-touch is not set\n# CONFIG_PACKAGE_coreutils-tr is not set\n# CONFIG_PACKAGE_coreutils-true is not set\n# CONFIG_PACKAGE_coreutils-truncate is not set\n# CONFIG_PACKAGE_coreutils-tsort is not set\n# CONFIG_PACKAGE_coreutils-tty is not set\n# CONFIG_PACKAGE_coreutils-uname is not set\n# CONFIG_PACKAGE_coreutils-unexpand is not set\n# CONFIG_PACKAGE_coreutils-uniq is not set\n# CONFIG_PACKAGE_coreutils-unlink is not set\n# CONFIG_PACKAGE_coreutils-uptime is not set\n# CONFIG_PACKAGE_coreutils-users is not set\n# CONFIG_PACKAGE_coreutils-vdir is not set\n# CONFIG_PACKAGE_coreutils-wc is not set\n# CONFIG_PACKAGE_coreutils-who is not set\n# CONFIG_PACKAGE_coreutils-whoami is not set\n# CONFIG_PACKAGE_coreutils-yes is not set\n# CONFIG_PACKAGE_crconf is not set\n# CONFIG_PACKAGE_crelay is not set\n# CONFIG_PACKAGE_crun is not set\n# CONFIG_PACKAGE_csstidy is not set\n# CONFIG_PACKAGE_ct-bugcheck is not set\n# CONFIG_PACKAGE_ctop is not set\n# CONFIG_PACKAGE_dbus is not set\n# CONFIG_PACKAGE_dbus-utils is not set\n# CONFIG_PACKAGE_device-observatory is not set\n# CONFIG_PACKAGE_dfu-util is not set\n# CONFIG_PACKAGE_digitemp is not set\n# CONFIG_PACKAGE_digitemp-usb is not set\n# CONFIG_PACKAGE_dmesg is not set\n# CONFIG_PACKAGE_docker is not set\n# CONFIG_PACKAGE_docker-compose is not set\n# CONFIG_PACKAGE_dockerd is not set\n# CONFIG_PACKAGE_dropbearconvert is not set\n# CONFIG_PACKAGE_dtc is not set\n# CONFIG_PACKAGE_dumb-init is not set\n# CONFIG_PACKAGE_dump1090 is not set\n# CONFIG_PACKAGE_ecdsautils is not set\n# CONFIG_PACKAGE_elektra-kdb is not set\n# CONFIG_PACKAGE_evtest is not set\n# CONFIG_PACKAGE_extract is not set\n# CONFIG_PACKAGE_fdt-utils is not set\n# CONFIG_PACKAGE_file is not set\n# CONFIG_PACKAGE_findutils is not set\n# CONFIG_PACKAGE_findutils-find is not set\n# CONFIG_PACKAGE_findutils-locate is not set\n# CONFIG_PACKAGE_findutils-xargs is not set\n# CONFIG_PACKAGE_flashrom is not set\n# CONFIG_PACKAGE_flashrom-pci is not set\n# CONFIG_PACKAGE_flashrom-spi is not set\n# CONFIG_PACKAGE_flashrom-usb is not set\n# CONFIG_PACKAGE_flent-tools is not set\n# CONFIG_PACKAGE_flock is not set\n# CONFIG_PACKAGE_fritz-caldata is not set\n# CONFIG_PACKAGE_fritz-tffs is not set\n# CONFIG_PACKAGE_fritz-tffs-nand is not set\n# CONFIG_PACKAGE_ftdi_eeprom is not set\n# CONFIG_PACKAGE_gammu is not set\n# CONFIG_PACKAGE_gawk is not set\n# CONFIG_PACKAGE_gddrescue is not set\n# CONFIG_PACKAGE_getopt is not set\n# CONFIG_PACKAGE_giflib-utils is not set\n# CONFIG_PACKAGE_gkermit is not set\n# CONFIG_PACKAGE_gnuplot is not set\n# CONFIG_PACKAGE_gpioctl-sysfs is not set\n# CONFIG_PACKAGE_gpiod-tools is not set\n# CONFIG_PACKAGE_gpsd is not set\n# CONFIG_PACKAGE_gpsd-clients is not set\n# CONFIG_PACKAGE_gpsd-utils is not set\n# CONFIG_PACKAGE_grep is not set\n# CONFIG_PACKAGE_hamlib is not set\n# CONFIG_PACKAGE_haserl is not set\n# CONFIG_PACKAGE_hashdeep is not set\n# CONFIG_PACKAGE_haveged is not set\n# CONFIG_PACKAGE_hplip-common is not set\n# CONFIG_PACKAGE_hplip-sane is not set\n# CONFIG_PACKAGE_hub-ctrl is not set\n# CONFIG_PACKAGE_hwclock is not set\n# CONFIG_PACKAGE_hwinfo is not set\n# CONFIG_PACKAGE_hwloc-utils is not set\n# CONFIG_PACKAGE_i2c-tools is not set\n# CONFIG_PACKAGE_iconv is not set\n# CONFIG_PACKAGE_iio-utils is not set\n# CONFIG_PACKAGE_inotifywait is not set\n# CONFIG_PACKAGE_inotifywatch is not set\n# CONFIG_PACKAGE_io is not set\n# CONFIG_PACKAGE_ipfs-http-client-tests is not set\n# CONFIG_PACKAGE_irqbalance is not set\n# CONFIG_PACKAGE_iwcap is not set\nCONFIG_PACKAGE_iwinfo=y\n# CONFIG_PACKAGE_jq is not set\nCONFIG_PACKAGE_jshn=y\n# CONFIG_PACKAGE_kmod is not set\n# CONFIG_PACKAGE_lcd4linux-custom is not set\n# CONFIG_PACKAGE_lcdproc-clients is not set\n# CONFIG_PACKAGE_lcdproc-drivers is not set\n# CONFIG_PACKAGE_lcdproc-server is not set\n# CONFIG_PACKAGE_less is not set\n# CONFIG_PACKAGE_less-wide is not set\nCONFIG_PACKAGE_libjson-script=y\n# CONFIG_PACKAGE_libnetwork is not set\n# CONFIG_PACKAGE_libxml2-utils is not set\n# CONFIG_PACKAGE_lm-sensors is not set\n# CONFIG_PACKAGE_lm-sensors-detect is not set\n# CONFIG_PACKAGE_logger is not set\n# CONFIG_PACKAGE_logrotate is not set\n# CONFIG_PACKAGE_look is not set\n# CONFIG_PACKAGE_losetup is not set\n# CONFIG_PACKAGE_lrzsz is not set\n# CONFIG_PACKAGE_lscpu is not set\nCONFIG_PACKAGE_lsof=y\n# CONFIG_PACKAGE_lxc is not set\nCONFIG_PACKAGE_maccalc=y\n# CONFIG_PACKAGE_macchanger is not set\n# CONFIG_PACKAGE_mandoc is not set\n# CONFIG_PACKAGE_mbedtls-util is not set\n# CONFIG_PACKAGE_mbim-utils is not set\n# CONFIG_PACKAGE_mbtools is not set\n# CONFIG_PACKAGE_mc is not set\n# CONFIG_PACKAGE_mcookie is not set\n# CONFIG_PACKAGE_micrond is not set\n# CONFIG_PACKAGE_mmc-utils is not set\n# CONFIG_PACKAGE_more is not set\n# CONFIG_PACKAGE_moreutils is not set\n# CONFIG_PACKAGE_mosh-client is not set\n# CONFIG_PACKAGE_mosh-server is not set\n# CONFIG_PACKAGE_mount-utils is not set\n# CONFIG_PACKAGE_mpack is not set\n# CONFIG_PACKAGE_mt-st is not set\n# CONFIG_PACKAGE_namei is not set\n# CONFIG_PACKAGE_nand-utils is not set\n# CONFIG_PACKAGE_naywatch is not set\n# CONFIG_PACKAGE_netopeer2-cli is not set\n# CONFIG_PACKAGE_netopeer2-server is not set\n# CONFIG_PACKAGE_netwhere is not set\n# CONFIG_PACKAGE_nnn is not set\n# CONFIG_PACKAGE_nsenter is not set\n# CONFIG_PACKAGE_nss-utils is not set\n# CONFIG_PACKAGE_oath-toolkit is not set\n# CONFIG_PACKAGE_oci-runtime-tool is not set\n# CONFIG_PACKAGE_open-plc-utils is not set\n# CONFIG_PACKAGE_open2300 is not set\n# CONFIG_PACKAGE_openobex is not set\n# CONFIG_PACKAGE_openobex-apps is not set\n# CONFIG_PACKAGE_openocd is not set\n# CONFIG_PACKAGE_opensc-utils is not set\nCONFIG_PACKAGE_openssl-util=y\n# CONFIG_PACKAGE_openzwave is not set\n# CONFIG_PACKAGE_openzwave-config is not set\n# CONFIG_PACKAGE_owipcalc is not set\n# CONFIG_PACKAGE_pciids is not set\n# CONFIG_PACKAGE_pciutils is not set\n# CONFIG_PACKAGE_pcsc-tools is not set\n# CONFIG_PACKAGE_pcscd is not set\n# CONFIG_PACKAGE_podman is not set\n# CONFIG_PACKAGE_podman-selinux is not set\n# CONFIG_PACKAGE_policycoreutils is not set\n# CONFIG_PACKAGE_powertop is not set\n# CONFIG_PACKAGE_pps-tools is not set\n# CONFIG_PACKAGE_prlimit is not set\n# CONFIG_PACKAGE_procps-ng is not set\n# CONFIG_PACKAGE_progress is not set\n# CONFIG_PACKAGE_prometheus is not set\n# CONFIG_PACKAGE_prometheus-node-exporter-lua is not set\n# CONFIG_PACKAGE_prometheus-statsd-exporter is not set\n# CONFIG_PACKAGE_pservice is not set\n# CONFIG_PACKAGE_psmisc is not set\n# CONFIG_PACKAGE_pv is not set\n# CONFIG_PACKAGE_qmi-utils is not set\n# CONFIG_PACKAGE_qrencode is not set\n# CONFIG_PACKAGE_quota is not set\n# CONFIG_PACKAGE_ravpower-mcu is not set\n# CONFIG_PACKAGE_rclone is not set\n# CONFIG_PACKAGE_readsb is not set\n# CONFIG_PACKAGE_relayctl is not set\n# CONFIG_PACKAGE_rename is not set\n# CONFIG_PACKAGE_restic is not set\n# CONFIG_PACKAGE_rng-tools is not set\n# CONFIG_PACKAGE_rtl-ais is not set\n# CONFIG_PACKAGE_rtl-sdr is not set\n# CONFIG_PACKAGE_rtl_433 is not set\n# CONFIG_PACKAGE_runc is not set\n# CONFIG_PACKAGE_sane-backends is not set\n# CONFIG_PACKAGE_sane-daemon is not set\n# CONFIG_PACKAGE_sane-frontends is not set\n# CONFIG_PACKAGE_secilc is not set\n# CONFIG_PACKAGE_sed is not set\n# CONFIG_PACKAGE_selinux-audit2allow is not set\n# CONFIG_PACKAGE_selinux-chcat is not set\n# CONFIG_PACKAGE_selinux-semanage is not set\n# CONFIG_PACKAGE_semodule-utils is not set\n# CONFIG_PACKAGE_serdisplib-tools is not set\n# CONFIG_PACKAGE_setools is not set\n# CONFIG_PACKAGE_setserial is not set\n# CONFIG_PACKAGE_shadow-utils is not set\nCONFIG_PACKAGE_shellsync=y\n# CONFIG_PACKAGE_sipcalc is not set\n# CONFIG_PACKAGE_sispmctl is not set\n# CONFIG_PACKAGE_slide-switch is not set\n# CONFIG_PACKAGE_smartd is not set\n# CONFIG_PACKAGE_smartd-mail is not set\nCONFIG_PACKAGE_smartmontools=y\n# CONFIG_PACKAGE_smartmontools-drivedb is not set\n# CONFIG_PACKAGE_smstools3 is not set\n# CONFIG_PACKAGE_sockread is not set\n# CONFIG_PACKAGE_spi-tools is not set\n# CONFIG_PACKAGE_spidev-test is not set\n# CONFIG_PACKAGE_ssdeep is not set\n# CONFIG_PACKAGE_sshpass is not set\n# CONFIG_PACKAGE_strace is not set\nCONFIG_STRACE_NONE=y\n# CONFIG_STRACE_LIBDW is not set\n# CONFIG_STRACE_LIBUNWIND is not set\n# CONFIG_PACKAGE_stress is not set\n# CONFIG_PACKAGE_stress-ng is not set\n# CONFIG_PACKAGE_sumo is not set\n# CONFIG_PACKAGE_syncthing is not set\n# CONFIG_PACKAGE_sysrepo is not set\n# CONFIG_PACKAGE_sysrepocfg is not set\n# CONFIG_PACKAGE_sysrepoctl is not set\n# CONFIG_PACKAGE_sysstat is not set\n# CONFIG_PACKAGE_tar is not set\n# CONFIG_PACKAGE_taskwarrior is not set\n# CONFIG_PACKAGE_telldus-core is not set\n# CONFIG_PACKAGE_temperusb is not set\n# CONFIG_PACKAGE_tesseract is not set\n# CONFIG_PACKAGE_tini is not set\n# CONFIG_PACKAGE_tracertools is not set\n# CONFIG_PACKAGE_tree is not set\n# CONFIG_PACKAGE_triggerhappy is not set\nCONFIG_PACKAGE_ubi-utils=y\n# CONFIG_PACKAGE_ucode is not set\n# CONFIG_PACKAGE_udns-dnsget is not set\n# CONFIG_PACKAGE_udns-ex-rdns is not set\n# CONFIG_PACKAGE_udns-rblcheck is not set\n# CONFIG_PACKAGE_ugps is not set\n# CONFIG_PACKAGE_uhubctl is not set\n# CONFIG_PACKAGE_uledd is not set\n# CONFIG_PACKAGE_unshare is not set\n# CONFIG_PACKAGE_usb-modeswitch is not set\nCONFIG_PACKAGE_usbids=y\nCONFIG_PACKAGE_usbutils=y\n# CONFIG_PACKAGE_uuidd is not set\n# CONFIG_PACKAGE_uuidgen is not set\n# CONFIG_PACKAGE_uvcdynctrl is not set\n# CONFIG_PACKAGE_v4l-utils is not set\n# CONFIG_PACKAGE_view1090 is not set\n# CONFIG_PACKAGE_viewadsb is not set\n# CONFIG_PACKAGE_watchcat is not set\n# CONFIG_PACKAGE_whereis is not set\n# CONFIG_PACKAGE_which is not set\n# CONFIG_PACKAGE_whiptail is not set\n# CONFIG_PACKAGE_whois is not set\n# CONFIG_PACKAGE_wifitoggle is not set\n# CONFIG_PACKAGE_wipe is not set\n# CONFIG_PACKAGE_xsltproc is not set\n# CONFIG_PACKAGE_xxd is not set\n# CONFIG_PACKAGE_yanglint is not set\n# CONFIG_PACKAGE_yara is not set\n# CONFIG_PACKAGE_ykclient is not set\n# CONFIG_PACKAGE_ykpers is not set\n# CONFIG_PACKAGE_yq is not set\n# end of Utilities\n\n#\n# Xorg\n#\n\n#\n# Font-Utils\n#\n# CONFIG_PACKAGE_fontconfig is not set\n# end of Font-Utils\n# end of Xorg\n\nCONFIG_OVERRIDE_PKGS=\"kcptun\"\n", "meta": {"author": "igithublab", "repo": "MT1300", "sha": "773a03e1dbe89d8826939215ccf09181e2fb5473", "save_path": "github-repos/lean/igithublab-MT1300", "path": "github-repos/lean/igithublab-MT1300/MT1300-773a03e1dbe89d8826939215ccf09181e2fb5473/.config.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.028007518983365006, "lm_q2_score": 0.007011796029942597, "lm_q1q2_score": 0.00019638301041610066}}
{"text": "# Generated by Powerlevel10k configuration wizard on 2021-03-04 at 11:24 CET.\n# Based on romkatv/powerlevel10k/config/p10k-lean.zsh, checksum 9871.\n# Wizard options: nerdfont-complete + powerline, small icons, unicode, lean, 24h time,\n# 2 lines, disconnected, left frame, lightest-ornaments, sparse, many icons, fluent,\n# transient_prompt, instant_prompt=verbose.\n# Type `p10k configure` to generate another config.\n#\n# Config for Powerlevel10k with lean prompt style. Type `p10k configure` to generate\n# your own config based on it.\n#\n# Tip: Looking for a nice color? Here's a one-liner to print colormap.\n#\n#   for i in {0..255}; do print -Pn \"%K{$i}  %k%F{$i}${(l:3::0:)i}%f \" ${${(M)$((i%6)):#3}:+$'\\n'}; done\n\n# Temporarily change options.\n'builtin' 'local' '-a' 'p10k_config_opts'\n[[ ! -o 'aliases'         ]] || p10k_config_opts+=('aliases')\n[[ ! -o 'sh_glob'         ]] || p10k_config_opts+=('sh_glob')\n[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand')\n'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand'\n\n() {\n  emulate -L zsh -o extended_glob\n\n  # Unset all configuration options. This allows you to apply configuration changes without\n  # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`.\n  unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR'\n\n  # Zsh >= 5.1 is required.\n  autoload -Uz is-at-least && is-at-least 5.1 || return\n\n  # The list of segments shown on the left. Fill it with the most important segments.\n  typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(\n    # =========================[ Line #1 ]=========================\n    os_icon                 # os identifier\n    dir                     # current directory\n    vcs                     # git status\n    # =========================[ Line #2 ]=========================\n    newline                 # \\n\n    prompt_char             # prompt symbol\n  )\n\n  # The list of segments shown on the right. Fill it with less important segments.\n  # Right prompt on the last prompt line (where you are typing your commands) gets\n  # automatically hidden when the input line reaches it. Right prompt above the\n  # last prompt line gets hidden if it would overlap with left prompt.\n  typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(\n    # =========================[ Line #1 ]=========================\n    status                  # exit code of the last command\n    command_execution_time  # duration of the last command\n    background_jobs         # presence of background jobs\n    direnv                  # direnv status (https://direnv.net/)\n    asdf                    # asdf version manager (https://github.com/asdf-vm/asdf)\n    virtualenv              # python virtual environment (https://docs.python.org/3/library/venv.html)\n    anaconda                # conda environment (https://conda.io/)\n    pyenv                   # python environment (https://github.com/pyenv/pyenv)\n    goenv                   # go environment (https://github.com/syndbg/goenv)\n    nodenv                  # node.js version from nodenv (https://github.com/nodenv/nodenv)\n    nvm                     # node.js version from nvm (https://github.com/nvm-sh/nvm)\n    nodeenv                 # node.js environment (https://github.com/ekalinin/nodeenv)\n    # node_version          # node.js version\n    # go_version            # go version (https://golang.org)\n    # rust_version          # rustc version (https://www.rust-lang.org)\n    # dotnet_version        # .NET version (https://dotnet.microsoft.com)\n    # php_version           # php version (https://www.php.net/)\n    # laravel_version       # laravel php framework version (https://laravel.com/)\n    # java_version          # java version (https://www.java.com/)\n    # package               # name@version from package.json (https://docs.npmjs.com/files/package.json)\n    rbenv                   # ruby version from rbenv (https://github.com/rbenv/rbenv)\n    rvm                     # ruby version from rvm (https://rvm.io)\n    fvm                     # flutter version management (https://github.com/leoafarias/fvm)\n    luaenv                  # lua version from luaenv (https://github.com/cehoffman/luaenv)\n    jenv                    # java version from jenv (https://github.com/jenv/jenv)\n    plenv                   # perl version from plenv (https://github.com/tokuhirom/plenv)\n    phpenv                  # php version from phpenv (https://github.com/phpenv/phpenv)\n    scalaenv                # scala version from scalaenv (https://github.com/scalaenv/scalaenv)\n    haskell_stack           # haskell version from stack (https://haskellstack.org/)\n    kubecontext             # current kubernetes context (https://kubernetes.io/)\n    terraform               # terraform workspace (https://www.terraform.io)\n    aws                     # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html)\n    aws_eb_env              # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/)\n    azure                   # azure account name (https://docs.microsoft.com/en-us/cli/azure)\n    gcloud                  # google cloud cli account and project (https://cloud.google.com/)\n    google_app_cred         # google application credentials (https://cloud.google.com/docs/authentication/production)\n    context                 # user@hostname\n    nordvpn                 # nordvpn connection status, linux only (https://nordvpn.com/)\n    ranger                  # ranger shell (https://github.com/ranger/ranger)\n    nnn                     # nnn shell (https://github.com/jarun/nnn)\n    vim_shell               # vim shell indicator (:sh)\n    midnight_commander      # midnight commander shell (https://midnight-commander.org/)\n    nix_shell               # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html)\n    # vpn_ip                # virtual private network indicator\n    # load                  # CPU load\n    # disk_usage            # disk usage\n    # ram                   # free RAM\n    # swap                  # used swap\n    todo                    # todo items (https://github.com/todotxt/todo.txt-cli)\n    timewarrior             # timewarrior tracking status (https://timewarrior.net/)\n    taskwarrior             # taskwarrior task count (https://taskwarrior.org/)\n    time                    # current time\n    # =========================[ Line #2 ]=========================\n    newline\n    # ip                    # ip address and bandwidth usage for a specified network interface\n    # public_ip             # public IP address\n    # proxy                 # system-wide http/https/ftp proxy\n    # battery               # internal battery\n    # wifi                  # wifi speed\n    # example               # example user-defined segment (see prompt_example function below)\n  )\n\n  # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you.\n  typeset -g POWERLEVEL9K_MODE=nerdfont-complete\n  # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid\n  # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added.\n  typeset -g POWERLEVEL9K_ICON_PADDING=none\n\n  # Basic style options that define the overall look of your prompt. You probably don't want to\n  # change them.\n  typeset -g POWERLEVEL9K_BACKGROUND=                            # transparent background\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE=  # no surrounding whitespace\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' '  # separate segments with a space\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR=        # no end-of-line symbol\n\n  # When set to true, icons appear before content on both sides of the prompt. When set\n  # to false, icons go after content. If empty or not set, icons go before content in the left\n  # prompt and after content in the right prompt.\n  #\n  # You can also override it for a specific segment:\n  #\n  #   POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false\n  #\n  # Or for a specific segment in specific state:\n  #\n  #   POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false\n  typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT=true\n\n  # Add an empty line before each prompt.\n  typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true\n\n  # Connect left prompt lines with these symbols.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX='%244F\u256d\u2500'\n  typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX='%244F\u251c\u2500'\n  typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX='%244F\u2570\u2500'\n  # Connect right prompt lines with these symbols.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX=\n\n  # The left end of left prompt.\n  typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' '\n  # The right end of right prompt.\n  typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL=\n\n  # Ruler, a.k.a. the horizontal line before each prompt. If you set it to true, you'll\n  # probably want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false above and\n  # POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' below.\n  typeset -g POWERLEVEL9K_SHOW_RULER=false\n  typeset -g POWERLEVEL9K_RULER_CHAR='\u2500'        # reasonable alternative: '\u00b7'\n  typeset -g POWERLEVEL9K_RULER_FOREGROUND=244\n\n  # Filler between left and right prompt on the first prompt line. You can set it to '\u00b7' or '\u2500'\n  # to make it easier to see the alignment between left and right prompt and to separate prompt\n  # from command output. It serves the same purpose as ruler (see above) without increasing\n  # the number of prompt lines. You'll probably want to set POWERLEVEL9K_SHOW_RULER=false\n  # if using this. You might also like POWERLEVEL9K_PROMPT_ADD_NEWLINE=false for more compact\n  # prompt.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' '\n  if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then\n    # The color of the filler.\n    typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=244\n    # Add a space between the end of left prompt and the filler.\n    typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=' '\n    # Add a space between the filler and the start of right prompt.\n    typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' '\n    # Start filler from the edge of the screen if there are no left segments on the first line.\n    typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}'\n    # End filler on the edge of the screen if there are no right segments on the first line.\n    typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}'\n  fi\n\n  #################################[ os_icon: os identifier ]##################################\n  # OS identifier color.\n  typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='\u2b50'\n\n  ################################[ prompt_char: prompt symbol ]################################\n  # Green prompt symbol if the last command succeeded.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76\n  # Red prompt symbol if the last command failed.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196\n  # Default prompt symbol.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='\u276f'\n  # Prompt symbol in command vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='\u276e'\n  # Prompt symbol in visual vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V'\n  # Prompt symbol in overwrite vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='\u25b6'\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true\n  # No line terminator if prompt_char is the last segment.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=''\n  # No line introducer if prompt_char is the first segment.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=\n\n  ##################################[ dir: current directory ]##################################\n  # Default current directory color.\n  typeset -g POWERLEVEL9K_DIR_FOREGROUND=31\n  # If directory is too long, shorten some of its segments to the shortest possible unique\n  # prefix. The shortened directory can be tab-completed to the original.\n  typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique\n  # Replace removed segment suffixes with this symbol.\n  typeset -g POWERLEVEL9K_SHORTEN_DELIMITER=\n  # Color of the shortened directory segments.\n  typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=103\n  # Color of the anchor directory segments. Anchor segments are never shortened. The first\n  # segment is always an anchor.\n  typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=39\n  # Display anchor directory segments in bold.\n  typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true\n  # Don't shorten directories that contain any of these files. They are anchors.\n  local anchor_files=(\n    .bzr\n    .citc\n    .git\n    .hg\n    .node-version\n    .python-version\n    .go-version\n    .ruby-version\n    .lua-version\n    .java-version\n    .perl-version\n    .php-version\n    .tool-version\n    .shorten_folder_marker\n    .svn\n    .terraform\n    CVS\n    Cargo.toml\n    composer.json\n    go.mod\n    package.json\n    stack.yaml\n  )\n  typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER=\"(${(j:|:)anchor_files})\"\n  # If set to \"first\" (\"last\"), remove everything before the first (last) subdirectory that contains\n  # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is\n  # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first)\n  # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers\n  # and other directories don't.\n  #\n  # Optionally, \"first\" and \"last\" can be followed by \":<offset>\" where <offset> is an integer.\n  # This moves the truncation point to the right (positive offset) or to the left (negative offset)\n  # relative to the marker. Plain \"first\" and \"last\" are equivalent to \"first:0\" and \"last:0\"\n  # respectively.\n  typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false\n  # Don't shorten this many last directory segments. They are anchors.\n  typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1\n  # Shorten directory if it's longer than this even if there is space for it. The value can\n  # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty,\n  # directory will be shortened only when prompt doesn't fit or when other parameters demand it\n  # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below).\n  # If set to `0`, directory will always be shortened to its minimum length.\n  typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80\n  # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this\n  # many columns for typing commands.\n  typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40\n  # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least\n  # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands.\n  typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50\n  # If set to true, embed a hyperlink into the directory. Useful for quickly\n  # opening a directory in the file manager simply by clicking the link.\n  # Can also be handy when the directory is shortened, as it allows you to see\n  # the full directory that was used in previous commands.\n  typeset -g POWERLEVEL9K_DIR_HYPERLINK=false\n\n  # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON\n  # and POWERLEVEL9K_DIR_CLASSES below.\n  typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3\n\n  # The default icon shown next to non-writable and non-existent directories when\n  # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3.\n  # typeset -g POWERLEVEL9K_LOCK_ICON='\u2b50'\n\n  # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different\n  # directories. It must be an array with 3 * N elements. Each triplet consists of:\n  #\n  #   1. A pattern against which the current directory ($PWD) is matched. Matching is done with\n  #      extended_glob option enabled.\n  #   2. Directory class for the purpose of styling.\n  #   3. An empty string.\n  #\n  # Triplets are tried in order. The first triplet whose pattern matches $PWD wins.\n  #\n  # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories\n  # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_DIR_CLASSES=(\n  #     '~/work(|/*)'  WORK     ''\n  #     '~(|/*)'       HOME     ''\n  #     '*'            DEFAULT  '')\n  #\n  # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one\n  # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or\n  # WORK_NON_EXISTENT.\n  #\n  # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an\n  # option to define custom colors and icons for different directory classes.\n  #\n  #   # Styling for WORK.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=39\n  #\n  #   # Styling for WORK_NOT_WRITABLE.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=39\n  #\n  #   # Styling for WORK_NON_EXISTENT.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=39\n  #\n  # If a styling parameter isn't explicitly defined for some class, it falls back to the classless\n  # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls\n  # back to POWERLEVEL9K_DIR_FOREGROUND.\n  #\n  # typeset -g POWERLEVEL9K_DIR_CLASSES=()\n\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_DIR_PREFIX='%fin '\n\n  #####################################[ vcs: git status ]######################################\n  # Branch icon. Set this parameter to '\\uF126 ' for the popular Powerline branch icon.\n  typeset -g POWERLEVEL9K_VCS_BRANCH_ICON='\\uF126 '\n\n  # Untracked files icon. It's really a question mark, your font isn't broken.\n  # Change the value of this parameter to show a different icon.\n  typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?'\n\n  # Formatter for Git status.\n  #\n  # Example output: master \u21e342\u21e142 *42 merge ~42 +42 !42 ?42.\n  #\n  # You can edit the function to customize how Git status looks.\n  #\n  # VCS_STATUS_* parameters are set by gitstatus plugin. See reference:\n  # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh.\n  function my_git_formatter() {\n    emulate -L zsh\n\n    if [[ -n $P9K_CONTENT ]]; then\n      # If P9K_CONTENT is not empty, use it. It's either \"loading\" or from vcs_info (not from\n      # gitstatus plugin). VCS_STATUS_* parameters are not available in this case.\n      typeset -g my_git_format=$P9K_CONTENT\n      return\n    fi\n\n    if (( $1 )); then\n      # Styling for up-to-date Git status.\n      local       meta='%f'     # default foreground\n      local      clean='%76F'   # green foreground\n      local   modified='%178F'  # yellow foreground\n      local  untracked='%39F'   # blue foreground\n      local conflicted='%196F'  # red foreground\n    else\n      # Styling for incomplete and stale Git status.\n      local       meta='%244F'  # grey foreground\n      local      clean='%244F'  # grey foreground\n      local   modified='%244F'  # grey foreground\n      local  untracked='%244F'  # grey foreground\n      local conflicted='%244F'  # grey foreground\n    fi\n\n    local res\n\n    if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then\n      local branch=${(V)VCS_STATUS_LOCAL_BRANCH}\n      # If local branch name is at most 32 characters long, show it in full.\n      # Otherwise show the first 12 \u2026 the last 12.\n      # Tip: To always show local branch name in full without truncation, delete the next line.\n      (( $#branch > 32 )) && branch[13,-13]=\"\u2026\"  # <-- this line\n      res+=\"${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\\%/%%}\"\n    fi\n\n    if [[ -n $VCS_STATUS_TAG\n          # Show tag only if not on a branch.\n          # Tip: To always show tag, delete the next line.\n          && -z $VCS_STATUS_LOCAL_BRANCH  # <-- this line\n        ]]; then\n      local tag=${(V)VCS_STATUS_TAG}\n      # If tag name is at most 32 characters long, show it in full.\n      # Otherwise show the first 12 \u2026 the last 12.\n      # Tip: To always show tag name in full without truncation, delete the next line.\n      (( $#tag > 32 )) && tag[13,-13]=\"\u2026\"  # <-- this line\n      res+=\"${meta}#${clean}${tag//\\%/%%}\"\n    fi\n\n    # Display the current Git commit if there is no branch and no tag.\n    # Tip: To always display the current Git commit, delete the next line.\n    [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_LOCAL_BRANCH ]] &&  # <-- this line\n      res+=\"${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}\"\n\n    # Show tracking branch name if it differs from local branch.\n    if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then\n      res+=\"${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\\%/%%}\"\n    fi\n\n    # \u21e342 if behind the remote.\n    (( VCS_STATUS_COMMITS_BEHIND )) && res+=\" ${clean}\u21e3${VCS_STATUS_COMMITS_BEHIND}\"\n    # \u21e142 if ahead of the remote; no leading space if also behind the remote: \u21e342\u21e142.\n    (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=\" \"\n    (( VCS_STATUS_COMMITS_AHEAD  )) && res+=\"${clean}\u21e1${VCS_STATUS_COMMITS_AHEAD}\"\n    # \u21e042 if behind the push remote.\n    (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=\" ${clean}\u21e0${VCS_STATUS_PUSH_COMMITS_BEHIND}\"\n    (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=\" \"\n    # \u21e242 if ahead of the push remote; no leading space if also behind: \u21e042\u21e242.\n    (( VCS_STATUS_PUSH_COMMITS_AHEAD  )) && res+=\"${clean}\u21e2${VCS_STATUS_PUSH_COMMITS_AHEAD}\"\n    # *42 if have stashes.\n    (( VCS_STATUS_STASHES        )) && res+=\" ${clean}*${VCS_STATUS_STASHES}\"\n    # 'merge' if the repo is in an unusual state.\n    [[ -n $VCS_STATUS_ACTION     ]] && res+=\" ${conflicted}${VCS_STATUS_ACTION}\"\n    # ~42 if have merge conflicts.\n    (( VCS_STATUS_NUM_CONFLICTED )) && res+=\" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}\"\n    # +42 if have staged changes.\n    (( VCS_STATUS_NUM_STAGED     )) && res+=\" ${modified}+${VCS_STATUS_NUM_STAGED}\"\n    # !42 if have unstaged changes.\n    (( VCS_STATUS_NUM_UNSTAGED   )) && res+=\" ${modified}!${VCS_STATUS_NUM_UNSTAGED}\"\n    # ?42 if have untracked files. It's really a question mark, your font isn't broken.\n    # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon.\n    # Remove the next line if you don't want to see untracked files at all.\n    (( VCS_STATUS_NUM_UNTRACKED  )) && res+=\" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}\"\n    # \"\u2500\" if the number of unstaged files is unknown. This can happen due to\n    # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower\n    # than the number of files in the Git index, or due to bash.showDirtyState being set to false\n    # in the repository config. The number of staged and untracked files may also be unknown\n    # in this case.\n    (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=\" ${modified}\u2500\"\n\n    typeset -g my_git_format=$res\n  }\n  functions -M my_git_formatter 2>/dev/null\n\n  # Don't count the number of unstaged, untracked and conflicted files in Git repositories with\n  # more than this many files in the index. Negative value means infinity.\n  #\n  # If you are working in Git repositories with tens of millions of files and seeing performance\n  # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output\n  # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's\n  # config: `git config bash.showDirtyState false`.\n  typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1\n\n  # Don't show Git status in prompt for repositories whose workdir matches this pattern.\n  # For example, if set to '~', the Git repository at $HOME/.git will be ignored.\n  # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'.\n  typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~'\n\n  # Disable the default Git status formatting.\n  typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true\n  # Install our own Git status formatter.\n  typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}'\n  typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}'\n  # Enable counters for staged, unstaged, etc.\n  typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1\n\n  # Icon color.\n  typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=76\n  typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR=244\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  typeset -g POWERLEVEL9K_VCS_PREFIX='%fon '\n\n  # Show status of repositories of these types. You can add svn and/or hg if you are\n  # using them. If you do, your prompt may become slow even when your current directory\n  # isn't in an svn or hg reposotiry.\n  typeset -g POWERLEVEL9K_VCS_BACKENDS=(git)\n\n  # These settings are used for repositories other than Git or when gitstatusd fails and\n  # Powerlevel10k has to fall back to using vcs_info.\n  typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=76\n  typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=76\n  typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=178\n\n  ##########################[ status: exit code of the last command ]###########################\n  # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and\n  # style them independently from the regular OK and ERROR state.\n  typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true\n\n  # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as\n  # it will signify success by turning green.\n  typeset -g POWERLEVEL9K_STATUS_OK=false\n  typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=70\n  typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='\u2714'\n\n  # Status when some part of a pipe command fails but the overall exit status is zero. It may look\n  # like this: 1|0.\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=70\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='\u2714'\n\n  # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as\n  # it will signify error by turning red.\n  typeset -g POWERLEVEL9K_STATUS_ERROR=false\n  typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=160\n  typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  # Status when the last command was terminated by a signal.\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=160\n  # Use terse signal names: \"INT\" instead of \"SIGINT(2)\".\n  typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  # Status when some part of a pipe command fails and the overall exit status is also non-zero.\n  # It may look like this: 1|0.\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=160\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  ###################[ command_execution_time: duration of the last command ]###################\n  # Show duration of the last command if takes at least this many seconds.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3\n  # Show this many fractional digits. Zero means round to seconds.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0\n  # Execution time color.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=101\n  # Duration format: 1d 2h 3m 4s.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%ftook '\n\n  #######################[ background_jobs: presence of background jobs ]#######################\n  # Don't show the number of background jobs.\n  typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false\n  # Background jobs color.\n  typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ direnv: direnv status (https://direnv.net/) ]########################\n  # Direnv color.\n  typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]###############\n  # Default asdf color. Only used to display tools for which there is no color override (see below).\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND.\n  typeset -g POWERLEVEL9K_ASDF_FOREGROUND=66\n\n  # There are four parameters that can be used to hide asdf tools. Each parameter describes\n  # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at\n  # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to\n  # hide a tool, it gets shown.\n  #\n  # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and\n  # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands:\n  #\n  #   asdf local  python 3.8.1\n  #   asdf global python 3.8.1\n  #\n  # After running both commands the current python version is 3.8.1 and its source is \"local\" as\n  # it takes precedence over \"global\". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false,\n  # it'll hide python version in this case because 3.8.1 is the same as the global version.\n  # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't\n  # contain \"local\".\n\n  # Hide tool versions that don't come from one of these sources.\n  #\n  # Available sources:\n  #\n  # - shell   `asdf current` says \"set by ASDF_${TOOL}_VERSION environment variable\"\n  # - local   `asdf current` says \"set by /some/not/home/directory/file\"\n  # - global  `asdf current` says \"set by /home/username/file\"\n  #\n  # Note: If this parameter is set to (shell local global), it won't hide tools.\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES.\n  typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global)\n\n  # If set to false, hide tool versions that are the same as global.\n  #\n  # Note: The name of this parameter doesn't reflect its meaning at all.\n  # Note: If this parameter is set to true, it won't hide tools.\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW.\n  typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false\n\n  # If set to false, hide tool versions that are equal to \"system\".\n  #\n  # Note: If this parameter is set to true, it won't hide tools.\n  # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM.\n  typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true\n\n  # If set to non-empty value, hide tools unless there is a file matching the specified file pattern\n  # in the current directory, or its parent directory, or its grandparent directory, and so on.\n  #\n  # Note: If this parameter is set to empty value, it won't hide tools.\n  # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments.\n  # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB.\n  #\n  # Example: Hide nodejs version when there is no package.json and no *.js files in the current\n  # directory, in `..`, in `../..` and so on.\n  #\n  #   typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json'\n  typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB=\n\n  # Ruby version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=168\n  # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Python version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Go version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Node.js version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=70\n  # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Rust version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # .NET Core version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=134\n  # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_DOTNET_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Flutter version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=38\n  # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Lua version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Java version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Perl version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=67\n  # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Erlang version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=125\n  # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Elixir version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=129\n  # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Postgres version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=31\n  # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # PHP version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=99\n  # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Haskell version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=172\n  # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Julia version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=70\n  # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]###########\n  # NordVPN connection indicator color.\n  typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=39\n  # Hide NordVPN connection indicator when not connected.\n  typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION=\n  typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]##################\n  # Ranger shell color.\n  typeset -g POWERLEVEL9K_RANGER_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]#######################\n  # Nnn shell color.\n  typeset -g POWERLEVEL9K_NNN_FOREGROUND=72\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########################[ vim_shell: vim shell indicator (:sh) ]###########################\n  # Vim shell indicator color.\n  typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=34\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]######\n  # Midnight Commander shell color.\n  typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]##\n  # Nix shell color.\n  typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=74\n\n  # Tip: If you want to see just the icon without \"pure\" and \"impure\", uncomment the next line.\n  # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################################[ disk_usage: disk usage ]##################################\n  # Colors for different levels of disk usage.\n  typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=35\n  typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=220\n  typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=160\n  # Thresholds for different levels of disk usage (percentage points).\n  typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90\n  typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95\n  # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent.\n  typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################################[ ram: free RAM ]#######################################\n  # RAM color.\n  typeset -g POWERLEVEL9K_RAM_FOREGROUND=66\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################################[ swap: used swap ]######################################\n  # Swap color.\n  typeset -g POWERLEVEL9K_SWAP_FOREGROUND=96\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################################[ load: CPU load ]######################################\n  # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15.\n  typeset -g POWERLEVEL9K_LOAD_WHICH=5\n  # Load color when load is under 50%.\n  typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=66\n  # Load color when load is between 50% and 70%.\n  typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=178\n  # Load color when load is over 70%.\n  typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=166\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################\n  # Todo color.\n  typeset -g POWERLEVEL9K_TODO_FOREGROUND=110\n  # Hide todo when the total number of tasks is zero.\n  typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true\n  # Hide todo when the number of tasks after filtering is zero.\n  typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false\n\n  # Todo format. The following parameters are available within the expansion.\n  #\n  # - P9K_TODO_TOTAL_TASK_COUNT     The total number of tasks.\n  # - P9K_TODO_FILTERED_TASK_COUNT  The number of tasks after filtering.\n  #\n  # These variables correspond to the last line of the output of `todo.sh -p ls`:\n  #\n  #   TODO: 24 of 42 tasks shown\n  #\n  # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT.\n  #\n  # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############\n  # Timewarrior color.\n  typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=110\n  # If the tracked task is longer than 24 characters, truncate and append \"\u2026\".\n  # Tip: To always display tasks without truncation, delete the following parameter.\n  # Tip: To hide task names and display just the icon when time tracking is enabled, set the\n  # value of the following parameter to \"\".\n  typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+\u2026}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]##############\n  # Taskwarrior color.\n  typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=74\n\n  # Taskwarrior segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_TASKWARRIOR_PENDING_COUNT   The number of pending tasks: `task +PENDING count`.\n  # - P9K_TASKWARRIOR_OVERDUE_COUNT   The number of overdue tasks: `task +OVERDUE count`.\n  #\n  # Zero values are represented as empty parameters.\n  #\n  # The default format:\n  #\n  #   '${P9K_TASKWARRIOR_OVERDUE_COUNT:+\"!$P9K_TASKWARRIOR_OVERDUE_COUNT/\"}$P9K_TASKWARRIOR_PENDING_COUNT'\n  #\n  # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################################[ context: user@hostname ]##################################\n  # Context color when running with privileges.\n  typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=178\n  # Context color in SSH without privileges.\n  typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=180\n  # Default context color (no privileges, no SSH).\n  typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=180\n\n  # Context format when running with privileges: bold user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m'\n  # Context format when in SSH without privileges: user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m'\n  # Default context format (no privileges, no SSH): user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m'\n\n  # Don't show context unless running with privileges or in SSH.\n  # Tip: Remove the next line to always show context.\n  typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%fwith '\n\n  ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]###\n  # Python virtual environment color.\n  typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=37\n  # Don't show Python version next to the virtual environment name.\n  typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false\n  # If set to \"false\", won't show virtualenv if pyenv is already shown.\n  # If set to \"if-different\", won't show virtualenv if it's the same as pyenv.\n  typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false\n  # Separate environment name from Python version only with a space.\n  typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################[ anaconda: conda environment (https://conda.io/) ]######################\n  # Anaconda environment color.\n  typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=37\n\n  # Anaconda segment format. The following parameters are available within the expansion.\n  #\n  # - CONDA_PREFIX                 Absolute path to the active Anaconda/Miniconda environment.\n  # - CONDA_DEFAULT_ENV            Name of the active Anaconda/Miniconda environment.\n  # - CONDA_PROMPT_MODIFIER        Configurable prompt modifier (see below).\n  # - P9K_ANACONDA_PYTHON_VERSION  Current python version (python --version).\n  #\n  # CONDA_PROMPT_MODIFIER can be configured with the following command:\n  #\n  #   conda config --set env_prompt '({default_env}) '\n  #\n  # The last argument is a Python format string that can use the following variables:\n  #\n  # - prefix       The same as CONDA_PREFIX.\n  # - default_env  The same as CONDA_DEFAULT_ENV.\n  # - name         The last segment of CONDA_PREFIX.\n  # - stacked_env  Comma-separated list of names in the environment stack. The first element is\n  #                always the same as default_env.\n  #\n  # Note: '({default_env}) ' is the default value of env_prompt.\n  #\n  # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER\n  # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former\n  # is empty.\n  typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\\(}% }%\\)}:-${CONDA_PREFIX:t}}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################\n  # Pyenv color.\n  typeset -g POWERLEVEL9K_PYENV_FOREGROUND=37\n  # Hide python version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global)\n  # If set to false, hide python version if it's the same as global:\n  # $(pyenv version-name) == $(pyenv global).\n  typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide python version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true\n\n  # Pyenv segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_CONTENT                Current pyenv environment (pyenv version-name).\n  # - P9K_PYENV_PYTHON_VERSION   Current python version (python --version).\n  #\n  # The default format has the following logic:\n  #\n  # 1. Display \"$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION\" if $P9K_PYENV_PYTHON_VERSION is not\n  #   empty and unequal to $P9K_CONTENT.\n  # 2. Otherwise display just \"$P9K_CONTENT\".\n  typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_PYENV_PYTHON_VERSION:#$P9K_CONTENT}:+ $P9K_PYENV_PYTHON_VERSION}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################\n  # Goenv color.\n  typeset -g POWERLEVEL9K_GOENV_FOREGROUND=37\n  # Hide go version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global)\n  # If set to false, hide go version if it's the same as global:\n  # $(goenv version-name) == $(goenv global).\n  typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide go version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]##########\n  # Nodenv color.\n  typeset -g POWERLEVEL9K_NODENV_FOREGROUND=70\n  # Hide node version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global)\n  # If set to false, hide node version if it's the same as global:\n  # $(nodenv version-name) == $(nodenv global).\n  typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide node version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]###############\n  # Nvm color.\n  typeset -g POWERLEVEL9K_NVM_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############\n  # Nodeenv color.\n  typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=70\n  # Don't show Node version next to the environment name.\n  typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false\n  # Separate environment name from Node version only with a space.\n  typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############################[ node_version: node.js version ]###############################\n  # Node version color.\n  typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=70\n  # Show node version only when in a directory tree containing package.json.\n  typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ go_version: go version (https://golang.org) ]########################\n  # Go version color.\n  typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=37\n  # Show go version only when in a go project subdirectory.\n  typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #################[ rust_version: rustc version (https://www.rust-lang.org) ]##################\n  # Rust version color.\n  typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=37\n  # Show rust version only when in a rust project subdirectory.\n  typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################\n  # .NET version color.\n  typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=134\n  # Show .NET version only when in a .NET project subdirectory.\n  typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################[ php_version: php version (https://www.php.net/) ]######################\n  # PHP version color.\n  typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=99\n  # Show PHP version only when in a PHP project subdirectory.\n  typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]###########\n  # Laravel version color.\n  typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=161\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ####################[ java_version: java version (https://www.java.com/) ]####################\n  # Java version color.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=32\n  # Show java version only when in a java project subdirectory.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true\n  # Show brief version.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]####\n  # Package color.\n  typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=117\n  # Package format. The following parameters are available within the expansion.\n  #\n  # - P9K_PACKAGE_NAME     The value of `name` field in package.json.\n  # - P9K_PACKAGE_VERSION  The value of `version` field in package.json.\n  #\n  # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\\%/%%}@${P9K_PACKAGE_VERSION//\\%/%%}'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]##############\n  # Rbenv color.\n  typeset -g POWERLEVEL9K_RBENV_FOREGROUND=168\n  # Hide ruby version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global)\n  # If set to false, hide ruby version if it's the same as global:\n  # $(rbenv version-name) == $(rbenv global).\n  typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide ruby version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ rvm: ruby version from rvm (https://rvm.io) ]########################\n  # Rvm color.\n  typeset -g POWERLEVEL9K_RVM_FOREGROUND=168\n  # Don't show @gemset at the end.\n  typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false\n  # Don't show ruby- at the front.\n  typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############\n  # Fvm color.\n  typeset -g POWERLEVEL9K_FVM_FOREGROUND=38\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]###########\n  # Lua color.\n  typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=32\n  # Hide lua version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global)\n  # If set to false, hide lua version if it's the same as global:\n  # $(luaenv version-name) == $(luaenv global).\n  typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide lua version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################\n  # Java color.\n  typeset -g POWERLEVEL9K_JENV_FOREGROUND=32\n  # Hide java version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global)\n  # If set to false, hide java version if it's the same as global:\n  # $(jenv version-name) == $(jenv global).\n  typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide java version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############\n  # Perl color.\n  typeset -g POWERLEVEL9K_PLENV_FOREGROUND=67\n  # Hide perl version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global)\n  # If set to false, hide perl version if it's the same as global:\n  # $(plenv version-name) == $(plenv global).\n  typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide perl version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############\n  # PHP color.\n  typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=99\n  # Hide php version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global)\n  # If set to false, hide php version if it's the same as global:\n  # $(phpenv version-name) == $(phpenv global).\n  typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide php version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]#######\n  # Scala color.\n  typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=160\n  # Hide scala version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global)\n  # If set to false, hide scala version if it's the same as global:\n  # $(scalaenv version-name) == $(scalaenv global).\n  typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide scala version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]###########\n  # Haskell color.\n  typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=172\n  # Hide haskell version if it doesn't come from one of these sources.\n  #\n  #   shell:  version is set by STACK_YAML\n  #   local:  version is set by stack.yaml up the directory tree\n  #   global: version is set by the implicit global project (~/.stack/global-project/stack.yaml)\n  typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local)\n  # If set to false, hide haskell version if it's the same as in the implicit global project.\n  typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]#############\n  # Show kubecontext only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show kubecontext.\n  typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|fluxctl|stern'\n\n  # Kubernetes context classes for the purpose of using different colors, icons and expansions with\n  # different contexts.\n  #\n  # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current kubernetes context gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       DEFAULT)\n  #\n  # If your current kubernetes context is \"deathray-testing/default\", its class is TEST\n  # because \"deathray-testing/default\" doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'       DEFAULT)\n  typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=134\n  # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext\n  # segment. Parameter expansions are very flexible and fast, too. See reference:\n  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion.\n  #\n  # Within the expansion the following parameters are always available:\n  #\n  # - P9K_CONTENT                The content that would've been displayed if there was no content\n  #                              expansion defined.\n  # - P9K_KUBECONTEXT_NAME       The current context's name. Corresponds to column NAME in the\n  #                              output of `kubectl config get-contexts`.\n  # - P9K_KUBECONTEXT_CLUSTER    The current context's cluster. Corresponds to column CLUSTER in the\n  #                              output of `kubectl config get-contexts`.\n  # - P9K_KUBECONTEXT_NAMESPACE  The current context's namespace. Corresponds to column NAMESPACE\n  #                              in the output of `kubectl config get-contexts`. If there is no\n  #                              namespace, the parameter is set to \"default\".\n  # - P9K_KUBECONTEXT_USER       The current context's user. Corresponds to column AUTHINFO in the\n  #                              output of `kubectl config get-contexts`.\n  #\n  # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS),\n  # the following extra parameters are available:\n  #\n  # - P9K_KUBECONTEXT_CLOUD_NAME     Either \"gke\" or \"eks\".\n  # - P9K_KUBECONTEXT_CLOUD_ACCOUNT  Account/project ID.\n  # - P9K_KUBECONTEXT_CLOUD_ZONE     Availability zone.\n  # - P9K_KUBECONTEXT_CLOUD_CLUSTER  Cluster.\n  #\n  # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example,\n  # if P9K_KUBECONTEXT_CLUSTER is \"gke_my-account_us-east1-a_my-cluster-01\":\n  #\n  #   - P9K_KUBECONTEXT_CLOUD_NAME=gke\n  #   - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account\n  #   - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a\n  #   - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01\n  #\n  # If P9K_KUBECONTEXT_CLUSTER is \"arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01\":\n  #\n  #   - P9K_KUBECONTEXT_CLOUD_NAME=eks\n  #   - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012\n  #   - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1\n  #   - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01\n  typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION=\n  # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME.\n  POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}'\n  # Append the current context's namespace if it's not \"default\".\n  POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}'\n\n  # Custom prefix.\n  typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%fat '\n\n  ################[ terraform: terraform workspace (https://www.terraform.io) ]#################\n  # Don't show terraform workspace if it's literally \"default\".\n  typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false\n  # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current terraform workspace gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       OTHER)\n  #\n  # If your current terraform workspace is \"project_test\", its class is TEST because \"project_test\"\n  # doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'         OTHER)\n  typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=38\n  # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]#\n  # Show aws only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show aws.\n  typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt'\n\n  # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current AWS profile gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_AWS_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       DEFAULT)\n  #\n  # If your current AWS profile is \"company_test\", its class is TEST\n  # because \"company_test\" doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_AWS_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'       DEFAULT)\n  typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=208\n  # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]#\n  # AWS Elastic Beanstalk environment color.\n  typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]##########\n  # Show azure only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show azure.\n  typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt'\n  # Azure account name color.\n  typeset -g POWERLEVEL9K_AZURE_FOREGROUND=32\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_AZURE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]###########\n  # Show gcloud only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show gcloud.\n  typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs'\n   # Google cloud color.\n  typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=32\n\n  # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or\n  # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative\n  # enough. You can use the following parameters in the expansions. Each of them corresponds to the\n  # output of `gcloud` tool.\n  #\n  #   Parameter                | Source\n  #   -------------------------|--------------------------------------------------------------------\n  #   P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)'\n  #   P9K_GCLOUD_ACCOUNT       | gcloud config get-value account\n  #   P9K_GCLOUD_PROJECT_ID    | gcloud config get-value project\n  #   P9K_GCLOUD_PROJECT_NAME  | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)'\n  #\n  # Note: ${VARIABLE//\\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'.\n  #\n  # Obtaining project name requires sending a request to Google servers. This can take a long time\n  # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud\n  # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets\n  # set and gcloud prompt segment transitions to state COMPLETE.\n  #\n  # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL\n  # and COMPLETE. You can also hide gcloud in state PARTIAL by setting\n  # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and\n  # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty.\n  typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\\%/%%}'\n  typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\\%/%%}'\n\n  # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name\n  # this often. Negative value disables periodic polling. In this mode project name is retrieved\n  # only when the current configuration, account or project id changes.\n  typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]#\n  # Show google_app_cred only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show google_app_cred.\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt'\n\n  # Google application credentials classes for the purpose of using different colors, icons and\n  # expansions with different credentials.\n  #\n  # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first\n  # element in each pair defines a pattern against which the current kubernetes context gets\n  # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion\n  # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION\n  # parameters, you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order.\n  # The first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=(\n  #     '*:*prod*:*'  PROD\n  #     '*:*test*:*'  TEST\n  #     '*'           DEFAULT)\n  #\n  # If your current Google application credentials is \"service_account deathray-testing x@y.com\",\n  # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID'\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=(\n      # '*:*prod*:*'  PROD    # These values are examples that are unlikely\n      # '*:*test*:*'  TEST    # to match your needs. Customize them as needed.\n      '*'             DEFAULT)\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by\n  # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference:\n  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion.\n  #\n  # You can use the following parameters in the expansion. Each of them corresponds to one of the\n  # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS.\n  #\n  #   Parameter                        | JSON key file field\n  #   ---------------------------------+---------------\n  #   P9K_GOOGLE_APP_CRED_TYPE         | type\n  #   P9K_GOOGLE_APP_CRED_PROJECT_ID   | project_id\n  #   P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email\n  #\n  # Note: ${VARIABLE//\\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'.\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\\%/%%}'\n\n  ###############################[ public_ip: public IP address ]###############################\n  # Public IP color.\n  typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=94\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ########################[ vpn_ip: virtual private network indicator ]#########################\n  # VPN IP color.\n  typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=81\n  # When on VPN, show just an icon without the IP address.\n  # Tip: To display the private IP address when on VPN, remove the next line.\n  typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION=\n  # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN\n  # to see the name of the interface.\n  typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*'\n  # If set to true, show one segment per matching network interface. If set to false, show only\n  # one segment corresponding to the first matching network interface.\n  # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION.\n  typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ ip: ip address and bandwidth usage for a specified network interface ]###########\n  # IP color.\n  typeset -g POWERLEVEL9K_IP_FOREGROUND=38\n  # The following parameters are accessible within the expansion:\n  #\n  #   Parameter             | Meaning\n  #   ----------------------+---------------\n  #   P9K_IP_IP         | IP address\n  #   P9K_IP_INTERFACE  | network interface\n  #   P9K_IP_RX_BYTES   | total number of bytes received\n  #   P9K_IP_TX_BYTES   | total number of bytes sent\n  #   P9K_IP_RX_RATE    | receive rate (since last prompt)\n  #   P9K_IP_TX_RATE    | send rate (since last prompt)\n  typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='$P9K_IP_IP${P9K_IP_RX_RATE:+ %70F\u21e3$P9K_IP_RX_RATE}${P9K_IP_TX_RATE:+ %215F\u21e1$P9K_IP_TX_RATE}'\n  # Show information for the first network interface whose name matches this regular expression.\n  # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces.\n  typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #########################[ proxy: system-wide http/https/ftp proxy ]##########################\n  # Proxy color.\n  typeset -g POWERLEVEL9K_PROXY_FOREGROUND=68\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################################[ battery: internal battery ]#################################\n  # Show battery in red when it's below this level and not connected to power supply.\n  typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20\n  typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=160\n  # Show battery in green when it's charging or fully charged.\n  typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=70\n  # Show battery in yellow when it's discharging.\n  typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=178\n  # Battery pictograms going from low to high level of charge.\n  typeset -g POWERLEVEL9K_BATTERY_STAGES='\\uf58d\\uf579\\uf57a\\uf57b\\uf57c\\uf57d\\uf57e\\uf57f\\uf580\\uf581\\uf578'\n  # Don't show the remaining time to charge/discharge.\n  typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false\n\n  #####################################[ wifi: wifi speed ]#####################################\n  # WiFi color.\n  typeset -g POWERLEVEL9K_WIFI_FOREGROUND=68\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS).\n  #\n  #   # Wifi colors and icons for different signal strength levels (low to high).\n  #   typeset -g my_wifi_fg=(68 68 68 68 68)                           # <-- change these values\n  #   typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi')     # <-- change these values\n  #\n  #   typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps'\n  #   typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}'\n  #\n  # The following parameters are accessible within the expansions:\n  #\n  #   Parameter             | Meaning\n  #   ----------------------+---------------\n  #   P9K_WIFI_SSID         | service set identifier, a.k.a. network name\n  #   P9K_WIFI_LINK_AUTH    | authentication protocol such as \"wpa2-psk\" or \"none\"; empty if unknown\n  #   P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second\n  #   P9K_WIFI_RSSI         | signal strength in dBm, from -120 to 0\n  #   P9K_WIFI_NOISE        | noise in dBm, from -120 to 0\n  #   P9K_WIFI_BARS         | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE)\n\n  ####################################[ time: current time ]####################################\n  # Current time color.\n  typeset -g POWERLEVEL9K_TIME_FOREGROUND=66\n  # Format for the current time: 09:51:02. See `man 3 strftime`.\n  typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}'\n  # If set to true, time will update when you hit enter. This way prompts for the past\n  # commands will contain the start times of their commands as opposed to the default\n  # behavior where they contain the end times of their preceding commands.\n  typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  typeset -g POWERLEVEL9K_TIME_PREFIX='%fat '\n\n  # Example of a user-defined prompt segment. Function prompt_example will be called on every\n  # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or\n  # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and orange text greeting the user.\n  #\n  # Type `p10k help segment` for documentation and a more sophisticated example.\n  function prompt_example() {\n    p10k segment -f 208 -i '\u2b50' -t 'hello, %n'\n  }\n\n  # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job\n  # is to generate the prompt segment for display in instant prompt. See\n  # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt.\n  #\n  # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function\n  # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k\n  # will replay these calls without actually calling instant_prompt_*. It is imperative that\n  # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this\n  # rule is not observed, the content of instant prompt will be incorrect.\n  #\n  # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If\n  # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt.\n  function instant_prompt_example() {\n    # Since prompt_example always makes the same `p10k segment` calls, we can call it from\n    # instant_prompt_example. This will give us the same `example` prompt segment in the instant\n    # and regular prompts.\n    prompt_example\n  }\n\n  # User-defined prompt segments can be customized the same way as built-in segments.\n  # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208\n  # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt\n  # when accepting a command line. Supported values:\n  #\n  #   - off:      Don't change prompt when accepting a command line.\n  #   - always:   Trim down prompt when accepting a command line.\n  #   - same-dir: Trim down prompt when accepting a command line unless this is the first command\n  #               typed after changing current working directory.\n  typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=always\n\n  # Instant prompt mode.\n  #\n  #   - off:     Disable instant prompt. Choose this if you've tried instant prompt and found\n  #              it incompatible with your zsh configuration files.\n  #   - quiet:   Enable instant prompt and don't print warnings when detecting console output\n  #              during zsh initialization. Choose this if you've read and understood\n  #              https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt.\n  #   - verbose: Enable instant prompt and print a warning when detecting console output during\n  #              zsh initialization. Choose this if you've never tried instant prompt, haven't\n  #              seen the warning, or if you are unsure what this all means.\n  typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose\n\n  # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized.\n  # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload\n  # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you\n  # really need it.\n  typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true\n\n  # If p10k is already loaded, reload configuration.\n  # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true.\n  (( ! $+functions[p10k] )) || p10k reload\n}\n\n# Tell `p10k configure` which file it should overwrite.\ntypeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a}\n\n(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]}\n'builtin' 'unset' 'p10k_config_opts'\n", "meta": {"author": "dcabooter", "repo": "tools", "sha": "18cc9665ab79c51df375aa0c19baf3dbd0ac26ac", "save_path": "github-repos/lean/dcabooter-tools", "path": "github-repos/lean/dcabooter-tools/tools-18cc9665ab79c51df375aa0c19baf3dbd0ac26ac/zsh-zimfw/.p10k.zsh.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.016403033477822813, "lm_q2_score": 0.009125636648101388, "lm_q1q2_score": 0.00014968812344525384}}
{"text": "# Generated by Powerlevel10k configuration wizard on 2021-09-10 at 09:45 MDT.\n# Based on romkatv/powerlevel10k/config/p10k-lean.zsh.\n# Wizard options: nerdfont-complete + powerline, small icons, unicode, lean, 24h time,\n# 2 lines, dotted, no frame, dark-ornaments, sparse, many icons, concise,\n# instant_prompt=verbose.\n# Type `p10k configure` to generate another config.\n#\n# Config for Powerlevel10k with lean prompt style. Type `p10k configure` to generate\n# your own config based on it.\n#\n# Tip: Looking for a nice color? Here's a one-liner to print colormap.\n#\n#   for i in {0..255}; do print -Pn \"%K{$i}  %k%F{$i}${(l:3::0:)i}%f \" ${${(M)$((i%6)):#3}:+$'\\n'}; done\n\n# Temporarily change options.\n'builtin' 'local' '-a' 'p10k_config_opts'\n[[ ! -o 'aliases'         ]] || p10k_config_opts+=('aliases')\n[[ ! -o 'sh_glob'         ]] || p10k_config_opts+=('sh_glob')\n[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand')\n'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand'\n\n() {\n  emulate -L zsh -o extended_glob\n\n  # Unset all configuration options. This allows you to apply configuration changes without\n  # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`.\n  unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR'\n\n  # Zsh >= 5.1 is required.\n  autoload -Uz is-at-least && is-at-least 5.1 || return\n\n  # The list of segments shown on the left. Fill it with the most important segments.\n  typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(\n    # =========================[ Line #1 ]=========================\n    os_icon                 # os identifier\n    dir                     # current directory\n    vcs                     # git status\n    # =========================[ Line #2 ]=========================\n    newline\n    prompt_char             # prompt symbol\n  )\n\n  # The list of segments shown on the right. Fill it with less important segments.\n  # Right prompt on the last prompt line (where you are typing your commands) gets\n  # automatically hidden when the input line reaches it. Right prompt above the\n  # last prompt line gets hidden if it would overlap with left prompt.\n  typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(\n    # =========================[ Line #1 ]=========================\n    status                  # exit code of the last command\n    command_execution_time  # duration of the last command\n    background_jobs         # presence of background jobs\n    direnv                  # direnv status (https://direnv.net/)\n    asdf                    # asdf version manager (https://github.com/asdf-vm/asdf)\n    virtualenv              # python virtual environment (https://docs.python.org/3/library/venv.html)\n    anaconda                # conda environment (https://conda.io/)\n    pyenv                   # python environment (https://github.com/pyenv/pyenv)\n    goenv                   # go environment (https://github.com/syndbg/goenv)\n    nodenv                  # node.js version from nodenv (https://github.com/nodenv/nodenv)\n    nvm                     # node.js version from nvm (https://github.com/nvm-sh/nvm)\n    nodeenv                 # node.js environment (https://github.com/ekalinin/nodeenv)\n    # node_version          # node.js version\n    # go_version            # go version (https://golang.org)\n    # rust_version          # rustc version (https://www.rust-lang.org)\n    # dotnet_version        # .NET version (https://dotnet.microsoft.com)\n    # php_version           # php version (https://www.php.net/)\n    # laravel_version       # laravel php framework version (https://laravel.com/)\n    # java_version          # java version (https://www.java.com/)\n    # package               # name@version from package.json (https://docs.npmjs.com/files/package.json)\n    rbenv                   # ruby version from rbenv (https://github.com/rbenv/rbenv)\n    rvm                     # ruby version from rvm (https://rvm.io)\n    fvm                     # flutter version management (https://github.com/leoafarias/fvm)\n    luaenv                  # lua version from luaenv (https://github.com/cehoffman/luaenv)\n    jenv                    # java version from jenv (https://github.com/jenv/jenv)\n    plenv                   # perl version from plenv (https://github.com/tokuhirom/plenv)\n    phpenv                  # php version from phpenv (https://github.com/phpenv/phpenv)\n    scalaenv                # scala version from scalaenv (https://github.com/scalaenv/scalaenv)\n    haskell_stack           # haskell version from stack (https://haskellstack.org/)\n    kubecontext             # current kubernetes context (https://kubernetes.io/)\n    terraform               # terraform workspace (https://www.terraform.io)\n    # terraform_version     # terraform version (https://www.terraform.io)\n    aws                     # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html)\n    aws_eb_env              # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/)\n    azure                   # azure account name (https://docs.microsoft.com/en-us/cli/azure)\n    gcloud                  # google cloud cli account and project (https://cloud.google.com/)\n    google_app_cred         # google application credentials (https://cloud.google.com/docs/authentication/production)\n    toolbox                 # toolbox name (https://github.com/containers/toolbox)\n    context                 # user@hostname\n    nordvpn                 # nordvpn connection status, linux only (https://nordvpn.com/)\n    ranger                  # ranger shell (https://github.com/ranger/ranger)\n    nnn                     # nnn shell (https://github.com/jarun/nnn)\n    xplr                    # xplr shell (https://github.com/sayanarijit/xplr)\n    vim_shell               # vim shell indicator (:sh)\n    midnight_commander      # midnight commander shell (https://midnight-commander.org/)\n    nix_shell               # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html)\n    # vpn_ip                # virtual private network indicator\n    load                  # CPU load\n    # disk_usage            # disk usage\n    # ram                   # free RAM\n    # swap                  # used swap\n    todo                    # todo items (https://github.com/todotxt/todo.txt-cli)\n    timewarrior             # timewarrior tracking status (https://timewarrior.net/)\n    taskwarrior             # taskwarrior task count (https://taskwarrior.org/)\n    time                    # current time\n    # =========================[ Line #2 ]=========================\n    newline\n    # ip                    # ip address and bandwidth usage for a specified network interface\n    # public_ip             # public IP address\n    # proxy                 # system-wide http/https/ftp proxy\n    # battery               # internal battery\n    # wifi                  # wifi speed\n    # example               # example user-defined segment (see prompt_example function below)\n  )\n\n  # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you.\n  typeset -g POWERLEVEL9K_MODE=nerdfont-complete\n  # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid\n  # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added.\n  typeset -g POWERLEVEL9K_ICON_PADDING=none\n\n  # Basic style options that define the overall look of your prompt. You probably don't want to\n  # change them.\n  typeset -g POWERLEVEL9K_BACKGROUND=                            # transparent background\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE=  # no surrounding whitespace\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' '  # separate segments with a space\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR=        # no end-of-line symbol\n\n  # When set to true, icons appear before content on both sides of the prompt. When set\n  # to false, icons go after content. If empty or not set, icons go before content in the left\n  # prompt and after content in the right prompt.\n  #\n  # You can also override it for a specific segment:\n  #\n  #   POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false\n  #\n  # Or for a specific segment in specific state:\n  #\n  #   POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false\n  typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT=true\n\n  # Add an empty line before each prompt.\n  typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true\n\n  # Connect left prompt lines with these symbols.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX=\n  # Connect right prompt lines with these symbols.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX=\n\n  # The left end of left prompt.\n  typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=\n  # The right end of right prompt.\n  typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL=\n\n  # Ruler, a.k.a. the horizontal line before each prompt. If you set it to true, you'll\n  # probably want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false above and\n  # POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' below.\n  typeset -g POWERLEVEL9K_SHOW_RULER=false\n  typeset -g POWERLEVEL9K_RULER_CHAR='\u2500'        # reasonable alternative: '\u00b7'\n  typeset -g POWERLEVEL9K_RULER_FOREGROUND=240\n\n  # Filler between left and right prompt on the first prompt line. You can set it to '\u00b7' or '\u2500'\n  # to make it easier to see the alignment between left and right prompt and to separate prompt\n  # from command output. It serves the same purpose as ruler (see above) without increasing\n  # the number of prompt lines. You'll probably want to set POWERLEVEL9K_SHOW_RULER=false\n  # if using this. You might also like POWERLEVEL9K_PROMPT_ADD_NEWLINE=false for more compact\n  # prompt.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR='\u00b7'\n  if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then\n    # The color of the filler.\n    typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=240\n    # Add a space between the end of left prompt and the filler.\n    typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=' '\n    # Add a space between the filler and the start of right prompt.\n    typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' '\n    # Start filler from the edge of the screen if there are no left segments on the first line.\n    typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}'\n    # End filler on the edge of the screen if there are no right segments on the first line.\n    typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}'\n  fi\n\n  #################################[ os_icon: os identifier ]##################################\n  # OS identifier color.\n  typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='\u2b50'\n\n  ################################[ prompt_char: prompt symbol ]################################\n  # Green prompt symbol if the last command succeeded.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76\n  # Red prompt symbol if the last command failed.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196\n  # Default prompt symbol.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='\u276f'\n  # Prompt symbol in command vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='\u276e'\n  # Prompt symbol in visual vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V'\n  # Prompt symbol in overwrite vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='\u25b6'\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true\n  # No line terminator if prompt_char is the last segment.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=''\n  # No line introducer if prompt_char is the first segment.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=\n\n  ##################################[ dir: current directory ]##################################\n  # Default current directory color.\n  typeset -g POWERLEVEL9K_DIR_FOREGROUND=31\n  # If directory is too long, shorten some of its segments to the shortest possible unique\n  # prefix. The shortened directory can be tab-completed to the original.\n  typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique\n  # Replace removed segment suffixes with this symbol.\n  typeset -g POWERLEVEL9K_SHORTEN_DELIMITER=\n  # Color of the shortened directory segments.\n  typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=103\n  # Color of the anchor directory segments. Anchor segments are never shortened. The first\n  # segment is always an anchor.\n  typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=39\n  # Display anchor directory segments in bold.\n  typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true\n  # Don't shorten directories that contain any of these files. They are anchors.\n  local anchor_files=(\n    .bzr\n    .citc\n    .git\n    .hg\n    .node-version\n    .python-version\n    .go-version\n    .ruby-version\n    .lua-version\n    .java-version\n    .perl-version\n    .php-version\n    .tool-version\n    .shorten_folder_marker\n    .svn\n    .terraform\n    CVS\n    Cargo.toml\n    composer.json\n    go.mod\n    package.json\n    stack.yaml\n  )\n  typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER=\"(${(j:|:)anchor_files})\"\n  # If set to \"first\" (\"last\"), remove everything before the first (last) subdirectory that contains\n  # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is\n  # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first)\n  # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers\n  # and other directories don't.\n  #\n  # Optionally, \"first\" and \"last\" can be followed by \":<offset>\" where <offset> is an integer.\n  # This moves the truncation point to the right (positive offset) or to the left (negative offset)\n  # relative to the marker. Plain \"first\" and \"last\" are equivalent to \"first:0\" and \"last:0\"\n  # respectively.\n  typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false\n  # Don't shorten this many last directory segments. They are anchors.\n  typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1\n  # Shorten directory if it's longer than this even if there is space for it. The value can\n  # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty,\n  # directory will be shortened only when prompt doesn't fit or when other parameters demand it\n  # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below).\n  # If set to `0`, directory will always be shortened to its minimum length.\n  typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80\n  # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this\n  # many columns for typing commands.\n  typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40\n  # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least\n  # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands.\n  typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50\n  # If set to true, embed a hyperlink into the directory. Useful for quickly\n  # opening a directory in the file manager simply by clicking the link.\n  # Can also be handy when the directory is shortened, as it allows you to see\n  # the full directory that was used in previous commands.\n  typeset -g POWERLEVEL9K_DIR_HYPERLINK=false\n\n  # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON\n  # and POWERLEVEL9K_DIR_CLASSES below.\n  typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3\n\n  # The default icon shown next to non-writable and non-existent directories when\n  # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3.\n  # typeset -g POWERLEVEL9K_LOCK_ICON='\u2b50'\n\n  # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different\n  # directories. It must be an array with 3 * N elements. Each triplet consists of:\n  #\n  #   1. A pattern against which the current directory ($PWD) is matched. Matching is done with\n  #      extended_glob option enabled.\n  #   2. Directory class for the purpose of styling.\n  #   3. An empty string.\n  #\n  # Triplets are tried in order. The first triplet whose pattern matches $PWD wins.\n  #\n  # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories\n  # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_DIR_CLASSES=(\n  #     '~/work(|/*)'  WORK     ''\n  #     '~(|/*)'       HOME     ''\n  #     '*'            DEFAULT  '')\n  #\n  # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one\n  # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or\n  # WORK_NON_EXISTENT.\n  #\n  # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an\n  # option to define custom colors and icons for different directory classes.\n  #\n  #   # Styling for WORK.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=39\n  #\n  #   # Styling for WORK_NOT_WRITABLE.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=39\n  #\n  #   # Styling for WORK_NON_EXISTENT.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=39\n  #\n  # If a styling parameter isn't explicitly defined for some class, it falls back to the classless\n  # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls\n  # back to POWERLEVEL9K_DIR_FOREGROUND.\n  #\n  # typeset -g POWERLEVEL9K_DIR_CLASSES=()\n\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_DIR_PREFIX='%fin '\n\n  #####################################[ vcs: git status ]######################################\n  # Branch icon. Set this parameter to '\\uF126 ' for the popular Powerline branch icon.\n  typeset -g POWERLEVEL9K_VCS_BRANCH_ICON='\\uF126 '\n\n  # Untracked files icon. It's really a question mark, your font isn't broken.\n  # Change the value of this parameter to show a different icon.\n  typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?'\n\n  # Formatter for Git status.\n  #\n  # Example output: master wip \u21e342\u21e142 *42 merge ~42 +42 !42 ?42.\n  #\n  # You can edit the function to customize how Git status looks.\n  #\n  # VCS_STATUS_* parameters are set by gitstatus plugin. See reference:\n  # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh.\n  function my_git_formatter() {\n    emulate -L zsh\n\n    if [[ -n $P9K_CONTENT ]]; then\n      # If P9K_CONTENT is not empty, use it. It's either \"loading\" or from vcs_info (not from\n      # gitstatus plugin). VCS_STATUS_* parameters are not available in this case.\n      typeset -g my_git_format=$P9K_CONTENT\n      return\n    fi\n\n    if (( $1 )); then\n      # Styling for up-to-date Git status.\n      local       meta='%f'     # default foreground\n      local      clean='%76F'   # green foreground\n      local   modified='%178F'  # yellow foreground\n      local  untracked='%39F'   # blue foreground\n      local conflicted='%196F'  # red foreground\n    else\n      # Styling for incomplete and stale Git status.\n      local       meta='%244F'  # grey foreground\n      local      clean='%244F'  # grey foreground\n      local   modified='%244F'  # grey foreground\n      local  untracked='%244F'  # grey foreground\n      local conflicted='%244F'  # grey foreground\n    fi\n\n    # rbever: 9/10/21: added to change color of git branch based on status\n    # The branch color is either clean(green) or not(red)\n    local branch_color=${clean}\n    (( VCS_STATUS_NUM_CONFLICTED )) && branch_color=${conflicted}\n    (( VCS_STATUS_NUM_STAGED     )) && branch_color=${conflicted}\n    (( VCS_STATUS_NUM_UNSTAGED   )) && branch_color=${conflicted}\n    (( VCS_STATUS_NUM_UNTRACKED  )) && branch_color=${conflicted}\n\n    local res\n\n    if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then\n      local branch=${(V)VCS_STATUS_LOCAL_BRANCH}\n      # If local branch name is at most 32 characters long, show it in full.\n      # Otherwise show the first 12 \u2026 the last 12.\n      # Tip: To always show local branch name in full without truncation, delete the next line.\n      # (( $#branch > 32 )) && branch[13,-13]=\"\u2026\"  # <-- this line\n      res+=\"${branch_color}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\\%/%%}\"\n    fi\n\n    if [[ -n $VCS_STATUS_TAG\n          # Show tag only if not on a branch.\n          # Tip: To always show tag, delete the next line.\n          && -z $VCS_STATUS_LOCAL_BRANCH  # <-- this line\n        ]]; then\n      local tag=${(V)VCS_STATUS_TAG}\n      # If tag name is at most 32 characters long, show it in full.\n      # Otherwise show the first 12 \u2026 the last 12.\n      # Tip: To always show tag name in full without truncation, delete the next line.\n      (( $#tag > 32 )) && tag[13,-13]=\"\u2026\"  # <-- this line\n      res+=\"${meta}#${clean}${tag//\\%/%%}\"\n    fi\n\n    # Display the current Git commit if there is no branch and no tag.\n    # Tip: To always display the current Git commit, delete the next line.\n    [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_TAG ]] &&  # <-- this line\n      res+=\"${meta}@${branch_color}${VCS_STATUS_COMMIT[1,8]}\"\n\n    # Show tracking branch name if it differs from local branch.\n    if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then\n      res+=\"${meta}:${branch_color}${(V)VCS_STATUS_REMOTE_BRANCH//\\%/%%}\"\n    fi\n\n    # Display \"wip\" if the latest commit's summary contains \"wip\" or \"WIP\".\n    if [[ $VCS_STATUS_COMMIT_SUMMARY == (|*[^[:alnum:]])(wip|WIP)(|[^[:alnum:]]*) ]]; then\n      res+=\" ${modified}wip\"\n    fi\n\n    # \u21e342 if behind the remote.\n    (( VCS_STATUS_COMMITS_BEHIND )) && res+=\" ${clean}\u21e3${VCS_STATUS_COMMITS_BEHIND}\"\n    # \u21e142 if ahead of the remote; no leading space if also behind the remote: \u21e342\u21e142.\n    (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=\" \"\n    (( VCS_STATUS_COMMITS_AHEAD  )) && res+=\"${clean}\u21e1${VCS_STATUS_COMMITS_AHEAD}\"\n    # \u21e042 if behind the push remote.\n    (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=\" ${clean}\u21e0${VCS_STATUS_PUSH_COMMITS_BEHIND}\"\n    (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=\" \"\n    # \u21e242 if ahead of the push remote; no leading space if also behind: \u21e042\u21e242.\n    (( VCS_STATUS_PUSH_COMMITS_AHEAD  )) && res+=\"${clean}\u21e2${VCS_STATUS_PUSH_COMMITS_AHEAD}\"\n    # *42 if have stashes.\n    (( VCS_STATUS_STASHES        )) && res+=\" ${clean}*${VCS_STATUS_STASHES}\"\n    # 'merge' if the repo is in an unusual state.\n    [[ -n $VCS_STATUS_ACTION     ]] && res+=\" ${conflicted}${VCS_STATUS_ACTION}\"\n    # ~42 if have merge conflicts.\n    (( VCS_STATUS_NUM_CONFLICTED )) && res+=\" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}\"\n    # +42 if have staged changes.\n    (( VCS_STATUS_NUM_STAGED     )) && res+=\" ${modified}+${VCS_STATUS_NUM_STAGED}\"\n    # !42 if have unstaged changes.\n    (( VCS_STATUS_NUM_UNSTAGED   )) && res+=\" ${modified}!${VCS_STATUS_NUM_UNSTAGED}\"\n    # ?42 if have untracked files. It's really a question mark, your font isn't broken.\n    # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon.\n    # Remove the next line if you don't want to see untracked files at all.\n    (( VCS_STATUS_NUM_UNTRACKED  )) && res+=\" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}\"\n    # \"\u2500\" if the number of unstaged files is unknown. This can happen due to\n    # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower\n    # than the number of files in the Git index, or due to bash.showDirtyState being set to false\n    # in the repository config. The number of staged and untracked files may also be unknown\n    # in this case.\n    (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=\" ${modified}\u2500\"\n\n    typeset -g my_git_format=$res\n  }\n  functions -M my_git_formatter 2>/dev/null\n\n  # Don't count the number of unstaged, untracked and conflicted files in Git repositories with\n  # more than this many files in the index. Negative value means infinity.\n  #\n  # If you are working in Git repositories with tens of millions of files and seeing performance\n  # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output\n  # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's\n  # config: `git config bash.showDirtyState false`.\n  typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1\n\n  # Don't show Git status in prompt for repositories whose workdir matches this pattern.\n  # For example, if set to '~', the Git repository at $HOME/.git will be ignored.\n  # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'.\n  typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~'\n\n  # Disable the default Git status formatting.\n  typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true\n  # Install our own Git status formatter.\n  typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}'\n  typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}'\n  # Enable counters for staged, unstaged, etc.\n  typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1\n\n  # Icon color.\n  typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=255\n  typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR=244\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_VCS_PREFIX='%fon '\n\n  # Show status of repositories of these types. You can add svn and/or hg if you are\n  # using them. If you do, your prompt may become slow even when your current directory\n  # isn't in an svn or hg reposotiry.\n  typeset -g POWERLEVEL9K_VCS_BACKENDS=(git)\n\n  # These settings are used for repositories other than Git or when gitstatusd fails and\n  # Powerlevel10k has to fall back to using vcs_info.\n  typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=76\n  typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=76\n  typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=178\n\n  ##########################[ status: exit code of the last command ]###########################\n  # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and\n  # style them independently from the regular OK and ERROR state.\n  typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true\n\n  # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as\n  # it will signify success by turning green.\n  typeset -g POWERLEVEL9K_STATUS_OK=false\n  typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=70\n  typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='\u2714'\n\n  # Status when some part of a pipe command fails but the overall exit status is zero. It may look\n  # like this: 1|0.\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=70\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='\u2714'\n\n  # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as\n  # it will signify error by turning red.\n  typeset -g POWERLEVEL9K_STATUS_ERROR=false\n  typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=160\n  typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  # Status when the last command was terminated by a signal.\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=160\n  # Use terse signal names: \"INT\" instead of \"SIGINT(2)\".\n  typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  # Status when some part of a pipe command fails and the overall exit status is also non-zero.\n  # It may look like this: 1|0.\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=160\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  ###################[ command_execution_time: duration of the last command ]###################\n  # Show duration of the last command if takes at least this many seconds.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3\n  # Show this many fractional digits. Zero means round to seconds.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0\n  # Execution time color.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=101\n  # Duration format: 1d 2h 3m 4s.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%ftook '\n\n  #######################[ background_jobs: presence of background jobs ]#######################\n  # Don't show the number of background jobs.\n  typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false\n  # Background jobs color.\n  typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ direnv: direnv status (https://direnv.net/) ]########################\n  # Direnv color.\n  typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]###############\n  # Default asdf color. Only used to display tools for which there is no color override (see below).\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND.\n  typeset -g POWERLEVEL9K_ASDF_FOREGROUND=66\n\n  # There are four parameters that can be used to hide asdf tools. Each parameter describes\n  # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at\n  # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to\n  # hide a tool, it gets shown.\n  #\n  # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and\n  # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands:\n  #\n  #   asdf local  python 3.8.1\n  #   asdf global python 3.8.1\n  #\n  # After running both commands the current python version is 3.8.1 and its source is \"local\" as\n  # it takes precedence over \"global\". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false,\n  # it'll hide python version in this case because 3.8.1 is the same as the global version.\n  # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't\n  # contain \"local\".\n\n  # Hide tool versions that don't come from one of these sources.\n  #\n  # Available sources:\n  #\n  # - shell   `asdf current` says \"set by ASDF_${TOOL}_VERSION environment variable\"\n  # - local   `asdf current` says \"set by /some/not/home/directory/file\"\n  # - global  `asdf current` says \"set by /home/username/file\"\n  #\n  # Note: If this parameter is set to (shell local global), it won't hide tools.\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES.\n  typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global)\n\n  # If set to false, hide tool versions that are the same as global.\n  #\n  # Note: The name of this parameter doesn't reflect its meaning at all.\n  # Note: If this parameter is set to true, it won't hide tools.\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW.\n  typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false\n\n  # If set to false, hide tool versions that are equal to \"system\".\n  #\n  # Note: If this parameter is set to true, it won't hide tools.\n  # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM.\n  typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true\n\n  # If set to non-empty value, hide tools unless there is a file matching the specified file pattern\n  # in the current directory, or its parent directory, or its grandparent directory, and so on.\n  #\n  # Note: If this parameter is set to empty value, it won't hide tools.\n  # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments.\n  # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB.\n  #\n  # Example: Hide nodejs version when there is no package.json and no *.js files in the current\n  # directory, in `..`, in `../..` and so on.\n  #\n  #   typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json'\n  typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB=\n\n  # Ruby version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=168\n  # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Python version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Go version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Node.js version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=70\n  # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Rust version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # .NET Core version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=134\n  # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_DOTNET_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Flutter version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=38\n  # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Lua version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Java version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Perl version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=67\n  # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Erlang version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=125\n  # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Elixir version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=129\n  # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Postgres version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=31\n  # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # PHP version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=99\n  # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Haskell version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=172\n  # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Julia version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=70\n  # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]###########\n  # NordVPN connection indicator color.\n  typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=39\n  # Hide NordVPN connection indicator when not connected.\n  typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION=\n  typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]##################\n  # Ranger shell color.\n  typeset -g POWERLEVEL9K_RANGER_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]#######################\n  # Nnn shell color.\n  typeset -g POWERLEVEL9K_NNN_FOREGROUND=72\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################[ xplr: xplr shell (https://github.com/sayanarijit/xplr) ]##################\n  # xplr shell color.\n  typeset -g POWERLEVEL9K_XPLR_FOREGROUND=72\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_XPLR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########################[ vim_shell: vim shell indicator (:sh) ]###########################\n  # Vim shell indicator color.\n  typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=34\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]######\n  # Midnight Commander shell color.\n  typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]##\n  # Nix shell color.\n  typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=74\n\n  # Tip: If you want to see just the icon without \"pure\" and \"impure\", uncomment the next line.\n  # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################################[ disk_usage: disk usage ]##################################\n  # Colors for different levels of disk usage.\n  typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=35\n  typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=220\n  typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=160\n  # Thresholds for different levels of disk usage (percentage points).\n  typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90\n  typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95\n  # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent.\n  typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################################[ ram: free RAM ]#######################################\n  # RAM color.\n  typeset -g POWERLEVEL9K_RAM_FOREGROUND=66\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################################[ swap: used swap ]######################################\n  # Swap color.\n  typeset -g POWERLEVEL9K_SWAP_FOREGROUND=96\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################################[ load: CPU load ]######################################\n  # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15.\n  typeset -g POWERLEVEL9K_LOAD_WHICH=5\n  # Load color when load is under 50%.\n  typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=66\n  # Load color when load is between 50% and 70%.\n  typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=178\n  # Load color when load is over 70%.\n  typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=166\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################\n  # Todo color.\n  typeset -g POWERLEVEL9K_TODO_FOREGROUND=110\n  # Hide todo when the total number of tasks is zero.\n  typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true\n  # Hide todo when the number of tasks after filtering is zero.\n  typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false\n\n  # Todo format. The following parameters are available within the expansion.\n  #\n  # - P9K_TODO_TOTAL_TASK_COUNT     The total number of tasks.\n  # - P9K_TODO_FILTERED_TASK_COUNT  The number of tasks after filtering.\n  #\n  # These variables correspond to the last line of the output of `todo.sh -p ls`:\n  #\n  #   TODO: 24 of 42 tasks shown\n  #\n  # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT.\n  #\n  # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############\n  # Timewarrior color.\n  typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=110\n  # If the tracked task is longer than 24 characters, truncate and append \"\u2026\".\n  # Tip: To always display tasks without truncation, delete the following parameter.\n  # Tip: To hide task names and display just the icon when time tracking is enabled, set the\n  # value of the following parameter to \"\".\n  typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+\u2026}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]##############\n  # Taskwarrior color.\n  typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=74\n\n  # Taskwarrior segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_TASKWARRIOR_PENDING_COUNT   The number of pending tasks: `task +PENDING count`.\n  # - P9K_TASKWARRIOR_OVERDUE_COUNT   The number of overdue tasks: `task +OVERDUE count`.\n  #\n  # Zero values are represented as empty parameters.\n  #\n  # The default format:\n  #\n  #   '${P9K_TASKWARRIOR_OVERDUE_COUNT:+\"!$P9K_TASKWARRIOR_OVERDUE_COUNT/\"}$P9K_TASKWARRIOR_PENDING_COUNT'\n  #\n  # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################################[ context: user@hostname ]##################################\n  # Context color when running with privileges.\n  typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=178\n  # Context color in SSH without privileges.\n  typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=180\n  # Default context color (no privileges, no SSH).\n  typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=180\n\n  # Context format when running with privileges: bold user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m'\n  # Context format when in SSH without privileges: user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m'\n  # Default context format (no privileges, no SSH): user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m'\n\n  # Don't show context unless running with privileges or in SSH.\n  # Tip: Remove the next line to always show context.\n  typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%fwith '\n\n  ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]###\n  # Python virtual environment color.\n  typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=37\n  # Don't show Python version next to the virtual environment name.\n  typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false\n  # If set to \"false\", won't show virtualenv if pyenv is already shown.\n  # If set to \"if-different\", won't show virtualenv if it's the same as pyenv.\n  typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false\n  # Separate environment name from Python version only with a space.\n  typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################[ anaconda: conda environment (https://conda.io/) ]######################\n  # Anaconda environment color.\n  typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=37\n\n  # Anaconda segment format. The following parameters are available within the expansion.\n  #\n  # - CONDA_PREFIX                 Absolute path to the active Anaconda/Miniconda environment.\n  # - CONDA_DEFAULT_ENV            Name of the active Anaconda/Miniconda environment.\n  # - CONDA_PROMPT_MODIFIER        Configurable prompt modifier (see below).\n  # - P9K_ANACONDA_PYTHON_VERSION  Current python version (python --version).\n  #\n  # CONDA_PROMPT_MODIFIER can be configured with the following command:\n  #\n  #   conda config --set env_prompt '({default_env}) '\n  #\n  # The last argument is a Python format string that can use the following variables:\n  #\n  # - prefix       The same as CONDA_PREFIX.\n  # - default_env  The same as CONDA_DEFAULT_ENV.\n  # - name         The last segment of CONDA_PREFIX.\n  # - stacked_env  Comma-separated list of names in the environment stack. The first element is\n  #                always the same as default_env.\n  #\n  # Note: '({default_env}) ' is the default value of env_prompt.\n  #\n  # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER\n  # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former\n  # is empty.\n  typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\\(}% }%\\)}:-${CONDA_PREFIX:t}}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################\n  # Pyenv color.\n  typeset -g POWERLEVEL9K_PYENV_FOREGROUND=37\n  # Hide python version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global)\n  # If set to false, hide python version if it's the same as global:\n  # $(pyenv version-name) == $(pyenv global).\n  typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide python version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true\n\n  # Pyenv segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_CONTENT                Current pyenv environment (pyenv version-name).\n  # - P9K_PYENV_PYTHON_VERSION   Current python version (python --version).\n  #\n  # The default format has the following logic:\n  #\n  # 1. Display just \"$P9K_CONTENT\" if it's equal to \"$P9K_PYENV_PYTHON_VERSION\" or\n  #    starts with \"$P9K_PYENV_PYTHON_VERSION/\".\n  # 2. Otherwise display \"$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION\".\n  typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_CONTENT:#$P9K_PYENV_PYTHON_VERSION(|/*)}:+ $P9K_PYENV_PYTHON_VERSION}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################\n  # Goenv color.\n  typeset -g POWERLEVEL9K_GOENV_FOREGROUND=37\n  # Hide go version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global)\n  # If set to false, hide go version if it's the same as global:\n  # $(goenv version-name) == $(goenv global).\n  typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide go version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]##########\n  # Nodenv color.\n  typeset -g POWERLEVEL9K_NODENV_FOREGROUND=70\n  # Hide node version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global)\n  # If set to false, hide node version if it's the same as global:\n  # $(nodenv version-name) == $(nodenv global).\n  typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide node version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]###############\n  # Nvm color.\n  typeset -g POWERLEVEL9K_NVM_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############\n  # Nodeenv color.\n  typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=70\n  # Don't show Node version next to the environment name.\n  typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false\n  # Separate environment name from Node version only with a space.\n  typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############################[ node_version: node.js version ]###############################\n  # Node version color.\n  typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=70\n  # Show node version only when in a directory tree containing package.json.\n  typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ go_version: go version (https://golang.org) ]########################\n  # Go version color.\n  typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=37\n  # Show go version only when in a go project subdirectory.\n  typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #################[ rust_version: rustc version (https://www.rust-lang.org) ]##################\n  # Rust version color.\n  typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=37\n  # Show rust version only when in a rust project subdirectory.\n  typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################\n  # .NET version color.\n  typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=134\n  # Show .NET version only when in a .NET project subdirectory.\n  typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################[ php_version: php version (https://www.php.net/) ]######################\n  # PHP version color.\n  typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=99\n  # Show PHP version only when in a PHP project subdirectory.\n  typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]###########\n  # Laravel version color.\n  typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=161\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ####################[ java_version: java version (https://www.java.com/) ]####################\n  # Java version color.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=32\n  # Show java version only when in a java project subdirectory.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true\n  # Show brief version.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]####\n  # Package color.\n  typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=117\n  # Package format. The following parameters are available within the expansion.\n  #\n  # - P9K_PACKAGE_NAME     The value of `name` field in package.json.\n  # - P9K_PACKAGE_VERSION  The value of `version` field in package.json.\n  #\n  # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\\%/%%}@${P9K_PACKAGE_VERSION//\\%/%%}'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]##############\n  # Rbenv color.\n  typeset -g POWERLEVEL9K_RBENV_FOREGROUND=168\n  # Hide ruby version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global)\n  # If set to false, hide ruby version if it's the same as global:\n  # $(rbenv version-name) == $(rbenv global).\n  typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide ruby version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ rvm: ruby version from rvm (https://rvm.io) ]########################\n  # Rvm color.\n  typeset -g POWERLEVEL9K_RVM_FOREGROUND=168\n  # Don't show @gemset at the end.\n  typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false\n  # Don't show ruby- at the front.\n  typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############\n  # Fvm color.\n  typeset -g POWERLEVEL9K_FVM_FOREGROUND=38\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]###########\n  # Lua color.\n  typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=32\n  # Hide lua version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global)\n  # If set to false, hide lua version if it's the same as global:\n  # $(luaenv version-name) == $(luaenv global).\n  typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide lua version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################\n  # Java color.\n  typeset -g POWERLEVEL9K_JENV_FOREGROUND=32\n  # Hide java version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global)\n  # If set to false, hide java version if it's the same as global:\n  # $(jenv version-name) == $(jenv global).\n  typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide java version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############\n  # Perl color.\n  typeset -g POWERLEVEL9K_PLENV_FOREGROUND=67\n  # Hide perl version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global)\n  # If set to false, hide perl version if it's the same as global:\n  # $(plenv version-name) == $(plenv global).\n  typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide perl version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############\n  # PHP color.\n  typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=99\n  # Hide php version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global)\n  # If set to false, hide php version if it's the same as global:\n  # $(phpenv version-name) == $(phpenv global).\n  typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide php version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]#######\n  # Scala color.\n  typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=160\n  # Hide scala version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global)\n  # If set to false, hide scala version if it's the same as global:\n  # $(scalaenv version-name) == $(scalaenv global).\n  typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide scala version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]###########\n  # Haskell color.\n  typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=172\n  # Hide haskell version if it doesn't come from one of these sources.\n  #\n  #   shell:  version is set by STACK_YAML\n  #   local:  version is set by stack.yaml up the directory tree\n  #   global: version is set by the implicit global project (~/.stack/global-project/stack.yaml)\n  typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local)\n  # If set to false, hide haskell version if it's the same as in the implicit global project.\n  typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]#############\n  # Show kubecontext only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show kubecontext.\n  # typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|flux|fluxctl|stern'\n\n  # Kubernetes context classes for the purpose of using different colors, icons and expansions with\n  # different contexts.\n  #\n  # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current kubernetes context gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       DEFAULT)\n  #\n  # If your current kubernetes context is \"deathray-testing/default\", its class is TEST\n  # because \"deathray-testing/default\" doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'       DEFAULT)\n  typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=134\n  # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext\n  # segment. Parameter expansions are very flexible and fast, too. See reference:\n  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion.\n  #\n  # Within the expansion the following parameters are always available:\n  #\n  # - P9K_CONTENT                The content that would've been displayed if there was no content\n  #                              expansion defined.\n  # - P9K_KUBECONTEXT_NAME       The current context's name. Corresponds to column NAME in the\n  #                              output of `kubectl config get-contexts`.\n  # - P9K_KUBECONTEXT_CLUSTER    The current context's cluster. Corresponds to column CLUSTER in the\n  #                              output of `kubectl config get-contexts`.\n  # - P9K_KUBECONTEXT_NAMESPACE  The current context's namespace. Corresponds to column NAMESPACE\n  #                              in the output of `kubectl config get-contexts`. If there is no\n  #                              namespace, the parameter is set to \"default\".\n  # - P9K_KUBECONTEXT_USER       The current context's user. Corresponds to column AUTHINFO in the\n  #                              output of `kubectl config get-contexts`.\n  #\n  # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS),\n  # the following extra parameters are available:\n  #\n  # - P9K_KUBECONTEXT_CLOUD_NAME     Either \"gke\" or \"eks\".\n  # - P9K_KUBECONTEXT_CLOUD_ACCOUNT  Account/project ID.\n  # - P9K_KUBECONTEXT_CLOUD_ZONE     Availability zone.\n  # - P9K_KUBECONTEXT_CLOUD_CLUSTER  Cluster.\n  #\n  # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example,\n  # if P9K_KUBECONTEXT_CLUSTER is \"gke_my-account_us-east1-a_my-cluster-01\":\n  #\n  #   - P9K_KUBECONTEXT_CLOUD_NAME=gke\n  #   - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account\n  #   - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a\n  #   - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01\n  #\n  # If P9K_KUBECONTEXT_CLUSTER is \"arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01\":\n  #\n  #   - P9K_KUBECONTEXT_CLOUD_NAME=eks\n  #   - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012\n  #   - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1\n  #   - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01\n  typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION=\n  # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME.\n  POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}'\n  # Append the current context's namespace if it's not \"default\".\n  POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}'\n\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%fat '\n\n  ################[ terraform: terraform workspace (https://www.terraform.io) ]#################\n  # Don't show terraform workspace if it's literally \"default\".\n  typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false\n  # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current terraform workspace gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       OTHER)\n  #\n  # If your current terraform workspace is \"project_test\", its class is TEST because \"project_test\"\n  # doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'         OTHER)\n  typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=38\n  # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ terraform_version: terraform version (https://www.terraform.io) ]##############\n  # Terraform version color.\n  typeset -g POWERLEVEL9K_TERRAFORM_VERSION_FOREGROUND=38\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TERRAFORM_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]#\n  # Show aws only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show aws.\n  typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt'\n\n  # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current AWS profile gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_AWS_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       DEFAULT)\n  #\n  # If your current AWS profile is \"company_test\", its class is TEST\n  # because \"company_test\" doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_AWS_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'       DEFAULT)\n  typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=208\n  # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # AWS segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_AWS_PROFILE  The name of the current AWS profile.\n  # - P9K_AWS_REGION   The region associated with the current AWS profile.\n  typeset -g POWERLEVEL9K_AWS_CONTENT_EXPANSION='${P9K_AWS_PROFILE//\\%/%%}${P9K_AWS_REGION:+ ${P9K_AWS_REGION//\\%/%%}}'\n\n  #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]#\n  # AWS Elastic Beanstalk environment color.\n  typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]##########\n  # Show azure only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show azure.\n  typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt'\n  # Azure account name color.\n  typeset -g POWERLEVEL9K_AZURE_FOREGROUND=32\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_AZURE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]###########\n  # Show gcloud only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show gcloud.\n  typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs'\n   # Google cloud color.\n  typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=32\n\n  # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or\n  # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative\n  # enough. You can use the following parameters in the expansions. Each of them corresponds to the\n  # output of `gcloud` tool.\n  #\n  #   Parameter                | Source\n  #   -------------------------|--------------------------------------------------------------------\n  #   P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)'\n  #   P9K_GCLOUD_ACCOUNT       | gcloud config get-value account\n  #   P9K_GCLOUD_PROJECT_ID    | gcloud config get-value project\n  #   P9K_GCLOUD_PROJECT_NAME  | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)'\n  #\n  # Note: ${VARIABLE//\\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'.\n  #\n  # Obtaining project name requires sending a request to Google servers. This can take a long time\n  # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud\n  # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets\n  # set and gcloud prompt segment transitions to state COMPLETE.\n  #\n  # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL\n  # and COMPLETE. You can also hide gcloud in state PARTIAL by setting\n  # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and\n  # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty.\n  typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\\%/%%}'\n  typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\\%/%%}'\n\n  # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name\n  # this often. Negative value disables periodic polling. In this mode project name is retrieved\n  # only when the current configuration, account or project id changes.\n  typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]#\n  # Show google_app_cred only when the the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show google_app_cred.\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt'\n\n  # Google application credentials classes for the purpose of using different colors, icons and\n  # expansions with different credentials.\n  #\n  # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first\n  # element in each pair defines a pattern against which the current kubernetes context gets\n  # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion\n  # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION\n  # parameters, you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order.\n  # The first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=(\n  #     '*:*prod*:*'  PROD\n  #     '*:*test*:*'  TEST\n  #     '*'           DEFAULT)\n  #\n  # If your current Google application credentials is \"service_account deathray-testing x@y.com\",\n  # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID'\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=(\n      # '*:*prod*:*'  PROD    # These values are examples that are unlikely\n      # '*:*test*:*'  TEST    # to match your needs. Customize them as needed.\n      '*'             DEFAULT)\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by\n  # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference:\n  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion.\n  #\n  # You can use the following parameters in the expansion. Each of them corresponds to one of the\n  # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS.\n  #\n  #   Parameter                        | JSON key file field\n  #   ---------------------------------+---------------\n  #   P9K_GOOGLE_APP_CRED_TYPE         | type\n  #   P9K_GOOGLE_APP_CRED_PROJECT_ID   | project_id\n  #   P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email\n  #\n  # Note: ${VARIABLE//\\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'.\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\\%/%%}'\n\n  ##############[ toolbox: toolbox name (https://github.com/containers/toolbox) ]###############\n  # Toolbox color.\n  typeset -g POWERLEVEL9K_TOOLBOX_FOREGROUND=178\n  # Don't display the name of the toolbox if it matches fedora-toolbox-*.\n  typeset -g POWERLEVEL9K_TOOLBOX_CONTENT_EXPANSION='${P9K_TOOLBOX_NAME:#fedora-toolbox-*}'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TOOLBOX_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_TOOLBOX_PREFIX='%fin '\n\n  ###############################[ public_ip: public IP address ]###############################\n  # Public IP color.\n  typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=94\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ########################[ vpn_ip: virtual private network indicator ]#########################\n  # VPN IP color.\n  typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=81\n  # When on VPN, show just an icon without the IP address.\n  # Tip: To display the private IP address when on VPN, remove the next line.\n  typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION=\n  # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN\n  # to see the name of the interface.\n  typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*'\n  # If set to true, show one segment per matching network interface. If set to false, show only\n  # one segment corresponding to the first matching network interface.\n  # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION.\n  typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ ip: ip address and bandwidth usage for a specified network interface ]###########\n  # IP color.\n  typeset -g POWERLEVEL9K_IP_FOREGROUND=38\n  # The following parameters are accessible within the expansion:\n  #\n  #   Parameter             | Meaning\n  #   ----------------------+-------------------------------------------\n  #   P9K_IP_IP             | IP address\n  #   P9K_IP_INTERFACE      | network interface\n  #   P9K_IP_RX_BYTES       | total number of bytes received\n  #   P9K_IP_TX_BYTES       | total number of bytes sent\n  #   P9K_IP_RX_BYTES_DELTA | number of bytes received since last prompt\n  #   P9K_IP_TX_BYTES_DELTA | number of bytes sent since last prompt\n  #   P9K_IP_RX_RATE        | receive rate (since last prompt)\n  #   P9K_IP_TX_RATE        | send rate (since last prompt)\n  typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='$P9K_IP_IP${P9K_IP_RX_RATE:+ %70F\u21e3$P9K_IP_RX_RATE}${P9K_IP_TX_RATE:+ %215F\u21e1$P9K_IP_TX_RATE}'\n  # Show information for the first network interface whose name matches this regular expression.\n  # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces.\n  typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #########################[ proxy: system-wide http/https/ftp proxy ]##########################\n  # Proxy color.\n  typeset -g POWERLEVEL9K_PROXY_FOREGROUND=68\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################################[ battery: internal battery ]#################################\n  # Show battery in red when it's below this level and not connected to power supply.\n  typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20\n  typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=160\n  # Show battery in green when it's charging or fully charged.\n  typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=70\n  # Show battery in yellow when it's discharging.\n  typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=178\n  # Battery pictograms going from low to high level of charge.\n  typeset -g POWERLEVEL9K_BATTERY_STAGES='\\uf58d\\uf579\\uf57a\\uf57b\\uf57c\\uf57d\\uf57e\\uf57f\\uf580\\uf581\\uf578'\n  # Don't show the remaining time to charge/discharge.\n  typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false\n\n  #####################################[ wifi: wifi speed ]#####################################\n  # WiFi color.\n  typeset -g POWERLEVEL9K_WIFI_FOREGROUND=68\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS).\n  #\n  #   # Wifi colors and icons for different signal strength levels (low to high).\n  #   typeset -g my_wifi_fg=(68 68 68 68 68)                           # <-- change these values\n  #   typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi')     # <-- change these values\n  #\n  #   typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps'\n  #   typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}'\n  #\n  # The following parameters are accessible within the expansions:\n  #\n  #   Parameter             | Meaning\n  #   ----------------------+---------------\n  #   P9K_WIFI_SSID         | service set identifier, a.k.a. network name\n  #   P9K_WIFI_LINK_AUTH    | authentication protocol such as \"wpa2-psk\" or \"none\"; empty if unknown\n  #   P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second\n  #   P9K_WIFI_RSSI         | signal strength in dBm, from -120 to 0\n  #   P9K_WIFI_NOISE        | noise in dBm, from -120 to 0\n  #   P9K_WIFI_BARS         | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE)\n\n  ####################################[ time: current time ]####################################\n  # Current time color.\n  typeset -g POWERLEVEL9K_TIME_FOREGROUND=66\n  # Format for the current time: 09:51:02. See `man 3 strftime`.\n  typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}'\n  # If set to true, time will update when you hit enter. This way prompts for the past\n  # commands will contain the start times of their commands as opposed to the default\n  # behavior where they contain the end times of their preceding commands.\n  typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_TIME_PREFIX='%fat '\n  \n  # Example of a user-defined prompt segment. Function prompt_example will be called on every\n  # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or\n  # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and orange text greeting the user.\n  #\n  # Type `p10k help segment` for documentation and a more sophisticated example.\n  function prompt_example() {\n    p10k segment -f 208 -i '\u2b50' -t 'hello, %n'\n  }\n\n  # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job\n  # is to generate the prompt segment for display in instant prompt. See\n  # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt.\n  #\n  # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function\n  # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k\n  # will replay these calls without actually calling instant_prompt_*. It is imperative that\n  # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this\n  # rule is not observed, the content of instant prompt will be incorrect.\n  #\n  # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If\n  # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt.\n  function instant_prompt_example() {\n    # Since prompt_example always makes the same `p10k segment` calls, we can call it from\n    # instant_prompt_example. This will give us the same `example` prompt segment in the instant\n    # and regular prompts.\n    prompt_example\n  }\n\n  # User-defined prompt segments can be customized the same way as built-in segments.\n  # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208\n  # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt\n  # when accepting a command line. Supported values:\n  #\n  #   - off:      Don't change prompt when accepting a command line.\n  #   - always:   Trim down prompt when accepting a command line.\n  #   - same-dir: Trim down prompt when accepting a command line unless this is the first command\n  #               typed after changing current working directory.\n  typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=same-dir\n\n  # Instant prompt mode.\n  #\n  #   - off:     Disable instant prompt. Choose this if you've tried instant prompt and found\n  #              it incompatible with your zsh configuration files.\n  #   - quiet:   Enable instant prompt and don't print warnings when detecting console output\n  #              during zsh initialization. Choose this if you've read and understood\n  #              https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt.\n  #   - verbose: Enable instant prompt and print a warning when detecting console output during\n  #              zsh initialization. Choose this if you've never tried instant prompt, haven't\n  #              seen the warning, or if you are unsure what this all means.\n  typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose\n\n  # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized.\n  # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload\n  # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you\n  # really need it.\n  typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true\n\n  # If p10k is already loaded, reload configuration.\n  # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true.\n  (( ! $+functions[p10k] )) || p10k reload\n}\n\n# Tell `p10k configure` which file it should overwrite.\ntypeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a}\n\n(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]}\n'builtin' 'unset' 'p10k_config_opts'\n", "meta": {"author": "ryan-bever", "repo": "dotfiles", "sha": "3ee722300dfe39733eab52e8b51f678cf70afebb", "save_path": "github-repos/lean/ryan-bever-dotfiles", "path": "github-repos/lean/ryan-bever-dotfiles/dotfiles-3ee722300dfe39733eab52e8b51f678cf70afebb/dotfiles/.p10k.zsh.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.011331751861933095, "lm_q2_score": 0.008985427848608006, "lm_q1q2_score": 0.00010182063875372926}}
{"text": "# Generated by Powerlevel10k configuration wizard on 2022-10-18 at 08:38 CDT.\n# Based on romkatv/powerlevel10k/config/p10k-lean.zsh, checksum 30611.\n# Wizard options: nerdfont-complete + powerline, small icons, unicode, lean, 12h time,\n# 2 lines, solid, no frame, darkest-ornaments, sparse, few icons, concise,\n# instant_prompt=verbose.\n# Type `p10k configure` to generate another config.\n#\n# Config for Powerlevel10k with lean prompt style. Type `p10k configure` to generate\n# your own config based on it.\n#\n# Tip: Looking for a nice color? Here's a one-liner to print colormap.\n#\n#   for i in {0..255}; do print -Pn \"%K{$i}  %k%F{$i}${(l:3::0:)i}%f \" ${${(M)$((i%6)):#3}:+$'\\n'}; done\n\n# Temporarily change options.\n'builtin' 'local' '-a' 'p10k_config_opts'\n[[ ! -o 'aliases'         ]] || p10k_config_opts+=('aliases')\n[[ ! -o 'sh_glob'         ]] || p10k_config_opts+=('sh_glob')\n[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand')\n'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand'\n\n() {\n  emulate -L zsh -o extended_glob\n\n  # Unset all configuration options. This allows you to apply configuration changes without\n  # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`.\n  unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR'\n\n  # Zsh >= 5.1 is required.\n  [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return\n\n  # The list of segments shown on the left. Fill it with the most important segments.\n  typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(\n    # =========================[ Line #1 ]=========================\n    # os_icon               # os identifier\n    dir                     # current directory\n    vcs                     # git status\n    # =========================[ Line #2 ]=========================\n    newline                 # \\n\n    prompt_char             # prompt symbol\n  )\n\n  # The list of segments shown on the right. Fill it with less important segments.\n  # Right prompt on the last prompt line (where you are typing your commands) gets\n  # automatically hidden when the input line reaches it. Right prompt above the\n  # last prompt line gets hidden if it would overlap with left prompt.\n  typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(\n    # =========================[ Line #1 ]=========================\n    status                  # exit code of the last command\n    command_execution_time  # duration of the last command\n    background_jobs         # presence of background jobs\n    direnv                  # direnv status (https://direnv.net/)\n    asdf                    # asdf version manager (https://github.com/asdf-vm/asdf)\n    virtualenv              # python virtual environment (https://docs.python.org/3/library/venv.html)\n    anaconda                # conda environment (https://conda.io/)\n    pyenv                   # python environment (https://github.com/pyenv/pyenv)\n    goenv                   # go environment (https://github.com/syndbg/goenv)\n    nodenv                  # node.js version from nodenv (https://github.com/nodenv/nodenv)\n    nvm                     # node.js version from nvm (https://github.com/nvm-sh/nvm)\n    nodeenv                 # node.js environment (https://github.com/ekalinin/nodeenv)\n    # node_version          # node.js version\n    # go_version            # go version (https://golang.org)\n    # rust_version          # rustc version (https://www.rust-lang.org)\n    # dotnet_version        # .NET version (https://dotnet.microsoft.com)\n    # php_version           # php version (https://www.php.net/)\n    # laravel_version       # laravel php framework version (https://laravel.com/)\n    # java_version          # java version (https://www.java.com/)\n    # package               # name@version from package.json (https://docs.npmjs.com/files/package.json)\n    rbenv                   # ruby version from rbenv (https://github.com/rbenv/rbenv)\n    rvm                     # ruby version from rvm (https://rvm.io)\n    fvm                     # flutter version management (https://github.com/leoafarias/fvm)\n    luaenv                  # lua version from luaenv (https://github.com/cehoffman/luaenv)\n    jenv                    # java version from jenv (https://github.com/jenv/jenv)\n    plenv                   # perl version from plenv (https://github.com/tokuhirom/plenv)\n    perlbrew                # perl version from perlbrew (https://github.com/gugod/App-perlbrew)\n    phpenv                  # php version from phpenv (https://github.com/phpenv/phpenv)\n    scalaenv                # scala version from scalaenv (https://github.com/scalaenv/scalaenv)\n    haskell_stack           # haskell version from stack (https://haskellstack.org/)\n    kubecontext             # current kubernetes context (https://kubernetes.io/)\n    terraform               # terraform workspace (https://www.terraform.io)\n    # terraform_version     # terraform version (https://www.terraform.io)\n    aws                     # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html)\n    aws_eb_env              # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/)\n    azure                   # azure account name (https://docs.microsoft.com/en-us/cli/azure)\n    gcloud                  # google cloud cli account and project (https://cloud.google.com/)\n    google_app_cred         # google application credentials (https://cloud.google.com/docs/authentication/production)\n    toolbox                 # toolbox name (https://github.com/containers/toolbox)\n    context                 # user@hostname\n    nordvpn                 # nordvpn connection status, linux only (https://nordvpn.com/)\n    ranger                  # ranger shell (https://github.com/ranger/ranger)\n    nnn                     # nnn shell (https://github.com/jarun/nnn)\n    xplr                    # xplr shell (https://github.com/sayanarijit/xplr)\n    vim_shell               # vim shell indicator (:sh)\n    midnight_commander      # midnight commander shell (https://midnight-commander.org/)\n    nix_shell               # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html)\n    # vpn_ip                # virtual private network indicator\n    # load                  # CPU load\n    # disk_usage            # disk usage\n    ram                   # free RAM\n    # swap                  # used swap\n    todo                    # todo items (https://github.com/todotxt/todo.txt-cli)\n    timewarrior             # timewarrior tracking status (https://timewarrior.net/)\n    taskwarrior             # taskwarrior task count (https://taskwarrior.org/)\n    # cpu_arch              # CPU architecture\n    time                    # current time\n    # =========================[ Line #2 ]=========================\n    newline\n    # ip                    # ip address and bandwidth usage for a specified network interface\n    # public_ip             # public IP address\n    # proxy                 # system-wide http/https/ftp proxy\n    # battery               # internal battery\n    # wifi                  # wifi speed\n    # example               # example user-defined segment (see prompt_example function below)\n  )\n\n  # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you.\n  typeset -g POWERLEVEL9K_MODE=nerdfont-complete\n  # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid\n  # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added.\n  typeset -g POWERLEVEL9K_ICON_PADDING=none\n\n  # Basic style options that define the overall look of your prompt. You probably don't want to\n  # change them.\n  typeset -g POWERLEVEL9K_BACKGROUND=                            # transparent background\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE=  # no surrounding whitespace\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' '  # separate segments with a space\n  typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR=        # no end-of-line symbol\n\n  # When set to true, icons appear before content on both sides of the prompt. When set\n  # to false, icons go after content. If empty or not set, icons go before content in the left\n  # prompt and after content in the right prompt.\n  #\n  # You can also override it for a specific segment:\n  #\n  #   POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false\n  #\n  # Or for a specific segment in specific state:\n  #\n  #   POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false\n  typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT=true\n\n  # Add an empty line before each prompt.\n  typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true\n\n  # Connect left prompt lines with these symbols.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX=\n  # Connect right prompt lines with these symbols.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX=\n  typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX=\n\n  # The left end of left prompt.\n  typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=\n  # The right end of right prompt.\n  typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL=\n\n  # Ruler, a.k.a. the horizontal line before each prompt. If you set it to true, you'll\n  # probably want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false above and\n  # POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' below.\n  typeset -g POWERLEVEL9K_SHOW_RULER=false\n  typeset -g POWERLEVEL9K_RULER_CHAR='\u2500'        # reasonable alternative: '\u00b7'\n  typeset -g POWERLEVEL9K_RULER_FOREGROUND=238\n\n  # Filler between left and right prompt on the first prompt line. You can set it to '\u00b7' or '\u2500'\n  # to make it easier to see the alignment between left and right prompt and to separate prompt\n  # from command output. It serves the same purpose as ruler (see above) without increasing\n  # the number of prompt lines. You'll probably want to set POWERLEVEL9K_SHOW_RULER=false\n  # if using this. You might also like POWERLEVEL9K_PROMPT_ADD_NEWLINE=false for more compact\n  # prompt.\n  typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR='\u2500'\n  if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then\n    # The color of the filler.\n    typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=238\n    # Add a space between the end of left prompt and the filler.\n    typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=' '\n    # Add a space between the filler and the start of right prompt.\n    typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' '\n    # Start filler from the edge of the screen if there are no left segments on the first line.\n    typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}'\n    # End filler on the edge of the screen if there are no right segments on the first line.\n    typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}'\n  fi\n\n  #################################[ os_icon: os identifier ]##################################\n  # OS identifier color.\n  typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='\u2b50'\n\n  ################################[ prompt_char: prompt symbol ]################################\n  # Green prompt symbol if the last command succeeded.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76\n  # Red prompt symbol if the last command failed.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196\n  # Default prompt symbol.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='\u276f'\n  # Prompt symbol in command vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='\u276e'\n  # Prompt symbol in visual vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V'\n  # Prompt symbol in overwrite vi mode.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='\u25b6'\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true\n  # No line terminator if prompt_char is the last segment.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=''\n  # No line introducer if prompt_char is the first segment.\n  typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL=\n\n  ##################################[ dir: current directory ]##################################\n  # Default current directory color.\n  typeset -g POWERLEVEL9K_DIR_FOREGROUND=31\n  # If directory is too long, shorten some of its segments to the shortest possible unique\n  # prefix. The shortened directory can be tab-completed to the original.\n  typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique\n  # Replace removed segment suffixes with this symbol.\n  typeset -g POWERLEVEL9K_SHORTEN_DELIMITER=\n  # Color of the shortened directory segments.\n  typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=103\n  # Color of the anchor directory segments. Anchor segments are never shortened. The first\n  # segment is always an anchor.\n  typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=39\n  # Display anchor directory segments in bold.\n  typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true\n  # Don't shorten directories that contain any of these files. They are anchors.\n  local anchor_files=(\n    .bzr\n    .citc\n    .git\n    .hg\n    .node-version\n    .python-version\n    .go-version\n    .ruby-version\n    .lua-version\n    .java-version\n    .perl-version\n    .php-version\n    .tool-version\n    .shorten_folder_marker\n    .svn\n    .terraform\n    CVS\n    Cargo.toml\n    composer.json\n    go.mod\n    package.json\n    stack.yaml\n  )\n  typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER=\"(${(j:|:)anchor_files})\"\n  # If set to \"first\" (\"last\"), remove everything before the first (last) subdirectory that contains\n  # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is\n  # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first)\n  # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers\n  # and other directories don't.\n  #\n  # Optionally, \"first\" and \"last\" can be followed by \":<offset>\" where <offset> is an integer.\n  # This moves the truncation point to the right (positive offset) or to the left (negative offset)\n  # relative to the marker. Plain \"first\" and \"last\" are equivalent to \"first:0\" and \"last:0\"\n  # respectively.\n  typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false\n  # Don't shorten this many last directory segments. They are anchors.\n  typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1\n  # Shorten directory if it's longer than this even if there is space for it. The value can\n  # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty,\n  # directory will be shortened only when prompt doesn't fit or when other parameters demand it\n  # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below).\n  # If set to `0`, directory will always be shortened to its minimum length.\n  typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80\n  # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this\n  # many columns for typing commands.\n  typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40\n  # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least\n  # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands.\n  typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50\n  # If set to true, embed a hyperlink into the directory. Useful for quickly\n  # opening a directory in the file manager simply by clicking the link.\n  # Can also be handy when the directory is shortened, as it allows you to see\n  # the full directory that was used in previous commands.\n  typeset -g POWERLEVEL9K_DIR_HYPERLINK=false\n\n  # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON\n  # and POWERLEVEL9K_DIR_CLASSES below.\n  typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3\n\n  # The default icon shown next to non-writable and non-existent directories when\n  # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3.\n  # typeset -g POWERLEVEL9K_LOCK_ICON='\u2b50'\n\n  # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different\n  # directories. It must be an array with 3 * N elements. Each triplet consists of:\n  #\n  #   1. A pattern against which the current directory ($PWD) is matched. Matching is done with\n  #      extended_glob option enabled.\n  #   2. Directory class for the purpose of styling.\n  #   3. An empty string.\n  #\n  # Triplets are tried in order. The first triplet whose pattern matches $PWD wins.\n  #\n  # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories\n  # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_DIR_CLASSES=(\n  #     '~/work(|/*)'  WORK     ''\n  #     '~(|/*)'       HOME     ''\n  #     '*'            DEFAULT  '')\n  #\n  # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one\n  # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or\n  # WORK_NON_EXISTENT.\n  #\n  # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an\n  # option to define custom colors and icons for different directory classes.\n  #\n  #   # Styling for WORK.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=39\n  #\n  #   # Styling for WORK_NOT_WRITABLE.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=39\n  #\n  #   # Styling for WORK_NON_EXISTENT.\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=31\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=103\n  #   typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=39\n  #\n  # If a styling parameter isn't explicitly defined for some class, it falls back to the classless\n  # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls\n  # back to POWERLEVEL9K_DIR_FOREGROUND.\n  #\n  typeset -g POWERLEVEL9K_DIR_CLASSES=()\n\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_DIR_PREFIX='%fin '\n\n  #####################################[ vcs: git status ]######################################\n  # Branch icon. Set this parameter to '\\UE0A0 ' for the popular Powerline branch icon.\n  typeset -g POWERLEVEL9K_VCS_BRANCH_ICON=\n\n  # Untracked files icon. It's really a question mark, your font isn't broken.\n  # Change the value of this parameter to show a different icon.\n  typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?'\n\n  # Formatter for Git status.\n  #\n  # Example output: master wip \u21e342\u21e142 *42 merge ~42 +42 !42 ?42.\n  #\n  # You can edit the function to customize how Git status looks.\n  #\n  # VCS_STATUS_* parameters are set by gitstatus plugin. See reference:\n  # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh.\n  function my_git_formatter() {\n    emulate -L zsh\n\n    if [[ -n $P9K_CONTENT ]]; then\n      # If P9K_CONTENT is not empty, use it. It's either \"loading\" or from vcs_info (not from\n      # gitstatus plugin). VCS_STATUS_* parameters are not available in this case.\n      typeset -g my_git_format=$P9K_CONTENT\n      return\n    fi\n\n    if (( $1 )); then\n      # Styling for up-to-date Git status.\n      local       meta='%f'     # default foreground\n      local      clean='%76F'   # green foreground\n      local   modified='%178F'  # yellow foreground\n      local  untracked='%39F'   # blue foreground\n      local conflicted='%196F'  # red foreground\n    else\n      # Styling for incomplete and stale Git status.\n      local       meta='%244F'  # grey foreground\n      local      clean='%244F'  # grey foreground\n      local   modified='%244F'  # grey foreground\n      local  untracked='%244F'  # grey foreground\n      local conflicted='%244F'  # grey foreground\n    fi\n\n    local res\n\n    if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then\n      local branch=${(V)VCS_STATUS_LOCAL_BRANCH}\n      # If local branch name is at most 32 characters long, show it in full.\n      # Otherwise show the first 12 \u2026 the last 12.\n      # Tip: To always show local branch name in full without truncation, delete the next line.\n      (( $#branch > 32 )) && branch[13,-13]=\"\u2026\"  # <-- this line\n      res+=\"${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\\%/%%}\"\n    fi\n\n    if [[ -n $VCS_STATUS_TAG\n          # Show tag only if not on a branch.\n          # Tip: To always show tag, delete the next line.\n          && -z $VCS_STATUS_LOCAL_BRANCH  # <-- this line\n        ]]; then\n      local tag=${(V)VCS_STATUS_TAG}\n      # If tag name is at most 32 characters long, show it in full.\n      # Otherwise show the first 12 \u2026 the last 12.\n      # Tip: To always show tag name in full without truncation, delete the next line.\n      (( $#tag > 32 )) && tag[13,-13]=\"\u2026\"  # <-- this line\n      res+=\"${meta}#${clean}${tag//\\%/%%}\"\n    fi\n\n    # Display the current Git commit if there is no branch and no tag.\n    # Tip: To always display the current Git commit, delete the next line.\n    [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_TAG ]] &&  # <-- this line\n      res+=\"${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}\"\n\n    # Show tracking branch name if it differs from local branch.\n    if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then\n      res+=\"${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\\%/%%}\"\n    fi\n\n    # Display \"wip\" if the latest commit's summary contains \"wip\" or \"WIP\".\n    if [[ $VCS_STATUS_COMMIT_SUMMARY == (|*[^[:alnum:]])(wip|WIP)(|[^[:alnum:]]*) ]]; then\n      res+=\" ${modified}wip\"\n    fi\n\n    # \u21e342 if behind the remote.\n    (( VCS_STATUS_COMMITS_BEHIND )) && res+=\" ${clean}\u21e3${VCS_STATUS_COMMITS_BEHIND}\"\n    # \u21e142 if ahead of the remote; no leading space if also behind the remote: \u21e342\u21e142.\n    (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=\" \"\n    (( VCS_STATUS_COMMITS_AHEAD  )) && res+=\"${clean}\u21e1${VCS_STATUS_COMMITS_AHEAD}\"\n    # \u21e042 if behind the push remote.\n    (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=\" ${clean}\u21e0${VCS_STATUS_PUSH_COMMITS_BEHIND}\"\n    (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=\" \"\n    # \u21e242 if ahead of the push remote; no leading space if also behind: \u21e042\u21e242.\n    (( VCS_STATUS_PUSH_COMMITS_AHEAD  )) && res+=\"${clean}\u21e2${VCS_STATUS_PUSH_COMMITS_AHEAD}\"\n    # *42 if have stashes.\n    (( VCS_STATUS_STASHES        )) && res+=\" ${clean}*${VCS_STATUS_STASHES}\"\n    # 'merge' if the repo is in an unusual state.\n    [[ -n $VCS_STATUS_ACTION     ]] && res+=\" ${conflicted}${VCS_STATUS_ACTION}\"\n    # ~42 if have merge conflicts.\n    (( VCS_STATUS_NUM_CONFLICTED )) && res+=\" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}\"\n    # +42 if have staged changes.\n    (( VCS_STATUS_NUM_STAGED     )) && res+=\" ${modified}+${VCS_STATUS_NUM_STAGED}\"\n    # !42 if have unstaged changes.\n    (( VCS_STATUS_NUM_UNSTAGED   )) && res+=\" ${modified}!${VCS_STATUS_NUM_UNSTAGED}\"\n    # ?42 if have untracked files. It's really a question mark, your font isn't broken.\n    # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon.\n    # Remove the next line if you don't want to see untracked files at all.\n    (( VCS_STATUS_NUM_UNTRACKED  )) && res+=\" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}\"\n    # \"\u2500\" if the number of unstaged files is unknown. This can happen due to\n    # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower\n    # than the number of files in the Git index, or due to bash.showDirtyState being set to false\n    # in the repository config. The number of staged and untracked files may also be unknown\n    # in this case.\n    (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=\" ${modified}\u2500\"\n\n    typeset -g my_git_format=$res\n  }\n  functions -M my_git_formatter 2>/dev/null\n\n  # Don't count the number of unstaged, untracked and conflicted files in Git repositories with\n  # more than this many files in the index. Negative value means infinity.\n  #\n  # If you are working in Git repositories with tens of millions of files and seeing performance\n  # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output\n  # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's\n  # config: `git config bash.showDirtyState false`.\n  typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1\n\n  # Don't show Git status in prompt for repositories whose workdir matches this pattern.\n  # For example, if set to '~', the Git repository at $HOME/.git will be ignored.\n  # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'.\n  typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~'\n\n  # Disable the default Git status formatting.\n  typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true\n  # Install our own Git status formatter.\n  typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}'\n  typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}'\n  # Enable counters for staged, unstaged, etc.\n  typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1\n\n  # Icon color.\n  typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=76\n  typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR=244\n  # Custom icon.\n  typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION=\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_VCS_PREFIX='%fon '\n\n  # Show status of repositories of these types. You can add svn and/or hg if you are\n  # using them. If you do, your prompt may become slow even when your current directory\n  # isn't in an svn or hg repository.\n  typeset -g POWERLEVEL9K_VCS_BACKENDS=(git)\n\n  # These settings are used for repositories other than Git or when gitstatusd fails and\n  # Powerlevel10k has to fall back to using vcs_info.\n  typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=76\n  typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=76\n  typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=178\n\n  ##########################[ status: exit code of the last command ]###########################\n  # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and\n  # style them independently from the regular OK and ERROR state.\n  typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true\n\n  # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as\n  # it will signify success by turning green.\n  typeset -g POWERLEVEL9K_STATUS_OK=false\n  typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=70\n  typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='\u2714'\n\n  # Status when some part of a pipe command fails but the overall exit status is zero. It may look\n  # like this: 1|0.\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=70\n  typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='\u2714'\n\n  # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as\n  # it will signify error by turning red.\n  typeset -g POWERLEVEL9K_STATUS_ERROR=false\n  typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=160\n  typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  # Status when the last command was terminated by a signal.\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=160\n  # Use terse signal names: \"INT\" instead of \"SIGINT(2)\".\n  typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false\n  typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  # Status when some part of a pipe command fails and the overall exit status is also non-zero.\n  # It may look like this: 1|0.\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=160\n  typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='\u2718'\n\n  ###################[ command_execution_time: duration of the last command ]###################\n  # Show duration of the last command if takes at least this many seconds.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3\n  # Show this many fractional digits. Zero means round to seconds.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0\n  # Execution time color.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=101\n  # Duration format: 1d 2h 3m 4s.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s'\n  # Custom icon.\n  typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION=\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%ftook '\n\n  #######################[ background_jobs: presence of background jobs ]#######################\n  # Don't show the number of background jobs.\n  typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false\n  # Background jobs color.\n  typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ direnv: direnv status (https://direnv.net/) ]########################\n  # Direnv color.\n  typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]###############\n  # Default asdf color. Only used to display tools for which there is no color override (see below).\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND.\n  typeset -g POWERLEVEL9K_ASDF_FOREGROUND=66\n\n  # There are four parameters that can be used to hide asdf tools. Each parameter describes\n  # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at\n  # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to\n  # hide a tool, it gets shown.\n  #\n  # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and\n  # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands:\n  #\n  #   asdf local  python 3.8.1\n  #   asdf global python 3.8.1\n  #\n  # After running both commands the current python version is 3.8.1 and its source is \"local\" as\n  # it takes precedence over \"global\". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false,\n  # it'll hide python version in this case because 3.8.1 is the same as the global version.\n  # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't\n  # contain \"local\".\n\n  # Hide tool versions that don't come from one of these sources.\n  #\n  # Available sources:\n  #\n  # - shell   `asdf current` says \"set by ASDF_${TOOL}_VERSION environment variable\"\n  # - local   `asdf current` says \"set by /some/not/home/directory/file\"\n  # - global  `asdf current` says \"set by /home/username/file\"\n  #\n  # Note: If this parameter is set to (shell local global), it won't hide tools.\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES.\n  typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global)\n\n  # If set to false, hide tool versions that are the same as global.\n  #\n  # Note: The name of this parameter doesn't reflect its meaning at all.\n  # Note: If this parameter is set to true, it won't hide tools.\n  # Tip:  Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW.\n  typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false\n\n  # If set to false, hide tool versions that are equal to \"system\".\n  #\n  # Note: If this parameter is set to true, it won't hide tools.\n  # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM.\n  typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true\n\n  # If set to non-empty value, hide tools unless there is a file matching the specified file pattern\n  # in the current directory, or its parent directory, or its grandparent directory, and so on.\n  #\n  # Note: If this parameter is set to empty value, it won't hide tools.\n  # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments.\n  # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB.\n  #\n  # Example: Hide nodejs version when there is no package.json and no *.js files in the current\n  # directory, in `..`, in `../..` and so on.\n  #\n  #   typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json'\n  typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB=\n\n  # Ruby version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=168\n  # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Python version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Go version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Node.js version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=70\n  # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Rust version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=37\n  # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # .NET Core version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=134\n  # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_DOTNET_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Flutter version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=38\n  # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Lua version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Java version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Perl version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=67\n  # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Erlang version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=125\n  # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Elixir version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=129\n  # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Postgres version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=31\n  # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # PHP version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=99\n  # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Haskell version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=172\n  # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  # Julia version from asdf.\n  typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=70\n  # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar'\n\n  ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]###########\n  # NordVPN connection indicator color.\n  typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=39\n  # Hide NordVPN connection indicator when not connected.\n  typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION=\n  typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]##################\n  # Ranger shell color.\n  typeset -g POWERLEVEL9K_RANGER_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]#######################\n  # Nnn shell color.\n  typeset -g POWERLEVEL9K_NNN_FOREGROUND=72\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################[ xplr: xplr shell (https://github.com/sayanarijit/xplr) ]##################\n  # xplr shell color.\n  typeset -g POWERLEVEL9K_XPLR_FOREGROUND=72\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_XPLR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########################[ vim_shell: vim shell indicator (:sh) ]###########################\n  # Vim shell indicator color.\n  typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=34\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]######\n  # Midnight Commander shell color.\n  typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=178\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]##\n  # Nix shell color.\n  typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=74\n\n  # Tip: If you want to see just the icon without \"pure\" and \"impure\", uncomment the next line.\n  # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################################[ disk_usage: disk usage ]##################################\n  # Colors for different levels of disk usage.\n  typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=35\n  typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=220\n  typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=160\n  # Thresholds for different levels of disk usage (percentage points).\n  typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90\n  typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95\n  # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent.\n  typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################################[ ram: free RAM ]#######################################\n  # RAM color.\n  typeset -g POWERLEVEL9K_RAM_FOREGROUND=66\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################################[ swap: used swap ]######################################\n  # Swap color.\n  typeset -g POWERLEVEL9K_SWAP_FOREGROUND=96\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ######################################[ load: CPU load ]######################################\n  # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15.\n  typeset -g POWERLEVEL9K_LOAD_WHICH=5\n  # Load color when load is under 50%.\n  typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=66\n  # Load color when load is between 50% and 70%.\n  typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=178\n  # Load color when load is over 70%.\n  typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=166\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################\n  # Todo color.\n  typeset -g POWERLEVEL9K_TODO_FOREGROUND=110\n  # Hide todo when the total number of tasks is zero.\n  typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true\n  # Hide todo when the number of tasks after filtering is zero.\n  typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false\n\n  # Todo format. The following parameters are available within the expansion.\n  #\n  # - P9K_TODO_TOTAL_TASK_COUNT     The total number of tasks.\n  # - P9K_TODO_FILTERED_TASK_COUNT  The number of tasks after filtering.\n  #\n  # These variables correspond to the last line of the output of `todo.sh -p ls`:\n  #\n  #   TODO: 24 of 42 tasks shown\n  #\n  # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT.\n  #\n  # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############\n  # Timewarrior color.\n  typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=110\n  # If the tracked task is longer than 24 characters, truncate and append \"\u2026\".\n  # Tip: To always display tasks without truncation, delete the following parameter.\n  # Tip: To hide task names and display just the icon when time tracking is enabled, set the\n  # value of the following parameter to \"\".\n  typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+\u2026}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]##############\n  # Taskwarrior color.\n  typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=74\n\n  # Taskwarrior segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_TASKWARRIOR_PENDING_COUNT   The number of pending tasks: `task +PENDING count`.\n  # - P9K_TASKWARRIOR_OVERDUE_COUNT   The number of overdue tasks: `task +OVERDUE count`.\n  #\n  # Zero values are represented as empty parameters.\n  #\n  # The default format:\n  #\n  #   '${P9K_TASKWARRIOR_OVERDUE_COUNT:+\"!$P9K_TASKWARRIOR_OVERDUE_COUNT/\"}$P9K_TASKWARRIOR_PENDING_COUNT'\n  #\n  # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################################[ cpu_arch: CPU architecture ]################################\n  # CPU architecture color.\n  typeset -g POWERLEVEL9K_CPU_ARCH_FOREGROUND=172\n\n  # Hide the segment when on a specific CPU architecture.\n  # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_CONTENT_EXPANSION=\n  # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_VISUAL_IDENTIFIER_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_CPU_ARCH_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##################################[ context: user@hostname ]##################################\n  # Context color when running with privileges.\n  typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=178\n  # Context color in SSH without privileges.\n  typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=180\n  # Default context color (no privileges, no SSH).\n  typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=180\n\n  # Context format when running with privileges: bold user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m'\n  # Context format when in SSH without privileges: user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m'\n  # Default context format (no privileges, no SSH): user@hostname.\n  typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m'\n\n  # Don't show context unless running with privileges or in SSH.\n  # Tip: Remove the next line to always show context.\n  typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION=\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%fwith '\n\n  ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]###\n  # Python virtual environment color.\n  typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=37\n  # Don't show Python version next to the virtual environment name.\n  typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false\n  # If set to \"false\", won't show virtualenv if pyenv is already shown.\n  # If set to \"if-different\", won't show virtualenv if it's the same as pyenv.\n  typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false\n  # Separate environment name from Python version only with a space.\n  typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################[ anaconda: conda environment (https://conda.io/) ]######################\n  # Anaconda environment color.\n  typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=37\n\n  # Anaconda segment format. The following parameters are available within the expansion.\n  #\n  # - CONDA_PREFIX                 Absolute path to the active Anaconda/Miniconda environment.\n  # - CONDA_DEFAULT_ENV            Name of the active Anaconda/Miniconda environment.\n  # - CONDA_PROMPT_MODIFIER        Configurable prompt modifier (see below).\n  # - P9K_ANACONDA_PYTHON_VERSION  Current python version (python --version).\n  #\n  # CONDA_PROMPT_MODIFIER can be configured with the following command:\n  #\n  #   conda config --set env_prompt '({default_env}) '\n  #\n  # The last argument is a Python format string that can use the following variables:\n  #\n  # - prefix       The same as CONDA_PREFIX.\n  # - default_env  The same as CONDA_DEFAULT_ENV.\n  # - name         The last segment of CONDA_PREFIX.\n  # - stacked_env  Comma-separated list of names in the environment stack. The first element is\n  #                always the same as default_env.\n  #\n  # Note: '({default_env}) ' is the default value of env_prompt.\n  #\n  # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER\n  # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former\n  # is empty.\n  typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\\(}% }%\\)}:-${CONDA_PREFIX:t}}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################\n  # Pyenv color.\n  typeset -g POWERLEVEL9K_PYENV_FOREGROUND=37\n  # Hide python version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global)\n  # If set to false, hide python version if it's the same as global:\n  # $(pyenv version-name) == $(pyenv global).\n  typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide python version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true\n\n  # Pyenv segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_CONTENT                Current pyenv environment (pyenv version-name).\n  # - P9K_PYENV_PYTHON_VERSION   Current python version (python --version).\n  #\n  # The default format has the following logic:\n  #\n  # 1. Display just \"$P9K_CONTENT\" if it's equal to \"$P9K_PYENV_PYTHON_VERSION\" or\n  #    starts with \"$P9K_PYENV_PYTHON_VERSION/\".\n  # 2. Otherwise display \"$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION\".\n  typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_CONTENT:#$P9K_PYENV_PYTHON_VERSION(|/*)}:+ $P9K_PYENV_PYTHON_VERSION}'\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################\n  # Goenv color.\n  typeset -g POWERLEVEL9K_GOENV_FOREGROUND=37\n  # Hide go version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global)\n  # If set to false, hide go version if it's the same as global:\n  # $(goenv version-name) == $(goenv global).\n  typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide go version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]##########\n  # Nodenv color.\n  typeset -g POWERLEVEL9K_NODENV_FOREGROUND=70\n  # Hide node version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global)\n  # If set to false, hide node version if it's the same as global:\n  # $(nodenv version-name) == $(nodenv global).\n  typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide node version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]###############\n  # Nvm color.\n  typeset -g POWERLEVEL9K_NVM_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############\n  # Nodeenv color.\n  typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=70\n  # Don't show Node version next to the environment name.\n  typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false\n  # Separate environment name from Node version only with a space.\n  typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER=\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##############################[ node_version: node.js version ]###############################\n  # Node version color.\n  typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=70\n  # Show node version only when in a directory tree containing package.json.\n  typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ go_version: go version (https://golang.org) ]########################\n  # Go version color.\n  typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=37\n  # Show go version only when in a go project subdirectory.\n  typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #################[ rust_version: rustc version (https://www.rust-lang.org) ]##################\n  # Rust version color.\n  typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=37\n  # Show rust version only when in a rust project subdirectory.\n  typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################\n  # .NET version color.\n  typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=134\n  # Show .NET version only when in a .NET project subdirectory.\n  typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #####################[ php_version: php version (https://www.php.net/) ]######################\n  # PHP version color.\n  typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=99\n  # Show PHP version only when in a PHP project subdirectory.\n  typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]###########\n  # Laravel version color.\n  typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=161\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ####################[ java_version: java version (https://www.java.com/) ]####################\n  # Java version color.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=32\n  # Show java version only when in a java project subdirectory.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true\n  # Show brief version.\n  typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]####\n  # Package color.\n  typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=117\n  # Package format. The following parameters are available within the expansion.\n  #\n  # - P9K_PACKAGE_NAME     The value of `name` field in package.json.\n  # - P9K_PACKAGE_VERSION  The value of `version` field in package.json.\n  #\n  # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\\%/%%}@${P9K_PACKAGE_VERSION//\\%/%%}'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]##############\n  # Rbenv color.\n  typeset -g POWERLEVEL9K_RBENV_FOREGROUND=168\n  # Hide ruby version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global)\n  # If set to false, hide ruby version if it's the same as global:\n  # $(rbenv version-name) == $(rbenv global).\n  typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide ruby version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######################[ rvm: ruby version from rvm (https://rvm.io) ]########################\n  # Rvm color.\n  typeset -g POWERLEVEL9K_RVM_FOREGROUND=168\n  # Don't show @gemset at the end.\n  typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false\n  # Don't show ruby- at the front.\n  typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############\n  # Fvm color.\n  typeset -g POWERLEVEL9K_FVM_FOREGROUND=38\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]###########\n  # Lua color.\n  typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=32\n  # Hide lua version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global)\n  # If set to false, hide lua version if it's the same as global:\n  # $(luaenv version-name) == $(luaenv global).\n  typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide lua version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################\n  # Java color.\n  typeset -g POWERLEVEL9K_JENV_FOREGROUND=32\n  # Hide java version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global)\n  # If set to false, hide java version if it's the same as global:\n  # $(jenv version-name) == $(jenv global).\n  typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide java version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############\n  # Perl color.\n  typeset -g POWERLEVEL9K_PLENV_FOREGROUND=67\n  # Hide perl version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global)\n  # If set to false, hide perl version if it's the same as global:\n  # $(plenv version-name) == $(plenv global).\n  typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide perl version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ perlbrew: perl version from perlbrew (https://github.com/gugod/App-perlbrew) ]############\n  # Perlbrew color.\n  typeset -g POWERLEVEL9K_PERLBREW_FOREGROUND=67\n  # Show perlbrew version only when in a perl project subdirectory.\n  typeset -g POWERLEVEL9K_PERLBREW_PROJECT_ONLY=true\n  # Don't show \"perl-\" at the front.\n  typeset -g POWERLEVEL9K_PERLBREW_SHOW_PREFIX=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PERLBREW_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############\n  # PHP color.\n  typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=99\n  # Hide php version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global)\n  # If set to false, hide php version if it's the same as global:\n  # $(phpenv version-name) == $(phpenv global).\n  typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide php version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]#######\n  # Scala color.\n  typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=160\n  # Hide scala version if it doesn't come from one of these sources.\n  typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global)\n  # If set to false, hide scala version if it's the same as global:\n  # $(scalaenv version-name) == $(scalaenv global).\n  typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false\n  # If set to false, hide scala version if it's equal to \"system\".\n  typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]###########\n  # Haskell color.\n  typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=172\n  # Hide haskell version if it doesn't come from one of these sources.\n  #\n  #   shell:  version is set by STACK_YAML\n  #   local:  version is set by stack.yaml up the directory tree\n  #   global: version is set by the implicit global project (~/.stack/global-project/stack.yaml)\n  typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local)\n  # If set to false, hide haskell version if it's the same as in the implicit global project.\n  typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]#############\n  # Show kubecontext only when the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show kubecontext.\n  typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|flux|fluxctl|stern|kubeseal|skaffold'\n\n  # Kubernetes context classes for the purpose of using different colors, icons and expansions with\n  # different contexts.\n  #\n  # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current kubernetes context gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       DEFAULT)\n  #\n  # If your current kubernetes context is \"deathray-testing/default\", its class is TEST\n  # because \"deathray-testing/default\" doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'       DEFAULT)\n  typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=134\n  # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext\n  # segment. Parameter expansions are very flexible and fast, too. See reference:\n  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion.\n  #\n  # Within the expansion the following parameters are always available:\n  #\n  # - P9K_CONTENT                The content that would've been displayed if there was no content\n  #                              expansion defined.\n  # - P9K_KUBECONTEXT_NAME       The current context's name. Corresponds to column NAME in the\n  #                              output of `kubectl config get-contexts`.\n  # - P9K_KUBECONTEXT_CLUSTER    The current context's cluster. Corresponds to column CLUSTER in the\n  #                              output of `kubectl config get-contexts`.\n  # - P9K_KUBECONTEXT_NAMESPACE  The current context's namespace. Corresponds to column NAMESPACE\n  #                              in the output of `kubectl config get-contexts`. If there is no\n  #                              namespace, the parameter is set to \"default\".\n  # - P9K_KUBECONTEXT_USER       The current context's user. Corresponds to column AUTHINFO in the\n  #                              output of `kubectl config get-contexts`.\n  #\n  # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS),\n  # the following extra parameters are available:\n  #\n  # - P9K_KUBECONTEXT_CLOUD_NAME     Either \"gke\" or \"eks\".\n  # - P9K_KUBECONTEXT_CLOUD_ACCOUNT  Account/project ID.\n  # - P9K_KUBECONTEXT_CLOUD_ZONE     Availability zone.\n  # - P9K_KUBECONTEXT_CLOUD_CLUSTER  Cluster.\n  #\n  # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example,\n  # if P9K_KUBECONTEXT_CLUSTER is \"gke_my-account_us-east1-a_my-cluster-01\":\n  #\n  #   - P9K_KUBECONTEXT_CLOUD_NAME=gke\n  #   - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account\n  #   - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a\n  #   - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01\n  #\n  # If P9K_KUBECONTEXT_CLUSTER is \"arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01\":\n  #\n  #   - P9K_KUBECONTEXT_CLOUD_NAME=eks\n  #   - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012\n  #   - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1\n  #   - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01\n  typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION=\n  # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME.\n  POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}'\n  # Append the current context's namespace if it's not \"default\".\n  POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}'\n\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%fat '\n\n  ################[ terraform: terraform workspace (https://www.terraform.io) ]#################\n  # Don't show terraform workspace if it's literally \"default\".\n  typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false\n  # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current terraform workspace gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       OTHER)\n  #\n  # If your current terraform workspace is \"project_test\", its class is TEST because \"project_test\"\n  # doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'         OTHER)\n  typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=38\n  # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #############[ terraform_version: terraform version (https://www.terraform.io) ]##############\n  # Terraform version color.\n  typeset -g POWERLEVEL9K_TERRAFORM_VERSION_FOREGROUND=38\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TERRAFORM_VERSION_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]#\n  # Show aws only when the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show aws.\n  typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt'\n\n  # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element\n  # in each pair defines a pattern against which the current AWS profile gets matched.\n  # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below)\n  # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters,\n  # you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The\n  # first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_AWS_CLASSES=(\n  #     '*prod*'  PROD\n  #     '*test*'  TEST\n  #     '*'       DEFAULT)\n  #\n  # If your current AWS profile is \"company_test\", its class is TEST\n  # because \"company_test\" doesn't match the pattern '*prod*' but does match '*test*'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <'\n  typeset -g POWERLEVEL9K_AWS_CLASSES=(\n      # '*prod*'  PROD    # These values are examples that are unlikely\n      # '*test*'  TEST    # to match your needs. Customize them as needed.\n      '*'       DEFAULT)\n  typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=208\n  # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # AWS segment format. The following parameters are available within the expansion.\n  #\n  # - P9K_AWS_PROFILE  The name of the current AWS profile.\n  # - P9K_AWS_REGION   The region associated with the current AWS profile.\n  typeset -g POWERLEVEL9K_AWS_CONTENT_EXPANSION='${P9K_AWS_PROFILE//\\%/%%}${P9K_AWS_REGION:+ ${P9K_AWS_REGION//\\%/%%}}'\n\n  #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]#\n  # AWS Elastic Beanstalk environment color.\n  typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=70\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]##########\n  # Show azure only when the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show azure.\n  typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt'\n  # Azure account name color.\n  typeset -g POWERLEVEL9K_AZURE_FOREGROUND=32\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_AZURE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]###########\n  # Show gcloud only when the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show gcloud.\n  typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs|gsutil'\n   # Google cloud color.\n  typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=32\n\n  # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or\n  # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative\n  # enough. You can use the following parameters in the expansions. Each of them corresponds to the\n  # output of `gcloud` tool.\n  #\n  #   Parameter                | Source\n  #   -------------------------|--------------------------------------------------------------------\n  #   P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)'\n  #   P9K_GCLOUD_ACCOUNT       | gcloud config get-value account\n  #   P9K_GCLOUD_PROJECT_ID    | gcloud config get-value project\n  #   P9K_GCLOUD_PROJECT_NAME  | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)'\n  #\n  # Note: ${VARIABLE//\\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'.\n  #\n  # Obtaining project name requires sending a request to Google servers. This can take a long time\n  # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud\n  # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets\n  # set and gcloud prompt segment transitions to state COMPLETE.\n  #\n  # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL\n  # and COMPLETE. You can also hide gcloud in state PARTIAL by setting\n  # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and\n  # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty.\n  typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\\%/%%}'\n  typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\\%/%%}'\n\n  # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name\n  # this often. Negative value disables periodic polling. In this mode project name is retrieved\n  # only when the current configuration, account or project id changes.\n  typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60\n\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]#\n  # Show google_app_cred only when the command you are typing invokes one of these tools.\n  # Tip: Remove the next line to always show google_app_cred.\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt'\n\n  # Google application credentials classes for the purpose of using different colors, icons and\n  # expansions with different credentials.\n  #\n  # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first\n  # element in each pair defines a pattern against which the current kubernetes context gets\n  # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion\n  # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION\n  # parameters, you'll see this value in your prompt. The second element of each pair in\n  # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order.\n  # The first match wins.\n  #\n  # For example, given these settings:\n  #\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=(\n  #     '*:*prod*:*'  PROD\n  #     '*:*test*:*'  TEST\n  #     '*'           DEFAULT)\n  #\n  # If your current Google application credentials is \"service_account deathray-testing x@y.com\",\n  # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'.\n  #\n  # You can define different colors, icons and content expansions for different classes:\n  #\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  #   typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID'\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=(\n      # '*:*prod*:*'  PROD    # These values are examples that are unlikely\n      # '*:*test*:*'  TEST    # to match your needs. Customize them as needed.\n      '*'             DEFAULT)\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=32\n  # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by\n  # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference:\n  # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion.\n  #\n  # You can use the following parameters in the expansion. Each of them corresponds to one of the\n  # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS.\n  #\n  #   Parameter                        | JSON key file field\n  #   ---------------------------------+---------------\n  #   P9K_GOOGLE_APP_CRED_TYPE         | type\n  #   P9K_GOOGLE_APP_CRED_PROJECT_ID   | project_id\n  #   P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email\n  #\n  # Note: ${VARIABLE//\\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'.\n  typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\\%/%%}'\n\n  ##############[ toolbox: toolbox name (https://github.com/containers/toolbox) ]###############\n  # Toolbox color.\n  typeset -g POWERLEVEL9K_TOOLBOX_FOREGROUND=178\n  # Don't display the name of the toolbox if it matches fedora-toolbox-*.\n  typeset -g POWERLEVEL9K_TOOLBOX_CONTENT_EXPANSION='${P9K_TOOLBOX_NAME:#fedora-toolbox-*}'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_TOOLBOX_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_TOOLBOX_PREFIX='%fin '\n\n  ###############################[ public_ip: public IP address ]###############################\n  # Public IP color.\n  typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=94\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ########################[ vpn_ip: virtual private network indicator ]#########################\n  # VPN IP color.\n  typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=81\n  # When on VPN, show just an icon without the IP address.\n  # Tip: To display the private IP address when on VPN, remove the next line.\n  typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION=\n  # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN\n  # to see the name of the interface.\n  typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*'\n  # If set to true, show one segment per matching network interface. If set to false, show only\n  # one segment corresponding to the first matching network interface.\n  # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION.\n  typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ###########[ ip: ip address and bandwidth usage for a specified network interface ]###########\n  # IP color.\n  typeset -g POWERLEVEL9K_IP_FOREGROUND=38\n  # The following parameters are accessible within the expansion:\n  #\n  #   Parameter             | Meaning\n  #   ----------------------+-------------------------------------------\n  #   P9K_IP_IP             | IP address\n  #   P9K_IP_INTERFACE      | network interface\n  #   P9K_IP_RX_BYTES       | total number of bytes received\n  #   P9K_IP_TX_BYTES       | total number of bytes sent\n  #   P9K_IP_RX_BYTES_DELTA | number of bytes received since last prompt\n  #   P9K_IP_TX_BYTES_DELTA | number of bytes sent since last prompt\n  #   P9K_IP_RX_RATE        | receive rate (since last prompt)\n  #   P9K_IP_TX_RATE        | send rate (since last prompt)\n  typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='$P9K_IP_IP${P9K_IP_RX_RATE:+ %70F\u21e3$P9K_IP_RX_RATE}${P9K_IP_TX_RATE:+ %215F\u21e1$P9K_IP_TX_RATE}'\n  # Show information for the first network interface whose name matches this regular expression.\n  # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces.\n  typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*'\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  #########################[ proxy: system-wide http/https/ftp proxy ]##########################\n  # Proxy color.\n  typeset -g POWERLEVEL9K_PROXY_FOREGROUND=68\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  ################################[ battery: internal battery ]#################################\n  # Show battery in red when it's below this level and not connected to power supply.\n  typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20\n  typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=160\n  # Show battery in green when it's charging or fully charged.\n  typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=70\n  # Show battery in yellow when it's discharging.\n  typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=178\n  # Battery pictograms going from low to high level of charge.\n  typeset -g POWERLEVEL9K_BATTERY_STAGES='\\uf58d\\uf579\\uf57a\\uf57b\\uf57c\\uf57d\\uf57e\\uf57f\\uf580\\uf581\\uf578'\n  # Don't show the remaining time to charge/discharge.\n  typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false\n\n  #####################################[ wifi: wifi speed ]#####################################\n  # WiFi color.\n  typeset -g POWERLEVEL9K_WIFI_FOREGROUND=68\n  # Custom icon.\n  # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS).\n  #\n  #   # Wifi colors and icons for different signal strength levels (low to high).\n  #   typeset -g my_wifi_fg=(68 68 68 68 68)                           # <-- change these values\n  #   typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi')     # <-- change these values\n  #\n  #   typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps'\n  #   typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}'\n  #\n  # The following parameters are accessible within the expansions:\n  #\n  #   Parameter             | Meaning\n  #   ----------------------+---------------\n  #   P9K_WIFI_SSID         | service set identifier, a.k.a. network name\n  #   P9K_WIFI_LINK_AUTH    | authentication protocol such as \"wpa2-psk\" or \"none\"; empty if unknown\n  #   P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second\n  #   P9K_WIFI_RSSI         | signal strength in dBm, from -120 to 0\n  #   P9K_WIFI_NOISE        | noise in dBm, from -120 to 0\n  #   P9K_WIFI_BARS         | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE)\n\n  ####################################[ time: current time ]####################################\n  # Current time color.\n  typeset -g POWERLEVEL9K_TIME_FOREGROUND=66\n  # Format for the current time: 09:51:02. See `man 3 strftime`.\n  typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%I:%M:%S %p}'\n  # If set to true, time will update when you hit enter. This way prompts for the past\n  # commands will contain the start times of their commands as opposed to the default\n  # behavior where they contain the end times of their preceding commands.\n  typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false\n  # Custom icon.\n  typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION=\n  # Custom prefix.\n  # typeset -g POWERLEVEL9K_TIME_PREFIX='%fat '\n\n  # Example of a user-defined prompt segment. Function prompt_example will be called on every\n  # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or\n  # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and orange text greeting the user.\n  #\n  # Type `p10k help segment` for documentation and a more sophisticated example.\n  function prompt_example() {\n    p10k segment -f 208 -i '\u2b50' -t 'hello, %n'\n  }\n\n  # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job\n  # is to generate the prompt segment for display in instant prompt. See\n  # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt.\n  #\n  # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function\n  # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k\n  # will replay these calls without actually calling instant_prompt_*. It is imperative that\n  # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this\n  # rule is not observed, the content of instant prompt will be incorrect.\n  #\n  # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If\n  # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt.\n  function instant_prompt_example() {\n    # Since prompt_example always makes the same `p10k segment` calls, we can call it from\n    # instant_prompt_example. This will give us the same `example` prompt segment in the instant\n    # and regular prompts.\n    prompt_example\n  }\n\n  # User-defined prompt segments can be customized the same way as built-in segments.\n  # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208\n  # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='\u2b50'\n\n  # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt\n  # when accepting a command line. Supported values:\n  #\n  #   - off:      Don't change prompt when accepting a command line.\n  #   - always:   Trim down prompt when accepting a command line.\n  #   - same-dir: Trim down prompt when accepting a command line unless this is the first command\n  #               typed after changing current working directory.\n  typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=off\n\n  # Instant prompt mode.\n  #\n  #   - off:     Disable instant prompt. Choose this if you've tried instant prompt and found\n  #              it incompatible with your zsh configuration files.\n  #   - quiet:   Enable instant prompt and don't print warnings when detecting console output\n  #              during zsh initialization. Choose this if you've read and understood\n  #              https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt.\n  #   - verbose: Enable instant prompt and print a warning when detecting console output during\n  #              zsh initialization. Choose this if you've never tried instant prompt, haven't\n  #              seen the warning, or if you are unsure what this all means.\n  typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose\n\n  # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized.\n  # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload\n  # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you\n  # really need it.\n  typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true\n\n  # If p10k is already loaded, reload configuration.\n  # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true.\n  (( ! $+functions[p10k] )) || p10k reload\n}\n\n# Tell `p10k configure` which file it should overwrite.\ntypeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a}\n\n(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]}\n'builtin' 'unset' 'p10k_config_opts'\n", "meta": {"author": "mraarone", "repo": "dotfiles", "sha": "c41059ccf79e1760d999b62cc5dd35863f186db1", "save_path": "github-repos/lean/mraarone-dotfiles", "path": "github-repos/lean/mraarone-dotfiles/dotfiles-c41059ccf79e1760d999b62cc5dd35863f186db1/powerlevel10k/.p10k.zsh.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.010652509583375378, "lm_q2_score": 0.009412589978373853, "lm_q1q2_score": 0.00010026770494901052}}
